blob: 7a97ce52c68731c61f692e97dfa4e6640d509c89 [file] [log] [blame]
Jordy Rose910c4052011-09-02 06:44:22 +00001//==-- RetainCountChecker.cpp - Checks for leaks and other issues -*- C++ -*--//
Ted Kremenek2fff37e2008-03-06 00:08:09 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Jordy Rose910c4052011-09-02 06:44:22 +000010// This file defines the methods for RetainCountChecker, which implements
11// a reference count checker for Core Foundation and Cocoa on (Mac OS X).
Ted Kremenek2fff37e2008-03-06 00:08:09 +000012//
13//===----------------------------------------------------------------------===//
14
Jordy Rose910c4052011-09-02 06:44:22 +000015#include "ClangSACheckers.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000016#include "clang/AST/Attr.h"
Ted Kremenekb2771592011-03-30 17:41:19 +000017#include "clang/AST/DeclCXX.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000018#include "clang/AST/DeclObjC.h"
19#include "clang/AST/ParentMap.h"
20#include "clang/Analysis/DomainSpecific/CocoaConventions.h"
Ted Kremenek0b526b42010-02-18 00:05:58 +000021#include "clang/Basic/LangOptions.h"
22#include "clang/Basic/SourceManager.h"
Ted Kremenek9b663712011-02-10 01:03:03 +000023#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
24#include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000025#include "clang/StaticAnalyzer/Core/Checker.h"
26#include "clang/StaticAnalyzer/Core/CheckerManager.h"
Jordan Rosef540c542012-07-26 21:39:41 +000027#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
Jordy Rose910c4052011-09-02 06:44:22 +000028#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
Ted Kremenek18c66fd2011-08-15 22:09:50 +000029#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
Ted Kremenek9b663712011-02-10 01:03:03 +000030#include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
Ted Kremenek5774e392013-08-14 23:41:46 +000031#include "clang/StaticAnalyzer/Checkers/ObjCRetainCount.h"
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000032#include "llvm/ADT/DenseMap.h"
33#include "llvm/ADT/FoldingSet.h"
Ted Kremenek6d348932008-10-21 15:53:15 +000034#include "llvm/ADT/ImmutableList.h"
Ted Kremenek0b526b42010-02-18 00:05:58 +000035#include "llvm/ADT/ImmutableMap.h"
Ted Kremenek6ed9afc2008-05-16 18:33:44 +000036#include "llvm/ADT/STLExtras.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000037#include "llvm/ADT/SmallString.h"
Ted Kremenek0b526b42010-02-18 00:05:58 +000038#include "llvm/ADT/StringExtras.h"
Chris Lattner5f9e2722011-07-23 10:55:15 +000039#include <cstdarg>
Ted Kremenek2fff37e2008-03-06 00:08:09 +000040
Ted Kremenek08a838d2013-04-16 21:44:22 +000041#include "AllocationDiagnostics.h"
42
Ted Kremenek2fff37e2008-03-06 00:08:09 +000043using namespace clang;
Ted Kremenek9ef65372010-12-23 07:20:52 +000044using namespace ento;
Ted Kremenek5774e392013-08-14 23:41:46 +000045using namespace objc_retain;
Ted Kremeneka64e89b2010-01-27 06:13:48 +000046using llvm::StrInStrNoCase;
Ted Kremenek4c79e552008-11-05 16:54:44 +000047
Ted Kremenek05cbe1a2008-04-09 23:49:11 +000048//===----------------------------------------------------------------------===//
Ted Kremenek5774e392013-08-14 23:41:46 +000049// Adapters for FoldingSet.
Ted Kremenek05cbe1a2008-04-09 23:49:11 +000050//===----------------------------------------------------------------------===//
51
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000052namespace llvm {
Ted Kremenekb77449c2009-05-03 05:20:50 +000053template <> struct FoldingSetTrait<ArgEffect> {
Ted Kremenek5774e392013-08-14 23:41:46 +000054static inline void Profile(const ArgEffect X, FoldingSetNodeID &ID) {
Ted Kremenekb77449c2009-05-03 05:20:50 +000055 ID.AddInteger((unsigned) X);
56}
Ted Kremenek553cf182008-06-25 21:21:56 +000057};
Ted Kremenek5774e392013-08-14 23:41:46 +000058template <> struct FoldingSetTrait<RetEffect> {
59 static inline void Profile(const RetEffect &X, FoldingSetNodeID &ID) {
60 ID.AddInteger((unsigned) X.getKind());
61 ID.AddInteger((unsigned) X.getObjKind());
62}
63};
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000064} // end llvm namespace
65
Ted Kremenek5774e392013-08-14 23:41:46 +000066//===----------------------------------------------------------------------===//
67// Reference-counting logic (typestate + counts).
68//===----------------------------------------------------------------------===//
69
Ted Kremenekb77449c2009-05-03 05:20:50 +000070/// ArgEffects summarizes the effects of a function/method call on all of
71/// its arguments.
72typedef llvm::ImmutableMap<unsigned,ArgEffect> ArgEffects;
73
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000074namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +000075class RefVal {
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +000076public:
77 enum Kind {
78 Owned = 0, // Owning reference.
79 NotOwned, // Reference is not owned by still valid (not freed).
80 Released, // Object has been released.
81 ReturnedOwned, // Returned object passes ownership to caller.
82 ReturnedNotOwned, // Return object does not pass ownership to caller.
83 ERROR_START,
84 ErrorDeallocNotOwned, // -dealloc called on non-owned object.
85 ErrorDeallocGC, // Calling -dealloc with GC enabled.
86 ErrorUseAfterRelease, // Object used after released.
87 ErrorReleaseNotOwned, // Release of an object that was not owned.
88 ERROR_LEAK_START,
89 ErrorLeak, // A memory leak due to excessive reference counts.
90 ErrorLeakReturned, // A memory leak due to the returning method not having
91 // the correct naming conventions.
92 ErrorGCLeakReturned,
93 ErrorOverAutorelease,
94 ErrorReturnedNotOwned
95 };
Ted Kremenekdcee3ce2010-07-01 20:16:50 +000096
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +000097private:
98 Kind kind;
99 RetEffect::ObjKind okind;
100 unsigned Cnt;
101 unsigned ACnt;
102 QualType T;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000103
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000104 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, unsigned acnt, QualType t)
105 : kind(k), okind(o), Cnt(cnt), ACnt(acnt), T(t) {}
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000106
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000107public:
108 Kind getKind() const { return kind; }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000109
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000110 RetEffect::ObjKind getObjKind() const { return okind; }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000111
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000112 unsigned getCount() const { return Cnt; }
113 unsigned getAutoreleaseCount() const { return ACnt; }
114 unsigned getCombinedCounts() const { return Cnt + ACnt; }
115 void clearCounts() { Cnt = 0; ACnt = 0; }
116 void setCount(unsigned i) { Cnt = i; }
117 void setAutoreleaseCount(unsigned i) { ACnt = i; }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000118
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000119 QualType getType() const { return T; }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000120
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000121 bool isOwned() const {
122 return getKind() == Owned;
123 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000124
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000125 bool isNotOwned() const {
126 return getKind() == NotOwned;
127 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000128
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000129 bool isReturnedOwned() const {
130 return getKind() == ReturnedOwned;
131 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000132
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000133 bool isReturnedNotOwned() const {
134 return getKind() == ReturnedNotOwned;
135 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000136
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000137 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
138 unsigned Count = 1) {
139 return RefVal(Owned, o, Count, 0, t);
140 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000141
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000142 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
143 unsigned Count = 0) {
144 return RefVal(NotOwned, o, Count, 0, t);
145 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000146
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000147 // Comparison, profiling, and pretty-printing.
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000148
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000149 bool operator==(const RefVal& X) const {
150 return kind == X.kind && Cnt == X.Cnt && T == X.T && ACnt == X.ACnt;
151 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000152
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000153 RefVal operator-(size_t i) const {
154 return RefVal(getKind(), getObjKind(), getCount() - i,
155 getAutoreleaseCount(), getType());
156 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000157
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000158 RefVal operator+(size_t i) const {
159 return RefVal(getKind(), getObjKind(), getCount() + i,
160 getAutoreleaseCount(), getType());
161 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000162
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000163 RefVal operator^(Kind k) const {
164 return RefVal(k, getObjKind(), getCount(), getAutoreleaseCount(),
165 getType());
166 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000167
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000168 RefVal autorelease() const {
169 return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount()+1,
170 getType());
171 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000172
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000173 void Profile(llvm::FoldingSetNodeID& ID) const {
174 ID.AddInteger((unsigned) kind);
175 ID.AddInteger(Cnt);
176 ID.AddInteger(ACnt);
177 ID.Add(T);
178 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000179
Ted Kremenek9c378f72011-08-12 23:37:29 +0000180 void print(raw_ostream &Out) const;
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000181};
182
Ted Kremenek9c378f72011-08-12 23:37:29 +0000183void RefVal::print(raw_ostream &Out) const {
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000184 if (!T.isNull())
Jordy Rosedbd658e2011-08-28 19:11:56 +0000185 Out << "Tracked " << T.getAsString() << '/';
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000186
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000187 switch (getKind()) {
Jordy Rose910c4052011-09-02 06:44:22 +0000188 default: llvm_unreachable("Invalid RefVal kind");
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000189 case Owned: {
190 Out << "Owned";
191 unsigned cnt = getCount();
192 if (cnt) Out << " (+ " << cnt << ")";
193 break;
194 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000195
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000196 case NotOwned: {
197 Out << "NotOwned";
198 unsigned cnt = getCount();
199 if (cnt) Out << " (+ " << cnt << ")";
200 break;
201 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000202
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000203 case ReturnedOwned: {
204 Out << "ReturnedOwned";
205 unsigned cnt = getCount();
206 if (cnt) Out << " (+ " << cnt << ")";
207 break;
208 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000209
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000210 case ReturnedNotOwned: {
211 Out << "ReturnedNotOwned";
212 unsigned cnt = getCount();
213 if (cnt) Out << " (+ " << cnt << ")";
214 break;
215 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000216
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000217 case Released:
218 Out << "Released";
219 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000220
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000221 case ErrorDeallocGC:
222 Out << "-dealloc (GC)";
223 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000224
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000225 case ErrorDeallocNotOwned:
226 Out << "-dealloc (not-owned)";
227 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000228
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000229 case ErrorLeak:
230 Out << "Leaked";
231 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000232
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000233 case ErrorLeakReturned:
234 Out << "Leaked (Bad naming)";
235 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000236
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000237 case ErrorGCLeakReturned:
238 Out << "Leaked (GC-ed at return)";
239 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000240
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000241 case ErrorUseAfterRelease:
242 Out << "Use-After-Release [ERROR]";
243 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000244
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000245 case ErrorReleaseNotOwned:
246 Out << "Release of Not-Owned [ERROR]";
247 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000248
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000249 case RefVal::ErrorOverAutorelease:
Jordan Rose2545b1d2013-04-23 01:42:25 +0000250 Out << "Over-autoreleased";
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000251 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000252
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000253 case RefVal::ErrorReturnedNotOwned:
254 Out << "Non-owned object returned instead of owned";
255 break;
256 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000257
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000258 if (ACnt) {
259 Out << " [ARC +" << ACnt << ']';
260 }
261}
262} //end anonymous namespace
263
264//===----------------------------------------------------------------------===//
265// RefBindings - State used to track object reference counts.
266//===----------------------------------------------------------------------===//
267
Jordan Rose166d5022012-11-02 01:54:06 +0000268REGISTER_MAP_WITH_PROGRAMSTATE(RefBindings, SymbolRef, RefVal)
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000269
Anna Zaks8d6b43c2012-08-14 00:36:15 +0000270static inline const RefVal *getRefBinding(ProgramStateRef State,
271 SymbolRef Sym) {
272 return State->get<RefBindings>(Sym);
273}
274
275static inline ProgramStateRef setRefBinding(ProgramStateRef State,
276 SymbolRef Sym, RefVal Val) {
277 return State->set<RefBindings>(Sym, Val);
278}
279
280static ProgramStateRef removeRefBinding(ProgramStateRef State, SymbolRef Sym) {
281 return State->remove<RefBindings>(Sym);
282}
283
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000284//===----------------------------------------------------------------------===//
Jordy Rose910c4052011-09-02 06:44:22 +0000285// Function/Method behavior summaries.
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000286//===----------------------------------------------------------------------===//
287
288namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000289class RetainSummary {
Jordy Roseef945882012-03-18 01:26:10 +0000290 /// Args - a map of (index, ArgEffect) pairs, where index
Ted Kremenek1bffd742008-05-06 15:44:25 +0000291 /// specifies the argument (starting from 0). This can be sparsely
292 /// populated; arguments with no entry in Args use 'DefaultArgEffect'.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000293 ArgEffects Args;
Mike Stump1eb44332009-09-09 15:08:12 +0000294
Ted Kremenek1bffd742008-05-06 15:44:25 +0000295 /// DefaultArgEffect - The default ArgEffect to apply to arguments that
296 /// do not have an entry in Args.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000297 ArgEffect DefaultArgEffect;
Mike Stump1eb44332009-09-09 15:08:12 +0000298
Ted Kremenek553cf182008-06-25 21:21:56 +0000299 /// Receiver - If this summary applies to an Objective-C message expression,
300 /// this is the effect applied to the state of the receiver.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000301 ArgEffect Receiver;
Mike Stump1eb44332009-09-09 15:08:12 +0000302
Ted Kremenek553cf182008-06-25 21:21:56 +0000303 /// Ret - The effect on the return value. Used to indicate if the
Jordy Rose76c506f2011-08-21 21:58:18 +0000304 /// function/method call returns a new tracked symbol.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000305 RetEffect Ret;
Mike Stump1eb44332009-09-09 15:08:12 +0000306
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000307public:
Ted Kremenekb77449c2009-05-03 05:20:50 +0000308 RetainSummary(ArgEffects A, RetEffect R, ArgEffect defaultEff,
Jordy Rosee62e87b2011-08-20 20:55:40 +0000309 ArgEffect ReceiverEff)
310 : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000311
Ted Kremenek553cf182008-06-25 21:21:56 +0000312 /// getArg - Return the argument effect on the argument specified by
313 /// idx (starting from 0).
Ted Kremenek1ac08d62008-03-11 17:48:22 +0000314 ArgEffect getArg(unsigned idx) const {
Ted Kremenekb77449c2009-05-03 05:20:50 +0000315 if (const ArgEffect *AE = Args.lookup(idx))
316 return *AE;
Mike Stump1eb44332009-09-09 15:08:12 +0000317
Ted Kremenek1bffd742008-05-06 15:44:25 +0000318 return DefaultArgEffect;
Ted Kremenek1ac08d62008-03-11 17:48:22 +0000319 }
Ted Kremenek53c7ea12013-08-14 23:41:49 +0000320
Ted Kremenek11fe1752011-01-27 18:43:03 +0000321 void addArg(ArgEffects::Factory &af, unsigned idx, ArgEffect e) {
322 Args = af.add(Args, idx, e);
323 }
Mike Stump1eb44332009-09-09 15:08:12 +0000324
Ted Kremenek885c27b2009-05-04 05:31:22 +0000325 /// setDefaultArgEffect - Set the default argument effect.
326 void setDefaultArgEffect(ArgEffect E) {
327 DefaultArgEffect = E;
328 }
Mike Stump1eb44332009-09-09 15:08:12 +0000329
Ted Kremenek553cf182008-06-25 21:21:56 +0000330 /// getRetEffect - Returns the effect on the return value of the call.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000331 RetEffect getRetEffect() const { return Ret; }
Mike Stump1eb44332009-09-09 15:08:12 +0000332
Ted Kremenek885c27b2009-05-04 05:31:22 +0000333 /// setRetEffect - Set the effect of the return value of the call.
334 void setRetEffect(RetEffect E) { Ret = E; }
Mike Stump1eb44332009-09-09 15:08:12 +0000335
Ted Kremenek12b94342011-01-27 06:54:14 +0000336
337 /// Sets the effect on the receiver of the message.
338 void setReceiverEffect(ArgEffect e) { Receiver = e; }
339
Ted Kremenek553cf182008-06-25 21:21:56 +0000340 /// getReceiverEffect - Returns the effect on the receiver of the call.
341 /// This is only meaningful if the summary applies to an ObjCMessageExpr*.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000342 ArgEffect getReceiverEffect() const { return Receiver; }
Jordy Rose4df54fe2011-08-23 04:27:15 +0000343
344 /// Test if two retain summaries are identical. Note that merely equivalent
345 /// summaries are not necessarily identical (for example, if an explicit
346 /// argument effect matches the default effect).
347 bool operator==(const RetainSummary &Other) const {
348 return Args == Other.Args && DefaultArgEffect == Other.DefaultArgEffect &&
349 Receiver == Other.Receiver && Ret == Other.Ret;
350 }
Jordy Roseef945882012-03-18 01:26:10 +0000351
352 /// Profile this summary for inclusion in a FoldingSet.
353 void Profile(llvm::FoldingSetNodeID& ID) const {
354 ID.Add(Args);
355 ID.Add(DefaultArgEffect);
356 ID.Add(Receiver);
357 ID.Add(Ret);
358 }
359
360 /// A retain summary is simple if it has no ArgEffects other than the default.
361 bool isSimple() const {
362 return Args.isEmpty();
363 }
Jordan Rose4531b7d2012-07-02 19:27:43 +0000364
365private:
366 ArgEffects getArgEffects() const { return Args; }
367 ArgEffect getDefaultArgEffect() const { return DefaultArgEffect; }
368
369 friend class RetainSummaryManager;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000370};
Ted Kremenek4f22a782008-06-23 23:30:29 +0000371} // end anonymous namespace
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000372
Ted Kremenek553cf182008-06-25 21:21:56 +0000373//===----------------------------------------------------------------------===//
374// Data structures for constructing summaries.
375//===----------------------------------------------------------------------===//
Ted Kremenek53301ba2008-06-24 03:49:48 +0000376
Ted Kremenek553cf182008-06-25 21:21:56 +0000377namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000378class ObjCSummaryKey {
Ted Kremenek553cf182008-06-25 21:21:56 +0000379 IdentifierInfo* II;
380 Selector S;
Mike Stump1eb44332009-09-09 15:08:12 +0000381public:
Ted Kremenek553cf182008-06-25 21:21:56 +0000382 ObjCSummaryKey(IdentifierInfo* ii, Selector s)
383 : II(ii), S(s) {}
384
Ted Kremenek9c378f72011-08-12 23:37:29 +0000385 ObjCSummaryKey(const ObjCInterfaceDecl *d, Selector s)
Ted Kremenek553cf182008-06-25 21:21:56 +0000386 : II(d ? d->getIdentifier() : 0), S(s) {}
Ted Kremenek70b6a832009-05-13 18:16:01 +0000387
Ted Kremenek553cf182008-06-25 21:21:56 +0000388 ObjCSummaryKey(Selector s)
389 : II(0), S(s) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000390
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000391 IdentifierInfo *getIdentifier() const { return II; }
Ted Kremenek553cf182008-06-25 21:21:56 +0000392 Selector getSelector() const { return S; }
393};
Ted Kremenek4f22a782008-06-23 23:30:29 +0000394}
395
396namespace llvm {
Ted Kremenek553cf182008-06-25 21:21:56 +0000397template <> struct DenseMapInfo<ObjCSummaryKey> {
398 static inline ObjCSummaryKey getEmptyKey() {
399 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
400 DenseMapInfo<Selector>::getEmptyKey());
401 }
Mike Stump1eb44332009-09-09 15:08:12 +0000402
Ted Kremenek553cf182008-06-25 21:21:56 +0000403 static inline ObjCSummaryKey getTombstoneKey() {
404 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
Mike Stump1eb44332009-09-09 15:08:12 +0000405 DenseMapInfo<Selector>::getTombstoneKey());
Ted Kremenek553cf182008-06-25 21:21:56 +0000406 }
Mike Stump1eb44332009-09-09 15:08:12 +0000407
Ted Kremenek553cf182008-06-25 21:21:56 +0000408 static unsigned getHashValue(const ObjCSummaryKey &V) {
Benjamin Kramer28b23072012-05-27 13:28:44 +0000409 typedef std::pair<IdentifierInfo*, Selector> PairTy;
410 return DenseMapInfo<PairTy>::getHashValue(PairTy(V.getIdentifier(),
411 V.getSelector()));
Ted Kremenek553cf182008-06-25 21:21:56 +0000412 }
Mike Stump1eb44332009-09-09 15:08:12 +0000413
Ted Kremenek553cf182008-06-25 21:21:56 +0000414 static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
Benjamin Kramer28b23072012-05-27 13:28:44 +0000415 return LHS.getIdentifier() == RHS.getIdentifier() &&
416 LHS.getSelector() == RHS.getSelector();
Ted Kremenek553cf182008-06-25 21:21:56 +0000417 }
Mike Stump1eb44332009-09-09 15:08:12 +0000418
Ted Kremenek553cf182008-06-25 21:21:56 +0000419};
Ted Kremenek4f22a782008-06-23 23:30:29 +0000420} // end llvm namespace
Mike Stump1eb44332009-09-09 15:08:12 +0000421
Ted Kremenek4f22a782008-06-23 23:30:29 +0000422namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000423class ObjCSummaryCache {
Ted Kremenek93edbc52011-10-05 23:54:29 +0000424 typedef llvm::DenseMap<ObjCSummaryKey, const RetainSummary *> MapTy;
Ted Kremenek553cf182008-06-25 21:21:56 +0000425 MapTy M;
426public:
427 ObjCSummaryCache() {}
Mike Stump1eb44332009-09-09 15:08:12 +0000428
Ted Kremenek93edbc52011-10-05 23:54:29 +0000429 const RetainSummary * find(const ObjCInterfaceDecl *D, Selector S) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000430 // Do a lookup with the (D,S) pair. If we find a match return
431 // the iterator.
432 ObjCSummaryKey K(D, S);
433 MapTy::iterator I = M.find(K);
Mike Stump1eb44332009-09-09 15:08:12 +0000434
Jordan Rose4531b7d2012-07-02 19:27:43 +0000435 if (I != M.end())
Ted Kremenek614cc542009-07-21 23:27:57 +0000436 return I->second;
Jordan Rose4531b7d2012-07-02 19:27:43 +0000437 if (!D)
438 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +0000439
Ted Kremenek553cf182008-06-25 21:21:56 +0000440 // Walk the super chain. If we find a hit with a parent, we'll end
441 // up returning that summary. We actually allow that key (null,S), as
442 // we cache summaries for the null ObjCInterfaceDecl* to allow us to
443 // generate initial summaries without having to worry about NSObject
444 // being declared.
445 // FIXME: We may change this at some point.
Ted Kremenek9c378f72011-08-12 23:37:29 +0000446 for (ObjCInterfaceDecl *C=D->getSuperClass() ;; C=C->getSuperClass()) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000447 if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
448 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000449
Ted Kremenek553cf182008-06-25 21:21:56 +0000450 if (!C)
Ted Kremenek614cc542009-07-21 23:27:57 +0000451 return NULL;
Ted Kremenek553cf182008-06-25 21:21:56 +0000452 }
Mike Stump1eb44332009-09-09 15:08:12 +0000453
454 // Cache the summary with original key to make the next lookup faster
Ted Kremenek553cf182008-06-25 21:21:56 +0000455 // and return the iterator.
Ted Kremenek93edbc52011-10-05 23:54:29 +0000456 const RetainSummary *Summ = I->second;
Ted Kremenek614cc542009-07-21 23:27:57 +0000457 M[K] = Summ;
458 return Summ;
Ted Kremenek553cf182008-06-25 21:21:56 +0000459 }
Mike Stump1eb44332009-09-09 15:08:12 +0000460
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000461 const RetainSummary *find(IdentifierInfo* II, Selector S) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000462 // FIXME: Class method lookup. Right now we dont' have a good way
463 // of going between IdentifierInfo* and the class hierarchy.
Ted Kremenek614cc542009-07-21 23:27:57 +0000464 MapTy::iterator I = M.find(ObjCSummaryKey(II, S));
Mike Stump1eb44332009-09-09 15:08:12 +0000465
Ted Kremenek614cc542009-07-21 23:27:57 +0000466 if (I == M.end())
467 I = M.find(ObjCSummaryKey(S));
Mike Stump1eb44332009-09-09 15:08:12 +0000468
Ted Kremenek614cc542009-07-21 23:27:57 +0000469 return I == M.end() ? NULL : I->second;
Ted Kremenek553cf182008-06-25 21:21:56 +0000470 }
Mike Stump1eb44332009-09-09 15:08:12 +0000471
Ted Kremenek93edbc52011-10-05 23:54:29 +0000472 const RetainSummary *& operator[](ObjCSummaryKey K) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000473 return M[K];
474 }
Mike Stump1eb44332009-09-09 15:08:12 +0000475
Ted Kremenek93edbc52011-10-05 23:54:29 +0000476 const RetainSummary *& operator[](Selector S) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000477 return M[ ObjCSummaryKey(S) ];
478 }
Mike Stump1eb44332009-09-09 15:08:12 +0000479};
Ted Kremenek553cf182008-06-25 21:21:56 +0000480} // end anonymous namespace
481
482//===----------------------------------------------------------------------===//
483// Data structures for managing collections of summaries.
484//===----------------------------------------------------------------------===//
485
486namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000487class RetainSummaryManager {
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000488
489 //==-----------------------------------------------------------------==//
490 // Typedefs.
491 //==-----------------------------------------------------------------==//
Mike Stump1eb44332009-09-09 15:08:12 +0000492
Ted Kremenek93edbc52011-10-05 23:54:29 +0000493 typedef llvm::DenseMap<const FunctionDecl*, const RetainSummary *>
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000494 FuncSummariesTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000495
Ted Kremenek4f22a782008-06-23 23:30:29 +0000496 typedef ObjCSummaryCache ObjCMethodSummariesTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000497
Jordy Roseef945882012-03-18 01:26:10 +0000498 typedef llvm::FoldingSetNodeWrapper<RetainSummary> CachedSummaryNode;
499
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000500 //==-----------------------------------------------------------------==//
501 // Data.
502 //==-----------------------------------------------------------------==//
Mike Stump1eb44332009-09-09 15:08:12 +0000503
Ted Kremenek553cf182008-06-25 21:21:56 +0000504 /// Ctx - The ASTContext object for the analyzed ASTs.
Ted Kremenek9c378f72011-08-12 23:37:29 +0000505 ASTContext &Ctx;
Ted Kremenek179064e2008-07-01 17:21:27 +0000506
Ted Kremenek553cf182008-06-25 21:21:56 +0000507 /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
Ted Kremenek377e2302008-04-29 05:33:51 +0000508 const bool GCEnabled;
Mike Stump1eb44332009-09-09 15:08:12 +0000509
John McCallf85e1932011-06-15 23:02:42 +0000510 /// Records whether or not the analyzed code runs in ARC mode.
511 const bool ARCEnabled;
512
Ted Kremenek553cf182008-06-25 21:21:56 +0000513 /// FuncSummaries - A map from FunctionDecls to summaries.
Mike Stump1eb44332009-09-09 15:08:12 +0000514 FuncSummariesTy FuncSummaries;
515
Ted Kremenek553cf182008-06-25 21:21:56 +0000516 /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
517 /// to summaries.
Ted Kremenek1f180c32008-06-23 22:21:20 +0000518 ObjCMethodSummariesTy ObjCClassMethodSummaries;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000519
Ted Kremenek553cf182008-06-25 21:21:56 +0000520 /// ObjCMethodSummaries - A map from selectors to summaries.
Ted Kremenek1f180c32008-06-23 22:21:20 +0000521 ObjCMethodSummariesTy ObjCMethodSummaries;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000522
Ted Kremenek553cf182008-06-25 21:21:56 +0000523 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
524 /// and all other data used by the checker.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000525 llvm::BumpPtrAllocator BPAlloc;
Mike Stump1eb44332009-09-09 15:08:12 +0000526
Ted Kremenekb77449c2009-05-03 05:20:50 +0000527 /// AF - A factory for ArgEffects objects.
Mike Stump1eb44332009-09-09 15:08:12 +0000528 ArgEffects::Factory AF;
529
Ted Kremenek553cf182008-06-25 21:21:56 +0000530 /// ScratchArgs - A holding buffer for construct ArgEffects.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000531 ArgEffects ScratchArgs;
Mike Stump1eb44332009-09-09 15:08:12 +0000532
Ted Kremenekec315332009-05-07 23:40:42 +0000533 /// ObjCAllocRetE - Default return effect for methods returning Objective-C
534 /// objects.
535 RetEffect ObjCAllocRetE;
Ted Kremenek547d4952009-06-05 23:18:01 +0000536
Mike Stump1eb44332009-09-09 15:08:12 +0000537 /// ObjCInitRetE - Default return effect for init methods returning
Ted Kremenekac02f202009-08-20 05:13:36 +0000538 /// Objective-C objects.
Ted Kremenek547d4952009-06-05 23:18:01 +0000539 RetEffect ObjCInitRetE;
Mike Stump1eb44332009-09-09 15:08:12 +0000540
Jordy Roseef945882012-03-18 01:26:10 +0000541 /// SimpleSummaries - Used for uniquing summaries that don't have special
542 /// effects.
543 llvm::FoldingSet<CachedSummaryNode> SimpleSummaries;
Mike Stump1eb44332009-09-09 15:08:12 +0000544
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000545 //==-----------------------------------------------------------------==//
546 // Methods.
547 //==-----------------------------------------------------------------==//
Mike Stump1eb44332009-09-09 15:08:12 +0000548
Ted Kremenek553cf182008-06-25 21:21:56 +0000549 /// getArgEffects - Returns a persistent ArgEffects object based on the
550 /// data in ScratchArgs.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000551 ArgEffects getArgEffects();
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000552
Mike Stump1eb44332009-09-09 15:08:12 +0000553 enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
Ted Kremenek93edbc52011-10-05 23:54:29 +0000554
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000555 const RetainSummary *getUnarySummary(const FunctionType* FT,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000556 UnaryFuncKind func);
Mike Stump1eb44332009-09-09 15:08:12 +0000557
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000558 const RetainSummary *getCFSummaryCreateRule(const FunctionDecl *FD);
559 const RetainSummary *getCFSummaryGetRule(const FunctionDecl *FD);
560 const RetainSummary *getCFCreateGetRuleSummary(const FunctionDecl *FD);
Mike Stump1eb44332009-09-09 15:08:12 +0000561
Jordy Roseef945882012-03-18 01:26:10 +0000562 const RetainSummary *getPersistentSummary(const RetainSummary &OldSumm);
Ted Kremenek706522f2008-10-29 04:07:07 +0000563
Jordy Roseef945882012-03-18 01:26:10 +0000564 const RetainSummary *getPersistentSummary(RetEffect RetEff,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000565 ArgEffect ReceiverEff = DoNothing,
566 ArgEffect DefaultEff = MayEscape) {
Jordy Roseef945882012-03-18 01:26:10 +0000567 RetainSummary Summ(getArgEffects(), RetEff, DefaultEff, ReceiverEff);
568 return getPersistentSummary(Summ);
569 }
570
Ted Kremenekc91fdf62012-05-08 00:12:09 +0000571 const RetainSummary *getDoNothingSummary() {
572 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
573 }
574
Jordy Roseef945882012-03-18 01:26:10 +0000575 const RetainSummary *getDefaultSummary() {
576 return getPersistentSummary(RetEffect::MakeNoRet(),
577 DoNothing, MayEscape);
Ted Kremenek9c32d082008-05-06 00:30:21 +0000578 }
Mike Stump1eb44332009-09-09 15:08:12 +0000579
Ted Kremenek93edbc52011-10-05 23:54:29 +0000580 const RetainSummary *getPersistentStopSummary() {
Jordy Roseef945882012-03-18 01:26:10 +0000581 return getPersistentSummary(RetEffect::MakeNoRet(),
582 StopTracking, StopTracking);
Mike Stump1eb44332009-09-09 15:08:12 +0000583 }
Ted Kremenekb3095252008-05-06 04:20:12 +0000584
Ted Kremenek1f180c32008-06-23 22:21:20 +0000585 void InitializeClassMethodSummaries();
586 void InitializeMethodSummaries();
Ted Kremenek896cd9d2008-10-23 01:56:15 +0000587private:
Ted Kremenek93edbc52011-10-05 23:54:29 +0000588 void addNSObjectClsMethSummary(Selector S, const RetainSummary *Summ) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000589 ObjCClassMethodSummaries[S] = Summ;
590 }
Mike Stump1eb44332009-09-09 15:08:12 +0000591
Ted Kremenek93edbc52011-10-05 23:54:29 +0000592 void addNSObjectMethSummary(Selector S, const RetainSummary *Summ) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000593 ObjCMethodSummaries[S] = Summ;
594 }
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +0000595
Ted Kremeneka9797122012-02-18 21:37:48 +0000596 void addClassMethSummary(const char* Cls, const char* name,
597 const RetainSummary *Summ, bool isNullary = true) {
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +0000598 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
Ted Kremeneka9797122012-02-18 21:37:48 +0000599 Selector S = isNullary ? GetNullarySelector(name, Ctx)
600 : GetUnarySelector(name, Ctx);
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +0000601 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
602 }
Mike Stump1eb44332009-09-09 15:08:12 +0000603
Ted Kremenek6c4becb2009-02-25 02:54:57 +0000604 void addInstMethSummary(const char* Cls, const char* nullaryName,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000605 const RetainSummary *Summ) {
Ted Kremenek6c4becb2009-02-25 02:54:57 +0000606 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
607 Selector S = GetNullarySelector(nullaryName, Ctx);
608 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
609 }
Mike Stump1eb44332009-09-09 15:08:12 +0000610
Ted Kremenekde4d5332009-04-24 17:50:11 +0000611 Selector generateSelector(va_list argp) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000612 SmallVector<IdentifierInfo*, 10> II;
Ted Kremenekde4d5332009-04-24 17:50:11 +0000613
Ted Kremenek9e476de2008-08-12 18:30:56 +0000614 while (const char* s = va_arg(argp, const char*))
615 II.push_back(&Ctx.Idents.get(s));
Ted Kremenekde4d5332009-04-24 17:50:11 +0000616
Mike Stump1eb44332009-09-09 15:08:12 +0000617 return Ctx.Selectors.getSelector(II.size(), &II[0]);
Ted Kremenekde4d5332009-04-24 17:50:11 +0000618 }
Mike Stump1eb44332009-09-09 15:08:12 +0000619
Ted Kremenekde4d5332009-04-24 17:50:11 +0000620 void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy& Summaries,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000621 const RetainSummary * Summ, va_list argp) {
Ted Kremenekde4d5332009-04-24 17:50:11 +0000622 Selector S = generateSelector(argp);
623 Summaries[ObjCSummaryKey(ClsII, S)] = Summ;
Ted Kremenek70a733e2008-07-18 17:24:20 +0000624 }
Mike Stump1eb44332009-09-09 15:08:12 +0000625
Ted Kremenek93edbc52011-10-05 23:54:29 +0000626 void addInstMethSummary(const char* Cls, const RetainSummary * Summ, ...) {
Ted Kremenekaf9dc272008-08-12 18:48:50 +0000627 va_list argp;
628 va_start(argp, Summ);
Ted Kremenekde4d5332009-04-24 17:50:11 +0000629 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Mike Stump1eb44332009-09-09 15:08:12 +0000630 va_end(argp);
Ted Kremenekaf9dc272008-08-12 18:48:50 +0000631 }
Mike Stump1eb44332009-09-09 15:08:12 +0000632
Ted Kremenek93edbc52011-10-05 23:54:29 +0000633 void addClsMethSummary(const char* Cls, const RetainSummary * Summ, ...) {
Ted Kremenekde4d5332009-04-24 17:50:11 +0000634 va_list argp;
635 va_start(argp, Summ);
636 addMethodSummary(&Ctx.Idents.get(Cls),ObjCClassMethodSummaries, Summ, argp);
637 va_end(argp);
638 }
Mike Stump1eb44332009-09-09 15:08:12 +0000639
Ted Kremenek93edbc52011-10-05 23:54:29 +0000640 void addClsMethSummary(IdentifierInfo *II, const RetainSummary * Summ, ...) {
Ted Kremenekde4d5332009-04-24 17:50:11 +0000641 va_list argp;
642 va_start(argp, Summ);
643 addMethodSummary(II, ObjCClassMethodSummaries, Summ, argp);
644 va_end(argp);
645 }
646
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000647public:
Mike Stump1eb44332009-09-09 15:08:12 +0000648
Ted Kremenek9c378f72011-08-12 23:37:29 +0000649 RetainSummaryManager(ASTContext &ctx, bool gcenabled, bool usesARC)
Ted Kremenek179064e2008-07-01 17:21:27 +0000650 : Ctx(ctx),
John McCallf85e1932011-06-15 23:02:42 +0000651 GCEnabled(gcenabled),
652 ARCEnabled(usesARC),
653 AF(BPAlloc), ScratchArgs(AF.getEmptyMap()),
654 ObjCAllocRetE(gcenabled
655 ? RetEffect::MakeGCNotOwned()
656 : (usesARC ? RetEffect::MakeARCNotOwned()
657 : RetEffect::MakeOwned(RetEffect::ObjC, true))),
658 ObjCInitRetE(gcenabled
659 ? RetEffect::MakeGCNotOwned()
660 : (usesARC ? RetEffect::MakeARCNotOwned()
Jordy Roseef945882012-03-18 01:26:10 +0000661 : RetEffect::MakeOwnedWhenTrackedReceiver())) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000662 InitializeClassMethodSummaries();
663 InitializeMethodSummaries();
664 }
Mike Stump1eb44332009-09-09 15:08:12 +0000665
Jordan Rose4531b7d2012-07-02 19:27:43 +0000666 const RetainSummary *getSummary(const CallEvent &Call,
667 ProgramStateRef State = 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000668
Jordan Rose4531b7d2012-07-02 19:27:43 +0000669 const RetainSummary *getFunctionSummary(const FunctionDecl *FD);
670
671 const RetainSummary *getMethodSummary(Selector S, const ObjCInterfaceDecl *ID,
Jordy Rosef3aae582012-03-17 21:13:07 +0000672 const ObjCMethodDecl *MD,
673 QualType RetTy,
674 ObjCMethodSummariesTy &CachedSummaries);
675
Jordan Rosecde8cdb2012-07-02 19:27:56 +0000676 const RetainSummary *getInstanceMethodSummary(const ObjCMethodCall &M,
Jordan Rose4531b7d2012-07-02 19:27:43 +0000677 ProgramStateRef State);
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000678
Jordan Rosecde8cdb2012-07-02 19:27:56 +0000679 const RetainSummary *getClassMethodSummary(const ObjCMethodCall &M) {
Jordan Rose4531b7d2012-07-02 19:27:43 +0000680 assert(!M.isInstanceMessage());
681 const ObjCInterfaceDecl *Class = M.getReceiverInterface();
Mike Stump1eb44332009-09-09 15:08:12 +0000682
Jordan Rose4531b7d2012-07-02 19:27:43 +0000683 return getMethodSummary(M.getSelector(), Class, M.getDecl(),
684 M.getResultType(), ObjCClassMethodSummaries);
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +0000685 }
Ted Kremenek552333c2009-04-29 17:17:48 +0000686
687 /// getMethodSummary - This version of getMethodSummary is used to query
688 /// the summary for the current method being analyzed.
Ted Kremenek93edbc52011-10-05 23:54:29 +0000689 const RetainSummary *getMethodSummary(const ObjCMethodDecl *MD) {
Ted Kremeneka8833552009-04-29 23:03:22 +0000690 const ObjCInterfaceDecl *ID = MD->getClassInterface();
Ted Kremenek70a65762009-04-30 05:41:14 +0000691 Selector S = MD->getSelector();
Ted Kremenek552333c2009-04-29 17:17:48 +0000692 QualType ResultTy = MD->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +0000693
Jordy Rosef3aae582012-03-17 21:13:07 +0000694 ObjCMethodSummariesTy *CachedSummaries;
Ted Kremenek552333c2009-04-29 17:17:48 +0000695 if (MD->isInstanceMethod())
Jordy Rosef3aae582012-03-17 21:13:07 +0000696 CachedSummaries = &ObjCMethodSummaries;
Ted Kremenek552333c2009-04-29 17:17:48 +0000697 else
Jordy Rosef3aae582012-03-17 21:13:07 +0000698 CachedSummaries = &ObjCClassMethodSummaries;
699
Jordan Rose4531b7d2012-07-02 19:27:43 +0000700 return getMethodSummary(S, ID, MD, ResultTy, *CachedSummaries);
Ted Kremenek552333c2009-04-29 17:17:48 +0000701 }
Mike Stump1eb44332009-09-09 15:08:12 +0000702
Jordy Rosef3aae582012-03-17 21:13:07 +0000703 const RetainSummary *getStandardMethodSummary(const ObjCMethodDecl *MD,
Jordan Rose4531b7d2012-07-02 19:27:43 +0000704 Selector S, QualType RetTy);
Ted Kremeneka8833552009-04-29 23:03:22 +0000705
Jordan Rose44405b72013-04-04 22:31:48 +0000706 /// Determine if there is a special return effect for this function or method.
707 Optional<RetEffect> getRetEffectFromAnnotations(QualType RetTy,
708 const Decl *D);
709
Ted Kremenek93edbc52011-10-05 23:54:29 +0000710 void updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenek4dd8fb42009-05-09 02:58:13 +0000711 const ObjCMethodDecl *MD);
712
Ted Kremenek93edbc52011-10-05 23:54:29 +0000713 void updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenek4dd8fb42009-05-09 02:58:13 +0000714 const FunctionDecl *FD);
715
Jordan Rose4531b7d2012-07-02 19:27:43 +0000716 void updateSummaryForCall(const RetainSummary *&Summ,
717 const CallEvent &Call);
718
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000719 bool isGCEnabled() const { return GCEnabled; }
Mike Stump1eb44332009-09-09 15:08:12 +0000720
John McCallf85e1932011-06-15 23:02:42 +0000721 bool isARCEnabled() const { return ARCEnabled; }
722
723 bool isARCorGCEnabled() const { return GCEnabled || ARCEnabled; }
Jordan Rose4531b7d2012-07-02 19:27:43 +0000724
725 RetEffect getObjAllocRetEffect() const { return ObjCAllocRetE; }
726
727 friend class RetainSummaryTemplate;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000728};
Mike Stump1eb44332009-09-09 15:08:12 +0000729
Jordy Rose0fe62f82011-08-24 09:02:37 +0000730// Used to avoid allocating long-term (BPAlloc'd) memory for default retain
731// summaries. If a function or method looks like it has a default summary, but
732// it has annotations, the annotations are added to the stack-based template
733// and then copied into managed memory.
734class RetainSummaryTemplate {
735 RetainSummaryManager &Manager;
Ted Kremenek93edbc52011-10-05 23:54:29 +0000736 const RetainSummary *&RealSummary;
Jordy Rose0fe62f82011-08-24 09:02:37 +0000737 RetainSummary ScratchSummary;
738 bool Accessed;
739public:
Jordan Rose4531b7d2012-07-02 19:27:43 +0000740 RetainSummaryTemplate(const RetainSummary *&real, RetainSummaryManager &mgr)
741 : Manager(mgr), RealSummary(real), ScratchSummary(*real), Accessed(false) {}
Jordy Rose0fe62f82011-08-24 09:02:37 +0000742
743 ~RetainSummaryTemplate() {
Ted Kremenek93edbc52011-10-05 23:54:29 +0000744 if (Accessed)
Jordy Roseef945882012-03-18 01:26:10 +0000745 RealSummary = Manager.getPersistentSummary(ScratchSummary);
Jordy Rose0fe62f82011-08-24 09:02:37 +0000746 }
747
748 RetainSummary &operator*() {
749 Accessed = true;
Ted Kremenek93edbc52011-10-05 23:54:29 +0000750 return ScratchSummary;
Jordy Rose0fe62f82011-08-24 09:02:37 +0000751 }
752
753 RetainSummary *operator->() {
754 Accessed = true;
Ted Kremenek93edbc52011-10-05 23:54:29 +0000755 return &ScratchSummary;
Jordy Rose0fe62f82011-08-24 09:02:37 +0000756 }
757};
758
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000759} // end anonymous namespace
760
761//===----------------------------------------------------------------------===//
762// Implementation of checker data structures.
763//===----------------------------------------------------------------------===//
764
Ted Kremenekb77449c2009-05-03 05:20:50 +0000765ArgEffects RetainSummaryManager::getArgEffects() {
766 ArgEffects AE = ScratchArgs;
Ted Kremenek3baf6722010-11-24 00:54:37 +0000767 ScratchArgs = AF.getEmptyMap();
Ted Kremenekb77449c2009-05-03 05:20:50 +0000768 return AE;
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000769}
770
Ted Kremenek93edbc52011-10-05 23:54:29 +0000771const RetainSummary *
Jordy Roseef945882012-03-18 01:26:10 +0000772RetainSummaryManager::getPersistentSummary(const RetainSummary &OldSumm) {
773 // Unique "simple" summaries -- those without ArgEffects.
774 if (OldSumm.isSimple()) {
775 llvm::FoldingSetNodeID ID;
776 OldSumm.Profile(ID);
777
778 void *Pos;
779 CachedSummaryNode *N = SimpleSummaries.FindNodeOrInsertPos(ID, Pos);
780
781 if (!N) {
782 N = (CachedSummaryNode *) BPAlloc.Allocate<CachedSummaryNode>();
783 new (N) CachedSummaryNode(OldSumm);
784 SimpleSummaries.InsertNode(N, Pos);
785 }
786
787 return &N->getValue();
788 }
789
Ted Kremenek93edbc52011-10-05 23:54:29 +0000790 RetainSummary *Summ = (RetainSummary *) BPAlloc.Allocate<RetainSummary>();
Jordy Roseef945882012-03-18 01:26:10 +0000791 new (Summ) RetainSummary(OldSumm);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000792 return Summ;
793}
794
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000795//===----------------------------------------------------------------------===//
796// Summary creation for functions (largely uses of Core Foundation).
797//===----------------------------------------------------------------------===//
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000798
Ted Kremenek9c378f72011-08-12 23:37:29 +0000799static bool isRetain(const FunctionDecl *FD, StringRef FName) {
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000800 return FName.endswith("Retain");
Ted Kremenek12619382009-01-12 21:45:02 +0000801}
802
Ted Kremenek9c378f72011-08-12 23:37:29 +0000803static bool isRelease(const FunctionDecl *FD, StringRef FName) {
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000804 return FName.endswith("Release");
Ted Kremenek12619382009-01-12 21:45:02 +0000805}
806
Jordy Rose76c506f2011-08-21 21:58:18 +0000807static bool isMakeCollectable(const FunctionDecl *FD, StringRef FName) {
808 // FIXME: Remove FunctionDecl parameter.
809 // FIXME: Is it really okay if MakeCollectable isn't a suffix?
810 return FName.find("MakeCollectable") != StringRef::npos;
811}
812
Anna Zaks554067f2012-08-29 23:23:43 +0000813static ArgEffect getStopTrackingHardEquivalent(ArgEffect E) {
Jordan Rose4531b7d2012-07-02 19:27:43 +0000814 switch (E) {
815 case DoNothing:
816 case Autorelease:
817 case DecRefBridgedTransfered:
818 case IncRef:
819 case IncRefMsg:
820 case MakeCollectable:
821 case MayEscape:
Jordan Rose4531b7d2012-07-02 19:27:43 +0000822 case StopTracking:
Anna Zaks554067f2012-08-29 23:23:43 +0000823 case StopTrackingHard:
824 return StopTrackingHard;
Jordan Rose4531b7d2012-07-02 19:27:43 +0000825 case DecRef:
Anna Zaks554067f2012-08-29 23:23:43 +0000826 case DecRefAndStopTrackingHard:
827 return DecRefAndStopTrackingHard;
Jordan Rose4531b7d2012-07-02 19:27:43 +0000828 case DecRefMsg:
Anna Zaks554067f2012-08-29 23:23:43 +0000829 case DecRefMsgAndStopTrackingHard:
830 return DecRefMsgAndStopTrackingHard;
Jordan Rose4531b7d2012-07-02 19:27:43 +0000831 case Dealloc:
832 return Dealloc;
833 }
834
835 llvm_unreachable("Unknown ArgEffect kind");
836}
837
838void RetainSummaryManager::updateSummaryForCall(const RetainSummary *&S,
839 const CallEvent &Call) {
840 if (Call.hasNonZeroCallbackArg()) {
Anna Zaks554067f2012-08-29 23:23:43 +0000841 ArgEffect RecEffect =
842 getStopTrackingHardEquivalent(S->getReceiverEffect());
843 ArgEffect DefEffect =
844 getStopTrackingHardEquivalent(S->getDefaultArgEffect());
Jordan Rose4531b7d2012-07-02 19:27:43 +0000845
846 ArgEffects CustomArgEffects = S->getArgEffects();
847 for (ArgEffects::iterator I = CustomArgEffects.begin(),
848 E = CustomArgEffects.end();
849 I != E; ++I) {
Anna Zaks554067f2012-08-29 23:23:43 +0000850 ArgEffect Translated = getStopTrackingHardEquivalent(I->second);
Jordan Rose4531b7d2012-07-02 19:27:43 +0000851 if (Translated != DefEffect)
852 ScratchArgs = AF.add(ScratchArgs, I->first, Translated);
853 }
854
Anna Zaks554067f2012-08-29 23:23:43 +0000855 RetEffect RE = RetEffect::MakeNoRetHard();
Jordan Rose4531b7d2012-07-02 19:27:43 +0000856
857 // Special cases where the callback argument CANNOT free the return value.
858 // This can generally only happen if we know that the callback will only be
859 // called when the return value is already being deallocated.
860 if (const FunctionCall *FC = dyn_cast<FunctionCall>(&Call)) {
Jordan Rose4a25f302012-09-01 17:39:13 +0000861 if (IdentifierInfo *Name = FC->getDecl()->getIdentifier()) {
862 // When the CGBitmapContext is deallocated, the callback here will free
863 // the associated data buffer.
Jordan Rosea89f7192012-08-31 18:19:18 +0000864 if (Name->isStr("CGBitmapContextCreateWithData"))
865 RE = S->getRetEffect();
Jordan Rose4a25f302012-09-01 17:39:13 +0000866 }
Jordan Rose4531b7d2012-07-02 19:27:43 +0000867 }
868
869 S = getPersistentSummary(RE, RecEffect, DefEffect);
870 }
Anna Zaks5a901932012-08-24 00:06:12 +0000871
872 // Special case '[super init];' and '[self init];'
873 //
874 // Even though calling '[super init]' without assigning the result to self
875 // and checking if the parent returns 'nil' is a bad pattern, it is common.
876 // Additionally, our Self Init checker already warns about it. To avoid
877 // overwhelming the user with messages from both checkers, we model the case
878 // of '[super init]' in cases when it is not consumed by another expression
879 // as if the call preserves the value of 'self'; essentially, assuming it can
880 // never fail and return 'nil'.
881 // Note, we don't want to just stop tracking the value since we want the
882 // RetainCount checker to report leaks and use-after-free if SelfInit checker
883 // is turned off.
884 if (const ObjCMethodCall *MC = dyn_cast<ObjCMethodCall>(&Call)) {
885 if (MC->getMethodFamily() == OMF_init && MC->isReceiverSelfOrSuper()) {
886
887 // Check if the message is not consumed, we know it will not be used in
888 // an assignment, ex: "self = [super init]".
889 const Expr *ME = MC->getOriginExpr();
890 const LocationContext *LCtx = MC->getLocationContext();
891 ParentMap &PM = LCtx->getAnalysisDeclContext()->getParentMap();
892 if (!PM.isConsumedExpr(ME)) {
893 RetainSummaryTemplate ModifiableSummaryTemplate(S, *this);
894 ModifiableSummaryTemplate->setReceiverEffect(DoNothing);
895 ModifiableSummaryTemplate->setRetEffect(RetEffect::MakeNoRet());
896 }
897 }
898
899 }
Jordan Rose4531b7d2012-07-02 19:27:43 +0000900}
901
Anna Zaks58822c42012-05-04 22:18:39 +0000902const RetainSummary *
Jordan Rose4531b7d2012-07-02 19:27:43 +0000903RetainSummaryManager::getSummary(const CallEvent &Call,
904 ProgramStateRef State) {
905 const RetainSummary *Summ;
906 switch (Call.getKind()) {
907 case CE_Function:
908 Summ = getFunctionSummary(cast<FunctionCall>(Call).getDecl());
909 break;
910 case CE_CXXMember:
Jordan Rosefdaa3382012-07-03 22:55:57 +0000911 case CE_CXXMemberOperator:
Jordan Rose4531b7d2012-07-02 19:27:43 +0000912 case CE_Block:
913 case CE_CXXConstructor:
Jordan Rose8d276d32012-07-10 22:07:47 +0000914 case CE_CXXDestructor:
Jordan Rose70cbf3c2012-07-02 22:21:47 +0000915 case CE_CXXAllocator:
Jordan Rose4531b7d2012-07-02 19:27:43 +0000916 // FIXME: These calls are currently unsupported.
917 return getPersistentStopSummary();
Jordan Rose8919e682012-07-18 21:59:51 +0000918 case CE_ObjCMessage: {
Jordan Rosecde8cdb2012-07-02 19:27:56 +0000919 const ObjCMethodCall &Msg = cast<ObjCMethodCall>(Call);
Jordan Rose4531b7d2012-07-02 19:27:43 +0000920 if (Msg.isInstanceMessage())
921 Summ = getInstanceMethodSummary(Msg, State);
922 else
923 Summ = getClassMethodSummary(Msg);
924 break;
925 }
926 }
927
928 updateSummaryForCall(Summ, Call);
929
930 assert(Summ && "Unknown call type?");
931 return Summ;
932}
933
934const RetainSummary *
935RetainSummaryManager::getFunctionSummary(const FunctionDecl *FD) {
936 // If we don't know what function we're calling, use our default summary.
937 if (!FD)
938 return getDefaultSummary();
939
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000940 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000941 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000942 if (I != FuncSummaries.end())
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000943 return I->second;
944
Ted Kremeneke401a0c2009-05-04 15:34:07 +0000945 // No summary? Generate one.
Ted Kremenek93edbc52011-10-05 23:54:29 +0000946 const RetainSummary *S = 0;
Jordan Rose15d18e12012-08-06 21:28:02 +0000947 bool AllowAnnotations = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000948
Ted Kremenek37d785b2008-07-15 16:50:12 +0000949 do {
Ted Kremenek12619382009-01-12 21:45:02 +0000950 // We generate "stop" summaries for implicitly defined functions.
951 if (FD->isImplicit()) {
952 S = getPersistentStopSummary();
953 break;
Ted Kremenek37d785b2008-07-15 16:50:12 +0000954 }
Mike Stump1eb44332009-09-09 15:08:12 +0000955
John McCall183700f2009-09-21 23:43:11 +0000956 // [PR 3337] Use 'getAs<FunctionType>' to strip away any typedefs on the
Ted Kremenek99890652009-01-16 18:40:33 +0000957 // function's type.
John McCall183700f2009-09-21 23:43:11 +0000958 const FunctionType* FT = FD->getType()->getAs<FunctionType>();
Ted Kremenek48c6d182009-12-16 06:06:43 +0000959 const IdentifierInfo *II = FD->getIdentifier();
960 if (!II)
961 break;
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000962
963 StringRef FName = II->getName();
Mike Stump1eb44332009-09-09 15:08:12 +0000964
Ted Kremenekbf0a4dd2009-03-05 22:11:14 +0000965 // Strip away preceding '_'. Doing this here will effect all the checks
966 // down below.
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000967 FName = FName.substr(FName.find_first_not_of('_'));
Mike Stump1eb44332009-09-09 15:08:12 +0000968
Ted Kremenek12619382009-01-12 21:45:02 +0000969 // Inspect the result type.
970 QualType RetTy = FT->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +0000971
Ted Kremenek12619382009-01-12 21:45:02 +0000972 // FIXME: This should all be refactored into a chain of "summary lookup"
973 // filters.
Ted Kremenek008636a2009-10-14 00:27:24 +0000974 assert(ScratchArgs.isEmpty());
Ted Kremenek39d88b02009-06-15 20:36:07 +0000975
Ted Kremenekbefc6d22012-04-26 04:32:23 +0000976 if (FName == "pthread_create" || FName == "pthread_setspecific") {
977 // Part of: <rdar://problem/7299394> and <rdar://problem/11282706>.
978 // This will be addressed better with IPA.
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000979 S = getPersistentStopSummary();
980 } else if (FName == "NSMakeCollectable") {
981 // Handle: id NSMakeCollectable(CFTypeRef)
982 S = (RetTy->isObjCIdType())
983 ? getUnarySummary(FT, cfmakecollectable)
984 : getPersistentStopSummary();
Jordan Rose15d18e12012-08-06 21:28:02 +0000985 // The headers on OS X 10.8 use cf_consumed/ns_returns_retained,
986 // but we can fully model NSMakeCollectable ourselves.
987 AllowAnnotations = false;
Ted Kremenek061707a2012-09-06 23:47:02 +0000988 } else if (FName == "CFPlugInInstanceCreate") {
989 S = getPersistentSummary(RetEffect::MakeNoRet());
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000990 } else if (FName == "IOBSDNameMatching" ||
991 FName == "IOServiceMatching" ||
992 FName == "IOServiceNameMatching" ||
Ted Kremenek537dd3a2012-05-01 05:28:27 +0000993 FName == "IORegistryEntrySearchCFProperty" ||
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000994 FName == "IORegistryEntryIDMatching" ||
995 FName == "IOOpenFirmwarePathMatching") {
996 // Part of <rdar://problem/6961230>. (IOKit)
997 // This should be addressed using a API table.
998 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
999 DoNothing, DoNothing);
1000 } else if (FName == "IOServiceGetMatchingService" ||
1001 FName == "IOServiceGetMatchingServices") {
1002 // FIXES: <rdar://problem/6326900>
1003 // This should be addressed using a API table. This strcmp is also
1004 // a little gross, but there is no need to super optimize here.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001005 ScratchArgs = AF.add(ScratchArgs, 1, DecRef);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001006 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1007 } else if (FName == "IOServiceAddNotification" ||
1008 FName == "IOServiceAddMatchingNotification") {
1009 // Part of <rdar://problem/6961230>. (IOKit)
1010 // This should be addressed using a API table.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001011 ScratchArgs = AF.add(ScratchArgs, 2, DecRef);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001012 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1013 } else if (FName == "CVPixelBufferCreateWithBytes") {
1014 // FIXES: <rdar://problem/7283567>
1015 // Eventually this can be improved by recognizing that the pixel
1016 // buffer passed to CVPixelBufferCreateWithBytes is released via
1017 // a callback and doing full IPA to make sure this is done correctly.
1018 // FIXME: This function has an out parameter that returns an
1019 // allocated object.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001020 ScratchArgs = AF.add(ScratchArgs, 7, StopTracking);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001021 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1022 } else if (FName == "CGBitmapContextCreateWithData") {
1023 // FIXES: <rdar://problem/7358899>
1024 // Eventually this can be improved by recognizing that 'releaseInfo'
1025 // passed to CGBitmapContextCreateWithData is released via
1026 // a callback and doing full IPA to make sure this is done correctly.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001027 ScratchArgs = AF.add(ScratchArgs, 8, StopTracking);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001028 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1029 DoNothing, DoNothing);
1030 } else if (FName == "CVPixelBufferCreateWithPlanarBytes") {
1031 // FIXES: <rdar://problem/7283567>
1032 // Eventually this can be improved by recognizing that the pixel
1033 // buffer passed to CVPixelBufferCreateWithPlanarBytes is released
1034 // via a callback and doing full IPA to make sure this is done
1035 // correctly.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001036 ScratchArgs = AF.add(ScratchArgs, 12, StopTracking);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001037 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Jordan Rose8a729b42013-05-02 01:51:40 +00001038 } else if (FName == "dispatch_set_context" ||
1039 FName == "xpc_connection_set_context") {
Ted Kremenek06911d42012-03-22 06:29:41 +00001040 // <rdar://problem/11059275> - The analyzer currently doesn't have
1041 // a good way to reason about the finalizer function for libdispatch.
1042 // If we pass a context object that is memory managed, stop tracking it.
Jordan Rose8a729b42013-05-02 01:51:40 +00001043 // <rdar://problem/13783514> - Same problem, but for XPC.
Ted Kremenek06911d42012-03-22 06:29:41 +00001044 // FIXME: this hack should possibly go away once we can handle
Jordan Rose8a729b42013-05-02 01:51:40 +00001045 // libdispatch and XPC finalizers.
Ted Kremenek06911d42012-03-22 06:29:41 +00001046 ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
1047 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenekc91fdf62012-05-08 00:12:09 +00001048 } else if (FName.startswith("NSLog")) {
1049 S = getDoNothingSummary();
Anna Zaks62a5c342012-03-30 05:48:16 +00001050 } else if (FName.startswith("NS") &&
1051 (FName.find("Insert") != StringRef::npos)) {
1052 // Whitelist NSXXInsertXX, for example NSMapInsertIfAbsent, since they can
1053 // be deallocated by NSMapRemove. (radar://11152419)
1054 ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
1055 ScratchArgs = AF.add(ScratchArgs, 2, StopTracking);
1056 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenekb04cb592009-06-11 18:17:24 +00001057 }
Mike Stump1eb44332009-09-09 15:08:12 +00001058
Ted Kremenekb04cb592009-06-11 18:17:24 +00001059 // Did we get a summary?
1060 if (S)
1061 break;
Ted Kremenek61991902009-03-17 22:43:44 +00001062
Jordan Rose5aff3f12013-03-04 23:21:32 +00001063 if (RetTy->isPointerType()) {
Ted Kremenek12619382009-01-12 21:45:02 +00001064 // For CoreFoundation ('CF') types.
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001065 if (cocoa::isRefType(RetTy, "CF", FName)) {
Ted Kremenek12619382009-01-12 21:45:02 +00001066 if (isRetain(FD, FName))
1067 S = getUnarySummary(FT, cfretain);
Jordy Rose76c506f2011-08-21 21:58:18 +00001068 else if (isMakeCollectable(FD, FName))
Ted Kremenek12619382009-01-12 21:45:02 +00001069 S = getUnarySummary(FT, cfmakecollectable);
Mike Stump1eb44332009-09-09 15:08:12 +00001070 else
John McCall7df2ff42011-10-01 00:48:56 +00001071 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek12619382009-01-12 21:45:02 +00001072
1073 break;
1074 }
1075
1076 // For CoreGraphics ('CG') types.
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001077 if (cocoa::isRefType(RetTy, "CG", FName)) {
Ted Kremenek12619382009-01-12 21:45:02 +00001078 if (isRetain(FD, FName))
1079 S = getUnarySummary(FT, cfretain);
1080 else
John McCall7df2ff42011-10-01 00:48:56 +00001081 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek12619382009-01-12 21:45:02 +00001082
1083 break;
1084 }
1085
1086 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001087 if (cocoa::isRefType(RetTy, "DADisk") ||
1088 cocoa::isRefType(RetTy, "DADissenter") ||
1089 cocoa::isRefType(RetTy, "DASessionRef")) {
John McCall7df2ff42011-10-01 00:48:56 +00001090 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek12619382009-01-12 21:45:02 +00001091 break;
1092 }
Mike Stump1eb44332009-09-09 15:08:12 +00001093
Jordan Rose5aff3f12013-03-04 23:21:32 +00001094 if (FD->getAttr<CFAuditedTransferAttr>()) {
1095 S = getCFCreateGetRuleSummary(FD);
1096 break;
1097 }
1098
Ted Kremenek12619382009-01-12 21:45:02 +00001099 break;
1100 }
1101
1102 // Check for release functions, the only kind of functions that we care
1103 // about that don't return a pointer type.
1104 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
Ted Kremeneke7d03122010-02-08 16:45:01 +00001105 // Test for 'CGCF'.
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001106 FName = FName.substr(FName.startswith("CGCF") ? 4 : 2);
Ted Kremeneke7d03122010-02-08 16:45:01 +00001107
Ted Kremenekbf0a4dd2009-03-05 22:11:14 +00001108 if (isRelease(FD, FName))
Ted Kremenek12619382009-01-12 21:45:02 +00001109 S = getUnarySummary(FT, cfrelease);
1110 else {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001111 assert (ScratchArgs.isEmpty());
Ted Kremenek68189282009-01-29 22:45:13 +00001112 // Remaining CoreFoundation and CoreGraphics functions.
1113 // We use to assume that they all strictly followed the ownership idiom
1114 // and that ownership cannot be transferred. While this is technically
1115 // correct, many methods allow a tracked object to escape. For example:
1116 //
Mike Stump1eb44332009-09-09 15:08:12 +00001117 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
Ted Kremenek68189282009-01-29 22:45:13 +00001118 // CFDictionaryAddValue(y, key, x);
Mike Stump1eb44332009-09-09 15:08:12 +00001119 // CFRelease(x);
Ted Kremenek68189282009-01-29 22:45:13 +00001120 // ... it is okay to use 'x' since 'y' has a reference to it
1121 //
1122 // We handle this and similar cases with the follow heuristic. If the
Ted Kremenekc4843812009-08-20 00:57:22 +00001123 // function name contains "InsertValue", "SetValue", "AddValue",
1124 // "AppendValue", or "SetAttribute", then we assume that arguments may
1125 // "escape." This means that something else holds on to the object,
1126 // allowing it be used even after its local retain count drops to 0.
Benjamin Kramere45c1492010-01-11 19:46:28 +00001127 ArgEffect E = (StrInStrNoCase(FName, "InsertValue") != StringRef::npos||
1128 StrInStrNoCase(FName, "AddValue") != StringRef::npos ||
1129 StrInStrNoCase(FName, "SetValue") != StringRef::npos ||
1130 StrInStrNoCase(FName, "AppendValue") != StringRef::npos||
Benjamin Kramerc027e542010-01-11 20:15:06 +00001131 StrInStrNoCase(FName, "SetAttribute") != StringRef::npos)
Ted Kremenek68189282009-01-29 22:45:13 +00001132 ? MayEscape : DoNothing;
Mike Stump1eb44332009-09-09 15:08:12 +00001133
Ted Kremenek68189282009-01-29 22:45:13 +00001134 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek12619382009-01-12 21:45:02 +00001135 }
1136 }
Ted Kremenek37d785b2008-07-15 16:50:12 +00001137 }
1138 while (0);
Mike Stump1eb44332009-09-09 15:08:12 +00001139
Jordan Rose4531b7d2012-07-02 19:27:43 +00001140 // If we got all the way here without any luck, use a default summary.
1141 if (!S)
1142 S = getDefaultSummary();
1143
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001144 // Annotations override defaults.
Jordan Rose15d18e12012-08-06 21:28:02 +00001145 if (AllowAnnotations)
1146 updateSummaryFromAnnotations(S, FD);
Mike Stump1eb44332009-09-09 15:08:12 +00001147
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001148 FuncSummaries[FD] = S;
Mike Stump1eb44332009-09-09 15:08:12 +00001149 return S;
Ted Kremenek2fff37e2008-03-06 00:08:09 +00001150}
1151
Ted Kremenek93edbc52011-10-05 23:54:29 +00001152const RetainSummary *
John McCall7df2ff42011-10-01 00:48:56 +00001153RetainSummaryManager::getCFCreateGetRuleSummary(const FunctionDecl *FD) {
1154 if (coreFoundation::followsCreateRule(FD))
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001155 return getCFSummaryCreateRule(FD);
Mike Stump1eb44332009-09-09 15:08:12 +00001156
Ted Kremenekd368d712011-05-25 06:19:45 +00001157 return getCFSummaryGetRule(FD);
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001158}
1159
Ted Kremenek93edbc52011-10-05 23:54:29 +00001160const RetainSummary *
Ted Kremenek6ad315a2009-02-23 16:51:39 +00001161RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1162 UnaryFuncKind func) {
1163
Ted Kremenek12619382009-01-12 21:45:02 +00001164 // Sanity check that this is *really* a unary function. This can
1165 // happen if people do weird things.
Douglas Gregor72564e72009-02-26 23:50:07 +00001166 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
Ted Kremenek12619382009-01-12 21:45:02 +00001167 if (!FTP || FTP->getNumArgs() != 1)
1168 return getPersistentStopSummary();
Mike Stump1eb44332009-09-09 15:08:12 +00001169
Ted Kremenekb77449c2009-05-03 05:20:50 +00001170 assert (ScratchArgs.isEmpty());
Mike Stump1eb44332009-09-09 15:08:12 +00001171
Jordy Rose76c506f2011-08-21 21:58:18 +00001172 ArgEffect Effect;
Ted Kremenek377e2302008-04-29 05:33:51 +00001173 switch (func) {
Jordy Rose76c506f2011-08-21 21:58:18 +00001174 case cfretain: Effect = IncRef; break;
1175 case cfrelease: Effect = DecRef; break;
1176 case cfmakecollectable: Effect = MakeCollectable; break;
Ted Kremenek940b1d82008-04-10 23:44:06 +00001177 }
Jordy Rose76c506f2011-08-21 21:58:18 +00001178
1179 ScratchArgs = AF.add(ScratchArgs, 0, Effect);
1180 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001181}
1182
Ted Kremenek93edbc52011-10-05 23:54:29 +00001183const RetainSummary *
Ted Kremenek9c378f72011-08-12 23:37:29 +00001184RetainSummaryManager::getCFSummaryCreateRule(const FunctionDecl *FD) {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001185 assert (ScratchArgs.isEmpty());
Mike Stump1eb44332009-09-09 15:08:12 +00001186
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001187 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001188}
1189
Ted Kremenek93edbc52011-10-05 23:54:29 +00001190const RetainSummary *
Ted Kremenek9c378f72011-08-12 23:37:29 +00001191RetainSummaryManager::getCFSummaryGetRule(const FunctionDecl *FD) {
Mike Stump1eb44332009-09-09 15:08:12 +00001192 assert (ScratchArgs.isEmpty());
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001193 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1194 DoNothing, DoNothing);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001195}
1196
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001197//===----------------------------------------------------------------------===//
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001198// Summary creation for Selectors.
1199//===----------------------------------------------------------------------===//
1200
Jordan Rose44405b72013-04-04 22:31:48 +00001201Optional<RetEffect>
1202RetainSummaryManager::getRetEffectFromAnnotations(QualType RetTy,
1203 const Decl *D) {
1204 if (cocoa::isCocoaObjectRef(RetTy)) {
1205 if (D->getAttr<NSReturnsRetainedAttr>())
1206 return ObjCAllocRetE;
1207
1208 if (D->getAttr<NSReturnsNotRetainedAttr>() ||
1209 D->getAttr<NSReturnsAutoreleasedAttr>())
1210 return RetEffect::MakeNotOwned(RetEffect::ObjC);
1211
1212 } else if (!RetTy->isPointerType()) {
1213 return None;
1214 }
1215
1216 if (D->getAttr<CFReturnsRetainedAttr>())
1217 return RetEffect::MakeOwned(RetEffect::CF, true);
1218
1219 if (D->getAttr<CFReturnsNotRetainedAttr>())
1220 return RetEffect::MakeNotOwned(RetEffect::CF);
1221
1222 return None;
1223}
1224
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001225void
Ted Kremenek93edbc52011-10-05 23:54:29 +00001226RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001227 const FunctionDecl *FD) {
1228 if (!FD)
1229 return;
1230
Jordan Rose4531b7d2012-07-02 19:27:43 +00001231 assert(Summ && "Must have a summary to add annotations to.");
1232 RetainSummaryTemplate Template(Summ, *this);
Jordy Rose4df54fe2011-08-23 04:27:15 +00001233
Ted Kremenek11fe1752011-01-27 18:43:03 +00001234 // Effects on the parameters.
1235 unsigned parm_idx = 0;
1236 for (FunctionDecl::param_const_iterator pi = FD->param_begin(),
John McCall98b8f162011-04-06 09:02:12 +00001237 pe = FD->param_end(); pi != pe; ++pi, ++parm_idx) {
Ted Kremenek11fe1752011-01-27 18:43:03 +00001238 const ParmVarDecl *pd = *pi;
Jordan Rose44405b72013-04-04 22:31:48 +00001239 if (pd->getAttr<NSConsumedAttr>())
1240 Template->addArg(AF, parm_idx, DecRefMsg);
1241 else if (pd->getAttr<CFConsumedAttr>())
Jordy Rose0fe62f82011-08-24 09:02:37 +00001242 Template->addArg(AF, parm_idx, DecRef);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001243 }
1244
Ted Kremenekb04cb592009-06-11 18:17:24 +00001245 QualType RetTy = FD->getResultType();
Jordan Rose44405b72013-04-04 22:31:48 +00001246 if (Optional<RetEffect> RetE = getRetEffectFromAnnotations(RetTy, FD))
1247 Template->setRetEffect(*RetE);
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001248}
1249
1250void
Ted Kremenek93edbc52011-10-05 23:54:29 +00001251RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
1252 const ObjCMethodDecl *MD) {
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001253 if (!MD)
1254 return;
1255
Jordan Rose4531b7d2012-07-02 19:27:43 +00001256 assert(Summ && "Must have a valid summary to add annotations to");
1257 RetainSummaryTemplate Template(Summ, *this);
Mike Stump1eb44332009-09-09 15:08:12 +00001258
Ted Kremenek12b94342011-01-27 06:54:14 +00001259 // Effects on the receiver.
Jordan Rose44405b72013-04-04 22:31:48 +00001260 if (MD->getAttr<NSConsumesSelfAttr>())
1261 Template->setReceiverEffect(DecRefMsg);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001262
1263 // Effects on the parameters.
1264 unsigned parm_idx = 0;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00001265 for (ObjCMethodDecl::param_const_iterator
1266 pi=MD->param_begin(), pe=MD->param_end();
Ted Kremenek11fe1752011-01-27 18:43:03 +00001267 pi != pe; ++pi, ++parm_idx) {
1268 const ParmVarDecl *pd = *pi;
Jordan Rose44405b72013-04-04 22:31:48 +00001269 if (pd->getAttr<NSConsumedAttr>())
1270 Template->addArg(AF, parm_idx, DecRefMsg);
1271 else if (pd->getAttr<CFConsumedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001272 Template->addArg(AF, parm_idx, DecRef);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001273 }
Ted Kremenek12b94342011-01-27 06:54:14 +00001274 }
1275
Jordan Rose44405b72013-04-04 22:31:48 +00001276 QualType RetTy = MD->getResultType();
1277 if (Optional<RetEffect> RetE = getRetEffectFromAnnotations(RetTy, MD))
1278 Template->setRetEffect(*RetE);
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001279}
1280
Ted Kremenek93edbc52011-10-05 23:54:29 +00001281const RetainSummary *
Jordy Rosef3aae582012-03-17 21:13:07 +00001282RetainSummaryManager::getStandardMethodSummary(const ObjCMethodDecl *MD,
1283 Selector S, QualType RetTy) {
Jordy Rosee921b1a2012-03-17 19:53:04 +00001284 // Any special effects?
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001285 ArgEffect ReceiverEff = DoNothing;
Jordy Rosee921b1a2012-03-17 19:53:04 +00001286 RetEffect ResultEff = RetEffect::MakeNoRet();
1287
1288 // Check the method family, and apply any default annotations.
1289 switch (MD ? MD->getMethodFamily() : S.getMethodFamily()) {
1290 case OMF_None:
1291 case OMF_performSelector:
1292 // Assume all Objective-C methods follow Cocoa Memory Management rules.
1293 // FIXME: Does the non-threaded performSelector family really belong here?
1294 // The selector could be, say, @selector(copy).
1295 if (cocoa::isCocoaObjectRef(RetTy))
1296 ResultEff = RetEffect::MakeNotOwned(RetEffect::ObjC);
1297 else if (coreFoundation::isCFObjectRef(RetTy)) {
1298 // ObjCMethodDecl currently doesn't consider CF objects as valid return
1299 // values for alloc, new, copy, or mutableCopy, so we have to
1300 // double-check with the selector. This is ugly, but there aren't that
1301 // many Objective-C methods that return CF objects, right?
1302 if (MD) {
1303 switch (S.getMethodFamily()) {
1304 case OMF_alloc:
1305 case OMF_new:
1306 case OMF_copy:
1307 case OMF_mutableCopy:
1308 ResultEff = RetEffect::MakeOwned(RetEffect::CF, true);
1309 break;
1310 default:
1311 ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1312 break;
1313 }
1314 } else {
1315 ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1316 }
1317 }
1318 break;
1319 case OMF_init:
1320 ResultEff = ObjCInitRetE;
1321 ReceiverEff = DecRefMsg;
1322 break;
1323 case OMF_alloc:
1324 case OMF_new:
1325 case OMF_copy:
1326 case OMF_mutableCopy:
1327 if (cocoa::isCocoaObjectRef(RetTy))
1328 ResultEff = ObjCAllocRetE;
1329 else if (coreFoundation::isCFObjectRef(RetTy))
1330 ResultEff = RetEffect::MakeOwned(RetEffect::CF, true);
1331 break;
1332 case OMF_autorelease:
1333 ReceiverEff = Autorelease;
1334 break;
1335 case OMF_retain:
1336 ReceiverEff = IncRefMsg;
1337 break;
1338 case OMF_release:
1339 ReceiverEff = DecRefMsg;
1340 break;
1341 case OMF_dealloc:
1342 ReceiverEff = Dealloc;
1343 break;
1344 case OMF_self:
1345 // -self is handled specially by the ExprEngine to propagate the receiver.
1346 break;
1347 case OMF_retainCount:
1348 case OMF_finalize:
1349 // These methods don't return objects.
1350 break;
1351 }
Mike Stump1eb44332009-09-09 15:08:12 +00001352
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001353 // If one of the arguments in the selector has the keyword 'delegate' we
1354 // should stop tracking the reference count for the receiver. This is
1355 // because the reference count is quite possibly handled by a delegate
1356 // method.
1357 if (S.isKeywordSelector()) {
Jordan Rose50571a92012-06-15 18:19:52 +00001358 for (unsigned i = 0, e = S.getNumArgs(); i != e; ++i) {
1359 StringRef Slot = S.getNameForSlot(i);
1360 if (Slot.substr(Slot.size() - 8).equals_lower("delegate")) {
1361 if (ResultEff == ObjCInitRetE)
Anna Zaks554067f2012-08-29 23:23:43 +00001362 ResultEff = RetEffect::MakeNoRetHard();
Jordan Rose50571a92012-06-15 18:19:52 +00001363 else
Anna Zaks554067f2012-08-29 23:23:43 +00001364 ReceiverEff = StopTrackingHard;
Jordan Rose50571a92012-06-15 18:19:52 +00001365 }
1366 }
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001367 }
Mike Stump1eb44332009-09-09 15:08:12 +00001368
Jordy Rosee921b1a2012-03-17 19:53:04 +00001369 if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing &&
1370 ResultEff.getKind() == RetEffect::NoRet)
Ted Kremenek93edbc52011-10-05 23:54:29 +00001371 return getDefaultSummary();
Mike Stump1eb44332009-09-09 15:08:12 +00001372
Jordy Rosee921b1a2012-03-17 19:53:04 +00001373 return getPersistentSummary(ResultEff, ReceiverEff, MayEscape);
Ted Kremenek250b1fa2009-04-23 23:08:22 +00001374}
1375
Ted Kremenek93edbc52011-10-05 23:54:29 +00001376const RetainSummary *
Jordan Rosecde8cdb2012-07-02 19:27:56 +00001377RetainSummaryManager::getInstanceMethodSummary(const ObjCMethodCall &Msg,
Jordan Rose4531b7d2012-07-02 19:27:43 +00001378 ProgramStateRef State) {
1379 const ObjCInterfaceDecl *ReceiverClass = 0;
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001380
Jordan Rose4531b7d2012-07-02 19:27:43 +00001381 // We do better tracking of the type of the object than the core ExprEngine.
1382 // See if we have its type in our private state.
1383 // FIXME: Eventually replace the use of state->get<RefBindings> with
1384 // a generic API for reasoning about the Objective-C types of symbolic
1385 // objects.
1386 SVal ReceiverV = Msg.getReceiverSVal();
1387 if (SymbolRef Sym = ReceiverV.getAsLocSymbol())
Anna Zaks8d6b43c2012-08-14 00:36:15 +00001388 if (const RefVal *T = getRefBinding(State, Sym))
Douglas Gregor04badcf2010-04-21 00:45:42 +00001389 if (const ObjCObjectPointerType *PT =
Jordan Rose4531b7d2012-07-02 19:27:43 +00001390 T->getType()->getAs<ObjCObjectPointerType>())
1391 ReceiverClass = PT->getInterfaceDecl();
1392
1393 // If we don't know what kind of object this is, fall back to its static type.
1394 if (!ReceiverClass)
1395 ReceiverClass = Msg.getReceiverInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00001396
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001397 // FIXME: The receiver could be a reference to a class, meaning that
1398 // we should use the class method.
Jordan Rose4531b7d2012-07-02 19:27:43 +00001399 // id x = [NSObject class];
1400 // [x performSelector:... withObject:... afterDelay:...];
1401 Selector S = Msg.getSelector();
1402 const ObjCMethodDecl *Method = Msg.getDecl();
1403 if (!Method && ReceiverClass)
1404 Method = ReceiverClass->getInstanceMethod(S);
1405
1406 return getMethodSummary(S, ReceiverClass, Method, Msg.getResultType(),
1407 ObjCMethodSummaries);
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001408}
1409
Ted Kremenek93edbc52011-10-05 23:54:29 +00001410const RetainSummary *
Jordan Rose4531b7d2012-07-02 19:27:43 +00001411RetainSummaryManager::getMethodSummary(Selector S, const ObjCInterfaceDecl *ID,
Jordy Rosef3aae582012-03-17 21:13:07 +00001412 const ObjCMethodDecl *MD, QualType RetTy,
1413 ObjCMethodSummariesTy &CachedSummaries) {
Ted Kremenek1bffd742008-05-06 15:44:25 +00001414
Ted Kremenek8711c032009-04-29 05:04:30 +00001415 // Look up a summary in our summary cache.
Jordan Rose4531b7d2012-07-02 19:27:43 +00001416 const RetainSummary *Summ = CachedSummaries.find(ID, S);
Mike Stump1eb44332009-09-09 15:08:12 +00001417
Ted Kremenek614cc542009-07-21 23:27:57 +00001418 if (!Summ) {
Jordy Rosef3aae582012-03-17 21:13:07 +00001419 Summ = getStandardMethodSummary(MD, S, RetTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001420
Ted Kremenek614cc542009-07-21 23:27:57 +00001421 // Annotations override defaults.
Jordy Rose4df54fe2011-08-23 04:27:15 +00001422 updateSummaryFromAnnotations(Summ, MD);
Mike Stump1eb44332009-09-09 15:08:12 +00001423
Ted Kremenek614cc542009-07-21 23:27:57 +00001424 // Memoize the summary.
Jordan Rose4531b7d2012-07-02 19:27:43 +00001425 CachedSummaries[ObjCSummaryKey(ID, S)] = Summ;
Ted Kremenek614cc542009-07-21 23:27:57 +00001426 }
Mike Stump1eb44332009-09-09 15:08:12 +00001427
Ted Kremeneke87450e2009-04-23 19:11:35 +00001428 return Summ;
Ted Kremenekc8395602008-05-06 21:26:51 +00001429}
1430
Mike Stump1eb44332009-09-09 15:08:12 +00001431void RetainSummaryManager::InitializeClassMethodSummaries() {
Ted Kremenekec315332009-05-07 23:40:42 +00001432 assert(ScratchArgs.isEmpty());
Mike Stump1eb44332009-09-09 15:08:12 +00001433 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek6fe2b7a2009-10-15 22:25:12 +00001434 addClassMethSummary("NSAssertionHandler", "currentHandler",
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001435 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Mike Stump1eb44332009-09-09 15:08:12 +00001436
Ted Kremenek6d348932008-10-21 15:53:15 +00001437 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001438 ScratchArgs = AF.add(ScratchArgs, 0, Autorelease);
Ted Kremenek6fe2b7a2009-10-15 22:25:12 +00001439 addClassMethSummary("NSAutoreleasePool", "addObject",
1440 getPersistentSummary(RetEffect::MakeNoRet(),
1441 DoNothing, Autorelease));
Ted Kremenek9c32d082008-05-06 00:30:21 +00001442}
1443
Ted Kremenek1f180c32008-06-23 22:21:20 +00001444void RetainSummaryManager::InitializeMethodSummaries() {
Mike Stump1eb44332009-09-09 15:08:12 +00001445
1446 assert (ScratchArgs.isEmpty());
1447
Ted Kremenekc8395602008-05-06 21:26:51 +00001448 // Create the "init" selector. It just acts as a pass-through for the
1449 // receiver.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001450 const RetainSummary *InitSumm = getPersistentSummary(ObjCInitRetE, DecRefMsg);
Ted Kremenekac02f202009-08-20 05:13:36 +00001451 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
1452
1453 // awakeAfterUsingCoder: behaves basically like an 'init' method. It
1454 // claims the receiver and returns a retained object.
1455 addNSObjectMethSummary(GetUnarySelector("awakeAfterUsingCoder", Ctx),
1456 InitSumm);
Mike Stump1eb44332009-09-09 15:08:12 +00001457
Ted Kremenekc8395602008-05-06 21:26:51 +00001458 // The next methods are allocators.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001459 const RetainSummary *AllocSumm = getPersistentSummary(ObjCAllocRetE);
1460 const RetainSummary *CFAllocSumm =
Ted Kremeneka834fb42009-08-28 19:52:12 +00001461 getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Mike Stump1eb44332009-09-09 15:08:12 +00001462
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001463 // Create the "retain" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001464 RetEffect NoRet = RetEffect::MakeNoRet();
Ted Kremenek93edbc52011-10-05 23:54:29 +00001465 const RetainSummary *Summ = getPersistentSummary(NoRet, IncRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001466 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001467
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001468 // Create the "release" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001469 Summ = getPersistentSummary(NoRet, DecRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001470 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001471
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001472 // Create the -dealloc summary.
Jordy Rose500abad2011-08-21 19:41:36 +00001473 Summ = getPersistentSummary(NoRet, Dealloc);
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001474 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001475
1476 // Create the "autorelease" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001477 Summ = getPersistentSummary(NoRet, Autorelease);
Ted Kremenek553cf182008-06-25 21:21:56 +00001478 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001479
Mike Stump1eb44332009-09-09 15:08:12 +00001480 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremenek89e202d2009-02-23 02:51:29 +00001481 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1482 // self-own themselves. However, they only do this once they are displayed.
1483 // Thus, we need to track an NSWindow's display status.
1484 // This is tracked in <rdar://problem/6062711>.
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +00001485 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001486 const RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenek78a35a32009-05-12 20:06:54 +00001487 StopTracking,
1488 StopTracking);
Mike Stump1eb44332009-09-09 15:08:12 +00001489
Ted Kremenek99d02692009-04-03 19:02:51 +00001490 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1491
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001492 // For NSPanel (which subclasses NSWindow), allocated objects are not
1493 // self-owned.
Ted Kremenek99d02692009-04-03 19:02:51 +00001494 // FIXME: For now we don't track NSPanels. object for the same reason
1495 // as for NSWindow objects.
1496 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
Mike Stump1eb44332009-09-09 15:08:12 +00001497
Jordan Rosee36d81b2013-01-31 22:06:02 +00001498 // Don't track allocated autorelease pools, as it is okay to prematurely
Ted Kremenekba67f6a2009-05-18 23:14:34 +00001499 // exit a method.
1500 addClassMethSummary("NSAutoreleasePool", "alloc", NoTrackYet);
Ted Kremeneka9797122012-02-18 21:37:48 +00001501 addClassMethSummary("NSAutoreleasePool", "allocWithZone", NoTrackYet, false);
Jordan Rosee36d81b2013-01-31 22:06:02 +00001502 addClassMethSummary("NSAutoreleasePool", "new", NoTrackYet);
Ted Kremenek553cf182008-06-25 21:21:56 +00001503
Ted Kremenek767d6492009-05-20 22:39:57 +00001504 // Create summaries QCRenderer/QCView -createSnapShotImageOfType:
1505 addInstMethSummary("QCRenderer", AllocSumm,
1506 "createSnapshotImageOfType", NULL);
1507 addInstMethSummary("QCView", AllocSumm,
1508 "createSnapshotImageOfType", NULL);
1509
Ted Kremenek211a9c62009-06-15 20:58:58 +00001510 // Create summaries for CIContext, 'createCGImage' and
Ted Kremeneka834fb42009-08-28 19:52:12 +00001511 // 'createCGLayerWithSize'. These objects are CF objects, and are not
1512 // automatically garbage collected.
1513 addInstMethSummary("CIContext", CFAllocSumm,
Ted Kremenek767d6492009-05-20 22:39:57 +00001514 "createCGImage", "fromRect", NULL);
Ted Kremeneka834fb42009-08-28 19:52:12 +00001515 addInstMethSummary("CIContext", CFAllocSumm,
Mike Stump1eb44332009-09-09 15:08:12 +00001516 "createCGImage", "fromRect", "format", "colorSpace", NULL);
Ted Kremeneka834fb42009-08-28 19:52:12 +00001517 addInstMethSummary("CIContext", CFAllocSumm, "createCGLayerWithSize",
Ted Kremenek211a9c62009-06-15 20:58:58 +00001518 "info", NULL);
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001519}
1520
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001521//===----------------------------------------------------------------------===//
Ted Kremenekc887d132009-04-29 18:50:19 +00001522// Error reporting.
1523//===----------------------------------------------------------------------===//
Ted Kremenekc887d132009-04-29 18:50:19 +00001524namespace {
Jordy Roseec9ef852011-08-23 20:55:48 +00001525 typedef llvm::DenseMap<const ExplodedNode *, const RetainSummary *>
1526 SummaryLogTy;
1527
Ted Kremenekc887d132009-04-29 18:50:19 +00001528 //===-------------===//
1529 // Bug Descriptions. //
Mike Stump1eb44332009-09-09 15:08:12 +00001530 //===-------------===//
1531
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001532 class CFRefBug : public BugType {
Ted Kremenekc887d132009-04-29 18:50:19 +00001533 protected:
Jordy Rose35c86952011-08-24 05:47:39 +00001534 CFRefBug(StringRef name)
Ted Kremenek6fd45052012-04-05 20:43:28 +00001535 : BugType(name, categories::MemoryCoreFoundationObjectiveC) {}
Ted Kremenekc887d132009-04-29 18:50:19 +00001536 public:
Mike Stump1eb44332009-09-09 15:08:12 +00001537
Ted Kremenekc887d132009-04-29 18:50:19 +00001538 // FIXME: Eventually remove.
Jordy Rose35c86952011-08-24 05:47:39 +00001539 virtual const char *getDescription() const = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001540
Ted Kremenekc887d132009-04-29 18:50:19 +00001541 virtual bool isLeak() const { return false; }
1542 };
Mike Stump1eb44332009-09-09 15:08:12 +00001543
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001544 class UseAfterRelease : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001545 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001546 UseAfterRelease() : CFRefBug("Use-after-release") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001547
Jordy Rose35c86952011-08-24 05:47:39 +00001548 const char *getDescription() const {
Ted Kremenekc887d132009-04-29 18:50:19 +00001549 return "Reference-counted object is used after it is released";
Mike Stump1eb44332009-09-09 15:08:12 +00001550 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001551 };
Mike Stump1eb44332009-09-09 15:08:12 +00001552
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001553 class BadRelease : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001554 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001555 BadRelease() : CFRefBug("Bad release") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001556
Jordy Rose35c86952011-08-24 05:47:39 +00001557 const char *getDescription() const {
Ted Kremenekbb206fd2009-10-01 17:31:50 +00001558 return "Incorrect decrement of the reference count of an object that is "
1559 "not owned at this point by the caller";
Ted Kremenekc887d132009-04-29 18:50:19 +00001560 }
1561 };
Mike Stump1eb44332009-09-09 15:08:12 +00001562
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001563 class DeallocGC : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001564 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001565 DeallocGC()
1566 : CFRefBug("-dealloc called while using garbage collection") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001567
Ted Kremenekc887d132009-04-29 18:50:19 +00001568 const char *getDescription() const {
Ted Kremenek369de562009-05-09 00:10:05 +00001569 return "-dealloc called while using garbage collection";
Ted Kremenekc887d132009-04-29 18:50:19 +00001570 }
1571 };
Mike Stump1eb44332009-09-09 15:08:12 +00001572
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001573 class DeallocNotOwned : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001574 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001575 DeallocNotOwned()
1576 : CFRefBug("-dealloc sent to non-exclusively owned object") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001577
Ted Kremenekc887d132009-04-29 18:50:19 +00001578 const char *getDescription() const {
1579 return "-dealloc sent to object that may be referenced elsewhere";
1580 }
Mike Stump1eb44332009-09-09 15:08:12 +00001581 };
1582
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001583 class OverAutorelease : public CFRefBug {
Ted Kremenek369de562009-05-09 00:10:05 +00001584 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001585 OverAutorelease()
Jordan Rose2545b1d2013-04-23 01:42:25 +00001586 : CFRefBug("Object autoreleased too many times") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001587
Ted Kremenek369de562009-05-09 00:10:05 +00001588 const char *getDescription() const {
Jordan Rose2545b1d2013-04-23 01:42:25 +00001589 return "Object autoreleased too many times";
Ted Kremenek369de562009-05-09 00:10:05 +00001590 }
1591 };
Mike Stump1eb44332009-09-09 15:08:12 +00001592
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001593 class ReturnedNotOwnedForOwned : public CFRefBug {
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001594 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001595 ReturnedNotOwnedForOwned()
1596 : CFRefBug("Method should return an owned object") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001597
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001598 const char *getDescription() const {
Jordy Rose5b5402b2011-07-15 22:17:54 +00001599 return "Object with a +0 retain count returned to caller where a +1 "
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001600 "(owning) retain count is expected";
1601 }
1602 };
Mike Stump1eb44332009-09-09 15:08:12 +00001603
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001604 class Leak : public CFRefBug {
Benjamin Kramerfacde172012-06-06 17:32:50 +00001605 public:
1606 Leak(StringRef name)
1607 : CFRefBug(name) {
Jordy Rosedb92bb62011-08-25 01:14:38 +00001608 // Leaks should not be reported if they are post-dominated by a sink.
1609 setSuppressOnSink(true);
1610 }
Mike Stump1eb44332009-09-09 15:08:12 +00001611
Jordy Rose35c86952011-08-24 05:47:39 +00001612 const char *getDescription() const { return ""; }
Mike Stump1eb44332009-09-09 15:08:12 +00001613
Ted Kremenekc887d132009-04-29 18:50:19 +00001614 bool isLeak() const { return true; }
1615 };
Mike Stump1eb44332009-09-09 15:08:12 +00001616
Ted Kremenekc887d132009-04-29 18:50:19 +00001617 //===---------===//
1618 // Bug Reports. //
1619 //===---------===//
Mike Stump1eb44332009-09-09 15:08:12 +00001620
Jordy Rose01153492012-03-24 02:45:35 +00001621 class CFRefReportVisitor : public BugReporterVisitorImpl<CFRefReportVisitor> {
Anna Zaks23f395e2011-08-20 01:27:22 +00001622 protected:
Anna Zaksdc757b02011-08-19 23:21:56 +00001623 SymbolRef Sym;
Jordy Roseec9ef852011-08-23 20:55:48 +00001624 const SummaryLogTy &SummaryLog;
Jordy Rose35c86952011-08-24 05:47:39 +00001625 bool GCEnabled;
Anna Zaks23f395e2011-08-20 01:27:22 +00001626
Anna Zaksdc757b02011-08-19 23:21:56 +00001627 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001628 CFRefReportVisitor(SymbolRef sym, bool gcEnabled, const SummaryLogTy &log)
1629 : Sym(sym), SummaryLog(log), GCEnabled(gcEnabled) {}
Anna Zaksdc757b02011-08-19 23:21:56 +00001630
Anna Zaks23f395e2011-08-20 01:27:22 +00001631 virtual void Profile(llvm::FoldingSetNodeID &ID) const {
Anna Zaksdc757b02011-08-19 23:21:56 +00001632 static int x = 0;
1633 ID.AddPointer(&x);
1634 ID.AddPointer(Sym);
1635 }
1636
Anna Zaks23f395e2011-08-20 01:27:22 +00001637 virtual PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
1638 const ExplodedNode *PrevN,
1639 BugReporterContext &BRC,
1640 BugReport &BR);
1641
1642 virtual PathDiagnosticPiece *getEndPath(BugReporterContext &BRC,
1643 const ExplodedNode *N,
1644 BugReport &BR);
1645 };
1646
1647 class CFRefLeakReportVisitor : public CFRefReportVisitor {
1648 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001649 CFRefLeakReportVisitor(SymbolRef sym, bool GCEnabled,
Jordy Roseec9ef852011-08-23 20:55:48 +00001650 const SummaryLogTy &log)
Jordy Rose35c86952011-08-24 05:47:39 +00001651 : CFRefReportVisitor(sym, GCEnabled, log) {}
Anna Zaks23f395e2011-08-20 01:27:22 +00001652
1653 PathDiagnosticPiece *getEndPath(BugReporterContext &BRC,
1654 const ExplodedNode *N,
1655 BugReport &BR);
Jordy Rose01153492012-03-24 02:45:35 +00001656
1657 virtual BugReporterVisitor *clone() const {
1658 // The curiously-recurring template pattern only works for one level of
1659 // subclassing. Rather than make a new template base for
1660 // CFRefReportVisitor, we simply override clone() to do the right thing.
1661 // This could be trouble someday if BugReporterVisitorImpl is ever
1662 // used for something else besides a convenient implementation of clone().
1663 return new CFRefLeakReportVisitor(*this);
1664 }
Anna Zaksdc757b02011-08-19 23:21:56 +00001665 };
1666
Anna Zakse172e8b2011-08-17 23:00:25 +00001667 class CFRefReport : public BugReport {
Jordy Rose20589562011-08-24 22:39:09 +00001668 void addGCModeDescription(const LangOptions &LOpts, bool GCEnabled);
Jordy Rose35c86952011-08-24 05:47:39 +00001669
Ted Kremenekc887d132009-04-29 18:50:19 +00001670 public:
Jordy Rose20589562011-08-24 22:39:09 +00001671 CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1672 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1673 bool registerVisitor = true)
Anna Zaksedf4dae2011-08-22 18:54:07 +00001674 : BugReport(D, D.getDescription(), n) {
Anna Zaks23f395e2011-08-20 01:27:22 +00001675 if (registerVisitor)
Jordy Rose20589562011-08-24 22:39:09 +00001676 addVisitor(new CFRefReportVisitor(sym, GCEnabled, Log));
1677 addGCModeDescription(LOpts, GCEnabled);
Anna Zaksdc757b02011-08-19 23:21:56 +00001678 }
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001679
Jordy Rose20589562011-08-24 22:39:09 +00001680 CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1681 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1682 StringRef endText)
Anna Zaksedf4dae2011-08-22 18:54:07 +00001683 : BugReport(D, D.getDescription(), endText, n) {
Jordy Rose20589562011-08-24 22:39:09 +00001684 addVisitor(new CFRefReportVisitor(sym, GCEnabled, Log));
1685 addGCModeDescription(LOpts, GCEnabled);
Anna Zaksdc757b02011-08-19 23:21:56 +00001686 }
Mike Stump1eb44332009-09-09 15:08:12 +00001687
Anna Zakse172e8b2011-08-17 23:00:25 +00001688 virtual std::pair<ranges_iterator, ranges_iterator> getRanges() {
Anna Zaksedf4dae2011-08-22 18:54:07 +00001689 const CFRefBug& BugTy = static_cast<CFRefBug&>(getBugType());
1690 if (!BugTy.isLeak())
Anna Zakse172e8b2011-08-17 23:00:25 +00001691 return BugReport::getRanges();
Ted Kremenekc887d132009-04-29 18:50:19 +00001692 else
Argyrios Kyrtzidis640ccf02010-12-04 01:12:15 +00001693 return std::make_pair(ranges_iterator(), ranges_iterator());
Ted Kremenekc887d132009-04-29 18:50:19 +00001694 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001695 };
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001696
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001697 class CFRefLeakReport : public CFRefReport {
Ted Kremenekc887d132009-04-29 18:50:19 +00001698 const MemRegion* AllocBinding;
1699 public:
Jordy Rose20589562011-08-24 22:39:09 +00001700 CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1701 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
Ted Kremenek08a838d2013-04-16 21:44:22 +00001702 CheckerContext &Ctx,
1703 bool IncludeAllocationLine);
Mike Stump1eb44332009-09-09 15:08:12 +00001704
Anna Zaks590dd8e2011-09-20 21:38:35 +00001705 PathDiagnosticLocation getLocation(const SourceManager &SM) const {
1706 assert(Location.isValid());
1707 return Location;
1708 }
Mike Stump1eb44332009-09-09 15:08:12 +00001709 };
Ted Kremenekc887d132009-04-29 18:50:19 +00001710} // end anonymous namespace
1711
Jordy Rose20589562011-08-24 22:39:09 +00001712void CFRefReport::addGCModeDescription(const LangOptions &LOpts,
1713 bool GCEnabled) {
Jordy Rosef95b19d2011-08-24 20:38:42 +00001714 const char *GCModeDescription = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001715
Douglas Gregore289d812011-09-13 17:21:33 +00001716 switch (LOpts.getGC()) {
Anna Zaks7f2531c2011-08-22 20:31:28 +00001717 case LangOptions::GCOnly:
Jordy Rose20589562011-08-24 22:39:09 +00001718 assert(GCEnabled);
Jordy Rose35c86952011-08-24 05:47:39 +00001719 GCModeDescription = "Code is compiled to only use garbage collection";
1720 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001721
Anna Zaks7f2531c2011-08-22 20:31:28 +00001722 case LangOptions::NonGC:
Jordy Rose20589562011-08-24 22:39:09 +00001723 assert(!GCEnabled);
Jordy Rose35c86952011-08-24 05:47:39 +00001724 GCModeDescription = "Code is compiled to use reference counts";
1725 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001726
Anna Zaks7f2531c2011-08-22 20:31:28 +00001727 case LangOptions::HybridGC:
Jordy Rose20589562011-08-24 22:39:09 +00001728 if (GCEnabled) {
Jordy Rose35c86952011-08-24 05:47:39 +00001729 GCModeDescription = "Code is compiled to use either garbage collection "
1730 "(GC) or reference counts (non-GC). The bug occurs "
1731 "with GC enabled";
1732 break;
1733 } else {
1734 GCModeDescription = "Code is compiled to use either garbage collection "
1735 "(GC) or reference counts (non-GC). The bug occurs "
1736 "in non-GC mode";
1737 break;
Anna Zaks7f2531c2011-08-22 20:31:28 +00001738 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001739 }
Jordy Rose35c86952011-08-24 05:47:39 +00001740
Jordy Rosef95b19d2011-08-24 20:38:42 +00001741 assert(GCModeDescription && "invalid/unknown GC mode");
Jordy Rose35c86952011-08-24 05:47:39 +00001742 addExtraText(GCModeDescription);
Ted Kremenekc887d132009-04-29 18:50:19 +00001743}
1744
Jordy Rose70fdbc32012-05-12 05:10:43 +00001745static bool isNumericLiteralExpression(const Expr *E) {
1746 // FIXME: This set of cases was copied from SemaExprObjC.
1747 return isa<IntegerLiteral>(E) ||
1748 isa<CharacterLiteral>(E) ||
1749 isa<FloatingLiteral>(E) ||
1750 isa<ObjCBoolLiteralExpr>(E) ||
1751 isa<CXXBoolLiteralExpr>(E);
1752}
1753
Anna Zaksdc757b02011-08-19 23:21:56 +00001754PathDiagnosticPiece *CFRefReportVisitor::VisitNode(const ExplodedNode *N,
1755 const ExplodedNode *PrevN,
1756 BugReporterContext &BRC,
1757 BugReport &BR) {
Jordan Rose28038f32012-07-10 22:07:42 +00001758 // FIXME: We will eventually need to handle non-statement-based events
1759 // (__attribute__((cleanup))).
David Blaikie7a95de62013-02-21 22:23:56 +00001760 if (!N->getLocation().getAs<StmtPoint>())
Ted Kremenek2033a952009-05-13 07:12:33 +00001761 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001762
Ted Kremenek8966bc12009-05-06 21:39:49 +00001763 // Check if the type state has changed.
Ted Kremenek8bef8232012-01-26 21:29:00 +00001764 ProgramStateRef PrevSt = PrevN->getState();
1765 ProgramStateRef CurrSt = N->getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001766 const LocationContext *LCtx = N->getLocationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00001767
Anna Zaks8d6b43c2012-08-14 00:36:15 +00001768 const RefVal* CurrT = getRefBinding(CurrSt, Sym);
Ted Kremenekc887d132009-04-29 18:50:19 +00001769 if (!CurrT) return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001770
Ted Kremenekb65be702009-06-18 01:23:53 +00001771 const RefVal &CurrV = *CurrT;
Anna Zaks8d6b43c2012-08-14 00:36:15 +00001772 const RefVal *PrevT = getRefBinding(PrevSt, Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00001773
Ted Kremenekc887d132009-04-29 18:50:19 +00001774 // Create a string buffer to constain all the useful things we want
1775 // to tell the user.
1776 std::string sbuf;
1777 llvm::raw_string_ostream os(sbuf);
Mike Stump1eb44332009-09-09 15:08:12 +00001778
Ted Kremenekc887d132009-04-29 18:50:19 +00001779 // This is the allocation site since the previous node had no bindings
1780 // for this symbol.
1781 if (!PrevT) {
David Blaikie7a95de62013-02-21 22:23:56 +00001782 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
Mike Stump1eb44332009-09-09 15:08:12 +00001783
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001784 if (isa<ObjCArrayLiteral>(S)) {
1785 os << "NSArray literal is an object with a +0 retain count";
Mike Stump1eb44332009-09-09 15:08:12 +00001786 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001787 else if (isa<ObjCDictionaryLiteral>(S)) {
1788 os << "NSDictionary literal is an object with a +0 retain count";
Ted Kremenekc887d132009-04-29 18:50:19 +00001789 }
Jordy Rose70fdbc32012-05-12 05:10:43 +00001790 else if (const ObjCBoxedExpr *BL = dyn_cast<ObjCBoxedExpr>(S)) {
1791 if (isNumericLiteralExpression(BL->getSubExpr()))
1792 os << "NSNumber literal is an object with a +0 retain count";
1793 else {
1794 const ObjCInterfaceDecl *BoxClass = 0;
1795 if (const ObjCMethodDecl *Method = BL->getBoxingMethod())
1796 BoxClass = Method->getClassInterface();
1797
1798 // We should always be able to find the boxing class interface,
1799 // but consider this future-proofing.
1800 if (BoxClass)
1801 os << *BoxClass << " b";
1802 else
1803 os << "B";
1804
1805 os << "oxed expression produces an object with a +0 retain count";
1806 }
1807 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001808 else {
1809 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
1810 // Get the name of the callee (if it is available).
1811 SVal X = CurrSt->getSValAsScalarOrLoc(CE->getCallee(), LCtx);
1812 if (const FunctionDecl *FD = X.getAsFunctionDecl())
1813 os << "Call to function '" << *FD << '\'';
1814 else
1815 os << "function call";
Ted Kremenekc887d132009-04-29 18:50:19 +00001816 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001817 else {
Jordan Rose8919e682012-07-18 21:59:51 +00001818 assert(isa<ObjCMessageExpr>(S));
Jordan Rosed563d3f2012-07-30 20:22:09 +00001819 CallEventManager &Mgr = CurrSt->getStateManager().getCallEventManager();
1820 CallEventRef<ObjCMethodCall> Call
1821 = Mgr.getObjCMethodCall(cast<ObjCMessageExpr>(S), CurrSt, LCtx);
1822
1823 switch (Call->getMessageKind()) {
Jordan Rose8919e682012-07-18 21:59:51 +00001824 case OCM_Message:
1825 os << "Method";
1826 break;
1827 case OCM_PropertyAccess:
1828 os << "Property";
1829 break;
1830 case OCM_Subscript:
1831 os << "Subscript";
1832 break;
1833 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001834 }
1835
1836 if (CurrV.getObjKind() == RetEffect::CF) {
1837 os << " returns a Core Foundation object with a ";
1838 }
1839 else {
1840 assert (CurrV.getObjKind() == RetEffect::ObjC);
1841 os << " returns an Objective-C object with a ";
1842 }
1843
1844 if (CurrV.isOwned()) {
1845 os << "+1 retain count";
1846
1847 if (GCEnabled) {
1848 assert(CurrV.getObjKind() == RetEffect::CF);
1849 os << ". "
1850 "Core Foundation objects are not automatically garbage collected.";
1851 }
1852 }
1853 else {
1854 assert (CurrV.isNotOwned());
1855 os << "+0 retain count";
1856 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001857 }
Mike Stump1eb44332009-09-09 15:08:12 +00001858
Anna Zaks220ac8c2011-09-15 01:08:34 +00001859 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
1860 N->getLocationContext());
Ted Kremenekc887d132009-04-29 18:50:19 +00001861 return new PathDiagnosticEventPiece(Pos, os.str());
1862 }
Mike Stump1eb44332009-09-09 15:08:12 +00001863
Ted Kremenekc887d132009-04-29 18:50:19 +00001864 // Gather up the effects that were performed on the object at this
1865 // program point
Chris Lattner5f9e2722011-07-23 10:55:15 +00001866 SmallVector<ArgEffect, 2> AEffects;
Mike Stump1eb44332009-09-09 15:08:12 +00001867
Jordy Roseec9ef852011-08-23 20:55:48 +00001868 const ExplodedNode *OrigNode = BRC.getNodeResolver().getOriginalNode(N);
1869 if (const RetainSummary *Summ = SummaryLog.lookup(OrigNode)) {
Ted Kremenekc887d132009-04-29 18:50:19 +00001870 // We only have summaries attached to nodes after evaluating CallExpr and
1871 // ObjCMessageExprs.
David Blaikie7a95de62013-02-21 22:23:56 +00001872 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
Mike Stump1eb44332009-09-09 15:08:12 +00001873
Ted Kremenek5f85e172009-07-22 22:35:28 +00001874 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
Ted Kremenekc887d132009-04-29 18:50:19 +00001875 // Iterate through the parameter expressions and see if the symbol
1876 // was ever passed as an argument.
1877 unsigned i = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001878
Ted Kremenek5f85e172009-07-22 22:35:28 +00001879 for (CallExpr::const_arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
Ted Kremenekc887d132009-04-29 18:50:19 +00001880 AI!=AE; ++AI, ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00001881
Ted Kremenekc887d132009-04-29 18:50:19 +00001882 // Retrieve the value of the argument. Is it the symbol
1883 // we are interested in?
Ted Kremenek5eca4822012-01-06 22:09:28 +00001884 if (CurrSt->getSValAsScalarOrLoc(*AI, LCtx).getAsLocSymbol() != Sym)
Ted Kremenekc887d132009-04-29 18:50:19 +00001885 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001886
Ted Kremenekc887d132009-04-29 18:50:19 +00001887 // We have an argument. Get the effect!
1888 AEffects.push_back(Summ->getArg(i));
1889 }
1890 }
Mike Stump1eb44332009-09-09 15:08:12 +00001891 else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00001892 if (const Expr *receiver = ME->getInstanceReceiver())
Ted Kremenek5eca4822012-01-06 22:09:28 +00001893 if (CurrSt->getSValAsScalarOrLoc(receiver, LCtx)
1894 .getAsLocSymbol() == Sym) {
Ted Kremenekc887d132009-04-29 18:50:19 +00001895 // The symbol we are tracking is the receiver.
1896 AEffects.push_back(Summ->getReceiverEffect());
1897 }
1898 }
1899 }
Mike Stump1eb44332009-09-09 15:08:12 +00001900
Ted Kremenekc887d132009-04-29 18:50:19 +00001901 do {
1902 // Get the previous type state.
1903 RefVal PrevV = *PrevT;
Mike Stump1eb44332009-09-09 15:08:12 +00001904
Ted Kremenekc887d132009-04-29 18:50:19 +00001905 // Specially handle -dealloc.
Benjamin Kramera1da6b22013-08-16 21:57:14 +00001906 if (!GCEnabled && std::find(AEffects.begin(), AEffects.end(), Dealloc) !=
1907 AEffects.end()) {
Ted Kremenekc887d132009-04-29 18:50:19 +00001908 // Determine if the object's reference count was pushed to zero.
1909 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
1910 // We may not have transitioned to 'release' if we hit an error.
1911 // This case is handled elsewhere.
1912 if (CurrV.getKind() == RefVal::Released) {
Ted Kremenekf21332e2009-05-08 20:01:42 +00001913 assert(CurrV.getCombinedCounts() == 0);
Ted Kremenekc887d132009-04-29 18:50:19 +00001914 os << "Object released by directly sending the '-dealloc' message";
1915 break;
1916 }
1917 }
Mike Stump1eb44332009-09-09 15:08:12 +00001918
Ted Kremenekc887d132009-04-29 18:50:19 +00001919 // Specially handle CFMakeCollectable and friends.
Benjamin Kramera1da6b22013-08-16 21:57:14 +00001920 if (std::find(AEffects.begin(), AEffects.end(), MakeCollectable) !=
1921 AEffects.end()) {
Ted Kremenekc887d132009-04-29 18:50:19 +00001922 // Get the name of the function.
David Blaikie7a95de62013-02-21 22:23:56 +00001923 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001924 SVal X =
1925 CurrSt->getSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee(), LCtx);
Ted Kremenek9c378f72011-08-12 23:37:29 +00001926 const FunctionDecl *FD = X.getAsFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001927
Jordy Rose35c86952011-08-24 05:47:39 +00001928 if (GCEnabled) {
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.");
Mike Stump1eb44332009-09-09 15:08:12 +00001931
Benjamin Kramerb8989f22011-10-14 18:45:37 +00001932 os << "In GC mode a call to '" << *FD
Ted Kremenekc887d132009-04-29 18:50:19 +00001933 << "' decrements an object's retain count and registers the "
1934 "object with the garbage collector. ";
Mike Stump1eb44332009-09-09 15:08:12 +00001935
Ted Kremenekc887d132009-04-29 18:50:19 +00001936 if (CurrV.getKind() == RefVal::Released) {
1937 assert(CurrV.getCount() == 0);
1938 os << "Since it now has a 0 retain count the object can be "
1939 "automatically collected by the garbage collector.";
1940 }
1941 else
1942 os << "An object must have a 0 retain count to be garbage collected. "
1943 "After this call its retain count is +" << CurrV.getCount()
1944 << '.';
1945 }
Mike Stump1eb44332009-09-09 15:08:12 +00001946 else
Benjamin Kramerb8989f22011-10-14 18:45:37 +00001947 os << "When GC is not enabled a call to '" << *FD
Ted Kremenekc887d132009-04-29 18:50:19 +00001948 << "' has no effect on its argument.";
Mike Stump1eb44332009-09-09 15:08:12 +00001949
Ted Kremenekc887d132009-04-29 18:50:19 +00001950 // Nothing more to say.
1951 break;
1952 }
Mike Stump1eb44332009-09-09 15:08:12 +00001953
1954 // Determine if the typestate has changed.
Ted Kremenekc887d132009-04-29 18:50:19 +00001955 if (!(PrevV == CurrV))
1956 switch (CurrV.getKind()) {
1957 case RefVal::Owned:
1958 case RefVal::NotOwned:
Mike Stump1eb44332009-09-09 15:08:12 +00001959
Ted Kremenekf21332e2009-05-08 20:01:42 +00001960 if (PrevV.getCount() == CurrV.getCount()) {
1961 // Did an autorelease message get sent?
1962 if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
1963 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001964
Zhongxing Xu264e9372009-05-12 10:10:00 +00001965 assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount());
Jordan Rose2545b1d2013-04-23 01:42:25 +00001966 os << "Object autoreleased";
Ted Kremenekf21332e2009-05-08 20:01:42 +00001967 break;
1968 }
Mike Stump1eb44332009-09-09 15:08:12 +00001969
Ted Kremenekc887d132009-04-29 18:50:19 +00001970 if (PrevV.getCount() > CurrV.getCount())
1971 os << "Reference count decremented.";
1972 else
1973 os << "Reference count incremented.";
Mike Stump1eb44332009-09-09 15:08:12 +00001974
Ted Kremenekc887d132009-04-29 18:50:19 +00001975 if (unsigned Count = CurrV.getCount())
1976 os << " The object now has a +" << Count << " retain count.";
Mike Stump1eb44332009-09-09 15:08:12 +00001977
Ted Kremenekc887d132009-04-29 18:50:19 +00001978 if (PrevV.getKind() == RefVal::Released) {
Jordy Rose35c86952011-08-24 05:47:39 +00001979 assert(GCEnabled && CurrV.getCount() > 0);
Jordy Rose74b7b2b2012-03-17 05:49:15 +00001980 os << " The object is not eligible for garbage collection until "
1981 "the retain count reaches 0 again.";
Ted Kremenekc887d132009-04-29 18:50:19 +00001982 }
Mike Stump1eb44332009-09-09 15:08:12 +00001983
Ted Kremenekc887d132009-04-29 18:50:19 +00001984 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001985
Ted Kremenekc887d132009-04-29 18:50:19 +00001986 case RefVal::Released:
1987 os << "Object released.";
1988 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001989
Ted Kremenekc887d132009-04-29 18:50:19 +00001990 case RefVal::ReturnedOwned:
Jordy Rose74b7b2b2012-03-17 05:49:15 +00001991 // Autoreleases can be applied after marking a node ReturnedOwned.
1992 if (CurrV.getAutoreleaseCount())
1993 return NULL;
1994
1995 os << "Object returned to caller as an owning reference (single "
1996 "retain count transferred to caller)";
Ted Kremenekc887d132009-04-29 18:50:19 +00001997 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001998
Ted Kremenekc887d132009-04-29 18:50:19 +00001999 case RefVal::ReturnedNotOwned:
Ted Kremenekf1365462011-05-26 18:45:44 +00002000 os << "Object returned to caller with a +0 retain count";
Ted Kremenekc887d132009-04-29 18:50:19 +00002001 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002002
Ted Kremenekc887d132009-04-29 18:50:19 +00002003 default:
2004 return NULL;
2005 }
Mike Stump1eb44332009-09-09 15:08:12 +00002006
Ted Kremenekc887d132009-04-29 18:50:19 +00002007 // Emit any remaining diagnostics for the argument effects (if any).
Chris Lattner5f9e2722011-07-23 10:55:15 +00002008 for (SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
Ted Kremenekc887d132009-04-29 18:50:19 +00002009 E=AEffects.end(); I != E; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +00002010
Ted Kremenekc887d132009-04-29 18:50:19 +00002011 // A bunch of things have alternate behavior under GC.
Jordy Rose35c86952011-08-24 05:47:39 +00002012 if (GCEnabled)
Ted Kremenekc887d132009-04-29 18:50:19 +00002013 switch (*I) {
2014 default: break;
2015 case Autorelease:
2016 os << "In GC mode an 'autorelease' has no effect.";
2017 continue;
2018 case IncRefMsg:
2019 os << "In GC mode the 'retain' message has no effect.";
2020 continue;
2021 case DecRefMsg:
2022 os << "In GC mode the 'release' message has no effect.";
2023 continue;
2024 }
2025 }
Mike Stump1eb44332009-09-09 15:08:12 +00002026 } while (0);
2027
Ted Kremenekc887d132009-04-29 18:50:19 +00002028 if (os.str().empty())
2029 return 0; // We have nothing to say!
Ted Kremenek2033a952009-05-13 07:12:33 +00002030
David Blaikie7a95de62013-02-21 22:23:56 +00002031 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
Anna Zaks220ac8c2011-09-15 01:08:34 +00002032 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
2033 N->getLocationContext());
Ted Kremenek9c378f72011-08-12 23:37:29 +00002034 PathDiagnosticPiece *P = new PathDiagnosticEventPiece(Pos, os.str());
Mike Stump1eb44332009-09-09 15:08:12 +00002035
Ted Kremenekc887d132009-04-29 18:50:19 +00002036 // Add the range by scanning the children of the statement for any bindings
2037 // to Sym.
Mike Stump1eb44332009-09-09 15:08:12 +00002038 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
Ted Kremenek5f85e172009-07-22 22:35:28 +00002039 I!=E; ++I)
Ted Kremenek9c378f72011-08-12 23:37:29 +00002040 if (const Expr *Exp = dyn_cast_or_null<Expr>(*I))
Ted Kremenek5eca4822012-01-06 22:09:28 +00002041 if (CurrSt->getSValAsScalarOrLoc(Exp, LCtx).getAsLocSymbol() == Sym) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002042 P->addRange(Exp->getSourceRange());
2043 break;
2044 }
Mike Stump1eb44332009-09-09 15:08:12 +00002045
Ted Kremenekc887d132009-04-29 18:50:19 +00002046 return P;
2047}
2048
Anna Zakse7e01682012-02-28 22:39:22 +00002049// Find the first node in the current function context that referred to the
2050// tracked symbol and the memory location that value was stored to. Note, the
2051// value is only reported if the allocation occurred in the same function as
Anna Zaks7a87e522013-04-10 21:42:06 +00002052// the leak. The function can also return a location context, which should be
2053// treated as interesting.
2054struct AllocationInfo {
2055 const ExplodedNode* N;
Anna Zaksee9043b2013-04-10 22:56:30 +00002056 const MemRegion *R;
Anna Zaks7a87e522013-04-10 21:42:06 +00002057 const LocationContext *InterestingMethodContext;
Anna Zaksee9043b2013-04-10 22:56:30 +00002058 AllocationInfo(const ExplodedNode *InN,
2059 const MemRegion *InR,
Anna Zaks7a87e522013-04-10 21:42:06 +00002060 const LocationContext *InInterestingMethodContext) :
2061 N(InN), R(InR), InterestingMethodContext(InInterestingMethodContext) {}
2062};
2063
2064static AllocationInfo
Ted Kremenek18c66fd2011-08-15 22:09:50 +00002065GetAllocationSite(ProgramStateManager& StateMgr, const ExplodedNode *N,
Ted Kremenekc887d132009-04-29 18:50:19 +00002066 SymbolRef Sym) {
Anna Zaks7a87e522013-04-10 21:42:06 +00002067 const ExplodedNode *AllocationNode = N;
2068 const ExplodedNode *AllocationNodeInCurrentContext = N;
Mike Stump1eb44332009-09-09 15:08:12 +00002069 const MemRegion* FirstBinding = 0;
Anna Zakse7e01682012-02-28 22:39:22 +00002070 const LocationContext *LeakContext = N->getLocationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002071
Anna Zaks7a87e522013-04-10 21:42:06 +00002072 // The location context of the init method called on the leaked object, if
2073 // available.
2074 const LocationContext *InitMethodContext = 0;
2075
Ted Kremenekc887d132009-04-29 18:50:19 +00002076 while (N) {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002077 ProgramStateRef St = N->getState();
Anna Zaks7a87e522013-04-10 21:42:06 +00002078 const LocationContext *NContext = N->getLocationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002079
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002080 if (!getRefBinding(St, Sym))
Ted Kremenekc887d132009-04-29 18:50:19 +00002081 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002082
Anna Zaks27b867e2012-03-21 19:45:01 +00002083 StoreManager::FindUniqueBinding FB(Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002084 StateMgr.iterBindings(St, FB);
Anna Zaks7a87e522013-04-10 21:42:06 +00002085
Anna Zaks27d99dd2013-04-10 21:42:02 +00002086 if (FB) {
2087 const MemRegion *R = FB.getRegion();
Anna Zaks8cf91f72013-04-10 22:56:33 +00002088 const VarRegion *VR = R->getBaseRegion()->getAs<VarRegion>();
Anna Zaks27d99dd2013-04-10 21:42:02 +00002089 // Do not show local variables belonging to a function other than
2090 // where the error is reported.
2091 if (!VR || VR->getStackFrame() == LeakContext->getCurrentStackFrame())
Anna Zaks7a87e522013-04-10 21:42:06 +00002092 FirstBinding = R;
Anna Zaks27d99dd2013-04-10 21:42:02 +00002093 }
Mike Stump1eb44332009-09-09 15:08:12 +00002094
Anna Zaks7a87e522013-04-10 21:42:06 +00002095 // AllocationNode is the last node in which the symbol was tracked.
2096 AllocationNode = N;
2097
2098 // AllocationNodeInCurrentContext, is the last node in the current context
2099 // in which the symbol was tracked.
2100 if (NContext == LeakContext)
2101 AllocationNodeInCurrentContext = N;
2102
Anna Zaksee9043b2013-04-10 22:56:30 +00002103 // Find the last init that was called on the given symbol and store the
2104 // init method's location context.
2105 if (!InitMethodContext)
2106 if (Optional<CallEnter> CEP = N->getLocation().getAs<CallEnter>()) {
2107 const Stmt *CE = CEP->getCallExpr();
Anna Zaks3d8f4622013-04-25 00:41:32 +00002108 if (const ObjCMessageExpr *ME = dyn_cast_or_null<ObjCMessageExpr>(CE)) {
Anna Zaksee9043b2013-04-10 22:56:30 +00002109 const Stmt *RecExpr = ME->getInstanceReceiver();
2110 if (RecExpr) {
2111 SVal RecV = St->getSVal(RecExpr, NContext);
2112 if (ME->getMethodFamily() == OMF_init && RecV.getAsSymbol() == Sym)
2113 InitMethodContext = CEP->getCalleeContext();
2114 }
2115 }
Anna Zaks7a87e522013-04-10 21:42:06 +00002116 }
Anna Zakse7e01682012-02-28 22:39:22 +00002117
Mike Stump1eb44332009-09-09 15:08:12 +00002118 N = N->pred_empty() ? NULL : *(N->pred_begin());
Ted Kremenekc887d132009-04-29 18:50:19 +00002119 }
Mike Stump1eb44332009-09-09 15:08:12 +00002120
Anna Zaks7a87e522013-04-10 21:42:06 +00002121 // If we are reporting a leak of the object that was allocated with alloc,
Anna Zaksee9043b2013-04-10 22:56:30 +00002122 // mark its init method as interesting.
Anna Zaks7a87e522013-04-10 21:42:06 +00002123 const LocationContext *InterestingMethodContext = 0;
2124 if (InitMethodContext) {
2125 const ProgramPoint AllocPP = AllocationNode->getLocation();
2126 if (Optional<StmtPoint> SP = AllocPP.getAs<StmtPoint>())
2127 if (const ObjCMessageExpr *ME = SP->getStmtAs<ObjCMessageExpr>())
2128 if (ME->getMethodFamily() == OMF_alloc)
2129 InterestingMethodContext = InitMethodContext;
2130 }
2131
Anna Zakse7e01682012-02-28 22:39:22 +00002132 // If allocation happened in a function different from the leak node context,
2133 // do not report the binding.
Ted Kremenek5a8fc882012-10-12 22:56:40 +00002134 assert(N && "Could not find allocation node");
Anna Zakse7e01682012-02-28 22:39:22 +00002135 if (N->getLocationContext() != LeakContext) {
2136 FirstBinding = 0;
2137 }
2138
Anna Zaks7a87e522013-04-10 21:42:06 +00002139 return AllocationInfo(AllocationNodeInCurrentContext,
2140 FirstBinding,
2141 InterestingMethodContext);
Ted Kremenekc887d132009-04-29 18:50:19 +00002142}
2143
2144PathDiagnosticPiece*
Anna Zaks23f395e2011-08-20 01:27:22 +00002145CFRefReportVisitor::getEndPath(BugReporterContext &BRC,
2146 const ExplodedNode *EndN,
2147 BugReport &BR) {
Ted Kremenek76aadc32012-03-09 01:13:14 +00002148 BR.markInteresting(Sym);
Anna Zaks23f395e2011-08-20 01:27:22 +00002149 return BugReporterVisitor::getDefaultEndPath(BRC, EndN, BR);
Ted Kremenekc887d132009-04-29 18:50:19 +00002150}
2151
2152PathDiagnosticPiece*
Anna Zaks23f395e2011-08-20 01:27:22 +00002153CFRefLeakReportVisitor::getEndPath(BugReporterContext &BRC,
2154 const ExplodedNode *EndN,
2155 BugReport &BR) {
Mike Stump1eb44332009-09-09 15:08:12 +00002156
Ted Kremenek8966bc12009-05-06 21:39:49 +00002157 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenekc887d132009-04-29 18:50:19 +00002158 // assigned to different variables, etc.
Ted Kremenek76aadc32012-03-09 01:13:14 +00002159 BR.markInteresting(Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002160
Ted Kremenekc887d132009-04-29 18:50:19 +00002161 // We are reporting a leak. Walk up the graph to get to the first node where
2162 // the symbol appeared, and also get the first VarDecl that tracked object
2163 // is stored to.
Anna Zaks7a87e522013-04-10 21:42:06 +00002164 AllocationInfo AllocI =
Ted Kremenekf04dced2009-05-08 23:32:51 +00002165 GetAllocationSite(BRC.getStateManager(), EndN, Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002166
Anna Zaks7a87e522013-04-10 21:42:06 +00002167 const MemRegion* FirstBinding = AllocI.R;
2168 BR.markInteresting(AllocI.InterestingMethodContext);
2169
Anna Zaks4fdf97b2011-09-15 18:56:07 +00002170 SourceManager& SM = BRC.getSourceManager();
Mike Stump1eb44332009-09-09 15:08:12 +00002171
Ted Kremenekc887d132009-04-29 18:50:19 +00002172 // Compute an actual location for the leak. Sometimes a leak doesn't
2173 // occur at an actual statement (e.g., transition between blocks; end
2174 // of function) so we need to walk the graph and compute a real location.
Ted Kremenek9c378f72011-08-12 23:37:29 +00002175 const ExplodedNode *LeakN = EndN;
Anna Zaks4fdf97b2011-09-15 18:56:07 +00002176 PathDiagnosticLocation L = PathDiagnosticLocation::createEndOfPath(LeakN, SM);
Mike Stump1eb44332009-09-09 15:08:12 +00002177
Ted Kremenekc887d132009-04-29 18:50:19 +00002178 std::string sbuf;
2179 llvm::raw_string_ostream os(sbuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002180
Ted Kremenekf1365462011-05-26 18:45:44 +00002181 os << "Object leaked: ";
Mike Stump1eb44332009-09-09 15:08:12 +00002182
Ted Kremenekf1365462011-05-26 18:45:44 +00002183 if (FirstBinding) {
2184 os << "object allocated and stored into '"
2185 << FirstBinding->getString() << '\'';
2186 }
2187 else
2188 os << "allocated object";
Mike Stump1eb44332009-09-09 15:08:12 +00002189
Ted Kremenekc887d132009-04-29 18:50:19 +00002190 // Get the retain count.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002191 const RefVal* RV = getRefBinding(EndN->getState(), Sym);
Ted Kremenek5a8fc882012-10-12 22:56:40 +00002192 assert(RV);
Mike Stump1eb44332009-09-09 15:08:12 +00002193
Ted Kremenekc887d132009-04-29 18:50:19 +00002194 if (RV->getKind() == RefVal::ErrorLeakReturned) {
2195 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
Jordy Rose5b5402b2011-07-15 22:17:54 +00002196 // objects. Only "copy", "alloc", "retain" and "new" transfer ownership
Ted Kremenekc887d132009-04-29 18:50:19 +00002197 // to the caller for NS objects.
Ted Kremenekd368d712011-05-25 06:19:45 +00002198 const Decl *D = &EndN->getCodeDecl();
Ted Kremenekec9f36e2012-09-06 23:03:07 +00002199
2200 os << (isa<ObjCMethodDecl>(D) ? " is returned from a method "
2201 : " is returned from a function ");
2202
2203 if (D->getAttr<CFReturnsNotRetainedAttr>())
2204 os << "that is annotated as CF_RETURNS_NOT_RETAINED";
2205 else if (D->getAttr<NSReturnsNotRetainedAttr>())
2206 os << "that is annotated as NS_RETURNS_NOT_RETAINED";
Ted Kremenekd368d712011-05-25 06:19:45 +00002207 else {
Ted Kremenekec9f36e2012-09-06 23:03:07 +00002208 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2209 os << "whose name ('" << MD->getSelector().getAsString()
2210 << "') does not start with 'copy', 'mutableCopy', 'alloc' or 'new'."
2211 " This violates the naming convention rules"
2212 " given in the Memory Management Guide for Cocoa";
2213 }
2214 else {
2215 const FunctionDecl *FD = cast<FunctionDecl>(D);
2216 os << "whose name ('" << *FD
2217 << "') does not contain 'Copy' or 'Create'. This violates the naming"
2218 " convention rules given in the Memory Management Guide for Core"
2219 " Foundation";
2220 }
2221 }
Ted Kremenekc887d132009-04-29 18:50:19 +00002222 }
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002223 else if (RV->getKind() == RefVal::ErrorGCLeakReturned) {
David Blaikiee1300142013-02-21 22:37:44 +00002224 const ObjCMethodDecl &MD = cast<ObjCMethodDecl>(EndN->getCodeDecl());
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002225 os << " and returned from method '" << MD.getSelector().getAsString()
Ted Kremenek82f2be52009-05-10 16:52:15 +00002226 << "' is potentially leaked when using garbage collection. Callers "
2227 "of this method do not expect a returned object with a +1 retain "
2228 "count since they expect the object to be managed by the garbage "
2229 "collector";
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002230 }
Ted Kremenekc887d132009-04-29 18:50:19 +00002231 else
Ted Kremenekabf517c2010-10-15 22:50:23 +00002232 os << " is not referenced later in this execution path and has a retain "
Ted Kremenekf1365462011-05-26 18:45:44 +00002233 "count of +" << RV->getCount();
Mike Stump1eb44332009-09-09 15:08:12 +00002234
Ted Kremenekc887d132009-04-29 18:50:19 +00002235 return new PathDiagnosticEventPiece(L, os.str());
2236}
2237
Jordy Rose20589562011-08-24 22:39:09 +00002238CFRefLeakReport::CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts,
2239 bool GCEnabled, const SummaryLogTy &Log,
2240 ExplodedNode *n, SymbolRef sym,
Ted Kremenek08a838d2013-04-16 21:44:22 +00002241 CheckerContext &Ctx,
2242 bool IncludeAllocationLine)
2243 : CFRefReport(D, LOpts, GCEnabled, Log, n, sym, false) {
Mike Stump1eb44332009-09-09 15:08:12 +00002244
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00002245 // Most bug reports are cached at the location where they occurred.
Ted Kremenekc887d132009-04-29 18:50:19 +00002246 // With leaks, we want to unique them by the location where they were
2247 // allocated, and only report a single path. To do this, we need to find
2248 // the allocation site of a piece of tracked memory, which we do via a
2249 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2250 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2251 // that all ancestor nodes that represent the allocation site have the
2252 // same SourceLocation.
Ted Kremenek9c378f72011-08-12 23:37:29 +00002253 const ExplodedNode *AllocNode = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002254
Anna Zaks6a93bd52011-10-25 19:57:11 +00002255 const SourceManager& SMgr = Ctx.getSourceManager();
Anna Zaks590dd8e2011-09-20 21:38:35 +00002256
Anna Zaks7a87e522013-04-10 21:42:06 +00002257 AllocationInfo AllocI =
Anna Zaks6a93bd52011-10-25 19:57:11 +00002258 GetAllocationSite(Ctx.getStateManager(), getErrorNode(), sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002259
Anna Zaks7a87e522013-04-10 21:42:06 +00002260 AllocNode = AllocI.N;
2261 AllocBinding = AllocI.R;
2262 markInteresting(AllocI.InterestingMethodContext);
2263
Ted Kremenekc887d132009-04-29 18:50:19 +00002264 // Get the SourceLocation for the allocation site.
Jordan Rose852aa0d2012-07-10 22:07:52 +00002265 // FIXME: This will crash the analyzer if an allocation comes from an
2266 // implicit call. (Currently there are no such allocations in Cocoa, though.)
2267 const Stmt *AllocStmt;
Ted Kremenekc887d132009-04-29 18:50:19 +00002268 ProgramPoint P = AllocNode->getLocation();
David Blaikie7a95de62013-02-21 22:23:56 +00002269 if (Optional<CallExitEnd> Exit = P.getAs<CallExitEnd>())
Jordan Rose852aa0d2012-07-10 22:07:52 +00002270 AllocStmt = Exit->getCalleeContext()->getCallSite();
2271 else
David Blaikie7a95de62013-02-21 22:23:56 +00002272 AllocStmt = P.castAs<PostStmt>().getStmt();
Jordan Rose852aa0d2012-07-10 22:07:52 +00002273 assert(AllocStmt && "All allocations must come from explicit calls");
Anna Zakse3a813a2013-04-23 23:57:50 +00002274
2275 PathDiagnosticLocation AllocLocation =
2276 PathDiagnosticLocation::createBegin(AllocStmt, SMgr,
2277 AllocNode->getLocationContext());
2278 Location = AllocLocation;
2279
2280 // Set uniqieing info, which will be used for unique the bug reports. The
2281 // leaks should be uniqued on the allocation site.
2282 UniqueingLocation = AllocLocation;
2283 UniqueingDecl = AllocNode->getLocationContext()->getDecl();
2284
Ted Kremenekc887d132009-04-29 18:50:19 +00002285 // Fill in the description of the bug.
2286 Description.clear();
2287 llvm::raw_string_ostream os(Description);
Ted Kremenekdd924e22009-05-02 19:05:19 +00002288 os << "Potential leak ";
Jordy Rose20589562011-08-24 22:39:09 +00002289 if (GCEnabled)
Ted Kremenekdd924e22009-05-02 19:05:19 +00002290 os << "(when using garbage collection) ";
Anna Zaks212000e2012-02-28 21:49:08 +00002291 os << "of an object";
Mike Stump1eb44332009-09-09 15:08:12 +00002292
Ted Kremenek08a838d2013-04-16 21:44:22 +00002293 if (AllocBinding) {
Anna Zaks212000e2012-02-28 21:49:08 +00002294 os << " stored into '" << AllocBinding->getString() << '\'';
Ted Kremenek08a838d2013-04-16 21:44:22 +00002295 if (IncludeAllocationLine) {
2296 FullSourceLoc SL(AllocStmt->getLocStart(), Ctx.getSourceManager());
2297 os << " (allocated on line " << SL.getSpellingLineNumber() << ")";
2298 }
2299 }
Anna Zaksdc757b02011-08-19 23:21:56 +00002300
Jordy Rose20589562011-08-24 22:39:09 +00002301 addVisitor(new CFRefLeakReportVisitor(sym, GCEnabled, Log));
Ted Kremenekc887d132009-04-29 18:50:19 +00002302}
2303
2304//===----------------------------------------------------------------------===//
2305// Main checker logic.
2306//===----------------------------------------------------------------------===//
2307
Ted Kremenekd593eb92009-11-25 22:17:44 +00002308namespace {
Jordy Rose910c4052011-09-02 06:44:22 +00002309class RetainCountChecker
Jordy Rose9c083b72011-08-24 18:56:32 +00002310 : public Checker< check::Bind,
Jordy Rose38f17d62011-08-23 19:01:07 +00002311 check::DeadSymbols,
Jordy Rose9c083b72011-08-24 18:56:32 +00002312 check::EndAnalysis,
Anna Zaks344c77a2013-01-03 00:25:29 +00002313 check::EndFunction,
Jordy Rose67044292011-08-17 21:27:39 +00002314 check::PostStmt<BlockExpr>,
John McCallf85e1932011-06-15 23:02:42 +00002315 check::PostStmt<CastExpr>,
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002316 check::PostStmt<ObjCArrayLiteral>,
2317 check::PostStmt<ObjCDictionaryLiteral>,
Jordy Rose70fdbc32012-05-12 05:10:43 +00002318 check::PostStmt<ObjCBoxedExpr>,
Jordan Rosefe6a0112012-07-02 19:28:21 +00002319 check::PostCall,
Jordy Rosef53e8c72011-08-23 19:43:16 +00002320 check::PreStmt<ReturnStmt>,
Jordy Rose67044292011-08-17 21:27:39 +00002321 check::RegionChanges,
Jordy Rose76c506f2011-08-21 21:58:18 +00002322 eval::Assume,
2323 eval::Call > {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002324 mutable OwningPtr<CFRefBug> useAfterRelease, releaseNotOwned;
2325 mutable OwningPtr<CFRefBug> deallocGC, deallocNotOwned;
2326 mutable OwningPtr<CFRefBug> overAutorelease, returnNotOwnedForOwned;
2327 mutable OwningPtr<CFRefBug> leakWithinFunction, leakAtReturn;
2328 mutable OwningPtr<CFRefBug> leakWithinFunctionGC, leakAtReturnGC;
Jordy Rose38f17d62011-08-23 19:01:07 +00002329
2330 typedef llvm::DenseMap<SymbolRef, const SimpleProgramPointTag *> SymbolTagMap;
2331
2332 // This map is only used to ensure proper deletion of any allocated tags.
2333 mutable SymbolTagMap DeadSymbolTags;
2334
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002335 mutable OwningPtr<RetainSummaryManager> Summaries;
2336 mutable OwningPtr<RetainSummaryManager> SummariesGC;
Jordy Rose9c083b72011-08-24 18:56:32 +00002337 mutable SummaryLogTy SummaryLog;
2338 mutable bool ShouldResetSummaryLog;
2339
Ted Kremenek08a838d2013-04-16 21:44:22 +00002340 /// Optional setting to indicate if leak reports should include
2341 /// the allocation line.
2342 mutable bool IncludeAllocationLine;
2343
Jordy Rose2f9a66d2011-08-20 21:17:59 +00002344public:
Ted Kremenek08a838d2013-04-16 21:44:22 +00002345 RetainCountChecker(AnalyzerOptions &AO)
2346 : ShouldResetSummaryLog(false),
2347 IncludeAllocationLine(shouldIncludeAllocationSiteInLeakDiagnostics(AO)) {}
Jordy Rose38f17d62011-08-23 19:01:07 +00002348
Jordy Rose910c4052011-09-02 06:44:22 +00002349 virtual ~RetainCountChecker() {
Jordy Rose38f17d62011-08-23 19:01:07 +00002350 DeleteContainerSeconds(DeadSymbolTags);
2351 }
2352
Jordy Rose9c083b72011-08-24 18:56:32 +00002353 void checkEndAnalysis(ExplodedGraph &G, BugReporter &BR,
2354 ExprEngine &Eng) const {
2355 // FIXME: This is a hack to make sure the summary log gets cleared between
2356 // analyses of different code bodies.
2357 //
2358 // Why is this necessary? Because a checker's lifetime is tied to a
2359 // translation unit, but an ExplodedGraph's lifetime is just a code body.
2360 // Once in a blue moon, a new ExplodedNode will have the same address as an
2361 // old one with an associated summary, and the bug report visitor gets very
2362 // confused. (To make things worse, the summary lifetime is currently also
2363 // tied to a code body, so we get a crash instead of incorrect results.)
Jordy Rose1ab51c72011-08-24 09:27:24 +00002364 //
2365 // Why is this a bad solution? Because if the lifetime of the ExplodedGraph
2366 // changes, things will start going wrong again. Really the lifetime of this
2367 // log needs to be tied to either the specific nodes in it or the entire
2368 // ExplodedGraph, not to a specific part of the code being analyzed.
2369 //
Jordy Rose9c083b72011-08-24 18:56:32 +00002370 // (Also, having stateful local data means that the same checker can't be
2371 // used from multiple threads, but a lot of checkers have incorrect
2372 // assumptions about that anyway. So that wasn't a priority at the time of
2373 // this fix.)
Jordy Rose1ab51c72011-08-24 09:27:24 +00002374 //
Jordy Rose9c083b72011-08-24 18:56:32 +00002375 // This happens at the end of analysis, but bug reports are emitted /after/
2376 // this point. So we can't just clear the summary log now. Instead, we mark
2377 // that the next time we access the summary log, it should be cleared.
2378
2379 // If we never reset the summary log during /this/ code body analysis,
2380 // there were no new summaries. There might still have been summaries from
2381 // the /last/ analysis, so clear them out to make sure the bug report
2382 // visitors don't get confused.
2383 if (ShouldResetSummaryLog)
2384 SummaryLog.clear();
2385
2386 ShouldResetSummaryLog = !SummaryLog.empty();
Jordy Rose1ab51c72011-08-24 09:27:24 +00002387 }
2388
Jordy Rose17a38e22011-09-02 05:55:19 +00002389 CFRefBug *getLeakWithinFunctionBug(const LangOptions &LOpts,
2390 bool GCEnabled) const {
2391 if (GCEnabled) {
Jordy Rosedb92bb62011-08-25 01:14:38 +00002392 if (!leakWithinFunctionGC)
Benjamin Kramerfacde172012-06-06 17:32:50 +00002393 leakWithinFunctionGC.reset(new Leak("Leak of object when using "
2394 "garbage collection"));
Jordy Rose17a38e22011-09-02 05:55:19 +00002395 return leakWithinFunctionGC.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002396 } else {
2397 if (!leakWithinFunction) {
Douglas Gregore289d812011-09-13 17:21:33 +00002398 if (LOpts.getGC() == LangOptions::HybridGC) {
Benjamin Kramerfacde172012-06-06 17:32:50 +00002399 leakWithinFunction.reset(new Leak("Leak of object when not using "
2400 "garbage collection (GC) in "
2401 "dual GC/non-GC code"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002402 } else {
Benjamin Kramerfacde172012-06-06 17:32:50 +00002403 leakWithinFunction.reset(new Leak("Leak"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002404 }
2405 }
Jordy Rose17a38e22011-09-02 05:55:19 +00002406 return leakWithinFunction.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002407 }
2408 }
2409
Jordy Rose17a38e22011-09-02 05:55:19 +00002410 CFRefBug *getLeakAtReturnBug(const LangOptions &LOpts, bool GCEnabled) const {
2411 if (GCEnabled) {
Jordy Rosedb92bb62011-08-25 01:14:38 +00002412 if (!leakAtReturnGC)
Benjamin Kramerfacde172012-06-06 17:32:50 +00002413 leakAtReturnGC.reset(new Leak("Leak of returned object when using "
2414 "garbage collection"));
Jordy Rose17a38e22011-09-02 05:55:19 +00002415 return leakAtReturnGC.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002416 } else {
2417 if (!leakAtReturn) {
Douglas Gregore289d812011-09-13 17:21:33 +00002418 if (LOpts.getGC() == LangOptions::HybridGC) {
Benjamin Kramerfacde172012-06-06 17:32:50 +00002419 leakAtReturn.reset(new Leak("Leak of returned object when not using "
2420 "garbage collection (GC) in dual "
2421 "GC/non-GC code"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002422 } else {
Benjamin Kramerfacde172012-06-06 17:32:50 +00002423 leakAtReturn.reset(new Leak("Leak of returned object"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002424 }
2425 }
Jordy Rose17a38e22011-09-02 05:55:19 +00002426 return leakAtReturn.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002427 }
2428 }
2429
Jordy Rose17a38e22011-09-02 05:55:19 +00002430 RetainSummaryManager &getSummaryManager(ASTContext &Ctx,
2431 bool GCEnabled) const {
2432 // FIXME: We don't support ARC being turned on and off during one analysis.
2433 // (nor, for that matter, do we support changing ASTContexts)
David Blaikie4e4d0842012-03-11 07:00:24 +00002434 bool ARCEnabled = (bool)Ctx.getLangOpts().ObjCAutoRefCount;
Jordy Rose17a38e22011-09-02 05:55:19 +00002435 if (GCEnabled) {
2436 if (!SummariesGC)
Jordy Roseb6cfc092011-08-25 00:10:37 +00002437 SummariesGC.reset(new RetainSummaryManager(Ctx, true, ARCEnabled));
Jordy Rose17a38e22011-09-02 05:55:19 +00002438 else
2439 assert(SummariesGC->isARCEnabled() == ARCEnabled);
Jordy Roseb6cfc092011-08-25 00:10:37 +00002440 return *SummariesGC;
2441 } else {
Jordy Rose17a38e22011-09-02 05:55:19 +00002442 if (!Summaries)
Jordy Roseb6cfc092011-08-25 00:10:37 +00002443 Summaries.reset(new RetainSummaryManager(Ctx, false, ARCEnabled));
Jordy Rose17a38e22011-09-02 05:55:19 +00002444 else
2445 assert(Summaries->isARCEnabled() == ARCEnabled);
Jordy Roseb6cfc092011-08-25 00:10:37 +00002446 return *Summaries;
2447 }
2448 }
2449
Jordy Rose17a38e22011-09-02 05:55:19 +00002450 RetainSummaryManager &getSummaryManager(CheckerContext &C) const {
2451 return getSummaryManager(C.getASTContext(), C.isObjCGCEnabled());
2452 }
2453
Ted Kremenek8bef8232012-01-26 21:29:00 +00002454 void printState(raw_ostream &Out, ProgramStateRef State,
Jordy Rosedbd658e2011-08-28 19:11:56 +00002455 const char *NL, const char *Sep) const;
2456
Anna Zaks390909c2011-10-06 00:43:15 +00002457 void checkBind(SVal loc, SVal val, const Stmt *S, CheckerContext &C) const;
Jordy Roseab027fd2011-08-20 21:16:58 +00002458 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
2459 void checkPostStmt(const CastExpr *CE, CheckerContext &C) const;
John McCallf85e1932011-06-15 23:02:42 +00002460
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002461 void checkPostStmt(const ObjCArrayLiteral *AL, CheckerContext &C) const;
2462 void checkPostStmt(const ObjCDictionaryLiteral *DL, CheckerContext &C) const;
Jordy Rose70fdbc32012-05-12 05:10:43 +00002463 void checkPostStmt(const ObjCBoxedExpr *BE, CheckerContext &C) const;
2464
Jordan Rosefe6a0112012-07-02 19:28:21 +00002465 void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002466
Jordan Rose4531b7d2012-07-02 19:27:43 +00002467 void checkSummary(const RetainSummary &Summ, const CallEvent &Call,
Jordy Rosee38dd952011-08-28 05:16:28 +00002468 CheckerContext &C) const;
Jordy Rose294396b2011-08-22 23:48:23 +00002469
Anna Zaks554067f2012-08-29 23:23:43 +00002470 void processSummaryOfInlined(const RetainSummary &Summ,
2471 const CallEvent &Call,
2472 CheckerContext &C) const;
2473
Jordy Rose76c506f2011-08-21 21:58:18 +00002474 bool evalCall(const CallExpr *CE, CheckerContext &C) const;
2475
Ted Kremenek8bef8232012-01-26 21:29:00 +00002476 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Jordy Roseab027fd2011-08-20 21:16:58 +00002477 bool Assumption) const;
Jordy Rose67044292011-08-17 21:27:39 +00002478
Ted Kremenek8bef8232012-01-26 21:29:00 +00002479 ProgramStateRef
2480 checkRegionChanges(ProgramStateRef state,
Anna Zaksbf53dfa2012-12-20 00:38:25 +00002481 const InvalidatedSymbols *invalidated,
Jordy Rose537716a2011-08-27 22:51:26 +00002482 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00002483 ArrayRef<const MemRegion *> Regions,
Jordan Rose740d4902012-07-02 19:27:35 +00002484 const CallEvent *Call) const;
Jordy Roseab027fd2011-08-20 21:16:58 +00002485
Ted Kremenek8bef8232012-01-26 21:29:00 +00002486 bool wantsRegionChangeUpdate(ProgramStateRef state) const {
Jordy Rose2f9a66d2011-08-20 21:17:59 +00002487 return true;
Jordy Roseab027fd2011-08-20 21:16:58 +00002488 }
Jordy Rose294396b2011-08-22 23:48:23 +00002489
Jordy Rosef53e8c72011-08-23 19:43:16 +00002490 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
2491 void checkReturnWithRetEffect(const ReturnStmt *S, CheckerContext &C,
2492 ExplodedNode *Pred, RetEffect RE, RefVal X,
Ted Kremenek8bef8232012-01-26 21:29:00 +00002493 SymbolRef Sym, ProgramStateRef state) const;
Jordy Rosef53e8c72011-08-23 19:43:16 +00002494
Jordy Rose38f17d62011-08-23 19:01:07 +00002495 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Anna Zaks344c77a2013-01-03 00:25:29 +00002496 void checkEndFunction(CheckerContext &C) const;
Jordy Rose38f17d62011-08-23 19:01:07 +00002497
Ted Kremenek8bef8232012-01-26 21:29:00 +00002498 ProgramStateRef updateSymbol(ProgramStateRef state, SymbolRef sym,
Anna Zaks554067f2012-08-29 23:23:43 +00002499 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
2500 CheckerContext &C) const;
Jordy Rosee0a5d322011-08-23 20:27:16 +00002501
Ted Kremenek8bef8232012-01-26 21:29:00 +00002502 void processNonLeakError(ProgramStateRef St, SourceRange ErrorRange,
Jordy Rose294396b2011-08-22 23:48:23 +00002503 RefVal::Kind ErrorKind, SymbolRef Sym,
2504 CheckerContext &C) const;
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002505
2506 void processObjCLiterals(CheckerContext &C, const Expr *Ex) const;
Jordy Rose294396b2011-08-22 23:48:23 +00002507
Jordy Rose38f17d62011-08-23 19:01:07 +00002508 const ProgramPointTag *getDeadSymbolTag(SymbolRef sym) const;
2509
Ted Kremenek8bef8232012-01-26 21:29:00 +00002510 ProgramStateRef handleSymbolDeath(ProgramStateRef state,
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002511 SymbolRef sid, RefVal V,
2512 SmallVectorImpl<SymbolRef> &Leaked) const;
Jordy Rose38f17d62011-08-23 19:01:07 +00002513
Jordan Rose4ee1c552012-12-06 18:58:18 +00002514 ProgramStateRef
Jordan Rose2bce86c2012-08-18 00:30:16 +00002515 handleAutoreleaseCounts(ProgramStateRef state, ExplodedNode *Pred,
2516 const ProgramPointTag *Tag, CheckerContext &Ctx,
2517 SymbolRef Sym, RefVal V) const;
Jordy Rose8d228632011-08-23 20:07:14 +00002518
Ted Kremenek8bef8232012-01-26 21:29:00 +00002519 ExplodedNode *processLeaks(ProgramStateRef state,
Jordy Rose38f17d62011-08-23 19:01:07 +00002520 SmallVectorImpl<SymbolRef> &Leaked,
Anna Zaks6a93bd52011-10-25 19:57:11 +00002521 CheckerContext &Ctx,
Jordy Rose38f17d62011-08-23 19:01:07 +00002522 ExplodedNode *Pred = 0) const;
Ted Kremenekd593eb92009-11-25 22:17:44 +00002523};
2524} // end anonymous namespace
2525
Jordy Rose67044292011-08-17 21:27:39 +00002526namespace {
2527class StopTrackingCallback : public SymbolVisitor {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002528 ProgramStateRef state;
Jordy Rose67044292011-08-17 21:27:39 +00002529public:
Ted Kremenek8bef8232012-01-26 21:29:00 +00002530 StopTrackingCallback(ProgramStateRef st) : state(st) {}
2531 ProgramStateRef getState() const { return state; }
Jordy Rose67044292011-08-17 21:27:39 +00002532
2533 bool VisitSymbol(SymbolRef sym) {
2534 state = state->remove<RefBindings>(sym);
2535 return true;
2536 }
2537};
2538} // end anonymous namespace
2539
Jordy Rose910c4052011-09-02 06:44:22 +00002540//===----------------------------------------------------------------------===//
2541// Handle statements that may have an effect on refcounts.
2542//===----------------------------------------------------------------------===//
Jordy Rose67044292011-08-17 21:27:39 +00002543
Jordy Rose910c4052011-09-02 06:44:22 +00002544void RetainCountChecker::checkPostStmt(const BlockExpr *BE,
2545 CheckerContext &C) const {
Jordy Rose67044292011-08-17 21:27:39 +00002546
Jordy Rose910c4052011-09-02 06:44:22 +00002547 // Scan the BlockDecRefExprs for any object the retain count checker
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002548 // may be tracking.
John McCall469a1eb2011-02-02 13:00:07 +00002549 if (!BE->getBlockDecl()->hasCaptures())
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002550 return;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002551
Ted Kremenek8bef8232012-01-26 21:29:00 +00002552 ProgramStateRef state = C.getState();
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002553 const BlockDataRegion *R =
Ted Kremenek5eca4822012-01-06 22:09:28 +00002554 cast<BlockDataRegion>(state->getSVal(BE,
2555 C.getLocationContext()).getAsRegion());
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002556
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002557 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
2558 E = R->referenced_vars_end();
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002559
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002560 if (I == E)
2561 return;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002562
Ted Kremenek67d12872009-12-07 22:05:27 +00002563 // FIXME: For now we invalidate the tracking of all symbols passed to blocks
2564 // via captured variables, even though captured variables result in a copy
2565 // and in implicit increment/decrement of a retain count.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002566 SmallVector<const MemRegion*, 10> Regions;
Anna Zaks39ac1872011-10-26 21:06:44 +00002567 const LocationContext *LC = C.getLocationContext();
Ted Kremenekc8413fd2010-12-02 07:49:45 +00002568 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002569
Ted Kremenek67d12872009-12-07 22:05:27 +00002570 for ( ; I != E; ++I) {
Ted Kremeneke3ce2c12012-12-06 07:17:20 +00002571 const VarRegion *VR = I.getCapturedRegion();
Ted Kremenek67d12872009-12-07 22:05:27 +00002572 if (VR->getSuperRegion() == R) {
2573 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2574 }
2575 Regions.push_back(VR);
2576 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002577
Ted Kremenek67d12872009-12-07 22:05:27 +00002578 state =
2579 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
2580 Regions.data() + Regions.size()).getState();
Anna Zaks0bd6b112011-10-26 21:06:34 +00002581 C.addTransition(state);
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002582}
2583
Jordy Rose910c4052011-09-02 06:44:22 +00002584void RetainCountChecker::checkPostStmt(const CastExpr *CE,
2585 CheckerContext &C) const {
John McCallf85e1932011-06-15 23:02:42 +00002586 const ObjCBridgedCastExpr *BE = dyn_cast<ObjCBridgedCastExpr>(CE);
2587 if (!BE)
2588 return;
2589
John McCall71c482c2011-06-17 06:50:50 +00002590 ArgEffect AE = IncRef;
John McCallf85e1932011-06-15 23:02:42 +00002591
2592 switch (BE->getBridgeKind()) {
2593 case clang::OBC_Bridge:
2594 // Do nothing.
2595 return;
2596 case clang::OBC_BridgeRetained:
2597 AE = IncRef;
2598 break;
2599 case clang::OBC_BridgeTransfer:
2600 AE = DecRefBridgedTransfered;
2601 break;
2602 }
2603
Ted Kremenek8bef8232012-01-26 21:29:00 +00002604 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00002605 SymbolRef Sym = state->getSVal(CE, C.getLocationContext()).getAsLocSymbol();
John McCallf85e1932011-06-15 23:02:42 +00002606 if (!Sym)
2607 return;
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002608 const RefVal* T = getRefBinding(state, Sym);
John McCallf85e1932011-06-15 23:02:42 +00002609 if (!T)
2610 return;
2611
John McCallf85e1932011-06-15 23:02:42 +00002612 RefVal::Kind hasErr = (RefVal::Kind) 0;
Jordy Rose17a38e22011-09-02 05:55:19 +00002613 state = updateSymbol(state, Sym, *T, AE, hasErr, C);
John McCallf85e1932011-06-15 23:02:42 +00002614
2615 if (hasErr) {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002616 // FIXME: If we get an error during a bridge cast, should we report it?
2617 // Should we assert that there is no error?
John McCallf85e1932011-06-15 23:02:42 +00002618 return;
2619 }
2620
Anna Zaks0bd6b112011-10-26 21:06:34 +00002621 C.addTransition(state);
John McCallf85e1932011-06-15 23:02:42 +00002622}
2623
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002624void RetainCountChecker::processObjCLiterals(CheckerContext &C,
2625 const Expr *Ex) const {
2626 ProgramStateRef state = C.getState();
2627 const ExplodedNode *pred = C.getPredecessor();
2628 for (Stmt::const_child_iterator it = Ex->child_begin(), et = Ex->child_end() ;
2629 it != et ; ++it) {
2630 const Stmt *child = *it;
2631 SVal V = state->getSVal(child, pred->getLocationContext());
2632 if (SymbolRef sym = V.getAsSymbol())
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002633 if (const RefVal* T = getRefBinding(state, sym)) {
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002634 RefVal::Kind hasErr = (RefVal::Kind) 0;
2635 state = updateSymbol(state, sym, *T, MayEscape, hasErr, C);
2636 if (hasErr) {
2637 processNonLeakError(state, child->getSourceRange(), hasErr, sym, C);
2638 return;
2639 }
2640 }
2641 }
2642
2643 // Return the object as autoreleased.
2644 // RetEffect RE = RetEffect::MakeNotOwned(RetEffect::ObjC);
2645 if (SymbolRef sym =
2646 state->getSVal(Ex, pred->getLocationContext()).getAsSymbol()) {
2647 QualType ResultTy = Ex->getType();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002648 state = setRefBinding(state, sym,
2649 RefVal::makeNotOwned(RetEffect::ObjC, ResultTy));
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002650 }
2651
2652 C.addTransition(state);
2653}
2654
2655void RetainCountChecker::checkPostStmt(const ObjCArrayLiteral *AL,
2656 CheckerContext &C) const {
2657 // Apply the 'MayEscape' to all values.
2658 processObjCLiterals(C, AL);
2659}
2660
2661void RetainCountChecker::checkPostStmt(const ObjCDictionaryLiteral *DL,
2662 CheckerContext &C) const {
2663 // Apply the 'MayEscape' to all keys and values.
2664 processObjCLiterals(C, DL);
2665}
2666
Jordy Rose70fdbc32012-05-12 05:10:43 +00002667void RetainCountChecker::checkPostStmt(const ObjCBoxedExpr *Ex,
2668 CheckerContext &C) const {
2669 const ExplodedNode *Pred = C.getPredecessor();
2670 const LocationContext *LCtx = Pred->getLocationContext();
2671 ProgramStateRef State = Pred->getState();
2672
2673 if (SymbolRef Sym = State->getSVal(Ex, LCtx).getAsSymbol()) {
2674 QualType ResultTy = Ex->getType();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002675 State = setRefBinding(State, Sym,
2676 RefVal::makeNotOwned(RetEffect::ObjC, ResultTy));
Jordy Rose70fdbc32012-05-12 05:10:43 +00002677 }
2678
2679 C.addTransition(State);
2680}
2681
Jordan Rosefe6a0112012-07-02 19:28:21 +00002682void RetainCountChecker::checkPostCall(const CallEvent &Call,
2683 CheckerContext &C) const {
Jordan Rosefe6a0112012-07-02 19:28:21 +00002684 RetainSummaryManager &Summaries = getSummaryManager(C);
2685 const RetainSummary *Summ = Summaries.getSummary(Call, C.getState());
Anna Zaks554067f2012-08-29 23:23:43 +00002686
2687 if (C.wasInlined) {
2688 processSummaryOfInlined(*Summ, Call, C);
2689 return;
2690 }
Jordan Rosefe6a0112012-07-02 19:28:21 +00002691 checkSummary(*Summ, Call, C);
Jordy Rose294396b2011-08-22 23:48:23 +00002692}
2693
Jordy Rose910c4052011-09-02 06:44:22 +00002694/// GetReturnType - Used to get the return type of a message expression or
2695/// function call with the intention of affixing that type to a tracked symbol.
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +00002696/// While the return type can be queried directly from RetEx, when
Jordy Rose910c4052011-09-02 06:44:22 +00002697/// invoking class methods we augment to the return type to be that of
2698/// a pointer to the class (as opposed it just being id).
2699// FIXME: We may be able to do this with related result types instead.
2700// This function is probably overestimating.
2701static QualType GetReturnType(const Expr *RetE, ASTContext &Ctx) {
2702 QualType RetTy = RetE->getType();
2703 // If RetE is not a message expression just return its type.
2704 // If RetE is a message expression, return its types if it is something
2705 /// more specific than id.
2706 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RetE))
2707 if (const ObjCObjectPointerType *PT = RetTy->getAs<ObjCObjectPointerType>())
2708 if (PT->isObjCQualifiedIdType() || PT->isObjCIdType() ||
2709 PT->isObjCClassType()) {
2710 // At this point we know the return type of the message expression is
2711 // id, id<...>, or Class. If we have an ObjCInterfaceDecl, we know this
2712 // is a call to a class method whose type we can resolve. In such
2713 // cases, promote the return type to XXX* (where XXX is the class).
2714 const ObjCInterfaceDecl *D = ME->getReceiverInterface();
2715 return !D ? RetTy :
2716 Ctx.getObjCObjectPointerType(Ctx.getObjCInterfaceType(D));
2717 }
2718
2719 return RetTy;
2720}
2721
Anna Zaks554067f2012-08-29 23:23:43 +00002722// We don't always get the exact modeling of the function with regards to the
2723// retain count checker even when the function is inlined. For example, we need
2724// to stop tracking the symbols which were marked with StopTrackingHard.
2725void RetainCountChecker::processSummaryOfInlined(const RetainSummary &Summ,
2726 const CallEvent &CallOrMsg,
2727 CheckerContext &C) const {
2728 ProgramStateRef state = C.getState();
2729
2730 // Evaluate the effect of the arguments.
2731 for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
2732 if (Summ.getArg(idx) == StopTrackingHard) {
2733 SVal V = CallOrMsg.getArgSVal(idx);
2734 if (SymbolRef Sym = V.getAsLocSymbol()) {
2735 state = removeRefBinding(state, Sym);
2736 }
2737 }
2738 }
2739
2740 // Evaluate the effect on the message receiver.
2741 const ObjCMethodCall *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg);
2742 if (MsgInvocation) {
2743 if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
2744 if (Summ.getReceiverEffect() == StopTrackingHard) {
2745 state = removeRefBinding(state, Sym);
2746 }
2747 }
2748 }
2749
2750 // Consult the summary for the return value.
2751 RetEffect RE = Summ.getRetEffect();
2752 if (RE.getKind() == RetEffect::NoRetHard) {
Jordan Rose2f3017f2012-11-02 23:49:29 +00002753 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
Anna Zaks554067f2012-08-29 23:23:43 +00002754 if (Sym)
2755 state = removeRefBinding(state, Sym);
2756 }
2757
2758 C.addTransition(state);
2759}
2760
Jordy Rose910c4052011-09-02 06:44:22 +00002761void RetainCountChecker::checkSummary(const RetainSummary &Summ,
Jordan Rose4531b7d2012-07-02 19:27:43 +00002762 const CallEvent &CallOrMsg,
Jordy Rose910c4052011-09-02 06:44:22 +00002763 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002764 ProgramStateRef state = C.getState();
Jordy Rose294396b2011-08-22 23:48:23 +00002765
2766 // Evaluate the effect of the arguments.
2767 RefVal::Kind hasErr = (RefVal::Kind) 0;
2768 SourceRange ErrorRange;
2769 SymbolRef ErrorSym = 0;
2770
2771 for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
Jordy Rose537716a2011-08-27 22:51:26 +00002772 SVal V = CallOrMsg.getArgSVal(idx);
Jordy Rose294396b2011-08-22 23:48:23 +00002773
2774 if (SymbolRef Sym = V.getAsLocSymbol()) {
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002775 if (const RefVal *T = getRefBinding(state, Sym)) {
Jordy Rose17a38e22011-09-02 05:55:19 +00002776 state = updateSymbol(state, Sym, *T, Summ.getArg(idx), hasErr, C);
Jordy Rose294396b2011-08-22 23:48:23 +00002777 if (hasErr) {
2778 ErrorRange = CallOrMsg.getArgSourceRange(idx);
2779 ErrorSym = Sym;
2780 break;
2781 }
2782 }
2783 }
2784 }
2785
2786 // Evaluate the effect on the message receiver.
2787 bool ReceiverIsTracked = false;
Jordan Rose4531b7d2012-07-02 19:27:43 +00002788 if (!hasErr) {
Jordan Rosecde8cdb2012-07-02 19:27:56 +00002789 const ObjCMethodCall *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg);
Jordan Rose4531b7d2012-07-02 19:27:43 +00002790 if (MsgInvocation) {
2791 if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002792 if (const RefVal *T = getRefBinding(state, Sym)) {
Jordan Rose4531b7d2012-07-02 19:27:43 +00002793 ReceiverIsTracked = true;
2794 state = updateSymbol(state, Sym, *T, Summ.getReceiverEffect(),
Anna Zaks554067f2012-08-29 23:23:43 +00002795 hasErr, C);
Jordan Rose4531b7d2012-07-02 19:27:43 +00002796 if (hasErr) {
Jordan Rose8919e682012-07-18 21:59:51 +00002797 ErrorRange = MsgInvocation->getOriginExpr()->getReceiverRange();
Jordan Rose4531b7d2012-07-02 19:27:43 +00002798 ErrorSym = Sym;
2799 }
Jordy Rose294396b2011-08-22 23:48:23 +00002800 }
2801 }
2802 }
2803 }
2804
2805 // Process any errors.
2806 if (hasErr) {
2807 processNonLeakError(state, ErrorRange, hasErr, ErrorSym, C);
2808 return;
2809 }
2810
2811 // Consult the summary for the return value.
2812 RetEffect RE = Summ.getRetEffect();
2813
2814 if (RE.getKind() == RetEffect::OwnedWhenTrackedReceiver) {
Jordy Roseb6cfc092011-08-25 00:10:37 +00002815 if (ReceiverIsTracked)
Jordy Rose17a38e22011-09-02 05:55:19 +00002816 RE = getSummaryManager(C).getObjAllocRetEffect();
Jordy Roseb6cfc092011-08-25 00:10:37 +00002817 else
Jordy Rose294396b2011-08-22 23:48:23 +00002818 RE = RetEffect::MakeNoRet();
2819 }
2820
2821 switch (RE.getKind()) {
2822 default:
David Blaikie7530c032012-01-17 06:56:22 +00002823 llvm_unreachable("Unhandled RetEffect.");
Jordy Rose294396b2011-08-22 23:48:23 +00002824
2825 case RetEffect::NoRet:
Anna Zaks554067f2012-08-29 23:23:43 +00002826 case RetEffect::NoRetHard:
Jordy Rose294396b2011-08-22 23:48:23 +00002827 // No work necessary.
2828 break;
2829
2830 case RetEffect::OwnedAllocatedSymbol:
2831 case RetEffect::OwnedSymbol: {
Jordan Rose2f3017f2012-11-02 23:49:29 +00002832 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
Jordy Rose294396b2011-08-22 23:48:23 +00002833 if (!Sym)
2834 break;
2835
Jordan Rose4531b7d2012-07-02 19:27:43 +00002836 // Use the result type from the CallEvent as it automatically adjusts
Jordy Rose294396b2011-08-22 23:48:23 +00002837 // for methods/functions that return references.
Jordan Rose4531b7d2012-07-02 19:27:43 +00002838 QualType ResultTy = CallOrMsg.getResultType();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002839 state = setRefBinding(state, Sym, RefVal::makeOwned(RE.getObjKind(),
2840 ResultTy));
Jordy Rose294396b2011-08-22 23:48:23 +00002841
2842 // FIXME: Add a flag to the checker where allocations are assumed to
Anna Zaksc6ba23f2012-08-14 15:39:13 +00002843 // *not* fail.
Jordy Rose294396b2011-08-22 23:48:23 +00002844 break;
2845 }
2846
2847 case RetEffect::GCNotOwnedSymbol:
2848 case RetEffect::ARCNotOwnedSymbol:
2849 case RetEffect::NotOwnedSymbol: {
2850 const Expr *Ex = CallOrMsg.getOriginExpr();
Jordan Rose2f3017f2012-11-02 23:49:29 +00002851 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
Jordy Rose294396b2011-08-22 23:48:23 +00002852 if (!Sym)
2853 break;
Ted Kremenek74616822012-10-12 22:56:45 +00002854 assert(Ex);
Jordy Rose294396b2011-08-22 23:48:23 +00002855 // Use GetReturnType in order to give [NSFoo alloc] the type NSFoo *.
2856 QualType ResultTy = GetReturnType(Ex, C.getASTContext());
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002857 state = setRefBinding(state, Sym, RefVal::makeNotOwned(RE.getObjKind(),
2858 ResultTy));
Jordy Rose294396b2011-08-22 23:48:23 +00002859 break;
2860 }
2861 }
2862
2863 // This check is actually necessary; otherwise the statement builder thinks
2864 // we've hit a previously-found path.
2865 // Normally addTransition takes care of this, but we want the node pointer.
2866 ExplodedNode *NewNode;
2867 if (state == C.getState()) {
2868 NewNode = C.getPredecessor();
2869 } else {
Anna Zaks0bd6b112011-10-26 21:06:34 +00002870 NewNode = C.addTransition(state);
Jordy Rose294396b2011-08-22 23:48:23 +00002871 }
2872
Jordy Rose9c083b72011-08-24 18:56:32 +00002873 // Annotate the node with summary we used.
2874 if (NewNode) {
2875 // FIXME: This is ugly. See checkEndAnalysis for why it's necessary.
2876 if (ShouldResetSummaryLog) {
2877 SummaryLog.clear();
2878 ShouldResetSummaryLog = false;
2879 }
Jordy Roseec9ef852011-08-23 20:55:48 +00002880 SummaryLog[NewNode] = &Summ;
Jordy Rose9c083b72011-08-24 18:56:32 +00002881 }
Jordy Rose294396b2011-08-22 23:48:23 +00002882}
2883
Jordy Rosee0a5d322011-08-23 20:27:16 +00002884
Ted Kremenek8bef8232012-01-26 21:29:00 +00002885ProgramStateRef
2886RetainCountChecker::updateSymbol(ProgramStateRef state, SymbolRef sym,
Jordy Rose910c4052011-09-02 06:44:22 +00002887 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
2888 CheckerContext &C) const {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002889 // In GC mode [... release] and [... retain] do nothing.
Jordy Rose910c4052011-09-02 06:44:22 +00002890 // In ARC mode they shouldn't exist at all, but we just ignore them.
Jordy Rose17a38e22011-09-02 05:55:19 +00002891 bool IgnoreRetainMsg = C.isObjCGCEnabled();
2892 if (!IgnoreRetainMsg)
David Blaikie4e4d0842012-03-11 07:00:24 +00002893 IgnoreRetainMsg = (bool)C.getASTContext().getLangOpts().ObjCAutoRefCount;
Jordy Rose17a38e22011-09-02 05:55:19 +00002894
Jordy Rosee0a5d322011-08-23 20:27:16 +00002895 switch (E) {
Jordan Rose4531b7d2012-07-02 19:27:43 +00002896 default:
2897 break;
2898 case IncRefMsg:
2899 E = IgnoreRetainMsg ? DoNothing : IncRef;
2900 break;
2901 case DecRefMsg:
2902 E = IgnoreRetainMsg ? DoNothing : DecRef;
2903 break;
Anna Zaks554067f2012-08-29 23:23:43 +00002904 case DecRefMsgAndStopTrackingHard:
2905 E = IgnoreRetainMsg ? StopTracking : DecRefAndStopTrackingHard;
Jordan Rose4531b7d2012-07-02 19:27:43 +00002906 break;
2907 case MakeCollectable:
2908 E = C.isObjCGCEnabled() ? DecRef : DoNothing;
2909 break;
Jordy Rosee0a5d322011-08-23 20:27:16 +00002910 }
2911
2912 // Handle all use-after-releases.
Jordy Rose17a38e22011-09-02 05:55:19 +00002913 if (!C.isObjCGCEnabled() && V.getKind() == RefVal::Released) {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002914 V = V ^ RefVal::ErrorUseAfterRelease;
2915 hasErr = V.getKind();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002916 return setRefBinding(state, sym, V);
Jordy Rosee0a5d322011-08-23 20:27:16 +00002917 }
2918
2919 switch (E) {
2920 case DecRefMsg:
2921 case IncRefMsg:
2922 case MakeCollectable:
Anna Zaks554067f2012-08-29 23:23:43 +00002923 case DecRefMsgAndStopTrackingHard:
Jordy Rosee0a5d322011-08-23 20:27:16 +00002924 llvm_unreachable("DecRefMsg/IncRefMsg/MakeCollectable already converted");
Jordy Rosee0a5d322011-08-23 20:27:16 +00002925
2926 case Dealloc:
2927 // Any use of -dealloc in GC is *bad*.
Jordy Rose17a38e22011-09-02 05:55:19 +00002928 if (C.isObjCGCEnabled()) {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002929 V = V ^ RefVal::ErrorDeallocGC;
2930 hasErr = V.getKind();
2931 break;
2932 }
2933
2934 switch (V.getKind()) {
2935 default:
2936 llvm_unreachable("Invalid RefVal state for an explicit dealloc.");
Jordy Rosee0a5d322011-08-23 20:27:16 +00002937 case RefVal::Owned:
2938 // The object immediately transitions to the released state.
2939 V = V ^ RefVal::Released;
2940 V.clearCounts();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002941 return setRefBinding(state, sym, V);
Jordy Rosee0a5d322011-08-23 20:27:16 +00002942 case RefVal::NotOwned:
2943 V = V ^ RefVal::ErrorDeallocNotOwned;
2944 hasErr = V.getKind();
2945 break;
2946 }
2947 break;
2948
Jordy Rosee0a5d322011-08-23 20:27:16 +00002949 case MayEscape:
2950 if (V.getKind() == RefVal::Owned) {
2951 V = V ^ RefVal::NotOwned;
2952 break;
2953 }
2954
2955 // Fall-through.
2956
Jordy Rosee0a5d322011-08-23 20:27:16 +00002957 case DoNothing:
2958 return state;
2959
2960 case Autorelease:
Jordy Rose17a38e22011-09-02 05:55:19 +00002961 if (C.isObjCGCEnabled())
Jordy Rosee0a5d322011-08-23 20:27:16 +00002962 return state;
Jordy Rosee0a5d322011-08-23 20:27:16 +00002963 // Update the autorelease counts.
Jordy Rosee0a5d322011-08-23 20:27:16 +00002964 V = V.autorelease();
2965 break;
2966
2967 case StopTracking:
Anna Zaks554067f2012-08-29 23:23:43 +00002968 case StopTrackingHard:
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002969 return removeRefBinding(state, sym);
Jordy Rosee0a5d322011-08-23 20:27:16 +00002970
2971 case IncRef:
2972 switch (V.getKind()) {
2973 default:
2974 llvm_unreachable("Invalid RefVal state for a retain.");
Jordy Rosee0a5d322011-08-23 20:27:16 +00002975 case RefVal::Owned:
2976 case RefVal::NotOwned:
2977 V = V + 1;
2978 break;
2979 case RefVal::Released:
2980 // Non-GC cases are handled above.
Jordy Rose17a38e22011-09-02 05:55:19 +00002981 assert(C.isObjCGCEnabled());
Jordy Rosee0a5d322011-08-23 20:27:16 +00002982 V = (V ^ RefVal::Owned) + 1;
2983 break;
2984 }
2985 break;
2986
Jordy Rosee0a5d322011-08-23 20:27:16 +00002987 case DecRef:
2988 case DecRefBridgedTransfered:
Anna Zaks554067f2012-08-29 23:23:43 +00002989 case DecRefAndStopTrackingHard:
Jordy Rosee0a5d322011-08-23 20:27:16 +00002990 switch (V.getKind()) {
2991 default:
2992 // case 'RefVal::Released' handled above.
2993 llvm_unreachable("Invalid RefVal state for a release.");
Jordy Rosee0a5d322011-08-23 20:27:16 +00002994
2995 case RefVal::Owned:
2996 assert(V.getCount() > 0);
2997 if (V.getCount() == 1)
2998 V = V ^ (E == DecRefBridgedTransfered ?
2999 RefVal::NotOwned : RefVal::Released);
Anna Zaks554067f2012-08-29 23:23:43 +00003000 else if (E == DecRefAndStopTrackingHard)
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003001 return removeRefBinding(state, sym);
Jordan Rose4531b7d2012-07-02 19:27:43 +00003002
Jordy Rosee0a5d322011-08-23 20:27:16 +00003003 V = V - 1;
3004 break;
3005
3006 case RefVal::NotOwned:
Jordan Rose4531b7d2012-07-02 19:27:43 +00003007 if (V.getCount() > 0) {
Anna Zaks554067f2012-08-29 23:23:43 +00003008 if (E == DecRefAndStopTrackingHard)
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003009 return removeRefBinding(state, sym);
Jordy Rosee0a5d322011-08-23 20:27:16 +00003010 V = V - 1;
Jordan Rose4531b7d2012-07-02 19:27:43 +00003011 } else {
Jordy Rosee0a5d322011-08-23 20:27:16 +00003012 V = V ^ RefVal::ErrorReleaseNotOwned;
3013 hasErr = V.getKind();
3014 }
3015 break;
3016
3017 case RefVal::Released:
3018 // Non-GC cases are handled above.
Jordy Rose17a38e22011-09-02 05:55:19 +00003019 assert(C.isObjCGCEnabled());
Jordy Rosee0a5d322011-08-23 20:27:16 +00003020 V = V ^ RefVal::ErrorUseAfterRelease;
3021 hasErr = V.getKind();
3022 break;
3023 }
3024 break;
3025 }
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003026 return setRefBinding(state, sym, V);
Jordy Rosee0a5d322011-08-23 20:27:16 +00003027}
3028
Ted Kremenek8bef8232012-01-26 21:29:00 +00003029void RetainCountChecker::processNonLeakError(ProgramStateRef St,
Jordy Rose910c4052011-09-02 06:44:22 +00003030 SourceRange ErrorRange,
3031 RefVal::Kind ErrorKind,
3032 SymbolRef Sym,
3033 CheckerContext &C) const {
Jordy Rose294396b2011-08-22 23:48:23 +00003034 ExplodedNode *N = C.generateSink(St);
3035 if (!N)
3036 return;
3037
Jordy Rose294396b2011-08-22 23:48:23 +00003038 CFRefBug *BT;
3039 switch (ErrorKind) {
3040 default:
3041 llvm_unreachable("Unhandled error.");
Jordy Rose294396b2011-08-22 23:48:23 +00003042 case RefVal::ErrorUseAfterRelease:
Jordy Rosed6334e12011-08-25 00:34:03 +00003043 if (!useAfterRelease)
3044 useAfterRelease.reset(new UseAfterRelease());
3045 BT = &*useAfterRelease;
Jordy Rose294396b2011-08-22 23:48:23 +00003046 break;
3047 case RefVal::ErrorReleaseNotOwned:
Jordy Rosed6334e12011-08-25 00:34:03 +00003048 if (!releaseNotOwned)
3049 releaseNotOwned.reset(new BadRelease());
3050 BT = &*releaseNotOwned;
Jordy Rose294396b2011-08-22 23:48:23 +00003051 break;
3052 case RefVal::ErrorDeallocGC:
Jordy Rosed6334e12011-08-25 00:34:03 +00003053 if (!deallocGC)
3054 deallocGC.reset(new DeallocGC());
3055 BT = &*deallocGC;
Jordy Rose294396b2011-08-22 23:48:23 +00003056 break;
3057 case RefVal::ErrorDeallocNotOwned:
Jordy Rosed6334e12011-08-25 00:34:03 +00003058 if (!deallocNotOwned)
3059 deallocNotOwned.reset(new DeallocNotOwned());
3060 BT = &*deallocNotOwned;
Jordy Rose294396b2011-08-22 23:48:23 +00003061 break;
3062 }
3063
Jordy Rosed6334e12011-08-25 00:34:03 +00003064 assert(BT);
David Blaikie4e4d0842012-03-11 07:00:24 +00003065 CFRefReport *report = new CFRefReport(*BT, C.getASTContext().getLangOpts(),
Jordy Rose17a38e22011-09-02 05:55:19 +00003066 C.isObjCGCEnabled(), SummaryLog,
3067 N, Sym);
Jordy Rose294396b2011-08-22 23:48:23 +00003068 report->addRange(ErrorRange);
Jordan Rose785950e2012-11-02 01:53:40 +00003069 C.emitReport(report);
Jordy Rose294396b2011-08-22 23:48:23 +00003070}
3071
Jordy Rose910c4052011-09-02 06:44:22 +00003072//===----------------------------------------------------------------------===//
3073// Handle the return values of retain-count-related functions.
3074//===----------------------------------------------------------------------===//
3075
3076bool RetainCountChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
Jordy Rose76c506f2011-08-21 21:58:18 +00003077 // Get the callee. We're only interested in simple C functions.
Ted Kremenek8bef8232012-01-26 21:29:00 +00003078 ProgramStateRef state = C.getState();
Anna Zaksb805c8f2011-12-01 05:57:37 +00003079 const FunctionDecl *FD = C.getCalleeDecl(CE);
Jordy Rose76c506f2011-08-21 21:58:18 +00003080 if (!FD)
3081 return false;
3082
3083 IdentifierInfo *II = FD->getIdentifier();
3084 if (!II)
3085 return false;
3086
3087 // For now, we're only handling the functions that return aliases of their
3088 // arguments: CFRetain and CFMakeCollectable (and their families).
3089 // Eventually we should add other functions we can model entirely,
3090 // such as CFRelease, which don't invalidate their arguments or globals.
3091 if (CE->getNumArgs() != 1)
3092 return false;
3093
3094 // Get the name of the function.
3095 StringRef FName = II->getName();
3096 FName = FName.substr(FName.find_first_not_of('_'));
3097
3098 // See if it's one of the specific functions we know how to eval.
3099 bool canEval = false;
3100
Anna Zaksb805c8f2011-12-01 05:57:37 +00003101 QualType ResultTy = CE->getCallReturnType();
Jordy Rose76c506f2011-08-21 21:58:18 +00003102 if (ResultTy->isObjCIdType()) {
3103 // Handle: id NSMakeCollectable(CFTypeRef)
3104 canEval = II->isStr("NSMakeCollectable");
3105 } else if (ResultTy->isPointerType()) {
3106 // Handle: (CF|CG)Retain
3107 // CFMakeCollectable
3108 // It's okay to be a little sloppy here (CGMakeCollectable doesn't exist).
3109 if (cocoa::isRefType(ResultTy, "CF", FName) ||
3110 cocoa::isRefType(ResultTy, "CG", FName)) {
3111 canEval = isRetain(FD, FName) || isMakeCollectable(FD, FName);
3112 }
3113 }
3114
3115 if (!canEval)
3116 return false;
3117
3118 // Bind the return value.
Ted Kremenek5eca4822012-01-06 22:09:28 +00003119 const LocationContext *LCtx = C.getLocationContext();
3120 SVal RetVal = state->getSVal(CE->getArg(0), LCtx);
Jordy Rose76c506f2011-08-21 21:58:18 +00003121 if (RetVal.isUnknown()) {
3122 // If the receiver is unknown, conjure a return value.
3123 SValBuilder &SVB = C.getSValBuilder();
Ted Kremenek66c486f2012-08-22 06:26:15 +00003124 RetVal = SVB.conjureSymbolVal(0, CE, LCtx, ResultTy, C.blockCount());
Jordy Rose76c506f2011-08-21 21:58:18 +00003125 }
Ted Kremenek5eca4822012-01-06 22:09:28 +00003126 state = state->BindExpr(CE, LCtx, RetVal, false);
Jordy Rose76c506f2011-08-21 21:58:18 +00003127
Jordy Rose294396b2011-08-22 23:48:23 +00003128 // FIXME: This should not be necessary, but otherwise the argument seems to be
3129 // considered alive during the next statement.
3130 if (const MemRegion *ArgRegion = RetVal.getAsRegion()) {
3131 // Save the refcount status of the argument.
3132 SymbolRef Sym = RetVal.getAsLocSymbol();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003133 const RefVal *Binding = 0;
Jordy Rose294396b2011-08-22 23:48:23 +00003134 if (Sym)
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003135 Binding = getRefBinding(state, Sym);
Jordy Rose76c506f2011-08-21 21:58:18 +00003136
Jordy Rose294396b2011-08-22 23:48:23 +00003137 // Invalidate the argument region.
Anna Zaksbf53dfa2012-12-20 00:38:25 +00003138 state = state->invalidateRegions(ArgRegion, CE, C.blockCount(), LCtx,
Anna Zaks64eb0702013-01-16 01:35:54 +00003139 /*CausesPointerEscape*/ false);
Jordy Rose76c506f2011-08-21 21:58:18 +00003140
Jordy Rose294396b2011-08-22 23:48:23 +00003141 // Restore the refcount status of the argument.
3142 if (Binding)
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003143 state = setRefBinding(state, Sym, *Binding);
Jordy Rose294396b2011-08-22 23:48:23 +00003144 }
3145
Anna Zaks0bd6b112011-10-26 21:06:34 +00003146 C.addTransition(state);
Jordy Rose76c506f2011-08-21 21:58:18 +00003147 return true;
3148}
3149
Jordy Rose910c4052011-09-02 06:44:22 +00003150//===----------------------------------------------------------------------===//
3151// Handle return statements.
3152//===----------------------------------------------------------------------===//
Jordy Rosef53e8c72011-08-23 19:43:16 +00003153
Jordy Rose910c4052011-09-02 06:44:22 +00003154void RetainCountChecker::checkPreStmt(const ReturnStmt *S,
3155 CheckerContext &C) const {
Ted Kremeneke5715782012-02-25 02:09:09 +00003156
3157 // Only adjust the reference count if this is the top-level call frame,
3158 // and not the result of inlining. In the future, we should do
3159 // better checking even for inlined calls, and see if they match
3160 // with their expected semantics (e.g., the method should return a retained
3161 // object, etc.).
Anna Zaksfadcd5d2012-11-03 02:54:16 +00003162 if (!C.inTopFrame())
Ted Kremeneke5715782012-02-25 02:09:09 +00003163 return;
3164
Jordy Rosef53e8c72011-08-23 19:43:16 +00003165 const Expr *RetE = S->getRetValue();
3166 if (!RetE)
3167 return;
3168
Ted Kremenek8bef8232012-01-26 21:29:00 +00003169 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00003170 SymbolRef Sym =
3171 state->getSValAsScalarOrLoc(RetE, C.getLocationContext()).getAsLocSymbol();
Jordy Rosef53e8c72011-08-23 19:43:16 +00003172 if (!Sym)
3173 return;
3174
3175 // Get the reference count binding (if any).
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003176 const RefVal *T = getRefBinding(state, Sym);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003177 if (!T)
3178 return;
3179
3180 // Change the reference count.
3181 RefVal X = *T;
3182
3183 switch (X.getKind()) {
3184 case RefVal::Owned: {
3185 unsigned cnt = X.getCount();
3186 assert(cnt > 0);
3187 X.setCount(cnt - 1);
3188 X = X ^ RefVal::ReturnedOwned;
3189 break;
3190 }
3191
3192 case RefVal::NotOwned: {
3193 unsigned cnt = X.getCount();
3194 if (cnt) {
3195 X.setCount(cnt - 1);
3196 X = X ^ RefVal::ReturnedOwned;
3197 }
3198 else {
3199 X = X ^ RefVal::ReturnedNotOwned;
3200 }
3201 break;
3202 }
3203
3204 default:
3205 return;
3206 }
3207
3208 // Update the binding.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003209 state = setRefBinding(state, Sym, X);
Anna Zaks0bd6b112011-10-26 21:06:34 +00003210 ExplodedNode *Pred = C.addTransition(state);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003211
3212 // At this point we have updated the state properly.
3213 // Everything after this is merely checking to see if the return value has
3214 // been over- or under-retained.
3215
3216 // Did we cache out?
3217 if (!Pred)
3218 return;
3219
Jordy Rosef53e8c72011-08-23 19:43:16 +00003220 // Update the autorelease counts.
3221 static SimpleProgramPointTag
Jordy Rose910c4052011-09-02 06:44:22 +00003222 AutoreleaseTag("RetainCountChecker : Autorelease");
Jordan Rose4ee1c552012-12-06 18:58:18 +00003223 state = handleAutoreleaseCounts(state, Pred, &AutoreleaseTag, C, Sym, X);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003224
3225 // Did we cache out?
Jordan Rose4ee1c552012-12-06 18:58:18 +00003226 if (!state)
Jordy Rosef53e8c72011-08-23 19:43:16 +00003227 return;
3228
3229 // Get the updated binding.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003230 T = getRefBinding(state, Sym);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003231 assert(T);
3232 X = *T;
3233
3234 // Consult the summary of the enclosing method.
Jordy Rose17a38e22011-09-02 05:55:19 +00003235 RetainSummaryManager &Summaries = getSummaryManager(C);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003236 const Decl *CD = &Pred->getCodeDecl();
Jordan Rose4531b7d2012-07-02 19:27:43 +00003237 RetEffect RE = RetEffect::MakeNoRet();
Jordy Rosef53e8c72011-08-23 19:43:16 +00003238
Jordan Rose4531b7d2012-07-02 19:27:43 +00003239 // FIXME: What is the convention for blocks? Is there one?
Jordy Rosef53e8c72011-08-23 19:43:16 +00003240 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CD)) {
Jordy Roseb6cfc092011-08-25 00:10:37 +00003241 const RetainSummary *Summ = Summaries.getMethodSummary(MD);
Jordan Rose4531b7d2012-07-02 19:27:43 +00003242 RE = Summ->getRetEffect();
3243 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) {
3244 if (!isa<CXXMethodDecl>(FD)) {
3245 const RetainSummary *Summ = Summaries.getFunctionSummary(FD);
3246 RE = Summ->getRetEffect();
3247 }
Jordy Rosef53e8c72011-08-23 19:43:16 +00003248 }
3249
Jordan Rose4531b7d2012-07-02 19:27:43 +00003250 checkReturnWithRetEffect(S, C, Pred, RE, X, Sym, state);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003251}
3252
Jordy Rose910c4052011-09-02 06:44:22 +00003253void RetainCountChecker::checkReturnWithRetEffect(const ReturnStmt *S,
3254 CheckerContext &C,
3255 ExplodedNode *Pred,
3256 RetEffect RE, RefVal X,
3257 SymbolRef Sym,
Ted Kremenek8bef8232012-01-26 21:29:00 +00003258 ProgramStateRef state) const {
Jordy Rosef53e8c72011-08-23 19:43:16 +00003259 // Any leaks or other errors?
3260 if (X.isReturnedOwned() && X.getCount() == 0) {
3261 if (RE.getKind() != RetEffect::NoRet) {
3262 bool hasError = false;
Jordy Rose17a38e22011-09-02 05:55:19 +00003263 if (C.isObjCGCEnabled() && RE.getObjKind() == RetEffect::ObjC) {
Jordy Rosef53e8c72011-08-23 19:43:16 +00003264 // Things are more complicated with garbage collection. If the
3265 // returned object is suppose to be an Objective-C object, we have
3266 // a leak (as the caller expects a GC'ed object) because no
3267 // method should return ownership unless it returns a CF object.
3268 hasError = true;
3269 X = X ^ RefVal::ErrorGCLeakReturned;
3270 }
3271 else if (!RE.isOwned()) {
3272 // Either we are using GC and the returned object is a CF type
3273 // or we aren't using GC. In either case, we expect that the
3274 // enclosing method is expected to return ownership.
3275 hasError = true;
3276 X = X ^ RefVal::ErrorLeakReturned;
3277 }
3278
3279 if (hasError) {
3280 // Generate an error node.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003281 state = setRefBinding(state, Sym, X);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003282
3283 static SimpleProgramPointTag
Jordy Rose910c4052011-09-02 06:44:22 +00003284 ReturnOwnLeakTag("RetainCountChecker : ReturnsOwnLeak");
Anna Zaks0bd6b112011-10-26 21:06:34 +00003285 ExplodedNode *N = C.addTransition(state, Pred, &ReturnOwnLeakTag);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003286 if (N) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003287 const LangOptions &LOpts = C.getASTContext().getLangOpts();
Jordy Rose17a38e22011-09-02 05:55:19 +00003288 bool GCEnabled = C.isObjCGCEnabled();
Jordy Rosef53e8c72011-08-23 19:43:16 +00003289 CFRefReport *report =
Jordy Rose17a38e22011-09-02 05:55:19 +00003290 new CFRefLeakReport(*getLeakAtReturnBug(LOpts, GCEnabled),
3291 LOpts, GCEnabled, SummaryLog,
Ted Kremenek08a838d2013-04-16 21:44:22 +00003292 N, Sym, C, IncludeAllocationLine);
3293
Jordan Rose785950e2012-11-02 01:53:40 +00003294 C.emitReport(report);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003295 }
3296 }
3297 }
3298 } else if (X.isReturnedNotOwned()) {
3299 if (RE.isOwned()) {
3300 // Trying to return a not owned object to a caller expecting an
3301 // owned object.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003302 state = setRefBinding(state, Sym, X ^ RefVal::ErrorReturnedNotOwned);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003303
3304 static SimpleProgramPointTag
Jordy Rose910c4052011-09-02 06:44:22 +00003305 ReturnNotOwnedTag("RetainCountChecker : ReturnNotOwnedForOwned");
Anna Zaks0bd6b112011-10-26 21:06:34 +00003306 ExplodedNode *N = C.addTransition(state, Pred, &ReturnNotOwnedTag);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003307 if (N) {
Jordy Rosed6334e12011-08-25 00:34:03 +00003308 if (!returnNotOwnedForOwned)
3309 returnNotOwnedForOwned.reset(new ReturnedNotOwnedForOwned());
3310
Jordy Rosef53e8c72011-08-23 19:43:16 +00003311 CFRefReport *report =
Jordy Rosed6334e12011-08-25 00:34:03 +00003312 new CFRefReport(*returnNotOwnedForOwned,
David Blaikie4e4d0842012-03-11 07:00:24 +00003313 C.getASTContext().getLangOpts(),
Jordy Rose17a38e22011-09-02 05:55:19 +00003314 C.isObjCGCEnabled(), SummaryLog, N, Sym);
Jordan Rose785950e2012-11-02 01:53:40 +00003315 C.emitReport(report);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003316 }
3317 }
3318 }
3319}
3320
Jordy Rose8d228632011-08-23 20:07:14 +00003321//===----------------------------------------------------------------------===//
Jordy Rose910c4052011-09-02 06:44:22 +00003322// Check various ways a symbol can be invalidated.
3323//===----------------------------------------------------------------------===//
3324
Anna Zaks390909c2011-10-06 00:43:15 +00003325void RetainCountChecker::checkBind(SVal loc, SVal val, const Stmt *S,
Jordy Rose910c4052011-09-02 06:44:22 +00003326 CheckerContext &C) const {
3327 // Are we storing to something that causes the value to "escape"?
3328 bool escapes = true;
3329
3330 // A value escapes in three possible cases (this may change):
3331 //
3332 // (1) we are binding to something that is not a memory region.
3333 // (2) we are binding to a memregion that does not have stack storage
3334 // (3) we are binding to a memregion with stack storage that the store
3335 // does not understand.
Ted Kremenek8bef8232012-01-26 21:29:00 +00003336 ProgramStateRef state = C.getState();
Jordy Rose910c4052011-09-02 06:44:22 +00003337
David Blaikiedc84cd52013-02-20 22:23:23 +00003338 if (Optional<loc::MemRegionVal> regionLoc = loc.getAs<loc::MemRegionVal>()) {
Jordy Rose910c4052011-09-02 06:44:22 +00003339 escapes = !regionLoc->getRegion()->hasStackStorage();
3340
3341 if (!escapes) {
3342 // To test (3), generate a new state with the binding added. If it is
3343 // the same state, then it escapes (since the store cannot represent
3344 // the binding).
Anna Zakse7958da2012-05-02 00:15:40 +00003345 // Do this only if we know that the store is not supposed to generate the
3346 // same state.
3347 SVal StoredVal = state->getSVal(regionLoc->getRegion());
3348 if (StoredVal != val)
3349 escapes = (state == (state->bindLoc(*regionLoc, val)));
Jordy Rose910c4052011-09-02 06:44:22 +00003350 }
Ted Kremenekde5b4fb2012-03-27 01:12:45 +00003351 if (!escapes) {
3352 // Case 4: We do not currently model what happens when a symbol is
3353 // assigned to a struct field, so be conservative here and let the symbol
3354 // go. TODO: This could definitely be improved upon.
3355 escapes = !isa<VarRegion>(regionLoc->getRegion());
3356 }
Jordy Rose910c4052011-09-02 06:44:22 +00003357 }
3358
3359 // If our store can represent the binding and we aren't storing to something
3360 // that doesn't have local storage then just return and have the simulation
3361 // state continue as is.
3362 if (!escapes)
3363 return;
3364
3365 // Otherwise, find all symbols referenced by 'val' that we are tracking
3366 // and stop tracking them.
3367 state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
Anna Zaks0bd6b112011-10-26 21:06:34 +00003368 C.addTransition(state);
Jordy Rose910c4052011-09-02 06:44:22 +00003369}
3370
Ted Kremenek8bef8232012-01-26 21:29:00 +00003371ProgramStateRef RetainCountChecker::evalAssume(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003372 SVal Cond,
3373 bool Assumption) const {
3374
3375 // FIXME: We may add to the interface of evalAssume the list of symbols
3376 // whose assumptions have changed. For now we just iterate through the
3377 // bindings and check if any of the tracked symbols are NULL. This isn't
3378 // too bad since the number of symbols we will track in practice are
3379 // probably small and evalAssume is only called at branches and a few
3380 // other places.
Jordan Rose166d5022012-11-02 01:54:06 +00003381 RefBindingsTy B = state->get<RefBindings>();
Jordy Rose910c4052011-09-02 06:44:22 +00003382
3383 if (B.isEmpty())
3384 return state;
3385
3386 bool changed = false;
Jordan Rose166d5022012-11-02 01:54:06 +00003387 RefBindingsTy::Factory &RefBFactory = state->get_context<RefBindings>();
Jordy Rose910c4052011-09-02 06:44:22 +00003388
Jordan Rose166d5022012-11-02 01:54:06 +00003389 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Ted Kremenek47cbd0f2012-09-07 22:31:01 +00003390 // Check if the symbol is null stop tracking the symbol.
Jordan Roseec8d4202012-11-01 00:18:27 +00003391 ConstraintManager &CMgr = state->getConstraintManager();
3392 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
3393 if (AllocFailed.isConstrainedTrue()) {
Jordy Rose910c4052011-09-02 06:44:22 +00003394 changed = true;
3395 B = RefBFactory.remove(B, I.getKey());
3396 }
3397 }
3398
3399 if (changed)
3400 state = state->set<RefBindings>(B);
3401
3402 return state;
3403}
3404
Ted Kremenek8bef8232012-01-26 21:29:00 +00003405ProgramStateRef
3406RetainCountChecker::checkRegionChanges(ProgramStateRef state,
Anna Zaksbf53dfa2012-12-20 00:38:25 +00003407 const InvalidatedSymbols *invalidated,
Jordy Rose910c4052011-09-02 06:44:22 +00003408 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00003409 ArrayRef<const MemRegion *> Regions,
Jordan Rose740d4902012-07-02 19:27:35 +00003410 const CallEvent *Call) const {
Jordy Rose910c4052011-09-02 06:44:22 +00003411 if (!invalidated)
3412 return state;
3413
3414 llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
3415 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
3416 E = ExplicitRegions.end(); I != E; ++I) {
3417 if (const SymbolicRegion *SR = (*I)->StripCasts()->getAs<SymbolicRegion>())
3418 WhitelistedSymbols.insert(SR->getSymbol());
3419 }
3420
Anna Zaksbf53dfa2012-12-20 00:38:25 +00003421 for (InvalidatedSymbols::const_iterator I=invalidated->begin(),
Jordy Rose910c4052011-09-02 06:44:22 +00003422 E = invalidated->end(); I!=E; ++I) {
3423 SymbolRef sym = *I;
3424 if (WhitelistedSymbols.count(sym))
3425 continue;
3426 // Remove any existing reference-count binding.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003427 state = removeRefBinding(state, sym);
Jordy Rose910c4052011-09-02 06:44:22 +00003428 }
3429 return state;
3430}
3431
3432//===----------------------------------------------------------------------===//
Jordy Rose8d228632011-08-23 20:07:14 +00003433// Handle dead symbols and end-of-path.
3434//===----------------------------------------------------------------------===//
3435
Jordan Rose4ee1c552012-12-06 18:58:18 +00003436ProgramStateRef
3437RetainCountChecker::handleAutoreleaseCounts(ProgramStateRef state,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003438 ExplodedNode *Pred,
Jordan Rose2bce86c2012-08-18 00:30:16 +00003439 const ProgramPointTag *Tag,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003440 CheckerContext &Ctx,
Jordy Rose910c4052011-09-02 06:44:22 +00003441 SymbolRef Sym, RefVal V) const {
Jordy Rose8d228632011-08-23 20:07:14 +00003442 unsigned ACnt = V.getAutoreleaseCount();
3443
3444 // No autorelease counts? Nothing to be done.
3445 if (!ACnt)
Jordan Rose4ee1c552012-12-06 18:58:18 +00003446 return state;
Jordy Rose8d228632011-08-23 20:07:14 +00003447
Anna Zaks6a93bd52011-10-25 19:57:11 +00003448 assert(!Ctx.isObjCGCEnabled() && "Autorelease counts in GC mode?");
Jordy Rose8d228632011-08-23 20:07:14 +00003449 unsigned Cnt = V.getCount();
3450
3451 // FIXME: Handle sending 'autorelease' to already released object.
3452
3453 if (V.getKind() == RefVal::ReturnedOwned)
3454 ++Cnt;
3455
3456 if (ACnt <= Cnt) {
3457 if (ACnt == Cnt) {
3458 V.clearCounts();
3459 if (V.getKind() == RefVal::ReturnedOwned)
3460 V = V ^ RefVal::ReturnedNotOwned;
3461 else
3462 V = V ^ RefVal::NotOwned;
3463 } else {
Anna Zaks0217b1d2013-01-31 22:36:17 +00003464 V.setCount(V.getCount() - ACnt);
Jordy Rose8d228632011-08-23 20:07:14 +00003465 V.setAutoreleaseCount(0);
3466 }
Jordan Rose4ee1c552012-12-06 18:58:18 +00003467 return setRefBinding(state, Sym, V);
Jordy Rose8d228632011-08-23 20:07:14 +00003468 }
3469
3470 // Woah! More autorelease counts then retain counts left.
3471 // Emit hard error.
3472 V = V ^ RefVal::ErrorOverAutorelease;
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003473 state = setRefBinding(state, Sym, V);
Jordy Rose8d228632011-08-23 20:07:14 +00003474
Jordan Rosefa06f042012-08-20 18:43:42 +00003475 ExplodedNode *N = Ctx.generateSink(state, Pred, Tag);
Jordan Rose2bce86c2012-08-18 00:30:16 +00003476 if (N) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003477 SmallString<128> sbuf;
Jordy Rose8d228632011-08-23 20:07:14 +00003478 llvm::raw_svector_ostream os(sbuf);
Jordan Rose2545b1d2013-04-23 01:42:25 +00003479 os << "Object was autoreleased ";
Jordy Rose8d228632011-08-23 20:07:14 +00003480 if (V.getAutoreleaseCount() > 1)
Jordan Rose2545b1d2013-04-23 01:42:25 +00003481 os << V.getAutoreleaseCount() << " times but the object ";
3482 else
3483 os << "but ";
3484 os << "has a +" << V.getCount() << " retain count";
Jordy Rose8d228632011-08-23 20:07:14 +00003485
Jordy Rosed6334e12011-08-25 00:34:03 +00003486 if (!overAutorelease)
3487 overAutorelease.reset(new OverAutorelease());
3488
David Blaikie4e4d0842012-03-11 07:00:24 +00003489 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
Jordy Rose8d228632011-08-23 20:07:14 +00003490 CFRefReport *report =
Jordy Rosed6334e12011-08-25 00:34:03 +00003491 new CFRefReport(*overAutorelease, LOpts, /* GCEnabled = */ false,
3492 SummaryLog, N, Sym, os.str());
Jordan Rose785950e2012-11-02 01:53:40 +00003493 Ctx.emitReport(report);
Jordy Rose8d228632011-08-23 20:07:14 +00003494 }
3495
Jordan Rose4ee1c552012-12-06 18:58:18 +00003496 return 0;
Jordy Rose8d228632011-08-23 20:07:14 +00003497}
Jordy Rose38f17d62011-08-23 19:01:07 +00003498
Ted Kremenek8bef8232012-01-26 21:29:00 +00003499ProgramStateRef
3500RetainCountChecker::handleSymbolDeath(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003501 SymbolRef sid, RefVal V,
Jordy Rose38f17d62011-08-23 19:01:07 +00003502 SmallVectorImpl<SymbolRef> &Leaked) const {
Jordy Rose53376122011-08-24 04:48:19 +00003503 bool hasLeak = false;
Jordy Rose38f17d62011-08-23 19:01:07 +00003504 if (V.isOwned())
3505 hasLeak = true;
3506 else if (V.isNotOwned() || V.isReturnedOwned())
3507 hasLeak = (V.getCount() > 0);
3508
3509 if (!hasLeak)
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003510 return removeRefBinding(state, sid);
Jordy Rose38f17d62011-08-23 19:01:07 +00003511
3512 Leaked.push_back(sid);
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003513 return setRefBinding(state, sid, V ^ RefVal::ErrorLeak);
Jordy Rose38f17d62011-08-23 19:01:07 +00003514}
3515
3516ExplodedNode *
Ted Kremenek8bef8232012-01-26 21:29:00 +00003517RetainCountChecker::processLeaks(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003518 SmallVectorImpl<SymbolRef> &Leaked,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003519 CheckerContext &Ctx,
3520 ExplodedNode *Pred) const {
Jordy Rose38f17d62011-08-23 19:01:07 +00003521 // Generate an intermediate node representing the leak point.
Jordan Rose2bce86c2012-08-18 00:30:16 +00003522 ExplodedNode *N = Ctx.addTransition(state, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003523
3524 if (N) {
3525 for (SmallVectorImpl<SymbolRef>::iterator
3526 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3527
David Blaikie4e4d0842012-03-11 07:00:24 +00003528 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
Anna Zaks6a93bd52011-10-25 19:57:11 +00003529 bool GCEnabled = Ctx.isObjCGCEnabled();
Jordy Rose17a38e22011-09-02 05:55:19 +00003530 CFRefBug *BT = Pred ? getLeakWithinFunctionBug(LOpts, GCEnabled)
3531 : getLeakAtReturnBug(LOpts, GCEnabled);
Jordy Rose38f17d62011-08-23 19:01:07 +00003532 assert(BT && "BugType not initialized.");
Jordy Rose20589562011-08-24 22:39:09 +00003533
Jordy Rose17a38e22011-09-02 05:55:19 +00003534 CFRefLeakReport *report = new CFRefLeakReport(*BT, LOpts, GCEnabled,
Ted Kremenek08a838d2013-04-16 21:44:22 +00003535 SummaryLog, N, *I, Ctx,
3536 IncludeAllocationLine);
Jordan Rose785950e2012-11-02 01:53:40 +00003537 Ctx.emitReport(report);
Jordy Rose38f17d62011-08-23 19:01:07 +00003538 }
3539 }
3540
3541 return N;
3542}
3543
Anna Zaks344c77a2013-01-03 00:25:29 +00003544void RetainCountChecker::checkEndFunction(CheckerContext &Ctx) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +00003545 ProgramStateRef state = Ctx.getState();
Jordan Rose166d5022012-11-02 01:54:06 +00003546 RefBindingsTy B = state->get<RefBindings>();
Anna Zaksaf498a22011-10-25 19:56:48 +00003547 ExplodedNode *Pred = Ctx.getPredecessor();
Jordy Rose38f17d62011-08-23 19:01:07 +00003548
Jordan Rosed8188f82013-08-01 22:16:36 +00003549 // Don't process anything within synthesized bodies.
3550 const LocationContext *LCtx = Pred->getLocationContext();
3551 if (LCtx->getAnalysisDeclContext()->isBodyAutosynthesized()) {
3552 assert(LCtx->getParent());
3553 return;
3554 }
3555
Jordan Rose166d5022012-11-02 01:54:06 +00003556 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Jordan Rose4ee1c552012-12-06 18:58:18 +00003557 state = handleAutoreleaseCounts(state, Pred, /*Tag=*/0, Ctx,
3558 I->first, I->second);
Jordy Rose8d228632011-08-23 20:07:14 +00003559 if (!state)
Jordy Rose38f17d62011-08-23 19:01:07 +00003560 return;
3561 }
3562
Ted Kremenek0cf3d472012-02-07 00:24:33 +00003563 // If the current LocationContext has a parent, don't check for leaks.
3564 // We will do that later.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003565 // FIXME: we should instead check for imbalances of the retain/releases,
Ted Kremenek0cf3d472012-02-07 00:24:33 +00003566 // and suggest annotations.
Jordan Rosed8188f82013-08-01 22:16:36 +00003567 if (LCtx->getParent())
Ted Kremenek0cf3d472012-02-07 00:24:33 +00003568 return;
3569
Jordy Rose38f17d62011-08-23 19:01:07 +00003570 B = state->get<RefBindings>();
3571 SmallVector<SymbolRef, 10> Leaked;
3572
Jordan Rose166d5022012-11-02 01:54:06 +00003573 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I)
Jordy Rose8d228632011-08-23 20:07:14 +00003574 state = handleSymbolDeath(state, I->first, I->second, Leaked);
Jordy Rose38f17d62011-08-23 19:01:07 +00003575
Jordan Rose2bce86c2012-08-18 00:30:16 +00003576 processLeaks(state, Leaked, Ctx, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003577}
3578
3579const ProgramPointTag *
Jordy Rose910c4052011-09-02 06:44:22 +00003580RetainCountChecker::getDeadSymbolTag(SymbolRef sym) const {
Jordy Rose38f17d62011-08-23 19:01:07 +00003581 const SimpleProgramPointTag *&tag = DeadSymbolTags[sym];
3582 if (!tag) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003583 SmallString<64> buf;
Jordy Rose38f17d62011-08-23 19:01:07 +00003584 llvm::raw_svector_ostream out(buf);
Anna Zaksf62ceec2011-12-05 18:58:11 +00003585 out << "RetainCountChecker : Dead Symbol : ";
3586 sym->dumpToStream(out);
Jordy Rose38f17d62011-08-23 19:01:07 +00003587 tag = new SimpleProgramPointTag(out.str());
3588 }
3589 return tag;
3590}
3591
Jordy Rose910c4052011-09-02 06:44:22 +00003592void RetainCountChecker::checkDeadSymbols(SymbolReaper &SymReaper,
3593 CheckerContext &C) const {
Jordy Rose38f17d62011-08-23 19:01:07 +00003594 ExplodedNode *Pred = C.getPredecessor();
3595
Ted Kremenek8bef8232012-01-26 21:29:00 +00003596 ProgramStateRef state = C.getState();
Jordan Rose166d5022012-11-02 01:54:06 +00003597 RefBindingsTy B = state->get<RefBindings>();
Jordan Rose4ee1c552012-12-06 18:58:18 +00003598 SmallVector<SymbolRef, 10> Leaked;
Jordy Rose38f17d62011-08-23 19:01:07 +00003599
3600 // Update counts from autorelease pools
3601 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3602 E = SymReaper.dead_end(); I != E; ++I) {
3603 SymbolRef Sym = *I;
3604 if (const RefVal *T = B.lookup(Sym)){
3605 // Use the symbol as the tag.
3606 // FIXME: This might not be as unique as we would like.
Jordan Rose2bce86c2012-08-18 00:30:16 +00003607 const ProgramPointTag *Tag = getDeadSymbolTag(Sym);
Jordan Rose4ee1c552012-12-06 18:58:18 +00003608 state = handleAutoreleaseCounts(state, Pred, Tag, C, Sym, *T);
Jordy Rose8d228632011-08-23 20:07:14 +00003609 if (!state)
Jordy Rose38f17d62011-08-23 19:01:07 +00003610 return;
Jordan Rose4ee1c552012-12-06 18:58:18 +00003611
3612 // Fetch the new reference count from the state, and use it to handle
3613 // this symbol.
3614 state = handleSymbolDeath(state, *I, *getRefBinding(state, Sym), Leaked);
Jordy Rose38f17d62011-08-23 19:01:07 +00003615 }
3616 }
3617
Jordan Rose4ee1c552012-12-06 18:58:18 +00003618 if (Leaked.empty()) {
3619 C.addTransition(state);
3620 return;
Jordy Rose38f17d62011-08-23 19:01:07 +00003621 }
3622
Jordan Rose2bce86c2012-08-18 00:30:16 +00003623 Pred = processLeaks(state, Leaked, C, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003624
3625 // Did we cache out?
3626 if (!Pred)
3627 return;
3628
3629 // Now generate a new node that nukes the old bindings.
Jordan Rose4ee1c552012-12-06 18:58:18 +00003630 // The only bindings left at this point are the leaked symbols.
Jordan Rose166d5022012-11-02 01:54:06 +00003631 RefBindingsTy::Factory &F = state->get_context<RefBindings>();
Jordan Rose4ee1c552012-12-06 18:58:18 +00003632 B = state->get<RefBindings>();
Jordy Rose38f17d62011-08-23 19:01:07 +00003633
Jordan Rose4ee1c552012-12-06 18:58:18 +00003634 for (SmallVectorImpl<SymbolRef>::iterator I = Leaked.begin(),
3635 E = Leaked.end();
3636 I != E; ++I)
Jordy Rose38f17d62011-08-23 19:01:07 +00003637 B = F.remove(B, *I);
3638
3639 state = state->set<RefBindings>(B);
Anna Zaks0bd6b112011-10-26 21:06:34 +00003640 C.addTransition(state, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003641}
3642
Ted Kremenek8bef8232012-01-26 21:29:00 +00003643void RetainCountChecker::printState(raw_ostream &Out, ProgramStateRef State,
Jordy Rose910c4052011-09-02 06:44:22 +00003644 const char *NL, const char *Sep) const {
Jordy Rosedbd658e2011-08-28 19:11:56 +00003645
Jordan Rose166d5022012-11-02 01:54:06 +00003646 RefBindingsTy B = State->get<RefBindings>();
Jordy Rosedbd658e2011-08-28 19:11:56 +00003647
Ted Kremenek65a08922013-03-28 18:43:18 +00003648 if (B.isEmpty())
3649 return;
3650
3651 Out << Sep << NL;
Jordy Rosedbd658e2011-08-28 19:11:56 +00003652
Jordan Rose166d5022012-11-02 01:54:06 +00003653 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Jordy Rosedbd658e2011-08-28 19:11:56 +00003654 Out << I->first << " : ";
3655 I->second.print(Out);
3656 Out << NL;
3657 }
Jordy Rosedbd658e2011-08-28 19:11:56 +00003658}
3659
3660//===----------------------------------------------------------------------===//
Jordy Rose910c4052011-09-02 06:44:22 +00003661// Checker registration.
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00003662//===----------------------------------------------------------------------===//
3663
Jordy Rose17a38e22011-09-02 05:55:19 +00003664void ento::registerRetainCountChecker(CheckerManager &Mgr) {
Ted Kremenek08a838d2013-04-16 21:44:22 +00003665 Mgr.registerChecker<RetainCountChecker>(Mgr.getAnalyzerOptions());
Jordy Rose17a38e22011-09-02 05:55:19 +00003666}
3667
Ted Kremenek53c7ea12013-08-14 23:41:49 +00003668//===----------------------------------------------------------------------===//
3669// Implementation of the CallEffects API.
3670//===----------------------------------------------------------------------===//
3671
3672namespace clang { namespace ento { namespace objc_retain {
3673
3674// This is a bit gross, but it allows us to populate CallEffects without
3675// creating a bunch of accessors. This kind is very localized, so the
3676// damage of this macro is limited.
3677#define createCallEffect(D, KIND)\
3678 ASTContext &Ctx = D->getASTContext();\
3679 LangOptions L = Ctx.getLangOpts();\
3680 RetainSummaryManager M(Ctx, L.GCOnly, L.ObjCAutoRefCount);\
3681 const RetainSummary *S = M.get ## KIND ## Summary(D);\
3682 CallEffects CE(S->getRetEffect());\
3683 CE.Receiver = S->getReceiverEffect();\
Ted Kremenek21043742013-08-16 23:14:22 +00003684 unsigned N = D->param_size();\
Ted Kremenek53c7ea12013-08-14 23:41:49 +00003685 for (unsigned i = 0; i < N; ++i) {\
3686 CE.Args.push_back(S->getArg(i));\
3687 }
3688
3689CallEffects CallEffects::getEffect(const ObjCMethodDecl *MD) {
3690 createCallEffect(MD, Method);
3691 return CE;
3692}
3693
3694CallEffects CallEffects::getEffect(const FunctionDecl *FD) {
3695 createCallEffect(FD, Function);
3696 return CE;
3697}
3698
3699#undef createCallEffect
3700
3701}}}