blob: 49eef236e90641c11fc0407aa570311e05ed7485 [file] [log] [blame]
Jordy Rose75e680e2011-09-02 06:44:22 +00001//==-- RetainCountChecker.cpp - Checks for leaks and other issues -*- C++ -*--//
Ted Kremenekea6507f2008-03-06 00:08:09 +00002//
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//
Jordy Rose75e680e2011-09-02 06:44:22 +000010// This file defines the methods for RetainCountChecker, which implements
11// a reference count checker for Core Foundation and Cocoa on (Mac OS X).
Ted Kremenekea6507f2008-03-06 00:08:09 +000012//
13//===----------------------------------------------------------------------===//
14
Jordy Rose75e680e2011-09-02 06:44:22 +000015#include "ClangSACheckers.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000016#include "AllocationDiagnostics.h"
Jordan Rose0675c872014-04-09 01:39:22 +000017#include "SelectorExtras.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000018#include "clang/AST/Attr.h"
Ted Kremenek98a24e32011-03-30 17:41:19 +000019#include "clang/AST/DeclCXX.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000020#include "clang/AST/DeclObjC.h"
21#include "clang/AST/ParentMap.h"
22#include "clang/Analysis/DomainSpecific/CocoaConventions.h"
Ted Kremenek2b36f3f2010-02-18 00:05:58 +000023#include "clang/Basic/LangOptions.h"
24#include "clang/Basic/SourceManager.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000025#include "clang/StaticAnalyzer/Checkers/ObjCRetainCount.h"
Ted Kremenekf8cbac42011-02-10 01:03:03 +000026#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
27#include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000028#include "clang/StaticAnalyzer/Core/Checker.h"
29#include "clang/StaticAnalyzer/Core/CheckerManager.h"
Jordan Rose4f7df9b2012-07-26 21:39:41 +000030#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
Jordy Rose75e680e2011-09-02 06:44:22 +000031#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
Ted Kremenek001fd5b2011-08-15 22:09:50 +000032#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
Ted Kremenekf8cbac42011-02-10 01:03:03 +000033#include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
Ted Kremenek819e9b62008-03-11 06:39:11 +000034#include "llvm/ADT/DenseMap.h"
35#include "llvm/ADT/FoldingSet.h"
Ted Kremenek0747e7e2008-10-21 15:53:15 +000036#include "llvm/ADT/ImmutableList.h"
Ted Kremenek2b36f3f2010-02-18 00:05:58 +000037#include "llvm/ADT/ImmutableMap.h"
Ted Kremenekc812b232008-05-16 18:33:44 +000038#include "llvm/ADT/STLExtras.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000039#include "llvm/ADT/SmallString.h"
Ted Kremenek2b36f3f2010-02-18 00:05:58 +000040#include "llvm/ADT/StringExtras.h"
Chris Lattner0e62c1c2011-07-23 10:55:15 +000041#include <cstdarg>
Ted Kremenekea6507f2008-03-06 00:08:09 +000042
43using namespace clang;
Ted Kremenek98857c92010-12-23 07:20:52 +000044using namespace ento;
Ted Kremenek243c0852013-08-14 23:41:46 +000045using namespace objc_retain;
Ted Kremenekdb1832d2010-01-27 06:13:48 +000046using llvm::StrInStrNoCase;
Ted Kremenek2855a932008-11-05 16:54:44 +000047
Ted Kremenekc8bef6a2008-04-09 23:49:11 +000048//===----------------------------------------------------------------------===//
Ted Kremenek243c0852013-08-14 23:41:46 +000049// Adapters for FoldingSet.
Ted Kremenekc8bef6a2008-04-09 23:49:11 +000050//===----------------------------------------------------------------------===//
51
Ted Kremenek819e9b62008-03-11 06:39:11 +000052namespace llvm {
Ted Kremenek7d79a5f2009-05-03 05:20:50 +000053template <> struct FoldingSetTrait<ArgEffect> {
Ted Kremenek243c0852013-08-14 23:41:46 +000054static inline void Profile(const ArgEffect X, FoldingSetNodeID &ID) {
Ted Kremenek7d79a5f2009-05-03 05:20:50 +000055 ID.AddInteger((unsigned) X);
56}
Ted Kremenek3185c9c2008-06-25 21:21:56 +000057};
Ted Kremenek243c0852013-08-14 23:41:46 +000058template <> struct FoldingSetTrait<RetEffect> {
59 static inline void Profile(const RetEffect &X, FoldingSetNodeID &ID) {
60 ID.AddInteger((unsigned) X.getKind());
61 ID.AddInteger((unsigned) X.getObjKind());
62}
63};
Ted Kremenek819e9b62008-03-11 06:39:11 +000064} // end llvm namespace
65
Ted Kremenek243c0852013-08-14 23:41:46 +000066//===----------------------------------------------------------------------===//
67// Reference-counting logic (typestate + counts).
68//===----------------------------------------------------------------------===//
69
Ted Kremenek7d79a5f2009-05-03 05:20:50 +000070/// ArgEffects summarizes the effects of a function/method call on all of
71/// its arguments.
72typedef llvm::ImmutableMap<unsigned,ArgEffect> ArgEffects;
73
Ted Kremenek819e9b62008-03-11 06:39:11 +000074namespace {
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +000075class RefVal {
Ted Kremeneka2968e52009-11-13 01:54:21 +000076public:
77 enum Kind {
78 Owned = 0, // Owning reference.
79 NotOwned, // Reference is not owned by still valid (not freed).
80 Released, // Object has been released.
81 ReturnedOwned, // Returned object passes ownership to caller.
82 ReturnedNotOwned, // Return object does not pass ownership to caller.
83 ERROR_START,
84 ErrorDeallocNotOwned, // -dealloc called on non-owned object.
85 ErrorDeallocGC, // Calling -dealloc with GC enabled.
86 ErrorUseAfterRelease, // Object used after released.
87 ErrorReleaseNotOwned, // Release of an object that was not owned.
88 ERROR_LEAK_START,
89 ErrorLeak, // A memory leak due to excessive reference counts.
90 ErrorLeakReturned, // A memory leak due to the returning method not having
91 // the correct naming conventions.
92 ErrorGCLeakReturned,
93 ErrorOverAutorelease,
94 ErrorReturnedNotOwned
95 };
Ted Kremenekbd862712010-07-01 20:16:50 +000096
Jordan Rosecb5386c2015-02-04 19:24:52 +000097 /// Tracks how an object referenced by an ivar has been used.
98 ///
99 /// This accounts for us not knowing if an arbitrary ivar is supposed to be
100 /// stored at +0 or +1.
101 enum class IvarAccessHistory {
102 None,
103 AccessedDirectly,
104 ReleasedAfterDirectAccess
105 };
106
Ted Kremeneka2968e52009-11-13 01:54:21 +0000107private:
Jordan Roseb3ad07e2014-03-25 17:10:58 +0000108 /// The number of outstanding retains.
Ted Kremeneka2968e52009-11-13 01:54:21 +0000109 unsigned Cnt;
Jordan Roseb3ad07e2014-03-25 17:10:58 +0000110 /// The number of outstanding autoreleases.
Ted Kremeneka2968e52009-11-13 01:54:21 +0000111 unsigned ACnt;
Jordan Roseb3ad07e2014-03-25 17:10:58 +0000112 /// The (static) type of the object at the time we started tracking it.
Ted Kremeneka2968e52009-11-13 01:54:21 +0000113 QualType T;
Ted Kremenekbd862712010-07-01 20:16:50 +0000114
Jordan Roseb3ad07e2014-03-25 17:10:58 +0000115 /// The current state of the object.
116 ///
117 /// See the RefVal::Kind enum for possible values.
118 unsigned RawKind : 5;
119
120 /// The kind of object being tracked (CF or ObjC), if known.
121 ///
122 /// See the RetEffect::ObjKind enum for possible values.
123 unsigned RawObjectKind : 2;
124
125 /// True if the current state and/or retain count may turn out to not be the
126 /// best possible approximation of the reference counting state.
127 ///
128 /// If true, the checker may decide to throw away ("override") this state
129 /// in favor of something else when it sees the object being used in new ways.
130 ///
131 /// This setting should not be propagated to state derived from this state.
132 /// Once we start deriving new states, it would be inconsistent to override
133 /// them.
Jordan Rosecb5386c2015-02-04 19:24:52 +0000134 unsigned RawIvarAccessHistory : 2;
Jordan Roseb3ad07e2014-03-25 17:10:58 +0000135
136 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, unsigned acnt, QualType t,
Jordan Rosecb5386c2015-02-04 19:24:52 +0000137 IvarAccessHistory IvarAccess)
Jordan Roseb3ad07e2014-03-25 17:10:58 +0000138 : Cnt(cnt), ACnt(acnt), T(t), RawKind(static_cast<unsigned>(k)),
Jordan Rosecb5386c2015-02-04 19:24:52 +0000139 RawObjectKind(static_cast<unsigned>(o)),
140 RawIvarAccessHistory(static_cast<unsigned>(IvarAccess)) {
Jordan Roseb3ad07e2014-03-25 17:10:58 +0000141 assert(getKind() == k && "not enough bits for the kind");
142 assert(getObjKind() == o && "not enough bits for the object kind");
Jordan Rosecb5386c2015-02-04 19:24:52 +0000143 assert(getIvarAccessHistory() == IvarAccess && "not enough bits");
Jordan Roseb3ad07e2014-03-25 17:10:58 +0000144 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000145
Ted Kremeneka2968e52009-11-13 01:54:21 +0000146public:
Jordan Roseb3ad07e2014-03-25 17:10:58 +0000147 Kind getKind() const { return static_cast<Kind>(RawKind); }
Ted Kremenekbd862712010-07-01 20:16:50 +0000148
Jordan Roseb3ad07e2014-03-25 17:10:58 +0000149 RetEffect::ObjKind getObjKind() const {
150 return static_cast<RetEffect::ObjKind>(RawObjectKind);
151 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000152
Ted Kremeneka2968e52009-11-13 01:54:21 +0000153 unsigned getCount() const { return Cnt; }
154 unsigned getAutoreleaseCount() const { return ACnt; }
155 unsigned getCombinedCounts() const { return Cnt + ACnt; }
Jordan Roseb3ad07e2014-03-25 17:10:58 +0000156 void clearCounts() {
157 Cnt = 0;
158 ACnt = 0;
Jordan Roseb3ad07e2014-03-25 17:10:58 +0000159 }
160 void setCount(unsigned i) {
161 Cnt = i;
Jordan Roseb3ad07e2014-03-25 17:10:58 +0000162 }
163 void setAutoreleaseCount(unsigned i) {
164 ACnt = i;
Jordan Roseb3ad07e2014-03-25 17:10:58 +0000165 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000166
Ted Kremeneka2968e52009-11-13 01:54:21 +0000167 QualType getType() const { return T; }
Ted Kremenekbd862712010-07-01 20:16:50 +0000168
Jordan Rosecb5386c2015-02-04 19:24:52 +0000169 /// Returns what the analyzer knows about direct accesses to a particular
170 /// instance variable.
171 ///
172 /// If the object with this refcount wasn't originally from an Objective-C
173 /// ivar region, this should always return IvarAccessHistory::None.
174 IvarAccessHistory getIvarAccessHistory() const {
175 return static_cast<IvarAccessHistory>(RawIvarAccessHistory);
176 }
Jordan Roseb3ad07e2014-03-25 17:10:58 +0000177
Ted Kremeneka2968e52009-11-13 01:54:21 +0000178 bool isOwned() const {
179 return getKind() == Owned;
180 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000181
Ted Kremeneka2968e52009-11-13 01:54:21 +0000182 bool isNotOwned() const {
183 return getKind() == NotOwned;
184 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000185
Ted Kremeneka2968e52009-11-13 01:54:21 +0000186 bool isReturnedOwned() const {
187 return getKind() == ReturnedOwned;
188 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000189
Ted Kremeneka2968e52009-11-13 01:54:21 +0000190 bool isReturnedNotOwned() const {
191 return getKind() == ReturnedNotOwned;
192 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000193
Jordan Roseb3ad07e2014-03-25 17:10:58 +0000194 /// Create a state for an object whose lifetime is the responsibility of the
195 /// current function, at least partially.
196 ///
197 /// Most commonly, this is an owned object with a retain count of +1.
Ted Kremeneka2968e52009-11-13 01:54:21 +0000198 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
199 unsigned Count = 1) {
Jordan Rosecb5386c2015-02-04 19:24:52 +0000200 return RefVal(Owned, o, Count, 0, t, IvarAccessHistory::None);
Ted Kremeneka2968e52009-11-13 01:54:21 +0000201 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000202
Jordan Roseb3ad07e2014-03-25 17:10:58 +0000203 /// Create a state for an object whose lifetime is not the responsibility of
204 /// the current function.
205 ///
206 /// Most commonly, this is an unowned object with a retain count of +0.
Ted Kremeneka2968e52009-11-13 01:54:21 +0000207 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
208 unsigned Count = 0) {
Jordan Rosecb5386c2015-02-04 19:24:52 +0000209 return RefVal(NotOwned, o, Count, 0, t, IvarAccessHistory::None);
Ted Kremeneka2968e52009-11-13 01:54:21 +0000210 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000211
Ted Kremeneka2968e52009-11-13 01:54:21 +0000212 RefVal operator-(size_t i) const {
213 return RefVal(getKind(), getObjKind(), getCount() - i,
Jordan Rosecb5386c2015-02-04 19:24:52 +0000214 getAutoreleaseCount(), getType(), getIvarAccessHistory());
Ted Kremeneka2968e52009-11-13 01:54:21 +0000215 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000216
Ted Kremeneka2968e52009-11-13 01:54:21 +0000217 RefVal operator+(size_t i) const {
218 return RefVal(getKind(), getObjKind(), getCount() + i,
Jordan Rosecb5386c2015-02-04 19:24:52 +0000219 getAutoreleaseCount(), getType(), getIvarAccessHistory());
Ted Kremeneka2968e52009-11-13 01:54:21 +0000220 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000221
Ted Kremeneka2968e52009-11-13 01:54:21 +0000222 RefVal operator^(Kind k) const {
223 return RefVal(k, getObjKind(), getCount(), getAutoreleaseCount(),
Jordan Rosecb5386c2015-02-04 19:24:52 +0000224 getType(), getIvarAccessHistory());
Ted Kremeneka2968e52009-11-13 01:54:21 +0000225 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000226
Ted Kremeneka2968e52009-11-13 01:54:21 +0000227 RefVal autorelease() const {
228 return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount()+1,
Jordan Rosecb5386c2015-02-04 19:24:52 +0000229 getType(), getIvarAccessHistory());
230 }
231
232 RefVal withIvarAccess() const {
233 assert(getIvarAccessHistory() == IvarAccessHistory::None);
234 return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount(),
235 getType(), IvarAccessHistory::AccessedDirectly);
236 }
237 RefVal releaseViaIvar() const {
238 assert(getIvarAccessHistory() == IvarAccessHistory::AccessedDirectly);
239 return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount(),
240 getType(), IvarAccessHistory::ReleasedAfterDirectAccess);
Ted Kremeneka2968e52009-11-13 01:54:21 +0000241 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000242
Jordan Roseb3ad07e2014-03-25 17:10:58 +0000243 // Comparison, profiling, and pretty-printing.
244
245 bool hasSameState(const RefVal &X) const {
Jordan Rosecb5386c2015-02-04 19:24:52 +0000246 return getKind() == X.getKind() && Cnt == X.Cnt && ACnt == X.ACnt &&
247 getIvarAccessHistory() == X.getIvarAccessHistory();
Jordan Roseb3ad07e2014-03-25 17:10:58 +0000248 }
249
250 bool operator==(const RefVal& X) const {
Jordan Rosecb5386c2015-02-04 19:24:52 +0000251 return T == X.T && hasSameState(X) && getObjKind() == X.getObjKind();
Jordan Roseb3ad07e2014-03-25 17:10:58 +0000252 }
253
Ted Kremeneka2968e52009-11-13 01:54:21 +0000254 void Profile(llvm::FoldingSetNodeID& ID) const {
Jordan Roseb3ad07e2014-03-25 17:10:58 +0000255 ID.Add(T);
256 ID.AddInteger(RawKind);
Ted Kremeneka2968e52009-11-13 01:54:21 +0000257 ID.AddInteger(Cnt);
258 ID.AddInteger(ACnt);
Jordan Roseb3ad07e2014-03-25 17:10:58 +0000259 ID.AddInteger(RawObjectKind);
Jordan Rosecb5386c2015-02-04 19:24:52 +0000260 ID.AddInteger(RawIvarAccessHistory);
Ted Kremeneka2968e52009-11-13 01:54:21 +0000261 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000262
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000263 void print(raw_ostream &Out) const;
Ted Kremeneka2968e52009-11-13 01:54:21 +0000264};
265
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000266void RefVal::print(raw_ostream &Out) const {
Ted Kremeneka2968e52009-11-13 01:54:21 +0000267 if (!T.isNull())
Jordy Rose58a20d32011-08-28 19:11:56 +0000268 Out << "Tracked " << T.getAsString() << '/';
Ted Kremenekbd862712010-07-01 20:16:50 +0000269
Ted Kremeneka2968e52009-11-13 01:54:21 +0000270 switch (getKind()) {
Jordy Rose75e680e2011-09-02 06:44:22 +0000271 default: llvm_unreachable("Invalid RefVal kind");
Ted Kremeneka2968e52009-11-13 01:54:21 +0000272 case Owned: {
273 Out << "Owned";
274 unsigned cnt = getCount();
275 if (cnt) Out << " (+ " << cnt << ")";
276 break;
277 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000278
Ted Kremeneka2968e52009-11-13 01:54:21 +0000279 case NotOwned: {
280 Out << "NotOwned";
281 unsigned cnt = getCount();
282 if (cnt) Out << " (+ " << cnt << ")";
283 break;
284 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000285
Ted Kremeneka2968e52009-11-13 01:54:21 +0000286 case ReturnedOwned: {
287 Out << "ReturnedOwned";
288 unsigned cnt = getCount();
289 if (cnt) Out << " (+ " << cnt << ")";
290 break;
291 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000292
Ted Kremeneka2968e52009-11-13 01:54:21 +0000293 case ReturnedNotOwned: {
294 Out << "ReturnedNotOwned";
295 unsigned cnt = getCount();
296 if (cnt) Out << " (+ " << cnt << ")";
297 break;
298 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000299
Ted Kremeneka2968e52009-11-13 01:54:21 +0000300 case Released:
301 Out << "Released";
302 break;
Ted Kremenekbd862712010-07-01 20:16:50 +0000303
Ted Kremeneka2968e52009-11-13 01:54:21 +0000304 case ErrorDeallocGC:
305 Out << "-dealloc (GC)";
306 break;
Ted Kremenekbd862712010-07-01 20:16:50 +0000307
Ted Kremeneka2968e52009-11-13 01:54:21 +0000308 case ErrorDeallocNotOwned:
309 Out << "-dealloc (not-owned)";
310 break;
Ted Kremenekbd862712010-07-01 20:16:50 +0000311
Ted Kremeneka2968e52009-11-13 01:54:21 +0000312 case ErrorLeak:
313 Out << "Leaked";
314 break;
Ted Kremenekbd862712010-07-01 20:16:50 +0000315
Ted Kremeneka2968e52009-11-13 01:54:21 +0000316 case ErrorLeakReturned:
317 Out << "Leaked (Bad naming)";
318 break;
Ted Kremenekbd862712010-07-01 20:16:50 +0000319
Ted Kremeneka2968e52009-11-13 01:54:21 +0000320 case ErrorGCLeakReturned:
321 Out << "Leaked (GC-ed at return)";
322 break;
Ted Kremenekbd862712010-07-01 20:16:50 +0000323
Ted Kremeneka2968e52009-11-13 01:54:21 +0000324 case ErrorUseAfterRelease:
325 Out << "Use-After-Release [ERROR]";
326 break;
Ted Kremenekbd862712010-07-01 20:16:50 +0000327
Ted Kremeneka2968e52009-11-13 01:54:21 +0000328 case ErrorReleaseNotOwned:
329 Out << "Release of Not-Owned [ERROR]";
330 break;
Ted Kremenekbd862712010-07-01 20:16:50 +0000331
Ted Kremeneka2968e52009-11-13 01:54:21 +0000332 case RefVal::ErrorOverAutorelease:
Jordan Rose7467f062013-04-23 01:42:25 +0000333 Out << "Over-autoreleased";
Ted Kremeneka2968e52009-11-13 01:54:21 +0000334 break;
Ted Kremenekbd862712010-07-01 20:16:50 +0000335
Ted Kremeneka2968e52009-11-13 01:54:21 +0000336 case RefVal::ErrorReturnedNotOwned:
337 Out << "Non-owned object returned instead of owned";
338 break;
339 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000340
Jordan Rosecb5386c2015-02-04 19:24:52 +0000341 switch (getIvarAccessHistory()) {
342 case IvarAccessHistory::None:
343 break;
344 case IvarAccessHistory::AccessedDirectly:
345 Out << " [direct ivar access]";
346 break;
347 case IvarAccessHistory::ReleasedAfterDirectAccess:
348 Out << " [released after direct ivar access]";
349 }
350
Ted Kremeneka2968e52009-11-13 01:54:21 +0000351 if (ACnt) {
Jordan Rosecb5386c2015-02-04 19:24:52 +0000352 Out << " [autorelease -" << ACnt << ']';
Ted Kremeneka2968e52009-11-13 01:54:21 +0000353 }
354}
355} //end anonymous namespace
356
357//===----------------------------------------------------------------------===//
358// RefBindings - State used to track object reference counts.
359//===----------------------------------------------------------------------===//
360
Jordan Rose0c153cb2012-11-02 01:54:06 +0000361REGISTER_MAP_WITH_PROGRAMSTATE(RefBindings, SymbolRef, RefVal)
Ted Kremeneka2968e52009-11-13 01:54:21 +0000362
Anna Zaksf5788c72012-08-14 00:36:15 +0000363static inline const RefVal *getRefBinding(ProgramStateRef State,
364 SymbolRef Sym) {
365 return State->get<RefBindings>(Sym);
366}
367
368static inline ProgramStateRef setRefBinding(ProgramStateRef State,
369 SymbolRef Sym, RefVal Val) {
370 return State->set<RefBindings>(Sym, Val);
371}
372
373static ProgramStateRef removeRefBinding(ProgramStateRef State, SymbolRef Sym) {
374 return State->remove<RefBindings>(Sym);
375}
376
Ted Kremeneka2968e52009-11-13 01:54:21 +0000377//===----------------------------------------------------------------------===//
Jordy Rose75e680e2011-09-02 06:44:22 +0000378// Function/Method behavior summaries.
Ted Kremeneka2968e52009-11-13 01:54:21 +0000379//===----------------------------------------------------------------------===//
380
381namespace {
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +0000382class RetainSummary {
Jordy Rose61c974b2012-03-18 01:26:10 +0000383 /// Args - a map of (index, ArgEffect) pairs, where index
Ted Kremenekcb2e6362008-05-06 15:44:25 +0000384 /// specifies the argument (starting from 0). This can be sparsely
385 /// populated; arguments with no entry in Args use 'DefaultArgEffect'.
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000386 ArgEffects Args;
Mike Stump11289f42009-09-09 15:08:12 +0000387
Ted Kremenekcb2e6362008-05-06 15:44:25 +0000388 /// DefaultArgEffect - The default ArgEffect to apply to arguments that
389 /// do not have an entry in Args.
Ted Kremeneke8300e52012-01-04 00:35:45 +0000390 ArgEffect DefaultArgEffect;
Mike Stump11289f42009-09-09 15:08:12 +0000391
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000392 /// Receiver - If this summary applies to an Objective-C message expression,
393 /// this is the effect applied to the state of the receiver.
Ted Kremeneke8300e52012-01-04 00:35:45 +0000394 ArgEffect Receiver;
Mike Stump11289f42009-09-09 15:08:12 +0000395
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000396 /// Ret - The effect on the return value. Used to indicate if the
Jordy Rose898a1482011-08-21 21:58:18 +0000397 /// function/method call returns a new tracked symbol.
Ted Kremeneke8300e52012-01-04 00:35:45 +0000398 RetEffect Ret;
Mike Stump11289f42009-09-09 15:08:12 +0000399
Ted Kremenek819e9b62008-03-11 06:39:11 +0000400public:
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000401 RetainSummary(ArgEffects A, RetEffect R, ArgEffect defaultEff,
Jordy Rose5a3c9ff2011-08-20 20:55:40 +0000402 ArgEffect ReceiverEff)
403 : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R) {}
Mike Stump11289f42009-09-09 15:08:12 +0000404
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000405 /// getArg - Return the argument effect on the argument specified by
406 /// idx (starting from 0).
Ted Kremenekbf9d8042008-03-11 17:48:22 +0000407 ArgEffect getArg(unsigned idx) const {
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000408 if (const ArgEffect *AE = Args.lookup(idx))
409 return *AE;
Mike Stump11289f42009-09-09 15:08:12 +0000410
Ted Kremenekcb2e6362008-05-06 15:44:25 +0000411 return DefaultArgEffect;
Ted Kremenekbf9d8042008-03-11 17:48:22 +0000412 }
Ted Kremenek71c080f2013-08-14 23:41:49 +0000413
Ted Kremenekafe348e2011-01-27 18:43:03 +0000414 void addArg(ArgEffects::Factory &af, unsigned idx, ArgEffect e) {
415 Args = af.add(Args, idx, e);
416 }
Mike Stump11289f42009-09-09 15:08:12 +0000417
Ted Kremenek1d9a2672009-05-04 05:31:22 +0000418 /// setDefaultArgEffect - Set the default argument effect.
419 void setDefaultArgEffect(ArgEffect E) {
420 DefaultArgEffect = E;
421 }
Mike Stump11289f42009-09-09 15:08:12 +0000422
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000423 /// getRetEffect - Returns the effect on the return value of the call.
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000424 RetEffect getRetEffect() const { return Ret; }
Mike Stump11289f42009-09-09 15:08:12 +0000425
Ted Kremenek1d9a2672009-05-04 05:31:22 +0000426 /// setRetEffect - Set the effect of the return value of the call.
427 void setRetEffect(RetEffect E) { Ret = E; }
Mike Stump11289f42009-09-09 15:08:12 +0000428
Ted Kremenek0e898382011-01-27 06:54:14 +0000429
430 /// Sets the effect on the receiver of the message.
431 void setReceiverEffect(ArgEffect e) { Receiver = e; }
432
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000433 /// getReceiverEffect - Returns the effect on the receiver of the call.
434 /// This is only meaningful if the summary applies to an ObjCMessageExpr*.
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000435 ArgEffect getReceiverEffect() const { return Receiver; }
Jordy Rose212e4592011-08-23 04:27:15 +0000436
437 /// Test if two retain summaries are identical. Note that merely equivalent
438 /// summaries are not necessarily identical (for example, if an explicit
439 /// argument effect matches the default effect).
440 bool operator==(const RetainSummary &Other) const {
441 return Args == Other.Args && DefaultArgEffect == Other.DefaultArgEffect &&
442 Receiver == Other.Receiver && Ret == Other.Ret;
443 }
Jordy Rose61c974b2012-03-18 01:26:10 +0000444
445 /// Profile this summary for inclusion in a FoldingSet.
446 void Profile(llvm::FoldingSetNodeID& ID) const {
447 ID.Add(Args);
448 ID.Add(DefaultArgEffect);
449 ID.Add(Receiver);
450 ID.Add(Ret);
451 }
452
453 /// A retain summary is simple if it has no ArgEffects other than the default.
454 bool isSimple() const {
455 return Args.isEmpty();
456 }
Jordan Roseeec15392012-07-02 19:27:43 +0000457
458private:
459 ArgEffects getArgEffects() const { return Args; }
460 ArgEffect getDefaultArgEffect() const { return DefaultArgEffect; }
461
462 friend class RetainSummaryManager;
Ted Kremenek819e9b62008-03-11 06:39:11 +0000463};
Ted Kremenek0cfc1612008-06-23 23:30:29 +0000464} // end anonymous namespace
Ted Kremenek819e9b62008-03-11 06:39:11 +0000465
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000466//===----------------------------------------------------------------------===//
467// Data structures for constructing summaries.
468//===----------------------------------------------------------------------===//
Ted Kremenekb1d13292008-06-24 03:49:48 +0000469
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000470namespace {
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +0000471class ObjCSummaryKey {
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000472 IdentifierInfo* II;
473 Selector S;
Mike Stump11289f42009-09-09 15:08:12 +0000474public:
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000475 ObjCSummaryKey(IdentifierInfo* ii, Selector s)
476 : II(ii), S(s) {}
477
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000478 ObjCSummaryKey(const ObjCInterfaceDecl *d, Selector s)
Craig Topper0dbb7832014-05-27 02:45:47 +0000479 : II(d ? d->getIdentifier() : nullptr), S(s) {}
Ted Kremenek5801f652009-05-13 18:16:01 +0000480
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000481 ObjCSummaryKey(Selector s)
Craig Topper0dbb7832014-05-27 02:45:47 +0000482 : II(nullptr), S(s) {}
Mike Stump11289f42009-09-09 15:08:12 +0000483
Ted Kremeneke8300e52012-01-04 00:35:45 +0000484 IdentifierInfo *getIdentifier() const { return II; }
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000485 Selector getSelector() const { return S; }
486};
Ted Kremenek0cfc1612008-06-23 23:30:29 +0000487}
488
489namespace llvm {
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000490template <> struct DenseMapInfo<ObjCSummaryKey> {
491 static inline ObjCSummaryKey getEmptyKey() {
492 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
493 DenseMapInfo<Selector>::getEmptyKey());
494 }
Mike Stump11289f42009-09-09 15:08:12 +0000495
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000496 static inline ObjCSummaryKey getTombstoneKey() {
497 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
Mike Stump11289f42009-09-09 15:08:12 +0000498 DenseMapInfo<Selector>::getTombstoneKey());
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000499 }
Mike Stump11289f42009-09-09 15:08:12 +0000500
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000501 static unsigned getHashValue(const ObjCSummaryKey &V) {
Benjamin Kramer69b5a602012-05-27 13:28:44 +0000502 typedef std::pair<IdentifierInfo*, Selector> PairTy;
503 return DenseMapInfo<PairTy>::getHashValue(PairTy(V.getIdentifier(),
504 V.getSelector()));
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000505 }
Mike Stump11289f42009-09-09 15:08:12 +0000506
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000507 static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
Benjamin Kramer69b5a602012-05-27 13:28:44 +0000508 return LHS.getIdentifier() == RHS.getIdentifier() &&
509 LHS.getSelector() == RHS.getSelector();
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000510 }
Mike Stump11289f42009-09-09 15:08:12 +0000511
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000512};
Ted Kremenek0cfc1612008-06-23 23:30:29 +0000513} // end llvm namespace
Mike Stump11289f42009-09-09 15:08:12 +0000514
Ted Kremenek0cfc1612008-06-23 23:30:29 +0000515namespace {
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +0000516class ObjCSummaryCache {
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000517 typedef llvm::DenseMap<ObjCSummaryKey, const RetainSummary *> MapTy;
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000518 MapTy M;
519public:
520 ObjCSummaryCache() {}
Mike Stump11289f42009-09-09 15:08:12 +0000521
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000522 const RetainSummary * find(const ObjCInterfaceDecl *D, Selector S) {
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000523 // Do a lookup with the (D,S) pair. If we find a match return
524 // the iterator.
525 ObjCSummaryKey K(D, S);
526 MapTy::iterator I = M.find(K);
Mike Stump11289f42009-09-09 15:08:12 +0000527
Jordan Roseeec15392012-07-02 19:27:43 +0000528 if (I != M.end())
Ted Kremenek8be51382009-07-21 23:27:57 +0000529 return I->second;
Jordan Roseeec15392012-07-02 19:27:43 +0000530 if (!D)
Craig Topper0dbb7832014-05-27 02:45:47 +0000531 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000532
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000533 // Walk the super chain. If we find a hit with a parent, we'll end
534 // up returning that summary. We actually allow that key (null,S), as
535 // we cache summaries for the null ObjCInterfaceDecl* to allow us to
536 // generate initial summaries without having to worry about NSObject
537 // being declared.
538 // FIXME: We may change this at some point.
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000539 for (ObjCInterfaceDecl *C=D->getSuperClass() ;; C=C->getSuperClass()) {
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000540 if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
541 break;
Mike Stump11289f42009-09-09 15:08:12 +0000542
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000543 if (!C)
Craig Topper0dbb7832014-05-27 02:45:47 +0000544 return nullptr;
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000545 }
Mike Stump11289f42009-09-09 15:08:12 +0000546
547 // Cache the summary with original key to make the next lookup faster
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000548 // and return the iterator.
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000549 const RetainSummary *Summ = I->second;
Ted Kremenek8be51382009-07-21 23:27:57 +0000550 M[K] = Summ;
551 return Summ;
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000552 }
Mike Stump11289f42009-09-09 15:08:12 +0000553
Ted Kremeneke8300e52012-01-04 00:35:45 +0000554 const RetainSummary *find(IdentifierInfo* II, Selector S) {
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000555 // FIXME: Class method lookup. Right now we dont' have a good way
556 // of going between IdentifierInfo* and the class hierarchy.
Ted Kremenek8be51382009-07-21 23:27:57 +0000557 MapTy::iterator I = M.find(ObjCSummaryKey(II, S));
Mike Stump11289f42009-09-09 15:08:12 +0000558
Ted Kremenek8be51382009-07-21 23:27:57 +0000559 if (I == M.end())
560 I = M.find(ObjCSummaryKey(S));
Mike Stump11289f42009-09-09 15:08:12 +0000561
Craig Topper0dbb7832014-05-27 02:45:47 +0000562 return I == M.end() ? nullptr : I->second;
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000563 }
Mike Stump11289f42009-09-09 15:08:12 +0000564
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000565 const RetainSummary *& operator[](ObjCSummaryKey K) {
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000566 return M[K];
567 }
Mike Stump11289f42009-09-09 15:08:12 +0000568
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000569 const RetainSummary *& operator[](Selector S) {
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000570 return M[ ObjCSummaryKey(S) ];
571 }
Mike Stump11289f42009-09-09 15:08:12 +0000572};
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000573} // end anonymous namespace
574
575//===----------------------------------------------------------------------===//
576// Data structures for managing collections of summaries.
577//===----------------------------------------------------------------------===//
578
579namespace {
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +0000580class RetainSummaryManager {
Ted Kremenek00daccd2008-05-05 22:11:16 +0000581
582 //==-----------------------------------------------------------------==//
583 // Typedefs.
584 //==-----------------------------------------------------------------==//
Mike Stump11289f42009-09-09 15:08:12 +0000585
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000586 typedef llvm::DenseMap<const FunctionDecl*, const RetainSummary *>
Ted Kremenek00daccd2008-05-05 22:11:16 +0000587 FuncSummariesTy;
Mike Stump11289f42009-09-09 15:08:12 +0000588
Ted Kremenek0cfc1612008-06-23 23:30:29 +0000589 typedef ObjCSummaryCache ObjCMethodSummariesTy;
Mike Stump11289f42009-09-09 15:08:12 +0000590
Jordy Rose61c974b2012-03-18 01:26:10 +0000591 typedef llvm::FoldingSetNodeWrapper<RetainSummary> CachedSummaryNode;
592
Ted Kremenek00daccd2008-05-05 22:11:16 +0000593 //==-----------------------------------------------------------------==//
594 // Data.
595 //==-----------------------------------------------------------------==//
Mike Stump11289f42009-09-09 15:08:12 +0000596
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000597 /// Ctx - The ASTContext object for the analyzed ASTs.
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000598 ASTContext &Ctx;
Ted Kremenekab54e512008-07-01 17:21:27 +0000599
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000600 /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
Ted Kremenek4b7ca772008-04-29 05:33:51 +0000601 const bool GCEnabled;
Mike Stump11289f42009-09-09 15:08:12 +0000602
John McCall31168b02011-06-15 23:02:42 +0000603 /// Records whether or not the analyzed code runs in ARC mode.
604 const bool ARCEnabled;
605
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000606 /// FuncSummaries - A map from FunctionDecls to summaries.
Mike Stump11289f42009-09-09 15:08:12 +0000607 FuncSummariesTy FuncSummaries;
608
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000609 /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
610 /// to summaries.
Ted Kremenekea736c52008-06-23 22:21:20 +0000611 ObjCMethodSummariesTy ObjCClassMethodSummaries;
Ted Kremenek00daccd2008-05-05 22:11:16 +0000612
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000613 /// ObjCMethodSummaries - A map from selectors to summaries.
Ted Kremenekea736c52008-06-23 22:21:20 +0000614 ObjCMethodSummariesTy ObjCMethodSummaries;
Ted Kremenek00daccd2008-05-05 22:11:16 +0000615
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000616 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
617 /// and all other data used by the checker.
Ted Kremenek00daccd2008-05-05 22:11:16 +0000618 llvm::BumpPtrAllocator BPAlloc;
Mike Stump11289f42009-09-09 15:08:12 +0000619
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000620 /// AF - A factory for ArgEffects objects.
Mike Stump11289f42009-09-09 15:08:12 +0000621 ArgEffects::Factory AF;
622
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000623 /// ScratchArgs - A holding buffer for construct ArgEffects.
Ted Kremeneke8300e52012-01-04 00:35:45 +0000624 ArgEffects ScratchArgs;
Mike Stump11289f42009-09-09 15:08:12 +0000625
Ted Kremenek9157fbb2009-05-07 23:40:42 +0000626 /// ObjCAllocRetE - Default return effect for methods returning Objective-C
627 /// objects.
628 RetEffect ObjCAllocRetE;
Ted Kremeneka03705c2009-06-05 23:18:01 +0000629
Mike Stump11289f42009-09-09 15:08:12 +0000630 /// ObjCInitRetE - Default return effect for init methods returning
Ted Kremenek815fbb62009-08-20 05:13:36 +0000631 /// Objective-C objects.
Ted Kremeneka03705c2009-06-05 23:18:01 +0000632 RetEffect ObjCInitRetE;
Mike Stump11289f42009-09-09 15:08:12 +0000633
Jordy Rose61c974b2012-03-18 01:26:10 +0000634 /// SimpleSummaries - Used for uniquing summaries that don't have special
635 /// effects.
636 llvm::FoldingSet<CachedSummaryNode> SimpleSummaries;
Mike Stump11289f42009-09-09 15:08:12 +0000637
Ted Kremenek00daccd2008-05-05 22:11:16 +0000638 //==-----------------------------------------------------------------==//
639 // Methods.
640 //==-----------------------------------------------------------------==//
Mike Stump11289f42009-09-09 15:08:12 +0000641
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000642 /// getArgEffects - Returns a persistent ArgEffects object based on the
643 /// data in ScratchArgs.
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000644 ArgEffects getArgEffects();
Ted Kremenek819e9b62008-03-11 06:39:11 +0000645
Jordan Rose77411322013-10-07 17:16:52 +0000646 enum UnaryFuncKind { cfretain, cfrelease, cfautorelease, cfmakecollectable };
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000647
Ted Kremeneke8300e52012-01-04 00:35:45 +0000648 const RetainSummary *getUnarySummary(const FunctionType* FT,
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000649 UnaryFuncKind func);
Mike Stump11289f42009-09-09 15:08:12 +0000650
Ted Kremeneke8300e52012-01-04 00:35:45 +0000651 const RetainSummary *getCFSummaryCreateRule(const FunctionDecl *FD);
652 const RetainSummary *getCFSummaryGetRule(const FunctionDecl *FD);
653 const RetainSummary *getCFCreateGetRuleSummary(const FunctionDecl *FD);
Mike Stump11289f42009-09-09 15:08:12 +0000654
Jordy Rose61c974b2012-03-18 01:26:10 +0000655 const RetainSummary *getPersistentSummary(const RetainSummary &OldSumm);
Ted Kremenek3700b762008-10-29 04:07:07 +0000656
Jordy Rose61c974b2012-03-18 01:26:10 +0000657 const RetainSummary *getPersistentSummary(RetEffect RetEff,
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000658 ArgEffect ReceiverEff = DoNothing,
659 ArgEffect DefaultEff = MayEscape) {
Jordy Rose61c974b2012-03-18 01:26:10 +0000660 RetainSummary Summ(getArgEffects(), RetEff, DefaultEff, ReceiverEff);
661 return getPersistentSummary(Summ);
662 }
663
Ted Kremenekececf9f2012-05-08 00:12:09 +0000664 const RetainSummary *getDoNothingSummary() {
665 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
666 }
667
Jordy Rose61c974b2012-03-18 01:26:10 +0000668 const RetainSummary *getDefaultSummary() {
669 return getPersistentSummary(RetEffect::MakeNoRet(),
670 DoNothing, MayEscape);
Ted Kremenek0806f912008-05-06 00:30:21 +0000671 }
Mike Stump11289f42009-09-09 15:08:12 +0000672
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000673 const RetainSummary *getPersistentStopSummary() {
Jordy Rose61c974b2012-03-18 01:26:10 +0000674 return getPersistentSummary(RetEffect::MakeNoRet(),
675 StopTracking, StopTracking);
Mike Stump11289f42009-09-09 15:08:12 +0000676 }
Ted Kremenek015c3562008-05-06 04:20:12 +0000677
Ted Kremenekea736c52008-06-23 22:21:20 +0000678 void InitializeClassMethodSummaries();
679 void InitializeMethodSummaries();
Ted Kremenekcc3d1882008-10-23 01:56:15 +0000680private:
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000681 void addNSObjectClsMethSummary(Selector S, const RetainSummary *Summ) {
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000682 ObjCClassMethodSummaries[S] = Summ;
683 }
Mike Stump11289f42009-09-09 15:08:12 +0000684
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000685 void addNSObjectMethSummary(Selector S, const RetainSummary *Summ) {
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000686 ObjCMethodSummaries[S] = Summ;
687 }
Ted Kremenek00dfe302009-03-04 23:30:42 +0000688
Ted Kremeneke8a5ba82012-02-18 21:37:48 +0000689 void addClassMethSummary(const char* Cls, const char* name,
690 const RetainSummary *Summ, bool isNullary = true) {
Ted Kremenek00dfe302009-03-04 23:30:42 +0000691 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
Ted Kremeneke8a5ba82012-02-18 21:37:48 +0000692 Selector S = isNullary ? GetNullarySelector(name, Ctx)
693 : GetUnarySelector(name, Ctx);
Ted Kremenek00dfe302009-03-04 23:30:42 +0000694 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
695 }
Mike Stump11289f42009-09-09 15:08:12 +0000696
Ted Kremenekdce78462009-02-25 02:54:57 +0000697 void addInstMethSummary(const char* Cls, const char* nullaryName,
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000698 const RetainSummary *Summ) {
Ted Kremenekdce78462009-02-25 02:54:57 +0000699 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
700 Selector S = GetNullarySelector(nullaryName, Ctx);
701 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
702 }
Mike Stump11289f42009-09-09 15:08:12 +0000703
Jordan Rose0675c872014-04-09 01:39:22 +0000704 void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy &Summaries,
705 const RetainSummary *Summ, va_list argp) {
706 Selector S = getKeywordSelector(Ctx, argp);
Ted Kremenek8a5ad392009-04-24 17:50:11 +0000707 Summaries[ObjCSummaryKey(ClsII, S)] = Summ;
Ted Kremenek3b2294c2008-07-18 17:24:20 +0000708 }
Mike Stump11289f42009-09-09 15:08:12 +0000709
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000710 void addInstMethSummary(const char* Cls, const RetainSummary * Summ, ...) {
Ted Kremenek3f13f592008-08-12 18:48:50 +0000711 va_list argp;
712 va_start(argp, Summ);
Ted Kremenek8a5ad392009-04-24 17:50:11 +0000713 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Mike Stump11289f42009-09-09 15:08:12 +0000714 va_end(argp);
Ted Kremenek3f13f592008-08-12 18:48:50 +0000715 }
Mike Stump11289f42009-09-09 15:08:12 +0000716
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000717 void addClsMethSummary(const char* Cls, const RetainSummary * Summ, ...) {
Ted Kremenek8a5ad392009-04-24 17:50:11 +0000718 va_list argp;
719 va_start(argp, Summ);
720 addMethodSummary(&Ctx.Idents.get(Cls),ObjCClassMethodSummaries, Summ, argp);
721 va_end(argp);
722 }
Mike Stump11289f42009-09-09 15:08:12 +0000723
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000724 void addClsMethSummary(IdentifierInfo *II, const RetainSummary * Summ, ...) {
Ted Kremenek8a5ad392009-04-24 17:50:11 +0000725 va_list argp;
726 va_start(argp, Summ);
727 addMethodSummary(II, ObjCClassMethodSummaries, Summ, argp);
728 va_end(argp);
729 }
730
Ted Kremenek819e9b62008-03-11 06:39:11 +0000731public:
Mike Stump11289f42009-09-09 15:08:12 +0000732
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000733 RetainSummaryManager(ASTContext &ctx, bool gcenabled, bool usesARC)
Ted Kremenekab54e512008-07-01 17:21:27 +0000734 : Ctx(ctx),
John McCall31168b02011-06-15 23:02:42 +0000735 GCEnabled(gcenabled),
736 ARCEnabled(usesARC),
737 AF(BPAlloc), ScratchArgs(AF.getEmptyMap()),
738 ObjCAllocRetE(gcenabled
739 ? RetEffect::MakeGCNotOwned()
Jordan Rose6ad4cb42014-01-07 21:39:41 +0000740 : (usesARC ? RetEffect::MakeNotOwned(RetEffect::ObjC)
John McCall31168b02011-06-15 23:02:42 +0000741 : RetEffect::MakeOwned(RetEffect::ObjC, true))),
742 ObjCInitRetE(gcenabled
743 ? RetEffect::MakeGCNotOwned()
Jordan Rose6ad4cb42014-01-07 21:39:41 +0000744 : (usesARC ? RetEffect::MakeNotOwned(RetEffect::ObjC)
Jordy Rose61c974b2012-03-18 01:26:10 +0000745 : RetEffect::MakeOwnedWhenTrackedReceiver())) {
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000746 InitializeClassMethodSummaries();
747 InitializeMethodSummaries();
748 }
Mike Stump11289f42009-09-09 15:08:12 +0000749
Jordan Roseeec15392012-07-02 19:27:43 +0000750 const RetainSummary *getSummary(const CallEvent &Call,
Craig Topper0dbb7832014-05-27 02:45:47 +0000751 ProgramStateRef State = nullptr);
Mike Stump11289f42009-09-09 15:08:12 +0000752
Jordan Roseeec15392012-07-02 19:27:43 +0000753 const RetainSummary *getFunctionSummary(const FunctionDecl *FD);
754
755 const RetainSummary *getMethodSummary(Selector S, const ObjCInterfaceDecl *ID,
Jordy Rose35e71c72012-03-17 21:13:07 +0000756 const ObjCMethodDecl *MD,
757 QualType RetTy,
758 ObjCMethodSummariesTy &CachedSummaries);
759
Jordan Rose6bad4902012-07-02 19:27:56 +0000760 const RetainSummary *getInstanceMethodSummary(const ObjCMethodCall &M,
Jordan Roseeec15392012-07-02 19:27:43 +0000761 ProgramStateRef State);
Ted Kremenekbd862712010-07-01 20:16:50 +0000762
Jordan Rose6bad4902012-07-02 19:27:56 +0000763 const RetainSummary *getClassMethodSummary(const ObjCMethodCall &M) {
Jordan Roseeec15392012-07-02 19:27:43 +0000764 assert(!M.isInstanceMessage());
765 const ObjCInterfaceDecl *Class = M.getReceiverInterface();
Mike Stump11289f42009-09-09 15:08:12 +0000766
Jordan Roseeec15392012-07-02 19:27:43 +0000767 return getMethodSummary(M.getSelector(), Class, M.getDecl(),
768 M.getResultType(), ObjCClassMethodSummaries);
Ted Kremenek7686ffa2009-04-29 00:42:39 +0000769 }
Ted Kremenek99fe1692009-04-29 17:17:48 +0000770
771 /// getMethodSummary - This version of getMethodSummary is used to query
772 /// the summary for the current method being analyzed.
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000773 const RetainSummary *getMethodSummary(const ObjCMethodDecl *MD) {
Ted Kremenek223a7d52009-04-29 23:03:22 +0000774 const ObjCInterfaceDecl *ID = MD->getClassInterface();
Ted Kremenekb2a143f2009-04-30 05:41:14 +0000775 Selector S = MD->getSelector();
Alp Toker314cc812014-01-25 16:55:45 +0000776 QualType ResultTy = MD->getReturnType();
Mike Stump11289f42009-09-09 15:08:12 +0000777
Jordy Rose35e71c72012-03-17 21:13:07 +0000778 ObjCMethodSummariesTy *CachedSummaries;
Ted Kremenek99fe1692009-04-29 17:17:48 +0000779 if (MD->isInstanceMethod())
Jordy Rose35e71c72012-03-17 21:13:07 +0000780 CachedSummaries = &ObjCMethodSummaries;
Ted Kremenek99fe1692009-04-29 17:17:48 +0000781 else
Jordy Rose35e71c72012-03-17 21:13:07 +0000782 CachedSummaries = &ObjCClassMethodSummaries;
783
Jordan Roseeec15392012-07-02 19:27:43 +0000784 return getMethodSummary(S, ID, MD, ResultTy, *CachedSummaries);
Ted Kremenek99fe1692009-04-29 17:17:48 +0000785 }
Mike Stump11289f42009-09-09 15:08:12 +0000786
Jordy Rose35e71c72012-03-17 21:13:07 +0000787 const RetainSummary *getStandardMethodSummary(const ObjCMethodDecl *MD,
Jordan Roseeec15392012-07-02 19:27:43 +0000788 Selector S, QualType RetTy);
Ted Kremenek223a7d52009-04-29 23:03:22 +0000789
Jordan Rose39032472013-04-04 22:31:48 +0000790 /// Determine if there is a special return effect for this function or method.
791 Optional<RetEffect> getRetEffectFromAnnotations(QualType RetTy,
792 const Decl *D);
793
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000794 void updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenekc2de7272009-05-09 02:58:13 +0000795 const ObjCMethodDecl *MD);
796
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000797 void updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenekc2de7272009-05-09 02:58:13 +0000798 const FunctionDecl *FD);
799
Jordan Roseeec15392012-07-02 19:27:43 +0000800 void updateSummaryForCall(const RetainSummary *&Summ,
801 const CallEvent &Call);
802
Ted Kremenek00daccd2008-05-05 22:11:16 +0000803 bool isGCEnabled() const { return GCEnabled; }
Mike Stump11289f42009-09-09 15:08:12 +0000804
John McCall31168b02011-06-15 23:02:42 +0000805 bool isARCEnabled() const { return ARCEnabled; }
806
807 bool isARCorGCEnabled() const { return GCEnabled || ARCEnabled; }
Jordan Roseeec15392012-07-02 19:27:43 +0000808
809 RetEffect getObjAllocRetEffect() const { return ObjCAllocRetE; }
810
811 friend class RetainSummaryTemplate;
Ted Kremenek819e9b62008-03-11 06:39:11 +0000812};
Mike Stump11289f42009-09-09 15:08:12 +0000813
Jordy Rose14de7c52011-08-24 09:02:37 +0000814// Used to avoid allocating long-term (BPAlloc'd) memory for default retain
815// summaries. If a function or method looks like it has a default summary, but
816// it has annotations, the annotations are added to the stack-based template
817// and then copied into managed memory.
818class RetainSummaryTemplate {
819 RetainSummaryManager &Manager;
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000820 const RetainSummary *&RealSummary;
Jordy Rose14de7c52011-08-24 09:02:37 +0000821 RetainSummary ScratchSummary;
822 bool Accessed;
823public:
Jordan Roseeec15392012-07-02 19:27:43 +0000824 RetainSummaryTemplate(const RetainSummary *&real, RetainSummaryManager &mgr)
825 : Manager(mgr), RealSummary(real), ScratchSummary(*real), Accessed(false) {}
Jordy Rose14de7c52011-08-24 09:02:37 +0000826
827 ~RetainSummaryTemplate() {
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000828 if (Accessed)
Jordy Rose61c974b2012-03-18 01:26:10 +0000829 RealSummary = Manager.getPersistentSummary(ScratchSummary);
Jordy Rose14de7c52011-08-24 09:02:37 +0000830 }
831
832 RetainSummary &operator*() {
833 Accessed = true;
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000834 return ScratchSummary;
Jordy Rose14de7c52011-08-24 09:02:37 +0000835 }
836
837 RetainSummary *operator->() {
838 Accessed = true;
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000839 return &ScratchSummary;
Jordy Rose14de7c52011-08-24 09:02:37 +0000840 }
841};
842
Ted Kremenek819e9b62008-03-11 06:39:11 +0000843} // end anonymous namespace
844
845//===----------------------------------------------------------------------===//
846// Implementation of checker data structures.
847//===----------------------------------------------------------------------===//
848
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000849ArgEffects RetainSummaryManager::getArgEffects() {
850 ArgEffects AE = ScratchArgs;
Ted Kremenekb3b56c62010-11-24 00:54:37 +0000851 ScratchArgs = AF.getEmptyMap();
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000852 return AE;
Ted Kremenek68d73d12008-03-12 01:21:45 +0000853}
854
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000855const RetainSummary *
Jordy Rose61c974b2012-03-18 01:26:10 +0000856RetainSummaryManager::getPersistentSummary(const RetainSummary &OldSumm) {
857 // Unique "simple" summaries -- those without ArgEffects.
858 if (OldSumm.isSimple()) {
859 llvm::FoldingSetNodeID ID;
860 OldSumm.Profile(ID);
861
862 void *Pos;
863 CachedSummaryNode *N = SimpleSummaries.FindNodeOrInsertPos(ID, Pos);
864
865 if (!N) {
866 N = (CachedSummaryNode *) BPAlloc.Allocate<CachedSummaryNode>();
867 new (N) CachedSummaryNode(OldSumm);
868 SimpleSummaries.InsertNode(N, Pos);
869 }
870
871 return &N->getValue();
872 }
873
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000874 RetainSummary *Summ = (RetainSummary *) BPAlloc.Allocate<RetainSummary>();
Jordy Rose61c974b2012-03-18 01:26:10 +0000875 new (Summ) RetainSummary(OldSumm);
Ted Kremenek68d73d12008-03-12 01:21:45 +0000876 return Summ;
877}
878
Ted Kremenek00daccd2008-05-05 22:11:16 +0000879//===----------------------------------------------------------------------===//
880// Summary creation for functions (largely uses of Core Foundation).
881//===----------------------------------------------------------------------===//
Ted Kremenek68d73d12008-03-12 01:21:45 +0000882
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000883static bool isRetain(const FunctionDecl *FD, StringRef FName) {
Benjamin Kramereaabbd82010-02-08 18:38:55 +0000884 return FName.endswith("Retain");
Ted Kremenek7e904222009-01-12 21:45:02 +0000885}
886
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000887static bool isRelease(const FunctionDecl *FD, StringRef FName) {
Benjamin Kramereaabbd82010-02-08 18:38:55 +0000888 return FName.endswith("Release");
Ted Kremenek7e904222009-01-12 21:45:02 +0000889}
890
Jordan Rose77411322013-10-07 17:16:52 +0000891static bool isAutorelease(const FunctionDecl *FD, StringRef FName) {
892 return FName.endswith("Autorelease");
893}
894
Jordy Rose898a1482011-08-21 21:58:18 +0000895static bool isMakeCollectable(const FunctionDecl *FD, StringRef FName) {
896 // FIXME: Remove FunctionDecl parameter.
897 // FIXME: Is it really okay if MakeCollectable isn't a suffix?
898 return FName.find("MakeCollectable") != StringRef::npos;
899}
900
Anna Zaks25612732012-08-29 23:23:43 +0000901static ArgEffect getStopTrackingHardEquivalent(ArgEffect E) {
Jordan Roseeec15392012-07-02 19:27:43 +0000902 switch (E) {
903 case DoNothing:
904 case Autorelease:
Benjamin Kramer2501f142013-10-20 11:47:15 +0000905 case DecRefBridgedTransferred:
Jordan Roseeec15392012-07-02 19:27:43 +0000906 case IncRef:
907 case IncRefMsg:
908 case MakeCollectable:
Douglas Gregoreb6e64c2015-06-19 23:17:46 +0000909 case UnretainedOutParameter:
910 case RetainedOutParameter:
Jordan Roseeec15392012-07-02 19:27:43 +0000911 case MayEscape:
Jordan Roseeec15392012-07-02 19:27:43 +0000912 case StopTracking:
Anna Zaks25612732012-08-29 23:23:43 +0000913 case StopTrackingHard:
914 return StopTrackingHard;
Jordan Roseeec15392012-07-02 19:27:43 +0000915 case DecRef:
Anna Zaks25612732012-08-29 23:23:43 +0000916 case DecRefAndStopTrackingHard:
917 return DecRefAndStopTrackingHard;
Jordan Roseeec15392012-07-02 19:27:43 +0000918 case DecRefMsg:
Anna Zaks25612732012-08-29 23:23:43 +0000919 case DecRefMsgAndStopTrackingHard:
920 return DecRefMsgAndStopTrackingHard;
Jordan Roseeec15392012-07-02 19:27:43 +0000921 case Dealloc:
922 return Dealloc;
923 }
924
925 llvm_unreachable("Unknown ArgEffect kind");
926}
927
928void RetainSummaryManager::updateSummaryForCall(const RetainSummary *&S,
929 const CallEvent &Call) {
930 if (Call.hasNonZeroCallbackArg()) {
Anna Zaks25612732012-08-29 23:23:43 +0000931 ArgEffect RecEffect =
932 getStopTrackingHardEquivalent(S->getReceiverEffect());
933 ArgEffect DefEffect =
934 getStopTrackingHardEquivalent(S->getDefaultArgEffect());
Jordan Roseeec15392012-07-02 19:27:43 +0000935
936 ArgEffects CustomArgEffects = S->getArgEffects();
937 for (ArgEffects::iterator I = CustomArgEffects.begin(),
938 E = CustomArgEffects.end();
939 I != E; ++I) {
Anna Zaks25612732012-08-29 23:23:43 +0000940 ArgEffect Translated = getStopTrackingHardEquivalent(I->second);
Jordan Roseeec15392012-07-02 19:27:43 +0000941 if (Translated != DefEffect)
942 ScratchArgs = AF.add(ScratchArgs, I->first, Translated);
943 }
944
Anna Zaks25612732012-08-29 23:23:43 +0000945 RetEffect RE = RetEffect::MakeNoRetHard();
Jordan Roseeec15392012-07-02 19:27:43 +0000946
947 // Special cases where the callback argument CANNOT free the return value.
948 // This can generally only happen if we know that the callback will only be
949 // called when the return value is already being deallocated.
Jordan Rose2a833ca2014-01-15 17:25:15 +0000950 if (const SimpleFunctionCall *FC = dyn_cast<SimpleFunctionCall>(&Call)) {
Jordan Roseccf192e2012-09-01 17:39:13 +0000951 if (IdentifierInfo *Name = FC->getDecl()->getIdentifier()) {
952 // When the CGBitmapContext is deallocated, the callback here will free
953 // the associated data buffer.
Jordan Rosed65f1c82012-08-31 18:19:18 +0000954 if (Name->isStr("CGBitmapContextCreateWithData"))
955 RE = S->getRetEffect();
Jordan Roseccf192e2012-09-01 17:39:13 +0000956 }
Jordan Roseeec15392012-07-02 19:27:43 +0000957 }
958
959 S = getPersistentSummary(RE, RecEffect, DefEffect);
960 }
Anna Zaks3d5d3d32012-08-24 00:06:12 +0000961
962 // Special case '[super init];' and '[self init];'
963 //
964 // Even though calling '[super init]' without assigning the result to self
965 // and checking if the parent returns 'nil' is a bad pattern, it is common.
966 // Additionally, our Self Init checker already warns about it. To avoid
967 // overwhelming the user with messages from both checkers, we model the case
968 // of '[super init]' in cases when it is not consumed by another expression
969 // as if the call preserves the value of 'self'; essentially, assuming it can
970 // never fail and return 'nil'.
971 // Note, we don't want to just stop tracking the value since we want the
972 // RetainCount checker to report leaks and use-after-free if SelfInit checker
973 // is turned off.
974 if (const ObjCMethodCall *MC = dyn_cast<ObjCMethodCall>(&Call)) {
975 if (MC->getMethodFamily() == OMF_init && MC->isReceiverSelfOrSuper()) {
976
977 // Check if the message is not consumed, we know it will not be used in
978 // an assignment, ex: "self = [super init]".
979 const Expr *ME = MC->getOriginExpr();
980 const LocationContext *LCtx = MC->getLocationContext();
981 ParentMap &PM = LCtx->getAnalysisDeclContext()->getParentMap();
982 if (!PM.isConsumedExpr(ME)) {
983 RetainSummaryTemplate ModifiableSummaryTemplate(S, *this);
984 ModifiableSummaryTemplate->setReceiverEffect(DoNothing);
985 ModifiableSummaryTemplate->setRetEffect(RetEffect::MakeNoRet());
986 }
987 }
988
989 }
Jordan Roseeec15392012-07-02 19:27:43 +0000990}
991
Anna Zaksf4c5ea52012-05-04 22:18:39 +0000992const RetainSummary *
Jordan Roseeec15392012-07-02 19:27:43 +0000993RetainSummaryManager::getSummary(const CallEvent &Call,
994 ProgramStateRef State) {
995 const RetainSummary *Summ;
996 switch (Call.getKind()) {
997 case CE_Function:
Jordan Rose2a833ca2014-01-15 17:25:15 +0000998 Summ = getFunctionSummary(cast<SimpleFunctionCall>(Call).getDecl());
Jordan Roseeec15392012-07-02 19:27:43 +0000999 break;
1000 case CE_CXXMember:
Jordan Rose017591a2012-07-03 22:55:57 +00001001 case CE_CXXMemberOperator:
Jordan Roseeec15392012-07-02 19:27:43 +00001002 case CE_Block:
1003 case CE_CXXConstructor:
Jordan Rose4ee71b82012-07-10 22:07:47 +00001004 case CE_CXXDestructor:
Jordan Rosea4ee0642012-07-02 22:21:47 +00001005 case CE_CXXAllocator:
Jordan Roseeec15392012-07-02 19:27:43 +00001006 // FIXME: These calls are currently unsupported.
1007 return getPersistentStopSummary();
Jordan Rose627b0462012-07-18 21:59:51 +00001008 case CE_ObjCMessage: {
Jordan Rose6bad4902012-07-02 19:27:56 +00001009 const ObjCMethodCall &Msg = cast<ObjCMethodCall>(Call);
Jordan Roseeec15392012-07-02 19:27:43 +00001010 if (Msg.isInstanceMessage())
1011 Summ = getInstanceMethodSummary(Msg, State);
1012 else
1013 Summ = getClassMethodSummary(Msg);
1014 break;
1015 }
1016 }
1017
1018 updateSummaryForCall(Summ, Call);
1019
1020 assert(Summ && "Unknown call type?");
1021 return Summ;
1022}
1023
1024const RetainSummary *
1025RetainSummaryManager::getFunctionSummary(const FunctionDecl *FD) {
1026 // If we don't know what function we're calling, use our default summary.
1027 if (!FD)
1028 return getDefaultSummary();
1029
Ted Kremenekf7141592008-04-24 17:22:33 +00001030 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremenek00daccd2008-05-05 22:11:16 +00001031 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremenek00daccd2008-05-05 22:11:16 +00001032 if (I != FuncSummaries.end())
Ted Kremenekf7141592008-04-24 17:22:33 +00001033 return I->second;
1034
Ted Kremenekdf76e6d2009-05-04 15:34:07 +00001035 // No summary? Generate one.
Craig Topper0dbb7832014-05-27 02:45:47 +00001036 const RetainSummary *S = nullptr;
Jordan Rose1c715602012-08-06 21:28:02 +00001037 bool AllowAnnotations = true;
Mike Stump11289f42009-09-09 15:08:12 +00001038
Ted Kremenekfa89e2f2008-07-15 16:50:12 +00001039 do {
Ted Kremenek7e904222009-01-12 21:45:02 +00001040 // We generate "stop" summaries for implicitly defined functions.
1041 if (FD->isImplicit()) {
1042 S = getPersistentStopSummary();
1043 break;
Ted Kremenekfa89e2f2008-07-15 16:50:12 +00001044 }
Mike Stump11289f42009-09-09 15:08:12 +00001045
John McCall9dd450b2009-09-21 23:43:11 +00001046 // [PR 3337] Use 'getAs<FunctionType>' to strip away any typedefs on the
Ted Kremenek86afde32009-01-16 18:40:33 +00001047 // function's type.
John McCall9dd450b2009-09-21 23:43:11 +00001048 const FunctionType* FT = FD->getType()->getAs<FunctionType>();
Ted Kremenek9bcc2642009-12-16 06:06:43 +00001049 const IdentifierInfo *II = FD->getIdentifier();
1050 if (!II)
1051 break;
Benjamin Kramereaabbd82010-02-08 18:38:55 +00001052
1053 StringRef FName = II->getName();
Mike Stump11289f42009-09-09 15:08:12 +00001054
Ted Kremenek5f968932009-03-05 22:11:14 +00001055 // Strip away preceding '_'. Doing this here will effect all the checks
1056 // down below.
Benjamin Kramereaabbd82010-02-08 18:38:55 +00001057 FName = FName.substr(FName.find_first_not_of('_'));
Mike Stump11289f42009-09-09 15:08:12 +00001058
Ted Kremenek7e904222009-01-12 21:45:02 +00001059 // Inspect the result type.
Alp Toker314cc812014-01-25 16:55:45 +00001060 QualType RetTy = FT->getReturnType();
Mike Stump11289f42009-09-09 15:08:12 +00001061
Ted Kremenek7e904222009-01-12 21:45:02 +00001062 // FIXME: This should all be refactored into a chain of "summary lookup"
1063 // filters.
Ted Kremenekb4ec3fc2009-10-14 00:27:24 +00001064 assert(ScratchArgs.isEmpty());
Ted Kremenek3092e9c2009-06-15 20:36:07 +00001065
Ted Kremenek01d152f2012-04-26 04:32:23 +00001066 if (FName == "pthread_create" || FName == "pthread_setspecific") {
1067 // Part of: <rdar://problem/7299394> and <rdar://problem/11282706>.
1068 // This will be addressed better with IPA.
Benjamin Kramereaabbd82010-02-08 18:38:55 +00001069 S = getPersistentStopSummary();
1070 } else if (FName == "NSMakeCollectable") {
1071 // Handle: id NSMakeCollectable(CFTypeRef)
1072 S = (RetTy->isObjCIdType())
1073 ? getUnarySummary(FT, cfmakecollectable)
1074 : getPersistentStopSummary();
Jordan Rose1c715602012-08-06 21:28:02 +00001075 // The headers on OS X 10.8 use cf_consumed/ns_returns_retained,
1076 // but we can fully model NSMakeCollectable ourselves.
1077 AllowAnnotations = false;
Ted Kremenekc008db92012-09-06 23:47:02 +00001078 } else if (FName == "CFPlugInInstanceCreate") {
1079 S = getPersistentSummary(RetEffect::MakeNoRet());
Benjamin Kramereaabbd82010-02-08 18:38:55 +00001080 } else if (FName == "IOBSDNameMatching" ||
1081 FName == "IOServiceMatching" ||
1082 FName == "IOServiceNameMatching" ||
Ted Kremenek555560c2012-05-01 05:28:27 +00001083 FName == "IORegistryEntrySearchCFProperty" ||
Benjamin Kramereaabbd82010-02-08 18:38:55 +00001084 FName == "IORegistryEntryIDMatching" ||
1085 FName == "IOOpenFirmwarePathMatching") {
1086 // Part of <rdar://problem/6961230>. (IOKit)
1087 // This should be addressed using a API table.
1088 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1089 DoNothing, DoNothing);
1090 } else if (FName == "IOServiceGetMatchingService" ||
1091 FName == "IOServiceGetMatchingServices") {
1092 // FIXES: <rdar://problem/6326900>
1093 // This should be addressed using a API table. This strcmp is also
1094 // a little gross, but there is no need to super optimize here.
Ted Kremenekb3b56c62010-11-24 00:54:37 +00001095 ScratchArgs = AF.add(ScratchArgs, 1, DecRef);
Benjamin Kramereaabbd82010-02-08 18:38:55 +00001096 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1097 } else if (FName == "IOServiceAddNotification" ||
1098 FName == "IOServiceAddMatchingNotification") {
1099 // Part of <rdar://problem/6961230>. (IOKit)
1100 // This should be addressed using a API table.
Ted Kremenekb3b56c62010-11-24 00:54:37 +00001101 ScratchArgs = AF.add(ScratchArgs, 2, DecRef);
Benjamin Kramereaabbd82010-02-08 18:38:55 +00001102 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1103 } else if (FName == "CVPixelBufferCreateWithBytes") {
1104 // FIXES: <rdar://problem/7283567>
1105 // Eventually this can be improved by recognizing that the pixel
1106 // buffer passed to CVPixelBufferCreateWithBytes is released via
1107 // a callback and doing full IPA to make sure this is done correctly.
1108 // FIXME: This function has an out parameter that returns an
1109 // allocated object.
Ted Kremenekb3b56c62010-11-24 00:54:37 +00001110 ScratchArgs = AF.add(ScratchArgs, 7, StopTracking);
Benjamin Kramereaabbd82010-02-08 18:38:55 +00001111 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1112 } else if (FName == "CGBitmapContextCreateWithData") {
1113 // FIXES: <rdar://problem/7358899>
1114 // Eventually this can be improved by recognizing that 'releaseInfo'
1115 // passed to CGBitmapContextCreateWithData is released via
1116 // a callback and doing full IPA to make sure this is done correctly.
Ted Kremenekb3b56c62010-11-24 00:54:37 +00001117 ScratchArgs = AF.add(ScratchArgs, 8, StopTracking);
Benjamin Kramereaabbd82010-02-08 18:38:55 +00001118 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1119 DoNothing, DoNothing);
1120 } else if (FName == "CVPixelBufferCreateWithPlanarBytes") {
1121 // FIXES: <rdar://problem/7283567>
1122 // Eventually this can be improved by recognizing that the pixel
1123 // buffer passed to CVPixelBufferCreateWithPlanarBytes is released
1124 // via a callback and doing full IPA to make sure this is done
1125 // correctly.
Ted Kremenekb3b56c62010-11-24 00:54:37 +00001126 ScratchArgs = AF.add(ScratchArgs, 12, StopTracking);
Benjamin Kramereaabbd82010-02-08 18:38:55 +00001127 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Jordan Roseb1479182013-05-02 01:51:40 +00001128 } else if (FName == "dispatch_set_context" ||
1129 FName == "xpc_connection_set_context") {
Ted Kremenek40c13432012-03-22 06:29:41 +00001130 // <rdar://problem/11059275> - The analyzer currently doesn't have
1131 // a good way to reason about the finalizer function for libdispatch.
1132 // If we pass a context object that is memory managed, stop tracking it.
Jordan Roseb1479182013-05-02 01:51:40 +00001133 // <rdar://problem/13783514> - Same problem, but for XPC.
Ted Kremenek40c13432012-03-22 06:29:41 +00001134 // FIXME: this hack should possibly go away once we can handle
Jordan Roseb1479182013-05-02 01:51:40 +00001135 // libdispatch and XPC finalizers.
Ted Kremenek40c13432012-03-22 06:29:41 +00001136 ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
1137 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenekececf9f2012-05-08 00:12:09 +00001138 } else if (FName.startswith("NSLog")) {
1139 S = getDoNothingSummary();
Anna Zaks90ab9bf2012-03-30 05:48:16 +00001140 } else if (FName.startswith("NS") &&
1141 (FName.find("Insert") != StringRef::npos)) {
1142 // Whitelist NSXXInsertXX, for example NSMapInsertIfAbsent, since they can
1143 // be deallocated by NSMapRemove. (radar://11152419)
1144 ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
1145 ScratchArgs = AF.add(ScratchArgs, 2, StopTracking);
1146 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenekea675cf2009-06-11 18:17:24 +00001147 }
Mike Stump11289f42009-09-09 15:08:12 +00001148
Ted Kremenekea675cf2009-06-11 18:17:24 +00001149 // Did we get a summary?
1150 if (S)
1151 break;
Ted Kremenek211094d2009-03-17 22:43:44 +00001152
Jordan Rose85707b22013-03-04 23:21:32 +00001153 if (RetTy->isPointerType()) {
Ted Kremenek7e904222009-01-12 21:45:02 +00001154 // For CoreFoundation ('CF') types.
Ted Kremeneke9918352010-01-27 18:00:17 +00001155 if (cocoa::isRefType(RetTy, "CF", FName)) {
Jordan Rose77411322013-10-07 17:16:52 +00001156 if (isRetain(FD, FName)) {
Ted Kremenek7e904222009-01-12 21:45:02 +00001157 S = getUnarySummary(FT, cfretain);
Jordan Rose77411322013-10-07 17:16:52 +00001158 } else if (isAutorelease(FD, FName)) {
1159 S = getUnarySummary(FT, cfautorelease);
1160 // The headers use cf_consumed, but we can fully model CFAutorelease
1161 // ourselves.
1162 AllowAnnotations = false;
1163 } else if (isMakeCollectable(FD, FName)) {
Ted Kremenek7e904222009-01-12 21:45:02 +00001164 S = getUnarySummary(FT, cfmakecollectable);
Jordan Rose77411322013-10-07 17:16:52 +00001165 AllowAnnotations = false;
1166 } else {
John McCall525f0552011-10-01 00:48:56 +00001167 S = getCFCreateGetRuleSummary(FD);
Jordan Rose77411322013-10-07 17:16:52 +00001168 }
Ted Kremenek7e904222009-01-12 21:45:02 +00001169
1170 break;
1171 }
1172
1173 // For CoreGraphics ('CG') types.
Ted Kremeneke9918352010-01-27 18:00:17 +00001174 if (cocoa::isRefType(RetTy, "CG", FName)) {
Ted Kremenek7e904222009-01-12 21:45:02 +00001175 if (isRetain(FD, FName))
1176 S = getUnarySummary(FT, cfretain);
1177 else
John McCall525f0552011-10-01 00:48:56 +00001178 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek7e904222009-01-12 21:45:02 +00001179
1180 break;
1181 }
1182
1183 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
Ted Kremeneke9918352010-01-27 18:00:17 +00001184 if (cocoa::isRefType(RetTy, "DADisk") ||
1185 cocoa::isRefType(RetTy, "DADissenter") ||
1186 cocoa::isRefType(RetTy, "DASessionRef")) {
John McCall525f0552011-10-01 00:48:56 +00001187 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek7e904222009-01-12 21:45:02 +00001188 break;
1189 }
Mike Stump11289f42009-09-09 15:08:12 +00001190
Aaron Ballman9ead1242013-12-19 02:39:40 +00001191 if (FD->hasAttr<CFAuditedTransferAttr>()) {
Jordan Rose85707b22013-03-04 23:21:32 +00001192 S = getCFCreateGetRuleSummary(FD);
1193 break;
1194 }
1195
Ted Kremenek7e904222009-01-12 21:45:02 +00001196 break;
1197 }
1198
1199 // Check for release functions, the only kind of functions that we care
1200 // about that don't return a pointer type.
1201 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
Ted Kremenekac5ab792010-02-08 16:45:01 +00001202 // Test for 'CGCF'.
Benjamin Kramereaabbd82010-02-08 18:38:55 +00001203 FName = FName.substr(FName.startswith("CGCF") ? 4 : 2);
Ted Kremenekac5ab792010-02-08 16:45:01 +00001204
Ted Kremenek5f968932009-03-05 22:11:14 +00001205 if (isRelease(FD, FName))
Ted Kremenek7e904222009-01-12 21:45:02 +00001206 S = getUnarySummary(FT, cfrelease);
1207 else {
Ted Kremenek7d79a5f2009-05-03 05:20:50 +00001208 assert (ScratchArgs.isEmpty());
Ted Kremeneked90de42009-01-29 22:45:13 +00001209 // Remaining CoreFoundation and CoreGraphics functions.
1210 // We use to assume that they all strictly followed the ownership idiom
1211 // and that ownership cannot be transferred. While this is technically
1212 // correct, many methods allow a tracked object to escape. For example:
1213 //
Mike Stump11289f42009-09-09 15:08:12 +00001214 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
Ted Kremeneked90de42009-01-29 22:45:13 +00001215 // CFDictionaryAddValue(y, key, x);
Mike Stump11289f42009-09-09 15:08:12 +00001216 // CFRelease(x);
Ted Kremeneked90de42009-01-29 22:45:13 +00001217 // ... it is okay to use 'x' since 'y' has a reference to it
1218 //
1219 // We handle this and similar cases with the follow heuristic. If the
Ted Kremenekd982f002009-08-20 00:57:22 +00001220 // function name contains "InsertValue", "SetValue", "AddValue",
1221 // "AppendValue", or "SetAttribute", then we assume that arguments may
1222 // "escape." This means that something else holds on to the object,
1223 // allowing it be used even after its local retain count drops to 0.
Benjamin Kramer0129bd72010-01-11 19:46:28 +00001224 ArgEffect E = (StrInStrNoCase(FName, "InsertValue") != StringRef::npos||
1225 StrInStrNoCase(FName, "AddValue") != StringRef::npos ||
1226 StrInStrNoCase(FName, "SetValue") != StringRef::npos ||
1227 StrInStrNoCase(FName, "AppendValue") != StringRef::npos||
Benjamin Kramer37808312010-01-11 20:15:06 +00001228 StrInStrNoCase(FName, "SetAttribute") != StringRef::npos)
Ted Kremeneked90de42009-01-29 22:45:13 +00001229 ? MayEscape : DoNothing;
Mike Stump11289f42009-09-09 15:08:12 +00001230
Ted Kremeneked90de42009-01-29 22:45:13 +00001231 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek7e904222009-01-12 21:45:02 +00001232 }
1233 }
Ted Kremenekfa89e2f2008-07-15 16:50:12 +00001234 }
1235 while (0);
Mike Stump11289f42009-09-09 15:08:12 +00001236
Jordan Roseeec15392012-07-02 19:27:43 +00001237 // If we got all the way here without any luck, use a default summary.
1238 if (!S)
1239 S = getDefaultSummary();
1240
Ted Kremenekc2de7272009-05-09 02:58:13 +00001241 // Annotations override defaults.
Jordan Rose1c715602012-08-06 21:28:02 +00001242 if (AllowAnnotations)
1243 updateSummaryFromAnnotations(S, FD);
Mike Stump11289f42009-09-09 15:08:12 +00001244
Ted Kremenek00daccd2008-05-05 22:11:16 +00001245 FuncSummaries[FD] = S;
Mike Stump11289f42009-09-09 15:08:12 +00001246 return S;
Ted Kremenekea6507f2008-03-06 00:08:09 +00001247}
1248
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001249const RetainSummary *
John McCall525f0552011-10-01 00:48:56 +00001250RetainSummaryManager::getCFCreateGetRuleSummary(const FunctionDecl *FD) {
1251 if (coreFoundation::followsCreateRule(FD))
Ted Kremenek875db812008-05-05 16:51:50 +00001252 return getCFSummaryCreateRule(FD);
Mike Stump11289f42009-09-09 15:08:12 +00001253
Ted Kremenek8e2c9b02011-05-25 06:19:45 +00001254 return getCFSummaryGetRule(FD);
Ted Kremenek875db812008-05-05 16:51:50 +00001255}
1256
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001257const RetainSummary *
Ted Kremenek82157a12009-02-23 16:51:39 +00001258RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1259 UnaryFuncKind func) {
1260
Ted Kremenek7e904222009-01-12 21:45:02 +00001261 // Sanity check that this is *really* a unary function. This can
1262 // happen if people do weird things.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001263 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
Alp Toker9cacbab2014-01-20 20:26:09 +00001264 if (!FTP || FTP->getNumParams() != 1)
Ted Kremenek7e904222009-01-12 21:45:02 +00001265 return getPersistentStopSummary();
Mike Stump11289f42009-09-09 15:08:12 +00001266
Ted Kremenek7d79a5f2009-05-03 05:20:50 +00001267 assert (ScratchArgs.isEmpty());
Mike Stump11289f42009-09-09 15:08:12 +00001268
Jordy Rose898a1482011-08-21 21:58:18 +00001269 ArgEffect Effect;
Ted Kremenek4b7ca772008-04-29 05:33:51 +00001270 switch (func) {
Jordan Rose77411322013-10-07 17:16:52 +00001271 case cfretain: Effect = IncRef; break;
1272 case cfrelease: Effect = DecRef; break;
1273 case cfautorelease: Effect = Autorelease; break;
1274 case cfmakecollectable: Effect = MakeCollectable; break;
Ted Kremenek4b772092008-04-10 23:44:06 +00001275 }
Jordy Rose898a1482011-08-21 21:58:18 +00001276
1277 ScratchArgs = AF.add(ScratchArgs, 0, Effect);
1278 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenek68d73d12008-03-12 01:21:45 +00001279}
1280
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001281const RetainSummary *
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001282RetainSummaryManager::getCFSummaryCreateRule(const FunctionDecl *FD) {
Ted Kremenek7d79a5f2009-05-03 05:20:50 +00001283 assert (ScratchArgs.isEmpty());
Mike Stump11289f42009-09-09 15:08:12 +00001284
Ted Kremenekaeb115f2009-01-28 05:56:51 +00001285 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenek68d73d12008-03-12 01:21:45 +00001286}
1287
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001288const RetainSummary *
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001289RetainSummaryManager::getCFSummaryGetRule(const FunctionDecl *FD) {
Mike Stump11289f42009-09-09 15:08:12 +00001290 assert (ScratchArgs.isEmpty());
Ted Kremenekaeb115f2009-01-28 05:56:51 +00001291 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1292 DoNothing, DoNothing);
Ted Kremenek68d73d12008-03-12 01:21:45 +00001293}
1294
Ted Kremenek819e9b62008-03-11 06:39:11 +00001295//===----------------------------------------------------------------------===//
Ted Kremenek00daccd2008-05-05 22:11:16 +00001296// Summary creation for Selectors.
1297//===----------------------------------------------------------------------===//
1298
Jordan Rose39032472013-04-04 22:31:48 +00001299Optional<RetEffect>
1300RetainSummaryManager::getRetEffectFromAnnotations(QualType RetTy,
1301 const Decl *D) {
1302 if (cocoa::isCocoaObjectRef(RetTy)) {
Aaron Ballman9ead1242013-12-19 02:39:40 +00001303 if (D->hasAttr<NSReturnsRetainedAttr>())
Jordan Rose39032472013-04-04 22:31:48 +00001304 return ObjCAllocRetE;
1305
Aaron Ballman9ead1242013-12-19 02:39:40 +00001306 if (D->hasAttr<NSReturnsNotRetainedAttr>() ||
1307 D->hasAttr<NSReturnsAutoreleasedAttr>())
Jordan Rose39032472013-04-04 22:31:48 +00001308 return RetEffect::MakeNotOwned(RetEffect::ObjC);
1309
1310 } else if (!RetTy->isPointerType()) {
1311 return None;
1312 }
1313
Aaron Ballman9ead1242013-12-19 02:39:40 +00001314 if (D->hasAttr<CFReturnsRetainedAttr>())
Jordan Rose39032472013-04-04 22:31:48 +00001315 return RetEffect::MakeOwned(RetEffect::CF, true);
1316
Aaron Ballman9ead1242013-12-19 02:39:40 +00001317 if (D->hasAttr<CFReturnsNotRetainedAttr>())
Jordan Rose39032472013-04-04 22:31:48 +00001318 return RetEffect::MakeNotOwned(RetEffect::CF);
1319
1320 return None;
1321}
1322
Ted Kremenekc2de7272009-05-09 02:58:13 +00001323void
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001324RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenekc2de7272009-05-09 02:58:13 +00001325 const FunctionDecl *FD) {
1326 if (!FD)
1327 return;
1328
Jordan Roseeec15392012-07-02 19:27:43 +00001329 assert(Summ && "Must have a summary to add annotations to.");
1330 RetainSummaryTemplate Template(Summ, *this);
Jordy Rose212e4592011-08-23 04:27:15 +00001331
Ted Kremenekafe348e2011-01-27 18:43:03 +00001332 // Effects on the parameters.
1333 unsigned parm_idx = 0;
1334 for (FunctionDecl::param_const_iterator pi = FD->param_begin(),
John McCall3337ca52011-04-06 09:02:12 +00001335 pe = FD->param_end(); pi != pe; ++pi, ++parm_idx) {
Ted Kremenekafe348e2011-01-27 18:43:03 +00001336 const ParmVarDecl *pd = *pi;
Aaron Ballman9ead1242013-12-19 02:39:40 +00001337 if (pd->hasAttr<NSConsumedAttr>())
Jordan Rose39032472013-04-04 22:31:48 +00001338 Template->addArg(AF, parm_idx, DecRefMsg);
Aaron Ballman9ead1242013-12-19 02:39:40 +00001339 else if (pd->hasAttr<CFConsumedAttr>())
Douglas Gregoreb6e64c2015-06-19 23:17:46 +00001340 Template->addArg(AF, parm_idx, DecRef);
1341 else if (pd->hasAttr<CFReturnsRetainedAttr>()) {
1342 QualType PointeeTy = pd->getType()->getPointeeType();
1343 if (!PointeeTy.isNull())
1344 if (coreFoundation::isCFObjectRef(PointeeTy))
1345 Template->addArg(AF, parm_idx, RetainedOutParameter);
1346 } else if (pd->hasAttr<CFReturnsNotRetainedAttr>()) {
1347 QualType PointeeTy = pd->getType()->getPointeeType();
1348 if (!PointeeTy.isNull())
1349 if (coreFoundation::isCFObjectRef(PointeeTy))
1350 Template->addArg(AF, parm_idx, UnretainedOutParameter);
1351 }
Ted Kremenekafe348e2011-01-27 18:43:03 +00001352 }
Alp Toker314cc812014-01-25 16:55:45 +00001353
1354 QualType RetTy = FD->getReturnType();
Jordan Rose39032472013-04-04 22:31:48 +00001355 if (Optional<RetEffect> RetE = getRetEffectFromAnnotations(RetTy, FD))
1356 Template->setRetEffect(*RetE);
Ted Kremenekc2de7272009-05-09 02:58:13 +00001357}
1358
1359void
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001360RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
1361 const ObjCMethodDecl *MD) {
Ted Kremenekc2de7272009-05-09 02:58:13 +00001362 if (!MD)
1363 return;
1364
Jordan Roseeec15392012-07-02 19:27:43 +00001365 assert(Summ && "Must have a valid summary to add annotations to");
1366 RetainSummaryTemplate Template(Summ, *this);
Mike Stump11289f42009-09-09 15:08:12 +00001367
Ted Kremenek0e898382011-01-27 06:54:14 +00001368 // Effects on the receiver.
Aaron Ballman9ead1242013-12-19 02:39:40 +00001369 if (MD->hasAttr<NSConsumesSelfAttr>())
Jordan Rose39032472013-04-04 22:31:48 +00001370 Template->setReceiverEffect(DecRefMsg);
Ted Kremenekafe348e2011-01-27 18:43:03 +00001371
1372 // Effects on the parameters.
1373 unsigned parm_idx = 0;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00001374 for (ObjCMethodDecl::param_const_iterator
1375 pi=MD->param_begin(), pe=MD->param_end();
Ted Kremenekafe348e2011-01-27 18:43:03 +00001376 pi != pe; ++pi, ++parm_idx) {
1377 const ParmVarDecl *pd = *pi;
Aaron Ballman9ead1242013-12-19 02:39:40 +00001378 if (pd->hasAttr<NSConsumedAttr>())
Jordan Rose39032472013-04-04 22:31:48 +00001379 Template->addArg(AF, parm_idx, DecRefMsg);
Aaron Ballman9ead1242013-12-19 02:39:40 +00001380 else if (pd->hasAttr<CFConsumedAttr>()) {
Jordy Rose14de7c52011-08-24 09:02:37 +00001381 Template->addArg(AF, parm_idx, DecRef);
Douglas Gregoreb6e64c2015-06-19 23:17:46 +00001382 } else if (pd->hasAttr<CFReturnsRetainedAttr>()) {
1383 QualType PointeeTy = pd->getType()->getPointeeType();
1384 if (!PointeeTy.isNull())
1385 if (coreFoundation::isCFObjectRef(PointeeTy))
1386 Template->addArg(AF, parm_idx, RetainedOutParameter);
1387 } else if (pd->hasAttr<CFReturnsNotRetainedAttr>()) {
1388 QualType PointeeTy = pd->getType()->getPointeeType();
1389 if (!PointeeTy.isNull())
1390 if (coreFoundation::isCFObjectRef(PointeeTy))
1391 Template->addArg(AF, parm_idx, UnretainedOutParameter);
1392 }
Ted Kremenek0e898382011-01-27 06:54:14 +00001393 }
Alp Toker314cc812014-01-25 16:55:45 +00001394
1395 QualType RetTy = MD->getReturnType();
Jordan Rose39032472013-04-04 22:31:48 +00001396 if (Optional<RetEffect> RetE = getRetEffectFromAnnotations(RetTy, MD))
1397 Template->setRetEffect(*RetE);
Ted Kremenekc2de7272009-05-09 02:58:13 +00001398}
1399
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001400const RetainSummary *
Jordy Rose35e71c72012-03-17 21:13:07 +00001401RetainSummaryManager::getStandardMethodSummary(const ObjCMethodDecl *MD,
1402 Selector S, QualType RetTy) {
Jordy Rose70638832012-03-17 19:53:04 +00001403 // Any special effects?
Ted Kremenek6a966b22009-04-24 21:56:17 +00001404 ArgEffect ReceiverEff = DoNothing;
Jordy Rose70638832012-03-17 19:53:04 +00001405 RetEffect ResultEff = RetEffect::MakeNoRet();
1406
1407 // Check the method family, and apply any default annotations.
1408 switch (MD ? MD->getMethodFamily() : S.getMethodFamily()) {
1409 case OMF_None:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00001410 case OMF_initialize:
Jordy Rose70638832012-03-17 19:53:04 +00001411 case OMF_performSelector:
1412 // Assume all Objective-C methods follow Cocoa Memory Management rules.
1413 // FIXME: Does the non-threaded performSelector family really belong here?
1414 // The selector could be, say, @selector(copy).
1415 if (cocoa::isCocoaObjectRef(RetTy))
1416 ResultEff = RetEffect::MakeNotOwned(RetEffect::ObjC);
1417 else if (coreFoundation::isCFObjectRef(RetTy)) {
1418 // ObjCMethodDecl currently doesn't consider CF objects as valid return
1419 // values for alloc, new, copy, or mutableCopy, so we have to
1420 // double-check with the selector. This is ugly, but there aren't that
1421 // many Objective-C methods that return CF objects, right?
1422 if (MD) {
1423 switch (S.getMethodFamily()) {
1424 case OMF_alloc:
1425 case OMF_new:
1426 case OMF_copy:
1427 case OMF_mutableCopy:
1428 ResultEff = RetEffect::MakeOwned(RetEffect::CF, true);
1429 break;
1430 default:
1431 ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1432 break;
1433 }
1434 } else {
1435 ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1436 }
1437 }
1438 break;
1439 case OMF_init:
1440 ResultEff = ObjCInitRetE;
1441 ReceiverEff = DecRefMsg;
1442 break;
1443 case OMF_alloc:
1444 case OMF_new:
1445 case OMF_copy:
1446 case OMF_mutableCopy:
1447 if (cocoa::isCocoaObjectRef(RetTy))
1448 ResultEff = ObjCAllocRetE;
1449 else if (coreFoundation::isCFObjectRef(RetTy))
1450 ResultEff = RetEffect::MakeOwned(RetEffect::CF, true);
1451 break;
1452 case OMF_autorelease:
1453 ReceiverEff = Autorelease;
1454 break;
1455 case OMF_retain:
1456 ReceiverEff = IncRefMsg;
1457 break;
1458 case OMF_release:
1459 ReceiverEff = DecRefMsg;
1460 break;
1461 case OMF_dealloc:
1462 ReceiverEff = Dealloc;
1463 break;
1464 case OMF_self:
1465 // -self is handled specially by the ExprEngine to propagate the receiver.
1466 break;
1467 case OMF_retainCount:
1468 case OMF_finalize:
1469 // These methods don't return objects.
1470 break;
1471 }
Mike Stump11289f42009-09-09 15:08:12 +00001472
Ted Kremenek6a966b22009-04-24 21:56:17 +00001473 // If one of the arguments in the selector has the keyword 'delegate' we
1474 // should stop tracking the reference count for the receiver. This is
1475 // because the reference count is quite possibly handled by a delegate
1476 // method.
1477 if (S.isKeywordSelector()) {
Jordan Rose95dfae82012-06-15 18:19:52 +00001478 for (unsigned i = 0, e = S.getNumArgs(); i != e; ++i) {
1479 StringRef Slot = S.getNameForSlot(i);
1480 if (Slot.substr(Slot.size() - 8).equals_lower("delegate")) {
1481 if (ResultEff == ObjCInitRetE)
Anna Zaks25612732012-08-29 23:23:43 +00001482 ResultEff = RetEffect::MakeNoRetHard();
Jordan Rose95dfae82012-06-15 18:19:52 +00001483 else
Anna Zaks25612732012-08-29 23:23:43 +00001484 ReceiverEff = StopTrackingHard;
Jordan Rose95dfae82012-06-15 18:19:52 +00001485 }
1486 }
Ted Kremenek6a966b22009-04-24 21:56:17 +00001487 }
Mike Stump11289f42009-09-09 15:08:12 +00001488
Jordy Rose70638832012-03-17 19:53:04 +00001489 if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing &&
1490 ResultEff.getKind() == RetEffect::NoRet)
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001491 return getDefaultSummary();
Mike Stump11289f42009-09-09 15:08:12 +00001492
Jordy Rose70638832012-03-17 19:53:04 +00001493 return getPersistentSummary(ResultEff, ReceiverEff, MayEscape);
Ted Kremenek60746a02009-04-23 23:08:22 +00001494}
1495
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001496const RetainSummary *
Jordan Rose6bad4902012-07-02 19:27:56 +00001497RetainSummaryManager::getInstanceMethodSummary(const ObjCMethodCall &Msg,
Jordan Roseeec15392012-07-02 19:27:43 +00001498 ProgramStateRef State) {
Craig Topper0dbb7832014-05-27 02:45:47 +00001499 const ObjCInterfaceDecl *ReceiverClass = nullptr;
Ted Kremeneka2968e52009-11-13 01:54:21 +00001500
Jordan Roseeec15392012-07-02 19:27:43 +00001501 // We do better tracking of the type of the object than the core ExprEngine.
1502 // See if we have its type in our private state.
1503 // FIXME: Eventually replace the use of state->get<RefBindings> with
1504 // a generic API for reasoning about the Objective-C types of symbolic
1505 // objects.
1506 SVal ReceiverV = Msg.getReceiverSVal();
1507 if (SymbolRef Sym = ReceiverV.getAsLocSymbol())
Anna Zaksf5788c72012-08-14 00:36:15 +00001508 if (const RefVal *T = getRefBinding(State, Sym))
Douglas Gregor9a129192010-04-21 00:45:42 +00001509 if (const ObjCObjectPointerType *PT =
Jordan Roseeec15392012-07-02 19:27:43 +00001510 T->getType()->getAs<ObjCObjectPointerType>())
1511 ReceiverClass = PT->getInterfaceDecl();
1512
1513 // If we don't know what kind of object this is, fall back to its static type.
1514 if (!ReceiverClass)
1515 ReceiverClass = Msg.getReceiverInterface();
Douglas Gregor9a129192010-04-21 00:45:42 +00001516
Ted Kremeneka2968e52009-11-13 01:54:21 +00001517 // FIXME: The receiver could be a reference to a class, meaning that
1518 // we should use the class method.
Jordan Roseeec15392012-07-02 19:27:43 +00001519 // id x = [NSObject class];
1520 // [x performSelector:... withObject:... afterDelay:...];
1521 Selector S = Msg.getSelector();
1522 const ObjCMethodDecl *Method = Msg.getDecl();
1523 if (!Method && ReceiverClass)
1524 Method = ReceiverClass->getInstanceMethod(S);
1525
1526 return getMethodSummary(S, ReceiverClass, Method, Msg.getResultType(),
1527 ObjCMethodSummaries);
Ted Kremeneka2968e52009-11-13 01:54:21 +00001528}
1529
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001530const RetainSummary *
Jordan Roseeec15392012-07-02 19:27:43 +00001531RetainSummaryManager::getMethodSummary(Selector S, const ObjCInterfaceDecl *ID,
Jordy Rose35e71c72012-03-17 21:13:07 +00001532 const ObjCMethodDecl *MD, QualType RetTy,
1533 ObjCMethodSummariesTy &CachedSummaries) {
Ted Kremenekcb2e6362008-05-06 15:44:25 +00001534
Ted Kremenek0b50fb12009-04-29 05:04:30 +00001535 // Look up a summary in our summary cache.
Jordan Roseeec15392012-07-02 19:27:43 +00001536 const RetainSummary *Summ = CachedSummaries.find(ID, S);
Mike Stump11289f42009-09-09 15:08:12 +00001537
Ted Kremenek8be51382009-07-21 23:27:57 +00001538 if (!Summ) {
Jordy Rose35e71c72012-03-17 21:13:07 +00001539 Summ = getStandardMethodSummary(MD, S, RetTy);
Mike Stump11289f42009-09-09 15:08:12 +00001540
Ted Kremenek8be51382009-07-21 23:27:57 +00001541 // Annotations override defaults.
Jordy Rose212e4592011-08-23 04:27:15 +00001542 updateSummaryFromAnnotations(Summ, MD);
Mike Stump11289f42009-09-09 15:08:12 +00001543
Ted Kremenek8be51382009-07-21 23:27:57 +00001544 // Memoize the summary.
Jordan Roseeec15392012-07-02 19:27:43 +00001545 CachedSummaries[ObjCSummaryKey(ID, S)] = Summ;
Ted Kremenek8be51382009-07-21 23:27:57 +00001546 }
Mike Stump11289f42009-09-09 15:08:12 +00001547
Ted Kremenekf27110f2009-04-23 19:11:35 +00001548 return Summ;
Ted Kremenek767d0742008-05-06 21:26:51 +00001549}
1550
Mike Stump11289f42009-09-09 15:08:12 +00001551void RetainSummaryManager::InitializeClassMethodSummaries() {
Ted Kremenek9157fbb2009-05-07 23:40:42 +00001552 assert(ScratchArgs.isEmpty());
Mike Stump11289f42009-09-09 15:08:12 +00001553 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek55adb822009-10-15 22:25:12 +00001554 addClassMethSummary("NSAssertionHandler", "currentHandler",
Ted Kremenekaeb115f2009-01-28 05:56:51 +00001555 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Mike Stump11289f42009-09-09 15:08:12 +00001556
Ted Kremenek0747e7e2008-10-21 15:53:15 +00001557 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremenekb3b56c62010-11-24 00:54:37 +00001558 ScratchArgs = AF.add(ScratchArgs, 0, Autorelease);
Ted Kremenek55adb822009-10-15 22:25:12 +00001559 addClassMethSummary("NSAutoreleasePool", "addObject",
1560 getPersistentSummary(RetEffect::MakeNoRet(),
1561 DoNothing, Autorelease));
Ted Kremenek0806f912008-05-06 00:30:21 +00001562}
1563
Ted Kremenekea736c52008-06-23 22:21:20 +00001564void RetainSummaryManager::InitializeMethodSummaries() {
Mike Stump11289f42009-09-09 15:08:12 +00001565
1566 assert (ScratchArgs.isEmpty());
1567
Ted Kremenek767d0742008-05-06 21:26:51 +00001568 // Create the "init" selector. It just acts as a pass-through for the
1569 // receiver.
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001570 const RetainSummary *InitSumm = getPersistentSummary(ObjCInitRetE, DecRefMsg);
Ted Kremenek815fbb62009-08-20 05:13:36 +00001571 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
1572
1573 // awakeAfterUsingCoder: behaves basically like an 'init' method. It
1574 // claims the receiver and returns a retained object.
1575 addNSObjectMethSummary(GetUnarySelector("awakeAfterUsingCoder", Ctx),
1576 InitSumm);
Mike Stump11289f42009-09-09 15:08:12 +00001577
Ted Kremenek767d0742008-05-06 21:26:51 +00001578 // The next methods are allocators.
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001579 const RetainSummary *AllocSumm = getPersistentSummary(ObjCAllocRetE);
1580 const RetainSummary *CFAllocSumm =
Ted Kremenek52ac2b52009-08-28 19:52:12 +00001581 getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Mike Stump11289f42009-09-09 15:08:12 +00001582
Ted Kremenekb0862dc2008-05-06 02:26:56 +00001583 // Create the "retain" selector.
Jordy Rose3f7f75682011-08-21 19:41:36 +00001584 RetEffect NoRet = RetEffect::MakeNoRet();
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001585 const RetainSummary *Summ = getPersistentSummary(NoRet, IncRefMsg);
Ted Kremenek3185c9c2008-06-25 21:21:56 +00001586 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Mike Stump11289f42009-09-09 15:08:12 +00001587
Ted Kremenekb0862dc2008-05-06 02:26:56 +00001588 // Create the "release" selector.
Jordy Rose3f7f75682011-08-21 19:41:36 +00001589 Summ = getPersistentSummary(NoRet, DecRefMsg);
Ted Kremenek3185c9c2008-06-25 21:21:56 +00001590 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Mike Stump11289f42009-09-09 15:08:12 +00001591
Ted Kremenekea072e32009-03-17 19:42:23 +00001592 // Create the -dealloc summary.
Jordy Rose3f7f75682011-08-21 19:41:36 +00001593 Summ = getPersistentSummary(NoRet, Dealloc);
Ted Kremenekea072e32009-03-17 19:42:23 +00001594 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
Ted Kremenekb0862dc2008-05-06 02:26:56 +00001595
1596 // Create the "autorelease" selector.
Jordy Rose3f7f75682011-08-21 19:41:36 +00001597 Summ = getPersistentSummary(NoRet, Autorelease);
Ted Kremenek3185c9c2008-06-25 21:21:56 +00001598 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Mike Stump11289f42009-09-09 15:08:12 +00001599
Mike Stump11289f42009-09-09 15:08:12 +00001600 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremeneke73f2822009-02-23 02:51:29 +00001601 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1602 // self-own themselves. However, they only do this once they are displayed.
1603 // Thus, we need to track an NSWindow's display status.
1604 // This is tracked in <rdar://problem/6062711>.
Ted Kremenek00dfe302009-03-04 23:30:42 +00001605 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001606 const RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenek1272f702009-05-12 20:06:54 +00001607 StopTracking,
1608 StopTracking);
Mike Stump11289f42009-09-09 15:08:12 +00001609
Ted Kremenek751e7e32009-04-03 19:02:51 +00001610 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1611
Ted Kremenek3f13f592008-08-12 18:48:50 +00001612 // For NSPanel (which subclasses NSWindow), allocated objects are not
1613 // self-owned.
Ted Kremenek751e7e32009-04-03 19:02:51 +00001614 // FIXME: For now we don't track NSPanels. object for the same reason
1615 // as for NSWindow objects.
1616 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
Mike Stump11289f42009-09-09 15:08:12 +00001617
Ted Kremenek9b12e722014-01-03 01:19:28 +00001618 // For NSNull, objects returned by +null are singletons that ignore
1619 // retain/release semantics. Just don't track them.
1620 // <rdar://problem/12858915>
1621 addClassMethSummary("NSNull", "null", NoTrackYet);
1622
Jordan Rose95bf3b02013-01-31 22:06:02 +00001623 // Don't track allocated autorelease pools, as it is okay to prematurely
Ted Kremenek501ba032009-05-18 23:14:34 +00001624 // exit a method.
1625 addClassMethSummary("NSAutoreleasePool", "alloc", NoTrackYet);
Ted Kremeneke8a5ba82012-02-18 21:37:48 +00001626 addClassMethSummary("NSAutoreleasePool", "allocWithZone", NoTrackYet, false);
Jordan Rose95bf3b02013-01-31 22:06:02 +00001627 addClassMethSummary("NSAutoreleasePool", "new", NoTrackYet);
Ted Kremenek3185c9c2008-06-25 21:21:56 +00001628
Ted Kremenek10369122009-05-20 22:39:57 +00001629 // Create summaries QCRenderer/QCView -createSnapShotImageOfType:
1630 addInstMethSummary("QCRenderer", AllocSumm,
Reid Kleckneree7cf842014-12-01 22:02:27 +00001631 "createSnapshotImageOfType", nullptr);
Ted Kremenek10369122009-05-20 22:39:57 +00001632 addInstMethSummary("QCView", AllocSumm,
Reid Kleckneree7cf842014-12-01 22:02:27 +00001633 "createSnapshotImageOfType", nullptr);
Ted Kremenek10369122009-05-20 22:39:57 +00001634
Ted Kremenek96aa1462009-06-15 20:58:58 +00001635 // Create summaries for CIContext, 'createCGImage' and
Ted Kremenek52ac2b52009-08-28 19:52:12 +00001636 // 'createCGLayerWithSize'. These objects are CF objects, and are not
1637 // automatically garbage collected.
1638 addInstMethSummary("CIContext", CFAllocSumm,
Reid Kleckneree7cf842014-12-01 22:02:27 +00001639 "createCGImage", "fromRect", nullptr);
1640 addInstMethSummary("CIContext", CFAllocSumm, "createCGImage", "fromRect",
1641 "format", "colorSpace", nullptr);
1642 addInstMethSummary("CIContext", CFAllocSumm, "createCGLayerWithSize", "info",
1643 nullptr);
Ted Kremenekbe7c56e2008-05-06 00:38:54 +00001644}
1645
Ted Kremenek00daccd2008-05-05 22:11:16 +00001646//===----------------------------------------------------------------------===//
Ted Kremenek6bd78702009-04-29 18:50:19 +00001647// Error reporting.
1648//===----------------------------------------------------------------------===//
Ted Kremenek6bd78702009-04-29 18:50:19 +00001649namespace {
Jordy Rose20d4e682011-08-23 20:55:48 +00001650 typedef llvm::DenseMap<const ExplodedNode *, const RetainSummary *>
1651 SummaryLogTy;
1652
Ted Kremenek6bd78702009-04-29 18:50:19 +00001653 //===-------------===//
1654 // Bug Descriptions. //
Mike Stump11289f42009-09-09 15:08:12 +00001655 //===-------------===//
1656
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00001657 class CFRefBug : public BugType {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001658 protected:
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001659 CFRefBug(const CheckerBase *checker, StringRef name)
1660 : BugType(checker, name, categories::MemoryCoreFoundationObjectiveC) {}
1661
Ted Kremenek6bd78702009-04-29 18:50:19 +00001662 public:
Mike Stump11289f42009-09-09 15:08:12 +00001663
Ted Kremenek6bd78702009-04-29 18:50:19 +00001664 // FIXME: Eventually remove.
Jordy Rose7a534982011-08-24 05:47:39 +00001665 virtual const char *getDescription() const = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001666
Ted Kremenek6bd78702009-04-29 18:50:19 +00001667 virtual bool isLeak() const { return false; }
1668 };
Mike Stump11289f42009-09-09 15:08:12 +00001669
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00001670 class UseAfterRelease : public CFRefBug {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001671 public:
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001672 UseAfterRelease(const CheckerBase *checker)
1673 : CFRefBug(checker, "Use-after-release") {}
Mike Stump11289f42009-09-09 15:08:12 +00001674
Craig Topperfb6b25b2014-03-15 04:29:04 +00001675 const char *getDescription() const override {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001676 return "Reference-counted object is used after it is released";
Mike Stump11289f42009-09-09 15:08:12 +00001677 }
Ted Kremenek6bd78702009-04-29 18:50:19 +00001678 };
Mike Stump11289f42009-09-09 15:08:12 +00001679
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00001680 class BadRelease : public CFRefBug {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001681 public:
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001682 BadRelease(const CheckerBase *checker) : CFRefBug(checker, "Bad release") {}
Mike Stump11289f42009-09-09 15:08:12 +00001683
Craig Topperfb6b25b2014-03-15 04:29:04 +00001684 const char *getDescription() const override {
Ted Kremenek5c22e112009-10-01 17:31:50 +00001685 return "Incorrect decrement of the reference count of an object that is "
1686 "not owned at this point by the caller";
Ted Kremenek6bd78702009-04-29 18:50:19 +00001687 }
1688 };
Mike Stump11289f42009-09-09 15:08:12 +00001689
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00001690 class DeallocGC : public CFRefBug {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001691 public:
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001692 DeallocGC(const CheckerBase *checker)
1693 : CFRefBug(checker, "-dealloc called while using garbage collection") {}
Mike Stump11289f42009-09-09 15:08:12 +00001694
Craig Topperfb6b25b2014-03-15 04:29:04 +00001695 const char *getDescription() const override {
Ted Kremenekd35272f2009-05-09 00:10:05 +00001696 return "-dealloc called while using garbage collection";
Ted Kremenek6bd78702009-04-29 18:50:19 +00001697 }
1698 };
Mike Stump11289f42009-09-09 15:08:12 +00001699
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00001700 class DeallocNotOwned : public CFRefBug {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001701 public:
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001702 DeallocNotOwned(const CheckerBase *checker)
1703 : CFRefBug(checker, "-dealloc sent to non-exclusively owned object") {}
Mike Stump11289f42009-09-09 15:08:12 +00001704
Craig Topperfb6b25b2014-03-15 04:29:04 +00001705 const char *getDescription() const override {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001706 return "-dealloc sent to object that may be referenced elsewhere";
1707 }
Mike Stump11289f42009-09-09 15:08:12 +00001708 };
1709
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00001710 class OverAutorelease : public CFRefBug {
Ted Kremenekd35272f2009-05-09 00:10:05 +00001711 public:
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001712 OverAutorelease(const CheckerBase *checker)
1713 : CFRefBug(checker, "Object autoreleased too many times") {}
Mike Stump11289f42009-09-09 15:08:12 +00001714
Craig Topperfb6b25b2014-03-15 04:29:04 +00001715 const char *getDescription() const override {
Jordan Rose7467f062013-04-23 01:42:25 +00001716 return "Object autoreleased too many times";
Ted Kremenekd35272f2009-05-09 00:10:05 +00001717 }
1718 };
Mike Stump11289f42009-09-09 15:08:12 +00001719
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00001720 class ReturnedNotOwnedForOwned : public CFRefBug {
Ted Kremenekdee56e32009-05-10 06:25:57 +00001721 public:
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001722 ReturnedNotOwnedForOwned(const CheckerBase *checker)
1723 : CFRefBug(checker, "Method should return an owned object") {}
Mike Stump11289f42009-09-09 15:08:12 +00001724
Craig Topperfb6b25b2014-03-15 04:29:04 +00001725 const char *getDescription() const override {
Jordy Rose43426f82011-07-15 22:17:54 +00001726 return "Object with a +0 retain count returned to caller where a +1 "
Ted Kremenekdee56e32009-05-10 06:25:57 +00001727 "(owning) retain count is expected";
1728 }
1729 };
Mike Stump11289f42009-09-09 15:08:12 +00001730
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00001731 class Leak : public CFRefBug {
Benjamin Kramerd1d76b22012-06-06 17:32:50 +00001732 public:
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001733 Leak(const CheckerBase *checker, StringRef name) : CFRefBug(checker, name) {
Jordy Rose15484da2011-08-25 01:14:38 +00001734 // Leaks should not be reported if they are post-dominated by a sink.
1735 setSuppressOnSink(true);
1736 }
Mike Stump11289f42009-09-09 15:08:12 +00001737
Craig Topperfb6b25b2014-03-15 04:29:04 +00001738 const char *getDescription() const override { return ""; }
Mike Stump11289f42009-09-09 15:08:12 +00001739
Craig Topperfb6b25b2014-03-15 04:29:04 +00001740 bool isLeak() const override { return true; }
Ted Kremenek6bd78702009-04-29 18:50:19 +00001741 };
Mike Stump11289f42009-09-09 15:08:12 +00001742
Ted Kremenek6bd78702009-04-29 18:50:19 +00001743 //===---------===//
1744 // Bug Reports. //
1745 //===---------===//
Mike Stump11289f42009-09-09 15:08:12 +00001746
Jordy Rosef78877e2012-03-24 02:45:35 +00001747 class CFRefReportVisitor : public BugReporterVisitorImpl<CFRefReportVisitor> {
Anna Zaks88255cc2011-08-20 01:27:22 +00001748 protected:
Anna Zaks071a89c2011-08-19 23:21:56 +00001749 SymbolRef Sym;
Jordy Rose20d4e682011-08-23 20:55:48 +00001750 const SummaryLogTy &SummaryLog;
Jordy Rose7a534982011-08-24 05:47:39 +00001751 bool GCEnabled;
Anna Zaks88255cc2011-08-20 01:27:22 +00001752
Anna Zaks071a89c2011-08-19 23:21:56 +00001753 public:
Jordy Rose7a534982011-08-24 05:47:39 +00001754 CFRefReportVisitor(SymbolRef sym, bool gcEnabled, const SummaryLogTy &log)
1755 : Sym(sym), SummaryLog(log), GCEnabled(gcEnabled) {}
Anna Zaks071a89c2011-08-19 23:21:56 +00001756
Craig Topperfb6b25b2014-03-15 04:29:04 +00001757 void Profile(llvm::FoldingSetNodeID &ID) const override {
Anna Zaks071a89c2011-08-19 23:21:56 +00001758 static int x = 0;
1759 ID.AddPointer(&x);
1760 ID.AddPointer(Sym);
1761 }
1762
Craig Topperfb6b25b2014-03-15 04:29:04 +00001763 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
1764 const ExplodedNode *PrevN,
1765 BugReporterContext &BRC,
1766 BugReport &BR) override;
Anna Zaks88255cc2011-08-20 01:27:22 +00001767
David Blaikied15481c2014-08-29 18:18:43 +00001768 std::unique_ptr<PathDiagnosticPiece> getEndPath(BugReporterContext &BRC,
1769 const ExplodedNode *N,
1770 BugReport &BR) override;
Anna Zaks88255cc2011-08-20 01:27:22 +00001771 };
1772
1773 class CFRefLeakReportVisitor : public CFRefReportVisitor {
1774 public:
Jordy Rose7a534982011-08-24 05:47:39 +00001775 CFRefLeakReportVisitor(SymbolRef sym, bool GCEnabled,
Jordy Rose20d4e682011-08-23 20:55:48 +00001776 const SummaryLogTy &log)
Jordy Rose7a534982011-08-24 05:47:39 +00001777 : CFRefReportVisitor(sym, GCEnabled, log) {}
Anna Zaks88255cc2011-08-20 01:27:22 +00001778
David Blaikied15481c2014-08-29 18:18:43 +00001779 std::unique_ptr<PathDiagnosticPiece> getEndPath(BugReporterContext &BRC,
1780 const ExplodedNode *N,
1781 BugReport &BR) override;
Jordy Rosef78877e2012-03-24 02:45:35 +00001782
David Blaikie91e79022014-09-04 23:54:33 +00001783 std::unique_ptr<BugReporterVisitor> clone() const override {
Jordy Rosef78877e2012-03-24 02:45:35 +00001784 // The curiously-recurring template pattern only works for one level of
1785 // subclassing. Rather than make a new template base for
1786 // CFRefReportVisitor, we simply override clone() to do the right thing.
1787 // This could be trouble someday if BugReporterVisitorImpl is ever
1788 // used for something else besides a convenient implementation of clone().
David Blaikie91e79022014-09-04 23:54:33 +00001789 return llvm::make_unique<CFRefLeakReportVisitor>(*this);
Jordy Rosef78877e2012-03-24 02:45:35 +00001790 }
Anna Zaks071a89c2011-08-19 23:21:56 +00001791 };
1792
Anna Zaks3a6bdf82011-08-17 23:00:25 +00001793 class CFRefReport : public BugReport {
Jordy Rose184bd142011-08-24 22:39:09 +00001794 void addGCModeDescription(const LangOptions &LOpts, bool GCEnabled);
Jordy Rose7a534982011-08-24 05:47:39 +00001795
Ted Kremenek6bd78702009-04-29 18:50:19 +00001796 public:
Jordy Rose184bd142011-08-24 22:39:09 +00001797 CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1798 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1799 bool registerVisitor = true)
Anna Zaks752de142011-08-22 18:54:07 +00001800 : BugReport(D, D.getDescription(), n) {
Anna Zaks88255cc2011-08-20 01:27:22 +00001801 if (registerVisitor)
David Blaikie91e79022014-09-04 23:54:33 +00001802 addVisitor(llvm::make_unique<CFRefReportVisitor>(sym, GCEnabled, Log));
Jordy Rose184bd142011-08-24 22:39:09 +00001803 addGCModeDescription(LOpts, GCEnabled);
Anna Zaks071a89c2011-08-19 23:21:56 +00001804 }
Ted Kremenek3978f792009-05-10 05:11:21 +00001805
Jordy Rose184bd142011-08-24 22:39:09 +00001806 CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1807 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1808 StringRef endText)
Anna Zaks752de142011-08-22 18:54:07 +00001809 : BugReport(D, D.getDescription(), endText, n) {
David Blaikie91e79022014-09-04 23:54:33 +00001810 addVisitor(llvm::make_unique<CFRefReportVisitor>(sym, GCEnabled, Log));
Jordy Rose184bd142011-08-24 22:39:09 +00001811 addGCModeDescription(LOpts, GCEnabled);
Anna Zaks071a89c2011-08-19 23:21:56 +00001812 }
Mike Stump11289f42009-09-09 15:08:12 +00001813
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00001814 llvm::iterator_range<ranges_iterator> getRanges() override {
Anna Zaks752de142011-08-22 18:54:07 +00001815 const CFRefBug& BugTy = static_cast<CFRefBug&>(getBugType());
1816 if (!BugTy.isLeak())
Anna Zaks3a6bdf82011-08-17 23:00:25 +00001817 return BugReport::getRanges();
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00001818 return llvm::make_range(ranges_iterator(), ranges_iterator());
Ted Kremenek6bd78702009-04-29 18:50:19 +00001819 }
Ted Kremenek6bd78702009-04-29 18:50:19 +00001820 };
Ted Kremenek3978f792009-05-10 05:11:21 +00001821
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00001822 class CFRefLeakReport : public CFRefReport {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001823 const MemRegion* AllocBinding;
1824 public:
Jordy Rose184bd142011-08-24 22:39:09 +00001825 CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1826 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
Ted Kremenek8671acb2013-04-16 21:44:22 +00001827 CheckerContext &Ctx,
1828 bool IncludeAllocationLine);
Mike Stump11289f42009-09-09 15:08:12 +00001829
Craig Topperfb6b25b2014-03-15 04:29:04 +00001830 PathDiagnosticLocation getLocation(const SourceManager &SM) const override {
Anna Zaksc29bed32011-09-20 21:38:35 +00001831 assert(Location.isValid());
1832 return Location;
1833 }
Mike Stump11289f42009-09-09 15:08:12 +00001834 };
Ted Kremenek6bd78702009-04-29 18:50:19 +00001835} // end anonymous namespace
1836
Jordy Rose184bd142011-08-24 22:39:09 +00001837void CFRefReport::addGCModeDescription(const LangOptions &LOpts,
1838 bool GCEnabled) {
Craig Topper0dbb7832014-05-27 02:45:47 +00001839 const char *GCModeDescription = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001840
Douglas Gregor79a91412011-09-13 17:21:33 +00001841 switch (LOpts.getGC()) {
Anna Zaks76c3fb62011-08-22 20:31:28 +00001842 case LangOptions::GCOnly:
Jordy Rose184bd142011-08-24 22:39:09 +00001843 assert(GCEnabled);
Jordy Rose7a534982011-08-24 05:47:39 +00001844 GCModeDescription = "Code is compiled to only use garbage collection";
1845 break;
Mike Stump11289f42009-09-09 15:08:12 +00001846
Anna Zaks76c3fb62011-08-22 20:31:28 +00001847 case LangOptions::NonGC:
Jordy Rose184bd142011-08-24 22:39:09 +00001848 assert(!GCEnabled);
Jordy Rose7a534982011-08-24 05:47:39 +00001849 GCModeDescription = "Code is compiled to use reference counts";
1850 break;
Mike Stump11289f42009-09-09 15:08:12 +00001851
Anna Zaks76c3fb62011-08-22 20:31:28 +00001852 case LangOptions::HybridGC:
Jordy Rose184bd142011-08-24 22:39:09 +00001853 if (GCEnabled) {
Jordy Rose7a534982011-08-24 05:47:39 +00001854 GCModeDescription = "Code is compiled to use either garbage collection "
1855 "(GC) or reference counts (non-GC). The bug occurs "
1856 "with GC enabled";
1857 break;
1858 } else {
1859 GCModeDescription = "Code is compiled to use either garbage collection "
1860 "(GC) or reference counts (non-GC). The bug occurs "
1861 "in non-GC mode";
1862 break;
Anna Zaks76c3fb62011-08-22 20:31:28 +00001863 }
Ted Kremenek6bd78702009-04-29 18:50:19 +00001864 }
Jordy Rose7a534982011-08-24 05:47:39 +00001865
Jordy Rose9ff02992011-08-24 20:38:42 +00001866 assert(GCModeDescription && "invalid/unknown GC mode");
Jordy Rose7a534982011-08-24 05:47:39 +00001867 addExtraText(GCModeDescription);
Ted Kremenek6bd78702009-04-29 18:50:19 +00001868}
1869
Jordy Rose6393f822012-05-12 05:10:43 +00001870static bool isNumericLiteralExpression(const Expr *E) {
1871 // FIXME: This set of cases was copied from SemaExprObjC.
1872 return isa<IntegerLiteral>(E) ||
1873 isa<CharacterLiteral>(E) ||
1874 isa<FloatingLiteral>(E) ||
1875 isa<ObjCBoolLiteralExpr>(E) ||
1876 isa<CXXBoolLiteralExpr>(E);
1877}
1878
Jordan Rosecb5386c2015-02-04 19:24:52 +00001879/// Returns true if this stack frame is for an Objective-C method that is a
1880/// property getter or setter whose body has been synthesized by the analyzer.
1881static bool isSynthesizedAccessor(const StackFrameContext *SFC) {
1882 auto Method = dyn_cast_or_null<ObjCMethodDecl>(SFC->getDecl());
1883 if (!Method || !Method->isPropertyAccessor())
1884 return false;
1885
1886 return SFC->getAnalysisDeclContext()->isBodyAutosynthesized();
1887}
1888
Anna Zaks071a89c2011-08-19 23:21:56 +00001889PathDiagnosticPiece *CFRefReportVisitor::VisitNode(const ExplodedNode *N,
1890 const ExplodedNode *PrevN,
1891 BugReporterContext &BRC,
1892 BugReport &BR) {
Jordan Rose681cce92012-07-10 22:07:42 +00001893 // FIXME: We will eventually need to handle non-statement-based events
1894 // (__attribute__((cleanup))).
David Blaikie87396b92013-02-21 22:23:56 +00001895 if (!N->getLocation().getAs<StmtPoint>())
Craig Topper0dbb7832014-05-27 02:45:47 +00001896 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001897
Ted Kremenekbb8d5462009-05-06 21:39:49 +00001898 // Check if the type state has changed.
Ted Kremenek49b1e382012-01-26 21:29:00 +00001899 ProgramStateRef PrevSt = PrevN->getState();
1900 ProgramStateRef CurrSt = N->getState();
Ted Kremenek632e3b72012-01-06 22:09:28 +00001901 const LocationContext *LCtx = N->getLocationContext();
Mike Stump11289f42009-09-09 15:08:12 +00001902
Anna Zaksf5788c72012-08-14 00:36:15 +00001903 const RefVal* CurrT = getRefBinding(CurrSt, Sym);
Craig Topper0dbb7832014-05-27 02:45:47 +00001904 if (!CurrT) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001905
Ted Kremenekd93c6e32009-06-18 01:23:53 +00001906 const RefVal &CurrV = *CurrT;
Anna Zaksf5788c72012-08-14 00:36:15 +00001907 const RefVal *PrevT = getRefBinding(PrevSt, Sym);
Mike Stump11289f42009-09-09 15:08:12 +00001908
Ted Kremenek6bd78702009-04-29 18:50:19 +00001909 // Create a string buffer to constain all the useful things we want
1910 // to tell the user.
1911 std::string sbuf;
1912 llvm::raw_string_ostream os(sbuf);
Mike Stump11289f42009-09-09 15:08:12 +00001913
Ted Kremenek6bd78702009-04-29 18:50:19 +00001914 // This is the allocation site since the previous node had no bindings
1915 // for this symbol.
1916 if (!PrevT) {
David Blaikie87396b92013-02-21 22:23:56 +00001917 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
Mike Stump11289f42009-09-09 15:08:12 +00001918
Jordan Rosecb5386c2015-02-04 19:24:52 +00001919 if (isa<ObjCIvarRefExpr>(S) &&
1920 isSynthesizedAccessor(LCtx->getCurrentStackFrame())) {
1921 S = LCtx->getCurrentStackFrame()->getCallSite();
1922 }
1923
Ted Kremenek415287d2012-03-06 20:06:12 +00001924 if (isa<ObjCArrayLiteral>(S)) {
1925 os << "NSArray literal is an object with a +0 retain count";
Mike Stump11289f42009-09-09 15:08:12 +00001926 }
Ted Kremenek415287d2012-03-06 20:06:12 +00001927 else if (isa<ObjCDictionaryLiteral>(S)) {
1928 os << "NSDictionary literal is an object with a +0 retain count";
Ted Kremenek6bd78702009-04-29 18:50:19 +00001929 }
Jordy Rose6393f822012-05-12 05:10:43 +00001930 else if (const ObjCBoxedExpr *BL = dyn_cast<ObjCBoxedExpr>(S)) {
1931 if (isNumericLiteralExpression(BL->getSubExpr()))
1932 os << "NSNumber literal is an object with a +0 retain count";
1933 else {
Craig Topper0dbb7832014-05-27 02:45:47 +00001934 const ObjCInterfaceDecl *BoxClass = nullptr;
Jordy Rose6393f822012-05-12 05:10:43 +00001935 if (const ObjCMethodDecl *Method = BL->getBoxingMethod())
1936 BoxClass = Method->getClassInterface();
1937
1938 // We should always be able to find the boxing class interface,
1939 // but consider this future-proofing.
1940 if (BoxClass)
1941 os << *BoxClass << " b";
1942 else
1943 os << "B";
1944
1945 os << "oxed expression produces an object with a +0 retain count";
1946 }
1947 }
Jordan Rosecb5386c2015-02-04 19:24:52 +00001948 else if (isa<ObjCIvarRefExpr>(S)) {
1949 os << "Object loaded from instance variable";
1950 }
Ted Kremenek415287d2012-03-06 20:06:12 +00001951 else {
1952 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
1953 // Get the name of the callee (if it is available).
1954 SVal X = CurrSt->getSValAsScalarOrLoc(CE->getCallee(), LCtx);
1955 if (const FunctionDecl *FD = X.getAsFunctionDecl())
1956 os << "Call to function '" << *FD << '\'';
1957 else
1958 os << "function call";
Ted Kremenek6bd78702009-04-29 18:50:19 +00001959 }
Ted Kremenek415287d2012-03-06 20:06:12 +00001960 else {
Jordan Rose627b0462012-07-18 21:59:51 +00001961 assert(isa<ObjCMessageExpr>(S));
Jordan Rosefcd016e2012-07-30 20:22:09 +00001962 CallEventManager &Mgr = CurrSt->getStateManager().getCallEventManager();
1963 CallEventRef<ObjCMethodCall> Call
1964 = Mgr.getObjCMethodCall(cast<ObjCMessageExpr>(S), CurrSt, LCtx);
1965
1966 switch (Call->getMessageKind()) {
Jordan Rose627b0462012-07-18 21:59:51 +00001967 case OCM_Message:
1968 os << "Method";
1969 break;
1970 case OCM_PropertyAccess:
1971 os << "Property";
1972 break;
1973 case OCM_Subscript:
1974 os << "Subscript";
1975 break;
1976 }
Ted Kremenek415287d2012-03-06 20:06:12 +00001977 }
1978
1979 if (CurrV.getObjKind() == RetEffect::CF) {
1980 os << " returns a Core Foundation object with a ";
1981 }
1982 else {
1983 assert (CurrV.getObjKind() == RetEffect::ObjC);
1984 os << " returns an Objective-C object with a ";
1985 }
1986
1987 if (CurrV.isOwned()) {
1988 os << "+1 retain count";
1989
1990 if (GCEnabled) {
1991 assert(CurrV.getObjKind() == RetEffect::CF);
1992 os << ". "
1993 "Core Foundation objects are not automatically garbage collected.";
1994 }
1995 }
1996 else {
1997 assert (CurrV.isNotOwned());
1998 os << "+0 retain count";
1999 }
Ted Kremenek6bd78702009-04-29 18:50:19 +00002000 }
Mike Stump11289f42009-09-09 15:08:12 +00002001
Anna Zaks3a769bd2011-09-15 01:08:34 +00002002 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
2003 N->getLocationContext());
Ted Kremenek6bd78702009-04-29 18:50:19 +00002004 return new PathDiagnosticEventPiece(Pos, os.str());
2005 }
Mike Stump11289f42009-09-09 15:08:12 +00002006
Ted Kremenek6bd78702009-04-29 18:50:19 +00002007 // Gather up the effects that were performed on the object at this
2008 // program point
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002009 SmallVector<ArgEffect, 2> AEffects;
Mike Stump11289f42009-09-09 15:08:12 +00002010
Jordy Rose20d4e682011-08-23 20:55:48 +00002011 const ExplodedNode *OrigNode = BRC.getNodeResolver().getOriginalNode(N);
2012 if (const RetainSummary *Summ = SummaryLog.lookup(OrigNode)) {
Ted Kremenek6bd78702009-04-29 18:50:19 +00002013 // We only have summaries attached to nodes after evaluating CallExpr and
2014 // ObjCMessageExprs.
David Blaikie87396b92013-02-21 22:23:56 +00002015 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
Mike Stump11289f42009-09-09 15:08:12 +00002016
Ted Kremenekbfd28fd2009-07-22 22:35:28 +00002017 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
Ted Kremenek6bd78702009-04-29 18:50:19 +00002018 // Iterate through the parameter expressions and see if the symbol
2019 // was ever passed as an argument.
2020 unsigned i = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002021
Ted Kremenekbfd28fd2009-07-22 22:35:28 +00002022 for (CallExpr::const_arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
Ted Kremenek6bd78702009-04-29 18:50:19 +00002023 AI!=AE; ++AI, ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002024
Ted Kremenek6bd78702009-04-29 18:50:19 +00002025 // Retrieve the value of the argument. Is it the symbol
2026 // we are interested in?
Ted Kremenek632e3b72012-01-06 22:09:28 +00002027 if (CurrSt->getSValAsScalarOrLoc(*AI, LCtx).getAsLocSymbol() != Sym)
Ted Kremenek6bd78702009-04-29 18:50:19 +00002028 continue;
Mike Stump11289f42009-09-09 15:08:12 +00002029
Ted Kremenek6bd78702009-04-29 18:50:19 +00002030 // We have an argument. Get the effect!
2031 AEffects.push_back(Summ->getArg(i));
2032 }
2033 }
Mike Stump11289f42009-09-09 15:08:12 +00002034 else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
Douglas Gregor9a129192010-04-21 00:45:42 +00002035 if (const Expr *receiver = ME->getInstanceReceiver())
Ted Kremenek632e3b72012-01-06 22:09:28 +00002036 if (CurrSt->getSValAsScalarOrLoc(receiver, LCtx)
2037 .getAsLocSymbol() == Sym) {
Ted Kremenek6bd78702009-04-29 18:50:19 +00002038 // The symbol we are tracking is the receiver.
2039 AEffects.push_back(Summ->getReceiverEffect());
2040 }
2041 }
2042 }
Mike Stump11289f42009-09-09 15:08:12 +00002043
Ted Kremenek6bd78702009-04-29 18:50:19 +00002044 do {
2045 // Get the previous type state.
2046 RefVal PrevV = *PrevT;
Mike Stump11289f42009-09-09 15:08:12 +00002047
Ted Kremenek6bd78702009-04-29 18:50:19 +00002048 // Specially handle -dealloc.
Benjamin Kramerab3838a2013-08-16 21:57:14 +00002049 if (!GCEnabled && std::find(AEffects.begin(), AEffects.end(), Dealloc) !=
2050 AEffects.end()) {
Ted Kremenek6bd78702009-04-29 18:50:19 +00002051 // Determine if the object's reference count was pushed to zero.
Jordan Roseb3ad07e2014-03-25 17:10:58 +00002052 assert(!PrevV.hasSameState(CurrV) && "The state should have changed.");
Ted Kremenek6bd78702009-04-29 18:50:19 +00002053 // We may not have transitioned to 'release' if we hit an error.
2054 // This case is handled elsewhere.
2055 if (CurrV.getKind() == RefVal::Released) {
Ted Kremenek3a0516b2009-05-08 20:01:42 +00002056 assert(CurrV.getCombinedCounts() == 0);
Ted Kremenek6bd78702009-04-29 18:50:19 +00002057 os << "Object released by directly sending the '-dealloc' message";
2058 break;
2059 }
2060 }
Mike Stump11289f42009-09-09 15:08:12 +00002061
Ted Kremenek6bd78702009-04-29 18:50:19 +00002062 // Specially handle CFMakeCollectable and friends.
Benjamin Kramerab3838a2013-08-16 21:57:14 +00002063 if (std::find(AEffects.begin(), AEffects.end(), MakeCollectable) !=
2064 AEffects.end()) {
Ted Kremenek6bd78702009-04-29 18:50:19 +00002065 // Get the name of the function.
David Blaikie87396b92013-02-21 22:23:56 +00002066 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
Ted Kremenek632e3b72012-01-06 22:09:28 +00002067 SVal X =
2068 CurrSt->getSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee(), LCtx);
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002069 const FunctionDecl *FD = X.getAsFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00002070
Jordy Rose7a534982011-08-24 05:47:39 +00002071 if (GCEnabled) {
Ted Kremenek6bd78702009-04-29 18:50:19 +00002072 // Determine if the object's reference count was pushed to zero.
Jordan Roseb3ad07e2014-03-25 17:10:58 +00002073 assert(!PrevV.hasSameState(CurrV) && "The state should have changed.");
Mike Stump11289f42009-09-09 15:08:12 +00002074
Benjamin Kramerb89514a2011-10-14 18:45:37 +00002075 os << "In GC mode a call to '" << *FD
Ted Kremenek6bd78702009-04-29 18:50:19 +00002076 << "' decrements an object's retain count and registers the "
2077 "object with the garbage collector. ";
Mike Stump11289f42009-09-09 15:08:12 +00002078
Ted Kremenek6bd78702009-04-29 18:50:19 +00002079 if (CurrV.getKind() == RefVal::Released) {
2080 assert(CurrV.getCount() == 0);
2081 os << "Since it now has a 0 retain count the object can be "
2082 "automatically collected by the garbage collector.";
2083 }
2084 else
2085 os << "An object must have a 0 retain count to be garbage collected. "
2086 "After this call its retain count is +" << CurrV.getCount()
2087 << '.';
2088 }
Mike Stump11289f42009-09-09 15:08:12 +00002089 else
Benjamin Kramerb89514a2011-10-14 18:45:37 +00002090 os << "When GC is not enabled a call to '" << *FD
Ted Kremenek6bd78702009-04-29 18:50:19 +00002091 << "' has no effect on its argument.";
Mike Stump11289f42009-09-09 15:08:12 +00002092
Ted Kremenek6bd78702009-04-29 18:50:19 +00002093 // Nothing more to say.
2094 break;
2095 }
Mike Stump11289f42009-09-09 15:08:12 +00002096
2097 // Determine if the typestate has changed.
Jordan Roseb3ad07e2014-03-25 17:10:58 +00002098 if (!PrevV.hasSameState(CurrV))
Ted Kremenek6bd78702009-04-29 18:50:19 +00002099 switch (CurrV.getKind()) {
2100 case RefVal::Owned:
2101 case RefVal::NotOwned:
Ted Kremenek3a0516b2009-05-08 20:01:42 +00002102 if (PrevV.getCount() == CurrV.getCount()) {
2103 // Did an autorelease message get sent?
2104 if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
Craig Topper0dbb7832014-05-27 02:45:47 +00002105 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002106
Zhongxing Xu08a2ede2009-05-12 10:10:00 +00002107 assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount());
Jordan Rose7467f062013-04-23 01:42:25 +00002108 os << "Object autoreleased";
Ted Kremenek3a0516b2009-05-08 20:01:42 +00002109 break;
2110 }
Mike Stump11289f42009-09-09 15:08:12 +00002111
Ted Kremenek6bd78702009-04-29 18:50:19 +00002112 if (PrevV.getCount() > CurrV.getCount())
2113 os << "Reference count decremented.";
2114 else
2115 os << "Reference count incremented.";
Mike Stump11289f42009-09-09 15:08:12 +00002116
Ted Kremenek6bd78702009-04-29 18:50:19 +00002117 if (unsigned Count = CurrV.getCount())
2118 os << " The object now has a +" << Count << " retain count.";
Mike Stump11289f42009-09-09 15:08:12 +00002119
Ted Kremenek6bd78702009-04-29 18:50:19 +00002120 if (PrevV.getKind() == RefVal::Released) {
Jordy Rose7a534982011-08-24 05:47:39 +00002121 assert(GCEnabled && CurrV.getCount() > 0);
Jordy Rose78373e52012-03-17 05:49:15 +00002122 os << " The object is not eligible for garbage collection until "
2123 "the retain count reaches 0 again.";
Ted Kremenek6bd78702009-04-29 18:50:19 +00002124 }
Mike Stump11289f42009-09-09 15:08:12 +00002125
Ted Kremenek6bd78702009-04-29 18:50:19 +00002126 break;
Mike Stump11289f42009-09-09 15:08:12 +00002127
Ted Kremenek6bd78702009-04-29 18:50:19 +00002128 case RefVal::Released:
Jordan Rosecb5386c2015-02-04 19:24:52 +00002129 if (CurrV.getIvarAccessHistory() ==
2130 RefVal::IvarAccessHistory::ReleasedAfterDirectAccess &&
2131 CurrV.getIvarAccessHistory() != PrevV.getIvarAccessHistory()) {
2132 os << "Strong instance variable relinquished. ";
2133 }
Ted Kremenek6bd78702009-04-29 18:50:19 +00002134 os << "Object released.";
2135 break;
Mike Stump11289f42009-09-09 15:08:12 +00002136
Ted Kremenek6bd78702009-04-29 18:50:19 +00002137 case RefVal::ReturnedOwned:
Jordy Rose78373e52012-03-17 05:49:15 +00002138 // Autoreleases can be applied after marking a node ReturnedOwned.
2139 if (CurrV.getAutoreleaseCount())
Craig Topper0dbb7832014-05-27 02:45:47 +00002140 return nullptr;
Jordy Rose78373e52012-03-17 05:49:15 +00002141
2142 os << "Object returned to caller as an owning reference (single "
2143 "retain count transferred to caller)";
Ted Kremenek6bd78702009-04-29 18:50:19 +00002144 break;
Mike Stump11289f42009-09-09 15:08:12 +00002145
Ted Kremenek6bd78702009-04-29 18:50:19 +00002146 case RefVal::ReturnedNotOwned:
Ted Kremenekf2301982011-05-26 18:45:44 +00002147 os << "Object returned to caller with a +0 retain count";
Ted Kremenek6bd78702009-04-29 18:50:19 +00002148 break;
Mike Stump11289f42009-09-09 15:08:12 +00002149
Ted Kremenek6bd78702009-04-29 18:50:19 +00002150 default:
Craig Topper0dbb7832014-05-27 02:45:47 +00002151 return nullptr;
Ted Kremenek6bd78702009-04-29 18:50:19 +00002152 }
Mike Stump11289f42009-09-09 15:08:12 +00002153
Ted Kremenek6bd78702009-04-29 18:50:19 +00002154 // Emit any remaining diagnostics for the argument effects (if any).
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002155 for (SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
Ted Kremenek6bd78702009-04-29 18:50:19 +00002156 E=AEffects.end(); I != E; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +00002157
Ted Kremenek6bd78702009-04-29 18:50:19 +00002158 // A bunch of things have alternate behavior under GC.
Jordy Rose7a534982011-08-24 05:47:39 +00002159 if (GCEnabled)
Ted Kremenek6bd78702009-04-29 18:50:19 +00002160 switch (*I) {
2161 default: break;
2162 case Autorelease:
2163 os << "In GC mode an 'autorelease' has no effect.";
2164 continue;
2165 case IncRefMsg:
2166 os << "In GC mode the 'retain' message has no effect.";
2167 continue;
2168 case DecRefMsg:
2169 os << "In GC mode the 'release' message has no effect.";
2170 continue;
2171 }
2172 }
Mike Stump11289f42009-09-09 15:08:12 +00002173 } while (0);
2174
Ted Kremenek6bd78702009-04-29 18:50:19 +00002175 if (os.str().empty())
Craig Topper0dbb7832014-05-27 02:45:47 +00002176 return nullptr; // We have nothing to say!
Ted Kremenek051a03d2009-05-13 07:12:33 +00002177
David Blaikie87396b92013-02-21 22:23:56 +00002178 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
Anna Zaks3a769bd2011-09-15 01:08:34 +00002179 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
2180 N->getLocationContext());
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002181 PathDiagnosticPiece *P = new PathDiagnosticEventPiece(Pos, os.str());
Mike Stump11289f42009-09-09 15:08:12 +00002182
Ted Kremenek6bd78702009-04-29 18:50:19 +00002183 // Add the range by scanning the children of the statement for any bindings
2184 // to Sym.
Mike Stump11289f42009-09-09 15:08:12 +00002185 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
Ted Kremenekbfd28fd2009-07-22 22:35:28 +00002186 I!=E; ++I)
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002187 if (const Expr *Exp = dyn_cast_or_null<Expr>(*I))
Ted Kremenek632e3b72012-01-06 22:09:28 +00002188 if (CurrSt->getSValAsScalarOrLoc(Exp, LCtx).getAsLocSymbol() == Sym) {
Ted Kremenek6bd78702009-04-29 18:50:19 +00002189 P->addRange(Exp->getSourceRange());
2190 break;
2191 }
Mike Stump11289f42009-09-09 15:08:12 +00002192
Ted Kremenek6bd78702009-04-29 18:50:19 +00002193 return P;
2194}
2195
Anna Zaks75de3232012-02-28 22:39:22 +00002196// Find the first node in the current function context that referred to the
2197// tracked symbol and the memory location that value was stored to. Note, the
2198// value is only reported if the allocation occurred in the same function as
Anna Zakse51362e2013-04-10 21:42:06 +00002199// the leak. The function can also return a location context, which should be
2200// treated as interesting.
2201struct AllocationInfo {
2202 const ExplodedNode* N;
Anna Zaks3f303be2013-04-10 22:56:30 +00002203 const MemRegion *R;
Anna Zakse51362e2013-04-10 21:42:06 +00002204 const LocationContext *InterestingMethodContext;
Anna Zaks3f303be2013-04-10 22:56:30 +00002205 AllocationInfo(const ExplodedNode *InN,
2206 const MemRegion *InR,
Anna Zakse51362e2013-04-10 21:42:06 +00002207 const LocationContext *InInterestingMethodContext) :
2208 N(InN), R(InR), InterestingMethodContext(InInterestingMethodContext) {}
2209};
2210
2211static AllocationInfo
Ted Kremenek001fd5b2011-08-15 22:09:50 +00002212GetAllocationSite(ProgramStateManager& StateMgr, const ExplodedNode *N,
Ted Kremenek6bd78702009-04-29 18:50:19 +00002213 SymbolRef Sym) {
Anna Zakse51362e2013-04-10 21:42:06 +00002214 const ExplodedNode *AllocationNode = N;
Anna Zaks486a0ff2015-02-05 01:02:53 +00002215 const ExplodedNode *AllocationNodeInCurrentOrParentContext = N;
Craig Topper0dbb7832014-05-27 02:45:47 +00002216 const MemRegion *FirstBinding = nullptr;
Anna Zaks75de3232012-02-28 22:39:22 +00002217 const LocationContext *LeakContext = N->getLocationContext();
Mike Stump11289f42009-09-09 15:08:12 +00002218
Anna Zakse51362e2013-04-10 21:42:06 +00002219 // The location context of the init method called on the leaked object, if
2220 // available.
Craig Topper0dbb7832014-05-27 02:45:47 +00002221 const LocationContext *InitMethodContext = nullptr;
Anna Zakse51362e2013-04-10 21:42:06 +00002222
Ted Kremenek6bd78702009-04-29 18:50:19 +00002223 while (N) {
Ted Kremenek49b1e382012-01-26 21:29:00 +00002224 ProgramStateRef St = N->getState();
Anna Zakse51362e2013-04-10 21:42:06 +00002225 const LocationContext *NContext = N->getLocationContext();
Mike Stump11289f42009-09-09 15:08:12 +00002226
Anna Zaksf5788c72012-08-14 00:36:15 +00002227 if (!getRefBinding(St, Sym))
Ted Kremenek6bd78702009-04-29 18:50:19 +00002228 break;
Mike Stump11289f42009-09-09 15:08:12 +00002229
Anna Zaks6797d6e2012-03-21 19:45:01 +00002230 StoreManager::FindUniqueBinding FB(Sym);
Mike Stump11289f42009-09-09 15:08:12 +00002231 StateMgr.iterBindings(St, FB);
Anna Zakse51362e2013-04-10 21:42:06 +00002232
Anna Zaks7c19abe2013-04-10 21:42:02 +00002233 if (FB) {
2234 const MemRegion *R = FB.getRegion();
Anna Zaks07804ef2013-04-10 22:56:33 +00002235 const VarRegion *VR = R->getBaseRegion()->getAs<VarRegion>();
Anna Zaks7c19abe2013-04-10 21:42:02 +00002236 // Do not show local variables belonging to a function other than
2237 // where the error is reported.
2238 if (!VR || VR->getStackFrame() == LeakContext->getCurrentStackFrame())
Anna Zakse51362e2013-04-10 21:42:06 +00002239 FirstBinding = R;
Anna Zaks7c19abe2013-04-10 21:42:02 +00002240 }
Mike Stump11289f42009-09-09 15:08:12 +00002241
Anna Zakse51362e2013-04-10 21:42:06 +00002242 // AllocationNode is the last node in which the symbol was tracked.
2243 AllocationNode = N;
2244
Anna Zaks486a0ff2015-02-05 01:02:53 +00002245 // AllocationNodeInCurrentContext, is the last node in the current or
2246 // parent context in which the symbol was tracked.
2247 //
2248 // Note that the allocation site might be in the parent conext. For example,
2249 // the case where an allocation happens in a block that captures a reference
2250 // to it and that reference is overwritten/dropped by another call to
2251 // the block.
2252 if (NContext == LeakContext || NContext->isParentOf(LeakContext))
2253 AllocationNodeInCurrentOrParentContext = N;
Anna Zakse51362e2013-04-10 21:42:06 +00002254
Anna Zaks3f303be2013-04-10 22:56:30 +00002255 // Find the last init that was called on the given symbol and store the
2256 // init method's location context.
2257 if (!InitMethodContext)
2258 if (Optional<CallEnter> CEP = N->getLocation().getAs<CallEnter>()) {
2259 const Stmt *CE = CEP->getCallExpr();
Anna Zaks99394bb2013-04-25 00:41:32 +00002260 if (const ObjCMessageExpr *ME = dyn_cast_or_null<ObjCMessageExpr>(CE)) {
Anna Zaks3f303be2013-04-10 22:56:30 +00002261 const Stmt *RecExpr = ME->getInstanceReceiver();
2262 if (RecExpr) {
2263 SVal RecV = St->getSVal(RecExpr, NContext);
2264 if (ME->getMethodFamily() == OMF_init && RecV.getAsSymbol() == Sym)
2265 InitMethodContext = CEP->getCalleeContext();
2266 }
2267 }
Anna Zakse51362e2013-04-10 21:42:06 +00002268 }
Anna Zaks75de3232012-02-28 22:39:22 +00002269
Craig Topper0dbb7832014-05-27 02:45:47 +00002270 N = N->pred_empty() ? nullptr : *(N->pred_begin());
Ted Kremenek6bd78702009-04-29 18:50:19 +00002271 }
Mike Stump11289f42009-09-09 15:08:12 +00002272
Anna Zakse51362e2013-04-10 21:42:06 +00002273 // If we are reporting a leak of the object that was allocated with alloc,
Anna Zaks3f303be2013-04-10 22:56:30 +00002274 // mark its init method as interesting.
Craig Topper0dbb7832014-05-27 02:45:47 +00002275 const LocationContext *InterestingMethodContext = nullptr;
Anna Zakse51362e2013-04-10 21:42:06 +00002276 if (InitMethodContext) {
2277 const ProgramPoint AllocPP = AllocationNode->getLocation();
2278 if (Optional<StmtPoint> SP = AllocPP.getAs<StmtPoint>())
2279 if (const ObjCMessageExpr *ME = SP->getStmtAs<ObjCMessageExpr>())
2280 if (ME->getMethodFamily() == OMF_alloc)
2281 InterestingMethodContext = InitMethodContext;
2282 }
2283
Anna Zaks75de3232012-02-28 22:39:22 +00002284 // If allocation happened in a function different from the leak node context,
2285 // do not report the binding.
Ted Kremenekb045b012012-10-12 22:56:40 +00002286 assert(N && "Could not find allocation node");
Anna Zaks75de3232012-02-28 22:39:22 +00002287 if (N->getLocationContext() != LeakContext) {
Craig Topper0dbb7832014-05-27 02:45:47 +00002288 FirstBinding = nullptr;
Anna Zaks75de3232012-02-28 22:39:22 +00002289 }
2290
Anna Zaks486a0ff2015-02-05 01:02:53 +00002291 return AllocationInfo(AllocationNodeInCurrentOrParentContext,
Anna Zakse51362e2013-04-10 21:42:06 +00002292 FirstBinding,
2293 InterestingMethodContext);
Ted Kremenek6bd78702009-04-29 18:50:19 +00002294}
2295
David Blaikied15481c2014-08-29 18:18:43 +00002296std::unique_ptr<PathDiagnosticPiece>
Anna Zaks88255cc2011-08-20 01:27:22 +00002297CFRefReportVisitor::getEndPath(BugReporterContext &BRC,
David Blaikied15481c2014-08-29 18:18:43 +00002298 const ExplodedNode *EndN, BugReport &BR) {
Ted Kremenek1e809b42012-03-09 01:13:14 +00002299 BR.markInteresting(Sym);
Anna Zaks88255cc2011-08-20 01:27:22 +00002300 return BugReporterVisitor::getDefaultEndPath(BRC, EndN, BR);
Ted Kremenek6bd78702009-04-29 18:50:19 +00002301}
2302
David Blaikied15481c2014-08-29 18:18:43 +00002303std::unique_ptr<PathDiagnosticPiece>
Anna Zaks88255cc2011-08-20 01:27:22 +00002304CFRefLeakReportVisitor::getEndPath(BugReporterContext &BRC,
David Blaikied15481c2014-08-29 18:18:43 +00002305 const ExplodedNode *EndN, BugReport &BR) {
Mike Stump11289f42009-09-09 15:08:12 +00002306
Ted Kremenekbb8d5462009-05-06 21:39:49 +00002307 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenek6bd78702009-04-29 18:50:19 +00002308 // assigned to different variables, etc.
Ted Kremenek1e809b42012-03-09 01:13:14 +00002309 BR.markInteresting(Sym);
Mike Stump11289f42009-09-09 15:08:12 +00002310
Ted Kremenek6bd78702009-04-29 18:50:19 +00002311 // We are reporting a leak. Walk up the graph to get to the first node where
2312 // the symbol appeared, and also get the first VarDecl that tracked object
2313 // is stored to.
Anna Zakse51362e2013-04-10 21:42:06 +00002314 AllocationInfo AllocI =
Ted Kremenek8c8fb482009-05-08 23:32:51 +00002315 GetAllocationSite(BRC.getStateManager(), EndN, Sym);
Mike Stump11289f42009-09-09 15:08:12 +00002316
Anna Zakse51362e2013-04-10 21:42:06 +00002317 const MemRegion* FirstBinding = AllocI.R;
2318 BR.markInteresting(AllocI.InterestingMethodContext);
2319
Anna Zaks921f0492011-09-15 18:56:07 +00002320 SourceManager& SM = BRC.getSourceManager();
Mike Stump11289f42009-09-09 15:08:12 +00002321
Ted Kremenek6bd78702009-04-29 18:50:19 +00002322 // Compute an actual location for the leak. Sometimes a leak doesn't
2323 // occur at an actual statement (e.g., transition between blocks; end
2324 // of function) so we need to walk the graph and compute a real location.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002325 const ExplodedNode *LeakN = EndN;
Anna Zaks921f0492011-09-15 18:56:07 +00002326 PathDiagnosticLocation L = PathDiagnosticLocation::createEndOfPath(LeakN, SM);
Mike Stump11289f42009-09-09 15:08:12 +00002327
Ted Kremenek6bd78702009-04-29 18:50:19 +00002328 std::string sbuf;
2329 llvm::raw_string_ostream os(sbuf);
Mike Stump11289f42009-09-09 15:08:12 +00002330
Ted Kremenekf2301982011-05-26 18:45:44 +00002331 os << "Object leaked: ";
Mike Stump11289f42009-09-09 15:08:12 +00002332
Ted Kremenekf2301982011-05-26 18:45:44 +00002333 if (FirstBinding) {
2334 os << "object allocated and stored into '"
2335 << FirstBinding->getString() << '\'';
2336 }
2337 else
2338 os << "allocated object";
Mike Stump11289f42009-09-09 15:08:12 +00002339
Ted Kremenek6bd78702009-04-29 18:50:19 +00002340 // Get the retain count.
Anna Zaksf5788c72012-08-14 00:36:15 +00002341 const RefVal* RV = getRefBinding(EndN->getState(), Sym);
Ted Kremenekb045b012012-10-12 22:56:40 +00002342 assert(RV);
Mike Stump11289f42009-09-09 15:08:12 +00002343
Ted Kremenek6bd78702009-04-29 18:50:19 +00002344 if (RV->getKind() == RefVal::ErrorLeakReturned) {
2345 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
Jordy Rose43426f82011-07-15 22:17:54 +00002346 // objects. Only "copy", "alloc", "retain" and "new" transfer ownership
Ted Kremenek6bd78702009-04-29 18:50:19 +00002347 // to the caller for NS objects.
Ted Kremenek8e2c9b02011-05-25 06:19:45 +00002348 const Decl *D = &EndN->getCodeDecl();
Ted Kremenek2a786952012-09-06 23:03:07 +00002349
2350 os << (isa<ObjCMethodDecl>(D) ? " is returned from a method "
2351 : " is returned from a function ");
2352
Aaron Ballman9ead1242013-12-19 02:39:40 +00002353 if (D->hasAttr<CFReturnsNotRetainedAttr>())
Ted Kremenek2a786952012-09-06 23:03:07 +00002354 os << "that is annotated as CF_RETURNS_NOT_RETAINED";
Aaron Ballman9ead1242013-12-19 02:39:40 +00002355 else if (D->hasAttr<NSReturnsNotRetainedAttr>())
Ted Kremenek2a786952012-09-06 23:03:07 +00002356 os << "that is annotated as NS_RETURNS_NOT_RETAINED";
Ted Kremenek8e2c9b02011-05-25 06:19:45 +00002357 else {
Ted Kremenek2a786952012-09-06 23:03:07 +00002358 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2359 os << "whose name ('" << MD->getSelector().getAsString()
2360 << "') does not start with 'copy', 'mutableCopy', 'alloc' or 'new'."
2361 " This violates the naming convention rules"
2362 " given in the Memory Management Guide for Cocoa";
2363 }
2364 else {
2365 const FunctionDecl *FD = cast<FunctionDecl>(D);
2366 os << "whose name ('" << *FD
2367 << "') does not contain 'Copy' or 'Create'. This violates the naming"
2368 " convention rules given in the Memory Management Guide for Core"
2369 " Foundation";
2370 }
2371 }
Ted Kremenek6bd78702009-04-29 18:50:19 +00002372 }
Ted Kremenekdee56e32009-05-10 06:25:57 +00002373 else if (RV->getKind() == RefVal::ErrorGCLeakReturned) {
David Blaikie3cbec0f2013-02-21 22:37:44 +00002374 const ObjCMethodDecl &MD = cast<ObjCMethodDecl>(EndN->getCodeDecl());
Ted Kremenekdee56e32009-05-10 06:25:57 +00002375 os << " and returned from method '" << MD.getSelector().getAsString()
Ted Kremenek1f8e4342009-05-10 16:52:15 +00002376 << "' is potentially leaked when using garbage collection. Callers "
2377 "of this method do not expect a returned object with a +1 retain "
2378 "count since they expect the object to be managed by the garbage "
2379 "collector";
Ted Kremenekdee56e32009-05-10 06:25:57 +00002380 }
Ted Kremenek6bd78702009-04-29 18:50:19 +00002381 else
Ted Kremenek4f63ac72010-10-15 22:50:23 +00002382 os << " is not referenced later in this execution path and has a retain "
Ted Kremenekf2301982011-05-26 18:45:44 +00002383 "count of +" << RV->getCount();
Mike Stump11289f42009-09-09 15:08:12 +00002384
David Blaikied15481c2014-08-29 18:18:43 +00002385 return llvm::make_unique<PathDiagnosticEventPiece>(L, os.str());
Ted Kremenek6bd78702009-04-29 18:50:19 +00002386}
2387
Jordy Rose184bd142011-08-24 22:39:09 +00002388CFRefLeakReport::CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts,
2389 bool GCEnabled, const SummaryLogTy &Log,
2390 ExplodedNode *n, SymbolRef sym,
Ted Kremenek8671acb2013-04-16 21:44:22 +00002391 CheckerContext &Ctx,
2392 bool IncludeAllocationLine)
2393 : CFRefReport(D, LOpts, GCEnabled, Log, n, sym, false) {
Mike Stump11289f42009-09-09 15:08:12 +00002394
Chris Lattner57540c52011-04-15 05:22:18 +00002395 // Most bug reports are cached at the location where they occurred.
Ted Kremenek6bd78702009-04-29 18:50:19 +00002396 // With leaks, we want to unique them by the location where they were
2397 // allocated, and only report a single path. To do this, we need to find
2398 // the allocation site of a piece of tracked memory, which we do via a
2399 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2400 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2401 // that all ancestor nodes that represent the allocation site have the
2402 // same SourceLocation.
Craig Topper0dbb7832014-05-27 02:45:47 +00002403 const ExplodedNode *AllocNode = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002404
Anna Zaks58734db2011-10-25 19:57:11 +00002405 const SourceManager& SMgr = Ctx.getSourceManager();
Anna Zaksc29bed32011-09-20 21:38:35 +00002406
Anna Zakse51362e2013-04-10 21:42:06 +00002407 AllocationInfo AllocI =
Anna Zaks58734db2011-10-25 19:57:11 +00002408 GetAllocationSite(Ctx.getStateManager(), getErrorNode(), sym);
Mike Stump11289f42009-09-09 15:08:12 +00002409
Anna Zakse51362e2013-04-10 21:42:06 +00002410 AllocNode = AllocI.N;
2411 AllocBinding = AllocI.R;
2412 markInteresting(AllocI.InterestingMethodContext);
2413
Ted Kremenek6bd78702009-04-29 18:50:19 +00002414 // Get the SourceLocation for the allocation site.
Jordan Rosefbe6dba2012-07-10 22:07:52 +00002415 // FIXME: This will crash the analyzer if an allocation comes from an
Anna Zaksa6fea132014-06-13 23:47:38 +00002416 // implicit call (ex: a destructor call).
2417 // (Currently there are no such allocations in Cocoa, though.)
2418 const Stmt *AllocStmt = 0;
Ted Kremenek6bd78702009-04-29 18:50:19 +00002419 ProgramPoint P = AllocNode->getLocation();
David Blaikie87396b92013-02-21 22:23:56 +00002420 if (Optional<CallExitEnd> Exit = P.getAs<CallExitEnd>())
Jordan Rosefbe6dba2012-07-10 22:07:52 +00002421 AllocStmt = Exit->getCalleeContext()->getCallSite();
Anna Zaks486a0ff2015-02-05 01:02:53 +00002422 else
2423 AllocStmt = P.castAs<PostStmt>().getStmt();
Anna Zaksa6fea132014-06-13 23:47:38 +00002424 assert(AllocStmt && "Cannot find allocation statement");
Anna Zaks40402872013-04-23 23:57:50 +00002425
2426 PathDiagnosticLocation AllocLocation =
2427 PathDiagnosticLocation::createBegin(AllocStmt, SMgr,
2428 AllocNode->getLocationContext());
2429 Location = AllocLocation;
2430
2431 // Set uniqieing info, which will be used for unique the bug reports. The
2432 // leaks should be uniqued on the allocation site.
2433 UniqueingLocation = AllocLocation;
2434 UniqueingDecl = AllocNode->getLocationContext()->getDecl();
2435
Ted Kremenek6bd78702009-04-29 18:50:19 +00002436 // Fill in the description of the bug.
2437 Description.clear();
2438 llvm::raw_string_ostream os(Description);
Ted Kremenekf1e76672009-05-02 19:05:19 +00002439 os << "Potential leak ";
Jordy Rose184bd142011-08-24 22:39:09 +00002440 if (GCEnabled)
Ted Kremenekf1e76672009-05-02 19:05:19 +00002441 os << "(when using garbage collection) ";
Anna Zaks16f38312012-02-28 21:49:08 +00002442 os << "of an object";
Mike Stump11289f42009-09-09 15:08:12 +00002443
Ted Kremenek8671acb2013-04-16 21:44:22 +00002444 if (AllocBinding) {
Anna Zaks16f38312012-02-28 21:49:08 +00002445 os << " stored into '" << AllocBinding->getString() << '\'';
Ted Kremenek8671acb2013-04-16 21:44:22 +00002446 if (IncludeAllocationLine) {
2447 FullSourceLoc SL(AllocStmt->getLocStart(), Ctx.getSourceManager());
2448 os << " (allocated on line " << SL.getSpellingLineNumber() << ")";
2449 }
2450 }
Anna Zaks071a89c2011-08-19 23:21:56 +00002451
David Blaikie91e79022014-09-04 23:54:33 +00002452 addVisitor(llvm::make_unique<CFRefLeakReportVisitor>(sym, GCEnabled, Log));
Ted Kremenek6bd78702009-04-29 18:50:19 +00002453}
2454
2455//===----------------------------------------------------------------------===//
2456// Main checker logic.
2457//===----------------------------------------------------------------------===//
2458
Ted Kremenek70a87882009-11-25 22:17:44 +00002459namespace {
Jordy Rose75e680e2011-09-02 06:44:22 +00002460class RetainCountChecker
Jordy Rose5df640d2011-08-24 18:56:32 +00002461 : public Checker< check::Bind,
Jordy Rose78612762011-08-23 19:01:07 +00002462 check::DeadSymbols,
Jordy Rose5df640d2011-08-24 18:56:32 +00002463 check::EndAnalysis,
Anna Zaks3fdcc0b2013-01-03 00:25:29 +00002464 check::EndFunction,
Jordy Rose217eb902011-08-17 21:27:39 +00002465 check::PostStmt<BlockExpr>,
John McCall31168b02011-06-15 23:02:42 +00002466 check::PostStmt<CastExpr>,
Ted Kremenek415287d2012-03-06 20:06:12 +00002467 check::PostStmt<ObjCArrayLiteral>,
2468 check::PostStmt<ObjCDictionaryLiteral>,
Jordy Rose6393f822012-05-12 05:10:43 +00002469 check::PostStmt<ObjCBoxedExpr>,
Jordan Roseb3ad07e2014-03-25 17:10:58 +00002470 check::PostStmt<ObjCIvarRefExpr>,
Jordan Rose682b3162012-07-02 19:28:21 +00002471 check::PostCall,
Jordy Rose298cc4d2011-08-23 19:43:16 +00002472 check::PreStmt<ReturnStmt>,
Jordy Rose217eb902011-08-17 21:27:39 +00002473 check::RegionChanges,
Jordy Rose898a1482011-08-21 21:58:18 +00002474 eval::Assume,
2475 eval::Call > {
Ahmed Charlesb8984322014-03-07 20:03:18 +00002476 mutable std::unique_ptr<CFRefBug> useAfterRelease, releaseNotOwned;
2477 mutable std::unique_ptr<CFRefBug> deallocGC, deallocNotOwned;
2478 mutable std::unique_ptr<CFRefBug> overAutorelease, returnNotOwnedForOwned;
2479 mutable std::unique_ptr<CFRefBug> leakWithinFunction, leakAtReturn;
2480 mutable std::unique_ptr<CFRefBug> leakWithinFunctionGC, leakAtReturnGC;
Jordy Rose78612762011-08-23 19:01:07 +00002481
Anton Yartsev6a619222014-02-17 18:25:34 +00002482 typedef llvm::DenseMap<SymbolRef, const CheckerProgramPointTag *> SymbolTagMap;
Jordy Rose78612762011-08-23 19:01:07 +00002483
2484 // This map is only used to ensure proper deletion of any allocated tags.
2485 mutable SymbolTagMap DeadSymbolTags;
2486
Ahmed Charlesb8984322014-03-07 20:03:18 +00002487 mutable std::unique_ptr<RetainSummaryManager> Summaries;
2488 mutable std::unique_ptr<RetainSummaryManager> SummariesGC;
Jordy Rose5df640d2011-08-24 18:56:32 +00002489 mutable SummaryLogTy SummaryLog;
2490 mutable bool ShouldResetSummaryLog;
2491
Ted Kremenek8671acb2013-04-16 21:44:22 +00002492 /// Optional setting to indicate if leak reports should include
2493 /// the allocation line.
2494 mutable bool IncludeAllocationLine;
2495
Jordy Rosea8f99ba2011-08-20 21:17:59 +00002496public:
Ted Kremenek8671acb2013-04-16 21:44:22 +00002497 RetainCountChecker(AnalyzerOptions &AO)
2498 : ShouldResetSummaryLog(false),
2499 IncludeAllocationLine(shouldIncludeAllocationSiteInLeakDiagnostics(AO)) {}
Jordy Rose78612762011-08-23 19:01:07 +00002500
Alexander Kornienko34eb2072015-04-11 02:00:23 +00002501 ~RetainCountChecker() override { DeleteContainerSeconds(DeadSymbolTags); }
Jordy Rose78612762011-08-23 19:01:07 +00002502
Jordy Rose5df640d2011-08-24 18:56:32 +00002503 void checkEndAnalysis(ExplodedGraph &G, BugReporter &BR,
2504 ExprEngine &Eng) const {
2505 // FIXME: This is a hack to make sure the summary log gets cleared between
2506 // analyses of different code bodies.
2507 //
2508 // Why is this necessary? Because a checker's lifetime is tied to a
2509 // translation unit, but an ExplodedGraph's lifetime is just a code body.
2510 // Once in a blue moon, a new ExplodedNode will have the same address as an
2511 // old one with an associated summary, and the bug report visitor gets very
2512 // confused. (To make things worse, the summary lifetime is currently also
2513 // tied to a code body, so we get a crash instead of incorrect results.)
Jordy Rose95589f12011-08-24 09:27:24 +00002514 //
2515 // Why is this a bad solution? Because if the lifetime of the ExplodedGraph
2516 // changes, things will start going wrong again. Really the lifetime of this
2517 // log needs to be tied to either the specific nodes in it or the entire
2518 // ExplodedGraph, not to a specific part of the code being analyzed.
2519 //
Jordy Rose5df640d2011-08-24 18:56:32 +00002520 // (Also, having stateful local data means that the same checker can't be
2521 // used from multiple threads, but a lot of checkers have incorrect
2522 // assumptions about that anyway. So that wasn't a priority at the time of
2523 // this fix.)
Jordy Rose95589f12011-08-24 09:27:24 +00002524 //
Jordy Rose5df640d2011-08-24 18:56:32 +00002525 // This happens at the end of analysis, but bug reports are emitted /after/
2526 // this point. So we can't just clear the summary log now. Instead, we mark
2527 // that the next time we access the summary log, it should be cleared.
2528
2529 // If we never reset the summary log during /this/ code body analysis,
2530 // there were no new summaries. There might still have been summaries from
2531 // the /last/ analysis, so clear them out to make sure the bug report
2532 // visitors don't get confused.
2533 if (ShouldResetSummaryLog)
2534 SummaryLog.clear();
2535
2536 ShouldResetSummaryLog = !SummaryLog.empty();
Jordy Rose95589f12011-08-24 09:27:24 +00002537 }
2538
Jordy Rosec49ec532011-09-02 05:55:19 +00002539 CFRefBug *getLeakWithinFunctionBug(const LangOptions &LOpts,
2540 bool GCEnabled) const {
2541 if (GCEnabled) {
Jordy Rose15484da2011-08-25 01:14:38 +00002542 if (!leakWithinFunctionGC)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002543 leakWithinFunctionGC.reset(new Leak(this, "Leak of object when using "
2544 "garbage collection"));
Jordy Rosec49ec532011-09-02 05:55:19 +00002545 return leakWithinFunctionGC.get();
Jordy Rose15484da2011-08-25 01:14:38 +00002546 } else {
2547 if (!leakWithinFunction) {
Douglas Gregor79a91412011-09-13 17:21:33 +00002548 if (LOpts.getGC() == LangOptions::HybridGC) {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002549 leakWithinFunction.reset(new Leak(this,
2550 "Leak of object when not using "
Benjamin Kramerd1d76b22012-06-06 17:32:50 +00002551 "garbage collection (GC) in "
2552 "dual GC/non-GC code"));
Jordy Rose15484da2011-08-25 01:14:38 +00002553 } else {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002554 leakWithinFunction.reset(new Leak(this, "Leak"));
Jordy Rose15484da2011-08-25 01:14:38 +00002555 }
2556 }
Jordy Rosec49ec532011-09-02 05:55:19 +00002557 return leakWithinFunction.get();
Jordy Rose15484da2011-08-25 01:14:38 +00002558 }
2559 }
2560
Jordy Rosec49ec532011-09-02 05:55:19 +00002561 CFRefBug *getLeakAtReturnBug(const LangOptions &LOpts, bool GCEnabled) const {
2562 if (GCEnabled) {
Jordy Rose15484da2011-08-25 01:14:38 +00002563 if (!leakAtReturnGC)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002564 leakAtReturnGC.reset(new Leak(this,
2565 "Leak of returned object when using "
Benjamin Kramerd1d76b22012-06-06 17:32:50 +00002566 "garbage collection"));
Jordy Rosec49ec532011-09-02 05:55:19 +00002567 return leakAtReturnGC.get();
Jordy Rose15484da2011-08-25 01:14:38 +00002568 } else {
2569 if (!leakAtReturn) {
Douglas Gregor79a91412011-09-13 17:21:33 +00002570 if (LOpts.getGC() == LangOptions::HybridGC) {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002571 leakAtReturn.reset(new Leak(this,
2572 "Leak of returned object when not using "
Benjamin Kramerd1d76b22012-06-06 17:32:50 +00002573 "garbage collection (GC) in dual "
2574 "GC/non-GC code"));
Jordy Rose15484da2011-08-25 01:14:38 +00002575 } else {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002576 leakAtReturn.reset(new Leak(this, "Leak of returned object"));
Jordy Rose15484da2011-08-25 01:14:38 +00002577 }
2578 }
Jordy Rosec49ec532011-09-02 05:55:19 +00002579 return leakAtReturn.get();
Jordy Rose15484da2011-08-25 01:14:38 +00002580 }
2581 }
2582
Jordy Rosec49ec532011-09-02 05:55:19 +00002583 RetainSummaryManager &getSummaryManager(ASTContext &Ctx,
2584 bool GCEnabled) const {
2585 // FIXME: We don't support ARC being turned on and off during one analysis.
2586 // (nor, for that matter, do we support changing ASTContexts)
David Blaikiebbafb8a2012-03-11 07:00:24 +00002587 bool ARCEnabled = (bool)Ctx.getLangOpts().ObjCAutoRefCount;
Jordy Rosec49ec532011-09-02 05:55:19 +00002588 if (GCEnabled) {
2589 if (!SummariesGC)
Jordy Rose8b289a22011-08-25 00:10:37 +00002590 SummariesGC.reset(new RetainSummaryManager(Ctx, true, ARCEnabled));
Jordy Rosec49ec532011-09-02 05:55:19 +00002591 else
2592 assert(SummariesGC->isARCEnabled() == ARCEnabled);
Jordy Rose8b289a22011-08-25 00:10:37 +00002593 return *SummariesGC;
2594 } else {
Jordy Rosec49ec532011-09-02 05:55:19 +00002595 if (!Summaries)
Jordy Rose8b289a22011-08-25 00:10:37 +00002596 Summaries.reset(new RetainSummaryManager(Ctx, false, ARCEnabled));
Jordy Rosec49ec532011-09-02 05:55:19 +00002597 else
2598 assert(Summaries->isARCEnabled() == ARCEnabled);
Jordy Rose8b289a22011-08-25 00:10:37 +00002599 return *Summaries;
2600 }
2601 }
2602
Jordy Rosec49ec532011-09-02 05:55:19 +00002603 RetainSummaryManager &getSummaryManager(CheckerContext &C) const {
2604 return getSummaryManager(C.getASTContext(), C.isObjCGCEnabled());
2605 }
2606
Ted Kremenek49b1e382012-01-26 21:29:00 +00002607 void printState(raw_ostream &Out, ProgramStateRef State,
Craig Topperfb6b25b2014-03-15 04:29:04 +00002608 const char *NL, const char *Sep) const override;
Jordy Rose58a20d32011-08-28 19:11:56 +00002609
Anna Zaks3e0f4152011-10-06 00:43:15 +00002610 void checkBind(SVal loc, SVal val, const Stmt *S, CheckerContext &C) const;
Jordy Rose5c252ef2011-08-20 21:16:58 +00002611 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
2612 void checkPostStmt(const CastExpr *CE, CheckerContext &C) const;
John McCall31168b02011-06-15 23:02:42 +00002613
Ted Kremenek415287d2012-03-06 20:06:12 +00002614 void checkPostStmt(const ObjCArrayLiteral *AL, CheckerContext &C) const;
2615 void checkPostStmt(const ObjCDictionaryLiteral *DL, CheckerContext &C) const;
Jordy Rose6393f822012-05-12 05:10:43 +00002616 void checkPostStmt(const ObjCBoxedExpr *BE, CheckerContext &C) const;
2617
Jordan Roseb3ad07e2014-03-25 17:10:58 +00002618 void checkPostStmt(const ObjCIvarRefExpr *IRE, CheckerContext &C) const;
2619
Jordan Rose682b3162012-07-02 19:28:21 +00002620 void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
Ted Kremenek415287d2012-03-06 20:06:12 +00002621
Jordan Roseeec15392012-07-02 19:27:43 +00002622 void checkSummary(const RetainSummary &Summ, const CallEvent &Call,
Jordy Rosed188d662011-08-28 05:16:28 +00002623 CheckerContext &C) const;
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002624
Anna Zaks25612732012-08-29 23:23:43 +00002625 void processSummaryOfInlined(const RetainSummary &Summ,
2626 const CallEvent &Call,
2627 CheckerContext &C) const;
2628
Jordy Rose898a1482011-08-21 21:58:18 +00002629 bool evalCall(const CallExpr *CE, CheckerContext &C) const;
2630
Ted Kremenek49b1e382012-01-26 21:29:00 +00002631 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Jordy Rose5c252ef2011-08-20 21:16:58 +00002632 bool Assumption) const;
Jordy Rose217eb902011-08-17 21:27:39 +00002633
Ted Kremenek49b1e382012-01-26 21:29:00 +00002634 ProgramStateRef
2635 checkRegionChanges(ProgramStateRef state,
Anna Zaksdc154152012-12-20 00:38:25 +00002636 const InvalidatedSymbols *invalidated,
Jordy Rose1fad6632011-08-27 22:51:26 +00002637 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks3d348342012-02-14 21:55:24 +00002638 ArrayRef<const MemRegion *> Regions,
Jordan Rose742920c2012-07-02 19:27:35 +00002639 const CallEvent *Call) const;
Jordy Rose5c252ef2011-08-20 21:16:58 +00002640
Ted Kremenek49b1e382012-01-26 21:29:00 +00002641 bool wantsRegionChangeUpdate(ProgramStateRef state) const {
Jordy Rosea8f99ba2011-08-20 21:17:59 +00002642 return true;
Jordy Rose5c252ef2011-08-20 21:16:58 +00002643 }
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002644
Jordy Rose298cc4d2011-08-23 19:43:16 +00002645 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
2646 void checkReturnWithRetEffect(const ReturnStmt *S, CheckerContext &C,
2647 ExplodedNode *Pred, RetEffect RE, RefVal X,
Ted Kremenek49b1e382012-01-26 21:29:00 +00002648 SymbolRef Sym, ProgramStateRef state) const;
Jordy Rose298cc4d2011-08-23 19:43:16 +00002649
Jordy Rose78612762011-08-23 19:01:07 +00002650 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Anna Zaks3fdcc0b2013-01-03 00:25:29 +00002651 void checkEndFunction(CheckerContext &C) const;
Jordy Rose78612762011-08-23 19:01:07 +00002652
Ted Kremenek49b1e382012-01-26 21:29:00 +00002653 ProgramStateRef updateSymbol(ProgramStateRef state, SymbolRef sym,
Anna Zaks25612732012-08-29 23:23:43 +00002654 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
2655 CheckerContext &C) const;
Jordy Rosebf77e512011-08-23 20:27:16 +00002656
Ted Kremenek49b1e382012-01-26 21:29:00 +00002657 void processNonLeakError(ProgramStateRef St, SourceRange ErrorRange,
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002658 RefVal::Kind ErrorKind, SymbolRef Sym,
2659 CheckerContext &C) const;
Ted Kremenek415287d2012-03-06 20:06:12 +00002660
2661 void processObjCLiterals(CheckerContext &C, const Expr *Ex) const;
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002662
Jordy Rose78612762011-08-23 19:01:07 +00002663 const ProgramPointTag *getDeadSymbolTag(SymbolRef sym) const;
2664
Ted Kremenek49b1e382012-01-26 21:29:00 +00002665 ProgramStateRef handleSymbolDeath(ProgramStateRef state,
Anna Zaksf5788c72012-08-14 00:36:15 +00002666 SymbolRef sid, RefVal V,
2667 SmallVectorImpl<SymbolRef> &Leaked) const;
Jordy Rose78612762011-08-23 19:01:07 +00002668
Jordan Roseff03c1d2012-12-06 18:58:18 +00002669 ProgramStateRef
Jordan Rose9f61f8a2012-08-18 00:30:16 +00002670 handleAutoreleaseCounts(ProgramStateRef state, ExplodedNode *Pred,
2671 const ProgramPointTag *Tag, CheckerContext &Ctx,
2672 SymbolRef Sym, RefVal V) const;
Jordy Rose6763e382011-08-23 20:07:14 +00002673
Ted Kremenek49b1e382012-01-26 21:29:00 +00002674 ExplodedNode *processLeaks(ProgramStateRef state,
Jordy Rose78612762011-08-23 19:01:07 +00002675 SmallVectorImpl<SymbolRef> &Leaked,
Anna Zaks58734db2011-10-25 19:57:11 +00002676 CheckerContext &Ctx,
Craig Topper0dbb7832014-05-27 02:45:47 +00002677 ExplodedNode *Pred = nullptr) const;
Ted Kremenek70a87882009-11-25 22:17:44 +00002678};
2679} // end anonymous namespace
2680
Jordy Rose217eb902011-08-17 21:27:39 +00002681namespace {
2682class StopTrackingCallback : public SymbolVisitor {
Ted Kremenek49b1e382012-01-26 21:29:00 +00002683 ProgramStateRef state;
Jordy Rose217eb902011-08-17 21:27:39 +00002684public:
Ted Kremenek49b1e382012-01-26 21:29:00 +00002685 StopTrackingCallback(ProgramStateRef st) : state(st) {}
2686 ProgramStateRef getState() const { return state; }
Jordy Rose217eb902011-08-17 21:27:39 +00002687
Craig Topperfb6b25b2014-03-15 04:29:04 +00002688 bool VisitSymbol(SymbolRef sym) override {
Jordy Rose217eb902011-08-17 21:27:39 +00002689 state = state->remove<RefBindings>(sym);
2690 return true;
2691 }
2692};
2693} // end anonymous namespace
2694
Jordy Rose75e680e2011-09-02 06:44:22 +00002695//===----------------------------------------------------------------------===//
2696// Handle statements that may have an effect on refcounts.
2697//===----------------------------------------------------------------------===//
Jordy Rose217eb902011-08-17 21:27:39 +00002698
Jordy Rose75e680e2011-09-02 06:44:22 +00002699void RetainCountChecker::checkPostStmt(const BlockExpr *BE,
2700 CheckerContext &C) const {
Jordy Rose217eb902011-08-17 21:27:39 +00002701
Jordy Rose75e680e2011-09-02 06:44:22 +00002702 // Scan the BlockDecRefExprs for any object the retain count checker
Ted Kremenekbd862712010-07-01 20:16:50 +00002703 // may be tracking.
John McCallc63de662011-02-02 13:00:07 +00002704 if (!BE->getBlockDecl()->hasCaptures())
Ted Kremenekf89dcda2009-11-26 02:38:19 +00002705 return;
Ted Kremenekbd862712010-07-01 20:16:50 +00002706
Ted Kremenek49b1e382012-01-26 21:29:00 +00002707 ProgramStateRef state = C.getState();
Ted Kremenekf89dcda2009-11-26 02:38:19 +00002708 const BlockDataRegion *R =
Ted Kremenek632e3b72012-01-06 22:09:28 +00002709 cast<BlockDataRegion>(state->getSVal(BE,
2710 C.getLocationContext()).getAsRegion());
Ted Kremenekbd862712010-07-01 20:16:50 +00002711
Ted Kremenekf89dcda2009-11-26 02:38:19 +00002712 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
2713 E = R->referenced_vars_end();
Ted Kremenekbd862712010-07-01 20:16:50 +00002714
Ted Kremenekf89dcda2009-11-26 02:38:19 +00002715 if (I == E)
2716 return;
Ted Kremenekbd862712010-07-01 20:16:50 +00002717
Ted Kremenek04af9f22009-12-07 22:05:27 +00002718 // FIXME: For now we invalidate the tracking of all symbols passed to blocks
2719 // via captured variables, even though captured variables result in a copy
2720 // and in implicit increment/decrement of a retain count.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002721 SmallVector<const MemRegion*, 10> Regions;
Anna Zaksc9abbe22011-10-26 21:06:44 +00002722 const LocationContext *LC = C.getLocationContext();
Ted Kremenek90af9092010-12-02 07:49:45 +00002723 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
Ted Kremenekbd862712010-07-01 20:16:50 +00002724
Ted Kremenek04af9f22009-12-07 22:05:27 +00002725 for ( ; I != E; ++I) {
Ted Kremenekbcf90532012-12-06 07:17:20 +00002726 const VarRegion *VR = I.getCapturedRegion();
Ted Kremenek04af9f22009-12-07 22:05:27 +00002727 if (VR->getSuperRegion() == R) {
2728 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2729 }
2730 Regions.push_back(VR);
2731 }
Ted Kremenekbd862712010-07-01 20:16:50 +00002732
Ted Kremenek04af9f22009-12-07 22:05:27 +00002733 state =
2734 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
2735 Regions.data() + Regions.size()).getState();
Anna Zaksda4c8d62011-10-26 21:06:34 +00002736 C.addTransition(state);
Ted Kremenekf89dcda2009-11-26 02:38:19 +00002737}
2738
Jordy Rose75e680e2011-09-02 06:44:22 +00002739void RetainCountChecker::checkPostStmt(const CastExpr *CE,
2740 CheckerContext &C) const {
John McCall31168b02011-06-15 23:02:42 +00002741 const ObjCBridgedCastExpr *BE = dyn_cast<ObjCBridgedCastExpr>(CE);
2742 if (!BE)
2743 return;
2744
John McCall640767f2011-06-17 06:50:50 +00002745 ArgEffect AE = IncRef;
John McCall31168b02011-06-15 23:02:42 +00002746
2747 switch (BE->getBridgeKind()) {
2748 case clang::OBC_Bridge:
2749 // Do nothing.
2750 return;
2751 case clang::OBC_BridgeRetained:
2752 AE = IncRef;
2753 break;
2754 case clang::OBC_BridgeTransfer:
Benjamin Kramer1d5d6342013-10-20 11:53:20 +00002755 AE = DecRefBridgedTransferred;
John McCall31168b02011-06-15 23:02:42 +00002756 break;
2757 }
2758
Ted Kremenek49b1e382012-01-26 21:29:00 +00002759 ProgramStateRef state = C.getState();
Ted Kremenek632e3b72012-01-06 22:09:28 +00002760 SymbolRef Sym = state->getSVal(CE, C.getLocationContext()).getAsLocSymbol();
John McCall31168b02011-06-15 23:02:42 +00002761 if (!Sym)
2762 return;
Anna Zaksf5788c72012-08-14 00:36:15 +00002763 const RefVal* T = getRefBinding(state, Sym);
John McCall31168b02011-06-15 23:02:42 +00002764 if (!T)
2765 return;
2766
John McCall31168b02011-06-15 23:02:42 +00002767 RefVal::Kind hasErr = (RefVal::Kind) 0;
Jordy Rosec49ec532011-09-02 05:55:19 +00002768 state = updateSymbol(state, Sym, *T, AE, hasErr, C);
John McCall31168b02011-06-15 23:02:42 +00002769
2770 if (hasErr) {
Jordy Rosebf77e512011-08-23 20:27:16 +00002771 // FIXME: If we get an error during a bridge cast, should we report it?
John McCall31168b02011-06-15 23:02:42 +00002772 return;
2773 }
2774
Anna Zaksda4c8d62011-10-26 21:06:34 +00002775 C.addTransition(state);
John McCall31168b02011-06-15 23:02:42 +00002776}
2777
Ted Kremenek415287d2012-03-06 20:06:12 +00002778void RetainCountChecker::processObjCLiterals(CheckerContext &C,
2779 const Expr *Ex) const {
2780 ProgramStateRef state = C.getState();
2781 const ExplodedNode *pred = C.getPredecessor();
2782 for (Stmt::const_child_iterator it = Ex->child_begin(), et = Ex->child_end() ;
2783 it != et ; ++it) {
2784 const Stmt *child = *it;
2785 SVal V = state->getSVal(child, pred->getLocationContext());
2786 if (SymbolRef sym = V.getAsSymbol())
Anna Zaksf5788c72012-08-14 00:36:15 +00002787 if (const RefVal* T = getRefBinding(state, sym)) {
Ted Kremenek415287d2012-03-06 20:06:12 +00002788 RefVal::Kind hasErr = (RefVal::Kind) 0;
2789 state = updateSymbol(state, sym, *T, MayEscape, hasErr, C);
2790 if (hasErr) {
2791 processNonLeakError(state, child->getSourceRange(), hasErr, sym, C);
2792 return;
2793 }
2794 }
2795 }
2796
2797 // Return the object as autoreleased.
2798 // RetEffect RE = RetEffect::MakeNotOwned(RetEffect::ObjC);
2799 if (SymbolRef sym =
2800 state->getSVal(Ex, pred->getLocationContext()).getAsSymbol()) {
2801 QualType ResultTy = Ex->getType();
Anna Zaksf5788c72012-08-14 00:36:15 +00002802 state = setRefBinding(state, sym,
2803 RefVal::makeNotOwned(RetEffect::ObjC, ResultTy));
Ted Kremenek415287d2012-03-06 20:06:12 +00002804 }
2805
2806 C.addTransition(state);
2807}
2808
2809void RetainCountChecker::checkPostStmt(const ObjCArrayLiteral *AL,
2810 CheckerContext &C) const {
2811 // Apply the 'MayEscape' to all values.
2812 processObjCLiterals(C, AL);
2813}
2814
2815void RetainCountChecker::checkPostStmt(const ObjCDictionaryLiteral *DL,
2816 CheckerContext &C) const {
2817 // Apply the 'MayEscape' to all keys and values.
2818 processObjCLiterals(C, DL);
2819}
2820
Jordy Rose6393f822012-05-12 05:10:43 +00002821void RetainCountChecker::checkPostStmt(const ObjCBoxedExpr *Ex,
2822 CheckerContext &C) const {
2823 const ExplodedNode *Pred = C.getPredecessor();
2824 const LocationContext *LCtx = Pred->getLocationContext();
2825 ProgramStateRef State = Pred->getState();
2826
2827 if (SymbolRef Sym = State->getSVal(Ex, LCtx).getAsSymbol()) {
2828 QualType ResultTy = Ex->getType();
Anna Zaksf5788c72012-08-14 00:36:15 +00002829 State = setRefBinding(State, Sym,
2830 RefVal::makeNotOwned(RetEffect::ObjC, ResultTy));
Jordy Rose6393f822012-05-12 05:10:43 +00002831 }
2832
2833 C.addTransition(State);
2834}
2835
Jordan Rosecb5386c2015-02-04 19:24:52 +00002836static bool wasLoadedFromIvar(SymbolRef Sym) {
2837 if (auto DerivedVal = dyn_cast<SymbolDerived>(Sym))
2838 return isa<ObjCIvarRegion>(DerivedVal->getRegion());
2839 if (auto RegionVal = dyn_cast<SymbolRegionValue>(Sym))
2840 return isa<ObjCIvarRegion>(RegionVal->getRegion());
2841 return false;
2842}
2843
Jordan Roseb3ad07e2014-03-25 17:10:58 +00002844void RetainCountChecker::checkPostStmt(const ObjCIvarRefExpr *IRE,
2845 CheckerContext &C) const {
Jordan Rosecb5386c2015-02-04 19:24:52 +00002846 Optional<Loc> IVarLoc = C.getSVal(IRE).getAs<Loc>();
2847 if (!IVarLoc)
2848 return;
2849
Jordan Roseb3ad07e2014-03-25 17:10:58 +00002850 ProgramStateRef State = C.getState();
Jordan Rosecb5386c2015-02-04 19:24:52 +00002851 SymbolRef Sym = State->getSVal(*IVarLoc).getAsSymbol();
Jordan Rose000bac52015-02-19 23:57:04 +00002852 if (!Sym || !wasLoadedFromIvar(Sym))
Jordan Rosecb5386c2015-02-04 19:24:52 +00002853 return;
2854
2855 // Accessing an ivar directly is unusual. If we've done that, be more
2856 // forgiving about what the surrounding code is allowed to do.
2857
2858 QualType Ty = Sym->getType();
2859 RetEffect::ObjKind Kind;
2860 if (Ty->isObjCRetainableType())
2861 Kind = RetEffect::ObjC;
2862 else if (coreFoundation::isCFObjectRef(Ty))
2863 Kind = RetEffect::CF;
2864 else
2865 return;
2866
Jordan Rose000bac52015-02-19 23:57:04 +00002867 // If the value is already known to be nil, don't bother tracking it.
2868 ConstraintManager &CMgr = State->getConstraintManager();
2869 if (CMgr.isNull(State, Sym).isConstrainedTrue())
Jordan Rosecb5386c2015-02-04 19:24:52 +00002870 return;
2871
2872 if (const RefVal *RV = getRefBinding(State, Sym)) {
2873 // If we've seen this symbol before, or we're only seeing it now because
2874 // of something the analyzer has synthesized, don't do anything.
2875 if (RV->getIvarAccessHistory() != RefVal::IvarAccessHistory::None ||
2876 isSynthesizedAccessor(C.getStackFrame())) {
2877 return;
2878 }
2879
Jordan Rosecb5386c2015-02-04 19:24:52 +00002880 // Note that this value has been loaded from an ivar.
2881 C.addTransition(setRefBinding(State, Sym, RV->withIvarAccess()));
2882 return;
2883 }
2884
2885 RefVal PlusZero = RefVal::makeNotOwned(Kind, Ty);
2886
2887 // In a synthesized accessor, the effective retain count is +0.
2888 if (isSynthesizedAccessor(C.getStackFrame())) {
2889 C.addTransition(setRefBinding(State, Sym, PlusZero));
2890 return;
2891 }
2892
Jordan Rose218772f2015-03-30 20:17:47 +00002893 State = setRefBinding(State, Sym, PlusZero.withIvarAccess());
Jordan Roseb3ad07e2014-03-25 17:10:58 +00002894 C.addTransition(State);
2895}
2896
Jordan Rose682b3162012-07-02 19:28:21 +00002897void RetainCountChecker::checkPostCall(const CallEvent &Call,
2898 CheckerContext &C) const {
Jordan Rose682b3162012-07-02 19:28:21 +00002899 RetainSummaryManager &Summaries = getSummaryManager(C);
2900 const RetainSummary *Summ = Summaries.getSummary(Call, C.getState());
Anna Zaks25612732012-08-29 23:23:43 +00002901
2902 if (C.wasInlined) {
2903 processSummaryOfInlined(*Summ, Call, C);
2904 return;
2905 }
Jordan Rose682b3162012-07-02 19:28:21 +00002906 checkSummary(*Summ, Call, C);
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002907}
2908
Jordy Rose75e680e2011-09-02 06:44:22 +00002909/// GetReturnType - Used to get the return type of a message expression or
2910/// function call with the intention of affixing that type to a tracked symbol.
Sylvestre Ledru830885c2012-07-23 08:59:39 +00002911/// While the return type can be queried directly from RetEx, when
Jordy Rose75e680e2011-09-02 06:44:22 +00002912/// invoking class methods we augment to the return type to be that of
2913/// a pointer to the class (as opposed it just being id).
2914// FIXME: We may be able to do this with related result types instead.
2915// This function is probably overestimating.
2916static QualType GetReturnType(const Expr *RetE, ASTContext &Ctx) {
2917 QualType RetTy = RetE->getType();
2918 // If RetE is not a message expression just return its type.
2919 // If RetE is a message expression, return its types if it is something
2920 /// more specific than id.
2921 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RetE))
2922 if (const ObjCObjectPointerType *PT = RetTy->getAs<ObjCObjectPointerType>())
2923 if (PT->isObjCQualifiedIdType() || PT->isObjCIdType() ||
2924 PT->isObjCClassType()) {
2925 // At this point we know the return type of the message expression is
2926 // id, id<...>, or Class. If we have an ObjCInterfaceDecl, we know this
2927 // is a call to a class method whose type we can resolve. In such
2928 // cases, promote the return type to XXX* (where XXX is the class).
2929 const ObjCInterfaceDecl *D = ME->getReceiverInterface();
2930 return !D ? RetTy :
2931 Ctx.getObjCObjectPointerType(Ctx.getObjCInterfaceType(D));
2932 }
2933
2934 return RetTy;
2935}
2936
Anna Zaks25612732012-08-29 23:23:43 +00002937// We don't always get the exact modeling of the function with regards to the
2938// retain count checker even when the function is inlined. For example, we need
2939// to stop tracking the symbols which were marked with StopTrackingHard.
2940void RetainCountChecker::processSummaryOfInlined(const RetainSummary &Summ,
2941 const CallEvent &CallOrMsg,
2942 CheckerContext &C) const {
2943 ProgramStateRef state = C.getState();
2944
2945 // Evaluate the effect of the arguments.
2946 for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
2947 if (Summ.getArg(idx) == StopTrackingHard) {
2948 SVal V = CallOrMsg.getArgSVal(idx);
2949 if (SymbolRef Sym = V.getAsLocSymbol()) {
2950 state = removeRefBinding(state, Sym);
2951 }
2952 }
2953 }
2954
2955 // Evaluate the effect on the message receiver.
2956 const ObjCMethodCall *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg);
2957 if (MsgInvocation) {
2958 if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
2959 if (Summ.getReceiverEffect() == StopTrackingHard) {
2960 state = removeRefBinding(state, Sym);
2961 }
2962 }
2963 }
2964
2965 // Consult the summary for the return value.
2966 RetEffect RE = Summ.getRetEffect();
2967 if (RE.getKind() == RetEffect::NoRetHard) {
Jordan Rose829c3832012-11-02 23:49:29 +00002968 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
Anna Zaks25612732012-08-29 23:23:43 +00002969 if (Sym)
2970 state = removeRefBinding(state, Sym);
2971 }
2972
2973 C.addTransition(state);
2974}
2975
Douglas Gregoreb6e64c2015-06-19 23:17:46 +00002976static ProgramStateRef updateOutParameter(ProgramStateRef State,
2977 SVal ArgVal,
2978 ArgEffect Effect) {
2979 auto *ArgRegion = dyn_cast_or_null<TypedValueRegion>(ArgVal.getAsRegion());
2980 if (!ArgRegion)
2981 return State;
2982
2983 QualType PointeeTy = ArgRegion->getValueType();
2984 if (!coreFoundation::isCFObjectRef(PointeeTy))
2985 return State;
2986
2987 SVal PointeeVal = State->getSVal(ArgRegion);
2988 SymbolRef Pointee = PointeeVal.getAsLocSymbol();
2989 if (!Pointee)
2990 return State;
2991
2992 switch (Effect) {
2993 case UnretainedOutParameter:
2994 State = setRefBinding(State, Pointee,
2995 RefVal::makeNotOwned(RetEffect::CF, PointeeTy));
2996 break;
2997 case RetainedOutParameter:
2998 // Do nothing. Retained out parameters will either point to a +1 reference
2999 // or NULL, but the way you check for failure differs depending on the API.
3000 // Consequently, we don't have a good way to track them yet.
3001 break;
3002
3003 default:
3004 llvm_unreachable("only for out parameters");
3005 }
3006
3007 return State;
3008}
3009
Jordy Rose75e680e2011-09-02 06:44:22 +00003010void RetainCountChecker::checkSummary(const RetainSummary &Summ,
Jordan Roseeec15392012-07-02 19:27:43 +00003011 const CallEvent &CallOrMsg,
Jordy Rose75e680e2011-09-02 06:44:22 +00003012 CheckerContext &C) const {
Ted Kremenek49b1e382012-01-26 21:29:00 +00003013 ProgramStateRef state = C.getState();
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003014
3015 // Evaluate the effect of the arguments.
3016 RefVal::Kind hasErr = (RefVal::Kind) 0;
3017 SourceRange ErrorRange;
Craig Topper0dbb7832014-05-27 02:45:47 +00003018 SymbolRef ErrorSym = nullptr;
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003019
3020 for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
Jordy Rose1fad6632011-08-27 22:51:26 +00003021 SVal V = CallOrMsg.getArgSVal(idx);
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003022
Douglas Gregoreb6e64c2015-06-19 23:17:46 +00003023 ArgEffect Effect = Summ.getArg(idx);
3024 if (Effect == RetainedOutParameter || Effect == UnretainedOutParameter) {
3025 state = updateOutParameter(state, V, Effect);
3026 } else if (SymbolRef Sym = V.getAsLocSymbol()) {
Anna Zaksf5788c72012-08-14 00:36:15 +00003027 if (const RefVal *T = getRefBinding(state, Sym)) {
Douglas Gregoreb6e64c2015-06-19 23:17:46 +00003028 state = updateSymbol(state, Sym, *T, Effect, hasErr, C);
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003029 if (hasErr) {
3030 ErrorRange = CallOrMsg.getArgSourceRange(idx);
3031 ErrorSym = Sym;
3032 break;
3033 }
3034 }
3035 }
3036 }
3037
3038 // Evaluate the effect on the message receiver.
3039 bool ReceiverIsTracked = false;
Jordan Roseeec15392012-07-02 19:27:43 +00003040 if (!hasErr) {
Jordan Rose6bad4902012-07-02 19:27:56 +00003041 const ObjCMethodCall *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg);
Jordan Roseeec15392012-07-02 19:27:43 +00003042 if (MsgInvocation) {
3043 if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
Anna Zaksf5788c72012-08-14 00:36:15 +00003044 if (const RefVal *T = getRefBinding(state, Sym)) {
Jordan Roseeec15392012-07-02 19:27:43 +00003045 ReceiverIsTracked = true;
3046 state = updateSymbol(state, Sym, *T, Summ.getReceiverEffect(),
Anna Zaks25612732012-08-29 23:23:43 +00003047 hasErr, C);
Jordan Roseeec15392012-07-02 19:27:43 +00003048 if (hasErr) {
Jordan Rose627b0462012-07-18 21:59:51 +00003049 ErrorRange = MsgInvocation->getOriginExpr()->getReceiverRange();
Jordan Roseeec15392012-07-02 19:27:43 +00003050 ErrorSym = Sym;
3051 }
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003052 }
3053 }
3054 }
3055 }
3056
3057 // Process any errors.
3058 if (hasErr) {
3059 processNonLeakError(state, ErrorRange, hasErr, ErrorSym, C);
3060 return;
3061 }
3062
3063 // Consult the summary for the return value.
3064 RetEffect RE = Summ.getRetEffect();
3065
3066 if (RE.getKind() == RetEffect::OwnedWhenTrackedReceiver) {
Jordy Rose8b289a22011-08-25 00:10:37 +00003067 if (ReceiverIsTracked)
Jordy Rosec49ec532011-09-02 05:55:19 +00003068 RE = getSummaryManager(C).getObjAllocRetEffect();
Jordy Rose8b289a22011-08-25 00:10:37 +00003069 else
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003070 RE = RetEffect::MakeNoRet();
3071 }
3072
3073 switch (RE.getKind()) {
3074 default:
David Blaikie8a40f702012-01-17 06:56:22 +00003075 llvm_unreachable("Unhandled RetEffect.");
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003076
3077 case RetEffect::NoRet:
Anna Zaks25612732012-08-29 23:23:43 +00003078 case RetEffect::NoRetHard:
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003079 // No work necessary.
3080 break;
3081
3082 case RetEffect::OwnedAllocatedSymbol:
3083 case RetEffect::OwnedSymbol: {
Jordan Rose829c3832012-11-02 23:49:29 +00003084 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003085 if (!Sym)
3086 break;
3087
Jordan Roseeec15392012-07-02 19:27:43 +00003088 // Use the result type from the CallEvent as it automatically adjusts
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003089 // for methods/functions that return references.
Jordan Roseeec15392012-07-02 19:27:43 +00003090 QualType ResultTy = CallOrMsg.getResultType();
Anna Zaksf5788c72012-08-14 00:36:15 +00003091 state = setRefBinding(state, Sym, RefVal::makeOwned(RE.getObjKind(),
3092 ResultTy));
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003093
3094 // FIXME: Add a flag to the checker where allocations are assumed to
Anna Zaks21487f72012-08-14 15:39:13 +00003095 // *not* fail.
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003096 break;
3097 }
3098
3099 case RetEffect::GCNotOwnedSymbol:
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003100 case RetEffect::NotOwnedSymbol: {
3101 const Expr *Ex = CallOrMsg.getOriginExpr();
Jordan Rose829c3832012-11-02 23:49:29 +00003102 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003103 if (!Sym)
3104 break;
Ted Kremenekbe400842012-10-12 22:56:45 +00003105 assert(Ex);
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003106 // Use GetReturnType in order to give [NSFoo alloc] the type NSFoo *.
3107 QualType ResultTy = GetReturnType(Ex, C.getASTContext());
Anna Zaksf5788c72012-08-14 00:36:15 +00003108 state = setRefBinding(state, Sym, RefVal::makeNotOwned(RE.getObjKind(),
3109 ResultTy));
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003110 break;
3111 }
3112 }
3113
3114 // This check is actually necessary; otherwise the statement builder thinks
3115 // we've hit a previously-found path.
3116 // Normally addTransition takes care of this, but we want the node pointer.
3117 ExplodedNode *NewNode;
3118 if (state == C.getState()) {
3119 NewNode = C.getPredecessor();
3120 } else {
Anna Zaksda4c8d62011-10-26 21:06:34 +00003121 NewNode = C.addTransition(state);
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003122 }
3123
Jordy Rose5df640d2011-08-24 18:56:32 +00003124 // Annotate the node with summary we used.
3125 if (NewNode) {
3126 // FIXME: This is ugly. See checkEndAnalysis for why it's necessary.
3127 if (ShouldResetSummaryLog) {
3128 SummaryLog.clear();
3129 ShouldResetSummaryLog = false;
3130 }
Jordy Rose20d4e682011-08-23 20:55:48 +00003131 SummaryLog[NewNode] = &Summ;
Jordy Rose5df640d2011-08-24 18:56:32 +00003132 }
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003133}
3134
Jordy Rosebf77e512011-08-23 20:27:16 +00003135
Ted Kremenek49b1e382012-01-26 21:29:00 +00003136ProgramStateRef
3137RetainCountChecker::updateSymbol(ProgramStateRef state, SymbolRef sym,
Jordy Rose75e680e2011-09-02 06:44:22 +00003138 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
3139 CheckerContext &C) const {
Jordy Rosebf77e512011-08-23 20:27:16 +00003140 // In GC mode [... release] and [... retain] do nothing.
Jordy Rose75e680e2011-09-02 06:44:22 +00003141 // In ARC mode they shouldn't exist at all, but we just ignore them.
Jordy Rosec49ec532011-09-02 05:55:19 +00003142 bool IgnoreRetainMsg = C.isObjCGCEnabled();
3143 if (!IgnoreRetainMsg)
David Blaikiebbafb8a2012-03-11 07:00:24 +00003144 IgnoreRetainMsg = (bool)C.getASTContext().getLangOpts().ObjCAutoRefCount;
Jordy Rosec49ec532011-09-02 05:55:19 +00003145
Jordy Rosebf77e512011-08-23 20:27:16 +00003146 switch (E) {
Jordan Roseeec15392012-07-02 19:27:43 +00003147 default:
3148 break;
3149 case IncRefMsg:
3150 E = IgnoreRetainMsg ? DoNothing : IncRef;
3151 break;
3152 case DecRefMsg:
3153 E = IgnoreRetainMsg ? DoNothing : DecRef;
3154 break;
Anna Zaks25612732012-08-29 23:23:43 +00003155 case DecRefMsgAndStopTrackingHard:
3156 E = IgnoreRetainMsg ? StopTracking : DecRefAndStopTrackingHard;
Jordan Roseeec15392012-07-02 19:27:43 +00003157 break;
3158 case MakeCollectable:
3159 E = C.isObjCGCEnabled() ? DecRef : DoNothing;
3160 break;
Jordy Rosebf77e512011-08-23 20:27:16 +00003161 }
3162
3163 // Handle all use-after-releases.
Jordy Rosec49ec532011-09-02 05:55:19 +00003164 if (!C.isObjCGCEnabled() && V.getKind() == RefVal::Released) {
Jordy Rosebf77e512011-08-23 20:27:16 +00003165 V = V ^ RefVal::ErrorUseAfterRelease;
3166 hasErr = V.getKind();
Anna Zaksf5788c72012-08-14 00:36:15 +00003167 return setRefBinding(state, sym, V);
Jordy Rosebf77e512011-08-23 20:27:16 +00003168 }
3169
3170 switch (E) {
3171 case DecRefMsg:
3172 case IncRefMsg:
3173 case MakeCollectable:
Anna Zaks25612732012-08-29 23:23:43 +00003174 case DecRefMsgAndStopTrackingHard:
Jordy Rosebf77e512011-08-23 20:27:16 +00003175 llvm_unreachable("DecRefMsg/IncRefMsg/MakeCollectable already converted");
Jordy Rosebf77e512011-08-23 20:27:16 +00003176
Douglas Gregoreb6e64c2015-06-19 23:17:46 +00003177 case UnretainedOutParameter:
3178 case RetainedOutParameter:
3179 llvm_unreachable("Applies to pointer-to-pointer parameters, which should "
3180 "not have ref state.");
3181
Jordy Rosebf77e512011-08-23 20:27:16 +00003182 case Dealloc:
3183 // Any use of -dealloc in GC is *bad*.
Jordy Rosec49ec532011-09-02 05:55:19 +00003184 if (C.isObjCGCEnabled()) {
Jordy Rosebf77e512011-08-23 20:27:16 +00003185 V = V ^ RefVal::ErrorDeallocGC;
3186 hasErr = V.getKind();
3187 break;
3188 }
3189
3190 switch (V.getKind()) {
3191 default:
3192 llvm_unreachable("Invalid RefVal state for an explicit dealloc.");
Jordy Rosebf77e512011-08-23 20:27:16 +00003193 case RefVal::Owned:
3194 // The object immediately transitions to the released state.
3195 V = V ^ RefVal::Released;
3196 V.clearCounts();
Anna Zaksf5788c72012-08-14 00:36:15 +00003197 return setRefBinding(state, sym, V);
Jordy Rosebf77e512011-08-23 20:27:16 +00003198 case RefVal::NotOwned:
3199 V = V ^ RefVal::ErrorDeallocNotOwned;
3200 hasErr = V.getKind();
3201 break;
3202 }
3203 break;
3204
Jordy Rosebf77e512011-08-23 20:27:16 +00003205 case MayEscape:
3206 if (V.getKind() == RefVal::Owned) {
3207 V = V ^ RefVal::NotOwned;
3208 break;
3209 }
3210
3211 // Fall-through.
3212
Jordy Rosebf77e512011-08-23 20:27:16 +00003213 case DoNothing:
3214 return state;
3215
3216 case Autorelease:
Jordy Rosec49ec532011-09-02 05:55:19 +00003217 if (C.isObjCGCEnabled())
Jordy Rosebf77e512011-08-23 20:27:16 +00003218 return state;
Jordy Rosebf77e512011-08-23 20:27:16 +00003219 // Update the autorelease counts.
Jordy Rosebf77e512011-08-23 20:27:16 +00003220 V = V.autorelease();
3221 break;
3222
3223 case StopTracking:
Anna Zaks25612732012-08-29 23:23:43 +00003224 case StopTrackingHard:
Anna Zaksf5788c72012-08-14 00:36:15 +00003225 return removeRefBinding(state, sym);
Jordy Rosebf77e512011-08-23 20:27:16 +00003226
3227 case IncRef:
3228 switch (V.getKind()) {
3229 default:
3230 llvm_unreachable("Invalid RefVal state for a retain.");
Jordy Rosebf77e512011-08-23 20:27:16 +00003231 case RefVal::Owned:
3232 case RefVal::NotOwned:
3233 V = V + 1;
3234 break;
3235 case RefVal::Released:
3236 // Non-GC cases are handled above.
Jordy Rosec49ec532011-09-02 05:55:19 +00003237 assert(C.isObjCGCEnabled());
Jordy Rosebf77e512011-08-23 20:27:16 +00003238 V = (V ^ RefVal::Owned) + 1;
3239 break;
3240 }
3241 break;
3242
Jordy Rosebf77e512011-08-23 20:27:16 +00003243 case DecRef:
Benjamin Kramer1d5d6342013-10-20 11:53:20 +00003244 case DecRefBridgedTransferred:
Anna Zaks25612732012-08-29 23:23:43 +00003245 case DecRefAndStopTrackingHard:
Jordy Rosebf77e512011-08-23 20:27:16 +00003246 switch (V.getKind()) {
3247 default:
3248 // case 'RefVal::Released' handled above.
3249 llvm_unreachable("Invalid RefVal state for a release.");
Jordy Rosebf77e512011-08-23 20:27:16 +00003250
3251 case RefVal::Owned:
3252 assert(V.getCount() > 0);
Jordan Rosecb5386c2015-02-04 19:24:52 +00003253 if (V.getCount() == 1) {
3254 if (E == DecRefBridgedTransferred ||
3255 V.getIvarAccessHistory() ==
3256 RefVal::IvarAccessHistory::AccessedDirectly)
3257 V = V ^ RefVal::NotOwned;
3258 else
3259 V = V ^ RefVal::Released;
3260 } else if (E == DecRefAndStopTrackingHard) {
Anna Zaksf5788c72012-08-14 00:36:15 +00003261 return removeRefBinding(state, sym);
Jordan Rosecb5386c2015-02-04 19:24:52 +00003262 }
Jordan Roseeec15392012-07-02 19:27:43 +00003263
Jordy Rosebf77e512011-08-23 20:27:16 +00003264 V = V - 1;
3265 break;
3266
3267 case RefVal::NotOwned:
Jordan Roseeec15392012-07-02 19:27:43 +00003268 if (V.getCount() > 0) {
Anna Zaks25612732012-08-29 23:23:43 +00003269 if (E == DecRefAndStopTrackingHard)
Anna Zaksf5788c72012-08-14 00:36:15 +00003270 return removeRefBinding(state, sym);
Jordy Rosebf77e512011-08-23 20:27:16 +00003271 V = V - 1;
Jordan Rosecb5386c2015-02-04 19:24:52 +00003272 } else if (V.getIvarAccessHistory() ==
3273 RefVal::IvarAccessHistory::AccessedDirectly) {
3274 // Assume that the instance variable was holding on the object at
3275 // +1, and we just didn't know.
3276 if (E == DecRefAndStopTrackingHard)
3277 return removeRefBinding(state, sym);
3278 V = V.releaseViaIvar() ^ RefVal::Released;
Jordan Roseeec15392012-07-02 19:27:43 +00003279 } else {
Jordy Rosebf77e512011-08-23 20:27:16 +00003280 V = V ^ RefVal::ErrorReleaseNotOwned;
3281 hasErr = V.getKind();
3282 }
3283 break;
3284
3285 case RefVal::Released:
3286 // Non-GC cases are handled above.
Jordy Rosec49ec532011-09-02 05:55:19 +00003287 assert(C.isObjCGCEnabled());
Jordy Rosebf77e512011-08-23 20:27:16 +00003288 V = V ^ RefVal::ErrorUseAfterRelease;
3289 hasErr = V.getKind();
3290 break;
3291 }
3292 break;
3293 }
Anna Zaksf5788c72012-08-14 00:36:15 +00003294 return setRefBinding(state, sym, V);
Jordy Rosebf77e512011-08-23 20:27:16 +00003295}
3296
Ted Kremenek49b1e382012-01-26 21:29:00 +00003297void RetainCountChecker::processNonLeakError(ProgramStateRef St,
Jordy Rose75e680e2011-09-02 06:44:22 +00003298 SourceRange ErrorRange,
3299 RefVal::Kind ErrorKind,
3300 SymbolRef Sym,
3301 CheckerContext &C) const {
Jordan Rose3da3f8e2015-03-30 20:18:00 +00003302 // HACK: Ignore retain-count issues on values accessed through ivars,
3303 // because of cases like this:
3304 // [_contentView retain];
3305 // [_contentView removeFromSuperview];
3306 // [self addSubview:_contentView]; // invalidates 'self'
3307 // [_contentView release];
3308 if (const RefVal *RV = getRefBinding(St, Sym))
3309 if (RV->getIvarAccessHistory() != RefVal::IvarAccessHistory::None)
3310 return;
3311
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003312 ExplodedNode *N = C.generateSink(St);
3313 if (!N)
3314 return;
3315
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003316 CFRefBug *BT;
3317 switch (ErrorKind) {
3318 default:
3319 llvm_unreachable("Unhandled error.");
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003320 case RefVal::ErrorUseAfterRelease:
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003321 if (!useAfterRelease)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00003322 useAfterRelease.reset(new UseAfterRelease(this));
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003323 BT = &*useAfterRelease;
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003324 break;
3325 case RefVal::ErrorReleaseNotOwned:
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003326 if (!releaseNotOwned)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00003327 releaseNotOwned.reset(new BadRelease(this));
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003328 BT = &*releaseNotOwned;
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003329 break;
3330 case RefVal::ErrorDeallocGC:
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003331 if (!deallocGC)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00003332 deallocGC.reset(new DeallocGC(this));
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003333 BT = &*deallocGC;
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003334 break;
3335 case RefVal::ErrorDeallocNotOwned:
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003336 if (!deallocNotOwned)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00003337 deallocNotOwned.reset(new DeallocNotOwned(this));
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003338 BT = &*deallocNotOwned;
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003339 break;
3340 }
3341
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003342 assert(BT);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003343 CFRefReport *report = new CFRefReport(*BT, C.getASTContext().getLangOpts(),
Jordy Rosec49ec532011-09-02 05:55:19 +00003344 C.isObjCGCEnabled(), SummaryLog,
3345 N, Sym);
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003346 report->addRange(ErrorRange);
Jordan Rosee10d5a72012-11-02 01:53:40 +00003347 C.emitReport(report);
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003348}
3349
Jordy Rose75e680e2011-09-02 06:44:22 +00003350//===----------------------------------------------------------------------===//
3351// Handle the return values of retain-count-related functions.
3352//===----------------------------------------------------------------------===//
3353
3354bool RetainCountChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
Jordy Rose898a1482011-08-21 21:58:18 +00003355 // Get the callee. We're only interested in simple C functions.
Ted Kremenek49b1e382012-01-26 21:29:00 +00003356 ProgramStateRef state = C.getState();
Anna Zaksc6aa5312011-12-01 05:57:37 +00003357 const FunctionDecl *FD = C.getCalleeDecl(CE);
Jordy Rose898a1482011-08-21 21:58:18 +00003358 if (!FD)
3359 return false;
3360
3361 IdentifierInfo *II = FD->getIdentifier();
3362 if (!II)
3363 return false;
3364
3365 // For now, we're only handling the functions that return aliases of their
3366 // arguments: CFRetain and CFMakeCollectable (and their families).
3367 // Eventually we should add other functions we can model entirely,
3368 // such as CFRelease, which don't invalidate their arguments or globals.
3369 if (CE->getNumArgs() != 1)
3370 return false;
3371
3372 // Get the name of the function.
3373 StringRef FName = II->getName();
3374 FName = FName.substr(FName.find_first_not_of('_'));
3375
3376 // See if it's one of the specific functions we know how to eval.
3377 bool canEval = false;
3378
David Majnemerced8bdf2015-02-25 17:36:15 +00003379 QualType ResultTy = CE->getCallReturnType(C.getASTContext());
Jordy Rose898a1482011-08-21 21:58:18 +00003380 if (ResultTy->isObjCIdType()) {
3381 // Handle: id NSMakeCollectable(CFTypeRef)
3382 canEval = II->isStr("NSMakeCollectable");
3383 } else if (ResultTy->isPointerType()) {
3384 // Handle: (CF|CG)Retain
Jordan Rose77411322013-10-07 17:16:52 +00003385 // CFAutorelease
Jordy Rose898a1482011-08-21 21:58:18 +00003386 // CFMakeCollectable
3387 // It's okay to be a little sloppy here (CGMakeCollectable doesn't exist).
3388 if (cocoa::isRefType(ResultTy, "CF", FName) ||
3389 cocoa::isRefType(ResultTy, "CG", FName)) {
Jordan Rose77411322013-10-07 17:16:52 +00003390 canEval = isRetain(FD, FName) || isAutorelease(FD, FName) ||
3391 isMakeCollectable(FD, FName);
Jordy Rose898a1482011-08-21 21:58:18 +00003392 }
3393 }
3394
3395 if (!canEval)
3396 return false;
3397
3398 // Bind the return value.
Ted Kremenek632e3b72012-01-06 22:09:28 +00003399 const LocationContext *LCtx = C.getLocationContext();
3400 SVal RetVal = state->getSVal(CE->getArg(0), LCtx);
Jordy Rose898a1482011-08-21 21:58:18 +00003401 if (RetVal.isUnknown()) {
3402 // If the receiver is unknown, conjure a return value.
3403 SValBuilder &SVB = C.getSValBuilder();
Craig Topper0dbb7832014-05-27 02:45:47 +00003404 RetVal = SVB.conjureSymbolVal(nullptr, CE, LCtx, ResultTy, C.blockCount());
Jordy Rose898a1482011-08-21 21:58:18 +00003405 }
Ted Kremenek632e3b72012-01-06 22:09:28 +00003406 state = state->BindExpr(CE, LCtx, RetVal, false);
Jordy Rose898a1482011-08-21 21:58:18 +00003407
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003408 // FIXME: This should not be necessary, but otherwise the argument seems to be
3409 // considered alive during the next statement.
3410 if (const MemRegion *ArgRegion = RetVal.getAsRegion()) {
3411 // Save the refcount status of the argument.
3412 SymbolRef Sym = RetVal.getAsLocSymbol();
Craig Topper0dbb7832014-05-27 02:45:47 +00003413 const RefVal *Binding = nullptr;
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003414 if (Sym)
Anna Zaksf5788c72012-08-14 00:36:15 +00003415 Binding = getRefBinding(state, Sym);
Jordy Rose898a1482011-08-21 21:58:18 +00003416
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003417 // Invalidate the argument region.
Anna Zaksdc154152012-12-20 00:38:25 +00003418 state = state->invalidateRegions(ArgRegion, CE, C.blockCount(), LCtx,
Anna Zaks0c34c1a2013-01-16 01:35:54 +00003419 /*CausesPointerEscape*/ false);
Jordy Rose898a1482011-08-21 21:58:18 +00003420
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003421 // Restore the refcount status of the argument.
3422 if (Binding)
Anna Zaksf5788c72012-08-14 00:36:15 +00003423 state = setRefBinding(state, Sym, *Binding);
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003424 }
3425
Anna Zaksda4c8d62011-10-26 21:06:34 +00003426 C.addTransition(state);
Jordy Rose898a1482011-08-21 21:58:18 +00003427 return true;
3428}
3429
Jordy Rose75e680e2011-09-02 06:44:22 +00003430//===----------------------------------------------------------------------===//
3431// Handle return statements.
3432//===----------------------------------------------------------------------===//
Jordy Rose298cc4d2011-08-23 19:43:16 +00003433
Jordy Rose75e680e2011-09-02 06:44:22 +00003434void RetainCountChecker::checkPreStmt(const ReturnStmt *S,
3435 CheckerContext &C) const {
Ted Kremenekef31f372012-02-25 02:09:09 +00003436
3437 // Only adjust the reference count if this is the top-level call frame,
3438 // and not the result of inlining. In the future, we should do
3439 // better checking even for inlined calls, and see if they match
3440 // with their expected semantics (e.g., the method should return a retained
3441 // object, etc.).
Anna Zaks44dc91b2012-11-03 02:54:16 +00003442 if (!C.inTopFrame())
Ted Kremenekef31f372012-02-25 02:09:09 +00003443 return;
3444
Jordy Rose298cc4d2011-08-23 19:43:16 +00003445 const Expr *RetE = S->getRetValue();
3446 if (!RetE)
3447 return;
3448
Ted Kremenek49b1e382012-01-26 21:29:00 +00003449 ProgramStateRef state = C.getState();
Ted Kremenek632e3b72012-01-06 22:09:28 +00003450 SymbolRef Sym =
3451 state->getSValAsScalarOrLoc(RetE, C.getLocationContext()).getAsLocSymbol();
Jordy Rose298cc4d2011-08-23 19:43:16 +00003452 if (!Sym)
3453 return;
3454
3455 // Get the reference count binding (if any).
Anna Zaksf5788c72012-08-14 00:36:15 +00003456 const RefVal *T = getRefBinding(state, Sym);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003457 if (!T)
3458 return;
3459
3460 // Change the reference count.
3461 RefVal X = *T;
3462
3463 switch (X.getKind()) {
3464 case RefVal::Owned: {
3465 unsigned cnt = X.getCount();
3466 assert(cnt > 0);
3467 X.setCount(cnt - 1);
3468 X = X ^ RefVal::ReturnedOwned;
3469 break;
3470 }
3471
3472 case RefVal::NotOwned: {
3473 unsigned cnt = X.getCount();
3474 if (cnt) {
3475 X.setCount(cnt - 1);
3476 X = X ^ RefVal::ReturnedOwned;
3477 }
3478 else {
3479 X = X ^ RefVal::ReturnedNotOwned;
3480 }
3481 break;
3482 }
3483
3484 default:
3485 return;
3486 }
3487
3488 // Update the binding.
Anna Zaksf5788c72012-08-14 00:36:15 +00003489 state = setRefBinding(state, Sym, X);
Anna Zaksda4c8d62011-10-26 21:06:34 +00003490 ExplodedNode *Pred = C.addTransition(state);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003491
3492 // At this point we have updated the state properly.
3493 // Everything after this is merely checking to see if the return value has
3494 // been over- or under-retained.
3495
3496 // Did we cache out?
3497 if (!Pred)
3498 return;
3499
Jordy Rose298cc4d2011-08-23 19:43:16 +00003500 // Update the autorelease counts.
Anton Yartsev6a619222014-02-17 18:25:34 +00003501 static CheckerProgramPointTag AutoreleaseTag(this, "Autorelease");
Jordan Roseff03c1d2012-12-06 18:58:18 +00003502 state = handleAutoreleaseCounts(state, Pred, &AutoreleaseTag, C, Sym, X);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003503
3504 // Did we cache out?
Jordan Roseff03c1d2012-12-06 18:58:18 +00003505 if (!state)
Jordy Rose298cc4d2011-08-23 19:43:16 +00003506 return;
3507
3508 // Get the updated binding.
Anna Zaksf5788c72012-08-14 00:36:15 +00003509 T = getRefBinding(state, Sym);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003510 assert(T);
3511 X = *T;
3512
3513 // Consult the summary of the enclosing method.
Jordy Rosec49ec532011-09-02 05:55:19 +00003514 RetainSummaryManager &Summaries = getSummaryManager(C);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003515 const Decl *CD = &Pred->getCodeDecl();
Jordan Roseeec15392012-07-02 19:27:43 +00003516 RetEffect RE = RetEffect::MakeNoRet();
Jordy Rose298cc4d2011-08-23 19:43:16 +00003517
Jordan Roseeec15392012-07-02 19:27:43 +00003518 // FIXME: What is the convention for blocks? Is there one?
Jordy Rose298cc4d2011-08-23 19:43:16 +00003519 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CD)) {
Jordy Rose8b289a22011-08-25 00:10:37 +00003520 const RetainSummary *Summ = Summaries.getMethodSummary(MD);
Jordan Roseeec15392012-07-02 19:27:43 +00003521 RE = Summ->getRetEffect();
3522 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) {
3523 if (!isa<CXXMethodDecl>(FD)) {
3524 const RetainSummary *Summ = Summaries.getFunctionSummary(FD);
3525 RE = Summ->getRetEffect();
3526 }
Jordy Rose298cc4d2011-08-23 19:43:16 +00003527 }
3528
Jordan Roseeec15392012-07-02 19:27:43 +00003529 checkReturnWithRetEffect(S, C, Pred, RE, X, Sym, state);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003530}
3531
Jordy Rose75e680e2011-09-02 06:44:22 +00003532void RetainCountChecker::checkReturnWithRetEffect(const ReturnStmt *S,
3533 CheckerContext &C,
3534 ExplodedNode *Pred,
3535 RetEffect RE, RefVal X,
3536 SymbolRef Sym,
Ted Kremenek49b1e382012-01-26 21:29:00 +00003537 ProgramStateRef state) const {
Jordan Rose3da3f8e2015-03-30 20:18:00 +00003538 // HACK: Ignore retain-count issues on values accessed through ivars,
3539 // because of cases like this:
3540 // [_contentView retain];
3541 // [_contentView removeFromSuperview];
3542 // [self addSubview:_contentView]; // invalidates 'self'
3543 // [_contentView release];
3544 if (X.getIvarAccessHistory() != RefVal::IvarAccessHistory::None)
3545 return;
3546
Jordy Rose298cc4d2011-08-23 19:43:16 +00003547 // Any leaks or other errors?
3548 if (X.isReturnedOwned() && X.getCount() == 0) {
3549 if (RE.getKind() != RetEffect::NoRet) {
3550 bool hasError = false;
Jordy Rosec49ec532011-09-02 05:55:19 +00003551 if (C.isObjCGCEnabled() && RE.getObjKind() == RetEffect::ObjC) {
Jordy Rose298cc4d2011-08-23 19:43:16 +00003552 // Things are more complicated with garbage collection. If the
3553 // returned object is suppose to be an Objective-C object, we have
3554 // a leak (as the caller expects a GC'ed object) because no
3555 // method should return ownership unless it returns a CF object.
3556 hasError = true;
3557 X = X ^ RefVal::ErrorGCLeakReturned;
3558 }
3559 else if (!RE.isOwned()) {
3560 // Either we are using GC and the returned object is a CF type
3561 // or we aren't using GC. In either case, we expect that the
3562 // enclosing method is expected to return ownership.
3563 hasError = true;
3564 X = X ^ RefVal::ErrorLeakReturned;
3565 }
3566
3567 if (hasError) {
3568 // Generate an error node.
Anna Zaksf5788c72012-08-14 00:36:15 +00003569 state = setRefBinding(state, Sym, X);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003570
Anton Yartsev6a619222014-02-17 18:25:34 +00003571 static CheckerProgramPointTag ReturnOwnLeakTag(this, "ReturnsOwnLeak");
Anna Zaksda4c8d62011-10-26 21:06:34 +00003572 ExplodedNode *N = C.addTransition(state, Pred, &ReturnOwnLeakTag);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003573 if (N) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003574 const LangOptions &LOpts = C.getASTContext().getLangOpts();
Jordy Rosec49ec532011-09-02 05:55:19 +00003575 bool GCEnabled = C.isObjCGCEnabled();
Jordy Rose298cc4d2011-08-23 19:43:16 +00003576 CFRefReport *report =
Jordy Rosec49ec532011-09-02 05:55:19 +00003577 new CFRefLeakReport(*getLeakAtReturnBug(LOpts, GCEnabled),
3578 LOpts, GCEnabled, SummaryLog,
Ted Kremenek8671acb2013-04-16 21:44:22 +00003579 N, Sym, C, IncludeAllocationLine);
3580
Jordan Rosee10d5a72012-11-02 01:53:40 +00003581 C.emitReport(report);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003582 }
3583 }
3584 }
3585 } else if (X.isReturnedNotOwned()) {
3586 if (RE.isOwned()) {
Jordan Rosecb5386c2015-02-04 19:24:52 +00003587 if (X.getIvarAccessHistory() ==
3588 RefVal::IvarAccessHistory::AccessedDirectly) {
3589 // Assume the method was trying to transfer a +1 reference from a
3590 // strong ivar to the caller.
3591 state = setRefBinding(state, Sym,
3592 X.releaseViaIvar() ^ RefVal::ReturnedOwned);
3593 } else {
3594 // Trying to return a not owned object to a caller expecting an
3595 // owned object.
3596 state = setRefBinding(state, Sym, X ^ RefVal::ErrorReturnedNotOwned);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003597
Jordan Rosecb5386c2015-02-04 19:24:52 +00003598 static CheckerProgramPointTag
3599 ReturnNotOwnedTag(this, "ReturnNotOwnedForOwned");
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003600
Jordan Rosecb5386c2015-02-04 19:24:52 +00003601 ExplodedNode *N = C.addTransition(state, Pred, &ReturnNotOwnedTag);
3602 if (N) {
3603 if (!returnNotOwnedForOwned)
3604 returnNotOwnedForOwned.reset(new ReturnedNotOwnedForOwned(this));
3605
3606 CFRefReport *report =
3607 new CFRefReport(*returnNotOwnedForOwned,
3608 C.getASTContext().getLangOpts(),
3609 C.isObjCGCEnabled(), SummaryLog, N, Sym);
3610 C.emitReport(report);
3611 }
Jordy Rose298cc4d2011-08-23 19:43:16 +00003612 }
3613 }
3614 }
3615}
3616
Jordy Rose6763e382011-08-23 20:07:14 +00003617//===----------------------------------------------------------------------===//
Jordy Rose75e680e2011-09-02 06:44:22 +00003618// Check various ways a symbol can be invalidated.
3619//===----------------------------------------------------------------------===//
3620
Anna Zaks3e0f4152011-10-06 00:43:15 +00003621void RetainCountChecker::checkBind(SVal loc, SVal val, const Stmt *S,
Jordy Rose75e680e2011-09-02 06:44:22 +00003622 CheckerContext &C) const {
3623 // Are we storing to something that causes the value to "escape"?
3624 bool escapes = true;
3625
3626 // A value escapes in three possible cases (this may change):
3627 //
3628 // (1) we are binding to something that is not a memory region.
3629 // (2) we are binding to a memregion that does not have stack storage
3630 // (3) we are binding to a memregion with stack storage that the store
3631 // does not understand.
Ted Kremenek49b1e382012-01-26 21:29:00 +00003632 ProgramStateRef state = C.getState();
Jordy Rose75e680e2011-09-02 06:44:22 +00003633
David Blaikie05785d12013-02-20 22:23:23 +00003634 if (Optional<loc::MemRegionVal> regionLoc = loc.getAs<loc::MemRegionVal>()) {
Jordy Rose75e680e2011-09-02 06:44:22 +00003635 escapes = !regionLoc->getRegion()->hasStackStorage();
3636
3637 if (!escapes) {
3638 // To test (3), generate a new state with the binding added. If it is
3639 // the same state, then it escapes (since the store cannot represent
3640 // the binding).
Anna Zaks70de7722012-05-02 00:15:40 +00003641 // Do this only if we know that the store is not supposed to generate the
3642 // same state.
3643 SVal StoredVal = state->getSVal(regionLoc->getRegion());
3644 if (StoredVal != val)
3645 escapes = (state == (state->bindLoc(*regionLoc, val)));
Jordy Rose75e680e2011-09-02 06:44:22 +00003646 }
Ted Kremeneke9a5bcf2012-03-27 01:12:45 +00003647 if (!escapes) {
3648 // Case 4: We do not currently model what happens when a symbol is
3649 // assigned to a struct field, so be conservative here and let the symbol
3650 // go. TODO: This could definitely be improved upon.
3651 escapes = !isa<VarRegion>(regionLoc->getRegion());
3652 }
Jordy Rose75e680e2011-09-02 06:44:22 +00003653 }
3654
Anna Zaksfb050942013-09-17 00:53:28 +00003655 // If we are storing the value into an auto function scope variable annotated
3656 // with (__attribute__((cleanup))), stop tracking the value to avoid leak
3657 // false positives.
3658 if (const VarRegion *LVR = dyn_cast_or_null<VarRegion>(loc.getAsRegion())) {
3659 const VarDecl *VD = LVR->getDecl();
Aaron Ballman9ead1242013-12-19 02:39:40 +00003660 if (VD->hasAttr<CleanupAttr>()) {
Anna Zaksfb050942013-09-17 00:53:28 +00003661 escapes = true;
3662 }
3663 }
3664
Jordy Rose75e680e2011-09-02 06:44:22 +00003665 // If our store can represent the binding and we aren't storing to something
3666 // that doesn't have local storage then just return and have the simulation
3667 // state continue as is.
3668 if (!escapes)
3669 return;
3670
3671 // Otherwise, find all symbols referenced by 'val' that we are tracking
3672 // and stop tracking them.
3673 state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
Anna Zaksda4c8d62011-10-26 21:06:34 +00003674 C.addTransition(state);
Jordy Rose75e680e2011-09-02 06:44:22 +00003675}
3676
Ted Kremenek49b1e382012-01-26 21:29:00 +00003677ProgramStateRef RetainCountChecker::evalAssume(ProgramStateRef state,
Jordy Rose75e680e2011-09-02 06:44:22 +00003678 SVal Cond,
3679 bool Assumption) const {
3680
3681 // FIXME: We may add to the interface of evalAssume the list of symbols
3682 // whose assumptions have changed. For now we just iterate through the
3683 // bindings and check if any of the tracked symbols are NULL. This isn't
3684 // too bad since the number of symbols we will track in practice are
3685 // probably small and evalAssume is only called at branches and a few
3686 // other places.
Jordan Rose0c153cb2012-11-02 01:54:06 +00003687 RefBindingsTy B = state->get<RefBindings>();
Jordy Rose75e680e2011-09-02 06:44:22 +00003688
3689 if (B.isEmpty())
3690 return state;
3691
3692 bool changed = false;
Jordan Rose0c153cb2012-11-02 01:54:06 +00003693 RefBindingsTy::Factory &RefBFactory = state->get_context<RefBindings>();
Jordy Rose75e680e2011-09-02 06:44:22 +00003694
Jordan Rose0c153cb2012-11-02 01:54:06 +00003695 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Ted Kremenek244e1d72012-09-07 22:31:01 +00003696 // Check if the symbol is null stop tracking the symbol.
Jordan Rose14fe9f32012-11-01 00:18:27 +00003697 ConstraintManager &CMgr = state->getConstraintManager();
3698 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
3699 if (AllocFailed.isConstrainedTrue()) {
Jordy Rose75e680e2011-09-02 06:44:22 +00003700 changed = true;
3701 B = RefBFactory.remove(B, I.getKey());
3702 }
3703 }
3704
3705 if (changed)
3706 state = state->set<RefBindings>(B);
3707
3708 return state;
3709}
3710
Ted Kremenek49b1e382012-01-26 21:29:00 +00003711ProgramStateRef
3712RetainCountChecker::checkRegionChanges(ProgramStateRef state,
Anna Zaksdc154152012-12-20 00:38:25 +00003713 const InvalidatedSymbols *invalidated,
Jordy Rose75e680e2011-09-02 06:44:22 +00003714 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks3d348342012-02-14 21:55:24 +00003715 ArrayRef<const MemRegion *> Regions,
Jordan Rose742920c2012-07-02 19:27:35 +00003716 const CallEvent *Call) const {
Jordy Rose75e680e2011-09-02 06:44:22 +00003717 if (!invalidated)
3718 return state;
3719
3720 llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
3721 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
3722 E = ExplicitRegions.end(); I != E; ++I) {
3723 if (const SymbolicRegion *SR = (*I)->StripCasts()->getAs<SymbolicRegion>())
3724 WhitelistedSymbols.insert(SR->getSymbol());
3725 }
3726
Anna Zaksdc154152012-12-20 00:38:25 +00003727 for (InvalidatedSymbols::const_iterator I=invalidated->begin(),
Jordy Rose75e680e2011-09-02 06:44:22 +00003728 E = invalidated->end(); I!=E; ++I) {
3729 SymbolRef sym = *I;
3730 if (WhitelistedSymbols.count(sym))
3731 continue;
3732 // Remove any existing reference-count binding.
Anna Zaksf5788c72012-08-14 00:36:15 +00003733 state = removeRefBinding(state, sym);
Jordy Rose75e680e2011-09-02 06:44:22 +00003734 }
3735 return state;
3736}
3737
3738//===----------------------------------------------------------------------===//
Jordy Rose6763e382011-08-23 20:07:14 +00003739// Handle dead symbols and end-of-path.
3740//===----------------------------------------------------------------------===//
3741
Jordan Roseff03c1d2012-12-06 18:58:18 +00003742ProgramStateRef
3743RetainCountChecker::handleAutoreleaseCounts(ProgramStateRef state,
Anna Zaks58734db2011-10-25 19:57:11 +00003744 ExplodedNode *Pred,
Jordan Rose9f61f8a2012-08-18 00:30:16 +00003745 const ProgramPointTag *Tag,
Anna Zaks58734db2011-10-25 19:57:11 +00003746 CheckerContext &Ctx,
Jordy Rose75e680e2011-09-02 06:44:22 +00003747 SymbolRef Sym, RefVal V) const {
Jordy Rose6763e382011-08-23 20:07:14 +00003748 unsigned ACnt = V.getAutoreleaseCount();
3749
3750 // No autorelease counts? Nothing to be done.
3751 if (!ACnt)
Jordan Roseff03c1d2012-12-06 18:58:18 +00003752 return state;
Jordy Rose6763e382011-08-23 20:07:14 +00003753
Anna Zaks58734db2011-10-25 19:57:11 +00003754 assert(!Ctx.isObjCGCEnabled() && "Autorelease counts in GC mode?");
Jordy Rose6763e382011-08-23 20:07:14 +00003755 unsigned Cnt = V.getCount();
3756
3757 // FIXME: Handle sending 'autorelease' to already released object.
3758
3759 if (V.getKind() == RefVal::ReturnedOwned)
3760 ++Cnt;
3761
Jordan Rosecb5386c2015-02-04 19:24:52 +00003762 // If we would over-release here, but we know the value came from an ivar,
3763 // assume it was a strong ivar that's just been relinquished.
3764 if (ACnt > Cnt &&
3765 V.getIvarAccessHistory() == RefVal::IvarAccessHistory::AccessedDirectly) {
3766 V = V.releaseViaIvar();
3767 --ACnt;
3768 }
3769
Jordy Rose6763e382011-08-23 20:07:14 +00003770 if (ACnt <= Cnt) {
3771 if (ACnt == Cnt) {
3772 V.clearCounts();
3773 if (V.getKind() == RefVal::ReturnedOwned)
3774 V = V ^ RefVal::ReturnedNotOwned;
3775 else
3776 V = V ^ RefVal::NotOwned;
3777 } else {
Anna Zaksa8bcc652013-01-31 22:36:17 +00003778 V.setCount(V.getCount() - ACnt);
Jordy Rose6763e382011-08-23 20:07:14 +00003779 V.setAutoreleaseCount(0);
3780 }
Jordan Roseff03c1d2012-12-06 18:58:18 +00003781 return setRefBinding(state, Sym, V);
Jordy Rose6763e382011-08-23 20:07:14 +00003782 }
3783
Jordan Rose3da3f8e2015-03-30 20:18:00 +00003784 // HACK: Ignore retain-count issues on values accessed through ivars,
3785 // because of cases like this:
3786 // [_contentView retain];
3787 // [_contentView removeFromSuperview];
3788 // [self addSubview:_contentView]; // invalidates 'self'
3789 // [_contentView release];
3790 if (V.getIvarAccessHistory() != RefVal::IvarAccessHistory::None)
3791 return state;
3792
Jordy Rose6763e382011-08-23 20:07:14 +00003793 // Woah! More autorelease counts then retain counts left.
3794 // Emit hard error.
3795 V = V ^ RefVal::ErrorOverAutorelease;
Anna Zaksf5788c72012-08-14 00:36:15 +00003796 state = setRefBinding(state, Sym, V);
Jordy Rose6763e382011-08-23 20:07:14 +00003797
Jordan Rose4b4613c2012-08-20 18:43:42 +00003798 ExplodedNode *N = Ctx.generateSink(state, Pred, Tag);
Jordan Rose9f61f8a2012-08-18 00:30:16 +00003799 if (N) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003800 SmallString<128> sbuf;
Jordy Rose6763e382011-08-23 20:07:14 +00003801 llvm::raw_svector_ostream os(sbuf);
Jordan Rose7467f062013-04-23 01:42:25 +00003802 os << "Object was autoreleased ";
Jordy Rose6763e382011-08-23 20:07:14 +00003803 if (V.getAutoreleaseCount() > 1)
Jordan Rose7467f062013-04-23 01:42:25 +00003804 os << V.getAutoreleaseCount() << " times but the object ";
3805 else
3806 os << "but ";
3807 os << "has a +" << V.getCount() << " retain count";
Jordy Rose6763e382011-08-23 20:07:14 +00003808
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003809 if (!overAutorelease)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00003810 overAutorelease.reset(new OverAutorelease(this));
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003811
David Blaikiebbafb8a2012-03-11 07:00:24 +00003812 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
Jordy Rose6763e382011-08-23 20:07:14 +00003813 CFRefReport *report =
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003814 new CFRefReport(*overAutorelease, LOpts, /* GCEnabled = */ false,
3815 SummaryLog, N, Sym, os.str());
Jordan Rosee10d5a72012-11-02 01:53:40 +00003816 Ctx.emitReport(report);
Jordy Rose6763e382011-08-23 20:07:14 +00003817 }
3818
Craig Topper0dbb7832014-05-27 02:45:47 +00003819 return nullptr;
Jordy Rose6763e382011-08-23 20:07:14 +00003820}
Jordy Rose78612762011-08-23 19:01:07 +00003821
Ted Kremenek49b1e382012-01-26 21:29:00 +00003822ProgramStateRef
3823RetainCountChecker::handleSymbolDeath(ProgramStateRef state,
Jordy Rose75e680e2011-09-02 06:44:22 +00003824 SymbolRef sid, RefVal V,
Jordy Rose78612762011-08-23 19:01:07 +00003825 SmallVectorImpl<SymbolRef> &Leaked) const {
Jordan Rose3da3f8e2015-03-30 20:18:00 +00003826 bool hasLeak;
3827
3828 // HACK: Ignore retain-count issues on values accessed through ivars,
3829 // because of cases like this:
3830 // [_contentView retain];
3831 // [_contentView removeFromSuperview];
3832 // [self addSubview:_contentView]; // invalidates 'self'
3833 // [_contentView release];
3834 if (V.getIvarAccessHistory() != RefVal::IvarAccessHistory::None)
3835 hasLeak = false;
3836 else if (V.isOwned())
Jordy Rose78612762011-08-23 19:01:07 +00003837 hasLeak = true;
3838 else if (V.isNotOwned() || V.isReturnedOwned())
3839 hasLeak = (V.getCount() > 0);
Jordan Rose3da3f8e2015-03-30 20:18:00 +00003840 else
3841 hasLeak = false;
Jordy Rose78612762011-08-23 19:01:07 +00003842
3843 if (!hasLeak)
Anna Zaksf5788c72012-08-14 00:36:15 +00003844 return removeRefBinding(state, sid);
Jordy Rose78612762011-08-23 19:01:07 +00003845
3846 Leaked.push_back(sid);
Anna Zaksf5788c72012-08-14 00:36:15 +00003847 return setRefBinding(state, sid, V ^ RefVal::ErrorLeak);
Jordy Rose78612762011-08-23 19:01:07 +00003848}
3849
3850ExplodedNode *
Ted Kremenek49b1e382012-01-26 21:29:00 +00003851RetainCountChecker::processLeaks(ProgramStateRef state,
Jordy Rose75e680e2011-09-02 06:44:22 +00003852 SmallVectorImpl<SymbolRef> &Leaked,
Anna Zaks58734db2011-10-25 19:57:11 +00003853 CheckerContext &Ctx,
3854 ExplodedNode *Pred) const {
Jordy Rose78612762011-08-23 19:01:07 +00003855 // Generate an intermediate node representing the leak point.
Jordan Rose9f61f8a2012-08-18 00:30:16 +00003856 ExplodedNode *N = Ctx.addTransition(state, Pred);
Jordy Rose78612762011-08-23 19:01:07 +00003857
3858 if (N) {
3859 for (SmallVectorImpl<SymbolRef>::iterator
3860 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3861
David Blaikiebbafb8a2012-03-11 07:00:24 +00003862 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
Anna Zaks58734db2011-10-25 19:57:11 +00003863 bool GCEnabled = Ctx.isObjCGCEnabled();
Jordy Rosec49ec532011-09-02 05:55:19 +00003864 CFRefBug *BT = Pred ? getLeakWithinFunctionBug(LOpts, GCEnabled)
3865 : getLeakAtReturnBug(LOpts, GCEnabled);
Jordy Rose78612762011-08-23 19:01:07 +00003866 assert(BT && "BugType not initialized.");
Jordy Rose184bd142011-08-24 22:39:09 +00003867
Jordy Rosec49ec532011-09-02 05:55:19 +00003868 CFRefLeakReport *report = new CFRefLeakReport(*BT, LOpts, GCEnabled,
Ted Kremenek8671acb2013-04-16 21:44:22 +00003869 SummaryLog, N, *I, Ctx,
3870 IncludeAllocationLine);
Jordan Rosee10d5a72012-11-02 01:53:40 +00003871 Ctx.emitReport(report);
Jordy Rose78612762011-08-23 19:01:07 +00003872 }
3873 }
3874
3875 return N;
3876}
3877
Anna Zaks3fdcc0b2013-01-03 00:25:29 +00003878void RetainCountChecker::checkEndFunction(CheckerContext &Ctx) const {
Ted Kremenek49b1e382012-01-26 21:29:00 +00003879 ProgramStateRef state = Ctx.getState();
Jordan Rose0c153cb2012-11-02 01:54:06 +00003880 RefBindingsTy B = state->get<RefBindings>();
Anna Zaks3eae3342011-10-25 19:56:48 +00003881 ExplodedNode *Pred = Ctx.getPredecessor();
Jordy Rose78612762011-08-23 19:01:07 +00003882
Jordan Rose7699e4a2013-08-01 22:16:36 +00003883 // Don't process anything within synthesized bodies.
3884 const LocationContext *LCtx = Pred->getLocationContext();
3885 if (LCtx->getAnalysisDeclContext()->isBodyAutosynthesized()) {
3886 assert(LCtx->getParent());
3887 return;
3888 }
3889
Jordan Rose0c153cb2012-11-02 01:54:06 +00003890 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Craig Topper0dbb7832014-05-27 02:45:47 +00003891 state = handleAutoreleaseCounts(state, Pred, /*Tag=*/nullptr, Ctx,
Jordan Roseff03c1d2012-12-06 18:58:18 +00003892 I->first, I->second);
Jordy Rose6763e382011-08-23 20:07:14 +00003893 if (!state)
Jordy Rose78612762011-08-23 19:01:07 +00003894 return;
3895 }
3896
Ted Kremeneka2bbac32012-02-07 00:24:33 +00003897 // If the current LocationContext has a parent, don't check for leaks.
3898 // We will do that later.
Anna Zaksf5788c72012-08-14 00:36:15 +00003899 // FIXME: we should instead check for imbalances of the retain/releases,
Ted Kremeneka2bbac32012-02-07 00:24:33 +00003900 // and suggest annotations.
Jordan Rose7699e4a2013-08-01 22:16:36 +00003901 if (LCtx->getParent())
Ted Kremeneka2bbac32012-02-07 00:24:33 +00003902 return;
3903
Jordy Rose78612762011-08-23 19:01:07 +00003904 B = state->get<RefBindings>();
3905 SmallVector<SymbolRef, 10> Leaked;
3906
Jordan Rose0c153cb2012-11-02 01:54:06 +00003907 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I)
Jordy Rose6763e382011-08-23 20:07:14 +00003908 state = handleSymbolDeath(state, I->first, I->second, Leaked);
Jordy Rose78612762011-08-23 19:01:07 +00003909
Jordan Rose9f61f8a2012-08-18 00:30:16 +00003910 processLeaks(state, Leaked, Ctx, Pred);
Jordy Rose78612762011-08-23 19:01:07 +00003911}
3912
3913const ProgramPointTag *
Jordy Rose75e680e2011-09-02 06:44:22 +00003914RetainCountChecker::getDeadSymbolTag(SymbolRef sym) const {
Anton Yartsev6a619222014-02-17 18:25:34 +00003915 const CheckerProgramPointTag *&tag = DeadSymbolTags[sym];
Jordy Rose78612762011-08-23 19:01:07 +00003916 if (!tag) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003917 SmallString<64> buf;
Jordy Rose78612762011-08-23 19:01:07 +00003918 llvm::raw_svector_ostream out(buf);
Anton Yartsev6a619222014-02-17 18:25:34 +00003919 out << "Dead Symbol : ";
Anna Zaks22351652011-12-05 18:58:11 +00003920 sym->dumpToStream(out);
Anton Yartsev6a619222014-02-17 18:25:34 +00003921 tag = new CheckerProgramPointTag(this, out.str());
Jordy Rose78612762011-08-23 19:01:07 +00003922 }
3923 return tag;
3924}
3925
Jordy Rose75e680e2011-09-02 06:44:22 +00003926void RetainCountChecker::checkDeadSymbols(SymbolReaper &SymReaper,
3927 CheckerContext &C) const {
Jordy Rose78612762011-08-23 19:01:07 +00003928 ExplodedNode *Pred = C.getPredecessor();
3929
Ted Kremenek49b1e382012-01-26 21:29:00 +00003930 ProgramStateRef state = C.getState();
Jordan Rose0c153cb2012-11-02 01:54:06 +00003931 RefBindingsTy B = state->get<RefBindings>();
Jordan Roseff03c1d2012-12-06 18:58:18 +00003932 SmallVector<SymbolRef, 10> Leaked;
Jordy Rose78612762011-08-23 19:01:07 +00003933
3934 // Update counts from autorelease pools
3935 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3936 E = SymReaper.dead_end(); I != E; ++I) {
3937 SymbolRef Sym = *I;
3938 if (const RefVal *T = B.lookup(Sym)){
3939 // Use the symbol as the tag.
3940 // FIXME: This might not be as unique as we would like.
Jordan Rose9f61f8a2012-08-18 00:30:16 +00003941 const ProgramPointTag *Tag = getDeadSymbolTag(Sym);
Jordan Roseff03c1d2012-12-06 18:58:18 +00003942 state = handleAutoreleaseCounts(state, Pred, Tag, C, Sym, *T);
Jordy Rose6763e382011-08-23 20:07:14 +00003943 if (!state)
Jordy Rose78612762011-08-23 19:01:07 +00003944 return;
Jordan Roseff03c1d2012-12-06 18:58:18 +00003945
3946 // Fetch the new reference count from the state, and use it to handle
3947 // this symbol.
3948 state = handleSymbolDeath(state, *I, *getRefBinding(state, Sym), Leaked);
Jordy Rose78612762011-08-23 19:01:07 +00003949 }
3950 }
3951
Jordan Roseff03c1d2012-12-06 18:58:18 +00003952 if (Leaked.empty()) {
3953 C.addTransition(state);
3954 return;
Jordy Rose78612762011-08-23 19:01:07 +00003955 }
3956
Jordan Rose9f61f8a2012-08-18 00:30:16 +00003957 Pred = processLeaks(state, Leaked, C, Pred);
Jordy Rose78612762011-08-23 19:01:07 +00003958
3959 // Did we cache out?
3960 if (!Pred)
3961 return;
3962
3963 // Now generate a new node that nukes the old bindings.
Jordan Roseff03c1d2012-12-06 18:58:18 +00003964 // The only bindings left at this point are the leaked symbols.
Jordan Rose0c153cb2012-11-02 01:54:06 +00003965 RefBindingsTy::Factory &F = state->get_context<RefBindings>();
Jordan Roseff03c1d2012-12-06 18:58:18 +00003966 B = state->get<RefBindings>();
Jordy Rose78612762011-08-23 19:01:07 +00003967
Jordan Roseff03c1d2012-12-06 18:58:18 +00003968 for (SmallVectorImpl<SymbolRef>::iterator I = Leaked.begin(),
3969 E = Leaked.end();
3970 I != E; ++I)
Jordy Rose78612762011-08-23 19:01:07 +00003971 B = F.remove(B, *I);
3972
3973 state = state->set<RefBindings>(B);
Anna Zaksda4c8d62011-10-26 21:06:34 +00003974 C.addTransition(state, Pred);
Jordy Rose78612762011-08-23 19:01:07 +00003975}
3976
Ted Kremenek49b1e382012-01-26 21:29:00 +00003977void RetainCountChecker::printState(raw_ostream &Out, ProgramStateRef State,
Jordy Rose75e680e2011-09-02 06:44:22 +00003978 const char *NL, const char *Sep) const {
Jordy Rose58a20d32011-08-28 19:11:56 +00003979
Jordan Rose0c153cb2012-11-02 01:54:06 +00003980 RefBindingsTy B = State->get<RefBindings>();
Jordy Rose58a20d32011-08-28 19:11:56 +00003981
Ted Kremenekdb70b522013-03-28 18:43:18 +00003982 if (B.isEmpty())
3983 return;
3984
3985 Out << Sep << NL;
Jordy Rose58a20d32011-08-28 19:11:56 +00003986
Jordan Rose0c153cb2012-11-02 01:54:06 +00003987 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Jordy Rose58a20d32011-08-28 19:11:56 +00003988 Out << I->first << " : ";
3989 I->second.print(Out);
3990 Out << NL;
3991 }
Jordy Rose58a20d32011-08-28 19:11:56 +00003992}
3993
3994//===----------------------------------------------------------------------===//
Jordy Rose75e680e2011-09-02 06:44:22 +00003995// Checker registration.
Ted Kremenek819e9b62008-03-11 06:39:11 +00003996//===----------------------------------------------------------------------===//
3997
Jordy Rosec49ec532011-09-02 05:55:19 +00003998void ento::registerRetainCountChecker(CheckerManager &Mgr) {
Ted Kremenek8671acb2013-04-16 21:44:22 +00003999 Mgr.registerChecker<RetainCountChecker>(Mgr.getAnalyzerOptions());
Jordy Rosec49ec532011-09-02 05:55:19 +00004000}
4001
Ted Kremenek71c080f2013-08-14 23:41:49 +00004002//===----------------------------------------------------------------------===//
4003// Implementation of the CallEffects API.
4004//===----------------------------------------------------------------------===//
4005
4006namespace clang { namespace ento { namespace objc_retain {
4007
4008// This is a bit gross, but it allows us to populate CallEffects without
4009// creating a bunch of accessors. This kind is very localized, so the
4010// damage of this macro is limited.
4011#define createCallEffect(D, KIND)\
4012 ASTContext &Ctx = D->getASTContext();\
4013 LangOptions L = Ctx.getLangOpts();\
4014 RetainSummaryManager M(Ctx, L.GCOnly, L.ObjCAutoRefCount);\
4015 const RetainSummary *S = M.get ## KIND ## Summary(D);\
4016 CallEffects CE(S->getRetEffect());\
4017 CE.Receiver = S->getReceiverEffect();\
Ted Kremeneke19529b2013-08-16 23:14:22 +00004018 unsigned N = D->param_size();\
Ted Kremenek71c080f2013-08-14 23:41:49 +00004019 for (unsigned i = 0; i < N; ++i) {\
4020 CE.Args.push_back(S->getArg(i));\
4021 }
4022
4023CallEffects CallEffects::getEffect(const ObjCMethodDecl *MD) {
4024 createCallEffect(MD, Method);
4025 return CE;
4026}
4027
4028CallEffects CallEffects::getEffect(const FunctionDecl *FD) {
4029 createCallEffect(FD, Function);
4030 return CE;
4031}
4032
4033#undef createCallEffect
4034
4035}}}