blob: c51b7af44536c35c681da9baf81e1675d22dd6e7 [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"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000016#include "AllocationDiagnostics.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000017#include "clang/AST/Attr.h"
Ted Kremenek98a24e32011-03-30 17:41:19 +000018#include "clang/AST/DeclCXX.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000019#include "clang/AST/DeclObjC.h"
20#include "clang/AST/ParentMap.h"
21#include "clang/Analysis/DomainSpecific/CocoaConventions.h"
Ted Kremenek2b36f3f2010-02-18 00:05:58 +000022#include "clang/Basic/LangOptions.h"
23#include "clang/Basic/SourceManager.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000024#include "clang/StaticAnalyzer/Checkers/ObjCRetainCount.h"
Ted Kremenekf8cbac42011-02-10 01:03:03 +000025#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
26#include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000027#include "clang/StaticAnalyzer/Core/Checker.h"
28#include "clang/StaticAnalyzer/Core/CheckerManager.h"
Jordan Rose4f7df9b2012-07-26 21:39:41 +000029#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
Jordy Rose75e680e2011-09-02 06:44:22 +000030#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
Ted Kremenek001fd5b2011-08-15 22:09:50 +000031#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
Ted Kremenekf8cbac42011-02-10 01:03:03 +000032#include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
Ted Kremenek819e9b62008-03-11 06:39:11 +000033#include "llvm/ADT/DenseMap.h"
34#include "llvm/ADT/FoldingSet.h"
Ted Kremenek0747e7e2008-10-21 15:53:15 +000035#include "llvm/ADT/ImmutableList.h"
Ted Kremenek2b36f3f2010-02-18 00:05:58 +000036#include "llvm/ADT/ImmutableMap.h"
Ted Kremenekc812b232008-05-16 18:33:44 +000037#include "llvm/ADT/STLExtras.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000038#include "llvm/ADT/SmallString.h"
Ted Kremenek2b36f3f2010-02-18 00:05:58 +000039#include "llvm/ADT/StringExtras.h"
Chris Lattner0e62c1c2011-07-23 10:55:15 +000040#include <cstdarg>
Ted Kremenekea6507f2008-03-06 00:08:09 +000041
42using namespace clang;
Ted Kremenek98857c92010-12-23 07:20:52 +000043using namespace ento;
Ted Kremenek243c0852013-08-14 23:41:46 +000044using namespace objc_retain;
Ted Kremenekdb1832d2010-01-27 06:13:48 +000045using llvm::StrInStrNoCase;
Ted Kremenek2855a932008-11-05 16:54:44 +000046
Ted Kremenekc8bef6a2008-04-09 23:49:11 +000047//===----------------------------------------------------------------------===//
Ted Kremenek243c0852013-08-14 23:41:46 +000048// Adapters for FoldingSet.
Ted Kremenekc8bef6a2008-04-09 23:49:11 +000049//===----------------------------------------------------------------------===//
50
Ted Kremenek819e9b62008-03-11 06:39:11 +000051namespace llvm {
Ted Kremenek7d79a5f2009-05-03 05:20:50 +000052template <> struct FoldingSetTrait<ArgEffect> {
Ted Kremenek243c0852013-08-14 23:41:46 +000053static inline void Profile(const ArgEffect X, FoldingSetNodeID &ID) {
Ted Kremenek7d79a5f2009-05-03 05:20:50 +000054 ID.AddInteger((unsigned) X);
55}
Ted Kremenek3185c9c2008-06-25 21:21:56 +000056};
Ted Kremenek243c0852013-08-14 23:41:46 +000057template <> struct FoldingSetTrait<RetEffect> {
58 static inline void Profile(const RetEffect &X, FoldingSetNodeID &ID) {
59 ID.AddInteger((unsigned) X.getKind());
60 ID.AddInteger((unsigned) X.getObjKind());
61}
62};
Ted Kremenek819e9b62008-03-11 06:39:11 +000063} // end llvm namespace
64
Ted Kremenek243c0852013-08-14 23:41:46 +000065//===----------------------------------------------------------------------===//
66// Reference-counting logic (typestate + counts).
67//===----------------------------------------------------------------------===//
68
Ted Kremenek7d79a5f2009-05-03 05:20:50 +000069/// ArgEffects summarizes the effects of a function/method call on all of
70/// its arguments.
71typedef llvm::ImmutableMap<unsigned,ArgEffect> ArgEffects;
72
Ted Kremenek819e9b62008-03-11 06:39:11 +000073namespace {
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +000074class RefVal {
Ted Kremeneka2968e52009-11-13 01:54:21 +000075public:
76 enum Kind {
77 Owned = 0, // Owning reference.
78 NotOwned, // Reference is not owned by still valid (not freed).
79 Released, // Object has been released.
80 ReturnedOwned, // Returned object passes ownership to caller.
81 ReturnedNotOwned, // Return object does not pass ownership to caller.
82 ERROR_START,
83 ErrorDeallocNotOwned, // -dealloc called on non-owned object.
84 ErrorDeallocGC, // Calling -dealloc with GC enabled.
85 ErrorUseAfterRelease, // Object used after released.
86 ErrorReleaseNotOwned, // Release of an object that was not owned.
87 ERROR_LEAK_START,
88 ErrorLeak, // A memory leak due to excessive reference counts.
89 ErrorLeakReturned, // A memory leak due to the returning method not having
90 // the correct naming conventions.
91 ErrorGCLeakReturned,
92 ErrorOverAutorelease,
93 ErrorReturnedNotOwned
94 };
Ted Kremenekbd862712010-07-01 20:16:50 +000095
Ted Kremeneka2968e52009-11-13 01:54:21 +000096private:
97 Kind kind;
98 RetEffect::ObjKind okind;
99 unsigned Cnt;
100 unsigned ACnt;
101 QualType T;
Ted Kremenekbd862712010-07-01 20:16:50 +0000102
Ted Kremeneka2968e52009-11-13 01:54:21 +0000103 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, unsigned acnt, QualType t)
104 : kind(k), okind(o), Cnt(cnt), ACnt(acnt), T(t) {}
Ted Kremenekbd862712010-07-01 20:16:50 +0000105
Ted Kremeneka2968e52009-11-13 01:54:21 +0000106public:
107 Kind getKind() const { return kind; }
Ted Kremenekbd862712010-07-01 20:16:50 +0000108
Ted Kremeneka2968e52009-11-13 01:54:21 +0000109 RetEffect::ObjKind getObjKind() const { return okind; }
Ted Kremenekbd862712010-07-01 20:16:50 +0000110
Ted Kremeneka2968e52009-11-13 01:54:21 +0000111 unsigned getCount() const { return Cnt; }
112 unsigned getAutoreleaseCount() const { return ACnt; }
113 unsigned getCombinedCounts() const { return Cnt + ACnt; }
114 void clearCounts() { Cnt = 0; ACnt = 0; }
115 void setCount(unsigned i) { Cnt = i; }
116 void setAutoreleaseCount(unsigned i) { ACnt = i; }
Ted Kremenekbd862712010-07-01 20:16:50 +0000117
Ted Kremeneka2968e52009-11-13 01:54:21 +0000118 QualType getType() const { return T; }
Ted Kremenekbd862712010-07-01 20:16:50 +0000119
Ted Kremeneka2968e52009-11-13 01:54:21 +0000120 bool isOwned() const {
121 return getKind() == Owned;
122 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000123
Ted Kremeneka2968e52009-11-13 01:54:21 +0000124 bool isNotOwned() const {
125 return getKind() == NotOwned;
126 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000127
Ted Kremeneka2968e52009-11-13 01:54:21 +0000128 bool isReturnedOwned() const {
129 return getKind() == ReturnedOwned;
130 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000131
Ted Kremeneka2968e52009-11-13 01:54:21 +0000132 bool isReturnedNotOwned() const {
133 return getKind() == ReturnedNotOwned;
134 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000135
Ted Kremeneka2968e52009-11-13 01:54:21 +0000136 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
137 unsigned Count = 1) {
138 return RefVal(Owned, o, Count, 0, t);
139 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000140
Ted Kremeneka2968e52009-11-13 01:54:21 +0000141 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
142 unsigned Count = 0) {
143 return RefVal(NotOwned, o, Count, 0, t);
144 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000145
Ted Kremeneka2968e52009-11-13 01:54:21 +0000146 // Comparison, profiling, and pretty-printing.
Ted Kremenekbd862712010-07-01 20:16:50 +0000147
Ted Kremeneka2968e52009-11-13 01:54:21 +0000148 bool operator==(const RefVal& X) const {
149 return kind == X.kind && Cnt == X.Cnt && T == X.T && ACnt == X.ACnt;
150 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000151
Ted Kremeneka2968e52009-11-13 01:54:21 +0000152 RefVal operator-(size_t i) const {
153 return RefVal(getKind(), getObjKind(), getCount() - i,
154 getAutoreleaseCount(), getType());
155 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000156
Ted Kremeneka2968e52009-11-13 01:54:21 +0000157 RefVal operator+(size_t i) const {
158 return RefVal(getKind(), getObjKind(), getCount() + i,
159 getAutoreleaseCount(), getType());
160 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000161
Ted Kremeneka2968e52009-11-13 01:54:21 +0000162 RefVal operator^(Kind k) const {
163 return RefVal(k, getObjKind(), getCount(), getAutoreleaseCount(),
164 getType());
165 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000166
Ted Kremeneka2968e52009-11-13 01:54:21 +0000167 RefVal autorelease() const {
168 return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount()+1,
169 getType());
170 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000171
Ted Kremeneka2968e52009-11-13 01:54:21 +0000172 void Profile(llvm::FoldingSetNodeID& ID) const {
173 ID.AddInteger((unsigned) kind);
174 ID.AddInteger(Cnt);
175 ID.AddInteger(ACnt);
176 ID.Add(T);
177 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000178
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000179 void print(raw_ostream &Out) const;
Ted Kremeneka2968e52009-11-13 01:54:21 +0000180};
181
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000182void RefVal::print(raw_ostream &Out) const {
Ted Kremeneka2968e52009-11-13 01:54:21 +0000183 if (!T.isNull())
Jordy Rose58a20d32011-08-28 19:11:56 +0000184 Out << "Tracked " << T.getAsString() << '/';
Ted Kremenekbd862712010-07-01 20:16:50 +0000185
Ted Kremeneka2968e52009-11-13 01:54:21 +0000186 switch (getKind()) {
Jordy Rose75e680e2011-09-02 06:44:22 +0000187 default: llvm_unreachable("Invalid RefVal kind");
Ted Kremeneka2968e52009-11-13 01:54:21 +0000188 case Owned: {
189 Out << "Owned";
190 unsigned cnt = getCount();
191 if (cnt) Out << " (+ " << cnt << ")";
192 break;
193 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000194
Ted Kremeneka2968e52009-11-13 01:54:21 +0000195 case NotOwned: {
196 Out << "NotOwned";
197 unsigned cnt = getCount();
198 if (cnt) Out << " (+ " << cnt << ")";
199 break;
200 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000201
Ted Kremeneka2968e52009-11-13 01:54:21 +0000202 case ReturnedOwned: {
203 Out << "ReturnedOwned";
204 unsigned cnt = getCount();
205 if (cnt) Out << " (+ " << cnt << ")";
206 break;
207 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000208
Ted Kremeneka2968e52009-11-13 01:54:21 +0000209 case ReturnedNotOwned: {
210 Out << "ReturnedNotOwned";
211 unsigned cnt = getCount();
212 if (cnt) Out << " (+ " << cnt << ")";
213 break;
214 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000215
Ted Kremeneka2968e52009-11-13 01:54:21 +0000216 case Released:
217 Out << "Released";
218 break;
Ted Kremenekbd862712010-07-01 20:16:50 +0000219
Ted Kremeneka2968e52009-11-13 01:54:21 +0000220 case ErrorDeallocGC:
221 Out << "-dealloc (GC)";
222 break;
Ted Kremenekbd862712010-07-01 20:16:50 +0000223
Ted Kremeneka2968e52009-11-13 01:54:21 +0000224 case ErrorDeallocNotOwned:
225 Out << "-dealloc (not-owned)";
226 break;
Ted Kremenekbd862712010-07-01 20:16:50 +0000227
Ted Kremeneka2968e52009-11-13 01:54:21 +0000228 case ErrorLeak:
229 Out << "Leaked";
230 break;
Ted Kremenekbd862712010-07-01 20:16:50 +0000231
Ted Kremeneka2968e52009-11-13 01:54:21 +0000232 case ErrorLeakReturned:
233 Out << "Leaked (Bad naming)";
234 break;
Ted Kremenekbd862712010-07-01 20:16:50 +0000235
Ted Kremeneka2968e52009-11-13 01:54:21 +0000236 case ErrorGCLeakReturned:
237 Out << "Leaked (GC-ed at return)";
238 break;
Ted Kremenekbd862712010-07-01 20:16:50 +0000239
Ted Kremeneka2968e52009-11-13 01:54:21 +0000240 case ErrorUseAfterRelease:
241 Out << "Use-After-Release [ERROR]";
242 break;
Ted Kremenekbd862712010-07-01 20:16:50 +0000243
Ted Kremeneka2968e52009-11-13 01:54:21 +0000244 case ErrorReleaseNotOwned:
245 Out << "Release of Not-Owned [ERROR]";
246 break;
Ted Kremenekbd862712010-07-01 20:16:50 +0000247
Ted Kremeneka2968e52009-11-13 01:54:21 +0000248 case RefVal::ErrorOverAutorelease:
Jordan Rose7467f062013-04-23 01:42:25 +0000249 Out << "Over-autoreleased";
Ted Kremeneka2968e52009-11-13 01:54:21 +0000250 break;
Ted Kremenekbd862712010-07-01 20:16:50 +0000251
Ted Kremeneka2968e52009-11-13 01:54:21 +0000252 case RefVal::ErrorReturnedNotOwned:
253 Out << "Non-owned object returned instead of owned";
254 break;
255 }
Ted Kremenekbd862712010-07-01 20:16:50 +0000256
Ted Kremeneka2968e52009-11-13 01:54:21 +0000257 if (ACnt) {
258 Out << " [ARC +" << ACnt << ']';
259 }
260}
261} //end anonymous namespace
262
263//===----------------------------------------------------------------------===//
264// RefBindings - State used to track object reference counts.
265//===----------------------------------------------------------------------===//
266
Jordan Rose0c153cb2012-11-02 01:54:06 +0000267REGISTER_MAP_WITH_PROGRAMSTATE(RefBindings, SymbolRef, RefVal)
Ted Kremeneka2968e52009-11-13 01:54:21 +0000268
Anna Zaksf5788c72012-08-14 00:36:15 +0000269static inline const RefVal *getRefBinding(ProgramStateRef State,
270 SymbolRef Sym) {
271 return State->get<RefBindings>(Sym);
272}
273
274static inline ProgramStateRef setRefBinding(ProgramStateRef State,
275 SymbolRef Sym, RefVal Val) {
276 return State->set<RefBindings>(Sym, Val);
277}
278
279static ProgramStateRef removeRefBinding(ProgramStateRef State, SymbolRef Sym) {
280 return State->remove<RefBindings>(Sym);
281}
282
Ted Kremeneka2968e52009-11-13 01:54:21 +0000283//===----------------------------------------------------------------------===//
Jordy Rose75e680e2011-09-02 06:44:22 +0000284// Function/Method behavior summaries.
Ted Kremeneka2968e52009-11-13 01:54:21 +0000285//===----------------------------------------------------------------------===//
286
287namespace {
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +0000288class RetainSummary {
Jordy Rose61c974b2012-03-18 01:26:10 +0000289 /// Args - a map of (index, ArgEffect) pairs, where index
Ted Kremenekcb2e6362008-05-06 15:44:25 +0000290 /// specifies the argument (starting from 0). This can be sparsely
291 /// populated; arguments with no entry in Args use 'DefaultArgEffect'.
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000292 ArgEffects Args;
Mike Stump11289f42009-09-09 15:08:12 +0000293
Ted Kremenekcb2e6362008-05-06 15:44:25 +0000294 /// DefaultArgEffect - The default ArgEffect to apply to arguments that
295 /// do not have an entry in Args.
Ted Kremeneke8300e52012-01-04 00:35:45 +0000296 ArgEffect DefaultArgEffect;
Mike Stump11289f42009-09-09 15:08:12 +0000297
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000298 /// Receiver - If this summary applies to an Objective-C message expression,
299 /// this is the effect applied to the state of the receiver.
Ted Kremeneke8300e52012-01-04 00:35:45 +0000300 ArgEffect Receiver;
Mike Stump11289f42009-09-09 15:08:12 +0000301
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000302 /// Ret - The effect on the return value. Used to indicate if the
Jordy Rose898a1482011-08-21 21:58:18 +0000303 /// function/method call returns a new tracked symbol.
Ted Kremeneke8300e52012-01-04 00:35:45 +0000304 RetEffect Ret;
Mike Stump11289f42009-09-09 15:08:12 +0000305
Ted Kremenek819e9b62008-03-11 06:39:11 +0000306public:
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000307 RetainSummary(ArgEffects A, RetEffect R, ArgEffect defaultEff,
Jordy Rose5a3c9ff2011-08-20 20:55:40 +0000308 ArgEffect ReceiverEff)
309 : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R) {}
Mike Stump11289f42009-09-09 15:08:12 +0000310
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000311 /// getArg - Return the argument effect on the argument specified by
312 /// idx (starting from 0).
Ted Kremenekbf9d8042008-03-11 17:48:22 +0000313 ArgEffect getArg(unsigned idx) const {
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000314 if (const ArgEffect *AE = Args.lookup(idx))
315 return *AE;
Mike Stump11289f42009-09-09 15:08:12 +0000316
Ted Kremenekcb2e6362008-05-06 15:44:25 +0000317 return DefaultArgEffect;
Ted Kremenekbf9d8042008-03-11 17:48:22 +0000318 }
Ted Kremenek71c080f2013-08-14 23:41:49 +0000319
Ted Kremenekafe348e2011-01-27 18:43:03 +0000320 void addArg(ArgEffects::Factory &af, unsigned idx, ArgEffect e) {
321 Args = af.add(Args, idx, e);
322 }
Mike Stump11289f42009-09-09 15:08:12 +0000323
Ted Kremenek1d9a2672009-05-04 05:31:22 +0000324 /// setDefaultArgEffect - Set the default argument effect.
325 void setDefaultArgEffect(ArgEffect E) {
326 DefaultArgEffect = E;
327 }
Mike Stump11289f42009-09-09 15:08:12 +0000328
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000329 /// getRetEffect - Returns the effect on the return value of the call.
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000330 RetEffect getRetEffect() const { return Ret; }
Mike Stump11289f42009-09-09 15:08:12 +0000331
Ted Kremenek1d9a2672009-05-04 05:31:22 +0000332 /// setRetEffect - Set the effect of the return value of the call.
333 void setRetEffect(RetEffect E) { Ret = E; }
Mike Stump11289f42009-09-09 15:08:12 +0000334
Ted Kremenek0e898382011-01-27 06:54:14 +0000335
336 /// Sets the effect on the receiver of the message.
337 void setReceiverEffect(ArgEffect e) { Receiver = e; }
338
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000339 /// getReceiverEffect - Returns the effect on the receiver of the call.
340 /// This is only meaningful if the summary applies to an ObjCMessageExpr*.
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000341 ArgEffect getReceiverEffect() const { return Receiver; }
Jordy Rose212e4592011-08-23 04:27:15 +0000342
343 /// Test if two retain summaries are identical. Note that merely equivalent
344 /// summaries are not necessarily identical (for example, if an explicit
345 /// argument effect matches the default effect).
346 bool operator==(const RetainSummary &Other) const {
347 return Args == Other.Args && DefaultArgEffect == Other.DefaultArgEffect &&
348 Receiver == Other.Receiver && Ret == Other.Ret;
349 }
Jordy Rose61c974b2012-03-18 01:26:10 +0000350
351 /// Profile this summary for inclusion in a FoldingSet.
352 void Profile(llvm::FoldingSetNodeID& ID) const {
353 ID.Add(Args);
354 ID.Add(DefaultArgEffect);
355 ID.Add(Receiver);
356 ID.Add(Ret);
357 }
358
359 /// A retain summary is simple if it has no ArgEffects other than the default.
360 bool isSimple() const {
361 return Args.isEmpty();
362 }
Jordan Roseeec15392012-07-02 19:27:43 +0000363
364private:
365 ArgEffects getArgEffects() const { return Args; }
366 ArgEffect getDefaultArgEffect() const { return DefaultArgEffect; }
367
368 friend class RetainSummaryManager;
Ted Kremenek819e9b62008-03-11 06:39:11 +0000369};
Ted Kremenek0cfc1612008-06-23 23:30:29 +0000370} // end anonymous namespace
Ted Kremenek819e9b62008-03-11 06:39:11 +0000371
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000372//===----------------------------------------------------------------------===//
373// Data structures for constructing summaries.
374//===----------------------------------------------------------------------===//
Ted Kremenekb1d13292008-06-24 03:49:48 +0000375
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000376namespace {
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +0000377class ObjCSummaryKey {
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000378 IdentifierInfo* II;
379 Selector S;
Mike Stump11289f42009-09-09 15:08:12 +0000380public:
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000381 ObjCSummaryKey(IdentifierInfo* ii, Selector s)
382 : II(ii), S(s) {}
383
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000384 ObjCSummaryKey(const ObjCInterfaceDecl *d, Selector s)
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000385 : II(d ? d->getIdentifier() : 0), S(s) {}
Ted Kremenek5801f652009-05-13 18:16:01 +0000386
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000387 ObjCSummaryKey(Selector s)
388 : II(0), S(s) {}
Mike Stump11289f42009-09-09 15:08:12 +0000389
Ted Kremeneke8300e52012-01-04 00:35:45 +0000390 IdentifierInfo *getIdentifier() const { return II; }
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000391 Selector getSelector() const { return S; }
392};
Ted Kremenek0cfc1612008-06-23 23:30:29 +0000393}
394
395namespace llvm {
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000396template <> struct DenseMapInfo<ObjCSummaryKey> {
397 static inline ObjCSummaryKey getEmptyKey() {
398 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
399 DenseMapInfo<Selector>::getEmptyKey());
400 }
Mike Stump11289f42009-09-09 15:08:12 +0000401
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000402 static inline ObjCSummaryKey getTombstoneKey() {
403 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
Mike Stump11289f42009-09-09 15:08:12 +0000404 DenseMapInfo<Selector>::getTombstoneKey());
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000405 }
Mike Stump11289f42009-09-09 15:08:12 +0000406
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000407 static unsigned getHashValue(const ObjCSummaryKey &V) {
Benjamin Kramer69b5a602012-05-27 13:28:44 +0000408 typedef std::pair<IdentifierInfo*, Selector> PairTy;
409 return DenseMapInfo<PairTy>::getHashValue(PairTy(V.getIdentifier(),
410 V.getSelector()));
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000411 }
Mike Stump11289f42009-09-09 15:08:12 +0000412
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000413 static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
Benjamin Kramer69b5a602012-05-27 13:28:44 +0000414 return LHS.getIdentifier() == RHS.getIdentifier() &&
415 LHS.getSelector() == RHS.getSelector();
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000416 }
Mike Stump11289f42009-09-09 15:08:12 +0000417
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000418};
Ted Kremenek0cfc1612008-06-23 23:30:29 +0000419} // end llvm namespace
Mike Stump11289f42009-09-09 15:08:12 +0000420
Ted Kremenek0cfc1612008-06-23 23:30:29 +0000421namespace {
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +0000422class ObjCSummaryCache {
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000423 typedef llvm::DenseMap<ObjCSummaryKey, const RetainSummary *> MapTy;
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000424 MapTy M;
425public:
426 ObjCSummaryCache() {}
Mike Stump11289f42009-09-09 15:08:12 +0000427
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000428 const RetainSummary * find(const ObjCInterfaceDecl *D, Selector S) {
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000429 // Do a lookup with the (D,S) pair. If we find a match return
430 // the iterator.
431 ObjCSummaryKey K(D, S);
432 MapTy::iterator I = M.find(K);
Mike Stump11289f42009-09-09 15:08:12 +0000433
Jordan Roseeec15392012-07-02 19:27:43 +0000434 if (I != M.end())
Ted Kremenek8be51382009-07-21 23:27:57 +0000435 return I->second;
Jordan Roseeec15392012-07-02 19:27:43 +0000436 if (!D)
437 return NULL;
Mike Stump11289f42009-09-09 15:08:12 +0000438
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000439 // Walk the super chain. If we find a hit with a parent, we'll end
440 // up returning that summary. We actually allow that key (null,S), as
441 // we cache summaries for the null ObjCInterfaceDecl* to allow us to
442 // generate initial summaries without having to worry about NSObject
443 // being declared.
444 // FIXME: We may change this at some point.
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000445 for (ObjCInterfaceDecl *C=D->getSuperClass() ;; C=C->getSuperClass()) {
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000446 if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
447 break;
Mike Stump11289f42009-09-09 15:08:12 +0000448
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000449 if (!C)
Ted Kremenek8be51382009-07-21 23:27:57 +0000450 return NULL;
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000451 }
Mike Stump11289f42009-09-09 15:08:12 +0000452
453 // Cache the summary with original key to make the next lookup faster
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000454 // and return the iterator.
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000455 const RetainSummary *Summ = I->second;
Ted Kremenek8be51382009-07-21 23:27:57 +0000456 M[K] = Summ;
457 return Summ;
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000458 }
Mike Stump11289f42009-09-09 15:08:12 +0000459
Ted Kremeneke8300e52012-01-04 00:35:45 +0000460 const RetainSummary *find(IdentifierInfo* II, Selector S) {
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000461 // FIXME: Class method lookup. Right now we dont' have a good way
462 // of going between IdentifierInfo* and the class hierarchy.
Ted Kremenek8be51382009-07-21 23:27:57 +0000463 MapTy::iterator I = M.find(ObjCSummaryKey(II, S));
Mike Stump11289f42009-09-09 15:08:12 +0000464
Ted Kremenek8be51382009-07-21 23:27:57 +0000465 if (I == M.end())
466 I = M.find(ObjCSummaryKey(S));
Mike Stump11289f42009-09-09 15:08:12 +0000467
Ted Kremenek8be51382009-07-21 23:27:57 +0000468 return I == M.end() ? NULL : I->second;
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000469 }
Mike Stump11289f42009-09-09 15:08:12 +0000470
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000471 const RetainSummary *& operator[](ObjCSummaryKey K) {
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000472 return M[K];
473 }
Mike Stump11289f42009-09-09 15:08:12 +0000474
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000475 const RetainSummary *& operator[](Selector S) {
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000476 return M[ ObjCSummaryKey(S) ];
477 }
Mike Stump11289f42009-09-09 15:08:12 +0000478};
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000479} // end anonymous namespace
480
481//===----------------------------------------------------------------------===//
482// Data structures for managing collections of summaries.
483//===----------------------------------------------------------------------===//
484
485namespace {
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +0000486class RetainSummaryManager {
Ted Kremenek00daccd2008-05-05 22:11:16 +0000487
488 //==-----------------------------------------------------------------==//
489 // Typedefs.
490 //==-----------------------------------------------------------------==//
Mike Stump11289f42009-09-09 15:08:12 +0000491
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000492 typedef llvm::DenseMap<const FunctionDecl*, const RetainSummary *>
Ted Kremenek00daccd2008-05-05 22:11:16 +0000493 FuncSummariesTy;
Mike Stump11289f42009-09-09 15:08:12 +0000494
Ted Kremenek0cfc1612008-06-23 23:30:29 +0000495 typedef ObjCSummaryCache ObjCMethodSummariesTy;
Mike Stump11289f42009-09-09 15:08:12 +0000496
Jordy Rose61c974b2012-03-18 01:26:10 +0000497 typedef llvm::FoldingSetNodeWrapper<RetainSummary> CachedSummaryNode;
498
Ted Kremenek00daccd2008-05-05 22:11:16 +0000499 //==-----------------------------------------------------------------==//
500 // Data.
501 //==-----------------------------------------------------------------==//
Mike Stump11289f42009-09-09 15:08:12 +0000502
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000503 /// Ctx - The ASTContext object for the analyzed ASTs.
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000504 ASTContext &Ctx;
Ted Kremenekab54e512008-07-01 17:21:27 +0000505
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000506 /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
Ted Kremenek4b7ca772008-04-29 05:33:51 +0000507 const bool GCEnabled;
Mike Stump11289f42009-09-09 15:08:12 +0000508
John McCall31168b02011-06-15 23:02:42 +0000509 /// Records whether or not the analyzed code runs in ARC mode.
510 const bool ARCEnabled;
511
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000512 /// FuncSummaries - A map from FunctionDecls to summaries.
Mike Stump11289f42009-09-09 15:08:12 +0000513 FuncSummariesTy FuncSummaries;
514
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000515 /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
516 /// to summaries.
Ted Kremenekea736c52008-06-23 22:21:20 +0000517 ObjCMethodSummariesTy ObjCClassMethodSummaries;
Ted Kremenek00daccd2008-05-05 22:11:16 +0000518
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000519 /// ObjCMethodSummaries - A map from selectors to summaries.
Ted Kremenekea736c52008-06-23 22:21:20 +0000520 ObjCMethodSummariesTy ObjCMethodSummaries;
Ted Kremenek00daccd2008-05-05 22:11:16 +0000521
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000522 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
523 /// and all other data used by the checker.
Ted Kremenek00daccd2008-05-05 22:11:16 +0000524 llvm::BumpPtrAllocator BPAlloc;
Mike Stump11289f42009-09-09 15:08:12 +0000525
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000526 /// AF - A factory for ArgEffects objects.
Mike Stump11289f42009-09-09 15:08:12 +0000527 ArgEffects::Factory AF;
528
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000529 /// ScratchArgs - A holding buffer for construct ArgEffects.
Ted Kremeneke8300e52012-01-04 00:35:45 +0000530 ArgEffects ScratchArgs;
Mike Stump11289f42009-09-09 15:08:12 +0000531
Ted Kremenek9157fbb2009-05-07 23:40:42 +0000532 /// ObjCAllocRetE - Default return effect for methods returning Objective-C
533 /// objects.
534 RetEffect ObjCAllocRetE;
Ted Kremeneka03705c2009-06-05 23:18:01 +0000535
Mike Stump11289f42009-09-09 15:08:12 +0000536 /// ObjCInitRetE - Default return effect for init methods returning
Ted Kremenek815fbb62009-08-20 05:13:36 +0000537 /// Objective-C objects.
Ted Kremeneka03705c2009-06-05 23:18:01 +0000538 RetEffect ObjCInitRetE;
Mike Stump11289f42009-09-09 15:08:12 +0000539
Jordy Rose61c974b2012-03-18 01:26:10 +0000540 /// SimpleSummaries - Used for uniquing summaries that don't have special
541 /// effects.
542 llvm::FoldingSet<CachedSummaryNode> SimpleSummaries;
Mike Stump11289f42009-09-09 15:08:12 +0000543
Ted Kremenek00daccd2008-05-05 22:11:16 +0000544 //==-----------------------------------------------------------------==//
545 // Methods.
546 //==-----------------------------------------------------------------==//
Mike Stump11289f42009-09-09 15:08:12 +0000547
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000548 /// getArgEffects - Returns a persistent ArgEffects object based on the
549 /// data in ScratchArgs.
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000550 ArgEffects getArgEffects();
Ted Kremenek819e9b62008-03-11 06:39:11 +0000551
Jordan Rose77411322013-10-07 17:16:52 +0000552 enum UnaryFuncKind { cfretain, cfrelease, cfautorelease, cfmakecollectable };
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000553
Ted Kremeneke8300e52012-01-04 00:35:45 +0000554 const RetainSummary *getUnarySummary(const FunctionType* FT,
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000555 UnaryFuncKind func);
Mike Stump11289f42009-09-09 15:08:12 +0000556
Ted Kremeneke8300e52012-01-04 00:35:45 +0000557 const RetainSummary *getCFSummaryCreateRule(const FunctionDecl *FD);
558 const RetainSummary *getCFSummaryGetRule(const FunctionDecl *FD);
559 const RetainSummary *getCFCreateGetRuleSummary(const FunctionDecl *FD);
Mike Stump11289f42009-09-09 15:08:12 +0000560
Jordy Rose61c974b2012-03-18 01:26:10 +0000561 const RetainSummary *getPersistentSummary(const RetainSummary &OldSumm);
Ted Kremenek3700b762008-10-29 04:07:07 +0000562
Jordy Rose61c974b2012-03-18 01:26:10 +0000563 const RetainSummary *getPersistentSummary(RetEffect RetEff,
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000564 ArgEffect ReceiverEff = DoNothing,
565 ArgEffect DefaultEff = MayEscape) {
Jordy Rose61c974b2012-03-18 01:26:10 +0000566 RetainSummary Summ(getArgEffects(), RetEff, DefaultEff, ReceiverEff);
567 return getPersistentSummary(Summ);
568 }
569
Ted Kremenekececf9f2012-05-08 00:12:09 +0000570 const RetainSummary *getDoNothingSummary() {
571 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
572 }
573
Jordy Rose61c974b2012-03-18 01:26:10 +0000574 const RetainSummary *getDefaultSummary() {
575 return getPersistentSummary(RetEffect::MakeNoRet(),
576 DoNothing, MayEscape);
Ted Kremenek0806f912008-05-06 00:30:21 +0000577 }
Mike Stump11289f42009-09-09 15:08:12 +0000578
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000579 const RetainSummary *getPersistentStopSummary() {
Jordy Rose61c974b2012-03-18 01:26:10 +0000580 return getPersistentSummary(RetEffect::MakeNoRet(),
581 StopTracking, StopTracking);
Mike Stump11289f42009-09-09 15:08:12 +0000582 }
Ted Kremenek015c3562008-05-06 04:20:12 +0000583
Ted Kremenekea736c52008-06-23 22:21:20 +0000584 void InitializeClassMethodSummaries();
585 void InitializeMethodSummaries();
Ted Kremenekcc3d1882008-10-23 01:56:15 +0000586private:
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000587 void addNSObjectClsMethSummary(Selector S, const RetainSummary *Summ) {
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000588 ObjCClassMethodSummaries[S] = Summ;
589 }
Mike Stump11289f42009-09-09 15:08:12 +0000590
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000591 void addNSObjectMethSummary(Selector S, const RetainSummary *Summ) {
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000592 ObjCMethodSummaries[S] = Summ;
593 }
Ted Kremenek00dfe302009-03-04 23:30:42 +0000594
Ted Kremeneke8a5ba82012-02-18 21:37:48 +0000595 void addClassMethSummary(const char* Cls, const char* name,
596 const RetainSummary *Summ, bool isNullary = true) {
Ted Kremenek00dfe302009-03-04 23:30:42 +0000597 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
Ted Kremeneke8a5ba82012-02-18 21:37:48 +0000598 Selector S = isNullary ? GetNullarySelector(name, Ctx)
599 : GetUnarySelector(name, Ctx);
Ted Kremenek00dfe302009-03-04 23:30:42 +0000600 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
601 }
Mike Stump11289f42009-09-09 15:08:12 +0000602
Ted Kremenekdce78462009-02-25 02:54:57 +0000603 void addInstMethSummary(const char* Cls, const char* nullaryName,
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000604 const RetainSummary *Summ) {
Ted Kremenekdce78462009-02-25 02:54:57 +0000605 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
606 Selector S = GetNullarySelector(nullaryName, Ctx);
607 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
608 }
Mike Stump11289f42009-09-09 15:08:12 +0000609
Ted Kremenek8a5ad392009-04-24 17:50:11 +0000610 Selector generateSelector(va_list argp) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000611 SmallVector<IdentifierInfo*, 10> II;
Ted Kremenek8a5ad392009-04-24 17:50:11 +0000612
Ted Kremenek050b91c2008-08-12 18:30:56 +0000613 while (const char* s = va_arg(argp, const char*))
614 II.push_back(&Ctx.Idents.get(s));
Ted Kremenek8a5ad392009-04-24 17:50:11 +0000615
Mike Stump11289f42009-09-09 15:08:12 +0000616 return Ctx.Selectors.getSelector(II.size(), &II[0]);
Ted Kremenek8a5ad392009-04-24 17:50:11 +0000617 }
Mike Stump11289f42009-09-09 15:08:12 +0000618
Ted Kremenek8a5ad392009-04-24 17:50:11 +0000619 void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy& Summaries,
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000620 const RetainSummary * Summ, va_list argp) {
Ted Kremenek8a5ad392009-04-24 17:50:11 +0000621 Selector S = generateSelector(argp);
622 Summaries[ObjCSummaryKey(ClsII, S)] = Summ;
Ted Kremenek3b2294c2008-07-18 17:24:20 +0000623 }
Mike Stump11289f42009-09-09 15:08:12 +0000624
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000625 void addInstMethSummary(const char* Cls, const RetainSummary * Summ, ...) {
Ted Kremenek3f13f592008-08-12 18:48:50 +0000626 va_list argp;
627 va_start(argp, Summ);
Ted Kremenek8a5ad392009-04-24 17:50:11 +0000628 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Mike Stump11289f42009-09-09 15:08:12 +0000629 va_end(argp);
Ted Kremenek3f13f592008-08-12 18:48:50 +0000630 }
Mike Stump11289f42009-09-09 15:08:12 +0000631
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000632 void addClsMethSummary(const char* Cls, const RetainSummary * Summ, ...) {
Ted Kremenek8a5ad392009-04-24 17:50:11 +0000633 va_list argp;
634 va_start(argp, Summ);
635 addMethodSummary(&Ctx.Idents.get(Cls),ObjCClassMethodSummaries, Summ, argp);
636 va_end(argp);
637 }
Mike Stump11289f42009-09-09 15:08:12 +0000638
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000639 void addClsMethSummary(IdentifierInfo *II, const RetainSummary * Summ, ...) {
Ted Kremenek8a5ad392009-04-24 17:50:11 +0000640 va_list argp;
641 va_start(argp, Summ);
642 addMethodSummary(II, ObjCClassMethodSummaries, Summ, argp);
643 va_end(argp);
644 }
645
Ted Kremenek819e9b62008-03-11 06:39:11 +0000646public:
Mike Stump11289f42009-09-09 15:08:12 +0000647
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000648 RetainSummaryManager(ASTContext &ctx, bool gcenabled, bool usesARC)
Ted Kremenekab54e512008-07-01 17:21:27 +0000649 : Ctx(ctx),
John McCall31168b02011-06-15 23:02:42 +0000650 GCEnabled(gcenabled),
651 ARCEnabled(usesARC),
652 AF(BPAlloc), ScratchArgs(AF.getEmptyMap()),
653 ObjCAllocRetE(gcenabled
654 ? RetEffect::MakeGCNotOwned()
655 : (usesARC ? RetEffect::MakeARCNotOwned()
656 : RetEffect::MakeOwned(RetEffect::ObjC, true))),
657 ObjCInitRetE(gcenabled
658 ? RetEffect::MakeGCNotOwned()
659 : (usesARC ? RetEffect::MakeARCNotOwned()
Jordy Rose61c974b2012-03-18 01:26:10 +0000660 : RetEffect::MakeOwnedWhenTrackedReceiver())) {
Ted Kremenek3185c9c2008-06-25 21:21:56 +0000661 InitializeClassMethodSummaries();
662 InitializeMethodSummaries();
663 }
Mike Stump11289f42009-09-09 15:08:12 +0000664
Jordan Roseeec15392012-07-02 19:27:43 +0000665 const RetainSummary *getSummary(const CallEvent &Call,
666 ProgramStateRef State = 0);
Mike Stump11289f42009-09-09 15:08:12 +0000667
Jordan Roseeec15392012-07-02 19:27:43 +0000668 const RetainSummary *getFunctionSummary(const FunctionDecl *FD);
669
670 const RetainSummary *getMethodSummary(Selector S, const ObjCInterfaceDecl *ID,
Jordy Rose35e71c72012-03-17 21:13:07 +0000671 const ObjCMethodDecl *MD,
672 QualType RetTy,
673 ObjCMethodSummariesTy &CachedSummaries);
674
Jordan Rose6bad4902012-07-02 19:27:56 +0000675 const RetainSummary *getInstanceMethodSummary(const ObjCMethodCall &M,
Jordan Roseeec15392012-07-02 19:27:43 +0000676 ProgramStateRef State);
Ted Kremenekbd862712010-07-01 20:16:50 +0000677
Jordan Rose6bad4902012-07-02 19:27:56 +0000678 const RetainSummary *getClassMethodSummary(const ObjCMethodCall &M) {
Jordan Roseeec15392012-07-02 19:27:43 +0000679 assert(!M.isInstanceMessage());
680 const ObjCInterfaceDecl *Class = M.getReceiverInterface();
Mike Stump11289f42009-09-09 15:08:12 +0000681
Jordan Roseeec15392012-07-02 19:27:43 +0000682 return getMethodSummary(M.getSelector(), Class, M.getDecl(),
683 M.getResultType(), ObjCClassMethodSummaries);
Ted Kremenek7686ffa2009-04-29 00:42:39 +0000684 }
Ted Kremenek99fe1692009-04-29 17:17:48 +0000685
686 /// getMethodSummary - This version of getMethodSummary is used to query
687 /// the summary for the current method being analyzed.
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000688 const RetainSummary *getMethodSummary(const ObjCMethodDecl *MD) {
Ted Kremenek223a7d52009-04-29 23:03:22 +0000689 const ObjCInterfaceDecl *ID = MD->getClassInterface();
Ted Kremenekb2a143f2009-04-30 05:41:14 +0000690 Selector S = MD->getSelector();
Ted Kremenek99fe1692009-04-29 17:17:48 +0000691 QualType ResultTy = MD->getResultType();
Mike Stump11289f42009-09-09 15:08:12 +0000692
Jordy Rose35e71c72012-03-17 21:13:07 +0000693 ObjCMethodSummariesTy *CachedSummaries;
Ted Kremenek99fe1692009-04-29 17:17:48 +0000694 if (MD->isInstanceMethod())
Jordy Rose35e71c72012-03-17 21:13:07 +0000695 CachedSummaries = &ObjCMethodSummaries;
Ted Kremenek99fe1692009-04-29 17:17:48 +0000696 else
Jordy Rose35e71c72012-03-17 21:13:07 +0000697 CachedSummaries = &ObjCClassMethodSummaries;
698
Jordan Roseeec15392012-07-02 19:27:43 +0000699 return getMethodSummary(S, ID, MD, ResultTy, *CachedSummaries);
Ted Kremenek99fe1692009-04-29 17:17:48 +0000700 }
Mike Stump11289f42009-09-09 15:08:12 +0000701
Jordy Rose35e71c72012-03-17 21:13:07 +0000702 const RetainSummary *getStandardMethodSummary(const ObjCMethodDecl *MD,
Jordan Roseeec15392012-07-02 19:27:43 +0000703 Selector S, QualType RetTy);
Ted Kremenek223a7d52009-04-29 23:03:22 +0000704
Jordan Rose39032472013-04-04 22:31:48 +0000705 /// Determine if there is a special return effect for this function or method.
706 Optional<RetEffect> getRetEffectFromAnnotations(QualType RetTy,
707 const Decl *D);
708
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000709 void updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenekc2de7272009-05-09 02:58:13 +0000710 const ObjCMethodDecl *MD);
711
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000712 void updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenekc2de7272009-05-09 02:58:13 +0000713 const FunctionDecl *FD);
714
Jordan Roseeec15392012-07-02 19:27:43 +0000715 void updateSummaryForCall(const RetainSummary *&Summ,
716 const CallEvent &Call);
717
Ted Kremenek00daccd2008-05-05 22:11:16 +0000718 bool isGCEnabled() const { return GCEnabled; }
Mike Stump11289f42009-09-09 15:08:12 +0000719
John McCall31168b02011-06-15 23:02:42 +0000720 bool isARCEnabled() const { return ARCEnabled; }
721
722 bool isARCorGCEnabled() const { return GCEnabled || ARCEnabled; }
Jordan Roseeec15392012-07-02 19:27:43 +0000723
724 RetEffect getObjAllocRetEffect() const { return ObjCAllocRetE; }
725
726 friend class RetainSummaryTemplate;
Ted Kremenek819e9b62008-03-11 06:39:11 +0000727};
Mike Stump11289f42009-09-09 15:08:12 +0000728
Jordy Rose14de7c52011-08-24 09:02:37 +0000729// Used to avoid allocating long-term (BPAlloc'd) memory for default retain
730// summaries. If a function or method looks like it has a default summary, but
731// it has annotations, the annotations are added to the stack-based template
732// and then copied into managed memory.
733class RetainSummaryTemplate {
734 RetainSummaryManager &Manager;
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000735 const RetainSummary *&RealSummary;
Jordy Rose14de7c52011-08-24 09:02:37 +0000736 RetainSummary ScratchSummary;
737 bool Accessed;
738public:
Jordan Roseeec15392012-07-02 19:27:43 +0000739 RetainSummaryTemplate(const RetainSummary *&real, RetainSummaryManager &mgr)
740 : Manager(mgr), RealSummary(real), ScratchSummary(*real), Accessed(false) {}
Jordy Rose14de7c52011-08-24 09:02:37 +0000741
742 ~RetainSummaryTemplate() {
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000743 if (Accessed)
Jordy Rose61c974b2012-03-18 01:26:10 +0000744 RealSummary = Manager.getPersistentSummary(ScratchSummary);
Jordy Rose14de7c52011-08-24 09:02:37 +0000745 }
746
747 RetainSummary &operator*() {
748 Accessed = true;
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000749 return ScratchSummary;
Jordy Rose14de7c52011-08-24 09:02:37 +0000750 }
751
752 RetainSummary *operator->() {
753 Accessed = true;
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000754 return &ScratchSummary;
Jordy Rose14de7c52011-08-24 09:02:37 +0000755 }
756};
757
Ted Kremenek819e9b62008-03-11 06:39:11 +0000758} // end anonymous namespace
759
760//===----------------------------------------------------------------------===//
761// Implementation of checker data structures.
762//===----------------------------------------------------------------------===//
763
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000764ArgEffects RetainSummaryManager::getArgEffects() {
765 ArgEffects AE = ScratchArgs;
Ted Kremenekb3b56c62010-11-24 00:54:37 +0000766 ScratchArgs = AF.getEmptyMap();
Ted Kremenek7d79a5f2009-05-03 05:20:50 +0000767 return AE;
Ted Kremenek68d73d12008-03-12 01:21:45 +0000768}
769
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000770const RetainSummary *
Jordy Rose61c974b2012-03-18 01:26:10 +0000771RetainSummaryManager::getPersistentSummary(const RetainSummary &OldSumm) {
772 // Unique "simple" summaries -- those without ArgEffects.
773 if (OldSumm.isSimple()) {
774 llvm::FoldingSetNodeID ID;
775 OldSumm.Profile(ID);
776
777 void *Pos;
778 CachedSummaryNode *N = SimpleSummaries.FindNodeOrInsertPos(ID, Pos);
779
780 if (!N) {
781 N = (CachedSummaryNode *) BPAlloc.Allocate<CachedSummaryNode>();
782 new (N) CachedSummaryNode(OldSumm);
783 SimpleSummaries.InsertNode(N, Pos);
784 }
785
786 return &N->getValue();
787 }
788
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000789 RetainSummary *Summ = (RetainSummary *) BPAlloc.Allocate<RetainSummary>();
Jordy Rose61c974b2012-03-18 01:26:10 +0000790 new (Summ) RetainSummary(OldSumm);
Ted Kremenek68d73d12008-03-12 01:21:45 +0000791 return Summ;
792}
793
Ted Kremenek00daccd2008-05-05 22:11:16 +0000794//===----------------------------------------------------------------------===//
795// Summary creation for functions (largely uses of Core Foundation).
796//===----------------------------------------------------------------------===//
Ted Kremenek68d73d12008-03-12 01:21:45 +0000797
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000798static bool isRetain(const FunctionDecl *FD, StringRef FName) {
Benjamin Kramereaabbd82010-02-08 18:38:55 +0000799 return FName.endswith("Retain");
Ted Kremenek7e904222009-01-12 21:45:02 +0000800}
801
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000802static bool isRelease(const FunctionDecl *FD, StringRef FName) {
Benjamin Kramereaabbd82010-02-08 18:38:55 +0000803 return FName.endswith("Release");
Ted Kremenek7e904222009-01-12 21:45:02 +0000804}
805
Jordan Rose77411322013-10-07 17:16:52 +0000806static bool isAutorelease(const FunctionDecl *FD, StringRef FName) {
807 return FName.endswith("Autorelease");
808}
809
Jordy Rose898a1482011-08-21 21:58:18 +0000810static bool isMakeCollectable(const FunctionDecl *FD, StringRef FName) {
811 // FIXME: Remove FunctionDecl parameter.
812 // FIXME: Is it really okay if MakeCollectable isn't a suffix?
813 return FName.find("MakeCollectable") != StringRef::npos;
814}
815
Anna Zaks25612732012-08-29 23:23:43 +0000816static ArgEffect getStopTrackingHardEquivalent(ArgEffect E) {
Jordan Roseeec15392012-07-02 19:27:43 +0000817 switch (E) {
818 case DoNothing:
819 case Autorelease:
Benjamin Kramer2501f142013-10-20 11:47:15 +0000820 case DecRefBridgedTransferred:
Jordan Roseeec15392012-07-02 19:27:43 +0000821 case IncRef:
822 case IncRefMsg:
823 case MakeCollectable:
824 case MayEscape:
Jordan Roseeec15392012-07-02 19:27:43 +0000825 case StopTracking:
Anna Zaks25612732012-08-29 23:23:43 +0000826 case StopTrackingHard:
827 return StopTrackingHard;
Jordan Roseeec15392012-07-02 19:27:43 +0000828 case DecRef:
Anna Zaks25612732012-08-29 23:23:43 +0000829 case DecRefAndStopTrackingHard:
830 return DecRefAndStopTrackingHard;
Jordan Roseeec15392012-07-02 19:27:43 +0000831 case DecRefMsg:
Anna Zaks25612732012-08-29 23:23:43 +0000832 case DecRefMsgAndStopTrackingHard:
833 return DecRefMsgAndStopTrackingHard;
Jordan Roseeec15392012-07-02 19:27:43 +0000834 case Dealloc:
835 return Dealloc;
836 }
837
838 llvm_unreachable("Unknown ArgEffect kind");
839}
840
841void RetainSummaryManager::updateSummaryForCall(const RetainSummary *&S,
842 const CallEvent &Call) {
843 if (Call.hasNonZeroCallbackArg()) {
Anna Zaks25612732012-08-29 23:23:43 +0000844 ArgEffect RecEffect =
845 getStopTrackingHardEquivalent(S->getReceiverEffect());
846 ArgEffect DefEffect =
847 getStopTrackingHardEquivalent(S->getDefaultArgEffect());
Jordan Roseeec15392012-07-02 19:27:43 +0000848
849 ArgEffects CustomArgEffects = S->getArgEffects();
850 for (ArgEffects::iterator I = CustomArgEffects.begin(),
851 E = CustomArgEffects.end();
852 I != E; ++I) {
Anna Zaks25612732012-08-29 23:23:43 +0000853 ArgEffect Translated = getStopTrackingHardEquivalent(I->second);
Jordan Roseeec15392012-07-02 19:27:43 +0000854 if (Translated != DefEffect)
855 ScratchArgs = AF.add(ScratchArgs, I->first, Translated);
856 }
857
Anna Zaks25612732012-08-29 23:23:43 +0000858 RetEffect RE = RetEffect::MakeNoRetHard();
Jordan Roseeec15392012-07-02 19:27:43 +0000859
860 // Special cases where the callback argument CANNOT free the return value.
861 // This can generally only happen if we know that the callback will only be
862 // called when the return value is already being deallocated.
863 if (const FunctionCall *FC = dyn_cast<FunctionCall>(&Call)) {
Jordan Roseccf192e2012-09-01 17:39:13 +0000864 if (IdentifierInfo *Name = FC->getDecl()->getIdentifier()) {
865 // When the CGBitmapContext is deallocated, the callback here will free
866 // the associated data buffer.
Jordan Rosed65f1c82012-08-31 18:19:18 +0000867 if (Name->isStr("CGBitmapContextCreateWithData"))
868 RE = S->getRetEffect();
Jordan Roseccf192e2012-09-01 17:39:13 +0000869 }
Jordan Roseeec15392012-07-02 19:27:43 +0000870 }
871
872 S = getPersistentSummary(RE, RecEffect, DefEffect);
873 }
Anna Zaks3d5d3d32012-08-24 00:06:12 +0000874
875 // Special case '[super init];' and '[self init];'
876 //
877 // Even though calling '[super init]' without assigning the result to self
878 // and checking if the parent returns 'nil' is a bad pattern, it is common.
879 // Additionally, our Self Init checker already warns about it. To avoid
880 // overwhelming the user with messages from both checkers, we model the case
881 // of '[super init]' in cases when it is not consumed by another expression
882 // as if the call preserves the value of 'self'; essentially, assuming it can
883 // never fail and return 'nil'.
884 // Note, we don't want to just stop tracking the value since we want the
885 // RetainCount checker to report leaks and use-after-free if SelfInit checker
886 // is turned off.
887 if (const ObjCMethodCall *MC = dyn_cast<ObjCMethodCall>(&Call)) {
888 if (MC->getMethodFamily() == OMF_init && MC->isReceiverSelfOrSuper()) {
889
890 // Check if the message is not consumed, we know it will not be used in
891 // an assignment, ex: "self = [super init]".
892 const Expr *ME = MC->getOriginExpr();
893 const LocationContext *LCtx = MC->getLocationContext();
894 ParentMap &PM = LCtx->getAnalysisDeclContext()->getParentMap();
895 if (!PM.isConsumedExpr(ME)) {
896 RetainSummaryTemplate ModifiableSummaryTemplate(S, *this);
897 ModifiableSummaryTemplate->setReceiverEffect(DoNothing);
898 ModifiableSummaryTemplate->setRetEffect(RetEffect::MakeNoRet());
899 }
900 }
901
902 }
Jordan Roseeec15392012-07-02 19:27:43 +0000903}
904
Anna Zaksf4c5ea52012-05-04 22:18:39 +0000905const RetainSummary *
Jordan Roseeec15392012-07-02 19:27:43 +0000906RetainSummaryManager::getSummary(const CallEvent &Call,
907 ProgramStateRef State) {
908 const RetainSummary *Summ;
909 switch (Call.getKind()) {
910 case CE_Function:
911 Summ = getFunctionSummary(cast<FunctionCall>(Call).getDecl());
912 break;
913 case CE_CXXMember:
Jordan Rose017591a2012-07-03 22:55:57 +0000914 case CE_CXXMemberOperator:
Jordan Roseeec15392012-07-02 19:27:43 +0000915 case CE_Block:
916 case CE_CXXConstructor:
Jordan Rose4ee71b82012-07-10 22:07:47 +0000917 case CE_CXXDestructor:
Jordan Rosea4ee0642012-07-02 22:21:47 +0000918 case CE_CXXAllocator:
Jordan Roseeec15392012-07-02 19:27:43 +0000919 // FIXME: These calls are currently unsupported.
920 return getPersistentStopSummary();
Jordan Rose627b0462012-07-18 21:59:51 +0000921 case CE_ObjCMessage: {
Jordan Rose6bad4902012-07-02 19:27:56 +0000922 const ObjCMethodCall &Msg = cast<ObjCMethodCall>(Call);
Jordan Roseeec15392012-07-02 19:27:43 +0000923 if (Msg.isInstanceMessage())
924 Summ = getInstanceMethodSummary(Msg, State);
925 else
926 Summ = getClassMethodSummary(Msg);
927 break;
928 }
929 }
930
931 updateSummaryForCall(Summ, Call);
932
933 assert(Summ && "Unknown call type?");
934 return Summ;
935}
936
937const RetainSummary *
938RetainSummaryManager::getFunctionSummary(const FunctionDecl *FD) {
939 // If we don't know what function we're calling, use our default summary.
940 if (!FD)
941 return getDefaultSummary();
942
Ted Kremenekf7141592008-04-24 17:22:33 +0000943 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremenek00daccd2008-05-05 22:11:16 +0000944 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremenek00daccd2008-05-05 22:11:16 +0000945 if (I != FuncSummaries.end())
Ted Kremenekf7141592008-04-24 17:22:33 +0000946 return I->second;
947
Ted Kremenekdf76e6d2009-05-04 15:34:07 +0000948 // No summary? Generate one.
Ted Kremenekf3e3f662011-10-05 23:54:29 +0000949 const RetainSummary *S = 0;
Jordan Rose1c715602012-08-06 21:28:02 +0000950 bool AllowAnnotations = true;
Mike Stump11289f42009-09-09 15:08:12 +0000951
Ted Kremenekfa89e2f2008-07-15 16:50:12 +0000952 do {
Ted Kremenek7e904222009-01-12 21:45:02 +0000953 // We generate "stop" summaries for implicitly defined functions.
954 if (FD->isImplicit()) {
955 S = getPersistentStopSummary();
956 break;
Ted Kremenekfa89e2f2008-07-15 16:50:12 +0000957 }
Mike Stump11289f42009-09-09 15:08:12 +0000958
John McCall9dd450b2009-09-21 23:43:11 +0000959 // [PR 3337] Use 'getAs<FunctionType>' to strip away any typedefs on the
Ted Kremenek86afde32009-01-16 18:40:33 +0000960 // function's type.
John McCall9dd450b2009-09-21 23:43:11 +0000961 const FunctionType* FT = FD->getType()->getAs<FunctionType>();
Ted Kremenek9bcc2642009-12-16 06:06:43 +0000962 const IdentifierInfo *II = FD->getIdentifier();
963 if (!II)
964 break;
Benjamin Kramereaabbd82010-02-08 18:38:55 +0000965
966 StringRef FName = II->getName();
Mike Stump11289f42009-09-09 15:08:12 +0000967
Ted Kremenek5f968932009-03-05 22:11:14 +0000968 // Strip away preceding '_'. Doing this here will effect all the checks
969 // down below.
Benjamin Kramereaabbd82010-02-08 18:38:55 +0000970 FName = FName.substr(FName.find_first_not_of('_'));
Mike Stump11289f42009-09-09 15:08:12 +0000971
Ted Kremenek7e904222009-01-12 21:45:02 +0000972 // Inspect the result type.
973 QualType RetTy = FT->getResultType();
Mike Stump11289f42009-09-09 15:08:12 +0000974
Ted Kremenek7e904222009-01-12 21:45:02 +0000975 // FIXME: This should all be refactored into a chain of "summary lookup"
976 // filters.
Ted Kremenekb4ec3fc2009-10-14 00:27:24 +0000977 assert(ScratchArgs.isEmpty());
Ted Kremenek3092e9c2009-06-15 20:36:07 +0000978
Ted Kremenek01d152f2012-04-26 04:32:23 +0000979 if (FName == "pthread_create" || FName == "pthread_setspecific") {
980 // Part of: <rdar://problem/7299394> and <rdar://problem/11282706>.
981 // This will be addressed better with IPA.
Benjamin Kramereaabbd82010-02-08 18:38:55 +0000982 S = getPersistentStopSummary();
983 } else if (FName == "NSMakeCollectable") {
984 // Handle: id NSMakeCollectable(CFTypeRef)
985 S = (RetTy->isObjCIdType())
986 ? getUnarySummary(FT, cfmakecollectable)
987 : getPersistentStopSummary();
Jordan Rose1c715602012-08-06 21:28:02 +0000988 // The headers on OS X 10.8 use cf_consumed/ns_returns_retained,
989 // but we can fully model NSMakeCollectable ourselves.
990 AllowAnnotations = false;
Ted Kremenekc008db92012-09-06 23:47:02 +0000991 } else if (FName == "CFPlugInInstanceCreate") {
992 S = getPersistentSummary(RetEffect::MakeNoRet());
Benjamin Kramereaabbd82010-02-08 18:38:55 +0000993 } else if (FName == "IOBSDNameMatching" ||
994 FName == "IOServiceMatching" ||
995 FName == "IOServiceNameMatching" ||
Ted Kremenek555560c2012-05-01 05:28:27 +0000996 FName == "IORegistryEntrySearchCFProperty" ||
Benjamin Kramereaabbd82010-02-08 18:38:55 +0000997 FName == "IORegistryEntryIDMatching" ||
998 FName == "IOOpenFirmwarePathMatching") {
999 // Part of <rdar://problem/6961230>. (IOKit)
1000 // This should be addressed using a API table.
1001 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1002 DoNothing, DoNothing);
1003 } else if (FName == "IOServiceGetMatchingService" ||
1004 FName == "IOServiceGetMatchingServices") {
1005 // FIXES: <rdar://problem/6326900>
1006 // This should be addressed using a API table. This strcmp is also
1007 // a little gross, but there is no need to super optimize here.
Ted Kremenekb3b56c62010-11-24 00:54:37 +00001008 ScratchArgs = AF.add(ScratchArgs, 1, DecRef);
Benjamin Kramereaabbd82010-02-08 18:38:55 +00001009 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1010 } else if (FName == "IOServiceAddNotification" ||
1011 FName == "IOServiceAddMatchingNotification") {
1012 // Part of <rdar://problem/6961230>. (IOKit)
1013 // This should be addressed using a API table.
Ted Kremenekb3b56c62010-11-24 00:54:37 +00001014 ScratchArgs = AF.add(ScratchArgs, 2, DecRef);
Benjamin Kramereaabbd82010-02-08 18:38:55 +00001015 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1016 } else if (FName == "CVPixelBufferCreateWithBytes") {
1017 // FIXES: <rdar://problem/7283567>
1018 // Eventually this can be improved by recognizing that the pixel
1019 // buffer passed to CVPixelBufferCreateWithBytes is released via
1020 // a callback and doing full IPA to make sure this is done correctly.
1021 // FIXME: This function has an out parameter that returns an
1022 // allocated object.
Ted Kremenekb3b56c62010-11-24 00:54:37 +00001023 ScratchArgs = AF.add(ScratchArgs, 7, StopTracking);
Benjamin Kramereaabbd82010-02-08 18:38:55 +00001024 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1025 } else if (FName == "CGBitmapContextCreateWithData") {
1026 // FIXES: <rdar://problem/7358899>
1027 // Eventually this can be improved by recognizing that 'releaseInfo'
1028 // passed to CGBitmapContextCreateWithData is released via
1029 // a callback and doing full IPA to make sure this is done correctly.
Ted Kremenekb3b56c62010-11-24 00:54:37 +00001030 ScratchArgs = AF.add(ScratchArgs, 8, StopTracking);
Benjamin Kramereaabbd82010-02-08 18:38:55 +00001031 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1032 DoNothing, DoNothing);
1033 } else if (FName == "CVPixelBufferCreateWithPlanarBytes") {
1034 // FIXES: <rdar://problem/7283567>
1035 // Eventually this can be improved by recognizing that the pixel
1036 // buffer passed to CVPixelBufferCreateWithPlanarBytes is released
1037 // via a callback and doing full IPA to make sure this is done
1038 // correctly.
Ted Kremenekb3b56c62010-11-24 00:54:37 +00001039 ScratchArgs = AF.add(ScratchArgs, 12, StopTracking);
Benjamin Kramereaabbd82010-02-08 18:38:55 +00001040 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Jordan Roseb1479182013-05-02 01:51:40 +00001041 } else if (FName == "dispatch_set_context" ||
1042 FName == "xpc_connection_set_context") {
Ted Kremenek40c13432012-03-22 06:29:41 +00001043 // <rdar://problem/11059275> - The analyzer currently doesn't have
1044 // a good way to reason about the finalizer function for libdispatch.
1045 // If we pass a context object that is memory managed, stop tracking it.
Jordan Roseb1479182013-05-02 01:51:40 +00001046 // <rdar://problem/13783514> - Same problem, but for XPC.
Ted Kremenek40c13432012-03-22 06:29:41 +00001047 // FIXME: this hack should possibly go away once we can handle
Jordan Roseb1479182013-05-02 01:51:40 +00001048 // libdispatch and XPC finalizers.
Ted Kremenek40c13432012-03-22 06:29:41 +00001049 ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
1050 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenekececf9f2012-05-08 00:12:09 +00001051 } else if (FName.startswith("NSLog")) {
1052 S = getDoNothingSummary();
Anna Zaks90ab9bf2012-03-30 05:48:16 +00001053 } else if (FName.startswith("NS") &&
1054 (FName.find("Insert") != StringRef::npos)) {
1055 // Whitelist NSXXInsertXX, for example NSMapInsertIfAbsent, since they can
1056 // be deallocated by NSMapRemove. (radar://11152419)
1057 ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
1058 ScratchArgs = AF.add(ScratchArgs, 2, StopTracking);
1059 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenekea675cf2009-06-11 18:17:24 +00001060 }
Mike Stump11289f42009-09-09 15:08:12 +00001061
Ted Kremenekea675cf2009-06-11 18:17:24 +00001062 // Did we get a summary?
1063 if (S)
1064 break;
Ted Kremenek211094d2009-03-17 22:43:44 +00001065
Jordan Rose85707b22013-03-04 23:21:32 +00001066 if (RetTy->isPointerType()) {
Ted Kremenek7e904222009-01-12 21:45:02 +00001067 // For CoreFoundation ('CF') types.
Ted Kremeneke9918352010-01-27 18:00:17 +00001068 if (cocoa::isRefType(RetTy, "CF", FName)) {
Jordan Rose77411322013-10-07 17:16:52 +00001069 if (isRetain(FD, FName)) {
Ted Kremenek7e904222009-01-12 21:45:02 +00001070 S = getUnarySummary(FT, cfretain);
Jordan Rose77411322013-10-07 17:16:52 +00001071 } else if (isAutorelease(FD, FName)) {
1072 S = getUnarySummary(FT, cfautorelease);
1073 // The headers use cf_consumed, but we can fully model CFAutorelease
1074 // ourselves.
1075 AllowAnnotations = false;
1076 } else if (isMakeCollectable(FD, FName)) {
Ted Kremenek7e904222009-01-12 21:45:02 +00001077 S = getUnarySummary(FT, cfmakecollectable);
Jordan Rose77411322013-10-07 17:16:52 +00001078 AllowAnnotations = false;
1079 } else {
John McCall525f0552011-10-01 00:48:56 +00001080 S = getCFCreateGetRuleSummary(FD);
Jordan Rose77411322013-10-07 17:16:52 +00001081 }
Ted Kremenek7e904222009-01-12 21:45:02 +00001082
1083 break;
1084 }
1085
1086 // For CoreGraphics ('CG') types.
Ted Kremeneke9918352010-01-27 18:00:17 +00001087 if (cocoa::isRefType(RetTy, "CG", FName)) {
Ted Kremenek7e904222009-01-12 21:45:02 +00001088 if (isRetain(FD, FName))
1089 S = getUnarySummary(FT, cfretain);
1090 else
John McCall525f0552011-10-01 00:48:56 +00001091 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek7e904222009-01-12 21:45:02 +00001092
1093 break;
1094 }
1095
1096 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
Ted Kremeneke9918352010-01-27 18:00:17 +00001097 if (cocoa::isRefType(RetTy, "DADisk") ||
1098 cocoa::isRefType(RetTy, "DADissenter") ||
1099 cocoa::isRefType(RetTy, "DASessionRef")) {
John McCall525f0552011-10-01 00:48:56 +00001100 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek7e904222009-01-12 21:45:02 +00001101 break;
1102 }
Mike Stump11289f42009-09-09 15:08:12 +00001103
Aaron Ballman9ead1242013-12-19 02:39:40 +00001104 if (FD->hasAttr<CFAuditedTransferAttr>()) {
Jordan Rose85707b22013-03-04 23:21:32 +00001105 S = getCFCreateGetRuleSummary(FD);
1106 break;
1107 }
1108
Ted Kremenek7e904222009-01-12 21:45:02 +00001109 break;
1110 }
1111
1112 // Check for release functions, the only kind of functions that we care
1113 // about that don't return a pointer type.
1114 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
Ted Kremenekac5ab792010-02-08 16:45:01 +00001115 // Test for 'CGCF'.
Benjamin Kramereaabbd82010-02-08 18:38:55 +00001116 FName = FName.substr(FName.startswith("CGCF") ? 4 : 2);
Ted Kremenekac5ab792010-02-08 16:45:01 +00001117
Ted Kremenek5f968932009-03-05 22:11:14 +00001118 if (isRelease(FD, FName))
Ted Kremenek7e904222009-01-12 21:45:02 +00001119 S = getUnarySummary(FT, cfrelease);
1120 else {
Ted Kremenek7d79a5f2009-05-03 05:20:50 +00001121 assert (ScratchArgs.isEmpty());
Ted Kremeneked90de42009-01-29 22:45:13 +00001122 // Remaining CoreFoundation and CoreGraphics functions.
1123 // We use to assume that they all strictly followed the ownership idiom
1124 // and that ownership cannot be transferred. While this is technically
1125 // correct, many methods allow a tracked object to escape. For example:
1126 //
Mike Stump11289f42009-09-09 15:08:12 +00001127 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
Ted Kremeneked90de42009-01-29 22:45:13 +00001128 // CFDictionaryAddValue(y, key, x);
Mike Stump11289f42009-09-09 15:08:12 +00001129 // CFRelease(x);
Ted Kremeneked90de42009-01-29 22:45:13 +00001130 // ... it is okay to use 'x' since 'y' has a reference to it
1131 //
1132 // We handle this and similar cases with the follow heuristic. If the
Ted Kremenekd982f002009-08-20 00:57:22 +00001133 // function name contains "InsertValue", "SetValue", "AddValue",
1134 // "AppendValue", or "SetAttribute", then we assume that arguments may
1135 // "escape." This means that something else holds on to the object,
1136 // allowing it be used even after its local retain count drops to 0.
Benjamin Kramer0129bd72010-01-11 19:46:28 +00001137 ArgEffect E = (StrInStrNoCase(FName, "InsertValue") != StringRef::npos||
1138 StrInStrNoCase(FName, "AddValue") != StringRef::npos ||
1139 StrInStrNoCase(FName, "SetValue") != StringRef::npos ||
1140 StrInStrNoCase(FName, "AppendValue") != StringRef::npos||
Benjamin Kramer37808312010-01-11 20:15:06 +00001141 StrInStrNoCase(FName, "SetAttribute") != StringRef::npos)
Ted Kremeneked90de42009-01-29 22:45:13 +00001142 ? MayEscape : DoNothing;
Mike Stump11289f42009-09-09 15:08:12 +00001143
Ted Kremeneked90de42009-01-29 22:45:13 +00001144 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek7e904222009-01-12 21:45:02 +00001145 }
1146 }
Ted Kremenekfa89e2f2008-07-15 16:50:12 +00001147 }
1148 while (0);
Mike Stump11289f42009-09-09 15:08:12 +00001149
Jordan Roseeec15392012-07-02 19:27:43 +00001150 // If we got all the way here without any luck, use a default summary.
1151 if (!S)
1152 S = getDefaultSummary();
1153
Ted Kremenekc2de7272009-05-09 02:58:13 +00001154 // Annotations override defaults.
Jordan Rose1c715602012-08-06 21:28:02 +00001155 if (AllowAnnotations)
1156 updateSummaryFromAnnotations(S, FD);
Mike Stump11289f42009-09-09 15:08:12 +00001157
Ted Kremenek00daccd2008-05-05 22:11:16 +00001158 FuncSummaries[FD] = S;
Mike Stump11289f42009-09-09 15:08:12 +00001159 return S;
Ted Kremenekea6507f2008-03-06 00:08:09 +00001160}
1161
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001162const RetainSummary *
John McCall525f0552011-10-01 00:48:56 +00001163RetainSummaryManager::getCFCreateGetRuleSummary(const FunctionDecl *FD) {
1164 if (coreFoundation::followsCreateRule(FD))
Ted Kremenek875db812008-05-05 16:51:50 +00001165 return getCFSummaryCreateRule(FD);
Mike Stump11289f42009-09-09 15:08:12 +00001166
Ted Kremenek8e2c9b02011-05-25 06:19:45 +00001167 return getCFSummaryGetRule(FD);
Ted Kremenek875db812008-05-05 16:51:50 +00001168}
1169
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001170const RetainSummary *
Ted Kremenek82157a12009-02-23 16:51:39 +00001171RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1172 UnaryFuncKind func) {
1173
Ted Kremenek7e904222009-01-12 21:45:02 +00001174 // Sanity check that this is *really* a unary function. This can
1175 // happen if people do weird things.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001176 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
Ted Kremenek7e904222009-01-12 21:45:02 +00001177 if (!FTP || FTP->getNumArgs() != 1)
1178 return getPersistentStopSummary();
Mike Stump11289f42009-09-09 15:08:12 +00001179
Ted Kremenek7d79a5f2009-05-03 05:20:50 +00001180 assert (ScratchArgs.isEmpty());
Mike Stump11289f42009-09-09 15:08:12 +00001181
Jordy Rose898a1482011-08-21 21:58:18 +00001182 ArgEffect Effect;
Ted Kremenek4b7ca772008-04-29 05:33:51 +00001183 switch (func) {
Jordan Rose77411322013-10-07 17:16:52 +00001184 case cfretain: Effect = IncRef; break;
1185 case cfrelease: Effect = DecRef; break;
1186 case cfautorelease: Effect = Autorelease; break;
1187 case cfmakecollectable: Effect = MakeCollectable; break;
Ted Kremenek4b772092008-04-10 23:44:06 +00001188 }
Jordy Rose898a1482011-08-21 21:58:18 +00001189
1190 ScratchArgs = AF.add(ScratchArgs, 0, Effect);
1191 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenek68d73d12008-03-12 01:21:45 +00001192}
1193
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001194const RetainSummary *
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001195RetainSummaryManager::getCFSummaryCreateRule(const FunctionDecl *FD) {
Ted Kremenek7d79a5f2009-05-03 05:20:50 +00001196 assert (ScratchArgs.isEmpty());
Mike Stump11289f42009-09-09 15:08:12 +00001197
Ted Kremenekaeb115f2009-01-28 05:56:51 +00001198 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenek68d73d12008-03-12 01:21:45 +00001199}
1200
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001201const RetainSummary *
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001202RetainSummaryManager::getCFSummaryGetRule(const FunctionDecl *FD) {
Mike Stump11289f42009-09-09 15:08:12 +00001203 assert (ScratchArgs.isEmpty());
Ted Kremenekaeb115f2009-01-28 05:56:51 +00001204 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1205 DoNothing, DoNothing);
Ted Kremenek68d73d12008-03-12 01:21:45 +00001206}
1207
Ted Kremenek819e9b62008-03-11 06:39:11 +00001208//===----------------------------------------------------------------------===//
Ted Kremenek00daccd2008-05-05 22:11:16 +00001209// Summary creation for Selectors.
1210//===----------------------------------------------------------------------===//
1211
Jordan Rose39032472013-04-04 22:31:48 +00001212Optional<RetEffect>
1213RetainSummaryManager::getRetEffectFromAnnotations(QualType RetTy,
1214 const Decl *D) {
1215 if (cocoa::isCocoaObjectRef(RetTy)) {
Aaron Ballman9ead1242013-12-19 02:39:40 +00001216 if (D->hasAttr<NSReturnsRetainedAttr>())
Jordan Rose39032472013-04-04 22:31:48 +00001217 return ObjCAllocRetE;
1218
Aaron Ballman9ead1242013-12-19 02:39:40 +00001219 if (D->hasAttr<NSReturnsNotRetainedAttr>() ||
1220 D->hasAttr<NSReturnsAutoreleasedAttr>())
Jordan Rose39032472013-04-04 22:31:48 +00001221 return RetEffect::MakeNotOwned(RetEffect::ObjC);
1222
1223 } else if (!RetTy->isPointerType()) {
1224 return None;
1225 }
1226
Aaron Ballman9ead1242013-12-19 02:39:40 +00001227 if (D->hasAttr<CFReturnsRetainedAttr>())
Jordan Rose39032472013-04-04 22:31:48 +00001228 return RetEffect::MakeOwned(RetEffect::CF, true);
1229
Aaron Ballman9ead1242013-12-19 02:39:40 +00001230 if (D->hasAttr<CFReturnsNotRetainedAttr>())
Jordan Rose39032472013-04-04 22:31:48 +00001231 return RetEffect::MakeNotOwned(RetEffect::CF);
1232
1233 return None;
1234}
1235
Ted Kremenekc2de7272009-05-09 02:58:13 +00001236void
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001237RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenekc2de7272009-05-09 02:58:13 +00001238 const FunctionDecl *FD) {
1239 if (!FD)
1240 return;
1241
Jordan Roseeec15392012-07-02 19:27:43 +00001242 assert(Summ && "Must have a summary to add annotations to.");
1243 RetainSummaryTemplate Template(Summ, *this);
Jordy Rose212e4592011-08-23 04:27:15 +00001244
Ted Kremenekafe348e2011-01-27 18:43:03 +00001245 // Effects on the parameters.
1246 unsigned parm_idx = 0;
1247 for (FunctionDecl::param_const_iterator pi = FD->param_begin(),
John McCall3337ca52011-04-06 09:02:12 +00001248 pe = FD->param_end(); pi != pe; ++pi, ++parm_idx) {
Ted Kremenekafe348e2011-01-27 18:43:03 +00001249 const ParmVarDecl *pd = *pi;
Aaron Ballman9ead1242013-12-19 02:39:40 +00001250 if (pd->hasAttr<NSConsumedAttr>())
Jordan Rose39032472013-04-04 22:31:48 +00001251 Template->addArg(AF, parm_idx, DecRefMsg);
Aaron Ballman9ead1242013-12-19 02:39:40 +00001252 else if (pd->hasAttr<CFConsumedAttr>())
Jordy Rose14de7c52011-08-24 09:02:37 +00001253 Template->addArg(AF, parm_idx, DecRef);
Ted Kremenekafe348e2011-01-27 18:43:03 +00001254 }
1255
Ted Kremenekea675cf2009-06-11 18:17:24 +00001256 QualType RetTy = FD->getResultType();
Jordan Rose39032472013-04-04 22:31:48 +00001257 if (Optional<RetEffect> RetE = getRetEffectFromAnnotations(RetTy, FD))
1258 Template->setRetEffect(*RetE);
Ted Kremenekc2de7272009-05-09 02:58:13 +00001259}
1260
1261void
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001262RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
1263 const ObjCMethodDecl *MD) {
Ted Kremenekc2de7272009-05-09 02:58:13 +00001264 if (!MD)
1265 return;
1266
Jordan Roseeec15392012-07-02 19:27:43 +00001267 assert(Summ && "Must have a valid summary to add annotations to");
1268 RetainSummaryTemplate Template(Summ, *this);
Mike Stump11289f42009-09-09 15:08:12 +00001269
Ted Kremenek0e898382011-01-27 06:54:14 +00001270 // Effects on the receiver.
Aaron Ballman9ead1242013-12-19 02:39:40 +00001271 if (MD->hasAttr<NSConsumesSelfAttr>())
Jordan Rose39032472013-04-04 22:31:48 +00001272 Template->setReceiverEffect(DecRefMsg);
Ted Kremenekafe348e2011-01-27 18:43:03 +00001273
1274 // Effects on the parameters.
1275 unsigned parm_idx = 0;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00001276 for (ObjCMethodDecl::param_const_iterator
1277 pi=MD->param_begin(), pe=MD->param_end();
Ted Kremenekafe348e2011-01-27 18:43:03 +00001278 pi != pe; ++pi, ++parm_idx) {
1279 const ParmVarDecl *pd = *pi;
Aaron Ballman9ead1242013-12-19 02:39:40 +00001280 if (pd->hasAttr<NSConsumedAttr>())
Jordan Rose39032472013-04-04 22:31:48 +00001281 Template->addArg(AF, parm_idx, DecRefMsg);
Aaron Ballman9ead1242013-12-19 02:39:40 +00001282 else if (pd->hasAttr<CFConsumedAttr>()) {
Jordy Rose14de7c52011-08-24 09:02:37 +00001283 Template->addArg(AF, parm_idx, DecRef);
Ted Kremenekafe348e2011-01-27 18:43:03 +00001284 }
Ted Kremenek0e898382011-01-27 06:54:14 +00001285 }
1286
Jordan Rose39032472013-04-04 22:31:48 +00001287 QualType RetTy = MD->getResultType();
1288 if (Optional<RetEffect> RetE = getRetEffectFromAnnotations(RetTy, MD))
1289 Template->setRetEffect(*RetE);
Ted Kremenekc2de7272009-05-09 02:58:13 +00001290}
1291
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001292const RetainSummary *
Jordy Rose35e71c72012-03-17 21:13:07 +00001293RetainSummaryManager::getStandardMethodSummary(const ObjCMethodDecl *MD,
1294 Selector S, QualType RetTy) {
Jordy Rose70638832012-03-17 19:53:04 +00001295 // Any special effects?
Ted Kremenek6a966b22009-04-24 21:56:17 +00001296 ArgEffect ReceiverEff = DoNothing;
Jordy Rose70638832012-03-17 19:53:04 +00001297 RetEffect ResultEff = RetEffect::MakeNoRet();
1298
1299 // Check the method family, and apply any default annotations.
1300 switch (MD ? MD->getMethodFamily() : S.getMethodFamily()) {
1301 case OMF_None:
1302 case OMF_performSelector:
1303 // Assume all Objective-C methods follow Cocoa Memory Management rules.
1304 // FIXME: Does the non-threaded performSelector family really belong here?
1305 // The selector could be, say, @selector(copy).
1306 if (cocoa::isCocoaObjectRef(RetTy))
1307 ResultEff = RetEffect::MakeNotOwned(RetEffect::ObjC);
1308 else if (coreFoundation::isCFObjectRef(RetTy)) {
1309 // ObjCMethodDecl currently doesn't consider CF objects as valid return
1310 // values for alloc, new, copy, or mutableCopy, so we have to
1311 // double-check with the selector. This is ugly, but there aren't that
1312 // many Objective-C methods that return CF objects, right?
1313 if (MD) {
1314 switch (S.getMethodFamily()) {
1315 case OMF_alloc:
1316 case OMF_new:
1317 case OMF_copy:
1318 case OMF_mutableCopy:
1319 ResultEff = RetEffect::MakeOwned(RetEffect::CF, true);
1320 break;
1321 default:
1322 ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1323 break;
1324 }
1325 } else {
1326 ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1327 }
1328 }
1329 break;
1330 case OMF_init:
1331 ResultEff = ObjCInitRetE;
1332 ReceiverEff = DecRefMsg;
1333 break;
1334 case OMF_alloc:
1335 case OMF_new:
1336 case OMF_copy:
1337 case OMF_mutableCopy:
1338 if (cocoa::isCocoaObjectRef(RetTy))
1339 ResultEff = ObjCAllocRetE;
1340 else if (coreFoundation::isCFObjectRef(RetTy))
1341 ResultEff = RetEffect::MakeOwned(RetEffect::CF, true);
1342 break;
1343 case OMF_autorelease:
1344 ReceiverEff = Autorelease;
1345 break;
1346 case OMF_retain:
1347 ReceiverEff = IncRefMsg;
1348 break;
1349 case OMF_release:
1350 ReceiverEff = DecRefMsg;
1351 break;
1352 case OMF_dealloc:
1353 ReceiverEff = Dealloc;
1354 break;
1355 case OMF_self:
1356 // -self is handled specially by the ExprEngine to propagate the receiver.
1357 break;
1358 case OMF_retainCount:
1359 case OMF_finalize:
1360 // These methods don't return objects.
1361 break;
1362 }
Mike Stump11289f42009-09-09 15:08:12 +00001363
Ted Kremenek6a966b22009-04-24 21:56:17 +00001364 // If one of the arguments in the selector has the keyword 'delegate' we
1365 // should stop tracking the reference count for the receiver. This is
1366 // because the reference count is quite possibly handled by a delegate
1367 // method.
1368 if (S.isKeywordSelector()) {
Jordan Rose95dfae82012-06-15 18:19:52 +00001369 for (unsigned i = 0, e = S.getNumArgs(); i != e; ++i) {
1370 StringRef Slot = S.getNameForSlot(i);
1371 if (Slot.substr(Slot.size() - 8).equals_lower("delegate")) {
1372 if (ResultEff == ObjCInitRetE)
Anna Zaks25612732012-08-29 23:23:43 +00001373 ResultEff = RetEffect::MakeNoRetHard();
Jordan Rose95dfae82012-06-15 18:19:52 +00001374 else
Anna Zaks25612732012-08-29 23:23:43 +00001375 ReceiverEff = StopTrackingHard;
Jordan Rose95dfae82012-06-15 18:19:52 +00001376 }
1377 }
Ted Kremenek6a966b22009-04-24 21:56:17 +00001378 }
Mike Stump11289f42009-09-09 15:08:12 +00001379
Jordy Rose70638832012-03-17 19:53:04 +00001380 if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing &&
1381 ResultEff.getKind() == RetEffect::NoRet)
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001382 return getDefaultSummary();
Mike Stump11289f42009-09-09 15:08:12 +00001383
Jordy Rose70638832012-03-17 19:53:04 +00001384 return getPersistentSummary(ResultEff, ReceiverEff, MayEscape);
Ted Kremenek60746a02009-04-23 23:08:22 +00001385}
1386
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001387const RetainSummary *
Jordan Rose6bad4902012-07-02 19:27:56 +00001388RetainSummaryManager::getInstanceMethodSummary(const ObjCMethodCall &Msg,
Jordan Roseeec15392012-07-02 19:27:43 +00001389 ProgramStateRef State) {
1390 const ObjCInterfaceDecl *ReceiverClass = 0;
Ted Kremeneka2968e52009-11-13 01:54:21 +00001391
Jordan Roseeec15392012-07-02 19:27:43 +00001392 // We do better tracking of the type of the object than the core ExprEngine.
1393 // See if we have its type in our private state.
1394 // FIXME: Eventually replace the use of state->get<RefBindings> with
1395 // a generic API for reasoning about the Objective-C types of symbolic
1396 // objects.
1397 SVal ReceiverV = Msg.getReceiverSVal();
1398 if (SymbolRef Sym = ReceiverV.getAsLocSymbol())
Anna Zaksf5788c72012-08-14 00:36:15 +00001399 if (const RefVal *T = getRefBinding(State, Sym))
Douglas Gregor9a129192010-04-21 00:45:42 +00001400 if (const ObjCObjectPointerType *PT =
Jordan Roseeec15392012-07-02 19:27:43 +00001401 T->getType()->getAs<ObjCObjectPointerType>())
1402 ReceiverClass = PT->getInterfaceDecl();
1403
1404 // If we don't know what kind of object this is, fall back to its static type.
1405 if (!ReceiverClass)
1406 ReceiverClass = Msg.getReceiverInterface();
Douglas Gregor9a129192010-04-21 00:45:42 +00001407
Ted Kremeneka2968e52009-11-13 01:54:21 +00001408 // FIXME: The receiver could be a reference to a class, meaning that
1409 // we should use the class method.
Jordan Roseeec15392012-07-02 19:27:43 +00001410 // id x = [NSObject class];
1411 // [x performSelector:... withObject:... afterDelay:...];
1412 Selector S = Msg.getSelector();
1413 const ObjCMethodDecl *Method = Msg.getDecl();
1414 if (!Method && ReceiverClass)
1415 Method = ReceiverClass->getInstanceMethod(S);
1416
1417 return getMethodSummary(S, ReceiverClass, Method, Msg.getResultType(),
1418 ObjCMethodSummaries);
Ted Kremeneka2968e52009-11-13 01:54:21 +00001419}
1420
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001421const RetainSummary *
Jordan Roseeec15392012-07-02 19:27:43 +00001422RetainSummaryManager::getMethodSummary(Selector S, const ObjCInterfaceDecl *ID,
Jordy Rose35e71c72012-03-17 21:13:07 +00001423 const ObjCMethodDecl *MD, QualType RetTy,
1424 ObjCMethodSummariesTy &CachedSummaries) {
Ted Kremenekcb2e6362008-05-06 15:44:25 +00001425
Ted Kremenek0b50fb12009-04-29 05:04:30 +00001426 // Look up a summary in our summary cache.
Jordan Roseeec15392012-07-02 19:27:43 +00001427 const RetainSummary *Summ = CachedSummaries.find(ID, S);
Mike Stump11289f42009-09-09 15:08:12 +00001428
Ted Kremenek8be51382009-07-21 23:27:57 +00001429 if (!Summ) {
Jordy Rose35e71c72012-03-17 21:13:07 +00001430 Summ = getStandardMethodSummary(MD, S, RetTy);
Mike Stump11289f42009-09-09 15:08:12 +00001431
Ted Kremenek8be51382009-07-21 23:27:57 +00001432 // Annotations override defaults.
Jordy Rose212e4592011-08-23 04:27:15 +00001433 updateSummaryFromAnnotations(Summ, MD);
Mike Stump11289f42009-09-09 15:08:12 +00001434
Ted Kremenek8be51382009-07-21 23:27:57 +00001435 // Memoize the summary.
Jordan Roseeec15392012-07-02 19:27:43 +00001436 CachedSummaries[ObjCSummaryKey(ID, S)] = Summ;
Ted Kremenek8be51382009-07-21 23:27:57 +00001437 }
Mike Stump11289f42009-09-09 15:08:12 +00001438
Ted Kremenekf27110f2009-04-23 19:11:35 +00001439 return Summ;
Ted Kremenek767d0742008-05-06 21:26:51 +00001440}
1441
Mike Stump11289f42009-09-09 15:08:12 +00001442void RetainSummaryManager::InitializeClassMethodSummaries() {
Ted Kremenek9157fbb2009-05-07 23:40:42 +00001443 assert(ScratchArgs.isEmpty());
Mike Stump11289f42009-09-09 15:08:12 +00001444 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek55adb822009-10-15 22:25:12 +00001445 addClassMethSummary("NSAssertionHandler", "currentHandler",
Ted Kremenekaeb115f2009-01-28 05:56:51 +00001446 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Mike Stump11289f42009-09-09 15:08:12 +00001447
Ted Kremenek0747e7e2008-10-21 15:53:15 +00001448 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremenekb3b56c62010-11-24 00:54:37 +00001449 ScratchArgs = AF.add(ScratchArgs, 0, Autorelease);
Ted Kremenek55adb822009-10-15 22:25:12 +00001450 addClassMethSummary("NSAutoreleasePool", "addObject",
1451 getPersistentSummary(RetEffect::MakeNoRet(),
1452 DoNothing, Autorelease));
Ted Kremenek0806f912008-05-06 00:30:21 +00001453}
1454
Ted Kremenekea736c52008-06-23 22:21:20 +00001455void RetainSummaryManager::InitializeMethodSummaries() {
Mike Stump11289f42009-09-09 15:08:12 +00001456
1457 assert (ScratchArgs.isEmpty());
1458
Ted Kremenek767d0742008-05-06 21:26:51 +00001459 // Create the "init" selector. It just acts as a pass-through for the
1460 // receiver.
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001461 const RetainSummary *InitSumm = getPersistentSummary(ObjCInitRetE, DecRefMsg);
Ted Kremenek815fbb62009-08-20 05:13:36 +00001462 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
1463
1464 // awakeAfterUsingCoder: behaves basically like an 'init' method. It
1465 // claims the receiver and returns a retained object.
1466 addNSObjectMethSummary(GetUnarySelector("awakeAfterUsingCoder", Ctx),
1467 InitSumm);
Mike Stump11289f42009-09-09 15:08:12 +00001468
Ted Kremenek767d0742008-05-06 21:26:51 +00001469 // The next methods are allocators.
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001470 const RetainSummary *AllocSumm = getPersistentSummary(ObjCAllocRetE);
1471 const RetainSummary *CFAllocSumm =
Ted Kremenek52ac2b52009-08-28 19:52:12 +00001472 getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Mike Stump11289f42009-09-09 15:08:12 +00001473
Ted Kremenekb0862dc2008-05-06 02:26:56 +00001474 // Create the "retain" selector.
Jordy Rose3f7f75682011-08-21 19:41:36 +00001475 RetEffect NoRet = RetEffect::MakeNoRet();
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001476 const RetainSummary *Summ = getPersistentSummary(NoRet, IncRefMsg);
Ted Kremenek3185c9c2008-06-25 21:21:56 +00001477 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Mike Stump11289f42009-09-09 15:08:12 +00001478
Ted Kremenekb0862dc2008-05-06 02:26:56 +00001479 // Create the "release" selector.
Jordy Rose3f7f75682011-08-21 19:41:36 +00001480 Summ = getPersistentSummary(NoRet, DecRefMsg);
Ted Kremenek3185c9c2008-06-25 21:21:56 +00001481 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Mike Stump11289f42009-09-09 15:08:12 +00001482
Ted Kremenekea072e32009-03-17 19:42:23 +00001483 // Create the -dealloc summary.
Jordy Rose3f7f75682011-08-21 19:41:36 +00001484 Summ = getPersistentSummary(NoRet, Dealloc);
Ted Kremenekea072e32009-03-17 19:42:23 +00001485 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
Ted Kremenekb0862dc2008-05-06 02:26:56 +00001486
1487 // Create the "autorelease" selector.
Jordy Rose3f7f75682011-08-21 19:41:36 +00001488 Summ = getPersistentSummary(NoRet, Autorelease);
Ted Kremenek3185c9c2008-06-25 21:21:56 +00001489 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Mike Stump11289f42009-09-09 15:08:12 +00001490
Mike Stump11289f42009-09-09 15:08:12 +00001491 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremeneke73f2822009-02-23 02:51:29 +00001492 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1493 // self-own themselves. However, they only do this once they are displayed.
1494 // Thus, we need to track an NSWindow's display status.
1495 // This is tracked in <rdar://problem/6062711>.
Ted Kremenek00dfe302009-03-04 23:30:42 +00001496 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
Ted Kremenekf3e3f662011-10-05 23:54:29 +00001497 const RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenek1272f702009-05-12 20:06:54 +00001498 StopTracking,
1499 StopTracking);
Mike Stump11289f42009-09-09 15:08:12 +00001500
Ted Kremenek751e7e32009-04-03 19:02:51 +00001501 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1502
Ted Kremenek3f13f592008-08-12 18:48:50 +00001503 // For NSPanel (which subclasses NSWindow), allocated objects are not
1504 // self-owned.
Ted Kremenek751e7e32009-04-03 19:02:51 +00001505 // FIXME: For now we don't track NSPanels. object for the same reason
1506 // as for NSWindow objects.
1507 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
Mike Stump11289f42009-09-09 15:08:12 +00001508
Ted Kremenek9b12e722014-01-03 01:19:28 +00001509 // For NSNull, objects returned by +null are singletons that ignore
1510 // retain/release semantics. Just don't track them.
1511 // <rdar://problem/12858915>
1512 addClassMethSummary("NSNull", "null", NoTrackYet);
1513
Jordan Rose95bf3b02013-01-31 22:06:02 +00001514 // Don't track allocated autorelease pools, as it is okay to prematurely
Ted Kremenek501ba032009-05-18 23:14:34 +00001515 // exit a method.
1516 addClassMethSummary("NSAutoreleasePool", "alloc", NoTrackYet);
Ted Kremeneke8a5ba82012-02-18 21:37:48 +00001517 addClassMethSummary("NSAutoreleasePool", "allocWithZone", NoTrackYet, false);
Jordan Rose95bf3b02013-01-31 22:06:02 +00001518 addClassMethSummary("NSAutoreleasePool", "new", NoTrackYet);
Ted Kremenek3185c9c2008-06-25 21:21:56 +00001519
Ted Kremenek10369122009-05-20 22:39:57 +00001520 // Create summaries QCRenderer/QCView -createSnapShotImageOfType:
1521 addInstMethSummary("QCRenderer", AllocSumm,
1522 "createSnapshotImageOfType", NULL);
1523 addInstMethSummary("QCView", AllocSumm,
1524 "createSnapshotImageOfType", NULL);
1525
Ted Kremenek96aa1462009-06-15 20:58:58 +00001526 // Create summaries for CIContext, 'createCGImage' and
Ted Kremenek52ac2b52009-08-28 19:52:12 +00001527 // 'createCGLayerWithSize'. These objects are CF objects, and are not
1528 // automatically garbage collected.
1529 addInstMethSummary("CIContext", CFAllocSumm,
Ted Kremenek10369122009-05-20 22:39:57 +00001530 "createCGImage", "fromRect", NULL);
Ted Kremenek52ac2b52009-08-28 19:52:12 +00001531 addInstMethSummary("CIContext", CFAllocSumm,
Mike Stump11289f42009-09-09 15:08:12 +00001532 "createCGImage", "fromRect", "format", "colorSpace", NULL);
Ted Kremenek52ac2b52009-08-28 19:52:12 +00001533 addInstMethSummary("CIContext", CFAllocSumm, "createCGLayerWithSize",
Ted Kremenek96aa1462009-06-15 20:58:58 +00001534 "info", NULL);
Ted Kremenekbe7c56e2008-05-06 00:38:54 +00001535}
1536
Ted Kremenek00daccd2008-05-05 22:11:16 +00001537//===----------------------------------------------------------------------===//
Ted Kremenek6bd78702009-04-29 18:50:19 +00001538// Error reporting.
1539//===----------------------------------------------------------------------===//
Ted Kremenek6bd78702009-04-29 18:50:19 +00001540namespace {
Jordy Rose20d4e682011-08-23 20:55:48 +00001541 typedef llvm::DenseMap<const ExplodedNode *, const RetainSummary *>
1542 SummaryLogTy;
1543
Ted Kremenek6bd78702009-04-29 18:50:19 +00001544 //===-------------===//
1545 // Bug Descriptions. //
Mike Stump11289f42009-09-09 15:08:12 +00001546 //===-------------===//
1547
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00001548 class CFRefBug : public BugType {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001549 protected:
Jordy Rose7a534982011-08-24 05:47:39 +00001550 CFRefBug(StringRef name)
Ted Kremenekb45d1982012-04-05 20:43:28 +00001551 : BugType(name, categories::MemoryCoreFoundationObjectiveC) {}
Ted Kremenek6bd78702009-04-29 18:50:19 +00001552 public:
Mike Stump11289f42009-09-09 15:08:12 +00001553
Ted Kremenek6bd78702009-04-29 18:50:19 +00001554 // FIXME: Eventually remove.
Jordy Rose7a534982011-08-24 05:47:39 +00001555 virtual const char *getDescription() const = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001556
Ted Kremenek6bd78702009-04-29 18:50:19 +00001557 virtual bool isLeak() const { return false; }
1558 };
Mike Stump11289f42009-09-09 15:08:12 +00001559
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00001560 class UseAfterRelease : public CFRefBug {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001561 public:
Jordy Rose7a534982011-08-24 05:47:39 +00001562 UseAfterRelease() : CFRefBug("Use-after-release") {}
Mike Stump11289f42009-09-09 15:08:12 +00001563
Jordy Rose7a534982011-08-24 05:47:39 +00001564 const char *getDescription() const {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001565 return "Reference-counted object is used after it is released";
Mike Stump11289f42009-09-09 15:08:12 +00001566 }
Ted Kremenek6bd78702009-04-29 18:50:19 +00001567 };
Mike Stump11289f42009-09-09 15:08:12 +00001568
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00001569 class BadRelease : public CFRefBug {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001570 public:
Jordy Rose7a534982011-08-24 05:47:39 +00001571 BadRelease() : CFRefBug("Bad release") {}
Mike Stump11289f42009-09-09 15:08:12 +00001572
Jordy Rose7a534982011-08-24 05:47:39 +00001573 const char *getDescription() const {
Ted Kremenek5c22e112009-10-01 17:31:50 +00001574 return "Incorrect decrement of the reference count of an object that is "
1575 "not owned at this point by the caller";
Ted Kremenek6bd78702009-04-29 18:50:19 +00001576 }
1577 };
Mike Stump11289f42009-09-09 15:08:12 +00001578
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00001579 class DeallocGC : public CFRefBug {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001580 public:
Jordy Rose7a534982011-08-24 05:47:39 +00001581 DeallocGC()
1582 : CFRefBug("-dealloc called while using garbage collection") {}
Mike Stump11289f42009-09-09 15:08:12 +00001583
Ted Kremenek6bd78702009-04-29 18:50:19 +00001584 const char *getDescription() const {
Ted Kremenekd35272f2009-05-09 00:10:05 +00001585 return "-dealloc called while using garbage collection";
Ted Kremenek6bd78702009-04-29 18:50:19 +00001586 }
1587 };
Mike Stump11289f42009-09-09 15:08:12 +00001588
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00001589 class DeallocNotOwned : public CFRefBug {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001590 public:
Jordy Rose7a534982011-08-24 05:47:39 +00001591 DeallocNotOwned()
1592 : CFRefBug("-dealloc sent to non-exclusively owned object") {}
Mike Stump11289f42009-09-09 15:08:12 +00001593
Ted Kremenek6bd78702009-04-29 18:50:19 +00001594 const char *getDescription() const {
1595 return "-dealloc sent to object that may be referenced elsewhere";
1596 }
Mike Stump11289f42009-09-09 15:08:12 +00001597 };
1598
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00001599 class OverAutorelease : public CFRefBug {
Ted Kremenekd35272f2009-05-09 00:10:05 +00001600 public:
Jordy Rose7a534982011-08-24 05:47:39 +00001601 OverAutorelease()
Jordan Rose7467f062013-04-23 01:42:25 +00001602 : CFRefBug("Object autoreleased too many times") {}
Mike Stump11289f42009-09-09 15:08:12 +00001603
Ted Kremenekd35272f2009-05-09 00:10:05 +00001604 const char *getDescription() const {
Jordan Rose7467f062013-04-23 01:42:25 +00001605 return "Object autoreleased too many times";
Ted Kremenekd35272f2009-05-09 00:10:05 +00001606 }
1607 };
Mike Stump11289f42009-09-09 15:08:12 +00001608
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00001609 class ReturnedNotOwnedForOwned : public CFRefBug {
Ted Kremenekdee56e32009-05-10 06:25:57 +00001610 public:
Jordy Rose7a534982011-08-24 05:47:39 +00001611 ReturnedNotOwnedForOwned()
1612 : CFRefBug("Method should return an owned object") {}
Mike Stump11289f42009-09-09 15:08:12 +00001613
Ted Kremenekdee56e32009-05-10 06:25:57 +00001614 const char *getDescription() const {
Jordy Rose43426f82011-07-15 22:17:54 +00001615 return "Object with a +0 retain count returned to caller where a +1 "
Ted Kremenekdee56e32009-05-10 06:25:57 +00001616 "(owning) retain count is expected";
1617 }
1618 };
Mike Stump11289f42009-09-09 15:08:12 +00001619
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00001620 class Leak : public CFRefBug {
Benjamin Kramerd1d76b22012-06-06 17:32:50 +00001621 public:
1622 Leak(StringRef name)
1623 : CFRefBug(name) {
Jordy Rose15484da2011-08-25 01:14:38 +00001624 // Leaks should not be reported if they are post-dominated by a sink.
1625 setSuppressOnSink(true);
1626 }
Mike Stump11289f42009-09-09 15:08:12 +00001627
Jordy Rose7a534982011-08-24 05:47:39 +00001628 const char *getDescription() const { return ""; }
Mike Stump11289f42009-09-09 15:08:12 +00001629
Ted Kremenek6bd78702009-04-29 18:50:19 +00001630 bool isLeak() const { return true; }
1631 };
Mike Stump11289f42009-09-09 15:08:12 +00001632
Ted Kremenek6bd78702009-04-29 18:50:19 +00001633 //===---------===//
1634 // Bug Reports. //
1635 //===---------===//
Mike Stump11289f42009-09-09 15:08:12 +00001636
Jordy Rosef78877e2012-03-24 02:45:35 +00001637 class CFRefReportVisitor : public BugReporterVisitorImpl<CFRefReportVisitor> {
Anna Zaks88255cc2011-08-20 01:27:22 +00001638 protected:
Anna Zaks071a89c2011-08-19 23:21:56 +00001639 SymbolRef Sym;
Jordy Rose20d4e682011-08-23 20:55:48 +00001640 const SummaryLogTy &SummaryLog;
Jordy Rose7a534982011-08-24 05:47:39 +00001641 bool GCEnabled;
Anna Zaks88255cc2011-08-20 01:27:22 +00001642
Anna Zaks071a89c2011-08-19 23:21:56 +00001643 public:
Jordy Rose7a534982011-08-24 05:47:39 +00001644 CFRefReportVisitor(SymbolRef sym, bool gcEnabled, const SummaryLogTy &log)
1645 : Sym(sym), SummaryLog(log), GCEnabled(gcEnabled) {}
Anna Zaks071a89c2011-08-19 23:21:56 +00001646
Anna Zaks88255cc2011-08-20 01:27:22 +00001647 virtual void Profile(llvm::FoldingSetNodeID &ID) const {
Anna Zaks071a89c2011-08-19 23:21:56 +00001648 static int x = 0;
1649 ID.AddPointer(&x);
1650 ID.AddPointer(Sym);
1651 }
1652
Anna Zaks88255cc2011-08-20 01:27:22 +00001653 virtual PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
1654 const ExplodedNode *PrevN,
1655 BugReporterContext &BRC,
1656 BugReport &BR);
1657
1658 virtual PathDiagnosticPiece *getEndPath(BugReporterContext &BRC,
1659 const ExplodedNode *N,
1660 BugReport &BR);
1661 };
1662
1663 class CFRefLeakReportVisitor : public CFRefReportVisitor {
1664 public:
Jordy Rose7a534982011-08-24 05:47:39 +00001665 CFRefLeakReportVisitor(SymbolRef sym, bool GCEnabled,
Jordy Rose20d4e682011-08-23 20:55:48 +00001666 const SummaryLogTy &log)
Jordy Rose7a534982011-08-24 05:47:39 +00001667 : CFRefReportVisitor(sym, GCEnabled, log) {}
Anna Zaks88255cc2011-08-20 01:27:22 +00001668
1669 PathDiagnosticPiece *getEndPath(BugReporterContext &BRC,
1670 const ExplodedNode *N,
1671 BugReport &BR);
Jordy Rosef78877e2012-03-24 02:45:35 +00001672
1673 virtual BugReporterVisitor *clone() const {
1674 // The curiously-recurring template pattern only works for one level of
1675 // subclassing. Rather than make a new template base for
1676 // CFRefReportVisitor, we simply override clone() to do the right thing.
1677 // This could be trouble someday if BugReporterVisitorImpl is ever
1678 // used for something else besides a convenient implementation of clone().
1679 return new CFRefLeakReportVisitor(*this);
1680 }
Anna Zaks071a89c2011-08-19 23:21:56 +00001681 };
1682
Anna Zaks3a6bdf82011-08-17 23:00:25 +00001683 class CFRefReport : public BugReport {
Jordy Rose184bd142011-08-24 22:39:09 +00001684 void addGCModeDescription(const LangOptions &LOpts, bool GCEnabled);
Jordy Rose7a534982011-08-24 05:47:39 +00001685
Ted Kremenek6bd78702009-04-29 18:50:19 +00001686 public:
Jordy Rose184bd142011-08-24 22:39:09 +00001687 CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1688 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1689 bool registerVisitor = true)
Anna Zaks752de142011-08-22 18:54:07 +00001690 : BugReport(D, D.getDescription(), n) {
Anna Zaks88255cc2011-08-20 01:27:22 +00001691 if (registerVisitor)
Jordy Rose184bd142011-08-24 22:39:09 +00001692 addVisitor(new CFRefReportVisitor(sym, GCEnabled, Log));
1693 addGCModeDescription(LOpts, GCEnabled);
Anna Zaks071a89c2011-08-19 23:21:56 +00001694 }
Ted Kremenek3978f792009-05-10 05:11:21 +00001695
Jordy Rose184bd142011-08-24 22:39:09 +00001696 CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1697 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1698 StringRef endText)
Anna Zaks752de142011-08-22 18:54:07 +00001699 : BugReport(D, D.getDescription(), endText, n) {
Jordy Rose184bd142011-08-24 22:39:09 +00001700 addVisitor(new CFRefReportVisitor(sym, GCEnabled, Log));
1701 addGCModeDescription(LOpts, GCEnabled);
Anna Zaks071a89c2011-08-19 23:21:56 +00001702 }
Mike Stump11289f42009-09-09 15:08:12 +00001703
Anna Zaks3a6bdf82011-08-17 23:00:25 +00001704 virtual std::pair<ranges_iterator, ranges_iterator> getRanges() {
Anna Zaks752de142011-08-22 18:54:07 +00001705 const CFRefBug& BugTy = static_cast<CFRefBug&>(getBugType());
1706 if (!BugTy.isLeak())
Anna Zaks3a6bdf82011-08-17 23:00:25 +00001707 return BugReport::getRanges();
Ted Kremenek6bd78702009-04-29 18:50:19 +00001708 else
Argyrios Kyrtzidisd22d8ff2010-12-04 01:12:15 +00001709 return std::make_pair(ranges_iterator(), ranges_iterator());
Ted Kremenek6bd78702009-04-29 18:50:19 +00001710 }
Ted Kremenek6bd78702009-04-29 18:50:19 +00001711 };
Ted Kremenek3978f792009-05-10 05:11:21 +00001712
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00001713 class CFRefLeakReport : public CFRefReport {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001714 const MemRegion* AllocBinding;
1715 public:
Jordy Rose184bd142011-08-24 22:39:09 +00001716 CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1717 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
Ted Kremenek8671acb2013-04-16 21:44:22 +00001718 CheckerContext &Ctx,
1719 bool IncludeAllocationLine);
Mike Stump11289f42009-09-09 15:08:12 +00001720
Anna Zaksc29bed32011-09-20 21:38:35 +00001721 PathDiagnosticLocation getLocation(const SourceManager &SM) const {
1722 assert(Location.isValid());
1723 return Location;
1724 }
Mike Stump11289f42009-09-09 15:08:12 +00001725 };
Ted Kremenek6bd78702009-04-29 18:50:19 +00001726} // end anonymous namespace
1727
Jordy Rose184bd142011-08-24 22:39:09 +00001728void CFRefReport::addGCModeDescription(const LangOptions &LOpts,
1729 bool GCEnabled) {
Jordy Rose9ff02992011-08-24 20:38:42 +00001730 const char *GCModeDescription = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001731
Douglas Gregor79a91412011-09-13 17:21:33 +00001732 switch (LOpts.getGC()) {
Anna Zaks76c3fb62011-08-22 20:31:28 +00001733 case LangOptions::GCOnly:
Jordy Rose184bd142011-08-24 22:39:09 +00001734 assert(GCEnabled);
Jordy Rose7a534982011-08-24 05:47:39 +00001735 GCModeDescription = "Code is compiled to only use garbage collection";
1736 break;
Mike Stump11289f42009-09-09 15:08:12 +00001737
Anna Zaks76c3fb62011-08-22 20:31:28 +00001738 case LangOptions::NonGC:
Jordy Rose184bd142011-08-24 22:39:09 +00001739 assert(!GCEnabled);
Jordy Rose7a534982011-08-24 05:47:39 +00001740 GCModeDescription = "Code is compiled to use reference counts";
1741 break;
Mike Stump11289f42009-09-09 15:08:12 +00001742
Anna Zaks76c3fb62011-08-22 20:31:28 +00001743 case LangOptions::HybridGC:
Jordy Rose184bd142011-08-24 22:39:09 +00001744 if (GCEnabled) {
Jordy Rose7a534982011-08-24 05:47:39 +00001745 GCModeDescription = "Code is compiled to use either garbage collection "
1746 "(GC) or reference counts (non-GC). The bug occurs "
1747 "with GC enabled";
1748 break;
1749 } else {
1750 GCModeDescription = "Code is compiled to use either garbage collection "
1751 "(GC) or reference counts (non-GC). The bug occurs "
1752 "in non-GC mode";
1753 break;
Anna Zaks76c3fb62011-08-22 20:31:28 +00001754 }
Ted Kremenek6bd78702009-04-29 18:50:19 +00001755 }
Jordy Rose7a534982011-08-24 05:47:39 +00001756
Jordy Rose9ff02992011-08-24 20:38:42 +00001757 assert(GCModeDescription && "invalid/unknown GC mode");
Jordy Rose7a534982011-08-24 05:47:39 +00001758 addExtraText(GCModeDescription);
Ted Kremenek6bd78702009-04-29 18:50:19 +00001759}
1760
Jordy Rose6393f822012-05-12 05:10:43 +00001761static bool isNumericLiteralExpression(const Expr *E) {
1762 // FIXME: This set of cases was copied from SemaExprObjC.
1763 return isa<IntegerLiteral>(E) ||
1764 isa<CharacterLiteral>(E) ||
1765 isa<FloatingLiteral>(E) ||
1766 isa<ObjCBoolLiteralExpr>(E) ||
1767 isa<CXXBoolLiteralExpr>(E);
1768}
1769
Anna Zaks071a89c2011-08-19 23:21:56 +00001770PathDiagnosticPiece *CFRefReportVisitor::VisitNode(const ExplodedNode *N,
1771 const ExplodedNode *PrevN,
1772 BugReporterContext &BRC,
1773 BugReport &BR) {
Jordan Rose681cce92012-07-10 22:07:42 +00001774 // FIXME: We will eventually need to handle non-statement-based events
1775 // (__attribute__((cleanup))).
David Blaikie87396b92013-02-21 22:23:56 +00001776 if (!N->getLocation().getAs<StmtPoint>())
Ted Kremenek051a03d2009-05-13 07:12:33 +00001777 return NULL;
Mike Stump11289f42009-09-09 15:08:12 +00001778
Ted Kremenekbb8d5462009-05-06 21:39:49 +00001779 // Check if the type state has changed.
Ted Kremenek49b1e382012-01-26 21:29:00 +00001780 ProgramStateRef PrevSt = PrevN->getState();
1781 ProgramStateRef CurrSt = N->getState();
Ted Kremenek632e3b72012-01-06 22:09:28 +00001782 const LocationContext *LCtx = N->getLocationContext();
Mike Stump11289f42009-09-09 15:08:12 +00001783
Anna Zaksf5788c72012-08-14 00:36:15 +00001784 const RefVal* CurrT = getRefBinding(CurrSt, Sym);
Ted Kremenek6bd78702009-04-29 18:50:19 +00001785 if (!CurrT) return NULL;
Mike Stump11289f42009-09-09 15:08:12 +00001786
Ted Kremenekd93c6e32009-06-18 01:23:53 +00001787 const RefVal &CurrV = *CurrT;
Anna Zaksf5788c72012-08-14 00:36:15 +00001788 const RefVal *PrevT = getRefBinding(PrevSt, Sym);
Mike Stump11289f42009-09-09 15:08:12 +00001789
Ted Kremenek6bd78702009-04-29 18:50:19 +00001790 // Create a string buffer to constain all the useful things we want
1791 // to tell the user.
1792 std::string sbuf;
1793 llvm::raw_string_ostream os(sbuf);
Mike Stump11289f42009-09-09 15:08:12 +00001794
Ted Kremenek6bd78702009-04-29 18:50:19 +00001795 // This is the allocation site since the previous node had no bindings
1796 // for this symbol.
1797 if (!PrevT) {
David Blaikie87396b92013-02-21 22:23:56 +00001798 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
Mike Stump11289f42009-09-09 15:08:12 +00001799
Ted Kremenek415287d2012-03-06 20:06:12 +00001800 if (isa<ObjCArrayLiteral>(S)) {
1801 os << "NSArray literal is an object with a +0 retain count";
Mike Stump11289f42009-09-09 15:08:12 +00001802 }
Ted Kremenek415287d2012-03-06 20:06:12 +00001803 else if (isa<ObjCDictionaryLiteral>(S)) {
1804 os << "NSDictionary literal is an object with a +0 retain count";
Ted Kremenek6bd78702009-04-29 18:50:19 +00001805 }
Jordy Rose6393f822012-05-12 05:10:43 +00001806 else if (const ObjCBoxedExpr *BL = dyn_cast<ObjCBoxedExpr>(S)) {
1807 if (isNumericLiteralExpression(BL->getSubExpr()))
1808 os << "NSNumber literal is an object with a +0 retain count";
1809 else {
1810 const ObjCInterfaceDecl *BoxClass = 0;
1811 if (const ObjCMethodDecl *Method = BL->getBoxingMethod())
1812 BoxClass = Method->getClassInterface();
1813
1814 // We should always be able to find the boxing class interface,
1815 // but consider this future-proofing.
1816 if (BoxClass)
1817 os << *BoxClass << " b";
1818 else
1819 os << "B";
1820
1821 os << "oxed expression produces an object with a +0 retain count";
1822 }
1823 }
Ted Kremenek415287d2012-03-06 20:06:12 +00001824 else {
1825 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
1826 // Get the name of the callee (if it is available).
1827 SVal X = CurrSt->getSValAsScalarOrLoc(CE->getCallee(), LCtx);
1828 if (const FunctionDecl *FD = X.getAsFunctionDecl())
1829 os << "Call to function '" << *FD << '\'';
1830 else
1831 os << "function call";
Ted Kremenek6bd78702009-04-29 18:50:19 +00001832 }
Ted Kremenek415287d2012-03-06 20:06:12 +00001833 else {
Jordan Rose627b0462012-07-18 21:59:51 +00001834 assert(isa<ObjCMessageExpr>(S));
Jordan Rosefcd016e2012-07-30 20:22:09 +00001835 CallEventManager &Mgr = CurrSt->getStateManager().getCallEventManager();
1836 CallEventRef<ObjCMethodCall> Call
1837 = Mgr.getObjCMethodCall(cast<ObjCMessageExpr>(S), CurrSt, LCtx);
1838
1839 switch (Call->getMessageKind()) {
Jordan Rose627b0462012-07-18 21:59:51 +00001840 case OCM_Message:
1841 os << "Method";
1842 break;
1843 case OCM_PropertyAccess:
1844 os << "Property";
1845 break;
1846 case OCM_Subscript:
1847 os << "Subscript";
1848 break;
1849 }
Ted Kremenek415287d2012-03-06 20:06:12 +00001850 }
1851
1852 if (CurrV.getObjKind() == RetEffect::CF) {
1853 os << " returns a Core Foundation object with a ";
1854 }
1855 else {
1856 assert (CurrV.getObjKind() == RetEffect::ObjC);
1857 os << " returns an Objective-C object with a ";
1858 }
1859
1860 if (CurrV.isOwned()) {
1861 os << "+1 retain count";
1862
1863 if (GCEnabled) {
1864 assert(CurrV.getObjKind() == RetEffect::CF);
1865 os << ". "
1866 "Core Foundation objects are not automatically garbage collected.";
1867 }
1868 }
1869 else {
1870 assert (CurrV.isNotOwned());
1871 os << "+0 retain count";
1872 }
Ted Kremenek6bd78702009-04-29 18:50:19 +00001873 }
Mike Stump11289f42009-09-09 15:08:12 +00001874
Anna Zaks3a769bd2011-09-15 01:08:34 +00001875 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
1876 N->getLocationContext());
Ted Kremenek6bd78702009-04-29 18:50:19 +00001877 return new PathDiagnosticEventPiece(Pos, os.str());
1878 }
Mike Stump11289f42009-09-09 15:08:12 +00001879
Ted Kremenek6bd78702009-04-29 18:50:19 +00001880 // Gather up the effects that were performed on the object at this
1881 // program point
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001882 SmallVector<ArgEffect, 2> AEffects;
Mike Stump11289f42009-09-09 15:08:12 +00001883
Jordy Rose20d4e682011-08-23 20:55:48 +00001884 const ExplodedNode *OrigNode = BRC.getNodeResolver().getOriginalNode(N);
1885 if (const RetainSummary *Summ = SummaryLog.lookup(OrigNode)) {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001886 // We only have summaries attached to nodes after evaluating CallExpr and
1887 // ObjCMessageExprs.
David Blaikie87396b92013-02-21 22:23:56 +00001888 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
Mike Stump11289f42009-09-09 15:08:12 +00001889
Ted Kremenekbfd28fd2009-07-22 22:35:28 +00001890 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001891 // Iterate through the parameter expressions and see if the symbol
1892 // was ever passed as an argument.
1893 unsigned i = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001894
Ted Kremenekbfd28fd2009-07-22 22:35:28 +00001895 for (CallExpr::const_arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
Ted Kremenek6bd78702009-04-29 18:50:19 +00001896 AI!=AE; ++AI, ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00001897
Ted Kremenek6bd78702009-04-29 18:50:19 +00001898 // Retrieve the value of the argument. Is it the symbol
1899 // we are interested in?
Ted Kremenek632e3b72012-01-06 22:09:28 +00001900 if (CurrSt->getSValAsScalarOrLoc(*AI, LCtx).getAsLocSymbol() != Sym)
Ted Kremenek6bd78702009-04-29 18:50:19 +00001901 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001902
Ted Kremenek6bd78702009-04-29 18:50:19 +00001903 // We have an argument. Get the effect!
1904 AEffects.push_back(Summ->getArg(i));
1905 }
1906 }
Mike Stump11289f42009-09-09 15:08:12 +00001907 else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
Douglas Gregor9a129192010-04-21 00:45:42 +00001908 if (const Expr *receiver = ME->getInstanceReceiver())
Ted Kremenek632e3b72012-01-06 22:09:28 +00001909 if (CurrSt->getSValAsScalarOrLoc(receiver, LCtx)
1910 .getAsLocSymbol() == Sym) {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001911 // The symbol we are tracking is the receiver.
1912 AEffects.push_back(Summ->getReceiverEffect());
1913 }
1914 }
1915 }
Mike Stump11289f42009-09-09 15:08:12 +00001916
Ted Kremenek6bd78702009-04-29 18:50:19 +00001917 do {
1918 // Get the previous type state.
1919 RefVal PrevV = *PrevT;
Mike Stump11289f42009-09-09 15:08:12 +00001920
Ted Kremenek6bd78702009-04-29 18:50:19 +00001921 // Specially handle -dealloc.
Benjamin Kramerab3838a2013-08-16 21:57:14 +00001922 if (!GCEnabled && std::find(AEffects.begin(), AEffects.end(), Dealloc) !=
1923 AEffects.end()) {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001924 // Determine if the object's reference count was pushed to zero.
1925 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
1926 // We may not have transitioned to 'release' if we hit an error.
1927 // This case is handled elsewhere.
1928 if (CurrV.getKind() == RefVal::Released) {
Ted Kremenek3a0516b2009-05-08 20:01:42 +00001929 assert(CurrV.getCombinedCounts() == 0);
Ted Kremenek6bd78702009-04-29 18:50:19 +00001930 os << "Object released by directly sending the '-dealloc' message";
1931 break;
1932 }
1933 }
Mike Stump11289f42009-09-09 15:08:12 +00001934
Ted Kremenek6bd78702009-04-29 18:50:19 +00001935 // Specially handle CFMakeCollectable and friends.
Benjamin Kramerab3838a2013-08-16 21:57:14 +00001936 if (std::find(AEffects.begin(), AEffects.end(), MakeCollectable) !=
1937 AEffects.end()) {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001938 // Get the name of the function.
David Blaikie87396b92013-02-21 22:23:56 +00001939 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
Ted Kremenek632e3b72012-01-06 22:09:28 +00001940 SVal X =
1941 CurrSt->getSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee(), LCtx);
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001942 const FunctionDecl *FD = X.getAsFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001943
Jordy Rose7a534982011-08-24 05:47:39 +00001944 if (GCEnabled) {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001945 // Determine if the object's reference count was pushed to zero.
1946 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
Mike Stump11289f42009-09-09 15:08:12 +00001947
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001948 os << "In GC mode a call to '" << *FD
Ted Kremenek6bd78702009-04-29 18:50:19 +00001949 << "' decrements an object's retain count and registers the "
1950 "object with the garbage collector. ";
Mike Stump11289f42009-09-09 15:08:12 +00001951
Ted Kremenek6bd78702009-04-29 18:50:19 +00001952 if (CurrV.getKind() == RefVal::Released) {
1953 assert(CurrV.getCount() == 0);
1954 os << "Since it now has a 0 retain count the object can be "
1955 "automatically collected by the garbage collector.";
1956 }
1957 else
1958 os << "An object must have a 0 retain count to be garbage collected. "
1959 "After this call its retain count is +" << CurrV.getCount()
1960 << '.';
1961 }
Mike Stump11289f42009-09-09 15:08:12 +00001962 else
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001963 os << "When GC is not enabled a call to '" << *FD
Ted Kremenek6bd78702009-04-29 18:50:19 +00001964 << "' has no effect on its argument.";
Mike Stump11289f42009-09-09 15:08:12 +00001965
Ted Kremenek6bd78702009-04-29 18:50:19 +00001966 // Nothing more to say.
1967 break;
1968 }
Mike Stump11289f42009-09-09 15:08:12 +00001969
1970 // Determine if the typestate has changed.
Ted Kremenek6bd78702009-04-29 18:50:19 +00001971 if (!(PrevV == CurrV))
1972 switch (CurrV.getKind()) {
1973 case RefVal::Owned:
1974 case RefVal::NotOwned:
Mike Stump11289f42009-09-09 15:08:12 +00001975
Ted Kremenek3a0516b2009-05-08 20:01:42 +00001976 if (PrevV.getCount() == CurrV.getCount()) {
1977 // Did an autorelease message get sent?
1978 if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
1979 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001980
Zhongxing Xu08a2ede2009-05-12 10:10:00 +00001981 assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount());
Jordan Rose7467f062013-04-23 01:42:25 +00001982 os << "Object autoreleased";
Ted Kremenek3a0516b2009-05-08 20:01:42 +00001983 break;
1984 }
Mike Stump11289f42009-09-09 15:08:12 +00001985
Ted Kremenek6bd78702009-04-29 18:50:19 +00001986 if (PrevV.getCount() > CurrV.getCount())
1987 os << "Reference count decremented.";
1988 else
1989 os << "Reference count incremented.";
Mike Stump11289f42009-09-09 15:08:12 +00001990
Ted Kremenek6bd78702009-04-29 18:50:19 +00001991 if (unsigned Count = CurrV.getCount())
1992 os << " The object now has a +" << Count << " retain count.";
Mike Stump11289f42009-09-09 15:08:12 +00001993
Ted Kremenek6bd78702009-04-29 18:50:19 +00001994 if (PrevV.getKind() == RefVal::Released) {
Jordy Rose7a534982011-08-24 05:47:39 +00001995 assert(GCEnabled && CurrV.getCount() > 0);
Jordy Rose78373e52012-03-17 05:49:15 +00001996 os << " The object is not eligible for garbage collection until "
1997 "the retain count reaches 0 again.";
Ted Kremenek6bd78702009-04-29 18:50:19 +00001998 }
Mike Stump11289f42009-09-09 15:08:12 +00001999
Ted Kremenek6bd78702009-04-29 18:50:19 +00002000 break;
Mike Stump11289f42009-09-09 15:08:12 +00002001
Ted Kremenek6bd78702009-04-29 18:50:19 +00002002 case RefVal::Released:
2003 os << "Object released.";
2004 break;
Mike Stump11289f42009-09-09 15:08:12 +00002005
Ted Kremenek6bd78702009-04-29 18:50:19 +00002006 case RefVal::ReturnedOwned:
Jordy Rose78373e52012-03-17 05:49:15 +00002007 // Autoreleases can be applied after marking a node ReturnedOwned.
2008 if (CurrV.getAutoreleaseCount())
2009 return NULL;
2010
2011 os << "Object returned to caller as an owning reference (single "
2012 "retain count transferred to caller)";
Ted Kremenek6bd78702009-04-29 18:50:19 +00002013 break;
Mike Stump11289f42009-09-09 15:08:12 +00002014
Ted Kremenek6bd78702009-04-29 18:50:19 +00002015 case RefVal::ReturnedNotOwned:
Ted Kremenekf2301982011-05-26 18:45:44 +00002016 os << "Object returned to caller with a +0 retain count";
Ted Kremenek6bd78702009-04-29 18:50:19 +00002017 break;
Mike Stump11289f42009-09-09 15:08:12 +00002018
Ted Kremenek6bd78702009-04-29 18:50:19 +00002019 default:
2020 return NULL;
2021 }
Mike Stump11289f42009-09-09 15:08:12 +00002022
Ted Kremenek6bd78702009-04-29 18:50:19 +00002023 // Emit any remaining diagnostics for the argument effects (if any).
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002024 for (SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
Ted Kremenek6bd78702009-04-29 18:50:19 +00002025 E=AEffects.end(); I != E; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +00002026
Ted Kremenek6bd78702009-04-29 18:50:19 +00002027 // A bunch of things have alternate behavior under GC.
Jordy Rose7a534982011-08-24 05:47:39 +00002028 if (GCEnabled)
Ted Kremenek6bd78702009-04-29 18:50:19 +00002029 switch (*I) {
2030 default: break;
2031 case Autorelease:
2032 os << "In GC mode an 'autorelease' has no effect.";
2033 continue;
2034 case IncRefMsg:
2035 os << "In GC mode the 'retain' message has no effect.";
2036 continue;
2037 case DecRefMsg:
2038 os << "In GC mode the 'release' message has no effect.";
2039 continue;
2040 }
2041 }
Mike Stump11289f42009-09-09 15:08:12 +00002042 } while (0);
2043
Ted Kremenek6bd78702009-04-29 18:50:19 +00002044 if (os.str().empty())
2045 return 0; // We have nothing to say!
Ted Kremenek051a03d2009-05-13 07:12:33 +00002046
David Blaikie87396b92013-02-21 22:23:56 +00002047 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
Anna Zaks3a769bd2011-09-15 01:08:34 +00002048 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
2049 N->getLocationContext());
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002050 PathDiagnosticPiece *P = new PathDiagnosticEventPiece(Pos, os.str());
Mike Stump11289f42009-09-09 15:08:12 +00002051
Ted Kremenek6bd78702009-04-29 18:50:19 +00002052 // Add the range by scanning the children of the statement for any bindings
2053 // to Sym.
Mike Stump11289f42009-09-09 15:08:12 +00002054 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
Ted Kremenekbfd28fd2009-07-22 22:35:28 +00002055 I!=E; ++I)
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002056 if (const Expr *Exp = dyn_cast_or_null<Expr>(*I))
Ted Kremenek632e3b72012-01-06 22:09:28 +00002057 if (CurrSt->getSValAsScalarOrLoc(Exp, LCtx).getAsLocSymbol() == Sym) {
Ted Kremenek6bd78702009-04-29 18:50:19 +00002058 P->addRange(Exp->getSourceRange());
2059 break;
2060 }
Mike Stump11289f42009-09-09 15:08:12 +00002061
Ted Kremenek6bd78702009-04-29 18:50:19 +00002062 return P;
2063}
2064
Anna Zaks75de3232012-02-28 22:39:22 +00002065// Find the first node in the current function context that referred to the
2066// tracked symbol and the memory location that value was stored to. Note, the
2067// value is only reported if the allocation occurred in the same function as
Anna Zakse51362e2013-04-10 21:42:06 +00002068// the leak. The function can also return a location context, which should be
2069// treated as interesting.
2070struct AllocationInfo {
2071 const ExplodedNode* N;
Anna Zaks3f303be2013-04-10 22:56:30 +00002072 const MemRegion *R;
Anna Zakse51362e2013-04-10 21:42:06 +00002073 const LocationContext *InterestingMethodContext;
Anna Zaks3f303be2013-04-10 22:56:30 +00002074 AllocationInfo(const ExplodedNode *InN,
2075 const MemRegion *InR,
Anna Zakse51362e2013-04-10 21:42:06 +00002076 const LocationContext *InInterestingMethodContext) :
2077 N(InN), R(InR), InterestingMethodContext(InInterestingMethodContext) {}
2078};
2079
2080static AllocationInfo
Ted Kremenek001fd5b2011-08-15 22:09:50 +00002081GetAllocationSite(ProgramStateManager& StateMgr, const ExplodedNode *N,
Ted Kremenek6bd78702009-04-29 18:50:19 +00002082 SymbolRef Sym) {
Anna Zakse51362e2013-04-10 21:42:06 +00002083 const ExplodedNode *AllocationNode = N;
2084 const ExplodedNode *AllocationNodeInCurrentContext = N;
Mike Stump11289f42009-09-09 15:08:12 +00002085 const MemRegion* FirstBinding = 0;
Anna Zaks75de3232012-02-28 22:39:22 +00002086 const LocationContext *LeakContext = N->getLocationContext();
Mike Stump11289f42009-09-09 15:08:12 +00002087
Anna Zakse51362e2013-04-10 21:42:06 +00002088 // The location context of the init method called on the leaked object, if
2089 // available.
2090 const LocationContext *InitMethodContext = 0;
2091
Ted Kremenek6bd78702009-04-29 18:50:19 +00002092 while (N) {
Ted Kremenek49b1e382012-01-26 21:29:00 +00002093 ProgramStateRef St = N->getState();
Anna Zakse51362e2013-04-10 21:42:06 +00002094 const LocationContext *NContext = N->getLocationContext();
Mike Stump11289f42009-09-09 15:08:12 +00002095
Anna Zaksf5788c72012-08-14 00:36:15 +00002096 if (!getRefBinding(St, Sym))
Ted Kremenek6bd78702009-04-29 18:50:19 +00002097 break;
Mike Stump11289f42009-09-09 15:08:12 +00002098
Anna Zaks6797d6e2012-03-21 19:45:01 +00002099 StoreManager::FindUniqueBinding FB(Sym);
Mike Stump11289f42009-09-09 15:08:12 +00002100 StateMgr.iterBindings(St, FB);
Anna Zakse51362e2013-04-10 21:42:06 +00002101
Anna Zaks7c19abe2013-04-10 21:42:02 +00002102 if (FB) {
2103 const MemRegion *R = FB.getRegion();
Anna Zaks07804ef2013-04-10 22:56:33 +00002104 const VarRegion *VR = R->getBaseRegion()->getAs<VarRegion>();
Anna Zaks7c19abe2013-04-10 21:42:02 +00002105 // Do not show local variables belonging to a function other than
2106 // where the error is reported.
2107 if (!VR || VR->getStackFrame() == LeakContext->getCurrentStackFrame())
Anna Zakse51362e2013-04-10 21:42:06 +00002108 FirstBinding = R;
Anna Zaks7c19abe2013-04-10 21:42:02 +00002109 }
Mike Stump11289f42009-09-09 15:08:12 +00002110
Anna Zakse51362e2013-04-10 21:42:06 +00002111 // AllocationNode is the last node in which the symbol was tracked.
2112 AllocationNode = N;
2113
2114 // AllocationNodeInCurrentContext, is the last node in the current context
2115 // in which the symbol was tracked.
2116 if (NContext == LeakContext)
2117 AllocationNodeInCurrentContext = N;
2118
Anna Zaks3f303be2013-04-10 22:56:30 +00002119 // Find the last init that was called on the given symbol and store the
2120 // init method's location context.
2121 if (!InitMethodContext)
2122 if (Optional<CallEnter> CEP = N->getLocation().getAs<CallEnter>()) {
2123 const Stmt *CE = CEP->getCallExpr();
Anna Zaks99394bb2013-04-25 00:41:32 +00002124 if (const ObjCMessageExpr *ME = dyn_cast_or_null<ObjCMessageExpr>(CE)) {
Anna Zaks3f303be2013-04-10 22:56:30 +00002125 const Stmt *RecExpr = ME->getInstanceReceiver();
2126 if (RecExpr) {
2127 SVal RecV = St->getSVal(RecExpr, NContext);
2128 if (ME->getMethodFamily() == OMF_init && RecV.getAsSymbol() == Sym)
2129 InitMethodContext = CEP->getCalleeContext();
2130 }
2131 }
Anna Zakse51362e2013-04-10 21:42:06 +00002132 }
Anna Zaks75de3232012-02-28 22:39:22 +00002133
Mike Stump11289f42009-09-09 15:08:12 +00002134 N = N->pred_empty() ? NULL : *(N->pred_begin());
Ted Kremenek6bd78702009-04-29 18:50:19 +00002135 }
Mike Stump11289f42009-09-09 15:08:12 +00002136
Anna Zakse51362e2013-04-10 21:42:06 +00002137 // If we are reporting a leak of the object that was allocated with alloc,
Anna Zaks3f303be2013-04-10 22:56:30 +00002138 // mark its init method as interesting.
Anna Zakse51362e2013-04-10 21:42:06 +00002139 const LocationContext *InterestingMethodContext = 0;
2140 if (InitMethodContext) {
2141 const ProgramPoint AllocPP = AllocationNode->getLocation();
2142 if (Optional<StmtPoint> SP = AllocPP.getAs<StmtPoint>())
2143 if (const ObjCMessageExpr *ME = SP->getStmtAs<ObjCMessageExpr>())
2144 if (ME->getMethodFamily() == OMF_alloc)
2145 InterestingMethodContext = InitMethodContext;
2146 }
2147
Anna Zaks75de3232012-02-28 22:39:22 +00002148 // If allocation happened in a function different from the leak node context,
2149 // do not report the binding.
Ted Kremenekb045b012012-10-12 22:56:40 +00002150 assert(N && "Could not find allocation node");
Anna Zaks75de3232012-02-28 22:39:22 +00002151 if (N->getLocationContext() != LeakContext) {
2152 FirstBinding = 0;
2153 }
2154
Anna Zakse51362e2013-04-10 21:42:06 +00002155 return AllocationInfo(AllocationNodeInCurrentContext,
2156 FirstBinding,
2157 InterestingMethodContext);
Ted Kremenek6bd78702009-04-29 18:50:19 +00002158}
2159
2160PathDiagnosticPiece*
Anna Zaks88255cc2011-08-20 01:27:22 +00002161CFRefReportVisitor::getEndPath(BugReporterContext &BRC,
2162 const ExplodedNode *EndN,
2163 BugReport &BR) {
Ted Kremenek1e809b42012-03-09 01:13:14 +00002164 BR.markInteresting(Sym);
Anna Zaks88255cc2011-08-20 01:27:22 +00002165 return BugReporterVisitor::getDefaultEndPath(BRC, EndN, BR);
Ted Kremenek6bd78702009-04-29 18:50:19 +00002166}
2167
2168PathDiagnosticPiece*
Anna Zaks88255cc2011-08-20 01:27:22 +00002169CFRefLeakReportVisitor::getEndPath(BugReporterContext &BRC,
2170 const ExplodedNode *EndN,
2171 BugReport &BR) {
Mike Stump11289f42009-09-09 15:08:12 +00002172
Ted Kremenekbb8d5462009-05-06 21:39:49 +00002173 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenek6bd78702009-04-29 18:50:19 +00002174 // assigned to different variables, etc.
Ted Kremenek1e809b42012-03-09 01:13:14 +00002175 BR.markInteresting(Sym);
Mike Stump11289f42009-09-09 15:08:12 +00002176
Ted Kremenek6bd78702009-04-29 18:50:19 +00002177 // We are reporting a leak. Walk up the graph to get to the first node where
2178 // the symbol appeared, and also get the first VarDecl that tracked object
2179 // is stored to.
Anna Zakse51362e2013-04-10 21:42:06 +00002180 AllocationInfo AllocI =
Ted Kremenek8c8fb482009-05-08 23:32:51 +00002181 GetAllocationSite(BRC.getStateManager(), EndN, Sym);
Mike Stump11289f42009-09-09 15:08:12 +00002182
Anna Zakse51362e2013-04-10 21:42:06 +00002183 const MemRegion* FirstBinding = AllocI.R;
2184 BR.markInteresting(AllocI.InterestingMethodContext);
2185
Anna Zaks921f0492011-09-15 18:56:07 +00002186 SourceManager& SM = BRC.getSourceManager();
Mike Stump11289f42009-09-09 15:08:12 +00002187
Ted Kremenek6bd78702009-04-29 18:50:19 +00002188 // Compute an actual location for the leak. Sometimes a leak doesn't
2189 // occur at an actual statement (e.g., transition between blocks; end
2190 // of function) so we need to walk the graph and compute a real location.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002191 const ExplodedNode *LeakN = EndN;
Anna Zaks921f0492011-09-15 18:56:07 +00002192 PathDiagnosticLocation L = PathDiagnosticLocation::createEndOfPath(LeakN, SM);
Mike Stump11289f42009-09-09 15:08:12 +00002193
Ted Kremenek6bd78702009-04-29 18:50:19 +00002194 std::string sbuf;
2195 llvm::raw_string_ostream os(sbuf);
Mike Stump11289f42009-09-09 15:08:12 +00002196
Ted Kremenekf2301982011-05-26 18:45:44 +00002197 os << "Object leaked: ";
Mike Stump11289f42009-09-09 15:08:12 +00002198
Ted Kremenekf2301982011-05-26 18:45:44 +00002199 if (FirstBinding) {
2200 os << "object allocated and stored into '"
2201 << FirstBinding->getString() << '\'';
2202 }
2203 else
2204 os << "allocated object";
Mike Stump11289f42009-09-09 15:08:12 +00002205
Ted Kremenek6bd78702009-04-29 18:50:19 +00002206 // Get the retain count.
Anna Zaksf5788c72012-08-14 00:36:15 +00002207 const RefVal* RV = getRefBinding(EndN->getState(), Sym);
Ted Kremenekb045b012012-10-12 22:56:40 +00002208 assert(RV);
Mike Stump11289f42009-09-09 15:08:12 +00002209
Ted Kremenek6bd78702009-04-29 18:50:19 +00002210 if (RV->getKind() == RefVal::ErrorLeakReturned) {
2211 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
Jordy Rose43426f82011-07-15 22:17:54 +00002212 // objects. Only "copy", "alloc", "retain" and "new" transfer ownership
Ted Kremenek6bd78702009-04-29 18:50:19 +00002213 // to the caller for NS objects.
Ted Kremenek8e2c9b02011-05-25 06:19:45 +00002214 const Decl *D = &EndN->getCodeDecl();
Ted Kremenek2a786952012-09-06 23:03:07 +00002215
2216 os << (isa<ObjCMethodDecl>(D) ? " is returned from a method "
2217 : " is returned from a function ");
2218
Aaron Ballman9ead1242013-12-19 02:39:40 +00002219 if (D->hasAttr<CFReturnsNotRetainedAttr>())
Ted Kremenek2a786952012-09-06 23:03:07 +00002220 os << "that is annotated as CF_RETURNS_NOT_RETAINED";
Aaron Ballman9ead1242013-12-19 02:39:40 +00002221 else if (D->hasAttr<NSReturnsNotRetainedAttr>())
Ted Kremenek2a786952012-09-06 23:03:07 +00002222 os << "that is annotated as NS_RETURNS_NOT_RETAINED";
Ted Kremenek8e2c9b02011-05-25 06:19:45 +00002223 else {
Ted Kremenek2a786952012-09-06 23:03:07 +00002224 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2225 os << "whose name ('" << MD->getSelector().getAsString()
2226 << "') does not start with 'copy', 'mutableCopy', 'alloc' or 'new'."
2227 " This violates the naming convention rules"
2228 " given in the Memory Management Guide for Cocoa";
2229 }
2230 else {
2231 const FunctionDecl *FD = cast<FunctionDecl>(D);
2232 os << "whose name ('" << *FD
2233 << "') does not contain 'Copy' or 'Create'. This violates the naming"
2234 " convention rules given in the Memory Management Guide for Core"
2235 " Foundation";
2236 }
2237 }
Ted Kremenek6bd78702009-04-29 18:50:19 +00002238 }
Ted Kremenekdee56e32009-05-10 06:25:57 +00002239 else if (RV->getKind() == RefVal::ErrorGCLeakReturned) {
David Blaikie3cbec0f2013-02-21 22:37:44 +00002240 const ObjCMethodDecl &MD = cast<ObjCMethodDecl>(EndN->getCodeDecl());
Ted Kremenekdee56e32009-05-10 06:25:57 +00002241 os << " and returned from method '" << MD.getSelector().getAsString()
Ted Kremenek1f8e4342009-05-10 16:52:15 +00002242 << "' is potentially leaked when using garbage collection. Callers "
2243 "of this method do not expect a returned object with a +1 retain "
2244 "count since they expect the object to be managed by the garbage "
2245 "collector";
Ted Kremenekdee56e32009-05-10 06:25:57 +00002246 }
Ted Kremenek6bd78702009-04-29 18:50:19 +00002247 else
Ted Kremenek4f63ac72010-10-15 22:50:23 +00002248 os << " is not referenced later in this execution path and has a retain "
Ted Kremenekf2301982011-05-26 18:45:44 +00002249 "count of +" << RV->getCount();
Mike Stump11289f42009-09-09 15:08:12 +00002250
Ted Kremenek6bd78702009-04-29 18:50:19 +00002251 return new PathDiagnosticEventPiece(L, os.str());
2252}
2253
Jordy Rose184bd142011-08-24 22:39:09 +00002254CFRefLeakReport::CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts,
2255 bool GCEnabled, const SummaryLogTy &Log,
2256 ExplodedNode *n, SymbolRef sym,
Ted Kremenek8671acb2013-04-16 21:44:22 +00002257 CheckerContext &Ctx,
2258 bool IncludeAllocationLine)
2259 : CFRefReport(D, LOpts, GCEnabled, Log, n, sym, false) {
Mike Stump11289f42009-09-09 15:08:12 +00002260
Chris Lattner57540c52011-04-15 05:22:18 +00002261 // Most bug reports are cached at the location where they occurred.
Ted Kremenek6bd78702009-04-29 18:50:19 +00002262 // With leaks, we want to unique them by the location where they were
2263 // allocated, and only report a single path. To do this, we need to find
2264 // the allocation site of a piece of tracked memory, which we do via a
2265 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2266 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2267 // that all ancestor nodes that represent the allocation site have the
2268 // same SourceLocation.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002269 const ExplodedNode *AllocNode = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002270
Anna Zaks58734db2011-10-25 19:57:11 +00002271 const SourceManager& SMgr = Ctx.getSourceManager();
Anna Zaksc29bed32011-09-20 21:38:35 +00002272
Anna Zakse51362e2013-04-10 21:42:06 +00002273 AllocationInfo AllocI =
Anna Zaks58734db2011-10-25 19:57:11 +00002274 GetAllocationSite(Ctx.getStateManager(), getErrorNode(), sym);
Mike Stump11289f42009-09-09 15:08:12 +00002275
Anna Zakse51362e2013-04-10 21:42:06 +00002276 AllocNode = AllocI.N;
2277 AllocBinding = AllocI.R;
2278 markInteresting(AllocI.InterestingMethodContext);
2279
Ted Kremenek6bd78702009-04-29 18:50:19 +00002280 // Get the SourceLocation for the allocation site.
Jordan Rosefbe6dba2012-07-10 22:07:52 +00002281 // FIXME: This will crash the analyzer if an allocation comes from an
2282 // implicit call. (Currently there are no such allocations in Cocoa, though.)
2283 const Stmt *AllocStmt;
Ted Kremenek6bd78702009-04-29 18:50:19 +00002284 ProgramPoint P = AllocNode->getLocation();
David Blaikie87396b92013-02-21 22:23:56 +00002285 if (Optional<CallExitEnd> Exit = P.getAs<CallExitEnd>())
Jordan Rosefbe6dba2012-07-10 22:07:52 +00002286 AllocStmt = Exit->getCalleeContext()->getCallSite();
2287 else
David Blaikie87396b92013-02-21 22:23:56 +00002288 AllocStmt = P.castAs<PostStmt>().getStmt();
Jordan Rosefbe6dba2012-07-10 22:07:52 +00002289 assert(AllocStmt && "All allocations must come from explicit calls");
Anna Zaks40402872013-04-23 23:57:50 +00002290
2291 PathDiagnosticLocation AllocLocation =
2292 PathDiagnosticLocation::createBegin(AllocStmt, SMgr,
2293 AllocNode->getLocationContext());
2294 Location = AllocLocation;
2295
2296 // Set uniqieing info, which will be used for unique the bug reports. The
2297 // leaks should be uniqued on the allocation site.
2298 UniqueingLocation = AllocLocation;
2299 UniqueingDecl = AllocNode->getLocationContext()->getDecl();
2300
Ted Kremenek6bd78702009-04-29 18:50:19 +00002301 // Fill in the description of the bug.
2302 Description.clear();
2303 llvm::raw_string_ostream os(Description);
Ted Kremenekf1e76672009-05-02 19:05:19 +00002304 os << "Potential leak ";
Jordy Rose184bd142011-08-24 22:39:09 +00002305 if (GCEnabled)
Ted Kremenekf1e76672009-05-02 19:05:19 +00002306 os << "(when using garbage collection) ";
Anna Zaks16f38312012-02-28 21:49:08 +00002307 os << "of an object";
Mike Stump11289f42009-09-09 15:08:12 +00002308
Ted Kremenek8671acb2013-04-16 21:44:22 +00002309 if (AllocBinding) {
Anna Zaks16f38312012-02-28 21:49:08 +00002310 os << " stored into '" << AllocBinding->getString() << '\'';
Ted Kremenek8671acb2013-04-16 21:44:22 +00002311 if (IncludeAllocationLine) {
2312 FullSourceLoc SL(AllocStmt->getLocStart(), Ctx.getSourceManager());
2313 os << " (allocated on line " << SL.getSpellingLineNumber() << ")";
2314 }
2315 }
Anna Zaks071a89c2011-08-19 23:21:56 +00002316
Jordy Rose184bd142011-08-24 22:39:09 +00002317 addVisitor(new CFRefLeakReportVisitor(sym, GCEnabled, Log));
Ted Kremenek6bd78702009-04-29 18:50:19 +00002318}
2319
2320//===----------------------------------------------------------------------===//
2321// Main checker logic.
2322//===----------------------------------------------------------------------===//
2323
Ted Kremenek70a87882009-11-25 22:17:44 +00002324namespace {
Jordy Rose75e680e2011-09-02 06:44:22 +00002325class RetainCountChecker
Jordy Rose5df640d2011-08-24 18:56:32 +00002326 : public Checker< check::Bind,
Jordy Rose78612762011-08-23 19:01:07 +00002327 check::DeadSymbols,
Jordy Rose5df640d2011-08-24 18:56:32 +00002328 check::EndAnalysis,
Anna Zaks3fdcc0b2013-01-03 00:25:29 +00002329 check::EndFunction,
Jordy Rose217eb902011-08-17 21:27:39 +00002330 check::PostStmt<BlockExpr>,
John McCall31168b02011-06-15 23:02:42 +00002331 check::PostStmt<CastExpr>,
Ted Kremenek415287d2012-03-06 20:06:12 +00002332 check::PostStmt<ObjCArrayLiteral>,
2333 check::PostStmt<ObjCDictionaryLiteral>,
Jordy Rose6393f822012-05-12 05:10:43 +00002334 check::PostStmt<ObjCBoxedExpr>,
Jordan Rose682b3162012-07-02 19:28:21 +00002335 check::PostCall,
Jordy Rose298cc4d2011-08-23 19:43:16 +00002336 check::PreStmt<ReturnStmt>,
Jordy Rose217eb902011-08-17 21:27:39 +00002337 check::RegionChanges,
Jordy Rose898a1482011-08-21 21:58:18 +00002338 eval::Assume,
2339 eval::Call > {
Dylan Noblesmithe2778992012-02-05 02:12:40 +00002340 mutable OwningPtr<CFRefBug> useAfterRelease, releaseNotOwned;
2341 mutable OwningPtr<CFRefBug> deallocGC, deallocNotOwned;
2342 mutable OwningPtr<CFRefBug> overAutorelease, returnNotOwnedForOwned;
2343 mutable OwningPtr<CFRefBug> leakWithinFunction, leakAtReturn;
2344 mutable OwningPtr<CFRefBug> leakWithinFunctionGC, leakAtReturnGC;
Jordy Rose78612762011-08-23 19:01:07 +00002345
2346 typedef llvm::DenseMap<SymbolRef, const SimpleProgramPointTag *> SymbolTagMap;
2347
2348 // This map is only used to ensure proper deletion of any allocated tags.
2349 mutable SymbolTagMap DeadSymbolTags;
2350
Dylan Noblesmithe2778992012-02-05 02:12:40 +00002351 mutable OwningPtr<RetainSummaryManager> Summaries;
2352 mutable OwningPtr<RetainSummaryManager> SummariesGC;
Jordy Rose5df640d2011-08-24 18:56:32 +00002353 mutable SummaryLogTy SummaryLog;
2354 mutable bool ShouldResetSummaryLog;
2355
Ted Kremenek8671acb2013-04-16 21:44:22 +00002356 /// Optional setting to indicate if leak reports should include
2357 /// the allocation line.
2358 mutable bool IncludeAllocationLine;
2359
Jordy Rosea8f99ba2011-08-20 21:17:59 +00002360public:
Ted Kremenek8671acb2013-04-16 21:44:22 +00002361 RetainCountChecker(AnalyzerOptions &AO)
2362 : ShouldResetSummaryLog(false),
2363 IncludeAllocationLine(shouldIncludeAllocationSiteInLeakDiagnostics(AO)) {}
Jordy Rose78612762011-08-23 19:01:07 +00002364
Jordy Rose75e680e2011-09-02 06:44:22 +00002365 virtual ~RetainCountChecker() {
Jordy Rose78612762011-08-23 19:01:07 +00002366 DeleteContainerSeconds(DeadSymbolTags);
2367 }
2368
Jordy Rose5df640d2011-08-24 18:56:32 +00002369 void checkEndAnalysis(ExplodedGraph &G, BugReporter &BR,
2370 ExprEngine &Eng) const {
2371 // FIXME: This is a hack to make sure the summary log gets cleared between
2372 // analyses of different code bodies.
2373 //
2374 // Why is this necessary? Because a checker's lifetime is tied to a
2375 // translation unit, but an ExplodedGraph's lifetime is just a code body.
2376 // Once in a blue moon, a new ExplodedNode will have the same address as an
2377 // old one with an associated summary, and the bug report visitor gets very
2378 // confused. (To make things worse, the summary lifetime is currently also
2379 // tied to a code body, so we get a crash instead of incorrect results.)
Jordy Rose95589f12011-08-24 09:27:24 +00002380 //
2381 // Why is this a bad solution? Because if the lifetime of the ExplodedGraph
2382 // changes, things will start going wrong again. Really the lifetime of this
2383 // log needs to be tied to either the specific nodes in it or the entire
2384 // ExplodedGraph, not to a specific part of the code being analyzed.
2385 //
Jordy Rose5df640d2011-08-24 18:56:32 +00002386 // (Also, having stateful local data means that the same checker can't be
2387 // used from multiple threads, but a lot of checkers have incorrect
2388 // assumptions about that anyway. So that wasn't a priority at the time of
2389 // this fix.)
Jordy Rose95589f12011-08-24 09:27:24 +00002390 //
Jordy Rose5df640d2011-08-24 18:56:32 +00002391 // This happens at the end of analysis, but bug reports are emitted /after/
2392 // this point. So we can't just clear the summary log now. Instead, we mark
2393 // that the next time we access the summary log, it should be cleared.
2394
2395 // If we never reset the summary log during /this/ code body analysis,
2396 // there were no new summaries. There might still have been summaries from
2397 // the /last/ analysis, so clear them out to make sure the bug report
2398 // visitors don't get confused.
2399 if (ShouldResetSummaryLog)
2400 SummaryLog.clear();
2401
2402 ShouldResetSummaryLog = !SummaryLog.empty();
Jordy Rose95589f12011-08-24 09:27:24 +00002403 }
2404
Jordy Rosec49ec532011-09-02 05:55:19 +00002405 CFRefBug *getLeakWithinFunctionBug(const LangOptions &LOpts,
2406 bool GCEnabled) const {
2407 if (GCEnabled) {
Jordy Rose15484da2011-08-25 01:14:38 +00002408 if (!leakWithinFunctionGC)
Benjamin Kramerd1d76b22012-06-06 17:32:50 +00002409 leakWithinFunctionGC.reset(new Leak("Leak of object when using "
2410 "garbage collection"));
Jordy Rosec49ec532011-09-02 05:55:19 +00002411 return leakWithinFunctionGC.get();
Jordy Rose15484da2011-08-25 01:14:38 +00002412 } else {
2413 if (!leakWithinFunction) {
Douglas Gregor79a91412011-09-13 17:21:33 +00002414 if (LOpts.getGC() == LangOptions::HybridGC) {
Benjamin Kramerd1d76b22012-06-06 17:32:50 +00002415 leakWithinFunction.reset(new Leak("Leak of object when not using "
2416 "garbage collection (GC) in "
2417 "dual GC/non-GC code"));
Jordy Rose15484da2011-08-25 01:14:38 +00002418 } else {
Benjamin Kramerd1d76b22012-06-06 17:32:50 +00002419 leakWithinFunction.reset(new Leak("Leak"));
Jordy Rose15484da2011-08-25 01:14:38 +00002420 }
2421 }
Jordy Rosec49ec532011-09-02 05:55:19 +00002422 return leakWithinFunction.get();
Jordy Rose15484da2011-08-25 01:14:38 +00002423 }
2424 }
2425
Jordy Rosec49ec532011-09-02 05:55:19 +00002426 CFRefBug *getLeakAtReturnBug(const LangOptions &LOpts, bool GCEnabled) const {
2427 if (GCEnabled) {
Jordy Rose15484da2011-08-25 01:14:38 +00002428 if (!leakAtReturnGC)
Benjamin Kramerd1d76b22012-06-06 17:32:50 +00002429 leakAtReturnGC.reset(new Leak("Leak of returned object when using "
2430 "garbage collection"));
Jordy Rosec49ec532011-09-02 05:55:19 +00002431 return leakAtReturnGC.get();
Jordy Rose15484da2011-08-25 01:14:38 +00002432 } else {
2433 if (!leakAtReturn) {
Douglas Gregor79a91412011-09-13 17:21:33 +00002434 if (LOpts.getGC() == LangOptions::HybridGC) {
Benjamin Kramerd1d76b22012-06-06 17:32:50 +00002435 leakAtReturn.reset(new Leak("Leak of returned object when not using "
2436 "garbage collection (GC) in dual "
2437 "GC/non-GC code"));
Jordy Rose15484da2011-08-25 01:14:38 +00002438 } else {
Benjamin Kramerd1d76b22012-06-06 17:32:50 +00002439 leakAtReturn.reset(new Leak("Leak of returned object"));
Jordy Rose15484da2011-08-25 01:14:38 +00002440 }
2441 }
Jordy Rosec49ec532011-09-02 05:55:19 +00002442 return leakAtReturn.get();
Jordy Rose15484da2011-08-25 01:14:38 +00002443 }
2444 }
2445
Jordy Rosec49ec532011-09-02 05:55:19 +00002446 RetainSummaryManager &getSummaryManager(ASTContext &Ctx,
2447 bool GCEnabled) const {
2448 // FIXME: We don't support ARC being turned on and off during one analysis.
2449 // (nor, for that matter, do we support changing ASTContexts)
David Blaikiebbafb8a2012-03-11 07:00:24 +00002450 bool ARCEnabled = (bool)Ctx.getLangOpts().ObjCAutoRefCount;
Jordy Rosec49ec532011-09-02 05:55:19 +00002451 if (GCEnabled) {
2452 if (!SummariesGC)
Jordy Rose8b289a22011-08-25 00:10:37 +00002453 SummariesGC.reset(new RetainSummaryManager(Ctx, true, ARCEnabled));
Jordy Rosec49ec532011-09-02 05:55:19 +00002454 else
2455 assert(SummariesGC->isARCEnabled() == ARCEnabled);
Jordy Rose8b289a22011-08-25 00:10:37 +00002456 return *SummariesGC;
2457 } else {
Jordy Rosec49ec532011-09-02 05:55:19 +00002458 if (!Summaries)
Jordy Rose8b289a22011-08-25 00:10:37 +00002459 Summaries.reset(new RetainSummaryManager(Ctx, false, ARCEnabled));
Jordy Rosec49ec532011-09-02 05:55:19 +00002460 else
2461 assert(Summaries->isARCEnabled() == ARCEnabled);
Jordy Rose8b289a22011-08-25 00:10:37 +00002462 return *Summaries;
2463 }
2464 }
2465
Jordy Rosec49ec532011-09-02 05:55:19 +00002466 RetainSummaryManager &getSummaryManager(CheckerContext &C) const {
2467 return getSummaryManager(C.getASTContext(), C.isObjCGCEnabled());
2468 }
2469
Ted Kremenek49b1e382012-01-26 21:29:00 +00002470 void printState(raw_ostream &Out, ProgramStateRef State,
Jordy Rose58a20d32011-08-28 19:11:56 +00002471 const char *NL, const char *Sep) const;
2472
Anna Zaks3e0f4152011-10-06 00:43:15 +00002473 void checkBind(SVal loc, SVal val, const Stmt *S, CheckerContext &C) const;
Jordy Rose5c252ef2011-08-20 21:16:58 +00002474 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
2475 void checkPostStmt(const CastExpr *CE, CheckerContext &C) const;
John McCall31168b02011-06-15 23:02:42 +00002476
Ted Kremenek415287d2012-03-06 20:06:12 +00002477 void checkPostStmt(const ObjCArrayLiteral *AL, CheckerContext &C) const;
2478 void checkPostStmt(const ObjCDictionaryLiteral *DL, CheckerContext &C) const;
Jordy Rose6393f822012-05-12 05:10:43 +00002479 void checkPostStmt(const ObjCBoxedExpr *BE, CheckerContext &C) const;
2480
Jordan Rose682b3162012-07-02 19:28:21 +00002481 void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
Ted Kremenek415287d2012-03-06 20:06:12 +00002482
Jordan Roseeec15392012-07-02 19:27:43 +00002483 void checkSummary(const RetainSummary &Summ, const CallEvent &Call,
Jordy Rosed188d662011-08-28 05:16:28 +00002484 CheckerContext &C) const;
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002485
Anna Zaks25612732012-08-29 23:23:43 +00002486 void processSummaryOfInlined(const RetainSummary &Summ,
2487 const CallEvent &Call,
2488 CheckerContext &C) const;
2489
Jordy Rose898a1482011-08-21 21:58:18 +00002490 bool evalCall(const CallExpr *CE, CheckerContext &C) const;
2491
Ted Kremenek49b1e382012-01-26 21:29:00 +00002492 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Jordy Rose5c252ef2011-08-20 21:16:58 +00002493 bool Assumption) const;
Jordy Rose217eb902011-08-17 21:27:39 +00002494
Ted Kremenek49b1e382012-01-26 21:29:00 +00002495 ProgramStateRef
2496 checkRegionChanges(ProgramStateRef state,
Anna Zaksdc154152012-12-20 00:38:25 +00002497 const InvalidatedSymbols *invalidated,
Jordy Rose1fad6632011-08-27 22:51:26 +00002498 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks3d348342012-02-14 21:55:24 +00002499 ArrayRef<const MemRegion *> Regions,
Jordan Rose742920c2012-07-02 19:27:35 +00002500 const CallEvent *Call) const;
Jordy Rose5c252ef2011-08-20 21:16:58 +00002501
Ted Kremenek49b1e382012-01-26 21:29:00 +00002502 bool wantsRegionChangeUpdate(ProgramStateRef state) const {
Jordy Rosea8f99ba2011-08-20 21:17:59 +00002503 return true;
Jordy Rose5c252ef2011-08-20 21:16:58 +00002504 }
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002505
Jordy Rose298cc4d2011-08-23 19:43:16 +00002506 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
2507 void checkReturnWithRetEffect(const ReturnStmt *S, CheckerContext &C,
2508 ExplodedNode *Pred, RetEffect RE, RefVal X,
Ted Kremenek49b1e382012-01-26 21:29:00 +00002509 SymbolRef Sym, ProgramStateRef state) const;
Jordy Rose298cc4d2011-08-23 19:43:16 +00002510
Jordy Rose78612762011-08-23 19:01:07 +00002511 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Anna Zaks3fdcc0b2013-01-03 00:25:29 +00002512 void checkEndFunction(CheckerContext &C) const;
Jordy Rose78612762011-08-23 19:01:07 +00002513
Ted Kremenek49b1e382012-01-26 21:29:00 +00002514 ProgramStateRef updateSymbol(ProgramStateRef state, SymbolRef sym,
Anna Zaks25612732012-08-29 23:23:43 +00002515 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
2516 CheckerContext &C) const;
Jordy Rosebf77e512011-08-23 20:27:16 +00002517
Ted Kremenek49b1e382012-01-26 21:29:00 +00002518 void processNonLeakError(ProgramStateRef St, SourceRange ErrorRange,
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002519 RefVal::Kind ErrorKind, SymbolRef Sym,
2520 CheckerContext &C) const;
Ted Kremenek415287d2012-03-06 20:06:12 +00002521
2522 void processObjCLiterals(CheckerContext &C, const Expr *Ex) const;
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002523
Jordy Rose78612762011-08-23 19:01:07 +00002524 const ProgramPointTag *getDeadSymbolTag(SymbolRef sym) const;
2525
Ted Kremenek49b1e382012-01-26 21:29:00 +00002526 ProgramStateRef handleSymbolDeath(ProgramStateRef state,
Anna Zaksf5788c72012-08-14 00:36:15 +00002527 SymbolRef sid, RefVal V,
2528 SmallVectorImpl<SymbolRef> &Leaked) const;
Jordy Rose78612762011-08-23 19:01:07 +00002529
Jordan Roseff03c1d2012-12-06 18:58:18 +00002530 ProgramStateRef
Jordan Rose9f61f8a2012-08-18 00:30:16 +00002531 handleAutoreleaseCounts(ProgramStateRef state, ExplodedNode *Pred,
2532 const ProgramPointTag *Tag, CheckerContext &Ctx,
2533 SymbolRef Sym, RefVal V) const;
Jordy Rose6763e382011-08-23 20:07:14 +00002534
Ted Kremenek49b1e382012-01-26 21:29:00 +00002535 ExplodedNode *processLeaks(ProgramStateRef state,
Jordy Rose78612762011-08-23 19:01:07 +00002536 SmallVectorImpl<SymbolRef> &Leaked,
Anna Zaks58734db2011-10-25 19:57:11 +00002537 CheckerContext &Ctx,
Jordy Rose78612762011-08-23 19:01:07 +00002538 ExplodedNode *Pred = 0) const;
Ted Kremenek70a87882009-11-25 22:17:44 +00002539};
2540} // end anonymous namespace
2541
Jordy Rose217eb902011-08-17 21:27:39 +00002542namespace {
2543class StopTrackingCallback : public SymbolVisitor {
Ted Kremenek49b1e382012-01-26 21:29:00 +00002544 ProgramStateRef state;
Jordy Rose217eb902011-08-17 21:27:39 +00002545public:
Ted Kremenek49b1e382012-01-26 21:29:00 +00002546 StopTrackingCallback(ProgramStateRef st) : state(st) {}
2547 ProgramStateRef getState() const { return state; }
Jordy Rose217eb902011-08-17 21:27:39 +00002548
2549 bool VisitSymbol(SymbolRef sym) {
2550 state = state->remove<RefBindings>(sym);
2551 return true;
2552 }
2553};
2554} // end anonymous namespace
2555
Jordy Rose75e680e2011-09-02 06:44:22 +00002556//===----------------------------------------------------------------------===//
2557// Handle statements that may have an effect on refcounts.
2558//===----------------------------------------------------------------------===//
Jordy Rose217eb902011-08-17 21:27:39 +00002559
Jordy Rose75e680e2011-09-02 06:44:22 +00002560void RetainCountChecker::checkPostStmt(const BlockExpr *BE,
2561 CheckerContext &C) const {
Jordy Rose217eb902011-08-17 21:27:39 +00002562
Jordy Rose75e680e2011-09-02 06:44:22 +00002563 // Scan the BlockDecRefExprs for any object the retain count checker
Ted Kremenekbd862712010-07-01 20:16:50 +00002564 // may be tracking.
John McCallc63de662011-02-02 13:00:07 +00002565 if (!BE->getBlockDecl()->hasCaptures())
Ted Kremenekf89dcda2009-11-26 02:38:19 +00002566 return;
Ted Kremenekbd862712010-07-01 20:16:50 +00002567
Ted Kremenek49b1e382012-01-26 21:29:00 +00002568 ProgramStateRef state = C.getState();
Ted Kremenekf89dcda2009-11-26 02:38:19 +00002569 const BlockDataRegion *R =
Ted Kremenek632e3b72012-01-06 22:09:28 +00002570 cast<BlockDataRegion>(state->getSVal(BE,
2571 C.getLocationContext()).getAsRegion());
Ted Kremenekbd862712010-07-01 20:16:50 +00002572
Ted Kremenekf89dcda2009-11-26 02:38:19 +00002573 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
2574 E = R->referenced_vars_end();
Ted Kremenekbd862712010-07-01 20:16:50 +00002575
Ted Kremenekf89dcda2009-11-26 02:38:19 +00002576 if (I == E)
2577 return;
Ted Kremenekbd862712010-07-01 20:16:50 +00002578
Ted Kremenek04af9f22009-12-07 22:05:27 +00002579 // FIXME: For now we invalidate the tracking of all symbols passed to blocks
2580 // via captured variables, even though captured variables result in a copy
2581 // and in implicit increment/decrement of a retain count.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002582 SmallVector<const MemRegion*, 10> Regions;
Anna Zaksc9abbe22011-10-26 21:06:44 +00002583 const LocationContext *LC = C.getLocationContext();
Ted Kremenek90af9092010-12-02 07:49:45 +00002584 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
Ted Kremenekbd862712010-07-01 20:16:50 +00002585
Ted Kremenek04af9f22009-12-07 22:05:27 +00002586 for ( ; I != E; ++I) {
Ted Kremenekbcf90532012-12-06 07:17:20 +00002587 const VarRegion *VR = I.getCapturedRegion();
Ted Kremenek04af9f22009-12-07 22:05:27 +00002588 if (VR->getSuperRegion() == R) {
2589 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2590 }
2591 Regions.push_back(VR);
2592 }
Ted Kremenekbd862712010-07-01 20:16:50 +00002593
Ted Kremenek04af9f22009-12-07 22:05:27 +00002594 state =
2595 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
2596 Regions.data() + Regions.size()).getState();
Anna Zaksda4c8d62011-10-26 21:06:34 +00002597 C.addTransition(state);
Ted Kremenekf89dcda2009-11-26 02:38:19 +00002598}
2599
Jordy Rose75e680e2011-09-02 06:44:22 +00002600void RetainCountChecker::checkPostStmt(const CastExpr *CE,
2601 CheckerContext &C) const {
John McCall31168b02011-06-15 23:02:42 +00002602 const ObjCBridgedCastExpr *BE = dyn_cast<ObjCBridgedCastExpr>(CE);
2603 if (!BE)
2604 return;
2605
John McCall640767f2011-06-17 06:50:50 +00002606 ArgEffect AE = IncRef;
John McCall31168b02011-06-15 23:02:42 +00002607
2608 switch (BE->getBridgeKind()) {
2609 case clang::OBC_Bridge:
2610 // Do nothing.
2611 return;
2612 case clang::OBC_BridgeRetained:
2613 AE = IncRef;
2614 break;
2615 case clang::OBC_BridgeTransfer:
Benjamin Kramer1d5d6342013-10-20 11:53:20 +00002616 AE = DecRefBridgedTransferred;
John McCall31168b02011-06-15 23:02:42 +00002617 break;
2618 }
2619
Ted Kremenek49b1e382012-01-26 21:29:00 +00002620 ProgramStateRef state = C.getState();
Ted Kremenek632e3b72012-01-06 22:09:28 +00002621 SymbolRef Sym = state->getSVal(CE, C.getLocationContext()).getAsLocSymbol();
John McCall31168b02011-06-15 23:02:42 +00002622 if (!Sym)
2623 return;
Anna Zaksf5788c72012-08-14 00:36:15 +00002624 const RefVal* T = getRefBinding(state, Sym);
John McCall31168b02011-06-15 23:02:42 +00002625 if (!T)
2626 return;
2627
John McCall31168b02011-06-15 23:02:42 +00002628 RefVal::Kind hasErr = (RefVal::Kind) 0;
Jordy Rosec49ec532011-09-02 05:55:19 +00002629 state = updateSymbol(state, Sym, *T, AE, hasErr, C);
John McCall31168b02011-06-15 23:02:42 +00002630
2631 if (hasErr) {
Jordy Rosebf77e512011-08-23 20:27:16 +00002632 // FIXME: If we get an error during a bridge cast, should we report it?
2633 // Should we assert that there is no error?
John McCall31168b02011-06-15 23:02:42 +00002634 return;
2635 }
2636
Anna Zaksda4c8d62011-10-26 21:06:34 +00002637 C.addTransition(state);
John McCall31168b02011-06-15 23:02:42 +00002638}
2639
Ted Kremenek415287d2012-03-06 20:06:12 +00002640void RetainCountChecker::processObjCLiterals(CheckerContext &C,
2641 const Expr *Ex) const {
2642 ProgramStateRef state = C.getState();
2643 const ExplodedNode *pred = C.getPredecessor();
2644 for (Stmt::const_child_iterator it = Ex->child_begin(), et = Ex->child_end() ;
2645 it != et ; ++it) {
2646 const Stmt *child = *it;
2647 SVal V = state->getSVal(child, pred->getLocationContext());
2648 if (SymbolRef sym = V.getAsSymbol())
Anna Zaksf5788c72012-08-14 00:36:15 +00002649 if (const RefVal* T = getRefBinding(state, sym)) {
Ted Kremenek415287d2012-03-06 20:06:12 +00002650 RefVal::Kind hasErr = (RefVal::Kind) 0;
2651 state = updateSymbol(state, sym, *T, MayEscape, hasErr, C);
2652 if (hasErr) {
2653 processNonLeakError(state, child->getSourceRange(), hasErr, sym, C);
2654 return;
2655 }
2656 }
2657 }
2658
2659 // Return the object as autoreleased.
2660 // RetEffect RE = RetEffect::MakeNotOwned(RetEffect::ObjC);
2661 if (SymbolRef sym =
2662 state->getSVal(Ex, pred->getLocationContext()).getAsSymbol()) {
2663 QualType ResultTy = Ex->getType();
Anna Zaksf5788c72012-08-14 00:36:15 +00002664 state = setRefBinding(state, sym,
2665 RefVal::makeNotOwned(RetEffect::ObjC, ResultTy));
Ted Kremenek415287d2012-03-06 20:06:12 +00002666 }
2667
2668 C.addTransition(state);
2669}
2670
2671void RetainCountChecker::checkPostStmt(const ObjCArrayLiteral *AL,
2672 CheckerContext &C) const {
2673 // Apply the 'MayEscape' to all values.
2674 processObjCLiterals(C, AL);
2675}
2676
2677void RetainCountChecker::checkPostStmt(const ObjCDictionaryLiteral *DL,
2678 CheckerContext &C) const {
2679 // Apply the 'MayEscape' to all keys and values.
2680 processObjCLiterals(C, DL);
2681}
2682
Jordy Rose6393f822012-05-12 05:10:43 +00002683void RetainCountChecker::checkPostStmt(const ObjCBoxedExpr *Ex,
2684 CheckerContext &C) const {
2685 const ExplodedNode *Pred = C.getPredecessor();
2686 const LocationContext *LCtx = Pred->getLocationContext();
2687 ProgramStateRef State = Pred->getState();
2688
2689 if (SymbolRef Sym = State->getSVal(Ex, LCtx).getAsSymbol()) {
2690 QualType ResultTy = Ex->getType();
Anna Zaksf5788c72012-08-14 00:36:15 +00002691 State = setRefBinding(State, Sym,
2692 RefVal::makeNotOwned(RetEffect::ObjC, ResultTy));
Jordy Rose6393f822012-05-12 05:10:43 +00002693 }
2694
2695 C.addTransition(State);
2696}
2697
Jordan Rose682b3162012-07-02 19:28:21 +00002698void RetainCountChecker::checkPostCall(const CallEvent &Call,
2699 CheckerContext &C) const {
Jordan Rose682b3162012-07-02 19:28:21 +00002700 RetainSummaryManager &Summaries = getSummaryManager(C);
2701 const RetainSummary *Summ = Summaries.getSummary(Call, C.getState());
Anna Zaks25612732012-08-29 23:23:43 +00002702
2703 if (C.wasInlined) {
2704 processSummaryOfInlined(*Summ, Call, C);
2705 return;
2706 }
Jordan Rose682b3162012-07-02 19:28:21 +00002707 checkSummary(*Summ, Call, C);
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002708}
2709
Jordy Rose75e680e2011-09-02 06:44:22 +00002710/// GetReturnType - Used to get the return type of a message expression or
2711/// function call with the intention of affixing that type to a tracked symbol.
Sylvestre Ledru830885c2012-07-23 08:59:39 +00002712/// While the return type can be queried directly from RetEx, when
Jordy Rose75e680e2011-09-02 06:44:22 +00002713/// invoking class methods we augment to the return type to be that of
2714/// a pointer to the class (as opposed it just being id).
2715// FIXME: We may be able to do this with related result types instead.
2716// This function is probably overestimating.
2717static QualType GetReturnType(const Expr *RetE, ASTContext &Ctx) {
2718 QualType RetTy = RetE->getType();
2719 // If RetE is not a message expression just return its type.
2720 // If RetE is a message expression, return its types if it is something
2721 /// more specific than id.
2722 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RetE))
2723 if (const ObjCObjectPointerType *PT = RetTy->getAs<ObjCObjectPointerType>())
2724 if (PT->isObjCQualifiedIdType() || PT->isObjCIdType() ||
2725 PT->isObjCClassType()) {
2726 // At this point we know the return type of the message expression is
2727 // id, id<...>, or Class. If we have an ObjCInterfaceDecl, we know this
2728 // is a call to a class method whose type we can resolve. In such
2729 // cases, promote the return type to XXX* (where XXX is the class).
2730 const ObjCInterfaceDecl *D = ME->getReceiverInterface();
2731 return !D ? RetTy :
2732 Ctx.getObjCObjectPointerType(Ctx.getObjCInterfaceType(D));
2733 }
2734
2735 return RetTy;
2736}
2737
Anna Zaks25612732012-08-29 23:23:43 +00002738// We don't always get the exact modeling of the function with regards to the
2739// retain count checker even when the function is inlined. For example, we need
2740// to stop tracking the symbols which were marked with StopTrackingHard.
2741void RetainCountChecker::processSummaryOfInlined(const RetainSummary &Summ,
2742 const CallEvent &CallOrMsg,
2743 CheckerContext &C) const {
2744 ProgramStateRef state = C.getState();
2745
2746 // Evaluate the effect of the arguments.
2747 for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
2748 if (Summ.getArg(idx) == StopTrackingHard) {
2749 SVal V = CallOrMsg.getArgSVal(idx);
2750 if (SymbolRef Sym = V.getAsLocSymbol()) {
2751 state = removeRefBinding(state, Sym);
2752 }
2753 }
2754 }
2755
2756 // Evaluate the effect on the message receiver.
2757 const ObjCMethodCall *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg);
2758 if (MsgInvocation) {
2759 if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
2760 if (Summ.getReceiverEffect() == StopTrackingHard) {
2761 state = removeRefBinding(state, Sym);
2762 }
2763 }
2764 }
2765
2766 // Consult the summary for the return value.
2767 RetEffect RE = Summ.getRetEffect();
2768 if (RE.getKind() == RetEffect::NoRetHard) {
Jordan Rose829c3832012-11-02 23:49:29 +00002769 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
Anna Zaks25612732012-08-29 23:23:43 +00002770 if (Sym)
2771 state = removeRefBinding(state, Sym);
2772 }
2773
2774 C.addTransition(state);
2775}
2776
Jordy Rose75e680e2011-09-02 06:44:22 +00002777void RetainCountChecker::checkSummary(const RetainSummary &Summ,
Jordan Roseeec15392012-07-02 19:27:43 +00002778 const CallEvent &CallOrMsg,
Jordy Rose75e680e2011-09-02 06:44:22 +00002779 CheckerContext &C) const {
Ted Kremenek49b1e382012-01-26 21:29:00 +00002780 ProgramStateRef state = C.getState();
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002781
2782 // Evaluate the effect of the arguments.
2783 RefVal::Kind hasErr = (RefVal::Kind) 0;
2784 SourceRange ErrorRange;
2785 SymbolRef ErrorSym = 0;
2786
2787 for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
Jordy Rose1fad6632011-08-27 22:51:26 +00002788 SVal V = CallOrMsg.getArgSVal(idx);
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002789
2790 if (SymbolRef Sym = V.getAsLocSymbol()) {
Anna Zaksf5788c72012-08-14 00:36:15 +00002791 if (const RefVal *T = getRefBinding(state, Sym)) {
Jordy Rosec49ec532011-09-02 05:55:19 +00002792 state = updateSymbol(state, Sym, *T, Summ.getArg(idx), hasErr, C);
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002793 if (hasErr) {
2794 ErrorRange = CallOrMsg.getArgSourceRange(idx);
2795 ErrorSym = Sym;
2796 break;
2797 }
2798 }
2799 }
2800 }
2801
2802 // Evaluate the effect on the message receiver.
2803 bool ReceiverIsTracked = false;
Jordan Roseeec15392012-07-02 19:27:43 +00002804 if (!hasErr) {
Jordan Rose6bad4902012-07-02 19:27:56 +00002805 const ObjCMethodCall *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg);
Jordan Roseeec15392012-07-02 19:27:43 +00002806 if (MsgInvocation) {
2807 if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
Anna Zaksf5788c72012-08-14 00:36:15 +00002808 if (const RefVal *T = getRefBinding(state, Sym)) {
Jordan Roseeec15392012-07-02 19:27:43 +00002809 ReceiverIsTracked = true;
2810 state = updateSymbol(state, Sym, *T, Summ.getReceiverEffect(),
Anna Zaks25612732012-08-29 23:23:43 +00002811 hasErr, C);
Jordan Roseeec15392012-07-02 19:27:43 +00002812 if (hasErr) {
Jordan Rose627b0462012-07-18 21:59:51 +00002813 ErrorRange = MsgInvocation->getOriginExpr()->getReceiverRange();
Jordan Roseeec15392012-07-02 19:27:43 +00002814 ErrorSym = Sym;
2815 }
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002816 }
2817 }
2818 }
2819 }
2820
2821 // Process any errors.
2822 if (hasErr) {
2823 processNonLeakError(state, ErrorRange, hasErr, ErrorSym, C);
2824 return;
2825 }
2826
2827 // Consult the summary for the return value.
2828 RetEffect RE = Summ.getRetEffect();
2829
2830 if (RE.getKind() == RetEffect::OwnedWhenTrackedReceiver) {
Jordy Rose8b289a22011-08-25 00:10:37 +00002831 if (ReceiverIsTracked)
Jordy Rosec49ec532011-09-02 05:55:19 +00002832 RE = getSummaryManager(C).getObjAllocRetEffect();
Jordy Rose8b289a22011-08-25 00:10:37 +00002833 else
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002834 RE = RetEffect::MakeNoRet();
2835 }
2836
2837 switch (RE.getKind()) {
2838 default:
David Blaikie8a40f702012-01-17 06:56:22 +00002839 llvm_unreachable("Unhandled RetEffect.");
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002840
2841 case RetEffect::NoRet:
Anna Zaks25612732012-08-29 23:23:43 +00002842 case RetEffect::NoRetHard:
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002843 // No work necessary.
2844 break;
2845
2846 case RetEffect::OwnedAllocatedSymbol:
2847 case RetEffect::OwnedSymbol: {
Jordan Rose829c3832012-11-02 23:49:29 +00002848 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002849 if (!Sym)
2850 break;
2851
Jordan Roseeec15392012-07-02 19:27:43 +00002852 // Use the result type from the CallEvent as it automatically adjusts
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002853 // for methods/functions that return references.
Jordan Roseeec15392012-07-02 19:27:43 +00002854 QualType ResultTy = CallOrMsg.getResultType();
Anna Zaksf5788c72012-08-14 00:36:15 +00002855 state = setRefBinding(state, Sym, RefVal::makeOwned(RE.getObjKind(),
2856 ResultTy));
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002857
2858 // FIXME: Add a flag to the checker where allocations are assumed to
Anna Zaks21487f72012-08-14 15:39:13 +00002859 // *not* fail.
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002860 break;
2861 }
2862
2863 case RetEffect::GCNotOwnedSymbol:
2864 case RetEffect::ARCNotOwnedSymbol:
2865 case RetEffect::NotOwnedSymbol: {
2866 const Expr *Ex = CallOrMsg.getOriginExpr();
Jordan Rose829c3832012-11-02 23:49:29 +00002867 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002868 if (!Sym)
2869 break;
Ted Kremenekbe400842012-10-12 22:56:45 +00002870 assert(Ex);
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002871 // Use GetReturnType in order to give [NSFoo alloc] the type NSFoo *.
2872 QualType ResultTy = GetReturnType(Ex, C.getASTContext());
Anna Zaksf5788c72012-08-14 00:36:15 +00002873 state = setRefBinding(state, Sym, RefVal::makeNotOwned(RE.getObjKind(),
2874 ResultTy));
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002875 break;
2876 }
2877 }
2878
2879 // This check is actually necessary; otherwise the statement builder thinks
2880 // we've hit a previously-found path.
2881 // Normally addTransition takes care of this, but we want the node pointer.
2882 ExplodedNode *NewNode;
2883 if (state == C.getState()) {
2884 NewNode = C.getPredecessor();
2885 } else {
Anna Zaksda4c8d62011-10-26 21:06:34 +00002886 NewNode = C.addTransition(state);
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002887 }
2888
Jordy Rose5df640d2011-08-24 18:56:32 +00002889 // Annotate the node with summary we used.
2890 if (NewNode) {
2891 // FIXME: This is ugly. See checkEndAnalysis for why it's necessary.
2892 if (ShouldResetSummaryLog) {
2893 SummaryLog.clear();
2894 ShouldResetSummaryLog = false;
2895 }
Jordy Rose20d4e682011-08-23 20:55:48 +00002896 SummaryLog[NewNode] = &Summ;
Jordy Rose5df640d2011-08-24 18:56:32 +00002897 }
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002898}
2899
Jordy Rosebf77e512011-08-23 20:27:16 +00002900
Ted Kremenek49b1e382012-01-26 21:29:00 +00002901ProgramStateRef
2902RetainCountChecker::updateSymbol(ProgramStateRef state, SymbolRef sym,
Jordy Rose75e680e2011-09-02 06:44:22 +00002903 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
2904 CheckerContext &C) const {
Jordy Rosebf77e512011-08-23 20:27:16 +00002905 // In GC mode [... release] and [... retain] do nothing.
Jordy Rose75e680e2011-09-02 06:44:22 +00002906 // In ARC mode they shouldn't exist at all, but we just ignore them.
Jordy Rosec49ec532011-09-02 05:55:19 +00002907 bool IgnoreRetainMsg = C.isObjCGCEnabled();
2908 if (!IgnoreRetainMsg)
David Blaikiebbafb8a2012-03-11 07:00:24 +00002909 IgnoreRetainMsg = (bool)C.getASTContext().getLangOpts().ObjCAutoRefCount;
Jordy Rosec49ec532011-09-02 05:55:19 +00002910
Jordy Rosebf77e512011-08-23 20:27:16 +00002911 switch (E) {
Jordan Roseeec15392012-07-02 19:27:43 +00002912 default:
2913 break;
2914 case IncRefMsg:
2915 E = IgnoreRetainMsg ? DoNothing : IncRef;
2916 break;
2917 case DecRefMsg:
2918 E = IgnoreRetainMsg ? DoNothing : DecRef;
2919 break;
Anna Zaks25612732012-08-29 23:23:43 +00002920 case DecRefMsgAndStopTrackingHard:
2921 E = IgnoreRetainMsg ? StopTracking : DecRefAndStopTrackingHard;
Jordan Roseeec15392012-07-02 19:27:43 +00002922 break;
2923 case MakeCollectable:
2924 E = C.isObjCGCEnabled() ? DecRef : DoNothing;
2925 break;
Jordy Rosebf77e512011-08-23 20:27:16 +00002926 }
2927
2928 // Handle all use-after-releases.
Jordy Rosec49ec532011-09-02 05:55:19 +00002929 if (!C.isObjCGCEnabled() && V.getKind() == RefVal::Released) {
Jordy Rosebf77e512011-08-23 20:27:16 +00002930 V = V ^ RefVal::ErrorUseAfterRelease;
2931 hasErr = V.getKind();
Anna Zaksf5788c72012-08-14 00:36:15 +00002932 return setRefBinding(state, sym, V);
Jordy Rosebf77e512011-08-23 20:27:16 +00002933 }
2934
2935 switch (E) {
2936 case DecRefMsg:
2937 case IncRefMsg:
2938 case MakeCollectable:
Anna Zaks25612732012-08-29 23:23:43 +00002939 case DecRefMsgAndStopTrackingHard:
Jordy Rosebf77e512011-08-23 20:27:16 +00002940 llvm_unreachable("DecRefMsg/IncRefMsg/MakeCollectable already converted");
Jordy Rosebf77e512011-08-23 20:27:16 +00002941
2942 case Dealloc:
2943 // Any use of -dealloc in GC is *bad*.
Jordy Rosec49ec532011-09-02 05:55:19 +00002944 if (C.isObjCGCEnabled()) {
Jordy Rosebf77e512011-08-23 20:27:16 +00002945 V = V ^ RefVal::ErrorDeallocGC;
2946 hasErr = V.getKind();
2947 break;
2948 }
2949
2950 switch (V.getKind()) {
2951 default:
2952 llvm_unreachable("Invalid RefVal state for an explicit dealloc.");
Jordy Rosebf77e512011-08-23 20:27:16 +00002953 case RefVal::Owned:
2954 // The object immediately transitions to the released state.
2955 V = V ^ RefVal::Released;
2956 V.clearCounts();
Anna Zaksf5788c72012-08-14 00:36:15 +00002957 return setRefBinding(state, sym, V);
Jordy Rosebf77e512011-08-23 20:27:16 +00002958 case RefVal::NotOwned:
2959 V = V ^ RefVal::ErrorDeallocNotOwned;
2960 hasErr = V.getKind();
2961 break;
2962 }
2963 break;
2964
Jordy Rosebf77e512011-08-23 20:27:16 +00002965 case MayEscape:
2966 if (V.getKind() == RefVal::Owned) {
2967 V = V ^ RefVal::NotOwned;
2968 break;
2969 }
2970
2971 // Fall-through.
2972
Jordy Rosebf77e512011-08-23 20:27:16 +00002973 case DoNothing:
2974 return state;
2975
2976 case Autorelease:
Jordy Rosec49ec532011-09-02 05:55:19 +00002977 if (C.isObjCGCEnabled())
Jordy Rosebf77e512011-08-23 20:27:16 +00002978 return state;
Jordy Rosebf77e512011-08-23 20:27:16 +00002979 // Update the autorelease counts.
Jordy Rosebf77e512011-08-23 20:27:16 +00002980 V = V.autorelease();
2981 break;
2982
2983 case StopTracking:
Anna Zaks25612732012-08-29 23:23:43 +00002984 case StopTrackingHard:
Anna Zaksf5788c72012-08-14 00:36:15 +00002985 return removeRefBinding(state, sym);
Jordy Rosebf77e512011-08-23 20:27:16 +00002986
2987 case IncRef:
2988 switch (V.getKind()) {
2989 default:
2990 llvm_unreachable("Invalid RefVal state for a retain.");
Jordy Rosebf77e512011-08-23 20:27:16 +00002991 case RefVal::Owned:
2992 case RefVal::NotOwned:
2993 V = V + 1;
2994 break;
2995 case RefVal::Released:
2996 // Non-GC cases are handled above.
Jordy Rosec49ec532011-09-02 05:55:19 +00002997 assert(C.isObjCGCEnabled());
Jordy Rosebf77e512011-08-23 20:27:16 +00002998 V = (V ^ RefVal::Owned) + 1;
2999 break;
3000 }
3001 break;
3002
Jordy Rosebf77e512011-08-23 20:27:16 +00003003 case DecRef:
Benjamin Kramer1d5d6342013-10-20 11:53:20 +00003004 case DecRefBridgedTransferred:
Anna Zaks25612732012-08-29 23:23:43 +00003005 case DecRefAndStopTrackingHard:
Jordy Rosebf77e512011-08-23 20:27:16 +00003006 switch (V.getKind()) {
3007 default:
3008 // case 'RefVal::Released' handled above.
3009 llvm_unreachable("Invalid RefVal state for a release.");
Jordy Rosebf77e512011-08-23 20:27:16 +00003010
3011 case RefVal::Owned:
3012 assert(V.getCount() > 0);
3013 if (V.getCount() == 1)
Benjamin Kramer1d5d6342013-10-20 11:53:20 +00003014 V = V ^ (E == DecRefBridgedTransferred ? RefVal::NotOwned
3015 : RefVal::Released);
Anna Zaks25612732012-08-29 23:23:43 +00003016 else if (E == DecRefAndStopTrackingHard)
Anna Zaksf5788c72012-08-14 00:36:15 +00003017 return removeRefBinding(state, sym);
Jordan Roseeec15392012-07-02 19:27:43 +00003018
Jordy Rosebf77e512011-08-23 20:27:16 +00003019 V = V - 1;
3020 break;
3021
3022 case RefVal::NotOwned:
Jordan Roseeec15392012-07-02 19:27:43 +00003023 if (V.getCount() > 0) {
Anna Zaks25612732012-08-29 23:23:43 +00003024 if (E == DecRefAndStopTrackingHard)
Anna Zaksf5788c72012-08-14 00:36:15 +00003025 return removeRefBinding(state, sym);
Jordy Rosebf77e512011-08-23 20:27:16 +00003026 V = V - 1;
Jordan Roseeec15392012-07-02 19:27:43 +00003027 } else {
Jordy Rosebf77e512011-08-23 20:27:16 +00003028 V = V ^ RefVal::ErrorReleaseNotOwned;
3029 hasErr = V.getKind();
3030 }
3031 break;
3032
3033 case RefVal::Released:
3034 // Non-GC cases are handled above.
Jordy Rosec49ec532011-09-02 05:55:19 +00003035 assert(C.isObjCGCEnabled());
Jordy Rosebf77e512011-08-23 20:27:16 +00003036 V = V ^ RefVal::ErrorUseAfterRelease;
3037 hasErr = V.getKind();
3038 break;
3039 }
3040 break;
3041 }
Anna Zaksf5788c72012-08-14 00:36:15 +00003042 return setRefBinding(state, sym, V);
Jordy Rosebf77e512011-08-23 20:27:16 +00003043}
3044
Ted Kremenek49b1e382012-01-26 21:29:00 +00003045void RetainCountChecker::processNonLeakError(ProgramStateRef St,
Jordy Rose75e680e2011-09-02 06:44:22 +00003046 SourceRange ErrorRange,
3047 RefVal::Kind ErrorKind,
3048 SymbolRef Sym,
3049 CheckerContext &C) const {
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003050 ExplodedNode *N = C.generateSink(St);
3051 if (!N)
3052 return;
3053
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003054 CFRefBug *BT;
3055 switch (ErrorKind) {
3056 default:
3057 llvm_unreachable("Unhandled error.");
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003058 case RefVal::ErrorUseAfterRelease:
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003059 if (!useAfterRelease)
3060 useAfterRelease.reset(new UseAfterRelease());
3061 BT = &*useAfterRelease;
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003062 break;
3063 case RefVal::ErrorReleaseNotOwned:
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003064 if (!releaseNotOwned)
3065 releaseNotOwned.reset(new BadRelease());
3066 BT = &*releaseNotOwned;
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003067 break;
3068 case RefVal::ErrorDeallocGC:
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003069 if (!deallocGC)
3070 deallocGC.reset(new DeallocGC());
3071 BT = &*deallocGC;
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003072 break;
3073 case RefVal::ErrorDeallocNotOwned:
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003074 if (!deallocNotOwned)
3075 deallocNotOwned.reset(new DeallocNotOwned());
3076 BT = &*deallocNotOwned;
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003077 break;
3078 }
3079
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003080 assert(BT);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003081 CFRefReport *report = new CFRefReport(*BT, C.getASTContext().getLangOpts(),
Jordy Rosec49ec532011-09-02 05:55:19 +00003082 C.isObjCGCEnabled(), SummaryLog,
3083 N, Sym);
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003084 report->addRange(ErrorRange);
Jordan Rosee10d5a72012-11-02 01:53:40 +00003085 C.emitReport(report);
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003086}
3087
Jordy Rose75e680e2011-09-02 06:44:22 +00003088//===----------------------------------------------------------------------===//
3089// Handle the return values of retain-count-related functions.
3090//===----------------------------------------------------------------------===//
3091
3092bool RetainCountChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
Jordy Rose898a1482011-08-21 21:58:18 +00003093 // Get the callee. We're only interested in simple C functions.
Ted Kremenek49b1e382012-01-26 21:29:00 +00003094 ProgramStateRef state = C.getState();
Anna Zaksc6aa5312011-12-01 05:57:37 +00003095 const FunctionDecl *FD = C.getCalleeDecl(CE);
Jordy Rose898a1482011-08-21 21:58:18 +00003096 if (!FD)
3097 return false;
3098
3099 IdentifierInfo *II = FD->getIdentifier();
3100 if (!II)
3101 return false;
3102
3103 // For now, we're only handling the functions that return aliases of their
3104 // arguments: CFRetain and CFMakeCollectable (and their families).
3105 // Eventually we should add other functions we can model entirely,
3106 // such as CFRelease, which don't invalidate their arguments or globals.
3107 if (CE->getNumArgs() != 1)
3108 return false;
3109
3110 // Get the name of the function.
3111 StringRef FName = II->getName();
3112 FName = FName.substr(FName.find_first_not_of('_'));
3113
3114 // See if it's one of the specific functions we know how to eval.
3115 bool canEval = false;
3116
Anna Zaksc6aa5312011-12-01 05:57:37 +00003117 QualType ResultTy = CE->getCallReturnType();
Jordy Rose898a1482011-08-21 21:58:18 +00003118 if (ResultTy->isObjCIdType()) {
3119 // Handle: id NSMakeCollectable(CFTypeRef)
3120 canEval = II->isStr("NSMakeCollectable");
3121 } else if (ResultTy->isPointerType()) {
3122 // Handle: (CF|CG)Retain
Jordan Rose77411322013-10-07 17:16:52 +00003123 // CFAutorelease
Jordy Rose898a1482011-08-21 21:58:18 +00003124 // CFMakeCollectable
3125 // It's okay to be a little sloppy here (CGMakeCollectable doesn't exist).
3126 if (cocoa::isRefType(ResultTy, "CF", FName) ||
3127 cocoa::isRefType(ResultTy, "CG", FName)) {
Jordan Rose77411322013-10-07 17:16:52 +00003128 canEval = isRetain(FD, FName) || isAutorelease(FD, FName) ||
3129 isMakeCollectable(FD, FName);
Jordy Rose898a1482011-08-21 21:58:18 +00003130 }
3131 }
3132
3133 if (!canEval)
3134 return false;
3135
3136 // Bind the return value.
Ted Kremenek632e3b72012-01-06 22:09:28 +00003137 const LocationContext *LCtx = C.getLocationContext();
3138 SVal RetVal = state->getSVal(CE->getArg(0), LCtx);
Jordy Rose898a1482011-08-21 21:58:18 +00003139 if (RetVal.isUnknown()) {
3140 // If the receiver is unknown, conjure a return value.
3141 SValBuilder &SVB = C.getSValBuilder();
Ted Kremenekd94854a2012-08-22 06:26:15 +00003142 RetVal = SVB.conjureSymbolVal(0, CE, LCtx, ResultTy, C.blockCount());
Jordy Rose898a1482011-08-21 21:58:18 +00003143 }
Ted Kremenek632e3b72012-01-06 22:09:28 +00003144 state = state->BindExpr(CE, LCtx, RetVal, false);
Jordy Rose898a1482011-08-21 21:58:18 +00003145
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003146 // FIXME: This should not be necessary, but otherwise the argument seems to be
3147 // considered alive during the next statement.
3148 if (const MemRegion *ArgRegion = RetVal.getAsRegion()) {
3149 // Save the refcount status of the argument.
3150 SymbolRef Sym = RetVal.getAsLocSymbol();
Anna Zaksf5788c72012-08-14 00:36:15 +00003151 const RefVal *Binding = 0;
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003152 if (Sym)
Anna Zaksf5788c72012-08-14 00:36:15 +00003153 Binding = getRefBinding(state, Sym);
Jordy Rose898a1482011-08-21 21:58:18 +00003154
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003155 // Invalidate the argument region.
Anna Zaksdc154152012-12-20 00:38:25 +00003156 state = state->invalidateRegions(ArgRegion, CE, C.blockCount(), LCtx,
Anna Zaks0c34c1a2013-01-16 01:35:54 +00003157 /*CausesPointerEscape*/ false);
Jordy Rose898a1482011-08-21 21:58:18 +00003158
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003159 // Restore the refcount status of the argument.
3160 if (Binding)
Anna Zaksf5788c72012-08-14 00:36:15 +00003161 state = setRefBinding(state, Sym, *Binding);
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003162 }
3163
Anna Zaksda4c8d62011-10-26 21:06:34 +00003164 C.addTransition(state);
Jordy Rose898a1482011-08-21 21:58:18 +00003165 return true;
3166}
3167
Jordy Rose75e680e2011-09-02 06:44:22 +00003168//===----------------------------------------------------------------------===//
3169// Handle return statements.
3170//===----------------------------------------------------------------------===//
Jordy Rose298cc4d2011-08-23 19:43:16 +00003171
Jordy Rose75e680e2011-09-02 06:44:22 +00003172void RetainCountChecker::checkPreStmt(const ReturnStmt *S,
3173 CheckerContext &C) const {
Ted Kremenekef31f372012-02-25 02:09:09 +00003174
3175 // Only adjust the reference count if this is the top-level call frame,
3176 // and not the result of inlining. In the future, we should do
3177 // better checking even for inlined calls, and see if they match
3178 // with their expected semantics (e.g., the method should return a retained
3179 // object, etc.).
Anna Zaks44dc91b2012-11-03 02:54:16 +00003180 if (!C.inTopFrame())
Ted Kremenekef31f372012-02-25 02:09:09 +00003181 return;
3182
Jordy Rose298cc4d2011-08-23 19:43:16 +00003183 const Expr *RetE = S->getRetValue();
3184 if (!RetE)
3185 return;
3186
Ted Kremenek49b1e382012-01-26 21:29:00 +00003187 ProgramStateRef state = C.getState();
Ted Kremenek632e3b72012-01-06 22:09:28 +00003188 SymbolRef Sym =
3189 state->getSValAsScalarOrLoc(RetE, C.getLocationContext()).getAsLocSymbol();
Jordy Rose298cc4d2011-08-23 19:43:16 +00003190 if (!Sym)
3191 return;
3192
3193 // Get the reference count binding (if any).
Anna Zaksf5788c72012-08-14 00:36:15 +00003194 const RefVal *T = getRefBinding(state, Sym);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003195 if (!T)
3196 return;
3197
3198 // Change the reference count.
3199 RefVal X = *T;
3200
3201 switch (X.getKind()) {
3202 case RefVal::Owned: {
3203 unsigned cnt = X.getCount();
3204 assert(cnt > 0);
3205 X.setCount(cnt - 1);
3206 X = X ^ RefVal::ReturnedOwned;
3207 break;
3208 }
3209
3210 case RefVal::NotOwned: {
3211 unsigned cnt = X.getCount();
3212 if (cnt) {
3213 X.setCount(cnt - 1);
3214 X = X ^ RefVal::ReturnedOwned;
3215 }
3216 else {
3217 X = X ^ RefVal::ReturnedNotOwned;
3218 }
3219 break;
3220 }
3221
3222 default:
3223 return;
3224 }
3225
3226 // Update the binding.
Anna Zaksf5788c72012-08-14 00:36:15 +00003227 state = setRefBinding(state, Sym, X);
Anna Zaksda4c8d62011-10-26 21:06:34 +00003228 ExplodedNode *Pred = C.addTransition(state);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003229
3230 // At this point we have updated the state properly.
3231 // Everything after this is merely checking to see if the return value has
3232 // been over- or under-retained.
3233
3234 // Did we cache out?
3235 if (!Pred)
3236 return;
3237
Jordy Rose298cc4d2011-08-23 19:43:16 +00003238 // Update the autorelease counts.
3239 static SimpleProgramPointTag
Jordy Rose75e680e2011-09-02 06:44:22 +00003240 AutoreleaseTag("RetainCountChecker : Autorelease");
Jordan Roseff03c1d2012-12-06 18:58:18 +00003241 state = handleAutoreleaseCounts(state, Pred, &AutoreleaseTag, C, Sym, X);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003242
3243 // Did we cache out?
Jordan Roseff03c1d2012-12-06 18:58:18 +00003244 if (!state)
Jordy Rose298cc4d2011-08-23 19:43:16 +00003245 return;
3246
3247 // Get the updated binding.
Anna Zaksf5788c72012-08-14 00:36:15 +00003248 T = getRefBinding(state, Sym);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003249 assert(T);
3250 X = *T;
3251
3252 // Consult the summary of the enclosing method.
Jordy Rosec49ec532011-09-02 05:55:19 +00003253 RetainSummaryManager &Summaries = getSummaryManager(C);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003254 const Decl *CD = &Pred->getCodeDecl();
Jordan Roseeec15392012-07-02 19:27:43 +00003255 RetEffect RE = RetEffect::MakeNoRet();
Jordy Rose298cc4d2011-08-23 19:43:16 +00003256
Jordan Roseeec15392012-07-02 19:27:43 +00003257 // FIXME: What is the convention for blocks? Is there one?
Jordy Rose298cc4d2011-08-23 19:43:16 +00003258 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CD)) {
Jordy Rose8b289a22011-08-25 00:10:37 +00003259 const RetainSummary *Summ = Summaries.getMethodSummary(MD);
Jordan Roseeec15392012-07-02 19:27:43 +00003260 RE = Summ->getRetEffect();
3261 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) {
3262 if (!isa<CXXMethodDecl>(FD)) {
3263 const RetainSummary *Summ = Summaries.getFunctionSummary(FD);
3264 RE = Summ->getRetEffect();
3265 }
Jordy Rose298cc4d2011-08-23 19:43:16 +00003266 }
3267
Jordan Roseeec15392012-07-02 19:27:43 +00003268 checkReturnWithRetEffect(S, C, Pred, RE, X, Sym, state);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003269}
3270
Jordy Rose75e680e2011-09-02 06:44:22 +00003271void RetainCountChecker::checkReturnWithRetEffect(const ReturnStmt *S,
3272 CheckerContext &C,
3273 ExplodedNode *Pred,
3274 RetEffect RE, RefVal X,
3275 SymbolRef Sym,
Ted Kremenek49b1e382012-01-26 21:29:00 +00003276 ProgramStateRef state) const {
Jordy Rose298cc4d2011-08-23 19:43:16 +00003277 // Any leaks or other errors?
3278 if (X.isReturnedOwned() && X.getCount() == 0) {
3279 if (RE.getKind() != RetEffect::NoRet) {
3280 bool hasError = false;
Jordy Rosec49ec532011-09-02 05:55:19 +00003281 if (C.isObjCGCEnabled() && RE.getObjKind() == RetEffect::ObjC) {
Jordy Rose298cc4d2011-08-23 19:43:16 +00003282 // Things are more complicated with garbage collection. If the
3283 // returned object is suppose to be an Objective-C object, we have
3284 // a leak (as the caller expects a GC'ed object) because no
3285 // method should return ownership unless it returns a CF object.
3286 hasError = true;
3287 X = X ^ RefVal::ErrorGCLeakReturned;
3288 }
3289 else if (!RE.isOwned()) {
3290 // Either we are using GC and the returned object is a CF type
3291 // or we aren't using GC. In either case, we expect that the
3292 // enclosing method is expected to return ownership.
3293 hasError = true;
3294 X = X ^ RefVal::ErrorLeakReturned;
3295 }
3296
3297 if (hasError) {
3298 // Generate an error node.
Anna Zaksf5788c72012-08-14 00:36:15 +00003299 state = setRefBinding(state, Sym, X);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003300
3301 static SimpleProgramPointTag
Jordy Rose75e680e2011-09-02 06:44:22 +00003302 ReturnOwnLeakTag("RetainCountChecker : ReturnsOwnLeak");
Anna Zaksda4c8d62011-10-26 21:06:34 +00003303 ExplodedNode *N = C.addTransition(state, Pred, &ReturnOwnLeakTag);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003304 if (N) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003305 const LangOptions &LOpts = C.getASTContext().getLangOpts();
Jordy Rosec49ec532011-09-02 05:55:19 +00003306 bool GCEnabled = C.isObjCGCEnabled();
Jordy Rose298cc4d2011-08-23 19:43:16 +00003307 CFRefReport *report =
Jordy Rosec49ec532011-09-02 05:55:19 +00003308 new CFRefLeakReport(*getLeakAtReturnBug(LOpts, GCEnabled),
3309 LOpts, GCEnabled, SummaryLog,
Ted Kremenek8671acb2013-04-16 21:44:22 +00003310 N, Sym, C, IncludeAllocationLine);
3311
Jordan Rosee10d5a72012-11-02 01:53:40 +00003312 C.emitReport(report);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003313 }
3314 }
3315 }
3316 } else if (X.isReturnedNotOwned()) {
3317 if (RE.isOwned()) {
3318 // Trying to return a not owned object to a caller expecting an
3319 // owned object.
Anna Zaksf5788c72012-08-14 00:36:15 +00003320 state = setRefBinding(state, Sym, X ^ RefVal::ErrorReturnedNotOwned);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003321
3322 static SimpleProgramPointTag
Jordy Rose75e680e2011-09-02 06:44:22 +00003323 ReturnNotOwnedTag("RetainCountChecker : ReturnNotOwnedForOwned");
Anna Zaksda4c8d62011-10-26 21:06:34 +00003324 ExplodedNode *N = C.addTransition(state, Pred, &ReturnNotOwnedTag);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003325 if (N) {
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003326 if (!returnNotOwnedForOwned)
3327 returnNotOwnedForOwned.reset(new ReturnedNotOwnedForOwned());
3328
Jordy Rose298cc4d2011-08-23 19:43:16 +00003329 CFRefReport *report =
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003330 new CFRefReport(*returnNotOwnedForOwned,
David Blaikiebbafb8a2012-03-11 07:00:24 +00003331 C.getASTContext().getLangOpts(),
Jordy Rosec49ec532011-09-02 05:55:19 +00003332 C.isObjCGCEnabled(), SummaryLog, N, Sym);
Jordan Rosee10d5a72012-11-02 01:53:40 +00003333 C.emitReport(report);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003334 }
3335 }
3336 }
3337}
3338
Jordy Rose6763e382011-08-23 20:07:14 +00003339//===----------------------------------------------------------------------===//
Jordy Rose75e680e2011-09-02 06:44:22 +00003340// Check various ways a symbol can be invalidated.
3341//===----------------------------------------------------------------------===//
3342
Anna Zaks3e0f4152011-10-06 00:43:15 +00003343void RetainCountChecker::checkBind(SVal loc, SVal val, const Stmt *S,
Jordy Rose75e680e2011-09-02 06:44:22 +00003344 CheckerContext &C) const {
3345 // Are we storing to something that causes the value to "escape"?
3346 bool escapes = true;
3347
3348 // A value escapes in three possible cases (this may change):
3349 //
3350 // (1) we are binding to something that is not a memory region.
3351 // (2) we are binding to a memregion that does not have stack storage
3352 // (3) we are binding to a memregion with stack storage that the store
3353 // does not understand.
Ted Kremenek49b1e382012-01-26 21:29:00 +00003354 ProgramStateRef state = C.getState();
Jordy Rose75e680e2011-09-02 06:44:22 +00003355
David Blaikie05785d12013-02-20 22:23:23 +00003356 if (Optional<loc::MemRegionVal> regionLoc = loc.getAs<loc::MemRegionVal>()) {
Jordy Rose75e680e2011-09-02 06:44:22 +00003357 escapes = !regionLoc->getRegion()->hasStackStorage();
3358
3359 if (!escapes) {
3360 // To test (3), generate a new state with the binding added. If it is
3361 // the same state, then it escapes (since the store cannot represent
3362 // the binding).
Anna Zaks70de7722012-05-02 00:15:40 +00003363 // Do this only if we know that the store is not supposed to generate the
3364 // same state.
3365 SVal StoredVal = state->getSVal(regionLoc->getRegion());
3366 if (StoredVal != val)
3367 escapes = (state == (state->bindLoc(*regionLoc, val)));
Jordy Rose75e680e2011-09-02 06:44:22 +00003368 }
Ted Kremeneke9a5bcf2012-03-27 01:12:45 +00003369 if (!escapes) {
3370 // Case 4: We do not currently model what happens when a symbol is
3371 // assigned to a struct field, so be conservative here and let the symbol
3372 // go. TODO: This could definitely be improved upon.
3373 escapes = !isa<VarRegion>(regionLoc->getRegion());
3374 }
Jordy Rose75e680e2011-09-02 06:44:22 +00003375 }
3376
Anna Zaksfb050942013-09-17 00:53:28 +00003377 // If we are storing the value into an auto function scope variable annotated
3378 // with (__attribute__((cleanup))), stop tracking the value to avoid leak
3379 // false positives.
3380 if (const VarRegion *LVR = dyn_cast_or_null<VarRegion>(loc.getAsRegion())) {
3381 const VarDecl *VD = LVR->getDecl();
Aaron Ballman9ead1242013-12-19 02:39:40 +00003382 if (VD->hasAttr<CleanupAttr>()) {
Anna Zaksfb050942013-09-17 00:53:28 +00003383 escapes = true;
3384 }
3385 }
3386
Jordy Rose75e680e2011-09-02 06:44:22 +00003387 // If our store can represent the binding and we aren't storing to something
3388 // that doesn't have local storage then just return and have the simulation
3389 // state continue as is.
3390 if (!escapes)
3391 return;
3392
3393 // Otherwise, find all symbols referenced by 'val' that we are tracking
3394 // and stop tracking them.
3395 state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
Anna Zaksda4c8d62011-10-26 21:06:34 +00003396 C.addTransition(state);
Jordy Rose75e680e2011-09-02 06:44:22 +00003397}
3398
Ted Kremenek49b1e382012-01-26 21:29:00 +00003399ProgramStateRef RetainCountChecker::evalAssume(ProgramStateRef state,
Jordy Rose75e680e2011-09-02 06:44:22 +00003400 SVal Cond,
3401 bool Assumption) const {
3402
3403 // FIXME: We may add to the interface of evalAssume the list of symbols
3404 // whose assumptions have changed. For now we just iterate through the
3405 // bindings and check if any of the tracked symbols are NULL. This isn't
3406 // too bad since the number of symbols we will track in practice are
3407 // probably small and evalAssume is only called at branches and a few
3408 // other places.
Jordan Rose0c153cb2012-11-02 01:54:06 +00003409 RefBindingsTy B = state->get<RefBindings>();
Jordy Rose75e680e2011-09-02 06:44:22 +00003410
3411 if (B.isEmpty())
3412 return state;
3413
3414 bool changed = false;
Jordan Rose0c153cb2012-11-02 01:54:06 +00003415 RefBindingsTy::Factory &RefBFactory = state->get_context<RefBindings>();
Jordy Rose75e680e2011-09-02 06:44:22 +00003416
Jordan Rose0c153cb2012-11-02 01:54:06 +00003417 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Ted Kremenek244e1d72012-09-07 22:31:01 +00003418 // Check if the symbol is null stop tracking the symbol.
Jordan Rose14fe9f32012-11-01 00:18:27 +00003419 ConstraintManager &CMgr = state->getConstraintManager();
3420 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
3421 if (AllocFailed.isConstrainedTrue()) {
Jordy Rose75e680e2011-09-02 06:44:22 +00003422 changed = true;
3423 B = RefBFactory.remove(B, I.getKey());
3424 }
3425 }
3426
3427 if (changed)
3428 state = state->set<RefBindings>(B);
3429
3430 return state;
3431}
3432
Ted Kremenek49b1e382012-01-26 21:29:00 +00003433ProgramStateRef
3434RetainCountChecker::checkRegionChanges(ProgramStateRef state,
Anna Zaksdc154152012-12-20 00:38:25 +00003435 const InvalidatedSymbols *invalidated,
Jordy Rose75e680e2011-09-02 06:44:22 +00003436 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks3d348342012-02-14 21:55:24 +00003437 ArrayRef<const MemRegion *> Regions,
Jordan Rose742920c2012-07-02 19:27:35 +00003438 const CallEvent *Call) const {
Jordy Rose75e680e2011-09-02 06:44:22 +00003439 if (!invalidated)
3440 return state;
3441
3442 llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
3443 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
3444 E = ExplicitRegions.end(); I != E; ++I) {
3445 if (const SymbolicRegion *SR = (*I)->StripCasts()->getAs<SymbolicRegion>())
3446 WhitelistedSymbols.insert(SR->getSymbol());
3447 }
3448
Anna Zaksdc154152012-12-20 00:38:25 +00003449 for (InvalidatedSymbols::const_iterator I=invalidated->begin(),
Jordy Rose75e680e2011-09-02 06:44:22 +00003450 E = invalidated->end(); I!=E; ++I) {
3451 SymbolRef sym = *I;
3452 if (WhitelistedSymbols.count(sym))
3453 continue;
3454 // Remove any existing reference-count binding.
Anna Zaksf5788c72012-08-14 00:36:15 +00003455 state = removeRefBinding(state, sym);
Jordy Rose75e680e2011-09-02 06:44:22 +00003456 }
3457 return state;
3458}
3459
3460//===----------------------------------------------------------------------===//
Jordy Rose6763e382011-08-23 20:07:14 +00003461// Handle dead symbols and end-of-path.
3462//===----------------------------------------------------------------------===//
3463
Jordan Roseff03c1d2012-12-06 18:58:18 +00003464ProgramStateRef
3465RetainCountChecker::handleAutoreleaseCounts(ProgramStateRef state,
Anna Zaks58734db2011-10-25 19:57:11 +00003466 ExplodedNode *Pred,
Jordan Rose9f61f8a2012-08-18 00:30:16 +00003467 const ProgramPointTag *Tag,
Anna Zaks58734db2011-10-25 19:57:11 +00003468 CheckerContext &Ctx,
Jordy Rose75e680e2011-09-02 06:44:22 +00003469 SymbolRef Sym, RefVal V) const {
Jordy Rose6763e382011-08-23 20:07:14 +00003470 unsigned ACnt = V.getAutoreleaseCount();
3471
3472 // No autorelease counts? Nothing to be done.
3473 if (!ACnt)
Jordan Roseff03c1d2012-12-06 18:58:18 +00003474 return state;
Jordy Rose6763e382011-08-23 20:07:14 +00003475
Anna Zaks58734db2011-10-25 19:57:11 +00003476 assert(!Ctx.isObjCGCEnabled() && "Autorelease counts in GC mode?");
Jordy Rose6763e382011-08-23 20:07:14 +00003477 unsigned Cnt = V.getCount();
3478
3479 // FIXME: Handle sending 'autorelease' to already released object.
3480
3481 if (V.getKind() == RefVal::ReturnedOwned)
3482 ++Cnt;
3483
3484 if (ACnt <= Cnt) {
3485 if (ACnt == Cnt) {
3486 V.clearCounts();
3487 if (V.getKind() == RefVal::ReturnedOwned)
3488 V = V ^ RefVal::ReturnedNotOwned;
3489 else
3490 V = V ^ RefVal::NotOwned;
3491 } else {
Anna Zaksa8bcc652013-01-31 22:36:17 +00003492 V.setCount(V.getCount() - ACnt);
Jordy Rose6763e382011-08-23 20:07:14 +00003493 V.setAutoreleaseCount(0);
3494 }
Jordan Roseff03c1d2012-12-06 18:58:18 +00003495 return setRefBinding(state, Sym, V);
Jordy Rose6763e382011-08-23 20:07:14 +00003496 }
3497
3498 // Woah! More autorelease counts then retain counts left.
3499 // Emit hard error.
3500 V = V ^ RefVal::ErrorOverAutorelease;
Anna Zaksf5788c72012-08-14 00:36:15 +00003501 state = setRefBinding(state, Sym, V);
Jordy Rose6763e382011-08-23 20:07:14 +00003502
Jordan Rose4b4613c2012-08-20 18:43:42 +00003503 ExplodedNode *N = Ctx.generateSink(state, Pred, Tag);
Jordan Rose9f61f8a2012-08-18 00:30:16 +00003504 if (N) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003505 SmallString<128> sbuf;
Jordy Rose6763e382011-08-23 20:07:14 +00003506 llvm::raw_svector_ostream os(sbuf);
Jordan Rose7467f062013-04-23 01:42:25 +00003507 os << "Object was autoreleased ";
Jordy Rose6763e382011-08-23 20:07:14 +00003508 if (V.getAutoreleaseCount() > 1)
Jordan Rose7467f062013-04-23 01:42:25 +00003509 os << V.getAutoreleaseCount() << " times but the object ";
3510 else
3511 os << "but ";
3512 os << "has a +" << V.getCount() << " retain count";
Jordy Rose6763e382011-08-23 20:07:14 +00003513
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003514 if (!overAutorelease)
3515 overAutorelease.reset(new OverAutorelease());
3516
David Blaikiebbafb8a2012-03-11 07:00:24 +00003517 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
Jordy Rose6763e382011-08-23 20:07:14 +00003518 CFRefReport *report =
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003519 new CFRefReport(*overAutorelease, LOpts, /* GCEnabled = */ false,
3520 SummaryLog, N, Sym, os.str());
Jordan Rosee10d5a72012-11-02 01:53:40 +00003521 Ctx.emitReport(report);
Jordy Rose6763e382011-08-23 20:07:14 +00003522 }
3523
Jordan Roseff03c1d2012-12-06 18:58:18 +00003524 return 0;
Jordy Rose6763e382011-08-23 20:07:14 +00003525}
Jordy Rose78612762011-08-23 19:01:07 +00003526
Ted Kremenek49b1e382012-01-26 21:29:00 +00003527ProgramStateRef
3528RetainCountChecker::handleSymbolDeath(ProgramStateRef state,
Jordy Rose75e680e2011-09-02 06:44:22 +00003529 SymbolRef sid, RefVal V,
Jordy Rose78612762011-08-23 19:01:07 +00003530 SmallVectorImpl<SymbolRef> &Leaked) const {
Jordy Rose03a8f9e2011-08-24 04:48:19 +00003531 bool hasLeak = false;
Jordy Rose78612762011-08-23 19:01:07 +00003532 if (V.isOwned())
3533 hasLeak = true;
3534 else if (V.isNotOwned() || V.isReturnedOwned())
3535 hasLeak = (V.getCount() > 0);
3536
3537 if (!hasLeak)
Anna Zaksf5788c72012-08-14 00:36:15 +00003538 return removeRefBinding(state, sid);
Jordy Rose78612762011-08-23 19:01:07 +00003539
3540 Leaked.push_back(sid);
Anna Zaksf5788c72012-08-14 00:36:15 +00003541 return setRefBinding(state, sid, V ^ RefVal::ErrorLeak);
Jordy Rose78612762011-08-23 19:01:07 +00003542}
3543
3544ExplodedNode *
Ted Kremenek49b1e382012-01-26 21:29:00 +00003545RetainCountChecker::processLeaks(ProgramStateRef state,
Jordy Rose75e680e2011-09-02 06:44:22 +00003546 SmallVectorImpl<SymbolRef> &Leaked,
Anna Zaks58734db2011-10-25 19:57:11 +00003547 CheckerContext &Ctx,
3548 ExplodedNode *Pred) const {
Jordy Rose78612762011-08-23 19:01:07 +00003549 // Generate an intermediate node representing the leak point.
Jordan Rose9f61f8a2012-08-18 00:30:16 +00003550 ExplodedNode *N = Ctx.addTransition(state, Pred);
Jordy Rose78612762011-08-23 19:01:07 +00003551
3552 if (N) {
3553 for (SmallVectorImpl<SymbolRef>::iterator
3554 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3555
David Blaikiebbafb8a2012-03-11 07:00:24 +00003556 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
Anna Zaks58734db2011-10-25 19:57:11 +00003557 bool GCEnabled = Ctx.isObjCGCEnabled();
Jordy Rosec49ec532011-09-02 05:55:19 +00003558 CFRefBug *BT = Pred ? getLeakWithinFunctionBug(LOpts, GCEnabled)
3559 : getLeakAtReturnBug(LOpts, GCEnabled);
Jordy Rose78612762011-08-23 19:01:07 +00003560 assert(BT && "BugType not initialized.");
Jordy Rose184bd142011-08-24 22:39:09 +00003561
Jordy Rosec49ec532011-09-02 05:55:19 +00003562 CFRefLeakReport *report = new CFRefLeakReport(*BT, LOpts, GCEnabled,
Ted Kremenek8671acb2013-04-16 21:44:22 +00003563 SummaryLog, N, *I, Ctx,
3564 IncludeAllocationLine);
Jordan Rosee10d5a72012-11-02 01:53:40 +00003565 Ctx.emitReport(report);
Jordy Rose78612762011-08-23 19:01:07 +00003566 }
3567 }
3568
3569 return N;
3570}
3571
Anna Zaks3fdcc0b2013-01-03 00:25:29 +00003572void RetainCountChecker::checkEndFunction(CheckerContext &Ctx) const {
Ted Kremenek49b1e382012-01-26 21:29:00 +00003573 ProgramStateRef state = Ctx.getState();
Jordan Rose0c153cb2012-11-02 01:54:06 +00003574 RefBindingsTy B = state->get<RefBindings>();
Anna Zaks3eae3342011-10-25 19:56:48 +00003575 ExplodedNode *Pred = Ctx.getPredecessor();
Jordy Rose78612762011-08-23 19:01:07 +00003576
Jordan Rose7699e4a2013-08-01 22:16:36 +00003577 // Don't process anything within synthesized bodies.
3578 const LocationContext *LCtx = Pred->getLocationContext();
3579 if (LCtx->getAnalysisDeclContext()->isBodyAutosynthesized()) {
3580 assert(LCtx->getParent());
3581 return;
3582 }
3583
Jordan Rose0c153cb2012-11-02 01:54:06 +00003584 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Jordan Roseff03c1d2012-12-06 18:58:18 +00003585 state = handleAutoreleaseCounts(state, Pred, /*Tag=*/0, Ctx,
3586 I->first, I->second);
Jordy Rose6763e382011-08-23 20:07:14 +00003587 if (!state)
Jordy Rose78612762011-08-23 19:01:07 +00003588 return;
3589 }
3590
Ted Kremeneka2bbac32012-02-07 00:24:33 +00003591 // If the current LocationContext has a parent, don't check for leaks.
3592 // We will do that later.
Anna Zaksf5788c72012-08-14 00:36:15 +00003593 // FIXME: we should instead check for imbalances of the retain/releases,
Ted Kremeneka2bbac32012-02-07 00:24:33 +00003594 // and suggest annotations.
Jordan Rose7699e4a2013-08-01 22:16:36 +00003595 if (LCtx->getParent())
Ted Kremeneka2bbac32012-02-07 00:24:33 +00003596 return;
3597
Jordy Rose78612762011-08-23 19:01:07 +00003598 B = state->get<RefBindings>();
3599 SmallVector<SymbolRef, 10> Leaked;
3600
Jordan Rose0c153cb2012-11-02 01:54:06 +00003601 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I)
Jordy Rose6763e382011-08-23 20:07:14 +00003602 state = handleSymbolDeath(state, I->first, I->second, Leaked);
Jordy Rose78612762011-08-23 19:01:07 +00003603
Jordan Rose9f61f8a2012-08-18 00:30:16 +00003604 processLeaks(state, Leaked, Ctx, Pred);
Jordy Rose78612762011-08-23 19:01:07 +00003605}
3606
3607const ProgramPointTag *
Jordy Rose75e680e2011-09-02 06:44:22 +00003608RetainCountChecker::getDeadSymbolTag(SymbolRef sym) const {
Jordy Rose78612762011-08-23 19:01:07 +00003609 const SimpleProgramPointTag *&tag = DeadSymbolTags[sym];
3610 if (!tag) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003611 SmallString<64> buf;
Jordy Rose78612762011-08-23 19:01:07 +00003612 llvm::raw_svector_ostream out(buf);
Anna Zaks22351652011-12-05 18:58:11 +00003613 out << "RetainCountChecker : Dead Symbol : ";
3614 sym->dumpToStream(out);
Jordy Rose78612762011-08-23 19:01:07 +00003615 tag = new SimpleProgramPointTag(out.str());
3616 }
3617 return tag;
3618}
3619
Jordy Rose75e680e2011-09-02 06:44:22 +00003620void RetainCountChecker::checkDeadSymbols(SymbolReaper &SymReaper,
3621 CheckerContext &C) const {
Jordy Rose78612762011-08-23 19:01:07 +00003622 ExplodedNode *Pred = C.getPredecessor();
3623
Ted Kremenek49b1e382012-01-26 21:29:00 +00003624 ProgramStateRef state = C.getState();
Jordan Rose0c153cb2012-11-02 01:54:06 +00003625 RefBindingsTy B = state->get<RefBindings>();
Jordan Roseff03c1d2012-12-06 18:58:18 +00003626 SmallVector<SymbolRef, 10> Leaked;
Jordy Rose78612762011-08-23 19:01:07 +00003627
3628 // Update counts from autorelease pools
3629 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3630 E = SymReaper.dead_end(); I != E; ++I) {
3631 SymbolRef Sym = *I;
3632 if (const RefVal *T = B.lookup(Sym)){
3633 // Use the symbol as the tag.
3634 // FIXME: This might not be as unique as we would like.
Jordan Rose9f61f8a2012-08-18 00:30:16 +00003635 const ProgramPointTag *Tag = getDeadSymbolTag(Sym);
Jordan Roseff03c1d2012-12-06 18:58:18 +00003636 state = handleAutoreleaseCounts(state, Pred, Tag, C, Sym, *T);
Jordy Rose6763e382011-08-23 20:07:14 +00003637 if (!state)
Jordy Rose78612762011-08-23 19:01:07 +00003638 return;
Jordan Roseff03c1d2012-12-06 18:58:18 +00003639
3640 // Fetch the new reference count from the state, and use it to handle
3641 // this symbol.
3642 state = handleSymbolDeath(state, *I, *getRefBinding(state, Sym), Leaked);
Jordy Rose78612762011-08-23 19:01:07 +00003643 }
3644 }
3645
Jordan Roseff03c1d2012-12-06 18:58:18 +00003646 if (Leaked.empty()) {
3647 C.addTransition(state);
3648 return;
Jordy Rose78612762011-08-23 19:01:07 +00003649 }
3650
Jordan Rose9f61f8a2012-08-18 00:30:16 +00003651 Pred = processLeaks(state, Leaked, C, Pred);
Jordy Rose78612762011-08-23 19:01:07 +00003652
3653 // Did we cache out?
3654 if (!Pred)
3655 return;
3656
3657 // Now generate a new node that nukes the old bindings.
Jordan Roseff03c1d2012-12-06 18:58:18 +00003658 // The only bindings left at this point are the leaked symbols.
Jordan Rose0c153cb2012-11-02 01:54:06 +00003659 RefBindingsTy::Factory &F = state->get_context<RefBindings>();
Jordan Roseff03c1d2012-12-06 18:58:18 +00003660 B = state->get<RefBindings>();
Jordy Rose78612762011-08-23 19:01:07 +00003661
Jordan Roseff03c1d2012-12-06 18:58:18 +00003662 for (SmallVectorImpl<SymbolRef>::iterator I = Leaked.begin(),
3663 E = Leaked.end();
3664 I != E; ++I)
Jordy Rose78612762011-08-23 19:01:07 +00003665 B = F.remove(B, *I);
3666
3667 state = state->set<RefBindings>(B);
Anna Zaksda4c8d62011-10-26 21:06:34 +00003668 C.addTransition(state, Pred);
Jordy Rose78612762011-08-23 19:01:07 +00003669}
3670
Ted Kremenek49b1e382012-01-26 21:29:00 +00003671void RetainCountChecker::printState(raw_ostream &Out, ProgramStateRef State,
Jordy Rose75e680e2011-09-02 06:44:22 +00003672 const char *NL, const char *Sep) const {
Jordy Rose58a20d32011-08-28 19:11:56 +00003673
Jordan Rose0c153cb2012-11-02 01:54:06 +00003674 RefBindingsTy B = State->get<RefBindings>();
Jordy Rose58a20d32011-08-28 19:11:56 +00003675
Ted Kremenekdb70b522013-03-28 18:43:18 +00003676 if (B.isEmpty())
3677 return;
3678
3679 Out << Sep << NL;
Jordy Rose58a20d32011-08-28 19:11:56 +00003680
Jordan Rose0c153cb2012-11-02 01:54:06 +00003681 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Jordy Rose58a20d32011-08-28 19:11:56 +00003682 Out << I->first << " : ";
3683 I->second.print(Out);
3684 Out << NL;
3685 }
Jordy Rose58a20d32011-08-28 19:11:56 +00003686}
3687
3688//===----------------------------------------------------------------------===//
Jordy Rose75e680e2011-09-02 06:44:22 +00003689// Checker registration.
Ted Kremenek819e9b62008-03-11 06:39:11 +00003690//===----------------------------------------------------------------------===//
3691
Jordy Rosec49ec532011-09-02 05:55:19 +00003692void ento::registerRetainCountChecker(CheckerManager &Mgr) {
Ted Kremenek8671acb2013-04-16 21:44:22 +00003693 Mgr.registerChecker<RetainCountChecker>(Mgr.getAnalyzerOptions());
Jordy Rosec49ec532011-09-02 05:55:19 +00003694}
3695
Ted Kremenek71c080f2013-08-14 23:41:49 +00003696//===----------------------------------------------------------------------===//
3697// Implementation of the CallEffects API.
3698//===----------------------------------------------------------------------===//
3699
3700namespace clang { namespace ento { namespace objc_retain {
3701
3702// This is a bit gross, but it allows us to populate CallEffects without
3703// creating a bunch of accessors. This kind is very localized, so the
3704// damage of this macro is limited.
3705#define createCallEffect(D, KIND)\
3706 ASTContext &Ctx = D->getASTContext();\
3707 LangOptions L = Ctx.getLangOpts();\
3708 RetainSummaryManager M(Ctx, L.GCOnly, L.ObjCAutoRefCount);\
3709 const RetainSummary *S = M.get ## KIND ## Summary(D);\
3710 CallEffects CE(S->getRetEffect());\
3711 CE.Receiver = S->getReceiverEffect();\
Ted Kremeneke19529b2013-08-16 23:14:22 +00003712 unsigned N = D->param_size();\
Ted Kremenek71c080f2013-08-14 23:41:49 +00003713 for (unsigned i = 0; i < N; ++i) {\
3714 CE.Args.push_back(S->getArg(i));\
3715 }
3716
3717CallEffects CallEffects::getEffect(const ObjCMethodDecl *MD) {
3718 createCallEffect(MD, Method);
3719 return CE;
3720}
3721
3722CallEffects CallEffects::getEffect(const FunctionDecl *FD) {
3723 createCallEffect(FD, Function);
3724 return CE;
3725}
3726
3727#undef createCallEffect
3728
3729}}}