blob: 0e1104730cdb420e6a1b722c744ae7cb3abc8e21 [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()
Jordan Rose6ad4cb42014-01-07 21:39:41 +0000655 : (usesARC ? RetEffect::MakeNotOwned(RetEffect::ObjC)
John McCall31168b02011-06-15 23:02:42 +0000656 : RetEffect::MakeOwned(RetEffect::ObjC, true))),
657 ObjCInitRetE(gcenabled
658 ? RetEffect::MakeGCNotOwned()
Jordan Rose6ad4cb42014-01-07 21:39:41 +0000659 : (usesARC ? RetEffect::MakeNotOwned(RetEffect::ObjC)
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();
Alp Toker314cc812014-01-25 16:55:45 +0000691 QualType ResultTy = MD->getReturnType();
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.
Jordan Rose2a833ca2014-01-15 17:25:15 +0000863 if (const SimpleFunctionCall *FC = dyn_cast<SimpleFunctionCall>(&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:
Jordan Rose2a833ca2014-01-15 17:25:15 +0000911 Summ = getFunctionSummary(cast<SimpleFunctionCall>(Call).getDecl());
Jordan Roseeec15392012-07-02 19:27:43 +0000912 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.
Alp Toker314cc812014-01-25 16:55:45 +0000973 QualType RetTy = FT->getReturnType();
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);
Alp Toker9cacbab2014-01-20 20:26:09 +00001177 if (!FTP || FTP->getNumParams() != 1)
Ted Kremenek7e904222009-01-12 21:45:02 +00001178 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 }
Alp Toker314cc812014-01-25 16:55:45 +00001255
1256 QualType RetTy = FD->getReturnType();
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 }
Alp Toker314cc812014-01-25 16:55:45 +00001286
1287 QualType RetTy = MD->getReturnType();
Jordan Rose39032472013-04-04 22:31:48 +00001288 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:
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001550 CFRefBug(const CheckerBase *checker, StringRef name)
1551 : BugType(checker, name, categories::MemoryCoreFoundationObjectiveC) {}
1552
Ted Kremenek6bd78702009-04-29 18:50:19 +00001553 public:
Mike Stump11289f42009-09-09 15:08:12 +00001554
Ted Kremenek6bd78702009-04-29 18:50:19 +00001555 // FIXME: Eventually remove.
Jordy Rose7a534982011-08-24 05:47:39 +00001556 virtual const char *getDescription() const = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001557
Ted Kremenek6bd78702009-04-29 18:50:19 +00001558 virtual bool isLeak() const { return false; }
1559 };
Mike Stump11289f42009-09-09 15:08:12 +00001560
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00001561 class UseAfterRelease : public CFRefBug {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001562 public:
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001563 UseAfterRelease(const CheckerBase *checker)
1564 : CFRefBug(checker, "Use-after-release") {}
Mike Stump11289f42009-09-09 15:08:12 +00001565
Craig Topperfb6b25b2014-03-15 04:29:04 +00001566 const char *getDescription() const override {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001567 return "Reference-counted object is used after it is released";
Mike Stump11289f42009-09-09 15:08:12 +00001568 }
Ted Kremenek6bd78702009-04-29 18:50:19 +00001569 };
Mike Stump11289f42009-09-09 15:08:12 +00001570
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00001571 class BadRelease : public CFRefBug {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001572 public:
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001573 BadRelease(const CheckerBase *checker) : CFRefBug(checker, "Bad release") {}
Mike Stump11289f42009-09-09 15:08:12 +00001574
Craig Topperfb6b25b2014-03-15 04:29:04 +00001575 const char *getDescription() const override {
Ted Kremenek5c22e112009-10-01 17:31:50 +00001576 return "Incorrect decrement of the reference count of an object that is "
1577 "not owned at this point by the caller";
Ted Kremenek6bd78702009-04-29 18:50:19 +00001578 }
1579 };
Mike Stump11289f42009-09-09 15:08:12 +00001580
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00001581 class DeallocGC : public CFRefBug {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001582 public:
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001583 DeallocGC(const CheckerBase *checker)
1584 : CFRefBug(checker, "-dealloc called while using garbage collection") {}
Mike Stump11289f42009-09-09 15:08:12 +00001585
Craig Topperfb6b25b2014-03-15 04:29:04 +00001586 const char *getDescription() const override {
Ted Kremenekd35272f2009-05-09 00:10:05 +00001587 return "-dealloc called while using garbage collection";
Ted Kremenek6bd78702009-04-29 18:50:19 +00001588 }
1589 };
Mike Stump11289f42009-09-09 15:08:12 +00001590
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00001591 class DeallocNotOwned : public CFRefBug {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001592 public:
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001593 DeallocNotOwned(const CheckerBase *checker)
1594 : CFRefBug(checker, "-dealloc sent to non-exclusively owned object") {}
Mike Stump11289f42009-09-09 15:08:12 +00001595
Craig Topperfb6b25b2014-03-15 04:29:04 +00001596 const char *getDescription() const override {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001597 return "-dealloc sent to object that may be referenced elsewhere";
1598 }
Mike Stump11289f42009-09-09 15:08:12 +00001599 };
1600
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00001601 class OverAutorelease : public CFRefBug {
Ted Kremenekd35272f2009-05-09 00:10:05 +00001602 public:
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001603 OverAutorelease(const CheckerBase *checker)
1604 : CFRefBug(checker, "Object autoreleased too many times") {}
Mike Stump11289f42009-09-09 15:08:12 +00001605
Craig Topperfb6b25b2014-03-15 04:29:04 +00001606 const char *getDescription() const override {
Jordan Rose7467f062013-04-23 01:42:25 +00001607 return "Object autoreleased too many times";
Ted Kremenekd35272f2009-05-09 00:10:05 +00001608 }
1609 };
Mike Stump11289f42009-09-09 15:08:12 +00001610
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00001611 class ReturnedNotOwnedForOwned : public CFRefBug {
Ted Kremenekdee56e32009-05-10 06:25:57 +00001612 public:
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001613 ReturnedNotOwnedForOwned(const CheckerBase *checker)
1614 : CFRefBug(checker, "Method should return an owned object") {}
Mike Stump11289f42009-09-09 15:08:12 +00001615
Craig Topperfb6b25b2014-03-15 04:29:04 +00001616 const char *getDescription() const override {
Jordy Rose43426f82011-07-15 22:17:54 +00001617 return "Object with a +0 retain count returned to caller where a +1 "
Ted Kremenekdee56e32009-05-10 06:25:57 +00001618 "(owning) retain count is expected";
1619 }
1620 };
Mike Stump11289f42009-09-09 15:08:12 +00001621
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00001622 class Leak : public CFRefBug {
Benjamin Kramerd1d76b22012-06-06 17:32:50 +00001623 public:
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001624 Leak(const CheckerBase *checker, StringRef name) : CFRefBug(checker, name) {
Jordy Rose15484da2011-08-25 01:14:38 +00001625 // Leaks should not be reported if they are post-dominated by a sink.
1626 setSuppressOnSink(true);
1627 }
Mike Stump11289f42009-09-09 15:08:12 +00001628
Craig Topperfb6b25b2014-03-15 04:29:04 +00001629 const char *getDescription() const override { return ""; }
Mike Stump11289f42009-09-09 15:08:12 +00001630
Craig Topperfb6b25b2014-03-15 04:29:04 +00001631 bool isLeak() const override { return true; }
Ted Kremenek6bd78702009-04-29 18:50:19 +00001632 };
Mike Stump11289f42009-09-09 15:08:12 +00001633
Ted Kremenek6bd78702009-04-29 18:50:19 +00001634 //===---------===//
1635 // Bug Reports. //
1636 //===---------===//
Mike Stump11289f42009-09-09 15:08:12 +00001637
Jordy Rosef78877e2012-03-24 02:45:35 +00001638 class CFRefReportVisitor : public BugReporterVisitorImpl<CFRefReportVisitor> {
Anna Zaks88255cc2011-08-20 01:27:22 +00001639 protected:
Anna Zaks071a89c2011-08-19 23:21:56 +00001640 SymbolRef Sym;
Jordy Rose20d4e682011-08-23 20:55:48 +00001641 const SummaryLogTy &SummaryLog;
Jordy Rose7a534982011-08-24 05:47:39 +00001642 bool GCEnabled;
Anna Zaks88255cc2011-08-20 01:27:22 +00001643
Anna Zaks071a89c2011-08-19 23:21:56 +00001644 public:
Jordy Rose7a534982011-08-24 05:47:39 +00001645 CFRefReportVisitor(SymbolRef sym, bool gcEnabled, const SummaryLogTy &log)
1646 : Sym(sym), SummaryLog(log), GCEnabled(gcEnabled) {}
Anna Zaks071a89c2011-08-19 23:21:56 +00001647
Craig Topperfb6b25b2014-03-15 04:29:04 +00001648 void Profile(llvm::FoldingSetNodeID &ID) const override {
Anna Zaks071a89c2011-08-19 23:21:56 +00001649 static int x = 0;
1650 ID.AddPointer(&x);
1651 ID.AddPointer(Sym);
1652 }
1653
Craig Topperfb6b25b2014-03-15 04:29:04 +00001654 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
1655 const ExplodedNode *PrevN,
1656 BugReporterContext &BRC,
1657 BugReport &BR) override;
Anna Zaks88255cc2011-08-20 01:27:22 +00001658
Craig Topperfb6b25b2014-03-15 04:29:04 +00001659 PathDiagnosticPiece *getEndPath(BugReporterContext &BRC,
1660 const ExplodedNode *N,
1661 BugReport &BR) override;
Anna Zaks88255cc2011-08-20 01:27:22 +00001662 };
1663
1664 class CFRefLeakReportVisitor : public CFRefReportVisitor {
1665 public:
Jordy Rose7a534982011-08-24 05:47:39 +00001666 CFRefLeakReportVisitor(SymbolRef sym, bool GCEnabled,
Jordy Rose20d4e682011-08-23 20:55:48 +00001667 const SummaryLogTy &log)
Jordy Rose7a534982011-08-24 05:47:39 +00001668 : CFRefReportVisitor(sym, GCEnabled, log) {}
Anna Zaks88255cc2011-08-20 01:27:22 +00001669
1670 PathDiagnosticPiece *getEndPath(BugReporterContext &BRC,
1671 const ExplodedNode *N,
Craig Topperfb6b25b2014-03-15 04:29:04 +00001672 BugReport &BR) override;
Jordy Rosef78877e2012-03-24 02:45:35 +00001673
Craig Topperfb6b25b2014-03-15 04:29:04 +00001674 BugReporterVisitor *clone() const override {
Jordy Rosef78877e2012-03-24 02:45:35 +00001675 // The curiously-recurring template pattern only works for one level of
1676 // subclassing. Rather than make a new template base for
1677 // CFRefReportVisitor, we simply override clone() to do the right thing.
1678 // This could be trouble someday if BugReporterVisitorImpl is ever
1679 // used for something else besides a convenient implementation of clone().
1680 return new CFRefLeakReportVisitor(*this);
1681 }
Anna Zaks071a89c2011-08-19 23:21:56 +00001682 };
1683
Anna Zaks3a6bdf82011-08-17 23:00:25 +00001684 class CFRefReport : public BugReport {
Jordy Rose184bd142011-08-24 22:39:09 +00001685 void addGCModeDescription(const LangOptions &LOpts, bool GCEnabled);
Jordy Rose7a534982011-08-24 05:47:39 +00001686
Ted Kremenek6bd78702009-04-29 18:50:19 +00001687 public:
Jordy Rose184bd142011-08-24 22:39:09 +00001688 CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1689 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1690 bool registerVisitor = true)
Anna Zaks752de142011-08-22 18:54:07 +00001691 : BugReport(D, D.getDescription(), n) {
Anna Zaks88255cc2011-08-20 01:27:22 +00001692 if (registerVisitor)
Jordy Rose184bd142011-08-24 22:39:09 +00001693 addVisitor(new CFRefReportVisitor(sym, GCEnabled, Log));
1694 addGCModeDescription(LOpts, GCEnabled);
Anna Zaks071a89c2011-08-19 23:21:56 +00001695 }
Ted Kremenek3978f792009-05-10 05:11:21 +00001696
Jordy Rose184bd142011-08-24 22:39:09 +00001697 CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1698 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1699 StringRef endText)
Anna Zaks752de142011-08-22 18:54:07 +00001700 : BugReport(D, D.getDescription(), endText, n) {
Jordy Rose184bd142011-08-24 22:39:09 +00001701 addVisitor(new CFRefReportVisitor(sym, GCEnabled, Log));
1702 addGCModeDescription(LOpts, GCEnabled);
Anna Zaks071a89c2011-08-19 23:21:56 +00001703 }
Mike Stump11289f42009-09-09 15:08:12 +00001704
Craig Topperfb6b25b2014-03-15 04:29:04 +00001705 std::pair<ranges_iterator, ranges_iterator> getRanges() override {
Anna Zaks752de142011-08-22 18:54:07 +00001706 const CFRefBug& BugTy = static_cast<CFRefBug&>(getBugType());
1707 if (!BugTy.isLeak())
Anna Zaks3a6bdf82011-08-17 23:00:25 +00001708 return BugReport::getRanges();
Ted Kremenek6bd78702009-04-29 18:50:19 +00001709 else
Argyrios Kyrtzidisd22d8ff2010-12-04 01:12:15 +00001710 return std::make_pair(ranges_iterator(), ranges_iterator());
Ted Kremenek6bd78702009-04-29 18:50:19 +00001711 }
Ted Kremenek6bd78702009-04-29 18:50:19 +00001712 };
Ted Kremenek3978f792009-05-10 05:11:21 +00001713
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00001714 class CFRefLeakReport : public CFRefReport {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001715 const MemRegion* AllocBinding;
1716 public:
Jordy Rose184bd142011-08-24 22:39:09 +00001717 CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1718 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
Ted Kremenek8671acb2013-04-16 21:44:22 +00001719 CheckerContext &Ctx,
1720 bool IncludeAllocationLine);
Mike Stump11289f42009-09-09 15:08:12 +00001721
Craig Topperfb6b25b2014-03-15 04:29:04 +00001722 PathDiagnosticLocation getLocation(const SourceManager &SM) const override {
Anna Zaksc29bed32011-09-20 21:38:35 +00001723 assert(Location.isValid());
1724 return Location;
1725 }
Mike Stump11289f42009-09-09 15:08:12 +00001726 };
Ted Kremenek6bd78702009-04-29 18:50:19 +00001727} // end anonymous namespace
1728
Jordy Rose184bd142011-08-24 22:39:09 +00001729void CFRefReport::addGCModeDescription(const LangOptions &LOpts,
1730 bool GCEnabled) {
Jordy Rose9ff02992011-08-24 20:38:42 +00001731 const char *GCModeDescription = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001732
Douglas Gregor79a91412011-09-13 17:21:33 +00001733 switch (LOpts.getGC()) {
Anna Zaks76c3fb62011-08-22 20:31:28 +00001734 case LangOptions::GCOnly:
Jordy Rose184bd142011-08-24 22:39:09 +00001735 assert(GCEnabled);
Jordy Rose7a534982011-08-24 05:47:39 +00001736 GCModeDescription = "Code is compiled to only use garbage collection";
1737 break;
Mike Stump11289f42009-09-09 15:08:12 +00001738
Anna Zaks76c3fb62011-08-22 20:31:28 +00001739 case LangOptions::NonGC:
Jordy Rose184bd142011-08-24 22:39:09 +00001740 assert(!GCEnabled);
Jordy Rose7a534982011-08-24 05:47:39 +00001741 GCModeDescription = "Code is compiled to use reference counts";
1742 break;
Mike Stump11289f42009-09-09 15:08:12 +00001743
Anna Zaks76c3fb62011-08-22 20:31:28 +00001744 case LangOptions::HybridGC:
Jordy Rose184bd142011-08-24 22:39:09 +00001745 if (GCEnabled) {
Jordy Rose7a534982011-08-24 05:47:39 +00001746 GCModeDescription = "Code is compiled to use either garbage collection "
1747 "(GC) or reference counts (non-GC). The bug occurs "
1748 "with GC enabled";
1749 break;
1750 } else {
1751 GCModeDescription = "Code is compiled to use either garbage collection "
1752 "(GC) or reference counts (non-GC). The bug occurs "
1753 "in non-GC mode";
1754 break;
Anna Zaks76c3fb62011-08-22 20:31:28 +00001755 }
Ted Kremenek6bd78702009-04-29 18:50:19 +00001756 }
Jordy Rose7a534982011-08-24 05:47:39 +00001757
Jordy Rose9ff02992011-08-24 20:38:42 +00001758 assert(GCModeDescription && "invalid/unknown GC mode");
Jordy Rose7a534982011-08-24 05:47:39 +00001759 addExtraText(GCModeDescription);
Ted Kremenek6bd78702009-04-29 18:50:19 +00001760}
1761
Jordy Rose6393f822012-05-12 05:10:43 +00001762static bool isNumericLiteralExpression(const Expr *E) {
1763 // FIXME: This set of cases was copied from SemaExprObjC.
1764 return isa<IntegerLiteral>(E) ||
1765 isa<CharacterLiteral>(E) ||
1766 isa<FloatingLiteral>(E) ||
1767 isa<ObjCBoolLiteralExpr>(E) ||
1768 isa<CXXBoolLiteralExpr>(E);
1769}
1770
Anna Zaks071a89c2011-08-19 23:21:56 +00001771PathDiagnosticPiece *CFRefReportVisitor::VisitNode(const ExplodedNode *N,
1772 const ExplodedNode *PrevN,
1773 BugReporterContext &BRC,
1774 BugReport &BR) {
Jordan Rose681cce92012-07-10 22:07:42 +00001775 // FIXME: We will eventually need to handle non-statement-based events
1776 // (__attribute__((cleanup))).
David Blaikie87396b92013-02-21 22:23:56 +00001777 if (!N->getLocation().getAs<StmtPoint>())
Ted Kremenek051a03d2009-05-13 07:12:33 +00001778 return NULL;
Mike Stump11289f42009-09-09 15:08:12 +00001779
Ted Kremenekbb8d5462009-05-06 21:39:49 +00001780 // Check if the type state has changed.
Ted Kremenek49b1e382012-01-26 21:29:00 +00001781 ProgramStateRef PrevSt = PrevN->getState();
1782 ProgramStateRef CurrSt = N->getState();
Ted Kremenek632e3b72012-01-06 22:09:28 +00001783 const LocationContext *LCtx = N->getLocationContext();
Mike Stump11289f42009-09-09 15:08:12 +00001784
Anna Zaksf5788c72012-08-14 00:36:15 +00001785 const RefVal* CurrT = getRefBinding(CurrSt, Sym);
Ted Kremenek6bd78702009-04-29 18:50:19 +00001786 if (!CurrT) return NULL;
Mike Stump11289f42009-09-09 15:08:12 +00001787
Ted Kremenekd93c6e32009-06-18 01:23:53 +00001788 const RefVal &CurrV = *CurrT;
Anna Zaksf5788c72012-08-14 00:36:15 +00001789 const RefVal *PrevT = getRefBinding(PrevSt, Sym);
Mike Stump11289f42009-09-09 15:08:12 +00001790
Ted Kremenek6bd78702009-04-29 18:50:19 +00001791 // Create a string buffer to constain all the useful things we want
1792 // to tell the user.
1793 std::string sbuf;
1794 llvm::raw_string_ostream os(sbuf);
Mike Stump11289f42009-09-09 15:08:12 +00001795
Ted Kremenek6bd78702009-04-29 18:50:19 +00001796 // This is the allocation site since the previous node had no bindings
1797 // for this symbol.
1798 if (!PrevT) {
David Blaikie87396b92013-02-21 22:23:56 +00001799 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
Mike Stump11289f42009-09-09 15:08:12 +00001800
Ted Kremenek415287d2012-03-06 20:06:12 +00001801 if (isa<ObjCArrayLiteral>(S)) {
1802 os << "NSArray literal is an object with a +0 retain count";
Mike Stump11289f42009-09-09 15:08:12 +00001803 }
Ted Kremenek415287d2012-03-06 20:06:12 +00001804 else if (isa<ObjCDictionaryLiteral>(S)) {
1805 os << "NSDictionary literal is an object with a +0 retain count";
Ted Kremenek6bd78702009-04-29 18:50:19 +00001806 }
Jordy Rose6393f822012-05-12 05:10:43 +00001807 else if (const ObjCBoxedExpr *BL = dyn_cast<ObjCBoxedExpr>(S)) {
1808 if (isNumericLiteralExpression(BL->getSubExpr()))
1809 os << "NSNumber literal is an object with a +0 retain count";
1810 else {
1811 const ObjCInterfaceDecl *BoxClass = 0;
1812 if (const ObjCMethodDecl *Method = BL->getBoxingMethod())
1813 BoxClass = Method->getClassInterface();
1814
1815 // We should always be able to find the boxing class interface,
1816 // but consider this future-proofing.
1817 if (BoxClass)
1818 os << *BoxClass << " b";
1819 else
1820 os << "B";
1821
1822 os << "oxed expression produces an object with a +0 retain count";
1823 }
1824 }
Ted Kremenek415287d2012-03-06 20:06:12 +00001825 else {
1826 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
1827 // Get the name of the callee (if it is available).
1828 SVal X = CurrSt->getSValAsScalarOrLoc(CE->getCallee(), LCtx);
1829 if (const FunctionDecl *FD = X.getAsFunctionDecl())
1830 os << "Call to function '" << *FD << '\'';
1831 else
1832 os << "function call";
Ted Kremenek6bd78702009-04-29 18:50:19 +00001833 }
Ted Kremenek415287d2012-03-06 20:06:12 +00001834 else {
Jordan Rose627b0462012-07-18 21:59:51 +00001835 assert(isa<ObjCMessageExpr>(S));
Jordan Rosefcd016e2012-07-30 20:22:09 +00001836 CallEventManager &Mgr = CurrSt->getStateManager().getCallEventManager();
1837 CallEventRef<ObjCMethodCall> Call
1838 = Mgr.getObjCMethodCall(cast<ObjCMessageExpr>(S), CurrSt, LCtx);
1839
1840 switch (Call->getMessageKind()) {
Jordan Rose627b0462012-07-18 21:59:51 +00001841 case OCM_Message:
1842 os << "Method";
1843 break;
1844 case OCM_PropertyAccess:
1845 os << "Property";
1846 break;
1847 case OCM_Subscript:
1848 os << "Subscript";
1849 break;
1850 }
Ted Kremenek415287d2012-03-06 20:06:12 +00001851 }
1852
1853 if (CurrV.getObjKind() == RetEffect::CF) {
1854 os << " returns a Core Foundation object with a ";
1855 }
1856 else {
1857 assert (CurrV.getObjKind() == RetEffect::ObjC);
1858 os << " returns an Objective-C object with a ";
1859 }
1860
1861 if (CurrV.isOwned()) {
1862 os << "+1 retain count";
1863
1864 if (GCEnabled) {
1865 assert(CurrV.getObjKind() == RetEffect::CF);
1866 os << ". "
1867 "Core Foundation objects are not automatically garbage collected.";
1868 }
1869 }
1870 else {
1871 assert (CurrV.isNotOwned());
1872 os << "+0 retain count";
1873 }
Ted Kremenek6bd78702009-04-29 18:50:19 +00001874 }
Mike Stump11289f42009-09-09 15:08:12 +00001875
Anna Zaks3a769bd2011-09-15 01:08:34 +00001876 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
1877 N->getLocationContext());
Ted Kremenek6bd78702009-04-29 18:50:19 +00001878 return new PathDiagnosticEventPiece(Pos, os.str());
1879 }
Mike Stump11289f42009-09-09 15:08:12 +00001880
Ted Kremenek6bd78702009-04-29 18:50:19 +00001881 // Gather up the effects that were performed on the object at this
1882 // program point
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001883 SmallVector<ArgEffect, 2> AEffects;
Mike Stump11289f42009-09-09 15:08:12 +00001884
Jordy Rose20d4e682011-08-23 20:55:48 +00001885 const ExplodedNode *OrigNode = BRC.getNodeResolver().getOriginalNode(N);
1886 if (const RetainSummary *Summ = SummaryLog.lookup(OrigNode)) {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001887 // We only have summaries attached to nodes after evaluating CallExpr and
1888 // ObjCMessageExprs.
David Blaikie87396b92013-02-21 22:23:56 +00001889 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
Mike Stump11289f42009-09-09 15:08:12 +00001890
Ted Kremenekbfd28fd2009-07-22 22:35:28 +00001891 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001892 // Iterate through the parameter expressions and see if the symbol
1893 // was ever passed as an argument.
1894 unsigned i = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001895
Ted Kremenekbfd28fd2009-07-22 22:35:28 +00001896 for (CallExpr::const_arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
Ted Kremenek6bd78702009-04-29 18:50:19 +00001897 AI!=AE; ++AI, ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00001898
Ted Kremenek6bd78702009-04-29 18:50:19 +00001899 // Retrieve the value of the argument. Is it the symbol
1900 // we are interested in?
Ted Kremenek632e3b72012-01-06 22:09:28 +00001901 if (CurrSt->getSValAsScalarOrLoc(*AI, LCtx).getAsLocSymbol() != Sym)
Ted Kremenek6bd78702009-04-29 18:50:19 +00001902 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001903
Ted Kremenek6bd78702009-04-29 18:50:19 +00001904 // We have an argument. Get the effect!
1905 AEffects.push_back(Summ->getArg(i));
1906 }
1907 }
Mike Stump11289f42009-09-09 15:08:12 +00001908 else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
Douglas Gregor9a129192010-04-21 00:45:42 +00001909 if (const Expr *receiver = ME->getInstanceReceiver())
Ted Kremenek632e3b72012-01-06 22:09:28 +00001910 if (CurrSt->getSValAsScalarOrLoc(receiver, LCtx)
1911 .getAsLocSymbol() == Sym) {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001912 // The symbol we are tracking is the receiver.
1913 AEffects.push_back(Summ->getReceiverEffect());
1914 }
1915 }
1916 }
Mike Stump11289f42009-09-09 15:08:12 +00001917
Ted Kremenek6bd78702009-04-29 18:50:19 +00001918 do {
1919 // Get the previous type state.
1920 RefVal PrevV = *PrevT;
Mike Stump11289f42009-09-09 15:08:12 +00001921
Ted Kremenek6bd78702009-04-29 18:50:19 +00001922 // Specially handle -dealloc.
Benjamin Kramerab3838a2013-08-16 21:57:14 +00001923 if (!GCEnabled && std::find(AEffects.begin(), AEffects.end(), Dealloc) !=
1924 AEffects.end()) {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001925 // Determine if the object's reference count was pushed to zero.
1926 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
1927 // We may not have transitioned to 'release' if we hit an error.
1928 // This case is handled elsewhere.
1929 if (CurrV.getKind() == RefVal::Released) {
Ted Kremenek3a0516b2009-05-08 20:01:42 +00001930 assert(CurrV.getCombinedCounts() == 0);
Ted Kremenek6bd78702009-04-29 18:50:19 +00001931 os << "Object released by directly sending the '-dealloc' message";
1932 break;
1933 }
1934 }
Mike Stump11289f42009-09-09 15:08:12 +00001935
Ted Kremenek6bd78702009-04-29 18:50:19 +00001936 // Specially handle CFMakeCollectable and friends.
Benjamin Kramerab3838a2013-08-16 21:57:14 +00001937 if (std::find(AEffects.begin(), AEffects.end(), MakeCollectable) !=
1938 AEffects.end()) {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001939 // Get the name of the function.
David Blaikie87396b92013-02-21 22:23:56 +00001940 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
Ted Kremenek632e3b72012-01-06 22:09:28 +00001941 SVal X =
1942 CurrSt->getSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee(), LCtx);
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001943 const FunctionDecl *FD = X.getAsFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001944
Jordy Rose7a534982011-08-24 05:47:39 +00001945 if (GCEnabled) {
Ted Kremenek6bd78702009-04-29 18:50:19 +00001946 // Determine if the object's reference count was pushed to zero.
1947 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
Mike Stump11289f42009-09-09 15:08:12 +00001948
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001949 os << "In GC mode a call to '" << *FD
Ted Kremenek6bd78702009-04-29 18:50:19 +00001950 << "' decrements an object's retain count and registers the "
1951 "object with the garbage collector. ";
Mike Stump11289f42009-09-09 15:08:12 +00001952
Ted Kremenek6bd78702009-04-29 18:50:19 +00001953 if (CurrV.getKind() == RefVal::Released) {
1954 assert(CurrV.getCount() == 0);
1955 os << "Since it now has a 0 retain count the object can be "
1956 "automatically collected by the garbage collector.";
1957 }
1958 else
1959 os << "An object must have a 0 retain count to be garbage collected. "
1960 "After this call its retain count is +" << CurrV.getCount()
1961 << '.';
1962 }
Mike Stump11289f42009-09-09 15:08:12 +00001963 else
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001964 os << "When GC is not enabled a call to '" << *FD
Ted Kremenek6bd78702009-04-29 18:50:19 +00001965 << "' has no effect on its argument.";
Mike Stump11289f42009-09-09 15:08:12 +00001966
Ted Kremenek6bd78702009-04-29 18:50:19 +00001967 // Nothing more to say.
1968 break;
1969 }
Mike Stump11289f42009-09-09 15:08:12 +00001970
1971 // Determine if the typestate has changed.
Ted Kremenek6bd78702009-04-29 18:50:19 +00001972 if (!(PrevV == CurrV))
1973 switch (CurrV.getKind()) {
1974 case RefVal::Owned:
1975 case RefVal::NotOwned:
Mike Stump11289f42009-09-09 15:08:12 +00001976
Ted Kremenek3a0516b2009-05-08 20:01:42 +00001977 if (PrevV.getCount() == CurrV.getCount()) {
1978 // Did an autorelease message get sent?
1979 if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
1980 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001981
Zhongxing Xu08a2ede2009-05-12 10:10:00 +00001982 assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount());
Jordan Rose7467f062013-04-23 01:42:25 +00001983 os << "Object autoreleased";
Ted Kremenek3a0516b2009-05-08 20:01:42 +00001984 break;
1985 }
Mike Stump11289f42009-09-09 15:08:12 +00001986
Ted Kremenek6bd78702009-04-29 18:50:19 +00001987 if (PrevV.getCount() > CurrV.getCount())
1988 os << "Reference count decremented.";
1989 else
1990 os << "Reference count incremented.";
Mike Stump11289f42009-09-09 15:08:12 +00001991
Ted Kremenek6bd78702009-04-29 18:50:19 +00001992 if (unsigned Count = CurrV.getCount())
1993 os << " The object now has a +" << Count << " retain count.";
Mike Stump11289f42009-09-09 15:08:12 +00001994
Ted Kremenek6bd78702009-04-29 18:50:19 +00001995 if (PrevV.getKind() == RefVal::Released) {
Jordy Rose7a534982011-08-24 05:47:39 +00001996 assert(GCEnabled && CurrV.getCount() > 0);
Jordy Rose78373e52012-03-17 05:49:15 +00001997 os << " The object is not eligible for garbage collection until "
1998 "the retain count reaches 0 again.";
Ted Kremenek6bd78702009-04-29 18:50:19 +00001999 }
Mike Stump11289f42009-09-09 15:08:12 +00002000
Ted Kremenek6bd78702009-04-29 18:50:19 +00002001 break;
Mike Stump11289f42009-09-09 15:08:12 +00002002
Ted Kremenek6bd78702009-04-29 18:50:19 +00002003 case RefVal::Released:
2004 os << "Object released.";
2005 break;
Mike Stump11289f42009-09-09 15:08:12 +00002006
Ted Kremenek6bd78702009-04-29 18:50:19 +00002007 case RefVal::ReturnedOwned:
Jordy Rose78373e52012-03-17 05:49:15 +00002008 // Autoreleases can be applied after marking a node ReturnedOwned.
2009 if (CurrV.getAutoreleaseCount())
2010 return NULL;
2011
2012 os << "Object returned to caller as an owning reference (single "
2013 "retain count transferred to caller)";
Ted Kremenek6bd78702009-04-29 18:50:19 +00002014 break;
Mike Stump11289f42009-09-09 15:08:12 +00002015
Ted Kremenek6bd78702009-04-29 18:50:19 +00002016 case RefVal::ReturnedNotOwned:
Ted Kremenekf2301982011-05-26 18:45:44 +00002017 os << "Object returned to caller with a +0 retain count";
Ted Kremenek6bd78702009-04-29 18:50:19 +00002018 break;
Mike Stump11289f42009-09-09 15:08:12 +00002019
Ted Kremenek6bd78702009-04-29 18:50:19 +00002020 default:
2021 return NULL;
2022 }
Mike Stump11289f42009-09-09 15:08:12 +00002023
Ted Kremenek6bd78702009-04-29 18:50:19 +00002024 // Emit any remaining diagnostics for the argument effects (if any).
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002025 for (SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
Ted Kremenek6bd78702009-04-29 18:50:19 +00002026 E=AEffects.end(); I != E; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +00002027
Ted Kremenek6bd78702009-04-29 18:50:19 +00002028 // A bunch of things have alternate behavior under GC.
Jordy Rose7a534982011-08-24 05:47:39 +00002029 if (GCEnabled)
Ted Kremenek6bd78702009-04-29 18:50:19 +00002030 switch (*I) {
2031 default: break;
2032 case Autorelease:
2033 os << "In GC mode an 'autorelease' has no effect.";
2034 continue;
2035 case IncRefMsg:
2036 os << "In GC mode the 'retain' message has no effect.";
2037 continue;
2038 case DecRefMsg:
2039 os << "In GC mode the 'release' message has no effect.";
2040 continue;
2041 }
2042 }
Mike Stump11289f42009-09-09 15:08:12 +00002043 } while (0);
2044
Ted Kremenek6bd78702009-04-29 18:50:19 +00002045 if (os.str().empty())
2046 return 0; // We have nothing to say!
Ted Kremenek051a03d2009-05-13 07:12:33 +00002047
David Blaikie87396b92013-02-21 22:23:56 +00002048 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
Anna Zaks3a769bd2011-09-15 01:08:34 +00002049 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
2050 N->getLocationContext());
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002051 PathDiagnosticPiece *P = new PathDiagnosticEventPiece(Pos, os.str());
Mike Stump11289f42009-09-09 15:08:12 +00002052
Ted Kremenek6bd78702009-04-29 18:50:19 +00002053 // Add the range by scanning the children of the statement for any bindings
2054 // to Sym.
Mike Stump11289f42009-09-09 15:08:12 +00002055 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
Ted Kremenekbfd28fd2009-07-22 22:35:28 +00002056 I!=E; ++I)
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002057 if (const Expr *Exp = dyn_cast_or_null<Expr>(*I))
Ted Kremenek632e3b72012-01-06 22:09:28 +00002058 if (CurrSt->getSValAsScalarOrLoc(Exp, LCtx).getAsLocSymbol() == Sym) {
Ted Kremenek6bd78702009-04-29 18:50:19 +00002059 P->addRange(Exp->getSourceRange());
2060 break;
2061 }
Mike Stump11289f42009-09-09 15:08:12 +00002062
Ted Kremenek6bd78702009-04-29 18:50:19 +00002063 return P;
2064}
2065
Anna Zaks75de3232012-02-28 22:39:22 +00002066// Find the first node in the current function context that referred to the
2067// tracked symbol and the memory location that value was stored to. Note, the
2068// value is only reported if the allocation occurred in the same function as
Anna Zakse51362e2013-04-10 21:42:06 +00002069// the leak. The function can also return a location context, which should be
2070// treated as interesting.
2071struct AllocationInfo {
2072 const ExplodedNode* N;
Anna Zaks3f303be2013-04-10 22:56:30 +00002073 const MemRegion *R;
Anna Zakse51362e2013-04-10 21:42:06 +00002074 const LocationContext *InterestingMethodContext;
Anna Zaks3f303be2013-04-10 22:56:30 +00002075 AllocationInfo(const ExplodedNode *InN,
2076 const MemRegion *InR,
Anna Zakse51362e2013-04-10 21:42:06 +00002077 const LocationContext *InInterestingMethodContext) :
2078 N(InN), R(InR), InterestingMethodContext(InInterestingMethodContext) {}
2079};
2080
2081static AllocationInfo
Ted Kremenek001fd5b2011-08-15 22:09:50 +00002082GetAllocationSite(ProgramStateManager& StateMgr, const ExplodedNode *N,
Ted Kremenek6bd78702009-04-29 18:50:19 +00002083 SymbolRef Sym) {
Anna Zakse51362e2013-04-10 21:42:06 +00002084 const ExplodedNode *AllocationNode = N;
2085 const ExplodedNode *AllocationNodeInCurrentContext = N;
Mike Stump11289f42009-09-09 15:08:12 +00002086 const MemRegion* FirstBinding = 0;
Anna Zaks75de3232012-02-28 22:39:22 +00002087 const LocationContext *LeakContext = N->getLocationContext();
Mike Stump11289f42009-09-09 15:08:12 +00002088
Anna Zakse51362e2013-04-10 21:42:06 +00002089 // The location context of the init method called on the leaked object, if
2090 // available.
2091 const LocationContext *InitMethodContext = 0;
2092
Ted Kremenek6bd78702009-04-29 18:50:19 +00002093 while (N) {
Ted Kremenek49b1e382012-01-26 21:29:00 +00002094 ProgramStateRef St = N->getState();
Anna Zakse51362e2013-04-10 21:42:06 +00002095 const LocationContext *NContext = N->getLocationContext();
Mike Stump11289f42009-09-09 15:08:12 +00002096
Anna Zaksf5788c72012-08-14 00:36:15 +00002097 if (!getRefBinding(St, Sym))
Ted Kremenek6bd78702009-04-29 18:50:19 +00002098 break;
Mike Stump11289f42009-09-09 15:08:12 +00002099
Anna Zaks6797d6e2012-03-21 19:45:01 +00002100 StoreManager::FindUniqueBinding FB(Sym);
Mike Stump11289f42009-09-09 15:08:12 +00002101 StateMgr.iterBindings(St, FB);
Anna Zakse51362e2013-04-10 21:42:06 +00002102
Anna Zaks7c19abe2013-04-10 21:42:02 +00002103 if (FB) {
2104 const MemRegion *R = FB.getRegion();
Anna Zaks07804ef2013-04-10 22:56:33 +00002105 const VarRegion *VR = R->getBaseRegion()->getAs<VarRegion>();
Anna Zaks7c19abe2013-04-10 21:42:02 +00002106 // Do not show local variables belonging to a function other than
2107 // where the error is reported.
2108 if (!VR || VR->getStackFrame() == LeakContext->getCurrentStackFrame())
Anna Zakse51362e2013-04-10 21:42:06 +00002109 FirstBinding = R;
Anna Zaks7c19abe2013-04-10 21:42:02 +00002110 }
Mike Stump11289f42009-09-09 15:08:12 +00002111
Anna Zakse51362e2013-04-10 21:42:06 +00002112 // AllocationNode is the last node in which the symbol was tracked.
2113 AllocationNode = N;
2114
2115 // AllocationNodeInCurrentContext, is the last node in the current context
2116 // in which the symbol was tracked.
2117 if (NContext == LeakContext)
2118 AllocationNodeInCurrentContext = N;
2119
Anna Zaks3f303be2013-04-10 22:56:30 +00002120 // Find the last init that was called on the given symbol and store the
2121 // init method's location context.
2122 if (!InitMethodContext)
2123 if (Optional<CallEnter> CEP = N->getLocation().getAs<CallEnter>()) {
2124 const Stmt *CE = CEP->getCallExpr();
Anna Zaks99394bb2013-04-25 00:41:32 +00002125 if (const ObjCMessageExpr *ME = dyn_cast_or_null<ObjCMessageExpr>(CE)) {
Anna Zaks3f303be2013-04-10 22:56:30 +00002126 const Stmt *RecExpr = ME->getInstanceReceiver();
2127 if (RecExpr) {
2128 SVal RecV = St->getSVal(RecExpr, NContext);
2129 if (ME->getMethodFamily() == OMF_init && RecV.getAsSymbol() == Sym)
2130 InitMethodContext = CEP->getCalleeContext();
2131 }
2132 }
Anna Zakse51362e2013-04-10 21:42:06 +00002133 }
Anna Zaks75de3232012-02-28 22:39:22 +00002134
Mike Stump11289f42009-09-09 15:08:12 +00002135 N = N->pred_empty() ? NULL : *(N->pred_begin());
Ted Kremenek6bd78702009-04-29 18:50:19 +00002136 }
Mike Stump11289f42009-09-09 15:08:12 +00002137
Anna Zakse51362e2013-04-10 21:42:06 +00002138 // If we are reporting a leak of the object that was allocated with alloc,
Anna Zaks3f303be2013-04-10 22:56:30 +00002139 // mark its init method as interesting.
Anna Zakse51362e2013-04-10 21:42:06 +00002140 const LocationContext *InterestingMethodContext = 0;
2141 if (InitMethodContext) {
2142 const ProgramPoint AllocPP = AllocationNode->getLocation();
2143 if (Optional<StmtPoint> SP = AllocPP.getAs<StmtPoint>())
2144 if (const ObjCMessageExpr *ME = SP->getStmtAs<ObjCMessageExpr>())
2145 if (ME->getMethodFamily() == OMF_alloc)
2146 InterestingMethodContext = InitMethodContext;
2147 }
2148
Anna Zaks75de3232012-02-28 22:39:22 +00002149 // If allocation happened in a function different from the leak node context,
2150 // do not report the binding.
Ted Kremenekb045b012012-10-12 22:56:40 +00002151 assert(N && "Could not find allocation node");
Anna Zaks75de3232012-02-28 22:39:22 +00002152 if (N->getLocationContext() != LeakContext) {
2153 FirstBinding = 0;
2154 }
2155
Anna Zakse51362e2013-04-10 21:42:06 +00002156 return AllocationInfo(AllocationNodeInCurrentContext,
2157 FirstBinding,
2158 InterestingMethodContext);
Ted Kremenek6bd78702009-04-29 18:50:19 +00002159}
2160
2161PathDiagnosticPiece*
Anna Zaks88255cc2011-08-20 01:27:22 +00002162CFRefReportVisitor::getEndPath(BugReporterContext &BRC,
2163 const ExplodedNode *EndN,
2164 BugReport &BR) {
Ted Kremenek1e809b42012-03-09 01:13:14 +00002165 BR.markInteresting(Sym);
Anna Zaks88255cc2011-08-20 01:27:22 +00002166 return BugReporterVisitor::getDefaultEndPath(BRC, EndN, BR);
Ted Kremenek6bd78702009-04-29 18:50:19 +00002167}
2168
2169PathDiagnosticPiece*
Anna Zaks88255cc2011-08-20 01:27:22 +00002170CFRefLeakReportVisitor::getEndPath(BugReporterContext &BRC,
2171 const ExplodedNode *EndN,
2172 BugReport &BR) {
Mike Stump11289f42009-09-09 15:08:12 +00002173
Ted Kremenekbb8d5462009-05-06 21:39:49 +00002174 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenek6bd78702009-04-29 18:50:19 +00002175 // assigned to different variables, etc.
Ted Kremenek1e809b42012-03-09 01:13:14 +00002176 BR.markInteresting(Sym);
Mike Stump11289f42009-09-09 15:08:12 +00002177
Ted Kremenek6bd78702009-04-29 18:50:19 +00002178 // We are reporting a leak. Walk up the graph to get to the first node where
2179 // the symbol appeared, and also get the first VarDecl that tracked object
2180 // is stored to.
Anna Zakse51362e2013-04-10 21:42:06 +00002181 AllocationInfo AllocI =
Ted Kremenek8c8fb482009-05-08 23:32:51 +00002182 GetAllocationSite(BRC.getStateManager(), EndN, Sym);
Mike Stump11289f42009-09-09 15:08:12 +00002183
Anna Zakse51362e2013-04-10 21:42:06 +00002184 const MemRegion* FirstBinding = AllocI.R;
2185 BR.markInteresting(AllocI.InterestingMethodContext);
2186
Anna Zaks921f0492011-09-15 18:56:07 +00002187 SourceManager& SM = BRC.getSourceManager();
Mike Stump11289f42009-09-09 15:08:12 +00002188
Ted Kremenek6bd78702009-04-29 18:50:19 +00002189 // Compute an actual location for the leak. Sometimes a leak doesn't
2190 // occur at an actual statement (e.g., transition between blocks; end
2191 // of function) so we need to walk the graph and compute a real location.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002192 const ExplodedNode *LeakN = EndN;
Anna Zaks921f0492011-09-15 18:56:07 +00002193 PathDiagnosticLocation L = PathDiagnosticLocation::createEndOfPath(LeakN, SM);
Mike Stump11289f42009-09-09 15:08:12 +00002194
Ted Kremenek6bd78702009-04-29 18:50:19 +00002195 std::string sbuf;
2196 llvm::raw_string_ostream os(sbuf);
Mike Stump11289f42009-09-09 15:08:12 +00002197
Ted Kremenekf2301982011-05-26 18:45:44 +00002198 os << "Object leaked: ";
Mike Stump11289f42009-09-09 15:08:12 +00002199
Ted Kremenekf2301982011-05-26 18:45:44 +00002200 if (FirstBinding) {
2201 os << "object allocated and stored into '"
2202 << FirstBinding->getString() << '\'';
2203 }
2204 else
2205 os << "allocated object";
Mike Stump11289f42009-09-09 15:08:12 +00002206
Ted Kremenek6bd78702009-04-29 18:50:19 +00002207 // Get the retain count.
Anna Zaksf5788c72012-08-14 00:36:15 +00002208 const RefVal* RV = getRefBinding(EndN->getState(), Sym);
Ted Kremenekb045b012012-10-12 22:56:40 +00002209 assert(RV);
Mike Stump11289f42009-09-09 15:08:12 +00002210
Ted Kremenek6bd78702009-04-29 18:50:19 +00002211 if (RV->getKind() == RefVal::ErrorLeakReturned) {
2212 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
Jordy Rose43426f82011-07-15 22:17:54 +00002213 // objects. Only "copy", "alloc", "retain" and "new" transfer ownership
Ted Kremenek6bd78702009-04-29 18:50:19 +00002214 // to the caller for NS objects.
Ted Kremenek8e2c9b02011-05-25 06:19:45 +00002215 const Decl *D = &EndN->getCodeDecl();
Ted Kremenek2a786952012-09-06 23:03:07 +00002216
2217 os << (isa<ObjCMethodDecl>(D) ? " is returned from a method "
2218 : " is returned from a function ");
2219
Aaron Ballman9ead1242013-12-19 02:39:40 +00002220 if (D->hasAttr<CFReturnsNotRetainedAttr>())
Ted Kremenek2a786952012-09-06 23:03:07 +00002221 os << "that is annotated as CF_RETURNS_NOT_RETAINED";
Aaron Ballman9ead1242013-12-19 02:39:40 +00002222 else if (D->hasAttr<NSReturnsNotRetainedAttr>())
Ted Kremenek2a786952012-09-06 23:03:07 +00002223 os << "that is annotated as NS_RETURNS_NOT_RETAINED";
Ted Kremenek8e2c9b02011-05-25 06:19:45 +00002224 else {
Ted Kremenek2a786952012-09-06 23:03:07 +00002225 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2226 os << "whose name ('" << MD->getSelector().getAsString()
2227 << "') does not start with 'copy', 'mutableCopy', 'alloc' or 'new'."
2228 " This violates the naming convention rules"
2229 " given in the Memory Management Guide for Cocoa";
2230 }
2231 else {
2232 const FunctionDecl *FD = cast<FunctionDecl>(D);
2233 os << "whose name ('" << *FD
2234 << "') does not contain 'Copy' or 'Create'. This violates the naming"
2235 " convention rules given in the Memory Management Guide for Core"
2236 " Foundation";
2237 }
2238 }
Ted Kremenek6bd78702009-04-29 18:50:19 +00002239 }
Ted Kremenekdee56e32009-05-10 06:25:57 +00002240 else if (RV->getKind() == RefVal::ErrorGCLeakReturned) {
David Blaikie3cbec0f2013-02-21 22:37:44 +00002241 const ObjCMethodDecl &MD = cast<ObjCMethodDecl>(EndN->getCodeDecl());
Ted Kremenekdee56e32009-05-10 06:25:57 +00002242 os << " and returned from method '" << MD.getSelector().getAsString()
Ted Kremenek1f8e4342009-05-10 16:52:15 +00002243 << "' is potentially leaked when using garbage collection. Callers "
2244 "of this method do not expect a returned object with a +1 retain "
2245 "count since they expect the object to be managed by the garbage "
2246 "collector";
Ted Kremenekdee56e32009-05-10 06:25:57 +00002247 }
Ted Kremenek6bd78702009-04-29 18:50:19 +00002248 else
Ted Kremenek4f63ac72010-10-15 22:50:23 +00002249 os << " is not referenced later in this execution path and has a retain "
Ted Kremenekf2301982011-05-26 18:45:44 +00002250 "count of +" << RV->getCount();
Mike Stump11289f42009-09-09 15:08:12 +00002251
Ted Kremenek6bd78702009-04-29 18:50:19 +00002252 return new PathDiagnosticEventPiece(L, os.str());
2253}
2254
Jordy Rose184bd142011-08-24 22:39:09 +00002255CFRefLeakReport::CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts,
2256 bool GCEnabled, const SummaryLogTy &Log,
2257 ExplodedNode *n, SymbolRef sym,
Ted Kremenek8671acb2013-04-16 21:44:22 +00002258 CheckerContext &Ctx,
2259 bool IncludeAllocationLine)
2260 : CFRefReport(D, LOpts, GCEnabled, Log, n, sym, false) {
Mike Stump11289f42009-09-09 15:08:12 +00002261
Chris Lattner57540c52011-04-15 05:22:18 +00002262 // Most bug reports are cached at the location where they occurred.
Ted Kremenek6bd78702009-04-29 18:50:19 +00002263 // With leaks, we want to unique them by the location where they were
2264 // allocated, and only report a single path. To do this, we need to find
2265 // the allocation site of a piece of tracked memory, which we do via a
2266 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2267 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2268 // that all ancestor nodes that represent the allocation site have the
2269 // same SourceLocation.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002270 const ExplodedNode *AllocNode = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002271
Anna Zaks58734db2011-10-25 19:57:11 +00002272 const SourceManager& SMgr = Ctx.getSourceManager();
Anna Zaksc29bed32011-09-20 21:38:35 +00002273
Anna Zakse51362e2013-04-10 21:42:06 +00002274 AllocationInfo AllocI =
Anna Zaks58734db2011-10-25 19:57:11 +00002275 GetAllocationSite(Ctx.getStateManager(), getErrorNode(), sym);
Mike Stump11289f42009-09-09 15:08:12 +00002276
Anna Zakse51362e2013-04-10 21:42:06 +00002277 AllocNode = AllocI.N;
2278 AllocBinding = AllocI.R;
2279 markInteresting(AllocI.InterestingMethodContext);
2280
Ted Kremenek6bd78702009-04-29 18:50:19 +00002281 // Get the SourceLocation for the allocation site.
Jordan Rosefbe6dba2012-07-10 22:07:52 +00002282 // FIXME: This will crash the analyzer if an allocation comes from an
2283 // implicit call. (Currently there are no such allocations in Cocoa, though.)
2284 const Stmt *AllocStmt;
Ted Kremenek6bd78702009-04-29 18:50:19 +00002285 ProgramPoint P = AllocNode->getLocation();
David Blaikie87396b92013-02-21 22:23:56 +00002286 if (Optional<CallExitEnd> Exit = P.getAs<CallExitEnd>())
Jordan Rosefbe6dba2012-07-10 22:07:52 +00002287 AllocStmt = Exit->getCalleeContext()->getCallSite();
2288 else
David Blaikie87396b92013-02-21 22:23:56 +00002289 AllocStmt = P.castAs<PostStmt>().getStmt();
Jordan Rosefbe6dba2012-07-10 22:07:52 +00002290 assert(AllocStmt && "All allocations must come from explicit calls");
Anna Zaks40402872013-04-23 23:57:50 +00002291
2292 PathDiagnosticLocation AllocLocation =
2293 PathDiagnosticLocation::createBegin(AllocStmt, SMgr,
2294 AllocNode->getLocationContext());
2295 Location = AllocLocation;
2296
2297 // Set uniqieing info, which will be used for unique the bug reports. The
2298 // leaks should be uniqued on the allocation site.
2299 UniqueingLocation = AllocLocation;
2300 UniqueingDecl = AllocNode->getLocationContext()->getDecl();
2301
Ted Kremenek6bd78702009-04-29 18:50:19 +00002302 // Fill in the description of the bug.
2303 Description.clear();
2304 llvm::raw_string_ostream os(Description);
Ted Kremenekf1e76672009-05-02 19:05:19 +00002305 os << "Potential leak ";
Jordy Rose184bd142011-08-24 22:39:09 +00002306 if (GCEnabled)
Ted Kremenekf1e76672009-05-02 19:05:19 +00002307 os << "(when using garbage collection) ";
Anna Zaks16f38312012-02-28 21:49:08 +00002308 os << "of an object";
Mike Stump11289f42009-09-09 15:08:12 +00002309
Ted Kremenek8671acb2013-04-16 21:44:22 +00002310 if (AllocBinding) {
Anna Zaks16f38312012-02-28 21:49:08 +00002311 os << " stored into '" << AllocBinding->getString() << '\'';
Ted Kremenek8671acb2013-04-16 21:44:22 +00002312 if (IncludeAllocationLine) {
2313 FullSourceLoc SL(AllocStmt->getLocStart(), Ctx.getSourceManager());
2314 os << " (allocated on line " << SL.getSpellingLineNumber() << ")";
2315 }
2316 }
Anna Zaks071a89c2011-08-19 23:21:56 +00002317
Jordy Rose184bd142011-08-24 22:39:09 +00002318 addVisitor(new CFRefLeakReportVisitor(sym, GCEnabled, Log));
Ted Kremenek6bd78702009-04-29 18:50:19 +00002319}
2320
2321//===----------------------------------------------------------------------===//
2322// Main checker logic.
2323//===----------------------------------------------------------------------===//
2324
Ted Kremenek70a87882009-11-25 22:17:44 +00002325namespace {
Jordy Rose75e680e2011-09-02 06:44:22 +00002326class RetainCountChecker
Jordy Rose5df640d2011-08-24 18:56:32 +00002327 : public Checker< check::Bind,
Jordy Rose78612762011-08-23 19:01:07 +00002328 check::DeadSymbols,
Jordy Rose5df640d2011-08-24 18:56:32 +00002329 check::EndAnalysis,
Anna Zaks3fdcc0b2013-01-03 00:25:29 +00002330 check::EndFunction,
Jordy Rose217eb902011-08-17 21:27:39 +00002331 check::PostStmt<BlockExpr>,
John McCall31168b02011-06-15 23:02:42 +00002332 check::PostStmt<CastExpr>,
Ted Kremenek415287d2012-03-06 20:06:12 +00002333 check::PostStmt<ObjCArrayLiteral>,
2334 check::PostStmt<ObjCDictionaryLiteral>,
Jordy Rose6393f822012-05-12 05:10:43 +00002335 check::PostStmt<ObjCBoxedExpr>,
Jordan Rose682b3162012-07-02 19:28:21 +00002336 check::PostCall,
Jordy Rose298cc4d2011-08-23 19:43:16 +00002337 check::PreStmt<ReturnStmt>,
Jordy Rose217eb902011-08-17 21:27:39 +00002338 check::RegionChanges,
Jordy Rose898a1482011-08-21 21:58:18 +00002339 eval::Assume,
2340 eval::Call > {
Ahmed Charlesb8984322014-03-07 20:03:18 +00002341 mutable std::unique_ptr<CFRefBug> useAfterRelease, releaseNotOwned;
2342 mutable std::unique_ptr<CFRefBug> deallocGC, deallocNotOwned;
2343 mutable std::unique_ptr<CFRefBug> overAutorelease, returnNotOwnedForOwned;
2344 mutable std::unique_ptr<CFRefBug> leakWithinFunction, leakAtReturn;
2345 mutable std::unique_ptr<CFRefBug> leakWithinFunctionGC, leakAtReturnGC;
Jordy Rose78612762011-08-23 19:01:07 +00002346
Anton Yartsev6a619222014-02-17 18:25:34 +00002347 typedef llvm::DenseMap<SymbolRef, const CheckerProgramPointTag *> SymbolTagMap;
Jordy Rose78612762011-08-23 19:01:07 +00002348
2349 // This map is only used to ensure proper deletion of any allocated tags.
2350 mutable SymbolTagMap DeadSymbolTags;
2351
Ahmed Charlesb8984322014-03-07 20:03:18 +00002352 mutable std::unique_ptr<RetainSummaryManager> Summaries;
2353 mutable std::unique_ptr<RetainSummaryManager> SummariesGC;
Jordy Rose5df640d2011-08-24 18:56:32 +00002354 mutable SummaryLogTy SummaryLog;
2355 mutable bool ShouldResetSummaryLog;
2356
Ted Kremenek8671acb2013-04-16 21:44:22 +00002357 /// Optional setting to indicate if leak reports should include
2358 /// the allocation line.
2359 mutable bool IncludeAllocationLine;
2360
Jordy Rosea8f99ba2011-08-20 21:17:59 +00002361public:
Ted Kremenek8671acb2013-04-16 21:44:22 +00002362 RetainCountChecker(AnalyzerOptions &AO)
2363 : ShouldResetSummaryLog(false),
2364 IncludeAllocationLine(shouldIncludeAllocationSiteInLeakDiagnostics(AO)) {}
Jordy Rose78612762011-08-23 19:01:07 +00002365
Jordy Rose75e680e2011-09-02 06:44:22 +00002366 virtual ~RetainCountChecker() {
Jordy Rose78612762011-08-23 19:01:07 +00002367 DeleteContainerSeconds(DeadSymbolTags);
2368 }
2369
Jordy Rose5df640d2011-08-24 18:56:32 +00002370 void checkEndAnalysis(ExplodedGraph &G, BugReporter &BR,
2371 ExprEngine &Eng) const {
2372 // FIXME: This is a hack to make sure the summary log gets cleared between
2373 // analyses of different code bodies.
2374 //
2375 // Why is this necessary? Because a checker's lifetime is tied to a
2376 // translation unit, but an ExplodedGraph's lifetime is just a code body.
2377 // Once in a blue moon, a new ExplodedNode will have the same address as an
2378 // old one with an associated summary, and the bug report visitor gets very
2379 // confused. (To make things worse, the summary lifetime is currently also
2380 // tied to a code body, so we get a crash instead of incorrect results.)
Jordy Rose95589f12011-08-24 09:27:24 +00002381 //
2382 // Why is this a bad solution? Because if the lifetime of the ExplodedGraph
2383 // changes, things will start going wrong again. Really the lifetime of this
2384 // log needs to be tied to either the specific nodes in it or the entire
2385 // ExplodedGraph, not to a specific part of the code being analyzed.
2386 //
Jordy Rose5df640d2011-08-24 18:56:32 +00002387 // (Also, having stateful local data means that the same checker can't be
2388 // used from multiple threads, but a lot of checkers have incorrect
2389 // assumptions about that anyway. So that wasn't a priority at the time of
2390 // this fix.)
Jordy Rose95589f12011-08-24 09:27:24 +00002391 //
Jordy Rose5df640d2011-08-24 18:56:32 +00002392 // This happens at the end of analysis, but bug reports are emitted /after/
2393 // this point. So we can't just clear the summary log now. Instead, we mark
2394 // that the next time we access the summary log, it should be cleared.
2395
2396 // If we never reset the summary log during /this/ code body analysis,
2397 // there were no new summaries. There might still have been summaries from
2398 // the /last/ analysis, so clear them out to make sure the bug report
2399 // visitors don't get confused.
2400 if (ShouldResetSummaryLog)
2401 SummaryLog.clear();
2402
2403 ShouldResetSummaryLog = !SummaryLog.empty();
Jordy Rose95589f12011-08-24 09:27:24 +00002404 }
2405
Jordy Rosec49ec532011-09-02 05:55:19 +00002406 CFRefBug *getLeakWithinFunctionBug(const LangOptions &LOpts,
2407 bool GCEnabled) const {
2408 if (GCEnabled) {
Jordy Rose15484da2011-08-25 01:14:38 +00002409 if (!leakWithinFunctionGC)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002410 leakWithinFunctionGC.reset(new Leak(this, "Leak of object when using "
2411 "garbage collection"));
Jordy Rosec49ec532011-09-02 05:55:19 +00002412 return leakWithinFunctionGC.get();
Jordy Rose15484da2011-08-25 01:14:38 +00002413 } else {
2414 if (!leakWithinFunction) {
Douglas Gregor79a91412011-09-13 17:21:33 +00002415 if (LOpts.getGC() == LangOptions::HybridGC) {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002416 leakWithinFunction.reset(new Leak(this,
2417 "Leak of object when not using "
Benjamin Kramerd1d76b22012-06-06 17:32:50 +00002418 "garbage collection (GC) in "
2419 "dual GC/non-GC code"));
Jordy Rose15484da2011-08-25 01:14:38 +00002420 } else {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002421 leakWithinFunction.reset(new Leak(this, "Leak"));
Jordy Rose15484da2011-08-25 01:14:38 +00002422 }
2423 }
Jordy Rosec49ec532011-09-02 05:55:19 +00002424 return leakWithinFunction.get();
Jordy Rose15484da2011-08-25 01:14:38 +00002425 }
2426 }
2427
Jordy Rosec49ec532011-09-02 05:55:19 +00002428 CFRefBug *getLeakAtReturnBug(const LangOptions &LOpts, bool GCEnabled) const {
2429 if (GCEnabled) {
Jordy Rose15484da2011-08-25 01:14:38 +00002430 if (!leakAtReturnGC)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002431 leakAtReturnGC.reset(new Leak(this,
2432 "Leak of returned object when using "
Benjamin Kramerd1d76b22012-06-06 17:32:50 +00002433 "garbage collection"));
Jordy Rosec49ec532011-09-02 05:55:19 +00002434 return leakAtReturnGC.get();
Jordy Rose15484da2011-08-25 01:14:38 +00002435 } else {
2436 if (!leakAtReturn) {
Douglas Gregor79a91412011-09-13 17:21:33 +00002437 if (LOpts.getGC() == LangOptions::HybridGC) {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002438 leakAtReturn.reset(new Leak(this,
2439 "Leak of returned object when not using "
Benjamin Kramerd1d76b22012-06-06 17:32:50 +00002440 "garbage collection (GC) in dual "
2441 "GC/non-GC code"));
Jordy Rose15484da2011-08-25 01:14:38 +00002442 } else {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002443 leakAtReturn.reset(new Leak(this, "Leak of returned object"));
Jordy Rose15484da2011-08-25 01:14:38 +00002444 }
2445 }
Jordy Rosec49ec532011-09-02 05:55:19 +00002446 return leakAtReturn.get();
Jordy Rose15484da2011-08-25 01:14:38 +00002447 }
2448 }
2449
Jordy Rosec49ec532011-09-02 05:55:19 +00002450 RetainSummaryManager &getSummaryManager(ASTContext &Ctx,
2451 bool GCEnabled) const {
2452 // FIXME: We don't support ARC being turned on and off during one analysis.
2453 // (nor, for that matter, do we support changing ASTContexts)
David Blaikiebbafb8a2012-03-11 07:00:24 +00002454 bool ARCEnabled = (bool)Ctx.getLangOpts().ObjCAutoRefCount;
Jordy Rosec49ec532011-09-02 05:55:19 +00002455 if (GCEnabled) {
2456 if (!SummariesGC)
Jordy Rose8b289a22011-08-25 00:10:37 +00002457 SummariesGC.reset(new RetainSummaryManager(Ctx, true, ARCEnabled));
Jordy Rosec49ec532011-09-02 05:55:19 +00002458 else
2459 assert(SummariesGC->isARCEnabled() == ARCEnabled);
Jordy Rose8b289a22011-08-25 00:10:37 +00002460 return *SummariesGC;
2461 } else {
Jordy Rosec49ec532011-09-02 05:55:19 +00002462 if (!Summaries)
Jordy Rose8b289a22011-08-25 00:10:37 +00002463 Summaries.reset(new RetainSummaryManager(Ctx, false, ARCEnabled));
Jordy Rosec49ec532011-09-02 05:55:19 +00002464 else
2465 assert(Summaries->isARCEnabled() == ARCEnabled);
Jordy Rose8b289a22011-08-25 00:10:37 +00002466 return *Summaries;
2467 }
2468 }
2469
Jordy Rosec49ec532011-09-02 05:55:19 +00002470 RetainSummaryManager &getSummaryManager(CheckerContext &C) const {
2471 return getSummaryManager(C.getASTContext(), C.isObjCGCEnabled());
2472 }
2473
Ted Kremenek49b1e382012-01-26 21:29:00 +00002474 void printState(raw_ostream &Out, ProgramStateRef State,
Craig Topperfb6b25b2014-03-15 04:29:04 +00002475 const char *NL, const char *Sep) const override;
Jordy Rose58a20d32011-08-28 19:11:56 +00002476
Anna Zaks3e0f4152011-10-06 00:43:15 +00002477 void checkBind(SVal loc, SVal val, const Stmt *S, CheckerContext &C) const;
Jordy Rose5c252ef2011-08-20 21:16:58 +00002478 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
2479 void checkPostStmt(const CastExpr *CE, CheckerContext &C) const;
John McCall31168b02011-06-15 23:02:42 +00002480
Ted Kremenek415287d2012-03-06 20:06:12 +00002481 void checkPostStmt(const ObjCArrayLiteral *AL, CheckerContext &C) const;
2482 void checkPostStmt(const ObjCDictionaryLiteral *DL, CheckerContext &C) const;
Jordy Rose6393f822012-05-12 05:10:43 +00002483 void checkPostStmt(const ObjCBoxedExpr *BE, CheckerContext &C) const;
2484
Jordan Rose682b3162012-07-02 19:28:21 +00002485 void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
Ted Kremenek415287d2012-03-06 20:06:12 +00002486
Jordan Roseeec15392012-07-02 19:27:43 +00002487 void checkSummary(const RetainSummary &Summ, const CallEvent &Call,
Jordy Rosed188d662011-08-28 05:16:28 +00002488 CheckerContext &C) const;
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002489
Anna Zaks25612732012-08-29 23:23:43 +00002490 void processSummaryOfInlined(const RetainSummary &Summ,
2491 const CallEvent &Call,
2492 CheckerContext &C) const;
2493
Jordy Rose898a1482011-08-21 21:58:18 +00002494 bool evalCall(const CallExpr *CE, CheckerContext &C) const;
2495
Ted Kremenek49b1e382012-01-26 21:29:00 +00002496 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Jordy Rose5c252ef2011-08-20 21:16:58 +00002497 bool Assumption) const;
Jordy Rose217eb902011-08-17 21:27:39 +00002498
Ted Kremenek49b1e382012-01-26 21:29:00 +00002499 ProgramStateRef
2500 checkRegionChanges(ProgramStateRef state,
Anna Zaksdc154152012-12-20 00:38:25 +00002501 const InvalidatedSymbols *invalidated,
Jordy Rose1fad6632011-08-27 22:51:26 +00002502 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks3d348342012-02-14 21:55:24 +00002503 ArrayRef<const MemRegion *> Regions,
Jordan Rose742920c2012-07-02 19:27:35 +00002504 const CallEvent *Call) const;
Jordy Rose5c252ef2011-08-20 21:16:58 +00002505
Ted Kremenek49b1e382012-01-26 21:29:00 +00002506 bool wantsRegionChangeUpdate(ProgramStateRef state) const {
Jordy Rosea8f99ba2011-08-20 21:17:59 +00002507 return true;
Jordy Rose5c252ef2011-08-20 21:16:58 +00002508 }
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002509
Jordy Rose298cc4d2011-08-23 19:43:16 +00002510 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
2511 void checkReturnWithRetEffect(const ReturnStmt *S, CheckerContext &C,
2512 ExplodedNode *Pred, RetEffect RE, RefVal X,
Ted Kremenek49b1e382012-01-26 21:29:00 +00002513 SymbolRef Sym, ProgramStateRef state) const;
Jordy Rose298cc4d2011-08-23 19:43:16 +00002514
Jordy Rose78612762011-08-23 19:01:07 +00002515 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Anna Zaks3fdcc0b2013-01-03 00:25:29 +00002516 void checkEndFunction(CheckerContext &C) const;
Jordy Rose78612762011-08-23 19:01:07 +00002517
Ted Kremenek49b1e382012-01-26 21:29:00 +00002518 ProgramStateRef updateSymbol(ProgramStateRef state, SymbolRef sym,
Anna Zaks25612732012-08-29 23:23:43 +00002519 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
2520 CheckerContext &C) const;
Jordy Rosebf77e512011-08-23 20:27:16 +00002521
Ted Kremenek49b1e382012-01-26 21:29:00 +00002522 void processNonLeakError(ProgramStateRef St, SourceRange ErrorRange,
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002523 RefVal::Kind ErrorKind, SymbolRef Sym,
2524 CheckerContext &C) const;
Ted Kremenek415287d2012-03-06 20:06:12 +00002525
2526 void processObjCLiterals(CheckerContext &C, const Expr *Ex) const;
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002527
Jordy Rose78612762011-08-23 19:01:07 +00002528 const ProgramPointTag *getDeadSymbolTag(SymbolRef sym) const;
2529
Ted Kremenek49b1e382012-01-26 21:29:00 +00002530 ProgramStateRef handleSymbolDeath(ProgramStateRef state,
Anna Zaksf5788c72012-08-14 00:36:15 +00002531 SymbolRef sid, RefVal V,
2532 SmallVectorImpl<SymbolRef> &Leaked) const;
Jordy Rose78612762011-08-23 19:01:07 +00002533
Jordan Roseff03c1d2012-12-06 18:58:18 +00002534 ProgramStateRef
Jordan Rose9f61f8a2012-08-18 00:30:16 +00002535 handleAutoreleaseCounts(ProgramStateRef state, ExplodedNode *Pred,
2536 const ProgramPointTag *Tag, CheckerContext &Ctx,
2537 SymbolRef Sym, RefVal V) const;
Jordy Rose6763e382011-08-23 20:07:14 +00002538
Ted Kremenek49b1e382012-01-26 21:29:00 +00002539 ExplodedNode *processLeaks(ProgramStateRef state,
Jordy Rose78612762011-08-23 19:01:07 +00002540 SmallVectorImpl<SymbolRef> &Leaked,
Anna Zaks58734db2011-10-25 19:57:11 +00002541 CheckerContext &Ctx,
Jordy Rose78612762011-08-23 19:01:07 +00002542 ExplodedNode *Pred = 0) const;
Ted Kremenek70a87882009-11-25 22:17:44 +00002543};
2544} // end anonymous namespace
2545
Jordy Rose217eb902011-08-17 21:27:39 +00002546namespace {
2547class StopTrackingCallback : public SymbolVisitor {
Ted Kremenek49b1e382012-01-26 21:29:00 +00002548 ProgramStateRef state;
Jordy Rose217eb902011-08-17 21:27:39 +00002549public:
Ted Kremenek49b1e382012-01-26 21:29:00 +00002550 StopTrackingCallback(ProgramStateRef st) : state(st) {}
2551 ProgramStateRef getState() const { return state; }
Jordy Rose217eb902011-08-17 21:27:39 +00002552
Craig Topperfb6b25b2014-03-15 04:29:04 +00002553 bool VisitSymbol(SymbolRef sym) override {
Jordy Rose217eb902011-08-17 21:27:39 +00002554 state = state->remove<RefBindings>(sym);
2555 return true;
2556 }
2557};
2558} // end anonymous namespace
2559
Jordy Rose75e680e2011-09-02 06:44:22 +00002560//===----------------------------------------------------------------------===//
2561// Handle statements that may have an effect on refcounts.
2562//===----------------------------------------------------------------------===//
Jordy Rose217eb902011-08-17 21:27:39 +00002563
Jordy Rose75e680e2011-09-02 06:44:22 +00002564void RetainCountChecker::checkPostStmt(const BlockExpr *BE,
2565 CheckerContext &C) const {
Jordy Rose217eb902011-08-17 21:27:39 +00002566
Jordy Rose75e680e2011-09-02 06:44:22 +00002567 // Scan the BlockDecRefExprs for any object the retain count checker
Ted Kremenekbd862712010-07-01 20:16:50 +00002568 // may be tracking.
John McCallc63de662011-02-02 13:00:07 +00002569 if (!BE->getBlockDecl()->hasCaptures())
Ted Kremenekf89dcda2009-11-26 02:38:19 +00002570 return;
Ted Kremenekbd862712010-07-01 20:16:50 +00002571
Ted Kremenek49b1e382012-01-26 21:29:00 +00002572 ProgramStateRef state = C.getState();
Ted Kremenekf89dcda2009-11-26 02:38:19 +00002573 const BlockDataRegion *R =
Ted Kremenek632e3b72012-01-06 22:09:28 +00002574 cast<BlockDataRegion>(state->getSVal(BE,
2575 C.getLocationContext()).getAsRegion());
Ted Kremenekbd862712010-07-01 20:16:50 +00002576
Ted Kremenekf89dcda2009-11-26 02:38:19 +00002577 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
2578 E = R->referenced_vars_end();
Ted Kremenekbd862712010-07-01 20:16:50 +00002579
Ted Kremenekf89dcda2009-11-26 02:38:19 +00002580 if (I == E)
2581 return;
Ted Kremenekbd862712010-07-01 20:16:50 +00002582
Ted Kremenek04af9f22009-12-07 22:05:27 +00002583 // FIXME: For now we invalidate the tracking of all symbols passed to blocks
2584 // via captured variables, even though captured variables result in a copy
2585 // and in implicit increment/decrement of a retain count.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002586 SmallVector<const MemRegion*, 10> Regions;
Anna Zaksc9abbe22011-10-26 21:06:44 +00002587 const LocationContext *LC = C.getLocationContext();
Ted Kremenek90af9092010-12-02 07:49:45 +00002588 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
Ted Kremenekbd862712010-07-01 20:16:50 +00002589
Ted Kremenek04af9f22009-12-07 22:05:27 +00002590 for ( ; I != E; ++I) {
Ted Kremenekbcf90532012-12-06 07:17:20 +00002591 const VarRegion *VR = I.getCapturedRegion();
Ted Kremenek04af9f22009-12-07 22:05:27 +00002592 if (VR->getSuperRegion() == R) {
2593 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2594 }
2595 Regions.push_back(VR);
2596 }
Ted Kremenekbd862712010-07-01 20:16:50 +00002597
Ted Kremenek04af9f22009-12-07 22:05:27 +00002598 state =
2599 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
2600 Regions.data() + Regions.size()).getState();
Anna Zaksda4c8d62011-10-26 21:06:34 +00002601 C.addTransition(state);
Ted Kremenekf89dcda2009-11-26 02:38:19 +00002602}
2603
Jordy Rose75e680e2011-09-02 06:44:22 +00002604void RetainCountChecker::checkPostStmt(const CastExpr *CE,
2605 CheckerContext &C) const {
John McCall31168b02011-06-15 23:02:42 +00002606 const ObjCBridgedCastExpr *BE = dyn_cast<ObjCBridgedCastExpr>(CE);
2607 if (!BE)
2608 return;
2609
John McCall640767f2011-06-17 06:50:50 +00002610 ArgEffect AE = IncRef;
John McCall31168b02011-06-15 23:02:42 +00002611
2612 switch (BE->getBridgeKind()) {
2613 case clang::OBC_Bridge:
2614 // Do nothing.
2615 return;
2616 case clang::OBC_BridgeRetained:
2617 AE = IncRef;
2618 break;
2619 case clang::OBC_BridgeTransfer:
Benjamin Kramer1d5d6342013-10-20 11:53:20 +00002620 AE = DecRefBridgedTransferred;
John McCall31168b02011-06-15 23:02:42 +00002621 break;
2622 }
2623
Ted Kremenek49b1e382012-01-26 21:29:00 +00002624 ProgramStateRef state = C.getState();
Ted Kremenek632e3b72012-01-06 22:09:28 +00002625 SymbolRef Sym = state->getSVal(CE, C.getLocationContext()).getAsLocSymbol();
John McCall31168b02011-06-15 23:02:42 +00002626 if (!Sym)
2627 return;
Anna Zaksf5788c72012-08-14 00:36:15 +00002628 const RefVal* T = getRefBinding(state, Sym);
John McCall31168b02011-06-15 23:02:42 +00002629 if (!T)
2630 return;
2631
John McCall31168b02011-06-15 23:02:42 +00002632 RefVal::Kind hasErr = (RefVal::Kind) 0;
Jordy Rosec49ec532011-09-02 05:55:19 +00002633 state = updateSymbol(state, Sym, *T, AE, hasErr, C);
John McCall31168b02011-06-15 23:02:42 +00002634
2635 if (hasErr) {
Jordy Rosebf77e512011-08-23 20:27:16 +00002636 // FIXME: If we get an error during a bridge cast, should we report it?
2637 // Should we assert that there is no error?
John McCall31168b02011-06-15 23:02:42 +00002638 return;
2639 }
2640
Anna Zaksda4c8d62011-10-26 21:06:34 +00002641 C.addTransition(state);
John McCall31168b02011-06-15 23:02:42 +00002642}
2643
Ted Kremenek415287d2012-03-06 20:06:12 +00002644void RetainCountChecker::processObjCLiterals(CheckerContext &C,
2645 const Expr *Ex) const {
2646 ProgramStateRef state = C.getState();
2647 const ExplodedNode *pred = C.getPredecessor();
2648 for (Stmt::const_child_iterator it = Ex->child_begin(), et = Ex->child_end() ;
2649 it != et ; ++it) {
2650 const Stmt *child = *it;
2651 SVal V = state->getSVal(child, pred->getLocationContext());
2652 if (SymbolRef sym = V.getAsSymbol())
Anna Zaksf5788c72012-08-14 00:36:15 +00002653 if (const RefVal* T = getRefBinding(state, sym)) {
Ted Kremenek415287d2012-03-06 20:06:12 +00002654 RefVal::Kind hasErr = (RefVal::Kind) 0;
2655 state = updateSymbol(state, sym, *T, MayEscape, hasErr, C);
2656 if (hasErr) {
2657 processNonLeakError(state, child->getSourceRange(), hasErr, sym, C);
2658 return;
2659 }
2660 }
2661 }
2662
2663 // Return the object as autoreleased.
2664 // RetEffect RE = RetEffect::MakeNotOwned(RetEffect::ObjC);
2665 if (SymbolRef sym =
2666 state->getSVal(Ex, pred->getLocationContext()).getAsSymbol()) {
2667 QualType ResultTy = Ex->getType();
Anna Zaksf5788c72012-08-14 00:36:15 +00002668 state = setRefBinding(state, sym,
2669 RefVal::makeNotOwned(RetEffect::ObjC, ResultTy));
Ted Kremenek415287d2012-03-06 20:06:12 +00002670 }
2671
2672 C.addTransition(state);
2673}
2674
2675void RetainCountChecker::checkPostStmt(const ObjCArrayLiteral *AL,
2676 CheckerContext &C) const {
2677 // Apply the 'MayEscape' to all values.
2678 processObjCLiterals(C, AL);
2679}
2680
2681void RetainCountChecker::checkPostStmt(const ObjCDictionaryLiteral *DL,
2682 CheckerContext &C) const {
2683 // Apply the 'MayEscape' to all keys and values.
2684 processObjCLiterals(C, DL);
2685}
2686
Jordy Rose6393f822012-05-12 05:10:43 +00002687void RetainCountChecker::checkPostStmt(const ObjCBoxedExpr *Ex,
2688 CheckerContext &C) const {
2689 const ExplodedNode *Pred = C.getPredecessor();
2690 const LocationContext *LCtx = Pred->getLocationContext();
2691 ProgramStateRef State = Pred->getState();
2692
2693 if (SymbolRef Sym = State->getSVal(Ex, LCtx).getAsSymbol()) {
2694 QualType ResultTy = Ex->getType();
Anna Zaksf5788c72012-08-14 00:36:15 +00002695 State = setRefBinding(State, Sym,
2696 RefVal::makeNotOwned(RetEffect::ObjC, ResultTy));
Jordy Rose6393f822012-05-12 05:10:43 +00002697 }
2698
2699 C.addTransition(State);
2700}
2701
Jordan Rose682b3162012-07-02 19:28:21 +00002702void RetainCountChecker::checkPostCall(const CallEvent &Call,
2703 CheckerContext &C) const {
Jordan Rose682b3162012-07-02 19:28:21 +00002704 RetainSummaryManager &Summaries = getSummaryManager(C);
2705 const RetainSummary *Summ = Summaries.getSummary(Call, C.getState());
Anna Zaks25612732012-08-29 23:23:43 +00002706
2707 if (C.wasInlined) {
2708 processSummaryOfInlined(*Summ, Call, C);
2709 return;
2710 }
Jordan Rose682b3162012-07-02 19:28:21 +00002711 checkSummary(*Summ, Call, C);
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002712}
2713
Jordy Rose75e680e2011-09-02 06:44:22 +00002714/// GetReturnType - Used to get the return type of a message expression or
2715/// function call with the intention of affixing that type to a tracked symbol.
Sylvestre Ledru830885c2012-07-23 08:59:39 +00002716/// While the return type can be queried directly from RetEx, when
Jordy Rose75e680e2011-09-02 06:44:22 +00002717/// invoking class methods we augment to the return type to be that of
2718/// a pointer to the class (as opposed it just being id).
2719// FIXME: We may be able to do this with related result types instead.
2720// This function is probably overestimating.
2721static QualType GetReturnType(const Expr *RetE, ASTContext &Ctx) {
2722 QualType RetTy = RetE->getType();
2723 // If RetE is not a message expression just return its type.
2724 // If RetE is a message expression, return its types if it is something
2725 /// more specific than id.
2726 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RetE))
2727 if (const ObjCObjectPointerType *PT = RetTy->getAs<ObjCObjectPointerType>())
2728 if (PT->isObjCQualifiedIdType() || PT->isObjCIdType() ||
2729 PT->isObjCClassType()) {
2730 // At this point we know the return type of the message expression is
2731 // id, id<...>, or Class. If we have an ObjCInterfaceDecl, we know this
2732 // is a call to a class method whose type we can resolve. In such
2733 // cases, promote the return type to XXX* (where XXX is the class).
2734 const ObjCInterfaceDecl *D = ME->getReceiverInterface();
2735 return !D ? RetTy :
2736 Ctx.getObjCObjectPointerType(Ctx.getObjCInterfaceType(D));
2737 }
2738
2739 return RetTy;
2740}
2741
Jordan Rose1a866cd2014-01-10 20:06:06 +00002742static bool wasSynthesizedProperty(const ObjCMethodCall *Call,
2743 ExplodedNode *N) {
2744 if (!Call || !Call->getDecl()->isPropertyAccessor())
2745 return false;
2746
2747 CallExitEnd PP = N->getLocation().castAs<CallExitEnd>();
2748 const StackFrameContext *Frame = PP.getCalleeContext();
2749 return Frame->getAnalysisDeclContext()->isBodyAutosynthesized();
2750}
2751
Anna Zaks25612732012-08-29 23:23:43 +00002752// We don't always get the exact modeling of the function with regards to the
2753// retain count checker even when the function is inlined. For example, we need
2754// to stop tracking the symbols which were marked with StopTrackingHard.
2755void RetainCountChecker::processSummaryOfInlined(const RetainSummary &Summ,
2756 const CallEvent &CallOrMsg,
2757 CheckerContext &C) const {
2758 ProgramStateRef state = C.getState();
2759
2760 // Evaluate the effect of the arguments.
2761 for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
2762 if (Summ.getArg(idx) == StopTrackingHard) {
2763 SVal V = CallOrMsg.getArgSVal(idx);
2764 if (SymbolRef Sym = V.getAsLocSymbol()) {
2765 state = removeRefBinding(state, Sym);
2766 }
2767 }
2768 }
2769
2770 // Evaluate the effect on the message receiver.
2771 const ObjCMethodCall *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg);
2772 if (MsgInvocation) {
2773 if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
2774 if (Summ.getReceiverEffect() == StopTrackingHard) {
2775 state = removeRefBinding(state, Sym);
2776 }
2777 }
2778 }
2779
2780 // Consult the summary for the return value.
2781 RetEffect RE = Summ.getRetEffect();
2782 if (RE.getKind() == RetEffect::NoRetHard) {
Jordan Rose829c3832012-11-02 23:49:29 +00002783 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
Anna Zaks25612732012-08-29 23:23:43 +00002784 if (Sym)
2785 state = removeRefBinding(state, Sym);
Jordan Rose1a866cd2014-01-10 20:06:06 +00002786 } else if (RE.getKind() == RetEffect::NotOwnedSymbol) {
2787 if (wasSynthesizedProperty(MsgInvocation, C.getPredecessor())) {
2788 // Believe the summary if we synthesized the body and the return value is
2789 // untracked. This handles property getters.
2790 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
2791 if (Sym && !getRefBinding(state, Sym))
2792 state = setRefBinding(state, Sym, RefVal::makeNotOwned(RE.getObjKind(),
2793 Sym->getType()));
2794 }
Anna Zaks25612732012-08-29 23:23:43 +00002795 }
2796
2797 C.addTransition(state);
2798}
2799
Jordy Rose75e680e2011-09-02 06:44:22 +00002800void RetainCountChecker::checkSummary(const RetainSummary &Summ,
Jordan Roseeec15392012-07-02 19:27:43 +00002801 const CallEvent &CallOrMsg,
Jordy Rose75e680e2011-09-02 06:44:22 +00002802 CheckerContext &C) const {
Ted Kremenek49b1e382012-01-26 21:29:00 +00002803 ProgramStateRef state = C.getState();
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002804
2805 // Evaluate the effect of the arguments.
2806 RefVal::Kind hasErr = (RefVal::Kind) 0;
2807 SourceRange ErrorRange;
2808 SymbolRef ErrorSym = 0;
2809
2810 for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
Jordy Rose1fad6632011-08-27 22:51:26 +00002811 SVal V = CallOrMsg.getArgSVal(idx);
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002812
2813 if (SymbolRef Sym = V.getAsLocSymbol()) {
Anna Zaksf5788c72012-08-14 00:36:15 +00002814 if (const RefVal *T = getRefBinding(state, Sym)) {
Jordy Rosec49ec532011-09-02 05:55:19 +00002815 state = updateSymbol(state, Sym, *T, Summ.getArg(idx), hasErr, C);
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002816 if (hasErr) {
2817 ErrorRange = CallOrMsg.getArgSourceRange(idx);
2818 ErrorSym = Sym;
2819 break;
2820 }
2821 }
2822 }
2823 }
2824
2825 // Evaluate the effect on the message receiver.
2826 bool ReceiverIsTracked = false;
Jordan Roseeec15392012-07-02 19:27:43 +00002827 if (!hasErr) {
Jordan Rose6bad4902012-07-02 19:27:56 +00002828 const ObjCMethodCall *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg);
Jordan Roseeec15392012-07-02 19:27:43 +00002829 if (MsgInvocation) {
2830 if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
Anna Zaksf5788c72012-08-14 00:36:15 +00002831 if (const RefVal *T = getRefBinding(state, Sym)) {
Jordan Roseeec15392012-07-02 19:27:43 +00002832 ReceiverIsTracked = true;
2833 state = updateSymbol(state, Sym, *T, Summ.getReceiverEffect(),
Anna Zaks25612732012-08-29 23:23:43 +00002834 hasErr, C);
Jordan Roseeec15392012-07-02 19:27:43 +00002835 if (hasErr) {
Jordan Rose627b0462012-07-18 21:59:51 +00002836 ErrorRange = MsgInvocation->getOriginExpr()->getReceiverRange();
Jordan Roseeec15392012-07-02 19:27:43 +00002837 ErrorSym = Sym;
2838 }
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002839 }
2840 }
2841 }
2842 }
2843
2844 // Process any errors.
2845 if (hasErr) {
2846 processNonLeakError(state, ErrorRange, hasErr, ErrorSym, C);
2847 return;
2848 }
2849
2850 // Consult the summary for the return value.
2851 RetEffect RE = Summ.getRetEffect();
2852
2853 if (RE.getKind() == RetEffect::OwnedWhenTrackedReceiver) {
Jordy Rose8b289a22011-08-25 00:10:37 +00002854 if (ReceiverIsTracked)
Jordy Rosec49ec532011-09-02 05:55:19 +00002855 RE = getSummaryManager(C).getObjAllocRetEffect();
Jordy Rose8b289a22011-08-25 00:10:37 +00002856 else
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002857 RE = RetEffect::MakeNoRet();
2858 }
2859
2860 switch (RE.getKind()) {
2861 default:
David Blaikie8a40f702012-01-17 06:56:22 +00002862 llvm_unreachable("Unhandled RetEffect.");
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002863
2864 case RetEffect::NoRet:
Anna Zaks25612732012-08-29 23:23:43 +00002865 case RetEffect::NoRetHard:
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002866 // No work necessary.
2867 break;
2868
2869 case RetEffect::OwnedAllocatedSymbol:
2870 case RetEffect::OwnedSymbol: {
Jordan Rose829c3832012-11-02 23:49:29 +00002871 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002872 if (!Sym)
2873 break;
2874
Jordan Roseeec15392012-07-02 19:27:43 +00002875 // Use the result type from the CallEvent as it automatically adjusts
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002876 // for methods/functions that return references.
Jordan Roseeec15392012-07-02 19:27:43 +00002877 QualType ResultTy = CallOrMsg.getResultType();
Anna Zaksf5788c72012-08-14 00:36:15 +00002878 state = setRefBinding(state, Sym, RefVal::makeOwned(RE.getObjKind(),
2879 ResultTy));
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002880
2881 // FIXME: Add a flag to the checker where allocations are assumed to
Anna Zaks21487f72012-08-14 15:39:13 +00002882 // *not* fail.
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002883 break;
2884 }
2885
2886 case RetEffect::GCNotOwnedSymbol:
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002887 case RetEffect::NotOwnedSymbol: {
2888 const Expr *Ex = CallOrMsg.getOriginExpr();
Jordan Rose829c3832012-11-02 23:49:29 +00002889 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002890 if (!Sym)
2891 break;
Ted Kremenekbe400842012-10-12 22:56:45 +00002892 assert(Ex);
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002893 // Use GetReturnType in order to give [NSFoo alloc] the type NSFoo *.
2894 QualType ResultTy = GetReturnType(Ex, C.getASTContext());
Anna Zaksf5788c72012-08-14 00:36:15 +00002895 state = setRefBinding(state, Sym, RefVal::makeNotOwned(RE.getObjKind(),
2896 ResultTy));
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002897 break;
2898 }
2899 }
2900
2901 // This check is actually necessary; otherwise the statement builder thinks
2902 // we've hit a previously-found path.
2903 // Normally addTransition takes care of this, but we want the node pointer.
2904 ExplodedNode *NewNode;
2905 if (state == C.getState()) {
2906 NewNode = C.getPredecessor();
2907 } else {
Anna Zaksda4c8d62011-10-26 21:06:34 +00002908 NewNode = C.addTransition(state);
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002909 }
2910
Jordy Rose5df640d2011-08-24 18:56:32 +00002911 // Annotate the node with summary we used.
2912 if (NewNode) {
2913 // FIXME: This is ugly. See checkEndAnalysis for why it's necessary.
2914 if (ShouldResetSummaryLog) {
2915 SummaryLog.clear();
2916 ShouldResetSummaryLog = false;
2917 }
Jordy Rose20d4e682011-08-23 20:55:48 +00002918 SummaryLog[NewNode] = &Summ;
Jordy Rose5df640d2011-08-24 18:56:32 +00002919 }
Jordy Rose5b31d7a2011-08-22 23:48:23 +00002920}
2921
Jordy Rosebf77e512011-08-23 20:27:16 +00002922
Ted Kremenek49b1e382012-01-26 21:29:00 +00002923ProgramStateRef
2924RetainCountChecker::updateSymbol(ProgramStateRef state, SymbolRef sym,
Jordy Rose75e680e2011-09-02 06:44:22 +00002925 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
2926 CheckerContext &C) const {
Jordy Rosebf77e512011-08-23 20:27:16 +00002927 // In GC mode [... release] and [... retain] do nothing.
Jordy Rose75e680e2011-09-02 06:44:22 +00002928 // In ARC mode they shouldn't exist at all, but we just ignore them.
Jordy Rosec49ec532011-09-02 05:55:19 +00002929 bool IgnoreRetainMsg = C.isObjCGCEnabled();
2930 if (!IgnoreRetainMsg)
David Blaikiebbafb8a2012-03-11 07:00:24 +00002931 IgnoreRetainMsg = (bool)C.getASTContext().getLangOpts().ObjCAutoRefCount;
Jordy Rosec49ec532011-09-02 05:55:19 +00002932
Jordy Rosebf77e512011-08-23 20:27:16 +00002933 switch (E) {
Jordan Roseeec15392012-07-02 19:27:43 +00002934 default:
2935 break;
2936 case IncRefMsg:
2937 E = IgnoreRetainMsg ? DoNothing : IncRef;
2938 break;
2939 case DecRefMsg:
2940 E = IgnoreRetainMsg ? DoNothing : DecRef;
2941 break;
Anna Zaks25612732012-08-29 23:23:43 +00002942 case DecRefMsgAndStopTrackingHard:
2943 E = IgnoreRetainMsg ? StopTracking : DecRefAndStopTrackingHard;
Jordan Roseeec15392012-07-02 19:27:43 +00002944 break;
2945 case MakeCollectable:
2946 E = C.isObjCGCEnabled() ? DecRef : DoNothing;
2947 break;
Jordy Rosebf77e512011-08-23 20:27:16 +00002948 }
2949
2950 // Handle all use-after-releases.
Jordy Rosec49ec532011-09-02 05:55:19 +00002951 if (!C.isObjCGCEnabled() && V.getKind() == RefVal::Released) {
Jordy Rosebf77e512011-08-23 20:27:16 +00002952 V = V ^ RefVal::ErrorUseAfterRelease;
2953 hasErr = V.getKind();
Anna Zaksf5788c72012-08-14 00:36:15 +00002954 return setRefBinding(state, sym, V);
Jordy Rosebf77e512011-08-23 20:27:16 +00002955 }
2956
2957 switch (E) {
2958 case DecRefMsg:
2959 case IncRefMsg:
2960 case MakeCollectable:
Anna Zaks25612732012-08-29 23:23:43 +00002961 case DecRefMsgAndStopTrackingHard:
Jordy Rosebf77e512011-08-23 20:27:16 +00002962 llvm_unreachable("DecRefMsg/IncRefMsg/MakeCollectable already converted");
Jordy Rosebf77e512011-08-23 20:27:16 +00002963
2964 case Dealloc:
2965 // Any use of -dealloc in GC is *bad*.
Jordy Rosec49ec532011-09-02 05:55:19 +00002966 if (C.isObjCGCEnabled()) {
Jordy Rosebf77e512011-08-23 20:27:16 +00002967 V = V ^ RefVal::ErrorDeallocGC;
2968 hasErr = V.getKind();
2969 break;
2970 }
2971
2972 switch (V.getKind()) {
2973 default:
2974 llvm_unreachable("Invalid RefVal state for an explicit dealloc.");
Jordy Rosebf77e512011-08-23 20:27:16 +00002975 case RefVal::Owned:
2976 // The object immediately transitions to the released state.
2977 V = V ^ RefVal::Released;
2978 V.clearCounts();
Anna Zaksf5788c72012-08-14 00:36:15 +00002979 return setRefBinding(state, sym, V);
Jordy Rosebf77e512011-08-23 20:27:16 +00002980 case RefVal::NotOwned:
2981 V = V ^ RefVal::ErrorDeallocNotOwned;
2982 hasErr = V.getKind();
2983 break;
2984 }
2985 break;
2986
Jordy Rosebf77e512011-08-23 20:27:16 +00002987 case MayEscape:
2988 if (V.getKind() == RefVal::Owned) {
2989 V = V ^ RefVal::NotOwned;
2990 break;
2991 }
2992
2993 // Fall-through.
2994
Jordy Rosebf77e512011-08-23 20:27:16 +00002995 case DoNothing:
2996 return state;
2997
2998 case Autorelease:
Jordy Rosec49ec532011-09-02 05:55:19 +00002999 if (C.isObjCGCEnabled())
Jordy Rosebf77e512011-08-23 20:27:16 +00003000 return state;
Jordy Rosebf77e512011-08-23 20:27:16 +00003001 // Update the autorelease counts.
Jordy Rosebf77e512011-08-23 20:27:16 +00003002 V = V.autorelease();
3003 break;
3004
3005 case StopTracking:
Anna Zaks25612732012-08-29 23:23:43 +00003006 case StopTrackingHard:
Anna Zaksf5788c72012-08-14 00:36:15 +00003007 return removeRefBinding(state, sym);
Jordy Rosebf77e512011-08-23 20:27:16 +00003008
3009 case IncRef:
3010 switch (V.getKind()) {
3011 default:
3012 llvm_unreachable("Invalid RefVal state for a retain.");
Jordy Rosebf77e512011-08-23 20:27:16 +00003013 case RefVal::Owned:
3014 case RefVal::NotOwned:
3015 V = V + 1;
3016 break;
3017 case RefVal::Released:
3018 // Non-GC cases are handled above.
Jordy Rosec49ec532011-09-02 05:55:19 +00003019 assert(C.isObjCGCEnabled());
Jordy Rosebf77e512011-08-23 20:27:16 +00003020 V = (V ^ RefVal::Owned) + 1;
3021 break;
3022 }
3023 break;
3024
Jordy Rosebf77e512011-08-23 20:27:16 +00003025 case DecRef:
Benjamin Kramer1d5d6342013-10-20 11:53:20 +00003026 case DecRefBridgedTransferred:
Anna Zaks25612732012-08-29 23:23:43 +00003027 case DecRefAndStopTrackingHard:
Jordy Rosebf77e512011-08-23 20:27:16 +00003028 switch (V.getKind()) {
3029 default:
3030 // case 'RefVal::Released' handled above.
3031 llvm_unreachable("Invalid RefVal state for a release.");
Jordy Rosebf77e512011-08-23 20:27:16 +00003032
3033 case RefVal::Owned:
3034 assert(V.getCount() > 0);
3035 if (V.getCount() == 1)
Benjamin Kramer1d5d6342013-10-20 11:53:20 +00003036 V = V ^ (E == DecRefBridgedTransferred ? RefVal::NotOwned
3037 : RefVal::Released);
Anna Zaks25612732012-08-29 23:23:43 +00003038 else if (E == DecRefAndStopTrackingHard)
Anna Zaksf5788c72012-08-14 00:36:15 +00003039 return removeRefBinding(state, sym);
Jordan Roseeec15392012-07-02 19:27:43 +00003040
Jordy Rosebf77e512011-08-23 20:27:16 +00003041 V = V - 1;
3042 break;
3043
3044 case RefVal::NotOwned:
Jordan Roseeec15392012-07-02 19:27:43 +00003045 if (V.getCount() > 0) {
Anna Zaks25612732012-08-29 23:23:43 +00003046 if (E == DecRefAndStopTrackingHard)
Anna Zaksf5788c72012-08-14 00:36:15 +00003047 return removeRefBinding(state, sym);
Jordy Rosebf77e512011-08-23 20:27:16 +00003048 V = V - 1;
Jordan Roseeec15392012-07-02 19:27:43 +00003049 } else {
Jordy Rosebf77e512011-08-23 20:27:16 +00003050 V = V ^ RefVal::ErrorReleaseNotOwned;
3051 hasErr = V.getKind();
3052 }
3053 break;
3054
3055 case RefVal::Released:
3056 // Non-GC cases are handled above.
Jordy Rosec49ec532011-09-02 05:55:19 +00003057 assert(C.isObjCGCEnabled());
Jordy Rosebf77e512011-08-23 20:27:16 +00003058 V = V ^ RefVal::ErrorUseAfterRelease;
3059 hasErr = V.getKind();
3060 break;
3061 }
3062 break;
3063 }
Anna Zaksf5788c72012-08-14 00:36:15 +00003064 return setRefBinding(state, sym, V);
Jordy Rosebf77e512011-08-23 20:27:16 +00003065}
3066
Ted Kremenek49b1e382012-01-26 21:29:00 +00003067void RetainCountChecker::processNonLeakError(ProgramStateRef St,
Jordy Rose75e680e2011-09-02 06:44:22 +00003068 SourceRange ErrorRange,
3069 RefVal::Kind ErrorKind,
3070 SymbolRef Sym,
3071 CheckerContext &C) const {
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003072 ExplodedNode *N = C.generateSink(St);
3073 if (!N)
3074 return;
3075
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003076 CFRefBug *BT;
3077 switch (ErrorKind) {
3078 default:
3079 llvm_unreachable("Unhandled error.");
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003080 case RefVal::ErrorUseAfterRelease:
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003081 if (!useAfterRelease)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00003082 useAfterRelease.reset(new UseAfterRelease(this));
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003083 BT = &*useAfterRelease;
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003084 break;
3085 case RefVal::ErrorReleaseNotOwned:
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003086 if (!releaseNotOwned)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00003087 releaseNotOwned.reset(new BadRelease(this));
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003088 BT = &*releaseNotOwned;
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003089 break;
3090 case RefVal::ErrorDeallocGC:
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003091 if (!deallocGC)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00003092 deallocGC.reset(new DeallocGC(this));
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003093 BT = &*deallocGC;
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003094 break;
3095 case RefVal::ErrorDeallocNotOwned:
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003096 if (!deallocNotOwned)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00003097 deallocNotOwned.reset(new DeallocNotOwned(this));
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003098 BT = &*deallocNotOwned;
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003099 break;
3100 }
3101
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003102 assert(BT);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003103 CFRefReport *report = new CFRefReport(*BT, C.getASTContext().getLangOpts(),
Jordy Rosec49ec532011-09-02 05:55:19 +00003104 C.isObjCGCEnabled(), SummaryLog,
3105 N, Sym);
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003106 report->addRange(ErrorRange);
Jordan Rosee10d5a72012-11-02 01:53:40 +00003107 C.emitReport(report);
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003108}
3109
Jordy Rose75e680e2011-09-02 06:44:22 +00003110//===----------------------------------------------------------------------===//
3111// Handle the return values of retain-count-related functions.
3112//===----------------------------------------------------------------------===//
3113
3114bool RetainCountChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
Jordy Rose898a1482011-08-21 21:58:18 +00003115 // Get the callee. We're only interested in simple C functions.
Ted Kremenek49b1e382012-01-26 21:29:00 +00003116 ProgramStateRef state = C.getState();
Anna Zaksc6aa5312011-12-01 05:57:37 +00003117 const FunctionDecl *FD = C.getCalleeDecl(CE);
Jordy Rose898a1482011-08-21 21:58:18 +00003118 if (!FD)
3119 return false;
3120
3121 IdentifierInfo *II = FD->getIdentifier();
3122 if (!II)
3123 return false;
3124
3125 // For now, we're only handling the functions that return aliases of their
3126 // arguments: CFRetain and CFMakeCollectable (and their families).
3127 // Eventually we should add other functions we can model entirely,
3128 // such as CFRelease, which don't invalidate their arguments or globals.
3129 if (CE->getNumArgs() != 1)
3130 return false;
3131
3132 // Get the name of the function.
3133 StringRef FName = II->getName();
3134 FName = FName.substr(FName.find_first_not_of('_'));
3135
3136 // See if it's one of the specific functions we know how to eval.
3137 bool canEval = false;
3138
Anna Zaksc6aa5312011-12-01 05:57:37 +00003139 QualType ResultTy = CE->getCallReturnType();
Jordy Rose898a1482011-08-21 21:58:18 +00003140 if (ResultTy->isObjCIdType()) {
3141 // Handle: id NSMakeCollectable(CFTypeRef)
3142 canEval = II->isStr("NSMakeCollectable");
3143 } else if (ResultTy->isPointerType()) {
3144 // Handle: (CF|CG)Retain
Jordan Rose77411322013-10-07 17:16:52 +00003145 // CFAutorelease
Jordy Rose898a1482011-08-21 21:58:18 +00003146 // CFMakeCollectable
3147 // It's okay to be a little sloppy here (CGMakeCollectable doesn't exist).
3148 if (cocoa::isRefType(ResultTy, "CF", FName) ||
3149 cocoa::isRefType(ResultTy, "CG", FName)) {
Jordan Rose77411322013-10-07 17:16:52 +00003150 canEval = isRetain(FD, FName) || isAutorelease(FD, FName) ||
3151 isMakeCollectable(FD, FName);
Jordy Rose898a1482011-08-21 21:58:18 +00003152 }
3153 }
3154
3155 if (!canEval)
3156 return false;
3157
3158 // Bind the return value.
Ted Kremenek632e3b72012-01-06 22:09:28 +00003159 const LocationContext *LCtx = C.getLocationContext();
3160 SVal RetVal = state->getSVal(CE->getArg(0), LCtx);
Jordy Rose898a1482011-08-21 21:58:18 +00003161 if (RetVal.isUnknown()) {
3162 // If the receiver is unknown, conjure a return value.
3163 SValBuilder &SVB = C.getSValBuilder();
Ted Kremenekd94854a2012-08-22 06:26:15 +00003164 RetVal = SVB.conjureSymbolVal(0, CE, LCtx, ResultTy, C.blockCount());
Jordy Rose898a1482011-08-21 21:58:18 +00003165 }
Ted Kremenek632e3b72012-01-06 22:09:28 +00003166 state = state->BindExpr(CE, LCtx, RetVal, false);
Jordy Rose898a1482011-08-21 21:58:18 +00003167
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003168 // FIXME: This should not be necessary, but otherwise the argument seems to be
3169 // considered alive during the next statement.
3170 if (const MemRegion *ArgRegion = RetVal.getAsRegion()) {
3171 // Save the refcount status of the argument.
3172 SymbolRef Sym = RetVal.getAsLocSymbol();
Anna Zaksf5788c72012-08-14 00:36:15 +00003173 const RefVal *Binding = 0;
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003174 if (Sym)
Anna Zaksf5788c72012-08-14 00:36:15 +00003175 Binding = getRefBinding(state, Sym);
Jordy Rose898a1482011-08-21 21:58:18 +00003176
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003177 // Invalidate the argument region.
Anna Zaksdc154152012-12-20 00:38:25 +00003178 state = state->invalidateRegions(ArgRegion, CE, C.blockCount(), LCtx,
Anna Zaks0c34c1a2013-01-16 01:35:54 +00003179 /*CausesPointerEscape*/ false);
Jordy Rose898a1482011-08-21 21:58:18 +00003180
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003181 // Restore the refcount status of the argument.
3182 if (Binding)
Anna Zaksf5788c72012-08-14 00:36:15 +00003183 state = setRefBinding(state, Sym, *Binding);
Jordy Rose5b31d7a2011-08-22 23:48:23 +00003184 }
3185
Anna Zaksda4c8d62011-10-26 21:06:34 +00003186 C.addTransition(state);
Jordy Rose898a1482011-08-21 21:58:18 +00003187 return true;
3188}
3189
Jordy Rose75e680e2011-09-02 06:44:22 +00003190//===----------------------------------------------------------------------===//
3191// Handle return statements.
3192//===----------------------------------------------------------------------===//
Jordy Rose298cc4d2011-08-23 19:43:16 +00003193
Jordy Rose75e680e2011-09-02 06:44:22 +00003194void RetainCountChecker::checkPreStmt(const ReturnStmt *S,
3195 CheckerContext &C) const {
Ted Kremenekef31f372012-02-25 02:09:09 +00003196
3197 // Only adjust the reference count if this is the top-level call frame,
3198 // and not the result of inlining. In the future, we should do
3199 // better checking even for inlined calls, and see if they match
3200 // with their expected semantics (e.g., the method should return a retained
3201 // object, etc.).
Anna Zaks44dc91b2012-11-03 02:54:16 +00003202 if (!C.inTopFrame())
Ted Kremenekef31f372012-02-25 02:09:09 +00003203 return;
3204
Jordy Rose298cc4d2011-08-23 19:43:16 +00003205 const Expr *RetE = S->getRetValue();
3206 if (!RetE)
3207 return;
3208
Ted Kremenek49b1e382012-01-26 21:29:00 +00003209 ProgramStateRef state = C.getState();
Ted Kremenek632e3b72012-01-06 22:09:28 +00003210 SymbolRef Sym =
3211 state->getSValAsScalarOrLoc(RetE, C.getLocationContext()).getAsLocSymbol();
Jordy Rose298cc4d2011-08-23 19:43:16 +00003212 if (!Sym)
3213 return;
3214
3215 // Get the reference count binding (if any).
Anna Zaksf5788c72012-08-14 00:36:15 +00003216 const RefVal *T = getRefBinding(state, Sym);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003217 if (!T)
3218 return;
3219
3220 // Change the reference count.
3221 RefVal X = *T;
3222
3223 switch (X.getKind()) {
3224 case RefVal::Owned: {
3225 unsigned cnt = X.getCount();
3226 assert(cnt > 0);
3227 X.setCount(cnt - 1);
3228 X = X ^ RefVal::ReturnedOwned;
3229 break;
3230 }
3231
3232 case RefVal::NotOwned: {
3233 unsigned cnt = X.getCount();
3234 if (cnt) {
3235 X.setCount(cnt - 1);
3236 X = X ^ RefVal::ReturnedOwned;
3237 }
3238 else {
3239 X = X ^ RefVal::ReturnedNotOwned;
3240 }
3241 break;
3242 }
3243
3244 default:
3245 return;
3246 }
3247
3248 // Update the binding.
Anna Zaksf5788c72012-08-14 00:36:15 +00003249 state = setRefBinding(state, Sym, X);
Anna Zaksda4c8d62011-10-26 21:06:34 +00003250 ExplodedNode *Pred = C.addTransition(state);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003251
3252 // At this point we have updated the state properly.
3253 // Everything after this is merely checking to see if the return value has
3254 // been over- or under-retained.
3255
3256 // Did we cache out?
3257 if (!Pred)
3258 return;
3259
Jordy Rose298cc4d2011-08-23 19:43:16 +00003260 // Update the autorelease counts.
Anton Yartsev6a619222014-02-17 18:25:34 +00003261 static CheckerProgramPointTag AutoreleaseTag(this, "Autorelease");
Jordan Roseff03c1d2012-12-06 18:58:18 +00003262 state = handleAutoreleaseCounts(state, Pred, &AutoreleaseTag, C, Sym, X);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003263
3264 // Did we cache out?
Jordan Roseff03c1d2012-12-06 18:58:18 +00003265 if (!state)
Jordy Rose298cc4d2011-08-23 19:43:16 +00003266 return;
3267
3268 // Get the updated binding.
Anna Zaksf5788c72012-08-14 00:36:15 +00003269 T = getRefBinding(state, Sym);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003270 assert(T);
3271 X = *T;
3272
3273 // Consult the summary of the enclosing method.
Jordy Rosec49ec532011-09-02 05:55:19 +00003274 RetainSummaryManager &Summaries = getSummaryManager(C);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003275 const Decl *CD = &Pred->getCodeDecl();
Jordan Roseeec15392012-07-02 19:27:43 +00003276 RetEffect RE = RetEffect::MakeNoRet();
Jordy Rose298cc4d2011-08-23 19:43:16 +00003277
Jordan Roseeec15392012-07-02 19:27:43 +00003278 // FIXME: What is the convention for blocks? Is there one?
Jordy Rose298cc4d2011-08-23 19:43:16 +00003279 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CD)) {
Jordy Rose8b289a22011-08-25 00:10:37 +00003280 const RetainSummary *Summ = Summaries.getMethodSummary(MD);
Jordan Roseeec15392012-07-02 19:27:43 +00003281 RE = Summ->getRetEffect();
3282 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) {
3283 if (!isa<CXXMethodDecl>(FD)) {
3284 const RetainSummary *Summ = Summaries.getFunctionSummary(FD);
3285 RE = Summ->getRetEffect();
3286 }
Jordy Rose298cc4d2011-08-23 19:43:16 +00003287 }
3288
Jordan Roseeec15392012-07-02 19:27:43 +00003289 checkReturnWithRetEffect(S, C, Pred, RE, X, Sym, state);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003290}
3291
Jordy Rose75e680e2011-09-02 06:44:22 +00003292void RetainCountChecker::checkReturnWithRetEffect(const ReturnStmt *S,
3293 CheckerContext &C,
3294 ExplodedNode *Pred,
3295 RetEffect RE, RefVal X,
3296 SymbolRef Sym,
Ted Kremenek49b1e382012-01-26 21:29:00 +00003297 ProgramStateRef state) const {
Jordy Rose298cc4d2011-08-23 19:43:16 +00003298 // Any leaks or other errors?
3299 if (X.isReturnedOwned() && X.getCount() == 0) {
3300 if (RE.getKind() != RetEffect::NoRet) {
3301 bool hasError = false;
Jordy Rosec49ec532011-09-02 05:55:19 +00003302 if (C.isObjCGCEnabled() && RE.getObjKind() == RetEffect::ObjC) {
Jordy Rose298cc4d2011-08-23 19:43:16 +00003303 // Things are more complicated with garbage collection. If the
3304 // returned object is suppose to be an Objective-C object, we have
3305 // a leak (as the caller expects a GC'ed object) because no
3306 // method should return ownership unless it returns a CF object.
3307 hasError = true;
3308 X = X ^ RefVal::ErrorGCLeakReturned;
3309 }
3310 else if (!RE.isOwned()) {
3311 // Either we are using GC and the returned object is a CF type
3312 // or we aren't using GC. In either case, we expect that the
3313 // enclosing method is expected to return ownership.
3314 hasError = true;
3315 X = X ^ RefVal::ErrorLeakReturned;
3316 }
3317
3318 if (hasError) {
3319 // Generate an error node.
Anna Zaksf5788c72012-08-14 00:36:15 +00003320 state = setRefBinding(state, Sym, X);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003321
Anton Yartsev6a619222014-02-17 18:25:34 +00003322 static CheckerProgramPointTag ReturnOwnLeakTag(this, "ReturnsOwnLeak");
Anna Zaksda4c8d62011-10-26 21:06:34 +00003323 ExplodedNode *N = C.addTransition(state, Pred, &ReturnOwnLeakTag);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003324 if (N) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003325 const LangOptions &LOpts = C.getASTContext().getLangOpts();
Jordy Rosec49ec532011-09-02 05:55:19 +00003326 bool GCEnabled = C.isObjCGCEnabled();
Jordy Rose298cc4d2011-08-23 19:43:16 +00003327 CFRefReport *report =
Jordy Rosec49ec532011-09-02 05:55:19 +00003328 new CFRefLeakReport(*getLeakAtReturnBug(LOpts, GCEnabled),
3329 LOpts, GCEnabled, SummaryLog,
Ted Kremenek8671acb2013-04-16 21:44:22 +00003330 N, Sym, C, IncludeAllocationLine);
3331
Jordan Rosee10d5a72012-11-02 01:53:40 +00003332 C.emitReport(report);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003333 }
3334 }
3335 }
3336 } else if (X.isReturnedNotOwned()) {
3337 if (RE.isOwned()) {
3338 // Trying to return a not owned object to a caller expecting an
3339 // owned object.
Anna Zaksf5788c72012-08-14 00:36:15 +00003340 state = setRefBinding(state, Sym, X ^ RefVal::ErrorReturnedNotOwned);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003341
Anton Yartsev6a619222014-02-17 18:25:34 +00003342 static CheckerProgramPointTag ReturnNotOwnedTag(this,
3343 "ReturnNotOwnedForOwned");
Anna Zaksda4c8d62011-10-26 21:06:34 +00003344 ExplodedNode *N = C.addTransition(state, Pred, &ReturnNotOwnedTag);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003345 if (N) {
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003346 if (!returnNotOwnedForOwned)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00003347 returnNotOwnedForOwned.reset(new ReturnedNotOwnedForOwned(this));
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003348
Jordy Rose298cc4d2011-08-23 19:43:16 +00003349 CFRefReport *report =
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003350 new CFRefReport(*returnNotOwnedForOwned,
David Blaikiebbafb8a2012-03-11 07:00:24 +00003351 C.getASTContext().getLangOpts(),
Jordy Rosec49ec532011-09-02 05:55:19 +00003352 C.isObjCGCEnabled(), SummaryLog, N, Sym);
Jordan Rosee10d5a72012-11-02 01:53:40 +00003353 C.emitReport(report);
Jordy Rose298cc4d2011-08-23 19:43:16 +00003354 }
3355 }
3356 }
3357}
3358
Jordy Rose6763e382011-08-23 20:07:14 +00003359//===----------------------------------------------------------------------===//
Jordy Rose75e680e2011-09-02 06:44:22 +00003360// Check various ways a symbol can be invalidated.
3361//===----------------------------------------------------------------------===//
3362
Anna Zaks3e0f4152011-10-06 00:43:15 +00003363void RetainCountChecker::checkBind(SVal loc, SVal val, const Stmt *S,
Jordy Rose75e680e2011-09-02 06:44:22 +00003364 CheckerContext &C) const {
3365 // Are we storing to something that causes the value to "escape"?
3366 bool escapes = true;
3367
3368 // A value escapes in three possible cases (this may change):
3369 //
3370 // (1) we are binding to something that is not a memory region.
3371 // (2) we are binding to a memregion that does not have stack storage
3372 // (3) we are binding to a memregion with stack storage that the store
3373 // does not understand.
Ted Kremenek49b1e382012-01-26 21:29:00 +00003374 ProgramStateRef state = C.getState();
Jordy Rose75e680e2011-09-02 06:44:22 +00003375
David Blaikie05785d12013-02-20 22:23:23 +00003376 if (Optional<loc::MemRegionVal> regionLoc = loc.getAs<loc::MemRegionVal>()) {
Jordy Rose75e680e2011-09-02 06:44:22 +00003377 escapes = !regionLoc->getRegion()->hasStackStorage();
3378
3379 if (!escapes) {
3380 // To test (3), generate a new state with the binding added. If it is
3381 // the same state, then it escapes (since the store cannot represent
3382 // the binding).
Anna Zaks70de7722012-05-02 00:15:40 +00003383 // Do this only if we know that the store is not supposed to generate the
3384 // same state.
3385 SVal StoredVal = state->getSVal(regionLoc->getRegion());
3386 if (StoredVal != val)
3387 escapes = (state == (state->bindLoc(*regionLoc, val)));
Jordy Rose75e680e2011-09-02 06:44:22 +00003388 }
Ted Kremeneke9a5bcf2012-03-27 01:12:45 +00003389 if (!escapes) {
3390 // Case 4: We do not currently model what happens when a symbol is
3391 // assigned to a struct field, so be conservative here and let the symbol
3392 // go. TODO: This could definitely be improved upon.
3393 escapes = !isa<VarRegion>(regionLoc->getRegion());
3394 }
Jordy Rose75e680e2011-09-02 06:44:22 +00003395 }
3396
Anna Zaksfb050942013-09-17 00:53:28 +00003397 // If we are storing the value into an auto function scope variable annotated
3398 // with (__attribute__((cleanup))), stop tracking the value to avoid leak
3399 // false positives.
3400 if (const VarRegion *LVR = dyn_cast_or_null<VarRegion>(loc.getAsRegion())) {
3401 const VarDecl *VD = LVR->getDecl();
Aaron Ballman9ead1242013-12-19 02:39:40 +00003402 if (VD->hasAttr<CleanupAttr>()) {
Anna Zaksfb050942013-09-17 00:53:28 +00003403 escapes = true;
3404 }
3405 }
3406
Jordy Rose75e680e2011-09-02 06:44:22 +00003407 // If our store can represent the binding and we aren't storing to something
3408 // that doesn't have local storage then just return and have the simulation
3409 // state continue as is.
3410 if (!escapes)
3411 return;
3412
3413 // Otherwise, find all symbols referenced by 'val' that we are tracking
3414 // and stop tracking them.
3415 state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
Anna Zaksda4c8d62011-10-26 21:06:34 +00003416 C.addTransition(state);
Jordy Rose75e680e2011-09-02 06:44:22 +00003417}
3418
Ted Kremenek49b1e382012-01-26 21:29:00 +00003419ProgramStateRef RetainCountChecker::evalAssume(ProgramStateRef state,
Jordy Rose75e680e2011-09-02 06:44:22 +00003420 SVal Cond,
3421 bool Assumption) const {
3422
3423 // FIXME: We may add to the interface of evalAssume the list of symbols
3424 // whose assumptions have changed. For now we just iterate through the
3425 // bindings and check if any of the tracked symbols are NULL. This isn't
3426 // too bad since the number of symbols we will track in practice are
3427 // probably small and evalAssume is only called at branches and a few
3428 // other places.
Jordan Rose0c153cb2012-11-02 01:54:06 +00003429 RefBindingsTy B = state->get<RefBindings>();
Jordy Rose75e680e2011-09-02 06:44:22 +00003430
3431 if (B.isEmpty())
3432 return state;
3433
3434 bool changed = false;
Jordan Rose0c153cb2012-11-02 01:54:06 +00003435 RefBindingsTy::Factory &RefBFactory = state->get_context<RefBindings>();
Jordy Rose75e680e2011-09-02 06:44:22 +00003436
Jordan Rose0c153cb2012-11-02 01:54:06 +00003437 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Ted Kremenek244e1d72012-09-07 22:31:01 +00003438 // Check if the symbol is null stop tracking the symbol.
Jordan Rose14fe9f32012-11-01 00:18:27 +00003439 ConstraintManager &CMgr = state->getConstraintManager();
3440 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
3441 if (AllocFailed.isConstrainedTrue()) {
Jordy Rose75e680e2011-09-02 06:44:22 +00003442 changed = true;
3443 B = RefBFactory.remove(B, I.getKey());
3444 }
3445 }
3446
3447 if (changed)
3448 state = state->set<RefBindings>(B);
3449
3450 return state;
3451}
3452
Ted Kremenek49b1e382012-01-26 21:29:00 +00003453ProgramStateRef
3454RetainCountChecker::checkRegionChanges(ProgramStateRef state,
Anna Zaksdc154152012-12-20 00:38:25 +00003455 const InvalidatedSymbols *invalidated,
Jordy Rose75e680e2011-09-02 06:44:22 +00003456 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks3d348342012-02-14 21:55:24 +00003457 ArrayRef<const MemRegion *> Regions,
Jordan Rose742920c2012-07-02 19:27:35 +00003458 const CallEvent *Call) const {
Jordy Rose75e680e2011-09-02 06:44:22 +00003459 if (!invalidated)
3460 return state;
3461
3462 llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
3463 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
3464 E = ExplicitRegions.end(); I != E; ++I) {
3465 if (const SymbolicRegion *SR = (*I)->StripCasts()->getAs<SymbolicRegion>())
3466 WhitelistedSymbols.insert(SR->getSymbol());
3467 }
3468
Anna Zaksdc154152012-12-20 00:38:25 +00003469 for (InvalidatedSymbols::const_iterator I=invalidated->begin(),
Jordy Rose75e680e2011-09-02 06:44:22 +00003470 E = invalidated->end(); I!=E; ++I) {
3471 SymbolRef sym = *I;
3472 if (WhitelistedSymbols.count(sym))
3473 continue;
3474 // Remove any existing reference-count binding.
Anna Zaksf5788c72012-08-14 00:36:15 +00003475 state = removeRefBinding(state, sym);
Jordy Rose75e680e2011-09-02 06:44:22 +00003476 }
3477 return state;
3478}
3479
3480//===----------------------------------------------------------------------===//
Jordy Rose6763e382011-08-23 20:07:14 +00003481// Handle dead symbols and end-of-path.
3482//===----------------------------------------------------------------------===//
3483
Jordan Roseff03c1d2012-12-06 18:58:18 +00003484ProgramStateRef
3485RetainCountChecker::handleAutoreleaseCounts(ProgramStateRef state,
Anna Zaks58734db2011-10-25 19:57:11 +00003486 ExplodedNode *Pred,
Jordan Rose9f61f8a2012-08-18 00:30:16 +00003487 const ProgramPointTag *Tag,
Anna Zaks58734db2011-10-25 19:57:11 +00003488 CheckerContext &Ctx,
Jordy Rose75e680e2011-09-02 06:44:22 +00003489 SymbolRef Sym, RefVal V) const {
Jordy Rose6763e382011-08-23 20:07:14 +00003490 unsigned ACnt = V.getAutoreleaseCount();
3491
3492 // No autorelease counts? Nothing to be done.
3493 if (!ACnt)
Jordan Roseff03c1d2012-12-06 18:58:18 +00003494 return state;
Jordy Rose6763e382011-08-23 20:07:14 +00003495
Anna Zaks58734db2011-10-25 19:57:11 +00003496 assert(!Ctx.isObjCGCEnabled() && "Autorelease counts in GC mode?");
Jordy Rose6763e382011-08-23 20:07:14 +00003497 unsigned Cnt = V.getCount();
3498
3499 // FIXME: Handle sending 'autorelease' to already released object.
3500
3501 if (V.getKind() == RefVal::ReturnedOwned)
3502 ++Cnt;
3503
3504 if (ACnt <= Cnt) {
3505 if (ACnt == Cnt) {
3506 V.clearCounts();
3507 if (V.getKind() == RefVal::ReturnedOwned)
3508 V = V ^ RefVal::ReturnedNotOwned;
3509 else
3510 V = V ^ RefVal::NotOwned;
3511 } else {
Anna Zaksa8bcc652013-01-31 22:36:17 +00003512 V.setCount(V.getCount() - ACnt);
Jordy Rose6763e382011-08-23 20:07:14 +00003513 V.setAutoreleaseCount(0);
3514 }
Jordan Roseff03c1d2012-12-06 18:58:18 +00003515 return setRefBinding(state, Sym, V);
Jordy Rose6763e382011-08-23 20:07:14 +00003516 }
3517
3518 // Woah! More autorelease counts then retain counts left.
3519 // Emit hard error.
3520 V = V ^ RefVal::ErrorOverAutorelease;
Anna Zaksf5788c72012-08-14 00:36:15 +00003521 state = setRefBinding(state, Sym, V);
Jordy Rose6763e382011-08-23 20:07:14 +00003522
Jordan Rose4b4613c2012-08-20 18:43:42 +00003523 ExplodedNode *N = Ctx.generateSink(state, Pred, Tag);
Jordan Rose9f61f8a2012-08-18 00:30:16 +00003524 if (N) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003525 SmallString<128> sbuf;
Jordy Rose6763e382011-08-23 20:07:14 +00003526 llvm::raw_svector_ostream os(sbuf);
Jordan Rose7467f062013-04-23 01:42:25 +00003527 os << "Object was autoreleased ";
Jordy Rose6763e382011-08-23 20:07:14 +00003528 if (V.getAutoreleaseCount() > 1)
Jordan Rose7467f062013-04-23 01:42:25 +00003529 os << V.getAutoreleaseCount() << " times but the object ";
3530 else
3531 os << "but ";
3532 os << "has a +" << V.getCount() << " retain count";
Jordy Rose6763e382011-08-23 20:07:14 +00003533
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003534 if (!overAutorelease)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00003535 overAutorelease.reset(new OverAutorelease(this));
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003536
David Blaikiebbafb8a2012-03-11 07:00:24 +00003537 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
Jordy Rose6763e382011-08-23 20:07:14 +00003538 CFRefReport *report =
Jordy Rose4ba0ba42011-08-25 00:34:03 +00003539 new CFRefReport(*overAutorelease, LOpts, /* GCEnabled = */ false,
3540 SummaryLog, N, Sym, os.str());
Jordan Rosee10d5a72012-11-02 01:53:40 +00003541 Ctx.emitReport(report);
Jordy Rose6763e382011-08-23 20:07:14 +00003542 }
3543
Jordan Roseff03c1d2012-12-06 18:58:18 +00003544 return 0;
Jordy Rose6763e382011-08-23 20:07:14 +00003545}
Jordy Rose78612762011-08-23 19:01:07 +00003546
Ted Kremenek49b1e382012-01-26 21:29:00 +00003547ProgramStateRef
3548RetainCountChecker::handleSymbolDeath(ProgramStateRef state,
Jordy Rose75e680e2011-09-02 06:44:22 +00003549 SymbolRef sid, RefVal V,
Jordy Rose78612762011-08-23 19:01:07 +00003550 SmallVectorImpl<SymbolRef> &Leaked) const {
Jordy Rose03a8f9e2011-08-24 04:48:19 +00003551 bool hasLeak = false;
Jordy Rose78612762011-08-23 19:01:07 +00003552 if (V.isOwned())
3553 hasLeak = true;
3554 else if (V.isNotOwned() || V.isReturnedOwned())
3555 hasLeak = (V.getCount() > 0);
3556
3557 if (!hasLeak)
Anna Zaksf5788c72012-08-14 00:36:15 +00003558 return removeRefBinding(state, sid);
Jordy Rose78612762011-08-23 19:01:07 +00003559
3560 Leaked.push_back(sid);
Anna Zaksf5788c72012-08-14 00:36:15 +00003561 return setRefBinding(state, sid, V ^ RefVal::ErrorLeak);
Jordy Rose78612762011-08-23 19:01:07 +00003562}
3563
3564ExplodedNode *
Ted Kremenek49b1e382012-01-26 21:29:00 +00003565RetainCountChecker::processLeaks(ProgramStateRef state,
Jordy Rose75e680e2011-09-02 06:44:22 +00003566 SmallVectorImpl<SymbolRef> &Leaked,
Anna Zaks58734db2011-10-25 19:57:11 +00003567 CheckerContext &Ctx,
3568 ExplodedNode *Pred) const {
Jordy Rose78612762011-08-23 19:01:07 +00003569 // Generate an intermediate node representing the leak point.
Jordan Rose9f61f8a2012-08-18 00:30:16 +00003570 ExplodedNode *N = Ctx.addTransition(state, Pred);
Jordy Rose78612762011-08-23 19:01:07 +00003571
3572 if (N) {
3573 for (SmallVectorImpl<SymbolRef>::iterator
3574 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3575
David Blaikiebbafb8a2012-03-11 07:00:24 +00003576 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
Anna Zaks58734db2011-10-25 19:57:11 +00003577 bool GCEnabled = Ctx.isObjCGCEnabled();
Jordy Rosec49ec532011-09-02 05:55:19 +00003578 CFRefBug *BT = Pred ? getLeakWithinFunctionBug(LOpts, GCEnabled)
3579 : getLeakAtReturnBug(LOpts, GCEnabled);
Jordy Rose78612762011-08-23 19:01:07 +00003580 assert(BT && "BugType not initialized.");
Jordy Rose184bd142011-08-24 22:39:09 +00003581
Jordy Rosec49ec532011-09-02 05:55:19 +00003582 CFRefLeakReport *report = new CFRefLeakReport(*BT, LOpts, GCEnabled,
Ted Kremenek8671acb2013-04-16 21:44:22 +00003583 SummaryLog, N, *I, Ctx,
3584 IncludeAllocationLine);
Jordan Rosee10d5a72012-11-02 01:53:40 +00003585 Ctx.emitReport(report);
Jordy Rose78612762011-08-23 19:01:07 +00003586 }
3587 }
3588
3589 return N;
3590}
3591
Anna Zaks3fdcc0b2013-01-03 00:25:29 +00003592void RetainCountChecker::checkEndFunction(CheckerContext &Ctx) const {
Ted Kremenek49b1e382012-01-26 21:29:00 +00003593 ProgramStateRef state = Ctx.getState();
Jordan Rose0c153cb2012-11-02 01:54:06 +00003594 RefBindingsTy B = state->get<RefBindings>();
Anna Zaks3eae3342011-10-25 19:56:48 +00003595 ExplodedNode *Pred = Ctx.getPredecessor();
Jordy Rose78612762011-08-23 19:01:07 +00003596
Jordan Rose7699e4a2013-08-01 22:16:36 +00003597 // Don't process anything within synthesized bodies.
3598 const LocationContext *LCtx = Pred->getLocationContext();
3599 if (LCtx->getAnalysisDeclContext()->isBodyAutosynthesized()) {
3600 assert(LCtx->getParent());
3601 return;
3602 }
3603
Jordan Rose0c153cb2012-11-02 01:54:06 +00003604 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Jordan Roseff03c1d2012-12-06 18:58:18 +00003605 state = handleAutoreleaseCounts(state, Pred, /*Tag=*/0, Ctx,
3606 I->first, I->second);
Jordy Rose6763e382011-08-23 20:07:14 +00003607 if (!state)
Jordy Rose78612762011-08-23 19:01:07 +00003608 return;
3609 }
3610
Ted Kremeneka2bbac32012-02-07 00:24:33 +00003611 // If the current LocationContext has a parent, don't check for leaks.
3612 // We will do that later.
Anna Zaksf5788c72012-08-14 00:36:15 +00003613 // FIXME: we should instead check for imbalances of the retain/releases,
Ted Kremeneka2bbac32012-02-07 00:24:33 +00003614 // and suggest annotations.
Jordan Rose7699e4a2013-08-01 22:16:36 +00003615 if (LCtx->getParent())
Ted Kremeneka2bbac32012-02-07 00:24:33 +00003616 return;
3617
Jordy Rose78612762011-08-23 19:01:07 +00003618 B = state->get<RefBindings>();
3619 SmallVector<SymbolRef, 10> Leaked;
3620
Jordan Rose0c153cb2012-11-02 01:54:06 +00003621 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I)
Jordy Rose6763e382011-08-23 20:07:14 +00003622 state = handleSymbolDeath(state, I->first, I->second, Leaked);
Jordy Rose78612762011-08-23 19:01:07 +00003623
Jordan Rose9f61f8a2012-08-18 00:30:16 +00003624 processLeaks(state, Leaked, Ctx, Pred);
Jordy Rose78612762011-08-23 19:01:07 +00003625}
3626
3627const ProgramPointTag *
Jordy Rose75e680e2011-09-02 06:44:22 +00003628RetainCountChecker::getDeadSymbolTag(SymbolRef sym) const {
Anton Yartsev6a619222014-02-17 18:25:34 +00003629 const CheckerProgramPointTag *&tag = DeadSymbolTags[sym];
Jordy Rose78612762011-08-23 19:01:07 +00003630 if (!tag) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003631 SmallString<64> buf;
Jordy Rose78612762011-08-23 19:01:07 +00003632 llvm::raw_svector_ostream out(buf);
Anton Yartsev6a619222014-02-17 18:25:34 +00003633 out << "Dead Symbol : ";
Anna Zaks22351652011-12-05 18:58:11 +00003634 sym->dumpToStream(out);
Anton Yartsev6a619222014-02-17 18:25:34 +00003635 tag = new CheckerProgramPointTag(this, out.str());
Jordy Rose78612762011-08-23 19:01:07 +00003636 }
3637 return tag;
3638}
3639
Jordy Rose75e680e2011-09-02 06:44:22 +00003640void RetainCountChecker::checkDeadSymbols(SymbolReaper &SymReaper,
3641 CheckerContext &C) const {
Jordy Rose78612762011-08-23 19:01:07 +00003642 ExplodedNode *Pred = C.getPredecessor();
3643
Ted Kremenek49b1e382012-01-26 21:29:00 +00003644 ProgramStateRef state = C.getState();
Jordan Rose0c153cb2012-11-02 01:54:06 +00003645 RefBindingsTy B = state->get<RefBindings>();
Jordan Roseff03c1d2012-12-06 18:58:18 +00003646 SmallVector<SymbolRef, 10> Leaked;
Jordy Rose78612762011-08-23 19:01:07 +00003647
3648 // Update counts from autorelease pools
3649 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3650 E = SymReaper.dead_end(); I != E; ++I) {
3651 SymbolRef Sym = *I;
3652 if (const RefVal *T = B.lookup(Sym)){
3653 // Use the symbol as the tag.
3654 // FIXME: This might not be as unique as we would like.
Jordan Rose9f61f8a2012-08-18 00:30:16 +00003655 const ProgramPointTag *Tag = getDeadSymbolTag(Sym);
Jordan Roseff03c1d2012-12-06 18:58:18 +00003656 state = handleAutoreleaseCounts(state, Pred, Tag, C, Sym, *T);
Jordy Rose6763e382011-08-23 20:07:14 +00003657 if (!state)
Jordy Rose78612762011-08-23 19:01:07 +00003658 return;
Jordan Roseff03c1d2012-12-06 18:58:18 +00003659
3660 // Fetch the new reference count from the state, and use it to handle
3661 // this symbol.
3662 state = handleSymbolDeath(state, *I, *getRefBinding(state, Sym), Leaked);
Jordy Rose78612762011-08-23 19:01:07 +00003663 }
3664 }
3665
Jordan Roseff03c1d2012-12-06 18:58:18 +00003666 if (Leaked.empty()) {
3667 C.addTransition(state);
3668 return;
Jordy Rose78612762011-08-23 19:01:07 +00003669 }
3670
Jordan Rose9f61f8a2012-08-18 00:30:16 +00003671 Pred = processLeaks(state, Leaked, C, Pred);
Jordy Rose78612762011-08-23 19:01:07 +00003672
3673 // Did we cache out?
3674 if (!Pred)
3675 return;
3676
3677 // Now generate a new node that nukes the old bindings.
Jordan Roseff03c1d2012-12-06 18:58:18 +00003678 // The only bindings left at this point are the leaked symbols.
Jordan Rose0c153cb2012-11-02 01:54:06 +00003679 RefBindingsTy::Factory &F = state->get_context<RefBindings>();
Jordan Roseff03c1d2012-12-06 18:58:18 +00003680 B = state->get<RefBindings>();
Jordy Rose78612762011-08-23 19:01:07 +00003681
Jordan Roseff03c1d2012-12-06 18:58:18 +00003682 for (SmallVectorImpl<SymbolRef>::iterator I = Leaked.begin(),
3683 E = Leaked.end();
3684 I != E; ++I)
Jordy Rose78612762011-08-23 19:01:07 +00003685 B = F.remove(B, *I);
3686
3687 state = state->set<RefBindings>(B);
Anna Zaksda4c8d62011-10-26 21:06:34 +00003688 C.addTransition(state, Pred);
Jordy Rose78612762011-08-23 19:01:07 +00003689}
3690
Ted Kremenek49b1e382012-01-26 21:29:00 +00003691void RetainCountChecker::printState(raw_ostream &Out, ProgramStateRef State,
Jordy Rose75e680e2011-09-02 06:44:22 +00003692 const char *NL, const char *Sep) const {
Jordy Rose58a20d32011-08-28 19:11:56 +00003693
Jordan Rose0c153cb2012-11-02 01:54:06 +00003694 RefBindingsTy B = State->get<RefBindings>();
Jordy Rose58a20d32011-08-28 19:11:56 +00003695
Ted Kremenekdb70b522013-03-28 18:43:18 +00003696 if (B.isEmpty())
3697 return;
3698
3699 Out << Sep << NL;
Jordy Rose58a20d32011-08-28 19:11:56 +00003700
Jordan Rose0c153cb2012-11-02 01:54:06 +00003701 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Jordy Rose58a20d32011-08-28 19:11:56 +00003702 Out << I->first << " : ";
3703 I->second.print(Out);
3704 Out << NL;
3705 }
Jordy Rose58a20d32011-08-28 19:11:56 +00003706}
3707
3708//===----------------------------------------------------------------------===//
Jordy Rose75e680e2011-09-02 06:44:22 +00003709// Checker registration.
Ted Kremenek819e9b62008-03-11 06:39:11 +00003710//===----------------------------------------------------------------------===//
3711
Jordy Rosec49ec532011-09-02 05:55:19 +00003712void ento::registerRetainCountChecker(CheckerManager &Mgr) {
Ted Kremenek8671acb2013-04-16 21:44:22 +00003713 Mgr.registerChecker<RetainCountChecker>(Mgr.getAnalyzerOptions());
Jordy Rosec49ec532011-09-02 05:55:19 +00003714}
3715
Ted Kremenek71c080f2013-08-14 23:41:49 +00003716//===----------------------------------------------------------------------===//
3717// Implementation of the CallEffects API.
3718//===----------------------------------------------------------------------===//
3719
3720namespace clang { namespace ento { namespace objc_retain {
3721
3722// This is a bit gross, but it allows us to populate CallEffects without
3723// creating a bunch of accessors. This kind is very localized, so the
3724// damage of this macro is limited.
3725#define createCallEffect(D, KIND)\
3726 ASTContext &Ctx = D->getASTContext();\
3727 LangOptions L = Ctx.getLangOpts();\
3728 RetainSummaryManager M(Ctx, L.GCOnly, L.ObjCAutoRefCount);\
3729 const RetainSummary *S = M.get ## KIND ## Summary(D);\
3730 CallEffects CE(S->getRetEffect());\
3731 CE.Receiver = S->getReceiverEffect();\
Ted Kremeneke19529b2013-08-16 23:14:22 +00003732 unsigned N = D->param_size();\
Ted Kremenek71c080f2013-08-14 23:41:49 +00003733 for (unsigned i = 0; i < N; ++i) {\
3734 CE.Args.push_back(S->getArg(i));\
3735 }
3736
3737CallEffects CallEffects::getEffect(const ObjCMethodDecl *MD) {
3738 createCallEffect(MD, Method);
3739 return CE;
3740}
3741
3742CallEffects CallEffects::getEffect(const FunctionDecl *FD) {
3743 createCallEffect(FD, Function);
3744 return CE;
3745}
3746
3747#undef createCallEffect
3748
3749}}}