blob: 447e66dfe7b6a8f7e3df5a52944c5bc6d2ab3def [file] [log] [blame]
Jordy Rose75e680e2011-09-02 06:44:22 +00001//==-- RetainCountChecker.cpp - Checks for leaks and other issues -*- C++ -*--//
Ted Kremenekea6507f2008-03-06 00:08:09 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Jordy Rose75e680e2011-09-02 06:44:22 +000010// This file defines the methods for RetainCountChecker, which implements
11// a reference count checker for Core Foundation and Cocoa on (Mac OS X).
Ted Kremenekea6507f2008-03-06 00:08:09 +000012//
13//===----------------------------------------------------------------------===//
14
Jordy Rose75e680e2011-09-02 06:44:22 +000015#include "ClangSACheckers.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000016#include "AllocationDiagnostics.h"
Jordan Rose0675c872014-04-09 01:39:22 +000017#include "SelectorExtras.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000018#include "clang/AST/Attr.h"
Ted Kremenek98a24e32011-03-30 17:41:19 +000019#include "clang/AST/DeclCXX.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000020#include "clang/AST/DeclObjC.h"
21#include "clang/AST/ParentMap.h"
22#include "clang/Analysis/DomainSpecific/CocoaConventions.h"
Ted Kremenek2b36f3f2010-02-18 00:05:58 +000023#include "clang/Basic/LangOptions.h"
24#include "clang/Basic/SourceManager.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000025#include "clang/StaticAnalyzer/Checkers/ObjCRetainCount.h"
Ted Kremenekf8cbac42011-02-10 01:03:03 +000026#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
27#include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000028#include "clang/StaticAnalyzer/Core/Checker.h"
29#include "clang/StaticAnalyzer/Core/CheckerManager.h"
Jordan Rose4f7df9b2012-07-26 21:39:41 +000030#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
Jordy Rose75e680e2011-09-02 06:44:22 +000031#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
Ted Kremenek001fd5b2011-08-15 22:09:50 +000032#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
Ted Kremenekf8cbac42011-02-10 01:03:03 +000033#include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
Ted Kremenek819e9b62008-03-11 06:39:11 +000034#include "llvm/ADT/DenseMap.h"
35#include "llvm/ADT/FoldingSet.h"
Ted Kremenek0747e7e2008-10-21 15:53:15 +000036#include "llvm/ADT/ImmutableList.h"
Ted Kremenek2b36f3f2010-02-18 00:05:58 +000037#include "llvm/ADT/ImmutableMap.h"
Ted Kremenekc812b232008-05-16 18:33:44 +000038#include "llvm/ADT/STLExtras.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000039#include "llvm/ADT/SmallString.h"
Ted Kremenek2b36f3f2010-02-18 00:05:58 +000040#include "llvm/ADT/StringExtras.h"
Chris Lattner0e62c1c2011-07-23 10:55:15 +000041#include <cstdarg>
Ted Kremenekea6507f2008-03-06 00:08:09 +000042
43using namespace clang;
Ted Kremenek98857c92010-12-23 07:20:52 +000044using namespace ento;
Ted Kremenek243c0852013-08-14 23:41:46 +000045using namespace objc_retain;
Ted Kremenekdb1832d2010-01-27 06:13:48 +000046using llvm::StrInStrNoCase;
Ted Kremenek2855a932008-11-05 16:54:44 +000047
Ted Kremenekc8bef6a2008-04-09 23:49:11 +000048//===----------------------------------------------------------------------===//
Ted Kremenek243c0852013-08-14 23:41:46 +000049// Adapters for FoldingSet.
Ted Kremenekc8bef6a2008-04-09 23:49:11 +000050//===----------------------------------------------------------------------===//
51
Ted Kremenek819e9b62008-03-11 06:39:11 +000052namespace llvm {
Ted Kremenek7d79a5f2009-05-03 05:20:50 +000053template <> struct FoldingSetTrait<ArgEffect> {
Ted Kremenek243c0852013-08-14 23:41:46 +000054static inline void Profile(const ArgEffect X, FoldingSetNodeID &ID) {
Ted Kremenek7d79a5f2009-05-03 05:20:50 +000055 ID.AddInteger((unsigned) X);
56}
Ted Kremenek3185c9c2008-06-25 21:21:56 +000057};
Ted Kremenek243c0852013-08-14 23:41:46 +000058template <> struct FoldingSetTrait<RetEffect> {
59 static inline void Profile(const RetEffect &X, FoldingSetNodeID &ID) {
60 ID.AddInteger((unsigned) X.getKind());
61 ID.AddInteger((unsigned) X.getObjKind());
62}
63};
Ted Kremenek819e9b62008-03-11 06:39:11 +000064} // end llvm namespace
65
Ted Kremenek243c0852013-08-14 23:41:46 +000066//===----------------------------------------------------------------------===//
67// Reference-counting logic (typestate + counts).
68//===----------------------------------------------------------------------===//
69
Ted Kremenek7d79a5f2009-05-03 05:20:50 +000070/// ArgEffects summarizes the effects of a function/method call on all of
71/// its arguments.
72typedef llvm::ImmutableMap<unsigned,ArgEffect> ArgEffects;
73
Ted Kremenek819e9b62008-03-11 06:39:11 +000074namespace {
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +000075class RefVal {
Ted Kremeneka2968e52009-11-13 01:54:21 +000076public:
77 enum Kind {
78 Owned = 0, // Owning reference.
79 NotOwned, // Reference is not owned by still valid (not freed).
80 Released, // Object has been released.
81 ReturnedOwned, // Returned object passes ownership to caller.
82 ReturnedNotOwned, // Return object does not pass ownership to caller.
83 ERROR_START,
84 ErrorDeallocNotOwned, // -dealloc called on non-owned object.
85 ErrorDeallocGC, // Calling -dealloc with GC enabled.
86 ErrorUseAfterRelease, // Object used after released.
87 ErrorReleaseNotOwned, // Release of an object that was not owned.
88 ERROR_LEAK_START,
89 ErrorLeak, // A memory leak due to excessive reference counts.
90 ErrorLeakReturned, // A memory leak due to the returning method not having
91 // the correct naming conventions.
92 ErrorGCLeakReturned,
93 ErrorOverAutorelease,
94 ErrorReturnedNotOwned
95 };
Ted Kremenekbd862712010-07-01 20:16:50 +000096
Ted Kremeneka2968e52009-11-13 01:54:21 +000097private:
Jordan Roseb3ad07e2014-03-25 17:10:58 +000098 /// The number of outstanding retains.
Ted Kremeneka2968e52009-11-13 01:54:21 +000099 unsigned Cnt;
Jordan Roseb3ad07e2014-03-25 17:10:58 +0000100 /// The number of outstanding autoreleases.
Ted Kremeneka2968e52009-11-13 01:54:21 +0000101 unsigned ACnt;
Jordan Roseb3ad07e2014-03-25 17:10:58 +0000102 /// The (static) type of the object at the time we started tracking it.
Ted Kremeneka2968e52009-11-13 01:54:21 +0000103 QualType T;
Ted Kremenekbd862712010-07-01 20:16:50 +0000104
Jordan Roseb3ad07e2014-03-25 17:10:58 +0000105 /// The current state of the object.
106 ///
107 /// See the RefVal::Kind enum for possible values.
108 unsigned RawKind : 5;
109
110 /// The kind of object being tracked (CF or ObjC), if known.
111 ///
112 /// See the RetEffect::ObjKind enum for possible values.
113 unsigned RawObjectKind : 2;
114
115 /// True if the current state and/or retain count may turn out to not be the
116 /// best possible approximation of the reference counting state.
117 ///
118 /// If true, the checker may decide to throw away ("override") this state
119 /// in favor of something else when it sees the object being used in new ways.
120 ///
121 /// This setting should not be propagated to state derived from this state.
122 /// Once we start deriving new states, it would be inconsistent to override
123 /// them.
124 unsigned IsOverridable : 1;
125
126 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, unsigned acnt, QualType t,
127 bool Overridable = false)
128 : Cnt(cnt), ACnt(acnt), T(t), RawKind(static_cast<unsigned>(k)),
129 RawObjectKind(static_cast<unsigned>(o)), IsOverridable(Overridable) {
130 assert(getKind() == k && "not enough bits for the kind");
131 assert(getObjKind() == o && "not enough bits for the object kind");
132 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000133
Ted Kremeneka2968e52009-11-13 01:54:21 +0000134public:
Jordan Roseb3ad07e2014-03-25 17:10:58 +0000135 Kind getKind() const { return static_cast<Kind>(RawKind); }
Ted Kremenekbd862712010-07-01 20:16:50 +0000136
Jordan Roseb3ad07e2014-03-25 17:10:58 +0000137 RetEffect::ObjKind getObjKind() const {
138 return static_cast<RetEffect::ObjKind>(RawObjectKind);
139 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000140
Ted Kremeneka2968e52009-11-13 01:54:21 +0000141 unsigned getCount() const { return Cnt; }
142 unsigned getAutoreleaseCount() const { return ACnt; }
143 unsigned getCombinedCounts() const { return Cnt + ACnt; }
Jordan Roseb3ad07e2014-03-25 17:10:58 +0000144 void clearCounts() {
145 Cnt = 0;
146 ACnt = 0;
147 IsOverridable = false;
148 }
149 void setCount(unsigned i) {
150 Cnt = i;
151 IsOverridable = false;
152 }
153 void setAutoreleaseCount(unsigned i) {
154 ACnt = i;
155 IsOverridable = false;
156 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000157
Ted Kremeneka2968e52009-11-13 01:54:21 +0000158 QualType getType() const { return T; }
Ted Kremenekbd862712010-07-01 20:16:50 +0000159
Jordan Roseb3ad07e2014-03-25 17:10:58 +0000160 bool isOverridable() const { return IsOverridable; }
161
Ted Kremeneka2968e52009-11-13 01:54:21 +0000162 bool isOwned() const {
163 return getKind() == Owned;
164 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000165
Ted Kremeneka2968e52009-11-13 01:54:21 +0000166 bool isNotOwned() const {
167 return getKind() == NotOwned;
168 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000169
Ted Kremeneka2968e52009-11-13 01:54:21 +0000170 bool isReturnedOwned() const {
171 return getKind() == ReturnedOwned;
172 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000173
Ted Kremeneka2968e52009-11-13 01:54:21 +0000174 bool isReturnedNotOwned() const {
175 return getKind() == ReturnedNotOwned;
176 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000177
Jordan Roseb3ad07e2014-03-25 17:10:58 +0000178 /// Create a state for an object whose lifetime is the responsibility of the
179 /// current function, at least partially.
180 ///
181 /// Most commonly, this is an owned object with a retain count of +1.
Ted Kremeneka2968e52009-11-13 01:54:21 +0000182 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
183 unsigned Count = 1) {
184 return RefVal(Owned, o, Count, 0, t);
185 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000186
Jordan Roseb3ad07e2014-03-25 17:10:58 +0000187 /// Create a state for an object whose lifetime is not the responsibility of
188 /// the current function.
189 ///
190 /// Most commonly, this is an unowned object with a retain count of +0.
Ted Kremeneka2968e52009-11-13 01:54:21 +0000191 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
192 unsigned Count = 0) {
193 return RefVal(NotOwned, o, Count, 0, t);
194 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000195
Jordan Roseb3ad07e2014-03-25 17:10:58 +0000196 /// Create an "overridable" state for an unowned object at +0.
197 ///
198 /// An overridable state is one that provides a good approximation of the
199 /// reference counting state now, but which may be discarded later if the
200 /// checker sees the object being used in new ways.
201 static RefVal makeOverridableNotOwned(RetEffect::ObjKind o, QualType t) {
202 return RefVal(NotOwned, o, 0, 0, t, /*Overridable=*/true);
Ted Kremeneka2968e52009-11-13 01:54:21 +0000203 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000204
Ted Kremeneka2968e52009-11-13 01:54:21 +0000205 RefVal operator-(size_t i) const {
206 return RefVal(getKind(), getObjKind(), getCount() - i,
207 getAutoreleaseCount(), getType());
208 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000209
Ted Kremeneka2968e52009-11-13 01:54:21 +0000210 RefVal operator+(size_t i) const {
211 return RefVal(getKind(), getObjKind(), getCount() + i,
212 getAutoreleaseCount(), getType());
213 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000214
Ted Kremeneka2968e52009-11-13 01:54:21 +0000215 RefVal operator^(Kind k) const {
216 return RefVal(k, getObjKind(), getCount(), getAutoreleaseCount(),
217 getType());
218 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000219
Ted Kremeneka2968e52009-11-13 01:54:21 +0000220 RefVal autorelease() const {
221 return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount()+1,
222 getType());
223 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000224
Jordan Roseb3ad07e2014-03-25 17:10:58 +0000225 // Comparison, profiling, and pretty-printing.
226
227 bool hasSameState(const RefVal &X) const {
228 return getKind() == X.getKind() && Cnt == X.Cnt && ACnt == X.ACnt;
229 }
230
231 bool operator==(const RefVal& X) const {
232 return T == X.T && hasSameState(X) && getObjKind() == X.getObjKind() &&
233 IsOverridable == X.IsOverridable;
234 }
235
Ted Kremeneka2968e52009-11-13 01:54:21 +0000236 void Profile(llvm::FoldingSetNodeID& ID) const {
Jordan Roseb3ad07e2014-03-25 17:10:58 +0000237 ID.Add(T);
238 ID.AddInteger(RawKind);
Ted Kremeneka2968e52009-11-13 01:54:21 +0000239 ID.AddInteger(Cnt);
240 ID.AddInteger(ACnt);
Jordan Roseb3ad07e2014-03-25 17:10:58 +0000241 ID.AddInteger(RawObjectKind);
242 ID.AddBoolean(IsOverridable);
Ted Kremeneka2968e52009-11-13 01:54:21 +0000243 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000244
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000245 void print(raw_ostream &Out) const;
Ted Kremeneka2968e52009-11-13 01:54:21 +0000246};
247
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000248void RefVal::print(raw_ostream &Out) const {
Ted Kremeneka2968e52009-11-13 01:54:21 +0000249 if (!T.isNull())
Jordy Rose58a20d32011-08-28 19:11:56 +0000250 Out << "Tracked " << T.getAsString() << '/';
Ted Kremenekbd862712010-07-01 20:16:50 +0000251
Jordan Roseb3ad07e2014-03-25 17:10:58 +0000252 if (isOverridable())
253 Out << "(overridable) ";
254
Ted Kremeneka2968e52009-11-13 01:54:21 +0000255 switch (getKind()) {
Jordy Rose75e680e2011-09-02 06:44:22 +0000256 default: llvm_unreachable("Invalid RefVal kind");
Ted Kremeneka2968e52009-11-13 01:54:21 +0000257 case Owned: {
258 Out << "Owned";
259 unsigned cnt = getCount();
260 if (cnt) Out << " (+ " << cnt << ")";
261 break;
262 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000263
Ted Kremeneka2968e52009-11-13 01:54:21 +0000264 case NotOwned: {
265 Out << "NotOwned";
266 unsigned cnt = getCount();
267 if (cnt) Out << " (+ " << cnt << ")";
268 break;
269 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000270
Ted Kremeneka2968e52009-11-13 01:54:21 +0000271 case ReturnedOwned: {
272 Out << "ReturnedOwned";
273 unsigned cnt = getCount();
274 if (cnt) Out << " (+ " << cnt << ")";
275 break;
276 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000277
Ted Kremeneka2968e52009-11-13 01:54:21 +0000278 case ReturnedNotOwned: {
279 Out << "ReturnedNotOwned";
280 unsigned cnt = getCount();
281 if (cnt) Out << " (+ " << cnt << ")";
282 break;
283 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000284
Ted Kremeneka2968e52009-11-13 01:54:21 +0000285 case Released:
286 Out << "Released";
287 break;
Ted Kremenekbd862712010-07-01 20:16:50 +0000288
Ted Kremeneka2968e52009-11-13 01:54:21 +0000289 case ErrorDeallocGC:
290 Out << "-dealloc (GC)";
291 break;
Ted Kremenekbd862712010-07-01 20:16:50 +0000292
Ted Kremeneka2968e52009-11-13 01:54:21 +0000293 case ErrorDeallocNotOwned:
294 Out << "-dealloc (not-owned)";
295 break;
Ted Kremenekbd862712010-07-01 20:16:50 +0000296
Ted Kremeneka2968e52009-11-13 01:54:21 +0000297 case ErrorLeak:
298 Out << "Leaked";
299 break;
Ted Kremenekbd862712010-07-01 20:16:50 +0000300
Ted Kremeneka2968e52009-11-13 01:54:21 +0000301 case ErrorLeakReturned:
302 Out << "Leaked (Bad naming)";
303 break;
Ted Kremenekbd862712010-07-01 20:16:50 +0000304
Ted Kremeneka2968e52009-11-13 01:54:21 +0000305 case ErrorGCLeakReturned:
306 Out << "Leaked (GC-ed at return)";
307 break;
Ted Kremenekbd862712010-07-01 20:16:50 +0000308
Ted Kremeneka2968e52009-11-13 01:54:21 +0000309 case ErrorUseAfterRelease:
310 Out << "Use-After-Release [ERROR]";
311 break;
Ted Kremenekbd862712010-07-01 20:16:50 +0000312
Ted Kremeneka2968e52009-11-13 01:54:21 +0000313 case ErrorReleaseNotOwned:
314 Out << "Release of Not-Owned [ERROR]";
315 break;
Ted Kremenekbd862712010-07-01 20:16:50 +0000316
Ted Kremeneka2968e52009-11-13 01:54:21 +0000317 case RefVal::ErrorOverAutorelease:
Jordan Rose7467f062013-04-23 01:42:25 +0000318 Out << "Over-autoreleased";
Ted Kremeneka2968e52009-11-13 01:54:21 +0000319 break;
Ted Kremenekbd862712010-07-01 20:16:50 +0000320
Ted Kremeneka2968e52009-11-13 01:54:21 +0000321 case RefVal::ErrorReturnedNotOwned:
322 Out << "Non-owned object returned instead of owned";
323 break;
324 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000325
Ted Kremeneka2968e52009-11-13 01:54:21 +0000326 if (ACnt) {
327 Out << " [ARC +" << ACnt << ']';
328 }
329}
330} //end anonymous namespace
331
332//===----------------------------------------------------------------------===//
333// RefBindings - State used to track object reference counts.
334//===----------------------------------------------------------------------===//
335
Jordan Rose0c153cb2012-11-02 01:54:06 +0000336REGISTER_MAP_WITH_PROGRAMSTATE(RefBindings, SymbolRef, RefVal)
Ted Kremeneka2968e52009-11-13 01:54:21 +0000337
Anna Zaksf5788c72012-08-14 00:36:15 +0000338static inline const RefVal *getRefBinding(ProgramStateRef State,
339 SymbolRef Sym) {
340 return State->get<RefBindings>(Sym);
341}
342
343static inline ProgramStateRef setRefBinding(ProgramStateRef State,
344 SymbolRef Sym, RefVal Val) {
345 return State->set<RefBindings>(Sym, Val);
346}
347
348static ProgramStateRef removeRefBinding(ProgramStateRef State, SymbolRef Sym) {
349 return State->remove<RefBindings>(Sym);
350}
351
Ted Kremeneka2968e52009-11-13 01:54:21 +0000352//===----------------------------------------------------------------------===//
Jordy Rose75e680e2011-09-02 06:44:22 +0000353// Function/Method behavior summaries.
Ted Kremeneka2968e52009-11-13 01:54:21 +0000354//===----------------------------------------------------------------------===//
355
356namespace {
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +0000357class RetainSummary {
Jordy Rose61c974b2012-03-18 01:26:10 +0000358 /// Args - a map of (index, ArgEffect) pairs, where index
Ted Kremenekcb2e6362008-05-06 15:44:25 +0000359 /// specifies the argument (starting from 0). This can be sparsely
360 /// populated; arguments with no entry in Args use 'DefaultArgEffect'.
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000361 ArgEffects Args;
Mike Stump11289f42009-09-09 15:08:12 +0000362
Ted Kremenekcb2e6362008-05-06 15:44:25 +0000363 /// DefaultArgEffect - The default ArgEffect to apply to arguments that
364 /// do not have an entry in Args.
Ted Kremeneke8300e52012-01-04 00:35:45 +0000365 ArgEffect DefaultArgEffect;
Mike Stump11289f42009-09-09 15:08:12 +0000366
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000367 /// Receiver - If this summary applies to an Objective-C message expression,
368 /// this is the effect applied to the state of the receiver.
Ted Kremeneke8300e52012-01-04 00:35:45 +0000369 ArgEffect Receiver;
Mike Stump11289f42009-09-09 15:08:12 +0000370
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000371 /// Ret - The effect on the return value. Used to indicate if the
Jordy Rose898a1482011-08-21 21:58:18 +0000372 /// function/method call returns a new tracked symbol.
Ted Kremeneke8300e52012-01-04 00:35:45 +0000373 RetEffect Ret;
Mike Stump11289f42009-09-09 15:08:12 +0000374
Ted Kremenek819e9b62008-03-11 06:39:11 +0000375public:
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000376 RetainSummary(ArgEffects A, RetEffect R, ArgEffect defaultEff,
Jordy Rose5a3c9ff2011-08-20 20:55:40 +0000377 ArgEffect ReceiverEff)
378 : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R) {}
Mike Stump11289f42009-09-09 15:08:12 +0000379
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000380 /// getArg - Return the argument effect on the argument specified by
381 /// idx (starting from 0).
Ted Kremenekbf9d8042008-03-11 17:48:22 +0000382 ArgEffect getArg(unsigned idx) const {
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000383 if (const ArgEffect *AE = Args.lookup(idx))
384 return *AE;
Mike Stump11289f42009-09-09 15:08:12 +0000385
Ted Kremenekcb2e6362008-05-06 15:44:25 +0000386 return DefaultArgEffect;
Ted Kremenekbf9d8042008-03-11 17:48:22 +0000387 }
Ted Kremenek71c080f2013-08-14 23:41:49 +0000388
Ted Kremenekafe348e2011-01-27 18:43:03 +0000389 void addArg(ArgEffects::Factory &af, unsigned idx, ArgEffect e) {
390 Args = af.add(Args, idx, e);
391 }
Mike Stump11289f42009-09-09 15:08:12 +0000392
Ted Kremenek1d9a2672009-05-04 05:31:22 +0000393 /// setDefaultArgEffect - Set the default argument effect.
394 void setDefaultArgEffect(ArgEffect E) {
395 DefaultArgEffect = E;
396 }
Mike Stump11289f42009-09-09 15:08:12 +0000397
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000398 /// getRetEffect - Returns the effect on the return value of the call.
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000399 RetEffect getRetEffect() const { return Ret; }
Mike Stump11289f42009-09-09 15:08:12 +0000400
Ted Kremenek1d9a2672009-05-04 05:31:22 +0000401 /// setRetEffect - Set the effect of the return value of the call.
402 void setRetEffect(RetEffect E) { Ret = E; }
Mike Stump11289f42009-09-09 15:08:12 +0000403
Ted Kremenek0e898382011-01-27 06:54:14 +0000404
405 /// Sets the effect on the receiver of the message.
406 void setReceiverEffect(ArgEffect e) { Receiver = e; }
407
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000408 /// getReceiverEffect - Returns the effect on the receiver of the call.
409 /// This is only meaningful if the summary applies to an ObjCMessageExpr*.
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000410 ArgEffect getReceiverEffect() const { return Receiver; }
Jordy Rose212e4592011-08-23 04:27:15 +0000411
412 /// Test if two retain summaries are identical. Note that merely equivalent
413 /// summaries are not necessarily identical (for example, if an explicit
414 /// argument effect matches the default effect).
415 bool operator==(const RetainSummary &Other) const {
416 return Args == Other.Args && DefaultArgEffect == Other.DefaultArgEffect &&
417 Receiver == Other.Receiver && Ret == Other.Ret;
418 }
Jordy Rose61c974b2012-03-18 01:26:10 +0000419
420 /// Profile this summary for inclusion in a FoldingSet.
421 void Profile(llvm::FoldingSetNodeID& ID) const {
422 ID.Add(Args);
423 ID.Add(DefaultArgEffect);
424 ID.Add(Receiver);
425 ID.Add(Ret);
426 }
427
428 /// A retain summary is simple if it has no ArgEffects other than the default.
429 bool isSimple() const {
430 return Args.isEmpty();
431 }
Jordan Roseeec15392012-07-02 19:27:43 +0000432
433private:
434 ArgEffects getArgEffects() const { return Args; }
435 ArgEffect getDefaultArgEffect() const { return DefaultArgEffect; }
436
437 friend class RetainSummaryManager;
Ted Kremenek819e9b62008-03-11 06:39:11 +0000438};
Ted Kremenek0cfc1612008-06-23 23:30:29 +0000439} // end anonymous namespace
Ted Kremenek819e9b62008-03-11 06:39:11 +0000440
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000441//===----------------------------------------------------------------------===//
442// Data structures for constructing summaries.
443//===----------------------------------------------------------------------===//
Ted Kremenekb1d13292008-06-24 03:49:48 +0000444
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000445namespace {
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +0000446class ObjCSummaryKey {
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000447 IdentifierInfo* II;
448 Selector S;
Mike Stump11289f42009-09-09 15:08:12 +0000449public:
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000450 ObjCSummaryKey(IdentifierInfo* ii, Selector s)
451 : II(ii), S(s) {}
452
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000453 ObjCSummaryKey(const ObjCInterfaceDecl *d, Selector s)
Craig Topper0dbb7832014-05-27 02:45:47 +0000454 : II(d ? d->getIdentifier() : nullptr), S(s) {}
Ted Kremenek5801f652009-05-13 18:16:01 +0000455
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000456 ObjCSummaryKey(Selector s)
Craig Topper0dbb7832014-05-27 02:45:47 +0000457 : II(nullptr), S(s) {}
Mike Stump11289f42009-09-09 15:08:12 +0000458
Ted Kremeneke8300e52012-01-04 00:35:45 +0000459 IdentifierInfo *getIdentifier() const { return II; }
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000460 Selector getSelector() const { return S; }
461};
Ted Kremenek0cfc1612008-06-23 23:30:29 +0000462}
463
464namespace llvm {
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000465template <> struct DenseMapInfo<ObjCSummaryKey> {
466 static inline ObjCSummaryKey getEmptyKey() {
467 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
468 DenseMapInfo<Selector>::getEmptyKey());
469 }
Mike Stump11289f42009-09-09 15:08:12 +0000470
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000471 static inline ObjCSummaryKey getTombstoneKey() {
472 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
Mike Stump11289f42009-09-09 15:08:12 +0000473 DenseMapInfo<Selector>::getTombstoneKey());
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000474 }
Mike Stump11289f42009-09-09 15:08:12 +0000475
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000476 static unsigned getHashValue(const ObjCSummaryKey &V) {
Benjamin Kramer69b5a602012-05-27 13:28:44 +0000477 typedef std::pair<IdentifierInfo*, Selector> PairTy;
478 return DenseMapInfo<PairTy>::getHashValue(PairTy(V.getIdentifier(),
479 V.getSelector()));
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000480 }
Mike Stump11289f42009-09-09 15:08:12 +0000481
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000482 static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
Benjamin Kramer69b5a602012-05-27 13:28:44 +0000483 return LHS.getIdentifier() == RHS.getIdentifier() &&
484 LHS.getSelector() == RHS.getSelector();
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000485 }
Mike Stump11289f42009-09-09 15:08:12 +0000486
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000487};
Ted Kremenek0cfc1612008-06-23 23:30:29 +0000488} // end llvm namespace
Mike Stump11289f42009-09-09 15:08:12 +0000489
Ted Kremenek0cfc1612008-06-23 23:30:29 +0000490namespace {
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +0000491class ObjCSummaryCache {
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000492 typedef llvm::DenseMap<ObjCSummaryKey, const RetainSummary *> MapTy;
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000493 MapTy M;
494public:
495 ObjCSummaryCache() {}
Mike Stump11289f42009-09-09 15:08:12 +0000496
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000497 const RetainSummary * find(const ObjCInterfaceDecl *D, Selector S) {
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000498 // Do a lookup with the (D,S) pair. If we find a match return
499 // the iterator.
500 ObjCSummaryKey K(D, S);
501 MapTy::iterator I = M.find(K);
Mike Stump11289f42009-09-09 15:08:12 +0000502
Jordan Roseeec15392012-07-02 19:27:43 +0000503 if (I != M.end())
Ted Kremenek8be51382009-07-21 23:27:57 +0000504 return I->second;
Jordan Roseeec15392012-07-02 19:27:43 +0000505 if (!D)
Craig Topper0dbb7832014-05-27 02:45:47 +0000506 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000507
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000508 // Walk the super chain. If we find a hit with a parent, we'll end
509 // up returning that summary. We actually allow that key (null,S), as
510 // we cache summaries for the null ObjCInterfaceDecl* to allow us to
511 // generate initial summaries without having to worry about NSObject
512 // being declared.
513 // FIXME: We may change this at some point.
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000514 for (ObjCInterfaceDecl *C=D->getSuperClass() ;; C=C->getSuperClass()) {
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000515 if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
516 break;
Mike Stump11289f42009-09-09 15:08:12 +0000517
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000518 if (!C)
Craig Topper0dbb7832014-05-27 02:45:47 +0000519 return nullptr;
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000520 }
Mike Stump11289f42009-09-09 15:08:12 +0000521
522 // Cache the summary with original key to make the next lookup faster
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000523 // and return the iterator.
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000524 const RetainSummary *Summ = I->second;
Ted Kremenek8be51382009-07-21 23:27:57 +0000525 M[K] = Summ;
526 return Summ;
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000527 }
Mike Stump11289f42009-09-09 15:08:12 +0000528
Ted Kremeneke8300e52012-01-04 00:35:45 +0000529 const RetainSummary *find(IdentifierInfo* II, Selector S) {
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000530 // FIXME: Class method lookup. Right now we dont' have a good way
531 // of going between IdentifierInfo* and the class hierarchy.
Ted Kremenek8be51382009-07-21 23:27:57 +0000532 MapTy::iterator I = M.find(ObjCSummaryKey(II, S));
Mike Stump11289f42009-09-09 15:08:12 +0000533
Ted Kremenek8be51382009-07-21 23:27:57 +0000534 if (I == M.end())
535 I = M.find(ObjCSummaryKey(S));
Mike Stump11289f42009-09-09 15:08:12 +0000536
Craig Topper0dbb7832014-05-27 02:45:47 +0000537 return I == M.end() ? nullptr : I->second;
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000538 }
Mike Stump11289f42009-09-09 15:08:12 +0000539
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000540 const RetainSummary *& operator[](ObjCSummaryKey K) {
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000541 return M[K];
542 }
Mike Stump11289f42009-09-09 15:08:12 +0000543
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000544 const RetainSummary *& operator[](Selector S) {
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000545 return M[ ObjCSummaryKey(S) ];
546 }
Mike Stump11289f42009-09-09 15:08:12 +0000547};
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000548} // end anonymous namespace
549
550//===----------------------------------------------------------------------===//
551// Data structures for managing collections of summaries.
552//===----------------------------------------------------------------------===//
553
554namespace {
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +0000555class RetainSummaryManager {
Ted Kremenek00daccd2008-05-05 22:11:16 +0000556
557 //==-----------------------------------------------------------------==//
558 // Typedefs.
559 //==-----------------------------------------------------------------==//
Mike Stump11289f42009-09-09 15:08:12 +0000560
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000561 typedef llvm::DenseMap<const FunctionDecl*, const RetainSummary *>
Ted Kremenek00daccd2008-05-05 22:11:16 +0000562 FuncSummariesTy;
Mike Stump11289f42009-09-09 15:08:12 +0000563
Ted Kremenek0cfc1612008-06-23 23:30:29 +0000564 typedef ObjCSummaryCache ObjCMethodSummariesTy;
Mike Stump11289f42009-09-09 15:08:12 +0000565
Jordy Rose61c974b2012-03-18 01:26:10 +0000566 typedef llvm::FoldingSetNodeWrapper<RetainSummary> CachedSummaryNode;
567
Ted Kremenek00daccd2008-05-05 22:11:16 +0000568 //==-----------------------------------------------------------------==//
569 // Data.
570 //==-----------------------------------------------------------------==//
Mike Stump11289f42009-09-09 15:08:12 +0000571
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000572 /// Ctx - The ASTContext object for the analyzed ASTs.
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000573 ASTContext &Ctx;
Ted Kremenekab54e512008-07-01 17:21:27 +0000574
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000575 /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
Ted Kremenek4b7ca772008-04-29 05:33:51 +0000576 const bool GCEnabled;
Mike Stump11289f42009-09-09 15:08:12 +0000577
John McCall31168b02011-06-15 23:02:42 +0000578 /// Records whether or not the analyzed code runs in ARC mode.
579 const bool ARCEnabled;
580
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000581 /// FuncSummaries - A map from FunctionDecls to summaries.
Mike Stump11289f42009-09-09 15:08:12 +0000582 FuncSummariesTy FuncSummaries;
583
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000584 /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
585 /// to summaries.
Ted Kremenekea736c52008-06-23 22:21:20 +0000586 ObjCMethodSummariesTy ObjCClassMethodSummaries;
Ted Kremenek00daccd2008-05-05 22:11:16 +0000587
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000588 /// ObjCMethodSummaries - A map from selectors to summaries.
Ted Kremenekea736c52008-06-23 22:21:20 +0000589 ObjCMethodSummariesTy ObjCMethodSummaries;
Ted Kremenek00daccd2008-05-05 22:11:16 +0000590
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000591 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
592 /// and all other data used by the checker.
Ted Kremenek00daccd2008-05-05 22:11:16 +0000593 llvm::BumpPtrAllocator BPAlloc;
Mike Stump11289f42009-09-09 15:08:12 +0000594
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000595 /// AF - A factory for ArgEffects objects.
Mike Stump11289f42009-09-09 15:08:12 +0000596 ArgEffects::Factory AF;
597
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000598 /// ScratchArgs - A holding buffer for construct ArgEffects.
Ted Kremeneke8300e52012-01-04 00:35:45 +0000599 ArgEffects ScratchArgs;
Mike Stump11289f42009-09-09 15:08:12 +0000600
Ted Kremenek9157fbb2009-05-07 23:40:42 +0000601 /// ObjCAllocRetE - Default return effect for methods returning Objective-C
602 /// objects.
603 RetEffect ObjCAllocRetE;
Ted Kremeneka03705c2009-06-05 23:18:01 +0000604
Mike Stump11289f42009-09-09 15:08:12 +0000605 /// ObjCInitRetE - Default return effect for init methods returning
Ted Kremenek815fbb62009-08-20 05:13:36 +0000606 /// Objective-C objects.
Ted Kremeneka03705c2009-06-05 23:18:01 +0000607 RetEffect ObjCInitRetE;
Mike Stump11289f42009-09-09 15:08:12 +0000608
Jordy Rose61c974b2012-03-18 01:26:10 +0000609 /// SimpleSummaries - Used for uniquing summaries that don't have special
610 /// effects.
611 llvm::FoldingSet<CachedSummaryNode> SimpleSummaries;
Mike Stump11289f42009-09-09 15:08:12 +0000612
Ted Kremenek00daccd2008-05-05 22:11:16 +0000613 //==-----------------------------------------------------------------==//
614 // Methods.
615 //==-----------------------------------------------------------------==//
Mike Stump11289f42009-09-09 15:08:12 +0000616
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000617 /// getArgEffects - Returns a persistent ArgEffects object based on the
618 /// data in ScratchArgs.
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000619 ArgEffects getArgEffects();
Ted Kremenek819e9b62008-03-11 06:39:11 +0000620
Jordan Rose77411322013-10-07 17:16:52 +0000621 enum UnaryFuncKind { cfretain, cfrelease, cfautorelease, cfmakecollectable };
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000622
Ted Kremeneke8300e52012-01-04 00:35:45 +0000623 const RetainSummary *getUnarySummary(const FunctionType* FT,
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000624 UnaryFuncKind func);
Mike Stump11289f42009-09-09 15:08:12 +0000625
Ted Kremeneke8300e52012-01-04 00:35:45 +0000626 const RetainSummary *getCFSummaryCreateRule(const FunctionDecl *FD);
627 const RetainSummary *getCFSummaryGetRule(const FunctionDecl *FD);
628 const RetainSummary *getCFCreateGetRuleSummary(const FunctionDecl *FD);
Mike Stump11289f42009-09-09 15:08:12 +0000629
Jordy Rose61c974b2012-03-18 01:26:10 +0000630 const RetainSummary *getPersistentSummary(const RetainSummary &OldSumm);
Ted Kremenek3700b762008-10-29 04:07:07 +0000631
Jordy Rose61c974b2012-03-18 01:26:10 +0000632 const RetainSummary *getPersistentSummary(RetEffect RetEff,
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000633 ArgEffect ReceiverEff = DoNothing,
634 ArgEffect DefaultEff = MayEscape) {
Jordy Rose61c974b2012-03-18 01:26:10 +0000635 RetainSummary Summ(getArgEffects(), RetEff, DefaultEff, ReceiverEff);
636 return getPersistentSummary(Summ);
637 }
638
Ted Kremenekececf9f2012-05-08 00:12:09 +0000639 const RetainSummary *getDoNothingSummary() {
640 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
641 }
642
Jordy Rose61c974b2012-03-18 01:26:10 +0000643 const RetainSummary *getDefaultSummary() {
644 return getPersistentSummary(RetEffect::MakeNoRet(),
645 DoNothing, MayEscape);
Ted Kremenek0806f912008-05-06 00:30:21 +0000646 }
Mike Stump11289f42009-09-09 15:08:12 +0000647
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000648 const RetainSummary *getPersistentStopSummary() {
Jordy Rose61c974b2012-03-18 01:26:10 +0000649 return getPersistentSummary(RetEffect::MakeNoRet(),
650 StopTracking, StopTracking);
Mike Stump11289f42009-09-09 15:08:12 +0000651 }
Ted Kremenek015c3562008-05-06 04:20:12 +0000652
Ted Kremenekea736c52008-06-23 22:21:20 +0000653 void InitializeClassMethodSummaries();
654 void InitializeMethodSummaries();
Ted Kremenekcc3d1882008-10-23 01:56:15 +0000655private:
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000656 void addNSObjectClsMethSummary(Selector S, const RetainSummary *Summ) {
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000657 ObjCClassMethodSummaries[S] = Summ;
658 }
Mike Stump11289f42009-09-09 15:08:12 +0000659
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000660 void addNSObjectMethSummary(Selector S, const RetainSummary *Summ) {
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000661 ObjCMethodSummaries[S] = Summ;
662 }
Ted Kremenek00dfe302009-03-04 23:30:42 +0000663
Ted Kremeneke8a5ba82012-02-18 21:37:48 +0000664 void addClassMethSummary(const char* Cls, const char* name,
665 const RetainSummary *Summ, bool isNullary = true) {
Ted Kremenek00dfe302009-03-04 23:30:42 +0000666 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
Ted Kremeneke8a5ba82012-02-18 21:37:48 +0000667 Selector S = isNullary ? GetNullarySelector(name, Ctx)
668 : GetUnarySelector(name, Ctx);
Ted Kremenek00dfe302009-03-04 23:30:42 +0000669 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
670 }
Mike Stump11289f42009-09-09 15:08:12 +0000671
Ted Kremenekdce78462009-02-25 02:54:57 +0000672 void addInstMethSummary(const char* Cls, const char* nullaryName,
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000673 const RetainSummary *Summ) {
Ted Kremenekdce78462009-02-25 02:54:57 +0000674 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
675 Selector S = GetNullarySelector(nullaryName, Ctx);
676 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
677 }
Mike Stump11289f42009-09-09 15:08:12 +0000678
Jordan Rose0675c872014-04-09 01:39:22 +0000679 void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy &Summaries,
680 const RetainSummary *Summ, va_list argp) {
681 Selector S = getKeywordSelector(Ctx, argp);
Ted Kremenek8a5ad392009-04-24 17:50:11 +0000682 Summaries[ObjCSummaryKey(ClsII, S)] = Summ;
Ted Kremenek3b2294c2008-07-18 17:24:20 +0000683 }
Mike Stump11289f42009-09-09 15:08:12 +0000684
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000685 void addInstMethSummary(const char* Cls, const RetainSummary * Summ, ...) {
Ted Kremenek3f13f592008-08-12 18:48:50 +0000686 va_list argp;
687 va_start(argp, Summ);
Ted Kremenek8a5ad392009-04-24 17:50:11 +0000688 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Mike Stump11289f42009-09-09 15:08:12 +0000689 va_end(argp);
Ted Kremenek3f13f592008-08-12 18:48:50 +0000690 }
Mike Stump11289f42009-09-09 15:08:12 +0000691
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000692 void addClsMethSummary(const char* Cls, const RetainSummary * Summ, ...) {
Ted Kremenek8a5ad392009-04-24 17:50:11 +0000693 va_list argp;
694 va_start(argp, Summ);
695 addMethodSummary(&Ctx.Idents.get(Cls),ObjCClassMethodSummaries, Summ, argp);
696 va_end(argp);
697 }
Mike Stump11289f42009-09-09 15:08:12 +0000698
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000699 void addClsMethSummary(IdentifierInfo *II, const RetainSummary * Summ, ...) {
Ted Kremenek8a5ad392009-04-24 17:50:11 +0000700 va_list argp;
701 va_start(argp, Summ);
702 addMethodSummary(II, ObjCClassMethodSummaries, Summ, argp);
703 va_end(argp);
704 }
705
Ted Kremenek819e9b62008-03-11 06:39:11 +0000706public:
Mike Stump11289f42009-09-09 15:08:12 +0000707
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000708 RetainSummaryManager(ASTContext &ctx, bool gcenabled, bool usesARC)
Ted Kremenekab54e512008-07-01 17:21:27 +0000709 : Ctx(ctx),
John McCall31168b02011-06-15 23:02:42 +0000710 GCEnabled(gcenabled),
711 ARCEnabled(usesARC),
712 AF(BPAlloc), ScratchArgs(AF.getEmptyMap()),
713 ObjCAllocRetE(gcenabled
714 ? RetEffect::MakeGCNotOwned()
Jordan Rose6ad4cb42014-01-07 21:39:41 +0000715 : (usesARC ? RetEffect::MakeNotOwned(RetEffect::ObjC)
John McCall31168b02011-06-15 23:02:42 +0000716 : RetEffect::MakeOwned(RetEffect::ObjC, true))),
717 ObjCInitRetE(gcenabled
718 ? RetEffect::MakeGCNotOwned()
Jordan Rose6ad4cb42014-01-07 21:39:41 +0000719 : (usesARC ? RetEffect::MakeNotOwned(RetEffect::ObjC)
Jordy Rose61c974b2012-03-18 01:26:10 +0000720 : RetEffect::MakeOwnedWhenTrackedReceiver())) {
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000721 InitializeClassMethodSummaries();
722 InitializeMethodSummaries();
723 }
Mike Stump11289f42009-09-09 15:08:12 +0000724
Jordan Roseeec15392012-07-02 19:27:43 +0000725 const RetainSummary *getSummary(const CallEvent &Call,
Craig Topper0dbb7832014-05-27 02:45:47 +0000726 ProgramStateRef State = nullptr);
Mike Stump11289f42009-09-09 15:08:12 +0000727
Jordan Roseeec15392012-07-02 19:27:43 +0000728 const RetainSummary *getFunctionSummary(const FunctionDecl *FD);
729
730 const RetainSummary *getMethodSummary(Selector S, const ObjCInterfaceDecl *ID,
Jordy Rose35e71c72012-03-17 21:13:07 +0000731 const ObjCMethodDecl *MD,
732 QualType RetTy,
733 ObjCMethodSummariesTy &CachedSummaries);
734
Jordan Rose6bad4902012-07-02 19:27:56 +0000735 const RetainSummary *getInstanceMethodSummary(const ObjCMethodCall &M,
Jordan Roseeec15392012-07-02 19:27:43 +0000736 ProgramStateRef State);
Ted Kremenekbd862712010-07-01 20:16:50 +0000737
Jordan Rose6bad4902012-07-02 19:27:56 +0000738 const RetainSummary *getClassMethodSummary(const ObjCMethodCall &M) {
Jordan Roseeec15392012-07-02 19:27:43 +0000739 assert(!M.isInstanceMessage());
740 const ObjCInterfaceDecl *Class = M.getReceiverInterface();
Mike Stump11289f42009-09-09 15:08:12 +0000741
Jordan Roseeec15392012-07-02 19:27:43 +0000742 return getMethodSummary(M.getSelector(), Class, M.getDecl(),
743 M.getResultType(), ObjCClassMethodSummaries);
Ted Kremenek7686ffa2009-04-29 00:42:39 +0000744 }
Ted Kremenek99fe1692009-04-29 17:17:48 +0000745
746 /// getMethodSummary - This version of getMethodSummary is used to query
747 /// the summary for the current method being analyzed.
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000748 const RetainSummary *getMethodSummary(const ObjCMethodDecl *MD) {
Ted Kremenek223a7d52009-04-29 23:03:22 +0000749 const ObjCInterfaceDecl *ID = MD->getClassInterface();
Ted Kremenekb2a143f2009-04-30 05:41:14 +0000750 Selector S = MD->getSelector();
Alp Toker314cc812014-01-25 16:55:45 +0000751 QualType ResultTy = MD->getReturnType();
Mike Stump11289f42009-09-09 15:08:12 +0000752
Jordy Rose35e71c72012-03-17 21:13:07 +0000753 ObjCMethodSummariesTy *CachedSummaries;
Ted Kremenek99fe1692009-04-29 17:17:48 +0000754 if (MD->isInstanceMethod())
Jordy Rose35e71c72012-03-17 21:13:07 +0000755 CachedSummaries = &ObjCMethodSummaries;
Ted Kremenek99fe1692009-04-29 17:17:48 +0000756 else
Jordy Rose35e71c72012-03-17 21:13:07 +0000757 CachedSummaries = &ObjCClassMethodSummaries;
758
Jordan Roseeec15392012-07-02 19:27:43 +0000759 return getMethodSummary(S, ID, MD, ResultTy, *CachedSummaries);
Ted Kremenek99fe1692009-04-29 17:17:48 +0000760 }
Mike Stump11289f42009-09-09 15:08:12 +0000761
Jordy Rose35e71c72012-03-17 21:13:07 +0000762 const RetainSummary *getStandardMethodSummary(const ObjCMethodDecl *MD,
Jordan Roseeec15392012-07-02 19:27:43 +0000763 Selector S, QualType RetTy);
Ted Kremenek223a7d52009-04-29 23:03:22 +0000764
Jordan Rose39032472013-04-04 22:31:48 +0000765 /// Determine if there is a special return effect for this function or method.
766 Optional<RetEffect> getRetEffectFromAnnotations(QualType RetTy,
767 const Decl *D);
768
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000769 void updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenekc2de7272009-05-09 02:58:13 +0000770 const ObjCMethodDecl *MD);
771
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000772 void updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenekc2de7272009-05-09 02:58:13 +0000773 const FunctionDecl *FD);
774
Jordan Roseeec15392012-07-02 19:27:43 +0000775 void updateSummaryForCall(const RetainSummary *&Summ,
776 const CallEvent &Call);
777
Ted Kremenek00daccd2008-05-05 22:11:16 +0000778 bool isGCEnabled() const { return GCEnabled; }
Mike Stump11289f42009-09-09 15:08:12 +0000779
John McCall31168b02011-06-15 23:02:42 +0000780 bool isARCEnabled() const { return ARCEnabled; }
781
782 bool isARCorGCEnabled() const { return GCEnabled || ARCEnabled; }
Jordan Roseeec15392012-07-02 19:27:43 +0000783
784 RetEffect getObjAllocRetEffect() const { return ObjCAllocRetE; }
785
786 friend class RetainSummaryTemplate;
Ted Kremenek819e9b62008-03-11 06:39:11 +0000787};
Mike Stump11289f42009-09-09 15:08:12 +0000788
Jordy Rose14de7c52011-08-24 09:02:37 +0000789// Used to avoid allocating long-term (BPAlloc'd) memory for default retain
790// summaries. If a function or method looks like it has a default summary, but
791// it has annotations, the annotations are added to the stack-based template
792// and then copied into managed memory.
793class RetainSummaryTemplate {
794 RetainSummaryManager &Manager;
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000795 const RetainSummary *&RealSummary;
Jordy Rose14de7c52011-08-24 09:02:37 +0000796 RetainSummary ScratchSummary;
797 bool Accessed;
798public:
Jordan Roseeec15392012-07-02 19:27:43 +0000799 RetainSummaryTemplate(const RetainSummary *&real, RetainSummaryManager &mgr)
800 : Manager(mgr), RealSummary(real), ScratchSummary(*real), Accessed(false) {}
Jordy Rose14de7c52011-08-24 09:02:37 +0000801
802 ~RetainSummaryTemplate() {
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000803 if (Accessed)
Jordy Rose61c974b2012-03-18 01:26:10 +0000804 RealSummary = Manager.getPersistentSummary(ScratchSummary);
Jordy Rose14de7c52011-08-24 09:02:37 +0000805 }
806
807 RetainSummary &operator*() {
808 Accessed = true;
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000809 return ScratchSummary;
Jordy Rose14de7c52011-08-24 09:02:37 +0000810 }
811
812 RetainSummary *operator->() {
813 Accessed = true;
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000814 return &ScratchSummary;
Jordy Rose14de7c52011-08-24 09:02:37 +0000815 }
816};
817
Ted Kremenek819e9b62008-03-11 06:39:11 +0000818} // end anonymous namespace
819
820//===----------------------------------------------------------------------===//
821// Implementation of checker data structures.
822//===----------------------------------------------------------------------===//
823
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000824ArgEffects RetainSummaryManager::getArgEffects() {
825 ArgEffects AE = ScratchArgs;
Ted Kremenekb3b56c62010-11-24 00:54:37 +0000826 ScratchArgs = AF.getEmptyMap();
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000827 return AE;
Ted Kremenek68d73d12008-03-12 01:21:45 +0000828}
829
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000830const RetainSummary *
Jordy Rose61c974b2012-03-18 01:26:10 +0000831RetainSummaryManager::getPersistentSummary(const RetainSummary &OldSumm) {
832 // Unique "simple" summaries -- those without ArgEffects.
833 if (OldSumm.isSimple()) {
834 llvm::FoldingSetNodeID ID;
835 OldSumm.Profile(ID);
836
837 void *Pos;
838 CachedSummaryNode *N = SimpleSummaries.FindNodeOrInsertPos(ID, Pos);
839
840 if (!N) {
841 N = (CachedSummaryNode *) BPAlloc.Allocate<CachedSummaryNode>();
842 new (N) CachedSummaryNode(OldSumm);
843 SimpleSummaries.InsertNode(N, Pos);
844 }
845
846 return &N->getValue();
847 }
848
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000849 RetainSummary *Summ = (RetainSummary *) BPAlloc.Allocate<RetainSummary>();
Jordy Rose61c974b2012-03-18 01:26:10 +0000850 new (Summ) RetainSummary(OldSumm);
Ted Kremenek68d73d12008-03-12 01:21:45 +0000851 return Summ;
852}
853
Ted Kremenek00daccd2008-05-05 22:11:16 +0000854//===----------------------------------------------------------------------===//
855// Summary creation for functions (largely uses of Core Foundation).
856//===----------------------------------------------------------------------===//
Ted Kremenek68d73d12008-03-12 01:21:45 +0000857
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000858static bool isRetain(const FunctionDecl *FD, StringRef FName) {
Benjamin Kramereaabbd82010-02-08 18:38:55 +0000859 return FName.endswith("Retain");
Ted Kremenek7e904222009-01-12 21:45:02 +0000860}
861
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000862static bool isRelease(const FunctionDecl *FD, StringRef FName) {
Benjamin Kramereaabbd82010-02-08 18:38:55 +0000863 return FName.endswith("Release");
Ted Kremenek7e904222009-01-12 21:45:02 +0000864}
865
Jordan Rose77411322013-10-07 17:16:52 +0000866static bool isAutorelease(const FunctionDecl *FD, StringRef FName) {
867 return FName.endswith("Autorelease");
868}
869
Jordy Rose898a1482011-08-21 21:58:18 +0000870static bool isMakeCollectable(const FunctionDecl *FD, StringRef FName) {
871 // FIXME: Remove FunctionDecl parameter.
872 // FIXME: Is it really okay if MakeCollectable isn't a suffix?
873 return FName.find("MakeCollectable") != StringRef::npos;
874}
875
Anna Zaks25612732012-08-29 23:23:43 +0000876static ArgEffect getStopTrackingHardEquivalent(ArgEffect E) {
Jordan Roseeec15392012-07-02 19:27:43 +0000877 switch (E) {
878 case DoNothing:
879 case Autorelease:
Benjamin Kramer2501f142013-10-20 11:47:15 +0000880 case DecRefBridgedTransferred:
Jordan Roseeec15392012-07-02 19:27:43 +0000881 case IncRef:
882 case IncRefMsg:
883 case MakeCollectable:
884 case MayEscape:
Jordan Roseeec15392012-07-02 19:27:43 +0000885 case StopTracking:
Anna Zaks25612732012-08-29 23:23:43 +0000886 case StopTrackingHard:
887 return StopTrackingHard;
Jordan Roseeec15392012-07-02 19:27:43 +0000888 case DecRef:
Anna Zaks25612732012-08-29 23:23:43 +0000889 case DecRefAndStopTrackingHard:
890 return DecRefAndStopTrackingHard;
Jordan Roseeec15392012-07-02 19:27:43 +0000891 case DecRefMsg:
Anna Zaks25612732012-08-29 23:23:43 +0000892 case DecRefMsgAndStopTrackingHard:
893 return DecRefMsgAndStopTrackingHard;
Jordan Roseeec15392012-07-02 19:27:43 +0000894 case Dealloc:
895 return Dealloc;
896 }
897
898 llvm_unreachable("Unknown ArgEffect kind");
899}
900
901void RetainSummaryManager::updateSummaryForCall(const RetainSummary *&S,
902 const CallEvent &Call) {
903 if (Call.hasNonZeroCallbackArg()) {
Anna Zaks25612732012-08-29 23:23:43 +0000904 ArgEffect RecEffect =
905 getStopTrackingHardEquivalent(S->getReceiverEffect());
906 ArgEffect DefEffect =
907 getStopTrackingHardEquivalent(S->getDefaultArgEffect());
Jordan Roseeec15392012-07-02 19:27:43 +0000908
909 ArgEffects CustomArgEffects = S->getArgEffects();
910 for (ArgEffects::iterator I = CustomArgEffects.begin(),
911 E = CustomArgEffects.end();
912 I != E; ++I) {
Anna Zaks25612732012-08-29 23:23:43 +0000913 ArgEffect Translated = getStopTrackingHardEquivalent(I->second);
Jordan Roseeec15392012-07-02 19:27:43 +0000914 if (Translated != DefEffect)
915 ScratchArgs = AF.add(ScratchArgs, I->first, Translated);
916 }
917
Anna Zaks25612732012-08-29 23:23:43 +0000918 RetEffect RE = RetEffect::MakeNoRetHard();
Jordan Roseeec15392012-07-02 19:27:43 +0000919
920 // Special cases where the callback argument CANNOT free the return value.
921 // This can generally only happen if we know that the callback will only be
922 // called when the return value is already being deallocated.
Jordan Rose2a833ca2014-01-15 17:25:15 +0000923 if (const SimpleFunctionCall *FC = dyn_cast<SimpleFunctionCall>(&Call)) {
Jordan Roseccf192e2012-09-01 17:39:13 +0000924 if (IdentifierInfo *Name = FC->getDecl()->getIdentifier()) {
925 // When the CGBitmapContext is deallocated, the callback here will free
926 // the associated data buffer.
Jordan Rosed65f1c82012-08-31 18:19:18 +0000927 if (Name->isStr("CGBitmapContextCreateWithData"))
928 RE = S->getRetEffect();
Jordan Roseccf192e2012-09-01 17:39:13 +0000929 }
Jordan Roseeec15392012-07-02 19:27:43 +0000930 }
931
932 S = getPersistentSummary(RE, RecEffect, DefEffect);
933 }
Anna Zaks3d5d3d32012-08-24 00:06:12 +0000934
935 // Special case '[super init];' and '[self init];'
936 //
937 // Even though calling '[super init]' without assigning the result to self
938 // and checking if the parent returns 'nil' is a bad pattern, it is common.
939 // Additionally, our Self Init checker already warns about it. To avoid
940 // overwhelming the user with messages from both checkers, we model the case
941 // of '[super init]' in cases when it is not consumed by another expression
942 // as if the call preserves the value of 'self'; essentially, assuming it can
943 // never fail and return 'nil'.
944 // Note, we don't want to just stop tracking the value since we want the
945 // RetainCount checker to report leaks and use-after-free if SelfInit checker
946 // is turned off.
947 if (const ObjCMethodCall *MC = dyn_cast<ObjCMethodCall>(&Call)) {
948 if (MC->getMethodFamily() == OMF_init && MC->isReceiverSelfOrSuper()) {
949
950 // Check if the message is not consumed, we know it will not be used in
951 // an assignment, ex: "self = [super init]".
952 const Expr *ME = MC->getOriginExpr();
953 const LocationContext *LCtx = MC->getLocationContext();
954 ParentMap &PM = LCtx->getAnalysisDeclContext()->getParentMap();
955 if (!PM.isConsumedExpr(ME)) {
956 RetainSummaryTemplate ModifiableSummaryTemplate(S, *this);
957 ModifiableSummaryTemplate->setReceiverEffect(DoNothing);
958 ModifiableSummaryTemplate->setRetEffect(RetEffect::MakeNoRet());
959 }
960 }
961
962 }
Jordan Roseeec15392012-07-02 19:27:43 +0000963}
964
Anna Zaksf4c5ea52012-05-04 22:18:39 +0000965const RetainSummary *
Jordan Roseeec15392012-07-02 19:27:43 +0000966RetainSummaryManager::getSummary(const CallEvent &Call,
967 ProgramStateRef State) {
968 const RetainSummary *Summ;
969 switch (Call.getKind()) {
970 case CE_Function:
Jordan Rose2a833ca2014-01-15 17:25:15 +0000971 Summ = getFunctionSummary(cast<SimpleFunctionCall>(Call).getDecl());
Jordan Roseeec15392012-07-02 19:27:43 +0000972 break;
973 case CE_CXXMember:
Jordan Rose017591a2012-07-03 22:55:57 +0000974 case CE_CXXMemberOperator:
Jordan Roseeec15392012-07-02 19:27:43 +0000975 case CE_Block:
976 case CE_CXXConstructor:
Jordan Rose4ee71b82012-07-10 22:07:47 +0000977 case CE_CXXDestructor:
Jordan Rosea4ee0642012-07-02 22:21:47 +0000978 case CE_CXXAllocator:
Jordan Roseeec15392012-07-02 19:27:43 +0000979 // FIXME: These calls are currently unsupported.
980 return getPersistentStopSummary();
Jordan Rose627b0462012-07-18 21:59:51 +0000981 case CE_ObjCMessage: {
Jordan Rose6bad4902012-07-02 19:27:56 +0000982 const ObjCMethodCall &Msg = cast<ObjCMethodCall>(Call);
Jordan Roseeec15392012-07-02 19:27:43 +0000983 if (Msg.isInstanceMessage())
984 Summ = getInstanceMethodSummary(Msg, State);
985 else
986 Summ = getClassMethodSummary(Msg);
987 break;
988 }
989 }
990
991 updateSummaryForCall(Summ, Call);
992
993 assert(Summ && "Unknown call type?");
994 return Summ;
995}
996
997const RetainSummary *
998RetainSummaryManager::getFunctionSummary(const FunctionDecl *FD) {
999 // If we don't know what function we're calling, use our default summary.
1000 if (!FD)
1001 return getDefaultSummary();
1002
Ted Kremenekf7141592008-04-24 17:22:33 +00001003 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremenek00daccd2008-05-05 22:11:16 +00001004 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremenek00daccd2008-05-05 22:11:16 +00001005 if (I != FuncSummaries.end())
Ted Kremenekf7141592008-04-24 17:22:33 +00001006 return I->second;
1007
Ted Kremenekdf76e6d2009-05-04 15:34:07 +00001008 // No summary? Generate one.
Craig Topper0dbb7832014-05-27 02:45:47 +00001009 const RetainSummary *S = nullptr;
Jordan Rose1c715602012-08-06 21:28:02 +00001010 bool AllowAnnotations = true;
Mike Stump11289f42009-09-09 15:08:12 +00001011
Ted Kremenekfa89e2f2008-07-15 16:50:12 +00001012 do {
Ted Kremenek7e904222009-01-12 21:45:02 +00001013 // We generate "stop" summaries for implicitly defined functions.
1014 if (FD->isImplicit()) {
1015 S = getPersistentStopSummary();
1016 break;
Ted Kremenekfa89e2f2008-07-15 16:50:12 +00001017 }
Mike Stump11289f42009-09-09 15:08:12 +00001018
John McCall9dd450b2009-09-21 23:43:11 +00001019 // [PR 3337] Use 'getAs<FunctionType>' to strip away any typedefs on the
Ted Kremenek86afde32009-01-16 18:40:33 +00001020 // function's type.
John McCall9dd450b2009-09-21 23:43:11 +00001021 const FunctionType* FT = FD->getType()->getAs<FunctionType>();
Ted Kremenek9bcc2642009-12-16 06:06:43 +00001022 const IdentifierInfo *II = FD->getIdentifier();
1023 if (!II)
1024 break;
Benjamin Kramereaabbd82010-02-08 18:38:55 +00001025
1026 StringRef FName = II->getName();
Mike Stump11289f42009-09-09 15:08:12 +00001027
Ted Kremenek5f968932009-03-05 22:11:14 +00001028 // Strip away preceding '_'. Doing this here will effect all the checks
1029 // down below.
Benjamin Kramereaabbd82010-02-08 18:38:55 +00001030 FName = FName.substr(FName.find_first_not_of('_'));
Mike Stump11289f42009-09-09 15:08:12 +00001031
Ted Kremenek7e904222009-01-12 21:45:02 +00001032 // Inspect the result type.
Alp Toker314cc812014-01-25 16:55:45 +00001033 QualType RetTy = FT->getReturnType();
Mike Stump11289f42009-09-09 15:08:12 +00001034
Ted Kremenek7e904222009-01-12 21:45:02 +00001035 // FIXME: This should all be refactored into a chain of "summary lookup"
1036 // filters.
Ted Kremenekb4ec3fc2009-10-14 00:27:24 +00001037 assert(ScratchArgs.isEmpty());
Ted Kremenek3092e9c2009-06-15 20:36:07 +00001038
Ted Kremenek01d152f2012-04-26 04:32:23 +00001039 if (FName == "pthread_create" || FName == "pthread_setspecific") {
1040 // Part of: <rdar://problem/7299394> and <rdar://problem/11282706>.
1041 // This will be addressed better with IPA.
Benjamin Kramereaabbd82010-02-08 18:38:55 +00001042 S = getPersistentStopSummary();
1043 } else if (FName == "NSMakeCollectable") {
1044 // Handle: id NSMakeCollectable(CFTypeRef)
1045 S = (RetTy->isObjCIdType())
1046 ? getUnarySummary(FT, cfmakecollectable)
1047 : getPersistentStopSummary();
Jordan Rose1c715602012-08-06 21:28:02 +00001048 // The headers on OS X 10.8 use cf_consumed/ns_returns_retained,
1049 // but we can fully model NSMakeCollectable ourselves.
1050 AllowAnnotations = false;
Ted Kremenekc008db92012-09-06 23:47:02 +00001051 } else if (FName == "CFPlugInInstanceCreate") {
1052 S = getPersistentSummary(RetEffect::MakeNoRet());
Benjamin Kramereaabbd82010-02-08 18:38:55 +00001053 } else if (FName == "IOBSDNameMatching" ||
1054 FName == "IOServiceMatching" ||
1055 FName == "IOServiceNameMatching" ||
Ted Kremenek555560c2012-05-01 05:28:27 +00001056 FName == "IORegistryEntrySearchCFProperty" ||
Benjamin Kramereaabbd82010-02-08 18:38:55 +00001057 FName == "IORegistryEntryIDMatching" ||
1058 FName == "IOOpenFirmwarePathMatching") {
1059 // Part of <rdar://problem/6961230>. (IOKit)
1060 // This should be addressed using a API table.
1061 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1062 DoNothing, DoNothing);
1063 } else if (FName == "IOServiceGetMatchingService" ||
1064 FName == "IOServiceGetMatchingServices") {
1065 // FIXES: <rdar://problem/6326900>
1066 // This should be addressed using a API table. This strcmp is also
1067 // a little gross, but there is no need to super optimize here.
Ted Kremenekb3b56c62010-11-24 00:54:37 +00001068 ScratchArgs = AF.add(ScratchArgs, 1, DecRef);
Benjamin Kramereaabbd82010-02-08 18:38:55 +00001069 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1070 } else if (FName == "IOServiceAddNotification" ||
1071 FName == "IOServiceAddMatchingNotification") {
1072 // Part of <rdar://problem/6961230>. (IOKit)
1073 // This should be addressed using a API table.
Ted Kremenekb3b56c62010-11-24 00:54:37 +00001074 ScratchArgs = AF.add(ScratchArgs, 2, DecRef);
Benjamin Kramereaabbd82010-02-08 18:38:55 +00001075 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1076 } else if (FName == "CVPixelBufferCreateWithBytes") {
1077 // FIXES: <rdar://problem/7283567>
1078 // Eventually this can be improved by recognizing that the pixel
1079 // buffer passed to CVPixelBufferCreateWithBytes is released via
1080 // a callback and doing full IPA to make sure this is done correctly.
1081 // FIXME: This function has an out parameter that returns an
1082 // allocated object.
Ted Kremenekb3b56c62010-11-24 00:54:37 +00001083 ScratchArgs = AF.add(ScratchArgs, 7, StopTracking);
Benjamin Kramereaabbd82010-02-08 18:38:55 +00001084 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1085 } else if (FName == "CGBitmapContextCreateWithData") {
1086 // FIXES: <rdar://problem/7358899>
1087 // Eventually this can be improved by recognizing that 'releaseInfo'
1088 // passed to CGBitmapContextCreateWithData is released via
1089 // a callback and doing full IPA to make sure this is done correctly.
Ted Kremenekb3b56c62010-11-24 00:54:37 +00001090 ScratchArgs = AF.add(ScratchArgs, 8, StopTracking);
Benjamin Kramereaabbd82010-02-08 18:38:55 +00001091 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1092 DoNothing, DoNothing);
1093 } else if (FName == "CVPixelBufferCreateWithPlanarBytes") {
1094 // FIXES: <rdar://problem/7283567>
1095 // Eventually this can be improved by recognizing that the pixel
1096 // buffer passed to CVPixelBufferCreateWithPlanarBytes is released
1097 // via a callback and doing full IPA to make sure this is done
1098 // correctly.
Ted Kremenekb3b56c62010-11-24 00:54:37 +00001099 ScratchArgs = AF.add(ScratchArgs, 12, StopTracking);
Benjamin Kramereaabbd82010-02-08 18:38:55 +00001100 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Jordan Roseb1479182013-05-02 01:51:40 +00001101 } else if (FName == "dispatch_set_context" ||
1102 FName == "xpc_connection_set_context") {
Ted Kremenek40c13432012-03-22 06:29:41 +00001103 // <rdar://problem/11059275> - The analyzer currently doesn't have
1104 // a good way to reason about the finalizer function for libdispatch.
1105 // If we pass a context object that is memory managed, stop tracking it.
Jordan Roseb1479182013-05-02 01:51:40 +00001106 // <rdar://problem/13783514> - Same problem, but for XPC.
Ted Kremenek40c13432012-03-22 06:29:41 +00001107 // FIXME: this hack should possibly go away once we can handle
Jordan Roseb1479182013-05-02 01:51:40 +00001108 // libdispatch and XPC finalizers.
Ted Kremenek40c13432012-03-22 06:29:41 +00001109 ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
1110 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenekececf9f2012-05-08 00:12:09 +00001111 } else if (FName.startswith("NSLog")) {
1112 S = getDoNothingSummary();
Anna Zaks90ab9bf2012-03-30 05:48:16 +00001113 } else if (FName.startswith("NS") &&
1114 (FName.find("Insert") != StringRef::npos)) {
1115 // Whitelist NSXXInsertXX, for example NSMapInsertIfAbsent, since they can
1116 // be deallocated by NSMapRemove. (radar://11152419)
1117 ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
1118 ScratchArgs = AF.add(ScratchArgs, 2, StopTracking);
1119 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenekea675cf2009-06-11 18:17:24 +00001120 }
Mike Stump11289f42009-09-09 15:08:12 +00001121
Ted Kremenekea675cf2009-06-11 18:17:24 +00001122 // Did we get a summary?
1123 if (S)
1124 break;
Ted Kremenek211094d2009-03-17 22:43:44 +00001125
Jordan Rose85707b22013-03-04 23:21:32 +00001126 if (RetTy->isPointerType()) {
Ted Kremenek7e904222009-01-12 21:45:02 +00001127 // For CoreFoundation ('CF') types.
Ted Kremeneke9918352010-01-27 18:00:17 +00001128 if (cocoa::isRefType(RetTy, "CF", FName)) {
Jordan Rose77411322013-10-07 17:16:52 +00001129 if (isRetain(FD, FName)) {
Ted Kremenek7e904222009-01-12 21:45:02 +00001130 S = getUnarySummary(FT, cfretain);
Jordan Rose77411322013-10-07 17:16:52 +00001131 } else if (isAutorelease(FD, FName)) {
1132 S = getUnarySummary(FT, cfautorelease);
1133 // The headers use cf_consumed, but we can fully model CFAutorelease
1134 // ourselves.
1135 AllowAnnotations = false;
1136 } else if (isMakeCollectable(FD, FName)) {
Ted Kremenek7e904222009-01-12 21:45:02 +00001137 S = getUnarySummary(FT, cfmakecollectable);
Jordan Rose77411322013-10-07 17:16:52 +00001138 AllowAnnotations = false;
1139 } else {
John McCall525f0552011-10-01 00:48:56 +00001140 S = getCFCreateGetRuleSummary(FD);
Jordan Rose77411322013-10-07 17:16:52 +00001141 }
Ted Kremenek7e904222009-01-12 21:45:02 +00001142
1143 break;
1144 }
1145
1146 // For CoreGraphics ('CG') types.
Ted Kremeneke9918352010-01-27 18:00:17 +00001147 if (cocoa::isRefType(RetTy, "CG", FName)) {
Ted Kremenek7e904222009-01-12 21:45:02 +00001148 if (isRetain(FD, FName))
1149 S = getUnarySummary(FT, cfretain);
1150 else
John McCall525f0552011-10-01 00:48:56 +00001151 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek7e904222009-01-12 21:45:02 +00001152
1153 break;
1154 }
1155
1156 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
Ted Kremeneke9918352010-01-27 18:00:17 +00001157 if (cocoa::isRefType(RetTy, "DADisk") ||
1158 cocoa::isRefType(RetTy, "DADissenter") ||
1159 cocoa::isRefType(RetTy, "DASessionRef")) {
John McCall525f0552011-10-01 00:48:56 +00001160 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek7e904222009-01-12 21:45:02 +00001161 break;
1162 }
Mike Stump11289f42009-09-09 15:08:12 +00001163
Aaron Ballman9ead1242013-12-19 02:39:40 +00001164 if (FD->hasAttr<CFAuditedTransferAttr>()) {
Jordan Rose85707b22013-03-04 23:21:32 +00001165 S = getCFCreateGetRuleSummary(FD);
1166 break;
1167 }
1168
Ted Kremenek7e904222009-01-12 21:45:02 +00001169 break;
1170 }
1171
1172 // Check for release functions, the only kind of functions that we care
1173 // about that don't return a pointer type.
1174 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
Ted Kremenekac5ab792010-02-08 16:45:01 +00001175 // Test for 'CGCF'.
Benjamin Kramereaabbd82010-02-08 18:38:55 +00001176 FName = FName.substr(FName.startswith("CGCF") ? 4 : 2);
Ted Kremenekac5ab792010-02-08 16:45:01 +00001177
Ted Kremenek5f968932009-03-05 22:11:14 +00001178 if (isRelease(FD, FName))
Ted Kremenek7e904222009-01-12 21:45:02 +00001179 S = getUnarySummary(FT, cfrelease);
1180 else {
Ted Kremenek7d79a5f2009-05-03 05:20:50 +00001181 assert (ScratchArgs.isEmpty());
Ted Kremeneked90de42009-01-29 22:45:13 +00001182 // Remaining CoreFoundation and CoreGraphics functions.
1183 // We use to assume that they all strictly followed the ownership idiom
1184 // and that ownership cannot be transferred. While this is technically
1185 // correct, many methods allow a tracked object to escape. For example:
1186 //
Mike Stump11289f42009-09-09 15:08:12 +00001187 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
Ted Kremeneked90de42009-01-29 22:45:13 +00001188 // CFDictionaryAddValue(y, key, x);
Mike Stump11289f42009-09-09 15:08:12 +00001189 // CFRelease(x);
Ted Kremeneked90de42009-01-29 22:45:13 +00001190 // ... it is okay to use 'x' since 'y' has a reference to it
1191 //
1192 // We handle this and similar cases with the follow heuristic. If the
Ted Kremenekd982f002009-08-20 00:57:22 +00001193 // function name contains "InsertValue", "SetValue", "AddValue",
1194 // "AppendValue", or "SetAttribute", then we assume that arguments may
1195 // "escape." This means that something else holds on to the object,
1196 // allowing it be used even after its local retain count drops to 0.
Benjamin Kramer0129bd72010-01-11 19:46:28 +00001197 ArgEffect E = (StrInStrNoCase(FName, "InsertValue") != StringRef::npos||
1198 StrInStrNoCase(FName, "AddValue") != StringRef::npos ||
1199 StrInStrNoCase(FName, "SetValue") != StringRef::npos ||
1200 StrInStrNoCase(FName, "AppendValue") != StringRef::npos||
Benjamin Kramer37808312010-01-11 20:15:06 +00001201 StrInStrNoCase(FName, "SetAttribute") != StringRef::npos)
Ted Kremeneked90de42009-01-29 22:45:13 +00001202 ? MayEscape : DoNothing;
Mike Stump11289f42009-09-09 15:08:12 +00001203
Ted Kremeneked90de42009-01-29 22:45:13 +00001204 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek7e904222009-01-12 21:45:02 +00001205 }
1206 }
Ted Kremenekfa89e2f2008-07-15 16:50:12 +00001207 }
1208 while (0);
Mike Stump11289f42009-09-09 15:08:12 +00001209
Jordan Roseeec15392012-07-02 19:27:43 +00001210 // If we got all the way here without any luck, use a default summary.
1211 if (!S)
1212 S = getDefaultSummary();
1213
Ted Kremenekc2de7272009-05-09 02:58:13 +00001214 // Annotations override defaults.
Jordan Rose1c715602012-08-06 21:28:02 +00001215 if (AllowAnnotations)
1216 updateSummaryFromAnnotations(S, FD);
Mike Stump11289f42009-09-09 15:08:12 +00001217
Ted Kremenek00daccd2008-05-05 22:11:16 +00001218 FuncSummaries[FD] = S;
Mike Stump11289f42009-09-09 15:08:12 +00001219 return S;
Ted Kremenekea6507f2008-03-06 00:08:09 +00001220}
1221
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001222const RetainSummary *
John McCall525f0552011-10-01 00:48:56 +00001223RetainSummaryManager::getCFCreateGetRuleSummary(const FunctionDecl *FD) {
1224 if (coreFoundation::followsCreateRule(FD))
Ted Kremenek875db812008-05-05 16:51:50 +00001225 return getCFSummaryCreateRule(FD);
Mike Stump11289f42009-09-09 15:08:12 +00001226
Ted Kremenek8e2c9b02011-05-25 06:19:45 +00001227 return getCFSummaryGetRule(FD);
Ted Kremenek875db812008-05-05 16:51:50 +00001228}
1229
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001230const RetainSummary *
Ted Kremenek82157a12009-02-23 16:51:39 +00001231RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1232 UnaryFuncKind func) {
1233
Ted Kremenek7e904222009-01-12 21:45:02 +00001234 // Sanity check that this is *really* a unary function. This can
1235 // happen if people do weird things.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001236 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
Alp Toker9cacbab2014-01-20 20:26:09 +00001237 if (!FTP || FTP->getNumParams() != 1)
Ted Kremenek7e904222009-01-12 21:45:02 +00001238 return getPersistentStopSummary();
Mike Stump11289f42009-09-09 15:08:12 +00001239
Ted Kremenek7d79a5f2009-05-03 05:20:50 +00001240 assert (ScratchArgs.isEmpty());
Mike Stump11289f42009-09-09 15:08:12 +00001241
Jordy Rose898a1482011-08-21 21:58:18 +00001242 ArgEffect Effect;
Ted Kremenek4b7ca772008-04-29 05:33:51 +00001243 switch (func) {
Jordan Rose77411322013-10-07 17:16:52 +00001244 case cfretain: Effect = IncRef; break;
1245 case cfrelease: Effect = DecRef; break;
1246 case cfautorelease: Effect = Autorelease; break;
1247 case cfmakecollectable: Effect = MakeCollectable; break;
Ted Kremenek4b772092008-04-10 23:44:06 +00001248 }
Jordy Rose898a1482011-08-21 21:58:18 +00001249
1250 ScratchArgs = AF.add(ScratchArgs, 0, Effect);
1251 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenek68d73d12008-03-12 01:21:45 +00001252}
1253
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001254const RetainSummary *
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001255RetainSummaryManager::getCFSummaryCreateRule(const FunctionDecl *FD) {
Ted Kremenek7d79a5f2009-05-03 05:20:50 +00001256 assert (ScratchArgs.isEmpty());
Mike Stump11289f42009-09-09 15:08:12 +00001257
Ted Kremenekaeb115f2009-01-28 05:56:51 +00001258 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenek68d73d12008-03-12 01:21:45 +00001259}
1260
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001261const RetainSummary *
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001262RetainSummaryManager::getCFSummaryGetRule(const FunctionDecl *FD) {
Mike Stump11289f42009-09-09 15:08:12 +00001263 assert (ScratchArgs.isEmpty());
Ted Kremenekaeb115f2009-01-28 05:56:51 +00001264 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1265 DoNothing, DoNothing);
Ted Kremenek68d73d12008-03-12 01:21:45 +00001266}
1267
Ted Kremenek819e9b62008-03-11 06:39:11 +00001268//===----------------------------------------------------------------------===//
Ted Kremenek00daccd2008-05-05 22:11:16 +00001269// Summary creation for Selectors.
1270//===----------------------------------------------------------------------===//
1271
Jordan Rose39032472013-04-04 22:31:48 +00001272Optional<RetEffect>
1273RetainSummaryManager::getRetEffectFromAnnotations(QualType RetTy,
1274 const Decl *D) {
1275 if (cocoa::isCocoaObjectRef(RetTy)) {
Aaron Ballman9ead1242013-12-19 02:39:40 +00001276 if (D->hasAttr<NSReturnsRetainedAttr>())
Jordan Rose39032472013-04-04 22:31:48 +00001277 return ObjCAllocRetE;
1278
Aaron Ballman9ead1242013-12-19 02:39:40 +00001279 if (D->hasAttr<NSReturnsNotRetainedAttr>() ||
1280 D->hasAttr<NSReturnsAutoreleasedAttr>())
Jordan Rose39032472013-04-04 22:31:48 +00001281 return RetEffect::MakeNotOwned(RetEffect::ObjC);
1282
1283 } else if (!RetTy->isPointerType()) {
1284 return None;
1285 }
1286
Aaron Ballman9ead1242013-12-19 02:39:40 +00001287 if (D->hasAttr<CFReturnsRetainedAttr>())
Jordan Rose39032472013-04-04 22:31:48 +00001288 return RetEffect::MakeOwned(RetEffect::CF, true);
1289
Aaron Ballman9ead1242013-12-19 02:39:40 +00001290 if (D->hasAttr<CFReturnsNotRetainedAttr>())
Jordan Rose39032472013-04-04 22:31:48 +00001291 return RetEffect::MakeNotOwned(RetEffect::CF);
1292
1293 return None;
1294}
1295
Ted Kremenekc2de7272009-05-09 02:58:13 +00001296void
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001297RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenekc2de7272009-05-09 02:58:13 +00001298 const FunctionDecl *FD) {
1299 if (!FD)
1300 return;
1301
Jordan Roseeec15392012-07-02 19:27:43 +00001302 assert(Summ && "Must have a summary to add annotations to.");
1303 RetainSummaryTemplate Template(Summ, *this);
Jordy Rose212e4592011-08-23 04:27:15 +00001304
Ted Kremenekafe348e2011-01-27 18:43:03 +00001305 // Effects on the parameters.
1306 unsigned parm_idx = 0;
1307 for (FunctionDecl::param_const_iterator pi = FD->param_begin(),
John McCall3337ca52011-04-06 09:02:12 +00001308 pe = FD->param_end(); pi != pe; ++pi, ++parm_idx) {
Ted Kremenekafe348e2011-01-27 18:43:03 +00001309 const ParmVarDecl *pd = *pi;
Aaron Ballman9ead1242013-12-19 02:39:40 +00001310 if (pd->hasAttr<NSConsumedAttr>())
Jordan Rose39032472013-04-04 22:31:48 +00001311 Template->addArg(AF, parm_idx, DecRefMsg);
Aaron Ballman9ead1242013-12-19 02:39:40 +00001312 else if (pd->hasAttr<CFConsumedAttr>())
Jordy Rose14de7c52011-08-24 09:02:37 +00001313 Template->addArg(AF, parm_idx, DecRef);
Ted Kremenekafe348e2011-01-27 18:43:03 +00001314 }
Alp Toker314cc812014-01-25 16:55:45 +00001315
1316 QualType RetTy = FD->getReturnType();
Jordan Rose39032472013-04-04 22:31:48 +00001317 if (Optional<RetEffect> RetE = getRetEffectFromAnnotations(RetTy, FD))
1318 Template->setRetEffect(*RetE);
Ted Kremenekc2de7272009-05-09 02:58:13 +00001319}
1320
1321void
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001322RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
1323 const ObjCMethodDecl *MD) {
Ted Kremenekc2de7272009-05-09 02:58:13 +00001324 if (!MD)
1325 return;
1326
Jordan Roseeec15392012-07-02 19:27:43 +00001327 assert(Summ && "Must have a valid summary to add annotations to");
1328 RetainSummaryTemplate Template(Summ, *this);
Mike Stump11289f42009-09-09 15:08:12 +00001329
Ted Kremenek0e898382011-01-27 06:54:14 +00001330 // Effects on the receiver.
Aaron Ballman9ead1242013-12-19 02:39:40 +00001331 if (MD->hasAttr<NSConsumesSelfAttr>())
Jordan Rose39032472013-04-04 22:31:48 +00001332 Template->setReceiverEffect(DecRefMsg);
Ted Kremenekafe348e2011-01-27 18:43:03 +00001333
1334 // Effects on the parameters.
1335 unsigned parm_idx = 0;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00001336 for (ObjCMethodDecl::param_const_iterator
1337 pi=MD->param_begin(), pe=MD->param_end();
Ted Kremenekafe348e2011-01-27 18:43:03 +00001338 pi != pe; ++pi, ++parm_idx) {
1339 const ParmVarDecl *pd = *pi;
Aaron Ballman9ead1242013-12-19 02:39:40 +00001340 if (pd->hasAttr<NSConsumedAttr>())
Jordan Rose39032472013-04-04 22:31:48 +00001341 Template->addArg(AF, parm_idx, DecRefMsg);
Aaron Ballman9ead1242013-12-19 02:39:40 +00001342 else if (pd->hasAttr<CFConsumedAttr>()) {
Jordy Rose14de7c52011-08-24 09:02:37 +00001343 Template->addArg(AF, parm_idx, DecRef);
Ted Kremenekafe348e2011-01-27 18:43:03 +00001344 }
Ted Kremenek0e898382011-01-27 06:54:14 +00001345 }
Alp Toker314cc812014-01-25 16:55:45 +00001346
1347 QualType RetTy = MD->getReturnType();
Jordan Rose39032472013-04-04 22:31:48 +00001348 if (Optional<RetEffect> RetE = getRetEffectFromAnnotations(RetTy, MD))
1349 Template->setRetEffect(*RetE);
Ted Kremenekc2de7272009-05-09 02:58:13 +00001350}
1351
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001352const RetainSummary *
Jordy Rose35e71c72012-03-17 21:13:07 +00001353RetainSummaryManager::getStandardMethodSummary(const ObjCMethodDecl *MD,
1354 Selector S, QualType RetTy) {
Jordy Rose70638832012-03-17 19:53:04 +00001355 // Any special effects?
Ted Kremenek6a966b22009-04-24 21:56:17 +00001356 ArgEffect ReceiverEff = DoNothing;
Jordy Rose70638832012-03-17 19:53:04 +00001357 RetEffect ResultEff = RetEffect::MakeNoRet();
1358
1359 // Check the method family, and apply any default annotations.
1360 switch (MD ? MD->getMethodFamily() : S.getMethodFamily()) {
1361 case OMF_None:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00001362 case OMF_initialize:
Jordy Rose70638832012-03-17 19:53:04 +00001363 case OMF_performSelector:
1364 // Assume all Objective-C methods follow Cocoa Memory Management rules.
1365 // FIXME: Does the non-threaded performSelector family really belong here?
1366 // The selector could be, say, @selector(copy).
1367 if (cocoa::isCocoaObjectRef(RetTy))
1368 ResultEff = RetEffect::MakeNotOwned(RetEffect::ObjC);
1369 else if (coreFoundation::isCFObjectRef(RetTy)) {
1370 // ObjCMethodDecl currently doesn't consider CF objects as valid return
1371 // values for alloc, new, copy, or mutableCopy, so we have to
1372 // double-check with the selector. This is ugly, but there aren't that
1373 // many Objective-C methods that return CF objects, right?
1374 if (MD) {
1375 switch (S.getMethodFamily()) {
1376 case OMF_alloc:
1377 case OMF_new:
1378 case OMF_copy:
1379 case OMF_mutableCopy:
1380 ResultEff = RetEffect::MakeOwned(RetEffect::CF, true);
1381 break;
1382 default:
1383 ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1384 break;
1385 }
1386 } else {
1387 ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1388 }
1389 }
1390 break;
1391 case OMF_init:
1392 ResultEff = ObjCInitRetE;
1393 ReceiverEff = DecRefMsg;
1394 break;
1395 case OMF_alloc:
1396 case OMF_new:
1397 case OMF_copy:
1398 case OMF_mutableCopy:
1399 if (cocoa::isCocoaObjectRef(RetTy))
1400 ResultEff = ObjCAllocRetE;
1401 else if (coreFoundation::isCFObjectRef(RetTy))
1402 ResultEff = RetEffect::MakeOwned(RetEffect::CF, true);
1403 break;
1404 case OMF_autorelease:
1405 ReceiverEff = Autorelease;
1406 break;
1407 case OMF_retain:
1408 ReceiverEff = IncRefMsg;
1409 break;
1410 case OMF_release:
1411 ReceiverEff = DecRefMsg;
1412 break;
1413 case OMF_dealloc:
1414 ReceiverEff = Dealloc;
1415 break;
1416 case OMF_self:
1417 // -self is handled specially by the ExprEngine to propagate the receiver.
1418 break;
1419 case OMF_retainCount:
1420 case OMF_finalize:
1421 // These methods don't return objects.
1422 break;
1423 }
Mike Stump11289f42009-09-09 15:08:12 +00001424
Ted Kremenek6a966b22009-04-24 21:56:17 +00001425 // If one of the arguments in the selector has the keyword 'delegate' we
1426 // should stop tracking the reference count for the receiver. This is
1427 // because the reference count is quite possibly handled by a delegate
1428 // method.
1429 if (S.isKeywordSelector()) {
Jordan Rose95dfae82012-06-15 18:19:52 +00001430 for (unsigned i = 0, e = S.getNumArgs(); i != e; ++i) {
1431 StringRef Slot = S.getNameForSlot(i);
1432 if (Slot.substr(Slot.size() - 8).equals_lower("delegate")) {
1433 if (ResultEff == ObjCInitRetE)
Anna Zaks25612732012-08-29 23:23:43 +00001434 ResultEff = RetEffect::MakeNoRetHard();
Jordan Rose95dfae82012-06-15 18:19:52 +00001435 else
Anna Zaks25612732012-08-29 23:23:43 +00001436 ReceiverEff = StopTrackingHard;
Jordan Rose95dfae82012-06-15 18:19:52 +00001437 }
1438 }
Ted Kremenek6a966b22009-04-24 21:56:17 +00001439 }
Mike Stump11289f42009-09-09 15:08:12 +00001440
Jordy Rose70638832012-03-17 19:53:04 +00001441 if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing &&
1442 ResultEff.getKind() == RetEffect::NoRet)
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001443 return getDefaultSummary();
Mike Stump11289f42009-09-09 15:08:12 +00001444
Jordy Rose70638832012-03-17 19:53:04 +00001445 return getPersistentSummary(ResultEff, ReceiverEff, MayEscape);
Ted Kremenek60746a02009-04-23 23:08:22 +00001446}
1447
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001448const RetainSummary *
Jordan Rose6bad4902012-07-02 19:27:56 +00001449RetainSummaryManager::getInstanceMethodSummary(const ObjCMethodCall &Msg,
Jordan Roseeec15392012-07-02 19:27:43 +00001450 ProgramStateRef State) {
Craig Topper0dbb7832014-05-27 02:45:47 +00001451 const ObjCInterfaceDecl *ReceiverClass = nullptr;
Ted Kremeneka2968e52009-11-13 01:54:21 +00001452
Jordan Roseeec15392012-07-02 19:27:43 +00001453 // We do better tracking of the type of the object than the core ExprEngine.
1454 // See if we have its type in our private state.
1455 // FIXME: Eventually replace the use of state->get<RefBindings> with
1456 // a generic API for reasoning about the Objective-C types of symbolic
1457 // objects.
1458 SVal ReceiverV = Msg.getReceiverSVal();
1459 if (SymbolRef Sym = ReceiverV.getAsLocSymbol())
Anna Zaksf5788c72012-08-14 00:36:15 +00001460 if (const RefVal *T = getRefBinding(State, Sym))
Douglas Gregor9a129192010-04-21 00:45:42 +00001461 if (const ObjCObjectPointerType *PT =
Jordan Roseeec15392012-07-02 19:27:43 +00001462 T->getType()->getAs<ObjCObjectPointerType>())
1463 ReceiverClass = PT->getInterfaceDecl();
1464
1465 // If we don't know what kind of object this is, fall back to its static type.
1466 if (!ReceiverClass)
1467 ReceiverClass = Msg.getReceiverInterface();
Douglas Gregor9a129192010-04-21 00:45:42 +00001468
Ted Kremeneka2968e52009-11-13 01:54:21 +00001469 // FIXME: The receiver could be a reference to a class, meaning that
1470 // we should use the class method.
Jordan Roseeec15392012-07-02 19:27:43 +00001471 // id x = [NSObject class];
1472 // [x performSelector:... withObject:... afterDelay:...];
1473 Selector S = Msg.getSelector();
1474 const ObjCMethodDecl *Method = Msg.getDecl();
1475 if (!Method && ReceiverClass)
1476 Method = ReceiverClass->getInstanceMethod(S);
1477
1478 return getMethodSummary(S, ReceiverClass, Method, Msg.getResultType(),
1479 ObjCMethodSummaries);
Ted Kremeneka2968e52009-11-13 01:54:21 +00001480}
1481
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001482const RetainSummary *
Jordan Roseeec15392012-07-02 19:27:43 +00001483RetainSummaryManager::getMethodSummary(Selector S, const ObjCInterfaceDecl *ID,
Jordy Rose35e71c72012-03-17 21:13:07 +00001484 const ObjCMethodDecl *MD, QualType RetTy,
1485 ObjCMethodSummariesTy &CachedSummaries) {
Ted Kremenekcb2e6362008-05-06 15:44:25 +00001486
Ted Kremenek0b50fb12009-04-29 05:04:30 +00001487 // Look up a summary in our summary cache.
Jordan Roseeec15392012-07-02 19:27:43 +00001488 const RetainSummary *Summ = CachedSummaries.find(ID, S);
Mike Stump11289f42009-09-09 15:08:12 +00001489
Ted Kremenek8be51382009-07-21 23:27:57 +00001490 if (!Summ) {
Jordy Rose35e71c72012-03-17 21:13:07 +00001491 Summ = getStandardMethodSummary(MD, S, RetTy);
Mike Stump11289f42009-09-09 15:08:12 +00001492
Ted Kremenek8be51382009-07-21 23:27:57 +00001493 // Annotations override defaults.
Jordy Rose212e4592011-08-23 04:27:15 +00001494 updateSummaryFromAnnotations(Summ, MD);
Mike Stump11289f42009-09-09 15:08:12 +00001495
Ted Kremenek8be51382009-07-21 23:27:57 +00001496 // Memoize the summary.
Jordan Roseeec15392012-07-02 19:27:43 +00001497 CachedSummaries[ObjCSummaryKey(ID, S)] = Summ;
Ted Kremenek8be51382009-07-21 23:27:57 +00001498 }
Mike Stump11289f42009-09-09 15:08:12 +00001499
Ted Kremenekf27110f2009-04-23 19:11:35 +00001500 return Summ;
Ted Kremenek767d0742008-05-06 21:26:51 +00001501}
1502
Mike Stump11289f42009-09-09 15:08:12 +00001503void RetainSummaryManager::InitializeClassMethodSummaries() {
Ted Kremenek9157fbb2009-05-07 23:40:42 +00001504 assert(ScratchArgs.isEmpty());
Mike Stump11289f42009-09-09 15:08:12 +00001505 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek55adb822009-10-15 22:25:12 +00001506 addClassMethSummary("NSAssertionHandler", "currentHandler",
Ted Kremenekaeb115f2009-01-28 05:56:51 +00001507 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Mike Stump11289f42009-09-09 15:08:12 +00001508
Ted Kremenek0747e7e2008-10-21 15:53:15 +00001509 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremenekb3b56c62010-11-24 00:54:37 +00001510 ScratchArgs = AF.add(ScratchArgs, 0, Autorelease);
Ted Kremenek55adb822009-10-15 22:25:12 +00001511 addClassMethSummary("NSAutoreleasePool", "addObject",
1512 getPersistentSummary(RetEffect::MakeNoRet(),
1513 DoNothing, Autorelease));
Ted Kremenek0806f912008-05-06 00:30:21 +00001514}
1515
Ted Kremenekea736c52008-06-23 22:21:20 +00001516void RetainSummaryManager::InitializeMethodSummaries() {
Mike Stump11289f42009-09-09 15:08:12 +00001517
1518 assert (ScratchArgs.isEmpty());
1519
Ted Kremenek767d0742008-05-06 21:26:51 +00001520 // Create the "init" selector. It just acts as a pass-through for the
1521 // receiver.
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001522 const RetainSummary *InitSumm = getPersistentSummary(ObjCInitRetE, DecRefMsg);
Ted Kremenek815fbb62009-08-20 05:13:36 +00001523 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
1524
1525 // awakeAfterUsingCoder: behaves basically like an 'init' method. It
1526 // claims the receiver and returns a retained object.
1527 addNSObjectMethSummary(GetUnarySelector("awakeAfterUsingCoder", Ctx),
1528 InitSumm);
Mike Stump11289f42009-09-09 15:08:12 +00001529
Ted Kremenek767d0742008-05-06 21:26:51 +00001530 // The next methods are allocators.
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001531 const RetainSummary *AllocSumm = getPersistentSummary(ObjCAllocRetE);
1532 const RetainSummary *CFAllocSumm =
Ted Kremenek52ac2b52009-08-28 19:52:12 +00001533 getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Mike Stump11289f42009-09-09 15:08:12 +00001534
Ted Kremenekb0862dc2008-05-06 02:26:56 +00001535 // Create the "retain" selector.
Jordy Rose3f7f75682011-08-21 19:41:36 +00001536 RetEffect NoRet = RetEffect::MakeNoRet();
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001537 const RetainSummary *Summ = getPersistentSummary(NoRet, IncRefMsg);
Ted Kremenek3185c9c2008-06-25 21:21:56 +00001538 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Mike Stump11289f42009-09-09 15:08:12 +00001539
Ted Kremenekb0862dc2008-05-06 02:26:56 +00001540 // Create the "release" selector.
Jordy Rose3f7f75682011-08-21 19:41:36 +00001541 Summ = getPersistentSummary(NoRet, DecRefMsg);
Ted Kremenek3185c9c2008-06-25 21:21:56 +00001542 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Mike Stump11289f42009-09-09 15:08:12 +00001543
Ted Kremenekea072e32009-03-17 19:42:23 +00001544 // Create the -dealloc summary.
Jordy Rose3f7f75682011-08-21 19:41:36 +00001545 Summ = getPersistentSummary(NoRet, Dealloc);
Ted Kremenekea072e32009-03-17 19:42:23 +00001546 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
Ted Kremenekb0862dc2008-05-06 02:26:56 +00001547
1548 // Create the "autorelease" selector.
Jordy Rose3f7f75682011-08-21 19:41:36 +00001549 Summ = getPersistentSummary(NoRet, Autorelease);
Ted Kremenek3185c9c2008-06-25 21:21:56 +00001550 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Mike Stump11289f42009-09-09 15:08:12 +00001551
Mike Stump11289f42009-09-09 15:08:12 +00001552 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremeneke73f2822009-02-23 02:51:29 +00001553 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1554 // self-own themselves. However, they only do this once they are displayed.
1555 // Thus, we need to track an NSWindow's display status.
1556 // This is tracked in <rdar://problem/6062711>.
Ted Kremenek00dfe302009-03-04 23:30:42 +00001557 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001558 const RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenek1272f702009-05-12 20:06:54 +00001559 StopTracking,
1560 StopTracking);
Mike Stump11289f42009-09-09 15:08:12 +00001561
Ted Kremenek751e7e32009-04-03 19:02:51 +00001562 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1563
Ted Kremenek3f13f592008-08-12 18:48:50 +00001564 // For NSPanel (which subclasses NSWindow), allocated objects are not
1565 // self-owned.
Ted Kremenek751e7e32009-04-03 19:02:51 +00001566 // FIXME: For now we don't track NSPanels. object for the same reason
1567 // as for NSWindow objects.
1568 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
Mike Stump11289f42009-09-09 15:08:12 +00001569
Ted Kremenek9b12e722014-01-03 01:19:28 +00001570 // For NSNull, objects returned by +null are singletons that ignore
1571 // retain/release semantics. Just don't track them.
1572 // <rdar://problem/12858915>
1573 addClassMethSummary("NSNull", "null", NoTrackYet);
1574
Jordan Rose95bf3b02013-01-31 22:06:02 +00001575 // Don't track allocated autorelease pools, as it is okay to prematurely
Ted Kremenek501ba032009-05-18 23:14:34 +00001576 // exit a method.
1577 addClassMethSummary("NSAutoreleasePool", "alloc", NoTrackYet);
Ted Kremeneke8a5ba82012-02-18 21:37:48 +00001578 addClassMethSummary("NSAutoreleasePool", "allocWithZone", NoTrackYet, false);
Jordan Rose95bf3b02013-01-31 22:06:02 +00001579 addClassMethSummary("NSAutoreleasePool", "new", NoTrackYet);
Ted Kremenek3185c9c2008-06-25 21:21:56 +00001580
Ted Kremenek10369122009-05-20 22:39:57 +00001581 // Create summaries QCRenderer/QCView -createSnapShotImageOfType:
1582 addInstMethSummary("QCRenderer", AllocSumm,
1583 "createSnapshotImageOfType", NULL);
1584 addInstMethSummary("QCView", AllocSumm,
1585 "createSnapshotImageOfType", NULL);
1586
Ted Kremenek96aa1462009-06-15 20:58:58 +00001587 // Create summaries for CIContext, 'createCGImage' and
Ted Kremenek52ac2b52009-08-28 19:52:12 +00001588 // 'createCGLayerWithSize'. These objects are CF objects, and are not
1589 // automatically garbage collected.
1590 addInstMethSummary("CIContext", CFAllocSumm,
Ted Kremenek10369122009-05-20 22:39:57 +00001591 "createCGImage", "fromRect", NULL);
Ted Kremenek52ac2b52009-08-28 19:52:12 +00001592 addInstMethSummary("CIContext", CFAllocSumm,
Mike Stump11289f42009-09-09 15:08:12 +00001593 "createCGImage", "fromRect", "format", "colorSpace", NULL);
Ted Kremenek52ac2b52009-08-28 19:52:12 +00001594 addInstMethSummary("CIContext", CFAllocSumm, "createCGLayerWithSize",
Ted Kremenek96aa1462009-06-15 20:58:58 +00001595 "info", NULL);
Ted Kremenekbe7c56e2008-05-06 00:38:54 +00001596}
1597
Ted Kremenek00daccd2008-05-05 22:11:16 +00001598//===----------------------------------------------------------------------===//
Ted Kremenek6bd78702009-04-29 18:50:19 +00001599// Error reporting.
1600//===----------------------------------------------------------------------===//
Ted Kremenek6bd78702009-04-29 18:50:19 +00001601namespace {
Jordy Rose20d4e682011-08-23 20:55:48 +00001602 typedef llvm::DenseMap<const ExplodedNode *, const RetainSummary *>
1603 SummaryLogTy;
1604
Ted Kremenek6bd78702009-04-29 18:50:19 +00001605 //===-------------===//
1606 // Bug Descriptions. //
Mike Stump11289f42009-09-09 15:08:12 +00001607 //===-------------===//
1608
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00001609 class CFRefBug : public BugType {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001610 protected:
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001611 CFRefBug(const CheckerBase *checker, StringRef name)
1612 : BugType(checker, name, categories::MemoryCoreFoundationObjectiveC) {}
1613
Ted Kremenek6bd78702009-04-29 18:50:19 +00001614 public:
Mike Stump11289f42009-09-09 15:08:12 +00001615
Ted Kremenek6bd78702009-04-29 18:50:19 +00001616 // FIXME: Eventually remove.
Jordy Rose7a534982011-08-24 05:47:39 +00001617 virtual const char *getDescription() const = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001618
Ted Kremenek6bd78702009-04-29 18:50:19 +00001619 virtual bool isLeak() const { return false; }
1620 };
Mike Stump11289f42009-09-09 15:08:12 +00001621
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00001622 class UseAfterRelease : public CFRefBug {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001623 public:
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001624 UseAfterRelease(const CheckerBase *checker)
1625 : CFRefBug(checker, "Use-after-release") {}
Mike Stump11289f42009-09-09 15:08:12 +00001626
Craig Topperfb6b25b2014-03-15 04:29:04 +00001627 const char *getDescription() const override {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001628 return "Reference-counted object is used after it is released";
Mike Stump11289f42009-09-09 15:08:12 +00001629 }
Ted Kremenek6bd78702009-04-29 18:50:19 +00001630 };
Mike Stump11289f42009-09-09 15:08:12 +00001631
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00001632 class BadRelease : public CFRefBug {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001633 public:
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001634 BadRelease(const CheckerBase *checker) : CFRefBug(checker, "Bad release") {}
Mike Stump11289f42009-09-09 15:08:12 +00001635
Craig Topperfb6b25b2014-03-15 04:29:04 +00001636 const char *getDescription() const override {
Ted Kremenek5c22e112009-10-01 17:31:50 +00001637 return "Incorrect decrement of the reference count of an object that is "
1638 "not owned at this point by the caller";
Ted Kremenek6bd78702009-04-29 18:50:19 +00001639 }
1640 };
Mike Stump11289f42009-09-09 15:08:12 +00001641
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00001642 class DeallocGC : public CFRefBug {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001643 public:
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001644 DeallocGC(const CheckerBase *checker)
1645 : CFRefBug(checker, "-dealloc called while using garbage collection") {}
Mike Stump11289f42009-09-09 15:08:12 +00001646
Craig Topperfb6b25b2014-03-15 04:29:04 +00001647 const char *getDescription() const override {
Ted Kremenekd35272f2009-05-09 00:10:05 +00001648 return "-dealloc called while using garbage collection";
Ted Kremenek6bd78702009-04-29 18:50:19 +00001649 }
1650 };
Mike Stump11289f42009-09-09 15:08:12 +00001651
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00001652 class DeallocNotOwned : public CFRefBug {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001653 public:
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001654 DeallocNotOwned(const CheckerBase *checker)
1655 : CFRefBug(checker, "-dealloc sent to non-exclusively owned object") {}
Mike Stump11289f42009-09-09 15:08:12 +00001656
Craig Topperfb6b25b2014-03-15 04:29:04 +00001657 const char *getDescription() const override {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001658 return "-dealloc sent to object that may be referenced elsewhere";
1659 }
Mike Stump11289f42009-09-09 15:08:12 +00001660 };
1661
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00001662 class OverAutorelease : public CFRefBug {
Ted Kremenekd35272f2009-05-09 00:10:05 +00001663 public:
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001664 OverAutorelease(const CheckerBase *checker)
1665 : CFRefBug(checker, "Object autoreleased too many times") {}
Mike Stump11289f42009-09-09 15:08:12 +00001666
Craig Topperfb6b25b2014-03-15 04:29:04 +00001667 const char *getDescription() const override {
Jordan Rose7467f062013-04-23 01:42:25 +00001668 return "Object autoreleased too many times";
Ted Kremenekd35272f2009-05-09 00:10:05 +00001669 }
1670 };
Mike Stump11289f42009-09-09 15:08:12 +00001671
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00001672 class ReturnedNotOwnedForOwned : public CFRefBug {
Ted Kremenekdee56e32009-05-10 06:25:57 +00001673 public:
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001674 ReturnedNotOwnedForOwned(const CheckerBase *checker)
1675 : CFRefBug(checker, "Method should return an owned object") {}
Mike Stump11289f42009-09-09 15:08:12 +00001676
Craig Topperfb6b25b2014-03-15 04:29:04 +00001677 const char *getDescription() const override {
Jordy Rose43426f82011-07-15 22:17:54 +00001678 return "Object with a +0 retain count returned to caller where a +1 "
Ted Kremenekdee56e32009-05-10 06:25:57 +00001679 "(owning) retain count is expected";
1680 }
1681 };
Mike Stump11289f42009-09-09 15:08:12 +00001682
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00001683 class Leak : public CFRefBug {
Benjamin Kramerd1d76b22012-06-06 17:32:50 +00001684 public:
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001685 Leak(const CheckerBase *checker, StringRef name) : CFRefBug(checker, name) {
Jordy Rose15484da2011-08-25 01:14:38 +00001686 // Leaks should not be reported if they are post-dominated by a sink.
1687 setSuppressOnSink(true);
1688 }
Mike Stump11289f42009-09-09 15:08:12 +00001689
Craig Topperfb6b25b2014-03-15 04:29:04 +00001690 const char *getDescription() const override { return ""; }
Mike Stump11289f42009-09-09 15:08:12 +00001691
Craig Topperfb6b25b2014-03-15 04:29:04 +00001692 bool isLeak() const override { return true; }
Ted Kremenek6bd78702009-04-29 18:50:19 +00001693 };
Mike Stump11289f42009-09-09 15:08:12 +00001694
Ted Kremenek6bd78702009-04-29 18:50:19 +00001695 //===---------===//
1696 // Bug Reports. //
1697 //===---------===//
Mike Stump11289f42009-09-09 15:08:12 +00001698
Jordy Rosef78877e2012-03-24 02:45:35 +00001699 class CFRefReportVisitor : public BugReporterVisitorImpl<CFRefReportVisitor> {
Anna Zaks88255cc2011-08-20 01:27:22 +00001700 protected:
Anna Zaks071a89c2011-08-19 23:21:56 +00001701 SymbolRef Sym;
Jordy Rose20d4e682011-08-23 20:55:48 +00001702 const SummaryLogTy &SummaryLog;
Jordy Rose7a534982011-08-24 05:47:39 +00001703 bool GCEnabled;
Anna Zaks88255cc2011-08-20 01:27:22 +00001704
Anna Zaks071a89c2011-08-19 23:21:56 +00001705 public:
Jordy Rose7a534982011-08-24 05:47:39 +00001706 CFRefReportVisitor(SymbolRef sym, bool gcEnabled, const SummaryLogTy &log)
1707 : Sym(sym), SummaryLog(log), GCEnabled(gcEnabled) {}
Anna Zaks071a89c2011-08-19 23:21:56 +00001708
Craig Topperfb6b25b2014-03-15 04:29:04 +00001709 void Profile(llvm::FoldingSetNodeID &ID) const override {
Anna Zaks071a89c2011-08-19 23:21:56 +00001710 static int x = 0;
1711 ID.AddPointer(&x);
1712 ID.AddPointer(Sym);
1713 }
1714
Craig Topperfb6b25b2014-03-15 04:29:04 +00001715 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
1716 const ExplodedNode *PrevN,
1717 BugReporterContext &BRC,
1718 BugReport &BR) override;
Anna Zaks88255cc2011-08-20 01:27:22 +00001719
David Blaikied15481c2014-08-29 18:18:43 +00001720 std::unique_ptr<PathDiagnosticPiece> getEndPath(BugReporterContext &BRC,
1721 const ExplodedNode *N,
1722 BugReport &BR) override;
Anna Zaks88255cc2011-08-20 01:27:22 +00001723 };
1724
1725 class CFRefLeakReportVisitor : public CFRefReportVisitor {
1726 public:
Jordy Rose7a534982011-08-24 05:47:39 +00001727 CFRefLeakReportVisitor(SymbolRef sym, bool GCEnabled,
Jordy Rose20d4e682011-08-23 20:55:48 +00001728 const SummaryLogTy &log)
Jordy Rose7a534982011-08-24 05:47:39 +00001729 : CFRefReportVisitor(sym, GCEnabled, log) {}
Anna Zaks88255cc2011-08-20 01:27:22 +00001730
David Blaikied15481c2014-08-29 18:18:43 +00001731 std::unique_ptr<PathDiagnosticPiece> getEndPath(BugReporterContext &BRC,
1732 const ExplodedNode *N,
1733 BugReport &BR) override;
Jordy Rosef78877e2012-03-24 02:45:35 +00001734
David Blaikie91e79022014-09-04 23:54:33 +00001735 std::unique_ptr<BugReporterVisitor> clone() const override {
Jordy Rosef78877e2012-03-24 02:45:35 +00001736 // The curiously-recurring template pattern only works for one level of
1737 // subclassing. Rather than make a new template base for
1738 // CFRefReportVisitor, we simply override clone() to do the right thing.
1739 // This could be trouble someday if BugReporterVisitorImpl is ever
1740 // used for something else besides a convenient implementation of clone().
David Blaikie91e79022014-09-04 23:54:33 +00001741 return llvm::make_unique<CFRefLeakReportVisitor>(*this);
Jordy Rosef78877e2012-03-24 02:45:35 +00001742 }
Anna Zaks071a89c2011-08-19 23:21:56 +00001743 };
1744
Anna Zaks3a6bdf82011-08-17 23:00:25 +00001745 class CFRefReport : public BugReport {
Jordy Rose184bd142011-08-24 22:39:09 +00001746 void addGCModeDescription(const LangOptions &LOpts, bool GCEnabled);
Jordy Rose7a534982011-08-24 05:47:39 +00001747
Ted Kremenek6bd78702009-04-29 18:50:19 +00001748 public:
Jordy Rose184bd142011-08-24 22:39:09 +00001749 CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1750 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1751 bool registerVisitor = true)
Anna Zaks752de142011-08-22 18:54:07 +00001752 : BugReport(D, D.getDescription(), n) {
Anna Zaks88255cc2011-08-20 01:27:22 +00001753 if (registerVisitor)
David Blaikie91e79022014-09-04 23:54:33 +00001754 addVisitor(llvm::make_unique<CFRefReportVisitor>(sym, GCEnabled, Log));
Jordy Rose184bd142011-08-24 22:39:09 +00001755 addGCModeDescription(LOpts, GCEnabled);
Anna Zaks071a89c2011-08-19 23:21:56 +00001756 }
Ted Kremenek3978f792009-05-10 05:11:21 +00001757
Jordy Rose184bd142011-08-24 22:39:09 +00001758 CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1759 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1760 StringRef endText)
Anna Zaks752de142011-08-22 18:54:07 +00001761 : BugReport(D, D.getDescription(), endText, n) {
David Blaikie91e79022014-09-04 23:54:33 +00001762 addVisitor(llvm::make_unique<CFRefReportVisitor>(sym, GCEnabled, Log));
Jordy Rose184bd142011-08-24 22:39:09 +00001763 addGCModeDescription(LOpts, GCEnabled);
Anna Zaks071a89c2011-08-19 23:21:56 +00001764 }
Mike Stump11289f42009-09-09 15:08:12 +00001765
Craig Topperfb6b25b2014-03-15 04:29:04 +00001766 std::pair<ranges_iterator, ranges_iterator> getRanges() override {
Anna Zaks752de142011-08-22 18:54:07 +00001767 const CFRefBug& BugTy = static_cast<CFRefBug&>(getBugType());
1768 if (!BugTy.isLeak())
Anna Zaks3a6bdf82011-08-17 23:00:25 +00001769 return BugReport::getRanges();
Ted Kremenek6bd78702009-04-29 18:50:19 +00001770 else
Argyrios Kyrtzidisd22d8ff2010-12-04 01:12:15 +00001771 return std::make_pair(ranges_iterator(), ranges_iterator());
Ted Kremenek6bd78702009-04-29 18:50:19 +00001772 }
Ted Kremenek6bd78702009-04-29 18:50:19 +00001773 };
Ted Kremenek3978f792009-05-10 05:11:21 +00001774
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00001775 class CFRefLeakReport : public CFRefReport {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001776 const MemRegion* AllocBinding;
1777 public:
Jordy Rose184bd142011-08-24 22:39:09 +00001778 CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1779 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
Ted Kremenek8671acb2013-04-16 21:44:22 +00001780 CheckerContext &Ctx,
1781 bool IncludeAllocationLine);
Mike Stump11289f42009-09-09 15:08:12 +00001782
Craig Topperfb6b25b2014-03-15 04:29:04 +00001783 PathDiagnosticLocation getLocation(const SourceManager &SM) const override {
Anna Zaksc29bed32011-09-20 21:38:35 +00001784 assert(Location.isValid());
1785 return Location;
1786 }
Mike Stump11289f42009-09-09 15:08:12 +00001787 };
Ted Kremenek6bd78702009-04-29 18:50:19 +00001788} // end anonymous namespace
1789
Jordy Rose184bd142011-08-24 22:39:09 +00001790void CFRefReport::addGCModeDescription(const LangOptions &LOpts,
1791 bool GCEnabled) {
Craig Topper0dbb7832014-05-27 02:45:47 +00001792 const char *GCModeDescription = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001793
Douglas Gregor79a91412011-09-13 17:21:33 +00001794 switch (LOpts.getGC()) {
Anna Zaks76c3fb62011-08-22 20:31:28 +00001795 case LangOptions::GCOnly:
Jordy Rose184bd142011-08-24 22:39:09 +00001796 assert(GCEnabled);
Jordy Rose7a534982011-08-24 05:47:39 +00001797 GCModeDescription = "Code is compiled to only use garbage collection";
1798 break;
Mike Stump11289f42009-09-09 15:08:12 +00001799
Anna Zaks76c3fb62011-08-22 20:31:28 +00001800 case LangOptions::NonGC:
Jordy Rose184bd142011-08-24 22:39:09 +00001801 assert(!GCEnabled);
Jordy Rose7a534982011-08-24 05:47:39 +00001802 GCModeDescription = "Code is compiled to use reference counts";
1803 break;
Mike Stump11289f42009-09-09 15:08:12 +00001804
Anna Zaks76c3fb62011-08-22 20:31:28 +00001805 case LangOptions::HybridGC:
Jordy Rose184bd142011-08-24 22:39:09 +00001806 if (GCEnabled) {
Jordy Rose7a534982011-08-24 05:47:39 +00001807 GCModeDescription = "Code is compiled to use either garbage collection "
1808 "(GC) or reference counts (non-GC). The bug occurs "
1809 "with GC enabled";
1810 break;
1811 } else {
1812 GCModeDescription = "Code is compiled to use either garbage collection "
1813 "(GC) or reference counts (non-GC). The bug occurs "
1814 "in non-GC mode";
1815 break;
Anna Zaks76c3fb62011-08-22 20:31:28 +00001816 }
Ted Kremenek6bd78702009-04-29 18:50:19 +00001817 }
Jordy Rose7a534982011-08-24 05:47:39 +00001818
Jordy Rose9ff02992011-08-24 20:38:42 +00001819 assert(GCModeDescription && "invalid/unknown GC mode");
Jordy Rose7a534982011-08-24 05:47:39 +00001820 addExtraText(GCModeDescription);
Ted Kremenek6bd78702009-04-29 18:50:19 +00001821}
1822
Jordy Rose6393f822012-05-12 05:10:43 +00001823static bool isNumericLiteralExpression(const Expr *E) {
1824 // FIXME: This set of cases was copied from SemaExprObjC.
1825 return isa<IntegerLiteral>(E) ||
1826 isa<CharacterLiteral>(E) ||
1827 isa<FloatingLiteral>(E) ||
1828 isa<ObjCBoolLiteralExpr>(E) ||
1829 isa<CXXBoolLiteralExpr>(E);
1830}
1831
Anna Zaks071a89c2011-08-19 23:21:56 +00001832PathDiagnosticPiece *CFRefReportVisitor::VisitNode(const ExplodedNode *N,
1833 const ExplodedNode *PrevN,
1834 BugReporterContext &BRC,
1835 BugReport &BR) {
Jordan Rose681cce92012-07-10 22:07:42 +00001836 // FIXME: We will eventually need to handle non-statement-based events
1837 // (__attribute__((cleanup))).
David Blaikie87396b92013-02-21 22:23:56 +00001838 if (!N->getLocation().getAs<StmtPoint>())
Craig Topper0dbb7832014-05-27 02:45:47 +00001839 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001840
Ted Kremenekbb8d5462009-05-06 21:39:49 +00001841 // Check if the type state has changed.
Ted Kremenek49b1e382012-01-26 21:29:00 +00001842 ProgramStateRef PrevSt = PrevN->getState();
1843 ProgramStateRef CurrSt = N->getState();
Ted Kremenek632e3b72012-01-06 22:09:28 +00001844 const LocationContext *LCtx = N->getLocationContext();
Mike Stump11289f42009-09-09 15:08:12 +00001845
Anna Zaksf5788c72012-08-14 00:36:15 +00001846 const RefVal* CurrT = getRefBinding(CurrSt, Sym);
Craig Topper0dbb7832014-05-27 02:45:47 +00001847 if (!CurrT) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001848
Ted Kremenekd93c6e32009-06-18 01:23:53 +00001849 const RefVal &CurrV = *CurrT;
Anna Zaksf5788c72012-08-14 00:36:15 +00001850 const RefVal *PrevT = getRefBinding(PrevSt, Sym);
Mike Stump11289f42009-09-09 15:08:12 +00001851
Ted Kremenek6bd78702009-04-29 18:50:19 +00001852 // Create a string buffer to constain all the useful things we want
1853 // to tell the user.
1854 std::string sbuf;
1855 llvm::raw_string_ostream os(sbuf);
Mike Stump11289f42009-09-09 15:08:12 +00001856
Ted Kremenek6bd78702009-04-29 18:50:19 +00001857 // This is the allocation site since the previous node had no bindings
1858 // for this symbol.
1859 if (!PrevT) {
David Blaikie87396b92013-02-21 22:23:56 +00001860 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
Mike Stump11289f42009-09-09 15:08:12 +00001861
Ted Kremenek415287d2012-03-06 20:06:12 +00001862 if (isa<ObjCArrayLiteral>(S)) {
1863 os << "NSArray literal is an object with a +0 retain count";
Mike Stump11289f42009-09-09 15:08:12 +00001864 }
Ted Kremenek415287d2012-03-06 20:06:12 +00001865 else if (isa<ObjCDictionaryLiteral>(S)) {
1866 os << "NSDictionary literal is an object with a +0 retain count";
Ted Kremenek6bd78702009-04-29 18:50:19 +00001867 }
Jordy Rose6393f822012-05-12 05:10:43 +00001868 else if (const ObjCBoxedExpr *BL = dyn_cast<ObjCBoxedExpr>(S)) {
1869 if (isNumericLiteralExpression(BL->getSubExpr()))
1870 os << "NSNumber literal is an object with a +0 retain count";
1871 else {
Craig Topper0dbb7832014-05-27 02:45:47 +00001872 const ObjCInterfaceDecl *BoxClass = nullptr;
Jordy Rose6393f822012-05-12 05:10:43 +00001873 if (const ObjCMethodDecl *Method = BL->getBoxingMethod())
1874 BoxClass = Method->getClassInterface();
1875
1876 // We should always be able to find the boxing class interface,
1877 // but consider this future-proofing.
1878 if (BoxClass)
1879 os << *BoxClass << " b";
1880 else
1881 os << "B";
1882
1883 os << "oxed expression produces an object with a +0 retain count";
1884 }
1885 }
Ted Kremenek415287d2012-03-06 20:06:12 +00001886 else {
1887 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
1888 // Get the name of the callee (if it is available).
1889 SVal X = CurrSt->getSValAsScalarOrLoc(CE->getCallee(), LCtx);
1890 if (const FunctionDecl *FD = X.getAsFunctionDecl())
1891 os << "Call to function '" << *FD << '\'';
1892 else
1893 os << "function call";
Ted Kremenek6bd78702009-04-29 18:50:19 +00001894 }
Ted Kremenek415287d2012-03-06 20:06:12 +00001895 else {
Jordan Rose627b0462012-07-18 21:59:51 +00001896 assert(isa<ObjCMessageExpr>(S));
Jordan Rosefcd016e2012-07-30 20:22:09 +00001897 CallEventManager &Mgr = CurrSt->getStateManager().getCallEventManager();
1898 CallEventRef<ObjCMethodCall> Call
1899 = Mgr.getObjCMethodCall(cast<ObjCMessageExpr>(S), CurrSt, LCtx);
1900
1901 switch (Call->getMessageKind()) {
Jordan Rose627b0462012-07-18 21:59:51 +00001902 case OCM_Message:
1903 os << "Method";
1904 break;
1905 case OCM_PropertyAccess:
1906 os << "Property";
1907 break;
1908 case OCM_Subscript:
1909 os << "Subscript";
1910 break;
1911 }
Ted Kremenek415287d2012-03-06 20:06:12 +00001912 }
1913
1914 if (CurrV.getObjKind() == RetEffect::CF) {
1915 os << " returns a Core Foundation object with a ";
1916 }
1917 else {
1918 assert (CurrV.getObjKind() == RetEffect::ObjC);
1919 os << " returns an Objective-C object with a ";
1920 }
1921
1922 if (CurrV.isOwned()) {
1923 os << "+1 retain count";
1924
1925 if (GCEnabled) {
1926 assert(CurrV.getObjKind() == RetEffect::CF);
1927 os << ". "
1928 "Core Foundation objects are not automatically garbage collected.";
1929 }
1930 }
1931 else {
1932 assert (CurrV.isNotOwned());
1933 os << "+0 retain count";
1934 }
Ted Kremenek6bd78702009-04-29 18:50:19 +00001935 }
Mike Stump11289f42009-09-09 15:08:12 +00001936
Anna Zaks3a769bd2011-09-15 01:08:34 +00001937 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
1938 N->getLocationContext());
Ted Kremenek6bd78702009-04-29 18:50:19 +00001939 return new PathDiagnosticEventPiece(Pos, os.str());
1940 }
Mike Stump11289f42009-09-09 15:08:12 +00001941
Ted Kremenek6bd78702009-04-29 18:50:19 +00001942 // Gather up the effects that were performed on the object at this
1943 // program point
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001944 SmallVector<ArgEffect, 2> AEffects;
Mike Stump11289f42009-09-09 15:08:12 +00001945
Jordy Rose20d4e682011-08-23 20:55:48 +00001946 const ExplodedNode *OrigNode = BRC.getNodeResolver().getOriginalNode(N);
1947 if (const RetainSummary *Summ = SummaryLog.lookup(OrigNode)) {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001948 // We only have summaries attached to nodes after evaluating CallExpr and
1949 // ObjCMessageExprs.
David Blaikie87396b92013-02-21 22:23:56 +00001950 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
Mike Stump11289f42009-09-09 15:08:12 +00001951
Ted Kremenekbfd28fd2009-07-22 22:35:28 +00001952 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001953 // Iterate through the parameter expressions and see if the symbol
1954 // was ever passed as an argument.
1955 unsigned i = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001956
Ted Kremenekbfd28fd2009-07-22 22:35:28 +00001957 for (CallExpr::const_arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
Ted Kremenek6bd78702009-04-29 18:50:19 +00001958 AI!=AE; ++AI, ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00001959
Ted Kremenek6bd78702009-04-29 18:50:19 +00001960 // Retrieve the value of the argument. Is it the symbol
1961 // we are interested in?
Ted Kremenek632e3b72012-01-06 22:09:28 +00001962 if (CurrSt->getSValAsScalarOrLoc(*AI, LCtx).getAsLocSymbol() != Sym)
Ted Kremenek6bd78702009-04-29 18:50:19 +00001963 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001964
Ted Kremenek6bd78702009-04-29 18:50:19 +00001965 // We have an argument. Get the effect!
1966 AEffects.push_back(Summ->getArg(i));
1967 }
1968 }
Mike Stump11289f42009-09-09 15:08:12 +00001969 else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
Douglas Gregor9a129192010-04-21 00:45:42 +00001970 if (const Expr *receiver = ME->getInstanceReceiver())
Ted Kremenek632e3b72012-01-06 22:09:28 +00001971 if (CurrSt->getSValAsScalarOrLoc(receiver, LCtx)
1972 .getAsLocSymbol() == Sym) {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001973 // The symbol we are tracking is the receiver.
1974 AEffects.push_back(Summ->getReceiverEffect());
1975 }
1976 }
1977 }
Mike Stump11289f42009-09-09 15:08:12 +00001978
Ted Kremenek6bd78702009-04-29 18:50:19 +00001979 do {
1980 // Get the previous type state.
1981 RefVal PrevV = *PrevT;
Mike Stump11289f42009-09-09 15:08:12 +00001982
Ted Kremenek6bd78702009-04-29 18:50:19 +00001983 // Specially handle -dealloc.
Benjamin Kramerab3838a2013-08-16 21:57:14 +00001984 if (!GCEnabled && std::find(AEffects.begin(), AEffects.end(), Dealloc) !=
1985 AEffects.end()) {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001986 // Determine if the object's reference count was pushed to zero.
Jordan Roseb3ad07e2014-03-25 17:10:58 +00001987 assert(!PrevV.hasSameState(CurrV) && "The state should have changed.");
Ted Kremenek6bd78702009-04-29 18:50:19 +00001988 // We may not have transitioned to 'release' if we hit an error.
1989 // This case is handled elsewhere.
1990 if (CurrV.getKind() == RefVal::Released) {
Ted Kremenek3a0516b2009-05-08 20:01:42 +00001991 assert(CurrV.getCombinedCounts() == 0);
Ted Kremenek6bd78702009-04-29 18:50:19 +00001992 os << "Object released by directly sending the '-dealloc' message";
1993 break;
1994 }
1995 }
Mike Stump11289f42009-09-09 15:08:12 +00001996
Ted Kremenek6bd78702009-04-29 18:50:19 +00001997 // Specially handle CFMakeCollectable and friends.
Benjamin Kramerab3838a2013-08-16 21:57:14 +00001998 if (std::find(AEffects.begin(), AEffects.end(), MakeCollectable) !=
1999 AEffects.end()) {
Ted Kremenek6bd78702009-04-29 18:50:19 +00002000 // Get the name of the function.
David Blaikie87396b92013-02-21 22:23:56 +00002001 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
Ted Kremenek632e3b72012-01-06 22:09:28 +00002002 SVal X =
2003 CurrSt->getSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee(), LCtx);
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002004 const FunctionDecl *FD = X.getAsFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00002005
Jordy Rose7a534982011-08-24 05:47:39 +00002006 if (GCEnabled) {
Ted Kremenek6bd78702009-04-29 18:50:19 +00002007 // Determine if the object's reference count was pushed to zero.
Jordan Roseb3ad07e2014-03-25 17:10:58 +00002008 assert(!PrevV.hasSameState(CurrV) && "The state should have changed.");
Mike Stump11289f42009-09-09 15:08:12 +00002009
Benjamin Kramerb89514a2011-10-14 18:45:37 +00002010 os << "In GC mode a call to '" << *FD
Ted Kremenek6bd78702009-04-29 18:50:19 +00002011 << "' decrements an object's retain count and registers the "
2012 "object with the garbage collector. ";
Mike Stump11289f42009-09-09 15:08:12 +00002013
Ted Kremenek6bd78702009-04-29 18:50:19 +00002014 if (CurrV.getKind() == RefVal::Released) {
2015 assert(CurrV.getCount() == 0);
2016 os << "Since it now has a 0 retain count the object can be "
2017 "automatically collected by the garbage collector.";
2018 }
2019 else
2020 os << "An object must have a 0 retain count to be garbage collected. "
2021 "After this call its retain count is +" << CurrV.getCount()
2022 << '.';
2023 }
Mike Stump11289f42009-09-09 15:08:12 +00002024 else
Benjamin Kramerb89514a2011-10-14 18:45:37 +00002025 os << "When GC is not enabled a call to '" << *FD
Ted Kremenek6bd78702009-04-29 18:50:19 +00002026 << "' has no effect on its argument.";
Mike Stump11289f42009-09-09 15:08:12 +00002027
Ted Kremenek6bd78702009-04-29 18:50:19 +00002028 // Nothing more to say.
2029 break;
2030 }
Mike Stump11289f42009-09-09 15:08:12 +00002031
2032 // Determine if the typestate has changed.
Jordan Roseb3ad07e2014-03-25 17:10:58 +00002033 if (!PrevV.hasSameState(CurrV))
Ted Kremenek6bd78702009-04-29 18:50:19 +00002034 switch (CurrV.getKind()) {
2035 case RefVal::Owned:
2036 case RefVal::NotOwned:
Mike Stump11289f42009-09-09 15:08:12 +00002037
Ted Kremenek3a0516b2009-05-08 20:01:42 +00002038 if (PrevV.getCount() == CurrV.getCount()) {
2039 // Did an autorelease message get sent?
2040 if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
Craig Topper0dbb7832014-05-27 02:45:47 +00002041 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002042
Zhongxing Xu08a2ede2009-05-12 10:10:00 +00002043 assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount());
Jordan Rose7467f062013-04-23 01:42:25 +00002044 os << "Object autoreleased";
Ted Kremenek3a0516b2009-05-08 20:01:42 +00002045 break;
2046 }
Mike Stump11289f42009-09-09 15:08:12 +00002047
Ted Kremenek6bd78702009-04-29 18:50:19 +00002048 if (PrevV.getCount() > CurrV.getCount())
2049 os << "Reference count decremented.";
2050 else
2051 os << "Reference count incremented.";
Mike Stump11289f42009-09-09 15:08:12 +00002052
Ted Kremenek6bd78702009-04-29 18:50:19 +00002053 if (unsigned Count = CurrV.getCount())
2054 os << " The object now has a +" << Count << " retain count.";
Mike Stump11289f42009-09-09 15:08:12 +00002055
Ted Kremenek6bd78702009-04-29 18:50:19 +00002056 if (PrevV.getKind() == RefVal::Released) {
Jordy Rose7a534982011-08-24 05:47:39 +00002057 assert(GCEnabled && CurrV.getCount() > 0);
Jordy Rose78373e52012-03-17 05:49:15 +00002058 os << " The object is not eligible for garbage collection until "
2059 "the retain count reaches 0 again.";
Ted Kremenek6bd78702009-04-29 18:50:19 +00002060 }
Mike Stump11289f42009-09-09 15:08:12 +00002061
Ted Kremenek6bd78702009-04-29 18:50:19 +00002062 break;
Mike Stump11289f42009-09-09 15:08:12 +00002063
Ted Kremenek6bd78702009-04-29 18:50:19 +00002064 case RefVal::Released:
2065 os << "Object released.";
2066 break;
Mike Stump11289f42009-09-09 15:08:12 +00002067
Ted Kremenek6bd78702009-04-29 18:50:19 +00002068 case RefVal::ReturnedOwned:
Jordy Rose78373e52012-03-17 05:49:15 +00002069 // Autoreleases can be applied after marking a node ReturnedOwned.
2070 if (CurrV.getAutoreleaseCount())
Craig Topper0dbb7832014-05-27 02:45:47 +00002071 return nullptr;
Jordy Rose78373e52012-03-17 05:49:15 +00002072
2073 os << "Object returned to caller as an owning reference (single "
2074 "retain count transferred to caller)";
Ted Kremenek6bd78702009-04-29 18:50:19 +00002075 break;
Mike Stump11289f42009-09-09 15:08:12 +00002076
Ted Kremenek6bd78702009-04-29 18:50:19 +00002077 case RefVal::ReturnedNotOwned:
Ted Kremenekf2301982011-05-26 18:45:44 +00002078 os << "Object returned to caller with a +0 retain count";
Ted Kremenek6bd78702009-04-29 18:50:19 +00002079 break;
Mike Stump11289f42009-09-09 15:08:12 +00002080
Ted Kremenek6bd78702009-04-29 18:50:19 +00002081 default:
Craig Topper0dbb7832014-05-27 02:45:47 +00002082 return nullptr;
Ted Kremenek6bd78702009-04-29 18:50:19 +00002083 }
Mike Stump11289f42009-09-09 15:08:12 +00002084
Ted Kremenek6bd78702009-04-29 18:50:19 +00002085 // Emit any remaining diagnostics for the argument effects (if any).
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002086 for (SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
Ted Kremenek6bd78702009-04-29 18:50:19 +00002087 E=AEffects.end(); I != E; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +00002088
Ted Kremenek6bd78702009-04-29 18:50:19 +00002089 // A bunch of things have alternate behavior under GC.
Jordy Rose7a534982011-08-24 05:47:39 +00002090 if (GCEnabled)
Ted Kremenek6bd78702009-04-29 18:50:19 +00002091 switch (*I) {
2092 default: break;
2093 case Autorelease:
2094 os << "In GC mode an 'autorelease' has no effect.";
2095 continue;
2096 case IncRefMsg:
2097 os << "In GC mode the 'retain' message has no effect.";
2098 continue;
2099 case DecRefMsg:
2100 os << "In GC mode the 'release' message has no effect.";
2101 continue;
2102 }
2103 }
Mike Stump11289f42009-09-09 15:08:12 +00002104 } while (0);
2105
Ted Kremenek6bd78702009-04-29 18:50:19 +00002106 if (os.str().empty())
Craig Topper0dbb7832014-05-27 02:45:47 +00002107 return nullptr; // We have nothing to say!
Ted Kremenek051a03d2009-05-13 07:12:33 +00002108
David Blaikie87396b92013-02-21 22:23:56 +00002109 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
Anna Zaks3a769bd2011-09-15 01:08:34 +00002110 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
2111 N->getLocationContext());
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002112 PathDiagnosticPiece *P = new PathDiagnosticEventPiece(Pos, os.str());
Mike Stump11289f42009-09-09 15:08:12 +00002113
Ted Kremenek6bd78702009-04-29 18:50:19 +00002114 // Add the range by scanning the children of the statement for any bindings
2115 // to Sym.
Mike Stump11289f42009-09-09 15:08:12 +00002116 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
Ted Kremenekbfd28fd2009-07-22 22:35:28 +00002117 I!=E; ++I)
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002118 if (const Expr *Exp = dyn_cast_or_null<Expr>(*I))
Ted Kremenek632e3b72012-01-06 22:09:28 +00002119 if (CurrSt->getSValAsScalarOrLoc(Exp, LCtx).getAsLocSymbol() == Sym) {
Ted Kremenek6bd78702009-04-29 18:50:19 +00002120 P->addRange(Exp->getSourceRange());
2121 break;
2122 }
Mike Stump11289f42009-09-09 15:08:12 +00002123
Ted Kremenek6bd78702009-04-29 18:50:19 +00002124 return P;
2125}
2126
Anna Zaks75de3232012-02-28 22:39:22 +00002127// Find the first node in the current function context that referred to the
2128// tracked symbol and the memory location that value was stored to. Note, the
2129// value is only reported if the allocation occurred in the same function as
Anna Zakse51362e2013-04-10 21:42:06 +00002130// the leak. The function can also return a location context, which should be
2131// treated as interesting.
2132struct AllocationInfo {
2133 const ExplodedNode* N;
Anna Zaks3f303be2013-04-10 22:56:30 +00002134 const MemRegion *R;
Anna Zakse51362e2013-04-10 21:42:06 +00002135 const LocationContext *InterestingMethodContext;
Anna Zaks3f303be2013-04-10 22:56:30 +00002136 AllocationInfo(const ExplodedNode *InN,
2137 const MemRegion *InR,
Anna Zakse51362e2013-04-10 21:42:06 +00002138 const LocationContext *InInterestingMethodContext) :
2139 N(InN), R(InR), InterestingMethodContext(InInterestingMethodContext) {}
2140};
2141
2142static AllocationInfo
Ted Kremenek001fd5b2011-08-15 22:09:50 +00002143GetAllocationSite(ProgramStateManager& StateMgr, const ExplodedNode *N,
Ted Kremenek6bd78702009-04-29 18:50:19 +00002144 SymbolRef Sym) {
Anna Zakse51362e2013-04-10 21:42:06 +00002145 const ExplodedNode *AllocationNode = N;
2146 const ExplodedNode *AllocationNodeInCurrentContext = N;
Craig Topper0dbb7832014-05-27 02:45:47 +00002147 const MemRegion *FirstBinding = nullptr;
Anna Zaks75de3232012-02-28 22:39:22 +00002148 const LocationContext *LeakContext = N->getLocationContext();
Mike Stump11289f42009-09-09 15:08:12 +00002149
Anna Zakse51362e2013-04-10 21:42:06 +00002150 // The location context of the init method called on the leaked object, if
2151 // available.
Craig Topper0dbb7832014-05-27 02:45:47 +00002152 const LocationContext *InitMethodContext = nullptr;
Anna Zakse51362e2013-04-10 21:42:06 +00002153
Ted Kremenek6bd78702009-04-29 18:50:19 +00002154 while (N) {
Ted Kremenek49b1e382012-01-26 21:29:00 +00002155 ProgramStateRef St = N->getState();
Anna Zakse51362e2013-04-10 21:42:06 +00002156 const LocationContext *NContext = N->getLocationContext();
Mike Stump11289f42009-09-09 15:08:12 +00002157
Anna Zaksf5788c72012-08-14 00:36:15 +00002158 if (!getRefBinding(St, Sym))
Ted Kremenek6bd78702009-04-29 18:50:19 +00002159 break;
Mike Stump11289f42009-09-09 15:08:12 +00002160
Anna Zaks6797d6e2012-03-21 19:45:01 +00002161 StoreManager::FindUniqueBinding FB(Sym);
Mike Stump11289f42009-09-09 15:08:12 +00002162 StateMgr.iterBindings(St, FB);
Anna Zakse51362e2013-04-10 21:42:06 +00002163
Anna Zaks7c19abe2013-04-10 21:42:02 +00002164 if (FB) {
2165 const MemRegion *R = FB.getRegion();
Anna Zaks07804ef2013-04-10 22:56:33 +00002166 const VarRegion *VR = R->getBaseRegion()->getAs<VarRegion>();
Anna Zaks7c19abe2013-04-10 21:42:02 +00002167 // Do not show local variables belonging to a function other than
2168 // where the error is reported.
2169 if (!VR || VR->getStackFrame() == LeakContext->getCurrentStackFrame())
Anna Zakse51362e2013-04-10 21:42:06 +00002170 FirstBinding = R;
Anna Zaks7c19abe2013-04-10 21:42:02 +00002171 }
Mike Stump11289f42009-09-09 15:08:12 +00002172
Anna Zakse51362e2013-04-10 21:42:06 +00002173 // AllocationNode is the last node in which the symbol was tracked.
2174 AllocationNode = N;
2175
2176 // AllocationNodeInCurrentContext, is the last node in the current context
2177 // in which the symbol was tracked.
2178 if (NContext == LeakContext)
2179 AllocationNodeInCurrentContext = N;
2180
Anna Zaks3f303be2013-04-10 22:56:30 +00002181 // Find the last init that was called on the given symbol and store the
2182 // init method's location context.
2183 if (!InitMethodContext)
2184 if (Optional<CallEnter> CEP = N->getLocation().getAs<CallEnter>()) {
2185 const Stmt *CE = CEP->getCallExpr();
Anna Zaks99394bb2013-04-25 00:41:32 +00002186 if (const ObjCMessageExpr *ME = dyn_cast_or_null<ObjCMessageExpr>(CE)) {
Anna Zaks3f303be2013-04-10 22:56:30 +00002187 const Stmt *RecExpr = ME->getInstanceReceiver();
2188 if (RecExpr) {
2189 SVal RecV = St->getSVal(RecExpr, NContext);
2190 if (ME->getMethodFamily() == OMF_init && RecV.getAsSymbol() == Sym)
2191 InitMethodContext = CEP->getCalleeContext();
2192 }
2193 }
Anna Zakse51362e2013-04-10 21:42:06 +00002194 }
Anna Zaks75de3232012-02-28 22:39:22 +00002195
Craig Topper0dbb7832014-05-27 02:45:47 +00002196 N = N->pred_empty() ? nullptr : *(N->pred_begin());
Ted Kremenek6bd78702009-04-29 18:50:19 +00002197 }
Mike Stump11289f42009-09-09 15:08:12 +00002198
Anna Zakse51362e2013-04-10 21:42:06 +00002199 // If we are reporting a leak of the object that was allocated with alloc,
Anna Zaks3f303be2013-04-10 22:56:30 +00002200 // mark its init method as interesting.
Craig Topper0dbb7832014-05-27 02:45:47 +00002201 const LocationContext *InterestingMethodContext = nullptr;
Anna Zakse51362e2013-04-10 21:42:06 +00002202 if (InitMethodContext) {
2203 const ProgramPoint AllocPP = AllocationNode->getLocation();
2204 if (Optional<StmtPoint> SP = AllocPP.getAs<StmtPoint>())
2205 if (const ObjCMessageExpr *ME = SP->getStmtAs<ObjCMessageExpr>())
2206 if (ME->getMethodFamily() == OMF_alloc)
2207 InterestingMethodContext = InitMethodContext;
2208 }
2209
Anna Zaks75de3232012-02-28 22:39:22 +00002210 // If allocation happened in a function different from the leak node context,
2211 // do not report the binding.
Ted Kremenekb045b012012-10-12 22:56:40 +00002212 assert(N && "Could not find allocation node");
Anna Zaks75de3232012-02-28 22:39:22 +00002213 if (N->getLocationContext() != LeakContext) {
Craig Topper0dbb7832014-05-27 02:45:47 +00002214 FirstBinding = nullptr;
Anna Zaks75de3232012-02-28 22:39:22 +00002215 }
2216
Anna Zakse51362e2013-04-10 21:42:06 +00002217 return AllocationInfo(AllocationNodeInCurrentContext,
2218 FirstBinding,
2219 InterestingMethodContext);
Ted Kremenek6bd78702009-04-29 18:50:19 +00002220}
2221
David Blaikied15481c2014-08-29 18:18:43 +00002222std::unique_ptr<PathDiagnosticPiece>
Anna Zaks88255cc2011-08-20 01:27:22 +00002223CFRefReportVisitor::getEndPath(BugReporterContext &BRC,
David Blaikied15481c2014-08-29 18:18:43 +00002224 const ExplodedNode *EndN, BugReport &BR) {
Ted Kremenek1e809b42012-03-09 01:13:14 +00002225 BR.markInteresting(Sym);
Anna Zaks88255cc2011-08-20 01:27:22 +00002226 return BugReporterVisitor::getDefaultEndPath(BRC, EndN, BR);
Ted Kremenek6bd78702009-04-29 18:50:19 +00002227}
2228
David Blaikied15481c2014-08-29 18:18:43 +00002229std::unique_ptr<PathDiagnosticPiece>
Anna Zaks88255cc2011-08-20 01:27:22 +00002230CFRefLeakReportVisitor::getEndPath(BugReporterContext &BRC,
David Blaikied15481c2014-08-29 18:18:43 +00002231 const ExplodedNode *EndN, BugReport &BR) {
Mike Stump11289f42009-09-09 15:08:12 +00002232
Ted Kremenekbb8d5462009-05-06 21:39:49 +00002233 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenek6bd78702009-04-29 18:50:19 +00002234 // assigned to different variables, etc.
Ted Kremenek1e809b42012-03-09 01:13:14 +00002235 BR.markInteresting(Sym);
Mike Stump11289f42009-09-09 15:08:12 +00002236
Ted Kremenek6bd78702009-04-29 18:50:19 +00002237 // We are reporting a leak. Walk up the graph to get to the first node where
2238 // the symbol appeared, and also get the first VarDecl that tracked object
2239 // is stored to.
Anna Zakse51362e2013-04-10 21:42:06 +00002240 AllocationInfo AllocI =
Ted Kremenek8c8fb482009-05-08 23:32:51 +00002241 GetAllocationSite(BRC.getStateManager(), EndN, Sym);
Mike Stump11289f42009-09-09 15:08:12 +00002242
Anna Zakse51362e2013-04-10 21:42:06 +00002243 const MemRegion* FirstBinding = AllocI.R;
2244 BR.markInteresting(AllocI.InterestingMethodContext);
2245
Anna Zaks921f0492011-09-15 18:56:07 +00002246 SourceManager& SM = BRC.getSourceManager();
Mike Stump11289f42009-09-09 15:08:12 +00002247
Ted Kremenek6bd78702009-04-29 18:50:19 +00002248 // Compute an actual location for the leak. Sometimes a leak doesn't
2249 // occur at an actual statement (e.g., transition between blocks; end
2250 // of function) so we need to walk the graph and compute a real location.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002251 const ExplodedNode *LeakN = EndN;
Anna Zaks921f0492011-09-15 18:56:07 +00002252 PathDiagnosticLocation L = PathDiagnosticLocation::createEndOfPath(LeakN, SM);
Mike Stump11289f42009-09-09 15:08:12 +00002253
Ted Kremenek6bd78702009-04-29 18:50:19 +00002254 std::string sbuf;
2255 llvm::raw_string_ostream os(sbuf);
Mike Stump11289f42009-09-09 15:08:12 +00002256
Ted Kremenekf2301982011-05-26 18:45:44 +00002257 os << "Object leaked: ";
Mike Stump11289f42009-09-09 15:08:12 +00002258
Ted Kremenekf2301982011-05-26 18:45:44 +00002259 if (FirstBinding) {
2260 os << "object allocated and stored into '"
2261 << FirstBinding->getString() << '\'';
2262 }
2263 else
2264 os << "allocated object";
Mike Stump11289f42009-09-09 15:08:12 +00002265
Ted Kremenek6bd78702009-04-29 18:50:19 +00002266 // Get the retain count.
Anna Zaksf5788c72012-08-14 00:36:15 +00002267 const RefVal* RV = getRefBinding(EndN->getState(), Sym);
Ted Kremenekb045b012012-10-12 22:56:40 +00002268 assert(RV);
Mike Stump11289f42009-09-09 15:08:12 +00002269
Ted Kremenek6bd78702009-04-29 18:50:19 +00002270 if (RV->getKind() == RefVal::ErrorLeakReturned) {
2271 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
Jordy Rose43426f82011-07-15 22:17:54 +00002272 // objects. Only "copy", "alloc", "retain" and "new" transfer ownership
Ted Kremenek6bd78702009-04-29 18:50:19 +00002273 // to the caller for NS objects.
Ted Kremenek8e2c9b02011-05-25 06:19:45 +00002274 const Decl *D = &EndN->getCodeDecl();
Ted Kremenek2a786952012-09-06 23:03:07 +00002275
2276 os << (isa<ObjCMethodDecl>(D) ? " is returned from a method "
2277 : " is returned from a function ");
2278
Aaron Ballman9ead1242013-12-19 02:39:40 +00002279 if (D->hasAttr<CFReturnsNotRetainedAttr>())
Ted Kremenek2a786952012-09-06 23:03:07 +00002280 os << "that is annotated as CF_RETURNS_NOT_RETAINED";
Aaron Ballman9ead1242013-12-19 02:39:40 +00002281 else if (D->hasAttr<NSReturnsNotRetainedAttr>())
Ted Kremenek2a786952012-09-06 23:03:07 +00002282 os << "that is annotated as NS_RETURNS_NOT_RETAINED";
Ted Kremenek8e2c9b02011-05-25 06:19:45 +00002283 else {
Ted Kremenek2a786952012-09-06 23:03:07 +00002284 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2285 os << "whose name ('" << MD->getSelector().getAsString()
2286 << "') does not start with 'copy', 'mutableCopy', 'alloc' or 'new'."
2287 " This violates the naming convention rules"
2288 " given in the Memory Management Guide for Cocoa";
2289 }
2290 else {
2291 const FunctionDecl *FD = cast<FunctionDecl>(D);
2292 os << "whose name ('" << *FD
2293 << "') does not contain 'Copy' or 'Create'. This violates the naming"
2294 " convention rules given in the Memory Management Guide for Core"
2295 " Foundation";
2296 }
2297 }
Ted Kremenek6bd78702009-04-29 18:50:19 +00002298 }
Ted Kremenekdee56e32009-05-10 06:25:57 +00002299 else if (RV->getKind() == RefVal::ErrorGCLeakReturned) {
David Blaikie3cbec0f2013-02-21 22:37:44 +00002300 const ObjCMethodDecl &MD = cast<ObjCMethodDecl>(EndN->getCodeDecl());
Ted Kremenekdee56e32009-05-10 06:25:57 +00002301 os << " and returned from method '" << MD.getSelector().getAsString()
Ted Kremenek1f8e4342009-05-10 16:52:15 +00002302 << "' is potentially leaked when using garbage collection. Callers "
2303 "of this method do not expect a returned object with a +1 retain "
2304 "count since they expect the object to be managed by the garbage "
2305 "collector";
Ted Kremenekdee56e32009-05-10 06:25:57 +00002306 }
Ted Kremenek6bd78702009-04-29 18:50:19 +00002307 else
Ted Kremenek4f63ac72010-10-15 22:50:23 +00002308 os << " is not referenced later in this execution path and has a retain "
Ted Kremenekf2301982011-05-26 18:45:44 +00002309 "count of +" << RV->getCount();
Mike Stump11289f42009-09-09 15:08:12 +00002310
David Blaikied15481c2014-08-29 18:18:43 +00002311 return llvm::make_unique<PathDiagnosticEventPiece>(L, os.str());
Ted Kremenek6bd78702009-04-29 18:50:19 +00002312}
2313
Jordy Rose184bd142011-08-24 22:39:09 +00002314CFRefLeakReport::CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts,
2315 bool GCEnabled, const SummaryLogTy &Log,
2316 ExplodedNode *n, SymbolRef sym,
Ted Kremenek8671acb2013-04-16 21:44:22 +00002317 CheckerContext &Ctx,
2318 bool IncludeAllocationLine)
2319 : CFRefReport(D, LOpts, GCEnabled, Log, n, sym, false) {
Mike Stump11289f42009-09-09 15:08:12 +00002320
Chris Lattner57540c52011-04-15 05:22:18 +00002321 // Most bug reports are cached at the location where they occurred.
Ted Kremenek6bd78702009-04-29 18:50:19 +00002322 // With leaks, we want to unique them by the location where they were
2323 // allocated, and only report a single path. To do this, we need to find
2324 // the allocation site of a piece of tracked memory, which we do via a
2325 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2326 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2327 // that all ancestor nodes that represent the allocation site have the
2328 // same SourceLocation.
Craig Topper0dbb7832014-05-27 02:45:47 +00002329 const ExplodedNode *AllocNode = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002330
Anna Zaks58734db2011-10-25 19:57:11 +00002331 const SourceManager& SMgr = Ctx.getSourceManager();
Anna Zaksc29bed32011-09-20 21:38:35 +00002332
Anna Zakse51362e2013-04-10 21:42:06 +00002333 AllocationInfo AllocI =
Anna Zaks58734db2011-10-25 19:57:11 +00002334 GetAllocationSite(Ctx.getStateManager(), getErrorNode(), sym);
Mike Stump11289f42009-09-09 15:08:12 +00002335
Anna Zakse51362e2013-04-10 21:42:06 +00002336 AllocNode = AllocI.N;
2337 AllocBinding = AllocI.R;
2338 markInteresting(AllocI.InterestingMethodContext);
2339
Ted Kremenek6bd78702009-04-29 18:50:19 +00002340 // Get the SourceLocation for the allocation site.
Jordan Rosefbe6dba2012-07-10 22:07:52 +00002341 // FIXME: This will crash the analyzer if an allocation comes from an
Anna Zaksa6fea132014-06-13 23:47:38 +00002342 // implicit call (ex: a destructor call).
2343 // (Currently there are no such allocations in Cocoa, though.)
2344 const Stmt *AllocStmt = 0;
Ted Kremenek6bd78702009-04-29 18:50:19 +00002345 ProgramPoint P = AllocNode->getLocation();
David Blaikie87396b92013-02-21 22:23:56 +00002346 if (Optional<CallExitEnd> Exit = P.getAs<CallExitEnd>())
Jordan Rosefbe6dba2012-07-10 22:07:52 +00002347 AllocStmt = Exit->getCalleeContext()->getCallSite();
Anna Zaksa6fea132014-06-13 23:47:38 +00002348 else {
2349 // We are going to get a BlockEdge when the leak and allocation happen in
2350 // different, non-nested frames (contexts). For example, the case where an
2351 // allocation happens in a block that captures a reference to it and
2352 // that reference is overwritten/dropped by another call to the block.
2353 if (Optional<BlockEdge> Edge = P.getAs<BlockEdge>()) {
2354 if (Optional<CFGStmt> St = Edge->getDst()->front().getAs<CFGStmt>()) {
2355 AllocStmt = St->getStmt();
2356 }
2357 }
2358 else {
2359 AllocStmt = P.castAs<PostStmt>().getStmt();
2360 }
2361 }
2362 assert(AllocStmt && "Cannot find allocation statement");
Anna Zaks40402872013-04-23 23:57:50 +00002363
2364 PathDiagnosticLocation AllocLocation =
2365 PathDiagnosticLocation::createBegin(AllocStmt, SMgr,
2366 AllocNode->getLocationContext());
2367 Location = AllocLocation;
2368
2369 // Set uniqieing info, which will be used for unique the bug reports. The
2370 // leaks should be uniqued on the allocation site.
2371 UniqueingLocation = AllocLocation;
2372 UniqueingDecl = AllocNode->getLocationContext()->getDecl();
2373
Ted Kremenek6bd78702009-04-29 18:50:19 +00002374 // Fill in the description of the bug.
2375 Description.clear();
2376 llvm::raw_string_ostream os(Description);
Ted Kremenekf1e76672009-05-02 19:05:19 +00002377 os << "Potential leak ";
Jordy Rose184bd142011-08-24 22:39:09 +00002378 if (GCEnabled)
Ted Kremenekf1e76672009-05-02 19:05:19 +00002379 os << "(when using garbage collection) ";
Anna Zaks16f38312012-02-28 21:49:08 +00002380 os << "of an object";
Mike Stump11289f42009-09-09 15:08:12 +00002381
Ted Kremenek8671acb2013-04-16 21:44:22 +00002382 if (AllocBinding) {
Anna Zaks16f38312012-02-28 21:49:08 +00002383 os << " stored into '" << AllocBinding->getString() << '\'';
Ted Kremenek8671acb2013-04-16 21:44:22 +00002384 if (IncludeAllocationLine) {
2385 FullSourceLoc SL(AllocStmt->getLocStart(), Ctx.getSourceManager());
2386 os << " (allocated on line " << SL.getSpellingLineNumber() << ")";
2387 }
2388 }
Anna Zaks071a89c2011-08-19 23:21:56 +00002389
David Blaikie91e79022014-09-04 23:54:33 +00002390 addVisitor(llvm::make_unique<CFRefLeakReportVisitor>(sym, GCEnabled, Log));
Ted Kremenek6bd78702009-04-29 18:50:19 +00002391}
2392
2393//===----------------------------------------------------------------------===//
2394// Main checker logic.
2395//===----------------------------------------------------------------------===//
2396
Ted Kremenek70a87882009-11-25 22:17:44 +00002397namespace {
Jordy Rose75e680e2011-09-02 06:44:22 +00002398class RetainCountChecker
Jordy Rose5df640d2011-08-24 18:56:32 +00002399 : public Checker< check::Bind,
Jordy Rose78612762011-08-23 19:01:07 +00002400 check::DeadSymbols,
Jordy Rose5df640d2011-08-24 18:56:32 +00002401 check::EndAnalysis,
Anna Zaks3fdcc0b2013-01-03 00:25:29 +00002402 check::EndFunction,
Jordy Rose217eb902011-08-17 21:27:39 +00002403 check::PostStmt<BlockExpr>,
John McCall31168b02011-06-15 23:02:42 +00002404 check::PostStmt<CastExpr>,
Ted Kremenek415287d2012-03-06 20:06:12 +00002405 check::PostStmt<ObjCArrayLiteral>,
2406 check::PostStmt<ObjCDictionaryLiteral>,
Jordy Rose6393f822012-05-12 05:10:43 +00002407 check::PostStmt<ObjCBoxedExpr>,
Jordan Roseb3ad07e2014-03-25 17:10:58 +00002408 check::PostStmt<ObjCIvarRefExpr>,
Jordan Rose682b3162012-07-02 19:28:21 +00002409 check::PostCall,
Jordy Rose298cc4d2011-08-23 19:43:16 +00002410 check::PreStmt<ReturnStmt>,
Jordy Rose217eb902011-08-17 21:27:39 +00002411 check::RegionChanges,
Jordy Rose898a1482011-08-21 21:58:18 +00002412 eval::Assume,
2413 eval::Call > {
Ahmed Charlesb8984322014-03-07 20:03:18 +00002414 mutable std::unique_ptr<CFRefBug> useAfterRelease, releaseNotOwned;
2415 mutable std::unique_ptr<CFRefBug> deallocGC, deallocNotOwned;
2416 mutable std::unique_ptr<CFRefBug> overAutorelease, returnNotOwnedForOwned;
2417 mutable std::unique_ptr<CFRefBug> leakWithinFunction, leakAtReturn;
2418 mutable std::unique_ptr<CFRefBug> leakWithinFunctionGC, leakAtReturnGC;
Jordy Rose78612762011-08-23 19:01:07 +00002419
Anton Yartsev6a619222014-02-17 18:25:34 +00002420 typedef llvm::DenseMap<SymbolRef, const CheckerProgramPointTag *> SymbolTagMap;
Jordy Rose78612762011-08-23 19:01:07 +00002421
2422 // This map is only used to ensure proper deletion of any allocated tags.
2423 mutable SymbolTagMap DeadSymbolTags;
2424
Ahmed Charlesb8984322014-03-07 20:03:18 +00002425 mutable std::unique_ptr<RetainSummaryManager> Summaries;
2426 mutable std::unique_ptr<RetainSummaryManager> SummariesGC;
Jordy Rose5df640d2011-08-24 18:56:32 +00002427 mutable SummaryLogTy SummaryLog;
2428 mutable bool ShouldResetSummaryLog;
2429
Ted Kremenek8671acb2013-04-16 21:44:22 +00002430 /// Optional setting to indicate if leak reports should include
2431 /// the allocation line.
2432 mutable bool IncludeAllocationLine;
2433
Jordy Rosea8f99ba2011-08-20 21:17:59 +00002434public:
Ted Kremenek8671acb2013-04-16 21:44:22 +00002435 RetainCountChecker(AnalyzerOptions &AO)
2436 : ShouldResetSummaryLog(false),
2437 IncludeAllocationLine(shouldIncludeAllocationSiteInLeakDiagnostics(AO)) {}
Jordy Rose78612762011-08-23 19:01:07 +00002438
Jordy Rose75e680e2011-09-02 06:44:22 +00002439 virtual ~RetainCountChecker() {
Jordy Rose78612762011-08-23 19:01:07 +00002440 DeleteContainerSeconds(DeadSymbolTags);
2441 }
2442
Jordy Rose5df640d2011-08-24 18:56:32 +00002443 void checkEndAnalysis(ExplodedGraph &G, BugReporter &BR,
2444 ExprEngine &Eng) const {
2445 // FIXME: This is a hack to make sure the summary log gets cleared between
2446 // analyses of different code bodies.
2447 //
2448 // Why is this necessary? Because a checker's lifetime is tied to a
2449 // translation unit, but an ExplodedGraph's lifetime is just a code body.
2450 // Once in a blue moon, a new ExplodedNode will have the same address as an
2451 // old one with an associated summary, and the bug report visitor gets very
2452 // confused. (To make things worse, the summary lifetime is currently also
2453 // tied to a code body, so we get a crash instead of incorrect results.)
Jordy Rose95589f12011-08-24 09:27:24 +00002454 //
2455 // Why is this a bad solution? Because if the lifetime of the ExplodedGraph
2456 // changes, things will start going wrong again. Really the lifetime of this
2457 // log needs to be tied to either the specific nodes in it or the entire
2458 // ExplodedGraph, not to a specific part of the code being analyzed.
2459 //
Jordy Rose5df640d2011-08-24 18:56:32 +00002460 // (Also, having stateful local data means that the same checker can't be
2461 // used from multiple threads, but a lot of checkers have incorrect
2462 // assumptions about that anyway. So that wasn't a priority at the time of
2463 // this fix.)
Jordy Rose95589f12011-08-24 09:27:24 +00002464 //
Jordy Rose5df640d2011-08-24 18:56:32 +00002465 // This happens at the end of analysis, but bug reports are emitted /after/
2466 // this point. So we can't just clear the summary log now. Instead, we mark
2467 // that the next time we access the summary log, it should be cleared.
2468
2469 // If we never reset the summary log during /this/ code body analysis,
2470 // there were no new summaries. There might still have been summaries from
2471 // the /last/ analysis, so clear them out to make sure the bug report
2472 // visitors don't get confused.
2473 if (ShouldResetSummaryLog)
2474 SummaryLog.clear();
2475
2476 ShouldResetSummaryLog = !SummaryLog.empty();
Jordy Rose95589f12011-08-24 09:27:24 +00002477 }
2478
Jordy Rosec49ec532011-09-02 05:55:19 +00002479 CFRefBug *getLeakWithinFunctionBug(const LangOptions &LOpts,
2480 bool GCEnabled) const {
2481 if (GCEnabled) {
Jordy Rose15484da2011-08-25 01:14:38 +00002482 if (!leakWithinFunctionGC)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002483 leakWithinFunctionGC.reset(new Leak(this, "Leak of object when using "
2484 "garbage collection"));
Jordy Rosec49ec532011-09-02 05:55:19 +00002485 return leakWithinFunctionGC.get();
Jordy Rose15484da2011-08-25 01:14:38 +00002486 } else {
2487 if (!leakWithinFunction) {
Douglas Gregor79a91412011-09-13 17:21:33 +00002488 if (LOpts.getGC() == LangOptions::HybridGC) {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002489 leakWithinFunction.reset(new Leak(this,
2490 "Leak of object when not using "
Benjamin Kramerd1d76b22012-06-06 17:32:50 +00002491 "garbage collection (GC) in "
2492 "dual GC/non-GC code"));
Jordy Rose15484da2011-08-25 01:14:38 +00002493 } else {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002494 leakWithinFunction.reset(new Leak(this, "Leak"));
Jordy Rose15484da2011-08-25 01:14:38 +00002495 }
2496 }
Jordy Rosec49ec532011-09-02 05:55:19 +00002497 return leakWithinFunction.get();
Jordy Rose15484da2011-08-25 01:14:38 +00002498 }
2499 }
2500
Jordy Rosec49ec532011-09-02 05:55:19 +00002501 CFRefBug *getLeakAtReturnBug(const LangOptions &LOpts, bool GCEnabled) const {
2502 if (GCEnabled) {
Jordy Rose15484da2011-08-25 01:14:38 +00002503 if (!leakAtReturnGC)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002504 leakAtReturnGC.reset(new Leak(this,
2505 "Leak of returned object when using "
Benjamin Kramerd1d76b22012-06-06 17:32:50 +00002506 "garbage collection"));
Jordy Rosec49ec532011-09-02 05:55:19 +00002507 return leakAtReturnGC.get();
Jordy Rose15484da2011-08-25 01:14:38 +00002508 } else {
2509 if (!leakAtReturn) {
Douglas Gregor79a91412011-09-13 17:21:33 +00002510 if (LOpts.getGC() == LangOptions::HybridGC) {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002511 leakAtReturn.reset(new Leak(this,
2512 "Leak of returned object when not using "
Benjamin Kramerd1d76b22012-06-06 17:32:50 +00002513 "garbage collection (GC) in dual "
2514 "GC/non-GC code"));
Jordy Rose15484da2011-08-25 01:14:38 +00002515 } else {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002516 leakAtReturn.reset(new Leak(this, "Leak of returned object"));
Jordy Rose15484da2011-08-25 01:14:38 +00002517 }
2518 }
Jordy Rosec49ec532011-09-02 05:55:19 +00002519 return leakAtReturn.get();
Jordy Rose15484da2011-08-25 01:14:38 +00002520 }
2521 }
2522
Jordy Rosec49ec532011-09-02 05:55:19 +00002523 RetainSummaryManager &getSummaryManager(ASTContext &Ctx,
2524 bool GCEnabled) const {
2525 // FIXME: We don't support ARC being turned on and off during one analysis.
2526 // (nor, for that matter, do we support changing ASTContexts)
David Blaikiebbafb8a2012-03-11 07:00:24 +00002527 bool ARCEnabled = (bool)Ctx.getLangOpts().ObjCAutoRefCount;
Jordy Rosec49ec532011-09-02 05:55:19 +00002528 if (GCEnabled) {
2529 if (!SummariesGC)
Jordy Rose8b289a22011-08-25 00:10:37 +00002530 SummariesGC.reset(new RetainSummaryManager(Ctx, true, ARCEnabled));
Jordy Rosec49ec532011-09-02 05:55:19 +00002531 else
2532 assert(SummariesGC->isARCEnabled() == ARCEnabled);
Jordy Rose8b289a22011-08-25 00:10:37 +00002533 return *SummariesGC;
2534 } else {
Jordy Rosec49ec532011-09-02 05:55:19 +00002535 if (!Summaries)
Jordy Rose8b289a22011-08-25 00:10:37 +00002536 Summaries.reset(new RetainSummaryManager(Ctx, false, ARCEnabled));
Jordy Rosec49ec532011-09-02 05:55:19 +00002537 else
2538 assert(Summaries->isARCEnabled() == ARCEnabled);
Jordy Rose8b289a22011-08-25 00:10:37 +00002539 return *Summaries;
2540 }
2541 }
2542
Jordy Rosec49ec532011-09-02 05:55:19 +00002543 RetainSummaryManager &getSummaryManager(CheckerContext &C) const {
2544 return getSummaryManager(C.getASTContext(), C.isObjCGCEnabled());
2545 }
2546
Ted Kremenek49b1e382012-01-26 21:29:00 +00002547 void printState(raw_ostream &Out, ProgramStateRef State,
Craig Topperfb6b25b2014-03-15 04:29:04 +00002548 const char *NL, const char *Sep) const override;
Jordy Rose58a20d32011-08-28 19:11:56 +00002549
Anna Zaks3e0f4152011-10-06 00:43:15 +00002550 void checkBind(SVal loc, SVal val, const Stmt *S, CheckerContext &C) const;
Jordy Rose5c252ef2011-08-20 21:16:58 +00002551 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
2552 void checkPostStmt(const CastExpr *CE, CheckerContext &C) const;
John McCall31168b02011-06-15 23:02:42 +00002553
Ted Kremenek415287d2012-03-06 20:06:12 +00002554 void checkPostStmt(const ObjCArrayLiteral *AL, CheckerContext &C) const;
2555 void checkPostStmt(const ObjCDictionaryLiteral *DL, CheckerContext &C) const;
Jordy Rose6393f822012-05-12 05:10:43 +00002556 void checkPostStmt(const ObjCBoxedExpr *BE, CheckerContext &C) const;
2557
Jordan Roseb3ad07e2014-03-25 17:10:58 +00002558 void checkPostStmt(const ObjCIvarRefExpr *IRE, CheckerContext &C) const;
2559
Jordan Rose682b3162012-07-02 19:28:21 +00002560 void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
Ted Kremenek415287d2012-03-06 20:06:12 +00002561
Jordan Roseeec15392012-07-02 19:27:43 +00002562 void checkSummary(const RetainSummary &Summ, const CallEvent &Call,
Jordy Rosed188d662011-08-28 05:16:28 +00002563 CheckerContext &C) const;
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002564
Anna Zaks25612732012-08-29 23:23:43 +00002565 void processSummaryOfInlined(const RetainSummary &Summ,
2566 const CallEvent &Call,
2567 CheckerContext &C) const;
2568
Jordy Rose898a1482011-08-21 21:58:18 +00002569 bool evalCall(const CallExpr *CE, CheckerContext &C) const;
2570
Ted Kremenek49b1e382012-01-26 21:29:00 +00002571 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Jordy Rose5c252ef2011-08-20 21:16:58 +00002572 bool Assumption) const;
Jordy Rose217eb902011-08-17 21:27:39 +00002573
Ted Kremenek49b1e382012-01-26 21:29:00 +00002574 ProgramStateRef
2575 checkRegionChanges(ProgramStateRef state,
Anna Zaksdc154152012-12-20 00:38:25 +00002576 const InvalidatedSymbols *invalidated,
Jordy Rose1fad6632011-08-27 22:51:26 +00002577 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks3d348342012-02-14 21:55:24 +00002578 ArrayRef<const MemRegion *> Regions,
Jordan Rose742920c2012-07-02 19:27:35 +00002579 const CallEvent *Call) const;
Jordy Rose5c252ef2011-08-20 21:16:58 +00002580
Ted Kremenek49b1e382012-01-26 21:29:00 +00002581 bool wantsRegionChangeUpdate(ProgramStateRef state) const {
Jordy Rosea8f99ba2011-08-20 21:17:59 +00002582 return true;
Jordy Rose5c252ef2011-08-20 21:16:58 +00002583 }
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002584
Jordy Rose298cc4d2011-08-23 19:43:16 +00002585 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
2586 void checkReturnWithRetEffect(const ReturnStmt *S, CheckerContext &C,
2587 ExplodedNode *Pred, RetEffect RE, RefVal X,
Ted Kremenek49b1e382012-01-26 21:29:00 +00002588 SymbolRef Sym, ProgramStateRef state) const;
Jordy Rose298cc4d2011-08-23 19:43:16 +00002589
Jordy Rose78612762011-08-23 19:01:07 +00002590 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Anna Zaks3fdcc0b2013-01-03 00:25:29 +00002591 void checkEndFunction(CheckerContext &C) const;
Jordy Rose78612762011-08-23 19:01:07 +00002592
Ted Kremenek49b1e382012-01-26 21:29:00 +00002593 ProgramStateRef updateSymbol(ProgramStateRef state, SymbolRef sym,
Anna Zaks25612732012-08-29 23:23:43 +00002594 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
2595 CheckerContext &C) const;
Jordy Rosebf77e512011-08-23 20:27:16 +00002596
Ted Kremenek49b1e382012-01-26 21:29:00 +00002597 void processNonLeakError(ProgramStateRef St, SourceRange ErrorRange,
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002598 RefVal::Kind ErrorKind, SymbolRef Sym,
2599 CheckerContext &C) const;
Ted Kremenek415287d2012-03-06 20:06:12 +00002600
2601 void processObjCLiterals(CheckerContext &C, const Expr *Ex) const;
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002602
Jordy Rose78612762011-08-23 19:01:07 +00002603 const ProgramPointTag *getDeadSymbolTag(SymbolRef sym) const;
2604
Ted Kremenek49b1e382012-01-26 21:29:00 +00002605 ProgramStateRef handleSymbolDeath(ProgramStateRef state,
Anna Zaksf5788c72012-08-14 00:36:15 +00002606 SymbolRef sid, RefVal V,
2607 SmallVectorImpl<SymbolRef> &Leaked) const;
Jordy Rose78612762011-08-23 19:01:07 +00002608
Jordan Roseff03c1d2012-12-06 18:58:18 +00002609 ProgramStateRef
Jordan Rose9f61f8a2012-08-18 00:30:16 +00002610 handleAutoreleaseCounts(ProgramStateRef state, ExplodedNode *Pred,
2611 const ProgramPointTag *Tag, CheckerContext &Ctx,
2612 SymbolRef Sym, RefVal V) const;
Jordy Rose6763e382011-08-23 20:07:14 +00002613
Ted Kremenek49b1e382012-01-26 21:29:00 +00002614 ExplodedNode *processLeaks(ProgramStateRef state,
Jordy Rose78612762011-08-23 19:01:07 +00002615 SmallVectorImpl<SymbolRef> &Leaked,
Anna Zaks58734db2011-10-25 19:57:11 +00002616 CheckerContext &Ctx,
Craig Topper0dbb7832014-05-27 02:45:47 +00002617 ExplodedNode *Pred = nullptr) const;
Ted Kremenek70a87882009-11-25 22:17:44 +00002618};
2619} // end anonymous namespace
2620
Jordy Rose217eb902011-08-17 21:27:39 +00002621namespace {
2622class StopTrackingCallback : public SymbolVisitor {
Ted Kremenek49b1e382012-01-26 21:29:00 +00002623 ProgramStateRef state;
Jordy Rose217eb902011-08-17 21:27:39 +00002624public:
Ted Kremenek49b1e382012-01-26 21:29:00 +00002625 StopTrackingCallback(ProgramStateRef st) : state(st) {}
2626 ProgramStateRef getState() const { return state; }
Jordy Rose217eb902011-08-17 21:27:39 +00002627
Craig Topperfb6b25b2014-03-15 04:29:04 +00002628 bool VisitSymbol(SymbolRef sym) override {
Jordy Rose217eb902011-08-17 21:27:39 +00002629 state = state->remove<RefBindings>(sym);
2630 return true;
2631 }
2632};
2633} // end anonymous namespace
2634
Jordy Rose75e680e2011-09-02 06:44:22 +00002635//===----------------------------------------------------------------------===//
2636// Handle statements that may have an effect on refcounts.
2637//===----------------------------------------------------------------------===//
Jordy Rose217eb902011-08-17 21:27:39 +00002638
Jordy Rose75e680e2011-09-02 06:44:22 +00002639void RetainCountChecker::checkPostStmt(const BlockExpr *BE,
2640 CheckerContext &C) const {
Jordy Rose217eb902011-08-17 21:27:39 +00002641
Jordy Rose75e680e2011-09-02 06:44:22 +00002642 // Scan the BlockDecRefExprs for any object the retain count checker
Ted Kremenekbd862712010-07-01 20:16:50 +00002643 // may be tracking.
John McCallc63de662011-02-02 13:00:07 +00002644 if (!BE->getBlockDecl()->hasCaptures())
Ted Kremenekf89dcda2009-11-26 02:38:19 +00002645 return;
Ted Kremenekbd862712010-07-01 20:16:50 +00002646
Ted Kremenek49b1e382012-01-26 21:29:00 +00002647 ProgramStateRef state = C.getState();
Ted Kremenekf89dcda2009-11-26 02:38:19 +00002648 const BlockDataRegion *R =
Ted Kremenek632e3b72012-01-06 22:09:28 +00002649 cast<BlockDataRegion>(state->getSVal(BE,
2650 C.getLocationContext()).getAsRegion());
Ted Kremenekbd862712010-07-01 20:16:50 +00002651
Ted Kremenekf89dcda2009-11-26 02:38:19 +00002652 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
2653 E = R->referenced_vars_end();
Ted Kremenekbd862712010-07-01 20:16:50 +00002654
Ted Kremenekf89dcda2009-11-26 02:38:19 +00002655 if (I == E)
2656 return;
Ted Kremenekbd862712010-07-01 20:16:50 +00002657
Ted Kremenek04af9f22009-12-07 22:05:27 +00002658 // FIXME: For now we invalidate the tracking of all symbols passed to blocks
2659 // via captured variables, even though captured variables result in a copy
2660 // and in implicit increment/decrement of a retain count.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002661 SmallVector<const MemRegion*, 10> Regions;
Anna Zaksc9abbe22011-10-26 21:06:44 +00002662 const LocationContext *LC = C.getLocationContext();
Ted Kremenek90af9092010-12-02 07:49:45 +00002663 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
Ted Kremenekbd862712010-07-01 20:16:50 +00002664
Ted Kremenek04af9f22009-12-07 22:05:27 +00002665 for ( ; I != E; ++I) {
Ted Kremenekbcf90532012-12-06 07:17:20 +00002666 const VarRegion *VR = I.getCapturedRegion();
Ted Kremenek04af9f22009-12-07 22:05:27 +00002667 if (VR->getSuperRegion() == R) {
2668 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2669 }
2670 Regions.push_back(VR);
2671 }
Ted Kremenekbd862712010-07-01 20:16:50 +00002672
Ted Kremenek04af9f22009-12-07 22:05:27 +00002673 state =
2674 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
2675 Regions.data() + Regions.size()).getState();
Anna Zaksda4c8d62011-10-26 21:06:34 +00002676 C.addTransition(state);
Ted Kremenekf89dcda2009-11-26 02:38:19 +00002677}
2678
Jordy Rose75e680e2011-09-02 06:44:22 +00002679void RetainCountChecker::checkPostStmt(const CastExpr *CE,
2680 CheckerContext &C) const {
John McCall31168b02011-06-15 23:02:42 +00002681 const ObjCBridgedCastExpr *BE = dyn_cast<ObjCBridgedCastExpr>(CE);
2682 if (!BE)
2683 return;
2684
John McCall640767f2011-06-17 06:50:50 +00002685 ArgEffect AE = IncRef;
John McCall31168b02011-06-15 23:02:42 +00002686
2687 switch (BE->getBridgeKind()) {
2688 case clang::OBC_Bridge:
2689 // Do nothing.
2690 return;
2691 case clang::OBC_BridgeRetained:
2692 AE = IncRef;
2693 break;
2694 case clang::OBC_BridgeTransfer:
Benjamin Kramer1d5d6342013-10-20 11:53:20 +00002695 AE = DecRefBridgedTransferred;
John McCall31168b02011-06-15 23:02:42 +00002696 break;
2697 }
2698
Ted Kremenek49b1e382012-01-26 21:29:00 +00002699 ProgramStateRef state = C.getState();
Ted Kremenek632e3b72012-01-06 22:09:28 +00002700 SymbolRef Sym = state->getSVal(CE, C.getLocationContext()).getAsLocSymbol();
John McCall31168b02011-06-15 23:02:42 +00002701 if (!Sym)
2702 return;
Anna Zaksf5788c72012-08-14 00:36:15 +00002703 const RefVal* T = getRefBinding(state, Sym);
John McCall31168b02011-06-15 23:02:42 +00002704 if (!T)
2705 return;
2706
John McCall31168b02011-06-15 23:02:42 +00002707 RefVal::Kind hasErr = (RefVal::Kind) 0;
Jordy Rosec49ec532011-09-02 05:55:19 +00002708 state = updateSymbol(state, Sym, *T, AE, hasErr, C);
John McCall31168b02011-06-15 23:02:42 +00002709
2710 if (hasErr) {
Jordy Rosebf77e512011-08-23 20:27:16 +00002711 // FIXME: If we get an error during a bridge cast, should we report it?
2712 // Should we assert that there is no error?
John McCall31168b02011-06-15 23:02:42 +00002713 return;
2714 }
2715
Anna Zaksda4c8d62011-10-26 21:06:34 +00002716 C.addTransition(state);
John McCall31168b02011-06-15 23:02:42 +00002717}
2718
Ted Kremenek415287d2012-03-06 20:06:12 +00002719void RetainCountChecker::processObjCLiterals(CheckerContext &C,
2720 const Expr *Ex) const {
2721 ProgramStateRef state = C.getState();
2722 const ExplodedNode *pred = C.getPredecessor();
2723 for (Stmt::const_child_iterator it = Ex->child_begin(), et = Ex->child_end() ;
2724 it != et ; ++it) {
2725 const Stmt *child = *it;
2726 SVal V = state->getSVal(child, pred->getLocationContext());
2727 if (SymbolRef sym = V.getAsSymbol())
Anna Zaksf5788c72012-08-14 00:36:15 +00002728 if (const RefVal* T = getRefBinding(state, sym)) {
Ted Kremenek415287d2012-03-06 20:06:12 +00002729 RefVal::Kind hasErr = (RefVal::Kind) 0;
2730 state = updateSymbol(state, sym, *T, MayEscape, hasErr, C);
2731 if (hasErr) {
2732 processNonLeakError(state, child->getSourceRange(), hasErr, sym, C);
2733 return;
2734 }
2735 }
2736 }
2737
2738 // Return the object as autoreleased.
2739 // RetEffect RE = RetEffect::MakeNotOwned(RetEffect::ObjC);
2740 if (SymbolRef sym =
2741 state->getSVal(Ex, pred->getLocationContext()).getAsSymbol()) {
2742 QualType ResultTy = Ex->getType();
Anna Zaksf5788c72012-08-14 00:36:15 +00002743 state = setRefBinding(state, sym,
2744 RefVal::makeNotOwned(RetEffect::ObjC, ResultTy));
Ted Kremenek415287d2012-03-06 20:06:12 +00002745 }
2746
2747 C.addTransition(state);
2748}
2749
2750void RetainCountChecker::checkPostStmt(const ObjCArrayLiteral *AL,
2751 CheckerContext &C) const {
2752 // Apply the 'MayEscape' to all values.
2753 processObjCLiterals(C, AL);
2754}
2755
2756void RetainCountChecker::checkPostStmt(const ObjCDictionaryLiteral *DL,
2757 CheckerContext &C) const {
2758 // Apply the 'MayEscape' to all keys and values.
2759 processObjCLiterals(C, DL);
2760}
2761
Jordy Rose6393f822012-05-12 05:10:43 +00002762void RetainCountChecker::checkPostStmt(const ObjCBoxedExpr *Ex,
2763 CheckerContext &C) const {
2764 const ExplodedNode *Pred = C.getPredecessor();
2765 const LocationContext *LCtx = Pred->getLocationContext();
2766 ProgramStateRef State = Pred->getState();
2767
2768 if (SymbolRef Sym = State->getSVal(Ex, LCtx).getAsSymbol()) {
2769 QualType ResultTy = Ex->getType();
Anna Zaksf5788c72012-08-14 00:36:15 +00002770 State = setRefBinding(State, Sym,
2771 RefVal::makeNotOwned(RetEffect::ObjC, ResultTy));
Jordy Rose6393f822012-05-12 05:10:43 +00002772 }
2773
2774 C.addTransition(State);
2775}
2776
Jordan Roseb3ad07e2014-03-25 17:10:58 +00002777void RetainCountChecker::checkPostStmt(const ObjCIvarRefExpr *IRE,
2778 CheckerContext &C) const {
2779 ProgramStateRef State = C.getState();
2780 // If an instance variable was previously accessed through a property,
2781 // it may have a synthesized refcount of +0. Override right now that we're
2782 // doing direct access.
2783 if (Optional<Loc> IVarLoc = C.getSVal(IRE).getAs<Loc>())
2784 if (SymbolRef Sym = State->getSVal(*IVarLoc).getAsSymbol())
2785 if (const RefVal *RV = getRefBinding(State, Sym))
2786 if (RV->isOverridable())
2787 State = removeRefBinding(State, Sym);
2788 C.addTransition(State);
2789}
2790
Jordan Rose682b3162012-07-02 19:28:21 +00002791void RetainCountChecker::checkPostCall(const CallEvent &Call,
2792 CheckerContext &C) const {
Jordan Rose682b3162012-07-02 19:28:21 +00002793 RetainSummaryManager &Summaries = getSummaryManager(C);
2794 const RetainSummary *Summ = Summaries.getSummary(Call, C.getState());
Anna Zaks25612732012-08-29 23:23:43 +00002795
2796 if (C.wasInlined) {
2797 processSummaryOfInlined(*Summ, Call, C);
2798 return;
2799 }
Jordan Rose682b3162012-07-02 19:28:21 +00002800 checkSummary(*Summ, Call, C);
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002801}
2802
Jordy Rose75e680e2011-09-02 06:44:22 +00002803/// GetReturnType - Used to get the return type of a message expression or
2804/// function call with the intention of affixing that type to a tracked symbol.
Sylvestre Ledru830885c2012-07-23 08:59:39 +00002805/// While the return type can be queried directly from RetEx, when
Jordy Rose75e680e2011-09-02 06:44:22 +00002806/// invoking class methods we augment to the return type to be that of
2807/// a pointer to the class (as opposed it just being id).
2808// FIXME: We may be able to do this with related result types instead.
2809// This function is probably overestimating.
2810static QualType GetReturnType(const Expr *RetE, ASTContext &Ctx) {
2811 QualType RetTy = RetE->getType();
2812 // If RetE is not a message expression just return its type.
2813 // If RetE is a message expression, return its types if it is something
2814 /// more specific than id.
2815 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RetE))
2816 if (const ObjCObjectPointerType *PT = RetTy->getAs<ObjCObjectPointerType>())
2817 if (PT->isObjCQualifiedIdType() || PT->isObjCIdType() ||
2818 PT->isObjCClassType()) {
2819 // At this point we know the return type of the message expression is
2820 // id, id<...>, or Class. If we have an ObjCInterfaceDecl, we know this
2821 // is a call to a class method whose type we can resolve. In such
2822 // cases, promote the return type to XXX* (where XXX is the class).
2823 const ObjCInterfaceDecl *D = ME->getReceiverInterface();
2824 return !D ? RetTy :
2825 Ctx.getObjCObjectPointerType(Ctx.getObjCInterfaceType(D));
2826 }
2827
2828 return RetTy;
2829}
2830
Jordan Rose1a866cd2014-01-10 20:06:06 +00002831static bool wasSynthesizedProperty(const ObjCMethodCall *Call,
2832 ExplodedNode *N) {
2833 if (!Call || !Call->getDecl()->isPropertyAccessor())
2834 return false;
2835
2836 CallExitEnd PP = N->getLocation().castAs<CallExitEnd>();
2837 const StackFrameContext *Frame = PP.getCalleeContext();
2838 return Frame->getAnalysisDeclContext()->isBodyAutosynthesized();
2839}
2840
Anna Zaks25612732012-08-29 23:23:43 +00002841// We don't always get the exact modeling of the function with regards to the
2842// retain count checker even when the function is inlined. For example, we need
2843// to stop tracking the symbols which were marked with StopTrackingHard.
2844void RetainCountChecker::processSummaryOfInlined(const RetainSummary &Summ,
2845 const CallEvent &CallOrMsg,
2846 CheckerContext &C) const {
2847 ProgramStateRef state = C.getState();
2848
2849 // Evaluate the effect of the arguments.
2850 for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
2851 if (Summ.getArg(idx) == StopTrackingHard) {
2852 SVal V = CallOrMsg.getArgSVal(idx);
2853 if (SymbolRef Sym = V.getAsLocSymbol()) {
2854 state = removeRefBinding(state, Sym);
2855 }
2856 }
2857 }
2858
2859 // Evaluate the effect on the message receiver.
2860 const ObjCMethodCall *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg);
2861 if (MsgInvocation) {
2862 if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
2863 if (Summ.getReceiverEffect() == StopTrackingHard) {
2864 state = removeRefBinding(state, Sym);
2865 }
2866 }
2867 }
2868
2869 // Consult the summary for the return value.
2870 RetEffect RE = Summ.getRetEffect();
2871 if (RE.getKind() == RetEffect::NoRetHard) {
Jordan Rose829c3832012-11-02 23:49:29 +00002872 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
Anna Zaks25612732012-08-29 23:23:43 +00002873 if (Sym)
2874 state = removeRefBinding(state, Sym);
Jordan Rose1a866cd2014-01-10 20:06:06 +00002875 } else if (RE.getKind() == RetEffect::NotOwnedSymbol) {
2876 if (wasSynthesizedProperty(MsgInvocation, C.getPredecessor())) {
Jordan Roseb3ad07e2014-03-25 17:10:58 +00002877 // Believe the summary if we synthesized the body of a property getter
2878 // and the return value is currently untracked. If the corresponding
2879 // instance variable is later accessed directly, however, we're going to
2880 // want to override this state, so that the owning object can perform
2881 // reference counting operations on its own ivars.
Jordan Rose1a866cd2014-01-10 20:06:06 +00002882 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
2883 if (Sym && !getRefBinding(state, Sym))
Jordan Roseb3ad07e2014-03-25 17:10:58 +00002884 state = setRefBinding(state, Sym,
2885 RefVal::makeOverridableNotOwned(RE.getObjKind(),
2886 Sym->getType()));
Jordan Rose1a866cd2014-01-10 20:06:06 +00002887 }
Anna Zaks25612732012-08-29 23:23:43 +00002888 }
2889
2890 C.addTransition(state);
2891}
2892
Jordy Rose75e680e2011-09-02 06:44:22 +00002893void RetainCountChecker::checkSummary(const RetainSummary &Summ,
Jordan Roseeec15392012-07-02 19:27:43 +00002894 const CallEvent &CallOrMsg,
Jordy Rose75e680e2011-09-02 06:44:22 +00002895 CheckerContext &C) const {
Ted Kremenek49b1e382012-01-26 21:29:00 +00002896 ProgramStateRef state = C.getState();
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002897
2898 // Evaluate the effect of the arguments.
2899 RefVal::Kind hasErr = (RefVal::Kind) 0;
2900 SourceRange ErrorRange;
Craig Topper0dbb7832014-05-27 02:45:47 +00002901 SymbolRef ErrorSym = nullptr;
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002902
2903 for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
Jordy Rose1fad6632011-08-27 22:51:26 +00002904 SVal V = CallOrMsg.getArgSVal(idx);
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002905
2906 if (SymbolRef Sym = V.getAsLocSymbol()) {
Anna Zaksf5788c72012-08-14 00:36:15 +00002907 if (const RefVal *T = getRefBinding(state, Sym)) {
Jordy Rosec49ec532011-09-02 05:55:19 +00002908 state = updateSymbol(state, Sym, *T, Summ.getArg(idx), hasErr, C);
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002909 if (hasErr) {
2910 ErrorRange = CallOrMsg.getArgSourceRange(idx);
2911 ErrorSym = Sym;
2912 break;
2913 }
2914 }
2915 }
2916 }
2917
2918 // Evaluate the effect on the message receiver.
2919 bool ReceiverIsTracked = false;
Jordan Roseeec15392012-07-02 19:27:43 +00002920 if (!hasErr) {
Jordan Rose6bad4902012-07-02 19:27:56 +00002921 const ObjCMethodCall *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg);
Jordan Roseeec15392012-07-02 19:27:43 +00002922 if (MsgInvocation) {
2923 if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
Anna Zaksf5788c72012-08-14 00:36:15 +00002924 if (const RefVal *T = getRefBinding(state, Sym)) {
Jordan Roseeec15392012-07-02 19:27:43 +00002925 ReceiverIsTracked = true;
2926 state = updateSymbol(state, Sym, *T, Summ.getReceiverEffect(),
Anna Zaks25612732012-08-29 23:23:43 +00002927 hasErr, C);
Jordan Roseeec15392012-07-02 19:27:43 +00002928 if (hasErr) {
Jordan Rose627b0462012-07-18 21:59:51 +00002929 ErrorRange = MsgInvocation->getOriginExpr()->getReceiverRange();
Jordan Roseeec15392012-07-02 19:27:43 +00002930 ErrorSym = Sym;
2931 }
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002932 }
2933 }
2934 }
2935 }
2936
2937 // Process any errors.
2938 if (hasErr) {
2939 processNonLeakError(state, ErrorRange, hasErr, ErrorSym, C);
2940 return;
2941 }
2942
2943 // Consult the summary for the return value.
2944 RetEffect RE = Summ.getRetEffect();
2945
2946 if (RE.getKind() == RetEffect::OwnedWhenTrackedReceiver) {
Jordy Rose8b289a22011-08-25 00:10:37 +00002947 if (ReceiverIsTracked)
Jordy Rosec49ec532011-09-02 05:55:19 +00002948 RE = getSummaryManager(C).getObjAllocRetEffect();
Jordy Rose8b289a22011-08-25 00:10:37 +00002949 else
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002950 RE = RetEffect::MakeNoRet();
2951 }
2952
2953 switch (RE.getKind()) {
2954 default:
David Blaikie8a40f702012-01-17 06:56:22 +00002955 llvm_unreachable("Unhandled RetEffect.");
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002956
2957 case RetEffect::NoRet:
Anna Zaks25612732012-08-29 23:23:43 +00002958 case RetEffect::NoRetHard:
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002959 // No work necessary.
2960 break;
2961
2962 case RetEffect::OwnedAllocatedSymbol:
2963 case RetEffect::OwnedSymbol: {
Jordan Rose829c3832012-11-02 23:49:29 +00002964 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002965 if (!Sym)
2966 break;
2967
Jordan Roseeec15392012-07-02 19:27:43 +00002968 // Use the result type from the CallEvent as it automatically adjusts
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002969 // for methods/functions that return references.
Jordan Roseeec15392012-07-02 19:27:43 +00002970 QualType ResultTy = CallOrMsg.getResultType();
Anna Zaksf5788c72012-08-14 00:36:15 +00002971 state = setRefBinding(state, Sym, RefVal::makeOwned(RE.getObjKind(),
2972 ResultTy));
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002973
2974 // FIXME: Add a flag to the checker where allocations are assumed to
Anna Zaks21487f72012-08-14 15:39:13 +00002975 // *not* fail.
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002976 break;
2977 }
2978
2979 case RetEffect::GCNotOwnedSymbol:
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002980 case RetEffect::NotOwnedSymbol: {
2981 const Expr *Ex = CallOrMsg.getOriginExpr();
Jordan Rose829c3832012-11-02 23:49:29 +00002982 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002983 if (!Sym)
2984 break;
Ted Kremenekbe400842012-10-12 22:56:45 +00002985 assert(Ex);
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002986 // Use GetReturnType in order to give [NSFoo alloc] the type NSFoo *.
2987 QualType ResultTy = GetReturnType(Ex, C.getASTContext());
Anna Zaksf5788c72012-08-14 00:36:15 +00002988 state = setRefBinding(state, Sym, RefVal::makeNotOwned(RE.getObjKind(),
2989 ResultTy));
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002990 break;
2991 }
2992 }
2993
2994 // This check is actually necessary; otherwise the statement builder thinks
2995 // we've hit a previously-found path.
2996 // Normally addTransition takes care of this, but we want the node pointer.
2997 ExplodedNode *NewNode;
2998 if (state == C.getState()) {
2999 NewNode = C.getPredecessor();
3000 } else {
Anna Zaksda4c8d62011-10-26 21:06:34 +00003001 NewNode = C.addTransition(state);
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003002 }
3003
Jordy Rose5df640d2011-08-24 18:56:32 +00003004 // Annotate the node with summary we used.
3005 if (NewNode) {
3006 // FIXME: This is ugly. See checkEndAnalysis for why it's necessary.
3007 if (ShouldResetSummaryLog) {
3008 SummaryLog.clear();
3009 ShouldResetSummaryLog = false;
3010 }
Jordy Rose20d4e682011-08-23 20:55:48 +00003011 SummaryLog[NewNode] = &Summ;
Jordy Rose5df640d2011-08-24 18:56:32 +00003012 }
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003013}
3014
Jordy Rosebf77e512011-08-23 20:27:16 +00003015
Ted Kremenek49b1e382012-01-26 21:29:00 +00003016ProgramStateRef
3017RetainCountChecker::updateSymbol(ProgramStateRef state, SymbolRef sym,
Jordy Rose75e680e2011-09-02 06:44:22 +00003018 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
3019 CheckerContext &C) const {
Jordy Rosebf77e512011-08-23 20:27:16 +00003020 // In GC mode [... release] and [... retain] do nothing.
Jordy Rose75e680e2011-09-02 06:44:22 +00003021 // In ARC mode they shouldn't exist at all, but we just ignore them.
Jordy Rosec49ec532011-09-02 05:55:19 +00003022 bool IgnoreRetainMsg = C.isObjCGCEnabled();
3023 if (!IgnoreRetainMsg)
David Blaikiebbafb8a2012-03-11 07:00:24 +00003024 IgnoreRetainMsg = (bool)C.getASTContext().getLangOpts().ObjCAutoRefCount;
Jordy Rosec49ec532011-09-02 05:55:19 +00003025
Jordy Rosebf77e512011-08-23 20:27:16 +00003026 switch (E) {
Jordan Roseeec15392012-07-02 19:27:43 +00003027 default:
3028 break;
3029 case IncRefMsg:
3030 E = IgnoreRetainMsg ? DoNothing : IncRef;
3031 break;
3032 case DecRefMsg:
3033 E = IgnoreRetainMsg ? DoNothing : DecRef;
3034 break;
Anna Zaks25612732012-08-29 23:23:43 +00003035 case DecRefMsgAndStopTrackingHard:
3036 E = IgnoreRetainMsg ? StopTracking : DecRefAndStopTrackingHard;
Jordan Roseeec15392012-07-02 19:27:43 +00003037 break;
3038 case MakeCollectable:
3039 E = C.isObjCGCEnabled() ? DecRef : DoNothing;
3040 break;
Jordy Rosebf77e512011-08-23 20:27:16 +00003041 }
3042
3043 // Handle all use-after-releases.
Jordy Rosec49ec532011-09-02 05:55:19 +00003044 if (!C.isObjCGCEnabled() && V.getKind() == RefVal::Released) {
Jordy Rosebf77e512011-08-23 20:27:16 +00003045 V = V ^ RefVal::ErrorUseAfterRelease;
3046 hasErr = V.getKind();
Anna Zaksf5788c72012-08-14 00:36:15 +00003047 return setRefBinding(state, sym, V);
Jordy Rosebf77e512011-08-23 20:27:16 +00003048 }
3049
3050 switch (E) {
3051 case DecRefMsg:
3052 case IncRefMsg:
3053 case MakeCollectable:
Anna Zaks25612732012-08-29 23:23:43 +00003054 case DecRefMsgAndStopTrackingHard:
Jordy Rosebf77e512011-08-23 20:27:16 +00003055 llvm_unreachable("DecRefMsg/IncRefMsg/MakeCollectable already converted");
Jordy Rosebf77e512011-08-23 20:27:16 +00003056
3057 case Dealloc:
3058 // Any use of -dealloc in GC is *bad*.
Jordy Rosec49ec532011-09-02 05:55:19 +00003059 if (C.isObjCGCEnabled()) {
Jordy Rosebf77e512011-08-23 20:27:16 +00003060 V = V ^ RefVal::ErrorDeallocGC;
3061 hasErr = V.getKind();
3062 break;
3063 }
3064
3065 switch (V.getKind()) {
3066 default:
3067 llvm_unreachable("Invalid RefVal state for an explicit dealloc.");
Jordy Rosebf77e512011-08-23 20:27:16 +00003068 case RefVal::Owned:
3069 // The object immediately transitions to the released state.
3070 V = V ^ RefVal::Released;
3071 V.clearCounts();
Anna Zaksf5788c72012-08-14 00:36:15 +00003072 return setRefBinding(state, sym, V);
Jordy Rosebf77e512011-08-23 20:27:16 +00003073 case RefVal::NotOwned:
3074 V = V ^ RefVal::ErrorDeallocNotOwned;
3075 hasErr = V.getKind();
3076 break;
3077 }
3078 break;
3079
Jordy Rosebf77e512011-08-23 20:27:16 +00003080 case MayEscape:
3081 if (V.getKind() == RefVal::Owned) {
3082 V = V ^ RefVal::NotOwned;
3083 break;
3084 }
3085
3086 // Fall-through.
3087
Jordy Rosebf77e512011-08-23 20:27:16 +00003088 case DoNothing:
3089 return state;
3090
3091 case Autorelease:
Jordy Rosec49ec532011-09-02 05:55:19 +00003092 if (C.isObjCGCEnabled())
Jordy Rosebf77e512011-08-23 20:27:16 +00003093 return state;
Jordy Rosebf77e512011-08-23 20:27:16 +00003094 // Update the autorelease counts.
Jordy Rosebf77e512011-08-23 20:27:16 +00003095 V = V.autorelease();
3096 break;
3097
3098 case StopTracking:
Anna Zaks25612732012-08-29 23:23:43 +00003099 case StopTrackingHard:
Anna Zaksf5788c72012-08-14 00:36:15 +00003100 return removeRefBinding(state, sym);
Jordy Rosebf77e512011-08-23 20:27:16 +00003101
3102 case IncRef:
3103 switch (V.getKind()) {
3104 default:
3105 llvm_unreachable("Invalid RefVal state for a retain.");
Jordy Rosebf77e512011-08-23 20:27:16 +00003106 case RefVal::Owned:
3107 case RefVal::NotOwned:
3108 V = V + 1;
3109 break;
3110 case RefVal::Released:
3111 // Non-GC cases are handled above.
Jordy Rosec49ec532011-09-02 05:55:19 +00003112 assert(C.isObjCGCEnabled());
Jordy Rosebf77e512011-08-23 20:27:16 +00003113 V = (V ^ RefVal::Owned) + 1;
3114 break;
3115 }
3116 break;
3117
Jordy Rosebf77e512011-08-23 20:27:16 +00003118 case DecRef:
Benjamin Kramer1d5d6342013-10-20 11:53:20 +00003119 case DecRefBridgedTransferred:
Anna Zaks25612732012-08-29 23:23:43 +00003120 case DecRefAndStopTrackingHard:
Jordy Rosebf77e512011-08-23 20:27:16 +00003121 switch (V.getKind()) {
3122 default:
3123 // case 'RefVal::Released' handled above.
3124 llvm_unreachable("Invalid RefVal state for a release.");
Jordy Rosebf77e512011-08-23 20:27:16 +00003125
3126 case RefVal::Owned:
3127 assert(V.getCount() > 0);
3128 if (V.getCount() == 1)
Benjamin Kramer1d5d6342013-10-20 11:53:20 +00003129 V = V ^ (E == DecRefBridgedTransferred ? RefVal::NotOwned
3130 : RefVal::Released);
Anna Zaks25612732012-08-29 23:23:43 +00003131 else if (E == DecRefAndStopTrackingHard)
Anna Zaksf5788c72012-08-14 00:36:15 +00003132 return removeRefBinding(state, sym);
Jordan Roseeec15392012-07-02 19:27:43 +00003133
Jordy Rosebf77e512011-08-23 20:27:16 +00003134 V = V - 1;
3135 break;
3136
3137 case RefVal::NotOwned:
Jordan Roseeec15392012-07-02 19:27:43 +00003138 if (V.getCount() > 0) {
Anna Zaks25612732012-08-29 23:23:43 +00003139 if (E == DecRefAndStopTrackingHard)
Anna Zaksf5788c72012-08-14 00:36:15 +00003140 return removeRefBinding(state, sym);
Jordy Rosebf77e512011-08-23 20:27:16 +00003141 V = V - 1;
Jordan Roseeec15392012-07-02 19:27:43 +00003142 } else {
Jordy Rosebf77e512011-08-23 20:27:16 +00003143 V = V ^ RefVal::ErrorReleaseNotOwned;
3144 hasErr = V.getKind();
3145 }
3146 break;
3147
3148 case RefVal::Released:
3149 // Non-GC cases are handled above.
Jordy Rosec49ec532011-09-02 05:55:19 +00003150 assert(C.isObjCGCEnabled());
Jordy Rosebf77e512011-08-23 20:27:16 +00003151 V = V ^ RefVal::ErrorUseAfterRelease;
3152 hasErr = V.getKind();
3153 break;
3154 }
3155 break;
3156 }
Anna Zaksf5788c72012-08-14 00:36:15 +00003157 return setRefBinding(state, sym, V);
Jordy Rosebf77e512011-08-23 20:27:16 +00003158}
3159
Ted Kremenek49b1e382012-01-26 21:29:00 +00003160void RetainCountChecker::processNonLeakError(ProgramStateRef St,
Jordy Rose75e680e2011-09-02 06:44:22 +00003161 SourceRange ErrorRange,
3162 RefVal::Kind ErrorKind,
3163 SymbolRef Sym,
3164 CheckerContext &C) const {
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003165 ExplodedNode *N = C.generateSink(St);
3166 if (!N)
3167 return;
3168
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003169 CFRefBug *BT;
3170 switch (ErrorKind) {
3171 default:
3172 llvm_unreachable("Unhandled error.");
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003173 case RefVal::ErrorUseAfterRelease:
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003174 if (!useAfterRelease)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00003175 useAfterRelease.reset(new UseAfterRelease(this));
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003176 BT = &*useAfterRelease;
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003177 break;
3178 case RefVal::ErrorReleaseNotOwned:
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003179 if (!releaseNotOwned)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00003180 releaseNotOwned.reset(new BadRelease(this));
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003181 BT = &*releaseNotOwned;
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003182 break;
3183 case RefVal::ErrorDeallocGC:
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003184 if (!deallocGC)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00003185 deallocGC.reset(new DeallocGC(this));
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003186 BT = &*deallocGC;
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003187 break;
3188 case RefVal::ErrorDeallocNotOwned:
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003189 if (!deallocNotOwned)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00003190 deallocNotOwned.reset(new DeallocNotOwned(this));
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003191 BT = &*deallocNotOwned;
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003192 break;
3193 }
3194
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003195 assert(BT);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003196 CFRefReport *report = new CFRefReport(*BT, C.getASTContext().getLangOpts(),
Jordy Rosec49ec532011-09-02 05:55:19 +00003197 C.isObjCGCEnabled(), SummaryLog,
3198 N, Sym);
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003199 report->addRange(ErrorRange);
Jordan Rosee10d5a72012-11-02 01:53:40 +00003200 C.emitReport(report);
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003201}
3202
Jordy Rose75e680e2011-09-02 06:44:22 +00003203//===----------------------------------------------------------------------===//
3204// Handle the return values of retain-count-related functions.
3205//===----------------------------------------------------------------------===//
3206
3207bool RetainCountChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
Jordy Rose898a1482011-08-21 21:58:18 +00003208 // Get the callee. We're only interested in simple C functions.
Ted Kremenek49b1e382012-01-26 21:29:00 +00003209 ProgramStateRef state = C.getState();
Anna Zaksc6aa5312011-12-01 05:57:37 +00003210 const FunctionDecl *FD = C.getCalleeDecl(CE);
Jordy Rose898a1482011-08-21 21:58:18 +00003211 if (!FD)
3212 return false;
3213
3214 IdentifierInfo *II = FD->getIdentifier();
3215 if (!II)
3216 return false;
3217
3218 // For now, we're only handling the functions that return aliases of their
3219 // arguments: CFRetain and CFMakeCollectable (and their families).
3220 // Eventually we should add other functions we can model entirely,
3221 // such as CFRelease, which don't invalidate their arguments or globals.
3222 if (CE->getNumArgs() != 1)
3223 return false;
3224
3225 // Get the name of the function.
3226 StringRef FName = II->getName();
3227 FName = FName.substr(FName.find_first_not_of('_'));
3228
3229 // See if it's one of the specific functions we know how to eval.
3230 bool canEval = false;
3231
Anna Zaksc6aa5312011-12-01 05:57:37 +00003232 QualType ResultTy = CE->getCallReturnType();
Jordy Rose898a1482011-08-21 21:58:18 +00003233 if (ResultTy->isObjCIdType()) {
3234 // Handle: id NSMakeCollectable(CFTypeRef)
3235 canEval = II->isStr("NSMakeCollectable");
3236 } else if (ResultTy->isPointerType()) {
3237 // Handle: (CF|CG)Retain
Jordan Rose77411322013-10-07 17:16:52 +00003238 // CFAutorelease
Jordy Rose898a1482011-08-21 21:58:18 +00003239 // CFMakeCollectable
3240 // It's okay to be a little sloppy here (CGMakeCollectable doesn't exist).
3241 if (cocoa::isRefType(ResultTy, "CF", FName) ||
3242 cocoa::isRefType(ResultTy, "CG", FName)) {
Jordan Rose77411322013-10-07 17:16:52 +00003243 canEval = isRetain(FD, FName) || isAutorelease(FD, FName) ||
3244 isMakeCollectable(FD, FName);
Jordy Rose898a1482011-08-21 21:58:18 +00003245 }
3246 }
3247
3248 if (!canEval)
3249 return false;
3250
3251 // Bind the return value.
Ted Kremenek632e3b72012-01-06 22:09:28 +00003252 const LocationContext *LCtx = C.getLocationContext();
3253 SVal RetVal = state->getSVal(CE->getArg(0), LCtx);
Jordy Rose898a1482011-08-21 21:58:18 +00003254 if (RetVal.isUnknown()) {
3255 // If the receiver is unknown, conjure a return value.
3256 SValBuilder &SVB = C.getSValBuilder();
Craig Topper0dbb7832014-05-27 02:45:47 +00003257 RetVal = SVB.conjureSymbolVal(nullptr, CE, LCtx, ResultTy, C.blockCount());
Jordy Rose898a1482011-08-21 21:58:18 +00003258 }
Ted Kremenek632e3b72012-01-06 22:09:28 +00003259 state = state->BindExpr(CE, LCtx, RetVal, false);
Jordy Rose898a1482011-08-21 21:58:18 +00003260
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003261 // FIXME: This should not be necessary, but otherwise the argument seems to be
3262 // considered alive during the next statement.
3263 if (const MemRegion *ArgRegion = RetVal.getAsRegion()) {
3264 // Save the refcount status of the argument.
3265 SymbolRef Sym = RetVal.getAsLocSymbol();
Craig Topper0dbb7832014-05-27 02:45:47 +00003266 const RefVal *Binding = nullptr;
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003267 if (Sym)
Anna Zaksf5788c72012-08-14 00:36:15 +00003268 Binding = getRefBinding(state, Sym);
Jordy Rose898a1482011-08-21 21:58:18 +00003269
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003270 // Invalidate the argument region.
Anna Zaksdc154152012-12-20 00:38:25 +00003271 state = state->invalidateRegions(ArgRegion, CE, C.blockCount(), LCtx,
Anna Zaks0c34c1a2013-01-16 01:35:54 +00003272 /*CausesPointerEscape*/ false);
Jordy Rose898a1482011-08-21 21:58:18 +00003273
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003274 // Restore the refcount status of the argument.
3275 if (Binding)
Anna Zaksf5788c72012-08-14 00:36:15 +00003276 state = setRefBinding(state, Sym, *Binding);
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003277 }
3278
Anna Zaksda4c8d62011-10-26 21:06:34 +00003279 C.addTransition(state);
Jordy Rose898a1482011-08-21 21:58:18 +00003280 return true;
3281}
3282
Jordy Rose75e680e2011-09-02 06:44:22 +00003283//===----------------------------------------------------------------------===//
3284// Handle return statements.
3285//===----------------------------------------------------------------------===//
Jordy Rose298cc4d2011-08-23 19:43:16 +00003286
Jordy Rose75e680e2011-09-02 06:44:22 +00003287void RetainCountChecker::checkPreStmt(const ReturnStmt *S,
3288 CheckerContext &C) const {
Ted Kremenekef31f372012-02-25 02:09:09 +00003289
3290 // Only adjust the reference count if this is the top-level call frame,
3291 // and not the result of inlining. In the future, we should do
3292 // better checking even for inlined calls, and see if they match
3293 // with their expected semantics (e.g., the method should return a retained
3294 // object, etc.).
Anna Zaks44dc91b2012-11-03 02:54:16 +00003295 if (!C.inTopFrame())
Ted Kremenekef31f372012-02-25 02:09:09 +00003296 return;
3297
Jordy Rose298cc4d2011-08-23 19:43:16 +00003298 const Expr *RetE = S->getRetValue();
3299 if (!RetE)
3300 return;
3301
Ted Kremenek49b1e382012-01-26 21:29:00 +00003302 ProgramStateRef state = C.getState();
Ted Kremenek632e3b72012-01-06 22:09:28 +00003303 SymbolRef Sym =
3304 state->getSValAsScalarOrLoc(RetE, C.getLocationContext()).getAsLocSymbol();
Jordy Rose298cc4d2011-08-23 19:43:16 +00003305 if (!Sym)
3306 return;
3307
3308 // Get the reference count binding (if any).
Anna Zaksf5788c72012-08-14 00:36:15 +00003309 const RefVal *T = getRefBinding(state, Sym);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003310 if (!T)
3311 return;
3312
3313 // Change the reference count.
3314 RefVal X = *T;
3315
3316 switch (X.getKind()) {
3317 case RefVal::Owned: {
3318 unsigned cnt = X.getCount();
3319 assert(cnt > 0);
3320 X.setCount(cnt - 1);
3321 X = X ^ RefVal::ReturnedOwned;
3322 break;
3323 }
3324
3325 case RefVal::NotOwned: {
3326 unsigned cnt = X.getCount();
3327 if (cnt) {
3328 X.setCount(cnt - 1);
3329 X = X ^ RefVal::ReturnedOwned;
3330 }
3331 else {
3332 X = X ^ RefVal::ReturnedNotOwned;
3333 }
3334 break;
3335 }
3336
3337 default:
3338 return;
3339 }
3340
3341 // Update the binding.
Anna Zaksf5788c72012-08-14 00:36:15 +00003342 state = setRefBinding(state, Sym, X);
Anna Zaksda4c8d62011-10-26 21:06:34 +00003343 ExplodedNode *Pred = C.addTransition(state);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003344
3345 // At this point we have updated the state properly.
3346 // Everything after this is merely checking to see if the return value has
3347 // been over- or under-retained.
3348
3349 // Did we cache out?
3350 if (!Pred)
3351 return;
3352
Jordy Rose298cc4d2011-08-23 19:43:16 +00003353 // Update the autorelease counts.
Anton Yartsev6a619222014-02-17 18:25:34 +00003354 static CheckerProgramPointTag AutoreleaseTag(this, "Autorelease");
Jordan Roseff03c1d2012-12-06 18:58:18 +00003355 state = handleAutoreleaseCounts(state, Pred, &AutoreleaseTag, C, Sym, X);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003356
3357 // Did we cache out?
Jordan Roseff03c1d2012-12-06 18:58:18 +00003358 if (!state)
Jordy Rose298cc4d2011-08-23 19:43:16 +00003359 return;
3360
3361 // Get the updated binding.
Anna Zaksf5788c72012-08-14 00:36:15 +00003362 T = getRefBinding(state, Sym);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003363 assert(T);
3364 X = *T;
3365
3366 // Consult the summary of the enclosing method.
Jordy Rosec49ec532011-09-02 05:55:19 +00003367 RetainSummaryManager &Summaries = getSummaryManager(C);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003368 const Decl *CD = &Pred->getCodeDecl();
Jordan Roseeec15392012-07-02 19:27:43 +00003369 RetEffect RE = RetEffect::MakeNoRet();
Jordy Rose298cc4d2011-08-23 19:43:16 +00003370
Jordan Roseeec15392012-07-02 19:27:43 +00003371 // FIXME: What is the convention for blocks? Is there one?
Jordy Rose298cc4d2011-08-23 19:43:16 +00003372 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CD)) {
Jordy Rose8b289a22011-08-25 00:10:37 +00003373 const RetainSummary *Summ = Summaries.getMethodSummary(MD);
Jordan Roseeec15392012-07-02 19:27:43 +00003374 RE = Summ->getRetEffect();
3375 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) {
3376 if (!isa<CXXMethodDecl>(FD)) {
3377 const RetainSummary *Summ = Summaries.getFunctionSummary(FD);
3378 RE = Summ->getRetEffect();
3379 }
Jordy Rose298cc4d2011-08-23 19:43:16 +00003380 }
3381
Jordan Roseeec15392012-07-02 19:27:43 +00003382 checkReturnWithRetEffect(S, C, Pred, RE, X, Sym, state);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003383}
3384
Jordy Rose75e680e2011-09-02 06:44:22 +00003385void RetainCountChecker::checkReturnWithRetEffect(const ReturnStmt *S,
3386 CheckerContext &C,
3387 ExplodedNode *Pred,
3388 RetEffect RE, RefVal X,
3389 SymbolRef Sym,
Ted Kremenek49b1e382012-01-26 21:29:00 +00003390 ProgramStateRef state) const {
Jordy Rose298cc4d2011-08-23 19:43:16 +00003391 // Any leaks or other errors?
3392 if (X.isReturnedOwned() && X.getCount() == 0) {
3393 if (RE.getKind() != RetEffect::NoRet) {
3394 bool hasError = false;
Jordy Rosec49ec532011-09-02 05:55:19 +00003395 if (C.isObjCGCEnabled() && RE.getObjKind() == RetEffect::ObjC) {
Jordy Rose298cc4d2011-08-23 19:43:16 +00003396 // Things are more complicated with garbage collection. If the
3397 // returned object is suppose to be an Objective-C object, we have
3398 // a leak (as the caller expects a GC'ed object) because no
3399 // method should return ownership unless it returns a CF object.
3400 hasError = true;
3401 X = X ^ RefVal::ErrorGCLeakReturned;
3402 }
3403 else if (!RE.isOwned()) {
3404 // Either we are using GC and the returned object is a CF type
3405 // or we aren't using GC. In either case, we expect that the
3406 // enclosing method is expected to return ownership.
3407 hasError = true;
3408 X = X ^ RefVal::ErrorLeakReturned;
3409 }
3410
3411 if (hasError) {
3412 // Generate an error node.
Anna Zaksf5788c72012-08-14 00:36:15 +00003413 state = setRefBinding(state, Sym, X);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003414
Anton Yartsev6a619222014-02-17 18:25:34 +00003415 static CheckerProgramPointTag ReturnOwnLeakTag(this, "ReturnsOwnLeak");
Anna Zaksda4c8d62011-10-26 21:06:34 +00003416 ExplodedNode *N = C.addTransition(state, Pred, &ReturnOwnLeakTag);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003417 if (N) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003418 const LangOptions &LOpts = C.getASTContext().getLangOpts();
Jordy Rosec49ec532011-09-02 05:55:19 +00003419 bool GCEnabled = C.isObjCGCEnabled();
Jordy Rose298cc4d2011-08-23 19:43:16 +00003420 CFRefReport *report =
Jordy Rosec49ec532011-09-02 05:55:19 +00003421 new CFRefLeakReport(*getLeakAtReturnBug(LOpts, GCEnabled),
3422 LOpts, GCEnabled, SummaryLog,
Ted Kremenek8671acb2013-04-16 21:44:22 +00003423 N, Sym, C, IncludeAllocationLine);
3424
Jordan Rosee10d5a72012-11-02 01:53:40 +00003425 C.emitReport(report);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003426 }
3427 }
3428 }
3429 } else if (X.isReturnedNotOwned()) {
3430 if (RE.isOwned()) {
3431 // Trying to return a not owned object to a caller expecting an
3432 // owned object.
Anna Zaksf5788c72012-08-14 00:36:15 +00003433 state = setRefBinding(state, Sym, X ^ RefVal::ErrorReturnedNotOwned);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003434
Anton Yartsev6a619222014-02-17 18:25:34 +00003435 static CheckerProgramPointTag ReturnNotOwnedTag(this,
3436 "ReturnNotOwnedForOwned");
Anna Zaksda4c8d62011-10-26 21:06:34 +00003437 ExplodedNode *N = C.addTransition(state, Pred, &ReturnNotOwnedTag);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003438 if (N) {
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003439 if (!returnNotOwnedForOwned)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00003440 returnNotOwnedForOwned.reset(new ReturnedNotOwnedForOwned(this));
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003441
Jordy Rose298cc4d2011-08-23 19:43:16 +00003442 CFRefReport *report =
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003443 new CFRefReport(*returnNotOwnedForOwned,
David Blaikiebbafb8a2012-03-11 07:00:24 +00003444 C.getASTContext().getLangOpts(),
Jordy Rosec49ec532011-09-02 05:55:19 +00003445 C.isObjCGCEnabled(), SummaryLog, N, Sym);
Jordan Rosee10d5a72012-11-02 01:53:40 +00003446 C.emitReport(report);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003447 }
3448 }
3449 }
3450}
3451
Jordy Rose6763e382011-08-23 20:07:14 +00003452//===----------------------------------------------------------------------===//
Jordy Rose75e680e2011-09-02 06:44:22 +00003453// Check various ways a symbol can be invalidated.
3454//===----------------------------------------------------------------------===//
3455
Anna Zaks3e0f4152011-10-06 00:43:15 +00003456void RetainCountChecker::checkBind(SVal loc, SVal val, const Stmt *S,
Jordy Rose75e680e2011-09-02 06:44:22 +00003457 CheckerContext &C) const {
3458 // Are we storing to something that causes the value to "escape"?
3459 bool escapes = true;
3460
3461 // A value escapes in three possible cases (this may change):
3462 //
3463 // (1) we are binding to something that is not a memory region.
3464 // (2) we are binding to a memregion that does not have stack storage
3465 // (3) we are binding to a memregion with stack storage that the store
3466 // does not understand.
Ted Kremenek49b1e382012-01-26 21:29:00 +00003467 ProgramStateRef state = C.getState();
Jordy Rose75e680e2011-09-02 06:44:22 +00003468
David Blaikie05785d12013-02-20 22:23:23 +00003469 if (Optional<loc::MemRegionVal> regionLoc = loc.getAs<loc::MemRegionVal>()) {
Jordy Rose75e680e2011-09-02 06:44:22 +00003470 escapes = !regionLoc->getRegion()->hasStackStorage();
3471
3472 if (!escapes) {
3473 // To test (3), generate a new state with the binding added. If it is
3474 // the same state, then it escapes (since the store cannot represent
3475 // the binding).
Anna Zaks70de7722012-05-02 00:15:40 +00003476 // Do this only if we know that the store is not supposed to generate the
3477 // same state.
3478 SVal StoredVal = state->getSVal(regionLoc->getRegion());
3479 if (StoredVal != val)
3480 escapes = (state == (state->bindLoc(*regionLoc, val)));
Jordy Rose75e680e2011-09-02 06:44:22 +00003481 }
Ted Kremeneke9a5bcf2012-03-27 01:12:45 +00003482 if (!escapes) {
3483 // Case 4: We do not currently model what happens when a symbol is
3484 // assigned to a struct field, so be conservative here and let the symbol
3485 // go. TODO: This could definitely be improved upon.
3486 escapes = !isa<VarRegion>(regionLoc->getRegion());
3487 }
Jordy Rose75e680e2011-09-02 06:44:22 +00003488 }
3489
Anna Zaksfb050942013-09-17 00:53:28 +00003490 // If we are storing the value into an auto function scope variable annotated
3491 // with (__attribute__((cleanup))), stop tracking the value to avoid leak
3492 // false positives.
3493 if (const VarRegion *LVR = dyn_cast_or_null<VarRegion>(loc.getAsRegion())) {
3494 const VarDecl *VD = LVR->getDecl();
Aaron Ballman9ead1242013-12-19 02:39:40 +00003495 if (VD->hasAttr<CleanupAttr>()) {
Anna Zaksfb050942013-09-17 00:53:28 +00003496 escapes = true;
3497 }
3498 }
3499
Jordy Rose75e680e2011-09-02 06:44:22 +00003500 // If our store can represent the binding and we aren't storing to something
3501 // that doesn't have local storage then just return and have the simulation
3502 // state continue as is.
3503 if (!escapes)
3504 return;
3505
3506 // Otherwise, find all symbols referenced by 'val' that we are tracking
3507 // and stop tracking them.
3508 state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
Anna Zaksda4c8d62011-10-26 21:06:34 +00003509 C.addTransition(state);
Jordy Rose75e680e2011-09-02 06:44:22 +00003510}
3511
Ted Kremenek49b1e382012-01-26 21:29:00 +00003512ProgramStateRef RetainCountChecker::evalAssume(ProgramStateRef state,
Jordy Rose75e680e2011-09-02 06:44:22 +00003513 SVal Cond,
3514 bool Assumption) const {
3515
3516 // FIXME: We may add to the interface of evalAssume the list of symbols
3517 // whose assumptions have changed. For now we just iterate through the
3518 // bindings and check if any of the tracked symbols are NULL. This isn't
3519 // too bad since the number of symbols we will track in practice are
3520 // probably small and evalAssume is only called at branches and a few
3521 // other places.
Jordan Rose0c153cb2012-11-02 01:54:06 +00003522 RefBindingsTy B = state->get<RefBindings>();
Jordy Rose75e680e2011-09-02 06:44:22 +00003523
3524 if (B.isEmpty())
3525 return state;
3526
3527 bool changed = false;
Jordan Rose0c153cb2012-11-02 01:54:06 +00003528 RefBindingsTy::Factory &RefBFactory = state->get_context<RefBindings>();
Jordy Rose75e680e2011-09-02 06:44:22 +00003529
Jordan Rose0c153cb2012-11-02 01:54:06 +00003530 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Ted Kremenek244e1d72012-09-07 22:31:01 +00003531 // Check if the symbol is null stop tracking the symbol.
Jordan Rose14fe9f32012-11-01 00:18:27 +00003532 ConstraintManager &CMgr = state->getConstraintManager();
3533 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
3534 if (AllocFailed.isConstrainedTrue()) {
Jordy Rose75e680e2011-09-02 06:44:22 +00003535 changed = true;
3536 B = RefBFactory.remove(B, I.getKey());
3537 }
3538 }
3539
3540 if (changed)
3541 state = state->set<RefBindings>(B);
3542
3543 return state;
3544}
3545
Ted Kremenek49b1e382012-01-26 21:29:00 +00003546ProgramStateRef
3547RetainCountChecker::checkRegionChanges(ProgramStateRef state,
Anna Zaksdc154152012-12-20 00:38:25 +00003548 const InvalidatedSymbols *invalidated,
Jordy Rose75e680e2011-09-02 06:44:22 +00003549 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks3d348342012-02-14 21:55:24 +00003550 ArrayRef<const MemRegion *> Regions,
Jordan Rose742920c2012-07-02 19:27:35 +00003551 const CallEvent *Call) const {
Jordy Rose75e680e2011-09-02 06:44:22 +00003552 if (!invalidated)
3553 return state;
3554
3555 llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
3556 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
3557 E = ExplicitRegions.end(); I != E; ++I) {
3558 if (const SymbolicRegion *SR = (*I)->StripCasts()->getAs<SymbolicRegion>())
3559 WhitelistedSymbols.insert(SR->getSymbol());
3560 }
3561
Anna Zaksdc154152012-12-20 00:38:25 +00003562 for (InvalidatedSymbols::const_iterator I=invalidated->begin(),
Jordy Rose75e680e2011-09-02 06:44:22 +00003563 E = invalidated->end(); I!=E; ++I) {
3564 SymbolRef sym = *I;
3565 if (WhitelistedSymbols.count(sym))
3566 continue;
3567 // Remove any existing reference-count binding.
Anna Zaksf5788c72012-08-14 00:36:15 +00003568 state = removeRefBinding(state, sym);
Jordy Rose75e680e2011-09-02 06:44:22 +00003569 }
3570 return state;
3571}
3572
3573//===----------------------------------------------------------------------===//
Jordy Rose6763e382011-08-23 20:07:14 +00003574// Handle dead symbols and end-of-path.
3575//===----------------------------------------------------------------------===//
3576
Jordan Roseff03c1d2012-12-06 18:58:18 +00003577ProgramStateRef
3578RetainCountChecker::handleAutoreleaseCounts(ProgramStateRef state,
Anna Zaks58734db2011-10-25 19:57:11 +00003579 ExplodedNode *Pred,
Jordan Rose9f61f8a2012-08-18 00:30:16 +00003580 const ProgramPointTag *Tag,
Anna Zaks58734db2011-10-25 19:57:11 +00003581 CheckerContext &Ctx,
Jordy Rose75e680e2011-09-02 06:44:22 +00003582 SymbolRef Sym, RefVal V) const {
Jordy Rose6763e382011-08-23 20:07:14 +00003583 unsigned ACnt = V.getAutoreleaseCount();
3584
3585 // No autorelease counts? Nothing to be done.
3586 if (!ACnt)
Jordan Roseff03c1d2012-12-06 18:58:18 +00003587 return state;
Jordy Rose6763e382011-08-23 20:07:14 +00003588
Anna Zaks58734db2011-10-25 19:57:11 +00003589 assert(!Ctx.isObjCGCEnabled() && "Autorelease counts in GC mode?");
Jordy Rose6763e382011-08-23 20:07:14 +00003590 unsigned Cnt = V.getCount();
3591
3592 // FIXME: Handle sending 'autorelease' to already released object.
3593
3594 if (V.getKind() == RefVal::ReturnedOwned)
3595 ++Cnt;
3596
3597 if (ACnt <= Cnt) {
3598 if (ACnt == Cnt) {
3599 V.clearCounts();
3600 if (V.getKind() == RefVal::ReturnedOwned)
3601 V = V ^ RefVal::ReturnedNotOwned;
3602 else
3603 V = V ^ RefVal::NotOwned;
3604 } else {
Anna Zaksa8bcc652013-01-31 22:36:17 +00003605 V.setCount(V.getCount() - ACnt);
Jordy Rose6763e382011-08-23 20:07:14 +00003606 V.setAutoreleaseCount(0);
3607 }
Jordan Roseff03c1d2012-12-06 18:58:18 +00003608 return setRefBinding(state, Sym, V);
Jordy Rose6763e382011-08-23 20:07:14 +00003609 }
3610
3611 // Woah! More autorelease counts then retain counts left.
3612 // Emit hard error.
3613 V = V ^ RefVal::ErrorOverAutorelease;
Anna Zaksf5788c72012-08-14 00:36:15 +00003614 state = setRefBinding(state, Sym, V);
Jordy Rose6763e382011-08-23 20:07:14 +00003615
Jordan Rose4b4613c2012-08-20 18:43:42 +00003616 ExplodedNode *N = Ctx.generateSink(state, Pred, Tag);
Jordan Rose9f61f8a2012-08-18 00:30:16 +00003617 if (N) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003618 SmallString<128> sbuf;
Jordy Rose6763e382011-08-23 20:07:14 +00003619 llvm::raw_svector_ostream os(sbuf);
Jordan Rose7467f062013-04-23 01:42:25 +00003620 os << "Object was autoreleased ";
Jordy Rose6763e382011-08-23 20:07:14 +00003621 if (V.getAutoreleaseCount() > 1)
Jordan Rose7467f062013-04-23 01:42:25 +00003622 os << V.getAutoreleaseCount() << " times but the object ";
3623 else
3624 os << "but ";
3625 os << "has a +" << V.getCount() << " retain count";
Jordy Rose6763e382011-08-23 20:07:14 +00003626
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003627 if (!overAutorelease)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00003628 overAutorelease.reset(new OverAutorelease(this));
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003629
David Blaikiebbafb8a2012-03-11 07:00:24 +00003630 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
Jordy Rose6763e382011-08-23 20:07:14 +00003631 CFRefReport *report =
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003632 new CFRefReport(*overAutorelease, LOpts, /* GCEnabled = */ false,
3633 SummaryLog, N, Sym, os.str());
Jordan Rosee10d5a72012-11-02 01:53:40 +00003634 Ctx.emitReport(report);
Jordy Rose6763e382011-08-23 20:07:14 +00003635 }
3636
Craig Topper0dbb7832014-05-27 02:45:47 +00003637 return nullptr;
Jordy Rose6763e382011-08-23 20:07:14 +00003638}
Jordy Rose78612762011-08-23 19:01:07 +00003639
Ted Kremenek49b1e382012-01-26 21:29:00 +00003640ProgramStateRef
3641RetainCountChecker::handleSymbolDeath(ProgramStateRef state,
Jordy Rose75e680e2011-09-02 06:44:22 +00003642 SymbolRef sid, RefVal V,
Jordy Rose78612762011-08-23 19:01:07 +00003643 SmallVectorImpl<SymbolRef> &Leaked) const {
Jordy Rose03a8f9e2011-08-24 04:48:19 +00003644 bool hasLeak = false;
Jordy Rose78612762011-08-23 19:01:07 +00003645 if (V.isOwned())
3646 hasLeak = true;
3647 else if (V.isNotOwned() || V.isReturnedOwned())
3648 hasLeak = (V.getCount() > 0);
3649
3650 if (!hasLeak)
Anna Zaksf5788c72012-08-14 00:36:15 +00003651 return removeRefBinding(state, sid);
Jordy Rose78612762011-08-23 19:01:07 +00003652
3653 Leaked.push_back(sid);
Anna Zaksf5788c72012-08-14 00:36:15 +00003654 return setRefBinding(state, sid, V ^ RefVal::ErrorLeak);
Jordy Rose78612762011-08-23 19:01:07 +00003655}
3656
3657ExplodedNode *
Ted Kremenek49b1e382012-01-26 21:29:00 +00003658RetainCountChecker::processLeaks(ProgramStateRef state,
Jordy Rose75e680e2011-09-02 06:44:22 +00003659 SmallVectorImpl<SymbolRef> &Leaked,
Anna Zaks58734db2011-10-25 19:57:11 +00003660 CheckerContext &Ctx,
3661 ExplodedNode *Pred) const {
Jordy Rose78612762011-08-23 19:01:07 +00003662 // Generate an intermediate node representing the leak point.
Jordan Rose9f61f8a2012-08-18 00:30:16 +00003663 ExplodedNode *N = Ctx.addTransition(state, Pred);
Jordy Rose78612762011-08-23 19:01:07 +00003664
3665 if (N) {
3666 for (SmallVectorImpl<SymbolRef>::iterator
3667 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3668
David Blaikiebbafb8a2012-03-11 07:00:24 +00003669 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
Anna Zaks58734db2011-10-25 19:57:11 +00003670 bool GCEnabled = Ctx.isObjCGCEnabled();
Jordy Rosec49ec532011-09-02 05:55:19 +00003671 CFRefBug *BT = Pred ? getLeakWithinFunctionBug(LOpts, GCEnabled)
3672 : getLeakAtReturnBug(LOpts, GCEnabled);
Jordy Rose78612762011-08-23 19:01:07 +00003673 assert(BT && "BugType not initialized.");
Jordy Rose184bd142011-08-24 22:39:09 +00003674
Jordy Rosec49ec532011-09-02 05:55:19 +00003675 CFRefLeakReport *report = new CFRefLeakReport(*BT, LOpts, GCEnabled,
Ted Kremenek8671acb2013-04-16 21:44:22 +00003676 SummaryLog, N, *I, Ctx,
3677 IncludeAllocationLine);
Jordan Rosee10d5a72012-11-02 01:53:40 +00003678 Ctx.emitReport(report);
Jordy Rose78612762011-08-23 19:01:07 +00003679 }
3680 }
3681
3682 return N;
3683}
3684
Anna Zaks3fdcc0b2013-01-03 00:25:29 +00003685void RetainCountChecker::checkEndFunction(CheckerContext &Ctx) const {
Ted Kremenek49b1e382012-01-26 21:29:00 +00003686 ProgramStateRef state = Ctx.getState();
Jordan Rose0c153cb2012-11-02 01:54:06 +00003687 RefBindingsTy B = state->get<RefBindings>();
Anna Zaks3eae3342011-10-25 19:56:48 +00003688 ExplodedNode *Pred = Ctx.getPredecessor();
Jordy Rose78612762011-08-23 19:01:07 +00003689
Jordan Rose7699e4a2013-08-01 22:16:36 +00003690 // Don't process anything within synthesized bodies.
3691 const LocationContext *LCtx = Pred->getLocationContext();
3692 if (LCtx->getAnalysisDeclContext()->isBodyAutosynthesized()) {
3693 assert(LCtx->getParent());
3694 return;
3695 }
3696
Jordan Rose0c153cb2012-11-02 01:54:06 +00003697 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Craig Topper0dbb7832014-05-27 02:45:47 +00003698 state = handleAutoreleaseCounts(state, Pred, /*Tag=*/nullptr, Ctx,
Jordan Roseff03c1d2012-12-06 18:58:18 +00003699 I->first, I->second);
Jordy Rose6763e382011-08-23 20:07:14 +00003700 if (!state)
Jordy Rose78612762011-08-23 19:01:07 +00003701 return;
3702 }
3703
Ted Kremeneka2bbac32012-02-07 00:24:33 +00003704 // If the current LocationContext has a parent, don't check for leaks.
3705 // We will do that later.
Anna Zaksf5788c72012-08-14 00:36:15 +00003706 // FIXME: we should instead check for imbalances of the retain/releases,
Ted Kremeneka2bbac32012-02-07 00:24:33 +00003707 // and suggest annotations.
Jordan Rose7699e4a2013-08-01 22:16:36 +00003708 if (LCtx->getParent())
Ted Kremeneka2bbac32012-02-07 00:24:33 +00003709 return;
3710
Jordy Rose78612762011-08-23 19:01:07 +00003711 B = state->get<RefBindings>();
3712 SmallVector<SymbolRef, 10> Leaked;
3713
Jordan Rose0c153cb2012-11-02 01:54:06 +00003714 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I)
Jordy Rose6763e382011-08-23 20:07:14 +00003715 state = handleSymbolDeath(state, I->first, I->second, Leaked);
Jordy Rose78612762011-08-23 19:01:07 +00003716
Jordan Rose9f61f8a2012-08-18 00:30:16 +00003717 processLeaks(state, Leaked, Ctx, Pred);
Jordy Rose78612762011-08-23 19:01:07 +00003718}
3719
3720const ProgramPointTag *
Jordy Rose75e680e2011-09-02 06:44:22 +00003721RetainCountChecker::getDeadSymbolTag(SymbolRef sym) const {
Anton Yartsev6a619222014-02-17 18:25:34 +00003722 const CheckerProgramPointTag *&tag = DeadSymbolTags[sym];
Jordy Rose78612762011-08-23 19:01:07 +00003723 if (!tag) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003724 SmallString<64> buf;
Jordy Rose78612762011-08-23 19:01:07 +00003725 llvm::raw_svector_ostream out(buf);
Anton Yartsev6a619222014-02-17 18:25:34 +00003726 out << "Dead Symbol : ";
Anna Zaks22351652011-12-05 18:58:11 +00003727 sym->dumpToStream(out);
Anton Yartsev6a619222014-02-17 18:25:34 +00003728 tag = new CheckerProgramPointTag(this, out.str());
Jordy Rose78612762011-08-23 19:01:07 +00003729 }
3730 return tag;
3731}
3732
Jordy Rose75e680e2011-09-02 06:44:22 +00003733void RetainCountChecker::checkDeadSymbols(SymbolReaper &SymReaper,
3734 CheckerContext &C) const {
Jordy Rose78612762011-08-23 19:01:07 +00003735 ExplodedNode *Pred = C.getPredecessor();
3736
Ted Kremenek49b1e382012-01-26 21:29:00 +00003737 ProgramStateRef state = C.getState();
Jordan Rose0c153cb2012-11-02 01:54:06 +00003738 RefBindingsTy B = state->get<RefBindings>();
Jordan Roseff03c1d2012-12-06 18:58:18 +00003739 SmallVector<SymbolRef, 10> Leaked;
Jordy Rose78612762011-08-23 19:01:07 +00003740
3741 // Update counts from autorelease pools
3742 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3743 E = SymReaper.dead_end(); I != E; ++I) {
3744 SymbolRef Sym = *I;
3745 if (const RefVal *T = B.lookup(Sym)){
3746 // Use the symbol as the tag.
3747 // FIXME: This might not be as unique as we would like.
Jordan Rose9f61f8a2012-08-18 00:30:16 +00003748 const ProgramPointTag *Tag = getDeadSymbolTag(Sym);
Jordan Roseff03c1d2012-12-06 18:58:18 +00003749 state = handleAutoreleaseCounts(state, Pred, Tag, C, Sym, *T);
Jordy Rose6763e382011-08-23 20:07:14 +00003750 if (!state)
Jordy Rose78612762011-08-23 19:01:07 +00003751 return;
Jordan Roseff03c1d2012-12-06 18:58:18 +00003752
3753 // Fetch the new reference count from the state, and use it to handle
3754 // this symbol.
3755 state = handleSymbolDeath(state, *I, *getRefBinding(state, Sym), Leaked);
Jordy Rose78612762011-08-23 19:01:07 +00003756 }
3757 }
3758
Jordan Roseff03c1d2012-12-06 18:58:18 +00003759 if (Leaked.empty()) {
3760 C.addTransition(state);
3761 return;
Jordy Rose78612762011-08-23 19:01:07 +00003762 }
3763
Jordan Rose9f61f8a2012-08-18 00:30:16 +00003764 Pred = processLeaks(state, Leaked, C, Pred);
Jordy Rose78612762011-08-23 19:01:07 +00003765
3766 // Did we cache out?
3767 if (!Pred)
3768 return;
3769
3770 // Now generate a new node that nukes the old bindings.
Jordan Roseff03c1d2012-12-06 18:58:18 +00003771 // The only bindings left at this point are the leaked symbols.
Jordan Rose0c153cb2012-11-02 01:54:06 +00003772 RefBindingsTy::Factory &F = state->get_context<RefBindings>();
Jordan Roseff03c1d2012-12-06 18:58:18 +00003773 B = state->get<RefBindings>();
Jordy Rose78612762011-08-23 19:01:07 +00003774
Jordan Roseff03c1d2012-12-06 18:58:18 +00003775 for (SmallVectorImpl<SymbolRef>::iterator I = Leaked.begin(),
3776 E = Leaked.end();
3777 I != E; ++I)
Jordy Rose78612762011-08-23 19:01:07 +00003778 B = F.remove(B, *I);
3779
3780 state = state->set<RefBindings>(B);
Anna Zaksda4c8d62011-10-26 21:06:34 +00003781 C.addTransition(state, Pred);
Jordy Rose78612762011-08-23 19:01:07 +00003782}
3783
Ted Kremenek49b1e382012-01-26 21:29:00 +00003784void RetainCountChecker::printState(raw_ostream &Out, ProgramStateRef State,
Jordy Rose75e680e2011-09-02 06:44:22 +00003785 const char *NL, const char *Sep) const {
Jordy Rose58a20d32011-08-28 19:11:56 +00003786
Jordan Rose0c153cb2012-11-02 01:54:06 +00003787 RefBindingsTy B = State->get<RefBindings>();
Jordy Rose58a20d32011-08-28 19:11:56 +00003788
Ted Kremenekdb70b522013-03-28 18:43:18 +00003789 if (B.isEmpty())
3790 return;
3791
3792 Out << Sep << NL;
Jordy Rose58a20d32011-08-28 19:11:56 +00003793
Jordan Rose0c153cb2012-11-02 01:54:06 +00003794 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Jordy Rose58a20d32011-08-28 19:11:56 +00003795 Out << I->first << " : ";
3796 I->second.print(Out);
3797 Out << NL;
3798 }
Jordy Rose58a20d32011-08-28 19:11:56 +00003799}
3800
3801//===----------------------------------------------------------------------===//
Jordy Rose75e680e2011-09-02 06:44:22 +00003802// Checker registration.
Ted Kremenek819e9b62008-03-11 06:39:11 +00003803//===----------------------------------------------------------------------===//
3804
Jordy Rosec49ec532011-09-02 05:55:19 +00003805void ento::registerRetainCountChecker(CheckerManager &Mgr) {
Ted Kremenek8671acb2013-04-16 21:44:22 +00003806 Mgr.registerChecker<RetainCountChecker>(Mgr.getAnalyzerOptions());
Jordy Rosec49ec532011-09-02 05:55:19 +00003807}
3808
Ted Kremenek71c080f2013-08-14 23:41:49 +00003809//===----------------------------------------------------------------------===//
3810// Implementation of the CallEffects API.
3811//===----------------------------------------------------------------------===//
3812
3813namespace clang { namespace ento { namespace objc_retain {
3814
3815// This is a bit gross, but it allows us to populate CallEffects without
3816// creating a bunch of accessors. This kind is very localized, so the
3817// damage of this macro is limited.
3818#define createCallEffect(D, KIND)\
3819 ASTContext &Ctx = D->getASTContext();\
3820 LangOptions L = Ctx.getLangOpts();\
3821 RetainSummaryManager M(Ctx, L.GCOnly, L.ObjCAutoRefCount);\
3822 const RetainSummary *S = M.get ## KIND ## Summary(D);\
3823 CallEffects CE(S->getRetEffect());\
3824 CE.Receiver = S->getReceiverEffect();\
Ted Kremeneke19529b2013-08-16 23:14:22 +00003825 unsigned N = D->param_size();\
Ted Kremenek71c080f2013-08-14 23:41:49 +00003826 for (unsigned i = 0; i < N; ++i) {\
3827 CE.Args.push_back(S->getArg(i));\
3828 }
3829
3830CallEffects CallEffects::getEffect(const ObjCMethodDecl *MD) {
3831 createCallEffect(MD, Method);
3832 return CE;
3833}
3834
3835CallEffects CallEffects::getEffect(const FunctionDecl *FD) {
3836 createCallEffect(FD, Function);
3837 return CE;
3838}
3839
3840#undef createCallEffect
3841
3842}}}