blob: 274eb80e90850637eabadd3f3a689dacef1a7d64 [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)
61 : K(k), S(s), 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,
Ted Kremeneke3659a72012-01-04 23:48:37 +0000137 check::PreStmt<ReturnStmt>,
Anna Zaks66c40402012-02-14 21:55:24 +0000138 check::PreStmt<CallExpr>,
Anna Zaksb319e022012-02-08 20:13:28 +0000139 check::PostStmt<CallExpr>,
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000140 check::PostStmt<CXXNewExpr>,
141 check::PreStmt<CXXDeleteExpr>,
Anna Zaksf5aa3f52012-03-22 00:57:20 +0000142 check::PostStmt<BlockExpr>,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000143 check::PostObjCMessage,
Ted Kremeneke3659a72012-01-04 23:48:37 +0000144 check::Location,
Anna Zaksbf53dfa2012-12-20 00:38:25 +0000145 eval::Assume>
Ted Kremeneke3659a72012-01-04 23:48:37 +0000146{
Anna Zaksfebdc322012-02-16 22:26:12 +0000147 mutable OwningPtr<BugType> BT_DoubleFree;
148 mutable OwningPtr<BugType> BT_Leak;
149 mutable OwningPtr<BugType> BT_UseFree;
150 mutable OwningPtr<BugType> BT_BadFree;
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000151 mutable OwningPtr<BugType> BT_BadDealloc;
Anna Zaks118aa752013-02-07 23:05:47 +0000152 mutable OwningPtr<BugType> BT_OffsetFree;
Anna Zaksb16ce452012-02-15 00:11:22 +0000153 mutable IdentifierInfo *II_malloc, *II_free, *II_realloc, *II_calloc,
Anna Zaks60a1fa42012-02-22 03:14:20 +0000154 *II_valloc, *II_reallocf, *II_strndup, *II_strdup;
155
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000156public:
Anna Zaksb16ce452012-02-15 00:11:22 +0000157 MallocChecker() : II_malloc(0), II_free(0), II_realloc(0), II_calloc(0),
Anna Zaks60a1fa42012-02-22 03:14:20 +0000158 II_valloc(0), II_reallocf(0), II_strndup(0), II_strdup(0) {}
Anna Zaks231361a2012-02-08 23:16:52 +0000159
160 /// In pessimistic mode, the checker assumes that it does not know which
161 /// functions might free the memory.
162 struct ChecksFilter {
163 DefaultBool CMallocPessimistic;
164 DefaultBool CMallocOptimistic;
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000165 DefaultBool CNewDeleteChecker;
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000166 DefaultBool CMismatchedDeallocatorChecker;
Anna Zaks231361a2012-02-08 23:16:52 +0000167 };
168
169 ChecksFilter Filter;
170
Anna Zaks66c40402012-02-14 21:55:24 +0000171 void checkPreStmt(const CallExpr *S, CheckerContext &C) const;
Anna Zaksb319e022012-02-08 20:13:28 +0000172 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000173 void checkPostStmt(const CXXNewExpr *NE, CheckerContext &C) const;
174 void checkPreStmt(const CXXDeleteExpr *DE, CheckerContext &C) const;
Anna Zaks4141e4d2012-11-13 03:18:01 +0000175 void checkPostObjCMessage(const ObjCMethodCall &Call, CheckerContext &C) const;
Anna Zaksf5aa3f52012-03-22 00:57:20 +0000176 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000177 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000178 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000179 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000180 bool Assumption) const;
Anna Zaks390909c2011-10-06 00:43:15 +0000181 void checkLocation(SVal l, bool isLoad, const Stmt *S,
182 CheckerContext &C) const;
Anna Zaksbf53dfa2012-12-20 00:38:25 +0000183
184 ProgramStateRef checkPointerEscape(ProgramStateRef State,
185 const InvalidatedSymbols &Escaped,
Anna Zaks233e26a2013-02-07 23:05:43 +0000186 const CallEvent *Call,
187 PointerEscapeKind Kind) const;
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000188
Anna Zaks93c5a242012-05-02 00:05:20 +0000189 void printState(raw_ostream &Out, ProgramStateRef State,
190 const char *NL, const char *Sep) const;
191
Zhongxing Xu7b760962009-11-13 07:25:27 +0000192private:
Anna Zaks66c40402012-02-14 21:55:24 +0000193 void initIdentifierInfo(ASTContext &C) const;
194
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000195 /// \brief Determine family of a deallocation expression.
196 AllocationFamily getAllocationFamily(CheckerContext &C, const Expr *E) const;
197
198 /// \brief Print names of allocators and deallocators.
199 ///
200 /// \returns true on success.
201 bool printAllocDeallocName(raw_ostream &os, CheckerContext &C,
202 const Expr *E) const;
203
204 /// \brief Print expected name of an allocator based on the deallocator's
205 /// family derived from the DeallocExpr.
206 void printExpectedAllocName(raw_ostream &os, CheckerContext &C,
207 const Expr *DeallocExpr) const;
208 /// \brief Print expected name of a deallocator based on the allocator's
209 /// family.
210 void printExpectedDeallocName(raw_ostream &os, AllocationFamily Family) const;
211
Jordan Rose9fe09f32013-03-09 00:59:10 +0000212 ///@{
Anna Zaks66c40402012-02-14 21:55:24 +0000213 /// Check if this is one of the functions which can allocate/reallocate memory
214 /// pointed to by one of its arguments.
215 bool isMemFunction(const FunctionDecl *FD, ASTContext &C) const;
Anna Zaks14345182012-05-18 01:16:10 +0000216 bool isFreeFunction(const FunctionDecl *FD, ASTContext &C) const;
217 bool isAllocationFunction(const FunctionDecl *FD, ASTContext &C) const;
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000218 bool isStandardNewDelete(const FunctionDecl *FD, ASTContext &C) const;
Jordan Rose9fe09f32013-03-09 00:59:10 +0000219 ///@}
Anna Zaks87cb5be2012-02-22 19:24:52 +0000220 static ProgramStateRef MallocMemReturnsAttr(CheckerContext &C,
221 const CallExpr *CE,
222 const OwnershipAttr* Att);
Ted Kremenek8bef8232012-01-26 21:29:00 +0000223 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000224 const Expr *SizeEx, SVal Init,
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000225 ProgramStateRef State,
226 AllocationFamily Family = AF_Malloc) {
Ted Kremenek5eca4822012-01-06 22:09:28 +0000227 return MallocMemAux(C, CE,
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000228 State->getSVal(SizeEx, C.getLocationContext()),
229 Init, State, Family);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000230 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000231
Ted Kremenek8bef8232012-01-26 21:29:00 +0000232 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000233 SVal SizeEx, SVal Init,
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000234 ProgramStateRef State,
235 AllocationFamily Family = AF_Malloc);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000236
Anna Zaks87cb5be2012-02-22 19:24:52 +0000237 /// Update the RefState to reflect the new memory allocation.
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000238 static ProgramStateRef
239 MallocUpdateRefState(CheckerContext &C, const Expr *E, ProgramStateRef State,
240 AllocationFamily Family = AF_Malloc);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000241
242 ProgramStateRef FreeMemAttr(CheckerContext &C, const CallExpr *CE,
243 const OwnershipAttr* Att) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000244 ProgramStateRef FreeMemAux(CheckerContext &C, const CallExpr *CE,
Anna Zaks5b7aa342012-06-22 02:04:31 +0000245 ProgramStateRef state, unsigned Num,
Anna Zaks55dd9562012-08-24 02:28:20 +0000246 bool Hold,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000247 bool &ReleasedAllocated,
248 bool ReturnsNullOnFailure = false) const;
Anna Zaks5b7aa342012-06-22 02:04:31 +0000249 ProgramStateRef FreeMemAux(CheckerContext &C, const Expr *Arg,
250 const Expr *ParentExpr,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000251 ProgramStateRef State,
Anna Zaks55dd9562012-08-24 02:28:20 +0000252 bool Hold,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000253 bool &ReleasedAllocated,
254 bool ReturnsNullOnFailure = false) const;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000255
Anna Zaks87cb5be2012-02-22 19:24:52 +0000256 ProgramStateRef ReallocMem(CheckerContext &C, const CallExpr *CE,
257 bool FreesMemOnFailure) const;
258 static ProgramStateRef CallocMem(CheckerContext &C, const CallExpr *CE);
Jordy Rose43859f62010-06-07 19:32:37 +0000259
Anna Zaks14345182012-05-18 01:16:10 +0000260 ///\brief Check if the memory associated with this symbol was released.
261 bool isReleased(SymbolRef Sym, CheckerContext &C) const;
262
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000263 bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C, const Stmt *S) const;
Anna Zaks91c2a112012-02-08 23:16:56 +0000264
Jordan Rose9fe09f32013-03-09 00:59:10 +0000265 /// Check if the function is known not to free memory, or if it is
266 /// "interesting" and should be modeled explicitly.
267 ///
268 /// We assume that pointers do not escape through calls to system functions
269 /// not handled by this checker.
270 bool doesNotFreeMemOrInteresting(const CallEvent *Call,
271 ProgramStateRef State) const;
Anna Zaks66c40402012-02-14 21:55:24 +0000272
Ted Kremenek9c378f72011-08-12 23:37:29 +0000273 static bool SummarizeValue(raw_ostream &os, SVal V);
274 static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000275 void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
276 const Expr *DeallocExpr) const;
Anton Yartsevbb369952013-03-13 14:39:10 +0000277 void ReportBadDealloc(CheckerContext &C, SourceRange Range,
278 const Expr *DeallocExpr, const RefState *RS) const;
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000279 void ReportOffsetFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
280 const Expr *DeallocExpr,
281 const Expr *AllocExpr = 0) const;
Anton Yartsevbb369952013-03-13 14:39:10 +0000282 void ReportUseAfterFree(CheckerContext &C, SourceRange Range,
283 SymbolRef Sym) const;
284 void ReportDoubleFree(CheckerContext &C, SourceRange Range, bool Released,
Anton Yartsev3258d4b2013-03-13 17:07:32 +0000285 SymbolRef Sym, SymbolRef PrevSym) const;
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000286
Anna Zaksca8e36e2012-02-23 21:38:21 +0000287 /// Find the location of the allocation for Sym on the path leading to the
288 /// exploded node N.
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000289 LeakInfo getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
290 CheckerContext &C) const;
Anna Zaksca8e36e2012-02-23 21:38:21 +0000291
Anna Zaksda046772012-02-11 21:02:40 +0000292 void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
293
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000294 /// The bug visitor which allows us to print extra diagnostics along the
295 /// BugReport path. For example, showing the allocation site of the leaked
296 /// region.
Jordy Rose01153492012-03-24 02:45:35 +0000297 class MallocBugVisitor : public BugReporterVisitorImpl<MallocBugVisitor> {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000298 protected:
Anna Zaksfe571602012-02-16 22:26:07 +0000299 enum NotificationMode {
300 Normal,
Anna Zaksfe571602012-02-16 22:26:07 +0000301 ReallocationFailed
302 };
303
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000304 // The allocated region symbol tracked by the main analysis.
305 SymbolRef Sym;
306
Anna Zaks88feba02012-05-10 01:37:40 +0000307 // The mode we are in, i.e. what kind of diagnostics will be emitted.
308 NotificationMode Mode;
Jordy Roseb000fb52012-03-24 03:15:09 +0000309
Anna Zaks88feba02012-05-10 01:37:40 +0000310 // A symbol from when the primary region should have been reallocated.
311 SymbolRef FailedReallocSymbol;
Jordy Roseb000fb52012-03-24 03:15:09 +0000312
Anna Zaks88feba02012-05-10 01:37:40 +0000313 bool IsLeak;
314
315 public:
316 MallocBugVisitor(SymbolRef S, bool isLeak = false)
317 : Sym(S), Mode(Normal), FailedReallocSymbol(0), IsLeak(isLeak) {}
Jordy Roseb000fb52012-03-24 03:15:09 +0000318
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000319 virtual ~MallocBugVisitor() {}
320
321 void Profile(llvm::FoldingSetNodeID &ID) const {
322 static int X = 0;
323 ID.AddPointer(&X);
324 ID.AddPointer(Sym);
325 }
326
Anna Zaksfe571602012-02-16 22:26:07 +0000327 inline bool isAllocated(const RefState *S, const RefState *SPrev,
328 const Stmt *Stmt) {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000329 // Did not track -> allocated. Other state (released) -> allocated.
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000330 return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXNewExpr>(Stmt)) &&
Anna Zaksfe571602012-02-16 22:26:07 +0000331 (S && S->isAllocated()) && (!SPrev || !SPrev->isAllocated()));
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000332 }
333
Anna Zaksfe571602012-02-16 22:26:07 +0000334 inline bool isReleased(const RefState *S, const RefState *SPrev,
335 const Stmt *Stmt) {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000336 // Did not track -> released. Other state (allocated) -> released.
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000337 return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXDeleteExpr>(Stmt)) &&
Anna Zaksfe571602012-02-16 22:26:07 +0000338 (S && S->isReleased()) && (!SPrev || !SPrev->isReleased()));
339 }
340
Anna Zaks5b7aa342012-06-22 02:04:31 +0000341 inline bool isRelinquished(const RefState *S, const RefState *SPrev,
342 const Stmt *Stmt) {
343 // Did not track -> relinquished. Other state (allocated) -> relinquished.
344 return (Stmt && (isa<CallExpr>(Stmt) || isa<ObjCMessageExpr>(Stmt) ||
345 isa<ObjCPropertyRefExpr>(Stmt)) &&
346 (S && S->isRelinquished()) &&
347 (!SPrev || !SPrev->isRelinquished()));
348 }
349
Anna Zaksfe571602012-02-16 22:26:07 +0000350 inline bool isReallocFailedCheck(const RefState *S, const RefState *SPrev,
351 const Stmt *Stmt) {
352 // If the expression is not a call, and the state change is
353 // released -> allocated, it must be the realloc return value
354 // check. If we have to handle more cases here, it might be cleaner just
355 // to track this extra bit in the state itself.
356 return ((!Stmt || !isa<CallExpr>(Stmt)) &&
357 (S && S->isAllocated()) && (SPrev && !SPrev->isAllocated()));
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000358 }
359
360 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
361 const ExplodedNode *PrevN,
362 BugReporterContext &BRC,
363 BugReport &BR);
Anna Zaks88feba02012-05-10 01:37:40 +0000364
365 PathDiagnosticPiece* getEndPath(BugReporterContext &BRC,
366 const ExplodedNode *EndPathNode,
367 BugReport &BR) {
368 if (!IsLeak)
369 return 0;
370
371 PathDiagnosticLocation L =
372 PathDiagnosticLocation::createEndOfPath(EndPathNode,
373 BRC.getSourceManager());
374 // Do not add the statement itself as a range in case of leak.
375 return new PathDiagnosticEventPiece(L, BR.getDescription(), false);
376 }
377
Anna Zaks56a938f2012-03-16 23:24:20 +0000378 private:
379 class StackHintGeneratorForReallocationFailed
380 : public StackHintGeneratorForSymbol {
381 public:
382 StackHintGeneratorForReallocationFailed(SymbolRef S, StringRef M)
383 : StackHintGeneratorForSymbol(S, M) {}
384
385 virtual std::string getMessageForArg(const Expr *ArgE, unsigned ArgIndex) {
Jordan Rose615a0922012-09-22 01:24:42 +0000386 // Printed parameters start at 1, not 0.
387 ++ArgIndex;
388
Anna Zaks56a938f2012-03-16 23:24:20 +0000389 SmallString<200> buf;
390 llvm::raw_svector_ostream os(buf);
391
Jordan Rose615a0922012-09-22 01:24:42 +0000392 os << "Reallocation of " << ArgIndex << llvm::getOrdinalSuffix(ArgIndex)
393 << " parameter failed";
Anna Zaks56a938f2012-03-16 23:24:20 +0000394
395 return os.str();
396 }
397
398 virtual std::string getMessageForReturn(const CallExpr *CallExpr) {
Anna Zaksfbd58742012-03-16 23:44:28 +0000399 return "Reallocation of returned value failed";
Anna Zaks56a938f2012-03-16 23:24:20 +0000400 }
401 };
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000402 };
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000403};
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000404} // end anonymous namespace
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000405
Jordan Rose166d5022012-11-02 01:54:06 +0000406REGISTER_MAP_WITH_PROGRAMSTATE(RegionState, SymbolRef, RefState)
407REGISTER_MAP_WITH_PROGRAMSTATE(ReallocPairs, SymbolRef, ReallocPair)
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000408
Anna Zaks4141e4d2012-11-13 03:18:01 +0000409// A map from the freed symbol to the symbol representing the return value of
410// the free function.
411REGISTER_MAP_WITH_PROGRAMSTATE(FreeReturnValue, SymbolRef, SymbolRef)
412
Anna Zaks4fb54872012-02-11 21:02:35 +0000413namespace {
414class StopTrackingCallback : public SymbolVisitor {
415 ProgramStateRef state;
416public:
417 StopTrackingCallback(ProgramStateRef st) : state(st) {}
418 ProgramStateRef getState() const { return state; }
419
420 bool VisitSymbol(SymbolRef sym) {
421 state = state->remove<RegionState>(sym);
422 return true;
423 }
424};
425} // end anonymous namespace
426
Anna Zaks66c40402012-02-14 21:55:24 +0000427void MallocChecker::initIdentifierInfo(ASTContext &Ctx) const {
Anna Zaksa38cb2c2012-05-18 22:47:40 +0000428 if (II_malloc)
429 return;
430 II_malloc = &Ctx.Idents.get("malloc");
431 II_free = &Ctx.Idents.get("free");
432 II_realloc = &Ctx.Idents.get("realloc");
433 II_reallocf = &Ctx.Idents.get("reallocf");
434 II_calloc = &Ctx.Idents.get("calloc");
435 II_valloc = &Ctx.Idents.get("valloc");
436 II_strdup = &Ctx.Idents.get("strdup");
437 II_strndup = &Ctx.Idents.get("strndup");
Anna Zaksb319e022012-02-08 20:13:28 +0000438}
439
Anna Zaks66c40402012-02-14 21:55:24 +0000440bool MallocChecker::isMemFunction(const FunctionDecl *FD, ASTContext &C) const {
Anna Zaks14345182012-05-18 01:16:10 +0000441 if (isFreeFunction(FD, C))
442 return true;
443
444 if (isAllocationFunction(FD, C))
445 return true;
446
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000447 if (isStandardNewDelete(FD, C))
448 return true;
449
Anna Zaks14345182012-05-18 01:16:10 +0000450 return false;
451}
452
453bool MallocChecker::isAllocationFunction(const FunctionDecl *FD,
454 ASTContext &C) const {
Anna Zaks1d6cc6a2012-02-15 02:12:00 +0000455 if (!FD)
456 return false;
Anna Zaks14345182012-05-18 01:16:10 +0000457
Jordan Rose5ef6e942012-07-10 23:13:01 +0000458 if (FD->getKind() == Decl::Function) {
459 IdentifierInfo *FunI = FD->getIdentifier();
460 initIdentifierInfo(C);
Anna Zaks66c40402012-02-14 21:55:24 +0000461
Jordan Rose5ef6e942012-07-10 23:13:01 +0000462 if (FunI == II_malloc || FunI == II_realloc ||
463 FunI == II_reallocf || FunI == II_calloc || FunI == II_valloc ||
464 FunI == II_strdup || FunI == II_strndup)
465 return true;
466 }
Anna Zaks66c40402012-02-14 21:55:24 +0000467
Anna Zaks14345182012-05-18 01:16:10 +0000468 if (Filter.CMallocOptimistic && FD->hasAttrs())
469 for (specific_attr_iterator<OwnershipAttr>
470 i = FD->specific_attr_begin<OwnershipAttr>(),
471 e = FD->specific_attr_end<OwnershipAttr>();
472 i != e; ++i)
473 if ((*i)->getOwnKind() == OwnershipAttr::Returns)
474 return true;
475 return false;
476}
477
478bool MallocChecker::isFreeFunction(const FunctionDecl *FD, ASTContext &C) const {
479 if (!FD)
480 return false;
481
Jordan Rose5ef6e942012-07-10 23:13:01 +0000482 if (FD->getKind() == Decl::Function) {
483 IdentifierInfo *FunI = FD->getIdentifier();
484 initIdentifierInfo(C);
Anna Zaks14345182012-05-18 01:16:10 +0000485
Jordan Rose5ef6e942012-07-10 23:13:01 +0000486 if (FunI == II_free || FunI == II_realloc || FunI == II_reallocf)
487 return true;
488 }
Anna Zaks66c40402012-02-14 21:55:24 +0000489
Anna Zaks14345182012-05-18 01:16:10 +0000490 if (Filter.CMallocOptimistic && FD->hasAttrs())
491 for (specific_attr_iterator<OwnershipAttr>
492 i = FD->specific_attr_begin<OwnershipAttr>(),
493 e = FD->specific_attr_end<OwnershipAttr>();
494 i != e; ++i)
495 if ((*i)->getOwnKind() == OwnershipAttr::Takes ||
496 (*i)->getOwnKind() == OwnershipAttr::Holds)
497 return true;
Anna Zaks66c40402012-02-14 21:55:24 +0000498 return false;
499}
500
Anton Yartsev69746282013-03-28 16:10:38 +0000501// Tells if the callee is one of the following:
502// 1) A global non-placement new/delete operator function.
503// 2) A global placement operator function with the single placement argument
504// of type std::nothrow_t.
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000505bool MallocChecker::isStandardNewDelete(const FunctionDecl *FD,
506 ASTContext &C) const {
507 if (!FD)
508 return false;
509
510 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
511 if (Kind != OO_New && Kind != OO_Array_New &&
512 Kind != OO_Delete && Kind != OO_Array_Delete)
513 return false;
514
Anton Yartsev69746282013-03-28 16:10:38 +0000515 // Skip all operator new/delete methods.
516 if (isa<CXXMethodDecl>(FD))
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000517 return false;
518
519 // Return true if tested operator is a standard placement nothrow operator.
520 if (FD->getNumParams() == 2) {
521 QualType T = FD->getParamDecl(1)->getType();
522 if (const IdentifierInfo *II = T.getBaseTypeIdentifier())
523 return II->getName().equals("nothrow_t");
524 }
525
526 // Skip placement operators.
527 if (FD->getNumParams() != 1 || FD->isVariadic())
528 return false;
529
530 // One of the standard new/new[]/delete/delete[] non-placement operators.
531 return true;
532}
533
Anna Zaksb319e022012-02-08 20:13:28 +0000534void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
Jordan Rosec20c7272012-09-20 01:55:32 +0000535 if (C.wasInlined)
536 return;
537
Anna Zaksb319e022012-02-08 20:13:28 +0000538 const FunctionDecl *FD = C.getCalleeDecl(CE);
539 if (!FD)
540 return;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000541
Anna Zaks87cb5be2012-02-22 19:24:52 +0000542 ProgramStateRef State = C.getState();
Anna Zaks55dd9562012-08-24 02:28:20 +0000543 bool ReleasedAllocatedMemory = false;
Jordan Rose5ef6e942012-07-10 23:13:01 +0000544
545 if (FD->getKind() == Decl::Function) {
546 initIdentifierInfo(C.getASTContext());
547 IdentifierInfo *FunI = FD->getIdentifier();
548
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000549 if (Filter.CMallocOptimistic || Filter.CMallocPessimistic ||
550 Filter.CMismatchedDeallocatorChecker) {
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000551 if (FunI == II_malloc || FunI == II_valloc) {
552 if (CE->getNumArgs() < 1)
553 return;
554 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
555 } else if (FunI == II_realloc) {
556 State = ReallocMem(C, CE, false);
557 } else if (FunI == II_reallocf) {
558 State = ReallocMem(C, CE, true);
559 } else if (FunI == II_calloc) {
560 State = CallocMem(C, CE);
561 } else if (FunI == II_free) {
562 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
563 } else if (FunI == II_strdup) {
564 State = MallocUpdateRefState(C, CE, State);
565 } else if (FunI == II_strndup) {
566 State = MallocUpdateRefState(C, CE, State);
567 }
568 }
569
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000570 if (Filter.CNewDeleteChecker || Filter.CMismatchedDeallocatorChecker) {
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000571 if (isStandardNewDelete(FD, C.getASTContext())) {
572 // Process direct calls to operator new/new[]/delete/delete[] functions
573 // as distinct from new/new[]/delete/delete[] expressions that are
574 // processed by the checkPostStmt callbacks for CXXNewExpr and
575 // CXXDeleteExpr.
576 OverloadedOperatorKind K = FD->getOverloadedOperator();
577 if (K == OO_New)
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000578 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
579 AF_CXXNew);
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000580 else if (K == OO_Array_New)
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000581 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
582 AF_CXXNewArray);
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000583 else if (K == OO_Delete || K == OO_Array_Delete)
584 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
585 else
586 llvm_unreachable("not a new/delete operator");
587 }
Jordan Rose5ef6e942012-07-10 23:13:01 +0000588 }
589 }
590
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000591 if (Filter.CMallocOptimistic || Filter.CMismatchedDeallocatorChecker) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000592 // Check all the attributes, if there are any.
593 // There can be multiple of these attributes.
594 if (FD->hasAttrs())
595 for (specific_attr_iterator<OwnershipAttr>
596 i = FD->specific_attr_begin<OwnershipAttr>(),
597 e = FD->specific_attr_end<OwnershipAttr>();
598 i != e; ++i) {
599 switch ((*i)->getOwnKind()) {
600 case OwnershipAttr::Returns:
601 State = MallocMemReturnsAttr(C, CE, *i);
602 break;
603 case OwnershipAttr::Takes:
604 case OwnershipAttr::Holds:
605 State = FreeMemAttr(C, CE, *i);
606 break;
607 }
608 }
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000609 }
Anna Zaks60a1fa42012-02-22 03:14:20 +0000610 C.addTransition(State);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000611}
612
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000613void MallocChecker::checkPostStmt(const CXXNewExpr *NE,
614 CheckerContext &C) const {
615
616 if (NE->getNumPlacementArgs())
617 for (CXXNewExpr::const_arg_iterator I = NE->placement_arg_begin(),
618 E = NE->placement_arg_end(); I != E; ++I)
619 if (SymbolRef Sym = C.getSVal(*I).getAsSymbol())
620 checkUseAfterFree(Sym, C, *I);
621
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000622 if (!Filter.CNewDeleteChecker && !Filter.CMismatchedDeallocatorChecker)
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000623 return;
624
625 if (!isStandardNewDelete(NE->getOperatorNew(), C.getASTContext()))
626 return;
627
628 ProgramStateRef State = C.getState();
629 // The return value from operator new is bound to a specified initialization
630 // value (if any) and we don't want to loose this value. So we call
631 // MallocUpdateRefState() instead of MallocMemAux() which breakes the
632 // existing binding.
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000633 State = MallocUpdateRefState(C, NE, State, NE->isArray() ? AF_CXXNewArray
634 : AF_CXXNew);
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000635 C.addTransition(State);
636}
637
638void MallocChecker::checkPreStmt(const CXXDeleteExpr *DE,
639 CheckerContext &C) const {
640
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000641 if (!Filter.CNewDeleteChecker)
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000642 if (SymbolRef Sym = C.getSVal(DE->getArgument()).getAsSymbol())
643 checkUseAfterFree(Sym, C, DE->getArgument());
644
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000645 if (!Filter.CNewDeleteChecker && !Filter.CMismatchedDeallocatorChecker)
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000646 return;
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000647
648 if (!isStandardNewDelete(DE->getOperatorDelete(), C.getASTContext()))
649 return;
650
651 ProgramStateRef State = C.getState();
652 bool ReleasedAllocated;
653 State = FreeMemAux(C, DE->getArgument(), DE, State,
654 /*Hold*/false, ReleasedAllocated);
655
656 C.addTransition(State);
657}
658
Jordan Rose9fe09f32013-03-09 00:59:10 +0000659static bool isKnownDeallocObjCMethodName(const ObjCMethodCall &Call) {
660 // If the first selector piece is one of the names below, assume that the
661 // object takes ownership of the memory, promising to eventually deallocate it
662 // with free().
663 // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
664 // (...unless a 'freeWhenDone' parameter is false, but that's checked later.)
665 StringRef FirstSlot = Call.getSelector().getNameForSlot(0);
666 if (FirstSlot == "dataWithBytesNoCopy" ||
667 FirstSlot == "initWithBytesNoCopy" ||
668 FirstSlot == "initWithCharactersNoCopy")
669 return true;
Anna Zaks5b7aa342012-06-22 02:04:31 +0000670
671 return false;
672}
673
Jordan Rose9fe09f32013-03-09 00:59:10 +0000674static Optional<bool> getFreeWhenDoneArg(const ObjCMethodCall &Call) {
675 Selector S = Call.getSelector();
676
677 // FIXME: We should not rely on fully-constrained symbols being folded.
678 for (unsigned i = 1; i < S.getNumArgs(); ++i)
679 if (S.getNameForSlot(i).equals("freeWhenDone"))
680 return !Call.getArgSVal(i).isZeroConstant();
681
682 return None;
683}
684
Anna Zaks4141e4d2012-11-13 03:18:01 +0000685void MallocChecker::checkPostObjCMessage(const ObjCMethodCall &Call,
686 CheckerContext &C) const {
Anna Zaksc2cca232012-12-11 00:17:53 +0000687 if (C.wasInlined)
688 return;
689
Jordan Rose9fe09f32013-03-09 00:59:10 +0000690 if (!isKnownDeallocObjCMethodName(Call))
691 return;
Anna Zaks4141e4d2012-11-13 03:18:01 +0000692
Jordan Rose9fe09f32013-03-09 00:59:10 +0000693 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(Call))
694 if (!*FreeWhenDone)
695 return;
696
697 bool ReleasedAllocatedMemory;
698 ProgramStateRef State = FreeMemAux(C, Call.getArgExpr(0),
699 Call.getOriginExpr(), C.getState(),
700 /*Hold=*/true, ReleasedAllocatedMemory,
701 /*RetNullOnFailure=*/true);
702
703 C.addTransition(State);
Anna Zaks5b7aa342012-06-22 02:04:31 +0000704}
705
Anna Zaks87cb5be2012-02-22 19:24:52 +0000706ProgramStateRef MallocChecker::MallocMemReturnsAttr(CheckerContext &C,
707 const CallExpr *CE,
708 const OwnershipAttr* Att) {
Sean Huntcf807c42010-08-18 23:23:40 +0000709 if (Att->getModule() != "malloc")
Anna Zaks87cb5be2012-02-22 19:24:52 +0000710 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000711
Sean Huntcf807c42010-08-18 23:23:40 +0000712 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000713 if (I != E) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000714 return MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), C.getState());
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000715 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000716 return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), C.getState());
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000717}
718
Anna Zaksb319e022012-02-08 20:13:28 +0000719ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000720 const CallExpr *CE,
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000721 SVal Size, SVal Init,
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000722 ProgramStateRef State,
723 AllocationFamily Family) {
Anna Zakse17fdb22012-06-07 03:57:32 +0000724
725 // Bind the return value to the symbolic value from the heap region.
726 // TODO: We could rewrite post visit to eval call; 'malloc' does not have
727 // side effects other than what we model here.
Ted Kremenek66c486f2012-08-22 06:26:15 +0000728 unsigned Count = C.blockCount();
Anna Zakse17fdb22012-06-07 03:57:32 +0000729 SValBuilder &svalBuilder = C.getSValBuilder();
730 const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
David Blaikie5251abe2013-02-20 05:52:05 +0000731 DefinedSVal RetVal = svalBuilder.getConjuredHeapSymbolVal(CE, LCtx, Count)
732 .castAs<DefinedSVal>();
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000733 State = State->BindExpr(CE, C.getLocationContext(), RetVal);
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000734
Anna Zaksb16ce452012-02-15 00:11:22 +0000735 // We expect the malloc functions to return a pointer.
David Blaikie5251abe2013-02-20 05:52:05 +0000736 if (!RetVal.getAs<Loc>())
Anna Zaksb16ce452012-02-15 00:11:22 +0000737 return 0;
738
Jordy Rose32f26562010-07-04 00:00:41 +0000739 // Fill the region with the initialization value.
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000740 State = State->bindDefault(RetVal, Init);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000741
Jordy Rose32f26562010-07-04 00:00:41 +0000742 // Set the region's extent equal to the Size parameter.
Anna Zakse9ef5622012-02-10 01:11:00 +0000743 const SymbolicRegion *R =
Anna Zakse17fdb22012-06-07 03:57:32 +0000744 dyn_cast_or_null<SymbolicRegion>(RetVal.getAsRegion());
Anna Zaks60a1fa42012-02-22 03:14:20 +0000745 if (!R)
Anna Zakse9ef5622012-02-10 01:11:00 +0000746 return 0;
David Blaikiedc84cd52013-02-20 22:23:23 +0000747 if (Optional<DefinedOrUnknownSVal> DefinedSize =
David Blaikie5251abe2013-02-20 05:52:05 +0000748 Size.getAs<DefinedOrUnknownSVal>()) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000749 SValBuilder &svalBuilder = C.getSValBuilder();
Anna Zaks60a1fa42012-02-22 03:14:20 +0000750 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
Anna Zaks60a1fa42012-02-22 03:14:20 +0000751 DefinedOrUnknownSVal extentMatchesSize =
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000752 svalBuilder.evalEQ(State, Extent, *DefinedSize);
Anna Zakse9ef5622012-02-10 01:11:00 +0000753
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000754 State = State->assume(extentMatchesSize, true);
755 assert(State);
Anna Zaks60a1fa42012-02-22 03:14:20 +0000756 }
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000757
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000758 return MallocUpdateRefState(C, CE, State, Family);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000759}
760
761ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C,
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000762 const Expr *E,
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000763 ProgramStateRef State,
764 AllocationFamily Family) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000765 // Get the return value.
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000766 SVal retVal = State->getSVal(E, C.getLocationContext());
Anna Zaks87cb5be2012-02-22 19:24:52 +0000767
768 // We expect the malloc functions to return a pointer.
David Blaikie5251abe2013-02-20 05:52:05 +0000769 if (!retVal.getAs<Loc>())
Anna Zaks87cb5be2012-02-22 19:24:52 +0000770 return 0;
771
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000772 SymbolRef Sym = retVal.getAsLocSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000773 assert(Sym);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000774
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000775 // Set the symbol's state to Allocated.
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000776 return State->set<RegionState>(Sym, RefState::getAllocated(Family, E));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000777}
778
Anna Zaks87cb5be2012-02-22 19:24:52 +0000779ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
780 const CallExpr *CE,
781 const OwnershipAttr* Att) const {
Sean Huntcf807c42010-08-18 23:23:40 +0000782 if (Att->getModule() != "malloc")
Anna Zaks87cb5be2012-02-22 19:24:52 +0000783 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000784
Anna Zaksb3d72752012-03-01 22:06:06 +0000785 ProgramStateRef State = C.getState();
Anna Zaks55dd9562012-08-24 02:28:20 +0000786 bool ReleasedAllocated = false;
Anna Zaksb3d72752012-03-01 22:06:06 +0000787
Sean Huntcf807c42010-08-18 23:23:40 +0000788 for (OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
789 I != E; ++I) {
Anna Zaksb3d72752012-03-01 22:06:06 +0000790 ProgramStateRef StateI = FreeMemAux(C, CE, State, *I,
Anna Zaks55dd9562012-08-24 02:28:20 +0000791 Att->getOwnKind() == OwnershipAttr::Holds,
792 ReleasedAllocated);
Anna Zaksb3d72752012-03-01 22:06:06 +0000793 if (StateI)
794 State = StateI;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000795 }
Anna Zaksb3d72752012-03-01 22:06:06 +0000796 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000797}
798
Ted Kremenek8bef8232012-01-26 21:29:00 +0000799ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
Anna Zakse9ef5622012-02-10 01:11:00 +0000800 const CallExpr *CE,
801 ProgramStateRef state,
802 unsigned Num,
Anna Zaks55dd9562012-08-24 02:28:20 +0000803 bool Hold,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000804 bool &ReleasedAllocated,
805 bool ReturnsNullOnFailure) const {
Anna Zaks259052d2012-04-10 23:41:11 +0000806 if (CE->getNumArgs() < (Num + 1))
807 return 0;
808
Anna Zaks4141e4d2012-11-13 03:18:01 +0000809 return FreeMemAux(C, CE->getArg(Num), CE, state, Hold,
810 ReleasedAllocated, ReturnsNullOnFailure);
811}
812
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000813/// Checks if the previous call to free on the given symbol failed - if free
814/// failed, returns true. Also, returns the corresponding return value symbol.
Benjamin Kramer4d9f4e52012-11-22 15:02:44 +0000815static bool didPreviousFreeFail(ProgramStateRef State,
816 SymbolRef Sym, SymbolRef &RetStatusSymbol) {
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000817 const SymbolRef *Ret = State->get<FreeReturnValue>(Sym);
Anna Zaks4141e4d2012-11-13 03:18:01 +0000818 if (Ret) {
819 assert(*Ret && "We should not store the null return symbol");
820 ConstraintManager &CMgr = State->getConstraintManager();
821 ConditionTruthVal FreeFailed = CMgr.isNull(State, *Ret);
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000822 RetStatusSymbol = *Ret;
823 return FreeFailed.isConstrainedTrue();
Anna Zaks4141e4d2012-11-13 03:18:01 +0000824 }
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000825 return false;
Anna Zaks5b7aa342012-06-22 02:04:31 +0000826}
827
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000828AllocationFamily MallocChecker::getAllocationFamily(CheckerContext &C,
829 const Expr *E) const {
830 if (!E)
831 return AF_None;
832
833 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
834 const FunctionDecl *FD = C.getCalleeDecl(CE);
835 ASTContext &Ctx = C.getASTContext();
836
837 if (isFreeFunction(FD, Ctx))
838 return AF_Malloc;
839
840 if (isStandardNewDelete(FD, Ctx)) {
841 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
842 if (Kind == OO_Delete)
843 return AF_CXXNew;
844 else if (Kind == OO_Array_Delete)
845 return AF_CXXNewArray;
846 }
847
848 return AF_None;
849 }
850
851 if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(E))
852 return DE->isArrayForm() ? AF_CXXNewArray : AF_CXXNew;
853
854 if (isa<ObjCMessageExpr>(E))
855 return AF_Malloc;
856
857 return AF_None;
858}
859
860bool MallocChecker::printAllocDeallocName(raw_ostream &os, CheckerContext &C,
861 const Expr *E) const {
862 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
863 // FIXME: This doesn't handle indirect calls.
864 const FunctionDecl *FD = CE->getDirectCallee();
865 if (!FD)
866 return false;
867
868 os << *FD;
869 if (!FD->isOverloadedOperator())
870 os << "()";
871 return true;
872 }
873
874 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E)) {
875 if (Msg->isInstanceMessage())
876 os << "-";
877 else
878 os << "+";
879 os << Msg->getSelector().getAsString();
880 return true;
881 }
882
883 if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(E)) {
884 os << "'"
885 << getOperatorSpelling(NE->getOperatorNew()->getOverloadedOperator())
886 << "'";
887 return true;
888 }
889
890 if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(E)) {
891 os << "'"
892 << getOperatorSpelling(DE->getOperatorDelete()->getOverloadedOperator())
893 << "'";
894 return true;
895 }
896
897 return false;
898}
899
900void MallocChecker::printExpectedAllocName(raw_ostream &os, CheckerContext &C,
901 const Expr *E) const {
902 AllocationFamily Family = getAllocationFamily(C, E);
903
904 switch(Family) {
905 case AF_Malloc: os << "malloc()"; return;
906 case AF_CXXNew: os << "'new'"; return;
907 case AF_CXXNewArray: os << "'new[]'"; return;
908 case AF_None: llvm_unreachable("not a deallocation expression");
909 }
910}
911
912void MallocChecker::printExpectedDeallocName(raw_ostream &os,
913 AllocationFamily Family) const {
914 switch(Family) {
915 case AF_Malloc: os << "free()"; return;
916 case AF_CXXNew: os << "'delete'"; return;
917 case AF_CXXNewArray: os << "'delete[]'"; return;
918 case AF_None: llvm_unreachable("suspicious AF_None argument");
919 }
920}
921
Anna Zaks5b7aa342012-06-22 02:04:31 +0000922ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
923 const Expr *ArgExpr,
924 const Expr *ParentExpr,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000925 ProgramStateRef State,
Anna Zaks55dd9562012-08-24 02:28:20 +0000926 bool Hold,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000927 bool &ReleasedAllocated,
928 bool ReturnsNullOnFailure) const {
Anna Zaks5b7aa342012-06-22 02:04:31 +0000929
Anna Zaks4141e4d2012-11-13 03:18:01 +0000930 SVal ArgVal = State->getSVal(ArgExpr, C.getLocationContext());
David Blaikie5251abe2013-02-20 05:52:05 +0000931 if (!ArgVal.getAs<DefinedOrUnknownSVal>())
Anna Zakse9ef5622012-02-10 01:11:00 +0000932 return 0;
David Blaikie5251abe2013-02-20 05:52:05 +0000933 DefinedOrUnknownSVal location = ArgVal.castAs<DefinedOrUnknownSVal>();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000934
935 // Check for null dereferences.
David Blaikie5251abe2013-02-20 05:52:05 +0000936 if (!location.getAs<Loc>())
Anna Zaksb319e022012-02-08 20:13:28 +0000937 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000938
Anna Zaksb276bd92012-02-14 00:26:13 +0000939 // The explicit NULL case, no operation is performed.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000940 ProgramStateRef notNullState, nullState;
Anna Zaks4141e4d2012-11-13 03:18:01 +0000941 llvm::tie(notNullState, nullState) = State->assume(location);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000942 if (nullState && !notNullState)
Anna Zaksb319e022012-02-08 20:13:28 +0000943 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000944
Jordy Rose43859f62010-06-07 19:32:37 +0000945 // Unknown values could easily be okay
946 // Undefined values are handled elsewhere
947 if (ArgVal.isUnknownOrUndef())
Anna Zaksb319e022012-02-08 20:13:28 +0000948 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000949
Jordy Rose43859f62010-06-07 19:32:37 +0000950 const MemRegion *R = ArgVal.getAsRegion();
951
952 // Nonlocs can't be freed, of course.
953 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
954 if (!R) {
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000955 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
Anna Zaksb319e022012-02-08 20:13:28 +0000956 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000957 }
958
959 R = R->StripCasts();
960
961 // Blocks might show up as heap data, but should not be free()d
962 if (isa<BlockDataRegion>(R)) {
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000963 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
Anna Zaksb319e022012-02-08 20:13:28 +0000964 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000965 }
966
967 const MemSpaceRegion *MS = R->getMemorySpace();
968
Anton Yartsevbb369952013-03-13 14:39:10 +0000969 // Parameters, locals, statics, globals, and memory returned by alloca()
970 // shouldn't be freed.
Jordy Rose43859f62010-06-07 19:32:37 +0000971 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
972 // FIXME: at the time this code was written, malloc() regions were
973 // represented by conjured symbols, which are all in UnknownSpaceRegion.
974 // This means that there isn't actually anything from HeapSpaceRegion
975 // that should be freed, even though we allow it here.
976 // Of course, free() can work on memory allocated outside the current
977 // function, so UnknownSpaceRegion is always a possibility.
978 // False negatives are better than false positives.
979
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000980 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
Anna Zaksb319e022012-02-08 20:13:28 +0000981 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000982 }
Anna Zaks118aa752013-02-07 23:05:47 +0000983
984 const SymbolicRegion *SrBase = dyn_cast<SymbolicRegion>(R->getBaseRegion());
Jordy Rose43859f62010-06-07 19:32:37 +0000985 // Various cases could lead to non-symbol values here.
986 // For now, ignore them.
Anna Zaks118aa752013-02-07 23:05:47 +0000987 if (!SrBase)
Anna Zaksb319e022012-02-08 20:13:28 +0000988 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000989
Anna Zaks118aa752013-02-07 23:05:47 +0000990 SymbolRef SymBase = SrBase->getSymbol();
991 const RefState *RsBase = State->get<RegionState>(SymBase);
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000992 SymbolRef PreviousRetStatusSymbol = 0;
Zhongxing Xu7e3cda92010-01-18 03:27:34 +0000993
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000994 // Check double free.
Anna Zaks118aa752013-02-07 23:05:47 +0000995 if (RsBase &&
996 (RsBase->isReleased() || RsBase->isRelinquished()) &&
997 !didPreviousFreeFail(State, SymBase, PreviousRetStatusSymbol)) {
Anton Yartsevbb369952013-03-13 14:39:10 +0000998 ReportDoubleFree(C, ParentExpr->getSourceRange(), RsBase->isReleased(),
999 SymBase, PreviousRetStatusSymbol);
Anna Zaksb319e022012-02-08 20:13:28 +00001000 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +00001001 }
1002
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001003 // Check if an expected deallocation function matches the real one.
1004 if (RsBase &&
1005 RsBase->getAllocationFamily() != AF_None &&
1006 RsBase->getAllocationFamily() != getAllocationFamily(C, ParentExpr) ) {
1007 ReportBadDealloc(C, ArgExpr->getSourceRange(), ParentExpr, RsBase);
1008 return 0;
1009 }
1010
Anna Zaks118aa752013-02-07 23:05:47 +00001011 // Check if the memory location being freed is the actual location
1012 // allocated, or an offset.
1013 RegionOffset Offset = R->getAsOffset();
1014 if (RsBase && RsBase->isAllocated() &&
1015 Offset.isValid() &&
1016 !Offset.hasSymbolicOffset() &&
1017 Offset.getOffset() != 0) {
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001018 const Expr *AllocExpr = cast<Expr>(RsBase->getStmt());
1019 ReportOffsetFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr,
1020 AllocExpr);
Anna Zaks118aa752013-02-07 23:05:47 +00001021 return 0;
1022 }
1023
1024 ReleasedAllocated = (RsBase != 0);
Anna Zaks55dd9562012-08-24 02:28:20 +00001025
Anna Zaks2ccecfa2012-11-13 19:47:40 +00001026 // Clean out the info on previous call to free return info.
Anna Zaks118aa752013-02-07 23:05:47 +00001027 State = State->remove<FreeReturnValue>(SymBase);
Anna Zaks2ccecfa2012-11-13 19:47:40 +00001028
Anna Zaks4141e4d2012-11-13 03:18:01 +00001029 // Keep track of the return value. If it is NULL, we will know that free
1030 // failed.
1031 if (ReturnsNullOnFailure) {
1032 SVal RetVal = C.getSVal(ParentExpr);
1033 SymbolRef RetStatusSymbol = RetVal.getAsSymbol();
1034 if (RetStatusSymbol) {
Anna Zaks118aa752013-02-07 23:05:47 +00001035 C.getSymbolManager().addSymbolDependency(SymBase, RetStatusSymbol);
1036 State = State->set<FreeReturnValue>(SymBase, RetStatusSymbol);
Anna Zaks4141e4d2012-11-13 03:18:01 +00001037 }
1038 }
1039
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001040 AllocationFamily Family = RsBase ? RsBase->getAllocationFamily() : AF_None;
Zhongxing Xu589c0f22009-11-12 08:38:56 +00001041 // Normal free.
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001042 if (Hold)
Anna Zaks118aa752013-02-07 23:05:47 +00001043 return State->set<RegionState>(SymBase,
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001044 RefState::getRelinquished(Family,
1045 ParentExpr));
1046
1047 return State->set<RegionState>(SymBase,
1048 RefState::getReleased(Family, ParentExpr));
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001049}
1050
Ted Kremenek9c378f72011-08-12 23:37:29 +00001051bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
David Blaikiedc84cd52013-02-20 22:23:23 +00001052 if (Optional<nonloc::ConcreteInt> IntVal = V.getAs<nonloc::ConcreteInt>())
Jordy Rose43859f62010-06-07 19:32:37 +00001053 os << "an integer (" << IntVal->getValue() << ")";
David Blaikiedc84cd52013-02-20 22:23:23 +00001054 else if (Optional<loc::ConcreteInt> ConstAddr = V.getAs<loc::ConcreteInt>())
Jordy Rose43859f62010-06-07 19:32:37 +00001055 os << "a constant address (" << ConstAddr->getValue() << ")";
David Blaikiedc84cd52013-02-20 22:23:23 +00001056 else if (Optional<loc::GotoLabel> Label = V.getAs<loc::GotoLabel>())
Chris Lattner68106302011-02-17 05:38:27 +00001057 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose43859f62010-06-07 19:32:37 +00001058 else
1059 return false;
1060
1061 return true;
1062}
1063
Ted Kremenek9c378f72011-08-12 23:37:29 +00001064bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose43859f62010-06-07 19:32:37 +00001065 const MemRegion *MR) {
1066 switch (MR->getKind()) {
1067 case MemRegion::FunctionTextRegionKind: {
Anna Zaks5fc1d0c2012-09-17 19:13:56 +00001068 const NamedDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
Jordy Rose43859f62010-06-07 19:32:37 +00001069 if (FD)
Benjamin Kramerb8989f22011-10-14 18:45:37 +00001070 os << "the address of the function '" << *FD << '\'';
Jordy Rose43859f62010-06-07 19:32:37 +00001071 else
1072 os << "the address of a function";
1073 return true;
1074 }
1075 case MemRegion::BlockTextRegionKind:
1076 os << "block text";
1077 return true;
1078 case MemRegion::BlockDataRegionKind:
1079 // FIXME: where the block came from?
1080 os << "a block";
1081 return true;
1082 default: {
1083 const MemSpaceRegion *MS = MR->getMemorySpace();
1084
Anna Zakseb31a762012-01-04 23:54:01 +00001085 if (isa<StackLocalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +00001086 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1087 const VarDecl *VD;
1088 if (VR)
1089 VD = VR->getDecl();
1090 else
1091 VD = NULL;
1092
1093 if (VD)
1094 os << "the address of the local variable '" << VD->getName() << "'";
1095 else
1096 os << "the address of a local stack variable";
1097 return true;
1098 }
Anna Zakseb31a762012-01-04 23:54:01 +00001099
1100 if (isa<StackArgumentsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +00001101 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1102 const VarDecl *VD;
1103 if (VR)
1104 VD = VR->getDecl();
1105 else
1106 VD = NULL;
1107
1108 if (VD)
1109 os << "the address of the parameter '" << VD->getName() << "'";
1110 else
1111 os << "the address of a parameter";
1112 return true;
1113 }
Anna Zakseb31a762012-01-04 23:54:01 +00001114
1115 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +00001116 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1117 const VarDecl *VD;
1118 if (VR)
1119 VD = VR->getDecl();
1120 else
1121 VD = NULL;
1122
1123 if (VD) {
1124 if (VD->isStaticLocal())
1125 os << "the address of the static variable '" << VD->getName() << "'";
1126 else
1127 os << "the address of the global variable '" << VD->getName() << "'";
1128 } else
1129 os << "the address of a global variable";
1130 return true;
1131 }
Anna Zakseb31a762012-01-04 23:54:01 +00001132
1133 return false;
Jordy Rose43859f62010-06-07 19:32:37 +00001134 }
1135 }
1136}
1137
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001138void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
1139 SourceRange Range,
1140 const Expr *DeallocExpr) const {
1141
1142 if (!Filter.CMallocOptimistic && !Filter.CMallocPessimistic &&
1143 !Filter.CNewDeleteChecker)
1144 return;
1145
Ted Kremenekd048c6e2010-12-20 21:19:09 +00001146 if (ExplodedNode *N = C.generateSink()) {
Jordy Rose43859f62010-06-07 19:32:37 +00001147 if (!BT_BadFree)
Anna Zaksfebdc322012-02-16 22:26:12 +00001148 BT_BadFree.reset(new BugType("Bad free", "Memory Error"));
Jordy Rose43859f62010-06-07 19:32:37 +00001149
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00001150 SmallString<100> buf;
Jordy Rose43859f62010-06-07 19:32:37 +00001151 llvm::raw_svector_ostream os(buf);
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001152
Jordy Rose43859f62010-06-07 19:32:37 +00001153 const MemRegion *MR = ArgVal.getAsRegion();
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001154 while (const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(MR))
1155 MR = ER->getSuperRegion();
1156
1157 if (MR && isa<AllocaRegion>(MR))
1158 os << "Memory allocated by alloca() should not be deallocated";
1159 else {
1160 os << "Argument to ";
1161 if (!printAllocDeallocName(os, C, DeallocExpr))
1162 os << "deallocator";
1163
1164 os << " is ";
1165 bool Summarized = MR ? SummarizeRegion(os, MR)
1166 : SummarizeValue(os, ArgVal);
1167 if (Summarized)
1168 os << ", which is not memory allocated by ";
Jordy Rose43859f62010-06-07 19:32:37 +00001169 else
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001170 os << "not memory allocated by ";
1171
1172 printExpectedAllocName(os, C, DeallocExpr);
Jordy Rose43859f62010-06-07 19:32:37 +00001173 }
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001174
Anna Zakse172e8b2011-08-17 23:00:25 +00001175 BugReport *R = new BugReport(*BT_BadFree, os.str(), N);
Ted Kremenek76aadc32012-03-09 01:13:14 +00001176 R->markInteresting(MR);
Anton Yartsevbb369952013-03-13 14:39:10 +00001177 R->addRange(Range);
Jordan Rose785950e2012-11-02 01:53:40 +00001178 C.emitReport(R);
Jordy Rose43859f62010-06-07 19:32:37 +00001179 }
1180}
1181
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001182void MallocChecker::ReportBadDealloc(CheckerContext &C, SourceRange Range,
1183 const Expr *DeallocExpr,
1184 const RefState *RS) const {
1185
1186 if (!Filter.CMismatchedDeallocatorChecker)
1187 return;
1188
1189 if (ExplodedNode *N = C.generateSink()) {
1190 if (!BT_BadDealloc)
1191 BT_BadDealloc.reset(new BugType("Bad deallocator", "Memory Error"));
1192
1193 SmallString<100> buf;
1194 llvm::raw_svector_ostream os(buf);
1195
1196 const Expr *AllocExpr = cast<Expr>(RS->getStmt());
1197 SmallString<20> AllocBuf;
1198 llvm::raw_svector_ostream AllocOs(AllocBuf);
1199 SmallString<20> DeallocBuf;
1200 llvm::raw_svector_ostream DeallocOs(DeallocBuf);
1201
1202 os << "Memory";
1203 if (printAllocDeallocName(AllocOs, C, AllocExpr))
1204 os << " allocated by " << AllocOs.str();
1205
1206 os << " should be deallocated by ";
1207 printExpectedDeallocName(os, RS->getAllocationFamily());
1208
1209 if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1210 os << ", not " << DeallocOs.str();
1211
1212 BugReport *R = new BugReport(*BT_BadDealloc, os.str(), N);
1213 R->addRange(Range);
1214 C.emitReport(R);
1215 }
1216}
1217
Anna Zaks118aa752013-02-07 23:05:47 +00001218void MallocChecker::ReportOffsetFree(CheckerContext &C, SVal ArgVal,
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001219 SourceRange Range, const Expr *DeallocExpr,
1220 const Expr *AllocExpr) const {
1221
1222 if (!Filter.CMallocOptimistic && !Filter.CMallocPessimistic &&
1223 !Filter.CNewDeleteChecker)
1224 return;
1225
Anna Zaks118aa752013-02-07 23:05:47 +00001226 ExplodedNode *N = C.generateSink();
1227 if (N == NULL)
1228 return;
1229
1230 if (!BT_OffsetFree)
1231 BT_OffsetFree.reset(new BugType("Offset free", "Memory Error"));
1232
1233 SmallString<100> buf;
1234 llvm::raw_svector_ostream os(buf);
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001235 SmallString<20> AllocNameBuf;
1236 llvm::raw_svector_ostream AllocNameOs(AllocNameBuf);
Anna Zaks118aa752013-02-07 23:05:47 +00001237
1238 const MemRegion *MR = ArgVal.getAsRegion();
1239 assert(MR && "Only MemRegion based symbols can have offset free errors");
1240
1241 RegionOffset Offset = MR->getAsOffset();
1242 assert((Offset.isValid() &&
1243 !Offset.hasSymbolicOffset() &&
1244 Offset.getOffset() != 0) &&
1245 "Only symbols with a valid offset can have offset free errors");
1246
1247 int offsetBytes = Offset.getOffset() / C.getASTContext().getCharWidth();
1248
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001249 os << "Argument to ";
1250 if (!printAllocDeallocName(os, C, DeallocExpr))
1251 os << "deallocator";
1252 os << " is offset by "
Anna Zaks118aa752013-02-07 23:05:47 +00001253 << offsetBytes
1254 << " "
1255 << ((abs(offsetBytes) > 1) ? "bytes" : "byte")
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001256 << " from the start of ";
1257 if (AllocExpr && printAllocDeallocName(AllocNameOs, C, AllocExpr))
1258 os << "memory allocated by " << AllocNameOs.str();
1259 else
1260 os << "allocated memory";
Anna Zaks118aa752013-02-07 23:05:47 +00001261
1262 BugReport *R = new BugReport(*BT_OffsetFree, os.str(), N);
1263 R->markInteresting(MR->getBaseRegion());
1264 R->addRange(Range);
1265 C.emitReport(R);
1266}
1267
Anton Yartsevbb369952013-03-13 14:39:10 +00001268void MallocChecker::ReportUseAfterFree(CheckerContext &C, SourceRange Range,
1269 SymbolRef Sym) const {
1270
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001271 if (!Filter.CMallocOptimistic && !Filter.CMallocPessimistic &&
1272 !Filter.CNewDeleteChecker)
1273 return;
1274
Anton Yartsevbb369952013-03-13 14:39:10 +00001275 if (ExplodedNode *N = C.generateSink()) {
1276 if (!BT_UseFree)
1277 BT_UseFree.reset(new BugType("Use-after-free", "Memory Error"));
1278
1279 BugReport *R = new BugReport(*BT_UseFree,
1280 "Use of memory after it is freed", N);
1281
1282 R->markInteresting(Sym);
1283 R->addRange(Range);
1284 R->addVisitor(new MallocBugVisitor(Sym));
1285 C.emitReport(R);
1286 }
1287}
1288
1289void MallocChecker::ReportDoubleFree(CheckerContext &C, SourceRange Range,
1290 bool Released, SymbolRef Sym,
Anton Yartsev3258d4b2013-03-13 17:07:32 +00001291 SymbolRef PrevSym) const {
Anton Yartsevbb369952013-03-13 14:39:10 +00001292
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001293 if (!Filter.CMallocOptimistic && !Filter.CMallocPessimistic &&
1294 !Filter.CNewDeleteChecker)
1295 return;
1296
Anton Yartsevbb369952013-03-13 14:39:10 +00001297 if (ExplodedNode *N = C.generateSink()) {
1298 if (!BT_DoubleFree)
1299 BT_DoubleFree.reset(new BugType("Double free", "Memory Error"));
1300
1301 BugReport *R = new BugReport(*BT_DoubleFree,
1302 (Released ? "Attempt to free released memory"
1303 : "Attempt to free non-owned memory"),
1304 N);
1305 R->addRange(Range);
Anton Yartsev3258d4b2013-03-13 17:07:32 +00001306 R->markInteresting(Sym);
1307 if (PrevSym)
1308 R->markInteresting(PrevSym);
Anton Yartsevbb369952013-03-13 14:39:10 +00001309 R->addVisitor(new MallocBugVisitor(Sym));
1310 C.emitReport(R);
1311 }
1312}
1313
Anna Zaks87cb5be2012-02-22 19:24:52 +00001314ProgramStateRef MallocChecker::ReallocMem(CheckerContext &C,
1315 const CallExpr *CE,
1316 bool FreesOnFail) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001317 if (CE->getNumArgs() < 2)
1318 return 0;
1319
Ted Kremenek8bef8232012-01-26 21:29:00 +00001320 ProgramStateRef state = C.getState();
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001321 const Expr *arg0Expr = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001322 const LocationContext *LCtx = C.getLocationContext();
Anna Zakse9ef5622012-02-10 01:11:00 +00001323 SVal Arg0Val = state->getSVal(arg0Expr, LCtx);
David Blaikie5251abe2013-02-20 05:52:05 +00001324 if (!Arg0Val.getAs<DefinedOrUnknownSVal>())
Anna Zaks87cb5be2012-02-22 19:24:52 +00001325 return 0;
David Blaikie5251abe2013-02-20 05:52:05 +00001326 DefinedOrUnknownSVal arg0Val = Arg0Val.castAs<DefinedOrUnknownSVal>();
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001327
Ted Kremenek846eabd2010-12-01 21:28:31 +00001328 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001329
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001330 DefinedOrUnknownSVal PtrEQ =
1331 svalBuilder.evalEQ(state, arg0Val, svalBuilder.makeNull());
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001332
Lenny Maiorani4d8d8032011-04-27 14:49:29 +00001333 // Get the size argument. If there is no size arg then give up.
1334 const Expr *Arg1 = CE->getArg(1);
1335 if (!Arg1)
Anna Zaks87cb5be2012-02-22 19:24:52 +00001336 return 0;
Lenny Maiorani4d8d8032011-04-27 14:49:29 +00001337
1338 // Get the value of the size argument.
Anna Zakse9ef5622012-02-10 01:11:00 +00001339 SVal Arg1ValG = state->getSVal(Arg1, LCtx);
David Blaikie5251abe2013-02-20 05:52:05 +00001340 if (!Arg1ValG.getAs<DefinedOrUnknownSVal>())
Anna Zaks87cb5be2012-02-22 19:24:52 +00001341 return 0;
David Blaikie5251abe2013-02-20 05:52:05 +00001342 DefinedOrUnknownSVal Arg1Val = Arg1ValG.castAs<DefinedOrUnknownSVal>();
Lenny Maiorani4d8d8032011-04-27 14:49:29 +00001343
1344 // Compare the size argument to 0.
1345 DefinedOrUnknownSVal SizeZero =
1346 svalBuilder.evalEQ(state, Arg1Val,
1347 svalBuilder.makeIntValWithPtrWidth(0, false));
1348
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001349 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
1350 llvm::tie(StatePtrIsNull, StatePtrNotNull) = state->assume(PtrEQ);
1351 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
1352 llvm::tie(StateSizeIsZero, StateSizeNotZero) = state->assume(SizeZero);
1353 // We only assume exceptional states if they are definitely true; if the
1354 // state is under-constrained, assume regular realloc behavior.
1355 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
1356 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
1357
Lenny Maiorani4d8d8032011-04-27 14:49:29 +00001358 // If the ptr is NULL and the size is not 0, the call is equivalent to
1359 // malloc(size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001360 if ( PrtIsNull && !SizeIsZero) {
Anna Zaks87cb5be2012-02-22 19:24:52 +00001361 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001362 UndefinedVal(), StatePtrIsNull);
Anna Zaks87cb5be2012-02-22 19:24:52 +00001363 return stateMalloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001364 }
1365
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001366 if (PrtIsNull && SizeIsZero)
Anna Zaks87cb5be2012-02-22 19:24:52 +00001367 return 0;
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001368
Anna Zaks30838b92012-02-13 20:57:07 +00001369 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001370 assert(!PrtIsNull);
Anna Zaks30838b92012-02-13 20:57:07 +00001371 SymbolRef FromPtr = arg0Val.getAsSymbol();
1372 SVal RetVal = state->getSVal(CE, LCtx);
1373 SymbolRef ToPtr = RetVal.getAsSymbol();
1374 if (!FromPtr || !ToPtr)
Anna Zaks87cb5be2012-02-22 19:24:52 +00001375 return 0;
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001376
Anna Zaks55dd9562012-08-24 02:28:20 +00001377 bool ReleasedAllocated = false;
1378
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001379 // If the size is 0, free the memory.
1380 if (SizeIsZero)
Anna Zaks55dd9562012-08-24 02:28:20 +00001381 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero, 0,
1382 false, ReleasedAllocated)){
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001383 // The semantics of the return value are:
1384 // If size was equal to 0, either NULL or a pointer suitable to be passed
Anna Zaksede875b2012-08-03 18:30:18 +00001385 // to free() is returned. We just free the input pointer and do not add
1386 // any constrains on the output pointer.
Anna Zaks87cb5be2012-02-22 19:24:52 +00001387 return stateFree;
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001388 }
1389
1390 // Default behavior.
Anna Zaks55dd9562012-08-24 02:28:20 +00001391 if (ProgramStateRef stateFree =
1392 FreeMemAux(C, CE, state, 0, false, ReleasedAllocated)) {
1393
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001394 ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
1395 UnknownVal(), stateFree);
Anna Zaks30838b92012-02-13 20:57:07 +00001396 if (!stateRealloc)
Anna Zaks87cb5be2012-02-22 19:24:52 +00001397 return 0;
Anna Zaks55dd9562012-08-24 02:28:20 +00001398
Anna Zaks9dc298b2012-09-12 22:57:34 +00001399 ReallocPairKind Kind = RPToBeFreedAfterFailure;
1400 if (FreesOnFail)
1401 Kind = RPIsFreeOnFailure;
1402 else if (!ReleasedAllocated)
1403 Kind = RPDoNotTrackAfterFailure;
1404
Anna Zaks55dd9562012-08-24 02:28:20 +00001405 // Record the info about the reallocated symbol so that we could properly
1406 // process failed reallocation.
Anna Zaks40add292012-02-15 00:11:25 +00001407 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
Anna Zaks9dc298b2012-09-12 22:57:34 +00001408 ReallocPair(FromPtr, Kind));
Anna Zaks55dd9562012-08-24 02:28:20 +00001409 // The reallocated symbol should stay alive for as long as the new symbol.
Anna Zaksb276bd92012-02-14 00:26:13 +00001410 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks87cb5be2012-02-22 19:24:52 +00001411 return stateRealloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001412 }
Anna Zaks87cb5be2012-02-22 19:24:52 +00001413 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +00001414}
Zhongxing Xu7b760962009-11-13 07:25:27 +00001415
Anna Zaks87cb5be2012-02-22 19:24:52 +00001416ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE){
Anna Zaks259052d2012-04-10 23:41:11 +00001417 if (CE->getNumArgs() < 2)
1418 return 0;
1419
Ted Kremenek8bef8232012-01-26 21:29:00 +00001420 ProgramStateRef state = C.getState();
Ted Kremenek846eabd2010-12-01 21:28:31 +00001421 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001422 const LocationContext *LCtx = C.getLocationContext();
1423 SVal count = state->getSVal(CE->getArg(0), LCtx);
1424 SVal elementSize = state->getSVal(CE->getArg(1), LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001425 SVal TotalSize = svalBuilder.evalBinOp(state, BO_Mul, count, elementSize,
1426 svalBuilder.getContext().getSizeType());
1427 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Zhongxing Xua5ce9662010-06-01 03:01:33 +00001428
Anna Zaks87cb5be2012-02-22 19:24:52 +00001429 return MallocMemAux(C, CE, TotalSize, zeroVal, state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +00001430}
1431
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001432LeakInfo
Anna Zaksca8e36e2012-02-23 21:38:21 +00001433MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
1434 CheckerContext &C) const {
Anna Zaks7752d292012-02-27 23:40:55 +00001435 const LocationContext *LeakContext = N->getLocationContext();
Anna Zaksca8e36e2012-02-23 21:38:21 +00001436 // Walk the ExplodedGraph backwards and find the first node that referred to
1437 // the tracked symbol.
1438 const ExplodedNode *AllocNode = N;
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001439 const MemRegion *ReferenceRegion = 0;
Anna Zaksca8e36e2012-02-23 21:38:21 +00001440
1441 while (N) {
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001442 ProgramStateRef State = N->getState();
1443 if (!State->get<RegionState>(Sym))
Anna Zaksca8e36e2012-02-23 21:38:21 +00001444 break;
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001445
1446 // Find the most recent expression bound to the symbol in the current
1447 // context.
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001448 if (!ReferenceRegion) {
Benjamin Kramer850f1b12012-03-21 21:03:48 +00001449 if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
1450 SVal Val = State->getSVal(MR);
1451 if (Val.getAsLocSymbol() == Sym)
1452 ReferenceRegion = MR;
1453 }
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001454 }
1455
Anna Zaks7752d292012-02-27 23:40:55 +00001456 // Allocation node, is the last node in the current context in which the
1457 // symbol was tracked.
1458 if (N->getLocationContext() == LeakContext)
1459 AllocNode = N;
Anna Zaksca8e36e2012-02-23 21:38:21 +00001460 N = N->pred_empty() ? NULL : *(N->pred_begin());
1461 }
1462
Anna Zaks97bfb552013-01-08 00:25:29 +00001463 return LeakInfo(AllocNode, ReferenceRegion);
Anna Zaksca8e36e2012-02-23 21:38:21 +00001464}
1465
Anna Zaksda046772012-02-11 21:02:40 +00001466void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
1467 CheckerContext &C) const {
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001468
1469 if (!Filter.CMallocOptimistic && !Filter.CMallocPessimistic &&
1470 !Filter.CNewDeleteChecker)
1471 return;
1472
Anna Zaksda046772012-02-11 21:02:40 +00001473 assert(N);
1474 if (!BT_Leak) {
Anna Zaksfebdc322012-02-16 22:26:12 +00001475 BT_Leak.reset(new BugType("Memory leak", "Memory Error"));
Anna Zaksda046772012-02-11 21:02:40 +00001476 // Leaks should not be reported if they are post-dominated by a sink:
1477 // (1) Sinks are higher importance bugs.
1478 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
1479 // with __noreturn functions such as assert() or exit(). We choose not
1480 // to report leaks on such paths.
1481 BT_Leak->setSuppressOnSink(true);
1482 }
1483
Anna Zaksca8e36e2012-02-23 21:38:21 +00001484 // Most bug reports are cached at the location where they occurred.
1485 // With leaks, we want to unique them by the location where they were
1486 // allocated, and only report a single path.
Anna Zaks7752d292012-02-27 23:40:55 +00001487 PathDiagnosticLocation LocUsedForUniqueing;
Anna Zaks97bfb552013-01-08 00:25:29 +00001488 const ExplodedNode *AllocNode = 0;
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001489 const MemRegion *Region = 0;
Anna Zaks97bfb552013-01-08 00:25:29 +00001490 llvm::tie(AllocNode, Region) = getAllocationSite(N, Sym, C);
1491
1492 ProgramPoint P = AllocNode->getLocation();
1493 const Stmt *AllocationStmt = 0;
David Blaikie7a95de62013-02-21 22:23:56 +00001494 if (Optional<CallExitEnd> Exit = P.getAs<CallExitEnd>())
Anna Zaks97bfb552013-01-08 00:25:29 +00001495 AllocationStmt = Exit->getCalleeContext()->getCallSite();
David Blaikie7a95de62013-02-21 22:23:56 +00001496 else if (Optional<StmtPoint> SP = P.getAs<StmtPoint>())
Anna Zaks97bfb552013-01-08 00:25:29 +00001497 AllocationStmt = SP->getStmt();
1498 if (AllocationStmt)
1499 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocationStmt,
1500 C.getSourceManager(),
1501 AllocNode->getLocationContext());
Anna Zaksca8e36e2012-02-23 21:38:21 +00001502
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001503 SmallString<200> buf;
1504 llvm::raw_svector_ostream os(buf);
1505 os << "Memory is never released; potential leak";
Jordan Rose919e8a12012-08-08 18:23:36 +00001506 if (Region && Region->canPrintPretty()) {
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001507 os << " of memory pointed to by '";
Jordan Rose919e8a12012-08-08 18:23:36 +00001508 Region->printPretty(os);
Jordan Rose0d53ab42012-08-08 18:23:31 +00001509 os << '\'';
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001510 }
1511
Anna Zaks97bfb552013-01-08 00:25:29 +00001512 BugReport *R = new BugReport(*BT_Leak, os.str(), N,
1513 LocUsedForUniqueing,
1514 AllocNode->getLocationContext()->getDecl());
Ted Kremenek76aadc32012-03-09 01:13:14 +00001515 R->markInteresting(Sym);
Anna Zaks88feba02012-05-10 01:37:40 +00001516 R->addVisitor(new MallocBugVisitor(Sym, true));
Jordan Rose785950e2012-11-02 01:53:40 +00001517 C.emitReport(R);
Anna Zaksda046772012-02-11 21:02:40 +00001518}
1519
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001520void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
1521 CheckerContext &C) const
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001522{
Zhongxing Xu173ff562010-08-15 08:19:57 +00001523 if (!SymReaper.hasDeadSymbols())
1524 return;
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +00001525
Ted Kremenek8bef8232012-01-26 21:29:00 +00001526 ProgramStateRef state = C.getState();
Zhongxing Xu173ff562010-08-15 08:19:57 +00001527 RegionStateTy RS = state->get<RegionState>();
Jordy Rose90760142010-08-18 04:33:47 +00001528 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xu173ff562010-08-15 08:19:57 +00001529
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001530 SmallVector<SymbolRef, 2> Errors;
Zhongxing Xu173ff562010-08-15 08:19:57 +00001531 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
1532 if (SymReaper.isDead(I->first)) {
Anna Zaks54458702012-10-29 22:51:54 +00001533 if (I->second.isAllocated())
Anna Zaksf8c17b72012-02-09 06:48:19 +00001534 Errors.push_back(I->first);
Jordy Rose90760142010-08-18 04:33:47 +00001535 // Remove the dead symbol from the map.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001536 RS = F.remove(RS, I->first);
Ted Kremenek217470e2011-07-28 23:07:51 +00001537
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +00001538 }
1539 }
Ted Kremenek217470e2011-07-28 23:07:51 +00001540
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001541 // Cleanup the Realloc Pairs Map.
Jordan Rose166d5022012-11-02 01:54:06 +00001542 ReallocPairsTy RP = state->get<ReallocPairs>();
1543 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Anna Zaks40add292012-02-15 00:11:25 +00001544 if (SymReaper.isDead(I->first) ||
1545 SymReaper.isDead(I->second.ReallocatedSym)) {
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001546 state = state->remove<ReallocPairs>(I->first);
1547 }
1548 }
1549
Anna Zaks4141e4d2012-11-13 03:18:01 +00001550 // Cleanup the FreeReturnValue Map.
1551 FreeReturnValueTy FR = state->get<FreeReturnValue>();
1552 for (FreeReturnValueTy::iterator I = FR.begin(), E = FR.end(); I != E; ++I) {
1553 if (SymReaper.isDead(I->first) ||
1554 SymReaper.isDead(I->second)) {
1555 state = state->remove<FreeReturnValue>(I->first);
1556 }
1557 }
1558
Anna Zaksca8e36e2012-02-23 21:38:21 +00001559 // Generate leak node.
Anna Zaks54458702012-10-29 22:51:54 +00001560 ExplodedNode *N = C.getPredecessor();
1561 if (!Errors.empty()) {
1562 static SimpleProgramPointTag Tag("MallocChecker : DeadSymbolsLeak");
1563 N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001564 for (SmallVector<SymbolRef, 2>::iterator
Anna Zaks54458702012-10-29 22:51:54 +00001565 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
Anna Zaksda046772012-02-11 21:02:40 +00001566 reportLeak(*I, N, C);
Anna Zaksf8c17b72012-02-09 06:48:19 +00001567 }
Ted Kremenek217470e2011-07-28 23:07:51 +00001568 }
Anna Zaks54458702012-10-29 22:51:54 +00001569
Anna Zaksca8e36e2012-02-23 21:38:21 +00001570 C.addTransition(state->set<RegionState>(RS), N);
Zhongxing Xu7b760962009-11-13 07:25:27 +00001571}
Zhongxing Xu243fde92009-11-17 07:54:15 +00001572
Anna Zaks66c40402012-02-14 21:55:24 +00001573void MallocChecker::checkPreStmt(const CallExpr *CE, CheckerContext &C) const {
Anna Zaks14345182012-05-18 01:16:10 +00001574 // We will check for double free in the post visit.
Anton Yartsev2de19ed2013-03-25 01:35:45 +00001575 if ((Filter.CMallocOptimistic || Filter.CMallocPessimistic) &&
1576 isFreeFunction(C.getCalleeDecl(CE), C.getASTContext()))
1577 return;
1578
1579 if (Filter.CNewDeleteChecker &&
1580 isStandardNewDelete(C.getCalleeDecl(CE), C.getASTContext()))
Anna Zaks66c40402012-02-14 21:55:24 +00001581 return;
1582
1583 // Check use after free, when a freed pointer is passed to a call.
1584 ProgramStateRef State = C.getState();
1585 for (CallExpr::const_arg_iterator I = CE->arg_begin(),
1586 E = CE->arg_end(); I != E; ++I) {
1587 const Expr *A = *I;
1588 if (A->getType().getTypePtr()->isAnyPointerType()) {
Anton Yartsevbb369952013-03-13 14:39:10 +00001589 SymbolRef Sym = C.getSVal(A).getAsSymbol();
Anna Zaks66c40402012-02-14 21:55:24 +00001590 if (!Sym)
1591 continue;
1592 if (checkUseAfterFree(Sym, C, A))
1593 return;
1594 }
1595 }
1596}
1597
Anna Zaks91c2a112012-02-08 23:16:56 +00001598void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
1599 const Expr *E = S->getRetValue();
1600 if (!E)
1601 return;
Anna Zaks0860cd02012-02-11 21:44:39 +00001602
1603 // Check if we are returning a symbol.
Jordan Rose0d53ab42012-08-08 18:23:31 +00001604 ProgramStateRef State = C.getState();
1605 SVal RetVal = State->getSVal(E, C.getLocationContext());
Anna Zaksd9ab7bb2012-02-22 02:36:01 +00001606 SymbolRef Sym = RetVal.getAsSymbol();
1607 if (!Sym)
1608 // If we are returning a field of the allocated struct or an array element,
1609 // the callee could still free the memory.
1610 // TODO: This logic should be a part of generic symbol escape callback.
1611 if (const MemRegion *MR = RetVal.getAsRegion())
1612 if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
1613 if (const SymbolicRegion *BMR =
1614 dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
1615 Sym = BMR->getSymbol();
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001616
Anna Zaks0860cd02012-02-11 21:44:39 +00001617 // Check if we are returning freed memory.
Jordan Rose0d53ab42012-08-08 18:23:31 +00001618 if (Sym)
Jordan Rose65d4bd62012-11-15 19:11:33 +00001619 checkUseAfterFree(Sym, C, E);
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001620}
Zhongxing Xub94b81a2009-12-31 06:13:07 +00001621
Anna Zaksf5aa3f52012-03-22 00:57:20 +00001622// TODO: Blocks should be either inlined or should call invalidate regions
1623// upon invocation. After that's in place, special casing here will not be
1624// needed.
1625void MallocChecker::checkPostStmt(const BlockExpr *BE,
1626 CheckerContext &C) const {
1627
1628 // Scan the BlockDecRefExprs for any object the retain count checker
1629 // may be tracking.
1630 if (!BE->getBlockDecl()->hasCaptures())
1631 return;
1632
1633 ProgramStateRef state = C.getState();
1634 const BlockDataRegion *R =
1635 cast<BlockDataRegion>(state->getSVal(BE,
1636 C.getLocationContext()).getAsRegion());
1637
1638 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
1639 E = R->referenced_vars_end();
1640
1641 if (I == E)
1642 return;
1643
1644 SmallVector<const MemRegion*, 10> Regions;
1645 const LocationContext *LC = C.getLocationContext();
1646 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
1647
1648 for ( ; I != E; ++I) {
Ted Kremeneke3ce2c12012-12-06 07:17:20 +00001649 const VarRegion *VR = I.getCapturedRegion();
Anna Zaksf5aa3f52012-03-22 00:57:20 +00001650 if (VR->getSuperRegion() == R) {
1651 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
1652 }
1653 Regions.push_back(VR);
1654 }
1655
1656 state =
1657 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
1658 Regions.data() + Regions.size()).getState();
1659 C.addTransition(state);
1660}
1661
Anna Zaks14345182012-05-18 01:16:10 +00001662bool MallocChecker::isReleased(SymbolRef Sym, CheckerContext &C) const {
Anna Zaks91c2a112012-02-08 23:16:56 +00001663 assert(Sym);
1664 const RefState *RS = C.getState()->get<RegionState>(Sym);
Anna Zaks14345182012-05-18 01:16:10 +00001665 return (RS && RS->isReleased());
1666}
1667
1668bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
1669 const Stmt *S) const {
Anna Zaks91c2a112012-02-08 23:16:56 +00001670
Anton Yartsevbb369952013-03-13 14:39:10 +00001671 if (isReleased(Sym, C)) {
1672 ReportUseAfterFree(C, S->getSourceRange(), Sym);
1673 return true;
Anna Zaks91c2a112012-02-08 23:16:56 +00001674 }
Anton Yartsevbb369952013-03-13 14:39:10 +00001675
Anna Zaks91c2a112012-02-08 23:16:56 +00001676 return false;
1677}
1678
Zhongxing Xuc8023782010-03-10 04:58:55 +00001679// Check if the location is a freed symbolic region.
Anna Zaks390909c2011-10-06 00:43:15 +00001680void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
1681 CheckerContext &C) const {
Zhongxing Xuc8023782010-03-10 04:58:55 +00001682 SymbolRef Sym = l.getLocSymbolInBase();
Anna Zaks91c2a112012-02-08 23:16:56 +00001683 if (Sym)
Anna Zaks14345182012-05-18 01:16:10 +00001684 checkUseAfterFree(Sym, C, S);
Zhongxing Xuc8023782010-03-10 04:58:55 +00001685}
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001686
Anna Zaks4fb54872012-02-11 21:02:35 +00001687// If a symbolic region is assumed to NULL (or another constant), stop tracking
1688// it - assuming that allocation failed on this path.
1689ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
1690 SVal Cond,
1691 bool Assumption) const {
1692 RegionStateTy RS = state->get<RegionState>();
Anna Zaks4fb54872012-02-11 21:02:35 +00001693 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
Ted Kremenek47cbd0f2012-09-07 22:31:01 +00001694 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Roseec8d4202012-11-01 00:18:27 +00001695 ConstraintManager &CMgr = state->getConstraintManager();
1696 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
1697 if (AllocFailed.isConstrainedTrue())
Anna Zaks4fb54872012-02-11 21:02:35 +00001698 state = state->remove<RegionState>(I.getKey());
1699 }
1700
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001701 // Realloc returns 0 when reallocation fails, which means that we should
1702 // restore the state of the pointer being reallocated.
Jordan Rose166d5022012-11-02 01:54:06 +00001703 ReallocPairsTy RP = state->get<ReallocPairs>();
1704 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Ted Kremenek47cbd0f2012-09-07 22:31:01 +00001705 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Roseec8d4202012-11-01 00:18:27 +00001706 ConstraintManager &CMgr = state->getConstraintManager();
1707 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
Jordan Rose79a29eb2012-11-01 00:25:15 +00001708 if (!AllocFailed.isConstrainedTrue())
Anna Zaks9dc298b2012-09-12 22:57:34 +00001709 continue;
Jordan Roseec8d4202012-11-01 00:18:27 +00001710
Anna Zaks9dc298b2012-09-12 22:57:34 +00001711 SymbolRef ReallocSym = I.getData().ReallocatedSym;
1712 if (const RefState *RS = state->get<RegionState>(ReallocSym)) {
1713 if (RS->isReleased()) {
1714 if (I.getData().Kind == RPToBeFreedAfterFailure)
Anna Zaks40add292012-02-15 00:11:25 +00001715 state = state->set<RegionState>(ReallocSym,
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001716 RefState::getAllocated(RS->getAllocationFamily(), RS->getStmt()));
Anna Zaks9dc298b2012-09-12 22:57:34 +00001717 else if (I.getData().Kind == RPDoNotTrackAfterFailure)
1718 state = state->remove<RegionState>(ReallocSym);
1719 else
1720 assert(I.getData().Kind == RPIsFreeOnFailure);
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001721 }
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001722 }
Anna Zaks9dc298b2012-09-12 22:57:34 +00001723 state = state->remove<ReallocPairs>(I.getKey());
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001724 }
1725
Anna Zaks4fb54872012-02-11 21:02:35 +00001726 return state;
1727}
1728
Jordan Rose9fe09f32013-03-09 00:59:10 +00001729bool MallocChecker::doesNotFreeMemOrInteresting(const CallEvent *Call,
1730 ProgramStateRef State) const {
Jordan Rose85d7e012012-07-02 19:27:51 +00001731 assert(Call);
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001732
1733 // For now, assume that any C++ call can free memory.
1734 // TODO: If we want to be more optimistic here, we'll need to make sure that
1735 // regions escape to C++ containers. They seem to do that even now, but for
1736 // mysterious reasons.
Jordan Rosecde8cdb2012-07-02 19:27:56 +00001737 if (!(isa<FunctionCall>(Call) || isa<ObjCMethodCall>(Call)))
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001738 return false;
1739
Jordan Rose740d4902012-07-02 19:27:35 +00001740 // Check Objective-C messages by selector name.
Jordan Rosecde8cdb2012-07-02 19:27:56 +00001741 if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) {
Jordan Rose85d7e012012-07-02 19:27:51 +00001742 // If it's not a framework call, or if it takes a callback, assume it
1743 // can free memory.
1744 if (!Call->isInSystemHeader() || Call->hasNonZeroCallbackArg())
Anna Zaks07d39a42012-02-28 01:54:22 +00001745 return false;
1746
Jordan Rose9fe09f32013-03-09 00:59:10 +00001747 // If it's a method we know about, handle it explicitly post-call.
1748 // This should happen before the "freeWhenDone" check below.
1749 if (isKnownDeallocObjCMethodName(*Msg))
1750 return true;
Anna Zaks52a04812012-06-20 23:35:57 +00001751
Jordan Rose9fe09f32013-03-09 00:59:10 +00001752 // If there's a "freeWhenDone" parameter, but the method isn't one we know
1753 // about, we can't be sure that the object will use free() to deallocate the
1754 // memory, so we can't model it explicitly. The best we can do is use it to
1755 // decide whether the pointer escapes.
1756 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(*Msg))
1757 return !*FreeWhenDone;
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001758
Jordan Rose9fe09f32013-03-09 00:59:10 +00001759 // If the first selector piece ends with "NoCopy", and there is no
1760 // "freeWhenDone" parameter set to zero, we know ownership is being
1761 // transferred. Again, though, we can't be sure that the object will use
1762 // free() to deallocate the memory, so we can't model it explicitly.
1763 StringRef FirstSlot = Msg->getSelector().getNameForSlot(0);
Jordan Rose740d4902012-07-02 19:27:35 +00001764 if (FirstSlot.endswith("NoCopy"))
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001765 return false;
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001766
Anna Zaks5f757682012-06-19 05:10:32 +00001767 // If the first selector starts with addPointer, insertPointer,
1768 // or replacePointer, assume we are dealing with NSPointerArray or similar.
1769 // This is similar to C++ containers (vector); we still might want to check
Jordan Rose740d4902012-07-02 19:27:35 +00001770 // that the pointers get freed by following the container itself.
1771 if (FirstSlot.startswith("addPointer") ||
1772 FirstSlot.startswith("insertPointer") ||
1773 FirstSlot.startswith("replacePointer")) {
Anna Zaks5f757682012-06-19 05:10:32 +00001774 return false;
1775 }
1776
Jordan Rose740d4902012-07-02 19:27:35 +00001777 // Otherwise, assume that the method does not free memory.
1778 // Most framework methods do not free memory.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001779 return true;
Anna Zaks66c40402012-02-14 21:55:24 +00001780 }
1781
Jordan Rose740d4902012-07-02 19:27:35 +00001782 // At this point the only thing left to handle is straight function calls.
1783 const FunctionDecl *FD = cast<FunctionCall>(Call)->getDecl();
1784 if (!FD)
1785 return false;
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001786
Jordan Rose740d4902012-07-02 19:27:35 +00001787 ASTContext &ASTC = State->getStateManager().getContext();
1788
1789 // If it's one of the allocation functions we can reason about, we model
1790 // its behavior explicitly.
1791 if (isMemFunction(FD, ASTC))
1792 return true;
1793
1794 // If it's not a system call, assume it frees memory.
1795 if (!Call->isInSystemHeader())
1796 return false;
1797
1798 // White list the system functions whose arguments escape.
1799 const IdentifierInfo *II = FD->getIdentifier();
1800 if (!II)
1801 return false;
1802 StringRef FName = II->getName();
1803
Jordan Rose740d4902012-07-02 19:27:35 +00001804 // White list the 'XXXNoCopy' CoreFoundation functions.
Jordan Rose85d7e012012-07-02 19:27:51 +00001805 // We specifically check these before
Jordan Rose740d4902012-07-02 19:27:35 +00001806 if (FName.endswith("NoCopy")) {
1807 // Look for the deallocator argument. We know that the memory ownership
1808 // is not transferred only if the deallocator argument is
1809 // 'kCFAllocatorNull'.
1810 for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
1811 const Expr *ArgE = Call->getArgExpr(i)->IgnoreParenCasts();
1812 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
1813 StringRef DeallocatorName = DE->getFoundDecl()->getName();
1814 if (DeallocatorName == "kCFAllocatorNull")
1815 return true;
1816 }
1817 }
1818 return false;
1819 }
1820
Jordan Rose740d4902012-07-02 19:27:35 +00001821 // Associating streams with malloced buffers. The pointer can escape if
Jordan Rose85d7e012012-07-02 19:27:51 +00001822 // 'closefn' is specified (and if that function does free memory),
1823 // but it will not if closefn is not specified.
Jordan Rose740d4902012-07-02 19:27:35 +00001824 // Currently, we do not inspect the 'closefn' function (PR12101).
1825 if (FName == "funopen")
Jordan Rose85d7e012012-07-02 19:27:51 +00001826 if (Call->getNumArgs() >= 4 && Call->getArgSVal(4).isConstant(0))
1827 return true;
Jordan Rose740d4902012-07-02 19:27:35 +00001828
1829 // Do not warn on pointers passed to 'setbuf' when used with std streams,
1830 // these leaks might be intentional when setting the buffer for stdio.
1831 // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
1832 if (FName == "setbuf" || FName =="setbuffer" ||
1833 FName == "setlinebuf" || FName == "setvbuf") {
1834 if (Call->getNumArgs() >= 1) {
1835 const Expr *ArgE = Call->getArgExpr(0)->IgnoreParenCasts();
1836 if (const DeclRefExpr *ArgDRE = dyn_cast<DeclRefExpr>(ArgE))
1837 if (const VarDecl *D = dyn_cast<VarDecl>(ArgDRE->getDecl()))
1838 if (D->getCanonicalDecl()->getName().find("std") != StringRef::npos)
1839 return false;
1840 }
1841 }
1842
1843 // A bunch of other functions which either take ownership of a pointer or
1844 // wrap the result up in a struct or object, meaning it can be freed later.
1845 // (See RetainCountChecker.) Not all the parameters here are invalidated,
1846 // but the Malloc checker cannot differentiate between them. The right way
1847 // of doing this would be to implement a pointer escapes callback.
1848 if (FName == "CGBitmapContextCreate" ||
1849 FName == "CGBitmapContextCreateWithData" ||
1850 FName == "CVPixelBufferCreateWithBytes" ||
1851 FName == "CVPixelBufferCreateWithPlanarBytes" ||
1852 FName == "OSAtomicEnqueue") {
1853 return false;
1854 }
1855
Jordan Rose85d7e012012-07-02 19:27:51 +00001856 // Handle cases where we know a buffer's /address/ can escape.
1857 // Note that the above checks handle some special cases where we know that
1858 // even though the address escapes, it's still our responsibility to free the
1859 // buffer.
1860 if (Call->argumentsMayEscape())
Jordan Rose740d4902012-07-02 19:27:35 +00001861 return false;
1862
1863 // Otherwise, assume that the function does not free memory.
1864 // Most system calls do not free the memory.
1865 return true;
Anna Zaks66c40402012-02-14 21:55:24 +00001866}
1867
Anna Zaksbf53dfa2012-12-20 00:38:25 +00001868ProgramStateRef MallocChecker::checkPointerEscape(ProgramStateRef State,
1869 const InvalidatedSymbols &Escaped,
Anna Zaks233e26a2013-02-07 23:05:43 +00001870 const CallEvent *Call,
1871 PointerEscapeKind Kind) const {
Jordan Rose9fe09f32013-03-09 00:59:10 +00001872 // If we know that the call does not free memory, or we want to process the
1873 // call later, keep tracking the top level arguments.
Anna Zaks233e26a2013-02-07 23:05:43 +00001874 if ((Kind == PSK_DirectEscapeOnCall ||
1875 Kind == PSK_IndirectEscapeOnCall) &&
Jordan Rose9fe09f32013-03-09 00:59:10 +00001876 doesNotFreeMemOrInteresting(Call, State)) {
Anna Zaks66c40402012-02-14 21:55:24 +00001877 return State;
Anna Zaks233e26a2013-02-07 23:05:43 +00001878 }
Anna Zaks66c40402012-02-14 21:55:24 +00001879
Anna Zaksbf53dfa2012-12-20 00:38:25 +00001880 for (InvalidatedSymbols::const_iterator I = Escaped.begin(),
1881 E = Escaped.end();
1882 I != E; ++I) {
Anna Zaks4fb54872012-02-11 21:02:35 +00001883 SymbolRef sym = *I;
Anna Zaksbf53dfa2012-12-20 00:38:25 +00001884
Anna Zaks5b7aa342012-06-22 02:04:31 +00001885 if (const RefState *RS = State->get<RegionState>(sym)) {
1886 if (RS->isAllocated())
Anna Zaks431e35c2012-08-09 00:42:24 +00001887 State = State->remove<RegionState>(sym);
Anna Zaks5b7aa342012-06-22 02:04:31 +00001888 }
Anna Zaks4fb54872012-02-11 21:02:35 +00001889 }
Anna Zaks66c40402012-02-14 21:55:24 +00001890 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001891}
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001892
Jordy Rose393f98b2012-03-18 07:43:35 +00001893static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
1894 ProgramStateRef prevState) {
Jordan Rose166d5022012-11-02 01:54:06 +00001895 ReallocPairsTy currMap = currState->get<ReallocPairs>();
1896 ReallocPairsTy prevMap = prevState->get<ReallocPairs>();
Jordy Rose393f98b2012-03-18 07:43:35 +00001897
Jordan Rose166d5022012-11-02 01:54:06 +00001898 for (ReallocPairsTy::iterator I = prevMap.begin(), E = prevMap.end();
Jordy Rose393f98b2012-03-18 07:43:35 +00001899 I != E; ++I) {
1900 SymbolRef sym = I.getKey();
1901 if (!currMap.lookup(sym))
1902 return sym;
1903 }
1904
1905 return NULL;
1906}
1907
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001908PathDiagnosticPiece *
1909MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
1910 const ExplodedNode *PrevN,
1911 BugReporterContext &BRC,
1912 BugReport &BR) {
Jordy Rose393f98b2012-03-18 07:43:35 +00001913 ProgramStateRef state = N->getState();
1914 ProgramStateRef statePrev = PrevN->getState();
1915
1916 const RefState *RS = state->get<RegionState>(Sym);
1917 const RefState *RSPrev = statePrev->get<RegionState>(Sym);
Anna Zaksede875b2012-08-03 18:30:18 +00001918 if (!RS)
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001919 return 0;
1920
Anna Zaksfe571602012-02-16 22:26:07 +00001921 const Stmt *S = 0;
1922 const char *Msg = 0;
Anna Zaks56a938f2012-03-16 23:24:20 +00001923 StackHintGeneratorForSymbol *StackHint = 0;
Anna Zaksfe571602012-02-16 22:26:07 +00001924
1925 // Retrieve the associated statement.
1926 ProgramPoint ProgLoc = N->getLocation();
David Blaikie7a95de62013-02-21 22:23:56 +00001927 if (Optional<StmtPoint> SP = ProgLoc.getAs<StmtPoint>()) {
Jordan Rose852aa0d2012-07-10 22:07:52 +00001928 S = SP->getStmt();
David Blaikie7a95de62013-02-21 22:23:56 +00001929 } else if (Optional<CallExitEnd> Exit = ProgLoc.getAs<CallExitEnd>()) {
Jordan Rose852aa0d2012-07-10 22:07:52 +00001930 S = Exit->getCalleeContext()->getCallSite();
David Blaikie7a95de62013-02-21 22:23:56 +00001931 } else if (Optional<BlockEdge> Edge = ProgLoc.getAs<BlockEdge>()) {
Ted Kremeneka4a17592013-01-04 19:04:36 +00001932 // If an assumption was made on a branch, it should be caught
1933 // here by looking at the state transition.
1934 S = Edge->getSrc()->getTerminator();
Anna Zaksfe571602012-02-16 22:26:07 +00001935 }
Ted Kremeneka4a17592013-01-04 19:04:36 +00001936
Anna Zaksfe571602012-02-16 22:26:07 +00001937 if (!S)
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001938 return 0;
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001939
Jordan Rose28038f32012-07-10 22:07:42 +00001940 // FIXME: We will eventually need to handle non-statement-based events
1941 // (__attribute__((cleanup))).
1942
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001943 // Find out if this is an interesting point and what is the kind.
Anna Zaksfe571602012-02-16 22:26:07 +00001944 if (Mode == Normal) {
Anna Zaks368a0d52012-03-15 21:13:02 +00001945 if (isAllocated(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001946 Msg = "Memory is allocated";
Anna Zaksfbd58742012-03-16 23:44:28 +00001947 StackHint = new StackHintGeneratorForSymbol(Sym,
1948 "Returned allocated memory");
Anna Zaks368a0d52012-03-15 21:13:02 +00001949 } else if (isReleased(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001950 Msg = "Memory is released";
Anna Zaksfbd58742012-03-16 23:44:28 +00001951 StackHint = new StackHintGeneratorForSymbol(Sym,
1952 "Returned released memory");
Anna Zaks5b7aa342012-06-22 02:04:31 +00001953 } else if (isRelinquished(RS, RSPrev, S)) {
1954 Msg = "Memory ownership is transfered";
1955 StackHint = new StackHintGeneratorForSymbol(Sym, "");
Anna Zaks368a0d52012-03-15 21:13:02 +00001956 } else if (isReallocFailedCheck(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001957 Mode = ReallocationFailed;
1958 Msg = "Reallocation failed";
Anna Zaks56a938f2012-03-16 23:24:20 +00001959 StackHint = new StackHintGeneratorForReallocationFailed(Sym,
Anna Zaksfbd58742012-03-16 23:44:28 +00001960 "Reallocation failed");
Jordy Rose393f98b2012-03-18 07:43:35 +00001961
Jordy Roseb000fb52012-03-24 03:15:09 +00001962 if (SymbolRef sym = findFailedReallocSymbol(state, statePrev)) {
1963 // Is it possible to fail two reallocs WITHOUT testing in between?
1964 assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
1965 "We only support one failed realloc at a time.");
Jordy Rose393f98b2012-03-18 07:43:35 +00001966 BR.markInteresting(sym);
Jordy Roseb000fb52012-03-24 03:15:09 +00001967 FailedReallocSymbol = sym;
1968 }
Anna Zaksfe571602012-02-16 22:26:07 +00001969 }
1970
1971 // We are in a special mode if a reallocation failed later in the path.
1972 } else if (Mode == ReallocationFailed) {
Jordy Roseb000fb52012-03-24 03:15:09 +00001973 assert(FailedReallocSymbol && "No symbol to look for.");
Anna Zaksfe571602012-02-16 22:26:07 +00001974
Jordy Roseb000fb52012-03-24 03:15:09 +00001975 // Is this is the first appearance of the reallocated symbol?
1976 if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
Jordy Roseb000fb52012-03-24 03:15:09 +00001977 // We're at the reallocation point.
1978 Msg = "Attempt to reallocate memory";
1979 StackHint = new StackHintGeneratorForSymbol(Sym,
1980 "Returned reallocated memory");
1981 FailedReallocSymbol = NULL;
1982 Mode = Normal;
1983 }
Anna Zaksfe571602012-02-16 22:26:07 +00001984 }
1985
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001986 if (!Msg)
1987 return 0;
Anna Zaks56a938f2012-03-16 23:24:20 +00001988 assert(StackHint);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001989
1990 // Generate the extra diagnostic.
Anna Zaksfe571602012-02-16 22:26:07 +00001991 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001992 N->getLocationContext());
Anna Zaks56a938f2012-03-16 23:24:20 +00001993 return new PathDiagnosticEventPiece(Pos, Msg, true, StackHint);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001994}
1995
Anna Zaks93c5a242012-05-02 00:05:20 +00001996void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State,
1997 const char *NL, const char *Sep) const {
1998
1999 RegionStateTy RS = State->get<RegionState>();
2000
Ted Kremenekc37fad62013-01-03 01:30:12 +00002001 if (!RS.isEmpty()) {
2002 Out << Sep << "MallocChecker:" << NL;
2003 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
2004 I.getKey()->dumpToStream(Out);
2005 Out << " : ";
2006 I.getData().dump(Out);
2007 Out << NL;
2008 }
2009 }
Anna Zaks93c5a242012-05-02 00:05:20 +00002010}
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002011
Anna Zaks231361a2012-02-08 23:16:52 +00002012#define REGISTER_CHECKER(name) \
2013void ento::register##name(CheckerManager &mgr) {\
Anna Zaksf0dfc9c2012-02-17 22:35:31 +00002014 registerCStringCheckerBasic(mgr); \
Anna Zaks231361a2012-02-08 23:16:52 +00002015 mgr.registerChecker<MallocChecker>()->Filter.C##name = true;\
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00002016}
Anna Zaks231361a2012-02-08 23:16:52 +00002017
2018REGISTER_CHECKER(MallocPessimistic)
2019REGISTER_CHECKER(MallocOptimistic)
Anton Yartsev2de19ed2013-03-25 01:35:45 +00002020REGISTER_CHECKER(NewDeleteChecker)
Anton Yartsev849c7bf2013-03-28 17:05:19 +00002021REGISTER_CHECKER(MismatchedDeallocatorChecker)