blob: ac74ecd0f493f373b62957f097a1f256930c2ced [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:
909 case MayEscape:
Jordan Roseeec15392012-07-02 19:27:43 +0000910 case StopTracking:
Anna Zaks25612732012-08-29 23:23:43 +0000911 case StopTrackingHard:
912 return StopTrackingHard;
Jordan Roseeec15392012-07-02 19:27:43 +0000913 case DecRef:
Anna Zaks25612732012-08-29 23:23:43 +0000914 case DecRefAndStopTrackingHard:
915 return DecRefAndStopTrackingHard;
Jordan Roseeec15392012-07-02 19:27:43 +0000916 case DecRefMsg:
Anna Zaks25612732012-08-29 23:23:43 +0000917 case DecRefMsgAndStopTrackingHard:
918 return DecRefMsgAndStopTrackingHard;
Jordan Roseeec15392012-07-02 19:27:43 +0000919 case Dealloc:
920 return Dealloc;
921 }
922
923 llvm_unreachable("Unknown ArgEffect kind");
924}
925
926void RetainSummaryManager::updateSummaryForCall(const RetainSummary *&S,
927 const CallEvent &Call) {
928 if (Call.hasNonZeroCallbackArg()) {
Anna Zaks25612732012-08-29 23:23:43 +0000929 ArgEffect RecEffect =
930 getStopTrackingHardEquivalent(S->getReceiverEffect());
931 ArgEffect DefEffect =
932 getStopTrackingHardEquivalent(S->getDefaultArgEffect());
Jordan Roseeec15392012-07-02 19:27:43 +0000933
934 ArgEffects CustomArgEffects = S->getArgEffects();
935 for (ArgEffects::iterator I = CustomArgEffects.begin(),
936 E = CustomArgEffects.end();
937 I != E; ++I) {
Anna Zaks25612732012-08-29 23:23:43 +0000938 ArgEffect Translated = getStopTrackingHardEquivalent(I->second);
Jordan Roseeec15392012-07-02 19:27:43 +0000939 if (Translated != DefEffect)
940 ScratchArgs = AF.add(ScratchArgs, I->first, Translated);
941 }
942
Anna Zaks25612732012-08-29 23:23:43 +0000943 RetEffect RE = RetEffect::MakeNoRetHard();
Jordan Roseeec15392012-07-02 19:27:43 +0000944
945 // Special cases where the callback argument CANNOT free the return value.
946 // This can generally only happen if we know that the callback will only be
947 // called when the return value is already being deallocated.
Jordan Rose2a833ca2014-01-15 17:25:15 +0000948 if (const SimpleFunctionCall *FC = dyn_cast<SimpleFunctionCall>(&Call)) {
Jordan Roseccf192e2012-09-01 17:39:13 +0000949 if (IdentifierInfo *Name = FC->getDecl()->getIdentifier()) {
950 // When the CGBitmapContext is deallocated, the callback here will free
951 // the associated data buffer.
Jordan Rosed65f1c82012-08-31 18:19:18 +0000952 if (Name->isStr("CGBitmapContextCreateWithData"))
953 RE = S->getRetEffect();
Jordan Roseccf192e2012-09-01 17:39:13 +0000954 }
Jordan Roseeec15392012-07-02 19:27:43 +0000955 }
956
957 S = getPersistentSummary(RE, RecEffect, DefEffect);
958 }
Anna Zaks3d5d3d32012-08-24 00:06:12 +0000959
960 // Special case '[super init];' and '[self init];'
961 //
962 // Even though calling '[super init]' without assigning the result to self
963 // and checking if the parent returns 'nil' is a bad pattern, it is common.
964 // Additionally, our Self Init checker already warns about it. To avoid
965 // overwhelming the user with messages from both checkers, we model the case
966 // of '[super init]' in cases when it is not consumed by another expression
967 // as if the call preserves the value of 'self'; essentially, assuming it can
968 // never fail and return 'nil'.
969 // Note, we don't want to just stop tracking the value since we want the
970 // RetainCount checker to report leaks and use-after-free if SelfInit checker
971 // is turned off.
972 if (const ObjCMethodCall *MC = dyn_cast<ObjCMethodCall>(&Call)) {
973 if (MC->getMethodFamily() == OMF_init && MC->isReceiverSelfOrSuper()) {
974
975 // Check if the message is not consumed, we know it will not be used in
976 // an assignment, ex: "self = [super init]".
977 const Expr *ME = MC->getOriginExpr();
978 const LocationContext *LCtx = MC->getLocationContext();
979 ParentMap &PM = LCtx->getAnalysisDeclContext()->getParentMap();
980 if (!PM.isConsumedExpr(ME)) {
981 RetainSummaryTemplate ModifiableSummaryTemplate(S, *this);
982 ModifiableSummaryTemplate->setReceiverEffect(DoNothing);
983 ModifiableSummaryTemplate->setRetEffect(RetEffect::MakeNoRet());
984 }
985 }
986
987 }
Jordan Roseeec15392012-07-02 19:27:43 +0000988}
989
Anna Zaksf4c5ea52012-05-04 22:18:39 +0000990const RetainSummary *
Jordan Roseeec15392012-07-02 19:27:43 +0000991RetainSummaryManager::getSummary(const CallEvent &Call,
992 ProgramStateRef State) {
993 const RetainSummary *Summ;
994 switch (Call.getKind()) {
995 case CE_Function:
Jordan Rose2a833ca2014-01-15 17:25:15 +0000996 Summ = getFunctionSummary(cast<SimpleFunctionCall>(Call).getDecl());
Jordan Roseeec15392012-07-02 19:27:43 +0000997 break;
998 case CE_CXXMember:
Jordan Rose017591a2012-07-03 22:55:57 +0000999 case CE_CXXMemberOperator:
Jordan Roseeec15392012-07-02 19:27:43 +00001000 case CE_Block:
1001 case CE_CXXConstructor:
Jordan Rose4ee71b82012-07-10 22:07:47 +00001002 case CE_CXXDestructor:
Jordan Rosea4ee0642012-07-02 22:21:47 +00001003 case CE_CXXAllocator:
Jordan Roseeec15392012-07-02 19:27:43 +00001004 // FIXME: These calls are currently unsupported.
1005 return getPersistentStopSummary();
Jordan Rose627b0462012-07-18 21:59:51 +00001006 case CE_ObjCMessage: {
Jordan Rose6bad4902012-07-02 19:27:56 +00001007 const ObjCMethodCall &Msg = cast<ObjCMethodCall>(Call);
Jordan Roseeec15392012-07-02 19:27:43 +00001008 if (Msg.isInstanceMessage())
1009 Summ = getInstanceMethodSummary(Msg, State);
1010 else
1011 Summ = getClassMethodSummary(Msg);
1012 break;
1013 }
1014 }
1015
1016 updateSummaryForCall(Summ, Call);
1017
1018 assert(Summ && "Unknown call type?");
1019 return Summ;
1020}
1021
1022const RetainSummary *
1023RetainSummaryManager::getFunctionSummary(const FunctionDecl *FD) {
1024 // If we don't know what function we're calling, use our default summary.
1025 if (!FD)
1026 return getDefaultSummary();
1027
Ted Kremenekf7141592008-04-24 17:22:33 +00001028 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremenek00daccd2008-05-05 22:11:16 +00001029 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremenek00daccd2008-05-05 22:11:16 +00001030 if (I != FuncSummaries.end())
Ted Kremenekf7141592008-04-24 17:22:33 +00001031 return I->second;
1032
Ted Kremenekdf76e6d2009-05-04 15:34:07 +00001033 // No summary? Generate one.
Craig Topper0dbb7832014-05-27 02:45:47 +00001034 const RetainSummary *S = nullptr;
Jordan Rose1c715602012-08-06 21:28:02 +00001035 bool AllowAnnotations = true;
Mike Stump11289f42009-09-09 15:08:12 +00001036
Ted Kremenekfa89e2f2008-07-15 16:50:12 +00001037 do {
Ted Kremenek7e904222009-01-12 21:45:02 +00001038 // We generate "stop" summaries for implicitly defined functions.
1039 if (FD->isImplicit()) {
1040 S = getPersistentStopSummary();
1041 break;
Ted Kremenekfa89e2f2008-07-15 16:50:12 +00001042 }
Mike Stump11289f42009-09-09 15:08:12 +00001043
John McCall9dd450b2009-09-21 23:43:11 +00001044 // [PR 3337] Use 'getAs<FunctionType>' to strip away any typedefs on the
Ted Kremenek86afde32009-01-16 18:40:33 +00001045 // function's type.
John McCall9dd450b2009-09-21 23:43:11 +00001046 const FunctionType* FT = FD->getType()->getAs<FunctionType>();
Ted Kremenek9bcc2642009-12-16 06:06:43 +00001047 const IdentifierInfo *II = FD->getIdentifier();
1048 if (!II)
1049 break;
Benjamin Kramereaabbd82010-02-08 18:38:55 +00001050
1051 StringRef FName = II->getName();
Mike Stump11289f42009-09-09 15:08:12 +00001052
Ted Kremenek5f968932009-03-05 22:11:14 +00001053 // Strip away preceding '_'. Doing this here will effect all the checks
1054 // down below.
Benjamin Kramereaabbd82010-02-08 18:38:55 +00001055 FName = FName.substr(FName.find_first_not_of('_'));
Mike Stump11289f42009-09-09 15:08:12 +00001056
Ted Kremenek7e904222009-01-12 21:45:02 +00001057 // Inspect the result type.
Alp Toker314cc812014-01-25 16:55:45 +00001058 QualType RetTy = FT->getReturnType();
Mike Stump11289f42009-09-09 15:08:12 +00001059
Ted Kremenek7e904222009-01-12 21:45:02 +00001060 // FIXME: This should all be refactored into a chain of "summary lookup"
1061 // filters.
Ted Kremenekb4ec3fc2009-10-14 00:27:24 +00001062 assert(ScratchArgs.isEmpty());
Ted Kremenek3092e9c2009-06-15 20:36:07 +00001063
Ted Kremenek01d152f2012-04-26 04:32:23 +00001064 if (FName == "pthread_create" || FName == "pthread_setspecific") {
1065 // Part of: <rdar://problem/7299394> and <rdar://problem/11282706>.
1066 // This will be addressed better with IPA.
Benjamin Kramereaabbd82010-02-08 18:38:55 +00001067 S = getPersistentStopSummary();
1068 } else if (FName == "NSMakeCollectable") {
1069 // Handle: id NSMakeCollectable(CFTypeRef)
1070 S = (RetTy->isObjCIdType())
1071 ? getUnarySummary(FT, cfmakecollectable)
1072 : getPersistentStopSummary();
Jordan Rose1c715602012-08-06 21:28:02 +00001073 // The headers on OS X 10.8 use cf_consumed/ns_returns_retained,
1074 // but we can fully model NSMakeCollectable ourselves.
1075 AllowAnnotations = false;
Ted Kremenekc008db92012-09-06 23:47:02 +00001076 } else if (FName == "CFPlugInInstanceCreate") {
1077 S = getPersistentSummary(RetEffect::MakeNoRet());
Benjamin Kramereaabbd82010-02-08 18:38:55 +00001078 } else if (FName == "IOBSDNameMatching" ||
1079 FName == "IOServiceMatching" ||
1080 FName == "IOServiceNameMatching" ||
Ted Kremenek555560c2012-05-01 05:28:27 +00001081 FName == "IORegistryEntrySearchCFProperty" ||
Benjamin Kramereaabbd82010-02-08 18:38:55 +00001082 FName == "IORegistryEntryIDMatching" ||
1083 FName == "IOOpenFirmwarePathMatching") {
1084 // Part of <rdar://problem/6961230>. (IOKit)
1085 // This should be addressed using a API table.
1086 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1087 DoNothing, DoNothing);
1088 } else if (FName == "IOServiceGetMatchingService" ||
1089 FName == "IOServiceGetMatchingServices") {
1090 // FIXES: <rdar://problem/6326900>
1091 // This should be addressed using a API table. This strcmp is also
1092 // a little gross, but there is no need to super optimize here.
Ted Kremenekb3b56c62010-11-24 00:54:37 +00001093 ScratchArgs = AF.add(ScratchArgs, 1, DecRef);
Benjamin Kramereaabbd82010-02-08 18:38:55 +00001094 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1095 } else if (FName == "IOServiceAddNotification" ||
1096 FName == "IOServiceAddMatchingNotification") {
1097 // Part of <rdar://problem/6961230>. (IOKit)
1098 // This should be addressed using a API table.
Ted Kremenekb3b56c62010-11-24 00:54:37 +00001099 ScratchArgs = AF.add(ScratchArgs, 2, DecRef);
Benjamin Kramereaabbd82010-02-08 18:38:55 +00001100 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1101 } else if (FName == "CVPixelBufferCreateWithBytes") {
1102 // FIXES: <rdar://problem/7283567>
1103 // Eventually this can be improved by recognizing that the pixel
1104 // buffer passed to CVPixelBufferCreateWithBytes is released via
1105 // a callback and doing full IPA to make sure this is done correctly.
1106 // FIXME: This function has an out parameter that returns an
1107 // allocated object.
Ted Kremenekb3b56c62010-11-24 00:54:37 +00001108 ScratchArgs = AF.add(ScratchArgs, 7, StopTracking);
Benjamin Kramereaabbd82010-02-08 18:38:55 +00001109 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1110 } else if (FName == "CGBitmapContextCreateWithData") {
1111 // FIXES: <rdar://problem/7358899>
1112 // Eventually this can be improved by recognizing that 'releaseInfo'
1113 // passed to CGBitmapContextCreateWithData is released via
1114 // a callback and doing full IPA to make sure this is done correctly.
Ted Kremenekb3b56c62010-11-24 00:54:37 +00001115 ScratchArgs = AF.add(ScratchArgs, 8, StopTracking);
Benjamin Kramereaabbd82010-02-08 18:38:55 +00001116 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1117 DoNothing, DoNothing);
1118 } else if (FName == "CVPixelBufferCreateWithPlanarBytes") {
1119 // FIXES: <rdar://problem/7283567>
1120 // Eventually this can be improved by recognizing that the pixel
1121 // buffer passed to CVPixelBufferCreateWithPlanarBytes is released
1122 // via a callback and doing full IPA to make sure this is done
1123 // correctly.
Ted Kremenekb3b56c62010-11-24 00:54:37 +00001124 ScratchArgs = AF.add(ScratchArgs, 12, StopTracking);
Benjamin Kramereaabbd82010-02-08 18:38:55 +00001125 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Jordan Roseb1479182013-05-02 01:51:40 +00001126 } else if (FName == "dispatch_set_context" ||
1127 FName == "xpc_connection_set_context") {
Ted Kremenek40c13432012-03-22 06:29:41 +00001128 // <rdar://problem/11059275> - The analyzer currently doesn't have
1129 // a good way to reason about the finalizer function for libdispatch.
1130 // If we pass a context object that is memory managed, stop tracking it.
Jordan Roseb1479182013-05-02 01:51:40 +00001131 // <rdar://problem/13783514> - Same problem, but for XPC.
Ted Kremenek40c13432012-03-22 06:29:41 +00001132 // FIXME: this hack should possibly go away once we can handle
Jordan Roseb1479182013-05-02 01:51:40 +00001133 // libdispatch and XPC finalizers.
Ted Kremenek40c13432012-03-22 06:29:41 +00001134 ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
1135 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenekececf9f2012-05-08 00:12:09 +00001136 } else if (FName.startswith("NSLog")) {
1137 S = getDoNothingSummary();
Anna Zaks90ab9bf2012-03-30 05:48:16 +00001138 } else if (FName.startswith("NS") &&
1139 (FName.find("Insert") != StringRef::npos)) {
1140 // Whitelist NSXXInsertXX, for example NSMapInsertIfAbsent, since they can
1141 // be deallocated by NSMapRemove. (radar://11152419)
1142 ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
1143 ScratchArgs = AF.add(ScratchArgs, 2, StopTracking);
1144 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenekea675cf2009-06-11 18:17:24 +00001145 }
Mike Stump11289f42009-09-09 15:08:12 +00001146
Ted Kremenekea675cf2009-06-11 18:17:24 +00001147 // Did we get a summary?
1148 if (S)
1149 break;
Ted Kremenek211094d2009-03-17 22:43:44 +00001150
Jordan Rose85707b22013-03-04 23:21:32 +00001151 if (RetTy->isPointerType()) {
Ted Kremenek7e904222009-01-12 21:45:02 +00001152 // For CoreFoundation ('CF') types.
Ted Kremeneke9918352010-01-27 18:00:17 +00001153 if (cocoa::isRefType(RetTy, "CF", FName)) {
Jordan Rose77411322013-10-07 17:16:52 +00001154 if (isRetain(FD, FName)) {
Ted Kremenek7e904222009-01-12 21:45:02 +00001155 S = getUnarySummary(FT, cfretain);
Jordan Rose77411322013-10-07 17:16:52 +00001156 } else if (isAutorelease(FD, FName)) {
1157 S = getUnarySummary(FT, cfautorelease);
1158 // The headers use cf_consumed, but we can fully model CFAutorelease
1159 // ourselves.
1160 AllowAnnotations = false;
1161 } else if (isMakeCollectable(FD, FName)) {
Ted Kremenek7e904222009-01-12 21:45:02 +00001162 S = getUnarySummary(FT, cfmakecollectable);
Jordan Rose77411322013-10-07 17:16:52 +00001163 AllowAnnotations = false;
1164 } else {
John McCall525f0552011-10-01 00:48:56 +00001165 S = getCFCreateGetRuleSummary(FD);
Jordan Rose77411322013-10-07 17:16:52 +00001166 }
Ted Kremenek7e904222009-01-12 21:45:02 +00001167
1168 break;
1169 }
1170
1171 // For CoreGraphics ('CG') types.
Ted Kremeneke9918352010-01-27 18:00:17 +00001172 if (cocoa::isRefType(RetTy, "CG", FName)) {
Ted Kremenek7e904222009-01-12 21:45:02 +00001173 if (isRetain(FD, FName))
1174 S = getUnarySummary(FT, cfretain);
1175 else
John McCall525f0552011-10-01 00:48:56 +00001176 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek7e904222009-01-12 21:45:02 +00001177
1178 break;
1179 }
1180
1181 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
Ted Kremeneke9918352010-01-27 18:00:17 +00001182 if (cocoa::isRefType(RetTy, "DADisk") ||
1183 cocoa::isRefType(RetTy, "DADissenter") ||
1184 cocoa::isRefType(RetTy, "DASessionRef")) {
John McCall525f0552011-10-01 00:48:56 +00001185 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek7e904222009-01-12 21:45:02 +00001186 break;
1187 }
Mike Stump11289f42009-09-09 15:08:12 +00001188
Aaron Ballman9ead1242013-12-19 02:39:40 +00001189 if (FD->hasAttr<CFAuditedTransferAttr>()) {
Jordan Rose85707b22013-03-04 23:21:32 +00001190 S = getCFCreateGetRuleSummary(FD);
1191 break;
1192 }
1193
Ted Kremenek7e904222009-01-12 21:45:02 +00001194 break;
1195 }
1196
1197 // Check for release functions, the only kind of functions that we care
1198 // about that don't return a pointer type.
1199 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
Ted Kremenekac5ab792010-02-08 16:45:01 +00001200 // Test for 'CGCF'.
Benjamin Kramereaabbd82010-02-08 18:38:55 +00001201 FName = FName.substr(FName.startswith("CGCF") ? 4 : 2);
Ted Kremenekac5ab792010-02-08 16:45:01 +00001202
Ted Kremenek5f968932009-03-05 22:11:14 +00001203 if (isRelease(FD, FName))
Ted Kremenek7e904222009-01-12 21:45:02 +00001204 S = getUnarySummary(FT, cfrelease);
1205 else {
Ted Kremenek7d79a5f2009-05-03 05:20:50 +00001206 assert (ScratchArgs.isEmpty());
Ted Kremeneked90de42009-01-29 22:45:13 +00001207 // Remaining CoreFoundation and CoreGraphics functions.
1208 // We use to assume that they all strictly followed the ownership idiom
1209 // and that ownership cannot be transferred. While this is technically
1210 // correct, many methods allow a tracked object to escape. For example:
1211 //
Mike Stump11289f42009-09-09 15:08:12 +00001212 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
Ted Kremeneked90de42009-01-29 22:45:13 +00001213 // CFDictionaryAddValue(y, key, x);
Mike Stump11289f42009-09-09 15:08:12 +00001214 // CFRelease(x);
Ted Kremeneked90de42009-01-29 22:45:13 +00001215 // ... it is okay to use 'x' since 'y' has a reference to it
1216 //
1217 // We handle this and similar cases with the follow heuristic. If the
Ted Kremenekd982f002009-08-20 00:57:22 +00001218 // function name contains "InsertValue", "SetValue", "AddValue",
1219 // "AppendValue", or "SetAttribute", then we assume that arguments may
1220 // "escape." This means that something else holds on to the object,
1221 // allowing it be used even after its local retain count drops to 0.
Benjamin Kramer0129bd72010-01-11 19:46:28 +00001222 ArgEffect E = (StrInStrNoCase(FName, "InsertValue") != StringRef::npos||
1223 StrInStrNoCase(FName, "AddValue") != StringRef::npos ||
1224 StrInStrNoCase(FName, "SetValue") != StringRef::npos ||
1225 StrInStrNoCase(FName, "AppendValue") != StringRef::npos||
Benjamin Kramer37808312010-01-11 20:15:06 +00001226 StrInStrNoCase(FName, "SetAttribute") != StringRef::npos)
Ted Kremeneked90de42009-01-29 22:45:13 +00001227 ? MayEscape : DoNothing;
Mike Stump11289f42009-09-09 15:08:12 +00001228
Ted Kremeneked90de42009-01-29 22:45:13 +00001229 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek7e904222009-01-12 21:45:02 +00001230 }
1231 }
Ted Kremenekfa89e2f2008-07-15 16:50:12 +00001232 }
1233 while (0);
Mike Stump11289f42009-09-09 15:08:12 +00001234
Jordan Roseeec15392012-07-02 19:27:43 +00001235 // If we got all the way here without any luck, use a default summary.
1236 if (!S)
1237 S = getDefaultSummary();
1238
Ted Kremenekc2de7272009-05-09 02:58:13 +00001239 // Annotations override defaults.
Jordan Rose1c715602012-08-06 21:28:02 +00001240 if (AllowAnnotations)
1241 updateSummaryFromAnnotations(S, FD);
Mike Stump11289f42009-09-09 15:08:12 +00001242
Ted Kremenek00daccd2008-05-05 22:11:16 +00001243 FuncSummaries[FD] = S;
Mike Stump11289f42009-09-09 15:08:12 +00001244 return S;
Ted Kremenekea6507f2008-03-06 00:08:09 +00001245}
1246
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001247const RetainSummary *
John McCall525f0552011-10-01 00:48:56 +00001248RetainSummaryManager::getCFCreateGetRuleSummary(const FunctionDecl *FD) {
1249 if (coreFoundation::followsCreateRule(FD))
Ted Kremenek875db812008-05-05 16:51:50 +00001250 return getCFSummaryCreateRule(FD);
Mike Stump11289f42009-09-09 15:08:12 +00001251
Ted Kremenek8e2c9b02011-05-25 06:19:45 +00001252 return getCFSummaryGetRule(FD);
Ted Kremenek875db812008-05-05 16:51:50 +00001253}
1254
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001255const RetainSummary *
Ted Kremenek82157a12009-02-23 16:51:39 +00001256RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1257 UnaryFuncKind func) {
1258
Ted Kremenek7e904222009-01-12 21:45:02 +00001259 // Sanity check that this is *really* a unary function. This can
1260 // happen if people do weird things.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001261 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
Alp Toker9cacbab2014-01-20 20:26:09 +00001262 if (!FTP || FTP->getNumParams() != 1)
Ted Kremenek7e904222009-01-12 21:45:02 +00001263 return getPersistentStopSummary();
Mike Stump11289f42009-09-09 15:08:12 +00001264
Ted Kremenek7d79a5f2009-05-03 05:20:50 +00001265 assert (ScratchArgs.isEmpty());
Mike Stump11289f42009-09-09 15:08:12 +00001266
Jordy Rose898a1482011-08-21 21:58:18 +00001267 ArgEffect Effect;
Ted Kremenek4b7ca772008-04-29 05:33:51 +00001268 switch (func) {
Jordan Rose77411322013-10-07 17:16:52 +00001269 case cfretain: Effect = IncRef; break;
1270 case cfrelease: Effect = DecRef; break;
1271 case cfautorelease: Effect = Autorelease; break;
1272 case cfmakecollectable: Effect = MakeCollectable; break;
Ted Kremenek4b772092008-04-10 23:44:06 +00001273 }
Jordy Rose898a1482011-08-21 21:58:18 +00001274
1275 ScratchArgs = AF.add(ScratchArgs, 0, Effect);
1276 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenek68d73d12008-03-12 01:21:45 +00001277}
1278
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001279const RetainSummary *
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001280RetainSummaryManager::getCFSummaryCreateRule(const FunctionDecl *FD) {
Ted Kremenek7d79a5f2009-05-03 05:20:50 +00001281 assert (ScratchArgs.isEmpty());
Mike Stump11289f42009-09-09 15:08:12 +00001282
Ted Kremenekaeb115f2009-01-28 05:56:51 +00001283 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenek68d73d12008-03-12 01:21:45 +00001284}
1285
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001286const RetainSummary *
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001287RetainSummaryManager::getCFSummaryGetRule(const FunctionDecl *FD) {
Mike Stump11289f42009-09-09 15:08:12 +00001288 assert (ScratchArgs.isEmpty());
Ted Kremenekaeb115f2009-01-28 05:56:51 +00001289 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1290 DoNothing, DoNothing);
Ted Kremenek68d73d12008-03-12 01:21:45 +00001291}
1292
Ted Kremenek819e9b62008-03-11 06:39:11 +00001293//===----------------------------------------------------------------------===//
Ted Kremenek00daccd2008-05-05 22:11:16 +00001294// Summary creation for Selectors.
1295//===----------------------------------------------------------------------===//
1296
Jordan Rose39032472013-04-04 22:31:48 +00001297Optional<RetEffect>
1298RetainSummaryManager::getRetEffectFromAnnotations(QualType RetTy,
1299 const Decl *D) {
1300 if (cocoa::isCocoaObjectRef(RetTy)) {
Aaron Ballman9ead1242013-12-19 02:39:40 +00001301 if (D->hasAttr<NSReturnsRetainedAttr>())
Jordan Rose39032472013-04-04 22:31:48 +00001302 return ObjCAllocRetE;
1303
Aaron Ballman9ead1242013-12-19 02:39:40 +00001304 if (D->hasAttr<NSReturnsNotRetainedAttr>() ||
1305 D->hasAttr<NSReturnsAutoreleasedAttr>())
Jordan Rose39032472013-04-04 22:31:48 +00001306 return RetEffect::MakeNotOwned(RetEffect::ObjC);
1307
1308 } else if (!RetTy->isPointerType()) {
1309 return None;
1310 }
1311
Aaron Ballman9ead1242013-12-19 02:39:40 +00001312 if (D->hasAttr<CFReturnsRetainedAttr>())
Jordan Rose39032472013-04-04 22:31:48 +00001313 return RetEffect::MakeOwned(RetEffect::CF, true);
1314
Aaron Ballman9ead1242013-12-19 02:39:40 +00001315 if (D->hasAttr<CFReturnsNotRetainedAttr>())
Jordan Rose39032472013-04-04 22:31:48 +00001316 return RetEffect::MakeNotOwned(RetEffect::CF);
1317
1318 return None;
1319}
1320
Ted Kremenekc2de7272009-05-09 02:58:13 +00001321void
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001322RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenekc2de7272009-05-09 02:58:13 +00001323 const FunctionDecl *FD) {
1324 if (!FD)
1325 return;
1326
Jordan Roseeec15392012-07-02 19:27:43 +00001327 assert(Summ && "Must have a summary to add annotations to.");
1328 RetainSummaryTemplate Template(Summ, *this);
Jordy Rose212e4592011-08-23 04:27:15 +00001329
Ted Kremenekafe348e2011-01-27 18:43:03 +00001330 // Effects on the parameters.
1331 unsigned parm_idx = 0;
1332 for (FunctionDecl::param_const_iterator pi = FD->param_begin(),
John McCall3337ca52011-04-06 09:02:12 +00001333 pe = FD->param_end(); pi != pe; ++pi, ++parm_idx) {
Ted Kremenekafe348e2011-01-27 18:43:03 +00001334 const ParmVarDecl *pd = *pi;
Aaron Ballman9ead1242013-12-19 02:39:40 +00001335 if (pd->hasAttr<NSConsumedAttr>())
Jordan Rose39032472013-04-04 22:31:48 +00001336 Template->addArg(AF, parm_idx, DecRefMsg);
Aaron Ballman9ead1242013-12-19 02:39:40 +00001337 else if (pd->hasAttr<CFConsumedAttr>())
Jordy Rose14de7c52011-08-24 09:02:37 +00001338 Template->addArg(AF, parm_idx, DecRef);
Ted Kremenekafe348e2011-01-27 18:43:03 +00001339 }
Alp Toker314cc812014-01-25 16:55:45 +00001340
1341 QualType RetTy = FD->getReturnType();
Jordan Rose39032472013-04-04 22:31:48 +00001342 if (Optional<RetEffect> RetE = getRetEffectFromAnnotations(RetTy, FD))
1343 Template->setRetEffect(*RetE);
Ted Kremenekc2de7272009-05-09 02:58:13 +00001344}
1345
1346void
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001347RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
1348 const ObjCMethodDecl *MD) {
Ted Kremenekc2de7272009-05-09 02:58:13 +00001349 if (!MD)
1350 return;
1351
Jordan Roseeec15392012-07-02 19:27:43 +00001352 assert(Summ && "Must have a valid summary to add annotations to");
1353 RetainSummaryTemplate Template(Summ, *this);
Mike Stump11289f42009-09-09 15:08:12 +00001354
Ted Kremenek0e898382011-01-27 06:54:14 +00001355 // Effects on the receiver.
Aaron Ballman9ead1242013-12-19 02:39:40 +00001356 if (MD->hasAttr<NSConsumesSelfAttr>())
Jordan Rose39032472013-04-04 22:31:48 +00001357 Template->setReceiverEffect(DecRefMsg);
Ted Kremenekafe348e2011-01-27 18:43:03 +00001358
1359 // Effects on the parameters.
1360 unsigned parm_idx = 0;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00001361 for (ObjCMethodDecl::param_const_iterator
1362 pi=MD->param_begin(), pe=MD->param_end();
Ted Kremenekafe348e2011-01-27 18:43:03 +00001363 pi != pe; ++pi, ++parm_idx) {
1364 const ParmVarDecl *pd = *pi;
Aaron Ballman9ead1242013-12-19 02:39:40 +00001365 if (pd->hasAttr<NSConsumedAttr>())
Jordan Rose39032472013-04-04 22:31:48 +00001366 Template->addArg(AF, parm_idx, DecRefMsg);
Aaron Ballman9ead1242013-12-19 02:39:40 +00001367 else if (pd->hasAttr<CFConsumedAttr>()) {
Jordy Rose14de7c52011-08-24 09:02:37 +00001368 Template->addArg(AF, parm_idx, DecRef);
Ted Kremenekafe348e2011-01-27 18:43:03 +00001369 }
Ted Kremenek0e898382011-01-27 06:54:14 +00001370 }
Alp Toker314cc812014-01-25 16:55:45 +00001371
1372 QualType RetTy = MD->getReturnType();
Jordan Rose39032472013-04-04 22:31:48 +00001373 if (Optional<RetEffect> RetE = getRetEffectFromAnnotations(RetTy, MD))
1374 Template->setRetEffect(*RetE);
Ted Kremenekc2de7272009-05-09 02:58:13 +00001375}
1376
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001377const RetainSummary *
Jordy Rose35e71c72012-03-17 21:13:07 +00001378RetainSummaryManager::getStandardMethodSummary(const ObjCMethodDecl *MD,
1379 Selector S, QualType RetTy) {
Jordy Rose70638832012-03-17 19:53:04 +00001380 // Any special effects?
Ted Kremenek6a966b22009-04-24 21:56:17 +00001381 ArgEffect ReceiverEff = DoNothing;
Jordy Rose70638832012-03-17 19:53:04 +00001382 RetEffect ResultEff = RetEffect::MakeNoRet();
1383
1384 // Check the method family, and apply any default annotations.
1385 switch (MD ? MD->getMethodFamily() : S.getMethodFamily()) {
1386 case OMF_None:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00001387 case OMF_initialize:
Jordy Rose70638832012-03-17 19:53:04 +00001388 case OMF_performSelector:
1389 // Assume all Objective-C methods follow Cocoa Memory Management rules.
1390 // FIXME: Does the non-threaded performSelector family really belong here?
1391 // The selector could be, say, @selector(copy).
1392 if (cocoa::isCocoaObjectRef(RetTy))
1393 ResultEff = RetEffect::MakeNotOwned(RetEffect::ObjC);
1394 else if (coreFoundation::isCFObjectRef(RetTy)) {
1395 // ObjCMethodDecl currently doesn't consider CF objects as valid return
1396 // values for alloc, new, copy, or mutableCopy, so we have to
1397 // double-check with the selector. This is ugly, but there aren't that
1398 // many Objective-C methods that return CF objects, right?
1399 if (MD) {
1400 switch (S.getMethodFamily()) {
1401 case OMF_alloc:
1402 case OMF_new:
1403 case OMF_copy:
1404 case OMF_mutableCopy:
1405 ResultEff = RetEffect::MakeOwned(RetEffect::CF, true);
1406 break;
1407 default:
1408 ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1409 break;
1410 }
1411 } else {
1412 ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1413 }
1414 }
1415 break;
1416 case OMF_init:
1417 ResultEff = ObjCInitRetE;
1418 ReceiverEff = DecRefMsg;
1419 break;
1420 case OMF_alloc:
1421 case OMF_new:
1422 case OMF_copy:
1423 case OMF_mutableCopy:
1424 if (cocoa::isCocoaObjectRef(RetTy))
1425 ResultEff = ObjCAllocRetE;
1426 else if (coreFoundation::isCFObjectRef(RetTy))
1427 ResultEff = RetEffect::MakeOwned(RetEffect::CF, true);
1428 break;
1429 case OMF_autorelease:
1430 ReceiverEff = Autorelease;
1431 break;
1432 case OMF_retain:
1433 ReceiverEff = IncRefMsg;
1434 break;
1435 case OMF_release:
1436 ReceiverEff = DecRefMsg;
1437 break;
1438 case OMF_dealloc:
1439 ReceiverEff = Dealloc;
1440 break;
1441 case OMF_self:
1442 // -self is handled specially by the ExprEngine to propagate the receiver.
1443 break;
1444 case OMF_retainCount:
1445 case OMF_finalize:
1446 // These methods don't return objects.
1447 break;
1448 }
Mike Stump11289f42009-09-09 15:08:12 +00001449
Ted Kremenek6a966b22009-04-24 21:56:17 +00001450 // If one of the arguments in the selector has the keyword 'delegate' we
1451 // should stop tracking the reference count for the receiver. This is
1452 // because the reference count is quite possibly handled by a delegate
1453 // method.
1454 if (S.isKeywordSelector()) {
Jordan Rose95dfae82012-06-15 18:19:52 +00001455 for (unsigned i = 0, e = S.getNumArgs(); i != e; ++i) {
1456 StringRef Slot = S.getNameForSlot(i);
1457 if (Slot.substr(Slot.size() - 8).equals_lower("delegate")) {
1458 if (ResultEff == ObjCInitRetE)
Anna Zaks25612732012-08-29 23:23:43 +00001459 ResultEff = RetEffect::MakeNoRetHard();
Jordan Rose95dfae82012-06-15 18:19:52 +00001460 else
Anna Zaks25612732012-08-29 23:23:43 +00001461 ReceiverEff = StopTrackingHard;
Jordan Rose95dfae82012-06-15 18:19:52 +00001462 }
1463 }
Ted Kremenek6a966b22009-04-24 21:56:17 +00001464 }
Mike Stump11289f42009-09-09 15:08:12 +00001465
Jordy Rose70638832012-03-17 19:53:04 +00001466 if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing &&
1467 ResultEff.getKind() == RetEffect::NoRet)
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001468 return getDefaultSummary();
Mike Stump11289f42009-09-09 15:08:12 +00001469
Jordy Rose70638832012-03-17 19:53:04 +00001470 return getPersistentSummary(ResultEff, ReceiverEff, MayEscape);
Ted Kremenek60746a02009-04-23 23:08:22 +00001471}
1472
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001473const RetainSummary *
Jordan Rose6bad4902012-07-02 19:27:56 +00001474RetainSummaryManager::getInstanceMethodSummary(const ObjCMethodCall &Msg,
Jordan Roseeec15392012-07-02 19:27:43 +00001475 ProgramStateRef State) {
Craig Topper0dbb7832014-05-27 02:45:47 +00001476 const ObjCInterfaceDecl *ReceiverClass = nullptr;
Ted Kremeneka2968e52009-11-13 01:54:21 +00001477
Jordan Roseeec15392012-07-02 19:27:43 +00001478 // We do better tracking of the type of the object than the core ExprEngine.
1479 // See if we have its type in our private state.
1480 // FIXME: Eventually replace the use of state->get<RefBindings> with
1481 // a generic API for reasoning about the Objective-C types of symbolic
1482 // objects.
1483 SVal ReceiverV = Msg.getReceiverSVal();
1484 if (SymbolRef Sym = ReceiverV.getAsLocSymbol())
Anna Zaksf5788c72012-08-14 00:36:15 +00001485 if (const RefVal *T = getRefBinding(State, Sym))
Douglas Gregor9a129192010-04-21 00:45:42 +00001486 if (const ObjCObjectPointerType *PT =
Jordan Roseeec15392012-07-02 19:27:43 +00001487 T->getType()->getAs<ObjCObjectPointerType>())
1488 ReceiverClass = PT->getInterfaceDecl();
1489
1490 // If we don't know what kind of object this is, fall back to its static type.
1491 if (!ReceiverClass)
1492 ReceiverClass = Msg.getReceiverInterface();
Douglas Gregor9a129192010-04-21 00:45:42 +00001493
Ted Kremeneka2968e52009-11-13 01:54:21 +00001494 // FIXME: The receiver could be a reference to a class, meaning that
1495 // we should use the class method.
Jordan Roseeec15392012-07-02 19:27:43 +00001496 // id x = [NSObject class];
1497 // [x performSelector:... withObject:... afterDelay:...];
1498 Selector S = Msg.getSelector();
1499 const ObjCMethodDecl *Method = Msg.getDecl();
1500 if (!Method && ReceiverClass)
1501 Method = ReceiverClass->getInstanceMethod(S);
1502
1503 return getMethodSummary(S, ReceiverClass, Method, Msg.getResultType(),
1504 ObjCMethodSummaries);
Ted Kremeneka2968e52009-11-13 01:54:21 +00001505}
1506
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001507const RetainSummary *
Jordan Roseeec15392012-07-02 19:27:43 +00001508RetainSummaryManager::getMethodSummary(Selector S, const ObjCInterfaceDecl *ID,
Jordy Rose35e71c72012-03-17 21:13:07 +00001509 const ObjCMethodDecl *MD, QualType RetTy,
1510 ObjCMethodSummariesTy &CachedSummaries) {
Ted Kremenekcb2e6362008-05-06 15:44:25 +00001511
Ted Kremenek0b50fb12009-04-29 05:04:30 +00001512 // Look up a summary in our summary cache.
Jordan Roseeec15392012-07-02 19:27:43 +00001513 const RetainSummary *Summ = CachedSummaries.find(ID, S);
Mike Stump11289f42009-09-09 15:08:12 +00001514
Ted Kremenek8be51382009-07-21 23:27:57 +00001515 if (!Summ) {
Jordy Rose35e71c72012-03-17 21:13:07 +00001516 Summ = getStandardMethodSummary(MD, S, RetTy);
Mike Stump11289f42009-09-09 15:08:12 +00001517
Ted Kremenek8be51382009-07-21 23:27:57 +00001518 // Annotations override defaults.
Jordy Rose212e4592011-08-23 04:27:15 +00001519 updateSummaryFromAnnotations(Summ, MD);
Mike Stump11289f42009-09-09 15:08:12 +00001520
Ted Kremenek8be51382009-07-21 23:27:57 +00001521 // Memoize the summary.
Jordan Roseeec15392012-07-02 19:27:43 +00001522 CachedSummaries[ObjCSummaryKey(ID, S)] = Summ;
Ted Kremenek8be51382009-07-21 23:27:57 +00001523 }
Mike Stump11289f42009-09-09 15:08:12 +00001524
Ted Kremenekf27110f2009-04-23 19:11:35 +00001525 return Summ;
Ted Kremenek767d0742008-05-06 21:26:51 +00001526}
1527
Mike Stump11289f42009-09-09 15:08:12 +00001528void RetainSummaryManager::InitializeClassMethodSummaries() {
Ted Kremenek9157fbb2009-05-07 23:40:42 +00001529 assert(ScratchArgs.isEmpty());
Mike Stump11289f42009-09-09 15:08:12 +00001530 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek55adb822009-10-15 22:25:12 +00001531 addClassMethSummary("NSAssertionHandler", "currentHandler",
Ted Kremenekaeb115f2009-01-28 05:56:51 +00001532 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Mike Stump11289f42009-09-09 15:08:12 +00001533
Ted Kremenek0747e7e2008-10-21 15:53:15 +00001534 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremenekb3b56c62010-11-24 00:54:37 +00001535 ScratchArgs = AF.add(ScratchArgs, 0, Autorelease);
Ted Kremenek55adb822009-10-15 22:25:12 +00001536 addClassMethSummary("NSAutoreleasePool", "addObject",
1537 getPersistentSummary(RetEffect::MakeNoRet(),
1538 DoNothing, Autorelease));
Ted Kremenek0806f912008-05-06 00:30:21 +00001539}
1540
Ted Kremenekea736c52008-06-23 22:21:20 +00001541void RetainSummaryManager::InitializeMethodSummaries() {
Mike Stump11289f42009-09-09 15:08:12 +00001542
1543 assert (ScratchArgs.isEmpty());
1544
Ted Kremenek767d0742008-05-06 21:26:51 +00001545 // Create the "init" selector. It just acts as a pass-through for the
1546 // receiver.
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001547 const RetainSummary *InitSumm = getPersistentSummary(ObjCInitRetE, DecRefMsg);
Ted Kremenek815fbb62009-08-20 05:13:36 +00001548 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
1549
1550 // awakeAfterUsingCoder: behaves basically like an 'init' method. It
1551 // claims the receiver and returns a retained object.
1552 addNSObjectMethSummary(GetUnarySelector("awakeAfterUsingCoder", Ctx),
1553 InitSumm);
Mike Stump11289f42009-09-09 15:08:12 +00001554
Ted Kremenek767d0742008-05-06 21:26:51 +00001555 // The next methods are allocators.
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001556 const RetainSummary *AllocSumm = getPersistentSummary(ObjCAllocRetE);
1557 const RetainSummary *CFAllocSumm =
Ted Kremenek52ac2b52009-08-28 19:52:12 +00001558 getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Mike Stump11289f42009-09-09 15:08:12 +00001559
Ted Kremenekb0862dc2008-05-06 02:26:56 +00001560 // Create the "retain" selector.
Jordy Rose3f7f75682011-08-21 19:41:36 +00001561 RetEffect NoRet = RetEffect::MakeNoRet();
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001562 const RetainSummary *Summ = getPersistentSummary(NoRet, IncRefMsg);
Ted Kremenek3185c9c2008-06-25 21:21:56 +00001563 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Mike Stump11289f42009-09-09 15:08:12 +00001564
Ted Kremenekb0862dc2008-05-06 02:26:56 +00001565 // Create the "release" selector.
Jordy Rose3f7f75682011-08-21 19:41:36 +00001566 Summ = getPersistentSummary(NoRet, DecRefMsg);
Ted Kremenek3185c9c2008-06-25 21:21:56 +00001567 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Mike Stump11289f42009-09-09 15:08:12 +00001568
Ted Kremenekea072e32009-03-17 19:42:23 +00001569 // Create the -dealloc summary.
Jordy Rose3f7f75682011-08-21 19:41:36 +00001570 Summ = getPersistentSummary(NoRet, Dealloc);
Ted Kremenekea072e32009-03-17 19:42:23 +00001571 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
Ted Kremenekb0862dc2008-05-06 02:26:56 +00001572
1573 // Create the "autorelease" selector.
Jordy Rose3f7f75682011-08-21 19:41:36 +00001574 Summ = getPersistentSummary(NoRet, Autorelease);
Ted Kremenek3185c9c2008-06-25 21:21:56 +00001575 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Mike Stump11289f42009-09-09 15:08:12 +00001576
Mike Stump11289f42009-09-09 15:08:12 +00001577 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremeneke73f2822009-02-23 02:51:29 +00001578 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1579 // self-own themselves. However, they only do this once they are displayed.
1580 // Thus, we need to track an NSWindow's display status.
1581 // This is tracked in <rdar://problem/6062711>.
Ted Kremenek00dfe302009-03-04 23:30:42 +00001582 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001583 const RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenek1272f702009-05-12 20:06:54 +00001584 StopTracking,
1585 StopTracking);
Mike Stump11289f42009-09-09 15:08:12 +00001586
Ted Kremenek751e7e32009-04-03 19:02:51 +00001587 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1588
Ted Kremenek3f13f592008-08-12 18:48:50 +00001589 // For NSPanel (which subclasses NSWindow), allocated objects are not
1590 // self-owned.
Ted Kremenek751e7e32009-04-03 19:02:51 +00001591 // FIXME: For now we don't track NSPanels. object for the same reason
1592 // as for NSWindow objects.
1593 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
Mike Stump11289f42009-09-09 15:08:12 +00001594
Ted Kremenek9b12e722014-01-03 01:19:28 +00001595 // For NSNull, objects returned by +null are singletons that ignore
1596 // retain/release semantics. Just don't track them.
1597 // <rdar://problem/12858915>
1598 addClassMethSummary("NSNull", "null", NoTrackYet);
1599
Jordan Rose95bf3b02013-01-31 22:06:02 +00001600 // Don't track allocated autorelease pools, as it is okay to prematurely
Ted Kremenek501ba032009-05-18 23:14:34 +00001601 // exit a method.
1602 addClassMethSummary("NSAutoreleasePool", "alloc", NoTrackYet);
Ted Kremeneke8a5ba82012-02-18 21:37:48 +00001603 addClassMethSummary("NSAutoreleasePool", "allocWithZone", NoTrackYet, false);
Jordan Rose95bf3b02013-01-31 22:06:02 +00001604 addClassMethSummary("NSAutoreleasePool", "new", NoTrackYet);
Ted Kremenek3185c9c2008-06-25 21:21:56 +00001605
Ted Kremenek10369122009-05-20 22:39:57 +00001606 // Create summaries QCRenderer/QCView -createSnapShotImageOfType:
1607 addInstMethSummary("QCRenderer", AllocSumm,
Reid Kleckneree7cf842014-12-01 22:02:27 +00001608 "createSnapshotImageOfType", nullptr);
Ted Kremenek10369122009-05-20 22:39:57 +00001609 addInstMethSummary("QCView", AllocSumm,
Reid Kleckneree7cf842014-12-01 22:02:27 +00001610 "createSnapshotImageOfType", nullptr);
Ted Kremenek10369122009-05-20 22:39:57 +00001611
Ted Kremenek96aa1462009-06-15 20:58:58 +00001612 // Create summaries for CIContext, 'createCGImage' and
Ted Kremenek52ac2b52009-08-28 19:52:12 +00001613 // 'createCGLayerWithSize'. These objects are CF objects, and are not
1614 // automatically garbage collected.
1615 addInstMethSummary("CIContext", CFAllocSumm,
Reid Kleckneree7cf842014-12-01 22:02:27 +00001616 "createCGImage", "fromRect", nullptr);
1617 addInstMethSummary("CIContext", CFAllocSumm, "createCGImage", "fromRect",
1618 "format", "colorSpace", nullptr);
1619 addInstMethSummary("CIContext", CFAllocSumm, "createCGLayerWithSize", "info",
1620 nullptr);
Ted Kremenekbe7c56e2008-05-06 00:38:54 +00001621}
1622
Ted Kremenek00daccd2008-05-05 22:11:16 +00001623//===----------------------------------------------------------------------===//
Ted Kremenek6bd78702009-04-29 18:50:19 +00001624// Error reporting.
1625//===----------------------------------------------------------------------===//
Ted Kremenek6bd78702009-04-29 18:50:19 +00001626namespace {
Jordy Rose20d4e682011-08-23 20:55:48 +00001627 typedef llvm::DenseMap<const ExplodedNode *, const RetainSummary *>
1628 SummaryLogTy;
1629
Ted Kremenek6bd78702009-04-29 18:50:19 +00001630 //===-------------===//
1631 // Bug Descriptions. //
Mike Stump11289f42009-09-09 15:08:12 +00001632 //===-------------===//
1633
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00001634 class CFRefBug : public BugType {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001635 protected:
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001636 CFRefBug(const CheckerBase *checker, StringRef name)
1637 : BugType(checker, name, categories::MemoryCoreFoundationObjectiveC) {}
1638
Ted Kremenek6bd78702009-04-29 18:50:19 +00001639 public:
Mike Stump11289f42009-09-09 15:08:12 +00001640
Ted Kremenek6bd78702009-04-29 18:50:19 +00001641 // FIXME: Eventually remove.
Jordy Rose7a534982011-08-24 05:47:39 +00001642 virtual const char *getDescription() const = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001643
Ted Kremenek6bd78702009-04-29 18:50:19 +00001644 virtual bool isLeak() const { return false; }
1645 };
Mike Stump11289f42009-09-09 15:08:12 +00001646
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00001647 class UseAfterRelease : public CFRefBug {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001648 public:
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001649 UseAfterRelease(const CheckerBase *checker)
1650 : CFRefBug(checker, "Use-after-release") {}
Mike Stump11289f42009-09-09 15:08:12 +00001651
Craig Topperfb6b25b2014-03-15 04:29:04 +00001652 const char *getDescription() const override {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001653 return "Reference-counted object is used after it is released";
Mike Stump11289f42009-09-09 15:08:12 +00001654 }
Ted Kremenek6bd78702009-04-29 18:50:19 +00001655 };
Mike Stump11289f42009-09-09 15:08:12 +00001656
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00001657 class BadRelease : public CFRefBug {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001658 public:
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001659 BadRelease(const CheckerBase *checker) : CFRefBug(checker, "Bad release") {}
Mike Stump11289f42009-09-09 15:08:12 +00001660
Craig Topperfb6b25b2014-03-15 04:29:04 +00001661 const char *getDescription() const override {
Ted Kremenek5c22e112009-10-01 17:31:50 +00001662 return "Incorrect decrement of the reference count of an object that is "
1663 "not owned at this point by the caller";
Ted Kremenek6bd78702009-04-29 18:50:19 +00001664 }
1665 };
Mike Stump11289f42009-09-09 15:08:12 +00001666
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00001667 class DeallocGC : public CFRefBug {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001668 public:
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001669 DeallocGC(const CheckerBase *checker)
1670 : CFRefBug(checker, "-dealloc called while using garbage collection") {}
Mike Stump11289f42009-09-09 15:08:12 +00001671
Craig Topperfb6b25b2014-03-15 04:29:04 +00001672 const char *getDescription() const override {
Ted Kremenekd35272f2009-05-09 00:10:05 +00001673 return "-dealloc called while using garbage collection";
Ted Kremenek6bd78702009-04-29 18:50:19 +00001674 }
1675 };
Mike Stump11289f42009-09-09 15:08:12 +00001676
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00001677 class DeallocNotOwned : public CFRefBug {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001678 public:
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001679 DeallocNotOwned(const CheckerBase *checker)
1680 : CFRefBug(checker, "-dealloc sent to non-exclusively owned object") {}
Mike Stump11289f42009-09-09 15:08:12 +00001681
Craig Topperfb6b25b2014-03-15 04:29:04 +00001682 const char *getDescription() const override {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001683 return "-dealloc sent to object that may be referenced elsewhere";
1684 }
Mike Stump11289f42009-09-09 15:08:12 +00001685 };
1686
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00001687 class OverAutorelease : public CFRefBug {
Ted Kremenekd35272f2009-05-09 00:10:05 +00001688 public:
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001689 OverAutorelease(const CheckerBase *checker)
1690 : CFRefBug(checker, "Object autoreleased too many times") {}
Mike Stump11289f42009-09-09 15:08:12 +00001691
Craig Topperfb6b25b2014-03-15 04:29:04 +00001692 const char *getDescription() const override {
Jordan Rose7467f062013-04-23 01:42:25 +00001693 return "Object autoreleased too many times";
Ted Kremenekd35272f2009-05-09 00:10:05 +00001694 }
1695 };
Mike Stump11289f42009-09-09 15:08:12 +00001696
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00001697 class ReturnedNotOwnedForOwned : public CFRefBug {
Ted Kremenekdee56e32009-05-10 06:25:57 +00001698 public:
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001699 ReturnedNotOwnedForOwned(const CheckerBase *checker)
1700 : CFRefBug(checker, "Method should return an owned object") {}
Mike Stump11289f42009-09-09 15:08:12 +00001701
Craig Topperfb6b25b2014-03-15 04:29:04 +00001702 const char *getDescription() const override {
Jordy Rose43426f82011-07-15 22:17:54 +00001703 return "Object with a +0 retain count returned to caller where a +1 "
Ted Kremenekdee56e32009-05-10 06:25:57 +00001704 "(owning) retain count is expected";
1705 }
1706 };
Mike Stump11289f42009-09-09 15:08:12 +00001707
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00001708 class Leak : public CFRefBug {
Benjamin Kramerd1d76b22012-06-06 17:32:50 +00001709 public:
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001710 Leak(const CheckerBase *checker, StringRef name) : CFRefBug(checker, name) {
Jordy Rose15484da2011-08-25 01:14:38 +00001711 // Leaks should not be reported if they are post-dominated by a sink.
1712 setSuppressOnSink(true);
1713 }
Mike Stump11289f42009-09-09 15:08:12 +00001714
Craig Topperfb6b25b2014-03-15 04:29:04 +00001715 const char *getDescription() const override { return ""; }
Mike Stump11289f42009-09-09 15:08:12 +00001716
Craig Topperfb6b25b2014-03-15 04:29:04 +00001717 bool isLeak() const override { return true; }
Ted Kremenek6bd78702009-04-29 18:50:19 +00001718 };
Mike Stump11289f42009-09-09 15:08:12 +00001719
Ted Kremenek6bd78702009-04-29 18:50:19 +00001720 //===---------===//
1721 // Bug Reports. //
1722 //===---------===//
Mike Stump11289f42009-09-09 15:08:12 +00001723
Jordy Rosef78877e2012-03-24 02:45:35 +00001724 class CFRefReportVisitor : public BugReporterVisitorImpl<CFRefReportVisitor> {
Anna Zaks88255cc2011-08-20 01:27:22 +00001725 protected:
Anna Zaks071a89c2011-08-19 23:21:56 +00001726 SymbolRef Sym;
Jordy Rose20d4e682011-08-23 20:55:48 +00001727 const SummaryLogTy &SummaryLog;
Jordy Rose7a534982011-08-24 05:47:39 +00001728 bool GCEnabled;
Anna Zaks88255cc2011-08-20 01:27:22 +00001729
Anna Zaks071a89c2011-08-19 23:21:56 +00001730 public:
Jordy Rose7a534982011-08-24 05:47:39 +00001731 CFRefReportVisitor(SymbolRef sym, bool gcEnabled, const SummaryLogTy &log)
1732 : Sym(sym), SummaryLog(log), GCEnabled(gcEnabled) {}
Anna Zaks071a89c2011-08-19 23:21:56 +00001733
Craig Topperfb6b25b2014-03-15 04:29:04 +00001734 void Profile(llvm::FoldingSetNodeID &ID) const override {
Anna Zaks071a89c2011-08-19 23:21:56 +00001735 static int x = 0;
1736 ID.AddPointer(&x);
1737 ID.AddPointer(Sym);
1738 }
1739
Craig Topperfb6b25b2014-03-15 04:29:04 +00001740 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
1741 const ExplodedNode *PrevN,
1742 BugReporterContext &BRC,
1743 BugReport &BR) override;
Anna Zaks88255cc2011-08-20 01:27:22 +00001744
David Blaikied15481c2014-08-29 18:18:43 +00001745 std::unique_ptr<PathDiagnosticPiece> getEndPath(BugReporterContext &BRC,
1746 const ExplodedNode *N,
1747 BugReport &BR) override;
Anna Zaks88255cc2011-08-20 01:27:22 +00001748 };
1749
1750 class CFRefLeakReportVisitor : public CFRefReportVisitor {
1751 public:
Jordy Rose7a534982011-08-24 05:47:39 +00001752 CFRefLeakReportVisitor(SymbolRef sym, bool GCEnabled,
Jordy Rose20d4e682011-08-23 20:55:48 +00001753 const SummaryLogTy &log)
Jordy Rose7a534982011-08-24 05:47:39 +00001754 : CFRefReportVisitor(sym, GCEnabled, log) {}
Anna Zaks88255cc2011-08-20 01:27:22 +00001755
David Blaikied15481c2014-08-29 18:18:43 +00001756 std::unique_ptr<PathDiagnosticPiece> getEndPath(BugReporterContext &BRC,
1757 const ExplodedNode *N,
1758 BugReport &BR) override;
Jordy Rosef78877e2012-03-24 02:45:35 +00001759
David Blaikie91e79022014-09-04 23:54:33 +00001760 std::unique_ptr<BugReporterVisitor> clone() const override {
Jordy Rosef78877e2012-03-24 02:45:35 +00001761 // The curiously-recurring template pattern only works for one level of
1762 // subclassing. Rather than make a new template base for
1763 // CFRefReportVisitor, we simply override clone() to do the right thing.
1764 // This could be trouble someday if BugReporterVisitorImpl is ever
1765 // used for something else besides a convenient implementation of clone().
David Blaikie91e79022014-09-04 23:54:33 +00001766 return llvm::make_unique<CFRefLeakReportVisitor>(*this);
Jordy Rosef78877e2012-03-24 02:45:35 +00001767 }
Anna Zaks071a89c2011-08-19 23:21:56 +00001768 };
1769
Anna Zaks3a6bdf82011-08-17 23:00:25 +00001770 class CFRefReport : public BugReport {
Jordy Rose184bd142011-08-24 22:39:09 +00001771 void addGCModeDescription(const LangOptions &LOpts, bool GCEnabled);
Jordy Rose7a534982011-08-24 05:47:39 +00001772
Ted Kremenek6bd78702009-04-29 18:50:19 +00001773 public:
Jordy Rose184bd142011-08-24 22:39:09 +00001774 CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1775 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1776 bool registerVisitor = true)
Anna Zaks752de142011-08-22 18:54:07 +00001777 : BugReport(D, D.getDescription(), n) {
Anna Zaks88255cc2011-08-20 01:27:22 +00001778 if (registerVisitor)
David Blaikie91e79022014-09-04 23:54:33 +00001779 addVisitor(llvm::make_unique<CFRefReportVisitor>(sym, GCEnabled, Log));
Jordy Rose184bd142011-08-24 22:39:09 +00001780 addGCModeDescription(LOpts, GCEnabled);
Anna Zaks071a89c2011-08-19 23:21:56 +00001781 }
Ted Kremenek3978f792009-05-10 05:11:21 +00001782
Jordy Rose184bd142011-08-24 22:39:09 +00001783 CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1784 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1785 StringRef endText)
Anna Zaks752de142011-08-22 18:54:07 +00001786 : BugReport(D, D.getDescription(), endText, n) {
David Blaikie91e79022014-09-04 23:54:33 +00001787 addVisitor(llvm::make_unique<CFRefReportVisitor>(sym, GCEnabled, Log));
Jordy Rose184bd142011-08-24 22:39:09 +00001788 addGCModeDescription(LOpts, GCEnabled);
Anna Zaks071a89c2011-08-19 23:21:56 +00001789 }
Mike Stump11289f42009-09-09 15:08:12 +00001790
Craig Topperfb6b25b2014-03-15 04:29:04 +00001791 std::pair<ranges_iterator, ranges_iterator> getRanges() override {
Anna Zaks752de142011-08-22 18:54:07 +00001792 const CFRefBug& BugTy = static_cast<CFRefBug&>(getBugType());
1793 if (!BugTy.isLeak())
Anna Zaks3a6bdf82011-08-17 23:00:25 +00001794 return BugReport::getRanges();
Ted Kremenek6bd78702009-04-29 18:50:19 +00001795 else
Argyrios Kyrtzidisd22d8ff2010-12-04 01:12:15 +00001796 return std::make_pair(ranges_iterator(), ranges_iterator());
Ted Kremenek6bd78702009-04-29 18:50:19 +00001797 }
Ted Kremenek6bd78702009-04-29 18:50:19 +00001798 };
Ted Kremenek3978f792009-05-10 05:11:21 +00001799
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00001800 class CFRefLeakReport : public CFRefReport {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001801 const MemRegion* AllocBinding;
1802 public:
Jordy Rose184bd142011-08-24 22:39:09 +00001803 CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1804 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
Ted Kremenek8671acb2013-04-16 21:44:22 +00001805 CheckerContext &Ctx,
1806 bool IncludeAllocationLine);
Mike Stump11289f42009-09-09 15:08:12 +00001807
Craig Topperfb6b25b2014-03-15 04:29:04 +00001808 PathDiagnosticLocation getLocation(const SourceManager &SM) const override {
Anna Zaksc29bed32011-09-20 21:38:35 +00001809 assert(Location.isValid());
1810 return Location;
1811 }
Mike Stump11289f42009-09-09 15:08:12 +00001812 };
Ted Kremenek6bd78702009-04-29 18:50:19 +00001813} // end anonymous namespace
1814
Jordy Rose184bd142011-08-24 22:39:09 +00001815void CFRefReport::addGCModeDescription(const LangOptions &LOpts,
1816 bool GCEnabled) {
Craig Topper0dbb7832014-05-27 02:45:47 +00001817 const char *GCModeDescription = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001818
Douglas Gregor79a91412011-09-13 17:21:33 +00001819 switch (LOpts.getGC()) {
Anna Zaks76c3fb62011-08-22 20:31:28 +00001820 case LangOptions::GCOnly:
Jordy Rose184bd142011-08-24 22:39:09 +00001821 assert(GCEnabled);
Jordy Rose7a534982011-08-24 05:47:39 +00001822 GCModeDescription = "Code is compiled to only use garbage collection";
1823 break;
Mike Stump11289f42009-09-09 15:08:12 +00001824
Anna Zaks76c3fb62011-08-22 20:31:28 +00001825 case LangOptions::NonGC:
Jordy Rose184bd142011-08-24 22:39:09 +00001826 assert(!GCEnabled);
Jordy Rose7a534982011-08-24 05:47:39 +00001827 GCModeDescription = "Code is compiled to use reference counts";
1828 break;
Mike Stump11289f42009-09-09 15:08:12 +00001829
Anna Zaks76c3fb62011-08-22 20:31:28 +00001830 case LangOptions::HybridGC:
Jordy Rose184bd142011-08-24 22:39:09 +00001831 if (GCEnabled) {
Jordy Rose7a534982011-08-24 05:47:39 +00001832 GCModeDescription = "Code is compiled to use either garbage collection "
1833 "(GC) or reference counts (non-GC). The bug occurs "
1834 "with GC enabled";
1835 break;
1836 } else {
1837 GCModeDescription = "Code is compiled to use either garbage collection "
1838 "(GC) or reference counts (non-GC). The bug occurs "
1839 "in non-GC mode";
1840 break;
Anna Zaks76c3fb62011-08-22 20:31:28 +00001841 }
Ted Kremenek6bd78702009-04-29 18:50:19 +00001842 }
Jordy Rose7a534982011-08-24 05:47:39 +00001843
Jordy Rose9ff02992011-08-24 20:38:42 +00001844 assert(GCModeDescription && "invalid/unknown GC mode");
Jordy Rose7a534982011-08-24 05:47:39 +00001845 addExtraText(GCModeDescription);
Ted Kremenek6bd78702009-04-29 18:50:19 +00001846}
1847
Jordy Rose6393f822012-05-12 05:10:43 +00001848static bool isNumericLiteralExpression(const Expr *E) {
1849 // FIXME: This set of cases was copied from SemaExprObjC.
1850 return isa<IntegerLiteral>(E) ||
1851 isa<CharacterLiteral>(E) ||
1852 isa<FloatingLiteral>(E) ||
1853 isa<ObjCBoolLiteralExpr>(E) ||
1854 isa<CXXBoolLiteralExpr>(E);
1855}
1856
Jordan Rosecb5386c2015-02-04 19:24:52 +00001857/// Returns true if this stack frame is for an Objective-C method that is a
1858/// property getter or setter whose body has been synthesized by the analyzer.
1859static bool isSynthesizedAccessor(const StackFrameContext *SFC) {
1860 auto Method = dyn_cast_or_null<ObjCMethodDecl>(SFC->getDecl());
1861 if (!Method || !Method->isPropertyAccessor())
1862 return false;
1863
1864 return SFC->getAnalysisDeclContext()->isBodyAutosynthesized();
1865}
1866
Anna Zaks071a89c2011-08-19 23:21:56 +00001867PathDiagnosticPiece *CFRefReportVisitor::VisitNode(const ExplodedNode *N,
1868 const ExplodedNode *PrevN,
1869 BugReporterContext &BRC,
1870 BugReport &BR) {
Jordan Rose681cce92012-07-10 22:07:42 +00001871 // FIXME: We will eventually need to handle non-statement-based events
1872 // (__attribute__((cleanup))).
David Blaikie87396b92013-02-21 22:23:56 +00001873 if (!N->getLocation().getAs<StmtPoint>())
Craig Topper0dbb7832014-05-27 02:45:47 +00001874 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001875
Ted Kremenekbb8d5462009-05-06 21:39:49 +00001876 // Check if the type state has changed.
Ted Kremenek49b1e382012-01-26 21:29:00 +00001877 ProgramStateRef PrevSt = PrevN->getState();
1878 ProgramStateRef CurrSt = N->getState();
Ted Kremenek632e3b72012-01-06 22:09:28 +00001879 const LocationContext *LCtx = N->getLocationContext();
Mike Stump11289f42009-09-09 15:08:12 +00001880
Anna Zaksf5788c72012-08-14 00:36:15 +00001881 const RefVal* CurrT = getRefBinding(CurrSt, Sym);
Craig Topper0dbb7832014-05-27 02:45:47 +00001882 if (!CurrT) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001883
Ted Kremenekd93c6e32009-06-18 01:23:53 +00001884 const RefVal &CurrV = *CurrT;
Anna Zaksf5788c72012-08-14 00:36:15 +00001885 const RefVal *PrevT = getRefBinding(PrevSt, Sym);
Mike Stump11289f42009-09-09 15:08:12 +00001886
Ted Kremenek6bd78702009-04-29 18:50:19 +00001887 // Create a string buffer to constain all the useful things we want
1888 // to tell the user.
1889 std::string sbuf;
1890 llvm::raw_string_ostream os(sbuf);
Mike Stump11289f42009-09-09 15:08:12 +00001891
Ted Kremenek6bd78702009-04-29 18:50:19 +00001892 // This is the allocation site since the previous node had no bindings
1893 // for this symbol.
1894 if (!PrevT) {
David Blaikie87396b92013-02-21 22:23:56 +00001895 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
Mike Stump11289f42009-09-09 15:08:12 +00001896
Jordan Rosecb5386c2015-02-04 19:24:52 +00001897 if (isa<ObjCIvarRefExpr>(S) &&
1898 isSynthesizedAccessor(LCtx->getCurrentStackFrame())) {
1899 S = LCtx->getCurrentStackFrame()->getCallSite();
1900 }
1901
Ted Kremenek415287d2012-03-06 20:06:12 +00001902 if (isa<ObjCArrayLiteral>(S)) {
1903 os << "NSArray literal is an object with a +0 retain count";
Mike Stump11289f42009-09-09 15:08:12 +00001904 }
Ted Kremenek415287d2012-03-06 20:06:12 +00001905 else if (isa<ObjCDictionaryLiteral>(S)) {
1906 os << "NSDictionary literal is an object with a +0 retain count";
Ted Kremenek6bd78702009-04-29 18:50:19 +00001907 }
Jordy Rose6393f822012-05-12 05:10:43 +00001908 else if (const ObjCBoxedExpr *BL = dyn_cast<ObjCBoxedExpr>(S)) {
1909 if (isNumericLiteralExpression(BL->getSubExpr()))
1910 os << "NSNumber literal is an object with a +0 retain count";
1911 else {
Craig Topper0dbb7832014-05-27 02:45:47 +00001912 const ObjCInterfaceDecl *BoxClass = nullptr;
Jordy Rose6393f822012-05-12 05:10:43 +00001913 if (const ObjCMethodDecl *Method = BL->getBoxingMethod())
1914 BoxClass = Method->getClassInterface();
1915
1916 // We should always be able to find the boxing class interface,
1917 // but consider this future-proofing.
1918 if (BoxClass)
1919 os << *BoxClass << " b";
1920 else
1921 os << "B";
1922
1923 os << "oxed expression produces an object with a +0 retain count";
1924 }
1925 }
Jordan Rosecb5386c2015-02-04 19:24:52 +00001926 else if (isa<ObjCIvarRefExpr>(S)) {
1927 os << "Object loaded from instance variable";
1928 }
Ted Kremenek415287d2012-03-06 20:06:12 +00001929 else {
1930 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
1931 // Get the name of the callee (if it is available).
1932 SVal X = CurrSt->getSValAsScalarOrLoc(CE->getCallee(), LCtx);
1933 if (const FunctionDecl *FD = X.getAsFunctionDecl())
1934 os << "Call to function '" << *FD << '\'';
1935 else
1936 os << "function call";
Ted Kremenek6bd78702009-04-29 18:50:19 +00001937 }
Ted Kremenek415287d2012-03-06 20:06:12 +00001938 else {
Jordan Rose627b0462012-07-18 21:59:51 +00001939 assert(isa<ObjCMessageExpr>(S));
Jordan Rosefcd016e2012-07-30 20:22:09 +00001940 CallEventManager &Mgr = CurrSt->getStateManager().getCallEventManager();
1941 CallEventRef<ObjCMethodCall> Call
1942 = Mgr.getObjCMethodCall(cast<ObjCMessageExpr>(S), CurrSt, LCtx);
1943
1944 switch (Call->getMessageKind()) {
Jordan Rose627b0462012-07-18 21:59:51 +00001945 case OCM_Message:
1946 os << "Method";
1947 break;
1948 case OCM_PropertyAccess:
1949 os << "Property";
1950 break;
1951 case OCM_Subscript:
1952 os << "Subscript";
1953 break;
1954 }
Ted Kremenek415287d2012-03-06 20:06:12 +00001955 }
1956
1957 if (CurrV.getObjKind() == RetEffect::CF) {
1958 os << " returns a Core Foundation object with a ";
1959 }
1960 else {
1961 assert (CurrV.getObjKind() == RetEffect::ObjC);
1962 os << " returns an Objective-C object with a ";
1963 }
1964
1965 if (CurrV.isOwned()) {
1966 os << "+1 retain count";
1967
1968 if (GCEnabled) {
1969 assert(CurrV.getObjKind() == RetEffect::CF);
1970 os << ". "
1971 "Core Foundation objects are not automatically garbage collected.";
1972 }
1973 }
1974 else {
1975 assert (CurrV.isNotOwned());
1976 os << "+0 retain count";
1977 }
Ted Kremenek6bd78702009-04-29 18:50:19 +00001978 }
Mike Stump11289f42009-09-09 15:08:12 +00001979
Anna Zaks3a769bd2011-09-15 01:08:34 +00001980 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
1981 N->getLocationContext());
Ted Kremenek6bd78702009-04-29 18:50:19 +00001982 return new PathDiagnosticEventPiece(Pos, os.str());
1983 }
Mike Stump11289f42009-09-09 15:08:12 +00001984
Ted Kremenek6bd78702009-04-29 18:50:19 +00001985 // Gather up the effects that were performed on the object at this
1986 // program point
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001987 SmallVector<ArgEffect, 2> AEffects;
Mike Stump11289f42009-09-09 15:08:12 +00001988
Jordy Rose20d4e682011-08-23 20:55:48 +00001989 const ExplodedNode *OrigNode = BRC.getNodeResolver().getOriginalNode(N);
1990 if (const RetainSummary *Summ = SummaryLog.lookup(OrigNode)) {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001991 // We only have summaries attached to nodes after evaluating CallExpr and
1992 // ObjCMessageExprs.
David Blaikie87396b92013-02-21 22:23:56 +00001993 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
Mike Stump11289f42009-09-09 15:08:12 +00001994
Ted Kremenekbfd28fd2009-07-22 22:35:28 +00001995 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001996 // Iterate through the parameter expressions and see if the symbol
1997 // was ever passed as an argument.
1998 unsigned i = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001999
Ted Kremenekbfd28fd2009-07-22 22:35:28 +00002000 for (CallExpr::const_arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
Ted Kremenek6bd78702009-04-29 18:50:19 +00002001 AI!=AE; ++AI, ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002002
Ted Kremenek6bd78702009-04-29 18:50:19 +00002003 // Retrieve the value of the argument. Is it the symbol
2004 // we are interested in?
Ted Kremenek632e3b72012-01-06 22:09:28 +00002005 if (CurrSt->getSValAsScalarOrLoc(*AI, LCtx).getAsLocSymbol() != Sym)
Ted Kremenek6bd78702009-04-29 18:50:19 +00002006 continue;
Mike Stump11289f42009-09-09 15:08:12 +00002007
Ted Kremenek6bd78702009-04-29 18:50:19 +00002008 // We have an argument. Get the effect!
2009 AEffects.push_back(Summ->getArg(i));
2010 }
2011 }
Mike Stump11289f42009-09-09 15:08:12 +00002012 else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
Douglas Gregor9a129192010-04-21 00:45:42 +00002013 if (const Expr *receiver = ME->getInstanceReceiver())
Ted Kremenek632e3b72012-01-06 22:09:28 +00002014 if (CurrSt->getSValAsScalarOrLoc(receiver, LCtx)
2015 .getAsLocSymbol() == Sym) {
Ted Kremenek6bd78702009-04-29 18:50:19 +00002016 // The symbol we are tracking is the receiver.
2017 AEffects.push_back(Summ->getReceiverEffect());
2018 }
2019 }
2020 }
Mike Stump11289f42009-09-09 15:08:12 +00002021
Ted Kremenek6bd78702009-04-29 18:50:19 +00002022 do {
2023 // Get the previous type state.
2024 RefVal PrevV = *PrevT;
Mike Stump11289f42009-09-09 15:08:12 +00002025
Ted Kremenek6bd78702009-04-29 18:50:19 +00002026 // Specially handle -dealloc.
Benjamin Kramerab3838a2013-08-16 21:57:14 +00002027 if (!GCEnabled && std::find(AEffects.begin(), AEffects.end(), Dealloc) !=
2028 AEffects.end()) {
Ted Kremenek6bd78702009-04-29 18:50:19 +00002029 // Determine if the object's reference count was pushed to zero.
Jordan Roseb3ad07e2014-03-25 17:10:58 +00002030 assert(!PrevV.hasSameState(CurrV) && "The state should have changed.");
Ted Kremenek6bd78702009-04-29 18:50:19 +00002031 // We may not have transitioned to 'release' if we hit an error.
2032 // This case is handled elsewhere.
2033 if (CurrV.getKind() == RefVal::Released) {
Ted Kremenek3a0516b2009-05-08 20:01:42 +00002034 assert(CurrV.getCombinedCounts() == 0);
Ted Kremenek6bd78702009-04-29 18:50:19 +00002035 os << "Object released by directly sending the '-dealloc' message";
2036 break;
2037 }
2038 }
Mike Stump11289f42009-09-09 15:08:12 +00002039
Ted Kremenek6bd78702009-04-29 18:50:19 +00002040 // Specially handle CFMakeCollectable and friends.
Benjamin Kramerab3838a2013-08-16 21:57:14 +00002041 if (std::find(AEffects.begin(), AEffects.end(), MakeCollectable) !=
2042 AEffects.end()) {
Ted Kremenek6bd78702009-04-29 18:50:19 +00002043 // Get the name of the function.
David Blaikie87396b92013-02-21 22:23:56 +00002044 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
Ted Kremenek632e3b72012-01-06 22:09:28 +00002045 SVal X =
2046 CurrSt->getSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee(), LCtx);
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002047 const FunctionDecl *FD = X.getAsFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00002048
Jordy Rose7a534982011-08-24 05:47:39 +00002049 if (GCEnabled) {
Ted Kremenek6bd78702009-04-29 18:50:19 +00002050 // Determine if the object's reference count was pushed to zero.
Jordan Roseb3ad07e2014-03-25 17:10:58 +00002051 assert(!PrevV.hasSameState(CurrV) && "The state should have changed.");
Mike Stump11289f42009-09-09 15:08:12 +00002052
Benjamin Kramerb89514a2011-10-14 18:45:37 +00002053 os << "In GC mode a call to '" << *FD
Ted Kremenek6bd78702009-04-29 18:50:19 +00002054 << "' decrements an object's retain count and registers the "
2055 "object with the garbage collector. ";
Mike Stump11289f42009-09-09 15:08:12 +00002056
Ted Kremenek6bd78702009-04-29 18:50:19 +00002057 if (CurrV.getKind() == RefVal::Released) {
2058 assert(CurrV.getCount() == 0);
2059 os << "Since it now has a 0 retain count the object can be "
2060 "automatically collected by the garbage collector.";
2061 }
2062 else
2063 os << "An object must have a 0 retain count to be garbage collected. "
2064 "After this call its retain count is +" << CurrV.getCount()
2065 << '.';
2066 }
Mike Stump11289f42009-09-09 15:08:12 +00002067 else
Benjamin Kramerb89514a2011-10-14 18:45:37 +00002068 os << "When GC is not enabled a call to '" << *FD
Ted Kremenek6bd78702009-04-29 18:50:19 +00002069 << "' has no effect on its argument.";
Mike Stump11289f42009-09-09 15:08:12 +00002070
Ted Kremenek6bd78702009-04-29 18:50:19 +00002071 // Nothing more to say.
2072 break;
2073 }
Mike Stump11289f42009-09-09 15:08:12 +00002074
2075 // Determine if the typestate has changed.
Jordan Roseb3ad07e2014-03-25 17:10:58 +00002076 if (!PrevV.hasSameState(CurrV))
Ted Kremenek6bd78702009-04-29 18:50:19 +00002077 switch (CurrV.getKind()) {
2078 case RefVal::Owned:
2079 case RefVal::NotOwned:
Ted Kremenek3a0516b2009-05-08 20:01:42 +00002080 if (PrevV.getCount() == CurrV.getCount()) {
2081 // Did an autorelease message get sent?
2082 if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
Craig Topper0dbb7832014-05-27 02:45:47 +00002083 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002084
Zhongxing Xu08a2ede2009-05-12 10:10:00 +00002085 assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount());
Jordan Rose7467f062013-04-23 01:42:25 +00002086 os << "Object autoreleased";
Ted Kremenek3a0516b2009-05-08 20:01:42 +00002087 break;
2088 }
Mike Stump11289f42009-09-09 15:08:12 +00002089
Ted Kremenek6bd78702009-04-29 18:50:19 +00002090 if (PrevV.getCount() > CurrV.getCount())
2091 os << "Reference count decremented.";
2092 else
2093 os << "Reference count incremented.";
Mike Stump11289f42009-09-09 15:08:12 +00002094
Ted Kremenek6bd78702009-04-29 18:50:19 +00002095 if (unsigned Count = CurrV.getCount())
2096 os << " The object now has a +" << Count << " retain count.";
Mike Stump11289f42009-09-09 15:08:12 +00002097
Ted Kremenek6bd78702009-04-29 18:50:19 +00002098 if (PrevV.getKind() == RefVal::Released) {
Jordy Rose7a534982011-08-24 05:47:39 +00002099 assert(GCEnabled && CurrV.getCount() > 0);
Jordy Rose78373e52012-03-17 05:49:15 +00002100 os << " The object is not eligible for garbage collection until "
2101 "the retain count reaches 0 again.";
Ted Kremenek6bd78702009-04-29 18:50:19 +00002102 }
Mike Stump11289f42009-09-09 15:08:12 +00002103
Ted Kremenek6bd78702009-04-29 18:50:19 +00002104 break;
Mike Stump11289f42009-09-09 15:08:12 +00002105
Ted Kremenek6bd78702009-04-29 18:50:19 +00002106 case RefVal::Released:
Jordan Rosecb5386c2015-02-04 19:24:52 +00002107 if (CurrV.getIvarAccessHistory() ==
2108 RefVal::IvarAccessHistory::ReleasedAfterDirectAccess &&
2109 CurrV.getIvarAccessHistory() != PrevV.getIvarAccessHistory()) {
2110 os << "Strong instance variable relinquished. ";
2111 }
Ted Kremenek6bd78702009-04-29 18:50:19 +00002112 os << "Object released.";
2113 break;
Mike Stump11289f42009-09-09 15:08:12 +00002114
Ted Kremenek6bd78702009-04-29 18:50:19 +00002115 case RefVal::ReturnedOwned:
Jordy Rose78373e52012-03-17 05:49:15 +00002116 // Autoreleases can be applied after marking a node ReturnedOwned.
2117 if (CurrV.getAutoreleaseCount())
Craig Topper0dbb7832014-05-27 02:45:47 +00002118 return nullptr;
Jordy Rose78373e52012-03-17 05:49:15 +00002119
2120 os << "Object returned to caller as an owning reference (single "
2121 "retain count transferred to caller)";
Ted Kremenek6bd78702009-04-29 18:50:19 +00002122 break;
Mike Stump11289f42009-09-09 15:08:12 +00002123
Ted Kremenek6bd78702009-04-29 18:50:19 +00002124 case RefVal::ReturnedNotOwned:
Ted Kremenekf2301982011-05-26 18:45:44 +00002125 os << "Object returned to caller with a +0 retain count";
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 default:
Craig Topper0dbb7832014-05-27 02:45:47 +00002129 return nullptr;
Ted Kremenek6bd78702009-04-29 18:50:19 +00002130 }
Mike Stump11289f42009-09-09 15:08:12 +00002131
Ted Kremenek6bd78702009-04-29 18:50:19 +00002132 // Emit any remaining diagnostics for the argument effects (if any).
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002133 for (SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
Ted Kremenek6bd78702009-04-29 18:50:19 +00002134 E=AEffects.end(); I != E; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +00002135
Ted Kremenek6bd78702009-04-29 18:50:19 +00002136 // A bunch of things have alternate behavior under GC.
Jordy Rose7a534982011-08-24 05:47:39 +00002137 if (GCEnabled)
Ted Kremenek6bd78702009-04-29 18:50:19 +00002138 switch (*I) {
2139 default: break;
2140 case Autorelease:
2141 os << "In GC mode an 'autorelease' has no effect.";
2142 continue;
2143 case IncRefMsg:
2144 os << "In GC mode the 'retain' message has no effect.";
2145 continue;
2146 case DecRefMsg:
2147 os << "In GC mode the 'release' message has no effect.";
2148 continue;
2149 }
2150 }
Mike Stump11289f42009-09-09 15:08:12 +00002151 } while (0);
2152
Ted Kremenek6bd78702009-04-29 18:50:19 +00002153 if (os.str().empty())
Craig Topper0dbb7832014-05-27 02:45:47 +00002154 return nullptr; // We have nothing to say!
Ted Kremenek051a03d2009-05-13 07:12:33 +00002155
David Blaikie87396b92013-02-21 22:23:56 +00002156 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
Anna Zaks3a769bd2011-09-15 01:08:34 +00002157 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
2158 N->getLocationContext());
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002159 PathDiagnosticPiece *P = new PathDiagnosticEventPiece(Pos, os.str());
Mike Stump11289f42009-09-09 15:08:12 +00002160
Ted Kremenek6bd78702009-04-29 18:50:19 +00002161 // Add the range by scanning the children of the statement for any bindings
2162 // to Sym.
Mike Stump11289f42009-09-09 15:08:12 +00002163 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
Ted Kremenekbfd28fd2009-07-22 22:35:28 +00002164 I!=E; ++I)
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002165 if (const Expr *Exp = dyn_cast_or_null<Expr>(*I))
Ted Kremenek632e3b72012-01-06 22:09:28 +00002166 if (CurrSt->getSValAsScalarOrLoc(Exp, LCtx).getAsLocSymbol() == Sym) {
Ted Kremenek6bd78702009-04-29 18:50:19 +00002167 P->addRange(Exp->getSourceRange());
2168 break;
2169 }
Mike Stump11289f42009-09-09 15:08:12 +00002170
Ted Kremenek6bd78702009-04-29 18:50:19 +00002171 return P;
2172}
2173
Anna Zaks75de3232012-02-28 22:39:22 +00002174// Find the first node in the current function context that referred to the
2175// tracked symbol and the memory location that value was stored to. Note, the
2176// value is only reported if the allocation occurred in the same function as
Anna Zakse51362e2013-04-10 21:42:06 +00002177// the leak. The function can also return a location context, which should be
2178// treated as interesting.
2179struct AllocationInfo {
2180 const ExplodedNode* N;
Anna Zaks3f303be2013-04-10 22:56:30 +00002181 const MemRegion *R;
Anna Zakse51362e2013-04-10 21:42:06 +00002182 const LocationContext *InterestingMethodContext;
Anna Zaks3f303be2013-04-10 22:56:30 +00002183 AllocationInfo(const ExplodedNode *InN,
2184 const MemRegion *InR,
Anna Zakse51362e2013-04-10 21:42:06 +00002185 const LocationContext *InInterestingMethodContext) :
2186 N(InN), R(InR), InterestingMethodContext(InInterestingMethodContext) {}
2187};
2188
2189static AllocationInfo
Ted Kremenek001fd5b2011-08-15 22:09:50 +00002190GetAllocationSite(ProgramStateManager& StateMgr, const ExplodedNode *N,
Ted Kremenek6bd78702009-04-29 18:50:19 +00002191 SymbolRef Sym) {
Anna Zakse51362e2013-04-10 21:42:06 +00002192 const ExplodedNode *AllocationNode = N;
Anna Zaks486a0ff2015-02-05 01:02:53 +00002193 const ExplodedNode *AllocationNodeInCurrentOrParentContext = N;
Craig Topper0dbb7832014-05-27 02:45:47 +00002194 const MemRegion *FirstBinding = nullptr;
Anna Zaks75de3232012-02-28 22:39:22 +00002195 const LocationContext *LeakContext = N->getLocationContext();
Mike Stump11289f42009-09-09 15:08:12 +00002196
Anna Zakse51362e2013-04-10 21:42:06 +00002197 // The location context of the init method called on the leaked object, if
2198 // available.
Craig Topper0dbb7832014-05-27 02:45:47 +00002199 const LocationContext *InitMethodContext = nullptr;
Anna Zakse51362e2013-04-10 21:42:06 +00002200
Ted Kremenek6bd78702009-04-29 18:50:19 +00002201 while (N) {
Ted Kremenek49b1e382012-01-26 21:29:00 +00002202 ProgramStateRef St = N->getState();
Anna Zakse51362e2013-04-10 21:42:06 +00002203 const LocationContext *NContext = N->getLocationContext();
Mike Stump11289f42009-09-09 15:08:12 +00002204
Anna Zaksf5788c72012-08-14 00:36:15 +00002205 if (!getRefBinding(St, Sym))
Ted Kremenek6bd78702009-04-29 18:50:19 +00002206 break;
Mike Stump11289f42009-09-09 15:08:12 +00002207
Anna Zaks6797d6e2012-03-21 19:45:01 +00002208 StoreManager::FindUniqueBinding FB(Sym);
Mike Stump11289f42009-09-09 15:08:12 +00002209 StateMgr.iterBindings(St, FB);
Anna Zakse51362e2013-04-10 21:42:06 +00002210
Anna Zaks7c19abe2013-04-10 21:42:02 +00002211 if (FB) {
2212 const MemRegion *R = FB.getRegion();
Anna Zaks07804ef2013-04-10 22:56:33 +00002213 const VarRegion *VR = R->getBaseRegion()->getAs<VarRegion>();
Anna Zaks7c19abe2013-04-10 21:42:02 +00002214 // Do not show local variables belonging to a function other than
2215 // where the error is reported.
2216 if (!VR || VR->getStackFrame() == LeakContext->getCurrentStackFrame())
Anna Zakse51362e2013-04-10 21:42:06 +00002217 FirstBinding = R;
Anna Zaks7c19abe2013-04-10 21:42:02 +00002218 }
Mike Stump11289f42009-09-09 15:08:12 +00002219
Anna Zakse51362e2013-04-10 21:42:06 +00002220 // AllocationNode is the last node in which the symbol was tracked.
2221 AllocationNode = N;
2222
Anna Zaks486a0ff2015-02-05 01:02:53 +00002223 // AllocationNodeInCurrentContext, is the last node in the current or
2224 // parent context in which the symbol was tracked.
2225 //
2226 // Note that the allocation site might be in the parent conext. For example,
2227 // the case where an allocation happens in a block that captures a reference
2228 // to it and that reference is overwritten/dropped by another call to
2229 // the block.
2230 if (NContext == LeakContext || NContext->isParentOf(LeakContext))
2231 AllocationNodeInCurrentOrParentContext = N;
Anna Zakse51362e2013-04-10 21:42:06 +00002232
Anna Zaks3f303be2013-04-10 22:56:30 +00002233 // Find the last init that was called on the given symbol and store the
2234 // init method's location context.
2235 if (!InitMethodContext)
2236 if (Optional<CallEnter> CEP = N->getLocation().getAs<CallEnter>()) {
2237 const Stmt *CE = CEP->getCallExpr();
Anna Zaks99394bb2013-04-25 00:41:32 +00002238 if (const ObjCMessageExpr *ME = dyn_cast_or_null<ObjCMessageExpr>(CE)) {
Anna Zaks3f303be2013-04-10 22:56:30 +00002239 const Stmt *RecExpr = ME->getInstanceReceiver();
2240 if (RecExpr) {
2241 SVal RecV = St->getSVal(RecExpr, NContext);
2242 if (ME->getMethodFamily() == OMF_init && RecV.getAsSymbol() == Sym)
2243 InitMethodContext = CEP->getCalleeContext();
2244 }
2245 }
Anna Zakse51362e2013-04-10 21:42:06 +00002246 }
Anna Zaks75de3232012-02-28 22:39:22 +00002247
Craig Topper0dbb7832014-05-27 02:45:47 +00002248 N = N->pred_empty() ? nullptr : *(N->pred_begin());
Ted Kremenek6bd78702009-04-29 18:50:19 +00002249 }
Mike Stump11289f42009-09-09 15:08:12 +00002250
Anna Zakse51362e2013-04-10 21:42:06 +00002251 // If we are reporting a leak of the object that was allocated with alloc,
Anna Zaks3f303be2013-04-10 22:56:30 +00002252 // mark its init method as interesting.
Craig Topper0dbb7832014-05-27 02:45:47 +00002253 const LocationContext *InterestingMethodContext = nullptr;
Anna Zakse51362e2013-04-10 21:42:06 +00002254 if (InitMethodContext) {
2255 const ProgramPoint AllocPP = AllocationNode->getLocation();
2256 if (Optional<StmtPoint> SP = AllocPP.getAs<StmtPoint>())
2257 if (const ObjCMessageExpr *ME = SP->getStmtAs<ObjCMessageExpr>())
2258 if (ME->getMethodFamily() == OMF_alloc)
2259 InterestingMethodContext = InitMethodContext;
2260 }
2261
Anna Zaks75de3232012-02-28 22:39:22 +00002262 // If allocation happened in a function different from the leak node context,
2263 // do not report the binding.
Ted Kremenekb045b012012-10-12 22:56:40 +00002264 assert(N && "Could not find allocation node");
Anna Zaks75de3232012-02-28 22:39:22 +00002265 if (N->getLocationContext() != LeakContext) {
Craig Topper0dbb7832014-05-27 02:45:47 +00002266 FirstBinding = nullptr;
Anna Zaks75de3232012-02-28 22:39:22 +00002267 }
2268
Anna Zaks486a0ff2015-02-05 01:02:53 +00002269 return AllocationInfo(AllocationNodeInCurrentOrParentContext,
Anna Zakse51362e2013-04-10 21:42:06 +00002270 FirstBinding,
2271 InterestingMethodContext);
Ted Kremenek6bd78702009-04-29 18:50:19 +00002272}
2273
David Blaikied15481c2014-08-29 18:18:43 +00002274std::unique_ptr<PathDiagnosticPiece>
Anna Zaks88255cc2011-08-20 01:27:22 +00002275CFRefReportVisitor::getEndPath(BugReporterContext &BRC,
David Blaikied15481c2014-08-29 18:18:43 +00002276 const ExplodedNode *EndN, BugReport &BR) {
Ted Kremenek1e809b42012-03-09 01:13:14 +00002277 BR.markInteresting(Sym);
Anna Zaks88255cc2011-08-20 01:27:22 +00002278 return BugReporterVisitor::getDefaultEndPath(BRC, EndN, BR);
Ted Kremenek6bd78702009-04-29 18:50:19 +00002279}
2280
David Blaikied15481c2014-08-29 18:18:43 +00002281std::unique_ptr<PathDiagnosticPiece>
Anna Zaks88255cc2011-08-20 01:27:22 +00002282CFRefLeakReportVisitor::getEndPath(BugReporterContext &BRC,
David Blaikied15481c2014-08-29 18:18:43 +00002283 const ExplodedNode *EndN, BugReport &BR) {
Mike Stump11289f42009-09-09 15:08:12 +00002284
Ted Kremenekbb8d5462009-05-06 21:39:49 +00002285 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenek6bd78702009-04-29 18:50:19 +00002286 // assigned to different variables, etc.
Ted Kremenek1e809b42012-03-09 01:13:14 +00002287 BR.markInteresting(Sym);
Mike Stump11289f42009-09-09 15:08:12 +00002288
Ted Kremenek6bd78702009-04-29 18:50:19 +00002289 // We are reporting a leak. Walk up the graph to get to the first node where
2290 // the symbol appeared, and also get the first VarDecl that tracked object
2291 // is stored to.
Anna Zakse51362e2013-04-10 21:42:06 +00002292 AllocationInfo AllocI =
Ted Kremenek8c8fb482009-05-08 23:32:51 +00002293 GetAllocationSite(BRC.getStateManager(), EndN, Sym);
Mike Stump11289f42009-09-09 15:08:12 +00002294
Anna Zakse51362e2013-04-10 21:42:06 +00002295 const MemRegion* FirstBinding = AllocI.R;
2296 BR.markInteresting(AllocI.InterestingMethodContext);
2297
Anna Zaks921f0492011-09-15 18:56:07 +00002298 SourceManager& SM = BRC.getSourceManager();
Mike Stump11289f42009-09-09 15:08:12 +00002299
Ted Kremenek6bd78702009-04-29 18:50:19 +00002300 // Compute an actual location for the leak. Sometimes a leak doesn't
2301 // occur at an actual statement (e.g., transition between blocks; end
2302 // of function) so we need to walk the graph and compute a real location.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002303 const ExplodedNode *LeakN = EndN;
Anna Zaks921f0492011-09-15 18:56:07 +00002304 PathDiagnosticLocation L = PathDiagnosticLocation::createEndOfPath(LeakN, SM);
Mike Stump11289f42009-09-09 15:08:12 +00002305
Ted Kremenek6bd78702009-04-29 18:50:19 +00002306 std::string sbuf;
2307 llvm::raw_string_ostream os(sbuf);
Mike Stump11289f42009-09-09 15:08:12 +00002308
Ted Kremenekf2301982011-05-26 18:45:44 +00002309 os << "Object leaked: ";
Mike Stump11289f42009-09-09 15:08:12 +00002310
Ted Kremenekf2301982011-05-26 18:45:44 +00002311 if (FirstBinding) {
2312 os << "object allocated and stored into '"
2313 << FirstBinding->getString() << '\'';
2314 }
2315 else
2316 os << "allocated object";
Mike Stump11289f42009-09-09 15:08:12 +00002317
Ted Kremenek6bd78702009-04-29 18:50:19 +00002318 // Get the retain count.
Anna Zaksf5788c72012-08-14 00:36:15 +00002319 const RefVal* RV = getRefBinding(EndN->getState(), Sym);
Ted Kremenekb045b012012-10-12 22:56:40 +00002320 assert(RV);
Mike Stump11289f42009-09-09 15:08:12 +00002321
Ted Kremenek6bd78702009-04-29 18:50:19 +00002322 if (RV->getKind() == RefVal::ErrorLeakReturned) {
2323 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
Jordy Rose43426f82011-07-15 22:17:54 +00002324 // objects. Only "copy", "alloc", "retain" and "new" transfer ownership
Ted Kremenek6bd78702009-04-29 18:50:19 +00002325 // to the caller for NS objects.
Ted Kremenek8e2c9b02011-05-25 06:19:45 +00002326 const Decl *D = &EndN->getCodeDecl();
Ted Kremenek2a786952012-09-06 23:03:07 +00002327
2328 os << (isa<ObjCMethodDecl>(D) ? " is returned from a method "
2329 : " is returned from a function ");
2330
Aaron Ballman9ead1242013-12-19 02:39:40 +00002331 if (D->hasAttr<CFReturnsNotRetainedAttr>())
Ted Kremenek2a786952012-09-06 23:03:07 +00002332 os << "that is annotated as CF_RETURNS_NOT_RETAINED";
Aaron Ballman9ead1242013-12-19 02:39:40 +00002333 else if (D->hasAttr<NSReturnsNotRetainedAttr>())
Ted Kremenek2a786952012-09-06 23:03:07 +00002334 os << "that is annotated as NS_RETURNS_NOT_RETAINED";
Ted Kremenek8e2c9b02011-05-25 06:19:45 +00002335 else {
Ted Kremenek2a786952012-09-06 23:03:07 +00002336 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2337 os << "whose name ('" << MD->getSelector().getAsString()
2338 << "') does not start with 'copy', 'mutableCopy', 'alloc' or 'new'."
2339 " This violates the naming convention rules"
2340 " given in the Memory Management Guide for Cocoa";
2341 }
2342 else {
2343 const FunctionDecl *FD = cast<FunctionDecl>(D);
2344 os << "whose name ('" << *FD
2345 << "') does not contain 'Copy' or 'Create'. This violates the naming"
2346 " convention rules given in the Memory Management Guide for Core"
2347 " Foundation";
2348 }
2349 }
Ted Kremenek6bd78702009-04-29 18:50:19 +00002350 }
Ted Kremenekdee56e32009-05-10 06:25:57 +00002351 else if (RV->getKind() == RefVal::ErrorGCLeakReturned) {
David Blaikie3cbec0f2013-02-21 22:37:44 +00002352 const ObjCMethodDecl &MD = cast<ObjCMethodDecl>(EndN->getCodeDecl());
Ted Kremenekdee56e32009-05-10 06:25:57 +00002353 os << " and returned from method '" << MD.getSelector().getAsString()
Ted Kremenek1f8e4342009-05-10 16:52:15 +00002354 << "' is potentially leaked when using garbage collection. Callers "
2355 "of this method do not expect a returned object with a +1 retain "
2356 "count since they expect the object to be managed by the garbage "
2357 "collector";
Ted Kremenekdee56e32009-05-10 06:25:57 +00002358 }
Ted Kremenek6bd78702009-04-29 18:50:19 +00002359 else
Ted Kremenek4f63ac72010-10-15 22:50:23 +00002360 os << " is not referenced later in this execution path and has a retain "
Ted Kremenekf2301982011-05-26 18:45:44 +00002361 "count of +" << RV->getCount();
Mike Stump11289f42009-09-09 15:08:12 +00002362
David Blaikied15481c2014-08-29 18:18:43 +00002363 return llvm::make_unique<PathDiagnosticEventPiece>(L, os.str());
Ted Kremenek6bd78702009-04-29 18:50:19 +00002364}
2365
Jordy Rose184bd142011-08-24 22:39:09 +00002366CFRefLeakReport::CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts,
2367 bool GCEnabled, const SummaryLogTy &Log,
2368 ExplodedNode *n, SymbolRef sym,
Ted Kremenek8671acb2013-04-16 21:44:22 +00002369 CheckerContext &Ctx,
2370 bool IncludeAllocationLine)
2371 : CFRefReport(D, LOpts, GCEnabled, Log, n, sym, false) {
Mike Stump11289f42009-09-09 15:08:12 +00002372
Chris Lattner57540c52011-04-15 05:22:18 +00002373 // Most bug reports are cached at the location where they occurred.
Ted Kremenek6bd78702009-04-29 18:50:19 +00002374 // With leaks, we want to unique them by the location where they were
2375 // allocated, and only report a single path. To do this, we need to find
2376 // the allocation site of a piece of tracked memory, which we do via a
2377 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2378 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2379 // that all ancestor nodes that represent the allocation site have the
2380 // same SourceLocation.
Craig Topper0dbb7832014-05-27 02:45:47 +00002381 const ExplodedNode *AllocNode = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002382
Anna Zaks58734db2011-10-25 19:57:11 +00002383 const SourceManager& SMgr = Ctx.getSourceManager();
Anna Zaksc29bed32011-09-20 21:38:35 +00002384
Anna Zakse51362e2013-04-10 21:42:06 +00002385 AllocationInfo AllocI =
Anna Zaks58734db2011-10-25 19:57:11 +00002386 GetAllocationSite(Ctx.getStateManager(), getErrorNode(), sym);
Mike Stump11289f42009-09-09 15:08:12 +00002387
Anna Zakse51362e2013-04-10 21:42:06 +00002388 AllocNode = AllocI.N;
2389 AllocBinding = AllocI.R;
2390 markInteresting(AllocI.InterestingMethodContext);
2391
Ted Kremenek6bd78702009-04-29 18:50:19 +00002392 // Get the SourceLocation for the allocation site.
Jordan Rosefbe6dba2012-07-10 22:07:52 +00002393 // FIXME: This will crash the analyzer if an allocation comes from an
Anna Zaksa6fea132014-06-13 23:47:38 +00002394 // implicit call (ex: a destructor call).
2395 // (Currently there are no such allocations in Cocoa, though.)
2396 const Stmt *AllocStmt = 0;
Ted Kremenek6bd78702009-04-29 18:50:19 +00002397 ProgramPoint P = AllocNode->getLocation();
David Blaikie87396b92013-02-21 22:23:56 +00002398 if (Optional<CallExitEnd> Exit = P.getAs<CallExitEnd>())
Jordan Rosefbe6dba2012-07-10 22:07:52 +00002399 AllocStmt = Exit->getCalleeContext()->getCallSite();
Anna Zaks486a0ff2015-02-05 01:02:53 +00002400 else
2401 AllocStmt = P.castAs<PostStmt>().getStmt();
Anna Zaksa6fea132014-06-13 23:47:38 +00002402 assert(AllocStmt && "Cannot find allocation statement");
Anna Zaks40402872013-04-23 23:57:50 +00002403
2404 PathDiagnosticLocation AllocLocation =
2405 PathDiagnosticLocation::createBegin(AllocStmt, SMgr,
2406 AllocNode->getLocationContext());
2407 Location = AllocLocation;
2408
2409 // Set uniqieing info, which will be used for unique the bug reports. The
2410 // leaks should be uniqued on the allocation site.
2411 UniqueingLocation = AllocLocation;
2412 UniqueingDecl = AllocNode->getLocationContext()->getDecl();
2413
Ted Kremenek6bd78702009-04-29 18:50:19 +00002414 // Fill in the description of the bug.
2415 Description.clear();
2416 llvm::raw_string_ostream os(Description);
Ted Kremenekf1e76672009-05-02 19:05:19 +00002417 os << "Potential leak ";
Jordy Rose184bd142011-08-24 22:39:09 +00002418 if (GCEnabled)
Ted Kremenekf1e76672009-05-02 19:05:19 +00002419 os << "(when using garbage collection) ";
Anna Zaks16f38312012-02-28 21:49:08 +00002420 os << "of an object";
Mike Stump11289f42009-09-09 15:08:12 +00002421
Ted Kremenek8671acb2013-04-16 21:44:22 +00002422 if (AllocBinding) {
Anna Zaks16f38312012-02-28 21:49:08 +00002423 os << " stored into '" << AllocBinding->getString() << '\'';
Ted Kremenek8671acb2013-04-16 21:44:22 +00002424 if (IncludeAllocationLine) {
2425 FullSourceLoc SL(AllocStmt->getLocStart(), Ctx.getSourceManager());
2426 os << " (allocated on line " << SL.getSpellingLineNumber() << ")";
2427 }
2428 }
Anna Zaks071a89c2011-08-19 23:21:56 +00002429
David Blaikie91e79022014-09-04 23:54:33 +00002430 addVisitor(llvm::make_unique<CFRefLeakReportVisitor>(sym, GCEnabled, Log));
Ted Kremenek6bd78702009-04-29 18:50:19 +00002431}
2432
2433//===----------------------------------------------------------------------===//
2434// Main checker logic.
2435//===----------------------------------------------------------------------===//
2436
Ted Kremenek70a87882009-11-25 22:17:44 +00002437namespace {
Jordy Rose75e680e2011-09-02 06:44:22 +00002438class RetainCountChecker
Jordy Rose5df640d2011-08-24 18:56:32 +00002439 : public Checker< check::Bind,
Jordy Rose78612762011-08-23 19:01:07 +00002440 check::DeadSymbols,
Jordy Rose5df640d2011-08-24 18:56:32 +00002441 check::EndAnalysis,
Anna Zaks3fdcc0b2013-01-03 00:25:29 +00002442 check::EndFunction,
Jordy Rose217eb902011-08-17 21:27:39 +00002443 check::PostStmt<BlockExpr>,
John McCall31168b02011-06-15 23:02:42 +00002444 check::PostStmt<CastExpr>,
Ted Kremenek415287d2012-03-06 20:06:12 +00002445 check::PostStmt<ObjCArrayLiteral>,
2446 check::PostStmt<ObjCDictionaryLiteral>,
Jordy Rose6393f822012-05-12 05:10:43 +00002447 check::PostStmt<ObjCBoxedExpr>,
Jordan Roseb3ad07e2014-03-25 17:10:58 +00002448 check::PostStmt<ObjCIvarRefExpr>,
Jordan Rose682b3162012-07-02 19:28:21 +00002449 check::PostCall,
Jordy Rose298cc4d2011-08-23 19:43:16 +00002450 check::PreStmt<ReturnStmt>,
Jordy Rose217eb902011-08-17 21:27:39 +00002451 check::RegionChanges,
Jordy Rose898a1482011-08-21 21:58:18 +00002452 eval::Assume,
2453 eval::Call > {
Ahmed Charlesb8984322014-03-07 20:03:18 +00002454 mutable std::unique_ptr<CFRefBug> useAfterRelease, releaseNotOwned;
2455 mutable std::unique_ptr<CFRefBug> deallocGC, deallocNotOwned;
2456 mutable std::unique_ptr<CFRefBug> overAutorelease, returnNotOwnedForOwned;
2457 mutable std::unique_ptr<CFRefBug> leakWithinFunction, leakAtReturn;
2458 mutable std::unique_ptr<CFRefBug> leakWithinFunctionGC, leakAtReturnGC;
Jordy Rose78612762011-08-23 19:01:07 +00002459
Anton Yartsev6a619222014-02-17 18:25:34 +00002460 typedef llvm::DenseMap<SymbolRef, const CheckerProgramPointTag *> SymbolTagMap;
Jordy Rose78612762011-08-23 19:01:07 +00002461
2462 // This map is only used to ensure proper deletion of any allocated tags.
2463 mutable SymbolTagMap DeadSymbolTags;
2464
Ahmed Charlesb8984322014-03-07 20:03:18 +00002465 mutable std::unique_ptr<RetainSummaryManager> Summaries;
2466 mutable std::unique_ptr<RetainSummaryManager> SummariesGC;
Jordy Rose5df640d2011-08-24 18:56:32 +00002467 mutable SummaryLogTy SummaryLog;
2468 mutable bool ShouldResetSummaryLog;
2469
Ted Kremenek8671acb2013-04-16 21:44:22 +00002470 /// Optional setting to indicate if leak reports should include
2471 /// the allocation line.
2472 mutable bool IncludeAllocationLine;
2473
Jordy Rosea8f99ba2011-08-20 21:17:59 +00002474public:
Ted Kremenek8671acb2013-04-16 21:44:22 +00002475 RetainCountChecker(AnalyzerOptions &AO)
2476 : ShouldResetSummaryLog(false),
2477 IncludeAllocationLine(shouldIncludeAllocationSiteInLeakDiagnostics(AO)) {}
Jordy Rose78612762011-08-23 19:01:07 +00002478
Jordy Rose75e680e2011-09-02 06:44:22 +00002479 virtual ~RetainCountChecker() {
Jordy Rose78612762011-08-23 19:01:07 +00002480 DeleteContainerSeconds(DeadSymbolTags);
2481 }
2482
Jordy Rose5df640d2011-08-24 18:56:32 +00002483 void checkEndAnalysis(ExplodedGraph &G, BugReporter &BR,
2484 ExprEngine &Eng) const {
2485 // FIXME: This is a hack to make sure the summary log gets cleared between
2486 // analyses of different code bodies.
2487 //
2488 // Why is this necessary? Because a checker's lifetime is tied to a
2489 // translation unit, but an ExplodedGraph's lifetime is just a code body.
2490 // Once in a blue moon, a new ExplodedNode will have the same address as an
2491 // old one with an associated summary, and the bug report visitor gets very
2492 // confused. (To make things worse, the summary lifetime is currently also
2493 // tied to a code body, so we get a crash instead of incorrect results.)
Jordy Rose95589f12011-08-24 09:27:24 +00002494 //
2495 // Why is this a bad solution? Because if the lifetime of the ExplodedGraph
2496 // changes, things will start going wrong again. Really the lifetime of this
2497 // log needs to be tied to either the specific nodes in it or the entire
2498 // ExplodedGraph, not to a specific part of the code being analyzed.
2499 //
Jordy Rose5df640d2011-08-24 18:56:32 +00002500 // (Also, having stateful local data means that the same checker can't be
2501 // used from multiple threads, but a lot of checkers have incorrect
2502 // assumptions about that anyway. So that wasn't a priority at the time of
2503 // this fix.)
Jordy Rose95589f12011-08-24 09:27:24 +00002504 //
Jordy Rose5df640d2011-08-24 18:56:32 +00002505 // This happens at the end of analysis, but bug reports are emitted /after/
2506 // this point. So we can't just clear the summary log now. Instead, we mark
2507 // that the next time we access the summary log, it should be cleared.
2508
2509 // If we never reset the summary log during /this/ code body analysis,
2510 // there were no new summaries. There might still have been summaries from
2511 // the /last/ analysis, so clear them out to make sure the bug report
2512 // visitors don't get confused.
2513 if (ShouldResetSummaryLog)
2514 SummaryLog.clear();
2515
2516 ShouldResetSummaryLog = !SummaryLog.empty();
Jordy Rose95589f12011-08-24 09:27:24 +00002517 }
2518
Jordy Rosec49ec532011-09-02 05:55:19 +00002519 CFRefBug *getLeakWithinFunctionBug(const LangOptions &LOpts,
2520 bool GCEnabled) const {
2521 if (GCEnabled) {
Jordy Rose15484da2011-08-25 01:14:38 +00002522 if (!leakWithinFunctionGC)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002523 leakWithinFunctionGC.reset(new Leak(this, "Leak of object when using "
2524 "garbage collection"));
Jordy Rosec49ec532011-09-02 05:55:19 +00002525 return leakWithinFunctionGC.get();
Jordy Rose15484da2011-08-25 01:14:38 +00002526 } else {
2527 if (!leakWithinFunction) {
Douglas Gregor79a91412011-09-13 17:21:33 +00002528 if (LOpts.getGC() == LangOptions::HybridGC) {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002529 leakWithinFunction.reset(new Leak(this,
2530 "Leak of object when not using "
Benjamin Kramerd1d76b22012-06-06 17:32:50 +00002531 "garbage collection (GC) in "
2532 "dual GC/non-GC code"));
Jordy Rose15484da2011-08-25 01:14:38 +00002533 } else {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002534 leakWithinFunction.reset(new Leak(this, "Leak"));
Jordy Rose15484da2011-08-25 01:14:38 +00002535 }
2536 }
Jordy Rosec49ec532011-09-02 05:55:19 +00002537 return leakWithinFunction.get();
Jordy Rose15484da2011-08-25 01:14:38 +00002538 }
2539 }
2540
Jordy Rosec49ec532011-09-02 05:55:19 +00002541 CFRefBug *getLeakAtReturnBug(const LangOptions &LOpts, bool GCEnabled) const {
2542 if (GCEnabled) {
Jordy Rose15484da2011-08-25 01:14:38 +00002543 if (!leakAtReturnGC)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002544 leakAtReturnGC.reset(new Leak(this,
2545 "Leak of returned object when using "
Benjamin Kramerd1d76b22012-06-06 17:32:50 +00002546 "garbage collection"));
Jordy Rosec49ec532011-09-02 05:55:19 +00002547 return leakAtReturnGC.get();
Jordy Rose15484da2011-08-25 01:14:38 +00002548 } else {
2549 if (!leakAtReturn) {
Douglas Gregor79a91412011-09-13 17:21:33 +00002550 if (LOpts.getGC() == LangOptions::HybridGC) {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002551 leakAtReturn.reset(new Leak(this,
2552 "Leak of returned object when not using "
Benjamin Kramerd1d76b22012-06-06 17:32:50 +00002553 "garbage collection (GC) in dual "
2554 "GC/non-GC code"));
Jordy Rose15484da2011-08-25 01:14:38 +00002555 } else {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002556 leakAtReturn.reset(new Leak(this, "Leak of returned object"));
Jordy Rose15484da2011-08-25 01:14:38 +00002557 }
2558 }
Jordy Rosec49ec532011-09-02 05:55:19 +00002559 return leakAtReturn.get();
Jordy Rose15484da2011-08-25 01:14:38 +00002560 }
2561 }
2562
Jordy Rosec49ec532011-09-02 05:55:19 +00002563 RetainSummaryManager &getSummaryManager(ASTContext &Ctx,
2564 bool GCEnabled) const {
2565 // FIXME: We don't support ARC being turned on and off during one analysis.
2566 // (nor, for that matter, do we support changing ASTContexts)
David Blaikiebbafb8a2012-03-11 07:00:24 +00002567 bool ARCEnabled = (bool)Ctx.getLangOpts().ObjCAutoRefCount;
Jordy Rosec49ec532011-09-02 05:55:19 +00002568 if (GCEnabled) {
2569 if (!SummariesGC)
Jordy Rose8b289a22011-08-25 00:10:37 +00002570 SummariesGC.reset(new RetainSummaryManager(Ctx, true, ARCEnabled));
Jordy Rosec49ec532011-09-02 05:55:19 +00002571 else
2572 assert(SummariesGC->isARCEnabled() == ARCEnabled);
Jordy Rose8b289a22011-08-25 00:10:37 +00002573 return *SummariesGC;
2574 } else {
Jordy Rosec49ec532011-09-02 05:55:19 +00002575 if (!Summaries)
Jordy Rose8b289a22011-08-25 00:10:37 +00002576 Summaries.reset(new RetainSummaryManager(Ctx, false, ARCEnabled));
Jordy Rosec49ec532011-09-02 05:55:19 +00002577 else
2578 assert(Summaries->isARCEnabled() == ARCEnabled);
Jordy Rose8b289a22011-08-25 00:10:37 +00002579 return *Summaries;
2580 }
2581 }
2582
Jordy Rosec49ec532011-09-02 05:55:19 +00002583 RetainSummaryManager &getSummaryManager(CheckerContext &C) const {
2584 return getSummaryManager(C.getASTContext(), C.isObjCGCEnabled());
2585 }
2586
Ted Kremenek49b1e382012-01-26 21:29:00 +00002587 void printState(raw_ostream &Out, ProgramStateRef State,
Craig Topperfb6b25b2014-03-15 04:29:04 +00002588 const char *NL, const char *Sep) const override;
Jordy Rose58a20d32011-08-28 19:11:56 +00002589
Anna Zaks3e0f4152011-10-06 00:43:15 +00002590 void checkBind(SVal loc, SVal val, const Stmt *S, CheckerContext &C) const;
Jordy Rose5c252ef2011-08-20 21:16:58 +00002591 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
2592 void checkPostStmt(const CastExpr *CE, CheckerContext &C) const;
John McCall31168b02011-06-15 23:02:42 +00002593
Ted Kremenek415287d2012-03-06 20:06:12 +00002594 void checkPostStmt(const ObjCArrayLiteral *AL, CheckerContext &C) const;
2595 void checkPostStmt(const ObjCDictionaryLiteral *DL, CheckerContext &C) const;
Jordy Rose6393f822012-05-12 05:10:43 +00002596 void checkPostStmt(const ObjCBoxedExpr *BE, CheckerContext &C) const;
2597
Jordan Roseb3ad07e2014-03-25 17:10:58 +00002598 void checkPostStmt(const ObjCIvarRefExpr *IRE, CheckerContext &C) const;
2599
Jordan Rose682b3162012-07-02 19:28:21 +00002600 void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
Ted Kremenek415287d2012-03-06 20:06:12 +00002601
Jordan Roseeec15392012-07-02 19:27:43 +00002602 void checkSummary(const RetainSummary &Summ, const CallEvent &Call,
Jordy Rosed188d662011-08-28 05:16:28 +00002603 CheckerContext &C) const;
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002604
Anna Zaks25612732012-08-29 23:23:43 +00002605 void processSummaryOfInlined(const RetainSummary &Summ,
2606 const CallEvent &Call,
2607 CheckerContext &C) const;
2608
Jordy Rose898a1482011-08-21 21:58:18 +00002609 bool evalCall(const CallExpr *CE, CheckerContext &C) const;
2610
Ted Kremenek49b1e382012-01-26 21:29:00 +00002611 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Jordy Rose5c252ef2011-08-20 21:16:58 +00002612 bool Assumption) const;
Jordy Rose217eb902011-08-17 21:27:39 +00002613
Ted Kremenek49b1e382012-01-26 21:29:00 +00002614 ProgramStateRef
2615 checkRegionChanges(ProgramStateRef state,
Anna Zaksdc154152012-12-20 00:38:25 +00002616 const InvalidatedSymbols *invalidated,
Jordy Rose1fad6632011-08-27 22:51:26 +00002617 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks3d348342012-02-14 21:55:24 +00002618 ArrayRef<const MemRegion *> Regions,
Jordan Rose742920c2012-07-02 19:27:35 +00002619 const CallEvent *Call) const;
Jordy Rose5c252ef2011-08-20 21:16:58 +00002620
Ted Kremenek49b1e382012-01-26 21:29:00 +00002621 bool wantsRegionChangeUpdate(ProgramStateRef state) const {
Jordy Rosea8f99ba2011-08-20 21:17:59 +00002622 return true;
Jordy Rose5c252ef2011-08-20 21:16:58 +00002623 }
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002624
Jordy Rose298cc4d2011-08-23 19:43:16 +00002625 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
2626 void checkReturnWithRetEffect(const ReturnStmt *S, CheckerContext &C,
2627 ExplodedNode *Pred, RetEffect RE, RefVal X,
Ted Kremenek49b1e382012-01-26 21:29:00 +00002628 SymbolRef Sym, ProgramStateRef state) const;
Jordy Rose298cc4d2011-08-23 19:43:16 +00002629
Jordy Rose78612762011-08-23 19:01:07 +00002630 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Anna Zaks3fdcc0b2013-01-03 00:25:29 +00002631 void checkEndFunction(CheckerContext &C) const;
Jordy Rose78612762011-08-23 19:01:07 +00002632
Ted Kremenek49b1e382012-01-26 21:29:00 +00002633 ProgramStateRef updateSymbol(ProgramStateRef state, SymbolRef sym,
Anna Zaks25612732012-08-29 23:23:43 +00002634 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
2635 CheckerContext &C) const;
Jordy Rosebf77e512011-08-23 20:27:16 +00002636
Ted Kremenek49b1e382012-01-26 21:29:00 +00002637 void processNonLeakError(ProgramStateRef St, SourceRange ErrorRange,
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002638 RefVal::Kind ErrorKind, SymbolRef Sym,
2639 CheckerContext &C) const;
Ted Kremenek415287d2012-03-06 20:06:12 +00002640
2641 void processObjCLiterals(CheckerContext &C, const Expr *Ex) const;
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002642
Jordy Rose78612762011-08-23 19:01:07 +00002643 const ProgramPointTag *getDeadSymbolTag(SymbolRef sym) const;
2644
Ted Kremenek49b1e382012-01-26 21:29:00 +00002645 ProgramStateRef handleSymbolDeath(ProgramStateRef state,
Anna Zaksf5788c72012-08-14 00:36:15 +00002646 SymbolRef sid, RefVal V,
2647 SmallVectorImpl<SymbolRef> &Leaked) const;
Jordy Rose78612762011-08-23 19:01:07 +00002648
Jordan Roseff03c1d2012-12-06 18:58:18 +00002649 ProgramStateRef
Jordan Rose9f61f8a2012-08-18 00:30:16 +00002650 handleAutoreleaseCounts(ProgramStateRef state, ExplodedNode *Pred,
2651 const ProgramPointTag *Tag, CheckerContext &Ctx,
2652 SymbolRef Sym, RefVal V) const;
Jordy Rose6763e382011-08-23 20:07:14 +00002653
Ted Kremenek49b1e382012-01-26 21:29:00 +00002654 ExplodedNode *processLeaks(ProgramStateRef state,
Jordy Rose78612762011-08-23 19:01:07 +00002655 SmallVectorImpl<SymbolRef> &Leaked,
Anna Zaks58734db2011-10-25 19:57:11 +00002656 CheckerContext &Ctx,
Craig Topper0dbb7832014-05-27 02:45:47 +00002657 ExplodedNode *Pred = nullptr) const;
Ted Kremenek70a87882009-11-25 22:17:44 +00002658};
2659} // end anonymous namespace
2660
Jordy Rose217eb902011-08-17 21:27:39 +00002661namespace {
2662class StopTrackingCallback : public SymbolVisitor {
Ted Kremenek49b1e382012-01-26 21:29:00 +00002663 ProgramStateRef state;
Jordy Rose217eb902011-08-17 21:27:39 +00002664public:
Ted Kremenek49b1e382012-01-26 21:29:00 +00002665 StopTrackingCallback(ProgramStateRef st) : state(st) {}
2666 ProgramStateRef getState() const { return state; }
Jordy Rose217eb902011-08-17 21:27:39 +00002667
Craig Topperfb6b25b2014-03-15 04:29:04 +00002668 bool VisitSymbol(SymbolRef sym) override {
Jordy Rose217eb902011-08-17 21:27:39 +00002669 state = state->remove<RefBindings>(sym);
2670 return true;
2671 }
2672};
2673} // end anonymous namespace
2674
Jordy Rose75e680e2011-09-02 06:44:22 +00002675//===----------------------------------------------------------------------===//
2676// Handle statements that may have an effect on refcounts.
2677//===----------------------------------------------------------------------===//
Jordy Rose217eb902011-08-17 21:27:39 +00002678
Jordy Rose75e680e2011-09-02 06:44:22 +00002679void RetainCountChecker::checkPostStmt(const BlockExpr *BE,
2680 CheckerContext &C) const {
Jordy Rose217eb902011-08-17 21:27:39 +00002681
Jordy Rose75e680e2011-09-02 06:44:22 +00002682 // Scan the BlockDecRefExprs for any object the retain count checker
Ted Kremenekbd862712010-07-01 20:16:50 +00002683 // may be tracking.
John McCallc63de662011-02-02 13:00:07 +00002684 if (!BE->getBlockDecl()->hasCaptures())
Ted Kremenekf89dcda2009-11-26 02:38:19 +00002685 return;
Ted Kremenekbd862712010-07-01 20:16:50 +00002686
Ted Kremenek49b1e382012-01-26 21:29:00 +00002687 ProgramStateRef state = C.getState();
Ted Kremenekf89dcda2009-11-26 02:38:19 +00002688 const BlockDataRegion *R =
Ted Kremenek632e3b72012-01-06 22:09:28 +00002689 cast<BlockDataRegion>(state->getSVal(BE,
2690 C.getLocationContext()).getAsRegion());
Ted Kremenekbd862712010-07-01 20:16:50 +00002691
Ted Kremenekf89dcda2009-11-26 02:38:19 +00002692 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
2693 E = R->referenced_vars_end();
Ted Kremenekbd862712010-07-01 20:16:50 +00002694
Ted Kremenekf89dcda2009-11-26 02:38:19 +00002695 if (I == E)
2696 return;
Ted Kremenekbd862712010-07-01 20:16:50 +00002697
Ted Kremenek04af9f22009-12-07 22:05:27 +00002698 // FIXME: For now we invalidate the tracking of all symbols passed to blocks
2699 // via captured variables, even though captured variables result in a copy
2700 // and in implicit increment/decrement of a retain count.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002701 SmallVector<const MemRegion*, 10> Regions;
Anna Zaksc9abbe22011-10-26 21:06:44 +00002702 const LocationContext *LC = C.getLocationContext();
Ted Kremenek90af9092010-12-02 07:49:45 +00002703 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
Ted Kremenekbd862712010-07-01 20:16:50 +00002704
Ted Kremenek04af9f22009-12-07 22:05:27 +00002705 for ( ; I != E; ++I) {
Ted Kremenekbcf90532012-12-06 07:17:20 +00002706 const VarRegion *VR = I.getCapturedRegion();
Ted Kremenek04af9f22009-12-07 22:05:27 +00002707 if (VR->getSuperRegion() == R) {
2708 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2709 }
2710 Regions.push_back(VR);
2711 }
Ted Kremenekbd862712010-07-01 20:16:50 +00002712
Ted Kremenek04af9f22009-12-07 22:05:27 +00002713 state =
2714 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
2715 Regions.data() + Regions.size()).getState();
Anna Zaksda4c8d62011-10-26 21:06:34 +00002716 C.addTransition(state);
Ted Kremenekf89dcda2009-11-26 02:38:19 +00002717}
2718
Jordy Rose75e680e2011-09-02 06:44:22 +00002719void RetainCountChecker::checkPostStmt(const CastExpr *CE,
2720 CheckerContext &C) const {
John McCall31168b02011-06-15 23:02:42 +00002721 const ObjCBridgedCastExpr *BE = dyn_cast<ObjCBridgedCastExpr>(CE);
2722 if (!BE)
2723 return;
2724
John McCall640767f2011-06-17 06:50:50 +00002725 ArgEffect AE = IncRef;
John McCall31168b02011-06-15 23:02:42 +00002726
2727 switch (BE->getBridgeKind()) {
2728 case clang::OBC_Bridge:
2729 // Do nothing.
2730 return;
2731 case clang::OBC_BridgeRetained:
2732 AE = IncRef;
2733 break;
2734 case clang::OBC_BridgeTransfer:
Benjamin Kramer1d5d6342013-10-20 11:53:20 +00002735 AE = DecRefBridgedTransferred;
John McCall31168b02011-06-15 23:02:42 +00002736 break;
2737 }
2738
Ted Kremenek49b1e382012-01-26 21:29:00 +00002739 ProgramStateRef state = C.getState();
Ted Kremenek632e3b72012-01-06 22:09:28 +00002740 SymbolRef Sym = state->getSVal(CE, C.getLocationContext()).getAsLocSymbol();
John McCall31168b02011-06-15 23:02:42 +00002741 if (!Sym)
2742 return;
Anna Zaksf5788c72012-08-14 00:36:15 +00002743 const RefVal* T = getRefBinding(state, Sym);
John McCall31168b02011-06-15 23:02:42 +00002744 if (!T)
2745 return;
2746
John McCall31168b02011-06-15 23:02:42 +00002747 RefVal::Kind hasErr = (RefVal::Kind) 0;
Jordy Rosec49ec532011-09-02 05:55:19 +00002748 state = updateSymbol(state, Sym, *T, AE, hasErr, C);
John McCall31168b02011-06-15 23:02:42 +00002749
2750 if (hasErr) {
Jordy Rosebf77e512011-08-23 20:27:16 +00002751 // FIXME: If we get an error during a bridge cast, should we report it?
2752 // Should we assert that there is no error?
John McCall31168b02011-06-15 23:02:42 +00002753 return;
2754 }
2755
Anna Zaksda4c8d62011-10-26 21:06:34 +00002756 C.addTransition(state);
John McCall31168b02011-06-15 23:02:42 +00002757}
2758
Ted Kremenek415287d2012-03-06 20:06:12 +00002759void RetainCountChecker::processObjCLiterals(CheckerContext &C,
2760 const Expr *Ex) const {
2761 ProgramStateRef state = C.getState();
2762 const ExplodedNode *pred = C.getPredecessor();
2763 for (Stmt::const_child_iterator it = Ex->child_begin(), et = Ex->child_end() ;
2764 it != et ; ++it) {
2765 const Stmt *child = *it;
2766 SVal V = state->getSVal(child, pred->getLocationContext());
2767 if (SymbolRef sym = V.getAsSymbol())
Anna Zaksf5788c72012-08-14 00:36:15 +00002768 if (const RefVal* T = getRefBinding(state, sym)) {
Ted Kremenek415287d2012-03-06 20:06:12 +00002769 RefVal::Kind hasErr = (RefVal::Kind) 0;
2770 state = updateSymbol(state, sym, *T, MayEscape, hasErr, C);
2771 if (hasErr) {
2772 processNonLeakError(state, child->getSourceRange(), hasErr, sym, C);
2773 return;
2774 }
2775 }
2776 }
2777
2778 // Return the object as autoreleased.
2779 // RetEffect RE = RetEffect::MakeNotOwned(RetEffect::ObjC);
2780 if (SymbolRef sym =
2781 state->getSVal(Ex, pred->getLocationContext()).getAsSymbol()) {
2782 QualType ResultTy = Ex->getType();
Anna Zaksf5788c72012-08-14 00:36:15 +00002783 state = setRefBinding(state, sym,
2784 RefVal::makeNotOwned(RetEffect::ObjC, ResultTy));
Ted Kremenek415287d2012-03-06 20:06:12 +00002785 }
2786
2787 C.addTransition(state);
2788}
2789
2790void RetainCountChecker::checkPostStmt(const ObjCArrayLiteral *AL,
2791 CheckerContext &C) const {
2792 // Apply the 'MayEscape' to all values.
2793 processObjCLiterals(C, AL);
2794}
2795
2796void RetainCountChecker::checkPostStmt(const ObjCDictionaryLiteral *DL,
2797 CheckerContext &C) const {
2798 // Apply the 'MayEscape' to all keys and values.
2799 processObjCLiterals(C, DL);
2800}
2801
Jordy Rose6393f822012-05-12 05:10:43 +00002802void RetainCountChecker::checkPostStmt(const ObjCBoxedExpr *Ex,
2803 CheckerContext &C) const {
2804 const ExplodedNode *Pred = C.getPredecessor();
2805 const LocationContext *LCtx = Pred->getLocationContext();
2806 ProgramStateRef State = Pred->getState();
2807
2808 if (SymbolRef Sym = State->getSVal(Ex, LCtx).getAsSymbol()) {
2809 QualType ResultTy = Ex->getType();
Anna Zaksf5788c72012-08-14 00:36:15 +00002810 State = setRefBinding(State, Sym,
2811 RefVal::makeNotOwned(RetEffect::ObjC, ResultTy));
Jordy Rose6393f822012-05-12 05:10:43 +00002812 }
2813
2814 C.addTransition(State);
2815}
2816
Jordan Rosecb5386c2015-02-04 19:24:52 +00002817static bool wasLoadedFromIvar(SymbolRef Sym) {
2818 if (auto DerivedVal = dyn_cast<SymbolDerived>(Sym))
2819 return isa<ObjCIvarRegion>(DerivedVal->getRegion());
2820 if (auto RegionVal = dyn_cast<SymbolRegionValue>(Sym))
2821 return isa<ObjCIvarRegion>(RegionVal->getRegion());
2822 return false;
2823}
2824
2825/// Returns the property that claims this instance variable, if any.
2826static const ObjCPropertyDecl *findPropForIvar(const ObjCIvarDecl *Ivar) {
2827 auto IsPropertyForIvar = [Ivar](const ObjCPropertyDecl *Prop) -> bool {
2828 return Prop->getPropertyIvarDecl() == Ivar;
2829 };
2830
2831 const ObjCInterfaceDecl *Interface = Ivar->getContainingInterface();
2832 auto PropIter = std::find_if(Interface->prop_begin(), Interface->prop_end(),
2833 IsPropertyForIvar);
2834 if (PropIter != Interface->prop_end()) {
2835 return *PropIter;
2836 }
2837
2838 for (auto Extension : Interface->visible_extensions()) {
2839 PropIter = std::find_if(Extension->prop_begin(), Extension->prop_end(),
2840 IsPropertyForIvar);
2841 if (PropIter != Extension->prop_end())
2842 return *PropIter;
2843 }
2844
2845 return nullptr;
2846}
2847
Jordan Roseb3ad07e2014-03-25 17:10:58 +00002848void RetainCountChecker::checkPostStmt(const ObjCIvarRefExpr *IRE,
2849 CheckerContext &C) const {
Jordan Rosecb5386c2015-02-04 19:24:52 +00002850 Optional<Loc> IVarLoc = C.getSVal(IRE).getAs<Loc>();
2851 if (!IVarLoc)
2852 return;
2853
Jordan Roseb3ad07e2014-03-25 17:10:58 +00002854 ProgramStateRef State = C.getState();
Jordan Rosecb5386c2015-02-04 19:24:52 +00002855 SymbolRef Sym = State->getSVal(*IVarLoc).getAsSymbol();
2856 if (!Sym)
2857 return;
2858
2859 // Accessing an ivar directly is unusual. If we've done that, be more
2860 // forgiving about what the surrounding code is allowed to do.
2861
2862 QualType Ty = Sym->getType();
2863 RetEffect::ObjKind Kind;
2864 if (Ty->isObjCRetainableType())
2865 Kind = RetEffect::ObjC;
2866 else if (coreFoundation::isCFObjectRef(Ty))
2867 Kind = RetEffect::CF;
2868 else
2869 return;
2870
2871 if (!wasLoadedFromIvar(Sym))
2872 return;
2873
2874 if (const RefVal *RV = getRefBinding(State, Sym)) {
2875 // If we've seen this symbol before, or we're only seeing it now because
2876 // of something the analyzer has synthesized, don't do anything.
2877 if (RV->getIvarAccessHistory() != RefVal::IvarAccessHistory::None ||
2878 isSynthesizedAccessor(C.getStackFrame())) {
2879 return;
2880 }
2881
2882 // Also don't do anything if the ivar is unretained. If so, we know that
2883 // there's no outstanding retain count for the value.
2884 if (const ObjCPropertyDecl *Prop = findPropForIvar(IRE->getDecl()))
2885 if (!Prop->isRetaining())
2886 return;
2887
2888 // Note that this value has been loaded from an ivar.
2889 C.addTransition(setRefBinding(State, Sym, RV->withIvarAccess()));
2890 return;
2891 }
2892
2893 RefVal PlusZero = RefVal::makeNotOwned(Kind, Ty);
2894
2895 // In a synthesized accessor, the effective retain count is +0.
2896 if (isSynthesizedAccessor(C.getStackFrame())) {
2897 C.addTransition(setRefBinding(State, Sym, PlusZero));
2898 return;
2899 }
2900
2901 // Try to find the property associated with this ivar.
2902 const ObjCPropertyDecl *Prop = findPropForIvar(IRE->getDecl());
2903
2904 if (Prop && !Prop->isRetaining())
2905 State = setRefBinding(State, Sym, PlusZero);
2906 else
2907 State = setRefBinding(State, Sym, PlusZero.withIvarAccess());
2908
Jordan Roseb3ad07e2014-03-25 17:10:58 +00002909 C.addTransition(State);
2910}
2911
Jordan Rose682b3162012-07-02 19:28:21 +00002912void RetainCountChecker::checkPostCall(const CallEvent &Call,
2913 CheckerContext &C) const {
Jordan Rose682b3162012-07-02 19:28:21 +00002914 RetainSummaryManager &Summaries = getSummaryManager(C);
2915 const RetainSummary *Summ = Summaries.getSummary(Call, C.getState());
Anna Zaks25612732012-08-29 23:23:43 +00002916
2917 if (C.wasInlined) {
2918 processSummaryOfInlined(*Summ, Call, C);
2919 return;
2920 }
Jordan Rose682b3162012-07-02 19:28:21 +00002921 checkSummary(*Summ, Call, C);
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002922}
2923
Jordy Rose75e680e2011-09-02 06:44:22 +00002924/// GetReturnType - Used to get the return type of a message expression or
2925/// function call with the intention of affixing that type to a tracked symbol.
Sylvestre Ledru830885c2012-07-23 08:59:39 +00002926/// While the return type can be queried directly from RetEx, when
Jordy Rose75e680e2011-09-02 06:44:22 +00002927/// invoking class methods we augment to the return type to be that of
2928/// a pointer to the class (as opposed it just being id).
2929// FIXME: We may be able to do this with related result types instead.
2930// This function is probably overestimating.
2931static QualType GetReturnType(const Expr *RetE, ASTContext &Ctx) {
2932 QualType RetTy = RetE->getType();
2933 // If RetE is not a message expression just return its type.
2934 // If RetE is a message expression, return its types if it is something
2935 /// more specific than id.
2936 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RetE))
2937 if (const ObjCObjectPointerType *PT = RetTy->getAs<ObjCObjectPointerType>())
2938 if (PT->isObjCQualifiedIdType() || PT->isObjCIdType() ||
2939 PT->isObjCClassType()) {
2940 // At this point we know the return type of the message expression is
2941 // id, id<...>, or Class. If we have an ObjCInterfaceDecl, we know this
2942 // is a call to a class method whose type we can resolve. In such
2943 // cases, promote the return type to XXX* (where XXX is the class).
2944 const ObjCInterfaceDecl *D = ME->getReceiverInterface();
2945 return !D ? RetTy :
2946 Ctx.getObjCObjectPointerType(Ctx.getObjCInterfaceType(D));
2947 }
2948
2949 return RetTy;
2950}
2951
Anna Zaks25612732012-08-29 23:23:43 +00002952// We don't always get the exact modeling of the function with regards to the
2953// retain count checker even when the function is inlined. For example, we need
2954// to stop tracking the symbols which were marked with StopTrackingHard.
2955void RetainCountChecker::processSummaryOfInlined(const RetainSummary &Summ,
2956 const CallEvent &CallOrMsg,
2957 CheckerContext &C) const {
2958 ProgramStateRef state = C.getState();
2959
2960 // Evaluate the effect of the arguments.
2961 for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
2962 if (Summ.getArg(idx) == StopTrackingHard) {
2963 SVal V = CallOrMsg.getArgSVal(idx);
2964 if (SymbolRef Sym = V.getAsLocSymbol()) {
2965 state = removeRefBinding(state, Sym);
2966 }
2967 }
2968 }
2969
2970 // Evaluate the effect on the message receiver.
2971 const ObjCMethodCall *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg);
2972 if (MsgInvocation) {
2973 if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
2974 if (Summ.getReceiverEffect() == StopTrackingHard) {
2975 state = removeRefBinding(state, Sym);
2976 }
2977 }
2978 }
2979
2980 // Consult the summary for the return value.
2981 RetEffect RE = Summ.getRetEffect();
2982 if (RE.getKind() == RetEffect::NoRetHard) {
Jordan Rose829c3832012-11-02 23:49:29 +00002983 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
Anna Zaks25612732012-08-29 23:23:43 +00002984 if (Sym)
2985 state = removeRefBinding(state, Sym);
2986 }
2987
2988 C.addTransition(state);
2989}
2990
Jordy Rose75e680e2011-09-02 06:44:22 +00002991void RetainCountChecker::checkSummary(const RetainSummary &Summ,
Jordan Roseeec15392012-07-02 19:27:43 +00002992 const CallEvent &CallOrMsg,
Jordy Rose75e680e2011-09-02 06:44:22 +00002993 CheckerContext &C) const {
Ted Kremenek49b1e382012-01-26 21:29:00 +00002994 ProgramStateRef state = C.getState();
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002995
2996 // Evaluate the effect of the arguments.
2997 RefVal::Kind hasErr = (RefVal::Kind) 0;
2998 SourceRange ErrorRange;
Craig Topper0dbb7832014-05-27 02:45:47 +00002999 SymbolRef ErrorSym = nullptr;
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003000
3001 for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
Jordy Rose1fad6632011-08-27 22:51:26 +00003002 SVal V = CallOrMsg.getArgSVal(idx);
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003003
3004 if (SymbolRef Sym = V.getAsLocSymbol()) {
Anna Zaksf5788c72012-08-14 00:36:15 +00003005 if (const RefVal *T = getRefBinding(state, Sym)) {
Jordy Rosec49ec532011-09-02 05:55:19 +00003006 state = updateSymbol(state, Sym, *T, Summ.getArg(idx), hasErr, C);
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003007 if (hasErr) {
3008 ErrorRange = CallOrMsg.getArgSourceRange(idx);
3009 ErrorSym = Sym;
3010 break;
3011 }
3012 }
3013 }
3014 }
3015
3016 // Evaluate the effect on the message receiver.
3017 bool ReceiverIsTracked = false;
Jordan Roseeec15392012-07-02 19:27:43 +00003018 if (!hasErr) {
Jordan Rose6bad4902012-07-02 19:27:56 +00003019 const ObjCMethodCall *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg);
Jordan Roseeec15392012-07-02 19:27:43 +00003020 if (MsgInvocation) {
3021 if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
Anna Zaksf5788c72012-08-14 00:36:15 +00003022 if (const RefVal *T = getRefBinding(state, Sym)) {
Jordan Roseeec15392012-07-02 19:27:43 +00003023 ReceiverIsTracked = true;
3024 state = updateSymbol(state, Sym, *T, Summ.getReceiverEffect(),
Anna Zaks25612732012-08-29 23:23:43 +00003025 hasErr, C);
Jordan Roseeec15392012-07-02 19:27:43 +00003026 if (hasErr) {
Jordan Rose627b0462012-07-18 21:59:51 +00003027 ErrorRange = MsgInvocation->getOriginExpr()->getReceiverRange();
Jordan Roseeec15392012-07-02 19:27:43 +00003028 ErrorSym = Sym;
3029 }
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003030 }
3031 }
3032 }
3033 }
3034
3035 // Process any errors.
3036 if (hasErr) {
3037 processNonLeakError(state, ErrorRange, hasErr, ErrorSym, C);
3038 return;
3039 }
3040
3041 // Consult the summary for the return value.
3042 RetEffect RE = Summ.getRetEffect();
3043
3044 if (RE.getKind() == RetEffect::OwnedWhenTrackedReceiver) {
Jordy Rose8b289a22011-08-25 00:10:37 +00003045 if (ReceiverIsTracked)
Jordy Rosec49ec532011-09-02 05:55:19 +00003046 RE = getSummaryManager(C).getObjAllocRetEffect();
Jordy Rose8b289a22011-08-25 00:10:37 +00003047 else
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003048 RE = RetEffect::MakeNoRet();
3049 }
3050
3051 switch (RE.getKind()) {
3052 default:
David Blaikie8a40f702012-01-17 06:56:22 +00003053 llvm_unreachable("Unhandled RetEffect.");
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003054
3055 case RetEffect::NoRet:
Anna Zaks25612732012-08-29 23:23:43 +00003056 case RetEffect::NoRetHard:
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003057 // No work necessary.
3058 break;
3059
3060 case RetEffect::OwnedAllocatedSymbol:
3061 case RetEffect::OwnedSymbol: {
Jordan Rose829c3832012-11-02 23:49:29 +00003062 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003063 if (!Sym)
3064 break;
3065
Jordan Roseeec15392012-07-02 19:27:43 +00003066 // Use the result type from the CallEvent as it automatically adjusts
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003067 // for methods/functions that return references.
Jordan Roseeec15392012-07-02 19:27:43 +00003068 QualType ResultTy = CallOrMsg.getResultType();
Anna Zaksf5788c72012-08-14 00:36:15 +00003069 state = setRefBinding(state, Sym, RefVal::makeOwned(RE.getObjKind(),
3070 ResultTy));
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003071
3072 // FIXME: Add a flag to the checker where allocations are assumed to
Anna Zaks21487f72012-08-14 15:39:13 +00003073 // *not* fail.
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003074 break;
3075 }
3076
3077 case RetEffect::GCNotOwnedSymbol:
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003078 case RetEffect::NotOwnedSymbol: {
3079 const Expr *Ex = CallOrMsg.getOriginExpr();
Jordan Rose829c3832012-11-02 23:49:29 +00003080 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003081 if (!Sym)
3082 break;
Ted Kremenekbe400842012-10-12 22:56:45 +00003083 assert(Ex);
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003084 // Use GetReturnType in order to give [NSFoo alloc] the type NSFoo *.
3085 QualType ResultTy = GetReturnType(Ex, C.getASTContext());
Anna Zaksf5788c72012-08-14 00:36:15 +00003086 state = setRefBinding(state, Sym, RefVal::makeNotOwned(RE.getObjKind(),
3087 ResultTy));
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003088 break;
3089 }
3090 }
3091
3092 // This check is actually necessary; otherwise the statement builder thinks
3093 // we've hit a previously-found path.
3094 // Normally addTransition takes care of this, but we want the node pointer.
3095 ExplodedNode *NewNode;
3096 if (state == C.getState()) {
3097 NewNode = C.getPredecessor();
3098 } else {
Anna Zaksda4c8d62011-10-26 21:06:34 +00003099 NewNode = C.addTransition(state);
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003100 }
3101
Jordy Rose5df640d2011-08-24 18:56:32 +00003102 // Annotate the node with summary we used.
3103 if (NewNode) {
3104 // FIXME: This is ugly. See checkEndAnalysis for why it's necessary.
3105 if (ShouldResetSummaryLog) {
3106 SummaryLog.clear();
3107 ShouldResetSummaryLog = false;
3108 }
Jordy Rose20d4e682011-08-23 20:55:48 +00003109 SummaryLog[NewNode] = &Summ;
Jordy Rose5df640d2011-08-24 18:56:32 +00003110 }
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003111}
3112
Jordy Rosebf77e512011-08-23 20:27:16 +00003113
Ted Kremenek49b1e382012-01-26 21:29:00 +00003114ProgramStateRef
3115RetainCountChecker::updateSymbol(ProgramStateRef state, SymbolRef sym,
Jordy Rose75e680e2011-09-02 06:44:22 +00003116 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
3117 CheckerContext &C) const {
Jordy Rosebf77e512011-08-23 20:27:16 +00003118 // In GC mode [... release] and [... retain] do nothing.
Jordy Rose75e680e2011-09-02 06:44:22 +00003119 // In ARC mode they shouldn't exist at all, but we just ignore them.
Jordy Rosec49ec532011-09-02 05:55:19 +00003120 bool IgnoreRetainMsg = C.isObjCGCEnabled();
3121 if (!IgnoreRetainMsg)
David Blaikiebbafb8a2012-03-11 07:00:24 +00003122 IgnoreRetainMsg = (bool)C.getASTContext().getLangOpts().ObjCAutoRefCount;
Jordy Rosec49ec532011-09-02 05:55:19 +00003123
Jordy Rosebf77e512011-08-23 20:27:16 +00003124 switch (E) {
Jordan Roseeec15392012-07-02 19:27:43 +00003125 default:
3126 break;
3127 case IncRefMsg:
3128 E = IgnoreRetainMsg ? DoNothing : IncRef;
3129 break;
3130 case DecRefMsg:
3131 E = IgnoreRetainMsg ? DoNothing : DecRef;
3132 break;
Anna Zaks25612732012-08-29 23:23:43 +00003133 case DecRefMsgAndStopTrackingHard:
3134 E = IgnoreRetainMsg ? StopTracking : DecRefAndStopTrackingHard;
Jordan Roseeec15392012-07-02 19:27:43 +00003135 break;
3136 case MakeCollectable:
3137 E = C.isObjCGCEnabled() ? DecRef : DoNothing;
3138 break;
Jordy Rosebf77e512011-08-23 20:27:16 +00003139 }
3140
3141 // Handle all use-after-releases.
Jordy Rosec49ec532011-09-02 05:55:19 +00003142 if (!C.isObjCGCEnabled() && V.getKind() == RefVal::Released) {
Jordy Rosebf77e512011-08-23 20:27:16 +00003143 V = V ^ RefVal::ErrorUseAfterRelease;
3144 hasErr = V.getKind();
Anna Zaksf5788c72012-08-14 00:36:15 +00003145 return setRefBinding(state, sym, V);
Jordy Rosebf77e512011-08-23 20:27:16 +00003146 }
3147
3148 switch (E) {
3149 case DecRefMsg:
3150 case IncRefMsg:
3151 case MakeCollectable:
Anna Zaks25612732012-08-29 23:23:43 +00003152 case DecRefMsgAndStopTrackingHard:
Jordy Rosebf77e512011-08-23 20:27:16 +00003153 llvm_unreachable("DecRefMsg/IncRefMsg/MakeCollectable already converted");
Jordy Rosebf77e512011-08-23 20:27:16 +00003154
3155 case Dealloc:
3156 // Any use of -dealloc in GC is *bad*.
Jordy Rosec49ec532011-09-02 05:55:19 +00003157 if (C.isObjCGCEnabled()) {
Jordy Rosebf77e512011-08-23 20:27:16 +00003158 V = V ^ RefVal::ErrorDeallocGC;
3159 hasErr = V.getKind();
3160 break;
3161 }
3162
3163 switch (V.getKind()) {
3164 default:
3165 llvm_unreachable("Invalid RefVal state for an explicit dealloc.");
Jordy Rosebf77e512011-08-23 20:27:16 +00003166 case RefVal::Owned:
3167 // The object immediately transitions to the released state.
3168 V = V ^ RefVal::Released;
3169 V.clearCounts();
Anna Zaksf5788c72012-08-14 00:36:15 +00003170 return setRefBinding(state, sym, V);
Jordy Rosebf77e512011-08-23 20:27:16 +00003171 case RefVal::NotOwned:
3172 V = V ^ RefVal::ErrorDeallocNotOwned;
3173 hasErr = V.getKind();
3174 break;
3175 }
3176 break;
3177
Jordy Rosebf77e512011-08-23 20:27:16 +00003178 case MayEscape:
3179 if (V.getKind() == RefVal::Owned) {
3180 V = V ^ RefVal::NotOwned;
3181 break;
3182 }
3183
3184 // Fall-through.
3185
Jordy Rosebf77e512011-08-23 20:27:16 +00003186 case DoNothing:
3187 return state;
3188
3189 case Autorelease:
Jordy Rosec49ec532011-09-02 05:55:19 +00003190 if (C.isObjCGCEnabled())
Jordy Rosebf77e512011-08-23 20:27:16 +00003191 return state;
Jordy Rosebf77e512011-08-23 20:27:16 +00003192 // Update the autorelease counts.
Jordy Rosebf77e512011-08-23 20:27:16 +00003193 V = V.autorelease();
3194 break;
3195
3196 case StopTracking:
Anna Zaks25612732012-08-29 23:23:43 +00003197 case StopTrackingHard:
Anna Zaksf5788c72012-08-14 00:36:15 +00003198 return removeRefBinding(state, sym);
Jordy Rosebf77e512011-08-23 20:27:16 +00003199
3200 case IncRef:
3201 switch (V.getKind()) {
3202 default:
3203 llvm_unreachable("Invalid RefVal state for a retain.");
Jordy Rosebf77e512011-08-23 20:27:16 +00003204 case RefVal::Owned:
3205 case RefVal::NotOwned:
3206 V = V + 1;
3207 break;
3208 case RefVal::Released:
3209 // Non-GC cases are handled above.
Jordy Rosec49ec532011-09-02 05:55:19 +00003210 assert(C.isObjCGCEnabled());
Jordy Rosebf77e512011-08-23 20:27:16 +00003211 V = (V ^ RefVal::Owned) + 1;
3212 break;
3213 }
3214 break;
3215
Jordy Rosebf77e512011-08-23 20:27:16 +00003216 case DecRef:
Benjamin Kramer1d5d6342013-10-20 11:53:20 +00003217 case DecRefBridgedTransferred:
Anna Zaks25612732012-08-29 23:23:43 +00003218 case DecRefAndStopTrackingHard:
Jordy Rosebf77e512011-08-23 20:27:16 +00003219 switch (V.getKind()) {
3220 default:
3221 // case 'RefVal::Released' handled above.
3222 llvm_unreachable("Invalid RefVal state for a release.");
Jordy Rosebf77e512011-08-23 20:27:16 +00003223
3224 case RefVal::Owned:
3225 assert(V.getCount() > 0);
Jordan Rosecb5386c2015-02-04 19:24:52 +00003226 if (V.getCount() == 1) {
3227 if (E == DecRefBridgedTransferred ||
3228 V.getIvarAccessHistory() ==
3229 RefVal::IvarAccessHistory::AccessedDirectly)
3230 V = V ^ RefVal::NotOwned;
3231 else
3232 V = V ^ RefVal::Released;
3233 } else if (E == DecRefAndStopTrackingHard) {
Anna Zaksf5788c72012-08-14 00:36:15 +00003234 return removeRefBinding(state, sym);
Jordan Rosecb5386c2015-02-04 19:24:52 +00003235 }
Jordan Roseeec15392012-07-02 19:27:43 +00003236
Jordy Rosebf77e512011-08-23 20:27:16 +00003237 V = V - 1;
3238 break;
3239
3240 case RefVal::NotOwned:
Jordan Roseeec15392012-07-02 19:27:43 +00003241 if (V.getCount() > 0) {
Anna Zaks25612732012-08-29 23:23:43 +00003242 if (E == DecRefAndStopTrackingHard)
Anna Zaksf5788c72012-08-14 00:36:15 +00003243 return removeRefBinding(state, sym);
Jordy Rosebf77e512011-08-23 20:27:16 +00003244 V = V - 1;
Jordan Rosecb5386c2015-02-04 19:24:52 +00003245 } else if (V.getIvarAccessHistory() ==
3246 RefVal::IvarAccessHistory::AccessedDirectly) {
3247 // Assume that the instance variable was holding on the object at
3248 // +1, and we just didn't know.
3249 if (E == DecRefAndStopTrackingHard)
3250 return removeRefBinding(state, sym);
3251 V = V.releaseViaIvar() ^ RefVal::Released;
Jordan Roseeec15392012-07-02 19:27:43 +00003252 } else {
Jordy Rosebf77e512011-08-23 20:27:16 +00003253 V = V ^ RefVal::ErrorReleaseNotOwned;
3254 hasErr = V.getKind();
3255 }
3256 break;
3257
3258 case RefVal::Released:
3259 // Non-GC cases are handled above.
Jordy Rosec49ec532011-09-02 05:55:19 +00003260 assert(C.isObjCGCEnabled());
Jordy Rosebf77e512011-08-23 20:27:16 +00003261 V = V ^ RefVal::ErrorUseAfterRelease;
3262 hasErr = V.getKind();
3263 break;
3264 }
3265 break;
3266 }
Anna Zaksf5788c72012-08-14 00:36:15 +00003267 return setRefBinding(state, sym, V);
Jordy Rosebf77e512011-08-23 20:27:16 +00003268}
3269
Ted Kremenek49b1e382012-01-26 21:29:00 +00003270void RetainCountChecker::processNonLeakError(ProgramStateRef St,
Jordy Rose75e680e2011-09-02 06:44:22 +00003271 SourceRange ErrorRange,
3272 RefVal::Kind ErrorKind,
3273 SymbolRef Sym,
3274 CheckerContext &C) const {
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003275 ExplodedNode *N = C.generateSink(St);
3276 if (!N)
3277 return;
3278
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003279 CFRefBug *BT;
3280 switch (ErrorKind) {
3281 default:
3282 llvm_unreachable("Unhandled error.");
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003283 case RefVal::ErrorUseAfterRelease:
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003284 if (!useAfterRelease)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00003285 useAfterRelease.reset(new UseAfterRelease(this));
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003286 BT = &*useAfterRelease;
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003287 break;
3288 case RefVal::ErrorReleaseNotOwned:
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003289 if (!releaseNotOwned)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00003290 releaseNotOwned.reset(new BadRelease(this));
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003291 BT = &*releaseNotOwned;
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003292 break;
3293 case RefVal::ErrorDeallocGC:
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003294 if (!deallocGC)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00003295 deallocGC.reset(new DeallocGC(this));
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003296 BT = &*deallocGC;
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003297 break;
3298 case RefVal::ErrorDeallocNotOwned:
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003299 if (!deallocNotOwned)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00003300 deallocNotOwned.reset(new DeallocNotOwned(this));
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003301 BT = &*deallocNotOwned;
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003302 break;
3303 }
3304
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003305 assert(BT);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003306 CFRefReport *report = new CFRefReport(*BT, C.getASTContext().getLangOpts(),
Jordy Rosec49ec532011-09-02 05:55:19 +00003307 C.isObjCGCEnabled(), SummaryLog,
3308 N, Sym);
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003309 report->addRange(ErrorRange);
Jordan Rosee10d5a72012-11-02 01:53:40 +00003310 C.emitReport(report);
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003311}
3312
Jordy Rose75e680e2011-09-02 06:44:22 +00003313//===----------------------------------------------------------------------===//
3314// Handle the return values of retain-count-related functions.
3315//===----------------------------------------------------------------------===//
3316
3317bool RetainCountChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
Jordy Rose898a1482011-08-21 21:58:18 +00003318 // Get the callee. We're only interested in simple C functions.
Ted Kremenek49b1e382012-01-26 21:29:00 +00003319 ProgramStateRef state = C.getState();
Anna Zaksc6aa5312011-12-01 05:57:37 +00003320 const FunctionDecl *FD = C.getCalleeDecl(CE);
Jordy Rose898a1482011-08-21 21:58:18 +00003321 if (!FD)
3322 return false;
3323
3324 IdentifierInfo *II = FD->getIdentifier();
3325 if (!II)
3326 return false;
3327
3328 // For now, we're only handling the functions that return aliases of their
3329 // arguments: CFRetain and CFMakeCollectable (and their families).
3330 // Eventually we should add other functions we can model entirely,
3331 // such as CFRelease, which don't invalidate their arguments or globals.
3332 if (CE->getNumArgs() != 1)
3333 return false;
3334
3335 // Get the name of the function.
3336 StringRef FName = II->getName();
3337 FName = FName.substr(FName.find_first_not_of('_'));
3338
3339 // See if it's one of the specific functions we know how to eval.
3340 bool canEval = false;
3341
Anna Zaksc6aa5312011-12-01 05:57:37 +00003342 QualType ResultTy = CE->getCallReturnType();
Jordy Rose898a1482011-08-21 21:58:18 +00003343 if (ResultTy->isObjCIdType()) {
3344 // Handle: id NSMakeCollectable(CFTypeRef)
3345 canEval = II->isStr("NSMakeCollectable");
3346 } else if (ResultTy->isPointerType()) {
3347 // Handle: (CF|CG)Retain
Jordan Rose77411322013-10-07 17:16:52 +00003348 // CFAutorelease
Jordy Rose898a1482011-08-21 21:58:18 +00003349 // CFMakeCollectable
3350 // It's okay to be a little sloppy here (CGMakeCollectable doesn't exist).
3351 if (cocoa::isRefType(ResultTy, "CF", FName) ||
3352 cocoa::isRefType(ResultTy, "CG", FName)) {
Jordan Rose77411322013-10-07 17:16:52 +00003353 canEval = isRetain(FD, FName) || isAutorelease(FD, FName) ||
3354 isMakeCollectable(FD, FName);
Jordy Rose898a1482011-08-21 21:58:18 +00003355 }
3356 }
3357
3358 if (!canEval)
3359 return false;
3360
3361 // Bind the return value.
Ted Kremenek632e3b72012-01-06 22:09:28 +00003362 const LocationContext *LCtx = C.getLocationContext();
3363 SVal RetVal = state->getSVal(CE->getArg(0), LCtx);
Jordy Rose898a1482011-08-21 21:58:18 +00003364 if (RetVal.isUnknown()) {
3365 // If the receiver is unknown, conjure a return value.
3366 SValBuilder &SVB = C.getSValBuilder();
Craig Topper0dbb7832014-05-27 02:45:47 +00003367 RetVal = SVB.conjureSymbolVal(nullptr, CE, LCtx, ResultTy, C.blockCount());
Jordy Rose898a1482011-08-21 21:58:18 +00003368 }
Ted Kremenek632e3b72012-01-06 22:09:28 +00003369 state = state->BindExpr(CE, LCtx, RetVal, false);
Jordy Rose898a1482011-08-21 21:58:18 +00003370
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003371 // FIXME: This should not be necessary, but otherwise the argument seems to be
3372 // considered alive during the next statement.
3373 if (const MemRegion *ArgRegion = RetVal.getAsRegion()) {
3374 // Save the refcount status of the argument.
3375 SymbolRef Sym = RetVal.getAsLocSymbol();
Craig Topper0dbb7832014-05-27 02:45:47 +00003376 const RefVal *Binding = nullptr;
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003377 if (Sym)
Anna Zaksf5788c72012-08-14 00:36:15 +00003378 Binding = getRefBinding(state, Sym);
Jordy Rose898a1482011-08-21 21:58:18 +00003379
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003380 // Invalidate the argument region.
Anna Zaksdc154152012-12-20 00:38:25 +00003381 state = state->invalidateRegions(ArgRegion, CE, C.blockCount(), LCtx,
Anna Zaks0c34c1a2013-01-16 01:35:54 +00003382 /*CausesPointerEscape*/ false);
Jordy Rose898a1482011-08-21 21:58:18 +00003383
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003384 // Restore the refcount status of the argument.
3385 if (Binding)
Anna Zaksf5788c72012-08-14 00:36:15 +00003386 state = setRefBinding(state, Sym, *Binding);
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003387 }
3388
Anna Zaksda4c8d62011-10-26 21:06:34 +00003389 C.addTransition(state);
Jordy Rose898a1482011-08-21 21:58:18 +00003390 return true;
3391}
3392
Jordy Rose75e680e2011-09-02 06:44:22 +00003393//===----------------------------------------------------------------------===//
3394// Handle return statements.
3395//===----------------------------------------------------------------------===//
Jordy Rose298cc4d2011-08-23 19:43:16 +00003396
Jordy Rose75e680e2011-09-02 06:44:22 +00003397void RetainCountChecker::checkPreStmt(const ReturnStmt *S,
3398 CheckerContext &C) const {
Ted Kremenekef31f372012-02-25 02:09:09 +00003399
3400 // Only adjust the reference count if this is the top-level call frame,
3401 // and not the result of inlining. In the future, we should do
3402 // better checking even for inlined calls, and see if they match
3403 // with their expected semantics (e.g., the method should return a retained
3404 // object, etc.).
Anna Zaks44dc91b2012-11-03 02:54:16 +00003405 if (!C.inTopFrame())
Ted Kremenekef31f372012-02-25 02:09:09 +00003406 return;
3407
Jordy Rose298cc4d2011-08-23 19:43:16 +00003408 const Expr *RetE = S->getRetValue();
3409 if (!RetE)
3410 return;
3411
Ted Kremenek49b1e382012-01-26 21:29:00 +00003412 ProgramStateRef state = C.getState();
Ted Kremenek632e3b72012-01-06 22:09:28 +00003413 SymbolRef Sym =
3414 state->getSValAsScalarOrLoc(RetE, C.getLocationContext()).getAsLocSymbol();
Jordy Rose298cc4d2011-08-23 19:43:16 +00003415 if (!Sym)
3416 return;
3417
3418 // Get the reference count binding (if any).
Anna Zaksf5788c72012-08-14 00:36:15 +00003419 const RefVal *T = getRefBinding(state, Sym);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003420 if (!T)
3421 return;
3422
3423 // Change the reference count.
3424 RefVal X = *T;
3425
3426 switch (X.getKind()) {
3427 case RefVal::Owned: {
3428 unsigned cnt = X.getCount();
3429 assert(cnt > 0);
3430 X.setCount(cnt - 1);
3431 X = X ^ RefVal::ReturnedOwned;
3432 break;
3433 }
3434
3435 case RefVal::NotOwned: {
3436 unsigned cnt = X.getCount();
3437 if (cnt) {
3438 X.setCount(cnt - 1);
3439 X = X ^ RefVal::ReturnedOwned;
3440 }
3441 else {
3442 X = X ^ RefVal::ReturnedNotOwned;
3443 }
3444 break;
3445 }
3446
3447 default:
3448 return;
3449 }
3450
3451 // Update the binding.
Anna Zaksf5788c72012-08-14 00:36:15 +00003452 state = setRefBinding(state, Sym, X);
Anna Zaksda4c8d62011-10-26 21:06:34 +00003453 ExplodedNode *Pred = C.addTransition(state);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003454
3455 // At this point we have updated the state properly.
3456 // Everything after this is merely checking to see if the return value has
3457 // been over- or under-retained.
3458
3459 // Did we cache out?
3460 if (!Pred)
3461 return;
3462
Jordy Rose298cc4d2011-08-23 19:43:16 +00003463 // Update the autorelease counts.
Anton Yartsev6a619222014-02-17 18:25:34 +00003464 static CheckerProgramPointTag AutoreleaseTag(this, "Autorelease");
Jordan Roseff03c1d2012-12-06 18:58:18 +00003465 state = handleAutoreleaseCounts(state, Pred, &AutoreleaseTag, C, Sym, X);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003466
3467 // Did we cache out?
Jordan Roseff03c1d2012-12-06 18:58:18 +00003468 if (!state)
Jordy Rose298cc4d2011-08-23 19:43:16 +00003469 return;
3470
3471 // Get the updated binding.
Anna Zaksf5788c72012-08-14 00:36:15 +00003472 T = getRefBinding(state, Sym);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003473 assert(T);
3474 X = *T;
3475
3476 // Consult the summary of the enclosing method.
Jordy Rosec49ec532011-09-02 05:55:19 +00003477 RetainSummaryManager &Summaries = getSummaryManager(C);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003478 const Decl *CD = &Pred->getCodeDecl();
Jordan Roseeec15392012-07-02 19:27:43 +00003479 RetEffect RE = RetEffect::MakeNoRet();
Jordy Rose298cc4d2011-08-23 19:43:16 +00003480
Jordan Roseeec15392012-07-02 19:27:43 +00003481 // FIXME: What is the convention for blocks? Is there one?
Jordy Rose298cc4d2011-08-23 19:43:16 +00003482 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CD)) {
Jordy Rose8b289a22011-08-25 00:10:37 +00003483 const RetainSummary *Summ = Summaries.getMethodSummary(MD);
Jordan Roseeec15392012-07-02 19:27:43 +00003484 RE = Summ->getRetEffect();
3485 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) {
3486 if (!isa<CXXMethodDecl>(FD)) {
3487 const RetainSummary *Summ = Summaries.getFunctionSummary(FD);
3488 RE = Summ->getRetEffect();
3489 }
Jordy Rose298cc4d2011-08-23 19:43:16 +00003490 }
3491
Jordan Roseeec15392012-07-02 19:27:43 +00003492 checkReturnWithRetEffect(S, C, Pred, RE, X, Sym, state);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003493}
3494
Jordy Rose75e680e2011-09-02 06:44:22 +00003495void RetainCountChecker::checkReturnWithRetEffect(const ReturnStmt *S,
3496 CheckerContext &C,
3497 ExplodedNode *Pred,
3498 RetEffect RE, RefVal X,
3499 SymbolRef Sym,
Ted Kremenek49b1e382012-01-26 21:29:00 +00003500 ProgramStateRef state) const {
Jordy Rose298cc4d2011-08-23 19:43:16 +00003501 // Any leaks or other errors?
3502 if (X.isReturnedOwned() && X.getCount() == 0) {
3503 if (RE.getKind() != RetEffect::NoRet) {
3504 bool hasError = false;
Jordy Rosec49ec532011-09-02 05:55:19 +00003505 if (C.isObjCGCEnabled() && RE.getObjKind() == RetEffect::ObjC) {
Jordy Rose298cc4d2011-08-23 19:43:16 +00003506 // Things are more complicated with garbage collection. If the
3507 // returned object is suppose to be an Objective-C object, we have
3508 // a leak (as the caller expects a GC'ed object) because no
3509 // method should return ownership unless it returns a CF object.
3510 hasError = true;
3511 X = X ^ RefVal::ErrorGCLeakReturned;
3512 }
3513 else if (!RE.isOwned()) {
3514 // Either we are using GC and the returned object is a CF type
3515 // or we aren't using GC. In either case, we expect that the
3516 // enclosing method is expected to return ownership.
3517 hasError = true;
3518 X = X ^ RefVal::ErrorLeakReturned;
3519 }
3520
3521 if (hasError) {
3522 // Generate an error node.
Anna Zaksf5788c72012-08-14 00:36:15 +00003523 state = setRefBinding(state, Sym, X);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003524
Anton Yartsev6a619222014-02-17 18:25:34 +00003525 static CheckerProgramPointTag ReturnOwnLeakTag(this, "ReturnsOwnLeak");
Anna Zaksda4c8d62011-10-26 21:06:34 +00003526 ExplodedNode *N = C.addTransition(state, Pred, &ReturnOwnLeakTag);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003527 if (N) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003528 const LangOptions &LOpts = C.getASTContext().getLangOpts();
Jordy Rosec49ec532011-09-02 05:55:19 +00003529 bool GCEnabled = C.isObjCGCEnabled();
Jordy Rose298cc4d2011-08-23 19:43:16 +00003530 CFRefReport *report =
Jordy Rosec49ec532011-09-02 05:55:19 +00003531 new CFRefLeakReport(*getLeakAtReturnBug(LOpts, GCEnabled),
3532 LOpts, GCEnabled, SummaryLog,
Ted Kremenek8671acb2013-04-16 21:44:22 +00003533 N, Sym, C, IncludeAllocationLine);
3534
Jordan Rosee10d5a72012-11-02 01:53:40 +00003535 C.emitReport(report);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003536 }
3537 }
3538 }
3539 } else if (X.isReturnedNotOwned()) {
3540 if (RE.isOwned()) {
Jordan Rosecb5386c2015-02-04 19:24:52 +00003541 if (X.getIvarAccessHistory() ==
3542 RefVal::IvarAccessHistory::AccessedDirectly) {
3543 // Assume the method was trying to transfer a +1 reference from a
3544 // strong ivar to the caller.
3545 state = setRefBinding(state, Sym,
3546 X.releaseViaIvar() ^ RefVal::ReturnedOwned);
3547 } else {
3548 // Trying to return a not owned object to a caller expecting an
3549 // owned object.
3550 state = setRefBinding(state, Sym, X ^ RefVal::ErrorReturnedNotOwned);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003551
Jordan Rosecb5386c2015-02-04 19:24:52 +00003552 static CheckerProgramPointTag
3553 ReturnNotOwnedTag(this, "ReturnNotOwnedForOwned");
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003554
Jordan Rosecb5386c2015-02-04 19:24:52 +00003555 ExplodedNode *N = C.addTransition(state, Pred, &ReturnNotOwnedTag);
3556 if (N) {
3557 if (!returnNotOwnedForOwned)
3558 returnNotOwnedForOwned.reset(new ReturnedNotOwnedForOwned(this));
3559
3560 CFRefReport *report =
3561 new CFRefReport(*returnNotOwnedForOwned,
3562 C.getASTContext().getLangOpts(),
3563 C.isObjCGCEnabled(), SummaryLog, N, Sym);
3564 C.emitReport(report);
3565 }
Jordy Rose298cc4d2011-08-23 19:43:16 +00003566 }
3567 }
3568 }
3569}
3570
Jordy Rose6763e382011-08-23 20:07:14 +00003571//===----------------------------------------------------------------------===//
Jordy Rose75e680e2011-09-02 06:44:22 +00003572// Check various ways a symbol can be invalidated.
3573//===----------------------------------------------------------------------===//
3574
Anna Zaks3e0f4152011-10-06 00:43:15 +00003575void RetainCountChecker::checkBind(SVal loc, SVal val, const Stmt *S,
Jordy Rose75e680e2011-09-02 06:44:22 +00003576 CheckerContext &C) const {
3577 // Are we storing to something that causes the value to "escape"?
3578 bool escapes = true;
3579
3580 // A value escapes in three possible cases (this may change):
3581 //
3582 // (1) we are binding to something that is not a memory region.
3583 // (2) we are binding to a memregion that does not have stack storage
3584 // (3) we are binding to a memregion with stack storage that the store
3585 // does not understand.
Ted Kremenek49b1e382012-01-26 21:29:00 +00003586 ProgramStateRef state = C.getState();
Jordy Rose75e680e2011-09-02 06:44:22 +00003587
David Blaikie05785d12013-02-20 22:23:23 +00003588 if (Optional<loc::MemRegionVal> regionLoc = loc.getAs<loc::MemRegionVal>()) {
Jordy Rose75e680e2011-09-02 06:44:22 +00003589 escapes = !regionLoc->getRegion()->hasStackStorage();
3590
3591 if (!escapes) {
3592 // To test (3), generate a new state with the binding added. If it is
3593 // the same state, then it escapes (since the store cannot represent
3594 // the binding).
Anna Zaks70de7722012-05-02 00:15:40 +00003595 // Do this only if we know that the store is not supposed to generate the
3596 // same state.
3597 SVal StoredVal = state->getSVal(regionLoc->getRegion());
3598 if (StoredVal != val)
3599 escapes = (state == (state->bindLoc(*regionLoc, val)));
Jordy Rose75e680e2011-09-02 06:44:22 +00003600 }
Ted Kremeneke9a5bcf2012-03-27 01:12:45 +00003601 if (!escapes) {
3602 // Case 4: We do not currently model what happens when a symbol is
3603 // assigned to a struct field, so be conservative here and let the symbol
3604 // go. TODO: This could definitely be improved upon.
3605 escapes = !isa<VarRegion>(regionLoc->getRegion());
3606 }
Jordy Rose75e680e2011-09-02 06:44:22 +00003607 }
3608
Anna Zaksfb050942013-09-17 00:53:28 +00003609 // If we are storing the value into an auto function scope variable annotated
3610 // with (__attribute__((cleanup))), stop tracking the value to avoid leak
3611 // false positives.
3612 if (const VarRegion *LVR = dyn_cast_or_null<VarRegion>(loc.getAsRegion())) {
3613 const VarDecl *VD = LVR->getDecl();
Aaron Ballman9ead1242013-12-19 02:39:40 +00003614 if (VD->hasAttr<CleanupAttr>()) {
Anna Zaksfb050942013-09-17 00:53:28 +00003615 escapes = true;
3616 }
3617 }
3618
Jordy Rose75e680e2011-09-02 06:44:22 +00003619 // If our store can represent the binding and we aren't storing to something
3620 // that doesn't have local storage then just return and have the simulation
3621 // state continue as is.
3622 if (!escapes)
3623 return;
3624
3625 // Otherwise, find all symbols referenced by 'val' that we are tracking
3626 // and stop tracking them.
3627 state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
Anna Zaksda4c8d62011-10-26 21:06:34 +00003628 C.addTransition(state);
Jordy Rose75e680e2011-09-02 06:44:22 +00003629}
3630
Ted Kremenek49b1e382012-01-26 21:29:00 +00003631ProgramStateRef RetainCountChecker::evalAssume(ProgramStateRef state,
Jordy Rose75e680e2011-09-02 06:44:22 +00003632 SVal Cond,
3633 bool Assumption) const {
3634
3635 // FIXME: We may add to the interface of evalAssume the list of symbols
3636 // whose assumptions have changed. For now we just iterate through the
3637 // bindings and check if any of the tracked symbols are NULL. This isn't
3638 // too bad since the number of symbols we will track in practice are
3639 // probably small and evalAssume is only called at branches and a few
3640 // other places.
Jordan Rose0c153cb2012-11-02 01:54:06 +00003641 RefBindingsTy B = state->get<RefBindings>();
Jordy Rose75e680e2011-09-02 06:44:22 +00003642
3643 if (B.isEmpty())
3644 return state;
3645
3646 bool changed = false;
Jordan Rose0c153cb2012-11-02 01:54:06 +00003647 RefBindingsTy::Factory &RefBFactory = state->get_context<RefBindings>();
Jordy Rose75e680e2011-09-02 06:44:22 +00003648
Jordan Rose0c153cb2012-11-02 01:54:06 +00003649 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Ted Kremenek244e1d72012-09-07 22:31:01 +00003650 // Check if the symbol is null stop tracking the symbol.
Jordan Rose14fe9f32012-11-01 00:18:27 +00003651 ConstraintManager &CMgr = state->getConstraintManager();
3652 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
3653 if (AllocFailed.isConstrainedTrue()) {
Jordy Rose75e680e2011-09-02 06:44:22 +00003654 changed = true;
3655 B = RefBFactory.remove(B, I.getKey());
3656 }
3657 }
3658
3659 if (changed)
3660 state = state->set<RefBindings>(B);
3661
3662 return state;
3663}
3664
Ted Kremenek49b1e382012-01-26 21:29:00 +00003665ProgramStateRef
3666RetainCountChecker::checkRegionChanges(ProgramStateRef state,
Anna Zaksdc154152012-12-20 00:38:25 +00003667 const InvalidatedSymbols *invalidated,
Jordy Rose75e680e2011-09-02 06:44:22 +00003668 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks3d348342012-02-14 21:55:24 +00003669 ArrayRef<const MemRegion *> Regions,
Jordan Rose742920c2012-07-02 19:27:35 +00003670 const CallEvent *Call) const {
Jordy Rose75e680e2011-09-02 06:44:22 +00003671 if (!invalidated)
3672 return state;
3673
3674 llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
3675 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
3676 E = ExplicitRegions.end(); I != E; ++I) {
3677 if (const SymbolicRegion *SR = (*I)->StripCasts()->getAs<SymbolicRegion>())
3678 WhitelistedSymbols.insert(SR->getSymbol());
3679 }
3680
Anna Zaksdc154152012-12-20 00:38:25 +00003681 for (InvalidatedSymbols::const_iterator I=invalidated->begin(),
Jordy Rose75e680e2011-09-02 06:44:22 +00003682 E = invalidated->end(); I!=E; ++I) {
3683 SymbolRef sym = *I;
3684 if (WhitelistedSymbols.count(sym))
3685 continue;
3686 // Remove any existing reference-count binding.
Anna Zaksf5788c72012-08-14 00:36:15 +00003687 state = removeRefBinding(state, sym);
Jordy Rose75e680e2011-09-02 06:44:22 +00003688 }
3689 return state;
3690}
3691
3692//===----------------------------------------------------------------------===//
Jordy Rose6763e382011-08-23 20:07:14 +00003693// Handle dead symbols and end-of-path.
3694//===----------------------------------------------------------------------===//
3695
Jordan Roseff03c1d2012-12-06 18:58:18 +00003696ProgramStateRef
3697RetainCountChecker::handleAutoreleaseCounts(ProgramStateRef state,
Anna Zaks58734db2011-10-25 19:57:11 +00003698 ExplodedNode *Pred,
Jordan Rose9f61f8a2012-08-18 00:30:16 +00003699 const ProgramPointTag *Tag,
Anna Zaks58734db2011-10-25 19:57:11 +00003700 CheckerContext &Ctx,
Jordy Rose75e680e2011-09-02 06:44:22 +00003701 SymbolRef Sym, RefVal V) const {
Jordy Rose6763e382011-08-23 20:07:14 +00003702 unsigned ACnt = V.getAutoreleaseCount();
3703
3704 // No autorelease counts? Nothing to be done.
3705 if (!ACnt)
Jordan Roseff03c1d2012-12-06 18:58:18 +00003706 return state;
Jordy Rose6763e382011-08-23 20:07:14 +00003707
Anna Zaks58734db2011-10-25 19:57:11 +00003708 assert(!Ctx.isObjCGCEnabled() && "Autorelease counts in GC mode?");
Jordy Rose6763e382011-08-23 20:07:14 +00003709 unsigned Cnt = V.getCount();
3710
3711 // FIXME: Handle sending 'autorelease' to already released object.
3712
3713 if (V.getKind() == RefVal::ReturnedOwned)
3714 ++Cnt;
3715
Jordan Rosecb5386c2015-02-04 19:24:52 +00003716 // If we would over-release here, but we know the value came from an ivar,
3717 // assume it was a strong ivar that's just been relinquished.
3718 if (ACnt > Cnt &&
3719 V.getIvarAccessHistory() == RefVal::IvarAccessHistory::AccessedDirectly) {
3720 V = V.releaseViaIvar();
3721 --ACnt;
3722 }
3723
Jordy Rose6763e382011-08-23 20:07:14 +00003724 if (ACnt <= Cnt) {
3725 if (ACnt == Cnt) {
3726 V.clearCounts();
3727 if (V.getKind() == RefVal::ReturnedOwned)
3728 V = V ^ RefVal::ReturnedNotOwned;
3729 else
3730 V = V ^ RefVal::NotOwned;
3731 } else {
Anna Zaksa8bcc652013-01-31 22:36:17 +00003732 V.setCount(V.getCount() - ACnt);
Jordy Rose6763e382011-08-23 20:07:14 +00003733 V.setAutoreleaseCount(0);
3734 }
Jordan Roseff03c1d2012-12-06 18:58:18 +00003735 return setRefBinding(state, Sym, V);
Jordy Rose6763e382011-08-23 20:07:14 +00003736 }
3737
3738 // Woah! More autorelease counts then retain counts left.
3739 // Emit hard error.
3740 V = V ^ RefVal::ErrorOverAutorelease;
Anna Zaksf5788c72012-08-14 00:36:15 +00003741 state = setRefBinding(state, Sym, V);
Jordy Rose6763e382011-08-23 20:07:14 +00003742
Jordan Rose4b4613c2012-08-20 18:43:42 +00003743 ExplodedNode *N = Ctx.generateSink(state, Pred, Tag);
Jordan Rose9f61f8a2012-08-18 00:30:16 +00003744 if (N) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003745 SmallString<128> sbuf;
Jordy Rose6763e382011-08-23 20:07:14 +00003746 llvm::raw_svector_ostream os(sbuf);
Jordan Rose7467f062013-04-23 01:42:25 +00003747 os << "Object was autoreleased ";
Jordy Rose6763e382011-08-23 20:07:14 +00003748 if (V.getAutoreleaseCount() > 1)
Jordan Rose7467f062013-04-23 01:42:25 +00003749 os << V.getAutoreleaseCount() << " times but the object ";
3750 else
3751 os << "but ";
3752 os << "has a +" << V.getCount() << " retain count";
Jordy Rose6763e382011-08-23 20:07:14 +00003753
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003754 if (!overAutorelease)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00003755 overAutorelease.reset(new OverAutorelease(this));
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003756
David Blaikiebbafb8a2012-03-11 07:00:24 +00003757 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
Jordy Rose6763e382011-08-23 20:07:14 +00003758 CFRefReport *report =
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003759 new CFRefReport(*overAutorelease, LOpts, /* GCEnabled = */ false,
3760 SummaryLog, N, Sym, os.str());
Jordan Rosee10d5a72012-11-02 01:53:40 +00003761 Ctx.emitReport(report);
Jordy Rose6763e382011-08-23 20:07:14 +00003762 }
3763
Craig Topper0dbb7832014-05-27 02:45:47 +00003764 return nullptr;
Jordy Rose6763e382011-08-23 20:07:14 +00003765}
Jordy Rose78612762011-08-23 19:01:07 +00003766
Ted Kremenek49b1e382012-01-26 21:29:00 +00003767ProgramStateRef
3768RetainCountChecker::handleSymbolDeath(ProgramStateRef state,
Jordy Rose75e680e2011-09-02 06:44:22 +00003769 SymbolRef sid, RefVal V,
Jordy Rose78612762011-08-23 19:01:07 +00003770 SmallVectorImpl<SymbolRef> &Leaked) const {
Jordy Rose03a8f9e2011-08-24 04:48:19 +00003771 bool hasLeak = false;
Jordy Rose78612762011-08-23 19:01:07 +00003772 if (V.isOwned())
3773 hasLeak = true;
3774 else if (V.isNotOwned() || V.isReturnedOwned())
3775 hasLeak = (V.getCount() > 0);
3776
3777 if (!hasLeak)
Anna Zaksf5788c72012-08-14 00:36:15 +00003778 return removeRefBinding(state, sid);
Jordy Rose78612762011-08-23 19:01:07 +00003779
3780 Leaked.push_back(sid);
Anna Zaksf5788c72012-08-14 00:36:15 +00003781 return setRefBinding(state, sid, V ^ RefVal::ErrorLeak);
Jordy Rose78612762011-08-23 19:01:07 +00003782}
3783
3784ExplodedNode *
Ted Kremenek49b1e382012-01-26 21:29:00 +00003785RetainCountChecker::processLeaks(ProgramStateRef state,
Jordy Rose75e680e2011-09-02 06:44:22 +00003786 SmallVectorImpl<SymbolRef> &Leaked,
Anna Zaks58734db2011-10-25 19:57:11 +00003787 CheckerContext &Ctx,
3788 ExplodedNode *Pred) const {
Jordy Rose78612762011-08-23 19:01:07 +00003789 // Generate an intermediate node representing the leak point.
Jordan Rose9f61f8a2012-08-18 00:30:16 +00003790 ExplodedNode *N = Ctx.addTransition(state, Pred);
Jordy Rose78612762011-08-23 19:01:07 +00003791
3792 if (N) {
3793 for (SmallVectorImpl<SymbolRef>::iterator
3794 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3795
David Blaikiebbafb8a2012-03-11 07:00:24 +00003796 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
Anna Zaks58734db2011-10-25 19:57:11 +00003797 bool GCEnabled = Ctx.isObjCGCEnabled();
Jordy Rosec49ec532011-09-02 05:55:19 +00003798 CFRefBug *BT = Pred ? getLeakWithinFunctionBug(LOpts, GCEnabled)
3799 : getLeakAtReturnBug(LOpts, GCEnabled);
Jordy Rose78612762011-08-23 19:01:07 +00003800 assert(BT && "BugType not initialized.");
Jordy Rose184bd142011-08-24 22:39:09 +00003801
Jordy Rosec49ec532011-09-02 05:55:19 +00003802 CFRefLeakReport *report = new CFRefLeakReport(*BT, LOpts, GCEnabled,
Ted Kremenek8671acb2013-04-16 21:44:22 +00003803 SummaryLog, N, *I, Ctx,
3804 IncludeAllocationLine);
Jordan Rosee10d5a72012-11-02 01:53:40 +00003805 Ctx.emitReport(report);
Jordy Rose78612762011-08-23 19:01:07 +00003806 }
3807 }
3808
3809 return N;
3810}
3811
Anna Zaks3fdcc0b2013-01-03 00:25:29 +00003812void RetainCountChecker::checkEndFunction(CheckerContext &Ctx) const {
Ted Kremenek49b1e382012-01-26 21:29:00 +00003813 ProgramStateRef state = Ctx.getState();
Jordan Rose0c153cb2012-11-02 01:54:06 +00003814 RefBindingsTy B = state->get<RefBindings>();
Anna Zaks3eae3342011-10-25 19:56:48 +00003815 ExplodedNode *Pred = Ctx.getPredecessor();
Jordy Rose78612762011-08-23 19:01:07 +00003816
Jordan Rose7699e4a2013-08-01 22:16:36 +00003817 // Don't process anything within synthesized bodies.
3818 const LocationContext *LCtx = Pred->getLocationContext();
3819 if (LCtx->getAnalysisDeclContext()->isBodyAutosynthesized()) {
3820 assert(LCtx->getParent());
3821 return;
3822 }
3823
Jordan Rose0c153cb2012-11-02 01:54:06 +00003824 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Craig Topper0dbb7832014-05-27 02:45:47 +00003825 state = handleAutoreleaseCounts(state, Pred, /*Tag=*/nullptr, Ctx,
Jordan Roseff03c1d2012-12-06 18:58:18 +00003826 I->first, I->second);
Jordy Rose6763e382011-08-23 20:07:14 +00003827 if (!state)
Jordy Rose78612762011-08-23 19:01:07 +00003828 return;
3829 }
3830
Ted Kremeneka2bbac32012-02-07 00:24:33 +00003831 // If the current LocationContext has a parent, don't check for leaks.
3832 // We will do that later.
Anna Zaksf5788c72012-08-14 00:36:15 +00003833 // FIXME: we should instead check for imbalances of the retain/releases,
Ted Kremeneka2bbac32012-02-07 00:24:33 +00003834 // and suggest annotations.
Jordan Rose7699e4a2013-08-01 22:16:36 +00003835 if (LCtx->getParent())
Ted Kremeneka2bbac32012-02-07 00:24:33 +00003836 return;
3837
Jordy Rose78612762011-08-23 19:01:07 +00003838 B = state->get<RefBindings>();
3839 SmallVector<SymbolRef, 10> Leaked;
3840
Jordan Rose0c153cb2012-11-02 01:54:06 +00003841 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I)
Jordy Rose6763e382011-08-23 20:07:14 +00003842 state = handleSymbolDeath(state, I->first, I->second, Leaked);
Jordy Rose78612762011-08-23 19:01:07 +00003843
Jordan Rose9f61f8a2012-08-18 00:30:16 +00003844 processLeaks(state, Leaked, Ctx, Pred);
Jordy Rose78612762011-08-23 19:01:07 +00003845}
3846
3847const ProgramPointTag *
Jordy Rose75e680e2011-09-02 06:44:22 +00003848RetainCountChecker::getDeadSymbolTag(SymbolRef sym) const {
Anton Yartsev6a619222014-02-17 18:25:34 +00003849 const CheckerProgramPointTag *&tag = DeadSymbolTags[sym];
Jordy Rose78612762011-08-23 19:01:07 +00003850 if (!tag) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003851 SmallString<64> buf;
Jordy Rose78612762011-08-23 19:01:07 +00003852 llvm::raw_svector_ostream out(buf);
Anton Yartsev6a619222014-02-17 18:25:34 +00003853 out << "Dead Symbol : ";
Anna Zaks22351652011-12-05 18:58:11 +00003854 sym->dumpToStream(out);
Anton Yartsev6a619222014-02-17 18:25:34 +00003855 tag = new CheckerProgramPointTag(this, out.str());
Jordy Rose78612762011-08-23 19:01:07 +00003856 }
3857 return tag;
3858}
3859
Jordy Rose75e680e2011-09-02 06:44:22 +00003860void RetainCountChecker::checkDeadSymbols(SymbolReaper &SymReaper,
3861 CheckerContext &C) const {
Jordy Rose78612762011-08-23 19:01:07 +00003862 ExplodedNode *Pred = C.getPredecessor();
3863
Ted Kremenek49b1e382012-01-26 21:29:00 +00003864 ProgramStateRef state = C.getState();
Jordan Rose0c153cb2012-11-02 01:54:06 +00003865 RefBindingsTy B = state->get<RefBindings>();
Jordan Roseff03c1d2012-12-06 18:58:18 +00003866 SmallVector<SymbolRef, 10> Leaked;
Jordy Rose78612762011-08-23 19:01:07 +00003867
3868 // Update counts from autorelease pools
3869 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3870 E = SymReaper.dead_end(); I != E; ++I) {
3871 SymbolRef Sym = *I;
3872 if (const RefVal *T = B.lookup(Sym)){
3873 // Use the symbol as the tag.
3874 // FIXME: This might not be as unique as we would like.
Jordan Rose9f61f8a2012-08-18 00:30:16 +00003875 const ProgramPointTag *Tag = getDeadSymbolTag(Sym);
Jordan Roseff03c1d2012-12-06 18:58:18 +00003876 state = handleAutoreleaseCounts(state, Pred, Tag, C, Sym, *T);
Jordy Rose6763e382011-08-23 20:07:14 +00003877 if (!state)
Jordy Rose78612762011-08-23 19:01:07 +00003878 return;
Jordan Roseff03c1d2012-12-06 18:58:18 +00003879
3880 // Fetch the new reference count from the state, and use it to handle
3881 // this symbol.
3882 state = handleSymbolDeath(state, *I, *getRefBinding(state, Sym), Leaked);
Jordy Rose78612762011-08-23 19:01:07 +00003883 }
3884 }
3885
Jordan Roseff03c1d2012-12-06 18:58:18 +00003886 if (Leaked.empty()) {
3887 C.addTransition(state);
3888 return;
Jordy Rose78612762011-08-23 19:01:07 +00003889 }
3890
Jordan Rose9f61f8a2012-08-18 00:30:16 +00003891 Pred = processLeaks(state, Leaked, C, Pred);
Jordy Rose78612762011-08-23 19:01:07 +00003892
3893 // Did we cache out?
3894 if (!Pred)
3895 return;
3896
3897 // Now generate a new node that nukes the old bindings.
Jordan Roseff03c1d2012-12-06 18:58:18 +00003898 // The only bindings left at this point are the leaked symbols.
Jordan Rose0c153cb2012-11-02 01:54:06 +00003899 RefBindingsTy::Factory &F = state->get_context<RefBindings>();
Jordan Roseff03c1d2012-12-06 18:58:18 +00003900 B = state->get<RefBindings>();
Jordy Rose78612762011-08-23 19:01:07 +00003901
Jordan Roseff03c1d2012-12-06 18:58:18 +00003902 for (SmallVectorImpl<SymbolRef>::iterator I = Leaked.begin(),
3903 E = Leaked.end();
3904 I != E; ++I)
Jordy Rose78612762011-08-23 19:01:07 +00003905 B = F.remove(B, *I);
3906
3907 state = state->set<RefBindings>(B);
Anna Zaksda4c8d62011-10-26 21:06:34 +00003908 C.addTransition(state, Pred);
Jordy Rose78612762011-08-23 19:01:07 +00003909}
3910
Ted Kremenek49b1e382012-01-26 21:29:00 +00003911void RetainCountChecker::printState(raw_ostream &Out, ProgramStateRef State,
Jordy Rose75e680e2011-09-02 06:44:22 +00003912 const char *NL, const char *Sep) const {
Jordy Rose58a20d32011-08-28 19:11:56 +00003913
Jordan Rose0c153cb2012-11-02 01:54:06 +00003914 RefBindingsTy B = State->get<RefBindings>();
Jordy Rose58a20d32011-08-28 19:11:56 +00003915
Ted Kremenekdb70b522013-03-28 18:43:18 +00003916 if (B.isEmpty())
3917 return;
3918
3919 Out << Sep << NL;
Jordy Rose58a20d32011-08-28 19:11:56 +00003920
Jordan Rose0c153cb2012-11-02 01:54:06 +00003921 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Jordy Rose58a20d32011-08-28 19:11:56 +00003922 Out << I->first << " : ";
3923 I->second.print(Out);
3924 Out << NL;
3925 }
Jordy Rose58a20d32011-08-28 19:11:56 +00003926}
3927
3928//===----------------------------------------------------------------------===//
Jordy Rose75e680e2011-09-02 06:44:22 +00003929// Checker registration.
Ted Kremenek819e9b62008-03-11 06:39:11 +00003930//===----------------------------------------------------------------------===//
3931
Jordy Rosec49ec532011-09-02 05:55:19 +00003932void ento::registerRetainCountChecker(CheckerManager &Mgr) {
Ted Kremenek8671acb2013-04-16 21:44:22 +00003933 Mgr.registerChecker<RetainCountChecker>(Mgr.getAnalyzerOptions());
Jordy Rosec49ec532011-09-02 05:55:19 +00003934}
3935
Ted Kremenek71c080f2013-08-14 23:41:49 +00003936//===----------------------------------------------------------------------===//
3937// Implementation of the CallEffects API.
3938//===----------------------------------------------------------------------===//
3939
3940namespace clang { namespace ento { namespace objc_retain {
3941
3942// This is a bit gross, but it allows us to populate CallEffects without
3943// creating a bunch of accessors. This kind is very localized, so the
3944// damage of this macro is limited.
3945#define createCallEffect(D, KIND)\
3946 ASTContext &Ctx = D->getASTContext();\
3947 LangOptions L = Ctx.getLangOpts();\
3948 RetainSummaryManager M(Ctx, L.GCOnly, L.ObjCAutoRefCount);\
3949 const RetainSummary *S = M.get ## KIND ## Summary(D);\
3950 CallEffects CE(S->getRetEffect());\
3951 CE.Receiver = S->getReceiverEffect();\
Ted Kremeneke19529b2013-08-16 23:14:22 +00003952 unsigned N = D->param_size();\
Ted Kremenek71c080f2013-08-14 23:41:49 +00003953 for (unsigned i = 0; i < N; ++i) {\
3954 CE.Args.push_back(S->getArg(i));\
3955 }
3956
3957CallEffects CallEffects::getEffect(const ObjCMethodDecl *MD) {
3958 createCallEffect(MD, Method);
3959 return CE;
3960}
3961
3962CallEffects CallEffects::getEffect(const FunctionDecl *FD) {
3963 createCallEffect(FD, Function);
3964 return CE;
3965}
3966
3967#undef createCallEffect
3968
3969}}}