blob: 9ac993160a258b197e15125e70a9c6c34c65b258 [file] [log] [blame]
Jordy Rose910c4052011-09-02 06:44:22 +00001//==-- RetainCountChecker.cpp - Checks for leaks and other issues -*- C++ -*--//
Ted Kremenek2fff37e2008-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 Rose910c4052011-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 Kremenek2fff37e2008-03-06 00:08:09 +000012//
13//===----------------------------------------------------------------------===//
14
Jordy Rose910c4052011-09-02 06:44:22 +000015#include "ClangSACheckers.h"
Stephen Hines651f13c2014-04-23 16:59:28 -070016#include "AllocationDiagnostics.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000017#include "clang/AST/Attr.h"
Ted Kremenekb2771592011-03-30 17:41:19 +000018#include "clang/AST/DeclCXX.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000019#include "clang/AST/DeclObjC.h"
20#include "clang/AST/ParentMap.h"
21#include "clang/Analysis/DomainSpecific/CocoaConventions.h"
Ted Kremenek0b526b42010-02-18 00:05:58 +000022#include "clang/Basic/LangOptions.h"
23#include "clang/Basic/SourceManager.h"
Stephen Hines651f13c2014-04-23 16:59:28 -070024#include "clang/StaticAnalyzer/Checkers/ObjCRetainCount.h"
Ted Kremenek9b663712011-02-10 01:03:03 +000025#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
26#include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000027#include "clang/StaticAnalyzer/Core/Checker.h"
28#include "clang/StaticAnalyzer/Core/CheckerManager.h"
Jordan Rosef540c542012-07-26 21:39:41 +000029#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
Jordy Rose910c4052011-09-02 06:44:22 +000030#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
Ted Kremenek18c66fd2011-08-15 22:09:50 +000031#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
Ted Kremenek9b663712011-02-10 01:03:03 +000032#include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000033#include "llvm/ADT/DenseMap.h"
34#include "llvm/ADT/FoldingSet.h"
Ted Kremenek6d348932008-10-21 15:53:15 +000035#include "llvm/ADT/ImmutableList.h"
Ted Kremenek0b526b42010-02-18 00:05:58 +000036#include "llvm/ADT/ImmutableMap.h"
Ted Kremenek6ed9afc2008-05-16 18:33:44 +000037#include "llvm/ADT/STLExtras.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000038#include "llvm/ADT/SmallString.h"
Ted Kremenek0b526b42010-02-18 00:05:58 +000039#include "llvm/ADT/StringExtras.h"
Chris Lattner5f9e2722011-07-23 10:55:15 +000040#include <cstdarg>
Ted Kremenek2fff37e2008-03-06 00:08:09 +000041
42using namespace clang;
Ted Kremenek9ef65372010-12-23 07:20:52 +000043using namespace ento;
Ted Kremenek5774e392013-08-14 23:41:46 +000044using namespace objc_retain;
Ted Kremeneka64e89b2010-01-27 06:13:48 +000045using llvm::StrInStrNoCase;
Ted Kremenek4c79e552008-11-05 16:54:44 +000046
Ted Kremenek05cbe1a2008-04-09 23:49:11 +000047//===----------------------------------------------------------------------===//
Ted Kremenek5774e392013-08-14 23:41:46 +000048// Adapters for FoldingSet.
Ted Kremenek05cbe1a2008-04-09 23:49:11 +000049//===----------------------------------------------------------------------===//
50
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000051namespace llvm {
Ted Kremenekb77449c2009-05-03 05:20:50 +000052template <> struct FoldingSetTrait<ArgEffect> {
Ted Kremenek5774e392013-08-14 23:41:46 +000053static inline void Profile(const ArgEffect X, FoldingSetNodeID &ID) {
Ted Kremenekb77449c2009-05-03 05:20:50 +000054 ID.AddInteger((unsigned) X);
55}
Ted Kremenek553cf182008-06-25 21:21:56 +000056};
Ted Kremenek5774e392013-08-14 23:41:46 +000057template <> struct FoldingSetTrait<RetEffect> {
58 static inline void Profile(const RetEffect &X, FoldingSetNodeID &ID) {
59 ID.AddInteger((unsigned) X.getKind());
60 ID.AddInteger((unsigned) X.getObjKind());
61}
62};
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000063} // end llvm namespace
64
Ted Kremenek5774e392013-08-14 23:41:46 +000065//===----------------------------------------------------------------------===//
66// Reference-counting logic (typestate + counts).
67//===----------------------------------------------------------------------===//
68
Ted Kremenekb77449c2009-05-03 05:20:50 +000069/// ArgEffects summarizes the effects of a function/method call on all of
70/// its arguments.
71typedef llvm::ImmutableMap<unsigned,ArgEffect> ArgEffects;
72
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000073namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +000074class RefVal {
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +000075public:
76 enum Kind {
77 Owned = 0, // Owning reference.
78 NotOwned, // Reference is not owned by still valid (not freed).
79 Released, // Object has been released.
80 ReturnedOwned, // Returned object passes ownership to caller.
81 ReturnedNotOwned, // Return object does not pass ownership to caller.
82 ERROR_START,
83 ErrorDeallocNotOwned, // -dealloc called on non-owned object.
84 ErrorDeallocGC, // Calling -dealloc with GC enabled.
85 ErrorUseAfterRelease, // Object used after released.
86 ErrorReleaseNotOwned, // Release of an object that was not owned.
87 ERROR_LEAK_START,
88 ErrorLeak, // A memory leak due to excessive reference counts.
89 ErrorLeakReturned, // A memory leak due to the returning method not having
90 // the correct naming conventions.
91 ErrorGCLeakReturned,
92 ErrorOverAutorelease,
93 ErrorReturnedNotOwned
94 };
Ted Kremenekdcee3ce2010-07-01 20:16:50 +000095
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +000096private:
Stephen Hines651f13c2014-04-23 16:59:28 -070097 /// The number of outstanding retains.
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +000098 unsigned Cnt;
Stephen Hines651f13c2014-04-23 16:59:28 -070099 /// The number of outstanding autoreleases.
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000100 unsigned ACnt;
Stephen Hines651f13c2014-04-23 16:59:28 -0700101 /// The (static) type of the object at the time we started tracking it.
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000102 QualType T;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000103
Stephen Hines651f13c2014-04-23 16:59:28 -0700104 /// The current state of the object.
105 ///
106 /// See the RefVal::Kind enum for possible values.
107 unsigned RawKind : 5;
108
109 /// The kind of object being tracked (CF or ObjC), if known.
110 ///
111 /// See the RetEffect::ObjKind enum for possible values.
112 unsigned RawObjectKind : 2;
113
114 /// True if the current state and/or retain count may turn out to not be the
115 /// best possible approximation of the reference counting state.
116 ///
117 /// If true, the checker may decide to throw away ("override") this state
118 /// in favor of something else when it sees the object being used in new ways.
119 ///
120 /// This setting should not be propagated to state derived from this state.
121 /// Once we start deriving new states, it would be inconsistent to override
122 /// them.
123 unsigned IsOverridable : 1;
124
125 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, unsigned acnt, QualType t,
126 bool Overridable = false)
127 : Cnt(cnt), ACnt(acnt), T(t), RawKind(static_cast<unsigned>(k)),
128 RawObjectKind(static_cast<unsigned>(o)), IsOverridable(Overridable) {
129 assert(getKind() == k && "not enough bits for the kind");
130 assert(getObjKind() == o && "not enough bits for the object kind");
131 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000132
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000133public:
Stephen Hines651f13c2014-04-23 16:59:28 -0700134 Kind getKind() const { return static_cast<Kind>(RawKind); }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000135
Stephen Hines651f13c2014-04-23 16:59:28 -0700136 RetEffect::ObjKind getObjKind() const {
137 return static_cast<RetEffect::ObjKind>(RawObjectKind);
138 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000139
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000140 unsigned getCount() const { return Cnt; }
141 unsigned getAutoreleaseCount() const { return ACnt; }
142 unsigned getCombinedCounts() const { return Cnt + ACnt; }
Stephen Hines651f13c2014-04-23 16:59:28 -0700143 void clearCounts() {
144 Cnt = 0;
145 ACnt = 0;
146 IsOverridable = false;
147 }
148 void setCount(unsigned i) {
149 Cnt = i;
150 IsOverridable = false;
151 }
152 void setAutoreleaseCount(unsigned i) {
153 ACnt = i;
154 IsOverridable = false;
155 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000156
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000157 QualType getType() const { return T; }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000158
Stephen Hines651f13c2014-04-23 16:59:28 -0700159 bool isOverridable() const { return IsOverridable; }
160
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000161 bool isOwned() const {
162 return getKind() == Owned;
163 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000164
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000165 bool isNotOwned() const {
166 return getKind() == NotOwned;
167 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000168
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000169 bool isReturnedOwned() const {
170 return getKind() == ReturnedOwned;
171 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000172
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000173 bool isReturnedNotOwned() const {
174 return getKind() == ReturnedNotOwned;
175 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000176
Stephen Hines651f13c2014-04-23 16:59:28 -0700177 /// Create a state for an object whose lifetime is the responsibility of the
178 /// current function, at least partially.
179 ///
180 /// Most commonly, this is an owned object with a retain count of +1.
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000181 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
182 unsigned Count = 1) {
183 return RefVal(Owned, o, Count, 0, t);
184 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000185
Stephen Hines651f13c2014-04-23 16:59:28 -0700186 /// Create a state for an object whose lifetime is not the responsibility of
187 /// the current function.
188 ///
189 /// Most commonly, this is an unowned object with a retain count of +0.
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000190 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
191 unsigned Count = 0) {
192 return RefVal(NotOwned, o, Count, 0, t);
193 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000194
Stephen Hines651f13c2014-04-23 16:59:28 -0700195 /// Create an "overridable" state for an unowned object at +0.
196 ///
197 /// An overridable state is one that provides a good approximation of the
198 /// reference counting state now, but which may be discarded later if the
199 /// checker sees the object being used in new ways.
200 static RefVal makeOverridableNotOwned(RetEffect::ObjKind o, QualType t) {
201 return RefVal(NotOwned, o, 0, 0, t, /*Overridable=*/true);
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000202 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000203
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000204 RefVal operator-(size_t i) const {
205 return RefVal(getKind(), getObjKind(), getCount() - i,
206 getAutoreleaseCount(), getType());
207 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000208
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000209 RefVal operator+(size_t i) const {
210 return RefVal(getKind(), getObjKind(), getCount() + i,
211 getAutoreleaseCount(), getType());
212 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000213
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000214 RefVal operator^(Kind k) const {
215 return RefVal(k, getObjKind(), getCount(), getAutoreleaseCount(),
216 getType());
217 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000218
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000219 RefVal autorelease() const {
220 return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount()+1,
221 getType());
222 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000223
Stephen Hines651f13c2014-04-23 16:59:28 -0700224 // Comparison, profiling, and pretty-printing.
225
226 bool hasSameState(const RefVal &X) const {
227 return getKind() == X.getKind() && Cnt == X.Cnt && ACnt == X.ACnt;
228 }
229
230 bool operator==(const RefVal& X) const {
231 return T == X.T && hasSameState(X) && getObjKind() == X.getObjKind() &&
232 IsOverridable == X.IsOverridable;
233 }
234
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000235 void Profile(llvm::FoldingSetNodeID& ID) const {
Stephen Hines651f13c2014-04-23 16:59:28 -0700236 ID.Add(T);
237 ID.AddInteger(RawKind);
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000238 ID.AddInteger(Cnt);
239 ID.AddInteger(ACnt);
Stephen Hines651f13c2014-04-23 16:59:28 -0700240 ID.AddInteger(RawObjectKind);
241 ID.AddBoolean(IsOverridable);
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000242 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000243
Ted Kremenek9c378f72011-08-12 23:37:29 +0000244 void print(raw_ostream &Out) const;
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000245};
246
Ted Kremenek9c378f72011-08-12 23:37:29 +0000247void RefVal::print(raw_ostream &Out) const {
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000248 if (!T.isNull())
Jordy Rosedbd658e2011-08-28 19:11:56 +0000249 Out << "Tracked " << T.getAsString() << '/';
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000250
Stephen Hines651f13c2014-04-23 16:59:28 -0700251 if (isOverridable())
252 Out << "(overridable) ";
253
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000254 switch (getKind()) {
Jordy Rose910c4052011-09-02 06:44:22 +0000255 default: llvm_unreachable("Invalid RefVal kind");
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000256 case Owned: {
257 Out << "Owned";
258 unsigned cnt = getCount();
259 if (cnt) Out << " (+ " << cnt << ")";
260 break;
261 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000262
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000263 case NotOwned: {
264 Out << "NotOwned";
265 unsigned cnt = getCount();
266 if (cnt) Out << " (+ " << cnt << ")";
267 break;
268 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000269
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000270 case ReturnedOwned: {
271 Out << "ReturnedOwned";
272 unsigned cnt = getCount();
273 if (cnt) Out << " (+ " << cnt << ")";
274 break;
275 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000276
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000277 case ReturnedNotOwned: {
278 Out << "ReturnedNotOwned";
279 unsigned cnt = getCount();
280 if (cnt) Out << " (+ " << cnt << ")";
281 break;
282 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000283
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000284 case Released:
285 Out << "Released";
286 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000287
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000288 case ErrorDeallocGC:
289 Out << "-dealloc (GC)";
290 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000291
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000292 case ErrorDeallocNotOwned:
293 Out << "-dealloc (not-owned)";
294 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000295
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000296 case ErrorLeak:
297 Out << "Leaked";
298 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000299
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000300 case ErrorLeakReturned:
301 Out << "Leaked (Bad naming)";
302 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000303
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000304 case ErrorGCLeakReturned:
305 Out << "Leaked (GC-ed at return)";
306 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000307
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000308 case ErrorUseAfterRelease:
309 Out << "Use-After-Release [ERROR]";
310 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000311
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000312 case ErrorReleaseNotOwned:
313 Out << "Release of Not-Owned [ERROR]";
314 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000315
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000316 case RefVal::ErrorOverAutorelease:
Jordan Rose2545b1d2013-04-23 01:42:25 +0000317 Out << "Over-autoreleased";
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000318 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000319
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000320 case RefVal::ErrorReturnedNotOwned:
321 Out << "Non-owned object returned instead of owned";
322 break;
323 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000324
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000325 if (ACnt) {
326 Out << " [ARC +" << ACnt << ']';
327 }
328}
329} //end anonymous namespace
330
331//===----------------------------------------------------------------------===//
332// RefBindings - State used to track object reference counts.
333//===----------------------------------------------------------------------===//
334
Jordan Rose166d5022012-11-02 01:54:06 +0000335REGISTER_MAP_WITH_PROGRAMSTATE(RefBindings, SymbolRef, RefVal)
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000336
Anna Zaks8d6b43c2012-08-14 00:36:15 +0000337static inline const RefVal *getRefBinding(ProgramStateRef State,
338 SymbolRef Sym) {
339 return State->get<RefBindings>(Sym);
340}
341
342static inline ProgramStateRef setRefBinding(ProgramStateRef State,
343 SymbolRef Sym, RefVal Val) {
344 return State->set<RefBindings>(Sym, Val);
345}
346
347static ProgramStateRef removeRefBinding(ProgramStateRef State, SymbolRef Sym) {
348 return State->remove<RefBindings>(Sym);
349}
350
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000351//===----------------------------------------------------------------------===//
Jordy Rose910c4052011-09-02 06:44:22 +0000352// Function/Method behavior summaries.
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000353//===----------------------------------------------------------------------===//
354
355namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000356class RetainSummary {
Jordy Roseef945882012-03-18 01:26:10 +0000357 /// Args - a map of (index, ArgEffect) pairs, where index
Ted Kremenek1bffd742008-05-06 15:44:25 +0000358 /// specifies the argument (starting from 0). This can be sparsely
359 /// populated; arguments with no entry in Args use 'DefaultArgEffect'.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000360 ArgEffects Args;
Mike Stump1eb44332009-09-09 15:08:12 +0000361
Ted Kremenek1bffd742008-05-06 15:44:25 +0000362 /// DefaultArgEffect - The default ArgEffect to apply to arguments that
363 /// do not have an entry in Args.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000364 ArgEffect DefaultArgEffect;
Mike Stump1eb44332009-09-09 15:08:12 +0000365
Ted Kremenek553cf182008-06-25 21:21:56 +0000366 /// Receiver - If this summary applies to an Objective-C message expression,
367 /// this is the effect applied to the state of the receiver.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000368 ArgEffect Receiver;
Mike Stump1eb44332009-09-09 15:08:12 +0000369
Ted Kremenek553cf182008-06-25 21:21:56 +0000370 /// Ret - The effect on the return value. Used to indicate if the
Jordy Rose76c506f2011-08-21 21:58:18 +0000371 /// function/method call returns a new tracked symbol.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000372 RetEffect Ret;
Mike Stump1eb44332009-09-09 15:08:12 +0000373
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000374public:
Ted Kremenekb77449c2009-05-03 05:20:50 +0000375 RetainSummary(ArgEffects A, RetEffect R, ArgEffect defaultEff,
Jordy Rosee62e87b2011-08-20 20:55:40 +0000376 ArgEffect ReceiverEff)
377 : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000378
Ted Kremenek553cf182008-06-25 21:21:56 +0000379 /// getArg - Return the argument effect on the argument specified by
380 /// idx (starting from 0).
Ted Kremenek1ac08d62008-03-11 17:48:22 +0000381 ArgEffect getArg(unsigned idx) const {
Ted Kremenekb77449c2009-05-03 05:20:50 +0000382 if (const ArgEffect *AE = Args.lookup(idx))
383 return *AE;
Mike Stump1eb44332009-09-09 15:08:12 +0000384
Ted Kremenek1bffd742008-05-06 15:44:25 +0000385 return DefaultArgEffect;
Ted Kremenek1ac08d62008-03-11 17:48:22 +0000386 }
Ted Kremenek53c7ea12013-08-14 23:41:49 +0000387
Ted Kremenek11fe1752011-01-27 18:43:03 +0000388 void addArg(ArgEffects::Factory &af, unsigned idx, ArgEffect e) {
389 Args = af.add(Args, idx, e);
390 }
Mike Stump1eb44332009-09-09 15:08:12 +0000391
Ted Kremenek885c27b2009-05-04 05:31:22 +0000392 /// setDefaultArgEffect - Set the default argument effect.
393 void setDefaultArgEffect(ArgEffect E) {
394 DefaultArgEffect = E;
395 }
Mike Stump1eb44332009-09-09 15:08:12 +0000396
Ted Kremenek553cf182008-06-25 21:21:56 +0000397 /// getRetEffect - Returns the effect on the return value of the call.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000398 RetEffect getRetEffect() const { return Ret; }
Mike Stump1eb44332009-09-09 15:08:12 +0000399
Ted Kremenek885c27b2009-05-04 05:31:22 +0000400 /// setRetEffect - Set the effect of the return value of the call.
401 void setRetEffect(RetEffect E) { Ret = E; }
Mike Stump1eb44332009-09-09 15:08:12 +0000402
Ted Kremenek12b94342011-01-27 06:54:14 +0000403
404 /// Sets the effect on the receiver of the message.
405 void setReceiverEffect(ArgEffect e) { Receiver = e; }
406
Ted Kremenek553cf182008-06-25 21:21:56 +0000407 /// getReceiverEffect - Returns the effect on the receiver of the call.
408 /// This is only meaningful if the summary applies to an ObjCMessageExpr*.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000409 ArgEffect getReceiverEffect() const { return Receiver; }
Jordy Rose4df54fe2011-08-23 04:27:15 +0000410
411 /// Test if two retain summaries are identical. Note that merely equivalent
412 /// summaries are not necessarily identical (for example, if an explicit
413 /// argument effect matches the default effect).
414 bool operator==(const RetainSummary &Other) const {
415 return Args == Other.Args && DefaultArgEffect == Other.DefaultArgEffect &&
416 Receiver == Other.Receiver && Ret == Other.Ret;
417 }
Jordy Roseef945882012-03-18 01:26:10 +0000418
419 /// Profile this summary for inclusion in a FoldingSet.
420 void Profile(llvm::FoldingSetNodeID& ID) const {
421 ID.Add(Args);
422 ID.Add(DefaultArgEffect);
423 ID.Add(Receiver);
424 ID.Add(Ret);
425 }
426
427 /// A retain summary is simple if it has no ArgEffects other than the default.
428 bool isSimple() const {
429 return Args.isEmpty();
430 }
Jordan Rose4531b7d2012-07-02 19:27:43 +0000431
432private:
433 ArgEffects getArgEffects() const { return Args; }
434 ArgEffect getDefaultArgEffect() const { return DefaultArgEffect; }
435
436 friend class RetainSummaryManager;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000437};
Ted Kremenek4f22a782008-06-23 23:30:29 +0000438} // end anonymous namespace
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000439
Ted Kremenek553cf182008-06-25 21:21:56 +0000440//===----------------------------------------------------------------------===//
441// Data structures for constructing summaries.
442//===----------------------------------------------------------------------===//
Ted Kremenek53301ba2008-06-24 03:49:48 +0000443
Ted Kremenek553cf182008-06-25 21:21:56 +0000444namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000445class ObjCSummaryKey {
Ted Kremenek553cf182008-06-25 21:21:56 +0000446 IdentifierInfo* II;
447 Selector S;
Mike Stump1eb44332009-09-09 15:08:12 +0000448public:
Ted Kremenek553cf182008-06-25 21:21:56 +0000449 ObjCSummaryKey(IdentifierInfo* ii, Selector s)
450 : II(ii), S(s) {}
451
Ted Kremenek9c378f72011-08-12 23:37:29 +0000452 ObjCSummaryKey(const ObjCInterfaceDecl *d, Selector s)
Ted Kremenek553cf182008-06-25 21:21:56 +0000453 : II(d ? d->getIdentifier() : 0), S(s) {}
Ted Kremenek70b6a832009-05-13 18:16:01 +0000454
Ted Kremenek553cf182008-06-25 21:21:56 +0000455 ObjCSummaryKey(Selector s)
456 : II(0), S(s) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000457
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000458 IdentifierInfo *getIdentifier() const { return II; }
Ted Kremenek553cf182008-06-25 21:21:56 +0000459 Selector getSelector() const { return S; }
460};
Ted Kremenek4f22a782008-06-23 23:30:29 +0000461}
462
463namespace llvm {
Ted Kremenek553cf182008-06-25 21:21:56 +0000464template <> struct DenseMapInfo<ObjCSummaryKey> {
465 static inline ObjCSummaryKey getEmptyKey() {
466 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
467 DenseMapInfo<Selector>::getEmptyKey());
468 }
Mike Stump1eb44332009-09-09 15:08:12 +0000469
Ted Kremenek553cf182008-06-25 21:21:56 +0000470 static inline ObjCSummaryKey getTombstoneKey() {
471 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
Mike Stump1eb44332009-09-09 15:08:12 +0000472 DenseMapInfo<Selector>::getTombstoneKey());
Ted Kremenek553cf182008-06-25 21:21:56 +0000473 }
Mike Stump1eb44332009-09-09 15:08:12 +0000474
Ted Kremenek553cf182008-06-25 21:21:56 +0000475 static unsigned getHashValue(const ObjCSummaryKey &V) {
Benjamin Kramer28b23072012-05-27 13:28:44 +0000476 typedef std::pair<IdentifierInfo*, Selector> PairTy;
477 return DenseMapInfo<PairTy>::getHashValue(PairTy(V.getIdentifier(),
478 V.getSelector()));
Ted Kremenek553cf182008-06-25 21:21:56 +0000479 }
Mike Stump1eb44332009-09-09 15:08:12 +0000480
Ted Kremenek553cf182008-06-25 21:21:56 +0000481 static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
Benjamin Kramer28b23072012-05-27 13:28:44 +0000482 return LHS.getIdentifier() == RHS.getIdentifier() &&
483 LHS.getSelector() == RHS.getSelector();
Ted Kremenek553cf182008-06-25 21:21:56 +0000484 }
Mike Stump1eb44332009-09-09 15:08:12 +0000485
Ted Kremenek553cf182008-06-25 21:21:56 +0000486};
Ted Kremenek4f22a782008-06-23 23:30:29 +0000487} // end llvm namespace
Mike Stump1eb44332009-09-09 15:08:12 +0000488
Ted Kremenek4f22a782008-06-23 23:30:29 +0000489namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000490class ObjCSummaryCache {
Ted Kremenek93edbc52011-10-05 23:54:29 +0000491 typedef llvm::DenseMap<ObjCSummaryKey, const RetainSummary *> MapTy;
Ted Kremenek553cf182008-06-25 21:21:56 +0000492 MapTy M;
493public:
494 ObjCSummaryCache() {}
Mike Stump1eb44332009-09-09 15:08:12 +0000495
Ted Kremenek93edbc52011-10-05 23:54:29 +0000496 const RetainSummary * find(const ObjCInterfaceDecl *D, Selector S) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000497 // Do a lookup with the (D,S) pair. If we find a match return
498 // the iterator.
499 ObjCSummaryKey K(D, S);
500 MapTy::iterator I = M.find(K);
Mike Stump1eb44332009-09-09 15:08:12 +0000501
Jordan Rose4531b7d2012-07-02 19:27:43 +0000502 if (I != M.end())
Ted Kremenek614cc542009-07-21 23:27:57 +0000503 return I->second;
Jordan Rose4531b7d2012-07-02 19:27:43 +0000504 if (!D)
505 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +0000506
Ted Kremenek553cf182008-06-25 21:21:56 +0000507 // Walk the super chain. If we find a hit with a parent, we'll end
508 // up returning that summary. We actually allow that key (null,S), as
509 // we cache summaries for the null ObjCInterfaceDecl* to allow us to
510 // generate initial summaries without having to worry about NSObject
511 // being declared.
512 // FIXME: We may change this at some point.
Ted Kremenek9c378f72011-08-12 23:37:29 +0000513 for (ObjCInterfaceDecl *C=D->getSuperClass() ;; C=C->getSuperClass()) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000514 if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
515 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000516
Ted Kremenek553cf182008-06-25 21:21:56 +0000517 if (!C)
Ted Kremenek614cc542009-07-21 23:27:57 +0000518 return NULL;
Ted Kremenek553cf182008-06-25 21:21:56 +0000519 }
Mike Stump1eb44332009-09-09 15:08:12 +0000520
521 // Cache the summary with original key to make the next lookup faster
Ted Kremenek553cf182008-06-25 21:21:56 +0000522 // and return the iterator.
Ted Kremenek93edbc52011-10-05 23:54:29 +0000523 const RetainSummary *Summ = I->second;
Ted Kremenek614cc542009-07-21 23:27:57 +0000524 M[K] = Summ;
525 return Summ;
Ted Kremenek553cf182008-06-25 21:21:56 +0000526 }
Mike Stump1eb44332009-09-09 15:08:12 +0000527
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000528 const RetainSummary *find(IdentifierInfo* II, Selector S) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000529 // FIXME: Class method lookup. Right now we dont' have a good way
530 // of going between IdentifierInfo* and the class hierarchy.
Ted Kremenek614cc542009-07-21 23:27:57 +0000531 MapTy::iterator I = M.find(ObjCSummaryKey(II, S));
Mike Stump1eb44332009-09-09 15:08:12 +0000532
Ted Kremenek614cc542009-07-21 23:27:57 +0000533 if (I == M.end())
534 I = M.find(ObjCSummaryKey(S));
Mike Stump1eb44332009-09-09 15:08:12 +0000535
Ted Kremenek614cc542009-07-21 23:27:57 +0000536 return I == M.end() ? NULL : I->second;
Ted Kremenek553cf182008-06-25 21:21:56 +0000537 }
Mike Stump1eb44332009-09-09 15:08:12 +0000538
Ted Kremenek93edbc52011-10-05 23:54:29 +0000539 const RetainSummary *& operator[](ObjCSummaryKey K) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000540 return M[K];
541 }
Mike Stump1eb44332009-09-09 15:08:12 +0000542
Ted Kremenek93edbc52011-10-05 23:54:29 +0000543 const RetainSummary *& operator[](Selector S) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000544 return M[ ObjCSummaryKey(S) ];
545 }
Mike Stump1eb44332009-09-09 15:08:12 +0000546};
Ted Kremenek553cf182008-06-25 21:21:56 +0000547} // end anonymous namespace
548
549//===----------------------------------------------------------------------===//
550// Data structures for managing collections of summaries.
551//===----------------------------------------------------------------------===//
552
553namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000554class RetainSummaryManager {
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000555
556 //==-----------------------------------------------------------------==//
557 // Typedefs.
558 //==-----------------------------------------------------------------==//
Mike Stump1eb44332009-09-09 15:08:12 +0000559
Ted Kremenek93edbc52011-10-05 23:54:29 +0000560 typedef llvm::DenseMap<const FunctionDecl*, const RetainSummary *>
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000561 FuncSummariesTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000562
Ted Kremenek4f22a782008-06-23 23:30:29 +0000563 typedef ObjCSummaryCache ObjCMethodSummariesTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000564
Jordy Roseef945882012-03-18 01:26:10 +0000565 typedef llvm::FoldingSetNodeWrapper<RetainSummary> CachedSummaryNode;
566
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000567 //==-----------------------------------------------------------------==//
568 // Data.
569 //==-----------------------------------------------------------------==//
Mike Stump1eb44332009-09-09 15:08:12 +0000570
Ted Kremenek553cf182008-06-25 21:21:56 +0000571 /// Ctx - The ASTContext object for the analyzed ASTs.
Ted Kremenek9c378f72011-08-12 23:37:29 +0000572 ASTContext &Ctx;
Ted Kremenek179064e2008-07-01 17:21:27 +0000573
Ted Kremenek553cf182008-06-25 21:21:56 +0000574 /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
Ted Kremenek377e2302008-04-29 05:33:51 +0000575 const bool GCEnabled;
Mike Stump1eb44332009-09-09 15:08:12 +0000576
John McCallf85e1932011-06-15 23:02:42 +0000577 /// Records whether or not the analyzed code runs in ARC mode.
578 const bool ARCEnabled;
579
Ted Kremenek553cf182008-06-25 21:21:56 +0000580 /// FuncSummaries - A map from FunctionDecls to summaries.
Mike Stump1eb44332009-09-09 15:08:12 +0000581 FuncSummariesTy FuncSummaries;
582
Ted Kremenek553cf182008-06-25 21:21:56 +0000583 /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
584 /// to summaries.
Ted Kremenek1f180c32008-06-23 22:21:20 +0000585 ObjCMethodSummariesTy ObjCClassMethodSummaries;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000586
Ted Kremenek553cf182008-06-25 21:21:56 +0000587 /// ObjCMethodSummaries - A map from selectors to summaries.
Ted Kremenek1f180c32008-06-23 22:21:20 +0000588 ObjCMethodSummariesTy ObjCMethodSummaries;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000589
Ted Kremenek553cf182008-06-25 21:21:56 +0000590 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
591 /// and all other data used by the checker.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000592 llvm::BumpPtrAllocator BPAlloc;
Mike Stump1eb44332009-09-09 15:08:12 +0000593
Ted Kremenekb77449c2009-05-03 05:20:50 +0000594 /// AF - A factory for ArgEffects objects.
Mike Stump1eb44332009-09-09 15:08:12 +0000595 ArgEffects::Factory AF;
596
Ted Kremenek553cf182008-06-25 21:21:56 +0000597 /// ScratchArgs - A holding buffer for construct ArgEffects.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000598 ArgEffects ScratchArgs;
Mike Stump1eb44332009-09-09 15:08:12 +0000599
Ted Kremenekec315332009-05-07 23:40:42 +0000600 /// ObjCAllocRetE - Default return effect for methods returning Objective-C
601 /// objects.
602 RetEffect ObjCAllocRetE;
Ted Kremenek547d4952009-06-05 23:18:01 +0000603
Mike Stump1eb44332009-09-09 15:08:12 +0000604 /// ObjCInitRetE - Default return effect for init methods returning
Ted Kremenekac02f202009-08-20 05:13:36 +0000605 /// Objective-C objects.
Ted Kremenek547d4952009-06-05 23:18:01 +0000606 RetEffect ObjCInitRetE;
Mike Stump1eb44332009-09-09 15:08:12 +0000607
Jordy Roseef945882012-03-18 01:26:10 +0000608 /// SimpleSummaries - Used for uniquing summaries that don't have special
609 /// effects.
610 llvm::FoldingSet<CachedSummaryNode> SimpleSummaries;
Mike Stump1eb44332009-09-09 15:08:12 +0000611
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000612 //==-----------------------------------------------------------------==//
613 // Methods.
614 //==-----------------------------------------------------------------==//
Mike Stump1eb44332009-09-09 15:08:12 +0000615
Ted Kremenek553cf182008-06-25 21:21:56 +0000616 /// getArgEffects - Returns a persistent ArgEffects object based on the
617 /// data in ScratchArgs.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000618 ArgEffects getArgEffects();
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000619
Jordan Rose391165f2013-10-07 17:16:52 +0000620 enum UnaryFuncKind { cfretain, cfrelease, cfautorelease, cfmakecollectable };
Ted Kremenek93edbc52011-10-05 23:54:29 +0000621
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000622 const RetainSummary *getUnarySummary(const FunctionType* FT,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000623 UnaryFuncKind func);
Mike Stump1eb44332009-09-09 15:08:12 +0000624
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000625 const RetainSummary *getCFSummaryCreateRule(const FunctionDecl *FD);
626 const RetainSummary *getCFSummaryGetRule(const FunctionDecl *FD);
627 const RetainSummary *getCFCreateGetRuleSummary(const FunctionDecl *FD);
Mike Stump1eb44332009-09-09 15:08:12 +0000628
Jordy Roseef945882012-03-18 01:26:10 +0000629 const RetainSummary *getPersistentSummary(const RetainSummary &OldSumm);
Ted Kremenek706522f2008-10-29 04:07:07 +0000630
Jordy Roseef945882012-03-18 01:26:10 +0000631 const RetainSummary *getPersistentSummary(RetEffect RetEff,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000632 ArgEffect ReceiverEff = DoNothing,
633 ArgEffect DefaultEff = MayEscape) {
Jordy Roseef945882012-03-18 01:26:10 +0000634 RetainSummary Summ(getArgEffects(), RetEff, DefaultEff, ReceiverEff);
635 return getPersistentSummary(Summ);
636 }
637
Ted Kremenekc91fdf62012-05-08 00:12:09 +0000638 const RetainSummary *getDoNothingSummary() {
639 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
640 }
641
Jordy Roseef945882012-03-18 01:26:10 +0000642 const RetainSummary *getDefaultSummary() {
643 return getPersistentSummary(RetEffect::MakeNoRet(),
644 DoNothing, MayEscape);
Ted Kremenek9c32d082008-05-06 00:30:21 +0000645 }
Mike Stump1eb44332009-09-09 15:08:12 +0000646
Ted Kremenek93edbc52011-10-05 23:54:29 +0000647 const RetainSummary *getPersistentStopSummary() {
Jordy Roseef945882012-03-18 01:26:10 +0000648 return getPersistentSummary(RetEffect::MakeNoRet(),
649 StopTracking, StopTracking);
Mike Stump1eb44332009-09-09 15:08:12 +0000650 }
Ted Kremenekb3095252008-05-06 04:20:12 +0000651
Ted Kremenek1f180c32008-06-23 22:21:20 +0000652 void InitializeClassMethodSummaries();
653 void InitializeMethodSummaries();
Ted Kremenek896cd9d2008-10-23 01:56:15 +0000654private:
Ted Kremenek93edbc52011-10-05 23:54:29 +0000655 void addNSObjectClsMethSummary(Selector S, const RetainSummary *Summ) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000656 ObjCClassMethodSummaries[S] = Summ;
657 }
Mike Stump1eb44332009-09-09 15:08:12 +0000658
Ted Kremenek93edbc52011-10-05 23:54:29 +0000659 void addNSObjectMethSummary(Selector S, const RetainSummary *Summ) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000660 ObjCMethodSummaries[S] = Summ;
661 }
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +0000662
Ted Kremeneka9797122012-02-18 21:37:48 +0000663 void addClassMethSummary(const char* Cls, const char* name,
664 const RetainSummary *Summ, bool isNullary = true) {
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +0000665 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
Ted Kremeneka9797122012-02-18 21:37:48 +0000666 Selector S = isNullary ? GetNullarySelector(name, Ctx)
667 : GetUnarySelector(name, Ctx);
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +0000668 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
669 }
Mike Stump1eb44332009-09-09 15:08:12 +0000670
Ted Kremenek6c4becb2009-02-25 02:54:57 +0000671 void addInstMethSummary(const char* Cls, const char* nullaryName,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000672 const RetainSummary *Summ) {
Ted Kremenek6c4becb2009-02-25 02:54:57 +0000673 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
674 Selector S = GetNullarySelector(nullaryName, Ctx);
675 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
676 }
Mike Stump1eb44332009-09-09 15:08:12 +0000677
Ted Kremenekde4d5332009-04-24 17:50:11 +0000678 Selector generateSelector(va_list argp) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000679 SmallVector<IdentifierInfo*, 10> II;
Ted Kremenekde4d5332009-04-24 17:50:11 +0000680
Ted Kremenek9e476de2008-08-12 18:30:56 +0000681 while (const char* s = va_arg(argp, const char*))
682 II.push_back(&Ctx.Idents.get(s));
Ted Kremenekde4d5332009-04-24 17:50:11 +0000683
Mike Stump1eb44332009-09-09 15:08:12 +0000684 return Ctx.Selectors.getSelector(II.size(), &II[0]);
Ted Kremenekde4d5332009-04-24 17:50:11 +0000685 }
Mike Stump1eb44332009-09-09 15:08:12 +0000686
Ted Kremenekde4d5332009-04-24 17:50:11 +0000687 void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy& Summaries,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000688 const RetainSummary * Summ, va_list argp) {
Ted Kremenekde4d5332009-04-24 17:50:11 +0000689 Selector S = generateSelector(argp);
690 Summaries[ObjCSummaryKey(ClsII, S)] = Summ;
Ted Kremenek70a733e2008-07-18 17:24:20 +0000691 }
Mike Stump1eb44332009-09-09 15:08:12 +0000692
Ted Kremenek93edbc52011-10-05 23:54:29 +0000693 void addInstMethSummary(const char* Cls, const RetainSummary * Summ, ...) {
Ted Kremenekaf9dc272008-08-12 18:48:50 +0000694 va_list argp;
695 va_start(argp, Summ);
Ted Kremenekde4d5332009-04-24 17:50:11 +0000696 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Mike Stump1eb44332009-09-09 15:08:12 +0000697 va_end(argp);
Ted Kremenekaf9dc272008-08-12 18:48:50 +0000698 }
Mike Stump1eb44332009-09-09 15:08:12 +0000699
Ted Kremenek93edbc52011-10-05 23:54:29 +0000700 void addClsMethSummary(const char* Cls, const RetainSummary * Summ, ...) {
Ted Kremenekde4d5332009-04-24 17:50:11 +0000701 va_list argp;
702 va_start(argp, Summ);
703 addMethodSummary(&Ctx.Idents.get(Cls),ObjCClassMethodSummaries, Summ, argp);
704 va_end(argp);
705 }
Mike Stump1eb44332009-09-09 15:08:12 +0000706
Ted Kremenek93edbc52011-10-05 23:54:29 +0000707 void addClsMethSummary(IdentifierInfo *II, const RetainSummary * Summ, ...) {
Ted Kremenekde4d5332009-04-24 17:50:11 +0000708 va_list argp;
709 va_start(argp, Summ);
710 addMethodSummary(II, ObjCClassMethodSummaries, Summ, argp);
711 va_end(argp);
712 }
713
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000714public:
Mike Stump1eb44332009-09-09 15:08:12 +0000715
Ted Kremenek9c378f72011-08-12 23:37:29 +0000716 RetainSummaryManager(ASTContext &ctx, bool gcenabled, bool usesARC)
Ted Kremenek179064e2008-07-01 17:21:27 +0000717 : Ctx(ctx),
John McCallf85e1932011-06-15 23:02:42 +0000718 GCEnabled(gcenabled),
719 ARCEnabled(usesARC),
720 AF(BPAlloc), ScratchArgs(AF.getEmptyMap()),
721 ObjCAllocRetE(gcenabled
722 ? RetEffect::MakeGCNotOwned()
Stephen Hines651f13c2014-04-23 16:59:28 -0700723 : (usesARC ? RetEffect::MakeNotOwned(RetEffect::ObjC)
John McCallf85e1932011-06-15 23:02:42 +0000724 : RetEffect::MakeOwned(RetEffect::ObjC, true))),
725 ObjCInitRetE(gcenabled
726 ? RetEffect::MakeGCNotOwned()
Stephen Hines651f13c2014-04-23 16:59:28 -0700727 : (usesARC ? RetEffect::MakeNotOwned(RetEffect::ObjC)
Jordy Roseef945882012-03-18 01:26:10 +0000728 : RetEffect::MakeOwnedWhenTrackedReceiver())) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000729 InitializeClassMethodSummaries();
730 InitializeMethodSummaries();
731 }
Mike Stump1eb44332009-09-09 15:08:12 +0000732
Jordan Rose4531b7d2012-07-02 19:27:43 +0000733 const RetainSummary *getSummary(const CallEvent &Call,
734 ProgramStateRef State = 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000735
Jordan Rose4531b7d2012-07-02 19:27:43 +0000736 const RetainSummary *getFunctionSummary(const FunctionDecl *FD);
737
738 const RetainSummary *getMethodSummary(Selector S, const ObjCInterfaceDecl *ID,
Jordy Rosef3aae582012-03-17 21:13:07 +0000739 const ObjCMethodDecl *MD,
740 QualType RetTy,
741 ObjCMethodSummariesTy &CachedSummaries);
742
Jordan Rosecde8cdb2012-07-02 19:27:56 +0000743 const RetainSummary *getInstanceMethodSummary(const ObjCMethodCall &M,
Jordan Rose4531b7d2012-07-02 19:27:43 +0000744 ProgramStateRef State);
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000745
Jordan Rosecde8cdb2012-07-02 19:27:56 +0000746 const RetainSummary *getClassMethodSummary(const ObjCMethodCall &M) {
Jordan Rose4531b7d2012-07-02 19:27:43 +0000747 assert(!M.isInstanceMessage());
748 const ObjCInterfaceDecl *Class = M.getReceiverInterface();
Mike Stump1eb44332009-09-09 15:08:12 +0000749
Jordan Rose4531b7d2012-07-02 19:27:43 +0000750 return getMethodSummary(M.getSelector(), Class, M.getDecl(),
751 M.getResultType(), ObjCClassMethodSummaries);
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +0000752 }
Ted Kremenek552333c2009-04-29 17:17:48 +0000753
754 /// getMethodSummary - This version of getMethodSummary is used to query
755 /// the summary for the current method being analyzed.
Ted Kremenek93edbc52011-10-05 23:54:29 +0000756 const RetainSummary *getMethodSummary(const ObjCMethodDecl *MD) {
Ted Kremeneka8833552009-04-29 23:03:22 +0000757 const ObjCInterfaceDecl *ID = MD->getClassInterface();
Ted Kremenek70a65762009-04-30 05:41:14 +0000758 Selector S = MD->getSelector();
Stephen Hines651f13c2014-04-23 16:59:28 -0700759 QualType ResultTy = MD->getReturnType();
Mike Stump1eb44332009-09-09 15:08:12 +0000760
Jordy Rosef3aae582012-03-17 21:13:07 +0000761 ObjCMethodSummariesTy *CachedSummaries;
Ted Kremenek552333c2009-04-29 17:17:48 +0000762 if (MD->isInstanceMethod())
Jordy Rosef3aae582012-03-17 21:13:07 +0000763 CachedSummaries = &ObjCMethodSummaries;
Ted Kremenek552333c2009-04-29 17:17:48 +0000764 else
Jordy Rosef3aae582012-03-17 21:13:07 +0000765 CachedSummaries = &ObjCClassMethodSummaries;
766
Jordan Rose4531b7d2012-07-02 19:27:43 +0000767 return getMethodSummary(S, ID, MD, ResultTy, *CachedSummaries);
Ted Kremenek552333c2009-04-29 17:17:48 +0000768 }
Mike Stump1eb44332009-09-09 15:08:12 +0000769
Jordy Rosef3aae582012-03-17 21:13:07 +0000770 const RetainSummary *getStandardMethodSummary(const ObjCMethodDecl *MD,
Jordan Rose4531b7d2012-07-02 19:27:43 +0000771 Selector S, QualType RetTy);
Ted Kremeneka8833552009-04-29 23:03:22 +0000772
Jordan Rose44405b72013-04-04 22:31:48 +0000773 /// Determine if there is a special return effect for this function or method.
774 Optional<RetEffect> getRetEffectFromAnnotations(QualType RetTy,
775 const Decl *D);
776
Ted Kremenek93edbc52011-10-05 23:54:29 +0000777 void updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenek4dd8fb42009-05-09 02:58:13 +0000778 const ObjCMethodDecl *MD);
779
Ted Kremenek93edbc52011-10-05 23:54:29 +0000780 void updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenek4dd8fb42009-05-09 02:58:13 +0000781 const FunctionDecl *FD);
782
Jordan Rose4531b7d2012-07-02 19:27:43 +0000783 void updateSummaryForCall(const RetainSummary *&Summ,
784 const CallEvent &Call);
785
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000786 bool isGCEnabled() const { return GCEnabled; }
Mike Stump1eb44332009-09-09 15:08:12 +0000787
John McCallf85e1932011-06-15 23:02:42 +0000788 bool isARCEnabled() const { return ARCEnabled; }
789
790 bool isARCorGCEnabled() const { return GCEnabled || ARCEnabled; }
Jordan Rose4531b7d2012-07-02 19:27:43 +0000791
792 RetEffect getObjAllocRetEffect() const { return ObjCAllocRetE; }
793
794 friend class RetainSummaryTemplate;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000795};
Mike Stump1eb44332009-09-09 15:08:12 +0000796
Jordy Rose0fe62f82011-08-24 09:02:37 +0000797// Used to avoid allocating long-term (BPAlloc'd) memory for default retain
798// summaries. If a function or method looks like it has a default summary, but
799// it has annotations, the annotations are added to the stack-based template
800// and then copied into managed memory.
801class RetainSummaryTemplate {
802 RetainSummaryManager &Manager;
Ted Kremenek93edbc52011-10-05 23:54:29 +0000803 const RetainSummary *&RealSummary;
Jordy Rose0fe62f82011-08-24 09:02:37 +0000804 RetainSummary ScratchSummary;
805 bool Accessed;
806public:
Jordan Rose4531b7d2012-07-02 19:27:43 +0000807 RetainSummaryTemplate(const RetainSummary *&real, RetainSummaryManager &mgr)
808 : Manager(mgr), RealSummary(real), ScratchSummary(*real), Accessed(false) {}
Jordy Rose0fe62f82011-08-24 09:02:37 +0000809
810 ~RetainSummaryTemplate() {
Ted Kremenek93edbc52011-10-05 23:54:29 +0000811 if (Accessed)
Jordy Roseef945882012-03-18 01:26:10 +0000812 RealSummary = Manager.getPersistentSummary(ScratchSummary);
Jordy Rose0fe62f82011-08-24 09:02:37 +0000813 }
814
815 RetainSummary &operator*() {
816 Accessed = true;
Ted Kremenek93edbc52011-10-05 23:54:29 +0000817 return ScratchSummary;
Jordy Rose0fe62f82011-08-24 09:02:37 +0000818 }
819
820 RetainSummary *operator->() {
821 Accessed = true;
Ted Kremenek93edbc52011-10-05 23:54:29 +0000822 return &ScratchSummary;
Jordy Rose0fe62f82011-08-24 09:02:37 +0000823 }
824};
825
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000826} // end anonymous namespace
827
828//===----------------------------------------------------------------------===//
829// Implementation of checker data structures.
830//===----------------------------------------------------------------------===//
831
Ted Kremenekb77449c2009-05-03 05:20:50 +0000832ArgEffects RetainSummaryManager::getArgEffects() {
833 ArgEffects AE = ScratchArgs;
Ted Kremenek3baf6722010-11-24 00:54:37 +0000834 ScratchArgs = AF.getEmptyMap();
Ted Kremenekb77449c2009-05-03 05:20:50 +0000835 return AE;
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000836}
837
Ted Kremenek93edbc52011-10-05 23:54:29 +0000838const RetainSummary *
Jordy Roseef945882012-03-18 01:26:10 +0000839RetainSummaryManager::getPersistentSummary(const RetainSummary &OldSumm) {
840 // Unique "simple" summaries -- those without ArgEffects.
841 if (OldSumm.isSimple()) {
842 llvm::FoldingSetNodeID ID;
843 OldSumm.Profile(ID);
844
845 void *Pos;
846 CachedSummaryNode *N = SimpleSummaries.FindNodeOrInsertPos(ID, Pos);
847
848 if (!N) {
849 N = (CachedSummaryNode *) BPAlloc.Allocate<CachedSummaryNode>();
850 new (N) CachedSummaryNode(OldSumm);
851 SimpleSummaries.InsertNode(N, Pos);
852 }
853
854 return &N->getValue();
855 }
856
Ted Kremenek93edbc52011-10-05 23:54:29 +0000857 RetainSummary *Summ = (RetainSummary *) BPAlloc.Allocate<RetainSummary>();
Jordy Roseef945882012-03-18 01:26:10 +0000858 new (Summ) RetainSummary(OldSumm);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000859 return Summ;
860}
861
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000862//===----------------------------------------------------------------------===//
863// Summary creation for functions (largely uses of Core Foundation).
864//===----------------------------------------------------------------------===//
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000865
Ted Kremenek9c378f72011-08-12 23:37:29 +0000866static bool isRetain(const FunctionDecl *FD, StringRef FName) {
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000867 return FName.endswith("Retain");
Ted Kremenek12619382009-01-12 21:45:02 +0000868}
869
Ted Kremenek9c378f72011-08-12 23:37:29 +0000870static bool isRelease(const FunctionDecl *FD, StringRef FName) {
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000871 return FName.endswith("Release");
Ted Kremenek12619382009-01-12 21:45:02 +0000872}
873
Jordan Rose391165f2013-10-07 17:16:52 +0000874static bool isAutorelease(const FunctionDecl *FD, StringRef FName) {
875 return FName.endswith("Autorelease");
876}
877
Jordy Rose76c506f2011-08-21 21:58:18 +0000878static bool isMakeCollectable(const FunctionDecl *FD, StringRef FName) {
879 // FIXME: Remove FunctionDecl parameter.
880 // FIXME: Is it really okay if MakeCollectable isn't a suffix?
881 return FName.find("MakeCollectable") != StringRef::npos;
882}
883
Anna Zaks554067f2012-08-29 23:23:43 +0000884static ArgEffect getStopTrackingHardEquivalent(ArgEffect E) {
Jordan Rose4531b7d2012-07-02 19:27:43 +0000885 switch (E) {
886 case DoNothing:
887 case Autorelease:
Benjamin Kramer06382062013-10-20 11:47:15 +0000888 case DecRefBridgedTransferred:
Jordan Rose4531b7d2012-07-02 19:27:43 +0000889 case IncRef:
890 case IncRefMsg:
891 case MakeCollectable:
892 case MayEscape:
Jordan Rose4531b7d2012-07-02 19:27:43 +0000893 case StopTracking:
Anna Zaks554067f2012-08-29 23:23:43 +0000894 case StopTrackingHard:
895 return StopTrackingHard;
Jordan Rose4531b7d2012-07-02 19:27:43 +0000896 case DecRef:
Anna Zaks554067f2012-08-29 23:23:43 +0000897 case DecRefAndStopTrackingHard:
898 return DecRefAndStopTrackingHard;
Jordan Rose4531b7d2012-07-02 19:27:43 +0000899 case DecRefMsg:
Anna Zaks554067f2012-08-29 23:23:43 +0000900 case DecRefMsgAndStopTrackingHard:
901 return DecRefMsgAndStopTrackingHard;
Jordan Rose4531b7d2012-07-02 19:27:43 +0000902 case Dealloc:
903 return Dealloc;
904 }
905
906 llvm_unreachable("Unknown ArgEffect kind");
907}
908
909void RetainSummaryManager::updateSummaryForCall(const RetainSummary *&S,
910 const CallEvent &Call) {
911 if (Call.hasNonZeroCallbackArg()) {
Anna Zaks554067f2012-08-29 23:23:43 +0000912 ArgEffect RecEffect =
913 getStopTrackingHardEquivalent(S->getReceiverEffect());
914 ArgEffect DefEffect =
915 getStopTrackingHardEquivalent(S->getDefaultArgEffect());
Jordan Rose4531b7d2012-07-02 19:27:43 +0000916
917 ArgEffects CustomArgEffects = S->getArgEffects();
918 for (ArgEffects::iterator I = CustomArgEffects.begin(),
919 E = CustomArgEffects.end();
920 I != E; ++I) {
Anna Zaks554067f2012-08-29 23:23:43 +0000921 ArgEffect Translated = getStopTrackingHardEquivalent(I->second);
Jordan Rose4531b7d2012-07-02 19:27:43 +0000922 if (Translated != DefEffect)
923 ScratchArgs = AF.add(ScratchArgs, I->first, Translated);
924 }
925
Anna Zaks554067f2012-08-29 23:23:43 +0000926 RetEffect RE = RetEffect::MakeNoRetHard();
Jordan Rose4531b7d2012-07-02 19:27:43 +0000927
928 // Special cases where the callback argument CANNOT free the return value.
929 // This can generally only happen if we know that the callback will only be
930 // called when the return value is already being deallocated.
Stephen Hines651f13c2014-04-23 16:59:28 -0700931 if (const SimpleFunctionCall *FC = dyn_cast<SimpleFunctionCall>(&Call)) {
Jordan Rose4a25f302012-09-01 17:39:13 +0000932 if (IdentifierInfo *Name = FC->getDecl()->getIdentifier()) {
933 // When the CGBitmapContext is deallocated, the callback here will free
934 // the associated data buffer.
Jordan Rosea89f7192012-08-31 18:19:18 +0000935 if (Name->isStr("CGBitmapContextCreateWithData"))
936 RE = S->getRetEffect();
Jordan Rose4a25f302012-09-01 17:39:13 +0000937 }
Jordan Rose4531b7d2012-07-02 19:27:43 +0000938 }
939
940 S = getPersistentSummary(RE, RecEffect, DefEffect);
941 }
Anna Zaks5a901932012-08-24 00:06:12 +0000942
943 // Special case '[super init];' and '[self init];'
944 //
945 // Even though calling '[super init]' without assigning the result to self
946 // and checking if the parent returns 'nil' is a bad pattern, it is common.
947 // Additionally, our Self Init checker already warns about it. To avoid
948 // overwhelming the user with messages from both checkers, we model the case
949 // of '[super init]' in cases when it is not consumed by another expression
950 // as if the call preserves the value of 'self'; essentially, assuming it can
951 // never fail and return 'nil'.
952 // Note, we don't want to just stop tracking the value since we want the
953 // RetainCount checker to report leaks and use-after-free if SelfInit checker
954 // is turned off.
955 if (const ObjCMethodCall *MC = dyn_cast<ObjCMethodCall>(&Call)) {
956 if (MC->getMethodFamily() == OMF_init && MC->isReceiverSelfOrSuper()) {
957
958 // Check if the message is not consumed, we know it will not be used in
959 // an assignment, ex: "self = [super init]".
960 const Expr *ME = MC->getOriginExpr();
961 const LocationContext *LCtx = MC->getLocationContext();
962 ParentMap &PM = LCtx->getAnalysisDeclContext()->getParentMap();
963 if (!PM.isConsumedExpr(ME)) {
964 RetainSummaryTemplate ModifiableSummaryTemplate(S, *this);
965 ModifiableSummaryTemplate->setReceiverEffect(DoNothing);
966 ModifiableSummaryTemplate->setRetEffect(RetEffect::MakeNoRet());
967 }
968 }
969
970 }
Jordan Rose4531b7d2012-07-02 19:27:43 +0000971}
972
Anna Zaks58822c42012-05-04 22:18:39 +0000973const RetainSummary *
Jordan Rose4531b7d2012-07-02 19:27:43 +0000974RetainSummaryManager::getSummary(const CallEvent &Call,
975 ProgramStateRef State) {
976 const RetainSummary *Summ;
977 switch (Call.getKind()) {
978 case CE_Function:
Stephen Hines651f13c2014-04-23 16:59:28 -0700979 Summ = getFunctionSummary(cast<SimpleFunctionCall>(Call).getDecl());
Jordan Rose4531b7d2012-07-02 19:27:43 +0000980 break;
981 case CE_CXXMember:
Jordan Rosefdaa3382012-07-03 22:55:57 +0000982 case CE_CXXMemberOperator:
Jordan Rose4531b7d2012-07-02 19:27:43 +0000983 case CE_Block:
984 case CE_CXXConstructor:
Jordan Rose8d276d32012-07-10 22:07:47 +0000985 case CE_CXXDestructor:
Jordan Rose70cbf3c2012-07-02 22:21:47 +0000986 case CE_CXXAllocator:
Jordan Rose4531b7d2012-07-02 19:27:43 +0000987 // FIXME: These calls are currently unsupported.
988 return getPersistentStopSummary();
Jordan Rose8919e682012-07-18 21:59:51 +0000989 case CE_ObjCMessage: {
Jordan Rosecde8cdb2012-07-02 19:27:56 +0000990 const ObjCMethodCall &Msg = cast<ObjCMethodCall>(Call);
Jordan Rose4531b7d2012-07-02 19:27:43 +0000991 if (Msg.isInstanceMessage())
992 Summ = getInstanceMethodSummary(Msg, State);
993 else
994 Summ = getClassMethodSummary(Msg);
995 break;
996 }
997 }
998
999 updateSummaryForCall(Summ, Call);
1000
1001 assert(Summ && "Unknown call type?");
1002 return Summ;
1003}
1004
1005const RetainSummary *
1006RetainSummaryManager::getFunctionSummary(const FunctionDecl *FD) {
1007 // If we don't know what function we're calling, use our default summary.
1008 if (!FD)
1009 return getDefaultSummary();
1010
Ted Kremenek891d5cc2008-04-24 17:22:33 +00001011 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001012 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001013 if (I != FuncSummaries.end())
Ted Kremenek891d5cc2008-04-24 17:22:33 +00001014 return I->second;
1015
Ted Kremeneke401a0c2009-05-04 15:34:07 +00001016 // No summary? Generate one.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001017 const RetainSummary *S = 0;
Jordan Rose15d18e12012-08-06 21:28:02 +00001018 bool AllowAnnotations = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001019
Ted Kremenek37d785b2008-07-15 16:50:12 +00001020 do {
Ted Kremenek12619382009-01-12 21:45:02 +00001021 // We generate "stop" summaries for implicitly defined functions.
1022 if (FD->isImplicit()) {
1023 S = getPersistentStopSummary();
1024 break;
Ted Kremenek37d785b2008-07-15 16:50:12 +00001025 }
Mike Stump1eb44332009-09-09 15:08:12 +00001026
John McCall183700f2009-09-21 23:43:11 +00001027 // [PR 3337] Use 'getAs<FunctionType>' to strip away any typedefs on the
Ted Kremenek99890652009-01-16 18:40:33 +00001028 // function's type.
John McCall183700f2009-09-21 23:43:11 +00001029 const FunctionType* FT = FD->getType()->getAs<FunctionType>();
Ted Kremenek48c6d182009-12-16 06:06:43 +00001030 const IdentifierInfo *II = FD->getIdentifier();
1031 if (!II)
1032 break;
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001033
1034 StringRef FName = II->getName();
Mike Stump1eb44332009-09-09 15:08:12 +00001035
Ted Kremenekbf0a4dd2009-03-05 22:11:14 +00001036 // Strip away preceding '_'. Doing this here will effect all the checks
1037 // down below.
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001038 FName = FName.substr(FName.find_first_not_of('_'));
Mike Stump1eb44332009-09-09 15:08:12 +00001039
Ted Kremenek12619382009-01-12 21:45:02 +00001040 // Inspect the result type.
Stephen Hines651f13c2014-04-23 16:59:28 -07001041 QualType RetTy = FT->getReturnType();
Mike Stump1eb44332009-09-09 15:08:12 +00001042
Ted Kremenek12619382009-01-12 21:45:02 +00001043 // FIXME: This should all be refactored into a chain of "summary lookup"
1044 // filters.
Ted Kremenek008636a2009-10-14 00:27:24 +00001045 assert(ScratchArgs.isEmpty());
Ted Kremenek39d88b02009-06-15 20:36:07 +00001046
Ted Kremenekbefc6d22012-04-26 04:32:23 +00001047 if (FName == "pthread_create" || FName == "pthread_setspecific") {
1048 // Part of: <rdar://problem/7299394> and <rdar://problem/11282706>.
1049 // This will be addressed better with IPA.
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001050 S = getPersistentStopSummary();
1051 } else if (FName == "NSMakeCollectable") {
1052 // Handle: id NSMakeCollectable(CFTypeRef)
1053 S = (RetTy->isObjCIdType())
1054 ? getUnarySummary(FT, cfmakecollectable)
1055 : getPersistentStopSummary();
Jordan Rose15d18e12012-08-06 21:28:02 +00001056 // The headers on OS X 10.8 use cf_consumed/ns_returns_retained,
1057 // but we can fully model NSMakeCollectable ourselves.
1058 AllowAnnotations = false;
Ted Kremenek061707a2012-09-06 23:47:02 +00001059 } else if (FName == "CFPlugInInstanceCreate") {
1060 S = getPersistentSummary(RetEffect::MakeNoRet());
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001061 } else if (FName == "IOBSDNameMatching" ||
1062 FName == "IOServiceMatching" ||
1063 FName == "IOServiceNameMatching" ||
Ted Kremenek537dd3a2012-05-01 05:28:27 +00001064 FName == "IORegistryEntrySearchCFProperty" ||
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001065 FName == "IORegistryEntryIDMatching" ||
1066 FName == "IOOpenFirmwarePathMatching") {
1067 // Part of <rdar://problem/6961230>. (IOKit)
1068 // This should be addressed using a API table.
1069 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1070 DoNothing, DoNothing);
1071 } else if (FName == "IOServiceGetMatchingService" ||
1072 FName == "IOServiceGetMatchingServices") {
1073 // FIXES: <rdar://problem/6326900>
1074 // This should be addressed using a API table. This strcmp is also
1075 // a little gross, but there is no need to super optimize here.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001076 ScratchArgs = AF.add(ScratchArgs, 1, DecRef);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001077 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1078 } else if (FName == "IOServiceAddNotification" ||
1079 FName == "IOServiceAddMatchingNotification") {
1080 // Part of <rdar://problem/6961230>. (IOKit)
1081 // This should be addressed using a API table.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001082 ScratchArgs = AF.add(ScratchArgs, 2, DecRef);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001083 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1084 } else if (FName == "CVPixelBufferCreateWithBytes") {
1085 // FIXES: <rdar://problem/7283567>
1086 // Eventually this can be improved by recognizing that the pixel
1087 // buffer passed to CVPixelBufferCreateWithBytes is released via
1088 // a callback and doing full IPA to make sure this is done correctly.
1089 // FIXME: This function has an out parameter that returns an
1090 // allocated object.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001091 ScratchArgs = AF.add(ScratchArgs, 7, StopTracking);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001092 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1093 } else if (FName == "CGBitmapContextCreateWithData") {
1094 // FIXES: <rdar://problem/7358899>
1095 // Eventually this can be improved by recognizing that 'releaseInfo'
1096 // passed to CGBitmapContextCreateWithData is released via
1097 // a callback and doing full IPA to make sure this is done correctly.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001098 ScratchArgs = AF.add(ScratchArgs, 8, StopTracking);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001099 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1100 DoNothing, DoNothing);
1101 } else if (FName == "CVPixelBufferCreateWithPlanarBytes") {
1102 // FIXES: <rdar://problem/7283567>
1103 // Eventually this can be improved by recognizing that the pixel
1104 // buffer passed to CVPixelBufferCreateWithPlanarBytes is released
1105 // via a callback and doing full IPA to make sure this is done
1106 // correctly.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001107 ScratchArgs = AF.add(ScratchArgs, 12, StopTracking);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001108 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Jordan Rose8a729b42013-05-02 01:51:40 +00001109 } else if (FName == "dispatch_set_context" ||
1110 FName == "xpc_connection_set_context") {
Ted Kremenek06911d42012-03-22 06:29:41 +00001111 // <rdar://problem/11059275> - The analyzer currently doesn't have
1112 // a good way to reason about the finalizer function for libdispatch.
1113 // If we pass a context object that is memory managed, stop tracking it.
Jordan Rose8a729b42013-05-02 01:51:40 +00001114 // <rdar://problem/13783514> - Same problem, but for XPC.
Ted Kremenek06911d42012-03-22 06:29:41 +00001115 // FIXME: this hack should possibly go away once we can handle
Jordan Rose8a729b42013-05-02 01:51:40 +00001116 // libdispatch and XPC finalizers.
Ted Kremenek06911d42012-03-22 06:29:41 +00001117 ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
1118 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenekc91fdf62012-05-08 00:12:09 +00001119 } else if (FName.startswith("NSLog")) {
1120 S = getDoNothingSummary();
Anna Zaks62a5c342012-03-30 05:48:16 +00001121 } else if (FName.startswith("NS") &&
1122 (FName.find("Insert") != StringRef::npos)) {
1123 // Whitelist NSXXInsertXX, for example NSMapInsertIfAbsent, since they can
1124 // be deallocated by NSMapRemove. (radar://11152419)
1125 ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
1126 ScratchArgs = AF.add(ScratchArgs, 2, StopTracking);
1127 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenekb04cb592009-06-11 18:17:24 +00001128 }
Mike Stump1eb44332009-09-09 15:08:12 +00001129
Ted Kremenekb04cb592009-06-11 18:17:24 +00001130 // Did we get a summary?
1131 if (S)
1132 break;
Ted Kremenek61991902009-03-17 22:43:44 +00001133
Jordan Rose5aff3f12013-03-04 23:21:32 +00001134 if (RetTy->isPointerType()) {
Ted Kremenek12619382009-01-12 21:45:02 +00001135 // For CoreFoundation ('CF') types.
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001136 if (cocoa::isRefType(RetTy, "CF", FName)) {
Jordan Rose391165f2013-10-07 17:16:52 +00001137 if (isRetain(FD, FName)) {
Ted Kremenek12619382009-01-12 21:45:02 +00001138 S = getUnarySummary(FT, cfretain);
Jordan Rose391165f2013-10-07 17:16:52 +00001139 } else if (isAutorelease(FD, FName)) {
1140 S = getUnarySummary(FT, cfautorelease);
1141 // The headers use cf_consumed, but we can fully model CFAutorelease
1142 // ourselves.
1143 AllowAnnotations = false;
1144 } else if (isMakeCollectable(FD, FName)) {
Ted Kremenek12619382009-01-12 21:45:02 +00001145 S = getUnarySummary(FT, cfmakecollectable);
Jordan Rose391165f2013-10-07 17:16:52 +00001146 AllowAnnotations = false;
1147 } else {
John McCall7df2ff42011-10-01 00:48:56 +00001148 S = getCFCreateGetRuleSummary(FD);
Jordan Rose391165f2013-10-07 17:16:52 +00001149 }
Ted Kremenek12619382009-01-12 21:45:02 +00001150
1151 break;
1152 }
1153
1154 // For CoreGraphics ('CG') types.
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001155 if (cocoa::isRefType(RetTy, "CG", FName)) {
Ted Kremenek12619382009-01-12 21:45:02 +00001156 if (isRetain(FD, FName))
1157 S = getUnarySummary(FT, cfretain);
1158 else
John McCall7df2ff42011-10-01 00:48:56 +00001159 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek12619382009-01-12 21:45:02 +00001160
1161 break;
1162 }
1163
1164 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001165 if (cocoa::isRefType(RetTy, "DADisk") ||
1166 cocoa::isRefType(RetTy, "DADissenter") ||
1167 cocoa::isRefType(RetTy, "DASessionRef")) {
John McCall7df2ff42011-10-01 00:48:56 +00001168 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek12619382009-01-12 21:45:02 +00001169 break;
1170 }
Mike Stump1eb44332009-09-09 15:08:12 +00001171
Stephen Hines651f13c2014-04-23 16:59:28 -07001172 if (FD->hasAttr<CFAuditedTransferAttr>()) {
Jordan Rose5aff3f12013-03-04 23:21:32 +00001173 S = getCFCreateGetRuleSummary(FD);
1174 break;
1175 }
1176
Ted Kremenek12619382009-01-12 21:45:02 +00001177 break;
1178 }
1179
1180 // Check for release functions, the only kind of functions that we care
1181 // about that don't return a pointer type.
1182 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
Ted Kremeneke7d03122010-02-08 16:45:01 +00001183 // Test for 'CGCF'.
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001184 FName = FName.substr(FName.startswith("CGCF") ? 4 : 2);
Ted Kremeneke7d03122010-02-08 16:45:01 +00001185
Ted Kremenekbf0a4dd2009-03-05 22:11:14 +00001186 if (isRelease(FD, FName))
Ted Kremenek12619382009-01-12 21:45:02 +00001187 S = getUnarySummary(FT, cfrelease);
1188 else {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001189 assert (ScratchArgs.isEmpty());
Ted Kremenek68189282009-01-29 22:45:13 +00001190 // Remaining CoreFoundation and CoreGraphics functions.
1191 // We use to assume that they all strictly followed the ownership idiom
1192 // and that ownership cannot be transferred. While this is technically
1193 // correct, many methods allow a tracked object to escape. For example:
1194 //
Mike Stump1eb44332009-09-09 15:08:12 +00001195 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
Ted Kremenek68189282009-01-29 22:45:13 +00001196 // CFDictionaryAddValue(y, key, x);
Mike Stump1eb44332009-09-09 15:08:12 +00001197 // CFRelease(x);
Ted Kremenek68189282009-01-29 22:45:13 +00001198 // ... it is okay to use 'x' since 'y' has a reference to it
1199 //
1200 // We handle this and similar cases with the follow heuristic. If the
Ted Kremenekc4843812009-08-20 00:57:22 +00001201 // function name contains "InsertValue", "SetValue", "AddValue",
1202 // "AppendValue", or "SetAttribute", then we assume that arguments may
1203 // "escape." This means that something else holds on to the object,
1204 // allowing it be used even after its local retain count drops to 0.
Benjamin Kramere45c1492010-01-11 19:46:28 +00001205 ArgEffect E = (StrInStrNoCase(FName, "InsertValue") != StringRef::npos||
1206 StrInStrNoCase(FName, "AddValue") != StringRef::npos ||
1207 StrInStrNoCase(FName, "SetValue") != StringRef::npos ||
1208 StrInStrNoCase(FName, "AppendValue") != StringRef::npos||
Benjamin Kramerc027e542010-01-11 20:15:06 +00001209 StrInStrNoCase(FName, "SetAttribute") != StringRef::npos)
Ted Kremenek68189282009-01-29 22:45:13 +00001210 ? MayEscape : DoNothing;
Mike Stump1eb44332009-09-09 15:08:12 +00001211
Ted Kremenek68189282009-01-29 22:45:13 +00001212 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek12619382009-01-12 21:45:02 +00001213 }
1214 }
Ted Kremenek37d785b2008-07-15 16:50:12 +00001215 }
1216 while (0);
Mike Stump1eb44332009-09-09 15:08:12 +00001217
Jordan Rose4531b7d2012-07-02 19:27:43 +00001218 // If we got all the way here without any luck, use a default summary.
1219 if (!S)
1220 S = getDefaultSummary();
1221
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001222 // Annotations override defaults.
Jordan Rose15d18e12012-08-06 21:28:02 +00001223 if (AllowAnnotations)
1224 updateSummaryFromAnnotations(S, FD);
Mike Stump1eb44332009-09-09 15:08:12 +00001225
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001226 FuncSummaries[FD] = S;
Mike Stump1eb44332009-09-09 15:08:12 +00001227 return S;
Ted Kremenek2fff37e2008-03-06 00:08:09 +00001228}
1229
Ted Kremenek93edbc52011-10-05 23:54:29 +00001230const RetainSummary *
John McCall7df2ff42011-10-01 00:48:56 +00001231RetainSummaryManager::getCFCreateGetRuleSummary(const FunctionDecl *FD) {
1232 if (coreFoundation::followsCreateRule(FD))
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001233 return getCFSummaryCreateRule(FD);
Mike Stump1eb44332009-09-09 15:08:12 +00001234
Ted Kremenekd368d712011-05-25 06:19:45 +00001235 return getCFSummaryGetRule(FD);
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001236}
1237
Ted Kremenek93edbc52011-10-05 23:54:29 +00001238const RetainSummary *
Ted Kremenek6ad315a2009-02-23 16:51:39 +00001239RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1240 UnaryFuncKind func) {
1241
Ted Kremenek12619382009-01-12 21:45:02 +00001242 // Sanity check that this is *really* a unary function. This can
1243 // happen if people do weird things.
Douglas Gregor72564e72009-02-26 23:50:07 +00001244 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
Stephen Hines651f13c2014-04-23 16:59:28 -07001245 if (!FTP || FTP->getNumParams() != 1)
Ted Kremenek12619382009-01-12 21:45:02 +00001246 return getPersistentStopSummary();
Mike Stump1eb44332009-09-09 15:08:12 +00001247
Ted Kremenekb77449c2009-05-03 05:20:50 +00001248 assert (ScratchArgs.isEmpty());
Mike Stump1eb44332009-09-09 15:08:12 +00001249
Jordy Rose76c506f2011-08-21 21:58:18 +00001250 ArgEffect Effect;
Ted Kremenek377e2302008-04-29 05:33:51 +00001251 switch (func) {
Jordan Rose391165f2013-10-07 17:16:52 +00001252 case cfretain: Effect = IncRef; break;
1253 case cfrelease: Effect = DecRef; break;
1254 case cfautorelease: Effect = Autorelease; break;
1255 case cfmakecollectable: Effect = MakeCollectable; break;
Ted Kremenek940b1d82008-04-10 23:44:06 +00001256 }
Jordy Rose76c506f2011-08-21 21:58:18 +00001257
1258 ScratchArgs = AF.add(ScratchArgs, 0, Effect);
1259 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001260}
1261
Ted Kremenek93edbc52011-10-05 23:54:29 +00001262const RetainSummary *
Ted Kremenek9c378f72011-08-12 23:37:29 +00001263RetainSummaryManager::getCFSummaryCreateRule(const FunctionDecl *FD) {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001264 assert (ScratchArgs.isEmpty());
Mike Stump1eb44332009-09-09 15:08:12 +00001265
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001266 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001267}
1268
Ted Kremenek93edbc52011-10-05 23:54:29 +00001269const RetainSummary *
Ted Kremenek9c378f72011-08-12 23:37:29 +00001270RetainSummaryManager::getCFSummaryGetRule(const FunctionDecl *FD) {
Mike Stump1eb44332009-09-09 15:08:12 +00001271 assert (ScratchArgs.isEmpty());
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001272 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1273 DoNothing, DoNothing);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001274}
1275
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001276//===----------------------------------------------------------------------===//
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001277// Summary creation for Selectors.
1278//===----------------------------------------------------------------------===//
1279
Jordan Rose44405b72013-04-04 22:31:48 +00001280Optional<RetEffect>
1281RetainSummaryManager::getRetEffectFromAnnotations(QualType RetTy,
1282 const Decl *D) {
1283 if (cocoa::isCocoaObjectRef(RetTy)) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001284 if (D->hasAttr<NSReturnsRetainedAttr>())
Jordan Rose44405b72013-04-04 22:31:48 +00001285 return ObjCAllocRetE;
1286
Stephen Hines651f13c2014-04-23 16:59:28 -07001287 if (D->hasAttr<NSReturnsNotRetainedAttr>() ||
1288 D->hasAttr<NSReturnsAutoreleasedAttr>())
Jordan Rose44405b72013-04-04 22:31:48 +00001289 return RetEffect::MakeNotOwned(RetEffect::ObjC);
1290
1291 } else if (!RetTy->isPointerType()) {
1292 return None;
1293 }
1294
Stephen Hines651f13c2014-04-23 16:59:28 -07001295 if (D->hasAttr<CFReturnsRetainedAttr>())
Jordan Rose44405b72013-04-04 22:31:48 +00001296 return RetEffect::MakeOwned(RetEffect::CF, true);
1297
Stephen Hines651f13c2014-04-23 16:59:28 -07001298 if (D->hasAttr<CFReturnsNotRetainedAttr>())
Jordan Rose44405b72013-04-04 22:31:48 +00001299 return RetEffect::MakeNotOwned(RetEffect::CF);
1300
1301 return None;
1302}
1303
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001304void
Ted Kremenek93edbc52011-10-05 23:54:29 +00001305RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001306 const FunctionDecl *FD) {
1307 if (!FD)
1308 return;
1309
Jordan Rose4531b7d2012-07-02 19:27:43 +00001310 assert(Summ && "Must have a summary to add annotations to.");
1311 RetainSummaryTemplate Template(Summ, *this);
Jordy Rose4df54fe2011-08-23 04:27:15 +00001312
Ted Kremenek11fe1752011-01-27 18:43:03 +00001313 // Effects on the parameters.
1314 unsigned parm_idx = 0;
1315 for (FunctionDecl::param_const_iterator pi = FD->param_begin(),
John McCall98b8f162011-04-06 09:02:12 +00001316 pe = FD->param_end(); pi != pe; ++pi, ++parm_idx) {
Ted Kremenek11fe1752011-01-27 18:43:03 +00001317 const ParmVarDecl *pd = *pi;
Stephen Hines651f13c2014-04-23 16:59:28 -07001318 if (pd->hasAttr<NSConsumedAttr>())
Jordan Rose44405b72013-04-04 22:31:48 +00001319 Template->addArg(AF, parm_idx, DecRefMsg);
Stephen Hines651f13c2014-04-23 16:59:28 -07001320 else if (pd->hasAttr<CFConsumedAttr>())
Jordy Rose0fe62f82011-08-24 09:02:37 +00001321 Template->addArg(AF, parm_idx, DecRef);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001322 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001323
1324 QualType RetTy = FD->getReturnType();
Jordan Rose44405b72013-04-04 22:31:48 +00001325 if (Optional<RetEffect> RetE = getRetEffectFromAnnotations(RetTy, FD))
1326 Template->setRetEffect(*RetE);
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001327}
1328
1329void
Ted Kremenek93edbc52011-10-05 23:54:29 +00001330RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
1331 const ObjCMethodDecl *MD) {
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001332 if (!MD)
1333 return;
1334
Jordan Rose4531b7d2012-07-02 19:27:43 +00001335 assert(Summ && "Must have a valid summary to add annotations to");
1336 RetainSummaryTemplate Template(Summ, *this);
Mike Stump1eb44332009-09-09 15:08:12 +00001337
Ted Kremenek12b94342011-01-27 06:54:14 +00001338 // Effects on the receiver.
Stephen Hines651f13c2014-04-23 16:59:28 -07001339 if (MD->hasAttr<NSConsumesSelfAttr>())
Jordan Rose44405b72013-04-04 22:31:48 +00001340 Template->setReceiverEffect(DecRefMsg);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001341
1342 // Effects on the parameters.
1343 unsigned parm_idx = 0;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00001344 for (ObjCMethodDecl::param_const_iterator
1345 pi=MD->param_begin(), pe=MD->param_end();
Ted Kremenek11fe1752011-01-27 18:43:03 +00001346 pi != pe; ++pi, ++parm_idx) {
1347 const ParmVarDecl *pd = *pi;
Stephen Hines651f13c2014-04-23 16:59:28 -07001348 if (pd->hasAttr<NSConsumedAttr>())
Jordan Rose44405b72013-04-04 22:31:48 +00001349 Template->addArg(AF, parm_idx, DecRefMsg);
Stephen Hines651f13c2014-04-23 16:59:28 -07001350 else if (pd->hasAttr<CFConsumedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001351 Template->addArg(AF, parm_idx, DecRef);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001352 }
Ted Kremenek12b94342011-01-27 06:54:14 +00001353 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001354
1355 QualType RetTy = MD->getReturnType();
Jordan Rose44405b72013-04-04 22:31:48 +00001356 if (Optional<RetEffect> RetE = getRetEffectFromAnnotations(RetTy, MD))
1357 Template->setRetEffect(*RetE);
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001358}
1359
Ted Kremenek93edbc52011-10-05 23:54:29 +00001360const RetainSummary *
Jordy Rosef3aae582012-03-17 21:13:07 +00001361RetainSummaryManager::getStandardMethodSummary(const ObjCMethodDecl *MD,
1362 Selector S, QualType RetTy) {
Jordy Rosee921b1a2012-03-17 19:53:04 +00001363 // Any special effects?
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001364 ArgEffect ReceiverEff = DoNothing;
Jordy Rosee921b1a2012-03-17 19:53:04 +00001365 RetEffect ResultEff = RetEffect::MakeNoRet();
1366
1367 // Check the method family, and apply any default annotations.
1368 switch (MD ? MD->getMethodFamily() : S.getMethodFamily()) {
1369 case OMF_None:
1370 case OMF_performSelector:
1371 // Assume all Objective-C methods follow Cocoa Memory Management rules.
1372 // FIXME: Does the non-threaded performSelector family really belong here?
1373 // The selector could be, say, @selector(copy).
1374 if (cocoa::isCocoaObjectRef(RetTy))
1375 ResultEff = RetEffect::MakeNotOwned(RetEffect::ObjC);
1376 else if (coreFoundation::isCFObjectRef(RetTy)) {
1377 // ObjCMethodDecl currently doesn't consider CF objects as valid return
1378 // values for alloc, new, copy, or mutableCopy, so we have to
1379 // double-check with the selector. This is ugly, but there aren't that
1380 // many Objective-C methods that return CF objects, right?
1381 if (MD) {
1382 switch (S.getMethodFamily()) {
1383 case OMF_alloc:
1384 case OMF_new:
1385 case OMF_copy:
1386 case OMF_mutableCopy:
1387 ResultEff = RetEffect::MakeOwned(RetEffect::CF, true);
1388 break;
1389 default:
1390 ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1391 break;
1392 }
1393 } else {
1394 ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1395 }
1396 }
1397 break;
1398 case OMF_init:
1399 ResultEff = ObjCInitRetE;
1400 ReceiverEff = DecRefMsg;
1401 break;
1402 case OMF_alloc:
1403 case OMF_new:
1404 case OMF_copy:
1405 case OMF_mutableCopy:
1406 if (cocoa::isCocoaObjectRef(RetTy))
1407 ResultEff = ObjCAllocRetE;
1408 else if (coreFoundation::isCFObjectRef(RetTy))
1409 ResultEff = RetEffect::MakeOwned(RetEffect::CF, true);
1410 break;
1411 case OMF_autorelease:
1412 ReceiverEff = Autorelease;
1413 break;
1414 case OMF_retain:
1415 ReceiverEff = IncRefMsg;
1416 break;
1417 case OMF_release:
1418 ReceiverEff = DecRefMsg;
1419 break;
1420 case OMF_dealloc:
1421 ReceiverEff = Dealloc;
1422 break;
1423 case OMF_self:
1424 // -self is handled specially by the ExprEngine to propagate the receiver.
1425 break;
1426 case OMF_retainCount:
1427 case OMF_finalize:
1428 // These methods don't return objects.
1429 break;
1430 }
Mike Stump1eb44332009-09-09 15:08:12 +00001431
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001432 // If one of the arguments in the selector has the keyword 'delegate' we
1433 // should stop tracking the reference count for the receiver. This is
1434 // because the reference count is quite possibly handled by a delegate
1435 // method.
1436 if (S.isKeywordSelector()) {
Jordan Rose50571a92012-06-15 18:19:52 +00001437 for (unsigned i = 0, e = S.getNumArgs(); i != e; ++i) {
1438 StringRef Slot = S.getNameForSlot(i);
1439 if (Slot.substr(Slot.size() - 8).equals_lower("delegate")) {
1440 if (ResultEff == ObjCInitRetE)
Anna Zaks554067f2012-08-29 23:23:43 +00001441 ResultEff = RetEffect::MakeNoRetHard();
Jordan Rose50571a92012-06-15 18:19:52 +00001442 else
Anna Zaks554067f2012-08-29 23:23:43 +00001443 ReceiverEff = StopTrackingHard;
Jordan Rose50571a92012-06-15 18:19:52 +00001444 }
1445 }
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001446 }
Mike Stump1eb44332009-09-09 15:08:12 +00001447
Jordy Rosee921b1a2012-03-17 19:53:04 +00001448 if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing &&
1449 ResultEff.getKind() == RetEffect::NoRet)
Ted Kremenek93edbc52011-10-05 23:54:29 +00001450 return getDefaultSummary();
Mike Stump1eb44332009-09-09 15:08:12 +00001451
Jordy Rosee921b1a2012-03-17 19:53:04 +00001452 return getPersistentSummary(ResultEff, ReceiverEff, MayEscape);
Ted Kremenek250b1fa2009-04-23 23:08:22 +00001453}
1454
Ted Kremenek93edbc52011-10-05 23:54:29 +00001455const RetainSummary *
Jordan Rosecde8cdb2012-07-02 19:27:56 +00001456RetainSummaryManager::getInstanceMethodSummary(const ObjCMethodCall &Msg,
Jordan Rose4531b7d2012-07-02 19:27:43 +00001457 ProgramStateRef State) {
1458 const ObjCInterfaceDecl *ReceiverClass = 0;
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001459
Jordan Rose4531b7d2012-07-02 19:27:43 +00001460 // We do better tracking of the type of the object than the core ExprEngine.
1461 // See if we have its type in our private state.
1462 // FIXME: Eventually replace the use of state->get<RefBindings> with
1463 // a generic API for reasoning about the Objective-C types of symbolic
1464 // objects.
1465 SVal ReceiverV = Msg.getReceiverSVal();
1466 if (SymbolRef Sym = ReceiverV.getAsLocSymbol())
Anna Zaks8d6b43c2012-08-14 00:36:15 +00001467 if (const RefVal *T = getRefBinding(State, Sym))
Douglas Gregor04badcf2010-04-21 00:45:42 +00001468 if (const ObjCObjectPointerType *PT =
Jordan Rose4531b7d2012-07-02 19:27:43 +00001469 T->getType()->getAs<ObjCObjectPointerType>())
1470 ReceiverClass = PT->getInterfaceDecl();
1471
1472 // If we don't know what kind of object this is, fall back to its static type.
1473 if (!ReceiverClass)
1474 ReceiverClass = Msg.getReceiverInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00001475
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001476 // FIXME: The receiver could be a reference to a class, meaning that
1477 // we should use the class method.
Jordan Rose4531b7d2012-07-02 19:27:43 +00001478 // id x = [NSObject class];
1479 // [x performSelector:... withObject:... afterDelay:...];
1480 Selector S = Msg.getSelector();
1481 const ObjCMethodDecl *Method = Msg.getDecl();
1482 if (!Method && ReceiverClass)
1483 Method = ReceiverClass->getInstanceMethod(S);
1484
1485 return getMethodSummary(S, ReceiverClass, Method, Msg.getResultType(),
1486 ObjCMethodSummaries);
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001487}
1488
Ted Kremenek93edbc52011-10-05 23:54:29 +00001489const RetainSummary *
Jordan Rose4531b7d2012-07-02 19:27:43 +00001490RetainSummaryManager::getMethodSummary(Selector S, const ObjCInterfaceDecl *ID,
Jordy Rosef3aae582012-03-17 21:13:07 +00001491 const ObjCMethodDecl *MD, QualType RetTy,
1492 ObjCMethodSummariesTy &CachedSummaries) {
Ted Kremenek1bffd742008-05-06 15:44:25 +00001493
Ted Kremenek8711c032009-04-29 05:04:30 +00001494 // Look up a summary in our summary cache.
Jordan Rose4531b7d2012-07-02 19:27:43 +00001495 const RetainSummary *Summ = CachedSummaries.find(ID, S);
Mike Stump1eb44332009-09-09 15:08:12 +00001496
Ted Kremenek614cc542009-07-21 23:27:57 +00001497 if (!Summ) {
Jordy Rosef3aae582012-03-17 21:13:07 +00001498 Summ = getStandardMethodSummary(MD, S, RetTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001499
Ted Kremenek614cc542009-07-21 23:27:57 +00001500 // Annotations override defaults.
Jordy Rose4df54fe2011-08-23 04:27:15 +00001501 updateSummaryFromAnnotations(Summ, MD);
Mike Stump1eb44332009-09-09 15:08:12 +00001502
Ted Kremenek614cc542009-07-21 23:27:57 +00001503 // Memoize the summary.
Jordan Rose4531b7d2012-07-02 19:27:43 +00001504 CachedSummaries[ObjCSummaryKey(ID, S)] = Summ;
Ted Kremenek614cc542009-07-21 23:27:57 +00001505 }
Mike Stump1eb44332009-09-09 15:08:12 +00001506
Ted Kremeneke87450e2009-04-23 19:11:35 +00001507 return Summ;
Ted Kremenekc8395602008-05-06 21:26:51 +00001508}
1509
Mike Stump1eb44332009-09-09 15:08:12 +00001510void RetainSummaryManager::InitializeClassMethodSummaries() {
Ted Kremenekec315332009-05-07 23:40:42 +00001511 assert(ScratchArgs.isEmpty());
Mike Stump1eb44332009-09-09 15:08:12 +00001512 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek6fe2b7a2009-10-15 22:25:12 +00001513 addClassMethSummary("NSAssertionHandler", "currentHandler",
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001514 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Mike Stump1eb44332009-09-09 15:08:12 +00001515
Ted Kremenek6d348932008-10-21 15:53:15 +00001516 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001517 ScratchArgs = AF.add(ScratchArgs, 0, Autorelease);
Ted Kremenek6fe2b7a2009-10-15 22:25:12 +00001518 addClassMethSummary("NSAutoreleasePool", "addObject",
1519 getPersistentSummary(RetEffect::MakeNoRet(),
1520 DoNothing, Autorelease));
Ted Kremenek9c32d082008-05-06 00:30:21 +00001521}
1522
Ted Kremenek1f180c32008-06-23 22:21:20 +00001523void RetainSummaryManager::InitializeMethodSummaries() {
Mike Stump1eb44332009-09-09 15:08:12 +00001524
1525 assert (ScratchArgs.isEmpty());
1526
Ted Kremenekc8395602008-05-06 21:26:51 +00001527 // Create the "init" selector. It just acts as a pass-through for the
1528 // receiver.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001529 const RetainSummary *InitSumm = getPersistentSummary(ObjCInitRetE, DecRefMsg);
Ted Kremenekac02f202009-08-20 05:13:36 +00001530 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
1531
1532 // awakeAfterUsingCoder: behaves basically like an 'init' method. It
1533 // claims the receiver and returns a retained object.
1534 addNSObjectMethSummary(GetUnarySelector("awakeAfterUsingCoder", Ctx),
1535 InitSumm);
Mike Stump1eb44332009-09-09 15:08:12 +00001536
Ted Kremenekc8395602008-05-06 21:26:51 +00001537 // The next methods are allocators.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001538 const RetainSummary *AllocSumm = getPersistentSummary(ObjCAllocRetE);
1539 const RetainSummary *CFAllocSumm =
Ted Kremeneka834fb42009-08-28 19:52:12 +00001540 getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Mike Stump1eb44332009-09-09 15:08:12 +00001541
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001542 // Create the "retain" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001543 RetEffect NoRet = RetEffect::MakeNoRet();
Ted Kremenek93edbc52011-10-05 23:54:29 +00001544 const RetainSummary *Summ = getPersistentSummary(NoRet, IncRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001545 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001546
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001547 // Create the "release" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001548 Summ = getPersistentSummary(NoRet, DecRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001549 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001550
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001551 // Create the -dealloc summary.
Jordy Rose500abad2011-08-21 19:41:36 +00001552 Summ = getPersistentSummary(NoRet, Dealloc);
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001553 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001554
1555 // Create the "autorelease" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001556 Summ = getPersistentSummary(NoRet, Autorelease);
Ted Kremenek553cf182008-06-25 21:21:56 +00001557 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001558
Mike Stump1eb44332009-09-09 15:08:12 +00001559 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremenek89e202d2009-02-23 02:51:29 +00001560 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1561 // self-own themselves. However, they only do this once they are displayed.
1562 // Thus, we need to track an NSWindow's display status.
1563 // This is tracked in <rdar://problem/6062711>.
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +00001564 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001565 const RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenek78a35a32009-05-12 20:06:54 +00001566 StopTracking,
1567 StopTracking);
Mike Stump1eb44332009-09-09 15:08:12 +00001568
Ted Kremenek99d02692009-04-03 19:02:51 +00001569 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1570
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001571 // For NSPanel (which subclasses NSWindow), allocated objects are not
1572 // self-owned.
Ted Kremenek99d02692009-04-03 19:02:51 +00001573 // FIXME: For now we don't track NSPanels. object for the same reason
1574 // as for NSWindow objects.
1575 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
Mike Stump1eb44332009-09-09 15:08:12 +00001576
Stephen Hines651f13c2014-04-23 16:59:28 -07001577 // For NSNull, objects returned by +null are singletons that ignore
1578 // retain/release semantics. Just don't track them.
1579 // <rdar://problem/12858915>
1580 addClassMethSummary("NSNull", "null", NoTrackYet);
1581
Jordan Rosee36d81b2013-01-31 22:06:02 +00001582 // Don't track allocated autorelease pools, as it is okay to prematurely
Ted Kremenekba67f6a2009-05-18 23:14:34 +00001583 // exit a method.
1584 addClassMethSummary("NSAutoreleasePool", "alloc", NoTrackYet);
Ted Kremeneka9797122012-02-18 21:37:48 +00001585 addClassMethSummary("NSAutoreleasePool", "allocWithZone", NoTrackYet, false);
Jordan Rosee36d81b2013-01-31 22:06:02 +00001586 addClassMethSummary("NSAutoreleasePool", "new", NoTrackYet);
Ted Kremenek553cf182008-06-25 21:21:56 +00001587
Ted Kremenek767d6492009-05-20 22:39:57 +00001588 // Create summaries QCRenderer/QCView -createSnapShotImageOfType:
1589 addInstMethSummary("QCRenderer", AllocSumm,
1590 "createSnapshotImageOfType", NULL);
1591 addInstMethSummary("QCView", AllocSumm,
1592 "createSnapshotImageOfType", NULL);
1593
Ted Kremenek211a9c62009-06-15 20:58:58 +00001594 // Create summaries for CIContext, 'createCGImage' and
Ted Kremeneka834fb42009-08-28 19:52:12 +00001595 // 'createCGLayerWithSize'. These objects are CF objects, and are not
1596 // automatically garbage collected.
1597 addInstMethSummary("CIContext", CFAllocSumm,
Ted Kremenek767d6492009-05-20 22:39:57 +00001598 "createCGImage", "fromRect", NULL);
Ted Kremeneka834fb42009-08-28 19:52:12 +00001599 addInstMethSummary("CIContext", CFAllocSumm,
Mike Stump1eb44332009-09-09 15:08:12 +00001600 "createCGImage", "fromRect", "format", "colorSpace", NULL);
Ted Kremeneka834fb42009-08-28 19:52:12 +00001601 addInstMethSummary("CIContext", CFAllocSumm, "createCGLayerWithSize",
Ted Kremenek211a9c62009-06-15 20:58:58 +00001602 "info", NULL);
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001603}
1604
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001605//===----------------------------------------------------------------------===//
Ted Kremenekc887d132009-04-29 18:50:19 +00001606// Error reporting.
1607//===----------------------------------------------------------------------===//
Ted Kremenekc887d132009-04-29 18:50:19 +00001608namespace {
Jordy Roseec9ef852011-08-23 20:55:48 +00001609 typedef llvm::DenseMap<const ExplodedNode *, const RetainSummary *>
1610 SummaryLogTy;
1611
Ted Kremenekc887d132009-04-29 18:50:19 +00001612 //===-------------===//
1613 // Bug Descriptions. //
Mike Stump1eb44332009-09-09 15:08:12 +00001614 //===-------------===//
1615
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001616 class CFRefBug : public BugType {
Ted Kremenekc887d132009-04-29 18:50:19 +00001617 protected:
Stephen Hines651f13c2014-04-23 16:59:28 -07001618 CFRefBug(const CheckerBase *checker, StringRef name)
1619 : BugType(checker, name, categories::MemoryCoreFoundationObjectiveC) {}
1620
Ted Kremenekc887d132009-04-29 18:50:19 +00001621 public:
Mike Stump1eb44332009-09-09 15:08:12 +00001622
Ted Kremenekc887d132009-04-29 18:50:19 +00001623 // FIXME: Eventually remove.
Jordy Rose35c86952011-08-24 05:47:39 +00001624 virtual const char *getDescription() const = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001625
Ted Kremenekc887d132009-04-29 18:50:19 +00001626 virtual bool isLeak() const { return false; }
1627 };
Mike Stump1eb44332009-09-09 15:08:12 +00001628
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001629 class UseAfterRelease : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001630 public:
Stephen Hines651f13c2014-04-23 16:59:28 -07001631 UseAfterRelease(const CheckerBase *checker)
1632 : CFRefBug(checker, "Use-after-release") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001633
Stephen Hines651f13c2014-04-23 16:59:28 -07001634 const char *getDescription() const override {
Ted Kremenekc887d132009-04-29 18:50:19 +00001635 return "Reference-counted object is used after it is released";
Mike Stump1eb44332009-09-09 15:08:12 +00001636 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001637 };
Mike Stump1eb44332009-09-09 15:08:12 +00001638
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001639 class BadRelease : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001640 public:
Stephen Hines651f13c2014-04-23 16:59:28 -07001641 BadRelease(const CheckerBase *checker) : CFRefBug(checker, "Bad release") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001642
Stephen Hines651f13c2014-04-23 16:59:28 -07001643 const char *getDescription() const override {
Ted Kremenekbb206fd2009-10-01 17:31:50 +00001644 return "Incorrect decrement of the reference count of an object that is "
1645 "not owned at this point by the caller";
Ted Kremenekc887d132009-04-29 18:50:19 +00001646 }
1647 };
Mike Stump1eb44332009-09-09 15:08:12 +00001648
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001649 class DeallocGC : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001650 public:
Stephen Hines651f13c2014-04-23 16:59:28 -07001651 DeallocGC(const CheckerBase *checker)
1652 : CFRefBug(checker, "-dealloc called while using garbage collection") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001653
Stephen Hines651f13c2014-04-23 16:59:28 -07001654 const char *getDescription() const override {
Ted Kremenek369de562009-05-09 00:10:05 +00001655 return "-dealloc called while using garbage collection";
Ted Kremenekc887d132009-04-29 18:50:19 +00001656 }
1657 };
Mike Stump1eb44332009-09-09 15:08:12 +00001658
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001659 class DeallocNotOwned : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001660 public:
Stephen Hines651f13c2014-04-23 16:59:28 -07001661 DeallocNotOwned(const CheckerBase *checker)
1662 : CFRefBug(checker, "-dealloc sent to non-exclusively owned object") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001663
Stephen Hines651f13c2014-04-23 16:59:28 -07001664 const char *getDescription() const override {
Ted Kremenekc887d132009-04-29 18:50:19 +00001665 return "-dealloc sent to object that may be referenced elsewhere";
1666 }
Mike Stump1eb44332009-09-09 15:08:12 +00001667 };
1668
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001669 class OverAutorelease : public CFRefBug {
Ted Kremenek369de562009-05-09 00:10:05 +00001670 public:
Stephen Hines651f13c2014-04-23 16:59:28 -07001671 OverAutorelease(const CheckerBase *checker)
1672 : CFRefBug(checker, "Object autoreleased too many times") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001673
Stephen Hines651f13c2014-04-23 16:59:28 -07001674 const char *getDescription() const override {
Jordan Rose2545b1d2013-04-23 01:42:25 +00001675 return "Object autoreleased too many times";
Ted Kremenek369de562009-05-09 00:10:05 +00001676 }
1677 };
Mike Stump1eb44332009-09-09 15:08:12 +00001678
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001679 class ReturnedNotOwnedForOwned : public CFRefBug {
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001680 public:
Stephen Hines651f13c2014-04-23 16:59:28 -07001681 ReturnedNotOwnedForOwned(const CheckerBase *checker)
1682 : CFRefBug(checker, "Method should return an owned object") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001683
Stephen Hines651f13c2014-04-23 16:59:28 -07001684 const char *getDescription() const override {
Jordy Rose5b5402b2011-07-15 22:17:54 +00001685 return "Object with a +0 retain count returned to caller where a +1 "
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001686 "(owning) retain count is expected";
1687 }
1688 };
Mike Stump1eb44332009-09-09 15:08:12 +00001689
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001690 class Leak : public CFRefBug {
Benjamin Kramerfacde172012-06-06 17:32:50 +00001691 public:
Stephen Hines651f13c2014-04-23 16:59:28 -07001692 Leak(const CheckerBase *checker, StringRef name) : CFRefBug(checker, name) {
Jordy Rosedb92bb62011-08-25 01:14:38 +00001693 // Leaks should not be reported if they are post-dominated by a sink.
1694 setSuppressOnSink(true);
1695 }
Mike Stump1eb44332009-09-09 15:08:12 +00001696
Stephen Hines651f13c2014-04-23 16:59:28 -07001697 const char *getDescription() const override { return ""; }
Mike Stump1eb44332009-09-09 15:08:12 +00001698
Stephen Hines651f13c2014-04-23 16:59:28 -07001699 bool isLeak() const override { return true; }
Ted Kremenekc887d132009-04-29 18:50:19 +00001700 };
Mike Stump1eb44332009-09-09 15:08:12 +00001701
Ted Kremenekc887d132009-04-29 18:50:19 +00001702 //===---------===//
1703 // Bug Reports. //
1704 //===---------===//
Mike Stump1eb44332009-09-09 15:08:12 +00001705
Jordy Rose01153492012-03-24 02:45:35 +00001706 class CFRefReportVisitor : public BugReporterVisitorImpl<CFRefReportVisitor> {
Anna Zaks23f395e2011-08-20 01:27:22 +00001707 protected:
Anna Zaksdc757b02011-08-19 23:21:56 +00001708 SymbolRef Sym;
Jordy Roseec9ef852011-08-23 20:55:48 +00001709 const SummaryLogTy &SummaryLog;
Jordy Rose35c86952011-08-24 05:47:39 +00001710 bool GCEnabled;
Anna Zaks23f395e2011-08-20 01:27:22 +00001711
Anna Zaksdc757b02011-08-19 23:21:56 +00001712 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001713 CFRefReportVisitor(SymbolRef sym, bool gcEnabled, const SummaryLogTy &log)
1714 : Sym(sym), SummaryLog(log), GCEnabled(gcEnabled) {}
Anna Zaksdc757b02011-08-19 23:21:56 +00001715
Stephen Hines651f13c2014-04-23 16:59:28 -07001716 void Profile(llvm::FoldingSetNodeID &ID) const override {
Anna Zaksdc757b02011-08-19 23:21:56 +00001717 static int x = 0;
1718 ID.AddPointer(&x);
1719 ID.AddPointer(Sym);
1720 }
1721
Stephen Hines651f13c2014-04-23 16:59:28 -07001722 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
1723 const ExplodedNode *PrevN,
1724 BugReporterContext &BRC,
1725 BugReport &BR) override;
Anna Zaks23f395e2011-08-20 01:27:22 +00001726
Stephen Hines651f13c2014-04-23 16:59:28 -07001727 PathDiagnosticPiece *getEndPath(BugReporterContext &BRC,
1728 const ExplodedNode *N,
1729 BugReport &BR) override;
Anna Zaks23f395e2011-08-20 01:27:22 +00001730 };
1731
1732 class CFRefLeakReportVisitor : public CFRefReportVisitor {
1733 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001734 CFRefLeakReportVisitor(SymbolRef sym, bool GCEnabled,
Jordy Roseec9ef852011-08-23 20:55:48 +00001735 const SummaryLogTy &log)
Jordy Rose35c86952011-08-24 05:47:39 +00001736 : CFRefReportVisitor(sym, GCEnabled, log) {}
Anna Zaks23f395e2011-08-20 01:27:22 +00001737
1738 PathDiagnosticPiece *getEndPath(BugReporterContext &BRC,
1739 const ExplodedNode *N,
Stephen Hines651f13c2014-04-23 16:59:28 -07001740 BugReport &BR) override;
Jordy Rose01153492012-03-24 02:45:35 +00001741
Stephen Hines651f13c2014-04-23 16:59:28 -07001742 BugReporterVisitor *clone() const override {
Jordy Rose01153492012-03-24 02:45:35 +00001743 // The curiously-recurring template pattern only works for one level of
1744 // subclassing. Rather than make a new template base for
1745 // CFRefReportVisitor, we simply override clone() to do the right thing.
1746 // This could be trouble someday if BugReporterVisitorImpl is ever
1747 // used for something else besides a convenient implementation of clone().
1748 return new CFRefLeakReportVisitor(*this);
1749 }
Anna Zaksdc757b02011-08-19 23:21:56 +00001750 };
1751
Anna Zakse172e8b2011-08-17 23:00:25 +00001752 class CFRefReport : public BugReport {
Jordy Rose20589562011-08-24 22:39:09 +00001753 void addGCModeDescription(const LangOptions &LOpts, bool GCEnabled);
Jordy Rose35c86952011-08-24 05:47:39 +00001754
Ted Kremenekc887d132009-04-29 18:50:19 +00001755 public:
Jordy Rose20589562011-08-24 22:39:09 +00001756 CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1757 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1758 bool registerVisitor = true)
Anna Zaksedf4dae2011-08-22 18:54:07 +00001759 : BugReport(D, D.getDescription(), n) {
Anna Zaks23f395e2011-08-20 01:27:22 +00001760 if (registerVisitor)
Jordy Rose20589562011-08-24 22:39:09 +00001761 addVisitor(new CFRefReportVisitor(sym, GCEnabled, Log));
1762 addGCModeDescription(LOpts, GCEnabled);
Anna Zaksdc757b02011-08-19 23:21:56 +00001763 }
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001764
Jordy Rose20589562011-08-24 22:39:09 +00001765 CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1766 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1767 StringRef endText)
Anna Zaksedf4dae2011-08-22 18:54:07 +00001768 : BugReport(D, D.getDescription(), endText, n) {
Jordy Rose20589562011-08-24 22:39:09 +00001769 addVisitor(new CFRefReportVisitor(sym, GCEnabled, Log));
1770 addGCModeDescription(LOpts, GCEnabled);
Anna Zaksdc757b02011-08-19 23:21:56 +00001771 }
Mike Stump1eb44332009-09-09 15:08:12 +00001772
Stephen Hines651f13c2014-04-23 16:59:28 -07001773 std::pair<ranges_iterator, ranges_iterator> getRanges() override {
Anna Zaksedf4dae2011-08-22 18:54:07 +00001774 const CFRefBug& BugTy = static_cast<CFRefBug&>(getBugType());
1775 if (!BugTy.isLeak())
Anna Zakse172e8b2011-08-17 23:00:25 +00001776 return BugReport::getRanges();
Ted Kremenekc887d132009-04-29 18:50:19 +00001777 else
Argyrios Kyrtzidis640ccf02010-12-04 01:12:15 +00001778 return std::make_pair(ranges_iterator(), ranges_iterator());
Ted Kremenekc887d132009-04-29 18:50:19 +00001779 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001780 };
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001781
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001782 class CFRefLeakReport : public CFRefReport {
Ted Kremenekc887d132009-04-29 18:50:19 +00001783 const MemRegion* AllocBinding;
1784 public:
Jordy Rose20589562011-08-24 22:39:09 +00001785 CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1786 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
Ted Kremenek08a838d2013-04-16 21:44:22 +00001787 CheckerContext &Ctx,
1788 bool IncludeAllocationLine);
Mike Stump1eb44332009-09-09 15:08:12 +00001789
Stephen Hines651f13c2014-04-23 16:59:28 -07001790 PathDiagnosticLocation getLocation(const SourceManager &SM) const override {
Anna Zaks590dd8e2011-09-20 21:38:35 +00001791 assert(Location.isValid());
1792 return Location;
1793 }
Mike Stump1eb44332009-09-09 15:08:12 +00001794 };
Ted Kremenekc887d132009-04-29 18:50:19 +00001795} // end anonymous namespace
1796
Jordy Rose20589562011-08-24 22:39:09 +00001797void CFRefReport::addGCModeDescription(const LangOptions &LOpts,
1798 bool GCEnabled) {
Jordy Rosef95b19d2011-08-24 20:38:42 +00001799 const char *GCModeDescription = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001800
Douglas Gregore289d812011-09-13 17:21:33 +00001801 switch (LOpts.getGC()) {
Anna Zaks7f2531c2011-08-22 20:31:28 +00001802 case LangOptions::GCOnly:
Jordy Rose20589562011-08-24 22:39:09 +00001803 assert(GCEnabled);
Jordy Rose35c86952011-08-24 05:47:39 +00001804 GCModeDescription = "Code is compiled to only use garbage collection";
1805 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001806
Anna Zaks7f2531c2011-08-22 20:31:28 +00001807 case LangOptions::NonGC:
Jordy Rose20589562011-08-24 22:39:09 +00001808 assert(!GCEnabled);
Jordy Rose35c86952011-08-24 05:47:39 +00001809 GCModeDescription = "Code is compiled to use reference counts";
1810 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001811
Anna Zaks7f2531c2011-08-22 20:31:28 +00001812 case LangOptions::HybridGC:
Jordy Rose20589562011-08-24 22:39:09 +00001813 if (GCEnabled) {
Jordy Rose35c86952011-08-24 05:47:39 +00001814 GCModeDescription = "Code is compiled to use either garbage collection "
1815 "(GC) or reference counts (non-GC). The bug occurs "
1816 "with GC enabled";
1817 break;
1818 } else {
1819 GCModeDescription = "Code is compiled to use either garbage collection "
1820 "(GC) or reference counts (non-GC). The bug occurs "
1821 "in non-GC mode";
1822 break;
Anna Zaks7f2531c2011-08-22 20:31:28 +00001823 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001824 }
Jordy Rose35c86952011-08-24 05:47:39 +00001825
Jordy Rosef95b19d2011-08-24 20:38:42 +00001826 assert(GCModeDescription && "invalid/unknown GC mode");
Jordy Rose35c86952011-08-24 05:47:39 +00001827 addExtraText(GCModeDescription);
Ted Kremenekc887d132009-04-29 18:50:19 +00001828}
1829
Jordy Rose70fdbc32012-05-12 05:10:43 +00001830static bool isNumericLiteralExpression(const Expr *E) {
1831 // FIXME: This set of cases was copied from SemaExprObjC.
1832 return isa<IntegerLiteral>(E) ||
1833 isa<CharacterLiteral>(E) ||
1834 isa<FloatingLiteral>(E) ||
1835 isa<ObjCBoolLiteralExpr>(E) ||
1836 isa<CXXBoolLiteralExpr>(E);
1837}
1838
Anna Zaksdc757b02011-08-19 23:21:56 +00001839PathDiagnosticPiece *CFRefReportVisitor::VisitNode(const ExplodedNode *N,
1840 const ExplodedNode *PrevN,
1841 BugReporterContext &BRC,
1842 BugReport &BR) {
Jordan Rose28038f32012-07-10 22:07:42 +00001843 // FIXME: We will eventually need to handle non-statement-based events
1844 // (__attribute__((cleanup))).
David Blaikie7a95de62013-02-21 22:23:56 +00001845 if (!N->getLocation().getAs<StmtPoint>())
Ted Kremenek2033a952009-05-13 07:12:33 +00001846 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001847
Ted Kremenek8966bc12009-05-06 21:39:49 +00001848 // Check if the type state has changed.
Ted Kremenek8bef8232012-01-26 21:29:00 +00001849 ProgramStateRef PrevSt = PrevN->getState();
1850 ProgramStateRef CurrSt = N->getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001851 const LocationContext *LCtx = N->getLocationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00001852
Anna Zaks8d6b43c2012-08-14 00:36:15 +00001853 const RefVal* CurrT = getRefBinding(CurrSt, Sym);
Ted Kremenekc887d132009-04-29 18:50:19 +00001854 if (!CurrT) return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001855
Ted Kremenekb65be702009-06-18 01:23:53 +00001856 const RefVal &CurrV = *CurrT;
Anna Zaks8d6b43c2012-08-14 00:36:15 +00001857 const RefVal *PrevT = getRefBinding(PrevSt, Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00001858
Ted Kremenekc887d132009-04-29 18:50:19 +00001859 // Create a string buffer to constain all the useful things we want
1860 // to tell the user.
1861 std::string sbuf;
1862 llvm::raw_string_ostream os(sbuf);
Mike Stump1eb44332009-09-09 15:08:12 +00001863
Ted Kremenekc887d132009-04-29 18:50:19 +00001864 // This is the allocation site since the previous node had no bindings
1865 // for this symbol.
1866 if (!PrevT) {
David Blaikie7a95de62013-02-21 22:23:56 +00001867 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
Mike Stump1eb44332009-09-09 15:08:12 +00001868
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001869 if (isa<ObjCArrayLiteral>(S)) {
1870 os << "NSArray literal is an object with a +0 retain count";
Mike Stump1eb44332009-09-09 15:08:12 +00001871 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001872 else if (isa<ObjCDictionaryLiteral>(S)) {
1873 os << "NSDictionary literal is an object with a +0 retain count";
Ted Kremenekc887d132009-04-29 18:50:19 +00001874 }
Jordy Rose70fdbc32012-05-12 05:10:43 +00001875 else if (const ObjCBoxedExpr *BL = dyn_cast<ObjCBoxedExpr>(S)) {
1876 if (isNumericLiteralExpression(BL->getSubExpr()))
1877 os << "NSNumber literal is an object with a +0 retain count";
1878 else {
1879 const ObjCInterfaceDecl *BoxClass = 0;
1880 if (const ObjCMethodDecl *Method = BL->getBoxingMethod())
1881 BoxClass = Method->getClassInterface();
1882
1883 // We should always be able to find the boxing class interface,
1884 // but consider this future-proofing.
1885 if (BoxClass)
1886 os << *BoxClass << " b";
1887 else
1888 os << "B";
1889
1890 os << "oxed expression produces an object with a +0 retain count";
1891 }
1892 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001893 else {
1894 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
1895 // Get the name of the callee (if it is available).
1896 SVal X = CurrSt->getSValAsScalarOrLoc(CE->getCallee(), LCtx);
1897 if (const FunctionDecl *FD = X.getAsFunctionDecl())
1898 os << "Call to function '" << *FD << '\'';
1899 else
1900 os << "function call";
Ted Kremenekc887d132009-04-29 18:50:19 +00001901 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001902 else {
Jordan Rose8919e682012-07-18 21:59:51 +00001903 assert(isa<ObjCMessageExpr>(S));
Jordan Rosed563d3f2012-07-30 20:22:09 +00001904 CallEventManager &Mgr = CurrSt->getStateManager().getCallEventManager();
1905 CallEventRef<ObjCMethodCall> Call
1906 = Mgr.getObjCMethodCall(cast<ObjCMessageExpr>(S), CurrSt, LCtx);
1907
1908 switch (Call->getMessageKind()) {
Jordan Rose8919e682012-07-18 21:59:51 +00001909 case OCM_Message:
1910 os << "Method";
1911 break;
1912 case OCM_PropertyAccess:
1913 os << "Property";
1914 break;
1915 case OCM_Subscript:
1916 os << "Subscript";
1917 break;
1918 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001919 }
1920
1921 if (CurrV.getObjKind() == RetEffect::CF) {
1922 os << " returns a Core Foundation object with a ";
1923 }
1924 else {
1925 assert (CurrV.getObjKind() == RetEffect::ObjC);
1926 os << " returns an Objective-C object with a ";
1927 }
1928
1929 if (CurrV.isOwned()) {
1930 os << "+1 retain count";
1931
1932 if (GCEnabled) {
1933 assert(CurrV.getObjKind() == RetEffect::CF);
1934 os << ". "
1935 "Core Foundation objects are not automatically garbage collected.";
1936 }
1937 }
1938 else {
1939 assert (CurrV.isNotOwned());
1940 os << "+0 retain count";
1941 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001942 }
Mike Stump1eb44332009-09-09 15:08:12 +00001943
Anna Zaks220ac8c2011-09-15 01:08:34 +00001944 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
1945 N->getLocationContext());
Ted Kremenekc887d132009-04-29 18:50:19 +00001946 return new PathDiagnosticEventPiece(Pos, os.str());
1947 }
Mike Stump1eb44332009-09-09 15:08:12 +00001948
Ted Kremenekc887d132009-04-29 18:50:19 +00001949 // Gather up the effects that were performed on the object at this
1950 // program point
Chris Lattner5f9e2722011-07-23 10:55:15 +00001951 SmallVector<ArgEffect, 2> AEffects;
Mike Stump1eb44332009-09-09 15:08:12 +00001952
Jordy Roseec9ef852011-08-23 20:55:48 +00001953 const ExplodedNode *OrigNode = BRC.getNodeResolver().getOriginalNode(N);
1954 if (const RetainSummary *Summ = SummaryLog.lookup(OrigNode)) {
Ted Kremenekc887d132009-04-29 18:50:19 +00001955 // We only have summaries attached to nodes after evaluating CallExpr and
1956 // ObjCMessageExprs.
David Blaikie7a95de62013-02-21 22:23:56 +00001957 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
Mike Stump1eb44332009-09-09 15:08:12 +00001958
Ted Kremenek5f85e172009-07-22 22:35:28 +00001959 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
Ted Kremenekc887d132009-04-29 18:50:19 +00001960 // Iterate through the parameter expressions and see if the symbol
1961 // was ever passed as an argument.
1962 unsigned i = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001963
Ted Kremenek5f85e172009-07-22 22:35:28 +00001964 for (CallExpr::const_arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
Ted Kremenekc887d132009-04-29 18:50:19 +00001965 AI!=AE; ++AI, ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00001966
Ted Kremenekc887d132009-04-29 18:50:19 +00001967 // Retrieve the value of the argument. Is it the symbol
1968 // we are interested in?
Ted Kremenek5eca4822012-01-06 22:09:28 +00001969 if (CurrSt->getSValAsScalarOrLoc(*AI, LCtx).getAsLocSymbol() != Sym)
Ted Kremenekc887d132009-04-29 18:50:19 +00001970 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001971
Ted Kremenekc887d132009-04-29 18:50:19 +00001972 // We have an argument. Get the effect!
1973 AEffects.push_back(Summ->getArg(i));
1974 }
1975 }
Mike Stump1eb44332009-09-09 15:08:12 +00001976 else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00001977 if (const Expr *receiver = ME->getInstanceReceiver())
Ted Kremenek5eca4822012-01-06 22:09:28 +00001978 if (CurrSt->getSValAsScalarOrLoc(receiver, LCtx)
1979 .getAsLocSymbol() == Sym) {
Ted Kremenekc887d132009-04-29 18:50:19 +00001980 // The symbol we are tracking is the receiver.
1981 AEffects.push_back(Summ->getReceiverEffect());
1982 }
1983 }
1984 }
Mike Stump1eb44332009-09-09 15:08:12 +00001985
Ted Kremenekc887d132009-04-29 18:50:19 +00001986 do {
1987 // Get the previous type state.
1988 RefVal PrevV = *PrevT;
Mike Stump1eb44332009-09-09 15:08:12 +00001989
Ted Kremenekc887d132009-04-29 18:50:19 +00001990 // Specially handle -dealloc.
Benjamin Kramera1da6b22013-08-16 21:57:14 +00001991 if (!GCEnabled && std::find(AEffects.begin(), AEffects.end(), Dealloc) !=
1992 AEffects.end()) {
Ted Kremenekc887d132009-04-29 18:50:19 +00001993 // Determine if the object's reference count was pushed to zero.
Stephen Hines651f13c2014-04-23 16:59:28 -07001994 assert(!PrevV.hasSameState(CurrV) && "The state should have changed.");
Ted Kremenekc887d132009-04-29 18:50:19 +00001995 // We may not have transitioned to 'release' if we hit an error.
1996 // This case is handled elsewhere.
1997 if (CurrV.getKind() == RefVal::Released) {
Ted Kremenekf21332e2009-05-08 20:01:42 +00001998 assert(CurrV.getCombinedCounts() == 0);
Ted Kremenekc887d132009-04-29 18:50:19 +00001999 os << "Object released by directly sending the '-dealloc' message";
2000 break;
2001 }
2002 }
Mike Stump1eb44332009-09-09 15:08:12 +00002003
Ted Kremenekc887d132009-04-29 18:50:19 +00002004 // Specially handle CFMakeCollectable and friends.
Benjamin Kramera1da6b22013-08-16 21:57:14 +00002005 if (std::find(AEffects.begin(), AEffects.end(), MakeCollectable) !=
2006 AEffects.end()) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002007 // Get the name of the function.
David Blaikie7a95de62013-02-21 22:23:56 +00002008 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
Ted Kremenek5eca4822012-01-06 22:09:28 +00002009 SVal X =
2010 CurrSt->getSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee(), LCtx);
Ted Kremenek9c378f72011-08-12 23:37:29 +00002011 const FunctionDecl *FD = X.getAsFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002012
Jordy Rose35c86952011-08-24 05:47:39 +00002013 if (GCEnabled) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002014 // Determine if the object's reference count was pushed to zero.
Stephen Hines651f13c2014-04-23 16:59:28 -07002015 assert(!PrevV.hasSameState(CurrV) && "The state should have changed.");
Mike Stump1eb44332009-09-09 15:08:12 +00002016
Benjamin Kramerb8989f22011-10-14 18:45:37 +00002017 os << "In GC mode a call to '" << *FD
Ted Kremenekc887d132009-04-29 18:50:19 +00002018 << "' decrements an object's retain count and registers the "
2019 "object with the garbage collector. ";
Mike Stump1eb44332009-09-09 15:08:12 +00002020
Ted Kremenekc887d132009-04-29 18:50:19 +00002021 if (CurrV.getKind() == RefVal::Released) {
2022 assert(CurrV.getCount() == 0);
2023 os << "Since it now has a 0 retain count the object can be "
2024 "automatically collected by the garbage collector.";
2025 }
2026 else
2027 os << "An object must have a 0 retain count to be garbage collected. "
2028 "After this call its retain count is +" << CurrV.getCount()
2029 << '.';
2030 }
Mike Stump1eb44332009-09-09 15:08:12 +00002031 else
Benjamin Kramerb8989f22011-10-14 18:45:37 +00002032 os << "When GC is not enabled a call to '" << *FD
Ted Kremenekc887d132009-04-29 18:50:19 +00002033 << "' has no effect on its argument.";
Mike Stump1eb44332009-09-09 15:08:12 +00002034
Ted Kremenekc887d132009-04-29 18:50:19 +00002035 // Nothing more to say.
2036 break;
2037 }
Mike Stump1eb44332009-09-09 15:08:12 +00002038
2039 // Determine if the typestate has changed.
Stephen Hines651f13c2014-04-23 16:59:28 -07002040 if (!PrevV.hasSameState(CurrV))
Ted Kremenekc887d132009-04-29 18:50:19 +00002041 switch (CurrV.getKind()) {
2042 case RefVal::Owned:
2043 case RefVal::NotOwned:
Mike Stump1eb44332009-09-09 15:08:12 +00002044
Ted Kremenekf21332e2009-05-08 20:01:42 +00002045 if (PrevV.getCount() == CurrV.getCount()) {
2046 // Did an autorelease message get sent?
2047 if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
2048 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002049
Zhongxing Xu264e9372009-05-12 10:10:00 +00002050 assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount());
Jordan Rose2545b1d2013-04-23 01:42:25 +00002051 os << "Object autoreleased";
Ted Kremenekf21332e2009-05-08 20:01:42 +00002052 break;
2053 }
Mike Stump1eb44332009-09-09 15:08:12 +00002054
Ted Kremenekc887d132009-04-29 18:50:19 +00002055 if (PrevV.getCount() > CurrV.getCount())
2056 os << "Reference count decremented.";
2057 else
2058 os << "Reference count incremented.";
Mike Stump1eb44332009-09-09 15:08:12 +00002059
Ted Kremenekc887d132009-04-29 18:50:19 +00002060 if (unsigned Count = CurrV.getCount())
2061 os << " The object now has a +" << Count << " retain count.";
Mike Stump1eb44332009-09-09 15:08:12 +00002062
Ted Kremenekc887d132009-04-29 18:50:19 +00002063 if (PrevV.getKind() == RefVal::Released) {
Jordy Rose35c86952011-08-24 05:47:39 +00002064 assert(GCEnabled && CurrV.getCount() > 0);
Jordy Rose74b7b2b2012-03-17 05:49:15 +00002065 os << " The object is not eligible for garbage collection until "
2066 "the retain count reaches 0 again.";
Ted Kremenekc887d132009-04-29 18:50:19 +00002067 }
Mike Stump1eb44332009-09-09 15:08:12 +00002068
Ted Kremenekc887d132009-04-29 18:50:19 +00002069 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002070
Ted Kremenekc887d132009-04-29 18:50:19 +00002071 case RefVal::Released:
2072 os << "Object released.";
2073 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002074
Ted Kremenekc887d132009-04-29 18:50:19 +00002075 case RefVal::ReturnedOwned:
Jordy Rose74b7b2b2012-03-17 05:49:15 +00002076 // Autoreleases can be applied after marking a node ReturnedOwned.
2077 if (CurrV.getAutoreleaseCount())
2078 return NULL;
2079
2080 os << "Object returned to caller as an owning reference (single "
2081 "retain count transferred to caller)";
Ted Kremenekc887d132009-04-29 18:50:19 +00002082 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002083
Ted Kremenekc887d132009-04-29 18:50:19 +00002084 case RefVal::ReturnedNotOwned:
Ted Kremenekf1365462011-05-26 18:45:44 +00002085 os << "Object returned to caller with a +0 retain count";
Ted Kremenekc887d132009-04-29 18:50:19 +00002086 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002087
Ted Kremenekc887d132009-04-29 18:50:19 +00002088 default:
2089 return NULL;
2090 }
Mike Stump1eb44332009-09-09 15:08:12 +00002091
Ted Kremenekc887d132009-04-29 18:50:19 +00002092 // Emit any remaining diagnostics for the argument effects (if any).
Chris Lattner5f9e2722011-07-23 10:55:15 +00002093 for (SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
Ted Kremenekc887d132009-04-29 18:50:19 +00002094 E=AEffects.end(); I != E; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +00002095
Ted Kremenekc887d132009-04-29 18:50:19 +00002096 // A bunch of things have alternate behavior under GC.
Jordy Rose35c86952011-08-24 05:47:39 +00002097 if (GCEnabled)
Ted Kremenekc887d132009-04-29 18:50:19 +00002098 switch (*I) {
2099 default: break;
2100 case Autorelease:
2101 os << "In GC mode an 'autorelease' has no effect.";
2102 continue;
2103 case IncRefMsg:
2104 os << "In GC mode the 'retain' message has no effect.";
2105 continue;
2106 case DecRefMsg:
2107 os << "In GC mode the 'release' message has no effect.";
2108 continue;
2109 }
2110 }
Mike Stump1eb44332009-09-09 15:08:12 +00002111 } while (0);
2112
Ted Kremenekc887d132009-04-29 18:50:19 +00002113 if (os.str().empty())
2114 return 0; // We have nothing to say!
Ted Kremenek2033a952009-05-13 07:12:33 +00002115
David Blaikie7a95de62013-02-21 22:23:56 +00002116 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
Anna Zaks220ac8c2011-09-15 01:08:34 +00002117 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
2118 N->getLocationContext());
Ted Kremenek9c378f72011-08-12 23:37:29 +00002119 PathDiagnosticPiece *P = new PathDiagnosticEventPiece(Pos, os.str());
Mike Stump1eb44332009-09-09 15:08:12 +00002120
Ted Kremenekc887d132009-04-29 18:50:19 +00002121 // Add the range by scanning the children of the statement for any bindings
2122 // to Sym.
Mike Stump1eb44332009-09-09 15:08:12 +00002123 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
Ted Kremenek5f85e172009-07-22 22:35:28 +00002124 I!=E; ++I)
Ted Kremenek9c378f72011-08-12 23:37:29 +00002125 if (const Expr *Exp = dyn_cast_or_null<Expr>(*I))
Ted Kremenek5eca4822012-01-06 22:09:28 +00002126 if (CurrSt->getSValAsScalarOrLoc(Exp, LCtx).getAsLocSymbol() == Sym) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002127 P->addRange(Exp->getSourceRange());
2128 break;
2129 }
Mike Stump1eb44332009-09-09 15:08:12 +00002130
Ted Kremenekc887d132009-04-29 18:50:19 +00002131 return P;
2132}
2133
Anna Zakse7e01682012-02-28 22:39:22 +00002134// Find the first node in the current function context that referred to the
2135// tracked symbol and the memory location that value was stored to. Note, the
2136// value is only reported if the allocation occurred in the same function as
Anna Zaks7a87e522013-04-10 21:42:06 +00002137// the leak. The function can also return a location context, which should be
2138// treated as interesting.
2139struct AllocationInfo {
2140 const ExplodedNode* N;
Anna Zaksee9043b2013-04-10 22:56:30 +00002141 const MemRegion *R;
Anna Zaks7a87e522013-04-10 21:42:06 +00002142 const LocationContext *InterestingMethodContext;
Anna Zaksee9043b2013-04-10 22:56:30 +00002143 AllocationInfo(const ExplodedNode *InN,
2144 const MemRegion *InR,
Anna Zaks7a87e522013-04-10 21:42:06 +00002145 const LocationContext *InInterestingMethodContext) :
2146 N(InN), R(InR), InterestingMethodContext(InInterestingMethodContext) {}
2147};
2148
2149static AllocationInfo
Ted Kremenek18c66fd2011-08-15 22:09:50 +00002150GetAllocationSite(ProgramStateManager& StateMgr, const ExplodedNode *N,
Ted Kremenekc887d132009-04-29 18:50:19 +00002151 SymbolRef Sym) {
Anna Zaks7a87e522013-04-10 21:42:06 +00002152 const ExplodedNode *AllocationNode = N;
2153 const ExplodedNode *AllocationNodeInCurrentContext = N;
Mike Stump1eb44332009-09-09 15:08:12 +00002154 const MemRegion* FirstBinding = 0;
Anna Zakse7e01682012-02-28 22:39:22 +00002155 const LocationContext *LeakContext = N->getLocationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002156
Anna Zaks7a87e522013-04-10 21:42:06 +00002157 // The location context of the init method called on the leaked object, if
2158 // available.
2159 const LocationContext *InitMethodContext = 0;
2160
Ted Kremenekc887d132009-04-29 18:50:19 +00002161 while (N) {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002162 ProgramStateRef St = N->getState();
Anna Zaks7a87e522013-04-10 21:42:06 +00002163 const LocationContext *NContext = N->getLocationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002164
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002165 if (!getRefBinding(St, Sym))
Ted Kremenekc887d132009-04-29 18:50:19 +00002166 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002167
Anna Zaks27b867e2012-03-21 19:45:01 +00002168 StoreManager::FindUniqueBinding FB(Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002169 StateMgr.iterBindings(St, FB);
Anna Zaks7a87e522013-04-10 21:42:06 +00002170
Anna Zaks27d99dd2013-04-10 21:42:02 +00002171 if (FB) {
2172 const MemRegion *R = FB.getRegion();
Anna Zaks8cf91f72013-04-10 22:56:33 +00002173 const VarRegion *VR = R->getBaseRegion()->getAs<VarRegion>();
Anna Zaks27d99dd2013-04-10 21:42:02 +00002174 // Do not show local variables belonging to a function other than
2175 // where the error is reported.
2176 if (!VR || VR->getStackFrame() == LeakContext->getCurrentStackFrame())
Anna Zaks7a87e522013-04-10 21:42:06 +00002177 FirstBinding = R;
Anna Zaks27d99dd2013-04-10 21:42:02 +00002178 }
Mike Stump1eb44332009-09-09 15:08:12 +00002179
Anna Zaks7a87e522013-04-10 21:42:06 +00002180 // AllocationNode is the last node in which the symbol was tracked.
2181 AllocationNode = N;
2182
2183 // AllocationNodeInCurrentContext, is the last node in the current context
2184 // in which the symbol was tracked.
2185 if (NContext == LeakContext)
2186 AllocationNodeInCurrentContext = N;
2187
Anna Zaksee9043b2013-04-10 22:56:30 +00002188 // Find the last init that was called on the given symbol and store the
2189 // init method's location context.
2190 if (!InitMethodContext)
2191 if (Optional<CallEnter> CEP = N->getLocation().getAs<CallEnter>()) {
2192 const Stmt *CE = CEP->getCallExpr();
Anna Zaks3d8f4622013-04-25 00:41:32 +00002193 if (const ObjCMessageExpr *ME = dyn_cast_or_null<ObjCMessageExpr>(CE)) {
Anna Zaksee9043b2013-04-10 22:56:30 +00002194 const Stmt *RecExpr = ME->getInstanceReceiver();
2195 if (RecExpr) {
2196 SVal RecV = St->getSVal(RecExpr, NContext);
2197 if (ME->getMethodFamily() == OMF_init && RecV.getAsSymbol() == Sym)
2198 InitMethodContext = CEP->getCalleeContext();
2199 }
2200 }
Anna Zaks7a87e522013-04-10 21:42:06 +00002201 }
Anna Zakse7e01682012-02-28 22:39:22 +00002202
Mike Stump1eb44332009-09-09 15:08:12 +00002203 N = N->pred_empty() ? NULL : *(N->pred_begin());
Ted Kremenekc887d132009-04-29 18:50:19 +00002204 }
Mike Stump1eb44332009-09-09 15:08:12 +00002205
Anna Zaks7a87e522013-04-10 21:42:06 +00002206 // If we are reporting a leak of the object that was allocated with alloc,
Anna Zaksee9043b2013-04-10 22:56:30 +00002207 // mark its init method as interesting.
Anna Zaks7a87e522013-04-10 21:42:06 +00002208 const LocationContext *InterestingMethodContext = 0;
2209 if (InitMethodContext) {
2210 const ProgramPoint AllocPP = AllocationNode->getLocation();
2211 if (Optional<StmtPoint> SP = AllocPP.getAs<StmtPoint>())
2212 if (const ObjCMessageExpr *ME = SP->getStmtAs<ObjCMessageExpr>())
2213 if (ME->getMethodFamily() == OMF_alloc)
2214 InterestingMethodContext = InitMethodContext;
2215 }
2216
Anna Zakse7e01682012-02-28 22:39:22 +00002217 // If allocation happened in a function different from the leak node context,
2218 // do not report the binding.
Ted Kremenek5a8fc882012-10-12 22:56:40 +00002219 assert(N && "Could not find allocation node");
Anna Zakse7e01682012-02-28 22:39:22 +00002220 if (N->getLocationContext() != LeakContext) {
2221 FirstBinding = 0;
2222 }
2223
Anna Zaks7a87e522013-04-10 21:42:06 +00002224 return AllocationInfo(AllocationNodeInCurrentContext,
2225 FirstBinding,
2226 InterestingMethodContext);
Ted Kremenekc887d132009-04-29 18:50:19 +00002227}
2228
2229PathDiagnosticPiece*
Anna Zaks23f395e2011-08-20 01:27:22 +00002230CFRefReportVisitor::getEndPath(BugReporterContext &BRC,
2231 const ExplodedNode *EndN,
2232 BugReport &BR) {
Ted Kremenek76aadc32012-03-09 01:13:14 +00002233 BR.markInteresting(Sym);
Anna Zaks23f395e2011-08-20 01:27:22 +00002234 return BugReporterVisitor::getDefaultEndPath(BRC, EndN, BR);
Ted Kremenekc887d132009-04-29 18:50:19 +00002235}
2236
2237PathDiagnosticPiece*
Anna Zaks23f395e2011-08-20 01:27:22 +00002238CFRefLeakReportVisitor::getEndPath(BugReporterContext &BRC,
2239 const ExplodedNode *EndN,
2240 BugReport &BR) {
Mike Stump1eb44332009-09-09 15:08:12 +00002241
Ted Kremenek8966bc12009-05-06 21:39:49 +00002242 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenekc887d132009-04-29 18:50:19 +00002243 // assigned to different variables, etc.
Ted Kremenek76aadc32012-03-09 01:13:14 +00002244 BR.markInteresting(Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002245
Ted Kremenekc887d132009-04-29 18:50:19 +00002246 // We are reporting a leak. Walk up the graph to get to the first node where
2247 // the symbol appeared, and also get the first VarDecl that tracked object
2248 // is stored to.
Anna Zaks7a87e522013-04-10 21:42:06 +00002249 AllocationInfo AllocI =
Ted Kremenekf04dced2009-05-08 23:32:51 +00002250 GetAllocationSite(BRC.getStateManager(), EndN, Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002251
Anna Zaks7a87e522013-04-10 21:42:06 +00002252 const MemRegion* FirstBinding = AllocI.R;
2253 BR.markInteresting(AllocI.InterestingMethodContext);
2254
Anna Zaks4fdf97b2011-09-15 18:56:07 +00002255 SourceManager& SM = BRC.getSourceManager();
Mike Stump1eb44332009-09-09 15:08:12 +00002256
Ted Kremenekc887d132009-04-29 18:50:19 +00002257 // Compute an actual location for the leak. Sometimes a leak doesn't
2258 // occur at an actual statement (e.g., transition between blocks; end
2259 // of function) so we need to walk the graph and compute a real location.
Ted Kremenek9c378f72011-08-12 23:37:29 +00002260 const ExplodedNode *LeakN = EndN;
Anna Zaks4fdf97b2011-09-15 18:56:07 +00002261 PathDiagnosticLocation L = PathDiagnosticLocation::createEndOfPath(LeakN, SM);
Mike Stump1eb44332009-09-09 15:08:12 +00002262
Ted Kremenekc887d132009-04-29 18:50:19 +00002263 std::string sbuf;
2264 llvm::raw_string_ostream os(sbuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002265
Ted Kremenekf1365462011-05-26 18:45:44 +00002266 os << "Object leaked: ";
Mike Stump1eb44332009-09-09 15:08:12 +00002267
Ted Kremenekf1365462011-05-26 18:45:44 +00002268 if (FirstBinding) {
2269 os << "object allocated and stored into '"
2270 << FirstBinding->getString() << '\'';
2271 }
2272 else
2273 os << "allocated object";
Mike Stump1eb44332009-09-09 15:08:12 +00002274
Ted Kremenekc887d132009-04-29 18:50:19 +00002275 // Get the retain count.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002276 const RefVal* RV = getRefBinding(EndN->getState(), Sym);
Ted Kremenek5a8fc882012-10-12 22:56:40 +00002277 assert(RV);
Mike Stump1eb44332009-09-09 15:08:12 +00002278
Ted Kremenekc887d132009-04-29 18:50:19 +00002279 if (RV->getKind() == RefVal::ErrorLeakReturned) {
2280 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
Jordy Rose5b5402b2011-07-15 22:17:54 +00002281 // objects. Only "copy", "alloc", "retain" and "new" transfer ownership
Ted Kremenekc887d132009-04-29 18:50:19 +00002282 // to the caller for NS objects.
Ted Kremenekd368d712011-05-25 06:19:45 +00002283 const Decl *D = &EndN->getCodeDecl();
Ted Kremenekec9f36e2012-09-06 23:03:07 +00002284
2285 os << (isa<ObjCMethodDecl>(D) ? " is returned from a method "
2286 : " is returned from a function ");
2287
Stephen Hines651f13c2014-04-23 16:59:28 -07002288 if (D->hasAttr<CFReturnsNotRetainedAttr>())
Ted Kremenekec9f36e2012-09-06 23:03:07 +00002289 os << "that is annotated as CF_RETURNS_NOT_RETAINED";
Stephen Hines651f13c2014-04-23 16:59:28 -07002290 else if (D->hasAttr<NSReturnsNotRetainedAttr>())
Ted Kremenekec9f36e2012-09-06 23:03:07 +00002291 os << "that is annotated as NS_RETURNS_NOT_RETAINED";
Ted Kremenekd368d712011-05-25 06:19:45 +00002292 else {
Ted Kremenekec9f36e2012-09-06 23:03:07 +00002293 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2294 os << "whose name ('" << MD->getSelector().getAsString()
2295 << "') does not start with 'copy', 'mutableCopy', 'alloc' or 'new'."
2296 " This violates the naming convention rules"
2297 " given in the Memory Management Guide for Cocoa";
2298 }
2299 else {
2300 const FunctionDecl *FD = cast<FunctionDecl>(D);
2301 os << "whose name ('" << *FD
2302 << "') does not contain 'Copy' or 'Create'. This violates the naming"
2303 " convention rules given in the Memory Management Guide for Core"
2304 " Foundation";
2305 }
2306 }
Ted Kremenekc887d132009-04-29 18:50:19 +00002307 }
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002308 else if (RV->getKind() == RefVal::ErrorGCLeakReturned) {
David Blaikiee1300142013-02-21 22:37:44 +00002309 const ObjCMethodDecl &MD = cast<ObjCMethodDecl>(EndN->getCodeDecl());
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002310 os << " and returned from method '" << MD.getSelector().getAsString()
Ted Kremenek82f2be52009-05-10 16:52:15 +00002311 << "' is potentially leaked when using garbage collection. Callers "
2312 "of this method do not expect a returned object with a +1 retain "
2313 "count since they expect the object to be managed by the garbage "
2314 "collector";
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002315 }
Ted Kremenekc887d132009-04-29 18:50:19 +00002316 else
Ted Kremenekabf517c2010-10-15 22:50:23 +00002317 os << " is not referenced later in this execution path and has a retain "
Ted Kremenekf1365462011-05-26 18:45:44 +00002318 "count of +" << RV->getCount();
Mike Stump1eb44332009-09-09 15:08:12 +00002319
Ted Kremenekc887d132009-04-29 18:50:19 +00002320 return new PathDiagnosticEventPiece(L, os.str());
2321}
2322
Jordy Rose20589562011-08-24 22:39:09 +00002323CFRefLeakReport::CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts,
2324 bool GCEnabled, const SummaryLogTy &Log,
2325 ExplodedNode *n, SymbolRef sym,
Ted Kremenek08a838d2013-04-16 21:44:22 +00002326 CheckerContext &Ctx,
2327 bool IncludeAllocationLine)
2328 : CFRefReport(D, LOpts, GCEnabled, Log, n, sym, false) {
Mike Stump1eb44332009-09-09 15:08:12 +00002329
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00002330 // Most bug reports are cached at the location where they occurred.
Ted Kremenekc887d132009-04-29 18:50:19 +00002331 // With leaks, we want to unique them by the location where they were
2332 // allocated, and only report a single path. To do this, we need to find
2333 // the allocation site of a piece of tracked memory, which we do via a
2334 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2335 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2336 // that all ancestor nodes that represent the allocation site have the
2337 // same SourceLocation.
Ted Kremenek9c378f72011-08-12 23:37:29 +00002338 const ExplodedNode *AllocNode = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002339
Anna Zaks6a93bd52011-10-25 19:57:11 +00002340 const SourceManager& SMgr = Ctx.getSourceManager();
Anna Zaks590dd8e2011-09-20 21:38:35 +00002341
Anna Zaks7a87e522013-04-10 21:42:06 +00002342 AllocationInfo AllocI =
Anna Zaks6a93bd52011-10-25 19:57:11 +00002343 GetAllocationSite(Ctx.getStateManager(), getErrorNode(), sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002344
Anna Zaks7a87e522013-04-10 21:42:06 +00002345 AllocNode = AllocI.N;
2346 AllocBinding = AllocI.R;
2347 markInteresting(AllocI.InterestingMethodContext);
2348
Ted Kremenekc887d132009-04-29 18:50:19 +00002349 // Get the SourceLocation for the allocation site.
Jordan Rose852aa0d2012-07-10 22:07:52 +00002350 // FIXME: This will crash the analyzer if an allocation comes from an
2351 // implicit call. (Currently there are no such allocations in Cocoa, though.)
2352 const Stmt *AllocStmt;
Ted Kremenekc887d132009-04-29 18:50:19 +00002353 ProgramPoint P = AllocNode->getLocation();
David Blaikie7a95de62013-02-21 22:23:56 +00002354 if (Optional<CallExitEnd> Exit = P.getAs<CallExitEnd>())
Jordan Rose852aa0d2012-07-10 22:07:52 +00002355 AllocStmt = Exit->getCalleeContext()->getCallSite();
2356 else
David Blaikie7a95de62013-02-21 22:23:56 +00002357 AllocStmt = P.castAs<PostStmt>().getStmt();
Jordan Rose852aa0d2012-07-10 22:07:52 +00002358 assert(AllocStmt && "All allocations must come from explicit calls");
Anna Zakse3a813a2013-04-23 23:57:50 +00002359
2360 PathDiagnosticLocation AllocLocation =
2361 PathDiagnosticLocation::createBegin(AllocStmt, SMgr,
2362 AllocNode->getLocationContext());
2363 Location = AllocLocation;
2364
2365 // Set uniqieing info, which will be used for unique the bug reports. The
2366 // leaks should be uniqued on the allocation site.
2367 UniqueingLocation = AllocLocation;
2368 UniqueingDecl = AllocNode->getLocationContext()->getDecl();
2369
Ted Kremenekc887d132009-04-29 18:50:19 +00002370 // Fill in the description of the bug.
2371 Description.clear();
2372 llvm::raw_string_ostream os(Description);
Ted Kremenekdd924e22009-05-02 19:05:19 +00002373 os << "Potential leak ";
Jordy Rose20589562011-08-24 22:39:09 +00002374 if (GCEnabled)
Ted Kremenekdd924e22009-05-02 19:05:19 +00002375 os << "(when using garbage collection) ";
Anna Zaks212000e2012-02-28 21:49:08 +00002376 os << "of an object";
Mike Stump1eb44332009-09-09 15:08:12 +00002377
Ted Kremenek08a838d2013-04-16 21:44:22 +00002378 if (AllocBinding) {
Anna Zaks212000e2012-02-28 21:49:08 +00002379 os << " stored into '" << AllocBinding->getString() << '\'';
Ted Kremenek08a838d2013-04-16 21:44:22 +00002380 if (IncludeAllocationLine) {
2381 FullSourceLoc SL(AllocStmt->getLocStart(), Ctx.getSourceManager());
2382 os << " (allocated on line " << SL.getSpellingLineNumber() << ")";
2383 }
2384 }
Anna Zaksdc757b02011-08-19 23:21:56 +00002385
Jordy Rose20589562011-08-24 22:39:09 +00002386 addVisitor(new CFRefLeakReportVisitor(sym, GCEnabled, Log));
Ted Kremenekc887d132009-04-29 18:50:19 +00002387}
2388
2389//===----------------------------------------------------------------------===//
2390// Main checker logic.
2391//===----------------------------------------------------------------------===//
2392
Ted Kremenekd593eb92009-11-25 22:17:44 +00002393namespace {
Jordy Rose910c4052011-09-02 06:44:22 +00002394class RetainCountChecker
Jordy Rose9c083b72011-08-24 18:56:32 +00002395 : public Checker< check::Bind,
Jordy Rose38f17d62011-08-23 19:01:07 +00002396 check::DeadSymbols,
Jordy Rose9c083b72011-08-24 18:56:32 +00002397 check::EndAnalysis,
Anna Zaks344c77a2013-01-03 00:25:29 +00002398 check::EndFunction,
Jordy Rose67044292011-08-17 21:27:39 +00002399 check::PostStmt<BlockExpr>,
John McCallf85e1932011-06-15 23:02:42 +00002400 check::PostStmt<CastExpr>,
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002401 check::PostStmt<ObjCArrayLiteral>,
2402 check::PostStmt<ObjCDictionaryLiteral>,
Jordy Rose70fdbc32012-05-12 05:10:43 +00002403 check::PostStmt<ObjCBoxedExpr>,
Stephen Hines651f13c2014-04-23 16:59:28 -07002404 check::PostStmt<ObjCIvarRefExpr>,
Jordan Rosefe6a0112012-07-02 19:28:21 +00002405 check::PostCall,
Jordy Rosef53e8c72011-08-23 19:43:16 +00002406 check::PreStmt<ReturnStmt>,
Jordy Rose67044292011-08-17 21:27:39 +00002407 check::RegionChanges,
Jordy Rose76c506f2011-08-21 21:58:18 +00002408 eval::Assume,
2409 eval::Call > {
Stephen Hines651f13c2014-04-23 16:59:28 -07002410 mutable std::unique_ptr<CFRefBug> useAfterRelease, releaseNotOwned;
2411 mutable std::unique_ptr<CFRefBug> deallocGC, deallocNotOwned;
2412 mutable std::unique_ptr<CFRefBug> overAutorelease, returnNotOwnedForOwned;
2413 mutable std::unique_ptr<CFRefBug> leakWithinFunction, leakAtReturn;
2414 mutable std::unique_ptr<CFRefBug> leakWithinFunctionGC, leakAtReturnGC;
Jordy Rose38f17d62011-08-23 19:01:07 +00002415
Stephen Hines651f13c2014-04-23 16:59:28 -07002416 typedef llvm::DenseMap<SymbolRef, const CheckerProgramPointTag *> SymbolTagMap;
Jordy Rose38f17d62011-08-23 19:01:07 +00002417
2418 // This map is only used to ensure proper deletion of any allocated tags.
2419 mutable SymbolTagMap DeadSymbolTags;
2420
Stephen Hines651f13c2014-04-23 16:59:28 -07002421 mutable std::unique_ptr<RetainSummaryManager> Summaries;
2422 mutable std::unique_ptr<RetainSummaryManager> SummariesGC;
Jordy Rose9c083b72011-08-24 18:56:32 +00002423 mutable SummaryLogTy SummaryLog;
2424 mutable bool ShouldResetSummaryLog;
2425
Ted Kremenek08a838d2013-04-16 21:44:22 +00002426 /// Optional setting to indicate if leak reports should include
2427 /// the allocation line.
2428 mutable bool IncludeAllocationLine;
2429
Jordy Rose2f9a66d2011-08-20 21:17:59 +00002430public:
Ted Kremenek08a838d2013-04-16 21:44:22 +00002431 RetainCountChecker(AnalyzerOptions &AO)
2432 : ShouldResetSummaryLog(false),
2433 IncludeAllocationLine(shouldIncludeAllocationSiteInLeakDiagnostics(AO)) {}
Jordy Rose38f17d62011-08-23 19:01:07 +00002434
Jordy Rose910c4052011-09-02 06:44:22 +00002435 virtual ~RetainCountChecker() {
Jordy Rose38f17d62011-08-23 19:01:07 +00002436 DeleteContainerSeconds(DeadSymbolTags);
2437 }
2438
Jordy Rose9c083b72011-08-24 18:56:32 +00002439 void checkEndAnalysis(ExplodedGraph &G, BugReporter &BR,
2440 ExprEngine &Eng) const {
2441 // FIXME: This is a hack to make sure the summary log gets cleared between
2442 // analyses of different code bodies.
2443 //
2444 // Why is this necessary? Because a checker's lifetime is tied to a
2445 // translation unit, but an ExplodedGraph's lifetime is just a code body.
2446 // Once in a blue moon, a new ExplodedNode will have the same address as an
2447 // old one with an associated summary, and the bug report visitor gets very
2448 // confused. (To make things worse, the summary lifetime is currently also
2449 // tied to a code body, so we get a crash instead of incorrect results.)
Jordy Rose1ab51c72011-08-24 09:27:24 +00002450 //
2451 // Why is this a bad solution? Because if the lifetime of the ExplodedGraph
2452 // changes, things will start going wrong again. Really the lifetime of this
2453 // log needs to be tied to either the specific nodes in it or the entire
2454 // ExplodedGraph, not to a specific part of the code being analyzed.
2455 //
Jordy Rose9c083b72011-08-24 18:56:32 +00002456 // (Also, having stateful local data means that the same checker can't be
2457 // used from multiple threads, but a lot of checkers have incorrect
2458 // assumptions about that anyway. So that wasn't a priority at the time of
2459 // this fix.)
Jordy Rose1ab51c72011-08-24 09:27:24 +00002460 //
Jordy Rose9c083b72011-08-24 18:56:32 +00002461 // This happens at the end of analysis, but bug reports are emitted /after/
2462 // this point. So we can't just clear the summary log now. Instead, we mark
2463 // that the next time we access the summary log, it should be cleared.
2464
2465 // If we never reset the summary log during /this/ code body analysis,
2466 // there were no new summaries. There might still have been summaries from
2467 // the /last/ analysis, so clear them out to make sure the bug report
2468 // visitors don't get confused.
2469 if (ShouldResetSummaryLog)
2470 SummaryLog.clear();
2471
2472 ShouldResetSummaryLog = !SummaryLog.empty();
Jordy Rose1ab51c72011-08-24 09:27:24 +00002473 }
2474
Jordy Rose17a38e22011-09-02 05:55:19 +00002475 CFRefBug *getLeakWithinFunctionBug(const LangOptions &LOpts,
2476 bool GCEnabled) const {
2477 if (GCEnabled) {
Jordy Rosedb92bb62011-08-25 01:14:38 +00002478 if (!leakWithinFunctionGC)
Stephen Hines651f13c2014-04-23 16:59:28 -07002479 leakWithinFunctionGC.reset(new Leak(this, "Leak of object when using "
2480 "garbage collection"));
Jordy Rose17a38e22011-09-02 05:55:19 +00002481 return leakWithinFunctionGC.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002482 } else {
2483 if (!leakWithinFunction) {
Douglas Gregore289d812011-09-13 17:21:33 +00002484 if (LOpts.getGC() == LangOptions::HybridGC) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002485 leakWithinFunction.reset(new Leak(this,
2486 "Leak of object when not using "
Benjamin Kramerfacde172012-06-06 17:32:50 +00002487 "garbage collection (GC) in "
2488 "dual GC/non-GC code"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002489 } else {
Stephen Hines651f13c2014-04-23 16:59:28 -07002490 leakWithinFunction.reset(new Leak(this, "Leak"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002491 }
2492 }
Jordy Rose17a38e22011-09-02 05:55:19 +00002493 return leakWithinFunction.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002494 }
2495 }
2496
Jordy Rose17a38e22011-09-02 05:55:19 +00002497 CFRefBug *getLeakAtReturnBug(const LangOptions &LOpts, bool GCEnabled) const {
2498 if (GCEnabled) {
Jordy Rosedb92bb62011-08-25 01:14:38 +00002499 if (!leakAtReturnGC)
Stephen Hines651f13c2014-04-23 16:59:28 -07002500 leakAtReturnGC.reset(new Leak(this,
2501 "Leak of returned object when using "
Benjamin Kramerfacde172012-06-06 17:32:50 +00002502 "garbage collection"));
Jordy Rose17a38e22011-09-02 05:55:19 +00002503 return leakAtReturnGC.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002504 } else {
2505 if (!leakAtReturn) {
Douglas Gregore289d812011-09-13 17:21:33 +00002506 if (LOpts.getGC() == LangOptions::HybridGC) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002507 leakAtReturn.reset(new Leak(this,
2508 "Leak of returned object when not using "
Benjamin Kramerfacde172012-06-06 17:32:50 +00002509 "garbage collection (GC) in dual "
2510 "GC/non-GC code"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002511 } else {
Stephen Hines651f13c2014-04-23 16:59:28 -07002512 leakAtReturn.reset(new Leak(this, "Leak of returned object"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002513 }
2514 }
Jordy Rose17a38e22011-09-02 05:55:19 +00002515 return leakAtReturn.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002516 }
2517 }
2518
Jordy Rose17a38e22011-09-02 05:55:19 +00002519 RetainSummaryManager &getSummaryManager(ASTContext &Ctx,
2520 bool GCEnabled) const {
2521 // FIXME: We don't support ARC being turned on and off during one analysis.
2522 // (nor, for that matter, do we support changing ASTContexts)
David Blaikie4e4d0842012-03-11 07:00:24 +00002523 bool ARCEnabled = (bool)Ctx.getLangOpts().ObjCAutoRefCount;
Jordy Rose17a38e22011-09-02 05:55:19 +00002524 if (GCEnabled) {
2525 if (!SummariesGC)
Jordy Roseb6cfc092011-08-25 00:10:37 +00002526 SummariesGC.reset(new RetainSummaryManager(Ctx, true, ARCEnabled));
Jordy Rose17a38e22011-09-02 05:55:19 +00002527 else
2528 assert(SummariesGC->isARCEnabled() == ARCEnabled);
Jordy Roseb6cfc092011-08-25 00:10:37 +00002529 return *SummariesGC;
2530 } else {
Jordy Rose17a38e22011-09-02 05:55:19 +00002531 if (!Summaries)
Jordy Roseb6cfc092011-08-25 00:10:37 +00002532 Summaries.reset(new RetainSummaryManager(Ctx, false, ARCEnabled));
Jordy Rose17a38e22011-09-02 05:55:19 +00002533 else
2534 assert(Summaries->isARCEnabled() == ARCEnabled);
Jordy Roseb6cfc092011-08-25 00:10:37 +00002535 return *Summaries;
2536 }
2537 }
2538
Jordy Rose17a38e22011-09-02 05:55:19 +00002539 RetainSummaryManager &getSummaryManager(CheckerContext &C) const {
2540 return getSummaryManager(C.getASTContext(), C.isObjCGCEnabled());
2541 }
2542
Ted Kremenek8bef8232012-01-26 21:29:00 +00002543 void printState(raw_ostream &Out, ProgramStateRef State,
Stephen Hines651f13c2014-04-23 16:59:28 -07002544 const char *NL, const char *Sep) const override;
Jordy Rosedbd658e2011-08-28 19:11:56 +00002545
Anna Zaks390909c2011-10-06 00:43:15 +00002546 void checkBind(SVal loc, SVal val, const Stmt *S, CheckerContext &C) const;
Jordy Roseab027fd2011-08-20 21:16:58 +00002547 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
2548 void checkPostStmt(const CastExpr *CE, CheckerContext &C) const;
John McCallf85e1932011-06-15 23:02:42 +00002549
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002550 void checkPostStmt(const ObjCArrayLiteral *AL, CheckerContext &C) const;
2551 void checkPostStmt(const ObjCDictionaryLiteral *DL, CheckerContext &C) const;
Jordy Rose70fdbc32012-05-12 05:10:43 +00002552 void checkPostStmt(const ObjCBoxedExpr *BE, CheckerContext &C) const;
2553
Stephen Hines651f13c2014-04-23 16:59:28 -07002554 void checkPostStmt(const ObjCIvarRefExpr *IRE, CheckerContext &C) const;
2555
Jordan Rosefe6a0112012-07-02 19:28:21 +00002556 void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002557
Jordan Rose4531b7d2012-07-02 19:27:43 +00002558 void checkSummary(const RetainSummary &Summ, const CallEvent &Call,
Jordy Rosee38dd952011-08-28 05:16:28 +00002559 CheckerContext &C) const;
Jordy Rose294396b2011-08-22 23:48:23 +00002560
Anna Zaks554067f2012-08-29 23:23:43 +00002561 void processSummaryOfInlined(const RetainSummary &Summ,
2562 const CallEvent &Call,
2563 CheckerContext &C) const;
2564
Jordy Rose76c506f2011-08-21 21:58:18 +00002565 bool evalCall(const CallExpr *CE, CheckerContext &C) const;
2566
Ted Kremenek8bef8232012-01-26 21:29:00 +00002567 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Jordy Roseab027fd2011-08-20 21:16:58 +00002568 bool Assumption) const;
Jordy Rose67044292011-08-17 21:27:39 +00002569
Ted Kremenek8bef8232012-01-26 21:29:00 +00002570 ProgramStateRef
2571 checkRegionChanges(ProgramStateRef state,
Anna Zaksbf53dfa2012-12-20 00:38:25 +00002572 const InvalidatedSymbols *invalidated,
Jordy Rose537716a2011-08-27 22:51:26 +00002573 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00002574 ArrayRef<const MemRegion *> Regions,
Jordan Rose740d4902012-07-02 19:27:35 +00002575 const CallEvent *Call) const;
Jordy Roseab027fd2011-08-20 21:16:58 +00002576
Ted Kremenek8bef8232012-01-26 21:29:00 +00002577 bool wantsRegionChangeUpdate(ProgramStateRef state) const {
Jordy Rose2f9a66d2011-08-20 21:17:59 +00002578 return true;
Jordy Roseab027fd2011-08-20 21:16:58 +00002579 }
Jordy Rose294396b2011-08-22 23:48:23 +00002580
Jordy Rosef53e8c72011-08-23 19:43:16 +00002581 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
2582 void checkReturnWithRetEffect(const ReturnStmt *S, CheckerContext &C,
2583 ExplodedNode *Pred, RetEffect RE, RefVal X,
Ted Kremenek8bef8232012-01-26 21:29:00 +00002584 SymbolRef Sym, ProgramStateRef state) const;
Jordy Rosef53e8c72011-08-23 19:43:16 +00002585
Jordy Rose38f17d62011-08-23 19:01:07 +00002586 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Anna Zaks344c77a2013-01-03 00:25:29 +00002587 void checkEndFunction(CheckerContext &C) const;
Jordy Rose38f17d62011-08-23 19:01:07 +00002588
Ted Kremenek8bef8232012-01-26 21:29:00 +00002589 ProgramStateRef updateSymbol(ProgramStateRef state, SymbolRef sym,
Anna Zaks554067f2012-08-29 23:23:43 +00002590 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
2591 CheckerContext &C) const;
Jordy Rosee0a5d322011-08-23 20:27:16 +00002592
Ted Kremenek8bef8232012-01-26 21:29:00 +00002593 void processNonLeakError(ProgramStateRef St, SourceRange ErrorRange,
Jordy Rose294396b2011-08-22 23:48:23 +00002594 RefVal::Kind ErrorKind, SymbolRef Sym,
2595 CheckerContext &C) const;
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002596
2597 void processObjCLiterals(CheckerContext &C, const Expr *Ex) const;
Jordy Rose294396b2011-08-22 23:48:23 +00002598
Jordy Rose38f17d62011-08-23 19:01:07 +00002599 const ProgramPointTag *getDeadSymbolTag(SymbolRef sym) const;
2600
Ted Kremenek8bef8232012-01-26 21:29:00 +00002601 ProgramStateRef handleSymbolDeath(ProgramStateRef state,
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002602 SymbolRef sid, RefVal V,
2603 SmallVectorImpl<SymbolRef> &Leaked) const;
Jordy Rose38f17d62011-08-23 19:01:07 +00002604
Jordan Rose4ee1c552012-12-06 18:58:18 +00002605 ProgramStateRef
Jordan Rose2bce86c2012-08-18 00:30:16 +00002606 handleAutoreleaseCounts(ProgramStateRef state, ExplodedNode *Pred,
2607 const ProgramPointTag *Tag, CheckerContext &Ctx,
2608 SymbolRef Sym, RefVal V) const;
Jordy Rose8d228632011-08-23 20:07:14 +00002609
Ted Kremenek8bef8232012-01-26 21:29:00 +00002610 ExplodedNode *processLeaks(ProgramStateRef state,
Jordy Rose38f17d62011-08-23 19:01:07 +00002611 SmallVectorImpl<SymbolRef> &Leaked,
Anna Zaks6a93bd52011-10-25 19:57:11 +00002612 CheckerContext &Ctx,
Jordy Rose38f17d62011-08-23 19:01:07 +00002613 ExplodedNode *Pred = 0) const;
Ted Kremenekd593eb92009-11-25 22:17:44 +00002614};
2615} // end anonymous namespace
2616
Jordy Rose67044292011-08-17 21:27:39 +00002617namespace {
2618class StopTrackingCallback : public SymbolVisitor {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002619 ProgramStateRef state;
Jordy Rose67044292011-08-17 21:27:39 +00002620public:
Ted Kremenek8bef8232012-01-26 21:29:00 +00002621 StopTrackingCallback(ProgramStateRef st) : state(st) {}
2622 ProgramStateRef getState() const { return state; }
Jordy Rose67044292011-08-17 21:27:39 +00002623
Stephen Hines651f13c2014-04-23 16:59:28 -07002624 bool VisitSymbol(SymbolRef sym) override {
Jordy Rose67044292011-08-17 21:27:39 +00002625 state = state->remove<RefBindings>(sym);
2626 return true;
2627 }
2628};
2629} // end anonymous namespace
2630
Jordy Rose910c4052011-09-02 06:44:22 +00002631//===----------------------------------------------------------------------===//
2632// Handle statements that may have an effect on refcounts.
2633//===----------------------------------------------------------------------===//
Jordy Rose67044292011-08-17 21:27:39 +00002634
Jordy Rose910c4052011-09-02 06:44:22 +00002635void RetainCountChecker::checkPostStmt(const BlockExpr *BE,
2636 CheckerContext &C) const {
Jordy Rose67044292011-08-17 21:27:39 +00002637
Jordy Rose910c4052011-09-02 06:44:22 +00002638 // Scan the BlockDecRefExprs for any object the retain count checker
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002639 // may be tracking.
John McCall469a1eb2011-02-02 13:00:07 +00002640 if (!BE->getBlockDecl()->hasCaptures())
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002641 return;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002642
Ted Kremenek8bef8232012-01-26 21:29:00 +00002643 ProgramStateRef state = C.getState();
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002644 const BlockDataRegion *R =
Ted Kremenek5eca4822012-01-06 22:09:28 +00002645 cast<BlockDataRegion>(state->getSVal(BE,
2646 C.getLocationContext()).getAsRegion());
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002647
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002648 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
2649 E = R->referenced_vars_end();
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002650
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002651 if (I == E)
2652 return;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002653
Ted Kremenek67d12872009-12-07 22:05:27 +00002654 // FIXME: For now we invalidate the tracking of all symbols passed to blocks
2655 // via captured variables, even though captured variables result in a copy
2656 // and in implicit increment/decrement of a retain count.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002657 SmallVector<const MemRegion*, 10> Regions;
Anna Zaks39ac1872011-10-26 21:06:44 +00002658 const LocationContext *LC = C.getLocationContext();
Ted Kremenekc8413fd2010-12-02 07:49:45 +00002659 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002660
Ted Kremenek67d12872009-12-07 22:05:27 +00002661 for ( ; I != E; ++I) {
Ted Kremeneke3ce2c12012-12-06 07:17:20 +00002662 const VarRegion *VR = I.getCapturedRegion();
Ted Kremenek67d12872009-12-07 22:05:27 +00002663 if (VR->getSuperRegion() == R) {
2664 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2665 }
2666 Regions.push_back(VR);
2667 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002668
Ted Kremenek67d12872009-12-07 22:05:27 +00002669 state =
2670 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
2671 Regions.data() + Regions.size()).getState();
Anna Zaks0bd6b112011-10-26 21:06:34 +00002672 C.addTransition(state);
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002673}
2674
Jordy Rose910c4052011-09-02 06:44:22 +00002675void RetainCountChecker::checkPostStmt(const CastExpr *CE,
2676 CheckerContext &C) const {
John McCallf85e1932011-06-15 23:02:42 +00002677 const ObjCBridgedCastExpr *BE = dyn_cast<ObjCBridgedCastExpr>(CE);
2678 if (!BE)
2679 return;
2680
John McCall71c482c2011-06-17 06:50:50 +00002681 ArgEffect AE = IncRef;
John McCallf85e1932011-06-15 23:02:42 +00002682
2683 switch (BE->getBridgeKind()) {
2684 case clang::OBC_Bridge:
2685 // Do nothing.
2686 return;
2687 case clang::OBC_BridgeRetained:
2688 AE = IncRef;
2689 break;
2690 case clang::OBC_BridgeTransfer:
Benjamin Kramerd29849e2013-10-20 11:53:20 +00002691 AE = DecRefBridgedTransferred;
John McCallf85e1932011-06-15 23:02:42 +00002692 break;
2693 }
2694
Ted Kremenek8bef8232012-01-26 21:29:00 +00002695 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00002696 SymbolRef Sym = state->getSVal(CE, C.getLocationContext()).getAsLocSymbol();
John McCallf85e1932011-06-15 23:02:42 +00002697 if (!Sym)
2698 return;
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002699 const RefVal* T = getRefBinding(state, Sym);
John McCallf85e1932011-06-15 23:02:42 +00002700 if (!T)
2701 return;
2702
John McCallf85e1932011-06-15 23:02:42 +00002703 RefVal::Kind hasErr = (RefVal::Kind) 0;
Jordy Rose17a38e22011-09-02 05:55:19 +00002704 state = updateSymbol(state, Sym, *T, AE, hasErr, C);
John McCallf85e1932011-06-15 23:02:42 +00002705
2706 if (hasErr) {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002707 // FIXME: If we get an error during a bridge cast, should we report it?
2708 // Should we assert that there is no error?
John McCallf85e1932011-06-15 23:02:42 +00002709 return;
2710 }
2711
Anna Zaks0bd6b112011-10-26 21:06:34 +00002712 C.addTransition(state);
John McCallf85e1932011-06-15 23:02:42 +00002713}
2714
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002715void RetainCountChecker::processObjCLiterals(CheckerContext &C,
2716 const Expr *Ex) const {
2717 ProgramStateRef state = C.getState();
2718 const ExplodedNode *pred = C.getPredecessor();
2719 for (Stmt::const_child_iterator it = Ex->child_begin(), et = Ex->child_end() ;
2720 it != et ; ++it) {
2721 const Stmt *child = *it;
2722 SVal V = state->getSVal(child, pred->getLocationContext());
2723 if (SymbolRef sym = V.getAsSymbol())
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002724 if (const RefVal* T = getRefBinding(state, sym)) {
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002725 RefVal::Kind hasErr = (RefVal::Kind) 0;
2726 state = updateSymbol(state, sym, *T, MayEscape, hasErr, C);
2727 if (hasErr) {
2728 processNonLeakError(state, child->getSourceRange(), hasErr, sym, C);
2729 return;
2730 }
2731 }
2732 }
2733
2734 // Return the object as autoreleased.
2735 // RetEffect RE = RetEffect::MakeNotOwned(RetEffect::ObjC);
2736 if (SymbolRef sym =
2737 state->getSVal(Ex, pred->getLocationContext()).getAsSymbol()) {
2738 QualType ResultTy = Ex->getType();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002739 state = setRefBinding(state, sym,
2740 RefVal::makeNotOwned(RetEffect::ObjC, ResultTy));
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002741 }
2742
2743 C.addTransition(state);
2744}
2745
2746void RetainCountChecker::checkPostStmt(const ObjCArrayLiteral *AL,
2747 CheckerContext &C) const {
2748 // Apply the 'MayEscape' to all values.
2749 processObjCLiterals(C, AL);
2750}
2751
2752void RetainCountChecker::checkPostStmt(const ObjCDictionaryLiteral *DL,
2753 CheckerContext &C) const {
2754 // Apply the 'MayEscape' to all keys and values.
2755 processObjCLiterals(C, DL);
2756}
2757
Jordy Rose70fdbc32012-05-12 05:10:43 +00002758void RetainCountChecker::checkPostStmt(const ObjCBoxedExpr *Ex,
2759 CheckerContext &C) const {
2760 const ExplodedNode *Pred = C.getPredecessor();
2761 const LocationContext *LCtx = Pred->getLocationContext();
2762 ProgramStateRef State = Pred->getState();
2763
2764 if (SymbolRef Sym = State->getSVal(Ex, LCtx).getAsSymbol()) {
2765 QualType ResultTy = Ex->getType();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002766 State = setRefBinding(State, Sym,
2767 RefVal::makeNotOwned(RetEffect::ObjC, ResultTy));
Jordy Rose70fdbc32012-05-12 05:10:43 +00002768 }
2769
2770 C.addTransition(State);
2771}
2772
Stephen Hines651f13c2014-04-23 16:59:28 -07002773void RetainCountChecker::checkPostStmt(const ObjCIvarRefExpr *IRE,
2774 CheckerContext &C) const {
2775 ProgramStateRef State = C.getState();
2776 // If an instance variable was previously accessed through a property,
2777 // it may have a synthesized refcount of +0. Override right now that we're
2778 // doing direct access.
2779 if (Optional<Loc> IVarLoc = C.getSVal(IRE).getAs<Loc>())
2780 if (SymbolRef Sym = State->getSVal(*IVarLoc).getAsSymbol())
2781 if (const RefVal *RV = getRefBinding(State, Sym))
2782 if (RV->isOverridable())
2783 State = removeRefBinding(State, Sym);
2784 C.addTransition(State);
2785}
2786
Jordan Rosefe6a0112012-07-02 19:28:21 +00002787void RetainCountChecker::checkPostCall(const CallEvent &Call,
2788 CheckerContext &C) const {
Jordan Rosefe6a0112012-07-02 19:28:21 +00002789 RetainSummaryManager &Summaries = getSummaryManager(C);
2790 const RetainSummary *Summ = Summaries.getSummary(Call, C.getState());
Anna Zaks554067f2012-08-29 23:23:43 +00002791
2792 if (C.wasInlined) {
2793 processSummaryOfInlined(*Summ, Call, C);
2794 return;
2795 }
Jordan Rosefe6a0112012-07-02 19:28:21 +00002796 checkSummary(*Summ, Call, C);
Jordy Rose294396b2011-08-22 23:48:23 +00002797}
2798
Jordy Rose910c4052011-09-02 06:44:22 +00002799/// GetReturnType - Used to get the return type of a message expression or
2800/// function call with the intention of affixing that type to a tracked symbol.
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +00002801/// While the return type can be queried directly from RetEx, when
Jordy Rose910c4052011-09-02 06:44:22 +00002802/// invoking class methods we augment to the return type to be that of
2803/// a pointer to the class (as opposed it just being id).
2804// FIXME: We may be able to do this with related result types instead.
2805// This function is probably overestimating.
2806static QualType GetReturnType(const Expr *RetE, ASTContext &Ctx) {
2807 QualType RetTy = RetE->getType();
2808 // If RetE is not a message expression just return its type.
2809 // If RetE is a message expression, return its types if it is something
2810 /// more specific than id.
2811 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RetE))
2812 if (const ObjCObjectPointerType *PT = RetTy->getAs<ObjCObjectPointerType>())
2813 if (PT->isObjCQualifiedIdType() || PT->isObjCIdType() ||
2814 PT->isObjCClassType()) {
2815 // At this point we know the return type of the message expression is
2816 // id, id<...>, or Class. If we have an ObjCInterfaceDecl, we know this
2817 // is a call to a class method whose type we can resolve. In such
2818 // cases, promote the return type to XXX* (where XXX is the class).
2819 const ObjCInterfaceDecl *D = ME->getReceiverInterface();
2820 return !D ? RetTy :
2821 Ctx.getObjCObjectPointerType(Ctx.getObjCInterfaceType(D));
2822 }
2823
2824 return RetTy;
2825}
2826
Stephen Hines651f13c2014-04-23 16:59:28 -07002827static bool wasSynthesizedProperty(const ObjCMethodCall *Call,
2828 ExplodedNode *N) {
2829 if (!Call || !Call->getDecl()->isPropertyAccessor())
2830 return false;
2831
2832 CallExitEnd PP = N->getLocation().castAs<CallExitEnd>();
2833 const StackFrameContext *Frame = PP.getCalleeContext();
2834 return Frame->getAnalysisDeclContext()->isBodyAutosynthesized();
2835}
2836
Anna Zaks554067f2012-08-29 23:23:43 +00002837// We don't always get the exact modeling of the function with regards to the
2838// retain count checker even when the function is inlined. For example, we need
2839// to stop tracking the symbols which were marked with StopTrackingHard.
2840void RetainCountChecker::processSummaryOfInlined(const RetainSummary &Summ,
2841 const CallEvent &CallOrMsg,
2842 CheckerContext &C) const {
2843 ProgramStateRef state = C.getState();
2844
2845 // Evaluate the effect of the arguments.
2846 for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
2847 if (Summ.getArg(idx) == StopTrackingHard) {
2848 SVal V = CallOrMsg.getArgSVal(idx);
2849 if (SymbolRef Sym = V.getAsLocSymbol()) {
2850 state = removeRefBinding(state, Sym);
2851 }
2852 }
2853 }
2854
2855 // Evaluate the effect on the message receiver.
2856 const ObjCMethodCall *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg);
2857 if (MsgInvocation) {
2858 if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
2859 if (Summ.getReceiverEffect() == StopTrackingHard) {
2860 state = removeRefBinding(state, Sym);
2861 }
2862 }
2863 }
2864
2865 // Consult the summary for the return value.
2866 RetEffect RE = Summ.getRetEffect();
2867 if (RE.getKind() == RetEffect::NoRetHard) {
Jordan Rose2f3017f2012-11-02 23:49:29 +00002868 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
Anna Zaks554067f2012-08-29 23:23:43 +00002869 if (Sym)
2870 state = removeRefBinding(state, Sym);
Stephen Hines651f13c2014-04-23 16:59:28 -07002871 } else if (RE.getKind() == RetEffect::NotOwnedSymbol) {
2872 if (wasSynthesizedProperty(MsgInvocation, C.getPredecessor())) {
2873 // Believe the summary if we synthesized the body of a property getter
2874 // and the return value is currently untracked. If the corresponding
2875 // instance variable is later accessed directly, however, we're going to
2876 // want to override this state, so that the owning object can perform
2877 // reference counting operations on its own ivars.
2878 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
2879 if (Sym && !getRefBinding(state, Sym))
2880 state = setRefBinding(state, Sym,
2881 RefVal::makeOverridableNotOwned(RE.getObjKind(),
2882 Sym->getType()));
2883 }
Anna Zaks554067f2012-08-29 23:23:43 +00002884 }
2885
2886 C.addTransition(state);
2887}
2888
Jordy Rose910c4052011-09-02 06:44:22 +00002889void RetainCountChecker::checkSummary(const RetainSummary &Summ,
Jordan Rose4531b7d2012-07-02 19:27:43 +00002890 const CallEvent &CallOrMsg,
Jordy Rose910c4052011-09-02 06:44:22 +00002891 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002892 ProgramStateRef state = C.getState();
Jordy Rose294396b2011-08-22 23:48:23 +00002893
2894 // Evaluate the effect of the arguments.
2895 RefVal::Kind hasErr = (RefVal::Kind) 0;
2896 SourceRange ErrorRange;
2897 SymbolRef ErrorSym = 0;
2898
2899 for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
Jordy Rose537716a2011-08-27 22:51:26 +00002900 SVal V = CallOrMsg.getArgSVal(idx);
Jordy Rose294396b2011-08-22 23:48:23 +00002901
2902 if (SymbolRef Sym = V.getAsLocSymbol()) {
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002903 if (const RefVal *T = getRefBinding(state, Sym)) {
Jordy Rose17a38e22011-09-02 05:55:19 +00002904 state = updateSymbol(state, Sym, *T, Summ.getArg(idx), hasErr, C);
Jordy Rose294396b2011-08-22 23:48:23 +00002905 if (hasErr) {
2906 ErrorRange = CallOrMsg.getArgSourceRange(idx);
2907 ErrorSym = Sym;
2908 break;
2909 }
2910 }
2911 }
2912 }
2913
2914 // Evaluate the effect on the message receiver.
2915 bool ReceiverIsTracked = false;
Jordan Rose4531b7d2012-07-02 19:27:43 +00002916 if (!hasErr) {
Jordan Rosecde8cdb2012-07-02 19:27:56 +00002917 const ObjCMethodCall *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg);
Jordan Rose4531b7d2012-07-02 19:27:43 +00002918 if (MsgInvocation) {
2919 if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002920 if (const RefVal *T = getRefBinding(state, Sym)) {
Jordan Rose4531b7d2012-07-02 19:27:43 +00002921 ReceiverIsTracked = true;
2922 state = updateSymbol(state, Sym, *T, Summ.getReceiverEffect(),
Anna Zaks554067f2012-08-29 23:23:43 +00002923 hasErr, C);
Jordan Rose4531b7d2012-07-02 19:27:43 +00002924 if (hasErr) {
Jordan Rose8919e682012-07-18 21:59:51 +00002925 ErrorRange = MsgInvocation->getOriginExpr()->getReceiverRange();
Jordan Rose4531b7d2012-07-02 19:27:43 +00002926 ErrorSym = Sym;
2927 }
Jordy Rose294396b2011-08-22 23:48:23 +00002928 }
2929 }
2930 }
2931 }
2932
2933 // Process any errors.
2934 if (hasErr) {
2935 processNonLeakError(state, ErrorRange, hasErr, ErrorSym, C);
2936 return;
2937 }
2938
2939 // Consult the summary for the return value.
2940 RetEffect RE = Summ.getRetEffect();
2941
2942 if (RE.getKind() == RetEffect::OwnedWhenTrackedReceiver) {
Jordy Roseb6cfc092011-08-25 00:10:37 +00002943 if (ReceiverIsTracked)
Jordy Rose17a38e22011-09-02 05:55:19 +00002944 RE = getSummaryManager(C).getObjAllocRetEffect();
Jordy Roseb6cfc092011-08-25 00:10:37 +00002945 else
Jordy Rose294396b2011-08-22 23:48:23 +00002946 RE = RetEffect::MakeNoRet();
2947 }
2948
2949 switch (RE.getKind()) {
2950 default:
David Blaikie7530c032012-01-17 06:56:22 +00002951 llvm_unreachable("Unhandled RetEffect.");
Jordy Rose294396b2011-08-22 23:48:23 +00002952
2953 case RetEffect::NoRet:
Anna Zaks554067f2012-08-29 23:23:43 +00002954 case RetEffect::NoRetHard:
Jordy Rose294396b2011-08-22 23:48:23 +00002955 // No work necessary.
2956 break;
2957
2958 case RetEffect::OwnedAllocatedSymbol:
2959 case RetEffect::OwnedSymbol: {
Jordan Rose2f3017f2012-11-02 23:49:29 +00002960 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
Jordy Rose294396b2011-08-22 23:48:23 +00002961 if (!Sym)
2962 break;
2963
Jordan Rose4531b7d2012-07-02 19:27:43 +00002964 // Use the result type from the CallEvent as it automatically adjusts
Jordy Rose294396b2011-08-22 23:48:23 +00002965 // for methods/functions that return references.
Jordan Rose4531b7d2012-07-02 19:27:43 +00002966 QualType ResultTy = CallOrMsg.getResultType();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002967 state = setRefBinding(state, Sym, RefVal::makeOwned(RE.getObjKind(),
2968 ResultTy));
Jordy Rose294396b2011-08-22 23:48:23 +00002969
2970 // FIXME: Add a flag to the checker where allocations are assumed to
Anna Zaksc6ba23f2012-08-14 15:39:13 +00002971 // *not* fail.
Jordy Rose294396b2011-08-22 23:48:23 +00002972 break;
2973 }
2974
2975 case RetEffect::GCNotOwnedSymbol:
Jordy Rose294396b2011-08-22 23:48:23 +00002976 case RetEffect::NotOwnedSymbol: {
2977 const Expr *Ex = CallOrMsg.getOriginExpr();
Jordan Rose2f3017f2012-11-02 23:49:29 +00002978 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
Jordy Rose294396b2011-08-22 23:48:23 +00002979 if (!Sym)
2980 break;
Ted Kremenek74616822012-10-12 22:56:45 +00002981 assert(Ex);
Jordy Rose294396b2011-08-22 23:48:23 +00002982 // Use GetReturnType in order to give [NSFoo alloc] the type NSFoo *.
2983 QualType ResultTy = GetReturnType(Ex, C.getASTContext());
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002984 state = setRefBinding(state, Sym, RefVal::makeNotOwned(RE.getObjKind(),
2985 ResultTy));
Jordy Rose294396b2011-08-22 23:48:23 +00002986 break;
2987 }
2988 }
2989
2990 // This check is actually necessary; otherwise the statement builder thinks
2991 // we've hit a previously-found path.
2992 // Normally addTransition takes care of this, but we want the node pointer.
2993 ExplodedNode *NewNode;
2994 if (state == C.getState()) {
2995 NewNode = C.getPredecessor();
2996 } else {
Anna Zaks0bd6b112011-10-26 21:06:34 +00002997 NewNode = C.addTransition(state);
Jordy Rose294396b2011-08-22 23:48:23 +00002998 }
2999
Jordy Rose9c083b72011-08-24 18:56:32 +00003000 // Annotate the node with summary we used.
3001 if (NewNode) {
3002 // FIXME: This is ugly. See checkEndAnalysis for why it's necessary.
3003 if (ShouldResetSummaryLog) {
3004 SummaryLog.clear();
3005 ShouldResetSummaryLog = false;
3006 }
Jordy Roseec9ef852011-08-23 20:55:48 +00003007 SummaryLog[NewNode] = &Summ;
Jordy Rose9c083b72011-08-24 18:56:32 +00003008 }
Jordy Rose294396b2011-08-22 23:48:23 +00003009}
3010
Jordy Rosee0a5d322011-08-23 20:27:16 +00003011
Ted Kremenek8bef8232012-01-26 21:29:00 +00003012ProgramStateRef
3013RetainCountChecker::updateSymbol(ProgramStateRef state, SymbolRef sym,
Jordy Rose910c4052011-09-02 06:44:22 +00003014 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
3015 CheckerContext &C) const {
Jordy Rosee0a5d322011-08-23 20:27:16 +00003016 // In GC mode [... release] and [... retain] do nothing.
Jordy Rose910c4052011-09-02 06:44:22 +00003017 // In ARC mode they shouldn't exist at all, but we just ignore them.
Jordy Rose17a38e22011-09-02 05:55:19 +00003018 bool IgnoreRetainMsg = C.isObjCGCEnabled();
3019 if (!IgnoreRetainMsg)
David Blaikie4e4d0842012-03-11 07:00:24 +00003020 IgnoreRetainMsg = (bool)C.getASTContext().getLangOpts().ObjCAutoRefCount;
Jordy Rose17a38e22011-09-02 05:55:19 +00003021
Jordy Rosee0a5d322011-08-23 20:27:16 +00003022 switch (E) {
Jordan Rose4531b7d2012-07-02 19:27:43 +00003023 default:
3024 break;
3025 case IncRefMsg:
3026 E = IgnoreRetainMsg ? DoNothing : IncRef;
3027 break;
3028 case DecRefMsg:
3029 E = IgnoreRetainMsg ? DoNothing : DecRef;
3030 break;
Anna Zaks554067f2012-08-29 23:23:43 +00003031 case DecRefMsgAndStopTrackingHard:
3032 E = IgnoreRetainMsg ? StopTracking : DecRefAndStopTrackingHard;
Jordan Rose4531b7d2012-07-02 19:27:43 +00003033 break;
3034 case MakeCollectable:
3035 E = C.isObjCGCEnabled() ? DecRef : DoNothing;
3036 break;
Jordy Rosee0a5d322011-08-23 20:27:16 +00003037 }
3038
3039 // Handle all use-after-releases.
Jordy Rose17a38e22011-09-02 05:55:19 +00003040 if (!C.isObjCGCEnabled() && V.getKind() == RefVal::Released) {
Jordy Rosee0a5d322011-08-23 20:27:16 +00003041 V = V ^ RefVal::ErrorUseAfterRelease;
3042 hasErr = V.getKind();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003043 return setRefBinding(state, sym, V);
Jordy Rosee0a5d322011-08-23 20:27:16 +00003044 }
3045
3046 switch (E) {
3047 case DecRefMsg:
3048 case IncRefMsg:
3049 case MakeCollectable:
Anna Zaks554067f2012-08-29 23:23:43 +00003050 case DecRefMsgAndStopTrackingHard:
Jordy Rosee0a5d322011-08-23 20:27:16 +00003051 llvm_unreachable("DecRefMsg/IncRefMsg/MakeCollectable already converted");
Jordy Rosee0a5d322011-08-23 20:27:16 +00003052
3053 case Dealloc:
3054 // Any use of -dealloc in GC is *bad*.
Jordy Rose17a38e22011-09-02 05:55:19 +00003055 if (C.isObjCGCEnabled()) {
Jordy Rosee0a5d322011-08-23 20:27:16 +00003056 V = V ^ RefVal::ErrorDeallocGC;
3057 hasErr = V.getKind();
3058 break;
3059 }
3060
3061 switch (V.getKind()) {
3062 default:
3063 llvm_unreachable("Invalid RefVal state for an explicit dealloc.");
Jordy Rosee0a5d322011-08-23 20:27:16 +00003064 case RefVal::Owned:
3065 // The object immediately transitions to the released state.
3066 V = V ^ RefVal::Released;
3067 V.clearCounts();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003068 return setRefBinding(state, sym, V);
Jordy Rosee0a5d322011-08-23 20:27:16 +00003069 case RefVal::NotOwned:
3070 V = V ^ RefVal::ErrorDeallocNotOwned;
3071 hasErr = V.getKind();
3072 break;
3073 }
3074 break;
3075
Jordy Rosee0a5d322011-08-23 20:27:16 +00003076 case MayEscape:
3077 if (V.getKind() == RefVal::Owned) {
3078 V = V ^ RefVal::NotOwned;
3079 break;
3080 }
3081
3082 // Fall-through.
3083
Jordy Rosee0a5d322011-08-23 20:27:16 +00003084 case DoNothing:
3085 return state;
3086
3087 case Autorelease:
Jordy Rose17a38e22011-09-02 05:55:19 +00003088 if (C.isObjCGCEnabled())
Jordy Rosee0a5d322011-08-23 20:27:16 +00003089 return state;
Jordy Rosee0a5d322011-08-23 20:27:16 +00003090 // Update the autorelease counts.
Jordy Rosee0a5d322011-08-23 20:27:16 +00003091 V = V.autorelease();
3092 break;
3093
3094 case StopTracking:
Anna Zaks554067f2012-08-29 23:23:43 +00003095 case StopTrackingHard:
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003096 return removeRefBinding(state, sym);
Jordy Rosee0a5d322011-08-23 20:27:16 +00003097
3098 case IncRef:
3099 switch (V.getKind()) {
3100 default:
3101 llvm_unreachable("Invalid RefVal state for a retain.");
Jordy Rosee0a5d322011-08-23 20:27:16 +00003102 case RefVal::Owned:
3103 case RefVal::NotOwned:
3104 V = V + 1;
3105 break;
3106 case RefVal::Released:
3107 // Non-GC cases are handled above.
Jordy Rose17a38e22011-09-02 05:55:19 +00003108 assert(C.isObjCGCEnabled());
Jordy Rosee0a5d322011-08-23 20:27:16 +00003109 V = (V ^ RefVal::Owned) + 1;
3110 break;
3111 }
3112 break;
3113
Jordy Rosee0a5d322011-08-23 20:27:16 +00003114 case DecRef:
Benjamin Kramerd29849e2013-10-20 11:53:20 +00003115 case DecRefBridgedTransferred:
Anna Zaks554067f2012-08-29 23:23:43 +00003116 case DecRefAndStopTrackingHard:
Jordy Rosee0a5d322011-08-23 20:27:16 +00003117 switch (V.getKind()) {
3118 default:
3119 // case 'RefVal::Released' handled above.
3120 llvm_unreachable("Invalid RefVal state for a release.");
Jordy Rosee0a5d322011-08-23 20:27:16 +00003121
3122 case RefVal::Owned:
3123 assert(V.getCount() > 0);
3124 if (V.getCount() == 1)
Benjamin Kramerd29849e2013-10-20 11:53:20 +00003125 V = V ^ (E == DecRefBridgedTransferred ? RefVal::NotOwned
3126 : RefVal::Released);
Anna Zaks554067f2012-08-29 23:23:43 +00003127 else if (E == DecRefAndStopTrackingHard)
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003128 return removeRefBinding(state, sym);
Jordan Rose4531b7d2012-07-02 19:27:43 +00003129
Jordy Rosee0a5d322011-08-23 20:27:16 +00003130 V = V - 1;
3131 break;
3132
3133 case RefVal::NotOwned:
Jordan Rose4531b7d2012-07-02 19:27:43 +00003134 if (V.getCount() > 0) {
Anna Zaks554067f2012-08-29 23:23:43 +00003135 if (E == DecRefAndStopTrackingHard)
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003136 return removeRefBinding(state, sym);
Jordy Rosee0a5d322011-08-23 20:27:16 +00003137 V = V - 1;
Jordan Rose4531b7d2012-07-02 19:27:43 +00003138 } else {
Jordy Rosee0a5d322011-08-23 20:27:16 +00003139 V = V ^ RefVal::ErrorReleaseNotOwned;
3140 hasErr = V.getKind();
3141 }
3142 break;
3143
3144 case RefVal::Released:
3145 // Non-GC cases are handled above.
Jordy Rose17a38e22011-09-02 05:55:19 +00003146 assert(C.isObjCGCEnabled());
Jordy Rosee0a5d322011-08-23 20:27:16 +00003147 V = V ^ RefVal::ErrorUseAfterRelease;
3148 hasErr = V.getKind();
3149 break;
3150 }
3151 break;
3152 }
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003153 return setRefBinding(state, sym, V);
Jordy Rosee0a5d322011-08-23 20:27:16 +00003154}
3155
Ted Kremenek8bef8232012-01-26 21:29:00 +00003156void RetainCountChecker::processNonLeakError(ProgramStateRef St,
Jordy Rose910c4052011-09-02 06:44:22 +00003157 SourceRange ErrorRange,
3158 RefVal::Kind ErrorKind,
3159 SymbolRef Sym,
3160 CheckerContext &C) const {
Jordy Rose294396b2011-08-22 23:48:23 +00003161 ExplodedNode *N = C.generateSink(St);
3162 if (!N)
3163 return;
3164
Jordy Rose294396b2011-08-22 23:48:23 +00003165 CFRefBug *BT;
3166 switch (ErrorKind) {
3167 default:
3168 llvm_unreachable("Unhandled error.");
Jordy Rose294396b2011-08-22 23:48:23 +00003169 case RefVal::ErrorUseAfterRelease:
Jordy Rosed6334e12011-08-25 00:34:03 +00003170 if (!useAfterRelease)
Stephen Hines651f13c2014-04-23 16:59:28 -07003171 useAfterRelease.reset(new UseAfterRelease(this));
Jordy Rosed6334e12011-08-25 00:34:03 +00003172 BT = &*useAfterRelease;
Jordy Rose294396b2011-08-22 23:48:23 +00003173 break;
3174 case RefVal::ErrorReleaseNotOwned:
Jordy Rosed6334e12011-08-25 00:34:03 +00003175 if (!releaseNotOwned)
Stephen Hines651f13c2014-04-23 16:59:28 -07003176 releaseNotOwned.reset(new BadRelease(this));
Jordy Rosed6334e12011-08-25 00:34:03 +00003177 BT = &*releaseNotOwned;
Jordy Rose294396b2011-08-22 23:48:23 +00003178 break;
3179 case RefVal::ErrorDeallocGC:
Jordy Rosed6334e12011-08-25 00:34:03 +00003180 if (!deallocGC)
Stephen Hines651f13c2014-04-23 16:59:28 -07003181 deallocGC.reset(new DeallocGC(this));
Jordy Rosed6334e12011-08-25 00:34:03 +00003182 BT = &*deallocGC;
Jordy Rose294396b2011-08-22 23:48:23 +00003183 break;
3184 case RefVal::ErrorDeallocNotOwned:
Jordy Rosed6334e12011-08-25 00:34:03 +00003185 if (!deallocNotOwned)
Stephen Hines651f13c2014-04-23 16:59:28 -07003186 deallocNotOwned.reset(new DeallocNotOwned(this));
Jordy Rosed6334e12011-08-25 00:34:03 +00003187 BT = &*deallocNotOwned;
Jordy Rose294396b2011-08-22 23:48:23 +00003188 break;
3189 }
3190
Jordy Rosed6334e12011-08-25 00:34:03 +00003191 assert(BT);
David Blaikie4e4d0842012-03-11 07:00:24 +00003192 CFRefReport *report = new CFRefReport(*BT, C.getASTContext().getLangOpts(),
Jordy Rose17a38e22011-09-02 05:55:19 +00003193 C.isObjCGCEnabled(), SummaryLog,
3194 N, Sym);
Jordy Rose294396b2011-08-22 23:48:23 +00003195 report->addRange(ErrorRange);
Jordan Rose785950e2012-11-02 01:53:40 +00003196 C.emitReport(report);
Jordy Rose294396b2011-08-22 23:48:23 +00003197}
3198
Jordy Rose910c4052011-09-02 06:44:22 +00003199//===----------------------------------------------------------------------===//
3200// Handle the return values of retain-count-related functions.
3201//===----------------------------------------------------------------------===//
3202
3203bool RetainCountChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
Jordy Rose76c506f2011-08-21 21:58:18 +00003204 // Get the callee. We're only interested in simple C functions.
Ted Kremenek8bef8232012-01-26 21:29:00 +00003205 ProgramStateRef state = C.getState();
Anna Zaksb805c8f2011-12-01 05:57:37 +00003206 const FunctionDecl *FD = C.getCalleeDecl(CE);
Jordy Rose76c506f2011-08-21 21:58:18 +00003207 if (!FD)
3208 return false;
3209
3210 IdentifierInfo *II = FD->getIdentifier();
3211 if (!II)
3212 return false;
3213
3214 // For now, we're only handling the functions that return aliases of their
3215 // arguments: CFRetain and CFMakeCollectable (and their families).
3216 // Eventually we should add other functions we can model entirely,
3217 // such as CFRelease, which don't invalidate their arguments or globals.
3218 if (CE->getNumArgs() != 1)
3219 return false;
3220
3221 // Get the name of the function.
3222 StringRef FName = II->getName();
3223 FName = FName.substr(FName.find_first_not_of('_'));
3224
3225 // See if it's one of the specific functions we know how to eval.
3226 bool canEval = false;
3227
Anna Zaksb805c8f2011-12-01 05:57:37 +00003228 QualType ResultTy = CE->getCallReturnType();
Jordy Rose76c506f2011-08-21 21:58:18 +00003229 if (ResultTy->isObjCIdType()) {
3230 // Handle: id NSMakeCollectable(CFTypeRef)
3231 canEval = II->isStr("NSMakeCollectable");
3232 } else if (ResultTy->isPointerType()) {
3233 // Handle: (CF|CG)Retain
Jordan Rose391165f2013-10-07 17:16:52 +00003234 // CFAutorelease
Jordy Rose76c506f2011-08-21 21:58:18 +00003235 // CFMakeCollectable
3236 // It's okay to be a little sloppy here (CGMakeCollectable doesn't exist).
3237 if (cocoa::isRefType(ResultTy, "CF", FName) ||
3238 cocoa::isRefType(ResultTy, "CG", FName)) {
Jordan Rose391165f2013-10-07 17:16:52 +00003239 canEval = isRetain(FD, FName) || isAutorelease(FD, FName) ||
3240 isMakeCollectable(FD, FName);
Jordy Rose76c506f2011-08-21 21:58:18 +00003241 }
3242 }
3243
3244 if (!canEval)
3245 return false;
3246
3247 // Bind the return value.
Ted Kremenek5eca4822012-01-06 22:09:28 +00003248 const LocationContext *LCtx = C.getLocationContext();
3249 SVal RetVal = state->getSVal(CE->getArg(0), LCtx);
Jordy Rose76c506f2011-08-21 21:58:18 +00003250 if (RetVal.isUnknown()) {
3251 // If the receiver is unknown, conjure a return value.
3252 SValBuilder &SVB = C.getSValBuilder();
Ted Kremenek66c486f2012-08-22 06:26:15 +00003253 RetVal = SVB.conjureSymbolVal(0, CE, LCtx, ResultTy, C.blockCount());
Jordy Rose76c506f2011-08-21 21:58:18 +00003254 }
Ted Kremenek5eca4822012-01-06 22:09:28 +00003255 state = state->BindExpr(CE, LCtx, RetVal, false);
Jordy Rose76c506f2011-08-21 21:58:18 +00003256
Jordy Rose294396b2011-08-22 23:48:23 +00003257 // FIXME: This should not be necessary, but otherwise the argument seems to be
3258 // considered alive during the next statement.
3259 if (const MemRegion *ArgRegion = RetVal.getAsRegion()) {
3260 // Save the refcount status of the argument.
3261 SymbolRef Sym = RetVal.getAsLocSymbol();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003262 const RefVal *Binding = 0;
Jordy Rose294396b2011-08-22 23:48:23 +00003263 if (Sym)
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003264 Binding = getRefBinding(state, Sym);
Jordy Rose76c506f2011-08-21 21:58:18 +00003265
Jordy Rose294396b2011-08-22 23:48:23 +00003266 // Invalidate the argument region.
Anna Zaksbf53dfa2012-12-20 00:38:25 +00003267 state = state->invalidateRegions(ArgRegion, CE, C.blockCount(), LCtx,
Anna Zaks64eb0702013-01-16 01:35:54 +00003268 /*CausesPointerEscape*/ false);
Jordy Rose76c506f2011-08-21 21:58:18 +00003269
Jordy Rose294396b2011-08-22 23:48:23 +00003270 // Restore the refcount status of the argument.
3271 if (Binding)
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003272 state = setRefBinding(state, Sym, *Binding);
Jordy Rose294396b2011-08-22 23:48:23 +00003273 }
3274
Anna Zaks0bd6b112011-10-26 21:06:34 +00003275 C.addTransition(state);
Jordy Rose76c506f2011-08-21 21:58:18 +00003276 return true;
3277}
3278
Jordy Rose910c4052011-09-02 06:44:22 +00003279//===----------------------------------------------------------------------===//
3280// Handle return statements.
3281//===----------------------------------------------------------------------===//
Jordy Rosef53e8c72011-08-23 19:43:16 +00003282
Jordy Rose910c4052011-09-02 06:44:22 +00003283void RetainCountChecker::checkPreStmt(const ReturnStmt *S,
3284 CheckerContext &C) const {
Ted Kremeneke5715782012-02-25 02:09:09 +00003285
3286 // Only adjust the reference count if this is the top-level call frame,
3287 // and not the result of inlining. In the future, we should do
3288 // better checking even for inlined calls, and see if they match
3289 // with their expected semantics (e.g., the method should return a retained
3290 // object, etc.).
Anna Zaksfadcd5d2012-11-03 02:54:16 +00003291 if (!C.inTopFrame())
Ted Kremeneke5715782012-02-25 02:09:09 +00003292 return;
3293
Jordy Rosef53e8c72011-08-23 19:43:16 +00003294 const Expr *RetE = S->getRetValue();
3295 if (!RetE)
3296 return;
3297
Ted Kremenek8bef8232012-01-26 21:29:00 +00003298 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00003299 SymbolRef Sym =
3300 state->getSValAsScalarOrLoc(RetE, C.getLocationContext()).getAsLocSymbol();
Jordy Rosef53e8c72011-08-23 19:43:16 +00003301 if (!Sym)
3302 return;
3303
3304 // Get the reference count binding (if any).
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003305 const RefVal *T = getRefBinding(state, Sym);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003306 if (!T)
3307 return;
3308
3309 // Change the reference count.
3310 RefVal X = *T;
3311
3312 switch (X.getKind()) {
3313 case RefVal::Owned: {
3314 unsigned cnt = X.getCount();
3315 assert(cnt > 0);
3316 X.setCount(cnt - 1);
3317 X = X ^ RefVal::ReturnedOwned;
3318 break;
3319 }
3320
3321 case RefVal::NotOwned: {
3322 unsigned cnt = X.getCount();
3323 if (cnt) {
3324 X.setCount(cnt - 1);
3325 X = X ^ RefVal::ReturnedOwned;
3326 }
3327 else {
3328 X = X ^ RefVal::ReturnedNotOwned;
3329 }
3330 break;
3331 }
3332
3333 default:
3334 return;
3335 }
3336
3337 // Update the binding.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003338 state = setRefBinding(state, Sym, X);
Anna Zaks0bd6b112011-10-26 21:06:34 +00003339 ExplodedNode *Pred = C.addTransition(state);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003340
3341 // At this point we have updated the state properly.
3342 // Everything after this is merely checking to see if the return value has
3343 // been over- or under-retained.
3344
3345 // Did we cache out?
3346 if (!Pred)
3347 return;
3348
Jordy Rosef53e8c72011-08-23 19:43:16 +00003349 // Update the autorelease counts.
Stephen Hines651f13c2014-04-23 16:59:28 -07003350 static CheckerProgramPointTag AutoreleaseTag(this, "Autorelease");
Jordan Rose4ee1c552012-12-06 18:58:18 +00003351 state = handleAutoreleaseCounts(state, Pred, &AutoreleaseTag, C, Sym, X);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003352
3353 // Did we cache out?
Jordan Rose4ee1c552012-12-06 18:58:18 +00003354 if (!state)
Jordy Rosef53e8c72011-08-23 19:43:16 +00003355 return;
3356
3357 // Get the updated binding.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003358 T = getRefBinding(state, Sym);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003359 assert(T);
3360 X = *T;
3361
3362 // Consult the summary of the enclosing method.
Jordy Rose17a38e22011-09-02 05:55:19 +00003363 RetainSummaryManager &Summaries = getSummaryManager(C);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003364 const Decl *CD = &Pred->getCodeDecl();
Jordan Rose4531b7d2012-07-02 19:27:43 +00003365 RetEffect RE = RetEffect::MakeNoRet();
Jordy Rosef53e8c72011-08-23 19:43:16 +00003366
Jordan Rose4531b7d2012-07-02 19:27:43 +00003367 // FIXME: What is the convention for blocks? Is there one?
Jordy Rosef53e8c72011-08-23 19:43:16 +00003368 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CD)) {
Jordy Roseb6cfc092011-08-25 00:10:37 +00003369 const RetainSummary *Summ = Summaries.getMethodSummary(MD);
Jordan Rose4531b7d2012-07-02 19:27:43 +00003370 RE = Summ->getRetEffect();
3371 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) {
3372 if (!isa<CXXMethodDecl>(FD)) {
3373 const RetainSummary *Summ = Summaries.getFunctionSummary(FD);
3374 RE = Summ->getRetEffect();
3375 }
Jordy Rosef53e8c72011-08-23 19:43:16 +00003376 }
3377
Jordan Rose4531b7d2012-07-02 19:27:43 +00003378 checkReturnWithRetEffect(S, C, Pred, RE, X, Sym, state);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003379}
3380
Jordy Rose910c4052011-09-02 06:44:22 +00003381void RetainCountChecker::checkReturnWithRetEffect(const ReturnStmt *S,
3382 CheckerContext &C,
3383 ExplodedNode *Pred,
3384 RetEffect RE, RefVal X,
3385 SymbolRef Sym,
Ted Kremenek8bef8232012-01-26 21:29:00 +00003386 ProgramStateRef state) const {
Jordy Rosef53e8c72011-08-23 19:43:16 +00003387 // Any leaks or other errors?
3388 if (X.isReturnedOwned() && X.getCount() == 0) {
3389 if (RE.getKind() != RetEffect::NoRet) {
3390 bool hasError = false;
Jordy Rose17a38e22011-09-02 05:55:19 +00003391 if (C.isObjCGCEnabled() && RE.getObjKind() == RetEffect::ObjC) {
Jordy Rosef53e8c72011-08-23 19:43:16 +00003392 // Things are more complicated with garbage collection. If the
3393 // returned object is suppose to be an Objective-C object, we have
3394 // a leak (as the caller expects a GC'ed object) because no
3395 // method should return ownership unless it returns a CF object.
3396 hasError = true;
3397 X = X ^ RefVal::ErrorGCLeakReturned;
3398 }
3399 else if (!RE.isOwned()) {
3400 // Either we are using GC and the returned object is a CF type
3401 // or we aren't using GC. In either case, we expect that the
3402 // enclosing method is expected to return ownership.
3403 hasError = true;
3404 X = X ^ RefVal::ErrorLeakReturned;
3405 }
3406
3407 if (hasError) {
3408 // Generate an error node.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003409 state = setRefBinding(state, Sym, X);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003410
Stephen Hines651f13c2014-04-23 16:59:28 -07003411 static CheckerProgramPointTag ReturnOwnLeakTag(this, "ReturnsOwnLeak");
Anna Zaks0bd6b112011-10-26 21:06:34 +00003412 ExplodedNode *N = C.addTransition(state, Pred, &ReturnOwnLeakTag);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003413 if (N) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003414 const LangOptions &LOpts = C.getASTContext().getLangOpts();
Jordy Rose17a38e22011-09-02 05:55:19 +00003415 bool GCEnabled = C.isObjCGCEnabled();
Jordy Rosef53e8c72011-08-23 19:43:16 +00003416 CFRefReport *report =
Jordy Rose17a38e22011-09-02 05:55:19 +00003417 new CFRefLeakReport(*getLeakAtReturnBug(LOpts, GCEnabled),
3418 LOpts, GCEnabled, SummaryLog,
Ted Kremenek08a838d2013-04-16 21:44:22 +00003419 N, Sym, C, IncludeAllocationLine);
3420
Jordan Rose785950e2012-11-02 01:53:40 +00003421 C.emitReport(report);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003422 }
3423 }
3424 }
3425 } else if (X.isReturnedNotOwned()) {
3426 if (RE.isOwned()) {
3427 // Trying to return a not owned object to a caller expecting an
3428 // owned object.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003429 state = setRefBinding(state, Sym, X ^ RefVal::ErrorReturnedNotOwned);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003430
Stephen Hines651f13c2014-04-23 16:59:28 -07003431 static CheckerProgramPointTag ReturnNotOwnedTag(this,
3432 "ReturnNotOwnedForOwned");
Anna Zaks0bd6b112011-10-26 21:06:34 +00003433 ExplodedNode *N = C.addTransition(state, Pred, &ReturnNotOwnedTag);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003434 if (N) {
Jordy Rosed6334e12011-08-25 00:34:03 +00003435 if (!returnNotOwnedForOwned)
Stephen Hines651f13c2014-04-23 16:59:28 -07003436 returnNotOwnedForOwned.reset(new ReturnedNotOwnedForOwned(this));
Jordy Rosed6334e12011-08-25 00:34:03 +00003437
Jordy Rosef53e8c72011-08-23 19:43:16 +00003438 CFRefReport *report =
Jordy Rosed6334e12011-08-25 00:34:03 +00003439 new CFRefReport(*returnNotOwnedForOwned,
David Blaikie4e4d0842012-03-11 07:00:24 +00003440 C.getASTContext().getLangOpts(),
Jordy Rose17a38e22011-09-02 05:55:19 +00003441 C.isObjCGCEnabled(), SummaryLog, N, Sym);
Jordan Rose785950e2012-11-02 01:53:40 +00003442 C.emitReport(report);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003443 }
3444 }
3445 }
3446}
3447
Jordy Rose8d228632011-08-23 20:07:14 +00003448//===----------------------------------------------------------------------===//
Jordy Rose910c4052011-09-02 06:44:22 +00003449// Check various ways a symbol can be invalidated.
3450//===----------------------------------------------------------------------===//
3451
Anna Zaks390909c2011-10-06 00:43:15 +00003452void RetainCountChecker::checkBind(SVal loc, SVal val, const Stmt *S,
Jordy Rose910c4052011-09-02 06:44:22 +00003453 CheckerContext &C) const {
3454 // Are we storing to something that causes the value to "escape"?
3455 bool escapes = true;
3456
3457 // A value escapes in three possible cases (this may change):
3458 //
3459 // (1) we are binding to something that is not a memory region.
3460 // (2) we are binding to a memregion that does not have stack storage
3461 // (3) we are binding to a memregion with stack storage that the store
3462 // does not understand.
Ted Kremenek8bef8232012-01-26 21:29:00 +00003463 ProgramStateRef state = C.getState();
Jordy Rose910c4052011-09-02 06:44:22 +00003464
David Blaikiedc84cd52013-02-20 22:23:23 +00003465 if (Optional<loc::MemRegionVal> regionLoc = loc.getAs<loc::MemRegionVal>()) {
Jordy Rose910c4052011-09-02 06:44:22 +00003466 escapes = !regionLoc->getRegion()->hasStackStorage();
3467
3468 if (!escapes) {
3469 // To test (3), generate a new state with the binding added. If it is
3470 // the same state, then it escapes (since the store cannot represent
3471 // the binding).
Anna Zakse7958da2012-05-02 00:15:40 +00003472 // Do this only if we know that the store is not supposed to generate the
3473 // same state.
3474 SVal StoredVal = state->getSVal(regionLoc->getRegion());
3475 if (StoredVal != val)
3476 escapes = (state == (state->bindLoc(*regionLoc, val)));
Jordy Rose910c4052011-09-02 06:44:22 +00003477 }
Ted Kremenekde5b4fb2012-03-27 01:12:45 +00003478 if (!escapes) {
3479 // Case 4: We do not currently model what happens when a symbol is
3480 // assigned to a struct field, so be conservative here and let the symbol
3481 // go. TODO: This could definitely be improved upon.
3482 escapes = !isa<VarRegion>(regionLoc->getRegion());
3483 }
Jordy Rose910c4052011-09-02 06:44:22 +00003484 }
3485
Anna Zaks73fa2522013-09-17 00:53:28 +00003486 // If we are storing the value into an auto function scope variable annotated
3487 // with (__attribute__((cleanup))), stop tracking the value to avoid leak
3488 // false positives.
3489 if (const VarRegion *LVR = dyn_cast_or_null<VarRegion>(loc.getAsRegion())) {
3490 const VarDecl *VD = LVR->getDecl();
Stephen Hines651f13c2014-04-23 16:59:28 -07003491 if (VD->hasAttr<CleanupAttr>()) {
Anna Zaks73fa2522013-09-17 00:53:28 +00003492 escapes = true;
3493 }
3494 }
3495
Jordy Rose910c4052011-09-02 06:44:22 +00003496 // If our store can represent the binding and we aren't storing to something
3497 // that doesn't have local storage then just return and have the simulation
3498 // state continue as is.
3499 if (!escapes)
3500 return;
3501
3502 // Otherwise, find all symbols referenced by 'val' that we are tracking
3503 // and stop tracking them.
3504 state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
Anna Zaks0bd6b112011-10-26 21:06:34 +00003505 C.addTransition(state);
Jordy Rose910c4052011-09-02 06:44:22 +00003506}
3507
Ted Kremenek8bef8232012-01-26 21:29:00 +00003508ProgramStateRef RetainCountChecker::evalAssume(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003509 SVal Cond,
3510 bool Assumption) const {
3511
3512 // FIXME: We may add to the interface of evalAssume the list of symbols
3513 // whose assumptions have changed. For now we just iterate through the
3514 // bindings and check if any of the tracked symbols are NULL. This isn't
3515 // too bad since the number of symbols we will track in practice are
3516 // probably small and evalAssume is only called at branches and a few
3517 // other places.
Jordan Rose166d5022012-11-02 01:54:06 +00003518 RefBindingsTy B = state->get<RefBindings>();
Jordy Rose910c4052011-09-02 06:44:22 +00003519
3520 if (B.isEmpty())
3521 return state;
3522
3523 bool changed = false;
Jordan Rose166d5022012-11-02 01:54:06 +00003524 RefBindingsTy::Factory &RefBFactory = state->get_context<RefBindings>();
Jordy Rose910c4052011-09-02 06:44:22 +00003525
Jordan Rose166d5022012-11-02 01:54:06 +00003526 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Ted Kremenek47cbd0f2012-09-07 22:31:01 +00003527 // Check if the symbol is null stop tracking the symbol.
Jordan Roseec8d4202012-11-01 00:18:27 +00003528 ConstraintManager &CMgr = state->getConstraintManager();
3529 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
3530 if (AllocFailed.isConstrainedTrue()) {
Jordy Rose910c4052011-09-02 06:44:22 +00003531 changed = true;
3532 B = RefBFactory.remove(B, I.getKey());
3533 }
3534 }
3535
3536 if (changed)
3537 state = state->set<RefBindings>(B);
3538
3539 return state;
3540}
3541
Ted Kremenek8bef8232012-01-26 21:29:00 +00003542ProgramStateRef
3543RetainCountChecker::checkRegionChanges(ProgramStateRef state,
Anna Zaksbf53dfa2012-12-20 00:38:25 +00003544 const InvalidatedSymbols *invalidated,
Jordy Rose910c4052011-09-02 06:44:22 +00003545 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00003546 ArrayRef<const MemRegion *> Regions,
Jordan Rose740d4902012-07-02 19:27:35 +00003547 const CallEvent *Call) const {
Jordy Rose910c4052011-09-02 06:44:22 +00003548 if (!invalidated)
3549 return state;
3550
3551 llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
3552 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
3553 E = ExplicitRegions.end(); I != E; ++I) {
3554 if (const SymbolicRegion *SR = (*I)->StripCasts()->getAs<SymbolicRegion>())
3555 WhitelistedSymbols.insert(SR->getSymbol());
3556 }
3557
Anna Zaksbf53dfa2012-12-20 00:38:25 +00003558 for (InvalidatedSymbols::const_iterator I=invalidated->begin(),
Jordy Rose910c4052011-09-02 06:44:22 +00003559 E = invalidated->end(); I!=E; ++I) {
3560 SymbolRef sym = *I;
3561 if (WhitelistedSymbols.count(sym))
3562 continue;
3563 // Remove any existing reference-count binding.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003564 state = removeRefBinding(state, sym);
Jordy Rose910c4052011-09-02 06:44:22 +00003565 }
3566 return state;
3567}
3568
3569//===----------------------------------------------------------------------===//
Jordy Rose8d228632011-08-23 20:07:14 +00003570// Handle dead symbols and end-of-path.
3571//===----------------------------------------------------------------------===//
3572
Jordan Rose4ee1c552012-12-06 18:58:18 +00003573ProgramStateRef
3574RetainCountChecker::handleAutoreleaseCounts(ProgramStateRef state,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003575 ExplodedNode *Pred,
Jordan Rose2bce86c2012-08-18 00:30:16 +00003576 const ProgramPointTag *Tag,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003577 CheckerContext &Ctx,
Jordy Rose910c4052011-09-02 06:44:22 +00003578 SymbolRef Sym, RefVal V) const {
Jordy Rose8d228632011-08-23 20:07:14 +00003579 unsigned ACnt = V.getAutoreleaseCount();
3580
3581 // No autorelease counts? Nothing to be done.
3582 if (!ACnt)
Jordan Rose4ee1c552012-12-06 18:58:18 +00003583 return state;
Jordy Rose8d228632011-08-23 20:07:14 +00003584
Anna Zaks6a93bd52011-10-25 19:57:11 +00003585 assert(!Ctx.isObjCGCEnabled() && "Autorelease counts in GC mode?");
Jordy Rose8d228632011-08-23 20:07:14 +00003586 unsigned Cnt = V.getCount();
3587
3588 // FIXME: Handle sending 'autorelease' to already released object.
3589
3590 if (V.getKind() == RefVal::ReturnedOwned)
3591 ++Cnt;
3592
3593 if (ACnt <= Cnt) {
3594 if (ACnt == Cnt) {
3595 V.clearCounts();
3596 if (V.getKind() == RefVal::ReturnedOwned)
3597 V = V ^ RefVal::ReturnedNotOwned;
3598 else
3599 V = V ^ RefVal::NotOwned;
3600 } else {
Anna Zaks0217b1d2013-01-31 22:36:17 +00003601 V.setCount(V.getCount() - ACnt);
Jordy Rose8d228632011-08-23 20:07:14 +00003602 V.setAutoreleaseCount(0);
3603 }
Jordan Rose4ee1c552012-12-06 18:58:18 +00003604 return setRefBinding(state, Sym, V);
Jordy Rose8d228632011-08-23 20:07:14 +00003605 }
3606
3607 // Woah! More autorelease counts then retain counts left.
3608 // Emit hard error.
3609 V = V ^ RefVal::ErrorOverAutorelease;
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003610 state = setRefBinding(state, Sym, V);
Jordy Rose8d228632011-08-23 20:07:14 +00003611
Jordan Rosefa06f042012-08-20 18:43:42 +00003612 ExplodedNode *N = Ctx.generateSink(state, Pred, Tag);
Jordan Rose2bce86c2012-08-18 00:30:16 +00003613 if (N) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003614 SmallString<128> sbuf;
Jordy Rose8d228632011-08-23 20:07:14 +00003615 llvm::raw_svector_ostream os(sbuf);
Jordan Rose2545b1d2013-04-23 01:42:25 +00003616 os << "Object was autoreleased ";
Jordy Rose8d228632011-08-23 20:07:14 +00003617 if (V.getAutoreleaseCount() > 1)
Jordan Rose2545b1d2013-04-23 01:42:25 +00003618 os << V.getAutoreleaseCount() << " times but the object ";
3619 else
3620 os << "but ";
3621 os << "has a +" << V.getCount() << " retain count";
Jordy Rose8d228632011-08-23 20:07:14 +00003622
Jordy Rosed6334e12011-08-25 00:34:03 +00003623 if (!overAutorelease)
Stephen Hines651f13c2014-04-23 16:59:28 -07003624 overAutorelease.reset(new OverAutorelease(this));
Jordy Rosed6334e12011-08-25 00:34:03 +00003625
David Blaikie4e4d0842012-03-11 07:00:24 +00003626 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
Jordy Rose8d228632011-08-23 20:07:14 +00003627 CFRefReport *report =
Jordy Rosed6334e12011-08-25 00:34:03 +00003628 new CFRefReport(*overAutorelease, LOpts, /* GCEnabled = */ false,
3629 SummaryLog, N, Sym, os.str());
Jordan Rose785950e2012-11-02 01:53:40 +00003630 Ctx.emitReport(report);
Jordy Rose8d228632011-08-23 20:07:14 +00003631 }
3632
Jordan Rose4ee1c552012-12-06 18:58:18 +00003633 return 0;
Jordy Rose8d228632011-08-23 20:07:14 +00003634}
Jordy Rose38f17d62011-08-23 19:01:07 +00003635
Ted Kremenek8bef8232012-01-26 21:29:00 +00003636ProgramStateRef
3637RetainCountChecker::handleSymbolDeath(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003638 SymbolRef sid, RefVal V,
Jordy Rose38f17d62011-08-23 19:01:07 +00003639 SmallVectorImpl<SymbolRef> &Leaked) const {
Jordy Rose53376122011-08-24 04:48:19 +00003640 bool hasLeak = false;
Jordy Rose38f17d62011-08-23 19:01:07 +00003641 if (V.isOwned())
3642 hasLeak = true;
3643 else if (V.isNotOwned() || V.isReturnedOwned())
3644 hasLeak = (V.getCount() > 0);
3645
3646 if (!hasLeak)
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003647 return removeRefBinding(state, sid);
Jordy Rose38f17d62011-08-23 19:01:07 +00003648
3649 Leaked.push_back(sid);
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003650 return setRefBinding(state, sid, V ^ RefVal::ErrorLeak);
Jordy Rose38f17d62011-08-23 19:01:07 +00003651}
3652
3653ExplodedNode *
Ted Kremenek8bef8232012-01-26 21:29:00 +00003654RetainCountChecker::processLeaks(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003655 SmallVectorImpl<SymbolRef> &Leaked,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003656 CheckerContext &Ctx,
3657 ExplodedNode *Pred) const {
Jordy Rose38f17d62011-08-23 19:01:07 +00003658 // Generate an intermediate node representing the leak point.
Jordan Rose2bce86c2012-08-18 00:30:16 +00003659 ExplodedNode *N = Ctx.addTransition(state, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003660
3661 if (N) {
3662 for (SmallVectorImpl<SymbolRef>::iterator
3663 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3664
David Blaikie4e4d0842012-03-11 07:00:24 +00003665 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
Anna Zaks6a93bd52011-10-25 19:57:11 +00003666 bool GCEnabled = Ctx.isObjCGCEnabled();
Jordy Rose17a38e22011-09-02 05:55:19 +00003667 CFRefBug *BT = Pred ? getLeakWithinFunctionBug(LOpts, GCEnabled)
3668 : getLeakAtReturnBug(LOpts, GCEnabled);
Jordy Rose38f17d62011-08-23 19:01:07 +00003669 assert(BT && "BugType not initialized.");
Jordy Rose20589562011-08-24 22:39:09 +00003670
Jordy Rose17a38e22011-09-02 05:55:19 +00003671 CFRefLeakReport *report = new CFRefLeakReport(*BT, LOpts, GCEnabled,
Ted Kremenek08a838d2013-04-16 21:44:22 +00003672 SummaryLog, N, *I, Ctx,
3673 IncludeAllocationLine);
Jordan Rose785950e2012-11-02 01:53:40 +00003674 Ctx.emitReport(report);
Jordy Rose38f17d62011-08-23 19:01:07 +00003675 }
3676 }
3677
3678 return N;
3679}
3680
Anna Zaks344c77a2013-01-03 00:25:29 +00003681void RetainCountChecker::checkEndFunction(CheckerContext &Ctx) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +00003682 ProgramStateRef state = Ctx.getState();
Jordan Rose166d5022012-11-02 01:54:06 +00003683 RefBindingsTy B = state->get<RefBindings>();
Anna Zaksaf498a22011-10-25 19:56:48 +00003684 ExplodedNode *Pred = Ctx.getPredecessor();
Jordy Rose38f17d62011-08-23 19:01:07 +00003685
Jordan Rosed8188f82013-08-01 22:16:36 +00003686 // Don't process anything within synthesized bodies.
3687 const LocationContext *LCtx = Pred->getLocationContext();
3688 if (LCtx->getAnalysisDeclContext()->isBodyAutosynthesized()) {
3689 assert(LCtx->getParent());
3690 return;
3691 }
3692
Jordan Rose166d5022012-11-02 01:54:06 +00003693 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Jordan Rose4ee1c552012-12-06 18:58:18 +00003694 state = handleAutoreleaseCounts(state, Pred, /*Tag=*/0, Ctx,
3695 I->first, I->second);
Jordy Rose8d228632011-08-23 20:07:14 +00003696 if (!state)
Jordy Rose38f17d62011-08-23 19:01:07 +00003697 return;
3698 }
3699
Ted Kremenek0cf3d472012-02-07 00:24:33 +00003700 // If the current LocationContext has a parent, don't check for leaks.
3701 // We will do that later.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003702 // FIXME: we should instead check for imbalances of the retain/releases,
Ted Kremenek0cf3d472012-02-07 00:24:33 +00003703 // and suggest annotations.
Jordan Rosed8188f82013-08-01 22:16:36 +00003704 if (LCtx->getParent())
Ted Kremenek0cf3d472012-02-07 00:24:33 +00003705 return;
3706
Jordy Rose38f17d62011-08-23 19:01:07 +00003707 B = state->get<RefBindings>();
3708 SmallVector<SymbolRef, 10> Leaked;
3709
Jordan Rose166d5022012-11-02 01:54:06 +00003710 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I)
Jordy Rose8d228632011-08-23 20:07:14 +00003711 state = handleSymbolDeath(state, I->first, I->second, Leaked);
Jordy Rose38f17d62011-08-23 19:01:07 +00003712
Jordan Rose2bce86c2012-08-18 00:30:16 +00003713 processLeaks(state, Leaked, Ctx, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003714}
3715
3716const ProgramPointTag *
Jordy Rose910c4052011-09-02 06:44:22 +00003717RetainCountChecker::getDeadSymbolTag(SymbolRef sym) const {
Stephen Hines651f13c2014-04-23 16:59:28 -07003718 const CheckerProgramPointTag *&tag = DeadSymbolTags[sym];
Jordy Rose38f17d62011-08-23 19:01:07 +00003719 if (!tag) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003720 SmallString<64> buf;
Jordy Rose38f17d62011-08-23 19:01:07 +00003721 llvm::raw_svector_ostream out(buf);
Stephen Hines651f13c2014-04-23 16:59:28 -07003722 out << "Dead Symbol : ";
Anna Zaksf62ceec2011-12-05 18:58:11 +00003723 sym->dumpToStream(out);
Stephen Hines651f13c2014-04-23 16:59:28 -07003724 tag = new CheckerProgramPointTag(this, out.str());
Jordy Rose38f17d62011-08-23 19:01:07 +00003725 }
3726 return tag;
3727}
3728
Jordy Rose910c4052011-09-02 06:44:22 +00003729void RetainCountChecker::checkDeadSymbols(SymbolReaper &SymReaper,
3730 CheckerContext &C) const {
Jordy Rose38f17d62011-08-23 19:01:07 +00003731 ExplodedNode *Pred = C.getPredecessor();
3732
Ted Kremenek8bef8232012-01-26 21:29:00 +00003733 ProgramStateRef state = C.getState();
Jordan Rose166d5022012-11-02 01:54:06 +00003734 RefBindingsTy B = state->get<RefBindings>();
Jordan Rose4ee1c552012-12-06 18:58:18 +00003735 SmallVector<SymbolRef, 10> Leaked;
Jordy Rose38f17d62011-08-23 19:01:07 +00003736
3737 // Update counts from autorelease pools
3738 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3739 E = SymReaper.dead_end(); I != E; ++I) {
3740 SymbolRef Sym = *I;
3741 if (const RefVal *T = B.lookup(Sym)){
3742 // Use the symbol as the tag.
3743 // FIXME: This might not be as unique as we would like.
Jordan Rose2bce86c2012-08-18 00:30:16 +00003744 const ProgramPointTag *Tag = getDeadSymbolTag(Sym);
Jordan Rose4ee1c552012-12-06 18:58:18 +00003745 state = handleAutoreleaseCounts(state, Pred, Tag, C, Sym, *T);
Jordy Rose8d228632011-08-23 20:07:14 +00003746 if (!state)
Jordy Rose38f17d62011-08-23 19:01:07 +00003747 return;
Jordan Rose4ee1c552012-12-06 18:58:18 +00003748
3749 // Fetch the new reference count from the state, and use it to handle
3750 // this symbol.
3751 state = handleSymbolDeath(state, *I, *getRefBinding(state, Sym), Leaked);
Jordy Rose38f17d62011-08-23 19:01:07 +00003752 }
3753 }
3754
Jordan Rose4ee1c552012-12-06 18:58:18 +00003755 if (Leaked.empty()) {
3756 C.addTransition(state);
3757 return;
Jordy Rose38f17d62011-08-23 19:01:07 +00003758 }
3759
Jordan Rose2bce86c2012-08-18 00:30:16 +00003760 Pred = processLeaks(state, Leaked, C, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003761
3762 // Did we cache out?
3763 if (!Pred)
3764 return;
3765
3766 // Now generate a new node that nukes the old bindings.
Jordan Rose4ee1c552012-12-06 18:58:18 +00003767 // The only bindings left at this point are the leaked symbols.
Jordan Rose166d5022012-11-02 01:54:06 +00003768 RefBindingsTy::Factory &F = state->get_context<RefBindings>();
Jordan Rose4ee1c552012-12-06 18:58:18 +00003769 B = state->get<RefBindings>();
Jordy Rose38f17d62011-08-23 19:01:07 +00003770
Jordan Rose4ee1c552012-12-06 18:58:18 +00003771 for (SmallVectorImpl<SymbolRef>::iterator I = Leaked.begin(),
3772 E = Leaked.end();
3773 I != E; ++I)
Jordy Rose38f17d62011-08-23 19:01:07 +00003774 B = F.remove(B, *I);
3775
3776 state = state->set<RefBindings>(B);
Anna Zaks0bd6b112011-10-26 21:06:34 +00003777 C.addTransition(state, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003778}
3779
Ted Kremenek8bef8232012-01-26 21:29:00 +00003780void RetainCountChecker::printState(raw_ostream &Out, ProgramStateRef State,
Jordy Rose910c4052011-09-02 06:44:22 +00003781 const char *NL, const char *Sep) const {
Jordy Rosedbd658e2011-08-28 19:11:56 +00003782
Jordan Rose166d5022012-11-02 01:54:06 +00003783 RefBindingsTy B = State->get<RefBindings>();
Jordy Rosedbd658e2011-08-28 19:11:56 +00003784
Ted Kremenek65a08922013-03-28 18:43:18 +00003785 if (B.isEmpty())
3786 return;
3787
3788 Out << Sep << NL;
Jordy Rosedbd658e2011-08-28 19:11:56 +00003789
Jordan Rose166d5022012-11-02 01:54:06 +00003790 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Jordy Rosedbd658e2011-08-28 19:11:56 +00003791 Out << I->first << " : ";
3792 I->second.print(Out);
3793 Out << NL;
3794 }
Jordy Rosedbd658e2011-08-28 19:11:56 +00003795}
3796
3797//===----------------------------------------------------------------------===//
Jordy Rose910c4052011-09-02 06:44:22 +00003798// Checker registration.
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00003799//===----------------------------------------------------------------------===//
3800
Jordy Rose17a38e22011-09-02 05:55:19 +00003801void ento::registerRetainCountChecker(CheckerManager &Mgr) {
Ted Kremenek08a838d2013-04-16 21:44:22 +00003802 Mgr.registerChecker<RetainCountChecker>(Mgr.getAnalyzerOptions());
Jordy Rose17a38e22011-09-02 05:55:19 +00003803}
3804
Ted Kremenek53c7ea12013-08-14 23:41:49 +00003805//===----------------------------------------------------------------------===//
3806// Implementation of the CallEffects API.
3807//===----------------------------------------------------------------------===//
3808
3809namespace clang { namespace ento { namespace objc_retain {
3810
3811// This is a bit gross, but it allows us to populate CallEffects without
3812// creating a bunch of accessors. This kind is very localized, so the
3813// damage of this macro is limited.
3814#define createCallEffect(D, KIND)\
3815 ASTContext &Ctx = D->getASTContext();\
3816 LangOptions L = Ctx.getLangOpts();\
3817 RetainSummaryManager M(Ctx, L.GCOnly, L.ObjCAutoRefCount);\
3818 const RetainSummary *S = M.get ## KIND ## Summary(D);\
3819 CallEffects CE(S->getRetEffect());\
3820 CE.Receiver = S->getReceiverEffect();\
Ted Kremenek21043742013-08-16 23:14:22 +00003821 unsigned N = D->param_size();\
Ted Kremenek53c7ea12013-08-14 23:41:49 +00003822 for (unsigned i = 0; i < N; ++i) {\
3823 CE.Args.push_back(S->getArg(i));\
3824 }
3825
3826CallEffects CallEffects::getEffect(const ObjCMethodDecl *MD) {
3827 createCallEffect(MD, Method);
3828 return CE;
3829}
3830
3831CallEffects CallEffects::getEffect(const FunctionDecl *FD) {
3832 createCallEffect(FD, Function);
3833 return CE;
3834}
3835
3836#undef createCallEffect
3837
3838}}}