blob: f983c3085635157b51fc87c1e9323c3f7b99829b [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};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000064} // end llvm namespace
Ted Kremenek819e9b62008-03-11 06:39:11 +000065
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 }
Hans Wennborgdcfba332015-10-06 23:40:43 +0000237
Jordan Rosecb5386c2015-02-04 19:24:52 +0000238 RefVal releaseViaIvar() const {
239 assert(getIvarAccessHistory() == IvarAccessHistory::AccessedDirectly);
240 return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount(),
241 getType(), IvarAccessHistory::ReleasedAfterDirectAccess);
Ted Kremeneka2968e52009-11-13 01:54:21 +0000242 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000243
Jordan Roseb3ad07e2014-03-25 17:10:58 +0000244 // Comparison, profiling, and pretty-printing.
245
246 bool hasSameState(const RefVal &X) const {
Jordan Rosecb5386c2015-02-04 19:24:52 +0000247 return getKind() == X.getKind() && Cnt == X.Cnt && ACnt == X.ACnt &&
248 getIvarAccessHistory() == X.getIvarAccessHistory();
Jordan Roseb3ad07e2014-03-25 17:10:58 +0000249 }
250
251 bool operator==(const RefVal& X) const {
Jordan Rosecb5386c2015-02-04 19:24:52 +0000252 return T == X.T && hasSameState(X) && getObjKind() == X.getObjKind();
Jordan Roseb3ad07e2014-03-25 17:10:58 +0000253 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000254
Ted Kremeneka2968e52009-11-13 01:54:21 +0000255 void Profile(llvm::FoldingSetNodeID& ID) const {
Jordan Roseb3ad07e2014-03-25 17:10:58 +0000256 ID.Add(T);
257 ID.AddInteger(RawKind);
Ted Kremeneka2968e52009-11-13 01:54:21 +0000258 ID.AddInteger(Cnt);
259 ID.AddInteger(ACnt);
Jordan Roseb3ad07e2014-03-25 17:10:58 +0000260 ID.AddInteger(RawObjectKind);
Jordan Rosecb5386c2015-02-04 19:24:52 +0000261 ID.AddInteger(RawIvarAccessHistory);
Ted Kremeneka2968e52009-11-13 01:54:21 +0000262 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000263
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000264 void print(raw_ostream &Out) const;
Ted Kremeneka2968e52009-11-13 01:54:21 +0000265};
266
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000267void RefVal::print(raw_ostream &Out) const {
Ted Kremeneka2968e52009-11-13 01:54:21 +0000268 if (!T.isNull())
Jordy Rose58a20d32011-08-28 19:11:56 +0000269 Out << "Tracked " << T.getAsString() << '/';
Ted Kremenekbd862712010-07-01 20:16:50 +0000270
Ted Kremeneka2968e52009-11-13 01:54:21 +0000271 switch (getKind()) {
Jordy Rose75e680e2011-09-02 06:44:22 +0000272 default: llvm_unreachable("Invalid RefVal kind");
Ted Kremeneka2968e52009-11-13 01:54:21 +0000273 case Owned: {
274 Out << "Owned";
275 unsigned cnt = getCount();
276 if (cnt) Out << " (+ " << cnt << ")";
277 break;
278 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000279
Ted Kremeneka2968e52009-11-13 01:54:21 +0000280 case NotOwned: {
281 Out << "NotOwned";
282 unsigned cnt = getCount();
283 if (cnt) Out << " (+ " << cnt << ")";
284 break;
285 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000286
Ted Kremeneka2968e52009-11-13 01:54:21 +0000287 case ReturnedOwned: {
288 Out << "ReturnedOwned";
289 unsigned cnt = getCount();
290 if (cnt) Out << " (+ " << cnt << ")";
291 break;
292 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000293
Ted Kremeneka2968e52009-11-13 01:54:21 +0000294 case ReturnedNotOwned: {
295 Out << "ReturnedNotOwned";
296 unsigned cnt = getCount();
297 if (cnt) Out << " (+ " << cnt << ")";
298 break;
299 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000300
Ted Kremeneka2968e52009-11-13 01:54:21 +0000301 case Released:
302 Out << "Released";
303 break;
Ted Kremenekbd862712010-07-01 20:16:50 +0000304
Ted Kremeneka2968e52009-11-13 01:54:21 +0000305 case ErrorDeallocGC:
306 Out << "-dealloc (GC)";
307 break;
Ted Kremenekbd862712010-07-01 20:16:50 +0000308
Ted Kremeneka2968e52009-11-13 01:54:21 +0000309 case ErrorDeallocNotOwned:
310 Out << "-dealloc (not-owned)";
311 break;
Ted Kremenekbd862712010-07-01 20:16:50 +0000312
Ted Kremeneka2968e52009-11-13 01:54:21 +0000313 case ErrorLeak:
314 Out << "Leaked";
315 break;
Ted Kremenekbd862712010-07-01 20:16:50 +0000316
Ted Kremeneka2968e52009-11-13 01:54:21 +0000317 case ErrorLeakReturned:
318 Out << "Leaked (Bad naming)";
319 break;
Ted Kremenekbd862712010-07-01 20:16:50 +0000320
Ted Kremeneka2968e52009-11-13 01:54:21 +0000321 case ErrorGCLeakReturned:
322 Out << "Leaked (GC-ed at return)";
323 break;
Ted Kremenekbd862712010-07-01 20:16:50 +0000324
Ted Kremeneka2968e52009-11-13 01:54:21 +0000325 case ErrorUseAfterRelease:
326 Out << "Use-After-Release [ERROR]";
327 break;
Ted Kremenekbd862712010-07-01 20:16:50 +0000328
Ted Kremeneka2968e52009-11-13 01:54:21 +0000329 case ErrorReleaseNotOwned:
330 Out << "Release of Not-Owned [ERROR]";
331 break;
Ted Kremenekbd862712010-07-01 20:16:50 +0000332
Ted Kremeneka2968e52009-11-13 01:54:21 +0000333 case RefVal::ErrorOverAutorelease:
Jordan Rose7467f062013-04-23 01:42:25 +0000334 Out << "Over-autoreleased";
Ted Kremeneka2968e52009-11-13 01:54:21 +0000335 break;
Ted Kremenekbd862712010-07-01 20:16:50 +0000336
Ted Kremeneka2968e52009-11-13 01:54:21 +0000337 case RefVal::ErrorReturnedNotOwned:
338 Out << "Non-owned object returned instead of owned";
339 break;
340 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000341
Jordan Rosecb5386c2015-02-04 19:24:52 +0000342 switch (getIvarAccessHistory()) {
343 case IvarAccessHistory::None:
344 break;
345 case IvarAccessHistory::AccessedDirectly:
346 Out << " [direct ivar access]";
347 break;
348 case IvarAccessHistory::ReleasedAfterDirectAccess:
349 Out << " [released after direct ivar access]";
350 }
351
Ted Kremeneka2968e52009-11-13 01:54:21 +0000352 if (ACnt) {
Jordan Rosecb5386c2015-02-04 19:24:52 +0000353 Out << " [autorelease -" << ACnt << ']';
Ted Kremeneka2968e52009-11-13 01:54:21 +0000354 }
355}
356} //end anonymous namespace
357
358//===----------------------------------------------------------------------===//
359// RefBindings - State used to track object reference counts.
360//===----------------------------------------------------------------------===//
361
Jordan Rose0c153cb2012-11-02 01:54:06 +0000362REGISTER_MAP_WITH_PROGRAMSTATE(RefBindings, SymbolRef, RefVal)
Ted Kremeneka2968e52009-11-13 01:54:21 +0000363
Anna Zaksf5788c72012-08-14 00:36:15 +0000364static inline const RefVal *getRefBinding(ProgramStateRef State,
365 SymbolRef Sym) {
366 return State->get<RefBindings>(Sym);
367}
368
369static inline ProgramStateRef setRefBinding(ProgramStateRef State,
370 SymbolRef Sym, RefVal Val) {
371 return State->set<RefBindings>(Sym, Val);
372}
373
374static ProgramStateRef removeRefBinding(ProgramStateRef State, SymbolRef Sym) {
375 return State->remove<RefBindings>(Sym);
376}
377
Ted Kremeneka2968e52009-11-13 01:54:21 +0000378//===----------------------------------------------------------------------===//
Jordy Rose75e680e2011-09-02 06:44:22 +0000379// Function/Method behavior summaries.
Ted Kremeneka2968e52009-11-13 01:54:21 +0000380//===----------------------------------------------------------------------===//
381
382namespace {
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +0000383class RetainSummary {
Jordy Rose61c974b2012-03-18 01:26:10 +0000384 /// Args - a map of (index, ArgEffect) pairs, where index
Ted Kremenekcb2e6362008-05-06 15:44:25 +0000385 /// specifies the argument (starting from 0). This can be sparsely
386 /// populated; arguments with no entry in Args use 'DefaultArgEffect'.
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000387 ArgEffects Args;
Mike Stump11289f42009-09-09 15:08:12 +0000388
Ted Kremenekcb2e6362008-05-06 15:44:25 +0000389 /// DefaultArgEffect - The default ArgEffect to apply to arguments that
390 /// do not have an entry in Args.
Ted Kremeneke8300e52012-01-04 00:35:45 +0000391 ArgEffect DefaultArgEffect;
Mike Stump11289f42009-09-09 15:08:12 +0000392
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000393 /// Receiver - If this summary applies to an Objective-C message expression,
394 /// this is the effect applied to the state of the receiver.
Ted Kremeneke8300e52012-01-04 00:35:45 +0000395 ArgEffect Receiver;
Mike Stump11289f42009-09-09 15:08:12 +0000396
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000397 /// Ret - The effect on the return value. Used to indicate if the
Jordy Rose898a1482011-08-21 21:58:18 +0000398 /// function/method call returns a new tracked symbol.
Ted Kremeneke8300e52012-01-04 00:35:45 +0000399 RetEffect Ret;
Mike Stump11289f42009-09-09 15:08:12 +0000400
Ted Kremenek819e9b62008-03-11 06:39:11 +0000401public:
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000402 RetainSummary(ArgEffects A, RetEffect R, ArgEffect defaultEff,
Jordy Rose5a3c9ff2011-08-20 20:55:40 +0000403 ArgEffect ReceiverEff)
404 : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R) {}
Mike Stump11289f42009-09-09 15:08:12 +0000405
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000406 /// getArg - Return the argument effect on the argument specified by
407 /// idx (starting from 0).
Ted Kremenekbf9d8042008-03-11 17:48:22 +0000408 ArgEffect getArg(unsigned idx) const {
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000409 if (const ArgEffect *AE = Args.lookup(idx))
410 return *AE;
Mike Stump11289f42009-09-09 15:08:12 +0000411
Ted Kremenekcb2e6362008-05-06 15:44:25 +0000412 return DefaultArgEffect;
Ted Kremenekbf9d8042008-03-11 17:48:22 +0000413 }
Ted Kremenek71c080f2013-08-14 23:41:49 +0000414
Ted Kremenekafe348e2011-01-27 18:43:03 +0000415 void addArg(ArgEffects::Factory &af, unsigned idx, ArgEffect e) {
416 Args = af.add(Args, idx, e);
417 }
Mike Stump11289f42009-09-09 15:08:12 +0000418
Ted Kremenek1d9a2672009-05-04 05:31:22 +0000419 /// setDefaultArgEffect - Set the default argument effect.
420 void setDefaultArgEffect(ArgEffect E) {
421 DefaultArgEffect = E;
422 }
Mike Stump11289f42009-09-09 15:08:12 +0000423
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000424 /// getRetEffect - Returns the effect on the return value of the call.
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000425 RetEffect getRetEffect() const { return Ret; }
Mike Stump11289f42009-09-09 15:08:12 +0000426
Ted Kremenek1d9a2672009-05-04 05:31:22 +0000427 /// setRetEffect - Set the effect of the return value of the call.
428 void setRetEffect(RetEffect E) { Ret = E; }
Mike Stump11289f42009-09-09 15:08:12 +0000429
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000430
Ted Kremenek0e898382011-01-27 06:54:14 +0000431 /// Sets the effect on the receiver of the message.
432 void setReceiverEffect(ArgEffect e) { Receiver = e; }
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000433
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000434 /// getReceiverEffect - Returns the effect on the receiver of the call.
435 /// This is only meaningful if the summary applies to an ObjCMessageExpr*.
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000436 ArgEffect getReceiverEffect() const { return Receiver; }
Jordy Rose212e4592011-08-23 04:27:15 +0000437
438 /// Test if two retain summaries are identical. Note that merely equivalent
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000439 /// summaries are not necessarily identical (for example, if an explicit
Jordy Rose212e4592011-08-23 04:27:15 +0000440 /// argument effect matches the default effect).
441 bool operator==(const RetainSummary &Other) const {
442 return Args == Other.Args && DefaultArgEffect == Other.DefaultArgEffect &&
443 Receiver == Other.Receiver && Ret == Other.Ret;
444 }
Jordy Rose61c974b2012-03-18 01:26:10 +0000445
446 /// Profile this summary for inclusion in a FoldingSet.
447 void Profile(llvm::FoldingSetNodeID& ID) const {
448 ID.Add(Args);
449 ID.Add(DefaultArgEffect);
450 ID.Add(Receiver);
451 ID.Add(Ret);
452 }
453
454 /// A retain summary is simple if it has no ArgEffects other than the default.
455 bool isSimple() const {
456 return Args.isEmpty();
457 }
Jordan Roseeec15392012-07-02 19:27:43 +0000458
459private:
460 ArgEffects getArgEffects() const { return Args; }
461 ArgEffect getDefaultArgEffect() const { return DefaultArgEffect; }
462
463 friend class RetainSummaryManager;
Ted Kremenek819e9b62008-03-11 06:39:11 +0000464};
Ted Kremenek0cfc1612008-06-23 23:30:29 +0000465} // end anonymous namespace
Ted Kremenek819e9b62008-03-11 06:39:11 +0000466
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000467//===----------------------------------------------------------------------===//
468// Data structures for constructing summaries.
469//===----------------------------------------------------------------------===//
Ted Kremenekb1d13292008-06-24 03:49:48 +0000470
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000471namespace {
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +0000472class ObjCSummaryKey {
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000473 IdentifierInfo* II;
474 Selector S;
Mike Stump11289f42009-09-09 15:08:12 +0000475public:
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000476 ObjCSummaryKey(IdentifierInfo* ii, Selector s)
477 : II(ii), S(s) {}
478
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000479 ObjCSummaryKey(const ObjCInterfaceDecl *d, Selector s)
Craig Topper0dbb7832014-05-27 02:45:47 +0000480 : II(d ? d->getIdentifier() : nullptr), S(s) {}
Ted Kremenek5801f652009-05-13 18:16:01 +0000481
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000482 ObjCSummaryKey(Selector s)
Craig Topper0dbb7832014-05-27 02:45:47 +0000483 : II(nullptr), S(s) {}
Mike Stump11289f42009-09-09 15:08:12 +0000484
Ted Kremeneke8300e52012-01-04 00:35:45 +0000485 IdentifierInfo *getIdentifier() const { return II; }
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000486 Selector getSelector() const { return S; }
487};
Hans Wennborgdcfba332015-10-06 23:40:43 +0000488} // end anonymous namespace
Ted Kremenek0cfc1612008-06-23 23:30:29 +0000489
490namespace llvm {
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000491template <> struct DenseMapInfo<ObjCSummaryKey> {
492 static inline ObjCSummaryKey getEmptyKey() {
493 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
494 DenseMapInfo<Selector>::getEmptyKey());
495 }
Mike Stump11289f42009-09-09 15:08:12 +0000496
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000497 static inline ObjCSummaryKey getTombstoneKey() {
498 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
Mike Stump11289f42009-09-09 15:08:12 +0000499 DenseMapInfo<Selector>::getTombstoneKey());
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000500 }
Mike Stump11289f42009-09-09 15:08:12 +0000501
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000502 static unsigned getHashValue(const ObjCSummaryKey &V) {
Benjamin Kramer69b5a602012-05-27 13:28:44 +0000503 typedef std::pair<IdentifierInfo*, Selector> PairTy;
504 return DenseMapInfo<PairTy>::getHashValue(PairTy(V.getIdentifier(),
505 V.getSelector()));
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000506 }
Mike Stump11289f42009-09-09 15:08:12 +0000507
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000508 static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
Benjamin Kramer69b5a602012-05-27 13:28:44 +0000509 return LHS.getIdentifier() == RHS.getIdentifier() &&
510 LHS.getSelector() == RHS.getSelector();
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000511 }
Mike Stump11289f42009-09-09 15:08:12 +0000512
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000513};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000514} // end llvm namespace
Mike Stump11289f42009-09-09 15:08:12 +0000515
Ted Kremenek0cfc1612008-06-23 23:30:29 +0000516namespace {
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +0000517class ObjCSummaryCache {
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000518 typedef llvm::DenseMap<ObjCSummaryKey, const RetainSummary *> MapTy;
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000519 MapTy M;
520public:
521 ObjCSummaryCache() {}
Mike Stump11289f42009-09-09 15:08:12 +0000522
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000523 const RetainSummary * find(const ObjCInterfaceDecl *D, Selector S) {
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000524 // Do a lookup with the (D,S) pair. If we find a match return
525 // the iterator.
526 ObjCSummaryKey K(D, S);
527 MapTy::iterator I = M.find(K);
Mike Stump11289f42009-09-09 15:08:12 +0000528
Jordan Roseeec15392012-07-02 19:27:43 +0000529 if (I != M.end())
Ted Kremenek8be51382009-07-21 23:27:57 +0000530 return I->second;
Jordan Roseeec15392012-07-02 19:27:43 +0000531 if (!D)
Craig Topper0dbb7832014-05-27 02:45:47 +0000532 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000533
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000534 // Walk the super chain. If we find a hit with a parent, we'll end
535 // up returning that summary. We actually allow that key (null,S), as
536 // we cache summaries for the null ObjCInterfaceDecl* to allow us to
537 // generate initial summaries without having to worry about NSObject
538 // being declared.
539 // FIXME: We may change this at some point.
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000540 for (ObjCInterfaceDecl *C=D->getSuperClass() ;; C=C->getSuperClass()) {
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000541 if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
542 break;
Mike Stump11289f42009-09-09 15:08:12 +0000543
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000544 if (!C)
Craig Topper0dbb7832014-05-27 02:45:47 +0000545 return nullptr;
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000546 }
Mike Stump11289f42009-09-09 15:08:12 +0000547
548 // Cache the summary with original key to make the next lookup faster
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000549 // and return the iterator.
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000550 const RetainSummary *Summ = I->second;
Ted Kremenek8be51382009-07-21 23:27:57 +0000551 M[K] = Summ;
552 return Summ;
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000553 }
Mike Stump11289f42009-09-09 15:08:12 +0000554
Ted Kremeneke8300e52012-01-04 00:35:45 +0000555 const RetainSummary *find(IdentifierInfo* II, Selector S) {
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000556 // FIXME: Class method lookup. Right now we dont' have a good way
557 // of going between IdentifierInfo* and the class hierarchy.
Ted Kremenek8be51382009-07-21 23:27:57 +0000558 MapTy::iterator I = M.find(ObjCSummaryKey(II, S));
Mike Stump11289f42009-09-09 15:08:12 +0000559
Ted Kremenek8be51382009-07-21 23:27:57 +0000560 if (I == M.end())
561 I = M.find(ObjCSummaryKey(S));
Mike Stump11289f42009-09-09 15:08:12 +0000562
Craig Topper0dbb7832014-05-27 02:45:47 +0000563 return I == M.end() ? nullptr : I->second;
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000564 }
Mike Stump11289f42009-09-09 15:08:12 +0000565
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000566 const RetainSummary *& operator[](ObjCSummaryKey K) {
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000567 return M[K];
568 }
Mike Stump11289f42009-09-09 15:08:12 +0000569
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000570 const RetainSummary *& operator[](Selector S) {
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000571 return M[ ObjCSummaryKey(S) ];
572 }
Mike Stump11289f42009-09-09 15:08:12 +0000573};
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000574} // end anonymous namespace
575
576//===----------------------------------------------------------------------===//
577// Data structures for managing collections of summaries.
578//===----------------------------------------------------------------------===//
579
580namespace {
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +0000581class RetainSummaryManager {
Ted Kremenek00daccd2008-05-05 22:11:16 +0000582
583 //==-----------------------------------------------------------------==//
584 // Typedefs.
585 //==-----------------------------------------------------------------==//
Mike Stump11289f42009-09-09 15:08:12 +0000586
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000587 typedef llvm::DenseMap<const FunctionDecl*, const RetainSummary *>
Ted Kremenek00daccd2008-05-05 22:11:16 +0000588 FuncSummariesTy;
Mike Stump11289f42009-09-09 15:08:12 +0000589
Ted Kremenek0cfc1612008-06-23 23:30:29 +0000590 typedef ObjCSummaryCache ObjCMethodSummariesTy;
Mike Stump11289f42009-09-09 15:08:12 +0000591
Jordy Rose61c974b2012-03-18 01:26:10 +0000592 typedef llvm::FoldingSetNodeWrapper<RetainSummary> CachedSummaryNode;
593
Ted Kremenek00daccd2008-05-05 22:11:16 +0000594 //==-----------------------------------------------------------------==//
595 // Data.
596 //==-----------------------------------------------------------------==//
Mike Stump11289f42009-09-09 15:08:12 +0000597
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000598 /// Ctx - The ASTContext object for the analyzed ASTs.
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000599 ASTContext &Ctx;
Ted Kremenekab54e512008-07-01 17:21:27 +0000600
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000601 /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
Ted Kremenek4b7ca772008-04-29 05:33:51 +0000602 const bool GCEnabled;
Mike Stump11289f42009-09-09 15:08:12 +0000603
John McCall31168b02011-06-15 23:02:42 +0000604 /// Records whether or not the analyzed code runs in ARC mode.
605 const bool ARCEnabled;
606
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000607 /// FuncSummaries - A map from FunctionDecls to summaries.
Mike Stump11289f42009-09-09 15:08:12 +0000608 FuncSummariesTy FuncSummaries;
609
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000610 /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
611 /// to summaries.
Ted Kremenekea736c52008-06-23 22:21:20 +0000612 ObjCMethodSummariesTy ObjCClassMethodSummaries;
Ted Kremenek00daccd2008-05-05 22:11:16 +0000613
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000614 /// ObjCMethodSummaries - A map from selectors to summaries.
Ted Kremenekea736c52008-06-23 22:21:20 +0000615 ObjCMethodSummariesTy ObjCMethodSummaries;
Ted Kremenek00daccd2008-05-05 22:11:16 +0000616
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000617 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
618 /// and all other data used by the checker.
Ted Kremenek00daccd2008-05-05 22:11:16 +0000619 llvm::BumpPtrAllocator BPAlloc;
Mike Stump11289f42009-09-09 15:08:12 +0000620
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000621 /// AF - A factory for ArgEffects objects.
Mike Stump11289f42009-09-09 15:08:12 +0000622 ArgEffects::Factory AF;
623
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000624 /// ScratchArgs - A holding buffer for construct ArgEffects.
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000625 ArgEffects ScratchArgs;
Mike Stump11289f42009-09-09 15:08:12 +0000626
Ted Kremenek9157fbb2009-05-07 23:40:42 +0000627 /// ObjCAllocRetE - Default return effect for methods returning Objective-C
628 /// objects.
629 RetEffect ObjCAllocRetE;
Ted Kremeneka03705c2009-06-05 23:18:01 +0000630
Mike Stump11289f42009-09-09 15:08:12 +0000631 /// ObjCInitRetE - Default return effect for init methods returning
Ted Kremenek815fbb62009-08-20 05:13:36 +0000632 /// Objective-C objects.
Ted Kremeneka03705c2009-06-05 23:18:01 +0000633 RetEffect ObjCInitRetE;
Mike Stump11289f42009-09-09 15:08:12 +0000634
Jordy Rose61c974b2012-03-18 01:26:10 +0000635 /// SimpleSummaries - Used for uniquing summaries that don't have special
636 /// effects.
637 llvm::FoldingSet<CachedSummaryNode> SimpleSummaries;
Mike Stump11289f42009-09-09 15:08:12 +0000638
Ted Kremenek00daccd2008-05-05 22:11:16 +0000639 //==-----------------------------------------------------------------==//
640 // Methods.
641 //==-----------------------------------------------------------------==//
Mike Stump11289f42009-09-09 15:08:12 +0000642
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000643 /// getArgEffects - Returns a persistent ArgEffects object based on the
644 /// data in ScratchArgs.
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000645 ArgEffects getArgEffects();
Ted Kremenek819e9b62008-03-11 06:39:11 +0000646
Jordan Rose77411322013-10-07 17:16:52 +0000647 enum UnaryFuncKind { cfretain, cfrelease, cfautorelease, cfmakecollectable };
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000648
Ted Kremeneke8300e52012-01-04 00:35:45 +0000649 const RetainSummary *getUnarySummary(const FunctionType* FT,
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000650 UnaryFuncKind func);
Mike Stump11289f42009-09-09 15:08:12 +0000651
Ted Kremeneke8300e52012-01-04 00:35:45 +0000652 const RetainSummary *getCFSummaryCreateRule(const FunctionDecl *FD);
653 const RetainSummary *getCFSummaryGetRule(const FunctionDecl *FD);
654 const RetainSummary *getCFCreateGetRuleSummary(const FunctionDecl *FD);
Mike Stump11289f42009-09-09 15:08:12 +0000655
Jordy Rose61c974b2012-03-18 01:26:10 +0000656 const RetainSummary *getPersistentSummary(const RetainSummary &OldSumm);
Ted Kremenek3700b762008-10-29 04:07:07 +0000657
Jordy Rose61c974b2012-03-18 01:26:10 +0000658 const RetainSummary *getPersistentSummary(RetEffect RetEff,
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000659 ArgEffect ReceiverEff = DoNothing,
660 ArgEffect DefaultEff = MayEscape) {
Jordy Rose61c974b2012-03-18 01:26:10 +0000661 RetainSummary Summ(getArgEffects(), RetEff, DefaultEff, ReceiverEff);
662 return getPersistentSummary(Summ);
663 }
664
Ted Kremenekececf9f2012-05-08 00:12:09 +0000665 const RetainSummary *getDoNothingSummary() {
666 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
667 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000668
Jordy Rose61c974b2012-03-18 01:26:10 +0000669 const RetainSummary *getDefaultSummary() {
670 return getPersistentSummary(RetEffect::MakeNoRet(),
671 DoNothing, MayEscape);
Ted Kremenek0806f912008-05-06 00:30:21 +0000672 }
Mike Stump11289f42009-09-09 15:08:12 +0000673
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000674 const RetainSummary *getPersistentStopSummary() {
Jordy Rose61c974b2012-03-18 01:26:10 +0000675 return getPersistentSummary(RetEffect::MakeNoRet(),
676 StopTracking, StopTracking);
Mike Stump11289f42009-09-09 15:08:12 +0000677 }
Ted Kremenek015c3562008-05-06 04:20:12 +0000678
Ted Kremenekea736c52008-06-23 22:21:20 +0000679 void InitializeClassMethodSummaries();
680 void InitializeMethodSummaries();
Ted Kremenekcc3d1882008-10-23 01:56:15 +0000681private:
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000682 void addNSObjectClsMethSummary(Selector S, const RetainSummary *Summ) {
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000683 ObjCClassMethodSummaries[S] = Summ;
684 }
Mike Stump11289f42009-09-09 15:08:12 +0000685
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000686 void addNSObjectMethSummary(Selector S, const RetainSummary *Summ) {
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000687 ObjCMethodSummaries[S] = Summ;
688 }
Ted Kremenek00dfe302009-03-04 23:30:42 +0000689
Ted Kremeneke8a5ba82012-02-18 21:37:48 +0000690 void addClassMethSummary(const char* Cls, const char* name,
691 const RetainSummary *Summ, bool isNullary = true) {
Ted Kremenek00dfe302009-03-04 23:30:42 +0000692 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000693 Selector S = isNullary ? GetNullarySelector(name, Ctx)
Ted Kremeneke8a5ba82012-02-18 21:37:48 +0000694 : GetUnarySelector(name, Ctx);
Ted Kremenek00dfe302009-03-04 23:30:42 +0000695 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
696 }
Mike Stump11289f42009-09-09 15:08:12 +0000697
Ted Kremenekdce78462009-02-25 02:54:57 +0000698 void addInstMethSummary(const char* Cls, const char* nullaryName,
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000699 const RetainSummary *Summ) {
Ted Kremenekdce78462009-02-25 02:54:57 +0000700 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
701 Selector S = GetNullarySelector(nullaryName, Ctx);
702 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
703 }
Mike Stump11289f42009-09-09 15:08:12 +0000704
Jordan Rose0675c872014-04-09 01:39:22 +0000705 void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy &Summaries,
706 const RetainSummary *Summ, va_list argp) {
707 Selector S = getKeywordSelector(Ctx, argp);
Ted Kremenek8a5ad392009-04-24 17:50:11 +0000708 Summaries[ObjCSummaryKey(ClsII, S)] = Summ;
Ted Kremenek3b2294c2008-07-18 17:24:20 +0000709 }
Mike Stump11289f42009-09-09 15:08:12 +0000710
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000711 void addInstMethSummary(const char* Cls, const RetainSummary * Summ, ...) {
Ted Kremenek3f13f592008-08-12 18:48:50 +0000712 va_list argp;
713 va_start(argp, Summ);
Ted Kremenek8a5ad392009-04-24 17:50:11 +0000714 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Mike Stump11289f42009-09-09 15:08:12 +0000715 va_end(argp);
Ted Kremenek3f13f592008-08-12 18:48:50 +0000716 }
Mike Stump11289f42009-09-09 15:08:12 +0000717
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000718 void addClsMethSummary(const char* Cls, const RetainSummary * Summ, ...) {
Ted Kremenek8a5ad392009-04-24 17:50:11 +0000719 va_list argp;
720 va_start(argp, Summ);
721 addMethodSummary(&Ctx.Idents.get(Cls),ObjCClassMethodSummaries, Summ, argp);
722 va_end(argp);
723 }
Mike Stump11289f42009-09-09 15:08:12 +0000724
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000725 void addClsMethSummary(IdentifierInfo *II, const RetainSummary * Summ, ...) {
Ted Kremenek8a5ad392009-04-24 17:50:11 +0000726 va_list argp;
727 va_start(argp, Summ);
728 addMethodSummary(II, ObjCClassMethodSummaries, Summ, argp);
729 va_end(argp);
730 }
731
Ted Kremenek819e9b62008-03-11 06:39:11 +0000732public:
Mike Stump11289f42009-09-09 15:08:12 +0000733
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000734 RetainSummaryManager(ASTContext &ctx, bool gcenabled, bool usesARC)
Ted Kremenekab54e512008-07-01 17:21:27 +0000735 : Ctx(ctx),
John McCall31168b02011-06-15 23:02:42 +0000736 GCEnabled(gcenabled),
737 ARCEnabled(usesARC),
738 AF(BPAlloc), ScratchArgs(AF.getEmptyMap()),
739 ObjCAllocRetE(gcenabled
740 ? RetEffect::MakeGCNotOwned()
Jordan Rose6ad4cb42014-01-07 21:39:41 +0000741 : (usesARC ? RetEffect::MakeNotOwned(RetEffect::ObjC)
John McCall31168b02011-06-15 23:02:42 +0000742 : RetEffect::MakeOwned(RetEffect::ObjC, true))),
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000743 ObjCInitRetE(gcenabled
John McCall31168b02011-06-15 23:02:42 +0000744 ? RetEffect::MakeGCNotOwned()
Jordan Rose6ad4cb42014-01-07 21:39:41 +0000745 : (usesARC ? RetEffect::MakeNotOwned(RetEffect::ObjC)
Jordy Rose61c974b2012-03-18 01:26:10 +0000746 : RetEffect::MakeOwnedWhenTrackedReceiver())) {
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000747 InitializeClassMethodSummaries();
748 InitializeMethodSummaries();
749 }
Mike Stump11289f42009-09-09 15:08:12 +0000750
Jordan Roseeec15392012-07-02 19:27:43 +0000751 const RetainSummary *getSummary(const CallEvent &Call,
Craig Topper0dbb7832014-05-27 02:45:47 +0000752 ProgramStateRef State = nullptr);
Mike Stump11289f42009-09-09 15:08:12 +0000753
Jordan Roseeec15392012-07-02 19:27:43 +0000754 const RetainSummary *getFunctionSummary(const FunctionDecl *FD);
755
756 const RetainSummary *getMethodSummary(Selector S, const ObjCInterfaceDecl *ID,
Jordy Rose35e71c72012-03-17 21:13:07 +0000757 const ObjCMethodDecl *MD,
758 QualType RetTy,
759 ObjCMethodSummariesTy &CachedSummaries);
760
Jordan Rose6bad4902012-07-02 19:27:56 +0000761 const RetainSummary *getInstanceMethodSummary(const ObjCMethodCall &M,
Jordan Roseeec15392012-07-02 19:27:43 +0000762 ProgramStateRef State);
Ted Kremenekbd862712010-07-01 20:16:50 +0000763
Jordan Rose6bad4902012-07-02 19:27:56 +0000764 const RetainSummary *getClassMethodSummary(const ObjCMethodCall &M) {
Jordan Roseeec15392012-07-02 19:27:43 +0000765 assert(!M.isInstanceMessage());
766 const ObjCInterfaceDecl *Class = M.getReceiverInterface();
Mike Stump11289f42009-09-09 15:08:12 +0000767
Jordan Roseeec15392012-07-02 19:27:43 +0000768 return getMethodSummary(M.getSelector(), Class, M.getDecl(),
769 M.getResultType(), ObjCClassMethodSummaries);
Ted Kremenek7686ffa2009-04-29 00:42:39 +0000770 }
Ted Kremenek99fe1692009-04-29 17:17:48 +0000771
772 /// getMethodSummary - This version of getMethodSummary is used to query
773 /// the summary for the current method being analyzed.
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000774 const RetainSummary *getMethodSummary(const ObjCMethodDecl *MD) {
Ted Kremenek223a7d52009-04-29 23:03:22 +0000775 const ObjCInterfaceDecl *ID = MD->getClassInterface();
Ted Kremenekb2a143f2009-04-30 05:41:14 +0000776 Selector S = MD->getSelector();
Alp Toker314cc812014-01-25 16:55:45 +0000777 QualType ResultTy = MD->getReturnType();
Mike Stump11289f42009-09-09 15:08:12 +0000778
Jordy Rose35e71c72012-03-17 21:13:07 +0000779 ObjCMethodSummariesTy *CachedSummaries;
Ted Kremenek99fe1692009-04-29 17:17:48 +0000780 if (MD->isInstanceMethod())
Jordy Rose35e71c72012-03-17 21:13:07 +0000781 CachedSummaries = &ObjCMethodSummaries;
Ted Kremenek99fe1692009-04-29 17:17:48 +0000782 else
Jordy Rose35e71c72012-03-17 21:13:07 +0000783 CachedSummaries = &ObjCClassMethodSummaries;
784
Jordan Roseeec15392012-07-02 19:27:43 +0000785 return getMethodSummary(S, ID, MD, ResultTy, *CachedSummaries);
Ted Kremenek99fe1692009-04-29 17:17:48 +0000786 }
Mike Stump11289f42009-09-09 15:08:12 +0000787
Jordy Rose35e71c72012-03-17 21:13:07 +0000788 const RetainSummary *getStandardMethodSummary(const ObjCMethodDecl *MD,
Jordan Roseeec15392012-07-02 19:27:43 +0000789 Selector S, QualType RetTy);
Ted Kremenek223a7d52009-04-29 23:03:22 +0000790
Jordan Rose39032472013-04-04 22:31:48 +0000791 /// Determine if there is a special return effect for this function or method.
792 Optional<RetEffect> getRetEffectFromAnnotations(QualType RetTy,
793 const Decl *D);
794
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000795 void updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenekc2de7272009-05-09 02:58:13 +0000796 const ObjCMethodDecl *MD);
797
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000798 void updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenekc2de7272009-05-09 02:58:13 +0000799 const FunctionDecl *FD);
800
Jordan Roseeec15392012-07-02 19:27:43 +0000801 void updateSummaryForCall(const RetainSummary *&Summ,
802 const CallEvent &Call);
803
Ted Kremenek00daccd2008-05-05 22:11:16 +0000804 bool isGCEnabled() const { return GCEnabled; }
Mike Stump11289f42009-09-09 15:08:12 +0000805
John McCall31168b02011-06-15 23:02:42 +0000806 bool isARCEnabled() const { return ARCEnabled; }
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000807
John McCall31168b02011-06-15 23:02:42 +0000808 bool isARCorGCEnabled() const { return GCEnabled || ARCEnabled; }
Jordan Roseeec15392012-07-02 19:27:43 +0000809
810 RetEffect getObjAllocRetEffect() const { return ObjCAllocRetE; }
811
812 friend class RetainSummaryTemplate;
Ted Kremenek819e9b62008-03-11 06:39:11 +0000813};
Mike Stump11289f42009-09-09 15:08:12 +0000814
Jordy Rose14de7c52011-08-24 09:02:37 +0000815// Used to avoid allocating long-term (BPAlloc'd) memory for default retain
816// summaries. If a function or method looks like it has a default summary, but
817// it has annotations, the annotations are added to the stack-based template
818// and then copied into managed memory.
819class RetainSummaryTemplate {
820 RetainSummaryManager &Manager;
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000821 const RetainSummary *&RealSummary;
Jordy Rose14de7c52011-08-24 09:02:37 +0000822 RetainSummary ScratchSummary;
823 bool Accessed;
824public:
Jordan Roseeec15392012-07-02 19:27:43 +0000825 RetainSummaryTemplate(const RetainSummary *&real, RetainSummaryManager &mgr)
826 : Manager(mgr), RealSummary(real), ScratchSummary(*real), Accessed(false) {}
Jordy Rose14de7c52011-08-24 09:02:37 +0000827
828 ~RetainSummaryTemplate() {
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000829 if (Accessed)
Jordy Rose61c974b2012-03-18 01:26:10 +0000830 RealSummary = Manager.getPersistentSummary(ScratchSummary);
Jordy Rose14de7c52011-08-24 09:02:37 +0000831 }
832
833 RetainSummary &operator*() {
834 Accessed = true;
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000835 return ScratchSummary;
Jordy Rose14de7c52011-08-24 09:02:37 +0000836 }
837
838 RetainSummary *operator->() {
839 Accessed = true;
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000840 return &ScratchSummary;
Jordy Rose14de7c52011-08-24 09:02:37 +0000841 }
842};
843
Ted Kremenek819e9b62008-03-11 06:39:11 +0000844} // end anonymous namespace
845
846//===----------------------------------------------------------------------===//
847// Implementation of checker data structures.
848//===----------------------------------------------------------------------===//
849
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000850ArgEffects RetainSummaryManager::getArgEffects() {
851 ArgEffects AE = ScratchArgs;
Ted Kremenekb3b56c62010-11-24 00:54:37 +0000852 ScratchArgs = AF.getEmptyMap();
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000853 return AE;
Ted Kremenek68d73d12008-03-12 01:21:45 +0000854}
855
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000856const RetainSummary *
Jordy Rose61c974b2012-03-18 01:26:10 +0000857RetainSummaryManager::getPersistentSummary(const RetainSummary &OldSumm) {
858 // Unique "simple" summaries -- those without ArgEffects.
859 if (OldSumm.isSimple()) {
860 llvm::FoldingSetNodeID ID;
861 OldSumm.Profile(ID);
862
863 void *Pos;
864 CachedSummaryNode *N = SimpleSummaries.FindNodeOrInsertPos(ID, Pos);
865
866 if (!N) {
867 N = (CachedSummaryNode *) BPAlloc.Allocate<CachedSummaryNode>();
868 new (N) CachedSummaryNode(OldSumm);
869 SimpleSummaries.InsertNode(N, Pos);
870 }
871
872 return &N->getValue();
873 }
874
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000875 RetainSummary *Summ = (RetainSummary *) BPAlloc.Allocate<RetainSummary>();
Jordy Rose61c974b2012-03-18 01:26:10 +0000876 new (Summ) RetainSummary(OldSumm);
Ted Kremenek68d73d12008-03-12 01:21:45 +0000877 return Summ;
878}
879
Ted Kremenek00daccd2008-05-05 22:11:16 +0000880//===----------------------------------------------------------------------===//
881// Summary creation for functions (largely uses of Core Foundation).
882//===----------------------------------------------------------------------===//
Ted Kremenek68d73d12008-03-12 01:21:45 +0000883
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000884static bool isRetain(const FunctionDecl *FD, StringRef FName) {
Benjamin Kramereaabbd82010-02-08 18:38:55 +0000885 return FName.endswith("Retain");
Ted Kremenek7e904222009-01-12 21:45:02 +0000886}
887
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000888static bool isRelease(const FunctionDecl *FD, StringRef FName) {
Benjamin Kramereaabbd82010-02-08 18:38:55 +0000889 return FName.endswith("Release");
Ted Kremenek7e904222009-01-12 21:45:02 +0000890}
891
Jordan Rose77411322013-10-07 17:16:52 +0000892static bool isAutorelease(const FunctionDecl *FD, StringRef FName) {
893 return FName.endswith("Autorelease");
894}
895
Jordy Rose898a1482011-08-21 21:58:18 +0000896static bool isMakeCollectable(const FunctionDecl *FD, StringRef FName) {
897 // FIXME: Remove FunctionDecl parameter.
898 // FIXME: Is it really okay if MakeCollectable isn't a suffix?
899 return FName.find("MakeCollectable") != StringRef::npos;
900}
901
Anna Zaks25612732012-08-29 23:23:43 +0000902static ArgEffect getStopTrackingHardEquivalent(ArgEffect E) {
Jordan Roseeec15392012-07-02 19:27:43 +0000903 switch (E) {
904 case DoNothing:
905 case Autorelease:
Benjamin Kramer2501f142013-10-20 11:47:15 +0000906 case DecRefBridgedTransferred:
Jordan Roseeec15392012-07-02 19:27:43 +0000907 case IncRef:
908 case IncRefMsg:
909 case MakeCollectable:
Douglas Gregoreb6e64c2015-06-19 23:17:46 +0000910 case UnretainedOutParameter:
911 case RetainedOutParameter:
Jordan Roseeec15392012-07-02 19:27:43 +0000912 case MayEscape:
Jordan Roseeec15392012-07-02 19:27:43 +0000913 case StopTracking:
Anna Zaks25612732012-08-29 23:23:43 +0000914 case StopTrackingHard:
915 return StopTrackingHard;
Jordan Roseeec15392012-07-02 19:27:43 +0000916 case DecRef:
Anna Zaks25612732012-08-29 23:23:43 +0000917 case DecRefAndStopTrackingHard:
918 return DecRefAndStopTrackingHard;
Jordan Roseeec15392012-07-02 19:27:43 +0000919 case DecRefMsg:
Anna Zaks25612732012-08-29 23:23:43 +0000920 case DecRefMsgAndStopTrackingHard:
921 return DecRefMsgAndStopTrackingHard;
Jordan Roseeec15392012-07-02 19:27:43 +0000922 case Dealloc:
923 return Dealloc;
924 }
925
926 llvm_unreachable("Unknown ArgEffect kind");
927}
928
929void RetainSummaryManager::updateSummaryForCall(const RetainSummary *&S,
930 const CallEvent &Call) {
931 if (Call.hasNonZeroCallbackArg()) {
Anna Zaks25612732012-08-29 23:23:43 +0000932 ArgEffect RecEffect =
933 getStopTrackingHardEquivalent(S->getReceiverEffect());
934 ArgEffect DefEffect =
935 getStopTrackingHardEquivalent(S->getDefaultArgEffect());
Jordan Roseeec15392012-07-02 19:27:43 +0000936
937 ArgEffects CustomArgEffects = S->getArgEffects();
938 for (ArgEffects::iterator I = CustomArgEffects.begin(),
939 E = CustomArgEffects.end();
940 I != E; ++I) {
Anna Zaks25612732012-08-29 23:23:43 +0000941 ArgEffect Translated = getStopTrackingHardEquivalent(I->second);
Jordan Roseeec15392012-07-02 19:27:43 +0000942 if (Translated != DefEffect)
943 ScratchArgs = AF.add(ScratchArgs, I->first, Translated);
944 }
945
Anna Zaks25612732012-08-29 23:23:43 +0000946 RetEffect RE = RetEffect::MakeNoRetHard();
Jordan Roseeec15392012-07-02 19:27:43 +0000947
948 // Special cases where the callback argument CANNOT free the return value.
949 // This can generally only happen if we know that the callback will only be
950 // called when the return value is already being deallocated.
Jordan Rose2a833ca2014-01-15 17:25:15 +0000951 if (const SimpleFunctionCall *FC = dyn_cast<SimpleFunctionCall>(&Call)) {
Jordan Roseccf192e2012-09-01 17:39:13 +0000952 if (IdentifierInfo *Name = FC->getDecl()->getIdentifier()) {
953 // When the CGBitmapContext is deallocated, the callback here will free
954 // the associated data buffer.
Jordan Rosed65f1c82012-08-31 18:19:18 +0000955 if (Name->isStr("CGBitmapContextCreateWithData"))
956 RE = S->getRetEffect();
Jordan Roseccf192e2012-09-01 17:39:13 +0000957 }
Jordan Roseeec15392012-07-02 19:27:43 +0000958 }
959
960 S = getPersistentSummary(RE, RecEffect, DefEffect);
961 }
Anna Zaks3d5d3d32012-08-24 00:06:12 +0000962
963 // Special case '[super init];' and '[self init];'
964 //
965 // Even though calling '[super init]' without assigning the result to self
966 // and checking if the parent returns 'nil' is a bad pattern, it is common.
967 // Additionally, our Self Init checker already warns about it. To avoid
968 // overwhelming the user with messages from both checkers, we model the case
969 // of '[super init]' in cases when it is not consumed by another expression
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000970 // as if the call preserves the value of 'self'; essentially, assuming it can
Anna Zaks3d5d3d32012-08-24 00:06:12 +0000971 // never fail and return 'nil'.
972 // Note, we don't want to just stop tracking the value since we want the
973 // RetainCount checker to report leaks and use-after-free if SelfInit checker
974 // is turned off.
975 if (const ObjCMethodCall *MC = dyn_cast<ObjCMethodCall>(&Call)) {
976 if (MC->getMethodFamily() == OMF_init && MC->isReceiverSelfOrSuper()) {
977
978 // Check if the message is not consumed, we know it will not be used in
979 // an assignment, ex: "self = [super init]".
980 const Expr *ME = MC->getOriginExpr();
981 const LocationContext *LCtx = MC->getLocationContext();
982 ParentMap &PM = LCtx->getAnalysisDeclContext()->getParentMap();
983 if (!PM.isConsumedExpr(ME)) {
984 RetainSummaryTemplate ModifiableSummaryTemplate(S, *this);
985 ModifiableSummaryTemplate->setReceiverEffect(DoNothing);
986 ModifiableSummaryTemplate->setRetEffect(RetEffect::MakeNoRet());
987 }
988 }
Anna Zaks3d5d3d32012-08-24 00:06:12 +0000989 }
Jordan Roseeec15392012-07-02 19:27:43 +0000990}
991
Anna Zaksf4c5ea52012-05-04 22:18:39 +0000992const RetainSummary *
Jordan Roseeec15392012-07-02 19:27:43 +0000993RetainSummaryManager::getSummary(const CallEvent &Call,
994 ProgramStateRef State) {
995 const RetainSummary *Summ;
996 switch (Call.getKind()) {
997 case CE_Function:
Jordan Rose2a833ca2014-01-15 17:25:15 +0000998 Summ = getFunctionSummary(cast<SimpleFunctionCall>(Call).getDecl());
Jordan Roseeec15392012-07-02 19:27:43 +0000999 break;
1000 case CE_CXXMember:
Jordan Rose017591a2012-07-03 22:55:57 +00001001 case CE_CXXMemberOperator:
Jordan Roseeec15392012-07-02 19:27:43 +00001002 case CE_Block:
1003 case CE_CXXConstructor:
Jordan Rose4ee71b82012-07-10 22:07:47 +00001004 case CE_CXXDestructor:
Jordan Rosea4ee0642012-07-02 22:21:47 +00001005 case CE_CXXAllocator:
Jordan Roseeec15392012-07-02 19:27:43 +00001006 // FIXME: These calls are currently unsupported.
1007 return getPersistentStopSummary();
Jordan Rose627b0462012-07-18 21:59:51 +00001008 case CE_ObjCMessage: {
Jordan Rose6bad4902012-07-02 19:27:56 +00001009 const ObjCMethodCall &Msg = cast<ObjCMethodCall>(Call);
Jordan Roseeec15392012-07-02 19:27:43 +00001010 if (Msg.isInstanceMessage())
1011 Summ = getInstanceMethodSummary(Msg, State);
1012 else
1013 Summ = getClassMethodSummary(Msg);
1014 break;
1015 }
1016 }
1017
1018 updateSummaryForCall(Summ, Call);
1019
1020 assert(Summ && "Unknown call type?");
1021 return Summ;
1022}
1023
1024const RetainSummary *
1025RetainSummaryManager::getFunctionSummary(const FunctionDecl *FD) {
1026 // If we don't know what function we're calling, use our default summary.
1027 if (!FD)
1028 return getDefaultSummary();
1029
Ted Kremenekf7141592008-04-24 17:22:33 +00001030 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremenek00daccd2008-05-05 22:11:16 +00001031 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremenek00daccd2008-05-05 22:11:16 +00001032 if (I != FuncSummaries.end())
Ted Kremenekf7141592008-04-24 17:22:33 +00001033 return I->second;
1034
Ted Kremenekdf76e6d2009-05-04 15:34:07 +00001035 // No summary? Generate one.
Craig Topper0dbb7832014-05-27 02:45:47 +00001036 const RetainSummary *S = nullptr;
Jordan Rose1c715602012-08-06 21:28:02 +00001037 bool AllowAnnotations = true;
Mike Stump11289f42009-09-09 15:08:12 +00001038
Ted Kremenekfa89e2f2008-07-15 16:50:12 +00001039 do {
Ted Kremenek7e904222009-01-12 21:45:02 +00001040 // We generate "stop" summaries for implicitly defined functions.
1041 if (FD->isImplicit()) {
1042 S = getPersistentStopSummary();
1043 break;
Ted Kremenekfa89e2f2008-07-15 16:50:12 +00001044 }
Mike Stump11289f42009-09-09 15:08:12 +00001045
John McCall9dd450b2009-09-21 23:43:11 +00001046 // [PR 3337] Use 'getAs<FunctionType>' to strip away any typedefs on the
Ted Kremenek86afde32009-01-16 18:40:33 +00001047 // function's type.
John McCall9dd450b2009-09-21 23:43:11 +00001048 const FunctionType* FT = FD->getType()->getAs<FunctionType>();
Ted Kremenek9bcc2642009-12-16 06:06:43 +00001049 const IdentifierInfo *II = FD->getIdentifier();
1050 if (!II)
1051 break;
Benjamin Kramereaabbd82010-02-08 18:38:55 +00001052
1053 StringRef FName = II->getName();
Mike Stump11289f42009-09-09 15:08:12 +00001054
Ted Kremenek5f968932009-03-05 22:11:14 +00001055 // Strip away preceding '_'. Doing this here will effect all the checks
1056 // down below.
Benjamin Kramereaabbd82010-02-08 18:38:55 +00001057 FName = FName.substr(FName.find_first_not_of('_'));
Mike Stump11289f42009-09-09 15:08:12 +00001058
Ted Kremenek7e904222009-01-12 21:45:02 +00001059 // Inspect the result type.
Alp Toker314cc812014-01-25 16:55:45 +00001060 QualType RetTy = FT->getReturnType();
Mike Stump11289f42009-09-09 15:08:12 +00001061
Ted Kremenek7e904222009-01-12 21:45:02 +00001062 // FIXME: This should all be refactored into a chain of "summary lookup"
1063 // filters.
Ted Kremenekb4ec3fc2009-10-14 00:27:24 +00001064 assert(ScratchArgs.isEmpty());
Ted Kremenek3092e9c2009-06-15 20:36:07 +00001065
Ted Kremenek01d152f2012-04-26 04:32:23 +00001066 if (FName == "pthread_create" || FName == "pthread_setspecific") {
1067 // Part of: <rdar://problem/7299394> and <rdar://problem/11282706>.
1068 // This will be addressed better with IPA.
Benjamin Kramereaabbd82010-02-08 18:38:55 +00001069 S = getPersistentStopSummary();
1070 } else if (FName == "NSMakeCollectable") {
1071 // Handle: id NSMakeCollectable(CFTypeRef)
1072 S = (RetTy->isObjCIdType())
1073 ? getUnarySummary(FT, cfmakecollectable)
1074 : getPersistentStopSummary();
Jordan Rose1c715602012-08-06 21:28:02 +00001075 // The headers on OS X 10.8 use cf_consumed/ns_returns_retained,
1076 // but we can fully model NSMakeCollectable ourselves.
1077 AllowAnnotations = false;
Ted Kremenekc008db92012-09-06 23:47:02 +00001078 } else if (FName == "CFPlugInInstanceCreate") {
1079 S = getPersistentSummary(RetEffect::MakeNoRet());
Benjamin Kramereaabbd82010-02-08 18:38:55 +00001080 } else if (FName == "IOBSDNameMatching" ||
1081 FName == "IOServiceMatching" ||
1082 FName == "IOServiceNameMatching" ||
Ted Kremenek555560c2012-05-01 05:28:27 +00001083 FName == "IORegistryEntrySearchCFProperty" ||
Benjamin Kramereaabbd82010-02-08 18:38:55 +00001084 FName == "IORegistryEntryIDMatching" ||
1085 FName == "IOOpenFirmwarePathMatching") {
1086 // Part of <rdar://problem/6961230>. (IOKit)
1087 // This should be addressed using a API table.
1088 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1089 DoNothing, DoNothing);
1090 } else if (FName == "IOServiceGetMatchingService" ||
1091 FName == "IOServiceGetMatchingServices") {
1092 // FIXES: <rdar://problem/6326900>
1093 // This should be addressed using a API table. This strcmp is also
1094 // a little gross, but there is no need to super optimize here.
Ted Kremenekb3b56c62010-11-24 00:54:37 +00001095 ScratchArgs = AF.add(ScratchArgs, 1, DecRef);
Benjamin Kramereaabbd82010-02-08 18:38:55 +00001096 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1097 } else if (FName == "IOServiceAddNotification" ||
1098 FName == "IOServiceAddMatchingNotification") {
1099 // Part of <rdar://problem/6961230>. (IOKit)
1100 // This should be addressed using a API table.
Ted Kremenekb3b56c62010-11-24 00:54:37 +00001101 ScratchArgs = AF.add(ScratchArgs, 2, DecRef);
Benjamin Kramereaabbd82010-02-08 18:38:55 +00001102 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1103 } else if (FName == "CVPixelBufferCreateWithBytes") {
1104 // FIXES: <rdar://problem/7283567>
1105 // Eventually this can be improved by recognizing that the pixel
1106 // buffer passed to CVPixelBufferCreateWithBytes is released via
1107 // a callback and doing full IPA to make sure this is done correctly.
1108 // FIXME: This function has an out parameter that returns an
1109 // allocated object.
Ted Kremenekb3b56c62010-11-24 00:54:37 +00001110 ScratchArgs = AF.add(ScratchArgs, 7, StopTracking);
Benjamin Kramereaabbd82010-02-08 18:38:55 +00001111 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1112 } else if (FName == "CGBitmapContextCreateWithData") {
1113 // FIXES: <rdar://problem/7358899>
1114 // Eventually this can be improved by recognizing that 'releaseInfo'
1115 // passed to CGBitmapContextCreateWithData is released via
1116 // a callback and doing full IPA to make sure this is done correctly.
Ted Kremenekb3b56c62010-11-24 00:54:37 +00001117 ScratchArgs = AF.add(ScratchArgs, 8, StopTracking);
Benjamin Kramereaabbd82010-02-08 18:38:55 +00001118 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1119 DoNothing, DoNothing);
1120 } else if (FName == "CVPixelBufferCreateWithPlanarBytes") {
1121 // FIXES: <rdar://problem/7283567>
1122 // Eventually this can be improved by recognizing that the pixel
1123 // buffer passed to CVPixelBufferCreateWithPlanarBytes is released
1124 // via a callback and doing full IPA to make sure this is done
1125 // correctly.
Ted Kremenekb3b56c62010-11-24 00:54:37 +00001126 ScratchArgs = AF.add(ScratchArgs, 12, StopTracking);
Benjamin Kramereaabbd82010-02-08 18:38:55 +00001127 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Jordan Roseb1479182013-05-02 01:51:40 +00001128 } else if (FName == "dispatch_set_context" ||
1129 FName == "xpc_connection_set_context") {
Ted Kremenek40c13432012-03-22 06:29:41 +00001130 // <rdar://problem/11059275> - The analyzer currently doesn't have
1131 // a good way to reason about the finalizer function for libdispatch.
1132 // If we pass a context object that is memory managed, stop tracking it.
Jordan Roseb1479182013-05-02 01:51:40 +00001133 // <rdar://problem/13783514> - Same problem, but for XPC.
Ted Kremenek40c13432012-03-22 06:29:41 +00001134 // FIXME: this hack should possibly go away once we can handle
Jordan Roseb1479182013-05-02 01:51:40 +00001135 // libdispatch and XPC finalizers.
Ted Kremenek40c13432012-03-22 06:29:41 +00001136 ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
1137 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenekececf9f2012-05-08 00:12:09 +00001138 } else if (FName.startswith("NSLog")) {
1139 S = getDoNothingSummary();
Anna Zaks90ab9bf2012-03-30 05:48:16 +00001140 } else if (FName.startswith("NS") &&
1141 (FName.find("Insert") != StringRef::npos)) {
1142 // Whitelist NSXXInsertXX, for example NSMapInsertIfAbsent, since they can
1143 // be deallocated by NSMapRemove. (radar://11152419)
1144 ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
1145 ScratchArgs = AF.add(ScratchArgs, 2, StopTracking);
1146 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenekea675cf2009-06-11 18:17:24 +00001147 }
Mike Stump11289f42009-09-09 15:08:12 +00001148
Ted Kremenekea675cf2009-06-11 18:17:24 +00001149 // Did we get a summary?
1150 if (S)
1151 break;
Ted Kremenek211094d2009-03-17 22:43:44 +00001152
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001153 if (RetTy->isPointerType()) {
Ted Kremenek7e904222009-01-12 21:45:02 +00001154 // For CoreFoundation ('CF') types.
Ted Kremeneke9918352010-01-27 18:00:17 +00001155 if (cocoa::isRefType(RetTy, "CF", FName)) {
Jordan Rose77411322013-10-07 17:16:52 +00001156 if (isRetain(FD, FName)) {
Ted Kremenek7e904222009-01-12 21:45:02 +00001157 S = getUnarySummary(FT, cfretain);
Jordan Rose77411322013-10-07 17:16:52 +00001158 } else if (isAutorelease(FD, FName)) {
1159 S = getUnarySummary(FT, cfautorelease);
1160 // The headers use cf_consumed, but we can fully model CFAutorelease
1161 // ourselves.
1162 AllowAnnotations = false;
1163 } else if (isMakeCollectable(FD, FName)) {
Ted Kremenek7e904222009-01-12 21:45:02 +00001164 S = getUnarySummary(FT, cfmakecollectable);
Jordan Rose77411322013-10-07 17:16:52 +00001165 AllowAnnotations = false;
1166 } else {
John McCall525f0552011-10-01 00:48:56 +00001167 S = getCFCreateGetRuleSummary(FD);
Jordan Rose77411322013-10-07 17:16:52 +00001168 }
Ted Kremenek7e904222009-01-12 21:45:02 +00001169
1170 break;
1171 }
1172
1173 // For CoreGraphics ('CG') types.
Ted Kremeneke9918352010-01-27 18:00:17 +00001174 if (cocoa::isRefType(RetTy, "CG", FName)) {
Ted Kremenek7e904222009-01-12 21:45:02 +00001175 if (isRetain(FD, FName))
1176 S = getUnarySummary(FT, cfretain);
1177 else
John McCall525f0552011-10-01 00:48:56 +00001178 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek7e904222009-01-12 21:45:02 +00001179
1180 break;
1181 }
1182
1183 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
Ted Kremeneke9918352010-01-27 18:00:17 +00001184 if (cocoa::isRefType(RetTy, "DADisk") ||
1185 cocoa::isRefType(RetTy, "DADissenter") ||
1186 cocoa::isRefType(RetTy, "DASessionRef")) {
John McCall525f0552011-10-01 00:48:56 +00001187 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek7e904222009-01-12 21:45:02 +00001188 break;
1189 }
Mike Stump11289f42009-09-09 15:08:12 +00001190
Aaron Ballman9ead1242013-12-19 02:39:40 +00001191 if (FD->hasAttr<CFAuditedTransferAttr>()) {
Jordan Rose85707b22013-03-04 23:21:32 +00001192 S = getCFCreateGetRuleSummary(FD);
1193 break;
1194 }
1195
Ted Kremenek7e904222009-01-12 21:45:02 +00001196 break;
1197 }
1198
1199 // Check for release functions, the only kind of functions that we care
1200 // about that don't return a pointer type.
1201 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
Ted Kremenekac5ab792010-02-08 16:45:01 +00001202 // Test for 'CGCF'.
Benjamin Kramereaabbd82010-02-08 18:38:55 +00001203 FName = FName.substr(FName.startswith("CGCF") ? 4 : 2);
Ted Kremenekac5ab792010-02-08 16:45:01 +00001204
Ted Kremenek5f968932009-03-05 22:11:14 +00001205 if (isRelease(FD, FName))
Ted Kremenek7e904222009-01-12 21:45:02 +00001206 S = getUnarySummary(FT, cfrelease);
1207 else {
Ted Kremenek7d79a5f2009-05-03 05:20:50 +00001208 assert (ScratchArgs.isEmpty());
Ted Kremeneked90de42009-01-29 22:45:13 +00001209 // Remaining CoreFoundation and CoreGraphics functions.
1210 // We use to assume that they all strictly followed the ownership idiom
1211 // and that ownership cannot be transferred. While this is technically
1212 // correct, many methods allow a tracked object to escape. For example:
1213 //
Mike Stump11289f42009-09-09 15:08:12 +00001214 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
Ted Kremeneked90de42009-01-29 22:45:13 +00001215 // CFDictionaryAddValue(y, key, x);
Mike Stump11289f42009-09-09 15:08:12 +00001216 // CFRelease(x);
Ted Kremeneked90de42009-01-29 22:45:13 +00001217 // ... it is okay to use 'x' since 'y' has a reference to it
1218 //
1219 // We handle this and similar cases with the follow heuristic. If the
Ted Kremenekd982f002009-08-20 00:57:22 +00001220 // function name contains "InsertValue", "SetValue", "AddValue",
1221 // "AppendValue", or "SetAttribute", then we assume that arguments may
1222 // "escape." This means that something else holds on to the object,
1223 // allowing it be used even after its local retain count drops to 0.
Benjamin Kramer0129bd72010-01-11 19:46:28 +00001224 ArgEffect E = (StrInStrNoCase(FName, "InsertValue") != StringRef::npos||
1225 StrInStrNoCase(FName, "AddValue") != StringRef::npos ||
1226 StrInStrNoCase(FName, "SetValue") != StringRef::npos ||
1227 StrInStrNoCase(FName, "AppendValue") != StringRef::npos||
Benjamin Kramer37808312010-01-11 20:15:06 +00001228 StrInStrNoCase(FName, "SetAttribute") != StringRef::npos)
Ted Kremeneked90de42009-01-29 22:45:13 +00001229 ? MayEscape : DoNothing;
Mike Stump11289f42009-09-09 15:08:12 +00001230
Ted Kremeneked90de42009-01-29 22:45:13 +00001231 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek7e904222009-01-12 21:45:02 +00001232 }
1233 }
Ted Kremenekfa89e2f2008-07-15 16:50:12 +00001234 }
1235 while (0);
Mike Stump11289f42009-09-09 15:08:12 +00001236
Jordan Roseeec15392012-07-02 19:27:43 +00001237 // If we got all the way here without any luck, use a default summary.
1238 if (!S)
1239 S = getDefaultSummary();
1240
Ted Kremenekc2de7272009-05-09 02:58:13 +00001241 // Annotations override defaults.
Jordan Rose1c715602012-08-06 21:28:02 +00001242 if (AllowAnnotations)
1243 updateSummaryFromAnnotations(S, FD);
Mike Stump11289f42009-09-09 15:08:12 +00001244
Ted Kremenek00daccd2008-05-05 22:11:16 +00001245 FuncSummaries[FD] = S;
Mike Stump11289f42009-09-09 15:08:12 +00001246 return S;
Ted Kremenekea6507f2008-03-06 00:08:09 +00001247}
1248
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001249const RetainSummary *
John McCall525f0552011-10-01 00:48:56 +00001250RetainSummaryManager::getCFCreateGetRuleSummary(const FunctionDecl *FD) {
1251 if (coreFoundation::followsCreateRule(FD))
Ted Kremenek875db812008-05-05 16:51:50 +00001252 return getCFSummaryCreateRule(FD);
Mike Stump11289f42009-09-09 15:08:12 +00001253
Ted Kremenek8e2c9b02011-05-25 06:19:45 +00001254 return getCFSummaryGetRule(FD);
Ted Kremenek875db812008-05-05 16:51:50 +00001255}
1256
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001257const RetainSummary *
Ted Kremenek82157a12009-02-23 16:51:39 +00001258RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1259 UnaryFuncKind func) {
1260
Ted Kremenek7e904222009-01-12 21:45:02 +00001261 // Sanity check that this is *really* a unary function. This can
1262 // happen if people do weird things.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001263 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
Alp Toker9cacbab2014-01-20 20:26:09 +00001264 if (!FTP || FTP->getNumParams() != 1)
Ted Kremenek7e904222009-01-12 21:45:02 +00001265 return getPersistentStopSummary();
Mike Stump11289f42009-09-09 15:08:12 +00001266
Ted Kremenek7d79a5f2009-05-03 05:20:50 +00001267 assert (ScratchArgs.isEmpty());
Mike Stump11289f42009-09-09 15:08:12 +00001268
Jordy Rose898a1482011-08-21 21:58:18 +00001269 ArgEffect Effect;
Ted Kremenek4b7ca772008-04-29 05:33:51 +00001270 switch (func) {
Jordan Rose77411322013-10-07 17:16:52 +00001271 case cfretain: Effect = IncRef; break;
1272 case cfrelease: Effect = DecRef; break;
1273 case cfautorelease: Effect = Autorelease; break;
1274 case cfmakecollectable: Effect = MakeCollectable; break;
Ted Kremenek4b772092008-04-10 23:44:06 +00001275 }
Jordy Rose898a1482011-08-21 21:58:18 +00001276
1277 ScratchArgs = AF.add(ScratchArgs, 0, Effect);
1278 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenek68d73d12008-03-12 01:21:45 +00001279}
1280
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001281const RetainSummary *
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001282RetainSummaryManager::getCFSummaryCreateRule(const FunctionDecl *FD) {
Ted Kremenek7d79a5f2009-05-03 05:20:50 +00001283 assert (ScratchArgs.isEmpty());
Mike Stump11289f42009-09-09 15:08:12 +00001284
Ted Kremenekaeb115f2009-01-28 05:56:51 +00001285 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenek68d73d12008-03-12 01:21:45 +00001286}
1287
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001288const RetainSummary *
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001289RetainSummaryManager::getCFSummaryGetRule(const FunctionDecl *FD) {
Mike Stump11289f42009-09-09 15:08:12 +00001290 assert (ScratchArgs.isEmpty());
Ted Kremenekaeb115f2009-01-28 05:56:51 +00001291 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1292 DoNothing, DoNothing);
Ted Kremenek68d73d12008-03-12 01:21:45 +00001293}
1294
Ted Kremenek819e9b62008-03-11 06:39:11 +00001295//===----------------------------------------------------------------------===//
Ted Kremenek00daccd2008-05-05 22:11:16 +00001296// Summary creation for Selectors.
1297//===----------------------------------------------------------------------===//
1298
Jordan Rose39032472013-04-04 22:31:48 +00001299Optional<RetEffect>
1300RetainSummaryManager::getRetEffectFromAnnotations(QualType RetTy,
1301 const Decl *D) {
1302 if (cocoa::isCocoaObjectRef(RetTy)) {
Aaron Ballman9ead1242013-12-19 02:39:40 +00001303 if (D->hasAttr<NSReturnsRetainedAttr>())
Jordan Rose39032472013-04-04 22:31:48 +00001304 return ObjCAllocRetE;
1305
Aaron Ballman9ead1242013-12-19 02:39:40 +00001306 if (D->hasAttr<NSReturnsNotRetainedAttr>() ||
1307 D->hasAttr<NSReturnsAutoreleasedAttr>())
Jordan Rose39032472013-04-04 22:31:48 +00001308 return RetEffect::MakeNotOwned(RetEffect::ObjC);
1309
1310 } else if (!RetTy->isPointerType()) {
1311 return None;
1312 }
1313
Aaron Ballman9ead1242013-12-19 02:39:40 +00001314 if (D->hasAttr<CFReturnsRetainedAttr>())
Jordan Rose39032472013-04-04 22:31:48 +00001315 return RetEffect::MakeOwned(RetEffect::CF, true);
1316
Aaron Ballman9ead1242013-12-19 02:39:40 +00001317 if (D->hasAttr<CFReturnsNotRetainedAttr>())
Jordan Rose39032472013-04-04 22:31:48 +00001318 return RetEffect::MakeNotOwned(RetEffect::CF);
1319
1320 return None;
1321}
1322
Ted Kremenekc2de7272009-05-09 02:58:13 +00001323void
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001324RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenekc2de7272009-05-09 02:58:13 +00001325 const FunctionDecl *FD) {
1326 if (!FD)
1327 return;
1328
Jordan Roseeec15392012-07-02 19:27:43 +00001329 assert(Summ && "Must have a summary to add annotations to.");
1330 RetainSummaryTemplate Template(Summ, *this);
Jordy Rose212e4592011-08-23 04:27:15 +00001331
Ted Kremenekafe348e2011-01-27 18:43:03 +00001332 // Effects on the parameters.
1333 unsigned parm_idx = 0;
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001334 for (FunctionDecl::param_const_iterator pi = FD->param_begin(),
John McCall3337ca52011-04-06 09:02:12 +00001335 pe = FD->param_end(); pi != pe; ++pi, ++parm_idx) {
Ted Kremenekafe348e2011-01-27 18:43:03 +00001336 const ParmVarDecl *pd = *pi;
Aaron Ballman9ead1242013-12-19 02:39:40 +00001337 if (pd->hasAttr<NSConsumedAttr>())
Jordan Rose39032472013-04-04 22:31:48 +00001338 Template->addArg(AF, parm_idx, DecRefMsg);
Aaron Ballman9ead1242013-12-19 02:39:40 +00001339 else if (pd->hasAttr<CFConsumedAttr>())
Douglas Gregoreb6e64c2015-06-19 23:17:46 +00001340 Template->addArg(AF, parm_idx, DecRef);
1341 else if (pd->hasAttr<CFReturnsRetainedAttr>()) {
1342 QualType PointeeTy = pd->getType()->getPointeeType();
1343 if (!PointeeTy.isNull())
1344 if (coreFoundation::isCFObjectRef(PointeeTy))
1345 Template->addArg(AF, parm_idx, RetainedOutParameter);
1346 } else if (pd->hasAttr<CFReturnsNotRetainedAttr>()) {
1347 QualType PointeeTy = pd->getType()->getPointeeType();
1348 if (!PointeeTy.isNull())
1349 if (coreFoundation::isCFObjectRef(PointeeTy))
1350 Template->addArg(AF, parm_idx, UnretainedOutParameter);
1351 }
Ted Kremenekafe348e2011-01-27 18:43:03 +00001352 }
Alp Toker314cc812014-01-25 16:55:45 +00001353
1354 QualType RetTy = FD->getReturnType();
Jordan Rose39032472013-04-04 22:31:48 +00001355 if (Optional<RetEffect> RetE = getRetEffectFromAnnotations(RetTy, FD))
1356 Template->setRetEffect(*RetE);
Ted Kremenekc2de7272009-05-09 02:58:13 +00001357}
1358
1359void
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001360RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
1361 const ObjCMethodDecl *MD) {
Ted Kremenekc2de7272009-05-09 02:58:13 +00001362 if (!MD)
1363 return;
1364
Jordan Roseeec15392012-07-02 19:27:43 +00001365 assert(Summ && "Must have a valid summary to add annotations to");
1366 RetainSummaryTemplate Template(Summ, *this);
Mike Stump11289f42009-09-09 15:08:12 +00001367
Ted Kremenek0e898382011-01-27 06:54:14 +00001368 // Effects on the receiver.
Aaron Ballman9ead1242013-12-19 02:39:40 +00001369 if (MD->hasAttr<NSConsumesSelfAttr>())
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001370 Template->setReceiverEffect(DecRefMsg);
1371
Ted Kremenekafe348e2011-01-27 18:43:03 +00001372 // Effects on the parameters.
1373 unsigned parm_idx = 0;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00001374 for (ObjCMethodDecl::param_const_iterator
1375 pi=MD->param_begin(), pe=MD->param_end();
Ted Kremenekafe348e2011-01-27 18:43:03 +00001376 pi != pe; ++pi, ++parm_idx) {
1377 const ParmVarDecl *pd = *pi;
Aaron Ballman9ead1242013-12-19 02:39:40 +00001378 if (pd->hasAttr<NSConsumedAttr>())
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001379 Template->addArg(AF, parm_idx, DecRefMsg);
Aaron Ballman9ead1242013-12-19 02:39:40 +00001380 else if (pd->hasAttr<CFConsumedAttr>()) {
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001381 Template->addArg(AF, parm_idx, DecRef);
Douglas Gregoreb6e64c2015-06-19 23:17:46 +00001382 } else if (pd->hasAttr<CFReturnsRetainedAttr>()) {
1383 QualType PointeeTy = pd->getType()->getPointeeType();
1384 if (!PointeeTy.isNull())
1385 if (coreFoundation::isCFObjectRef(PointeeTy))
1386 Template->addArg(AF, parm_idx, RetainedOutParameter);
1387 } else if (pd->hasAttr<CFReturnsNotRetainedAttr>()) {
1388 QualType PointeeTy = pd->getType()->getPointeeType();
1389 if (!PointeeTy.isNull())
1390 if (coreFoundation::isCFObjectRef(PointeeTy))
1391 Template->addArg(AF, parm_idx, UnretainedOutParameter);
1392 }
Ted Kremenek0e898382011-01-27 06:54:14 +00001393 }
Alp Toker314cc812014-01-25 16:55:45 +00001394
1395 QualType RetTy = MD->getReturnType();
Jordan Rose39032472013-04-04 22:31:48 +00001396 if (Optional<RetEffect> RetE = getRetEffectFromAnnotations(RetTy, MD))
1397 Template->setRetEffect(*RetE);
Ted Kremenekc2de7272009-05-09 02:58:13 +00001398}
1399
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001400const RetainSummary *
Jordy Rose35e71c72012-03-17 21:13:07 +00001401RetainSummaryManager::getStandardMethodSummary(const ObjCMethodDecl *MD,
1402 Selector S, QualType RetTy) {
Jordy Rose70638832012-03-17 19:53:04 +00001403 // Any special effects?
Ted Kremenek6a966b22009-04-24 21:56:17 +00001404 ArgEffect ReceiverEff = DoNothing;
Jordy Rose70638832012-03-17 19:53:04 +00001405 RetEffect ResultEff = RetEffect::MakeNoRet();
1406
1407 // Check the method family, and apply any default annotations.
1408 switch (MD ? MD->getMethodFamily() : S.getMethodFamily()) {
1409 case OMF_None:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00001410 case OMF_initialize:
Jordy Rose70638832012-03-17 19:53:04 +00001411 case OMF_performSelector:
1412 // Assume all Objective-C methods follow Cocoa Memory Management rules.
1413 // FIXME: Does the non-threaded performSelector family really belong here?
1414 // The selector could be, say, @selector(copy).
1415 if (cocoa::isCocoaObjectRef(RetTy))
1416 ResultEff = RetEffect::MakeNotOwned(RetEffect::ObjC);
1417 else if (coreFoundation::isCFObjectRef(RetTy)) {
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001418 // ObjCMethodDecl currently doesn't consider CF objects as valid return
Jordy Rose70638832012-03-17 19:53:04 +00001419 // values for alloc, new, copy, or mutableCopy, so we have to
1420 // double-check with the selector. This is ugly, but there aren't that
1421 // many Objective-C methods that return CF objects, right?
1422 if (MD) {
1423 switch (S.getMethodFamily()) {
1424 case OMF_alloc:
1425 case OMF_new:
1426 case OMF_copy:
1427 case OMF_mutableCopy:
1428 ResultEff = RetEffect::MakeOwned(RetEffect::CF, true);
1429 break;
1430 default:
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001431 ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
Jordy Rose70638832012-03-17 19:53:04 +00001432 break;
1433 }
1434 } else {
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001435 ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
Jordy Rose70638832012-03-17 19:53:04 +00001436 }
1437 }
1438 break;
1439 case OMF_init:
1440 ResultEff = ObjCInitRetE;
1441 ReceiverEff = DecRefMsg;
1442 break;
1443 case OMF_alloc:
1444 case OMF_new:
1445 case OMF_copy:
1446 case OMF_mutableCopy:
1447 if (cocoa::isCocoaObjectRef(RetTy))
1448 ResultEff = ObjCAllocRetE;
1449 else if (coreFoundation::isCFObjectRef(RetTy))
1450 ResultEff = RetEffect::MakeOwned(RetEffect::CF, true);
1451 break;
1452 case OMF_autorelease:
1453 ReceiverEff = Autorelease;
1454 break;
1455 case OMF_retain:
1456 ReceiverEff = IncRefMsg;
1457 break;
1458 case OMF_release:
1459 ReceiverEff = DecRefMsg;
1460 break;
1461 case OMF_dealloc:
1462 ReceiverEff = Dealloc;
1463 break;
1464 case OMF_self:
1465 // -self is handled specially by the ExprEngine to propagate the receiver.
1466 break;
1467 case OMF_retainCount:
1468 case OMF_finalize:
1469 // These methods don't return objects.
1470 break;
1471 }
Mike Stump11289f42009-09-09 15:08:12 +00001472
Ted Kremenek6a966b22009-04-24 21:56:17 +00001473 // If one of the arguments in the selector has the keyword 'delegate' we
1474 // should stop tracking the reference count for the receiver. This is
1475 // because the reference count is quite possibly handled by a delegate
1476 // method.
1477 if (S.isKeywordSelector()) {
Jordan Rose95dfae82012-06-15 18:19:52 +00001478 for (unsigned i = 0, e = S.getNumArgs(); i != e; ++i) {
1479 StringRef Slot = S.getNameForSlot(i);
1480 if (Slot.substr(Slot.size() - 8).equals_lower("delegate")) {
1481 if (ResultEff == ObjCInitRetE)
Anna Zaks25612732012-08-29 23:23:43 +00001482 ResultEff = RetEffect::MakeNoRetHard();
Jordan Rose95dfae82012-06-15 18:19:52 +00001483 else
Anna Zaks25612732012-08-29 23:23:43 +00001484 ReceiverEff = StopTrackingHard;
Jordan Rose95dfae82012-06-15 18:19:52 +00001485 }
1486 }
Ted Kremenek6a966b22009-04-24 21:56:17 +00001487 }
Mike Stump11289f42009-09-09 15:08:12 +00001488
Jordy Rose70638832012-03-17 19:53:04 +00001489 if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing &&
1490 ResultEff.getKind() == RetEffect::NoRet)
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001491 return getDefaultSummary();
Mike Stump11289f42009-09-09 15:08:12 +00001492
Jordy Rose70638832012-03-17 19:53:04 +00001493 return getPersistentSummary(ResultEff, ReceiverEff, MayEscape);
Ted Kremenek60746a02009-04-23 23:08:22 +00001494}
1495
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001496const RetainSummary *
Jordan Rose6bad4902012-07-02 19:27:56 +00001497RetainSummaryManager::getInstanceMethodSummary(const ObjCMethodCall &Msg,
Jordan Roseeec15392012-07-02 19:27:43 +00001498 ProgramStateRef State) {
Craig Topper0dbb7832014-05-27 02:45:47 +00001499 const ObjCInterfaceDecl *ReceiverClass = nullptr;
Ted Kremeneka2968e52009-11-13 01:54:21 +00001500
Jordan Roseeec15392012-07-02 19:27:43 +00001501 // We do better tracking of the type of the object than the core ExprEngine.
1502 // See if we have its type in our private state.
1503 // FIXME: Eventually replace the use of state->get<RefBindings> with
1504 // a generic API for reasoning about the Objective-C types of symbolic
1505 // objects.
1506 SVal ReceiverV = Msg.getReceiverSVal();
1507 if (SymbolRef Sym = ReceiverV.getAsLocSymbol())
Anna Zaksf5788c72012-08-14 00:36:15 +00001508 if (const RefVal *T = getRefBinding(State, Sym))
Douglas Gregor9a129192010-04-21 00:45:42 +00001509 if (const ObjCObjectPointerType *PT =
Jordan Roseeec15392012-07-02 19:27:43 +00001510 T->getType()->getAs<ObjCObjectPointerType>())
1511 ReceiverClass = PT->getInterfaceDecl();
1512
1513 // If we don't know what kind of object this is, fall back to its static type.
1514 if (!ReceiverClass)
1515 ReceiverClass = Msg.getReceiverInterface();
Douglas Gregor9a129192010-04-21 00:45:42 +00001516
Ted Kremeneka2968e52009-11-13 01:54:21 +00001517 // FIXME: The receiver could be a reference to a class, meaning that
1518 // we should use the class method.
Jordan Roseeec15392012-07-02 19:27:43 +00001519 // id x = [NSObject class];
1520 // [x performSelector:... withObject:... afterDelay:...];
1521 Selector S = Msg.getSelector();
1522 const ObjCMethodDecl *Method = Msg.getDecl();
1523 if (!Method && ReceiverClass)
1524 Method = ReceiverClass->getInstanceMethod(S);
1525
1526 return getMethodSummary(S, ReceiverClass, Method, Msg.getResultType(),
1527 ObjCMethodSummaries);
Ted Kremeneka2968e52009-11-13 01:54:21 +00001528}
1529
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001530const RetainSummary *
Jordan Roseeec15392012-07-02 19:27:43 +00001531RetainSummaryManager::getMethodSummary(Selector S, const ObjCInterfaceDecl *ID,
Jordy Rose35e71c72012-03-17 21:13:07 +00001532 const ObjCMethodDecl *MD, QualType RetTy,
1533 ObjCMethodSummariesTy &CachedSummaries) {
Ted Kremenekcb2e6362008-05-06 15:44:25 +00001534
Ted Kremenek0b50fb12009-04-29 05:04:30 +00001535 // Look up a summary in our summary cache.
Jordan Roseeec15392012-07-02 19:27:43 +00001536 const RetainSummary *Summ = CachedSummaries.find(ID, S);
Mike Stump11289f42009-09-09 15:08:12 +00001537
Ted Kremenek8be51382009-07-21 23:27:57 +00001538 if (!Summ) {
Jordy Rose35e71c72012-03-17 21:13:07 +00001539 Summ = getStandardMethodSummary(MD, S, RetTy);
Mike Stump11289f42009-09-09 15:08:12 +00001540
Ted Kremenek8be51382009-07-21 23:27:57 +00001541 // Annotations override defaults.
Jordy Rose212e4592011-08-23 04:27:15 +00001542 updateSummaryFromAnnotations(Summ, MD);
Mike Stump11289f42009-09-09 15:08:12 +00001543
Ted Kremenek8be51382009-07-21 23:27:57 +00001544 // Memoize the summary.
Jordan Roseeec15392012-07-02 19:27:43 +00001545 CachedSummaries[ObjCSummaryKey(ID, S)] = Summ;
Ted Kremenek8be51382009-07-21 23:27:57 +00001546 }
Mike Stump11289f42009-09-09 15:08:12 +00001547
Ted Kremenekf27110f2009-04-23 19:11:35 +00001548 return Summ;
Ted Kremenek767d0742008-05-06 21:26:51 +00001549}
1550
Mike Stump11289f42009-09-09 15:08:12 +00001551void RetainSummaryManager::InitializeClassMethodSummaries() {
Ted Kremenek9157fbb2009-05-07 23:40:42 +00001552 assert(ScratchArgs.isEmpty());
Mike Stump11289f42009-09-09 15:08:12 +00001553 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek55adb822009-10-15 22:25:12 +00001554 addClassMethSummary("NSAssertionHandler", "currentHandler",
Ted Kremenekaeb115f2009-01-28 05:56:51 +00001555 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Mike Stump11289f42009-09-09 15:08:12 +00001556
Ted Kremenek0747e7e2008-10-21 15:53:15 +00001557 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremenekb3b56c62010-11-24 00:54:37 +00001558 ScratchArgs = AF.add(ScratchArgs, 0, Autorelease);
Ted Kremenek55adb822009-10-15 22:25:12 +00001559 addClassMethSummary("NSAutoreleasePool", "addObject",
1560 getPersistentSummary(RetEffect::MakeNoRet(),
1561 DoNothing, Autorelease));
Ted Kremenek0806f912008-05-06 00:30:21 +00001562}
1563
Ted Kremenekea736c52008-06-23 22:21:20 +00001564void RetainSummaryManager::InitializeMethodSummaries() {
Mike Stump11289f42009-09-09 15:08:12 +00001565
1566 assert (ScratchArgs.isEmpty());
1567
Ted Kremenek767d0742008-05-06 21:26:51 +00001568 // Create the "init" selector. It just acts as a pass-through for the
1569 // receiver.
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001570 const RetainSummary *InitSumm = getPersistentSummary(ObjCInitRetE, DecRefMsg);
Ted Kremenek815fbb62009-08-20 05:13:36 +00001571 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
1572
1573 // awakeAfterUsingCoder: behaves basically like an 'init' method. It
1574 // claims the receiver and returns a retained object.
1575 addNSObjectMethSummary(GetUnarySelector("awakeAfterUsingCoder", Ctx),
1576 InitSumm);
Mike Stump11289f42009-09-09 15:08:12 +00001577
Ted Kremenek767d0742008-05-06 21:26:51 +00001578 // The next methods are allocators.
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001579 const RetainSummary *AllocSumm = getPersistentSummary(ObjCAllocRetE);
1580 const RetainSummary *CFAllocSumm =
Ted Kremenek52ac2b52009-08-28 19:52:12 +00001581 getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Mike Stump11289f42009-09-09 15:08:12 +00001582
Ted Kremenekb0862dc2008-05-06 02:26:56 +00001583 // Create the "retain" selector.
Jordy Rose3f7f75682011-08-21 19:41:36 +00001584 RetEffect NoRet = RetEffect::MakeNoRet();
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001585 const RetainSummary *Summ = getPersistentSummary(NoRet, IncRefMsg);
Ted Kremenek3185c9c2008-06-25 21:21:56 +00001586 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Mike Stump11289f42009-09-09 15:08:12 +00001587
Ted Kremenekb0862dc2008-05-06 02:26:56 +00001588 // Create the "release" selector.
Jordy Rose3f7f75682011-08-21 19:41:36 +00001589 Summ = getPersistentSummary(NoRet, DecRefMsg);
Ted Kremenek3185c9c2008-06-25 21:21:56 +00001590 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Mike Stump11289f42009-09-09 15:08:12 +00001591
Ted Kremenekea072e32009-03-17 19:42:23 +00001592 // Create the -dealloc summary.
Jordy Rose3f7f75682011-08-21 19:41:36 +00001593 Summ = getPersistentSummary(NoRet, Dealloc);
Ted Kremenekea072e32009-03-17 19:42:23 +00001594 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
Ted Kremenekb0862dc2008-05-06 02:26:56 +00001595
1596 // Create the "autorelease" selector.
Jordy Rose3f7f75682011-08-21 19:41:36 +00001597 Summ = getPersistentSummary(NoRet, Autorelease);
Ted Kremenek3185c9c2008-06-25 21:21:56 +00001598 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Mike Stump11289f42009-09-09 15:08:12 +00001599
Mike Stump11289f42009-09-09 15:08:12 +00001600 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremeneke73f2822009-02-23 02:51:29 +00001601 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1602 // self-own themselves. However, they only do this once they are displayed.
1603 // Thus, we need to track an NSWindow's display status.
1604 // This is tracked in <rdar://problem/6062711>.
Ted Kremenek00dfe302009-03-04 23:30:42 +00001605 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001606 const RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenek1272f702009-05-12 20:06:54 +00001607 StopTracking,
1608 StopTracking);
Mike Stump11289f42009-09-09 15:08:12 +00001609
Ted Kremenek751e7e32009-04-03 19:02:51 +00001610 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1611
Ted Kremenek3f13f592008-08-12 18:48:50 +00001612 // For NSPanel (which subclasses NSWindow), allocated objects are not
1613 // self-owned.
Ted Kremenek751e7e32009-04-03 19:02:51 +00001614 // FIXME: For now we don't track NSPanels. object for the same reason
1615 // as for NSWindow objects.
1616 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
Mike Stump11289f42009-09-09 15:08:12 +00001617
Ted Kremenek9b12e722014-01-03 01:19:28 +00001618 // For NSNull, objects returned by +null are singletons that ignore
1619 // retain/release semantics. Just don't track them.
1620 // <rdar://problem/12858915>
1621 addClassMethSummary("NSNull", "null", NoTrackYet);
1622
Jordan Rose95bf3b02013-01-31 22:06:02 +00001623 // Don't track allocated autorelease pools, as it is okay to prematurely
Ted Kremenek501ba032009-05-18 23:14:34 +00001624 // exit a method.
1625 addClassMethSummary("NSAutoreleasePool", "alloc", NoTrackYet);
Ted Kremeneke8a5ba82012-02-18 21:37:48 +00001626 addClassMethSummary("NSAutoreleasePool", "allocWithZone", NoTrackYet, false);
Jordan Rose95bf3b02013-01-31 22:06:02 +00001627 addClassMethSummary("NSAutoreleasePool", "new", NoTrackYet);
Ted Kremenek3185c9c2008-06-25 21:21:56 +00001628
Ted Kremenek10369122009-05-20 22:39:57 +00001629 // Create summaries QCRenderer/QCView -createSnapShotImageOfType:
1630 addInstMethSummary("QCRenderer", AllocSumm,
Reid Kleckneree7cf842014-12-01 22:02:27 +00001631 "createSnapshotImageOfType", nullptr);
Ted Kremenek10369122009-05-20 22:39:57 +00001632 addInstMethSummary("QCView", AllocSumm,
Reid Kleckneree7cf842014-12-01 22:02:27 +00001633 "createSnapshotImageOfType", nullptr);
Ted Kremenek10369122009-05-20 22:39:57 +00001634
Ted Kremenek96aa1462009-06-15 20:58:58 +00001635 // Create summaries for CIContext, 'createCGImage' and
Ted Kremenek52ac2b52009-08-28 19:52:12 +00001636 // 'createCGLayerWithSize'. These objects are CF objects, and are not
1637 // automatically garbage collected.
1638 addInstMethSummary("CIContext", CFAllocSumm,
Reid Kleckneree7cf842014-12-01 22:02:27 +00001639 "createCGImage", "fromRect", nullptr);
1640 addInstMethSummary("CIContext", CFAllocSumm, "createCGImage", "fromRect",
1641 "format", "colorSpace", nullptr);
1642 addInstMethSummary("CIContext", CFAllocSumm, "createCGLayerWithSize", "info",
1643 nullptr);
Ted Kremenekbe7c56e2008-05-06 00:38:54 +00001644}
1645
Ted Kremenek00daccd2008-05-05 22:11:16 +00001646//===----------------------------------------------------------------------===//
Ted Kremenek6bd78702009-04-29 18:50:19 +00001647// Error reporting.
1648//===----------------------------------------------------------------------===//
Ted Kremenek6bd78702009-04-29 18:50:19 +00001649namespace {
Jordy Rose20d4e682011-08-23 20:55:48 +00001650 typedef llvm::DenseMap<const ExplodedNode *, const RetainSummary *>
1651 SummaryLogTy;
1652
Ted Kremenek6bd78702009-04-29 18:50:19 +00001653 //===-------------===//
1654 // Bug Descriptions. //
Mike Stump11289f42009-09-09 15:08:12 +00001655 //===-------------===//
1656
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00001657 class CFRefBug : public BugType {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001658 protected:
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001659 CFRefBug(const CheckerBase *checker, StringRef name)
1660 : BugType(checker, name, categories::MemoryCoreFoundationObjectiveC) {}
1661
Ted Kremenek6bd78702009-04-29 18:50:19 +00001662 public:
Mike Stump11289f42009-09-09 15:08:12 +00001663
Ted Kremenek6bd78702009-04-29 18:50:19 +00001664 // FIXME: Eventually remove.
Jordy Rose7a534982011-08-24 05:47:39 +00001665 virtual const char *getDescription() const = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001666
Ted Kremenek6bd78702009-04-29 18:50:19 +00001667 virtual bool isLeak() const { return false; }
1668 };
Mike Stump11289f42009-09-09 15:08:12 +00001669
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00001670 class UseAfterRelease : public CFRefBug {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001671 public:
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001672 UseAfterRelease(const CheckerBase *checker)
1673 : CFRefBug(checker, "Use-after-release") {}
Mike Stump11289f42009-09-09 15:08:12 +00001674
Craig Topperfb6b25b2014-03-15 04:29:04 +00001675 const char *getDescription() const override {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001676 return "Reference-counted object is used after it is released";
Mike Stump11289f42009-09-09 15:08:12 +00001677 }
Ted Kremenek6bd78702009-04-29 18:50:19 +00001678 };
Mike Stump11289f42009-09-09 15:08:12 +00001679
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00001680 class BadRelease : public CFRefBug {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001681 public:
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001682 BadRelease(const CheckerBase *checker) : CFRefBug(checker, "Bad release") {}
Mike Stump11289f42009-09-09 15:08:12 +00001683
Craig Topperfb6b25b2014-03-15 04:29:04 +00001684 const char *getDescription() const override {
Ted Kremenek5c22e112009-10-01 17:31:50 +00001685 return "Incorrect decrement of the reference count of an object that is "
1686 "not owned at this point by the caller";
Ted Kremenek6bd78702009-04-29 18:50:19 +00001687 }
1688 };
Mike Stump11289f42009-09-09 15:08:12 +00001689
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00001690 class DeallocGC : public CFRefBug {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001691 public:
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001692 DeallocGC(const CheckerBase *checker)
1693 : CFRefBug(checker, "-dealloc called while using garbage collection") {}
Mike Stump11289f42009-09-09 15:08:12 +00001694
Craig Topperfb6b25b2014-03-15 04:29:04 +00001695 const char *getDescription() const override {
Ted Kremenekd35272f2009-05-09 00:10:05 +00001696 return "-dealloc called while using garbage collection";
Ted Kremenek6bd78702009-04-29 18:50:19 +00001697 }
1698 };
Mike Stump11289f42009-09-09 15:08:12 +00001699
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00001700 class DeallocNotOwned : public CFRefBug {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001701 public:
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001702 DeallocNotOwned(const CheckerBase *checker)
1703 : CFRefBug(checker, "-dealloc sent to non-exclusively owned object") {}
Mike Stump11289f42009-09-09 15:08:12 +00001704
Craig Topperfb6b25b2014-03-15 04:29:04 +00001705 const char *getDescription() const override {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001706 return "-dealloc sent to object that may be referenced elsewhere";
1707 }
Mike Stump11289f42009-09-09 15:08:12 +00001708 };
1709
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00001710 class OverAutorelease : public CFRefBug {
Ted Kremenekd35272f2009-05-09 00:10:05 +00001711 public:
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001712 OverAutorelease(const CheckerBase *checker)
1713 : CFRefBug(checker, "Object autoreleased too many times") {}
Mike Stump11289f42009-09-09 15:08:12 +00001714
Craig Topperfb6b25b2014-03-15 04:29:04 +00001715 const char *getDescription() const override {
Jordan Rose7467f062013-04-23 01:42:25 +00001716 return "Object autoreleased too many times";
Ted Kremenekd35272f2009-05-09 00:10:05 +00001717 }
1718 };
Mike Stump11289f42009-09-09 15:08:12 +00001719
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00001720 class ReturnedNotOwnedForOwned : public CFRefBug {
Ted Kremenekdee56e32009-05-10 06:25:57 +00001721 public:
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001722 ReturnedNotOwnedForOwned(const CheckerBase *checker)
1723 : CFRefBug(checker, "Method should return an owned object") {}
Mike Stump11289f42009-09-09 15:08:12 +00001724
Craig Topperfb6b25b2014-03-15 04:29:04 +00001725 const char *getDescription() const override {
Jordy Rose43426f82011-07-15 22:17:54 +00001726 return "Object with a +0 retain count returned to caller where a +1 "
Ted Kremenekdee56e32009-05-10 06:25:57 +00001727 "(owning) retain count is expected";
1728 }
1729 };
Mike Stump11289f42009-09-09 15:08:12 +00001730
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00001731 class Leak : public CFRefBug {
Benjamin Kramerd1d76b22012-06-06 17:32:50 +00001732 public:
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001733 Leak(const CheckerBase *checker, StringRef name) : CFRefBug(checker, name) {
Jordy Rose15484da2011-08-25 01:14:38 +00001734 // Leaks should not be reported if they are post-dominated by a sink.
1735 setSuppressOnSink(true);
1736 }
Mike Stump11289f42009-09-09 15:08:12 +00001737
Craig Topperfb6b25b2014-03-15 04:29:04 +00001738 const char *getDescription() const override { return ""; }
Mike Stump11289f42009-09-09 15:08:12 +00001739
Craig Topperfb6b25b2014-03-15 04:29:04 +00001740 bool isLeak() const override { return true; }
Ted Kremenek6bd78702009-04-29 18:50:19 +00001741 };
Mike Stump11289f42009-09-09 15:08:12 +00001742
Ted Kremenek6bd78702009-04-29 18:50:19 +00001743 //===---------===//
1744 // Bug Reports. //
1745 //===---------===//
Mike Stump11289f42009-09-09 15:08:12 +00001746
Jordy Rosef78877e2012-03-24 02:45:35 +00001747 class CFRefReportVisitor : public BugReporterVisitorImpl<CFRefReportVisitor> {
Anna Zaks88255cc2011-08-20 01:27:22 +00001748 protected:
Anna Zaks071a89c2011-08-19 23:21:56 +00001749 SymbolRef Sym;
Jordy Rose20d4e682011-08-23 20:55:48 +00001750 const SummaryLogTy &SummaryLog;
Jordy Rose7a534982011-08-24 05:47:39 +00001751 bool GCEnabled;
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001752
Anna Zaks071a89c2011-08-19 23:21:56 +00001753 public:
Jordy Rose7a534982011-08-24 05:47:39 +00001754 CFRefReportVisitor(SymbolRef sym, bool gcEnabled, const SummaryLogTy &log)
1755 : Sym(sym), SummaryLog(log), GCEnabled(gcEnabled) {}
Anna Zaks071a89c2011-08-19 23:21:56 +00001756
Craig Topperfb6b25b2014-03-15 04:29:04 +00001757 void Profile(llvm::FoldingSetNodeID &ID) const override {
Anna Zaks071a89c2011-08-19 23:21:56 +00001758 static int x = 0;
1759 ID.AddPointer(&x);
1760 ID.AddPointer(Sym);
1761 }
1762
Craig Topperfb6b25b2014-03-15 04:29:04 +00001763 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
1764 const ExplodedNode *PrevN,
1765 BugReporterContext &BRC,
1766 BugReport &BR) override;
Anna Zaks88255cc2011-08-20 01:27:22 +00001767
David Blaikied15481c2014-08-29 18:18:43 +00001768 std::unique_ptr<PathDiagnosticPiece> getEndPath(BugReporterContext &BRC,
1769 const ExplodedNode *N,
1770 BugReport &BR) override;
Anna Zaks88255cc2011-08-20 01:27:22 +00001771 };
1772
1773 class CFRefLeakReportVisitor : public CFRefReportVisitor {
1774 public:
Jordy Rose7a534982011-08-24 05:47:39 +00001775 CFRefLeakReportVisitor(SymbolRef sym, bool GCEnabled,
Jordy Rose20d4e682011-08-23 20:55:48 +00001776 const SummaryLogTy &log)
Jordy Rose7a534982011-08-24 05:47:39 +00001777 : CFRefReportVisitor(sym, GCEnabled, log) {}
Anna Zaks88255cc2011-08-20 01:27:22 +00001778
David Blaikied15481c2014-08-29 18:18:43 +00001779 std::unique_ptr<PathDiagnosticPiece> getEndPath(BugReporterContext &BRC,
1780 const ExplodedNode *N,
1781 BugReport &BR) override;
Jordy Rosef78877e2012-03-24 02:45:35 +00001782
David Blaikie91e79022014-09-04 23:54:33 +00001783 std::unique_ptr<BugReporterVisitor> clone() const override {
Jordy Rosef78877e2012-03-24 02:45:35 +00001784 // The curiously-recurring template pattern only works for one level of
1785 // subclassing. Rather than make a new template base for
1786 // CFRefReportVisitor, we simply override clone() to do the right thing.
1787 // This could be trouble someday if BugReporterVisitorImpl is ever
1788 // used for something else besides a convenient implementation of clone().
David Blaikie91e79022014-09-04 23:54:33 +00001789 return llvm::make_unique<CFRefLeakReportVisitor>(*this);
Jordy Rosef78877e2012-03-24 02:45:35 +00001790 }
Anna Zaks071a89c2011-08-19 23:21:56 +00001791 };
1792
Anna Zaks3a6bdf82011-08-17 23:00:25 +00001793 class CFRefReport : public BugReport {
Jordy Rose184bd142011-08-24 22:39:09 +00001794 void addGCModeDescription(const LangOptions &LOpts, bool GCEnabled);
Jordy Rose7a534982011-08-24 05:47:39 +00001795
Ted Kremenek6bd78702009-04-29 18:50:19 +00001796 public:
Jordy Rose184bd142011-08-24 22:39:09 +00001797 CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1798 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1799 bool registerVisitor = true)
Anna Zaks752de142011-08-22 18:54:07 +00001800 : BugReport(D, D.getDescription(), n) {
Anna Zaks88255cc2011-08-20 01:27:22 +00001801 if (registerVisitor)
David Blaikie91e79022014-09-04 23:54:33 +00001802 addVisitor(llvm::make_unique<CFRefReportVisitor>(sym, GCEnabled, Log));
Jordy Rose184bd142011-08-24 22:39:09 +00001803 addGCModeDescription(LOpts, GCEnabled);
Anna Zaks071a89c2011-08-19 23:21:56 +00001804 }
Ted Kremenek3978f792009-05-10 05:11:21 +00001805
Jordy Rose184bd142011-08-24 22:39:09 +00001806 CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1807 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1808 StringRef endText)
Anna Zaks752de142011-08-22 18:54:07 +00001809 : BugReport(D, D.getDescription(), endText, n) {
David Blaikie91e79022014-09-04 23:54:33 +00001810 addVisitor(llvm::make_unique<CFRefReportVisitor>(sym, GCEnabled, Log));
Jordy Rose184bd142011-08-24 22:39:09 +00001811 addGCModeDescription(LOpts, GCEnabled);
Anna Zaks071a89c2011-08-19 23:21:56 +00001812 }
Mike Stump11289f42009-09-09 15:08:12 +00001813
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00001814 llvm::iterator_range<ranges_iterator> getRanges() override {
Anna Zaks752de142011-08-22 18:54:07 +00001815 const CFRefBug& BugTy = static_cast<CFRefBug&>(getBugType());
1816 if (!BugTy.isLeak())
Anna Zaks3a6bdf82011-08-17 23:00:25 +00001817 return BugReport::getRanges();
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00001818 return llvm::make_range(ranges_iterator(), ranges_iterator());
Ted Kremenek6bd78702009-04-29 18:50:19 +00001819 }
Ted Kremenek6bd78702009-04-29 18:50:19 +00001820 };
Ted Kremenek3978f792009-05-10 05:11:21 +00001821
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00001822 class CFRefLeakReport : public CFRefReport {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001823 const MemRegion* AllocBinding;
1824 public:
Jordy Rose184bd142011-08-24 22:39:09 +00001825 CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1826 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
Ted Kremenek8671acb2013-04-16 21:44:22 +00001827 CheckerContext &Ctx,
1828 bool IncludeAllocationLine);
Mike Stump11289f42009-09-09 15:08:12 +00001829
Craig Topperfb6b25b2014-03-15 04:29:04 +00001830 PathDiagnosticLocation getLocation(const SourceManager &SM) const override {
Anna Zaksc29bed32011-09-20 21:38:35 +00001831 assert(Location.isValid());
1832 return Location;
1833 }
Mike Stump11289f42009-09-09 15:08:12 +00001834 };
Ted Kremenek6bd78702009-04-29 18:50:19 +00001835} // end anonymous namespace
1836
Jordy Rose184bd142011-08-24 22:39:09 +00001837void CFRefReport::addGCModeDescription(const LangOptions &LOpts,
1838 bool GCEnabled) {
Craig Topper0dbb7832014-05-27 02:45:47 +00001839 const char *GCModeDescription = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001840
Douglas Gregor79a91412011-09-13 17:21:33 +00001841 switch (LOpts.getGC()) {
Anna Zaks76c3fb62011-08-22 20:31:28 +00001842 case LangOptions::GCOnly:
Jordy Rose184bd142011-08-24 22:39:09 +00001843 assert(GCEnabled);
Jordy Rose7a534982011-08-24 05:47:39 +00001844 GCModeDescription = "Code is compiled to only use garbage collection";
1845 break;
Mike Stump11289f42009-09-09 15:08:12 +00001846
Anna Zaks76c3fb62011-08-22 20:31:28 +00001847 case LangOptions::NonGC:
Jordy Rose184bd142011-08-24 22:39:09 +00001848 assert(!GCEnabled);
Jordy Rose7a534982011-08-24 05:47:39 +00001849 GCModeDescription = "Code is compiled to use reference counts";
1850 break;
Mike Stump11289f42009-09-09 15:08:12 +00001851
Anna Zaks76c3fb62011-08-22 20:31:28 +00001852 case LangOptions::HybridGC:
Jordy Rose184bd142011-08-24 22:39:09 +00001853 if (GCEnabled) {
Jordy Rose7a534982011-08-24 05:47:39 +00001854 GCModeDescription = "Code is compiled to use either garbage collection "
1855 "(GC) or reference counts (non-GC). The bug occurs "
1856 "with GC enabled";
1857 break;
1858 } else {
1859 GCModeDescription = "Code is compiled to use either garbage collection "
1860 "(GC) or reference counts (non-GC). The bug occurs "
1861 "in non-GC mode";
1862 break;
Anna Zaks76c3fb62011-08-22 20:31:28 +00001863 }
Ted Kremenek6bd78702009-04-29 18:50:19 +00001864 }
Jordy Rose7a534982011-08-24 05:47:39 +00001865
Jordy Rose9ff02992011-08-24 20:38:42 +00001866 assert(GCModeDescription && "invalid/unknown GC mode");
Jordy Rose7a534982011-08-24 05:47:39 +00001867 addExtraText(GCModeDescription);
Ted Kremenek6bd78702009-04-29 18:50:19 +00001868}
1869
Jordy Rose6393f822012-05-12 05:10:43 +00001870static bool isNumericLiteralExpression(const Expr *E) {
1871 // FIXME: This set of cases was copied from SemaExprObjC.
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001872 return isa<IntegerLiteral>(E) ||
Jordy Rose6393f822012-05-12 05:10:43 +00001873 isa<CharacterLiteral>(E) ||
1874 isa<FloatingLiteral>(E) ||
1875 isa<ObjCBoolLiteralExpr>(E) ||
1876 isa<CXXBoolLiteralExpr>(E);
1877}
1878
Jordan Rosecb5386c2015-02-04 19:24:52 +00001879/// Returns true if this stack frame is for an Objective-C method that is a
1880/// property getter or setter whose body has been synthesized by the analyzer.
1881static bool isSynthesizedAccessor(const StackFrameContext *SFC) {
1882 auto Method = dyn_cast_or_null<ObjCMethodDecl>(SFC->getDecl());
1883 if (!Method || !Method->isPropertyAccessor())
1884 return false;
1885
1886 return SFC->getAnalysisDeclContext()->isBodyAutosynthesized();
1887}
1888
Anna Zaks071a89c2011-08-19 23:21:56 +00001889PathDiagnosticPiece *CFRefReportVisitor::VisitNode(const ExplodedNode *N,
1890 const ExplodedNode *PrevN,
1891 BugReporterContext &BRC,
1892 BugReport &BR) {
Jordan Rose681cce92012-07-10 22:07:42 +00001893 // FIXME: We will eventually need to handle non-statement-based events
1894 // (__attribute__((cleanup))).
David Blaikie87396b92013-02-21 22:23:56 +00001895 if (!N->getLocation().getAs<StmtPoint>())
Craig Topper0dbb7832014-05-27 02:45:47 +00001896 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001897
Ted Kremenekbb8d5462009-05-06 21:39:49 +00001898 // Check if the type state has changed.
Ted Kremenek49b1e382012-01-26 21:29:00 +00001899 ProgramStateRef PrevSt = PrevN->getState();
1900 ProgramStateRef CurrSt = N->getState();
Ted Kremenek632e3b72012-01-06 22:09:28 +00001901 const LocationContext *LCtx = N->getLocationContext();
Mike Stump11289f42009-09-09 15:08:12 +00001902
Anna Zaksf5788c72012-08-14 00:36:15 +00001903 const RefVal* CurrT = getRefBinding(CurrSt, Sym);
Craig Topper0dbb7832014-05-27 02:45:47 +00001904 if (!CurrT) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001905
Ted Kremenekd93c6e32009-06-18 01:23:53 +00001906 const RefVal &CurrV = *CurrT;
Anna Zaksf5788c72012-08-14 00:36:15 +00001907 const RefVal *PrevT = getRefBinding(PrevSt, Sym);
Mike Stump11289f42009-09-09 15:08:12 +00001908
Ted Kremenek6bd78702009-04-29 18:50:19 +00001909 // Create a string buffer to constain all the useful things we want
1910 // to tell the user.
1911 std::string sbuf;
1912 llvm::raw_string_ostream os(sbuf);
Mike Stump11289f42009-09-09 15:08:12 +00001913
Ted Kremenek6bd78702009-04-29 18:50:19 +00001914 // This is the allocation site since the previous node had no bindings
1915 // for this symbol.
1916 if (!PrevT) {
David Blaikie87396b92013-02-21 22:23:56 +00001917 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
Mike Stump11289f42009-09-09 15:08:12 +00001918
Jordan Rosecb5386c2015-02-04 19:24:52 +00001919 if (isa<ObjCIvarRefExpr>(S) &&
1920 isSynthesizedAccessor(LCtx->getCurrentStackFrame())) {
1921 S = LCtx->getCurrentStackFrame()->getCallSite();
1922 }
1923
Ted Kremenek415287d2012-03-06 20:06:12 +00001924 if (isa<ObjCArrayLiteral>(S)) {
1925 os << "NSArray literal is an object with a +0 retain count";
Mike Stump11289f42009-09-09 15:08:12 +00001926 }
Ted Kremenek415287d2012-03-06 20:06:12 +00001927 else if (isa<ObjCDictionaryLiteral>(S)) {
1928 os << "NSDictionary literal is an object with a +0 retain count";
Ted Kremenek6bd78702009-04-29 18:50:19 +00001929 }
Jordy Rose6393f822012-05-12 05:10:43 +00001930 else if (const ObjCBoxedExpr *BL = dyn_cast<ObjCBoxedExpr>(S)) {
1931 if (isNumericLiteralExpression(BL->getSubExpr()))
1932 os << "NSNumber literal is an object with a +0 retain count";
1933 else {
Craig Topper0dbb7832014-05-27 02:45:47 +00001934 const ObjCInterfaceDecl *BoxClass = nullptr;
Jordy Rose6393f822012-05-12 05:10:43 +00001935 if (const ObjCMethodDecl *Method = BL->getBoxingMethod())
1936 BoxClass = Method->getClassInterface();
1937
1938 // We should always be able to find the boxing class interface,
1939 // but consider this future-proofing.
1940 if (BoxClass)
1941 os << *BoxClass << " b";
1942 else
1943 os << "B";
1944
1945 os << "oxed expression produces an object with a +0 retain count";
1946 }
1947 }
Jordan Rosecb5386c2015-02-04 19:24:52 +00001948 else if (isa<ObjCIvarRefExpr>(S)) {
1949 os << "Object loaded from instance variable";
1950 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001951 else {
Ted Kremenek415287d2012-03-06 20:06:12 +00001952 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
1953 // Get the name of the callee (if it is available).
1954 SVal X = CurrSt->getSValAsScalarOrLoc(CE->getCallee(), LCtx);
1955 if (const FunctionDecl *FD = X.getAsFunctionDecl())
1956 os << "Call to function '" << *FD << '\'';
1957 else
1958 os << "function call";
Ted Kremenek6bd78702009-04-29 18:50:19 +00001959 }
Ted Kremenek415287d2012-03-06 20:06:12 +00001960 else {
Jordan Rose627b0462012-07-18 21:59:51 +00001961 assert(isa<ObjCMessageExpr>(S));
Jordan Rosefcd016e2012-07-30 20:22:09 +00001962 CallEventManager &Mgr = CurrSt->getStateManager().getCallEventManager();
1963 CallEventRef<ObjCMethodCall> Call
1964 = Mgr.getObjCMethodCall(cast<ObjCMessageExpr>(S), CurrSt, LCtx);
1965
1966 switch (Call->getMessageKind()) {
Jordan Rose627b0462012-07-18 21:59:51 +00001967 case OCM_Message:
1968 os << "Method";
1969 break;
1970 case OCM_PropertyAccess:
1971 os << "Property";
1972 break;
1973 case OCM_Subscript:
1974 os << "Subscript";
1975 break;
1976 }
Ted Kremenek415287d2012-03-06 20:06:12 +00001977 }
1978
1979 if (CurrV.getObjKind() == RetEffect::CF) {
1980 os << " returns a Core Foundation object with a ";
1981 }
1982 else {
1983 assert (CurrV.getObjKind() == RetEffect::ObjC);
1984 os << " returns an Objective-C object with a ";
1985 }
1986
1987 if (CurrV.isOwned()) {
1988 os << "+1 retain count";
1989
1990 if (GCEnabled) {
1991 assert(CurrV.getObjKind() == RetEffect::CF);
1992 os << ". "
1993 "Core Foundation objects are not automatically garbage collected.";
1994 }
1995 }
1996 else {
1997 assert (CurrV.isNotOwned());
1998 os << "+0 retain count";
1999 }
Ted Kremenek6bd78702009-04-29 18:50:19 +00002000 }
Mike Stump11289f42009-09-09 15:08:12 +00002001
Anna Zaks3a769bd2011-09-15 01:08:34 +00002002 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
2003 N->getLocationContext());
Ted Kremenek6bd78702009-04-29 18:50:19 +00002004 return new PathDiagnosticEventPiece(Pos, os.str());
2005 }
Mike Stump11289f42009-09-09 15:08:12 +00002006
Ted Kremenek6bd78702009-04-29 18:50:19 +00002007 // Gather up the effects that were performed on the object at this
2008 // program point
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002009 SmallVector<ArgEffect, 2> AEffects;
Mike Stump11289f42009-09-09 15:08:12 +00002010
Jordy Rose20d4e682011-08-23 20:55:48 +00002011 const ExplodedNode *OrigNode = BRC.getNodeResolver().getOriginalNode(N);
2012 if (const RetainSummary *Summ = SummaryLog.lookup(OrigNode)) {
Ted Kremenek6bd78702009-04-29 18:50:19 +00002013 // We only have summaries attached to nodes after evaluating CallExpr and
2014 // ObjCMessageExprs.
David Blaikie87396b92013-02-21 22:23:56 +00002015 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
Mike Stump11289f42009-09-09 15:08:12 +00002016
Ted Kremenekbfd28fd2009-07-22 22:35:28 +00002017 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
Ted Kremenek6bd78702009-04-29 18:50:19 +00002018 // Iterate through the parameter expressions and see if the symbol
2019 // was ever passed as an argument.
2020 unsigned i = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002021
Ted Kremenekbfd28fd2009-07-22 22:35:28 +00002022 for (CallExpr::const_arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
Ted Kremenek6bd78702009-04-29 18:50:19 +00002023 AI!=AE; ++AI, ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002024
Ted Kremenek6bd78702009-04-29 18:50:19 +00002025 // Retrieve the value of the argument. Is it the symbol
2026 // we are interested in?
Ted Kremenek632e3b72012-01-06 22:09:28 +00002027 if (CurrSt->getSValAsScalarOrLoc(*AI, LCtx).getAsLocSymbol() != Sym)
Ted Kremenek6bd78702009-04-29 18:50:19 +00002028 continue;
Mike Stump11289f42009-09-09 15:08:12 +00002029
Ted Kremenek6bd78702009-04-29 18:50:19 +00002030 // We have an argument. Get the effect!
2031 AEffects.push_back(Summ->getArg(i));
2032 }
2033 }
Mike Stump11289f42009-09-09 15:08:12 +00002034 else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
Douglas Gregor9a129192010-04-21 00:45:42 +00002035 if (const Expr *receiver = ME->getInstanceReceiver())
Ted Kremenek632e3b72012-01-06 22:09:28 +00002036 if (CurrSt->getSValAsScalarOrLoc(receiver, LCtx)
2037 .getAsLocSymbol() == Sym) {
Ted Kremenek6bd78702009-04-29 18:50:19 +00002038 // The symbol we are tracking is the receiver.
2039 AEffects.push_back(Summ->getReceiverEffect());
2040 }
2041 }
2042 }
Mike Stump11289f42009-09-09 15:08:12 +00002043
Ted Kremenek6bd78702009-04-29 18:50:19 +00002044 do {
2045 // Get the previous type state.
2046 RefVal PrevV = *PrevT;
Mike Stump11289f42009-09-09 15:08:12 +00002047
Ted Kremenek6bd78702009-04-29 18:50:19 +00002048 // Specially handle -dealloc.
Benjamin Kramerab3838a2013-08-16 21:57:14 +00002049 if (!GCEnabled && std::find(AEffects.begin(), AEffects.end(), Dealloc) !=
2050 AEffects.end()) {
Ted Kremenek6bd78702009-04-29 18:50:19 +00002051 // Determine if the object's reference count was pushed to zero.
Jordan Roseb3ad07e2014-03-25 17:10:58 +00002052 assert(!PrevV.hasSameState(CurrV) && "The state should have changed.");
Ted Kremenek6bd78702009-04-29 18:50:19 +00002053 // We may not have transitioned to 'release' if we hit an error.
2054 // This case is handled elsewhere.
2055 if (CurrV.getKind() == RefVal::Released) {
Ted Kremenek3a0516b2009-05-08 20:01:42 +00002056 assert(CurrV.getCombinedCounts() == 0);
Ted Kremenek6bd78702009-04-29 18:50:19 +00002057 os << "Object released by directly sending the '-dealloc' message";
2058 break;
2059 }
2060 }
Mike Stump11289f42009-09-09 15:08:12 +00002061
Ted Kremenek6bd78702009-04-29 18:50:19 +00002062 // Specially handle CFMakeCollectable and friends.
Benjamin Kramerab3838a2013-08-16 21:57:14 +00002063 if (std::find(AEffects.begin(), AEffects.end(), MakeCollectable) !=
2064 AEffects.end()) {
Ted Kremenek6bd78702009-04-29 18:50:19 +00002065 // Get the name of the function.
David Blaikie87396b92013-02-21 22:23:56 +00002066 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
Ted Kremenek632e3b72012-01-06 22:09:28 +00002067 SVal X =
2068 CurrSt->getSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee(), LCtx);
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002069 const FunctionDecl *FD = X.getAsFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00002070
Jordy Rose7a534982011-08-24 05:47:39 +00002071 if (GCEnabled) {
Ted Kremenek6bd78702009-04-29 18:50:19 +00002072 // Determine if the object's reference count was pushed to zero.
Jordan Roseb3ad07e2014-03-25 17:10:58 +00002073 assert(!PrevV.hasSameState(CurrV) && "The state should have changed.");
Mike Stump11289f42009-09-09 15:08:12 +00002074
Benjamin Kramerb89514a2011-10-14 18:45:37 +00002075 os << "In GC mode a call to '" << *FD
Ted Kremenek6bd78702009-04-29 18:50:19 +00002076 << "' decrements an object's retain count and registers the "
2077 "object with the garbage collector. ";
Mike Stump11289f42009-09-09 15:08:12 +00002078
Ted Kremenek6bd78702009-04-29 18:50:19 +00002079 if (CurrV.getKind() == RefVal::Released) {
2080 assert(CurrV.getCount() == 0);
2081 os << "Since it now has a 0 retain count the object can be "
2082 "automatically collected by the garbage collector.";
2083 }
2084 else
2085 os << "An object must have a 0 retain count to be garbage collected. "
2086 "After this call its retain count is +" << CurrV.getCount()
2087 << '.';
2088 }
Mike Stump11289f42009-09-09 15:08:12 +00002089 else
Benjamin Kramerb89514a2011-10-14 18:45:37 +00002090 os << "When GC is not enabled a call to '" << *FD
Ted Kremenek6bd78702009-04-29 18:50:19 +00002091 << "' has no effect on its argument.";
Mike Stump11289f42009-09-09 15:08:12 +00002092
Ted Kremenek6bd78702009-04-29 18:50:19 +00002093 // Nothing more to say.
2094 break;
2095 }
Mike Stump11289f42009-09-09 15:08:12 +00002096
2097 // Determine if the typestate has changed.
Jordan Roseb3ad07e2014-03-25 17:10:58 +00002098 if (!PrevV.hasSameState(CurrV))
Ted Kremenek6bd78702009-04-29 18:50:19 +00002099 switch (CurrV.getKind()) {
2100 case RefVal::Owned:
2101 case RefVal::NotOwned:
Ted Kremenek3a0516b2009-05-08 20:01:42 +00002102 if (PrevV.getCount() == CurrV.getCount()) {
2103 // Did an autorelease message get sent?
2104 if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
Craig Topper0dbb7832014-05-27 02:45:47 +00002105 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002106
Zhongxing Xu08a2ede2009-05-12 10:10:00 +00002107 assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount());
Jordan Rose7467f062013-04-23 01:42:25 +00002108 os << "Object autoreleased";
Ted Kremenek3a0516b2009-05-08 20:01:42 +00002109 break;
2110 }
Mike Stump11289f42009-09-09 15:08:12 +00002111
Ted Kremenek6bd78702009-04-29 18:50:19 +00002112 if (PrevV.getCount() > CurrV.getCount())
2113 os << "Reference count decremented.";
2114 else
2115 os << "Reference count incremented.";
Mike Stump11289f42009-09-09 15:08:12 +00002116
Ted Kremenek6bd78702009-04-29 18:50:19 +00002117 if (unsigned Count = CurrV.getCount())
2118 os << " The object now has a +" << Count << " retain count.";
Mike Stump11289f42009-09-09 15:08:12 +00002119
Ted Kremenek6bd78702009-04-29 18:50:19 +00002120 if (PrevV.getKind() == RefVal::Released) {
Jordy Rose7a534982011-08-24 05:47:39 +00002121 assert(GCEnabled && CurrV.getCount() > 0);
Jordy Rose78373e52012-03-17 05:49:15 +00002122 os << " The object is not eligible for garbage collection until "
2123 "the retain count reaches 0 again.";
Ted Kremenek6bd78702009-04-29 18:50:19 +00002124 }
Mike Stump11289f42009-09-09 15:08:12 +00002125
Ted Kremenek6bd78702009-04-29 18:50:19 +00002126 break;
Mike Stump11289f42009-09-09 15:08:12 +00002127
Ted Kremenek6bd78702009-04-29 18:50:19 +00002128 case RefVal::Released:
Jordan Rosecb5386c2015-02-04 19:24:52 +00002129 if (CurrV.getIvarAccessHistory() ==
2130 RefVal::IvarAccessHistory::ReleasedAfterDirectAccess &&
2131 CurrV.getIvarAccessHistory() != PrevV.getIvarAccessHistory()) {
2132 os << "Strong instance variable relinquished. ";
2133 }
Ted Kremenek6bd78702009-04-29 18:50:19 +00002134 os << "Object released.";
2135 break;
Mike Stump11289f42009-09-09 15:08:12 +00002136
Ted Kremenek6bd78702009-04-29 18:50:19 +00002137 case RefVal::ReturnedOwned:
Jordy Rose78373e52012-03-17 05:49:15 +00002138 // Autoreleases can be applied after marking a node ReturnedOwned.
2139 if (CurrV.getAutoreleaseCount())
Craig Topper0dbb7832014-05-27 02:45:47 +00002140 return nullptr;
Jordy Rose78373e52012-03-17 05:49:15 +00002141
2142 os << "Object returned to caller as an owning reference (single "
2143 "retain count transferred to caller)";
Ted Kremenek6bd78702009-04-29 18:50:19 +00002144 break;
Mike Stump11289f42009-09-09 15:08:12 +00002145
Ted Kremenek6bd78702009-04-29 18:50:19 +00002146 case RefVal::ReturnedNotOwned:
Ted Kremenekf2301982011-05-26 18:45:44 +00002147 os << "Object returned to caller with a +0 retain count";
Ted Kremenek6bd78702009-04-29 18:50:19 +00002148 break;
Mike Stump11289f42009-09-09 15:08:12 +00002149
Ted Kremenek6bd78702009-04-29 18:50:19 +00002150 default:
Craig Topper0dbb7832014-05-27 02:45:47 +00002151 return nullptr;
Ted Kremenek6bd78702009-04-29 18:50:19 +00002152 }
Mike Stump11289f42009-09-09 15:08:12 +00002153
Ted Kremenek6bd78702009-04-29 18:50:19 +00002154 // Emit any remaining diagnostics for the argument effects (if any).
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002155 for (SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
Ted Kremenek6bd78702009-04-29 18:50:19 +00002156 E=AEffects.end(); I != E; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +00002157
Ted Kremenek6bd78702009-04-29 18:50:19 +00002158 // A bunch of things have alternate behavior under GC.
Jordy Rose7a534982011-08-24 05:47:39 +00002159 if (GCEnabled)
Ted Kremenek6bd78702009-04-29 18:50:19 +00002160 switch (*I) {
2161 default: break;
2162 case Autorelease:
2163 os << "In GC mode an 'autorelease' has no effect.";
2164 continue;
2165 case IncRefMsg:
2166 os << "In GC mode the 'retain' message has no effect.";
2167 continue;
2168 case DecRefMsg:
2169 os << "In GC mode the 'release' message has no effect.";
2170 continue;
2171 }
2172 }
Mike Stump11289f42009-09-09 15:08:12 +00002173 } while (0);
2174
Ted Kremenek6bd78702009-04-29 18:50:19 +00002175 if (os.str().empty())
Craig Topper0dbb7832014-05-27 02:45:47 +00002176 return nullptr; // We have nothing to say!
Ted Kremenek051a03d2009-05-13 07:12:33 +00002177
David Blaikie87396b92013-02-21 22:23:56 +00002178 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
Anna Zaks3a769bd2011-09-15 01:08:34 +00002179 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
2180 N->getLocationContext());
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002181 PathDiagnosticPiece *P = new PathDiagnosticEventPiece(Pos, os.str());
Mike Stump11289f42009-09-09 15:08:12 +00002182
Ted Kremenek6bd78702009-04-29 18:50:19 +00002183 // Add the range by scanning the children of the statement for any bindings
2184 // to Sym.
Benjamin Kramer973431b2015-07-03 15:12:24 +00002185 for (const Stmt *Child : S->children())
2186 if (const Expr *Exp = dyn_cast_or_null<Expr>(Child))
Ted Kremenek632e3b72012-01-06 22:09:28 +00002187 if (CurrSt->getSValAsScalarOrLoc(Exp, LCtx).getAsLocSymbol() == Sym) {
Ted Kremenek6bd78702009-04-29 18:50:19 +00002188 P->addRange(Exp->getSourceRange());
2189 break;
2190 }
Mike Stump11289f42009-09-09 15:08:12 +00002191
Ted Kremenek6bd78702009-04-29 18:50:19 +00002192 return P;
2193}
2194
Benjamin Kramere003ca22015-10-28 13:54:16 +00002195namespace {
Anna Zaks75de3232012-02-28 22:39:22 +00002196// Find the first node in the current function context that referred to the
2197// tracked symbol and the memory location that value was stored to. Note, the
2198// value is only reported if the allocation occurred in the same function as
Anna Zakse51362e2013-04-10 21:42:06 +00002199// the leak. The function can also return a location context, which should be
2200// treated as interesting.
2201struct AllocationInfo {
2202 const ExplodedNode* N;
Anna Zaks3f303be2013-04-10 22:56:30 +00002203 const MemRegion *R;
Anna Zakse51362e2013-04-10 21:42:06 +00002204 const LocationContext *InterestingMethodContext;
Anna Zaks3f303be2013-04-10 22:56:30 +00002205 AllocationInfo(const ExplodedNode *InN,
2206 const MemRegion *InR,
Anna Zakse51362e2013-04-10 21:42:06 +00002207 const LocationContext *InInterestingMethodContext) :
2208 N(InN), R(InR), InterestingMethodContext(InInterestingMethodContext) {}
2209};
Benjamin Kramere003ca22015-10-28 13:54:16 +00002210} // end anonymous namespace
Anna Zakse51362e2013-04-10 21:42:06 +00002211
2212static AllocationInfo
Ted Kremenek001fd5b2011-08-15 22:09:50 +00002213GetAllocationSite(ProgramStateManager& StateMgr, const ExplodedNode *N,
Ted Kremenek6bd78702009-04-29 18:50:19 +00002214 SymbolRef Sym) {
Anna Zakse51362e2013-04-10 21:42:06 +00002215 const ExplodedNode *AllocationNode = N;
Anna Zaks486a0ff2015-02-05 01:02:53 +00002216 const ExplodedNode *AllocationNodeInCurrentOrParentContext = N;
Craig Topper0dbb7832014-05-27 02:45:47 +00002217 const MemRegion *FirstBinding = nullptr;
Anna Zaks75de3232012-02-28 22:39:22 +00002218 const LocationContext *LeakContext = N->getLocationContext();
Mike Stump11289f42009-09-09 15:08:12 +00002219
Anna Zakse51362e2013-04-10 21:42:06 +00002220 // The location context of the init method called on the leaked object, if
2221 // available.
Craig Topper0dbb7832014-05-27 02:45:47 +00002222 const LocationContext *InitMethodContext = nullptr;
Anna Zakse51362e2013-04-10 21:42:06 +00002223
Ted Kremenek6bd78702009-04-29 18:50:19 +00002224 while (N) {
Ted Kremenek49b1e382012-01-26 21:29:00 +00002225 ProgramStateRef St = N->getState();
Anna Zakse51362e2013-04-10 21:42:06 +00002226 const LocationContext *NContext = N->getLocationContext();
Mike Stump11289f42009-09-09 15:08:12 +00002227
Anna Zaksf5788c72012-08-14 00:36:15 +00002228 if (!getRefBinding(St, Sym))
Ted Kremenek6bd78702009-04-29 18:50:19 +00002229 break;
Mike Stump11289f42009-09-09 15:08:12 +00002230
Anna Zaks6797d6e2012-03-21 19:45:01 +00002231 StoreManager::FindUniqueBinding FB(Sym);
Mike Stump11289f42009-09-09 15:08:12 +00002232 StateMgr.iterBindings(St, FB);
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002233
Anna Zaks7c19abe2013-04-10 21:42:02 +00002234 if (FB) {
2235 const MemRegion *R = FB.getRegion();
Anna Zaks07804ef2013-04-10 22:56:33 +00002236 const VarRegion *VR = R->getBaseRegion()->getAs<VarRegion>();
Anna Zaks7c19abe2013-04-10 21:42:02 +00002237 // Do not show local variables belonging to a function other than
2238 // where the error is reported.
2239 if (!VR || VR->getStackFrame() == LeakContext->getCurrentStackFrame())
Anna Zakse51362e2013-04-10 21:42:06 +00002240 FirstBinding = R;
Anna Zaks7c19abe2013-04-10 21:42:02 +00002241 }
Mike Stump11289f42009-09-09 15:08:12 +00002242
Anna Zakse51362e2013-04-10 21:42:06 +00002243 // AllocationNode is the last node in which the symbol was tracked.
2244 AllocationNode = N;
2245
Anna Zaks486a0ff2015-02-05 01:02:53 +00002246 // AllocationNodeInCurrentContext, is the last node in the current or
2247 // parent context in which the symbol was tracked.
2248 //
2249 // Note that the allocation site might be in the parent conext. For example,
2250 // the case where an allocation happens in a block that captures a reference
2251 // to it and that reference is overwritten/dropped by another call to
2252 // the block.
2253 if (NContext == LeakContext || NContext->isParentOf(LeakContext))
2254 AllocationNodeInCurrentOrParentContext = N;
Anna Zakse51362e2013-04-10 21:42:06 +00002255
Anna Zaks3f303be2013-04-10 22:56:30 +00002256 // Find the last init that was called on the given symbol and store the
2257 // init method's location context.
2258 if (!InitMethodContext)
2259 if (Optional<CallEnter> CEP = N->getLocation().getAs<CallEnter>()) {
2260 const Stmt *CE = CEP->getCallExpr();
Anna Zaks99394bb2013-04-25 00:41:32 +00002261 if (const ObjCMessageExpr *ME = dyn_cast_or_null<ObjCMessageExpr>(CE)) {
Anna Zaks3f303be2013-04-10 22:56:30 +00002262 const Stmt *RecExpr = ME->getInstanceReceiver();
2263 if (RecExpr) {
2264 SVal RecV = St->getSVal(RecExpr, NContext);
2265 if (ME->getMethodFamily() == OMF_init && RecV.getAsSymbol() == Sym)
2266 InitMethodContext = CEP->getCalleeContext();
2267 }
2268 }
Anna Zakse51362e2013-04-10 21:42:06 +00002269 }
Anna Zaks75de3232012-02-28 22:39:22 +00002270
Craig Topper0dbb7832014-05-27 02:45:47 +00002271 N = N->pred_empty() ? nullptr : *(N->pred_begin());
Ted Kremenek6bd78702009-04-29 18:50:19 +00002272 }
Mike Stump11289f42009-09-09 15:08:12 +00002273
Anna Zakse51362e2013-04-10 21:42:06 +00002274 // If we are reporting a leak of the object that was allocated with alloc,
Anna Zaks3f303be2013-04-10 22:56:30 +00002275 // mark its init method as interesting.
Craig Topper0dbb7832014-05-27 02:45:47 +00002276 const LocationContext *InterestingMethodContext = nullptr;
Anna Zakse51362e2013-04-10 21:42:06 +00002277 if (InitMethodContext) {
2278 const ProgramPoint AllocPP = AllocationNode->getLocation();
2279 if (Optional<StmtPoint> SP = AllocPP.getAs<StmtPoint>())
2280 if (const ObjCMessageExpr *ME = SP->getStmtAs<ObjCMessageExpr>())
2281 if (ME->getMethodFamily() == OMF_alloc)
2282 InterestingMethodContext = InitMethodContext;
2283 }
2284
Anna Zaks75de3232012-02-28 22:39:22 +00002285 // If allocation happened in a function different from the leak node context,
2286 // do not report the binding.
Ted Kremenekb045b012012-10-12 22:56:40 +00002287 assert(N && "Could not find allocation node");
Anna Zaks75de3232012-02-28 22:39:22 +00002288 if (N->getLocationContext() != LeakContext) {
Craig Topper0dbb7832014-05-27 02:45:47 +00002289 FirstBinding = nullptr;
Anna Zaks75de3232012-02-28 22:39:22 +00002290 }
2291
Anna Zaks486a0ff2015-02-05 01:02:53 +00002292 return AllocationInfo(AllocationNodeInCurrentOrParentContext,
Anna Zakse51362e2013-04-10 21:42:06 +00002293 FirstBinding,
2294 InterestingMethodContext);
Ted Kremenek6bd78702009-04-29 18:50:19 +00002295}
2296
David Blaikied15481c2014-08-29 18:18:43 +00002297std::unique_ptr<PathDiagnosticPiece>
Anna Zaks88255cc2011-08-20 01:27:22 +00002298CFRefReportVisitor::getEndPath(BugReporterContext &BRC,
David Blaikied15481c2014-08-29 18:18:43 +00002299 const ExplodedNode *EndN, BugReport &BR) {
Ted Kremenek1e809b42012-03-09 01:13:14 +00002300 BR.markInteresting(Sym);
Anna Zaks88255cc2011-08-20 01:27:22 +00002301 return BugReporterVisitor::getDefaultEndPath(BRC, EndN, BR);
Ted Kremenek6bd78702009-04-29 18:50:19 +00002302}
2303
David Blaikied15481c2014-08-29 18:18:43 +00002304std::unique_ptr<PathDiagnosticPiece>
Anna Zaks88255cc2011-08-20 01:27:22 +00002305CFRefLeakReportVisitor::getEndPath(BugReporterContext &BRC,
David Blaikied15481c2014-08-29 18:18:43 +00002306 const ExplodedNode *EndN, BugReport &BR) {
Mike Stump11289f42009-09-09 15:08:12 +00002307
Ted Kremenekbb8d5462009-05-06 21:39:49 +00002308 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenek6bd78702009-04-29 18:50:19 +00002309 // assigned to different variables, etc.
Ted Kremenek1e809b42012-03-09 01:13:14 +00002310 BR.markInteresting(Sym);
Mike Stump11289f42009-09-09 15:08:12 +00002311
Ted Kremenek6bd78702009-04-29 18:50:19 +00002312 // We are reporting a leak. Walk up the graph to get to the first node where
2313 // the symbol appeared, and also get the first VarDecl that tracked object
2314 // is stored to.
Anna Zakse51362e2013-04-10 21:42:06 +00002315 AllocationInfo AllocI =
Ted Kremenek8c8fb482009-05-08 23:32:51 +00002316 GetAllocationSite(BRC.getStateManager(), EndN, Sym);
Mike Stump11289f42009-09-09 15:08:12 +00002317
Anna Zakse51362e2013-04-10 21:42:06 +00002318 const MemRegion* FirstBinding = AllocI.R;
2319 BR.markInteresting(AllocI.InterestingMethodContext);
2320
Anna Zaks921f0492011-09-15 18:56:07 +00002321 SourceManager& SM = BRC.getSourceManager();
Mike Stump11289f42009-09-09 15:08:12 +00002322
Ted Kremenek6bd78702009-04-29 18:50:19 +00002323 // Compute an actual location for the leak. Sometimes a leak doesn't
2324 // occur at an actual statement (e.g., transition between blocks; end
2325 // of function) so we need to walk the graph and compute a real location.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002326 const ExplodedNode *LeakN = EndN;
Anna Zaks921f0492011-09-15 18:56:07 +00002327 PathDiagnosticLocation L = PathDiagnosticLocation::createEndOfPath(LeakN, SM);
Mike Stump11289f42009-09-09 15:08:12 +00002328
Ted Kremenek6bd78702009-04-29 18:50:19 +00002329 std::string sbuf;
2330 llvm::raw_string_ostream os(sbuf);
Mike Stump11289f42009-09-09 15:08:12 +00002331
Ted Kremenekf2301982011-05-26 18:45:44 +00002332 os << "Object leaked: ";
Mike Stump11289f42009-09-09 15:08:12 +00002333
Ted Kremenekf2301982011-05-26 18:45:44 +00002334 if (FirstBinding) {
2335 os << "object allocated and stored into '"
2336 << FirstBinding->getString() << '\'';
2337 }
2338 else
2339 os << "allocated object";
Mike Stump11289f42009-09-09 15:08:12 +00002340
Ted Kremenek6bd78702009-04-29 18:50:19 +00002341 // Get the retain count.
Anna Zaksf5788c72012-08-14 00:36:15 +00002342 const RefVal* RV = getRefBinding(EndN->getState(), Sym);
Ted Kremenekb045b012012-10-12 22:56:40 +00002343 assert(RV);
Mike Stump11289f42009-09-09 15:08:12 +00002344
Ted Kremenek6bd78702009-04-29 18:50:19 +00002345 if (RV->getKind() == RefVal::ErrorLeakReturned) {
2346 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
Jordy Rose43426f82011-07-15 22:17:54 +00002347 // objects. Only "copy", "alloc", "retain" and "new" transfer ownership
Ted Kremenek6bd78702009-04-29 18:50:19 +00002348 // to the caller for NS objects.
Ted Kremenek8e2c9b02011-05-25 06:19:45 +00002349 const Decl *D = &EndN->getCodeDecl();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002350
Ted Kremenek2a786952012-09-06 23:03:07 +00002351 os << (isa<ObjCMethodDecl>(D) ? " is returned from a method "
2352 : " is returned from a function ");
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002353
Aaron Ballman9ead1242013-12-19 02:39:40 +00002354 if (D->hasAttr<CFReturnsNotRetainedAttr>())
Ted Kremenek2a786952012-09-06 23:03:07 +00002355 os << "that is annotated as CF_RETURNS_NOT_RETAINED";
Aaron Ballman9ead1242013-12-19 02:39:40 +00002356 else if (D->hasAttr<NSReturnsNotRetainedAttr>())
Ted Kremenek2a786952012-09-06 23:03:07 +00002357 os << "that is annotated as NS_RETURNS_NOT_RETAINED";
Ted Kremenek8e2c9b02011-05-25 06:19:45 +00002358 else {
Ted Kremenek2a786952012-09-06 23:03:07 +00002359 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2360 os << "whose name ('" << MD->getSelector().getAsString()
2361 << "') does not start with 'copy', 'mutableCopy', 'alloc' or 'new'."
2362 " This violates the naming convention rules"
2363 " given in the Memory Management Guide for Cocoa";
2364 }
2365 else {
2366 const FunctionDecl *FD = cast<FunctionDecl>(D);
2367 os << "whose name ('" << *FD
2368 << "') does not contain 'Copy' or 'Create'. This violates the naming"
2369 " convention rules given in the Memory Management Guide for Core"
2370 " Foundation";
2371 }
2372 }
Ted Kremenek6bd78702009-04-29 18:50:19 +00002373 }
Ted Kremenekdee56e32009-05-10 06:25:57 +00002374 else if (RV->getKind() == RefVal::ErrorGCLeakReturned) {
David Blaikie3cbec0f2013-02-21 22:37:44 +00002375 const ObjCMethodDecl &MD = cast<ObjCMethodDecl>(EndN->getCodeDecl());
Ted Kremenekdee56e32009-05-10 06:25:57 +00002376 os << " and returned from method '" << MD.getSelector().getAsString()
Ted Kremenek1f8e4342009-05-10 16:52:15 +00002377 << "' is potentially leaked when using garbage collection. Callers "
2378 "of this method do not expect a returned object with a +1 retain "
2379 "count since they expect the object to be managed by the garbage "
2380 "collector";
Ted Kremenekdee56e32009-05-10 06:25:57 +00002381 }
Ted Kremenek6bd78702009-04-29 18:50:19 +00002382 else
Ted Kremenek4f63ac72010-10-15 22:50:23 +00002383 os << " is not referenced later in this execution path and has a retain "
Ted Kremenekf2301982011-05-26 18:45:44 +00002384 "count of +" << RV->getCount();
Mike Stump11289f42009-09-09 15:08:12 +00002385
David Blaikied15481c2014-08-29 18:18:43 +00002386 return llvm::make_unique<PathDiagnosticEventPiece>(L, os.str());
Ted Kremenek6bd78702009-04-29 18:50:19 +00002387}
2388
Jordy Rose184bd142011-08-24 22:39:09 +00002389CFRefLeakReport::CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts,
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002390 bool GCEnabled, const SummaryLogTy &Log,
Jordy Rose184bd142011-08-24 22:39:09 +00002391 ExplodedNode *n, SymbolRef sym,
Ted Kremenek8671acb2013-04-16 21:44:22 +00002392 CheckerContext &Ctx,
2393 bool IncludeAllocationLine)
2394 : CFRefReport(D, LOpts, GCEnabled, Log, n, sym, false) {
Mike Stump11289f42009-09-09 15:08:12 +00002395
Chris Lattner57540c52011-04-15 05:22:18 +00002396 // Most bug reports are cached at the location where they occurred.
Ted Kremenek6bd78702009-04-29 18:50:19 +00002397 // With leaks, we want to unique them by the location where they were
2398 // allocated, and only report a single path. To do this, we need to find
2399 // the allocation site of a piece of tracked memory, which we do via a
2400 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2401 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2402 // that all ancestor nodes that represent the allocation site have the
2403 // same SourceLocation.
Craig Topper0dbb7832014-05-27 02:45:47 +00002404 const ExplodedNode *AllocNode = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002405
Anna Zaks58734db2011-10-25 19:57:11 +00002406 const SourceManager& SMgr = Ctx.getSourceManager();
Anna Zaksc29bed32011-09-20 21:38:35 +00002407
Anna Zakse51362e2013-04-10 21:42:06 +00002408 AllocationInfo AllocI =
Anna Zaks58734db2011-10-25 19:57:11 +00002409 GetAllocationSite(Ctx.getStateManager(), getErrorNode(), sym);
Mike Stump11289f42009-09-09 15:08:12 +00002410
Anna Zakse51362e2013-04-10 21:42:06 +00002411 AllocNode = AllocI.N;
2412 AllocBinding = AllocI.R;
2413 markInteresting(AllocI.InterestingMethodContext);
2414
Ted Kremenek6bd78702009-04-29 18:50:19 +00002415 // Get the SourceLocation for the allocation site.
Jordan Rosefbe6dba2012-07-10 22:07:52 +00002416 // FIXME: This will crash the analyzer if an allocation comes from an
Anna Zaksa6fea132014-06-13 23:47:38 +00002417 // implicit call (ex: a destructor call).
2418 // (Currently there are no such allocations in Cocoa, though.)
Hans Wennborgdcfba332015-10-06 23:40:43 +00002419 const Stmt *AllocStmt = nullptr;
Ted Kremenek6bd78702009-04-29 18:50:19 +00002420 ProgramPoint P = AllocNode->getLocation();
David Blaikie87396b92013-02-21 22:23:56 +00002421 if (Optional<CallExitEnd> Exit = P.getAs<CallExitEnd>())
Jordan Rosefbe6dba2012-07-10 22:07:52 +00002422 AllocStmt = Exit->getCalleeContext()->getCallSite();
Anna Zaks486a0ff2015-02-05 01:02:53 +00002423 else
2424 AllocStmt = P.castAs<PostStmt>().getStmt();
Anna Zaksa6fea132014-06-13 23:47:38 +00002425 assert(AllocStmt && "Cannot find allocation statement");
Anna Zaks40402872013-04-23 23:57:50 +00002426
2427 PathDiagnosticLocation AllocLocation =
2428 PathDiagnosticLocation::createBegin(AllocStmt, SMgr,
2429 AllocNode->getLocationContext());
2430 Location = AllocLocation;
2431
2432 // Set uniqieing info, which will be used for unique the bug reports. The
2433 // leaks should be uniqued on the allocation site.
2434 UniqueingLocation = AllocLocation;
2435 UniqueingDecl = AllocNode->getLocationContext()->getDecl();
2436
Ted Kremenek6bd78702009-04-29 18:50:19 +00002437 // Fill in the description of the bug.
2438 Description.clear();
2439 llvm::raw_string_ostream os(Description);
Ted Kremenekf1e76672009-05-02 19:05:19 +00002440 os << "Potential leak ";
Jordy Rose184bd142011-08-24 22:39:09 +00002441 if (GCEnabled)
Ted Kremenekf1e76672009-05-02 19:05:19 +00002442 os << "(when using garbage collection) ";
Anna Zaks16f38312012-02-28 21:49:08 +00002443 os << "of an object";
Mike Stump11289f42009-09-09 15:08:12 +00002444
Ted Kremenek8671acb2013-04-16 21:44:22 +00002445 if (AllocBinding) {
Anna Zaks16f38312012-02-28 21:49:08 +00002446 os << " stored into '" << AllocBinding->getString() << '\'';
Ted Kremenek8671acb2013-04-16 21:44:22 +00002447 if (IncludeAllocationLine) {
2448 FullSourceLoc SL(AllocStmt->getLocStart(), Ctx.getSourceManager());
2449 os << " (allocated on line " << SL.getSpellingLineNumber() << ")";
2450 }
2451 }
Anna Zaks071a89c2011-08-19 23:21:56 +00002452
David Blaikie91e79022014-09-04 23:54:33 +00002453 addVisitor(llvm::make_unique<CFRefLeakReportVisitor>(sym, GCEnabled, Log));
Ted Kremenek6bd78702009-04-29 18:50:19 +00002454}
2455
2456//===----------------------------------------------------------------------===//
2457// Main checker logic.
2458//===----------------------------------------------------------------------===//
2459
Ted Kremenek70a87882009-11-25 22:17:44 +00002460namespace {
Jordy Rose75e680e2011-09-02 06:44:22 +00002461class RetainCountChecker
Jordy Rose5df640d2011-08-24 18:56:32 +00002462 : public Checker< check::Bind,
Jordy Rose78612762011-08-23 19:01:07 +00002463 check::DeadSymbols,
Jordy Rose5df640d2011-08-24 18:56:32 +00002464 check::EndAnalysis,
Anna Zaks3fdcc0b2013-01-03 00:25:29 +00002465 check::EndFunction,
Jordy Rose217eb902011-08-17 21:27:39 +00002466 check::PostStmt<BlockExpr>,
John McCall31168b02011-06-15 23:02:42 +00002467 check::PostStmt<CastExpr>,
Ted Kremenek415287d2012-03-06 20:06:12 +00002468 check::PostStmt<ObjCArrayLiteral>,
2469 check::PostStmt<ObjCDictionaryLiteral>,
Jordy Rose6393f822012-05-12 05:10:43 +00002470 check::PostStmt<ObjCBoxedExpr>,
Jordan Roseb3ad07e2014-03-25 17:10:58 +00002471 check::PostStmt<ObjCIvarRefExpr>,
Jordan Rose682b3162012-07-02 19:28:21 +00002472 check::PostCall,
Jordy Rose298cc4d2011-08-23 19:43:16 +00002473 check::PreStmt<ReturnStmt>,
Jordy Rose217eb902011-08-17 21:27:39 +00002474 check::RegionChanges,
Jordy Rose898a1482011-08-21 21:58:18 +00002475 eval::Assume,
2476 eval::Call > {
Ahmed Charlesb8984322014-03-07 20:03:18 +00002477 mutable std::unique_ptr<CFRefBug> useAfterRelease, releaseNotOwned;
2478 mutable std::unique_ptr<CFRefBug> deallocGC, deallocNotOwned;
2479 mutable std::unique_ptr<CFRefBug> overAutorelease, returnNotOwnedForOwned;
2480 mutable std::unique_ptr<CFRefBug> leakWithinFunction, leakAtReturn;
2481 mutable std::unique_ptr<CFRefBug> leakWithinFunctionGC, leakAtReturnGC;
Jordy Rose78612762011-08-23 19:01:07 +00002482
Anton Yartsev6a619222014-02-17 18:25:34 +00002483 typedef llvm::DenseMap<SymbolRef, const CheckerProgramPointTag *> SymbolTagMap;
Jordy Rose78612762011-08-23 19:01:07 +00002484
2485 // This map is only used to ensure proper deletion of any allocated tags.
2486 mutable SymbolTagMap DeadSymbolTags;
2487
Ahmed Charlesb8984322014-03-07 20:03:18 +00002488 mutable std::unique_ptr<RetainSummaryManager> Summaries;
2489 mutable std::unique_ptr<RetainSummaryManager> SummariesGC;
Jordy Rose5df640d2011-08-24 18:56:32 +00002490 mutable SummaryLogTy SummaryLog;
2491 mutable bool ShouldResetSummaryLog;
2492
Ted Kremenek8671acb2013-04-16 21:44:22 +00002493 /// Optional setting to indicate if leak reports should include
2494 /// the allocation line.
2495 mutable bool IncludeAllocationLine;
2496
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002497public:
Ted Kremenek8671acb2013-04-16 21:44:22 +00002498 RetainCountChecker(AnalyzerOptions &AO)
2499 : ShouldResetSummaryLog(false),
2500 IncludeAllocationLine(shouldIncludeAllocationSiteInLeakDiagnostics(AO)) {}
Jordy Rose78612762011-08-23 19:01:07 +00002501
Alexander Kornienko34eb2072015-04-11 02:00:23 +00002502 ~RetainCountChecker() override { DeleteContainerSeconds(DeadSymbolTags); }
Jordy Rose78612762011-08-23 19:01:07 +00002503
Jordy Rose5df640d2011-08-24 18:56:32 +00002504 void checkEndAnalysis(ExplodedGraph &G, BugReporter &BR,
2505 ExprEngine &Eng) const {
2506 // FIXME: This is a hack to make sure the summary log gets cleared between
2507 // analyses of different code bodies.
2508 //
2509 // Why is this necessary? Because a checker's lifetime is tied to a
2510 // translation unit, but an ExplodedGraph's lifetime is just a code body.
2511 // Once in a blue moon, a new ExplodedNode will have the same address as an
2512 // old one with an associated summary, and the bug report visitor gets very
2513 // confused. (To make things worse, the summary lifetime is currently also
2514 // tied to a code body, so we get a crash instead of incorrect results.)
Jordy Rose95589f12011-08-24 09:27:24 +00002515 //
2516 // Why is this a bad solution? Because if the lifetime of the ExplodedGraph
2517 // changes, things will start going wrong again. Really the lifetime of this
2518 // log needs to be tied to either the specific nodes in it or the entire
2519 // ExplodedGraph, not to a specific part of the code being analyzed.
2520 //
Jordy Rose5df640d2011-08-24 18:56:32 +00002521 // (Also, having stateful local data means that the same checker can't be
2522 // used from multiple threads, but a lot of checkers have incorrect
2523 // assumptions about that anyway. So that wasn't a priority at the time of
2524 // this fix.)
Jordy Rose95589f12011-08-24 09:27:24 +00002525 //
Jordy Rose5df640d2011-08-24 18:56:32 +00002526 // This happens at the end of analysis, but bug reports are emitted /after/
2527 // this point. So we can't just clear the summary log now. Instead, we mark
2528 // that the next time we access the summary log, it should be cleared.
2529
2530 // If we never reset the summary log during /this/ code body analysis,
2531 // there were no new summaries. There might still have been summaries from
2532 // the /last/ analysis, so clear them out to make sure the bug report
2533 // visitors don't get confused.
2534 if (ShouldResetSummaryLog)
2535 SummaryLog.clear();
2536
2537 ShouldResetSummaryLog = !SummaryLog.empty();
Jordy Rose95589f12011-08-24 09:27:24 +00002538 }
2539
Jordy Rosec49ec532011-09-02 05:55:19 +00002540 CFRefBug *getLeakWithinFunctionBug(const LangOptions &LOpts,
2541 bool GCEnabled) const {
2542 if (GCEnabled) {
Jordy Rose15484da2011-08-25 01:14:38 +00002543 if (!leakWithinFunctionGC)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002544 leakWithinFunctionGC.reset(new Leak(this, "Leak of object when using "
2545 "garbage collection"));
Jordy Rosec49ec532011-09-02 05:55:19 +00002546 return leakWithinFunctionGC.get();
Jordy Rose15484da2011-08-25 01:14:38 +00002547 } else {
2548 if (!leakWithinFunction) {
Douglas Gregor79a91412011-09-13 17:21:33 +00002549 if (LOpts.getGC() == LangOptions::HybridGC) {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002550 leakWithinFunction.reset(new Leak(this,
2551 "Leak of object when not using "
Benjamin Kramerd1d76b22012-06-06 17:32:50 +00002552 "garbage collection (GC) in "
2553 "dual GC/non-GC code"));
Jordy Rose15484da2011-08-25 01:14:38 +00002554 } else {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002555 leakWithinFunction.reset(new Leak(this, "Leak"));
Jordy Rose15484da2011-08-25 01:14:38 +00002556 }
2557 }
Jordy Rosec49ec532011-09-02 05:55:19 +00002558 return leakWithinFunction.get();
Jordy Rose15484da2011-08-25 01:14:38 +00002559 }
2560 }
2561
Jordy Rosec49ec532011-09-02 05:55:19 +00002562 CFRefBug *getLeakAtReturnBug(const LangOptions &LOpts, bool GCEnabled) const {
2563 if (GCEnabled) {
Jordy Rose15484da2011-08-25 01:14:38 +00002564 if (!leakAtReturnGC)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002565 leakAtReturnGC.reset(new Leak(this,
2566 "Leak of returned object when using "
Benjamin Kramerd1d76b22012-06-06 17:32:50 +00002567 "garbage collection"));
Jordy Rosec49ec532011-09-02 05:55:19 +00002568 return leakAtReturnGC.get();
Jordy Rose15484da2011-08-25 01:14:38 +00002569 } else {
2570 if (!leakAtReturn) {
Douglas Gregor79a91412011-09-13 17:21:33 +00002571 if (LOpts.getGC() == LangOptions::HybridGC) {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002572 leakAtReturn.reset(new Leak(this,
2573 "Leak of returned object when not using "
Benjamin Kramerd1d76b22012-06-06 17:32:50 +00002574 "garbage collection (GC) in dual "
2575 "GC/non-GC code"));
Jordy Rose15484da2011-08-25 01:14:38 +00002576 } else {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002577 leakAtReturn.reset(new Leak(this, "Leak of returned object"));
Jordy Rose15484da2011-08-25 01:14:38 +00002578 }
2579 }
Jordy Rosec49ec532011-09-02 05:55:19 +00002580 return leakAtReturn.get();
Jordy Rose15484da2011-08-25 01:14:38 +00002581 }
2582 }
2583
Jordy Rosec49ec532011-09-02 05:55:19 +00002584 RetainSummaryManager &getSummaryManager(ASTContext &Ctx,
2585 bool GCEnabled) const {
2586 // FIXME: We don't support ARC being turned on and off during one analysis.
2587 // (nor, for that matter, do we support changing ASTContexts)
David Blaikiebbafb8a2012-03-11 07:00:24 +00002588 bool ARCEnabled = (bool)Ctx.getLangOpts().ObjCAutoRefCount;
Jordy Rosec49ec532011-09-02 05:55:19 +00002589 if (GCEnabled) {
2590 if (!SummariesGC)
Jordy Rose8b289a22011-08-25 00:10:37 +00002591 SummariesGC.reset(new RetainSummaryManager(Ctx, true, ARCEnabled));
Jordy Rosec49ec532011-09-02 05:55:19 +00002592 else
2593 assert(SummariesGC->isARCEnabled() == ARCEnabled);
Jordy Rose8b289a22011-08-25 00:10:37 +00002594 return *SummariesGC;
2595 } else {
Jordy Rosec49ec532011-09-02 05:55:19 +00002596 if (!Summaries)
Jordy Rose8b289a22011-08-25 00:10:37 +00002597 Summaries.reset(new RetainSummaryManager(Ctx, false, ARCEnabled));
Jordy Rosec49ec532011-09-02 05:55:19 +00002598 else
2599 assert(Summaries->isARCEnabled() == ARCEnabled);
Jordy Rose8b289a22011-08-25 00:10:37 +00002600 return *Summaries;
2601 }
2602 }
2603
Jordy Rosec49ec532011-09-02 05:55:19 +00002604 RetainSummaryManager &getSummaryManager(CheckerContext &C) const {
2605 return getSummaryManager(C.getASTContext(), C.isObjCGCEnabled());
2606 }
2607
Ted Kremenek49b1e382012-01-26 21:29:00 +00002608 void printState(raw_ostream &Out, ProgramStateRef State,
Craig Topperfb6b25b2014-03-15 04:29:04 +00002609 const char *NL, const char *Sep) const override;
Jordy Rose58a20d32011-08-28 19:11:56 +00002610
Anna Zaks3e0f4152011-10-06 00:43:15 +00002611 void checkBind(SVal loc, SVal val, const Stmt *S, CheckerContext &C) const;
Jordy Rose5c252ef2011-08-20 21:16:58 +00002612 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
2613 void checkPostStmt(const CastExpr *CE, CheckerContext &C) const;
John McCall31168b02011-06-15 23:02:42 +00002614
Ted Kremenek415287d2012-03-06 20:06:12 +00002615 void checkPostStmt(const ObjCArrayLiteral *AL, CheckerContext &C) const;
2616 void checkPostStmt(const ObjCDictionaryLiteral *DL, CheckerContext &C) const;
Jordy Rose6393f822012-05-12 05:10:43 +00002617 void checkPostStmt(const ObjCBoxedExpr *BE, CheckerContext &C) const;
2618
Jordan Roseb3ad07e2014-03-25 17:10:58 +00002619 void checkPostStmt(const ObjCIvarRefExpr *IRE, CheckerContext &C) const;
2620
Jordan Rose682b3162012-07-02 19:28:21 +00002621 void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002622
Jordan Roseeec15392012-07-02 19:27:43 +00002623 void checkSummary(const RetainSummary &Summ, const CallEvent &Call,
Jordy Rosed188d662011-08-28 05:16:28 +00002624 CheckerContext &C) const;
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002625
Anna Zaks25612732012-08-29 23:23:43 +00002626 void processSummaryOfInlined(const RetainSummary &Summ,
2627 const CallEvent &Call,
2628 CheckerContext &C) const;
2629
Jordy Rose898a1482011-08-21 21:58:18 +00002630 bool evalCall(const CallExpr *CE, CheckerContext &C) const;
2631
Ted Kremenek49b1e382012-01-26 21:29:00 +00002632 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Jordy Rose5c252ef2011-08-20 21:16:58 +00002633 bool Assumption) const;
Jordy Rose217eb902011-08-17 21:27:39 +00002634
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002635 ProgramStateRef
Ted Kremenek49b1e382012-01-26 21:29:00 +00002636 checkRegionChanges(ProgramStateRef state,
Anna Zaksdc154152012-12-20 00:38:25 +00002637 const InvalidatedSymbols *invalidated,
Jordy Rose1fad6632011-08-27 22:51:26 +00002638 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks3d348342012-02-14 21:55:24 +00002639 ArrayRef<const MemRegion *> Regions,
Jordan Rose742920c2012-07-02 19:27:35 +00002640 const CallEvent *Call) const;
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002641
Ted Kremenek49b1e382012-01-26 21:29:00 +00002642 bool wantsRegionChangeUpdate(ProgramStateRef state) const {
Jordy Rosea8f99ba2011-08-20 21:17:59 +00002643 return true;
Jordy Rose5c252ef2011-08-20 21:16:58 +00002644 }
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002645
Jordy Rose298cc4d2011-08-23 19:43:16 +00002646 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
2647 void checkReturnWithRetEffect(const ReturnStmt *S, CheckerContext &C,
2648 ExplodedNode *Pred, RetEffect RE, RefVal X,
Ted Kremenek49b1e382012-01-26 21:29:00 +00002649 SymbolRef Sym, ProgramStateRef state) const;
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002650
Jordy Rose78612762011-08-23 19:01:07 +00002651 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Anna Zaks3fdcc0b2013-01-03 00:25:29 +00002652 void checkEndFunction(CheckerContext &C) const;
Jordy Rose78612762011-08-23 19:01:07 +00002653
Ted Kremenek49b1e382012-01-26 21:29:00 +00002654 ProgramStateRef updateSymbol(ProgramStateRef state, SymbolRef sym,
Anna Zaks25612732012-08-29 23:23:43 +00002655 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
2656 CheckerContext &C) const;
Jordy Rosebf77e512011-08-23 20:27:16 +00002657
Ted Kremenek49b1e382012-01-26 21:29:00 +00002658 void processNonLeakError(ProgramStateRef St, SourceRange ErrorRange,
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002659 RefVal::Kind ErrorKind, SymbolRef Sym,
2660 CheckerContext &C) const;
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002661
Ted Kremenek415287d2012-03-06 20:06:12 +00002662 void processObjCLiterals(CheckerContext &C, const Expr *Ex) const;
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002663
Jordy Rose78612762011-08-23 19:01:07 +00002664 const ProgramPointTag *getDeadSymbolTag(SymbolRef sym) const;
2665
Ted Kremenek49b1e382012-01-26 21:29:00 +00002666 ProgramStateRef handleSymbolDeath(ProgramStateRef state,
Anna Zaksf5788c72012-08-14 00:36:15 +00002667 SymbolRef sid, RefVal V,
2668 SmallVectorImpl<SymbolRef> &Leaked) const;
Jordy Rose78612762011-08-23 19:01:07 +00002669
Jordan Roseff03c1d2012-12-06 18:58:18 +00002670 ProgramStateRef
Jordan Rose9f61f8a2012-08-18 00:30:16 +00002671 handleAutoreleaseCounts(ProgramStateRef state, ExplodedNode *Pred,
2672 const ProgramPointTag *Tag, CheckerContext &Ctx,
2673 SymbolRef Sym, RefVal V) const;
Jordy Rose6763e382011-08-23 20:07:14 +00002674
Ted Kremenek49b1e382012-01-26 21:29:00 +00002675 ExplodedNode *processLeaks(ProgramStateRef state,
Jordy Rose78612762011-08-23 19:01:07 +00002676 SmallVectorImpl<SymbolRef> &Leaked,
Anna Zaks58734db2011-10-25 19:57:11 +00002677 CheckerContext &Ctx,
Craig Topper0dbb7832014-05-27 02:45:47 +00002678 ExplodedNode *Pred = nullptr) const;
Ted Kremenek70a87882009-11-25 22:17:44 +00002679};
2680} // end anonymous namespace
2681
Jordy Rose217eb902011-08-17 21:27:39 +00002682namespace {
David Blaikie903c2932015-08-13 22:50:09 +00002683class StopTrackingCallback final : public SymbolVisitor {
Ted Kremenek49b1e382012-01-26 21:29:00 +00002684 ProgramStateRef state;
Jordy Rose217eb902011-08-17 21:27:39 +00002685public:
Ted Kremenek49b1e382012-01-26 21:29:00 +00002686 StopTrackingCallback(ProgramStateRef st) : state(st) {}
2687 ProgramStateRef getState() const { return state; }
Jordy Rose217eb902011-08-17 21:27:39 +00002688
Craig Topperfb6b25b2014-03-15 04:29:04 +00002689 bool VisitSymbol(SymbolRef sym) override {
Jordy Rose217eb902011-08-17 21:27:39 +00002690 state = state->remove<RefBindings>(sym);
2691 return true;
2692 }
2693};
2694} // end anonymous namespace
2695
Jordy Rose75e680e2011-09-02 06:44:22 +00002696//===----------------------------------------------------------------------===//
2697// Handle statements that may have an effect on refcounts.
2698//===----------------------------------------------------------------------===//
Jordy Rose217eb902011-08-17 21:27:39 +00002699
Jordy Rose75e680e2011-09-02 06:44:22 +00002700void RetainCountChecker::checkPostStmt(const BlockExpr *BE,
2701 CheckerContext &C) const {
Jordy Rose217eb902011-08-17 21:27:39 +00002702
Jordy Rose75e680e2011-09-02 06:44:22 +00002703 // Scan the BlockDecRefExprs for any object the retain count checker
Ted Kremenekbd862712010-07-01 20:16:50 +00002704 // may be tracking.
John McCallc63de662011-02-02 13:00:07 +00002705 if (!BE->getBlockDecl()->hasCaptures())
Ted Kremenekf89dcda2009-11-26 02:38:19 +00002706 return;
Ted Kremenekbd862712010-07-01 20:16:50 +00002707
Ted Kremenek49b1e382012-01-26 21:29:00 +00002708 ProgramStateRef state = C.getState();
Ted Kremenekf89dcda2009-11-26 02:38:19 +00002709 const BlockDataRegion *R =
Ted Kremenek632e3b72012-01-06 22:09:28 +00002710 cast<BlockDataRegion>(state->getSVal(BE,
2711 C.getLocationContext()).getAsRegion());
Ted Kremenekbd862712010-07-01 20:16:50 +00002712
Ted Kremenekf89dcda2009-11-26 02:38:19 +00002713 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
2714 E = R->referenced_vars_end();
Ted Kremenekbd862712010-07-01 20:16:50 +00002715
Ted Kremenekf89dcda2009-11-26 02:38:19 +00002716 if (I == E)
2717 return;
Ted Kremenekbd862712010-07-01 20:16:50 +00002718
Ted Kremenek04af9f22009-12-07 22:05:27 +00002719 // FIXME: For now we invalidate the tracking of all symbols passed to blocks
2720 // via captured variables, even though captured variables result in a copy
2721 // and in implicit increment/decrement of a retain count.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002722 SmallVector<const MemRegion*, 10> Regions;
Anna Zaksc9abbe22011-10-26 21:06:44 +00002723 const LocationContext *LC = C.getLocationContext();
Ted Kremenek90af9092010-12-02 07:49:45 +00002724 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
Ted Kremenekbd862712010-07-01 20:16:50 +00002725
Ted Kremenek04af9f22009-12-07 22:05:27 +00002726 for ( ; I != E; ++I) {
Ted Kremenekbcf90532012-12-06 07:17:20 +00002727 const VarRegion *VR = I.getCapturedRegion();
Ted Kremenek04af9f22009-12-07 22:05:27 +00002728 if (VR->getSuperRegion() == R) {
2729 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2730 }
2731 Regions.push_back(VR);
2732 }
Ted Kremenekbd862712010-07-01 20:16:50 +00002733
Ted Kremenek04af9f22009-12-07 22:05:27 +00002734 state =
2735 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
2736 Regions.data() + Regions.size()).getState();
Anna Zaksda4c8d62011-10-26 21:06:34 +00002737 C.addTransition(state);
Ted Kremenekf89dcda2009-11-26 02:38:19 +00002738}
2739
Jordy Rose75e680e2011-09-02 06:44:22 +00002740void RetainCountChecker::checkPostStmt(const CastExpr *CE,
2741 CheckerContext &C) const {
John McCall31168b02011-06-15 23:02:42 +00002742 const ObjCBridgedCastExpr *BE = dyn_cast<ObjCBridgedCastExpr>(CE);
2743 if (!BE)
2744 return;
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002745
John McCall640767f2011-06-17 06:50:50 +00002746 ArgEffect AE = IncRef;
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002747
John McCall31168b02011-06-15 23:02:42 +00002748 switch (BE->getBridgeKind()) {
2749 case clang::OBC_Bridge:
2750 // Do nothing.
2751 return;
2752 case clang::OBC_BridgeRetained:
2753 AE = IncRef;
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002754 break;
John McCall31168b02011-06-15 23:02:42 +00002755 case clang::OBC_BridgeTransfer:
Benjamin Kramer1d5d6342013-10-20 11:53:20 +00002756 AE = DecRefBridgedTransferred;
John McCall31168b02011-06-15 23:02:42 +00002757 break;
2758 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002759
Ted Kremenek49b1e382012-01-26 21:29:00 +00002760 ProgramStateRef state = C.getState();
Ted Kremenek632e3b72012-01-06 22:09:28 +00002761 SymbolRef Sym = state->getSVal(CE, C.getLocationContext()).getAsLocSymbol();
John McCall31168b02011-06-15 23:02:42 +00002762 if (!Sym)
2763 return;
Anna Zaksf5788c72012-08-14 00:36:15 +00002764 const RefVal* T = getRefBinding(state, Sym);
John McCall31168b02011-06-15 23:02:42 +00002765 if (!T)
2766 return;
2767
John McCall31168b02011-06-15 23:02:42 +00002768 RefVal::Kind hasErr = (RefVal::Kind) 0;
Jordy Rosec49ec532011-09-02 05:55:19 +00002769 state = updateSymbol(state, Sym, *T, AE, hasErr, C);
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002770
John McCall31168b02011-06-15 23:02:42 +00002771 if (hasErr) {
Jordy Rosebf77e512011-08-23 20:27:16 +00002772 // FIXME: If we get an error during a bridge cast, should we report it?
John McCall31168b02011-06-15 23:02:42 +00002773 return;
2774 }
2775
Anna Zaksda4c8d62011-10-26 21:06:34 +00002776 C.addTransition(state);
John McCall31168b02011-06-15 23:02:42 +00002777}
2778
Ted Kremenek415287d2012-03-06 20:06:12 +00002779void RetainCountChecker::processObjCLiterals(CheckerContext &C,
2780 const Expr *Ex) const {
2781 ProgramStateRef state = C.getState();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002782 const ExplodedNode *pred = C.getPredecessor();
Benjamin Kramer973431b2015-07-03 15:12:24 +00002783 for (const Stmt *Child : Ex->children()) {
2784 SVal V = state->getSVal(Child, pred->getLocationContext());
Ted Kremenek415287d2012-03-06 20:06:12 +00002785 if (SymbolRef sym = V.getAsSymbol())
Anna Zaksf5788c72012-08-14 00:36:15 +00002786 if (const RefVal* T = getRefBinding(state, sym)) {
Ted Kremenek415287d2012-03-06 20:06:12 +00002787 RefVal::Kind hasErr = (RefVal::Kind) 0;
2788 state = updateSymbol(state, sym, *T, MayEscape, hasErr, C);
2789 if (hasErr) {
Benjamin Kramer973431b2015-07-03 15:12:24 +00002790 processNonLeakError(state, Child->getSourceRange(), hasErr, sym, C);
Ted Kremenek415287d2012-03-06 20:06:12 +00002791 return;
2792 }
2793 }
2794 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002795
Ted Kremenek415287d2012-03-06 20:06:12 +00002796 // Return the object as autoreleased.
2797 // RetEffect RE = RetEffect::MakeNotOwned(RetEffect::ObjC);
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002798 if (SymbolRef sym =
Ted Kremenek415287d2012-03-06 20:06:12 +00002799 state->getSVal(Ex, pred->getLocationContext()).getAsSymbol()) {
2800 QualType ResultTy = Ex->getType();
Anna Zaksf5788c72012-08-14 00:36:15 +00002801 state = setRefBinding(state, sym,
2802 RefVal::makeNotOwned(RetEffect::ObjC, ResultTy));
Ted Kremenek415287d2012-03-06 20:06:12 +00002803 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002804
2805 C.addTransition(state);
Ted Kremenek415287d2012-03-06 20:06:12 +00002806}
2807
2808void RetainCountChecker::checkPostStmt(const ObjCArrayLiteral *AL,
2809 CheckerContext &C) const {
2810 // Apply the 'MayEscape' to all values.
2811 processObjCLiterals(C, AL);
2812}
2813
2814void RetainCountChecker::checkPostStmt(const ObjCDictionaryLiteral *DL,
2815 CheckerContext &C) const {
2816 // Apply the 'MayEscape' to all keys and values.
2817 processObjCLiterals(C, DL);
2818}
2819
Jordy Rose6393f822012-05-12 05:10:43 +00002820void RetainCountChecker::checkPostStmt(const ObjCBoxedExpr *Ex,
2821 CheckerContext &C) const {
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002822 const ExplodedNode *Pred = C.getPredecessor();
Jordy Rose6393f822012-05-12 05:10:43 +00002823 const LocationContext *LCtx = Pred->getLocationContext();
2824 ProgramStateRef State = Pred->getState();
2825
2826 if (SymbolRef Sym = State->getSVal(Ex, LCtx).getAsSymbol()) {
2827 QualType ResultTy = Ex->getType();
Anna Zaksf5788c72012-08-14 00:36:15 +00002828 State = setRefBinding(State, Sym,
2829 RefVal::makeNotOwned(RetEffect::ObjC, ResultTy));
Jordy Rose6393f822012-05-12 05:10:43 +00002830 }
2831
2832 C.addTransition(State);
2833}
2834
Jordan Rosecb5386c2015-02-04 19:24:52 +00002835static bool wasLoadedFromIvar(SymbolRef Sym) {
2836 if (auto DerivedVal = dyn_cast<SymbolDerived>(Sym))
2837 return isa<ObjCIvarRegion>(DerivedVal->getRegion());
2838 if (auto RegionVal = dyn_cast<SymbolRegionValue>(Sym))
2839 return isa<ObjCIvarRegion>(RegionVal->getRegion());
2840 return false;
2841}
2842
Jordan Roseb3ad07e2014-03-25 17:10:58 +00002843void RetainCountChecker::checkPostStmt(const ObjCIvarRefExpr *IRE,
2844 CheckerContext &C) const {
Jordan Rosecb5386c2015-02-04 19:24:52 +00002845 Optional<Loc> IVarLoc = C.getSVal(IRE).getAs<Loc>();
2846 if (!IVarLoc)
2847 return;
2848
Jordan Roseb3ad07e2014-03-25 17:10:58 +00002849 ProgramStateRef State = C.getState();
Jordan Rosecb5386c2015-02-04 19:24:52 +00002850 SymbolRef Sym = State->getSVal(*IVarLoc).getAsSymbol();
Jordan Rose000bac52015-02-19 23:57:04 +00002851 if (!Sym || !wasLoadedFromIvar(Sym))
Jordan Rosecb5386c2015-02-04 19:24:52 +00002852 return;
2853
2854 // Accessing an ivar directly is unusual. If we've done that, be more
2855 // forgiving about what the surrounding code is allowed to do.
2856
2857 QualType Ty = Sym->getType();
2858 RetEffect::ObjKind Kind;
2859 if (Ty->isObjCRetainableType())
2860 Kind = RetEffect::ObjC;
2861 else if (coreFoundation::isCFObjectRef(Ty))
2862 Kind = RetEffect::CF;
2863 else
2864 return;
2865
Jordan Rose000bac52015-02-19 23:57:04 +00002866 // If the value is already known to be nil, don't bother tracking it.
2867 ConstraintManager &CMgr = State->getConstraintManager();
2868 if (CMgr.isNull(State, Sym).isConstrainedTrue())
Jordan Rosecb5386c2015-02-04 19:24:52 +00002869 return;
2870
2871 if (const RefVal *RV = getRefBinding(State, Sym)) {
2872 // If we've seen this symbol before, or we're only seeing it now because
2873 // of something the analyzer has synthesized, don't do anything.
2874 if (RV->getIvarAccessHistory() != RefVal::IvarAccessHistory::None ||
2875 isSynthesizedAccessor(C.getStackFrame())) {
2876 return;
2877 }
2878
Jordan Rosecb5386c2015-02-04 19:24:52 +00002879 // Note that this value has been loaded from an ivar.
2880 C.addTransition(setRefBinding(State, Sym, RV->withIvarAccess()));
2881 return;
2882 }
2883
2884 RefVal PlusZero = RefVal::makeNotOwned(Kind, Ty);
2885
2886 // In a synthesized accessor, the effective retain count is +0.
2887 if (isSynthesizedAccessor(C.getStackFrame())) {
2888 C.addTransition(setRefBinding(State, Sym, PlusZero));
2889 return;
2890 }
2891
Jordan Rose218772f2015-03-30 20:17:47 +00002892 State = setRefBinding(State, Sym, PlusZero.withIvarAccess());
Jordan Roseb3ad07e2014-03-25 17:10:58 +00002893 C.addTransition(State);
2894}
2895
Jordan Rose682b3162012-07-02 19:28:21 +00002896void RetainCountChecker::checkPostCall(const CallEvent &Call,
2897 CheckerContext &C) const {
Jordan Rose682b3162012-07-02 19:28:21 +00002898 RetainSummaryManager &Summaries = getSummaryManager(C);
2899 const RetainSummary *Summ = Summaries.getSummary(Call, C.getState());
Anna Zaks25612732012-08-29 23:23:43 +00002900
2901 if (C.wasInlined) {
2902 processSummaryOfInlined(*Summ, Call, C);
2903 return;
2904 }
Jordan Rose682b3162012-07-02 19:28:21 +00002905 checkSummary(*Summ, Call, C);
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002906}
2907
Jordy Rose75e680e2011-09-02 06:44:22 +00002908/// GetReturnType - Used to get the return type of a message expression or
2909/// function call with the intention of affixing that type to a tracked symbol.
Sylvestre Ledru830885c2012-07-23 08:59:39 +00002910/// While the return type can be queried directly from RetEx, when
Jordy Rose75e680e2011-09-02 06:44:22 +00002911/// invoking class methods we augment to the return type to be that of
2912/// a pointer to the class (as opposed it just being id).
2913// FIXME: We may be able to do this with related result types instead.
2914// This function is probably overestimating.
2915static QualType GetReturnType(const Expr *RetE, ASTContext &Ctx) {
2916 QualType RetTy = RetE->getType();
2917 // If RetE is not a message expression just return its type.
2918 // If RetE is a message expression, return its types if it is something
2919 /// more specific than id.
2920 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RetE))
2921 if (const ObjCObjectPointerType *PT = RetTy->getAs<ObjCObjectPointerType>())
2922 if (PT->isObjCQualifiedIdType() || PT->isObjCIdType() ||
2923 PT->isObjCClassType()) {
2924 // At this point we know the return type of the message expression is
2925 // id, id<...>, or Class. If we have an ObjCInterfaceDecl, we know this
2926 // is a call to a class method whose type we can resolve. In such
2927 // cases, promote the return type to XXX* (where XXX is the class).
2928 const ObjCInterfaceDecl *D = ME->getReceiverInterface();
2929 return !D ? RetTy :
2930 Ctx.getObjCObjectPointerType(Ctx.getObjCInterfaceType(D));
2931 }
2932
2933 return RetTy;
2934}
2935
Anna Zaks25612732012-08-29 23:23:43 +00002936// We don't always get the exact modeling of the function with regards to the
2937// retain count checker even when the function is inlined. For example, we need
2938// to stop tracking the symbols which were marked with StopTrackingHard.
2939void RetainCountChecker::processSummaryOfInlined(const RetainSummary &Summ,
2940 const CallEvent &CallOrMsg,
2941 CheckerContext &C) const {
2942 ProgramStateRef state = C.getState();
2943
2944 // Evaluate the effect of the arguments.
2945 for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
2946 if (Summ.getArg(idx) == StopTrackingHard) {
2947 SVal V = CallOrMsg.getArgSVal(idx);
2948 if (SymbolRef Sym = V.getAsLocSymbol()) {
2949 state = removeRefBinding(state, Sym);
2950 }
2951 }
2952 }
2953
2954 // Evaluate the effect on the message receiver.
2955 const ObjCMethodCall *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg);
2956 if (MsgInvocation) {
2957 if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
2958 if (Summ.getReceiverEffect() == StopTrackingHard) {
2959 state = removeRefBinding(state, Sym);
2960 }
2961 }
2962 }
2963
2964 // Consult the summary for the return value.
2965 RetEffect RE = Summ.getRetEffect();
2966 if (RE.getKind() == RetEffect::NoRetHard) {
Jordan Rose829c3832012-11-02 23:49:29 +00002967 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
Anna Zaks25612732012-08-29 23:23:43 +00002968 if (Sym)
2969 state = removeRefBinding(state, Sym);
2970 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002971
Anna Zaks25612732012-08-29 23:23:43 +00002972 C.addTransition(state);
2973}
2974
Douglas Gregoreb6e64c2015-06-19 23:17:46 +00002975static ProgramStateRef updateOutParameter(ProgramStateRef State,
2976 SVal ArgVal,
2977 ArgEffect Effect) {
2978 auto *ArgRegion = dyn_cast_or_null<TypedValueRegion>(ArgVal.getAsRegion());
2979 if (!ArgRegion)
2980 return State;
2981
2982 QualType PointeeTy = ArgRegion->getValueType();
2983 if (!coreFoundation::isCFObjectRef(PointeeTy))
2984 return State;
2985
2986 SVal PointeeVal = State->getSVal(ArgRegion);
2987 SymbolRef Pointee = PointeeVal.getAsLocSymbol();
2988 if (!Pointee)
2989 return State;
2990
2991 switch (Effect) {
2992 case UnretainedOutParameter:
2993 State = setRefBinding(State, Pointee,
2994 RefVal::makeNotOwned(RetEffect::CF, PointeeTy));
2995 break;
2996 case RetainedOutParameter:
2997 // Do nothing. Retained out parameters will either point to a +1 reference
2998 // or NULL, but the way you check for failure differs depending on the API.
2999 // Consequently, we don't have a good way to track them yet.
3000 break;
3001
3002 default:
3003 llvm_unreachable("only for out parameters");
3004 }
3005
3006 return State;
3007}
3008
Jordy Rose75e680e2011-09-02 06:44:22 +00003009void RetainCountChecker::checkSummary(const RetainSummary &Summ,
Jordan Roseeec15392012-07-02 19:27:43 +00003010 const CallEvent &CallOrMsg,
Jordy Rose75e680e2011-09-02 06:44:22 +00003011 CheckerContext &C) const {
Ted Kremenek49b1e382012-01-26 21:29:00 +00003012 ProgramStateRef state = C.getState();
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003013
3014 // Evaluate the effect of the arguments.
3015 RefVal::Kind hasErr = (RefVal::Kind) 0;
3016 SourceRange ErrorRange;
Craig Topper0dbb7832014-05-27 02:45:47 +00003017 SymbolRef ErrorSym = nullptr;
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003018
3019 for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
Jordy Rose1fad6632011-08-27 22:51:26 +00003020 SVal V = CallOrMsg.getArgSVal(idx);
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003021
Douglas Gregoreb6e64c2015-06-19 23:17:46 +00003022 ArgEffect Effect = Summ.getArg(idx);
3023 if (Effect == RetainedOutParameter || Effect == UnretainedOutParameter) {
3024 state = updateOutParameter(state, V, Effect);
3025 } else if (SymbolRef Sym = V.getAsLocSymbol()) {
Anna Zaksf5788c72012-08-14 00:36:15 +00003026 if (const RefVal *T = getRefBinding(state, Sym)) {
Douglas Gregoreb6e64c2015-06-19 23:17:46 +00003027 state = updateSymbol(state, Sym, *T, Effect, hasErr, C);
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003028 if (hasErr) {
3029 ErrorRange = CallOrMsg.getArgSourceRange(idx);
3030 ErrorSym = Sym;
3031 break;
3032 }
3033 }
3034 }
3035 }
3036
3037 // Evaluate the effect on the message receiver.
3038 bool ReceiverIsTracked = false;
Jordan Roseeec15392012-07-02 19:27:43 +00003039 if (!hasErr) {
Jordan Rose6bad4902012-07-02 19:27:56 +00003040 const ObjCMethodCall *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg);
Jordan Roseeec15392012-07-02 19:27:43 +00003041 if (MsgInvocation) {
3042 if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
Anna Zaksf5788c72012-08-14 00:36:15 +00003043 if (const RefVal *T = getRefBinding(state, Sym)) {
Jordan Roseeec15392012-07-02 19:27:43 +00003044 ReceiverIsTracked = true;
3045 state = updateSymbol(state, Sym, *T, Summ.getReceiverEffect(),
Anna Zaks25612732012-08-29 23:23:43 +00003046 hasErr, C);
Jordan Roseeec15392012-07-02 19:27:43 +00003047 if (hasErr) {
Jordan Rose627b0462012-07-18 21:59:51 +00003048 ErrorRange = MsgInvocation->getOriginExpr()->getReceiverRange();
Jordan Roseeec15392012-07-02 19:27:43 +00003049 ErrorSym = Sym;
3050 }
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003051 }
3052 }
3053 }
3054 }
3055
3056 // Process any errors.
3057 if (hasErr) {
3058 processNonLeakError(state, ErrorRange, hasErr, ErrorSym, C);
3059 return;
3060 }
3061
3062 // Consult the summary for the return value.
3063 RetEffect RE = Summ.getRetEffect();
3064
3065 if (RE.getKind() == RetEffect::OwnedWhenTrackedReceiver) {
Jordy Rose8b289a22011-08-25 00:10:37 +00003066 if (ReceiverIsTracked)
Ted Kremenek3a0678e2015-09-08 03:50:52 +00003067 RE = getSummaryManager(C).getObjAllocRetEffect();
Jordy Rose8b289a22011-08-25 00:10:37 +00003068 else
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003069 RE = RetEffect::MakeNoRet();
3070 }
3071
3072 switch (RE.getKind()) {
3073 default:
David Blaikie8a40f702012-01-17 06:56:22 +00003074 llvm_unreachable("Unhandled RetEffect.");
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003075
3076 case RetEffect::NoRet:
Anna Zaks25612732012-08-29 23:23:43 +00003077 case RetEffect::NoRetHard:
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003078 // No work necessary.
3079 break;
3080
3081 case RetEffect::OwnedAllocatedSymbol:
3082 case RetEffect::OwnedSymbol: {
Jordan Rose829c3832012-11-02 23:49:29 +00003083 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003084 if (!Sym)
3085 break;
3086
Jordan Roseeec15392012-07-02 19:27:43 +00003087 // Use the result type from the CallEvent as it automatically adjusts
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003088 // for methods/functions that return references.
Jordan Roseeec15392012-07-02 19:27:43 +00003089 QualType ResultTy = CallOrMsg.getResultType();
Anna Zaksf5788c72012-08-14 00:36:15 +00003090 state = setRefBinding(state, Sym, RefVal::makeOwned(RE.getObjKind(),
3091 ResultTy));
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003092
3093 // FIXME: Add a flag to the checker where allocations are assumed to
Anna Zaks21487f72012-08-14 15:39:13 +00003094 // *not* fail.
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003095 break;
3096 }
3097
3098 case RetEffect::GCNotOwnedSymbol:
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003099 case RetEffect::NotOwnedSymbol: {
3100 const Expr *Ex = CallOrMsg.getOriginExpr();
Jordan Rose829c3832012-11-02 23:49:29 +00003101 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003102 if (!Sym)
3103 break;
Ted Kremenekbe400842012-10-12 22:56:45 +00003104 assert(Ex);
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003105 // Use GetReturnType in order to give [NSFoo alloc] the type NSFoo *.
3106 QualType ResultTy = GetReturnType(Ex, C.getASTContext());
Anna Zaksf5788c72012-08-14 00:36:15 +00003107 state = setRefBinding(state, Sym, RefVal::makeNotOwned(RE.getObjKind(),
3108 ResultTy));
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003109 break;
3110 }
3111 }
3112
3113 // This check is actually necessary; otherwise the statement builder thinks
3114 // we've hit a previously-found path.
3115 // Normally addTransition takes care of this, but we want the node pointer.
3116 ExplodedNode *NewNode;
3117 if (state == C.getState()) {
3118 NewNode = C.getPredecessor();
3119 } else {
Anna Zaksda4c8d62011-10-26 21:06:34 +00003120 NewNode = C.addTransition(state);
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003121 }
3122
Jordy Rose5df640d2011-08-24 18:56:32 +00003123 // Annotate the node with summary we used.
3124 if (NewNode) {
3125 // FIXME: This is ugly. See checkEndAnalysis for why it's necessary.
3126 if (ShouldResetSummaryLog) {
3127 SummaryLog.clear();
3128 ShouldResetSummaryLog = false;
3129 }
Jordy Rose20d4e682011-08-23 20:55:48 +00003130 SummaryLog[NewNode] = &Summ;
Jordy Rose5df640d2011-08-24 18:56:32 +00003131 }
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003132}
3133
Ted Kremenek3a0678e2015-09-08 03:50:52 +00003134ProgramStateRef
Ted Kremenek49b1e382012-01-26 21:29:00 +00003135RetainCountChecker::updateSymbol(ProgramStateRef state, SymbolRef sym,
Jordy Rose75e680e2011-09-02 06:44:22 +00003136 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
3137 CheckerContext &C) const {
Jordy Rosebf77e512011-08-23 20:27:16 +00003138 // In GC mode [... release] and [... retain] do nothing.
Jordy Rose75e680e2011-09-02 06:44:22 +00003139 // In ARC mode they shouldn't exist at all, but we just ignore them.
Jordy Rosec49ec532011-09-02 05:55:19 +00003140 bool IgnoreRetainMsg = C.isObjCGCEnabled();
3141 if (!IgnoreRetainMsg)
David Blaikiebbafb8a2012-03-11 07:00:24 +00003142 IgnoreRetainMsg = (bool)C.getASTContext().getLangOpts().ObjCAutoRefCount;
Jordy Rosec49ec532011-09-02 05:55:19 +00003143
Jordy Rosebf77e512011-08-23 20:27:16 +00003144 switch (E) {
Jordan Roseeec15392012-07-02 19:27:43 +00003145 default:
3146 break;
3147 case IncRefMsg:
3148 E = IgnoreRetainMsg ? DoNothing : IncRef;
3149 break;
3150 case DecRefMsg:
3151 E = IgnoreRetainMsg ? DoNothing : DecRef;
3152 break;
Anna Zaks25612732012-08-29 23:23:43 +00003153 case DecRefMsgAndStopTrackingHard:
3154 E = IgnoreRetainMsg ? StopTracking : DecRefAndStopTrackingHard;
Jordan Roseeec15392012-07-02 19:27:43 +00003155 break;
3156 case MakeCollectable:
3157 E = C.isObjCGCEnabled() ? DecRef : DoNothing;
3158 break;
Jordy Rosebf77e512011-08-23 20:27:16 +00003159 }
3160
3161 // Handle all use-after-releases.
Jordy Rosec49ec532011-09-02 05:55:19 +00003162 if (!C.isObjCGCEnabled() && V.getKind() == RefVal::Released) {
Jordy Rosebf77e512011-08-23 20:27:16 +00003163 V = V ^ RefVal::ErrorUseAfterRelease;
3164 hasErr = V.getKind();
Anna Zaksf5788c72012-08-14 00:36:15 +00003165 return setRefBinding(state, sym, V);
Jordy Rosebf77e512011-08-23 20:27:16 +00003166 }
3167
3168 switch (E) {
3169 case DecRefMsg:
3170 case IncRefMsg:
3171 case MakeCollectable:
Anna Zaks25612732012-08-29 23:23:43 +00003172 case DecRefMsgAndStopTrackingHard:
Jordy Rosebf77e512011-08-23 20:27:16 +00003173 llvm_unreachable("DecRefMsg/IncRefMsg/MakeCollectable already converted");
Jordy Rosebf77e512011-08-23 20:27:16 +00003174
Douglas Gregoreb6e64c2015-06-19 23:17:46 +00003175 case UnretainedOutParameter:
3176 case RetainedOutParameter:
3177 llvm_unreachable("Applies to pointer-to-pointer parameters, which should "
3178 "not have ref state.");
3179
Jordy Rosebf77e512011-08-23 20:27:16 +00003180 case Dealloc:
3181 // Any use of -dealloc in GC is *bad*.
Jordy Rosec49ec532011-09-02 05:55:19 +00003182 if (C.isObjCGCEnabled()) {
Jordy Rosebf77e512011-08-23 20:27:16 +00003183 V = V ^ RefVal::ErrorDeallocGC;
3184 hasErr = V.getKind();
3185 break;
3186 }
3187
3188 switch (V.getKind()) {
3189 default:
3190 llvm_unreachable("Invalid RefVal state for an explicit dealloc.");
Jordy Rosebf77e512011-08-23 20:27:16 +00003191 case RefVal::Owned:
3192 // The object immediately transitions to the released state.
3193 V = V ^ RefVal::Released;
3194 V.clearCounts();
Anna Zaksf5788c72012-08-14 00:36:15 +00003195 return setRefBinding(state, sym, V);
Jordy Rosebf77e512011-08-23 20:27:16 +00003196 case RefVal::NotOwned:
3197 V = V ^ RefVal::ErrorDeallocNotOwned;
3198 hasErr = V.getKind();
3199 break;
3200 }
3201 break;
3202
Jordy Rosebf77e512011-08-23 20:27:16 +00003203 case MayEscape:
3204 if (V.getKind() == RefVal::Owned) {
3205 V = V ^ RefVal::NotOwned;
3206 break;
3207 }
3208
3209 // Fall-through.
3210
Jordy Rosebf77e512011-08-23 20:27:16 +00003211 case DoNothing:
3212 return state;
3213
3214 case Autorelease:
Jordy Rosec49ec532011-09-02 05:55:19 +00003215 if (C.isObjCGCEnabled())
Jordy Rosebf77e512011-08-23 20:27:16 +00003216 return state;
Jordy Rosebf77e512011-08-23 20:27:16 +00003217 // Update the autorelease counts.
Jordy Rosebf77e512011-08-23 20:27:16 +00003218 V = V.autorelease();
3219 break;
3220
3221 case StopTracking:
Anna Zaks25612732012-08-29 23:23:43 +00003222 case StopTrackingHard:
Anna Zaksf5788c72012-08-14 00:36:15 +00003223 return removeRefBinding(state, sym);
Jordy Rosebf77e512011-08-23 20:27:16 +00003224
3225 case IncRef:
3226 switch (V.getKind()) {
3227 default:
3228 llvm_unreachable("Invalid RefVal state for a retain.");
Jordy Rosebf77e512011-08-23 20:27:16 +00003229 case RefVal::Owned:
3230 case RefVal::NotOwned:
3231 V = V + 1;
3232 break;
3233 case RefVal::Released:
3234 // Non-GC cases are handled above.
Jordy Rosec49ec532011-09-02 05:55:19 +00003235 assert(C.isObjCGCEnabled());
Jordy Rosebf77e512011-08-23 20:27:16 +00003236 V = (V ^ RefVal::Owned) + 1;
3237 break;
3238 }
3239 break;
3240
Jordy Rosebf77e512011-08-23 20:27:16 +00003241 case DecRef:
Benjamin Kramer1d5d6342013-10-20 11:53:20 +00003242 case DecRefBridgedTransferred:
Anna Zaks25612732012-08-29 23:23:43 +00003243 case DecRefAndStopTrackingHard:
Jordy Rosebf77e512011-08-23 20:27:16 +00003244 switch (V.getKind()) {
3245 default:
3246 // case 'RefVal::Released' handled above.
3247 llvm_unreachable("Invalid RefVal state for a release.");
Jordy Rosebf77e512011-08-23 20:27:16 +00003248
3249 case RefVal::Owned:
3250 assert(V.getCount() > 0);
Jordan Rosecb5386c2015-02-04 19:24:52 +00003251 if (V.getCount() == 1) {
3252 if (E == DecRefBridgedTransferred ||
3253 V.getIvarAccessHistory() ==
3254 RefVal::IvarAccessHistory::AccessedDirectly)
3255 V = V ^ RefVal::NotOwned;
3256 else
3257 V = V ^ RefVal::Released;
3258 } else if (E == DecRefAndStopTrackingHard) {
Anna Zaksf5788c72012-08-14 00:36:15 +00003259 return removeRefBinding(state, sym);
Jordan Rosecb5386c2015-02-04 19:24:52 +00003260 }
Jordan Roseeec15392012-07-02 19:27:43 +00003261
Jordy Rosebf77e512011-08-23 20:27:16 +00003262 V = V - 1;
3263 break;
3264
3265 case RefVal::NotOwned:
Jordan Roseeec15392012-07-02 19:27:43 +00003266 if (V.getCount() > 0) {
Anna Zaks25612732012-08-29 23:23:43 +00003267 if (E == DecRefAndStopTrackingHard)
Anna Zaksf5788c72012-08-14 00:36:15 +00003268 return removeRefBinding(state, sym);
Jordy Rosebf77e512011-08-23 20:27:16 +00003269 V = V - 1;
Jordan Rosecb5386c2015-02-04 19:24:52 +00003270 } else if (V.getIvarAccessHistory() ==
3271 RefVal::IvarAccessHistory::AccessedDirectly) {
3272 // Assume that the instance variable was holding on the object at
3273 // +1, and we just didn't know.
3274 if (E == DecRefAndStopTrackingHard)
3275 return removeRefBinding(state, sym);
3276 V = V.releaseViaIvar() ^ RefVal::Released;
Jordan Roseeec15392012-07-02 19:27:43 +00003277 } else {
Jordy Rosebf77e512011-08-23 20:27:16 +00003278 V = V ^ RefVal::ErrorReleaseNotOwned;
3279 hasErr = V.getKind();
3280 }
3281 break;
3282
3283 case RefVal::Released:
3284 // Non-GC cases are handled above.
Jordy Rosec49ec532011-09-02 05:55:19 +00003285 assert(C.isObjCGCEnabled());
Jordy Rosebf77e512011-08-23 20:27:16 +00003286 V = V ^ RefVal::ErrorUseAfterRelease;
3287 hasErr = V.getKind();
3288 break;
3289 }
3290 break;
3291 }
Anna Zaksf5788c72012-08-14 00:36:15 +00003292 return setRefBinding(state, sym, V);
Jordy Rosebf77e512011-08-23 20:27:16 +00003293}
3294
Ted Kremenek49b1e382012-01-26 21:29:00 +00003295void RetainCountChecker::processNonLeakError(ProgramStateRef St,
Jordy Rose75e680e2011-09-02 06:44:22 +00003296 SourceRange ErrorRange,
3297 RefVal::Kind ErrorKind,
3298 SymbolRef Sym,
3299 CheckerContext &C) const {
Jordan Rose3da3f8e2015-03-30 20:18:00 +00003300 // HACK: Ignore retain-count issues on values accessed through ivars,
3301 // because of cases like this:
3302 // [_contentView retain];
3303 // [_contentView removeFromSuperview];
3304 // [self addSubview:_contentView]; // invalidates 'self'
3305 // [_contentView release];
3306 if (const RefVal *RV = getRefBinding(St, Sym))
3307 if (RV->getIvarAccessHistory() != RefVal::IvarAccessHistory::None)
3308 return;
3309
Devin Coughline39bd402015-09-16 22:03:05 +00003310 ExplodedNode *N = C.generateErrorNode(St);
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003311 if (!N)
3312 return;
3313
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003314 CFRefBug *BT;
3315 switch (ErrorKind) {
3316 default:
3317 llvm_unreachable("Unhandled error.");
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003318 case RefVal::ErrorUseAfterRelease:
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003319 if (!useAfterRelease)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00003320 useAfterRelease.reset(new UseAfterRelease(this));
Aaron Ballmanff661392015-06-22 13:28:21 +00003321 BT = useAfterRelease.get();
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003322 break;
3323 case RefVal::ErrorReleaseNotOwned:
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003324 if (!releaseNotOwned)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00003325 releaseNotOwned.reset(new BadRelease(this));
Aaron Ballmanff661392015-06-22 13:28:21 +00003326 BT = releaseNotOwned.get();
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003327 break;
3328 case RefVal::ErrorDeallocGC:
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003329 if (!deallocGC)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00003330 deallocGC.reset(new DeallocGC(this));
Aaron Ballmanff661392015-06-22 13:28:21 +00003331 BT = deallocGC.get();
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003332 break;
3333 case RefVal::ErrorDeallocNotOwned:
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003334 if (!deallocNotOwned)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00003335 deallocNotOwned.reset(new DeallocNotOwned(this));
Aaron Ballmanff661392015-06-22 13:28:21 +00003336 BT = deallocNotOwned.get();
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003337 break;
3338 }
3339
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003340 assert(BT);
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00003341 auto report = std::unique_ptr<BugReport>(
3342 new CFRefReport(*BT, C.getASTContext().getLangOpts(), C.isObjCGCEnabled(),
3343 SummaryLog, N, Sym));
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003344 report->addRange(ErrorRange);
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00003345 C.emitReport(std::move(report));
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003346}
3347
Jordy Rose75e680e2011-09-02 06:44:22 +00003348//===----------------------------------------------------------------------===//
3349// Handle the return values of retain-count-related functions.
3350//===----------------------------------------------------------------------===//
3351
3352bool RetainCountChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
Jordy Rose898a1482011-08-21 21:58:18 +00003353 // Get the callee. We're only interested in simple C functions.
Ted Kremenek49b1e382012-01-26 21:29:00 +00003354 ProgramStateRef state = C.getState();
Anna Zaksc6aa5312011-12-01 05:57:37 +00003355 const FunctionDecl *FD = C.getCalleeDecl(CE);
Jordy Rose898a1482011-08-21 21:58:18 +00003356 if (!FD)
3357 return false;
3358
3359 IdentifierInfo *II = FD->getIdentifier();
3360 if (!II)
3361 return false;
3362
3363 // For now, we're only handling the functions that return aliases of their
3364 // arguments: CFRetain and CFMakeCollectable (and their families).
3365 // Eventually we should add other functions we can model entirely,
3366 // such as CFRelease, which don't invalidate their arguments or globals.
3367 if (CE->getNumArgs() != 1)
3368 return false;
3369
3370 // Get the name of the function.
3371 StringRef FName = II->getName();
3372 FName = FName.substr(FName.find_first_not_of('_'));
3373
3374 // See if it's one of the specific functions we know how to eval.
3375 bool canEval = false;
3376
David Majnemerced8bdf2015-02-25 17:36:15 +00003377 QualType ResultTy = CE->getCallReturnType(C.getASTContext());
Jordy Rose898a1482011-08-21 21:58:18 +00003378 if (ResultTy->isObjCIdType()) {
3379 // Handle: id NSMakeCollectable(CFTypeRef)
3380 canEval = II->isStr("NSMakeCollectable");
3381 } else if (ResultTy->isPointerType()) {
3382 // Handle: (CF|CG)Retain
Jordan Rose77411322013-10-07 17:16:52 +00003383 // CFAutorelease
Jordy Rose898a1482011-08-21 21:58:18 +00003384 // CFMakeCollectable
3385 // It's okay to be a little sloppy here (CGMakeCollectable doesn't exist).
3386 if (cocoa::isRefType(ResultTy, "CF", FName) ||
3387 cocoa::isRefType(ResultTy, "CG", FName)) {
Jordan Rose77411322013-10-07 17:16:52 +00003388 canEval = isRetain(FD, FName) || isAutorelease(FD, FName) ||
3389 isMakeCollectable(FD, FName);
Jordy Rose898a1482011-08-21 21:58:18 +00003390 }
3391 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +00003392
Jordy Rose898a1482011-08-21 21:58:18 +00003393 if (!canEval)
3394 return false;
3395
3396 // Bind the return value.
Ted Kremenek632e3b72012-01-06 22:09:28 +00003397 const LocationContext *LCtx = C.getLocationContext();
3398 SVal RetVal = state->getSVal(CE->getArg(0), LCtx);
Jordy Rose898a1482011-08-21 21:58:18 +00003399 if (RetVal.isUnknown()) {
3400 // If the receiver is unknown, conjure a return value.
3401 SValBuilder &SVB = C.getSValBuilder();
Craig Topper0dbb7832014-05-27 02:45:47 +00003402 RetVal = SVB.conjureSymbolVal(nullptr, CE, LCtx, ResultTy, C.blockCount());
Jordy Rose898a1482011-08-21 21:58:18 +00003403 }
Ted Kremenek632e3b72012-01-06 22:09:28 +00003404 state = state->BindExpr(CE, LCtx, RetVal, false);
Jordy Rose898a1482011-08-21 21:58:18 +00003405
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003406 // FIXME: This should not be necessary, but otherwise the argument seems to be
3407 // considered alive during the next statement.
3408 if (const MemRegion *ArgRegion = RetVal.getAsRegion()) {
3409 // Save the refcount status of the argument.
3410 SymbolRef Sym = RetVal.getAsLocSymbol();
Craig Topper0dbb7832014-05-27 02:45:47 +00003411 const RefVal *Binding = nullptr;
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003412 if (Sym)
Anna Zaksf5788c72012-08-14 00:36:15 +00003413 Binding = getRefBinding(state, Sym);
Jordy Rose898a1482011-08-21 21:58:18 +00003414
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003415 // Invalidate the argument region.
Anna Zaksdc154152012-12-20 00:38:25 +00003416 state = state->invalidateRegions(ArgRegion, CE, C.blockCount(), LCtx,
Anna Zaks0c34c1a2013-01-16 01:35:54 +00003417 /*CausesPointerEscape*/ false);
Jordy Rose898a1482011-08-21 21:58:18 +00003418
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003419 // Restore the refcount status of the argument.
3420 if (Binding)
Anna Zaksf5788c72012-08-14 00:36:15 +00003421 state = setRefBinding(state, Sym, *Binding);
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003422 }
3423
Anna Zaksda4c8d62011-10-26 21:06:34 +00003424 C.addTransition(state);
Jordy Rose898a1482011-08-21 21:58:18 +00003425 return true;
3426}
3427
Jordy Rose75e680e2011-09-02 06:44:22 +00003428//===----------------------------------------------------------------------===//
3429// Handle return statements.
3430//===----------------------------------------------------------------------===//
Jordy Rose298cc4d2011-08-23 19:43:16 +00003431
Jordy Rose75e680e2011-09-02 06:44:22 +00003432void RetainCountChecker::checkPreStmt(const ReturnStmt *S,
3433 CheckerContext &C) const {
Ted Kremenekef31f372012-02-25 02:09:09 +00003434
3435 // Only adjust the reference count if this is the top-level call frame,
3436 // and not the result of inlining. In the future, we should do
3437 // better checking even for inlined calls, and see if they match
3438 // with their expected semantics (e.g., the method should return a retained
3439 // object, etc.).
Anna Zaks44dc91b2012-11-03 02:54:16 +00003440 if (!C.inTopFrame())
Ted Kremenekef31f372012-02-25 02:09:09 +00003441 return;
3442
Jordy Rose298cc4d2011-08-23 19:43:16 +00003443 const Expr *RetE = S->getRetValue();
3444 if (!RetE)
3445 return;
3446
Ted Kremenek49b1e382012-01-26 21:29:00 +00003447 ProgramStateRef state = C.getState();
Ted Kremenek632e3b72012-01-06 22:09:28 +00003448 SymbolRef Sym =
3449 state->getSValAsScalarOrLoc(RetE, C.getLocationContext()).getAsLocSymbol();
Jordy Rose298cc4d2011-08-23 19:43:16 +00003450 if (!Sym)
3451 return;
3452
3453 // Get the reference count binding (if any).
Anna Zaksf5788c72012-08-14 00:36:15 +00003454 const RefVal *T = getRefBinding(state, Sym);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003455 if (!T)
3456 return;
3457
3458 // Change the reference count.
3459 RefVal X = *T;
3460
3461 switch (X.getKind()) {
3462 case RefVal::Owned: {
3463 unsigned cnt = X.getCount();
3464 assert(cnt > 0);
3465 X.setCount(cnt - 1);
3466 X = X ^ RefVal::ReturnedOwned;
3467 break;
3468 }
3469
3470 case RefVal::NotOwned: {
3471 unsigned cnt = X.getCount();
3472 if (cnt) {
3473 X.setCount(cnt - 1);
3474 X = X ^ RefVal::ReturnedOwned;
3475 }
3476 else {
3477 X = X ^ RefVal::ReturnedNotOwned;
3478 }
3479 break;
3480 }
3481
3482 default:
3483 return;
3484 }
3485
3486 // Update the binding.
Anna Zaksf5788c72012-08-14 00:36:15 +00003487 state = setRefBinding(state, Sym, X);
Anna Zaksda4c8d62011-10-26 21:06:34 +00003488 ExplodedNode *Pred = C.addTransition(state);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003489
3490 // At this point we have updated the state properly.
3491 // Everything after this is merely checking to see if the return value has
3492 // been over- or under-retained.
3493
3494 // Did we cache out?
3495 if (!Pred)
3496 return;
3497
Jordy Rose298cc4d2011-08-23 19:43:16 +00003498 // Update the autorelease counts.
Anton Yartsev6a619222014-02-17 18:25:34 +00003499 static CheckerProgramPointTag AutoreleaseTag(this, "Autorelease");
Jordan Roseff03c1d2012-12-06 18:58:18 +00003500 state = handleAutoreleaseCounts(state, Pred, &AutoreleaseTag, C, Sym, X);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003501
3502 // Did we cache out?
Jordan Roseff03c1d2012-12-06 18:58:18 +00003503 if (!state)
Jordy Rose298cc4d2011-08-23 19:43:16 +00003504 return;
3505
3506 // Get the updated binding.
Anna Zaksf5788c72012-08-14 00:36:15 +00003507 T = getRefBinding(state, Sym);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003508 assert(T);
3509 X = *T;
3510
3511 // Consult the summary of the enclosing method.
Jordy Rosec49ec532011-09-02 05:55:19 +00003512 RetainSummaryManager &Summaries = getSummaryManager(C);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003513 const Decl *CD = &Pred->getCodeDecl();
Jordan Roseeec15392012-07-02 19:27:43 +00003514 RetEffect RE = RetEffect::MakeNoRet();
Jordy Rose298cc4d2011-08-23 19:43:16 +00003515
Jordan Roseeec15392012-07-02 19:27:43 +00003516 // FIXME: What is the convention for blocks? Is there one?
Jordy Rose298cc4d2011-08-23 19:43:16 +00003517 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CD)) {
Jordy Rose8b289a22011-08-25 00:10:37 +00003518 const RetainSummary *Summ = Summaries.getMethodSummary(MD);
Jordan Roseeec15392012-07-02 19:27:43 +00003519 RE = Summ->getRetEffect();
3520 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) {
3521 if (!isa<CXXMethodDecl>(FD)) {
3522 const RetainSummary *Summ = Summaries.getFunctionSummary(FD);
3523 RE = Summ->getRetEffect();
3524 }
Jordy Rose298cc4d2011-08-23 19:43:16 +00003525 }
3526
Jordan Roseeec15392012-07-02 19:27:43 +00003527 checkReturnWithRetEffect(S, C, Pred, RE, X, Sym, state);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003528}
3529
Jordy Rose75e680e2011-09-02 06:44:22 +00003530void RetainCountChecker::checkReturnWithRetEffect(const ReturnStmt *S,
3531 CheckerContext &C,
3532 ExplodedNode *Pred,
3533 RetEffect RE, RefVal X,
3534 SymbolRef Sym,
Hans Wennborgdcfba332015-10-06 23:40:43 +00003535 ProgramStateRef state) const {
Jordan Rose3da3f8e2015-03-30 20:18:00 +00003536 // HACK: Ignore retain-count issues on values accessed through ivars,
3537 // because of cases like this:
3538 // [_contentView retain];
3539 // [_contentView removeFromSuperview];
3540 // [self addSubview:_contentView]; // invalidates 'self'
3541 // [_contentView release];
3542 if (X.getIvarAccessHistory() != RefVal::IvarAccessHistory::None)
3543 return;
3544
Jordy Rose298cc4d2011-08-23 19:43:16 +00003545 // Any leaks or other errors?
3546 if (X.isReturnedOwned() && X.getCount() == 0) {
3547 if (RE.getKind() != RetEffect::NoRet) {
3548 bool hasError = false;
Jordy Rosec49ec532011-09-02 05:55:19 +00003549 if (C.isObjCGCEnabled() && RE.getObjKind() == RetEffect::ObjC) {
Jordy Rose298cc4d2011-08-23 19:43:16 +00003550 // Things are more complicated with garbage collection. If the
3551 // returned object is suppose to be an Objective-C object, we have
3552 // a leak (as the caller expects a GC'ed object) because no
3553 // method should return ownership unless it returns a CF object.
3554 hasError = true;
3555 X = X ^ RefVal::ErrorGCLeakReturned;
3556 }
3557 else if (!RE.isOwned()) {
3558 // Either we are using GC and the returned object is a CF type
3559 // or we aren't using GC. In either case, we expect that the
3560 // enclosing method is expected to return ownership.
3561 hasError = true;
3562 X = X ^ RefVal::ErrorLeakReturned;
3563 }
3564
3565 if (hasError) {
3566 // Generate an error node.
Anna Zaksf5788c72012-08-14 00:36:15 +00003567 state = setRefBinding(state, Sym, X);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003568
Anton Yartsev6a619222014-02-17 18:25:34 +00003569 static CheckerProgramPointTag ReturnOwnLeakTag(this, "ReturnsOwnLeak");
Anna Zaksda4c8d62011-10-26 21:06:34 +00003570 ExplodedNode *N = C.addTransition(state, Pred, &ReturnOwnLeakTag);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003571 if (N) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003572 const LangOptions &LOpts = C.getASTContext().getLangOpts();
Jordy Rosec49ec532011-09-02 05:55:19 +00003573 bool GCEnabled = C.isObjCGCEnabled();
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00003574 C.emitReport(std::unique_ptr<BugReport>(new CFRefLeakReport(
3575 *getLeakAtReturnBug(LOpts, GCEnabled), LOpts, GCEnabled,
3576 SummaryLog, N, Sym, C, IncludeAllocationLine)));
Jordy Rose298cc4d2011-08-23 19:43:16 +00003577 }
3578 }
3579 }
3580 } else if (X.isReturnedNotOwned()) {
3581 if (RE.isOwned()) {
Jordan Rosecb5386c2015-02-04 19:24:52 +00003582 if (X.getIvarAccessHistory() ==
3583 RefVal::IvarAccessHistory::AccessedDirectly) {
3584 // Assume the method was trying to transfer a +1 reference from a
3585 // strong ivar to the caller.
3586 state = setRefBinding(state, Sym,
3587 X.releaseViaIvar() ^ RefVal::ReturnedOwned);
3588 } else {
3589 // Trying to return a not owned object to a caller expecting an
3590 // owned object.
3591 state = setRefBinding(state, Sym, X ^ RefVal::ErrorReturnedNotOwned);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003592
Jordan Rosecb5386c2015-02-04 19:24:52 +00003593 static CheckerProgramPointTag
3594 ReturnNotOwnedTag(this, "ReturnNotOwnedForOwned");
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003595
Jordan Rosecb5386c2015-02-04 19:24:52 +00003596 ExplodedNode *N = C.addTransition(state, Pred, &ReturnNotOwnedTag);
3597 if (N) {
3598 if (!returnNotOwnedForOwned)
3599 returnNotOwnedForOwned.reset(new ReturnedNotOwnedForOwned(this));
3600
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00003601 C.emitReport(std::unique_ptr<BugReport>(new CFRefReport(
3602 *returnNotOwnedForOwned, C.getASTContext().getLangOpts(),
3603 C.isObjCGCEnabled(), SummaryLog, N, Sym)));
Jordan Rosecb5386c2015-02-04 19:24:52 +00003604 }
Jordy Rose298cc4d2011-08-23 19:43:16 +00003605 }
3606 }
3607 }
3608}
3609
Jordy Rose6763e382011-08-23 20:07:14 +00003610//===----------------------------------------------------------------------===//
Jordy Rose75e680e2011-09-02 06:44:22 +00003611// Check various ways a symbol can be invalidated.
3612//===----------------------------------------------------------------------===//
3613
Anna Zaks3e0f4152011-10-06 00:43:15 +00003614void RetainCountChecker::checkBind(SVal loc, SVal val, const Stmt *S,
Jordy Rose75e680e2011-09-02 06:44:22 +00003615 CheckerContext &C) const {
3616 // Are we storing to something that causes the value to "escape"?
3617 bool escapes = true;
3618
3619 // A value escapes in three possible cases (this may change):
3620 //
3621 // (1) we are binding to something that is not a memory region.
3622 // (2) we are binding to a memregion that does not have stack storage
3623 // (3) we are binding to a memregion with stack storage that the store
3624 // does not understand.
Ted Kremenek49b1e382012-01-26 21:29:00 +00003625 ProgramStateRef state = C.getState();
Jordy Rose75e680e2011-09-02 06:44:22 +00003626
David Blaikie05785d12013-02-20 22:23:23 +00003627 if (Optional<loc::MemRegionVal> regionLoc = loc.getAs<loc::MemRegionVal>()) {
Jordy Rose75e680e2011-09-02 06:44:22 +00003628 escapes = !regionLoc->getRegion()->hasStackStorage();
3629
3630 if (!escapes) {
3631 // To test (3), generate a new state with the binding added. If it is
3632 // the same state, then it escapes (since the store cannot represent
3633 // the binding).
Anna Zaks70de7722012-05-02 00:15:40 +00003634 // Do this only if we know that the store is not supposed to generate the
3635 // same state.
3636 SVal StoredVal = state->getSVal(regionLoc->getRegion());
3637 if (StoredVal != val)
3638 escapes = (state == (state->bindLoc(*regionLoc, val)));
Jordy Rose75e680e2011-09-02 06:44:22 +00003639 }
Ted Kremeneke9a5bcf2012-03-27 01:12:45 +00003640 if (!escapes) {
3641 // Case 4: We do not currently model what happens when a symbol is
3642 // assigned to a struct field, so be conservative here and let the symbol
3643 // go. TODO: This could definitely be improved upon.
3644 escapes = !isa<VarRegion>(regionLoc->getRegion());
3645 }
Jordy Rose75e680e2011-09-02 06:44:22 +00003646 }
3647
Anna Zaksfb050942013-09-17 00:53:28 +00003648 // If we are storing the value into an auto function scope variable annotated
3649 // with (__attribute__((cleanup))), stop tracking the value to avoid leak
3650 // false positives.
3651 if (const VarRegion *LVR = dyn_cast_or_null<VarRegion>(loc.getAsRegion())) {
3652 const VarDecl *VD = LVR->getDecl();
Aaron Ballman9ead1242013-12-19 02:39:40 +00003653 if (VD->hasAttr<CleanupAttr>()) {
Anna Zaksfb050942013-09-17 00:53:28 +00003654 escapes = true;
3655 }
3656 }
3657
Jordy Rose75e680e2011-09-02 06:44:22 +00003658 // If our store can represent the binding and we aren't storing to something
3659 // that doesn't have local storage then just return and have the simulation
3660 // state continue as is.
3661 if (!escapes)
3662 return;
3663
3664 // Otherwise, find all symbols referenced by 'val' that we are tracking
3665 // and stop tracking them.
3666 state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
Anna Zaksda4c8d62011-10-26 21:06:34 +00003667 C.addTransition(state);
Jordy Rose75e680e2011-09-02 06:44:22 +00003668}
3669
Ted Kremenek49b1e382012-01-26 21:29:00 +00003670ProgramStateRef RetainCountChecker::evalAssume(ProgramStateRef state,
Jordy Rose75e680e2011-09-02 06:44:22 +00003671 SVal Cond,
3672 bool Assumption) const {
Jordy Rose75e680e2011-09-02 06:44:22 +00003673 // FIXME: We may add to the interface of evalAssume the list of symbols
3674 // whose assumptions have changed. For now we just iterate through the
3675 // bindings and check if any of the tracked symbols are NULL. This isn't
3676 // too bad since the number of symbols we will track in practice are
3677 // probably small and evalAssume is only called at branches and a few
3678 // other places.
Jordan Rose0c153cb2012-11-02 01:54:06 +00003679 RefBindingsTy B = state->get<RefBindings>();
Jordy Rose75e680e2011-09-02 06:44:22 +00003680
3681 if (B.isEmpty())
3682 return state;
3683
3684 bool changed = false;
Jordan Rose0c153cb2012-11-02 01:54:06 +00003685 RefBindingsTy::Factory &RefBFactory = state->get_context<RefBindings>();
Jordy Rose75e680e2011-09-02 06:44:22 +00003686
Jordan Rose0c153cb2012-11-02 01:54:06 +00003687 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Ted Kremenek244e1d72012-09-07 22:31:01 +00003688 // Check if the symbol is null stop tracking the symbol.
Jordan Rose14fe9f32012-11-01 00:18:27 +00003689 ConstraintManager &CMgr = state->getConstraintManager();
3690 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
3691 if (AllocFailed.isConstrainedTrue()) {
Jordy Rose75e680e2011-09-02 06:44:22 +00003692 changed = true;
3693 B = RefBFactory.remove(B, I.getKey());
3694 }
3695 }
3696
3697 if (changed)
3698 state = state->set<RefBindings>(B);
3699
3700 return state;
3701}
3702
Ted Kremenek3a0678e2015-09-08 03:50:52 +00003703ProgramStateRef
Ted Kremenek49b1e382012-01-26 21:29:00 +00003704RetainCountChecker::checkRegionChanges(ProgramStateRef state,
Anna Zaksdc154152012-12-20 00:38:25 +00003705 const InvalidatedSymbols *invalidated,
Jordy Rose75e680e2011-09-02 06:44:22 +00003706 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks3d348342012-02-14 21:55:24 +00003707 ArrayRef<const MemRegion *> Regions,
Jordan Rose742920c2012-07-02 19:27:35 +00003708 const CallEvent *Call) const {
Jordy Rose75e680e2011-09-02 06:44:22 +00003709 if (!invalidated)
3710 return state;
3711
3712 llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
3713 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
3714 E = ExplicitRegions.end(); I != E; ++I) {
3715 if (const SymbolicRegion *SR = (*I)->StripCasts()->getAs<SymbolicRegion>())
3716 WhitelistedSymbols.insert(SR->getSymbol());
3717 }
3718
Anna Zaksdc154152012-12-20 00:38:25 +00003719 for (InvalidatedSymbols::const_iterator I=invalidated->begin(),
Jordy Rose75e680e2011-09-02 06:44:22 +00003720 E = invalidated->end(); I!=E; ++I) {
3721 SymbolRef sym = *I;
3722 if (WhitelistedSymbols.count(sym))
3723 continue;
3724 // Remove any existing reference-count binding.
Anna Zaksf5788c72012-08-14 00:36:15 +00003725 state = removeRefBinding(state, sym);
Jordy Rose75e680e2011-09-02 06:44:22 +00003726 }
3727 return state;
3728}
3729
3730//===----------------------------------------------------------------------===//
Jordy Rose6763e382011-08-23 20:07:14 +00003731// Handle dead symbols and end-of-path.
3732//===----------------------------------------------------------------------===//
3733
Jordan Roseff03c1d2012-12-06 18:58:18 +00003734ProgramStateRef
3735RetainCountChecker::handleAutoreleaseCounts(ProgramStateRef state,
Anna Zaks58734db2011-10-25 19:57:11 +00003736 ExplodedNode *Pred,
Jordan Rose9f61f8a2012-08-18 00:30:16 +00003737 const ProgramPointTag *Tag,
Anna Zaks58734db2011-10-25 19:57:11 +00003738 CheckerContext &Ctx,
Jordy Rose75e680e2011-09-02 06:44:22 +00003739 SymbolRef Sym, RefVal V) const {
Jordy Rose6763e382011-08-23 20:07:14 +00003740 unsigned ACnt = V.getAutoreleaseCount();
3741
3742 // No autorelease counts? Nothing to be done.
3743 if (!ACnt)
Jordan Roseff03c1d2012-12-06 18:58:18 +00003744 return state;
Jordy Rose6763e382011-08-23 20:07:14 +00003745
Anna Zaks58734db2011-10-25 19:57:11 +00003746 assert(!Ctx.isObjCGCEnabled() && "Autorelease counts in GC mode?");
Jordy Rose6763e382011-08-23 20:07:14 +00003747 unsigned Cnt = V.getCount();
3748
3749 // FIXME: Handle sending 'autorelease' to already released object.
3750
3751 if (V.getKind() == RefVal::ReturnedOwned)
3752 ++Cnt;
3753
Jordan Rosecb5386c2015-02-04 19:24:52 +00003754 // If we would over-release here, but we know the value came from an ivar,
3755 // assume it was a strong ivar that's just been relinquished.
3756 if (ACnt > Cnt &&
3757 V.getIvarAccessHistory() == RefVal::IvarAccessHistory::AccessedDirectly) {
3758 V = V.releaseViaIvar();
3759 --ACnt;
3760 }
3761
Jordy Rose6763e382011-08-23 20:07:14 +00003762 if (ACnt <= Cnt) {
3763 if (ACnt == Cnt) {
3764 V.clearCounts();
3765 if (V.getKind() == RefVal::ReturnedOwned)
3766 V = V ^ RefVal::ReturnedNotOwned;
3767 else
3768 V = V ^ RefVal::NotOwned;
3769 } else {
Anna Zaksa8bcc652013-01-31 22:36:17 +00003770 V.setCount(V.getCount() - ACnt);
Jordy Rose6763e382011-08-23 20:07:14 +00003771 V.setAutoreleaseCount(0);
3772 }
Jordan Roseff03c1d2012-12-06 18:58:18 +00003773 return setRefBinding(state, Sym, V);
Jordy Rose6763e382011-08-23 20:07:14 +00003774 }
3775
Jordan Rose3da3f8e2015-03-30 20:18:00 +00003776 // HACK: Ignore retain-count issues on values accessed through ivars,
3777 // because of cases like this:
3778 // [_contentView retain];
3779 // [_contentView removeFromSuperview];
3780 // [self addSubview:_contentView]; // invalidates 'self'
3781 // [_contentView release];
3782 if (V.getIvarAccessHistory() != RefVal::IvarAccessHistory::None)
3783 return state;
3784
Jordy Rose6763e382011-08-23 20:07:14 +00003785 // Woah! More autorelease counts then retain counts left.
3786 // Emit hard error.
3787 V = V ^ RefVal::ErrorOverAutorelease;
Anna Zaksf5788c72012-08-14 00:36:15 +00003788 state = setRefBinding(state, Sym, V);
Jordy Rose6763e382011-08-23 20:07:14 +00003789
Jordan Rose4b4613c2012-08-20 18:43:42 +00003790 ExplodedNode *N = Ctx.generateSink(state, Pred, Tag);
Jordan Rose9f61f8a2012-08-18 00:30:16 +00003791 if (N) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003792 SmallString<128> sbuf;
Jordy Rose6763e382011-08-23 20:07:14 +00003793 llvm::raw_svector_ostream os(sbuf);
Jordan Rose7467f062013-04-23 01:42:25 +00003794 os << "Object was autoreleased ";
Jordy Rose6763e382011-08-23 20:07:14 +00003795 if (V.getAutoreleaseCount() > 1)
Jordan Rose7467f062013-04-23 01:42:25 +00003796 os << V.getAutoreleaseCount() << " times but the object ";
3797 else
3798 os << "but ";
3799 os << "has a +" << V.getCount() << " retain count";
Jordy Rose6763e382011-08-23 20:07:14 +00003800
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003801 if (!overAutorelease)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00003802 overAutorelease.reset(new OverAutorelease(this));
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003803
David Blaikiebbafb8a2012-03-11 07:00:24 +00003804 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00003805 Ctx.emitReport(std::unique_ptr<BugReport>(
3806 new CFRefReport(*overAutorelease, LOpts, /* GCEnabled = */ false,
3807 SummaryLog, N, Sym, os.str())));
Jordy Rose6763e382011-08-23 20:07:14 +00003808 }
3809
Craig Topper0dbb7832014-05-27 02:45:47 +00003810 return nullptr;
Jordy Rose6763e382011-08-23 20:07:14 +00003811}
Jordy Rose78612762011-08-23 19:01:07 +00003812
Ted Kremenek3a0678e2015-09-08 03:50:52 +00003813ProgramStateRef
Ted Kremenek49b1e382012-01-26 21:29:00 +00003814RetainCountChecker::handleSymbolDeath(ProgramStateRef state,
Jordy Rose75e680e2011-09-02 06:44:22 +00003815 SymbolRef sid, RefVal V,
Jordy Rose78612762011-08-23 19:01:07 +00003816 SmallVectorImpl<SymbolRef> &Leaked) const {
Jordan Rose3da3f8e2015-03-30 20:18:00 +00003817 bool hasLeak;
3818
3819 // HACK: Ignore retain-count issues on values accessed through ivars,
3820 // because of cases like this:
3821 // [_contentView retain];
3822 // [_contentView removeFromSuperview];
3823 // [self addSubview:_contentView]; // invalidates 'self'
3824 // [_contentView release];
3825 if (V.getIvarAccessHistory() != RefVal::IvarAccessHistory::None)
3826 hasLeak = false;
3827 else if (V.isOwned())
Jordy Rose78612762011-08-23 19:01:07 +00003828 hasLeak = true;
3829 else if (V.isNotOwned() || V.isReturnedOwned())
3830 hasLeak = (V.getCount() > 0);
Jordan Rose3da3f8e2015-03-30 20:18:00 +00003831 else
3832 hasLeak = false;
Jordy Rose78612762011-08-23 19:01:07 +00003833
3834 if (!hasLeak)
Anna Zaksf5788c72012-08-14 00:36:15 +00003835 return removeRefBinding(state, sid);
Jordy Rose78612762011-08-23 19:01:07 +00003836
3837 Leaked.push_back(sid);
Anna Zaksf5788c72012-08-14 00:36:15 +00003838 return setRefBinding(state, sid, V ^ RefVal::ErrorLeak);
Jordy Rose78612762011-08-23 19:01:07 +00003839}
3840
3841ExplodedNode *
Ted Kremenek49b1e382012-01-26 21:29:00 +00003842RetainCountChecker::processLeaks(ProgramStateRef state,
Jordy Rose75e680e2011-09-02 06:44:22 +00003843 SmallVectorImpl<SymbolRef> &Leaked,
Anna Zaks58734db2011-10-25 19:57:11 +00003844 CheckerContext &Ctx,
3845 ExplodedNode *Pred) const {
Jordy Rose78612762011-08-23 19:01:07 +00003846 // Generate an intermediate node representing the leak point.
Jordan Rose9f61f8a2012-08-18 00:30:16 +00003847 ExplodedNode *N = Ctx.addTransition(state, Pred);
Jordy Rose78612762011-08-23 19:01:07 +00003848
3849 if (N) {
3850 for (SmallVectorImpl<SymbolRef>::iterator
3851 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3852
David Blaikiebbafb8a2012-03-11 07:00:24 +00003853 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
Anna Zaks58734db2011-10-25 19:57:11 +00003854 bool GCEnabled = Ctx.isObjCGCEnabled();
Jordy Rosec49ec532011-09-02 05:55:19 +00003855 CFRefBug *BT = Pred ? getLeakWithinFunctionBug(LOpts, GCEnabled)
3856 : getLeakAtReturnBug(LOpts, GCEnabled);
Jordy Rose78612762011-08-23 19:01:07 +00003857 assert(BT && "BugType not initialized.");
Jordy Rose184bd142011-08-24 22:39:09 +00003858
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00003859 Ctx.emitReport(std::unique_ptr<BugReport>(
3860 new CFRefLeakReport(*BT, LOpts, GCEnabled, SummaryLog, N, *I, Ctx,
3861 IncludeAllocationLine)));
Jordy Rose78612762011-08-23 19:01:07 +00003862 }
3863 }
3864
3865 return N;
3866}
3867
Anna Zaks3fdcc0b2013-01-03 00:25:29 +00003868void RetainCountChecker::checkEndFunction(CheckerContext &Ctx) const {
Ted Kremenek49b1e382012-01-26 21:29:00 +00003869 ProgramStateRef state = Ctx.getState();
Jordan Rose0c153cb2012-11-02 01:54:06 +00003870 RefBindingsTy B = state->get<RefBindings>();
Anna Zaks3eae3342011-10-25 19:56:48 +00003871 ExplodedNode *Pred = Ctx.getPredecessor();
Jordy Rose78612762011-08-23 19:01:07 +00003872
Jordan Rose7699e4a2013-08-01 22:16:36 +00003873 // Don't process anything within synthesized bodies.
3874 const LocationContext *LCtx = Pred->getLocationContext();
3875 if (LCtx->getAnalysisDeclContext()->isBodyAutosynthesized()) {
3876 assert(LCtx->getParent());
3877 return;
3878 }
3879
Jordan Rose0c153cb2012-11-02 01:54:06 +00003880 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Craig Topper0dbb7832014-05-27 02:45:47 +00003881 state = handleAutoreleaseCounts(state, Pred, /*Tag=*/nullptr, Ctx,
Jordan Roseff03c1d2012-12-06 18:58:18 +00003882 I->first, I->second);
Jordy Rose6763e382011-08-23 20:07:14 +00003883 if (!state)
Jordy Rose78612762011-08-23 19:01:07 +00003884 return;
3885 }
3886
Ted Kremeneka2bbac32012-02-07 00:24:33 +00003887 // If the current LocationContext has a parent, don't check for leaks.
3888 // We will do that later.
Anna Zaksf5788c72012-08-14 00:36:15 +00003889 // FIXME: we should instead check for imbalances of the retain/releases,
Ted Kremeneka2bbac32012-02-07 00:24:33 +00003890 // and suggest annotations.
Jordan Rose7699e4a2013-08-01 22:16:36 +00003891 if (LCtx->getParent())
Ted Kremeneka2bbac32012-02-07 00:24:33 +00003892 return;
Ted Kremenek3a0678e2015-09-08 03:50:52 +00003893
Jordy Rose78612762011-08-23 19:01:07 +00003894 B = state->get<RefBindings>();
3895 SmallVector<SymbolRef, 10> Leaked;
3896
Jordan Rose0c153cb2012-11-02 01:54:06 +00003897 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I)
Jordy Rose6763e382011-08-23 20:07:14 +00003898 state = handleSymbolDeath(state, I->first, I->second, Leaked);
Jordy Rose78612762011-08-23 19:01:07 +00003899
Jordan Rose9f61f8a2012-08-18 00:30:16 +00003900 processLeaks(state, Leaked, Ctx, Pred);
Jordy Rose78612762011-08-23 19:01:07 +00003901}
3902
3903const ProgramPointTag *
Jordy Rose75e680e2011-09-02 06:44:22 +00003904RetainCountChecker::getDeadSymbolTag(SymbolRef sym) const {
Anton Yartsev6a619222014-02-17 18:25:34 +00003905 const CheckerProgramPointTag *&tag = DeadSymbolTags[sym];
Jordy Rose78612762011-08-23 19:01:07 +00003906 if (!tag) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003907 SmallString<64> buf;
Jordy Rose78612762011-08-23 19:01:07 +00003908 llvm::raw_svector_ostream out(buf);
Anton Yartsev6a619222014-02-17 18:25:34 +00003909 out << "Dead Symbol : ";
Anna Zaks22351652011-12-05 18:58:11 +00003910 sym->dumpToStream(out);
Anton Yartsev6a619222014-02-17 18:25:34 +00003911 tag = new CheckerProgramPointTag(this, out.str());
Jordy Rose78612762011-08-23 19:01:07 +00003912 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +00003913 return tag;
Jordy Rose78612762011-08-23 19:01:07 +00003914}
3915
Jordy Rose75e680e2011-09-02 06:44:22 +00003916void RetainCountChecker::checkDeadSymbols(SymbolReaper &SymReaper,
3917 CheckerContext &C) const {
Jordy Rose78612762011-08-23 19:01:07 +00003918 ExplodedNode *Pred = C.getPredecessor();
3919
Ted Kremenek49b1e382012-01-26 21:29:00 +00003920 ProgramStateRef state = C.getState();
Jordan Rose0c153cb2012-11-02 01:54:06 +00003921 RefBindingsTy B = state->get<RefBindings>();
Jordan Roseff03c1d2012-12-06 18:58:18 +00003922 SmallVector<SymbolRef, 10> Leaked;
Jordy Rose78612762011-08-23 19:01:07 +00003923
3924 // Update counts from autorelease pools
3925 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3926 E = SymReaper.dead_end(); I != E; ++I) {
3927 SymbolRef Sym = *I;
3928 if (const RefVal *T = B.lookup(Sym)){
3929 // Use the symbol as the tag.
3930 // FIXME: This might not be as unique as we would like.
Jordan Rose9f61f8a2012-08-18 00:30:16 +00003931 const ProgramPointTag *Tag = getDeadSymbolTag(Sym);
Jordan Roseff03c1d2012-12-06 18:58:18 +00003932 state = handleAutoreleaseCounts(state, Pred, Tag, C, Sym, *T);
Jordy Rose6763e382011-08-23 20:07:14 +00003933 if (!state)
Jordy Rose78612762011-08-23 19:01:07 +00003934 return;
Jordan Roseff03c1d2012-12-06 18:58:18 +00003935
3936 // Fetch the new reference count from the state, and use it to handle
3937 // this symbol.
3938 state = handleSymbolDeath(state, *I, *getRefBinding(state, Sym), Leaked);
Jordy Rose78612762011-08-23 19:01:07 +00003939 }
3940 }
3941
Jordan Roseff03c1d2012-12-06 18:58:18 +00003942 if (Leaked.empty()) {
3943 C.addTransition(state);
3944 return;
Jordy Rose78612762011-08-23 19:01:07 +00003945 }
3946
Jordan Rose9f61f8a2012-08-18 00:30:16 +00003947 Pred = processLeaks(state, Leaked, C, Pred);
Jordy Rose78612762011-08-23 19:01:07 +00003948
3949 // Did we cache out?
3950 if (!Pred)
3951 return;
3952
3953 // Now generate a new node that nukes the old bindings.
Jordan Roseff03c1d2012-12-06 18:58:18 +00003954 // The only bindings left at this point are the leaked symbols.
Jordan Rose0c153cb2012-11-02 01:54:06 +00003955 RefBindingsTy::Factory &F = state->get_context<RefBindings>();
Jordan Roseff03c1d2012-12-06 18:58:18 +00003956 B = state->get<RefBindings>();
Jordy Rose78612762011-08-23 19:01:07 +00003957
Jordan Roseff03c1d2012-12-06 18:58:18 +00003958 for (SmallVectorImpl<SymbolRef>::iterator I = Leaked.begin(),
3959 E = Leaked.end();
3960 I != E; ++I)
Jordy Rose78612762011-08-23 19:01:07 +00003961 B = F.remove(B, *I);
3962
3963 state = state->set<RefBindings>(B);
Anna Zaksda4c8d62011-10-26 21:06:34 +00003964 C.addTransition(state, Pred);
Jordy Rose78612762011-08-23 19:01:07 +00003965}
3966
Ted Kremenek49b1e382012-01-26 21:29:00 +00003967void RetainCountChecker::printState(raw_ostream &Out, ProgramStateRef State,
Jordy Rose75e680e2011-09-02 06:44:22 +00003968 const char *NL, const char *Sep) const {
Jordy Rose58a20d32011-08-28 19:11:56 +00003969
Jordan Rose0c153cb2012-11-02 01:54:06 +00003970 RefBindingsTy B = State->get<RefBindings>();
Jordy Rose58a20d32011-08-28 19:11:56 +00003971
Ted Kremenekdb70b522013-03-28 18:43:18 +00003972 if (B.isEmpty())
3973 return;
3974
3975 Out << Sep << NL;
Jordy Rose58a20d32011-08-28 19:11:56 +00003976
Jordan Rose0c153cb2012-11-02 01:54:06 +00003977 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Jordy Rose58a20d32011-08-28 19:11:56 +00003978 Out << I->first << " : ";
3979 I->second.print(Out);
3980 Out << NL;
3981 }
Jordy Rose58a20d32011-08-28 19:11:56 +00003982}
3983
3984//===----------------------------------------------------------------------===//
Jordy Rose75e680e2011-09-02 06:44:22 +00003985// Checker registration.
Ted Kremenek819e9b62008-03-11 06:39:11 +00003986//===----------------------------------------------------------------------===//
3987
Jordy Rosec49ec532011-09-02 05:55:19 +00003988void ento::registerRetainCountChecker(CheckerManager &Mgr) {
Ted Kremenek8671acb2013-04-16 21:44:22 +00003989 Mgr.registerChecker<RetainCountChecker>(Mgr.getAnalyzerOptions());
Jordy Rosec49ec532011-09-02 05:55:19 +00003990}
3991
Ted Kremenek71c080f2013-08-14 23:41:49 +00003992//===----------------------------------------------------------------------===//
3993// Implementation of the CallEffects API.
3994//===----------------------------------------------------------------------===//
3995
Hans Wennborgdcfba332015-10-06 23:40:43 +00003996namespace clang {
3997namespace ento {
3998namespace objc_retain {
Ted Kremenek71c080f2013-08-14 23:41:49 +00003999
4000// This is a bit gross, but it allows us to populate CallEffects without
4001// creating a bunch of accessors. This kind is very localized, so the
4002// damage of this macro is limited.
4003#define createCallEffect(D, KIND)\
4004 ASTContext &Ctx = D->getASTContext();\
4005 LangOptions L = Ctx.getLangOpts();\
4006 RetainSummaryManager M(Ctx, L.GCOnly, L.ObjCAutoRefCount);\
4007 const RetainSummary *S = M.get ## KIND ## Summary(D);\
4008 CallEffects CE(S->getRetEffect());\
4009 CE.Receiver = S->getReceiverEffect();\
Ted Kremeneke19529b2013-08-16 23:14:22 +00004010 unsigned N = D->param_size();\
Ted Kremenek71c080f2013-08-14 23:41:49 +00004011 for (unsigned i = 0; i < N; ++i) {\
4012 CE.Args.push_back(S->getArg(i));\
4013 }
4014
4015CallEffects CallEffects::getEffect(const ObjCMethodDecl *MD) {
4016 createCallEffect(MD, Method);
4017 return CE;
4018}
4019
4020CallEffects CallEffects::getEffect(const FunctionDecl *FD) {
4021 createCallEffect(FD, Function);
4022 return CE;
4023}
4024
4025#undef createCallEffect
4026
Hans Wennborgdcfba332015-10-06 23:40:43 +00004027} // end namespace objc_retain
4028} // end namespace ento
4029} // end namespace clang