blob: 098c464eefa349cd44585a3dc119299c66183978 [file] [log] [blame]
Jordy Rose910c4052011-09-02 06:44:22 +00001//==-- RetainCountChecker.cpp - Checks for leaks and other issues -*- C++ -*--//
Ted Kremenek2fff37e2008-03-06 00:08:09 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Jordy Rose910c4052011-09-02 06:44:22 +000010// This file defines the methods for RetainCountChecker, which implements
11// a reference count checker for Core Foundation and Cocoa on (Mac OS X).
Ted Kremenek2fff37e2008-03-06 00:08:09 +000012//
13//===----------------------------------------------------------------------===//
14
Jordy Rose910c4052011-09-02 06:44:22 +000015#include "ClangSACheckers.h"
Mike Stump1eb44332009-09-09 15:08:12 +000016#include "clang/AST/DeclObjC.h"
Ted Kremenekb2771592011-03-30 17:41:19 +000017#include "clang/AST/DeclCXX.h"
Ted Kremenek0b526b42010-02-18 00:05:58 +000018#include "clang/Basic/LangOptions.h"
19#include "clang/Basic/SourceManager.h"
Jordy Rose910c4052011-09-02 06:44:22 +000020#include "clang/Analysis/DomainSpecific/CocoaConventions.h"
Ted Kremenek4c42bb72011-11-14 21:59:21 +000021#include "clang/AST/ParentMap.h"
Jordy Rose910c4052011-09-02 06:44:22 +000022#include "clang/StaticAnalyzer/Core/Checker.h"
23#include "clang/StaticAnalyzer/Core/CheckerManager.h"
Ted Kremenek9b663712011-02-10 01:03:03 +000024#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
25#include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
Jordy Rose910c4052011-09-02 06:44:22 +000026#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
Ted Kremenek18c66fd2011-08-15 22:09:50 +000027#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
Ted Kremenek9b663712011-02-10 01:03:03 +000028#include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
Jordy Rosed1e5a892011-09-02 08:02:59 +000029#include "clang/StaticAnalyzer/Core/PathSensitive/ObjCMessage.h"
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000030#include "llvm/ADT/DenseMap.h"
31#include "llvm/ADT/FoldingSet.h"
Ted Kremenek6d348932008-10-21 15:53:15 +000032#include "llvm/ADT/ImmutableList.h"
Ted Kremenek0b526b42010-02-18 00:05:58 +000033#include "llvm/ADT/ImmutableMap.h"
Benjamin Kramer8fe83e12012-02-04 13:45:25 +000034#include "llvm/ADT/SmallString.h"
Ted Kremenek6ed9afc2008-05-16 18:33:44 +000035#include "llvm/ADT/STLExtras.h"
Ted Kremenek0b526b42010-02-18 00:05:58 +000036#include "llvm/ADT/StringExtras.h"
Chris Lattner5f9e2722011-07-23 10:55:15 +000037#include <cstdarg>
Ted Kremenek2fff37e2008-03-06 00:08:09 +000038
39using namespace clang;
Ted Kremenek9ef65372010-12-23 07:20:52 +000040using namespace ento;
Ted Kremeneka64e89b2010-01-27 06:13:48 +000041using llvm::StrInStrNoCase;
Ted Kremenek4c79e552008-11-05 16:54:44 +000042
Ted Kremenekd775c662010-05-21 21:57:00 +000043namespace {
Jordy Rose910c4052011-09-02 06:44:22 +000044/// Wrapper around different kinds of node builder, so that helper functions
45/// can have a common interface.
Francois Pichetea097852011-01-11 10:41:37 +000046class GenericNodeBuilderRefCount {
Anna Zaks4eff8232011-10-05 23:44:11 +000047 CheckerContext *C;
Ted Kremenekca804532011-08-12 23:04:46 +000048 const ProgramPointTag *tag;
Ted Kremenek9d9d3a62009-05-08 23:09:42 +000049public:
Anna Zaks4eff8232011-10-05 23:44:11 +000050 GenericNodeBuilderRefCount(CheckerContext &c,
Anna Zaksaf498a22011-10-25 19:56:48 +000051 const ProgramPointTag *t = 0)
Anna Zaks6a93bd52011-10-25 19:57:11 +000052 : C(&c), tag(t){}
Zhongxing Xu031ccc02009-08-06 12:48:26 +000053
Ted Kremenek8bef8232012-01-26 21:29:00 +000054 ExplodedNode *MakeNode(ProgramStateRef state, ExplodedNode *Pred,
Anna Zaksf05aac82011-10-18 23:05:58 +000055 bool MarkAsSink = false) {
Anna Zaks0bd6b112011-10-26 21:06:34 +000056 return C->addTransition(state, Pred, tag, MarkAsSink);
Ted Kremenek9d9d3a62009-05-08 23:09:42 +000057 }
58};
59} // end anonymous namespace
60
Ted Kremenek05cbe1a2008-04-09 23:49:11 +000061//===----------------------------------------------------------------------===//
Ted Kremenek553cf182008-06-25 21:21:56 +000062// Primitives used for constructing summaries for function/method calls.
Ted Kremenek05cbe1a2008-04-09 23:49:11 +000063//===----------------------------------------------------------------------===//
64
Ted Kremenek553cf182008-06-25 21:21:56 +000065/// ArgEffect is used to summarize a function/method call's effect on a
66/// particular argument.
Jordy Rosebd85b132011-08-24 19:10:50 +000067enum ArgEffect { DoNothing, Autorelease, Dealloc, DecRef, DecRefMsg,
John McCallf85e1932011-06-15 23:02:42 +000068 DecRefBridgedTransfered,
Jordy Rosebd85b132011-08-24 19:10:50 +000069 IncRefMsg, IncRef, MakeCollectable, MayEscape,
Jordan Rose29299c62012-06-27 00:51:18 +000070 NewAutoreleasePool, StopTracking };
Ted Kremenek553cf182008-06-25 21:21:56 +000071
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000072namespace llvm {
Ted Kremenekb77449c2009-05-03 05:20:50 +000073template <> struct FoldingSetTrait<ArgEffect> {
74static inline void Profile(const ArgEffect X, FoldingSetNodeID& ID) {
75 ID.AddInteger((unsigned) X);
76}
Ted Kremenek553cf182008-06-25 21:21:56 +000077};
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000078} // end llvm namespace
79
Ted Kremenekb77449c2009-05-03 05:20:50 +000080/// ArgEffects summarizes the effects of a function/method call on all of
81/// its arguments.
82typedef llvm::ImmutableMap<unsigned,ArgEffect> ArgEffects;
83
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000084namespace {
Ted Kremenek553cf182008-06-25 21:21:56 +000085
86/// RetEffect is used to summarize a function/method call's behavior with
Mike Stump1eb44332009-09-09 15:08:12 +000087/// respect to its return value.
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +000088class RetEffect {
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000089public:
Jordy Rose76c506f2011-08-21 21:58:18 +000090 enum Kind { NoRet, OwnedSymbol, OwnedAllocatedSymbol,
John McCallf85e1932011-06-15 23:02:42 +000091 NotOwnedSymbol, GCNotOwnedSymbol, ARCNotOwnedSymbol,
Ted Kremenek78a35a32009-05-12 20:06:54 +000092 OwnedWhenTrackedReceiver };
Mike Stump1eb44332009-09-09 15:08:12 +000093
94 enum ObjKind { CF, ObjC, AnyObj };
Ted Kremenek2d1652e2009-01-28 05:56:51 +000095
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000096private:
Ted Kremenek2d1652e2009-01-28 05:56:51 +000097 Kind K;
98 ObjKind O;
Ted Kremenek2d1652e2009-01-28 05:56:51 +000099
Jordy Rose76c506f2011-08-21 21:58:18 +0000100 RetEffect(Kind k, ObjKind o = AnyObj) : K(k), O(o) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000101
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000102public:
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000103 Kind getKind() const { return K; }
104
105 ObjKind getObjKind() const { return O; }
Mike Stump1eb44332009-09-09 15:08:12 +0000106
Ted Kremeneka8833552009-04-29 23:03:22 +0000107 bool isOwned() const {
Ted Kremenek78a35a32009-05-12 20:06:54 +0000108 return K == OwnedSymbol || K == OwnedAllocatedSymbol ||
109 K == OwnedWhenTrackedReceiver;
Ted Kremeneka8833552009-04-29 23:03:22 +0000110 }
Mike Stump1eb44332009-09-09 15:08:12 +0000111
Jordy Rose4df54fe2011-08-23 04:27:15 +0000112 bool operator==(const RetEffect &Other) const {
113 return K == Other.K && O == Other.O;
114 }
115
Ted Kremenek78a35a32009-05-12 20:06:54 +0000116 static RetEffect MakeOwnedWhenTrackedReceiver() {
117 return RetEffect(OwnedWhenTrackedReceiver, ObjC);
118 }
Mike Stump1eb44332009-09-09 15:08:12 +0000119
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000120 static RetEffect MakeOwned(ObjKind o, bool isAllocated = false) {
121 return RetEffect(isAllocated ? OwnedAllocatedSymbol : OwnedSymbol, o);
Mike Stump1eb44332009-09-09 15:08:12 +0000122 }
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000123 static RetEffect MakeNotOwned(ObjKind o) {
124 return RetEffect(NotOwnedSymbol, o);
Ted Kremeneke798e7c2009-04-27 19:14:45 +0000125 }
126 static RetEffect MakeGCNotOwned() {
127 return RetEffect(GCNotOwnedSymbol, ObjC);
128 }
John McCallf85e1932011-06-15 23:02:42 +0000129 static RetEffect MakeARCNotOwned() {
130 return RetEffect(ARCNotOwnedSymbol, ObjC);
131 }
Ted Kremenek553cf182008-06-25 21:21:56 +0000132 static RetEffect MakeNoRet() {
133 return RetEffect(NoRet);
Ted Kremeneka7344702008-06-23 18:02:52 +0000134 }
Jordy Roseef945882012-03-18 01:26:10 +0000135
136 void Profile(llvm::FoldingSetNodeID& ID) const {
137 ID.AddInteger((unsigned) K);
138 ID.AddInteger((unsigned) O);
139 }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000140};
Mike Stump1eb44332009-09-09 15:08:12 +0000141
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000142//===----------------------------------------------------------------------===//
143// Reference-counting logic (typestate + counts).
144//===----------------------------------------------------------------------===//
Mike Stump1eb44332009-09-09 15:08:12 +0000145
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000146class RefVal {
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000147public:
148 enum Kind {
149 Owned = 0, // Owning reference.
150 NotOwned, // Reference is not owned by still valid (not freed).
151 Released, // Object has been released.
152 ReturnedOwned, // Returned object passes ownership to caller.
153 ReturnedNotOwned, // Return object does not pass ownership to caller.
154 ERROR_START,
155 ErrorDeallocNotOwned, // -dealloc called on non-owned object.
156 ErrorDeallocGC, // Calling -dealloc with GC enabled.
157 ErrorUseAfterRelease, // Object used after released.
158 ErrorReleaseNotOwned, // Release of an object that was not owned.
159 ERROR_LEAK_START,
160 ErrorLeak, // A memory leak due to excessive reference counts.
161 ErrorLeakReturned, // A memory leak due to the returning method not having
162 // the correct naming conventions.
163 ErrorGCLeakReturned,
164 ErrorOverAutorelease,
165 ErrorReturnedNotOwned
166 };
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000167
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000168private:
169 Kind kind;
170 RetEffect::ObjKind okind;
171 unsigned Cnt;
172 unsigned ACnt;
173 QualType T;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000174
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000175 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, unsigned acnt, QualType t)
176 : kind(k), okind(o), Cnt(cnt), ACnt(acnt), T(t) {}
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000177
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000178public:
179 Kind getKind() const { return kind; }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000180
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000181 RetEffect::ObjKind getObjKind() const { return okind; }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000182
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000183 unsigned getCount() const { return Cnt; }
184 unsigned getAutoreleaseCount() const { return ACnt; }
185 unsigned getCombinedCounts() const { return Cnt + ACnt; }
186 void clearCounts() { Cnt = 0; ACnt = 0; }
187 void setCount(unsigned i) { Cnt = i; }
188 void setAutoreleaseCount(unsigned i) { ACnt = i; }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000189
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000190 QualType getType() const { return T; }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000191
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000192 bool isOwned() const {
193 return getKind() == Owned;
194 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000195
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000196 bool isNotOwned() const {
197 return getKind() == NotOwned;
198 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000199
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000200 bool isReturnedOwned() const {
201 return getKind() == ReturnedOwned;
202 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000203
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000204 bool isReturnedNotOwned() const {
205 return getKind() == ReturnedNotOwned;
206 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000207
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000208 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
209 unsigned Count = 1) {
210 return RefVal(Owned, o, Count, 0, t);
211 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000212
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000213 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
214 unsigned Count = 0) {
215 return RefVal(NotOwned, o, Count, 0, t);
216 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000217
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000218 // Comparison, profiling, and pretty-printing.
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000219
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000220 bool operator==(const RefVal& X) const {
221 return kind == X.kind && Cnt == X.Cnt && T == X.T && ACnt == X.ACnt;
222 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000223
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000224 RefVal operator-(size_t i) const {
225 return RefVal(getKind(), getObjKind(), getCount() - i,
226 getAutoreleaseCount(), getType());
227 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000228
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000229 RefVal operator+(size_t i) const {
230 return RefVal(getKind(), getObjKind(), getCount() + i,
231 getAutoreleaseCount(), getType());
232 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000233
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000234 RefVal operator^(Kind k) const {
235 return RefVal(k, getObjKind(), getCount(), getAutoreleaseCount(),
236 getType());
237 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000238
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000239 RefVal autorelease() const {
240 return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount()+1,
241 getType());
242 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000243
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000244 void Profile(llvm::FoldingSetNodeID& ID) const {
245 ID.AddInteger((unsigned) kind);
246 ID.AddInteger(Cnt);
247 ID.AddInteger(ACnt);
248 ID.Add(T);
249 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000250
Ted Kremenek9c378f72011-08-12 23:37:29 +0000251 void print(raw_ostream &Out) const;
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000252};
253
Ted Kremenek9c378f72011-08-12 23:37:29 +0000254void RefVal::print(raw_ostream &Out) const {
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000255 if (!T.isNull())
Jordy Rosedbd658e2011-08-28 19:11:56 +0000256 Out << "Tracked " << T.getAsString() << '/';
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000257
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000258 switch (getKind()) {
Jordy Rose910c4052011-09-02 06:44:22 +0000259 default: llvm_unreachable("Invalid RefVal kind");
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000260 case Owned: {
261 Out << "Owned";
262 unsigned cnt = getCount();
263 if (cnt) Out << " (+ " << cnt << ")";
264 break;
265 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000266
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000267 case NotOwned: {
268 Out << "NotOwned";
269 unsigned cnt = getCount();
270 if (cnt) Out << " (+ " << cnt << ")";
271 break;
272 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000273
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000274 case ReturnedOwned: {
275 Out << "ReturnedOwned";
276 unsigned cnt = getCount();
277 if (cnt) Out << " (+ " << cnt << ")";
278 break;
279 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000280
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000281 case ReturnedNotOwned: {
282 Out << "ReturnedNotOwned";
283 unsigned cnt = getCount();
284 if (cnt) Out << " (+ " << cnt << ")";
285 break;
286 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000287
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000288 case Released:
289 Out << "Released";
290 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000291
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000292 case ErrorDeallocGC:
293 Out << "-dealloc (GC)";
294 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000295
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000296 case ErrorDeallocNotOwned:
297 Out << "-dealloc (not-owned)";
298 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000299
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000300 case ErrorLeak:
301 Out << "Leaked";
302 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000303
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000304 case ErrorLeakReturned:
305 Out << "Leaked (Bad naming)";
306 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000307
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000308 case ErrorGCLeakReturned:
309 Out << "Leaked (GC-ed at return)";
310 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000311
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000312 case ErrorUseAfterRelease:
313 Out << "Use-After-Release [ERROR]";
314 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000315
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000316 case ErrorReleaseNotOwned:
317 Out << "Release of Not-Owned [ERROR]";
318 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000319
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000320 case RefVal::ErrorOverAutorelease:
321 Out << "Over autoreleased";
322 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000323
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000324 case RefVal::ErrorReturnedNotOwned:
325 Out << "Non-owned object returned instead of owned";
326 break;
327 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000328
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000329 if (ACnt) {
330 Out << " [ARC +" << ACnt << ']';
331 }
332}
333} //end anonymous namespace
334
335//===----------------------------------------------------------------------===//
336// RefBindings - State used to track object reference counts.
337//===----------------------------------------------------------------------===//
338
339typedef llvm::ImmutableMap<SymbolRef, RefVal> RefBindings;
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000340
341namespace clang {
Ted Kremenek9ef65372010-12-23 07:20:52 +0000342namespace ento {
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000343template<>
344struct ProgramStateTrait<RefBindings>
345 : public ProgramStatePartialTrait<RefBindings> {
346 static void *GDMIndex() {
347 static int RefBIndex = 0;
348 return &RefBIndex;
349 }
350};
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000351}
Argyrios Kyrtzidis5a4f98f2010-12-22 18:53:20 +0000352}
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000353
354//===----------------------------------------------------------------------===//
Jordy Rose910c4052011-09-02 06:44:22 +0000355// Function/Method behavior summaries.
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000356//===----------------------------------------------------------------------===//
357
358namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000359class RetainSummary {
Jordy Roseef945882012-03-18 01:26:10 +0000360 /// Args - a map of (index, ArgEffect) pairs, where index
Ted Kremenek1bffd742008-05-06 15:44:25 +0000361 /// specifies the argument (starting from 0). This can be sparsely
362 /// populated; arguments with no entry in Args use 'DefaultArgEffect'.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000363 ArgEffects Args;
Mike Stump1eb44332009-09-09 15:08:12 +0000364
Ted Kremenek1bffd742008-05-06 15:44:25 +0000365 /// DefaultArgEffect - The default ArgEffect to apply to arguments that
366 /// do not have an entry in Args.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000367 ArgEffect DefaultArgEffect;
Mike Stump1eb44332009-09-09 15:08:12 +0000368
Ted Kremenek553cf182008-06-25 21:21:56 +0000369 /// Receiver - If this summary applies to an Objective-C message expression,
370 /// this is the effect applied to the state of the receiver.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000371 ArgEffect Receiver;
Mike Stump1eb44332009-09-09 15:08:12 +0000372
Ted Kremenek553cf182008-06-25 21:21:56 +0000373 /// Ret - The effect on the return value. Used to indicate if the
Jordy Rose76c506f2011-08-21 21:58:18 +0000374 /// function/method call returns a new tracked symbol.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000375 RetEffect Ret;
Mike Stump1eb44332009-09-09 15:08:12 +0000376
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000377public:
Ted Kremenekb77449c2009-05-03 05:20:50 +0000378 RetainSummary(ArgEffects A, RetEffect R, ArgEffect defaultEff,
Jordy Rosee62e87b2011-08-20 20:55:40 +0000379 ArgEffect ReceiverEff)
380 : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000381
Ted Kremenek553cf182008-06-25 21:21:56 +0000382 /// getArg - Return the argument effect on the argument specified by
383 /// idx (starting from 0).
Ted Kremenek1ac08d62008-03-11 17:48:22 +0000384 ArgEffect getArg(unsigned idx) const {
Ted Kremenekb77449c2009-05-03 05:20:50 +0000385 if (const ArgEffect *AE = Args.lookup(idx))
386 return *AE;
Mike Stump1eb44332009-09-09 15:08:12 +0000387
Ted Kremenek1bffd742008-05-06 15:44:25 +0000388 return DefaultArgEffect;
Ted Kremenek1ac08d62008-03-11 17:48:22 +0000389 }
Ted Kremenek11fe1752011-01-27 18:43:03 +0000390
391 void addArg(ArgEffects::Factory &af, unsigned idx, ArgEffect e) {
392 Args = af.add(Args, idx, e);
393 }
Mike Stump1eb44332009-09-09 15:08:12 +0000394
Ted Kremenek885c27b2009-05-04 05:31:22 +0000395 /// setDefaultArgEffect - Set the default argument effect.
396 void setDefaultArgEffect(ArgEffect E) {
397 DefaultArgEffect = E;
398 }
Mike Stump1eb44332009-09-09 15:08:12 +0000399
Ted Kremenek553cf182008-06-25 21:21:56 +0000400 /// getRetEffect - Returns the effect on the return value of the call.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000401 RetEffect getRetEffect() const { return Ret; }
Mike Stump1eb44332009-09-09 15:08:12 +0000402
Ted Kremenek885c27b2009-05-04 05:31:22 +0000403 /// setRetEffect - Set the effect of the return value of the call.
404 void setRetEffect(RetEffect E) { Ret = E; }
Mike Stump1eb44332009-09-09 15:08:12 +0000405
Ted Kremenek12b94342011-01-27 06:54:14 +0000406
407 /// Sets the effect on the receiver of the message.
408 void setReceiverEffect(ArgEffect e) { Receiver = e; }
409
Ted Kremenek553cf182008-06-25 21:21:56 +0000410 /// getReceiverEffect - Returns the effect on the receiver of the call.
411 /// This is only meaningful if the summary applies to an ObjCMessageExpr*.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000412 ArgEffect getReceiverEffect() const { return Receiver; }
Jordy Rose4df54fe2011-08-23 04:27:15 +0000413
414 /// Test if two retain summaries are identical. Note that merely equivalent
415 /// summaries are not necessarily identical (for example, if an explicit
416 /// argument effect matches the default effect).
417 bool operator==(const RetainSummary &Other) const {
418 return Args == Other.Args && DefaultArgEffect == Other.DefaultArgEffect &&
419 Receiver == Other.Receiver && Ret == Other.Ret;
420 }
Jordy Roseef945882012-03-18 01:26:10 +0000421
422 /// Profile this summary for inclusion in a FoldingSet.
423 void Profile(llvm::FoldingSetNodeID& ID) const {
424 ID.Add(Args);
425 ID.Add(DefaultArgEffect);
426 ID.Add(Receiver);
427 ID.Add(Ret);
428 }
429
430 /// A retain summary is simple if it has no ArgEffects other than the default.
431 bool isSimple() const {
432 return Args.isEmpty();
433 }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000434};
Ted Kremenek4f22a782008-06-23 23:30:29 +0000435} // end anonymous namespace
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000436
Ted Kremenek553cf182008-06-25 21:21:56 +0000437//===----------------------------------------------------------------------===//
438// Data structures for constructing summaries.
439//===----------------------------------------------------------------------===//
Ted Kremenek53301ba2008-06-24 03:49:48 +0000440
Ted Kremenek553cf182008-06-25 21:21:56 +0000441namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000442class ObjCSummaryKey {
Ted Kremenek553cf182008-06-25 21:21:56 +0000443 IdentifierInfo* II;
444 Selector S;
Mike Stump1eb44332009-09-09 15:08:12 +0000445public:
Ted Kremenek553cf182008-06-25 21:21:56 +0000446 ObjCSummaryKey(IdentifierInfo* ii, Selector s)
447 : II(ii), S(s) {}
448
Ted Kremenek9c378f72011-08-12 23:37:29 +0000449 ObjCSummaryKey(const ObjCInterfaceDecl *d, Selector s)
Ted Kremenek553cf182008-06-25 21:21:56 +0000450 : II(d ? d->getIdentifier() : 0), S(s) {}
Ted Kremenek70b6a832009-05-13 18:16:01 +0000451
Ted Kremenek9c378f72011-08-12 23:37:29 +0000452 ObjCSummaryKey(const ObjCInterfaceDecl *d, IdentifierInfo *ii, Selector s)
Ted Kremenek70b6a832009-05-13 18:16:01 +0000453 : II(d ? d->getIdentifier() : ii), S(s) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000454
Ted Kremenek553cf182008-06-25 21:21:56 +0000455 ObjCSummaryKey(Selector s)
456 : II(0), S(s) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000457
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000458 IdentifierInfo *getIdentifier() const { return II; }
Ted Kremenek553cf182008-06-25 21:21:56 +0000459 Selector getSelector() const { return S; }
460};
Ted Kremenek4f22a782008-06-23 23:30:29 +0000461}
462
463namespace llvm {
Ted Kremenek553cf182008-06-25 21:21:56 +0000464template <> struct DenseMapInfo<ObjCSummaryKey> {
465 static inline ObjCSummaryKey getEmptyKey() {
466 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
467 DenseMapInfo<Selector>::getEmptyKey());
468 }
Mike Stump1eb44332009-09-09 15:08:12 +0000469
Ted Kremenek553cf182008-06-25 21:21:56 +0000470 static inline ObjCSummaryKey getTombstoneKey() {
471 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
Mike Stump1eb44332009-09-09 15:08:12 +0000472 DenseMapInfo<Selector>::getTombstoneKey());
Ted Kremenek553cf182008-06-25 21:21:56 +0000473 }
Mike Stump1eb44332009-09-09 15:08:12 +0000474
Ted Kremenek553cf182008-06-25 21:21:56 +0000475 static unsigned getHashValue(const ObjCSummaryKey &V) {
Benjamin Kramer28b23072012-05-27 13:28:44 +0000476 typedef std::pair<IdentifierInfo*, Selector> PairTy;
477 return DenseMapInfo<PairTy>::getHashValue(PairTy(V.getIdentifier(),
478 V.getSelector()));
Ted Kremenek553cf182008-06-25 21:21:56 +0000479 }
Mike Stump1eb44332009-09-09 15:08:12 +0000480
Ted Kremenek553cf182008-06-25 21:21:56 +0000481 static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
Benjamin Kramer28b23072012-05-27 13:28:44 +0000482 return LHS.getIdentifier() == RHS.getIdentifier() &&
483 LHS.getSelector() == RHS.getSelector();
Ted Kremenek553cf182008-06-25 21:21:56 +0000484 }
Mike Stump1eb44332009-09-09 15:08:12 +0000485
Ted Kremenek553cf182008-06-25 21:21:56 +0000486};
Chris Lattner06159e82009-12-15 07:26:51 +0000487template <>
488struct isPodLike<ObjCSummaryKey> { static const bool value = true; };
Ted Kremenek4f22a782008-06-23 23:30:29 +0000489} // end llvm namespace
Mike Stump1eb44332009-09-09 15:08:12 +0000490
Ted Kremenek4f22a782008-06-23 23:30:29 +0000491namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000492class ObjCSummaryCache {
Ted Kremenek93edbc52011-10-05 23:54:29 +0000493 typedef llvm::DenseMap<ObjCSummaryKey, const RetainSummary *> MapTy;
Ted Kremenek553cf182008-06-25 21:21:56 +0000494 MapTy M;
495public:
496 ObjCSummaryCache() {}
Mike Stump1eb44332009-09-09 15:08:12 +0000497
Ted Kremenek93edbc52011-10-05 23:54:29 +0000498 const RetainSummary * find(const ObjCInterfaceDecl *D, IdentifierInfo *ClsName,
Ted Kremeneka8833552009-04-29 23:03:22 +0000499 Selector S) {
Ted Kremenek8711c032009-04-29 05:04:30 +0000500 // Lookup the method using the decl for the class @interface. If we
501 // have no decl, lookup using the class name.
502 return D ? find(D, S) : find(ClsName, S);
503 }
Mike Stump1eb44332009-09-09 15:08:12 +0000504
Ted Kremenek93edbc52011-10-05 23:54:29 +0000505 const RetainSummary * find(const ObjCInterfaceDecl *D, Selector S) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000506 // Do a lookup with the (D,S) pair. If we find a match return
507 // the iterator.
508 ObjCSummaryKey K(D, S);
509 MapTy::iterator I = M.find(K);
Mike Stump1eb44332009-09-09 15:08:12 +0000510
Ted Kremenek553cf182008-06-25 21:21:56 +0000511 if (I != M.end() || !D)
Ted Kremenek614cc542009-07-21 23:27:57 +0000512 return I->second;
Mike Stump1eb44332009-09-09 15:08:12 +0000513
Ted Kremenek553cf182008-06-25 21:21:56 +0000514 // Walk the super chain. If we find a hit with a parent, we'll end
515 // up returning that summary. We actually allow that key (null,S), as
516 // we cache summaries for the null ObjCInterfaceDecl* to allow us to
517 // generate initial summaries without having to worry about NSObject
518 // being declared.
519 // FIXME: We may change this at some point.
Ted Kremenek9c378f72011-08-12 23:37:29 +0000520 for (ObjCInterfaceDecl *C=D->getSuperClass() ;; C=C->getSuperClass()) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000521 if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
522 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000523
Ted Kremenek553cf182008-06-25 21:21:56 +0000524 if (!C)
Ted Kremenek614cc542009-07-21 23:27:57 +0000525 return NULL;
Ted Kremenek553cf182008-06-25 21:21:56 +0000526 }
Mike Stump1eb44332009-09-09 15:08:12 +0000527
528 // Cache the summary with original key to make the next lookup faster
Ted Kremenek553cf182008-06-25 21:21:56 +0000529 // and return the iterator.
Ted Kremenek93edbc52011-10-05 23:54:29 +0000530 const RetainSummary *Summ = I->second;
Ted Kremenek614cc542009-07-21 23:27:57 +0000531 M[K] = Summ;
532 return Summ;
Ted Kremenek553cf182008-06-25 21:21:56 +0000533 }
Mike Stump1eb44332009-09-09 15:08:12 +0000534
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000535 const RetainSummary *find(IdentifierInfo* II, Selector S) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000536 // FIXME: Class method lookup. Right now we dont' have a good way
537 // of going between IdentifierInfo* and the class hierarchy.
Ted Kremenek614cc542009-07-21 23:27:57 +0000538 MapTy::iterator I = M.find(ObjCSummaryKey(II, S));
Mike Stump1eb44332009-09-09 15:08:12 +0000539
Ted Kremenek614cc542009-07-21 23:27:57 +0000540 if (I == M.end())
541 I = M.find(ObjCSummaryKey(S));
Mike Stump1eb44332009-09-09 15:08:12 +0000542
Ted Kremenek614cc542009-07-21 23:27:57 +0000543 return I == M.end() ? NULL : I->second;
Ted Kremenek553cf182008-06-25 21:21:56 +0000544 }
Mike Stump1eb44332009-09-09 15:08:12 +0000545
Ted Kremenek93edbc52011-10-05 23:54:29 +0000546 const RetainSummary *& operator[](ObjCSummaryKey K) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000547 return M[K];
548 }
Mike Stump1eb44332009-09-09 15:08:12 +0000549
Ted Kremenek93edbc52011-10-05 23:54:29 +0000550 const RetainSummary *& operator[](Selector S) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000551 return M[ ObjCSummaryKey(S) ];
552 }
Mike Stump1eb44332009-09-09 15:08:12 +0000553};
Ted Kremenek553cf182008-06-25 21:21:56 +0000554} // end anonymous namespace
555
556//===----------------------------------------------------------------------===//
557// Data structures for managing collections of summaries.
558//===----------------------------------------------------------------------===//
559
560namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000561class RetainSummaryManager {
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000562
563 //==-----------------------------------------------------------------==//
564 // Typedefs.
565 //==-----------------------------------------------------------------==//
Mike Stump1eb44332009-09-09 15:08:12 +0000566
Ted Kremenek93edbc52011-10-05 23:54:29 +0000567 typedef llvm::DenseMap<const FunctionDecl*, const RetainSummary *>
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000568 FuncSummariesTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000569
Ted Kremenek4f22a782008-06-23 23:30:29 +0000570 typedef ObjCSummaryCache ObjCMethodSummariesTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000571
Jordy Roseef945882012-03-18 01:26:10 +0000572 typedef llvm::FoldingSetNodeWrapper<RetainSummary> CachedSummaryNode;
573
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000574 //==-----------------------------------------------------------------==//
575 // Data.
576 //==-----------------------------------------------------------------==//
Mike Stump1eb44332009-09-09 15:08:12 +0000577
Ted Kremenek553cf182008-06-25 21:21:56 +0000578 /// Ctx - The ASTContext object for the analyzed ASTs.
Ted Kremenek9c378f72011-08-12 23:37:29 +0000579 ASTContext &Ctx;
Ted Kremenek179064e2008-07-01 17:21:27 +0000580
Ted Kremenek553cf182008-06-25 21:21:56 +0000581 /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
Ted Kremenek377e2302008-04-29 05:33:51 +0000582 const bool GCEnabled;
Mike Stump1eb44332009-09-09 15:08:12 +0000583
John McCallf85e1932011-06-15 23:02:42 +0000584 /// Records whether or not the analyzed code runs in ARC mode.
585 const bool ARCEnabled;
586
Ted Kremenek553cf182008-06-25 21:21:56 +0000587 /// FuncSummaries - A map from FunctionDecls to summaries.
Mike Stump1eb44332009-09-09 15:08:12 +0000588 FuncSummariesTy FuncSummaries;
589
Ted Kremenek553cf182008-06-25 21:21:56 +0000590 /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
591 /// to summaries.
Ted Kremenek1f180c32008-06-23 22:21:20 +0000592 ObjCMethodSummariesTy ObjCClassMethodSummaries;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000593
Ted Kremenek553cf182008-06-25 21:21:56 +0000594 /// ObjCMethodSummaries - A map from selectors to summaries.
Ted Kremenek1f180c32008-06-23 22:21:20 +0000595 ObjCMethodSummariesTy ObjCMethodSummaries;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000596
Ted Kremenek553cf182008-06-25 21:21:56 +0000597 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
598 /// and all other data used by the checker.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000599 llvm::BumpPtrAllocator BPAlloc;
Mike Stump1eb44332009-09-09 15:08:12 +0000600
Ted Kremenekb77449c2009-05-03 05:20:50 +0000601 /// AF - A factory for ArgEffects objects.
Mike Stump1eb44332009-09-09 15:08:12 +0000602 ArgEffects::Factory AF;
603
Ted Kremenek553cf182008-06-25 21:21:56 +0000604 /// ScratchArgs - A holding buffer for construct ArgEffects.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000605 ArgEffects ScratchArgs;
Mike Stump1eb44332009-09-09 15:08:12 +0000606
Ted Kremenekec315332009-05-07 23:40:42 +0000607 /// ObjCAllocRetE - Default return effect for methods returning Objective-C
608 /// objects.
609 RetEffect ObjCAllocRetE;
Ted Kremenek547d4952009-06-05 23:18:01 +0000610
Mike Stump1eb44332009-09-09 15:08:12 +0000611 /// ObjCInitRetE - Default return effect for init methods returning
Ted Kremenekac02f202009-08-20 05:13:36 +0000612 /// Objective-C objects.
Ted Kremenek547d4952009-06-05 23:18:01 +0000613 RetEffect ObjCInitRetE;
Mike Stump1eb44332009-09-09 15:08:12 +0000614
Jordy Roseef945882012-03-18 01:26:10 +0000615 /// SimpleSummaries - Used for uniquing summaries that don't have special
616 /// effects.
617 llvm::FoldingSet<CachedSummaryNode> SimpleSummaries;
Mike Stump1eb44332009-09-09 15:08:12 +0000618
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000619 //==-----------------------------------------------------------------==//
620 // Methods.
621 //==-----------------------------------------------------------------==//
Mike Stump1eb44332009-09-09 15:08:12 +0000622
Ted Kremenek553cf182008-06-25 21:21:56 +0000623 /// getArgEffects - Returns a persistent ArgEffects object based on the
624 /// data in ScratchArgs.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000625 ArgEffects getArgEffects();
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000626
Mike Stump1eb44332009-09-09 15:08:12 +0000627 enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
628
Ted Kremenek896cd9d2008-10-23 01:56:15 +0000629public:
Ted Kremenek78a35a32009-05-12 20:06:54 +0000630 RetEffect getObjAllocRetEffect() const { return ObjCAllocRetE; }
Ted Kremenek93edbc52011-10-05 23:54:29 +0000631
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000632 const RetainSummary *getUnarySummary(const FunctionType* FT,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000633 UnaryFuncKind func);
Mike Stump1eb44332009-09-09 15:08:12 +0000634
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000635 const RetainSummary *getCFSummaryCreateRule(const FunctionDecl *FD);
636 const RetainSummary *getCFSummaryGetRule(const FunctionDecl *FD);
637 const RetainSummary *getCFCreateGetRuleSummary(const FunctionDecl *FD);
Mike Stump1eb44332009-09-09 15:08:12 +0000638
Jordy Roseef945882012-03-18 01:26:10 +0000639 const RetainSummary *getPersistentSummary(const RetainSummary &OldSumm);
Ted Kremenek706522f2008-10-29 04:07:07 +0000640
Jordy Roseef945882012-03-18 01:26:10 +0000641 const RetainSummary *getPersistentSummary(RetEffect RetEff,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000642 ArgEffect ReceiverEff = DoNothing,
643 ArgEffect DefaultEff = MayEscape) {
Jordy Roseef945882012-03-18 01:26:10 +0000644 RetainSummary Summ(getArgEffects(), RetEff, DefaultEff, ReceiverEff);
645 return getPersistentSummary(Summ);
646 }
647
Ted Kremenekc91fdf62012-05-08 00:12:09 +0000648 const RetainSummary *getDoNothingSummary() {
649 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
650 }
651
Jordy Roseef945882012-03-18 01:26:10 +0000652 const RetainSummary *getDefaultSummary() {
653 return getPersistentSummary(RetEffect::MakeNoRet(),
654 DoNothing, MayEscape);
Ted Kremenek9c32d082008-05-06 00:30:21 +0000655 }
Mike Stump1eb44332009-09-09 15:08:12 +0000656
Ted Kremenek93edbc52011-10-05 23:54:29 +0000657 const RetainSummary *getPersistentStopSummary() {
Jordy Roseef945882012-03-18 01:26:10 +0000658 return getPersistentSummary(RetEffect::MakeNoRet(),
659 StopTracking, StopTracking);
Mike Stump1eb44332009-09-09 15:08:12 +0000660 }
Ted Kremenekb3095252008-05-06 04:20:12 +0000661
Ted Kremenek1f180c32008-06-23 22:21:20 +0000662 void InitializeClassMethodSummaries();
663 void InitializeMethodSummaries();
Ted Kremenek896cd9d2008-10-23 01:56:15 +0000664private:
Ted Kremenek93edbc52011-10-05 23:54:29 +0000665 void addNSObjectClsMethSummary(Selector S, const RetainSummary *Summ) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000666 ObjCClassMethodSummaries[S] = Summ;
667 }
Mike Stump1eb44332009-09-09 15:08:12 +0000668
Ted Kremenek93edbc52011-10-05 23:54:29 +0000669 void addNSObjectMethSummary(Selector S, const RetainSummary *Summ) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000670 ObjCMethodSummaries[S] = Summ;
671 }
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +0000672
Ted Kremeneka9797122012-02-18 21:37:48 +0000673 void addClassMethSummary(const char* Cls, const char* name,
674 const RetainSummary *Summ, bool isNullary = true) {
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +0000675 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
Ted Kremeneka9797122012-02-18 21:37:48 +0000676 Selector S = isNullary ? GetNullarySelector(name, Ctx)
677 : GetUnarySelector(name, Ctx);
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +0000678 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
679 }
Mike Stump1eb44332009-09-09 15:08:12 +0000680
Ted Kremenek6c4becb2009-02-25 02:54:57 +0000681 void addInstMethSummary(const char* Cls, const char* nullaryName,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000682 const RetainSummary *Summ) {
Ted Kremenek6c4becb2009-02-25 02:54:57 +0000683 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
684 Selector S = GetNullarySelector(nullaryName, Ctx);
685 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
686 }
Mike Stump1eb44332009-09-09 15:08:12 +0000687
Ted Kremenekde4d5332009-04-24 17:50:11 +0000688 Selector generateSelector(va_list argp) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000689 SmallVector<IdentifierInfo*, 10> II;
Ted Kremenekde4d5332009-04-24 17:50:11 +0000690
Ted Kremenek9e476de2008-08-12 18:30:56 +0000691 while (const char* s = va_arg(argp, const char*))
692 II.push_back(&Ctx.Idents.get(s));
Ted Kremenekde4d5332009-04-24 17:50:11 +0000693
Mike Stump1eb44332009-09-09 15:08:12 +0000694 return Ctx.Selectors.getSelector(II.size(), &II[0]);
Ted Kremenekde4d5332009-04-24 17:50:11 +0000695 }
Mike Stump1eb44332009-09-09 15:08:12 +0000696
Ted Kremenekde4d5332009-04-24 17:50:11 +0000697 void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy& Summaries,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000698 const RetainSummary * Summ, va_list argp) {
Ted Kremenekde4d5332009-04-24 17:50:11 +0000699 Selector S = generateSelector(argp);
700 Summaries[ObjCSummaryKey(ClsII, S)] = Summ;
Ted Kremenek70a733e2008-07-18 17:24:20 +0000701 }
Mike Stump1eb44332009-09-09 15:08:12 +0000702
Ted Kremenek93edbc52011-10-05 23:54:29 +0000703 void addInstMethSummary(const char* Cls, const RetainSummary * Summ, ...) {
Ted Kremenekaf9dc272008-08-12 18:48:50 +0000704 va_list argp;
705 va_start(argp, Summ);
Ted Kremenekde4d5332009-04-24 17:50:11 +0000706 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Mike Stump1eb44332009-09-09 15:08:12 +0000707 va_end(argp);
Ted Kremenekaf9dc272008-08-12 18:48:50 +0000708 }
Mike Stump1eb44332009-09-09 15:08:12 +0000709
Ted Kremenek93edbc52011-10-05 23:54:29 +0000710 void addClsMethSummary(const char* Cls, const RetainSummary * Summ, ...) {
Ted Kremenekde4d5332009-04-24 17:50:11 +0000711 va_list argp;
712 va_start(argp, Summ);
713 addMethodSummary(&Ctx.Idents.get(Cls),ObjCClassMethodSummaries, Summ, argp);
714 va_end(argp);
715 }
Mike Stump1eb44332009-09-09 15:08:12 +0000716
Ted Kremenek93edbc52011-10-05 23:54:29 +0000717 void addClsMethSummary(IdentifierInfo *II, const RetainSummary * Summ, ...) {
Ted Kremenekde4d5332009-04-24 17:50:11 +0000718 va_list argp;
719 va_start(argp, Summ);
720 addMethodSummary(II, ObjCClassMethodSummaries, Summ, argp);
721 va_end(argp);
722 }
723
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000724public:
Mike Stump1eb44332009-09-09 15:08:12 +0000725
Ted Kremenek9c378f72011-08-12 23:37:29 +0000726 RetainSummaryManager(ASTContext &ctx, bool gcenabled, bool usesARC)
Ted Kremenek179064e2008-07-01 17:21:27 +0000727 : Ctx(ctx),
John McCallf85e1932011-06-15 23:02:42 +0000728 GCEnabled(gcenabled),
729 ARCEnabled(usesARC),
730 AF(BPAlloc), ScratchArgs(AF.getEmptyMap()),
731 ObjCAllocRetE(gcenabled
732 ? RetEffect::MakeGCNotOwned()
733 : (usesARC ? RetEffect::MakeARCNotOwned()
734 : RetEffect::MakeOwned(RetEffect::ObjC, true))),
735 ObjCInitRetE(gcenabled
736 ? RetEffect::MakeGCNotOwned()
737 : (usesARC ? RetEffect::MakeARCNotOwned()
Jordy Roseef945882012-03-18 01:26:10 +0000738 : RetEffect::MakeOwnedWhenTrackedReceiver())) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000739 InitializeClassMethodSummaries();
740 InitializeMethodSummaries();
741 }
Mike Stump1eb44332009-09-09 15:08:12 +0000742
Anna Zaks58822c42012-05-04 22:18:39 +0000743 const RetainSummary *getSummary(const FunctionDecl *FD,
744 const CallOrObjCMessage *CME = 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000745
Jordy Rosef3aae582012-03-17 21:13:07 +0000746 const RetainSummary *getMethodSummary(Selector S, IdentifierInfo *ClsName,
747 const ObjCInterfaceDecl *ID,
748 const ObjCMethodDecl *MD,
749 QualType RetTy,
750 ObjCMethodSummariesTy &CachedSummaries);
751
Ted Kremenek93edbc52011-10-05 23:54:29 +0000752 const RetainSummary *getInstanceMethodSummary(const ObjCMessage &msg,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000753 ProgramStateRef state,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000754 const LocationContext *LC);
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000755
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000756 const RetainSummary *getInstanceMethodSummary(const ObjCMessage &msg,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000757 const ObjCInterfaceDecl *ID) {
Jordy Rosef3aae582012-03-17 21:13:07 +0000758 return getMethodSummary(msg.getSelector(), 0, ID, msg.getMethodDecl(),
759 msg.getType(Ctx), ObjCMethodSummaries);
Ted Kremenek8711c032009-04-29 05:04:30 +0000760 }
Mike Stump1eb44332009-09-09 15:08:12 +0000761
Ted Kremenek93edbc52011-10-05 23:54:29 +0000762 const RetainSummary *getClassMethodSummary(const ObjCMessage &msg) {
Argyrios Kyrtzidis432424d2011-01-25 00:03:53 +0000763 const ObjCInterfaceDecl *Class = 0;
764 if (!msg.isInstanceMessage())
765 Class = msg.getReceiverInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +0000766
Jordy Rosef3aae582012-03-17 21:13:07 +0000767 return getMethodSummary(msg.getSelector(), Class->getIdentifier(),
768 Class, msg.getMethodDecl(), msg.getType(Ctx),
769 ObjCClassMethodSummaries);
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +0000770 }
Ted Kremenek552333c2009-04-29 17:17:48 +0000771
772 /// getMethodSummary - This version of getMethodSummary is used to query
773 /// the summary for the current method being analyzed.
Ted Kremenek93edbc52011-10-05 23:54:29 +0000774 const RetainSummary *getMethodSummary(const ObjCMethodDecl *MD) {
Ted Kremeneka8833552009-04-29 23:03:22 +0000775 // FIXME: Eventually this should be unneeded.
Ted Kremeneka8833552009-04-29 23:03:22 +0000776 const ObjCInterfaceDecl *ID = MD->getClassInterface();
Ted Kremenek70a65762009-04-30 05:41:14 +0000777 Selector S = MD->getSelector();
Ted Kremenek552333c2009-04-29 17:17:48 +0000778 IdentifierInfo *ClsName = ID->getIdentifier();
779 QualType ResultTy = MD->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +0000780
Jordy Rosef3aae582012-03-17 21:13:07 +0000781 ObjCMethodSummariesTy *CachedSummaries;
Ted Kremenek552333c2009-04-29 17:17:48 +0000782 if (MD->isInstanceMethod())
Jordy Rosef3aae582012-03-17 21:13:07 +0000783 CachedSummaries = &ObjCMethodSummaries;
Ted Kremenek552333c2009-04-29 17:17:48 +0000784 else
Jordy Rosef3aae582012-03-17 21:13:07 +0000785 CachedSummaries = &ObjCClassMethodSummaries;
786
787 return getMethodSummary(S, ClsName, ID, MD, ResultTy, *CachedSummaries);
Ted Kremenek552333c2009-04-29 17:17:48 +0000788 }
Mike Stump1eb44332009-09-09 15:08:12 +0000789
Jordy Rosef3aae582012-03-17 21:13:07 +0000790 const RetainSummary *getStandardMethodSummary(const ObjCMethodDecl *MD,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000791 Selector S, QualType RetTy);
Ted Kremeneka8833552009-04-29 23:03:22 +0000792
Ted Kremenek93edbc52011-10-05 23:54:29 +0000793 void updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenek4dd8fb42009-05-09 02:58:13 +0000794 const ObjCMethodDecl *MD);
795
Ted Kremenek93edbc52011-10-05 23:54:29 +0000796 void updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenek4dd8fb42009-05-09 02:58:13 +0000797 const FunctionDecl *FD);
798
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000799 bool isGCEnabled() const { return GCEnabled; }
Mike Stump1eb44332009-09-09 15:08:12 +0000800
John McCallf85e1932011-06-15 23:02:42 +0000801 bool isARCEnabled() const { return ARCEnabled; }
802
803 bool isARCorGCEnabled() const { return GCEnabled || ARCEnabled; }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000804};
Mike Stump1eb44332009-09-09 15:08:12 +0000805
Jordy Rose0fe62f82011-08-24 09:02:37 +0000806// Used to avoid allocating long-term (BPAlloc'd) memory for default retain
807// summaries. If a function or method looks like it has a default summary, but
808// it has annotations, the annotations are added to the stack-based template
809// and then copied into managed memory.
810class RetainSummaryTemplate {
811 RetainSummaryManager &Manager;
Ted Kremenek93edbc52011-10-05 23:54:29 +0000812 const RetainSummary *&RealSummary;
Jordy Rose0fe62f82011-08-24 09:02:37 +0000813 RetainSummary ScratchSummary;
814 bool Accessed;
815public:
Jordy Rosee921b1a2012-03-17 19:53:04 +0000816 RetainSummaryTemplate(const RetainSummary *&real, const RetainSummary &base,
817 RetainSummaryManager &mgr)
818 : Manager(mgr), RealSummary(real), ScratchSummary(real ? *real : base),
Ted Kremenek93edbc52011-10-05 23:54:29 +0000819 Accessed(false) {}
Jordy Rose0fe62f82011-08-24 09:02:37 +0000820
821 ~RetainSummaryTemplate() {
Ted Kremenek93edbc52011-10-05 23:54:29 +0000822 if (Accessed)
Jordy Roseef945882012-03-18 01:26:10 +0000823 RealSummary = Manager.getPersistentSummary(ScratchSummary);
Jordy Rose0fe62f82011-08-24 09:02:37 +0000824 }
825
826 RetainSummary &operator*() {
827 Accessed = true;
Ted Kremenek93edbc52011-10-05 23:54:29 +0000828 return ScratchSummary;
Jordy Rose0fe62f82011-08-24 09:02:37 +0000829 }
830
831 RetainSummary *operator->() {
832 Accessed = true;
Ted Kremenek93edbc52011-10-05 23:54:29 +0000833 return &ScratchSummary;
Jordy Rose0fe62f82011-08-24 09:02:37 +0000834 }
835};
836
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000837} // end anonymous namespace
838
839//===----------------------------------------------------------------------===//
840// Implementation of checker data structures.
841//===----------------------------------------------------------------------===//
842
Ted Kremenekb77449c2009-05-03 05:20:50 +0000843ArgEffects RetainSummaryManager::getArgEffects() {
844 ArgEffects AE = ScratchArgs;
Ted Kremenek3baf6722010-11-24 00:54:37 +0000845 ScratchArgs = AF.getEmptyMap();
Ted Kremenekb77449c2009-05-03 05:20:50 +0000846 return AE;
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000847}
848
Ted Kremenek93edbc52011-10-05 23:54:29 +0000849const RetainSummary *
Jordy Roseef945882012-03-18 01:26:10 +0000850RetainSummaryManager::getPersistentSummary(const RetainSummary &OldSumm) {
851 // Unique "simple" summaries -- those without ArgEffects.
852 if (OldSumm.isSimple()) {
853 llvm::FoldingSetNodeID ID;
854 OldSumm.Profile(ID);
855
856 void *Pos;
857 CachedSummaryNode *N = SimpleSummaries.FindNodeOrInsertPos(ID, Pos);
858
859 if (!N) {
860 N = (CachedSummaryNode *) BPAlloc.Allocate<CachedSummaryNode>();
861 new (N) CachedSummaryNode(OldSumm);
862 SimpleSummaries.InsertNode(N, Pos);
863 }
864
865 return &N->getValue();
866 }
867
Ted Kremenek93edbc52011-10-05 23:54:29 +0000868 RetainSummary *Summ = (RetainSummary *) BPAlloc.Allocate<RetainSummary>();
Jordy Roseef945882012-03-18 01:26:10 +0000869 new (Summ) RetainSummary(OldSumm);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000870 return Summ;
871}
872
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000873//===----------------------------------------------------------------------===//
874// Summary creation for functions (largely uses of Core Foundation).
875//===----------------------------------------------------------------------===//
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000876
Ted Kremenek9c378f72011-08-12 23:37:29 +0000877static bool isRetain(const FunctionDecl *FD, StringRef FName) {
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000878 return FName.endswith("Retain");
Ted Kremenek12619382009-01-12 21:45:02 +0000879}
880
Ted Kremenek9c378f72011-08-12 23:37:29 +0000881static bool isRelease(const FunctionDecl *FD, StringRef FName) {
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000882 return FName.endswith("Release");
Ted Kremenek12619382009-01-12 21:45:02 +0000883}
884
Jordy Rose76c506f2011-08-21 21:58:18 +0000885static bool isMakeCollectable(const FunctionDecl *FD, StringRef FName) {
886 // FIXME: Remove FunctionDecl parameter.
887 // FIXME: Is it really okay if MakeCollectable isn't a suffix?
888 return FName.find("MakeCollectable") != StringRef::npos;
889}
890
Anna Zaks58822c42012-05-04 22:18:39 +0000891const RetainSummary *
892RetainSummaryManager::getSummary(const FunctionDecl *FD,
893 const CallOrObjCMessage *CME) {
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000894 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000895 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000896 if (I != FuncSummaries.end())
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000897 return I->second;
898
Ted Kremeneke401a0c2009-05-04 15:34:07 +0000899 // No summary? Generate one.
Ted Kremenek93edbc52011-10-05 23:54:29 +0000900 const RetainSummary *S = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000901
Ted Kremenek37d785b2008-07-15 16:50:12 +0000902 do {
Ted Kremenek12619382009-01-12 21:45:02 +0000903 // We generate "stop" summaries for implicitly defined functions.
904 if (FD->isImplicit()) {
905 S = getPersistentStopSummary();
906 break;
Ted Kremenek37d785b2008-07-15 16:50:12 +0000907 }
Ted Kremenek9ca28512011-05-02 21:21:42 +0000908 // For C++ methods, generate an implicit "stop" summary as well. We
909 // can relax this once we have a clear policy for C++ methods and
910 // ownership attributes.
911 if (isa<CXXMethodDecl>(FD)) {
912 S = getPersistentStopSummary();
913 break;
914 }
Mike Stump1eb44332009-09-09 15:08:12 +0000915
John McCall183700f2009-09-21 23:43:11 +0000916 // [PR 3337] Use 'getAs<FunctionType>' to strip away any typedefs on the
Ted Kremenek99890652009-01-16 18:40:33 +0000917 // function's type.
John McCall183700f2009-09-21 23:43:11 +0000918 const FunctionType* FT = FD->getType()->getAs<FunctionType>();
Ted Kremenek48c6d182009-12-16 06:06:43 +0000919 const IdentifierInfo *II = FD->getIdentifier();
920 if (!II)
921 break;
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000922
923 StringRef FName = II->getName();
Mike Stump1eb44332009-09-09 15:08:12 +0000924
Ted Kremenekbf0a4dd2009-03-05 22:11:14 +0000925 // Strip away preceding '_'. Doing this here will effect all the checks
926 // down below.
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000927 FName = FName.substr(FName.find_first_not_of('_'));
Mike Stump1eb44332009-09-09 15:08:12 +0000928
Ted Kremenek12619382009-01-12 21:45:02 +0000929 // Inspect the result type.
930 QualType RetTy = FT->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +0000931
Ted Kremenek12619382009-01-12 21:45:02 +0000932 // FIXME: This should all be refactored into a chain of "summary lookup"
933 // filters.
Ted Kremenek008636a2009-10-14 00:27:24 +0000934 assert(ScratchArgs.isEmpty());
Ted Kremenek39d88b02009-06-15 20:36:07 +0000935
Ted Kremenekbefc6d22012-04-26 04:32:23 +0000936 if (FName == "pthread_create" || FName == "pthread_setspecific") {
937 // Part of: <rdar://problem/7299394> and <rdar://problem/11282706>.
938 // This will be addressed better with IPA.
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000939 S = getPersistentStopSummary();
940 } else if (FName == "NSMakeCollectable") {
941 // Handle: id NSMakeCollectable(CFTypeRef)
942 S = (RetTy->isObjCIdType())
943 ? getUnarySummary(FT, cfmakecollectable)
944 : getPersistentStopSummary();
945 } else if (FName == "IOBSDNameMatching" ||
946 FName == "IOServiceMatching" ||
947 FName == "IOServiceNameMatching" ||
Ted Kremenek537dd3a2012-05-01 05:28:27 +0000948 FName == "IORegistryEntrySearchCFProperty" ||
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000949 FName == "IORegistryEntryIDMatching" ||
950 FName == "IOOpenFirmwarePathMatching") {
951 // Part of <rdar://problem/6961230>. (IOKit)
952 // This should be addressed using a API table.
953 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
954 DoNothing, DoNothing);
955 } else if (FName == "IOServiceGetMatchingService" ||
956 FName == "IOServiceGetMatchingServices") {
957 // FIXES: <rdar://problem/6326900>
958 // This should be addressed using a API table. This strcmp is also
959 // a little gross, but there is no need to super optimize here.
Ted Kremenek3baf6722010-11-24 00:54:37 +0000960 ScratchArgs = AF.add(ScratchArgs, 1, DecRef);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000961 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
962 } else if (FName == "IOServiceAddNotification" ||
963 FName == "IOServiceAddMatchingNotification") {
964 // Part of <rdar://problem/6961230>. (IOKit)
965 // This should be addressed using a API table.
Ted Kremenek3baf6722010-11-24 00:54:37 +0000966 ScratchArgs = AF.add(ScratchArgs, 2, DecRef);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000967 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
968 } else if (FName == "CVPixelBufferCreateWithBytes") {
969 // FIXES: <rdar://problem/7283567>
970 // Eventually this can be improved by recognizing that the pixel
971 // buffer passed to CVPixelBufferCreateWithBytes is released via
972 // a callback and doing full IPA to make sure this is done correctly.
973 // FIXME: This function has an out parameter that returns an
974 // allocated object.
Ted Kremenek3baf6722010-11-24 00:54:37 +0000975 ScratchArgs = AF.add(ScratchArgs, 7, StopTracking);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000976 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
977 } else if (FName == "CGBitmapContextCreateWithData") {
978 // FIXES: <rdar://problem/7358899>
979 // Eventually this can be improved by recognizing that 'releaseInfo'
980 // passed to CGBitmapContextCreateWithData is released via
981 // a callback and doing full IPA to make sure this is done correctly.
Ted Kremenek3baf6722010-11-24 00:54:37 +0000982 ScratchArgs = AF.add(ScratchArgs, 8, StopTracking);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000983 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
984 DoNothing, DoNothing);
985 } else if (FName == "CVPixelBufferCreateWithPlanarBytes") {
986 // FIXES: <rdar://problem/7283567>
987 // Eventually this can be improved by recognizing that the pixel
988 // buffer passed to CVPixelBufferCreateWithPlanarBytes is released
989 // via a callback and doing full IPA to make sure this is done
990 // correctly.
Ted Kremenek3baf6722010-11-24 00:54:37 +0000991 ScratchArgs = AF.add(ScratchArgs, 12, StopTracking);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000992 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenek06911d42012-03-22 06:29:41 +0000993 } else if (FName == "dispatch_set_context") {
994 // <rdar://problem/11059275> - The analyzer currently doesn't have
995 // a good way to reason about the finalizer function for libdispatch.
996 // If we pass a context object that is memory managed, stop tracking it.
997 // FIXME: this hack should possibly go away once we can handle
998 // libdispatch finalizers.
999 ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
1000 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenekc91fdf62012-05-08 00:12:09 +00001001 } else if (FName.startswith("NSLog")) {
1002 S = getDoNothingSummary();
Anna Zaks62a5c342012-03-30 05:48:16 +00001003 } else if (FName.startswith("NS") &&
1004 (FName.find("Insert") != StringRef::npos)) {
1005 // Whitelist NSXXInsertXX, for example NSMapInsertIfAbsent, since they can
1006 // be deallocated by NSMapRemove. (radar://11152419)
1007 ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
1008 ScratchArgs = AF.add(ScratchArgs, 2, StopTracking);
1009 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Anna Zaks58822c42012-05-04 22:18:39 +00001010 } else if (CME && CME->hasNonZeroCallbackArg()) {
Anna Zaks41a669a2012-05-07 17:47:09 +00001011 // Allow objects to escape through callbacks. radar://10973977
1012 S = getPersistentStopSummary();
Ted Kremenekb04cb592009-06-11 18:17:24 +00001013 }
Mike Stump1eb44332009-09-09 15:08:12 +00001014
Ted Kremenekb04cb592009-06-11 18:17:24 +00001015 // Did we get a summary?
1016 if (S)
1017 break;
Ted Kremenek61991902009-03-17 22:43:44 +00001018
1019 // Enable this code once the semantics of NSDeallocateObject are resolved
1020 // for GC. <rdar://problem/6619988>
1021#if 0
1022 // Handle: NSDeallocateObject(id anObject);
1023 // This method does allow 'nil' (although we don't check it now).
Mike Stump1eb44332009-09-09 15:08:12 +00001024 if (strcmp(FName, "NSDeallocateObject") == 0) {
Ted Kremenek61991902009-03-17 22:43:44 +00001025 return RetTy == Ctx.VoidTy
1026 ? getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, Dealloc)
1027 : getPersistentStopSummary();
1028 }
1029#endif
Ted Kremenek12619382009-01-12 21:45:02 +00001030
1031 if (RetTy->isPointerType()) {
1032 // For CoreFoundation ('CF') types.
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001033 if (cocoa::isRefType(RetTy, "CF", FName)) {
Ted Kremenek12619382009-01-12 21:45:02 +00001034 if (isRetain(FD, FName))
1035 S = getUnarySummary(FT, cfretain);
Jordy Rose76c506f2011-08-21 21:58:18 +00001036 else if (isMakeCollectable(FD, FName))
Ted Kremenek12619382009-01-12 21:45:02 +00001037 S = getUnarySummary(FT, cfmakecollectable);
Mike Stump1eb44332009-09-09 15:08:12 +00001038 else
John McCall7df2ff42011-10-01 00:48:56 +00001039 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek12619382009-01-12 21:45:02 +00001040
1041 break;
1042 }
1043
1044 // For CoreGraphics ('CG') types.
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001045 if (cocoa::isRefType(RetTy, "CG", FName)) {
Ted Kremenek12619382009-01-12 21:45:02 +00001046 if (isRetain(FD, FName))
1047 S = getUnarySummary(FT, cfretain);
1048 else
John McCall7df2ff42011-10-01 00:48:56 +00001049 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek12619382009-01-12 21:45:02 +00001050
1051 break;
1052 }
1053
1054 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001055 if (cocoa::isRefType(RetTy, "DADisk") ||
1056 cocoa::isRefType(RetTy, "DADissenter") ||
1057 cocoa::isRefType(RetTy, "DASessionRef")) {
John McCall7df2ff42011-10-01 00:48:56 +00001058 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek12619382009-01-12 21:45:02 +00001059 break;
1060 }
Mike Stump1eb44332009-09-09 15:08:12 +00001061
Ted Kremenek12619382009-01-12 21:45:02 +00001062 break;
1063 }
1064
1065 // Check for release functions, the only kind of functions that we care
1066 // about that don't return a pointer type.
1067 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
Ted Kremeneke7d03122010-02-08 16:45:01 +00001068 // Test for 'CGCF'.
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001069 FName = FName.substr(FName.startswith("CGCF") ? 4 : 2);
Ted Kremeneke7d03122010-02-08 16:45:01 +00001070
Ted Kremenekbf0a4dd2009-03-05 22:11:14 +00001071 if (isRelease(FD, FName))
Ted Kremenek12619382009-01-12 21:45:02 +00001072 S = getUnarySummary(FT, cfrelease);
1073 else {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001074 assert (ScratchArgs.isEmpty());
Ted Kremenek68189282009-01-29 22:45:13 +00001075 // Remaining CoreFoundation and CoreGraphics functions.
1076 // We use to assume that they all strictly followed the ownership idiom
1077 // and that ownership cannot be transferred. While this is technically
1078 // correct, many methods allow a tracked object to escape. For example:
1079 //
Mike Stump1eb44332009-09-09 15:08:12 +00001080 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
Ted Kremenek68189282009-01-29 22:45:13 +00001081 // CFDictionaryAddValue(y, key, x);
Mike Stump1eb44332009-09-09 15:08:12 +00001082 // CFRelease(x);
Ted Kremenek68189282009-01-29 22:45:13 +00001083 // ... it is okay to use 'x' since 'y' has a reference to it
1084 //
1085 // We handle this and similar cases with the follow heuristic. If the
Ted Kremenekc4843812009-08-20 00:57:22 +00001086 // function name contains "InsertValue", "SetValue", "AddValue",
1087 // "AppendValue", or "SetAttribute", then we assume that arguments may
1088 // "escape." This means that something else holds on to the object,
1089 // allowing it be used even after its local retain count drops to 0.
Benjamin Kramere45c1492010-01-11 19:46:28 +00001090 ArgEffect E = (StrInStrNoCase(FName, "InsertValue") != StringRef::npos||
1091 StrInStrNoCase(FName, "AddValue") != StringRef::npos ||
1092 StrInStrNoCase(FName, "SetValue") != StringRef::npos ||
1093 StrInStrNoCase(FName, "AppendValue") != StringRef::npos||
Benjamin Kramerc027e542010-01-11 20:15:06 +00001094 StrInStrNoCase(FName, "SetAttribute") != StringRef::npos)
Ted Kremenek68189282009-01-29 22:45:13 +00001095 ? MayEscape : DoNothing;
Mike Stump1eb44332009-09-09 15:08:12 +00001096
Ted Kremenek68189282009-01-29 22:45:13 +00001097 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek12619382009-01-12 21:45:02 +00001098 }
1099 }
Ted Kremenek37d785b2008-07-15 16:50:12 +00001100 }
1101 while (0);
Mike Stump1eb44332009-09-09 15:08:12 +00001102
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001103 // Annotations override defaults.
Jordy Rose4df54fe2011-08-23 04:27:15 +00001104 updateSummaryFromAnnotations(S, FD);
Mike Stump1eb44332009-09-09 15:08:12 +00001105
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001106 FuncSummaries[FD] = S;
Mike Stump1eb44332009-09-09 15:08:12 +00001107 return S;
Ted Kremenek2fff37e2008-03-06 00:08:09 +00001108}
1109
Ted Kremenek93edbc52011-10-05 23:54:29 +00001110const RetainSummary *
John McCall7df2ff42011-10-01 00:48:56 +00001111RetainSummaryManager::getCFCreateGetRuleSummary(const FunctionDecl *FD) {
1112 if (coreFoundation::followsCreateRule(FD))
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001113 return getCFSummaryCreateRule(FD);
Mike Stump1eb44332009-09-09 15:08:12 +00001114
Ted Kremenekd368d712011-05-25 06:19:45 +00001115 return getCFSummaryGetRule(FD);
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001116}
1117
Ted Kremenek93edbc52011-10-05 23:54:29 +00001118const RetainSummary *
Ted Kremenek6ad315a2009-02-23 16:51:39 +00001119RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1120 UnaryFuncKind func) {
1121
Ted Kremenek12619382009-01-12 21:45:02 +00001122 // Sanity check that this is *really* a unary function. This can
1123 // happen if people do weird things.
Douglas Gregor72564e72009-02-26 23:50:07 +00001124 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
Ted Kremenek12619382009-01-12 21:45:02 +00001125 if (!FTP || FTP->getNumArgs() != 1)
1126 return getPersistentStopSummary();
Mike Stump1eb44332009-09-09 15:08:12 +00001127
Ted Kremenekb77449c2009-05-03 05:20:50 +00001128 assert (ScratchArgs.isEmpty());
Mike Stump1eb44332009-09-09 15:08:12 +00001129
Jordy Rose76c506f2011-08-21 21:58:18 +00001130 ArgEffect Effect;
Ted Kremenek377e2302008-04-29 05:33:51 +00001131 switch (func) {
Jordy Rose76c506f2011-08-21 21:58:18 +00001132 case cfretain: Effect = IncRef; break;
1133 case cfrelease: Effect = DecRef; break;
1134 case cfmakecollectable: Effect = MakeCollectable; break;
Ted Kremenek940b1d82008-04-10 23:44:06 +00001135 }
Jordy Rose76c506f2011-08-21 21:58:18 +00001136
1137 ScratchArgs = AF.add(ScratchArgs, 0, Effect);
1138 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001139}
1140
Ted Kremenek93edbc52011-10-05 23:54:29 +00001141const RetainSummary *
Ted Kremenek9c378f72011-08-12 23:37:29 +00001142RetainSummaryManager::getCFSummaryCreateRule(const FunctionDecl *FD) {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001143 assert (ScratchArgs.isEmpty());
Mike Stump1eb44332009-09-09 15:08:12 +00001144
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001145 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001146}
1147
Ted Kremenek93edbc52011-10-05 23:54:29 +00001148const RetainSummary *
Ted Kremenek9c378f72011-08-12 23:37:29 +00001149RetainSummaryManager::getCFSummaryGetRule(const FunctionDecl *FD) {
Mike Stump1eb44332009-09-09 15:08:12 +00001150 assert (ScratchArgs.isEmpty());
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001151 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1152 DoNothing, DoNothing);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001153}
1154
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001155//===----------------------------------------------------------------------===//
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001156// Summary creation for Selectors.
1157//===----------------------------------------------------------------------===//
1158
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001159void
Ted Kremenek93edbc52011-10-05 23:54:29 +00001160RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001161 const FunctionDecl *FD) {
1162 if (!FD)
1163 return;
1164
Jordy Roseef945882012-03-18 01:26:10 +00001165 RetainSummaryTemplate Template(Summ, *getDefaultSummary(), *this);
Jordy Rose4df54fe2011-08-23 04:27:15 +00001166
Ted Kremenek11fe1752011-01-27 18:43:03 +00001167 // Effects on the parameters.
1168 unsigned parm_idx = 0;
1169 for (FunctionDecl::param_const_iterator pi = FD->param_begin(),
John McCall98b8f162011-04-06 09:02:12 +00001170 pe = FD->param_end(); pi != pe; ++pi, ++parm_idx) {
Ted Kremenek11fe1752011-01-27 18:43:03 +00001171 const ParmVarDecl *pd = *pi;
1172 if (pd->getAttr<NSConsumedAttr>()) {
Jordy Rose4df54fe2011-08-23 04:27:15 +00001173 if (!GCEnabled) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001174 Template->addArg(AF, parm_idx, DecRef);
Jordy Rose4df54fe2011-08-23 04:27:15 +00001175 }
1176 } else if (pd->getAttr<CFConsumedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001177 Template->addArg(AF, parm_idx, DecRef);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001178 }
1179 }
1180
Ted Kremenekb04cb592009-06-11 18:17:24 +00001181 QualType RetTy = FD->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00001182
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001183 // Determine if there is a special return effect for this method.
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001184 if (cocoa::isCocoaObjectRef(RetTy)) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001185 if (FD->getAttr<NSReturnsRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001186 Template->setRetEffect(ObjCAllocRetE);
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001187 }
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001188 else if (FD->getAttr<CFReturnsRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001189 Template->setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenekb04cb592009-06-11 18:17:24 +00001190 }
Ted Kremenek60411112010-02-18 00:06:12 +00001191 else if (FD->getAttr<NSReturnsNotRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001192 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::ObjC));
Ted Kremenek60411112010-02-18 00:06:12 +00001193 }
1194 else if (FD->getAttr<CFReturnsNotRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001195 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::CF));
Jordy Rose4df54fe2011-08-23 04:27:15 +00001196 }
1197 } else if (RetTy->getAs<PointerType>()) {
1198 if (FD->getAttr<CFReturnsRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001199 Template->setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
Jordy Rose4df54fe2011-08-23 04:27:15 +00001200 }
1201 else if (FD->getAttr<CFReturnsNotRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001202 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::CF));
Ted Kremenek60411112010-02-18 00:06:12 +00001203 }
Ted Kremenekb04cb592009-06-11 18:17:24 +00001204 }
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001205}
1206
1207void
Ted Kremenek93edbc52011-10-05 23:54:29 +00001208RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
1209 const ObjCMethodDecl *MD) {
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001210 if (!MD)
1211 return;
1212
Jordy Roseef945882012-03-18 01:26:10 +00001213 RetainSummaryTemplate Template(Summ, *getDefaultSummary(), *this);
Ted Kremenek6d4b76d2009-07-06 18:30:43 +00001214 bool isTrackedLoc = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001215
Ted Kremenek12b94342011-01-27 06:54:14 +00001216 // Effects on the receiver.
1217 if (MD->getAttr<NSConsumesSelfAttr>()) {
Ted Kremenek11fe1752011-01-27 18:43:03 +00001218 if (!GCEnabled)
Jordy Rose0fe62f82011-08-24 09:02:37 +00001219 Template->setReceiverEffect(DecRefMsg);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001220 }
1221
1222 // Effects on the parameters.
1223 unsigned parm_idx = 0;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00001224 for (ObjCMethodDecl::param_const_iterator
1225 pi=MD->param_begin(), pe=MD->param_end();
Ted Kremenek11fe1752011-01-27 18:43:03 +00001226 pi != pe; ++pi, ++parm_idx) {
1227 const ParmVarDecl *pd = *pi;
1228 if (pd->getAttr<NSConsumedAttr>()) {
1229 if (!GCEnabled)
Jordy Rose0fe62f82011-08-24 09:02:37 +00001230 Template->addArg(AF, parm_idx, DecRef);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001231 }
1232 else if(pd->getAttr<CFConsumedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001233 Template->addArg(AF, parm_idx, DecRef);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001234 }
Ted Kremenek12b94342011-01-27 06:54:14 +00001235 }
1236
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001237 // Determine if there is a special return effect for this method.
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001238 if (cocoa::isCocoaObjectRef(MD->getResultType())) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001239 if (MD->getAttr<NSReturnsRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001240 Template->setRetEffect(ObjCAllocRetE);
Ted Kremenek6d4b76d2009-07-06 18:30:43 +00001241 return;
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001242 }
Ted Kremenek60411112010-02-18 00:06:12 +00001243 if (MD->getAttr<NSReturnsNotRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001244 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::ObjC));
Ted Kremenek60411112010-02-18 00:06:12 +00001245 return;
1246 }
Mike Stump1eb44332009-09-09 15:08:12 +00001247
Ted Kremenek6d4b76d2009-07-06 18:30:43 +00001248 isTrackedLoc = true;
Jordy Rose0fe62f82011-08-24 09:02:37 +00001249 } else {
Ted Kremenek6217b802009-07-29 21:53:49 +00001250 isTrackedLoc = MD->getResultType()->getAs<PointerType>() != NULL;
Jordy Rose0fe62f82011-08-24 09:02:37 +00001251 }
Mike Stump1eb44332009-09-09 15:08:12 +00001252
Ted Kremenek60411112010-02-18 00:06:12 +00001253 if (isTrackedLoc) {
1254 if (MD->getAttr<CFReturnsRetainedAttr>())
Jordy Rose0fe62f82011-08-24 09:02:37 +00001255 Template->setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenek60411112010-02-18 00:06:12 +00001256 else if (MD->getAttr<CFReturnsNotRetainedAttr>())
Jordy Rose0fe62f82011-08-24 09:02:37 +00001257 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::CF));
Ted Kremenek60411112010-02-18 00:06:12 +00001258 }
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001259}
1260
Ted Kremenek93edbc52011-10-05 23:54:29 +00001261const RetainSummary *
Jordy Rosef3aae582012-03-17 21:13:07 +00001262RetainSummaryManager::getStandardMethodSummary(const ObjCMethodDecl *MD,
1263 Selector S, QualType RetTy) {
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001264
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +00001265 if (MD) {
Ted Kremenek376d1e72009-04-24 18:00:17 +00001266 // Scan the method decl for 'void*' arguments. These should be treated
1267 // as 'StopTracking' because they are often used with delegates.
1268 // Delegates are a frequent form of false positives with the retain
1269 // count checker.
1270 unsigned i = 0;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00001271 for (ObjCMethodDecl::param_const_iterator I = MD->param_begin(),
Ted Kremenek376d1e72009-04-24 18:00:17 +00001272 E = MD->param_end(); I != E; ++I, ++i)
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00001273 if (const ParmVarDecl *PD = *I) {
Ted Kremenek376d1e72009-04-24 18:00:17 +00001274 QualType Ty = Ctx.getCanonicalType(PD->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001275 if (Ty.getLocalUnqualifiedType() == Ctx.VoidPtrTy)
Ted Kremenek3baf6722010-11-24 00:54:37 +00001276 ScratchArgs = AF.add(ScratchArgs, i, StopTracking);
Ted Kremenek376d1e72009-04-24 18:00:17 +00001277 }
1278 }
Mike Stump1eb44332009-09-09 15:08:12 +00001279
Jordy Rosee921b1a2012-03-17 19:53:04 +00001280 // Any special effects?
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001281 ArgEffect ReceiverEff = DoNothing;
Jordy Rosee921b1a2012-03-17 19:53:04 +00001282 RetEffect ResultEff = RetEffect::MakeNoRet();
1283
1284 // Check the method family, and apply any default annotations.
1285 switch (MD ? MD->getMethodFamily() : S.getMethodFamily()) {
1286 case OMF_None:
1287 case OMF_performSelector:
1288 // Assume all Objective-C methods follow Cocoa Memory Management rules.
1289 // FIXME: Does the non-threaded performSelector family really belong here?
1290 // The selector could be, say, @selector(copy).
1291 if (cocoa::isCocoaObjectRef(RetTy))
1292 ResultEff = RetEffect::MakeNotOwned(RetEffect::ObjC);
1293 else if (coreFoundation::isCFObjectRef(RetTy)) {
1294 // ObjCMethodDecl currently doesn't consider CF objects as valid return
1295 // values for alloc, new, copy, or mutableCopy, so we have to
1296 // double-check with the selector. This is ugly, but there aren't that
1297 // many Objective-C methods that return CF objects, right?
1298 if (MD) {
1299 switch (S.getMethodFamily()) {
1300 case OMF_alloc:
1301 case OMF_new:
1302 case OMF_copy:
1303 case OMF_mutableCopy:
1304 ResultEff = RetEffect::MakeOwned(RetEffect::CF, true);
1305 break;
1306 default:
1307 ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1308 break;
1309 }
1310 } else {
1311 ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1312 }
1313 }
1314 break;
1315 case OMF_init:
1316 ResultEff = ObjCInitRetE;
1317 ReceiverEff = DecRefMsg;
1318 break;
1319 case OMF_alloc:
1320 case OMF_new:
1321 case OMF_copy:
1322 case OMF_mutableCopy:
1323 if (cocoa::isCocoaObjectRef(RetTy))
1324 ResultEff = ObjCAllocRetE;
1325 else if (coreFoundation::isCFObjectRef(RetTy))
1326 ResultEff = RetEffect::MakeOwned(RetEffect::CF, true);
1327 break;
1328 case OMF_autorelease:
1329 ReceiverEff = Autorelease;
1330 break;
1331 case OMF_retain:
1332 ReceiverEff = IncRefMsg;
1333 break;
1334 case OMF_release:
1335 ReceiverEff = DecRefMsg;
1336 break;
1337 case OMF_dealloc:
1338 ReceiverEff = Dealloc;
1339 break;
1340 case OMF_self:
1341 // -self is handled specially by the ExprEngine to propagate the receiver.
1342 break;
1343 case OMF_retainCount:
1344 case OMF_finalize:
1345 // These methods don't return objects.
1346 break;
1347 }
Mike Stump1eb44332009-09-09 15:08:12 +00001348
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001349 // If one of the arguments in the selector has the keyword 'delegate' we
1350 // should stop tracking the reference count for the receiver. This is
1351 // because the reference count is quite possibly handled by a delegate
1352 // method.
1353 if (S.isKeywordSelector()) {
Jordan Rose50571a92012-06-15 18:19:52 +00001354 for (unsigned i = 0, e = S.getNumArgs(); i != e; ++i) {
1355 StringRef Slot = S.getNameForSlot(i);
1356 if (Slot.substr(Slot.size() - 8).equals_lower("delegate")) {
1357 if (ResultEff == ObjCInitRetE)
1358 ResultEff = RetEffect::MakeNoRet();
1359 else
1360 ReceiverEff = StopTracking;
1361 }
1362 }
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001363 }
Mike Stump1eb44332009-09-09 15:08:12 +00001364
Jordy Rosee921b1a2012-03-17 19:53:04 +00001365 if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing &&
1366 ResultEff.getKind() == RetEffect::NoRet)
Ted Kremenek93edbc52011-10-05 23:54:29 +00001367 return getDefaultSummary();
Mike Stump1eb44332009-09-09 15:08:12 +00001368
Jordy Rosee921b1a2012-03-17 19:53:04 +00001369 return getPersistentSummary(ResultEff, ReceiverEff, MayEscape);
Ted Kremenek250b1fa2009-04-23 23:08:22 +00001370}
1371
Ted Kremenek93edbc52011-10-05 23:54:29 +00001372const RetainSummary *
Argyrios Kyrtzidis432424d2011-01-25 00:03:53 +00001373RetainSummaryManager::getInstanceMethodSummary(const ObjCMessage &msg,
Ted Kremenek8bef8232012-01-26 21:29:00 +00001374 ProgramStateRef state,
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001375 const LocationContext *LC) {
1376
1377 // We need the type-information of the tracked receiver object
1378 // Retrieve it from the state.
Argyrios Kyrtzidis432424d2011-01-25 00:03:53 +00001379 const Expr *Receiver = msg.getInstanceReceiver();
Ted Kremenek9c378f72011-08-12 23:37:29 +00001380 const ObjCInterfaceDecl *ID = 0;
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001381
1382 // FIXME: Is this really working as expected? There are cases where
1383 // we just use the 'ID' from the message expression.
Douglas Gregor04badcf2010-04-21 00:45:42 +00001384 SVal receiverV;
1385
Ted Kremenek8f326752010-05-21 21:56:53 +00001386 if (Receiver) {
Ted Kremenek5eca4822012-01-06 22:09:28 +00001387 receiverV = state->getSValAsScalarOrLoc(Receiver, LC);
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00001388
Douglas Gregor04badcf2010-04-21 00:45:42 +00001389 // FIXME: Eventually replace the use of state->get<RefBindings> with
1390 // a generic API for reasoning about the Objective-C types of symbolic
1391 // objects.
1392 if (SymbolRef Sym = receiverV.getAsLocSymbol())
1393 if (const RefVal *T = state->get<RefBindings>(Sym))
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00001394 if (const ObjCObjectPointerType* PT =
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001395 T->getType()->getAs<ObjCObjectPointerType>())
Douglas Gregor04badcf2010-04-21 00:45:42 +00001396 ID = PT->getInterfaceDecl();
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00001397
Douglas Gregor04badcf2010-04-21 00:45:42 +00001398 // FIXME: this is a hack. This may or may not be the actual method
1399 // that is called.
1400 if (!ID) {
1401 if (const ObjCObjectPointerType *PT =
1402 Receiver->getType()->getAs<ObjCObjectPointerType>())
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001403 ID = PT->getInterfaceDecl();
Douglas Gregor04badcf2010-04-21 00:45:42 +00001404 }
1405 } else {
1406 // FIXME: Hack for 'super'.
Argyrios Kyrtzidis432424d2011-01-25 00:03:53 +00001407 ID = msg.getReceiverInterface();
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001408 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001409
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001410 // FIXME: The receiver could be a reference to a class, meaning that
1411 // we should use the class method.
Jordy Rose4df54fe2011-08-23 04:27:15 +00001412 return getInstanceMethodSummary(msg, ID);
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001413}
1414
Ted Kremenek93edbc52011-10-05 23:54:29 +00001415const RetainSummary *
Jordy Rosef3aae582012-03-17 21:13:07 +00001416RetainSummaryManager::getMethodSummary(Selector S, IdentifierInfo *ClsName,
1417 const ObjCInterfaceDecl *ID,
1418 const ObjCMethodDecl *MD, QualType RetTy,
1419 ObjCMethodSummariesTy &CachedSummaries) {
Ted Kremenek1bffd742008-05-06 15:44:25 +00001420
Ted Kremenek8711c032009-04-29 05:04:30 +00001421 // Look up a summary in our summary cache.
Jordy Rosef3aae582012-03-17 21:13:07 +00001422 const RetainSummary *Summ = CachedSummaries.find(ID, ClsName, S);
Mike Stump1eb44332009-09-09 15:08:12 +00001423
Ted Kremenek614cc542009-07-21 23:27:57 +00001424 if (!Summ) {
Jordy Rosef3aae582012-03-17 21:13:07 +00001425 Summ = getStandardMethodSummary(MD, S, RetTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001426
Ted Kremenek614cc542009-07-21 23:27:57 +00001427 // Annotations override defaults.
Jordy Rose4df54fe2011-08-23 04:27:15 +00001428 updateSummaryFromAnnotations(Summ, MD);
Mike Stump1eb44332009-09-09 15:08:12 +00001429
Ted Kremenek614cc542009-07-21 23:27:57 +00001430 // Memoize the summary.
Jordy Rosef3aae582012-03-17 21:13:07 +00001431 CachedSummaries[ObjCSummaryKey(ID, ClsName, S)] = Summ;
Ted Kremenek614cc542009-07-21 23:27:57 +00001432 }
Mike Stump1eb44332009-09-09 15:08:12 +00001433
Ted Kremeneke87450e2009-04-23 19:11:35 +00001434 return Summ;
Ted Kremenekc8395602008-05-06 21:26:51 +00001435}
1436
Mike Stump1eb44332009-09-09 15:08:12 +00001437void RetainSummaryManager::InitializeClassMethodSummaries() {
Ted Kremenekec315332009-05-07 23:40:42 +00001438 assert(ScratchArgs.isEmpty());
Mike Stump1eb44332009-09-09 15:08:12 +00001439 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek6fe2b7a2009-10-15 22:25:12 +00001440 addClassMethSummary("NSAssertionHandler", "currentHandler",
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001441 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Mike Stump1eb44332009-09-09 15:08:12 +00001442
Ted Kremenek6d348932008-10-21 15:53:15 +00001443 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001444 ScratchArgs = AF.add(ScratchArgs, 0, Autorelease);
Ted Kremenek6fe2b7a2009-10-15 22:25:12 +00001445 addClassMethSummary("NSAutoreleasePool", "addObject",
1446 getPersistentSummary(RetEffect::MakeNoRet(),
1447 DoNothing, Autorelease));
Mike Stump1eb44332009-09-09 15:08:12 +00001448
Ted Kremenekde4d5332009-04-24 17:50:11 +00001449 // Create the summaries for [NSObject performSelector...]. We treat
1450 // these as 'stop tracking' for the arguments because they are often
1451 // used for delegates that can release the object. When we have better
1452 // inter-procedural analysis we can potentially do something better. This
1453 // workaround is to remove false positives.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001454 const RetainSummary *Summ =
Ted Kremenek012614e2011-08-17 21:04:19 +00001455 getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, StopTracking);
Ted Kremenekde4d5332009-04-24 17:50:11 +00001456 IdentifierInfo *NSObjectII = &Ctx.Idents.get("NSObject");
1457 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1458 "afterDelay", NULL);
1459 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1460 "afterDelay", "inModes", NULL);
1461 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1462 "withObject", "waitUntilDone", NULL);
1463 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1464 "withObject", "waitUntilDone", "modes", NULL);
1465 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1466 "withObject", "waitUntilDone", NULL);
1467 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1468 "withObject", "waitUntilDone", "modes", NULL);
1469 addClsMethSummary(NSObjectII, Summ, "performSelectorInBackground",
1470 "withObject", NULL);
Ted Kremenek9c32d082008-05-06 00:30:21 +00001471}
1472
Ted Kremenek1f180c32008-06-23 22:21:20 +00001473void RetainSummaryManager::InitializeMethodSummaries() {
Mike Stump1eb44332009-09-09 15:08:12 +00001474
1475 assert (ScratchArgs.isEmpty());
1476
Ted Kremenekc8395602008-05-06 21:26:51 +00001477 // Create the "init" selector. It just acts as a pass-through for the
1478 // receiver.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001479 const RetainSummary *InitSumm = getPersistentSummary(ObjCInitRetE, DecRefMsg);
Ted Kremenekac02f202009-08-20 05:13:36 +00001480 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
1481
1482 // awakeAfterUsingCoder: behaves basically like an 'init' method. It
1483 // claims the receiver and returns a retained object.
1484 addNSObjectMethSummary(GetUnarySelector("awakeAfterUsingCoder", Ctx),
1485 InitSumm);
Mike Stump1eb44332009-09-09 15:08:12 +00001486
Ted Kremenekc8395602008-05-06 21:26:51 +00001487 // The next methods are allocators.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001488 const RetainSummary *AllocSumm = getPersistentSummary(ObjCAllocRetE);
1489 const RetainSummary *CFAllocSumm =
Ted Kremeneka834fb42009-08-28 19:52:12 +00001490 getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Mike Stump1eb44332009-09-09 15:08:12 +00001491
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001492 // Create the "retain" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001493 RetEffect NoRet = RetEffect::MakeNoRet();
Ted Kremenek93edbc52011-10-05 23:54:29 +00001494 const RetainSummary *Summ = getPersistentSummary(NoRet, IncRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001495 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001496
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001497 // Create the "release" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001498 Summ = getPersistentSummary(NoRet, DecRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001499 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001500
Ted Kremenek299e8152008-05-07 21:17:39 +00001501 // Create the "drain" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001502 Summ = getPersistentSummary(NoRet, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek553cf182008-06-25 21:21:56 +00001503 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001504
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001505 // Create the -dealloc summary.
Jordy Rose500abad2011-08-21 19:41:36 +00001506 Summ = getPersistentSummary(NoRet, Dealloc);
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001507 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001508
1509 // Create the "autorelease" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001510 Summ = getPersistentSummary(NoRet, Autorelease);
Ted Kremenek553cf182008-06-25 21:21:56 +00001511 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001512
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00001513 // Specially handle NSAutoreleasePool.
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001514 addInstMethSummary("NSAutoreleasePool", "init",
Jordy Rose500abad2011-08-21 19:41:36 +00001515 getPersistentSummary(NoRet, NewAutoreleasePool));
Mike Stump1eb44332009-09-09 15:08:12 +00001516
1517 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremenek89e202d2009-02-23 02:51:29 +00001518 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1519 // self-own themselves. However, they only do this once they are displayed.
1520 // Thus, we need to track an NSWindow's display status.
1521 // This is tracked in <rdar://problem/6062711>.
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +00001522 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001523 const RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenek78a35a32009-05-12 20:06:54 +00001524 StopTracking,
1525 StopTracking);
Mike Stump1eb44332009-09-09 15:08:12 +00001526
Ted Kremenek99d02692009-04-03 19:02:51 +00001527 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1528
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +00001529#if 0
Ted Kremenek78a35a32009-05-12 20:06:54 +00001530 addInstMethSummary("NSWindow", NoTrackYet, "initWithContentRect",
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001531 "styleMask", "backing", "defer", NULL);
Mike Stump1eb44332009-09-09 15:08:12 +00001532
Ted Kremenek78a35a32009-05-12 20:06:54 +00001533 addInstMethSummary("NSWindow", NoTrackYet, "initWithContentRect",
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001534 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +00001535#endif
Mike Stump1eb44332009-09-09 15:08:12 +00001536
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001537 // For NSPanel (which subclasses NSWindow), allocated objects are not
1538 // self-owned.
Ted Kremenek99d02692009-04-03 19:02:51 +00001539 // FIXME: For now we don't track NSPanels. object for the same reason
1540 // as for NSWindow objects.
1541 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
Mike Stump1eb44332009-09-09 15:08:12 +00001542
Ted Kremenek78a35a32009-05-12 20:06:54 +00001543#if 0
1544 addInstMethSummary("NSPanel", NoTrackYet, "initWithContentRect",
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001545 "styleMask", "backing", "defer", NULL);
Mike Stump1eb44332009-09-09 15:08:12 +00001546
Ted Kremenek78a35a32009-05-12 20:06:54 +00001547 addInstMethSummary("NSPanel", NoTrackYet, "initWithContentRect",
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001548 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek78a35a32009-05-12 20:06:54 +00001549#endif
Mike Stump1eb44332009-09-09 15:08:12 +00001550
Ted Kremenekba67f6a2009-05-18 23:14:34 +00001551 // Don't track allocated autorelease pools yet, as it is okay to prematurely
1552 // exit a method.
1553 addClassMethSummary("NSAutoreleasePool", "alloc", NoTrackYet);
Ted Kremeneka9797122012-02-18 21:37:48 +00001554 addClassMethSummary("NSAutoreleasePool", "allocWithZone", NoTrackYet, false);
Ted Kremenek553cf182008-06-25 21:21:56 +00001555
Ted Kremenek767d6492009-05-20 22:39:57 +00001556 // Create summaries QCRenderer/QCView -createSnapShotImageOfType:
1557 addInstMethSummary("QCRenderer", AllocSumm,
1558 "createSnapshotImageOfType", NULL);
1559 addInstMethSummary("QCView", AllocSumm,
1560 "createSnapshotImageOfType", NULL);
1561
Ted Kremenek211a9c62009-06-15 20:58:58 +00001562 // Create summaries for CIContext, 'createCGImage' and
Ted Kremeneka834fb42009-08-28 19:52:12 +00001563 // 'createCGLayerWithSize'. These objects are CF objects, and are not
1564 // automatically garbage collected.
1565 addInstMethSummary("CIContext", CFAllocSumm,
Ted Kremenek767d6492009-05-20 22:39:57 +00001566 "createCGImage", "fromRect", NULL);
Ted Kremeneka834fb42009-08-28 19:52:12 +00001567 addInstMethSummary("CIContext", CFAllocSumm,
Mike Stump1eb44332009-09-09 15:08:12 +00001568 "createCGImage", "fromRect", "format", "colorSpace", NULL);
Ted Kremeneka834fb42009-08-28 19:52:12 +00001569 addInstMethSummary("CIContext", CFAllocSumm, "createCGLayerWithSize",
Ted Kremenek211a9c62009-06-15 20:58:58 +00001570 "info", NULL);
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001571}
1572
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001573//===----------------------------------------------------------------------===//
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001574// AutoreleaseBindings - State used to track objects in autorelease pools.
Ted Kremenek6d348932008-10-21 15:53:15 +00001575//===----------------------------------------------------------------------===//
1576
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001577typedef llvm::ImmutableMap<SymbolRef, unsigned> ARCounts;
1578typedef llvm::ImmutableMap<SymbolRef, ARCounts> ARPoolContents;
1579typedef llvm::ImmutableList<SymbolRef> ARStack;
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00001580
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001581static int AutoRCIndex = 0;
Ted Kremenek6d348932008-10-21 15:53:15 +00001582static int AutoRBIndex = 0;
1583
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001584namespace { class AutoreleasePoolContents {}; }
1585namespace { class AutoreleaseStack {}; }
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001586
Ted Kremenek6d348932008-10-21 15:53:15 +00001587namespace clang {
Ted Kremenek9ef65372010-12-23 07:20:52 +00001588namespace ento {
Ted Kremenek18c66fd2011-08-15 22:09:50 +00001589template<> struct ProgramStateTrait<AutoreleaseStack>
1590 : public ProgramStatePartialTrait<ARStack> {
Ted Kremenek9c378f72011-08-12 23:37:29 +00001591 static inline void *GDMIndex() { return &AutoRBIndex; }
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001592};
1593
Ted Kremenek18c66fd2011-08-15 22:09:50 +00001594template<> struct ProgramStateTrait<AutoreleasePoolContents>
1595 : public ProgramStatePartialTrait<ARPoolContents> {
Ted Kremenek9c378f72011-08-12 23:37:29 +00001596 static inline void *GDMIndex() { return &AutoRCIndex; }
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001597};
Argyrios Kyrtzidis5a4f98f2010-12-22 18:53:20 +00001598} // end GR namespace
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001599} // end clang namespace
Ted Kremenek6d348932008-10-21 15:53:15 +00001600
Ted Kremenek8bef8232012-01-26 21:29:00 +00001601static SymbolRef GetCurrentAutoreleasePool(ProgramStateRef state) {
Ted Kremenek7037ab82009-03-20 17:34:15 +00001602 ARStack stack = state->get<AutoreleaseStack>();
1603 return stack.isEmpty() ? SymbolRef() : stack.getHead();
1604}
1605
Ted Kremenek8bef8232012-01-26 21:29:00 +00001606static ProgramStateRef
1607SendAutorelease(ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +00001608 ARCounts::Factory &F,
1609 SymbolRef sym) {
Ted Kremenek7037ab82009-03-20 17:34:15 +00001610 SymbolRef pool = GetCurrentAutoreleasePool(state);
Ted Kremenekb65be702009-06-18 01:23:53 +00001611 const ARCounts *cnts = state->get<AutoreleasePoolContents>(pool);
Ted Kremenek7037ab82009-03-20 17:34:15 +00001612 ARCounts newCnts(0);
Mike Stump1eb44332009-09-09 15:08:12 +00001613
Ted Kremenek7037ab82009-03-20 17:34:15 +00001614 if (cnts) {
1615 const unsigned *cnt = (*cnts).lookup(sym);
Ted Kremenek3baf6722010-11-24 00:54:37 +00001616 newCnts = F.add(*cnts, sym, cnt ? *cnt + 1 : 1);
Ted Kremenek7037ab82009-03-20 17:34:15 +00001617 }
1618 else
Ted Kremenek3baf6722010-11-24 00:54:37 +00001619 newCnts = F.add(F.getEmptyMap(), sym, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001620
Ted Kremenekb65be702009-06-18 01:23:53 +00001621 return state->set<AutoreleasePoolContents>(pool, newCnts);
Ted Kremenek7037ab82009-03-20 17:34:15 +00001622}
1623
Ted Kremenek13922612008-04-16 20:40:59 +00001624//===----------------------------------------------------------------------===//
Ted Kremenekc887d132009-04-29 18:50:19 +00001625// Error reporting.
1626//===----------------------------------------------------------------------===//
Ted Kremenekc887d132009-04-29 18:50:19 +00001627namespace {
Jordy Roseec9ef852011-08-23 20:55:48 +00001628 typedef llvm::DenseMap<const ExplodedNode *, const RetainSummary *>
1629 SummaryLogTy;
1630
Ted Kremenekc887d132009-04-29 18:50:19 +00001631 //===-------------===//
1632 // Bug Descriptions. //
Mike Stump1eb44332009-09-09 15:08:12 +00001633 //===-------------===//
1634
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001635 class CFRefBug : public BugType {
Ted Kremenekc887d132009-04-29 18:50:19 +00001636 protected:
Jordy Rose35c86952011-08-24 05:47:39 +00001637 CFRefBug(StringRef name)
Ted Kremenek6fd45052012-04-05 20:43:28 +00001638 : BugType(name, categories::MemoryCoreFoundationObjectiveC) {}
Ted Kremenekc887d132009-04-29 18:50:19 +00001639 public:
Mike Stump1eb44332009-09-09 15:08:12 +00001640
Ted Kremenekc887d132009-04-29 18:50:19 +00001641 // FIXME: Eventually remove.
Jordy Rose35c86952011-08-24 05:47:39 +00001642 virtual const char *getDescription() const = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001643
Ted Kremenekc887d132009-04-29 18:50:19 +00001644 virtual bool isLeak() const { return false; }
1645 };
Mike Stump1eb44332009-09-09 15:08:12 +00001646
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001647 class UseAfterRelease : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001648 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001649 UseAfterRelease() : CFRefBug("Use-after-release") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001650
Jordy Rose35c86952011-08-24 05:47:39 +00001651 const char *getDescription() const {
Ted Kremenekc887d132009-04-29 18:50:19 +00001652 return "Reference-counted object is used after it is released";
Mike Stump1eb44332009-09-09 15:08:12 +00001653 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001654 };
Mike Stump1eb44332009-09-09 15:08:12 +00001655
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001656 class BadRelease : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001657 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001658 BadRelease() : CFRefBug("Bad release") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001659
Jordy Rose35c86952011-08-24 05:47:39 +00001660 const char *getDescription() const {
Ted Kremenekbb206fd2009-10-01 17:31:50 +00001661 return "Incorrect decrement of the reference count of an object that is "
1662 "not owned at this point by the caller";
Ted Kremenekc887d132009-04-29 18:50:19 +00001663 }
1664 };
Mike Stump1eb44332009-09-09 15:08:12 +00001665
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001666 class DeallocGC : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001667 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001668 DeallocGC()
1669 : CFRefBug("-dealloc called while using garbage collection") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001670
Ted Kremenekc887d132009-04-29 18:50:19 +00001671 const char *getDescription() const {
Ted Kremenek369de562009-05-09 00:10:05 +00001672 return "-dealloc called while using garbage collection";
Ted Kremenekc887d132009-04-29 18:50:19 +00001673 }
1674 };
Mike Stump1eb44332009-09-09 15:08:12 +00001675
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001676 class DeallocNotOwned : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001677 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001678 DeallocNotOwned()
1679 : CFRefBug("-dealloc sent to non-exclusively owned object") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001680
Ted Kremenekc887d132009-04-29 18:50:19 +00001681 const char *getDescription() const {
1682 return "-dealloc sent to object that may be referenced elsewhere";
1683 }
Mike Stump1eb44332009-09-09 15:08:12 +00001684 };
1685
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001686 class OverAutorelease : public CFRefBug {
Ted Kremenek369de562009-05-09 00:10:05 +00001687 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001688 OverAutorelease()
1689 : CFRefBug("Object sent -autorelease too many times") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001690
Ted Kremenek369de562009-05-09 00:10:05 +00001691 const char *getDescription() const {
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001692 return "Object sent -autorelease too many times";
Ted Kremenek369de562009-05-09 00:10:05 +00001693 }
1694 };
Mike Stump1eb44332009-09-09 15:08:12 +00001695
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001696 class ReturnedNotOwnedForOwned : public CFRefBug {
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001697 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001698 ReturnedNotOwnedForOwned()
1699 : CFRefBug("Method should return an owned object") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001700
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001701 const char *getDescription() const {
Jordy Rose5b5402b2011-07-15 22:17:54 +00001702 return "Object with a +0 retain count returned to caller where a +1 "
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001703 "(owning) retain count is expected";
1704 }
1705 };
Mike Stump1eb44332009-09-09 15:08:12 +00001706
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001707 class Leak : public CFRefBug {
Benjamin Kramerfacde172012-06-06 17:32:50 +00001708 public:
1709 Leak(StringRef name)
1710 : CFRefBug(name) {
Jordy Rosedb92bb62011-08-25 01:14:38 +00001711 // Leaks should not be reported if they are post-dominated by a sink.
1712 setSuppressOnSink(true);
1713 }
Mike Stump1eb44332009-09-09 15:08:12 +00001714
Jordy Rose35c86952011-08-24 05:47:39 +00001715 const char *getDescription() const { return ""; }
Mike Stump1eb44332009-09-09 15:08:12 +00001716
Ted Kremenekc887d132009-04-29 18:50:19 +00001717 bool isLeak() const { return true; }
1718 };
Mike Stump1eb44332009-09-09 15:08:12 +00001719
Ted Kremenekc887d132009-04-29 18:50:19 +00001720 //===---------===//
1721 // Bug Reports. //
1722 //===---------===//
Mike Stump1eb44332009-09-09 15:08:12 +00001723
Jordy Rose01153492012-03-24 02:45:35 +00001724 class CFRefReportVisitor : public BugReporterVisitorImpl<CFRefReportVisitor> {
Anna Zaks23f395e2011-08-20 01:27:22 +00001725 protected:
Anna Zaksdc757b02011-08-19 23:21:56 +00001726 SymbolRef Sym;
Jordy Roseec9ef852011-08-23 20:55:48 +00001727 const SummaryLogTy &SummaryLog;
Jordy Rose35c86952011-08-24 05:47:39 +00001728 bool GCEnabled;
Anna Zaks23f395e2011-08-20 01:27:22 +00001729
Anna Zaksdc757b02011-08-19 23:21:56 +00001730 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001731 CFRefReportVisitor(SymbolRef sym, bool gcEnabled, const SummaryLogTy &log)
1732 : Sym(sym), SummaryLog(log), GCEnabled(gcEnabled) {}
Anna Zaksdc757b02011-08-19 23:21:56 +00001733
Anna Zaks23f395e2011-08-20 01:27:22 +00001734 virtual void Profile(llvm::FoldingSetNodeID &ID) const {
Anna Zaksdc757b02011-08-19 23:21:56 +00001735 static int x = 0;
1736 ID.AddPointer(&x);
1737 ID.AddPointer(Sym);
1738 }
1739
Anna Zaks23f395e2011-08-20 01:27:22 +00001740 virtual PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
1741 const ExplodedNode *PrevN,
1742 BugReporterContext &BRC,
1743 BugReport &BR);
1744
1745 virtual PathDiagnosticPiece *getEndPath(BugReporterContext &BRC,
1746 const ExplodedNode *N,
1747 BugReport &BR);
1748 };
1749
1750 class CFRefLeakReportVisitor : public CFRefReportVisitor {
1751 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001752 CFRefLeakReportVisitor(SymbolRef sym, bool GCEnabled,
Jordy Roseec9ef852011-08-23 20:55:48 +00001753 const SummaryLogTy &log)
Jordy Rose35c86952011-08-24 05:47:39 +00001754 : CFRefReportVisitor(sym, GCEnabled, log) {}
Anna Zaks23f395e2011-08-20 01:27:22 +00001755
1756 PathDiagnosticPiece *getEndPath(BugReporterContext &BRC,
1757 const ExplodedNode *N,
1758 BugReport &BR);
Jordy Rose01153492012-03-24 02:45:35 +00001759
1760 virtual BugReporterVisitor *clone() const {
1761 // The curiously-recurring template pattern only works for one level of
1762 // subclassing. Rather than make a new template base for
1763 // CFRefReportVisitor, we simply override clone() to do the right thing.
1764 // This could be trouble someday if BugReporterVisitorImpl is ever
1765 // used for something else besides a convenient implementation of clone().
1766 return new CFRefLeakReportVisitor(*this);
1767 }
Anna Zaksdc757b02011-08-19 23:21:56 +00001768 };
1769
Anna Zakse172e8b2011-08-17 23:00:25 +00001770 class CFRefReport : public BugReport {
Jordy Rose20589562011-08-24 22:39:09 +00001771 void addGCModeDescription(const LangOptions &LOpts, bool GCEnabled);
Jordy Rose35c86952011-08-24 05:47:39 +00001772
Ted Kremenekc887d132009-04-29 18:50:19 +00001773 public:
Jordy Rose20589562011-08-24 22:39:09 +00001774 CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1775 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1776 bool registerVisitor = true)
Anna Zaksedf4dae2011-08-22 18:54:07 +00001777 : BugReport(D, D.getDescription(), n) {
Anna Zaks23f395e2011-08-20 01:27:22 +00001778 if (registerVisitor)
Jordy Rose20589562011-08-24 22:39:09 +00001779 addVisitor(new CFRefReportVisitor(sym, GCEnabled, Log));
1780 addGCModeDescription(LOpts, GCEnabled);
Anna Zaksdc757b02011-08-19 23:21:56 +00001781 }
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001782
Jordy Rose20589562011-08-24 22:39:09 +00001783 CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1784 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1785 StringRef endText)
Anna Zaksedf4dae2011-08-22 18:54:07 +00001786 : BugReport(D, D.getDescription(), endText, n) {
Jordy Rose20589562011-08-24 22:39:09 +00001787 addVisitor(new CFRefReportVisitor(sym, GCEnabled, Log));
1788 addGCModeDescription(LOpts, GCEnabled);
Anna Zaksdc757b02011-08-19 23:21:56 +00001789 }
Mike Stump1eb44332009-09-09 15:08:12 +00001790
Anna Zakse172e8b2011-08-17 23:00:25 +00001791 virtual std::pair<ranges_iterator, ranges_iterator> getRanges() {
Anna Zaksedf4dae2011-08-22 18:54:07 +00001792 const CFRefBug& BugTy = static_cast<CFRefBug&>(getBugType());
1793 if (!BugTy.isLeak())
Anna Zakse172e8b2011-08-17 23:00:25 +00001794 return BugReport::getRanges();
Ted Kremenekc887d132009-04-29 18:50:19 +00001795 else
Argyrios Kyrtzidis640ccf02010-12-04 01:12:15 +00001796 return std::make_pair(ranges_iterator(), ranges_iterator());
Ted Kremenekc887d132009-04-29 18:50:19 +00001797 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001798 };
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001799
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001800 class CFRefLeakReport : public CFRefReport {
Ted Kremenekc887d132009-04-29 18:50:19 +00001801 const MemRegion* AllocBinding;
Anna Zaks23f395e2011-08-20 01:27:22 +00001802
Ted Kremenekc887d132009-04-29 18:50:19 +00001803 public:
Jordy Rose20589562011-08-24 22:39:09 +00001804 CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1805 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
Anna Zaks6a93bd52011-10-25 19:57:11 +00001806 CheckerContext &Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001807
Anna Zaks590dd8e2011-09-20 21:38:35 +00001808 PathDiagnosticLocation getLocation(const SourceManager &SM) const {
1809 assert(Location.isValid());
1810 return Location;
1811 }
Mike Stump1eb44332009-09-09 15:08:12 +00001812 };
Ted Kremenekc887d132009-04-29 18:50:19 +00001813} // end anonymous namespace
1814
Jordy Rose20589562011-08-24 22:39:09 +00001815void CFRefReport::addGCModeDescription(const LangOptions &LOpts,
1816 bool GCEnabled) {
Jordy Rosef95b19d2011-08-24 20:38:42 +00001817 const char *GCModeDescription = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001818
Douglas Gregore289d812011-09-13 17:21:33 +00001819 switch (LOpts.getGC()) {
Anna Zaks7f2531c2011-08-22 20:31:28 +00001820 case LangOptions::GCOnly:
Jordy Rose20589562011-08-24 22:39:09 +00001821 assert(GCEnabled);
Jordy Rose35c86952011-08-24 05:47:39 +00001822 GCModeDescription = "Code is compiled to only use garbage collection";
1823 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001824
Anna Zaks7f2531c2011-08-22 20:31:28 +00001825 case LangOptions::NonGC:
Jordy Rose20589562011-08-24 22:39:09 +00001826 assert(!GCEnabled);
Jordy Rose35c86952011-08-24 05:47:39 +00001827 GCModeDescription = "Code is compiled to use reference counts";
1828 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001829
Anna Zaks7f2531c2011-08-22 20:31:28 +00001830 case LangOptions::HybridGC:
Jordy Rose20589562011-08-24 22:39:09 +00001831 if (GCEnabled) {
Jordy Rose35c86952011-08-24 05:47:39 +00001832 GCModeDescription = "Code is compiled to use either garbage collection "
1833 "(GC) or reference counts (non-GC). The bug occurs "
1834 "with GC enabled";
1835 break;
1836 } else {
1837 GCModeDescription = "Code is compiled to use either garbage collection "
1838 "(GC) or reference counts (non-GC). The bug occurs "
1839 "in non-GC mode";
1840 break;
Anna Zaks7f2531c2011-08-22 20:31:28 +00001841 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001842 }
Jordy Rose35c86952011-08-24 05:47:39 +00001843
Jordy Rosef95b19d2011-08-24 20:38:42 +00001844 assert(GCModeDescription && "invalid/unknown GC mode");
Jordy Rose35c86952011-08-24 05:47:39 +00001845 addExtraText(GCModeDescription);
Ted Kremenekc887d132009-04-29 18:50:19 +00001846}
1847
Jordy Rose910c4052011-09-02 06:44:22 +00001848// FIXME: This should be a method on SmallVector.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001849static inline bool contains(const SmallVectorImpl<ArgEffect>& V,
Ted Kremenekc887d132009-04-29 18:50:19 +00001850 ArgEffect X) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001851 for (SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
Ted Kremenekc887d132009-04-29 18:50:19 +00001852 I!=E; ++I)
1853 if (*I == X) return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001854
Ted Kremenekc887d132009-04-29 18:50:19 +00001855 return false;
1856}
1857
Jordy Rose70fdbc32012-05-12 05:10:43 +00001858static bool isNumericLiteralExpression(const Expr *E) {
1859 // FIXME: This set of cases was copied from SemaExprObjC.
1860 return isa<IntegerLiteral>(E) ||
1861 isa<CharacterLiteral>(E) ||
1862 isa<FloatingLiteral>(E) ||
1863 isa<ObjCBoolLiteralExpr>(E) ||
1864 isa<CXXBoolLiteralExpr>(E);
1865}
1866
Ted Kremenek4c42bb72011-11-14 21:59:21 +00001867static bool isPropertyAccess(const Stmt *S, ParentMap &PM) {
1868 unsigned maxDepth = 4;
1869 while (S && maxDepth) {
1870 if (const PseudoObjectExpr *PO = dyn_cast<PseudoObjectExpr>(S)) {
1871 if (!isa<ObjCMessageExpr>(PO->getSyntacticForm()))
1872 return true;
1873 return false;
1874 }
1875 S = PM.getParent(S);
1876 --maxDepth;
1877 }
1878 return false;
1879}
1880
Anna Zaksdc757b02011-08-19 23:21:56 +00001881PathDiagnosticPiece *CFRefReportVisitor::VisitNode(const ExplodedNode *N,
1882 const ExplodedNode *PrevN,
1883 BugReporterContext &BRC,
1884 BugReport &BR) {
Mike Stump1eb44332009-09-09 15:08:12 +00001885
Jordy Rosef53e8c72011-08-23 19:43:16 +00001886 if (!isa<StmtPoint>(N->getLocation()))
Ted Kremenek2033a952009-05-13 07:12:33 +00001887 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001888
Ted Kremenek8966bc12009-05-06 21:39:49 +00001889 // Check if the type state has changed.
Ted Kremenek8bef8232012-01-26 21:29:00 +00001890 ProgramStateRef PrevSt = PrevN->getState();
1891 ProgramStateRef CurrSt = N->getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001892 const LocationContext *LCtx = N->getLocationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00001893
1894 const RefVal* CurrT = CurrSt->get<RefBindings>(Sym);
Ted Kremenekc887d132009-04-29 18:50:19 +00001895 if (!CurrT) return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001896
Ted Kremenekb65be702009-06-18 01:23:53 +00001897 const RefVal &CurrV = *CurrT;
1898 const RefVal *PrevT = PrevSt->get<RefBindings>(Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00001899
Ted Kremenekc887d132009-04-29 18:50:19 +00001900 // Create a string buffer to constain all the useful things we want
1901 // to tell the user.
1902 std::string sbuf;
1903 llvm::raw_string_ostream os(sbuf);
Mike Stump1eb44332009-09-09 15:08:12 +00001904
Ted Kremenekc887d132009-04-29 18:50:19 +00001905 // This is the allocation site since the previous node had no bindings
1906 // for this symbol.
1907 if (!PrevT) {
Jordy Rosef53e8c72011-08-23 19:43:16 +00001908 const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
Mike Stump1eb44332009-09-09 15:08:12 +00001909
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001910 if (isa<ObjCArrayLiteral>(S)) {
1911 os << "NSArray literal is an object with a +0 retain count";
Mike Stump1eb44332009-09-09 15:08:12 +00001912 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001913 else if (isa<ObjCDictionaryLiteral>(S)) {
1914 os << "NSDictionary literal is an object with a +0 retain count";
Ted Kremenekc887d132009-04-29 18:50:19 +00001915 }
Jordy Rose70fdbc32012-05-12 05:10:43 +00001916 else if (const ObjCBoxedExpr *BL = dyn_cast<ObjCBoxedExpr>(S)) {
1917 if (isNumericLiteralExpression(BL->getSubExpr()))
1918 os << "NSNumber literal is an object with a +0 retain count";
1919 else {
1920 const ObjCInterfaceDecl *BoxClass = 0;
1921 if (const ObjCMethodDecl *Method = BL->getBoxingMethod())
1922 BoxClass = Method->getClassInterface();
1923
1924 // We should always be able to find the boxing class interface,
1925 // but consider this future-proofing.
1926 if (BoxClass)
1927 os << *BoxClass << " b";
1928 else
1929 os << "B";
1930
1931 os << "oxed expression produces an object with a +0 retain count";
1932 }
1933 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001934 else {
1935 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
1936 // Get the name of the callee (if it is available).
1937 SVal X = CurrSt->getSValAsScalarOrLoc(CE->getCallee(), LCtx);
1938 if (const FunctionDecl *FD = X.getAsFunctionDecl())
1939 os << "Call to function '" << *FD << '\'';
1940 else
1941 os << "function call";
Ted Kremenekc887d132009-04-29 18:50:19 +00001942 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001943 else {
1944 assert(isa<ObjCMessageExpr>(S));
1945 // The message expression may have between written directly or as
1946 // a property access. Lazily determine which case we are looking at.
1947 os << (isPropertyAccess(S, N->getParentMap()) ? "Property" : "Method");
1948 }
1949
1950 if (CurrV.getObjKind() == RetEffect::CF) {
1951 os << " returns a Core Foundation object with a ";
1952 }
1953 else {
1954 assert (CurrV.getObjKind() == RetEffect::ObjC);
1955 os << " returns an Objective-C object with a ";
1956 }
1957
1958 if (CurrV.isOwned()) {
1959 os << "+1 retain count";
1960
1961 if (GCEnabled) {
1962 assert(CurrV.getObjKind() == RetEffect::CF);
1963 os << ". "
1964 "Core Foundation objects are not automatically garbage collected.";
1965 }
1966 }
1967 else {
1968 assert (CurrV.isNotOwned());
1969 os << "+0 retain count";
1970 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001971 }
Mike Stump1eb44332009-09-09 15:08:12 +00001972
Anna Zaks220ac8c2011-09-15 01:08:34 +00001973 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
1974 N->getLocationContext());
Ted Kremenekc887d132009-04-29 18:50:19 +00001975 return new PathDiagnosticEventPiece(Pos, os.str());
1976 }
Mike Stump1eb44332009-09-09 15:08:12 +00001977
Ted Kremenekc887d132009-04-29 18:50:19 +00001978 // Gather up the effects that were performed on the object at this
1979 // program point
Chris Lattner5f9e2722011-07-23 10:55:15 +00001980 SmallVector<ArgEffect, 2> AEffects;
Mike Stump1eb44332009-09-09 15:08:12 +00001981
Jordy Roseec9ef852011-08-23 20:55:48 +00001982 const ExplodedNode *OrigNode = BRC.getNodeResolver().getOriginalNode(N);
1983 if (const RetainSummary *Summ = SummaryLog.lookup(OrigNode)) {
Ted Kremenekc887d132009-04-29 18:50:19 +00001984 // We only have summaries attached to nodes after evaluating CallExpr and
1985 // ObjCMessageExprs.
Jordy Rosef53e8c72011-08-23 19:43:16 +00001986 const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
Mike Stump1eb44332009-09-09 15:08:12 +00001987
Ted Kremenek5f85e172009-07-22 22:35:28 +00001988 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
Ted Kremenekc887d132009-04-29 18:50:19 +00001989 // Iterate through the parameter expressions and see if the symbol
1990 // was ever passed as an argument.
1991 unsigned i = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001992
Ted Kremenek5f85e172009-07-22 22:35:28 +00001993 for (CallExpr::const_arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
Ted Kremenekc887d132009-04-29 18:50:19 +00001994 AI!=AE; ++AI, ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00001995
Ted Kremenekc887d132009-04-29 18:50:19 +00001996 // Retrieve the value of the argument. Is it the symbol
1997 // we are interested in?
Ted Kremenek5eca4822012-01-06 22:09:28 +00001998 if (CurrSt->getSValAsScalarOrLoc(*AI, LCtx).getAsLocSymbol() != Sym)
Ted Kremenekc887d132009-04-29 18:50:19 +00001999 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00002000
Ted Kremenekc887d132009-04-29 18:50:19 +00002001 // We have an argument. Get the effect!
2002 AEffects.push_back(Summ->getArg(i));
2003 }
2004 }
Mike Stump1eb44332009-09-09 15:08:12 +00002005 else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002006 if (const Expr *receiver = ME->getInstanceReceiver())
Ted Kremenek5eca4822012-01-06 22:09:28 +00002007 if (CurrSt->getSValAsScalarOrLoc(receiver, LCtx)
2008 .getAsLocSymbol() == Sym) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002009 // The symbol we are tracking is the receiver.
2010 AEffects.push_back(Summ->getReceiverEffect());
2011 }
2012 }
2013 }
Mike Stump1eb44332009-09-09 15:08:12 +00002014
Ted Kremenekc887d132009-04-29 18:50:19 +00002015 do {
2016 // Get the previous type state.
2017 RefVal PrevV = *PrevT;
Mike Stump1eb44332009-09-09 15:08:12 +00002018
Ted Kremenekc887d132009-04-29 18:50:19 +00002019 // Specially handle -dealloc.
Jordy Rose35c86952011-08-24 05:47:39 +00002020 if (!GCEnabled && contains(AEffects, Dealloc)) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002021 // Determine if the object's reference count was pushed to zero.
2022 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2023 // We may not have transitioned to 'release' if we hit an error.
2024 // This case is handled elsewhere.
2025 if (CurrV.getKind() == RefVal::Released) {
Ted Kremenekf21332e2009-05-08 20:01:42 +00002026 assert(CurrV.getCombinedCounts() == 0);
Ted Kremenekc887d132009-04-29 18:50:19 +00002027 os << "Object released by directly sending the '-dealloc' message";
2028 break;
2029 }
2030 }
Mike Stump1eb44332009-09-09 15:08:12 +00002031
Ted Kremenekc887d132009-04-29 18:50:19 +00002032 // Specially handle CFMakeCollectable and friends.
2033 if (contains(AEffects, MakeCollectable)) {
2034 // Get the name of the function.
Jordy Rosef53e8c72011-08-23 19:43:16 +00002035 const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
Ted Kremenek5eca4822012-01-06 22:09:28 +00002036 SVal X =
2037 CurrSt->getSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee(), LCtx);
Ted Kremenek9c378f72011-08-12 23:37:29 +00002038 const FunctionDecl *FD = X.getAsFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002039
Jordy Rose35c86952011-08-24 05:47:39 +00002040 if (GCEnabled) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002041 // Determine if the object's reference count was pushed to zero.
2042 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
Mike Stump1eb44332009-09-09 15:08:12 +00002043
Benjamin Kramerb8989f22011-10-14 18:45:37 +00002044 os << "In GC mode a call to '" << *FD
Ted Kremenekc887d132009-04-29 18:50:19 +00002045 << "' decrements an object's retain count and registers the "
2046 "object with the garbage collector. ";
Mike Stump1eb44332009-09-09 15:08:12 +00002047
Ted Kremenekc887d132009-04-29 18:50:19 +00002048 if (CurrV.getKind() == RefVal::Released) {
2049 assert(CurrV.getCount() == 0);
2050 os << "Since it now has a 0 retain count the object can be "
2051 "automatically collected by the garbage collector.";
2052 }
2053 else
2054 os << "An object must have a 0 retain count to be garbage collected. "
2055 "After this call its retain count is +" << CurrV.getCount()
2056 << '.';
2057 }
Mike Stump1eb44332009-09-09 15:08:12 +00002058 else
Benjamin Kramerb8989f22011-10-14 18:45:37 +00002059 os << "When GC is not enabled a call to '" << *FD
Ted Kremenekc887d132009-04-29 18:50:19 +00002060 << "' has no effect on its argument.";
Mike Stump1eb44332009-09-09 15:08:12 +00002061
Ted Kremenekc887d132009-04-29 18:50:19 +00002062 // Nothing more to say.
2063 break;
2064 }
Mike Stump1eb44332009-09-09 15:08:12 +00002065
2066 // Determine if the typestate has changed.
Ted Kremenekc887d132009-04-29 18:50:19 +00002067 if (!(PrevV == CurrV))
2068 switch (CurrV.getKind()) {
2069 case RefVal::Owned:
2070 case RefVal::NotOwned:
Mike Stump1eb44332009-09-09 15:08:12 +00002071
Ted Kremenekf21332e2009-05-08 20:01:42 +00002072 if (PrevV.getCount() == CurrV.getCount()) {
2073 // Did an autorelease message get sent?
2074 if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
2075 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002076
Zhongxing Xu264e9372009-05-12 10:10:00 +00002077 assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount());
Ted Kremenekeaedfea2009-05-10 05:11:21 +00002078 os << "Object sent -autorelease message";
Ted Kremenekf21332e2009-05-08 20:01:42 +00002079 break;
2080 }
Mike Stump1eb44332009-09-09 15:08:12 +00002081
Ted Kremenekc887d132009-04-29 18:50:19 +00002082 if (PrevV.getCount() > CurrV.getCount())
2083 os << "Reference count decremented.";
2084 else
2085 os << "Reference count incremented.";
Mike Stump1eb44332009-09-09 15:08:12 +00002086
Ted Kremenekc887d132009-04-29 18:50:19 +00002087 if (unsigned Count = CurrV.getCount())
2088 os << " The object now has a +" << Count << " retain count.";
Mike Stump1eb44332009-09-09 15:08:12 +00002089
Ted Kremenekc887d132009-04-29 18:50:19 +00002090 if (PrevV.getKind() == RefVal::Released) {
Jordy Rose35c86952011-08-24 05:47:39 +00002091 assert(GCEnabled && CurrV.getCount() > 0);
Jordy Rose74b7b2b2012-03-17 05:49:15 +00002092 os << " The object is not eligible for garbage collection until "
2093 "the retain count reaches 0 again.";
Ted Kremenekc887d132009-04-29 18:50:19 +00002094 }
Mike Stump1eb44332009-09-09 15:08:12 +00002095
Ted Kremenekc887d132009-04-29 18:50:19 +00002096 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002097
Ted Kremenekc887d132009-04-29 18:50:19 +00002098 case RefVal::Released:
2099 os << "Object released.";
2100 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002101
Ted Kremenekc887d132009-04-29 18:50:19 +00002102 case RefVal::ReturnedOwned:
Jordy Rose74b7b2b2012-03-17 05:49:15 +00002103 // Autoreleases can be applied after marking a node ReturnedOwned.
2104 if (CurrV.getAutoreleaseCount())
2105 return NULL;
2106
2107 os << "Object returned to caller as an owning reference (single "
2108 "retain count transferred to caller)";
Ted Kremenekc887d132009-04-29 18:50:19 +00002109 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002110
Ted Kremenekc887d132009-04-29 18:50:19 +00002111 case RefVal::ReturnedNotOwned:
Ted Kremenekf1365462011-05-26 18:45:44 +00002112 os << "Object returned to caller with a +0 retain count";
Ted Kremenekc887d132009-04-29 18:50:19 +00002113 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002114
Ted Kremenekc887d132009-04-29 18:50:19 +00002115 default:
2116 return NULL;
2117 }
Mike Stump1eb44332009-09-09 15:08:12 +00002118
Ted Kremenekc887d132009-04-29 18:50:19 +00002119 // Emit any remaining diagnostics for the argument effects (if any).
Chris Lattner5f9e2722011-07-23 10:55:15 +00002120 for (SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
Ted Kremenekc887d132009-04-29 18:50:19 +00002121 E=AEffects.end(); I != E; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +00002122
Ted Kremenekc887d132009-04-29 18:50:19 +00002123 // A bunch of things have alternate behavior under GC.
Jordy Rose35c86952011-08-24 05:47:39 +00002124 if (GCEnabled)
Ted Kremenekc887d132009-04-29 18:50:19 +00002125 switch (*I) {
2126 default: break;
2127 case Autorelease:
2128 os << "In GC mode an 'autorelease' has no effect.";
2129 continue;
2130 case IncRefMsg:
2131 os << "In GC mode the 'retain' message has no effect.";
2132 continue;
2133 case DecRefMsg:
2134 os << "In GC mode the 'release' message has no effect.";
2135 continue;
2136 }
2137 }
Mike Stump1eb44332009-09-09 15:08:12 +00002138 } while (0);
2139
Ted Kremenekc887d132009-04-29 18:50:19 +00002140 if (os.str().empty())
2141 return 0; // We have nothing to say!
Ted Kremenek2033a952009-05-13 07:12:33 +00002142
Jordy Rosef53e8c72011-08-23 19:43:16 +00002143 const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
Anna Zaks220ac8c2011-09-15 01:08:34 +00002144 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
2145 N->getLocationContext());
Ted Kremenek9c378f72011-08-12 23:37:29 +00002146 PathDiagnosticPiece *P = new PathDiagnosticEventPiece(Pos, os.str());
Mike Stump1eb44332009-09-09 15:08:12 +00002147
Ted Kremenekc887d132009-04-29 18:50:19 +00002148 // Add the range by scanning the children of the statement for any bindings
2149 // to Sym.
Mike Stump1eb44332009-09-09 15:08:12 +00002150 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
Ted Kremenek5f85e172009-07-22 22:35:28 +00002151 I!=E; ++I)
Ted Kremenek9c378f72011-08-12 23:37:29 +00002152 if (const Expr *Exp = dyn_cast_or_null<Expr>(*I))
Ted Kremenek5eca4822012-01-06 22:09:28 +00002153 if (CurrSt->getSValAsScalarOrLoc(Exp, LCtx).getAsLocSymbol() == Sym) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002154 P->addRange(Exp->getSourceRange());
2155 break;
2156 }
Mike Stump1eb44332009-09-09 15:08:12 +00002157
Ted Kremenekc887d132009-04-29 18:50:19 +00002158 return P;
2159}
2160
Anna Zakse7e01682012-02-28 22:39:22 +00002161// Find the first node in the current function context that referred to the
2162// tracked symbol and the memory location that value was stored to. Note, the
2163// value is only reported if the allocation occurred in the same function as
2164// the leak.
Zhongxing Xuc5619d92009-08-06 01:32:16 +00002165static std::pair<const ExplodedNode*,const MemRegion*>
Ted Kremenek18c66fd2011-08-15 22:09:50 +00002166GetAllocationSite(ProgramStateManager& StateMgr, const ExplodedNode *N,
Ted Kremenekc887d132009-04-29 18:50:19 +00002167 SymbolRef Sym) {
Ted Kremenek9c378f72011-08-12 23:37:29 +00002168 const ExplodedNode *Last = N;
Mike Stump1eb44332009-09-09 15:08:12 +00002169 const MemRegion* FirstBinding = 0;
Anna Zakse7e01682012-02-28 22:39:22 +00002170 const LocationContext *LeakContext = N->getLocationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002171
Ted Kremenekc887d132009-04-29 18:50:19 +00002172 while (N) {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002173 ProgramStateRef St = N->getState();
Ted Kremenekc887d132009-04-29 18:50:19 +00002174 RefBindings B = St->get<RefBindings>();
Mike Stump1eb44332009-09-09 15:08:12 +00002175
Ted Kremenekc887d132009-04-29 18:50:19 +00002176 if (!B.lookup(Sym))
2177 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002178
Anna Zaks27b867e2012-03-21 19:45:01 +00002179 StoreManager::FindUniqueBinding FB(Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002180 StateMgr.iterBindings(St, FB);
2181 if (FB) FirstBinding = FB.getRegion();
2182
Anna Zakse7e01682012-02-28 22:39:22 +00002183 // Allocation node, is the last node in the current context in which the
2184 // symbol was tracked.
2185 if (N->getLocationContext() == LeakContext)
2186 Last = N;
2187
Mike Stump1eb44332009-09-09 15:08:12 +00002188 N = N->pred_empty() ? NULL : *(N->pred_begin());
Ted Kremenekc887d132009-04-29 18:50:19 +00002189 }
Mike Stump1eb44332009-09-09 15:08:12 +00002190
Anna Zakse7e01682012-02-28 22:39:22 +00002191 // If allocation happened in a function different from the leak node context,
2192 // do not report the binding.
2193 if (N->getLocationContext() != LeakContext) {
2194 FirstBinding = 0;
2195 }
2196
Ted Kremenekc887d132009-04-29 18:50:19 +00002197 return std::make_pair(Last, FirstBinding);
2198}
2199
2200PathDiagnosticPiece*
Anna Zaks23f395e2011-08-20 01:27:22 +00002201CFRefReportVisitor::getEndPath(BugReporterContext &BRC,
2202 const ExplodedNode *EndN,
2203 BugReport &BR) {
Ted Kremenek76aadc32012-03-09 01:13:14 +00002204 BR.markInteresting(Sym);
Anna Zaks23f395e2011-08-20 01:27:22 +00002205 return BugReporterVisitor::getDefaultEndPath(BRC, EndN, BR);
Ted Kremenekc887d132009-04-29 18:50:19 +00002206}
2207
2208PathDiagnosticPiece*
Anna Zaks23f395e2011-08-20 01:27:22 +00002209CFRefLeakReportVisitor::getEndPath(BugReporterContext &BRC,
2210 const ExplodedNode *EndN,
2211 BugReport &BR) {
Mike Stump1eb44332009-09-09 15:08:12 +00002212
Ted Kremenek8966bc12009-05-06 21:39:49 +00002213 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenekc887d132009-04-29 18:50:19 +00002214 // assigned to different variables, etc.
Ted Kremenek76aadc32012-03-09 01:13:14 +00002215 BR.markInteresting(Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002216
Ted Kremenekc887d132009-04-29 18:50:19 +00002217 // We are reporting a leak. Walk up the graph to get to the first node where
2218 // the symbol appeared, and also get the first VarDecl that tracked object
2219 // is stored to.
Ted Kremenek9c378f72011-08-12 23:37:29 +00002220 const ExplodedNode *AllocNode = 0;
Ted Kremenekc887d132009-04-29 18:50:19 +00002221 const MemRegion* FirstBinding = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002222
Ted Kremenekc887d132009-04-29 18:50:19 +00002223 llvm::tie(AllocNode, FirstBinding) =
Ted Kremenekf04dced2009-05-08 23:32:51 +00002224 GetAllocationSite(BRC.getStateManager(), EndN, Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002225
Anna Zaks4fdf97b2011-09-15 18:56:07 +00002226 SourceManager& SM = BRC.getSourceManager();
Mike Stump1eb44332009-09-09 15:08:12 +00002227
Ted Kremenekc887d132009-04-29 18:50:19 +00002228 // Compute an actual location for the leak. Sometimes a leak doesn't
2229 // occur at an actual statement (e.g., transition between blocks; end
2230 // of function) so we need to walk the graph and compute a real location.
Ted Kremenek9c378f72011-08-12 23:37:29 +00002231 const ExplodedNode *LeakN = EndN;
Anna Zaks4fdf97b2011-09-15 18:56:07 +00002232 PathDiagnosticLocation L = PathDiagnosticLocation::createEndOfPath(LeakN, SM);
Mike Stump1eb44332009-09-09 15:08:12 +00002233
Ted Kremenekc887d132009-04-29 18:50:19 +00002234 std::string sbuf;
2235 llvm::raw_string_ostream os(sbuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002236
Ted Kremenekf1365462011-05-26 18:45:44 +00002237 os << "Object leaked: ";
Mike Stump1eb44332009-09-09 15:08:12 +00002238
Ted Kremenekf1365462011-05-26 18:45:44 +00002239 if (FirstBinding) {
2240 os << "object allocated and stored into '"
2241 << FirstBinding->getString() << '\'';
2242 }
2243 else
2244 os << "allocated object";
Mike Stump1eb44332009-09-09 15:08:12 +00002245
Ted Kremenekc887d132009-04-29 18:50:19 +00002246 // Get the retain count.
2247 const RefVal* RV = EndN->getState()->get<RefBindings>(Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002248
Ted Kremenekc887d132009-04-29 18:50:19 +00002249 if (RV->getKind() == RefVal::ErrorLeakReturned) {
2250 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
Jordy Rose5b5402b2011-07-15 22:17:54 +00002251 // objects. Only "copy", "alloc", "retain" and "new" transfer ownership
Ted Kremenekc887d132009-04-29 18:50:19 +00002252 // to the caller for NS objects.
Ted Kremenekd368d712011-05-25 06:19:45 +00002253 const Decl *D = &EndN->getCodeDecl();
2254 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2255 os << " is returned from a method whose name ('"
2256 << MD->getSelector().getAsString()
2257 << "') does not start with 'copy', 'mutableCopy', 'alloc' or 'new'."
Jordy Rose5b5402b2011-07-15 22:17:54 +00002258 " This violates the naming convention rules"
Ted Kremenekf1365462011-05-26 18:45:44 +00002259 " given in the Memory Management Guide for Cocoa";
Ted Kremenekd368d712011-05-25 06:19:45 +00002260 }
2261 else {
2262 const FunctionDecl *FD = cast<FunctionDecl>(D);
Ted Kremenekb7dcddf2011-12-22 06:35:52 +00002263 os << " is returned from a function whose name ('"
Benjamin Kramera59d20b2012-02-07 11:57:57 +00002264 << *FD
Ted Kremenekd368d712011-05-25 06:19:45 +00002265 << "') does not contain 'Copy' or 'Create'. This violates the naming"
Ted Kremenekb7dcddf2011-12-22 06:35:52 +00002266 " convention rules given in the Memory Management Guide for Core"
Ted Kremenekf1365462011-05-26 18:45:44 +00002267 " Foundation";
Ted Kremenekd368d712011-05-25 06:19:45 +00002268 }
Ted Kremenekc887d132009-04-29 18:50:19 +00002269 }
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002270 else if (RV->getKind() == RefVal::ErrorGCLeakReturned) {
Ted Kremenek9c378f72011-08-12 23:37:29 +00002271 ObjCMethodDecl &MD = cast<ObjCMethodDecl>(EndN->getCodeDecl());
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002272 os << " and returned from method '" << MD.getSelector().getAsString()
Ted Kremenek82f2be52009-05-10 16:52:15 +00002273 << "' is potentially leaked when using garbage collection. Callers "
2274 "of this method do not expect a returned object with a +1 retain "
2275 "count since they expect the object to be managed by the garbage "
2276 "collector";
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002277 }
Ted Kremenekc887d132009-04-29 18:50:19 +00002278 else
Ted Kremenekabf517c2010-10-15 22:50:23 +00002279 os << " is not referenced later in this execution path and has a retain "
Ted Kremenekf1365462011-05-26 18:45:44 +00002280 "count of +" << RV->getCount();
Mike Stump1eb44332009-09-09 15:08:12 +00002281
Ted Kremenekc887d132009-04-29 18:50:19 +00002282 return new PathDiagnosticEventPiece(L, os.str());
2283}
2284
Jordy Rose20589562011-08-24 22:39:09 +00002285CFRefLeakReport::CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts,
2286 bool GCEnabled, const SummaryLogTy &Log,
2287 ExplodedNode *n, SymbolRef sym,
Anna Zaks6a93bd52011-10-25 19:57:11 +00002288 CheckerContext &Ctx)
Jordy Rose20589562011-08-24 22:39:09 +00002289: CFRefReport(D, LOpts, GCEnabled, Log, n, sym, false) {
Mike Stump1eb44332009-09-09 15:08:12 +00002290
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00002291 // Most bug reports are cached at the location where they occurred.
Ted Kremenekc887d132009-04-29 18:50:19 +00002292 // With leaks, we want to unique them by the location where they were
2293 // allocated, and only report a single path. To do this, we need to find
2294 // the allocation site of a piece of tracked memory, which we do via a
2295 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2296 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2297 // that all ancestor nodes that represent the allocation site have the
2298 // same SourceLocation.
Ted Kremenek9c378f72011-08-12 23:37:29 +00002299 const ExplodedNode *AllocNode = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002300
Anna Zaks6a93bd52011-10-25 19:57:11 +00002301 const SourceManager& SMgr = Ctx.getSourceManager();
Anna Zaks590dd8e2011-09-20 21:38:35 +00002302
Ted Kremenekc887d132009-04-29 18:50:19 +00002303 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding.
Anna Zaks6a93bd52011-10-25 19:57:11 +00002304 GetAllocationSite(Ctx.getStateManager(), getErrorNode(), sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002305
Ted Kremenekc887d132009-04-29 18:50:19 +00002306 // Get the SourceLocation for the allocation site.
2307 ProgramPoint P = AllocNode->getLocation();
Anna Zaks590dd8e2011-09-20 21:38:35 +00002308 const Stmt *AllocStmt = cast<PostStmt>(P).getStmt();
2309 Location = PathDiagnosticLocation::createBegin(AllocStmt, SMgr,
2310 n->getLocationContext());
Ted Kremenekc887d132009-04-29 18:50:19 +00002311 // Fill in the description of the bug.
2312 Description.clear();
2313 llvm::raw_string_ostream os(Description);
Ted Kremenekdd924e22009-05-02 19:05:19 +00002314 os << "Potential leak ";
Jordy Rose20589562011-08-24 22:39:09 +00002315 if (GCEnabled)
Ted Kremenekdd924e22009-05-02 19:05:19 +00002316 os << "(when using garbage collection) ";
Anna Zaks212000e2012-02-28 21:49:08 +00002317 os << "of an object";
Mike Stump1eb44332009-09-09 15:08:12 +00002318
Ted Kremenekc887d132009-04-29 18:50:19 +00002319 // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2320 if (AllocBinding)
Anna Zaks212000e2012-02-28 21:49:08 +00002321 os << " stored into '" << AllocBinding->getString() << '\'';
Anna Zaksdc757b02011-08-19 23:21:56 +00002322
Jordy Rose20589562011-08-24 22:39:09 +00002323 addVisitor(new CFRefLeakReportVisitor(sym, GCEnabled, Log));
Ted Kremenekc887d132009-04-29 18:50:19 +00002324}
2325
2326//===----------------------------------------------------------------------===//
2327// Main checker logic.
2328//===----------------------------------------------------------------------===//
2329
Ted Kremenekd593eb92009-11-25 22:17:44 +00002330namespace {
Jordy Rose910c4052011-09-02 06:44:22 +00002331class RetainCountChecker
Jordy Rose9c083b72011-08-24 18:56:32 +00002332 : public Checker< check::Bind,
Jordy Rose38f17d62011-08-23 19:01:07 +00002333 check::DeadSymbols,
Jordy Rose9c083b72011-08-24 18:56:32 +00002334 check::EndAnalysis,
Jordy Rose38f17d62011-08-23 19:01:07 +00002335 check::EndPath,
Jordy Rose67044292011-08-17 21:27:39 +00002336 check::PostStmt<BlockExpr>,
John McCallf85e1932011-06-15 23:02:42 +00002337 check::PostStmt<CastExpr>,
Jordy Rose294396b2011-08-22 23:48:23 +00002338 check::PostStmt<CallExpr>,
Jordy Rose537716a2011-08-27 22:51:26 +00002339 check::PostStmt<CXXConstructExpr>,
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002340 check::PostStmt<ObjCArrayLiteral>,
2341 check::PostStmt<ObjCDictionaryLiteral>,
Jordy Rose70fdbc32012-05-12 05:10:43 +00002342 check::PostStmt<ObjCBoxedExpr>,
Jordy Rose294396b2011-08-22 23:48:23 +00002343 check::PostObjCMessage,
Jordy Rosef53e8c72011-08-23 19:43:16 +00002344 check::PreStmt<ReturnStmt>,
Jordy Rose67044292011-08-17 21:27:39 +00002345 check::RegionChanges,
Jordy Rose76c506f2011-08-21 21:58:18 +00002346 eval::Assume,
2347 eval::Call > {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002348 mutable OwningPtr<CFRefBug> useAfterRelease, releaseNotOwned;
2349 mutable OwningPtr<CFRefBug> deallocGC, deallocNotOwned;
2350 mutable OwningPtr<CFRefBug> overAutorelease, returnNotOwnedForOwned;
2351 mutable OwningPtr<CFRefBug> leakWithinFunction, leakAtReturn;
2352 mutable OwningPtr<CFRefBug> leakWithinFunctionGC, leakAtReturnGC;
Jordy Rose38f17d62011-08-23 19:01:07 +00002353
2354 typedef llvm::DenseMap<SymbolRef, const SimpleProgramPointTag *> SymbolTagMap;
2355
2356 // This map is only used to ensure proper deletion of any allocated tags.
2357 mutable SymbolTagMap DeadSymbolTags;
2358
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002359 mutable OwningPtr<RetainSummaryManager> Summaries;
2360 mutable OwningPtr<RetainSummaryManager> SummariesGC;
Jordy Roseb6cfc092011-08-25 00:10:37 +00002361
Jordy Rosee0a5d322011-08-23 20:27:16 +00002362 mutable ARCounts::Factory ARCountFactory;
2363
Jordy Rose9c083b72011-08-24 18:56:32 +00002364 mutable SummaryLogTy SummaryLog;
2365 mutable bool ShouldResetSummaryLog;
2366
Jordy Rose2f9a66d2011-08-20 21:17:59 +00002367public:
Jordy Rose910c4052011-09-02 06:44:22 +00002368 RetainCountChecker() : ShouldResetSummaryLog(false) {}
Jordy Rose38f17d62011-08-23 19:01:07 +00002369
Jordy Rose910c4052011-09-02 06:44:22 +00002370 virtual ~RetainCountChecker() {
Jordy Rose38f17d62011-08-23 19:01:07 +00002371 DeleteContainerSeconds(DeadSymbolTags);
2372 }
2373
Jordy Rose9c083b72011-08-24 18:56:32 +00002374 void checkEndAnalysis(ExplodedGraph &G, BugReporter &BR,
2375 ExprEngine &Eng) const {
2376 // FIXME: This is a hack to make sure the summary log gets cleared between
2377 // analyses of different code bodies.
2378 //
2379 // Why is this necessary? Because a checker's lifetime is tied to a
2380 // translation unit, but an ExplodedGraph's lifetime is just a code body.
2381 // Once in a blue moon, a new ExplodedNode will have the same address as an
2382 // old one with an associated summary, and the bug report visitor gets very
2383 // confused. (To make things worse, the summary lifetime is currently also
2384 // tied to a code body, so we get a crash instead of incorrect results.)
Jordy Rose1ab51c72011-08-24 09:27:24 +00002385 //
2386 // Why is this a bad solution? Because if the lifetime of the ExplodedGraph
2387 // changes, things will start going wrong again. Really the lifetime of this
2388 // log needs to be tied to either the specific nodes in it or the entire
2389 // ExplodedGraph, not to a specific part of the code being analyzed.
2390 //
Jordy Rose9c083b72011-08-24 18:56:32 +00002391 // (Also, having stateful local data means that the same checker can't be
2392 // used from multiple threads, but a lot of checkers have incorrect
2393 // assumptions about that anyway. So that wasn't a priority at the time of
2394 // this fix.)
Jordy Rose1ab51c72011-08-24 09:27:24 +00002395 //
Jordy Rose9c083b72011-08-24 18:56:32 +00002396 // This happens at the end of analysis, but bug reports are emitted /after/
2397 // this point. So we can't just clear the summary log now. Instead, we mark
2398 // that the next time we access the summary log, it should be cleared.
2399
2400 // If we never reset the summary log during /this/ code body analysis,
2401 // there were no new summaries. There might still have been summaries from
2402 // the /last/ analysis, so clear them out to make sure the bug report
2403 // visitors don't get confused.
2404 if (ShouldResetSummaryLog)
2405 SummaryLog.clear();
2406
2407 ShouldResetSummaryLog = !SummaryLog.empty();
Jordy Rose1ab51c72011-08-24 09:27:24 +00002408 }
2409
Jordy Rose17a38e22011-09-02 05:55:19 +00002410 CFRefBug *getLeakWithinFunctionBug(const LangOptions &LOpts,
2411 bool GCEnabled) const {
2412 if (GCEnabled) {
Jordy Rosedb92bb62011-08-25 01:14:38 +00002413 if (!leakWithinFunctionGC)
Benjamin Kramerfacde172012-06-06 17:32:50 +00002414 leakWithinFunctionGC.reset(new Leak("Leak of object when using "
2415 "garbage collection"));
Jordy Rose17a38e22011-09-02 05:55:19 +00002416 return leakWithinFunctionGC.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002417 } else {
2418 if (!leakWithinFunction) {
Douglas Gregore289d812011-09-13 17:21:33 +00002419 if (LOpts.getGC() == LangOptions::HybridGC) {
Benjamin Kramerfacde172012-06-06 17:32:50 +00002420 leakWithinFunction.reset(new Leak("Leak of object when not using "
2421 "garbage collection (GC) in "
2422 "dual GC/non-GC code"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002423 } else {
Benjamin Kramerfacde172012-06-06 17:32:50 +00002424 leakWithinFunction.reset(new Leak("Leak"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002425 }
2426 }
Jordy Rose17a38e22011-09-02 05:55:19 +00002427 return leakWithinFunction.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002428 }
2429 }
2430
Jordy Rose17a38e22011-09-02 05:55:19 +00002431 CFRefBug *getLeakAtReturnBug(const LangOptions &LOpts, bool GCEnabled) const {
2432 if (GCEnabled) {
Jordy Rosedb92bb62011-08-25 01:14:38 +00002433 if (!leakAtReturnGC)
Benjamin Kramerfacde172012-06-06 17:32:50 +00002434 leakAtReturnGC.reset(new Leak("Leak of returned object when using "
2435 "garbage collection"));
Jordy Rose17a38e22011-09-02 05:55:19 +00002436 return leakAtReturnGC.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002437 } else {
2438 if (!leakAtReturn) {
Douglas Gregore289d812011-09-13 17:21:33 +00002439 if (LOpts.getGC() == LangOptions::HybridGC) {
Benjamin Kramerfacde172012-06-06 17:32:50 +00002440 leakAtReturn.reset(new Leak("Leak of returned object when not using "
2441 "garbage collection (GC) in dual "
2442 "GC/non-GC code"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002443 } else {
Benjamin Kramerfacde172012-06-06 17:32:50 +00002444 leakAtReturn.reset(new Leak("Leak of returned object"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002445 }
2446 }
Jordy Rose17a38e22011-09-02 05:55:19 +00002447 return leakAtReturn.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002448 }
2449 }
2450
Jordy Rose17a38e22011-09-02 05:55:19 +00002451 RetainSummaryManager &getSummaryManager(ASTContext &Ctx,
2452 bool GCEnabled) const {
2453 // FIXME: We don't support ARC being turned on and off during one analysis.
2454 // (nor, for that matter, do we support changing ASTContexts)
David Blaikie4e4d0842012-03-11 07:00:24 +00002455 bool ARCEnabled = (bool)Ctx.getLangOpts().ObjCAutoRefCount;
Jordy Rose17a38e22011-09-02 05:55:19 +00002456 if (GCEnabled) {
2457 if (!SummariesGC)
Jordy Roseb6cfc092011-08-25 00:10:37 +00002458 SummariesGC.reset(new RetainSummaryManager(Ctx, true, ARCEnabled));
Jordy Rose17a38e22011-09-02 05:55:19 +00002459 else
2460 assert(SummariesGC->isARCEnabled() == ARCEnabled);
Jordy Roseb6cfc092011-08-25 00:10:37 +00002461 return *SummariesGC;
2462 } else {
Jordy Rose17a38e22011-09-02 05:55:19 +00002463 if (!Summaries)
Jordy Roseb6cfc092011-08-25 00:10:37 +00002464 Summaries.reset(new RetainSummaryManager(Ctx, false, ARCEnabled));
Jordy Rose17a38e22011-09-02 05:55:19 +00002465 else
2466 assert(Summaries->isARCEnabled() == ARCEnabled);
Jordy Roseb6cfc092011-08-25 00:10:37 +00002467 return *Summaries;
2468 }
2469 }
2470
Jordy Rose17a38e22011-09-02 05:55:19 +00002471 RetainSummaryManager &getSummaryManager(CheckerContext &C) const {
2472 return getSummaryManager(C.getASTContext(), C.isObjCGCEnabled());
2473 }
2474
Ted Kremenek8bef8232012-01-26 21:29:00 +00002475 void printState(raw_ostream &Out, ProgramStateRef State,
Jordy Rosedbd658e2011-08-28 19:11:56 +00002476 const char *NL, const char *Sep) const;
2477
Anna Zaks390909c2011-10-06 00:43:15 +00002478 void checkBind(SVal loc, SVal val, const Stmt *S, CheckerContext &C) const;
Jordy Roseab027fd2011-08-20 21:16:58 +00002479 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
2480 void checkPostStmt(const CastExpr *CE, CheckerContext &C) const;
John McCallf85e1932011-06-15 23:02:42 +00002481
Jordy Rose294396b2011-08-22 23:48:23 +00002482 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
Jordy Rose537716a2011-08-27 22:51:26 +00002483 void checkPostStmt(const CXXConstructExpr *CE, CheckerContext &C) const;
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002484 void checkPostStmt(const ObjCArrayLiteral *AL, CheckerContext &C) const;
2485 void checkPostStmt(const ObjCDictionaryLiteral *DL, CheckerContext &C) const;
Jordy Rose70fdbc32012-05-12 05:10:43 +00002486 void checkPostStmt(const ObjCBoxedExpr *BE, CheckerContext &C) const;
2487
Jordy Rose294396b2011-08-22 23:48:23 +00002488 void checkPostObjCMessage(const ObjCMessage &Msg, CheckerContext &C) const;
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002489
Jordy Rose294396b2011-08-22 23:48:23 +00002490 void checkSummary(const RetainSummary &Summ, const CallOrObjCMessage &Call,
Jordy Rosee38dd952011-08-28 05:16:28 +00002491 CheckerContext &C) const;
Jordy Rose294396b2011-08-22 23:48:23 +00002492
Jordy Rose76c506f2011-08-21 21:58:18 +00002493 bool evalCall(const CallExpr *CE, CheckerContext &C) const;
2494
Ted Kremenek8bef8232012-01-26 21:29:00 +00002495 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Jordy Roseab027fd2011-08-20 21:16:58 +00002496 bool Assumption) const;
Jordy Rose67044292011-08-17 21:27:39 +00002497
Ted Kremenek8bef8232012-01-26 21:29:00 +00002498 ProgramStateRef
2499 checkRegionChanges(ProgramStateRef state,
Jordy Rose537716a2011-08-27 22:51:26 +00002500 const StoreManager::InvalidatedSymbols *invalidated,
2501 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00002502 ArrayRef<const MemRegion *> Regions,
Jordan Rose740d4902012-07-02 19:27:35 +00002503 const CallEvent *Call) const;
Jordy Roseab027fd2011-08-20 21:16:58 +00002504
Ted Kremenek8bef8232012-01-26 21:29:00 +00002505 bool wantsRegionChangeUpdate(ProgramStateRef state) const {
Jordy Rose2f9a66d2011-08-20 21:17:59 +00002506 return true;
Jordy Roseab027fd2011-08-20 21:16:58 +00002507 }
Jordy Rose294396b2011-08-22 23:48:23 +00002508
Jordy Rosef53e8c72011-08-23 19:43:16 +00002509 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
2510 void checkReturnWithRetEffect(const ReturnStmt *S, CheckerContext &C,
2511 ExplodedNode *Pred, RetEffect RE, RefVal X,
Ted Kremenek8bef8232012-01-26 21:29:00 +00002512 SymbolRef Sym, ProgramStateRef state) const;
Jordy Rosef53e8c72011-08-23 19:43:16 +00002513
Jordy Rose38f17d62011-08-23 19:01:07 +00002514 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Anna Zaksaf498a22011-10-25 19:56:48 +00002515 void checkEndPath(CheckerContext &C) const;
Jordy Rose38f17d62011-08-23 19:01:07 +00002516
Ted Kremenek8bef8232012-01-26 21:29:00 +00002517 ProgramStateRef updateSymbol(ProgramStateRef state, SymbolRef sym,
Jordy Rose17a38e22011-09-02 05:55:19 +00002518 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
2519 CheckerContext &C) const;
Jordy Rosee0a5d322011-08-23 20:27:16 +00002520
Ted Kremenek8bef8232012-01-26 21:29:00 +00002521 void processNonLeakError(ProgramStateRef St, SourceRange ErrorRange,
Jordy Rose294396b2011-08-22 23:48:23 +00002522 RefVal::Kind ErrorKind, SymbolRef Sym,
2523 CheckerContext &C) const;
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002524
2525 void processObjCLiterals(CheckerContext &C, const Expr *Ex) const;
Jordy Rose294396b2011-08-22 23:48:23 +00002526
Jordy Rose38f17d62011-08-23 19:01:07 +00002527 const ProgramPointTag *getDeadSymbolTag(SymbolRef sym) const;
2528
Ted Kremenek8bef8232012-01-26 21:29:00 +00002529 ProgramStateRef handleSymbolDeath(ProgramStateRef state,
Jordy Rose38f17d62011-08-23 19:01:07 +00002530 SymbolRef sid, RefVal V,
2531 SmallVectorImpl<SymbolRef> &Leaked) const;
2532
Ted Kremenek8bef8232012-01-26 21:29:00 +00002533 std::pair<ExplodedNode *, ProgramStateRef >
2534 handleAutoreleaseCounts(ProgramStateRef state,
Jordy Rose8d228632011-08-23 20:07:14 +00002535 GenericNodeBuilderRefCount Bd, ExplodedNode *Pred,
Anna Zaks6a93bd52011-10-25 19:57:11 +00002536 CheckerContext &Ctx, SymbolRef Sym, RefVal V) const;
Jordy Rose8d228632011-08-23 20:07:14 +00002537
Ted Kremenek8bef8232012-01-26 21:29:00 +00002538 ExplodedNode *processLeaks(ProgramStateRef state,
Jordy Rose38f17d62011-08-23 19:01:07 +00002539 SmallVectorImpl<SymbolRef> &Leaked,
2540 GenericNodeBuilderRefCount &Builder,
Anna Zaks6a93bd52011-10-25 19:57:11 +00002541 CheckerContext &Ctx,
Jordy Rose38f17d62011-08-23 19:01:07 +00002542 ExplodedNode *Pred = 0) const;
Ted Kremenekd593eb92009-11-25 22:17:44 +00002543};
2544} // end anonymous namespace
2545
Jordy Rose67044292011-08-17 21:27:39 +00002546namespace {
2547class StopTrackingCallback : public SymbolVisitor {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002548 ProgramStateRef state;
Jordy Rose67044292011-08-17 21:27:39 +00002549public:
Ted Kremenek8bef8232012-01-26 21:29:00 +00002550 StopTrackingCallback(ProgramStateRef st) : state(st) {}
2551 ProgramStateRef getState() const { return state; }
Jordy Rose67044292011-08-17 21:27:39 +00002552
2553 bool VisitSymbol(SymbolRef sym) {
2554 state = state->remove<RefBindings>(sym);
2555 return true;
2556 }
2557};
2558} // end anonymous namespace
2559
Jordy Rose910c4052011-09-02 06:44:22 +00002560//===----------------------------------------------------------------------===//
2561// Handle statements that may have an effect on refcounts.
2562//===----------------------------------------------------------------------===//
Jordy Rose67044292011-08-17 21:27:39 +00002563
Jordy Rose910c4052011-09-02 06:44:22 +00002564void RetainCountChecker::checkPostStmt(const BlockExpr *BE,
2565 CheckerContext &C) const {
Jordy Rose67044292011-08-17 21:27:39 +00002566
Jordy Rose910c4052011-09-02 06:44:22 +00002567 // Scan the BlockDecRefExprs for any object the retain count checker
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002568 // may be tracking.
John McCall469a1eb2011-02-02 13:00:07 +00002569 if (!BE->getBlockDecl()->hasCaptures())
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002570 return;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002571
Ted Kremenek8bef8232012-01-26 21:29:00 +00002572 ProgramStateRef state = C.getState();
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002573 const BlockDataRegion *R =
Ted Kremenek5eca4822012-01-06 22:09:28 +00002574 cast<BlockDataRegion>(state->getSVal(BE,
2575 C.getLocationContext()).getAsRegion());
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002576
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002577 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
2578 E = R->referenced_vars_end();
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002579
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002580 if (I == E)
2581 return;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002582
Ted Kremenek67d12872009-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 Lattner5f9e2722011-07-23 10:55:15 +00002586 SmallVector<const MemRegion*, 10> Regions;
Anna Zaks39ac1872011-10-26 21:06:44 +00002587 const LocationContext *LC = C.getLocationContext();
Ted Kremenekc8413fd2010-12-02 07:49:45 +00002588 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002589
Ted Kremenek67d12872009-12-07 22:05:27 +00002590 for ( ; I != E; ++I) {
2591 const VarRegion *VR = *I;
2592 if (VR->getSuperRegion() == R) {
2593 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2594 }
2595 Regions.push_back(VR);
2596 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002597
Ted Kremenek67d12872009-12-07 22:05:27 +00002598 state =
2599 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
2600 Regions.data() + Regions.size()).getState();
Anna Zaks0bd6b112011-10-26 21:06:34 +00002601 C.addTransition(state);
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002602}
2603
Jordy Rose910c4052011-09-02 06:44:22 +00002604void RetainCountChecker::checkPostStmt(const CastExpr *CE,
2605 CheckerContext &C) const {
John McCallf85e1932011-06-15 23:02:42 +00002606 const ObjCBridgedCastExpr *BE = dyn_cast<ObjCBridgedCastExpr>(CE);
2607 if (!BE)
2608 return;
2609
John McCall71c482c2011-06-17 06:50:50 +00002610 ArgEffect AE = IncRef;
John McCallf85e1932011-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:
2620 AE = DecRefBridgedTransfered;
2621 break;
2622 }
2623
Ted Kremenek8bef8232012-01-26 21:29:00 +00002624 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00002625 SymbolRef Sym = state->getSVal(CE, C.getLocationContext()).getAsLocSymbol();
John McCallf85e1932011-06-15 23:02:42 +00002626 if (!Sym)
2627 return;
2628 const RefVal* T = state->get<RefBindings>(Sym);
2629 if (!T)
2630 return;
2631
John McCallf85e1932011-06-15 23:02:42 +00002632 RefVal::Kind hasErr = (RefVal::Kind) 0;
Jordy Rose17a38e22011-09-02 05:55:19 +00002633 state = updateSymbol(state, Sym, *T, AE, hasErr, C);
John McCallf85e1932011-06-15 23:02:42 +00002634
2635 if (hasErr) {
Jordy Rosee0a5d322011-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 McCallf85e1932011-06-15 23:02:42 +00002638 return;
2639 }
2640
Anna Zaks0bd6b112011-10-26 21:06:34 +00002641 C.addTransition(state);
John McCallf85e1932011-06-15 23:02:42 +00002642}
2643
Jordy Rose910c4052011-09-02 06:44:22 +00002644void RetainCountChecker::checkPostStmt(const CallExpr *CE,
2645 CheckerContext &C) const {
Ted Kremenek514f2c92012-03-23 06:26:56 +00002646 if (C.wasInlined)
2647 return;
2648
Jordy Rose294396b2011-08-22 23:48:23 +00002649 // Get the callee.
Ted Kremenek8bef8232012-01-26 21:29:00 +00002650 ProgramStateRef state = C.getState();
Jordy Rose294396b2011-08-22 23:48:23 +00002651 const Expr *Callee = CE->getCallee();
Ted Kremenek5eca4822012-01-06 22:09:28 +00002652 SVal L = state->getSVal(Callee, C.getLocationContext());
Jordy Rose294396b2011-08-22 23:48:23 +00002653
Jordy Rose17a38e22011-09-02 05:55:19 +00002654 RetainSummaryManager &Summaries = getSummaryManager(C);
Ted Kremenek93edbc52011-10-05 23:54:29 +00002655 const RetainSummary *Summ = 0;
Jordy Rose294396b2011-08-22 23:48:23 +00002656
2657 // FIXME: Better support for blocks. For now we stop tracking anything
2658 // that is passed to blocks.
2659 // FIXME: Need to handle variables that are "captured" by the block.
2660 if (dyn_cast_or_null<BlockDataRegion>(L.getAsRegion())) {
2661 Summ = Summaries.getPersistentStopSummary();
2662 } else if (const FunctionDecl *FD = L.getAsFunctionDecl()) {
Anna Zaks58822c42012-05-04 22:18:39 +00002663 CallOrObjCMessage CME(CE, state, C.getLocationContext());
2664 Summ = Summaries.getSummary(FD, &CME);
Jordy Rose294396b2011-08-22 23:48:23 +00002665 } else if (const CXXMemberCallExpr *me = dyn_cast<CXXMemberCallExpr>(CE)) {
Anna Zaks58822c42012-05-04 22:18:39 +00002666 if (const CXXMethodDecl *MD = me->getMethodDecl()) {
2667 CallOrObjCMessage CME(CE, state, C.getLocationContext());
2668 Summ = Summaries.getSummary(MD, &CME);
2669 }
Jordy Rose294396b2011-08-22 23:48:23 +00002670 }
2671
Jordy Rose294396b2011-08-22 23:48:23 +00002672 if (!Summ)
Ted Kremenek93edbc52011-10-05 23:54:29 +00002673 Summ = Summaries.getDefaultSummary();
Jordy Rose294396b2011-08-22 23:48:23 +00002674
Ted Kremenek5eca4822012-01-06 22:09:28 +00002675 checkSummary(*Summ, CallOrObjCMessage(CE, state, C.getLocationContext()), C);
Jordy Rose294396b2011-08-22 23:48:23 +00002676}
2677
Jordy Rose910c4052011-09-02 06:44:22 +00002678void RetainCountChecker::checkPostStmt(const CXXConstructExpr *CE,
2679 CheckerContext &C) const {
Jordy Rose537716a2011-08-27 22:51:26 +00002680 const CXXConstructorDecl *Ctor = CE->getConstructor();
2681 if (!Ctor)
2682 return;
2683
Jordy Rose17a38e22011-09-02 05:55:19 +00002684 RetainSummaryManager &Summaries = getSummaryManager(C);
Anna Zaks58822c42012-05-04 22:18:39 +00002685 ProgramStateRef state = C.getState();
2686 CallOrObjCMessage CME(CE, state, C.getLocationContext());
2687 const RetainSummary *Summ = Summaries.getSummary(Ctor, &CME);
Jordy Rose537716a2011-08-27 22:51:26 +00002688
2689 // If we didn't get a summary, this constructor doesn't affect retain counts.
2690 if (!Summ)
2691 return;
2692
Ted Kremenek5eca4822012-01-06 22:09:28 +00002693 checkSummary(*Summ, CallOrObjCMessage(CE, state, C.getLocationContext()), C);
Jordy Rose537716a2011-08-27 22:51:26 +00002694}
2695
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002696void RetainCountChecker::processObjCLiterals(CheckerContext &C,
2697 const Expr *Ex) const {
2698 ProgramStateRef state = C.getState();
2699 const ExplodedNode *pred = C.getPredecessor();
2700 for (Stmt::const_child_iterator it = Ex->child_begin(), et = Ex->child_end() ;
2701 it != et ; ++it) {
2702 const Stmt *child = *it;
2703 SVal V = state->getSVal(child, pred->getLocationContext());
2704 if (SymbolRef sym = V.getAsSymbol())
2705 if (const RefVal* T = state->get<RefBindings>(sym)) {
2706 RefVal::Kind hasErr = (RefVal::Kind) 0;
2707 state = updateSymbol(state, sym, *T, MayEscape, hasErr, C);
2708 if (hasErr) {
2709 processNonLeakError(state, child->getSourceRange(), hasErr, sym, C);
2710 return;
2711 }
2712 }
2713 }
2714
2715 // Return the object as autoreleased.
2716 // RetEffect RE = RetEffect::MakeNotOwned(RetEffect::ObjC);
2717 if (SymbolRef sym =
2718 state->getSVal(Ex, pred->getLocationContext()).getAsSymbol()) {
2719 QualType ResultTy = Ex->getType();
2720 state = state->set<RefBindings>(sym, RefVal::makeNotOwned(RetEffect::ObjC,
2721 ResultTy));
2722 }
2723
2724 C.addTransition(state);
2725}
2726
2727void RetainCountChecker::checkPostStmt(const ObjCArrayLiteral *AL,
2728 CheckerContext &C) const {
2729 // Apply the 'MayEscape' to all values.
2730 processObjCLiterals(C, AL);
2731}
2732
2733void RetainCountChecker::checkPostStmt(const ObjCDictionaryLiteral *DL,
2734 CheckerContext &C) const {
2735 // Apply the 'MayEscape' to all keys and values.
2736 processObjCLiterals(C, DL);
2737}
2738
Jordy Rose70fdbc32012-05-12 05:10:43 +00002739void RetainCountChecker::checkPostStmt(const ObjCBoxedExpr *Ex,
2740 CheckerContext &C) const {
2741 const ExplodedNode *Pred = C.getPredecessor();
2742 const LocationContext *LCtx = Pred->getLocationContext();
2743 ProgramStateRef State = Pred->getState();
2744
2745 if (SymbolRef Sym = State->getSVal(Ex, LCtx).getAsSymbol()) {
2746 QualType ResultTy = Ex->getType();
2747 State = State->set<RefBindings>(Sym, RefVal::makeNotOwned(RetEffect::ObjC,
2748 ResultTy));
2749 }
2750
2751 C.addTransition(State);
2752}
2753
Jordy Rose910c4052011-09-02 06:44:22 +00002754void RetainCountChecker::checkPostObjCMessage(const ObjCMessage &Msg,
2755 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002756 ProgramStateRef state = C.getState();
Jordy Rose294396b2011-08-22 23:48:23 +00002757
Jordy Rose17a38e22011-09-02 05:55:19 +00002758 RetainSummaryManager &Summaries = getSummaryManager(C);
Jordy Roseb6cfc092011-08-25 00:10:37 +00002759
Ted Kremenek93edbc52011-10-05 23:54:29 +00002760 const RetainSummary *Summ;
Jordy Rose294396b2011-08-22 23:48:23 +00002761 if (Msg.isInstanceMessage()) {
Anna Zaksa2a86032011-11-01 22:41:01 +00002762 const LocationContext *LC = C.getLocationContext();
Jordy Rose294396b2011-08-22 23:48:23 +00002763 Summ = Summaries.getInstanceMethodSummary(Msg, state, LC);
2764 } else {
2765 Summ = Summaries.getClassMethodSummary(Msg);
2766 }
2767
2768 // If we didn't get a summary, this message doesn't affect retain counts.
2769 if (!Summ)
2770 return;
2771
Ted Kremenek5eca4822012-01-06 22:09:28 +00002772 checkSummary(*Summ, CallOrObjCMessage(Msg, state, C.getLocationContext()), C);
Jordy Rose294396b2011-08-22 23:48:23 +00002773}
2774
Jordy Rose910c4052011-09-02 06:44:22 +00002775/// GetReturnType - Used to get the return type of a message expression or
2776/// function call with the intention of affixing that type to a tracked symbol.
2777/// While the the return type can be queried directly from RetEx, when
2778/// invoking class methods we augment to the return type to be that of
2779/// a pointer to the class (as opposed it just being id).
2780// FIXME: We may be able to do this with related result types instead.
2781// This function is probably overestimating.
2782static QualType GetReturnType(const Expr *RetE, ASTContext &Ctx) {
2783 QualType RetTy = RetE->getType();
2784 // If RetE is not a message expression just return its type.
2785 // If RetE is a message expression, return its types if it is something
2786 /// more specific than id.
2787 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RetE))
2788 if (const ObjCObjectPointerType *PT = RetTy->getAs<ObjCObjectPointerType>())
2789 if (PT->isObjCQualifiedIdType() || PT->isObjCIdType() ||
2790 PT->isObjCClassType()) {
2791 // At this point we know the return type of the message expression is
2792 // id, id<...>, or Class. If we have an ObjCInterfaceDecl, we know this
2793 // is a call to a class method whose type we can resolve. In such
2794 // cases, promote the return type to XXX* (where XXX is the class).
2795 const ObjCInterfaceDecl *D = ME->getReceiverInterface();
2796 return !D ? RetTy :
2797 Ctx.getObjCObjectPointerType(Ctx.getObjCInterfaceType(D));
2798 }
2799
2800 return RetTy;
2801}
2802
2803void RetainCountChecker::checkSummary(const RetainSummary &Summ,
2804 const CallOrObjCMessage &CallOrMsg,
2805 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002806 ProgramStateRef state = C.getState();
Jordy Rose294396b2011-08-22 23:48:23 +00002807
2808 // Evaluate the effect of the arguments.
2809 RefVal::Kind hasErr = (RefVal::Kind) 0;
2810 SourceRange ErrorRange;
2811 SymbolRef ErrorSym = 0;
2812
2813 for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
Jordy Rose537716a2011-08-27 22:51:26 +00002814 SVal V = CallOrMsg.getArgSVal(idx);
Jordy Rose294396b2011-08-22 23:48:23 +00002815
2816 if (SymbolRef Sym = V.getAsLocSymbol()) {
2817 if (RefBindings::data_type *T = state->get<RefBindings>(Sym)) {
Jordy Rose17a38e22011-09-02 05:55:19 +00002818 state = updateSymbol(state, Sym, *T, Summ.getArg(idx), hasErr, C);
Jordy Rose294396b2011-08-22 23:48:23 +00002819 if (hasErr) {
2820 ErrorRange = CallOrMsg.getArgSourceRange(idx);
2821 ErrorSym = Sym;
2822 break;
2823 }
2824 }
2825 }
2826 }
2827
2828 // Evaluate the effect on the message receiver.
2829 bool ReceiverIsTracked = false;
Jordy Rosee38dd952011-08-28 05:16:28 +00002830 if (!hasErr && CallOrMsg.isObjCMessage()) {
Anna Zaks39ac1872011-10-26 21:06:44 +00002831 const LocationContext *LC = C.getLocationContext();
Jordy Rosee38dd952011-08-28 05:16:28 +00002832 SVal Receiver = CallOrMsg.getInstanceMessageReceiver(LC);
2833 if (SymbolRef Sym = Receiver.getAsLocSymbol()) {
Jordy Rose294396b2011-08-22 23:48:23 +00002834 if (const RefVal *T = state->get<RefBindings>(Sym)) {
2835 ReceiverIsTracked = true;
Jordy Rose17a38e22011-09-02 05:55:19 +00002836 state = updateSymbol(state, Sym, *T, Summ.getReceiverEffect(),
2837 hasErr, C);
Jordy Rose294396b2011-08-22 23:48:23 +00002838 if (hasErr) {
Jordy Rosee38dd952011-08-28 05:16:28 +00002839 ErrorRange = CallOrMsg.getReceiverSourceRange();
Jordy Rose294396b2011-08-22 23:48:23 +00002840 ErrorSym = Sym;
2841 }
2842 }
2843 }
2844 }
2845
2846 // Process any errors.
2847 if (hasErr) {
2848 processNonLeakError(state, ErrorRange, hasErr, ErrorSym, C);
2849 return;
2850 }
2851
2852 // Consult the summary for the return value.
2853 RetEffect RE = Summ.getRetEffect();
2854
2855 if (RE.getKind() == RetEffect::OwnedWhenTrackedReceiver) {
Jordy Roseb6cfc092011-08-25 00:10:37 +00002856 if (ReceiverIsTracked)
Jordy Rose17a38e22011-09-02 05:55:19 +00002857 RE = getSummaryManager(C).getObjAllocRetEffect();
Jordy Roseb6cfc092011-08-25 00:10:37 +00002858 else
Jordy Rose294396b2011-08-22 23:48:23 +00002859 RE = RetEffect::MakeNoRet();
2860 }
2861
2862 switch (RE.getKind()) {
2863 default:
David Blaikie7530c032012-01-17 06:56:22 +00002864 llvm_unreachable("Unhandled RetEffect.");
Jordy Rose294396b2011-08-22 23:48:23 +00002865
2866 case RetEffect::NoRet:
2867 // No work necessary.
2868 break;
2869
2870 case RetEffect::OwnedAllocatedSymbol:
2871 case RetEffect::OwnedSymbol: {
Ted Kremenek5eca4822012-01-06 22:09:28 +00002872 SymbolRef Sym = state->getSVal(CallOrMsg.getOriginExpr(),
2873 C.getLocationContext()).getAsSymbol();
Jordy Rose294396b2011-08-22 23:48:23 +00002874 if (!Sym)
2875 break;
2876
2877 // Use the result type from callOrMsg as it automatically adjusts
2878 // for methods/functions that return references.
2879 QualType ResultTy = CallOrMsg.getResultType(C.getASTContext());
2880 state = state->set<RefBindings>(Sym, RefVal::makeOwned(RE.getObjKind(),
2881 ResultTy));
2882
2883 // FIXME: Add a flag to the checker where allocations are assumed to
2884 // *not* fail. (The code below is out-of-date, though.)
2885#if 0
2886 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) {
2887 bool isFeasible;
2888 state = state.assume(loc::SymbolVal(Sym), true, isFeasible);
2889 assert(isFeasible && "Cannot assume fresh symbol is non-null.");
2890 }
2891#endif
2892
2893 break;
2894 }
2895
2896 case RetEffect::GCNotOwnedSymbol:
2897 case RetEffect::ARCNotOwnedSymbol:
2898 case RetEffect::NotOwnedSymbol: {
2899 const Expr *Ex = CallOrMsg.getOriginExpr();
Ted Kremenek5eca4822012-01-06 22:09:28 +00002900 SymbolRef Sym = state->getSVal(Ex, C.getLocationContext()).getAsSymbol();
Jordy Rose294396b2011-08-22 23:48:23 +00002901 if (!Sym)
2902 break;
2903
2904 // Use GetReturnType in order to give [NSFoo alloc] the type NSFoo *.
2905 QualType ResultTy = GetReturnType(Ex, C.getASTContext());
2906 state = state->set<RefBindings>(Sym, RefVal::makeNotOwned(RE.getObjKind(),
2907 ResultTy));
2908 break;
2909 }
2910 }
2911
2912 // This check is actually necessary; otherwise the statement builder thinks
2913 // we've hit a previously-found path.
2914 // Normally addTransition takes care of this, but we want the node pointer.
2915 ExplodedNode *NewNode;
2916 if (state == C.getState()) {
2917 NewNode = C.getPredecessor();
2918 } else {
Anna Zaks0bd6b112011-10-26 21:06:34 +00002919 NewNode = C.addTransition(state);
Jordy Rose294396b2011-08-22 23:48:23 +00002920 }
2921
Jordy Rose9c083b72011-08-24 18:56:32 +00002922 // Annotate the node with summary we used.
2923 if (NewNode) {
2924 // FIXME: This is ugly. See checkEndAnalysis for why it's necessary.
2925 if (ShouldResetSummaryLog) {
2926 SummaryLog.clear();
2927 ShouldResetSummaryLog = false;
2928 }
Jordy Roseec9ef852011-08-23 20:55:48 +00002929 SummaryLog[NewNode] = &Summ;
Jordy Rose9c083b72011-08-24 18:56:32 +00002930 }
Jordy Rose294396b2011-08-22 23:48:23 +00002931}
2932
Jordy Rosee0a5d322011-08-23 20:27:16 +00002933
Ted Kremenek8bef8232012-01-26 21:29:00 +00002934ProgramStateRef
2935RetainCountChecker::updateSymbol(ProgramStateRef state, SymbolRef sym,
Jordy Rose910c4052011-09-02 06:44:22 +00002936 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
2937 CheckerContext &C) const {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002938 // In GC mode [... release] and [... retain] do nothing.
Jordy Rose910c4052011-09-02 06:44:22 +00002939 // In ARC mode they shouldn't exist at all, but we just ignore them.
Jordy Rose17a38e22011-09-02 05:55:19 +00002940 bool IgnoreRetainMsg = C.isObjCGCEnabled();
2941 if (!IgnoreRetainMsg)
David Blaikie4e4d0842012-03-11 07:00:24 +00002942 IgnoreRetainMsg = (bool)C.getASTContext().getLangOpts().ObjCAutoRefCount;
Jordy Rose17a38e22011-09-02 05:55:19 +00002943
Jordy Rosee0a5d322011-08-23 20:27:16 +00002944 switch (E) {
2945 default: break;
Jordy Rose17a38e22011-09-02 05:55:19 +00002946 case IncRefMsg: E = IgnoreRetainMsg ? DoNothing : IncRef; break;
2947 case DecRefMsg: E = IgnoreRetainMsg ? DoNothing : DecRef; break;
2948 case MakeCollectable: E = C.isObjCGCEnabled() ? DecRef : DoNothing; break;
2949 case NewAutoreleasePool: E = C.isObjCGCEnabled() ? DoNothing :
2950 NewAutoreleasePool; break;
Jordy Rosee0a5d322011-08-23 20:27:16 +00002951 }
2952
2953 // Handle all use-after-releases.
Jordy Rose17a38e22011-09-02 05:55:19 +00002954 if (!C.isObjCGCEnabled() && V.getKind() == RefVal::Released) {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002955 V = V ^ RefVal::ErrorUseAfterRelease;
2956 hasErr = V.getKind();
2957 return state->set<RefBindings>(sym, V);
2958 }
2959
2960 switch (E) {
2961 case DecRefMsg:
2962 case IncRefMsg:
2963 case MakeCollectable:
2964 llvm_unreachable("DecRefMsg/IncRefMsg/MakeCollectable already converted");
Jordy Rosee0a5d322011-08-23 20:27:16 +00002965
2966 case Dealloc:
2967 // Any use of -dealloc in GC is *bad*.
Jordy Rose17a38e22011-09-02 05:55:19 +00002968 if (C.isObjCGCEnabled()) {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002969 V = V ^ RefVal::ErrorDeallocGC;
2970 hasErr = V.getKind();
2971 break;
2972 }
2973
2974 switch (V.getKind()) {
2975 default:
2976 llvm_unreachable("Invalid RefVal state for an explicit dealloc.");
Jordy Rosee0a5d322011-08-23 20:27:16 +00002977 case RefVal::Owned:
2978 // The object immediately transitions to the released state.
2979 V = V ^ RefVal::Released;
2980 V.clearCounts();
2981 return state->set<RefBindings>(sym, V);
2982 case RefVal::NotOwned:
2983 V = V ^ RefVal::ErrorDeallocNotOwned;
2984 hasErr = V.getKind();
2985 break;
2986 }
2987 break;
2988
2989 case NewAutoreleasePool:
Jordy Rose17a38e22011-09-02 05:55:19 +00002990 assert(!C.isObjCGCEnabled());
Jordy Rosee0a5d322011-08-23 20:27:16 +00002991 return state->add<AutoreleaseStack>(sym);
2992
2993 case MayEscape:
2994 if (V.getKind() == RefVal::Owned) {
2995 V = V ^ RefVal::NotOwned;
2996 break;
2997 }
2998
2999 // Fall-through.
3000
Jordy Rosee0a5d322011-08-23 20:27:16 +00003001 case DoNothing:
3002 return state;
3003
3004 case Autorelease:
Jordy Rose17a38e22011-09-02 05:55:19 +00003005 if (C.isObjCGCEnabled())
Jordy Rosee0a5d322011-08-23 20:27:16 +00003006 return state;
3007
3008 // Update the autorelease counts.
3009 state = SendAutorelease(state, ARCountFactory, sym);
3010 V = V.autorelease();
3011 break;
3012
3013 case StopTracking:
3014 return state->remove<RefBindings>(sym);
3015
3016 case IncRef:
3017 switch (V.getKind()) {
3018 default:
3019 llvm_unreachable("Invalid RefVal state for a retain.");
Jordy Rosee0a5d322011-08-23 20:27:16 +00003020 case RefVal::Owned:
3021 case RefVal::NotOwned:
3022 V = V + 1;
3023 break;
3024 case RefVal::Released:
3025 // Non-GC cases are handled above.
Jordy Rose17a38e22011-09-02 05:55:19 +00003026 assert(C.isObjCGCEnabled());
Jordy Rosee0a5d322011-08-23 20:27:16 +00003027 V = (V ^ RefVal::Owned) + 1;
3028 break;
3029 }
3030 break;
3031
Jordy Rosee0a5d322011-08-23 20:27:16 +00003032 case DecRef:
3033 case DecRefBridgedTransfered:
3034 switch (V.getKind()) {
3035 default:
3036 // case 'RefVal::Released' handled above.
3037 llvm_unreachable("Invalid RefVal state for a release.");
Jordy Rosee0a5d322011-08-23 20:27:16 +00003038
3039 case RefVal::Owned:
3040 assert(V.getCount() > 0);
3041 if (V.getCount() == 1)
3042 V = V ^ (E == DecRefBridgedTransfered ?
3043 RefVal::NotOwned : RefVal::Released);
3044 V = V - 1;
3045 break;
3046
3047 case RefVal::NotOwned:
3048 if (V.getCount() > 0)
3049 V = V - 1;
3050 else {
3051 V = V ^ RefVal::ErrorReleaseNotOwned;
3052 hasErr = V.getKind();
3053 }
3054 break;
3055
3056 case RefVal::Released:
3057 // Non-GC cases are handled above.
Jordy Rose17a38e22011-09-02 05:55:19 +00003058 assert(C.isObjCGCEnabled());
Jordy Rosee0a5d322011-08-23 20:27:16 +00003059 V = V ^ RefVal::ErrorUseAfterRelease;
3060 hasErr = V.getKind();
3061 break;
3062 }
3063 break;
3064 }
3065 return state->set<RefBindings>(sym, V);
3066}
3067
Ted Kremenek8bef8232012-01-26 21:29:00 +00003068void RetainCountChecker::processNonLeakError(ProgramStateRef St,
Jordy Rose910c4052011-09-02 06:44:22 +00003069 SourceRange ErrorRange,
3070 RefVal::Kind ErrorKind,
3071 SymbolRef Sym,
3072 CheckerContext &C) const {
Jordy Rose294396b2011-08-22 23:48:23 +00003073 ExplodedNode *N = C.generateSink(St);
3074 if (!N)
3075 return;
3076
Jordy Rose294396b2011-08-22 23:48:23 +00003077 CFRefBug *BT;
3078 switch (ErrorKind) {
3079 default:
3080 llvm_unreachable("Unhandled error.");
Jordy Rose294396b2011-08-22 23:48:23 +00003081 case RefVal::ErrorUseAfterRelease:
Jordy Rosed6334e12011-08-25 00:34:03 +00003082 if (!useAfterRelease)
3083 useAfterRelease.reset(new UseAfterRelease());
3084 BT = &*useAfterRelease;
Jordy Rose294396b2011-08-22 23:48:23 +00003085 break;
3086 case RefVal::ErrorReleaseNotOwned:
Jordy Rosed6334e12011-08-25 00:34:03 +00003087 if (!releaseNotOwned)
3088 releaseNotOwned.reset(new BadRelease());
3089 BT = &*releaseNotOwned;
Jordy Rose294396b2011-08-22 23:48:23 +00003090 break;
3091 case RefVal::ErrorDeallocGC:
Jordy Rosed6334e12011-08-25 00:34:03 +00003092 if (!deallocGC)
3093 deallocGC.reset(new DeallocGC());
3094 BT = &*deallocGC;
Jordy Rose294396b2011-08-22 23:48:23 +00003095 break;
3096 case RefVal::ErrorDeallocNotOwned:
Jordy Rosed6334e12011-08-25 00:34:03 +00003097 if (!deallocNotOwned)
3098 deallocNotOwned.reset(new DeallocNotOwned());
3099 BT = &*deallocNotOwned;
Jordy Rose294396b2011-08-22 23:48:23 +00003100 break;
3101 }
3102
Jordy Rosed6334e12011-08-25 00:34:03 +00003103 assert(BT);
David Blaikie4e4d0842012-03-11 07:00:24 +00003104 CFRefReport *report = new CFRefReport(*BT, C.getASTContext().getLangOpts(),
Jordy Rose17a38e22011-09-02 05:55:19 +00003105 C.isObjCGCEnabled(), SummaryLog,
3106 N, Sym);
Jordy Rose294396b2011-08-22 23:48:23 +00003107 report->addRange(ErrorRange);
3108 C.EmitReport(report);
3109}
3110
Jordy Rose910c4052011-09-02 06:44:22 +00003111//===----------------------------------------------------------------------===//
3112// Handle the return values of retain-count-related functions.
3113//===----------------------------------------------------------------------===//
3114
3115bool RetainCountChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
Jordy Rose76c506f2011-08-21 21:58:18 +00003116 // Get the callee. We're only interested in simple C functions.
Ted Kremenek8bef8232012-01-26 21:29:00 +00003117 ProgramStateRef state = C.getState();
Anna Zaksb805c8f2011-12-01 05:57:37 +00003118 const FunctionDecl *FD = C.getCalleeDecl(CE);
Jordy Rose76c506f2011-08-21 21:58:18 +00003119 if (!FD)
3120 return false;
3121
3122 IdentifierInfo *II = FD->getIdentifier();
3123 if (!II)
3124 return false;
3125
3126 // For now, we're only handling the functions that return aliases of their
3127 // arguments: CFRetain and CFMakeCollectable (and their families).
3128 // Eventually we should add other functions we can model entirely,
3129 // such as CFRelease, which don't invalidate their arguments or globals.
3130 if (CE->getNumArgs() != 1)
3131 return false;
3132
3133 // Get the name of the function.
3134 StringRef FName = II->getName();
3135 FName = FName.substr(FName.find_first_not_of('_'));
3136
3137 // See if it's one of the specific functions we know how to eval.
3138 bool canEval = false;
3139
Anna Zaksb805c8f2011-12-01 05:57:37 +00003140 QualType ResultTy = CE->getCallReturnType();
Jordy Rose76c506f2011-08-21 21:58:18 +00003141 if (ResultTy->isObjCIdType()) {
3142 // Handle: id NSMakeCollectable(CFTypeRef)
3143 canEval = II->isStr("NSMakeCollectable");
3144 } else if (ResultTy->isPointerType()) {
3145 // Handle: (CF|CG)Retain
3146 // 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)) {
3150 canEval = isRetain(FD, FName) || isMakeCollectable(FD, FName);
3151 }
3152 }
3153
3154 if (!canEval)
3155 return false;
3156
3157 // Bind the return value.
Ted Kremenek5eca4822012-01-06 22:09:28 +00003158 const LocationContext *LCtx = C.getLocationContext();
3159 SVal RetVal = state->getSVal(CE->getArg(0), LCtx);
Jordy Rose76c506f2011-08-21 21:58:18 +00003160 if (RetVal.isUnknown()) {
3161 // If the receiver is unknown, conjure a return value.
3162 SValBuilder &SVB = C.getSValBuilder();
Anna Zaks5d0ea6d2011-10-04 20:43:05 +00003163 unsigned Count = C.getCurrentBlockCount();
Ted Kremenek3133f792012-02-17 23:13:45 +00003164 SVal RetVal = SVB.getConjuredSymbolVal(0, CE, LCtx, ResultTy, Count);
Jordy Rose76c506f2011-08-21 21:58:18 +00003165 }
Ted Kremenek5eca4822012-01-06 22:09:28 +00003166 state = state->BindExpr(CE, LCtx, RetVal, false);
Jordy Rose76c506f2011-08-21 21:58:18 +00003167
Jordy Rose294396b2011-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();
3173 RefBindings::data_type *Binding = 0;
3174 if (Sym)
3175 Binding = state->get<RefBindings>(Sym);
Jordy Rose76c506f2011-08-21 21:58:18 +00003176
Jordy Rose294396b2011-08-22 23:48:23 +00003177 // Invalidate the argument region.
Anna Zaks5d0ea6d2011-10-04 20:43:05 +00003178 unsigned Count = C.getCurrentBlockCount();
Ted Kremenek3133f792012-02-17 23:13:45 +00003179 state = state->invalidateRegions(ArgRegion, CE, Count, LCtx);
Jordy Rose76c506f2011-08-21 21:58:18 +00003180
Jordy Rose294396b2011-08-22 23:48:23 +00003181 // Restore the refcount status of the argument.
3182 if (Binding)
3183 state = state->set<RefBindings>(Sym, *Binding);
3184 }
3185
Anna Zaks0bd6b112011-10-26 21:06:34 +00003186 C.addTransition(state);
Jordy Rose76c506f2011-08-21 21:58:18 +00003187 return true;
3188}
3189
Jordy Rose910c4052011-09-02 06:44:22 +00003190//===----------------------------------------------------------------------===//
3191// Handle return statements.
3192//===----------------------------------------------------------------------===//
Jordy Rosef53e8c72011-08-23 19:43:16 +00003193
Ted Kremeneke5715782012-02-25 02:09:09 +00003194// Return true if the current LocationContext has no caller context.
3195static bool inTopFrame(CheckerContext &C) {
3196 const LocationContext *LC = C.getLocationContext();
3197 return LC->getParent() == 0;
3198}
3199
Jordy Rose910c4052011-09-02 06:44:22 +00003200void RetainCountChecker::checkPreStmt(const ReturnStmt *S,
3201 CheckerContext &C) const {
Ted Kremeneke5715782012-02-25 02:09:09 +00003202
3203 // Only adjust the reference count if this is the top-level call frame,
3204 // and not the result of inlining. In the future, we should do
3205 // better checking even for inlined calls, and see if they match
3206 // with their expected semantics (e.g., the method should return a retained
3207 // object, etc.).
3208 if (!inTopFrame(C))
3209 return;
3210
Jordy Rosef53e8c72011-08-23 19:43:16 +00003211 const Expr *RetE = S->getRetValue();
3212 if (!RetE)
3213 return;
3214
Ted Kremenek8bef8232012-01-26 21:29:00 +00003215 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00003216 SymbolRef Sym =
3217 state->getSValAsScalarOrLoc(RetE, C.getLocationContext()).getAsLocSymbol();
Jordy Rosef53e8c72011-08-23 19:43:16 +00003218 if (!Sym)
3219 return;
3220
3221 // Get the reference count binding (if any).
3222 const RefVal *T = state->get<RefBindings>(Sym);
3223 if (!T)
3224 return;
3225
3226 // Change the reference count.
3227 RefVal X = *T;
3228
3229 switch (X.getKind()) {
3230 case RefVal::Owned: {
3231 unsigned cnt = X.getCount();
3232 assert(cnt > 0);
3233 X.setCount(cnt - 1);
3234 X = X ^ RefVal::ReturnedOwned;
3235 break;
3236 }
3237
3238 case RefVal::NotOwned: {
3239 unsigned cnt = X.getCount();
3240 if (cnt) {
3241 X.setCount(cnt - 1);
3242 X = X ^ RefVal::ReturnedOwned;
3243 }
3244 else {
3245 X = X ^ RefVal::ReturnedNotOwned;
3246 }
3247 break;
3248 }
3249
3250 default:
3251 return;
3252 }
3253
3254 // Update the binding.
3255 state = state->set<RefBindings>(Sym, X);
Anna Zaks0bd6b112011-10-26 21:06:34 +00003256 ExplodedNode *Pred = C.addTransition(state);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003257
3258 // At this point we have updated the state properly.
3259 // Everything after this is merely checking to see if the return value has
3260 // been over- or under-retained.
3261
3262 // Did we cache out?
3263 if (!Pred)
3264 return;
3265
Jordy Rosef53e8c72011-08-23 19:43:16 +00003266 // Update the autorelease counts.
3267 static SimpleProgramPointTag
Jordy Rose910c4052011-09-02 06:44:22 +00003268 AutoreleaseTag("RetainCountChecker : Autorelease");
Anna Zaks4eff8232011-10-05 23:44:11 +00003269 GenericNodeBuilderRefCount Bd(C, &AutoreleaseTag);
Anna Zaks6a93bd52011-10-25 19:57:11 +00003270 llvm::tie(Pred, state) = handleAutoreleaseCounts(state, Bd, Pred, C, Sym, X);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003271
3272 // Did we cache out?
Jordy Rose8d228632011-08-23 20:07:14 +00003273 if (!Pred)
Jordy Rosef53e8c72011-08-23 19:43:16 +00003274 return;
3275
3276 // Get the updated binding.
3277 T = state->get<RefBindings>(Sym);
3278 assert(T);
3279 X = *T;
3280
3281 // Consult the summary of the enclosing method.
Jordy Rose17a38e22011-09-02 05:55:19 +00003282 RetainSummaryManager &Summaries = getSummaryManager(C);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003283 const Decl *CD = &Pred->getCodeDecl();
3284
3285 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CD)) {
3286 // Unlike regular functions, /all/ ObjC methods are assumed to always
3287 // follow Cocoa retain-count conventions, not just those with special
3288 // names or attributes.
Jordy Roseb6cfc092011-08-25 00:10:37 +00003289 const RetainSummary *Summ = Summaries.getMethodSummary(MD);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003290 RetEffect RE = Summ ? Summ->getRetEffect() : RetEffect::MakeNoRet();
3291 checkReturnWithRetEffect(S, C, Pred, RE, X, Sym, state);
3292 }
3293
3294 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) {
3295 if (!isa<CXXMethodDecl>(FD))
Anna Zaks58822c42012-05-04 22:18:39 +00003296 if (const RetainSummary *Summ = Summaries.getSummary(FD, 0))
Jordy Rosef53e8c72011-08-23 19:43:16 +00003297 checkReturnWithRetEffect(S, C, Pred, Summ->getRetEffect(), X,
3298 Sym, state);
3299 }
3300}
3301
Jordy Rose910c4052011-09-02 06:44:22 +00003302void RetainCountChecker::checkReturnWithRetEffect(const ReturnStmt *S,
3303 CheckerContext &C,
3304 ExplodedNode *Pred,
3305 RetEffect RE, RefVal X,
3306 SymbolRef Sym,
Ted Kremenek8bef8232012-01-26 21:29:00 +00003307 ProgramStateRef state) const {
Jordy Rosef53e8c72011-08-23 19:43:16 +00003308 // Any leaks or other errors?
3309 if (X.isReturnedOwned() && X.getCount() == 0) {
3310 if (RE.getKind() != RetEffect::NoRet) {
3311 bool hasError = false;
Jordy Rose17a38e22011-09-02 05:55:19 +00003312 if (C.isObjCGCEnabled() && RE.getObjKind() == RetEffect::ObjC) {
Jordy Rosef53e8c72011-08-23 19:43:16 +00003313 // Things are more complicated with garbage collection. If the
3314 // returned object is suppose to be an Objective-C object, we have
3315 // a leak (as the caller expects a GC'ed object) because no
3316 // method should return ownership unless it returns a CF object.
3317 hasError = true;
3318 X = X ^ RefVal::ErrorGCLeakReturned;
3319 }
3320 else if (!RE.isOwned()) {
3321 // Either we are using GC and the returned object is a CF type
3322 // or we aren't using GC. In either case, we expect that the
3323 // enclosing method is expected to return ownership.
3324 hasError = true;
3325 X = X ^ RefVal::ErrorLeakReturned;
3326 }
3327
3328 if (hasError) {
3329 // Generate an error node.
3330 state = state->set<RefBindings>(Sym, X);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003331
3332 static SimpleProgramPointTag
Jordy Rose910c4052011-09-02 06:44:22 +00003333 ReturnOwnLeakTag("RetainCountChecker : ReturnsOwnLeak");
Anna Zaks0bd6b112011-10-26 21:06:34 +00003334 ExplodedNode *N = C.addTransition(state, Pred, &ReturnOwnLeakTag);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003335 if (N) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003336 const LangOptions &LOpts = C.getASTContext().getLangOpts();
Jordy Rose17a38e22011-09-02 05:55:19 +00003337 bool GCEnabled = C.isObjCGCEnabled();
Jordy Rosef53e8c72011-08-23 19:43:16 +00003338 CFRefReport *report =
Jordy Rose17a38e22011-09-02 05:55:19 +00003339 new CFRefLeakReport(*getLeakAtReturnBug(LOpts, GCEnabled),
3340 LOpts, GCEnabled, SummaryLog,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003341 N, Sym, C);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003342 C.EmitReport(report);
3343 }
3344 }
3345 }
3346 } else if (X.isReturnedNotOwned()) {
3347 if (RE.isOwned()) {
3348 // Trying to return a not owned object to a caller expecting an
3349 // owned object.
3350 state = state->set<RefBindings>(Sym, X ^ RefVal::ErrorReturnedNotOwned);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003351
3352 static SimpleProgramPointTag
Jordy Rose910c4052011-09-02 06:44:22 +00003353 ReturnNotOwnedTag("RetainCountChecker : ReturnNotOwnedForOwned");
Anna Zaks0bd6b112011-10-26 21:06:34 +00003354 ExplodedNode *N = C.addTransition(state, Pred, &ReturnNotOwnedTag);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003355 if (N) {
Jordy Rosed6334e12011-08-25 00:34:03 +00003356 if (!returnNotOwnedForOwned)
3357 returnNotOwnedForOwned.reset(new ReturnedNotOwnedForOwned());
3358
Jordy Rosef53e8c72011-08-23 19:43:16 +00003359 CFRefReport *report =
Jordy Rosed6334e12011-08-25 00:34:03 +00003360 new CFRefReport(*returnNotOwnedForOwned,
David Blaikie4e4d0842012-03-11 07:00:24 +00003361 C.getASTContext().getLangOpts(),
Jordy Rose17a38e22011-09-02 05:55:19 +00003362 C.isObjCGCEnabled(), SummaryLog, N, Sym);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003363 C.EmitReport(report);
3364 }
3365 }
3366 }
3367}
3368
Jordy Rose8d228632011-08-23 20:07:14 +00003369//===----------------------------------------------------------------------===//
Jordy Rose910c4052011-09-02 06:44:22 +00003370// Check various ways a symbol can be invalidated.
3371//===----------------------------------------------------------------------===//
3372
Anna Zaks390909c2011-10-06 00:43:15 +00003373void RetainCountChecker::checkBind(SVal loc, SVal val, const Stmt *S,
Jordy Rose910c4052011-09-02 06:44:22 +00003374 CheckerContext &C) const {
3375 // Are we storing to something that causes the value to "escape"?
3376 bool escapes = true;
3377
3378 // A value escapes in three possible cases (this may change):
3379 //
3380 // (1) we are binding to something that is not a memory region.
3381 // (2) we are binding to a memregion that does not have stack storage
3382 // (3) we are binding to a memregion with stack storage that the store
3383 // does not understand.
Ted Kremenek8bef8232012-01-26 21:29:00 +00003384 ProgramStateRef state = C.getState();
Jordy Rose910c4052011-09-02 06:44:22 +00003385
3386 if (loc::MemRegionVal *regionLoc = dyn_cast<loc::MemRegionVal>(&loc)) {
3387 escapes = !regionLoc->getRegion()->hasStackStorage();
3388
3389 if (!escapes) {
3390 // To test (3), generate a new state with the binding added. If it is
3391 // the same state, then it escapes (since the store cannot represent
3392 // the binding).
Anna Zakse7958da2012-05-02 00:15:40 +00003393 // Do this only if we know that the store is not supposed to generate the
3394 // same state.
3395 SVal StoredVal = state->getSVal(regionLoc->getRegion());
3396 if (StoredVal != val)
3397 escapes = (state == (state->bindLoc(*regionLoc, val)));
Jordy Rose910c4052011-09-02 06:44:22 +00003398 }
Ted Kremenekde5b4fb2012-03-27 01:12:45 +00003399 if (!escapes) {
3400 // Case 4: We do not currently model what happens when a symbol is
3401 // assigned to a struct field, so be conservative here and let the symbol
3402 // go. TODO: This could definitely be improved upon.
3403 escapes = !isa<VarRegion>(regionLoc->getRegion());
3404 }
Jordy Rose910c4052011-09-02 06:44:22 +00003405 }
3406
3407 // 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 Zaks0bd6b112011-10-26 21:06:34 +00003416 C.addTransition(state);
Jordy Rose910c4052011-09-02 06:44:22 +00003417}
3418
Ted Kremenek8bef8232012-01-26 21:29:00 +00003419ProgramStateRef RetainCountChecker::evalAssume(ProgramStateRef state,
Jordy Rose910c4052011-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.
3429 RefBindings B = state->get<RefBindings>();
3430
3431 if (B.isEmpty())
3432 return state;
3433
3434 bool changed = false;
3435 RefBindings::Factory &RefBFactory = state->get_context<RefBindings>();
3436
3437 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
3438 // Check if the symbol is null (or equal to any constant).
3439 // If this is the case, stop tracking the symbol.
3440 if (state->getSymVal(I.getKey())) {
3441 changed = true;
3442 B = RefBFactory.remove(B, I.getKey());
3443 }
3444 }
3445
3446 if (changed)
3447 state = state->set<RefBindings>(B);
3448
3449 return state;
3450}
3451
Ted Kremenek8bef8232012-01-26 21:29:00 +00003452ProgramStateRef
3453RetainCountChecker::checkRegionChanges(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003454 const StoreManager::InvalidatedSymbols *invalidated,
3455 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00003456 ArrayRef<const MemRegion *> Regions,
Jordan Rose740d4902012-07-02 19:27:35 +00003457 const CallEvent *Call) const {
Jordy Rose910c4052011-09-02 06:44:22 +00003458 if (!invalidated)
3459 return state;
3460
3461 llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
3462 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
3463 E = ExplicitRegions.end(); I != E; ++I) {
3464 if (const SymbolicRegion *SR = (*I)->StripCasts()->getAs<SymbolicRegion>())
3465 WhitelistedSymbols.insert(SR->getSymbol());
3466 }
3467
3468 for (StoreManager::InvalidatedSymbols::const_iterator I=invalidated->begin(),
3469 E = invalidated->end(); I!=E; ++I) {
3470 SymbolRef sym = *I;
3471 if (WhitelistedSymbols.count(sym))
3472 continue;
3473 // Remove any existing reference-count binding.
3474 state = state->remove<RefBindings>(sym);
3475 }
3476 return state;
3477}
3478
3479//===----------------------------------------------------------------------===//
Jordy Rose8d228632011-08-23 20:07:14 +00003480// Handle dead symbols and end-of-path.
3481//===----------------------------------------------------------------------===//
3482
Ted Kremenek8bef8232012-01-26 21:29:00 +00003483std::pair<ExplodedNode *, ProgramStateRef >
3484RetainCountChecker::handleAutoreleaseCounts(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003485 GenericNodeBuilderRefCount Bd,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003486 ExplodedNode *Pred,
3487 CheckerContext &Ctx,
Jordy Rose910c4052011-09-02 06:44:22 +00003488 SymbolRef Sym, RefVal V) const {
Jordy Rose8d228632011-08-23 20:07:14 +00003489 unsigned ACnt = V.getAutoreleaseCount();
3490
3491 // No autorelease counts? Nothing to be done.
3492 if (!ACnt)
3493 return std::make_pair(Pred, state);
3494
Anna Zaks6a93bd52011-10-25 19:57:11 +00003495 assert(!Ctx.isObjCGCEnabled() && "Autorelease counts in GC mode?");
Jordy Rose8d228632011-08-23 20:07:14 +00003496 unsigned Cnt = V.getCount();
3497
3498 // FIXME: Handle sending 'autorelease' to already released object.
3499
3500 if (V.getKind() == RefVal::ReturnedOwned)
3501 ++Cnt;
3502
3503 if (ACnt <= Cnt) {
3504 if (ACnt == Cnt) {
3505 V.clearCounts();
3506 if (V.getKind() == RefVal::ReturnedOwned)
3507 V = V ^ RefVal::ReturnedNotOwned;
3508 else
3509 V = V ^ RefVal::NotOwned;
3510 } else {
3511 V.setCount(Cnt - ACnt);
3512 V.setAutoreleaseCount(0);
3513 }
3514 state = state->set<RefBindings>(Sym, V);
3515 ExplodedNode *N = Bd.MakeNode(state, Pred);
3516 if (N == 0)
3517 state = 0;
3518 return std::make_pair(N, state);
3519 }
3520
3521 // Woah! More autorelease counts then retain counts left.
3522 // Emit hard error.
3523 V = V ^ RefVal::ErrorOverAutorelease;
3524 state = state->set<RefBindings>(Sym, V);
3525
Anna Zaksf05aac82011-10-18 23:05:58 +00003526 if (ExplodedNode *N = Bd.MakeNode(state, Pred, true)) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003527 SmallString<128> sbuf;
Jordy Rose8d228632011-08-23 20:07:14 +00003528 llvm::raw_svector_ostream os(sbuf);
3529 os << "Object over-autoreleased: object was sent -autorelease ";
3530 if (V.getAutoreleaseCount() > 1)
3531 os << V.getAutoreleaseCount() << " times ";
3532 os << "but the object has a +" << V.getCount() << " retain count";
3533
Jordy Rosed6334e12011-08-25 00:34:03 +00003534 if (!overAutorelease)
3535 overAutorelease.reset(new OverAutorelease());
3536
David Blaikie4e4d0842012-03-11 07:00:24 +00003537 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
Jordy Rose8d228632011-08-23 20:07:14 +00003538 CFRefReport *report =
Jordy Rosed6334e12011-08-25 00:34:03 +00003539 new CFRefReport(*overAutorelease, LOpts, /* GCEnabled = */ false,
3540 SummaryLog, N, Sym, os.str());
Anna Zaks6a93bd52011-10-25 19:57:11 +00003541 Ctx.EmitReport(report);
Jordy Rose8d228632011-08-23 20:07:14 +00003542 }
3543
Ted Kremenek8bef8232012-01-26 21:29:00 +00003544 return std::make_pair((ExplodedNode *)0, (ProgramStateRef )0);
Jordy Rose8d228632011-08-23 20:07:14 +00003545}
Jordy Rose38f17d62011-08-23 19:01:07 +00003546
Ted Kremenek8bef8232012-01-26 21:29:00 +00003547ProgramStateRef
3548RetainCountChecker::handleSymbolDeath(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003549 SymbolRef sid, RefVal V,
Jordy Rose38f17d62011-08-23 19:01:07 +00003550 SmallVectorImpl<SymbolRef> &Leaked) const {
Jordy Rose53376122011-08-24 04:48:19 +00003551 bool hasLeak = false;
Jordy Rose38f17d62011-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)
3558 return state->remove<RefBindings>(sid);
3559
3560 Leaked.push_back(sid);
3561 return state->set<RefBindings>(sid, V ^ RefVal::ErrorLeak);
3562}
3563
3564ExplodedNode *
Ted Kremenek8bef8232012-01-26 21:29:00 +00003565RetainCountChecker::processLeaks(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003566 SmallVectorImpl<SymbolRef> &Leaked,
3567 GenericNodeBuilderRefCount &Builder,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003568 CheckerContext &Ctx,
3569 ExplodedNode *Pred) const {
Jordy Rose38f17d62011-08-23 19:01:07 +00003570 if (Leaked.empty())
3571 return Pred;
3572
3573 // Generate an intermediate node representing the leak point.
3574 ExplodedNode *N = Builder.MakeNode(state, Pred);
3575
3576 if (N) {
3577 for (SmallVectorImpl<SymbolRef>::iterator
3578 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3579
David Blaikie4e4d0842012-03-11 07:00:24 +00003580 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
Anna Zaks6a93bd52011-10-25 19:57:11 +00003581 bool GCEnabled = Ctx.isObjCGCEnabled();
Jordy Rose17a38e22011-09-02 05:55:19 +00003582 CFRefBug *BT = Pred ? getLeakWithinFunctionBug(LOpts, GCEnabled)
3583 : getLeakAtReturnBug(LOpts, GCEnabled);
Jordy Rose38f17d62011-08-23 19:01:07 +00003584 assert(BT && "BugType not initialized.");
Jordy Rose20589562011-08-24 22:39:09 +00003585
Jordy Rose17a38e22011-09-02 05:55:19 +00003586 CFRefLeakReport *report = new CFRefLeakReport(*BT, LOpts, GCEnabled,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003587 SummaryLog, N, *I, Ctx);
3588 Ctx.EmitReport(report);
Jordy Rose38f17d62011-08-23 19:01:07 +00003589 }
3590 }
3591
3592 return N;
3593}
3594
Anna Zaksaf498a22011-10-25 19:56:48 +00003595void RetainCountChecker::checkEndPath(CheckerContext &Ctx) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +00003596 ProgramStateRef state = Ctx.getState();
Anna Zaksaf498a22011-10-25 19:56:48 +00003597 GenericNodeBuilderRefCount Bd(Ctx);
Jordy Rose38f17d62011-08-23 19:01:07 +00003598 RefBindings B = state->get<RefBindings>();
Anna Zaksaf498a22011-10-25 19:56:48 +00003599 ExplodedNode *Pred = Ctx.getPredecessor();
Jordy Rose38f17d62011-08-23 19:01:07 +00003600
3601 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Anna Zaks6a93bd52011-10-25 19:57:11 +00003602 llvm::tie(Pred, state) = handleAutoreleaseCounts(state, Bd, Pred, Ctx,
Jordy Rose8d228632011-08-23 20:07:14 +00003603 I->first, I->second);
3604 if (!state)
Jordy Rose38f17d62011-08-23 19:01:07 +00003605 return;
3606 }
3607
Ted Kremenek0cf3d472012-02-07 00:24:33 +00003608 // If the current LocationContext has a parent, don't check for leaks.
3609 // We will do that later.
3610 // FIXME: we should instead check for imblances of the retain/releases,
3611 // and suggest annotations.
3612 if (Ctx.getLocationContext()->getParent())
3613 return;
3614
Jordy Rose38f17d62011-08-23 19:01:07 +00003615 B = state->get<RefBindings>();
3616 SmallVector<SymbolRef, 10> Leaked;
3617
3618 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I)
Jordy Rose8d228632011-08-23 20:07:14 +00003619 state = handleSymbolDeath(state, I->first, I->second, Leaked);
Jordy Rose38f17d62011-08-23 19:01:07 +00003620
Anna Zaks6a93bd52011-10-25 19:57:11 +00003621 processLeaks(state, Leaked, Bd, Ctx, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003622}
3623
3624const ProgramPointTag *
Jordy Rose910c4052011-09-02 06:44:22 +00003625RetainCountChecker::getDeadSymbolTag(SymbolRef sym) const {
Jordy Rose38f17d62011-08-23 19:01:07 +00003626 const SimpleProgramPointTag *&tag = DeadSymbolTags[sym];
3627 if (!tag) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003628 SmallString<64> buf;
Jordy Rose38f17d62011-08-23 19:01:07 +00003629 llvm::raw_svector_ostream out(buf);
Anna Zaksf62ceec2011-12-05 18:58:11 +00003630 out << "RetainCountChecker : Dead Symbol : ";
3631 sym->dumpToStream(out);
Jordy Rose38f17d62011-08-23 19:01:07 +00003632 tag = new SimpleProgramPointTag(out.str());
3633 }
3634 return tag;
3635}
3636
Jordy Rose910c4052011-09-02 06:44:22 +00003637void RetainCountChecker::checkDeadSymbols(SymbolReaper &SymReaper,
3638 CheckerContext &C) const {
Jordy Rose38f17d62011-08-23 19:01:07 +00003639 ExplodedNode *Pred = C.getPredecessor();
3640
Ted Kremenek8bef8232012-01-26 21:29:00 +00003641 ProgramStateRef state = C.getState();
Jordy Rose38f17d62011-08-23 19:01:07 +00003642 RefBindings B = state->get<RefBindings>();
3643
3644 // Update counts from autorelease pools
3645 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3646 E = SymReaper.dead_end(); I != E; ++I) {
3647 SymbolRef Sym = *I;
3648 if (const RefVal *T = B.lookup(Sym)){
3649 // Use the symbol as the tag.
3650 // FIXME: This might not be as unique as we would like.
Anna Zaks4eff8232011-10-05 23:44:11 +00003651 GenericNodeBuilderRefCount Bd(C, getDeadSymbolTag(Sym));
Anna Zaks6a93bd52011-10-25 19:57:11 +00003652 llvm::tie(Pred, state) = handleAutoreleaseCounts(state, Bd, Pred, C,
Jordy Rose8d228632011-08-23 20:07:14 +00003653 Sym, *T);
3654 if (!state)
Jordy Rose38f17d62011-08-23 19:01:07 +00003655 return;
3656 }
3657 }
3658
3659 B = state->get<RefBindings>();
3660 SmallVector<SymbolRef, 10> Leaked;
3661
3662 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3663 E = SymReaper.dead_end(); I != E; ++I) {
3664 if (const RefVal *T = B.lookup(*I))
3665 state = handleSymbolDeath(state, *I, *T, Leaked);
3666 }
3667
3668 {
Anna Zaks4eff8232011-10-05 23:44:11 +00003669 GenericNodeBuilderRefCount Bd(C, this);
Anna Zaks6a93bd52011-10-25 19:57:11 +00003670 Pred = processLeaks(state, Leaked, Bd, C, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003671 }
3672
3673 // Did we cache out?
3674 if (!Pred)
3675 return;
3676
3677 // Now generate a new node that nukes the old bindings.
3678 RefBindings::Factory &F = state->get_context<RefBindings>();
3679
3680 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3681 E = SymReaper.dead_end(); I != E; ++I)
3682 B = F.remove(B, *I);
3683
3684 state = state->set<RefBindings>(B);
Anna Zaks0bd6b112011-10-26 21:06:34 +00003685 C.addTransition(state, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003686}
3687
Ted Kremenekd593eb92009-11-25 22:17:44 +00003688//===----------------------------------------------------------------------===//
Jordy Rosedbd658e2011-08-28 19:11:56 +00003689// Debug printing of refcount bindings and autorelease pools.
3690//===----------------------------------------------------------------------===//
3691
3692static void PrintPool(raw_ostream &Out, SymbolRef Sym,
Ted Kremenek8bef8232012-01-26 21:29:00 +00003693 ProgramStateRef State) {
Jordy Rosedbd658e2011-08-28 19:11:56 +00003694 Out << ' ';
3695 if (Sym)
Anna Zaksf62ceec2011-12-05 18:58:11 +00003696 Sym->dumpToStream(Out);
Jordy Rosedbd658e2011-08-28 19:11:56 +00003697 else
3698 Out << "<pool>";
3699 Out << ":{";
3700
3701 // Get the contents of the pool.
3702 if (const ARCounts *Cnts = State->get<AutoreleasePoolContents>(Sym))
3703 for (ARCounts::iterator I = Cnts->begin(), E = Cnts->end(); I != E; ++I)
3704 Out << '(' << I.getKey() << ',' << I.getData() << ')';
3705
3706 Out << '}';
3707}
3708
Ted Kremenek8bef8232012-01-26 21:29:00 +00003709static bool UsesAutorelease(ProgramStateRef state) {
Jordy Rosedbd658e2011-08-28 19:11:56 +00003710 // A state uses autorelease if it allocated an autorelease pool or if it has
3711 // objects in the caller's autorelease pool.
3712 return !state->get<AutoreleaseStack>().isEmpty() ||
3713 state->get<AutoreleasePoolContents>(SymbolRef());
3714}
3715
Ted Kremenek8bef8232012-01-26 21:29:00 +00003716void RetainCountChecker::printState(raw_ostream &Out, ProgramStateRef State,
Jordy Rose910c4052011-09-02 06:44:22 +00003717 const char *NL, const char *Sep) const {
Jordy Rosedbd658e2011-08-28 19:11:56 +00003718
3719 RefBindings B = State->get<RefBindings>();
3720
3721 if (!B.isEmpty())
3722 Out << Sep << NL;
3723
3724 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
3725 Out << I->first << " : ";
3726 I->second.print(Out);
3727 Out << NL;
3728 }
3729
3730 // Print the autorelease stack.
3731 if (UsesAutorelease(State)) {
3732 Out << Sep << NL << "AR pool stack:";
3733 ARStack Stack = State->get<AutoreleaseStack>();
3734
3735 PrintPool(Out, SymbolRef(), State); // Print the caller's pool.
3736 for (ARStack::iterator I = Stack.begin(), E = Stack.end(); I != E; ++I)
3737 PrintPool(Out, *I, State);
3738
3739 Out << NL;
3740 }
3741}
3742
3743//===----------------------------------------------------------------------===//
Jordy Rose910c4052011-09-02 06:44:22 +00003744// Checker registration.
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00003745//===----------------------------------------------------------------------===//
3746
Jordy Rose17a38e22011-09-02 05:55:19 +00003747void ento::registerRetainCountChecker(CheckerManager &Mgr) {
Jordy Rose910c4052011-09-02 06:44:22 +00003748 Mgr.registerChecker<RetainCountChecker>();
Jordy Rose17a38e22011-09-02 05:55:19 +00003749}
3750