blob: a6ddf1dfbbc131a7ba9b9dfab79416b8cb437a04 [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"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000016#include "clang/AST/Attr.h"
Ted Kremenekb2771592011-03-30 17:41:19 +000017#include "clang/AST/DeclCXX.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000018#include "clang/AST/DeclObjC.h"
19#include "clang/AST/ParentMap.h"
20#include "clang/Analysis/DomainSpecific/CocoaConventions.h"
Ted Kremenek0b526b42010-02-18 00:05:58 +000021#include "clang/Basic/LangOptions.h"
22#include "clang/Basic/SourceManager.h"
Ted Kremenek9b663712011-02-10 01:03:03 +000023#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
24#include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000025#include "clang/StaticAnalyzer/Core/Checker.h"
26#include "clang/StaticAnalyzer/Core/CheckerManager.h"
Jordan Rosef540c542012-07-26 21:39:41 +000027#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
Jordy Rose910c4052011-09-02 06:44:22 +000028#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
Ted Kremenek18c66fd2011-08-15 22:09:50 +000029#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
Ted Kremenek9b663712011-02-10 01:03:03 +000030#include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
Ted Kremenek5774e392013-08-14 23:41:46 +000031#include "clang/StaticAnalyzer/Checkers/ObjCRetainCount.h"
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000032#include "llvm/ADT/DenseMap.h"
33#include "llvm/ADT/FoldingSet.h"
Ted Kremenek6d348932008-10-21 15:53:15 +000034#include "llvm/ADT/ImmutableList.h"
Ted Kremenek0b526b42010-02-18 00:05:58 +000035#include "llvm/ADT/ImmutableMap.h"
Ted Kremenek6ed9afc2008-05-16 18:33:44 +000036#include "llvm/ADT/STLExtras.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000037#include "llvm/ADT/SmallString.h"
Ted Kremenek0b526b42010-02-18 00:05:58 +000038#include "llvm/ADT/StringExtras.h"
Chris Lattner5f9e2722011-07-23 10:55:15 +000039#include <cstdarg>
Ted Kremenek2fff37e2008-03-06 00:08:09 +000040
Ted Kremenek08a838d2013-04-16 21:44:22 +000041#include "AllocationDiagnostics.h"
42
Ted Kremenek2fff37e2008-03-06 00:08:09 +000043using namespace clang;
Ted Kremenek9ef65372010-12-23 07:20:52 +000044using namespace ento;
Ted Kremenek5774e392013-08-14 23:41:46 +000045using namespace objc_retain;
Ted Kremeneka64e89b2010-01-27 06:13:48 +000046using llvm::StrInStrNoCase;
Ted Kremenek4c79e552008-11-05 16:54:44 +000047
Ted Kremenek05cbe1a2008-04-09 23:49:11 +000048//===----------------------------------------------------------------------===//
Ted Kremenek5774e392013-08-14 23:41:46 +000049// Adapters for FoldingSet.
Ted Kremenek05cbe1a2008-04-09 23:49:11 +000050//===----------------------------------------------------------------------===//
51
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000052namespace llvm {
Ted Kremenekb77449c2009-05-03 05:20:50 +000053template <> struct FoldingSetTrait<ArgEffect> {
Ted Kremenek5774e392013-08-14 23:41:46 +000054static inline void Profile(const ArgEffect X, FoldingSetNodeID &ID) {
Ted Kremenekb77449c2009-05-03 05:20:50 +000055 ID.AddInteger((unsigned) X);
56}
Ted Kremenek553cf182008-06-25 21:21:56 +000057};
Ted Kremenek5774e392013-08-14 23:41:46 +000058template <> struct FoldingSetTrait<RetEffect> {
59 static inline void Profile(const RetEffect &X, FoldingSetNodeID &ID) {
60 ID.AddInteger((unsigned) X.getKind());
61 ID.AddInteger((unsigned) X.getObjKind());
62}
63};
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000064} // end llvm namespace
65
Ted Kremenek5774e392013-08-14 23:41:46 +000066//===----------------------------------------------------------------------===//
67// Reference-counting logic (typestate + counts).
68//===----------------------------------------------------------------------===//
69
Ted Kremenekb77449c2009-05-03 05:20:50 +000070/// ArgEffects summarizes the effects of a function/method call on all of
71/// its arguments.
72typedef llvm::ImmutableMap<unsigned,ArgEffect> ArgEffects;
73
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000074namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +000075class RefVal {
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +000076public:
77 enum Kind {
78 Owned = 0, // Owning reference.
79 NotOwned, // Reference is not owned by still valid (not freed).
80 Released, // Object has been released.
81 ReturnedOwned, // Returned object passes ownership to caller.
82 ReturnedNotOwned, // Return object does not pass ownership to caller.
83 ERROR_START,
84 ErrorDeallocNotOwned, // -dealloc called on non-owned object.
85 ErrorDeallocGC, // Calling -dealloc with GC enabled.
86 ErrorUseAfterRelease, // Object used after released.
87 ErrorReleaseNotOwned, // Release of an object that was not owned.
88 ERROR_LEAK_START,
89 ErrorLeak, // A memory leak due to excessive reference counts.
90 ErrorLeakReturned, // A memory leak due to the returning method not having
91 // the correct naming conventions.
92 ErrorGCLeakReturned,
93 ErrorOverAutorelease,
94 ErrorReturnedNotOwned
95 };
Ted Kremenekdcee3ce2010-07-01 20:16:50 +000096
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +000097private:
98 Kind kind;
99 RetEffect::ObjKind okind;
100 unsigned Cnt;
101 unsigned ACnt;
102 QualType T;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000103
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000104 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, unsigned acnt, QualType t)
105 : kind(k), okind(o), Cnt(cnt), ACnt(acnt), T(t) {}
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000106
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000107public:
108 Kind getKind() const { return kind; }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000109
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000110 RetEffect::ObjKind getObjKind() const { return okind; }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000111
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000112 unsigned getCount() const { return Cnt; }
113 unsigned getAutoreleaseCount() const { return ACnt; }
114 unsigned getCombinedCounts() const { return Cnt + ACnt; }
115 void clearCounts() { Cnt = 0; ACnt = 0; }
116 void setCount(unsigned i) { Cnt = i; }
117 void setAutoreleaseCount(unsigned i) { ACnt = i; }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000118
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000119 QualType getType() const { return T; }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000120
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000121 bool isOwned() const {
122 return getKind() == Owned;
123 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000124
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000125 bool isNotOwned() const {
126 return getKind() == NotOwned;
127 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000128
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000129 bool isReturnedOwned() const {
130 return getKind() == ReturnedOwned;
131 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000132
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000133 bool isReturnedNotOwned() const {
134 return getKind() == ReturnedNotOwned;
135 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000136
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000137 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
138 unsigned Count = 1) {
139 return RefVal(Owned, o, Count, 0, t);
140 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000141
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000142 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
143 unsigned Count = 0) {
144 return RefVal(NotOwned, o, Count, 0, t);
145 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000146
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000147 // Comparison, profiling, and pretty-printing.
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000148
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000149 bool operator==(const RefVal& X) const {
150 return kind == X.kind && Cnt == X.Cnt && T == X.T && ACnt == X.ACnt;
151 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000152
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000153 RefVal operator-(size_t i) const {
154 return RefVal(getKind(), getObjKind(), getCount() - i,
155 getAutoreleaseCount(), getType());
156 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000157
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000158 RefVal operator+(size_t i) const {
159 return RefVal(getKind(), getObjKind(), getCount() + i,
160 getAutoreleaseCount(), getType());
161 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000162
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000163 RefVal operator^(Kind k) const {
164 return RefVal(k, getObjKind(), getCount(), getAutoreleaseCount(),
165 getType());
166 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000167
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000168 RefVal autorelease() const {
169 return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount()+1,
170 getType());
171 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000172
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000173 void Profile(llvm::FoldingSetNodeID& ID) const {
174 ID.AddInteger((unsigned) kind);
175 ID.AddInteger(Cnt);
176 ID.AddInteger(ACnt);
177 ID.Add(T);
178 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000179
Ted Kremenek9c378f72011-08-12 23:37:29 +0000180 void print(raw_ostream &Out) const;
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000181};
182
Ted Kremenek9c378f72011-08-12 23:37:29 +0000183void RefVal::print(raw_ostream &Out) const {
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000184 if (!T.isNull())
Jordy Rosedbd658e2011-08-28 19:11:56 +0000185 Out << "Tracked " << T.getAsString() << '/';
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000186
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000187 switch (getKind()) {
Jordy Rose910c4052011-09-02 06:44:22 +0000188 default: llvm_unreachable("Invalid RefVal kind");
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000189 case Owned: {
190 Out << "Owned";
191 unsigned cnt = getCount();
192 if (cnt) Out << " (+ " << cnt << ")";
193 break;
194 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000195
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000196 case NotOwned: {
197 Out << "NotOwned";
198 unsigned cnt = getCount();
199 if (cnt) Out << " (+ " << cnt << ")";
200 break;
201 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000202
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000203 case ReturnedOwned: {
204 Out << "ReturnedOwned";
205 unsigned cnt = getCount();
206 if (cnt) Out << " (+ " << cnt << ")";
207 break;
208 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000209
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000210 case ReturnedNotOwned: {
211 Out << "ReturnedNotOwned";
212 unsigned cnt = getCount();
213 if (cnt) Out << " (+ " << cnt << ")";
214 break;
215 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000216
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000217 case Released:
218 Out << "Released";
219 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000220
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000221 case ErrorDeallocGC:
222 Out << "-dealloc (GC)";
223 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000224
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000225 case ErrorDeallocNotOwned:
226 Out << "-dealloc (not-owned)";
227 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000228
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000229 case ErrorLeak:
230 Out << "Leaked";
231 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000232
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000233 case ErrorLeakReturned:
234 Out << "Leaked (Bad naming)";
235 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000236
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000237 case ErrorGCLeakReturned:
238 Out << "Leaked (GC-ed at return)";
239 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000240
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000241 case ErrorUseAfterRelease:
242 Out << "Use-After-Release [ERROR]";
243 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000244
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000245 case ErrorReleaseNotOwned:
246 Out << "Release of Not-Owned [ERROR]";
247 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000248
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000249 case RefVal::ErrorOverAutorelease:
Jordan Rose2545b1d2013-04-23 01:42:25 +0000250 Out << "Over-autoreleased";
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000251 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000252
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000253 case RefVal::ErrorReturnedNotOwned:
254 Out << "Non-owned object returned instead of owned";
255 break;
256 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000257
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000258 if (ACnt) {
259 Out << " [ARC +" << ACnt << ']';
260 }
261}
262} //end anonymous namespace
263
264//===----------------------------------------------------------------------===//
265// RefBindings - State used to track object reference counts.
266//===----------------------------------------------------------------------===//
267
Jordan Rose166d5022012-11-02 01:54:06 +0000268REGISTER_MAP_WITH_PROGRAMSTATE(RefBindings, SymbolRef, RefVal)
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000269
Anna Zaks8d6b43c2012-08-14 00:36:15 +0000270static inline const RefVal *getRefBinding(ProgramStateRef State,
271 SymbolRef Sym) {
272 return State->get<RefBindings>(Sym);
273}
274
275static inline ProgramStateRef setRefBinding(ProgramStateRef State,
276 SymbolRef Sym, RefVal Val) {
277 return State->set<RefBindings>(Sym, Val);
278}
279
280static ProgramStateRef removeRefBinding(ProgramStateRef State, SymbolRef Sym) {
281 return State->remove<RefBindings>(Sym);
282}
283
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000284//===----------------------------------------------------------------------===//
Jordy Rose910c4052011-09-02 06:44:22 +0000285// Function/Method behavior summaries.
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000286//===----------------------------------------------------------------------===//
287
288namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000289class RetainSummary {
Jordy Roseef945882012-03-18 01:26:10 +0000290 /// Args - a map of (index, ArgEffect) pairs, where index
Ted Kremenek1bffd742008-05-06 15:44:25 +0000291 /// specifies the argument (starting from 0). This can be sparsely
292 /// populated; arguments with no entry in Args use 'DefaultArgEffect'.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000293 ArgEffects Args;
Mike Stump1eb44332009-09-09 15:08:12 +0000294
Ted Kremenek1bffd742008-05-06 15:44:25 +0000295 /// DefaultArgEffect - The default ArgEffect to apply to arguments that
296 /// do not have an entry in Args.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000297 ArgEffect DefaultArgEffect;
Mike Stump1eb44332009-09-09 15:08:12 +0000298
Ted Kremenek553cf182008-06-25 21:21:56 +0000299 /// Receiver - If this summary applies to an Objective-C message expression,
300 /// this is the effect applied to the state of the receiver.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000301 ArgEffect Receiver;
Mike Stump1eb44332009-09-09 15:08:12 +0000302
Ted Kremenek553cf182008-06-25 21:21:56 +0000303 /// Ret - The effect on the return value. Used to indicate if the
Jordy Rose76c506f2011-08-21 21:58:18 +0000304 /// function/method call returns a new tracked symbol.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000305 RetEffect Ret;
Mike Stump1eb44332009-09-09 15:08:12 +0000306
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000307public:
Ted Kremenekb77449c2009-05-03 05:20:50 +0000308 RetainSummary(ArgEffects A, RetEffect R, ArgEffect defaultEff,
Jordy Rosee62e87b2011-08-20 20:55:40 +0000309 ArgEffect ReceiverEff)
310 : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000311
Ted Kremenek553cf182008-06-25 21:21:56 +0000312 /// getArg - Return the argument effect on the argument specified by
313 /// idx (starting from 0).
Ted Kremenek1ac08d62008-03-11 17:48:22 +0000314 ArgEffect getArg(unsigned idx) const {
Ted Kremenekb77449c2009-05-03 05:20:50 +0000315 if (const ArgEffect *AE = Args.lookup(idx))
316 return *AE;
Mike Stump1eb44332009-09-09 15:08:12 +0000317
Ted Kremenek1bffd742008-05-06 15:44:25 +0000318 return DefaultArgEffect;
Ted Kremenek1ac08d62008-03-11 17:48:22 +0000319 }
Ted Kremenek53c7ea12013-08-14 23:41:49 +0000320
Ted Kremenek11fe1752011-01-27 18:43:03 +0000321 void addArg(ArgEffects::Factory &af, unsigned idx, ArgEffect e) {
322 Args = af.add(Args, idx, e);
323 }
Mike Stump1eb44332009-09-09 15:08:12 +0000324
Ted Kremenek885c27b2009-05-04 05:31:22 +0000325 /// setDefaultArgEffect - Set the default argument effect.
326 void setDefaultArgEffect(ArgEffect E) {
327 DefaultArgEffect = E;
328 }
Mike Stump1eb44332009-09-09 15:08:12 +0000329
Ted Kremenek553cf182008-06-25 21:21:56 +0000330 /// getRetEffect - Returns the effect on the return value of the call.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000331 RetEffect getRetEffect() const { return Ret; }
Mike Stump1eb44332009-09-09 15:08:12 +0000332
Ted Kremenek885c27b2009-05-04 05:31:22 +0000333 /// setRetEffect - Set the effect of the return value of the call.
334 void setRetEffect(RetEffect E) { Ret = E; }
Mike Stump1eb44332009-09-09 15:08:12 +0000335
Ted Kremenek12b94342011-01-27 06:54:14 +0000336
337 /// Sets the effect on the receiver of the message.
338 void setReceiverEffect(ArgEffect e) { Receiver = e; }
339
Ted Kremenek553cf182008-06-25 21:21:56 +0000340 /// getReceiverEffect - Returns the effect on the receiver of the call.
341 /// This is only meaningful if the summary applies to an ObjCMessageExpr*.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000342 ArgEffect getReceiverEffect() const { return Receiver; }
Jordy Rose4df54fe2011-08-23 04:27:15 +0000343
344 /// Test if two retain summaries are identical. Note that merely equivalent
345 /// summaries are not necessarily identical (for example, if an explicit
346 /// argument effect matches the default effect).
347 bool operator==(const RetainSummary &Other) const {
348 return Args == Other.Args && DefaultArgEffect == Other.DefaultArgEffect &&
349 Receiver == Other.Receiver && Ret == Other.Ret;
350 }
Jordy Roseef945882012-03-18 01:26:10 +0000351
352 /// Profile this summary for inclusion in a FoldingSet.
353 void Profile(llvm::FoldingSetNodeID& ID) const {
354 ID.Add(Args);
355 ID.Add(DefaultArgEffect);
356 ID.Add(Receiver);
357 ID.Add(Ret);
358 }
359
360 /// A retain summary is simple if it has no ArgEffects other than the default.
361 bool isSimple() const {
362 return Args.isEmpty();
363 }
Jordan Rose4531b7d2012-07-02 19:27:43 +0000364
365private:
366 ArgEffects getArgEffects() const { return Args; }
367 ArgEffect getDefaultArgEffect() const { return DefaultArgEffect; }
368
369 friend class RetainSummaryManager;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000370};
Ted Kremenek4f22a782008-06-23 23:30:29 +0000371} // end anonymous namespace
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000372
Ted Kremenek553cf182008-06-25 21:21:56 +0000373//===----------------------------------------------------------------------===//
374// Data structures for constructing summaries.
375//===----------------------------------------------------------------------===//
Ted Kremenek53301ba2008-06-24 03:49:48 +0000376
Ted Kremenek553cf182008-06-25 21:21:56 +0000377namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000378class ObjCSummaryKey {
Ted Kremenek553cf182008-06-25 21:21:56 +0000379 IdentifierInfo* II;
380 Selector S;
Mike Stump1eb44332009-09-09 15:08:12 +0000381public:
Ted Kremenek553cf182008-06-25 21:21:56 +0000382 ObjCSummaryKey(IdentifierInfo* ii, Selector s)
383 : II(ii), S(s) {}
384
Ted Kremenek9c378f72011-08-12 23:37:29 +0000385 ObjCSummaryKey(const ObjCInterfaceDecl *d, Selector s)
Ted Kremenek553cf182008-06-25 21:21:56 +0000386 : II(d ? d->getIdentifier() : 0), S(s) {}
Ted Kremenek70b6a832009-05-13 18:16:01 +0000387
Ted Kremenek553cf182008-06-25 21:21:56 +0000388 ObjCSummaryKey(Selector s)
389 : II(0), S(s) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000390
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000391 IdentifierInfo *getIdentifier() const { return II; }
Ted Kremenek553cf182008-06-25 21:21:56 +0000392 Selector getSelector() const { return S; }
393};
Ted Kremenek4f22a782008-06-23 23:30:29 +0000394}
395
396namespace llvm {
Ted Kremenek553cf182008-06-25 21:21:56 +0000397template <> struct DenseMapInfo<ObjCSummaryKey> {
398 static inline ObjCSummaryKey getEmptyKey() {
399 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
400 DenseMapInfo<Selector>::getEmptyKey());
401 }
Mike Stump1eb44332009-09-09 15:08:12 +0000402
Ted Kremenek553cf182008-06-25 21:21:56 +0000403 static inline ObjCSummaryKey getTombstoneKey() {
404 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
Mike Stump1eb44332009-09-09 15:08:12 +0000405 DenseMapInfo<Selector>::getTombstoneKey());
Ted Kremenek553cf182008-06-25 21:21:56 +0000406 }
Mike Stump1eb44332009-09-09 15:08:12 +0000407
Ted Kremenek553cf182008-06-25 21:21:56 +0000408 static unsigned getHashValue(const ObjCSummaryKey &V) {
Benjamin Kramer28b23072012-05-27 13:28:44 +0000409 typedef std::pair<IdentifierInfo*, Selector> PairTy;
410 return DenseMapInfo<PairTy>::getHashValue(PairTy(V.getIdentifier(),
411 V.getSelector()));
Ted Kremenek553cf182008-06-25 21:21:56 +0000412 }
Mike Stump1eb44332009-09-09 15:08:12 +0000413
Ted Kremenek553cf182008-06-25 21:21:56 +0000414 static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
Benjamin Kramer28b23072012-05-27 13:28:44 +0000415 return LHS.getIdentifier() == RHS.getIdentifier() &&
416 LHS.getSelector() == RHS.getSelector();
Ted Kremenek553cf182008-06-25 21:21:56 +0000417 }
Mike Stump1eb44332009-09-09 15:08:12 +0000418
Ted Kremenek553cf182008-06-25 21:21:56 +0000419};
Chris Lattner06159e82009-12-15 07:26:51 +0000420template <>
421struct isPodLike<ObjCSummaryKey> { static const bool value = true; };
Ted Kremenek4f22a782008-06-23 23:30:29 +0000422} // end llvm namespace
Mike Stump1eb44332009-09-09 15:08:12 +0000423
Ted Kremenek4f22a782008-06-23 23:30:29 +0000424namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000425class ObjCSummaryCache {
Ted Kremenek93edbc52011-10-05 23:54:29 +0000426 typedef llvm::DenseMap<ObjCSummaryKey, const RetainSummary *> MapTy;
Ted Kremenek553cf182008-06-25 21:21:56 +0000427 MapTy M;
428public:
429 ObjCSummaryCache() {}
Mike Stump1eb44332009-09-09 15:08:12 +0000430
Ted Kremenek93edbc52011-10-05 23:54:29 +0000431 const RetainSummary * find(const ObjCInterfaceDecl *D, Selector S) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000432 // Do a lookup with the (D,S) pair. If we find a match return
433 // the iterator.
434 ObjCSummaryKey K(D, S);
435 MapTy::iterator I = M.find(K);
Mike Stump1eb44332009-09-09 15:08:12 +0000436
Jordan Rose4531b7d2012-07-02 19:27:43 +0000437 if (I != M.end())
Ted Kremenek614cc542009-07-21 23:27:57 +0000438 return I->second;
Jordan Rose4531b7d2012-07-02 19:27:43 +0000439 if (!D)
440 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +0000441
Ted Kremenek553cf182008-06-25 21:21:56 +0000442 // Walk the super chain. If we find a hit with a parent, we'll end
443 // up returning that summary. We actually allow that key (null,S), as
444 // we cache summaries for the null ObjCInterfaceDecl* to allow us to
445 // generate initial summaries without having to worry about NSObject
446 // being declared.
447 // FIXME: We may change this at some point.
Ted Kremenek9c378f72011-08-12 23:37:29 +0000448 for (ObjCInterfaceDecl *C=D->getSuperClass() ;; C=C->getSuperClass()) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000449 if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
450 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000451
Ted Kremenek553cf182008-06-25 21:21:56 +0000452 if (!C)
Ted Kremenek614cc542009-07-21 23:27:57 +0000453 return NULL;
Ted Kremenek553cf182008-06-25 21:21:56 +0000454 }
Mike Stump1eb44332009-09-09 15:08:12 +0000455
456 // Cache the summary with original key to make the next lookup faster
Ted Kremenek553cf182008-06-25 21:21:56 +0000457 // and return the iterator.
Ted Kremenek93edbc52011-10-05 23:54:29 +0000458 const RetainSummary *Summ = I->second;
Ted Kremenek614cc542009-07-21 23:27:57 +0000459 M[K] = Summ;
460 return Summ;
Ted Kremenek553cf182008-06-25 21:21:56 +0000461 }
Mike Stump1eb44332009-09-09 15:08:12 +0000462
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000463 const RetainSummary *find(IdentifierInfo* II, Selector S) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000464 // FIXME: Class method lookup. Right now we dont' have a good way
465 // of going between IdentifierInfo* and the class hierarchy.
Ted Kremenek614cc542009-07-21 23:27:57 +0000466 MapTy::iterator I = M.find(ObjCSummaryKey(II, S));
Mike Stump1eb44332009-09-09 15:08:12 +0000467
Ted Kremenek614cc542009-07-21 23:27:57 +0000468 if (I == M.end())
469 I = M.find(ObjCSummaryKey(S));
Mike Stump1eb44332009-09-09 15:08:12 +0000470
Ted Kremenek614cc542009-07-21 23:27:57 +0000471 return I == M.end() ? NULL : I->second;
Ted Kremenek553cf182008-06-25 21:21:56 +0000472 }
Mike Stump1eb44332009-09-09 15:08:12 +0000473
Ted Kremenek93edbc52011-10-05 23:54:29 +0000474 const RetainSummary *& operator[](ObjCSummaryKey K) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000475 return M[K];
476 }
Mike Stump1eb44332009-09-09 15:08:12 +0000477
Ted Kremenek93edbc52011-10-05 23:54:29 +0000478 const RetainSummary *& operator[](Selector S) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000479 return M[ ObjCSummaryKey(S) ];
480 }
Mike Stump1eb44332009-09-09 15:08:12 +0000481};
Ted Kremenek553cf182008-06-25 21:21:56 +0000482} // end anonymous namespace
483
484//===----------------------------------------------------------------------===//
485// Data structures for managing collections of summaries.
486//===----------------------------------------------------------------------===//
487
488namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000489class RetainSummaryManager {
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000490
491 //==-----------------------------------------------------------------==//
492 // Typedefs.
493 //==-----------------------------------------------------------------==//
Mike Stump1eb44332009-09-09 15:08:12 +0000494
Ted Kremenek93edbc52011-10-05 23:54:29 +0000495 typedef llvm::DenseMap<const FunctionDecl*, const RetainSummary *>
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000496 FuncSummariesTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000497
Ted Kremenek4f22a782008-06-23 23:30:29 +0000498 typedef ObjCSummaryCache ObjCMethodSummariesTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000499
Jordy Roseef945882012-03-18 01:26:10 +0000500 typedef llvm::FoldingSetNodeWrapper<RetainSummary> CachedSummaryNode;
501
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000502 //==-----------------------------------------------------------------==//
503 // Data.
504 //==-----------------------------------------------------------------==//
Mike Stump1eb44332009-09-09 15:08:12 +0000505
Ted Kremenek553cf182008-06-25 21:21:56 +0000506 /// Ctx - The ASTContext object for the analyzed ASTs.
Ted Kremenek9c378f72011-08-12 23:37:29 +0000507 ASTContext &Ctx;
Ted Kremenek179064e2008-07-01 17:21:27 +0000508
Ted Kremenek553cf182008-06-25 21:21:56 +0000509 /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
Ted Kremenek377e2302008-04-29 05:33:51 +0000510 const bool GCEnabled;
Mike Stump1eb44332009-09-09 15:08:12 +0000511
John McCallf85e1932011-06-15 23:02:42 +0000512 /// Records whether or not the analyzed code runs in ARC mode.
513 const bool ARCEnabled;
514
Ted Kremenek553cf182008-06-25 21:21:56 +0000515 /// FuncSummaries - A map from FunctionDecls to summaries.
Mike Stump1eb44332009-09-09 15:08:12 +0000516 FuncSummariesTy FuncSummaries;
517
Ted Kremenek553cf182008-06-25 21:21:56 +0000518 /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
519 /// to summaries.
Ted Kremenek1f180c32008-06-23 22:21:20 +0000520 ObjCMethodSummariesTy ObjCClassMethodSummaries;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000521
Ted Kremenek553cf182008-06-25 21:21:56 +0000522 /// ObjCMethodSummaries - A map from selectors to summaries.
Ted Kremenek1f180c32008-06-23 22:21:20 +0000523 ObjCMethodSummariesTy ObjCMethodSummaries;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000524
Ted Kremenek553cf182008-06-25 21:21:56 +0000525 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
526 /// and all other data used by the checker.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000527 llvm::BumpPtrAllocator BPAlloc;
Mike Stump1eb44332009-09-09 15:08:12 +0000528
Ted Kremenekb77449c2009-05-03 05:20:50 +0000529 /// AF - A factory for ArgEffects objects.
Mike Stump1eb44332009-09-09 15:08:12 +0000530 ArgEffects::Factory AF;
531
Ted Kremenek553cf182008-06-25 21:21:56 +0000532 /// ScratchArgs - A holding buffer for construct ArgEffects.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000533 ArgEffects ScratchArgs;
Mike Stump1eb44332009-09-09 15:08:12 +0000534
Ted Kremenekec315332009-05-07 23:40:42 +0000535 /// ObjCAllocRetE - Default return effect for methods returning Objective-C
536 /// objects.
537 RetEffect ObjCAllocRetE;
Ted Kremenek547d4952009-06-05 23:18:01 +0000538
Mike Stump1eb44332009-09-09 15:08:12 +0000539 /// ObjCInitRetE - Default return effect for init methods returning
Ted Kremenekac02f202009-08-20 05:13:36 +0000540 /// Objective-C objects.
Ted Kremenek547d4952009-06-05 23:18:01 +0000541 RetEffect ObjCInitRetE;
Mike Stump1eb44332009-09-09 15:08:12 +0000542
Jordy Roseef945882012-03-18 01:26:10 +0000543 /// SimpleSummaries - Used for uniquing summaries that don't have special
544 /// effects.
545 llvm::FoldingSet<CachedSummaryNode> SimpleSummaries;
Mike Stump1eb44332009-09-09 15:08:12 +0000546
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000547 //==-----------------------------------------------------------------==//
548 // Methods.
549 //==-----------------------------------------------------------------==//
Mike Stump1eb44332009-09-09 15:08:12 +0000550
Ted Kremenek553cf182008-06-25 21:21:56 +0000551 /// getArgEffects - Returns a persistent ArgEffects object based on the
552 /// data in ScratchArgs.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000553 ArgEffects getArgEffects();
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000554
Mike Stump1eb44332009-09-09 15:08:12 +0000555 enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
Ted Kremenek93edbc52011-10-05 23:54:29 +0000556
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000557 const RetainSummary *getUnarySummary(const FunctionType* FT,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000558 UnaryFuncKind func);
Mike Stump1eb44332009-09-09 15:08:12 +0000559
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000560 const RetainSummary *getCFSummaryCreateRule(const FunctionDecl *FD);
561 const RetainSummary *getCFSummaryGetRule(const FunctionDecl *FD);
562 const RetainSummary *getCFCreateGetRuleSummary(const FunctionDecl *FD);
Mike Stump1eb44332009-09-09 15:08:12 +0000563
Jordy Roseef945882012-03-18 01:26:10 +0000564 const RetainSummary *getPersistentSummary(const RetainSummary &OldSumm);
Ted Kremenek706522f2008-10-29 04:07:07 +0000565
Jordy Roseef945882012-03-18 01:26:10 +0000566 const RetainSummary *getPersistentSummary(RetEffect RetEff,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000567 ArgEffect ReceiverEff = DoNothing,
568 ArgEffect DefaultEff = MayEscape) {
Jordy Roseef945882012-03-18 01:26:10 +0000569 RetainSummary Summ(getArgEffects(), RetEff, DefaultEff, ReceiverEff);
570 return getPersistentSummary(Summ);
571 }
572
Ted Kremenekc91fdf62012-05-08 00:12:09 +0000573 const RetainSummary *getDoNothingSummary() {
574 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
575 }
576
Jordy Roseef945882012-03-18 01:26:10 +0000577 const RetainSummary *getDefaultSummary() {
578 return getPersistentSummary(RetEffect::MakeNoRet(),
579 DoNothing, MayEscape);
Ted Kremenek9c32d082008-05-06 00:30:21 +0000580 }
Mike Stump1eb44332009-09-09 15:08:12 +0000581
Ted Kremenek93edbc52011-10-05 23:54:29 +0000582 const RetainSummary *getPersistentStopSummary() {
Jordy Roseef945882012-03-18 01:26:10 +0000583 return getPersistentSummary(RetEffect::MakeNoRet(),
584 StopTracking, StopTracking);
Mike Stump1eb44332009-09-09 15:08:12 +0000585 }
Ted Kremenekb3095252008-05-06 04:20:12 +0000586
Ted Kremenek1f180c32008-06-23 22:21:20 +0000587 void InitializeClassMethodSummaries();
588 void InitializeMethodSummaries();
Ted Kremenek896cd9d2008-10-23 01:56:15 +0000589private:
Ted Kremenek93edbc52011-10-05 23:54:29 +0000590 void addNSObjectClsMethSummary(Selector S, const RetainSummary *Summ) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000591 ObjCClassMethodSummaries[S] = Summ;
592 }
Mike Stump1eb44332009-09-09 15:08:12 +0000593
Ted Kremenek93edbc52011-10-05 23:54:29 +0000594 void addNSObjectMethSummary(Selector S, const RetainSummary *Summ) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000595 ObjCMethodSummaries[S] = Summ;
596 }
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +0000597
Ted Kremeneka9797122012-02-18 21:37:48 +0000598 void addClassMethSummary(const char* Cls, const char* name,
599 const RetainSummary *Summ, bool isNullary = true) {
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +0000600 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
Ted Kremeneka9797122012-02-18 21:37:48 +0000601 Selector S = isNullary ? GetNullarySelector(name, Ctx)
602 : GetUnarySelector(name, Ctx);
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +0000603 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
604 }
Mike Stump1eb44332009-09-09 15:08:12 +0000605
Ted Kremenek6c4becb2009-02-25 02:54:57 +0000606 void addInstMethSummary(const char* Cls, const char* nullaryName,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000607 const RetainSummary *Summ) {
Ted Kremenek6c4becb2009-02-25 02:54:57 +0000608 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
609 Selector S = GetNullarySelector(nullaryName, Ctx);
610 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
611 }
Mike Stump1eb44332009-09-09 15:08:12 +0000612
Ted Kremenekde4d5332009-04-24 17:50:11 +0000613 Selector generateSelector(va_list argp) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000614 SmallVector<IdentifierInfo*, 10> II;
Ted Kremenekde4d5332009-04-24 17:50:11 +0000615
Ted Kremenek9e476de2008-08-12 18:30:56 +0000616 while (const char* s = va_arg(argp, const char*))
617 II.push_back(&Ctx.Idents.get(s));
Ted Kremenekde4d5332009-04-24 17:50:11 +0000618
Mike Stump1eb44332009-09-09 15:08:12 +0000619 return Ctx.Selectors.getSelector(II.size(), &II[0]);
Ted Kremenekde4d5332009-04-24 17:50:11 +0000620 }
Mike Stump1eb44332009-09-09 15:08:12 +0000621
Ted Kremenekde4d5332009-04-24 17:50:11 +0000622 void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy& Summaries,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000623 const RetainSummary * Summ, va_list argp) {
Ted Kremenekde4d5332009-04-24 17:50:11 +0000624 Selector S = generateSelector(argp);
625 Summaries[ObjCSummaryKey(ClsII, S)] = Summ;
Ted Kremenek70a733e2008-07-18 17:24:20 +0000626 }
Mike Stump1eb44332009-09-09 15:08:12 +0000627
Ted Kremenek93edbc52011-10-05 23:54:29 +0000628 void addInstMethSummary(const char* Cls, const RetainSummary * Summ, ...) {
Ted Kremenekaf9dc272008-08-12 18:48:50 +0000629 va_list argp;
630 va_start(argp, Summ);
Ted Kremenekde4d5332009-04-24 17:50:11 +0000631 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Mike Stump1eb44332009-09-09 15:08:12 +0000632 va_end(argp);
Ted Kremenekaf9dc272008-08-12 18:48:50 +0000633 }
Mike Stump1eb44332009-09-09 15:08:12 +0000634
Ted Kremenek93edbc52011-10-05 23:54:29 +0000635 void addClsMethSummary(const char* Cls, const RetainSummary * Summ, ...) {
Ted Kremenekde4d5332009-04-24 17:50:11 +0000636 va_list argp;
637 va_start(argp, Summ);
638 addMethodSummary(&Ctx.Idents.get(Cls),ObjCClassMethodSummaries, Summ, argp);
639 va_end(argp);
640 }
Mike Stump1eb44332009-09-09 15:08:12 +0000641
Ted Kremenek93edbc52011-10-05 23:54:29 +0000642 void addClsMethSummary(IdentifierInfo *II, const RetainSummary * Summ, ...) {
Ted Kremenekde4d5332009-04-24 17:50:11 +0000643 va_list argp;
644 va_start(argp, Summ);
645 addMethodSummary(II, ObjCClassMethodSummaries, Summ, argp);
646 va_end(argp);
647 }
648
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000649public:
Mike Stump1eb44332009-09-09 15:08:12 +0000650
Ted Kremenek9c378f72011-08-12 23:37:29 +0000651 RetainSummaryManager(ASTContext &ctx, bool gcenabled, bool usesARC)
Ted Kremenek179064e2008-07-01 17:21:27 +0000652 : Ctx(ctx),
John McCallf85e1932011-06-15 23:02:42 +0000653 GCEnabled(gcenabled),
654 ARCEnabled(usesARC),
655 AF(BPAlloc), ScratchArgs(AF.getEmptyMap()),
656 ObjCAllocRetE(gcenabled
657 ? RetEffect::MakeGCNotOwned()
658 : (usesARC ? RetEffect::MakeARCNotOwned()
659 : RetEffect::MakeOwned(RetEffect::ObjC, true))),
660 ObjCInitRetE(gcenabled
661 ? RetEffect::MakeGCNotOwned()
662 : (usesARC ? RetEffect::MakeARCNotOwned()
Jordy Roseef945882012-03-18 01:26:10 +0000663 : RetEffect::MakeOwnedWhenTrackedReceiver())) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000664 InitializeClassMethodSummaries();
665 InitializeMethodSummaries();
666 }
Mike Stump1eb44332009-09-09 15:08:12 +0000667
Jordan Rose4531b7d2012-07-02 19:27:43 +0000668 const RetainSummary *getSummary(const CallEvent &Call,
669 ProgramStateRef State = 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000670
Jordan Rose4531b7d2012-07-02 19:27:43 +0000671 const RetainSummary *getFunctionSummary(const FunctionDecl *FD);
672
673 const RetainSummary *getMethodSummary(Selector S, const ObjCInterfaceDecl *ID,
Jordy Rosef3aae582012-03-17 21:13:07 +0000674 const ObjCMethodDecl *MD,
675 QualType RetTy,
676 ObjCMethodSummariesTy &CachedSummaries);
677
Jordan Rosecde8cdb2012-07-02 19:27:56 +0000678 const RetainSummary *getInstanceMethodSummary(const ObjCMethodCall &M,
Jordan Rose4531b7d2012-07-02 19:27:43 +0000679 ProgramStateRef State);
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000680
Jordan Rosecde8cdb2012-07-02 19:27:56 +0000681 const RetainSummary *getClassMethodSummary(const ObjCMethodCall &M) {
Jordan Rose4531b7d2012-07-02 19:27:43 +0000682 assert(!M.isInstanceMessage());
683 const ObjCInterfaceDecl *Class = M.getReceiverInterface();
Mike Stump1eb44332009-09-09 15:08:12 +0000684
Jordan Rose4531b7d2012-07-02 19:27:43 +0000685 return getMethodSummary(M.getSelector(), Class, M.getDecl(),
686 M.getResultType(), ObjCClassMethodSummaries);
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +0000687 }
Ted Kremenek552333c2009-04-29 17:17:48 +0000688
689 /// getMethodSummary - This version of getMethodSummary is used to query
690 /// the summary for the current method being analyzed.
Ted Kremenek93edbc52011-10-05 23:54:29 +0000691 const RetainSummary *getMethodSummary(const ObjCMethodDecl *MD) {
Ted Kremeneka8833552009-04-29 23:03:22 +0000692 const ObjCInterfaceDecl *ID = MD->getClassInterface();
Ted Kremenek70a65762009-04-30 05:41:14 +0000693 Selector S = MD->getSelector();
Ted Kremenek552333c2009-04-29 17:17:48 +0000694 QualType ResultTy = MD->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +0000695
Jordy Rosef3aae582012-03-17 21:13:07 +0000696 ObjCMethodSummariesTy *CachedSummaries;
Ted Kremenek552333c2009-04-29 17:17:48 +0000697 if (MD->isInstanceMethod())
Jordy Rosef3aae582012-03-17 21:13:07 +0000698 CachedSummaries = &ObjCMethodSummaries;
Ted Kremenek552333c2009-04-29 17:17:48 +0000699 else
Jordy Rosef3aae582012-03-17 21:13:07 +0000700 CachedSummaries = &ObjCClassMethodSummaries;
701
Jordan Rose4531b7d2012-07-02 19:27:43 +0000702 return getMethodSummary(S, ID, MD, ResultTy, *CachedSummaries);
Ted Kremenek552333c2009-04-29 17:17:48 +0000703 }
Mike Stump1eb44332009-09-09 15:08:12 +0000704
Jordy Rosef3aae582012-03-17 21:13:07 +0000705 const RetainSummary *getStandardMethodSummary(const ObjCMethodDecl *MD,
Jordan Rose4531b7d2012-07-02 19:27:43 +0000706 Selector S, QualType RetTy);
Ted Kremeneka8833552009-04-29 23:03:22 +0000707
Jordan Rose44405b72013-04-04 22:31:48 +0000708 /// Determine if there is a special return effect for this function or method.
709 Optional<RetEffect> getRetEffectFromAnnotations(QualType RetTy,
710 const Decl *D);
711
Ted Kremenek93edbc52011-10-05 23:54:29 +0000712 void updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenek4dd8fb42009-05-09 02:58:13 +0000713 const ObjCMethodDecl *MD);
714
Ted Kremenek93edbc52011-10-05 23:54:29 +0000715 void updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenek4dd8fb42009-05-09 02:58:13 +0000716 const FunctionDecl *FD);
717
Jordan Rose4531b7d2012-07-02 19:27:43 +0000718 void updateSummaryForCall(const RetainSummary *&Summ,
719 const CallEvent &Call);
720
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000721 bool isGCEnabled() const { return GCEnabled; }
Mike Stump1eb44332009-09-09 15:08:12 +0000722
John McCallf85e1932011-06-15 23:02:42 +0000723 bool isARCEnabled() const { return ARCEnabled; }
724
725 bool isARCorGCEnabled() const { return GCEnabled || ARCEnabled; }
Jordan Rose4531b7d2012-07-02 19:27:43 +0000726
727 RetEffect getObjAllocRetEffect() const { return ObjCAllocRetE; }
728
729 friend class RetainSummaryTemplate;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000730};
Mike Stump1eb44332009-09-09 15:08:12 +0000731
Jordy Rose0fe62f82011-08-24 09:02:37 +0000732// Used to avoid allocating long-term (BPAlloc'd) memory for default retain
733// summaries. If a function or method looks like it has a default summary, but
734// it has annotations, the annotations are added to the stack-based template
735// and then copied into managed memory.
736class RetainSummaryTemplate {
737 RetainSummaryManager &Manager;
Ted Kremenek93edbc52011-10-05 23:54:29 +0000738 const RetainSummary *&RealSummary;
Jordy Rose0fe62f82011-08-24 09:02:37 +0000739 RetainSummary ScratchSummary;
740 bool Accessed;
741public:
Jordan Rose4531b7d2012-07-02 19:27:43 +0000742 RetainSummaryTemplate(const RetainSummary *&real, RetainSummaryManager &mgr)
743 : Manager(mgr), RealSummary(real), ScratchSummary(*real), Accessed(false) {}
Jordy Rose0fe62f82011-08-24 09:02:37 +0000744
745 ~RetainSummaryTemplate() {
Ted Kremenek93edbc52011-10-05 23:54:29 +0000746 if (Accessed)
Jordy Roseef945882012-03-18 01:26:10 +0000747 RealSummary = Manager.getPersistentSummary(ScratchSummary);
Jordy Rose0fe62f82011-08-24 09:02:37 +0000748 }
749
750 RetainSummary &operator*() {
751 Accessed = true;
Ted Kremenek93edbc52011-10-05 23:54:29 +0000752 return ScratchSummary;
Jordy Rose0fe62f82011-08-24 09:02:37 +0000753 }
754
755 RetainSummary *operator->() {
756 Accessed = true;
Ted Kremenek93edbc52011-10-05 23:54:29 +0000757 return &ScratchSummary;
Jordy Rose0fe62f82011-08-24 09:02:37 +0000758 }
759};
760
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000761} // end anonymous namespace
762
763//===----------------------------------------------------------------------===//
764// Implementation of checker data structures.
765//===----------------------------------------------------------------------===//
766
Ted Kremenekb77449c2009-05-03 05:20:50 +0000767ArgEffects RetainSummaryManager::getArgEffects() {
768 ArgEffects AE = ScratchArgs;
Ted Kremenek3baf6722010-11-24 00:54:37 +0000769 ScratchArgs = AF.getEmptyMap();
Ted Kremenekb77449c2009-05-03 05:20:50 +0000770 return AE;
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000771}
772
Ted Kremenek93edbc52011-10-05 23:54:29 +0000773const RetainSummary *
Jordy Roseef945882012-03-18 01:26:10 +0000774RetainSummaryManager::getPersistentSummary(const RetainSummary &OldSumm) {
775 // Unique "simple" summaries -- those without ArgEffects.
776 if (OldSumm.isSimple()) {
777 llvm::FoldingSetNodeID ID;
778 OldSumm.Profile(ID);
779
780 void *Pos;
781 CachedSummaryNode *N = SimpleSummaries.FindNodeOrInsertPos(ID, Pos);
782
783 if (!N) {
784 N = (CachedSummaryNode *) BPAlloc.Allocate<CachedSummaryNode>();
785 new (N) CachedSummaryNode(OldSumm);
786 SimpleSummaries.InsertNode(N, Pos);
787 }
788
789 return &N->getValue();
790 }
791
Ted Kremenek93edbc52011-10-05 23:54:29 +0000792 RetainSummary *Summ = (RetainSummary *) BPAlloc.Allocate<RetainSummary>();
Jordy Roseef945882012-03-18 01:26:10 +0000793 new (Summ) RetainSummary(OldSumm);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000794 return Summ;
795}
796
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000797//===----------------------------------------------------------------------===//
798// Summary creation for functions (largely uses of Core Foundation).
799//===----------------------------------------------------------------------===//
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000800
Ted Kremenek9c378f72011-08-12 23:37:29 +0000801static bool isRetain(const FunctionDecl *FD, StringRef FName) {
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000802 return FName.endswith("Retain");
Ted Kremenek12619382009-01-12 21:45:02 +0000803}
804
Ted Kremenek9c378f72011-08-12 23:37:29 +0000805static bool isRelease(const FunctionDecl *FD, StringRef FName) {
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000806 return FName.endswith("Release");
Ted Kremenek12619382009-01-12 21:45:02 +0000807}
808
Jordy Rose76c506f2011-08-21 21:58:18 +0000809static bool isMakeCollectable(const FunctionDecl *FD, StringRef FName) {
810 // FIXME: Remove FunctionDecl parameter.
811 // FIXME: Is it really okay if MakeCollectable isn't a suffix?
812 return FName.find("MakeCollectable") != StringRef::npos;
813}
814
Anna Zaks554067f2012-08-29 23:23:43 +0000815static ArgEffect getStopTrackingHardEquivalent(ArgEffect E) {
Jordan Rose4531b7d2012-07-02 19:27:43 +0000816 switch (E) {
817 case DoNothing:
818 case Autorelease:
819 case DecRefBridgedTransfered:
820 case IncRef:
821 case IncRefMsg:
822 case MakeCollectable:
823 case MayEscape:
Jordan Rose4531b7d2012-07-02 19:27:43 +0000824 case StopTracking:
Anna Zaks554067f2012-08-29 23:23:43 +0000825 case StopTrackingHard:
826 return StopTrackingHard;
Jordan Rose4531b7d2012-07-02 19:27:43 +0000827 case DecRef:
Anna Zaks554067f2012-08-29 23:23:43 +0000828 case DecRefAndStopTrackingHard:
829 return DecRefAndStopTrackingHard;
Jordan Rose4531b7d2012-07-02 19:27:43 +0000830 case DecRefMsg:
Anna Zaks554067f2012-08-29 23:23:43 +0000831 case DecRefMsgAndStopTrackingHard:
832 return DecRefMsgAndStopTrackingHard;
Jordan Rose4531b7d2012-07-02 19:27:43 +0000833 case Dealloc:
834 return Dealloc;
835 }
836
837 llvm_unreachable("Unknown ArgEffect kind");
838}
839
840void RetainSummaryManager::updateSummaryForCall(const RetainSummary *&S,
841 const CallEvent &Call) {
842 if (Call.hasNonZeroCallbackArg()) {
Anna Zaks554067f2012-08-29 23:23:43 +0000843 ArgEffect RecEffect =
844 getStopTrackingHardEquivalent(S->getReceiverEffect());
845 ArgEffect DefEffect =
846 getStopTrackingHardEquivalent(S->getDefaultArgEffect());
Jordan Rose4531b7d2012-07-02 19:27:43 +0000847
848 ArgEffects CustomArgEffects = S->getArgEffects();
849 for (ArgEffects::iterator I = CustomArgEffects.begin(),
850 E = CustomArgEffects.end();
851 I != E; ++I) {
Anna Zaks554067f2012-08-29 23:23:43 +0000852 ArgEffect Translated = getStopTrackingHardEquivalent(I->second);
Jordan Rose4531b7d2012-07-02 19:27:43 +0000853 if (Translated != DefEffect)
854 ScratchArgs = AF.add(ScratchArgs, I->first, Translated);
855 }
856
Anna Zaks554067f2012-08-29 23:23:43 +0000857 RetEffect RE = RetEffect::MakeNoRetHard();
Jordan Rose4531b7d2012-07-02 19:27:43 +0000858
859 // Special cases where the callback argument CANNOT free the return value.
860 // This can generally only happen if we know that the callback will only be
861 // called when the return value is already being deallocated.
862 if (const FunctionCall *FC = dyn_cast<FunctionCall>(&Call)) {
Jordan Rose4a25f302012-09-01 17:39:13 +0000863 if (IdentifierInfo *Name = FC->getDecl()->getIdentifier()) {
864 // When the CGBitmapContext is deallocated, the callback here will free
865 // the associated data buffer.
Jordan Rosea89f7192012-08-31 18:19:18 +0000866 if (Name->isStr("CGBitmapContextCreateWithData"))
867 RE = S->getRetEffect();
Jordan Rose4a25f302012-09-01 17:39:13 +0000868 }
Jordan Rose4531b7d2012-07-02 19:27:43 +0000869 }
870
871 S = getPersistentSummary(RE, RecEffect, DefEffect);
872 }
Anna Zaks5a901932012-08-24 00:06:12 +0000873
874 // Special case '[super init];' and '[self init];'
875 //
876 // Even though calling '[super init]' without assigning the result to self
877 // and checking if the parent returns 'nil' is a bad pattern, it is common.
878 // Additionally, our Self Init checker already warns about it. To avoid
879 // overwhelming the user with messages from both checkers, we model the case
880 // of '[super init]' in cases when it is not consumed by another expression
881 // as if the call preserves the value of 'self'; essentially, assuming it can
882 // never fail and return 'nil'.
883 // Note, we don't want to just stop tracking the value since we want the
884 // RetainCount checker to report leaks and use-after-free if SelfInit checker
885 // is turned off.
886 if (const ObjCMethodCall *MC = dyn_cast<ObjCMethodCall>(&Call)) {
887 if (MC->getMethodFamily() == OMF_init && MC->isReceiverSelfOrSuper()) {
888
889 // Check if the message is not consumed, we know it will not be used in
890 // an assignment, ex: "self = [super init]".
891 const Expr *ME = MC->getOriginExpr();
892 const LocationContext *LCtx = MC->getLocationContext();
893 ParentMap &PM = LCtx->getAnalysisDeclContext()->getParentMap();
894 if (!PM.isConsumedExpr(ME)) {
895 RetainSummaryTemplate ModifiableSummaryTemplate(S, *this);
896 ModifiableSummaryTemplate->setReceiverEffect(DoNothing);
897 ModifiableSummaryTemplate->setRetEffect(RetEffect::MakeNoRet());
898 }
899 }
900
901 }
Jordan Rose4531b7d2012-07-02 19:27:43 +0000902}
903
Anna Zaks58822c42012-05-04 22:18:39 +0000904const RetainSummary *
Jordan Rose4531b7d2012-07-02 19:27:43 +0000905RetainSummaryManager::getSummary(const CallEvent &Call,
906 ProgramStateRef State) {
907 const RetainSummary *Summ;
908 switch (Call.getKind()) {
909 case CE_Function:
910 Summ = getFunctionSummary(cast<FunctionCall>(Call).getDecl());
911 break;
912 case CE_CXXMember:
Jordan Rosefdaa3382012-07-03 22:55:57 +0000913 case CE_CXXMemberOperator:
Jordan Rose4531b7d2012-07-02 19:27:43 +0000914 case CE_Block:
915 case CE_CXXConstructor:
Jordan Rose8d276d32012-07-10 22:07:47 +0000916 case CE_CXXDestructor:
Jordan Rose70cbf3c2012-07-02 22:21:47 +0000917 case CE_CXXAllocator:
Jordan Rose4531b7d2012-07-02 19:27:43 +0000918 // FIXME: These calls are currently unsupported.
919 return getPersistentStopSummary();
Jordan Rose8919e682012-07-18 21:59:51 +0000920 case CE_ObjCMessage: {
Jordan Rosecde8cdb2012-07-02 19:27:56 +0000921 const ObjCMethodCall &Msg = cast<ObjCMethodCall>(Call);
Jordan Rose4531b7d2012-07-02 19:27:43 +0000922 if (Msg.isInstanceMessage())
923 Summ = getInstanceMethodSummary(Msg, State);
924 else
925 Summ = getClassMethodSummary(Msg);
926 break;
927 }
928 }
929
930 updateSummaryForCall(Summ, Call);
931
932 assert(Summ && "Unknown call type?");
933 return Summ;
934}
935
936const RetainSummary *
937RetainSummaryManager::getFunctionSummary(const FunctionDecl *FD) {
938 // If we don't know what function we're calling, use our default summary.
939 if (!FD)
940 return getDefaultSummary();
941
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000942 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000943 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000944 if (I != FuncSummaries.end())
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000945 return I->second;
946
Ted Kremeneke401a0c2009-05-04 15:34:07 +0000947 // No summary? Generate one.
Ted Kremenek93edbc52011-10-05 23:54:29 +0000948 const RetainSummary *S = 0;
Jordan Rose15d18e12012-08-06 21:28:02 +0000949 bool AllowAnnotations = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000950
Ted Kremenek37d785b2008-07-15 16:50:12 +0000951 do {
Ted Kremenek12619382009-01-12 21:45:02 +0000952 // We generate "stop" summaries for implicitly defined functions.
953 if (FD->isImplicit()) {
954 S = getPersistentStopSummary();
955 break;
Ted Kremenek37d785b2008-07-15 16:50:12 +0000956 }
Mike Stump1eb44332009-09-09 15:08:12 +0000957
John McCall183700f2009-09-21 23:43:11 +0000958 // [PR 3337] Use 'getAs<FunctionType>' to strip away any typedefs on the
Ted Kremenek99890652009-01-16 18:40:33 +0000959 // function's type.
John McCall183700f2009-09-21 23:43:11 +0000960 const FunctionType* FT = FD->getType()->getAs<FunctionType>();
Ted Kremenek48c6d182009-12-16 06:06:43 +0000961 const IdentifierInfo *II = FD->getIdentifier();
962 if (!II)
963 break;
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000964
965 StringRef FName = II->getName();
Mike Stump1eb44332009-09-09 15:08:12 +0000966
Ted Kremenekbf0a4dd2009-03-05 22:11:14 +0000967 // Strip away preceding '_'. Doing this here will effect all the checks
968 // down below.
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000969 FName = FName.substr(FName.find_first_not_of('_'));
Mike Stump1eb44332009-09-09 15:08:12 +0000970
Ted Kremenek12619382009-01-12 21:45:02 +0000971 // Inspect the result type.
972 QualType RetTy = FT->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +0000973
Ted Kremenek12619382009-01-12 21:45:02 +0000974 // FIXME: This should all be refactored into a chain of "summary lookup"
975 // filters.
Ted Kremenek008636a2009-10-14 00:27:24 +0000976 assert(ScratchArgs.isEmpty());
Ted Kremenek39d88b02009-06-15 20:36:07 +0000977
Ted Kremenekbefc6d22012-04-26 04:32:23 +0000978 if (FName == "pthread_create" || FName == "pthread_setspecific") {
979 // Part of: <rdar://problem/7299394> and <rdar://problem/11282706>.
980 // This will be addressed better with IPA.
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000981 S = getPersistentStopSummary();
982 } else if (FName == "NSMakeCollectable") {
983 // Handle: id NSMakeCollectable(CFTypeRef)
984 S = (RetTy->isObjCIdType())
985 ? getUnarySummary(FT, cfmakecollectable)
986 : getPersistentStopSummary();
Jordan Rose15d18e12012-08-06 21:28:02 +0000987 // The headers on OS X 10.8 use cf_consumed/ns_returns_retained,
988 // but we can fully model NSMakeCollectable ourselves.
989 AllowAnnotations = false;
Ted Kremenek061707a2012-09-06 23:47:02 +0000990 } else if (FName == "CFPlugInInstanceCreate") {
991 S = getPersistentSummary(RetEffect::MakeNoRet());
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000992 } else if (FName == "IOBSDNameMatching" ||
993 FName == "IOServiceMatching" ||
994 FName == "IOServiceNameMatching" ||
Ted Kremenek537dd3a2012-05-01 05:28:27 +0000995 FName == "IORegistryEntrySearchCFProperty" ||
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000996 FName == "IORegistryEntryIDMatching" ||
997 FName == "IOOpenFirmwarePathMatching") {
998 // Part of <rdar://problem/6961230>. (IOKit)
999 // This should be addressed using a API table.
1000 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1001 DoNothing, DoNothing);
1002 } else if (FName == "IOServiceGetMatchingService" ||
1003 FName == "IOServiceGetMatchingServices") {
1004 // FIXES: <rdar://problem/6326900>
1005 // This should be addressed using a API table. This strcmp is also
1006 // a little gross, but there is no need to super optimize here.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001007 ScratchArgs = AF.add(ScratchArgs, 1, DecRef);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001008 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1009 } else if (FName == "IOServiceAddNotification" ||
1010 FName == "IOServiceAddMatchingNotification") {
1011 // Part of <rdar://problem/6961230>. (IOKit)
1012 // This should be addressed using a API table.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001013 ScratchArgs = AF.add(ScratchArgs, 2, DecRef);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001014 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1015 } else if (FName == "CVPixelBufferCreateWithBytes") {
1016 // FIXES: <rdar://problem/7283567>
1017 // Eventually this can be improved by recognizing that the pixel
1018 // buffer passed to CVPixelBufferCreateWithBytes is released via
1019 // a callback and doing full IPA to make sure this is done correctly.
1020 // FIXME: This function has an out parameter that returns an
1021 // allocated object.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001022 ScratchArgs = AF.add(ScratchArgs, 7, StopTracking);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001023 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1024 } else if (FName == "CGBitmapContextCreateWithData") {
1025 // FIXES: <rdar://problem/7358899>
1026 // Eventually this can be improved by recognizing that 'releaseInfo'
1027 // passed to CGBitmapContextCreateWithData is released via
1028 // a callback and doing full IPA to make sure this is done correctly.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001029 ScratchArgs = AF.add(ScratchArgs, 8, StopTracking);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001030 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1031 DoNothing, DoNothing);
1032 } else if (FName == "CVPixelBufferCreateWithPlanarBytes") {
1033 // FIXES: <rdar://problem/7283567>
1034 // Eventually this can be improved by recognizing that the pixel
1035 // buffer passed to CVPixelBufferCreateWithPlanarBytes is released
1036 // via a callback and doing full IPA to make sure this is done
1037 // correctly.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001038 ScratchArgs = AF.add(ScratchArgs, 12, StopTracking);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001039 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Jordan Rose8a729b42013-05-02 01:51:40 +00001040 } else if (FName == "dispatch_set_context" ||
1041 FName == "xpc_connection_set_context") {
Ted Kremenek06911d42012-03-22 06:29:41 +00001042 // <rdar://problem/11059275> - The analyzer currently doesn't have
1043 // a good way to reason about the finalizer function for libdispatch.
1044 // If we pass a context object that is memory managed, stop tracking it.
Jordan Rose8a729b42013-05-02 01:51:40 +00001045 // <rdar://problem/13783514> - Same problem, but for XPC.
Ted Kremenek06911d42012-03-22 06:29:41 +00001046 // FIXME: this hack should possibly go away once we can handle
Jordan Rose8a729b42013-05-02 01:51:40 +00001047 // libdispatch and XPC finalizers.
Ted Kremenek06911d42012-03-22 06:29:41 +00001048 ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
1049 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenekc91fdf62012-05-08 00:12:09 +00001050 } else if (FName.startswith("NSLog")) {
1051 S = getDoNothingSummary();
Anna Zaks62a5c342012-03-30 05:48:16 +00001052 } else if (FName.startswith("NS") &&
1053 (FName.find("Insert") != StringRef::npos)) {
1054 // Whitelist NSXXInsertXX, for example NSMapInsertIfAbsent, since they can
1055 // be deallocated by NSMapRemove. (radar://11152419)
1056 ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
1057 ScratchArgs = AF.add(ScratchArgs, 2, StopTracking);
1058 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenekb04cb592009-06-11 18:17:24 +00001059 }
Mike Stump1eb44332009-09-09 15:08:12 +00001060
Ted Kremenekb04cb592009-06-11 18:17:24 +00001061 // Did we get a summary?
1062 if (S)
1063 break;
Ted Kremenek61991902009-03-17 22:43:44 +00001064
Jordan Rose5aff3f12013-03-04 23:21:32 +00001065 if (RetTy->isPointerType()) {
Ted Kremenek12619382009-01-12 21:45:02 +00001066 // For CoreFoundation ('CF') types.
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001067 if (cocoa::isRefType(RetTy, "CF", FName)) {
Ted Kremenek12619382009-01-12 21:45:02 +00001068 if (isRetain(FD, FName))
1069 S = getUnarySummary(FT, cfretain);
Jordy Rose76c506f2011-08-21 21:58:18 +00001070 else if (isMakeCollectable(FD, FName))
Ted Kremenek12619382009-01-12 21:45:02 +00001071 S = getUnarySummary(FT, cfmakecollectable);
Mike Stump1eb44332009-09-09 15:08:12 +00001072 else
John McCall7df2ff42011-10-01 00:48:56 +00001073 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek12619382009-01-12 21:45:02 +00001074
1075 break;
1076 }
1077
1078 // For CoreGraphics ('CG') types.
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001079 if (cocoa::isRefType(RetTy, "CG", FName)) {
Ted Kremenek12619382009-01-12 21:45:02 +00001080 if (isRetain(FD, FName))
1081 S = getUnarySummary(FT, cfretain);
1082 else
John McCall7df2ff42011-10-01 00:48:56 +00001083 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek12619382009-01-12 21:45:02 +00001084
1085 break;
1086 }
1087
1088 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001089 if (cocoa::isRefType(RetTy, "DADisk") ||
1090 cocoa::isRefType(RetTy, "DADissenter") ||
1091 cocoa::isRefType(RetTy, "DASessionRef")) {
John McCall7df2ff42011-10-01 00:48:56 +00001092 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek12619382009-01-12 21:45:02 +00001093 break;
1094 }
Mike Stump1eb44332009-09-09 15:08:12 +00001095
Jordan Rose5aff3f12013-03-04 23:21:32 +00001096 if (FD->getAttr<CFAuditedTransferAttr>()) {
1097 S = getCFCreateGetRuleSummary(FD);
1098 break;
1099 }
1100
Ted Kremenek12619382009-01-12 21:45:02 +00001101 break;
1102 }
1103
1104 // Check for release functions, the only kind of functions that we care
1105 // about that don't return a pointer type.
1106 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
Ted Kremeneke7d03122010-02-08 16:45:01 +00001107 // Test for 'CGCF'.
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001108 FName = FName.substr(FName.startswith("CGCF") ? 4 : 2);
Ted Kremeneke7d03122010-02-08 16:45:01 +00001109
Ted Kremenekbf0a4dd2009-03-05 22:11:14 +00001110 if (isRelease(FD, FName))
Ted Kremenek12619382009-01-12 21:45:02 +00001111 S = getUnarySummary(FT, cfrelease);
1112 else {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001113 assert (ScratchArgs.isEmpty());
Ted Kremenek68189282009-01-29 22:45:13 +00001114 // Remaining CoreFoundation and CoreGraphics functions.
1115 // We use to assume that they all strictly followed the ownership idiom
1116 // and that ownership cannot be transferred. While this is technically
1117 // correct, many methods allow a tracked object to escape. For example:
1118 //
Mike Stump1eb44332009-09-09 15:08:12 +00001119 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
Ted Kremenek68189282009-01-29 22:45:13 +00001120 // CFDictionaryAddValue(y, key, x);
Mike Stump1eb44332009-09-09 15:08:12 +00001121 // CFRelease(x);
Ted Kremenek68189282009-01-29 22:45:13 +00001122 // ... it is okay to use 'x' since 'y' has a reference to it
1123 //
1124 // We handle this and similar cases with the follow heuristic. If the
Ted Kremenekc4843812009-08-20 00:57:22 +00001125 // function name contains "InsertValue", "SetValue", "AddValue",
1126 // "AppendValue", or "SetAttribute", then we assume that arguments may
1127 // "escape." This means that something else holds on to the object,
1128 // allowing it be used even after its local retain count drops to 0.
Benjamin Kramere45c1492010-01-11 19:46:28 +00001129 ArgEffect E = (StrInStrNoCase(FName, "InsertValue") != StringRef::npos||
1130 StrInStrNoCase(FName, "AddValue") != StringRef::npos ||
1131 StrInStrNoCase(FName, "SetValue") != StringRef::npos ||
1132 StrInStrNoCase(FName, "AppendValue") != StringRef::npos||
Benjamin Kramerc027e542010-01-11 20:15:06 +00001133 StrInStrNoCase(FName, "SetAttribute") != StringRef::npos)
Ted Kremenek68189282009-01-29 22:45:13 +00001134 ? MayEscape : DoNothing;
Mike Stump1eb44332009-09-09 15:08:12 +00001135
Ted Kremenek68189282009-01-29 22:45:13 +00001136 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek12619382009-01-12 21:45:02 +00001137 }
1138 }
Ted Kremenek37d785b2008-07-15 16:50:12 +00001139 }
1140 while (0);
Mike Stump1eb44332009-09-09 15:08:12 +00001141
Jordan Rose4531b7d2012-07-02 19:27:43 +00001142 // If we got all the way here without any luck, use a default summary.
1143 if (!S)
1144 S = getDefaultSummary();
1145
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001146 // Annotations override defaults.
Jordan Rose15d18e12012-08-06 21:28:02 +00001147 if (AllowAnnotations)
1148 updateSummaryFromAnnotations(S, FD);
Mike Stump1eb44332009-09-09 15:08:12 +00001149
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001150 FuncSummaries[FD] = S;
Mike Stump1eb44332009-09-09 15:08:12 +00001151 return S;
Ted Kremenek2fff37e2008-03-06 00:08:09 +00001152}
1153
Ted Kremenek93edbc52011-10-05 23:54:29 +00001154const RetainSummary *
John McCall7df2ff42011-10-01 00:48:56 +00001155RetainSummaryManager::getCFCreateGetRuleSummary(const FunctionDecl *FD) {
1156 if (coreFoundation::followsCreateRule(FD))
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001157 return getCFSummaryCreateRule(FD);
Mike Stump1eb44332009-09-09 15:08:12 +00001158
Ted Kremenekd368d712011-05-25 06:19:45 +00001159 return getCFSummaryGetRule(FD);
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001160}
1161
Ted Kremenek93edbc52011-10-05 23:54:29 +00001162const RetainSummary *
Ted Kremenek6ad315a2009-02-23 16:51:39 +00001163RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1164 UnaryFuncKind func) {
1165
Ted Kremenek12619382009-01-12 21:45:02 +00001166 // Sanity check that this is *really* a unary function. This can
1167 // happen if people do weird things.
Douglas Gregor72564e72009-02-26 23:50:07 +00001168 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
Ted Kremenek12619382009-01-12 21:45:02 +00001169 if (!FTP || FTP->getNumArgs() != 1)
1170 return getPersistentStopSummary();
Mike Stump1eb44332009-09-09 15:08:12 +00001171
Ted Kremenekb77449c2009-05-03 05:20:50 +00001172 assert (ScratchArgs.isEmpty());
Mike Stump1eb44332009-09-09 15:08:12 +00001173
Jordy Rose76c506f2011-08-21 21:58:18 +00001174 ArgEffect Effect;
Ted Kremenek377e2302008-04-29 05:33:51 +00001175 switch (func) {
Jordy Rose76c506f2011-08-21 21:58:18 +00001176 case cfretain: Effect = IncRef; break;
1177 case cfrelease: Effect = DecRef; break;
1178 case cfmakecollectable: Effect = MakeCollectable; break;
Ted Kremenek940b1d82008-04-10 23:44:06 +00001179 }
Jordy Rose76c506f2011-08-21 21:58:18 +00001180
1181 ScratchArgs = AF.add(ScratchArgs, 0, Effect);
1182 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001183}
1184
Ted Kremenek93edbc52011-10-05 23:54:29 +00001185const RetainSummary *
Ted Kremenek9c378f72011-08-12 23:37:29 +00001186RetainSummaryManager::getCFSummaryCreateRule(const FunctionDecl *FD) {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001187 assert (ScratchArgs.isEmpty());
Mike Stump1eb44332009-09-09 15:08:12 +00001188
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001189 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001190}
1191
Ted Kremenek93edbc52011-10-05 23:54:29 +00001192const RetainSummary *
Ted Kremenek9c378f72011-08-12 23:37:29 +00001193RetainSummaryManager::getCFSummaryGetRule(const FunctionDecl *FD) {
Mike Stump1eb44332009-09-09 15:08:12 +00001194 assert (ScratchArgs.isEmpty());
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001195 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1196 DoNothing, DoNothing);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001197}
1198
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001199//===----------------------------------------------------------------------===//
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001200// Summary creation for Selectors.
1201//===----------------------------------------------------------------------===//
1202
Jordan Rose44405b72013-04-04 22:31:48 +00001203Optional<RetEffect>
1204RetainSummaryManager::getRetEffectFromAnnotations(QualType RetTy,
1205 const Decl *D) {
1206 if (cocoa::isCocoaObjectRef(RetTy)) {
1207 if (D->getAttr<NSReturnsRetainedAttr>())
1208 return ObjCAllocRetE;
1209
1210 if (D->getAttr<NSReturnsNotRetainedAttr>() ||
1211 D->getAttr<NSReturnsAutoreleasedAttr>())
1212 return RetEffect::MakeNotOwned(RetEffect::ObjC);
1213
1214 } else if (!RetTy->isPointerType()) {
1215 return None;
1216 }
1217
1218 if (D->getAttr<CFReturnsRetainedAttr>())
1219 return RetEffect::MakeOwned(RetEffect::CF, true);
1220
1221 if (D->getAttr<CFReturnsNotRetainedAttr>())
1222 return RetEffect::MakeNotOwned(RetEffect::CF);
1223
1224 return None;
1225}
1226
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001227void
Ted Kremenek93edbc52011-10-05 23:54:29 +00001228RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001229 const FunctionDecl *FD) {
1230 if (!FD)
1231 return;
1232
Jordan Rose4531b7d2012-07-02 19:27:43 +00001233 assert(Summ && "Must have a summary to add annotations to.");
1234 RetainSummaryTemplate Template(Summ, *this);
Jordy Rose4df54fe2011-08-23 04:27:15 +00001235
Ted Kremenek11fe1752011-01-27 18:43:03 +00001236 // Effects on the parameters.
1237 unsigned parm_idx = 0;
1238 for (FunctionDecl::param_const_iterator pi = FD->param_begin(),
John McCall98b8f162011-04-06 09:02:12 +00001239 pe = FD->param_end(); pi != pe; ++pi, ++parm_idx) {
Ted Kremenek11fe1752011-01-27 18:43:03 +00001240 const ParmVarDecl *pd = *pi;
Jordan Rose44405b72013-04-04 22:31:48 +00001241 if (pd->getAttr<NSConsumedAttr>())
1242 Template->addArg(AF, parm_idx, DecRefMsg);
1243 else if (pd->getAttr<CFConsumedAttr>())
Jordy Rose0fe62f82011-08-24 09:02:37 +00001244 Template->addArg(AF, parm_idx, DecRef);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001245 }
1246
Ted Kremenekb04cb592009-06-11 18:17:24 +00001247 QualType RetTy = FD->getResultType();
Jordan Rose44405b72013-04-04 22:31:48 +00001248 if (Optional<RetEffect> RetE = getRetEffectFromAnnotations(RetTy, FD))
1249 Template->setRetEffect(*RetE);
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001250}
1251
1252void
Ted Kremenek93edbc52011-10-05 23:54:29 +00001253RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
1254 const ObjCMethodDecl *MD) {
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001255 if (!MD)
1256 return;
1257
Jordan Rose4531b7d2012-07-02 19:27:43 +00001258 assert(Summ && "Must have a valid summary to add annotations to");
1259 RetainSummaryTemplate Template(Summ, *this);
Mike Stump1eb44332009-09-09 15:08:12 +00001260
Ted Kremenek12b94342011-01-27 06:54:14 +00001261 // Effects on the receiver.
Jordan Rose44405b72013-04-04 22:31:48 +00001262 if (MD->getAttr<NSConsumesSelfAttr>())
1263 Template->setReceiverEffect(DecRefMsg);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001264
1265 // Effects on the parameters.
1266 unsigned parm_idx = 0;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00001267 for (ObjCMethodDecl::param_const_iterator
1268 pi=MD->param_begin(), pe=MD->param_end();
Ted Kremenek11fe1752011-01-27 18:43:03 +00001269 pi != pe; ++pi, ++parm_idx) {
1270 const ParmVarDecl *pd = *pi;
Jordan Rose44405b72013-04-04 22:31:48 +00001271 if (pd->getAttr<NSConsumedAttr>())
1272 Template->addArg(AF, parm_idx, DecRefMsg);
1273 else if (pd->getAttr<CFConsumedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001274 Template->addArg(AF, parm_idx, DecRef);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001275 }
Ted Kremenek12b94342011-01-27 06:54:14 +00001276 }
1277
Jordan Rose44405b72013-04-04 22:31:48 +00001278 QualType RetTy = MD->getResultType();
1279 if (Optional<RetEffect> RetE = getRetEffectFromAnnotations(RetTy, MD))
1280 Template->setRetEffect(*RetE);
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001281}
1282
Ted Kremenek93edbc52011-10-05 23:54:29 +00001283const RetainSummary *
Jordy Rosef3aae582012-03-17 21:13:07 +00001284RetainSummaryManager::getStandardMethodSummary(const ObjCMethodDecl *MD,
1285 Selector S, QualType RetTy) {
Jordy Rosee921b1a2012-03-17 19:53:04 +00001286 // Any special effects?
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001287 ArgEffect ReceiverEff = DoNothing;
Jordy Rosee921b1a2012-03-17 19:53:04 +00001288 RetEffect ResultEff = RetEffect::MakeNoRet();
1289
1290 // Check the method family, and apply any default annotations.
1291 switch (MD ? MD->getMethodFamily() : S.getMethodFamily()) {
1292 case OMF_None:
1293 case OMF_performSelector:
1294 // Assume all Objective-C methods follow Cocoa Memory Management rules.
1295 // FIXME: Does the non-threaded performSelector family really belong here?
1296 // The selector could be, say, @selector(copy).
1297 if (cocoa::isCocoaObjectRef(RetTy))
1298 ResultEff = RetEffect::MakeNotOwned(RetEffect::ObjC);
1299 else if (coreFoundation::isCFObjectRef(RetTy)) {
1300 // ObjCMethodDecl currently doesn't consider CF objects as valid return
1301 // values for alloc, new, copy, or mutableCopy, so we have to
1302 // double-check with the selector. This is ugly, but there aren't that
1303 // many Objective-C methods that return CF objects, right?
1304 if (MD) {
1305 switch (S.getMethodFamily()) {
1306 case OMF_alloc:
1307 case OMF_new:
1308 case OMF_copy:
1309 case OMF_mutableCopy:
1310 ResultEff = RetEffect::MakeOwned(RetEffect::CF, true);
1311 break;
1312 default:
1313 ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1314 break;
1315 }
1316 } else {
1317 ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1318 }
1319 }
1320 break;
1321 case OMF_init:
1322 ResultEff = ObjCInitRetE;
1323 ReceiverEff = DecRefMsg;
1324 break;
1325 case OMF_alloc:
1326 case OMF_new:
1327 case OMF_copy:
1328 case OMF_mutableCopy:
1329 if (cocoa::isCocoaObjectRef(RetTy))
1330 ResultEff = ObjCAllocRetE;
1331 else if (coreFoundation::isCFObjectRef(RetTy))
1332 ResultEff = RetEffect::MakeOwned(RetEffect::CF, true);
1333 break;
1334 case OMF_autorelease:
1335 ReceiverEff = Autorelease;
1336 break;
1337 case OMF_retain:
1338 ReceiverEff = IncRefMsg;
1339 break;
1340 case OMF_release:
1341 ReceiverEff = DecRefMsg;
1342 break;
1343 case OMF_dealloc:
1344 ReceiverEff = Dealloc;
1345 break;
1346 case OMF_self:
1347 // -self is handled specially by the ExprEngine to propagate the receiver.
1348 break;
1349 case OMF_retainCount:
1350 case OMF_finalize:
1351 // These methods don't return objects.
1352 break;
1353 }
Mike Stump1eb44332009-09-09 15:08:12 +00001354
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001355 // If one of the arguments in the selector has the keyword 'delegate' we
1356 // should stop tracking the reference count for the receiver. This is
1357 // because the reference count is quite possibly handled by a delegate
1358 // method.
1359 if (S.isKeywordSelector()) {
Jordan Rose50571a92012-06-15 18:19:52 +00001360 for (unsigned i = 0, e = S.getNumArgs(); i != e; ++i) {
1361 StringRef Slot = S.getNameForSlot(i);
1362 if (Slot.substr(Slot.size() - 8).equals_lower("delegate")) {
1363 if (ResultEff == ObjCInitRetE)
Anna Zaks554067f2012-08-29 23:23:43 +00001364 ResultEff = RetEffect::MakeNoRetHard();
Jordan Rose50571a92012-06-15 18:19:52 +00001365 else
Anna Zaks554067f2012-08-29 23:23:43 +00001366 ReceiverEff = StopTrackingHard;
Jordan Rose50571a92012-06-15 18:19:52 +00001367 }
1368 }
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001369 }
Mike Stump1eb44332009-09-09 15:08:12 +00001370
Jordy Rosee921b1a2012-03-17 19:53:04 +00001371 if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing &&
1372 ResultEff.getKind() == RetEffect::NoRet)
Ted Kremenek93edbc52011-10-05 23:54:29 +00001373 return getDefaultSummary();
Mike Stump1eb44332009-09-09 15:08:12 +00001374
Jordy Rosee921b1a2012-03-17 19:53:04 +00001375 return getPersistentSummary(ResultEff, ReceiverEff, MayEscape);
Ted Kremenek250b1fa2009-04-23 23:08:22 +00001376}
1377
Ted Kremenek93edbc52011-10-05 23:54:29 +00001378const RetainSummary *
Jordan Rosecde8cdb2012-07-02 19:27:56 +00001379RetainSummaryManager::getInstanceMethodSummary(const ObjCMethodCall &Msg,
Jordan Rose4531b7d2012-07-02 19:27:43 +00001380 ProgramStateRef State) {
1381 const ObjCInterfaceDecl *ReceiverClass = 0;
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001382
Jordan Rose4531b7d2012-07-02 19:27:43 +00001383 // We do better tracking of the type of the object than the core ExprEngine.
1384 // See if we have its type in our private state.
1385 // FIXME: Eventually replace the use of state->get<RefBindings> with
1386 // a generic API for reasoning about the Objective-C types of symbolic
1387 // objects.
1388 SVal ReceiverV = Msg.getReceiverSVal();
1389 if (SymbolRef Sym = ReceiverV.getAsLocSymbol())
Anna Zaks8d6b43c2012-08-14 00:36:15 +00001390 if (const RefVal *T = getRefBinding(State, Sym))
Douglas Gregor04badcf2010-04-21 00:45:42 +00001391 if (const ObjCObjectPointerType *PT =
Jordan Rose4531b7d2012-07-02 19:27:43 +00001392 T->getType()->getAs<ObjCObjectPointerType>())
1393 ReceiverClass = PT->getInterfaceDecl();
1394
1395 // If we don't know what kind of object this is, fall back to its static type.
1396 if (!ReceiverClass)
1397 ReceiverClass = Msg.getReceiverInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00001398
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001399 // FIXME: The receiver could be a reference to a class, meaning that
1400 // we should use the class method.
Jordan Rose4531b7d2012-07-02 19:27:43 +00001401 // id x = [NSObject class];
1402 // [x performSelector:... withObject:... afterDelay:...];
1403 Selector S = Msg.getSelector();
1404 const ObjCMethodDecl *Method = Msg.getDecl();
1405 if (!Method && ReceiverClass)
1406 Method = ReceiverClass->getInstanceMethod(S);
1407
1408 return getMethodSummary(S, ReceiverClass, Method, Msg.getResultType(),
1409 ObjCMethodSummaries);
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001410}
1411
Ted Kremenek93edbc52011-10-05 23:54:29 +00001412const RetainSummary *
Jordan Rose4531b7d2012-07-02 19:27:43 +00001413RetainSummaryManager::getMethodSummary(Selector S, const ObjCInterfaceDecl *ID,
Jordy Rosef3aae582012-03-17 21:13:07 +00001414 const ObjCMethodDecl *MD, QualType RetTy,
1415 ObjCMethodSummariesTy &CachedSummaries) {
Ted Kremenek1bffd742008-05-06 15:44:25 +00001416
Ted Kremenek8711c032009-04-29 05:04:30 +00001417 // Look up a summary in our summary cache.
Jordan Rose4531b7d2012-07-02 19:27:43 +00001418 const RetainSummary *Summ = CachedSummaries.find(ID, S);
Mike Stump1eb44332009-09-09 15:08:12 +00001419
Ted Kremenek614cc542009-07-21 23:27:57 +00001420 if (!Summ) {
Jordy Rosef3aae582012-03-17 21:13:07 +00001421 Summ = getStandardMethodSummary(MD, S, RetTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001422
Ted Kremenek614cc542009-07-21 23:27:57 +00001423 // Annotations override defaults.
Jordy Rose4df54fe2011-08-23 04:27:15 +00001424 updateSummaryFromAnnotations(Summ, MD);
Mike Stump1eb44332009-09-09 15:08:12 +00001425
Ted Kremenek614cc542009-07-21 23:27:57 +00001426 // Memoize the summary.
Jordan Rose4531b7d2012-07-02 19:27:43 +00001427 CachedSummaries[ObjCSummaryKey(ID, S)] = Summ;
Ted Kremenek614cc542009-07-21 23:27:57 +00001428 }
Mike Stump1eb44332009-09-09 15:08:12 +00001429
Ted Kremeneke87450e2009-04-23 19:11:35 +00001430 return Summ;
Ted Kremenekc8395602008-05-06 21:26:51 +00001431}
1432
Mike Stump1eb44332009-09-09 15:08:12 +00001433void RetainSummaryManager::InitializeClassMethodSummaries() {
Ted Kremenekec315332009-05-07 23:40:42 +00001434 assert(ScratchArgs.isEmpty());
Mike Stump1eb44332009-09-09 15:08:12 +00001435 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek6fe2b7a2009-10-15 22:25:12 +00001436 addClassMethSummary("NSAssertionHandler", "currentHandler",
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001437 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Mike Stump1eb44332009-09-09 15:08:12 +00001438
Ted Kremenek6d348932008-10-21 15:53:15 +00001439 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001440 ScratchArgs = AF.add(ScratchArgs, 0, Autorelease);
Ted Kremenek6fe2b7a2009-10-15 22:25:12 +00001441 addClassMethSummary("NSAutoreleasePool", "addObject",
1442 getPersistentSummary(RetEffect::MakeNoRet(),
1443 DoNothing, Autorelease));
Ted Kremenek9c32d082008-05-06 00:30:21 +00001444}
1445
Ted Kremenek1f180c32008-06-23 22:21:20 +00001446void RetainSummaryManager::InitializeMethodSummaries() {
Mike Stump1eb44332009-09-09 15:08:12 +00001447
1448 assert (ScratchArgs.isEmpty());
1449
Ted Kremenekc8395602008-05-06 21:26:51 +00001450 // Create the "init" selector. It just acts as a pass-through for the
1451 // receiver.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001452 const RetainSummary *InitSumm = getPersistentSummary(ObjCInitRetE, DecRefMsg);
Ted Kremenekac02f202009-08-20 05:13:36 +00001453 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
1454
1455 // awakeAfterUsingCoder: behaves basically like an 'init' method. It
1456 // claims the receiver and returns a retained object.
1457 addNSObjectMethSummary(GetUnarySelector("awakeAfterUsingCoder", Ctx),
1458 InitSumm);
Mike Stump1eb44332009-09-09 15:08:12 +00001459
Ted Kremenekc8395602008-05-06 21:26:51 +00001460 // The next methods are allocators.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001461 const RetainSummary *AllocSumm = getPersistentSummary(ObjCAllocRetE);
1462 const RetainSummary *CFAllocSumm =
Ted Kremeneka834fb42009-08-28 19:52:12 +00001463 getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Mike Stump1eb44332009-09-09 15:08:12 +00001464
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001465 // Create the "retain" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001466 RetEffect NoRet = RetEffect::MakeNoRet();
Ted Kremenek93edbc52011-10-05 23:54:29 +00001467 const RetainSummary *Summ = getPersistentSummary(NoRet, IncRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001468 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001469
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001470 // Create the "release" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001471 Summ = getPersistentSummary(NoRet, DecRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001472 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001473
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001474 // Create the -dealloc summary.
Jordy Rose500abad2011-08-21 19:41:36 +00001475 Summ = getPersistentSummary(NoRet, Dealloc);
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001476 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001477
1478 // Create the "autorelease" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001479 Summ = getPersistentSummary(NoRet, Autorelease);
Ted Kremenek553cf182008-06-25 21:21:56 +00001480 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001481
Mike Stump1eb44332009-09-09 15:08:12 +00001482 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremenek89e202d2009-02-23 02:51:29 +00001483 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1484 // self-own themselves. However, they only do this once they are displayed.
1485 // Thus, we need to track an NSWindow's display status.
1486 // This is tracked in <rdar://problem/6062711>.
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +00001487 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001488 const RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenek78a35a32009-05-12 20:06:54 +00001489 StopTracking,
1490 StopTracking);
Mike Stump1eb44332009-09-09 15:08:12 +00001491
Ted Kremenek99d02692009-04-03 19:02:51 +00001492 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1493
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001494 // For NSPanel (which subclasses NSWindow), allocated objects are not
1495 // self-owned.
Ted Kremenek99d02692009-04-03 19:02:51 +00001496 // FIXME: For now we don't track NSPanels. object for the same reason
1497 // as for NSWindow objects.
1498 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
Mike Stump1eb44332009-09-09 15:08:12 +00001499
Jordan Rosee36d81b2013-01-31 22:06:02 +00001500 // Don't track allocated autorelease pools, as it is okay to prematurely
Ted Kremenekba67f6a2009-05-18 23:14:34 +00001501 // exit a method.
1502 addClassMethSummary("NSAutoreleasePool", "alloc", NoTrackYet);
Ted Kremeneka9797122012-02-18 21:37:48 +00001503 addClassMethSummary("NSAutoreleasePool", "allocWithZone", NoTrackYet, false);
Jordan Rosee36d81b2013-01-31 22:06:02 +00001504 addClassMethSummary("NSAutoreleasePool", "new", NoTrackYet);
Ted Kremenek553cf182008-06-25 21:21:56 +00001505
Ted Kremenek767d6492009-05-20 22:39:57 +00001506 // Create summaries QCRenderer/QCView -createSnapShotImageOfType:
1507 addInstMethSummary("QCRenderer", AllocSumm,
1508 "createSnapshotImageOfType", NULL);
1509 addInstMethSummary("QCView", AllocSumm,
1510 "createSnapshotImageOfType", NULL);
1511
Ted Kremenek211a9c62009-06-15 20:58:58 +00001512 // Create summaries for CIContext, 'createCGImage' and
Ted Kremeneka834fb42009-08-28 19:52:12 +00001513 // 'createCGLayerWithSize'. These objects are CF objects, and are not
1514 // automatically garbage collected.
1515 addInstMethSummary("CIContext", CFAllocSumm,
Ted Kremenek767d6492009-05-20 22:39:57 +00001516 "createCGImage", "fromRect", NULL);
Ted Kremeneka834fb42009-08-28 19:52:12 +00001517 addInstMethSummary("CIContext", CFAllocSumm,
Mike Stump1eb44332009-09-09 15:08:12 +00001518 "createCGImage", "fromRect", "format", "colorSpace", NULL);
Ted Kremeneka834fb42009-08-28 19:52:12 +00001519 addInstMethSummary("CIContext", CFAllocSumm, "createCGLayerWithSize",
Ted Kremenek211a9c62009-06-15 20:58:58 +00001520 "info", NULL);
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001521}
1522
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001523//===----------------------------------------------------------------------===//
Ted Kremenekc887d132009-04-29 18:50:19 +00001524// Error reporting.
1525//===----------------------------------------------------------------------===//
Ted Kremenekc887d132009-04-29 18:50:19 +00001526namespace {
Jordy Roseec9ef852011-08-23 20:55:48 +00001527 typedef llvm::DenseMap<const ExplodedNode *, const RetainSummary *>
1528 SummaryLogTy;
1529
Ted Kremenekc887d132009-04-29 18:50:19 +00001530 //===-------------===//
1531 // Bug Descriptions. //
Mike Stump1eb44332009-09-09 15:08:12 +00001532 //===-------------===//
1533
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001534 class CFRefBug : public BugType {
Ted Kremenekc887d132009-04-29 18:50:19 +00001535 protected:
Jordy Rose35c86952011-08-24 05:47:39 +00001536 CFRefBug(StringRef name)
Ted Kremenek6fd45052012-04-05 20:43:28 +00001537 : BugType(name, categories::MemoryCoreFoundationObjectiveC) {}
Ted Kremenekc887d132009-04-29 18:50:19 +00001538 public:
Mike Stump1eb44332009-09-09 15:08:12 +00001539
Ted Kremenekc887d132009-04-29 18:50:19 +00001540 // FIXME: Eventually remove.
Jordy Rose35c86952011-08-24 05:47:39 +00001541 virtual const char *getDescription() const = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001542
Ted Kremenekc887d132009-04-29 18:50:19 +00001543 virtual bool isLeak() const { return false; }
1544 };
Mike Stump1eb44332009-09-09 15:08:12 +00001545
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001546 class UseAfterRelease : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001547 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001548 UseAfterRelease() : CFRefBug("Use-after-release") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001549
Jordy Rose35c86952011-08-24 05:47:39 +00001550 const char *getDescription() const {
Ted Kremenekc887d132009-04-29 18:50:19 +00001551 return "Reference-counted object is used after it is released";
Mike Stump1eb44332009-09-09 15:08:12 +00001552 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001553 };
Mike Stump1eb44332009-09-09 15:08:12 +00001554
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001555 class BadRelease : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001556 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001557 BadRelease() : CFRefBug("Bad release") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001558
Jordy Rose35c86952011-08-24 05:47:39 +00001559 const char *getDescription() const {
Ted Kremenekbb206fd2009-10-01 17:31:50 +00001560 return "Incorrect decrement of the reference count of an object that is "
1561 "not owned at this point by the caller";
Ted Kremenekc887d132009-04-29 18:50:19 +00001562 }
1563 };
Mike Stump1eb44332009-09-09 15:08:12 +00001564
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001565 class DeallocGC : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001566 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001567 DeallocGC()
1568 : CFRefBug("-dealloc called while using garbage collection") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001569
Ted Kremenekc887d132009-04-29 18:50:19 +00001570 const char *getDescription() const {
Ted Kremenek369de562009-05-09 00:10:05 +00001571 return "-dealloc called while using garbage collection";
Ted Kremenekc887d132009-04-29 18:50:19 +00001572 }
1573 };
Mike Stump1eb44332009-09-09 15:08:12 +00001574
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001575 class DeallocNotOwned : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001576 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001577 DeallocNotOwned()
1578 : CFRefBug("-dealloc sent to non-exclusively owned object") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001579
Ted Kremenekc887d132009-04-29 18:50:19 +00001580 const char *getDescription() const {
1581 return "-dealloc sent to object that may be referenced elsewhere";
1582 }
Mike Stump1eb44332009-09-09 15:08:12 +00001583 };
1584
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001585 class OverAutorelease : public CFRefBug {
Ted Kremenek369de562009-05-09 00:10:05 +00001586 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001587 OverAutorelease()
Jordan Rose2545b1d2013-04-23 01:42:25 +00001588 : CFRefBug("Object autoreleased too many times") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001589
Ted Kremenek369de562009-05-09 00:10:05 +00001590 const char *getDescription() const {
Jordan Rose2545b1d2013-04-23 01:42:25 +00001591 return "Object autoreleased too many times";
Ted Kremenek369de562009-05-09 00:10:05 +00001592 }
1593 };
Mike Stump1eb44332009-09-09 15:08:12 +00001594
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001595 class ReturnedNotOwnedForOwned : public CFRefBug {
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001596 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001597 ReturnedNotOwnedForOwned()
1598 : CFRefBug("Method should return an owned object") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001599
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001600 const char *getDescription() const {
Jordy Rose5b5402b2011-07-15 22:17:54 +00001601 return "Object with a +0 retain count returned to caller where a +1 "
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001602 "(owning) retain count is expected";
1603 }
1604 };
Mike Stump1eb44332009-09-09 15:08:12 +00001605
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001606 class Leak : public CFRefBug {
Benjamin Kramerfacde172012-06-06 17:32:50 +00001607 public:
1608 Leak(StringRef name)
1609 : CFRefBug(name) {
Jordy Rosedb92bb62011-08-25 01:14:38 +00001610 // Leaks should not be reported if they are post-dominated by a sink.
1611 setSuppressOnSink(true);
1612 }
Mike Stump1eb44332009-09-09 15:08:12 +00001613
Jordy Rose35c86952011-08-24 05:47:39 +00001614 const char *getDescription() const { return ""; }
Mike Stump1eb44332009-09-09 15:08:12 +00001615
Ted Kremenekc887d132009-04-29 18:50:19 +00001616 bool isLeak() const { return true; }
1617 };
Mike Stump1eb44332009-09-09 15:08:12 +00001618
Ted Kremenekc887d132009-04-29 18:50:19 +00001619 //===---------===//
1620 // Bug Reports. //
1621 //===---------===//
Mike Stump1eb44332009-09-09 15:08:12 +00001622
Jordy Rose01153492012-03-24 02:45:35 +00001623 class CFRefReportVisitor : public BugReporterVisitorImpl<CFRefReportVisitor> {
Anna Zaks23f395e2011-08-20 01:27:22 +00001624 protected:
Anna Zaksdc757b02011-08-19 23:21:56 +00001625 SymbolRef Sym;
Jordy Roseec9ef852011-08-23 20:55:48 +00001626 const SummaryLogTy &SummaryLog;
Jordy Rose35c86952011-08-24 05:47:39 +00001627 bool GCEnabled;
Anna Zaks23f395e2011-08-20 01:27:22 +00001628
Anna Zaksdc757b02011-08-19 23:21:56 +00001629 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001630 CFRefReportVisitor(SymbolRef sym, bool gcEnabled, const SummaryLogTy &log)
1631 : Sym(sym), SummaryLog(log), GCEnabled(gcEnabled) {}
Anna Zaksdc757b02011-08-19 23:21:56 +00001632
Anna Zaks23f395e2011-08-20 01:27:22 +00001633 virtual void Profile(llvm::FoldingSetNodeID &ID) const {
Anna Zaksdc757b02011-08-19 23:21:56 +00001634 static int x = 0;
1635 ID.AddPointer(&x);
1636 ID.AddPointer(Sym);
1637 }
1638
Anna Zaks23f395e2011-08-20 01:27:22 +00001639 virtual PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
1640 const ExplodedNode *PrevN,
1641 BugReporterContext &BRC,
1642 BugReport &BR);
1643
1644 virtual PathDiagnosticPiece *getEndPath(BugReporterContext &BRC,
1645 const ExplodedNode *N,
1646 BugReport &BR);
1647 };
1648
1649 class CFRefLeakReportVisitor : public CFRefReportVisitor {
1650 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001651 CFRefLeakReportVisitor(SymbolRef sym, bool GCEnabled,
Jordy Roseec9ef852011-08-23 20:55:48 +00001652 const SummaryLogTy &log)
Jordy Rose35c86952011-08-24 05:47:39 +00001653 : CFRefReportVisitor(sym, GCEnabled, log) {}
Anna Zaks23f395e2011-08-20 01:27:22 +00001654
1655 PathDiagnosticPiece *getEndPath(BugReporterContext &BRC,
1656 const ExplodedNode *N,
1657 BugReport &BR);
Jordy Rose01153492012-03-24 02:45:35 +00001658
1659 virtual BugReporterVisitor *clone() const {
1660 // The curiously-recurring template pattern only works for one level of
1661 // subclassing. Rather than make a new template base for
1662 // CFRefReportVisitor, we simply override clone() to do the right thing.
1663 // This could be trouble someday if BugReporterVisitorImpl is ever
1664 // used for something else besides a convenient implementation of clone().
1665 return new CFRefLeakReportVisitor(*this);
1666 }
Anna Zaksdc757b02011-08-19 23:21:56 +00001667 };
1668
Anna Zakse172e8b2011-08-17 23:00:25 +00001669 class CFRefReport : public BugReport {
Jordy Rose20589562011-08-24 22:39:09 +00001670 void addGCModeDescription(const LangOptions &LOpts, bool GCEnabled);
Jordy Rose35c86952011-08-24 05:47:39 +00001671
Ted Kremenekc887d132009-04-29 18:50:19 +00001672 public:
Jordy Rose20589562011-08-24 22:39:09 +00001673 CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1674 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1675 bool registerVisitor = true)
Anna Zaksedf4dae2011-08-22 18:54:07 +00001676 : BugReport(D, D.getDescription(), n) {
Anna Zaks23f395e2011-08-20 01:27:22 +00001677 if (registerVisitor)
Jordy Rose20589562011-08-24 22:39:09 +00001678 addVisitor(new CFRefReportVisitor(sym, GCEnabled, Log));
1679 addGCModeDescription(LOpts, GCEnabled);
Anna Zaksdc757b02011-08-19 23:21:56 +00001680 }
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001681
Jordy Rose20589562011-08-24 22:39:09 +00001682 CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1683 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1684 StringRef endText)
Anna Zaksedf4dae2011-08-22 18:54:07 +00001685 : BugReport(D, D.getDescription(), endText, n) {
Jordy Rose20589562011-08-24 22:39:09 +00001686 addVisitor(new CFRefReportVisitor(sym, GCEnabled, Log));
1687 addGCModeDescription(LOpts, GCEnabled);
Anna Zaksdc757b02011-08-19 23:21:56 +00001688 }
Mike Stump1eb44332009-09-09 15:08:12 +00001689
Anna Zakse172e8b2011-08-17 23:00:25 +00001690 virtual std::pair<ranges_iterator, ranges_iterator> getRanges() {
Anna Zaksedf4dae2011-08-22 18:54:07 +00001691 const CFRefBug& BugTy = static_cast<CFRefBug&>(getBugType());
1692 if (!BugTy.isLeak())
Anna Zakse172e8b2011-08-17 23:00:25 +00001693 return BugReport::getRanges();
Ted Kremenekc887d132009-04-29 18:50:19 +00001694 else
Argyrios Kyrtzidis640ccf02010-12-04 01:12:15 +00001695 return std::make_pair(ranges_iterator(), ranges_iterator());
Ted Kremenekc887d132009-04-29 18:50:19 +00001696 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001697 };
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001698
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001699 class CFRefLeakReport : public CFRefReport {
Ted Kremenekc887d132009-04-29 18:50:19 +00001700 const MemRegion* AllocBinding;
1701 public:
Jordy Rose20589562011-08-24 22:39:09 +00001702 CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1703 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
Ted Kremenek08a838d2013-04-16 21:44:22 +00001704 CheckerContext &Ctx,
1705 bool IncludeAllocationLine);
Mike Stump1eb44332009-09-09 15:08:12 +00001706
Anna Zaks590dd8e2011-09-20 21:38:35 +00001707 PathDiagnosticLocation getLocation(const SourceManager &SM) const {
1708 assert(Location.isValid());
1709 return Location;
1710 }
Mike Stump1eb44332009-09-09 15:08:12 +00001711 };
Ted Kremenekc887d132009-04-29 18:50:19 +00001712} // end anonymous namespace
1713
Jordy Rose20589562011-08-24 22:39:09 +00001714void CFRefReport::addGCModeDescription(const LangOptions &LOpts,
1715 bool GCEnabled) {
Jordy Rosef95b19d2011-08-24 20:38:42 +00001716 const char *GCModeDescription = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001717
Douglas Gregore289d812011-09-13 17:21:33 +00001718 switch (LOpts.getGC()) {
Anna Zaks7f2531c2011-08-22 20:31:28 +00001719 case LangOptions::GCOnly:
Jordy Rose20589562011-08-24 22:39:09 +00001720 assert(GCEnabled);
Jordy Rose35c86952011-08-24 05:47:39 +00001721 GCModeDescription = "Code is compiled to only use garbage collection";
1722 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001723
Anna Zaks7f2531c2011-08-22 20:31:28 +00001724 case LangOptions::NonGC:
Jordy Rose20589562011-08-24 22:39:09 +00001725 assert(!GCEnabled);
Jordy Rose35c86952011-08-24 05:47:39 +00001726 GCModeDescription = "Code is compiled to use reference counts";
1727 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001728
Anna Zaks7f2531c2011-08-22 20:31:28 +00001729 case LangOptions::HybridGC:
Jordy Rose20589562011-08-24 22:39:09 +00001730 if (GCEnabled) {
Jordy Rose35c86952011-08-24 05:47:39 +00001731 GCModeDescription = "Code is compiled to use either garbage collection "
1732 "(GC) or reference counts (non-GC). The bug occurs "
1733 "with GC enabled";
1734 break;
1735 } else {
1736 GCModeDescription = "Code is compiled to use either garbage collection "
1737 "(GC) or reference counts (non-GC). The bug occurs "
1738 "in non-GC mode";
1739 break;
Anna Zaks7f2531c2011-08-22 20:31:28 +00001740 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001741 }
Jordy Rose35c86952011-08-24 05:47:39 +00001742
Jordy Rosef95b19d2011-08-24 20:38:42 +00001743 assert(GCModeDescription && "invalid/unknown GC mode");
Jordy Rose35c86952011-08-24 05:47:39 +00001744 addExtraText(GCModeDescription);
Ted Kremenekc887d132009-04-29 18:50:19 +00001745}
1746
Jordy Rose70fdbc32012-05-12 05:10:43 +00001747static bool isNumericLiteralExpression(const Expr *E) {
1748 // FIXME: This set of cases was copied from SemaExprObjC.
1749 return isa<IntegerLiteral>(E) ||
1750 isa<CharacterLiteral>(E) ||
1751 isa<FloatingLiteral>(E) ||
1752 isa<ObjCBoolLiteralExpr>(E) ||
1753 isa<CXXBoolLiteralExpr>(E);
1754}
1755
Anna Zaksdc757b02011-08-19 23:21:56 +00001756PathDiagnosticPiece *CFRefReportVisitor::VisitNode(const ExplodedNode *N,
1757 const ExplodedNode *PrevN,
1758 BugReporterContext &BRC,
1759 BugReport &BR) {
Jordan Rose28038f32012-07-10 22:07:42 +00001760 // FIXME: We will eventually need to handle non-statement-based events
1761 // (__attribute__((cleanup))).
David Blaikie7a95de62013-02-21 22:23:56 +00001762 if (!N->getLocation().getAs<StmtPoint>())
Ted Kremenek2033a952009-05-13 07:12:33 +00001763 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001764
Ted Kremenek8966bc12009-05-06 21:39:49 +00001765 // Check if the type state has changed.
Ted Kremenek8bef8232012-01-26 21:29:00 +00001766 ProgramStateRef PrevSt = PrevN->getState();
1767 ProgramStateRef CurrSt = N->getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001768 const LocationContext *LCtx = N->getLocationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00001769
Anna Zaks8d6b43c2012-08-14 00:36:15 +00001770 const RefVal* CurrT = getRefBinding(CurrSt, Sym);
Ted Kremenekc887d132009-04-29 18:50:19 +00001771 if (!CurrT) return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001772
Ted Kremenekb65be702009-06-18 01:23:53 +00001773 const RefVal &CurrV = *CurrT;
Anna Zaks8d6b43c2012-08-14 00:36:15 +00001774 const RefVal *PrevT = getRefBinding(PrevSt, Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00001775
Ted Kremenekc887d132009-04-29 18:50:19 +00001776 // Create a string buffer to constain all the useful things we want
1777 // to tell the user.
1778 std::string sbuf;
1779 llvm::raw_string_ostream os(sbuf);
Mike Stump1eb44332009-09-09 15:08:12 +00001780
Ted Kremenekc887d132009-04-29 18:50:19 +00001781 // This is the allocation site since the previous node had no bindings
1782 // for this symbol.
1783 if (!PrevT) {
David Blaikie7a95de62013-02-21 22:23:56 +00001784 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
Mike Stump1eb44332009-09-09 15:08:12 +00001785
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001786 if (isa<ObjCArrayLiteral>(S)) {
1787 os << "NSArray literal is an object with a +0 retain count";
Mike Stump1eb44332009-09-09 15:08:12 +00001788 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001789 else if (isa<ObjCDictionaryLiteral>(S)) {
1790 os << "NSDictionary literal is an object with a +0 retain count";
Ted Kremenekc887d132009-04-29 18:50:19 +00001791 }
Jordy Rose70fdbc32012-05-12 05:10:43 +00001792 else if (const ObjCBoxedExpr *BL = dyn_cast<ObjCBoxedExpr>(S)) {
1793 if (isNumericLiteralExpression(BL->getSubExpr()))
1794 os << "NSNumber literal is an object with a +0 retain count";
1795 else {
1796 const ObjCInterfaceDecl *BoxClass = 0;
1797 if (const ObjCMethodDecl *Method = BL->getBoxingMethod())
1798 BoxClass = Method->getClassInterface();
1799
1800 // We should always be able to find the boxing class interface,
1801 // but consider this future-proofing.
1802 if (BoxClass)
1803 os << *BoxClass << " b";
1804 else
1805 os << "B";
1806
1807 os << "oxed expression produces an object with a +0 retain count";
1808 }
1809 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001810 else {
1811 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
1812 // Get the name of the callee (if it is available).
1813 SVal X = CurrSt->getSValAsScalarOrLoc(CE->getCallee(), LCtx);
1814 if (const FunctionDecl *FD = X.getAsFunctionDecl())
1815 os << "Call to function '" << *FD << '\'';
1816 else
1817 os << "function call";
Ted Kremenekc887d132009-04-29 18:50:19 +00001818 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001819 else {
Jordan Rose8919e682012-07-18 21:59:51 +00001820 assert(isa<ObjCMessageExpr>(S));
Jordan Rosed563d3f2012-07-30 20:22:09 +00001821 CallEventManager &Mgr = CurrSt->getStateManager().getCallEventManager();
1822 CallEventRef<ObjCMethodCall> Call
1823 = Mgr.getObjCMethodCall(cast<ObjCMessageExpr>(S), CurrSt, LCtx);
1824
1825 switch (Call->getMessageKind()) {
Jordan Rose8919e682012-07-18 21:59:51 +00001826 case OCM_Message:
1827 os << "Method";
1828 break;
1829 case OCM_PropertyAccess:
1830 os << "Property";
1831 break;
1832 case OCM_Subscript:
1833 os << "Subscript";
1834 break;
1835 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001836 }
1837
1838 if (CurrV.getObjKind() == RetEffect::CF) {
1839 os << " returns a Core Foundation object with a ";
1840 }
1841 else {
1842 assert (CurrV.getObjKind() == RetEffect::ObjC);
1843 os << " returns an Objective-C object with a ";
1844 }
1845
1846 if (CurrV.isOwned()) {
1847 os << "+1 retain count";
1848
1849 if (GCEnabled) {
1850 assert(CurrV.getObjKind() == RetEffect::CF);
1851 os << ". "
1852 "Core Foundation objects are not automatically garbage collected.";
1853 }
1854 }
1855 else {
1856 assert (CurrV.isNotOwned());
1857 os << "+0 retain count";
1858 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001859 }
Mike Stump1eb44332009-09-09 15:08:12 +00001860
Anna Zaks220ac8c2011-09-15 01:08:34 +00001861 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
1862 N->getLocationContext());
Ted Kremenekc887d132009-04-29 18:50:19 +00001863 return new PathDiagnosticEventPiece(Pos, os.str());
1864 }
Mike Stump1eb44332009-09-09 15:08:12 +00001865
Ted Kremenekc887d132009-04-29 18:50:19 +00001866 // Gather up the effects that were performed on the object at this
1867 // program point
Chris Lattner5f9e2722011-07-23 10:55:15 +00001868 SmallVector<ArgEffect, 2> AEffects;
Mike Stump1eb44332009-09-09 15:08:12 +00001869
Jordy Roseec9ef852011-08-23 20:55:48 +00001870 const ExplodedNode *OrigNode = BRC.getNodeResolver().getOriginalNode(N);
1871 if (const RetainSummary *Summ = SummaryLog.lookup(OrigNode)) {
Ted Kremenekc887d132009-04-29 18:50:19 +00001872 // We only have summaries attached to nodes after evaluating CallExpr and
1873 // ObjCMessageExprs.
David Blaikie7a95de62013-02-21 22:23:56 +00001874 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
Mike Stump1eb44332009-09-09 15:08:12 +00001875
Ted Kremenek5f85e172009-07-22 22:35:28 +00001876 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
Ted Kremenekc887d132009-04-29 18:50:19 +00001877 // Iterate through the parameter expressions and see if the symbol
1878 // was ever passed as an argument.
1879 unsigned i = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001880
Ted Kremenek5f85e172009-07-22 22:35:28 +00001881 for (CallExpr::const_arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
Ted Kremenekc887d132009-04-29 18:50:19 +00001882 AI!=AE; ++AI, ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00001883
Ted Kremenekc887d132009-04-29 18:50:19 +00001884 // Retrieve the value of the argument. Is it the symbol
1885 // we are interested in?
Ted Kremenek5eca4822012-01-06 22:09:28 +00001886 if (CurrSt->getSValAsScalarOrLoc(*AI, LCtx).getAsLocSymbol() != Sym)
Ted Kremenekc887d132009-04-29 18:50:19 +00001887 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001888
Ted Kremenekc887d132009-04-29 18:50:19 +00001889 // We have an argument. Get the effect!
1890 AEffects.push_back(Summ->getArg(i));
1891 }
1892 }
Mike Stump1eb44332009-09-09 15:08:12 +00001893 else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00001894 if (const Expr *receiver = ME->getInstanceReceiver())
Ted Kremenek5eca4822012-01-06 22:09:28 +00001895 if (CurrSt->getSValAsScalarOrLoc(receiver, LCtx)
1896 .getAsLocSymbol() == Sym) {
Ted Kremenekc887d132009-04-29 18:50:19 +00001897 // The symbol we are tracking is the receiver.
1898 AEffects.push_back(Summ->getReceiverEffect());
1899 }
1900 }
1901 }
Mike Stump1eb44332009-09-09 15:08:12 +00001902
Ted Kremenekc887d132009-04-29 18:50:19 +00001903 do {
1904 // Get the previous type state.
1905 RefVal PrevV = *PrevT;
Mike Stump1eb44332009-09-09 15:08:12 +00001906
Ted Kremenekc887d132009-04-29 18:50:19 +00001907 // Specially handle -dealloc.
Benjamin Kramera1da6b22013-08-16 21:57:14 +00001908 if (!GCEnabled && std::find(AEffects.begin(), AEffects.end(), Dealloc) !=
1909 AEffects.end()) {
Ted Kremenekc887d132009-04-29 18:50:19 +00001910 // Determine if the object's reference count was pushed to zero.
1911 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
1912 // We may not have transitioned to 'release' if we hit an error.
1913 // This case is handled elsewhere.
1914 if (CurrV.getKind() == RefVal::Released) {
Ted Kremenekf21332e2009-05-08 20:01:42 +00001915 assert(CurrV.getCombinedCounts() == 0);
Ted Kremenekc887d132009-04-29 18:50:19 +00001916 os << "Object released by directly sending the '-dealloc' message";
1917 break;
1918 }
1919 }
Mike Stump1eb44332009-09-09 15:08:12 +00001920
Ted Kremenekc887d132009-04-29 18:50:19 +00001921 // Specially handle CFMakeCollectable and friends.
Benjamin Kramera1da6b22013-08-16 21:57:14 +00001922 if (std::find(AEffects.begin(), AEffects.end(), MakeCollectable) !=
1923 AEffects.end()) {
Ted Kremenekc887d132009-04-29 18:50:19 +00001924 // Get the name of the function.
David Blaikie7a95de62013-02-21 22:23:56 +00001925 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001926 SVal X =
1927 CurrSt->getSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee(), LCtx);
Ted Kremenek9c378f72011-08-12 23:37:29 +00001928 const FunctionDecl *FD = X.getAsFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001929
Jordy Rose35c86952011-08-24 05:47:39 +00001930 if (GCEnabled) {
Ted Kremenekc887d132009-04-29 18:50:19 +00001931 // Determine if the object's reference count was pushed to zero.
1932 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
Mike Stump1eb44332009-09-09 15:08:12 +00001933
Benjamin Kramerb8989f22011-10-14 18:45:37 +00001934 os << "In GC mode a call to '" << *FD
Ted Kremenekc887d132009-04-29 18:50:19 +00001935 << "' decrements an object's retain count and registers the "
1936 "object with the garbage collector. ";
Mike Stump1eb44332009-09-09 15:08:12 +00001937
Ted Kremenekc887d132009-04-29 18:50:19 +00001938 if (CurrV.getKind() == RefVal::Released) {
1939 assert(CurrV.getCount() == 0);
1940 os << "Since it now has a 0 retain count the object can be "
1941 "automatically collected by the garbage collector.";
1942 }
1943 else
1944 os << "An object must have a 0 retain count to be garbage collected. "
1945 "After this call its retain count is +" << CurrV.getCount()
1946 << '.';
1947 }
Mike Stump1eb44332009-09-09 15:08:12 +00001948 else
Benjamin Kramerb8989f22011-10-14 18:45:37 +00001949 os << "When GC is not enabled a call to '" << *FD
Ted Kremenekc887d132009-04-29 18:50:19 +00001950 << "' has no effect on its argument.";
Mike Stump1eb44332009-09-09 15:08:12 +00001951
Ted Kremenekc887d132009-04-29 18:50:19 +00001952 // Nothing more to say.
1953 break;
1954 }
Mike Stump1eb44332009-09-09 15:08:12 +00001955
1956 // Determine if the typestate has changed.
Ted Kremenekc887d132009-04-29 18:50:19 +00001957 if (!(PrevV == CurrV))
1958 switch (CurrV.getKind()) {
1959 case RefVal::Owned:
1960 case RefVal::NotOwned:
Mike Stump1eb44332009-09-09 15:08:12 +00001961
Ted Kremenekf21332e2009-05-08 20:01:42 +00001962 if (PrevV.getCount() == CurrV.getCount()) {
1963 // Did an autorelease message get sent?
1964 if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
1965 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001966
Zhongxing Xu264e9372009-05-12 10:10:00 +00001967 assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount());
Jordan Rose2545b1d2013-04-23 01:42:25 +00001968 os << "Object autoreleased";
Ted Kremenekf21332e2009-05-08 20:01:42 +00001969 break;
1970 }
Mike Stump1eb44332009-09-09 15:08:12 +00001971
Ted Kremenekc887d132009-04-29 18:50:19 +00001972 if (PrevV.getCount() > CurrV.getCount())
1973 os << "Reference count decremented.";
1974 else
1975 os << "Reference count incremented.";
Mike Stump1eb44332009-09-09 15:08:12 +00001976
Ted Kremenekc887d132009-04-29 18:50:19 +00001977 if (unsigned Count = CurrV.getCount())
1978 os << " The object now has a +" << Count << " retain count.";
Mike Stump1eb44332009-09-09 15:08:12 +00001979
Ted Kremenekc887d132009-04-29 18:50:19 +00001980 if (PrevV.getKind() == RefVal::Released) {
Jordy Rose35c86952011-08-24 05:47:39 +00001981 assert(GCEnabled && CurrV.getCount() > 0);
Jordy Rose74b7b2b2012-03-17 05:49:15 +00001982 os << " The object is not eligible for garbage collection until "
1983 "the retain count reaches 0 again.";
Ted Kremenekc887d132009-04-29 18:50:19 +00001984 }
Mike Stump1eb44332009-09-09 15:08:12 +00001985
Ted Kremenekc887d132009-04-29 18:50:19 +00001986 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001987
Ted Kremenekc887d132009-04-29 18:50:19 +00001988 case RefVal::Released:
1989 os << "Object released.";
1990 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001991
Ted Kremenekc887d132009-04-29 18:50:19 +00001992 case RefVal::ReturnedOwned:
Jordy Rose74b7b2b2012-03-17 05:49:15 +00001993 // Autoreleases can be applied after marking a node ReturnedOwned.
1994 if (CurrV.getAutoreleaseCount())
1995 return NULL;
1996
1997 os << "Object returned to caller as an owning reference (single "
1998 "retain count transferred to caller)";
Ted Kremenekc887d132009-04-29 18:50:19 +00001999 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002000
Ted Kremenekc887d132009-04-29 18:50:19 +00002001 case RefVal::ReturnedNotOwned:
Ted Kremenekf1365462011-05-26 18:45:44 +00002002 os << "Object returned to caller with a +0 retain count";
Ted Kremenekc887d132009-04-29 18:50:19 +00002003 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002004
Ted Kremenekc887d132009-04-29 18:50:19 +00002005 default:
2006 return NULL;
2007 }
Mike Stump1eb44332009-09-09 15:08:12 +00002008
Ted Kremenekc887d132009-04-29 18:50:19 +00002009 // Emit any remaining diagnostics for the argument effects (if any).
Chris Lattner5f9e2722011-07-23 10:55:15 +00002010 for (SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
Ted Kremenekc887d132009-04-29 18:50:19 +00002011 E=AEffects.end(); I != E; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +00002012
Ted Kremenekc887d132009-04-29 18:50:19 +00002013 // A bunch of things have alternate behavior under GC.
Jordy Rose35c86952011-08-24 05:47:39 +00002014 if (GCEnabled)
Ted Kremenekc887d132009-04-29 18:50:19 +00002015 switch (*I) {
2016 default: break;
2017 case Autorelease:
2018 os << "In GC mode an 'autorelease' has no effect.";
2019 continue;
2020 case IncRefMsg:
2021 os << "In GC mode the 'retain' message has no effect.";
2022 continue;
2023 case DecRefMsg:
2024 os << "In GC mode the 'release' message has no effect.";
2025 continue;
2026 }
2027 }
Mike Stump1eb44332009-09-09 15:08:12 +00002028 } while (0);
2029
Ted Kremenekc887d132009-04-29 18:50:19 +00002030 if (os.str().empty())
2031 return 0; // We have nothing to say!
Ted Kremenek2033a952009-05-13 07:12:33 +00002032
David Blaikie7a95de62013-02-21 22:23:56 +00002033 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
Anna Zaks220ac8c2011-09-15 01:08:34 +00002034 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
2035 N->getLocationContext());
Ted Kremenek9c378f72011-08-12 23:37:29 +00002036 PathDiagnosticPiece *P = new PathDiagnosticEventPiece(Pos, os.str());
Mike Stump1eb44332009-09-09 15:08:12 +00002037
Ted Kremenekc887d132009-04-29 18:50:19 +00002038 // Add the range by scanning the children of the statement for any bindings
2039 // to Sym.
Mike Stump1eb44332009-09-09 15:08:12 +00002040 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
Ted Kremenek5f85e172009-07-22 22:35:28 +00002041 I!=E; ++I)
Ted Kremenek9c378f72011-08-12 23:37:29 +00002042 if (const Expr *Exp = dyn_cast_or_null<Expr>(*I))
Ted Kremenek5eca4822012-01-06 22:09:28 +00002043 if (CurrSt->getSValAsScalarOrLoc(Exp, LCtx).getAsLocSymbol() == Sym) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002044 P->addRange(Exp->getSourceRange());
2045 break;
2046 }
Mike Stump1eb44332009-09-09 15:08:12 +00002047
Ted Kremenekc887d132009-04-29 18:50:19 +00002048 return P;
2049}
2050
Anna Zakse7e01682012-02-28 22:39:22 +00002051// Find the first node in the current function context that referred to the
2052// tracked symbol and the memory location that value was stored to. Note, the
2053// value is only reported if the allocation occurred in the same function as
Anna Zaks7a87e522013-04-10 21:42:06 +00002054// the leak. The function can also return a location context, which should be
2055// treated as interesting.
2056struct AllocationInfo {
2057 const ExplodedNode* N;
Anna Zaksee9043b2013-04-10 22:56:30 +00002058 const MemRegion *R;
Anna Zaks7a87e522013-04-10 21:42:06 +00002059 const LocationContext *InterestingMethodContext;
Anna Zaksee9043b2013-04-10 22:56:30 +00002060 AllocationInfo(const ExplodedNode *InN,
2061 const MemRegion *InR,
Anna Zaks7a87e522013-04-10 21:42:06 +00002062 const LocationContext *InInterestingMethodContext) :
2063 N(InN), R(InR), InterestingMethodContext(InInterestingMethodContext) {}
2064};
2065
2066static AllocationInfo
Ted Kremenek18c66fd2011-08-15 22:09:50 +00002067GetAllocationSite(ProgramStateManager& StateMgr, const ExplodedNode *N,
Ted Kremenekc887d132009-04-29 18:50:19 +00002068 SymbolRef Sym) {
Anna Zaks7a87e522013-04-10 21:42:06 +00002069 const ExplodedNode *AllocationNode = N;
2070 const ExplodedNode *AllocationNodeInCurrentContext = N;
Mike Stump1eb44332009-09-09 15:08:12 +00002071 const MemRegion* FirstBinding = 0;
Anna Zakse7e01682012-02-28 22:39:22 +00002072 const LocationContext *LeakContext = N->getLocationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002073
Anna Zaks7a87e522013-04-10 21:42:06 +00002074 // The location context of the init method called on the leaked object, if
2075 // available.
2076 const LocationContext *InitMethodContext = 0;
2077
Ted Kremenekc887d132009-04-29 18:50:19 +00002078 while (N) {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002079 ProgramStateRef St = N->getState();
Anna Zaks7a87e522013-04-10 21:42:06 +00002080 const LocationContext *NContext = N->getLocationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002081
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002082 if (!getRefBinding(St, Sym))
Ted Kremenekc887d132009-04-29 18:50:19 +00002083 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002084
Anna Zaks27b867e2012-03-21 19:45:01 +00002085 StoreManager::FindUniqueBinding FB(Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002086 StateMgr.iterBindings(St, FB);
Anna Zaks7a87e522013-04-10 21:42:06 +00002087
Anna Zaks27d99dd2013-04-10 21:42:02 +00002088 if (FB) {
2089 const MemRegion *R = FB.getRegion();
Anna Zaks8cf91f72013-04-10 22:56:33 +00002090 const VarRegion *VR = R->getBaseRegion()->getAs<VarRegion>();
Anna Zaks27d99dd2013-04-10 21:42:02 +00002091 // Do not show local variables belonging to a function other than
2092 // where the error is reported.
2093 if (!VR || VR->getStackFrame() == LeakContext->getCurrentStackFrame())
Anna Zaks7a87e522013-04-10 21:42:06 +00002094 FirstBinding = R;
Anna Zaks27d99dd2013-04-10 21:42:02 +00002095 }
Mike Stump1eb44332009-09-09 15:08:12 +00002096
Anna Zaks7a87e522013-04-10 21:42:06 +00002097 // AllocationNode is the last node in which the symbol was tracked.
2098 AllocationNode = N;
2099
2100 // AllocationNodeInCurrentContext, is the last node in the current context
2101 // in which the symbol was tracked.
2102 if (NContext == LeakContext)
2103 AllocationNodeInCurrentContext = N;
2104
Anna Zaksee9043b2013-04-10 22:56:30 +00002105 // Find the last init that was called on the given symbol and store the
2106 // init method's location context.
2107 if (!InitMethodContext)
2108 if (Optional<CallEnter> CEP = N->getLocation().getAs<CallEnter>()) {
2109 const Stmt *CE = CEP->getCallExpr();
Anna Zaks3d8f4622013-04-25 00:41:32 +00002110 if (const ObjCMessageExpr *ME = dyn_cast_or_null<ObjCMessageExpr>(CE)) {
Anna Zaksee9043b2013-04-10 22:56:30 +00002111 const Stmt *RecExpr = ME->getInstanceReceiver();
2112 if (RecExpr) {
2113 SVal RecV = St->getSVal(RecExpr, NContext);
2114 if (ME->getMethodFamily() == OMF_init && RecV.getAsSymbol() == Sym)
2115 InitMethodContext = CEP->getCalleeContext();
2116 }
2117 }
Anna Zaks7a87e522013-04-10 21:42:06 +00002118 }
Anna Zakse7e01682012-02-28 22:39:22 +00002119
Mike Stump1eb44332009-09-09 15:08:12 +00002120 N = N->pred_empty() ? NULL : *(N->pred_begin());
Ted Kremenekc887d132009-04-29 18:50:19 +00002121 }
Mike Stump1eb44332009-09-09 15:08:12 +00002122
Anna Zaks7a87e522013-04-10 21:42:06 +00002123 // If we are reporting a leak of the object that was allocated with alloc,
Anna Zaksee9043b2013-04-10 22:56:30 +00002124 // mark its init method as interesting.
Anna Zaks7a87e522013-04-10 21:42:06 +00002125 const LocationContext *InterestingMethodContext = 0;
2126 if (InitMethodContext) {
2127 const ProgramPoint AllocPP = AllocationNode->getLocation();
2128 if (Optional<StmtPoint> SP = AllocPP.getAs<StmtPoint>())
2129 if (const ObjCMessageExpr *ME = SP->getStmtAs<ObjCMessageExpr>())
2130 if (ME->getMethodFamily() == OMF_alloc)
2131 InterestingMethodContext = InitMethodContext;
2132 }
2133
Anna Zakse7e01682012-02-28 22:39:22 +00002134 // If allocation happened in a function different from the leak node context,
2135 // do not report the binding.
Ted Kremenek5a8fc882012-10-12 22:56:40 +00002136 assert(N && "Could not find allocation node");
Anna Zakse7e01682012-02-28 22:39:22 +00002137 if (N->getLocationContext() != LeakContext) {
2138 FirstBinding = 0;
2139 }
2140
Anna Zaks7a87e522013-04-10 21:42:06 +00002141 return AllocationInfo(AllocationNodeInCurrentContext,
2142 FirstBinding,
2143 InterestingMethodContext);
Ted Kremenekc887d132009-04-29 18:50:19 +00002144}
2145
2146PathDiagnosticPiece*
Anna Zaks23f395e2011-08-20 01:27:22 +00002147CFRefReportVisitor::getEndPath(BugReporterContext &BRC,
2148 const ExplodedNode *EndN,
2149 BugReport &BR) {
Ted Kremenek76aadc32012-03-09 01:13:14 +00002150 BR.markInteresting(Sym);
Anna Zaks23f395e2011-08-20 01:27:22 +00002151 return BugReporterVisitor::getDefaultEndPath(BRC, EndN, BR);
Ted Kremenekc887d132009-04-29 18:50:19 +00002152}
2153
2154PathDiagnosticPiece*
Anna Zaks23f395e2011-08-20 01:27:22 +00002155CFRefLeakReportVisitor::getEndPath(BugReporterContext &BRC,
2156 const ExplodedNode *EndN,
2157 BugReport &BR) {
Mike Stump1eb44332009-09-09 15:08:12 +00002158
Ted Kremenek8966bc12009-05-06 21:39:49 +00002159 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenekc887d132009-04-29 18:50:19 +00002160 // assigned to different variables, etc.
Ted Kremenek76aadc32012-03-09 01:13:14 +00002161 BR.markInteresting(Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002162
Ted Kremenekc887d132009-04-29 18:50:19 +00002163 // We are reporting a leak. Walk up the graph to get to the first node where
2164 // the symbol appeared, and also get the first VarDecl that tracked object
2165 // is stored to.
Anna Zaks7a87e522013-04-10 21:42:06 +00002166 AllocationInfo AllocI =
Ted Kremenekf04dced2009-05-08 23:32:51 +00002167 GetAllocationSite(BRC.getStateManager(), EndN, Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002168
Anna Zaks7a87e522013-04-10 21:42:06 +00002169 const MemRegion* FirstBinding = AllocI.R;
2170 BR.markInteresting(AllocI.InterestingMethodContext);
2171
Anna Zaks4fdf97b2011-09-15 18:56:07 +00002172 SourceManager& SM = BRC.getSourceManager();
Mike Stump1eb44332009-09-09 15:08:12 +00002173
Ted Kremenekc887d132009-04-29 18:50:19 +00002174 // Compute an actual location for the leak. Sometimes a leak doesn't
2175 // occur at an actual statement (e.g., transition between blocks; end
2176 // of function) so we need to walk the graph and compute a real location.
Ted Kremenek9c378f72011-08-12 23:37:29 +00002177 const ExplodedNode *LeakN = EndN;
Anna Zaks4fdf97b2011-09-15 18:56:07 +00002178 PathDiagnosticLocation L = PathDiagnosticLocation::createEndOfPath(LeakN, SM);
Mike Stump1eb44332009-09-09 15:08:12 +00002179
Ted Kremenekc887d132009-04-29 18:50:19 +00002180 std::string sbuf;
2181 llvm::raw_string_ostream os(sbuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002182
Ted Kremenekf1365462011-05-26 18:45:44 +00002183 os << "Object leaked: ";
Mike Stump1eb44332009-09-09 15:08:12 +00002184
Ted Kremenekf1365462011-05-26 18:45:44 +00002185 if (FirstBinding) {
2186 os << "object allocated and stored into '"
2187 << FirstBinding->getString() << '\'';
2188 }
2189 else
2190 os << "allocated object";
Mike Stump1eb44332009-09-09 15:08:12 +00002191
Ted Kremenekc887d132009-04-29 18:50:19 +00002192 // Get the retain count.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002193 const RefVal* RV = getRefBinding(EndN->getState(), Sym);
Ted Kremenek5a8fc882012-10-12 22:56:40 +00002194 assert(RV);
Mike Stump1eb44332009-09-09 15:08:12 +00002195
Ted Kremenekc887d132009-04-29 18:50:19 +00002196 if (RV->getKind() == RefVal::ErrorLeakReturned) {
2197 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
Jordy Rose5b5402b2011-07-15 22:17:54 +00002198 // objects. Only "copy", "alloc", "retain" and "new" transfer ownership
Ted Kremenekc887d132009-04-29 18:50:19 +00002199 // to the caller for NS objects.
Ted Kremenekd368d712011-05-25 06:19:45 +00002200 const Decl *D = &EndN->getCodeDecl();
Ted Kremenekec9f36e2012-09-06 23:03:07 +00002201
2202 os << (isa<ObjCMethodDecl>(D) ? " is returned from a method "
2203 : " is returned from a function ");
2204
2205 if (D->getAttr<CFReturnsNotRetainedAttr>())
2206 os << "that is annotated as CF_RETURNS_NOT_RETAINED";
2207 else if (D->getAttr<NSReturnsNotRetainedAttr>())
2208 os << "that is annotated as NS_RETURNS_NOT_RETAINED";
Ted Kremenekd368d712011-05-25 06:19:45 +00002209 else {
Ted Kremenekec9f36e2012-09-06 23:03:07 +00002210 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2211 os << "whose name ('" << MD->getSelector().getAsString()
2212 << "') does not start with 'copy', 'mutableCopy', 'alloc' or 'new'."
2213 " This violates the naming convention rules"
2214 " given in the Memory Management Guide for Cocoa";
2215 }
2216 else {
2217 const FunctionDecl *FD = cast<FunctionDecl>(D);
2218 os << "whose name ('" << *FD
2219 << "') does not contain 'Copy' or 'Create'. This violates the naming"
2220 " convention rules given in the Memory Management Guide for Core"
2221 " Foundation";
2222 }
2223 }
Ted Kremenekc887d132009-04-29 18:50:19 +00002224 }
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002225 else if (RV->getKind() == RefVal::ErrorGCLeakReturned) {
David Blaikiee1300142013-02-21 22:37:44 +00002226 const ObjCMethodDecl &MD = cast<ObjCMethodDecl>(EndN->getCodeDecl());
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002227 os << " and returned from method '" << MD.getSelector().getAsString()
Ted Kremenek82f2be52009-05-10 16:52:15 +00002228 << "' is potentially leaked when using garbage collection. Callers "
2229 "of this method do not expect a returned object with a +1 retain "
2230 "count since they expect the object to be managed by the garbage "
2231 "collector";
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002232 }
Ted Kremenekc887d132009-04-29 18:50:19 +00002233 else
Ted Kremenekabf517c2010-10-15 22:50:23 +00002234 os << " is not referenced later in this execution path and has a retain "
Ted Kremenekf1365462011-05-26 18:45:44 +00002235 "count of +" << RV->getCount();
Mike Stump1eb44332009-09-09 15:08:12 +00002236
Ted Kremenekc887d132009-04-29 18:50:19 +00002237 return new PathDiagnosticEventPiece(L, os.str());
2238}
2239
Jordy Rose20589562011-08-24 22:39:09 +00002240CFRefLeakReport::CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts,
2241 bool GCEnabled, const SummaryLogTy &Log,
2242 ExplodedNode *n, SymbolRef sym,
Ted Kremenek08a838d2013-04-16 21:44:22 +00002243 CheckerContext &Ctx,
2244 bool IncludeAllocationLine)
2245 : CFRefReport(D, LOpts, GCEnabled, Log, n, sym, false) {
Mike Stump1eb44332009-09-09 15:08:12 +00002246
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00002247 // Most bug reports are cached at the location where they occurred.
Ted Kremenekc887d132009-04-29 18:50:19 +00002248 // With leaks, we want to unique them by the location where they were
2249 // allocated, and only report a single path. To do this, we need to find
2250 // the allocation site of a piece of tracked memory, which we do via a
2251 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2252 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2253 // that all ancestor nodes that represent the allocation site have the
2254 // same SourceLocation.
Ted Kremenek9c378f72011-08-12 23:37:29 +00002255 const ExplodedNode *AllocNode = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002256
Anna Zaks6a93bd52011-10-25 19:57:11 +00002257 const SourceManager& SMgr = Ctx.getSourceManager();
Anna Zaks590dd8e2011-09-20 21:38:35 +00002258
Anna Zaks7a87e522013-04-10 21:42:06 +00002259 AllocationInfo AllocI =
Anna Zaks6a93bd52011-10-25 19:57:11 +00002260 GetAllocationSite(Ctx.getStateManager(), getErrorNode(), sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002261
Anna Zaks7a87e522013-04-10 21:42:06 +00002262 AllocNode = AllocI.N;
2263 AllocBinding = AllocI.R;
2264 markInteresting(AllocI.InterestingMethodContext);
2265
Ted Kremenekc887d132009-04-29 18:50:19 +00002266 // Get the SourceLocation for the allocation site.
Jordan Rose852aa0d2012-07-10 22:07:52 +00002267 // FIXME: This will crash the analyzer if an allocation comes from an
2268 // implicit call. (Currently there are no such allocations in Cocoa, though.)
2269 const Stmt *AllocStmt;
Ted Kremenekc887d132009-04-29 18:50:19 +00002270 ProgramPoint P = AllocNode->getLocation();
David Blaikie7a95de62013-02-21 22:23:56 +00002271 if (Optional<CallExitEnd> Exit = P.getAs<CallExitEnd>())
Jordan Rose852aa0d2012-07-10 22:07:52 +00002272 AllocStmt = Exit->getCalleeContext()->getCallSite();
2273 else
David Blaikie7a95de62013-02-21 22:23:56 +00002274 AllocStmt = P.castAs<PostStmt>().getStmt();
Jordan Rose852aa0d2012-07-10 22:07:52 +00002275 assert(AllocStmt && "All allocations must come from explicit calls");
Anna Zakse3a813a2013-04-23 23:57:50 +00002276
2277 PathDiagnosticLocation AllocLocation =
2278 PathDiagnosticLocation::createBegin(AllocStmt, SMgr,
2279 AllocNode->getLocationContext());
2280 Location = AllocLocation;
2281
2282 // Set uniqieing info, which will be used for unique the bug reports. The
2283 // leaks should be uniqued on the allocation site.
2284 UniqueingLocation = AllocLocation;
2285 UniqueingDecl = AllocNode->getLocationContext()->getDecl();
2286
Ted Kremenekc887d132009-04-29 18:50:19 +00002287 // Fill in the description of the bug.
2288 Description.clear();
2289 llvm::raw_string_ostream os(Description);
Ted Kremenekdd924e22009-05-02 19:05:19 +00002290 os << "Potential leak ";
Jordy Rose20589562011-08-24 22:39:09 +00002291 if (GCEnabled)
Ted Kremenekdd924e22009-05-02 19:05:19 +00002292 os << "(when using garbage collection) ";
Anna Zaks212000e2012-02-28 21:49:08 +00002293 os << "of an object";
Mike Stump1eb44332009-09-09 15:08:12 +00002294
Ted Kremenek08a838d2013-04-16 21:44:22 +00002295 if (AllocBinding) {
Anna Zaks212000e2012-02-28 21:49:08 +00002296 os << " stored into '" << AllocBinding->getString() << '\'';
Ted Kremenek08a838d2013-04-16 21:44:22 +00002297 if (IncludeAllocationLine) {
2298 FullSourceLoc SL(AllocStmt->getLocStart(), Ctx.getSourceManager());
2299 os << " (allocated on line " << SL.getSpellingLineNumber() << ")";
2300 }
2301 }
Anna Zaksdc757b02011-08-19 23:21:56 +00002302
Jordy Rose20589562011-08-24 22:39:09 +00002303 addVisitor(new CFRefLeakReportVisitor(sym, GCEnabled, Log));
Ted Kremenekc887d132009-04-29 18:50:19 +00002304}
2305
2306//===----------------------------------------------------------------------===//
2307// Main checker logic.
2308//===----------------------------------------------------------------------===//
2309
Ted Kremenekd593eb92009-11-25 22:17:44 +00002310namespace {
Jordy Rose910c4052011-09-02 06:44:22 +00002311class RetainCountChecker
Jordy Rose9c083b72011-08-24 18:56:32 +00002312 : public Checker< check::Bind,
Jordy Rose38f17d62011-08-23 19:01:07 +00002313 check::DeadSymbols,
Jordy Rose9c083b72011-08-24 18:56:32 +00002314 check::EndAnalysis,
Anna Zaks344c77a2013-01-03 00:25:29 +00002315 check::EndFunction,
Jordy Rose67044292011-08-17 21:27:39 +00002316 check::PostStmt<BlockExpr>,
John McCallf85e1932011-06-15 23:02:42 +00002317 check::PostStmt<CastExpr>,
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002318 check::PostStmt<ObjCArrayLiteral>,
2319 check::PostStmt<ObjCDictionaryLiteral>,
Jordy Rose70fdbc32012-05-12 05:10:43 +00002320 check::PostStmt<ObjCBoxedExpr>,
Jordan Rosefe6a0112012-07-02 19:28:21 +00002321 check::PostCall,
Jordy Rosef53e8c72011-08-23 19:43:16 +00002322 check::PreStmt<ReturnStmt>,
Jordy Rose67044292011-08-17 21:27:39 +00002323 check::RegionChanges,
Jordy Rose76c506f2011-08-21 21:58:18 +00002324 eval::Assume,
2325 eval::Call > {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002326 mutable OwningPtr<CFRefBug> useAfterRelease, releaseNotOwned;
2327 mutable OwningPtr<CFRefBug> deallocGC, deallocNotOwned;
2328 mutable OwningPtr<CFRefBug> overAutorelease, returnNotOwnedForOwned;
2329 mutable OwningPtr<CFRefBug> leakWithinFunction, leakAtReturn;
2330 mutable OwningPtr<CFRefBug> leakWithinFunctionGC, leakAtReturnGC;
Jordy Rose38f17d62011-08-23 19:01:07 +00002331
2332 typedef llvm::DenseMap<SymbolRef, const SimpleProgramPointTag *> SymbolTagMap;
2333
2334 // This map is only used to ensure proper deletion of any allocated tags.
2335 mutable SymbolTagMap DeadSymbolTags;
2336
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002337 mutable OwningPtr<RetainSummaryManager> Summaries;
2338 mutable OwningPtr<RetainSummaryManager> SummariesGC;
Jordy Rose9c083b72011-08-24 18:56:32 +00002339 mutable SummaryLogTy SummaryLog;
2340 mutable bool ShouldResetSummaryLog;
2341
Ted Kremenek08a838d2013-04-16 21:44:22 +00002342 /// Optional setting to indicate if leak reports should include
2343 /// the allocation line.
2344 mutable bool IncludeAllocationLine;
2345
Jordy Rose2f9a66d2011-08-20 21:17:59 +00002346public:
Ted Kremenek08a838d2013-04-16 21:44:22 +00002347 RetainCountChecker(AnalyzerOptions &AO)
2348 : ShouldResetSummaryLog(false),
2349 IncludeAllocationLine(shouldIncludeAllocationSiteInLeakDiagnostics(AO)) {}
Jordy Rose38f17d62011-08-23 19:01:07 +00002350
Jordy Rose910c4052011-09-02 06:44:22 +00002351 virtual ~RetainCountChecker() {
Jordy Rose38f17d62011-08-23 19:01:07 +00002352 DeleteContainerSeconds(DeadSymbolTags);
2353 }
2354
Jordy Rose9c083b72011-08-24 18:56:32 +00002355 void checkEndAnalysis(ExplodedGraph &G, BugReporter &BR,
2356 ExprEngine &Eng) const {
2357 // FIXME: This is a hack to make sure the summary log gets cleared between
2358 // analyses of different code bodies.
2359 //
2360 // Why is this necessary? Because a checker's lifetime is tied to a
2361 // translation unit, but an ExplodedGraph's lifetime is just a code body.
2362 // Once in a blue moon, a new ExplodedNode will have the same address as an
2363 // old one with an associated summary, and the bug report visitor gets very
2364 // confused. (To make things worse, the summary lifetime is currently also
2365 // tied to a code body, so we get a crash instead of incorrect results.)
Jordy Rose1ab51c72011-08-24 09:27:24 +00002366 //
2367 // Why is this a bad solution? Because if the lifetime of the ExplodedGraph
2368 // changes, things will start going wrong again. Really the lifetime of this
2369 // log needs to be tied to either the specific nodes in it or the entire
2370 // ExplodedGraph, not to a specific part of the code being analyzed.
2371 //
Jordy Rose9c083b72011-08-24 18:56:32 +00002372 // (Also, having stateful local data means that the same checker can't be
2373 // used from multiple threads, but a lot of checkers have incorrect
2374 // assumptions about that anyway. So that wasn't a priority at the time of
2375 // this fix.)
Jordy Rose1ab51c72011-08-24 09:27:24 +00002376 //
Jordy Rose9c083b72011-08-24 18:56:32 +00002377 // This happens at the end of analysis, but bug reports are emitted /after/
2378 // this point. So we can't just clear the summary log now. Instead, we mark
2379 // that the next time we access the summary log, it should be cleared.
2380
2381 // If we never reset the summary log during /this/ code body analysis,
2382 // there were no new summaries. There might still have been summaries from
2383 // the /last/ analysis, so clear them out to make sure the bug report
2384 // visitors don't get confused.
2385 if (ShouldResetSummaryLog)
2386 SummaryLog.clear();
2387
2388 ShouldResetSummaryLog = !SummaryLog.empty();
Jordy Rose1ab51c72011-08-24 09:27:24 +00002389 }
2390
Jordy Rose17a38e22011-09-02 05:55:19 +00002391 CFRefBug *getLeakWithinFunctionBug(const LangOptions &LOpts,
2392 bool GCEnabled) const {
2393 if (GCEnabled) {
Jordy Rosedb92bb62011-08-25 01:14:38 +00002394 if (!leakWithinFunctionGC)
Benjamin Kramerfacde172012-06-06 17:32:50 +00002395 leakWithinFunctionGC.reset(new Leak("Leak of object when using "
2396 "garbage collection"));
Jordy Rose17a38e22011-09-02 05:55:19 +00002397 return leakWithinFunctionGC.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002398 } else {
2399 if (!leakWithinFunction) {
Douglas Gregore289d812011-09-13 17:21:33 +00002400 if (LOpts.getGC() == LangOptions::HybridGC) {
Benjamin Kramerfacde172012-06-06 17:32:50 +00002401 leakWithinFunction.reset(new Leak("Leak of object when not using "
2402 "garbage collection (GC) in "
2403 "dual GC/non-GC code"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002404 } else {
Benjamin Kramerfacde172012-06-06 17:32:50 +00002405 leakWithinFunction.reset(new Leak("Leak"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002406 }
2407 }
Jordy Rose17a38e22011-09-02 05:55:19 +00002408 return leakWithinFunction.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002409 }
2410 }
2411
Jordy Rose17a38e22011-09-02 05:55:19 +00002412 CFRefBug *getLeakAtReturnBug(const LangOptions &LOpts, bool GCEnabled) const {
2413 if (GCEnabled) {
Jordy Rosedb92bb62011-08-25 01:14:38 +00002414 if (!leakAtReturnGC)
Benjamin Kramerfacde172012-06-06 17:32:50 +00002415 leakAtReturnGC.reset(new Leak("Leak of returned object when using "
2416 "garbage collection"));
Jordy Rose17a38e22011-09-02 05:55:19 +00002417 return leakAtReturnGC.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002418 } else {
2419 if (!leakAtReturn) {
Douglas Gregore289d812011-09-13 17:21:33 +00002420 if (LOpts.getGC() == LangOptions::HybridGC) {
Benjamin Kramerfacde172012-06-06 17:32:50 +00002421 leakAtReturn.reset(new Leak("Leak of returned object when not using "
2422 "garbage collection (GC) in dual "
2423 "GC/non-GC code"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002424 } else {
Benjamin Kramerfacde172012-06-06 17:32:50 +00002425 leakAtReturn.reset(new Leak("Leak of returned object"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002426 }
2427 }
Jordy Rose17a38e22011-09-02 05:55:19 +00002428 return leakAtReturn.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002429 }
2430 }
2431
Jordy Rose17a38e22011-09-02 05:55:19 +00002432 RetainSummaryManager &getSummaryManager(ASTContext &Ctx,
2433 bool GCEnabled) const {
2434 // FIXME: We don't support ARC being turned on and off during one analysis.
2435 // (nor, for that matter, do we support changing ASTContexts)
David Blaikie4e4d0842012-03-11 07:00:24 +00002436 bool ARCEnabled = (bool)Ctx.getLangOpts().ObjCAutoRefCount;
Jordy Rose17a38e22011-09-02 05:55:19 +00002437 if (GCEnabled) {
2438 if (!SummariesGC)
Jordy Roseb6cfc092011-08-25 00:10:37 +00002439 SummariesGC.reset(new RetainSummaryManager(Ctx, true, ARCEnabled));
Jordy Rose17a38e22011-09-02 05:55:19 +00002440 else
2441 assert(SummariesGC->isARCEnabled() == ARCEnabled);
Jordy Roseb6cfc092011-08-25 00:10:37 +00002442 return *SummariesGC;
2443 } else {
Jordy Rose17a38e22011-09-02 05:55:19 +00002444 if (!Summaries)
Jordy Roseb6cfc092011-08-25 00:10:37 +00002445 Summaries.reset(new RetainSummaryManager(Ctx, false, ARCEnabled));
Jordy Rose17a38e22011-09-02 05:55:19 +00002446 else
2447 assert(Summaries->isARCEnabled() == ARCEnabled);
Jordy Roseb6cfc092011-08-25 00:10:37 +00002448 return *Summaries;
2449 }
2450 }
2451
Jordy Rose17a38e22011-09-02 05:55:19 +00002452 RetainSummaryManager &getSummaryManager(CheckerContext &C) const {
2453 return getSummaryManager(C.getASTContext(), C.isObjCGCEnabled());
2454 }
2455
Ted Kremenek8bef8232012-01-26 21:29:00 +00002456 void printState(raw_ostream &Out, ProgramStateRef State,
Jordy Rosedbd658e2011-08-28 19:11:56 +00002457 const char *NL, const char *Sep) const;
2458
Anna Zaks390909c2011-10-06 00:43:15 +00002459 void checkBind(SVal loc, SVal val, const Stmt *S, CheckerContext &C) const;
Jordy Roseab027fd2011-08-20 21:16:58 +00002460 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
2461 void checkPostStmt(const CastExpr *CE, CheckerContext &C) const;
John McCallf85e1932011-06-15 23:02:42 +00002462
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002463 void checkPostStmt(const ObjCArrayLiteral *AL, CheckerContext &C) const;
2464 void checkPostStmt(const ObjCDictionaryLiteral *DL, CheckerContext &C) const;
Jordy Rose70fdbc32012-05-12 05:10:43 +00002465 void checkPostStmt(const ObjCBoxedExpr *BE, CheckerContext &C) const;
2466
Jordan Rosefe6a0112012-07-02 19:28:21 +00002467 void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002468
Jordan Rose4531b7d2012-07-02 19:27:43 +00002469 void checkSummary(const RetainSummary &Summ, const CallEvent &Call,
Jordy Rosee38dd952011-08-28 05:16:28 +00002470 CheckerContext &C) const;
Jordy Rose294396b2011-08-22 23:48:23 +00002471
Anna Zaks554067f2012-08-29 23:23:43 +00002472 void processSummaryOfInlined(const RetainSummary &Summ,
2473 const CallEvent &Call,
2474 CheckerContext &C) const;
2475
Jordy Rose76c506f2011-08-21 21:58:18 +00002476 bool evalCall(const CallExpr *CE, CheckerContext &C) const;
2477
Ted Kremenek8bef8232012-01-26 21:29:00 +00002478 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Jordy Roseab027fd2011-08-20 21:16:58 +00002479 bool Assumption) const;
Jordy Rose67044292011-08-17 21:27:39 +00002480
Ted Kremenek8bef8232012-01-26 21:29:00 +00002481 ProgramStateRef
2482 checkRegionChanges(ProgramStateRef state,
Anna Zaksbf53dfa2012-12-20 00:38:25 +00002483 const InvalidatedSymbols *invalidated,
Jordy Rose537716a2011-08-27 22:51:26 +00002484 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00002485 ArrayRef<const MemRegion *> Regions,
Jordan Rose740d4902012-07-02 19:27:35 +00002486 const CallEvent *Call) const;
Jordy Roseab027fd2011-08-20 21:16:58 +00002487
Ted Kremenek8bef8232012-01-26 21:29:00 +00002488 bool wantsRegionChangeUpdate(ProgramStateRef state) const {
Jordy Rose2f9a66d2011-08-20 21:17:59 +00002489 return true;
Jordy Roseab027fd2011-08-20 21:16:58 +00002490 }
Jordy Rose294396b2011-08-22 23:48:23 +00002491
Jordy Rosef53e8c72011-08-23 19:43:16 +00002492 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
2493 void checkReturnWithRetEffect(const ReturnStmt *S, CheckerContext &C,
2494 ExplodedNode *Pred, RetEffect RE, RefVal X,
Ted Kremenek8bef8232012-01-26 21:29:00 +00002495 SymbolRef Sym, ProgramStateRef state) const;
Jordy Rosef53e8c72011-08-23 19:43:16 +00002496
Jordy Rose38f17d62011-08-23 19:01:07 +00002497 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Anna Zaks344c77a2013-01-03 00:25:29 +00002498 void checkEndFunction(CheckerContext &C) const;
Jordy Rose38f17d62011-08-23 19:01:07 +00002499
Ted Kremenek8bef8232012-01-26 21:29:00 +00002500 ProgramStateRef updateSymbol(ProgramStateRef state, SymbolRef sym,
Anna Zaks554067f2012-08-29 23:23:43 +00002501 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
2502 CheckerContext &C) const;
Jordy Rosee0a5d322011-08-23 20:27:16 +00002503
Ted Kremenek8bef8232012-01-26 21:29:00 +00002504 void processNonLeakError(ProgramStateRef St, SourceRange ErrorRange,
Jordy Rose294396b2011-08-22 23:48:23 +00002505 RefVal::Kind ErrorKind, SymbolRef Sym,
2506 CheckerContext &C) const;
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002507
2508 void processObjCLiterals(CheckerContext &C, const Expr *Ex) const;
Jordy Rose294396b2011-08-22 23:48:23 +00002509
Jordy Rose38f17d62011-08-23 19:01:07 +00002510 const ProgramPointTag *getDeadSymbolTag(SymbolRef sym) const;
2511
Ted Kremenek8bef8232012-01-26 21:29:00 +00002512 ProgramStateRef handleSymbolDeath(ProgramStateRef state,
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002513 SymbolRef sid, RefVal V,
2514 SmallVectorImpl<SymbolRef> &Leaked) const;
Jordy Rose38f17d62011-08-23 19:01:07 +00002515
Jordan Rose4ee1c552012-12-06 18:58:18 +00002516 ProgramStateRef
Jordan Rose2bce86c2012-08-18 00:30:16 +00002517 handleAutoreleaseCounts(ProgramStateRef state, ExplodedNode *Pred,
2518 const ProgramPointTag *Tag, CheckerContext &Ctx,
2519 SymbolRef Sym, RefVal V) const;
Jordy Rose8d228632011-08-23 20:07:14 +00002520
Ted Kremenek8bef8232012-01-26 21:29:00 +00002521 ExplodedNode *processLeaks(ProgramStateRef state,
Jordy Rose38f17d62011-08-23 19:01:07 +00002522 SmallVectorImpl<SymbolRef> &Leaked,
Anna Zaks6a93bd52011-10-25 19:57:11 +00002523 CheckerContext &Ctx,
Jordy Rose38f17d62011-08-23 19:01:07 +00002524 ExplodedNode *Pred = 0) const;
Ted Kremenekd593eb92009-11-25 22:17:44 +00002525};
2526} // end anonymous namespace
2527
Jordy Rose67044292011-08-17 21:27:39 +00002528namespace {
2529class StopTrackingCallback : public SymbolVisitor {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002530 ProgramStateRef state;
Jordy Rose67044292011-08-17 21:27:39 +00002531public:
Ted Kremenek8bef8232012-01-26 21:29:00 +00002532 StopTrackingCallback(ProgramStateRef st) : state(st) {}
2533 ProgramStateRef getState() const { return state; }
Jordy Rose67044292011-08-17 21:27:39 +00002534
2535 bool VisitSymbol(SymbolRef sym) {
2536 state = state->remove<RefBindings>(sym);
2537 return true;
2538 }
2539};
2540} // end anonymous namespace
2541
Jordy Rose910c4052011-09-02 06:44:22 +00002542//===----------------------------------------------------------------------===//
2543// Handle statements that may have an effect on refcounts.
2544//===----------------------------------------------------------------------===//
Jordy Rose67044292011-08-17 21:27:39 +00002545
Jordy Rose910c4052011-09-02 06:44:22 +00002546void RetainCountChecker::checkPostStmt(const BlockExpr *BE,
2547 CheckerContext &C) const {
Jordy Rose67044292011-08-17 21:27:39 +00002548
Jordy Rose910c4052011-09-02 06:44:22 +00002549 // Scan the BlockDecRefExprs for any object the retain count checker
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002550 // may be tracking.
John McCall469a1eb2011-02-02 13:00:07 +00002551 if (!BE->getBlockDecl()->hasCaptures())
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002552 return;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002553
Ted Kremenek8bef8232012-01-26 21:29:00 +00002554 ProgramStateRef state = C.getState();
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002555 const BlockDataRegion *R =
Ted Kremenek5eca4822012-01-06 22:09:28 +00002556 cast<BlockDataRegion>(state->getSVal(BE,
2557 C.getLocationContext()).getAsRegion());
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002558
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002559 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
2560 E = R->referenced_vars_end();
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002561
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002562 if (I == E)
2563 return;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002564
Ted Kremenek67d12872009-12-07 22:05:27 +00002565 // FIXME: For now we invalidate the tracking of all symbols passed to blocks
2566 // via captured variables, even though captured variables result in a copy
2567 // and in implicit increment/decrement of a retain count.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002568 SmallVector<const MemRegion*, 10> Regions;
Anna Zaks39ac1872011-10-26 21:06:44 +00002569 const LocationContext *LC = C.getLocationContext();
Ted Kremenekc8413fd2010-12-02 07:49:45 +00002570 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002571
Ted Kremenek67d12872009-12-07 22:05:27 +00002572 for ( ; I != E; ++I) {
Ted Kremeneke3ce2c12012-12-06 07:17:20 +00002573 const VarRegion *VR = I.getCapturedRegion();
Ted Kremenek67d12872009-12-07 22:05:27 +00002574 if (VR->getSuperRegion() == R) {
2575 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2576 }
2577 Regions.push_back(VR);
2578 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002579
Ted Kremenek67d12872009-12-07 22:05:27 +00002580 state =
2581 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
2582 Regions.data() + Regions.size()).getState();
Anna Zaks0bd6b112011-10-26 21:06:34 +00002583 C.addTransition(state);
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002584}
2585
Jordy Rose910c4052011-09-02 06:44:22 +00002586void RetainCountChecker::checkPostStmt(const CastExpr *CE,
2587 CheckerContext &C) const {
John McCallf85e1932011-06-15 23:02:42 +00002588 const ObjCBridgedCastExpr *BE = dyn_cast<ObjCBridgedCastExpr>(CE);
2589 if (!BE)
2590 return;
2591
John McCall71c482c2011-06-17 06:50:50 +00002592 ArgEffect AE = IncRef;
John McCallf85e1932011-06-15 23:02:42 +00002593
2594 switch (BE->getBridgeKind()) {
2595 case clang::OBC_Bridge:
2596 // Do nothing.
2597 return;
2598 case clang::OBC_BridgeRetained:
2599 AE = IncRef;
2600 break;
2601 case clang::OBC_BridgeTransfer:
2602 AE = DecRefBridgedTransfered;
2603 break;
2604 }
2605
Ted Kremenek8bef8232012-01-26 21:29:00 +00002606 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00002607 SymbolRef Sym = state->getSVal(CE, C.getLocationContext()).getAsLocSymbol();
John McCallf85e1932011-06-15 23:02:42 +00002608 if (!Sym)
2609 return;
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002610 const RefVal* T = getRefBinding(state, Sym);
John McCallf85e1932011-06-15 23:02:42 +00002611 if (!T)
2612 return;
2613
John McCallf85e1932011-06-15 23:02:42 +00002614 RefVal::Kind hasErr = (RefVal::Kind) 0;
Jordy Rose17a38e22011-09-02 05:55:19 +00002615 state = updateSymbol(state, Sym, *T, AE, hasErr, C);
John McCallf85e1932011-06-15 23:02:42 +00002616
2617 if (hasErr) {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002618 // FIXME: If we get an error during a bridge cast, should we report it?
2619 // Should we assert that there is no error?
John McCallf85e1932011-06-15 23:02:42 +00002620 return;
2621 }
2622
Anna Zaks0bd6b112011-10-26 21:06:34 +00002623 C.addTransition(state);
John McCallf85e1932011-06-15 23:02:42 +00002624}
2625
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002626void RetainCountChecker::processObjCLiterals(CheckerContext &C,
2627 const Expr *Ex) const {
2628 ProgramStateRef state = C.getState();
2629 const ExplodedNode *pred = C.getPredecessor();
2630 for (Stmt::const_child_iterator it = Ex->child_begin(), et = Ex->child_end() ;
2631 it != et ; ++it) {
2632 const Stmt *child = *it;
2633 SVal V = state->getSVal(child, pred->getLocationContext());
2634 if (SymbolRef sym = V.getAsSymbol())
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002635 if (const RefVal* T = getRefBinding(state, sym)) {
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002636 RefVal::Kind hasErr = (RefVal::Kind) 0;
2637 state = updateSymbol(state, sym, *T, MayEscape, hasErr, C);
2638 if (hasErr) {
2639 processNonLeakError(state, child->getSourceRange(), hasErr, sym, C);
2640 return;
2641 }
2642 }
2643 }
2644
2645 // Return the object as autoreleased.
2646 // RetEffect RE = RetEffect::MakeNotOwned(RetEffect::ObjC);
2647 if (SymbolRef sym =
2648 state->getSVal(Ex, pred->getLocationContext()).getAsSymbol()) {
2649 QualType ResultTy = Ex->getType();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002650 state = setRefBinding(state, sym,
2651 RefVal::makeNotOwned(RetEffect::ObjC, ResultTy));
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002652 }
2653
2654 C.addTransition(state);
2655}
2656
2657void RetainCountChecker::checkPostStmt(const ObjCArrayLiteral *AL,
2658 CheckerContext &C) const {
2659 // Apply the 'MayEscape' to all values.
2660 processObjCLiterals(C, AL);
2661}
2662
2663void RetainCountChecker::checkPostStmt(const ObjCDictionaryLiteral *DL,
2664 CheckerContext &C) const {
2665 // Apply the 'MayEscape' to all keys and values.
2666 processObjCLiterals(C, DL);
2667}
2668
Jordy Rose70fdbc32012-05-12 05:10:43 +00002669void RetainCountChecker::checkPostStmt(const ObjCBoxedExpr *Ex,
2670 CheckerContext &C) const {
2671 const ExplodedNode *Pred = C.getPredecessor();
2672 const LocationContext *LCtx = Pred->getLocationContext();
2673 ProgramStateRef State = Pred->getState();
2674
2675 if (SymbolRef Sym = State->getSVal(Ex, LCtx).getAsSymbol()) {
2676 QualType ResultTy = Ex->getType();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002677 State = setRefBinding(State, Sym,
2678 RefVal::makeNotOwned(RetEffect::ObjC, ResultTy));
Jordy Rose70fdbc32012-05-12 05:10:43 +00002679 }
2680
2681 C.addTransition(State);
2682}
2683
Jordan Rosefe6a0112012-07-02 19:28:21 +00002684void RetainCountChecker::checkPostCall(const CallEvent &Call,
2685 CheckerContext &C) const {
Jordan Rosefe6a0112012-07-02 19:28:21 +00002686 RetainSummaryManager &Summaries = getSummaryManager(C);
2687 const RetainSummary *Summ = Summaries.getSummary(Call, C.getState());
Anna Zaks554067f2012-08-29 23:23:43 +00002688
2689 if (C.wasInlined) {
2690 processSummaryOfInlined(*Summ, Call, C);
2691 return;
2692 }
Jordan Rosefe6a0112012-07-02 19:28:21 +00002693 checkSummary(*Summ, Call, C);
Jordy Rose294396b2011-08-22 23:48:23 +00002694}
2695
Jordy Rose910c4052011-09-02 06:44:22 +00002696/// GetReturnType - Used to get the return type of a message expression or
2697/// function call with the intention of affixing that type to a tracked symbol.
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +00002698/// While the return type can be queried directly from RetEx, when
Jordy Rose910c4052011-09-02 06:44:22 +00002699/// invoking class methods we augment to the return type to be that of
2700/// a pointer to the class (as opposed it just being id).
2701// FIXME: We may be able to do this with related result types instead.
2702// This function is probably overestimating.
2703static QualType GetReturnType(const Expr *RetE, ASTContext &Ctx) {
2704 QualType RetTy = RetE->getType();
2705 // If RetE is not a message expression just return its type.
2706 // If RetE is a message expression, return its types if it is something
2707 /// more specific than id.
2708 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RetE))
2709 if (const ObjCObjectPointerType *PT = RetTy->getAs<ObjCObjectPointerType>())
2710 if (PT->isObjCQualifiedIdType() || PT->isObjCIdType() ||
2711 PT->isObjCClassType()) {
2712 // At this point we know the return type of the message expression is
2713 // id, id<...>, or Class. If we have an ObjCInterfaceDecl, we know this
2714 // is a call to a class method whose type we can resolve. In such
2715 // cases, promote the return type to XXX* (where XXX is the class).
2716 const ObjCInterfaceDecl *D = ME->getReceiverInterface();
2717 return !D ? RetTy :
2718 Ctx.getObjCObjectPointerType(Ctx.getObjCInterfaceType(D));
2719 }
2720
2721 return RetTy;
2722}
2723
Anna Zaks554067f2012-08-29 23:23:43 +00002724// We don't always get the exact modeling of the function with regards to the
2725// retain count checker even when the function is inlined. For example, we need
2726// to stop tracking the symbols which were marked with StopTrackingHard.
2727void RetainCountChecker::processSummaryOfInlined(const RetainSummary &Summ,
2728 const CallEvent &CallOrMsg,
2729 CheckerContext &C) const {
2730 ProgramStateRef state = C.getState();
2731
2732 // Evaluate the effect of the arguments.
2733 for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
2734 if (Summ.getArg(idx) == StopTrackingHard) {
2735 SVal V = CallOrMsg.getArgSVal(idx);
2736 if (SymbolRef Sym = V.getAsLocSymbol()) {
2737 state = removeRefBinding(state, Sym);
2738 }
2739 }
2740 }
2741
2742 // Evaluate the effect on the message receiver.
2743 const ObjCMethodCall *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg);
2744 if (MsgInvocation) {
2745 if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
2746 if (Summ.getReceiverEffect() == StopTrackingHard) {
2747 state = removeRefBinding(state, Sym);
2748 }
2749 }
2750 }
2751
2752 // Consult the summary for the return value.
2753 RetEffect RE = Summ.getRetEffect();
2754 if (RE.getKind() == RetEffect::NoRetHard) {
Jordan Rose2f3017f2012-11-02 23:49:29 +00002755 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
Anna Zaks554067f2012-08-29 23:23:43 +00002756 if (Sym)
2757 state = removeRefBinding(state, Sym);
2758 }
2759
2760 C.addTransition(state);
2761}
2762
Jordy Rose910c4052011-09-02 06:44:22 +00002763void RetainCountChecker::checkSummary(const RetainSummary &Summ,
Jordan Rose4531b7d2012-07-02 19:27:43 +00002764 const CallEvent &CallOrMsg,
Jordy Rose910c4052011-09-02 06:44:22 +00002765 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002766 ProgramStateRef state = C.getState();
Jordy Rose294396b2011-08-22 23:48:23 +00002767
2768 // Evaluate the effect of the arguments.
2769 RefVal::Kind hasErr = (RefVal::Kind) 0;
2770 SourceRange ErrorRange;
2771 SymbolRef ErrorSym = 0;
2772
2773 for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
Jordy Rose537716a2011-08-27 22:51:26 +00002774 SVal V = CallOrMsg.getArgSVal(idx);
Jordy Rose294396b2011-08-22 23:48:23 +00002775
2776 if (SymbolRef Sym = V.getAsLocSymbol()) {
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002777 if (const RefVal *T = getRefBinding(state, Sym)) {
Jordy Rose17a38e22011-09-02 05:55:19 +00002778 state = updateSymbol(state, Sym, *T, Summ.getArg(idx), hasErr, C);
Jordy Rose294396b2011-08-22 23:48:23 +00002779 if (hasErr) {
2780 ErrorRange = CallOrMsg.getArgSourceRange(idx);
2781 ErrorSym = Sym;
2782 break;
2783 }
2784 }
2785 }
2786 }
2787
2788 // Evaluate the effect on the message receiver.
2789 bool ReceiverIsTracked = false;
Jordan Rose4531b7d2012-07-02 19:27:43 +00002790 if (!hasErr) {
Jordan Rosecde8cdb2012-07-02 19:27:56 +00002791 const ObjCMethodCall *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg);
Jordan Rose4531b7d2012-07-02 19:27:43 +00002792 if (MsgInvocation) {
2793 if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002794 if (const RefVal *T = getRefBinding(state, Sym)) {
Jordan Rose4531b7d2012-07-02 19:27:43 +00002795 ReceiverIsTracked = true;
2796 state = updateSymbol(state, Sym, *T, Summ.getReceiverEffect(),
Anna Zaks554067f2012-08-29 23:23:43 +00002797 hasErr, C);
Jordan Rose4531b7d2012-07-02 19:27:43 +00002798 if (hasErr) {
Jordan Rose8919e682012-07-18 21:59:51 +00002799 ErrorRange = MsgInvocation->getOriginExpr()->getReceiverRange();
Jordan Rose4531b7d2012-07-02 19:27:43 +00002800 ErrorSym = Sym;
2801 }
Jordy Rose294396b2011-08-22 23:48:23 +00002802 }
2803 }
2804 }
2805 }
2806
2807 // Process any errors.
2808 if (hasErr) {
2809 processNonLeakError(state, ErrorRange, hasErr, ErrorSym, C);
2810 return;
2811 }
2812
2813 // Consult the summary for the return value.
2814 RetEffect RE = Summ.getRetEffect();
2815
2816 if (RE.getKind() == RetEffect::OwnedWhenTrackedReceiver) {
Jordy Roseb6cfc092011-08-25 00:10:37 +00002817 if (ReceiverIsTracked)
Jordy Rose17a38e22011-09-02 05:55:19 +00002818 RE = getSummaryManager(C).getObjAllocRetEffect();
Jordy Roseb6cfc092011-08-25 00:10:37 +00002819 else
Jordy Rose294396b2011-08-22 23:48:23 +00002820 RE = RetEffect::MakeNoRet();
2821 }
2822
2823 switch (RE.getKind()) {
2824 default:
David Blaikie7530c032012-01-17 06:56:22 +00002825 llvm_unreachable("Unhandled RetEffect.");
Jordy Rose294396b2011-08-22 23:48:23 +00002826
2827 case RetEffect::NoRet:
Anna Zaks554067f2012-08-29 23:23:43 +00002828 case RetEffect::NoRetHard:
Jordy Rose294396b2011-08-22 23:48:23 +00002829 // No work necessary.
2830 break;
2831
2832 case RetEffect::OwnedAllocatedSymbol:
2833 case RetEffect::OwnedSymbol: {
Jordan Rose2f3017f2012-11-02 23:49:29 +00002834 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
Jordy Rose294396b2011-08-22 23:48:23 +00002835 if (!Sym)
2836 break;
2837
Jordan Rose4531b7d2012-07-02 19:27:43 +00002838 // Use the result type from the CallEvent as it automatically adjusts
Jordy Rose294396b2011-08-22 23:48:23 +00002839 // for methods/functions that return references.
Jordan Rose4531b7d2012-07-02 19:27:43 +00002840 QualType ResultTy = CallOrMsg.getResultType();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002841 state = setRefBinding(state, Sym, RefVal::makeOwned(RE.getObjKind(),
2842 ResultTy));
Jordy Rose294396b2011-08-22 23:48:23 +00002843
2844 // FIXME: Add a flag to the checker where allocations are assumed to
Anna Zaksc6ba23f2012-08-14 15:39:13 +00002845 // *not* fail.
Jordy Rose294396b2011-08-22 23:48:23 +00002846 break;
2847 }
2848
2849 case RetEffect::GCNotOwnedSymbol:
2850 case RetEffect::ARCNotOwnedSymbol:
2851 case RetEffect::NotOwnedSymbol: {
2852 const Expr *Ex = CallOrMsg.getOriginExpr();
Jordan Rose2f3017f2012-11-02 23:49:29 +00002853 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
Jordy Rose294396b2011-08-22 23:48:23 +00002854 if (!Sym)
2855 break;
Ted Kremenek74616822012-10-12 22:56:45 +00002856 assert(Ex);
Jordy Rose294396b2011-08-22 23:48:23 +00002857 // Use GetReturnType in order to give [NSFoo alloc] the type NSFoo *.
2858 QualType ResultTy = GetReturnType(Ex, C.getASTContext());
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002859 state = setRefBinding(state, Sym, RefVal::makeNotOwned(RE.getObjKind(),
2860 ResultTy));
Jordy Rose294396b2011-08-22 23:48:23 +00002861 break;
2862 }
2863 }
2864
2865 // This check is actually necessary; otherwise the statement builder thinks
2866 // we've hit a previously-found path.
2867 // Normally addTransition takes care of this, but we want the node pointer.
2868 ExplodedNode *NewNode;
2869 if (state == C.getState()) {
2870 NewNode = C.getPredecessor();
2871 } else {
Anna Zaks0bd6b112011-10-26 21:06:34 +00002872 NewNode = C.addTransition(state);
Jordy Rose294396b2011-08-22 23:48:23 +00002873 }
2874
Jordy Rose9c083b72011-08-24 18:56:32 +00002875 // Annotate the node with summary we used.
2876 if (NewNode) {
2877 // FIXME: This is ugly. See checkEndAnalysis for why it's necessary.
2878 if (ShouldResetSummaryLog) {
2879 SummaryLog.clear();
2880 ShouldResetSummaryLog = false;
2881 }
Jordy Roseec9ef852011-08-23 20:55:48 +00002882 SummaryLog[NewNode] = &Summ;
Jordy Rose9c083b72011-08-24 18:56:32 +00002883 }
Jordy Rose294396b2011-08-22 23:48:23 +00002884}
2885
Jordy Rosee0a5d322011-08-23 20:27:16 +00002886
Ted Kremenek8bef8232012-01-26 21:29:00 +00002887ProgramStateRef
2888RetainCountChecker::updateSymbol(ProgramStateRef state, SymbolRef sym,
Jordy Rose910c4052011-09-02 06:44:22 +00002889 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
2890 CheckerContext &C) const {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002891 // In GC mode [... release] and [... retain] do nothing.
Jordy Rose910c4052011-09-02 06:44:22 +00002892 // In ARC mode they shouldn't exist at all, but we just ignore them.
Jordy Rose17a38e22011-09-02 05:55:19 +00002893 bool IgnoreRetainMsg = C.isObjCGCEnabled();
2894 if (!IgnoreRetainMsg)
David Blaikie4e4d0842012-03-11 07:00:24 +00002895 IgnoreRetainMsg = (bool)C.getASTContext().getLangOpts().ObjCAutoRefCount;
Jordy Rose17a38e22011-09-02 05:55:19 +00002896
Jordy Rosee0a5d322011-08-23 20:27:16 +00002897 switch (E) {
Jordan Rose4531b7d2012-07-02 19:27:43 +00002898 default:
2899 break;
2900 case IncRefMsg:
2901 E = IgnoreRetainMsg ? DoNothing : IncRef;
2902 break;
2903 case DecRefMsg:
2904 E = IgnoreRetainMsg ? DoNothing : DecRef;
2905 break;
Anna Zaks554067f2012-08-29 23:23:43 +00002906 case DecRefMsgAndStopTrackingHard:
2907 E = IgnoreRetainMsg ? StopTracking : DecRefAndStopTrackingHard;
Jordan Rose4531b7d2012-07-02 19:27:43 +00002908 break;
2909 case MakeCollectable:
2910 E = C.isObjCGCEnabled() ? DecRef : DoNothing;
2911 break;
Jordy Rosee0a5d322011-08-23 20:27:16 +00002912 }
2913
2914 // Handle all use-after-releases.
Jordy Rose17a38e22011-09-02 05:55:19 +00002915 if (!C.isObjCGCEnabled() && V.getKind() == RefVal::Released) {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002916 V = V ^ RefVal::ErrorUseAfterRelease;
2917 hasErr = V.getKind();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002918 return setRefBinding(state, sym, V);
Jordy Rosee0a5d322011-08-23 20:27:16 +00002919 }
2920
2921 switch (E) {
2922 case DecRefMsg:
2923 case IncRefMsg:
2924 case MakeCollectable:
Anna Zaks554067f2012-08-29 23:23:43 +00002925 case DecRefMsgAndStopTrackingHard:
Jordy Rosee0a5d322011-08-23 20:27:16 +00002926 llvm_unreachable("DecRefMsg/IncRefMsg/MakeCollectable already converted");
Jordy Rosee0a5d322011-08-23 20:27:16 +00002927
2928 case Dealloc:
2929 // Any use of -dealloc in GC is *bad*.
Jordy Rose17a38e22011-09-02 05:55:19 +00002930 if (C.isObjCGCEnabled()) {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002931 V = V ^ RefVal::ErrorDeallocGC;
2932 hasErr = V.getKind();
2933 break;
2934 }
2935
2936 switch (V.getKind()) {
2937 default:
2938 llvm_unreachable("Invalid RefVal state for an explicit dealloc.");
Jordy Rosee0a5d322011-08-23 20:27:16 +00002939 case RefVal::Owned:
2940 // The object immediately transitions to the released state.
2941 V = V ^ RefVal::Released;
2942 V.clearCounts();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002943 return setRefBinding(state, sym, V);
Jordy Rosee0a5d322011-08-23 20:27:16 +00002944 case RefVal::NotOwned:
2945 V = V ^ RefVal::ErrorDeallocNotOwned;
2946 hasErr = V.getKind();
2947 break;
2948 }
2949 break;
2950
Jordy Rosee0a5d322011-08-23 20:27:16 +00002951 case MayEscape:
2952 if (V.getKind() == RefVal::Owned) {
2953 V = V ^ RefVal::NotOwned;
2954 break;
2955 }
2956
2957 // Fall-through.
2958
Jordy Rosee0a5d322011-08-23 20:27:16 +00002959 case DoNothing:
2960 return state;
2961
2962 case Autorelease:
Jordy Rose17a38e22011-09-02 05:55:19 +00002963 if (C.isObjCGCEnabled())
Jordy Rosee0a5d322011-08-23 20:27:16 +00002964 return state;
Jordy Rosee0a5d322011-08-23 20:27:16 +00002965 // Update the autorelease counts.
Jordy Rosee0a5d322011-08-23 20:27:16 +00002966 V = V.autorelease();
2967 break;
2968
2969 case StopTracking:
Anna Zaks554067f2012-08-29 23:23:43 +00002970 case StopTrackingHard:
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002971 return removeRefBinding(state, sym);
Jordy Rosee0a5d322011-08-23 20:27:16 +00002972
2973 case IncRef:
2974 switch (V.getKind()) {
2975 default:
2976 llvm_unreachable("Invalid RefVal state for a retain.");
Jordy Rosee0a5d322011-08-23 20:27:16 +00002977 case RefVal::Owned:
2978 case RefVal::NotOwned:
2979 V = V + 1;
2980 break;
2981 case RefVal::Released:
2982 // Non-GC cases are handled above.
Jordy Rose17a38e22011-09-02 05:55:19 +00002983 assert(C.isObjCGCEnabled());
Jordy Rosee0a5d322011-08-23 20:27:16 +00002984 V = (V ^ RefVal::Owned) + 1;
2985 break;
2986 }
2987 break;
2988
Jordy Rosee0a5d322011-08-23 20:27:16 +00002989 case DecRef:
2990 case DecRefBridgedTransfered:
Anna Zaks554067f2012-08-29 23:23:43 +00002991 case DecRefAndStopTrackingHard:
Jordy Rosee0a5d322011-08-23 20:27:16 +00002992 switch (V.getKind()) {
2993 default:
2994 // case 'RefVal::Released' handled above.
2995 llvm_unreachable("Invalid RefVal state for a release.");
Jordy Rosee0a5d322011-08-23 20:27:16 +00002996
2997 case RefVal::Owned:
2998 assert(V.getCount() > 0);
2999 if (V.getCount() == 1)
3000 V = V ^ (E == DecRefBridgedTransfered ?
3001 RefVal::NotOwned : RefVal::Released);
Anna Zaks554067f2012-08-29 23:23:43 +00003002 else if (E == DecRefAndStopTrackingHard)
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003003 return removeRefBinding(state, sym);
Jordan Rose4531b7d2012-07-02 19:27:43 +00003004
Jordy Rosee0a5d322011-08-23 20:27:16 +00003005 V = V - 1;
3006 break;
3007
3008 case RefVal::NotOwned:
Jordan Rose4531b7d2012-07-02 19:27:43 +00003009 if (V.getCount() > 0) {
Anna Zaks554067f2012-08-29 23:23:43 +00003010 if (E == DecRefAndStopTrackingHard)
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003011 return removeRefBinding(state, sym);
Jordy Rosee0a5d322011-08-23 20:27:16 +00003012 V = V - 1;
Jordan Rose4531b7d2012-07-02 19:27:43 +00003013 } else {
Jordy Rosee0a5d322011-08-23 20:27:16 +00003014 V = V ^ RefVal::ErrorReleaseNotOwned;
3015 hasErr = V.getKind();
3016 }
3017 break;
3018
3019 case RefVal::Released:
3020 // Non-GC cases are handled above.
Jordy Rose17a38e22011-09-02 05:55:19 +00003021 assert(C.isObjCGCEnabled());
Jordy Rosee0a5d322011-08-23 20:27:16 +00003022 V = V ^ RefVal::ErrorUseAfterRelease;
3023 hasErr = V.getKind();
3024 break;
3025 }
3026 break;
3027 }
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003028 return setRefBinding(state, sym, V);
Jordy Rosee0a5d322011-08-23 20:27:16 +00003029}
3030
Ted Kremenek8bef8232012-01-26 21:29:00 +00003031void RetainCountChecker::processNonLeakError(ProgramStateRef St,
Jordy Rose910c4052011-09-02 06:44:22 +00003032 SourceRange ErrorRange,
3033 RefVal::Kind ErrorKind,
3034 SymbolRef Sym,
3035 CheckerContext &C) const {
Jordy Rose294396b2011-08-22 23:48:23 +00003036 ExplodedNode *N = C.generateSink(St);
3037 if (!N)
3038 return;
3039
Jordy Rose294396b2011-08-22 23:48:23 +00003040 CFRefBug *BT;
3041 switch (ErrorKind) {
3042 default:
3043 llvm_unreachable("Unhandled error.");
Jordy Rose294396b2011-08-22 23:48:23 +00003044 case RefVal::ErrorUseAfterRelease:
Jordy Rosed6334e12011-08-25 00:34:03 +00003045 if (!useAfterRelease)
3046 useAfterRelease.reset(new UseAfterRelease());
3047 BT = &*useAfterRelease;
Jordy Rose294396b2011-08-22 23:48:23 +00003048 break;
3049 case RefVal::ErrorReleaseNotOwned:
Jordy Rosed6334e12011-08-25 00:34:03 +00003050 if (!releaseNotOwned)
3051 releaseNotOwned.reset(new BadRelease());
3052 BT = &*releaseNotOwned;
Jordy Rose294396b2011-08-22 23:48:23 +00003053 break;
3054 case RefVal::ErrorDeallocGC:
Jordy Rosed6334e12011-08-25 00:34:03 +00003055 if (!deallocGC)
3056 deallocGC.reset(new DeallocGC());
3057 BT = &*deallocGC;
Jordy Rose294396b2011-08-22 23:48:23 +00003058 break;
3059 case RefVal::ErrorDeallocNotOwned:
Jordy Rosed6334e12011-08-25 00:34:03 +00003060 if (!deallocNotOwned)
3061 deallocNotOwned.reset(new DeallocNotOwned());
3062 BT = &*deallocNotOwned;
Jordy Rose294396b2011-08-22 23:48:23 +00003063 break;
3064 }
3065
Jordy Rosed6334e12011-08-25 00:34:03 +00003066 assert(BT);
David Blaikie4e4d0842012-03-11 07:00:24 +00003067 CFRefReport *report = new CFRefReport(*BT, C.getASTContext().getLangOpts(),
Jordy Rose17a38e22011-09-02 05:55:19 +00003068 C.isObjCGCEnabled(), SummaryLog,
3069 N, Sym);
Jordy Rose294396b2011-08-22 23:48:23 +00003070 report->addRange(ErrorRange);
Jordan Rose785950e2012-11-02 01:53:40 +00003071 C.emitReport(report);
Jordy Rose294396b2011-08-22 23:48:23 +00003072}
3073
Jordy Rose910c4052011-09-02 06:44:22 +00003074//===----------------------------------------------------------------------===//
3075// Handle the return values of retain-count-related functions.
3076//===----------------------------------------------------------------------===//
3077
3078bool RetainCountChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
Jordy Rose76c506f2011-08-21 21:58:18 +00003079 // Get the callee. We're only interested in simple C functions.
Ted Kremenek8bef8232012-01-26 21:29:00 +00003080 ProgramStateRef state = C.getState();
Anna Zaksb805c8f2011-12-01 05:57:37 +00003081 const FunctionDecl *FD = C.getCalleeDecl(CE);
Jordy Rose76c506f2011-08-21 21:58:18 +00003082 if (!FD)
3083 return false;
3084
3085 IdentifierInfo *II = FD->getIdentifier();
3086 if (!II)
3087 return false;
3088
3089 // For now, we're only handling the functions that return aliases of their
3090 // arguments: CFRetain and CFMakeCollectable (and their families).
3091 // Eventually we should add other functions we can model entirely,
3092 // such as CFRelease, which don't invalidate their arguments or globals.
3093 if (CE->getNumArgs() != 1)
3094 return false;
3095
3096 // Get the name of the function.
3097 StringRef FName = II->getName();
3098 FName = FName.substr(FName.find_first_not_of('_'));
3099
3100 // See if it's one of the specific functions we know how to eval.
3101 bool canEval = false;
3102
Anna Zaksb805c8f2011-12-01 05:57:37 +00003103 QualType ResultTy = CE->getCallReturnType();
Jordy Rose76c506f2011-08-21 21:58:18 +00003104 if (ResultTy->isObjCIdType()) {
3105 // Handle: id NSMakeCollectable(CFTypeRef)
3106 canEval = II->isStr("NSMakeCollectable");
3107 } else if (ResultTy->isPointerType()) {
3108 // Handle: (CF|CG)Retain
3109 // CFMakeCollectable
3110 // It's okay to be a little sloppy here (CGMakeCollectable doesn't exist).
3111 if (cocoa::isRefType(ResultTy, "CF", FName) ||
3112 cocoa::isRefType(ResultTy, "CG", FName)) {
3113 canEval = isRetain(FD, FName) || isMakeCollectable(FD, FName);
3114 }
3115 }
3116
3117 if (!canEval)
3118 return false;
3119
3120 // Bind the return value.
Ted Kremenek5eca4822012-01-06 22:09:28 +00003121 const LocationContext *LCtx = C.getLocationContext();
3122 SVal RetVal = state->getSVal(CE->getArg(0), LCtx);
Jordy Rose76c506f2011-08-21 21:58:18 +00003123 if (RetVal.isUnknown()) {
3124 // If the receiver is unknown, conjure a return value.
3125 SValBuilder &SVB = C.getSValBuilder();
Ted Kremenek66c486f2012-08-22 06:26:15 +00003126 RetVal = SVB.conjureSymbolVal(0, CE, LCtx, ResultTy, C.blockCount());
Jordy Rose76c506f2011-08-21 21:58:18 +00003127 }
Ted Kremenek5eca4822012-01-06 22:09:28 +00003128 state = state->BindExpr(CE, LCtx, RetVal, false);
Jordy Rose76c506f2011-08-21 21:58:18 +00003129
Jordy Rose294396b2011-08-22 23:48:23 +00003130 // FIXME: This should not be necessary, but otherwise the argument seems to be
3131 // considered alive during the next statement.
3132 if (const MemRegion *ArgRegion = RetVal.getAsRegion()) {
3133 // Save the refcount status of the argument.
3134 SymbolRef Sym = RetVal.getAsLocSymbol();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003135 const RefVal *Binding = 0;
Jordy Rose294396b2011-08-22 23:48:23 +00003136 if (Sym)
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003137 Binding = getRefBinding(state, Sym);
Jordy Rose76c506f2011-08-21 21:58:18 +00003138
Jordy Rose294396b2011-08-22 23:48:23 +00003139 // Invalidate the argument region.
Anna Zaksbf53dfa2012-12-20 00:38:25 +00003140 state = state->invalidateRegions(ArgRegion, CE, C.blockCount(), LCtx,
Anna Zaks64eb0702013-01-16 01:35:54 +00003141 /*CausesPointerEscape*/ false);
Jordy Rose76c506f2011-08-21 21:58:18 +00003142
Jordy Rose294396b2011-08-22 23:48:23 +00003143 // Restore the refcount status of the argument.
3144 if (Binding)
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003145 state = setRefBinding(state, Sym, *Binding);
Jordy Rose294396b2011-08-22 23:48:23 +00003146 }
3147
Anna Zaks0bd6b112011-10-26 21:06:34 +00003148 C.addTransition(state);
Jordy Rose76c506f2011-08-21 21:58:18 +00003149 return true;
3150}
3151
Jordy Rose910c4052011-09-02 06:44:22 +00003152//===----------------------------------------------------------------------===//
3153// Handle return statements.
3154//===----------------------------------------------------------------------===//
Jordy Rosef53e8c72011-08-23 19:43:16 +00003155
Jordy Rose910c4052011-09-02 06:44:22 +00003156void RetainCountChecker::checkPreStmt(const ReturnStmt *S,
3157 CheckerContext &C) const {
Ted Kremeneke5715782012-02-25 02:09:09 +00003158
3159 // Only adjust the reference count if this is the top-level call frame,
3160 // and not the result of inlining. In the future, we should do
3161 // better checking even for inlined calls, and see if they match
3162 // with their expected semantics (e.g., the method should return a retained
3163 // object, etc.).
Anna Zaksfadcd5d2012-11-03 02:54:16 +00003164 if (!C.inTopFrame())
Ted Kremeneke5715782012-02-25 02:09:09 +00003165 return;
3166
Jordy Rosef53e8c72011-08-23 19:43:16 +00003167 const Expr *RetE = S->getRetValue();
3168 if (!RetE)
3169 return;
3170
Ted Kremenek8bef8232012-01-26 21:29:00 +00003171 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00003172 SymbolRef Sym =
3173 state->getSValAsScalarOrLoc(RetE, C.getLocationContext()).getAsLocSymbol();
Jordy Rosef53e8c72011-08-23 19:43:16 +00003174 if (!Sym)
3175 return;
3176
3177 // Get the reference count binding (if any).
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003178 const RefVal *T = getRefBinding(state, Sym);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003179 if (!T)
3180 return;
3181
3182 // Change the reference count.
3183 RefVal X = *T;
3184
3185 switch (X.getKind()) {
3186 case RefVal::Owned: {
3187 unsigned cnt = X.getCount();
3188 assert(cnt > 0);
3189 X.setCount(cnt - 1);
3190 X = X ^ RefVal::ReturnedOwned;
3191 break;
3192 }
3193
3194 case RefVal::NotOwned: {
3195 unsigned cnt = X.getCount();
3196 if (cnt) {
3197 X.setCount(cnt - 1);
3198 X = X ^ RefVal::ReturnedOwned;
3199 }
3200 else {
3201 X = X ^ RefVal::ReturnedNotOwned;
3202 }
3203 break;
3204 }
3205
3206 default:
3207 return;
3208 }
3209
3210 // Update the binding.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003211 state = setRefBinding(state, Sym, X);
Anna Zaks0bd6b112011-10-26 21:06:34 +00003212 ExplodedNode *Pred = C.addTransition(state);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003213
3214 // At this point we have updated the state properly.
3215 // Everything after this is merely checking to see if the return value has
3216 // been over- or under-retained.
3217
3218 // Did we cache out?
3219 if (!Pred)
3220 return;
3221
Jordy Rosef53e8c72011-08-23 19:43:16 +00003222 // Update the autorelease counts.
3223 static SimpleProgramPointTag
Jordy Rose910c4052011-09-02 06:44:22 +00003224 AutoreleaseTag("RetainCountChecker : Autorelease");
Jordan Rose4ee1c552012-12-06 18:58:18 +00003225 state = handleAutoreleaseCounts(state, Pred, &AutoreleaseTag, C, Sym, X);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003226
3227 // Did we cache out?
Jordan Rose4ee1c552012-12-06 18:58:18 +00003228 if (!state)
Jordy Rosef53e8c72011-08-23 19:43:16 +00003229 return;
3230
3231 // Get the updated binding.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003232 T = getRefBinding(state, Sym);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003233 assert(T);
3234 X = *T;
3235
3236 // Consult the summary of the enclosing method.
Jordy Rose17a38e22011-09-02 05:55:19 +00003237 RetainSummaryManager &Summaries = getSummaryManager(C);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003238 const Decl *CD = &Pred->getCodeDecl();
Jordan Rose4531b7d2012-07-02 19:27:43 +00003239 RetEffect RE = RetEffect::MakeNoRet();
Jordy Rosef53e8c72011-08-23 19:43:16 +00003240
Jordan Rose4531b7d2012-07-02 19:27:43 +00003241 // FIXME: What is the convention for blocks? Is there one?
Jordy Rosef53e8c72011-08-23 19:43:16 +00003242 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CD)) {
Jordy Roseb6cfc092011-08-25 00:10:37 +00003243 const RetainSummary *Summ = Summaries.getMethodSummary(MD);
Jordan Rose4531b7d2012-07-02 19:27:43 +00003244 RE = Summ->getRetEffect();
3245 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) {
3246 if (!isa<CXXMethodDecl>(FD)) {
3247 const RetainSummary *Summ = Summaries.getFunctionSummary(FD);
3248 RE = Summ->getRetEffect();
3249 }
Jordy Rosef53e8c72011-08-23 19:43:16 +00003250 }
3251
Jordan Rose4531b7d2012-07-02 19:27:43 +00003252 checkReturnWithRetEffect(S, C, Pred, RE, X, Sym, state);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003253}
3254
Jordy Rose910c4052011-09-02 06:44:22 +00003255void RetainCountChecker::checkReturnWithRetEffect(const ReturnStmt *S,
3256 CheckerContext &C,
3257 ExplodedNode *Pred,
3258 RetEffect RE, RefVal X,
3259 SymbolRef Sym,
Ted Kremenek8bef8232012-01-26 21:29:00 +00003260 ProgramStateRef state) const {
Jordy Rosef53e8c72011-08-23 19:43:16 +00003261 // Any leaks or other errors?
3262 if (X.isReturnedOwned() && X.getCount() == 0) {
3263 if (RE.getKind() != RetEffect::NoRet) {
3264 bool hasError = false;
Jordy Rose17a38e22011-09-02 05:55:19 +00003265 if (C.isObjCGCEnabled() && RE.getObjKind() == RetEffect::ObjC) {
Jordy Rosef53e8c72011-08-23 19:43:16 +00003266 // Things are more complicated with garbage collection. If the
3267 // returned object is suppose to be an Objective-C object, we have
3268 // a leak (as the caller expects a GC'ed object) because no
3269 // method should return ownership unless it returns a CF object.
3270 hasError = true;
3271 X = X ^ RefVal::ErrorGCLeakReturned;
3272 }
3273 else if (!RE.isOwned()) {
3274 // Either we are using GC and the returned object is a CF type
3275 // or we aren't using GC. In either case, we expect that the
3276 // enclosing method is expected to return ownership.
3277 hasError = true;
3278 X = X ^ RefVal::ErrorLeakReturned;
3279 }
3280
3281 if (hasError) {
3282 // Generate an error node.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003283 state = setRefBinding(state, Sym, X);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003284
3285 static SimpleProgramPointTag
Jordy Rose910c4052011-09-02 06:44:22 +00003286 ReturnOwnLeakTag("RetainCountChecker : ReturnsOwnLeak");
Anna Zaks0bd6b112011-10-26 21:06:34 +00003287 ExplodedNode *N = C.addTransition(state, Pred, &ReturnOwnLeakTag);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003288 if (N) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003289 const LangOptions &LOpts = C.getASTContext().getLangOpts();
Jordy Rose17a38e22011-09-02 05:55:19 +00003290 bool GCEnabled = C.isObjCGCEnabled();
Jordy Rosef53e8c72011-08-23 19:43:16 +00003291 CFRefReport *report =
Jordy Rose17a38e22011-09-02 05:55:19 +00003292 new CFRefLeakReport(*getLeakAtReturnBug(LOpts, GCEnabled),
3293 LOpts, GCEnabled, SummaryLog,
Ted Kremenek08a838d2013-04-16 21:44:22 +00003294 N, Sym, C, IncludeAllocationLine);
3295
Jordan Rose785950e2012-11-02 01:53:40 +00003296 C.emitReport(report);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003297 }
3298 }
3299 }
3300 } else if (X.isReturnedNotOwned()) {
3301 if (RE.isOwned()) {
3302 // Trying to return a not owned object to a caller expecting an
3303 // owned object.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003304 state = setRefBinding(state, Sym, X ^ RefVal::ErrorReturnedNotOwned);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003305
3306 static SimpleProgramPointTag
Jordy Rose910c4052011-09-02 06:44:22 +00003307 ReturnNotOwnedTag("RetainCountChecker : ReturnNotOwnedForOwned");
Anna Zaks0bd6b112011-10-26 21:06:34 +00003308 ExplodedNode *N = C.addTransition(state, Pred, &ReturnNotOwnedTag);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003309 if (N) {
Jordy Rosed6334e12011-08-25 00:34:03 +00003310 if (!returnNotOwnedForOwned)
3311 returnNotOwnedForOwned.reset(new ReturnedNotOwnedForOwned());
3312
Jordy Rosef53e8c72011-08-23 19:43:16 +00003313 CFRefReport *report =
Jordy Rosed6334e12011-08-25 00:34:03 +00003314 new CFRefReport(*returnNotOwnedForOwned,
David Blaikie4e4d0842012-03-11 07:00:24 +00003315 C.getASTContext().getLangOpts(),
Jordy Rose17a38e22011-09-02 05:55:19 +00003316 C.isObjCGCEnabled(), SummaryLog, N, Sym);
Jordan Rose785950e2012-11-02 01:53:40 +00003317 C.emitReport(report);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003318 }
3319 }
3320 }
3321}
3322
Jordy Rose8d228632011-08-23 20:07:14 +00003323//===----------------------------------------------------------------------===//
Jordy Rose910c4052011-09-02 06:44:22 +00003324// Check various ways a symbol can be invalidated.
3325//===----------------------------------------------------------------------===//
3326
Anna Zaks390909c2011-10-06 00:43:15 +00003327void RetainCountChecker::checkBind(SVal loc, SVal val, const Stmt *S,
Jordy Rose910c4052011-09-02 06:44:22 +00003328 CheckerContext &C) const {
3329 // Are we storing to something that causes the value to "escape"?
3330 bool escapes = true;
3331
3332 // A value escapes in three possible cases (this may change):
3333 //
3334 // (1) we are binding to something that is not a memory region.
3335 // (2) we are binding to a memregion that does not have stack storage
3336 // (3) we are binding to a memregion with stack storage that the store
3337 // does not understand.
Ted Kremenek8bef8232012-01-26 21:29:00 +00003338 ProgramStateRef state = C.getState();
Jordy Rose910c4052011-09-02 06:44:22 +00003339
David Blaikiedc84cd52013-02-20 22:23:23 +00003340 if (Optional<loc::MemRegionVal> regionLoc = loc.getAs<loc::MemRegionVal>()) {
Jordy Rose910c4052011-09-02 06:44:22 +00003341 escapes = !regionLoc->getRegion()->hasStackStorage();
3342
3343 if (!escapes) {
3344 // To test (3), generate a new state with the binding added. If it is
3345 // the same state, then it escapes (since the store cannot represent
3346 // the binding).
Anna Zakse7958da2012-05-02 00:15:40 +00003347 // Do this only if we know that the store is not supposed to generate the
3348 // same state.
3349 SVal StoredVal = state->getSVal(regionLoc->getRegion());
3350 if (StoredVal != val)
3351 escapes = (state == (state->bindLoc(*regionLoc, val)));
Jordy Rose910c4052011-09-02 06:44:22 +00003352 }
Ted Kremenekde5b4fb2012-03-27 01:12:45 +00003353 if (!escapes) {
3354 // Case 4: We do not currently model what happens when a symbol is
3355 // assigned to a struct field, so be conservative here and let the symbol
3356 // go. TODO: This could definitely be improved upon.
3357 escapes = !isa<VarRegion>(regionLoc->getRegion());
3358 }
Jordy Rose910c4052011-09-02 06:44:22 +00003359 }
3360
3361 // If our store can represent the binding and we aren't storing to something
3362 // that doesn't have local storage then just return and have the simulation
3363 // state continue as is.
3364 if (!escapes)
3365 return;
3366
3367 // Otherwise, find all symbols referenced by 'val' that we are tracking
3368 // and stop tracking them.
3369 state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
Anna Zaks0bd6b112011-10-26 21:06:34 +00003370 C.addTransition(state);
Jordy Rose910c4052011-09-02 06:44:22 +00003371}
3372
Ted Kremenek8bef8232012-01-26 21:29:00 +00003373ProgramStateRef RetainCountChecker::evalAssume(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003374 SVal Cond,
3375 bool Assumption) const {
3376
3377 // FIXME: We may add to the interface of evalAssume the list of symbols
3378 // whose assumptions have changed. For now we just iterate through the
3379 // bindings and check if any of the tracked symbols are NULL. This isn't
3380 // too bad since the number of symbols we will track in practice are
3381 // probably small and evalAssume is only called at branches and a few
3382 // other places.
Jordan Rose166d5022012-11-02 01:54:06 +00003383 RefBindingsTy B = state->get<RefBindings>();
Jordy Rose910c4052011-09-02 06:44:22 +00003384
3385 if (B.isEmpty())
3386 return state;
3387
3388 bool changed = false;
Jordan Rose166d5022012-11-02 01:54:06 +00003389 RefBindingsTy::Factory &RefBFactory = state->get_context<RefBindings>();
Jordy Rose910c4052011-09-02 06:44:22 +00003390
Jordan Rose166d5022012-11-02 01:54:06 +00003391 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Ted Kremenek47cbd0f2012-09-07 22:31:01 +00003392 // Check if the symbol is null stop tracking the symbol.
Jordan Roseec8d4202012-11-01 00:18:27 +00003393 ConstraintManager &CMgr = state->getConstraintManager();
3394 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
3395 if (AllocFailed.isConstrainedTrue()) {
Jordy Rose910c4052011-09-02 06:44:22 +00003396 changed = true;
3397 B = RefBFactory.remove(B, I.getKey());
3398 }
3399 }
3400
3401 if (changed)
3402 state = state->set<RefBindings>(B);
3403
3404 return state;
3405}
3406
Ted Kremenek8bef8232012-01-26 21:29:00 +00003407ProgramStateRef
3408RetainCountChecker::checkRegionChanges(ProgramStateRef state,
Anna Zaksbf53dfa2012-12-20 00:38:25 +00003409 const InvalidatedSymbols *invalidated,
Jordy Rose910c4052011-09-02 06:44:22 +00003410 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00003411 ArrayRef<const MemRegion *> Regions,
Jordan Rose740d4902012-07-02 19:27:35 +00003412 const CallEvent *Call) const {
Jordy Rose910c4052011-09-02 06:44:22 +00003413 if (!invalidated)
3414 return state;
3415
3416 llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
3417 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
3418 E = ExplicitRegions.end(); I != E; ++I) {
3419 if (const SymbolicRegion *SR = (*I)->StripCasts()->getAs<SymbolicRegion>())
3420 WhitelistedSymbols.insert(SR->getSymbol());
3421 }
3422
Anna Zaksbf53dfa2012-12-20 00:38:25 +00003423 for (InvalidatedSymbols::const_iterator I=invalidated->begin(),
Jordy Rose910c4052011-09-02 06:44:22 +00003424 E = invalidated->end(); I!=E; ++I) {
3425 SymbolRef sym = *I;
3426 if (WhitelistedSymbols.count(sym))
3427 continue;
3428 // Remove any existing reference-count binding.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003429 state = removeRefBinding(state, sym);
Jordy Rose910c4052011-09-02 06:44:22 +00003430 }
3431 return state;
3432}
3433
3434//===----------------------------------------------------------------------===//
Jordy Rose8d228632011-08-23 20:07:14 +00003435// Handle dead symbols and end-of-path.
3436//===----------------------------------------------------------------------===//
3437
Jordan Rose4ee1c552012-12-06 18:58:18 +00003438ProgramStateRef
3439RetainCountChecker::handleAutoreleaseCounts(ProgramStateRef state,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003440 ExplodedNode *Pred,
Jordan Rose2bce86c2012-08-18 00:30:16 +00003441 const ProgramPointTag *Tag,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003442 CheckerContext &Ctx,
Jordy Rose910c4052011-09-02 06:44:22 +00003443 SymbolRef Sym, RefVal V) const {
Jordy Rose8d228632011-08-23 20:07:14 +00003444 unsigned ACnt = V.getAutoreleaseCount();
3445
3446 // No autorelease counts? Nothing to be done.
3447 if (!ACnt)
Jordan Rose4ee1c552012-12-06 18:58:18 +00003448 return state;
Jordy Rose8d228632011-08-23 20:07:14 +00003449
Anna Zaks6a93bd52011-10-25 19:57:11 +00003450 assert(!Ctx.isObjCGCEnabled() && "Autorelease counts in GC mode?");
Jordy Rose8d228632011-08-23 20:07:14 +00003451 unsigned Cnt = V.getCount();
3452
3453 // FIXME: Handle sending 'autorelease' to already released object.
3454
3455 if (V.getKind() == RefVal::ReturnedOwned)
3456 ++Cnt;
3457
3458 if (ACnt <= Cnt) {
3459 if (ACnt == Cnt) {
3460 V.clearCounts();
3461 if (V.getKind() == RefVal::ReturnedOwned)
3462 V = V ^ RefVal::ReturnedNotOwned;
3463 else
3464 V = V ^ RefVal::NotOwned;
3465 } else {
Anna Zaks0217b1d2013-01-31 22:36:17 +00003466 V.setCount(V.getCount() - ACnt);
Jordy Rose8d228632011-08-23 20:07:14 +00003467 V.setAutoreleaseCount(0);
3468 }
Jordan Rose4ee1c552012-12-06 18:58:18 +00003469 return setRefBinding(state, Sym, V);
Jordy Rose8d228632011-08-23 20:07:14 +00003470 }
3471
3472 // Woah! More autorelease counts then retain counts left.
3473 // Emit hard error.
3474 V = V ^ RefVal::ErrorOverAutorelease;
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003475 state = setRefBinding(state, Sym, V);
Jordy Rose8d228632011-08-23 20:07:14 +00003476
Jordan Rosefa06f042012-08-20 18:43:42 +00003477 ExplodedNode *N = Ctx.generateSink(state, Pred, Tag);
Jordan Rose2bce86c2012-08-18 00:30:16 +00003478 if (N) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003479 SmallString<128> sbuf;
Jordy Rose8d228632011-08-23 20:07:14 +00003480 llvm::raw_svector_ostream os(sbuf);
Jordan Rose2545b1d2013-04-23 01:42:25 +00003481 os << "Object was autoreleased ";
Jordy Rose8d228632011-08-23 20:07:14 +00003482 if (V.getAutoreleaseCount() > 1)
Jordan Rose2545b1d2013-04-23 01:42:25 +00003483 os << V.getAutoreleaseCount() << " times but the object ";
3484 else
3485 os << "but ";
3486 os << "has a +" << V.getCount() << " retain count";
Jordy Rose8d228632011-08-23 20:07:14 +00003487
Jordy Rosed6334e12011-08-25 00:34:03 +00003488 if (!overAutorelease)
3489 overAutorelease.reset(new OverAutorelease());
3490
David Blaikie4e4d0842012-03-11 07:00:24 +00003491 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
Jordy Rose8d228632011-08-23 20:07:14 +00003492 CFRefReport *report =
Jordy Rosed6334e12011-08-25 00:34:03 +00003493 new CFRefReport(*overAutorelease, LOpts, /* GCEnabled = */ false,
3494 SummaryLog, N, Sym, os.str());
Jordan Rose785950e2012-11-02 01:53:40 +00003495 Ctx.emitReport(report);
Jordy Rose8d228632011-08-23 20:07:14 +00003496 }
3497
Jordan Rose4ee1c552012-12-06 18:58:18 +00003498 return 0;
Jordy Rose8d228632011-08-23 20:07:14 +00003499}
Jordy Rose38f17d62011-08-23 19:01:07 +00003500
Ted Kremenek8bef8232012-01-26 21:29:00 +00003501ProgramStateRef
3502RetainCountChecker::handleSymbolDeath(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003503 SymbolRef sid, RefVal V,
Jordy Rose38f17d62011-08-23 19:01:07 +00003504 SmallVectorImpl<SymbolRef> &Leaked) const {
Jordy Rose53376122011-08-24 04:48:19 +00003505 bool hasLeak = false;
Jordy Rose38f17d62011-08-23 19:01:07 +00003506 if (V.isOwned())
3507 hasLeak = true;
3508 else if (V.isNotOwned() || V.isReturnedOwned())
3509 hasLeak = (V.getCount() > 0);
3510
3511 if (!hasLeak)
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003512 return removeRefBinding(state, sid);
Jordy Rose38f17d62011-08-23 19:01:07 +00003513
3514 Leaked.push_back(sid);
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003515 return setRefBinding(state, sid, V ^ RefVal::ErrorLeak);
Jordy Rose38f17d62011-08-23 19:01:07 +00003516}
3517
3518ExplodedNode *
Ted Kremenek8bef8232012-01-26 21:29:00 +00003519RetainCountChecker::processLeaks(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003520 SmallVectorImpl<SymbolRef> &Leaked,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003521 CheckerContext &Ctx,
3522 ExplodedNode *Pred) const {
Jordy Rose38f17d62011-08-23 19:01:07 +00003523 // Generate an intermediate node representing the leak point.
Jordan Rose2bce86c2012-08-18 00:30:16 +00003524 ExplodedNode *N = Ctx.addTransition(state, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003525
3526 if (N) {
3527 for (SmallVectorImpl<SymbolRef>::iterator
3528 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3529
David Blaikie4e4d0842012-03-11 07:00:24 +00003530 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
Anna Zaks6a93bd52011-10-25 19:57:11 +00003531 bool GCEnabled = Ctx.isObjCGCEnabled();
Jordy Rose17a38e22011-09-02 05:55:19 +00003532 CFRefBug *BT = Pred ? getLeakWithinFunctionBug(LOpts, GCEnabled)
3533 : getLeakAtReturnBug(LOpts, GCEnabled);
Jordy Rose38f17d62011-08-23 19:01:07 +00003534 assert(BT && "BugType not initialized.");
Jordy Rose20589562011-08-24 22:39:09 +00003535
Jordy Rose17a38e22011-09-02 05:55:19 +00003536 CFRefLeakReport *report = new CFRefLeakReport(*BT, LOpts, GCEnabled,
Ted Kremenek08a838d2013-04-16 21:44:22 +00003537 SummaryLog, N, *I, Ctx,
3538 IncludeAllocationLine);
Jordan Rose785950e2012-11-02 01:53:40 +00003539 Ctx.emitReport(report);
Jordy Rose38f17d62011-08-23 19:01:07 +00003540 }
3541 }
3542
3543 return N;
3544}
3545
Anna Zaks344c77a2013-01-03 00:25:29 +00003546void RetainCountChecker::checkEndFunction(CheckerContext &Ctx) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +00003547 ProgramStateRef state = Ctx.getState();
Jordan Rose166d5022012-11-02 01:54:06 +00003548 RefBindingsTy B = state->get<RefBindings>();
Anna Zaksaf498a22011-10-25 19:56:48 +00003549 ExplodedNode *Pred = Ctx.getPredecessor();
Jordy Rose38f17d62011-08-23 19:01:07 +00003550
Jordan Rosed8188f82013-08-01 22:16:36 +00003551 // Don't process anything within synthesized bodies.
3552 const LocationContext *LCtx = Pred->getLocationContext();
3553 if (LCtx->getAnalysisDeclContext()->isBodyAutosynthesized()) {
3554 assert(LCtx->getParent());
3555 return;
3556 }
3557
Jordan Rose166d5022012-11-02 01:54:06 +00003558 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Jordan Rose4ee1c552012-12-06 18:58:18 +00003559 state = handleAutoreleaseCounts(state, Pred, /*Tag=*/0, Ctx,
3560 I->first, I->second);
Jordy Rose8d228632011-08-23 20:07:14 +00003561 if (!state)
Jordy Rose38f17d62011-08-23 19:01:07 +00003562 return;
3563 }
3564
Ted Kremenek0cf3d472012-02-07 00:24:33 +00003565 // If the current LocationContext has a parent, don't check for leaks.
3566 // We will do that later.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003567 // FIXME: we should instead check for imbalances of the retain/releases,
Ted Kremenek0cf3d472012-02-07 00:24:33 +00003568 // and suggest annotations.
Jordan Rosed8188f82013-08-01 22:16:36 +00003569 if (LCtx->getParent())
Ted Kremenek0cf3d472012-02-07 00:24:33 +00003570 return;
3571
Jordy Rose38f17d62011-08-23 19:01:07 +00003572 B = state->get<RefBindings>();
3573 SmallVector<SymbolRef, 10> Leaked;
3574
Jordan Rose166d5022012-11-02 01:54:06 +00003575 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I)
Jordy Rose8d228632011-08-23 20:07:14 +00003576 state = handleSymbolDeath(state, I->first, I->second, Leaked);
Jordy Rose38f17d62011-08-23 19:01:07 +00003577
Jordan Rose2bce86c2012-08-18 00:30:16 +00003578 processLeaks(state, Leaked, Ctx, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003579}
3580
3581const ProgramPointTag *
Jordy Rose910c4052011-09-02 06:44:22 +00003582RetainCountChecker::getDeadSymbolTag(SymbolRef sym) const {
Jordy Rose38f17d62011-08-23 19:01:07 +00003583 const SimpleProgramPointTag *&tag = DeadSymbolTags[sym];
3584 if (!tag) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003585 SmallString<64> buf;
Jordy Rose38f17d62011-08-23 19:01:07 +00003586 llvm::raw_svector_ostream out(buf);
Anna Zaksf62ceec2011-12-05 18:58:11 +00003587 out << "RetainCountChecker : Dead Symbol : ";
3588 sym->dumpToStream(out);
Jordy Rose38f17d62011-08-23 19:01:07 +00003589 tag = new SimpleProgramPointTag(out.str());
3590 }
3591 return tag;
3592}
3593
Jordy Rose910c4052011-09-02 06:44:22 +00003594void RetainCountChecker::checkDeadSymbols(SymbolReaper &SymReaper,
3595 CheckerContext &C) const {
Jordy Rose38f17d62011-08-23 19:01:07 +00003596 ExplodedNode *Pred = C.getPredecessor();
3597
Ted Kremenek8bef8232012-01-26 21:29:00 +00003598 ProgramStateRef state = C.getState();
Jordan Rose166d5022012-11-02 01:54:06 +00003599 RefBindingsTy B = state->get<RefBindings>();
Jordan Rose4ee1c552012-12-06 18:58:18 +00003600 SmallVector<SymbolRef, 10> Leaked;
Jordy Rose38f17d62011-08-23 19:01:07 +00003601
3602 // Update counts from autorelease pools
3603 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3604 E = SymReaper.dead_end(); I != E; ++I) {
3605 SymbolRef Sym = *I;
3606 if (const RefVal *T = B.lookup(Sym)){
3607 // Use the symbol as the tag.
3608 // FIXME: This might not be as unique as we would like.
Jordan Rose2bce86c2012-08-18 00:30:16 +00003609 const ProgramPointTag *Tag = getDeadSymbolTag(Sym);
Jordan Rose4ee1c552012-12-06 18:58:18 +00003610 state = handleAutoreleaseCounts(state, Pred, Tag, C, Sym, *T);
Jordy Rose8d228632011-08-23 20:07:14 +00003611 if (!state)
Jordy Rose38f17d62011-08-23 19:01:07 +00003612 return;
Jordan Rose4ee1c552012-12-06 18:58:18 +00003613
3614 // Fetch the new reference count from the state, and use it to handle
3615 // this symbol.
3616 state = handleSymbolDeath(state, *I, *getRefBinding(state, Sym), Leaked);
Jordy Rose38f17d62011-08-23 19:01:07 +00003617 }
3618 }
3619
Jordan Rose4ee1c552012-12-06 18:58:18 +00003620 if (Leaked.empty()) {
3621 C.addTransition(state);
3622 return;
Jordy Rose38f17d62011-08-23 19:01:07 +00003623 }
3624
Jordan Rose2bce86c2012-08-18 00:30:16 +00003625 Pred = processLeaks(state, Leaked, C, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003626
3627 // Did we cache out?
3628 if (!Pred)
3629 return;
3630
3631 // Now generate a new node that nukes the old bindings.
Jordan Rose4ee1c552012-12-06 18:58:18 +00003632 // The only bindings left at this point are the leaked symbols.
Jordan Rose166d5022012-11-02 01:54:06 +00003633 RefBindingsTy::Factory &F = state->get_context<RefBindings>();
Jordan Rose4ee1c552012-12-06 18:58:18 +00003634 B = state->get<RefBindings>();
Jordy Rose38f17d62011-08-23 19:01:07 +00003635
Jordan Rose4ee1c552012-12-06 18:58:18 +00003636 for (SmallVectorImpl<SymbolRef>::iterator I = Leaked.begin(),
3637 E = Leaked.end();
3638 I != E; ++I)
Jordy Rose38f17d62011-08-23 19:01:07 +00003639 B = F.remove(B, *I);
3640
3641 state = state->set<RefBindings>(B);
Anna Zaks0bd6b112011-10-26 21:06:34 +00003642 C.addTransition(state, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003643}
3644
Ted Kremenek8bef8232012-01-26 21:29:00 +00003645void RetainCountChecker::printState(raw_ostream &Out, ProgramStateRef State,
Jordy Rose910c4052011-09-02 06:44:22 +00003646 const char *NL, const char *Sep) const {
Jordy Rosedbd658e2011-08-28 19:11:56 +00003647
Jordan Rose166d5022012-11-02 01:54:06 +00003648 RefBindingsTy B = State->get<RefBindings>();
Jordy Rosedbd658e2011-08-28 19:11:56 +00003649
Ted Kremenek65a08922013-03-28 18:43:18 +00003650 if (B.isEmpty())
3651 return;
3652
3653 Out << Sep << NL;
Jordy Rosedbd658e2011-08-28 19:11:56 +00003654
Jordan Rose166d5022012-11-02 01:54:06 +00003655 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Jordy Rosedbd658e2011-08-28 19:11:56 +00003656 Out << I->first << " : ";
3657 I->second.print(Out);
3658 Out << NL;
3659 }
Jordy Rosedbd658e2011-08-28 19:11:56 +00003660}
3661
3662//===----------------------------------------------------------------------===//
Jordy Rose910c4052011-09-02 06:44:22 +00003663// Checker registration.
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00003664//===----------------------------------------------------------------------===//
3665
Jordy Rose17a38e22011-09-02 05:55:19 +00003666void ento::registerRetainCountChecker(CheckerManager &Mgr) {
Ted Kremenek08a838d2013-04-16 21:44:22 +00003667 Mgr.registerChecker<RetainCountChecker>(Mgr.getAnalyzerOptions());
Jordy Rose17a38e22011-09-02 05:55:19 +00003668}
3669
Ted Kremenek53c7ea12013-08-14 23:41:49 +00003670//===----------------------------------------------------------------------===//
3671// Implementation of the CallEffects API.
3672//===----------------------------------------------------------------------===//
3673
3674namespace clang { namespace ento { namespace objc_retain {
3675
3676// This is a bit gross, but it allows us to populate CallEffects without
3677// creating a bunch of accessors. This kind is very localized, so the
3678// damage of this macro is limited.
3679#define createCallEffect(D, KIND)\
3680 ASTContext &Ctx = D->getASTContext();\
3681 LangOptions L = Ctx.getLangOpts();\
3682 RetainSummaryManager M(Ctx, L.GCOnly, L.ObjCAutoRefCount);\
3683 const RetainSummary *S = M.get ## KIND ## Summary(D);\
3684 CallEffects CE(S->getRetEffect());\
3685 CE.Receiver = S->getReceiverEffect();\
Ted Kremenek21043742013-08-16 23:14:22 +00003686 unsigned N = D->param_size();\
Ted Kremenek53c7ea12013-08-14 23:41:49 +00003687 for (unsigned i = 0; i < N; ++i) {\
3688 CE.Args.push_back(S->getArg(i));\
3689 }
3690
3691CallEffects CallEffects::getEffect(const ObjCMethodDecl *MD) {
3692 createCallEffect(MD, Method);
3693 return CE;
3694}
3695
3696CallEffects CallEffects::getEffect(const FunctionDecl *FD) {
3697 createCallEffect(FD, Function);
3698 return CE;
3699}
3700
3701#undef createCallEffect
3702
3703}}}