blob: be2f2205d13b64b4f182eb5c7edf1f60751a894c [file] [log] [blame]
Jordy Rose910c4052011-09-02 06:44:22 +00001//==-- RetainCountChecker.cpp - Checks for leaks and other issues -*- C++ -*--//
Ted Kremenek2fff37e2008-03-06 00:08:09 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Jordy Rose910c4052011-09-02 06:44:22 +000010// This file defines the methods for RetainCountChecker, which implements
11// a reference count checker for Core Foundation and Cocoa on (Mac OS X).
Ted Kremenek2fff37e2008-03-06 00:08:09 +000012//
13//===----------------------------------------------------------------------===//
14
Jordy Rose910c4052011-09-02 06:44:22 +000015#include "ClangSACheckers.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000016#include "clang/AST/Attr.h"
Ted Kremenekb2771592011-03-30 17:41:19 +000017#include "clang/AST/DeclCXX.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000018#include "clang/AST/DeclObjC.h"
19#include "clang/AST/ParentMap.h"
20#include "clang/Analysis/DomainSpecific/CocoaConventions.h"
Ted Kremenek0b526b42010-02-18 00:05:58 +000021#include "clang/Basic/LangOptions.h"
22#include "clang/Basic/SourceManager.h"
Ted Kremenek9b663712011-02-10 01:03:03 +000023#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
24#include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000025#include "clang/StaticAnalyzer/Core/Checker.h"
26#include "clang/StaticAnalyzer/Core/CheckerManager.h"
Jordan Rosef540c542012-07-26 21:39:41 +000027#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
Jordy Rose910c4052011-09-02 06:44:22 +000028#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
Ted Kremenek18c66fd2011-08-15 22:09:50 +000029#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
Ted Kremenek9b663712011-02-10 01:03:03 +000030#include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
Ted Kremenek5774e392013-08-14 23:41:46 +000031#include "clang/StaticAnalyzer/Checkers/ObjCRetainCount.h"
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000032#include "llvm/ADT/DenseMap.h"
33#include "llvm/ADT/FoldingSet.h"
Ted Kremenek6d348932008-10-21 15:53:15 +000034#include "llvm/ADT/ImmutableList.h"
Ted Kremenek0b526b42010-02-18 00:05:58 +000035#include "llvm/ADT/ImmutableMap.h"
Ted Kremenek6ed9afc2008-05-16 18:33:44 +000036#include "llvm/ADT/STLExtras.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000037#include "llvm/ADT/SmallString.h"
Ted Kremenek0b526b42010-02-18 00:05:58 +000038#include "llvm/ADT/StringExtras.h"
Chris Lattner5f9e2722011-07-23 10:55:15 +000039#include <cstdarg>
Ted Kremenek2fff37e2008-03-06 00:08:09 +000040
Ted Kremenek08a838d2013-04-16 21:44:22 +000041#include "AllocationDiagnostics.h"
42
Ted Kremenek2fff37e2008-03-06 00:08:09 +000043using namespace clang;
Ted Kremenek9ef65372010-12-23 07:20:52 +000044using namespace ento;
Ted Kremenek5774e392013-08-14 23:41:46 +000045using namespace objc_retain;
Ted Kremeneka64e89b2010-01-27 06:13:48 +000046using llvm::StrInStrNoCase;
Ted Kremenek4c79e552008-11-05 16:54:44 +000047
Ted Kremenek05cbe1a2008-04-09 23:49:11 +000048//===----------------------------------------------------------------------===//
Ted Kremenek5774e392013-08-14 23:41:46 +000049// Adapters for FoldingSet.
Ted Kremenek05cbe1a2008-04-09 23:49:11 +000050//===----------------------------------------------------------------------===//
51
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000052namespace llvm {
Ted Kremenekb77449c2009-05-03 05:20:50 +000053template <> struct FoldingSetTrait<ArgEffect> {
Ted Kremenek5774e392013-08-14 23:41:46 +000054static inline void Profile(const ArgEffect X, FoldingSetNodeID &ID) {
Ted Kremenekb77449c2009-05-03 05:20:50 +000055 ID.AddInteger((unsigned) X);
56}
Ted Kremenek553cf182008-06-25 21:21:56 +000057};
Ted Kremenek5774e392013-08-14 23:41:46 +000058template <> struct FoldingSetTrait<RetEffect> {
59 static inline void Profile(const RetEffect &X, FoldingSetNodeID &ID) {
60 ID.AddInteger((unsigned) X.getKind());
61 ID.AddInteger((unsigned) X.getObjKind());
62}
63};
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000064} // end llvm namespace
65
Ted Kremenek5774e392013-08-14 23:41:46 +000066//===----------------------------------------------------------------------===//
67// Reference-counting logic (typestate + counts).
68//===----------------------------------------------------------------------===//
69
Ted Kremenekb77449c2009-05-03 05:20:50 +000070/// ArgEffects summarizes the effects of a function/method call on all of
71/// its arguments.
72typedef llvm::ImmutableMap<unsigned,ArgEffect> ArgEffects;
73
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000074namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +000075class RefVal {
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +000076public:
77 enum Kind {
78 Owned = 0, // Owning reference.
79 NotOwned, // Reference is not owned by still valid (not freed).
80 Released, // Object has been released.
81 ReturnedOwned, // Returned object passes ownership to caller.
82 ReturnedNotOwned, // Return object does not pass ownership to caller.
83 ERROR_START,
84 ErrorDeallocNotOwned, // -dealloc called on non-owned object.
85 ErrorDeallocGC, // Calling -dealloc with GC enabled.
86 ErrorUseAfterRelease, // Object used after released.
87 ErrorReleaseNotOwned, // Release of an object that was not owned.
88 ERROR_LEAK_START,
89 ErrorLeak, // A memory leak due to excessive reference counts.
90 ErrorLeakReturned, // A memory leak due to the returning method not having
91 // the correct naming conventions.
92 ErrorGCLeakReturned,
93 ErrorOverAutorelease,
94 ErrorReturnedNotOwned
95 };
Ted Kremenekdcee3ce2010-07-01 20:16:50 +000096
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +000097private:
98 Kind kind;
99 RetEffect::ObjKind okind;
100 unsigned Cnt;
101 unsigned ACnt;
102 QualType T;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000103
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000104 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, unsigned acnt, QualType t)
105 : kind(k), okind(o), Cnt(cnt), ACnt(acnt), T(t) {}
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000106
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000107public:
108 Kind getKind() const { return kind; }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000109
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000110 RetEffect::ObjKind getObjKind() const { return okind; }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000111
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000112 unsigned getCount() const { return Cnt; }
113 unsigned getAutoreleaseCount() const { return ACnt; }
114 unsigned getCombinedCounts() const { return Cnt + ACnt; }
115 void clearCounts() { Cnt = 0; ACnt = 0; }
116 void setCount(unsigned i) { Cnt = i; }
117 void setAutoreleaseCount(unsigned i) { ACnt = i; }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000118
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000119 QualType getType() const { return T; }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000120
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000121 bool isOwned() const {
122 return getKind() == Owned;
123 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000124
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000125 bool isNotOwned() const {
126 return getKind() == NotOwned;
127 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000128
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000129 bool isReturnedOwned() const {
130 return getKind() == ReturnedOwned;
131 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000132
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000133 bool isReturnedNotOwned() const {
134 return getKind() == ReturnedNotOwned;
135 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000136
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000137 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
138 unsigned Count = 1) {
139 return RefVal(Owned, o, Count, 0, t);
140 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000141
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000142 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
143 unsigned Count = 0) {
144 return RefVal(NotOwned, o, Count, 0, t);
145 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000146
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000147 // Comparison, profiling, and pretty-printing.
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000148
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000149 bool operator==(const RefVal& X) const {
150 return kind == X.kind && Cnt == X.Cnt && T == X.T && ACnt == X.ACnt;
151 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000152
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000153 RefVal operator-(size_t i) const {
154 return RefVal(getKind(), getObjKind(), getCount() - i,
155 getAutoreleaseCount(), getType());
156 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000157
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000158 RefVal operator+(size_t i) const {
159 return RefVal(getKind(), getObjKind(), getCount() + i,
160 getAutoreleaseCount(), getType());
161 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000162
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000163 RefVal operator^(Kind k) const {
164 return RefVal(k, getObjKind(), getCount(), getAutoreleaseCount(),
165 getType());
166 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000167
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000168 RefVal autorelease() const {
169 return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount()+1,
170 getType());
171 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000172
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000173 void Profile(llvm::FoldingSetNodeID& ID) const {
174 ID.AddInteger((unsigned) kind);
175 ID.AddInteger(Cnt);
176 ID.AddInteger(ACnt);
177 ID.Add(T);
178 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000179
Ted Kremenek9c378f72011-08-12 23:37:29 +0000180 void print(raw_ostream &Out) const;
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000181};
182
Ted Kremenek9c378f72011-08-12 23:37:29 +0000183void RefVal::print(raw_ostream &Out) const {
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000184 if (!T.isNull())
Jordy Rosedbd658e2011-08-28 19:11:56 +0000185 Out << "Tracked " << T.getAsString() << '/';
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000186
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000187 switch (getKind()) {
Jordy Rose910c4052011-09-02 06:44:22 +0000188 default: llvm_unreachable("Invalid RefVal kind");
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000189 case Owned: {
190 Out << "Owned";
191 unsigned cnt = getCount();
192 if (cnt) Out << " (+ " << cnt << ")";
193 break;
194 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000195
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000196 case NotOwned: {
197 Out << "NotOwned";
198 unsigned cnt = getCount();
199 if (cnt) Out << " (+ " << cnt << ")";
200 break;
201 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000202
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000203 case ReturnedOwned: {
204 Out << "ReturnedOwned";
205 unsigned cnt = getCount();
206 if (cnt) Out << " (+ " << cnt << ")";
207 break;
208 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000209
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000210 case ReturnedNotOwned: {
211 Out << "ReturnedNotOwned";
212 unsigned cnt = getCount();
213 if (cnt) Out << " (+ " << cnt << ")";
214 break;
215 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000216
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000217 case Released:
218 Out << "Released";
219 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000220
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000221 case ErrorDeallocGC:
222 Out << "-dealloc (GC)";
223 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000224
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000225 case ErrorDeallocNotOwned:
226 Out << "-dealloc (not-owned)";
227 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000228
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000229 case ErrorLeak:
230 Out << "Leaked";
231 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000232
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000233 case ErrorLeakReturned:
234 Out << "Leaked (Bad naming)";
235 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000236
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000237 case ErrorGCLeakReturned:
238 Out << "Leaked (GC-ed at return)";
239 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000240
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000241 case ErrorUseAfterRelease:
242 Out << "Use-After-Release [ERROR]";
243 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000244
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000245 case ErrorReleaseNotOwned:
246 Out << "Release of Not-Owned [ERROR]";
247 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000248
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000249 case RefVal::ErrorOverAutorelease:
Jordan Rose2545b1d2013-04-23 01:42:25 +0000250 Out << "Over-autoreleased";
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000251 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000252
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000253 case RefVal::ErrorReturnedNotOwned:
254 Out << "Non-owned object returned instead of owned";
255 break;
256 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000257
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000258 if (ACnt) {
259 Out << " [ARC +" << ACnt << ']';
260 }
261}
262} //end anonymous namespace
263
264//===----------------------------------------------------------------------===//
265// RefBindings - State used to track object reference counts.
266//===----------------------------------------------------------------------===//
267
Jordan Rose166d5022012-11-02 01:54:06 +0000268REGISTER_MAP_WITH_PROGRAMSTATE(RefBindings, SymbolRef, RefVal)
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000269
Anna Zaks8d6b43c2012-08-14 00:36:15 +0000270static inline const RefVal *getRefBinding(ProgramStateRef State,
271 SymbolRef Sym) {
272 return State->get<RefBindings>(Sym);
273}
274
275static inline ProgramStateRef setRefBinding(ProgramStateRef State,
276 SymbolRef Sym, RefVal Val) {
277 return State->set<RefBindings>(Sym, Val);
278}
279
280static ProgramStateRef removeRefBinding(ProgramStateRef State, SymbolRef Sym) {
281 return State->remove<RefBindings>(Sym);
282}
283
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000284//===----------------------------------------------------------------------===//
Jordy Rose910c4052011-09-02 06:44:22 +0000285// Function/Method behavior summaries.
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000286//===----------------------------------------------------------------------===//
287
288namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000289class RetainSummary {
Jordy Roseef945882012-03-18 01:26:10 +0000290 /// Args - a map of (index, ArgEffect) pairs, where index
Ted Kremenek1bffd742008-05-06 15:44:25 +0000291 /// specifies the argument (starting from 0). This can be sparsely
292 /// populated; arguments with no entry in Args use 'DefaultArgEffect'.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000293 ArgEffects Args;
Mike Stump1eb44332009-09-09 15:08:12 +0000294
Ted Kremenek1bffd742008-05-06 15:44:25 +0000295 /// DefaultArgEffect - The default ArgEffect to apply to arguments that
296 /// do not have an entry in Args.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000297 ArgEffect DefaultArgEffect;
Mike Stump1eb44332009-09-09 15:08:12 +0000298
Ted Kremenek553cf182008-06-25 21:21:56 +0000299 /// Receiver - If this summary applies to an Objective-C message expression,
300 /// this is the effect applied to the state of the receiver.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000301 ArgEffect Receiver;
Mike Stump1eb44332009-09-09 15:08:12 +0000302
Ted Kremenek553cf182008-06-25 21:21:56 +0000303 /// Ret - The effect on the return value. Used to indicate if the
Jordy Rose76c506f2011-08-21 21:58:18 +0000304 /// function/method call returns a new tracked symbol.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000305 RetEffect Ret;
Mike Stump1eb44332009-09-09 15:08:12 +0000306
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000307public:
Ted Kremenekb77449c2009-05-03 05:20:50 +0000308 RetainSummary(ArgEffects A, RetEffect R, ArgEffect defaultEff,
Jordy Rosee62e87b2011-08-20 20:55:40 +0000309 ArgEffect ReceiverEff)
310 : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000311
Ted Kremenek553cf182008-06-25 21:21:56 +0000312 /// getArg - Return the argument effect on the argument specified by
313 /// idx (starting from 0).
Ted Kremenek1ac08d62008-03-11 17:48:22 +0000314 ArgEffect getArg(unsigned idx) const {
Ted Kremenekb77449c2009-05-03 05:20:50 +0000315 if (const ArgEffect *AE = Args.lookup(idx))
316 return *AE;
Mike Stump1eb44332009-09-09 15:08:12 +0000317
Ted Kremenek1bffd742008-05-06 15:44:25 +0000318 return DefaultArgEffect;
Ted Kremenek1ac08d62008-03-11 17:48:22 +0000319 }
Ted Kremenek53c7ea12013-08-14 23:41:49 +0000320
321 /// Return the number of argument effects. This is O(n) in the number
322 /// of arguments.
323 unsigned getNumArgs() const {
Benjamin Kramera1da6b22013-08-16 21:57:14 +0000324 return std::distance(Args.begin(), Args.end());
Ted Kremenek53c7ea12013-08-14 23:41:49 +0000325 }
Ted Kremenek11fe1752011-01-27 18:43:03 +0000326
327 void addArg(ArgEffects::Factory &af, unsigned idx, ArgEffect e) {
328 Args = af.add(Args, idx, e);
329 }
Mike Stump1eb44332009-09-09 15:08:12 +0000330
Ted Kremenek885c27b2009-05-04 05:31:22 +0000331 /// setDefaultArgEffect - Set the default argument effect.
332 void setDefaultArgEffect(ArgEffect E) {
333 DefaultArgEffect = E;
334 }
Mike Stump1eb44332009-09-09 15:08:12 +0000335
Ted Kremenek553cf182008-06-25 21:21:56 +0000336 /// getRetEffect - Returns the effect on the return value of the call.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000337 RetEffect getRetEffect() const { return Ret; }
Mike Stump1eb44332009-09-09 15:08:12 +0000338
Ted Kremenek885c27b2009-05-04 05:31:22 +0000339 /// setRetEffect - Set the effect of the return value of the call.
340 void setRetEffect(RetEffect E) { Ret = E; }
Mike Stump1eb44332009-09-09 15:08:12 +0000341
Ted Kremenek12b94342011-01-27 06:54:14 +0000342
343 /// Sets the effect on the receiver of the message.
344 void setReceiverEffect(ArgEffect e) { Receiver = e; }
345
Ted Kremenek553cf182008-06-25 21:21:56 +0000346 /// getReceiverEffect - Returns the effect on the receiver of the call.
347 /// This is only meaningful if the summary applies to an ObjCMessageExpr*.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000348 ArgEffect getReceiverEffect() const { return Receiver; }
Jordy Rose4df54fe2011-08-23 04:27:15 +0000349
350 /// Test if two retain summaries are identical. Note that merely equivalent
351 /// summaries are not necessarily identical (for example, if an explicit
352 /// argument effect matches the default effect).
353 bool operator==(const RetainSummary &Other) const {
354 return Args == Other.Args && DefaultArgEffect == Other.DefaultArgEffect &&
355 Receiver == Other.Receiver && Ret == Other.Ret;
356 }
Jordy Roseef945882012-03-18 01:26:10 +0000357
358 /// Profile this summary for inclusion in a FoldingSet.
359 void Profile(llvm::FoldingSetNodeID& ID) const {
360 ID.Add(Args);
361 ID.Add(DefaultArgEffect);
362 ID.Add(Receiver);
363 ID.Add(Ret);
364 }
365
366 /// A retain summary is simple if it has no ArgEffects other than the default.
367 bool isSimple() const {
368 return Args.isEmpty();
369 }
Jordan Rose4531b7d2012-07-02 19:27:43 +0000370
371private:
372 ArgEffects getArgEffects() const { return Args; }
373 ArgEffect getDefaultArgEffect() const { return DefaultArgEffect; }
374
375 friend class RetainSummaryManager;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000376};
Ted Kremenek4f22a782008-06-23 23:30:29 +0000377} // end anonymous namespace
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000378
Ted Kremenek553cf182008-06-25 21:21:56 +0000379//===----------------------------------------------------------------------===//
380// Data structures for constructing summaries.
381//===----------------------------------------------------------------------===//
Ted Kremenek53301ba2008-06-24 03:49:48 +0000382
Ted Kremenek553cf182008-06-25 21:21:56 +0000383namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000384class ObjCSummaryKey {
Ted Kremenek553cf182008-06-25 21:21:56 +0000385 IdentifierInfo* II;
386 Selector S;
Mike Stump1eb44332009-09-09 15:08:12 +0000387public:
Ted Kremenek553cf182008-06-25 21:21:56 +0000388 ObjCSummaryKey(IdentifierInfo* ii, Selector s)
389 : II(ii), S(s) {}
390
Ted Kremenek9c378f72011-08-12 23:37:29 +0000391 ObjCSummaryKey(const ObjCInterfaceDecl *d, Selector s)
Ted Kremenek553cf182008-06-25 21:21:56 +0000392 : II(d ? d->getIdentifier() : 0), S(s) {}
Ted Kremenek70b6a832009-05-13 18:16:01 +0000393
Ted Kremenek553cf182008-06-25 21:21:56 +0000394 ObjCSummaryKey(Selector s)
395 : II(0), S(s) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000396
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000397 IdentifierInfo *getIdentifier() const { return II; }
Ted Kremenek553cf182008-06-25 21:21:56 +0000398 Selector getSelector() const { return S; }
399};
Ted Kremenek4f22a782008-06-23 23:30:29 +0000400}
401
402namespace llvm {
Ted Kremenek553cf182008-06-25 21:21:56 +0000403template <> struct DenseMapInfo<ObjCSummaryKey> {
404 static inline ObjCSummaryKey getEmptyKey() {
405 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
406 DenseMapInfo<Selector>::getEmptyKey());
407 }
Mike Stump1eb44332009-09-09 15:08:12 +0000408
Ted Kremenek553cf182008-06-25 21:21:56 +0000409 static inline ObjCSummaryKey getTombstoneKey() {
410 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
Mike Stump1eb44332009-09-09 15:08:12 +0000411 DenseMapInfo<Selector>::getTombstoneKey());
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 unsigned getHashValue(const ObjCSummaryKey &V) {
Benjamin Kramer28b23072012-05-27 13:28:44 +0000415 typedef std::pair<IdentifierInfo*, Selector> PairTy;
416 return DenseMapInfo<PairTy>::getHashValue(PairTy(V.getIdentifier(),
417 V.getSelector()));
Ted Kremenek553cf182008-06-25 21:21:56 +0000418 }
Mike Stump1eb44332009-09-09 15:08:12 +0000419
Ted Kremenek553cf182008-06-25 21:21:56 +0000420 static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
Benjamin Kramer28b23072012-05-27 13:28:44 +0000421 return LHS.getIdentifier() == RHS.getIdentifier() &&
422 LHS.getSelector() == RHS.getSelector();
Ted Kremenek553cf182008-06-25 21:21:56 +0000423 }
Mike Stump1eb44332009-09-09 15:08:12 +0000424
Ted Kremenek553cf182008-06-25 21:21:56 +0000425};
Chris Lattner06159e82009-12-15 07:26:51 +0000426template <>
427struct isPodLike<ObjCSummaryKey> { static const bool value = true; };
Ted Kremenek4f22a782008-06-23 23:30:29 +0000428} // end llvm namespace
Mike Stump1eb44332009-09-09 15:08:12 +0000429
Ted Kremenek4f22a782008-06-23 23:30:29 +0000430namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000431class ObjCSummaryCache {
Ted Kremenek93edbc52011-10-05 23:54:29 +0000432 typedef llvm::DenseMap<ObjCSummaryKey, const RetainSummary *> MapTy;
Ted Kremenek553cf182008-06-25 21:21:56 +0000433 MapTy M;
434public:
435 ObjCSummaryCache() {}
Mike Stump1eb44332009-09-09 15:08:12 +0000436
Ted Kremenek93edbc52011-10-05 23:54:29 +0000437 const RetainSummary * find(const ObjCInterfaceDecl *D, Selector S) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000438 // Do a lookup with the (D,S) pair. If we find a match return
439 // the iterator.
440 ObjCSummaryKey K(D, S);
441 MapTy::iterator I = M.find(K);
Mike Stump1eb44332009-09-09 15:08:12 +0000442
Jordan Rose4531b7d2012-07-02 19:27:43 +0000443 if (I != M.end())
Ted Kremenek614cc542009-07-21 23:27:57 +0000444 return I->second;
Jordan Rose4531b7d2012-07-02 19:27:43 +0000445 if (!D)
446 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +0000447
Ted Kremenek553cf182008-06-25 21:21:56 +0000448 // Walk the super chain. If we find a hit with a parent, we'll end
449 // up returning that summary. We actually allow that key (null,S), as
450 // we cache summaries for the null ObjCInterfaceDecl* to allow us to
451 // generate initial summaries without having to worry about NSObject
452 // being declared.
453 // FIXME: We may change this at some point.
Ted Kremenek9c378f72011-08-12 23:37:29 +0000454 for (ObjCInterfaceDecl *C=D->getSuperClass() ;; C=C->getSuperClass()) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000455 if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
456 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000457
Ted Kremenek553cf182008-06-25 21:21:56 +0000458 if (!C)
Ted Kremenek614cc542009-07-21 23:27:57 +0000459 return NULL;
Ted Kremenek553cf182008-06-25 21:21:56 +0000460 }
Mike Stump1eb44332009-09-09 15:08:12 +0000461
462 // Cache the summary with original key to make the next lookup faster
Ted Kremenek553cf182008-06-25 21:21:56 +0000463 // and return the iterator.
Ted Kremenek93edbc52011-10-05 23:54:29 +0000464 const RetainSummary *Summ = I->second;
Ted Kremenek614cc542009-07-21 23:27:57 +0000465 M[K] = Summ;
466 return Summ;
Ted Kremenek553cf182008-06-25 21:21:56 +0000467 }
Mike Stump1eb44332009-09-09 15:08:12 +0000468
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000469 const RetainSummary *find(IdentifierInfo* II, Selector S) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000470 // FIXME: Class method lookup. Right now we dont' have a good way
471 // of going between IdentifierInfo* and the class hierarchy.
Ted Kremenek614cc542009-07-21 23:27:57 +0000472 MapTy::iterator I = M.find(ObjCSummaryKey(II, S));
Mike Stump1eb44332009-09-09 15:08:12 +0000473
Ted Kremenek614cc542009-07-21 23:27:57 +0000474 if (I == M.end())
475 I = M.find(ObjCSummaryKey(S));
Mike Stump1eb44332009-09-09 15:08:12 +0000476
Ted Kremenek614cc542009-07-21 23:27:57 +0000477 return I == M.end() ? NULL : I->second;
Ted Kremenek553cf182008-06-25 21:21:56 +0000478 }
Mike Stump1eb44332009-09-09 15:08:12 +0000479
Ted Kremenek93edbc52011-10-05 23:54:29 +0000480 const RetainSummary *& operator[](ObjCSummaryKey K) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000481 return M[K];
482 }
Mike Stump1eb44332009-09-09 15:08:12 +0000483
Ted Kremenek93edbc52011-10-05 23:54:29 +0000484 const RetainSummary *& operator[](Selector S) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000485 return M[ ObjCSummaryKey(S) ];
486 }
Mike Stump1eb44332009-09-09 15:08:12 +0000487};
Ted Kremenek553cf182008-06-25 21:21:56 +0000488} // end anonymous namespace
489
490//===----------------------------------------------------------------------===//
491// Data structures for managing collections of summaries.
492//===----------------------------------------------------------------------===//
493
494namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000495class RetainSummaryManager {
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000496
497 //==-----------------------------------------------------------------==//
498 // Typedefs.
499 //==-----------------------------------------------------------------==//
Mike Stump1eb44332009-09-09 15:08:12 +0000500
Ted Kremenek93edbc52011-10-05 23:54:29 +0000501 typedef llvm::DenseMap<const FunctionDecl*, const RetainSummary *>
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000502 FuncSummariesTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000503
Ted Kremenek4f22a782008-06-23 23:30:29 +0000504 typedef ObjCSummaryCache ObjCMethodSummariesTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000505
Jordy Roseef945882012-03-18 01:26:10 +0000506 typedef llvm::FoldingSetNodeWrapper<RetainSummary> CachedSummaryNode;
507
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000508 //==-----------------------------------------------------------------==//
509 // Data.
510 //==-----------------------------------------------------------------==//
Mike Stump1eb44332009-09-09 15:08:12 +0000511
Ted Kremenek553cf182008-06-25 21:21:56 +0000512 /// Ctx - The ASTContext object for the analyzed ASTs.
Ted Kremenek9c378f72011-08-12 23:37:29 +0000513 ASTContext &Ctx;
Ted Kremenek179064e2008-07-01 17:21:27 +0000514
Ted Kremenek553cf182008-06-25 21:21:56 +0000515 /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
Ted Kremenek377e2302008-04-29 05:33:51 +0000516 const bool GCEnabled;
Mike Stump1eb44332009-09-09 15:08:12 +0000517
John McCallf85e1932011-06-15 23:02:42 +0000518 /// Records whether or not the analyzed code runs in ARC mode.
519 const bool ARCEnabled;
520
Ted Kremenek553cf182008-06-25 21:21:56 +0000521 /// FuncSummaries - A map from FunctionDecls to summaries.
Mike Stump1eb44332009-09-09 15:08:12 +0000522 FuncSummariesTy FuncSummaries;
523
Ted Kremenek553cf182008-06-25 21:21:56 +0000524 /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
525 /// to summaries.
Ted Kremenek1f180c32008-06-23 22:21:20 +0000526 ObjCMethodSummariesTy ObjCClassMethodSummaries;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000527
Ted Kremenek553cf182008-06-25 21:21:56 +0000528 /// ObjCMethodSummaries - A map from selectors to summaries.
Ted Kremenek1f180c32008-06-23 22:21:20 +0000529 ObjCMethodSummariesTy ObjCMethodSummaries;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000530
Ted Kremenek553cf182008-06-25 21:21:56 +0000531 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
532 /// and all other data used by the checker.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000533 llvm::BumpPtrAllocator BPAlloc;
Mike Stump1eb44332009-09-09 15:08:12 +0000534
Ted Kremenekb77449c2009-05-03 05:20:50 +0000535 /// AF - A factory for ArgEffects objects.
Mike Stump1eb44332009-09-09 15:08:12 +0000536 ArgEffects::Factory AF;
537
Ted Kremenek553cf182008-06-25 21:21:56 +0000538 /// ScratchArgs - A holding buffer for construct ArgEffects.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000539 ArgEffects ScratchArgs;
Mike Stump1eb44332009-09-09 15:08:12 +0000540
Ted Kremenekec315332009-05-07 23:40:42 +0000541 /// ObjCAllocRetE - Default return effect for methods returning Objective-C
542 /// objects.
543 RetEffect ObjCAllocRetE;
Ted Kremenek547d4952009-06-05 23:18:01 +0000544
Mike Stump1eb44332009-09-09 15:08:12 +0000545 /// ObjCInitRetE - Default return effect for init methods returning
Ted Kremenekac02f202009-08-20 05:13:36 +0000546 /// Objective-C objects.
Ted Kremenek547d4952009-06-05 23:18:01 +0000547 RetEffect ObjCInitRetE;
Mike Stump1eb44332009-09-09 15:08:12 +0000548
Jordy Roseef945882012-03-18 01:26:10 +0000549 /// SimpleSummaries - Used for uniquing summaries that don't have special
550 /// effects.
551 llvm::FoldingSet<CachedSummaryNode> SimpleSummaries;
Mike Stump1eb44332009-09-09 15:08:12 +0000552
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000553 //==-----------------------------------------------------------------==//
554 // Methods.
555 //==-----------------------------------------------------------------==//
Mike Stump1eb44332009-09-09 15:08:12 +0000556
Ted Kremenek553cf182008-06-25 21:21:56 +0000557 /// getArgEffects - Returns a persistent ArgEffects object based on the
558 /// data in ScratchArgs.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000559 ArgEffects getArgEffects();
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000560
Mike Stump1eb44332009-09-09 15:08:12 +0000561 enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
Ted Kremenek93edbc52011-10-05 23:54:29 +0000562
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000563 const RetainSummary *getUnarySummary(const FunctionType* FT,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000564 UnaryFuncKind func);
Mike Stump1eb44332009-09-09 15:08:12 +0000565
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000566 const RetainSummary *getCFSummaryCreateRule(const FunctionDecl *FD);
567 const RetainSummary *getCFSummaryGetRule(const FunctionDecl *FD);
568 const RetainSummary *getCFCreateGetRuleSummary(const FunctionDecl *FD);
Mike Stump1eb44332009-09-09 15:08:12 +0000569
Jordy Roseef945882012-03-18 01:26:10 +0000570 const RetainSummary *getPersistentSummary(const RetainSummary &OldSumm);
Ted Kremenek706522f2008-10-29 04:07:07 +0000571
Jordy Roseef945882012-03-18 01:26:10 +0000572 const RetainSummary *getPersistentSummary(RetEffect RetEff,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000573 ArgEffect ReceiverEff = DoNothing,
574 ArgEffect DefaultEff = MayEscape) {
Jordy Roseef945882012-03-18 01:26:10 +0000575 RetainSummary Summ(getArgEffects(), RetEff, DefaultEff, ReceiverEff);
576 return getPersistentSummary(Summ);
577 }
578
Ted Kremenekc91fdf62012-05-08 00:12:09 +0000579 const RetainSummary *getDoNothingSummary() {
580 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
581 }
582
Jordy Roseef945882012-03-18 01:26:10 +0000583 const RetainSummary *getDefaultSummary() {
584 return getPersistentSummary(RetEffect::MakeNoRet(),
585 DoNothing, MayEscape);
Ted Kremenek9c32d082008-05-06 00:30:21 +0000586 }
Mike Stump1eb44332009-09-09 15:08:12 +0000587
Ted Kremenek93edbc52011-10-05 23:54:29 +0000588 const RetainSummary *getPersistentStopSummary() {
Jordy Roseef945882012-03-18 01:26:10 +0000589 return getPersistentSummary(RetEffect::MakeNoRet(),
590 StopTracking, StopTracking);
Mike Stump1eb44332009-09-09 15:08:12 +0000591 }
Ted Kremenekb3095252008-05-06 04:20:12 +0000592
Ted Kremenek1f180c32008-06-23 22:21:20 +0000593 void InitializeClassMethodSummaries();
594 void InitializeMethodSummaries();
Ted Kremenek896cd9d2008-10-23 01:56:15 +0000595private:
Ted Kremenek93edbc52011-10-05 23:54:29 +0000596 void addNSObjectClsMethSummary(Selector S, const RetainSummary *Summ) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000597 ObjCClassMethodSummaries[S] = Summ;
598 }
Mike Stump1eb44332009-09-09 15:08:12 +0000599
Ted Kremenek93edbc52011-10-05 23:54:29 +0000600 void addNSObjectMethSummary(Selector S, const RetainSummary *Summ) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000601 ObjCMethodSummaries[S] = Summ;
602 }
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +0000603
Ted Kremeneka9797122012-02-18 21:37:48 +0000604 void addClassMethSummary(const char* Cls, const char* name,
605 const RetainSummary *Summ, bool isNullary = true) {
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +0000606 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
Ted Kremeneka9797122012-02-18 21:37:48 +0000607 Selector S = isNullary ? GetNullarySelector(name, Ctx)
608 : GetUnarySelector(name, Ctx);
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +0000609 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
610 }
Mike Stump1eb44332009-09-09 15:08:12 +0000611
Ted Kremenek6c4becb2009-02-25 02:54:57 +0000612 void addInstMethSummary(const char* Cls, const char* nullaryName,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000613 const RetainSummary *Summ) {
Ted Kremenek6c4becb2009-02-25 02:54:57 +0000614 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
615 Selector S = GetNullarySelector(nullaryName, Ctx);
616 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
617 }
Mike Stump1eb44332009-09-09 15:08:12 +0000618
Ted Kremenekde4d5332009-04-24 17:50:11 +0000619 Selector generateSelector(va_list argp) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000620 SmallVector<IdentifierInfo*, 10> II;
Ted Kremenekde4d5332009-04-24 17:50:11 +0000621
Ted Kremenek9e476de2008-08-12 18:30:56 +0000622 while (const char* s = va_arg(argp, const char*))
623 II.push_back(&Ctx.Idents.get(s));
Ted Kremenekde4d5332009-04-24 17:50:11 +0000624
Mike Stump1eb44332009-09-09 15:08:12 +0000625 return Ctx.Selectors.getSelector(II.size(), &II[0]);
Ted Kremenekde4d5332009-04-24 17:50:11 +0000626 }
Mike Stump1eb44332009-09-09 15:08:12 +0000627
Ted Kremenekde4d5332009-04-24 17:50:11 +0000628 void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy& Summaries,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000629 const RetainSummary * Summ, va_list argp) {
Ted Kremenekde4d5332009-04-24 17:50:11 +0000630 Selector S = generateSelector(argp);
631 Summaries[ObjCSummaryKey(ClsII, S)] = Summ;
Ted Kremenek70a733e2008-07-18 17:24:20 +0000632 }
Mike Stump1eb44332009-09-09 15:08:12 +0000633
Ted Kremenek93edbc52011-10-05 23:54:29 +0000634 void addInstMethSummary(const char* Cls, const RetainSummary * Summ, ...) {
Ted Kremenekaf9dc272008-08-12 18:48:50 +0000635 va_list argp;
636 va_start(argp, Summ);
Ted Kremenekde4d5332009-04-24 17:50:11 +0000637 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Mike Stump1eb44332009-09-09 15:08:12 +0000638 va_end(argp);
Ted Kremenekaf9dc272008-08-12 18:48:50 +0000639 }
Mike Stump1eb44332009-09-09 15:08:12 +0000640
Ted Kremenek93edbc52011-10-05 23:54:29 +0000641 void addClsMethSummary(const char* Cls, const RetainSummary * Summ, ...) {
Ted Kremenekde4d5332009-04-24 17:50:11 +0000642 va_list argp;
643 va_start(argp, Summ);
644 addMethodSummary(&Ctx.Idents.get(Cls),ObjCClassMethodSummaries, Summ, argp);
645 va_end(argp);
646 }
Mike Stump1eb44332009-09-09 15:08:12 +0000647
Ted Kremenek93edbc52011-10-05 23:54:29 +0000648 void addClsMethSummary(IdentifierInfo *II, const RetainSummary * Summ, ...) {
Ted Kremenekde4d5332009-04-24 17:50:11 +0000649 va_list argp;
650 va_start(argp, Summ);
651 addMethodSummary(II, ObjCClassMethodSummaries, Summ, argp);
652 va_end(argp);
653 }
654
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000655public:
Mike Stump1eb44332009-09-09 15:08:12 +0000656
Ted Kremenek9c378f72011-08-12 23:37:29 +0000657 RetainSummaryManager(ASTContext &ctx, bool gcenabled, bool usesARC)
Ted Kremenek179064e2008-07-01 17:21:27 +0000658 : Ctx(ctx),
John McCallf85e1932011-06-15 23:02:42 +0000659 GCEnabled(gcenabled),
660 ARCEnabled(usesARC),
661 AF(BPAlloc), ScratchArgs(AF.getEmptyMap()),
662 ObjCAllocRetE(gcenabled
663 ? RetEffect::MakeGCNotOwned()
664 : (usesARC ? RetEffect::MakeARCNotOwned()
665 : RetEffect::MakeOwned(RetEffect::ObjC, true))),
666 ObjCInitRetE(gcenabled
667 ? RetEffect::MakeGCNotOwned()
668 : (usesARC ? RetEffect::MakeARCNotOwned()
Jordy Roseef945882012-03-18 01:26:10 +0000669 : RetEffect::MakeOwnedWhenTrackedReceiver())) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000670 InitializeClassMethodSummaries();
671 InitializeMethodSummaries();
672 }
Mike Stump1eb44332009-09-09 15:08:12 +0000673
Jordan Rose4531b7d2012-07-02 19:27:43 +0000674 const RetainSummary *getSummary(const CallEvent &Call,
675 ProgramStateRef State = 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000676
Jordan Rose4531b7d2012-07-02 19:27:43 +0000677 const RetainSummary *getFunctionSummary(const FunctionDecl *FD);
678
679 const RetainSummary *getMethodSummary(Selector S, const ObjCInterfaceDecl *ID,
Jordy Rosef3aae582012-03-17 21:13:07 +0000680 const ObjCMethodDecl *MD,
681 QualType RetTy,
682 ObjCMethodSummariesTy &CachedSummaries);
683
Jordan Rosecde8cdb2012-07-02 19:27:56 +0000684 const RetainSummary *getInstanceMethodSummary(const ObjCMethodCall &M,
Jordan Rose4531b7d2012-07-02 19:27:43 +0000685 ProgramStateRef State);
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000686
Jordan Rosecde8cdb2012-07-02 19:27:56 +0000687 const RetainSummary *getClassMethodSummary(const ObjCMethodCall &M) {
Jordan Rose4531b7d2012-07-02 19:27:43 +0000688 assert(!M.isInstanceMessage());
689 const ObjCInterfaceDecl *Class = M.getReceiverInterface();
Mike Stump1eb44332009-09-09 15:08:12 +0000690
Jordan Rose4531b7d2012-07-02 19:27:43 +0000691 return getMethodSummary(M.getSelector(), Class, M.getDecl(),
692 M.getResultType(), ObjCClassMethodSummaries);
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +0000693 }
Ted Kremenek552333c2009-04-29 17:17:48 +0000694
695 /// getMethodSummary - This version of getMethodSummary is used to query
696 /// the summary for the current method being analyzed.
Ted Kremenek93edbc52011-10-05 23:54:29 +0000697 const RetainSummary *getMethodSummary(const ObjCMethodDecl *MD) {
Ted Kremeneka8833552009-04-29 23:03:22 +0000698 const ObjCInterfaceDecl *ID = MD->getClassInterface();
Ted Kremenek70a65762009-04-30 05:41:14 +0000699 Selector S = MD->getSelector();
Ted Kremenek552333c2009-04-29 17:17:48 +0000700 QualType ResultTy = MD->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +0000701
Jordy Rosef3aae582012-03-17 21:13:07 +0000702 ObjCMethodSummariesTy *CachedSummaries;
Ted Kremenek552333c2009-04-29 17:17:48 +0000703 if (MD->isInstanceMethod())
Jordy Rosef3aae582012-03-17 21:13:07 +0000704 CachedSummaries = &ObjCMethodSummaries;
Ted Kremenek552333c2009-04-29 17:17:48 +0000705 else
Jordy Rosef3aae582012-03-17 21:13:07 +0000706 CachedSummaries = &ObjCClassMethodSummaries;
707
Jordan Rose4531b7d2012-07-02 19:27:43 +0000708 return getMethodSummary(S, ID, MD, ResultTy, *CachedSummaries);
Ted Kremenek552333c2009-04-29 17:17:48 +0000709 }
Mike Stump1eb44332009-09-09 15:08:12 +0000710
Jordy Rosef3aae582012-03-17 21:13:07 +0000711 const RetainSummary *getStandardMethodSummary(const ObjCMethodDecl *MD,
Jordan Rose4531b7d2012-07-02 19:27:43 +0000712 Selector S, QualType RetTy);
Ted Kremeneka8833552009-04-29 23:03:22 +0000713
Jordan Rose44405b72013-04-04 22:31:48 +0000714 /// Determine if there is a special return effect for this function or method.
715 Optional<RetEffect> getRetEffectFromAnnotations(QualType RetTy,
716 const Decl *D);
717
Ted Kremenek93edbc52011-10-05 23:54:29 +0000718 void updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenek4dd8fb42009-05-09 02:58:13 +0000719 const ObjCMethodDecl *MD);
720
Ted Kremenek93edbc52011-10-05 23:54:29 +0000721 void updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenek4dd8fb42009-05-09 02:58:13 +0000722 const FunctionDecl *FD);
723
Jordan Rose4531b7d2012-07-02 19:27:43 +0000724 void updateSummaryForCall(const RetainSummary *&Summ,
725 const CallEvent &Call);
726
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000727 bool isGCEnabled() const { return GCEnabled; }
Mike Stump1eb44332009-09-09 15:08:12 +0000728
John McCallf85e1932011-06-15 23:02:42 +0000729 bool isARCEnabled() const { return ARCEnabled; }
730
731 bool isARCorGCEnabled() const { return GCEnabled || ARCEnabled; }
Jordan Rose4531b7d2012-07-02 19:27:43 +0000732
733 RetEffect getObjAllocRetEffect() const { return ObjCAllocRetE; }
734
735 friend class RetainSummaryTemplate;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000736};
Mike Stump1eb44332009-09-09 15:08:12 +0000737
Jordy Rose0fe62f82011-08-24 09:02:37 +0000738// Used to avoid allocating long-term (BPAlloc'd) memory for default retain
739// summaries. If a function or method looks like it has a default summary, but
740// it has annotations, the annotations are added to the stack-based template
741// and then copied into managed memory.
742class RetainSummaryTemplate {
743 RetainSummaryManager &Manager;
Ted Kremenek93edbc52011-10-05 23:54:29 +0000744 const RetainSummary *&RealSummary;
Jordy Rose0fe62f82011-08-24 09:02:37 +0000745 RetainSummary ScratchSummary;
746 bool Accessed;
747public:
Jordan Rose4531b7d2012-07-02 19:27:43 +0000748 RetainSummaryTemplate(const RetainSummary *&real, RetainSummaryManager &mgr)
749 : Manager(mgr), RealSummary(real), ScratchSummary(*real), Accessed(false) {}
Jordy Rose0fe62f82011-08-24 09:02:37 +0000750
751 ~RetainSummaryTemplate() {
Ted Kremenek93edbc52011-10-05 23:54:29 +0000752 if (Accessed)
Jordy Roseef945882012-03-18 01:26:10 +0000753 RealSummary = Manager.getPersistentSummary(ScratchSummary);
Jordy Rose0fe62f82011-08-24 09:02:37 +0000754 }
755
756 RetainSummary &operator*() {
757 Accessed = true;
Ted Kremenek93edbc52011-10-05 23:54:29 +0000758 return ScratchSummary;
Jordy Rose0fe62f82011-08-24 09:02:37 +0000759 }
760
761 RetainSummary *operator->() {
762 Accessed = true;
Ted Kremenek93edbc52011-10-05 23:54:29 +0000763 return &ScratchSummary;
Jordy Rose0fe62f82011-08-24 09:02:37 +0000764 }
765};
766
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000767} // end anonymous namespace
768
769//===----------------------------------------------------------------------===//
770// Implementation of checker data structures.
771//===----------------------------------------------------------------------===//
772
Ted Kremenekb77449c2009-05-03 05:20:50 +0000773ArgEffects RetainSummaryManager::getArgEffects() {
774 ArgEffects AE = ScratchArgs;
Ted Kremenek3baf6722010-11-24 00:54:37 +0000775 ScratchArgs = AF.getEmptyMap();
Ted Kremenekb77449c2009-05-03 05:20:50 +0000776 return AE;
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000777}
778
Ted Kremenek93edbc52011-10-05 23:54:29 +0000779const RetainSummary *
Jordy Roseef945882012-03-18 01:26:10 +0000780RetainSummaryManager::getPersistentSummary(const RetainSummary &OldSumm) {
781 // Unique "simple" summaries -- those without ArgEffects.
782 if (OldSumm.isSimple()) {
783 llvm::FoldingSetNodeID ID;
784 OldSumm.Profile(ID);
785
786 void *Pos;
787 CachedSummaryNode *N = SimpleSummaries.FindNodeOrInsertPos(ID, Pos);
788
789 if (!N) {
790 N = (CachedSummaryNode *) BPAlloc.Allocate<CachedSummaryNode>();
791 new (N) CachedSummaryNode(OldSumm);
792 SimpleSummaries.InsertNode(N, Pos);
793 }
794
795 return &N->getValue();
796 }
797
Ted Kremenek93edbc52011-10-05 23:54:29 +0000798 RetainSummary *Summ = (RetainSummary *) BPAlloc.Allocate<RetainSummary>();
Jordy Roseef945882012-03-18 01:26:10 +0000799 new (Summ) RetainSummary(OldSumm);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000800 return Summ;
801}
802
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000803//===----------------------------------------------------------------------===//
804// Summary creation for functions (largely uses of Core Foundation).
805//===----------------------------------------------------------------------===//
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000806
Ted Kremenek9c378f72011-08-12 23:37:29 +0000807static bool isRetain(const FunctionDecl *FD, StringRef FName) {
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000808 return FName.endswith("Retain");
Ted Kremenek12619382009-01-12 21:45:02 +0000809}
810
Ted Kremenek9c378f72011-08-12 23:37:29 +0000811static bool isRelease(const FunctionDecl *FD, StringRef FName) {
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000812 return FName.endswith("Release");
Ted Kremenek12619382009-01-12 21:45:02 +0000813}
814
Jordy Rose76c506f2011-08-21 21:58:18 +0000815static bool isMakeCollectable(const FunctionDecl *FD, StringRef FName) {
816 // FIXME: Remove FunctionDecl parameter.
817 // FIXME: Is it really okay if MakeCollectable isn't a suffix?
818 return FName.find("MakeCollectable") != StringRef::npos;
819}
820
Anna Zaks554067f2012-08-29 23:23:43 +0000821static ArgEffect getStopTrackingHardEquivalent(ArgEffect E) {
Jordan Rose4531b7d2012-07-02 19:27:43 +0000822 switch (E) {
823 case DoNothing:
824 case Autorelease:
825 case DecRefBridgedTransfered:
826 case IncRef:
827 case IncRefMsg:
828 case MakeCollectable:
829 case MayEscape:
Jordan Rose4531b7d2012-07-02 19:27:43 +0000830 case StopTracking:
Anna Zaks554067f2012-08-29 23:23:43 +0000831 case StopTrackingHard:
832 return StopTrackingHard;
Jordan Rose4531b7d2012-07-02 19:27:43 +0000833 case DecRef:
Anna Zaks554067f2012-08-29 23:23:43 +0000834 case DecRefAndStopTrackingHard:
835 return DecRefAndStopTrackingHard;
Jordan Rose4531b7d2012-07-02 19:27:43 +0000836 case DecRefMsg:
Anna Zaks554067f2012-08-29 23:23:43 +0000837 case DecRefMsgAndStopTrackingHard:
838 return DecRefMsgAndStopTrackingHard;
Jordan Rose4531b7d2012-07-02 19:27:43 +0000839 case Dealloc:
840 return Dealloc;
841 }
842
843 llvm_unreachable("Unknown ArgEffect kind");
844}
845
846void RetainSummaryManager::updateSummaryForCall(const RetainSummary *&S,
847 const CallEvent &Call) {
848 if (Call.hasNonZeroCallbackArg()) {
Anna Zaks554067f2012-08-29 23:23:43 +0000849 ArgEffect RecEffect =
850 getStopTrackingHardEquivalent(S->getReceiverEffect());
851 ArgEffect DefEffect =
852 getStopTrackingHardEquivalent(S->getDefaultArgEffect());
Jordan Rose4531b7d2012-07-02 19:27:43 +0000853
854 ArgEffects CustomArgEffects = S->getArgEffects();
855 for (ArgEffects::iterator I = CustomArgEffects.begin(),
856 E = CustomArgEffects.end();
857 I != E; ++I) {
Anna Zaks554067f2012-08-29 23:23:43 +0000858 ArgEffect Translated = getStopTrackingHardEquivalent(I->second);
Jordan Rose4531b7d2012-07-02 19:27:43 +0000859 if (Translated != DefEffect)
860 ScratchArgs = AF.add(ScratchArgs, I->first, Translated);
861 }
862
Anna Zaks554067f2012-08-29 23:23:43 +0000863 RetEffect RE = RetEffect::MakeNoRetHard();
Jordan Rose4531b7d2012-07-02 19:27:43 +0000864
865 // Special cases where the callback argument CANNOT free the return value.
866 // This can generally only happen if we know that the callback will only be
867 // called when the return value is already being deallocated.
868 if (const FunctionCall *FC = dyn_cast<FunctionCall>(&Call)) {
Jordan Rose4a25f302012-09-01 17:39:13 +0000869 if (IdentifierInfo *Name = FC->getDecl()->getIdentifier()) {
870 // When the CGBitmapContext is deallocated, the callback here will free
871 // the associated data buffer.
Jordan Rosea89f7192012-08-31 18:19:18 +0000872 if (Name->isStr("CGBitmapContextCreateWithData"))
873 RE = S->getRetEffect();
Jordan Rose4a25f302012-09-01 17:39:13 +0000874 }
Jordan Rose4531b7d2012-07-02 19:27:43 +0000875 }
876
877 S = getPersistentSummary(RE, RecEffect, DefEffect);
878 }
Anna Zaks5a901932012-08-24 00:06:12 +0000879
880 // Special case '[super init];' and '[self init];'
881 //
882 // Even though calling '[super init]' without assigning the result to self
883 // and checking if the parent returns 'nil' is a bad pattern, it is common.
884 // Additionally, our Self Init checker already warns about it. To avoid
885 // overwhelming the user with messages from both checkers, we model the case
886 // of '[super init]' in cases when it is not consumed by another expression
887 // as if the call preserves the value of 'self'; essentially, assuming it can
888 // never fail and return 'nil'.
889 // Note, we don't want to just stop tracking the value since we want the
890 // RetainCount checker to report leaks and use-after-free if SelfInit checker
891 // is turned off.
892 if (const ObjCMethodCall *MC = dyn_cast<ObjCMethodCall>(&Call)) {
893 if (MC->getMethodFamily() == OMF_init && MC->isReceiverSelfOrSuper()) {
894
895 // Check if the message is not consumed, we know it will not be used in
896 // an assignment, ex: "self = [super init]".
897 const Expr *ME = MC->getOriginExpr();
898 const LocationContext *LCtx = MC->getLocationContext();
899 ParentMap &PM = LCtx->getAnalysisDeclContext()->getParentMap();
900 if (!PM.isConsumedExpr(ME)) {
901 RetainSummaryTemplate ModifiableSummaryTemplate(S, *this);
902 ModifiableSummaryTemplate->setReceiverEffect(DoNothing);
903 ModifiableSummaryTemplate->setRetEffect(RetEffect::MakeNoRet());
904 }
905 }
906
907 }
Jordan Rose4531b7d2012-07-02 19:27:43 +0000908}
909
Anna Zaks58822c42012-05-04 22:18:39 +0000910const RetainSummary *
Jordan Rose4531b7d2012-07-02 19:27:43 +0000911RetainSummaryManager::getSummary(const CallEvent &Call,
912 ProgramStateRef State) {
913 const RetainSummary *Summ;
914 switch (Call.getKind()) {
915 case CE_Function:
916 Summ = getFunctionSummary(cast<FunctionCall>(Call).getDecl());
917 break;
918 case CE_CXXMember:
Jordan Rosefdaa3382012-07-03 22:55:57 +0000919 case CE_CXXMemberOperator:
Jordan Rose4531b7d2012-07-02 19:27:43 +0000920 case CE_Block:
921 case CE_CXXConstructor:
Jordan Rose8d276d32012-07-10 22:07:47 +0000922 case CE_CXXDestructor:
Jordan Rose70cbf3c2012-07-02 22:21:47 +0000923 case CE_CXXAllocator:
Jordan Rose4531b7d2012-07-02 19:27:43 +0000924 // FIXME: These calls are currently unsupported.
925 return getPersistentStopSummary();
Jordan Rose8919e682012-07-18 21:59:51 +0000926 case CE_ObjCMessage: {
Jordan Rosecde8cdb2012-07-02 19:27:56 +0000927 const ObjCMethodCall &Msg = cast<ObjCMethodCall>(Call);
Jordan Rose4531b7d2012-07-02 19:27:43 +0000928 if (Msg.isInstanceMessage())
929 Summ = getInstanceMethodSummary(Msg, State);
930 else
931 Summ = getClassMethodSummary(Msg);
932 break;
933 }
934 }
935
936 updateSummaryForCall(Summ, Call);
937
938 assert(Summ && "Unknown call type?");
939 return Summ;
940}
941
942const RetainSummary *
943RetainSummaryManager::getFunctionSummary(const FunctionDecl *FD) {
944 // If we don't know what function we're calling, use our default summary.
945 if (!FD)
946 return getDefaultSummary();
947
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000948 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000949 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000950 if (I != FuncSummaries.end())
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000951 return I->second;
952
Ted Kremeneke401a0c2009-05-04 15:34:07 +0000953 // No summary? Generate one.
Ted Kremenek93edbc52011-10-05 23:54:29 +0000954 const RetainSummary *S = 0;
Jordan Rose15d18e12012-08-06 21:28:02 +0000955 bool AllowAnnotations = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000956
Ted Kremenek37d785b2008-07-15 16:50:12 +0000957 do {
Ted Kremenek12619382009-01-12 21:45:02 +0000958 // We generate "stop" summaries for implicitly defined functions.
959 if (FD->isImplicit()) {
960 S = getPersistentStopSummary();
961 break;
Ted Kremenek37d785b2008-07-15 16:50:12 +0000962 }
Mike Stump1eb44332009-09-09 15:08:12 +0000963
John McCall183700f2009-09-21 23:43:11 +0000964 // [PR 3337] Use 'getAs<FunctionType>' to strip away any typedefs on the
Ted Kremenek99890652009-01-16 18:40:33 +0000965 // function's type.
John McCall183700f2009-09-21 23:43:11 +0000966 const FunctionType* FT = FD->getType()->getAs<FunctionType>();
Ted Kremenek48c6d182009-12-16 06:06:43 +0000967 const IdentifierInfo *II = FD->getIdentifier();
968 if (!II)
969 break;
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000970
971 StringRef FName = II->getName();
Mike Stump1eb44332009-09-09 15:08:12 +0000972
Ted Kremenekbf0a4dd2009-03-05 22:11:14 +0000973 // Strip away preceding '_'. Doing this here will effect all the checks
974 // down below.
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000975 FName = FName.substr(FName.find_first_not_of('_'));
Mike Stump1eb44332009-09-09 15:08:12 +0000976
Ted Kremenek12619382009-01-12 21:45:02 +0000977 // Inspect the result type.
978 QualType RetTy = FT->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +0000979
Ted Kremenek12619382009-01-12 21:45:02 +0000980 // FIXME: This should all be refactored into a chain of "summary lookup"
981 // filters.
Ted Kremenek008636a2009-10-14 00:27:24 +0000982 assert(ScratchArgs.isEmpty());
Ted Kremenek39d88b02009-06-15 20:36:07 +0000983
Ted Kremenekbefc6d22012-04-26 04:32:23 +0000984 if (FName == "pthread_create" || FName == "pthread_setspecific") {
985 // Part of: <rdar://problem/7299394> and <rdar://problem/11282706>.
986 // This will be addressed better with IPA.
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000987 S = getPersistentStopSummary();
988 } else if (FName == "NSMakeCollectable") {
989 // Handle: id NSMakeCollectable(CFTypeRef)
990 S = (RetTy->isObjCIdType())
991 ? getUnarySummary(FT, cfmakecollectable)
992 : getPersistentStopSummary();
Jordan Rose15d18e12012-08-06 21:28:02 +0000993 // The headers on OS X 10.8 use cf_consumed/ns_returns_retained,
994 // but we can fully model NSMakeCollectable ourselves.
995 AllowAnnotations = false;
Ted Kremenek061707a2012-09-06 23:47:02 +0000996 } else if (FName == "CFPlugInInstanceCreate") {
997 S = getPersistentSummary(RetEffect::MakeNoRet());
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000998 } else if (FName == "IOBSDNameMatching" ||
999 FName == "IOServiceMatching" ||
1000 FName == "IOServiceNameMatching" ||
Ted Kremenek537dd3a2012-05-01 05:28:27 +00001001 FName == "IORegistryEntrySearchCFProperty" ||
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001002 FName == "IORegistryEntryIDMatching" ||
1003 FName == "IOOpenFirmwarePathMatching") {
1004 // Part of <rdar://problem/6961230>. (IOKit)
1005 // This should be addressed using a API table.
1006 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1007 DoNothing, DoNothing);
1008 } else if (FName == "IOServiceGetMatchingService" ||
1009 FName == "IOServiceGetMatchingServices") {
1010 // FIXES: <rdar://problem/6326900>
1011 // This should be addressed using a API table. This strcmp is also
1012 // a little gross, but there is no need to super optimize here.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001013 ScratchArgs = AF.add(ScratchArgs, 1, DecRef);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001014 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1015 } else if (FName == "IOServiceAddNotification" ||
1016 FName == "IOServiceAddMatchingNotification") {
1017 // Part of <rdar://problem/6961230>. (IOKit)
1018 // This should be addressed using a API table.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001019 ScratchArgs = AF.add(ScratchArgs, 2, DecRef);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001020 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1021 } else if (FName == "CVPixelBufferCreateWithBytes") {
1022 // FIXES: <rdar://problem/7283567>
1023 // Eventually this can be improved by recognizing that the pixel
1024 // buffer passed to CVPixelBufferCreateWithBytes is released via
1025 // a callback and doing full IPA to make sure this is done correctly.
1026 // FIXME: This function has an out parameter that returns an
1027 // allocated object.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001028 ScratchArgs = AF.add(ScratchArgs, 7, StopTracking);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001029 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1030 } else if (FName == "CGBitmapContextCreateWithData") {
1031 // FIXES: <rdar://problem/7358899>
1032 // Eventually this can be improved by recognizing that 'releaseInfo'
1033 // passed to CGBitmapContextCreateWithData is released via
1034 // a callback and doing full IPA to make sure this is done correctly.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001035 ScratchArgs = AF.add(ScratchArgs, 8, StopTracking);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001036 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1037 DoNothing, DoNothing);
1038 } else if (FName == "CVPixelBufferCreateWithPlanarBytes") {
1039 // FIXES: <rdar://problem/7283567>
1040 // Eventually this can be improved by recognizing that the pixel
1041 // buffer passed to CVPixelBufferCreateWithPlanarBytes is released
1042 // via a callback and doing full IPA to make sure this is done
1043 // correctly.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001044 ScratchArgs = AF.add(ScratchArgs, 12, StopTracking);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001045 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Jordan Rose8a729b42013-05-02 01:51:40 +00001046 } else if (FName == "dispatch_set_context" ||
1047 FName == "xpc_connection_set_context") {
Ted Kremenek06911d42012-03-22 06:29:41 +00001048 // <rdar://problem/11059275> - The analyzer currently doesn't have
1049 // a good way to reason about the finalizer function for libdispatch.
1050 // If we pass a context object that is memory managed, stop tracking it.
Jordan Rose8a729b42013-05-02 01:51:40 +00001051 // <rdar://problem/13783514> - Same problem, but for XPC.
Ted Kremenek06911d42012-03-22 06:29:41 +00001052 // FIXME: this hack should possibly go away once we can handle
Jordan Rose8a729b42013-05-02 01:51:40 +00001053 // libdispatch and XPC finalizers.
Ted Kremenek06911d42012-03-22 06:29:41 +00001054 ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
1055 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenekc91fdf62012-05-08 00:12:09 +00001056 } else if (FName.startswith("NSLog")) {
1057 S = getDoNothingSummary();
Anna Zaks62a5c342012-03-30 05:48:16 +00001058 } else if (FName.startswith("NS") &&
1059 (FName.find("Insert") != StringRef::npos)) {
1060 // Whitelist NSXXInsertXX, for example NSMapInsertIfAbsent, since they can
1061 // be deallocated by NSMapRemove. (radar://11152419)
1062 ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
1063 ScratchArgs = AF.add(ScratchArgs, 2, StopTracking);
1064 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenekb04cb592009-06-11 18:17:24 +00001065 }
Mike Stump1eb44332009-09-09 15:08:12 +00001066
Ted Kremenekb04cb592009-06-11 18:17:24 +00001067 // Did we get a summary?
1068 if (S)
1069 break;
Ted Kremenek61991902009-03-17 22:43:44 +00001070
Jordan Rose5aff3f12013-03-04 23:21:32 +00001071 if (RetTy->isPointerType()) {
Ted Kremenek12619382009-01-12 21:45:02 +00001072 // For CoreFoundation ('CF') types.
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001073 if (cocoa::isRefType(RetTy, "CF", FName)) {
Ted Kremenek12619382009-01-12 21:45:02 +00001074 if (isRetain(FD, FName))
1075 S = getUnarySummary(FT, cfretain);
Jordy Rose76c506f2011-08-21 21:58:18 +00001076 else if (isMakeCollectable(FD, FName))
Ted Kremenek12619382009-01-12 21:45:02 +00001077 S = getUnarySummary(FT, cfmakecollectable);
Mike Stump1eb44332009-09-09 15:08:12 +00001078 else
John McCall7df2ff42011-10-01 00:48:56 +00001079 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek12619382009-01-12 21:45:02 +00001080
1081 break;
1082 }
1083
1084 // For CoreGraphics ('CG') types.
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001085 if (cocoa::isRefType(RetTy, "CG", FName)) {
Ted Kremenek12619382009-01-12 21:45:02 +00001086 if (isRetain(FD, FName))
1087 S = getUnarySummary(FT, cfretain);
1088 else
John McCall7df2ff42011-10-01 00:48:56 +00001089 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek12619382009-01-12 21:45:02 +00001090
1091 break;
1092 }
1093
1094 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001095 if (cocoa::isRefType(RetTy, "DADisk") ||
1096 cocoa::isRefType(RetTy, "DADissenter") ||
1097 cocoa::isRefType(RetTy, "DASessionRef")) {
John McCall7df2ff42011-10-01 00:48:56 +00001098 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek12619382009-01-12 21:45:02 +00001099 break;
1100 }
Mike Stump1eb44332009-09-09 15:08:12 +00001101
Jordan Rose5aff3f12013-03-04 23:21:32 +00001102 if (FD->getAttr<CFAuditedTransferAttr>()) {
1103 S = getCFCreateGetRuleSummary(FD);
1104 break;
1105 }
1106
Ted Kremenek12619382009-01-12 21:45:02 +00001107 break;
1108 }
1109
1110 // Check for release functions, the only kind of functions that we care
1111 // about that don't return a pointer type.
1112 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
Ted Kremeneke7d03122010-02-08 16:45:01 +00001113 // Test for 'CGCF'.
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001114 FName = FName.substr(FName.startswith("CGCF") ? 4 : 2);
Ted Kremeneke7d03122010-02-08 16:45:01 +00001115
Ted Kremenekbf0a4dd2009-03-05 22:11:14 +00001116 if (isRelease(FD, FName))
Ted Kremenek12619382009-01-12 21:45:02 +00001117 S = getUnarySummary(FT, cfrelease);
1118 else {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001119 assert (ScratchArgs.isEmpty());
Ted Kremenek68189282009-01-29 22:45:13 +00001120 // Remaining CoreFoundation and CoreGraphics functions.
1121 // We use to assume that they all strictly followed the ownership idiom
1122 // and that ownership cannot be transferred. While this is technically
1123 // correct, many methods allow a tracked object to escape. For example:
1124 //
Mike Stump1eb44332009-09-09 15:08:12 +00001125 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
Ted Kremenek68189282009-01-29 22:45:13 +00001126 // CFDictionaryAddValue(y, key, x);
Mike Stump1eb44332009-09-09 15:08:12 +00001127 // CFRelease(x);
Ted Kremenek68189282009-01-29 22:45:13 +00001128 // ... it is okay to use 'x' since 'y' has a reference to it
1129 //
1130 // We handle this and similar cases with the follow heuristic. If the
Ted Kremenekc4843812009-08-20 00:57:22 +00001131 // function name contains "InsertValue", "SetValue", "AddValue",
1132 // "AppendValue", or "SetAttribute", then we assume that arguments may
1133 // "escape." This means that something else holds on to the object,
1134 // allowing it be used even after its local retain count drops to 0.
Benjamin Kramere45c1492010-01-11 19:46:28 +00001135 ArgEffect E = (StrInStrNoCase(FName, "InsertValue") != StringRef::npos||
1136 StrInStrNoCase(FName, "AddValue") != StringRef::npos ||
1137 StrInStrNoCase(FName, "SetValue") != StringRef::npos ||
1138 StrInStrNoCase(FName, "AppendValue") != StringRef::npos||
Benjamin Kramerc027e542010-01-11 20:15:06 +00001139 StrInStrNoCase(FName, "SetAttribute") != StringRef::npos)
Ted Kremenek68189282009-01-29 22:45:13 +00001140 ? MayEscape : DoNothing;
Mike Stump1eb44332009-09-09 15:08:12 +00001141
Ted Kremenek68189282009-01-29 22:45:13 +00001142 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek12619382009-01-12 21:45:02 +00001143 }
1144 }
Ted Kremenek37d785b2008-07-15 16:50:12 +00001145 }
1146 while (0);
Mike Stump1eb44332009-09-09 15:08:12 +00001147
Jordan Rose4531b7d2012-07-02 19:27:43 +00001148 // If we got all the way here without any luck, use a default summary.
1149 if (!S)
1150 S = getDefaultSummary();
1151
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001152 // Annotations override defaults.
Jordan Rose15d18e12012-08-06 21:28:02 +00001153 if (AllowAnnotations)
1154 updateSummaryFromAnnotations(S, FD);
Mike Stump1eb44332009-09-09 15:08:12 +00001155
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001156 FuncSummaries[FD] = S;
Mike Stump1eb44332009-09-09 15:08:12 +00001157 return S;
Ted Kremenek2fff37e2008-03-06 00:08:09 +00001158}
1159
Ted Kremenek93edbc52011-10-05 23:54:29 +00001160const RetainSummary *
John McCall7df2ff42011-10-01 00:48:56 +00001161RetainSummaryManager::getCFCreateGetRuleSummary(const FunctionDecl *FD) {
1162 if (coreFoundation::followsCreateRule(FD))
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001163 return getCFSummaryCreateRule(FD);
Mike Stump1eb44332009-09-09 15:08:12 +00001164
Ted Kremenekd368d712011-05-25 06:19:45 +00001165 return getCFSummaryGetRule(FD);
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001166}
1167
Ted Kremenek93edbc52011-10-05 23:54:29 +00001168const RetainSummary *
Ted Kremenek6ad315a2009-02-23 16:51:39 +00001169RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1170 UnaryFuncKind func) {
1171
Ted Kremenek12619382009-01-12 21:45:02 +00001172 // Sanity check that this is *really* a unary function. This can
1173 // happen if people do weird things.
Douglas Gregor72564e72009-02-26 23:50:07 +00001174 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
Ted Kremenek12619382009-01-12 21:45:02 +00001175 if (!FTP || FTP->getNumArgs() != 1)
1176 return getPersistentStopSummary();
Mike Stump1eb44332009-09-09 15:08:12 +00001177
Ted Kremenekb77449c2009-05-03 05:20:50 +00001178 assert (ScratchArgs.isEmpty());
Mike Stump1eb44332009-09-09 15:08:12 +00001179
Jordy Rose76c506f2011-08-21 21:58:18 +00001180 ArgEffect Effect;
Ted Kremenek377e2302008-04-29 05:33:51 +00001181 switch (func) {
Jordy Rose76c506f2011-08-21 21:58:18 +00001182 case cfretain: Effect = IncRef; break;
1183 case cfrelease: Effect = DecRef; break;
1184 case cfmakecollectable: Effect = MakeCollectable; break;
Ted Kremenek940b1d82008-04-10 23:44:06 +00001185 }
Jordy Rose76c506f2011-08-21 21:58:18 +00001186
1187 ScratchArgs = AF.add(ScratchArgs, 0, Effect);
1188 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001189}
1190
Ted Kremenek93edbc52011-10-05 23:54:29 +00001191const RetainSummary *
Ted Kremenek9c378f72011-08-12 23:37:29 +00001192RetainSummaryManager::getCFSummaryCreateRule(const FunctionDecl *FD) {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001193 assert (ScratchArgs.isEmpty());
Mike Stump1eb44332009-09-09 15:08:12 +00001194
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001195 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001196}
1197
Ted Kremenek93edbc52011-10-05 23:54:29 +00001198const RetainSummary *
Ted Kremenek9c378f72011-08-12 23:37:29 +00001199RetainSummaryManager::getCFSummaryGetRule(const FunctionDecl *FD) {
Mike Stump1eb44332009-09-09 15:08:12 +00001200 assert (ScratchArgs.isEmpty());
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001201 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1202 DoNothing, DoNothing);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001203}
1204
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001205//===----------------------------------------------------------------------===//
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001206// Summary creation for Selectors.
1207//===----------------------------------------------------------------------===//
1208
Jordan Rose44405b72013-04-04 22:31:48 +00001209Optional<RetEffect>
1210RetainSummaryManager::getRetEffectFromAnnotations(QualType RetTy,
1211 const Decl *D) {
1212 if (cocoa::isCocoaObjectRef(RetTy)) {
1213 if (D->getAttr<NSReturnsRetainedAttr>())
1214 return ObjCAllocRetE;
1215
1216 if (D->getAttr<NSReturnsNotRetainedAttr>() ||
1217 D->getAttr<NSReturnsAutoreleasedAttr>())
1218 return RetEffect::MakeNotOwned(RetEffect::ObjC);
1219
1220 } else if (!RetTy->isPointerType()) {
1221 return None;
1222 }
1223
1224 if (D->getAttr<CFReturnsRetainedAttr>())
1225 return RetEffect::MakeOwned(RetEffect::CF, true);
1226
1227 if (D->getAttr<CFReturnsNotRetainedAttr>())
1228 return RetEffect::MakeNotOwned(RetEffect::CF);
1229
1230 return None;
1231}
1232
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001233void
Ted Kremenek93edbc52011-10-05 23:54:29 +00001234RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001235 const FunctionDecl *FD) {
1236 if (!FD)
1237 return;
1238
Jordan Rose4531b7d2012-07-02 19:27:43 +00001239 assert(Summ && "Must have a summary to add annotations to.");
1240 RetainSummaryTemplate Template(Summ, *this);
Jordy Rose4df54fe2011-08-23 04:27:15 +00001241
Ted Kremenek11fe1752011-01-27 18:43:03 +00001242 // Effects on the parameters.
1243 unsigned parm_idx = 0;
1244 for (FunctionDecl::param_const_iterator pi = FD->param_begin(),
John McCall98b8f162011-04-06 09:02:12 +00001245 pe = FD->param_end(); pi != pe; ++pi, ++parm_idx) {
Ted Kremenek11fe1752011-01-27 18:43:03 +00001246 const ParmVarDecl *pd = *pi;
Jordan Rose44405b72013-04-04 22:31:48 +00001247 if (pd->getAttr<NSConsumedAttr>())
1248 Template->addArg(AF, parm_idx, DecRefMsg);
1249 else if (pd->getAttr<CFConsumedAttr>())
Jordy Rose0fe62f82011-08-24 09:02:37 +00001250 Template->addArg(AF, parm_idx, DecRef);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001251 }
1252
Ted Kremenekb04cb592009-06-11 18:17:24 +00001253 QualType RetTy = FD->getResultType();
Jordan Rose44405b72013-04-04 22:31:48 +00001254 if (Optional<RetEffect> RetE = getRetEffectFromAnnotations(RetTy, FD))
1255 Template->setRetEffect(*RetE);
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001256}
1257
1258void
Ted Kremenek93edbc52011-10-05 23:54:29 +00001259RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
1260 const ObjCMethodDecl *MD) {
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001261 if (!MD)
1262 return;
1263
Jordan Rose4531b7d2012-07-02 19:27:43 +00001264 assert(Summ && "Must have a valid summary to add annotations to");
1265 RetainSummaryTemplate Template(Summ, *this);
Mike Stump1eb44332009-09-09 15:08:12 +00001266
Ted Kremenek12b94342011-01-27 06:54:14 +00001267 // Effects on the receiver.
Jordan Rose44405b72013-04-04 22:31:48 +00001268 if (MD->getAttr<NSConsumesSelfAttr>())
1269 Template->setReceiverEffect(DecRefMsg);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001270
1271 // Effects on the parameters.
1272 unsigned parm_idx = 0;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00001273 for (ObjCMethodDecl::param_const_iterator
1274 pi=MD->param_begin(), pe=MD->param_end();
Ted Kremenek11fe1752011-01-27 18:43:03 +00001275 pi != pe; ++pi, ++parm_idx) {
1276 const ParmVarDecl *pd = *pi;
Jordan Rose44405b72013-04-04 22:31:48 +00001277 if (pd->getAttr<NSConsumedAttr>())
1278 Template->addArg(AF, parm_idx, DecRefMsg);
1279 else if (pd->getAttr<CFConsumedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001280 Template->addArg(AF, parm_idx, DecRef);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001281 }
Ted Kremenek12b94342011-01-27 06:54:14 +00001282 }
1283
Jordan Rose44405b72013-04-04 22:31:48 +00001284 QualType RetTy = MD->getResultType();
1285 if (Optional<RetEffect> RetE = getRetEffectFromAnnotations(RetTy, MD))
1286 Template->setRetEffect(*RetE);
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001287}
1288
Ted Kremenek93edbc52011-10-05 23:54:29 +00001289const RetainSummary *
Jordy Rosef3aae582012-03-17 21:13:07 +00001290RetainSummaryManager::getStandardMethodSummary(const ObjCMethodDecl *MD,
1291 Selector S, QualType RetTy) {
Jordy Rosee921b1a2012-03-17 19:53:04 +00001292 // Any special effects?
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001293 ArgEffect ReceiverEff = DoNothing;
Jordy Rosee921b1a2012-03-17 19:53:04 +00001294 RetEffect ResultEff = RetEffect::MakeNoRet();
1295
1296 // Check the method family, and apply any default annotations.
1297 switch (MD ? MD->getMethodFamily() : S.getMethodFamily()) {
1298 case OMF_None:
1299 case OMF_performSelector:
1300 // Assume all Objective-C methods follow Cocoa Memory Management rules.
1301 // FIXME: Does the non-threaded performSelector family really belong here?
1302 // The selector could be, say, @selector(copy).
1303 if (cocoa::isCocoaObjectRef(RetTy))
1304 ResultEff = RetEffect::MakeNotOwned(RetEffect::ObjC);
1305 else if (coreFoundation::isCFObjectRef(RetTy)) {
1306 // ObjCMethodDecl currently doesn't consider CF objects as valid return
1307 // values for alloc, new, copy, or mutableCopy, so we have to
1308 // double-check with the selector. This is ugly, but there aren't that
1309 // many Objective-C methods that return CF objects, right?
1310 if (MD) {
1311 switch (S.getMethodFamily()) {
1312 case OMF_alloc:
1313 case OMF_new:
1314 case OMF_copy:
1315 case OMF_mutableCopy:
1316 ResultEff = RetEffect::MakeOwned(RetEffect::CF, true);
1317 break;
1318 default:
1319 ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1320 break;
1321 }
1322 } else {
1323 ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1324 }
1325 }
1326 break;
1327 case OMF_init:
1328 ResultEff = ObjCInitRetE;
1329 ReceiverEff = DecRefMsg;
1330 break;
1331 case OMF_alloc:
1332 case OMF_new:
1333 case OMF_copy:
1334 case OMF_mutableCopy:
1335 if (cocoa::isCocoaObjectRef(RetTy))
1336 ResultEff = ObjCAllocRetE;
1337 else if (coreFoundation::isCFObjectRef(RetTy))
1338 ResultEff = RetEffect::MakeOwned(RetEffect::CF, true);
1339 break;
1340 case OMF_autorelease:
1341 ReceiverEff = Autorelease;
1342 break;
1343 case OMF_retain:
1344 ReceiverEff = IncRefMsg;
1345 break;
1346 case OMF_release:
1347 ReceiverEff = DecRefMsg;
1348 break;
1349 case OMF_dealloc:
1350 ReceiverEff = Dealloc;
1351 break;
1352 case OMF_self:
1353 // -self is handled specially by the ExprEngine to propagate the receiver.
1354 break;
1355 case OMF_retainCount:
1356 case OMF_finalize:
1357 // These methods don't return objects.
1358 break;
1359 }
Mike Stump1eb44332009-09-09 15:08:12 +00001360
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001361 // If one of the arguments in the selector has the keyword 'delegate' we
1362 // should stop tracking the reference count for the receiver. This is
1363 // because the reference count is quite possibly handled by a delegate
1364 // method.
1365 if (S.isKeywordSelector()) {
Jordan Rose50571a92012-06-15 18:19:52 +00001366 for (unsigned i = 0, e = S.getNumArgs(); i != e; ++i) {
1367 StringRef Slot = S.getNameForSlot(i);
1368 if (Slot.substr(Slot.size() - 8).equals_lower("delegate")) {
1369 if (ResultEff == ObjCInitRetE)
Anna Zaks554067f2012-08-29 23:23:43 +00001370 ResultEff = RetEffect::MakeNoRetHard();
Jordan Rose50571a92012-06-15 18:19:52 +00001371 else
Anna Zaks554067f2012-08-29 23:23:43 +00001372 ReceiverEff = StopTrackingHard;
Jordan Rose50571a92012-06-15 18:19:52 +00001373 }
1374 }
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001375 }
Mike Stump1eb44332009-09-09 15:08:12 +00001376
Jordy Rosee921b1a2012-03-17 19:53:04 +00001377 if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing &&
1378 ResultEff.getKind() == RetEffect::NoRet)
Ted Kremenek93edbc52011-10-05 23:54:29 +00001379 return getDefaultSummary();
Mike Stump1eb44332009-09-09 15:08:12 +00001380
Jordy Rosee921b1a2012-03-17 19:53:04 +00001381 return getPersistentSummary(ResultEff, ReceiverEff, MayEscape);
Ted Kremenek250b1fa2009-04-23 23:08:22 +00001382}
1383
Ted Kremenek93edbc52011-10-05 23:54:29 +00001384const RetainSummary *
Jordan Rosecde8cdb2012-07-02 19:27:56 +00001385RetainSummaryManager::getInstanceMethodSummary(const ObjCMethodCall &Msg,
Jordan Rose4531b7d2012-07-02 19:27:43 +00001386 ProgramStateRef State) {
1387 const ObjCInterfaceDecl *ReceiverClass = 0;
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001388
Jordan Rose4531b7d2012-07-02 19:27:43 +00001389 // We do better tracking of the type of the object than the core ExprEngine.
1390 // See if we have its type in our private state.
1391 // FIXME: Eventually replace the use of state->get<RefBindings> with
1392 // a generic API for reasoning about the Objective-C types of symbolic
1393 // objects.
1394 SVal ReceiverV = Msg.getReceiverSVal();
1395 if (SymbolRef Sym = ReceiverV.getAsLocSymbol())
Anna Zaks8d6b43c2012-08-14 00:36:15 +00001396 if (const RefVal *T = getRefBinding(State, Sym))
Douglas Gregor04badcf2010-04-21 00:45:42 +00001397 if (const ObjCObjectPointerType *PT =
Jordan Rose4531b7d2012-07-02 19:27:43 +00001398 T->getType()->getAs<ObjCObjectPointerType>())
1399 ReceiverClass = PT->getInterfaceDecl();
1400
1401 // If we don't know what kind of object this is, fall back to its static type.
1402 if (!ReceiverClass)
1403 ReceiverClass = Msg.getReceiverInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00001404
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001405 // FIXME: The receiver could be a reference to a class, meaning that
1406 // we should use the class method.
Jordan Rose4531b7d2012-07-02 19:27:43 +00001407 // id x = [NSObject class];
1408 // [x performSelector:... withObject:... afterDelay:...];
1409 Selector S = Msg.getSelector();
1410 const ObjCMethodDecl *Method = Msg.getDecl();
1411 if (!Method && ReceiverClass)
1412 Method = ReceiverClass->getInstanceMethod(S);
1413
1414 return getMethodSummary(S, ReceiverClass, Method, Msg.getResultType(),
1415 ObjCMethodSummaries);
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001416}
1417
Ted Kremenek93edbc52011-10-05 23:54:29 +00001418const RetainSummary *
Jordan Rose4531b7d2012-07-02 19:27:43 +00001419RetainSummaryManager::getMethodSummary(Selector S, const ObjCInterfaceDecl *ID,
Jordy Rosef3aae582012-03-17 21:13:07 +00001420 const ObjCMethodDecl *MD, QualType RetTy,
1421 ObjCMethodSummariesTy &CachedSummaries) {
Ted Kremenek1bffd742008-05-06 15:44:25 +00001422
Ted Kremenek8711c032009-04-29 05:04:30 +00001423 // Look up a summary in our summary cache.
Jordan Rose4531b7d2012-07-02 19:27:43 +00001424 const RetainSummary *Summ = CachedSummaries.find(ID, S);
Mike Stump1eb44332009-09-09 15:08:12 +00001425
Ted Kremenek614cc542009-07-21 23:27:57 +00001426 if (!Summ) {
Jordy Rosef3aae582012-03-17 21:13:07 +00001427 Summ = getStandardMethodSummary(MD, S, RetTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001428
Ted Kremenek614cc542009-07-21 23:27:57 +00001429 // Annotations override defaults.
Jordy Rose4df54fe2011-08-23 04:27:15 +00001430 updateSummaryFromAnnotations(Summ, MD);
Mike Stump1eb44332009-09-09 15:08:12 +00001431
Ted Kremenek614cc542009-07-21 23:27:57 +00001432 // Memoize the summary.
Jordan Rose4531b7d2012-07-02 19:27:43 +00001433 CachedSummaries[ObjCSummaryKey(ID, S)] = Summ;
Ted Kremenek614cc542009-07-21 23:27:57 +00001434 }
Mike Stump1eb44332009-09-09 15:08:12 +00001435
Ted Kremeneke87450e2009-04-23 19:11:35 +00001436 return Summ;
Ted Kremenekc8395602008-05-06 21:26:51 +00001437}
1438
Mike Stump1eb44332009-09-09 15:08:12 +00001439void RetainSummaryManager::InitializeClassMethodSummaries() {
Ted Kremenekec315332009-05-07 23:40:42 +00001440 assert(ScratchArgs.isEmpty());
Mike Stump1eb44332009-09-09 15:08:12 +00001441 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek6fe2b7a2009-10-15 22:25:12 +00001442 addClassMethSummary("NSAssertionHandler", "currentHandler",
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001443 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Mike Stump1eb44332009-09-09 15:08:12 +00001444
Ted Kremenek6d348932008-10-21 15:53:15 +00001445 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001446 ScratchArgs = AF.add(ScratchArgs, 0, Autorelease);
Ted Kremenek6fe2b7a2009-10-15 22:25:12 +00001447 addClassMethSummary("NSAutoreleasePool", "addObject",
1448 getPersistentSummary(RetEffect::MakeNoRet(),
1449 DoNothing, Autorelease));
Ted Kremenek9c32d082008-05-06 00:30:21 +00001450}
1451
Ted Kremenek1f180c32008-06-23 22:21:20 +00001452void RetainSummaryManager::InitializeMethodSummaries() {
Mike Stump1eb44332009-09-09 15:08:12 +00001453
1454 assert (ScratchArgs.isEmpty());
1455
Ted Kremenekc8395602008-05-06 21:26:51 +00001456 // Create the "init" selector. It just acts as a pass-through for the
1457 // receiver.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001458 const RetainSummary *InitSumm = getPersistentSummary(ObjCInitRetE, DecRefMsg);
Ted Kremenekac02f202009-08-20 05:13:36 +00001459 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
1460
1461 // awakeAfterUsingCoder: behaves basically like an 'init' method. It
1462 // claims the receiver and returns a retained object.
1463 addNSObjectMethSummary(GetUnarySelector("awakeAfterUsingCoder", Ctx),
1464 InitSumm);
Mike Stump1eb44332009-09-09 15:08:12 +00001465
Ted Kremenekc8395602008-05-06 21:26:51 +00001466 // The next methods are allocators.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001467 const RetainSummary *AllocSumm = getPersistentSummary(ObjCAllocRetE);
1468 const RetainSummary *CFAllocSumm =
Ted Kremeneka834fb42009-08-28 19:52:12 +00001469 getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Mike Stump1eb44332009-09-09 15:08:12 +00001470
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001471 // Create the "retain" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001472 RetEffect NoRet = RetEffect::MakeNoRet();
Ted Kremenek93edbc52011-10-05 23:54:29 +00001473 const RetainSummary *Summ = getPersistentSummary(NoRet, IncRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001474 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001475
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001476 // Create the "release" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001477 Summ = getPersistentSummary(NoRet, DecRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001478 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001479
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001480 // Create the -dealloc summary.
Jordy Rose500abad2011-08-21 19:41:36 +00001481 Summ = getPersistentSummary(NoRet, Dealloc);
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001482 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001483
1484 // Create the "autorelease" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001485 Summ = getPersistentSummary(NoRet, Autorelease);
Ted Kremenek553cf182008-06-25 21:21:56 +00001486 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001487
Mike Stump1eb44332009-09-09 15:08:12 +00001488 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremenek89e202d2009-02-23 02:51:29 +00001489 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1490 // self-own themselves. However, they only do this once they are displayed.
1491 // Thus, we need to track an NSWindow's display status.
1492 // This is tracked in <rdar://problem/6062711>.
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +00001493 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001494 const RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenek78a35a32009-05-12 20:06:54 +00001495 StopTracking,
1496 StopTracking);
Mike Stump1eb44332009-09-09 15:08:12 +00001497
Ted Kremenek99d02692009-04-03 19:02:51 +00001498 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1499
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001500 // For NSPanel (which subclasses NSWindow), allocated objects are not
1501 // self-owned.
Ted Kremenek99d02692009-04-03 19:02:51 +00001502 // FIXME: For now we don't track NSPanels. object for the same reason
1503 // as for NSWindow objects.
1504 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
Mike Stump1eb44332009-09-09 15:08:12 +00001505
Jordan Rosee36d81b2013-01-31 22:06:02 +00001506 // Don't track allocated autorelease pools, as it is okay to prematurely
Ted Kremenekba67f6a2009-05-18 23:14:34 +00001507 // exit a method.
1508 addClassMethSummary("NSAutoreleasePool", "alloc", NoTrackYet);
Ted Kremeneka9797122012-02-18 21:37:48 +00001509 addClassMethSummary("NSAutoreleasePool", "allocWithZone", NoTrackYet, false);
Jordan Rosee36d81b2013-01-31 22:06:02 +00001510 addClassMethSummary("NSAutoreleasePool", "new", NoTrackYet);
Ted Kremenek553cf182008-06-25 21:21:56 +00001511
Ted Kremenek767d6492009-05-20 22:39:57 +00001512 // Create summaries QCRenderer/QCView -createSnapShotImageOfType:
1513 addInstMethSummary("QCRenderer", AllocSumm,
1514 "createSnapshotImageOfType", NULL);
1515 addInstMethSummary("QCView", AllocSumm,
1516 "createSnapshotImageOfType", NULL);
1517
Ted Kremenek211a9c62009-06-15 20:58:58 +00001518 // Create summaries for CIContext, 'createCGImage' and
Ted Kremeneka834fb42009-08-28 19:52:12 +00001519 // 'createCGLayerWithSize'. These objects are CF objects, and are not
1520 // automatically garbage collected.
1521 addInstMethSummary("CIContext", CFAllocSumm,
Ted Kremenek767d6492009-05-20 22:39:57 +00001522 "createCGImage", "fromRect", NULL);
Ted Kremeneka834fb42009-08-28 19:52:12 +00001523 addInstMethSummary("CIContext", CFAllocSumm,
Mike Stump1eb44332009-09-09 15:08:12 +00001524 "createCGImage", "fromRect", "format", "colorSpace", NULL);
Ted Kremeneka834fb42009-08-28 19:52:12 +00001525 addInstMethSummary("CIContext", CFAllocSumm, "createCGLayerWithSize",
Ted Kremenek211a9c62009-06-15 20:58:58 +00001526 "info", NULL);
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001527}
1528
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001529//===----------------------------------------------------------------------===//
Ted Kremenekc887d132009-04-29 18:50:19 +00001530// Error reporting.
1531//===----------------------------------------------------------------------===//
Ted Kremenekc887d132009-04-29 18:50:19 +00001532namespace {
Jordy Roseec9ef852011-08-23 20:55:48 +00001533 typedef llvm::DenseMap<const ExplodedNode *, const RetainSummary *>
1534 SummaryLogTy;
1535
Ted Kremenekc887d132009-04-29 18:50:19 +00001536 //===-------------===//
1537 // Bug Descriptions. //
Mike Stump1eb44332009-09-09 15:08:12 +00001538 //===-------------===//
1539
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001540 class CFRefBug : public BugType {
Ted Kremenekc887d132009-04-29 18:50:19 +00001541 protected:
Jordy Rose35c86952011-08-24 05:47:39 +00001542 CFRefBug(StringRef name)
Ted Kremenek6fd45052012-04-05 20:43:28 +00001543 : BugType(name, categories::MemoryCoreFoundationObjectiveC) {}
Ted Kremenekc887d132009-04-29 18:50:19 +00001544 public:
Mike Stump1eb44332009-09-09 15:08:12 +00001545
Ted Kremenekc887d132009-04-29 18:50:19 +00001546 // FIXME: Eventually remove.
Jordy Rose35c86952011-08-24 05:47:39 +00001547 virtual const char *getDescription() const = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001548
Ted Kremenekc887d132009-04-29 18:50:19 +00001549 virtual bool isLeak() const { return false; }
1550 };
Mike Stump1eb44332009-09-09 15:08:12 +00001551
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001552 class UseAfterRelease : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001553 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001554 UseAfterRelease() : CFRefBug("Use-after-release") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001555
Jordy Rose35c86952011-08-24 05:47:39 +00001556 const char *getDescription() const {
Ted Kremenekc887d132009-04-29 18:50:19 +00001557 return "Reference-counted object is used after it is released";
Mike Stump1eb44332009-09-09 15:08:12 +00001558 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001559 };
Mike Stump1eb44332009-09-09 15:08:12 +00001560
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001561 class BadRelease : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001562 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001563 BadRelease() : CFRefBug("Bad release") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001564
Jordy Rose35c86952011-08-24 05:47:39 +00001565 const char *getDescription() const {
Ted Kremenekbb206fd2009-10-01 17:31:50 +00001566 return "Incorrect decrement of the reference count of an object that is "
1567 "not owned at this point by the caller";
Ted Kremenekc887d132009-04-29 18:50:19 +00001568 }
1569 };
Mike Stump1eb44332009-09-09 15:08:12 +00001570
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001571 class DeallocGC : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001572 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001573 DeallocGC()
1574 : CFRefBug("-dealloc called while using garbage collection") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001575
Ted Kremenekc887d132009-04-29 18:50:19 +00001576 const char *getDescription() const {
Ted Kremenek369de562009-05-09 00:10:05 +00001577 return "-dealloc called while using garbage collection";
Ted Kremenekc887d132009-04-29 18:50:19 +00001578 }
1579 };
Mike Stump1eb44332009-09-09 15:08:12 +00001580
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001581 class DeallocNotOwned : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001582 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001583 DeallocNotOwned()
1584 : CFRefBug("-dealloc sent to non-exclusively owned object") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001585
Ted Kremenekc887d132009-04-29 18:50:19 +00001586 const char *getDescription() const {
1587 return "-dealloc sent to object that may be referenced elsewhere";
1588 }
Mike Stump1eb44332009-09-09 15:08:12 +00001589 };
1590
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001591 class OverAutorelease : public CFRefBug {
Ted Kremenek369de562009-05-09 00:10:05 +00001592 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001593 OverAutorelease()
Jordan Rose2545b1d2013-04-23 01:42:25 +00001594 : CFRefBug("Object autoreleased too many times") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001595
Ted Kremenek369de562009-05-09 00:10:05 +00001596 const char *getDescription() const {
Jordan Rose2545b1d2013-04-23 01:42:25 +00001597 return "Object autoreleased too many times";
Ted Kremenek369de562009-05-09 00:10:05 +00001598 }
1599 };
Mike Stump1eb44332009-09-09 15:08:12 +00001600
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001601 class ReturnedNotOwnedForOwned : public CFRefBug {
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001602 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001603 ReturnedNotOwnedForOwned()
1604 : CFRefBug("Method should return an owned object") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001605
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001606 const char *getDescription() const {
Jordy Rose5b5402b2011-07-15 22:17:54 +00001607 return "Object with a +0 retain count returned to caller where a +1 "
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001608 "(owning) retain count is expected";
1609 }
1610 };
Mike Stump1eb44332009-09-09 15:08:12 +00001611
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001612 class Leak : public CFRefBug {
Benjamin Kramerfacde172012-06-06 17:32:50 +00001613 public:
1614 Leak(StringRef name)
1615 : CFRefBug(name) {
Jordy Rosedb92bb62011-08-25 01:14:38 +00001616 // Leaks should not be reported if they are post-dominated by a sink.
1617 setSuppressOnSink(true);
1618 }
Mike Stump1eb44332009-09-09 15:08:12 +00001619
Jordy Rose35c86952011-08-24 05:47:39 +00001620 const char *getDescription() const { return ""; }
Mike Stump1eb44332009-09-09 15:08:12 +00001621
Ted Kremenekc887d132009-04-29 18:50:19 +00001622 bool isLeak() const { return true; }
1623 };
Mike Stump1eb44332009-09-09 15:08:12 +00001624
Ted Kremenekc887d132009-04-29 18:50:19 +00001625 //===---------===//
1626 // Bug Reports. //
1627 //===---------===//
Mike Stump1eb44332009-09-09 15:08:12 +00001628
Jordy Rose01153492012-03-24 02:45:35 +00001629 class CFRefReportVisitor : public BugReporterVisitorImpl<CFRefReportVisitor> {
Anna Zaks23f395e2011-08-20 01:27:22 +00001630 protected:
Anna Zaksdc757b02011-08-19 23:21:56 +00001631 SymbolRef Sym;
Jordy Roseec9ef852011-08-23 20:55:48 +00001632 const SummaryLogTy &SummaryLog;
Jordy Rose35c86952011-08-24 05:47:39 +00001633 bool GCEnabled;
Anna Zaks23f395e2011-08-20 01:27:22 +00001634
Anna Zaksdc757b02011-08-19 23:21:56 +00001635 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001636 CFRefReportVisitor(SymbolRef sym, bool gcEnabled, const SummaryLogTy &log)
1637 : Sym(sym), SummaryLog(log), GCEnabled(gcEnabled) {}
Anna Zaksdc757b02011-08-19 23:21:56 +00001638
Anna Zaks23f395e2011-08-20 01:27:22 +00001639 virtual void Profile(llvm::FoldingSetNodeID &ID) const {
Anna Zaksdc757b02011-08-19 23:21:56 +00001640 static int x = 0;
1641 ID.AddPointer(&x);
1642 ID.AddPointer(Sym);
1643 }
1644
Anna Zaks23f395e2011-08-20 01:27:22 +00001645 virtual PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
1646 const ExplodedNode *PrevN,
1647 BugReporterContext &BRC,
1648 BugReport &BR);
1649
1650 virtual PathDiagnosticPiece *getEndPath(BugReporterContext &BRC,
1651 const ExplodedNode *N,
1652 BugReport &BR);
1653 };
1654
1655 class CFRefLeakReportVisitor : public CFRefReportVisitor {
1656 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001657 CFRefLeakReportVisitor(SymbolRef sym, bool GCEnabled,
Jordy Roseec9ef852011-08-23 20:55:48 +00001658 const SummaryLogTy &log)
Jordy Rose35c86952011-08-24 05:47:39 +00001659 : CFRefReportVisitor(sym, GCEnabled, log) {}
Anna Zaks23f395e2011-08-20 01:27:22 +00001660
1661 PathDiagnosticPiece *getEndPath(BugReporterContext &BRC,
1662 const ExplodedNode *N,
1663 BugReport &BR);
Jordy Rose01153492012-03-24 02:45:35 +00001664
1665 virtual BugReporterVisitor *clone() const {
1666 // The curiously-recurring template pattern only works for one level of
1667 // subclassing. Rather than make a new template base for
1668 // CFRefReportVisitor, we simply override clone() to do the right thing.
1669 // This could be trouble someday if BugReporterVisitorImpl is ever
1670 // used for something else besides a convenient implementation of clone().
1671 return new CFRefLeakReportVisitor(*this);
1672 }
Anna Zaksdc757b02011-08-19 23:21:56 +00001673 };
1674
Anna Zakse172e8b2011-08-17 23:00:25 +00001675 class CFRefReport : public BugReport {
Jordy Rose20589562011-08-24 22:39:09 +00001676 void addGCModeDescription(const LangOptions &LOpts, bool GCEnabled);
Jordy Rose35c86952011-08-24 05:47:39 +00001677
Ted Kremenekc887d132009-04-29 18:50:19 +00001678 public:
Jordy Rose20589562011-08-24 22:39:09 +00001679 CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1680 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1681 bool registerVisitor = true)
Anna Zaksedf4dae2011-08-22 18:54:07 +00001682 : BugReport(D, D.getDescription(), n) {
Anna Zaks23f395e2011-08-20 01:27:22 +00001683 if (registerVisitor)
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 }
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001687
Jordy Rose20589562011-08-24 22:39:09 +00001688 CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1689 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1690 StringRef endText)
Anna Zaksedf4dae2011-08-22 18:54:07 +00001691 : BugReport(D, D.getDescription(), endText, n) {
Jordy Rose20589562011-08-24 22:39:09 +00001692 addVisitor(new CFRefReportVisitor(sym, GCEnabled, Log));
1693 addGCModeDescription(LOpts, GCEnabled);
Anna Zaksdc757b02011-08-19 23:21:56 +00001694 }
Mike Stump1eb44332009-09-09 15:08:12 +00001695
Anna Zakse172e8b2011-08-17 23:00:25 +00001696 virtual std::pair<ranges_iterator, ranges_iterator> getRanges() {
Anna Zaksedf4dae2011-08-22 18:54:07 +00001697 const CFRefBug& BugTy = static_cast<CFRefBug&>(getBugType());
1698 if (!BugTy.isLeak())
Anna Zakse172e8b2011-08-17 23:00:25 +00001699 return BugReport::getRanges();
Ted Kremenekc887d132009-04-29 18:50:19 +00001700 else
Argyrios Kyrtzidis640ccf02010-12-04 01:12:15 +00001701 return std::make_pair(ranges_iterator(), ranges_iterator());
Ted Kremenekc887d132009-04-29 18:50:19 +00001702 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001703 };
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001704
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001705 class CFRefLeakReport : public CFRefReport {
Ted Kremenekc887d132009-04-29 18:50:19 +00001706 const MemRegion* AllocBinding;
1707 public:
Jordy Rose20589562011-08-24 22:39:09 +00001708 CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1709 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
Ted Kremenek08a838d2013-04-16 21:44:22 +00001710 CheckerContext &Ctx,
1711 bool IncludeAllocationLine);
Mike Stump1eb44332009-09-09 15:08:12 +00001712
Anna Zaks590dd8e2011-09-20 21:38:35 +00001713 PathDiagnosticLocation getLocation(const SourceManager &SM) const {
1714 assert(Location.isValid());
1715 return Location;
1716 }
Mike Stump1eb44332009-09-09 15:08:12 +00001717 };
Ted Kremenekc887d132009-04-29 18:50:19 +00001718} // end anonymous namespace
1719
Jordy Rose20589562011-08-24 22:39:09 +00001720void CFRefReport::addGCModeDescription(const LangOptions &LOpts,
1721 bool GCEnabled) {
Jordy Rosef95b19d2011-08-24 20:38:42 +00001722 const char *GCModeDescription = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001723
Douglas Gregore289d812011-09-13 17:21:33 +00001724 switch (LOpts.getGC()) {
Anna Zaks7f2531c2011-08-22 20:31:28 +00001725 case LangOptions::GCOnly:
Jordy Rose20589562011-08-24 22:39:09 +00001726 assert(GCEnabled);
Jordy Rose35c86952011-08-24 05:47:39 +00001727 GCModeDescription = "Code is compiled to only use garbage collection";
1728 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001729
Anna Zaks7f2531c2011-08-22 20:31:28 +00001730 case LangOptions::NonGC:
Jordy Rose20589562011-08-24 22:39:09 +00001731 assert(!GCEnabled);
Jordy Rose35c86952011-08-24 05:47:39 +00001732 GCModeDescription = "Code is compiled to use reference counts";
1733 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001734
Anna Zaks7f2531c2011-08-22 20:31:28 +00001735 case LangOptions::HybridGC:
Jordy Rose20589562011-08-24 22:39:09 +00001736 if (GCEnabled) {
Jordy Rose35c86952011-08-24 05:47:39 +00001737 GCModeDescription = "Code is compiled to use either garbage collection "
1738 "(GC) or reference counts (non-GC). The bug occurs "
1739 "with GC enabled";
1740 break;
1741 } else {
1742 GCModeDescription = "Code is compiled to use either garbage collection "
1743 "(GC) or reference counts (non-GC). The bug occurs "
1744 "in non-GC mode";
1745 break;
Anna Zaks7f2531c2011-08-22 20:31:28 +00001746 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001747 }
Jordy Rose35c86952011-08-24 05:47:39 +00001748
Jordy Rosef95b19d2011-08-24 20:38:42 +00001749 assert(GCModeDescription && "invalid/unknown GC mode");
Jordy Rose35c86952011-08-24 05:47:39 +00001750 addExtraText(GCModeDescription);
Ted Kremenekc887d132009-04-29 18:50:19 +00001751}
1752
Jordy Rose70fdbc32012-05-12 05:10:43 +00001753static bool isNumericLiteralExpression(const Expr *E) {
1754 // FIXME: This set of cases was copied from SemaExprObjC.
1755 return isa<IntegerLiteral>(E) ||
1756 isa<CharacterLiteral>(E) ||
1757 isa<FloatingLiteral>(E) ||
1758 isa<ObjCBoolLiteralExpr>(E) ||
1759 isa<CXXBoolLiteralExpr>(E);
1760}
1761
Anna Zaksdc757b02011-08-19 23:21:56 +00001762PathDiagnosticPiece *CFRefReportVisitor::VisitNode(const ExplodedNode *N,
1763 const ExplodedNode *PrevN,
1764 BugReporterContext &BRC,
1765 BugReport &BR) {
Jordan Rose28038f32012-07-10 22:07:42 +00001766 // FIXME: We will eventually need to handle non-statement-based events
1767 // (__attribute__((cleanup))).
David Blaikie7a95de62013-02-21 22:23:56 +00001768 if (!N->getLocation().getAs<StmtPoint>())
Ted Kremenek2033a952009-05-13 07:12:33 +00001769 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001770
Ted Kremenek8966bc12009-05-06 21:39:49 +00001771 // Check if the type state has changed.
Ted Kremenek8bef8232012-01-26 21:29:00 +00001772 ProgramStateRef PrevSt = PrevN->getState();
1773 ProgramStateRef CurrSt = N->getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001774 const LocationContext *LCtx = N->getLocationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00001775
Anna Zaks8d6b43c2012-08-14 00:36:15 +00001776 const RefVal* CurrT = getRefBinding(CurrSt, Sym);
Ted Kremenekc887d132009-04-29 18:50:19 +00001777 if (!CurrT) return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001778
Ted Kremenekb65be702009-06-18 01:23:53 +00001779 const RefVal &CurrV = *CurrT;
Anna Zaks8d6b43c2012-08-14 00:36:15 +00001780 const RefVal *PrevT = getRefBinding(PrevSt, Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00001781
Ted Kremenekc887d132009-04-29 18:50:19 +00001782 // Create a string buffer to constain all the useful things we want
1783 // to tell the user.
1784 std::string sbuf;
1785 llvm::raw_string_ostream os(sbuf);
Mike Stump1eb44332009-09-09 15:08:12 +00001786
Ted Kremenekc887d132009-04-29 18:50:19 +00001787 // This is the allocation site since the previous node had no bindings
1788 // for this symbol.
1789 if (!PrevT) {
David Blaikie7a95de62013-02-21 22:23:56 +00001790 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
Mike Stump1eb44332009-09-09 15:08:12 +00001791
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001792 if (isa<ObjCArrayLiteral>(S)) {
1793 os << "NSArray literal is an object with a +0 retain count";
Mike Stump1eb44332009-09-09 15:08:12 +00001794 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001795 else if (isa<ObjCDictionaryLiteral>(S)) {
1796 os << "NSDictionary literal is an object with a +0 retain count";
Ted Kremenekc887d132009-04-29 18:50:19 +00001797 }
Jordy Rose70fdbc32012-05-12 05:10:43 +00001798 else if (const ObjCBoxedExpr *BL = dyn_cast<ObjCBoxedExpr>(S)) {
1799 if (isNumericLiteralExpression(BL->getSubExpr()))
1800 os << "NSNumber literal is an object with a +0 retain count";
1801 else {
1802 const ObjCInterfaceDecl *BoxClass = 0;
1803 if (const ObjCMethodDecl *Method = BL->getBoxingMethod())
1804 BoxClass = Method->getClassInterface();
1805
1806 // We should always be able to find the boxing class interface,
1807 // but consider this future-proofing.
1808 if (BoxClass)
1809 os << *BoxClass << " b";
1810 else
1811 os << "B";
1812
1813 os << "oxed expression produces an object with a +0 retain count";
1814 }
1815 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001816 else {
1817 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
1818 // Get the name of the callee (if it is available).
1819 SVal X = CurrSt->getSValAsScalarOrLoc(CE->getCallee(), LCtx);
1820 if (const FunctionDecl *FD = X.getAsFunctionDecl())
1821 os << "Call to function '" << *FD << '\'';
1822 else
1823 os << "function call";
Ted Kremenekc887d132009-04-29 18:50:19 +00001824 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001825 else {
Jordan Rose8919e682012-07-18 21:59:51 +00001826 assert(isa<ObjCMessageExpr>(S));
Jordan Rosed563d3f2012-07-30 20:22:09 +00001827 CallEventManager &Mgr = CurrSt->getStateManager().getCallEventManager();
1828 CallEventRef<ObjCMethodCall> Call
1829 = Mgr.getObjCMethodCall(cast<ObjCMessageExpr>(S), CurrSt, LCtx);
1830
1831 switch (Call->getMessageKind()) {
Jordan Rose8919e682012-07-18 21:59:51 +00001832 case OCM_Message:
1833 os << "Method";
1834 break;
1835 case OCM_PropertyAccess:
1836 os << "Property";
1837 break;
1838 case OCM_Subscript:
1839 os << "Subscript";
1840 break;
1841 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001842 }
1843
1844 if (CurrV.getObjKind() == RetEffect::CF) {
1845 os << " returns a Core Foundation object with a ";
1846 }
1847 else {
1848 assert (CurrV.getObjKind() == RetEffect::ObjC);
1849 os << " returns an Objective-C object with a ";
1850 }
1851
1852 if (CurrV.isOwned()) {
1853 os << "+1 retain count";
1854
1855 if (GCEnabled) {
1856 assert(CurrV.getObjKind() == RetEffect::CF);
1857 os << ". "
1858 "Core Foundation objects are not automatically garbage collected.";
1859 }
1860 }
1861 else {
1862 assert (CurrV.isNotOwned());
1863 os << "+0 retain count";
1864 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001865 }
Mike Stump1eb44332009-09-09 15:08:12 +00001866
Anna Zaks220ac8c2011-09-15 01:08:34 +00001867 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
1868 N->getLocationContext());
Ted Kremenekc887d132009-04-29 18:50:19 +00001869 return new PathDiagnosticEventPiece(Pos, os.str());
1870 }
Mike Stump1eb44332009-09-09 15:08:12 +00001871
Ted Kremenekc887d132009-04-29 18:50:19 +00001872 // Gather up the effects that were performed on the object at this
1873 // program point
Chris Lattner5f9e2722011-07-23 10:55:15 +00001874 SmallVector<ArgEffect, 2> AEffects;
Mike Stump1eb44332009-09-09 15:08:12 +00001875
Jordy Roseec9ef852011-08-23 20:55:48 +00001876 const ExplodedNode *OrigNode = BRC.getNodeResolver().getOriginalNode(N);
1877 if (const RetainSummary *Summ = SummaryLog.lookup(OrigNode)) {
Ted Kremenekc887d132009-04-29 18:50:19 +00001878 // We only have summaries attached to nodes after evaluating CallExpr and
1879 // ObjCMessageExprs.
David Blaikie7a95de62013-02-21 22:23:56 +00001880 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
Mike Stump1eb44332009-09-09 15:08:12 +00001881
Ted Kremenek5f85e172009-07-22 22:35:28 +00001882 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
Ted Kremenekc887d132009-04-29 18:50:19 +00001883 // Iterate through the parameter expressions and see if the symbol
1884 // was ever passed as an argument.
1885 unsigned i = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001886
Ted Kremenek5f85e172009-07-22 22:35:28 +00001887 for (CallExpr::const_arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
Ted Kremenekc887d132009-04-29 18:50:19 +00001888 AI!=AE; ++AI, ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00001889
Ted Kremenekc887d132009-04-29 18:50:19 +00001890 // Retrieve the value of the argument. Is it the symbol
1891 // we are interested in?
Ted Kremenek5eca4822012-01-06 22:09:28 +00001892 if (CurrSt->getSValAsScalarOrLoc(*AI, LCtx).getAsLocSymbol() != Sym)
Ted Kremenekc887d132009-04-29 18:50:19 +00001893 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001894
Ted Kremenekc887d132009-04-29 18:50:19 +00001895 // We have an argument. Get the effect!
1896 AEffects.push_back(Summ->getArg(i));
1897 }
1898 }
Mike Stump1eb44332009-09-09 15:08:12 +00001899 else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00001900 if (const Expr *receiver = ME->getInstanceReceiver())
Ted Kremenek5eca4822012-01-06 22:09:28 +00001901 if (CurrSt->getSValAsScalarOrLoc(receiver, LCtx)
1902 .getAsLocSymbol() == Sym) {
Ted Kremenekc887d132009-04-29 18:50:19 +00001903 // The symbol we are tracking is the receiver.
1904 AEffects.push_back(Summ->getReceiverEffect());
1905 }
1906 }
1907 }
Mike Stump1eb44332009-09-09 15:08:12 +00001908
Ted Kremenekc887d132009-04-29 18:50:19 +00001909 do {
1910 // Get the previous type state.
1911 RefVal PrevV = *PrevT;
Mike Stump1eb44332009-09-09 15:08:12 +00001912
Ted Kremenekc887d132009-04-29 18:50:19 +00001913 // Specially handle -dealloc.
Benjamin Kramera1da6b22013-08-16 21:57:14 +00001914 if (!GCEnabled && std::find(AEffects.begin(), AEffects.end(), Dealloc) !=
1915 AEffects.end()) {
Ted Kremenekc887d132009-04-29 18:50:19 +00001916 // Determine if the object's reference count was pushed to zero.
1917 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
1918 // We may not have transitioned to 'release' if we hit an error.
1919 // This case is handled elsewhere.
1920 if (CurrV.getKind() == RefVal::Released) {
Ted Kremenekf21332e2009-05-08 20:01:42 +00001921 assert(CurrV.getCombinedCounts() == 0);
Ted Kremenekc887d132009-04-29 18:50:19 +00001922 os << "Object released by directly sending the '-dealloc' message";
1923 break;
1924 }
1925 }
Mike Stump1eb44332009-09-09 15:08:12 +00001926
Ted Kremenekc887d132009-04-29 18:50:19 +00001927 // Specially handle CFMakeCollectable and friends.
Benjamin Kramera1da6b22013-08-16 21:57:14 +00001928 if (std::find(AEffects.begin(), AEffects.end(), MakeCollectable) !=
1929 AEffects.end()) {
Ted Kremenekc887d132009-04-29 18:50:19 +00001930 // Get the name of the function.
David Blaikie7a95de62013-02-21 22:23:56 +00001931 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001932 SVal X =
1933 CurrSt->getSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee(), LCtx);
Ted Kremenek9c378f72011-08-12 23:37:29 +00001934 const FunctionDecl *FD = X.getAsFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001935
Jordy Rose35c86952011-08-24 05:47:39 +00001936 if (GCEnabled) {
Ted Kremenekc887d132009-04-29 18:50:19 +00001937 // Determine if the object's reference count was pushed to zero.
1938 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
Mike Stump1eb44332009-09-09 15:08:12 +00001939
Benjamin Kramerb8989f22011-10-14 18:45:37 +00001940 os << "In GC mode a call to '" << *FD
Ted Kremenekc887d132009-04-29 18:50:19 +00001941 << "' decrements an object's retain count and registers the "
1942 "object with the garbage collector. ";
Mike Stump1eb44332009-09-09 15:08:12 +00001943
Ted Kremenekc887d132009-04-29 18:50:19 +00001944 if (CurrV.getKind() == RefVal::Released) {
1945 assert(CurrV.getCount() == 0);
1946 os << "Since it now has a 0 retain count the object can be "
1947 "automatically collected by the garbage collector.";
1948 }
1949 else
1950 os << "An object must have a 0 retain count to be garbage collected. "
1951 "After this call its retain count is +" << CurrV.getCount()
1952 << '.';
1953 }
Mike Stump1eb44332009-09-09 15:08:12 +00001954 else
Benjamin Kramerb8989f22011-10-14 18:45:37 +00001955 os << "When GC is not enabled a call to '" << *FD
Ted Kremenekc887d132009-04-29 18:50:19 +00001956 << "' has no effect on its argument.";
Mike Stump1eb44332009-09-09 15:08:12 +00001957
Ted Kremenekc887d132009-04-29 18:50:19 +00001958 // Nothing more to say.
1959 break;
1960 }
Mike Stump1eb44332009-09-09 15:08:12 +00001961
1962 // Determine if the typestate has changed.
Ted Kremenekc887d132009-04-29 18:50:19 +00001963 if (!(PrevV == CurrV))
1964 switch (CurrV.getKind()) {
1965 case RefVal::Owned:
1966 case RefVal::NotOwned:
Mike Stump1eb44332009-09-09 15:08:12 +00001967
Ted Kremenekf21332e2009-05-08 20:01:42 +00001968 if (PrevV.getCount() == CurrV.getCount()) {
1969 // Did an autorelease message get sent?
1970 if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
1971 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001972
Zhongxing Xu264e9372009-05-12 10:10:00 +00001973 assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount());
Jordan Rose2545b1d2013-04-23 01:42:25 +00001974 os << "Object autoreleased";
Ted Kremenekf21332e2009-05-08 20:01:42 +00001975 break;
1976 }
Mike Stump1eb44332009-09-09 15:08:12 +00001977
Ted Kremenekc887d132009-04-29 18:50:19 +00001978 if (PrevV.getCount() > CurrV.getCount())
1979 os << "Reference count decremented.";
1980 else
1981 os << "Reference count incremented.";
Mike Stump1eb44332009-09-09 15:08:12 +00001982
Ted Kremenekc887d132009-04-29 18:50:19 +00001983 if (unsigned Count = CurrV.getCount())
1984 os << " The object now has a +" << Count << " retain count.";
Mike Stump1eb44332009-09-09 15:08:12 +00001985
Ted Kremenekc887d132009-04-29 18:50:19 +00001986 if (PrevV.getKind() == RefVal::Released) {
Jordy Rose35c86952011-08-24 05:47:39 +00001987 assert(GCEnabled && CurrV.getCount() > 0);
Jordy Rose74b7b2b2012-03-17 05:49:15 +00001988 os << " The object is not eligible for garbage collection until "
1989 "the retain count reaches 0 again.";
Ted Kremenekc887d132009-04-29 18:50:19 +00001990 }
Mike Stump1eb44332009-09-09 15:08:12 +00001991
Ted Kremenekc887d132009-04-29 18:50:19 +00001992 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001993
Ted Kremenekc887d132009-04-29 18:50:19 +00001994 case RefVal::Released:
1995 os << "Object released.";
1996 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001997
Ted Kremenekc887d132009-04-29 18:50:19 +00001998 case RefVal::ReturnedOwned:
Jordy Rose74b7b2b2012-03-17 05:49:15 +00001999 // Autoreleases can be applied after marking a node ReturnedOwned.
2000 if (CurrV.getAutoreleaseCount())
2001 return NULL;
2002
2003 os << "Object returned to caller as an owning reference (single "
2004 "retain count transferred to caller)";
Ted Kremenekc887d132009-04-29 18:50:19 +00002005 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002006
Ted Kremenekc887d132009-04-29 18:50:19 +00002007 case RefVal::ReturnedNotOwned:
Ted Kremenekf1365462011-05-26 18:45:44 +00002008 os << "Object returned to caller with a +0 retain count";
Ted Kremenekc887d132009-04-29 18:50:19 +00002009 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002010
Ted Kremenekc887d132009-04-29 18:50:19 +00002011 default:
2012 return NULL;
2013 }
Mike Stump1eb44332009-09-09 15:08:12 +00002014
Ted Kremenekc887d132009-04-29 18:50:19 +00002015 // Emit any remaining diagnostics for the argument effects (if any).
Chris Lattner5f9e2722011-07-23 10:55:15 +00002016 for (SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
Ted Kremenekc887d132009-04-29 18:50:19 +00002017 E=AEffects.end(); I != E; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +00002018
Ted Kremenekc887d132009-04-29 18:50:19 +00002019 // A bunch of things have alternate behavior under GC.
Jordy Rose35c86952011-08-24 05:47:39 +00002020 if (GCEnabled)
Ted Kremenekc887d132009-04-29 18:50:19 +00002021 switch (*I) {
2022 default: break;
2023 case Autorelease:
2024 os << "In GC mode an 'autorelease' has no effect.";
2025 continue;
2026 case IncRefMsg:
2027 os << "In GC mode the 'retain' message has no effect.";
2028 continue;
2029 case DecRefMsg:
2030 os << "In GC mode the 'release' message has no effect.";
2031 continue;
2032 }
2033 }
Mike Stump1eb44332009-09-09 15:08:12 +00002034 } while (0);
2035
Ted Kremenekc887d132009-04-29 18:50:19 +00002036 if (os.str().empty())
2037 return 0; // We have nothing to say!
Ted Kremenek2033a952009-05-13 07:12:33 +00002038
David Blaikie7a95de62013-02-21 22:23:56 +00002039 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
Anna Zaks220ac8c2011-09-15 01:08:34 +00002040 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
2041 N->getLocationContext());
Ted Kremenek9c378f72011-08-12 23:37:29 +00002042 PathDiagnosticPiece *P = new PathDiagnosticEventPiece(Pos, os.str());
Mike Stump1eb44332009-09-09 15:08:12 +00002043
Ted Kremenekc887d132009-04-29 18:50:19 +00002044 // Add the range by scanning the children of the statement for any bindings
2045 // to Sym.
Mike Stump1eb44332009-09-09 15:08:12 +00002046 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
Ted Kremenek5f85e172009-07-22 22:35:28 +00002047 I!=E; ++I)
Ted Kremenek9c378f72011-08-12 23:37:29 +00002048 if (const Expr *Exp = dyn_cast_or_null<Expr>(*I))
Ted Kremenek5eca4822012-01-06 22:09:28 +00002049 if (CurrSt->getSValAsScalarOrLoc(Exp, LCtx).getAsLocSymbol() == Sym) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002050 P->addRange(Exp->getSourceRange());
2051 break;
2052 }
Mike Stump1eb44332009-09-09 15:08:12 +00002053
Ted Kremenekc887d132009-04-29 18:50:19 +00002054 return P;
2055}
2056
Anna Zakse7e01682012-02-28 22:39:22 +00002057// Find the first node in the current function context that referred to the
2058// tracked symbol and the memory location that value was stored to. Note, the
2059// value is only reported if the allocation occurred in the same function as
Anna Zaks7a87e522013-04-10 21:42:06 +00002060// the leak. The function can also return a location context, which should be
2061// treated as interesting.
2062struct AllocationInfo {
2063 const ExplodedNode* N;
Anna Zaksee9043b2013-04-10 22:56:30 +00002064 const MemRegion *R;
Anna Zaks7a87e522013-04-10 21:42:06 +00002065 const LocationContext *InterestingMethodContext;
Anna Zaksee9043b2013-04-10 22:56:30 +00002066 AllocationInfo(const ExplodedNode *InN,
2067 const MemRegion *InR,
Anna Zaks7a87e522013-04-10 21:42:06 +00002068 const LocationContext *InInterestingMethodContext) :
2069 N(InN), R(InR), InterestingMethodContext(InInterestingMethodContext) {}
2070};
2071
2072static AllocationInfo
Ted Kremenek18c66fd2011-08-15 22:09:50 +00002073GetAllocationSite(ProgramStateManager& StateMgr, const ExplodedNode *N,
Ted Kremenekc887d132009-04-29 18:50:19 +00002074 SymbolRef Sym) {
Anna Zaks7a87e522013-04-10 21:42:06 +00002075 const ExplodedNode *AllocationNode = N;
2076 const ExplodedNode *AllocationNodeInCurrentContext = N;
Mike Stump1eb44332009-09-09 15:08:12 +00002077 const MemRegion* FirstBinding = 0;
Anna Zakse7e01682012-02-28 22:39:22 +00002078 const LocationContext *LeakContext = N->getLocationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002079
Anna Zaks7a87e522013-04-10 21:42:06 +00002080 // The location context of the init method called on the leaked object, if
2081 // available.
2082 const LocationContext *InitMethodContext = 0;
2083
Ted Kremenekc887d132009-04-29 18:50:19 +00002084 while (N) {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002085 ProgramStateRef St = N->getState();
Anna Zaks7a87e522013-04-10 21:42:06 +00002086 const LocationContext *NContext = N->getLocationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002087
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002088 if (!getRefBinding(St, Sym))
Ted Kremenekc887d132009-04-29 18:50:19 +00002089 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002090
Anna Zaks27b867e2012-03-21 19:45:01 +00002091 StoreManager::FindUniqueBinding FB(Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002092 StateMgr.iterBindings(St, FB);
Anna Zaks7a87e522013-04-10 21:42:06 +00002093
Anna Zaks27d99dd2013-04-10 21:42:02 +00002094 if (FB) {
2095 const MemRegion *R = FB.getRegion();
Anna Zaks8cf91f72013-04-10 22:56:33 +00002096 const VarRegion *VR = R->getBaseRegion()->getAs<VarRegion>();
Anna Zaks27d99dd2013-04-10 21:42:02 +00002097 // Do not show local variables belonging to a function other than
2098 // where the error is reported.
2099 if (!VR || VR->getStackFrame() == LeakContext->getCurrentStackFrame())
Anna Zaks7a87e522013-04-10 21:42:06 +00002100 FirstBinding = R;
Anna Zaks27d99dd2013-04-10 21:42:02 +00002101 }
Mike Stump1eb44332009-09-09 15:08:12 +00002102
Anna Zaks7a87e522013-04-10 21:42:06 +00002103 // AllocationNode is the last node in which the symbol was tracked.
2104 AllocationNode = N;
2105
2106 // AllocationNodeInCurrentContext, is the last node in the current context
2107 // in which the symbol was tracked.
2108 if (NContext == LeakContext)
2109 AllocationNodeInCurrentContext = N;
2110
Anna Zaksee9043b2013-04-10 22:56:30 +00002111 // Find the last init that was called on the given symbol and store the
2112 // init method's location context.
2113 if (!InitMethodContext)
2114 if (Optional<CallEnter> CEP = N->getLocation().getAs<CallEnter>()) {
2115 const Stmt *CE = CEP->getCallExpr();
Anna Zaks3d8f4622013-04-25 00:41:32 +00002116 if (const ObjCMessageExpr *ME = dyn_cast_or_null<ObjCMessageExpr>(CE)) {
Anna Zaksee9043b2013-04-10 22:56:30 +00002117 const Stmt *RecExpr = ME->getInstanceReceiver();
2118 if (RecExpr) {
2119 SVal RecV = St->getSVal(RecExpr, NContext);
2120 if (ME->getMethodFamily() == OMF_init && RecV.getAsSymbol() == Sym)
2121 InitMethodContext = CEP->getCalleeContext();
2122 }
2123 }
Anna Zaks7a87e522013-04-10 21:42:06 +00002124 }
Anna Zakse7e01682012-02-28 22:39:22 +00002125
Mike Stump1eb44332009-09-09 15:08:12 +00002126 N = N->pred_empty() ? NULL : *(N->pred_begin());
Ted Kremenekc887d132009-04-29 18:50:19 +00002127 }
Mike Stump1eb44332009-09-09 15:08:12 +00002128
Anna Zaks7a87e522013-04-10 21:42:06 +00002129 // If we are reporting a leak of the object that was allocated with alloc,
Anna Zaksee9043b2013-04-10 22:56:30 +00002130 // mark its init method as interesting.
Anna Zaks7a87e522013-04-10 21:42:06 +00002131 const LocationContext *InterestingMethodContext = 0;
2132 if (InitMethodContext) {
2133 const ProgramPoint AllocPP = AllocationNode->getLocation();
2134 if (Optional<StmtPoint> SP = AllocPP.getAs<StmtPoint>())
2135 if (const ObjCMessageExpr *ME = SP->getStmtAs<ObjCMessageExpr>())
2136 if (ME->getMethodFamily() == OMF_alloc)
2137 InterestingMethodContext = InitMethodContext;
2138 }
2139
Anna Zakse7e01682012-02-28 22:39:22 +00002140 // If allocation happened in a function different from the leak node context,
2141 // do not report the binding.
Ted Kremenek5a8fc882012-10-12 22:56:40 +00002142 assert(N && "Could not find allocation node");
Anna Zakse7e01682012-02-28 22:39:22 +00002143 if (N->getLocationContext() != LeakContext) {
2144 FirstBinding = 0;
2145 }
2146
Anna Zaks7a87e522013-04-10 21:42:06 +00002147 return AllocationInfo(AllocationNodeInCurrentContext,
2148 FirstBinding,
2149 InterestingMethodContext);
Ted Kremenekc887d132009-04-29 18:50:19 +00002150}
2151
2152PathDiagnosticPiece*
Anna Zaks23f395e2011-08-20 01:27:22 +00002153CFRefReportVisitor::getEndPath(BugReporterContext &BRC,
2154 const ExplodedNode *EndN,
2155 BugReport &BR) {
Ted Kremenek76aadc32012-03-09 01:13:14 +00002156 BR.markInteresting(Sym);
Anna Zaks23f395e2011-08-20 01:27:22 +00002157 return BugReporterVisitor::getDefaultEndPath(BRC, EndN, BR);
Ted Kremenekc887d132009-04-29 18:50:19 +00002158}
2159
2160PathDiagnosticPiece*
Anna Zaks23f395e2011-08-20 01:27:22 +00002161CFRefLeakReportVisitor::getEndPath(BugReporterContext &BRC,
2162 const ExplodedNode *EndN,
2163 BugReport &BR) {
Mike Stump1eb44332009-09-09 15:08:12 +00002164
Ted Kremenek8966bc12009-05-06 21:39:49 +00002165 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenekc887d132009-04-29 18:50:19 +00002166 // assigned to different variables, etc.
Ted Kremenek76aadc32012-03-09 01:13:14 +00002167 BR.markInteresting(Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002168
Ted Kremenekc887d132009-04-29 18:50:19 +00002169 // We are reporting a leak. Walk up the graph to get to the first node where
2170 // the symbol appeared, and also get the first VarDecl that tracked object
2171 // is stored to.
Anna Zaks7a87e522013-04-10 21:42:06 +00002172 AllocationInfo AllocI =
Ted Kremenekf04dced2009-05-08 23:32:51 +00002173 GetAllocationSite(BRC.getStateManager(), EndN, Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002174
Anna Zaks7a87e522013-04-10 21:42:06 +00002175 const MemRegion* FirstBinding = AllocI.R;
2176 BR.markInteresting(AllocI.InterestingMethodContext);
2177
Anna Zaks4fdf97b2011-09-15 18:56:07 +00002178 SourceManager& SM = BRC.getSourceManager();
Mike Stump1eb44332009-09-09 15:08:12 +00002179
Ted Kremenekc887d132009-04-29 18:50:19 +00002180 // Compute an actual location for the leak. Sometimes a leak doesn't
2181 // occur at an actual statement (e.g., transition between blocks; end
2182 // of function) so we need to walk the graph and compute a real location.
Ted Kremenek9c378f72011-08-12 23:37:29 +00002183 const ExplodedNode *LeakN = EndN;
Anna Zaks4fdf97b2011-09-15 18:56:07 +00002184 PathDiagnosticLocation L = PathDiagnosticLocation::createEndOfPath(LeakN, SM);
Mike Stump1eb44332009-09-09 15:08:12 +00002185
Ted Kremenekc887d132009-04-29 18:50:19 +00002186 std::string sbuf;
2187 llvm::raw_string_ostream os(sbuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002188
Ted Kremenekf1365462011-05-26 18:45:44 +00002189 os << "Object leaked: ";
Mike Stump1eb44332009-09-09 15:08:12 +00002190
Ted Kremenekf1365462011-05-26 18:45:44 +00002191 if (FirstBinding) {
2192 os << "object allocated and stored into '"
2193 << FirstBinding->getString() << '\'';
2194 }
2195 else
2196 os << "allocated object";
Mike Stump1eb44332009-09-09 15:08:12 +00002197
Ted Kremenekc887d132009-04-29 18:50:19 +00002198 // Get the retain count.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002199 const RefVal* RV = getRefBinding(EndN->getState(), Sym);
Ted Kremenek5a8fc882012-10-12 22:56:40 +00002200 assert(RV);
Mike Stump1eb44332009-09-09 15:08:12 +00002201
Ted Kremenekc887d132009-04-29 18:50:19 +00002202 if (RV->getKind() == RefVal::ErrorLeakReturned) {
2203 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
Jordy Rose5b5402b2011-07-15 22:17:54 +00002204 // objects. Only "copy", "alloc", "retain" and "new" transfer ownership
Ted Kremenekc887d132009-04-29 18:50:19 +00002205 // to the caller for NS objects.
Ted Kremenekd368d712011-05-25 06:19:45 +00002206 const Decl *D = &EndN->getCodeDecl();
Ted Kremenekec9f36e2012-09-06 23:03:07 +00002207
2208 os << (isa<ObjCMethodDecl>(D) ? " is returned from a method "
2209 : " is returned from a function ");
2210
2211 if (D->getAttr<CFReturnsNotRetainedAttr>())
2212 os << "that is annotated as CF_RETURNS_NOT_RETAINED";
2213 else if (D->getAttr<NSReturnsNotRetainedAttr>())
2214 os << "that is annotated as NS_RETURNS_NOT_RETAINED";
Ted Kremenekd368d712011-05-25 06:19:45 +00002215 else {
Ted Kremenekec9f36e2012-09-06 23:03:07 +00002216 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2217 os << "whose name ('" << MD->getSelector().getAsString()
2218 << "') does not start with 'copy', 'mutableCopy', 'alloc' or 'new'."
2219 " This violates the naming convention rules"
2220 " given in the Memory Management Guide for Cocoa";
2221 }
2222 else {
2223 const FunctionDecl *FD = cast<FunctionDecl>(D);
2224 os << "whose name ('" << *FD
2225 << "') does not contain 'Copy' or 'Create'. This violates the naming"
2226 " convention rules given in the Memory Management Guide for Core"
2227 " Foundation";
2228 }
2229 }
Ted Kremenekc887d132009-04-29 18:50:19 +00002230 }
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002231 else if (RV->getKind() == RefVal::ErrorGCLeakReturned) {
David Blaikiee1300142013-02-21 22:37:44 +00002232 const ObjCMethodDecl &MD = cast<ObjCMethodDecl>(EndN->getCodeDecl());
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002233 os << " and returned from method '" << MD.getSelector().getAsString()
Ted Kremenek82f2be52009-05-10 16:52:15 +00002234 << "' is potentially leaked when using garbage collection. Callers "
2235 "of this method do not expect a returned object with a +1 retain "
2236 "count since they expect the object to be managed by the garbage "
2237 "collector";
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002238 }
Ted Kremenekc887d132009-04-29 18:50:19 +00002239 else
Ted Kremenekabf517c2010-10-15 22:50:23 +00002240 os << " is not referenced later in this execution path and has a retain "
Ted Kremenekf1365462011-05-26 18:45:44 +00002241 "count of +" << RV->getCount();
Mike Stump1eb44332009-09-09 15:08:12 +00002242
Ted Kremenekc887d132009-04-29 18:50:19 +00002243 return new PathDiagnosticEventPiece(L, os.str());
2244}
2245
Jordy Rose20589562011-08-24 22:39:09 +00002246CFRefLeakReport::CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts,
2247 bool GCEnabled, const SummaryLogTy &Log,
2248 ExplodedNode *n, SymbolRef sym,
Ted Kremenek08a838d2013-04-16 21:44:22 +00002249 CheckerContext &Ctx,
2250 bool IncludeAllocationLine)
2251 : CFRefReport(D, LOpts, GCEnabled, Log, n, sym, false) {
Mike Stump1eb44332009-09-09 15:08:12 +00002252
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00002253 // Most bug reports are cached at the location where they occurred.
Ted Kremenekc887d132009-04-29 18:50:19 +00002254 // With leaks, we want to unique them by the location where they were
2255 // allocated, and only report a single path. To do this, we need to find
2256 // the allocation site of a piece of tracked memory, which we do via a
2257 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2258 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2259 // that all ancestor nodes that represent the allocation site have the
2260 // same SourceLocation.
Ted Kremenek9c378f72011-08-12 23:37:29 +00002261 const ExplodedNode *AllocNode = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002262
Anna Zaks6a93bd52011-10-25 19:57:11 +00002263 const SourceManager& SMgr = Ctx.getSourceManager();
Anna Zaks590dd8e2011-09-20 21:38:35 +00002264
Anna Zaks7a87e522013-04-10 21:42:06 +00002265 AllocationInfo AllocI =
Anna Zaks6a93bd52011-10-25 19:57:11 +00002266 GetAllocationSite(Ctx.getStateManager(), getErrorNode(), sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002267
Anna Zaks7a87e522013-04-10 21:42:06 +00002268 AllocNode = AllocI.N;
2269 AllocBinding = AllocI.R;
2270 markInteresting(AllocI.InterestingMethodContext);
2271
Ted Kremenekc887d132009-04-29 18:50:19 +00002272 // Get the SourceLocation for the allocation site.
Jordan Rose852aa0d2012-07-10 22:07:52 +00002273 // FIXME: This will crash the analyzer if an allocation comes from an
2274 // implicit call. (Currently there are no such allocations in Cocoa, though.)
2275 const Stmt *AllocStmt;
Ted Kremenekc887d132009-04-29 18:50:19 +00002276 ProgramPoint P = AllocNode->getLocation();
David Blaikie7a95de62013-02-21 22:23:56 +00002277 if (Optional<CallExitEnd> Exit = P.getAs<CallExitEnd>())
Jordan Rose852aa0d2012-07-10 22:07:52 +00002278 AllocStmt = Exit->getCalleeContext()->getCallSite();
2279 else
David Blaikie7a95de62013-02-21 22:23:56 +00002280 AllocStmt = P.castAs<PostStmt>().getStmt();
Jordan Rose852aa0d2012-07-10 22:07:52 +00002281 assert(AllocStmt && "All allocations must come from explicit calls");
Anna Zakse3a813a2013-04-23 23:57:50 +00002282
2283 PathDiagnosticLocation AllocLocation =
2284 PathDiagnosticLocation::createBegin(AllocStmt, SMgr,
2285 AllocNode->getLocationContext());
2286 Location = AllocLocation;
2287
2288 // Set uniqieing info, which will be used for unique the bug reports. The
2289 // leaks should be uniqued on the allocation site.
2290 UniqueingLocation = AllocLocation;
2291 UniqueingDecl = AllocNode->getLocationContext()->getDecl();
2292
Ted Kremenekc887d132009-04-29 18:50:19 +00002293 // Fill in the description of the bug.
2294 Description.clear();
2295 llvm::raw_string_ostream os(Description);
Ted Kremenekdd924e22009-05-02 19:05:19 +00002296 os << "Potential leak ";
Jordy Rose20589562011-08-24 22:39:09 +00002297 if (GCEnabled)
Ted Kremenekdd924e22009-05-02 19:05:19 +00002298 os << "(when using garbage collection) ";
Anna Zaks212000e2012-02-28 21:49:08 +00002299 os << "of an object";
Mike Stump1eb44332009-09-09 15:08:12 +00002300
Ted Kremenek08a838d2013-04-16 21:44:22 +00002301 if (AllocBinding) {
Anna Zaks212000e2012-02-28 21:49:08 +00002302 os << " stored into '" << AllocBinding->getString() << '\'';
Ted Kremenek08a838d2013-04-16 21:44:22 +00002303 if (IncludeAllocationLine) {
2304 FullSourceLoc SL(AllocStmt->getLocStart(), Ctx.getSourceManager());
2305 os << " (allocated on line " << SL.getSpellingLineNumber() << ")";
2306 }
2307 }
Anna Zaksdc757b02011-08-19 23:21:56 +00002308
Jordy Rose20589562011-08-24 22:39:09 +00002309 addVisitor(new CFRefLeakReportVisitor(sym, GCEnabled, Log));
Ted Kremenekc887d132009-04-29 18:50:19 +00002310}
2311
2312//===----------------------------------------------------------------------===//
2313// Main checker logic.
2314//===----------------------------------------------------------------------===//
2315
Ted Kremenekd593eb92009-11-25 22:17:44 +00002316namespace {
Jordy Rose910c4052011-09-02 06:44:22 +00002317class RetainCountChecker
Jordy Rose9c083b72011-08-24 18:56:32 +00002318 : public Checker< check::Bind,
Jordy Rose38f17d62011-08-23 19:01:07 +00002319 check::DeadSymbols,
Jordy Rose9c083b72011-08-24 18:56:32 +00002320 check::EndAnalysis,
Anna Zaks344c77a2013-01-03 00:25:29 +00002321 check::EndFunction,
Jordy Rose67044292011-08-17 21:27:39 +00002322 check::PostStmt<BlockExpr>,
John McCallf85e1932011-06-15 23:02:42 +00002323 check::PostStmt<CastExpr>,
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002324 check::PostStmt<ObjCArrayLiteral>,
2325 check::PostStmt<ObjCDictionaryLiteral>,
Jordy Rose70fdbc32012-05-12 05:10:43 +00002326 check::PostStmt<ObjCBoxedExpr>,
Jordan Rosefe6a0112012-07-02 19:28:21 +00002327 check::PostCall,
Jordy Rosef53e8c72011-08-23 19:43:16 +00002328 check::PreStmt<ReturnStmt>,
Jordy Rose67044292011-08-17 21:27:39 +00002329 check::RegionChanges,
Jordy Rose76c506f2011-08-21 21:58:18 +00002330 eval::Assume,
2331 eval::Call > {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002332 mutable OwningPtr<CFRefBug> useAfterRelease, releaseNotOwned;
2333 mutable OwningPtr<CFRefBug> deallocGC, deallocNotOwned;
2334 mutable OwningPtr<CFRefBug> overAutorelease, returnNotOwnedForOwned;
2335 mutable OwningPtr<CFRefBug> leakWithinFunction, leakAtReturn;
2336 mutable OwningPtr<CFRefBug> leakWithinFunctionGC, leakAtReturnGC;
Jordy Rose38f17d62011-08-23 19:01:07 +00002337
2338 typedef llvm::DenseMap<SymbolRef, const SimpleProgramPointTag *> SymbolTagMap;
2339
2340 // This map is only used to ensure proper deletion of any allocated tags.
2341 mutable SymbolTagMap DeadSymbolTags;
2342
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002343 mutable OwningPtr<RetainSummaryManager> Summaries;
2344 mutable OwningPtr<RetainSummaryManager> SummariesGC;
Jordy Rose9c083b72011-08-24 18:56:32 +00002345 mutable SummaryLogTy SummaryLog;
2346 mutable bool ShouldResetSummaryLog;
2347
Ted Kremenek08a838d2013-04-16 21:44:22 +00002348 /// Optional setting to indicate if leak reports should include
2349 /// the allocation line.
2350 mutable bool IncludeAllocationLine;
2351
Jordy Rose2f9a66d2011-08-20 21:17:59 +00002352public:
Ted Kremenek08a838d2013-04-16 21:44:22 +00002353 RetainCountChecker(AnalyzerOptions &AO)
2354 : ShouldResetSummaryLog(false),
2355 IncludeAllocationLine(shouldIncludeAllocationSiteInLeakDiagnostics(AO)) {}
Jordy Rose38f17d62011-08-23 19:01:07 +00002356
Jordy Rose910c4052011-09-02 06:44:22 +00002357 virtual ~RetainCountChecker() {
Jordy Rose38f17d62011-08-23 19:01:07 +00002358 DeleteContainerSeconds(DeadSymbolTags);
2359 }
2360
Jordy Rose9c083b72011-08-24 18:56:32 +00002361 void checkEndAnalysis(ExplodedGraph &G, BugReporter &BR,
2362 ExprEngine &Eng) const {
2363 // FIXME: This is a hack to make sure the summary log gets cleared between
2364 // analyses of different code bodies.
2365 //
2366 // Why is this necessary? Because a checker's lifetime is tied to a
2367 // translation unit, but an ExplodedGraph's lifetime is just a code body.
2368 // Once in a blue moon, a new ExplodedNode will have the same address as an
2369 // old one with an associated summary, and the bug report visitor gets very
2370 // confused. (To make things worse, the summary lifetime is currently also
2371 // tied to a code body, so we get a crash instead of incorrect results.)
Jordy Rose1ab51c72011-08-24 09:27:24 +00002372 //
2373 // Why is this a bad solution? Because if the lifetime of the ExplodedGraph
2374 // changes, things will start going wrong again. Really the lifetime of this
2375 // log needs to be tied to either the specific nodes in it or the entire
2376 // ExplodedGraph, not to a specific part of the code being analyzed.
2377 //
Jordy Rose9c083b72011-08-24 18:56:32 +00002378 // (Also, having stateful local data means that the same checker can't be
2379 // used from multiple threads, but a lot of checkers have incorrect
2380 // assumptions about that anyway. So that wasn't a priority at the time of
2381 // this fix.)
Jordy Rose1ab51c72011-08-24 09:27:24 +00002382 //
Jordy Rose9c083b72011-08-24 18:56:32 +00002383 // This happens at the end of analysis, but bug reports are emitted /after/
2384 // this point. So we can't just clear the summary log now. Instead, we mark
2385 // that the next time we access the summary log, it should be cleared.
2386
2387 // If we never reset the summary log during /this/ code body analysis,
2388 // there were no new summaries. There might still have been summaries from
2389 // the /last/ analysis, so clear them out to make sure the bug report
2390 // visitors don't get confused.
2391 if (ShouldResetSummaryLog)
2392 SummaryLog.clear();
2393
2394 ShouldResetSummaryLog = !SummaryLog.empty();
Jordy Rose1ab51c72011-08-24 09:27:24 +00002395 }
2396
Jordy Rose17a38e22011-09-02 05:55:19 +00002397 CFRefBug *getLeakWithinFunctionBug(const LangOptions &LOpts,
2398 bool GCEnabled) const {
2399 if (GCEnabled) {
Jordy Rosedb92bb62011-08-25 01:14:38 +00002400 if (!leakWithinFunctionGC)
Benjamin Kramerfacde172012-06-06 17:32:50 +00002401 leakWithinFunctionGC.reset(new Leak("Leak of object when using "
2402 "garbage collection"));
Jordy Rose17a38e22011-09-02 05:55:19 +00002403 return leakWithinFunctionGC.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002404 } else {
2405 if (!leakWithinFunction) {
Douglas Gregore289d812011-09-13 17:21:33 +00002406 if (LOpts.getGC() == LangOptions::HybridGC) {
Benjamin Kramerfacde172012-06-06 17:32:50 +00002407 leakWithinFunction.reset(new Leak("Leak of object when not using "
2408 "garbage collection (GC) in "
2409 "dual GC/non-GC code"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002410 } else {
Benjamin Kramerfacde172012-06-06 17:32:50 +00002411 leakWithinFunction.reset(new Leak("Leak"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002412 }
2413 }
Jordy Rose17a38e22011-09-02 05:55:19 +00002414 return leakWithinFunction.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002415 }
2416 }
2417
Jordy Rose17a38e22011-09-02 05:55:19 +00002418 CFRefBug *getLeakAtReturnBug(const LangOptions &LOpts, bool GCEnabled) const {
2419 if (GCEnabled) {
Jordy Rosedb92bb62011-08-25 01:14:38 +00002420 if (!leakAtReturnGC)
Benjamin Kramerfacde172012-06-06 17:32:50 +00002421 leakAtReturnGC.reset(new Leak("Leak of returned object when using "
2422 "garbage collection"));
Jordy Rose17a38e22011-09-02 05:55:19 +00002423 return leakAtReturnGC.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002424 } else {
2425 if (!leakAtReturn) {
Douglas Gregore289d812011-09-13 17:21:33 +00002426 if (LOpts.getGC() == LangOptions::HybridGC) {
Benjamin Kramerfacde172012-06-06 17:32:50 +00002427 leakAtReturn.reset(new Leak("Leak of returned object when not using "
2428 "garbage collection (GC) in dual "
2429 "GC/non-GC code"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002430 } else {
Benjamin Kramerfacde172012-06-06 17:32:50 +00002431 leakAtReturn.reset(new Leak("Leak of returned object"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002432 }
2433 }
Jordy Rose17a38e22011-09-02 05:55:19 +00002434 return leakAtReturn.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002435 }
2436 }
2437
Jordy Rose17a38e22011-09-02 05:55:19 +00002438 RetainSummaryManager &getSummaryManager(ASTContext &Ctx,
2439 bool GCEnabled) const {
2440 // FIXME: We don't support ARC being turned on and off during one analysis.
2441 // (nor, for that matter, do we support changing ASTContexts)
David Blaikie4e4d0842012-03-11 07:00:24 +00002442 bool ARCEnabled = (bool)Ctx.getLangOpts().ObjCAutoRefCount;
Jordy Rose17a38e22011-09-02 05:55:19 +00002443 if (GCEnabled) {
2444 if (!SummariesGC)
Jordy Roseb6cfc092011-08-25 00:10:37 +00002445 SummariesGC.reset(new RetainSummaryManager(Ctx, true, ARCEnabled));
Jordy Rose17a38e22011-09-02 05:55:19 +00002446 else
2447 assert(SummariesGC->isARCEnabled() == ARCEnabled);
Jordy Roseb6cfc092011-08-25 00:10:37 +00002448 return *SummariesGC;
2449 } else {
Jordy Rose17a38e22011-09-02 05:55:19 +00002450 if (!Summaries)
Jordy Roseb6cfc092011-08-25 00:10:37 +00002451 Summaries.reset(new RetainSummaryManager(Ctx, false, ARCEnabled));
Jordy Rose17a38e22011-09-02 05:55:19 +00002452 else
2453 assert(Summaries->isARCEnabled() == ARCEnabled);
Jordy Roseb6cfc092011-08-25 00:10:37 +00002454 return *Summaries;
2455 }
2456 }
2457
Jordy Rose17a38e22011-09-02 05:55:19 +00002458 RetainSummaryManager &getSummaryManager(CheckerContext &C) const {
2459 return getSummaryManager(C.getASTContext(), C.isObjCGCEnabled());
2460 }
2461
Ted Kremenek8bef8232012-01-26 21:29:00 +00002462 void printState(raw_ostream &Out, ProgramStateRef State,
Jordy Rosedbd658e2011-08-28 19:11:56 +00002463 const char *NL, const char *Sep) const;
2464
Anna Zaks390909c2011-10-06 00:43:15 +00002465 void checkBind(SVal loc, SVal val, const Stmt *S, CheckerContext &C) const;
Jordy Roseab027fd2011-08-20 21:16:58 +00002466 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
2467 void checkPostStmt(const CastExpr *CE, CheckerContext &C) const;
John McCallf85e1932011-06-15 23:02:42 +00002468
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002469 void checkPostStmt(const ObjCArrayLiteral *AL, CheckerContext &C) const;
2470 void checkPostStmt(const ObjCDictionaryLiteral *DL, CheckerContext &C) const;
Jordy Rose70fdbc32012-05-12 05:10:43 +00002471 void checkPostStmt(const ObjCBoxedExpr *BE, CheckerContext &C) const;
2472
Jordan Rosefe6a0112012-07-02 19:28:21 +00002473 void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002474
Jordan Rose4531b7d2012-07-02 19:27:43 +00002475 void checkSummary(const RetainSummary &Summ, const CallEvent &Call,
Jordy Rosee38dd952011-08-28 05:16:28 +00002476 CheckerContext &C) const;
Jordy Rose294396b2011-08-22 23:48:23 +00002477
Anna Zaks554067f2012-08-29 23:23:43 +00002478 void processSummaryOfInlined(const RetainSummary &Summ,
2479 const CallEvent &Call,
2480 CheckerContext &C) const;
2481
Jordy Rose76c506f2011-08-21 21:58:18 +00002482 bool evalCall(const CallExpr *CE, CheckerContext &C) const;
2483
Ted Kremenek8bef8232012-01-26 21:29:00 +00002484 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Jordy Roseab027fd2011-08-20 21:16:58 +00002485 bool Assumption) const;
Jordy Rose67044292011-08-17 21:27:39 +00002486
Ted Kremenek8bef8232012-01-26 21:29:00 +00002487 ProgramStateRef
2488 checkRegionChanges(ProgramStateRef state,
Anna Zaksbf53dfa2012-12-20 00:38:25 +00002489 const InvalidatedSymbols *invalidated,
Jordy Rose537716a2011-08-27 22:51:26 +00002490 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00002491 ArrayRef<const MemRegion *> Regions,
Jordan Rose740d4902012-07-02 19:27:35 +00002492 const CallEvent *Call) const;
Jordy Roseab027fd2011-08-20 21:16:58 +00002493
Ted Kremenek8bef8232012-01-26 21:29:00 +00002494 bool wantsRegionChangeUpdate(ProgramStateRef state) const {
Jordy Rose2f9a66d2011-08-20 21:17:59 +00002495 return true;
Jordy Roseab027fd2011-08-20 21:16:58 +00002496 }
Jordy Rose294396b2011-08-22 23:48:23 +00002497
Jordy Rosef53e8c72011-08-23 19:43:16 +00002498 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
2499 void checkReturnWithRetEffect(const ReturnStmt *S, CheckerContext &C,
2500 ExplodedNode *Pred, RetEffect RE, RefVal X,
Ted Kremenek8bef8232012-01-26 21:29:00 +00002501 SymbolRef Sym, ProgramStateRef state) const;
Jordy Rosef53e8c72011-08-23 19:43:16 +00002502
Jordy Rose38f17d62011-08-23 19:01:07 +00002503 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Anna Zaks344c77a2013-01-03 00:25:29 +00002504 void checkEndFunction(CheckerContext &C) const;
Jordy Rose38f17d62011-08-23 19:01:07 +00002505
Ted Kremenek8bef8232012-01-26 21:29:00 +00002506 ProgramStateRef updateSymbol(ProgramStateRef state, SymbolRef sym,
Anna Zaks554067f2012-08-29 23:23:43 +00002507 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
2508 CheckerContext &C) const;
Jordy Rosee0a5d322011-08-23 20:27:16 +00002509
Ted Kremenek8bef8232012-01-26 21:29:00 +00002510 void processNonLeakError(ProgramStateRef St, SourceRange ErrorRange,
Jordy Rose294396b2011-08-22 23:48:23 +00002511 RefVal::Kind ErrorKind, SymbolRef Sym,
2512 CheckerContext &C) const;
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002513
2514 void processObjCLiterals(CheckerContext &C, const Expr *Ex) const;
Jordy Rose294396b2011-08-22 23:48:23 +00002515
Jordy Rose38f17d62011-08-23 19:01:07 +00002516 const ProgramPointTag *getDeadSymbolTag(SymbolRef sym) const;
2517
Ted Kremenek8bef8232012-01-26 21:29:00 +00002518 ProgramStateRef handleSymbolDeath(ProgramStateRef state,
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002519 SymbolRef sid, RefVal V,
2520 SmallVectorImpl<SymbolRef> &Leaked) const;
Jordy Rose38f17d62011-08-23 19:01:07 +00002521
Jordan Rose4ee1c552012-12-06 18:58:18 +00002522 ProgramStateRef
Jordan Rose2bce86c2012-08-18 00:30:16 +00002523 handleAutoreleaseCounts(ProgramStateRef state, ExplodedNode *Pred,
2524 const ProgramPointTag *Tag, CheckerContext &Ctx,
2525 SymbolRef Sym, RefVal V) const;
Jordy Rose8d228632011-08-23 20:07:14 +00002526
Ted Kremenek8bef8232012-01-26 21:29:00 +00002527 ExplodedNode *processLeaks(ProgramStateRef state,
Jordy Rose38f17d62011-08-23 19:01:07 +00002528 SmallVectorImpl<SymbolRef> &Leaked,
Anna Zaks6a93bd52011-10-25 19:57:11 +00002529 CheckerContext &Ctx,
Jordy Rose38f17d62011-08-23 19:01:07 +00002530 ExplodedNode *Pred = 0) const;
Ted Kremenekd593eb92009-11-25 22:17:44 +00002531};
2532} // end anonymous namespace
2533
Jordy Rose67044292011-08-17 21:27:39 +00002534namespace {
2535class StopTrackingCallback : public SymbolVisitor {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002536 ProgramStateRef state;
Jordy Rose67044292011-08-17 21:27:39 +00002537public:
Ted Kremenek8bef8232012-01-26 21:29:00 +00002538 StopTrackingCallback(ProgramStateRef st) : state(st) {}
2539 ProgramStateRef getState() const { return state; }
Jordy Rose67044292011-08-17 21:27:39 +00002540
2541 bool VisitSymbol(SymbolRef sym) {
2542 state = state->remove<RefBindings>(sym);
2543 return true;
2544 }
2545};
2546} // end anonymous namespace
2547
Jordy Rose910c4052011-09-02 06:44:22 +00002548//===----------------------------------------------------------------------===//
2549// Handle statements that may have an effect on refcounts.
2550//===----------------------------------------------------------------------===//
Jordy Rose67044292011-08-17 21:27:39 +00002551
Jordy Rose910c4052011-09-02 06:44:22 +00002552void RetainCountChecker::checkPostStmt(const BlockExpr *BE,
2553 CheckerContext &C) const {
Jordy Rose67044292011-08-17 21:27:39 +00002554
Jordy Rose910c4052011-09-02 06:44:22 +00002555 // Scan the BlockDecRefExprs for any object the retain count checker
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002556 // may be tracking.
John McCall469a1eb2011-02-02 13:00:07 +00002557 if (!BE->getBlockDecl()->hasCaptures())
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002558 return;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002559
Ted Kremenek8bef8232012-01-26 21:29:00 +00002560 ProgramStateRef state = C.getState();
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002561 const BlockDataRegion *R =
Ted Kremenek5eca4822012-01-06 22:09:28 +00002562 cast<BlockDataRegion>(state->getSVal(BE,
2563 C.getLocationContext()).getAsRegion());
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002564
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002565 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
2566 E = R->referenced_vars_end();
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002567
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002568 if (I == E)
2569 return;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002570
Ted Kremenek67d12872009-12-07 22:05:27 +00002571 // FIXME: For now we invalidate the tracking of all symbols passed to blocks
2572 // via captured variables, even though captured variables result in a copy
2573 // and in implicit increment/decrement of a retain count.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002574 SmallVector<const MemRegion*, 10> Regions;
Anna Zaks39ac1872011-10-26 21:06:44 +00002575 const LocationContext *LC = C.getLocationContext();
Ted Kremenekc8413fd2010-12-02 07:49:45 +00002576 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002577
Ted Kremenek67d12872009-12-07 22:05:27 +00002578 for ( ; I != E; ++I) {
Ted Kremeneke3ce2c12012-12-06 07:17:20 +00002579 const VarRegion *VR = I.getCapturedRegion();
Ted Kremenek67d12872009-12-07 22:05:27 +00002580 if (VR->getSuperRegion() == R) {
2581 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2582 }
2583 Regions.push_back(VR);
2584 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002585
Ted Kremenek67d12872009-12-07 22:05:27 +00002586 state =
2587 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
2588 Regions.data() + Regions.size()).getState();
Anna Zaks0bd6b112011-10-26 21:06:34 +00002589 C.addTransition(state);
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002590}
2591
Jordy Rose910c4052011-09-02 06:44:22 +00002592void RetainCountChecker::checkPostStmt(const CastExpr *CE,
2593 CheckerContext &C) const {
John McCallf85e1932011-06-15 23:02:42 +00002594 const ObjCBridgedCastExpr *BE = dyn_cast<ObjCBridgedCastExpr>(CE);
2595 if (!BE)
2596 return;
2597
John McCall71c482c2011-06-17 06:50:50 +00002598 ArgEffect AE = IncRef;
John McCallf85e1932011-06-15 23:02:42 +00002599
2600 switch (BE->getBridgeKind()) {
2601 case clang::OBC_Bridge:
2602 // Do nothing.
2603 return;
2604 case clang::OBC_BridgeRetained:
2605 AE = IncRef;
2606 break;
2607 case clang::OBC_BridgeTransfer:
2608 AE = DecRefBridgedTransfered;
2609 break;
2610 }
2611
Ted Kremenek8bef8232012-01-26 21:29:00 +00002612 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00002613 SymbolRef Sym = state->getSVal(CE, C.getLocationContext()).getAsLocSymbol();
John McCallf85e1932011-06-15 23:02:42 +00002614 if (!Sym)
2615 return;
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002616 const RefVal* T = getRefBinding(state, Sym);
John McCallf85e1932011-06-15 23:02:42 +00002617 if (!T)
2618 return;
2619
John McCallf85e1932011-06-15 23:02:42 +00002620 RefVal::Kind hasErr = (RefVal::Kind) 0;
Jordy Rose17a38e22011-09-02 05:55:19 +00002621 state = updateSymbol(state, Sym, *T, AE, hasErr, C);
John McCallf85e1932011-06-15 23:02:42 +00002622
2623 if (hasErr) {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002624 // FIXME: If we get an error during a bridge cast, should we report it?
2625 // Should we assert that there is no error?
John McCallf85e1932011-06-15 23:02:42 +00002626 return;
2627 }
2628
Anna Zaks0bd6b112011-10-26 21:06:34 +00002629 C.addTransition(state);
John McCallf85e1932011-06-15 23:02:42 +00002630}
2631
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002632void RetainCountChecker::processObjCLiterals(CheckerContext &C,
2633 const Expr *Ex) const {
2634 ProgramStateRef state = C.getState();
2635 const ExplodedNode *pred = C.getPredecessor();
2636 for (Stmt::const_child_iterator it = Ex->child_begin(), et = Ex->child_end() ;
2637 it != et ; ++it) {
2638 const Stmt *child = *it;
2639 SVal V = state->getSVal(child, pred->getLocationContext());
2640 if (SymbolRef sym = V.getAsSymbol())
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002641 if (const RefVal* T = getRefBinding(state, sym)) {
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002642 RefVal::Kind hasErr = (RefVal::Kind) 0;
2643 state = updateSymbol(state, sym, *T, MayEscape, hasErr, C);
2644 if (hasErr) {
2645 processNonLeakError(state, child->getSourceRange(), hasErr, sym, C);
2646 return;
2647 }
2648 }
2649 }
2650
2651 // Return the object as autoreleased.
2652 // RetEffect RE = RetEffect::MakeNotOwned(RetEffect::ObjC);
2653 if (SymbolRef sym =
2654 state->getSVal(Ex, pred->getLocationContext()).getAsSymbol()) {
2655 QualType ResultTy = Ex->getType();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002656 state = setRefBinding(state, sym,
2657 RefVal::makeNotOwned(RetEffect::ObjC, ResultTy));
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002658 }
2659
2660 C.addTransition(state);
2661}
2662
2663void RetainCountChecker::checkPostStmt(const ObjCArrayLiteral *AL,
2664 CheckerContext &C) const {
2665 // Apply the 'MayEscape' to all values.
2666 processObjCLiterals(C, AL);
2667}
2668
2669void RetainCountChecker::checkPostStmt(const ObjCDictionaryLiteral *DL,
2670 CheckerContext &C) const {
2671 // Apply the 'MayEscape' to all keys and values.
2672 processObjCLiterals(C, DL);
2673}
2674
Jordy Rose70fdbc32012-05-12 05:10:43 +00002675void RetainCountChecker::checkPostStmt(const ObjCBoxedExpr *Ex,
2676 CheckerContext &C) const {
2677 const ExplodedNode *Pred = C.getPredecessor();
2678 const LocationContext *LCtx = Pred->getLocationContext();
2679 ProgramStateRef State = Pred->getState();
2680
2681 if (SymbolRef Sym = State->getSVal(Ex, LCtx).getAsSymbol()) {
2682 QualType ResultTy = Ex->getType();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002683 State = setRefBinding(State, Sym,
2684 RefVal::makeNotOwned(RetEffect::ObjC, ResultTy));
Jordy Rose70fdbc32012-05-12 05:10:43 +00002685 }
2686
2687 C.addTransition(State);
2688}
2689
Jordan Rosefe6a0112012-07-02 19:28:21 +00002690void RetainCountChecker::checkPostCall(const CallEvent &Call,
2691 CheckerContext &C) const {
Jordan Rosefe6a0112012-07-02 19:28:21 +00002692 RetainSummaryManager &Summaries = getSummaryManager(C);
2693 const RetainSummary *Summ = Summaries.getSummary(Call, C.getState());
Anna Zaks554067f2012-08-29 23:23:43 +00002694
2695 if (C.wasInlined) {
2696 processSummaryOfInlined(*Summ, Call, C);
2697 return;
2698 }
Jordan Rosefe6a0112012-07-02 19:28:21 +00002699 checkSummary(*Summ, Call, C);
Jordy Rose294396b2011-08-22 23:48:23 +00002700}
2701
Jordy Rose910c4052011-09-02 06:44:22 +00002702/// GetReturnType - Used to get the return type of a message expression or
2703/// function call with the intention of affixing that type to a tracked symbol.
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +00002704/// While the return type can be queried directly from RetEx, when
Jordy Rose910c4052011-09-02 06:44:22 +00002705/// invoking class methods we augment to the return type to be that of
2706/// a pointer to the class (as opposed it just being id).
2707// FIXME: We may be able to do this with related result types instead.
2708// This function is probably overestimating.
2709static QualType GetReturnType(const Expr *RetE, ASTContext &Ctx) {
2710 QualType RetTy = RetE->getType();
2711 // If RetE is not a message expression just return its type.
2712 // If RetE is a message expression, return its types if it is something
2713 /// more specific than id.
2714 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RetE))
2715 if (const ObjCObjectPointerType *PT = RetTy->getAs<ObjCObjectPointerType>())
2716 if (PT->isObjCQualifiedIdType() || PT->isObjCIdType() ||
2717 PT->isObjCClassType()) {
2718 // At this point we know the return type of the message expression is
2719 // id, id<...>, or Class. If we have an ObjCInterfaceDecl, we know this
2720 // is a call to a class method whose type we can resolve. In such
2721 // cases, promote the return type to XXX* (where XXX is the class).
2722 const ObjCInterfaceDecl *D = ME->getReceiverInterface();
2723 return !D ? RetTy :
2724 Ctx.getObjCObjectPointerType(Ctx.getObjCInterfaceType(D));
2725 }
2726
2727 return RetTy;
2728}
2729
Anna Zaks554067f2012-08-29 23:23:43 +00002730// We don't always get the exact modeling of the function with regards to the
2731// retain count checker even when the function is inlined. For example, we need
2732// to stop tracking the symbols which were marked with StopTrackingHard.
2733void RetainCountChecker::processSummaryOfInlined(const RetainSummary &Summ,
2734 const CallEvent &CallOrMsg,
2735 CheckerContext &C) const {
2736 ProgramStateRef state = C.getState();
2737
2738 // Evaluate the effect of the arguments.
2739 for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
2740 if (Summ.getArg(idx) == StopTrackingHard) {
2741 SVal V = CallOrMsg.getArgSVal(idx);
2742 if (SymbolRef Sym = V.getAsLocSymbol()) {
2743 state = removeRefBinding(state, Sym);
2744 }
2745 }
2746 }
2747
2748 // Evaluate the effect on the message receiver.
2749 const ObjCMethodCall *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg);
2750 if (MsgInvocation) {
2751 if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
2752 if (Summ.getReceiverEffect() == StopTrackingHard) {
2753 state = removeRefBinding(state, Sym);
2754 }
2755 }
2756 }
2757
2758 // Consult the summary for the return value.
2759 RetEffect RE = Summ.getRetEffect();
2760 if (RE.getKind() == RetEffect::NoRetHard) {
Jordan Rose2f3017f2012-11-02 23:49:29 +00002761 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
Anna Zaks554067f2012-08-29 23:23:43 +00002762 if (Sym)
2763 state = removeRefBinding(state, Sym);
2764 }
2765
2766 C.addTransition(state);
2767}
2768
Jordy Rose910c4052011-09-02 06:44:22 +00002769void RetainCountChecker::checkSummary(const RetainSummary &Summ,
Jordan Rose4531b7d2012-07-02 19:27:43 +00002770 const CallEvent &CallOrMsg,
Jordy Rose910c4052011-09-02 06:44:22 +00002771 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002772 ProgramStateRef state = C.getState();
Jordy Rose294396b2011-08-22 23:48:23 +00002773
2774 // Evaluate the effect of the arguments.
2775 RefVal::Kind hasErr = (RefVal::Kind) 0;
2776 SourceRange ErrorRange;
2777 SymbolRef ErrorSym = 0;
2778
2779 for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
Jordy Rose537716a2011-08-27 22:51:26 +00002780 SVal V = CallOrMsg.getArgSVal(idx);
Jordy Rose294396b2011-08-22 23:48:23 +00002781
2782 if (SymbolRef Sym = V.getAsLocSymbol()) {
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002783 if (const RefVal *T = getRefBinding(state, Sym)) {
Jordy Rose17a38e22011-09-02 05:55:19 +00002784 state = updateSymbol(state, Sym, *T, Summ.getArg(idx), hasErr, C);
Jordy Rose294396b2011-08-22 23:48:23 +00002785 if (hasErr) {
2786 ErrorRange = CallOrMsg.getArgSourceRange(idx);
2787 ErrorSym = Sym;
2788 break;
2789 }
2790 }
2791 }
2792 }
2793
2794 // Evaluate the effect on the message receiver.
2795 bool ReceiverIsTracked = false;
Jordan Rose4531b7d2012-07-02 19:27:43 +00002796 if (!hasErr) {
Jordan Rosecde8cdb2012-07-02 19:27:56 +00002797 const ObjCMethodCall *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg);
Jordan Rose4531b7d2012-07-02 19:27:43 +00002798 if (MsgInvocation) {
2799 if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002800 if (const RefVal *T = getRefBinding(state, Sym)) {
Jordan Rose4531b7d2012-07-02 19:27:43 +00002801 ReceiverIsTracked = true;
2802 state = updateSymbol(state, Sym, *T, Summ.getReceiverEffect(),
Anna Zaks554067f2012-08-29 23:23:43 +00002803 hasErr, C);
Jordan Rose4531b7d2012-07-02 19:27:43 +00002804 if (hasErr) {
Jordan Rose8919e682012-07-18 21:59:51 +00002805 ErrorRange = MsgInvocation->getOriginExpr()->getReceiverRange();
Jordan Rose4531b7d2012-07-02 19:27:43 +00002806 ErrorSym = Sym;
2807 }
Jordy Rose294396b2011-08-22 23:48:23 +00002808 }
2809 }
2810 }
2811 }
2812
2813 // Process any errors.
2814 if (hasErr) {
2815 processNonLeakError(state, ErrorRange, hasErr, ErrorSym, C);
2816 return;
2817 }
2818
2819 // Consult the summary for the return value.
2820 RetEffect RE = Summ.getRetEffect();
2821
2822 if (RE.getKind() == RetEffect::OwnedWhenTrackedReceiver) {
Jordy Roseb6cfc092011-08-25 00:10:37 +00002823 if (ReceiverIsTracked)
Jordy Rose17a38e22011-09-02 05:55:19 +00002824 RE = getSummaryManager(C).getObjAllocRetEffect();
Jordy Roseb6cfc092011-08-25 00:10:37 +00002825 else
Jordy Rose294396b2011-08-22 23:48:23 +00002826 RE = RetEffect::MakeNoRet();
2827 }
2828
2829 switch (RE.getKind()) {
2830 default:
David Blaikie7530c032012-01-17 06:56:22 +00002831 llvm_unreachable("Unhandled RetEffect.");
Jordy Rose294396b2011-08-22 23:48:23 +00002832
2833 case RetEffect::NoRet:
Anna Zaks554067f2012-08-29 23:23:43 +00002834 case RetEffect::NoRetHard:
Jordy Rose294396b2011-08-22 23:48:23 +00002835 // No work necessary.
2836 break;
2837
2838 case RetEffect::OwnedAllocatedSymbol:
2839 case RetEffect::OwnedSymbol: {
Jordan Rose2f3017f2012-11-02 23:49:29 +00002840 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
Jordy Rose294396b2011-08-22 23:48:23 +00002841 if (!Sym)
2842 break;
2843
Jordan Rose4531b7d2012-07-02 19:27:43 +00002844 // Use the result type from the CallEvent as it automatically adjusts
Jordy Rose294396b2011-08-22 23:48:23 +00002845 // for methods/functions that return references.
Jordan Rose4531b7d2012-07-02 19:27:43 +00002846 QualType ResultTy = CallOrMsg.getResultType();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002847 state = setRefBinding(state, Sym, RefVal::makeOwned(RE.getObjKind(),
2848 ResultTy));
Jordy Rose294396b2011-08-22 23:48:23 +00002849
2850 // FIXME: Add a flag to the checker where allocations are assumed to
Anna Zaksc6ba23f2012-08-14 15:39:13 +00002851 // *not* fail.
Jordy Rose294396b2011-08-22 23:48:23 +00002852 break;
2853 }
2854
2855 case RetEffect::GCNotOwnedSymbol:
2856 case RetEffect::ARCNotOwnedSymbol:
2857 case RetEffect::NotOwnedSymbol: {
2858 const Expr *Ex = CallOrMsg.getOriginExpr();
Jordan Rose2f3017f2012-11-02 23:49:29 +00002859 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
Jordy Rose294396b2011-08-22 23:48:23 +00002860 if (!Sym)
2861 break;
Ted Kremenek74616822012-10-12 22:56:45 +00002862 assert(Ex);
Jordy Rose294396b2011-08-22 23:48:23 +00002863 // Use GetReturnType in order to give [NSFoo alloc] the type NSFoo *.
2864 QualType ResultTy = GetReturnType(Ex, C.getASTContext());
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002865 state = setRefBinding(state, Sym, RefVal::makeNotOwned(RE.getObjKind(),
2866 ResultTy));
Jordy Rose294396b2011-08-22 23:48:23 +00002867 break;
2868 }
2869 }
2870
2871 // This check is actually necessary; otherwise the statement builder thinks
2872 // we've hit a previously-found path.
2873 // Normally addTransition takes care of this, but we want the node pointer.
2874 ExplodedNode *NewNode;
2875 if (state == C.getState()) {
2876 NewNode = C.getPredecessor();
2877 } else {
Anna Zaks0bd6b112011-10-26 21:06:34 +00002878 NewNode = C.addTransition(state);
Jordy Rose294396b2011-08-22 23:48:23 +00002879 }
2880
Jordy Rose9c083b72011-08-24 18:56:32 +00002881 // Annotate the node with summary we used.
2882 if (NewNode) {
2883 // FIXME: This is ugly. See checkEndAnalysis for why it's necessary.
2884 if (ShouldResetSummaryLog) {
2885 SummaryLog.clear();
2886 ShouldResetSummaryLog = false;
2887 }
Jordy Roseec9ef852011-08-23 20:55:48 +00002888 SummaryLog[NewNode] = &Summ;
Jordy Rose9c083b72011-08-24 18:56:32 +00002889 }
Jordy Rose294396b2011-08-22 23:48:23 +00002890}
2891
Jordy Rosee0a5d322011-08-23 20:27:16 +00002892
Ted Kremenek8bef8232012-01-26 21:29:00 +00002893ProgramStateRef
2894RetainCountChecker::updateSymbol(ProgramStateRef state, SymbolRef sym,
Jordy Rose910c4052011-09-02 06:44:22 +00002895 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
2896 CheckerContext &C) const {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002897 // In GC mode [... release] and [... retain] do nothing.
Jordy Rose910c4052011-09-02 06:44:22 +00002898 // In ARC mode they shouldn't exist at all, but we just ignore them.
Jordy Rose17a38e22011-09-02 05:55:19 +00002899 bool IgnoreRetainMsg = C.isObjCGCEnabled();
2900 if (!IgnoreRetainMsg)
David Blaikie4e4d0842012-03-11 07:00:24 +00002901 IgnoreRetainMsg = (bool)C.getASTContext().getLangOpts().ObjCAutoRefCount;
Jordy Rose17a38e22011-09-02 05:55:19 +00002902
Jordy Rosee0a5d322011-08-23 20:27:16 +00002903 switch (E) {
Jordan Rose4531b7d2012-07-02 19:27:43 +00002904 default:
2905 break;
2906 case IncRefMsg:
2907 E = IgnoreRetainMsg ? DoNothing : IncRef;
2908 break;
2909 case DecRefMsg:
2910 E = IgnoreRetainMsg ? DoNothing : DecRef;
2911 break;
Anna Zaks554067f2012-08-29 23:23:43 +00002912 case DecRefMsgAndStopTrackingHard:
2913 E = IgnoreRetainMsg ? StopTracking : DecRefAndStopTrackingHard;
Jordan Rose4531b7d2012-07-02 19:27:43 +00002914 break;
2915 case MakeCollectable:
2916 E = C.isObjCGCEnabled() ? DecRef : DoNothing;
2917 break;
Jordy Rosee0a5d322011-08-23 20:27:16 +00002918 }
2919
2920 // Handle all use-after-releases.
Jordy Rose17a38e22011-09-02 05:55:19 +00002921 if (!C.isObjCGCEnabled() && V.getKind() == RefVal::Released) {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002922 V = V ^ RefVal::ErrorUseAfterRelease;
2923 hasErr = V.getKind();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002924 return setRefBinding(state, sym, V);
Jordy Rosee0a5d322011-08-23 20:27:16 +00002925 }
2926
2927 switch (E) {
2928 case DecRefMsg:
2929 case IncRefMsg:
2930 case MakeCollectable:
Anna Zaks554067f2012-08-29 23:23:43 +00002931 case DecRefMsgAndStopTrackingHard:
Jordy Rosee0a5d322011-08-23 20:27:16 +00002932 llvm_unreachable("DecRefMsg/IncRefMsg/MakeCollectable already converted");
Jordy Rosee0a5d322011-08-23 20:27:16 +00002933
2934 case Dealloc:
2935 // Any use of -dealloc in GC is *bad*.
Jordy Rose17a38e22011-09-02 05:55:19 +00002936 if (C.isObjCGCEnabled()) {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002937 V = V ^ RefVal::ErrorDeallocGC;
2938 hasErr = V.getKind();
2939 break;
2940 }
2941
2942 switch (V.getKind()) {
2943 default:
2944 llvm_unreachable("Invalid RefVal state for an explicit dealloc.");
Jordy Rosee0a5d322011-08-23 20:27:16 +00002945 case RefVal::Owned:
2946 // The object immediately transitions to the released state.
2947 V = V ^ RefVal::Released;
2948 V.clearCounts();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002949 return setRefBinding(state, sym, V);
Jordy Rosee0a5d322011-08-23 20:27:16 +00002950 case RefVal::NotOwned:
2951 V = V ^ RefVal::ErrorDeallocNotOwned;
2952 hasErr = V.getKind();
2953 break;
2954 }
2955 break;
2956
Jordy Rosee0a5d322011-08-23 20:27:16 +00002957 case MayEscape:
2958 if (V.getKind() == RefVal::Owned) {
2959 V = V ^ RefVal::NotOwned;
2960 break;
2961 }
2962
2963 // Fall-through.
2964
Jordy Rosee0a5d322011-08-23 20:27:16 +00002965 case DoNothing:
2966 return state;
2967
2968 case Autorelease:
Jordy Rose17a38e22011-09-02 05:55:19 +00002969 if (C.isObjCGCEnabled())
Jordy Rosee0a5d322011-08-23 20:27:16 +00002970 return state;
Jordy Rosee0a5d322011-08-23 20:27:16 +00002971 // Update the autorelease counts.
Jordy Rosee0a5d322011-08-23 20:27:16 +00002972 V = V.autorelease();
2973 break;
2974
2975 case StopTracking:
Anna Zaks554067f2012-08-29 23:23:43 +00002976 case StopTrackingHard:
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002977 return removeRefBinding(state, sym);
Jordy Rosee0a5d322011-08-23 20:27:16 +00002978
2979 case IncRef:
2980 switch (V.getKind()) {
2981 default:
2982 llvm_unreachable("Invalid RefVal state for a retain.");
Jordy Rosee0a5d322011-08-23 20:27:16 +00002983 case RefVal::Owned:
2984 case RefVal::NotOwned:
2985 V = V + 1;
2986 break;
2987 case RefVal::Released:
2988 // Non-GC cases are handled above.
Jordy Rose17a38e22011-09-02 05:55:19 +00002989 assert(C.isObjCGCEnabled());
Jordy Rosee0a5d322011-08-23 20:27:16 +00002990 V = (V ^ RefVal::Owned) + 1;
2991 break;
2992 }
2993 break;
2994
Jordy Rosee0a5d322011-08-23 20:27:16 +00002995 case DecRef:
2996 case DecRefBridgedTransfered:
Anna Zaks554067f2012-08-29 23:23:43 +00002997 case DecRefAndStopTrackingHard:
Jordy Rosee0a5d322011-08-23 20:27:16 +00002998 switch (V.getKind()) {
2999 default:
3000 // case 'RefVal::Released' handled above.
3001 llvm_unreachable("Invalid RefVal state for a release.");
Jordy Rosee0a5d322011-08-23 20:27:16 +00003002
3003 case RefVal::Owned:
3004 assert(V.getCount() > 0);
3005 if (V.getCount() == 1)
3006 V = V ^ (E == DecRefBridgedTransfered ?
3007 RefVal::NotOwned : RefVal::Released);
Anna Zaks554067f2012-08-29 23:23:43 +00003008 else if (E == DecRefAndStopTrackingHard)
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003009 return removeRefBinding(state, sym);
Jordan Rose4531b7d2012-07-02 19:27:43 +00003010
Jordy Rosee0a5d322011-08-23 20:27:16 +00003011 V = V - 1;
3012 break;
3013
3014 case RefVal::NotOwned:
Jordan Rose4531b7d2012-07-02 19:27:43 +00003015 if (V.getCount() > 0) {
Anna Zaks554067f2012-08-29 23:23:43 +00003016 if (E == DecRefAndStopTrackingHard)
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003017 return removeRefBinding(state, sym);
Jordy Rosee0a5d322011-08-23 20:27:16 +00003018 V = V - 1;
Jordan Rose4531b7d2012-07-02 19:27:43 +00003019 } else {
Jordy Rosee0a5d322011-08-23 20:27:16 +00003020 V = V ^ RefVal::ErrorReleaseNotOwned;
3021 hasErr = V.getKind();
3022 }
3023 break;
3024
3025 case RefVal::Released:
3026 // Non-GC cases are handled above.
Jordy Rose17a38e22011-09-02 05:55:19 +00003027 assert(C.isObjCGCEnabled());
Jordy Rosee0a5d322011-08-23 20:27:16 +00003028 V = V ^ RefVal::ErrorUseAfterRelease;
3029 hasErr = V.getKind();
3030 break;
3031 }
3032 break;
3033 }
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003034 return setRefBinding(state, sym, V);
Jordy Rosee0a5d322011-08-23 20:27:16 +00003035}
3036
Ted Kremenek8bef8232012-01-26 21:29:00 +00003037void RetainCountChecker::processNonLeakError(ProgramStateRef St,
Jordy Rose910c4052011-09-02 06:44:22 +00003038 SourceRange ErrorRange,
3039 RefVal::Kind ErrorKind,
3040 SymbolRef Sym,
3041 CheckerContext &C) const {
Jordy Rose294396b2011-08-22 23:48:23 +00003042 ExplodedNode *N = C.generateSink(St);
3043 if (!N)
3044 return;
3045
Jordy Rose294396b2011-08-22 23:48:23 +00003046 CFRefBug *BT;
3047 switch (ErrorKind) {
3048 default:
3049 llvm_unreachable("Unhandled error.");
Jordy Rose294396b2011-08-22 23:48:23 +00003050 case RefVal::ErrorUseAfterRelease:
Jordy Rosed6334e12011-08-25 00:34:03 +00003051 if (!useAfterRelease)
3052 useAfterRelease.reset(new UseAfterRelease());
3053 BT = &*useAfterRelease;
Jordy Rose294396b2011-08-22 23:48:23 +00003054 break;
3055 case RefVal::ErrorReleaseNotOwned:
Jordy Rosed6334e12011-08-25 00:34:03 +00003056 if (!releaseNotOwned)
3057 releaseNotOwned.reset(new BadRelease());
3058 BT = &*releaseNotOwned;
Jordy Rose294396b2011-08-22 23:48:23 +00003059 break;
3060 case RefVal::ErrorDeallocGC:
Jordy Rosed6334e12011-08-25 00:34:03 +00003061 if (!deallocGC)
3062 deallocGC.reset(new DeallocGC());
3063 BT = &*deallocGC;
Jordy Rose294396b2011-08-22 23:48:23 +00003064 break;
3065 case RefVal::ErrorDeallocNotOwned:
Jordy Rosed6334e12011-08-25 00:34:03 +00003066 if (!deallocNotOwned)
3067 deallocNotOwned.reset(new DeallocNotOwned());
3068 BT = &*deallocNotOwned;
Jordy Rose294396b2011-08-22 23:48:23 +00003069 break;
3070 }
3071
Jordy Rosed6334e12011-08-25 00:34:03 +00003072 assert(BT);
David Blaikie4e4d0842012-03-11 07:00:24 +00003073 CFRefReport *report = new CFRefReport(*BT, C.getASTContext().getLangOpts(),
Jordy Rose17a38e22011-09-02 05:55:19 +00003074 C.isObjCGCEnabled(), SummaryLog,
3075 N, Sym);
Jordy Rose294396b2011-08-22 23:48:23 +00003076 report->addRange(ErrorRange);
Jordan Rose785950e2012-11-02 01:53:40 +00003077 C.emitReport(report);
Jordy Rose294396b2011-08-22 23:48:23 +00003078}
3079
Jordy Rose910c4052011-09-02 06:44:22 +00003080//===----------------------------------------------------------------------===//
3081// Handle the return values of retain-count-related functions.
3082//===----------------------------------------------------------------------===//
3083
3084bool RetainCountChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
Jordy Rose76c506f2011-08-21 21:58:18 +00003085 // Get the callee. We're only interested in simple C functions.
Ted Kremenek8bef8232012-01-26 21:29:00 +00003086 ProgramStateRef state = C.getState();
Anna Zaksb805c8f2011-12-01 05:57:37 +00003087 const FunctionDecl *FD = C.getCalleeDecl(CE);
Jordy Rose76c506f2011-08-21 21:58:18 +00003088 if (!FD)
3089 return false;
3090
3091 IdentifierInfo *II = FD->getIdentifier();
3092 if (!II)
3093 return false;
3094
3095 // For now, we're only handling the functions that return aliases of their
3096 // arguments: CFRetain and CFMakeCollectable (and their families).
3097 // Eventually we should add other functions we can model entirely,
3098 // such as CFRelease, which don't invalidate their arguments or globals.
3099 if (CE->getNumArgs() != 1)
3100 return false;
3101
3102 // Get the name of the function.
3103 StringRef FName = II->getName();
3104 FName = FName.substr(FName.find_first_not_of('_'));
3105
3106 // See if it's one of the specific functions we know how to eval.
3107 bool canEval = false;
3108
Anna Zaksb805c8f2011-12-01 05:57:37 +00003109 QualType ResultTy = CE->getCallReturnType();
Jordy Rose76c506f2011-08-21 21:58:18 +00003110 if (ResultTy->isObjCIdType()) {
3111 // Handle: id NSMakeCollectable(CFTypeRef)
3112 canEval = II->isStr("NSMakeCollectable");
3113 } else if (ResultTy->isPointerType()) {
3114 // Handle: (CF|CG)Retain
3115 // CFMakeCollectable
3116 // It's okay to be a little sloppy here (CGMakeCollectable doesn't exist).
3117 if (cocoa::isRefType(ResultTy, "CF", FName) ||
3118 cocoa::isRefType(ResultTy, "CG", FName)) {
3119 canEval = isRetain(FD, FName) || isMakeCollectable(FD, FName);
3120 }
3121 }
3122
3123 if (!canEval)
3124 return false;
3125
3126 // Bind the return value.
Ted Kremenek5eca4822012-01-06 22:09:28 +00003127 const LocationContext *LCtx = C.getLocationContext();
3128 SVal RetVal = state->getSVal(CE->getArg(0), LCtx);
Jordy Rose76c506f2011-08-21 21:58:18 +00003129 if (RetVal.isUnknown()) {
3130 // If the receiver is unknown, conjure a return value.
3131 SValBuilder &SVB = C.getSValBuilder();
Ted Kremenek66c486f2012-08-22 06:26:15 +00003132 RetVal = SVB.conjureSymbolVal(0, CE, LCtx, ResultTy, C.blockCount());
Jordy Rose76c506f2011-08-21 21:58:18 +00003133 }
Ted Kremenek5eca4822012-01-06 22:09:28 +00003134 state = state->BindExpr(CE, LCtx, RetVal, false);
Jordy Rose76c506f2011-08-21 21:58:18 +00003135
Jordy Rose294396b2011-08-22 23:48:23 +00003136 // FIXME: This should not be necessary, but otherwise the argument seems to be
3137 // considered alive during the next statement.
3138 if (const MemRegion *ArgRegion = RetVal.getAsRegion()) {
3139 // Save the refcount status of the argument.
3140 SymbolRef Sym = RetVal.getAsLocSymbol();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003141 const RefVal *Binding = 0;
Jordy Rose294396b2011-08-22 23:48:23 +00003142 if (Sym)
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003143 Binding = getRefBinding(state, Sym);
Jordy Rose76c506f2011-08-21 21:58:18 +00003144
Jordy Rose294396b2011-08-22 23:48:23 +00003145 // Invalidate the argument region.
Anna Zaksbf53dfa2012-12-20 00:38:25 +00003146 state = state->invalidateRegions(ArgRegion, CE, C.blockCount(), LCtx,
Anna Zaks64eb0702013-01-16 01:35:54 +00003147 /*CausesPointerEscape*/ false);
Jordy Rose76c506f2011-08-21 21:58:18 +00003148
Jordy Rose294396b2011-08-22 23:48:23 +00003149 // Restore the refcount status of the argument.
3150 if (Binding)
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003151 state = setRefBinding(state, Sym, *Binding);
Jordy Rose294396b2011-08-22 23:48:23 +00003152 }
3153
Anna Zaks0bd6b112011-10-26 21:06:34 +00003154 C.addTransition(state);
Jordy Rose76c506f2011-08-21 21:58:18 +00003155 return true;
3156}
3157
Jordy Rose910c4052011-09-02 06:44:22 +00003158//===----------------------------------------------------------------------===//
3159// Handle return statements.
3160//===----------------------------------------------------------------------===//
Jordy Rosef53e8c72011-08-23 19:43:16 +00003161
Jordy Rose910c4052011-09-02 06:44:22 +00003162void RetainCountChecker::checkPreStmt(const ReturnStmt *S,
3163 CheckerContext &C) const {
Ted Kremeneke5715782012-02-25 02:09:09 +00003164
3165 // Only adjust the reference count if this is the top-level call frame,
3166 // and not the result of inlining. In the future, we should do
3167 // better checking even for inlined calls, and see if they match
3168 // with their expected semantics (e.g., the method should return a retained
3169 // object, etc.).
Anna Zaksfadcd5d2012-11-03 02:54:16 +00003170 if (!C.inTopFrame())
Ted Kremeneke5715782012-02-25 02:09:09 +00003171 return;
3172
Jordy Rosef53e8c72011-08-23 19:43:16 +00003173 const Expr *RetE = S->getRetValue();
3174 if (!RetE)
3175 return;
3176
Ted Kremenek8bef8232012-01-26 21:29:00 +00003177 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00003178 SymbolRef Sym =
3179 state->getSValAsScalarOrLoc(RetE, C.getLocationContext()).getAsLocSymbol();
Jordy Rosef53e8c72011-08-23 19:43:16 +00003180 if (!Sym)
3181 return;
3182
3183 // Get the reference count binding (if any).
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003184 const RefVal *T = getRefBinding(state, Sym);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003185 if (!T)
3186 return;
3187
3188 // Change the reference count.
3189 RefVal X = *T;
3190
3191 switch (X.getKind()) {
3192 case RefVal::Owned: {
3193 unsigned cnt = X.getCount();
3194 assert(cnt > 0);
3195 X.setCount(cnt - 1);
3196 X = X ^ RefVal::ReturnedOwned;
3197 break;
3198 }
3199
3200 case RefVal::NotOwned: {
3201 unsigned cnt = X.getCount();
3202 if (cnt) {
3203 X.setCount(cnt - 1);
3204 X = X ^ RefVal::ReturnedOwned;
3205 }
3206 else {
3207 X = X ^ RefVal::ReturnedNotOwned;
3208 }
3209 break;
3210 }
3211
3212 default:
3213 return;
3214 }
3215
3216 // Update the binding.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003217 state = setRefBinding(state, Sym, X);
Anna Zaks0bd6b112011-10-26 21:06:34 +00003218 ExplodedNode *Pred = C.addTransition(state);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003219
3220 // At this point we have updated the state properly.
3221 // Everything after this is merely checking to see if the return value has
3222 // been over- or under-retained.
3223
3224 // Did we cache out?
3225 if (!Pred)
3226 return;
3227
Jordy Rosef53e8c72011-08-23 19:43:16 +00003228 // Update the autorelease counts.
3229 static SimpleProgramPointTag
Jordy Rose910c4052011-09-02 06:44:22 +00003230 AutoreleaseTag("RetainCountChecker : Autorelease");
Jordan Rose4ee1c552012-12-06 18:58:18 +00003231 state = handleAutoreleaseCounts(state, Pred, &AutoreleaseTag, C, Sym, X);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003232
3233 // Did we cache out?
Jordan Rose4ee1c552012-12-06 18:58:18 +00003234 if (!state)
Jordy Rosef53e8c72011-08-23 19:43:16 +00003235 return;
3236
3237 // Get the updated binding.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003238 T = getRefBinding(state, Sym);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003239 assert(T);
3240 X = *T;
3241
3242 // Consult the summary of the enclosing method.
Jordy Rose17a38e22011-09-02 05:55:19 +00003243 RetainSummaryManager &Summaries = getSummaryManager(C);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003244 const Decl *CD = &Pred->getCodeDecl();
Jordan Rose4531b7d2012-07-02 19:27:43 +00003245 RetEffect RE = RetEffect::MakeNoRet();
Jordy Rosef53e8c72011-08-23 19:43:16 +00003246
Jordan Rose4531b7d2012-07-02 19:27:43 +00003247 // FIXME: What is the convention for blocks? Is there one?
Jordy Rosef53e8c72011-08-23 19:43:16 +00003248 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CD)) {
Jordy Roseb6cfc092011-08-25 00:10:37 +00003249 const RetainSummary *Summ = Summaries.getMethodSummary(MD);
Jordan Rose4531b7d2012-07-02 19:27:43 +00003250 RE = Summ->getRetEffect();
3251 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) {
3252 if (!isa<CXXMethodDecl>(FD)) {
3253 const RetainSummary *Summ = Summaries.getFunctionSummary(FD);
3254 RE = Summ->getRetEffect();
3255 }
Jordy Rosef53e8c72011-08-23 19:43:16 +00003256 }
3257
Jordan Rose4531b7d2012-07-02 19:27:43 +00003258 checkReturnWithRetEffect(S, C, Pred, RE, X, Sym, state);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003259}
3260
Jordy Rose910c4052011-09-02 06:44:22 +00003261void RetainCountChecker::checkReturnWithRetEffect(const ReturnStmt *S,
3262 CheckerContext &C,
3263 ExplodedNode *Pred,
3264 RetEffect RE, RefVal X,
3265 SymbolRef Sym,
Ted Kremenek8bef8232012-01-26 21:29:00 +00003266 ProgramStateRef state) const {
Jordy Rosef53e8c72011-08-23 19:43:16 +00003267 // Any leaks or other errors?
3268 if (X.isReturnedOwned() && X.getCount() == 0) {
3269 if (RE.getKind() != RetEffect::NoRet) {
3270 bool hasError = false;
Jordy Rose17a38e22011-09-02 05:55:19 +00003271 if (C.isObjCGCEnabled() && RE.getObjKind() == RetEffect::ObjC) {
Jordy Rosef53e8c72011-08-23 19:43:16 +00003272 // Things are more complicated with garbage collection. If the
3273 // returned object is suppose to be an Objective-C object, we have
3274 // a leak (as the caller expects a GC'ed object) because no
3275 // method should return ownership unless it returns a CF object.
3276 hasError = true;
3277 X = X ^ RefVal::ErrorGCLeakReturned;
3278 }
3279 else if (!RE.isOwned()) {
3280 // Either we are using GC and the returned object is a CF type
3281 // or we aren't using GC. In either case, we expect that the
3282 // enclosing method is expected to return ownership.
3283 hasError = true;
3284 X = X ^ RefVal::ErrorLeakReturned;
3285 }
3286
3287 if (hasError) {
3288 // Generate an error node.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003289 state = setRefBinding(state, Sym, X);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003290
3291 static SimpleProgramPointTag
Jordy Rose910c4052011-09-02 06:44:22 +00003292 ReturnOwnLeakTag("RetainCountChecker : ReturnsOwnLeak");
Anna Zaks0bd6b112011-10-26 21:06:34 +00003293 ExplodedNode *N = C.addTransition(state, Pred, &ReturnOwnLeakTag);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003294 if (N) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003295 const LangOptions &LOpts = C.getASTContext().getLangOpts();
Jordy Rose17a38e22011-09-02 05:55:19 +00003296 bool GCEnabled = C.isObjCGCEnabled();
Jordy Rosef53e8c72011-08-23 19:43:16 +00003297 CFRefReport *report =
Jordy Rose17a38e22011-09-02 05:55:19 +00003298 new CFRefLeakReport(*getLeakAtReturnBug(LOpts, GCEnabled),
3299 LOpts, GCEnabled, SummaryLog,
Ted Kremenek08a838d2013-04-16 21:44:22 +00003300 N, Sym, C, IncludeAllocationLine);
3301
Jordan Rose785950e2012-11-02 01:53:40 +00003302 C.emitReport(report);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003303 }
3304 }
3305 }
3306 } else if (X.isReturnedNotOwned()) {
3307 if (RE.isOwned()) {
3308 // Trying to return a not owned object to a caller expecting an
3309 // owned object.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003310 state = setRefBinding(state, Sym, X ^ RefVal::ErrorReturnedNotOwned);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003311
3312 static SimpleProgramPointTag
Jordy Rose910c4052011-09-02 06:44:22 +00003313 ReturnNotOwnedTag("RetainCountChecker : ReturnNotOwnedForOwned");
Anna Zaks0bd6b112011-10-26 21:06:34 +00003314 ExplodedNode *N = C.addTransition(state, Pred, &ReturnNotOwnedTag);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003315 if (N) {
Jordy Rosed6334e12011-08-25 00:34:03 +00003316 if (!returnNotOwnedForOwned)
3317 returnNotOwnedForOwned.reset(new ReturnedNotOwnedForOwned());
3318
Jordy Rosef53e8c72011-08-23 19:43:16 +00003319 CFRefReport *report =
Jordy Rosed6334e12011-08-25 00:34:03 +00003320 new CFRefReport(*returnNotOwnedForOwned,
David Blaikie4e4d0842012-03-11 07:00:24 +00003321 C.getASTContext().getLangOpts(),
Jordy Rose17a38e22011-09-02 05:55:19 +00003322 C.isObjCGCEnabled(), SummaryLog, N, Sym);
Jordan Rose785950e2012-11-02 01:53:40 +00003323 C.emitReport(report);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003324 }
3325 }
3326 }
3327}
3328
Jordy Rose8d228632011-08-23 20:07:14 +00003329//===----------------------------------------------------------------------===//
Jordy Rose910c4052011-09-02 06:44:22 +00003330// Check various ways a symbol can be invalidated.
3331//===----------------------------------------------------------------------===//
3332
Anna Zaks390909c2011-10-06 00:43:15 +00003333void RetainCountChecker::checkBind(SVal loc, SVal val, const Stmt *S,
Jordy Rose910c4052011-09-02 06:44:22 +00003334 CheckerContext &C) const {
3335 // Are we storing to something that causes the value to "escape"?
3336 bool escapes = true;
3337
3338 // A value escapes in three possible cases (this may change):
3339 //
3340 // (1) we are binding to something that is not a memory region.
3341 // (2) we are binding to a memregion that does not have stack storage
3342 // (3) we are binding to a memregion with stack storage that the store
3343 // does not understand.
Ted Kremenek8bef8232012-01-26 21:29:00 +00003344 ProgramStateRef state = C.getState();
Jordy Rose910c4052011-09-02 06:44:22 +00003345
David Blaikiedc84cd52013-02-20 22:23:23 +00003346 if (Optional<loc::MemRegionVal> regionLoc = loc.getAs<loc::MemRegionVal>()) {
Jordy Rose910c4052011-09-02 06:44:22 +00003347 escapes = !regionLoc->getRegion()->hasStackStorage();
3348
3349 if (!escapes) {
3350 // To test (3), generate a new state with the binding added. If it is
3351 // the same state, then it escapes (since the store cannot represent
3352 // the binding).
Anna Zakse7958da2012-05-02 00:15:40 +00003353 // Do this only if we know that the store is not supposed to generate the
3354 // same state.
3355 SVal StoredVal = state->getSVal(regionLoc->getRegion());
3356 if (StoredVal != val)
3357 escapes = (state == (state->bindLoc(*regionLoc, val)));
Jordy Rose910c4052011-09-02 06:44:22 +00003358 }
Ted Kremenekde5b4fb2012-03-27 01:12:45 +00003359 if (!escapes) {
3360 // Case 4: We do not currently model what happens when a symbol is
3361 // assigned to a struct field, so be conservative here and let the symbol
3362 // go. TODO: This could definitely be improved upon.
3363 escapes = !isa<VarRegion>(regionLoc->getRegion());
3364 }
Jordy Rose910c4052011-09-02 06:44:22 +00003365 }
3366
3367 // If our store can represent the binding and we aren't storing to something
3368 // that doesn't have local storage then just return and have the simulation
3369 // state continue as is.
3370 if (!escapes)
3371 return;
3372
3373 // Otherwise, find all symbols referenced by 'val' that we are tracking
3374 // and stop tracking them.
3375 state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
Anna Zaks0bd6b112011-10-26 21:06:34 +00003376 C.addTransition(state);
Jordy Rose910c4052011-09-02 06:44:22 +00003377}
3378
Ted Kremenek8bef8232012-01-26 21:29:00 +00003379ProgramStateRef RetainCountChecker::evalAssume(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003380 SVal Cond,
3381 bool Assumption) const {
3382
3383 // FIXME: We may add to the interface of evalAssume the list of symbols
3384 // whose assumptions have changed. For now we just iterate through the
3385 // bindings and check if any of the tracked symbols are NULL. This isn't
3386 // too bad since the number of symbols we will track in practice are
3387 // probably small and evalAssume is only called at branches and a few
3388 // other places.
Jordan Rose166d5022012-11-02 01:54:06 +00003389 RefBindingsTy B = state->get<RefBindings>();
Jordy Rose910c4052011-09-02 06:44:22 +00003390
3391 if (B.isEmpty())
3392 return state;
3393
3394 bool changed = false;
Jordan Rose166d5022012-11-02 01:54:06 +00003395 RefBindingsTy::Factory &RefBFactory = state->get_context<RefBindings>();
Jordy Rose910c4052011-09-02 06:44:22 +00003396
Jordan Rose166d5022012-11-02 01:54:06 +00003397 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Ted Kremenek47cbd0f2012-09-07 22:31:01 +00003398 // Check if the symbol is null stop tracking the symbol.
Jordan Roseec8d4202012-11-01 00:18:27 +00003399 ConstraintManager &CMgr = state->getConstraintManager();
3400 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
3401 if (AllocFailed.isConstrainedTrue()) {
Jordy Rose910c4052011-09-02 06:44:22 +00003402 changed = true;
3403 B = RefBFactory.remove(B, I.getKey());
3404 }
3405 }
3406
3407 if (changed)
3408 state = state->set<RefBindings>(B);
3409
3410 return state;
3411}
3412
Ted Kremenek8bef8232012-01-26 21:29:00 +00003413ProgramStateRef
3414RetainCountChecker::checkRegionChanges(ProgramStateRef state,
Anna Zaksbf53dfa2012-12-20 00:38:25 +00003415 const InvalidatedSymbols *invalidated,
Jordy Rose910c4052011-09-02 06:44:22 +00003416 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00003417 ArrayRef<const MemRegion *> Regions,
Jordan Rose740d4902012-07-02 19:27:35 +00003418 const CallEvent *Call) const {
Jordy Rose910c4052011-09-02 06:44:22 +00003419 if (!invalidated)
3420 return state;
3421
3422 llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
3423 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
3424 E = ExplicitRegions.end(); I != E; ++I) {
3425 if (const SymbolicRegion *SR = (*I)->StripCasts()->getAs<SymbolicRegion>())
3426 WhitelistedSymbols.insert(SR->getSymbol());
3427 }
3428
Anna Zaksbf53dfa2012-12-20 00:38:25 +00003429 for (InvalidatedSymbols::const_iterator I=invalidated->begin(),
Jordy Rose910c4052011-09-02 06:44:22 +00003430 E = invalidated->end(); I!=E; ++I) {
3431 SymbolRef sym = *I;
3432 if (WhitelistedSymbols.count(sym))
3433 continue;
3434 // Remove any existing reference-count binding.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003435 state = removeRefBinding(state, sym);
Jordy Rose910c4052011-09-02 06:44:22 +00003436 }
3437 return state;
3438}
3439
3440//===----------------------------------------------------------------------===//
Jordy Rose8d228632011-08-23 20:07:14 +00003441// Handle dead symbols and end-of-path.
3442//===----------------------------------------------------------------------===//
3443
Jordan Rose4ee1c552012-12-06 18:58:18 +00003444ProgramStateRef
3445RetainCountChecker::handleAutoreleaseCounts(ProgramStateRef state,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003446 ExplodedNode *Pred,
Jordan Rose2bce86c2012-08-18 00:30:16 +00003447 const ProgramPointTag *Tag,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003448 CheckerContext &Ctx,
Jordy Rose910c4052011-09-02 06:44:22 +00003449 SymbolRef Sym, RefVal V) const {
Jordy Rose8d228632011-08-23 20:07:14 +00003450 unsigned ACnt = V.getAutoreleaseCount();
3451
3452 // No autorelease counts? Nothing to be done.
3453 if (!ACnt)
Jordan Rose4ee1c552012-12-06 18:58:18 +00003454 return state;
Jordy Rose8d228632011-08-23 20:07:14 +00003455
Anna Zaks6a93bd52011-10-25 19:57:11 +00003456 assert(!Ctx.isObjCGCEnabled() && "Autorelease counts in GC mode?");
Jordy Rose8d228632011-08-23 20:07:14 +00003457 unsigned Cnt = V.getCount();
3458
3459 // FIXME: Handle sending 'autorelease' to already released object.
3460
3461 if (V.getKind() == RefVal::ReturnedOwned)
3462 ++Cnt;
3463
3464 if (ACnt <= Cnt) {
3465 if (ACnt == Cnt) {
3466 V.clearCounts();
3467 if (V.getKind() == RefVal::ReturnedOwned)
3468 V = V ^ RefVal::ReturnedNotOwned;
3469 else
3470 V = V ^ RefVal::NotOwned;
3471 } else {
Anna Zaks0217b1d2013-01-31 22:36:17 +00003472 V.setCount(V.getCount() - ACnt);
Jordy Rose8d228632011-08-23 20:07:14 +00003473 V.setAutoreleaseCount(0);
3474 }
Jordan Rose4ee1c552012-12-06 18:58:18 +00003475 return setRefBinding(state, Sym, V);
Jordy Rose8d228632011-08-23 20:07:14 +00003476 }
3477
3478 // Woah! More autorelease counts then retain counts left.
3479 // Emit hard error.
3480 V = V ^ RefVal::ErrorOverAutorelease;
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003481 state = setRefBinding(state, Sym, V);
Jordy Rose8d228632011-08-23 20:07:14 +00003482
Jordan Rosefa06f042012-08-20 18:43:42 +00003483 ExplodedNode *N = Ctx.generateSink(state, Pred, Tag);
Jordan Rose2bce86c2012-08-18 00:30:16 +00003484 if (N) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003485 SmallString<128> sbuf;
Jordy Rose8d228632011-08-23 20:07:14 +00003486 llvm::raw_svector_ostream os(sbuf);
Jordan Rose2545b1d2013-04-23 01:42:25 +00003487 os << "Object was autoreleased ";
Jordy Rose8d228632011-08-23 20:07:14 +00003488 if (V.getAutoreleaseCount() > 1)
Jordan Rose2545b1d2013-04-23 01:42:25 +00003489 os << V.getAutoreleaseCount() << " times but the object ";
3490 else
3491 os << "but ";
3492 os << "has a +" << V.getCount() << " retain count";
Jordy Rose8d228632011-08-23 20:07:14 +00003493
Jordy Rosed6334e12011-08-25 00:34:03 +00003494 if (!overAutorelease)
3495 overAutorelease.reset(new OverAutorelease());
3496
David Blaikie4e4d0842012-03-11 07:00:24 +00003497 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
Jordy Rose8d228632011-08-23 20:07:14 +00003498 CFRefReport *report =
Jordy Rosed6334e12011-08-25 00:34:03 +00003499 new CFRefReport(*overAutorelease, LOpts, /* GCEnabled = */ false,
3500 SummaryLog, N, Sym, os.str());
Jordan Rose785950e2012-11-02 01:53:40 +00003501 Ctx.emitReport(report);
Jordy Rose8d228632011-08-23 20:07:14 +00003502 }
3503
Jordan Rose4ee1c552012-12-06 18:58:18 +00003504 return 0;
Jordy Rose8d228632011-08-23 20:07:14 +00003505}
Jordy Rose38f17d62011-08-23 19:01:07 +00003506
Ted Kremenek8bef8232012-01-26 21:29:00 +00003507ProgramStateRef
3508RetainCountChecker::handleSymbolDeath(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003509 SymbolRef sid, RefVal V,
Jordy Rose38f17d62011-08-23 19:01:07 +00003510 SmallVectorImpl<SymbolRef> &Leaked) const {
Jordy Rose53376122011-08-24 04:48:19 +00003511 bool hasLeak = false;
Jordy Rose38f17d62011-08-23 19:01:07 +00003512 if (V.isOwned())
3513 hasLeak = true;
3514 else if (V.isNotOwned() || V.isReturnedOwned())
3515 hasLeak = (V.getCount() > 0);
3516
3517 if (!hasLeak)
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003518 return removeRefBinding(state, sid);
Jordy Rose38f17d62011-08-23 19:01:07 +00003519
3520 Leaked.push_back(sid);
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003521 return setRefBinding(state, sid, V ^ RefVal::ErrorLeak);
Jordy Rose38f17d62011-08-23 19:01:07 +00003522}
3523
3524ExplodedNode *
Ted Kremenek8bef8232012-01-26 21:29:00 +00003525RetainCountChecker::processLeaks(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003526 SmallVectorImpl<SymbolRef> &Leaked,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003527 CheckerContext &Ctx,
3528 ExplodedNode *Pred) const {
Jordy Rose38f17d62011-08-23 19:01:07 +00003529 // Generate an intermediate node representing the leak point.
Jordan Rose2bce86c2012-08-18 00:30:16 +00003530 ExplodedNode *N = Ctx.addTransition(state, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003531
3532 if (N) {
3533 for (SmallVectorImpl<SymbolRef>::iterator
3534 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3535
David Blaikie4e4d0842012-03-11 07:00:24 +00003536 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
Anna Zaks6a93bd52011-10-25 19:57:11 +00003537 bool GCEnabled = Ctx.isObjCGCEnabled();
Jordy Rose17a38e22011-09-02 05:55:19 +00003538 CFRefBug *BT = Pred ? getLeakWithinFunctionBug(LOpts, GCEnabled)
3539 : getLeakAtReturnBug(LOpts, GCEnabled);
Jordy Rose38f17d62011-08-23 19:01:07 +00003540 assert(BT && "BugType not initialized.");
Jordy Rose20589562011-08-24 22:39:09 +00003541
Jordy Rose17a38e22011-09-02 05:55:19 +00003542 CFRefLeakReport *report = new CFRefLeakReport(*BT, LOpts, GCEnabled,
Ted Kremenek08a838d2013-04-16 21:44:22 +00003543 SummaryLog, N, *I, Ctx,
3544 IncludeAllocationLine);
Jordan Rose785950e2012-11-02 01:53:40 +00003545 Ctx.emitReport(report);
Jordy Rose38f17d62011-08-23 19:01:07 +00003546 }
3547 }
3548
3549 return N;
3550}
3551
Anna Zaks344c77a2013-01-03 00:25:29 +00003552void RetainCountChecker::checkEndFunction(CheckerContext &Ctx) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +00003553 ProgramStateRef state = Ctx.getState();
Jordan Rose166d5022012-11-02 01:54:06 +00003554 RefBindingsTy B = state->get<RefBindings>();
Anna Zaksaf498a22011-10-25 19:56:48 +00003555 ExplodedNode *Pred = Ctx.getPredecessor();
Jordy Rose38f17d62011-08-23 19:01:07 +00003556
Jordan Rosed8188f82013-08-01 22:16:36 +00003557 // Don't process anything within synthesized bodies.
3558 const LocationContext *LCtx = Pred->getLocationContext();
3559 if (LCtx->getAnalysisDeclContext()->isBodyAutosynthesized()) {
3560 assert(LCtx->getParent());
3561 return;
3562 }
3563
Jordan Rose166d5022012-11-02 01:54:06 +00003564 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Jordan Rose4ee1c552012-12-06 18:58:18 +00003565 state = handleAutoreleaseCounts(state, Pred, /*Tag=*/0, Ctx,
3566 I->first, I->second);
Jordy Rose8d228632011-08-23 20:07:14 +00003567 if (!state)
Jordy Rose38f17d62011-08-23 19:01:07 +00003568 return;
3569 }
3570
Ted Kremenek0cf3d472012-02-07 00:24:33 +00003571 // If the current LocationContext has a parent, don't check for leaks.
3572 // We will do that later.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003573 // FIXME: we should instead check for imbalances of the retain/releases,
Ted Kremenek0cf3d472012-02-07 00:24:33 +00003574 // and suggest annotations.
Jordan Rosed8188f82013-08-01 22:16:36 +00003575 if (LCtx->getParent())
Ted Kremenek0cf3d472012-02-07 00:24:33 +00003576 return;
3577
Jordy Rose38f17d62011-08-23 19:01:07 +00003578 B = state->get<RefBindings>();
3579 SmallVector<SymbolRef, 10> Leaked;
3580
Jordan Rose166d5022012-11-02 01:54:06 +00003581 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I)
Jordy Rose8d228632011-08-23 20:07:14 +00003582 state = handleSymbolDeath(state, I->first, I->second, Leaked);
Jordy Rose38f17d62011-08-23 19:01:07 +00003583
Jordan Rose2bce86c2012-08-18 00:30:16 +00003584 processLeaks(state, Leaked, Ctx, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003585}
3586
3587const ProgramPointTag *
Jordy Rose910c4052011-09-02 06:44:22 +00003588RetainCountChecker::getDeadSymbolTag(SymbolRef sym) const {
Jordy Rose38f17d62011-08-23 19:01:07 +00003589 const SimpleProgramPointTag *&tag = DeadSymbolTags[sym];
3590 if (!tag) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003591 SmallString<64> buf;
Jordy Rose38f17d62011-08-23 19:01:07 +00003592 llvm::raw_svector_ostream out(buf);
Anna Zaksf62ceec2011-12-05 18:58:11 +00003593 out << "RetainCountChecker : Dead Symbol : ";
3594 sym->dumpToStream(out);
Jordy Rose38f17d62011-08-23 19:01:07 +00003595 tag = new SimpleProgramPointTag(out.str());
3596 }
3597 return tag;
3598}
3599
Jordy Rose910c4052011-09-02 06:44:22 +00003600void RetainCountChecker::checkDeadSymbols(SymbolReaper &SymReaper,
3601 CheckerContext &C) const {
Jordy Rose38f17d62011-08-23 19:01:07 +00003602 ExplodedNode *Pred = C.getPredecessor();
3603
Ted Kremenek8bef8232012-01-26 21:29:00 +00003604 ProgramStateRef state = C.getState();
Jordan Rose166d5022012-11-02 01:54:06 +00003605 RefBindingsTy B = state->get<RefBindings>();
Jordan Rose4ee1c552012-12-06 18:58:18 +00003606 SmallVector<SymbolRef, 10> Leaked;
Jordy Rose38f17d62011-08-23 19:01:07 +00003607
3608 // Update counts from autorelease pools
3609 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3610 E = SymReaper.dead_end(); I != E; ++I) {
3611 SymbolRef Sym = *I;
3612 if (const RefVal *T = B.lookup(Sym)){
3613 // Use the symbol as the tag.
3614 // FIXME: This might not be as unique as we would like.
Jordan Rose2bce86c2012-08-18 00:30:16 +00003615 const ProgramPointTag *Tag = getDeadSymbolTag(Sym);
Jordan Rose4ee1c552012-12-06 18:58:18 +00003616 state = handleAutoreleaseCounts(state, Pred, Tag, C, Sym, *T);
Jordy Rose8d228632011-08-23 20:07:14 +00003617 if (!state)
Jordy Rose38f17d62011-08-23 19:01:07 +00003618 return;
Jordan Rose4ee1c552012-12-06 18:58:18 +00003619
3620 // Fetch the new reference count from the state, and use it to handle
3621 // this symbol.
3622 state = handleSymbolDeath(state, *I, *getRefBinding(state, Sym), Leaked);
Jordy Rose38f17d62011-08-23 19:01:07 +00003623 }
3624 }
3625
Jordan Rose4ee1c552012-12-06 18:58:18 +00003626 if (Leaked.empty()) {
3627 C.addTransition(state);
3628 return;
Jordy Rose38f17d62011-08-23 19:01:07 +00003629 }
3630
Jordan Rose2bce86c2012-08-18 00:30:16 +00003631 Pred = processLeaks(state, Leaked, C, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003632
3633 // Did we cache out?
3634 if (!Pred)
3635 return;
3636
3637 // Now generate a new node that nukes the old bindings.
Jordan Rose4ee1c552012-12-06 18:58:18 +00003638 // The only bindings left at this point are the leaked symbols.
Jordan Rose166d5022012-11-02 01:54:06 +00003639 RefBindingsTy::Factory &F = state->get_context<RefBindings>();
Jordan Rose4ee1c552012-12-06 18:58:18 +00003640 B = state->get<RefBindings>();
Jordy Rose38f17d62011-08-23 19:01:07 +00003641
Jordan Rose4ee1c552012-12-06 18:58:18 +00003642 for (SmallVectorImpl<SymbolRef>::iterator I = Leaked.begin(),
3643 E = Leaked.end();
3644 I != E; ++I)
Jordy Rose38f17d62011-08-23 19:01:07 +00003645 B = F.remove(B, *I);
3646
3647 state = state->set<RefBindings>(B);
Anna Zaks0bd6b112011-10-26 21:06:34 +00003648 C.addTransition(state, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003649}
3650
Ted Kremenek8bef8232012-01-26 21:29:00 +00003651void RetainCountChecker::printState(raw_ostream &Out, ProgramStateRef State,
Jordy Rose910c4052011-09-02 06:44:22 +00003652 const char *NL, const char *Sep) const {
Jordy Rosedbd658e2011-08-28 19:11:56 +00003653
Jordan Rose166d5022012-11-02 01:54:06 +00003654 RefBindingsTy B = State->get<RefBindings>();
Jordy Rosedbd658e2011-08-28 19:11:56 +00003655
Ted Kremenek65a08922013-03-28 18:43:18 +00003656 if (B.isEmpty())
3657 return;
3658
3659 Out << Sep << NL;
Jordy Rosedbd658e2011-08-28 19:11:56 +00003660
Jordan Rose166d5022012-11-02 01:54:06 +00003661 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Jordy Rosedbd658e2011-08-28 19:11:56 +00003662 Out << I->first << " : ";
3663 I->second.print(Out);
3664 Out << NL;
3665 }
Jordy Rosedbd658e2011-08-28 19:11:56 +00003666}
3667
3668//===----------------------------------------------------------------------===//
Jordy Rose910c4052011-09-02 06:44:22 +00003669// Checker registration.
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00003670//===----------------------------------------------------------------------===//
3671
Jordy Rose17a38e22011-09-02 05:55:19 +00003672void ento::registerRetainCountChecker(CheckerManager &Mgr) {
Ted Kremenek08a838d2013-04-16 21:44:22 +00003673 Mgr.registerChecker<RetainCountChecker>(Mgr.getAnalyzerOptions());
Jordy Rose17a38e22011-09-02 05:55:19 +00003674}
3675
Ted Kremenek53c7ea12013-08-14 23:41:49 +00003676//===----------------------------------------------------------------------===//
3677// Implementation of the CallEffects API.
3678//===----------------------------------------------------------------------===//
3679
3680namespace clang { namespace ento { namespace objc_retain {
3681
3682// This is a bit gross, but it allows us to populate CallEffects without
3683// creating a bunch of accessors. This kind is very localized, so the
3684// damage of this macro is limited.
3685#define createCallEffect(D, KIND)\
3686 ASTContext &Ctx = D->getASTContext();\
3687 LangOptions L = Ctx.getLangOpts();\
3688 RetainSummaryManager M(Ctx, L.GCOnly, L.ObjCAutoRefCount);\
3689 const RetainSummary *S = M.get ## KIND ## Summary(D);\
3690 CallEffects CE(S->getRetEffect());\
3691 CE.Receiver = S->getReceiverEffect();\
3692 unsigned N = S->getNumArgs();\
3693 for (unsigned i = 0; i < N; ++i) {\
3694 CE.Args.push_back(S->getArg(i));\
3695 }
3696
3697CallEffects CallEffects::getEffect(const ObjCMethodDecl *MD) {
3698 createCallEffect(MD, Method);
3699 return CE;
3700}
3701
3702CallEffects CallEffects::getEffect(const FunctionDecl *FD) {
3703 createCallEffect(FD, Function);
3704 return CE;
3705}
3706
3707#undef createCallEffect
3708
3709}}}