blob: 613c78835abe6c33d61a2b5d505654377be0dc8d [file] [log] [blame]
Jordy Rose75e680e2011-09-02 06:44:22 +00001//==-- RetainCountChecker.cpp - Checks for leaks and other issues -*- C++ -*--//
Ted Kremenekea6507f2008-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 Rose75e680e2011-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 Kremenekea6507f2008-03-06 00:08:09 +000012//
13//===----------------------------------------------------------------------===//
14
Jordy Rose75e680e2011-09-02 06:44:22 +000015#include "ClangSACheckers.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000016#include "clang/AST/Attr.h"
Ted Kremenek98a24e32011-03-30 17:41:19 +000017#include "clang/AST/DeclCXX.h"
Benjamin Kramerea70eb32012-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 Kremenek2b36f3f2010-02-18 00:05:58 +000021#include "clang/Basic/LangOptions.h"
22#include "clang/Basic/SourceManager.h"
Ted Kremenekf8cbac42011-02-10 01:03:03 +000023#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
24#include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "clang/StaticAnalyzer/Core/Checker.h"
26#include "clang/StaticAnalyzer/Core/CheckerManager.h"
Jordan Rose4f7df9b2012-07-26 21:39:41 +000027#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
Jordy Rose75e680e2011-09-02 06:44:22 +000028#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
Ted Kremenek001fd5b2011-08-15 22:09:50 +000029#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
Ted Kremenekf8cbac42011-02-10 01:03:03 +000030#include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
Ted Kremenek243c0852013-08-14 23:41:46 +000031#include "clang/StaticAnalyzer/Checkers/ObjCRetainCount.h"
Ted Kremenek819e9b62008-03-11 06:39:11 +000032#include "llvm/ADT/DenseMap.h"
33#include "llvm/ADT/FoldingSet.h"
Ted Kremenek0747e7e2008-10-21 15:53:15 +000034#include "llvm/ADT/ImmutableList.h"
Ted Kremenek2b36f3f2010-02-18 00:05:58 +000035#include "llvm/ADT/ImmutableMap.h"
Ted Kremenekc812b232008-05-16 18:33:44 +000036#include "llvm/ADT/STLExtras.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000037#include "llvm/ADT/SmallString.h"
Ted Kremenek2b36f3f2010-02-18 00:05:58 +000038#include "llvm/ADT/StringExtras.h"
Chris Lattner0e62c1c2011-07-23 10:55:15 +000039#include <cstdarg>
Ted Kremenekea6507f2008-03-06 00:08:09 +000040
Ted Kremenek8671acb2013-04-16 21:44:22 +000041#include "AllocationDiagnostics.h"
42
Ted Kremenekea6507f2008-03-06 00:08:09 +000043using namespace clang;
Ted Kremenek98857c92010-12-23 07:20:52 +000044using namespace ento;
Ted Kremenek243c0852013-08-14 23:41:46 +000045using namespace objc_retain;
Ted Kremenekdb1832d2010-01-27 06:13:48 +000046using llvm::StrInStrNoCase;
Ted Kremenek2855a932008-11-05 16:54:44 +000047
Ted Kremenekc8bef6a2008-04-09 23:49:11 +000048//===----------------------------------------------------------------------===//
Ted Kremenek243c0852013-08-14 23:41:46 +000049// Adapters for FoldingSet.
Ted Kremenekc8bef6a2008-04-09 23:49:11 +000050//===----------------------------------------------------------------------===//
51
Ted Kremenek819e9b62008-03-11 06:39:11 +000052namespace llvm {
Ted Kremenek7d79a5f2009-05-03 05:20:50 +000053template <> struct FoldingSetTrait<ArgEffect> {
Ted Kremenek243c0852013-08-14 23:41:46 +000054static inline void Profile(const ArgEffect X, FoldingSetNodeID &ID) {
Ted Kremenek7d79a5f2009-05-03 05:20:50 +000055 ID.AddInteger((unsigned) X);
56}
Ted Kremenek3185c9c2008-06-25 21:21:56 +000057};
Ted Kremenek243c0852013-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 Kremenek819e9b62008-03-11 06:39:11 +000064} // end llvm namespace
65
Ted Kremenek243c0852013-08-14 23:41:46 +000066//===----------------------------------------------------------------------===//
67// Reference-counting logic (typestate + counts).
68//===----------------------------------------------------------------------===//
69
Ted Kremenek7d79a5f2009-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 Kremenek819e9b62008-03-11 06:39:11 +000074namespace {
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +000075class RefVal {
Ted Kremeneka2968e52009-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 Kremenekbd862712010-07-01 20:16:50 +000096
Ted Kremeneka2968e52009-11-13 01:54:21 +000097private:
98 Kind kind;
99 RetEffect::ObjKind okind;
100 unsigned Cnt;
101 unsigned ACnt;
102 QualType T;
Ted Kremenekbd862712010-07-01 20:16:50 +0000103
Ted Kremeneka2968e52009-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 Kremenekbd862712010-07-01 20:16:50 +0000106
Ted Kremeneka2968e52009-11-13 01:54:21 +0000107public:
108 Kind getKind() const { return kind; }
Ted Kremenekbd862712010-07-01 20:16:50 +0000109
Ted Kremeneka2968e52009-11-13 01:54:21 +0000110 RetEffect::ObjKind getObjKind() const { return okind; }
Ted Kremenekbd862712010-07-01 20:16:50 +0000111
Ted Kremeneka2968e52009-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 Kremenekbd862712010-07-01 20:16:50 +0000118
Ted Kremeneka2968e52009-11-13 01:54:21 +0000119 QualType getType() const { return T; }
Ted Kremenekbd862712010-07-01 20:16:50 +0000120
Ted Kremeneka2968e52009-11-13 01:54:21 +0000121 bool isOwned() const {
122 return getKind() == Owned;
123 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000124
Ted Kremeneka2968e52009-11-13 01:54:21 +0000125 bool isNotOwned() const {
126 return getKind() == NotOwned;
127 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000128
Ted Kremeneka2968e52009-11-13 01:54:21 +0000129 bool isReturnedOwned() const {
130 return getKind() == ReturnedOwned;
131 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000132
Ted Kremeneka2968e52009-11-13 01:54:21 +0000133 bool isReturnedNotOwned() const {
134 return getKind() == ReturnedNotOwned;
135 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000136
Ted Kremeneka2968e52009-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 Kremenekbd862712010-07-01 20:16:50 +0000141
Ted Kremeneka2968e52009-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 Kremenekbd862712010-07-01 20:16:50 +0000146
Ted Kremeneka2968e52009-11-13 01:54:21 +0000147 // Comparison, profiling, and pretty-printing.
Ted Kremenekbd862712010-07-01 20:16:50 +0000148
Ted Kremeneka2968e52009-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 Kremenekbd862712010-07-01 20:16:50 +0000152
Ted Kremeneka2968e52009-11-13 01:54:21 +0000153 RefVal operator-(size_t i) const {
154 return RefVal(getKind(), getObjKind(), getCount() - i,
155 getAutoreleaseCount(), getType());
156 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000157
Ted Kremeneka2968e52009-11-13 01:54:21 +0000158 RefVal operator+(size_t i) const {
159 return RefVal(getKind(), getObjKind(), getCount() + i,
160 getAutoreleaseCount(), getType());
161 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000162
Ted Kremeneka2968e52009-11-13 01:54:21 +0000163 RefVal operator^(Kind k) const {
164 return RefVal(k, getObjKind(), getCount(), getAutoreleaseCount(),
165 getType());
166 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000167
Ted Kremeneka2968e52009-11-13 01:54:21 +0000168 RefVal autorelease() const {
169 return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount()+1,
170 getType());
171 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000172
Ted Kremeneka2968e52009-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 Kremenekbd862712010-07-01 20:16:50 +0000179
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000180 void print(raw_ostream &Out) const;
Ted Kremeneka2968e52009-11-13 01:54:21 +0000181};
182
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000183void RefVal::print(raw_ostream &Out) const {
Ted Kremeneka2968e52009-11-13 01:54:21 +0000184 if (!T.isNull())
Jordy Rose58a20d32011-08-28 19:11:56 +0000185 Out << "Tracked " << T.getAsString() << '/';
Ted Kremenekbd862712010-07-01 20:16:50 +0000186
Ted Kremeneka2968e52009-11-13 01:54:21 +0000187 switch (getKind()) {
Jordy Rose75e680e2011-09-02 06:44:22 +0000188 default: llvm_unreachable("Invalid RefVal kind");
Ted Kremeneka2968e52009-11-13 01:54:21 +0000189 case Owned: {
190 Out << "Owned";
191 unsigned cnt = getCount();
192 if (cnt) Out << " (+ " << cnt << ")";
193 break;
194 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000195
Ted Kremeneka2968e52009-11-13 01:54:21 +0000196 case NotOwned: {
197 Out << "NotOwned";
198 unsigned cnt = getCount();
199 if (cnt) Out << " (+ " << cnt << ")";
200 break;
201 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000202
Ted Kremeneka2968e52009-11-13 01:54:21 +0000203 case ReturnedOwned: {
204 Out << "ReturnedOwned";
205 unsigned cnt = getCount();
206 if (cnt) Out << " (+ " << cnt << ")";
207 break;
208 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000209
Ted Kremeneka2968e52009-11-13 01:54:21 +0000210 case ReturnedNotOwned: {
211 Out << "ReturnedNotOwned";
212 unsigned cnt = getCount();
213 if (cnt) Out << " (+ " << cnt << ")";
214 break;
215 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000216
Ted Kremeneka2968e52009-11-13 01:54:21 +0000217 case Released:
218 Out << "Released";
219 break;
Ted Kremenekbd862712010-07-01 20:16:50 +0000220
Ted Kremeneka2968e52009-11-13 01:54:21 +0000221 case ErrorDeallocGC:
222 Out << "-dealloc (GC)";
223 break;
Ted Kremenekbd862712010-07-01 20:16:50 +0000224
Ted Kremeneka2968e52009-11-13 01:54:21 +0000225 case ErrorDeallocNotOwned:
226 Out << "-dealloc (not-owned)";
227 break;
Ted Kremenekbd862712010-07-01 20:16:50 +0000228
Ted Kremeneka2968e52009-11-13 01:54:21 +0000229 case ErrorLeak:
230 Out << "Leaked";
231 break;
Ted Kremenekbd862712010-07-01 20:16:50 +0000232
Ted Kremeneka2968e52009-11-13 01:54:21 +0000233 case ErrorLeakReturned:
234 Out << "Leaked (Bad naming)";
235 break;
Ted Kremenekbd862712010-07-01 20:16:50 +0000236
Ted Kremeneka2968e52009-11-13 01:54:21 +0000237 case ErrorGCLeakReturned:
238 Out << "Leaked (GC-ed at return)";
239 break;
Ted Kremenekbd862712010-07-01 20:16:50 +0000240
Ted Kremeneka2968e52009-11-13 01:54:21 +0000241 case ErrorUseAfterRelease:
242 Out << "Use-After-Release [ERROR]";
243 break;
Ted Kremenekbd862712010-07-01 20:16:50 +0000244
Ted Kremeneka2968e52009-11-13 01:54:21 +0000245 case ErrorReleaseNotOwned:
246 Out << "Release of Not-Owned [ERROR]";
247 break;
Ted Kremenekbd862712010-07-01 20:16:50 +0000248
Ted Kremeneka2968e52009-11-13 01:54:21 +0000249 case RefVal::ErrorOverAutorelease:
Jordan Rose7467f062013-04-23 01:42:25 +0000250 Out << "Over-autoreleased";
Ted Kremeneka2968e52009-11-13 01:54:21 +0000251 break;
Ted Kremenekbd862712010-07-01 20:16:50 +0000252
Ted Kremeneka2968e52009-11-13 01:54:21 +0000253 case RefVal::ErrorReturnedNotOwned:
254 Out << "Non-owned object returned instead of owned";
255 break;
256 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000257
Ted Kremeneka2968e52009-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 Rose0c153cb2012-11-02 01:54:06 +0000268REGISTER_MAP_WITH_PROGRAMSTATE(RefBindings, SymbolRef, RefVal)
Ted Kremeneka2968e52009-11-13 01:54:21 +0000269
Anna Zaksf5788c72012-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 Kremeneka2968e52009-11-13 01:54:21 +0000284//===----------------------------------------------------------------------===//
Jordy Rose75e680e2011-09-02 06:44:22 +0000285// Function/Method behavior summaries.
Ted Kremeneka2968e52009-11-13 01:54:21 +0000286//===----------------------------------------------------------------------===//
287
288namespace {
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +0000289class RetainSummary {
Jordy Rose61c974b2012-03-18 01:26:10 +0000290 /// Args - a map of (index, ArgEffect) pairs, where index
Ted Kremenekcb2e6362008-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 Kremenek7d79a5f2009-05-03 05:20:50 +0000293 ArgEffects Args;
Mike Stump11289f42009-09-09 15:08:12 +0000294
Ted Kremenekcb2e6362008-05-06 15:44:25 +0000295 /// DefaultArgEffect - The default ArgEffect to apply to arguments that
296 /// do not have an entry in Args.
Ted Kremeneke8300e52012-01-04 00:35:45 +0000297 ArgEffect DefaultArgEffect;
Mike Stump11289f42009-09-09 15:08:12 +0000298
Ted Kremenek3185c9c2008-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 Kremeneke8300e52012-01-04 00:35:45 +0000301 ArgEffect Receiver;
Mike Stump11289f42009-09-09 15:08:12 +0000302
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000303 /// Ret - The effect on the return value. Used to indicate if the
Jordy Rose898a1482011-08-21 21:58:18 +0000304 /// function/method call returns a new tracked symbol.
Ted Kremeneke8300e52012-01-04 00:35:45 +0000305 RetEffect Ret;
Mike Stump11289f42009-09-09 15:08:12 +0000306
Ted Kremenek819e9b62008-03-11 06:39:11 +0000307public:
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000308 RetainSummary(ArgEffects A, RetEffect R, ArgEffect defaultEff,
Jordy Rose5a3c9ff2011-08-20 20:55:40 +0000309 ArgEffect ReceiverEff)
310 : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R) {}
Mike Stump11289f42009-09-09 15:08:12 +0000311
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000312 /// getArg - Return the argument effect on the argument specified by
313 /// idx (starting from 0).
Ted Kremenekbf9d8042008-03-11 17:48:22 +0000314 ArgEffect getArg(unsigned idx) const {
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000315 if (const ArgEffect *AE = Args.lookup(idx))
316 return *AE;
Mike Stump11289f42009-09-09 15:08:12 +0000317
Ted Kremenekcb2e6362008-05-06 15:44:25 +0000318 return DefaultArgEffect;
Ted Kremenekbf9d8042008-03-11 17:48:22 +0000319 }
Ted Kremenek71c080f2013-08-14 23:41:49 +0000320
Ted Kremenekafe348e2011-01-27 18:43:03 +0000321 void addArg(ArgEffects::Factory &af, unsigned idx, ArgEffect e) {
322 Args = af.add(Args, idx, e);
323 }
Mike Stump11289f42009-09-09 15:08:12 +0000324
Ted Kremenek1d9a2672009-05-04 05:31:22 +0000325 /// setDefaultArgEffect - Set the default argument effect.
326 void setDefaultArgEffect(ArgEffect E) {
327 DefaultArgEffect = E;
328 }
Mike Stump11289f42009-09-09 15:08:12 +0000329
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000330 /// getRetEffect - Returns the effect on the return value of the call.
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000331 RetEffect getRetEffect() const { return Ret; }
Mike Stump11289f42009-09-09 15:08:12 +0000332
Ted Kremenek1d9a2672009-05-04 05:31:22 +0000333 /// setRetEffect - Set the effect of the return value of the call.
334 void setRetEffect(RetEffect E) { Ret = E; }
Mike Stump11289f42009-09-09 15:08:12 +0000335
Ted Kremenek0e898382011-01-27 06:54:14 +0000336
337 /// Sets the effect on the receiver of the message.
338 void setReceiverEffect(ArgEffect e) { Receiver = e; }
339
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000340 /// getReceiverEffect - Returns the effect on the receiver of the call.
341 /// This is only meaningful if the summary applies to an ObjCMessageExpr*.
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000342 ArgEffect getReceiverEffect() const { return Receiver; }
Jordy Rose212e4592011-08-23 04:27:15 +0000343
344 /// Test if two retain summaries are identical. Note that merely equivalent
345 /// summaries are not necessarily identical (for example, if an explicit
346 /// argument effect matches the default effect).
347 bool operator==(const RetainSummary &Other) const {
348 return Args == Other.Args && DefaultArgEffect == Other.DefaultArgEffect &&
349 Receiver == Other.Receiver && Ret == Other.Ret;
350 }
Jordy Rose61c974b2012-03-18 01:26:10 +0000351
352 /// Profile this summary for inclusion in a FoldingSet.
353 void Profile(llvm::FoldingSetNodeID& ID) const {
354 ID.Add(Args);
355 ID.Add(DefaultArgEffect);
356 ID.Add(Receiver);
357 ID.Add(Ret);
358 }
359
360 /// A retain summary is simple if it has no ArgEffects other than the default.
361 bool isSimple() const {
362 return Args.isEmpty();
363 }
Jordan Roseeec15392012-07-02 19:27:43 +0000364
365private:
366 ArgEffects getArgEffects() const { return Args; }
367 ArgEffect getDefaultArgEffect() const { return DefaultArgEffect; }
368
369 friend class RetainSummaryManager;
Ted Kremenek819e9b62008-03-11 06:39:11 +0000370};
Ted Kremenek0cfc1612008-06-23 23:30:29 +0000371} // end anonymous namespace
Ted Kremenek819e9b62008-03-11 06:39:11 +0000372
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000373//===----------------------------------------------------------------------===//
374// Data structures for constructing summaries.
375//===----------------------------------------------------------------------===//
Ted Kremenekb1d13292008-06-24 03:49:48 +0000376
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000377namespace {
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +0000378class ObjCSummaryKey {
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000379 IdentifierInfo* II;
380 Selector S;
Mike Stump11289f42009-09-09 15:08:12 +0000381public:
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000382 ObjCSummaryKey(IdentifierInfo* ii, Selector s)
383 : II(ii), S(s) {}
384
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000385 ObjCSummaryKey(const ObjCInterfaceDecl *d, Selector s)
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000386 : II(d ? d->getIdentifier() : 0), S(s) {}
Ted Kremenek5801f652009-05-13 18:16:01 +0000387
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000388 ObjCSummaryKey(Selector s)
389 : II(0), S(s) {}
Mike Stump11289f42009-09-09 15:08:12 +0000390
Ted Kremeneke8300e52012-01-04 00:35:45 +0000391 IdentifierInfo *getIdentifier() const { return II; }
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000392 Selector getSelector() const { return S; }
393};
Ted Kremenek0cfc1612008-06-23 23:30:29 +0000394}
395
396namespace llvm {
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000397template <> struct DenseMapInfo<ObjCSummaryKey> {
398 static inline ObjCSummaryKey getEmptyKey() {
399 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
400 DenseMapInfo<Selector>::getEmptyKey());
401 }
Mike Stump11289f42009-09-09 15:08:12 +0000402
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000403 static inline ObjCSummaryKey getTombstoneKey() {
404 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
Mike Stump11289f42009-09-09 15:08:12 +0000405 DenseMapInfo<Selector>::getTombstoneKey());
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000406 }
Mike Stump11289f42009-09-09 15:08:12 +0000407
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000408 static unsigned getHashValue(const ObjCSummaryKey &V) {
Benjamin Kramer69b5a602012-05-27 13:28:44 +0000409 typedef std::pair<IdentifierInfo*, Selector> PairTy;
410 return DenseMapInfo<PairTy>::getHashValue(PairTy(V.getIdentifier(),
411 V.getSelector()));
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000412 }
Mike Stump11289f42009-09-09 15:08:12 +0000413
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000414 static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
Benjamin Kramer69b5a602012-05-27 13:28:44 +0000415 return LHS.getIdentifier() == RHS.getIdentifier() &&
416 LHS.getSelector() == RHS.getSelector();
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000417 }
Mike Stump11289f42009-09-09 15:08:12 +0000418
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000419};
Ted Kremenek0cfc1612008-06-23 23:30:29 +0000420} // end llvm namespace
Mike Stump11289f42009-09-09 15:08:12 +0000421
Ted Kremenek0cfc1612008-06-23 23:30:29 +0000422namespace {
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +0000423class ObjCSummaryCache {
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000424 typedef llvm::DenseMap<ObjCSummaryKey, const RetainSummary *> MapTy;
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000425 MapTy M;
426public:
427 ObjCSummaryCache() {}
Mike Stump11289f42009-09-09 15:08:12 +0000428
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000429 const RetainSummary * find(const ObjCInterfaceDecl *D, Selector S) {
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000430 // Do a lookup with the (D,S) pair. If we find a match return
431 // the iterator.
432 ObjCSummaryKey K(D, S);
433 MapTy::iterator I = M.find(K);
Mike Stump11289f42009-09-09 15:08:12 +0000434
Jordan Roseeec15392012-07-02 19:27:43 +0000435 if (I != M.end())
Ted Kremenek8be51382009-07-21 23:27:57 +0000436 return I->second;
Jordan Roseeec15392012-07-02 19:27:43 +0000437 if (!D)
438 return NULL;
Mike Stump11289f42009-09-09 15:08:12 +0000439
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000440 // Walk the super chain. If we find a hit with a parent, we'll end
441 // up returning that summary. We actually allow that key (null,S), as
442 // we cache summaries for the null ObjCInterfaceDecl* to allow us to
443 // generate initial summaries without having to worry about NSObject
444 // being declared.
445 // FIXME: We may change this at some point.
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000446 for (ObjCInterfaceDecl *C=D->getSuperClass() ;; C=C->getSuperClass()) {
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000447 if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
448 break;
Mike Stump11289f42009-09-09 15:08:12 +0000449
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000450 if (!C)
Ted Kremenek8be51382009-07-21 23:27:57 +0000451 return NULL;
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000452 }
Mike Stump11289f42009-09-09 15:08:12 +0000453
454 // Cache the summary with original key to make the next lookup faster
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000455 // and return the iterator.
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000456 const RetainSummary *Summ = I->second;
Ted Kremenek8be51382009-07-21 23:27:57 +0000457 M[K] = Summ;
458 return Summ;
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000459 }
Mike Stump11289f42009-09-09 15:08:12 +0000460
Ted Kremeneke8300e52012-01-04 00:35:45 +0000461 const RetainSummary *find(IdentifierInfo* II, Selector S) {
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000462 // FIXME: Class method lookup. Right now we dont' have a good way
463 // of going between IdentifierInfo* and the class hierarchy.
Ted Kremenek8be51382009-07-21 23:27:57 +0000464 MapTy::iterator I = M.find(ObjCSummaryKey(II, S));
Mike Stump11289f42009-09-09 15:08:12 +0000465
Ted Kremenek8be51382009-07-21 23:27:57 +0000466 if (I == M.end())
467 I = M.find(ObjCSummaryKey(S));
Mike Stump11289f42009-09-09 15:08:12 +0000468
Ted Kremenek8be51382009-07-21 23:27:57 +0000469 return I == M.end() ? NULL : I->second;
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000470 }
Mike Stump11289f42009-09-09 15:08:12 +0000471
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000472 const RetainSummary *& operator[](ObjCSummaryKey K) {
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000473 return M[K];
474 }
Mike Stump11289f42009-09-09 15:08:12 +0000475
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000476 const RetainSummary *& operator[](Selector S) {
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000477 return M[ ObjCSummaryKey(S) ];
478 }
Mike Stump11289f42009-09-09 15:08:12 +0000479};
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000480} // end anonymous namespace
481
482//===----------------------------------------------------------------------===//
483// Data structures for managing collections of summaries.
484//===----------------------------------------------------------------------===//
485
486namespace {
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +0000487class RetainSummaryManager {
Ted Kremenek00daccd2008-05-05 22:11:16 +0000488
489 //==-----------------------------------------------------------------==//
490 // Typedefs.
491 //==-----------------------------------------------------------------==//
Mike Stump11289f42009-09-09 15:08:12 +0000492
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000493 typedef llvm::DenseMap<const FunctionDecl*, const RetainSummary *>
Ted Kremenek00daccd2008-05-05 22:11:16 +0000494 FuncSummariesTy;
Mike Stump11289f42009-09-09 15:08:12 +0000495
Ted Kremenek0cfc1612008-06-23 23:30:29 +0000496 typedef ObjCSummaryCache ObjCMethodSummariesTy;
Mike Stump11289f42009-09-09 15:08:12 +0000497
Jordy Rose61c974b2012-03-18 01:26:10 +0000498 typedef llvm::FoldingSetNodeWrapper<RetainSummary> CachedSummaryNode;
499
Ted Kremenek00daccd2008-05-05 22:11:16 +0000500 //==-----------------------------------------------------------------==//
501 // Data.
502 //==-----------------------------------------------------------------==//
Mike Stump11289f42009-09-09 15:08:12 +0000503
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000504 /// Ctx - The ASTContext object for the analyzed ASTs.
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000505 ASTContext &Ctx;
Ted Kremenekab54e512008-07-01 17:21:27 +0000506
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000507 /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
Ted Kremenek4b7ca772008-04-29 05:33:51 +0000508 const bool GCEnabled;
Mike Stump11289f42009-09-09 15:08:12 +0000509
John McCall31168b02011-06-15 23:02:42 +0000510 /// Records whether or not the analyzed code runs in ARC mode.
511 const bool ARCEnabled;
512
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000513 /// FuncSummaries - A map from FunctionDecls to summaries.
Mike Stump11289f42009-09-09 15:08:12 +0000514 FuncSummariesTy FuncSummaries;
515
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000516 /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
517 /// to summaries.
Ted Kremenekea736c52008-06-23 22:21:20 +0000518 ObjCMethodSummariesTy ObjCClassMethodSummaries;
Ted Kremenek00daccd2008-05-05 22:11:16 +0000519
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000520 /// ObjCMethodSummaries - A map from selectors to summaries.
Ted Kremenekea736c52008-06-23 22:21:20 +0000521 ObjCMethodSummariesTy ObjCMethodSummaries;
Ted Kremenek00daccd2008-05-05 22:11:16 +0000522
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000523 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
524 /// and all other data used by the checker.
Ted Kremenek00daccd2008-05-05 22:11:16 +0000525 llvm::BumpPtrAllocator BPAlloc;
Mike Stump11289f42009-09-09 15:08:12 +0000526
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000527 /// AF - A factory for ArgEffects objects.
Mike Stump11289f42009-09-09 15:08:12 +0000528 ArgEffects::Factory AF;
529
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000530 /// ScratchArgs - A holding buffer for construct ArgEffects.
Ted Kremeneke8300e52012-01-04 00:35:45 +0000531 ArgEffects ScratchArgs;
Mike Stump11289f42009-09-09 15:08:12 +0000532
Ted Kremenek9157fbb2009-05-07 23:40:42 +0000533 /// ObjCAllocRetE - Default return effect for methods returning Objective-C
534 /// objects.
535 RetEffect ObjCAllocRetE;
Ted Kremeneka03705c2009-06-05 23:18:01 +0000536
Mike Stump11289f42009-09-09 15:08:12 +0000537 /// ObjCInitRetE - Default return effect for init methods returning
Ted Kremenek815fbb62009-08-20 05:13:36 +0000538 /// Objective-C objects.
Ted Kremeneka03705c2009-06-05 23:18:01 +0000539 RetEffect ObjCInitRetE;
Mike Stump11289f42009-09-09 15:08:12 +0000540
Jordy Rose61c974b2012-03-18 01:26:10 +0000541 /// SimpleSummaries - Used for uniquing summaries that don't have special
542 /// effects.
543 llvm::FoldingSet<CachedSummaryNode> SimpleSummaries;
Mike Stump11289f42009-09-09 15:08:12 +0000544
Ted Kremenek00daccd2008-05-05 22:11:16 +0000545 //==-----------------------------------------------------------------==//
546 // Methods.
547 //==-----------------------------------------------------------------==//
Mike Stump11289f42009-09-09 15:08:12 +0000548
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000549 /// getArgEffects - Returns a persistent ArgEffects object based on the
550 /// data in ScratchArgs.
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000551 ArgEffects getArgEffects();
Ted Kremenek819e9b62008-03-11 06:39:11 +0000552
Jordan Rose77411322013-10-07 17:16:52 +0000553 enum UnaryFuncKind { cfretain, cfrelease, cfautorelease, cfmakecollectable };
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000554
Ted Kremeneke8300e52012-01-04 00:35:45 +0000555 const RetainSummary *getUnarySummary(const FunctionType* FT,
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000556 UnaryFuncKind func);
Mike Stump11289f42009-09-09 15:08:12 +0000557
Ted Kremeneke8300e52012-01-04 00:35:45 +0000558 const RetainSummary *getCFSummaryCreateRule(const FunctionDecl *FD);
559 const RetainSummary *getCFSummaryGetRule(const FunctionDecl *FD);
560 const RetainSummary *getCFCreateGetRuleSummary(const FunctionDecl *FD);
Mike Stump11289f42009-09-09 15:08:12 +0000561
Jordy Rose61c974b2012-03-18 01:26:10 +0000562 const RetainSummary *getPersistentSummary(const RetainSummary &OldSumm);
Ted Kremenek3700b762008-10-29 04:07:07 +0000563
Jordy Rose61c974b2012-03-18 01:26:10 +0000564 const RetainSummary *getPersistentSummary(RetEffect RetEff,
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000565 ArgEffect ReceiverEff = DoNothing,
566 ArgEffect DefaultEff = MayEscape) {
Jordy Rose61c974b2012-03-18 01:26:10 +0000567 RetainSummary Summ(getArgEffects(), RetEff, DefaultEff, ReceiverEff);
568 return getPersistentSummary(Summ);
569 }
570
Ted Kremenekececf9f2012-05-08 00:12:09 +0000571 const RetainSummary *getDoNothingSummary() {
572 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
573 }
574
Jordy Rose61c974b2012-03-18 01:26:10 +0000575 const RetainSummary *getDefaultSummary() {
576 return getPersistentSummary(RetEffect::MakeNoRet(),
577 DoNothing, MayEscape);
Ted Kremenek0806f912008-05-06 00:30:21 +0000578 }
Mike Stump11289f42009-09-09 15:08:12 +0000579
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000580 const RetainSummary *getPersistentStopSummary() {
Jordy Rose61c974b2012-03-18 01:26:10 +0000581 return getPersistentSummary(RetEffect::MakeNoRet(),
582 StopTracking, StopTracking);
Mike Stump11289f42009-09-09 15:08:12 +0000583 }
Ted Kremenek015c3562008-05-06 04:20:12 +0000584
Ted Kremenekea736c52008-06-23 22:21:20 +0000585 void InitializeClassMethodSummaries();
586 void InitializeMethodSummaries();
Ted Kremenekcc3d1882008-10-23 01:56:15 +0000587private:
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000588 void addNSObjectClsMethSummary(Selector S, const RetainSummary *Summ) {
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000589 ObjCClassMethodSummaries[S] = Summ;
590 }
Mike Stump11289f42009-09-09 15:08:12 +0000591
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000592 void addNSObjectMethSummary(Selector S, const RetainSummary *Summ) {
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000593 ObjCMethodSummaries[S] = Summ;
594 }
Ted Kremenek00dfe302009-03-04 23:30:42 +0000595
Ted Kremeneke8a5ba82012-02-18 21:37:48 +0000596 void addClassMethSummary(const char* Cls, const char* name,
597 const RetainSummary *Summ, bool isNullary = true) {
Ted Kremenek00dfe302009-03-04 23:30:42 +0000598 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
Ted Kremeneke8a5ba82012-02-18 21:37:48 +0000599 Selector S = isNullary ? GetNullarySelector(name, Ctx)
600 : GetUnarySelector(name, Ctx);
Ted Kremenek00dfe302009-03-04 23:30:42 +0000601 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
602 }
Mike Stump11289f42009-09-09 15:08:12 +0000603
Ted Kremenekdce78462009-02-25 02:54:57 +0000604 void addInstMethSummary(const char* Cls, const char* nullaryName,
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000605 const RetainSummary *Summ) {
Ted Kremenekdce78462009-02-25 02:54:57 +0000606 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
607 Selector S = GetNullarySelector(nullaryName, Ctx);
608 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
609 }
Mike Stump11289f42009-09-09 15:08:12 +0000610
Ted Kremenek8a5ad392009-04-24 17:50:11 +0000611 Selector generateSelector(va_list argp) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000612 SmallVector<IdentifierInfo*, 10> II;
Ted Kremenek8a5ad392009-04-24 17:50:11 +0000613
Ted Kremenek050b91c2008-08-12 18:30:56 +0000614 while (const char* s = va_arg(argp, const char*))
615 II.push_back(&Ctx.Idents.get(s));
Ted Kremenek8a5ad392009-04-24 17:50:11 +0000616
Mike Stump11289f42009-09-09 15:08:12 +0000617 return Ctx.Selectors.getSelector(II.size(), &II[0]);
Ted Kremenek8a5ad392009-04-24 17:50:11 +0000618 }
Mike Stump11289f42009-09-09 15:08:12 +0000619
Ted Kremenek8a5ad392009-04-24 17:50:11 +0000620 void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy& Summaries,
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000621 const RetainSummary * Summ, va_list argp) {
Ted Kremenek8a5ad392009-04-24 17:50:11 +0000622 Selector S = generateSelector(argp);
623 Summaries[ObjCSummaryKey(ClsII, S)] = Summ;
Ted Kremenek3b2294c2008-07-18 17:24:20 +0000624 }
Mike Stump11289f42009-09-09 15:08:12 +0000625
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000626 void addInstMethSummary(const char* Cls, const RetainSummary * Summ, ...) {
Ted Kremenek3f13f592008-08-12 18:48:50 +0000627 va_list argp;
628 va_start(argp, Summ);
Ted Kremenek8a5ad392009-04-24 17:50:11 +0000629 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Mike Stump11289f42009-09-09 15:08:12 +0000630 va_end(argp);
Ted Kremenek3f13f592008-08-12 18:48:50 +0000631 }
Mike Stump11289f42009-09-09 15:08:12 +0000632
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000633 void addClsMethSummary(const char* Cls, const RetainSummary * Summ, ...) {
Ted Kremenek8a5ad392009-04-24 17:50:11 +0000634 va_list argp;
635 va_start(argp, Summ);
636 addMethodSummary(&Ctx.Idents.get(Cls),ObjCClassMethodSummaries, Summ, argp);
637 va_end(argp);
638 }
Mike Stump11289f42009-09-09 15:08:12 +0000639
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000640 void addClsMethSummary(IdentifierInfo *II, const RetainSummary * Summ, ...) {
Ted Kremenek8a5ad392009-04-24 17:50:11 +0000641 va_list argp;
642 va_start(argp, Summ);
643 addMethodSummary(II, ObjCClassMethodSummaries, Summ, argp);
644 va_end(argp);
645 }
646
Ted Kremenek819e9b62008-03-11 06:39:11 +0000647public:
Mike Stump11289f42009-09-09 15:08:12 +0000648
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000649 RetainSummaryManager(ASTContext &ctx, bool gcenabled, bool usesARC)
Ted Kremenekab54e512008-07-01 17:21:27 +0000650 : Ctx(ctx),
John McCall31168b02011-06-15 23:02:42 +0000651 GCEnabled(gcenabled),
652 ARCEnabled(usesARC),
653 AF(BPAlloc), ScratchArgs(AF.getEmptyMap()),
654 ObjCAllocRetE(gcenabled
655 ? RetEffect::MakeGCNotOwned()
656 : (usesARC ? RetEffect::MakeARCNotOwned()
657 : RetEffect::MakeOwned(RetEffect::ObjC, true))),
658 ObjCInitRetE(gcenabled
659 ? RetEffect::MakeGCNotOwned()
660 : (usesARC ? RetEffect::MakeARCNotOwned()
Jordy Rose61c974b2012-03-18 01:26:10 +0000661 : RetEffect::MakeOwnedWhenTrackedReceiver())) {
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000662 InitializeClassMethodSummaries();
663 InitializeMethodSummaries();
664 }
Mike Stump11289f42009-09-09 15:08:12 +0000665
Jordan Roseeec15392012-07-02 19:27:43 +0000666 const RetainSummary *getSummary(const CallEvent &Call,
667 ProgramStateRef State = 0);
Mike Stump11289f42009-09-09 15:08:12 +0000668
Jordan Roseeec15392012-07-02 19:27:43 +0000669 const RetainSummary *getFunctionSummary(const FunctionDecl *FD);
670
671 const RetainSummary *getMethodSummary(Selector S, const ObjCInterfaceDecl *ID,
Jordy Rose35e71c72012-03-17 21:13:07 +0000672 const ObjCMethodDecl *MD,
673 QualType RetTy,
674 ObjCMethodSummariesTy &CachedSummaries);
675
Jordan Rose6bad4902012-07-02 19:27:56 +0000676 const RetainSummary *getInstanceMethodSummary(const ObjCMethodCall &M,
Jordan Roseeec15392012-07-02 19:27:43 +0000677 ProgramStateRef State);
Ted Kremenekbd862712010-07-01 20:16:50 +0000678
Jordan Rose6bad4902012-07-02 19:27:56 +0000679 const RetainSummary *getClassMethodSummary(const ObjCMethodCall &M) {
Jordan Roseeec15392012-07-02 19:27:43 +0000680 assert(!M.isInstanceMessage());
681 const ObjCInterfaceDecl *Class = M.getReceiverInterface();
Mike Stump11289f42009-09-09 15:08:12 +0000682
Jordan Roseeec15392012-07-02 19:27:43 +0000683 return getMethodSummary(M.getSelector(), Class, M.getDecl(),
684 M.getResultType(), ObjCClassMethodSummaries);
Ted Kremenek7686ffa2009-04-29 00:42:39 +0000685 }
Ted Kremenek99fe1692009-04-29 17:17:48 +0000686
687 /// getMethodSummary - This version of getMethodSummary is used to query
688 /// the summary for the current method being analyzed.
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000689 const RetainSummary *getMethodSummary(const ObjCMethodDecl *MD) {
Ted Kremenek223a7d52009-04-29 23:03:22 +0000690 const ObjCInterfaceDecl *ID = MD->getClassInterface();
Ted Kremenekb2a143f2009-04-30 05:41:14 +0000691 Selector S = MD->getSelector();
Ted Kremenek99fe1692009-04-29 17:17:48 +0000692 QualType ResultTy = MD->getResultType();
Mike Stump11289f42009-09-09 15:08:12 +0000693
Jordy Rose35e71c72012-03-17 21:13:07 +0000694 ObjCMethodSummariesTy *CachedSummaries;
Ted Kremenek99fe1692009-04-29 17:17:48 +0000695 if (MD->isInstanceMethod())
Jordy Rose35e71c72012-03-17 21:13:07 +0000696 CachedSummaries = &ObjCMethodSummaries;
Ted Kremenek99fe1692009-04-29 17:17:48 +0000697 else
Jordy Rose35e71c72012-03-17 21:13:07 +0000698 CachedSummaries = &ObjCClassMethodSummaries;
699
Jordan Roseeec15392012-07-02 19:27:43 +0000700 return getMethodSummary(S, ID, MD, ResultTy, *CachedSummaries);
Ted Kremenek99fe1692009-04-29 17:17:48 +0000701 }
Mike Stump11289f42009-09-09 15:08:12 +0000702
Jordy Rose35e71c72012-03-17 21:13:07 +0000703 const RetainSummary *getStandardMethodSummary(const ObjCMethodDecl *MD,
Jordan Roseeec15392012-07-02 19:27:43 +0000704 Selector S, QualType RetTy);
Ted Kremenek223a7d52009-04-29 23:03:22 +0000705
Jordan Rose39032472013-04-04 22:31:48 +0000706 /// Determine if there is a special return effect for this function or method.
707 Optional<RetEffect> getRetEffectFromAnnotations(QualType RetTy,
708 const Decl *D);
709
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000710 void updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenekc2de7272009-05-09 02:58:13 +0000711 const ObjCMethodDecl *MD);
712
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000713 void updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenekc2de7272009-05-09 02:58:13 +0000714 const FunctionDecl *FD);
715
Jordan Roseeec15392012-07-02 19:27:43 +0000716 void updateSummaryForCall(const RetainSummary *&Summ,
717 const CallEvent &Call);
718
Ted Kremenek00daccd2008-05-05 22:11:16 +0000719 bool isGCEnabled() const { return GCEnabled; }
Mike Stump11289f42009-09-09 15:08:12 +0000720
John McCall31168b02011-06-15 23:02:42 +0000721 bool isARCEnabled() const { return ARCEnabled; }
722
723 bool isARCorGCEnabled() const { return GCEnabled || ARCEnabled; }
Jordan Roseeec15392012-07-02 19:27:43 +0000724
725 RetEffect getObjAllocRetEffect() const { return ObjCAllocRetE; }
726
727 friend class RetainSummaryTemplate;
Ted Kremenek819e9b62008-03-11 06:39:11 +0000728};
Mike Stump11289f42009-09-09 15:08:12 +0000729
Jordy Rose14de7c52011-08-24 09:02:37 +0000730// Used to avoid allocating long-term (BPAlloc'd) memory for default retain
731// summaries. If a function or method looks like it has a default summary, but
732// it has annotations, the annotations are added to the stack-based template
733// and then copied into managed memory.
734class RetainSummaryTemplate {
735 RetainSummaryManager &Manager;
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000736 const RetainSummary *&RealSummary;
Jordy Rose14de7c52011-08-24 09:02:37 +0000737 RetainSummary ScratchSummary;
738 bool Accessed;
739public:
Jordan Roseeec15392012-07-02 19:27:43 +0000740 RetainSummaryTemplate(const RetainSummary *&real, RetainSummaryManager &mgr)
741 : Manager(mgr), RealSummary(real), ScratchSummary(*real), Accessed(false) {}
Jordy Rose14de7c52011-08-24 09:02:37 +0000742
743 ~RetainSummaryTemplate() {
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000744 if (Accessed)
Jordy Rose61c974b2012-03-18 01:26:10 +0000745 RealSummary = Manager.getPersistentSummary(ScratchSummary);
Jordy Rose14de7c52011-08-24 09:02:37 +0000746 }
747
748 RetainSummary &operator*() {
749 Accessed = true;
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000750 return ScratchSummary;
Jordy Rose14de7c52011-08-24 09:02:37 +0000751 }
752
753 RetainSummary *operator->() {
754 Accessed = true;
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000755 return &ScratchSummary;
Jordy Rose14de7c52011-08-24 09:02:37 +0000756 }
757};
758
Ted Kremenek819e9b62008-03-11 06:39:11 +0000759} // end anonymous namespace
760
761//===----------------------------------------------------------------------===//
762// Implementation of checker data structures.
763//===----------------------------------------------------------------------===//
764
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000765ArgEffects RetainSummaryManager::getArgEffects() {
766 ArgEffects AE = ScratchArgs;
Ted Kremenekb3b56c62010-11-24 00:54:37 +0000767 ScratchArgs = AF.getEmptyMap();
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000768 return AE;
Ted Kremenek68d73d12008-03-12 01:21:45 +0000769}
770
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000771const RetainSummary *
Jordy Rose61c974b2012-03-18 01:26:10 +0000772RetainSummaryManager::getPersistentSummary(const RetainSummary &OldSumm) {
773 // Unique "simple" summaries -- those without ArgEffects.
774 if (OldSumm.isSimple()) {
775 llvm::FoldingSetNodeID ID;
776 OldSumm.Profile(ID);
777
778 void *Pos;
779 CachedSummaryNode *N = SimpleSummaries.FindNodeOrInsertPos(ID, Pos);
780
781 if (!N) {
782 N = (CachedSummaryNode *) BPAlloc.Allocate<CachedSummaryNode>();
783 new (N) CachedSummaryNode(OldSumm);
784 SimpleSummaries.InsertNode(N, Pos);
785 }
786
787 return &N->getValue();
788 }
789
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000790 RetainSummary *Summ = (RetainSummary *) BPAlloc.Allocate<RetainSummary>();
Jordy Rose61c974b2012-03-18 01:26:10 +0000791 new (Summ) RetainSummary(OldSumm);
Ted Kremenek68d73d12008-03-12 01:21:45 +0000792 return Summ;
793}
794
Ted Kremenek00daccd2008-05-05 22:11:16 +0000795//===----------------------------------------------------------------------===//
796// Summary creation for functions (largely uses of Core Foundation).
797//===----------------------------------------------------------------------===//
Ted Kremenek68d73d12008-03-12 01:21:45 +0000798
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000799static bool isRetain(const FunctionDecl *FD, StringRef FName) {
Benjamin Kramereaabbd82010-02-08 18:38:55 +0000800 return FName.endswith("Retain");
Ted Kremenek7e904222009-01-12 21:45:02 +0000801}
802
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000803static bool isRelease(const FunctionDecl *FD, StringRef FName) {
Benjamin Kramereaabbd82010-02-08 18:38:55 +0000804 return FName.endswith("Release");
Ted Kremenek7e904222009-01-12 21:45:02 +0000805}
806
Jordan Rose77411322013-10-07 17:16:52 +0000807static bool isAutorelease(const FunctionDecl *FD, StringRef FName) {
808 return FName.endswith("Autorelease");
809}
810
Jordy Rose898a1482011-08-21 21:58:18 +0000811static bool isMakeCollectable(const FunctionDecl *FD, StringRef FName) {
812 // FIXME: Remove FunctionDecl parameter.
813 // FIXME: Is it really okay if MakeCollectable isn't a suffix?
814 return FName.find("MakeCollectable") != StringRef::npos;
815}
816
Anna Zaks25612732012-08-29 23:23:43 +0000817static ArgEffect getStopTrackingHardEquivalent(ArgEffect E) {
Jordan Roseeec15392012-07-02 19:27:43 +0000818 switch (E) {
819 case DoNothing:
820 case Autorelease:
Benjamin Kramer2501f142013-10-20 11:47:15 +0000821 case DecRefBridgedTransferred:
Jordan Roseeec15392012-07-02 19:27:43 +0000822 case IncRef:
823 case IncRefMsg:
824 case MakeCollectable:
825 case MayEscape:
Jordan Roseeec15392012-07-02 19:27:43 +0000826 case StopTracking:
Anna Zaks25612732012-08-29 23:23:43 +0000827 case StopTrackingHard:
828 return StopTrackingHard;
Jordan Roseeec15392012-07-02 19:27:43 +0000829 case DecRef:
Anna Zaks25612732012-08-29 23:23:43 +0000830 case DecRefAndStopTrackingHard:
831 return DecRefAndStopTrackingHard;
Jordan Roseeec15392012-07-02 19:27:43 +0000832 case DecRefMsg:
Anna Zaks25612732012-08-29 23:23:43 +0000833 case DecRefMsgAndStopTrackingHard:
834 return DecRefMsgAndStopTrackingHard;
Jordan Roseeec15392012-07-02 19:27:43 +0000835 case Dealloc:
836 return Dealloc;
837 }
838
839 llvm_unreachable("Unknown ArgEffect kind");
840}
841
842void RetainSummaryManager::updateSummaryForCall(const RetainSummary *&S,
843 const CallEvent &Call) {
844 if (Call.hasNonZeroCallbackArg()) {
Anna Zaks25612732012-08-29 23:23:43 +0000845 ArgEffect RecEffect =
846 getStopTrackingHardEquivalent(S->getReceiverEffect());
847 ArgEffect DefEffect =
848 getStopTrackingHardEquivalent(S->getDefaultArgEffect());
Jordan Roseeec15392012-07-02 19:27:43 +0000849
850 ArgEffects CustomArgEffects = S->getArgEffects();
851 for (ArgEffects::iterator I = CustomArgEffects.begin(),
852 E = CustomArgEffects.end();
853 I != E; ++I) {
Anna Zaks25612732012-08-29 23:23:43 +0000854 ArgEffect Translated = getStopTrackingHardEquivalent(I->second);
Jordan Roseeec15392012-07-02 19:27:43 +0000855 if (Translated != DefEffect)
856 ScratchArgs = AF.add(ScratchArgs, I->first, Translated);
857 }
858
Anna Zaks25612732012-08-29 23:23:43 +0000859 RetEffect RE = RetEffect::MakeNoRetHard();
Jordan Roseeec15392012-07-02 19:27:43 +0000860
861 // Special cases where the callback argument CANNOT free the return value.
862 // This can generally only happen if we know that the callback will only be
863 // called when the return value is already being deallocated.
864 if (const FunctionCall *FC = dyn_cast<FunctionCall>(&Call)) {
Jordan Roseccf192e2012-09-01 17:39:13 +0000865 if (IdentifierInfo *Name = FC->getDecl()->getIdentifier()) {
866 // When the CGBitmapContext is deallocated, the callback here will free
867 // the associated data buffer.
Jordan Rosed65f1c82012-08-31 18:19:18 +0000868 if (Name->isStr("CGBitmapContextCreateWithData"))
869 RE = S->getRetEffect();
Jordan Roseccf192e2012-09-01 17:39:13 +0000870 }
Jordan Roseeec15392012-07-02 19:27:43 +0000871 }
872
873 S = getPersistentSummary(RE, RecEffect, DefEffect);
874 }
Anna Zaks3d5d3d32012-08-24 00:06:12 +0000875
876 // Special case '[super init];' and '[self init];'
877 //
878 // Even though calling '[super init]' without assigning the result to self
879 // and checking if the parent returns 'nil' is a bad pattern, it is common.
880 // Additionally, our Self Init checker already warns about it. To avoid
881 // overwhelming the user with messages from both checkers, we model the case
882 // of '[super init]' in cases when it is not consumed by another expression
883 // as if the call preserves the value of 'self'; essentially, assuming it can
884 // never fail and return 'nil'.
885 // Note, we don't want to just stop tracking the value since we want the
886 // RetainCount checker to report leaks and use-after-free if SelfInit checker
887 // is turned off.
888 if (const ObjCMethodCall *MC = dyn_cast<ObjCMethodCall>(&Call)) {
889 if (MC->getMethodFamily() == OMF_init && MC->isReceiverSelfOrSuper()) {
890
891 // Check if the message is not consumed, we know it will not be used in
892 // an assignment, ex: "self = [super init]".
893 const Expr *ME = MC->getOriginExpr();
894 const LocationContext *LCtx = MC->getLocationContext();
895 ParentMap &PM = LCtx->getAnalysisDeclContext()->getParentMap();
896 if (!PM.isConsumedExpr(ME)) {
897 RetainSummaryTemplate ModifiableSummaryTemplate(S, *this);
898 ModifiableSummaryTemplate->setReceiverEffect(DoNothing);
899 ModifiableSummaryTemplate->setRetEffect(RetEffect::MakeNoRet());
900 }
901 }
902
903 }
Jordan Roseeec15392012-07-02 19:27:43 +0000904}
905
Anna Zaksf4c5ea52012-05-04 22:18:39 +0000906const RetainSummary *
Jordan Roseeec15392012-07-02 19:27:43 +0000907RetainSummaryManager::getSummary(const CallEvent &Call,
908 ProgramStateRef State) {
909 const RetainSummary *Summ;
910 switch (Call.getKind()) {
911 case CE_Function:
912 Summ = getFunctionSummary(cast<FunctionCall>(Call).getDecl());
913 break;
914 case CE_CXXMember:
Jordan Rose017591a2012-07-03 22:55:57 +0000915 case CE_CXXMemberOperator:
Jordan Roseeec15392012-07-02 19:27:43 +0000916 case CE_Block:
917 case CE_CXXConstructor:
Jordan Rose4ee71b82012-07-10 22:07:47 +0000918 case CE_CXXDestructor:
Jordan Rosea4ee0642012-07-02 22:21:47 +0000919 case CE_CXXAllocator:
Jordan Roseeec15392012-07-02 19:27:43 +0000920 // FIXME: These calls are currently unsupported.
921 return getPersistentStopSummary();
Jordan Rose627b0462012-07-18 21:59:51 +0000922 case CE_ObjCMessage: {
Jordan Rose6bad4902012-07-02 19:27:56 +0000923 const ObjCMethodCall &Msg = cast<ObjCMethodCall>(Call);
Jordan Roseeec15392012-07-02 19:27:43 +0000924 if (Msg.isInstanceMessage())
925 Summ = getInstanceMethodSummary(Msg, State);
926 else
927 Summ = getClassMethodSummary(Msg);
928 break;
929 }
930 }
931
932 updateSummaryForCall(Summ, Call);
933
934 assert(Summ && "Unknown call type?");
935 return Summ;
936}
937
938const RetainSummary *
939RetainSummaryManager::getFunctionSummary(const FunctionDecl *FD) {
940 // If we don't know what function we're calling, use our default summary.
941 if (!FD)
942 return getDefaultSummary();
943
Ted Kremenekf7141592008-04-24 17:22:33 +0000944 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremenek00daccd2008-05-05 22:11:16 +0000945 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremenek00daccd2008-05-05 22:11:16 +0000946 if (I != FuncSummaries.end())
Ted Kremenekf7141592008-04-24 17:22:33 +0000947 return I->second;
948
Ted Kremenekdf76e6d2009-05-04 15:34:07 +0000949 // No summary? Generate one.
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000950 const RetainSummary *S = 0;
Jordan Rose1c715602012-08-06 21:28:02 +0000951 bool AllowAnnotations = true;
Mike Stump11289f42009-09-09 15:08:12 +0000952
Ted Kremenekfa89e2f2008-07-15 16:50:12 +0000953 do {
Ted Kremenek7e904222009-01-12 21:45:02 +0000954 // We generate "stop" summaries for implicitly defined functions.
955 if (FD->isImplicit()) {
956 S = getPersistentStopSummary();
957 break;
Ted Kremenekfa89e2f2008-07-15 16:50:12 +0000958 }
Mike Stump11289f42009-09-09 15:08:12 +0000959
John McCall9dd450b2009-09-21 23:43:11 +0000960 // [PR 3337] Use 'getAs<FunctionType>' to strip away any typedefs on the
Ted Kremenek86afde32009-01-16 18:40:33 +0000961 // function's type.
John McCall9dd450b2009-09-21 23:43:11 +0000962 const FunctionType* FT = FD->getType()->getAs<FunctionType>();
Ted Kremenek9bcc2642009-12-16 06:06:43 +0000963 const IdentifierInfo *II = FD->getIdentifier();
964 if (!II)
965 break;
Benjamin Kramereaabbd82010-02-08 18:38:55 +0000966
967 StringRef FName = II->getName();
Mike Stump11289f42009-09-09 15:08:12 +0000968
Ted Kremenek5f968932009-03-05 22:11:14 +0000969 // Strip away preceding '_'. Doing this here will effect all the checks
970 // down below.
Benjamin Kramereaabbd82010-02-08 18:38:55 +0000971 FName = FName.substr(FName.find_first_not_of('_'));
Mike Stump11289f42009-09-09 15:08:12 +0000972
Ted Kremenek7e904222009-01-12 21:45:02 +0000973 // Inspect the result type.
974 QualType RetTy = FT->getResultType();
Mike Stump11289f42009-09-09 15:08:12 +0000975
Ted Kremenek7e904222009-01-12 21:45:02 +0000976 // FIXME: This should all be refactored into a chain of "summary lookup"
977 // filters.
Ted Kremenekb4ec3fc2009-10-14 00:27:24 +0000978 assert(ScratchArgs.isEmpty());
Ted Kremenek3092e9c2009-06-15 20:36:07 +0000979
Ted Kremenek01d152f2012-04-26 04:32:23 +0000980 if (FName == "pthread_create" || FName == "pthread_setspecific") {
981 // Part of: <rdar://problem/7299394> and <rdar://problem/11282706>.
982 // This will be addressed better with IPA.
Benjamin Kramereaabbd82010-02-08 18:38:55 +0000983 S = getPersistentStopSummary();
984 } else if (FName == "NSMakeCollectable") {
985 // Handle: id NSMakeCollectable(CFTypeRef)
986 S = (RetTy->isObjCIdType())
987 ? getUnarySummary(FT, cfmakecollectable)
988 : getPersistentStopSummary();
Jordan Rose1c715602012-08-06 21:28:02 +0000989 // The headers on OS X 10.8 use cf_consumed/ns_returns_retained,
990 // but we can fully model NSMakeCollectable ourselves.
991 AllowAnnotations = false;
Ted Kremenekc008db92012-09-06 23:47:02 +0000992 } else if (FName == "CFPlugInInstanceCreate") {
993 S = getPersistentSummary(RetEffect::MakeNoRet());
Benjamin Kramereaabbd82010-02-08 18:38:55 +0000994 } else if (FName == "IOBSDNameMatching" ||
995 FName == "IOServiceMatching" ||
996 FName == "IOServiceNameMatching" ||
Ted Kremenek555560c2012-05-01 05:28:27 +0000997 FName == "IORegistryEntrySearchCFProperty" ||
Benjamin Kramereaabbd82010-02-08 18:38:55 +0000998 FName == "IORegistryEntryIDMatching" ||
999 FName == "IOOpenFirmwarePathMatching") {
1000 // Part of <rdar://problem/6961230>. (IOKit)
1001 // This should be addressed using a API table.
1002 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1003 DoNothing, DoNothing);
1004 } else if (FName == "IOServiceGetMatchingService" ||
1005 FName == "IOServiceGetMatchingServices") {
1006 // FIXES: <rdar://problem/6326900>
1007 // This should be addressed using a API table. This strcmp is also
1008 // a little gross, but there is no need to super optimize here.
Ted Kremenekb3b56c62010-11-24 00:54:37 +00001009 ScratchArgs = AF.add(ScratchArgs, 1, DecRef);
Benjamin Kramereaabbd82010-02-08 18:38:55 +00001010 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1011 } else if (FName == "IOServiceAddNotification" ||
1012 FName == "IOServiceAddMatchingNotification") {
1013 // Part of <rdar://problem/6961230>. (IOKit)
1014 // This should be addressed using a API table.
Ted Kremenekb3b56c62010-11-24 00:54:37 +00001015 ScratchArgs = AF.add(ScratchArgs, 2, DecRef);
Benjamin Kramereaabbd82010-02-08 18:38:55 +00001016 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1017 } else if (FName == "CVPixelBufferCreateWithBytes") {
1018 // FIXES: <rdar://problem/7283567>
1019 // Eventually this can be improved by recognizing that the pixel
1020 // buffer passed to CVPixelBufferCreateWithBytes is released via
1021 // a callback and doing full IPA to make sure this is done correctly.
1022 // FIXME: This function has an out parameter that returns an
1023 // allocated object.
Ted Kremenekb3b56c62010-11-24 00:54:37 +00001024 ScratchArgs = AF.add(ScratchArgs, 7, StopTracking);
Benjamin Kramereaabbd82010-02-08 18:38:55 +00001025 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1026 } else if (FName == "CGBitmapContextCreateWithData") {
1027 // FIXES: <rdar://problem/7358899>
1028 // Eventually this can be improved by recognizing that 'releaseInfo'
1029 // passed to CGBitmapContextCreateWithData is released via
1030 // a callback and doing full IPA to make sure this is done correctly.
Ted Kremenekb3b56c62010-11-24 00:54:37 +00001031 ScratchArgs = AF.add(ScratchArgs, 8, StopTracking);
Benjamin Kramereaabbd82010-02-08 18:38:55 +00001032 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1033 DoNothing, DoNothing);
1034 } else if (FName == "CVPixelBufferCreateWithPlanarBytes") {
1035 // FIXES: <rdar://problem/7283567>
1036 // Eventually this can be improved by recognizing that the pixel
1037 // buffer passed to CVPixelBufferCreateWithPlanarBytes is released
1038 // via a callback and doing full IPA to make sure this is done
1039 // correctly.
Ted Kremenekb3b56c62010-11-24 00:54:37 +00001040 ScratchArgs = AF.add(ScratchArgs, 12, StopTracking);
Benjamin Kramereaabbd82010-02-08 18:38:55 +00001041 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Jordan Roseb1479182013-05-02 01:51:40 +00001042 } else if (FName == "dispatch_set_context" ||
1043 FName == "xpc_connection_set_context") {
Ted Kremenek40c13432012-03-22 06:29:41 +00001044 // <rdar://problem/11059275> - The analyzer currently doesn't have
1045 // a good way to reason about the finalizer function for libdispatch.
1046 // If we pass a context object that is memory managed, stop tracking it.
Jordan Roseb1479182013-05-02 01:51:40 +00001047 // <rdar://problem/13783514> - Same problem, but for XPC.
Ted Kremenek40c13432012-03-22 06:29:41 +00001048 // FIXME: this hack should possibly go away once we can handle
Jordan Roseb1479182013-05-02 01:51:40 +00001049 // libdispatch and XPC finalizers.
Ted Kremenek40c13432012-03-22 06:29:41 +00001050 ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
1051 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenekececf9f2012-05-08 00:12:09 +00001052 } else if (FName.startswith("NSLog")) {
1053 S = getDoNothingSummary();
Anna Zaks90ab9bf2012-03-30 05:48:16 +00001054 } else if (FName.startswith("NS") &&
1055 (FName.find("Insert") != StringRef::npos)) {
1056 // Whitelist NSXXInsertXX, for example NSMapInsertIfAbsent, since they can
1057 // be deallocated by NSMapRemove. (radar://11152419)
1058 ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
1059 ScratchArgs = AF.add(ScratchArgs, 2, StopTracking);
1060 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenekea675cf2009-06-11 18:17:24 +00001061 }
Mike Stump11289f42009-09-09 15:08:12 +00001062
Ted Kremenekea675cf2009-06-11 18:17:24 +00001063 // Did we get a summary?
1064 if (S)
1065 break;
Ted Kremenek211094d2009-03-17 22:43:44 +00001066
Jordan Rose85707b22013-03-04 23:21:32 +00001067 if (RetTy->isPointerType()) {
Ted Kremenek7e904222009-01-12 21:45:02 +00001068 // For CoreFoundation ('CF') types.
Ted Kremeneke9918352010-01-27 18:00:17 +00001069 if (cocoa::isRefType(RetTy, "CF", FName)) {
Jordan Rose77411322013-10-07 17:16:52 +00001070 if (isRetain(FD, FName)) {
Ted Kremenek7e904222009-01-12 21:45:02 +00001071 S = getUnarySummary(FT, cfretain);
Jordan Rose77411322013-10-07 17:16:52 +00001072 } else if (isAutorelease(FD, FName)) {
1073 S = getUnarySummary(FT, cfautorelease);
1074 // The headers use cf_consumed, but we can fully model CFAutorelease
1075 // ourselves.
1076 AllowAnnotations = false;
1077 } else if (isMakeCollectable(FD, FName)) {
Ted Kremenek7e904222009-01-12 21:45:02 +00001078 S = getUnarySummary(FT, cfmakecollectable);
Jordan Rose77411322013-10-07 17:16:52 +00001079 AllowAnnotations = false;
1080 } else {
John McCall525f0552011-10-01 00:48:56 +00001081 S = getCFCreateGetRuleSummary(FD);
Jordan Rose77411322013-10-07 17:16:52 +00001082 }
Ted Kremenek7e904222009-01-12 21:45:02 +00001083
1084 break;
1085 }
1086
1087 // For CoreGraphics ('CG') types.
Ted Kremeneke9918352010-01-27 18:00:17 +00001088 if (cocoa::isRefType(RetTy, "CG", FName)) {
Ted Kremenek7e904222009-01-12 21:45:02 +00001089 if (isRetain(FD, FName))
1090 S = getUnarySummary(FT, cfretain);
1091 else
John McCall525f0552011-10-01 00:48:56 +00001092 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek7e904222009-01-12 21:45:02 +00001093
1094 break;
1095 }
1096
1097 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
Ted Kremeneke9918352010-01-27 18:00:17 +00001098 if (cocoa::isRefType(RetTy, "DADisk") ||
1099 cocoa::isRefType(RetTy, "DADissenter") ||
1100 cocoa::isRefType(RetTy, "DASessionRef")) {
John McCall525f0552011-10-01 00:48:56 +00001101 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek7e904222009-01-12 21:45:02 +00001102 break;
1103 }
Mike Stump11289f42009-09-09 15:08:12 +00001104
Aaron Ballman9ead1242013-12-19 02:39:40 +00001105 if (FD->hasAttr<CFAuditedTransferAttr>()) {
Jordan Rose85707b22013-03-04 23:21:32 +00001106 S = getCFCreateGetRuleSummary(FD);
1107 break;
1108 }
1109
Ted Kremenek7e904222009-01-12 21:45:02 +00001110 break;
1111 }
1112
1113 // Check for release functions, the only kind of functions that we care
1114 // about that don't return a pointer type.
1115 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
Ted Kremenekac5ab792010-02-08 16:45:01 +00001116 // Test for 'CGCF'.
Benjamin Kramereaabbd82010-02-08 18:38:55 +00001117 FName = FName.substr(FName.startswith("CGCF") ? 4 : 2);
Ted Kremenekac5ab792010-02-08 16:45:01 +00001118
Ted Kremenek5f968932009-03-05 22:11:14 +00001119 if (isRelease(FD, FName))
Ted Kremenek7e904222009-01-12 21:45:02 +00001120 S = getUnarySummary(FT, cfrelease);
1121 else {
Ted Kremenek7d79a5f2009-05-03 05:20:50 +00001122 assert (ScratchArgs.isEmpty());
Ted Kremeneked90de42009-01-29 22:45:13 +00001123 // Remaining CoreFoundation and CoreGraphics functions.
1124 // We use to assume that they all strictly followed the ownership idiom
1125 // and that ownership cannot be transferred. While this is technically
1126 // correct, many methods allow a tracked object to escape. For example:
1127 //
Mike Stump11289f42009-09-09 15:08:12 +00001128 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
Ted Kremeneked90de42009-01-29 22:45:13 +00001129 // CFDictionaryAddValue(y, key, x);
Mike Stump11289f42009-09-09 15:08:12 +00001130 // CFRelease(x);
Ted Kremeneked90de42009-01-29 22:45:13 +00001131 // ... it is okay to use 'x' since 'y' has a reference to it
1132 //
1133 // We handle this and similar cases with the follow heuristic. If the
Ted Kremenekd982f002009-08-20 00:57:22 +00001134 // function name contains "InsertValue", "SetValue", "AddValue",
1135 // "AppendValue", or "SetAttribute", then we assume that arguments may
1136 // "escape." This means that something else holds on to the object,
1137 // allowing it be used even after its local retain count drops to 0.
Benjamin Kramer0129bd72010-01-11 19:46:28 +00001138 ArgEffect E = (StrInStrNoCase(FName, "InsertValue") != StringRef::npos||
1139 StrInStrNoCase(FName, "AddValue") != StringRef::npos ||
1140 StrInStrNoCase(FName, "SetValue") != StringRef::npos ||
1141 StrInStrNoCase(FName, "AppendValue") != StringRef::npos||
Benjamin Kramer37808312010-01-11 20:15:06 +00001142 StrInStrNoCase(FName, "SetAttribute") != StringRef::npos)
Ted Kremeneked90de42009-01-29 22:45:13 +00001143 ? MayEscape : DoNothing;
Mike Stump11289f42009-09-09 15:08:12 +00001144
Ted Kremeneked90de42009-01-29 22:45:13 +00001145 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek7e904222009-01-12 21:45:02 +00001146 }
1147 }
Ted Kremenekfa89e2f2008-07-15 16:50:12 +00001148 }
1149 while (0);
Mike Stump11289f42009-09-09 15:08:12 +00001150
Jordan Roseeec15392012-07-02 19:27:43 +00001151 // If we got all the way here without any luck, use a default summary.
1152 if (!S)
1153 S = getDefaultSummary();
1154
Ted Kremenekc2de7272009-05-09 02:58:13 +00001155 // Annotations override defaults.
Jordan Rose1c715602012-08-06 21:28:02 +00001156 if (AllowAnnotations)
1157 updateSummaryFromAnnotations(S, FD);
Mike Stump11289f42009-09-09 15:08:12 +00001158
Ted Kremenek00daccd2008-05-05 22:11:16 +00001159 FuncSummaries[FD] = S;
Mike Stump11289f42009-09-09 15:08:12 +00001160 return S;
Ted Kremenekea6507f2008-03-06 00:08:09 +00001161}
1162
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001163const RetainSummary *
John McCall525f0552011-10-01 00:48:56 +00001164RetainSummaryManager::getCFCreateGetRuleSummary(const FunctionDecl *FD) {
1165 if (coreFoundation::followsCreateRule(FD))
Ted Kremenek875db812008-05-05 16:51:50 +00001166 return getCFSummaryCreateRule(FD);
Mike Stump11289f42009-09-09 15:08:12 +00001167
Ted Kremenek8e2c9b02011-05-25 06:19:45 +00001168 return getCFSummaryGetRule(FD);
Ted Kremenek875db812008-05-05 16:51:50 +00001169}
1170
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001171const RetainSummary *
Ted Kremenek82157a12009-02-23 16:51:39 +00001172RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1173 UnaryFuncKind func) {
1174
Ted Kremenek7e904222009-01-12 21:45:02 +00001175 // Sanity check that this is *really* a unary function. This can
1176 // happen if people do weird things.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001177 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
Ted Kremenek7e904222009-01-12 21:45:02 +00001178 if (!FTP || FTP->getNumArgs() != 1)
1179 return getPersistentStopSummary();
Mike Stump11289f42009-09-09 15:08:12 +00001180
Ted Kremenek7d79a5f2009-05-03 05:20:50 +00001181 assert (ScratchArgs.isEmpty());
Mike Stump11289f42009-09-09 15:08:12 +00001182
Jordy Rose898a1482011-08-21 21:58:18 +00001183 ArgEffect Effect;
Ted Kremenek4b7ca772008-04-29 05:33:51 +00001184 switch (func) {
Jordan Rose77411322013-10-07 17:16:52 +00001185 case cfretain: Effect = IncRef; break;
1186 case cfrelease: Effect = DecRef; break;
1187 case cfautorelease: Effect = Autorelease; break;
1188 case cfmakecollectable: Effect = MakeCollectable; break;
Ted Kremenek4b772092008-04-10 23:44:06 +00001189 }
Jordy Rose898a1482011-08-21 21:58:18 +00001190
1191 ScratchArgs = AF.add(ScratchArgs, 0, Effect);
1192 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenek68d73d12008-03-12 01:21:45 +00001193}
1194
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001195const RetainSummary *
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001196RetainSummaryManager::getCFSummaryCreateRule(const FunctionDecl *FD) {
Ted Kremenek7d79a5f2009-05-03 05:20:50 +00001197 assert (ScratchArgs.isEmpty());
Mike Stump11289f42009-09-09 15:08:12 +00001198
Ted Kremenekaeb115f2009-01-28 05:56:51 +00001199 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenek68d73d12008-03-12 01:21:45 +00001200}
1201
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001202const RetainSummary *
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001203RetainSummaryManager::getCFSummaryGetRule(const FunctionDecl *FD) {
Mike Stump11289f42009-09-09 15:08:12 +00001204 assert (ScratchArgs.isEmpty());
Ted Kremenekaeb115f2009-01-28 05:56:51 +00001205 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1206 DoNothing, DoNothing);
Ted Kremenek68d73d12008-03-12 01:21:45 +00001207}
1208
Ted Kremenek819e9b62008-03-11 06:39:11 +00001209//===----------------------------------------------------------------------===//
Ted Kremenek00daccd2008-05-05 22:11:16 +00001210// Summary creation for Selectors.
1211//===----------------------------------------------------------------------===//
1212
Jordan Rose39032472013-04-04 22:31:48 +00001213Optional<RetEffect>
1214RetainSummaryManager::getRetEffectFromAnnotations(QualType RetTy,
1215 const Decl *D) {
1216 if (cocoa::isCocoaObjectRef(RetTy)) {
Aaron Ballman9ead1242013-12-19 02:39:40 +00001217 if (D->hasAttr<NSReturnsRetainedAttr>())
Jordan Rose39032472013-04-04 22:31:48 +00001218 return ObjCAllocRetE;
1219
Aaron Ballman9ead1242013-12-19 02:39:40 +00001220 if (D->hasAttr<NSReturnsNotRetainedAttr>() ||
1221 D->hasAttr<NSReturnsAutoreleasedAttr>())
Jordan Rose39032472013-04-04 22:31:48 +00001222 return RetEffect::MakeNotOwned(RetEffect::ObjC);
1223
1224 } else if (!RetTy->isPointerType()) {
1225 return None;
1226 }
1227
Aaron Ballman9ead1242013-12-19 02:39:40 +00001228 if (D->hasAttr<CFReturnsRetainedAttr>())
Jordan Rose39032472013-04-04 22:31:48 +00001229 return RetEffect::MakeOwned(RetEffect::CF, true);
1230
Aaron Ballman9ead1242013-12-19 02:39:40 +00001231 if (D->hasAttr<CFReturnsNotRetainedAttr>())
Jordan Rose39032472013-04-04 22:31:48 +00001232 return RetEffect::MakeNotOwned(RetEffect::CF);
1233
1234 return None;
1235}
1236
Ted Kremenekc2de7272009-05-09 02:58:13 +00001237void
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001238RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenekc2de7272009-05-09 02:58:13 +00001239 const FunctionDecl *FD) {
1240 if (!FD)
1241 return;
1242
Jordan Roseeec15392012-07-02 19:27:43 +00001243 assert(Summ && "Must have a summary to add annotations to.");
1244 RetainSummaryTemplate Template(Summ, *this);
Jordy Rose212e4592011-08-23 04:27:15 +00001245
Ted Kremenekafe348e2011-01-27 18:43:03 +00001246 // Effects on the parameters.
1247 unsigned parm_idx = 0;
1248 for (FunctionDecl::param_const_iterator pi = FD->param_begin(),
John McCall3337ca52011-04-06 09:02:12 +00001249 pe = FD->param_end(); pi != pe; ++pi, ++parm_idx) {
Ted Kremenekafe348e2011-01-27 18:43:03 +00001250 const ParmVarDecl *pd = *pi;
Aaron Ballman9ead1242013-12-19 02:39:40 +00001251 if (pd->hasAttr<NSConsumedAttr>())
Jordan Rose39032472013-04-04 22:31:48 +00001252 Template->addArg(AF, parm_idx, DecRefMsg);
Aaron Ballman9ead1242013-12-19 02:39:40 +00001253 else if (pd->hasAttr<CFConsumedAttr>())
Jordy Rose14de7c52011-08-24 09:02:37 +00001254 Template->addArg(AF, parm_idx, DecRef);
Ted Kremenekafe348e2011-01-27 18:43:03 +00001255 }
1256
Ted Kremenekea675cf2009-06-11 18:17:24 +00001257 QualType RetTy = FD->getResultType();
Jordan Rose39032472013-04-04 22:31:48 +00001258 if (Optional<RetEffect> RetE = getRetEffectFromAnnotations(RetTy, FD))
1259 Template->setRetEffect(*RetE);
Ted Kremenekc2de7272009-05-09 02:58:13 +00001260}
1261
1262void
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001263RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
1264 const ObjCMethodDecl *MD) {
Ted Kremenekc2de7272009-05-09 02:58:13 +00001265 if (!MD)
1266 return;
1267
Jordan Roseeec15392012-07-02 19:27:43 +00001268 assert(Summ && "Must have a valid summary to add annotations to");
1269 RetainSummaryTemplate Template(Summ, *this);
Mike Stump11289f42009-09-09 15:08:12 +00001270
Ted Kremenek0e898382011-01-27 06:54:14 +00001271 // Effects on the receiver.
Aaron Ballman9ead1242013-12-19 02:39:40 +00001272 if (MD->hasAttr<NSConsumesSelfAttr>())
Jordan Rose39032472013-04-04 22:31:48 +00001273 Template->setReceiverEffect(DecRefMsg);
Ted Kremenekafe348e2011-01-27 18:43:03 +00001274
1275 // Effects on the parameters.
1276 unsigned parm_idx = 0;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00001277 for (ObjCMethodDecl::param_const_iterator
1278 pi=MD->param_begin(), pe=MD->param_end();
Ted Kremenekafe348e2011-01-27 18:43:03 +00001279 pi != pe; ++pi, ++parm_idx) {
1280 const ParmVarDecl *pd = *pi;
Aaron Ballman9ead1242013-12-19 02:39:40 +00001281 if (pd->hasAttr<NSConsumedAttr>())
Jordan Rose39032472013-04-04 22:31:48 +00001282 Template->addArg(AF, parm_idx, DecRefMsg);
Aaron Ballman9ead1242013-12-19 02:39:40 +00001283 else if (pd->hasAttr<CFConsumedAttr>()) {
Jordy Rose14de7c52011-08-24 09:02:37 +00001284 Template->addArg(AF, parm_idx, DecRef);
Ted Kremenekafe348e2011-01-27 18:43:03 +00001285 }
Ted Kremenek0e898382011-01-27 06:54:14 +00001286 }
1287
Jordan Rose39032472013-04-04 22:31:48 +00001288 QualType RetTy = MD->getResultType();
1289 if (Optional<RetEffect> RetE = getRetEffectFromAnnotations(RetTy, MD))
1290 Template->setRetEffect(*RetE);
Ted Kremenekc2de7272009-05-09 02:58:13 +00001291}
1292
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001293const RetainSummary *
Jordy Rose35e71c72012-03-17 21:13:07 +00001294RetainSummaryManager::getStandardMethodSummary(const ObjCMethodDecl *MD,
1295 Selector S, QualType RetTy) {
Jordy Rose70638832012-03-17 19:53:04 +00001296 // Any special effects?
Ted Kremenek6a966b22009-04-24 21:56:17 +00001297 ArgEffect ReceiverEff = DoNothing;
Jordy Rose70638832012-03-17 19:53:04 +00001298 RetEffect ResultEff = RetEffect::MakeNoRet();
1299
1300 // Check the method family, and apply any default annotations.
1301 switch (MD ? MD->getMethodFamily() : S.getMethodFamily()) {
1302 case OMF_None:
1303 case OMF_performSelector:
1304 // Assume all Objective-C methods follow Cocoa Memory Management rules.
1305 // FIXME: Does the non-threaded performSelector family really belong here?
1306 // The selector could be, say, @selector(copy).
1307 if (cocoa::isCocoaObjectRef(RetTy))
1308 ResultEff = RetEffect::MakeNotOwned(RetEffect::ObjC);
1309 else if (coreFoundation::isCFObjectRef(RetTy)) {
1310 // ObjCMethodDecl currently doesn't consider CF objects as valid return
1311 // values for alloc, new, copy, or mutableCopy, so we have to
1312 // double-check with the selector. This is ugly, but there aren't that
1313 // many Objective-C methods that return CF objects, right?
1314 if (MD) {
1315 switch (S.getMethodFamily()) {
1316 case OMF_alloc:
1317 case OMF_new:
1318 case OMF_copy:
1319 case OMF_mutableCopy:
1320 ResultEff = RetEffect::MakeOwned(RetEffect::CF, true);
1321 break;
1322 default:
1323 ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1324 break;
1325 }
1326 } else {
1327 ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1328 }
1329 }
1330 break;
1331 case OMF_init:
1332 ResultEff = ObjCInitRetE;
1333 ReceiverEff = DecRefMsg;
1334 break;
1335 case OMF_alloc:
1336 case OMF_new:
1337 case OMF_copy:
1338 case OMF_mutableCopy:
1339 if (cocoa::isCocoaObjectRef(RetTy))
1340 ResultEff = ObjCAllocRetE;
1341 else if (coreFoundation::isCFObjectRef(RetTy))
1342 ResultEff = RetEffect::MakeOwned(RetEffect::CF, true);
1343 break;
1344 case OMF_autorelease:
1345 ReceiverEff = Autorelease;
1346 break;
1347 case OMF_retain:
1348 ReceiverEff = IncRefMsg;
1349 break;
1350 case OMF_release:
1351 ReceiverEff = DecRefMsg;
1352 break;
1353 case OMF_dealloc:
1354 ReceiverEff = Dealloc;
1355 break;
1356 case OMF_self:
1357 // -self is handled specially by the ExprEngine to propagate the receiver.
1358 break;
1359 case OMF_retainCount:
1360 case OMF_finalize:
1361 // These methods don't return objects.
1362 break;
1363 }
Mike Stump11289f42009-09-09 15:08:12 +00001364
Ted Kremenek6a966b22009-04-24 21:56:17 +00001365 // If one of the arguments in the selector has the keyword 'delegate' we
1366 // should stop tracking the reference count for the receiver. This is
1367 // because the reference count is quite possibly handled by a delegate
1368 // method.
1369 if (S.isKeywordSelector()) {
Jordan Rose95dfae82012-06-15 18:19:52 +00001370 for (unsigned i = 0, e = S.getNumArgs(); i != e; ++i) {
1371 StringRef Slot = S.getNameForSlot(i);
1372 if (Slot.substr(Slot.size() - 8).equals_lower("delegate")) {
1373 if (ResultEff == ObjCInitRetE)
Anna Zaks25612732012-08-29 23:23:43 +00001374 ResultEff = RetEffect::MakeNoRetHard();
Jordan Rose95dfae82012-06-15 18:19:52 +00001375 else
Anna Zaks25612732012-08-29 23:23:43 +00001376 ReceiverEff = StopTrackingHard;
Jordan Rose95dfae82012-06-15 18:19:52 +00001377 }
1378 }
Ted Kremenek6a966b22009-04-24 21:56:17 +00001379 }
Mike Stump11289f42009-09-09 15:08:12 +00001380
Jordy Rose70638832012-03-17 19:53:04 +00001381 if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing &&
1382 ResultEff.getKind() == RetEffect::NoRet)
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001383 return getDefaultSummary();
Mike Stump11289f42009-09-09 15:08:12 +00001384
Jordy Rose70638832012-03-17 19:53:04 +00001385 return getPersistentSummary(ResultEff, ReceiverEff, MayEscape);
Ted Kremenek60746a02009-04-23 23:08:22 +00001386}
1387
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001388const RetainSummary *
Jordan Rose6bad4902012-07-02 19:27:56 +00001389RetainSummaryManager::getInstanceMethodSummary(const ObjCMethodCall &Msg,
Jordan Roseeec15392012-07-02 19:27:43 +00001390 ProgramStateRef State) {
1391 const ObjCInterfaceDecl *ReceiverClass = 0;
Ted Kremeneka2968e52009-11-13 01:54:21 +00001392
Jordan Roseeec15392012-07-02 19:27:43 +00001393 // We do better tracking of the type of the object than the core ExprEngine.
1394 // See if we have its type in our private state.
1395 // FIXME: Eventually replace the use of state->get<RefBindings> with
1396 // a generic API for reasoning about the Objective-C types of symbolic
1397 // objects.
1398 SVal ReceiverV = Msg.getReceiverSVal();
1399 if (SymbolRef Sym = ReceiverV.getAsLocSymbol())
Anna Zaksf5788c72012-08-14 00:36:15 +00001400 if (const RefVal *T = getRefBinding(State, Sym))
Douglas Gregor9a129192010-04-21 00:45:42 +00001401 if (const ObjCObjectPointerType *PT =
Jordan Roseeec15392012-07-02 19:27:43 +00001402 T->getType()->getAs<ObjCObjectPointerType>())
1403 ReceiverClass = PT->getInterfaceDecl();
1404
1405 // If we don't know what kind of object this is, fall back to its static type.
1406 if (!ReceiverClass)
1407 ReceiverClass = Msg.getReceiverInterface();
Douglas Gregor9a129192010-04-21 00:45:42 +00001408
Ted Kremeneka2968e52009-11-13 01:54:21 +00001409 // FIXME: The receiver could be a reference to a class, meaning that
1410 // we should use the class method.
Jordan Roseeec15392012-07-02 19:27:43 +00001411 // id x = [NSObject class];
1412 // [x performSelector:... withObject:... afterDelay:...];
1413 Selector S = Msg.getSelector();
1414 const ObjCMethodDecl *Method = Msg.getDecl();
1415 if (!Method && ReceiverClass)
1416 Method = ReceiverClass->getInstanceMethod(S);
1417
1418 return getMethodSummary(S, ReceiverClass, Method, Msg.getResultType(),
1419 ObjCMethodSummaries);
Ted Kremeneka2968e52009-11-13 01:54:21 +00001420}
1421
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001422const RetainSummary *
Jordan Roseeec15392012-07-02 19:27:43 +00001423RetainSummaryManager::getMethodSummary(Selector S, const ObjCInterfaceDecl *ID,
Jordy Rose35e71c72012-03-17 21:13:07 +00001424 const ObjCMethodDecl *MD, QualType RetTy,
1425 ObjCMethodSummariesTy &CachedSummaries) {
Ted Kremenekcb2e6362008-05-06 15:44:25 +00001426
Ted Kremenek0b50fb12009-04-29 05:04:30 +00001427 // Look up a summary in our summary cache.
Jordan Roseeec15392012-07-02 19:27:43 +00001428 const RetainSummary *Summ = CachedSummaries.find(ID, S);
Mike Stump11289f42009-09-09 15:08:12 +00001429
Ted Kremenek8be51382009-07-21 23:27:57 +00001430 if (!Summ) {
Jordy Rose35e71c72012-03-17 21:13:07 +00001431 Summ = getStandardMethodSummary(MD, S, RetTy);
Mike Stump11289f42009-09-09 15:08:12 +00001432
Ted Kremenek8be51382009-07-21 23:27:57 +00001433 // Annotations override defaults.
Jordy Rose212e4592011-08-23 04:27:15 +00001434 updateSummaryFromAnnotations(Summ, MD);
Mike Stump11289f42009-09-09 15:08:12 +00001435
Ted Kremenek8be51382009-07-21 23:27:57 +00001436 // Memoize the summary.
Jordan Roseeec15392012-07-02 19:27:43 +00001437 CachedSummaries[ObjCSummaryKey(ID, S)] = Summ;
Ted Kremenek8be51382009-07-21 23:27:57 +00001438 }
Mike Stump11289f42009-09-09 15:08:12 +00001439
Ted Kremenekf27110f2009-04-23 19:11:35 +00001440 return Summ;
Ted Kremenek767d0742008-05-06 21:26:51 +00001441}
1442
Mike Stump11289f42009-09-09 15:08:12 +00001443void RetainSummaryManager::InitializeClassMethodSummaries() {
Ted Kremenek9157fbb2009-05-07 23:40:42 +00001444 assert(ScratchArgs.isEmpty());
Mike Stump11289f42009-09-09 15:08:12 +00001445 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek55adb822009-10-15 22:25:12 +00001446 addClassMethSummary("NSAssertionHandler", "currentHandler",
Ted Kremenekaeb115f2009-01-28 05:56:51 +00001447 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Mike Stump11289f42009-09-09 15:08:12 +00001448
Ted Kremenek0747e7e2008-10-21 15:53:15 +00001449 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremenekb3b56c62010-11-24 00:54:37 +00001450 ScratchArgs = AF.add(ScratchArgs, 0, Autorelease);
Ted Kremenek55adb822009-10-15 22:25:12 +00001451 addClassMethSummary("NSAutoreleasePool", "addObject",
1452 getPersistentSummary(RetEffect::MakeNoRet(),
1453 DoNothing, Autorelease));
Ted Kremenek0806f912008-05-06 00:30:21 +00001454}
1455
Ted Kremenekea736c52008-06-23 22:21:20 +00001456void RetainSummaryManager::InitializeMethodSummaries() {
Mike Stump11289f42009-09-09 15:08:12 +00001457
1458 assert (ScratchArgs.isEmpty());
1459
Ted Kremenek767d0742008-05-06 21:26:51 +00001460 // Create the "init" selector. It just acts as a pass-through for the
1461 // receiver.
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001462 const RetainSummary *InitSumm = getPersistentSummary(ObjCInitRetE, DecRefMsg);
Ted Kremenek815fbb62009-08-20 05:13:36 +00001463 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
1464
1465 // awakeAfterUsingCoder: behaves basically like an 'init' method. It
1466 // claims the receiver and returns a retained object.
1467 addNSObjectMethSummary(GetUnarySelector("awakeAfterUsingCoder", Ctx),
1468 InitSumm);
Mike Stump11289f42009-09-09 15:08:12 +00001469
Ted Kremenek767d0742008-05-06 21:26:51 +00001470 // The next methods are allocators.
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001471 const RetainSummary *AllocSumm = getPersistentSummary(ObjCAllocRetE);
1472 const RetainSummary *CFAllocSumm =
Ted Kremenek52ac2b52009-08-28 19:52:12 +00001473 getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Mike Stump11289f42009-09-09 15:08:12 +00001474
Ted Kremenekb0862dc2008-05-06 02:26:56 +00001475 // Create the "retain" selector.
Jordy Rose3f7f75682011-08-21 19:41:36 +00001476 RetEffect NoRet = RetEffect::MakeNoRet();
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001477 const RetainSummary *Summ = getPersistentSummary(NoRet, IncRefMsg);
Ted Kremenek3185c9c2008-06-25 21:21:56 +00001478 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Mike Stump11289f42009-09-09 15:08:12 +00001479
Ted Kremenekb0862dc2008-05-06 02:26:56 +00001480 // Create the "release" selector.
Jordy Rose3f7f75682011-08-21 19:41:36 +00001481 Summ = getPersistentSummary(NoRet, DecRefMsg);
Ted Kremenek3185c9c2008-06-25 21:21:56 +00001482 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Mike Stump11289f42009-09-09 15:08:12 +00001483
Ted Kremenekea072e32009-03-17 19:42:23 +00001484 // Create the -dealloc summary.
Jordy Rose3f7f75682011-08-21 19:41:36 +00001485 Summ = getPersistentSummary(NoRet, Dealloc);
Ted Kremenekea072e32009-03-17 19:42:23 +00001486 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
Ted Kremenekb0862dc2008-05-06 02:26:56 +00001487
1488 // Create the "autorelease" selector.
Jordy Rose3f7f75682011-08-21 19:41:36 +00001489 Summ = getPersistentSummary(NoRet, Autorelease);
Ted Kremenek3185c9c2008-06-25 21:21:56 +00001490 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Mike Stump11289f42009-09-09 15:08:12 +00001491
Mike Stump11289f42009-09-09 15:08:12 +00001492 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremeneke73f2822009-02-23 02:51:29 +00001493 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1494 // self-own themselves. However, they only do this once they are displayed.
1495 // Thus, we need to track an NSWindow's display status.
1496 // This is tracked in <rdar://problem/6062711>.
Ted Kremenek00dfe302009-03-04 23:30:42 +00001497 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001498 const RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenek1272f702009-05-12 20:06:54 +00001499 StopTracking,
1500 StopTracking);
Mike Stump11289f42009-09-09 15:08:12 +00001501
Ted Kremenek751e7e32009-04-03 19:02:51 +00001502 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1503
Ted Kremenek3f13f592008-08-12 18:48:50 +00001504 // For NSPanel (which subclasses NSWindow), allocated objects are not
1505 // self-owned.
Ted Kremenek751e7e32009-04-03 19:02:51 +00001506 // FIXME: For now we don't track NSPanels. object for the same reason
1507 // as for NSWindow objects.
1508 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
Mike Stump11289f42009-09-09 15:08:12 +00001509
Ted Kremenek9b12e722014-01-03 01:19:28 +00001510 // For NSNull, objects returned by +null are singletons that ignore
1511 // retain/release semantics. Just don't track them.
1512 // <rdar://problem/12858915>
1513 addClassMethSummary("NSNull", "null", NoTrackYet);
1514
Jordan Rose95bf3b02013-01-31 22:06:02 +00001515 // Don't track allocated autorelease pools, as it is okay to prematurely
Ted Kremenek501ba032009-05-18 23:14:34 +00001516 // exit a method.
1517 addClassMethSummary("NSAutoreleasePool", "alloc", NoTrackYet);
Ted Kremeneke8a5ba82012-02-18 21:37:48 +00001518 addClassMethSummary("NSAutoreleasePool", "allocWithZone", NoTrackYet, false);
Jordan Rose95bf3b02013-01-31 22:06:02 +00001519 addClassMethSummary("NSAutoreleasePool", "new", NoTrackYet);
Ted Kremenek3185c9c2008-06-25 21:21:56 +00001520
Ted Kremenek10369122009-05-20 22:39:57 +00001521 // Create summaries QCRenderer/QCView -createSnapShotImageOfType:
1522 addInstMethSummary("QCRenderer", AllocSumm,
1523 "createSnapshotImageOfType", NULL);
1524 addInstMethSummary("QCView", AllocSumm,
1525 "createSnapshotImageOfType", NULL);
1526
Ted Kremenek96aa1462009-06-15 20:58:58 +00001527 // Create summaries for CIContext, 'createCGImage' and
Ted Kremenek52ac2b52009-08-28 19:52:12 +00001528 // 'createCGLayerWithSize'. These objects are CF objects, and are not
1529 // automatically garbage collected.
1530 addInstMethSummary("CIContext", CFAllocSumm,
Ted Kremenek10369122009-05-20 22:39:57 +00001531 "createCGImage", "fromRect", NULL);
Ted Kremenek52ac2b52009-08-28 19:52:12 +00001532 addInstMethSummary("CIContext", CFAllocSumm,
Mike Stump11289f42009-09-09 15:08:12 +00001533 "createCGImage", "fromRect", "format", "colorSpace", NULL);
Ted Kremenek52ac2b52009-08-28 19:52:12 +00001534 addInstMethSummary("CIContext", CFAllocSumm, "createCGLayerWithSize",
Ted Kremenek96aa1462009-06-15 20:58:58 +00001535 "info", NULL);
Ted Kremenekbe7c56e2008-05-06 00:38:54 +00001536}
1537
Ted Kremenek00daccd2008-05-05 22:11:16 +00001538//===----------------------------------------------------------------------===//
Ted Kremenek6bd78702009-04-29 18:50:19 +00001539// Error reporting.
1540//===----------------------------------------------------------------------===//
Ted Kremenek6bd78702009-04-29 18:50:19 +00001541namespace {
Jordy Rose20d4e682011-08-23 20:55:48 +00001542 typedef llvm::DenseMap<const ExplodedNode *, const RetainSummary *>
1543 SummaryLogTy;
1544
Ted Kremenek6bd78702009-04-29 18:50:19 +00001545 //===-------------===//
1546 // Bug Descriptions. //
Mike Stump11289f42009-09-09 15:08:12 +00001547 //===-------------===//
1548
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00001549 class CFRefBug : public BugType {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001550 protected:
Jordy Rose7a534982011-08-24 05:47:39 +00001551 CFRefBug(StringRef name)
Ted Kremenekb45d1982012-04-05 20:43:28 +00001552 : BugType(name, categories::MemoryCoreFoundationObjectiveC) {}
Ted Kremenek6bd78702009-04-29 18:50:19 +00001553 public:
Mike Stump11289f42009-09-09 15:08:12 +00001554
Ted Kremenek6bd78702009-04-29 18:50:19 +00001555 // FIXME: Eventually remove.
Jordy Rose7a534982011-08-24 05:47:39 +00001556 virtual const char *getDescription() const = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001557
Ted Kremenek6bd78702009-04-29 18:50:19 +00001558 virtual bool isLeak() const { return false; }
1559 };
Mike Stump11289f42009-09-09 15:08:12 +00001560
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00001561 class UseAfterRelease : public CFRefBug {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001562 public:
Jordy Rose7a534982011-08-24 05:47:39 +00001563 UseAfterRelease() : CFRefBug("Use-after-release") {}
Mike Stump11289f42009-09-09 15:08:12 +00001564
Jordy Rose7a534982011-08-24 05:47:39 +00001565 const char *getDescription() const {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001566 return "Reference-counted object is used after it is released";
Mike Stump11289f42009-09-09 15:08:12 +00001567 }
Ted Kremenek6bd78702009-04-29 18:50:19 +00001568 };
Mike Stump11289f42009-09-09 15:08:12 +00001569
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00001570 class BadRelease : public CFRefBug {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001571 public:
Jordy Rose7a534982011-08-24 05:47:39 +00001572 BadRelease() : CFRefBug("Bad release") {}
Mike Stump11289f42009-09-09 15:08:12 +00001573
Jordy Rose7a534982011-08-24 05:47:39 +00001574 const char *getDescription() const {
Ted Kremenek5c22e112009-10-01 17:31:50 +00001575 return "Incorrect decrement of the reference count of an object that is "
1576 "not owned at this point by the caller";
Ted Kremenek6bd78702009-04-29 18:50:19 +00001577 }
1578 };
Mike Stump11289f42009-09-09 15:08:12 +00001579
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00001580 class DeallocGC : public CFRefBug {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001581 public:
Jordy Rose7a534982011-08-24 05:47:39 +00001582 DeallocGC()
1583 : CFRefBug("-dealloc called while using garbage collection") {}
Mike Stump11289f42009-09-09 15:08:12 +00001584
Ted Kremenek6bd78702009-04-29 18:50:19 +00001585 const char *getDescription() const {
Ted Kremenekd35272f2009-05-09 00:10:05 +00001586 return "-dealloc called while using garbage collection";
Ted Kremenek6bd78702009-04-29 18:50:19 +00001587 }
1588 };
Mike Stump11289f42009-09-09 15:08:12 +00001589
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00001590 class DeallocNotOwned : public CFRefBug {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001591 public:
Jordy Rose7a534982011-08-24 05:47:39 +00001592 DeallocNotOwned()
1593 : CFRefBug("-dealloc sent to non-exclusively owned object") {}
Mike Stump11289f42009-09-09 15:08:12 +00001594
Ted Kremenek6bd78702009-04-29 18:50:19 +00001595 const char *getDescription() const {
1596 return "-dealloc sent to object that may be referenced elsewhere";
1597 }
Mike Stump11289f42009-09-09 15:08:12 +00001598 };
1599
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00001600 class OverAutorelease : public CFRefBug {
Ted Kremenekd35272f2009-05-09 00:10:05 +00001601 public:
Jordy Rose7a534982011-08-24 05:47:39 +00001602 OverAutorelease()
Jordan Rose7467f062013-04-23 01:42:25 +00001603 : CFRefBug("Object autoreleased too many times") {}
Mike Stump11289f42009-09-09 15:08:12 +00001604
Ted Kremenekd35272f2009-05-09 00:10:05 +00001605 const char *getDescription() const {
Jordan Rose7467f062013-04-23 01:42:25 +00001606 return "Object autoreleased too many times";
Ted Kremenekd35272f2009-05-09 00:10:05 +00001607 }
1608 };
Mike Stump11289f42009-09-09 15:08:12 +00001609
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00001610 class ReturnedNotOwnedForOwned : public CFRefBug {
Ted Kremenekdee56e32009-05-10 06:25:57 +00001611 public:
Jordy Rose7a534982011-08-24 05:47:39 +00001612 ReturnedNotOwnedForOwned()
1613 : CFRefBug("Method should return an owned object") {}
Mike Stump11289f42009-09-09 15:08:12 +00001614
Ted Kremenekdee56e32009-05-10 06:25:57 +00001615 const char *getDescription() const {
Jordy Rose43426f82011-07-15 22:17:54 +00001616 return "Object with a +0 retain count returned to caller where a +1 "
Ted Kremenekdee56e32009-05-10 06:25:57 +00001617 "(owning) retain count is expected";
1618 }
1619 };
Mike Stump11289f42009-09-09 15:08:12 +00001620
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00001621 class Leak : public CFRefBug {
Benjamin Kramerd1d76b22012-06-06 17:32:50 +00001622 public:
1623 Leak(StringRef name)
1624 : CFRefBug(name) {
Jordy Rose15484da2011-08-25 01:14:38 +00001625 // Leaks should not be reported if they are post-dominated by a sink.
1626 setSuppressOnSink(true);
1627 }
Mike Stump11289f42009-09-09 15:08:12 +00001628
Jordy Rose7a534982011-08-24 05:47:39 +00001629 const char *getDescription() const { return ""; }
Mike Stump11289f42009-09-09 15:08:12 +00001630
Ted Kremenek6bd78702009-04-29 18:50:19 +00001631 bool isLeak() const { return true; }
1632 };
Mike Stump11289f42009-09-09 15:08:12 +00001633
Ted Kremenek6bd78702009-04-29 18:50:19 +00001634 //===---------===//
1635 // Bug Reports. //
1636 //===---------===//
Mike Stump11289f42009-09-09 15:08:12 +00001637
Jordy Rosef78877e2012-03-24 02:45:35 +00001638 class CFRefReportVisitor : public BugReporterVisitorImpl<CFRefReportVisitor> {
Anna Zaks88255cc2011-08-20 01:27:22 +00001639 protected:
Anna Zaks071a89c2011-08-19 23:21:56 +00001640 SymbolRef Sym;
Jordy Rose20d4e682011-08-23 20:55:48 +00001641 const SummaryLogTy &SummaryLog;
Jordy Rose7a534982011-08-24 05:47:39 +00001642 bool GCEnabled;
Anna Zaks88255cc2011-08-20 01:27:22 +00001643
Anna Zaks071a89c2011-08-19 23:21:56 +00001644 public:
Jordy Rose7a534982011-08-24 05:47:39 +00001645 CFRefReportVisitor(SymbolRef sym, bool gcEnabled, const SummaryLogTy &log)
1646 : Sym(sym), SummaryLog(log), GCEnabled(gcEnabled) {}
Anna Zaks071a89c2011-08-19 23:21:56 +00001647
Anna Zaks88255cc2011-08-20 01:27:22 +00001648 virtual void Profile(llvm::FoldingSetNodeID &ID) const {
Anna Zaks071a89c2011-08-19 23:21:56 +00001649 static int x = 0;
1650 ID.AddPointer(&x);
1651 ID.AddPointer(Sym);
1652 }
1653
Anna Zaks88255cc2011-08-20 01:27:22 +00001654 virtual PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
1655 const ExplodedNode *PrevN,
1656 BugReporterContext &BRC,
1657 BugReport &BR);
1658
1659 virtual PathDiagnosticPiece *getEndPath(BugReporterContext &BRC,
1660 const ExplodedNode *N,
1661 BugReport &BR);
1662 };
1663
1664 class CFRefLeakReportVisitor : public CFRefReportVisitor {
1665 public:
Jordy Rose7a534982011-08-24 05:47:39 +00001666 CFRefLeakReportVisitor(SymbolRef sym, bool GCEnabled,
Jordy Rose20d4e682011-08-23 20:55:48 +00001667 const SummaryLogTy &log)
Jordy Rose7a534982011-08-24 05:47:39 +00001668 : CFRefReportVisitor(sym, GCEnabled, log) {}
Anna Zaks88255cc2011-08-20 01:27:22 +00001669
1670 PathDiagnosticPiece *getEndPath(BugReporterContext &BRC,
1671 const ExplodedNode *N,
1672 BugReport &BR);
Jordy Rosef78877e2012-03-24 02:45:35 +00001673
1674 virtual BugReporterVisitor *clone() const {
1675 // The curiously-recurring template pattern only works for one level of
1676 // subclassing. Rather than make a new template base for
1677 // CFRefReportVisitor, we simply override clone() to do the right thing.
1678 // This could be trouble someday if BugReporterVisitorImpl is ever
1679 // used for something else besides a convenient implementation of clone().
1680 return new CFRefLeakReportVisitor(*this);
1681 }
Anna Zaks071a89c2011-08-19 23:21:56 +00001682 };
1683
Anna Zaks3a6bdf82011-08-17 23:00:25 +00001684 class CFRefReport : public BugReport {
Jordy Rose184bd142011-08-24 22:39:09 +00001685 void addGCModeDescription(const LangOptions &LOpts, bool GCEnabled);
Jordy Rose7a534982011-08-24 05:47:39 +00001686
Ted Kremenek6bd78702009-04-29 18:50:19 +00001687 public:
Jordy Rose184bd142011-08-24 22:39:09 +00001688 CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1689 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1690 bool registerVisitor = true)
Anna Zaks752de142011-08-22 18:54:07 +00001691 : BugReport(D, D.getDescription(), n) {
Anna Zaks88255cc2011-08-20 01:27:22 +00001692 if (registerVisitor)
Jordy Rose184bd142011-08-24 22:39:09 +00001693 addVisitor(new CFRefReportVisitor(sym, GCEnabled, Log));
1694 addGCModeDescription(LOpts, GCEnabled);
Anna Zaks071a89c2011-08-19 23:21:56 +00001695 }
Ted Kremenek3978f792009-05-10 05:11:21 +00001696
Jordy Rose184bd142011-08-24 22:39:09 +00001697 CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1698 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1699 StringRef endText)
Anna Zaks752de142011-08-22 18:54:07 +00001700 : BugReport(D, D.getDescription(), endText, n) {
Jordy Rose184bd142011-08-24 22:39:09 +00001701 addVisitor(new CFRefReportVisitor(sym, GCEnabled, Log));
1702 addGCModeDescription(LOpts, GCEnabled);
Anna Zaks071a89c2011-08-19 23:21:56 +00001703 }
Mike Stump11289f42009-09-09 15:08:12 +00001704
Anna Zaks3a6bdf82011-08-17 23:00:25 +00001705 virtual std::pair<ranges_iterator, ranges_iterator> getRanges() {
Anna Zaks752de142011-08-22 18:54:07 +00001706 const CFRefBug& BugTy = static_cast<CFRefBug&>(getBugType());
1707 if (!BugTy.isLeak())
Anna Zaks3a6bdf82011-08-17 23:00:25 +00001708 return BugReport::getRanges();
Ted Kremenek6bd78702009-04-29 18:50:19 +00001709 else
Argyrios Kyrtzidisd22d8ff2010-12-04 01:12:15 +00001710 return std::make_pair(ranges_iterator(), ranges_iterator());
Ted Kremenek6bd78702009-04-29 18:50:19 +00001711 }
Ted Kremenek6bd78702009-04-29 18:50:19 +00001712 };
Ted Kremenek3978f792009-05-10 05:11:21 +00001713
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00001714 class CFRefLeakReport : public CFRefReport {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001715 const MemRegion* AllocBinding;
1716 public:
Jordy Rose184bd142011-08-24 22:39:09 +00001717 CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1718 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
Ted Kremenek8671acb2013-04-16 21:44:22 +00001719 CheckerContext &Ctx,
1720 bool IncludeAllocationLine);
Mike Stump11289f42009-09-09 15:08:12 +00001721
Anna Zaksc29bed32011-09-20 21:38:35 +00001722 PathDiagnosticLocation getLocation(const SourceManager &SM) const {
1723 assert(Location.isValid());
1724 return Location;
1725 }
Mike Stump11289f42009-09-09 15:08:12 +00001726 };
Ted Kremenek6bd78702009-04-29 18:50:19 +00001727} // end anonymous namespace
1728
Jordy Rose184bd142011-08-24 22:39:09 +00001729void CFRefReport::addGCModeDescription(const LangOptions &LOpts,
1730 bool GCEnabled) {
Jordy Rose9ff02992011-08-24 20:38:42 +00001731 const char *GCModeDescription = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001732
Douglas Gregor79a91412011-09-13 17:21:33 +00001733 switch (LOpts.getGC()) {
Anna Zaks76c3fb62011-08-22 20:31:28 +00001734 case LangOptions::GCOnly:
Jordy Rose184bd142011-08-24 22:39:09 +00001735 assert(GCEnabled);
Jordy Rose7a534982011-08-24 05:47:39 +00001736 GCModeDescription = "Code is compiled to only use garbage collection";
1737 break;
Mike Stump11289f42009-09-09 15:08:12 +00001738
Anna Zaks76c3fb62011-08-22 20:31:28 +00001739 case LangOptions::NonGC:
Jordy Rose184bd142011-08-24 22:39:09 +00001740 assert(!GCEnabled);
Jordy Rose7a534982011-08-24 05:47:39 +00001741 GCModeDescription = "Code is compiled to use reference counts";
1742 break;
Mike Stump11289f42009-09-09 15:08:12 +00001743
Anna Zaks76c3fb62011-08-22 20:31:28 +00001744 case LangOptions::HybridGC:
Jordy Rose184bd142011-08-24 22:39:09 +00001745 if (GCEnabled) {
Jordy Rose7a534982011-08-24 05:47:39 +00001746 GCModeDescription = "Code is compiled to use either garbage collection "
1747 "(GC) or reference counts (non-GC). The bug occurs "
1748 "with GC enabled";
1749 break;
1750 } else {
1751 GCModeDescription = "Code is compiled to use either garbage collection "
1752 "(GC) or reference counts (non-GC). The bug occurs "
1753 "in non-GC mode";
1754 break;
Anna Zaks76c3fb62011-08-22 20:31:28 +00001755 }
Ted Kremenek6bd78702009-04-29 18:50:19 +00001756 }
Jordy Rose7a534982011-08-24 05:47:39 +00001757
Jordy Rose9ff02992011-08-24 20:38:42 +00001758 assert(GCModeDescription && "invalid/unknown GC mode");
Jordy Rose7a534982011-08-24 05:47:39 +00001759 addExtraText(GCModeDescription);
Ted Kremenek6bd78702009-04-29 18:50:19 +00001760}
1761
Jordy Rose6393f822012-05-12 05:10:43 +00001762static bool isNumericLiteralExpression(const Expr *E) {
1763 // FIXME: This set of cases was copied from SemaExprObjC.
1764 return isa<IntegerLiteral>(E) ||
1765 isa<CharacterLiteral>(E) ||
1766 isa<FloatingLiteral>(E) ||
1767 isa<ObjCBoolLiteralExpr>(E) ||
1768 isa<CXXBoolLiteralExpr>(E);
1769}
1770
Anna Zaks071a89c2011-08-19 23:21:56 +00001771PathDiagnosticPiece *CFRefReportVisitor::VisitNode(const ExplodedNode *N,
1772 const ExplodedNode *PrevN,
1773 BugReporterContext &BRC,
1774 BugReport &BR) {
Jordan Rose681cce92012-07-10 22:07:42 +00001775 // FIXME: We will eventually need to handle non-statement-based events
1776 // (__attribute__((cleanup))).
David Blaikie87396b92013-02-21 22:23:56 +00001777 if (!N->getLocation().getAs<StmtPoint>())
Ted Kremenek051a03d2009-05-13 07:12:33 +00001778 return NULL;
Mike Stump11289f42009-09-09 15:08:12 +00001779
Ted Kremenekbb8d5462009-05-06 21:39:49 +00001780 // Check if the type state has changed.
Ted Kremenek49b1e382012-01-26 21:29:00 +00001781 ProgramStateRef PrevSt = PrevN->getState();
1782 ProgramStateRef CurrSt = N->getState();
Ted Kremenek632e3b72012-01-06 22:09:28 +00001783 const LocationContext *LCtx = N->getLocationContext();
Mike Stump11289f42009-09-09 15:08:12 +00001784
Anna Zaksf5788c72012-08-14 00:36:15 +00001785 const RefVal* CurrT = getRefBinding(CurrSt, Sym);
Ted Kremenek6bd78702009-04-29 18:50:19 +00001786 if (!CurrT) return NULL;
Mike Stump11289f42009-09-09 15:08:12 +00001787
Ted Kremenekd93c6e32009-06-18 01:23:53 +00001788 const RefVal &CurrV = *CurrT;
Anna Zaksf5788c72012-08-14 00:36:15 +00001789 const RefVal *PrevT = getRefBinding(PrevSt, Sym);
Mike Stump11289f42009-09-09 15:08:12 +00001790
Ted Kremenek6bd78702009-04-29 18:50:19 +00001791 // Create a string buffer to constain all the useful things we want
1792 // to tell the user.
1793 std::string sbuf;
1794 llvm::raw_string_ostream os(sbuf);
Mike Stump11289f42009-09-09 15:08:12 +00001795
Ted Kremenek6bd78702009-04-29 18:50:19 +00001796 // This is the allocation site since the previous node had no bindings
1797 // for this symbol.
1798 if (!PrevT) {
David Blaikie87396b92013-02-21 22:23:56 +00001799 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
Mike Stump11289f42009-09-09 15:08:12 +00001800
Ted Kremenek415287d2012-03-06 20:06:12 +00001801 if (isa<ObjCArrayLiteral>(S)) {
1802 os << "NSArray literal is an object with a +0 retain count";
Mike Stump11289f42009-09-09 15:08:12 +00001803 }
Ted Kremenek415287d2012-03-06 20:06:12 +00001804 else if (isa<ObjCDictionaryLiteral>(S)) {
1805 os << "NSDictionary literal is an object with a +0 retain count";
Ted Kremenek6bd78702009-04-29 18:50:19 +00001806 }
Jordy Rose6393f822012-05-12 05:10:43 +00001807 else if (const ObjCBoxedExpr *BL = dyn_cast<ObjCBoxedExpr>(S)) {
1808 if (isNumericLiteralExpression(BL->getSubExpr()))
1809 os << "NSNumber literal is an object with a +0 retain count";
1810 else {
1811 const ObjCInterfaceDecl *BoxClass = 0;
1812 if (const ObjCMethodDecl *Method = BL->getBoxingMethod())
1813 BoxClass = Method->getClassInterface();
1814
1815 // We should always be able to find the boxing class interface,
1816 // but consider this future-proofing.
1817 if (BoxClass)
1818 os << *BoxClass << " b";
1819 else
1820 os << "B";
1821
1822 os << "oxed expression produces an object with a +0 retain count";
1823 }
1824 }
Ted Kremenek415287d2012-03-06 20:06:12 +00001825 else {
1826 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
1827 // Get the name of the callee (if it is available).
1828 SVal X = CurrSt->getSValAsScalarOrLoc(CE->getCallee(), LCtx);
1829 if (const FunctionDecl *FD = X.getAsFunctionDecl())
1830 os << "Call to function '" << *FD << '\'';
1831 else
1832 os << "function call";
Ted Kremenek6bd78702009-04-29 18:50:19 +00001833 }
Ted Kremenek415287d2012-03-06 20:06:12 +00001834 else {
Jordan Rose627b0462012-07-18 21:59:51 +00001835 assert(isa<ObjCMessageExpr>(S));
Jordan Rosefcd016e2012-07-30 20:22:09 +00001836 CallEventManager &Mgr = CurrSt->getStateManager().getCallEventManager();
1837 CallEventRef<ObjCMethodCall> Call
1838 = Mgr.getObjCMethodCall(cast<ObjCMessageExpr>(S), CurrSt, LCtx);
1839
1840 switch (Call->getMessageKind()) {
Jordan Rose627b0462012-07-18 21:59:51 +00001841 case OCM_Message:
1842 os << "Method";
1843 break;
1844 case OCM_PropertyAccess:
1845 os << "Property";
1846 break;
1847 case OCM_Subscript:
1848 os << "Subscript";
1849 break;
1850 }
Ted Kremenek415287d2012-03-06 20:06:12 +00001851 }
1852
1853 if (CurrV.getObjKind() == RetEffect::CF) {
1854 os << " returns a Core Foundation object with a ";
1855 }
1856 else {
1857 assert (CurrV.getObjKind() == RetEffect::ObjC);
1858 os << " returns an Objective-C object with a ";
1859 }
1860
1861 if (CurrV.isOwned()) {
1862 os << "+1 retain count";
1863
1864 if (GCEnabled) {
1865 assert(CurrV.getObjKind() == RetEffect::CF);
1866 os << ". "
1867 "Core Foundation objects are not automatically garbage collected.";
1868 }
1869 }
1870 else {
1871 assert (CurrV.isNotOwned());
1872 os << "+0 retain count";
1873 }
Ted Kremenek6bd78702009-04-29 18:50:19 +00001874 }
Mike Stump11289f42009-09-09 15:08:12 +00001875
Anna Zaks3a769bd2011-09-15 01:08:34 +00001876 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
1877 N->getLocationContext());
Ted Kremenek6bd78702009-04-29 18:50:19 +00001878 return new PathDiagnosticEventPiece(Pos, os.str());
1879 }
Mike Stump11289f42009-09-09 15:08:12 +00001880
Ted Kremenek6bd78702009-04-29 18:50:19 +00001881 // Gather up the effects that were performed on the object at this
1882 // program point
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001883 SmallVector<ArgEffect, 2> AEffects;
Mike Stump11289f42009-09-09 15:08:12 +00001884
Jordy Rose20d4e682011-08-23 20:55:48 +00001885 const ExplodedNode *OrigNode = BRC.getNodeResolver().getOriginalNode(N);
1886 if (const RetainSummary *Summ = SummaryLog.lookup(OrigNode)) {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001887 // We only have summaries attached to nodes after evaluating CallExpr and
1888 // ObjCMessageExprs.
David Blaikie87396b92013-02-21 22:23:56 +00001889 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
Mike Stump11289f42009-09-09 15:08:12 +00001890
Ted Kremenekbfd28fd2009-07-22 22:35:28 +00001891 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001892 // Iterate through the parameter expressions and see if the symbol
1893 // was ever passed as an argument.
1894 unsigned i = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001895
Ted Kremenekbfd28fd2009-07-22 22:35:28 +00001896 for (CallExpr::const_arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
Ted Kremenek6bd78702009-04-29 18:50:19 +00001897 AI!=AE; ++AI, ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00001898
Ted Kremenek6bd78702009-04-29 18:50:19 +00001899 // Retrieve the value of the argument. Is it the symbol
1900 // we are interested in?
Ted Kremenek632e3b72012-01-06 22:09:28 +00001901 if (CurrSt->getSValAsScalarOrLoc(*AI, LCtx).getAsLocSymbol() != Sym)
Ted Kremenek6bd78702009-04-29 18:50:19 +00001902 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001903
Ted Kremenek6bd78702009-04-29 18:50:19 +00001904 // We have an argument. Get the effect!
1905 AEffects.push_back(Summ->getArg(i));
1906 }
1907 }
Mike Stump11289f42009-09-09 15:08:12 +00001908 else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
Douglas Gregor9a129192010-04-21 00:45:42 +00001909 if (const Expr *receiver = ME->getInstanceReceiver())
Ted Kremenek632e3b72012-01-06 22:09:28 +00001910 if (CurrSt->getSValAsScalarOrLoc(receiver, LCtx)
1911 .getAsLocSymbol() == Sym) {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001912 // The symbol we are tracking is the receiver.
1913 AEffects.push_back(Summ->getReceiverEffect());
1914 }
1915 }
1916 }
Mike Stump11289f42009-09-09 15:08:12 +00001917
Ted Kremenek6bd78702009-04-29 18:50:19 +00001918 do {
1919 // Get the previous type state.
1920 RefVal PrevV = *PrevT;
Mike Stump11289f42009-09-09 15:08:12 +00001921
Ted Kremenek6bd78702009-04-29 18:50:19 +00001922 // Specially handle -dealloc.
Benjamin Kramerab3838a2013-08-16 21:57:14 +00001923 if (!GCEnabled && std::find(AEffects.begin(), AEffects.end(), Dealloc) !=
1924 AEffects.end()) {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001925 // Determine if the object's reference count was pushed to zero.
1926 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
1927 // We may not have transitioned to 'release' if we hit an error.
1928 // This case is handled elsewhere.
1929 if (CurrV.getKind() == RefVal::Released) {
Ted Kremenek3a0516b2009-05-08 20:01:42 +00001930 assert(CurrV.getCombinedCounts() == 0);
Ted Kremenek6bd78702009-04-29 18:50:19 +00001931 os << "Object released by directly sending the '-dealloc' message";
1932 break;
1933 }
1934 }
Mike Stump11289f42009-09-09 15:08:12 +00001935
Ted Kremenek6bd78702009-04-29 18:50:19 +00001936 // Specially handle CFMakeCollectable and friends.
Benjamin Kramerab3838a2013-08-16 21:57:14 +00001937 if (std::find(AEffects.begin(), AEffects.end(), MakeCollectable) !=
1938 AEffects.end()) {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001939 // Get the name of the function.
David Blaikie87396b92013-02-21 22:23:56 +00001940 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
Ted Kremenek632e3b72012-01-06 22:09:28 +00001941 SVal X =
1942 CurrSt->getSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee(), LCtx);
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001943 const FunctionDecl *FD = X.getAsFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001944
Jordy Rose7a534982011-08-24 05:47:39 +00001945 if (GCEnabled) {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001946 // Determine if the object's reference count was pushed to zero.
1947 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
Mike Stump11289f42009-09-09 15:08:12 +00001948
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001949 os << "In GC mode a call to '" << *FD
Ted Kremenek6bd78702009-04-29 18:50:19 +00001950 << "' decrements an object's retain count and registers the "
1951 "object with the garbage collector. ";
Mike Stump11289f42009-09-09 15:08:12 +00001952
Ted Kremenek6bd78702009-04-29 18:50:19 +00001953 if (CurrV.getKind() == RefVal::Released) {
1954 assert(CurrV.getCount() == 0);
1955 os << "Since it now has a 0 retain count the object can be "
1956 "automatically collected by the garbage collector.";
1957 }
1958 else
1959 os << "An object must have a 0 retain count to be garbage collected. "
1960 "After this call its retain count is +" << CurrV.getCount()
1961 << '.';
1962 }
Mike Stump11289f42009-09-09 15:08:12 +00001963 else
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001964 os << "When GC is not enabled a call to '" << *FD
Ted Kremenek6bd78702009-04-29 18:50:19 +00001965 << "' has no effect on its argument.";
Mike Stump11289f42009-09-09 15:08:12 +00001966
Ted Kremenek6bd78702009-04-29 18:50:19 +00001967 // Nothing more to say.
1968 break;
1969 }
Mike Stump11289f42009-09-09 15:08:12 +00001970
1971 // Determine if the typestate has changed.
Ted Kremenek6bd78702009-04-29 18:50:19 +00001972 if (!(PrevV == CurrV))
1973 switch (CurrV.getKind()) {
1974 case RefVal::Owned:
1975 case RefVal::NotOwned:
Mike Stump11289f42009-09-09 15:08:12 +00001976
Ted Kremenek3a0516b2009-05-08 20:01:42 +00001977 if (PrevV.getCount() == CurrV.getCount()) {
1978 // Did an autorelease message get sent?
1979 if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
1980 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001981
Zhongxing Xu08a2ede2009-05-12 10:10:00 +00001982 assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount());
Jordan Rose7467f062013-04-23 01:42:25 +00001983 os << "Object autoreleased";
Ted Kremenek3a0516b2009-05-08 20:01:42 +00001984 break;
1985 }
Mike Stump11289f42009-09-09 15:08:12 +00001986
Ted Kremenek6bd78702009-04-29 18:50:19 +00001987 if (PrevV.getCount() > CurrV.getCount())
1988 os << "Reference count decremented.";
1989 else
1990 os << "Reference count incremented.";
Mike Stump11289f42009-09-09 15:08:12 +00001991
Ted Kremenek6bd78702009-04-29 18:50:19 +00001992 if (unsigned Count = CurrV.getCount())
1993 os << " The object now has a +" << Count << " retain count.";
Mike Stump11289f42009-09-09 15:08:12 +00001994
Ted Kremenek6bd78702009-04-29 18:50:19 +00001995 if (PrevV.getKind() == RefVal::Released) {
Jordy Rose7a534982011-08-24 05:47:39 +00001996 assert(GCEnabled && CurrV.getCount() > 0);
Jordy Rose78373e52012-03-17 05:49:15 +00001997 os << " The object is not eligible for garbage collection until "
1998 "the retain count reaches 0 again.";
Ted Kremenek6bd78702009-04-29 18:50:19 +00001999 }
Mike Stump11289f42009-09-09 15:08:12 +00002000
Ted Kremenek6bd78702009-04-29 18:50:19 +00002001 break;
Mike Stump11289f42009-09-09 15:08:12 +00002002
Ted Kremenek6bd78702009-04-29 18:50:19 +00002003 case RefVal::Released:
2004 os << "Object released.";
2005 break;
Mike Stump11289f42009-09-09 15:08:12 +00002006
Ted Kremenek6bd78702009-04-29 18:50:19 +00002007 case RefVal::ReturnedOwned:
Jordy Rose78373e52012-03-17 05:49:15 +00002008 // Autoreleases can be applied after marking a node ReturnedOwned.
2009 if (CurrV.getAutoreleaseCount())
2010 return NULL;
2011
2012 os << "Object returned to caller as an owning reference (single "
2013 "retain count transferred to caller)";
Ted Kremenek6bd78702009-04-29 18:50:19 +00002014 break;
Mike Stump11289f42009-09-09 15:08:12 +00002015
Ted Kremenek6bd78702009-04-29 18:50:19 +00002016 case RefVal::ReturnedNotOwned:
Ted Kremenekf2301982011-05-26 18:45:44 +00002017 os << "Object returned to caller with a +0 retain count";
Ted Kremenek6bd78702009-04-29 18:50:19 +00002018 break;
Mike Stump11289f42009-09-09 15:08:12 +00002019
Ted Kremenek6bd78702009-04-29 18:50:19 +00002020 default:
2021 return NULL;
2022 }
Mike Stump11289f42009-09-09 15:08:12 +00002023
Ted Kremenek6bd78702009-04-29 18:50:19 +00002024 // Emit any remaining diagnostics for the argument effects (if any).
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002025 for (SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
Ted Kremenek6bd78702009-04-29 18:50:19 +00002026 E=AEffects.end(); I != E; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +00002027
Ted Kremenek6bd78702009-04-29 18:50:19 +00002028 // A bunch of things have alternate behavior under GC.
Jordy Rose7a534982011-08-24 05:47:39 +00002029 if (GCEnabled)
Ted Kremenek6bd78702009-04-29 18:50:19 +00002030 switch (*I) {
2031 default: break;
2032 case Autorelease:
2033 os << "In GC mode an 'autorelease' has no effect.";
2034 continue;
2035 case IncRefMsg:
2036 os << "In GC mode the 'retain' message has no effect.";
2037 continue;
2038 case DecRefMsg:
2039 os << "In GC mode the 'release' message has no effect.";
2040 continue;
2041 }
2042 }
Mike Stump11289f42009-09-09 15:08:12 +00002043 } while (0);
2044
Ted Kremenek6bd78702009-04-29 18:50:19 +00002045 if (os.str().empty())
2046 return 0; // We have nothing to say!
Ted Kremenek051a03d2009-05-13 07:12:33 +00002047
David Blaikie87396b92013-02-21 22:23:56 +00002048 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
Anna Zaks3a769bd2011-09-15 01:08:34 +00002049 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
2050 N->getLocationContext());
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002051 PathDiagnosticPiece *P = new PathDiagnosticEventPiece(Pos, os.str());
Mike Stump11289f42009-09-09 15:08:12 +00002052
Ted Kremenek6bd78702009-04-29 18:50:19 +00002053 // Add the range by scanning the children of the statement for any bindings
2054 // to Sym.
Mike Stump11289f42009-09-09 15:08:12 +00002055 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
Ted Kremenekbfd28fd2009-07-22 22:35:28 +00002056 I!=E; ++I)
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002057 if (const Expr *Exp = dyn_cast_or_null<Expr>(*I))
Ted Kremenek632e3b72012-01-06 22:09:28 +00002058 if (CurrSt->getSValAsScalarOrLoc(Exp, LCtx).getAsLocSymbol() == Sym) {
Ted Kremenek6bd78702009-04-29 18:50:19 +00002059 P->addRange(Exp->getSourceRange());
2060 break;
2061 }
Mike Stump11289f42009-09-09 15:08:12 +00002062
Ted Kremenek6bd78702009-04-29 18:50:19 +00002063 return P;
2064}
2065
Anna Zaks75de3232012-02-28 22:39:22 +00002066// Find the first node in the current function context that referred to the
2067// tracked symbol and the memory location that value was stored to. Note, the
2068// value is only reported if the allocation occurred in the same function as
Anna Zakse51362e2013-04-10 21:42:06 +00002069// the leak. The function can also return a location context, which should be
2070// treated as interesting.
2071struct AllocationInfo {
2072 const ExplodedNode* N;
Anna Zaks3f303be2013-04-10 22:56:30 +00002073 const MemRegion *R;
Anna Zakse51362e2013-04-10 21:42:06 +00002074 const LocationContext *InterestingMethodContext;
Anna Zaks3f303be2013-04-10 22:56:30 +00002075 AllocationInfo(const ExplodedNode *InN,
2076 const MemRegion *InR,
Anna Zakse51362e2013-04-10 21:42:06 +00002077 const LocationContext *InInterestingMethodContext) :
2078 N(InN), R(InR), InterestingMethodContext(InInterestingMethodContext) {}
2079};
2080
2081static AllocationInfo
Ted Kremenek001fd5b2011-08-15 22:09:50 +00002082GetAllocationSite(ProgramStateManager& StateMgr, const ExplodedNode *N,
Ted Kremenek6bd78702009-04-29 18:50:19 +00002083 SymbolRef Sym) {
Anna Zakse51362e2013-04-10 21:42:06 +00002084 const ExplodedNode *AllocationNode = N;
2085 const ExplodedNode *AllocationNodeInCurrentContext = N;
Mike Stump11289f42009-09-09 15:08:12 +00002086 const MemRegion* FirstBinding = 0;
Anna Zaks75de3232012-02-28 22:39:22 +00002087 const LocationContext *LeakContext = N->getLocationContext();
Mike Stump11289f42009-09-09 15:08:12 +00002088
Anna Zakse51362e2013-04-10 21:42:06 +00002089 // The location context of the init method called on the leaked object, if
2090 // available.
2091 const LocationContext *InitMethodContext = 0;
2092
Ted Kremenek6bd78702009-04-29 18:50:19 +00002093 while (N) {
Ted Kremenek49b1e382012-01-26 21:29:00 +00002094 ProgramStateRef St = N->getState();
Anna Zakse51362e2013-04-10 21:42:06 +00002095 const LocationContext *NContext = N->getLocationContext();
Mike Stump11289f42009-09-09 15:08:12 +00002096
Anna Zaksf5788c72012-08-14 00:36:15 +00002097 if (!getRefBinding(St, Sym))
Ted Kremenek6bd78702009-04-29 18:50:19 +00002098 break;
Mike Stump11289f42009-09-09 15:08:12 +00002099
Anna Zaks6797d6e2012-03-21 19:45:01 +00002100 StoreManager::FindUniqueBinding FB(Sym);
Mike Stump11289f42009-09-09 15:08:12 +00002101 StateMgr.iterBindings(St, FB);
Anna Zakse51362e2013-04-10 21:42:06 +00002102
Anna Zaks7c19abe2013-04-10 21:42:02 +00002103 if (FB) {
2104 const MemRegion *R = FB.getRegion();
Anna Zaks07804ef2013-04-10 22:56:33 +00002105 const VarRegion *VR = R->getBaseRegion()->getAs<VarRegion>();
Anna Zaks7c19abe2013-04-10 21:42:02 +00002106 // Do not show local variables belonging to a function other than
2107 // where the error is reported.
2108 if (!VR || VR->getStackFrame() == LeakContext->getCurrentStackFrame())
Anna Zakse51362e2013-04-10 21:42:06 +00002109 FirstBinding = R;
Anna Zaks7c19abe2013-04-10 21:42:02 +00002110 }
Mike Stump11289f42009-09-09 15:08:12 +00002111
Anna Zakse51362e2013-04-10 21:42:06 +00002112 // AllocationNode is the last node in which the symbol was tracked.
2113 AllocationNode = N;
2114
2115 // AllocationNodeInCurrentContext, is the last node in the current context
2116 // in which the symbol was tracked.
2117 if (NContext == LeakContext)
2118 AllocationNodeInCurrentContext = N;
2119
Anna Zaks3f303be2013-04-10 22:56:30 +00002120 // Find the last init that was called on the given symbol and store the
2121 // init method's location context.
2122 if (!InitMethodContext)
2123 if (Optional<CallEnter> CEP = N->getLocation().getAs<CallEnter>()) {
2124 const Stmt *CE = CEP->getCallExpr();
Anna Zaks99394bb2013-04-25 00:41:32 +00002125 if (const ObjCMessageExpr *ME = dyn_cast_or_null<ObjCMessageExpr>(CE)) {
Anna Zaks3f303be2013-04-10 22:56:30 +00002126 const Stmt *RecExpr = ME->getInstanceReceiver();
2127 if (RecExpr) {
2128 SVal RecV = St->getSVal(RecExpr, NContext);
2129 if (ME->getMethodFamily() == OMF_init && RecV.getAsSymbol() == Sym)
2130 InitMethodContext = CEP->getCalleeContext();
2131 }
2132 }
Anna Zakse51362e2013-04-10 21:42:06 +00002133 }
Anna Zaks75de3232012-02-28 22:39:22 +00002134
Mike Stump11289f42009-09-09 15:08:12 +00002135 N = N->pred_empty() ? NULL : *(N->pred_begin());
Ted Kremenek6bd78702009-04-29 18:50:19 +00002136 }
Mike Stump11289f42009-09-09 15:08:12 +00002137
Anna Zakse51362e2013-04-10 21:42:06 +00002138 // If we are reporting a leak of the object that was allocated with alloc,
Anna Zaks3f303be2013-04-10 22:56:30 +00002139 // mark its init method as interesting.
Anna Zakse51362e2013-04-10 21:42:06 +00002140 const LocationContext *InterestingMethodContext = 0;
2141 if (InitMethodContext) {
2142 const ProgramPoint AllocPP = AllocationNode->getLocation();
2143 if (Optional<StmtPoint> SP = AllocPP.getAs<StmtPoint>())
2144 if (const ObjCMessageExpr *ME = SP->getStmtAs<ObjCMessageExpr>())
2145 if (ME->getMethodFamily() == OMF_alloc)
2146 InterestingMethodContext = InitMethodContext;
2147 }
2148
Anna Zaks75de3232012-02-28 22:39:22 +00002149 // If allocation happened in a function different from the leak node context,
2150 // do not report the binding.
Ted Kremenekb045b012012-10-12 22:56:40 +00002151 assert(N && "Could not find allocation node");
Anna Zaks75de3232012-02-28 22:39:22 +00002152 if (N->getLocationContext() != LeakContext) {
2153 FirstBinding = 0;
2154 }
2155
Anna Zakse51362e2013-04-10 21:42:06 +00002156 return AllocationInfo(AllocationNodeInCurrentContext,
2157 FirstBinding,
2158 InterestingMethodContext);
Ted Kremenek6bd78702009-04-29 18:50:19 +00002159}
2160
2161PathDiagnosticPiece*
Anna Zaks88255cc2011-08-20 01:27:22 +00002162CFRefReportVisitor::getEndPath(BugReporterContext &BRC,
2163 const ExplodedNode *EndN,
2164 BugReport &BR) {
Ted Kremenek1e809b42012-03-09 01:13:14 +00002165 BR.markInteresting(Sym);
Anna Zaks88255cc2011-08-20 01:27:22 +00002166 return BugReporterVisitor::getDefaultEndPath(BRC, EndN, BR);
Ted Kremenek6bd78702009-04-29 18:50:19 +00002167}
2168
2169PathDiagnosticPiece*
Anna Zaks88255cc2011-08-20 01:27:22 +00002170CFRefLeakReportVisitor::getEndPath(BugReporterContext &BRC,
2171 const ExplodedNode *EndN,
2172 BugReport &BR) {
Mike Stump11289f42009-09-09 15:08:12 +00002173
Ted Kremenekbb8d5462009-05-06 21:39:49 +00002174 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenek6bd78702009-04-29 18:50:19 +00002175 // assigned to different variables, etc.
Ted Kremenek1e809b42012-03-09 01:13:14 +00002176 BR.markInteresting(Sym);
Mike Stump11289f42009-09-09 15:08:12 +00002177
Ted Kremenek6bd78702009-04-29 18:50:19 +00002178 // We are reporting a leak. Walk up the graph to get to the first node where
2179 // the symbol appeared, and also get the first VarDecl that tracked object
2180 // is stored to.
Anna Zakse51362e2013-04-10 21:42:06 +00002181 AllocationInfo AllocI =
Ted Kremenek8c8fb482009-05-08 23:32:51 +00002182 GetAllocationSite(BRC.getStateManager(), EndN, Sym);
Mike Stump11289f42009-09-09 15:08:12 +00002183
Anna Zakse51362e2013-04-10 21:42:06 +00002184 const MemRegion* FirstBinding = AllocI.R;
2185 BR.markInteresting(AllocI.InterestingMethodContext);
2186
Anna Zaks921f0492011-09-15 18:56:07 +00002187 SourceManager& SM = BRC.getSourceManager();
Mike Stump11289f42009-09-09 15:08:12 +00002188
Ted Kremenek6bd78702009-04-29 18:50:19 +00002189 // Compute an actual location for the leak. Sometimes a leak doesn't
2190 // occur at an actual statement (e.g., transition between blocks; end
2191 // of function) so we need to walk the graph and compute a real location.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002192 const ExplodedNode *LeakN = EndN;
Anna Zaks921f0492011-09-15 18:56:07 +00002193 PathDiagnosticLocation L = PathDiagnosticLocation::createEndOfPath(LeakN, SM);
Mike Stump11289f42009-09-09 15:08:12 +00002194
Ted Kremenek6bd78702009-04-29 18:50:19 +00002195 std::string sbuf;
2196 llvm::raw_string_ostream os(sbuf);
Mike Stump11289f42009-09-09 15:08:12 +00002197
Ted Kremenekf2301982011-05-26 18:45:44 +00002198 os << "Object leaked: ";
Mike Stump11289f42009-09-09 15:08:12 +00002199
Ted Kremenekf2301982011-05-26 18:45:44 +00002200 if (FirstBinding) {
2201 os << "object allocated and stored into '"
2202 << FirstBinding->getString() << '\'';
2203 }
2204 else
2205 os << "allocated object";
Mike Stump11289f42009-09-09 15:08:12 +00002206
Ted Kremenek6bd78702009-04-29 18:50:19 +00002207 // Get the retain count.
Anna Zaksf5788c72012-08-14 00:36:15 +00002208 const RefVal* RV = getRefBinding(EndN->getState(), Sym);
Ted Kremenekb045b012012-10-12 22:56:40 +00002209 assert(RV);
Mike Stump11289f42009-09-09 15:08:12 +00002210
Ted Kremenek6bd78702009-04-29 18:50:19 +00002211 if (RV->getKind() == RefVal::ErrorLeakReturned) {
2212 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
Jordy Rose43426f82011-07-15 22:17:54 +00002213 // objects. Only "copy", "alloc", "retain" and "new" transfer ownership
Ted Kremenek6bd78702009-04-29 18:50:19 +00002214 // to the caller for NS objects.
Ted Kremenek8e2c9b02011-05-25 06:19:45 +00002215 const Decl *D = &EndN->getCodeDecl();
Ted Kremenek2a786952012-09-06 23:03:07 +00002216
2217 os << (isa<ObjCMethodDecl>(D) ? " is returned from a method "
2218 : " is returned from a function ");
2219
Aaron Ballman9ead1242013-12-19 02:39:40 +00002220 if (D->hasAttr<CFReturnsNotRetainedAttr>())
Ted Kremenek2a786952012-09-06 23:03:07 +00002221 os << "that is annotated as CF_RETURNS_NOT_RETAINED";
Aaron Ballman9ead1242013-12-19 02:39:40 +00002222 else if (D->hasAttr<NSReturnsNotRetainedAttr>())
Ted Kremenek2a786952012-09-06 23:03:07 +00002223 os << "that is annotated as NS_RETURNS_NOT_RETAINED";
Ted Kremenek8e2c9b02011-05-25 06:19:45 +00002224 else {
Ted Kremenek2a786952012-09-06 23:03:07 +00002225 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2226 os << "whose name ('" << MD->getSelector().getAsString()
2227 << "') does not start with 'copy', 'mutableCopy', 'alloc' or 'new'."
2228 " This violates the naming convention rules"
2229 " given in the Memory Management Guide for Cocoa";
2230 }
2231 else {
2232 const FunctionDecl *FD = cast<FunctionDecl>(D);
2233 os << "whose name ('" << *FD
2234 << "') does not contain 'Copy' or 'Create'. This violates the naming"
2235 " convention rules given in the Memory Management Guide for Core"
2236 " Foundation";
2237 }
2238 }
Ted Kremenek6bd78702009-04-29 18:50:19 +00002239 }
Ted Kremenekdee56e32009-05-10 06:25:57 +00002240 else if (RV->getKind() == RefVal::ErrorGCLeakReturned) {
David Blaikie3cbec0f2013-02-21 22:37:44 +00002241 const ObjCMethodDecl &MD = cast<ObjCMethodDecl>(EndN->getCodeDecl());
Ted Kremenekdee56e32009-05-10 06:25:57 +00002242 os << " and returned from method '" << MD.getSelector().getAsString()
Ted Kremenek1f8e4342009-05-10 16:52:15 +00002243 << "' is potentially leaked when using garbage collection. Callers "
2244 "of this method do not expect a returned object with a +1 retain "
2245 "count since they expect the object to be managed by the garbage "
2246 "collector";
Ted Kremenekdee56e32009-05-10 06:25:57 +00002247 }
Ted Kremenek6bd78702009-04-29 18:50:19 +00002248 else
Ted Kremenek4f63ac72010-10-15 22:50:23 +00002249 os << " is not referenced later in this execution path and has a retain "
Ted Kremenekf2301982011-05-26 18:45:44 +00002250 "count of +" << RV->getCount();
Mike Stump11289f42009-09-09 15:08:12 +00002251
Ted Kremenek6bd78702009-04-29 18:50:19 +00002252 return new PathDiagnosticEventPiece(L, os.str());
2253}
2254
Jordy Rose184bd142011-08-24 22:39:09 +00002255CFRefLeakReport::CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts,
2256 bool GCEnabled, const SummaryLogTy &Log,
2257 ExplodedNode *n, SymbolRef sym,
Ted Kremenek8671acb2013-04-16 21:44:22 +00002258 CheckerContext &Ctx,
2259 bool IncludeAllocationLine)
2260 : CFRefReport(D, LOpts, GCEnabled, Log, n, sym, false) {
Mike Stump11289f42009-09-09 15:08:12 +00002261
Chris Lattner57540c52011-04-15 05:22:18 +00002262 // Most bug reports are cached at the location where they occurred.
Ted Kremenek6bd78702009-04-29 18:50:19 +00002263 // With leaks, we want to unique them by the location where they were
2264 // allocated, and only report a single path. To do this, we need to find
2265 // the allocation site of a piece of tracked memory, which we do via a
2266 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2267 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2268 // that all ancestor nodes that represent the allocation site have the
2269 // same SourceLocation.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002270 const ExplodedNode *AllocNode = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002271
Anna Zaks58734db2011-10-25 19:57:11 +00002272 const SourceManager& SMgr = Ctx.getSourceManager();
Anna Zaksc29bed32011-09-20 21:38:35 +00002273
Anna Zakse51362e2013-04-10 21:42:06 +00002274 AllocationInfo AllocI =
Anna Zaks58734db2011-10-25 19:57:11 +00002275 GetAllocationSite(Ctx.getStateManager(), getErrorNode(), sym);
Mike Stump11289f42009-09-09 15:08:12 +00002276
Anna Zakse51362e2013-04-10 21:42:06 +00002277 AllocNode = AllocI.N;
2278 AllocBinding = AllocI.R;
2279 markInteresting(AllocI.InterestingMethodContext);
2280
Ted Kremenek6bd78702009-04-29 18:50:19 +00002281 // Get the SourceLocation for the allocation site.
Jordan Rosefbe6dba2012-07-10 22:07:52 +00002282 // FIXME: This will crash the analyzer if an allocation comes from an
2283 // implicit call. (Currently there are no such allocations in Cocoa, though.)
2284 const Stmt *AllocStmt;
Ted Kremenek6bd78702009-04-29 18:50:19 +00002285 ProgramPoint P = AllocNode->getLocation();
David Blaikie87396b92013-02-21 22:23:56 +00002286 if (Optional<CallExitEnd> Exit = P.getAs<CallExitEnd>())
Jordan Rosefbe6dba2012-07-10 22:07:52 +00002287 AllocStmt = Exit->getCalleeContext()->getCallSite();
2288 else
David Blaikie87396b92013-02-21 22:23:56 +00002289 AllocStmt = P.castAs<PostStmt>().getStmt();
Jordan Rosefbe6dba2012-07-10 22:07:52 +00002290 assert(AllocStmt && "All allocations must come from explicit calls");
Anna Zaks40402872013-04-23 23:57:50 +00002291
2292 PathDiagnosticLocation AllocLocation =
2293 PathDiagnosticLocation::createBegin(AllocStmt, SMgr,
2294 AllocNode->getLocationContext());
2295 Location = AllocLocation;
2296
2297 // Set uniqieing info, which will be used for unique the bug reports. The
2298 // leaks should be uniqued on the allocation site.
2299 UniqueingLocation = AllocLocation;
2300 UniqueingDecl = AllocNode->getLocationContext()->getDecl();
2301
Ted Kremenek6bd78702009-04-29 18:50:19 +00002302 // Fill in the description of the bug.
2303 Description.clear();
2304 llvm::raw_string_ostream os(Description);
Ted Kremenekf1e76672009-05-02 19:05:19 +00002305 os << "Potential leak ";
Jordy Rose184bd142011-08-24 22:39:09 +00002306 if (GCEnabled)
Ted Kremenekf1e76672009-05-02 19:05:19 +00002307 os << "(when using garbage collection) ";
Anna Zaks16f38312012-02-28 21:49:08 +00002308 os << "of an object";
Mike Stump11289f42009-09-09 15:08:12 +00002309
Ted Kremenek8671acb2013-04-16 21:44:22 +00002310 if (AllocBinding) {
Anna Zaks16f38312012-02-28 21:49:08 +00002311 os << " stored into '" << AllocBinding->getString() << '\'';
Ted Kremenek8671acb2013-04-16 21:44:22 +00002312 if (IncludeAllocationLine) {
2313 FullSourceLoc SL(AllocStmt->getLocStart(), Ctx.getSourceManager());
2314 os << " (allocated on line " << SL.getSpellingLineNumber() << ")";
2315 }
2316 }
Anna Zaks071a89c2011-08-19 23:21:56 +00002317
Jordy Rose184bd142011-08-24 22:39:09 +00002318 addVisitor(new CFRefLeakReportVisitor(sym, GCEnabled, Log));
Ted Kremenek6bd78702009-04-29 18:50:19 +00002319}
2320
2321//===----------------------------------------------------------------------===//
2322// Main checker logic.
2323//===----------------------------------------------------------------------===//
2324
Ted Kremenek70a87882009-11-25 22:17:44 +00002325namespace {
Jordy Rose75e680e2011-09-02 06:44:22 +00002326class RetainCountChecker
Jordy Rose5df640d2011-08-24 18:56:32 +00002327 : public Checker< check::Bind,
Jordy Rose78612762011-08-23 19:01:07 +00002328 check::DeadSymbols,
Jordy Rose5df640d2011-08-24 18:56:32 +00002329 check::EndAnalysis,
Anna Zaks3fdcc0b2013-01-03 00:25:29 +00002330 check::EndFunction,
Jordy Rose217eb902011-08-17 21:27:39 +00002331 check::PostStmt<BlockExpr>,
John McCall31168b02011-06-15 23:02:42 +00002332 check::PostStmt<CastExpr>,
Ted Kremenek415287d2012-03-06 20:06:12 +00002333 check::PostStmt<ObjCArrayLiteral>,
2334 check::PostStmt<ObjCDictionaryLiteral>,
Jordy Rose6393f822012-05-12 05:10:43 +00002335 check::PostStmt<ObjCBoxedExpr>,
Jordan Rose682b3162012-07-02 19:28:21 +00002336 check::PostCall,
Jordy Rose298cc4d2011-08-23 19:43:16 +00002337 check::PreStmt<ReturnStmt>,
Jordy Rose217eb902011-08-17 21:27:39 +00002338 check::RegionChanges,
Jordy Rose898a1482011-08-21 21:58:18 +00002339 eval::Assume,
2340 eval::Call > {
Dylan Noblesmithe2778992012-02-05 02:12:40 +00002341 mutable OwningPtr<CFRefBug> useAfterRelease, releaseNotOwned;
2342 mutable OwningPtr<CFRefBug> deallocGC, deallocNotOwned;
2343 mutable OwningPtr<CFRefBug> overAutorelease, returnNotOwnedForOwned;
2344 mutable OwningPtr<CFRefBug> leakWithinFunction, leakAtReturn;
2345 mutable OwningPtr<CFRefBug> leakWithinFunctionGC, leakAtReturnGC;
Jordy Rose78612762011-08-23 19:01:07 +00002346
2347 typedef llvm::DenseMap<SymbolRef, const SimpleProgramPointTag *> SymbolTagMap;
2348
2349 // This map is only used to ensure proper deletion of any allocated tags.
2350 mutable SymbolTagMap DeadSymbolTags;
2351
Dylan Noblesmithe2778992012-02-05 02:12:40 +00002352 mutable OwningPtr<RetainSummaryManager> Summaries;
2353 mutable OwningPtr<RetainSummaryManager> SummariesGC;
Jordy Rose5df640d2011-08-24 18:56:32 +00002354 mutable SummaryLogTy SummaryLog;
2355 mutable bool ShouldResetSummaryLog;
2356
Ted Kremenek8671acb2013-04-16 21:44:22 +00002357 /// Optional setting to indicate if leak reports should include
2358 /// the allocation line.
2359 mutable bool IncludeAllocationLine;
2360
Jordy Rosea8f99ba2011-08-20 21:17:59 +00002361public:
Ted Kremenek8671acb2013-04-16 21:44:22 +00002362 RetainCountChecker(AnalyzerOptions &AO)
2363 : ShouldResetSummaryLog(false),
2364 IncludeAllocationLine(shouldIncludeAllocationSiteInLeakDiagnostics(AO)) {}
Jordy Rose78612762011-08-23 19:01:07 +00002365
Jordy Rose75e680e2011-09-02 06:44:22 +00002366 virtual ~RetainCountChecker() {
Jordy Rose78612762011-08-23 19:01:07 +00002367 DeleteContainerSeconds(DeadSymbolTags);
2368 }
2369
Jordy Rose5df640d2011-08-24 18:56:32 +00002370 void checkEndAnalysis(ExplodedGraph &G, BugReporter &BR,
2371 ExprEngine &Eng) const {
2372 // FIXME: This is a hack to make sure the summary log gets cleared between
2373 // analyses of different code bodies.
2374 //
2375 // Why is this necessary? Because a checker's lifetime is tied to a
2376 // translation unit, but an ExplodedGraph's lifetime is just a code body.
2377 // Once in a blue moon, a new ExplodedNode will have the same address as an
2378 // old one with an associated summary, and the bug report visitor gets very
2379 // confused. (To make things worse, the summary lifetime is currently also
2380 // tied to a code body, so we get a crash instead of incorrect results.)
Jordy Rose95589f12011-08-24 09:27:24 +00002381 //
2382 // Why is this a bad solution? Because if the lifetime of the ExplodedGraph
2383 // changes, things will start going wrong again. Really the lifetime of this
2384 // log needs to be tied to either the specific nodes in it or the entire
2385 // ExplodedGraph, not to a specific part of the code being analyzed.
2386 //
Jordy Rose5df640d2011-08-24 18:56:32 +00002387 // (Also, having stateful local data means that the same checker can't be
2388 // used from multiple threads, but a lot of checkers have incorrect
2389 // assumptions about that anyway. So that wasn't a priority at the time of
2390 // this fix.)
Jordy Rose95589f12011-08-24 09:27:24 +00002391 //
Jordy Rose5df640d2011-08-24 18:56:32 +00002392 // This happens at the end of analysis, but bug reports are emitted /after/
2393 // this point. So we can't just clear the summary log now. Instead, we mark
2394 // that the next time we access the summary log, it should be cleared.
2395
2396 // If we never reset the summary log during /this/ code body analysis,
2397 // there were no new summaries. There might still have been summaries from
2398 // the /last/ analysis, so clear them out to make sure the bug report
2399 // visitors don't get confused.
2400 if (ShouldResetSummaryLog)
2401 SummaryLog.clear();
2402
2403 ShouldResetSummaryLog = !SummaryLog.empty();
Jordy Rose95589f12011-08-24 09:27:24 +00002404 }
2405
Jordy Rosec49ec532011-09-02 05:55:19 +00002406 CFRefBug *getLeakWithinFunctionBug(const LangOptions &LOpts,
2407 bool GCEnabled) const {
2408 if (GCEnabled) {
Jordy Rose15484da2011-08-25 01:14:38 +00002409 if (!leakWithinFunctionGC)
Benjamin Kramerd1d76b22012-06-06 17:32:50 +00002410 leakWithinFunctionGC.reset(new Leak("Leak of object when using "
2411 "garbage collection"));
Jordy Rosec49ec532011-09-02 05:55:19 +00002412 return leakWithinFunctionGC.get();
Jordy Rose15484da2011-08-25 01:14:38 +00002413 } else {
2414 if (!leakWithinFunction) {
Douglas Gregor79a91412011-09-13 17:21:33 +00002415 if (LOpts.getGC() == LangOptions::HybridGC) {
Benjamin Kramerd1d76b22012-06-06 17:32:50 +00002416 leakWithinFunction.reset(new Leak("Leak of object when not using "
2417 "garbage collection (GC) in "
2418 "dual GC/non-GC code"));
Jordy Rose15484da2011-08-25 01:14:38 +00002419 } else {
Benjamin Kramerd1d76b22012-06-06 17:32:50 +00002420 leakWithinFunction.reset(new Leak("Leak"));
Jordy Rose15484da2011-08-25 01:14:38 +00002421 }
2422 }
Jordy Rosec49ec532011-09-02 05:55:19 +00002423 return leakWithinFunction.get();
Jordy Rose15484da2011-08-25 01:14:38 +00002424 }
2425 }
2426
Jordy Rosec49ec532011-09-02 05:55:19 +00002427 CFRefBug *getLeakAtReturnBug(const LangOptions &LOpts, bool GCEnabled) const {
2428 if (GCEnabled) {
Jordy Rose15484da2011-08-25 01:14:38 +00002429 if (!leakAtReturnGC)
Benjamin Kramerd1d76b22012-06-06 17:32:50 +00002430 leakAtReturnGC.reset(new Leak("Leak of returned object when using "
2431 "garbage collection"));
Jordy Rosec49ec532011-09-02 05:55:19 +00002432 return leakAtReturnGC.get();
Jordy Rose15484da2011-08-25 01:14:38 +00002433 } else {
2434 if (!leakAtReturn) {
Douglas Gregor79a91412011-09-13 17:21:33 +00002435 if (LOpts.getGC() == LangOptions::HybridGC) {
Benjamin Kramerd1d76b22012-06-06 17:32:50 +00002436 leakAtReturn.reset(new Leak("Leak of returned object when not using "
2437 "garbage collection (GC) in dual "
2438 "GC/non-GC code"));
Jordy Rose15484da2011-08-25 01:14:38 +00002439 } else {
Benjamin Kramerd1d76b22012-06-06 17:32:50 +00002440 leakAtReturn.reset(new Leak("Leak of returned object"));
Jordy Rose15484da2011-08-25 01:14:38 +00002441 }
2442 }
Jordy Rosec49ec532011-09-02 05:55:19 +00002443 return leakAtReturn.get();
Jordy Rose15484da2011-08-25 01:14:38 +00002444 }
2445 }
2446
Jordy Rosec49ec532011-09-02 05:55:19 +00002447 RetainSummaryManager &getSummaryManager(ASTContext &Ctx,
2448 bool GCEnabled) const {
2449 // FIXME: We don't support ARC being turned on and off during one analysis.
2450 // (nor, for that matter, do we support changing ASTContexts)
David Blaikiebbafb8a2012-03-11 07:00:24 +00002451 bool ARCEnabled = (bool)Ctx.getLangOpts().ObjCAutoRefCount;
Jordy Rosec49ec532011-09-02 05:55:19 +00002452 if (GCEnabled) {
2453 if (!SummariesGC)
Jordy Rose8b289a22011-08-25 00:10:37 +00002454 SummariesGC.reset(new RetainSummaryManager(Ctx, true, ARCEnabled));
Jordy Rosec49ec532011-09-02 05:55:19 +00002455 else
2456 assert(SummariesGC->isARCEnabled() == ARCEnabled);
Jordy Rose8b289a22011-08-25 00:10:37 +00002457 return *SummariesGC;
2458 } else {
Jordy Rosec49ec532011-09-02 05:55:19 +00002459 if (!Summaries)
Jordy Rose8b289a22011-08-25 00:10:37 +00002460 Summaries.reset(new RetainSummaryManager(Ctx, false, ARCEnabled));
Jordy Rosec49ec532011-09-02 05:55:19 +00002461 else
2462 assert(Summaries->isARCEnabled() == ARCEnabled);
Jordy Rose8b289a22011-08-25 00:10:37 +00002463 return *Summaries;
2464 }
2465 }
2466
Jordy Rosec49ec532011-09-02 05:55:19 +00002467 RetainSummaryManager &getSummaryManager(CheckerContext &C) const {
2468 return getSummaryManager(C.getASTContext(), C.isObjCGCEnabled());
2469 }
2470
Ted Kremenek49b1e382012-01-26 21:29:00 +00002471 void printState(raw_ostream &Out, ProgramStateRef State,
Jordy Rose58a20d32011-08-28 19:11:56 +00002472 const char *NL, const char *Sep) const;
2473
Anna Zaks3e0f4152011-10-06 00:43:15 +00002474 void checkBind(SVal loc, SVal val, const Stmt *S, CheckerContext &C) const;
Jordy Rose5c252ef2011-08-20 21:16:58 +00002475 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
2476 void checkPostStmt(const CastExpr *CE, CheckerContext &C) const;
John McCall31168b02011-06-15 23:02:42 +00002477
Ted Kremenek415287d2012-03-06 20:06:12 +00002478 void checkPostStmt(const ObjCArrayLiteral *AL, CheckerContext &C) const;
2479 void checkPostStmt(const ObjCDictionaryLiteral *DL, CheckerContext &C) const;
Jordy Rose6393f822012-05-12 05:10:43 +00002480 void checkPostStmt(const ObjCBoxedExpr *BE, CheckerContext &C) const;
2481
Jordan Rose682b3162012-07-02 19:28:21 +00002482 void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
Ted Kremenek415287d2012-03-06 20:06:12 +00002483
Jordan Roseeec15392012-07-02 19:27:43 +00002484 void checkSummary(const RetainSummary &Summ, const CallEvent &Call,
Jordy Rosed188d662011-08-28 05:16:28 +00002485 CheckerContext &C) const;
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002486
Anna Zaks25612732012-08-29 23:23:43 +00002487 void processSummaryOfInlined(const RetainSummary &Summ,
2488 const CallEvent &Call,
2489 CheckerContext &C) const;
2490
Jordy Rose898a1482011-08-21 21:58:18 +00002491 bool evalCall(const CallExpr *CE, CheckerContext &C) const;
2492
Ted Kremenek49b1e382012-01-26 21:29:00 +00002493 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Jordy Rose5c252ef2011-08-20 21:16:58 +00002494 bool Assumption) const;
Jordy Rose217eb902011-08-17 21:27:39 +00002495
Ted Kremenek49b1e382012-01-26 21:29:00 +00002496 ProgramStateRef
2497 checkRegionChanges(ProgramStateRef state,
Anna Zaksdc154152012-12-20 00:38:25 +00002498 const InvalidatedSymbols *invalidated,
Jordy Rose1fad6632011-08-27 22:51:26 +00002499 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks3d348342012-02-14 21:55:24 +00002500 ArrayRef<const MemRegion *> Regions,
Jordan Rose742920c2012-07-02 19:27:35 +00002501 const CallEvent *Call) const;
Jordy Rose5c252ef2011-08-20 21:16:58 +00002502
Ted Kremenek49b1e382012-01-26 21:29:00 +00002503 bool wantsRegionChangeUpdate(ProgramStateRef state) const {
Jordy Rosea8f99ba2011-08-20 21:17:59 +00002504 return true;
Jordy Rose5c252ef2011-08-20 21:16:58 +00002505 }
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002506
Jordy Rose298cc4d2011-08-23 19:43:16 +00002507 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
2508 void checkReturnWithRetEffect(const ReturnStmt *S, CheckerContext &C,
2509 ExplodedNode *Pred, RetEffect RE, RefVal X,
Ted Kremenek49b1e382012-01-26 21:29:00 +00002510 SymbolRef Sym, ProgramStateRef state) const;
Jordy Rose298cc4d2011-08-23 19:43:16 +00002511
Jordy Rose78612762011-08-23 19:01:07 +00002512 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Anna Zaks3fdcc0b2013-01-03 00:25:29 +00002513 void checkEndFunction(CheckerContext &C) const;
Jordy Rose78612762011-08-23 19:01:07 +00002514
Ted Kremenek49b1e382012-01-26 21:29:00 +00002515 ProgramStateRef updateSymbol(ProgramStateRef state, SymbolRef sym,
Anna Zaks25612732012-08-29 23:23:43 +00002516 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
2517 CheckerContext &C) const;
Jordy Rosebf77e512011-08-23 20:27:16 +00002518
Ted Kremenek49b1e382012-01-26 21:29:00 +00002519 void processNonLeakError(ProgramStateRef St, SourceRange ErrorRange,
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002520 RefVal::Kind ErrorKind, SymbolRef Sym,
2521 CheckerContext &C) const;
Ted Kremenek415287d2012-03-06 20:06:12 +00002522
2523 void processObjCLiterals(CheckerContext &C, const Expr *Ex) const;
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002524
Jordy Rose78612762011-08-23 19:01:07 +00002525 const ProgramPointTag *getDeadSymbolTag(SymbolRef sym) const;
2526
Ted Kremenek49b1e382012-01-26 21:29:00 +00002527 ProgramStateRef handleSymbolDeath(ProgramStateRef state,
Anna Zaksf5788c72012-08-14 00:36:15 +00002528 SymbolRef sid, RefVal V,
2529 SmallVectorImpl<SymbolRef> &Leaked) const;
Jordy Rose78612762011-08-23 19:01:07 +00002530
Jordan Roseff03c1d2012-12-06 18:58:18 +00002531 ProgramStateRef
Jordan Rose9f61f8a2012-08-18 00:30:16 +00002532 handleAutoreleaseCounts(ProgramStateRef state, ExplodedNode *Pred,
2533 const ProgramPointTag *Tag, CheckerContext &Ctx,
2534 SymbolRef Sym, RefVal V) const;
Jordy Rose6763e382011-08-23 20:07:14 +00002535
Ted Kremenek49b1e382012-01-26 21:29:00 +00002536 ExplodedNode *processLeaks(ProgramStateRef state,
Jordy Rose78612762011-08-23 19:01:07 +00002537 SmallVectorImpl<SymbolRef> &Leaked,
Anna Zaks58734db2011-10-25 19:57:11 +00002538 CheckerContext &Ctx,
Jordy Rose78612762011-08-23 19:01:07 +00002539 ExplodedNode *Pred = 0) const;
Ted Kremenek70a87882009-11-25 22:17:44 +00002540};
2541} // end anonymous namespace
2542
Jordy Rose217eb902011-08-17 21:27:39 +00002543namespace {
2544class StopTrackingCallback : public SymbolVisitor {
Ted Kremenek49b1e382012-01-26 21:29:00 +00002545 ProgramStateRef state;
Jordy Rose217eb902011-08-17 21:27:39 +00002546public:
Ted Kremenek49b1e382012-01-26 21:29:00 +00002547 StopTrackingCallback(ProgramStateRef st) : state(st) {}
2548 ProgramStateRef getState() const { return state; }
Jordy Rose217eb902011-08-17 21:27:39 +00002549
2550 bool VisitSymbol(SymbolRef sym) {
2551 state = state->remove<RefBindings>(sym);
2552 return true;
2553 }
2554};
2555} // end anonymous namespace
2556
Jordy Rose75e680e2011-09-02 06:44:22 +00002557//===----------------------------------------------------------------------===//
2558// Handle statements that may have an effect on refcounts.
2559//===----------------------------------------------------------------------===//
Jordy Rose217eb902011-08-17 21:27:39 +00002560
Jordy Rose75e680e2011-09-02 06:44:22 +00002561void RetainCountChecker::checkPostStmt(const BlockExpr *BE,
2562 CheckerContext &C) const {
Jordy Rose217eb902011-08-17 21:27:39 +00002563
Jordy Rose75e680e2011-09-02 06:44:22 +00002564 // Scan the BlockDecRefExprs for any object the retain count checker
Ted Kremenekbd862712010-07-01 20:16:50 +00002565 // may be tracking.
John McCallc63de662011-02-02 13:00:07 +00002566 if (!BE->getBlockDecl()->hasCaptures())
Ted Kremenekf89dcda2009-11-26 02:38:19 +00002567 return;
Ted Kremenekbd862712010-07-01 20:16:50 +00002568
Ted Kremenek49b1e382012-01-26 21:29:00 +00002569 ProgramStateRef state = C.getState();
Ted Kremenekf89dcda2009-11-26 02:38:19 +00002570 const BlockDataRegion *R =
Ted Kremenek632e3b72012-01-06 22:09:28 +00002571 cast<BlockDataRegion>(state->getSVal(BE,
2572 C.getLocationContext()).getAsRegion());
Ted Kremenekbd862712010-07-01 20:16:50 +00002573
Ted Kremenekf89dcda2009-11-26 02:38:19 +00002574 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
2575 E = R->referenced_vars_end();
Ted Kremenekbd862712010-07-01 20:16:50 +00002576
Ted Kremenekf89dcda2009-11-26 02:38:19 +00002577 if (I == E)
2578 return;
Ted Kremenekbd862712010-07-01 20:16:50 +00002579
Ted Kremenek04af9f22009-12-07 22:05:27 +00002580 // FIXME: For now we invalidate the tracking of all symbols passed to blocks
2581 // via captured variables, even though captured variables result in a copy
2582 // and in implicit increment/decrement of a retain count.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002583 SmallVector<const MemRegion*, 10> Regions;
Anna Zaksc9abbe22011-10-26 21:06:44 +00002584 const LocationContext *LC = C.getLocationContext();
Ted Kremenek90af9092010-12-02 07:49:45 +00002585 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
Ted Kremenekbd862712010-07-01 20:16:50 +00002586
Ted Kremenek04af9f22009-12-07 22:05:27 +00002587 for ( ; I != E; ++I) {
Ted Kremenekbcf90532012-12-06 07:17:20 +00002588 const VarRegion *VR = I.getCapturedRegion();
Ted Kremenek04af9f22009-12-07 22:05:27 +00002589 if (VR->getSuperRegion() == R) {
2590 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2591 }
2592 Regions.push_back(VR);
2593 }
Ted Kremenekbd862712010-07-01 20:16:50 +00002594
Ted Kremenek04af9f22009-12-07 22:05:27 +00002595 state =
2596 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
2597 Regions.data() + Regions.size()).getState();
Anna Zaksda4c8d62011-10-26 21:06:34 +00002598 C.addTransition(state);
Ted Kremenekf89dcda2009-11-26 02:38:19 +00002599}
2600
Jordy Rose75e680e2011-09-02 06:44:22 +00002601void RetainCountChecker::checkPostStmt(const CastExpr *CE,
2602 CheckerContext &C) const {
John McCall31168b02011-06-15 23:02:42 +00002603 const ObjCBridgedCastExpr *BE = dyn_cast<ObjCBridgedCastExpr>(CE);
2604 if (!BE)
2605 return;
2606
John McCall640767f2011-06-17 06:50:50 +00002607 ArgEffect AE = IncRef;
John McCall31168b02011-06-15 23:02:42 +00002608
2609 switch (BE->getBridgeKind()) {
2610 case clang::OBC_Bridge:
2611 // Do nothing.
2612 return;
2613 case clang::OBC_BridgeRetained:
2614 AE = IncRef;
2615 break;
2616 case clang::OBC_BridgeTransfer:
Benjamin Kramer1d5d6342013-10-20 11:53:20 +00002617 AE = DecRefBridgedTransferred;
John McCall31168b02011-06-15 23:02:42 +00002618 break;
2619 }
2620
Ted Kremenek49b1e382012-01-26 21:29:00 +00002621 ProgramStateRef state = C.getState();
Ted Kremenek632e3b72012-01-06 22:09:28 +00002622 SymbolRef Sym = state->getSVal(CE, C.getLocationContext()).getAsLocSymbol();
John McCall31168b02011-06-15 23:02:42 +00002623 if (!Sym)
2624 return;
Anna Zaksf5788c72012-08-14 00:36:15 +00002625 const RefVal* T = getRefBinding(state, Sym);
John McCall31168b02011-06-15 23:02:42 +00002626 if (!T)
2627 return;
2628
John McCall31168b02011-06-15 23:02:42 +00002629 RefVal::Kind hasErr = (RefVal::Kind) 0;
Jordy Rosec49ec532011-09-02 05:55:19 +00002630 state = updateSymbol(state, Sym, *T, AE, hasErr, C);
John McCall31168b02011-06-15 23:02:42 +00002631
2632 if (hasErr) {
Jordy Rosebf77e512011-08-23 20:27:16 +00002633 // FIXME: If we get an error during a bridge cast, should we report it?
2634 // Should we assert that there is no error?
John McCall31168b02011-06-15 23:02:42 +00002635 return;
2636 }
2637
Anna Zaksda4c8d62011-10-26 21:06:34 +00002638 C.addTransition(state);
John McCall31168b02011-06-15 23:02:42 +00002639}
2640
Ted Kremenek415287d2012-03-06 20:06:12 +00002641void RetainCountChecker::processObjCLiterals(CheckerContext &C,
2642 const Expr *Ex) const {
2643 ProgramStateRef state = C.getState();
2644 const ExplodedNode *pred = C.getPredecessor();
2645 for (Stmt::const_child_iterator it = Ex->child_begin(), et = Ex->child_end() ;
2646 it != et ; ++it) {
2647 const Stmt *child = *it;
2648 SVal V = state->getSVal(child, pred->getLocationContext());
2649 if (SymbolRef sym = V.getAsSymbol())
Anna Zaksf5788c72012-08-14 00:36:15 +00002650 if (const RefVal* T = getRefBinding(state, sym)) {
Ted Kremenek415287d2012-03-06 20:06:12 +00002651 RefVal::Kind hasErr = (RefVal::Kind) 0;
2652 state = updateSymbol(state, sym, *T, MayEscape, hasErr, C);
2653 if (hasErr) {
2654 processNonLeakError(state, child->getSourceRange(), hasErr, sym, C);
2655 return;
2656 }
2657 }
2658 }
2659
2660 // Return the object as autoreleased.
2661 // RetEffect RE = RetEffect::MakeNotOwned(RetEffect::ObjC);
2662 if (SymbolRef sym =
2663 state->getSVal(Ex, pred->getLocationContext()).getAsSymbol()) {
2664 QualType ResultTy = Ex->getType();
Anna Zaksf5788c72012-08-14 00:36:15 +00002665 state = setRefBinding(state, sym,
2666 RefVal::makeNotOwned(RetEffect::ObjC, ResultTy));
Ted Kremenek415287d2012-03-06 20:06:12 +00002667 }
2668
2669 C.addTransition(state);
2670}
2671
2672void RetainCountChecker::checkPostStmt(const ObjCArrayLiteral *AL,
2673 CheckerContext &C) const {
2674 // Apply the 'MayEscape' to all values.
2675 processObjCLiterals(C, AL);
2676}
2677
2678void RetainCountChecker::checkPostStmt(const ObjCDictionaryLiteral *DL,
2679 CheckerContext &C) const {
2680 // Apply the 'MayEscape' to all keys and values.
2681 processObjCLiterals(C, DL);
2682}
2683
Jordy Rose6393f822012-05-12 05:10:43 +00002684void RetainCountChecker::checkPostStmt(const ObjCBoxedExpr *Ex,
2685 CheckerContext &C) const {
2686 const ExplodedNode *Pred = C.getPredecessor();
2687 const LocationContext *LCtx = Pred->getLocationContext();
2688 ProgramStateRef State = Pred->getState();
2689
2690 if (SymbolRef Sym = State->getSVal(Ex, LCtx).getAsSymbol()) {
2691 QualType ResultTy = Ex->getType();
Anna Zaksf5788c72012-08-14 00:36:15 +00002692 State = setRefBinding(State, Sym,
2693 RefVal::makeNotOwned(RetEffect::ObjC, ResultTy));
Jordy Rose6393f822012-05-12 05:10:43 +00002694 }
2695
2696 C.addTransition(State);
2697}
2698
Jordan Rose682b3162012-07-02 19:28:21 +00002699void RetainCountChecker::checkPostCall(const CallEvent &Call,
2700 CheckerContext &C) const {
Jordan Rose682b3162012-07-02 19:28:21 +00002701 RetainSummaryManager &Summaries = getSummaryManager(C);
2702 const RetainSummary *Summ = Summaries.getSummary(Call, C.getState());
Anna Zaks25612732012-08-29 23:23:43 +00002703
2704 if (C.wasInlined) {
2705 processSummaryOfInlined(*Summ, Call, C);
2706 return;
2707 }
Jordan Rose682b3162012-07-02 19:28:21 +00002708 checkSummary(*Summ, Call, C);
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002709}
2710
Jordy Rose75e680e2011-09-02 06:44:22 +00002711/// GetReturnType - Used to get the return type of a message expression or
2712/// function call with the intention of affixing that type to a tracked symbol.
Sylvestre Ledru830885c2012-07-23 08:59:39 +00002713/// While the return type can be queried directly from RetEx, when
Jordy Rose75e680e2011-09-02 06:44:22 +00002714/// invoking class methods we augment to the return type to be that of
2715/// a pointer to the class (as opposed it just being id).
2716// FIXME: We may be able to do this with related result types instead.
2717// This function is probably overestimating.
2718static QualType GetReturnType(const Expr *RetE, ASTContext &Ctx) {
2719 QualType RetTy = RetE->getType();
2720 // If RetE is not a message expression just return its type.
2721 // If RetE is a message expression, return its types if it is something
2722 /// more specific than id.
2723 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RetE))
2724 if (const ObjCObjectPointerType *PT = RetTy->getAs<ObjCObjectPointerType>())
2725 if (PT->isObjCQualifiedIdType() || PT->isObjCIdType() ||
2726 PT->isObjCClassType()) {
2727 // At this point we know the return type of the message expression is
2728 // id, id<...>, or Class. If we have an ObjCInterfaceDecl, we know this
2729 // is a call to a class method whose type we can resolve. In such
2730 // cases, promote the return type to XXX* (where XXX is the class).
2731 const ObjCInterfaceDecl *D = ME->getReceiverInterface();
2732 return !D ? RetTy :
2733 Ctx.getObjCObjectPointerType(Ctx.getObjCInterfaceType(D));
2734 }
2735
2736 return RetTy;
2737}
2738
Anna Zaks25612732012-08-29 23:23:43 +00002739// We don't always get the exact modeling of the function with regards to the
2740// retain count checker even when the function is inlined. For example, we need
2741// to stop tracking the symbols which were marked with StopTrackingHard.
2742void RetainCountChecker::processSummaryOfInlined(const RetainSummary &Summ,
2743 const CallEvent &CallOrMsg,
2744 CheckerContext &C) const {
2745 ProgramStateRef state = C.getState();
2746
2747 // Evaluate the effect of the arguments.
2748 for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
2749 if (Summ.getArg(idx) == StopTrackingHard) {
2750 SVal V = CallOrMsg.getArgSVal(idx);
2751 if (SymbolRef Sym = V.getAsLocSymbol()) {
2752 state = removeRefBinding(state, Sym);
2753 }
2754 }
2755 }
2756
2757 // Evaluate the effect on the message receiver.
2758 const ObjCMethodCall *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg);
2759 if (MsgInvocation) {
2760 if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
2761 if (Summ.getReceiverEffect() == StopTrackingHard) {
2762 state = removeRefBinding(state, Sym);
2763 }
2764 }
2765 }
2766
2767 // Consult the summary for the return value.
2768 RetEffect RE = Summ.getRetEffect();
2769 if (RE.getKind() == RetEffect::NoRetHard) {
Jordan Rose829c3832012-11-02 23:49:29 +00002770 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
Anna Zaks25612732012-08-29 23:23:43 +00002771 if (Sym)
2772 state = removeRefBinding(state, Sym);
2773 }
2774
2775 C.addTransition(state);
2776}
2777
Jordy Rose75e680e2011-09-02 06:44:22 +00002778void RetainCountChecker::checkSummary(const RetainSummary &Summ,
Jordan Roseeec15392012-07-02 19:27:43 +00002779 const CallEvent &CallOrMsg,
Jordy Rose75e680e2011-09-02 06:44:22 +00002780 CheckerContext &C) const {
Ted Kremenek49b1e382012-01-26 21:29:00 +00002781 ProgramStateRef state = C.getState();
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002782
2783 // Evaluate the effect of the arguments.
2784 RefVal::Kind hasErr = (RefVal::Kind) 0;
2785 SourceRange ErrorRange;
2786 SymbolRef ErrorSym = 0;
2787
2788 for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
Jordy Rose1fad6632011-08-27 22:51:26 +00002789 SVal V = CallOrMsg.getArgSVal(idx);
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002790
2791 if (SymbolRef Sym = V.getAsLocSymbol()) {
Anna Zaksf5788c72012-08-14 00:36:15 +00002792 if (const RefVal *T = getRefBinding(state, Sym)) {
Jordy Rosec49ec532011-09-02 05:55:19 +00002793 state = updateSymbol(state, Sym, *T, Summ.getArg(idx), hasErr, C);
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002794 if (hasErr) {
2795 ErrorRange = CallOrMsg.getArgSourceRange(idx);
2796 ErrorSym = Sym;
2797 break;
2798 }
2799 }
2800 }
2801 }
2802
2803 // Evaluate the effect on the message receiver.
2804 bool ReceiverIsTracked = false;
Jordan Roseeec15392012-07-02 19:27:43 +00002805 if (!hasErr) {
Jordan Rose6bad4902012-07-02 19:27:56 +00002806 const ObjCMethodCall *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg);
Jordan Roseeec15392012-07-02 19:27:43 +00002807 if (MsgInvocation) {
2808 if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
Anna Zaksf5788c72012-08-14 00:36:15 +00002809 if (const RefVal *T = getRefBinding(state, Sym)) {
Jordan Roseeec15392012-07-02 19:27:43 +00002810 ReceiverIsTracked = true;
2811 state = updateSymbol(state, Sym, *T, Summ.getReceiverEffect(),
Anna Zaks25612732012-08-29 23:23:43 +00002812 hasErr, C);
Jordan Roseeec15392012-07-02 19:27:43 +00002813 if (hasErr) {
Jordan Rose627b0462012-07-18 21:59:51 +00002814 ErrorRange = MsgInvocation->getOriginExpr()->getReceiverRange();
Jordan Roseeec15392012-07-02 19:27:43 +00002815 ErrorSym = Sym;
2816 }
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002817 }
2818 }
2819 }
2820 }
2821
2822 // Process any errors.
2823 if (hasErr) {
2824 processNonLeakError(state, ErrorRange, hasErr, ErrorSym, C);
2825 return;
2826 }
2827
2828 // Consult the summary for the return value.
2829 RetEffect RE = Summ.getRetEffect();
2830
2831 if (RE.getKind() == RetEffect::OwnedWhenTrackedReceiver) {
Jordy Rose8b289a22011-08-25 00:10:37 +00002832 if (ReceiverIsTracked)
Jordy Rosec49ec532011-09-02 05:55:19 +00002833 RE = getSummaryManager(C).getObjAllocRetEffect();
Jordy Rose8b289a22011-08-25 00:10:37 +00002834 else
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002835 RE = RetEffect::MakeNoRet();
2836 }
2837
2838 switch (RE.getKind()) {
2839 default:
David Blaikie8a40f702012-01-17 06:56:22 +00002840 llvm_unreachable("Unhandled RetEffect.");
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002841
2842 case RetEffect::NoRet:
Anna Zaks25612732012-08-29 23:23:43 +00002843 case RetEffect::NoRetHard:
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002844 // No work necessary.
2845 break;
2846
2847 case RetEffect::OwnedAllocatedSymbol:
2848 case RetEffect::OwnedSymbol: {
Jordan Rose829c3832012-11-02 23:49:29 +00002849 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002850 if (!Sym)
2851 break;
2852
Jordan Roseeec15392012-07-02 19:27:43 +00002853 // Use the result type from the CallEvent as it automatically adjusts
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002854 // for methods/functions that return references.
Jordan Roseeec15392012-07-02 19:27:43 +00002855 QualType ResultTy = CallOrMsg.getResultType();
Anna Zaksf5788c72012-08-14 00:36:15 +00002856 state = setRefBinding(state, Sym, RefVal::makeOwned(RE.getObjKind(),
2857 ResultTy));
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002858
2859 // FIXME: Add a flag to the checker where allocations are assumed to
Anna Zaks21487f72012-08-14 15:39:13 +00002860 // *not* fail.
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002861 break;
2862 }
2863
2864 case RetEffect::GCNotOwnedSymbol:
2865 case RetEffect::ARCNotOwnedSymbol:
2866 case RetEffect::NotOwnedSymbol: {
2867 const Expr *Ex = CallOrMsg.getOriginExpr();
Jordan Rose829c3832012-11-02 23:49:29 +00002868 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002869 if (!Sym)
2870 break;
Ted Kremenekbe400842012-10-12 22:56:45 +00002871 assert(Ex);
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002872 // Use GetReturnType in order to give [NSFoo alloc] the type NSFoo *.
2873 QualType ResultTy = GetReturnType(Ex, C.getASTContext());
Anna Zaksf5788c72012-08-14 00:36:15 +00002874 state = setRefBinding(state, Sym, RefVal::makeNotOwned(RE.getObjKind(),
2875 ResultTy));
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002876 break;
2877 }
2878 }
2879
2880 // This check is actually necessary; otherwise the statement builder thinks
2881 // we've hit a previously-found path.
2882 // Normally addTransition takes care of this, but we want the node pointer.
2883 ExplodedNode *NewNode;
2884 if (state == C.getState()) {
2885 NewNode = C.getPredecessor();
2886 } else {
Anna Zaksda4c8d62011-10-26 21:06:34 +00002887 NewNode = C.addTransition(state);
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002888 }
2889
Jordy Rose5df640d2011-08-24 18:56:32 +00002890 // Annotate the node with summary we used.
2891 if (NewNode) {
2892 // FIXME: This is ugly. See checkEndAnalysis for why it's necessary.
2893 if (ShouldResetSummaryLog) {
2894 SummaryLog.clear();
2895 ShouldResetSummaryLog = false;
2896 }
Jordy Rose20d4e682011-08-23 20:55:48 +00002897 SummaryLog[NewNode] = &Summ;
Jordy Rose5df640d2011-08-24 18:56:32 +00002898 }
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002899}
2900
Jordy Rosebf77e512011-08-23 20:27:16 +00002901
Ted Kremenek49b1e382012-01-26 21:29:00 +00002902ProgramStateRef
2903RetainCountChecker::updateSymbol(ProgramStateRef state, SymbolRef sym,
Jordy Rose75e680e2011-09-02 06:44:22 +00002904 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
2905 CheckerContext &C) const {
Jordy Rosebf77e512011-08-23 20:27:16 +00002906 // In GC mode [... release] and [... retain] do nothing.
Jordy Rose75e680e2011-09-02 06:44:22 +00002907 // In ARC mode they shouldn't exist at all, but we just ignore them.
Jordy Rosec49ec532011-09-02 05:55:19 +00002908 bool IgnoreRetainMsg = C.isObjCGCEnabled();
2909 if (!IgnoreRetainMsg)
David Blaikiebbafb8a2012-03-11 07:00:24 +00002910 IgnoreRetainMsg = (bool)C.getASTContext().getLangOpts().ObjCAutoRefCount;
Jordy Rosec49ec532011-09-02 05:55:19 +00002911
Jordy Rosebf77e512011-08-23 20:27:16 +00002912 switch (E) {
Jordan Roseeec15392012-07-02 19:27:43 +00002913 default:
2914 break;
2915 case IncRefMsg:
2916 E = IgnoreRetainMsg ? DoNothing : IncRef;
2917 break;
2918 case DecRefMsg:
2919 E = IgnoreRetainMsg ? DoNothing : DecRef;
2920 break;
Anna Zaks25612732012-08-29 23:23:43 +00002921 case DecRefMsgAndStopTrackingHard:
2922 E = IgnoreRetainMsg ? StopTracking : DecRefAndStopTrackingHard;
Jordan Roseeec15392012-07-02 19:27:43 +00002923 break;
2924 case MakeCollectable:
2925 E = C.isObjCGCEnabled() ? DecRef : DoNothing;
2926 break;
Jordy Rosebf77e512011-08-23 20:27:16 +00002927 }
2928
2929 // Handle all use-after-releases.
Jordy Rosec49ec532011-09-02 05:55:19 +00002930 if (!C.isObjCGCEnabled() && V.getKind() == RefVal::Released) {
Jordy Rosebf77e512011-08-23 20:27:16 +00002931 V = V ^ RefVal::ErrorUseAfterRelease;
2932 hasErr = V.getKind();
Anna Zaksf5788c72012-08-14 00:36:15 +00002933 return setRefBinding(state, sym, V);
Jordy Rosebf77e512011-08-23 20:27:16 +00002934 }
2935
2936 switch (E) {
2937 case DecRefMsg:
2938 case IncRefMsg:
2939 case MakeCollectable:
Anna Zaks25612732012-08-29 23:23:43 +00002940 case DecRefMsgAndStopTrackingHard:
Jordy Rosebf77e512011-08-23 20:27:16 +00002941 llvm_unreachable("DecRefMsg/IncRefMsg/MakeCollectable already converted");
Jordy Rosebf77e512011-08-23 20:27:16 +00002942
2943 case Dealloc:
2944 // Any use of -dealloc in GC is *bad*.
Jordy Rosec49ec532011-09-02 05:55:19 +00002945 if (C.isObjCGCEnabled()) {
Jordy Rosebf77e512011-08-23 20:27:16 +00002946 V = V ^ RefVal::ErrorDeallocGC;
2947 hasErr = V.getKind();
2948 break;
2949 }
2950
2951 switch (V.getKind()) {
2952 default:
2953 llvm_unreachable("Invalid RefVal state for an explicit dealloc.");
Jordy Rosebf77e512011-08-23 20:27:16 +00002954 case RefVal::Owned:
2955 // The object immediately transitions to the released state.
2956 V = V ^ RefVal::Released;
2957 V.clearCounts();
Anna Zaksf5788c72012-08-14 00:36:15 +00002958 return setRefBinding(state, sym, V);
Jordy Rosebf77e512011-08-23 20:27:16 +00002959 case RefVal::NotOwned:
2960 V = V ^ RefVal::ErrorDeallocNotOwned;
2961 hasErr = V.getKind();
2962 break;
2963 }
2964 break;
2965
Jordy Rosebf77e512011-08-23 20:27:16 +00002966 case MayEscape:
2967 if (V.getKind() == RefVal::Owned) {
2968 V = V ^ RefVal::NotOwned;
2969 break;
2970 }
2971
2972 // Fall-through.
2973
Jordy Rosebf77e512011-08-23 20:27:16 +00002974 case DoNothing:
2975 return state;
2976
2977 case Autorelease:
Jordy Rosec49ec532011-09-02 05:55:19 +00002978 if (C.isObjCGCEnabled())
Jordy Rosebf77e512011-08-23 20:27:16 +00002979 return state;
Jordy Rosebf77e512011-08-23 20:27:16 +00002980 // Update the autorelease counts.
Jordy Rosebf77e512011-08-23 20:27:16 +00002981 V = V.autorelease();
2982 break;
2983
2984 case StopTracking:
Anna Zaks25612732012-08-29 23:23:43 +00002985 case StopTrackingHard:
Anna Zaksf5788c72012-08-14 00:36:15 +00002986 return removeRefBinding(state, sym);
Jordy Rosebf77e512011-08-23 20:27:16 +00002987
2988 case IncRef:
2989 switch (V.getKind()) {
2990 default:
2991 llvm_unreachable("Invalid RefVal state for a retain.");
Jordy Rosebf77e512011-08-23 20:27:16 +00002992 case RefVal::Owned:
2993 case RefVal::NotOwned:
2994 V = V + 1;
2995 break;
2996 case RefVal::Released:
2997 // Non-GC cases are handled above.
Jordy Rosec49ec532011-09-02 05:55:19 +00002998 assert(C.isObjCGCEnabled());
Jordy Rosebf77e512011-08-23 20:27:16 +00002999 V = (V ^ RefVal::Owned) + 1;
3000 break;
3001 }
3002 break;
3003
Jordy Rosebf77e512011-08-23 20:27:16 +00003004 case DecRef:
Benjamin Kramer1d5d6342013-10-20 11:53:20 +00003005 case DecRefBridgedTransferred:
Anna Zaks25612732012-08-29 23:23:43 +00003006 case DecRefAndStopTrackingHard:
Jordy Rosebf77e512011-08-23 20:27:16 +00003007 switch (V.getKind()) {
3008 default:
3009 // case 'RefVal::Released' handled above.
3010 llvm_unreachable("Invalid RefVal state for a release.");
Jordy Rosebf77e512011-08-23 20:27:16 +00003011
3012 case RefVal::Owned:
3013 assert(V.getCount() > 0);
3014 if (V.getCount() == 1)
Benjamin Kramer1d5d6342013-10-20 11:53:20 +00003015 V = V ^ (E == DecRefBridgedTransferred ? RefVal::NotOwned
3016 : RefVal::Released);
Anna Zaks25612732012-08-29 23:23:43 +00003017 else if (E == DecRefAndStopTrackingHard)
Anna Zaksf5788c72012-08-14 00:36:15 +00003018 return removeRefBinding(state, sym);
Jordan Roseeec15392012-07-02 19:27:43 +00003019
Jordy Rosebf77e512011-08-23 20:27:16 +00003020 V = V - 1;
3021 break;
3022
3023 case RefVal::NotOwned:
Jordan Roseeec15392012-07-02 19:27:43 +00003024 if (V.getCount() > 0) {
Anna Zaks25612732012-08-29 23:23:43 +00003025 if (E == DecRefAndStopTrackingHard)
Anna Zaksf5788c72012-08-14 00:36:15 +00003026 return removeRefBinding(state, sym);
Jordy Rosebf77e512011-08-23 20:27:16 +00003027 V = V - 1;
Jordan Roseeec15392012-07-02 19:27:43 +00003028 } else {
Jordy Rosebf77e512011-08-23 20:27:16 +00003029 V = V ^ RefVal::ErrorReleaseNotOwned;
3030 hasErr = V.getKind();
3031 }
3032 break;
3033
3034 case RefVal::Released:
3035 // Non-GC cases are handled above.
Jordy Rosec49ec532011-09-02 05:55:19 +00003036 assert(C.isObjCGCEnabled());
Jordy Rosebf77e512011-08-23 20:27:16 +00003037 V = V ^ RefVal::ErrorUseAfterRelease;
3038 hasErr = V.getKind();
3039 break;
3040 }
3041 break;
3042 }
Anna Zaksf5788c72012-08-14 00:36:15 +00003043 return setRefBinding(state, sym, V);
Jordy Rosebf77e512011-08-23 20:27:16 +00003044}
3045
Ted Kremenek49b1e382012-01-26 21:29:00 +00003046void RetainCountChecker::processNonLeakError(ProgramStateRef St,
Jordy Rose75e680e2011-09-02 06:44:22 +00003047 SourceRange ErrorRange,
3048 RefVal::Kind ErrorKind,
3049 SymbolRef Sym,
3050 CheckerContext &C) const {
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003051 ExplodedNode *N = C.generateSink(St);
3052 if (!N)
3053 return;
3054
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003055 CFRefBug *BT;
3056 switch (ErrorKind) {
3057 default:
3058 llvm_unreachable("Unhandled error.");
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003059 case RefVal::ErrorUseAfterRelease:
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003060 if (!useAfterRelease)
3061 useAfterRelease.reset(new UseAfterRelease());
3062 BT = &*useAfterRelease;
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003063 break;
3064 case RefVal::ErrorReleaseNotOwned:
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003065 if (!releaseNotOwned)
3066 releaseNotOwned.reset(new BadRelease());
3067 BT = &*releaseNotOwned;
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003068 break;
3069 case RefVal::ErrorDeallocGC:
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003070 if (!deallocGC)
3071 deallocGC.reset(new DeallocGC());
3072 BT = &*deallocGC;
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003073 break;
3074 case RefVal::ErrorDeallocNotOwned:
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003075 if (!deallocNotOwned)
3076 deallocNotOwned.reset(new DeallocNotOwned());
3077 BT = &*deallocNotOwned;
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003078 break;
3079 }
3080
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003081 assert(BT);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003082 CFRefReport *report = new CFRefReport(*BT, C.getASTContext().getLangOpts(),
Jordy Rosec49ec532011-09-02 05:55:19 +00003083 C.isObjCGCEnabled(), SummaryLog,
3084 N, Sym);
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003085 report->addRange(ErrorRange);
Jordan Rosee10d5a72012-11-02 01:53:40 +00003086 C.emitReport(report);
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003087}
3088
Jordy Rose75e680e2011-09-02 06:44:22 +00003089//===----------------------------------------------------------------------===//
3090// Handle the return values of retain-count-related functions.
3091//===----------------------------------------------------------------------===//
3092
3093bool RetainCountChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
Jordy Rose898a1482011-08-21 21:58:18 +00003094 // Get the callee. We're only interested in simple C functions.
Ted Kremenek49b1e382012-01-26 21:29:00 +00003095 ProgramStateRef state = C.getState();
Anna Zaksc6aa5312011-12-01 05:57:37 +00003096 const FunctionDecl *FD = C.getCalleeDecl(CE);
Jordy Rose898a1482011-08-21 21:58:18 +00003097 if (!FD)
3098 return false;
3099
3100 IdentifierInfo *II = FD->getIdentifier();
3101 if (!II)
3102 return false;
3103
3104 // For now, we're only handling the functions that return aliases of their
3105 // arguments: CFRetain and CFMakeCollectable (and their families).
3106 // Eventually we should add other functions we can model entirely,
3107 // such as CFRelease, which don't invalidate their arguments or globals.
3108 if (CE->getNumArgs() != 1)
3109 return false;
3110
3111 // Get the name of the function.
3112 StringRef FName = II->getName();
3113 FName = FName.substr(FName.find_first_not_of('_'));
3114
3115 // See if it's one of the specific functions we know how to eval.
3116 bool canEval = false;
3117
Anna Zaksc6aa5312011-12-01 05:57:37 +00003118 QualType ResultTy = CE->getCallReturnType();
Jordy Rose898a1482011-08-21 21:58:18 +00003119 if (ResultTy->isObjCIdType()) {
3120 // Handle: id NSMakeCollectable(CFTypeRef)
3121 canEval = II->isStr("NSMakeCollectable");
3122 } else if (ResultTy->isPointerType()) {
3123 // Handle: (CF|CG)Retain
Jordan Rose77411322013-10-07 17:16:52 +00003124 // CFAutorelease
Jordy Rose898a1482011-08-21 21:58:18 +00003125 // CFMakeCollectable
3126 // It's okay to be a little sloppy here (CGMakeCollectable doesn't exist).
3127 if (cocoa::isRefType(ResultTy, "CF", FName) ||
3128 cocoa::isRefType(ResultTy, "CG", FName)) {
Jordan Rose77411322013-10-07 17:16:52 +00003129 canEval = isRetain(FD, FName) || isAutorelease(FD, FName) ||
3130 isMakeCollectable(FD, FName);
Jordy Rose898a1482011-08-21 21:58:18 +00003131 }
3132 }
3133
3134 if (!canEval)
3135 return false;
3136
3137 // Bind the return value.
Ted Kremenek632e3b72012-01-06 22:09:28 +00003138 const LocationContext *LCtx = C.getLocationContext();
3139 SVal RetVal = state->getSVal(CE->getArg(0), LCtx);
Jordy Rose898a1482011-08-21 21:58:18 +00003140 if (RetVal.isUnknown()) {
3141 // If the receiver is unknown, conjure a return value.
3142 SValBuilder &SVB = C.getSValBuilder();
Ted Kremenekd94854a2012-08-22 06:26:15 +00003143 RetVal = SVB.conjureSymbolVal(0, CE, LCtx, ResultTy, C.blockCount());
Jordy Rose898a1482011-08-21 21:58:18 +00003144 }
Ted Kremenek632e3b72012-01-06 22:09:28 +00003145 state = state->BindExpr(CE, LCtx, RetVal, false);
Jordy Rose898a1482011-08-21 21:58:18 +00003146
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003147 // FIXME: This should not be necessary, but otherwise the argument seems to be
3148 // considered alive during the next statement.
3149 if (const MemRegion *ArgRegion = RetVal.getAsRegion()) {
3150 // Save the refcount status of the argument.
3151 SymbolRef Sym = RetVal.getAsLocSymbol();
Anna Zaksf5788c72012-08-14 00:36:15 +00003152 const RefVal *Binding = 0;
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003153 if (Sym)
Anna Zaksf5788c72012-08-14 00:36:15 +00003154 Binding = getRefBinding(state, Sym);
Jordy Rose898a1482011-08-21 21:58:18 +00003155
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003156 // Invalidate the argument region.
Anna Zaksdc154152012-12-20 00:38:25 +00003157 state = state->invalidateRegions(ArgRegion, CE, C.blockCount(), LCtx,
Anna Zaks0c34c1a2013-01-16 01:35:54 +00003158 /*CausesPointerEscape*/ false);
Jordy Rose898a1482011-08-21 21:58:18 +00003159
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003160 // Restore the refcount status of the argument.
3161 if (Binding)
Anna Zaksf5788c72012-08-14 00:36:15 +00003162 state = setRefBinding(state, Sym, *Binding);
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003163 }
3164
Anna Zaksda4c8d62011-10-26 21:06:34 +00003165 C.addTransition(state);
Jordy Rose898a1482011-08-21 21:58:18 +00003166 return true;
3167}
3168
Jordy Rose75e680e2011-09-02 06:44:22 +00003169//===----------------------------------------------------------------------===//
3170// Handle return statements.
3171//===----------------------------------------------------------------------===//
Jordy Rose298cc4d2011-08-23 19:43:16 +00003172
Jordy Rose75e680e2011-09-02 06:44:22 +00003173void RetainCountChecker::checkPreStmt(const ReturnStmt *S,
3174 CheckerContext &C) const {
Ted Kremenekef31f372012-02-25 02:09:09 +00003175
3176 // Only adjust the reference count if this is the top-level call frame,
3177 // and not the result of inlining. In the future, we should do
3178 // better checking even for inlined calls, and see if they match
3179 // with their expected semantics (e.g., the method should return a retained
3180 // object, etc.).
Anna Zaks44dc91b2012-11-03 02:54:16 +00003181 if (!C.inTopFrame())
Ted Kremenekef31f372012-02-25 02:09:09 +00003182 return;
3183
Jordy Rose298cc4d2011-08-23 19:43:16 +00003184 const Expr *RetE = S->getRetValue();
3185 if (!RetE)
3186 return;
3187
Ted Kremenek49b1e382012-01-26 21:29:00 +00003188 ProgramStateRef state = C.getState();
Ted Kremenek632e3b72012-01-06 22:09:28 +00003189 SymbolRef Sym =
3190 state->getSValAsScalarOrLoc(RetE, C.getLocationContext()).getAsLocSymbol();
Jordy Rose298cc4d2011-08-23 19:43:16 +00003191 if (!Sym)
3192 return;
3193
3194 // Get the reference count binding (if any).
Anna Zaksf5788c72012-08-14 00:36:15 +00003195 const RefVal *T = getRefBinding(state, Sym);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003196 if (!T)
3197 return;
3198
3199 // Change the reference count.
3200 RefVal X = *T;
3201
3202 switch (X.getKind()) {
3203 case RefVal::Owned: {
3204 unsigned cnt = X.getCount();
3205 assert(cnt > 0);
3206 X.setCount(cnt - 1);
3207 X = X ^ RefVal::ReturnedOwned;
3208 break;
3209 }
3210
3211 case RefVal::NotOwned: {
3212 unsigned cnt = X.getCount();
3213 if (cnt) {
3214 X.setCount(cnt - 1);
3215 X = X ^ RefVal::ReturnedOwned;
3216 }
3217 else {
3218 X = X ^ RefVal::ReturnedNotOwned;
3219 }
3220 break;
3221 }
3222
3223 default:
3224 return;
3225 }
3226
3227 // Update the binding.
Anna Zaksf5788c72012-08-14 00:36:15 +00003228 state = setRefBinding(state, Sym, X);
Anna Zaksda4c8d62011-10-26 21:06:34 +00003229 ExplodedNode *Pred = C.addTransition(state);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003230
3231 // At this point we have updated the state properly.
3232 // Everything after this is merely checking to see if the return value has
3233 // been over- or under-retained.
3234
3235 // Did we cache out?
3236 if (!Pred)
3237 return;
3238
Jordy Rose298cc4d2011-08-23 19:43:16 +00003239 // Update the autorelease counts.
3240 static SimpleProgramPointTag
Jordy Rose75e680e2011-09-02 06:44:22 +00003241 AutoreleaseTag("RetainCountChecker : Autorelease");
Jordan Roseff03c1d2012-12-06 18:58:18 +00003242 state = handleAutoreleaseCounts(state, Pred, &AutoreleaseTag, C, Sym, X);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003243
3244 // Did we cache out?
Jordan Roseff03c1d2012-12-06 18:58:18 +00003245 if (!state)
Jordy Rose298cc4d2011-08-23 19:43:16 +00003246 return;
3247
3248 // Get the updated binding.
Anna Zaksf5788c72012-08-14 00:36:15 +00003249 T = getRefBinding(state, Sym);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003250 assert(T);
3251 X = *T;
3252
3253 // Consult the summary of the enclosing method.
Jordy Rosec49ec532011-09-02 05:55:19 +00003254 RetainSummaryManager &Summaries = getSummaryManager(C);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003255 const Decl *CD = &Pred->getCodeDecl();
Jordan Roseeec15392012-07-02 19:27:43 +00003256 RetEffect RE = RetEffect::MakeNoRet();
Jordy Rose298cc4d2011-08-23 19:43:16 +00003257
Jordan Roseeec15392012-07-02 19:27:43 +00003258 // FIXME: What is the convention for blocks? Is there one?
Jordy Rose298cc4d2011-08-23 19:43:16 +00003259 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CD)) {
Jordy Rose8b289a22011-08-25 00:10:37 +00003260 const RetainSummary *Summ = Summaries.getMethodSummary(MD);
Jordan Roseeec15392012-07-02 19:27:43 +00003261 RE = Summ->getRetEffect();
3262 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) {
3263 if (!isa<CXXMethodDecl>(FD)) {
3264 const RetainSummary *Summ = Summaries.getFunctionSummary(FD);
3265 RE = Summ->getRetEffect();
3266 }
Jordy Rose298cc4d2011-08-23 19:43:16 +00003267 }
3268
Jordan Roseeec15392012-07-02 19:27:43 +00003269 checkReturnWithRetEffect(S, C, Pred, RE, X, Sym, state);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003270}
3271
Jordy Rose75e680e2011-09-02 06:44:22 +00003272void RetainCountChecker::checkReturnWithRetEffect(const ReturnStmt *S,
3273 CheckerContext &C,
3274 ExplodedNode *Pred,
3275 RetEffect RE, RefVal X,
3276 SymbolRef Sym,
Ted Kremenek49b1e382012-01-26 21:29:00 +00003277 ProgramStateRef state) const {
Jordy Rose298cc4d2011-08-23 19:43:16 +00003278 // Any leaks or other errors?
3279 if (X.isReturnedOwned() && X.getCount() == 0) {
3280 if (RE.getKind() != RetEffect::NoRet) {
3281 bool hasError = false;
Jordy Rosec49ec532011-09-02 05:55:19 +00003282 if (C.isObjCGCEnabled() && RE.getObjKind() == RetEffect::ObjC) {
Jordy Rose298cc4d2011-08-23 19:43:16 +00003283 // Things are more complicated with garbage collection. If the
3284 // returned object is suppose to be an Objective-C object, we have
3285 // a leak (as the caller expects a GC'ed object) because no
3286 // method should return ownership unless it returns a CF object.
3287 hasError = true;
3288 X = X ^ RefVal::ErrorGCLeakReturned;
3289 }
3290 else if (!RE.isOwned()) {
3291 // Either we are using GC and the returned object is a CF type
3292 // or we aren't using GC. In either case, we expect that the
3293 // enclosing method is expected to return ownership.
3294 hasError = true;
3295 X = X ^ RefVal::ErrorLeakReturned;
3296 }
3297
3298 if (hasError) {
3299 // Generate an error node.
Anna Zaksf5788c72012-08-14 00:36:15 +00003300 state = setRefBinding(state, Sym, X);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003301
3302 static SimpleProgramPointTag
Jordy Rose75e680e2011-09-02 06:44:22 +00003303 ReturnOwnLeakTag("RetainCountChecker : ReturnsOwnLeak");
Anna Zaksda4c8d62011-10-26 21:06:34 +00003304 ExplodedNode *N = C.addTransition(state, Pred, &ReturnOwnLeakTag);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003305 if (N) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003306 const LangOptions &LOpts = C.getASTContext().getLangOpts();
Jordy Rosec49ec532011-09-02 05:55:19 +00003307 bool GCEnabled = C.isObjCGCEnabled();
Jordy Rose298cc4d2011-08-23 19:43:16 +00003308 CFRefReport *report =
Jordy Rosec49ec532011-09-02 05:55:19 +00003309 new CFRefLeakReport(*getLeakAtReturnBug(LOpts, GCEnabled),
3310 LOpts, GCEnabled, SummaryLog,
Ted Kremenek8671acb2013-04-16 21:44:22 +00003311 N, Sym, C, IncludeAllocationLine);
3312
Jordan Rosee10d5a72012-11-02 01:53:40 +00003313 C.emitReport(report);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003314 }
3315 }
3316 }
3317 } else if (X.isReturnedNotOwned()) {
3318 if (RE.isOwned()) {
3319 // Trying to return a not owned object to a caller expecting an
3320 // owned object.
Anna Zaksf5788c72012-08-14 00:36:15 +00003321 state = setRefBinding(state, Sym, X ^ RefVal::ErrorReturnedNotOwned);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003322
3323 static SimpleProgramPointTag
Jordy Rose75e680e2011-09-02 06:44:22 +00003324 ReturnNotOwnedTag("RetainCountChecker : ReturnNotOwnedForOwned");
Anna Zaksda4c8d62011-10-26 21:06:34 +00003325 ExplodedNode *N = C.addTransition(state, Pred, &ReturnNotOwnedTag);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003326 if (N) {
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003327 if (!returnNotOwnedForOwned)
3328 returnNotOwnedForOwned.reset(new ReturnedNotOwnedForOwned());
3329
Jordy Rose298cc4d2011-08-23 19:43:16 +00003330 CFRefReport *report =
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003331 new CFRefReport(*returnNotOwnedForOwned,
David Blaikiebbafb8a2012-03-11 07:00:24 +00003332 C.getASTContext().getLangOpts(),
Jordy Rosec49ec532011-09-02 05:55:19 +00003333 C.isObjCGCEnabled(), SummaryLog, N, Sym);
Jordan Rosee10d5a72012-11-02 01:53:40 +00003334 C.emitReport(report);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003335 }
3336 }
3337 }
3338}
3339
Jordy Rose6763e382011-08-23 20:07:14 +00003340//===----------------------------------------------------------------------===//
Jordy Rose75e680e2011-09-02 06:44:22 +00003341// Check various ways a symbol can be invalidated.
3342//===----------------------------------------------------------------------===//
3343
Anna Zaks3e0f4152011-10-06 00:43:15 +00003344void RetainCountChecker::checkBind(SVal loc, SVal val, const Stmt *S,
Jordy Rose75e680e2011-09-02 06:44:22 +00003345 CheckerContext &C) const {
3346 // Are we storing to something that causes the value to "escape"?
3347 bool escapes = true;
3348
3349 // A value escapes in three possible cases (this may change):
3350 //
3351 // (1) we are binding to something that is not a memory region.
3352 // (2) we are binding to a memregion that does not have stack storage
3353 // (3) we are binding to a memregion with stack storage that the store
3354 // does not understand.
Ted Kremenek49b1e382012-01-26 21:29:00 +00003355 ProgramStateRef state = C.getState();
Jordy Rose75e680e2011-09-02 06:44:22 +00003356
David Blaikie05785d12013-02-20 22:23:23 +00003357 if (Optional<loc::MemRegionVal> regionLoc = loc.getAs<loc::MemRegionVal>()) {
Jordy Rose75e680e2011-09-02 06:44:22 +00003358 escapes = !regionLoc->getRegion()->hasStackStorage();
3359
3360 if (!escapes) {
3361 // To test (3), generate a new state with the binding added. If it is
3362 // the same state, then it escapes (since the store cannot represent
3363 // the binding).
Anna Zaks70de7722012-05-02 00:15:40 +00003364 // Do this only if we know that the store is not supposed to generate the
3365 // same state.
3366 SVal StoredVal = state->getSVal(regionLoc->getRegion());
3367 if (StoredVal != val)
3368 escapes = (state == (state->bindLoc(*regionLoc, val)));
Jordy Rose75e680e2011-09-02 06:44:22 +00003369 }
Ted Kremeneke9a5bcf2012-03-27 01:12:45 +00003370 if (!escapes) {
3371 // Case 4: We do not currently model what happens when a symbol is
3372 // assigned to a struct field, so be conservative here and let the symbol
3373 // go. TODO: This could definitely be improved upon.
3374 escapes = !isa<VarRegion>(regionLoc->getRegion());
3375 }
Jordy Rose75e680e2011-09-02 06:44:22 +00003376 }
3377
Anna Zaksfb050942013-09-17 00:53:28 +00003378 // If we are storing the value into an auto function scope variable annotated
3379 // with (__attribute__((cleanup))), stop tracking the value to avoid leak
3380 // false positives.
3381 if (const VarRegion *LVR = dyn_cast_or_null<VarRegion>(loc.getAsRegion())) {
3382 const VarDecl *VD = LVR->getDecl();
Aaron Ballman9ead1242013-12-19 02:39:40 +00003383 if (VD->hasAttr<CleanupAttr>()) {
Anna Zaksfb050942013-09-17 00:53:28 +00003384 escapes = true;
3385 }
3386 }
3387
Jordy Rose75e680e2011-09-02 06:44:22 +00003388 // If our store can represent the binding and we aren't storing to something
3389 // that doesn't have local storage then just return and have the simulation
3390 // state continue as is.
3391 if (!escapes)
3392 return;
3393
3394 // Otherwise, find all symbols referenced by 'val' that we are tracking
3395 // and stop tracking them.
3396 state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
Anna Zaksda4c8d62011-10-26 21:06:34 +00003397 C.addTransition(state);
Jordy Rose75e680e2011-09-02 06:44:22 +00003398}
3399
Ted Kremenek49b1e382012-01-26 21:29:00 +00003400ProgramStateRef RetainCountChecker::evalAssume(ProgramStateRef state,
Jordy Rose75e680e2011-09-02 06:44:22 +00003401 SVal Cond,
3402 bool Assumption) const {
3403
3404 // FIXME: We may add to the interface of evalAssume the list of symbols
3405 // whose assumptions have changed. For now we just iterate through the
3406 // bindings and check if any of the tracked symbols are NULL. This isn't
3407 // too bad since the number of symbols we will track in practice are
3408 // probably small and evalAssume is only called at branches and a few
3409 // other places.
Jordan Rose0c153cb2012-11-02 01:54:06 +00003410 RefBindingsTy B = state->get<RefBindings>();
Jordy Rose75e680e2011-09-02 06:44:22 +00003411
3412 if (B.isEmpty())
3413 return state;
3414
3415 bool changed = false;
Jordan Rose0c153cb2012-11-02 01:54:06 +00003416 RefBindingsTy::Factory &RefBFactory = state->get_context<RefBindings>();
Jordy Rose75e680e2011-09-02 06:44:22 +00003417
Jordan Rose0c153cb2012-11-02 01:54:06 +00003418 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Ted Kremenek244e1d72012-09-07 22:31:01 +00003419 // Check if the symbol is null stop tracking the symbol.
Jordan Rose14fe9f32012-11-01 00:18:27 +00003420 ConstraintManager &CMgr = state->getConstraintManager();
3421 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
3422 if (AllocFailed.isConstrainedTrue()) {
Jordy Rose75e680e2011-09-02 06:44:22 +00003423 changed = true;
3424 B = RefBFactory.remove(B, I.getKey());
3425 }
3426 }
3427
3428 if (changed)
3429 state = state->set<RefBindings>(B);
3430
3431 return state;
3432}
3433
Ted Kremenek49b1e382012-01-26 21:29:00 +00003434ProgramStateRef
3435RetainCountChecker::checkRegionChanges(ProgramStateRef state,
Anna Zaksdc154152012-12-20 00:38:25 +00003436 const InvalidatedSymbols *invalidated,
Jordy Rose75e680e2011-09-02 06:44:22 +00003437 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks3d348342012-02-14 21:55:24 +00003438 ArrayRef<const MemRegion *> Regions,
Jordan Rose742920c2012-07-02 19:27:35 +00003439 const CallEvent *Call) const {
Jordy Rose75e680e2011-09-02 06:44:22 +00003440 if (!invalidated)
3441 return state;
3442
3443 llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
3444 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
3445 E = ExplicitRegions.end(); I != E; ++I) {
3446 if (const SymbolicRegion *SR = (*I)->StripCasts()->getAs<SymbolicRegion>())
3447 WhitelistedSymbols.insert(SR->getSymbol());
3448 }
3449
Anna Zaksdc154152012-12-20 00:38:25 +00003450 for (InvalidatedSymbols::const_iterator I=invalidated->begin(),
Jordy Rose75e680e2011-09-02 06:44:22 +00003451 E = invalidated->end(); I!=E; ++I) {
3452 SymbolRef sym = *I;
3453 if (WhitelistedSymbols.count(sym))
3454 continue;
3455 // Remove any existing reference-count binding.
Anna Zaksf5788c72012-08-14 00:36:15 +00003456 state = removeRefBinding(state, sym);
Jordy Rose75e680e2011-09-02 06:44:22 +00003457 }
3458 return state;
3459}
3460
3461//===----------------------------------------------------------------------===//
Jordy Rose6763e382011-08-23 20:07:14 +00003462// Handle dead symbols and end-of-path.
3463//===----------------------------------------------------------------------===//
3464
Jordan Roseff03c1d2012-12-06 18:58:18 +00003465ProgramStateRef
3466RetainCountChecker::handleAutoreleaseCounts(ProgramStateRef state,
Anna Zaks58734db2011-10-25 19:57:11 +00003467 ExplodedNode *Pred,
Jordan Rose9f61f8a2012-08-18 00:30:16 +00003468 const ProgramPointTag *Tag,
Anna Zaks58734db2011-10-25 19:57:11 +00003469 CheckerContext &Ctx,
Jordy Rose75e680e2011-09-02 06:44:22 +00003470 SymbolRef Sym, RefVal V) const {
Jordy Rose6763e382011-08-23 20:07:14 +00003471 unsigned ACnt = V.getAutoreleaseCount();
3472
3473 // No autorelease counts? Nothing to be done.
3474 if (!ACnt)
Jordan Roseff03c1d2012-12-06 18:58:18 +00003475 return state;
Jordy Rose6763e382011-08-23 20:07:14 +00003476
Anna Zaks58734db2011-10-25 19:57:11 +00003477 assert(!Ctx.isObjCGCEnabled() && "Autorelease counts in GC mode?");
Jordy Rose6763e382011-08-23 20:07:14 +00003478 unsigned Cnt = V.getCount();
3479
3480 // FIXME: Handle sending 'autorelease' to already released object.
3481
3482 if (V.getKind() == RefVal::ReturnedOwned)
3483 ++Cnt;
3484
3485 if (ACnt <= Cnt) {
3486 if (ACnt == Cnt) {
3487 V.clearCounts();
3488 if (V.getKind() == RefVal::ReturnedOwned)
3489 V = V ^ RefVal::ReturnedNotOwned;
3490 else
3491 V = V ^ RefVal::NotOwned;
3492 } else {
Anna Zaksa8bcc652013-01-31 22:36:17 +00003493 V.setCount(V.getCount() - ACnt);
Jordy Rose6763e382011-08-23 20:07:14 +00003494 V.setAutoreleaseCount(0);
3495 }
Jordan Roseff03c1d2012-12-06 18:58:18 +00003496 return setRefBinding(state, Sym, V);
Jordy Rose6763e382011-08-23 20:07:14 +00003497 }
3498
3499 // Woah! More autorelease counts then retain counts left.
3500 // Emit hard error.
3501 V = V ^ RefVal::ErrorOverAutorelease;
Anna Zaksf5788c72012-08-14 00:36:15 +00003502 state = setRefBinding(state, Sym, V);
Jordy Rose6763e382011-08-23 20:07:14 +00003503
Jordan Rose4b4613c2012-08-20 18:43:42 +00003504 ExplodedNode *N = Ctx.generateSink(state, Pred, Tag);
Jordan Rose9f61f8a2012-08-18 00:30:16 +00003505 if (N) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003506 SmallString<128> sbuf;
Jordy Rose6763e382011-08-23 20:07:14 +00003507 llvm::raw_svector_ostream os(sbuf);
Jordan Rose7467f062013-04-23 01:42:25 +00003508 os << "Object was autoreleased ";
Jordy Rose6763e382011-08-23 20:07:14 +00003509 if (V.getAutoreleaseCount() > 1)
Jordan Rose7467f062013-04-23 01:42:25 +00003510 os << V.getAutoreleaseCount() << " times but the object ";
3511 else
3512 os << "but ";
3513 os << "has a +" << V.getCount() << " retain count";
Jordy Rose6763e382011-08-23 20:07:14 +00003514
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003515 if (!overAutorelease)
3516 overAutorelease.reset(new OverAutorelease());
3517
David Blaikiebbafb8a2012-03-11 07:00:24 +00003518 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
Jordy Rose6763e382011-08-23 20:07:14 +00003519 CFRefReport *report =
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003520 new CFRefReport(*overAutorelease, LOpts, /* GCEnabled = */ false,
3521 SummaryLog, N, Sym, os.str());
Jordan Rosee10d5a72012-11-02 01:53:40 +00003522 Ctx.emitReport(report);
Jordy Rose6763e382011-08-23 20:07:14 +00003523 }
3524
Jordan Roseff03c1d2012-12-06 18:58:18 +00003525 return 0;
Jordy Rose6763e382011-08-23 20:07:14 +00003526}
Jordy Rose78612762011-08-23 19:01:07 +00003527
Ted Kremenek49b1e382012-01-26 21:29:00 +00003528ProgramStateRef
3529RetainCountChecker::handleSymbolDeath(ProgramStateRef state,
Jordy Rose75e680e2011-09-02 06:44:22 +00003530 SymbolRef sid, RefVal V,
Jordy Rose78612762011-08-23 19:01:07 +00003531 SmallVectorImpl<SymbolRef> &Leaked) const {
Jordy Rose03a8f9e2011-08-24 04:48:19 +00003532 bool hasLeak = false;
Jordy Rose78612762011-08-23 19:01:07 +00003533 if (V.isOwned())
3534 hasLeak = true;
3535 else if (V.isNotOwned() || V.isReturnedOwned())
3536 hasLeak = (V.getCount() > 0);
3537
3538 if (!hasLeak)
Anna Zaksf5788c72012-08-14 00:36:15 +00003539 return removeRefBinding(state, sid);
Jordy Rose78612762011-08-23 19:01:07 +00003540
3541 Leaked.push_back(sid);
Anna Zaksf5788c72012-08-14 00:36:15 +00003542 return setRefBinding(state, sid, V ^ RefVal::ErrorLeak);
Jordy Rose78612762011-08-23 19:01:07 +00003543}
3544
3545ExplodedNode *
Ted Kremenek49b1e382012-01-26 21:29:00 +00003546RetainCountChecker::processLeaks(ProgramStateRef state,
Jordy Rose75e680e2011-09-02 06:44:22 +00003547 SmallVectorImpl<SymbolRef> &Leaked,
Anna Zaks58734db2011-10-25 19:57:11 +00003548 CheckerContext &Ctx,
3549 ExplodedNode *Pred) const {
Jordy Rose78612762011-08-23 19:01:07 +00003550 // Generate an intermediate node representing the leak point.
Jordan Rose9f61f8a2012-08-18 00:30:16 +00003551 ExplodedNode *N = Ctx.addTransition(state, Pred);
Jordy Rose78612762011-08-23 19:01:07 +00003552
3553 if (N) {
3554 for (SmallVectorImpl<SymbolRef>::iterator
3555 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3556
David Blaikiebbafb8a2012-03-11 07:00:24 +00003557 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
Anna Zaks58734db2011-10-25 19:57:11 +00003558 bool GCEnabled = Ctx.isObjCGCEnabled();
Jordy Rosec49ec532011-09-02 05:55:19 +00003559 CFRefBug *BT = Pred ? getLeakWithinFunctionBug(LOpts, GCEnabled)
3560 : getLeakAtReturnBug(LOpts, GCEnabled);
Jordy Rose78612762011-08-23 19:01:07 +00003561 assert(BT && "BugType not initialized.");
Jordy Rose184bd142011-08-24 22:39:09 +00003562
Jordy Rosec49ec532011-09-02 05:55:19 +00003563 CFRefLeakReport *report = new CFRefLeakReport(*BT, LOpts, GCEnabled,
Ted Kremenek8671acb2013-04-16 21:44:22 +00003564 SummaryLog, N, *I, Ctx,
3565 IncludeAllocationLine);
Jordan Rosee10d5a72012-11-02 01:53:40 +00003566 Ctx.emitReport(report);
Jordy Rose78612762011-08-23 19:01:07 +00003567 }
3568 }
3569
3570 return N;
3571}
3572
Anna Zaks3fdcc0b2013-01-03 00:25:29 +00003573void RetainCountChecker::checkEndFunction(CheckerContext &Ctx) const {
Ted Kremenek49b1e382012-01-26 21:29:00 +00003574 ProgramStateRef state = Ctx.getState();
Jordan Rose0c153cb2012-11-02 01:54:06 +00003575 RefBindingsTy B = state->get<RefBindings>();
Anna Zaks3eae3342011-10-25 19:56:48 +00003576 ExplodedNode *Pred = Ctx.getPredecessor();
Jordy Rose78612762011-08-23 19:01:07 +00003577
Jordan Rose7699e4a2013-08-01 22:16:36 +00003578 // Don't process anything within synthesized bodies.
3579 const LocationContext *LCtx = Pred->getLocationContext();
3580 if (LCtx->getAnalysisDeclContext()->isBodyAutosynthesized()) {
3581 assert(LCtx->getParent());
3582 return;
3583 }
3584
Jordan Rose0c153cb2012-11-02 01:54:06 +00003585 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Jordan Roseff03c1d2012-12-06 18:58:18 +00003586 state = handleAutoreleaseCounts(state, Pred, /*Tag=*/0, Ctx,
3587 I->first, I->second);
Jordy Rose6763e382011-08-23 20:07:14 +00003588 if (!state)
Jordy Rose78612762011-08-23 19:01:07 +00003589 return;
3590 }
3591
Ted Kremeneka2bbac32012-02-07 00:24:33 +00003592 // If the current LocationContext has a parent, don't check for leaks.
3593 // We will do that later.
Anna Zaksf5788c72012-08-14 00:36:15 +00003594 // FIXME: we should instead check for imbalances of the retain/releases,
Ted Kremeneka2bbac32012-02-07 00:24:33 +00003595 // and suggest annotations.
Jordan Rose7699e4a2013-08-01 22:16:36 +00003596 if (LCtx->getParent())
Ted Kremeneka2bbac32012-02-07 00:24:33 +00003597 return;
3598
Jordy Rose78612762011-08-23 19:01:07 +00003599 B = state->get<RefBindings>();
3600 SmallVector<SymbolRef, 10> Leaked;
3601
Jordan Rose0c153cb2012-11-02 01:54:06 +00003602 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I)
Jordy Rose6763e382011-08-23 20:07:14 +00003603 state = handleSymbolDeath(state, I->first, I->second, Leaked);
Jordy Rose78612762011-08-23 19:01:07 +00003604
Jordan Rose9f61f8a2012-08-18 00:30:16 +00003605 processLeaks(state, Leaked, Ctx, Pred);
Jordy Rose78612762011-08-23 19:01:07 +00003606}
3607
3608const ProgramPointTag *
Jordy Rose75e680e2011-09-02 06:44:22 +00003609RetainCountChecker::getDeadSymbolTag(SymbolRef sym) const {
Jordy Rose78612762011-08-23 19:01:07 +00003610 const SimpleProgramPointTag *&tag = DeadSymbolTags[sym];
3611 if (!tag) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003612 SmallString<64> buf;
Jordy Rose78612762011-08-23 19:01:07 +00003613 llvm::raw_svector_ostream out(buf);
Anna Zaks22351652011-12-05 18:58:11 +00003614 out << "RetainCountChecker : Dead Symbol : ";
3615 sym->dumpToStream(out);
Jordy Rose78612762011-08-23 19:01:07 +00003616 tag = new SimpleProgramPointTag(out.str());
3617 }
3618 return tag;
3619}
3620
Jordy Rose75e680e2011-09-02 06:44:22 +00003621void RetainCountChecker::checkDeadSymbols(SymbolReaper &SymReaper,
3622 CheckerContext &C) const {
Jordy Rose78612762011-08-23 19:01:07 +00003623 ExplodedNode *Pred = C.getPredecessor();
3624
Ted Kremenek49b1e382012-01-26 21:29:00 +00003625 ProgramStateRef state = C.getState();
Jordan Rose0c153cb2012-11-02 01:54:06 +00003626 RefBindingsTy B = state->get<RefBindings>();
Jordan Roseff03c1d2012-12-06 18:58:18 +00003627 SmallVector<SymbolRef, 10> Leaked;
Jordy Rose78612762011-08-23 19:01:07 +00003628
3629 // Update counts from autorelease pools
3630 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3631 E = SymReaper.dead_end(); I != E; ++I) {
3632 SymbolRef Sym = *I;
3633 if (const RefVal *T = B.lookup(Sym)){
3634 // Use the symbol as the tag.
3635 // FIXME: This might not be as unique as we would like.
Jordan Rose9f61f8a2012-08-18 00:30:16 +00003636 const ProgramPointTag *Tag = getDeadSymbolTag(Sym);
Jordan Roseff03c1d2012-12-06 18:58:18 +00003637 state = handleAutoreleaseCounts(state, Pred, Tag, C, Sym, *T);
Jordy Rose6763e382011-08-23 20:07:14 +00003638 if (!state)
Jordy Rose78612762011-08-23 19:01:07 +00003639 return;
Jordan Roseff03c1d2012-12-06 18:58:18 +00003640
3641 // Fetch the new reference count from the state, and use it to handle
3642 // this symbol.
3643 state = handleSymbolDeath(state, *I, *getRefBinding(state, Sym), Leaked);
Jordy Rose78612762011-08-23 19:01:07 +00003644 }
3645 }
3646
Jordan Roseff03c1d2012-12-06 18:58:18 +00003647 if (Leaked.empty()) {
3648 C.addTransition(state);
3649 return;
Jordy Rose78612762011-08-23 19:01:07 +00003650 }
3651
Jordan Rose9f61f8a2012-08-18 00:30:16 +00003652 Pred = processLeaks(state, Leaked, C, Pred);
Jordy Rose78612762011-08-23 19:01:07 +00003653
3654 // Did we cache out?
3655 if (!Pred)
3656 return;
3657
3658 // Now generate a new node that nukes the old bindings.
Jordan Roseff03c1d2012-12-06 18:58:18 +00003659 // The only bindings left at this point are the leaked symbols.
Jordan Rose0c153cb2012-11-02 01:54:06 +00003660 RefBindingsTy::Factory &F = state->get_context<RefBindings>();
Jordan Roseff03c1d2012-12-06 18:58:18 +00003661 B = state->get<RefBindings>();
Jordy Rose78612762011-08-23 19:01:07 +00003662
Jordan Roseff03c1d2012-12-06 18:58:18 +00003663 for (SmallVectorImpl<SymbolRef>::iterator I = Leaked.begin(),
3664 E = Leaked.end();
3665 I != E; ++I)
Jordy Rose78612762011-08-23 19:01:07 +00003666 B = F.remove(B, *I);
3667
3668 state = state->set<RefBindings>(B);
Anna Zaksda4c8d62011-10-26 21:06:34 +00003669 C.addTransition(state, Pred);
Jordy Rose78612762011-08-23 19:01:07 +00003670}
3671
Ted Kremenek49b1e382012-01-26 21:29:00 +00003672void RetainCountChecker::printState(raw_ostream &Out, ProgramStateRef State,
Jordy Rose75e680e2011-09-02 06:44:22 +00003673 const char *NL, const char *Sep) const {
Jordy Rose58a20d32011-08-28 19:11:56 +00003674
Jordan Rose0c153cb2012-11-02 01:54:06 +00003675 RefBindingsTy B = State->get<RefBindings>();
Jordy Rose58a20d32011-08-28 19:11:56 +00003676
Ted Kremenekdb70b522013-03-28 18:43:18 +00003677 if (B.isEmpty())
3678 return;
3679
3680 Out << Sep << NL;
Jordy Rose58a20d32011-08-28 19:11:56 +00003681
Jordan Rose0c153cb2012-11-02 01:54:06 +00003682 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Jordy Rose58a20d32011-08-28 19:11:56 +00003683 Out << I->first << " : ";
3684 I->second.print(Out);
3685 Out << NL;
3686 }
Jordy Rose58a20d32011-08-28 19:11:56 +00003687}
3688
3689//===----------------------------------------------------------------------===//
Jordy Rose75e680e2011-09-02 06:44:22 +00003690// Checker registration.
Ted Kremenek819e9b62008-03-11 06:39:11 +00003691//===----------------------------------------------------------------------===//
3692
Jordy Rosec49ec532011-09-02 05:55:19 +00003693void ento::registerRetainCountChecker(CheckerManager &Mgr) {
Ted Kremenek8671acb2013-04-16 21:44:22 +00003694 Mgr.registerChecker<RetainCountChecker>(Mgr.getAnalyzerOptions());
Jordy Rosec49ec532011-09-02 05:55:19 +00003695}
3696
Ted Kremenek71c080f2013-08-14 23:41:49 +00003697//===----------------------------------------------------------------------===//
3698// Implementation of the CallEffects API.
3699//===----------------------------------------------------------------------===//
3700
3701namespace clang { namespace ento { namespace objc_retain {
3702
3703// This is a bit gross, but it allows us to populate CallEffects without
3704// creating a bunch of accessors. This kind is very localized, so the
3705// damage of this macro is limited.
3706#define createCallEffect(D, KIND)\
3707 ASTContext &Ctx = D->getASTContext();\
3708 LangOptions L = Ctx.getLangOpts();\
3709 RetainSummaryManager M(Ctx, L.GCOnly, L.ObjCAutoRefCount);\
3710 const RetainSummary *S = M.get ## KIND ## Summary(D);\
3711 CallEffects CE(S->getRetEffect());\
3712 CE.Receiver = S->getReceiverEffect();\
Ted Kremeneke19529b2013-08-16 23:14:22 +00003713 unsigned N = D->param_size();\
Ted Kremenek71c080f2013-08-14 23:41:49 +00003714 for (unsigned i = 0; i < N; ++i) {\
3715 CE.Args.push_back(S->getArg(i));\
3716 }
3717
3718CallEffects CallEffects::getEffect(const ObjCMethodDecl *MD) {
3719 createCallEffect(MD, Method);
3720 return CE;
3721}
3722
3723CallEffects CallEffects::getEffect(const FunctionDecl *FD) {
3724 createCallEffect(FD, Function);
3725 return CE;
3726}
3727
3728#undef createCallEffect
3729
3730}}}