blob: 1a1fa4e2e9a0c8196d5983ccb8efb278001e7f6a [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
321 /// Return the number of argument effects. This is O(n) in the number
322 /// of arguments.
323 unsigned getNumArgs() const {
324 unsigned N = 0;
325 for (ArgEffects::iterator I = Args.begin(), E = Args.end(); I != E; ++I) {
326 ++N;
327 };
328 return N;
329 }
Ted Kremenek11fe1752011-01-27 18:43:03 +0000330
331 void addArg(ArgEffects::Factory &af, unsigned idx, ArgEffect e) {
332 Args = af.add(Args, idx, e);
333 }
Mike Stump1eb44332009-09-09 15:08:12 +0000334
Ted Kremenek885c27b2009-05-04 05:31:22 +0000335 /// setDefaultArgEffect - Set the default argument effect.
336 void setDefaultArgEffect(ArgEffect E) {
337 DefaultArgEffect = E;
338 }
Mike Stump1eb44332009-09-09 15:08:12 +0000339
Ted Kremenek553cf182008-06-25 21:21:56 +0000340 /// getRetEffect - Returns the effect on the return value of the call.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000341 RetEffect getRetEffect() const { return Ret; }
Mike Stump1eb44332009-09-09 15:08:12 +0000342
Ted Kremenek885c27b2009-05-04 05:31:22 +0000343 /// setRetEffect - Set the effect of the return value of the call.
344 void setRetEffect(RetEffect E) { Ret = E; }
Mike Stump1eb44332009-09-09 15:08:12 +0000345
Ted Kremenek12b94342011-01-27 06:54:14 +0000346
347 /// Sets the effect on the receiver of the message.
348 void setReceiverEffect(ArgEffect e) { Receiver = e; }
349
Ted Kremenek553cf182008-06-25 21:21:56 +0000350 /// getReceiverEffect - Returns the effect on the receiver of the call.
351 /// This is only meaningful if the summary applies to an ObjCMessageExpr*.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000352 ArgEffect getReceiverEffect() const { return Receiver; }
Jordy Rose4df54fe2011-08-23 04:27:15 +0000353
354 /// Test if two retain summaries are identical. Note that merely equivalent
355 /// summaries are not necessarily identical (for example, if an explicit
356 /// argument effect matches the default effect).
357 bool operator==(const RetainSummary &Other) const {
358 return Args == Other.Args && DefaultArgEffect == Other.DefaultArgEffect &&
359 Receiver == Other.Receiver && Ret == Other.Ret;
360 }
Jordy Roseef945882012-03-18 01:26:10 +0000361
362 /// Profile this summary for inclusion in a FoldingSet.
363 void Profile(llvm::FoldingSetNodeID& ID) const {
364 ID.Add(Args);
365 ID.Add(DefaultArgEffect);
366 ID.Add(Receiver);
367 ID.Add(Ret);
368 }
369
370 /// A retain summary is simple if it has no ArgEffects other than the default.
371 bool isSimple() const {
372 return Args.isEmpty();
373 }
Jordan Rose4531b7d2012-07-02 19:27:43 +0000374
375private:
376 ArgEffects getArgEffects() const { return Args; }
377 ArgEffect getDefaultArgEffect() const { return DefaultArgEffect; }
378
379 friend class RetainSummaryManager;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000380};
Ted Kremenek4f22a782008-06-23 23:30:29 +0000381} // end anonymous namespace
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000382
Ted Kremenek553cf182008-06-25 21:21:56 +0000383//===----------------------------------------------------------------------===//
384// Data structures for constructing summaries.
385//===----------------------------------------------------------------------===//
Ted Kremenek53301ba2008-06-24 03:49:48 +0000386
Ted Kremenek553cf182008-06-25 21:21:56 +0000387namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000388class ObjCSummaryKey {
Ted Kremenek553cf182008-06-25 21:21:56 +0000389 IdentifierInfo* II;
390 Selector S;
Mike Stump1eb44332009-09-09 15:08:12 +0000391public:
Ted Kremenek553cf182008-06-25 21:21:56 +0000392 ObjCSummaryKey(IdentifierInfo* ii, Selector s)
393 : II(ii), S(s) {}
394
Ted Kremenek9c378f72011-08-12 23:37:29 +0000395 ObjCSummaryKey(const ObjCInterfaceDecl *d, Selector s)
Ted Kremenek553cf182008-06-25 21:21:56 +0000396 : II(d ? d->getIdentifier() : 0), S(s) {}
Ted Kremenek70b6a832009-05-13 18:16:01 +0000397
Ted Kremenek553cf182008-06-25 21:21:56 +0000398 ObjCSummaryKey(Selector s)
399 : II(0), S(s) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000400
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000401 IdentifierInfo *getIdentifier() const { return II; }
Ted Kremenek553cf182008-06-25 21:21:56 +0000402 Selector getSelector() const { return S; }
403};
Ted Kremenek4f22a782008-06-23 23:30:29 +0000404}
405
406namespace llvm {
Ted Kremenek553cf182008-06-25 21:21:56 +0000407template <> struct DenseMapInfo<ObjCSummaryKey> {
408 static inline ObjCSummaryKey getEmptyKey() {
409 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
410 DenseMapInfo<Selector>::getEmptyKey());
411 }
Mike Stump1eb44332009-09-09 15:08:12 +0000412
Ted Kremenek553cf182008-06-25 21:21:56 +0000413 static inline ObjCSummaryKey getTombstoneKey() {
414 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
Mike Stump1eb44332009-09-09 15:08:12 +0000415 DenseMapInfo<Selector>::getTombstoneKey());
Ted Kremenek553cf182008-06-25 21:21:56 +0000416 }
Mike Stump1eb44332009-09-09 15:08:12 +0000417
Ted Kremenek553cf182008-06-25 21:21:56 +0000418 static unsigned getHashValue(const ObjCSummaryKey &V) {
Benjamin Kramer28b23072012-05-27 13:28:44 +0000419 typedef std::pair<IdentifierInfo*, Selector> PairTy;
420 return DenseMapInfo<PairTy>::getHashValue(PairTy(V.getIdentifier(),
421 V.getSelector()));
Ted Kremenek553cf182008-06-25 21:21:56 +0000422 }
Mike Stump1eb44332009-09-09 15:08:12 +0000423
Ted Kremenek553cf182008-06-25 21:21:56 +0000424 static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
Benjamin Kramer28b23072012-05-27 13:28:44 +0000425 return LHS.getIdentifier() == RHS.getIdentifier() &&
426 LHS.getSelector() == RHS.getSelector();
Ted Kremenek553cf182008-06-25 21:21:56 +0000427 }
Mike Stump1eb44332009-09-09 15:08:12 +0000428
Ted Kremenek553cf182008-06-25 21:21:56 +0000429};
Chris Lattner06159e82009-12-15 07:26:51 +0000430template <>
431struct isPodLike<ObjCSummaryKey> { static const bool value = true; };
Ted Kremenek4f22a782008-06-23 23:30:29 +0000432} // end llvm namespace
Mike Stump1eb44332009-09-09 15:08:12 +0000433
Ted Kremenek4f22a782008-06-23 23:30:29 +0000434namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000435class ObjCSummaryCache {
Ted Kremenek93edbc52011-10-05 23:54:29 +0000436 typedef llvm::DenseMap<ObjCSummaryKey, const RetainSummary *> MapTy;
Ted Kremenek553cf182008-06-25 21:21:56 +0000437 MapTy M;
438public:
439 ObjCSummaryCache() {}
Mike Stump1eb44332009-09-09 15:08:12 +0000440
Ted Kremenek93edbc52011-10-05 23:54:29 +0000441 const RetainSummary * find(const ObjCInterfaceDecl *D, Selector S) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000442 // Do a lookup with the (D,S) pair. If we find a match return
443 // the iterator.
444 ObjCSummaryKey K(D, S);
445 MapTy::iterator I = M.find(K);
Mike Stump1eb44332009-09-09 15:08:12 +0000446
Jordan Rose4531b7d2012-07-02 19:27:43 +0000447 if (I != M.end())
Ted Kremenek614cc542009-07-21 23:27:57 +0000448 return I->second;
Jordan Rose4531b7d2012-07-02 19:27:43 +0000449 if (!D)
450 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +0000451
Ted Kremenek553cf182008-06-25 21:21:56 +0000452 // Walk the super chain. If we find a hit with a parent, we'll end
453 // up returning that summary. We actually allow that key (null,S), as
454 // we cache summaries for the null ObjCInterfaceDecl* to allow us to
455 // generate initial summaries without having to worry about NSObject
456 // being declared.
457 // FIXME: We may change this at some point.
Ted Kremenek9c378f72011-08-12 23:37:29 +0000458 for (ObjCInterfaceDecl *C=D->getSuperClass() ;; C=C->getSuperClass()) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000459 if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
460 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000461
Ted Kremenek553cf182008-06-25 21:21:56 +0000462 if (!C)
Ted Kremenek614cc542009-07-21 23:27:57 +0000463 return NULL;
Ted Kremenek553cf182008-06-25 21:21:56 +0000464 }
Mike Stump1eb44332009-09-09 15:08:12 +0000465
466 // Cache the summary with original key to make the next lookup faster
Ted Kremenek553cf182008-06-25 21:21:56 +0000467 // and return the iterator.
Ted Kremenek93edbc52011-10-05 23:54:29 +0000468 const RetainSummary *Summ = I->second;
Ted Kremenek614cc542009-07-21 23:27:57 +0000469 M[K] = Summ;
470 return Summ;
Ted Kremenek553cf182008-06-25 21:21:56 +0000471 }
Mike Stump1eb44332009-09-09 15:08:12 +0000472
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000473 const RetainSummary *find(IdentifierInfo* II, Selector S) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000474 // FIXME: Class method lookup. Right now we dont' have a good way
475 // of going between IdentifierInfo* and the class hierarchy.
Ted Kremenek614cc542009-07-21 23:27:57 +0000476 MapTy::iterator I = M.find(ObjCSummaryKey(II, S));
Mike Stump1eb44332009-09-09 15:08:12 +0000477
Ted Kremenek614cc542009-07-21 23:27:57 +0000478 if (I == M.end())
479 I = M.find(ObjCSummaryKey(S));
Mike Stump1eb44332009-09-09 15:08:12 +0000480
Ted Kremenek614cc542009-07-21 23:27:57 +0000481 return I == M.end() ? NULL : I->second;
Ted Kremenek553cf182008-06-25 21:21:56 +0000482 }
Mike Stump1eb44332009-09-09 15:08:12 +0000483
Ted Kremenek93edbc52011-10-05 23:54:29 +0000484 const RetainSummary *& operator[](ObjCSummaryKey K) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000485 return M[K];
486 }
Mike Stump1eb44332009-09-09 15:08:12 +0000487
Ted Kremenek93edbc52011-10-05 23:54:29 +0000488 const RetainSummary *& operator[](Selector S) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000489 return M[ ObjCSummaryKey(S) ];
490 }
Mike Stump1eb44332009-09-09 15:08:12 +0000491};
Ted Kremenek553cf182008-06-25 21:21:56 +0000492} // end anonymous namespace
493
494//===----------------------------------------------------------------------===//
495// Data structures for managing collections of summaries.
496//===----------------------------------------------------------------------===//
497
498namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000499class RetainSummaryManager {
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000500
501 //==-----------------------------------------------------------------==//
502 // Typedefs.
503 //==-----------------------------------------------------------------==//
Mike Stump1eb44332009-09-09 15:08:12 +0000504
Ted Kremenek93edbc52011-10-05 23:54:29 +0000505 typedef llvm::DenseMap<const FunctionDecl*, const RetainSummary *>
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000506 FuncSummariesTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000507
Ted Kremenek4f22a782008-06-23 23:30:29 +0000508 typedef ObjCSummaryCache ObjCMethodSummariesTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000509
Jordy Roseef945882012-03-18 01:26:10 +0000510 typedef llvm::FoldingSetNodeWrapper<RetainSummary> CachedSummaryNode;
511
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000512 //==-----------------------------------------------------------------==//
513 // Data.
514 //==-----------------------------------------------------------------==//
Mike Stump1eb44332009-09-09 15:08:12 +0000515
Ted Kremenek553cf182008-06-25 21:21:56 +0000516 /// Ctx - The ASTContext object for the analyzed ASTs.
Ted Kremenek9c378f72011-08-12 23:37:29 +0000517 ASTContext &Ctx;
Ted Kremenek179064e2008-07-01 17:21:27 +0000518
Ted Kremenek553cf182008-06-25 21:21:56 +0000519 /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
Ted Kremenek377e2302008-04-29 05:33:51 +0000520 const bool GCEnabled;
Mike Stump1eb44332009-09-09 15:08:12 +0000521
John McCallf85e1932011-06-15 23:02:42 +0000522 /// Records whether or not the analyzed code runs in ARC mode.
523 const bool ARCEnabled;
524
Ted Kremenek553cf182008-06-25 21:21:56 +0000525 /// FuncSummaries - A map from FunctionDecls to summaries.
Mike Stump1eb44332009-09-09 15:08:12 +0000526 FuncSummariesTy FuncSummaries;
527
Ted Kremenek553cf182008-06-25 21:21:56 +0000528 /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
529 /// to summaries.
Ted Kremenek1f180c32008-06-23 22:21:20 +0000530 ObjCMethodSummariesTy ObjCClassMethodSummaries;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000531
Ted Kremenek553cf182008-06-25 21:21:56 +0000532 /// ObjCMethodSummaries - A map from selectors to summaries.
Ted Kremenek1f180c32008-06-23 22:21:20 +0000533 ObjCMethodSummariesTy ObjCMethodSummaries;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000534
Ted Kremenek553cf182008-06-25 21:21:56 +0000535 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
536 /// and all other data used by the checker.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000537 llvm::BumpPtrAllocator BPAlloc;
Mike Stump1eb44332009-09-09 15:08:12 +0000538
Ted Kremenekb77449c2009-05-03 05:20:50 +0000539 /// AF - A factory for ArgEffects objects.
Mike Stump1eb44332009-09-09 15:08:12 +0000540 ArgEffects::Factory AF;
541
Ted Kremenek553cf182008-06-25 21:21:56 +0000542 /// ScratchArgs - A holding buffer for construct ArgEffects.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000543 ArgEffects ScratchArgs;
Mike Stump1eb44332009-09-09 15:08:12 +0000544
Ted Kremenekec315332009-05-07 23:40:42 +0000545 /// ObjCAllocRetE - Default return effect for methods returning Objective-C
546 /// objects.
547 RetEffect ObjCAllocRetE;
Ted Kremenek547d4952009-06-05 23:18:01 +0000548
Mike Stump1eb44332009-09-09 15:08:12 +0000549 /// ObjCInitRetE - Default return effect for init methods returning
Ted Kremenekac02f202009-08-20 05:13:36 +0000550 /// Objective-C objects.
Ted Kremenek547d4952009-06-05 23:18:01 +0000551 RetEffect ObjCInitRetE;
Mike Stump1eb44332009-09-09 15:08:12 +0000552
Jordy Roseef945882012-03-18 01:26:10 +0000553 /// SimpleSummaries - Used for uniquing summaries that don't have special
554 /// effects.
555 llvm::FoldingSet<CachedSummaryNode> SimpleSummaries;
Mike Stump1eb44332009-09-09 15:08:12 +0000556
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000557 //==-----------------------------------------------------------------==//
558 // Methods.
559 //==-----------------------------------------------------------------==//
Mike Stump1eb44332009-09-09 15:08:12 +0000560
Ted Kremenek553cf182008-06-25 21:21:56 +0000561 /// getArgEffects - Returns a persistent ArgEffects object based on the
562 /// data in ScratchArgs.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000563 ArgEffects getArgEffects();
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000564
Mike Stump1eb44332009-09-09 15:08:12 +0000565 enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
Ted Kremenek93edbc52011-10-05 23:54:29 +0000566
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000567 const RetainSummary *getUnarySummary(const FunctionType* FT,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000568 UnaryFuncKind func);
Mike Stump1eb44332009-09-09 15:08:12 +0000569
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000570 const RetainSummary *getCFSummaryCreateRule(const FunctionDecl *FD);
571 const RetainSummary *getCFSummaryGetRule(const FunctionDecl *FD);
572 const RetainSummary *getCFCreateGetRuleSummary(const FunctionDecl *FD);
Mike Stump1eb44332009-09-09 15:08:12 +0000573
Jordy Roseef945882012-03-18 01:26:10 +0000574 const RetainSummary *getPersistentSummary(const RetainSummary &OldSumm);
Ted Kremenek706522f2008-10-29 04:07:07 +0000575
Jordy Roseef945882012-03-18 01:26:10 +0000576 const RetainSummary *getPersistentSummary(RetEffect RetEff,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000577 ArgEffect ReceiverEff = DoNothing,
578 ArgEffect DefaultEff = MayEscape) {
Jordy Roseef945882012-03-18 01:26:10 +0000579 RetainSummary Summ(getArgEffects(), RetEff, DefaultEff, ReceiverEff);
580 return getPersistentSummary(Summ);
581 }
582
Ted Kremenekc91fdf62012-05-08 00:12:09 +0000583 const RetainSummary *getDoNothingSummary() {
584 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
585 }
586
Jordy Roseef945882012-03-18 01:26:10 +0000587 const RetainSummary *getDefaultSummary() {
588 return getPersistentSummary(RetEffect::MakeNoRet(),
589 DoNothing, MayEscape);
Ted Kremenek9c32d082008-05-06 00:30:21 +0000590 }
Mike Stump1eb44332009-09-09 15:08:12 +0000591
Ted Kremenek93edbc52011-10-05 23:54:29 +0000592 const RetainSummary *getPersistentStopSummary() {
Jordy Roseef945882012-03-18 01:26:10 +0000593 return getPersistentSummary(RetEffect::MakeNoRet(),
594 StopTracking, StopTracking);
Mike Stump1eb44332009-09-09 15:08:12 +0000595 }
Ted Kremenekb3095252008-05-06 04:20:12 +0000596
Ted Kremenek1f180c32008-06-23 22:21:20 +0000597 void InitializeClassMethodSummaries();
598 void InitializeMethodSummaries();
Ted Kremenek896cd9d2008-10-23 01:56:15 +0000599private:
Ted Kremenek93edbc52011-10-05 23:54:29 +0000600 void addNSObjectClsMethSummary(Selector S, const RetainSummary *Summ) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000601 ObjCClassMethodSummaries[S] = Summ;
602 }
Mike Stump1eb44332009-09-09 15:08:12 +0000603
Ted Kremenek93edbc52011-10-05 23:54:29 +0000604 void addNSObjectMethSummary(Selector S, const RetainSummary *Summ) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000605 ObjCMethodSummaries[S] = Summ;
606 }
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +0000607
Ted Kremeneka9797122012-02-18 21:37:48 +0000608 void addClassMethSummary(const char* Cls, const char* name,
609 const RetainSummary *Summ, bool isNullary = true) {
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +0000610 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
Ted Kremeneka9797122012-02-18 21:37:48 +0000611 Selector S = isNullary ? GetNullarySelector(name, Ctx)
612 : GetUnarySelector(name, Ctx);
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +0000613 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
614 }
Mike Stump1eb44332009-09-09 15:08:12 +0000615
Ted Kremenek6c4becb2009-02-25 02:54:57 +0000616 void addInstMethSummary(const char* Cls, const char* nullaryName,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000617 const RetainSummary *Summ) {
Ted Kremenek6c4becb2009-02-25 02:54:57 +0000618 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
619 Selector S = GetNullarySelector(nullaryName, Ctx);
620 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
621 }
Mike Stump1eb44332009-09-09 15:08:12 +0000622
Ted Kremenekde4d5332009-04-24 17:50:11 +0000623 Selector generateSelector(va_list argp) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000624 SmallVector<IdentifierInfo*, 10> II;
Ted Kremenekde4d5332009-04-24 17:50:11 +0000625
Ted Kremenek9e476de2008-08-12 18:30:56 +0000626 while (const char* s = va_arg(argp, const char*))
627 II.push_back(&Ctx.Idents.get(s));
Ted Kremenekde4d5332009-04-24 17:50:11 +0000628
Mike Stump1eb44332009-09-09 15:08:12 +0000629 return Ctx.Selectors.getSelector(II.size(), &II[0]);
Ted Kremenekde4d5332009-04-24 17:50:11 +0000630 }
Mike Stump1eb44332009-09-09 15:08:12 +0000631
Ted Kremenekde4d5332009-04-24 17:50:11 +0000632 void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy& Summaries,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000633 const RetainSummary * Summ, va_list argp) {
Ted Kremenekde4d5332009-04-24 17:50:11 +0000634 Selector S = generateSelector(argp);
635 Summaries[ObjCSummaryKey(ClsII, S)] = Summ;
Ted Kremenek70a733e2008-07-18 17:24:20 +0000636 }
Mike Stump1eb44332009-09-09 15:08:12 +0000637
Ted Kremenek93edbc52011-10-05 23:54:29 +0000638 void addInstMethSummary(const char* Cls, const RetainSummary * Summ, ...) {
Ted Kremenekaf9dc272008-08-12 18:48:50 +0000639 va_list argp;
640 va_start(argp, Summ);
Ted Kremenekde4d5332009-04-24 17:50:11 +0000641 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Mike Stump1eb44332009-09-09 15:08:12 +0000642 va_end(argp);
Ted Kremenekaf9dc272008-08-12 18:48:50 +0000643 }
Mike Stump1eb44332009-09-09 15:08:12 +0000644
Ted Kremenek93edbc52011-10-05 23:54:29 +0000645 void addClsMethSummary(const char* Cls, const RetainSummary * Summ, ...) {
Ted Kremenekde4d5332009-04-24 17:50:11 +0000646 va_list argp;
647 va_start(argp, Summ);
648 addMethodSummary(&Ctx.Idents.get(Cls),ObjCClassMethodSummaries, Summ, argp);
649 va_end(argp);
650 }
Mike Stump1eb44332009-09-09 15:08:12 +0000651
Ted Kremenek93edbc52011-10-05 23:54:29 +0000652 void addClsMethSummary(IdentifierInfo *II, const RetainSummary * Summ, ...) {
Ted Kremenekde4d5332009-04-24 17:50:11 +0000653 va_list argp;
654 va_start(argp, Summ);
655 addMethodSummary(II, ObjCClassMethodSummaries, Summ, argp);
656 va_end(argp);
657 }
658
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000659public:
Mike Stump1eb44332009-09-09 15:08:12 +0000660
Ted Kremenek9c378f72011-08-12 23:37:29 +0000661 RetainSummaryManager(ASTContext &ctx, bool gcenabled, bool usesARC)
Ted Kremenek179064e2008-07-01 17:21:27 +0000662 : Ctx(ctx),
John McCallf85e1932011-06-15 23:02:42 +0000663 GCEnabled(gcenabled),
664 ARCEnabled(usesARC),
665 AF(BPAlloc), ScratchArgs(AF.getEmptyMap()),
666 ObjCAllocRetE(gcenabled
667 ? RetEffect::MakeGCNotOwned()
668 : (usesARC ? RetEffect::MakeARCNotOwned()
669 : RetEffect::MakeOwned(RetEffect::ObjC, true))),
670 ObjCInitRetE(gcenabled
671 ? RetEffect::MakeGCNotOwned()
672 : (usesARC ? RetEffect::MakeARCNotOwned()
Jordy Roseef945882012-03-18 01:26:10 +0000673 : RetEffect::MakeOwnedWhenTrackedReceiver())) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000674 InitializeClassMethodSummaries();
675 InitializeMethodSummaries();
676 }
Mike Stump1eb44332009-09-09 15:08:12 +0000677
Jordan Rose4531b7d2012-07-02 19:27:43 +0000678 const RetainSummary *getSummary(const CallEvent &Call,
679 ProgramStateRef State = 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000680
Jordan Rose4531b7d2012-07-02 19:27:43 +0000681 const RetainSummary *getFunctionSummary(const FunctionDecl *FD);
682
683 const RetainSummary *getMethodSummary(Selector S, const ObjCInterfaceDecl *ID,
Jordy Rosef3aae582012-03-17 21:13:07 +0000684 const ObjCMethodDecl *MD,
685 QualType RetTy,
686 ObjCMethodSummariesTy &CachedSummaries);
687
Jordan Rosecde8cdb2012-07-02 19:27:56 +0000688 const RetainSummary *getInstanceMethodSummary(const ObjCMethodCall &M,
Jordan Rose4531b7d2012-07-02 19:27:43 +0000689 ProgramStateRef State);
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000690
Jordan Rosecde8cdb2012-07-02 19:27:56 +0000691 const RetainSummary *getClassMethodSummary(const ObjCMethodCall &M) {
Jordan Rose4531b7d2012-07-02 19:27:43 +0000692 assert(!M.isInstanceMessage());
693 const ObjCInterfaceDecl *Class = M.getReceiverInterface();
Mike Stump1eb44332009-09-09 15:08:12 +0000694
Jordan Rose4531b7d2012-07-02 19:27:43 +0000695 return getMethodSummary(M.getSelector(), Class, M.getDecl(),
696 M.getResultType(), ObjCClassMethodSummaries);
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +0000697 }
Ted Kremenek552333c2009-04-29 17:17:48 +0000698
699 /// getMethodSummary - This version of getMethodSummary is used to query
700 /// the summary for the current method being analyzed.
Ted Kremenek93edbc52011-10-05 23:54:29 +0000701 const RetainSummary *getMethodSummary(const ObjCMethodDecl *MD) {
Ted Kremeneka8833552009-04-29 23:03:22 +0000702 const ObjCInterfaceDecl *ID = MD->getClassInterface();
Ted Kremenek70a65762009-04-30 05:41:14 +0000703 Selector S = MD->getSelector();
Ted Kremenek552333c2009-04-29 17:17:48 +0000704 QualType ResultTy = MD->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +0000705
Jordy Rosef3aae582012-03-17 21:13:07 +0000706 ObjCMethodSummariesTy *CachedSummaries;
Ted Kremenek552333c2009-04-29 17:17:48 +0000707 if (MD->isInstanceMethod())
Jordy Rosef3aae582012-03-17 21:13:07 +0000708 CachedSummaries = &ObjCMethodSummaries;
Ted Kremenek552333c2009-04-29 17:17:48 +0000709 else
Jordy Rosef3aae582012-03-17 21:13:07 +0000710 CachedSummaries = &ObjCClassMethodSummaries;
711
Jordan Rose4531b7d2012-07-02 19:27:43 +0000712 return getMethodSummary(S, ID, MD, ResultTy, *CachedSummaries);
Ted Kremenek552333c2009-04-29 17:17:48 +0000713 }
Mike Stump1eb44332009-09-09 15:08:12 +0000714
Jordy Rosef3aae582012-03-17 21:13:07 +0000715 const RetainSummary *getStandardMethodSummary(const ObjCMethodDecl *MD,
Jordan Rose4531b7d2012-07-02 19:27:43 +0000716 Selector S, QualType RetTy);
Ted Kremeneka8833552009-04-29 23:03:22 +0000717
Jordan Rose44405b72013-04-04 22:31:48 +0000718 /// Determine if there is a special return effect for this function or method.
719 Optional<RetEffect> getRetEffectFromAnnotations(QualType RetTy,
720 const Decl *D);
721
Ted Kremenek93edbc52011-10-05 23:54:29 +0000722 void updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenek4dd8fb42009-05-09 02:58:13 +0000723 const ObjCMethodDecl *MD);
724
Ted Kremenek93edbc52011-10-05 23:54:29 +0000725 void updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenek4dd8fb42009-05-09 02:58:13 +0000726 const FunctionDecl *FD);
727
Jordan Rose4531b7d2012-07-02 19:27:43 +0000728 void updateSummaryForCall(const RetainSummary *&Summ,
729 const CallEvent &Call);
730
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000731 bool isGCEnabled() const { return GCEnabled; }
Mike Stump1eb44332009-09-09 15:08:12 +0000732
John McCallf85e1932011-06-15 23:02:42 +0000733 bool isARCEnabled() const { return ARCEnabled; }
734
735 bool isARCorGCEnabled() const { return GCEnabled || ARCEnabled; }
Jordan Rose4531b7d2012-07-02 19:27:43 +0000736
737 RetEffect getObjAllocRetEffect() const { return ObjCAllocRetE; }
738
739 friend class RetainSummaryTemplate;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000740};
Mike Stump1eb44332009-09-09 15:08:12 +0000741
Jordy Rose0fe62f82011-08-24 09:02:37 +0000742// Used to avoid allocating long-term (BPAlloc'd) memory for default retain
743// summaries. If a function or method looks like it has a default summary, but
744// it has annotations, the annotations are added to the stack-based template
745// and then copied into managed memory.
746class RetainSummaryTemplate {
747 RetainSummaryManager &Manager;
Ted Kremenek93edbc52011-10-05 23:54:29 +0000748 const RetainSummary *&RealSummary;
Jordy Rose0fe62f82011-08-24 09:02:37 +0000749 RetainSummary ScratchSummary;
750 bool Accessed;
751public:
Jordan Rose4531b7d2012-07-02 19:27:43 +0000752 RetainSummaryTemplate(const RetainSummary *&real, RetainSummaryManager &mgr)
753 : Manager(mgr), RealSummary(real), ScratchSummary(*real), Accessed(false) {}
Jordy Rose0fe62f82011-08-24 09:02:37 +0000754
755 ~RetainSummaryTemplate() {
Ted Kremenek93edbc52011-10-05 23:54:29 +0000756 if (Accessed)
Jordy Roseef945882012-03-18 01:26:10 +0000757 RealSummary = Manager.getPersistentSummary(ScratchSummary);
Jordy Rose0fe62f82011-08-24 09:02:37 +0000758 }
759
760 RetainSummary &operator*() {
761 Accessed = true;
Ted Kremenek93edbc52011-10-05 23:54:29 +0000762 return ScratchSummary;
Jordy Rose0fe62f82011-08-24 09:02:37 +0000763 }
764
765 RetainSummary *operator->() {
766 Accessed = true;
Ted Kremenek93edbc52011-10-05 23:54:29 +0000767 return &ScratchSummary;
Jordy Rose0fe62f82011-08-24 09:02:37 +0000768 }
769};
770
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000771} // end anonymous namespace
772
773//===----------------------------------------------------------------------===//
774// Implementation of checker data structures.
775//===----------------------------------------------------------------------===//
776
Ted Kremenekb77449c2009-05-03 05:20:50 +0000777ArgEffects RetainSummaryManager::getArgEffects() {
778 ArgEffects AE = ScratchArgs;
Ted Kremenek3baf6722010-11-24 00:54:37 +0000779 ScratchArgs = AF.getEmptyMap();
Ted Kremenekb77449c2009-05-03 05:20:50 +0000780 return AE;
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000781}
782
Ted Kremenek93edbc52011-10-05 23:54:29 +0000783const RetainSummary *
Jordy Roseef945882012-03-18 01:26:10 +0000784RetainSummaryManager::getPersistentSummary(const RetainSummary &OldSumm) {
785 // Unique "simple" summaries -- those without ArgEffects.
786 if (OldSumm.isSimple()) {
787 llvm::FoldingSetNodeID ID;
788 OldSumm.Profile(ID);
789
790 void *Pos;
791 CachedSummaryNode *N = SimpleSummaries.FindNodeOrInsertPos(ID, Pos);
792
793 if (!N) {
794 N = (CachedSummaryNode *) BPAlloc.Allocate<CachedSummaryNode>();
795 new (N) CachedSummaryNode(OldSumm);
796 SimpleSummaries.InsertNode(N, Pos);
797 }
798
799 return &N->getValue();
800 }
801
Ted Kremenek93edbc52011-10-05 23:54:29 +0000802 RetainSummary *Summ = (RetainSummary *) BPAlloc.Allocate<RetainSummary>();
Jordy Roseef945882012-03-18 01:26:10 +0000803 new (Summ) RetainSummary(OldSumm);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000804 return Summ;
805}
806
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000807//===----------------------------------------------------------------------===//
808// Summary creation for functions (largely uses of Core Foundation).
809//===----------------------------------------------------------------------===//
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000810
Ted Kremenek9c378f72011-08-12 23:37:29 +0000811static bool isRetain(const FunctionDecl *FD, StringRef FName) {
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000812 return FName.endswith("Retain");
Ted Kremenek12619382009-01-12 21:45:02 +0000813}
814
Ted Kremenek9c378f72011-08-12 23:37:29 +0000815static bool isRelease(const FunctionDecl *FD, StringRef FName) {
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000816 return FName.endswith("Release");
Ted Kremenek12619382009-01-12 21:45:02 +0000817}
818
Jordy Rose76c506f2011-08-21 21:58:18 +0000819static bool isMakeCollectable(const FunctionDecl *FD, StringRef FName) {
820 // FIXME: Remove FunctionDecl parameter.
821 // FIXME: Is it really okay if MakeCollectable isn't a suffix?
822 return FName.find("MakeCollectable") != StringRef::npos;
823}
824
Anna Zaks554067f2012-08-29 23:23:43 +0000825static ArgEffect getStopTrackingHardEquivalent(ArgEffect E) {
Jordan Rose4531b7d2012-07-02 19:27:43 +0000826 switch (E) {
827 case DoNothing:
828 case Autorelease:
829 case DecRefBridgedTransfered:
830 case IncRef:
831 case IncRefMsg:
832 case MakeCollectable:
833 case MayEscape:
Jordan Rose4531b7d2012-07-02 19:27:43 +0000834 case StopTracking:
Anna Zaks554067f2012-08-29 23:23:43 +0000835 case StopTrackingHard:
836 return StopTrackingHard;
Jordan Rose4531b7d2012-07-02 19:27:43 +0000837 case DecRef:
Anna Zaks554067f2012-08-29 23:23:43 +0000838 case DecRefAndStopTrackingHard:
839 return DecRefAndStopTrackingHard;
Jordan Rose4531b7d2012-07-02 19:27:43 +0000840 case DecRefMsg:
Anna Zaks554067f2012-08-29 23:23:43 +0000841 case DecRefMsgAndStopTrackingHard:
842 return DecRefMsgAndStopTrackingHard;
Jordan Rose4531b7d2012-07-02 19:27:43 +0000843 case Dealloc:
844 return Dealloc;
845 }
846
847 llvm_unreachable("Unknown ArgEffect kind");
848}
849
850void RetainSummaryManager::updateSummaryForCall(const RetainSummary *&S,
851 const CallEvent &Call) {
852 if (Call.hasNonZeroCallbackArg()) {
Anna Zaks554067f2012-08-29 23:23:43 +0000853 ArgEffect RecEffect =
854 getStopTrackingHardEquivalent(S->getReceiverEffect());
855 ArgEffect DefEffect =
856 getStopTrackingHardEquivalent(S->getDefaultArgEffect());
Jordan Rose4531b7d2012-07-02 19:27:43 +0000857
858 ArgEffects CustomArgEffects = S->getArgEffects();
859 for (ArgEffects::iterator I = CustomArgEffects.begin(),
860 E = CustomArgEffects.end();
861 I != E; ++I) {
Anna Zaks554067f2012-08-29 23:23:43 +0000862 ArgEffect Translated = getStopTrackingHardEquivalent(I->second);
Jordan Rose4531b7d2012-07-02 19:27:43 +0000863 if (Translated != DefEffect)
864 ScratchArgs = AF.add(ScratchArgs, I->first, Translated);
865 }
866
Anna Zaks554067f2012-08-29 23:23:43 +0000867 RetEffect RE = RetEffect::MakeNoRetHard();
Jordan Rose4531b7d2012-07-02 19:27:43 +0000868
869 // Special cases where the callback argument CANNOT free the return value.
870 // This can generally only happen if we know that the callback will only be
871 // called when the return value is already being deallocated.
872 if (const FunctionCall *FC = dyn_cast<FunctionCall>(&Call)) {
Jordan Rose4a25f302012-09-01 17:39:13 +0000873 if (IdentifierInfo *Name = FC->getDecl()->getIdentifier()) {
874 // When the CGBitmapContext is deallocated, the callback here will free
875 // the associated data buffer.
Jordan Rosea89f7192012-08-31 18:19:18 +0000876 if (Name->isStr("CGBitmapContextCreateWithData"))
877 RE = S->getRetEffect();
Jordan Rose4a25f302012-09-01 17:39:13 +0000878 }
Jordan Rose4531b7d2012-07-02 19:27:43 +0000879 }
880
881 S = getPersistentSummary(RE, RecEffect, DefEffect);
882 }
Anna Zaks5a901932012-08-24 00:06:12 +0000883
884 // Special case '[super init];' and '[self init];'
885 //
886 // Even though calling '[super init]' without assigning the result to self
887 // and checking if the parent returns 'nil' is a bad pattern, it is common.
888 // Additionally, our Self Init checker already warns about it. To avoid
889 // overwhelming the user with messages from both checkers, we model the case
890 // of '[super init]' in cases when it is not consumed by another expression
891 // as if the call preserves the value of 'self'; essentially, assuming it can
892 // never fail and return 'nil'.
893 // Note, we don't want to just stop tracking the value since we want the
894 // RetainCount checker to report leaks and use-after-free if SelfInit checker
895 // is turned off.
896 if (const ObjCMethodCall *MC = dyn_cast<ObjCMethodCall>(&Call)) {
897 if (MC->getMethodFamily() == OMF_init && MC->isReceiverSelfOrSuper()) {
898
899 // Check if the message is not consumed, we know it will not be used in
900 // an assignment, ex: "self = [super init]".
901 const Expr *ME = MC->getOriginExpr();
902 const LocationContext *LCtx = MC->getLocationContext();
903 ParentMap &PM = LCtx->getAnalysisDeclContext()->getParentMap();
904 if (!PM.isConsumedExpr(ME)) {
905 RetainSummaryTemplate ModifiableSummaryTemplate(S, *this);
906 ModifiableSummaryTemplate->setReceiverEffect(DoNothing);
907 ModifiableSummaryTemplate->setRetEffect(RetEffect::MakeNoRet());
908 }
909 }
910
911 }
Jordan Rose4531b7d2012-07-02 19:27:43 +0000912}
913
Anna Zaks58822c42012-05-04 22:18:39 +0000914const RetainSummary *
Jordan Rose4531b7d2012-07-02 19:27:43 +0000915RetainSummaryManager::getSummary(const CallEvent &Call,
916 ProgramStateRef State) {
917 const RetainSummary *Summ;
918 switch (Call.getKind()) {
919 case CE_Function:
920 Summ = getFunctionSummary(cast<FunctionCall>(Call).getDecl());
921 break;
922 case CE_CXXMember:
Jordan Rosefdaa3382012-07-03 22:55:57 +0000923 case CE_CXXMemberOperator:
Jordan Rose4531b7d2012-07-02 19:27:43 +0000924 case CE_Block:
925 case CE_CXXConstructor:
Jordan Rose8d276d32012-07-10 22:07:47 +0000926 case CE_CXXDestructor:
Jordan Rose70cbf3c2012-07-02 22:21:47 +0000927 case CE_CXXAllocator:
Jordan Rose4531b7d2012-07-02 19:27:43 +0000928 // FIXME: These calls are currently unsupported.
929 return getPersistentStopSummary();
Jordan Rose8919e682012-07-18 21:59:51 +0000930 case CE_ObjCMessage: {
Jordan Rosecde8cdb2012-07-02 19:27:56 +0000931 const ObjCMethodCall &Msg = cast<ObjCMethodCall>(Call);
Jordan Rose4531b7d2012-07-02 19:27:43 +0000932 if (Msg.isInstanceMessage())
933 Summ = getInstanceMethodSummary(Msg, State);
934 else
935 Summ = getClassMethodSummary(Msg);
936 break;
937 }
938 }
939
940 updateSummaryForCall(Summ, Call);
941
942 assert(Summ && "Unknown call type?");
943 return Summ;
944}
945
946const RetainSummary *
947RetainSummaryManager::getFunctionSummary(const FunctionDecl *FD) {
948 // If we don't know what function we're calling, use our default summary.
949 if (!FD)
950 return getDefaultSummary();
951
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000952 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000953 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000954 if (I != FuncSummaries.end())
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000955 return I->second;
956
Ted Kremeneke401a0c2009-05-04 15:34:07 +0000957 // No summary? Generate one.
Ted Kremenek93edbc52011-10-05 23:54:29 +0000958 const RetainSummary *S = 0;
Jordan Rose15d18e12012-08-06 21:28:02 +0000959 bool AllowAnnotations = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000960
Ted Kremenek37d785b2008-07-15 16:50:12 +0000961 do {
Ted Kremenek12619382009-01-12 21:45:02 +0000962 // We generate "stop" summaries for implicitly defined functions.
963 if (FD->isImplicit()) {
964 S = getPersistentStopSummary();
965 break;
Ted Kremenek37d785b2008-07-15 16:50:12 +0000966 }
Mike Stump1eb44332009-09-09 15:08:12 +0000967
John McCall183700f2009-09-21 23:43:11 +0000968 // [PR 3337] Use 'getAs<FunctionType>' to strip away any typedefs on the
Ted Kremenek99890652009-01-16 18:40:33 +0000969 // function's type.
John McCall183700f2009-09-21 23:43:11 +0000970 const FunctionType* FT = FD->getType()->getAs<FunctionType>();
Ted Kremenek48c6d182009-12-16 06:06:43 +0000971 const IdentifierInfo *II = FD->getIdentifier();
972 if (!II)
973 break;
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000974
975 StringRef FName = II->getName();
Mike Stump1eb44332009-09-09 15:08:12 +0000976
Ted Kremenekbf0a4dd2009-03-05 22:11:14 +0000977 // Strip away preceding '_'. Doing this here will effect all the checks
978 // down below.
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000979 FName = FName.substr(FName.find_first_not_of('_'));
Mike Stump1eb44332009-09-09 15:08:12 +0000980
Ted Kremenek12619382009-01-12 21:45:02 +0000981 // Inspect the result type.
982 QualType RetTy = FT->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +0000983
Ted Kremenek12619382009-01-12 21:45:02 +0000984 // FIXME: This should all be refactored into a chain of "summary lookup"
985 // filters.
Ted Kremenek008636a2009-10-14 00:27:24 +0000986 assert(ScratchArgs.isEmpty());
Ted Kremenek39d88b02009-06-15 20:36:07 +0000987
Ted Kremenekbefc6d22012-04-26 04:32:23 +0000988 if (FName == "pthread_create" || FName == "pthread_setspecific") {
989 // Part of: <rdar://problem/7299394> and <rdar://problem/11282706>.
990 // This will be addressed better with IPA.
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000991 S = getPersistentStopSummary();
992 } else if (FName == "NSMakeCollectable") {
993 // Handle: id NSMakeCollectable(CFTypeRef)
994 S = (RetTy->isObjCIdType())
995 ? getUnarySummary(FT, cfmakecollectable)
996 : getPersistentStopSummary();
Jordan Rose15d18e12012-08-06 21:28:02 +0000997 // The headers on OS X 10.8 use cf_consumed/ns_returns_retained,
998 // but we can fully model NSMakeCollectable ourselves.
999 AllowAnnotations = false;
Ted Kremenek061707a2012-09-06 23:47:02 +00001000 } else if (FName == "CFPlugInInstanceCreate") {
1001 S = getPersistentSummary(RetEffect::MakeNoRet());
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001002 } else if (FName == "IOBSDNameMatching" ||
1003 FName == "IOServiceMatching" ||
1004 FName == "IOServiceNameMatching" ||
Ted Kremenek537dd3a2012-05-01 05:28:27 +00001005 FName == "IORegistryEntrySearchCFProperty" ||
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001006 FName == "IORegistryEntryIDMatching" ||
1007 FName == "IOOpenFirmwarePathMatching") {
1008 // Part of <rdar://problem/6961230>. (IOKit)
1009 // This should be addressed using a API table.
1010 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1011 DoNothing, DoNothing);
1012 } else if (FName == "IOServiceGetMatchingService" ||
1013 FName == "IOServiceGetMatchingServices") {
1014 // FIXES: <rdar://problem/6326900>
1015 // This should be addressed using a API table. This strcmp is also
1016 // a little gross, but there is no need to super optimize here.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001017 ScratchArgs = AF.add(ScratchArgs, 1, DecRef);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001018 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1019 } else if (FName == "IOServiceAddNotification" ||
1020 FName == "IOServiceAddMatchingNotification") {
1021 // Part of <rdar://problem/6961230>. (IOKit)
1022 // This should be addressed using a API table.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001023 ScratchArgs = AF.add(ScratchArgs, 2, DecRef);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001024 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1025 } else if (FName == "CVPixelBufferCreateWithBytes") {
1026 // FIXES: <rdar://problem/7283567>
1027 // Eventually this can be improved by recognizing that the pixel
1028 // buffer passed to CVPixelBufferCreateWithBytes is released via
1029 // a callback and doing full IPA to make sure this is done correctly.
1030 // FIXME: This function has an out parameter that returns an
1031 // allocated object.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001032 ScratchArgs = AF.add(ScratchArgs, 7, StopTracking);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001033 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1034 } else if (FName == "CGBitmapContextCreateWithData") {
1035 // FIXES: <rdar://problem/7358899>
1036 // Eventually this can be improved by recognizing that 'releaseInfo'
1037 // passed to CGBitmapContextCreateWithData is released via
1038 // a callback and doing full IPA to make sure this is done correctly.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001039 ScratchArgs = AF.add(ScratchArgs, 8, StopTracking);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001040 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1041 DoNothing, DoNothing);
1042 } else if (FName == "CVPixelBufferCreateWithPlanarBytes") {
1043 // FIXES: <rdar://problem/7283567>
1044 // Eventually this can be improved by recognizing that the pixel
1045 // buffer passed to CVPixelBufferCreateWithPlanarBytes is released
1046 // via a callback and doing full IPA to make sure this is done
1047 // correctly.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001048 ScratchArgs = AF.add(ScratchArgs, 12, StopTracking);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001049 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Jordan Rose8a729b42013-05-02 01:51:40 +00001050 } else if (FName == "dispatch_set_context" ||
1051 FName == "xpc_connection_set_context") {
Ted Kremenek06911d42012-03-22 06:29:41 +00001052 // <rdar://problem/11059275> - The analyzer currently doesn't have
1053 // a good way to reason about the finalizer function for libdispatch.
1054 // If we pass a context object that is memory managed, stop tracking it.
Jordan Rose8a729b42013-05-02 01:51:40 +00001055 // <rdar://problem/13783514> - Same problem, but for XPC.
Ted Kremenek06911d42012-03-22 06:29:41 +00001056 // FIXME: this hack should possibly go away once we can handle
Jordan Rose8a729b42013-05-02 01:51:40 +00001057 // libdispatch and XPC finalizers.
Ted Kremenek06911d42012-03-22 06:29:41 +00001058 ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
1059 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenekc91fdf62012-05-08 00:12:09 +00001060 } else if (FName.startswith("NSLog")) {
1061 S = getDoNothingSummary();
Anna Zaks62a5c342012-03-30 05:48:16 +00001062 } else if (FName.startswith("NS") &&
1063 (FName.find("Insert") != StringRef::npos)) {
1064 // Whitelist NSXXInsertXX, for example NSMapInsertIfAbsent, since they can
1065 // be deallocated by NSMapRemove. (radar://11152419)
1066 ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
1067 ScratchArgs = AF.add(ScratchArgs, 2, StopTracking);
1068 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenekb04cb592009-06-11 18:17:24 +00001069 }
Mike Stump1eb44332009-09-09 15:08:12 +00001070
Ted Kremenekb04cb592009-06-11 18:17:24 +00001071 // Did we get a summary?
1072 if (S)
1073 break;
Ted Kremenek61991902009-03-17 22:43:44 +00001074
Jordan Rose5aff3f12013-03-04 23:21:32 +00001075 if (RetTy->isPointerType()) {
Ted Kremenek12619382009-01-12 21:45:02 +00001076 // For CoreFoundation ('CF') types.
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001077 if (cocoa::isRefType(RetTy, "CF", FName)) {
Ted Kremenek12619382009-01-12 21:45:02 +00001078 if (isRetain(FD, FName))
1079 S = getUnarySummary(FT, cfretain);
Jordy Rose76c506f2011-08-21 21:58:18 +00001080 else if (isMakeCollectable(FD, FName))
Ted Kremenek12619382009-01-12 21:45:02 +00001081 S = getUnarySummary(FT, cfmakecollectable);
Mike Stump1eb44332009-09-09 15:08:12 +00001082 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 CoreGraphics ('CG') types.
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001089 if (cocoa::isRefType(RetTy, "CG", FName)) {
Ted Kremenek12619382009-01-12 21:45:02 +00001090 if (isRetain(FD, FName))
1091 S = getUnarySummary(FT, cfretain);
1092 else
John McCall7df2ff42011-10-01 00:48:56 +00001093 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek12619382009-01-12 21:45:02 +00001094
1095 break;
1096 }
1097
1098 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001099 if (cocoa::isRefType(RetTy, "DADisk") ||
1100 cocoa::isRefType(RetTy, "DADissenter") ||
1101 cocoa::isRefType(RetTy, "DASessionRef")) {
John McCall7df2ff42011-10-01 00:48:56 +00001102 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek12619382009-01-12 21:45:02 +00001103 break;
1104 }
Mike Stump1eb44332009-09-09 15:08:12 +00001105
Jordan Rose5aff3f12013-03-04 23:21:32 +00001106 if (FD->getAttr<CFAuditedTransferAttr>()) {
1107 S = getCFCreateGetRuleSummary(FD);
1108 break;
1109 }
1110
Ted Kremenek12619382009-01-12 21:45:02 +00001111 break;
1112 }
1113
1114 // Check for release functions, the only kind of functions that we care
1115 // about that don't return a pointer type.
1116 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
Ted Kremeneke7d03122010-02-08 16:45:01 +00001117 // Test for 'CGCF'.
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001118 FName = FName.substr(FName.startswith("CGCF") ? 4 : 2);
Ted Kremeneke7d03122010-02-08 16:45:01 +00001119
Ted Kremenekbf0a4dd2009-03-05 22:11:14 +00001120 if (isRelease(FD, FName))
Ted Kremenek12619382009-01-12 21:45:02 +00001121 S = getUnarySummary(FT, cfrelease);
1122 else {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001123 assert (ScratchArgs.isEmpty());
Ted Kremenek68189282009-01-29 22:45:13 +00001124 // Remaining CoreFoundation and CoreGraphics functions.
1125 // We use to assume that they all strictly followed the ownership idiom
1126 // and that ownership cannot be transferred. While this is technically
1127 // correct, many methods allow a tracked object to escape. For example:
1128 //
Mike Stump1eb44332009-09-09 15:08:12 +00001129 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
Ted Kremenek68189282009-01-29 22:45:13 +00001130 // CFDictionaryAddValue(y, key, x);
Mike Stump1eb44332009-09-09 15:08:12 +00001131 // CFRelease(x);
Ted Kremenek68189282009-01-29 22:45:13 +00001132 // ... it is okay to use 'x' since 'y' has a reference to it
1133 //
1134 // We handle this and similar cases with the follow heuristic. If the
Ted Kremenekc4843812009-08-20 00:57:22 +00001135 // function name contains "InsertValue", "SetValue", "AddValue",
1136 // "AppendValue", or "SetAttribute", then we assume that arguments may
1137 // "escape." This means that something else holds on to the object,
1138 // allowing it be used even after its local retain count drops to 0.
Benjamin Kramere45c1492010-01-11 19:46:28 +00001139 ArgEffect E = (StrInStrNoCase(FName, "InsertValue") != StringRef::npos||
1140 StrInStrNoCase(FName, "AddValue") != StringRef::npos ||
1141 StrInStrNoCase(FName, "SetValue") != StringRef::npos ||
1142 StrInStrNoCase(FName, "AppendValue") != StringRef::npos||
Benjamin Kramerc027e542010-01-11 20:15:06 +00001143 StrInStrNoCase(FName, "SetAttribute") != StringRef::npos)
Ted Kremenek68189282009-01-29 22:45:13 +00001144 ? MayEscape : DoNothing;
Mike Stump1eb44332009-09-09 15:08:12 +00001145
Ted Kremenek68189282009-01-29 22:45:13 +00001146 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek12619382009-01-12 21:45:02 +00001147 }
1148 }
Ted Kremenek37d785b2008-07-15 16:50:12 +00001149 }
1150 while (0);
Mike Stump1eb44332009-09-09 15:08:12 +00001151
Jordan Rose4531b7d2012-07-02 19:27:43 +00001152 // If we got all the way here without any luck, use a default summary.
1153 if (!S)
1154 S = getDefaultSummary();
1155
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001156 // Annotations override defaults.
Jordan Rose15d18e12012-08-06 21:28:02 +00001157 if (AllowAnnotations)
1158 updateSummaryFromAnnotations(S, FD);
Mike Stump1eb44332009-09-09 15:08:12 +00001159
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001160 FuncSummaries[FD] = S;
Mike Stump1eb44332009-09-09 15:08:12 +00001161 return S;
Ted Kremenek2fff37e2008-03-06 00:08:09 +00001162}
1163
Ted Kremenek93edbc52011-10-05 23:54:29 +00001164const RetainSummary *
John McCall7df2ff42011-10-01 00:48:56 +00001165RetainSummaryManager::getCFCreateGetRuleSummary(const FunctionDecl *FD) {
1166 if (coreFoundation::followsCreateRule(FD))
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001167 return getCFSummaryCreateRule(FD);
Mike Stump1eb44332009-09-09 15:08:12 +00001168
Ted Kremenekd368d712011-05-25 06:19:45 +00001169 return getCFSummaryGetRule(FD);
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001170}
1171
Ted Kremenek93edbc52011-10-05 23:54:29 +00001172const RetainSummary *
Ted Kremenek6ad315a2009-02-23 16:51:39 +00001173RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1174 UnaryFuncKind func) {
1175
Ted Kremenek12619382009-01-12 21:45:02 +00001176 // Sanity check that this is *really* a unary function. This can
1177 // happen if people do weird things.
Douglas Gregor72564e72009-02-26 23:50:07 +00001178 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
Ted Kremenek12619382009-01-12 21:45:02 +00001179 if (!FTP || FTP->getNumArgs() != 1)
1180 return getPersistentStopSummary();
Mike Stump1eb44332009-09-09 15:08:12 +00001181
Ted Kremenekb77449c2009-05-03 05:20:50 +00001182 assert (ScratchArgs.isEmpty());
Mike Stump1eb44332009-09-09 15:08:12 +00001183
Jordy Rose76c506f2011-08-21 21:58:18 +00001184 ArgEffect Effect;
Ted Kremenek377e2302008-04-29 05:33:51 +00001185 switch (func) {
Jordy Rose76c506f2011-08-21 21:58:18 +00001186 case cfretain: Effect = IncRef; break;
1187 case cfrelease: Effect = DecRef; break;
1188 case cfmakecollectable: Effect = MakeCollectable; break;
Ted Kremenek940b1d82008-04-10 23:44:06 +00001189 }
Jordy Rose76c506f2011-08-21 21:58:18 +00001190
1191 ScratchArgs = AF.add(ScratchArgs, 0, Effect);
1192 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001193}
1194
Ted Kremenek93edbc52011-10-05 23:54:29 +00001195const RetainSummary *
Ted Kremenek9c378f72011-08-12 23:37:29 +00001196RetainSummaryManager::getCFSummaryCreateRule(const FunctionDecl *FD) {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001197 assert (ScratchArgs.isEmpty());
Mike Stump1eb44332009-09-09 15:08:12 +00001198
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001199 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001200}
1201
Ted Kremenek93edbc52011-10-05 23:54:29 +00001202const RetainSummary *
Ted Kremenek9c378f72011-08-12 23:37:29 +00001203RetainSummaryManager::getCFSummaryGetRule(const FunctionDecl *FD) {
Mike Stump1eb44332009-09-09 15:08:12 +00001204 assert (ScratchArgs.isEmpty());
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001205 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1206 DoNothing, DoNothing);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001207}
1208
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001209//===----------------------------------------------------------------------===//
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001210// Summary creation for Selectors.
1211//===----------------------------------------------------------------------===//
1212
Jordan Rose44405b72013-04-04 22:31:48 +00001213Optional<RetEffect>
1214RetainSummaryManager::getRetEffectFromAnnotations(QualType RetTy,
1215 const Decl *D) {
1216 if (cocoa::isCocoaObjectRef(RetTy)) {
1217 if (D->getAttr<NSReturnsRetainedAttr>())
1218 return ObjCAllocRetE;
1219
1220 if (D->getAttr<NSReturnsNotRetainedAttr>() ||
1221 D->getAttr<NSReturnsAutoreleasedAttr>())
1222 return RetEffect::MakeNotOwned(RetEffect::ObjC);
1223
1224 } else if (!RetTy->isPointerType()) {
1225 return None;
1226 }
1227
1228 if (D->getAttr<CFReturnsRetainedAttr>())
1229 return RetEffect::MakeOwned(RetEffect::CF, true);
1230
1231 if (D->getAttr<CFReturnsNotRetainedAttr>())
1232 return RetEffect::MakeNotOwned(RetEffect::CF);
1233
1234 return None;
1235}
1236
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001237void
Ted Kremenek93edbc52011-10-05 23:54:29 +00001238RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001239 const FunctionDecl *FD) {
1240 if (!FD)
1241 return;
1242
Jordan Rose4531b7d2012-07-02 19:27:43 +00001243 assert(Summ && "Must have a summary to add annotations to.");
1244 RetainSummaryTemplate Template(Summ, *this);
Jordy Rose4df54fe2011-08-23 04:27:15 +00001245
Ted Kremenek11fe1752011-01-27 18:43:03 +00001246 // Effects on the parameters.
1247 unsigned parm_idx = 0;
1248 for (FunctionDecl::param_const_iterator pi = FD->param_begin(),
John McCall98b8f162011-04-06 09:02:12 +00001249 pe = FD->param_end(); pi != pe; ++pi, ++parm_idx) {
Ted Kremenek11fe1752011-01-27 18:43:03 +00001250 const ParmVarDecl *pd = *pi;
Jordan Rose44405b72013-04-04 22:31:48 +00001251 if (pd->getAttr<NSConsumedAttr>())
1252 Template->addArg(AF, parm_idx, DecRefMsg);
1253 else if (pd->getAttr<CFConsumedAttr>())
Jordy Rose0fe62f82011-08-24 09:02:37 +00001254 Template->addArg(AF, parm_idx, DecRef);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001255 }
1256
Ted Kremenekb04cb592009-06-11 18:17:24 +00001257 QualType RetTy = FD->getResultType();
Jordan Rose44405b72013-04-04 22:31:48 +00001258 if (Optional<RetEffect> RetE = getRetEffectFromAnnotations(RetTy, FD))
1259 Template->setRetEffect(*RetE);
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001260}
1261
1262void
Ted Kremenek93edbc52011-10-05 23:54:29 +00001263RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
1264 const ObjCMethodDecl *MD) {
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001265 if (!MD)
1266 return;
1267
Jordan Rose4531b7d2012-07-02 19:27:43 +00001268 assert(Summ && "Must have a valid summary to add annotations to");
1269 RetainSummaryTemplate Template(Summ, *this);
Mike Stump1eb44332009-09-09 15:08:12 +00001270
Ted Kremenek12b94342011-01-27 06:54:14 +00001271 // Effects on the receiver.
Jordan Rose44405b72013-04-04 22:31:48 +00001272 if (MD->getAttr<NSConsumesSelfAttr>())
1273 Template->setReceiverEffect(DecRefMsg);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001274
1275 // Effects on the parameters.
1276 unsigned parm_idx = 0;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00001277 for (ObjCMethodDecl::param_const_iterator
1278 pi=MD->param_begin(), pe=MD->param_end();
Ted Kremenek11fe1752011-01-27 18:43:03 +00001279 pi != pe; ++pi, ++parm_idx) {
1280 const ParmVarDecl *pd = *pi;
Jordan Rose44405b72013-04-04 22:31:48 +00001281 if (pd->getAttr<NSConsumedAttr>())
1282 Template->addArg(AF, parm_idx, DecRefMsg);
1283 else if (pd->getAttr<CFConsumedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001284 Template->addArg(AF, parm_idx, DecRef);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001285 }
Ted Kremenek12b94342011-01-27 06:54:14 +00001286 }
1287
Jordan Rose44405b72013-04-04 22:31:48 +00001288 QualType RetTy = MD->getResultType();
1289 if (Optional<RetEffect> RetE = getRetEffectFromAnnotations(RetTy, MD))
1290 Template->setRetEffect(*RetE);
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001291}
1292
Ted Kremenek93edbc52011-10-05 23:54:29 +00001293const RetainSummary *
Jordy Rosef3aae582012-03-17 21:13:07 +00001294RetainSummaryManager::getStandardMethodSummary(const ObjCMethodDecl *MD,
1295 Selector S, QualType RetTy) {
Jordy Rosee921b1a2012-03-17 19:53:04 +00001296 // Any special effects?
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001297 ArgEffect ReceiverEff = DoNothing;
Jordy Rosee921b1a2012-03-17 19:53:04 +00001298 RetEffect ResultEff = RetEffect::MakeNoRet();
1299
1300 // Check the method family, and apply any default annotations.
1301 switch (MD ? MD->getMethodFamily() : S.getMethodFamily()) {
1302 case OMF_None:
1303 case OMF_performSelector:
1304 // Assume all Objective-C methods follow Cocoa Memory Management rules.
1305 // FIXME: Does the non-threaded performSelector family really belong here?
1306 // The selector could be, say, @selector(copy).
1307 if (cocoa::isCocoaObjectRef(RetTy))
1308 ResultEff = RetEffect::MakeNotOwned(RetEffect::ObjC);
1309 else if (coreFoundation::isCFObjectRef(RetTy)) {
1310 // ObjCMethodDecl currently doesn't consider CF objects as valid return
1311 // values for alloc, new, copy, or mutableCopy, so we have to
1312 // double-check with the selector. This is ugly, but there aren't that
1313 // many Objective-C methods that return CF objects, right?
1314 if (MD) {
1315 switch (S.getMethodFamily()) {
1316 case OMF_alloc:
1317 case OMF_new:
1318 case OMF_copy:
1319 case OMF_mutableCopy:
1320 ResultEff = RetEffect::MakeOwned(RetEffect::CF, true);
1321 break;
1322 default:
1323 ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1324 break;
1325 }
1326 } else {
1327 ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1328 }
1329 }
1330 break;
1331 case OMF_init:
1332 ResultEff = ObjCInitRetE;
1333 ReceiverEff = DecRefMsg;
1334 break;
1335 case OMF_alloc:
1336 case OMF_new:
1337 case OMF_copy:
1338 case OMF_mutableCopy:
1339 if (cocoa::isCocoaObjectRef(RetTy))
1340 ResultEff = ObjCAllocRetE;
1341 else if (coreFoundation::isCFObjectRef(RetTy))
1342 ResultEff = RetEffect::MakeOwned(RetEffect::CF, true);
1343 break;
1344 case OMF_autorelease:
1345 ReceiverEff = Autorelease;
1346 break;
1347 case OMF_retain:
1348 ReceiverEff = IncRefMsg;
1349 break;
1350 case OMF_release:
1351 ReceiverEff = DecRefMsg;
1352 break;
1353 case OMF_dealloc:
1354 ReceiverEff = Dealloc;
1355 break;
1356 case OMF_self:
1357 // -self is handled specially by the ExprEngine to propagate the receiver.
1358 break;
1359 case OMF_retainCount:
1360 case OMF_finalize:
1361 // These methods don't return objects.
1362 break;
1363 }
Mike Stump1eb44332009-09-09 15:08:12 +00001364
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001365 // If one of the arguments in the selector has the keyword 'delegate' we
1366 // should stop tracking the reference count for the receiver. This is
1367 // because the reference count is quite possibly handled by a delegate
1368 // method.
1369 if (S.isKeywordSelector()) {
Jordan Rose50571a92012-06-15 18:19:52 +00001370 for (unsigned i = 0, e = S.getNumArgs(); i != e; ++i) {
1371 StringRef Slot = S.getNameForSlot(i);
1372 if (Slot.substr(Slot.size() - 8).equals_lower("delegate")) {
1373 if (ResultEff == ObjCInitRetE)
Anna Zaks554067f2012-08-29 23:23:43 +00001374 ResultEff = RetEffect::MakeNoRetHard();
Jordan Rose50571a92012-06-15 18:19:52 +00001375 else
Anna Zaks554067f2012-08-29 23:23:43 +00001376 ReceiverEff = StopTrackingHard;
Jordan Rose50571a92012-06-15 18:19:52 +00001377 }
1378 }
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001379 }
Mike Stump1eb44332009-09-09 15:08:12 +00001380
Jordy Rosee921b1a2012-03-17 19:53:04 +00001381 if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing &&
1382 ResultEff.getKind() == RetEffect::NoRet)
Ted Kremenek93edbc52011-10-05 23:54:29 +00001383 return getDefaultSummary();
Mike Stump1eb44332009-09-09 15:08:12 +00001384
Jordy Rosee921b1a2012-03-17 19:53:04 +00001385 return getPersistentSummary(ResultEff, ReceiverEff, MayEscape);
Ted Kremenek250b1fa2009-04-23 23:08:22 +00001386}
1387
Ted Kremenek93edbc52011-10-05 23:54:29 +00001388const RetainSummary *
Jordan Rosecde8cdb2012-07-02 19:27:56 +00001389RetainSummaryManager::getInstanceMethodSummary(const ObjCMethodCall &Msg,
Jordan Rose4531b7d2012-07-02 19:27:43 +00001390 ProgramStateRef State) {
1391 const ObjCInterfaceDecl *ReceiverClass = 0;
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001392
Jordan Rose4531b7d2012-07-02 19:27:43 +00001393 // We do better tracking of the type of the object than the core ExprEngine.
1394 // See if we have its type in our private state.
1395 // FIXME: Eventually replace the use of state->get<RefBindings> with
1396 // a generic API for reasoning about the Objective-C types of symbolic
1397 // objects.
1398 SVal ReceiverV = Msg.getReceiverSVal();
1399 if (SymbolRef Sym = ReceiverV.getAsLocSymbol())
Anna Zaks8d6b43c2012-08-14 00:36:15 +00001400 if (const RefVal *T = getRefBinding(State, Sym))
Douglas Gregor04badcf2010-04-21 00:45:42 +00001401 if (const ObjCObjectPointerType *PT =
Jordan Rose4531b7d2012-07-02 19:27:43 +00001402 T->getType()->getAs<ObjCObjectPointerType>())
1403 ReceiverClass = PT->getInterfaceDecl();
1404
1405 // If we don't know what kind of object this is, fall back to its static type.
1406 if (!ReceiverClass)
1407 ReceiverClass = Msg.getReceiverInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00001408
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001409 // FIXME: The receiver could be a reference to a class, meaning that
1410 // we should use the class method.
Jordan Rose4531b7d2012-07-02 19:27:43 +00001411 // id x = [NSObject class];
1412 // [x performSelector:... withObject:... afterDelay:...];
1413 Selector S = Msg.getSelector();
1414 const ObjCMethodDecl *Method = Msg.getDecl();
1415 if (!Method && ReceiverClass)
1416 Method = ReceiverClass->getInstanceMethod(S);
1417
1418 return getMethodSummary(S, ReceiverClass, Method, Msg.getResultType(),
1419 ObjCMethodSummaries);
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001420}
1421
Ted Kremenek93edbc52011-10-05 23:54:29 +00001422const RetainSummary *
Jordan Rose4531b7d2012-07-02 19:27:43 +00001423RetainSummaryManager::getMethodSummary(Selector S, const ObjCInterfaceDecl *ID,
Jordy Rosef3aae582012-03-17 21:13:07 +00001424 const ObjCMethodDecl *MD, QualType RetTy,
1425 ObjCMethodSummariesTy &CachedSummaries) {
Ted Kremenek1bffd742008-05-06 15:44:25 +00001426
Ted Kremenek8711c032009-04-29 05:04:30 +00001427 // Look up a summary in our summary cache.
Jordan Rose4531b7d2012-07-02 19:27:43 +00001428 const RetainSummary *Summ = CachedSummaries.find(ID, S);
Mike Stump1eb44332009-09-09 15:08:12 +00001429
Ted Kremenek614cc542009-07-21 23:27:57 +00001430 if (!Summ) {
Jordy Rosef3aae582012-03-17 21:13:07 +00001431 Summ = getStandardMethodSummary(MD, S, RetTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001432
Ted Kremenek614cc542009-07-21 23:27:57 +00001433 // Annotations override defaults.
Jordy Rose4df54fe2011-08-23 04:27:15 +00001434 updateSummaryFromAnnotations(Summ, MD);
Mike Stump1eb44332009-09-09 15:08:12 +00001435
Ted Kremenek614cc542009-07-21 23:27:57 +00001436 // Memoize the summary.
Jordan Rose4531b7d2012-07-02 19:27:43 +00001437 CachedSummaries[ObjCSummaryKey(ID, S)] = Summ;
Ted Kremenek614cc542009-07-21 23:27:57 +00001438 }
Mike Stump1eb44332009-09-09 15:08:12 +00001439
Ted Kremeneke87450e2009-04-23 19:11:35 +00001440 return Summ;
Ted Kremenekc8395602008-05-06 21:26:51 +00001441}
1442
Mike Stump1eb44332009-09-09 15:08:12 +00001443void RetainSummaryManager::InitializeClassMethodSummaries() {
Ted Kremenekec315332009-05-07 23:40:42 +00001444 assert(ScratchArgs.isEmpty());
Mike Stump1eb44332009-09-09 15:08:12 +00001445 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek6fe2b7a2009-10-15 22:25:12 +00001446 addClassMethSummary("NSAssertionHandler", "currentHandler",
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001447 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Mike Stump1eb44332009-09-09 15:08:12 +00001448
Ted Kremenek6d348932008-10-21 15:53:15 +00001449 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001450 ScratchArgs = AF.add(ScratchArgs, 0, Autorelease);
Ted Kremenek6fe2b7a2009-10-15 22:25:12 +00001451 addClassMethSummary("NSAutoreleasePool", "addObject",
1452 getPersistentSummary(RetEffect::MakeNoRet(),
1453 DoNothing, Autorelease));
Ted Kremenek9c32d082008-05-06 00:30:21 +00001454}
1455
Ted Kremenek1f180c32008-06-23 22:21:20 +00001456void RetainSummaryManager::InitializeMethodSummaries() {
Mike Stump1eb44332009-09-09 15:08:12 +00001457
1458 assert (ScratchArgs.isEmpty());
1459
Ted Kremenekc8395602008-05-06 21:26:51 +00001460 // Create the "init" selector. It just acts as a pass-through for the
1461 // receiver.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001462 const RetainSummary *InitSumm = getPersistentSummary(ObjCInitRetE, DecRefMsg);
Ted Kremenekac02f202009-08-20 05:13:36 +00001463 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
1464
1465 // awakeAfterUsingCoder: behaves basically like an 'init' method. It
1466 // claims the receiver and returns a retained object.
1467 addNSObjectMethSummary(GetUnarySelector("awakeAfterUsingCoder", Ctx),
1468 InitSumm);
Mike Stump1eb44332009-09-09 15:08:12 +00001469
Ted Kremenekc8395602008-05-06 21:26:51 +00001470 // The next methods are allocators.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001471 const RetainSummary *AllocSumm = getPersistentSummary(ObjCAllocRetE);
1472 const RetainSummary *CFAllocSumm =
Ted Kremeneka834fb42009-08-28 19:52:12 +00001473 getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Mike Stump1eb44332009-09-09 15:08:12 +00001474
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001475 // Create the "retain" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001476 RetEffect NoRet = RetEffect::MakeNoRet();
Ted Kremenek93edbc52011-10-05 23:54:29 +00001477 const RetainSummary *Summ = getPersistentSummary(NoRet, IncRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001478 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001479
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001480 // Create the "release" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001481 Summ = getPersistentSummary(NoRet, DecRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001482 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001483
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001484 // Create the -dealloc summary.
Jordy Rose500abad2011-08-21 19:41:36 +00001485 Summ = getPersistentSummary(NoRet, Dealloc);
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001486 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001487
1488 // Create the "autorelease" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001489 Summ = getPersistentSummary(NoRet, Autorelease);
Ted Kremenek553cf182008-06-25 21:21:56 +00001490 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001491
Mike Stump1eb44332009-09-09 15:08:12 +00001492 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremenek89e202d2009-02-23 02:51:29 +00001493 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1494 // self-own themselves. However, they only do this once they are displayed.
1495 // Thus, we need to track an NSWindow's display status.
1496 // This is tracked in <rdar://problem/6062711>.
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +00001497 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001498 const RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenek78a35a32009-05-12 20:06:54 +00001499 StopTracking,
1500 StopTracking);
Mike Stump1eb44332009-09-09 15:08:12 +00001501
Ted Kremenek99d02692009-04-03 19:02:51 +00001502 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1503
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001504 // For NSPanel (which subclasses NSWindow), allocated objects are not
1505 // self-owned.
Ted Kremenek99d02692009-04-03 19:02:51 +00001506 // FIXME: For now we don't track NSPanels. object for the same reason
1507 // as for NSWindow objects.
1508 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
Mike Stump1eb44332009-09-09 15:08:12 +00001509
Jordan Rosee36d81b2013-01-31 22:06:02 +00001510 // Don't track allocated autorelease pools, as it is okay to prematurely
Ted Kremenekba67f6a2009-05-18 23:14:34 +00001511 // exit a method.
1512 addClassMethSummary("NSAutoreleasePool", "alloc", NoTrackYet);
Ted Kremeneka9797122012-02-18 21:37:48 +00001513 addClassMethSummary("NSAutoreleasePool", "allocWithZone", NoTrackYet, false);
Jordan Rosee36d81b2013-01-31 22:06:02 +00001514 addClassMethSummary("NSAutoreleasePool", "new", NoTrackYet);
Ted Kremenek553cf182008-06-25 21:21:56 +00001515
Ted Kremenek767d6492009-05-20 22:39:57 +00001516 // Create summaries QCRenderer/QCView -createSnapShotImageOfType:
1517 addInstMethSummary("QCRenderer", AllocSumm,
1518 "createSnapshotImageOfType", NULL);
1519 addInstMethSummary("QCView", AllocSumm,
1520 "createSnapshotImageOfType", NULL);
1521
Ted Kremenek211a9c62009-06-15 20:58:58 +00001522 // Create summaries for CIContext, 'createCGImage' and
Ted Kremeneka834fb42009-08-28 19:52:12 +00001523 // 'createCGLayerWithSize'. These objects are CF objects, and are not
1524 // automatically garbage collected.
1525 addInstMethSummary("CIContext", CFAllocSumm,
Ted Kremenek767d6492009-05-20 22:39:57 +00001526 "createCGImage", "fromRect", NULL);
Ted Kremeneka834fb42009-08-28 19:52:12 +00001527 addInstMethSummary("CIContext", CFAllocSumm,
Mike Stump1eb44332009-09-09 15:08:12 +00001528 "createCGImage", "fromRect", "format", "colorSpace", NULL);
Ted Kremeneka834fb42009-08-28 19:52:12 +00001529 addInstMethSummary("CIContext", CFAllocSumm, "createCGLayerWithSize",
Ted Kremenek211a9c62009-06-15 20:58:58 +00001530 "info", NULL);
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001531}
1532
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001533//===----------------------------------------------------------------------===//
Ted Kremenekc887d132009-04-29 18:50:19 +00001534// Error reporting.
1535//===----------------------------------------------------------------------===//
Ted Kremenekc887d132009-04-29 18:50:19 +00001536namespace {
Jordy Roseec9ef852011-08-23 20:55:48 +00001537 typedef llvm::DenseMap<const ExplodedNode *, const RetainSummary *>
1538 SummaryLogTy;
1539
Ted Kremenekc887d132009-04-29 18:50:19 +00001540 //===-------------===//
1541 // Bug Descriptions. //
Mike Stump1eb44332009-09-09 15:08:12 +00001542 //===-------------===//
1543
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001544 class CFRefBug : public BugType {
Ted Kremenekc887d132009-04-29 18:50:19 +00001545 protected:
Jordy Rose35c86952011-08-24 05:47:39 +00001546 CFRefBug(StringRef name)
Ted Kremenek6fd45052012-04-05 20:43:28 +00001547 : BugType(name, categories::MemoryCoreFoundationObjectiveC) {}
Ted Kremenekc887d132009-04-29 18:50:19 +00001548 public:
Mike Stump1eb44332009-09-09 15:08:12 +00001549
Ted Kremenekc887d132009-04-29 18:50:19 +00001550 // FIXME: Eventually remove.
Jordy Rose35c86952011-08-24 05:47:39 +00001551 virtual const char *getDescription() const = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001552
Ted Kremenekc887d132009-04-29 18:50:19 +00001553 virtual bool isLeak() const { return false; }
1554 };
Mike Stump1eb44332009-09-09 15:08:12 +00001555
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001556 class UseAfterRelease : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001557 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001558 UseAfterRelease() : CFRefBug("Use-after-release") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001559
Jordy Rose35c86952011-08-24 05:47:39 +00001560 const char *getDescription() const {
Ted Kremenekc887d132009-04-29 18:50:19 +00001561 return "Reference-counted object is used after it is released";
Mike Stump1eb44332009-09-09 15:08:12 +00001562 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001563 };
Mike Stump1eb44332009-09-09 15:08:12 +00001564
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001565 class BadRelease : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001566 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001567 BadRelease() : CFRefBug("Bad release") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001568
Jordy Rose35c86952011-08-24 05:47:39 +00001569 const char *getDescription() const {
Ted Kremenekbb206fd2009-10-01 17:31:50 +00001570 return "Incorrect decrement of the reference count of an object that is "
1571 "not owned at this point by the caller";
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 DeallocGC : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001576 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001577 DeallocGC()
1578 : CFRefBug("-dealloc called while using garbage collection") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001579
Ted Kremenekc887d132009-04-29 18:50:19 +00001580 const char *getDescription() const {
Ted Kremenek369de562009-05-09 00:10:05 +00001581 return "-dealloc called while using garbage collection";
Ted Kremenekc887d132009-04-29 18:50:19 +00001582 }
1583 };
Mike Stump1eb44332009-09-09 15:08:12 +00001584
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001585 class DeallocNotOwned : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001586 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001587 DeallocNotOwned()
1588 : CFRefBug("-dealloc sent to non-exclusively owned object") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001589
Ted Kremenekc887d132009-04-29 18:50:19 +00001590 const char *getDescription() const {
1591 return "-dealloc sent to object that may be referenced elsewhere";
1592 }
Mike Stump1eb44332009-09-09 15:08:12 +00001593 };
1594
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001595 class OverAutorelease : public CFRefBug {
Ted Kremenek369de562009-05-09 00:10:05 +00001596 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001597 OverAutorelease()
Jordan Rose2545b1d2013-04-23 01:42:25 +00001598 : CFRefBug("Object autoreleased too many times") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001599
Ted Kremenek369de562009-05-09 00:10:05 +00001600 const char *getDescription() const {
Jordan Rose2545b1d2013-04-23 01:42:25 +00001601 return "Object autoreleased too many times";
Ted Kremenek369de562009-05-09 00:10:05 +00001602 }
1603 };
Mike Stump1eb44332009-09-09 15:08:12 +00001604
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001605 class ReturnedNotOwnedForOwned : public CFRefBug {
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001606 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001607 ReturnedNotOwnedForOwned()
1608 : CFRefBug("Method should return an owned object") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001609
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001610 const char *getDescription() const {
Jordy Rose5b5402b2011-07-15 22:17:54 +00001611 return "Object with a +0 retain count returned to caller where a +1 "
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001612 "(owning) retain count is expected";
1613 }
1614 };
Mike Stump1eb44332009-09-09 15:08:12 +00001615
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001616 class Leak : public CFRefBug {
Benjamin Kramerfacde172012-06-06 17:32:50 +00001617 public:
1618 Leak(StringRef name)
1619 : CFRefBug(name) {
Jordy Rosedb92bb62011-08-25 01:14:38 +00001620 // Leaks should not be reported if they are post-dominated by a sink.
1621 setSuppressOnSink(true);
1622 }
Mike Stump1eb44332009-09-09 15:08:12 +00001623
Jordy Rose35c86952011-08-24 05:47:39 +00001624 const char *getDescription() const { return ""; }
Mike Stump1eb44332009-09-09 15:08:12 +00001625
Ted Kremenekc887d132009-04-29 18:50:19 +00001626 bool isLeak() const { return true; }
1627 };
Mike Stump1eb44332009-09-09 15:08:12 +00001628
Ted Kremenekc887d132009-04-29 18:50:19 +00001629 //===---------===//
1630 // Bug Reports. //
1631 //===---------===//
Mike Stump1eb44332009-09-09 15:08:12 +00001632
Jordy Rose01153492012-03-24 02:45:35 +00001633 class CFRefReportVisitor : public BugReporterVisitorImpl<CFRefReportVisitor> {
Anna Zaks23f395e2011-08-20 01:27:22 +00001634 protected:
Anna Zaksdc757b02011-08-19 23:21:56 +00001635 SymbolRef Sym;
Jordy Roseec9ef852011-08-23 20:55:48 +00001636 const SummaryLogTy &SummaryLog;
Jordy Rose35c86952011-08-24 05:47:39 +00001637 bool GCEnabled;
Anna Zaks23f395e2011-08-20 01:27:22 +00001638
Anna Zaksdc757b02011-08-19 23:21:56 +00001639 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001640 CFRefReportVisitor(SymbolRef sym, bool gcEnabled, const SummaryLogTy &log)
1641 : Sym(sym), SummaryLog(log), GCEnabled(gcEnabled) {}
Anna Zaksdc757b02011-08-19 23:21:56 +00001642
Anna Zaks23f395e2011-08-20 01:27:22 +00001643 virtual void Profile(llvm::FoldingSetNodeID &ID) const {
Anna Zaksdc757b02011-08-19 23:21:56 +00001644 static int x = 0;
1645 ID.AddPointer(&x);
1646 ID.AddPointer(Sym);
1647 }
1648
Anna Zaks23f395e2011-08-20 01:27:22 +00001649 virtual PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
1650 const ExplodedNode *PrevN,
1651 BugReporterContext &BRC,
1652 BugReport &BR);
1653
1654 virtual PathDiagnosticPiece *getEndPath(BugReporterContext &BRC,
1655 const ExplodedNode *N,
1656 BugReport &BR);
1657 };
1658
1659 class CFRefLeakReportVisitor : public CFRefReportVisitor {
1660 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001661 CFRefLeakReportVisitor(SymbolRef sym, bool GCEnabled,
Jordy Roseec9ef852011-08-23 20:55:48 +00001662 const SummaryLogTy &log)
Jordy Rose35c86952011-08-24 05:47:39 +00001663 : CFRefReportVisitor(sym, GCEnabled, log) {}
Anna Zaks23f395e2011-08-20 01:27:22 +00001664
1665 PathDiagnosticPiece *getEndPath(BugReporterContext &BRC,
1666 const ExplodedNode *N,
1667 BugReport &BR);
Jordy Rose01153492012-03-24 02:45:35 +00001668
1669 virtual BugReporterVisitor *clone() const {
1670 // The curiously-recurring template pattern only works for one level of
1671 // subclassing. Rather than make a new template base for
1672 // CFRefReportVisitor, we simply override clone() to do the right thing.
1673 // This could be trouble someday if BugReporterVisitorImpl is ever
1674 // used for something else besides a convenient implementation of clone().
1675 return new CFRefLeakReportVisitor(*this);
1676 }
Anna Zaksdc757b02011-08-19 23:21:56 +00001677 };
1678
Anna Zakse172e8b2011-08-17 23:00:25 +00001679 class CFRefReport : public BugReport {
Jordy Rose20589562011-08-24 22:39:09 +00001680 void addGCModeDescription(const LangOptions &LOpts, bool GCEnabled);
Jordy Rose35c86952011-08-24 05:47:39 +00001681
Ted Kremenekc887d132009-04-29 18:50:19 +00001682 public:
Jordy Rose20589562011-08-24 22:39:09 +00001683 CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1684 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1685 bool registerVisitor = true)
Anna Zaksedf4dae2011-08-22 18:54:07 +00001686 : BugReport(D, D.getDescription(), n) {
Anna Zaks23f395e2011-08-20 01:27:22 +00001687 if (registerVisitor)
Jordy Rose20589562011-08-24 22:39:09 +00001688 addVisitor(new CFRefReportVisitor(sym, GCEnabled, Log));
1689 addGCModeDescription(LOpts, GCEnabled);
Anna Zaksdc757b02011-08-19 23:21:56 +00001690 }
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001691
Jordy Rose20589562011-08-24 22:39:09 +00001692 CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1693 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1694 StringRef endText)
Anna Zaksedf4dae2011-08-22 18:54:07 +00001695 : BugReport(D, D.getDescription(), endText, n) {
Jordy Rose20589562011-08-24 22:39:09 +00001696 addVisitor(new CFRefReportVisitor(sym, GCEnabled, Log));
1697 addGCModeDescription(LOpts, GCEnabled);
Anna Zaksdc757b02011-08-19 23:21:56 +00001698 }
Mike Stump1eb44332009-09-09 15:08:12 +00001699
Anna Zakse172e8b2011-08-17 23:00:25 +00001700 virtual std::pair<ranges_iterator, ranges_iterator> getRanges() {
Anna Zaksedf4dae2011-08-22 18:54:07 +00001701 const CFRefBug& BugTy = static_cast<CFRefBug&>(getBugType());
1702 if (!BugTy.isLeak())
Anna Zakse172e8b2011-08-17 23:00:25 +00001703 return BugReport::getRanges();
Ted Kremenekc887d132009-04-29 18:50:19 +00001704 else
Argyrios Kyrtzidis640ccf02010-12-04 01:12:15 +00001705 return std::make_pair(ranges_iterator(), ranges_iterator());
Ted Kremenekc887d132009-04-29 18:50:19 +00001706 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001707 };
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001708
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001709 class CFRefLeakReport : public CFRefReport {
Ted Kremenekc887d132009-04-29 18:50:19 +00001710 const MemRegion* AllocBinding;
1711 public:
Jordy Rose20589562011-08-24 22:39:09 +00001712 CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1713 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
Ted Kremenek08a838d2013-04-16 21:44:22 +00001714 CheckerContext &Ctx,
1715 bool IncludeAllocationLine);
Mike Stump1eb44332009-09-09 15:08:12 +00001716
Anna Zaks590dd8e2011-09-20 21:38:35 +00001717 PathDiagnosticLocation getLocation(const SourceManager &SM) const {
1718 assert(Location.isValid());
1719 return Location;
1720 }
Mike Stump1eb44332009-09-09 15:08:12 +00001721 };
Ted Kremenekc887d132009-04-29 18:50:19 +00001722} // end anonymous namespace
1723
Jordy Rose20589562011-08-24 22:39:09 +00001724void CFRefReport::addGCModeDescription(const LangOptions &LOpts,
1725 bool GCEnabled) {
Jordy Rosef95b19d2011-08-24 20:38:42 +00001726 const char *GCModeDescription = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001727
Douglas Gregore289d812011-09-13 17:21:33 +00001728 switch (LOpts.getGC()) {
Anna Zaks7f2531c2011-08-22 20:31:28 +00001729 case LangOptions::GCOnly:
Jordy Rose20589562011-08-24 22:39:09 +00001730 assert(GCEnabled);
Jordy Rose35c86952011-08-24 05:47:39 +00001731 GCModeDescription = "Code is compiled to only use garbage collection";
1732 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001733
Anna Zaks7f2531c2011-08-22 20:31:28 +00001734 case LangOptions::NonGC:
Jordy Rose20589562011-08-24 22:39:09 +00001735 assert(!GCEnabled);
Jordy Rose35c86952011-08-24 05:47:39 +00001736 GCModeDescription = "Code is compiled to use reference counts";
1737 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001738
Anna Zaks7f2531c2011-08-22 20:31:28 +00001739 case LangOptions::HybridGC:
Jordy Rose20589562011-08-24 22:39:09 +00001740 if (GCEnabled) {
Jordy Rose35c86952011-08-24 05:47:39 +00001741 GCModeDescription = "Code is compiled to use either garbage collection "
1742 "(GC) or reference counts (non-GC). The bug occurs "
1743 "with GC enabled";
1744 break;
1745 } else {
1746 GCModeDescription = "Code is compiled to use either garbage collection "
1747 "(GC) or reference counts (non-GC). The bug occurs "
1748 "in non-GC mode";
1749 break;
Anna Zaks7f2531c2011-08-22 20:31:28 +00001750 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001751 }
Jordy Rose35c86952011-08-24 05:47:39 +00001752
Jordy Rosef95b19d2011-08-24 20:38:42 +00001753 assert(GCModeDescription && "invalid/unknown GC mode");
Jordy Rose35c86952011-08-24 05:47:39 +00001754 addExtraText(GCModeDescription);
Ted Kremenekc887d132009-04-29 18:50:19 +00001755}
1756
Jordy Rose910c4052011-09-02 06:44:22 +00001757// FIXME: This should be a method on SmallVector.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001758static inline bool contains(const SmallVectorImpl<ArgEffect>& V,
Ted Kremenekc887d132009-04-29 18:50:19 +00001759 ArgEffect X) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001760 for (SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
Ted Kremenekc887d132009-04-29 18:50:19 +00001761 I!=E; ++I)
1762 if (*I == X) return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001763
Ted Kremenekc887d132009-04-29 18:50:19 +00001764 return false;
1765}
1766
Jordy Rose70fdbc32012-05-12 05:10:43 +00001767static bool isNumericLiteralExpression(const Expr *E) {
1768 // FIXME: This set of cases was copied from SemaExprObjC.
1769 return isa<IntegerLiteral>(E) ||
1770 isa<CharacterLiteral>(E) ||
1771 isa<FloatingLiteral>(E) ||
1772 isa<ObjCBoolLiteralExpr>(E) ||
1773 isa<CXXBoolLiteralExpr>(E);
1774}
1775
Anna Zaksdc757b02011-08-19 23:21:56 +00001776PathDiagnosticPiece *CFRefReportVisitor::VisitNode(const ExplodedNode *N,
1777 const ExplodedNode *PrevN,
1778 BugReporterContext &BRC,
1779 BugReport &BR) {
Jordan Rose28038f32012-07-10 22:07:42 +00001780 // FIXME: We will eventually need to handle non-statement-based events
1781 // (__attribute__((cleanup))).
David Blaikie7a95de62013-02-21 22:23:56 +00001782 if (!N->getLocation().getAs<StmtPoint>())
Ted Kremenek2033a952009-05-13 07:12:33 +00001783 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001784
Ted Kremenek8966bc12009-05-06 21:39:49 +00001785 // Check if the type state has changed.
Ted Kremenek8bef8232012-01-26 21:29:00 +00001786 ProgramStateRef PrevSt = PrevN->getState();
1787 ProgramStateRef CurrSt = N->getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001788 const LocationContext *LCtx = N->getLocationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00001789
Anna Zaks8d6b43c2012-08-14 00:36:15 +00001790 const RefVal* CurrT = getRefBinding(CurrSt, Sym);
Ted Kremenekc887d132009-04-29 18:50:19 +00001791 if (!CurrT) return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001792
Ted Kremenekb65be702009-06-18 01:23:53 +00001793 const RefVal &CurrV = *CurrT;
Anna Zaks8d6b43c2012-08-14 00:36:15 +00001794 const RefVal *PrevT = getRefBinding(PrevSt, Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00001795
Ted Kremenekc887d132009-04-29 18:50:19 +00001796 // Create a string buffer to constain all the useful things we want
1797 // to tell the user.
1798 std::string sbuf;
1799 llvm::raw_string_ostream os(sbuf);
Mike Stump1eb44332009-09-09 15:08:12 +00001800
Ted Kremenekc887d132009-04-29 18:50:19 +00001801 // This is the allocation site since the previous node had no bindings
1802 // for this symbol.
1803 if (!PrevT) {
David Blaikie7a95de62013-02-21 22:23:56 +00001804 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
Mike Stump1eb44332009-09-09 15:08:12 +00001805
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001806 if (isa<ObjCArrayLiteral>(S)) {
1807 os << "NSArray literal is an object with a +0 retain count";
Mike Stump1eb44332009-09-09 15:08:12 +00001808 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001809 else if (isa<ObjCDictionaryLiteral>(S)) {
1810 os << "NSDictionary literal is an object with a +0 retain count";
Ted Kremenekc887d132009-04-29 18:50:19 +00001811 }
Jordy Rose70fdbc32012-05-12 05:10:43 +00001812 else if (const ObjCBoxedExpr *BL = dyn_cast<ObjCBoxedExpr>(S)) {
1813 if (isNumericLiteralExpression(BL->getSubExpr()))
1814 os << "NSNumber literal is an object with a +0 retain count";
1815 else {
1816 const ObjCInterfaceDecl *BoxClass = 0;
1817 if (const ObjCMethodDecl *Method = BL->getBoxingMethod())
1818 BoxClass = Method->getClassInterface();
1819
1820 // We should always be able to find the boxing class interface,
1821 // but consider this future-proofing.
1822 if (BoxClass)
1823 os << *BoxClass << " b";
1824 else
1825 os << "B";
1826
1827 os << "oxed expression produces an object with a +0 retain count";
1828 }
1829 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001830 else {
1831 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
1832 // Get the name of the callee (if it is available).
1833 SVal X = CurrSt->getSValAsScalarOrLoc(CE->getCallee(), LCtx);
1834 if (const FunctionDecl *FD = X.getAsFunctionDecl())
1835 os << "Call to function '" << *FD << '\'';
1836 else
1837 os << "function call";
Ted Kremenekc887d132009-04-29 18:50:19 +00001838 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001839 else {
Jordan Rose8919e682012-07-18 21:59:51 +00001840 assert(isa<ObjCMessageExpr>(S));
Jordan Rosed563d3f2012-07-30 20:22:09 +00001841 CallEventManager &Mgr = CurrSt->getStateManager().getCallEventManager();
1842 CallEventRef<ObjCMethodCall> Call
1843 = Mgr.getObjCMethodCall(cast<ObjCMessageExpr>(S), CurrSt, LCtx);
1844
1845 switch (Call->getMessageKind()) {
Jordan Rose8919e682012-07-18 21:59:51 +00001846 case OCM_Message:
1847 os << "Method";
1848 break;
1849 case OCM_PropertyAccess:
1850 os << "Property";
1851 break;
1852 case OCM_Subscript:
1853 os << "Subscript";
1854 break;
1855 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001856 }
1857
1858 if (CurrV.getObjKind() == RetEffect::CF) {
1859 os << " returns a Core Foundation object with a ";
1860 }
1861 else {
1862 assert (CurrV.getObjKind() == RetEffect::ObjC);
1863 os << " returns an Objective-C object with a ";
1864 }
1865
1866 if (CurrV.isOwned()) {
1867 os << "+1 retain count";
1868
1869 if (GCEnabled) {
1870 assert(CurrV.getObjKind() == RetEffect::CF);
1871 os << ". "
1872 "Core Foundation objects are not automatically garbage collected.";
1873 }
1874 }
1875 else {
1876 assert (CurrV.isNotOwned());
1877 os << "+0 retain count";
1878 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001879 }
Mike Stump1eb44332009-09-09 15:08:12 +00001880
Anna Zaks220ac8c2011-09-15 01:08:34 +00001881 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
1882 N->getLocationContext());
Ted Kremenekc887d132009-04-29 18:50:19 +00001883 return new PathDiagnosticEventPiece(Pos, os.str());
1884 }
Mike Stump1eb44332009-09-09 15:08:12 +00001885
Ted Kremenekc887d132009-04-29 18:50:19 +00001886 // Gather up the effects that were performed on the object at this
1887 // program point
Chris Lattner5f9e2722011-07-23 10:55:15 +00001888 SmallVector<ArgEffect, 2> AEffects;
Mike Stump1eb44332009-09-09 15:08:12 +00001889
Jordy Roseec9ef852011-08-23 20:55:48 +00001890 const ExplodedNode *OrigNode = BRC.getNodeResolver().getOriginalNode(N);
1891 if (const RetainSummary *Summ = SummaryLog.lookup(OrigNode)) {
Ted Kremenekc887d132009-04-29 18:50:19 +00001892 // We only have summaries attached to nodes after evaluating CallExpr and
1893 // ObjCMessageExprs.
David Blaikie7a95de62013-02-21 22:23:56 +00001894 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
Mike Stump1eb44332009-09-09 15:08:12 +00001895
Ted Kremenek5f85e172009-07-22 22:35:28 +00001896 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
Ted Kremenekc887d132009-04-29 18:50:19 +00001897 // Iterate through the parameter expressions and see if the symbol
1898 // was ever passed as an argument.
1899 unsigned i = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001900
Ted Kremenek5f85e172009-07-22 22:35:28 +00001901 for (CallExpr::const_arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
Ted Kremenekc887d132009-04-29 18:50:19 +00001902 AI!=AE; ++AI, ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00001903
Ted Kremenekc887d132009-04-29 18:50:19 +00001904 // Retrieve the value of the argument. Is it the symbol
1905 // we are interested in?
Ted Kremenek5eca4822012-01-06 22:09:28 +00001906 if (CurrSt->getSValAsScalarOrLoc(*AI, LCtx).getAsLocSymbol() != Sym)
Ted Kremenekc887d132009-04-29 18:50:19 +00001907 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001908
Ted Kremenekc887d132009-04-29 18:50:19 +00001909 // We have an argument. Get the effect!
1910 AEffects.push_back(Summ->getArg(i));
1911 }
1912 }
Mike Stump1eb44332009-09-09 15:08:12 +00001913 else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00001914 if (const Expr *receiver = ME->getInstanceReceiver())
Ted Kremenek5eca4822012-01-06 22:09:28 +00001915 if (CurrSt->getSValAsScalarOrLoc(receiver, LCtx)
1916 .getAsLocSymbol() == Sym) {
Ted Kremenekc887d132009-04-29 18:50:19 +00001917 // The symbol we are tracking is the receiver.
1918 AEffects.push_back(Summ->getReceiverEffect());
1919 }
1920 }
1921 }
Mike Stump1eb44332009-09-09 15:08:12 +00001922
Ted Kremenekc887d132009-04-29 18:50:19 +00001923 do {
1924 // Get the previous type state.
1925 RefVal PrevV = *PrevT;
Mike Stump1eb44332009-09-09 15:08:12 +00001926
Ted Kremenekc887d132009-04-29 18:50:19 +00001927 // Specially handle -dealloc.
Jordy Rose35c86952011-08-24 05:47:39 +00001928 if (!GCEnabled && contains(AEffects, Dealloc)) {
Ted Kremenekc887d132009-04-29 18:50:19 +00001929 // Determine if the object's reference count was pushed to zero.
1930 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
1931 // We may not have transitioned to 'release' if we hit an error.
1932 // This case is handled elsewhere.
1933 if (CurrV.getKind() == RefVal::Released) {
Ted Kremenekf21332e2009-05-08 20:01:42 +00001934 assert(CurrV.getCombinedCounts() == 0);
Ted Kremenekc887d132009-04-29 18:50:19 +00001935 os << "Object released by directly sending the '-dealloc' message";
1936 break;
1937 }
1938 }
Mike Stump1eb44332009-09-09 15:08:12 +00001939
Ted Kremenekc887d132009-04-29 18:50:19 +00001940 // Specially handle CFMakeCollectable and friends.
1941 if (contains(AEffects, MakeCollectable)) {
1942 // Get the name of the function.
David Blaikie7a95de62013-02-21 22:23:56 +00001943 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001944 SVal X =
1945 CurrSt->getSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee(), LCtx);
Ted Kremenek9c378f72011-08-12 23:37:29 +00001946 const FunctionDecl *FD = X.getAsFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001947
Jordy Rose35c86952011-08-24 05:47:39 +00001948 if (GCEnabled) {
Ted Kremenekc887d132009-04-29 18:50:19 +00001949 // Determine if the object's reference count was pushed to zero.
1950 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
Mike Stump1eb44332009-09-09 15:08:12 +00001951
Benjamin Kramerb8989f22011-10-14 18:45:37 +00001952 os << "In GC mode a call to '" << *FD
Ted Kremenekc887d132009-04-29 18:50:19 +00001953 << "' decrements an object's retain count and registers the "
1954 "object with the garbage collector. ";
Mike Stump1eb44332009-09-09 15:08:12 +00001955
Ted Kremenekc887d132009-04-29 18:50:19 +00001956 if (CurrV.getKind() == RefVal::Released) {
1957 assert(CurrV.getCount() == 0);
1958 os << "Since it now has a 0 retain count the object can be "
1959 "automatically collected by the garbage collector.";
1960 }
1961 else
1962 os << "An object must have a 0 retain count to be garbage collected. "
1963 "After this call its retain count is +" << CurrV.getCount()
1964 << '.';
1965 }
Mike Stump1eb44332009-09-09 15:08:12 +00001966 else
Benjamin Kramerb8989f22011-10-14 18:45:37 +00001967 os << "When GC is not enabled a call to '" << *FD
Ted Kremenekc887d132009-04-29 18:50:19 +00001968 << "' has no effect on its argument.";
Mike Stump1eb44332009-09-09 15:08:12 +00001969
Ted Kremenekc887d132009-04-29 18:50:19 +00001970 // Nothing more to say.
1971 break;
1972 }
Mike Stump1eb44332009-09-09 15:08:12 +00001973
1974 // Determine if the typestate has changed.
Ted Kremenekc887d132009-04-29 18:50:19 +00001975 if (!(PrevV == CurrV))
1976 switch (CurrV.getKind()) {
1977 case RefVal::Owned:
1978 case RefVal::NotOwned:
Mike Stump1eb44332009-09-09 15:08:12 +00001979
Ted Kremenekf21332e2009-05-08 20:01:42 +00001980 if (PrevV.getCount() == CurrV.getCount()) {
1981 // Did an autorelease message get sent?
1982 if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
1983 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001984
Zhongxing Xu264e9372009-05-12 10:10:00 +00001985 assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount());
Jordan Rose2545b1d2013-04-23 01:42:25 +00001986 os << "Object autoreleased";
Ted Kremenekf21332e2009-05-08 20:01:42 +00001987 break;
1988 }
Mike Stump1eb44332009-09-09 15:08:12 +00001989
Ted Kremenekc887d132009-04-29 18:50:19 +00001990 if (PrevV.getCount() > CurrV.getCount())
1991 os << "Reference count decremented.";
1992 else
1993 os << "Reference count incremented.";
Mike Stump1eb44332009-09-09 15:08:12 +00001994
Ted Kremenekc887d132009-04-29 18:50:19 +00001995 if (unsigned Count = CurrV.getCount())
1996 os << " The object now has a +" << Count << " retain count.";
Mike Stump1eb44332009-09-09 15:08:12 +00001997
Ted Kremenekc887d132009-04-29 18:50:19 +00001998 if (PrevV.getKind() == RefVal::Released) {
Jordy Rose35c86952011-08-24 05:47:39 +00001999 assert(GCEnabled && CurrV.getCount() > 0);
Jordy Rose74b7b2b2012-03-17 05:49:15 +00002000 os << " The object is not eligible for garbage collection until "
2001 "the retain count reaches 0 again.";
Ted Kremenekc887d132009-04-29 18:50:19 +00002002 }
Mike Stump1eb44332009-09-09 15:08:12 +00002003
Ted Kremenekc887d132009-04-29 18:50:19 +00002004 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002005
Ted Kremenekc887d132009-04-29 18:50:19 +00002006 case RefVal::Released:
2007 os << "Object released.";
2008 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002009
Ted Kremenekc887d132009-04-29 18:50:19 +00002010 case RefVal::ReturnedOwned:
Jordy Rose74b7b2b2012-03-17 05:49:15 +00002011 // Autoreleases can be applied after marking a node ReturnedOwned.
2012 if (CurrV.getAutoreleaseCount())
2013 return NULL;
2014
2015 os << "Object returned to caller as an owning reference (single "
2016 "retain count transferred to caller)";
Ted Kremenekc887d132009-04-29 18:50:19 +00002017 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002018
Ted Kremenekc887d132009-04-29 18:50:19 +00002019 case RefVal::ReturnedNotOwned:
Ted Kremenekf1365462011-05-26 18:45:44 +00002020 os << "Object returned to caller with a +0 retain count";
Ted Kremenekc887d132009-04-29 18:50:19 +00002021 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002022
Ted Kremenekc887d132009-04-29 18:50:19 +00002023 default:
2024 return NULL;
2025 }
Mike Stump1eb44332009-09-09 15:08:12 +00002026
Ted Kremenekc887d132009-04-29 18:50:19 +00002027 // Emit any remaining diagnostics for the argument effects (if any).
Chris Lattner5f9e2722011-07-23 10:55:15 +00002028 for (SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
Ted Kremenekc887d132009-04-29 18:50:19 +00002029 E=AEffects.end(); I != E; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +00002030
Ted Kremenekc887d132009-04-29 18:50:19 +00002031 // A bunch of things have alternate behavior under GC.
Jordy Rose35c86952011-08-24 05:47:39 +00002032 if (GCEnabled)
Ted Kremenekc887d132009-04-29 18:50:19 +00002033 switch (*I) {
2034 default: break;
2035 case Autorelease:
2036 os << "In GC mode an 'autorelease' has no effect.";
2037 continue;
2038 case IncRefMsg:
2039 os << "In GC mode the 'retain' message has no effect.";
2040 continue;
2041 case DecRefMsg:
2042 os << "In GC mode the 'release' message has no effect.";
2043 continue;
2044 }
2045 }
Mike Stump1eb44332009-09-09 15:08:12 +00002046 } while (0);
2047
Ted Kremenekc887d132009-04-29 18:50:19 +00002048 if (os.str().empty())
2049 return 0; // We have nothing to say!
Ted Kremenek2033a952009-05-13 07:12:33 +00002050
David Blaikie7a95de62013-02-21 22:23:56 +00002051 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
Anna Zaks220ac8c2011-09-15 01:08:34 +00002052 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
2053 N->getLocationContext());
Ted Kremenek9c378f72011-08-12 23:37:29 +00002054 PathDiagnosticPiece *P = new PathDiagnosticEventPiece(Pos, os.str());
Mike Stump1eb44332009-09-09 15:08:12 +00002055
Ted Kremenekc887d132009-04-29 18:50:19 +00002056 // Add the range by scanning the children of the statement for any bindings
2057 // to Sym.
Mike Stump1eb44332009-09-09 15:08:12 +00002058 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
Ted Kremenek5f85e172009-07-22 22:35:28 +00002059 I!=E; ++I)
Ted Kremenek9c378f72011-08-12 23:37:29 +00002060 if (const Expr *Exp = dyn_cast_or_null<Expr>(*I))
Ted Kremenek5eca4822012-01-06 22:09:28 +00002061 if (CurrSt->getSValAsScalarOrLoc(Exp, LCtx).getAsLocSymbol() == Sym) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002062 P->addRange(Exp->getSourceRange());
2063 break;
2064 }
Mike Stump1eb44332009-09-09 15:08:12 +00002065
Ted Kremenekc887d132009-04-29 18:50:19 +00002066 return P;
2067}
2068
Anna Zakse7e01682012-02-28 22:39:22 +00002069// Find the first node in the current function context that referred to the
2070// tracked symbol and the memory location that value was stored to. Note, the
2071// value is only reported if the allocation occurred in the same function as
Anna Zaks7a87e522013-04-10 21:42:06 +00002072// the leak. The function can also return a location context, which should be
2073// treated as interesting.
2074struct AllocationInfo {
2075 const ExplodedNode* N;
Anna Zaksee9043b2013-04-10 22:56:30 +00002076 const MemRegion *R;
Anna Zaks7a87e522013-04-10 21:42:06 +00002077 const LocationContext *InterestingMethodContext;
Anna Zaksee9043b2013-04-10 22:56:30 +00002078 AllocationInfo(const ExplodedNode *InN,
2079 const MemRegion *InR,
Anna Zaks7a87e522013-04-10 21:42:06 +00002080 const LocationContext *InInterestingMethodContext) :
2081 N(InN), R(InR), InterestingMethodContext(InInterestingMethodContext) {}
2082};
2083
2084static AllocationInfo
Ted Kremenek18c66fd2011-08-15 22:09:50 +00002085GetAllocationSite(ProgramStateManager& StateMgr, const ExplodedNode *N,
Ted Kremenekc887d132009-04-29 18:50:19 +00002086 SymbolRef Sym) {
Anna Zaks7a87e522013-04-10 21:42:06 +00002087 const ExplodedNode *AllocationNode = N;
2088 const ExplodedNode *AllocationNodeInCurrentContext = N;
Mike Stump1eb44332009-09-09 15:08:12 +00002089 const MemRegion* FirstBinding = 0;
Anna Zakse7e01682012-02-28 22:39:22 +00002090 const LocationContext *LeakContext = N->getLocationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002091
Anna Zaks7a87e522013-04-10 21:42:06 +00002092 // The location context of the init method called on the leaked object, if
2093 // available.
2094 const LocationContext *InitMethodContext = 0;
2095
Ted Kremenekc887d132009-04-29 18:50:19 +00002096 while (N) {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002097 ProgramStateRef St = N->getState();
Anna Zaks7a87e522013-04-10 21:42:06 +00002098 const LocationContext *NContext = N->getLocationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002099
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002100 if (!getRefBinding(St, Sym))
Ted Kremenekc887d132009-04-29 18:50:19 +00002101 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002102
Anna Zaks27b867e2012-03-21 19:45:01 +00002103 StoreManager::FindUniqueBinding FB(Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002104 StateMgr.iterBindings(St, FB);
Anna Zaks7a87e522013-04-10 21:42:06 +00002105
Anna Zaks27d99dd2013-04-10 21:42:02 +00002106 if (FB) {
2107 const MemRegion *R = FB.getRegion();
Anna Zaks8cf91f72013-04-10 22:56:33 +00002108 const VarRegion *VR = R->getBaseRegion()->getAs<VarRegion>();
Anna Zaks27d99dd2013-04-10 21:42:02 +00002109 // Do not show local variables belonging to a function other than
2110 // where the error is reported.
2111 if (!VR || VR->getStackFrame() == LeakContext->getCurrentStackFrame())
Anna Zaks7a87e522013-04-10 21:42:06 +00002112 FirstBinding = R;
Anna Zaks27d99dd2013-04-10 21:42:02 +00002113 }
Mike Stump1eb44332009-09-09 15:08:12 +00002114
Anna Zaks7a87e522013-04-10 21:42:06 +00002115 // AllocationNode is the last node in which the symbol was tracked.
2116 AllocationNode = N;
2117
2118 // AllocationNodeInCurrentContext, is the last node in the current context
2119 // in which the symbol was tracked.
2120 if (NContext == LeakContext)
2121 AllocationNodeInCurrentContext = N;
2122
Anna Zaksee9043b2013-04-10 22:56:30 +00002123 // Find the last init that was called on the given symbol and store the
2124 // init method's location context.
2125 if (!InitMethodContext)
2126 if (Optional<CallEnter> CEP = N->getLocation().getAs<CallEnter>()) {
2127 const Stmt *CE = CEP->getCallExpr();
Anna Zaks3d8f4622013-04-25 00:41:32 +00002128 if (const ObjCMessageExpr *ME = dyn_cast_or_null<ObjCMessageExpr>(CE)) {
Anna Zaksee9043b2013-04-10 22:56:30 +00002129 const Stmt *RecExpr = ME->getInstanceReceiver();
2130 if (RecExpr) {
2131 SVal RecV = St->getSVal(RecExpr, NContext);
2132 if (ME->getMethodFamily() == OMF_init && RecV.getAsSymbol() == Sym)
2133 InitMethodContext = CEP->getCalleeContext();
2134 }
2135 }
Anna Zaks7a87e522013-04-10 21:42:06 +00002136 }
Anna Zakse7e01682012-02-28 22:39:22 +00002137
Mike Stump1eb44332009-09-09 15:08:12 +00002138 N = N->pred_empty() ? NULL : *(N->pred_begin());
Ted Kremenekc887d132009-04-29 18:50:19 +00002139 }
Mike Stump1eb44332009-09-09 15:08:12 +00002140
Anna Zaks7a87e522013-04-10 21:42:06 +00002141 // If we are reporting a leak of the object that was allocated with alloc,
Anna Zaksee9043b2013-04-10 22:56:30 +00002142 // mark its init method as interesting.
Anna Zaks7a87e522013-04-10 21:42:06 +00002143 const LocationContext *InterestingMethodContext = 0;
2144 if (InitMethodContext) {
2145 const ProgramPoint AllocPP = AllocationNode->getLocation();
2146 if (Optional<StmtPoint> SP = AllocPP.getAs<StmtPoint>())
2147 if (const ObjCMessageExpr *ME = SP->getStmtAs<ObjCMessageExpr>())
2148 if (ME->getMethodFamily() == OMF_alloc)
2149 InterestingMethodContext = InitMethodContext;
2150 }
2151
Anna Zakse7e01682012-02-28 22:39:22 +00002152 // If allocation happened in a function different from the leak node context,
2153 // do not report the binding.
Ted Kremenek5a8fc882012-10-12 22:56:40 +00002154 assert(N && "Could not find allocation node");
Anna Zakse7e01682012-02-28 22:39:22 +00002155 if (N->getLocationContext() != LeakContext) {
2156 FirstBinding = 0;
2157 }
2158
Anna Zaks7a87e522013-04-10 21:42:06 +00002159 return AllocationInfo(AllocationNodeInCurrentContext,
2160 FirstBinding,
2161 InterestingMethodContext);
Ted Kremenekc887d132009-04-29 18:50:19 +00002162}
2163
2164PathDiagnosticPiece*
Anna Zaks23f395e2011-08-20 01:27:22 +00002165CFRefReportVisitor::getEndPath(BugReporterContext &BRC,
2166 const ExplodedNode *EndN,
2167 BugReport &BR) {
Ted Kremenek76aadc32012-03-09 01:13:14 +00002168 BR.markInteresting(Sym);
Anna Zaks23f395e2011-08-20 01:27:22 +00002169 return BugReporterVisitor::getDefaultEndPath(BRC, EndN, BR);
Ted Kremenekc887d132009-04-29 18:50:19 +00002170}
2171
2172PathDiagnosticPiece*
Anna Zaks23f395e2011-08-20 01:27:22 +00002173CFRefLeakReportVisitor::getEndPath(BugReporterContext &BRC,
2174 const ExplodedNode *EndN,
2175 BugReport &BR) {
Mike Stump1eb44332009-09-09 15:08:12 +00002176
Ted Kremenek8966bc12009-05-06 21:39:49 +00002177 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenekc887d132009-04-29 18:50:19 +00002178 // assigned to different variables, etc.
Ted Kremenek76aadc32012-03-09 01:13:14 +00002179 BR.markInteresting(Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002180
Ted Kremenekc887d132009-04-29 18:50:19 +00002181 // We are reporting a leak. Walk up the graph to get to the first node where
2182 // the symbol appeared, and also get the first VarDecl that tracked object
2183 // is stored to.
Anna Zaks7a87e522013-04-10 21:42:06 +00002184 AllocationInfo AllocI =
Ted Kremenekf04dced2009-05-08 23:32:51 +00002185 GetAllocationSite(BRC.getStateManager(), EndN, Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002186
Anna Zaks7a87e522013-04-10 21:42:06 +00002187 const MemRegion* FirstBinding = AllocI.R;
2188 BR.markInteresting(AllocI.InterestingMethodContext);
2189
Anna Zaks4fdf97b2011-09-15 18:56:07 +00002190 SourceManager& SM = BRC.getSourceManager();
Mike Stump1eb44332009-09-09 15:08:12 +00002191
Ted Kremenekc887d132009-04-29 18:50:19 +00002192 // Compute an actual location for the leak. Sometimes a leak doesn't
2193 // occur at an actual statement (e.g., transition between blocks; end
2194 // of function) so we need to walk the graph and compute a real location.
Ted Kremenek9c378f72011-08-12 23:37:29 +00002195 const ExplodedNode *LeakN = EndN;
Anna Zaks4fdf97b2011-09-15 18:56:07 +00002196 PathDiagnosticLocation L = PathDiagnosticLocation::createEndOfPath(LeakN, SM);
Mike Stump1eb44332009-09-09 15:08:12 +00002197
Ted Kremenekc887d132009-04-29 18:50:19 +00002198 std::string sbuf;
2199 llvm::raw_string_ostream os(sbuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002200
Ted Kremenekf1365462011-05-26 18:45:44 +00002201 os << "Object leaked: ";
Mike Stump1eb44332009-09-09 15:08:12 +00002202
Ted Kremenekf1365462011-05-26 18:45:44 +00002203 if (FirstBinding) {
2204 os << "object allocated and stored into '"
2205 << FirstBinding->getString() << '\'';
2206 }
2207 else
2208 os << "allocated object";
Mike Stump1eb44332009-09-09 15:08:12 +00002209
Ted Kremenekc887d132009-04-29 18:50:19 +00002210 // Get the retain count.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002211 const RefVal* RV = getRefBinding(EndN->getState(), Sym);
Ted Kremenek5a8fc882012-10-12 22:56:40 +00002212 assert(RV);
Mike Stump1eb44332009-09-09 15:08:12 +00002213
Ted Kremenekc887d132009-04-29 18:50:19 +00002214 if (RV->getKind() == RefVal::ErrorLeakReturned) {
2215 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
Jordy Rose5b5402b2011-07-15 22:17:54 +00002216 // objects. Only "copy", "alloc", "retain" and "new" transfer ownership
Ted Kremenekc887d132009-04-29 18:50:19 +00002217 // to the caller for NS objects.
Ted Kremenekd368d712011-05-25 06:19:45 +00002218 const Decl *D = &EndN->getCodeDecl();
Ted Kremenekec9f36e2012-09-06 23:03:07 +00002219
2220 os << (isa<ObjCMethodDecl>(D) ? " is returned from a method "
2221 : " is returned from a function ");
2222
2223 if (D->getAttr<CFReturnsNotRetainedAttr>())
2224 os << "that is annotated as CF_RETURNS_NOT_RETAINED";
2225 else if (D->getAttr<NSReturnsNotRetainedAttr>())
2226 os << "that is annotated as NS_RETURNS_NOT_RETAINED";
Ted Kremenekd368d712011-05-25 06:19:45 +00002227 else {
Ted Kremenekec9f36e2012-09-06 23:03:07 +00002228 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2229 os << "whose name ('" << MD->getSelector().getAsString()
2230 << "') does not start with 'copy', 'mutableCopy', 'alloc' or 'new'."
2231 " This violates the naming convention rules"
2232 " given in the Memory Management Guide for Cocoa";
2233 }
2234 else {
2235 const FunctionDecl *FD = cast<FunctionDecl>(D);
2236 os << "whose name ('" << *FD
2237 << "') does not contain 'Copy' or 'Create'. This violates the naming"
2238 " convention rules given in the Memory Management Guide for Core"
2239 " Foundation";
2240 }
2241 }
Ted Kremenekc887d132009-04-29 18:50:19 +00002242 }
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002243 else if (RV->getKind() == RefVal::ErrorGCLeakReturned) {
David Blaikiee1300142013-02-21 22:37:44 +00002244 const ObjCMethodDecl &MD = cast<ObjCMethodDecl>(EndN->getCodeDecl());
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002245 os << " and returned from method '" << MD.getSelector().getAsString()
Ted Kremenek82f2be52009-05-10 16:52:15 +00002246 << "' is potentially leaked when using garbage collection. Callers "
2247 "of this method do not expect a returned object with a +1 retain "
2248 "count since they expect the object to be managed by the garbage "
2249 "collector";
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002250 }
Ted Kremenekc887d132009-04-29 18:50:19 +00002251 else
Ted Kremenekabf517c2010-10-15 22:50:23 +00002252 os << " is not referenced later in this execution path and has a retain "
Ted Kremenekf1365462011-05-26 18:45:44 +00002253 "count of +" << RV->getCount();
Mike Stump1eb44332009-09-09 15:08:12 +00002254
Ted Kremenekc887d132009-04-29 18:50:19 +00002255 return new PathDiagnosticEventPiece(L, os.str());
2256}
2257
Jordy Rose20589562011-08-24 22:39:09 +00002258CFRefLeakReport::CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts,
2259 bool GCEnabled, const SummaryLogTy &Log,
2260 ExplodedNode *n, SymbolRef sym,
Ted Kremenek08a838d2013-04-16 21:44:22 +00002261 CheckerContext &Ctx,
2262 bool IncludeAllocationLine)
2263 : CFRefReport(D, LOpts, GCEnabled, Log, n, sym, false) {
Mike Stump1eb44332009-09-09 15:08:12 +00002264
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00002265 // Most bug reports are cached at the location where they occurred.
Ted Kremenekc887d132009-04-29 18:50:19 +00002266 // With leaks, we want to unique them by the location where they were
2267 // allocated, and only report a single path. To do this, we need to find
2268 // the allocation site of a piece of tracked memory, which we do via a
2269 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2270 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2271 // that all ancestor nodes that represent the allocation site have the
2272 // same SourceLocation.
Ted Kremenek9c378f72011-08-12 23:37:29 +00002273 const ExplodedNode *AllocNode = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002274
Anna Zaks6a93bd52011-10-25 19:57:11 +00002275 const SourceManager& SMgr = Ctx.getSourceManager();
Anna Zaks590dd8e2011-09-20 21:38:35 +00002276
Anna Zaks7a87e522013-04-10 21:42:06 +00002277 AllocationInfo AllocI =
Anna Zaks6a93bd52011-10-25 19:57:11 +00002278 GetAllocationSite(Ctx.getStateManager(), getErrorNode(), sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002279
Anna Zaks7a87e522013-04-10 21:42:06 +00002280 AllocNode = AllocI.N;
2281 AllocBinding = AllocI.R;
2282 markInteresting(AllocI.InterestingMethodContext);
2283
Ted Kremenekc887d132009-04-29 18:50:19 +00002284 // Get the SourceLocation for the allocation site.
Jordan Rose852aa0d2012-07-10 22:07:52 +00002285 // FIXME: This will crash the analyzer if an allocation comes from an
2286 // implicit call. (Currently there are no such allocations in Cocoa, though.)
2287 const Stmt *AllocStmt;
Ted Kremenekc887d132009-04-29 18:50:19 +00002288 ProgramPoint P = AllocNode->getLocation();
David Blaikie7a95de62013-02-21 22:23:56 +00002289 if (Optional<CallExitEnd> Exit = P.getAs<CallExitEnd>())
Jordan Rose852aa0d2012-07-10 22:07:52 +00002290 AllocStmt = Exit->getCalleeContext()->getCallSite();
2291 else
David Blaikie7a95de62013-02-21 22:23:56 +00002292 AllocStmt = P.castAs<PostStmt>().getStmt();
Jordan Rose852aa0d2012-07-10 22:07:52 +00002293 assert(AllocStmt && "All allocations must come from explicit calls");
Anna Zakse3a813a2013-04-23 23:57:50 +00002294
2295 PathDiagnosticLocation AllocLocation =
2296 PathDiagnosticLocation::createBegin(AllocStmt, SMgr,
2297 AllocNode->getLocationContext());
2298 Location = AllocLocation;
2299
2300 // Set uniqieing info, which will be used for unique the bug reports. The
2301 // leaks should be uniqued on the allocation site.
2302 UniqueingLocation = AllocLocation;
2303 UniqueingDecl = AllocNode->getLocationContext()->getDecl();
2304
Ted Kremenekc887d132009-04-29 18:50:19 +00002305 // Fill in the description of the bug.
2306 Description.clear();
2307 llvm::raw_string_ostream os(Description);
Ted Kremenekdd924e22009-05-02 19:05:19 +00002308 os << "Potential leak ";
Jordy Rose20589562011-08-24 22:39:09 +00002309 if (GCEnabled)
Ted Kremenekdd924e22009-05-02 19:05:19 +00002310 os << "(when using garbage collection) ";
Anna Zaks212000e2012-02-28 21:49:08 +00002311 os << "of an object";
Mike Stump1eb44332009-09-09 15:08:12 +00002312
Ted Kremenek08a838d2013-04-16 21:44:22 +00002313 if (AllocBinding) {
Anna Zaks212000e2012-02-28 21:49:08 +00002314 os << " stored into '" << AllocBinding->getString() << '\'';
Ted Kremenek08a838d2013-04-16 21:44:22 +00002315 if (IncludeAllocationLine) {
2316 FullSourceLoc SL(AllocStmt->getLocStart(), Ctx.getSourceManager());
2317 os << " (allocated on line " << SL.getSpellingLineNumber() << ")";
2318 }
2319 }
Anna Zaksdc757b02011-08-19 23:21:56 +00002320
Jordy Rose20589562011-08-24 22:39:09 +00002321 addVisitor(new CFRefLeakReportVisitor(sym, GCEnabled, Log));
Ted Kremenekc887d132009-04-29 18:50:19 +00002322}
2323
2324//===----------------------------------------------------------------------===//
2325// Main checker logic.
2326//===----------------------------------------------------------------------===//
2327
Ted Kremenekd593eb92009-11-25 22:17:44 +00002328namespace {
Jordy Rose910c4052011-09-02 06:44:22 +00002329class RetainCountChecker
Jordy Rose9c083b72011-08-24 18:56:32 +00002330 : public Checker< check::Bind,
Jordy Rose38f17d62011-08-23 19:01:07 +00002331 check::DeadSymbols,
Jordy Rose9c083b72011-08-24 18:56:32 +00002332 check::EndAnalysis,
Anna Zaks344c77a2013-01-03 00:25:29 +00002333 check::EndFunction,
Jordy Rose67044292011-08-17 21:27:39 +00002334 check::PostStmt<BlockExpr>,
John McCallf85e1932011-06-15 23:02:42 +00002335 check::PostStmt<CastExpr>,
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002336 check::PostStmt<ObjCArrayLiteral>,
2337 check::PostStmt<ObjCDictionaryLiteral>,
Jordy Rose70fdbc32012-05-12 05:10:43 +00002338 check::PostStmt<ObjCBoxedExpr>,
Jordan Rosefe6a0112012-07-02 19:28:21 +00002339 check::PostCall,
Jordy Rosef53e8c72011-08-23 19:43:16 +00002340 check::PreStmt<ReturnStmt>,
Jordy Rose67044292011-08-17 21:27:39 +00002341 check::RegionChanges,
Jordy Rose76c506f2011-08-21 21:58:18 +00002342 eval::Assume,
2343 eval::Call > {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002344 mutable OwningPtr<CFRefBug> useAfterRelease, releaseNotOwned;
2345 mutable OwningPtr<CFRefBug> deallocGC, deallocNotOwned;
2346 mutable OwningPtr<CFRefBug> overAutorelease, returnNotOwnedForOwned;
2347 mutable OwningPtr<CFRefBug> leakWithinFunction, leakAtReturn;
2348 mutable OwningPtr<CFRefBug> leakWithinFunctionGC, leakAtReturnGC;
Jordy Rose38f17d62011-08-23 19:01:07 +00002349
2350 typedef llvm::DenseMap<SymbolRef, const SimpleProgramPointTag *> SymbolTagMap;
2351
2352 // This map is only used to ensure proper deletion of any allocated tags.
2353 mutable SymbolTagMap DeadSymbolTags;
2354
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002355 mutable OwningPtr<RetainSummaryManager> Summaries;
2356 mutable OwningPtr<RetainSummaryManager> SummariesGC;
Jordy Rose9c083b72011-08-24 18:56:32 +00002357 mutable SummaryLogTy SummaryLog;
2358 mutable bool ShouldResetSummaryLog;
2359
Ted Kremenek08a838d2013-04-16 21:44:22 +00002360 /// Optional setting to indicate if leak reports should include
2361 /// the allocation line.
2362 mutable bool IncludeAllocationLine;
2363
Jordy Rose2f9a66d2011-08-20 21:17:59 +00002364public:
Ted Kremenek08a838d2013-04-16 21:44:22 +00002365 RetainCountChecker(AnalyzerOptions &AO)
2366 : ShouldResetSummaryLog(false),
2367 IncludeAllocationLine(shouldIncludeAllocationSiteInLeakDiagnostics(AO)) {}
Jordy Rose38f17d62011-08-23 19:01:07 +00002368
Jordy Rose910c4052011-09-02 06:44:22 +00002369 virtual ~RetainCountChecker() {
Jordy Rose38f17d62011-08-23 19:01:07 +00002370 DeleteContainerSeconds(DeadSymbolTags);
2371 }
2372
Jordy Rose9c083b72011-08-24 18:56:32 +00002373 void checkEndAnalysis(ExplodedGraph &G, BugReporter &BR,
2374 ExprEngine &Eng) const {
2375 // FIXME: This is a hack to make sure the summary log gets cleared between
2376 // analyses of different code bodies.
2377 //
2378 // Why is this necessary? Because a checker's lifetime is tied to a
2379 // translation unit, but an ExplodedGraph's lifetime is just a code body.
2380 // Once in a blue moon, a new ExplodedNode will have the same address as an
2381 // old one with an associated summary, and the bug report visitor gets very
2382 // confused. (To make things worse, the summary lifetime is currently also
2383 // tied to a code body, so we get a crash instead of incorrect results.)
Jordy Rose1ab51c72011-08-24 09:27:24 +00002384 //
2385 // Why is this a bad solution? Because if the lifetime of the ExplodedGraph
2386 // changes, things will start going wrong again. Really the lifetime of this
2387 // log needs to be tied to either the specific nodes in it or the entire
2388 // ExplodedGraph, not to a specific part of the code being analyzed.
2389 //
Jordy Rose9c083b72011-08-24 18:56:32 +00002390 // (Also, having stateful local data means that the same checker can't be
2391 // used from multiple threads, but a lot of checkers have incorrect
2392 // assumptions about that anyway. So that wasn't a priority at the time of
2393 // this fix.)
Jordy Rose1ab51c72011-08-24 09:27:24 +00002394 //
Jordy Rose9c083b72011-08-24 18:56:32 +00002395 // This happens at the end of analysis, but bug reports are emitted /after/
2396 // this point. So we can't just clear the summary log now. Instead, we mark
2397 // that the next time we access the summary log, it should be cleared.
2398
2399 // If we never reset the summary log during /this/ code body analysis,
2400 // there were no new summaries. There might still have been summaries from
2401 // the /last/ analysis, so clear them out to make sure the bug report
2402 // visitors don't get confused.
2403 if (ShouldResetSummaryLog)
2404 SummaryLog.clear();
2405
2406 ShouldResetSummaryLog = !SummaryLog.empty();
Jordy Rose1ab51c72011-08-24 09:27:24 +00002407 }
2408
Jordy Rose17a38e22011-09-02 05:55:19 +00002409 CFRefBug *getLeakWithinFunctionBug(const LangOptions &LOpts,
2410 bool GCEnabled) const {
2411 if (GCEnabled) {
Jordy Rosedb92bb62011-08-25 01:14:38 +00002412 if (!leakWithinFunctionGC)
Benjamin Kramerfacde172012-06-06 17:32:50 +00002413 leakWithinFunctionGC.reset(new Leak("Leak of object when using "
2414 "garbage collection"));
Jordy Rose17a38e22011-09-02 05:55:19 +00002415 return leakWithinFunctionGC.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002416 } else {
2417 if (!leakWithinFunction) {
Douglas Gregore289d812011-09-13 17:21:33 +00002418 if (LOpts.getGC() == LangOptions::HybridGC) {
Benjamin Kramerfacde172012-06-06 17:32:50 +00002419 leakWithinFunction.reset(new Leak("Leak of object when not using "
2420 "garbage collection (GC) in "
2421 "dual GC/non-GC code"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002422 } else {
Benjamin Kramerfacde172012-06-06 17:32:50 +00002423 leakWithinFunction.reset(new Leak("Leak"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002424 }
2425 }
Jordy Rose17a38e22011-09-02 05:55:19 +00002426 return leakWithinFunction.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002427 }
2428 }
2429
Jordy Rose17a38e22011-09-02 05:55:19 +00002430 CFRefBug *getLeakAtReturnBug(const LangOptions &LOpts, bool GCEnabled) const {
2431 if (GCEnabled) {
Jordy Rosedb92bb62011-08-25 01:14:38 +00002432 if (!leakAtReturnGC)
Benjamin Kramerfacde172012-06-06 17:32:50 +00002433 leakAtReturnGC.reset(new Leak("Leak of returned object when using "
2434 "garbage collection"));
Jordy Rose17a38e22011-09-02 05:55:19 +00002435 return leakAtReturnGC.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002436 } else {
2437 if (!leakAtReturn) {
Douglas Gregore289d812011-09-13 17:21:33 +00002438 if (LOpts.getGC() == LangOptions::HybridGC) {
Benjamin Kramerfacde172012-06-06 17:32:50 +00002439 leakAtReturn.reset(new Leak("Leak of returned object when not using "
2440 "garbage collection (GC) in dual "
2441 "GC/non-GC code"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002442 } else {
Benjamin Kramerfacde172012-06-06 17:32:50 +00002443 leakAtReturn.reset(new Leak("Leak of returned object"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002444 }
2445 }
Jordy Rose17a38e22011-09-02 05:55:19 +00002446 return leakAtReturn.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002447 }
2448 }
2449
Jordy Rose17a38e22011-09-02 05:55:19 +00002450 RetainSummaryManager &getSummaryManager(ASTContext &Ctx,
2451 bool GCEnabled) const {
2452 // FIXME: We don't support ARC being turned on and off during one analysis.
2453 // (nor, for that matter, do we support changing ASTContexts)
David Blaikie4e4d0842012-03-11 07:00:24 +00002454 bool ARCEnabled = (bool)Ctx.getLangOpts().ObjCAutoRefCount;
Jordy Rose17a38e22011-09-02 05:55:19 +00002455 if (GCEnabled) {
2456 if (!SummariesGC)
Jordy Roseb6cfc092011-08-25 00:10:37 +00002457 SummariesGC.reset(new RetainSummaryManager(Ctx, true, ARCEnabled));
Jordy Rose17a38e22011-09-02 05:55:19 +00002458 else
2459 assert(SummariesGC->isARCEnabled() == ARCEnabled);
Jordy Roseb6cfc092011-08-25 00:10:37 +00002460 return *SummariesGC;
2461 } else {
Jordy Rose17a38e22011-09-02 05:55:19 +00002462 if (!Summaries)
Jordy Roseb6cfc092011-08-25 00:10:37 +00002463 Summaries.reset(new RetainSummaryManager(Ctx, false, ARCEnabled));
Jordy Rose17a38e22011-09-02 05:55:19 +00002464 else
2465 assert(Summaries->isARCEnabled() == ARCEnabled);
Jordy Roseb6cfc092011-08-25 00:10:37 +00002466 return *Summaries;
2467 }
2468 }
2469
Jordy Rose17a38e22011-09-02 05:55:19 +00002470 RetainSummaryManager &getSummaryManager(CheckerContext &C) const {
2471 return getSummaryManager(C.getASTContext(), C.isObjCGCEnabled());
2472 }
2473
Ted Kremenek8bef8232012-01-26 21:29:00 +00002474 void printState(raw_ostream &Out, ProgramStateRef State,
Jordy Rosedbd658e2011-08-28 19:11:56 +00002475 const char *NL, const char *Sep) const;
2476
Anna Zaks390909c2011-10-06 00:43:15 +00002477 void checkBind(SVal loc, SVal val, const Stmt *S, CheckerContext &C) const;
Jordy Roseab027fd2011-08-20 21:16:58 +00002478 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
2479 void checkPostStmt(const CastExpr *CE, CheckerContext &C) const;
John McCallf85e1932011-06-15 23:02:42 +00002480
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002481 void checkPostStmt(const ObjCArrayLiteral *AL, CheckerContext &C) const;
2482 void checkPostStmt(const ObjCDictionaryLiteral *DL, CheckerContext &C) const;
Jordy Rose70fdbc32012-05-12 05:10:43 +00002483 void checkPostStmt(const ObjCBoxedExpr *BE, CheckerContext &C) const;
2484
Jordan Rosefe6a0112012-07-02 19:28:21 +00002485 void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002486
Jordan Rose4531b7d2012-07-02 19:27:43 +00002487 void checkSummary(const RetainSummary &Summ, const CallEvent &Call,
Jordy Rosee38dd952011-08-28 05:16:28 +00002488 CheckerContext &C) const;
Jordy Rose294396b2011-08-22 23:48:23 +00002489
Anna Zaks554067f2012-08-29 23:23:43 +00002490 void processSummaryOfInlined(const RetainSummary &Summ,
2491 const CallEvent &Call,
2492 CheckerContext &C) const;
2493
Jordy Rose76c506f2011-08-21 21:58:18 +00002494 bool evalCall(const CallExpr *CE, CheckerContext &C) const;
2495
Ted Kremenek8bef8232012-01-26 21:29:00 +00002496 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Jordy Roseab027fd2011-08-20 21:16:58 +00002497 bool Assumption) const;
Jordy Rose67044292011-08-17 21:27:39 +00002498
Ted Kremenek8bef8232012-01-26 21:29:00 +00002499 ProgramStateRef
2500 checkRegionChanges(ProgramStateRef state,
Anna Zaksbf53dfa2012-12-20 00:38:25 +00002501 const InvalidatedSymbols *invalidated,
Jordy Rose537716a2011-08-27 22:51:26 +00002502 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00002503 ArrayRef<const MemRegion *> Regions,
Jordan Rose740d4902012-07-02 19:27:35 +00002504 const CallEvent *Call) const;
Jordy Roseab027fd2011-08-20 21:16:58 +00002505
Ted Kremenek8bef8232012-01-26 21:29:00 +00002506 bool wantsRegionChangeUpdate(ProgramStateRef state) const {
Jordy Rose2f9a66d2011-08-20 21:17:59 +00002507 return true;
Jordy Roseab027fd2011-08-20 21:16:58 +00002508 }
Jordy Rose294396b2011-08-22 23:48:23 +00002509
Jordy Rosef53e8c72011-08-23 19:43:16 +00002510 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
2511 void checkReturnWithRetEffect(const ReturnStmt *S, CheckerContext &C,
2512 ExplodedNode *Pred, RetEffect RE, RefVal X,
Ted Kremenek8bef8232012-01-26 21:29:00 +00002513 SymbolRef Sym, ProgramStateRef state) const;
Jordy Rosef53e8c72011-08-23 19:43:16 +00002514
Jordy Rose38f17d62011-08-23 19:01:07 +00002515 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Anna Zaks344c77a2013-01-03 00:25:29 +00002516 void checkEndFunction(CheckerContext &C) const;
Jordy Rose38f17d62011-08-23 19:01:07 +00002517
Ted Kremenek8bef8232012-01-26 21:29:00 +00002518 ProgramStateRef updateSymbol(ProgramStateRef state, SymbolRef sym,
Anna Zaks554067f2012-08-29 23:23:43 +00002519 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
2520 CheckerContext &C) const;
Jordy Rosee0a5d322011-08-23 20:27:16 +00002521
Ted Kremenek8bef8232012-01-26 21:29:00 +00002522 void processNonLeakError(ProgramStateRef St, SourceRange ErrorRange,
Jordy Rose294396b2011-08-22 23:48:23 +00002523 RefVal::Kind ErrorKind, SymbolRef Sym,
2524 CheckerContext &C) const;
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002525
2526 void processObjCLiterals(CheckerContext &C, const Expr *Ex) const;
Jordy Rose294396b2011-08-22 23:48:23 +00002527
Jordy Rose38f17d62011-08-23 19:01:07 +00002528 const ProgramPointTag *getDeadSymbolTag(SymbolRef sym) const;
2529
Ted Kremenek8bef8232012-01-26 21:29:00 +00002530 ProgramStateRef handleSymbolDeath(ProgramStateRef state,
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002531 SymbolRef sid, RefVal V,
2532 SmallVectorImpl<SymbolRef> &Leaked) const;
Jordy Rose38f17d62011-08-23 19:01:07 +00002533
Jordan Rose4ee1c552012-12-06 18:58:18 +00002534 ProgramStateRef
Jordan Rose2bce86c2012-08-18 00:30:16 +00002535 handleAutoreleaseCounts(ProgramStateRef state, ExplodedNode *Pred,
2536 const ProgramPointTag *Tag, CheckerContext &Ctx,
2537 SymbolRef Sym, RefVal V) const;
Jordy Rose8d228632011-08-23 20:07:14 +00002538
Ted Kremenek8bef8232012-01-26 21:29:00 +00002539 ExplodedNode *processLeaks(ProgramStateRef state,
Jordy Rose38f17d62011-08-23 19:01:07 +00002540 SmallVectorImpl<SymbolRef> &Leaked,
Anna Zaks6a93bd52011-10-25 19:57:11 +00002541 CheckerContext &Ctx,
Jordy Rose38f17d62011-08-23 19:01:07 +00002542 ExplodedNode *Pred = 0) const;
Ted Kremenekd593eb92009-11-25 22:17:44 +00002543};
2544} // end anonymous namespace
2545
Jordy Rose67044292011-08-17 21:27:39 +00002546namespace {
2547class StopTrackingCallback : public SymbolVisitor {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002548 ProgramStateRef state;
Jordy Rose67044292011-08-17 21:27:39 +00002549public:
Ted Kremenek8bef8232012-01-26 21:29:00 +00002550 StopTrackingCallback(ProgramStateRef st) : state(st) {}
2551 ProgramStateRef getState() const { return state; }
Jordy Rose67044292011-08-17 21:27:39 +00002552
2553 bool VisitSymbol(SymbolRef sym) {
2554 state = state->remove<RefBindings>(sym);
2555 return true;
2556 }
2557};
2558} // end anonymous namespace
2559
Jordy Rose910c4052011-09-02 06:44:22 +00002560//===----------------------------------------------------------------------===//
2561// Handle statements that may have an effect on refcounts.
2562//===----------------------------------------------------------------------===//
Jordy Rose67044292011-08-17 21:27:39 +00002563
Jordy Rose910c4052011-09-02 06:44:22 +00002564void RetainCountChecker::checkPostStmt(const BlockExpr *BE,
2565 CheckerContext &C) const {
Jordy Rose67044292011-08-17 21:27:39 +00002566
Jordy Rose910c4052011-09-02 06:44:22 +00002567 // Scan the BlockDecRefExprs for any object the retain count checker
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002568 // may be tracking.
John McCall469a1eb2011-02-02 13:00:07 +00002569 if (!BE->getBlockDecl()->hasCaptures())
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002570 return;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002571
Ted Kremenek8bef8232012-01-26 21:29:00 +00002572 ProgramStateRef state = C.getState();
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002573 const BlockDataRegion *R =
Ted Kremenek5eca4822012-01-06 22:09:28 +00002574 cast<BlockDataRegion>(state->getSVal(BE,
2575 C.getLocationContext()).getAsRegion());
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002576
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002577 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
2578 E = R->referenced_vars_end();
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002579
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002580 if (I == E)
2581 return;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002582
Ted Kremenek67d12872009-12-07 22:05:27 +00002583 // FIXME: For now we invalidate the tracking of all symbols passed to blocks
2584 // via captured variables, even though captured variables result in a copy
2585 // and in implicit increment/decrement of a retain count.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002586 SmallVector<const MemRegion*, 10> Regions;
Anna Zaks39ac1872011-10-26 21:06:44 +00002587 const LocationContext *LC = C.getLocationContext();
Ted Kremenekc8413fd2010-12-02 07:49:45 +00002588 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002589
Ted Kremenek67d12872009-12-07 22:05:27 +00002590 for ( ; I != E; ++I) {
Ted Kremeneke3ce2c12012-12-06 07:17:20 +00002591 const VarRegion *VR = I.getCapturedRegion();
Ted Kremenek67d12872009-12-07 22:05:27 +00002592 if (VR->getSuperRegion() == R) {
2593 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2594 }
2595 Regions.push_back(VR);
2596 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002597
Ted Kremenek67d12872009-12-07 22:05:27 +00002598 state =
2599 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
2600 Regions.data() + Regions.size()).getState();
Anna Zaks0bd6b112011-10-26 21:06:34 +00002601 C.addTransition(state);
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002602}
2603
Jordy Rose910c4052011-09-02 06:44:22 +00002604void RetainCountChecker::checkPostStmt(const CastExpr *CE,
2605 CheckerContext &C) const {
John McCallf85e1932011-06-15 23:02:42 +00002606 const ObjCBridgedCastExpr *BE = dyn_cast<ObjCBridgedCastExpr>(CE);
2607 if (!BE)
2608 return;
2609
John McCall71c482c2011-06-17 06:50:50 +00002610 ArgEffect AE = IncRef;
John McCallf85e1932011-06-15 23:02:42 +00002611
2612 switch (BE->getBridgeKind()) {
2613 case clang::OBC_Bridge:
2614 // Do nothing.
2615 return;
2616 case clang::OBC_BridgeRetained:
2617 AE = IncRef;
2618 break;
2619 case clang::OBC_BridgeTransfer:
2620 AE = DecRefBridgedTransfered;
2621 break;
2622 }
2623
Ted Kremenek8bef8232012-01-26 21:29:00 +00002624 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00002625 SymbolRef Sym = state->getSVal(CE, C.getLocationContext()).getAsLocSymbol();
John McCallf85e1932011-06-15 23:02:42 +00002626 if (!Sym)
2627 return;
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002628 const RefVal* T = getRefBinding(state, Sym);
John McCallf85e1932011-06-15 23:02:42 +00002629 if (!T)
2630 return;
2631
John McCallf85e1932011-06-15 23:02:42 +00002632 RefVal::Kind hasErr = (RefVal::Kind) 0;
Jordy Rose17a38e22011-09-02 05:55:19 +00002633 state = updateSymbol(state, Sym, *T, AE, hasErr, C);
John McCallf85e1932011-06-15 23:02:42 +00002634
2635 if (hasErr) {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002636 // FIXME: If we get an error during a bridge cast, should we report it?
2637 // Should we assert that there is no error?
John McCallf85e1932011-06-15 23:02:42 +00002638 return;
2639 }
2640
Anna Zaks0bd6b112011-10-26 21:06:34 +00002641 C.addTransition(state);
John McCallf85e1932011-06-15 23:02:42 +00002642}
2643
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002644void RetainCountChecker::processObjCLiterals(CheckerContext &C,
2645 const Expr *Ex) const {
2646 ProgramStateRef state = C.getState();
2647 const ExplodedNode *pred = C.getPredecessor();
2648 for (Stmt::const_child_iterator it = Ex->child_begin(), et = Ex->child_end() ;
2649 it != et ; ++it) {
2650 const Stmt *child = *it;
2651 SVal V = state->getSVal(child, pred->getLocationContext());
2652 if (SymbolRef sym = V.getAsSymbol())
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002653 if (const RefVal* T = getRefBinding(state, sym)) {
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002654 RefVal::Kind hasErr = (RefVal::Kind) 0;
2655 state = updateSymbol(state, sym, *T, MayEscape, hasErr, C);
2656 if (hasErr) {
2657 processNonLeakError(state, child->getSourceRange(), hasErr, sym, C);
2658 return;
2659 }
2660 }
2661 }
2662
2663 // Return the object as autoreleased.
2664 // RetEffect RE = RetEffect::MakeNotOwned(RetEffect::ObjC);
2665 if (SymbolRef sym =
2666 state->getSVal(Ex, pred->getLocationContext()).getAsSymbol()) {
2667 QualType ResultTy = Ex->getType();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002668 state = setRefBinding(state, sym,
2669 RefVal::makeNotOwned(RetEffect::ObjC, ResultTy));
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002670 }
2671
2672 C.addTransition(state);
2673}
2674
2675void RetainCountChecker::checkPostStmt(const ObjCArrayLiteral *AL,
2676 CheckerContext &C) const {
2677 // Apply the 'MayEscape' to all values.
2678 processObjCLiterals(C, AL);
2679}
2680
2681void RetainCountChecker::checkPostStmt(const ObjCDictionaryLiteral *DL,
2682 CheckerContext &C) const {
2683 // Apply the 'MayEscape' to all keys and values.
2684 processObjCLiterals(C, DL);
2685}
2686
Jordy Rose70fdbc32012-05-12 05:10:43 +00002687void RetainCountChecker::checkPostStmt(const ObjCBoxedExpr *Ex,
2688 CheckerContext &C) const {
2689 const ExplodedNode *Pred = C.getPredecessor();
2690 const LocationContext *LCtx = Pred->getLocationContext();
2691 ProgramStateRef State = Pred->getState();
2692
2693 if (SymbolRef Sym = State->getSVal(Ex, LCtx).getAsSymbol()) {
2694 QualType ResultTy = Ex->getType();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002695 State = setRefBinding(State, Sym,
2696 RefVal::makeNotOwned(RetEffect::ObjC, ResultTy));
Jordy Rose70fdbc32012-05-12 05:10:43 +00002697 }
2698
2699 C.addTransition(State);
2700}
2701
Jordan Rosefe6a0112012-07-02 19:28:21 +00002702void RetainCountChecker::checkPostCall(const CallEvent &Call,
2703 CheckerContext &C) const {
Jordan Rosefe6a0112012-07-02 19:28:21 +00002704 RetainSummaryManager &Summaries = getSummaryManager(C);
2705 const RetainSummary *Summ = Summaries.getSummary(Call, C.getState());
Anna Zaks554067f2012-08-29 23:23:43 +00002706
2707 if (C.wasInlined) {
2708 processSummaryOfInlined(*Summ, Call, C);
2709 return;
2710 }
Jordan Rosefe6a0112012-07-02 19:28:21 +00002711 checkSummary(*Summ, Call, C);
Jordy Rose294396b2011-08-22 23:48:23 +00002712}
2713
Jordy Rose910c4052011-09-02 06:44:22 +00002714/// GetReturnType - Used to get the return type of a message expression or
2715/// function call with the intention of affixing that type to a tracked symbol.
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +00002716/// While the return type can be queried directly from RetEx, when
Jordy Rose910c4052011-09-02 06:44:22 +00002717/// invoking class methods we augment to the return type to be that of
2718/// a pointer to the class (as opposed it just being id).
2719// FIXME: We may be able to do this with related result types instead.
2720// This function is probably overestimating.
2721static QualType GetReturnType(const Expr *RetE, ASTContext &Ctx) {
2722 QualType RetTy = RetE->getType();
2723 // If RetE is not a message expression just return its type.
2724 // If RetE is a message expression, return its types if it is something
2725 /// more specific than id.
2726 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RetE))
2727 if (const ObjCObjectPointerType *PT = RetTy->getAs<ObjCObjectPointerType>())
2728 if (PT->isObjCQualifiedIdType() || PT->isObjCIdType() ||
2729 PT->isObjCClassType()) {
2730 // At this point we know the return type of the message expression is
2731 // id, id<...>, or Class. If we have an ObjCInterfaceDecl, we know this
2732 // is a call to a class method whose type we can resolve. In such
2733 // cases, promote the return type to XXX* (where XXX is the class).
2734 const ObjCInterfaceDecl *D = ME->getReceiverInterface();
2735 return !D ? RetTy :
2736 Ctx.getObjCObjectPointerType(Ctx.getObjCInterfaceType(D));
2737 }
2738
2739 return RetTy;
2740}
2741
Anna Zaks554067f2012-08-29 23:23:43 +00002742// We don't always get the exact modeling of the function with regards to the
2743// retain count checker even when the function is inlined. For example, we need
2744// to stop tracking the symbols which were marked with StopTrackingHard.
2745void RetainCountChecker::processSummaryOfInlined(const RetainSummary &Summ,
2746 const CallEvent &CallOrMsg,
2747 CheckerContext &C) const {
2748 ProgramStateRef state = C.getState();
2749
2750 // Evaluate the effect of the arguments.
2751 for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
2752 if (Summ.getArg(idx) == StopTrackingHard) {
2753 SVal V = CallOrMsg.getArgSVal(idx);
2754 if (SymbolRef Sym = V.getAsLocSymbol()) {
2755 state = removeRefBinding(state, Sym);
2756 }
2757 }
2758 }
2759
2760 // Evaluate the effect on the message receiver.
2761 const ObjCMethodCall *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg);
2762 if (MsgInvocation) {
2763 if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
2764 if (Summ.getReceiverEffect() == StopTrackingHard) {
2765 state = removeRefBinding(state, Sym);
2766 }
2767 }
2768 }
2769
2770 // Consult the summary for the return value.
2771 RetEffect RE = Summ.getRetEffect();
2772 if (RE.getKind() == RetEffect::NoRetHard) {
Jordan Rose2f3017f2012-11-02 23:49:29 +00002773 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
Anna Zaks554067f2012-08-29 23:23:43 +00002774 if (Sym)
2775 state = removeRefBinding(state, Sym);
2776 }
2777
2778 C.addTransition(state);
2779}
2780
Jordy Rose910c4052011-09-02 06:44:22 +00002781void RetainCountChecker::checkSummary(const RetainSummary &Summ,
Jordan Rose4531b7d2012-07-02 19:27:43 +00002782 const CallEvent &CallOrMsg,
Jordy Rose910c4052011-09-02 06:44:22 +00002783 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002784 ProgramStateRef state = C.getState();
Jordy Rose294396b2011-08-22 23:48:23 +00002785
2786 // Evaluate the effect of the arguments.
2787 RefVal::Kind hasErr = (RefVal::Kind) 0;
2788 SourceRange ErrorRange;
2789 SymbolRef ErrorSym = 0;
2790
2791 for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
Jordy Rose537716a2011-08-27 22:51:26 +00002792 SVal V = CallOrMsg.getArgSVal(idx);
Jordy Rose294396b2011-08-22 23:48:23 +00002793
2794 if (SymbolRef Sym = V.getAsLocSymbol()) {
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002795 if (const RefVal *T = getRefBinding(state, Sym)) {
Jordy Rose17a38e22011-09-02 05:55:19 +00002796 state = updateSymbol(state, Sym, *T, Summ.getArg(idx), hasErr, C);
Jordy Rose294396b2011-08-22 23:48:23 +00002797 if (hasErr) {
2798 ErrorRange = CallOrMsg.getArgSourceRange(idx);
2799 ErrorSym = Sym;
2800 break;
2801 }
2802 }
2803 }
2804 }
2805
2806 // Evaluate the effect on the message receiver.
2807 bool ReceiverIsTracked = false;
Jordan Rose4531b7d2012-07-02 19:27:43 +00002808 if (!hasErr) {
Jordan Rosecde8cdb2012-07-02 19:27:56 +00002809 const ObjCMethodCall *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg);
Jordan Rose4531b7d2012-07-02 19:27:43 +00002810 if (MsgInvocation) {
2811 if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002812 if (const RefVal *T = getRefBinding(state, Sym)) {
Jordan Rose4531b7d2012-07-02 19:27:43 +00002813 ReceiverIsTracked = true;
2814 state = updateSymbol(state, Sym, *T, Summ.getReceiverEffect(),
Anna Zaks554067f2012-08-29 23:23:43 +00002815 hasErr, C);
Jordan Rose4531b7d2012-07-02 19:27:43 +00002816 if (hasErr) {
Jordan Rose8919e682012-07-18 21:59:51 +00002817 ErrorRange = MsgInvocation->getOriginExpr()->getReceiverRange();
Jordan Rose4531b7d2012-07-02 19:27:43 +00002818 ErrorSym = Sym;
2819 }
Jordy Rose294396b2011-08-22 23:48:23 +00002820 }
2821 }
2822 }
2823 }
2824
2825 // Process any errors.
2826 if (hasErr) {
2827 processNonLeakError(state, ErrorRange, hasErr, ErrorSym, C);
2828 return;
2829 }
2830
2831 // Consult the summary for the return value.
2832 RetEffect RE = Summ.getRetEffect();
2833
2834 if (RE.getKind() == RetEffect::OwnedWhenTrackedReceiver) {
Jordy Roseb6cfc092011-08-25 00:10:37 +00002835 if (ReceiverIsTracked)
Jordy Rose17a38e22011-09-02 05:55:19 +00002836 RE = getSummaryManager(C).getObjAllocRetEffect();
Jordy Roseb6cfc092011-08-25 00:10:37 +00002837 else
Jordy Rose294396b2011-08-22 23:48:23 +00002838 RE = RetEffect::MakeNoRet();
2839 }
2840
2841 switch (RE.getKind()) {
2842 default:
David Blaikie7530c032012-01-17 06:56:22 +00002843 llvm_unreachable("Unhandled RetEffect.");
Jordy Rose294396b2011-08-22 23:48:23 +00002844
2845 case RetEffect::NoRet:
Anna Zaks554067f2012-08-29 23:23:43 +00002846 case RetEffect::NoRetHard:
Jordy Rose294396b2011-08-22 23:48:23 +00002847 // No work necessary.
2848 break;
2849
2850 case RetEffect::OwnedAllocatedSymbol:
2851 case RetEffect::OwnedSymbol: {
Jordan Rose2f3017f2012-11-02 23:49:29 +00002852 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
Jordy Rose294396b2011-08-22 23:48:23 +00002853 if (!Sym)
2854 break;
2855
Jordan Rose4531b7d2012-07-02 19:27:43 +00002856 // Use the result type from the CallEvent as it automatically adjusts
Jordy Rose294396b2011-08-22 23:48:23 +00002857 // for methods/functions that return references.
Jordan Rose4531b7d2012-07-02 19:27:43 +00002858 QualType ResultTy = CallOrMsg.getResultType();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002859 state = setRefBinding(state, Sym, RefVal::makeOwned(RE.getObjKind(),
2860 ResultTy));
Jordy Rose294396b2011-08-22 23:48:23 +00002861
2862 // FIXME: Add a flag to the checker where allocations are assumed to
Anna Zaksc6ba23f2012-08-14 15:39:13 +00002863 // *not* fail.
Jordy Rose294396b2011-08-22 23:48:23 +00002864 break;
2865 }
2866
2867 case RetEffect::GCNotOwnedSymbol:
2868 case RetEffect::ARCNotOwnedSymbol:
2869 case RetEffect::NotOwnedSymbol: {
2870 const Expr *Ex = CallOrMsg.getOriginExpr();
Jordan Rose2f3017f2012-11-02 23:49:29 +00002871 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
Jordy Rose294396b2011-08-22 23:48:23 +00002872 if (!Sym)
2873 break;
Ted Kremenek74616822012-10-12 22:56:45 +00002874 assert(Ex);
Jordy Rose294396b2011-08-22 23:48:23 +00002875 // Use GetReturnType in order to give [NSFoo alloc] the type NSFoo *.
2876 QualType ResultTy = GetReturnType(Ex, C.getASTContext());
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002877 state = setRefBinding(state, Sym, RefVal::makeNotOwned(RE.getObjKind(),
2878 ResultTy));
Jordy Rose294396b2011-08-22 23:48:23 +00002879 break;
2880 }
2881 }
2882
2883 // This check is actually necessary; otherwise the statement builder thinks
2884 // we've hit a previously-found path.
2885 // Normally addTransition takes care of this, but we want the node pointer.
2886 ExplodedNode *NewNode;
2887 if (state == C.getState()) {
2888 NewNode = C.getPredecessor();
2889 } else {
Anna Zaks0bd6b112011-10-26 21:06:34 +00002890 NewNode = C.addTransition(state);
Jordy Rose294396b2011-08-22 23:48:23 +00002891 }
2892
Jordy Rose9c083b72011-08-24 18:56:32 +00002893 // Annotate the node with summary we used.
2894 if (NewNode) {
2895 // FIXME: This is ugly. See checkEndAnalysis for why it's necessary.
2896 if (ShouldResetSummaryLog) {
2897 SummaryLog.clear();
2898 ShouldResetSummaryLog = false;
2899 }
Jordy Roseec9ef852011-08-23 20:55:48 +00002900 SummaryLog[NewNode] = &Summ;
Jordy Rose9c083b72011-08-24 18:56:32 +00002901 }
Jordy Rose294396b2011-08-22 23:48:23 +00002902}
2903
Jordy Rosee0a5d322011-08-23 20:27:16 +00002904
Ted Kremenek8bef8232012-01-26 21:29:00 +00002905ProgramStateRef
2906RetainCountChecker::updateSymbol(ProgramStateRef state, SymbolRef sym,
Jordy Rose910c4052011-09-02 06:44:22 +00002907 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
2908 CheckerContext &C) const {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002909 // In GC mode [... release] and [... retain] do nothing.
Jordy Rose910c4052011-09-02 06:44:22 +00002910 // In ARC mode they shouldn't exist at all, but we just ignore them.
Jordy Rose17a38e22011-09-02 05:55:19 +00002911 bool IgnoreRetainMsg = C.isObjCGCEnabled();
2912 if (!IgnoreRetainMsg)
David Blaikie4e4d0842012-03-11 07:00:24 +00002913 IgnoreRetainMsg = (bool)C.getASTContext().getLangOpts().ObjCAutoRefCount;
Jordy Rose17a38e22011-09-02 05:55:19 +00002914
Jordy Rosee0a5d322011-08-23 20:27:16 +00002915 switch (E) {
Jordan Rose4531b7d2012-07-02 19:27:43 +00002916 default:
2917 break;
2918 case IncRefMsg:
2919 E = IgnoreRetainMsg ? DoNothing : IncRef;
2920 break;
2921 case DecRefMsg:
2922 E = IgnoreRetainMsg ? DoNothing : DecRef;
2923 break;
Anna Zaks554067f2012-08-29 23:23:43 +00002924 case DecRefMsgAndStopTrackingHard:
2925 E = IgnoreRetainMsg ? StopTracking : DecRefAndStopTrackingHard;
Jordan Rose4531b7d2012-07-02 19:27:43 +00002926 break;
2927 case MakeCollectable:
2928 E = C.isObjCGCEnabled() ? DecRef : DoNothing;
2929 break;
Jordy Rosee0a5d322011-08-23 20:27:16 +00002930 }
2931
2932 // Handle all use-after-releases.
Jordy Rose17a38e22011-09-02 05:55:19 +00002933 if (!C.isObjCGCEnabled() && V.getKind() == RefVal::Released) {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002934 V = V ^ RefVal::ErrorUseAfterRelease;
2935 hasErr = V.getKind();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002936 return setRefBinding(state, sym, V);
Jordy Rosee0a5d322011-08-23 20:27:16 +00002937 }
2938
2939 switch (E) {
2940 case DecRefMsg:
2941 case IncRefMsg:
2942 case MakeCollectable:
Anna Zaks554067f2012-08-29 23:23:43 +00002943 case DecRefMsgAndStopTrackingHard:
Jordy Rosee0a5d322011-08-23 20:27:16 +00002944 llvm_unreachable("DecRefMsg/IncRefMsg/MakeCollectable already converted");
Jordy Rosee0a5d322011-08-23 20:27:16 +00002945
2946 case Dealloc:
2947 // Any use of -dealloc in GC is *bad*.
Jordy Rose17a38e22011-09-02 05:55:19 +00002948 if (C.isObjCGCEnabled()) {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002949 V = V ^ RefVal::ErrorDeallocGC;
2950 hasErr = V.getKind();
2951 break;
2952 }
2953
2954 switch (V.getKind()) {
2955 default:
2956 llvm_unreachable("Invalid RefVal state for an explicit dealloc.");
Jordy Rosee0a5d322011-08-23 20:27:16 +00002957 case RefVal::Owned:
2958 // The object immediately transitions to the released state.
2959 V = V ^ RefVal::Released;
2960 V.clearCounts();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002961 return setRefBinding(state, sym, V);
Jordy Rosee0a5d322011-08-23 20:27:16 +00002962 case RefVal::NotOwned:
2963 V = V ^ RefVal::ErrorDeallocNotOwned;
2964 hasErr = V.getKind();
2965 break;
2966 }
2967 break;
2968
Jordy Rosee0a5d322011-08-23 20:27:16 +00002969 case MayEscape:
2970 if (V.getKind() == RefVal::Owned) {
2971 V = V ^ RefVal::NotOwned;
2972 break;
2973 }
2974
2975 // Fall-through.
2976
Jordy Rosee0a5d322011-08-23 20:27:16 +00002977 case DoNothing:
2978 return state;
2979
2980 case Autorelease:
Jordy Rose17a38e22011-09-02 05:55:19 +00002981 if (C.isObjCGCEnabled())
Jordy Rosee0a5d322011-08-23 20:27:16 +00002982 return state;
Jordy Rosee0a5d322011-08-23 20:27:16 +00002983 // Update the autorelease counts.
Jordy Rosee0a5d322011-08-23 20:27:16 +00002984 V = V.autorelease();
2985 break;
2986
2987 case StopTracking:
Anna Zaks554067f2012-08-29 23:23:43 +00002988 case StopTrackingHard:
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002989 return removeRefBinding(state, sym);
Jordy Rosee0a5d322011-08-23 20:27:16 +00002990
2991 case IncRef:
2992 switch (V.getKind()) {
2993 default:
2994 llvm_unreachable("Invalid RefVal state for a retain.");
Jordy Rosee0a5d322011-08-23 20:27:16 +00002995 case RefVal::Owned:
2996 case RefVal::NotOwned:
2997 V = V + 1;
2998 break;
2999 case RefVal::Released:
3000 // Non-GC cases are handled above.
Jordy Rose17a38e22011-09-02 05:55:19 +00003001 assert(C.isObjCGCEnabled());
Jordy Rosee0a5d322011-08-23 20:27:16 +00003002 V = (V ^ RefVal::Owned) + 1;
3003 break;
3004 }
3005 break;
3006
Jordy Rosee0a5d322011-08-23 20:27:16 +00003007 case DecRef:
3008 case DecRefBridgedTransfered:
Anna Zaks554067f2012-08-29 23:23:43 +00003009 case DecRefAndStopTrackingHard:
Jordy Rosee0a5d322011-08-23 20:27:16 +00003010 switch (V.getKind()) {
3011 default:
3012 // case 'RefVal::Released' handled above.
3013 llvm_unreachable("Invalid RefVal state for a release.");
Jordy Rosee0a5d322011-08-23 20:27:16 +00003014
3015 case RefVal::Owned:
3016 assert(V.getCount() > 0);
3017 if (V.getCount() == 1)
3018 V = V ^ (E == DecRefBridgedTransfered ?
3019 RefVal::NotOwned : RefVal::Released);
Anna Zaks554067f2012-08-29 23:23:43 +00003020 else if (E == DecRefAndStopTrackingHard)
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003021 return removeRefBinding(state, sym);
Jordan Rose4531b7d2012-07-02 19:27:43 +00003022
Jordy Rosee0a5d322011-08-23 20:27:16 +00003023 V = V - 1;
3024 break;
3025
3026 case RefVal::NotOwned:
Jordan Rose4531b7d2012-07-02 19:27:43 +00003027 if (V.getCount() > 0) {
Anna Zaks554067f2012-08-29 23:23:43 +00003028 if (E == DecRefAndStopTrackingHard)
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003029 return removeRefBinding(state, sym);
Jordy Rosee0a5d322011-08-23 20:27:16 +00003030 V = V - 1;
Jordan Rose4531b7d2012-07-02 19:27:43 +00003031 } else {
Jordy Rosee0a5d322011-08-23 20:27:16 +00003032 V = V ^ RefVal::ErrorReleaseNotOwned;
3033 hasErr = V.getKind();
3034 }
3035 break;
3036
3037 case RefVal::Released:
3038 // Non-GC cases are handled above.
Jordy Rose17a38e22011-09-02 05:55:19 +00003039 assert(C.isObjCGCEnabled());
Jordy Rosee0a5d322011-08-23 20:27:16 +00003040 V = V ^ RefVal::ErrorUseAfterRelease;
3041 hasErr = V.getKind();
3042 break;
3043 }
3044 break;
3045 }
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003046 return setRefBinding(state, sym, V);
Jordy Rosee0a5d322011-08-23 20:27:16 +00003047}
3048
Ted Kremenek8bef8232012-01-26 21:29:00 +00003049void RetainCountChecker::processNonLeakError(ProgramStateRef St,
Jordy Rose910c4052011-09-02 06:44:22 +00003050 SourceRange ErrorRange,
3051 RefVal::Kind ErrorKind,
3052 SymbolRef Sym,
3053 CheckerContext &C) const {
Jordy Rose294396b2011-08-22 23:48:23 +00003054 ExplodedNode *N = C.generateSink(St);
3055 if (!N)
3056 return;
3057
Jordy Rose294396b2011-08-22 23:48:23 +00003058 CFRefBug *BT;
3059 switch (ErrorKind) {
3060 default:
3061 llvm_unreachable("Unhandled error.");
Jordy Rose294396b2011-08-22 23:48:23 +00003062 case RefVal::ErrorUseAfterRelease:
Jordy Rosed6334e12011-08-25 00:34:03 +00003063 if (!useAfterRelease)
3064 useAfterRelease.reset(new UseAfterRelease());
3065 BT = &*useAfterRelease;
Jordy Rose294396b2011-08-22 23:48:23 +00003066 break;
3067 case RefVal::ErrorReleaseNotOwned:
Jordy Rosed6334e12011-08-25 00:34:03 +00003068 if (!releaseNotOwned)
3069 releaseNotOwned.reset(new BadRelease());
3070 BT = &*releaseNotOwned;
Jordy Rose294396b2011-08-22 23:48:23 +00003071 break;
3072 case RefVal::ErrorDeallocGC:
Jordy Rosed6334e12011-08-25 00:34:03 +00003073 if (!deallocGC)
3074 deallocGC.reset(new DeallocGC());
3075 BT = &*deallocGC;
Jordy Rose294396b2011-08-22 23:48:23 +00003076 break;
3077 case RefVal::ErrorDeallocNotOwned:
Jordy Rosed6334e12011-08-25 00:34:03 +00003078 if (!deallocNotOwned)
3079 deallocNotOwned.reset(new DeallocNotOwned());
3080 BT = &*deallocNotOwned;
Jordy Rose294396b2011-08-22 23:48:23 +00003081 break;
3082 }
3083
Jordy Rosed6334e12011-08-25 00:34:03 +00003084 assert(BT);
David Blaikie4e4d0842012-03-11 07:00:24 +00003085 CFRefReport *report = new CFRefReport(*BT, C.getASTContext().getLangOpts(),
Jordy Rose17a38e22011-09-02 05:55:19 +00003086 C.isObjCGCEnabled(), SummaryLog,
3087 N, Sym);
Jordy Rose294396b2011-08-22 23:48:23 +00003088 report->addRange(ErrorRange);
Jordan Rose785950e2012-11-02 01:53:40 +00003089 C.emitReport(report);
Jordy Rose294396b2011-08-22 23:48:23 +00003090}
3091
Jordy Rose910c4052011-09-02 06:44:22 +00003092//===----------------------------------------------------------------------===//
3093// Handle the return values of retain-count-related functions.
3094//===----------------------------------------------------------------------===//
3095
3096bool RetainCountChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
Jordy Rose76c506f2011-08-21 21:58:18 +00003097 // Get the callee. We're only interested in simple C functions.
Ted Kremenek8bef8232012-01-26 21:29:00 +00003098 ProgramStateRef state = C.getState();
Anna Zaksb805c8f2011-12-01 05:57:37 +00003099 const FunctionDecl *FD = C.getCalleeDecl(CE);
Jordy Rose76c506f2011-08-21 21:58:18 +00003100 if (!FD)
3101 return false;
3102
3103 IdentifierInfo *II = FD->getIdentifier();
3104 if (!II)
3105 return false;
3106
3107 // For now, we're only handling the functions that return aliases of their
3108 // arguments: CFRetain and CFMakeCollectable (and their families).
3109 // Eventually we should add other functions we can model entirely,
3110 // such as CFRelease, which don't invalidate their arguments or globals.
3111 if (CE->getNumArgs() != 1)
3112 return false;
3113
3114 // Get the name of the function.
3115 StringRef FName = II->getName();
3116 FName = FName.substr(FName.find_first_not_of('_'));
3117
3118 // See if it's one of the specific functions we know how to eval.
3119 bool canEval = false;
3120
Anna Zaksb805c8f2011-12-01 05:57:37 +00003121 QualType ResultTy = CE->getCallReturnType();
Jordy Rose76c506f2011-08-21 21:58:18 +00003122 if (ResultTy->isObjCIdType()) {
3123 // Handle: id NSMakeCollectable(CFTypeRef)
3124 canEval = II->isStr("NSMakeCollectable");
3125 } else if (ResultTy->isPointerType()) {
3126 // Handle: (CF|CG)Retain
3127 // CFMakeCollectable
3128 // It's okay to be a little sloppy here (CGMakeCollectable doesn't exist).
3129 if (cocoa::isRefType(ResultTy, "CF", FName) ||
3130 cocoa::isRefType(ResultTy, "CG", FName)) {
3131 canEval = isRetain(FD, FName) || isMakeCollectable(FD, FName);
3132 }
3133 }
3134
3135 if (!canEval)
3136 return false;
3137
3138 // Bind the return value.
Ted Kremenek5eca4822012-01-06 22:09:28 +00003139 const LocationContext *LCtx = C.getLocationContext();
3140 SVal RetVal = state->getSVal(CE->getArg(0), LCtx);
Jordy Rose76c506f2011-08-21 21:58:18 +00003141 if (RetVal.isUnknown()) {
3142 // If the receiver is unknown, conjure a return value.
3143 SValBuilder &SVB = C.getSValBuilder();
Ted Kremenek66c486f2012-08-22 06:26:15 +00003144 RetVal = SVB.conjureSymbolVal(0, CE, LCtx, ResultTy, C.blockCount());
Jordy Rose76c506f2011-08-21 21:58:18 +00003145 }
Ted Kremenek5eca4822012-01-06 22:09:28 +00003146 state = state->BindExpr(CE, LCtx, RetVal, false);
Jordy Rose76c506f2011-08-21 21:58:18 +00003147
Jordy Rose294396b2011-08-22 23:48:23 +00003148 // FIXME: This should not be necessary, but otherwise the argument seems to be
3149 // considered alive during the next statement.
3150 if (const MemRegion *ArgRegion = RetVal.getAsRegion()) {
3151 // Save the refcount status of the argument.
3152 SymbolRef Sym = RetVal.getAsLocSymbol();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003153 const RefVal *Binding = 0;
Jordy Rose294396b2011-08-22 23:48:23 +00003154 if (Sym)
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003155 Binding = getRefBinding(state, Sym);
Jordy Rose76c506f2011-08-21 21:58:18 +00003156
Jordy Rose294396b2011-08-22 23:48:23 +00003157 // Invalidate the argument region.
Anna Zaksbf53dfa2012-12-20 00:38:25 +00003158 state = state->invalidateRegions(ArgRegion, CE, C.blockCount(), LCtx,
Anna Zaks64eb0702013-01-16 01:35:54 +00003159 /*CausesPointerEscape*/ false);
Jordy Rose76c506f2011-08-21 21:58:18 +00003160
Jordy Rose294396b2011-08-22 23:48:23 +00003161 // Restore the refcount status of the argument.
3162 if (Binding)
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003163 state = setRefBinding(state, Sym, *Binding);
Jordy Rose294396b2011-08-22 23:48:23 +00003164 }
3165
Anna Zaks0bd6b112011-10-26 21:06:34 +00003166 C.addTransition(state);
Jordy Rose76c506f2011-08-21 21:58:18 +00003167 return true;
3168}
3169
Jordy Rose910c4052011-09-02 06:44:22 +00003170//===----------------------------------------------------------------------===//
3171// Handle return statements.
3172//===----------------------------------------------------------------------===//
Jordy Rosef53e8c72011-08-23 19:43:16 +00003173
Jordy Rose910c4052011-09-02 06:44:22 +00003174void RetainCountChecker::checkPreStmt(const ReturnStmt *S,
3175 CheckerContext &C) const {
Ted Kremeneke5715782012-02-25 02:09:09 +00003176
3177 // Only adjust the reference count if this is the top-level call frame,
3178 // and not the result of inlining. In the future, we should do
3179 // better checking even for inlined calls, and see if they match
3180 // with their expected semantics (e.g., the method should return a retained
3181 // object, etc.).
Anna Zaksfadcd5d2012-11-03 02:54:16 +00003182 if (!C.inTopFrame())
Ted Kremeneke5715782012-02-25 02:09:09 +00003183 return;
3184
Jordy Rosef53e8c72011-08-23 19:43:16 +00003185 const Expr *RetE = S->getRetValue();
3186 if (!RetE)
3187 return;
3188
Ted Kremenek8bef8232012-01-26 21:29:00 +00003189 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00003190 SymbolRef Sym =
3191 state->getSValAsScalarOrLoc(RetE, C.getLocationContext()).getAsLocSymbol();
Jordy Rosef53e8c72011-08-23 19:43:16 +00003192 if (!Sym)
3193 return;
3194
3195 // Get the reference count binding (if any).
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003196 const RefVal *T = getRefBinding(state, Sym);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003197 if (!T)
3198 return;
3199
3200 // Change the reference count.
3201 RefVal X = *T;
3202
3203 switch (X.getKind()) {
3204 case RefVal::Owned: {
3205 unsigned cnt = X.getCount();
3206 assert(cnt > 0);
3207 X.setCount(cnt - 1);
3208 X = X ^ RefVal::ReturnedOwned;
3209 break;
3210 }
3211
3212 case RefVal::NotOwned: {
3213 unsigned cnt = X.getCount();
3214 if (cnt) {
3215 X.setCount(cnt - 1);
3216 X = X ^ RefVal::ReturnedOwned;
3217 }
3218 else {
3219 X = X ^ RefVal::ReturnedNotOwned;
3220 }
3221 break;
3222 }
3223
3224 default:
3225 return;
3226 }
3227
3228 // Update the binding.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003229 state = setRefBinding(state, Sym, X);
Anna Zaks0bd6b112011-10-26 21:06:34 +00003230 ExplodedNode *Pred = C.addTransition(state);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003231
3232 // At this point we have updated the state properly.
3233 // Everything after this is merely checking to see if the return value has
3234 // been over- or under-retained.
3235
3236 // Did we cache out?
3237 if (!Pred)
3238 return;
3239
Jordy Rosef53e8c72011-08-23 19:43:16 +00003240 // Update the autorelease counts.
3241 static SimpleProgramPointTag
Jordy Rose910c4052011-09-02 06:44:22 +00003242 AutoreleaseTag("RetainCountChecker : Autorelease");
Jordan Rose4ee1c552012-12-06 18:58:18 +00003243 state = handleAutoreleaseCounts(state, Pred, &AutoreleaseTag, C, Sym, X);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003244
3245 // Did we cache out?
Jordan Rose4ee1c552012-12-06 18:58:18 +00003246 if (!state)
Jordy Rosef53e8c72011-08-23 19:43:16 +00003247 return;
3248
3249 // Get the updated binding.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003250 T = getRefBinding(state, Sym);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003251 assert(T);
3252 X = *T;
3253
3254 // Consult the summary of the enclosing method.
Jordy Rose17a38e22011-09-02 05:55:19 +00003255 RetainSummaryManager &Summaries = getSummaryManager(C);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003256 const Decl *CD = &Pred->getCodeDecl();
Jordan Rose4531b7d2012-07-02 19:27:43 +00003257 RetEffect RE = RetEffect::MakeNoRet();
Jordy Rosef53e8c72011-08-23 19:43:16 +00003258
Jordan Rose4531b7d2012-07-02 19:27:43 +00003259 // FIXME: What is the convention for blocks? Is there one?
Jordy Rosef53e8c72011-08-23 19:43:16 +00003260 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CD)) {
Jordy Roseb6cfc092011-08-25 00:10:37 +00003261 const RetainSummary *Summ = Summaries.getMethodSummary(MD);
Jordan Rose4531b7d2012-07-02 19:27:43 +00003262 RE = Summ->getRetEffect();
3263 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) {
3264 if (!isa<CXXMethodDecl>(FD)) {
3265 const RetainSummary *Summ = Summaries.getFunctionSummary(FD);
3266 RE = Summ->getRetEffect();
3267 }
Jordy Rosef53e8c72011-08-23 19:43:16 +00003268 }
3269
Jordan Rose4531b7d2012-07-02 19:27:43 +00003270 checkReturnWithRetEffect(S, C, Pred, RE, X, Sym, state);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003271}
3272
Jordy Rose910c4052011-09-02 06:44:22 +00003273void RetainCountChecker::checkReturnWithRetEffect(const ReturnStmt *S,
3274 CheckerContext &C,
3275 ExplodedNode *Pred,
3276 RetEffect RE, RefVal X,
3277 SymbolRef Sym,
Ted Kremenek8bef8232012-01-26 21:29:00 +00003278 ProgramStateRef state) const {
Jordy Rosef53e8c72011-08-23 19:43:16 +00003279 // Any leaks or other errors?
3280 if (X.isReturnedOwned() && X.getCount() == 0) {
3281 if (RE.getKind() != RetEffect::NoRet) {
3282 bool hasError = false;
Jordy Rose17a38e22011-09-02 05:55:19 +00003283 if (C.isObjCGCEnabled() && RE.getObjKind() == RetEffect::ObjC) {
Jordy Rosef53e8c72011-08-23 19:43:16 +00003284 // Things are more complicated with garbage collection. If the
3285 // returned object is suppose to be an Objective-C object, we have
3286 // a leak (as the caller expects a GC'ed object) because no
3287 // method should return ownership unless it returns a CF object.
3288 hasError = true;
3289 X = X ^ RefVal::ErrorGCLeakReturned;
3290 }
3291 else if (!RE.isOwned()) {
3292 // Either we are using GC and the returned object is a CF type
3293 // or we aren't using GC. In either case, we expect that the
3294 // enclosing method is expected to return ownership.
3295 hasError = true;
3296 X = X ^ RefVal::ErrorLeakReturned;
3297 }
3298
3299 if (hasError) {
3300 // Generate an error node.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003301 state = setRefBinding(state, Sym, X);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003302
3303 static SimpleProgramPointTag
Jordy Rose910c4052011-09-02 06:44:22 +00003304 ReturnOwnLeakTag("RetainCountChecker : ReturnsOwnLeak");
Anna Zaks0bd6b112011-10-26 21:06:34 +00003305 ExplodedNode *N = C.addTransition(state, Pred, &ReturnOwnLeakTag);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003306 if (N) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003307 const LangOptions &LOpts = C.getASTContext().getLangOpts();
Jordy Rose17a38e22011-09-02 05:55:19 +00003308 bool GCEnabled = C.isObjCGCEnabled();
Jordy Rosef53e8c72011-08-23 19:43:16 +00003309 CFRefReport *report =
Jordy Rose17a38e22011-09-02 05:55:19 +00003310 new CFRefLeakReport(*getLeakAtReturnBug(LOpts, GCEnabled),
3311 LOpts, GCEnabled, SummaryLog,
Ted Kremenek08a838d2013-04-16 21:44:22 +00003312 N, Sym, C, IncludeAllocationLine);
3313
Jordan Rose785950e2012-11-02 01:53:40 +00003314 C.emitReport(report);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003315 }
3316 }
3317 }
3318 } else if (X.isReturnedNotOwned()) {
3319 if (RE.isOwned()) {
3320 // Trying to return a not owned object to a caller expecting an
3321 // owned object.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003322 state = setRefBinding(state, Sym, X ^ RefVal::ErrorReturnedNotOwned);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003323
3324 static SimpleProgramPointTag
Jordy Rose910c4052011-09-02 06:44:22 +00003325 ReturnNotOwnedTag("RetainCountChecker : ReturnNotOwnedForOwned");
Anna Zaks0bd6b112011-10-26 21:06:34 +00003326 ExplodedNode *N = C.addTransition(state, Pred, &ReturnNotOwnedTag);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003327 if (N) {
Jordy Rosed6334e12011-08-25 00:34:03 +00003328 if (!returnNotOwnedForOwned)
3329 returnNotOwnedForOwned.reset(new ReturnedNotOwnedForOwned());
3330
Jordy Rosef53e8c72011-08-23 19:43:16 +00003331 CFRefReport *report =
Jordy Rosed6334e12011-08-25 00:34:03 +00003332 new CFRefReport(*returnNotOwnedForOwned,
David Blaikie4e4d0842012-03-11 07:00:24 +00003333 C.getASTContext().getLangOpts(),
Jordy Rose17a38e22011-09-02 05:55:19 +00003334 C.isObjCGCEnabled(), SummaryLog, N, Sym);
Jordan Rose785950e2012-11-02 01:53:40 +00003335 C.emitReport(report);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003336 }
3337 }
3338 }
3339}
3340
Jordy Rose8d228632011-08-23 20:07:14 +00003341//===----------------------------------------------------------------------===//
Jordy Rose910c4052011-09-02 06:44:22 +00003342// Check various ways a symbol can be invalidated.
3343//===----------------------------------------------------------------------===//
3344
Anna Zaks390909c2011-10-06 00:43:15 +00003345void RetainCountChecker::checkBind(SVal loc, SVal val, const Stmt *S,
Jordy Rose910c4052011-09-02 06:44:22 +00003346 CheckerContext &C) const {
3347 // Are we storing to something that causes the value to "escape"?
3348 bool escapes = true;
3349
3350 // A value escapes in three possible cases (this may change):
3351 //
3352 // (1) we are binding to something that is not a memory region.
3353 // (2) we are binding to a memregion that does not have stack storage
3354 // (3) we are binding to a memregion with stack storage that the store
3355 // does not understand.
Ted Kremenek8bef8232012-01-26 21:29:00 +00003356 ProgramStateRef state = C.getState();
Jordy Rose910c4052011-09-02 06:44:22 +00003357
David Blaikiedc84cd52013-02-20 22:23:23 +00003358 if (Optional<loc::MemRegionVal> regionLoc = loc.getAs<loc::MemRegionVal>()) {
Jordy Rose910c4052011-09-02 06:44:22 +00003359 escapes = !regionLoc->getRegion()->hasStackStorage();
3360
3361 if (!escapes) {
3362 // To test (3), generate a new state with the binding added. If it is
3363 // the same state, then it escapes (since the store cannot represent
3364 // the binding).
Anna Zakse7958da2012-05-02 00:15:40 +00003365 // Do this only if we know that the store is not supposed to generate the
3366 // same state.
3367 SVal StoredVal = state->getSVal(regionLoc->getRegion());
3368 if (StoredVal != val)
3369 escapes = (state == (state->bindLoc(*regionLoc, val)));
Jordy Rose910c4052011-09-02 06:44:22 +00003370 }
Ted Kremenekde5b4fb2012-03-27 01:12:45 +00003371 if (!escapes) {
3372 // Case 4: We do not currently model what happens when a symbol is
3373 // assigned to a struct field, so be conservative here and let the symbol
3374 // go. TODO: This could definitely be improved upon.
3375 escapes = !isa<VarRegion>(regionLoc->getRegion());
3376 }
Jordy Rose910c4052011-09-02 06:44:22 +00003377 }
3378
3379 // If our store can represent the binding and we aren't storing to something
3380 // that doesn't have local storage then just return and have the simulation
3381 // state continue as is.
3382 if (!escapes)
3383 return;
3384
3385 // Otherwise, find all symbols referenced by 'val' that we are tracking
3386 // and stop tracking them.
3387 state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
Anna Zaks0bd6b112011-10-26 21:06:34 +00003388 C.addTransition(state);
Jordy Rose910c4052011-09-02 06:44:22 +00003389}
3390
Ted Kremenek8bef8232012-01-26 21:29:00 +00003391ProgramStateRef RetainCountChecker::evalAssume(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003392 SVal Cond,
3393 bool Assumption) const {
3394
3395 // FIXME: We may add to the interface of evalAssume the list of symbols
3396 // whose assumptions have changed. For now we just iterate through the
3397 // bindings and check if any of the tracked symbols are NULL. This isn't
3398 // too bad since the number of symbols we will track in practice are
3399 // probably small and evalAssume is only called at branches and a few
3400 // other places.
Jordan Rose166d5022012-11-02 01:54:06 +00003401 RefBindingsTy B = state->get<RefBindings>();
Jordy Rose910c4052011-09-02 06:44:22 +00003402
3403 if (B.isEmpty())
3404 return state;
3405
3406 bool changed = false;
Jordan Rose166d5022012-11-02 01:54:06 +00003407 RefBindingsTy::Factory &RefBFactory = state->get_context<RefBindings>();
Jordy Rose910c4052011-09-02 06:44:22 +00003408
Jordan Rose166d5022012-11-02 01:54:06 +00003409 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Ted Kremenek47cbd0f2012-09-07 22:31:01 +00003410 // Check if the symbol is null stop tracking the symbol.
Jordan Roseec8d4202012-11-01 00:18:27 +00003411 ConstraintManager &CMgr = state->getConstraintManager();
3412 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
3413 if (AllocFailed.isConstrainedTrue()) {
Jordy Rose910c4052011-09-02 06:44:22 +00003414 changed = true;
3415 B = RefBFactory.remove(B, I.getKey());
3416 }
3417 }
3418
3419 if (changed)
3420 state = state->set<RefBindings>(B);
3421
3422 return state;
3423}
3424
Ted Kremenek8bef8232012-01-26 21:29:00 +00003425ProgramStateRef
3426RetainCountChecker::checkRegionChanges(ProgramStateRef state,
Anna Zaksbf53dfa2012-12-20 00:38:25 +00003427 const InvalidatedSymbols *invalidated,
Jordy Rose910c4052011-09-02 06:44:22 +00003428 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00003429 ArrayRef<const MemRegion *> Regions,
Jordan Rose740d4902012-07-02 19:27:35 +00003430 const CallEvent *Call) const {
Jordy Rose910c4052011-09-02 06:44:22 +00003431 if (!invalidated)
3432 return state;
3433
3434 llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
3435 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
3436 E = ExplicitRegions.end(); I != E; ++I) {
3437 if (const SymbolicRegion *SR = (*I)->StripCasts()->getAs<SymbolicRegion>())
3438 WhitelistedSymbols.insert(SR->getSymbol());
3439 }
3440
Anna Zaksbf53dfa2012-12-20 00:38:25 +00003441 for (InvalidatedSymbols::const_iterator I=invalidated->begin(),
Jordy Rose910c4052011-09-02 06:44:22 +00003442 E = invalidated->end(); I!=E; ++I) {
3443 SymbolRef sym = *I;
3444 if (WhitelistedSymbols.count(sym))
3445 continue;
3446 // Remove any existing reference-count binding.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003447 state = removeRefBinding(state, sym);
Jordy Rose910c4052011-09-02 06:44:22 +00003448 }
3449 return state;
3450}
3451
3452//===----------------------------------------------------------------------===//
Jordy Rose8d228632011-08-23 20:07:14 +00003453// Handle dead symbols and end-of-path.
3454//===----------------------------------------------------------------------===//
3455
Jordan Rose4ee1c552012-12-06 18:58:18 +00003456ProgramStateRef
3457RetainCountChecker::handleAutoreleaseCounts(ProgramStateRef state,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003458 ExplodedNode *Pred,
Jordan Rose2bce86c2012-08-18 00:30:16 +00003459 const ProgramPointTag *Tag,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003460 CheckerContext &Ctx,
Jordy Rose910c4052011-09-02 06:44:22 +00003461 SymbolRef Sym, RefVal V) const {
Jordy Rose8d228632011-08-23 20:07:14 +00003462 unsigned ACnt = V.getAutoreleaseCount();
3463
3464 // No autorelease counts? Nothing to be done.
3465 if (!ACnt)
Jordan Rose4ee1c552012-12-06 18:58:18 +00003466 return state;
Jordy Rose8d228632011-08-23 20:07:14 +00003467
Anna Zaks6a93bd52011-10-25 19:57:11 +00003468 assert(!Ctx.isObjCGCEnabled() && "Autorelease counts in GC mode?");
Jordy Rose8d228632011-08-23 20:07:14 +00003469 unsigned Cnt = V.getCount();
3470
3471 // FIXME: Handle sending 'autorelease' to already released object.
3472
3473 if (V.getKind() == RefVal::ReturnedOwned)
3474 ++Cnt;
3475
3476 if (ACnt <= Cnt) {
3477 if (ACnt == Cnt) {
3478 V.clearCounts();
3479 if (V.getKind() == RefVal::ReturnedOwned)
3480 V = V ^ RefVal::ReturnedNotOwned;
3481 else
3482 V = V ^ RefVal::NotOwned;
3483 } else {
Anna Zaks0217b1d2013-01-31 22:36:17 +00003484 V.setCount(V.getCount() - ACnt);
Jordy Rose8d228632011-08-23 20:07:14 +00003485 V.setAutoreleaseCount(0);
3486 }
Jordan Rose4ee1c552012-12-06 18:58:18 +00003487 return setRefBinding(state, Sym, V);
Jordy Rose8d228632011-08-23 20:07:14 +00003488 }
3489
3490 // Woah! More autorelease counts then retain counts left.
3491 // Emit hard error.
3492 V = V ^ RefVal::ErrorOverAutorelease;
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003493 state = setRefBinding(state, Sym, V);
Jordy Rose8d228632011-08-23 20:07:14 +00003494
Jordan Rosefa06f042012-08-20 18:43:42 +00003495 ExplodedNode *N = Ctx.generateSink(state, Pred, Tag);
Jordan Rose2bce86c2012-08-18 00:30:16 +00003496 if (N) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003497 SmallString<128> sbuf;
Jordy Rose8d228632011-08-23 20:07:14 +00003498 llvm::raw_svector_ostream os(sbuf);
Jordan Rose2545b1d2013-04-23 01:42:25 +00003499 os << "Object was autoreleased ";
Jordy Rose8d228632011-08-23 20:07:14 +00003500 if (V.getAutoreleaseCount() > 1)
Jordan Rose2545b1d2013-04-23 01:42:25 +00003501 os << V.getAutoreleaseCount() << " times but the object ";
3502 else
3503 os << "but ";
3504 os << "has a +" << V.getCount() << " retain count";
Jordy Rose8d228632011-08-23 20:07:14 +00003505
Jordy Rosed6334e12011-08-25 00:34:03 +00003506 if (!overAutorelease)
3507 overAutorelease.reset(new OverAutorelease());
3508
David Blaikie4e4d0842012-03-11 07:00:24 +00003509 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
Jordy Rose8d228632011-08-23 20:07:14 +00003510 CFRefReport *report =
Jordy Rosed6334e12011-08-25 00:34:03 +00003511 new CFRefReport(*overAutorelease, LOpts, /* GCEnabled = */ false,
3512 SummaryLog, N, Sym, os.str());
Jordan Rose785950e2012-11-02 01:53:40 +00003513 Ctx.emitReport(report);
Jordy Rose8d228632011-08-23 20:07:14 +00003514 }
3515
Jordan Rose4ee1c552012-12-06 18:58:18 +00003516 return 0;
Jordy Rose8d228632011-08-23 20:07:14 +00003517}
Jordy Rose38f17d62011-08-23 19:01:07 +00003518
Ted Kremenek8bef8232012-01-26 21:29:00 +00003519ProgramStateRef
3520RetainCountChecker::handleSymbolDeath(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003521 SymbolRef sid, RefVal V,
Jordy Rose38f17d62011-08-23 19:01:07 +00003522 SmallVectorImpl<SymbolRef> &Leaked) const {
Jordy Rose53376122011-08-24 04:48:19 +00003523 bool hasLeak = false;
Jordy Rose38f17d62011-08-23 19:01:07 +00003524 if (V.isOwned())
3525 hasLeak = true;
3526 else if (V.isNotOwned() || V.isReturnedOwned())
3527 hasLeak = (V.getCount() > 0);
3528
3529 if (!hasLeak)
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003530 return removeRefBinding(state, sid);
Jordy Rose38f17d62011-08-23 19:01:07 +00003531
3532 Leaked.push_back(sid);
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003533 return setRefBinding(state, sid, V ^ RefVal::ErrorLeak);
Jordy Rose38f17d62011-08-23 19:01:07 +00003534}
3535
3536ExplodedNode *
Ted Kremenek8bef8232012-01-26 21:29:00 +00003537RetainCountChecker::processLeaks(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003538 SmallVectorImpl<SymbolRef> &Leaked,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003539 CheckerContext &Ctx,
3540 ExplodedNode *Pred) const {
Jordy Rose38f17d62011-08-23 19:01:07 +00003541 // Generate an intermediate node representing the leak point.
Jordan Rose2bce86c2012-08-18 00:30:16 +00003542 ExplodedNode *N = Ctx.addTransition(state, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003543
3544 if (N) {
3545 for (SmallVectorImpl<SymbolRef>::iterator
3546 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3547
David Blaikie4e4d0842012-03-11 07:00:24 +00003548 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
Anna Zaks6a93bd52011-10-25 19:57:11 +00003549 bool GCEnabled = Ctx.isObjCGCEnabled();
Jordy Rose17a38e22011-09-02 05:55:19 +00003550 CFRefBug *BT = Pred ? getLeakWithinFunctionBug(LOpts, GCEnabled)
3551 : getLeakAtReturnBug(LOpts, GCEnabled);
Jordy Rose38f17d62011-08-23 19:01:07 +00003552 assert(BT && "BugType not initialized.");
Jordy Rose20589562011-08-24 22:39:09 +00003553
Jordy Rose17a38e22011-09-02 05:55:19 +00003554 CFRefLeakReport *report = new CFRefLeakReport(*BT, LOpts, GCEnabled,
Ted Kremenek08a838d2013-04-16 21:44:22 +00003555 SummaryLog, N, *I, Ctx,
3556 IncludeAllocationLine);
Jordan Rose785950e2012-11-02 01:53:40 +00003557 Ctx.emitReport(report);
Jordy Rose38f17d62011-08-23 19:01:07 +00003558 }
3559 }
3560
3561 return N;
3562}
3563
Anna Zaks344c77a2013-01-03 00:25:29 +00003564void RetainCountChecker::checkEndFunction(CheckerContext &Ctx) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +00003565 ProgramStateRef state = Ctx.getState();
Jordan Rose166d5022012-11-02 01:54:06 +00003566 RefBindingsTy B = state->get<RefBindings>();
Anna Zaksaf498a22011-10-25 19:56:48 +00003567 ExplodedNode *Pred = Ctx.getPredecessor();
Jordy Rose38f17d62011-08-23 19:01:07 +00003568
Jordan Rosed8188f82013-08-01 22:16:36 +00003569 // Don't process anything within synthesized bodies.
3570 const LocationContext *LCtx = Pred->getLocationContext();
3571 if (LCtx->getAnalysisDeclContext()->isBodyAutosynthesized()) {
3572 assert(LCtx->getParent());
3573 return;
3574 }
3575
Jordan Rose166d5022012-11-02 01:54:06 +00003576 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Jordan Rose4ee1c552012-12-06 18:58:18 +00003577 state = handleAutoreleaseCounts(state, Pred, /*Tag=*/0, Ctx,
3578 I->first, I->second);
Jordy Rose8d228632011-08-23 20:07:14 +00003579 if (!state)
Jordy Rose38f17d62011-08-23 19:01:07 +00003580 return;
3581 }
3582
Ted Kremenek0cf3d472012-02-07 00:24:33 +00003583 // If the current LocationContext has a parent, don't check for leaks.
3584 // We will do that later.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003585 // FIXME: we should instead check for imbalances of the retain/releases,
Ted Kremenek0cf3d472012-02-07 00:24:33 +00003586 // and suggest annotations.
Jordan Rosed8188f82013-08-01 22:16:36 +00003587 if (LCtx->getParent())
Ted Kremenek0cf3d472012-02-07 00:24:33 +00003588 return;
3589
Jordy Rose38f17d62011-08-23 19:01:07 +00003590 B = state->get<RefBindings>();
3591 SmallVector<SymbolRef, 10> Leaked;
3592
Jordan Rose166d5022012-11-02 01:54:06 +00003593 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I)
Jordy Rose8d228632011-08-23 20:07:14 +00003594 state = handleSymbolDeath(state, I->first, I->second, Leaked);
Jordy Rose38f17d62011-08-23 19:01:07 +00003595
Jordan Rose2bce86c2012-08-18 00:30:16 +00003596 processLeaks(state, Leaked, Ctx, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003597}
3598
3599const ProgramPointTag *
Jordy Rose910c4052011-09-02 06:44:22 +00003600RetainCountChecker::getDeadSymbolTag(SymbolRef sym) const {
Jordy Rose38f17d62011-08-23 19:01:07 +00003601 const SimpleProgramPointTag *&tag = DeadSymbolTags[sym];
3602 if (!tag) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003603 SmallString<64> buf;
Jordy Rose38f17d62011-08-23 19:01:07 +00003604 llvm::raw_svector_ostream out(buf);
Anna Zaksf62ceec2011-12-05 18:58:11 +00003605 out << "RetainCountChecker : Dead Symbol : ";
3606 sym->dumpToStream(out);
Jordy Rose38f17d62011-08-23 19:01:07 +00003607 tag = new SimpleProgramPointTag(out.str());
3608 }
3609 return tag;
3610}
3611
Jordy Rose910c4052011-09-02 06:44:22 +00003612void RetainCountChecker::checkDeadSymbols(SymbolReaper &SymReaper,
3613 CheckerContext &C) const {
Jordy Rose38f17d62011-08-23 19:01:07 +00003614 ExplodedNode *Pred = C.getPredecessor();
3615
Ted Kremenek8bef8232012-01-26 21:29:00 +00003616 ProgramStateRef state = C.getState();
Jordan Rose166d5022012-11-02 01:54:06 +00003617 RefBindingsTy B = state->get<RefBindings>();
Jordan Rose4ee1c552012-12-06 18:58:18 +00003618 SmallVector<SymbolRef, 10> Leaked;
Jordy Rose38f17d62011-08-23 19:01:07 +00003619
3620 // Update counts from autorelease pools
3621 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3622 E = SymReaper.dead_end(); I != E; ++I) {
3623 SymbolRef Sym = *I;
3624 if (const RefVal *T = B.lookup(Sym)){
3625 // Use the symbol as the tag.
3626 // FIXME: This might not be as unique as we would like.
Jordan Rose2bce86c2012-08-18 00:30:16 +00003627 const ProgramPointTag *Tag = getDeadSymbolTag(Sym);
Jordan Rose4ee1c552012-12-06 18:58:18 +00003628 state = handleAutoreleaseCounts(state, Pred, Tag, C, Sym, *T);
Jordy Rose8d228632011-08-23 20:07:14 +00003629 if (!state)
Jordy Rose38f17d62011-08-23 19:01:07 +00003630 return;
Jordan Rose4ee1c552012-12-06 18:58:18 +00003631
3632 // Fetch the new reference count from the state, and use it to handle
3633 // this symbol.
3634 state = handleSymbolDeath(state, *I, *getRefBinding(state, Sym), Leaked);
Jordy Rose38f17d62011-08-23 19:01:07 +00003635 }
3636 }
3637
Jordan Rose4ee1c552012-12-06 18:58:18 +00003638 if (Leaked.empty()) {
3639 C.addTransition(state);
3640 return;
Jordy Rose38f17d62011-08-23 19:01:07 +00003641 }
3642
Jordan Rose2bce86c2012-08-18 00:30:16 +00003643 Pred = processLeaks(state, Leaked, C, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003644
3645 // Did we cache out?
3646 if (!Pred)
3647 return;
3648
3649 // Now generate a new node that nukes the old bindings.
Jordan Rose4ee1c552012-12-06 18:58:18 +00003650 // The only bindings left at this point are the leaked symbols.
Jordan Rose166d5022012-11-02 01:54:06 +00003651 RefBindingsTy::Factory &F = state->get_context<RefBindings>();
Jordan Rose4ee1c552012-12-06 18:58:18 +00003652 B = state->get<RefBindings>();
Jordy Rose38f17d62011-08-23 19:01:07 +00003653
Jordan Rose4ee1c552012-12-06 18:58:18 +00003654 for (SmallVectorImpl<SymbolRef>::iterator I = Leaked.begin(),
3655 E = Leaked.end();
3656 I != E; ++I)
Jordy Rose38f17d62011-08-23 19:01:07 +00003657 B = F.remove(B, *I);
3658
3659 state = state->set<RefBindings>(B);
Anna Zaks0bd6b112011-10-26 21:06:34 +00003660 C.addTransition(state, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003661}
3662
Ted Kremenek8bef8232012-01-26 21:29:00 +00003663void RetainCountChecker::printState(raw_ostream &Out, ProgramStateRef State,
Jordy Rose910c4052011-09-02 06:44:22 +00003664 const char *NL, const char *Sep) const {
Jordy Rosedbd658e2011-08-28 19:11:56 +00003665
Jordan Rose166d5022012-11-02 01:54:06 +00003666 RefBindingsTy B = State->get<RefBindings>();
Jordy Rosedbd658e2011-08-28 19:11:56 +00003667
Ted Kremenek65a08922013-03-28 18:43:18 +00003668 if (B.isEmpty())
3669 return;
3670
3671 Out << Sep << NL;
Jordy Rosedbd658e2011-08-28 19:11:56 +00003672
Jordan Rose166d5022012-11-02 01:54:06 +00003673 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Jordy Rosedbd658e2011-08-28 19:11:56 +00003674 Out << I->first << " : ";
3675 I->second.print(Out);
3676 Out << NL;
3677 }
Jordy Rosedbd658e2011-08-28 19:11:56 +00003678}
3679
3680//===----------------------------------------------------------------------===//
Jordy Rose910c4052011-09-02 06:44:22 +00003681// Checker registration.
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00003682//===----------------------------------------------------------------------===//
3683
Jordy Rose17a38e22011-09-02 05:55:19 +00003684void ento::registerRetainCountChecker(CheckerManager &Mgr) {
Ted Kremenek08a838d2013-04-16 21:44:22 +00003685 Mgr.registerChecker<RetainCountChecker>(Mgr.getAnalyzerOptions());
Jordy Rose17a38e22011-09-02 05:55:19 +00003686}
3687
Ted Kremenek53c7ea12013-08-14 23:41:49 +00003688//===----------------------------------------------------------------------===//
3689// Implementation of the CallEffects API.
3690//===----------------------------------------------------------------------===//
3691
3692namespace clang { namespace ento { namespace objc_retain {
3693
3694// This is a bit gross, but it allows us to populate CallEffects without
3695// creating a bunch of accessors. This kind is very localized, so the
3696// damage of this macro is limited.
3697#define createCallEffect(D, KIND)\
3698 ASTContext &Ctx = D->getASTContext();\
3699 LangOptions L = Ctx.getLangOpts();\
3700 RetainSummaryManager M(Ctx, L.GCOnly, L.ObjCAutoRefCount);\
3701 const RetainSummary *S = M.get ## KIND ## Summary(D);\
3702 CallEffects CE(S->getRetEffect());\
3703 CE.Receiver = S->getReceiverEffect();\
3704 unsigned N = S->getNumArgs();\
3705 for (unsigned i = 0; i < N; ++i) {\
3706 CE.Args.push_back(S->getArg(i));\
3707 }
3708
3709CallEffects CallEffects::getEffect(const ObjCMethodDecl *MD) {
3710 createCallEffect(MD, Method);
3711 return CE;
3712}
3713
3714CallEffects CallEffects::getEffect(const FunctionDecl *FD) {
3715 createCallEffect(FD, Function);
3716 return CE;
3717}
3718
3719#undef createCallEffect
3720
3721}}}