blob: 57666499c4e814460925fdc5683f5c1ed3c0cd82 [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 Yartsev849c7bf2013-03-28 17:05:19 +0000152 mutable OwningPtr<BugType> BT_BadDealloc;
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.
201 AllocationFamily getAllocationFamily(CheckerContext &C, const Expr *E) const;
202
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
Ted Kremenek9c378f72011-08-12 23:37:29 +0000285 static bool SummarizeValue(raw_ostream &os, SVal V);
286 static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000287 void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
288 const Expr *DeallocExpr) const;
Anton Yartsevbb369952013-03-13 14:39:10 +0000289 void ReportBadDealloc(CheckerContext &C, SourceRange Range,
290 const Expr *DeallocExpr, const RefState *RS) const;
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000291 void ReportOffsetFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
292 const Expr *DeallocExpr,
293 const Expr *AllocExpr = 0) const;
Anton Yartsevbb369952013-03-13 14:39:10 +0000294 void ReportUseAfterFree(CheckerContext &C, SourceRange Range,
295 SymbolRef Sym) const;
296 void ReportDoubleFree(CheckerContext &C, SourceRange Range, bool Released,
Anton Yartsev3258d4b2013-03-13 17:07:32 +0000297 SymbolRef Sym, SymbolRef PrevSym) const;
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000298
Anna Zaksca8e36e2012-02-23 21:38:21 +0000299 /// Find the location of the allocation for Sym on the path leading to the
300 /// exploded node N.
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000301 LeakInfo getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
302 CheckerContext &C) const;
Anna Zaksca8e36e2012-02-23 21:38:21 +0000303
Anna Zaksda046772012-02-11 21:02:40 +0000304 void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
305
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000306 /// The bug visitor which allows us to print extra diagnostics along the
307 /// BugReport path. For example, showing the allocation site of the leaked
308 /// region.
Jordy Rose01153492012-03-24 02:45:35 +0000309 class MallocBugVisitor : public BugReporterVisitorImpl<MallocBugVisitor> {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000310 protected:
Anna Zaksfe571602012-02-16 22:26:07 +0000311 enum NotificationMode {
312 Normal,
Anna Zaksfe571602012-02-16 22:26:07 +0000313 ReallocationFailed
314 };
315
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000316 // The allocated region symbol tracked by the main analysis.
317 SymbolRef Sym;
318
Anna Zaks88feba02012-05-10 01:37:40 +0000319 // The mode we are in, i.e. what kind of diagnostics will be emitted.
320 NotificationMode Mode;
Jordy Roseb000fb52012-03-24 03:15:09 +0000321
Anna Zaks88feba02012-05-10 01:37:40 +0000322 // A symbol from when the primary region should have been reallocated.
323 SymbolRef FailedReallocSymbol;
Jordy Roseb000fb52012-03-24 03:15:09 +0000324
Anna Zaks88feba02012-05-10 01:37:40 +0000325 bool IsLeak;
326
327 public:
328 MallocBugVisitor(SymbolRef S, bool isLeak = false)
329 : Sym(S), Mode(Normal), FailedReallocSymbol(0), IsLeak(isLeak) {}
Jordy Roseb000fb52012-03-24 03:15:09 +0000330
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000331 virtual ~MallocBugVisitor() {}
332
333 void Profile(llvm::FoldingSetNodeID &ID) const {
334 static int X = 0;
335 ID.AddPointer(&X);
336 ID.AddPointer(Sym);
337 }
338
Anna Zaksfe571602012-02-16 22:26:07 +0000339 inline bool isAllocated(const RefState *S, const RefState *SPrev,
340 const Stmt *Stmt) {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000341 // Did not track -> allocated. Other state (released) -> allocated.
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000342 return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXNewExpr>(Stmt)) &&
Anna Zaksfe571602012-02-16 22:26:07 +0000343 (S && S->isAllocated()) && (!SPrev || !SPrev->isAllocated()));
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000344 }
345
Anna Zaksfe571602012-02-16 22:26:07 +0000346 inline bool isReleased(const RefState *S, const RefState *SPrev,
347 const Stmt *Stmt) {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000348 // Did not track -> released. Other state (allocated) -> released.
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000349 return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXDeleteExpr>(Stmt)) &&
Anna Zaksfe571602012-02-16 22:26:07 +0000350 (S && S->isReleased()) && (!SPrev || !SPrev->isReleased()));
351 }
352
Anna Zaks5b7aa342012-06-22 02:04:31 +0000353 inline bool isRelinquished(const RefState *S, const RefState *SPrev,
354 const Stmt *Stmt) {
355 // Did not track -> relinquished. Other state (allocated) -> relinquished.
356 return (Stmt && (isa<CallExpr>(Stmt) || isa<ObjCMessageExpr>(Stmt) ||
357 isa<ObjCPropertyRefExpr>(Stmt)) &&
358 (S && S->isRelinquished()) &&
359 (!SPrev || !SPrev->isRelinquished()));
360 }
361
Anna Zaksfe571602012-02-16 22:26:07 +0000362 inline bool isReallocFailedCheck(const RefState *S, const RefState *SPrev,
363 const Stmt *Stmt) {
364 // If the expression is not a call, and the state change is
365 // released -> allocated, it must be the realloc return value
366 // check. If we have to handle more cases here, it might be cleaner just
367 // to track this extra bit in the state itself.
368 return ((!Stmt || !isa<CallExpr>(Stmt)) &&
369 (S && S->isAllocated()) && (SPrev && !SPrev->isAllocated()));
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000370 }
371
372 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
373 const ExplodedNode *PrevN,
374 BugReporterContext &BRC,
375 BugReport &BR);
Anna Zaks88feba02012-05-10 01:37:40 +0000376
377 PathDiagnosticPiece* getEndPath(BugReporterContext &BRC,
378 const ExplodedNode *EndPathNode,
379 BugReport &BR) {
380 if (!IsLeak)
381 return 0;
382
383 PathDiagnosticLocation L =
384 PathDiagnosticLocation::createEndOfPath(EndPathNode,
385 BRC.getSourceManager());
386 // Do not add the statement itself as a range in case of leak.
387 return new PathDiagnosticEventPiece(L, BR.getDescription(), false);
388 }
389
Anna Zaks56a938f2012-03-16 23:24:20 +0000390 private:
391 class StackHintGeneratorForReallocationFailed
392 : public StackHintGeneratorForSymbol {
393 public:
394 StackHintGeneratorForReallocationFailed(SymbolRef S, StringRef M)
395 : StackHintGeneratorForSymbol(S, M) {}
396
397 virtual std::string getMessageForArg(const Expr *ArgE, unsigned ArgIndex) {
Jordan Rose615a0922012-09-22 01:24:42 +0000398 // Printed parameters start at 1, not 0.
399 ++ArgIndex;
400
Anna Zaks56a938f2012-03-16 23:24:20 +0000401 SmallString<200> buf;
402 llvm::raw_svector_ostream os(buf);
403
Jordan Rose615a0922012-09-22 01:24:42 +0000404 os << "Reallocation of " << ArgIndex << llvm::getOrdinalSuffix(ArgIndex)
405 << " parameter failed";
Anna Zaks56a938f2012-03-16 23:24:20 +0000406
407 return os.str();
408 }
409
410 virtual std::string getMessageForReturn(const CallExpr *CallExpr) {
Anna Zaksfbd58742012-03-16 23:44:28 +0000411 return "Reallocation of returned value failed";
Anna Zaks56a938f2012-03-16 23:24:20 +0000412 }
413 };
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000414 };
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000415};
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000416} // end anonymous namespace
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000417
Jordan Rose166d5022012-11-02 01:54:06 +0000418REGISTER_MAP_WITH_PROGRAMSTATE(RegionState, SymbolRef, RefState)
419REGISTER_MAP_WITH_PROGRAMSTATE(ReallocPairs, SymbolRef, ReallocPair)
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000420
Anna Zaks4141e4d2012-11-13 03:18:01 +0000421// A map from the freed symbol to the symbol representing the return value of
422// the free function.
423REGISTER_MAP_WITH_PROGRAMSTATE(FreeReturnValue, SymbolRef, SymbolRef)
424
Anna Zaks4fb54872012-02-11 21:02:35 +0000425namespace {
426class StopTrackingCallback : public SymbolVisitor {
427 ProgramStateRef state;
428public:
429 StopTrackingCallback(ProgramStateRef st) : state(st) {}
430 ProgramStateRef getState() const { return state; }
431
432 bool VisitSymbol(SymbolRef sym) {
433 state = state->remove<RegionState>(sym);
434 return true;
435 }
436};
437} // end anonymous namespace
438
Anna Zaks66c40402012-02-14 21:55:24 +0000439void MallocChecker::initIdentifierInfo(ASTContext &Ctx) const {
Anna Zaksa38cb2c2012-05-18 22:47:40 +0000440 if (II_malloc)
441 return;
442 II_malloc = &Ctx.Idents.get("malloc");
443 II_free = &Ctx.Idents.get("free");
444 II_realloc = &Ctx.Idents.get("realloc");
445 II_reallocf = &Ctx.Idents.get("reallocf");
446 II_calloc = &Ctx.Idents.get("calloc");
447 II_valloc = &Ctx.Idents.get("valloc");
448 II_strdup = &Ctx.Idents.get("strdup");
449 II_strndup = &Ctx.Idents.get("strndup");
Anna Zaksb319e022012-02-08 20:13:28 +0000450}
451
Anna Zaks66c40402012-02-14 21:55:24 +0000452bool MallocChecker::isMemFunction(const FunctionDecl *FD, ASTContext &C) const {
Anna Zaks14345182012-05-18 01:16:10 +0000453 if (isFreeFunction(FD, C))
454 return true;
455
456 if (isAllocationFunction(FD, C))
457 return true;
458
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000459 if (isStandardNewDelete(FD, C))
460 return true;
461
Anna Zaks14345182012-05-18 01:16:10 +0000462 return false;
463}
464
465bool MallocChecker::isAllocationFunction(const FunctionDecl *FD,
466 ASTContext &C) const {
Anna Zaks1d6cc6a2012-02-15 02:12:00 +0000467 if (!FD)
468 return false;
Anna Zaks14345182012-05-18 01:16:10 +0000469
Jordan Rose5ef6e942012-07-10 23:13:01 +0000470 if (FD->getKind() == Decl::Function) {
471 IdentifierInfo *FunI = FD->getIdentifier();
472 initIdentifierInfo(C);
Anna Zaks66c40402012-02-14 21:55:24 +0000473
Jordan Rose5ef6e942012-07-10 23:13:01 +0000474 if (FunI == II_malloc || FunI == II_realloc ||
475 FunI == II_reallocf || FunI == II_calloc || FunI == II_valloc ||
476 FunI == II_strdup || FunI == II_strndup)
477 return true;
478 }
Anna Zaks66c40402012-02-14 21:55:24 +0000479
Anna Zaks14345182012-05-18 01:16:10 +0000480 if (Filter.CMallocOptimistic && FD->hasAttrs())
481 for (specific_attr_iterator<OwnershipAttr>
482 i = FD->specific_attr_begin<OwnershipAttr>(),
483 e = FD->specific_attr_end<OwnershipAttr>();
484 i != e; ++i)
485 if ((*i)->getOwnKind() == OwnershipAttr::Returns)
486 return true;
487 return false;
488}
489
490bool MallocChecker::isFreeFunction(const FunctionDecl *FD, ASTContext &C) const {
491 if (!FD)
492 return false;
493
Jordan Rose5ef6e942012-07-10 23:13:01 +0000494 if (FD->getKind() == Decl::Function) {
495 IdentifierInfo *FunI = FD->getIdentifier();
496 initIdentifierInfo(C);
Anna Zaks14345182012-05-18 01:16:10 +0000497
Jordan Rose5ef6e942012-07-10 23:13:01 +0000498 if (FunI == II_free || FunI == II_realloc || FunI == II_reallocf)
499 return true;
500 }
Anna Zaks66c40402012-02-14 21:55:24 +0000501
Anna Zaks14345182012-05-18 01:16:10 +0000502 if (Filter.CMallocOptimistic && FD->hasAttrs())
503 for (specific_attr_iterator<OwnershipAttr>
504 i = FD->specific_attr_begin<OwnershipAttr>(),
505 e = FD->specific_attr_end<OwnershipAttr>();
506 i != e; ++i)
507 if ((*i)->getOwnKind() == OwnershipAttr::Takes ||
508 (*i)->getOwnKind() == OwnershipAttr::Holds)
509 return true;
Anna Zaks66c40402012-02-14 21:55:24 +0000510 return false;
511}
512
Anton Yartsev69746282013-03-28 16:10:38 +0000513// Tells if the callee is one of the following:
514// 1) A global non-placement new/delete operator function.
515// 2) A global placement operator function with the single placement argument
516// of type std::nothrow_t.
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000517bool MallocChecker::isStandardNewDelete(const FunctionDecl *FD,
518 ASTContext &C) const {
519 if (!FD)
520 return false;
521
522 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
523 if (Kind != OO_New && Kind != OO_Array_New &&
524 Kind != OO_Delete && Kind != OO_Array_Delete)
525 return false;
526
Anton Yartsev69746282013-03-28 16:10:38 +0000527 // Skip all operator new/delete methods.
528 if (isa<CXXMethodDecl>(FD))
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000529 return false;
530
531 // Return true if tested operator is a standard placement nothrow operator.
532 if (FD->getNumParams() == 2) {
533 QualType T = FD->getParamDecl(1)->getType();
534 if (const IdentifierInfo *II = T.getBaseTypeIdentifier())
535 return II->getName().equals("nothrow_t");
536 }
537
538 // Skip placement operators.
539 if (FD->getNumParams() != 1 || FD->isVariadic())
540 return false;
541
542 // One of the standard new/new[]/delete/delete[] non-placement operators.
543 return true;
544}
545
Anna Zaksb319e022012-02-08 20:13:28 +0000546void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
Jordan Rosec20c7272012-09-20 01:55:32 +0000547 if (C.wasInlined)
548 return;
549
Anna Zaksb319e022012-02-08 20:13:28 +0000550 const FunctionDecl *FD = C.getCalleeDecl(CE);
551 if (!FD)
552 return;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000553
Anna Zaks87cb5be2012-02-22 19:24:52 +0000554 ProgramStateRef State = C.getState();
Anna Zaks55dd9562012-08-24 02:28:20 +0000555 bool ReleasedAllocatedMemory = false;
Jordan Rose5ef6e942012-07-10 23:13:01 +0000556
557 if (FD->getKind() == Decl::Function) {
558 initIdentifierInfo(C.getASTContext());
559 IdentifierInfo *FunI = FD->getIdentifier();
560
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000561 if (Filter.CMallocOptimistic || Filter.CMallocPessimistic ||
562 Filter.CMismatchedDeallocatorChecker) {
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000563 if (FunI == II_malloc || FunI == II_valloc) {
564 if (CE->getNumArgs() < 1)
565 return;
566 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
567 } else if (FunI == II_realloc) {
568 State = ReallocMem(C, CE, false);
569 } else if (FunI == II_reallocf) {
570 State = ReallocMem(C, CE, true);
571 } else if (FunI == II_calloc) {
572 State = CallocMem(C, CE);
573 } else if (FunI == II_free) {
574 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
575 } else if (FunI == II_strdup) {
576 State = MallocUpdateRefState(C, CE, State);
577 } else if (FunI == II_strndup) {
578 State = MallocUpdateRefState(C, CE, State);
579 }
580 }
581
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000582 if (Filter.CNewDeleteChecker || Filter.CMismatchedDeallocatorChecker) {
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000583 if (isStandardNewDelete(FD, C.getASTContext())) {
584 // Process direct calls to operator new/new[]/delete/delete[] functions
585 // as distinct from new/new[]/delete/delete[] expressions that are
586 // processed by the checkPostStmt callbacks for CXXNewExpr and
587 // CXXDeleteExpr.
588 OverloadedOperatorKind K = FD->getOverloadedOperator();
589 if (K == OO_New)
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000590 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
591 AF_CXXNew);
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000592 else if (K == OO_Array_New)
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000593 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
594 AF_CXXNewArray);
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000595 else if (K == OO_Delete || K == OO_Array_Delete)
596 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
597 else
598 llvm_unreachable("not a new/delete operator");
599 }
Jordan Rose5ef6e942012-07-10 23:13:01 +0000600 }
601 }
602
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000603 if (Filter.CMallocOptimistic || Filter.CMismatchedDeallocatorChecker) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000604 // Check all the attributes, if there are any.
605 // There can be multiple of these attributes.
606 if (FD->hasAttrs())
607 for (specific_attr_iterator<OwnershipAttr>
608 i = FD->specific_attr_begin<OwnershipAttr>(),
609 e = FD->specific_attr_end<OwnershipAttr>();
610 i != e; ++i) {
611 switch ((*i)->getOwnKind()) {
612 case OwnershipAttr::Returns:
613 State = MallocMemReturnsAttr(C, CE, *i);
614 break;
615 case OwnershipAttr::Takes:
616 case OwnershipAttr::Holds:
617 State = FreeMemAttr(C, CE, *i);
618 break;
619 }
620 }
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000621 }
Anna Zaks60a1fa42012-02-22 03:14:20 +0000622 C.addTransition(State);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000623}
624
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000625void MallocChecker::checkPostStmt(const CXXNewExpr *NE,
626 CheckerContext &C) const {
627
628 if (NE->getNumPlacementArgs())
629 for (CXXNewExpr::const_arg_iterator I = NE->placement_arg_begin(),
630 E = NE->placement_arg_end(); I != E; ++I)
631 if (SymbolRef Sym = C.getSVal(*I).getAsSymbol())
632 checkUseAfterFree(Sym, C, *I);
633
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000634 if (!Filter.CNewDeleteChecker && !Filter.CMismatchedDeallocatorChecker)
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000635 return;
636
637 if (!isStandardNewDelete(NE->getOperatorNew(), C.getASTContext()))
638 return;
639
640 ProgramStateRef State = C.getState();
641 // The return value from operator new is bound to a specified initialization
642 // value (if any) and we don't want to loose this value. So we call
643 // MallocUpdateRefState() instead of MallocMemAux() which breakes the
644 // existing binding.
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000645 State = MallocUpdateRefState(C, NE, State, NE->isArray() ? AF_CXXNewArray
646 : AF_CXXNew);
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000647 C.addTransition(State);
648}
649
650void MallocChecker::checkPreStmt(const CXXDeleteExpr *DE,
651 CheckerContext &C) const {
652
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000653 if (!Filter.CNewDeleteChecker)
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000654 if (SymbolRef Sym = C.getSVal(DE->getArgument()).getAsSymbol())
655 checkUseAfterFree(Sym, C, DE->getArgument());
656
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000657 if (!Filter.CNewDeleteChecker && !Filter.CMismatchedDeallocatorChecker)
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000658 return;
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000659
660 if (!isStandardNewDelete(DE->getOperatorDelete(), C.getASTContext()))
661 return;
662
663 ProgramStateRef State = C.getState();
664 bool ReleasedAllocated;
665 State = FreeMemAux(C, DE->getArgument(), DE, State,
666 /*Hold*/false, ReleasedAllocated);
667
668 C.addTransition(State);
669}
670
Jordan Rose9fe09f32013-03-09 00:59:10 +0000671static bool isKnownDeallocObjCMethodName(const ObjCMethodCall &Call) {
672 // If the first selector piece is one of the names below, assume that the
673 // object takes ownership of the memory, promising to eventually deallocate it
674 // with free().
675 // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
676 // (...unless a 'freeWhenDone' parameter is false, but that's checked later.)
677 StringRef FirstSlot = Call.getSelector().getNameForSlot(0);
678 if (FirstSlot == "dataWithBytesNoCopy" ||
679 FirstSlot == "initWithBytesNoCopy" ||
680 FirstSlot == "initWithCharactersNoCopy")
681 return true;
Anna Zaks5b7aa342012-06-22 02:04:31 +0000682
683 return false;
684}
685
Jordan Rose9fe09f32013-03-09 00:59:10 +0000686static Optional<bool> getFreeWhenDoneArg(const ObjCMethodCall &Call) {
687 Selector S = Call.getSelector();
688
689 // FIXME: We should not rely on fully-constrained symbols being folded.
690 for (unsigned i = 1; i < S.getNumArgs(); ++i)
691 if (S.getNameForSlot(i).equals("freeWhenDone"))
692 return !Call.getArgSVal(i).isZeroConstant();
693
694 return None;
695}
696
Anna Zaks4141e4d2012-11-13 03:18:01 +0000697void MallocChecker::checkPostObjCMessage(const ObjCMethodCall &Call,
698 CheckerContext &C) const {
Anna Zaksc2cca232012-12-11 00:17:53 +0000699 if (C.wasInlined)
700 return;
701
Jordan Rose9fe09f32013-03-09 00:59:10 +0000702 if (!isKnownDeallocObjCMethodName(Call))
703 return;
Anna Zaks4141e4d2012-11-13 03:18:01 +0000704
Jordan Rose9fe09f32013-03-09 00:59:10 +0000705 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(Call))
706 if (!*FreeWhenDone)
707 return;
708
709 bool ReleasedAllocatedMemory;
710 ProgramStateRef State = FreeMemAux(C, Call.getArgExpr(0),
711 Call.getOriginExpr(), C.getState(),
712 /*Hold=*/true, ReleasedAllocatedMemory,
713 /*RetNullOnFailure=*/true);
714
715 C.addTransition(State);
Anna Zaks5b7aa342012-06-22 02:04:31 +0000716}
717
Anna Zaks87cb5be2012-02-22 19:24:52 +0000718ProgramStateRef MallocChecker::MallocMemReturnsAttr(CheckerContext &C,
719 const CallExpr *CE,
720 const OwnershipAttr* Att) {
Sean Huntcf807c42010-08-18 23:23:40 +0000721 if (Att->getModule() != "malloc")
Anna Zaks87cb5be2012-02-22 19:24:52 +0000722 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000723
Sean Huntcf807c42010-08-18 23:23:40 +0000724 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000725 if (I != E) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000726 return MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), C.getState());
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000727 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000728 return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), C.getState());
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000729}
730
Anna Zaksb319e022012-02-08 20:13:28 +0000731ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000732 const CallExpr *CE,
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000733 SVal Size, SVal Init,
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000734 ProgramStateRef State,
735 AllocationFamily Family) {
Anna Zakse17fdb22012-06-07 03:57:32 +0000736
737 // Bind the return value to the symbolic value from the heap region.
738 // TODO: We could rewrite post visit to eval call; 'malloc' does not have
739 // side effects other than what we model here.
Ted Kremenek66c486f2012-08-22 06:26:15 +0000740 unsigned Count = C.blockCount();
Anna Zakse17fdb22012-06-07 03:57:32 +0000741 SValBuilder &svalBuilder = C.getSValBuilder();
742 const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
David Blaikie5251abe2013-02-20 05:52:05 +0000743 DefinedSVal RetVal = svalBuilder.getConjuredHeapSymbolVal(CE, LCtx, Count)
744 .castAs<DefinedSVal>();
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000745 State = State->BindExpr(CE, C.getLocationContext(), RetVal);
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000746
Anna Zaksb16ce452012-02-15 00:11:22 +0000747 // We expect the malloc functions to return a pointer.
David Blaikie5251abe2013-02-20 05:52:05 +0000748 if (!RetVal.getAs<Loc>())
Anna Zaksb16ce452012-02-15 00:11:22 +0000749 return 0;
750
Jordy Rose32f26562010-07-04 00:00:41 +0000751 // Fill the region with the initialization value.
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000752 State = State->bindDefault(RetVal, Init);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000753
Jordy Rose32f26562010-07-04 00:00:41 +0000754 // Set the region's extent equal to the Size parameter.
Anna Zakse9ef5622012-02-10 01:11:00 +0000755 const SymbolicRegion *R =
Anna Zakse17fdb22012-06-07 03:57:32 +0000756 dyn_cast_or_null<SymbolicRegion>(RetVal.getAsRegion());
Anna Zaks60a1fa42012-02-22 03:14:20 +0000757 if (!R)
Anna Zakse9ef5622012-02-10 01:11:00 +0000758 return 0;
David Blaikiedc84cd52013-02-20 22:23:23 +0000759 if (Optional<DefinedOrUnknownSVal> DefinedSize =
David Blaikie5251abe2013-02-20 05:52:05 +0000760 Size.getAs<DefinedOrUnknownSVal>()) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000761 SValBuilder &svalBuilder = C.getSValBuilder();
Anna Zaks60a1fa42012-02-22 03:14:20 +0000762 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
Anna Zaks60a1fa42012-02-22 03:14:20 +0000763 DefinedOrUnknownSVal extentMatchesSize =
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000764 svalBuilder.evalEQ(State, Extent, *DefinedSize);
Anna Zakse9ef5622012-02-10 01:11:00 +0000765
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000766 State = State->assume(extentMatchesSize, true);
767 assert(State);
Anna Zaks60a1fa42012-02-22 03:14:20 +0000768 }
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000769
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000770 return MallocUpdateRefState(C, CE, State, Family);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000771}
772
773ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C,
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000774 const Expr *E,
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000775 ProgramStateRef State,
776 AllocationFamily Family) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000777 // Get the return value.
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000778 SVal retVal = State->getSVal(E, C.getLocationContext());
Anna Zaks87cb5be2012-02-22 19:24:52 +0000779
780 // We expect the malloc functions to return a pointer.
David Blaikie5251abe2013-02-20 05:52:05 +0000781 if (!retVal.getAs<Loc>())
Anna Zaks87cb5be2012-02-22 19:24:52 +0000782 return 0;
783
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000784 SymbolRef Sym = retVal.getAsLocSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000785 assert(Sym);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000786
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000787 // Set the symbol's state to Allocated.
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000788 return State->set<RegionState>(Sym, RefState::getAllocated(Family, E));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000789}
790
Anna Zaks87cb5be2012-02-22 19:24:52 +0000791ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
792 const CallExpr *CE,
793 const OwnershipAttr* Att) const {
Sean Huntcf807c42010-08-18 23:23:40 +0000794 if (Att->getModule() != "malloc")
Anna Zaks87cb5be2012-02-22 19:24:52 +0000795 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000796
Anna Zaksb3d72752012-03-01 22:06:06 +0000797 ProgramStateRef State = C.getState();
Anna Zaks55dd9562012-08-24 02:28:20 +0000798 bool ReleasedAllocated = false;
Anna Zaksb3d72752012-03-01 22:06:06 +0000799
Sean Huntcf807c42010-08-18 23:23:40 +0000800 for (OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
801 I != E; ++I) {
Anna Zaksb3d72752012-03-01 22:06:06 +0000802 ProgramStateRef StateI = FreeMemAux(C, CE, State, *I,
Anna Zaks55dd9562012-08-24 02:28:20 +0000803 Att->getOwnKind() == OwnershipAttr::Holds,
804 ReleasedAllocated);
Anna Zaksb3d72752012-03-01 22:06:06 +0000805 if (StateI)
806 State = StateI;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000807 }
Anna Zaksb3d72752012-03-01 22:06:06 +0000808 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000809}
810
Ted Kremenek8bef8232012-01-26 21:29:00 +0000811ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
Anna Zakse9ef5622012-02-10 01:11:00 +0000812 const CallExpr *CE,
813 ProgramStateRef state,
814 unsigned Num,
Anna Zaks55dd9562012-08-24 02:28:20 +0000815 bool Hold,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000816 bool &ReleasedAllocated,
817 bool ReturnsNullOnFailure) const {
Anna Zaks259052d2012-04-10 23:41:11 +0000818 if (CE->getNumArgs() < (Num + 1))
819 return 0;
820
Anna Zaks4141e4d2012-11-13 03:18:01 +0000821 return FreeMemAux(C, CE->getArg(Num), CE, state, Hold,
822 ReleasedAllocated, ReturnsNullOnFailure);
823}
824
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000825/// Checks if the previous call to free on the given symbol failed - if free
826/// failed, returns true. Also, returns the corresponding return value symbol.
Benjamin Kramer4d9f4e52012-11-22 15:02:44 +0000827static bool didPreviousFreeFail(ProgramStateRef State,
828 SymbolRef Sym, SymbolRef &RetStatusSymbol) {
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000829 const SymbolRef *Ret = State->get<FreeReturnValue>(Sym);
Anna Zaks4141e4d2012-11-13 03:18:01 +0000830 if (Ret) {
831 assert(*Ret && "We should not store the null return symbol");
832 ConstraintManager &CMgr = State->getConstraintManager();
833 ConditionTruthVal FreeFailed = CMgr.isNull(State, *Ret);
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000834 RetStatusSymbol = *Ret;
835 return FreeFailed.isConstrainedTrue();
Anna Zaks4141e4d2012-11-13 03:18:01 +0000836 }
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000837 return false;
Anna Zaks5b7aa342012-06-22 02:04:31 +0000838}
839
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000840AllocationFamily MallocChecker::getAllocationFamily(CheckerContext &C,
841 const Expr *E) const {
842 if (!E)
843 return AF_None;
844
845 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
846 const FunctionDecl *FD = C.getCalleeDecl(CE);
847 ASTContext &Ctx = C.getASTContext();
848
849 if (isFreeFunction(FD, Ctx))
850 return AF_Malloc;
851
852 if (isStandardNewDelete(FD, Ctx)) {
853 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
854 if (Kind == OO_Delete)
855 return AF_CXXNew;
856 else if (Kind == OO_Array_Delete)
857 return AF_CXXNewArray;
858 }
859
860 return AF_None;
861 }
862
863 if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(E))
864 return DE->isArrayForm() ? AF_CXXNewArray : AF_CXXNew;
865
866 if (isa<ObjCMessageExpr>(E))
867 return AF_Malloc;
868
869 return AF_None;
870}
871
872bool MallocChecker::printAllocDeallocName(raw_ostream &os, CheckerContext &C,
873 const Expr *E) const {
874 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
875 // FIXME: This doesn't handle indirect calls.
876 const FunctionDecl *FD = CE->getDirectCallee();
877 if (!FD)
878 return false;
879
880 os << *FD;
881 if (!FD->isOverloadedOperator())
882 os << "()";
883 return true;
884 }
885
886 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E)) {
887 if (Msg->isInstanceMessage())
888 os << "-";
889 else
890 os << "+";
891 os << Msg->getSelector().getAsString();
892 return true;
893 }
894
895 if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(E)) {
896 os << "'"
897 << getOperatorSpelling(NE->getOperatorNew()->getOverloadedOperator())
898 << "'";
899 return true;
900 }
901
902 if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(E)) {
903 os << "'"
904 << getOperatorSpelling(DE->getOperatorDelete()->getOverloadedOperator())
905 << "'";
906 return true;
907 }
908
909 return false;
910}
911
912void MallocChecker::printExpectedAllocName(raw_ostream &os, CheckerContext &C,
913 const Expr *E) const {
914 AllocationFamily Family = getAllocationFamily(C, E);
915
916 switch(Family) {
917 case AF_Malloc: os << "malloc()"; return;
918 case AF_CXXNew: os << "'new'"; return;
919 case AF_CXXNewArray: os << "'new[]'"; return;
920 case AF_None: llvm_unreachable("not a deallocation expression");
921 }
922}
923
924void MallocChecker::printExpectedDeallocName(raw_ostream &os,
925 AllocationFamily Family) const {
926 switch(Family) {
927 case AF_Malloc: os << "free()"; return;
928 case AF_CXXNew: os << "'delete'"; return;
929 case AF_CXXNewArray: os << "'delete[]'"; return;
930 case AF_None: llvm_unreachable("suspicious AF_None argument");
931 }
932}
933
Anna Zaks5b7aa342012-06-22 02:04:31 +0000934ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
935 const Expr *ArgExpr,
936 const Expr *ParentExpr,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000937 ProgramStateRef State,
Anna Zaks55dd9562012-08-24 02:28:20 +0000938 bool Hold,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000939 bool &ReleasedAllocated,
940 bool ReturnsNullOnFailure) const {
Anna Zaks5b7aa342012-06-22 02:04:31 +0000941
Anna Zaks4141e4d2012-11-13 03:18:01 +0000942 SVal ArgVal = State->getSVal(ArgExpr, C.getLocationContext());
David Blaikie5251abe2013-02-20 05:52:05 +0000943 if (!ArgVal.getAs<DefinedOrUnknownSVal>())
Anna Zakse9ef5622012-02-10 01:11:00 +0000944 return 0;
David Blaikie5251abe2013-02-20 05:52:05 +0000945 DefinedOrUnknownSVal location = ArgVal.castAs<DefinedOrUnknownSVal>();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000946
947 // Check for null dereferences.
David Blaikie5251abe2013-02-20 05:52:05 +0000948 if (!location.getAs<Loc>())
Anna Zaksb319e022012-02-08 20:13:28 +0000949 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000950
Anna Zaksb276bd92012-02-14 00:26:13 +0000951 // The explicit NULL case, no operation is performed.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000952 ProgramStateRef notNullState, nullState;
Anna Zaks4141e4d2012-11-13 03:18:01 +0000953 llvm::tie(notNullState, nullState) = State->assume(location);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000954 if (nullState && !notNullState)
Anna Zaksb319e022012-02-08 20:13:28 +0000955 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000956
Jordy Rose43859f62010-06-07 19:32:37 +0000957 // Unknown values could easily be okay
958 // Undefined values are handled elsewhere
959 if (ArgVal.isUnknownOrUndef())
Anna Zaksb319e022012-02-08 20:13:28 +0000960 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000961
Jordy Rose43859f62010-06-07 19:32:37 +0000962 const MemRegion *R = ArgVal.getAsRegion();
963
964 // Nonlocs can't be freed, of course.
965 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
966 if (!R) {
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000967 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
Anna Zaksb319e022012-02-08 20:13:28 +0000968 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000969 }
970
971 R = R->StripCasts();
972
973 // Blocks might show up as heap data, but should not be free()d
974 if (isa<BlockDataRegion>(R)) {
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000975 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
Anna Zaksb319e022012-02-08 20:13:28 +0000976 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000977 }
978
979 const MemSpaceRegion *MS = R->getMemorySpace();
980
Anton Yartsevbb369952013-03-13 14:39:10 +0000981 // Parameters, locals, statics, globals, and memory returned by alloca()
982 // shouldn't be freed.
Jordy Rose43859f62010-06-07 19:32:37 +0000983 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
984 // FIXME: at the time this code was written, malloc() regions were
985 // represented by conjured symbols, which are all in UnknownSpaceRegion.
986 // This means that there isn't actually anything from HeapSpaceRegion
987 // that should be freed, even though we allow it here.
988 // Of course, free() can work on memory allocated outside the current
989 // function, so UnknownSpaceRegion is always a possibility.
990 // False negatives are better than false positives.
991
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000992 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
Anna Zaksb319e022012-02-08 20:13:28 +0000993 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000994 }
Anna Zaks118aa752013-02-07 23:05:47 +0000995
996 const SymbolicRegion *SrBase = dyn_cast<SymbolicRegion>(R->getBaseRegion());
Jordy Rose43859f62010-06-07 19:32:37 +0000997 // Various cases could lead to non-symbol values here.
998 // For now, ignore them.
Anna Zaks118aa752013-02-07 23:05:47 +0000999 if (!SrBase)
Anna Zaksb319e022012-02-08 20:13:28 +00001000 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +00001001
Anna Zaks118aa752013-02-07 23:05:47 +00001002 SymbolRef SymBase = SrBase->getSymbol();
1003 const RefState *RsBase = State->get<RegionState>(SymBase);
Anna Zaks2ccecfa2012-11-13 19:47:40 +00001004 SymbolRef PreviousRetStatusSymbol = 0;
Zhongxing Xu7e3cda92010-01-18 03:27:34 +00001005
Zhongxing Xu589c0f22009-11-12 08:38:56 +00001006 // Check double free.
Anna Zaks118aa752013-02-07 23:05:47 +00001007 if (RsBase &&
1008 (RsBase->isReleased() || RsBase->isRelinquished()) &&
1009 !didPreviousFreeFail(State, SymBase, PreviousRetStatusSymbol)) {
Anton Yartsevbb369952013-03-13 14:39:10 +00001010 ReportDoubleFree(C, ParentExpr->getSourceRange(), RsBase->isReleased(),
1011 SymBase, PreviousRetStatusSymbol);
Anna Zaksb319e022012-02-08 20:13:28 +00001012 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +00001013 }
1014
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001015 // Check if an expected deallocation function matches the real one.
1016 if (RsBase &&
1017 RsBase->getAllocationFamily() != AF_None &&
1018 RsBase->getAllocationFamily() != getAllocationFamily(C, ParentExpr) ) {
1019 ReportBadDealloc(C, ArgExpr->getSourceRange(), ParentExpr, RsBase);
1020 return 0;
1021 }
1022
Anna Zaks118aa752013-02-07 23:05:47 +00001023 // Check if the memory location being freed is the actual location
1024 // allocated, or an offset.
1025 RegionOffset Offset = R->getAsOffset();
1026 if (RsBase && RsBase->isAllocated() &&
1027 Offset.isValid() &&
1028 !Offset.hasSymbolicOffset() &&
1029 Offset.getOffset() != 0) {
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001030 const Expr *AllocExpr = cast<Expr>(RsBase->getStmt());
1031 ReportOffsetFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr,
1032 AllocExpr);
Anna Zaks118aa752013-02-07 23:05:47 +00001033 return 0;
1034 }
1035
1036 ReleasedAllocated = (RsBase != 0);
Anna Zaks55dd9562012-08-24 02:28:20 +00001037
Anna Zaks2ccecfa2012-11-13 19:47:40 +00001038 // Clean out the info on previous call to free return info.
Anna Zaks118aa752013-02-07 23:05:47 +00001039 State = State->remove<FreeReturnValue>(SymBase);
Anna Zaks2ccecfa2012-11-13 19:47:40 +00001040
Anna Zaks4141e4d2012-11-13 03:18:01 +00001041 // Keep track of the return value. If it is NULL, we will know that free
1042 // failed.
1043 if (ReturnsNullOnFailure) {
1044 SVal RetVal = C.getSVal(ParentExpr);
1045 SymbolRef RetStatusSymbol = RetVal.getAsSymbol();
1046 if (RetStatusSymbol) {
Anna Zaks118aa752013-02-07 23:05:47 +00001047 C.getSymbolManager().addSymbolDependency(SymBase, RetStatusSymbol);
1048 State = State->set<FreeReturnValue>(SymBase, RetStatusSymbol);
Anna Zaks4141e4d2012-11-13 03:18:01 +00001049 }
1050 }
1051
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001052 AllocationFamily Family = RsBase ? RsBase->getAllocationFamily() : AF_None;
Zhongxing Xu589c0f22009-11-12 08:38:56 +00001053 // Normal free.
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001054 if (Hold)
Anna Zaks118aa752013-02-07 23:05:47 +00001055 return State->set<RegionState>(SymBase,
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001056 RefState::getRelinquished(Family,
1057 ParentExpr));
1058
1059 return State->set<RegionState>(SymBase,
1060 RefState::getReleased(Family, ParentExpr));
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001061}
1062
Ted Kremenek9c378f72011-08-12 23:37:29 +00001063bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
David Blaikiedc84cd52013-02-20 22:23:23 +00001064 if (Optional<nonloc::ConcreteInt> IntVal = V.getAs<nonloc::ConcreteInt>())
Jordy Rose43859f62010-06-07 19:32:37 +00001065 os << "an integer (" << IntVal->getValue() << ")";
David Blaikiedc84cd52013-02-20 22:23:23 +00001066 else if (Optional<loc::ConcreteInt> ConstAddr = V.getAs<loc::ConcreteInt>())
Jordy Rose43859f62010-06-07 19:32:37 +00001067 os << "a constant address (" << ConstAddr->getValue() << ")";
David Blaikiedc84cd52013-02-20 22:23:23 +00001068 else if (Optional<loc::GotoLabel> Label = V.getAs<loc::GotoLabel>())
Chris Lattner68106302011-02-17 05:38:27 +00001069 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose43859f62010-06-07 19:32:37 +00001070 else
1071 return false;
1072
1073 return true;
1074}
1075
Ted Kremenek9c378f72011-08-12 23:37:29 +00001076bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose43859f62010-06-07 19:32:37 +00001077 const MemRegion *MR) {
1078 switch (MR->getKind()) {
1079 case MemRegion::FunctionTextRegionKind: {
Anna Zaks5fc1d0c2012-09-17 19:13:56 +00001080 const NamedDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
Jordy Rose43859f62010-06-07 19:32:37 +00001081 if (FD)
Benjamin Kramerb8989f22011-10-14 18:45:37 +00001082 os << "the address of the function '" << *FD << '\'';
Jordy Rose43859f62010-06-07 19:32:37 +00001083 else
1084 os << "the address of a function";
1085 return true;
1086 }
1087 case MemRegion::BlockTextRegionKind:
1088 os << "block text";
1089 return true;
1090 case MemRegion::BlockDataRegionKind:
1091 // FIXME: where the block came from?
1092 os << "a block";
1093 return true;
1094 default: {
1095 const MemSpaceRegion *MS = MR->getMemorySpace();
1096
Anna Zakseb31a762012-01-04 23:54:01 +00001097 if (isa<StackLocalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +00001098 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1099 const VarDecl *VD;
1100 if (VR)
1101 VD = VR->getDecl();
1102 else
1103 VD = NULL;
1104
1105 if (VD)
1106 os << "the address of the local variable '" << VD->getName() << "'";
1107 else
1108 os << "the address of a local stack variable";
1109 return true;
1110 }
Anna Zakseb31a762012-01-04 23:54:01 +00001111
1112 if (isa<StackArgumentsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +00001113 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1114 const VarDecl *VD;
1115 if (VR)
1116 VD = VR->getDecl();
1117 else
1118 VD = NULL;
1119
1120 if (VD)
1121 os << "the address of the parameter '" << VD->getName() << "'";
1122 else
1123 os << "the address of a parameter";
1124 return true;
1125 }
Anna Zakseb31a762012-01-04 23:54:01 +00001126
1127 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +00001128 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1129 const VarDecl *VD;
1130 if (VR)
1131 VD = VR->getDecl();
1132 else
1133 VD = NULL;
1134
1135 if (VD) {
1136 if (VD->isStaticLocal())
1137 os << "the address of the static variable '" << VD->getName() << "'";
1138 else
1139 os << "the address of the global variable '" << VD->getName() << "'";
1140 } else
1141 os << "the address of a global variable";
1142 return true;
1143 }
Anna Zakseb31a762012-01-04 23:54:01 +00001144
1145 return false;
Jordy Rose43859f62010-06-07 19:32:37 +00001146 }
1147 }
1148}
1149
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001150void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
1151 SourceRange Range,
1152 const Expr *DeallocExpr) const {
1153
1154 if (!Filter.CMallocOptimistic && !Filter.CMallocPessimistic &&
1155 !Filter.CNewDeleteChecker)
1156 return;
1157
Ted Kremenekd048c6e2010-12-20 21:19:09 +00001158 if (ExplodedNode *N = C.generateSink()) {
Jordy Rose43859f62010-06-07 19:32:37 +00001159 if (!BT_BadFree)
Anna Zaksfebdc322012-02-16 22:26:12 +00001160 BT_BadFree.reset(new BugType("Bad free", "Memory Error"));
Jordy Rose43859f62010-06-07 19:32:37 +00001161
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00001162 SmallString<100> buf;
Jordy Rose43859f62010-06-07 19:32:37 +00001163 llvm::raw_svector_ostream os(buf);
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001164
Jordy Rose43859f62010-06-07 19:32:37 +00001165 const MemRegion *MR = ArgVal.getAsRegion();
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001166 while (const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(MR))
1167 MR = ER->getSuperRegion();
1168
1169 if (MR && isa<AllocaRegion>(MR))
1170 os << "Memory allocated by alloca() should not be deallocated";
1171 else {
1172 os << "Argument to ";
1173 if (!printAllocDeallocName(os, C, DeallocExpr))
1174 os << "deallocator";
1175
1176 os << " is ";
1177 bool Summarized = MR ? SummarizeRegion(os, MR)
1178 : SummarizeValue(os, ArgVal);
1179 if (Summarized)
1180 os << ", which is not memory allocated by ";
Jordy Rose43859f62010-06-07 19:32:37 +00001181 else
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001182 os << "not memory allocated by ";
1183
1184 printExpectedAllocName(os, C, DeallocExpr);
Jordy Rose43859f62010-06-07 19:32:37 +00001185 }
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001186
Anna Zakse172e8b2011-08-17 23:00:25 +00001187 BugReport *R = new BugReport(*BT_BadFree, os.str(), N);
Ted Kremenek76aadc32012-03-09 01:13:14 +00001188 R->markInteresting(MR);
Anton Yartsevbb369952013-03-13 14:39:10 +00001189 R->addRange(Range);
Jordan Rose785950e2012-11-02 01:53:40 +00001190 C.emitReport(R);
Jordy Rose43859f62010-06-07 19:32:37 +00001191 }
1192}
1193
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001194void MallocChecker::ReportBadDealloc(CheckerContext &C, SourceRange Range,
1195 const Expr *DeallocExpr,
1196 const RefState *RS) const {
1197
1198 if (!Filter.CMismatchedDeallocatorChecker)
1199 return;
1200
1201 if (ExplodedNode *N = C.generateSink()) {
1202 if (!BT_BadDealloc)
1203 BT_BadDealloc.reset(new BugType("Bad deallocator", "Memory Error"));
1204
1205 SmallString<100> buf;
1206 llvm::raw_svector_ostream os(buf);
1207
1208 const Expr *AllocExpr = cast<Expr>(RS->getStmt());
1209 SmallString<20> AllocBuf;
1210 llvm::raw_svector_ostream AllocOs(AllocBuf);
1211 SmallString<20> DeallocBuf;
1212 llvm::raw_svector_ostream DeallocOs(DeallocBuf);
1213
1214 os << "Memory";
1215 if (printAllocDeallocName(AllocOs, C, AllocExpr))
1216 os << " allocated by " << AllocOs.str();
1217
1218 os << " should be deallocated by ";
1219 printExpectedDeallocName(os, RS->getAllocationFamily());
1220
1221 if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1222 os << ", not " << DeallocOs.str();
1223
1224 BugReport *R = new BugReport(*BT_BadDealloc, os.str(), N);
1225 R->addRange(Range);
1226 C.emitReport(R);
1227 }
1228}
1229
Anna Zaks118aa752013-02-07 23:05:47 +00001230void MallocChecker::ReportOffsetFree(CheckerContext &C, SVal ArgVal,
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001231 SourceRange Range, const Expr *DeallocExpr,
1232 const Expr *AllocExpr) const {
1233
1234 if (!Filter.CMallocOptimistic && !Filter.CMallocPessimistic &&
1235 !Filter.CNewDeleteChecker)
1236 return;
1237
Anna Zaks118aa752013-02-07 23:05:47 +00001238 ExplodedNode *N = C.generateSink();
1239 if (N == NULL)
1240 return;
1241
1242 if (!BT_OffsetFree)
1243 BT_OffsetFree.reset(new BugType("Offset free", "Memory Error"));
1244
1245 SmallString<100> buf;
1246 llvm::raw_svector_ostream os(buf);
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001247 SmallString<20> AllocNameBuf;
1248 llvm::raw_svector_ostream AllocNameOs(AllocNameBuf);
Anna Zaks118aa752013-02-07 23:05:47 +00001249
1250 const MemRegion *MR = ArgVal.getAsRegion();
1251 assert(MR && "Only MemRegion based symbols can have offset free errors");
1252
1253 RegionOffset Offset = MR->getAsOffset();
1254 assert((Offset.isValid() &&
1255 !Offset.hasSymbolicOffset() &&
1256 Offset.getOffset() != 0) &&
1257 "Only symbols with a valid offset can have offset free errors");
1258
1259 int offsetBytes = Offset.getOffset() / C.getASTContext().getCharWidth();
1260
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001261 os << "Argument to ";
1262 if (!printAllocDeallocName(os, C, DeallocExpr))
1263 os << "deallocator";
1264 os << " is offset by "
Anna Zaks118aa752013-02-07 23:05:47 +00001265 << offsetBytes
1266 << " "
1267 << ((abs(offsetBytes) > 1) ? "bytes" : "byte")
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001268 << " from the start of ";
1269 if (AllocExpr && printAllocDeallocName(AllocNameOs, C, AllocExpr))
1270 os << "memory allocated by " << AllocNameOs.str();
1271 else
1272 os << "allocated memory";
Anna Zaks118aa752013-02-07 23:05:47 +00001273
1274 BugReport *R = new BugReport(*BT_OffsetFree, os.str(), N);
1275 R->markInteresting(MR->getBaseRegion());
1276 R->addRange(Range);
1277 C.emitReport(R);
1278}
1279
Anton Yartsevbb369952013-03-13 14:39:10 +00001280void MallocChecker::ReportUseAfterFree(CheckerContext &C, SourceRange Range,
1281 SymbolRef Sym) const {
1282
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001283 if (!Filter.CMallocOptimistic && !Filter.CMallocPessimistic &&
1284 !Filter.CNewDeleteChecker)
1285 return;
1286
Anton Yartsevbb369952013-03-13 14:39:10 +00001287 if (ExplodedNode *N = C.generateSink()) {
1288 if (!BT_UseFree)
1289 BT_UseFree.reset(new BugType("Use-after-free", "Memory Error"));
1290
1291 BugReport *R = new BugReport(*BT_UseFree,
1292 "Use of memory after it is freed", N);
1293
1294 R->markInteresting(Sym);
1295 R->addRange(Range);
1296 R->addVisitor(new MallocBugVisitor(Sym));
1297 C.emitReport(R);
1298 }
1299}
1300
1301void MallocChecker::ReportDoubleFree(CheckerContext &C, SourceRange Range,
1302 bool Released, SymbolRef Sym,
Anton Yartsev3258d4b2013-03-13 17:07:32 +00001303 SymbolRef PrevSym) const {
Anton Yartsevbb369952013-03-13 14:39:10 +00001304
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001305 if (!Filter.CMallocOptimistic && !Filter.CMallocPessimistic &&
1306 !Filter.CNewDeleteChecker)
1307 return;
1308
Anton Yartsevbb369952013-03-13 14:39:10 +00001309 if (ExplodedNode *N = C.generateSink()) {
1310 if (!BT_DoubleFree)
1311 BT_DoubleFree.reset(new BugType("Double free", "Memory Error"));
1312
1313 BugReport *R = new BugReport(*BT_DoubleFree,
1314 (Released ? "Attempt to free released memory"
1315 : "Attempt to free non-owned memory"),
1316 N);
1317 R->addRange(Range);
Anton Yartsev3258d4b2013-03-13 17:07:32 +00001318 R->markInteresting(Sym);
1319 if (PrevSym)
1320 R->markInteresting(PrevSym);
Anton Yartsevbb369952013-03-13 14:39:10 +00001321 R->addVisitor(new MallocBugVisitor(Sym));
1322 C.emitReport(R);
1323 }
1324}
1325
Anna Zaks87cb5be2012-02-22 19:24:52 +00001326ProgramStateRef MallocChecker::ReallocMem(CheckerContext &C,
1327 const CallExpr *CE,
1328 bool FreesOnFail) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001329 if (CE->getNumArgs() < 2)
1330 return 0;
1331
Ted Kremenek8bef8232012-01-26 21:29:00 +00001332 ProgramStateRef state = C.getState();
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001333 const Expr *arg0Expr = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001334 const LocationContext *LCtx = C.getLocationContext();
Anna Zakse9ef5622012-02-10 01:11:00 +00001335 SVal Arg0Val = state->getSVal(arg0Expr, LCtx);
David Blaikie5251abe2013-02-20 05:52:05 +00001336 if (!Arg0Val.getAs<DefinedOrUnknownSVal>())
Anna Zaks87cb5be2012-02-22 19:24:52 +00001337 return 0;
David Blaikie5251abe2013-02-20 05:52:05 +00001338 DefinedOrUnknownSVal arg0Val = Arg0Val.castAs<DefinedOrUnknownSVal>();
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001339
Ted Kremenek846eabd2010-12-01 21:28:31 +00001340 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001341
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001342 DefinedOrUnknownSVal PtrEQ =
1343 svalBuilder.evalEQ(state, arg0Val, svalBuilder.makeNull());
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001344
Lenny Maiorani4d8d8032011-04-27 14:49:29 +00001345 // Get the size argument. If there is no size arg then give up.
1346 const Expr *Arg1 = CE->getArg(1);
1347 if (!Arg1)
Anna Zaks87cb5be2012-02-22 19:24:52 +00001348 return 0;
Lenny Maiorani4d8d8032011-04-27 14:49:29 +00001349
1350 // Get the value of the size argument.
Anna Zakse9ef5622012-02-10 01:11:00 +00001351 SVal Arg1ValG = state->getSVal(Arg1, LCtx);
David Blaikie5251abe2013-02-20 05:52:05 +00001352 if (!Arg1ValG.getAs<DefinedOrUnknownSVal>())
Anna Zaks87cb5be2012-02-22 19:24:52 +00001353 return 0;
David Blaikie5251abe2013-02-20 05:52:05 +00001354 DefinedOrUnknownSVal Arg1Val = Arg1ValG.castAs<DefinedOrUnknownSVal>();
Lenny Maiorani4d8d8032011-04-27 14:49:29 +00001355
1356 // Compare the size argument to 0.
1357 DefinedOrUnknownSVal SizeZero =
1358 svalBuilder.evalEQ(state, Arg1Val,
1359 svalBuilder.makeIntValWithPtrWidth(0, false));
1360
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001361 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
1362 llvm::tie(StatePtrIsNull, StatePtrNotNull) = state->assume(PtrEQ);
1363 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
1364 llvm::tie(StateSizeIsZero, StateSizeNotZero) = state->assume(SizeZero);
1365 // We only assume exceptional states if they are definitely true; if the
1366 // state is under-constrained, assume regular realloc behavior.
1367 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
1368 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
1369
Lenny Maiorani4d8d8032011-04-27 14:49:29 +00001370 // If the ptr is NULL and the size is not 0, the call is equivalent to
1371 // malloc(size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001372 if ( PrtIsNull && !SizeIsZero) {
Anna Zaks87cb5be2012-02-22 19:24:52 +00001373 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001374 UndefinedVal(), StatePtrIsNull);
Anna Zaks87cb5be2012-02-22 19:24:52 +00001375 return stateMalloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001376 }
1377
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001378 if (PrtIsNull && SizeIsZero)
Anna Zaks87cb5be2012-02-22 19:24:52 +00001379 return 0;
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001380
Anna Zaks30838b92012-02-13 20:57:07 +00001381 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001382 assert(!PrtIsNull);
Anna Zaks30838b92012-02-13 20:57:07 +00001383 SymbolRef FromPtr = arg0Val.getAsSymbol();
1384 SVal RetVal = state->getSVal(CE, LCtx);
1385 SymbolRef ToPtr = RetVal.getAsSymbol();
1386 if (!FromPtr || !ToPtr)
Anna Zaks87cb5be2012-02-22 19:24:52 +00001387 return 0;
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001388
Anna Zaks55dd9562012-08-24 02:28:20 +00001389 bool ReleasedAllocated = false;
1390
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001391 // If the size is 0, free the memory.
1392 if (SizeIsZero)
Anna Zaks55dd9562012-08-24 02:28:20 +00001393 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero, 0,
1394 false, ReleasedAllocated)){
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001395 // The semantics of the return value are:
1396 // If size was equal to 0, either NULL or a pointer suitable to be passed
Anna Zaksede875b2012-08-03 18:30:18 +00001397 // to free() is returned. We just free the input pointer and do not add
1398 // any constrains on the output pointer.
Anna Zaks87cb5be2012-02-22 19:24:52 +00001399 return stateFree;
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001400 }
1401
1402 // Default behavior.
Anna Zaks55dd9562012-08-24 02:28:20 +00001403 if (ProgramStateRef stateFree =
1404 FreeMemAux(C, CE, state, 0, false, ReleasedAllocated)) {
1405
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001406 ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
1407 UnknownVal(), stateFree);
Anna Zaks30838b92012-02-13 20:57:07 +00001408 if (!stateRealloc)
Anna Zaks87cb5be2012-02-22 19:24:52 +00001409 return 0;
Anna Zaks55dd9562012-08-24 02:28:20 +00001410
Anna Zaks9dc298b2012-09-12 22:57:34 +00001411 ReallocPairKind Kind = RPToBeFreedAfterFailure;
1412 if (FreesOnFail)
1413 Kind = RPIsFreeOnFailure;
1414 else if (!ReleasedAllocated)
1415 Kind = RPDoNotTrackAfterFailure;
1416
Anna Zaks55dd9562012-08-24 02:28:20 +00001417 // Record the info about the reallocated symbol so that we could properly
1418 // process failed reallocation.
Anna Zaks40add292012-02-15 00:11:25 +00001419 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
Anna Zaks9dc298b2012-09-12 22:57:34 +00001420 ReallocPair(FromPtr, Kind));
Anna Zaks55dd9562012-08-24 02:28:20 +00001421 // The reallocated symbol should stay alive for as long as the new symbol.
Anna Zaksb276bd92012-02-14 00:26:13 +00001422 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks87cb5be2012-02-22 19:24:52 +00001423 return stateRealloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001424 }
Anna Zaks87cb5be2012-02-22 19:24:52 +00001425 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +00001426}
Zhongxing Xu7b760962009-11-13 07:25:27 +00001427
Anna Zaks87cb5be2012-02-22 19:24:52 +00001428ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE){
Anna Zaks259052d2012-04-10 23:41:11 +00001429 if (CE->getNumArgs() < 2)
1430 return 0;
1431
Ted Kremenek8bef8232012-01-26 21:29:00 +00001432 ProgramStateRef state = C.getState();
Ted Kremenek846eabd2010-12-01 21:28:31 +00001433 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001434 const LocationContext *LCtx = C.getLocationContext();
1435 SVal count = state->getSVal(CE->getArg(0), LCtx);
1436 SVal elementSize = state->getSVal(CE->getArg(1), LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001437 SVal TotalSize = svalBuilder.evalBinOp(state, BO_Mul, count, elementSize,
1438 svalBuilder.getContext().getSizeType());
1439 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Zhongxing Xua5ce9662010-06-01 03:01:33 +00001440
Anna Zaks87cb5be2012-02-22 19:24:52 +00001441 return MallocMemAux(C, CE, TotalSize, zeroVal, state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +00001442}
1443
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001444LeakInfo
Anna Zaksca8e36e2012-02-23 21:38:21 +00001445MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
1446 CheckerContext &C) const {
Anna Zaks7752d292012-02-27 23:40:55 +00001447 const LocationContext *LeakContext = N->getLocationContext();
Anna Zaksca8e36e2012-02-23 21:38:21 +00001448 // Walk the ExplodedGraph backwards and find the first node that referred to
1449 // the tracked symbol.
1450 const ExplodedNode *AllocNode = N;
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001451 const MemRegion *ReferenceRegion = 0;
Anna Zaksca8e36e2012-02-23 21:38:21 +00001452
1453 while (N) {
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001454 ProgramStateRef State = N->getState();
1455 if (!State->get<RegionState>(Sym))
Anna Zaksca8e36e2012-02-23 21:38:21 +00001456 break;
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001457
1458 // Find the most recent expression bound to the symbol in the current
1459 // context.
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001460 if (!ReferenceRegion) {
Benjamin Kramer850f1b12012-03-21 21:03:48 +00001461 if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
1462 SVal Val = State->getSVal(MR);
1463 if (Val.getAsLocSymbol() == Sym)
1464 ReferenceRegion = MR;
1465 }
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001466 }
1467
Anna Zaks7752d292012-02-27 23:40:55 +00001468 // Allocation node, is the last node in the current context in which the
1469 // symbol was tracked.
1470 if (N->getLocationContext() == LeakContext)
1471 AllocNode = N;
Anna Zaksca8e36e2012-02-23 21:38:21 +00001472 N = N->pred_empty() ? NULL : *(N->pred_begin());
1473 }
1474
Anna Zaks97bfb552013-01-08 00:25:29 +00001475 return LeakInfo(AllocNode, ReferenceRegion);
Anna Zaksca8e36e2012-02-23 21:38:21 +00001476}
1477
Anna Zaksda046772012-02-11 21:02:40 +00001478void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
1479 CheckerContext &C) const {
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001480
1481 if (!Filter.CMallocOptimistic && !Filter.CMallocPessimistic &&
1482 !Filter.CNewDeleteChecker)
1483 return;
1484
Anna Zaksda046772012-02-11 21:02:40 +00001485 assert(N);
1486 if (!BT_Leak) {
Anna Zaksfebdc322012-02-16 22:26:12 +00001487 BT_Leak.reset(new BugType("Memory leak", "Memory Error"));
Anna Zaksda046772012-02-11 21:02:40 +00001488 // Leaks should not be reported if they are post-dominated by a sink:
1489 // (1) Sinks are higher importance bugs.
1490 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
1491 // with __noreturn functions such as assert() or exit(). We choose not
1492 // to report leaks on such paths.
1493 BT_Leak->setSuppressOnSink(true);
1494 }
1495
Anna Zaksca8e36e2012-02-23 21:38:21 +00001496 // Most bug reports are cached at the location where they occurred.
1497 // With leaks, we want to unique them by the location where they were
1498 // allocated, and only report a single path.
Anna Zaks7752d292012-02-27 23:40:55 +00001499 PathDiagnosticLocation LocUsedForUniqueing;
Anna Zaks97bfb552013-01-08 00:25:29 +00001500 const ExplodedNode *AllocNode = 0;
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001501 const MemRegion *Region = 0;
Anna Zaks97bfb552013-01-08 00:25:29 +00001502 llvm::tie(AllocNode, Region) = getAllocationSite(N, Sym, C);
1503
1504 ProgramPoint P = AllocNode->getLocation();
1505 const Stmt *AllocationStmt = 0;
David Blaikie7a95de62013-02-21 22:23:56 +00001506 if (Optional<CallExitEnd> Exit = P.getAs<CallExitEnd>())
Anna Zaks97bfb552013-01-08 00:25:29 +00001507 AllocationStmt = Exit->getCalleeContext()->getCallSite();
David Blaikie7a95de62013-02-21 22:23:56 +00001508 else if (Optional<StmtPoint> SP = P.getAs<StmtPoint>())
Anna Zaks97bfb552013-01-08 00:25:29 +00001509 AllocationStmt = SP->getStmt();
1510 if (AllocationStmt)
1511 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocationStmt,
1512 C.getSourceManager(),
1513 AllocNode->getLocationContext());
Anna Zaksca8e36e2012-02-23 21:38:21 +00001514
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001515 SmallString<200> buf;
1516 llvm::raw_svector_ostream os(buf);
1517 os << "Memory is never released; potential leak";
Jordan Rose919e8a12012-08-08 18:23:36 +00001518 if (Region && Region->canPrintPretty()) {
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001519 os << " of memory pointed to by '";
Jordan Rose919e8a12012-08-08 18:23:36 +00001520 Region->printPretty(os);
Jordan Rose0d53ab42012-08-08 18:23:31 +00001521 os << '\'';
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001522 }
1523
Anna Zaks97bfb552013-01-08 00:25:29 +00001524 BugReport *R = new BugReport(*BT_Leak, os.str(), N,
1525 LocUsedForUniqueing,
1526 AllocNode->getLocationContext()->getDecl());
Ted Kremenek76aadc32012-03-09 01:13:14 +00001527 R->markInteresting(Sym);
Anna Zaks88feba02012-05-10 01:37:40 +00001528 R->addVisitor(new MallocBugVisitor(Sym, true));
Jordan Rose785950e2012-11-02 01:53:40 +00001529 C.emitReport(R);
Anna Zaksda046772012-02-11 21:02:40 +00001530}
1531
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001532void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
1533 CheckerContext &C) const
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001534{
Zhongxing Xu173ff562010-08-15 08:19:57 +00001535 if (!SymReaper.hasDeadSymbols())
1536 return;
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +00001537
Ted Kremenek8bef8232012-01-26 21:29:00 +00001538 ProgramStateRef state = C.getState();
Zhongxing Xu173ff562010-08-15 08:19:57 +00001539 RegionStateTy RS = state->get<RegionState>();
Jordy Rose90760142010-08-18 04:33:47 +00001540 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xu173ff562010-08-15 08:19:57 +00001541
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001542 SmallVector<SymbolRef, 2> Errors;
Zhongxing Xu173ff562010-08-15 08:19:57 +00001543 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
1544 if (SymReaper.isDead(I->first)) {
Anna Zaks54458702012-10-29 22:51:54 +00001545 if (I->second.isAllocated())
Anna Zaksf8c17b72012-02-09 06:48:19 +00001546 Errors.push_back(I->first);
Jordy Rose90760142010-08-18 04:33:47 +00001547 // Remove the dead symbol from the map.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001548 RS = F.remove(RS, I->first);
Ted Kremenek217470e2011-07-28 23:07:51 +00001549
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +00001550 }
1551 }
Ted Kremenek217470e2011-07-28 23:07:51 +00001552
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001553 // Cleanup the Realloc Pairs Map.
Jordan Rose166d5022012-11-02 01:54:06 +00001554 ReallocPairsTy RP = state->get<ReallocPairs>();
1555 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Anna Zaks40add292012-02-15 00:11:25 +00001556 if (SymReaper.isDead(I->first) ||
1557 SymReaper.isDead(I->second.ReallocatedSym)) {
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001558 state = state->remove<ReallocPairs>(I->first);
1559 }
1560 }
1561
Anna Zaks4141e4d2012-11-13 03:18:01 +00001562 // Cleanup the FreeReturnValue Map.
1563 FreeReturnValueTy FR = state->get<FreeReturnValue>();
1564 for (FreeReturnValueTy::iterator I = FR.begin(), E = FR.end(); I != E; ++I) {
1565 if (SymReaper.isDead(I->first) ||
1566 SymReaper.isDead(I->second)) {
1567 state = state->remove<FreeReturnValue>(I->first);
1568 }
1569 }
1570
Anna Zaksca8e36e2012-02-23 21:38:21 +00001571 // Generate leak node.
Anna Zaks54458702012-10-29 22:51:54 +00001572 ExplodedNode *N = C.getPredecessor();
1573 if (!Errors.empty()) {
1574 static SimpleProgramPointTag Tag("MallocChecker : DeadSymbolsLeak");
1575 N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001576 for (SmallVector<SymbolRef, 2>::iterator
Anna Zaks54458702012-10-29 22:51:54 +00001577 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
Anna Zaksda046772012-02-11 21:02:40 +00001578 reportLeak(*I, N, C);
Anna Zaksf8c17b72012-02-09 06:48:19 +00001579 }
Ted Kremenek217470e2011-07-28 23:07:51 +00001580 }
Anna Zaks54458702012-10-29 22:51:54 +00001581
Anna Zaksca8e36e2012-02-23 21:38:21 +00001582 C.addTransition(state->set<RegionState>(RS), N);
Zhongxing Xu7b760962009-11-13 07:25:27 +00001583}
Zhongxing Xu243fde92009-11-17 07:54:15 +00001584
Anna Zaks66c40402012-02-14 21:55:24 +00001585void MallocChecker::checkPreStmt(const CallExpr *CE, CheckerContext &C) const {
Anna Zaks14345182012-05-18 01:16:10 +00001586 // We will check for double free in the post visit.
Anton Yartsev2de19ed2013-03-25 01:35:45 +00001587 if ((Filter.CMallocOptimistic || Filter.CMallocPessimistic) &&
1588 isFreeFunction(C.getCalleeDecl(CE), C.getASTContext()))
1589 return;
1590
1591 if (Filter.CNewDeleteChecker &&
1592 isStandardNewDelete(C.getCalleeDecl(CE), C.getASTContext()))
Anna Zaks66c40402012-02-14 21:55:24 +00001593 return;
1594
1595 // Check use after free, when a freed pointer is passed to a call.
1596 ProgramStateRef State = C.getState();
1597 for (CallExpr::const_arg_iterator I = CE->arg_begin(),
1598 E = CE->arg_end(); I != E; ++I) {
1599 const Expr *A = *I;
1600 if (A->getType().getTypePtr()->isAnyPointerType()) {
Anton Yartsevbb369952013-03-13 14:39:10 +00001601 SymbolRef Sym = C.getSVal(A).getAsSymbol();
Anna Zaks66c40402012-02-14 21:55:24 +00001602 if (!Sym)
1603 continue;
1604 if (checkUseAfterFree(Sym, C, A))
1605 return;
1606 }
1607 }
1608}
1609
Anna Zaks91c2a112012-02-08 23:16:56 +00001610void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
1611 const Expr *E = S->getRetValue();
1612 if (!E)
1613 return;
Anna Zaks0860cd02012-02-11 21:44:39 +00001614
1615 // Check if we are returning a symbol.
Jordan Rose0d53ab42012-08-08 18:23:31 +00001616 ProgramStateRef State = C.getState();
1617 SVal RetVal = State->getSVal(E, C.getLocationContext());
Anna Zaksd9ab7bb2012-02-22 02:36:01 +00001618 SymbolRef Sym = RetVal.getAsSymbol();
1619 if (!Sym)
1620 // If we are returning a field of the allocated struct or an array element,
1621 // the callee could still free the memory.
1622 // TODO: This logic should be a part of generic symbol escape callback.
1623 if (const MemRegion *MR = RetVal.getAsRegion())
1624 if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
1625 if (const SymbolicRegion *BMR =
1626 dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
1627 Sym = BMR->getSymbol();
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001628
Anna Zaks0860cd02012-02-11 21:44:39 +00001629 // Check if we are returning freed memory.
Jordan Rose0d53ab42012-08-08 18:23:31 +00001630 if (Sym)
Jordan Rose65d4bd62012-11-15 19:11:33 +00001631 checkUseAfterFree(Sym, C, E);
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001632}
Zhongxing Xub94b81a2009-12-31 06:13:07 +00001633
Anna Zaksf5aa3f52012-03-22 00:57:20 +00001634// TODO: Blocks should be either inlined or should call invalidate regions
1635// upon invocation. After that's in place, special casing here will not be
1636// needed.
1637void MallocChecker::checkPostStmt(const BlockExpr *BE,
1638 CheckerContext &C) const {
1639
1640 // Scan the BlockDecRefExprs for any object the retain count checker
1641 // may be tracking.
1642 if (!BE->getBlockDecl()->hasCaptures())
1643 return;
1644
1645 ProgramStateRef state = C.getState();
1646 const BlockDataRegion *R =
1647 cast<BlockDataRegion>(state->getSVal(BE,
1648 C.getLocationContext()).getAsRegion());
1649
1650 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
1651 E = R->referenced_vars_end();
1652
1653 if (I == E)
1654 return;
1655
1656 SmallVector<const MemRegion*, 10> Regions;
1657 const LocationContext *LC = C.getLocationContext();
1658 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
1659
1660 for ( ; I != E; ++I) {
Ted Kremeneke3ce2c12012-12-06 07:17:20 +00001661 const VarRegion *VR = I.getCapturedRegion();
Anna Zaksf5aa3f52012-03-22 00:57:20 +00001662 if (VR->getSuperRegion() == R) {
1663 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
1664 }
1665 Regions.push_back(VR);
1666 }
1667
1668 state =
1669 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
1670 Regions.data() + Regions.size()).getState();
1671 C.addTransition(state);
1672}
1673
Anna Zaks14345182012-05-18 01:16:10 +00001674bool MallocChecker::isReleased(SymbolRef Sym, CheckerContext &C) const {
Anna Zaks91c2a112012-02-08 23:16:56 +00001675 assert(Sym);
1676 const RefState *RS = C.getState()->get<RegionState>(Sym);
Anna Zaks14345182012-05-18 01:16:10 +00001677 return (RS && RS->isReleased());
1678}
1679
1680bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
1681 const Stmt *S) const {
Anna Zaks91c2a112012-02-08 23:16:56 +00001682
Anton Yartsevbb369952013-03-13 14:39:10 +00001683 if (isReleased(Sym, C)) {
1684 ReportUseAfterFree(C, S->getSourceRange(), Sym);
1685 return true;
Anna Zaks91c2a112012-02-08 23:16:56 +00001686 }
Anton Yartsevbb369952013-03-13 14:39:10 +00001687
Anna Zaks91c2a112012-02-08 23:16:56 +00001688 return false;
1689}
1690
Zhongxing Xuc8023782010-03-10 04:58:55 +00001691// Check if the location is a freed symbolic region.
Anna Zaks390909c2011-10-06 00:43:15 +00001692void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
1693 CheckerContext &C) const {
Zhongxing Xuc8023782010-03-10 04:58:55 +00001694 SymbolRef Sym = l.getLocSymbolInBase();
Anna Zaks91c2a112012-02-08 23:16:56 +00001695 if (Sym)
Anna Zaks14345182012-05-18 01:16:10 +00001696 checkUseAfterFree(Sym, C, S);
Zhongxing Xuc8023782010-03-10 04:58:55 +00001697}
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001698
Anna Zaks4fb54872012-02-11 21:02:35 +00001699// If a symbolic region is assumed to NULL (or another constant), stop tracking
1700// it - assuming that allocation failed on this path.
1701ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
1702 SVal Cond,
1703 bool Assumption) const {
1704 RegionStateTy RS = state->get<RegionState>();
Anna Zaks4fb54872012-02-11 21:02:35 +00001705 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
Ted Kremenek47cbd0f2012-09-07 22:31:01 +00001706 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Roseec8d4202012-11-01 00:18:27 +00001707 ConstraintManager &CMgr = state->getConstraintManager();
1708 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
1709 if (AllocFailed.isConstrainedTrue())
Anna Zaks4fb54872012-02-11 21:02:35 +00001710 state = state->remove<RegionState>(I.getKey());
1711 }
1712
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001713 // Realloc returns 0 when reallocation fails, which means that we should
1714 // restore the state of the pointer being reallocated.
Jordan Rose166d5022012-11-02 01:54:06 +00001715 ReallocPairsTy RP = state->get<ReallocPairs>();
1716 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Ted Kremenek47cbd0f2012-09-07 22:31:01 +00001717 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Roseec8d4202012-11-01 00:18:27 +00001718 ConstraintManager &CMgr = state->getConstraintManager();
1719 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
Jordan Rose79a29eb2012-11-01 00:25:15 +00001720 if (!AllocFailed.isConstrainedTrue())
Anna Zaks9dc298b2012-09-12 22:57:34 +00001721 continue;
Jordan Roseec8d4202012-11-01 00:18:27 +00001722
Anna Zaks9dc298b2012-09-12 22:57:34 +00001723 SymbolRef ReallocSym = I.getData().ReallocatedSym;
1724 if (const RefState *RS = state->get<RegionState>(ReallocSym)) {
1725 if (RS->isReleased()) {
1726 if (I.getData().Kind == RPToBeFreedAfterFailure)
Anna Zaks40add292012-02-15 00:11:25 +00001727 state = state->set<RegionState>(ReallocSym,
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001728 RefState::getAllocated(RS->getAllocationFamily(), RS->getStmt()));
Anna Zaks9dc298b2012-09-12 22:57:34 +00001729 else if (I.getData().Kind == RPDoNotTrackAfterFailure)
1730 state = state->remove<RegionState>(ReallocSym);
1731 else
1732 assert(I.getData().Kind == RPIsFreeOnFailure);
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001733 }
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001734 }
Anna Zaks9dc298b2012-09-12 22:57:34 +00001735 state = state->remove<ReallocPairs>(I.getKey());
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001736 }
1737
Anna Zaks4fb54872012-02-11 21:02:35 +00001738 return state;
1739}
1740
Jordan Rose9fe09f32013-03-09 00:59:10 +00001741bool MallocChecker::doesNotFreeMemOrInteresting(const CallEvent *Call,
1742 ProgramStateRef State) const {
Jordan Rose85d7e012012-07-02 19:27:51 +00001743 assert(Call);
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001744
1745 // For now, assume that any C++ call can free memory.
1746 // TODO: If we want to be more optimistic here, we'll need to make sure that
1747 // regions escape to C++ containers. They seem to do that even now, but for
1748 // mysterious reasons.
Jordan Rosecde8cdb2012-07-02 19:27:56 +00001749 if (!(isa<FunctionCall>(Call) || isa<ObjCMethodCall>(Call)))
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001750 return false;
1751
Jordan Rose740d4902012-07-02 19:27:35 +00001752 // Check Objective-C messages by selector name.
Jordan Rosecde8cdb2012-07-02 19:27:56 +00001753 if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) {
Jordan Rose85d7e012012-07-02 19:27:51 +00001754 // If it's not a framework call, or if it takes a callback, assume it
1755 // can free memory.
1756 if (!Call->isInSystemHeader() || Call->hasNonZeroCallbackArg())
Anna Zaks07d39a42012-02-28 01:54:22 +00001757 return false;
1758
Jordan Rose9fe09f32013-03-09 00:59:10 +00001759 // If it's a method we know about, handle it explicitly post-call.
1760 // This should happen before the "freeWhenDone" check below.
1761 if (isKnownDeallocObjCMethodName(*Msg))
1762 return true;
Anna Zaks52a04812012-06-20 23:35:57 +00001763
Jordan Rose9fe09f32013-03-09 00:59:10 +00001764 // If there's a "freeWhenDone" parameter, but the method isn't one we know
1765 // about, we can't be sure that the object will use free() to deallocate the
1766 // memory, so we can't model it explicitly. The best we can do is use it to
1767 // decide whether the pointer escapes.
1768 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(*Msg))
1769 return !*FreeWhenDone;
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001770
Jordan Rose9fe09f32013-03-09 00:59:10 +00001771 // If the first selector piece ends with "NoCopy", and there is no
1772 // "freeWhenDone" parameter set to zero, we know ownership is being
1773 // transferred. Again, though, we can't be sure that the object will use
1774 // free() to deallocate the memory, so we can't model it explicitly.
1775 StringRef FirstSlot = Msg->getSelector().getNameForSlot(0);
Jordan Rose740d4902012-07-02 19:27:35 +00001776 if (FirstSlot.endswith("NoCopy"))
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001777 return false;
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001778
Anna Zaks5f757682012-06-19 05:10:32 +00001779 // If the first selector starts with addPointer, insertPointer,
1780 // or replacePointer, assume we are dealing with NSPointerArray or similar.
1781 // This is similar to C++ containers (vector); we still might want to check
Jordan Rose740d4902012-07-02 19:27:35 +00001782 // that the pointers get freed by following the container itself.
1783 if (FirstSlot.startswith("addPointer") ||
1784 FirstSlot.startswith("insertPointer") ||
1785 FirstSlot.startswith("replacePointer")) {
Anna Zaks5f757682012-06-19 05:10:32 +00001786 return false;
1787 }
1788
Jordan Rose740d4902012-07-02 19:27:35 +00001789 // Otherwise, assume that the method does not free memory.
1790 // Most framework methods do not free memory.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001791 return true;
Anna Zaks66c40402012-02-14 21:55:24 +00001792 }
1793
Jordan Rose740d4902012-07-02 19:27:35 +00001794 // At this point the only thing left to handle is straight function calls.
1795 const FunctionDecl *FD = cast<FunctionCall>(Call)->getDecl();
1796 if (!FD)
1797 return false;
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001798
Jordan Rose740d4902012-07-02 19:27:35 +00001799 ASTContext &ASTC = State->getStateManager().getContext();
1800
1801 // If it's one of the allocation functions we can reason about, we model
1802 // its behavior explicitly.
1803 if (isMemFunction(FD, ASTC))
1804 return true;
1805
1806 // If it's not a system call, assume it frees memory.
1807 if (!Call->isInSystemHeader())
1808 return false;
1809
1810 // White list the system functions whose arguments escape.
1811 const IdentifierInfo *II = FD->getIdentifier();
1812 if (!II)
1813 return false;
1814 StringRef FName = II->getName();
1815
Jordan Rose740d4902012-07-02 19:27:35 +00001816 // White list the 'XXXNoCopy' CoreFoundation functions.
Jordan Rose85d7e012012-07-02 19:27:51 +00001817 // We specifically check these before
Jordan Rose740d4902012-07-02 19:27:35 +00001818 if (FName.endswith("NoCopy")) {
1819 // Look for the deallocator argument. We know that the memory ownership
1820 // is not transferred only if the deallocator argument is
1821 // 'kCFAllocatorNull'.
1822 for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
1823 const Expr *ArgE = Call->getArgExpr(i)->IgnoreParenCasts();
1824 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
1825 StringRef DeallocatorName = DE->getFoundDecl()->getName();
1826 if (DeallocatorName == "kCFAllocatorNull")
1827 return true;
1828 }
1829 }
1830 return false;
1831 }
1832
Jordan Rose740d4902012-07-02 19:27:35 +00001833 // Associating streams with malloced buffers. The pointer can escape if
Jordan Rose85d7e012012-07-02 19:27:51 +00001834 // 'closefn' is specified (and if that function does free memory),
1835 // but it will not if closefn is not specified.
Jordan Rose740d4902012-07-02 19:27:35 +00001836 // Currently, we do not inspect the 'closefn' function (PR12101).
1837 if (FName == "funopen")
Jordan Rose85d7e012012-07-02 19:27:51 +00001838 if (Call->getNumArgs() >= 4 && Call->getArgSVal(4).isConstant(0))
1839 return true;
Jordan Rose740d4902012-07-02 19:27:35 +00001840
1841 // Do not warn on pointers passed to 'setbuf' when used with std streams,
1842 // these leaks might be intentional when setting the buffer for stdio.
1843 // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
1844 if (FName == "setbuf" || FName =="setbuffer" ||
1845 FName == "setlinebuf" || FName == "setvbuf") {
1846 if (Call->getNumArgs() >= 1) {
1847 const Expr *ArgE = Call->getArgExpr(0)->IgnoreParenCasts();
1848 if (const DeclRefExpr *ArgDRE = dyn_cast<DeclRefExpr>(ArgE))
1849 if (const VarDecl *D = dyn_cast<VarDecl>(ArgDRE->getDecl()))
1850 if (D->getCanonicalDecl()->getName().find("std") != StringRef::npos)
1851 return false;
1852 }
1853 }
1854
1855 // A bunch of other functions which either take ownership of a pointer or
1856 // wrap the result up in a struct or object, meaning it can be freed later.
1857 // (See RetainCountChecker.) Not all the parameters here are invalidated,
1858 // but the Malloc checker cannot differentiate between them. The right way
1859 // of doing this would be to implement a pointer escapes callback.
1860 if (FName == "CGBitmapContextCreate" ||
1861 FName == "CGBitmapContextCreateWithData" ||
1862 FName == "CVPixelBufferCreateWithBytes" ||
1863 FName == "CVPixelBufferCreateWithPlanarBytes" ||
1864 FName == "OSAtomicEnqueue") {
1865 return false;
1866 }
1867
Jordan Rose85d7e012012-07-02 19:27:51 +00001868 // Handle cases where we know a buffer's /address/ can escape.
1869 // Note that the above checks handle some special cases where we know that
1870 // even though the address escapes, it's still our responsibility to free the
1871 // buffer.
1872 if (Call->argumentsMayEscape())
Jordan Rose740d4902012-07-02 19:27:35 +00001873 return false;
1874
1875 // Otherwise, assume that the function does not free memory.
1876 // Most system calls do not free the memory.
1877 return true;
Anna Zaks66c40402012-02-14 21:55:24 +00001878}
1879
Anna Zaks41988f32013-03-28 23:15:29 +00001880static bool retTrue(const RefState *RS) {
1881 return true;
1882}
1883
1884static bool checkIfNewOrNewArrayFamily(const RefState *RS) {
1885 return (RS->getAllocationFamily() == AF_CXXNewArray ||
1886 RS->getAllocationFamily() == AF_CXXNew);
1887}
1888
Anna Zaksbf53dfa2012-12-20 00:38:25 +00001889ProgramStateRef MallocChecker::checkPointerEscape(ProgramStateRef State,
1890 const InvalidatedSymbols &Escaped,
Anna Zaks233e26a2013-02-07 23:05:43 +00001891 const CallEvent *Call,
1892 PointerEscapeKind Kind) const {
Anna Zaks41988f32013-03-28 23:15:29 +00001893 return checkPointerEscapeAux(State, Escaped, Call, Kind, &retTrue);
1894}
1895
1896ProgramStateRef MallocChecker::checkConstPointerEscape(ProgramStateRef State,
1897 const InvalidatedSymbols &Escaped,
1898 const CallEvent *Call,
1899 PointerEscapeKind Kind) const {
1900 return checkPointerEscapeAux(State, Escaped, Call, Kind,
1901 &checkIfNewOrNewArrayFamily);
1902}
1903
1904ProgramStateRef MallocChecker::checkPointerEscapeAux(ProgramStateRef State,
1905 const InvalidatedSymbols &Escaped,
1906 const CallEvent *Call,
1907 PointerEscapeKind Kind,
1908 bool(*CheckRefState)(const RefState*)) const {
Jordan Rose9fe09f32013-03-09 00:59:10 +00001909 // If we know that the call does not free memory, or we want to process the
1910 // call later, keep tracking the top level arguments.
Anna Zaks233e26a2013-02-07 23:05:43 +00001911 if ((Kind == PSK_DirectEscapeOnCall ||
1912 Kind == PSK_IndirectEscapeOnCall) &&
Jordan Rose9fe09f32013-03-09 00:59:10 +00001913 doesNotFreeMemOrInteresting(Call, State)) {
Anna Zaks66c40402012-02-14 21:55:24 +00001914 return State;
Anna Zaks233e26a2013-02-07 23:05:43 +00001915 }
Anna Zaks66c40402012-02-14 21:55:24 +00001916
Anna Zaksbf53dfa2012-12-20 00:38:25 +00001917 for (InvalidatedSymbols::const_iterator I = Escaped.begin(),
Anna Zaks41988f32013-03-28 23:15:29 +00001918 E = Escaped.end();
1919 I != E; ++I) {
Anna Zaks4fb54872012-02-11 21:02:35 +00001920 SymbolRef sym = *I;
Anna Zaksbf53dfa2012-12-20 00:38:25 +00001921
Anna Zaks5b7aa342012-06-22 02:04:31 +00001922 if (const RefState *RS = State->get<RegionState>(sym)) {
Anna Zaks41988f32013-03-28 23:15:29 +00001923 if (RS->isAllocated() && CheckRefState(RS))
Anna Zaks431e35c2012-08-09 00:42:24 +00001924 State = State->remove<RegionState>(sym);
Anna Zaks5b7aa342012-06-22 02:04:31 +00001925 }
Anna Zaks4fb54872012-02-11 21:02:35 +00001926 }
Anna Zaks66c40402012-02-14 21:55:24 +00001927 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001928}
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001929
Jordy Rose393f98b2012-03-18 07:43:35 +00001930static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
1931 ProgramStateRef prevState) {
Jordan Rose166d5022012-11-02 01:54:06 +00001932 ReallocPairsTy currMap = currState->get<ReallocPairs>();
1933 ReallocPairsTy prevMap = prevState->get<ReallocPairs>();
Jordy Rose393f98b2012-03-18 07:43:35 +00001934
Jordan Rose166d5022012-11-02 01:54:06 +00001935 for (ReallocPairsTy::iterator I = prevMap.begin(), E = prevMap.end();
Jordy Rose393f98b2012-03-18 07:43:35 +00001936 I != E; ++I) {
1937 SymbolRef sym = I.getKey();
1938 if (!currMap.lookup(sym))
1939 return sym;
1940 }
1941
1942 return NULL;
1943}
1944
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001945PathDiagnosticPiece *
1946MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
1947 const ExplodedNode *PrevN,
1948 BugReporterContext &BRC,
1949 BugReport &BR) {
Jordy Rose393f98b2012-03-18 07:43:35 +00001950 ProgramStateRef state = N->getState();
1951 ProgramStateRef statePrev = PrevN->getState();
1952
1953 const RefState *RS = state->get<RegionState>(Sym);
1954 const RefState *RSPrev = statePrev->get<RegionState>(Sym);
Anna Zaksede875b2012-08-03 18:30:18 +00001955 if (!RS)
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001956 return 0;
1957
Anna Zaksfe571602012-02-16 22:26:07 +00001958 const Stmt *S = 0;
1959 const char *Msg = 0;
Anna Zaks56a938f2012-03-16 23:24:20 +00001960 StackHintGeneratorForSymbol *StackHint = 0;
Anna Zaksfe571602012-02-16 22:26:07 +00001961
1962 // Retrieve the associated statement.
1963 ProgramPoint ProgLoc = N->getLocation();
David Blaikie7a95de62013-02-21 22:23:56 +00001964 if (Optional<StmtPoint> SP = ProgLoc.getAs<StmtPoint>()) {
Jordan Rose852aa0d2012-07-10 22:07:52 +00001965 S = SP->getStmt();
David Blaikie7a95de62013-02-21 22:23:56 +00001966 } else if (Optional<CallExitEnd> Exit = ProgLoc.getAs<CallExitEnd>()) {
Jordan Rose852aa0d2012-07-10 22:07:52 +00001967 S = Exit->getCalleeContext()->getCallSite();
David Blaikie7a95de62013-02-21 22:23:56 +00001968 } else if (Optional<BlockEdge> Edge = ProgLoc.getAs<BlockEdge>()) {
Ted Kremeneka4a17592013-01-04 19:04:36 +00001969 // If an assumption was made on a branch, it should be caught
1970 // here by looking at the state transition.
1971 S = Edge->getSrc()->getTerminator();
Anna Zaksfe571602012-02-16 22:26:07 +00001972 }
Ted Kremeneka4a17592013-01-04 19:04:36 +00001973
Anna Zaksfe571602012-02-16 22:26:07 +00001974 if (!S)
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001975 return 0;
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001976
Jordan Rose28038f32012-07-10 22:07:42 +00001977 // FIXME: We will eventually need to handle non-statement-based events
1978 // (__attribute__((cleanup))).
1979
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001980 // Find out if this is an interesting point and what is the kind.
Anna Zaksfe571602012-02-16 22:26:07 +00001981 if (Mode == Normal) {
Anna Zaks368a0d52012-03-15 21:13:02 +00001982 if (isAllocated(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001983 Msg = "Memory is allocated";
Anna Zaksfbd58742012-03-16 23:44:28 +00001984 StackHint = new StackHintGeneratorForSymbol(Sym,
1985 "Returned allocated memory");
Anna Zaks368a0d52012-03-15 21:13:02 +00001986 } else if (isReleased(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001987 Msg = "Memory is released";
Anna Zaksfbd58742012-03-16 23:44:28 +00001988 StackHint = new StackHintGeneratorForSymbol(Sym,
1989 "Returned released memory");
Anna Zaks5b7aa342012-06-22 02:04:31 +00001990 } else if (isRelinquished(RS, RSPrev, S)) {
1991 Msg = "Memory ownership is transfered";
1992 StackHint = new StackHintGeneratorForSymbol(Sym, "");
Anna Zaks368a0d52012-03-15 21:13:02 +00001993 } else if (isReallocFailedCheck(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001994 Mode = ReallocationFailed;
1995 Msg = "Reallocation failed";
Anna Zaks56a938f2012-03-16 23:24:20 +00001996 StackHint = new StackHintGeneratorForReallocationFailed(Sym,
Anna Zaksfbd58742012-03-16 23:44:28 +00001997 "Reallocation failed");
Jordy Rose393f98b2012-03-18 07:43:35 +00001998
Jordy Roseb000fb52012-03-24 03:15:09 +00001999 if (SymbolRef sym = findFailedReallocSymbol(state, statePrev)) {
2000 // Is it possible to fail two reallocs WITHOUT testing in between?
2001 assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
2002 "We only support one failed realloc at a time.");
Jordy Rose393f98b2012-03-18 07:43:35 +00002003 BR.markInteresting(sym);
Jordy Roseb000fb52012-03-24 03:15:09 +00002004 FailedReallocSymbol = sym;
2005 }
Anna Zaksfe571602012-02-16 22:26:07 +00002006 }
2007
2008 // We are in a special mode if a reallocation failed later in the path.
2009 } else if (Mode == ReallocationFailed) {
Jordy Roseb000fb52012-03-24 03:15:09 +00002010 assert(FailedReallocSymbol && "No symbol to look for.");
Anna Zaksfe571602012-02-16 22:26:07 +00002011
Jordy Roseb000fb52012-03-24 03:15:09 +00002012 // Is this is the first appearance of the reallocated symbol?
2013 if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
Jordy Roseb000fb52012-03-24 03:15:09 +00002014 // We're at the reallocation point.
2015 Msg = "Attempt to reallocate memory";
2016 StackHint = new StackHintGeneratorForSymbol(Sym,
2017 "Returned reallocated memory");
2018 FailedReallocSymbol = NULL;
2019 Mode = Normal;
2020 }
Anna Zaksfe571602012-02-16 22:26:07 +00002021 }
2022
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002023 if (!Msg)
2024 return 0;
Anna Zaks56a938f2012-03-16 23:24:20 +00002025 assert(StackHint);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002026
2027 // Generate the extra diagnostic.
Anna Zaksfe571602012-02-16 22:26:07 +00002028 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002029 N->getLocationContext());
Anna Zaks56a938f2012-03-16 23:24:20 +00002030 return new PathDiagnosticEventPiece(Pos, Msg, true, StackHint);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002031}
2032
Anna Zaks93c5a242012-05-02 00:05:20 +00002033void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State,
2034 const char *NL, const char *Sep) const {
2035
2036 RegionStateTy RS = State->get<RegionState>();
2037
Ted Kremenekc37fad62013-01-03 01:30:12 +00002038 if (!RS.isEmpty()) {
2039 Out << Sep << "MallocChecker:" << NL;
2040 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
2041 I.getKey()->dumpToStream(Out);
2042 Out << " : ";
2043 I.getData().dump(Out);
2044 Out << NL;
2045 }
2046 }
Anna Zaks93c5a242012-05-02 00:05:20 +00002047}
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002048
Anna Zaks231361a2012-02-08 23:16:52 +00002049#define REGISTER_CHECKER(name) \
2050void ento::register##name(CheckerManager &mgr) {\
Anna Zaksf0dfc9c2012-02-17 22:35:31 +00002051 registerCStringCheckerBasic(mgr); \
Anna Zaks231361a2012-02-08 23:16:52 +00002052 mgr.registerChecker<MallocChecker>()->Filter.C##name = true;\
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00002053}
Anna Zaks231361a2012-02-08 23:16:52 +00002054
2055REGISTER_CHECKER(MallocPessimistic)
2056REGISTER_CHECKER(MallocOptimistic)
Anton Yartsev2de19ed2013-03-25 01:35:45 +00002057REGISTER_CHECKER(NewDeleteChecker)
Anton Yartsev849c7bf2013-03-28 17:05:19 +00002058REGISTER_CHECKER(MismatchedDeallocatorChecker)