blob: f686735010dde38da0a4e6f9b3d0279282eb4082 [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.
Anton Yartsev849c7bf2013-03-28 17:05:19 +000053 Relinquished };
54
Zhongxing Xu243fde92009-11-17 07:54:15 +000055 const Stmt *S;
Anton Yartsev849c7bf2013-03-28 17:05:19 +000056 unsigned K : 2; // Kind enum, but stored as a bitfield.
57 unsigned Family : 30; // Rest of 32-bit word, currently just an allocation
58 // family.
Zhongxing Xu243fde92009-11-17 07:54:15 +000059
Anton Yartsev849c7bf2013-03-28 17:05:19 +000060 RefState(Kind k, const Stmt *s, unsigned family)
Eric Christopher03852c82013-03-28 18:22:58 +000061 : S(s), K(k), Family(family) {}
Zhongxing Xu7fb14642009-12-11 00:55:44 +000062public:
Anna Zaks050cdd72012-06-20 20:57:46 +000063 bool isAllocated() const { return K == Allocated; }
Zhongxing Xu243fde92009-11-17 07:54:15 +000064 bool isReleased() const { return K == Released; }
Anna Zaks050cdd72012-06-20 20:57:46 +000065 bool isRelinquished() const { return K == Relinquished; }
Anton Yartsev849c7bf2013-03-28 17:05:19 +000066 AllocationFamily getAllocationFamily() const {
67 return (AllocationFamily)Family;
68 }
Anna Zaksc8bb3be2012-02-13 18:05:39 +000069 const Stmt *getStmt() const { return S; }
Zhongxing Xu243fde92009-11-17 07:54:15 +000070
71 bool operator==(const RefState &X) const {
Anton Yartsev849c7bf2013-03-28 17:05:19 +000072 return K == X.K && S == X.S && Family == X.Family;
Zhongxing Xu243fde92009-11-17 07:54:15 +000073 }
74
Anton Yartsev849c7bf2013-03-28 17:05:19 +000075 static RefState getAllocated(unsigned family, const Stmt *s) {
76 return RefState(Allocated, s, family);
Zhongxing Xub94b81a2009-12-31 06:13:07 +000077 }
Anton Yartsev849c7bf2013-03-28 17:05:19 +000078 static RefState getReleased(unsigned family, const Stmt *s) {
79 return RefState(Released, s, family);
80 }
81 static RefState getRelinquished(unsigned family, const Stmt *s) {
82 return RefState(Relinquished, s, family);
Ted Kremenekdde201b2010-08-06 21:12:55 +000083 }
Zhongxing Xu243fde92009-11-17 07:54:15 +000084
85 void Profile(llvm::FoldingSetNodeID &ID) const {
86 ID.AddInteger(K);
87 ID.AddPointer(S);
Anton Yartsev849c7bf2013-03-28 17:05:19 +000088 ID.AddInteger(Family);
Zhongxing Xu243fde92009-11-17 07:54:15 +000089 }
Ted Kremenekc37fad62013-01-03 01:30:12 +000090
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000091 void dump(raw_ostream &OS) const {
Ted Kremenekc37fad62013-01-03 01:30:12 +000092 static const char *Table[] = {
93 "Allocated",
94 "Released",
95 "Relinquished"
96 };
97 OS << Table[(unsigned) K];
98 }
99
100 LLVM_ATTRIBUTE_USED void dump() const {
101 dump(llvm::errs());
102 }
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000103};
104
Anna Zaks9dc298b2012-09-12 22:57:34 +0000105enum ReallocPairKind {
106 RPToBeFreedAfterFailure,
107 // The symbol has been freed when reallocation failed.
108 RPIsFreeOnFailure,
109 // The symbol does not need to be freed after reallocation fails.
110 RPDoNotTrackAfterFailure
111};
112
Anna Zaks55dd9562012-08-24 02:28:20 +0000113/// \class ReallocPair
114/// \brief Stores information about the symbol being reallocated by a call to
115/// 'realloc' to allow modeling failed reallocation later in the path.
Anna Zaks40add292012-02-15 00:11:25 +0000116struct ReallocPair {
Anna Zaks55dd9562012-08-24 02:28:20 +0000117 // \brief The symbol which realloc reallocated.
Anna Zaks40add292012-02-15 00:11:25 +0000118 SymbolRef ReallocatedSym;
Anna Zaks9dc298b2012-09-12 22:57:34 +0000119 ReallocPairKind Kind;
Anna Zaks55dd9562012-08-24 02:28:20 +0000120
Anna Zaks9dc298b2012-09-12 22:57:34 +0000121 ReallocPair(SymbolRef S, ReallocPairKind K) :
122 ReallocatedSym(S), Kind(K) {}
Anna Zaks40add292012-02-15 00:11:25 +0000123 void Profile(llvm::FoldingSetNodeID &ID) const {
Anna Zaks9dc298b2012-09-12 22:57:34 +0000124 ID.AddInteger(Kind);
Anna Zaks40add292012-02-15 00:11:25 +0000125 ID.AddPointer(ReallocatedSym);
126 }
127 bool operator==(const ReallocPair &X) const {
128 return ReallocatedSym == X.ReallocatedSym &&
Anna Zaks9dc298b2012-09-12 22:57:34 +0000129 Kind == X.Kind;
Anna Zaks40add292012-02-15 00:11:25 +0000130 }
131};
132
Anna Zaks97bfb552013-01-08 00:25:29 +0000133typedef std::pair<const ExplodedNode*, const MemRegion*> LeakInfo;
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000134
Anna Zaksb319e022012-02-08 20:13:28 +0000135class MallocChecker : public Checker<check::DeadSymbols,
Anna Zaksbf53dfa2012-12-20 00:38:25 +0000136 check::PointerEscape,
Anna Zaks41988f32013-03-28 23:15:29 +0000137 check::ConstPointerEscape,
Ted Kremeneke3659a72012-01-04 23:48:37 +0000138 check::PreStmt<ReturnStmt>,
Anna Zaks66c40402012-02-14 21:55:24 +0000139 check::PreStmt<CallExpr>,
Anna Zaksb319e022012-02-08 20:13:28 +0000140 check::PostStmt<CallExpr>,
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000141 check::PostStmt<CXXNewExpr>,
142 check::PreStmt<CXXDeleteExpr>,
Anna Zaksf5aa3f52012-03-22 00:57:20 +0000143 check::PostStmt<BlockExpr>,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000144 check::PostObjCMessage,
Ted Kremeneke3659a72012-01-04 23:48:37 +0000145 check::Location,
Anna Zaksbf53dfa2012-12-20 00:38:25 +0000146 eval::Assume>
Ted Kremeneke3659a72012-01-04 23:48:37 +0000147{
Anna Zaksfebdc322012-02-16 22:26:12 +0000148 mutable OwningPtr<BugType> BT_DoubleFree;
149 mutable OwningPtr<BugType> BT_Leak;
150 mutable OwningPtr<BugType> BT_UseFree;
151 mutable OwningPtr<BugType> BT_BadFree;
Anton Yartsev648cb712013-04-04 23:46:29 +0000152 mutable OwningPtr<BugType> BT_MismatchedDealloc;
Anna Zaks118aa752013-02-07 23:05:47 +0000153 mutable OwningPtr<BugType> BT_OffsetFree;
Anna Zaksb16ce452012-02-15 00:11:22 +0000154 mutable IdentifierInfo *II_malloc, *II_free, *II_realloc, *II_calloc,
Anna Zaks60a1fa42012-02-22 03:14:20 +0000155 *II_valloc, *II_reallocf, *II_strndup, *II_strdup;
156
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000157public:
Anna Zaksb16ce452012-02-15 00:11:22 +0000158 MallocChecker() : II_malloc(0), II_free(0), II_realloc(0), II_calloc(0),
Anna Zaks60a1fa42012-02-22 03:14:20 +0000159 II_valloc(0), II_reallocf(0), II_strndup(0), II_strdup(0) {}
Anna Zaks231361a2012-02-08 23:16:52 +0000160
161 /// In pessimistic mode, the checker assumes that it does not know which
162 /// functions might free the memory.
163 struct ChecksFilter {
164 DefaultBool CMallocPessimistic;
165 DefaultBool CMallocOptimistic;
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000166 DefaultBool CNewDeleteChecker;
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000167 DefaultBool CMismatchedDeallocatorChecker;
Anna Zaks231361a2012-02-08 23:16:52 +0000168 };
169
170 ChecksFilter Filter;
171
Anna Zaks66c40402012-02-14 21:55:24 +0000172 void checkPreStmt(const CallExpr *S, CheckerContext &C) const;
Anna Zaksb319e022012-02-08 20:13:28 +0000173 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000174 void checkPostStmt(const CXXNewExpr *NE, CheckerContext &C) const;
175 void checkPreStmt(const CXXDeleteExpr *DE, CheckerContext &C) const;
Anna Zaks4141e4d2012-11-13 03:18:01 +0000176 void checkPostObjCMessage(const ObjCMethodCall &Call, CheckerContext &C) const;
Anna Zaksf5aa3f52012-03-22 00:57:20 +0000177 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000178 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000179 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000180 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000181 bool Assumption) const;
Anna Zaks390909c2011-10-06 00:43:15 +0000182 void checkLocation(SVal l, bool isLoad, const Stmt *S,
183 CheckerContext &C) const;
Anna Zaksbf53dfa2012-12-20 00:38:25 +0000184
185 ProgramStateRef checkPointerEscape(ProgramStateRef State,
186 const InvalidatedSymbols &Escaped,
Anna Zaks233e26a2013-02-07 23:05:43 +0000187 const CallEvent *Call,
188 PointerEscapeKind Kind) const;
Anna Zaks41988f32013-03-28 23:15:29 +0000189 ProgramStateRef checkConstPointerEscape(ProgramStateRef State,
190 const InvalidatedSymbols &Escaped,
191 const CallEvent *Call,
192 PointerEscapeKind Kind) const;
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000193
Anna Zaks93c5a242012-05-02 00:05:20 +0000194 void printState(raw_ostream &Out, ProgramStateRef State,
195 const char *NL, const char *Sep) const;
196
Zhongxing Xu7b760962009-11-13 07:25:27 +0000197private:
Anna Zaks66c40402012-02-14 21:55:24 +0000198 void initIdentifierInfo(ASTContext &C) const;
199
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000200 /// \brief Determine family of a deallocation expression.
Anton Yartsev648cb712013-04-04 23:46:29 +0000201 AllocationFamily getAllocationFamily(CheckerContext &C, const Stmt *S) const;
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000202
203 /// \brief Print names of allocators and deallocators.
204 ///
205 /// \returns true on success.
206 bool printAllocDeallocName(raw_ostream &os, CheckerContext &C,
207 const Expr *E) const;
208
209 /// \brief Print expected name of an allocator based on the deallocator's
210 /// family derived from the DeallocExpr.
211 void printExpectedAllocName(raw_ostream &os, CheckerContext &C,
212 const Expr *DeallocExpr) const;
213 /// \brief Print expected name of a deallocator based on the allocator's
214 /// family.
215 void printExpectedDeallocName(raw_ostream &os, AllocationFamily Family) const;
216
Jordan Rose9fe09f32013-03-09 00:59:10 +0000217 ///@{
Anna Zaks66c40402012-02-14 21:55:24 +0000218 /// Check if this is one of the functions which can allocate/reallocate memory
219 /// pointed to by one of its arguments.
220 bool isMemFunction(const FunctionDecl *FD, ASTContext &C) const;
Anna Zaks14345182012-05-18 01:16:10 +0000221 bool isFreeFunction(const FunctionDecl *FD, ASTContext &C) const;
222 bool isAllocationFunction(const FunctionDecl *FD, ASTContext &C) const;
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000223 bool isStandardNewDelete(const FunctionDecl *FD, ASTContext &C) const;
Jordan Rose9fe09f32013-03-09 00:59:10 +0000224 ///@}
Anna Zaks87cb5be2012-02-22 19:24:52 +0000225 static ProgramStateRef MallocMemReturnsAttr(CheckerContext &C,
226 const CallExpr *CE,
227 const OwnershipAttr* Att);
Ted Kremenek8bef8232012-01-26 21:29:00 +0000228 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000229 const Expr *SizeEx, SVal Init,
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000230 ProgramStateRef State,
231 AllocationFamily Family = AF_Malloc) {
Ted Kremenek5eca4822012-01-06 22:09:28 +0000232 return MallocMemAux(C, CE,
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000233 State->getSVal(SizeEx, C.getLocationContext()),
234 Init, State, Family);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000235 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000236
Ted Kremenek8bef8232012-01-26 21:29:00 +0000237 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000238 SVal SizeEx, SVal Init,
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000239 ProgramStateRef State,
240 AllocationFamily Family = AF_Malloc);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000241
Anna Zaks87cb5be2012-02-22 19:24:52 +0000242 /// Update the RefState to reflect the new memory allocation.
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000243 static ProgramStateRef
244 MallocUpdateRefState(CheckerContext &C, const Expr *E, ProgramStateRef State,
245 AllocationFamily Family = AF_Malloc);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000246
247 ProgramStateRef FreeMemAttr(CheckerContext &C, const CallExpr *CE,
248 const OwnershipAttr* Att) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000249 ProgramStateRef FreeMemAux(CheckerContext &C, const CallExpr *CE,
Anna Zaks5b7aa342012-06-22 02:04:31 +0000250 ProgramStateRef state, unsigned Num,
Anna Zaks55dd9562012-08-24 02:28:20 +0000251 bool Hold,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000252 bool &ReleasedAllocated,
253 bool ReturnsNullOnFailure = false) const;
Anna Zaks5b7aa342012-06-22 02:04:31 +0000254 ProgramStateRef FreeMemAux(CheckerContext &C, const Expr *Arg,
255 const Expr *ParentExpr,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000256 ProgramStateRef State,
Anna Zaks55dd9562012-08-24 02:28:20 +0000257 bool Hold,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000258 bool &ReleasedAllocated,
259 bool ReturnsNullOnFailure = false) const;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000260
Anna Zaks87cb5be2012-02-22 19:24:52 +0000261 ProgramStateRef ReallocMem(CheckerContext &C, const CallExpr *CE,
262 bool FreesMemOnFailure) const;
263 static ProgramStateRef CallocMem(CheckerContext &C, const CallExpr *CE);
Jordy Rose43859f62010-06-07 19:32:37 +0000264
Anna Zaks14345182012-05-18 01:16:10 +0000265 ///\brief Check if the memory associated with this symbol was released.
266 bool isReleased(SymbolRef Sym, CheckerContext &C) const;
267
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000268 bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C, const Stmt *S) const;
Anna Zaks91c2a112012-02-08 23:16:56 +0000269
Jordan Rose9fe09f32013-03-09 00:59:10 +0000270 /// Check if the function is known not to free memory, or if it is
271 /// "interesting" and should be modeled explicitly.
272 ///
273 /// We assume that pointers do not escape through calls to system functions
274 /// not handled by this checker.
275 bool doesNotFreeMemOrInteresting(const CallEvent *Call,
276 ProgramStateRef State) const;
Anna Zaks66c40402012-02-14 21:55:24 +0000277
Anna Zaks41988f32013-03-28 23:15:29 +0000278 // Implementation of the checkPointerEscape callabcks.
279 ProgramStateRef checkPointerEscapeAux(ProgramStateRef State,
280 const InvalidatedSymbols &Escaped,
281 const CallEvent *Call,
282 PointerEscapeKind Kind,
283 bool(*CheckRefState)(const RefState*)) const;
284
Anton Yartsev648cb712013-04-04 23:46:29 +0000285 // Used to suppress warnings if they are not related to the tracked family
286 // (derived from AllocDeallocStmt).
287 bool isTrackedFamily(AllocationFamily Family) const;
288 bool isTrackedFamily(CheckerContext &C, const Stmt *AllocDeallocStmt) const;
289 bool isTrackedFamily(CheckerContext &C, SymbolRef Sym) const;
290
Ted Kremenek9c378f72011-08-12 23:37:29 +0000291 static bool SummarizeValue(raw_ostream &os, SVal V);
292 static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000293 void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
294 const Expr *DeallocExpr) const;
Anton Yartsev648cb712013-04-04 23:46:29 +0000295 void ReportMismatchedDealloc(CheckerContext &C, SourceRange Range,
296 const Expr *DeallocExpr,
297 const RefState *RS) const;
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000298 void ReportOffsetFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
299 const Expr *DeallocExpr,
300 const Expr *AllocExpr = 0) const;
Anton Yartsevbb369952013-03-13 14:39:10 +0000301 void ReportUseAfterFree(CheckerContext &C, SourceRange Range,
302 SymbolRef Sym) const;
303 void ReportDoubleFree(CheckerContext &C, SourceRange Range, bool Released,
Anton Yartsev3258d4b2013-03-13 17:07:32 +0000304 SymbolRef Sym, SymbolRef PrevSym) const;
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000305
Anna Zaksca8e36e2012-02-23 21:38:21 +0000306 /// Find the location of the allocation for Sym on the path leading to the
307 /// exploded node N.
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000308 LeakInfo getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
309 CheckerContext &C) const;
Anna Zaksca8e36e2012-02-23 21:38:21 +0000310
Anna Zaksda046772012-02-11 21:02:40 +0000311 void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
312
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000313 /// The bug visitor which allows us to print extra diagnostics along the
314 /// BugReport path. For example, showing the allocation site of the leaked
315 /// region.
Jordy Rose01153492012-03-24 02:45:35 +0000316 class MallocBugVisitor : public BugReporterVisitorImpl<MallocBugVisitor> {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000317 protected:
Anna Zaksfe571602012-02-16 22:26:07 +0000318 enum NotificationMode {
319 Normal,
Anna Zaksfe571602012-02-16 22:26:07 +0000320 ReallocationFailed
321 };
322
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000323 // The allocated region symbol tracked by the main analysis.
324 SymbolRef Sym;
325
Anna Zaks88feba02012-05-10 01:37:40 +0000326 // The mode we are in, i.e. what kind of diagnostics will be emitted.
327 NotificationMode Mode;
Jordy Roseb000fb52012-03-24 03:15:09 +0000328
Anna Zaks88feba02012-05-10 01:37:40 +0000329 // A symbol from when the primary region should have been reallocated.
330 SymbolRef FailedReallocSymbol;
Jordy Roseb000fb52012-03-24 03:15:09 +0000331
Anna Zaks88feba02012-05-10 01:37:40 +0000332 bool IsLeak;
333
334 public:
335 MallocBugVisitor(SymbolRef S, bool isLeak = false)
336 : Sym(S), Mode(Normal), FailedReallocSymbol(0), IsLeak(isLeak) {}
Jordy Roseb000fb52012-03-24 03:15:09 +0000337
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000338 virtual ~MallocBugVisitor() {}
339
340 void Profile(llvm::FoldingSetNodeID &ID) const {
341 static int X = 0;
342 ID.AddPointer(&X);
343 ID.AddPointer(Sym);
344 }
345
Anna Zaksfe571602012-02-16 22:26:07 +0000346 inline bool isAllocated(const RefState *S, const RefState *SPrev,
347 const Stmt *Stmt) {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000348 // Did not track -> allocated. Other state (released) -> allocated.
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000349 return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXNewExpr>(Stmt)) &&
Anna Zaksfe571602012-02-16 22:26:07 +0000350 (S && S->isAllocated()) && (!SPrev || !SPrev->isAllocated()));
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000351 }
352
Anna Zaksfe571602012-02-16 22:26:07 +0000353 inline bool isReleased(const RefState *S, const RefState *SPrev,
354 const Stmt *Stmt) {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000355 // Did not track -> released. Other state (allocated) -> released.
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000356 return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXDeleteExpr>(Stmt)) &&
Anna Zaksfe571602012-02-16 22:26:07 +0000357 (S && S->isReleased()) && (!SPrev || !SPrev->isReleased()));
358 }
359
Anna Zaks5b7aa342012-06-22 02:04:31 +0000360 inline bool isRelinquished(const RefState *S, const RefState *SPrev,
361 const Stmt *Stmt) {
362 // Did not track -> relinquished. Other state (allocated) -> relinquished.
363 return (Stmt && (isa<CallExpr>(Stmt) || isa<ObjCMessageExpr>(Stmt) ||
364 isa<ObjCPropertyRefExpr>(Stmt)) &&
365 (S && S->isRelinquished()) &&
366 (!SPrev || !SPrev->isRelinquished()));
367 }
368
Anna Zaksfe571602012-02-16 22:26:07 +0000369 inline bool isReallocFailedCheck(const RefState *S, const RefState *SPrev,
370 const Stmt *Stmt) {
371 // If the expression is not a call, and the state change is
372 // released -> allocated, it must be the realloc return value
373 // check. If we have to handle more cases here, it might be cleaner just
374 // to track this extra bit in the state itself.
375 return ((!Stmt || !isa<CallExpr>(Stmt)) &&
376 (S && S->isAllocated()) && (SPrev && !SPrev->isAllocated()));
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000377 }
378
379 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
380 const ExplodedNode *PrevN,
381 BugReporterContext &BRC,
382 BugReport &BR);
Anna Zaks88feba02012-05-10 01:37:40 +0000383
384 PathDiagnosticPiece* getEndPath(BugReporterContext &BRC,
385 const ExplodedNode *EndPathNode,
386 BugReport &BR) {
387 if (!IsLeak)
388 return 0;
389
390 PathDiagnosticLocation L =
391 PathDiagnosticLocation::createEndOfPath(EndPathNode,
392 BRC.getSourceManager());
393 // Do not add the statement itself as a range in case of leak.
394 return new PathDiagnosticEventPiece(L, BR.getDescription(), false);
395 }
396
Anna Zaks56a938f2012-03-16 23:24:20 +0000397 private:
398 class StackHintGeneratorForReallocationFailed
399 : public StackHintGeneratorForSymbol {
400 public:
401 StackHintGeneratorForReallocationFailed(SymbolRef S, StringRef M)
402 : StackHintGeneratorForSymbol(S, M) {}
403
404 virtual std::string getMessageForArg(const Expr *ArgE, unsigned ArgIndex) {
Jordan Rose615a0922012-09-22 01:24:42 +0000405 // Printed parameters start at 1, not 0.
406 ++ArgIndex;
407
Anna Zaks56a938f2012-03-16 23:24:20 +0000408 SmallString<200> buf;
409 llvm::raw_svector_ostream os(buf);
410
Jordan Rose615a0922012-09-22 01:24:42 +0000411 os << "Reallocation of " << ArgIndex << llvm::getOrdinalSuffix(ArgIndex)
412 << " parameter failed";
Anna Zaks56a938f2012-03-16 23:24:20 +0000413
414 return os.str();
415 }
416
417 virtual std::string getMessageForReturn(const CallExpr *CallExpr) {
Anna Zaksfbd58742012-03-16 23:44:28 +0000418 return "Reallocation of returned value failed";
Anna Zaks56a938f2012-03-16 23:24:20 +0000419 }
420 };
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000421 };
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000422};
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000423} // end anonymous namespace
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000424
Jordan Rose166d5022012-11-02 01:54:06 +0000425REGISTER_MAP_WITH_PROGRAMSTATE(RegionState, SymbolRef, RefState)
426REGISTER_MAP_WITH_PROGRAMSTATE(ReallocPairs, SymbolRef, ReallocPair)
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000427
Anna Zaks4141e4d2012-11-13 03:18:01 +0000428// A map from the freed symbol to the symbol representing the return value of
429// the free function.
430REGISTER_MAP_WITH_PROGRAMSTATE(FreeReturnValue, SymbolRef, SymbolRef)
431
Anna Zaks4fb54872012-02-11 21:02:35 +0000432namespace {
433class StopTrackingCallback : public SymbolVisitor {
434 ProgramStateRef state;
435public:
436 StopTrackingCallback(ProgramStateRef st) : state(st) {}
437 ProgramStateRef getState() const { return state; }
438
439 bool VisitSymbol(SymbolRef sym) {
440 state = state->remove<RegionState>(sym);
441 return true;
442 }
443};
444} // end anonymous namespace
445
Anna Zaks66c40402012-02-14 21:55:24 +0000446void MallocChecker::initIdentifierInfo(ASTContext &Ctx) const {
Anna Zaksa38cb2c2012-05-18 22:47:40 +0000447 if (II_malloc)
448 return;
449 II_malloc = &Ctx.Idents.get("malloc");
450 II_free = &Ctx.Idents.get("free");
451 II_realloc = &Ctx.Idents.get("realloc");
452 II_reallocf = &Ctx.Idents.get("reallocf");
453 II_calloc = &Ctx.Idents.get("calloc");
454 II_valloc = &Ctx.Idents.get("valloc");
455 II_strdup = &Ctx.Idents.get("strdup");
456 II_strndup = &Ctx.Idents.get("strndup");
Anna Zaksb319e022012-02-08 20:13:28 +0000457}
458
Anna Zaks66c40402012-02-14 21:55:24 +0000459bool MallocChecker::isMemFunction(const FunctionDecl *FD, ASTContext &C) const {
Anna Zaks14345182012-05-18 01:16:10 +0000460 if (isFreeFunction(FD, C))
461 return true;
462
463 if (isAllocationFunction(FD, C))
464 return true;
465
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000466 if (isStandardNewDelete(FD, C))
467 return true;
468
Anna Zaks14345182012-05-18 01:16:10 +0000469 return false;
470}
471
472bool MallocChecker::isAllocationFunction(const FunctionDecl *FD,
473 ASTContext &C) const {
Anna Zaks1d6cc6a2012-02-15 02:12:00 +0000474 if (!FD)
475 return false;
Anna Zaks14345182012-05-18 01:16:10 +0000476
Jordan Rose5ef6e942012-07-10 23:13:01 +0000477 if (FD->getKind() == Decl::Function) {
478 IdentifierInfo *FunI = FD->getIdentifier();
479 initIdentifierInfo(C);
Anna Zaks66c40402012-02-14 21:55:24 +0000480
Jordan Rose5ef6e942012-07-10 23:13:01 +0000481 if (FunI == II_malloc || FunI == II_realloc ||
482 FunI == II_reallocf || FunI == II_calloc || FunI == II_valloc ||
483 FunI == II_strdup || FunI == II_strndup)
484 return true;
485 }
Anna Zaks66c40402012-02-14 21:55:24 +0000486
Anna Zaks14345182012-05-18 01:16:10 +0000487 if (Filter.CMallocOptimistic && FD->hasAttrs())
488 for (specific_attr_iterator<OwnershipAttr>
489 i = FD->specific_attr_begin<OwnershipAttr>(),
490 e = FD->specific_attr_end<OwnershipAttr>();
491 i != e; ++i)
492 if ((*i)->getOwnKind() == OwnershipAttr::Returns)
493 return true;
494 return false;
495}
496
497bool MallocChecker::isFreeFunction(const FunctionDecl *FD, ASTContext &C) const {
498 if (!FD)
499 return false;
500
Jordan Rose5ef6e942012-07-10 23:13:01 +0000501 if (FD->getKind() == Decl::Function) {
502 IdentifierInfo *FunI = FD->getIdentifier();
503 initIdentifierInfo(C);
Anna Zaks14345182012-05-18 01:16:10 +0000504
Jordan Rose5ef6e942012-07-10 23:13:01 +0000505 if (FunI == II_free || FunI == II_realloc || FunI == II_reallocf)
506 return true;
507 }
Anna Zaks66c40402012-02-14 21:55:24 +0000508
Anna Zaks14345182012-05-18 01:16:10 +0000509 if (Filter.CMallocOptimistic && FD->hasAttrs())
510 for (specific_attr_iterator<OwnershipAttr>
511 i = FD->specific_attr_begin<OwnershipAttr>(),
512 e = FD->specific_attr_end<OwnershipAttr>();
513 i != e; ++i)
514 if ((*i)->getOwnKind() == OwnershipAttr::Takes ||
515 (*i)->getOwnKind() == OwnershipAttr::Holds)
516 return true;
Anna Zaks66c40402012-02-14 21:55:24 +0000517 return false;
518}
519
Anton Yartsev69746282013-03-28 16:10:38 +0000520// Tells if the callee is one of the following:
521// 1) A global non-placement new/delete operator function.
522// 2) A global placement operator function with the single placement argument
523// of type std::nothrow_t.
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000524bool MallocChecker::isStandardNewDelete(const FunctionDecl *FD,
525 ASTContext &C) const {
526 if (!FD)
527 return false;
528
529 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
530 if (Kind != OO_New && Kind != OO_Array_New &&
531 Kind != OO_Delete && Kind != OO_Array_Delete)
532 return false;
533
Anton Yartsev69746282013-03-28 16:10:38 +0000534 // Skip all operator new/delete methods.
535 if (isa<CXXMethodDecl>(FD))
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000536 return false;
537
538 // Return true if tested operator is a standard placement nothrow operator.
539 if (FD->getNumParams() == 2) {
540 QualType T = FD->getParamDecl(1)->getType();
541 if (const IdentifierInfo *II = T.getBaseTypeIdentifier())
542 return II->getName().equals("nothrow_t");
543 }
544
545 // Skip placement operators.
546 if (FD->getNumParams() != 1 || FD->isVariadic())
547 return false;
548
549 // One of the standard new/new[]/delete/delete[] non-placement operators.
550 return true;
551}
552
Anna Zaksb319e022012-02-08 20:13:28 +0000553void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
Jordan Rosec20c7272012-09-20 01:55:32 +0000554 if (C.wasInlined)
555 return;
556
Anna Zaksb319e022012-02-08 20:13:28 +0000557 const FunctionDecl *FD = C.getCalleeDecl(CE);
558 if (!FD)
559 return;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000560
Anna Zaks87cb5be2012-02-22 19:24:52 +0000561 ProgramStateRef State = C.getState();
Anna Zaks55dd9562012-08-24 02:28:20 +0000562 bool ReleasedAllocatedMemory = false;
Jordan Rose5ef6e942012-07-10 23:13:01 +0000563
564 if (FD->getKind() == Decl::Function) {
565 initIdentifierInfo(C.getASTContext());
566 IdentifierInfo *FunI = FD->getIdentifier();
567
Anton Yartsev648cb712013-04-04 23:46:29 +0000568 if (FunI == II_malloc || FunI == II_valloc) {
569 if (CE->getNumArgs() < 1)
570 return;
571 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
572 } else if (FunI == II_realloc) {
573 State = ReallocMem(C, CE, false);
574 } else if (FunI == II_reallocf) {
575 State = ReallocMem(C, CE, true);
576 } else if (FunI == II_calloc) {
577 State = CallocMem(C, CE);
578 } else if (FunI == II_free) {
579 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
580 } else if (FunI == II_strdup) {
581 State = MallocUpdateRefState(C, CE, State);
582 } else if (FunI == II_strndup) {
583 State = MallocUpdateRefState(C, CE, State);
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000584 }
Anton Yartsev648cb712013-04-04 23:46:29 +0000585 else if (isStandardNewDelete(FD, C.getASTContext())) {
586 // Process direct calls to operator new/new[]/delete/delete[] functions
587 // as distinct from new/new[]/delete/delete[] expressions that are
588 // processed by the checkPostStmt callbacks for CXXNewExpr and
589 // CXXDeleteExpr.
590 OverloadedOperatorKind K = FD->getOverloadedOperator();
591 if (K == OO_New)
592 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
593 AF_CXXNew);
594 else if (K == OO_Array_New)
595 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
596 AF_CXXNewArray);
597 else if (K == OO_Delete || K == OO_Array_Delete)
598 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
599 else
600 llvm_unreachable("not a new/delete operator");
Jordan Rose5ef6e942012-07-10 23:13:01 +0000601 }
602 }
603
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000604 if (Filter.CMallocOptimistic || Filter.CMismatchedDeallocatorChecker) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000605 // Check all the attributes, if there are any.
606 // There can be multiple of these attributes.
607 if (FD->hasAttrs())
608 for (specific_attr_iterator<OwnershipAttr>
609 i = FD->specific_attr_begin<OwnershipAttr>(),
610 e = FD->specific_attr_end<OwnershipAttr>();
611 i != e; ++i) {
612 switch ((*i)->getOwnKind()) {
613 case OwnershipAttr::Returns:
614 State = MallocMemReturnsAttr(C, CE, *i);
615 break;
616 case OwnershipAttr::Takes:
617 case OwnershipAttr::Holds:
618 State = FreeMemAttr(C, CE, *i);
619 break;
620 }
621 }
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000622 }
Anna Zaks60a1fa42012-02-22 03:14:20 +0000623 C.addTransition(State);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000624}
625
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000626void MallocChecker::checkPostStmt(const CXXNewExpr *NE,
627 CheckerContext &C) const {
628
629 if (NE->getNumPlacementArgs())
630 for (CXXNewExpr::const_arg_iterator I = NE->placement_arg_begin(),
631 E = NE->placement_arg_end(); I != E; ++I)
632 if (SymbolRef Sym = C.getSVal(*I).getAsSymbol())
633 checkUseAfterFree(Sym, C, *I);
634
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000635 if (!isStandardNewDelete(NE->getOperatorNew(), C.getASTContext()))
636 return;
637
638 ProgramStateRef State = C.getState();
639 // The return value from operator new is bound to a specified initialization
640 // value (if any) and we don't want to loose this value. So we call
641 // MallocUpdateRefState() instead of MallocMemAux() which breakes the
642 // existing binding.
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000643 State = MallocUpdateRefState(C, NE, State, NE->isArray() ? AF_CXXNewArray
644 : AF_CXXNew);
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000645 C.addTransition(State);
646}
647
648void MallocChecker::checkPreStmt(const CXXDeleteExpr *DE,
649 CheckerContext &C) const {
650
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000651 if (!Filter.CNewDeleteChecker)
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000652 if (SymbolRef Sym = C.getSVal(DE->getArgument()).getAsSymbol())
653 checkUseAfterFree(Sym, C, DE->getArgument());
654
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000655 if (!isStandardNewDelete(DE->getOperatorDelete(), C.getASTContext()))
656 return;
657
658 ProgramStateRef State = C.getState();
659 bool ReleasedAllocated;
660 State = FreeMemAux(C, DE->getArgument(), DE, State,
661 /*Hold*/false, ReleasedAllocated);
662
663 C.addTransition(State);
664}
665
Jordan Rose9fe09f32013-03-09 00:59:10 +0000666static bool isKnownDeallocObjCMethodName(const ObjCMethodCall &Call) {
667 // If the first selector piece is one of the names below, assume that the
668 // object takes ownership of the memory, promising to eventually deallocate it
669 // with free().
670 // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
671 // (...unless a 'freeWhenDone' parameter is false, but that's checked later.)
672 StringRef FirstSlot = Call.getSelector().getNameForSlot(0);
673 if (FirstSlot == "dataWithBytesNoCopy" ||
674 FirstSlot == "initWithBytesNoCopy" ||
675 FirstSlot == "initWithCharactersNoCopy")
676 return true;
Anna Zaks5b7aa342012-06-22 02:04:31 +0000677
678 return false;
679}
680
Jordan Rose9fe09f32013-03-09 00:59:10 +0000681static Optional<bool> getFreeWhenDoneArg(const ObjCMethodCall &Call) {
682 Selector S = Call.getSelector();
683
684 // FIXME: We should not rely on fully-constrained symbols being folded.
685 for (unsigned i = 1; i < S.getNumArgs(); ++i)
686 if (S.getNameForSlot(i).equals("freeWhenDone"))
687 return !Call.getArgSVal(i).isZeroConstant();
688
689 return None;
690}
691
Anna Zaks4141e4d2012-11-13 03:18:01 +0000692void MallocChecker::checkPostObjCMessage(const ObjCMethodCall &Call,
693 CheckerContext &C) const {
Anna Zaksc2cca232012-12-11 00:17:53 +0000694 if (C.wasInlined)
695 return;
696
Jordan Rose9fe09f32013-03-09 00:59:10 +0000697 if (!isKnownDeallocObjCMethodName(Call))
698 return;
Anna Zaks4141e4d2012-11-13 03:18:01 +0000699
Jordan Rose9fe09f32013-03-09 00:59:10 +0000700 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(Call))
701 if (!*FreeWhenDone)
702 return;
703
704 bool ReleasedAllocatedMemory;
705 ProgramStateRef State = FreeMemAux(C, Call.getArgExpr(0),
706 Call.getOriginExpr(), C.getState(),
707 /*Hold=*/true, ReleasedAllocatedMemory,
708 /*RetNullOnFailure=*/true);
709
710 C.addTransition(State);
Anna Zaks5b7aa342012-06-22 02:04:31 +0000711}
712
Anna Zaks87cb5be2012-02-22 19:24:52 +0000713ProgramStateRef MallocChecker::MallocMemReturnsAttr(CheckerContext &C,
714 const CallExpr *CE,
715 const OwnershipAttr* Att) {
Sean Huntcf807c42010-08-18 23:23:40 +0000716 if (Att->getModule() != "malloc")
Anna Zaks87cb5be2012-02-22 19:24:52 +0000717 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000718
Sean Huntcf807c42010-08-18 23:23:40 +0000719 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000720 if (I != E) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000721 return MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), C.getState());
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000722 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000723 return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), C.getState());
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000724}
725
Anna Zaksb319e022012-02-08 20:13:28 +0000726ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000727 const CallExpr *CE,
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000728 SVal Size, SVal Init,
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000729 ProgramStateRef State,
730 AllocationFamily Family) {
Anna Zakse17fdb22012-06-07 03:57:32 +0000731
732 // Bind the return value to the symbolic value from the heap region.
733 // TODO: We could rewrite post visit to eval call; 'malloc' does not have
734 // side effects other than what we model here.
Ted Kremenek66c486f2012-08-22 06:26:15 +0000735 unsigned Count = C.blockCount();
Anna Zakse17fdb22012-06-07 03:57:32 +0000736 SValBuilder &svalBuilder = C.getSValBuilder();
737 const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
David Blaikie5251abe2013-02-20 05:52:05 +0000738 DefinedSVal RetVal = svalBuilder.getConjuredHeapSymbolVal(CE, LCtx, Count)
739 .castAs<DefinedSVal>();
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000740 State = State->BindExpr(CE, C.getLocationContext(), RetVal);
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000741
Anna Zaksb16ce452012-02-15 00:11:22 +0000742 // We expect the malloc functions to return a pointer.
David Blaikie5251abe2013-02-20 05:52:05 +0000743 if (!RetVal.getAs<Loc>())
Anna Zaksb16ce452012-02-15 00:11:22 +0000744 return 0;
745
Jordy Rose32f26562010-07-04 00:00:41 +0000746 // Fill the region with the initialization value.
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000747 State = State->bindDefault(RetVal, Init);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000748
Jordy Rose32f26562010-07-04 00:00:41 +0000749 // Set the region's extent equal to the Size parameter.
Anna Zakse9ef5622012-02-10 01:11:00 +0000750 const SymbolicRegion *R =
Anna Zakse17fdb22012-06-07 03:57:32 +0000751 dyn_cast_or_null<SymbolicRegion>(RetVal.getAsRegion());
Anna Zaks60a1fa42012-02-22 03:14:20 +0000752 if (!R)
Anna Zakse9ef5622012-02-10 01:11:00 +0000753 return 0;
David Blaikiedc84cd52013-02-20 22:23:23 +0000754 if (Optional<DefinedOrUnknownSVal> DefinedSize =
David Blaikie5251abe2013-02-20 05:52:05 +0000755 Size.getAs<DefinedOrUnknownSVal>()) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000756 SValBuilder &svalBuilder = C.getSValBuilder();
Anna Zaks60a1fa42012-02-22 03:14:20 +0000757 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
Anna Zaks60a1fa42012-02-22 03:14:20 +0000758 DefinedOrUnknownSVal extentMatchesSize =
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000759 svalBuilder.evalEQ(State, Extent, *DefinedSize);
Anna Zakse9ef5622012-02-10 01:11:00 +0000760
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000761 State = State->assume(extentMatchesSize, true);
762 assert(State);
Anna Zaks60a1fa42012-02-22 03:14:20 +0000763 }
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000764
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000765 return MallocUpdateRefState(C, CE, State, Family);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000766}
767
768ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C,
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000769 const Expr *E,
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000770 ProgramStateRef State,
771 AllocationFamily Family) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000772 // Get the return value.
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000773 SVal retVal = State->getSVal(E, C.getLocationContext());
Anna Zaks87cb5be2012-02-22 19:24:52 +0000774
775 // We expect the malloc functions to return a pointer.
David Blaikie5251abe2013-02-20 05:52:05 +0000776 if (!retVal.getAs<Loc>())
Anna Zaks87cb5be2012-02-22 19:24:52 +0000777 return 0;
778
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000779 SymbolRef Sym = retVal.getAsLocSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000780 assert(Sym);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000781
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000782 // Set the symbol's state to Allocated.
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000783 return State->set<RegionState>(Sym, RefState::getAllocated(Family, E));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000784}
785
Anna Zaks87cb5be2012-02-22 19:24:52 +0000786ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
787 const CallExpr *CE,
788 const OwnershipAttr* Att) const {
Sean Huntcf807c42010-08-18 23:23:40 +0000789 if (Att->getModule() != "malloc")
Anna Zaks87cb5be2012-02-22 19:24:52 +0000790 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000791
Anna Zaksb3d72752012-03-01 22:06:06 +0000792 ProgramStateRef State = C.getState();
Anna Zaks55dd9562012-08-24 02:28:20 +0000793 bool ReleasedAllocated = false;
Anna Zaksb3d72752012-03-01 22:06:06 +0000794
Sean Huntcf807c42010-08-18 23:23:40 +0000795 for (OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
796 I != E; ++I) {
Anna Zaksb3d72752012-03-01 22:06:06 +0000797 ProgramStateRef StateI = FreeMemAux(C, CE, State, *I,
Anna Zaks55dd9562012-08-24 02:28:20 +0000798 Att->getOwnKind() == OwnershipAttr::Holds,
799 ReleasedAllocated);
Anna Zaksb3d72752012-03-01 22:06:06 +0000800 if (StateI)
801 State = StateI;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000802 }
Anna Zaksb3d72752012-03-01 22:06:06 +0000803 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000804}
805
Ted Kremenek8bef8232012-01-26 21:29:00 +0000806ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
Anna Zakse9ef5622012-02-10 01:11:00 +0000807 const CallExpr *CE,
808 ProgramStateRef state,
809 unsigned Num,
Anna Zaks55dd9562012-08-24 02:28:20 +0000810 bool Hold,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000811 bool &ReleasedAllocated,
812 bool ReturnsNullOnFailure) const {
Anna Zaks259052d2012-04-10 23:41:11 +0000813 if (CE->getNumArgs() < (Num + 1))
814 return 0;
815
Anna Zaks4141e4d2012-11-13 03:18:01 +0000816 return FreeMemAux(C, CE->getArg(Num), CE, state, Hold,
817 ReleasedAllocated, ReturnsNullOnFailure);
818}
819
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000820/// Checks if the previous call to free on the given symbol failed - if free
821/// failed, returns true. Also, returns the corresponding return value symbol.
Benjamin Kramer4d9f4e52012-11-22 15:02:44 +0000822static bool didPreviousFreeFail(ProgramStateRef State,
823 SymbolRef Sym, SymbolRef &RetStatusSymbol) {
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000824 const SymbolRef *Ret = State->get<FreeReturnValue>(Sym);
Anna Zaks4141e4d2012-11-13 03:18:01 +0000825 if (Ret) {
826 assert(*Ret && "We should not store the null return symbol");
827 ConstraintManager &CMgr = State->getConstraintManager();
828 ConditionTruthVal FreeFailed = CMgr.isNull(State, *Ret);
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000829 RetStatusSymbol = *Ret;
830 return FreeFailed.isConstrainedTrue();
Anna Zaks4141e4d2012-11-13 03:18:01 +0000831 }
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000832 return false;
Anna Zaks5b7aa342012-06-22 02:04:31 +0000833}
834
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000835AllocationFamily MallocChecker::getAllocationFamily(CheckerContext &C,
Anton Yartsev648cb712013-04-04 23:46:29 +0000836 const Stmt *S) const {
837 if (!S)
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000838 return AF_None;
839
Anton Yartsev648cb712013-04-04 23:46:29 +0000840 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000841 const FunctionDecl *FD = C.getCalleeDecl(CE);
Anton Yartsev648cb712013-04-04 23:46:29 +0000842
843 if (!FD)
844 FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
845
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000846 ASTContext &Ctx = C.getASTContext();
847
Anton Yartsev648cb712013-04-04 23:46:29 +0000848 if (isAllocationFunction(FD, Ctx) || isFreeFunction(FD, Ctx))
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000849 return AF_Malloc;
850
851 if (isStandardNewDelete(FD, Ctx)) {
852 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
Anton Yartsev648cb712013-04-04 23:46:29 +0000853 if (Kind == OO_New || Kind == OO_Delete)
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000854 return AF_CXXNew;
Anton Yartsev648cb712013-04-04 23:46:29 +0000855 else if (Kind == OO_Array_New || Kind == OO_Array_Delete)
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000856 return AF_CXXNewArray;
857 }
858
859 return AF_None;
860 }
861
Anton Yartsev648cb712013-04-04 23:46:29 +0000862 if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(S))
863 return NE->isArray() ? AF_CXXNewArray : AF_CXXNew;
864
865 if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(S))
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000866 return DE->isArrayForm() ? AF_CXXNewArray : AF_CXXNew;
867
Anton Yartsev648cb712013-04-04 23:46:29 +0000868 if (isa<ObjCMessageExpr>(S))
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000869 return AF_Malloc;
870
871 return AF_None;
872}
873
874bool MallocChecker::printAllocDeallocName(raw_ostream &os, CheckerContext &C,
875 const Expr *E) const {
876 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
877 // FIXME: This doesn't handle indirect calls.
878 const FunctionDecl *FD = CE->getDirectCallee();
879 if (!FD)
880 return false;
881
882 os << *FD;
883 if (!FD->isOverloadedOperator())
884 os << "()";
885 return true;
886 }
887
888 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E)) {
889 if (Msg->isInstanceMessage())
890 os << "-";
891 else
892 os << "+";
893 os << Msg->getSelector().getAsString();
894 return true;
895 }
896
897 if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(E)) {
898 os << "'"
899 << getOperatorSpelling(NE->getOperatorNew()->getOverloadedOperator())
900 << "'";
901 return true;
902 }
903
904 if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(E)) {
905 os << "'"
906 << getOperatorSpelling(DE->getOperatorDelete()->getOverloadedOperator())
907 << "'";
908 return true;
909 }
910
911 return false;
912}
913
914void MallocChecker::printExpectedAllocName(raw_ostream &os, CheckerContext &C,
915 const Expr *E) const {
916 AllocationFamily Family = getAllocationFamily(C, E);
917
918 switch(Family) {
919 case AF_Malloc: os << "malloc()"; return;
920 case AF_CXXNew: os << "'new'"; return;
921 case AF_CXXNewArray: os << "'new[]'"; return;
922 case AF_None: llvm_unreachable("not a deallocation expression");
923 }
924}
925
926void MallocChecker::printExpectedDeallocName(raw_ostream &os,
927 AllocationFamily Family) const {
928 switch(Family) {
929 case AF_Malloc: os << "free()"; return;
930 case AF_CXXNew: os << "'delete'"; return;
931 case AF_CXXNewArray: os << "'delete[]'"; return;
932 case AF_None: llvm_unreachable("suspicious AF_None argument");
933 }
934}
935
Anna Zaks5b7aa342012-06-22 02:04:31 +0000936ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
937 const Expr *ArgExpr,
938 const Expr *ParentExpr,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000939 ProgramStateRef State,
Anna Zaks55dd9562012-08-24 02:28:20 +0000940 bool Hold,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000941 bool &ReleasedAllocated,
942 bool ReturnsNullOnFailure) const {
Anna Zaks5b7aa342012-06-22 02:04:31 +0000943
Anna Zaks4141e4d2012-11-13 03:18:01 +0000944 SVal ArgVal = State->getSVal(ArgExpr, C.getLocationContext());
David Blaikie5251abe2013-02-20 05:52:05 +0000945 if (!ArgVal.getAs<DefinedOrUnknownSVal>())
Anna Zakse9ef5622012-02-10 01:11:00 +0000946 return 0;
David Blaikie5251abe2013-02-20 05:52:05 +0000947 DefinedOrUnknownSVal location = ArgVal.castAs<DefinedOrUnknownSVal>();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000948
949 // Check for null dereferences.
David Blaikie5251abe2013-02-20 05:52:05 +0000950 if (!location.getAs<Loc>())
Anna Zaksb319e022012-02-08 20:13:28 +0000951 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000952
Anna Zaksb276bd92012-02-14 00:26:13 +0000953 // The explicit NULL case, no operation is performed.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000954 ProgramStateRef notNullState, nullState;
Anna Zaks4141e4d2012-11-13 03:18:01 +0000955 llvm::tie(notNullState, nullState) = State->assume(location);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000956 if (nullState && !notNullState)
Anna Zaksb319e022012-02-08 20:13:28 +0000957 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000958
Jordy Rose43859f62010-06-07 19:32:37 +0000959 // Unknown values could easily be okay
960 // Undefined values are handled elsewhere
961 if (ArgVal.isUnknownOrUndef())
Anna Zaksb319e022012-02-08 20:13:28 +0000962 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000963
Jordy Rose43859f62010-06-07 19:32:37 +0000964 const MemRegion *R = ArgVal.getAsRegion();
965
966 // Nonlocs can't be freed, of course.
967 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
968 if (!R) {
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000969 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
Anna Zaksb319e022012-02-08 20:13:28 +0000970 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000971 }
972
973 R = R->StripCasts();
974
975 // Blocks might show up as heap data, but should not be free()d
976 if (isa<BlockDataRegion>(R)) {
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000977 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
Anna Zaksb319e022012-02-08 20:13:28 +0000978 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000979 }
980
981 const MemSpaceRegion *MS = R->getMemorySpace();
982
Anton Yartsevbb369952013-03-13 14:39:10 +0000983 // Parameters, locals, statics, globals, and memory returned by alloca()
984 // shouldn't be freed.
Jordy Rose43859f62010-06-07 19:32:37 +0000985 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
986 // FIXME: at the time this code was written, malloc() regions were
987 // represented by conjured symbols, which are all in UnknownSpaceRegion.
988 // This means that there isn't actually anything from HeapSpaceRegion
989 // that should be freed, even though we allow it here.
990 // Of course, free() can work on memory allocated outside the current
991 // function, so UnknownSpaceRegion is always a possibility.
992 // False negatives are better than false positives.
993
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000994 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
Anna Zaksb319e022012-02-08 20:13:28 +0000995 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000996 }
Anna Zaks118aa752013-02-07 23:05:47 +0000997
998 const SymbolicRegion *SrBase = dyn_cast<SymbolicRegion>(R->getBaseRegion());
Jordy Rose43859f62010-06-07 19:32:37 +0000999 // Various cases could lead to non-symbol values here.
1000 // For now, ignore them.
Anna Zaks118aa752013-02-07 23:05:47 +00001001 if (!SrBase)
Anna Zaksb319e022012-02-08 20:13:28 +00001002 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +00001003
Anna Zaks118aa752013-02-07 23:05:47 +00001004 SymbolRef SymBase = SrBase->getSymbol();
1005 const RefState *RsBase = State->get<RegionState>(SymBase);
Anna Zaks2ccecfa2012-11-13 19:47:40 +00001006 SymbolRef PreviousRetStatusSymbol = 0;
Zhongxing Xu7e3cda92010-01-18 03:27:34 +00001007
Anton Yartsev648cb712013-04-04 23:46:29 +00001008 if (RsBase) {
Zhongxing Xu589c0f22009-11-12 08:38:56 +00001009
Anton Yartsev648cb712013-04-04 23:46:29 +00001010 bool DeallocMatchesAlloc =
1011 RsBase->getAllocationFamily() == AF_None ||
1012 RsBase->getAllocationFamily() == getAllocationFamily(C, ParentExpr);
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001013
Anton Yartsev648cb712013-04-04 23:46:29 +00001014 // Check if an expected deallocation function matches the real one.
1015 if (!DeallocMatchesAlloc && RsBase->isAllocated()) {
1016 ReportMismatchedDealloc(C, ArgExpr->getSourceRange(), ParentExpr, RsBase);
1017 return 0;
1018 }
1019
1020 // Check double free.
1021 if (DeallocMatchesAlloc &&
1022 (RsBase->isReleased() || RsBase->isRelinquished()) &&
1023 !didPreviousFreeFail(State, SymBase, PreviousRetStatusSymbol)) {
1024 ReportDoubleFree(C, ParentExpr->getSourceRange(), RsBase->isReleased(),
1025 SymBase, PreviousRetStatusSymbol);
1026 return 0;
1027 }
1028
1029 // Check if the memory location being freed is the actual location
1030 // allocated, or an offset.
1031 RegionOffset Offset = R->getAsOffset();
1032 if (RsBase->isAllocated() &&
1033 Offset.isValid() &&
1034 !Offset.hasSymbolicOffset() &&
1035 Offset.getOffset() != 0) {
1036 const Expr *AllocExpr = cast<Expr>(RsBase->getStmt());
1037 ReportOffsetFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr,
1038 AllocExpr);
1039 return 0;
1040 }
Anna Zaks118aa752013-02-07 23:05:47 +00001041 }
1042
1043 ReleasedAllocated = (RsBase != 0);
Anna Zaks55dd9562012-08-24 02:28:20 +00001044
Anna Zaks2ccecfa2012-11-13 19:47:40 +00001045 // Clean out the info on previous call to free return info.
Anna Zaks118aa752013-02-07 23:05:47 +00001046 State = State->remove<FreeReturnValue>(SymBase);
Anna Zaks2ccecfa2012-11-13 19:47:40 +00001047
Anna Zaks4141e4d2012-11-13 03:18:01 +00001048 // Keep track of the return value. If it is NULL, we will know that free
1049 // failed.
1050 if (ReturnsNullOnFailure) {
1051 SVal RetVal = C.getSVal(ParentExpr);
1052 SymbolRef RetStatusSymbol = RetVal.getAsSymbol();
1053 if (RetStatusSymbol) {
Anna Zaks118aa752013-02-07 23:05:47 +00001054 C.getSymbolManager().addSymbolDependency(SymBase, RetStatusSymbol);
1055 State = State->set<FreeReturnValue>(SymBase, RetStatusSymbol);
Anna Zaks4141e4d2012-11-13 03:18:01 +00001056 }
1057 }
1058
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001059 AllocationFamily Family = RsBase ? RsBase->getAllocationFamily() : AF_None;
Zhongxing Xu589c0f22009-11-12 08:38:56 +00001060 // Normal free.
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001061 if (Hold)
Anna Zaks118aa752013-02-07 23:05:47 +00001062 return State->set<RegionState>(SymBase,
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001063 RefState::getRelinquished(Family,
1064 ParentExpr));
1065
1066 return State->set<RegionState>(SymBase,
1067 RefState::getReleased(Family, ParentExpr));
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001068}
1069
Anton Yartsev648cb712013-04-04 23:46:29 +00001070bool MallocChecker::isTrackedFamily(AllocationFamily Family) const {
1071 if (Family == AF_Malloc &&
1072 (!Filter.CMallocOptimistic && !Filter.CMallocPessimistic))
1073 return false;
1074
1075 if ((Family == AF_CXXNew || Family == AF_CXXNewArray) &&
1076 !Filter.CNewDeleteChecker)
1077 return false;
1078
1079 return true;
1080}
1081
1082bool MallocChecker::isTrackedFamily(CheckerContext &C,
1083 const Stmt *AllocDeallocStmt) const {
1084 return isTrackedFamily(getAllocationFamily(C, AllocDeallocStmt));
1085}
1086
1087bool MallocChecker::isTrackedFamily(CheckerContext &C, SymbolRef Sym) const {
1088 const RefState *RS = C.getState()->get<RegionState>(Sym);
1089
1090 return RS ? isTrackedFamily(RS->getAllocationFamily())
1091 : isTrackedFamily(AF_None);
1092}
1093
Ted Kremenek9c378f72011-08-12 23:37:29 +00001094bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
David Blaikiedc84cd52013-02-20 22:23:23 +00001095 if (Optional<nonloc::ConcreteInt> IntVal = V.getAs<nonloc::ConcreteInt>())
Jordy Rose43859f62010-06-07 19:32:37 +00001096 os << "an integer (" << IntVal->getValue() << ")";
David Blaikiedc84cd52013-02-20 22:23:23 +00001097 else if (Optional<loc::ConcreteInt> ConstAddr = V.getAs<loc::ConcreteInt>())
Jordy Rose43859f62010-06-07 19:32:37 +00001098 os << "a constant address (" << ConstAddr->getValue() << ")";
David Blaikiedc84cd52013-02-20 22:23:23 +00001099 else if (Optional<loc::GotoLabel> Label = V.getAs<loc::GotoLabel>())
Chris Lattner68106302011-02-17 05:38:27 +00001100 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose43859f62010-06-07 19:32:37 +00001101 else
1102 return false;
1103
1104 return true;
1105}
1106
Ted Kremenek9c378f72011-08-12 23:37:29 +00001107bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose43859f62010-06-07 19:32:37 +00001108 const MemRegion *MR) {
1109 switch (MR->getKind()) {
1110 case MemRegion::FunctionTextRegionKind: {
Anna Zaks5fc1d0c2012-09-17 19:13:56 +00001111 const NamedDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
Jordy Rose43859f62010-06-07 19:32:37 +00001112 if (FD)
Benjamin Kramerb8989f22011-10-14 18:45:37 +00001113 os << "the address of the function '" << *FD << '\'';
Jordy Rose43859f62010-06-07 19:32:37 +00001114 else
1115 os << "the address of a function";
1116 return true;
1117 }
1118 case MemRegion::BlockTextRegionKind:
1119 os << "block text";
1120 return true;
1121 case MemRegion::BlockDataRegionKind:
1122 // FIXME: where the block came from?
1123 os << "a block";
1124 return true;
1125 default: {
1126 const MemSpaceRegion *MS = MR->getMemorySpace();
1127
Anna Zakseb31a762012-01-04 23:54:01 +00001128 if (isa<StackLocalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +00001129 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1130 const VarDecl *VD;
1131 if (VR)
1132 VD = VR->getDecl();
1133 else
1134 VD = NULL;
1135
1136 if (VD)
1137 os << "the address of the local variable '" << VD->getName() << "'";
1138 else
1139 os << "the address of a local stack variable";
1140 return true;
1141 }
Anna Zakseb31a762012-01-04 23:54:01 +00001142
1143 if (isa<StackArgumentsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +00001144 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1145 const VarDecl *VD;
1146 if (VR)
1147 VD = VR->getDecl();
1148 else
1149 VD = NULL;
1150
1151 if (VD)
1152 os << "the address of the parameter '" << VD->getName() << "'";
1153 else
1154 os << "the address of a parameter";
1155 return true;
1156 }
Anna Zakseb31a762012-01-04 23:54:01 +00001157
1158 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +00001159 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1160 const VarDecl *VD;
1161 if (VR)
1162 VD = VR->getDecl();
1163 else
1164 VD = NULL;
1165
1166 if (VD) {
1167 if (VD->isStaticLocal())
1168 os << "the address of the static variable '" << VD->getName() << "'";
1169 else
1170 os << "the address of the global variable '" << VD->getName() << "'";
1171 } else
1172 os << "the address of a global variable";
1173 return true;
1174 }
Anna Zakseb31a762012-01-04 23:54:01 +00001175
1176 return false;
Jordy Rose43859f62010-06-07 19:32:37 +00001177 }
1178 }
1179}
1180
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001181void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
1182 SourceRange Range,
1183 const Expr *DeallocExpr) const {
1184
1185 if (!Filter.CMallocOptimistic && !Filter.CMallocPessimistic &&
1186 !Filter.CNewDeleteChecker)
1187 return;
1188
Anton Yartsev648cb712013-04-04 23:46:29 +00001189 if (!isTrackedFamily(C, DeallocExpr))
1190 return;
1191
Ted Kremenekd048c6e2010-12-20 21:19:09 +00001192 if (ExplodedNode *N = C.generateSink()) {
Jordy Rose43859f62010-06-07 19:32:37 +00001193 if (!BT_BadFree)
Anna Zaksfebdc322012-02-16 22:26:12 +00001194 BT_BadFree.reset(new BugType("Bad free", "Memory Error"));
Jordy Rose43859f62010-06-07 19:32:37 +00001195
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00001196 SmallString<100> buf;
Jordy Rose43859f62010-06-07 19:32:37 +00001197 llvm::raw_svector_ostream os(buf);
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001198
Jordy Rose43859f62010-06-07 19:32:37 +00001199 const MemRegion *MR = ArgVal.getAsRegion();
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001200 while (const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(MR))
1201 MR = ER->getSuperRegion();
1202
1203 if (MR && isa<AllocaRegion>(MR))
1204 os << "Memory allocated by alloca() should not be deallocated";
1205 else {
1206 os << "Argument to ";
1207 if (!printAllocDeallocName(os, C, DeallocExpr))
1208 os << "deallocator";
1209
1210 os << " is ";
1211 bool Summarized = MR ? SummarizeRegion(os, MR)
1212 : SummarizeValue(os, ArgVal);
1213 if (Summarized)
1214 os << ", which is not memory allocated by ";
Jordy Rose43859f62010-06-07 19:32:37 +00001215 else
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001216 os << "not memory allocated by ";
1217
1218 printExpectedAllocName(os, C, DeallocExpr);
Jordy Rose43859f62010-06-07 19:32:37 +00001219 }
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001220
Anna Zakse172e8b2011-08-17 23:00:25 +00001221 BugReport *R = new BugReport(*BT_BadFree, os.str(), N);
Ted Kremenek76aadc32012-03-09 01:13:14 +00001222 R->markInteresting(MR);
Anton Yartsevbb369952013-03-13 14:39:10 +00001223 R->addRange(Range);
Jordan Rose785950e2012-11-02 01:53:40 +00001224 C.emitReport(R);
Jordy Rose43859f62010-06-07 19:32:37 +00001225 }
1226}
1227
Anton Yartsev648cb712013-04-04 23:46:29 +00001228void MallocChecker::ReportMismatchedDealloc(CheckerContext &C,
1229 SourceRange Range,
1230 const Expr *DeallocExpr,
1231 const RefState *RS) const {
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001232
1233 if (!Filter.CMismatchedDeallocatorChecker)
1234 return;
1235
1236 if (ExplodedNode *N = C.generateSink()) {
Anton Yartsev648cb712013-04-04 23:46:29 +00001237 if (!BT_MismatchedDealloc)
1238 BT_MismatchedDealloc.reset(new BugType("Bad deallocator",
1239 "Memory Error"));
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001240
1241 SmallString<100> buf;
1242 llvm::raw_svector_ostream os(buf);
1243
1244 const Expr *AllocExpr = cast<Expr>(RS->getStmt());
1245 SmallString<20> AllocBuf;
1246 llvm::raw_svector_ostream AllocOs(AllocBuf);
1247 SmallString<20> DeallocBuf;
1248 llvm::raw_svector_ostream DeallocOs(DeallocBuf);
1249
1250 os << "Memory";
1251 if (printAllocDeallocName(AllocOs, C, AllocExpr))
1252 os << " allocated by " << AllocOs.str();
1253
1254 os << " should be deallocated by ";
1255 printExpectedDeallocName(os, RS->getAllocationFamily());
1256
1257 if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1258 os << ", not " << DeallocOs.str();
1259
Anton Yartsev648cb712013-04-04 23:46:29 +00001260 BugReport *R = new BugReport(*BT_MismatchedDealloc, os.str(), N);
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001261 R->addRange(Range);
1262 C.emitReport(R);
1263 }
1264}
1265
Anna Zaks118aa752013-02-07 23:05:47 +00001266void MallocChecker::ReportOffsetFree(CheckerContext &C, SVal ArgVal,
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001267 SourceRange Range, const Expr *DeallocExpr,
1268 const Expr *AllocExpr) const {
1269
1270 if (!Filter.CMallocOptimistic && !Filter.CMallocPessimistic &&
1271 !Filter.CNewDeleteChecker)
1272 return;
1273
Anton Yartsev648cb712013-04-04 23:46:29 +00001274 if (!isTrackedFamily(C, AllocExpr))
1275 return;
1276
Anna Zaks118aa752013-02-07 23:05:47 +00001277 ExplodedNode *N = C.generateSink();
1278 if (N == NULL)
1279 return;
1280
1281 if (!BT_OffsetFree)
1282 BT_OffsetFree.reset(new BugType("Offset free", "Memory Error"));
1283
1284 SmallString<100> buf;
1285 llvm::raw_svector_ostream os(buf);
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001286 SmallString<20> AllocNameBuf;
1287 llvm::raw_svector_ostream AllocNameOs(AllocNameBuf);
Anna Zaks118aa752013-02-07 23:05:47 +00001288
1289 const MemRegion *MR = ArgVal.getAsRegion();
1290 assert(MR && "Only MemRegion based symbols can have offset free errors");
1291
1292 RegionOffset Offset = MR->getAsOffset();
1293 assert((Offset.isValid() &&
1294 !Offset.hasSymbolicOffset() &&
1295 Offset.getOffset() != 0) &&
1296 "Only symbols with a valid offset can have offset free errors");
1297
1298 int offsetBytes = Offset.getOffset() / C.getASTContext().getCharWidth();
1299
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001300 os << "Argument to ";
1301 if (!printAllocDeallocName(os, C, DeallocExpr))
1302 os << "deallocator";
1303 os << " is offset by "
Anna Zaks118aa752013-02-07 23:05:47 +00001304 << offsetBytes
1305 << " "
1306 << ((abs(offsetBytes) > 1) ? "bytes" : "byte")
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001307 << " from the start of ";
1308 if (AllocExpr && printAllocDeallocName(AllocNameOs, C, AllocExpr))
1309 os << "memory allocated by " << AllocNameOs.str();
1310 else
1311 os << "allocated memory";
Anna Zaks118aa752013-02-07 23:05:47 +00001312
1313 BugReport *R = new BugReport(*BT_OffsetFree, os.str(), N);
1314 R->markInteresting(MR->getBaseRegion());
1315 R->addRange(Range);
1316 C.emitReport(R);
1317}
1318
Anton Yartsevbb369952013-03-13 14:39:10 +00001319void MallocChecker::ReportUseAfterFree(CheckerContext &C, SourceRange Range,
1320 SymbolRef Sym) const {
1321
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001322 if (!Filter.CMallocOptimistic && !Filter.CMallocPessimistic &&
1323 !Filter.CNewDeleteChecker)
1324 return;
1325
Anton Yartsev648cb712013-04-04 23:46:29 +00001326 if (!isTrackedFamily(C, Sym))
1327 return;
1328
Anton Yartsevbb369952013-03-13 14:39:10 +00001329 if (ExplodedNode *N = C.generateSink()) {
1330 if (!BT_UseFree)
1331 BT_UseFree.reset(new BugType("Use-after-free", "Memory Error"));
1332
1333 BugReport *R = new BugReport(*BT_UseFree,
1334 "Use of memory after it is freed", N);
1335
1336 R->markInteresting(Sym);
1337 R->addRange(Range);
1338 R->addVisitor(new MallocBugVisitor(Sym));
1339 C.emitReport(R);
1340 }
1341}
1342
1343void MallocChecker::ReportDoubleFree(CheckerContext &C, SourceRange Range,
1344 bool Released, SymbolRef Sym,
Anton Yartsev3258d4b2013-03-13 17:07:32 +00001345 SymbolRef PrevSym) const {
Anton Yartsevbb369952013-03-13 14:39:10 +00001346
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001347 if (!Filter.CMallocOptimistic && !Filter.CMallocPessimistic &&
1348 !Filter.CNewDeleteChecker)
1349 return;
1350
Anton Yartsev648cb712013-04-04 23:46:29 +00001351 if (!isTrackedFamily(C, Sym))
1352 return;
1353
Anton Yartsevbb369952013-03-13 14:39:10 +00001354 if (ExplodedNode *N = C.generateSink()) {
1355 if (!BT_DoubleFree)
1356 BT_DoubleFree.reset(new BugType("Double free", "Memory Error"));
1357
1358 BugReport *R = new BugReport(*BT_DoubleFree,
1359 (Released ? "Attempt to free released memory"
1360 : "Attempt to free non-owned memory"),
1361 N);
1362 R->addRange(Range);
Anton Yartsev3258d4b2013-03-13 17:07:32 +00001363 R->markInteresting(Sym);
1364 if (PrevSym)
1365 R->markInteresting(PrevSym);
Anton Yartsevbb369952013-03-13 14:39:10 +00001366 R->addVisitor(new MallocBugVisitor(Sym));
1367 C.emitReport(R);
1368 }
1369}
1370
Anna Zaks87cb5be2012-02-22 19:24:52 +00001371ProgramStateRef MallocChecker::ReallocMem(CheckerContext &C,
1372 const CallExpr *CE,
1373 bool FreesOnFail) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001374 if (CE->getNumArgs() < 2)
1375 return 0;
1376
Ted Kremenek8bef8232012-01-26 21:29:00 +00001377 ProgramStateRef state = C.getState();
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001378 const Expr *arg0Expr = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001379 const LocationContext *LCtx = C.getLocationContext();
Anna Zakse9ef5622012-02-10 01:11:00 +00001380 SVal Arg0Val = state->getSVal(arg0Expr, LCtx);
David Blaikie5251abe2013-02-20 05:52:05 +00001381 if (!Arg0Val.getAs<DefinedOrUnknownSVal>())
Anna Zaks87cb5be2012-02-22 19:24:52 +00001382 return 0;
David Blaikie5251abe2013-02-20 05:52:05 +00001383 DefinedOrUnknownSVal arg0Val = Arg0Val.castAs<DefinedOrUnknownSVal>();
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001384
Ted Kremenek846eabd2010-12-01 21:28:31 +00001385 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001386
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001387 DefinedOrUnknownSVal PtrEQ =
1388 svalBuilder.evalEQ(state, arg0Val, svalBuilder.makeNull());
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001389
Lenny Maiorani4d8d8032011-04-27 14:49:29 +00001390 // Get the size argument. If there is no size arg then give up.
1391 const Expr *Arg1 = CE->getArg(1);
1392 if (!Arg1)
Anna Zaks87cb5be2012-02-22 19:24:52 +00001393 return 0;
Lenny Maiorani4d8d8032011-04-27 14:49:29 +00001394
1395 // Get the value of the size argument.
Anna Zakse9ef5622012-02-10 01:11:00 +00001396 SVal Arg1ValG = state->getSVal(Arg1, LCtx);
David Blaikie5251abe2013-02-20 05:52:05 +00001397 if (!Arg1ValG.getAs<DefinedOrUnknownSVal>())
Anna Zaks87cb5be2012-02-22 19:24:52 +00001398 return 0;
David Blaikie5251abe2013-02-20 05:52:05 +00001399 DefinedOrUnknownSVal Arg1Val = Arg1ValG.castAs<DefinedOrUnknownSVal>();
Lenny Maiorani4d8d8032011-04-27 14:49:29 +00001400
1401 // Compare the size argument to 0.
1402 DefinedOrUnknownSVal SizeZero =
1403 svalBuilder.evalEQ(state, Arg1Val,
1404 svalBuilder.makeIntValWithPtrWidth(0, false));
1405
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001406 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
1407 llvm::tie(StatePtrIsNull, StatePtrNotNull) = state->assume(PtrEQ);
1408 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
1409 llvm::tie(StateSizeIsZero, StateSizeNotZero) = state->assume(SizeZero);
1410 // We only assume exceptional states if they are definitely true; if the
1411 // state is under-constrained, assume regular realloc behavior.
1412 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
1413 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
1414
Lenny Maiorani4d8d8032011-04-27 14:49:29 +00001415 // If the ptr is NULL and the size is not 0, the call is equivalent to
1416 // malloc(size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001417 if ( PrtIsNull && !SizeIsZero) {
Anna Zaks87cb5be2012-02-22 19:24:52 +00001418 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001419 UndefinedVal(), StatePtrIsNull);
Anna Zaks87cb5be2012-02-22 19:24:52 +00001420 return stateMalloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001421 }
1422
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001423 if (PrtIsNull && SizeIsZero)
Anna Zaks87cb5be2012-02-22 19:24:52 +00001424 return 0;
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001425
Anna Zaks30838b92012-02-13 20:57:07 +00001426 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001427 assert(!PrtIsNull);
Anna Zaks30838b92012-02-13 20:57:07 +00001428 SymbolRef FromPtr = arg0Val.getAsSymbol();
1429 SVal RetVal = state->getSVal(CE, LCtx);
1430 SymbolRef ToPtr = RetVal.getAsSymbol();
1431 if (!FromPtr || !ToPtr)
Anna Zaks87cb5be2012-02-22 19:24:52 +00001432 return 0;
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001433
Anna Zaks55dd9562012-08-24 02:28:20 +00001434 bool ReleasedAllocated = false;
1435
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001436 // If the size is 0, free the memory.
1437 if (SizeIsZero)
Anna Zaks55dd9562012-08-24 02:28:20 +00001438 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero, 0,
1439 false, ReleasedAllocated)){
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001440 // The semantics of the return value are:
1441 // If size was equal to 0, either NULL or a pointer suitable to be passed
Anna Zaksede875b2012-08-03 18:30:18 +00001442 // to free() is returned. We just free the input pointer and do not add
1443 // any constrains on the output pointer.
Anna Zaks87cb5be2012-02-22 19:24:52 +00001444 return stateFree;
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001445 }
1446
1447 // Default behavior.
Anna Zaks55dd9562012-08-24 02:28:20 +00001448 if (ProgramStateRef stateFree =
1449 FreeMemAux(C, CE, state, 0, false, ReleasedAllocated)) {
1450
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001451 ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
1452 UnknownVal(), stateFree);
Anna Zaks30838b92012-02-13 20:57:07 +00001453 if (!stateRealloc)
Anna Zaks87cb5be2012-02-22 19:24:52 +00001454 return 0;
Anna Zaks55dd9562012-08-24 02:28:20 +00001455
Anna Zaks9dc298b2012-09-12 22:57:34 +00001456 ReallocPairKind Kind = RPToBeFreedAfterFailure;
1457 if (FreesOnFail)
1458 Kind = RPIsFreeOnFailure;
1459 else if (!ReleasedAllocated)
1460 Kind = RPDoNotTrackAfterFailure;
1461
Anna Zaks55dd9562012-08-24 02:28:20 +00001462 // Record the info about the reallocated symbol so that we could properly
1463 // process failed reallocation.
Anna Zaks40add292012-02-15 00:11:25 +00001464 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
Anna Zaks9dc298b2012-09-12 22:57:34 +00001465 ReallocPair(FromPtr, Kind));
Anna Zaks55dd9562012-08-24 02:28:20 +00001466 // The reallocated symbol should stay alive for as long as the new symbol.
Anna Zaksb276bd92012-02-14 00:26:13 +00001467 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks87cb5be2012-02-22 19:24:52 +00001468 return stateRealloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001469 }
Anna Zaks87cb5be2012-02-22 19:24:52 +00001470 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +00001471}
Zhongxing Xu7b760962009-11-13 07:25:27 +00001472
Anna Zaks87cb5be2012-02-22 19:24:52 +00001473ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE){
Anna Zaks259052d2012-04-10 23:41:11 +00001474 if (CE->getNumArgs() < 2)
1475 return 0;
1476
Ted Kremenek8bef8232012-01-26 21:29:00 +00001477 ProgramStateRef state = C.getState();
Ted Kremenek846eabd2010-12-01 21:28:31 +00001478 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001479 const LocationContext *LCtx = C.getLocationContext();
1480 SVal count = state->getSVal(CE->getArg(0), LCtx);
1481 SVal elementSize = state->getSVal(CE->getArg(1), LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001482 SVal TotalSize = svalBuilder.evalBinOp(state, BO_Mul, count, elementSize,
1483 svalBuilder.getContext().getSizeType());
1484 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Zhongxing Xua5ce9662010-06-01 03:01:33 +00001485
Anna Zaks87cb5be2012-02-22 19:24:52 +00001486 return MallocMemAux(C, CE, TotalSize, zeroVal, state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +00001487}
1488
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001489LeakInfo
Anna Zaksca8e36e2012-02-23 21:38:21 +00001490MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
1491 CheckerContext &C) const {
Anna Zaks7752d292012-02-27 23:40:55 +00001492 const LocationContext *LeakContext = N->getLocationContext();
Anna Zaksca8e36e2012-02-23 21:38:21 +00001493 // Walk the ExplodedGraph backwards and find the first node that referred to
1494 // the tracked symbol.
1495 const ExplodedNode *AllocNode = N;
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001496 const MemRegion *ReferenceRegion = 0;
Anna Zaksca8e36e2012-02-23 21:38:21 +00001497
1498 while (N) {
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001499 ProgramStateRef State = N->getState();
1500 if (!State->get<RegionState>(Sym))
Anna Zaksca8e36e2012-02-23 21:38:21 +00001501 break;
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001502
1503 // Find the most recent expression bound to the symbol in the current
1504 // context.
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001505 if (!ReferenceRegion) {
Benjamin Kramer850f1b12012-03-21 21:03:48 +00001506 if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
1507 SVal Val = State->getSVal(MR);
1508 if (Val.getAsLocSymbol() == Sym)
1509 ReferenceRegion = MR;
1510 }
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001511 }
1512
Anna Zaks7752d292012-02-27 23:40:55 +00001513 // Allocation node, is the last node in the current context in which the
1514 // symbol was tracked.
1515 if (N->getLocationContext() == LeakContext)
1516 AllocNode = N;
Anna Zaksca8e36e2012-02-23 21:38:21 +00001517 N = N->pred_empty() ? NULL : *(N->pred_begin());
1518 }
1519
Anna Zaks97bfb552013-01-08 00:25:29 +00001520 return LeakInfo(AllocNode, ReferenceRegion);
Anna Zaksca8e36e2012-02-23 21:38:21 +00001521}
1522
Anna Zaksda046772012-02-11 21:02:40 +00001523void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
1524 CheckerContext &C) const {
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001525
1526 if (!Filter.CMallocOptimistic && !Filter.CMallocPessimistic &&
1527 !Filter.CNewDeleteChecker)
1528 return;
1529
Anna Zaksda046772012-02-11 21:02:40 +00001530 assert(N);
1531 if (!BT_Leak) {
Anna Zaksfebdc322012-02-16 22:26:12 +00001532 BT_Leak.reset(new BugType("Memory leak", "Memory Error"));
Anna Zaksda046772012-02-11 21:02:40 +00001533 // Leaks should not be reported if they are post-dominated by a sink:
1534 // (1) Sinks are higher importance bugs.
1535 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
1536 // with __noreturn functions such as assert() or exit(). We choose not
1537 // to report leaks on such paths.
1538 BT_Leak->setSuppressOnSink(true);
1539 }
1540
Anna Zaksca8e36e2012-02-23 21:38:21 +00001541 // Most bug reports are cached at the location where they occurred.
1542 // With leaks, we want to unique them by the location where they were
1543 // allocated, and only report a single path.
Anna Zaks7752d292012-02-27 23:40:55 +00001544 PathDiagnosticLocation LocUsedForUniqueing;
Anna Zaks97bfb552013-01-08 00:25:29 +00001545 const ExplodedNode *AllocNode = 0;
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001546 const MemRegion *Region = 0;
Anna Zaks97bfb552013-01-08 00:25:29 +00001547 llvm::tie(AllocNode, Region) = getAllocationSite(N, Sym, C);
1548
1549 ProgramPoint P = AllocNode->getLocation();
1550 const Stmt *AllocationStmt = 0;
David Blaikie7a95de62013-02-21 22:23:56 +00001551 if (Optional<CallExitEnd> Exit = P.getAs<CallExitEnd>())
Anna Zaks97bfb552013-01-08 00:25:29 +00001552 AllocationStmt = Exit->getCalleeContext()->getCallSite();
David Blaikie7a95de62013-02-21 22:23:56 +00001553 else if (Optional<StmtPoint> SP = P.getAs<StmtPoint>())
Anna Zaks97bfb552013-01-08 00:25:29 +00001554 AllocationStmt = SP->getStmt();
Anton Yartsev648cb712013-04-04 23:46:29 +00001555 if (AllocationStmt) {
Anna Zaks97bfb552013-01-08 00:25:29 +00001556 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocationStmt,
1557 C.getSourceManager(),
1558 AllocNode->getLocationContext());
Anton Yartsev648cb712013-04-04 23:46:29 +00001559 if (!isTrackedFamily(C, AllocationStmt))
1560 return;
1561 }
Anna Zaksca8e36e2012-02-23 21:38:21 +00001562
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001563 SmallString<200> buf;
1564 llvm::raw_svector_ostream os(buf);
1565 os << "Memory is never released; potential leak";
Jordan Rose919e8a12012-08-08 18:23:36 +00001566 if (Region && Region->canPrintPretty()) {
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001567 os << " of memory pointed to by '";
Jordan Rose919e8a12012-08-08 18:23:36 +00001568 Region->printPretty(os);
Jordan Rose0d53ab42012-08-08 18:23:31 +00001569 os << '\'';
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001570 }
1571
Anna Zaks97bfb552013-01-08 00:25:29 +00001572 BugReport *R = new BugReport(*BT_Leak, os.str(), N,
1573 LocUsedForUniqueing,
1574 AllocNode->getLocationContext()->getDecl());
Ted Kremenek76aadc32012-03-09 01:13:14 +00001575 R->markInteresting(Sym);
Anna Zaks88feba02012-05-10 01:37:40 +00001576 R->addVisitor(new MallocBugVisitor(Sym, true));
Jordan Rose785950e2012-11-02 01:53:40 +00001577 C.emitReport(R);
Anna Zaksda046772012-02-11 21:02:40 +00001578}
1579
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001580void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
1581 CheckerContext &C) const
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001582{
Zhongxing Xu173ff562010-08-15 08:19:57 +00001583 if (!SymReaper.hasDeadSymbols())
1584 return;
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +00001585
Ted Kremenek8bef8232012-01-26 21:29:00 +00001586 ProgramStateRef state = C.getState();
Zhongxing Xu173ff562010-08-15 08:19:57 +00001587 RegionStateTy RS = state->get<RegionState>();
Jordy Rose90760142010-08-18 04:33:47 +00001588 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xu173ff562010-08-15 08:19:57 +00001589
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001590 SmallVector<SymbolRef, 2> Errors;
Zhongxing Xu173ff562010-08-15 08:19:57 +00001591 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
1592 if (SymReaper.isDead(I->first)) {
Anna Zaks54458702012-10-29 22:51:54 +00001593 if (I->second.isAllocated())
Anna Zaksf8c17b72012-02-09 06:48:19 +00001594 Errors.push_back(I->first);
Jordy Rose90760142010-08-18 04:33:47 +00001595 // Remove the dead symbol from the map.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001596 RS = F.remove(RS, I->first);
Ted Kremenek217470e2011-07-28 23:07:51 +00001597
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +00001598 }
1599 }
Ted Kremenek217470e2011-07-28 23:07:51 +00001600
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001601 // Cleanup the Realloc Pairs Map.
Jordan Rose166d5022012-11-02 01:54:06 +00001602 ReallocPairsTy RP = state->get<ReallocPairs>();
1603 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Anna Zaks40add292012-02-15 00:11:25 +00001604 if (SymReaper.isDead(I->first) ||
1605 SymReaper.isDead(I->second.ReallocatedSym)) {
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001606 state = state->remove<ReallocPairs>(I->first);
1607 }
1608 }
1609
Anna Zaks4141e4d2012-11-13 03:18:01 +00001610 // Cleanup the FreeReturnValue Map.
1611 FreeReturnValueTy FR = state->get<FreeReturnValue>();
1612 for (FreeReturnValueTy::iterator I = FR.begin(), E = FR.end(); I != E; ++I) {
1613 if (SymReaper.isDead(I->first) ||
1614 SymReaper.isDead(I->second)) {
1615 state = state->remove<FreeReturnValue>(I->first);
1616 }
1617 }
1618
Anna Zaksca8e36e2012-02-23 21:38:21 +00001619 // Generate leak node.
Anna Zaks54458702012-10-29 22:51:54 +00001620 ExplodedNode *N = C.getPredecessor();
1621 if (!Errors.empty()) {
1622 static SimpleProgramPointTag Tag("MallocChecker : DeadSymbolsLeak");
1623 N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001624 for (SmallVector<SymbolRef, 2>::iterator
Anna Zaks54458702012-10-29 22:51:54 +00001625 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
Anna Zaksda046772012-02-11 21:02:40 +00001626 reportLeak(*I, N, C);
Anna Zaksf8c17b72012-02-09 06:48:19 +00001627 }
Ted Kremenek217470e2011-07-28 23:07:51 +00001628 }
Anna Zaks54458702012-10-29 22:51:54 +00001629
Anna Zaksca8e36e2012-02-23 21:38:21 +00001630 C.addTransition(state->set<RegionState>(RS), N);
Zhongxing Xu7b760962009-11-13 07:25:27 +00001631}
Zhongxing Xu243fde92009-11-17 07:54:15 +00001632
Anna Zaks66c40402012-02-14 21:55:24 +00001633void MallocChecker::checkPreStmt(const CallExpr *CE, CheckerContext &C) const {
Anna Zaks14345182012-05-18 01:16:10 +00001634 // We will check for double free in the post visit.
Anton Yartsev2de19ed2013-03-25 01:35:45 +00001635 if ((Filter.CMallocOptimistic || Filter.CMallocPessimistic) &&
1636 isFreeFunction(C.getCalleeDecl(CE), C.getASTContext()))
1637 return;
1638
1639 if (Filter.CNewDeleteChecker &&
1640 isStandardNewDelete(C.getCalleeDecl(CE), C.getASTContext()))
Anna Zaks66c40402012-02-14 21:55:24 +00001641 return;
1642
1643 // Check use after free, when a freed pointer is passed to a call.
1644 ProgramStateRef State = C.getState();
1645 for (CallExpr::const_arg_iterator I = CE->arg_begin(),
1646 E = CE->arg_end(); I != E; ++I) {
1647 const Expr *A = *I;
1648 if (A->getType().getTypePtr()->isAnyPointerType()) {
Anton Yartsevbb369952013-03-13 14:39:10 +00001649 SymbolRef Sym = C.getSVal(A).getAsSymbol();
Anna Zaks66c40402012-02-14 21:55:24 +00001650 if (!Sym)
1651 continue;
1652 if (checkUseAfterFree(Sym, C, A))
1653 return;
1654 }
1655 }
1656}
1657
Anna Zaks91c2a112012-02-08 23:16:56 +00001658void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
1659 const Expr *E = S->getRetValue();
1660 if (!E)
1661 return;
Anna Zaks0860cd02012-02-11 21:44:39 +00001662
1663 // Check if we are returning a symbol.
Jordan Rose0d53ab42012-08-08 18:23:31 +00001664 ProgramStateRef State = C.getState();
1665 SVal RetVal = State->getSVal(E, C.getLocationContext());
Anna Zaksd9ab7bb2012-02-22 02:36:01 +00001666 SymbolRef Sym = RetVal.getAsSymbol();
1667 if (!Sym)
1668 // If we are returning a field of the allocated struct or an array element,
1669 // the callee could still free the memory.
1670 // TODO: This logic should be a part of generic symbol escape callback.
1671 if (const MemRegion *MR = RetVal.getAsRegion())
1672 if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
1673 if (const SymbolicRegion *BMR =
1674 dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
1675 Sym = BMR->getSymbol();
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001676
Anna Zaks0860cd02012-02-11 21:44:39 +00001677 // Check if we are returning freed memory.
Jordan Rose0d53ab42012-08-08 18:23:31 +00001678 if (Sym)
Jordan Rose65d4bd62012-11-15 19:11:33 +00001679 checkUseAfterFree(Sym, C, E);
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001680}
Zhongxing Xub94b81a2009-12-31 06:13:07 +00001681
Anna Zaksf5aa3f52012-03-22 00:57:20 +00001682// TODO: Blocks should be either inlined or should call invalidate regions
1683// upon invocation. After that's in place, special casing here will not be
1684// needed.
1685void MallocChecker::checkPostStmt(const BlockExpr *BE,
1686 CheckerContext &C) const {
1687
1688 // Scan the BlockDecRefExprs for any object the retain count checker
1689 // may be tracking.
1690 if (!BE->getBlockDecl()->hasCaptures())
1691 return;
1692
1693 ProgramStateRef state = C.getState();
1694 const BlockDataRegion *R =
1695 cast<BlockDataRegion>(state->getSVal(BE,
1696 C.getLocationContext()).getAsRegion());
1697
1698 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
1699 E = R->referenced_vars_end();
1700
1701 if (I == E)
1702 return;
1703
1704 SmallVector<const MemRegion*, 10> Regions;
1705 const LocationContext *LC = C.getLocationContext();
1706 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
1707
1708 for ( ; I != E; ++I) {
Ted Kremeneke3ce2c12012-12-06 07:17:20 +00001709 const VarRegion *VR = I.getCapturedRegion();
Anna Zaksf5aa3f52012-03-22 00:57:20 +00001710 if (VR->getSuperRegion() == R) {
1711 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
1712 }
1713 Regions.push_back(VR);
1714 }
1715
1716 state =
1717 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
1718 Regions.data() + Regions.size()).getState();
1719 C.addTransition(state);
1720}
1721
Anna Zaks14345182012-05-18 01:16:10 +00001722bool MallocChecker::isReleased(SymbolRef Sym, CheckerContext &C) const {
Anna Zaks91c2a112012-02-08 23:16:56 +00001723 assert(Sym);
1724 const RefState *RS = C.getState()->get<RegionState>(Sym);
Anna Zaks14345182012-05-18 01:16:10 +00001725 return (RS && RS->isReleased());
1726}
1727
1728bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
1729 const Stmt *S) const {
Anna Zaks91c2a112012-02-08 23:16:56 +00001730
Anton Yartsevbb369952013-03-13 14:39:10 +00001731 if (isReleased(Sym, C)) {
1732 ReportUseAfterFree(C, S->getSourceRange(), Sym);
1733 return true;
Anna Zaks91c2a112012-02-08 23:16:56 +00001734 }
Anton Yartsevbb369952013-03-13 14:39:10 +00001735
Anna Zaks91c2a112012-02-08 23:16:56 +00001736 return false;
1737}
1738
Zhongxing Xuc8023782010-03-10 04:58:55 +00001739// Check if the location is a freed symbolic region.
Anna Zaks390909c2011-10-06 00:43:15 +00001740void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
1741 CheckerContext &C) const {
Zhongxing Xuc8023782010-03-10 04:58:55 +00001742 SymbolRef Sym = l.getLocSymbolInBase();
Anna Zaks91c2a112012-02-08 23:16:56 +00001743 if (Sym)
Anna Zaks14345182012-05-18 01:16:10 +00001744 checkUseAfterFree(Sym, C, S);
Zhongxing Xuc8023782010-03-10 04:58:55 +00001745}
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001746
Anna Zaks4fb54872012-02-11 21:02:35 +00001747// If a symbolic region is assumed to NULL (or another constant), stop tracking
1748// it - assuming that allocation failed on this path.
1749ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
1750 SVal Cond,
1751 bool Assumption) const {
1752 RegionStateTy RS = state->get<RegionState>();
Anna Zaks4fb54872012-02-11 21:02:35 +00001753 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
Ted Kremenek47cbd0f2012-09-07 22:31:01 +00001754 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Roseec8d4202012-11-01 00:18:27 +00001755 ConstraintManager &CMgr = state->getConstraintManager();
1756 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
1757 if (AllocFailed.isConstrainedTrue())
Anna Zaks4fb54872012-02-11 21:02:35 +00001758 state = state->remove<RegionState>(I.getKey());
1759 }
1760
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001761 // Realloc returns 0 when reallocation fails, which means that we should
1762 // restore the state of the pointer being reallocated.
Jordan Rose166d5022012-11-02 01:54:06 +00001763 ReallocPairsTy RP = state->get<ReallocPairs>();
1764 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Ted Kremenek47cbd0f2012-09-07 22:31:01 +00001765 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Roseec8d4202012-11-01 00:18:27 +00001766 ConstraintManager &CMgr = state->getConstraintManager();
1767 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
Jordan Rose79a29eb2012-11-01 00:25:15 +00001768 if (!AllocFailed.isConstrainedTrue())
Anna Zaks9dc298b2012-09-12 22:57:34 +00001769 continue;
Jordan Roseec8d4202012-11-01 00:18:27 +00001770
Anna Zaks9dc298b2012-09-12 22:57:34 +00001771 SymbolRef ReallocSym = I.getData().ReallocatedSym;
1772 if (const RefState *RS = state->get<RegionState>(ReallocSym)) {
1773 if (RS->isReleased()) {
1774 if (I.getData().Kind == RPToBeFreedAfterFailure)
Anna Zaks40add292012-02-15 00:11:25 +00001775 state = state->set<RegionState>(ReallocSym,
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001776 RefState::getAllocated(RS->getAllocationFamily(), RS->getStmt()));
Anna Zaks9dc298b2012-09-12 22:57:34 +00001777 else if (I.getData().Kind == RPDoNotTrackAfterFailure)
1778 state = state->remove<RegionState>(ReallocSym);
1779 else
1780 assert(I.getData().Kind == RPIsFreeOnFailure);
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001781 }
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001782 }
Anna Zaks9dc298b2012-09-12 22:57:34 +00001783 state = state->remove<ReallocPairs>(I.getKey());
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001784 }
1785
Anna Zaks4fb54872012-02-11 21:02:35 +00001786 return state;
1787}
1788
Jordan Rose9fe09f32013-03-09 00:59:10 +00001789bool MallocChecker::doesNotFreeMemOrInteresting(const CallEvent *Call,
1790 ProgramStateRef State) const {
Jordan Rose85d7e012012-07-02 19:27:51 +00001791 assert(Call);
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001792
1793 // For now, assume that any C++ call can free memory.
1794 // TODO: If we want to be more optimistic here, we'll need to make sure that
1795 // regions escape to C++ containers. They seem to do that even now, but for
1796 // mysterious reasons.
Jordan Rosecde8cdb2012-07-02 19:27:56 +00001797 if (!(isa<FunctionCall>(Call) || isa<ObjCMethodCall>(Call)))
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001798 return false;
1799
Jordan Rose740d4902012-07-02 19:27:35 +00001800 // Check Objective-C messages by selector name.
Jordan Rosecde8cdb2012-07-02 19:27:56 +00001801 if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) {
Jordan Rose85d7e012012-07-02 19:27:51 +00001802 // If it's not a framework call, or if it takes a callback, assume it
1803 // can free memory.
1804 if (!Call->isInSystemHeader() || Call->hasNonZeroCallbackArg())
Anna Zaks07d39a42012-02-28 01:54:22 +00001805 return false;
1806
Jordan Rose9fe09f32013-03-09 00:59:10 +00001807 // If it's a method we know about, handle it explicitly post-call.
1808 // This should happen before the "freeWhenDone" check below.
1809 if (isKnownDeallocObjCMethodName(*Msg))
1810 return true;
Anna Zaks52a04812012-06-20 23:35:57 +00001811
Jordan Rose9fe09f32013-03-09 00:59:10 +00001812 // If there's a "freeWhenDone" parameter, but the method isn't one we know
1813 // about, we can't be sure that the object will use free() to deallocate the
1814 // memory, so we can't model it explicitly. The best we can do is use it to
1815 // decide whether the pointer escapes.
1816 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(*Msg))
1817 return !*FreeWhenDone;
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001818
Jordan Rose9fe09f32013-03-09 00:59:10 +00001819 // If the first selector piece ends with "NoCopy", and there is no
1820 // "freeWhenDone" parameter set to zero, we know ownership is being
1821 // transferred. Again, though, we can't be sure that the object will use
1822 // free() to deallocate the memory, so we can't model it explicitly.
1823 StringRef FirstSlot = Msg->getSelector().getNameForSlot(0);
Jordan Rose740d4902012-07-02 19:27:35 +00001824 if (FirstSlot.endswith("NoCopy"))
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001825 return false;
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001826
Anna Zaks5f757682012-06-19 05:10:32 +00001827 // If the first selector starts with addPointer, insertPointer,
1828 // or replacePointer, assume we are dealing with NSPointerArray or similar.
1829 // This is similar to C++ containers (vector); we still might want to check
Jordan Rose740d4902012-07-02 19:27:35 +00001830 // that the pointers get freed by following the container itself.
1831 if (FirstSlot.startswith("addPointer") ||
1832 FirstSlot.startswith("insertPointer") ||
1833 FirstSlot.startswith("replacePointer")) {
Anna Zaks5f757682012-06-19 05:10:32 +00001834 return false;
1835 }
1836
Jordan Rose740d4902012-07-02 19:27:35 +00001837 // Otherwise, assume that the method does not free memory.
1838 // Most framework methods do not free memory.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001839 return true;
Anna Zaks66c40402012-02-14 21:55:24 +00001840 }
1841
Jordan Rose740d4902012-07-02 19:27:35 +00001842 // At this point the only thing left to handle is straight function calls.
1843 const FunctionDecl *FD = cast<FunctionCall>(Call)->getDecl();
1844 if (!FD)
1845 return false;
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001846
Jordan Rose740d4902012-07-02 19:27:35 +00001847 ASTContext &ASTC = State->getStateManager().getContext();
1848
1849 // If it's one of the allocation functions we can reason about, we model
1850 // its behavior explicitly.
1851 if (isMemFunction(FD, ASTC))
1852 return true;
1853
1854 // If it's not a system call, assume it frees memory.
1855 if (!Call->isInSystemHeader())
1856 return false;
1857
1858 // White list the system functions whose arguments escape.
1859 const IdentifierInfo *II = FD->getIdentifier();
1860 if (!II)
1861 return false;
1862 StringRef FName = II->getName();
1863
Jordan Rose740d4902012-07-02 19:27:35 +00001864 // White list the 'XXXNoCopy' CoreFoundation functions.
Jordan Rose85d7e012012-07-02 19:27:51 +00001865 // We specifically check these before
Jordan Rose740d4902012-07-02 19:27:35 +00001866 if (FName.endswith("NoCopy")) {
1867 // Look for the deallocator argument. We know that the memory ownership
1868 // is not transferred only if the deallocator argument is
1869 // 'kCFAllocatorNull'.
1870 for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
1871 const Expr *ArgE = Call->getArgExpr(i)->IgnoreParenCasts();
1872 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
1873 StringRef DeallocatorName = DE->getFoundDecl()->getName();
1874 if (DeallocatorName == "kCFAllocatorNull")
1875 return true;
1876 }
1877 }
1878 return false;
1879 }
1880
Jordan Rose740d4902012-07-02 19:27:35 +00001881 // Associating streams with malloced buffers. The pointer can escape if
Jordan Rose85d7e012012-07-02 19:27:51 +00001882 // 'closefn' is specified (and if that function does free memory),
1883 // but it will not if closefn is not specified.
Jordan Rose740d4902012-07-02 19:27:35 +00001884 // Currently, we do not inspect the 'closefn' function (PR12101).
1885 if (FName == "funopen")
Jordan Rose85d7e012012-07-02 19:27:51 +00001886 if (Call->getNumArgs() >= 4 && Call->getArgSVal(4).isConstant(0))
1887 return true;
Jordan Rose740d4902012-07-02 19:27:35 +00001888
1889 // Do not warn on pointers passed to 'setbuf' when used with std streams,
1890 // these leaks might be intentional when setting the buffer for stdio.
1891 // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
1892 if (FName == "setbuf" || FName =="setbuffer" ||
1893 FName == "setlinebuf" || FName == "setvbuf") {
1894 if (Call->getNumArgs() >= 1) {
1895 const Expr *ArgE = Call->getArgExpr(0)->IgnoreParenCasts();
1896 if (const DeclRefExpr *ArgDRE = dyn_cast<DeclRefExpr>(ArgE))
1897 if (const VarDecl *D = dyn_cast<VarDecl>(ArgDRE->getDecl()))
1898 if (D->getCanonicalDecl()->getName().find("std") != StringRef::npos)
1899 return false;
1900 }
1901 }
1902
1903 // A bunch of other functions which either take ownership of a pointer or
1904 // wrap the result up in a struct or object, meaning it can be freed later.
1905 // (See RetainCountChecker.) Not all the parameters here are invalidated,
1906 // but the Malloc checker cannot differentiate between them. The right way
1907 // of doing this would be to implement a pointer escapes callback.
1908 if (FName == "CGBitmapContextCreate" ||
1909 FName == "CGBitmapContextCreateWithData" ||
1910 FName == "CVPixelBufferCreateWithBytes" ||
1911 FName == "CVPixelBufferCreateWithPlanarBytes" ||
1912 FName == "OSAtomicEnqueue") {
1913 return false;
1914 }
1915
Jordan Rose85d7e012012-07-02 19:27:51 +00001916 // Handle cases where we know a buffer's /address/ can escape.
1917 // Note that the above checks handle some special cases where we know that
1918 // even though the address escapes, it's still our responsibility to free the
1919 // buffer.
1920 if (Call->argumentsMayEscape())
Jordan Rose740d4902012-07-02 19:27:35 +00001921 return false;
1922
1923 // Otherwise, assume that the function does not free memory.
1924 // Most system calls do not free the memory.
1925 return true;
Anna Zaks66c40402012-02-14 21:55:24 +00001926}
1927
Anna Zaks41988f32013-03-28 23:15:29 +00001928static bool retTrue(const RefState *RS) {
1929 return true;
1930}
1931
1932static bool checkIfNewOrNewArrayFamily(const RefState *RS) {
1933 return (RS->getAllocationFamily() == AF_CXXNewArray ||
1934 RS->getAllocationFamily() == AF_CXXNew);
1935}
1936
Anna Zaksbf53dfa2012-12-20 00:38:25 +00001937ProgramStateRef MallocChecker::checkPointerEscape(ProgramStateRef State,
1938 const InvalidatedSymbols &Escaped,
Anna Zaks233e26a2013-02-07 23:05:43 +00001939 const CallEvent *Call,
1940 PointerEscapeKind Kind) const {
Anna Zaks41988f32013-03-28 23:15:29 +00001941 return checkPointerEscapeAux(State, Escaped, Call, Kind, &retTrue);
1942}
1943
1944ProgramStateRef MallocChecker::checkConstPointerEscape(ProgramStateRef State,
1945 const InvalidatedSymbols &Escaped,
1946 const CallEvent *Call,
1947 PointerEscapeKind Kind) const {
1948 return checkPointerEscapeAux(State, Escaped, Call, Kind,
1949 &checkIfNewOrNewArrayFamily);
1950}
1951
1952ProgramStateRef MallocChecker::checkPointerEscapeAux(ProgramStateRef State,
1953 const InvalidatedSymbols &Escaped,
1954 const CallEvent *Call,
1955 PointerEscapeKind Kind,
1956 bool(*CheckRefState)(const RefState*)) const {
Jordan Rose9fe09f32013-03-09 00:59:10 +00001957 // If we know that the call does not free memory, or we want to process the
1958 // call later, keep tracking the top level arguments.
Anna Zaks233e26a2013-02-07 23:05:43 +00001959 if ((Kind == PSK_DirectEscapeOnCall ||
1960 Kind == PSK_IndirectEscapeOnCall) &&
Jordan Rose9fe09f32013-03-09 00:59:10 +00001961 doesNotFreeMemOrInteresting(Call, State)) {
Anna Zaks66c40402012-02-14 21:55:24 +00001962 return State;
Anna Zaks233e26a2013-02-07 23:05:43 +00001963 }
Anna Zaks66c40402012-02-14 21:55:24 +00001964
Anna Zaksbf53dfa2012-12-20 00:38:25 +00001965 for (InvalidatedSymbols::const_iterator I = Escaped.begin(),
Anna Zaks41988f32013-03-28 23:15:29 +00001966 E = Escaped.end();
1967 I != E; ++I) {
Anna Zaks4fb54872012-02-11 21:02:35 +00001968 SymbolRef sym = *I;
Anna Zaksbf53dfa2012-12-20 00:38:25 +00001969
Anna Zaks5b7aa342012-06-22 02:04:31 +00001970 if (const RefState *RS = State->get<RegionState>(sym)) {
Anna Zaks41988f32013-03-28 23:15:29 +00001971 if (RS->isAllocated() && CheckRefState(RS))
Anna Zaks431e35c2012-08-09 00:42:24 +00001972 State = State->remove<RegionState>(sym);
Anna Zaks5b7aa342012-06-22 02:04:31 +00001973 }
Anna Zaks4fb54872012-02-11 21:02:35 +00001974 }
Anna Zaks66c40402012-02-14 21:55:24 +00001975 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001976}
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001977
Jordy Rose393f98b2012-03-18 07:43:35 +00001978static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
1979 ProgramStateRef prevState) {
Jordan Rose166d5022012-11-02 01:54:06 +00001980 ReallocPairsTy currMap = currState->get<ReallocPairs>();
1981 ReallocPairsTy prevMap = prevState->get<ReallocPairs>();
Jordy Rose393f98b2012-03-18 07:43:35 +00001982
Jordan Rose166d5022012-11-02 01:54:06 +00001983 for (ReallocPairsTy::iterator I = prevMap.begin(), E = prevMap.end();
Jordy Rose393f98b2012-03-18 07:43:35 +00001984 I != E; ++I) {
1985 SymbolRef sym = I.getKey();
1986 if (!currMap.lookup(sym))
1987 return sym;
1988 }
1989
1990 return NULL;
1991}
1992
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001993PathDiagnosticPiece *
1994MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
1995 const ExplodedNode *PrevN,
1996 BugReporterContext &BRC,
1997 BugReport &BR) {
Jordy Rose393f98b2012-03-18 07:43:35 +00001998 ProgramStateRef state = N->getState();
1999 ProgramStateRef statePrev = PrevN->getState();
2000
2001 const RefState *RS = state->get<RegionState>(Sym);
2002 const RefState *RSPrev = statePrev->get<RegionState>(Sym);
Anna Zaksede875b2012-08-03 18:30:18 +00002003 if (!RS)
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002004 return 0;
2005
Anna Zaksfe571602012-02-16 22:26:07 +00002006 const Stmt *S = 0;
2007 const char *Msg = 0;
Anna Zaks56a938f2012-03-16 23:24:20 +00002008 StackHintGeneratorForSymbol *StackHint = 0;
Anna Zaksfe571602012-02-16 22:26:07 +00002009
2010 // Retrieve the associated statement.
2011 ProgramPoint ProgLoc = N->getLocation();
David Blaikie7a95de62013-02-21 22:23:56 +00002012 if (Optional<StmtPoint> SP = ProgLoc.getAs<StmtPoint>()) {
Jordan Rose852aa0d2012-07-10 22:07:52 +00002013 S = SP->getStmt();
David Blaikie7a95de62013-02-21 22:23:56 +00002014 } else if (Optional<CallExitEnd> Exit = ProgLoc.getAs<CallExitEnd>()) {
Jordan Rose852aa0d2012-07-10 22:07:52 +00002015 S = Exit->getCalleeContext()->getCallSite();
David Blaikie7a95de62013-02-21 22:23:56 +00002016 } else if (Optional<BlockEdge> Edge = ProgLoc.getAs<BlockEdge>()) {
Ted Kremeneka4a17592013-01-04 19:04:36 +00002017 // If an assumption was made on a branch, it should be caught
2018 // here by looking at the state transition.
2019 S = Edge->getSrc()->getTerminator();
Anna Zaksfe571602012-02-16 22:26:07 +00002020 }
Ted Kremeneka4a17592013-01-04 19:04:36 +00002021
Anna Zaksfe571602012-02-16 22:26:07 +00002022 if (!S)
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002023 return 0;
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002024
Jordan Rose28038f32012-07-10 22:07:42 +00002025 // FIXME: We will eventually need to handle non-statement-based events
2026 // (__attribute__((cleanup))).
2027
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002028 // Find out if this is an interesting point and what is the kind.
Anna Zaksfe571602012-02-16 22:26:07 +00002029 if (Mode == Normal) {
Anna Zaks368a0d52012-03-15 21:13:02 +00002030 if (isAllocated(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00002031 Msg = "Memory is allocated";
Anna Zaksfbd58742012-03-16 23:44:28 +00002032 StackHint = new StackHintGeneratorForSymbol(Sym,
2033 "Returned allocated memory");
Anna Zaks368a0d52012-03-15 21:13:02 +00002034 } else if (isReleased(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00002035 Msg = "Memory is released";
Anna Zaksfbd58742012-03-16 23:44:28 +00002036 StackHint = new StackHintGeneratorForSymbol(Sym,
2037 "Returned released memory");
Anna Zaks5b7aa342012-06-22 02:04:31 +00002038 } else if (isRelinquished(RS, RSPrev, S)) {
2039 Msg = "Memory ownership is transfered";
2040 StackHint = new StackHintGeneratorForSymbol(Sym, "");
Anna Zaks368a0d52012-03-15 21:13:02 +00002041 } else if (isReallocFailedCheck(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00002042 Mode = ReallocationFailed;
2043 Msg = "Reallocation failed";
Anna Zaks56a938f2012-03-16 23:24:20 +00002044 StackHint = new StackHintGeneratorForReallocationFailed(Sym,
Anna Zaksfbd58742012-03-16 23:44:28 +00002045 "Reallocation failed");
Jordy Rose393f98b2012-03-18 07:43:35 +00002046
Jordy Roseb000fb52012-03-24 03:15:09 +00002047 if (SymbolRef sym = findFailedReallocSymbol(state, statePrev)) {
2048 // Is it possible to fail two reallocs WITHOUT testing in between?
2049 assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
2050 "We only support one failed realloc at a time.");
Jordy Rose393f98b2012-03-18 07:43:35 +00002051 BR.markInteresting(sym);
Jordy Roseb000fb52012-03-24 03:15:09 +00002052 FailedReallocSymbol = sym;
2053 }
Anna Zaksfe571602012-02-16 22:26:07 +00002054 }
2055
2056 // We are in a special mode if a reallocation failed later in the path.
2057 } else if (Mode == ReallocationFailed) {
Jordy Roseb000fb52012-03-24 03:15:09 +00002058 assert(FailedReallocSymbol && "No symbol to look for.");
Anna Zaksfe571602012-02-16 22:26:07 +00002059
Jordy Roseb000fb52012-03-24 03:15:09 +00002060 // Is this is the first appearance of the reallocated symbol?
2061 if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
Jordy Roseb000fb52012-03-24 03:15:09 +00002062 // We're at the reallocation point.
2063 Msg = "Attempt to reallocate memory";
2064 StackHint = new StackHintGeneratorForSymbol(Sym,
2065 "Returned reallocated memory");
2066 FailedReallocSymbol = NULL;
2067 Mode = Normal;
2068 }
Anna Zaksfe571602012-02-16 22:26:07 +00002069 }
2070
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002071 if (!Msg)
2072 return 0;
Anna Zaks56a938f2012-03-16 23:24:20 +00002073 assert(StackHint);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002074
2075 // Generate the extra diagnostic.
Anna Zaksfe571602012-02-16 22:26:07 +00002076 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002077 N->getLocationContext());
Anna Zaks56a938f2012-03-16 23:24:20 +00002078 return new PathDiagnosticEventPiece(Pos, Msg, true, StackHint);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002079}
2080
Anna Zaks93c5a242012-05-02 00:05:20 +00002081void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State,
2082 const char *NL, const char *Sep) const {
2083
2084 RegionStateTy RS = State->get<RegionState>();
2085
Ted Kremenekc37fad62013-01-03 01:30:12 +00002086 if (!RS.isEmpty()) {
2087 Out << Sep << "MallocChecker:" << NL;
2088 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
2089 I.getKey()->dumpToStream(Out);
2090 Out << " : ";
2091 I.getData().dump(Out);
2092 Out << NL;
2093 }
2094 }
Anna Zaks93c5a242012-05-02 00:05:20 +00002095}
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002096
Anna Zaks231361a2012-02-08 23:16:52 +00002097#define REGISTER_CHECKER(name) \
2098void ento::register##name(CheckerManager &mgr) {\
Anna Zaksf0dfc9c2012-02-17 22:35:31 +00002099 registerCStringCheckerBasic(mgr); \
Anna Zaks231361a2012-02-08 23:16:52 +00002100 mgr.registerChecker<MallocChecker>()->Filter.C##name = true;\
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00002101}
Anna Zaks231361a2012-02-08 23:16:52 +00002102
2103REGISTER_CHECKER(MallocPessimistic)
2104REGISTER_CHECKER(MallocOptimistic)
Anton Yartsev2de19ed2013-03-25 01:35:45 +00002105REGISTER_CHECKER(NewDeleteChecker)
Anton Yartsev849c7bf2013-03-28 17:05:19 +00002106REGISTER_CHECKER(MismatchedDeallocatorChecker)