blob: 61448a035e0022be2187c5010ef8a84082da1201 [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,
Ted Kremenekf95e9fc2009-03-17 19:42:23 +000070 NewAutoreleasePool, SelfOwn, 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 }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000135};
Mike Stump1eb44332009-09-09 15:08:12 +0000136
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000137//===----------------------------------------------------------------------===//
138// Reference-counting logic (typestate + counts).
139//===----------------------------------------------------------------------===//
Mike Stump1eb44332009-09-09 15:08:12 +0000140
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000141class RefVal {
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000142public:
143 enum Kind {
144 Owned = 0, // Owning reference.
145 NotOwned, // Reference is not owned by still valid (not freed).
146 Released, // Object has been released.
147 ReturnedOwned, // Returned object passes ownership to caller.
148 ReturnedNotOwned, // Return object does not pass ownership to caller.
149 ERROR_START,
150 ErrorDeallocNotOwned, // -dealloc called on non-owned object.
151 ErrorDeallocGC, // Calling -dealloc with GC enabled.
152 ErrorUseAfterRelease, // Object used after released.
153 ErrorReleaseNotOwned, // Release of an object that was not owned.
154 ERROR_LEAK_START,
155 ErrorLeak, // A memory leak due to excessive reference counts.
156 ErrorLeakReturned, // A memory leak due to the returning method not having
157 // the correct naming conventions.
158 ErrorGCLeakReturned,
159 ErrorOverAutorelease,
160 ErrorReturnedNotOwned
161 };
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000162
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000163private:
164 Kind kind;
165 RetEffect::ObjKind okind;
166 unsigned Cnt;
167 unsigned ACnt;
168 QualType T;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000169
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000170 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, unsigned acnt, QualType t)
171 : kind(k), okind(o), Cnt(cnt), ACnt(acnt), T(t) {}
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000172
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000173public:
174 Kind getKind() const { return kind; }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000175
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000176 RetEffect::ObjKind getObjKind() const { return okind; }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000177
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000178 unsigned getCount() const { return Cnt; }
179 unsigned getAutoreleaseCount() const { return ACnt; }
180 unsigned getCombinedCounts() const { return Cnt + ACnt; }
181 void clearCounts() { Cnt = 0; ACnt = 0; }
182 void setCount(unsigned i) { Cnt = i; }
183 void setAutoreleaseCount(unsigned i) { ACnt = i; }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000184
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000185 QualType getType() const { return T; }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000186
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000187 bool isOwned() const {
188 return getKind() == Owned;
189 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000190
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000191 bool isNotOwned() const {
192 return getKind() == NotOwned;
193 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000194
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000195 bool isReturnedOwned() const {
196 return getKind() == ReturnedOwned;
197 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000198
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000199 bool isReturnedNotOwned() const {
200 return getKind() == ReturnedNotOwned;
201 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000202
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000203 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
204 unsigned Count = 1) {
205 return RefVal(Owned, o, Count, 0, t);
206 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000207
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000208 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
209 unsigned Count = 0) {
210 return RefVal(NotOwned, o, Count, 0, t);
211 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000212
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000213 // Comparison, profiling, and pretty-printing.
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000214
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000215 bool operator==(const RefVal& X) const {
216 return kind == X.kind && Cnt == X.Cnt && T == X.T && ACnt == X.ACnt;
217 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000218
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000219 RefVal operator-(size_t i) const {
220 return RefVal(getKind(), getObjKind(), getCount() - i,
221 getAutoreleaseCount(), getType());
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^(Kind k) const {
230 return RefVal(k, getObjKind(), getCount(), getAutoreleaseCount(),
231 getType());
232 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000233
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000234 RefVal autorelease() const {
235 return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount()+1,
236 getType());
237 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000238
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000239 void Profile(llvm::FoldingSetNodeID& ID) const {
240 ID.AddInteger((unsigned) kind);
241 ID.AddInteger(Cnt);
242 ID.AddInteger(ACnt);
243 ID.Add(T);
244 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000245
Ted Kremenek9c378f72011-08-12 23:37:29 +0000246 void print(raw_ostream &Out) const;
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000247};
248
Ted Kremenek9c378f72011-08-12 23:37:29 +0000249void RefVal::print(raw_ostream &Out) const {
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000250 if (!T.isNull())
Jordy Rosedbd658e2011-08-28 19:11:56 +0000251 Out << "Tracked " << T.getAsString() << '/';
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000252
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000253 switch (getKind()) {
Jordy Rose910c4052011-09-02 06:44:22 +0000254 default: llvm_unreachable("Invalid RefVal kind");
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000255 case Owned: {
256 Out << "Owned";
257 unsigned cnt = getCount();
258 if (cnt) Out << " (+ " << cnt << ")";
259 break;
260 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000261
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000262 case NotOwned: {
263 Out << "NotOwned";
264 unsigned cnt = getCount();
265 if (cnt) Out << " (+ " << cnt << ")";
266 break;
267 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000268
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000269 case ReturnedOwned: {
270 Out << "ReturnedOwned";
271 unsigned cnt = getCount();
272 if (cnt) Out << " (+ " << cnt << ")";
273 break;
274 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000275
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000276 case ReturnedNotOwned: {
277 Out << "ReturnedNotOwned";
278 unsigned cnt = getCount();
279 if (cnt) Out << " (+ " << cnt << ")";
280 break;
281 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000282
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000283 case Released:
284 Out << "Released";
285 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000286
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000287 case ErrorDeallocGC:
288 Out << "-dealloc (GC)";
289 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000290
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000291 case ErrorDeallocNotOwned:
292 Out << "-dealloc (not-owned)";
293 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000294
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000295 case ErrorLeak:
296 Out << "Leaked";
297 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000298
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000299 case ErrorLeakReturned:
300 Out << "Leaked (Bad naming)";
301 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000302
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000303 case ErrorGCLeakReturned:
304 Out << "Leaked (GC-ed at return)";
305 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000306
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000307 case ErrorUseAfterRelease:
308 Out << "Use-After-Release [ERROR]";
309 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000310
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000311 case ErrorReleaseNotOwned:
312 Out << "Release of Not-Owned [ERROR]";
313 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000314
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000315 case RefVal::ErrorOverAutorelease:
316 Out << "Over autoreleased";
317 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000318
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000319 case RefVal::ErrorReturnedNotOwned:
320 Out << "Non-owned object returned instead of owned";
321 break;
322 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000323
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000324 if (ACnt) {
325 Out << " [ARC +" << ACnt << ']';
326 }
327}
328} //end anonymous namespace
329
330//===----------------------------------------------------------------------===//
331// RefBindings - State used to track object reference counts.
332//===----------------------------------------------------------------------===//
333
334typedef llvm::ImmutableMap<SymbolRef, RefVal> RefBindings;
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000335
336namespace clang {
Ted Kremenek9ef65372010-12-23 07:20:52 +0000337namespace ento {
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000338template<>
339struct ProgramStateTrait<RefBindings>
340 : public ProgramStatePartialTrait<RefBindings> {
341 static void *GDMIndex() {
342 static int RefBIndex = 0;
343 return &RefBIndex;
344 }
345};
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000346}
Argyrios Kyrtzidis5a4f98f2010-12-22 18:53:20 +0000347}
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000348
349//===----------------------------------------------------------------------===//
Jordy Rose910c4052011-09-02 06:44:22 +0000350// Function/Method behavior summaries.
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000351//===----------------------------------------------------------------------===//
352
353namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000354class RetainSummary {
Ted Kremenek1bffd742008-05-06 15:44:25 +0000355 /// Args - an ordered vector of (index, ArgEffect) pairs, where index
356 /// specifies the argument (starting from 0). This can be sparsely
357 /// populated; arguments with no entry in Args use 'DefaultArgEffect'.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000358 ArgEffects Args;
Mike Stump1eb44332009-09-09 15:08:12 +0000359
Ted Kremenek1bffd742008-05-06 15:44:25 +0000360 /// DefaultArgEffect - The default ArgEffect to apply to arguments that
361 /// do not have an entry in Args.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000362 ArgEffect DefaultArgEffect;
Mike Stump1eb44332009-09-09 15:08:12 +0000363
Ted Kremenek553cf182008-06-25 21:21:56 +0000364 /// Receiver - If this summary applies to an Objective-C message expression,
365 /// this is the effect applied to the state of the receiver.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000366 ArgEffect Receiver;
Mike Stump1eb44332009-09-09 15:08:12 +0000367
Ted Kremenek553cf182008-06-25 21:21:56 +0000368 /// Ret - The effect on the return value. Used to indicate if the
Jordy Rose76c506f2011-08-21 21:58:18 +0000369 /// function/method call returns a new tracked symbol.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000370 RetEffect Ret;
Mike Stump1eb44332009-09-09 15:08:12 +0000371
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000372public:
Ted Kremenekb77449c2009-05-03 05:20:50 +0000373 RetainSummary(ArgEffects A, RetEffect R, ArgEffect defaultEff,
Jordy Rosee62e87b2011-08-20 20:55:40 +0000374 ArgEffect ReceiverEff)
375 : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000376
Ted Kremenek553cf182008-06-25 21:21:56 +0000377 /// getArg - Return the argument effect on the argument specified by
378 /// idx (starting from 0).
Ted Kremenek1ac08d62008-03-11 17:48:22 +0000379 ArgEffect getArg(unsigned idx) const {
Ted Kremenekb77449c2009-05-03 05:20:50 +0000380 if (const ArgEffect *AE = Args.lookup(idx))
381 return *AE;
Mike Stump1eb44332009-09-09 15:08:12 +0000382
Ted Kremenek1bffd742008-05-06 15:44:25 +0000383 return DefaultArgEffect;
Ted Kremenek1ac08d62008-03-11 17:48:22 +0000384 }
Ted Kremenek11fe1752011-01-27 18:43:03 +0000385
386 void addArg(ArgEffects::Factory &af, unsigned idx, ArgEffect e) {
387 Args = af.add(Args, idx, e);
388 }
Mike Stump1eb44332009-09-09 15:08:12 +0000389
Ted Kremenek885c27b2009-05-04 05:31:22 +0000390 /// setDefaultArgEffect - Set the default argument effect.
391 void setDefaultArgEffect(ArgEffect E) {
392 DefaultArgEffect = E;
393 }
Mike Stump1eb44332009-09-09 15:08:12 +0000394
Ted Kremenek553cf182008-06-25 21:21:56 +0000395 /// getRetEffect - Returns the effect on the return value of the call.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000396 RetEffect getRetEffect() const { return Ret; }
Mike Stump1eb44332009-09-09 15:08:12 +0000397
Ted Kremenek885c27b2009-05-04 05:31:22 +0000398 /// setRetEffect - Set the effect of the return value of the call.
399 void setRetEffect(RetEffect E) { Ret = E; }
Mike Stump1eb44332009-09-09 15:08:12 +0000400
Ted Kremenek12b94342011-01-27 06:54:14 +0000401
402 /// Sets the effect on the receiver of the message.
403 void setReceiverEffect(ArgEffect e) { Receiver = e; }
404
Ted Kremenek553cf182008-06-25 21:21:56 +0000405 /// getReceiverEffect - Returns the effect on the receiver of the call.
406 /// This is only meaningful if the summary applies to an ObjCMessageExpr*.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000407 ArgEffect getReceiverEffect() const { return Receiver; }
Jordy Rose4df54fe2011-08-23 04:27:15 +0000408
409 /// Test if two retain summaries are identical. Note that merely equivalent
410 /// summaries are not necessarily identical (for example, if an explicit
411 /// argument effect matches the default effect).
412 bool operator==(const RetainSummary &Other) const {
413 return Args == Other.Args && DefaultArgEffect == Other.DefaultArgEffect &&
414 Receiver == Other.Receiver && Ret == Other.Ret;
415 }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000416};
Ted Kremenek4f22a782008-06-23 23:30:29 +0000417} // end anonymous namespace
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000418
Ted Kremenek553cf182008-06-25 21:21:56 +0000419//===----------------------------------------------------------------------===//
420// Data structures for constructing summaries.
421//===----------------------------------------------------------------------===//
Ted Kremenek53301ba2008-06-24 03:49:48 +0000422
Ted Kremenek553cf182008-06-25 21:21:56 +0000423namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000424class ObjCSummaryKey {
Ted Kremenek553cf182008-06-25 21:21:56 +0000425 IdentifierInfo* II;
426 Selector S;
Mike Stump1eb44332009-09-09 15:08:12 +0000427public:
Ted Kremenek553cf182008-06-25 21:21:56 +0000428 ObjCSummaryKey(IdentifierInfo* ii, Selector s)
429 : II(ii), S(s) {}
430
Ted Kremenek9c378f72011-08-12 23:37:29 +0000431 ObjCSummaryKey(const ObjCInterfaceDecl *d, Selector s)
Ted Kremenek553cf182008-06-25 21:21:56 +0000432 : II(d ? d->getIdentifier() : 0), S(s) {}
Ted Kremenek70b6a832009-05-13 18:16:01 +0000433
Ted Kremenek9c378f72011-08-12 23:37:29 +0000434 ObjCSummaryKey(const ObjCInterfaceDecl *d, IdentifierInfo *ii, Selector s)
Ted Kremenek70b6a832009-05-13 18:16:01 +0000435 : II(d ? d->getIdentifier() : ii), S(s) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000436
Ted Kremenek553cf182008-06-25 21:21:56 +0000437 ObjCSummaryKey(Selector s)
438 : II(0), S(s) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000439
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000440 IdentifierInfo *getIdentifier() const { return II; }
Ted Kremenek553cf182008-06-25 21:21:56 +0000441 Selector getSelector() const { return S; }
442};
Ted Kremenek4f22a782008-06-23 23:30:29 +0000443}
444
445namespace llvm {
Ted Kremenek553cf182008-06-25 21:21:56 +0000446template <> struct DenseMapInfo<ObjCSummaryKey> {
447 static inline ObjCSummaryKey getEmptyKey() {
448 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
449 DenseMapInfo<Selector>::getEmptyKey());
450 }
Mike Stump1eb44332009-09-09 15:08:12 +0000451
Ted Kremenek553cf182008-06-25 21:21:56 +0000452 static inline ObjCSummaryKey getTombstoneKey() {
453 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
Mike Stump1eb44332009-09-09 15:08:12 +0000454 DenseMapInfo<Selector>::getTombstoneKey());
Ted Kremenek553cf182008-06-25 21:21:56 +0000455 }
Mike Stump1eb44332009-09-09 15:08:12 +0000456
Ted Kremenek553cf182008-06-25 21:21:56 +0000457 static unsigned getHashValue(const ObjCSummaryKey &V) {
458 return (DenseMapInfo<IdentifierInfo*>::getHashValue(V.getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000459 & 0x88888888)
Ted Kremenek553cf182008-06-25 21:21:56 +0000460 | (DenseMapInfo<Selector>::getHashValue(V.getSelector())
461 & 0x55555555);
462 }
Mike Stump1eb44332009-09-09 15:08:12 +0000463
Ted Kremenek553cf182008-06-25 21:21:56 +0000464 static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
465 return DenseMapInfo<IdentifierInfo*>::isEqual(LHS.getIdentifier(),
466 RHS.getIdentifier()) &&
467 DenseMapInfo<Selector>::isEqual(LHS.getSelector(),
468 RHS.getSelector());
469 }
Mike Stump1eb44332009-09-09 15:08:12 +0000470
Ted Kremenek553cf182008-06-25 21:21:56 +0000471};
Chris Lattner06159e82009-12-15 07:26:51 +0000472template <>
473struct isPodLike<ObjCSummaryKey> { static const bool value = true; };
Ted Kremenek4f22a782008-06-23 23:30:29 +0000474} // end llvm namespace
Mike Stump1eb44332009-09-09 15:08:12 +0000475
Ted Kremenek4f22a782008-06-23 23:30:29 +0000476namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000477class ObjCSummaryCache {
Ted Kremenek93edbc52011-10-05 23:54:29 +0000478 typedef llvm::DenseMap<ObjCSummaryKey, const RetainSummary *> MapTy;
Ted Kremenek553cf182008-06-25 21:21:56 +0000479 MapTy M;
480public:
481 ObjCSummaryCache() {}
Mike Stump1eb44332009-09-09 15:08:12 +0000482
Ted Kremenek93edbc52011-10-05 23:54:29 +0000483 const RetainSummary * find(const ObjCInterfaceDecl *D, IdentifierInfo *ClsName,
Ted Kremeneka8833552009-04-29 23:03:22 +0000484 Selector S) {
Ted Kremenek8711c032009-04-29 05:04:30 +0000485 // Lookup the method using the decl for the class @interface. If we
486 // have no decl, lookup using the class name.
487 return D ? find(D, S) : find(ClsName, S);
488 }
Mike Stump1eb44332009-09-09 15:08:12 +0000489
Ted Kremenek93edbc52011-10-05 23:54:29 +0000490 const RetainSummary * find(const ObjCInterfaceDecl *D, Selector S) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000491 // Do a lookup with the (D,S) pair. If we find a match return
492 // the iterator.
493 ObjCSummaryKey K(D, S);
494 MapTy::iterator I = M.find(K);
Mike Stump1eb44332009-09-09 15:08:12 +0000495
Ted Kremenek553cf182008-06-25 21:21:56 +0000496 if (I != M.end() || !D)
Ted Kremenek614cc542009-07-21 23:27:57 +0000497 return I->second;
Mike Stump1eb44332009-09-09 15:08:12 +0000498
Ted Kremenek553cf182008-06-25 21:21:56 +0000499 // Walk the super chain. If we find a hit with a parent, we'll end
500 // up returning that summary. We actually allow that key (null,S), as
501 // we cache summaries for the null ObjCInterfaceDecl* to allow us to
502 // generate initial summaries without having to worry about NSObject
503 // being declared.
504 // FIXME: We may change this at some point.
Ted Kremenek9c378f72011-08-12 23:37:29 +0000505 for (ObjCInterfaceDecl *C=D->getSuperClass() ;; C=C->getSuperClass()) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000506 if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
507 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000508
Ted Kremenek553cf182008-06-25 21:21:56 +0000509 if (!C)
Ted Kremenek614cc542009-07-21 23:27:57 +0000510 return NULL;
Ted Kremenek553cf182008-06-25 21:21:56 +0000511 }
Mike Stump1eb44332009-09-09 15:08:12 +0000512
513 // Cache the summary with original key to make the next lookup faster
Ted Kremenek553cf182008-06-25 21:21:56 +0000514 // and return the iterator.
Ted Kremenek93edbc52011-10-05 23:54:29 +0000515 const RetainSummary *Summ = I->second;
Ted Kremenek614cc542009-07-21 23:27:57 +0000516 M[K] = Summ;
517 return Summ;
Ted Kremenek553cf182008-06-25 21:21:56 +0000518 }
Mike Stump1eb44332009-09-09 15:08:12 +0000519
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000520 const RetainSummary *find(IdentifierInfo* II, Selector S) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000521 // FIXME: Class method lookup. Right now we dont' have a good way
522 // of going between IdentifierInfo* and the class hierarchy.
Ted Kremenek614cc542009-07-21 23:27:57 +0000523 MapTy::iterator I = M.find(ObjCSummaryKey(II, S));
Mike Stump1eb44332009-09-09 15:08:12 +0000524
Ted Kremenek614cc542009-07-21 23:27:57 +0000525 if (I == M.end())
526 I = M.find(ObjCSummaryKey(S));
Mike Stump1eb44332009-09-09 15:08:12 +0000527
Ted Kremenek614cc542009-07-21 23:27:57 +0000528 return I == M.end() ? NULL : I->second;
Ted Kremenek553cf182008-06-25 21:21:56 +0000529 }
Mike Stump1eb44332009-09-09 15:08:12 +0000530
Ted Kremenek93edbc52011-10-05 23:54:29 +0000531 const RetainSummary *& operator[](ObjCSummaryKey K) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000532 return M[K];
533 }
Mike Stump1eb44332009-09-09 15:08:12 +0000534
Ted Kremenek93edbc52011-10-05 23:54:29 +0000535 const RetainSummary *& operator[](Selector S) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000536 return M[ ObjCSummaryKey(S) ];
537 }
Mike Stump1eb44332009-09-09 15:08:12 +0000538};
Ted Kremenek553cf182008-06-25 21:21:56 +0000539} // end anonymous namespace
540
541//===----------------------------------------------------------------------===//
542// Data structures for managing collections of summaries.
543//===----------------------------------------------------------------------===//
544
545namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000546class RetainSummaryManager {
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000547
548 //==-----------------------------------------------------------------==//
549 // Typedefs.
550 //==-----------------------------------------------------------------==//
Mike Stump1eb44332009-09-09 15:08:12 +0000551
Ted Kremenek93edbc52011-10-05 23:54:29 +0000552 typedef llvm::DenseMap<const FunctionDecl*, const RetainSummary *>
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000553 FuncSummariesTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000554
Ted Kremenek4f22a782008-06-23 23:30:29 +0000555 typedef ObjCSummaryCache ObjCMethodSummariesTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000556
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000557 //==-----------------------------------------------------------------==//
558 // Data.
559 //==-----------------------------------------------------------------==//
Mike Stump1eb44332009-09-09 15:08:12 +0000560
Ted Kremenek553cf182008-06-25 21:21:56 +0000561 /// Ctx - The ASTContext object for the analyzed ASTs.
Ted Kremenek9c378f72011-08-12 23:37:29 +0000562 ASTContext &Ctx;
Ted Kremenek179064e2008-07-01 17:21:27 +0000563
Ted Kremenek553cf182008-06-25 21:21:56 +0000564 /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
Ted Kremenek377e2302008-04-29 05:33:51 +0000565 const bool GCEnabled;
Mike Stump1eb44332009-09-09 15:08:12 +0000566
John McCallf85e1932011-06-15 23:02:42 +0000567 /// Records whether or not the analyzed code runs in ARC mode.
568 const bool ARCEnabled;
569
Ted Kremenek553cf182008-06-25 21:21:56 +0000570 /// FuncSummaries - A map from FunctionDecls to summaries.
Mike Stump1eb44332009-09-09 15:08:12 +0000571 FuncSummariesTy FuncSummaries;
572
Ted Kremenek553cf182008-06-25 21:21:56 +0000573 /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
574 /// to summaries.
Ted Kremenek1f180c32008-06-23 22:21:20 +0000575 ObjCMethodSummariesTy ObjCClassMethodSummaries;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000576
Ted Kremenek553cf182008-06-25 21:21:56 +0000577 /// ObjCMethodSummaries - A map from selectors to summaries.
Ted Kremenek1f180c32008-06-23 22:21:20 +0000578 ObjCMethodSummariesTy ObjCMethodSummaries;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000579
Ted Kremenek553cf182008-06-25 21:21:56 +0000580 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
581 /// and all other data used by the checker.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000582 llvm::BumpPtrAllocator BPAlloc;
Mike Stump1eb44332009-09-09 15:08:12 +0000583
Ted Kremenekb77449c2009-05-03 05:20:50 +0000584 /// AF - A factory for ArgEffects objects.
Mike Stump1eb44332009-09-09 15:08:12 +0000585 ArgEffects::Factory AF;
586
Ted Kremenek553cf182008-06-25 21:21:56 +0000587 /// ScratchArgs - A holding buffer for construct ArgEffects.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000588 ArgEffects ScratchArgs;
Mike Stump1eb44332009-09-09 15:08:12 +0000589
Ted Kremenekec315332009-05-07 23:40:42 +0000590 /// ObjCAllocRetE - Default return effect for methods returning Objective-C
591 /// objects.
592 RetEffect ObjCAllocRetE;
Ted Kremenek547d4952009-06-05 23:18:01 +0000593
Mike Stump1eb44332009-09-09 15:08:12 +0000594 /// ObjCInitRetE - Default return effect for init methods returning
Ted Kremenekac02f202009-08-20 05:13:36 +0000595 /// Objective-C objects.
Ted Kremenek547d4952009-06-05 23:18:01 +0000596 RetEffect ObjCInitRetE;
Mike Stump1eb44332009-09-09 15:08:12 +0000597
Ted Kremenek7faca822009-05-04 04:57:00 +0000598 RetainSummary DefaultSummary;
Ted Kremenek93edbc52011-10-05 23:54:29 +0000599 const RetainSummary *StopSummary;
Mike Stump1eb44332009-09-09 15:08:12 +0000600
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000601 //==-----------------------------------------------------------------==//
602 // Methods.
603 //==-----------------------------------------------------------------==//
Mike Stump1eb44332009-09-09 15:08:12 +0000604
Ted Kremenek553cf182008-06-25 21:21:56 +0000605 /// getArgEffects - Returns a persistent ArgEffects object based on the
606 /// data in ScratchArgs.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000607 ArgEffects getArgEffects();
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000608
Mike Stump1eb44332009-09-09 15:08:12 +0000609 enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
610
Ted Kremenek896cd9d2008-10-23 01:56:15 +0000611public:
Ted Kremenek78a35a32009-05-12 20:06:54 +0000612 RetEffect getObjAllocRetEffect() const { return ObjCAllocRetE; }
613
Ted Kremenek93edbc52011-10-05 23:54:29 +0000614 const RetainSummary *getDefaultSummary() {
615 return &DefaultSummary;
616 }
617
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000618 const RetainSummary *getUnarySummary(const FunctionType* FT,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000619 UnaryFuncKind func);
Mike Stump1eb44332009-09-09 15:08:12 +0000620
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000621 const RetainSummary *getCFSummaryCreateRule(const FunctionDecl *FD);
622 const RetainSummary *getCFSummaryGetRule(const FunctionDecl *FD);
623 const RetainSummary *getCFCreateGetRuleSummary(const FunctionDecl *FD);
Mike Stump1eb44332009-09-09 15:08:12 +0000624
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000625 const RetainSummary *getPersistentSummary(ArgEffects AE, RetEffect RetEff,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000626 ArgEffect ReceiverEff = DoNothing,
627 ArgEffect DefaultEff = MayEscape);
Ted Kremenek706522f2008-10-29 04:07:07 +0000628
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000629 const RetainSummary *getPersistentSummary(RetEffect RE,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000630 ArgEffect ReceiverEff = DoNothing,
631 ArgEffect DefaultEff = MayEscape) {
Ted Kremenek1bffd742008-05-06 15:44:25 +0000632 return getPersistentSummary(getArgEffects(), RE, ReceiverEff, DefaultEff);
Ted Kremenek9c32d082008-05-06 00:30:21 +0000633 }
Mike Stump1eb44332009-09-09 15:08:12 +0000634
Ted Kremenek93edbc52011-10-05 23:54:29 +0000635 const RetainSummary *getPersistentStopSummary() {
Ted Kremenek432af592008-05-06 18:11:36 +0000636 if (StopSummary)
637 return StopSummary;
Mike Stump1eb44332009-09-09 15:08:12 +0000638
Ted Kremenek432af592008-05-06 18:11:36 +0000639 StopSummary = getPersistentSummary(RetEffect::MakeNoRet(),
640 StopTracking, StopTracking);
Ted Kremenek706522f2008-10-29 04:07:07 +0000641
Ted Kremenek432af592008-05-06 18:11:36 +0000642 return StopSummary;
Mike Stump1eb44332009-09-09 15:08:12 +0000643 }
Ted Kremenekb3095252008-05-06 04:20:12 +0000644
Ted Kremenek1f180c32008-06-23 22:21:20 +0000645 void InitializeClassMethodSummaries();
646 void InitializeMethodSummaries();
Ted Kremenek896cd9d2008-10-23 01:56:15 +0000647private:
Ted Kremenek93edbc52011-10-05 23:54:29 +0000648 void addNSObjectClsMethSummary(Selector S, const RetainSummary *Summ) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000649 ObjCClassMethodSummaries[S] = Summ;
650 }
Mike Stump1eb44332009-09-09 15:08:12 +0000651
Ted Kremenek93edbc52011-10-05 23:54:29 +0000652 void addNSObjectMethSummary(Selector S, const RetainSummary *Summ) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000653 ObjCMethodSummaries[S] = Summ;
654 }
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +0000655
Ted Kremeneka9797122012-02-18 21:37:48 +0000656 void addClassMethSummary(const char* Cls, const char* name,
657 const RetainSummary *Summ, bool isNullary = true) {
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +0000658 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
Ted Kremeneka9797122012-02-18 21:37:48 +0000659 Selector S = isNullary ? GetNullarySelector(name, Ctx)
660 : GetUnarySelector(name, Ctx);
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +0000661 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
662 }
Mike Stump1eb44332009-09-09 15:08:12 +0000663
Ted Kremenek6c4becb2009-02-25 02:54:57 +0000664 void addInstMethSummary(const char* Cls, const char* nullaryName,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000665 const RetainSummary *Summ) {
Ted Kremenek6c4becb2009-02-25 02:54:57 +0000666 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
667 Selector S = GetNullarySelector(nullaryName, Ctx);
668 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
669 }
Mike Stump1eb44332009-09-09 15:08:12 +0000670
Ted Kremenekde4d5332009-04-24 17:50:11 +0000671 Selector generateSelector(va_list argp) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000672 SmallVector<IdentifierInfo*, 10> II;
Ted Kremenekde4d5332009-04-24 17:50:11 +0000673
Ted Kremenek9e476de2008-08-12 18:30:56 +0000674 while (const char* s = va_arg(argp, const char*))
675 II.push_back(&Ctx.Idents.get(s));
Ted Kremenekde4d5332009-04-24 17:50:11 +0000676
Mike Stump1eb44332009-09-09 15:08:12 +0000677 return Ctx.Selectors.getSelector(II.size(), &II[0]);
Ted Kremenekde4d5332009-04-24 17:50:11 +0000678 }
Mike Stump1eb44332009-09-09 15:08:12 +0000679
Ted Kremenekde4d5332009-04-24 17:50:11 +0000680 void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy& Summaries,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000681 const RetainSummary * Summ, va_list argp) {
Ted Kremenekde4d5332009-04-24 17:50:11 +0000682 Selector S = generateSelector(argp);
683 Summaries[ObjCSummaryKey(ClsII, S)] = Summ;
Ted Kremenek70a733e2008-07-18 17:24:20 +0000684 }
Mike Stump1eb44332009-09-09 15:08:12 +0000685
Ted Kremenek93edbc52011-10-05 23:54:29 +0000686 void addInstMethSummary(const char* Cls, const RetainSummary * Summ, ...) {
Ted Kremenekaf9dc272008-08-12 18:48:50 +0000687 va_list argp;
688 va_start(argp, Summ);
Ted Kremenekde4d5332009-04-24 17:50:11 +0000689 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Mike Stump1eb44332009-09-09 15:08:12 +0000690 va_end(argp);
Ted Kremenekaf9dc272008-08-12 18:48:50 +0000691 }
Mike Stump1eb44332009-09-09 15:08:12 +0000692
Ted Kremenek93edbc52011-10-05 23:54:29 +0000693 void addClsMethSummary(const char* Cls, const RetainSummary * Summ, ...) {
Ted Kremenekde4d5332009-04-24 17:50:11 +0000694 va_list argp;
695 va_start(argp, Summ);
696 addMethodSummary(&Ctx.Idents.get(Cls),ObjCClassMethodSummaries, Summ, argp);
697 va_end(argp);
698 }
Mike Stump1eb44332009-09-09 15:08:12 +0000699
Ted Kremenek93edbc52011-10-05 23:54:29 +0000700 void addClsMethSummary(IdentifierInfo *II, const RetainSummary * Summ, ...) {
Ted Kremenekde4d5332009-04-24 17:50:11 +0000701 va_list argp;
702 va_start(argp, Summ);
703 addMethodSummary(II, ObjCClassMethodSummaries, Summ, argp);
704 va_end(argp);
705 }
706
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000707public:
Mike Stump1eb44332009-09-09 15:08:12 +0000708
Ted Kremenek9c378f72011-08-12 23:37:29 +0000709 RetainSummaryManager(ASTContext &ctx, bool gcenabled, bool usesARC)
Ted Kremenek179064e2008-07-01 17:21:27 +0000710 : Ctx(ctx),
John McCallf85e1932011-06-15 23:02:42 +0000711 GCEnabled(gcenabled),
712 ARCEnabled(usesARC),
713 AF(BPAlloc), ScratchArgs(AF.getEmptyMap()),
714 ObjCAllocRetE(gcenabled
715 ? RetEffect::MakeGCNotOwned()
716 : (usesARC ? RetEffect::MakeARCNotOwned()
717 : RetEffect::MakeOwned(RetEffect::ObjC, true))),
718 ObjCInitRetE(gcenabled
719 ? RetEffect::MakeGCNotOwned()
720 : (usesARC ? RetEffect::MakeARCNotOwned()
721 : RetEffect::MakeOwnedWhenTrackedReceiver())),
Ted Kremenek3baf6722010-11-24 00:54:37 +0000722 DefaultSummary(AF.getEmptyMap() /* per-argument effects (none) */,
Ted Kremenek7faca822009-05-04 04:57:00 +0000723 RetEffect::MakeNoRet() /* return effect */,
Ted Kremenekebd5a2d2009-05-11 18:30:24 +0000724 MayEscape, /* default argument effect */
725 DoNothing /* receiver effect */),
Ted Kremenekb77449c2009-05-03 05:20:50 +0000726 StopSummary(0) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000727
728 InitializeClassMethodSummaries();
729 InitializeMethodSummaries();
730 }
Mike Stump1eb44332009-09-09 15:08:12 +0000731
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000732 const RetainSummary *getSummary(const FunctionDecl *FD);
Mike Stump1eb44332009-09-09 15:08:12 +0000733
Ted Kremenek93edbc52011-10-05 23:54:29 +0000734 const RetainSummary *getInstanceMethodSummary(const ObjCMessage &msg,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000735 ProgramStateRef state,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000736 const LocationContext *LC);
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000737
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000738 const RetainSummary *getInstanceMethodSummary(const ObjCMessage &msg,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000739 const ObjCInterfaceDecl *ID) {
Argyrios Kyrtzidis432424d2011-01-25 00:03:53 +0000740 return getInstanceMethodSummary(msg.getSelector(), 0,
741 ID, msg.getMethodDecl(), msg.getType(Ctx));
Ted Kremenek8711c032009-04-29 05:04:30 +0000742 }
Mike Stump1eb44332009-09-09 15:08:12 +0000743
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000744 const RetainSummary *getInstanceMethodSummary(Selector S,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000745 IdentifierInfo *ClsName,
746 const ObjCInterfaceDecl *ID,
747 const ObjCMethodDecl *MD,
748 QualType RetTy);
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +0000749
Ted Kremenek93edbc52011-10-05 23:54:29 +0000750 const RetainSummary *getClassMethodSummary(Selector S,
751 IdentifierInfo *ClsName,
752 const ObjCInterfaceDecl *ID,
753 const ObjCMethodDecl *MD,
754 QualType RetTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000755
Ted Kremenek93edbc52011-10-05 23:54:29 +0000756 const RetainSummary *getClassMethodSummary(const ObjCMessage &msg) {
Argyrios Kyrtzidis432424d2011-01-25 00:03:53 +0000757 const ObjCInterfaceDecl *Class = 0;
758 if (!msg.isInstanceMessage())
759 Class = msg.getReceiverInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +0000760
Argyrios Kyrtzidis432424d2011-01-25 00:03:53 +0000761 return getClassMethodSummary(msg.getSelector(),
Douglas Gregor04badcf2010-04-21 00:45:42 +0000762 Class? Class->getIdentifier() : 0,
763 Class,
Argyrios Kyrtzidis432424d2011-01-25 00:03:53 +0000764 msg.getMethodDecl(), msg.getType(Ctx));
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +0000765 }
Ted Kremenek552333c2009-04-29 17:17:48 +0000766
767 /// getMethodSummary - This version of getMethodSummary is used to query
768 /// the summary for the current method being analyzed.
Ted Kremenek93edbc52011-10-05 23:54:29 +0000769 const RetainSummary *getMethodSummary(const ObjCMethodDecl *MD) {
Ted Kremeneka8833552009-04-29 23:03:22 +0000770 // FIXME: Eventually this should be unneeded.
Ted Kremeneka8833552009-04-29 23:03:22 +0000771 const ObjCInterfaceDecl *ID = MD->getClassInterface();
Ted Kremenek70a65762009-04-30 05:41:14 +0000772 Selector S = MD->getSelector();
Ted Kremenek552333c2009-04-29 17:17:48 +0000773 IdentifierInfo *ClsName = ID->getIdentifier();
774 QualType ResultTy = MD->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +0000775
Ted Kremenek552333c2009-04-29 17:17:48 +0000776 if (MD->isInstanceMethod())
777 return getInstanceMethodSummary(S, ClsName, ID, MD, ResultTy);
778 else
779 return getClassMethodSummary(S, ClsName, ID, MD, ResultTy);
780 }
Mike Stump1eb44332009-09-09 15:08:12 +0000781
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000782 const RetainSummary *getCommonMethodSummary(const ObjCMethodDecl *MD,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000783 Selector S, QualType RetTy);
Ted Kremeneka8833552009-04-29 23:03:22 +0000784
Ted Kremenek93edbc52011-10-05 23:54:29 +0000785 void updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenek4dd8fb42009-05-09 02:58:13 +0000786 const ObjCMethodDecl *MD);
787
Ted Kremenek93edbc52011-10-05 23:54:29 +0000788 void updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenek4dd8fb42009-05-09 02:58:13 +0000789 const FunctionDecl *FD);
790
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000791 bool isGCEnabled() const { return GCEnabled; }
Mike Stump1eb44332009-09-09 15:08:12 +0000792
John McCallf85e1932011-06-15 23:02:42 +0000793 bool isARCEnabled() const { return ARCEnabled; }
794
795 bool isARCorGCEnabled() const { return GCEnabled || ARCEnabled; }
796
Ted Kremenek93edbc52011-10-05 23:54:29 +0000797 const RetainSummary *copySummary(const RetainSummary *OldSumm) {
798 RetainSummary *Summ = (RetainSummary *) BPAlloc.Allocate<RetainSummary>();
Ted Kremenek885c27b2009-05-04 05:31:22 +0000799 new (Summ) RetainSummary(*OldSumm);
800 return Summ;
Mike Stump1eb44332009-09-09 15:08:12 +0000801 }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000802};
Mike Stump1eb44332009-09-09 15:08:12 +0000803
Jordy Rose0fe62f82011-08-24 09:02:37 +0000804// Used to avoid allocating long-term (BPAlloc'd) memory for default retain
805// summaries. If a function or method looks like it has a default summary, but
806// it has annotations, the annotations are added to the stack-based template
807// and then copied into managed memory.
808class RetainSummaryTemplate {
809 RetainSummaryManager &Manager;
Ted Kremenek93edbc52011-10-05 23:54:29 +0000810 const RetainSummary *&RealSummary;
Jordy Rose0fe62f82011-08-24 09:02:37 +0000811 RetainSummary ScratchSummary;
812 bool Accessed;
813public:
Jordy Rosee921b1a2012-03-17 19:53:04 +0000814 RetainSummaryTemplate(const RetainSummary *&real, const RetainSummary &base,
815 RetainSummaryManager &mgr)
816 : Manager(mgr), RealSummary(real), ScratchSummary(real ? *real : base),
Ted Kremenek93edbc52011-10-05 23:54:29 +0000817 Accessed(false) {}
Jordy Rose0fe62f82011-08-24 09:02:37 +0000818
819 ~RetainSummaryTemplate() {
Ted Kremenek93edbc52011-10-05 23:54:29 +0000820 if (Accessed)
Jordy Rose0fe62f82011-08-24 09:02:37 +0000821 RealSummary = Manager.copySummary(&ScratchSummary);
822 }
823
824 RetainSummary &operator*() {
825 Accessed = true;
Ted Kremenek93edbc52011-10-05 23:54:29 +0000826 return ScratchSummary;
Jordy Rose0fe62f82011-08-24 09:02:37 +0000827 }
828
829 RetainSummary *operator->() {
830 Accessed = true;
Ted Kremenek93edbc52011-10-05 23:54:29 +0000831 return &ScratchSummary;
Jordy Rose0fe62f82011-08-24 09:02:37 +0000832 }
833};
834
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000835} // end anonymous namespace
836
837//===----------------------------------------------------------------------===//
838// Implementation of checker data structures.
839//===----------------------------------------------------------------------===//
840
Ted Kremenekb77449c2009-05-03 05:20:50 +0000841ArgEffects RetainSummaryManager::getArgEffects() {
842 ArgEffects AE = ScratchArgs;
Ted Kremenek3baf6722010-11-24 00:54:37 +0000843 ScratchArgs = AF.getEmptyMap();
Ted Kremenekb77449c2009-05-03 05:20:50 +0000844 return AE;
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000845}
846
Ted Kremenek93edbc52011-10-05 23:54:29 +0000847const RetainSummary *
Ted Kremenekb77449c2009-05-03 05:20:50 +0000848RetainSummaryManager::getPersistentSummary(ArgEffects AE, RetEffect RetEff,
Ted Kremenek1bffd742008-05-06 15:44:25 +0000849 ArgEffect ReceiverEff,
Jordy Rosee62e87b2011-08-20 20:55:40 +0000850 ArgEffect DefaultEff) {
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000851 // Create the summary and return it.
Ted Kremenek93edbc52011-10-05 23:54:29 +0000852 RetainSummary *Summ = (RetainSummary *) BPAlloc.Allocate<RetainSummary>();
Jordy Rosee62e87b2011-08-20 20:55:40 +0000853 new (Summ) RetainSummary(AE, RetEff, DefaultEff, ReceiverEff);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000854 return Summ;
855}
856
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000857//===----------------------------------------------------------------------===//
858// Summary creation for functions (largely uses of Core Foundation).
859//===----------------------------------------------------------------------===//
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000860
Ted Kremenek9c378f72011-08-12 23:37:29 +0000861static bool isRetain(const FunctionDecl *FD, StringRef FName) {
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000862 return FName.endswith("Retain");
Ted Kremenek12619382009-01-12 21:45:02 +0000863}
864
Ted Kremenek9c378f72011-08-12 23:37:29 +0000865static bool isRelease(const FunctionDecl *FD, StringRef FName) {
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000866 return FName.endswith("Release");
Ted Kremenek12619382009-01-12 21:45:02 +0000867}
868
Jordy Rose76c506f2011-08-21 21:58:18 +0000869static bool isMakeCollectable(const FunctionDecl *FD, StringRef FName) {
870 // FIXME: Remove FunctionDecl parameter.
871 // FIXME: Is it really okay if MakeCollectable isn't a suffix?
872 return FName.find("MakeCollectable") != StringRef::npos;
873}
874
Ted Kremenek93edbc52011-10-05 23:54:29 +0000875const RetainSummary * RetainSummaryManager::getSummary(const FunctionDecl *FD) {
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000876 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000877 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000878 if (I != FuncSummaries.end())
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000879 return I->second;
880
Ted Kremeneke401a0c2009-05-04 15:34:07 +0000881 // No summary? Generate one.
Ted Kremenek93edbc52011-10-05 23:54:29 +0000882 const RetainSummary *S = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000883
Ted Kremenek37d785b2008-07-15 16:50:12 +0000884 do {
Ted Kremenek12619382009-01-12 21:45:02 +0000885 // We generate "stop" summaries for implicitly defined functions.
886 if (FD->isImplicit()) {
887 S = getPersistentStopSummary();
888 break;
Ted Kremenek37d785b2008-07-15 16:50:12 +0000889 }
Ted Kremenek9ca28512011-05-02 21:21:42 +0000890 // For C++ methods, generate an implicit "stop" summary as well. We
891 // can relax this once we have a clear policy for C++ methods and
892 // ownership attributes.
893 if (isa<CXXMethodDecl>(FD)) {
894 S = getPersistentStopSummary();
895 break;
896 }
Mike Stump1eb44332009-09-09 15:08:12 +0000897
John McCall183700f2009-09-21 23:43:11 +0000898 // [PR 3337] Use 'getAs<FunctionType>' to strip away any typedefs on the
Ted Kremenek99890652009-01-16 18:40:33 +0000899 // function's type.
John McCall183700f2009-09-21 23:43:11 +0000900 const FunctionType* FT = FD->getType()->getAs<FunctionType>();
Ted Kremenek48c6d182009-12-16 06:06:43 +0000901 const IdentifierInfo *II = FD->getIdentifier();
902 if (!II)
903 break;
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000904
905 StringRef FName = II->getName();
Mike Stump1eb44332009-09-09 15:08:12 +0000906
Ted Kremenekbf0a4dd2009-03-05 22:11:14 +0000907 // Strip away preceding '_'. Doing this here will effect all the checks
908 // down below.
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000909 FName = FName.substr(FName.find_first_not_of('_'));
Mike Stump1eb44332009-09-09 15:08:12 +0000910
Ted Kremenek12619382009-01-12 21:45:02 +0000911 // Inspect the result type.
912 QualType RetTy = FT->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +0000913
Ted Kremenek12619382009-01-12 21:45:02 +0000914 // FIXME: This should all be refactored into a chain of "summary lookup"
915 // filters.
Ted Kremenek008636a2009-10-14 00:27:24 +0000916 assert(ScratchArgs.isEmpty());
Ted Kremenek39d88b02009-06-15 20:36:07 +0000917
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000918 if (FName == "pthread_create") {
919 // Part of: <rdar://problem/7299394>. This will be addressed
920 // better with IPA.
921 S = getPersistentStopSummary();
922 } else if (FName == "NSMakeCollectable") {
923 // Handle: id NSMakeCollectable(CFTypeRef)
924 S = (RetTy->isObjCIdType())
925 ? getUnarySummary(FT, cfmakecollectable)
926 : getPersistentStopSummary();
927 } else if (FName == "IOBSDNameMatching" ||
928 FName == "IOServiceMatching" ||
929 FName == "IOServiceNameMatching" ||
930 FName == "IORegistryEntryIDMatching" ||
931 FName == "IOOpenFirmwarePathMatching") {
932 // Part of <rdar://problem/6961230>. (IOKit)
933 // This should be addressed using a API table.
934 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
935 DoNothing, DoNothing);
936 } else if (FName == "IOServiceGetMatchingService" ||
937 FName == "IOServiceGetMatchingServices") {
938 // FIXES: <rdar://problem/6326900>
939 // This should be addressed using a API table. This strcmp is also
940 // a little gross, but there is no need to super optimize here.
Ted Kremenek3baf6722010-11-24 00:54:37 +0000941 ScratchArgs = AF.add(ScratchArgs, 1, DecRef);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000942 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
943 } else if (FName == "IOServiceAddNotification" ||
944 FName == "IOServiceAddMatchingNotification") {
945 // Part of <rdar://problem/6961230>. (IOKit)
946 // This should be addressed using a API table.
Ted Kremenek3baf6722010-11-24 00:54:37 +0000947 ScratchArgs = AF.add(ScratchArgs, 2, DecRef);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000948 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
949 } else if (FName == "CVPixelBufferCreateWithBytes") {
950 // FIXES: <rdar://problem/7283567>
951 // Eventually this can be improved by recognizing that the pixel
952 // buffer passed to CVPixelBufferCreateWithBytes is released via
953 // a callback and doing full IPA to make sure this is done correctly.
954 // FIXME: This function has an out parameter that returns an
955 // allocated object.
Ted Kremenek3baf6722010-11-24 00:54:37 +0000956 ScratchArgs = AF.add(ScratchArgs, 7, StopTracking);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000957 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
958 } else if (FName == "CGBitmapContextCreateWithData") {
959 // FIXES: <rdar://problem/7358899>
960 // Eventually this can be improved by recognizing that 'releaseInfo'
961 // passed to CGBitmapContextCreateWithData is released via
962 // a callback and doing full IPA to make sure this is done correctly.
Ted Kremenek3baf6722010-11-24 00:54:37 +0000963 ScratchArgs = AF.add(ScratchArgs, 8, StopTracking);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000964 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
965 DoNothing, DoNothing);
966 } else if (FName == "CVPixelBufferCreateWithPlanarBytes") {
967 // FIXES: <rdar://problem/7283567>
968 // Eventually this can be improved by recognizing that the pixel
969 // buffer passed to CVPixelBufferCreateWithPlanarBytes is released
970 // via a callback and doing full IPA to make sure this is done
971 // correctly.
Ted Kremenek3baf6722010-11-24 00:54:37 +0000972 ScratchArgs = AF.add(ScratchArgs, 12, StopTracking);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000973 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenekb04cb592009-06-11 18:17:24 +0000974 }
Mike Stump1eb44332009-09-09 15:08:12 +0000975
Ted Kremenekb04cb592009-06-11 18:17:24 +0000976 // Did we get a summary?
977 if (S)
978 break;
Ted Kremenek61991902009-03-17 22:43:44 +0000979
980 // Enable this code once the semantics of NSDeallocateObject are resolved
981 // for GC. <rdar://problem/6619988>
982#if 0
983 // Handle: NSDeallocateObject(id anObject);
984 // This method does allow 'nil' (although we don't check it now).
Mike Stump1eb44332009-09-09 15:08:12 +0000985 if (strcmp(FName, "NSDeallocateObject") == 0) {
Ted Kremenek61991902009-03-17 22:43:44 +0000986 return RetTy == Ctx.VoidTy
987 ? getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, Dealloc)
988 : getPersistentStopSummary();
989 }
990#endif
Ted Kremenek12619382009-01-12 21:45:02 +0000991
992 if (RetTy->isPointerType()) {
993 // For CoreFoundation ('CF') types.
Ted Kremenek78acdbf2010-01-27 18:00:17 +0000994 if (cocoa::isRefType(RetTy, "CF", FName)) {
Ted Kremenek12619382009-01-12 21:45:02 +0000995 if (isRetain(FD, FName))
996 S = getUnarySummary(FT, cfretain);
Jordy Rose76c506f2011-08-21 21:58:18 +0000997 else if (isMakeCollectable(FD, FName))
Ted Kremenek12619382009-01-12 21:45:02 +0000998 S = getUnarySummary(FT, cfmakecollectable);
Mike Stump1eb44332009-09-09 15:08:12 +0000999 else
John McCall7df2ff42011-10-01 00:48:56 +00001000 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek12619382009-01-12 21:45:02 +00001001
1002 break;
1003 }
1004
1005 // For CoreGraphics ('CG') types.
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001006 if (cocoa::isRefType(RetTy, "CG", FName)) {
Ted Kremenek12619382009-01-12 21:45:02 +00001007 if (isRetain(FD, FName))
1008 S = getUnarySummary(FT, cfretain);
1009 else
John McCall7df2ff42011-10-01 00:48:56 +00001010 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek12619382009-01-12 21:45:02 +00001011
1012 break;
1013 }
1014
1015 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001016 if (cocoa::isRefType(RetTy, "DADisk") ||
1017 cocoa::isRefType(RetTy, "DADissenter") ||
1018 cocoa::isRefType(RetTy, "DASessionRef")) {
John McCall7df2ff42011-10-01 00:48:56 +00001019 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek12619382009-01-12 21:45:02 +00001020 break;
1021 }
Mike Stump1eb44332009-09-09 15:08:12 +00001022
Ted Kremenek12619382009-01-12 21:45:02 +00001023 break;
1024 }
1025
1026 // Check for release functions, the only kind of functions that we care
1027 // about that don't return a pointer type.
1028 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
Ted Kremeneke7d03122010-02-08 16:45:01 +00001029 // Test for 'CGCF'.
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001030 FName = FName.substr(FName.startswith("CGCF") ? 4 : 2);
Ted Kremeneke7d03122010-02-08 16:45:01 +00001031
Ted Kremenekbf0a4dd2009-03-05 22:11:14 +00001032 if (isRelease(FD, FName))
Ted Kremenek12619382009-01-12 21:45:02 +00001033 S = getUnarySummary(FT, cfrelease);
1034 else {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001035 assert (ScratchArgs.isEmpty());
Ted Kremenek68189282009-01-29 22:45:13 +00001036 // Remaining CoreFoundation and CoreGraphics functions.
1037 // We use to assume that they all strictly followed the ownership idiom
1038 // and that ownership cannot be transferred. While this is technically
1039 // correct, many methods allow a tracked object to escape. For example:
1040 //
Mike Stump1eb44332009-09-09 15:08:12 +00001041 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
Ted Kremenek68189282009-01-29 22:45:13 +00001042 // CFDictionaryAddValue(y, key, x);
Mike Stump1eb44332009-09-09 15:08:12 +00001043 // CFRelease(x);
Ted Kremenek68189282009-01-29 22:45:13 +00001044 // ... it is okay to use 'x' since 'y' has a reference to it
1045 //
1046 // We handle this and similar cases with the follow heuristic. If the
Ted Kremenekc4843812009-08-20 00:57:22 +00001047 // function name contains "InsertValue", "SetValue", "AddValue",
1048 // "AppendValue", or "SetAttribute", then we assume that arguments may
1049 // "escape." This means that something else holds on to the object,
1050 // allowing it be used even after its local retain count drops to 0.
Benjamin Kramere45c1492010-01-11 19:46:28 +00001051 ArgEffect E = (StrInStrNoCase(FName, "InsertValue") != StringRef::npos||
1052 StrInStrNoCase(FName, "AddValue") != StringRef::npos ||
1053 StrInStrNoCase(FName, "SetValue") != StringRef::npos ||
1054 StrInStrNoCase(FName, "AppendValue") != StringRef::npos||
Benjamin Kramerc027e542010-01-11 20:15:06 +00001055 StrInStrNoCase(FName, "SetAttribute") != StringRef::npos)
Ted Kremenek68189282009-01-29 22:45:13 +00001056 ? MayEscape : DoNothing;
Mike Stump1eb44332009-09-09 15:08:12 +00001057
Ted Kremenek68189282009-01-29 22:45:13 +00001058 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek12619382009-01-12 21:45:02 +00001059 }
1060 }
Ted Kremenek37d785b2008-07-15 16:50:12 +00001061 }
1062 while (0);
Mike Stump1eb44332009-09-09 15:08:12 +00001063
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001064 // Annotations override defaults.
Jordy Rose4df54fe2011-08-23 04:27:15 +00001065 updateSummaryFromAnnotations(S, FD);
Mike Stump1eb44332009-09-09 15:08:12 +00001066
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001067 FuncSummaries[FD] = S;
Mike Stump1eb44332009-09-09 15:08:12 +00001068 return S;
Ted Kremenek2fff37e2008-03-06 00:08:09 +00001069}
1070
Ted Kremenek93edbc52011-10-05 23:54:29 +00001071const RetainSummary *
John McCall7df2ff42011-10-01 00:48:56 +00001072RetainSummaryManager::getCFCreateGetRuleSummary(const FunctionDecl *FD) {
1073 if (coreFoundation::followsCreateRule(FD))
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001074 return getCFSummaryCreateRule(FD);
Mike Stump1eb44332009-09-09 15:08:12 +00001075
Ted Kremenekd368d712011-05-25 06:19:45 +00001076 return getCFSummaryGetRule(FD);
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001077}
1078
Ted Kremenek93edbc52011-10-05 23:54:29 +00001079const RetainSummary *
Ted Kremenek6ad315a2009-02-23 16:51:39 +00001080RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1081 UnaryFuncKind func) {
1082
Ted Kremenek12619382009-01-12 21:45:02 +00001083 // Sanity check that this is *really* a unary function. This can
1084 // happen if people do weird things.
Douglas Gregor72564e72009-02-26 23:50:07 +00001085 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
Ted Kremenek12619382009-01-12 21:45:02 +00001086 if (!FTP || FTP->getNumArgs() != 1)
1087 return getPersistentStopSummary();
Mike Stump1eb44332009-09-09 15:08:12 +00001088
Ted Kremenekb77449c2009-05-03 05:20:50 +00001089 assert (ScratchArgs.isEmpty());
Mike Stump1eb44332009-09-09 15:08:12 +00001090
Jordy Rose76c506f2011-08-21 21:58:18 +00001091 ArgEffect Effect;
Ted Kremenek377e2302008-04-29 05:33:51 +00001092 switch (func) {
Jordy Rose76c506f2011-08-21 21:58:18 +00001093 case cfretain: Effect = IncRef; break;
1094 case cfrelease: Effect = DecRef; break;
1095 case cfmakecollectable: Effect = MakeCollectable; break;
Ted Kremenek940b1d82008-04-10 23:44:06 +00001096 }
Jordy Rose76c506f2011-08-21 21:58:18 +00001097
1098 ScratchArgs = AF.add(ScratchArgs, 0, Effect);
1099 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001100}
1101
Ted Kremenek93edbc52011-10-05 23:54:29 +00001102const RetainSummary *
Ted Kremenek9c378f72011-08-12 23:37:29 +00001103RetainSummaryManager::getCFSummaryCreateRule(const FunctionDecl *FD) {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001104 assert (ScratchArgs.isEmpty());
Mike Stump1eb44332009-09-09 15:08:12 +00001105
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001106 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001107}
1108
Ted Kremenek93edbc52011-10-05 23:54:29 +00001109const RetainSummary *
Ted Kremenek9c378f72011-08-12 23:37:29 +00001110RetainSummaryManager::getCFSummaryGetRule(const FunctionDecl *FD) {
Mike Stump1eb44332009-09-09 15:08:12 +00001111 assert (ScratchArgs.isEmpty());
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001112 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1113 DoNothing, DoNothing);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001114}
1115
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001116//===----------------------------------------------------------------------===//
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001117// Summary creation for Selectors.
1118//===----------------------------------------------------------------------===//
1119
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001120void
Ted Kremenek93edbc52011-10-05 23:54:29 +00001121RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001122 const FunctionDecl *FD) {
1123 if (!FD)
1124 return;
1125
Jordy Rose0fe62f82011-08-24 09:02:37 +00001126 RetainSummaryTemplate Template(Summ, DefaultSummary, *this);
Jordy Rose4df54fe2011-08-23 04:27:15 +00001127
Ted Kremenek11fe1752011-01-27 18:43:03 +00001128 // Effects on the parameters.
1129 unsigned parm_idx = 0;
1130 for (FunctionDecl::param_const_iterator pi = FD->param_begin(),
John McCall98b8f162011-04-06 09:02:12 +00001131 pe = FD->param_end(); pi != pe; ++pi, ++parm_idx) {
Ted Kremenek11fe1752011-01-27 18:43:03 +00001132 const ParmVarDecl *pd = *pi;
1133 if (pd->getAttr<NSConsumedAttr>()) {
Jordy Rose4df54fe2011-08-23 04:27:15 +00001134 if (!GCEnabled) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001135 Template->addArg(AF, parm_idx, DecRef);
Jordy Rose4df54fe2011-08-23 04:27:15 +00001136 }
1137 } else if (pd->getAttr<CFConsumedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001138 Template->addArg(AF, parm_idx, DecRef);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001139 }
1140 }
1141
Ted Kremenekb04cb592009-06-11 18:17:24 +00001142 QualType RetTy = FD->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00001143
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001144 // Determine if there is a special return effect for this method.
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001145 if (cocoa::isCocoaObjectRef(RetTy)) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001146 if (FD->getAttr<NSReturnsRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001147 Template->setRetEffect(ObjCAllocRetE);
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001148 }
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001149 else if (FD->getAttr<CFReturnsRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001150 Template->setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenekb04cb592009-06-11 18:17:24 +00001151 }
Ted Kremenek60411112010-02-18 00:06:12 +00001152 else if (FD->getAttr<NSReturnsNotRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001153 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::ObjC));
Ted Kremenek60411112010-02-18 00:06:12 +00001154 }
1155 else if (FD->getAttr<CFReturnsNotRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001156 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::CF));
Jordy Rose4df54fe2011-08-23 04:27:15 +00001157 }
1158 } else if (RetTy->getAs<PointerType>()) {
1159 if (FD->getAttr<CFReturnsRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001160 Template->setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
Jordy Rose4df54fe2011-08-23 04:27:15 +00001161 }
1162 else if (FD->getAttr<CFReturnsNotRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001163 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::CF));
Ted Kremenek60411112010-02-18 00:06:12 +00001164 }
Ted Kremenekb04cb592009-06-11 18:17:24 +00001165 }
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001166}
1167
1168void
Ted Kremenek93edbc52011-10-05 23:54:29 +00001169RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
1170 const ObjCMethodDecl *MD) {
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001171 if (!MD)
1172 return;
1173
Jordy Rose0fe62f82011-08-24 09:02:37 +00001174 RetainSummaryTemplate Template(Summ, DefaultSummary, *this);
Ted Kremenek6d4b76d2009-07-06 18:30:43 +00001175 bool isTrackedLoc = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001176
Ted Kremenek12b94342011-01-27 06:54:14 +00001177 // Effects on the receiver.
1178 if (MD->getAttr<NSConsumesSelfAttr>()) {
Ted Kremenek11fe1752011-01-27 18:43:03 +00001179 if (!GCEnabled)
Jordy Rose0fe62f82011-08-24 09:02:37 +00001180 Template->setReceiverEffect(DecRefMsg);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001181 }
1182
1183 // Effects on the parameters.
1184 unsigned parm_idx = 0;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00001185 for (ObjCMethodDecl::param_const_iterator
1186 pi=MD->param_begin(), pe=MD->param_end();
Ted Kremenek11fe1752011-01-27 18:43:03 +00001187 pi != pe; ++pi, ++parm_idx) {
1188 const ParmVarDecl *pd = *pi;
1189 if (pd->getAttr<NSConsumedAttr>()) {
1190 if (!GCEnabled)
Jordy Rose0fe62f82011-08-24 09:02:37 +00001191 Template->addArg(AF, parm_idx, DecRef);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001192 }
1193 else if(pd->getAttr<CFConsumedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001194 Template->addArg(AF, parm_idx, DecRef);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001195 }
Ted Kremenek12b94342011-01-27 06:54:14 +00001196 }
1197
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001198 // Determine if there is a special return effect for this method.
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001199 if (cocoa::isCocoaObjectRef(MD->getResultType())) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001200 if (MD->getAttr<NSReturnsRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001201 Template->setRetEffect(ObjCAllocRetE);
Ted Kremenek6d4b76d2009-07-06 18:30:43 +00001202 return;
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001203 }
Ted Kremenek60411112010-02-18 00:06:12 +00001204 if (MD->getAttr<NSReturnsNotRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001205 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::ObjC));
Ted Kremenek60411112010-02-18 00:06:12 +00001206 return;
1207 }
Mike Stump1eb44332009-09-09 15:08:12 +00001208
Ted Kremenek6d4b76d2009-07-06 18:30:43 +00001209 isTrackedLoc = true;
Jordy Rose0fe62f82011-08-24 09:02:37 +00001210 } else {
Ted Kremenek6217b802009-07-29 21:53:49 +00001211 isTrackedLoc = MD->getResultType()->getAs<PointerType>() != NULL;
Jordy Rose0fe62f82011-08-24 09:02:37 +00001212 }
Mike Stump1eb44332009-09-09 15:08:12 +00001213
Ted Kremenek60411112010-02-18 00:06:12 +00001214 if (isTrackedLoc) {
1215 if (MD->getAttr<CFReturnsRetainedAttr>())
Jordy Rose0fe62f82011-08-24 09:02:37 +00001216 Template->setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenek60411112010-02-18 00:06:12 +00001217 else if (MD->getAttr<CFReturnsNotRetainedAttr>())
Jordy Rose0fe62f82011-08-24 09:02:37 +00001218 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::CF));
Ted Kremenek60411112010-02-18 00:06:12 +00001219 }
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001220}
1221
Ted Kremenek93edbc52011-10-05 23:54:29 +00001222const RetainSummary *
Ted Kremenek9c378f72011-08-12 23:37:29 +00001223RetainSummaryManager::getCommonMethodSummary(const ObjCMethodDecl *MD,
Ted Kremeneka8833552009-04-29 23:03:22 +00001224 Selector S, QualType RetTy) {
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001225
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +00001226 if (MD) {
Ted Kremenek376d1e72009-04-24 18:00:17 +00001227 // Scan the method decl for 'void*' arguments. These should be treated
1228 // as 'StopTracking' because they are often used with delegates.
1229 // Delegates are a frequent form of false positives with the retain
1230 // count checker.
1231 unsigned i = 0;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00001232 for (ObjCMethodDecl::param_const_iterator I = MD->param_begin(),
Ted Kremenek376d1e72009-04-24 18:00:17 +00001233 E = MD->param_end(); I != E; ++I, ++i)
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00001234 if (const ParmVarDecl *PD = *I) {
Ted Kremenek376d1e72009-04-24 18:00:17 +00001235 QualType Ty = Ctx.getCanonicalType(PD->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001236 if (Ty.getLocalUnqualifiedType() == Ctx.VoidPtrTy)
Ted Kremenek3baf6722010-11-24 00:54:37 +00001237 ScratchArgs = AF.add(ScratchArgs, i, StopTracking);
Ted Kremenek376d1e72009-04-24 18:00:17 +00001238 }
1239 }
Mike Stump1eb44332009-09-09 15:08:12 +00001240
Jordy Rosee921b1a2012-03-17 19:53:04 +00001241 // Any special effects?
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001242 ArgEffect ReceiverEff = DoNothing;
Jordy Rosee921b1a2012-03-17 19:53:04 +00001243 RetEffect ResultEff = RetEffect::MakeNoRet();
1244
1245 // Check the method family, and apply any default annotations.
1246 switch (MD ? MD->getMethodFamily() : S.getMethodFamily()) {
1247 case OMF_None:
1248 case OMF_performSelector:
1249 // Assume all Objective-C methods follow Cocoa Memory Management rules.
1250 // FIXME: Does the non-threaded performSelector family really belong here?
1251 // The selector could be, say, @selector(copy).
1252 if (cocoa::isCocoaObjectRef(RetTy))
1253 ResultEff = RetEffect::MakeNotOwned(RetEffect::ObjC);
1254 else if (coreFoundation::isCFObjectRef(RetTy)) {
1255 // ObjCMethodDecl currently doesn't consider CF objects as valid return
1256 // values for alloc, new, copy, or mutableCopy, so we have to
1257 // double-check with the selector. This is ugly, but there aren't that
1258 // many Objective-C methods that return CF objects, right?
1259 if (MD) {
1260 switch (S.getMethodFamily()) {
1261 case OMF_alloc:
1262 case OMF_new:
1263 case OMF_copy:
1264 case OMF_mutableCopy:
1265 ResultEff = RetEffect::MakeOwned(RetEffect::CF, true);
1266 break;
1267 default:
1268 ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1269 break;
1270 }
1271 } else {
1272 ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1273 }
1274 }
1275 break;
1276 case OMF_init:
1277 ResultEff = ObjCInitRetE;
1278 ReceiverEff = DecRefMsg;
1279 break;
1280 case OMF_alloc:
1281 case OMF_new:
1282 case OMF_copy:
1283 case OMF_mutableCopy:
1284 if (cocoa::isCocoaObjectRef(RetTy))
1285 ResultEff = ObjCAllocRetE;
1286 else if (coreFoundation::isCFObjectRef(RetTy))
1287 ResultEff = RetEffect::MakeOwned(RetEffect::CF, true);
1288 break;
1289 case OMF_autorelease:
1290 ReceiverEff = Autorelease;
1291 break;
1292 case OMF_retain:
1293 ReceiverEff = IncRefMsg;
1294 break;
1295 case OMF_release:
1296 ReceiverEff = DecRefMsg;
1297 break;
1298 case OMF_dealloc:
1299 ReceiverEff = Dealloc;
1300 break;
1301 case OMF_self:
1302 // -self is handled specially by the ExprEngine to propagate the receiver.
1303 break;
1304 case OMF_retainCount:
1305 case OMF_finalize:
1306 // These methods don't return objects.
1307 break;
1308 }
Mike Stump1eb44332009-09-09 15:08:12 +00001309
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001310 // If one of the arguments in the selector has the keyword 'delegate' we
1311 // should stop tracking the reference count for the receiver. This is
1312 // because the reference count is quite possibly handled by a delegate
1313 // method.
1314 if (S.isKeywordSelector()) {
1315 const std::string &str = S.getAsString();
1316 assert(!str.empty());
Benjamin Kramere45c1492010-01-11 19:46:28 +00001317 if (StrInStrNoCase(str, "delegate:") != StringRef::npos)
1318 ReceiverEff = StopTracking;
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001319 }
Mike Stump1eb44332009-09-09 15:08:12 +00001320
Jordy Rosee921b1a2012-03-17 19:53:04 +00001321 if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing &&
1322 ResultEff.getKind() == RetEffect::NoRet)
Ted Kremenek93edbc52011-10-05 23:54:29 +00001323 return getDefaultSummary();
Mike Stump1eb44332009-09-09 15:08:12 +00001324
Jordy Rosee921b1a2012-03-17 19:53:04 +00001325 return getPersistentSummary(ResultEff, ReceiverEff, MayEscape);
Ted Kremenek250b1fa2009-04-23 23:08:22 +00001326}
1327
Ted Kremenek93edbc52011-10-05 23:54:29 +00001328const RetainSummary *
Argyrios Kyrtzidis432424d2011-01-25 00:03:53 +00001329RetainSummaryManager::getInstanceMethodSummary(const ObjCMessage &msg,
Ted Kremenek8bef8232012-01-26 21:29:00 +00001330 ProgramStateRef state,
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001331 const LocationContext *LC) {
1332
1333 // We need the type-information of the tracked receiver object
1334 // Retrieve it from the state.
Argyrios Kyrtzidis432424d2011-01-25 00:03:53 +00001335 const Expr *Receiver = msg.getInstanceReceiver();
Ted Kremenek9c378f72011-08-12 23:37:29 +00001336 const ObjCInterfaceDecl *ID = 0;
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001337
1338 // FIXME: Is this really working as expected? There are cases where
1339 // we just use the 'ID' from the message expression.
Douglas Gregor04badcf2010-04-21 00:45:42 +00001340 SVal receiverV;
1341
Ted Kremenek8f326752010-05-21 21:56:53 +00001342 if (Receiver) {
Ted Kremenek5eca4822012-01-06 22:09:28 +00001343 receiverV = state->getSValAsScalarOrLoc(Receiver, LC);
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00001344
Douglas Gregor04badcf2010-04-21 00:45:42 +00001345 // FIXME: Eventually replace the use of state->get<RefBindings> with
1346 // a generic API for reasoning about the Objective-C types of symbolic
1347 // objects.
1348 if (SymbolRef Sym = receiverV.getAsLocSymbol())
1349 if (const RefVal *T = state->get<RefBindings>(Sym))
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00001350 if (const ObjCObjectPointerType* PT =
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001351 T->getType()->getAs<ObjCObjectPointerType>())
Douglas Gregor04badcf2010-04-21 00:45:42 +00001352 ID = PT->getInterfaceDecl();
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00001353
Douglas Gregor04badcf2010-04-21 00:45:42 +00001354 // FIXME: this is a hack. This may or may not be the actual method
1355 // that is called.
1356 if (!ID) {
1357 if (const ObjCObjectPointerType *PT =
1358 Receiver->getType()->getAs<ObjCObjectPointerType>())
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001359 ID = PT->getInterfaceDecl();
Douglas Gregor04badcf2010-04-21 00:45:42 +00001360 }
1361 } else {
1362 // FIXME: Hack for 'super'.
Argyrios Kyrtzidis432424d2011-01-25 00:03:53 +00001363 ID = msg.getReceiverInterface();
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001364 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001365
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001366 // FIXME: The receiver could be a reference to a class, meaning that
1367 // we should use the class method.
Jordy Rose4df54fe2011-08-23 04:27:15 +00001368 return getInstanceMethodSummary(msg, ID);
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001369}
1370
Ted Kremenek93edbc52011-10-05 23:54:29 +00001371const RetainSummary *
Ted Kremenekce8a41d2009-04-29 17:09:14 +00001372RetainSummaryManager::getInstanceMethodSummary(Selector S,
1373 IdentifierInfo *ClsName,
Ted Kremenek9c378f72011-08-12 23:37:29 +00001374 const ObjCInterfaceDecl *ID,
Ted Kremeneka8833552009-04-29 23:03:22 +00001375 const ObjCMethodDecl *MD,
Ted Kremenekce8a41d2009-04-29 17:09:14 +00001376 QualType RetTy) {
Ted Kremenek1bffd742008-05-06 15:44:25 +00001377
Ted Kremenek8711c032009-04-29 05:04:30 +00001378 // Look up a summary in our summary cache.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001379 const RetainSummary *Summ = ObjCMethodSummaries.find(ID, ClsName, S);
Mike Stump1eb44332009-09-09 15:08:12 +00001380
Ted Kremenek614cc542009-07-21 23:27:57 +00001381 if (!Summ) {
Jordy Rosee921b1a2012-03-17 19:53:04 +00001382 Summ = getCommonMethodSummary(MD, S, RetTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001383
Ted Kremenek614cc542009-07-21 23:27:57 +00001384 // Annotations override defaults.
Jordy Rose4df54fe2011-08-23 04:27:15 +00001385 updateSummaryFromAnnotations(Summ, MD);
Mike Stump1eb44332009-09-09 15:08:12 +00001386
Ted Kremenek614cc542009-07-21 23:27:57 +00001387 // Memoize the summary.
1388 ObjCMethodSummaries[ObjCSummaryKey(ID, ClsName, S)] = Summ;
1389 }
Mike Stump1eb44332009-09-09 15:08:12 +00001390
Ted Kremeneke87450e2009-04-23 19:11:35 +00001391 return Summ;
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001392}
1393
Ted Kremenek93edbc52011-10-05 23:54:29 +00001394const RetainSummary *
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +00001395RetainSummaryManager::getClassMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremeneka8833552009-04-29 23:03:22 +00001396 const ObjCInterfaceDecl *ID,
1397 const ObjCMethodDecl *MD,
1398 QualType RetTy) {
Ted Kremenekde4d5332009-04-24 17:50:11 +00001399
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +00001400 assert(ClsName && "Class name must be specified.");
Ted Kremenek93edbc52011-10-05 23:54:29 +00001401 const RetainSummary *Summ = ObjCClassMethodSummaries.find(ID, ClsName, S);
Mike Stump1eb44332009-09-09 15:08:12 +00001402
Ted Kremenek614cc542009-07-21 23:27:57 +00001403 if (!Summ) {
1404 Summ = getCommonMethodSummary(MD, S, RetTy);
Jordy Rose4df54fe2011-08-23 04:27:15 +00001405
Ted Kremenek614cc542009-07-21 23:27:57 +00001406 // Annotations override defaults.
Jordy Rose4df54fe2011-08-23 04:27:15 +00001407 updateSummaryFromAnnotations(Summ, MD);
1408
Ted Kremenek614cc542009-07-21 23:27:57 +00001409 // Memoize the summary.
1410 ObjCClassMethodSummaries[ObjCSummaryKey(ID, ClsName, S)] = Summ;
1411 }
Mike Stump1eb44332009-09-09 15:08:12 +00001412
Ted Kremeneke87450e2009-04-23 19:11:35 +00001413 return Summ;
Ted Kremenekc8395602008-05-06 21:26:51 +00001414}
1415
Mike Stump1eb44332009-09-09 15:08:12 +00001416void RetainSummaryManager::InitializeClassMethodSummaries() {
Ted Kremenekec315332009-05-07 23:40:42 +00001417 assert(ScratchArgs.isEmpty());
Mike Stump1eb44332009-09-09 15:08:12 +00001418 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek6fe2b7a2009-10-15 22:25:12 +00001419 addClassMethSummary("NSAssertionHandler", "currentHandler",
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001420 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Mike Stump1eb44332009-09-09 15:08:12 +00001421
Ted Kremenek6d348932008-10-21 15:53:15 +00001422 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001423 ScratchArgs = AF.add(ScratchArgs, 0, Autorelease);
Ted Kremenek6fe2b7a2009-10-15 22:25:12 +00001424 addClassMethSummary("NSAutoreleasePool", "addObject",
1425 getPersistentSummary(RetEffect::MakeNoRet(),
1426 DoNothing, Autorelease));
Mike Stump1eb44332009-09-09 15:08:12 +00001427
Ted Kremenekde4d5332009-04-24 17:50:11 +00001428 // Create the summaries for [NSObject performSelector...]. We treat
1429 // these as 'stop tracking' for the arguments because they are often
1430 // used for delegates that can release the object. When we have better
1431 // inter-procedural analysis we can potentially do something better. This
1432 // workaround is to remove false positives.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001433 const RetainSummary *Summ =
Ted Kremenek012614e2011-08-17 21:04:19 +00001434 getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, StopTracking);
Ted Kremenekde4d5332009-04-24 17:50:11 +00001435 IdentifierInfo *NSObjectII = &Ctx.Idents.get("NSObject");
1436 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1437 "afterDelay", NULL);
1438 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1439 "afterDelay", "inModes", NULL);
1440 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1441 "withObject", "waitUntilDone", NULL);
1442 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1443 "withObject", "waitUntilDone", "modes", NULL);
1444 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1445 "withObject", "waitUntilDone", NULL);
1446 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1447 "withObject", "waitUntilDone", "modes", NULL);
1448 addClsMethSummary(NSObjectII, Summ, "performSelectorInBackground",
1449 "withObject", NULL);
Ted Kremenek9c32d082008-05-06 00:30:21 +00001450}
1451
Ted Kremenek1f180c32008-06-23 22:21:20 +00001452void RetainSummaryManager::InitializeMethodSummaries() {
Mike Stump1eb44332009-09-09 15:08:12 +00001453
1454 assert (ScratchArgs.isEmpty());
1455
Ted Kremenekc8395602008-05-06 21:26:51 +00001456 // Create the "init" selector. It just acts as a pass-through for the
1457 // receiver.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001458 const RetainSummary *InitSumm = getPersistentSummary(ObjCInitRetE, DecRefMsg);
Ted Kremenekac02f202009-08-20 05:13:36 +00001459 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
1460
1461 // awakeAfterUsingCoder: behaves basically like an 'init' method. It
1462 // claims the receiver and returns a retained object.
1463 addNSObjectMethSummary(GetUnarySelector("awakeAfterUsingCoder", Ctx),
1464 InitSumm);
Mike Stump1eb44332009-09-09 15:08:12 +00001465
Ted Kremenekc8395602008-05-06 21:26:51 +00001466 // The next methods are allocators.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001467 const RetainSummary *AllocSumm = getPersistentSummary(ObjCAllocRetE);
1468 const RetainSummary *CFAllocSumm =
Ted Kremeneka834fb42009-08-28 19:52:12 +00001469 getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Mike Stump1eb44332009-09-09 15:08:12 +00001470
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001471 // Create the "retain" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001472 RetEffect NoRet = RetEffect::MakeNoRet();
Ted Kremenek93edbc52011-10-05 23:54:29 +00001473 const RetainSummary *Summ = getPersistentSummary(NoRet, IncRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001474 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001475
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001476 // Create the "release" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001477 Summ = getPersistentSummary(NoRet, DecRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001478 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001479
Ted Kremenek299e8152008-05-07 21:17:39 +00001480 // Create the "drain" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001481 Summ = getPersistentSummary(NoRet, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek553cf182008-06-25 21:21:56 +00001482 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001483
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001484 // Create the -dealloc summary.
Jordy Rose500abad2011-08-21 19:41:36 +00001485 Summ = getPersistentSummary(NoRet, Dealloc);
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001486 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001487
1488 // Create the "autorelease" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001489 Summ = getPersistentSummary(NoRet, Autorelease);
Ted Kremenek553cf182008-06-25 21:21:56 +00001490 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001491
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00001492 // Specially handle NSAutoreleasePool.
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001493 addInstMethSummary("NSAutoreleasePool", "init",
Jordy Rose500abad2011-08-21 19:41:36 +00001494 getPersistentSummary(NoRet, NewAutoreleasePool));
Mike Stump1eb44332009-09-09 15:08:12 +00001495
1496 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremenek89e202d2009-02-23 02:51:29 +00001497 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1498 // self-own themselves. However, they only do this once they are displayed.
1499 // Thus, we need to track an NSWindow's display status.
1500 // This is tracked in <rdar://problem/6062711>.
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +00001501 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001502 const RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenek78a35a32009-05-12 20:06:54 +00001503 StopTracking,
1504 StopTracking);
Mike Stump1eb44332009-09-09 15:08:12 +00001505
Ted Kremenek99d02692009-04-03 19:02:51 +00001506 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1507
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +00001508#if 0
Ted Kremenek78a35a32009-05-12 20:06:54 +00001509 addInstMethSummary("NSWindow", NoTrackYet, "initWithContentRect",
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001510 "styleMask", "backing", "defer", NULL);
Mike Stump1eb44332009-09-09 15:08:12 +00001511
Ted Kremenek78a35a32009-05-12 20:06:54 +00001512 addInstMethSummary("NSWindow", NoTrackYet, "initWithContentRect",
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001513 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +00001514#endif
Mike Stump1eb44332009-09-09 15:08:12 +00001515
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001516 // For NSPanel (which subclasses NSWindow), allocated objects are not
1517 // self-owned.
Ted Kremenek99d02692009-04-03 19:02:51 +00001518 // FIXME: For now we don't track NSPanels. object for the same reason
1519 // as for NSWindow objects.
1520 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
Mike Stump1eb44332009-09-09 15:08:12 +00001521
Ted Kremenek78a35a32009-05-12 20:06:54 +00001522#if 0
1523 addInstMethSummary("NSPanel", NoTrackYet, "initWithContentRect",
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001524 "styleMask", "backing", "defer", NULL);
Mike Stump1eb44332009-09-09 15:08:12 +00001525
Ted Kremenek78a35a32009-05-12 20:06:54 +00001526 addInstMethSummary("NSPanel", NoTrackYet, "initWithContentRect",
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001527 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek78a35a32009-05-12 20:06:54 +00001528#endif
Mike Stump1eb44332009-09-09 15:08:12 +00001529
Ted Kremenekba67f6a2009-05-18 23:14:34 +00001530 // Don't track allocated autorelease pools yet, as it is okay to prematurely
1531 // exit a method.
1532 addClassMethSummary("NSAutoreleasePool", "alloc", NoTrackYet);
Ted Kremeneka9797122012-02-18 21:37:48 +00001533 addClassMethSummary("NSAutoreleasePool", "allocWithZone", NoTrackYet, false);
Ted Kremenek553cf182008-06-25 21:21:56 +00001534
Ted Kremenek767d6492009-05-20 22:39:57 +00001535 // Create summaries QCRenderer/QCView -createSnapShotImageOfType:
1536 addInstMethSummary("QCRenderer", AllocSumm,
1537 "createSnapshotImageOfType", NULL);
1538 addInstMethSummary("QCView", AllocSumm,
1539 "createSnapshotImageOfType", NULL);
1540
Ted Kremenek211a9c62009-06-15 20:58:58 +00001541 // Create summaries for CIContext, 'createCGImage' and
Ted Kremeneka834fb42009-08-28 19:52:12 +00001542 // 'createCGLayerWithSize'. These objects are CF objects, and are not
1543 // automatically garbage collected.
1544 addInstMethSummary("CIContext", CFAllocSumm,
Ted Kremenek767d6492009-05-20 22:39:57 +00001545 "createCGImage", "fromRect", NULL);
Ted Kremeneka834fb42009-08-28 19:52:12 +00001546 addInstMethSummary("CIContext", CFAllocSumm,
Mike Stump1eb44332009-09-09 15:08:12 +00001547 "createCGImage", "fromRect", "format", "colorSpace", NULL);
Ted Kremeneka834fb42009-08-28 19:52:12 +00001548 addInstMethSummary("CIContext", CFAllocSumm, "createCGLayerWithSize",
Ted Kremenek211a9c62009-06-15 20:58:58 +00001549 "info", NULL);
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001550}
1551
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001552//===----------------------------------------------------------------------===//
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001553// AutoreleaseBindings - State used to track objects in autorelease pools.
Ted Kremenek6d348932008-10-21 15:53:15 +00001554//===----------------------------------------------------------------------===//
1555
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001556typedef llvm::ImmutableMap<SymbolRef, unsigned> ARCounts;
1557typedef llvm::ImmutableMap<SymbolRef, ARCounts> ARPoolContents;
1558typedef llvm::ImmutableList<SymbolRef> ARStack;
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00001559
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001560static int AutoRCIndex = 0;
Ted Kremenek6d348932008-10-21 15:53:15 +00001561static int AutoRBIndex = 0;
1562
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001563namespace { class AutoreleasePoolContents {}; }
1564namespace { class AutoreleaseStack {}; }
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001565
Ted Kremenek6d348932008-10-21 15:53:15 +00001566namespace clang {
Ted Kremenek9ef65372010-12-23 07:20:52 +00001567namespace ento {
Ted Kremenek18c66fd2011-08-15 22:09:50 +00001568template<> struct ProgramStateTrait<AutoreleaseStack>
1569 : public ProgramStatePartialTrait<ARStack> {
Ted Kremenek9c378f72011-08-12 23:37:29 +00001570 static inline void *GDMIndex() { return &AutoRBIndex; }
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001571};
1572
Ted Kremenek18c66fd2011-08-15 22:09:50 +00001573template<> struct ProgramStateTrait<AutoreleasePoolContents>
1574 : public ProgramStatePartialTrait<ARPoolContents> {
Ted Kremenek9c378f72011-08-12 23:37:29 +00001575 static inline void *GDMIndex() { return &AutoRCIndex; }
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001576};
Argyrios Kyrtzidis5a4f98f2010-12-22 18:53:20 +00001577} // end GR namespace
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001578} // end clang namespace
Ted Kremenek6d348932008-10-21 15:53:15 +00001579
Ted Kremenek8bef8232012-01-26 21:29:00 +00001580static SymbolRef GetCurrentAutoreleasePool(ProgramStateRef state) {
Ted Kremenek7037ab82009-03-20 17:34:15 +00001581 ARStack stack = state->get<AutoreleaseStack>();
1582 return stack.isEmpty() ? SymbolRef() : stack.getHead();
1583}
1584
Ted Kremenek8bef8232012-01-26 21:29:00 +00001585static ProgramStateRef
1586SendAutorelease(ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +00001587 ARCounts::Factory &F,
1588 SymbolRef sym) {
Ted Kremenek7037ab82009-03-20 17:34:15 +00001589 SymbolRef pool = GetCurrentAutoreleasePool(state);
Ted Kremenekb65be702009-06-18 01:23:53 +00001590 const ARCounts *cnts = state->get<AutoreleasePoolContents>(pool);
Ted Kremenek7037ab82009-03-20 17:34:15 +00001591 ARCounts newCnts(0);
Mike Stump1eb44332009-09-09 15:08:12 +00001592
Ted Kremenek7037ab82009-03-20 17:34:15 +00001593 if (cnts) {
1594 const unsigned *cnt = (*cnts).lookup(sym);
Ted Kremenek3baf6722010-11-24 00:54:37 +00001595 newCnts = F.add(*cnts, sym, cnt ? *cnt + 1 : 1);
Ted Kremenek7037ab82009-03-20 17:34:15 +00001596 }
1597 else
Ted Kremenek3baf6722010-11-24 00:54:37 +00001598 newCnts = F.add(F.getEmptyMap(), sym, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001599
Ted Kremenekb65be702009-06-18 01:23:53 +00001600 return state->set<AutoreleasePoolContents>(pool, newCnts);
Ted Kremenek7037ab82009-03-20 17:34:15 +00001601}
1602
Ted Kremenek13922612008-04-16 20:40:59 +00001603//===----------------------------------------------------------------------===//
Ted Kremenekc887d132009-04-29 18:50:19 +00001604// Error reporting.
1605//===----------------------------------------------------------------------===//
Ted Kremenekc887d132009-04-29 18:50:19 +00001606namespace {
Jordy Roseec9ef852011-08-23 20:55:48 +00001607 typedef llvm::DenseMap<const ExplodedNode *, const RetainSummary *>
1608 SummaryLogTy;
1609
Ted Kremenekc887d132009-04-29 18:50:19 +00001610 //===-------------===//
1611 // Bug Descriptions. //
Mike Stump1eb44332009-09-09 15:08:12 +00001612 //===-------------===//
1613
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001614 class CFRefBug : public BugType {
Ted Kremenekc887d132009-04-29 18:50:19 +00001615 protected:
Jordy Rose35c86952011-08-24 05:47:39 +00001616 CFRefBug(StringRef name)
1617 : BugType(name, "Memory (Core Foundation/Objective-C)") {}
Ted Kremenekc887d132009-04-29 18:50:19 +00001618 public:
Mike Stump1eb44332009-09-09 15:08:12 +00001619
Ted Kremenekc887d132009-04-29 18:50:19 +00001620 // FIXME: Eventually remove.
Jordy Rose35c86952011-08-24 05:47:39 +00001621 virtual const char *getDescription() const = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001622
Ted Kremenekc887d132009-04-29 18:50:19 +00001623 virtual bool isLeak() const { return false; }
1624 };
Mike Stump1eb44332009-09-09 15:08:12 +00001625
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001626 class UseAfterRelease : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001627 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001628 UseAfterRelease() : CFRefBug("Use-after-release") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001629
Jordy Rose35c86952011-08-24 05:47:39 +00001630 const char *getDescription() const {
Ted Kremenekc887d132009-04-29 18:50:19 +00001631 return "Reference-counted object is used after it is released";
Mike Stump1eb44332009-09-09 15:08:12 +00001632 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001633 };
Mike Stump1eb44332009-09-09 15:08:12 +00001634
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001635 class BadRelease : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001636 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001637 BadRelease() : CFRefBug("Bad release") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001638
Jordy Rose35c86952011-08-24 05:47:39 +00001639 const char *getDescription() const {
Ted Kremenekbb206fd2009-10-01 17:31:50 +00001640 return "Incorrect decrement of the reference count of an object that is "
1641 "not owned at this point by the caller";
Ted Kremenekc887d132009-04-29 18:50:19 +00001642 }
1643 };
Mike Stump1eb44332009-09-09 15:08:12 +00001644
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001645 class DeallocGC : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001646 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001647 DeallocGC()
1648 : CFRefBug("-dealloc called while using garbage collection") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001649
Ted Kremenekc887d132009-04-29 18:50:19 +00001650 const char *getDescription() const {
Ted Kremenek369de562009-05-09 00:10:05 +00001651 return "-dealloc called while using garbage collection";
Ted Kremenekc887d132009-04-29 18:50:19 +00001652 }
1653 };
Mike Stump1eb44332009-09-09 15:08:12 +00001654
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001655 class DeallocNotOwned : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001656 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001657 DeallocNotOwned()
1658 : CFRefBug("-dealloc sent to non-exclusively owned object") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001659
Ted Kremenekc887d132009-04-29 18:50:19 +00001660 const char *getDescription() const {
1661 return "-dealloc sent to object that may be referenced elsewhere";
1662 }
Mike Stump1eb44332009-09-09 15:08:12 +00001663 };
1664
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001665 class OverAutorelease : public CFRefBug {
Ted Kremenek369de562009-05-09 00:10:05 +00001666 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001667 OverAutorelease()
1668 : CFRefBug("Object sent -autorelease too many times") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001669
Ted Kremenek369de562009-05-09 00:10:05 +00001670 const char *getDescription() const {
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001671 return "Object sent -autorelease too many times";
Ted Kremenek369de562009-05-09 00:10:05 +00001672 }
1673 };
Mike Stump1eb44332009-09-09 15:08:12 +00001674
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001675 class ReturnedNotOwnedForOwned : public CFRefBug {
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001676 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001677 ReturnedNotOwnedForOwned()
1678 : CFRefBug("Method should return an owned object") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001679
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001680 const char *getDescription() const {
Jordy Rose5b5402b2011-07-15 22:17:54 +00001681 return "Object with a +0 retain count returned to caller where a +1 "
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001682 "(owning) retain count is expected";
1683 }
1684 };
Mike Stump1eb44332009-09-09 15:08:12 +00001685
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001686 class Leak : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001687 const bool isReturn;
1688 protected:
Jordy Rose35c86952011-08-24 05:47:39 +00001689 Leak(StringRef name, bool isRet)
Jordy Rosedb92bb62011-08-25 01:14:38 +00001690 : CFRefBug(name), isReturn(isRet) {
1691 // Leaks should not be reported if they are post-dominated by a sink.
1692 setSuppressOnSink(true);
1693 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001694 public:
Mike Stump1eb44332009-09-09 15:08:12 +00001695
Jordy Rose35c86952011-08-24 05:47:39 +00001696 const char *getDescription() const { return ""; }
Mike Stump1eb44332009-09-09 15:08:12 +00001697
Ted Kremenekc887d132009-04-29 18:50:19 +00001698 bool isLeak() const { return true; }
1699 };
Mike Stump1eb44332009-09-09 15:08:12 +00001700
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001701 class LeakAtReturn : public Leak {
Ted Kremenekc887d132009-04-29 18:50:19 +00001702 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001703 LeakAtReturn(StringRef name)
1704 : Leak(name, true) {}
Ted Kremenekc887d132009-04-29 18:50:19 +00001705 };
Mike Stump1eb44332009-09-09 15:08:12 +00001706
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001707 class LeakWithinFunction : public Leak {
Ted Kremenekc887d132009-04-29 18:50:19 +00001708 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001709 LeakWithinFunction(StringRef name)
1710 : Leak(name, false) {}
Mike Stump1eb44332009-09-09 15:08:12 +00001711 };
1712
Ted Kremenekc887d132009-04-29 18:50:19 +00001713 //===---------===//
1714 // Bug Reports. //
1715 //===---------===//
Mike Stump1eb44332009-09-09 15:08:12 +00001716
Anna Zaksdc757b02011-08-19 23:21:56 +00001717 class CFRefReportVisitor : public BugReporterVisitor {
Anna Zaks23f395e2011-08-20 01:27:22 +00001718 protected:
Anna Zaksdc757b02011-08-19 23:21:56 +00001719 SymbolRef Sym;
Jordy Roseec9ef852011-08-23 20:55:48 +00001720 const SummaryLogTy &SummaryLog;
Jordy Rose35c86952011-08-24 05:47:39 +00001721 bool GCEnabled;
Anna Zaks23f395e2011-08-20 01:27:22 +00001722
Anna Zaksdc757b02011-08-19 23:21:56 +00001723 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001724 CFRefReportVisitor(SymbolRef sym, bool gcEnabled, const SummaryLogTy &log)
1725 : Sym(sym), SummaryLog(log), GCEnabled(gcEnabled) {}
Anna Zaksdc757b02011-08-19 23:21:56 +00001726
Anna Zaks23f395e2011-08-20 01:27:22 +00001727 virtual void Profile(llvm::FoldingSetNodeID &ID) const {
Anna Zaksdc757b02011-08-19 23:21:56 +00001728 static int x = 0;
1729 ID.AddPointer(&x);
1730 ID.AddPointer(Sym);
1731 }
1732
Anna Zaks23f395e2011-08-20 01:27:22 +00001733 virtual PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
1734 const ExplodedNode *PrevN,
1735 BugReporterContext &BRC,
1736 BugReport &BR);
1737
1738 virtual PathDiagnosticPiece *getEndPath(BugReporterContext &BRC,
1739 const ExplodedNode *N,
1740 BugReport &BR);
1741 };
1742
1743 class CFRefLeakReportVisitor : public CFRefReportVisitor {
1744 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001745 CFRefLeakReportVisitor(SymbolRef sym, bool GCEnabled,
Jordy Roseec9ef852011-08-23 20:55:48 +00001746 const SummaryLogTy &log)
Jordy Rose35c86952011-08-24 05:47:39 +00001747 : CFRefReportVisitor(sym, GCEnabled, log) {}
Anna Zaks23f395e2011-08-20 01:27:22 +00001748
1749 PathDiagnosticPiece *getEndPath(BugReporterContext &BRC,
1750 const ExplodedNode *N,
1751 BugReport &BR);
Anna Zaksdc757b02011-08-19 23:21:56 +00001752 };
1753
Anna Zakse172e8b2011-08-17 23:00:25 +00001754 class CFRefReport : public BugReport {
Jordy Rose20589562011-08-24 22:39:09 +00001755 void addGCModeDescription(const LangOptions &LOpts, bool GCEnabled);
Jordy Rose35c86952011-08-24 05:47:39 +00001756
Ted Kremenekc887d132009-04-29 18:50:19 +00001757 public:
Jordy Rose20589562011-08-24 22:39:09 +00001758 CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1759 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1760 bool registerVisitor = true)
Anna Zaksedf4dae2011-08-22 18:54:07 +00001761 : BugReport(D, D.getDescription(), n) {
Anna Zaks23f395e2011-08-20 01:27:22 +00001762 if (registerVisitor)
Jordy Rose20589562011-08-24 22:39:09 +00001763 addVisitor(new CFRefReportVisitor(sym, GCEnabled, Log));
1764 addGCModeDescription(LOpts, GCEnabled);
Anna Zaksdc757b02011-08-19 23:21:56 +00001765 }
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001766
Jordy Rose20589562011-08-24 22:39:09 +00001767 CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1768 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1769 StringRef endText)
Anna Zaksedf4dae2011-08-22 18:54:07 +00001770 : BugReport(D, D.getDescription(), endText, n) {
Jordy Rose20589562011-08-24 22:39:09 +00001771 addVisitor(new CFRefReportVisitor(sym, GCEnabled, Log));
1772 addGCModeDescription(LOpts, GCEnabled);
Anna Zaksdc757b02011-08-19 23:21:56 +00001773 }
Mike Stump1eb44332009-09-09 15:08:12 +00001774
Anna Zakse172e8b2011-08-17 23:00:25 +00001775 virtual std::pair<ranges_iterator, ranges_iterator> getRanges() {
Anna Zaksedf4dae2011-08-22 18:54:07 +00001776 const CFRefBug& BugTy = static_cast<CFRefBug&>(getBugType());
1777 if (!BugTy.isLeak())
Anna Zakse172e8b2011-08-17 23:00:25 +00001778 return BugReport::getRanges();
Ted Kremenekc887d132009-04-29 18:50:19 +00001779 else
Argyrios Kyrtzidis640ccf02010-12-04 01:12:15 +00001780 return std::make_pair(ranges_iterator(), ranges_iterator());
Ted Kremenekc887d132009-04-29 18:50:19 +00001781 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001782 };
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001783
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001784 class CFRefLeakReport : public CFRefReport {
Ted Kremenekc887d132009-04-29 18:50:19 +00001785 const MemRegion* AllocBinding;
Anna Zaks23f395e2011-08-20 01:27:22 +00001786
Ted Kremenekc887d132009-04-29 18:50:19 +00001787 public:
Jordy Rose20589562011-08-24 22:39:09 +00001788 CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1789 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
Anna Zaks6a93bd52011-10-25 19:57:11 +00001790 CheckerContext &Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001791
Anna Zaks590dd8e2011-09-20 21:38:35 +00001792 PathDiagnosticLocation getLocation(const SourceManager &SM) const {
1793 assert(Location.isValid());
1794 return Location;
1795 }
Mike Stump1eb44332009-09-09 15:08:12 +00001796 };
Ted Kremenekc887d132009-04-29 18:50:19 +00001797} // end anonymous namespace
1798
Jordy Rose20589562011-08-24 22:39:09 +00001799void CFRefReport::addGCModeDescription(const LangOptions &LOpts,
1800 bool GCEnabled) {
Jordy Rosef95b19d2011-08-24 20:38:42 +00001801 const char *GCModeDescription = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001802
Douglas Gregore289d812011-09-13 17:21:33 +00001803 switch (LOpts.getGC()) {
Anna Zaks7f2531c2011-08-22 20:31:28 +00001804 case LangOptions::GCOnly:
Jordy Rose20589562011-08-24 22:39:09 +00001805 assert(GCEnabled);
Jordy Rose35c86952011-08-24 05:47:39 +00001806 GCModeDescription = "Code is compiled to only use garbage collection";
1807 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001808
Anna Zaks7f2531c2011-08-22 20:31:28 +00001809 case LangOptions::NonGC:
Jordy Rose20589562011-08-24 22:39:09 +00001810 assert(!GCEnabled);
Jordy Rose35c86952011-08-24 05:47:39 +00001811 GCModeDescription = "Code is compiled to use reference counts";
1812 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001813
Anna Zaks7f2531c2011-08-22 20:31:28 +00001814 case LangOptions::HybridGC:
Jordy Rose20589562011-08-24 22:39:09 +00001815 if (GCEnabled) {
Jordy Rose35c86952011-08-24 05:47:39 +00001816 GCModeDescription = "Code is compiled to use either garbage collection "
1817 "(GC) or reference counts (non-GC). The bug occurs "
1818 "with GC enabled";
1819 break;
1820 } else {
1821 GCModeDescription = "Code is compiled to use either garbage collection "
1822 "(GC) or reference counts (non-GC). The bug occurs "
1823 "in non-GC mode";
1824 break;
Anna Zaks7f2531c2011-08-22 20:31:28 +00001825 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001826 }
Jordy Rose35c86952011-08-24 05:47:39 +00001827
Jordy Rosef95b19d2011-08-24 20:38:42 +00001828 assert(GCModeDescription && "invalid/unknown GC mode");
Jordy Rose35c86952011-08-24 05:47:39 +00001829 addExtraText(GCModeDescription);
Ted Kremenekc887d132009-04-29 18:50:19 +00001830}
1831
Jordy Rose910c4052011-09-02 06:44:22 +00001832// FIXME: This should be a method on SmallVector.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001833static inline bool contains(const SmallVectorImpl<ArgEffect>& V,
Ted Kremenekc887d132009-04-29 18:50:19 +00001834 ArgEffect X) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001835 for (SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
Ted Kremenekc887d132009-04-29 18:50:19 +00001836 I!=E; ++I)
1837 if (*I == X) return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001838
Ted Kremenekc887d132009-04-29 18:50:19 +00001839 return false;
1840}
1841
Ted Kremenek4c42bb72011-11-14 21:59:21 +00001842static bool isPropertyAccess(const Stmt *S, ParentMap &PM) {
1843 unsigned maxDepth = 4;
1844 while (S && maxDepth) {
1845 if (const PseudoObjectExpr *PO = dyn_cast<PseudoObjectExpr>(S)) {
1846 if (!isa<ObjCMessageExpr>(PO->getSyntacticForm()))
1847 return true;
1848 return false;
1849 }
1850 S = PM.getParent(S);
1851 --maxDepth;
1852 }
1853 return false;
1854}
1855
Anna Zaksdc757b02011-08-19 23:21:56 +00001856PathDiagnosticPiece *CFRefReportVisitor::VisitNode(const ExplodedNode *N,
1857 const ExplodedNode *PrevN,
1858 BugReporterContext &BRC,
1859 BugReport &BR) {
Mike Stump1eb44332009-09-09 15:08:12 +00001860
Jordy Rosef53e8c72011-08-23 19:43:16 +00001861 if (!isa<StmtPoint>(N->getLocation()))
Ted Kremenek2033a952009-05-13 07:12:33 +00001862 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001863
Ted Kremenek8966bc12009-05-06 21:39:49 +00001864 // Check if the type state has changed.
Ted Kremenek8bef8232012-01-26 21:29:00 +00001865 ProgramStateRef PrevSt = PrevN->getState();
1866 ProgramStateRef CurrSt = N->getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001867 const LocationContext *LCtx = N->getLocationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00001868
1869 const RefVal* CurrT = CurrSt->get<RefBindings>(Sym);
Ted Kremenekc887d132009-04-29 18:50:19 +00001870 if (!CurrT) return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001871
Ted Kremenekb65be702009-06-18 01:23:53 +00001872 const RefVal &CurrV = *CurrT;
1873 const RefVal *PrevT = PrevSt->get<RefBindings>(Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00001874
Ted Kremenekc887d132009-04-29 18:50:19 +00001875 // Create a string buffer to constain all the useful things we want
1876 // to tell the user.
1877 std::string sbuf;
1878 llvm::raw_string_ostream os(sbuf);
Mike Stump1eb44332009-09-09 15:08:12 +00001879
Ted Kremenekc887d132009-04-29 18:50:19 +00001880 // This is the allocation site since the previous node had no bindings
1881 // for this symbol.
1882 if (!PrevT) {
Jordy Rosef53e8c72011-08-23 19:43:16 +00001883 const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
Mike Stump1eb44332009-09-09 15:08:12 +00001884
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001885 if (isa<ObjCArrayLiteral>(S)) {
1886 os << "NSArray literal is an object with a +0 retain count";
Mike Stump1eb44332009-09-09 15:08:12 +00001887 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001888 else if (isa<ObjCDictionaryLiteral>(S)) {
1889 os << "NSDictionary literal is an object with a +0 retain count";
Ted Kremenekc887d132009-04-29 18:50:19 +00001890 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001891 else {
1892 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
1893 // Get the name of the callee (if it is available).
1894 SVal X = CurrSt->getSValAsScalarOrLoc(CE->getCallee(), LCtx);
1895 if (const FunctionDecl *FD = X.getAsFunctionDecl())
1896 os << "Call to function '" << *FD << '\'';
1897 else
1898 os << "function call";
Ted Kremenekc887d132009-04-29 18:50:19 +00001899 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001900 else {
1901 assert(isa<ObjCMessageExpr>(S));
1902 // The message expression may have between written directly or as
1903 // a property access. Lazily determine which case we are looking at.
1904 os << (isPropertyAccess(S, N->getParentMap()) ? "Property" : "Method");
1905 }
1906
1907 if (CurrV.getObjKind() == RetEffect::CF) {
1908 os << " returns a Core Foundation object with a ";
1909 }
1910 else {
1911 assert (CurrV.getObjKind() == RetEffect::ObjC);
1912 os << " returns an Objective-C object with a ";
1913 }
1914
1915 if (CurrV.isOwned()) {
1916 os << "+1 retain count";
1917
1918 if (GCEnabled) {
1919 assert(CurrV.getObjKind() == RetEffect::CF);
1920 os << ". "
1921 "Core Foundation objects are not automatically garbage collected.";
1922 }
1923 }
1924 else {
1925 assert (CurrV.isNotOwned());
1926 os << "+0 retain count";
1927 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001928 }
Mike Stump1eb44332009-09-09 15:08:12 +00001929
Anna Zaks220ac8c2011-09-15 01:08:34 +00001930 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
1931 N->getLocationContext());
Ted Kremenekc887d132009-04-29 18:50:19 +00001932 return new PathDiagnosticEventPiece(Pos, os.str());
1933 }
Mike Stump1eb44332009-09-09 15:08:12 +00001934
Ted Kremenekc887d132009-04-29 18:50:19 +00001935 // Gather up the effects that were performed on the object at this
1936 // program point
Chris Lattner5f9e2722011-07-23 10:55:15 +00001937 SmallVector<ArgEffect, 2> AEffects;
Mike Stump1eb44332009-09-09 15:08:12 +00001938
Jordy Roseec9ef852011-08-23 20:55:48 +00001939 const ExplodedNode *OrigNode = BRC.getNodeResolver().getOriginalNode(N);
1940 if (const RetainSummary *Summ = SummaryLog.lookup(OrigNode)) {
Ted Kremenekc887d132009-04-29 18:50:19 +00001941 // We only have summaries attached to nodes after evaluating CallExpr and
1942 // ObjCMessageExprs.
Jordy Rosef53e8c72011-08-23 19:43:16 +00001943 const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
Mike Stump1eb44332009-09-09 15:08:12 +00001944
Ted Kremenek5f85e172009-07-22 22:35:28 +00001945 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
Ted Kremenekc887d132009-04-29 18:50:19 +00001946 // Iterate through the parameter expressions and see if the symbol
1947 // was ever passed as an argument.
1948 unsigned i = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001949
Ted Kremenek5f85e172009-07-22 22:35:28 +00001950 for (CallExpr::const_arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
Ted Kremenekc887d132009-04-29 18:50:19 +00001951 AI!=AE; ++AI, ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00001952
Ted Kremenekc887d132009-04-29 18:50:19 +00001953 // Retrieve the value of the argument. Is it the symbol
1954 // we are interested in?
Ted Kremenek5eca4822012-01-06 22:09:28 +00001955 if (CurrSt->getSValAsScalarOrLoc(*AI, LCtx).getAsLocSymbol() != Sym)
Ted Kremenekc887d132009-04-29 18:50:19 +00001956 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001957
Ted Kremenekc887d132009-04-29 18:50:19 +00001958 // We have an argument. Get the effect!
1959 AEffects.push_back(Summ->getArg(i));
1960 }
1961 }
Mike Stump1eb44332009-09-09 15:08:12 +00001962 else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00001963 if (const Expr *receiver = ME->getInstanceReceiver())
Ted Kremenek5eca4822012-01-06 22:09:28 +00001964 if (CurrSt->getSValAsScalarOrLoc(receiver, LCtx)
1965 .getAsLocSymbol() == Sym) {
Ted Kremenekc887d132009-04-29 18:50:19 +00001966 // The symbol we are tracking is the receiver.
1967 AEffects.push_back(Summ->getReceiverEffect());
1968 }
1969 }
1970 }
Mike Stump1eb44332009-09-09 15:08:12 +00001971
Ted Kremenekc887d132009-04-29 18:50:19 +00001972 do {
1973 // Get the previous type state.
1974 RefVal PrevV = *PrevT;
Mike Stump1eb44332009-09-09 15:08:12 +00001975
Ted Kremenekc887d132009-04-29 18:50:19 +00001976 // Specially handle -dealloc.
Jordy Rose35c86952011-08-24 05:47:39 +00001977 if (!GCEnabled && contains(AEffects, Dealloc)) {
Ted Kremenekc887d132009-04-29 18:50:19 +00001978 // Determine if the object's reference count was pushed to zero.
1979 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
1980 // We may not have transitioned to 'release' if we hit an error.
1981 // This case is handled elsewhere.
1982 if (CurrV.getKind() == RefVal::Released) {
Ted Kremenekf21332e2009-05-08 20:01:42 +00001983 assert(CurrV.getCombinedCounts() == 0);
Ted Kremenekc887d132009-04-29 18:50:19 +00001984 os << "Object released by directly sending the '-dealloc' message";
1985 break;
1986 }
1987 }
Mike Stump1eb44332009-09-09 15:08:12 +00001988
Ted Kremenekc887d132009-04-29 18:50:19 +00001989 // Specially handle CFMakeCollectable and friends.
1990 if (contains(AEffects, MakeCollectable)) {
1991 // Get the name of the function.
Jordy Rosef53e8c72011-08-23 19:43:16 +00001992 const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001993 SVal X =
1994 CurrSt->getSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee(), LCtx);
Ted Kremenek9c378f72011-08-12 23:37:29 +00001995 const FunctionDecl *FD = X.getAsFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001996
Jordy Rose35c86952011-08-24 05:47:39 +00001997 if (GCEnabled) {
Ted Kremenekc887d132009-04-29 18:50:19 +00001998 // Determine if the object's reference count was pushed to zero.
1999 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
Mike Stump1eb44332009-09-09 15:08:12 +00002000
Benjamin Kramerb8989f22011-10-14 18:45:37 +00002001 os << "In GC mode a call to '" << *FD
Ted Kremenekc887d132009-04-29 18:50:19 +00002002 << "' decrements an object's retain count and registers the "
2003 "object with the garbage collector. ";
Mike Stump1eb44332009-09-09 15:08:12 +00002004
Ted Kremenekc887d132009-04-29 18:50:19 +00002005 if (CurrV.getKind() == RefVal::Released) {
2006 assert(CurrV.getCount() == 0);
2007 os << "Since it now has a 0 retain count the object can be "
2008 "automatically collected by the garbage collector.";
2009 }
2010 else
2011 os << "An object must have a 0 retain count to be garbage collected. "
2012 "After this call its retain count is +" << CurrV.getCount()
2013 << '.';
2014 }
Mike Stump1eb44332009-09-09 15:08:12 +00002015 else
Benjamin Kramerb8989f22011-10-14 18:45:37 +00002016 os << "When GC is not enabled a call to '" << *FD
Ted Kremenekc887d132009-04-29 18:50:19 +00002017 << "' has no effect on its argument.";
Mike Stump1eb44332009-09-09 15:08:12 +00002018
Ted Kremenekc887d132009-04-29 18:50:19 +00002019 // Nothing more to say.
2020 break;
2021 }
Mike Stump1eb44332009-09-09 15:08:12 +00002022
2023 // Determine if the typestate has changed.
Ted Kremenekc887d132009-04-29 18:50:19 +00002024 if (!(PrevV == CurrV))
2025 switch (CurrV.getKind()) {
2026 case RefVal::Owned:
2027 case RefVal::NotOwned:
Mike Stump1eb44332009-09-09 15:08:12 +00002028
Ted Kremenekf21332e2009-05-08 20:01:42 +00002029 if (PrevV.getCount() == CurrV.getCount()) {
2030 // Did an autorelease message get sent?
2031 if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
2032 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002033
Zhongxing Xu264e9372009-05-12 10:10:00 +00002034 assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount());
Ted Kremenekeaedfea2009-05-10 05:11:21 +00002035 os << "Object sent -autorelease message";
Ted Kremenekf21332e2009-05-08 20:01:42 +00002036 break;
2037 }
Mike Stump1eb44332009-09-09 15:08:12 +00002038
Ted Kremenekc887d132009-04-29 18:50:19 +00002039 if (PrevV.getCount() > CurrV.getCount())
2040 os << "Reference count decremented.";
2041 else
2042 os << "Reference count incremented.";
Mike Stump1eb44332009-09-09 15:08:12 +00002043
Ted Kremenekc887d132009-04-29 18:50:19 +00002044 if (unsigned Count = CurrV.getCount())
2045 os << " The object now has a +" << Count << " retain count.";
Mike Stump1eb44332009-09-09 15:08:12 +00002046
Ted Kremenekc887d132009-04-29 18:50:19 +00002047 if (PrevV.getKind() == RefVal::Released) {
Jordy Rose35c86952011-08-24 05:47:39 +00002048 assert(GCEnabled && CurrV.getCount() > 0);
Jordy Rose74b7b2b2012-03-17 05:49:15 +00002049 os << " The object is not eligible for garbage collection until "
2050 "the retain count reaches 0 again.";
Ted Kremenekc887d132009-04-29 18:50:19 +00002051 }
Mike Stump1eb44332009-09-09 15:08:12 +00002052
Ted Kremenekc887d132009-04-29 18:50:19 +00002053 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002054
Ted Kremenekc887d132009-04-29 18:50:19 +00002055 case RefVal::Released:
2056 os << "Object released.";
2057 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002058
Ted Kremenekc887d132009-04-29 18:50:19 +00002059 case RefVal::ReturnedOwned:
Jordy Rose74b7b2b2012-03-17 05:49:15 +00002060 // Autoreleases can be applied after marking a node ReturnedOwned.
2061 if (CurrV.getAutoreleaseCount())
2062 return NULL;
2063
2064 os << "Object returned to caller as an owning reference (single "
2065 "retain count transferred to caller)";
Ted Kremenekc887d132009-04-29 18:50:19 +00002066 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002067
Ted Kremenekc887d132009-04-29 18:50:19 +00002068 case RefVal::ReturnedNotOwned:
Ted Kremenekf1365462011-05-26 18:45:44 +00002069 os << "Object returned to caller with a +0 retain count";
Ted Kremenekc887d132009-04-29 18:50:19 +00002070 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002071
Ted Kremenekc887d132009-04-29 18:50:19 +00002072 default:
2073 return NULL;
2074 }
Mike Stump1eb44332009-09-09 15:08:12 +00002075
Ted Kremenekc887d132009-04-29 18:50:19 +00002076 // Emit any remaining diagnostics for the argument effects (if any).
Chris Lattner5f9e2722011-07-23 10:55:15 +00002077 for (SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
Ted Kremenekc887d132009-04-29 18:50:19 +00002078 E=AEffects.end(); I != E; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +00002079
Ted Kremenekc887d132009-04-29 18:50:19 +00002080 // A bunch of things have alternate behavior under GC.
Jordy Rose35c86952011-08-24 05:47:39 +00002081 if (GCEnabled)
Ted Kremenekc887d132009-04-29 18:50:19 +00002082 switch (*I) {
2083 default: break;
2084 case Autorelease:
2085 os << "In GC mode an 'autorelease' has no effect.";
2086 continue;
2087 case IncRefMsg:
2088 os << "In GC mode the 'retain' message has no effect.";
2089 continue;
2090 case DecRefMsg:
2091 os << "In GC mode the 'release' message has no effect.";
2092 continue;
2093 }
2094 }
Mike Stump1eb44332009-09-09 15:08:12 +00002095 } while (0);
2096
Ted Kremenekc887d132009-04-29 18:50:19 +00002097 if (os.str().empty())
2098 return 0; // We have nothing to say!
Ted Kremenek2033a952009-05-13 07:12:33 +00002099
Jordy Rosef53e8c72011-08-23 19:43:16 +00002100 const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
Anna Zaks220ac8c2011-09-15 01:08:34 +00002101 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
2102 N->getLocationContext());
Ted Kremenek9c378f72011-08-12 23:37:29 +00002103 PathDiagnosticPiece *P = new PathDiagnosticEventPiece(Pos, os.str());
Mike Stump1eb44332009-09-09 15:08:12 +00002104
Ted Kremenekc887d132009-04-29 18:50:19 +00002105 // Add the range by scanning the children of the statement for any bindings
2106 // to Sym.
Mike Stump1eb44332009-09-09 15:08:12 +00002107 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
Ted Kremenek5f85e172009-07-22 22:35:28 +00002108 I!=E; ++I)
Ted Kremenek9c378f72011-08-12 23:37:29 +00002109 if (const Expr *Exp = dyn_cast_or_null<Expr>(*I))
Ted Kremenek5eca4822012-01-06 22:09:28 +00002110 if (CurrSt->getSValAsScalarOrLoc(Exp, LCtx).getAsLocSymbol() == Sym) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002111 P->addRange(Exp->getSourceRange());
2112 break;
2113 }
Mike Stump1eb44332009-09-09 15:08:12 +00002114
Ted Kremenekc887d132009-04-29 18:50:19 +00002115 return P;
2116}
2117
2118namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00002119 class FindUniqueBinding :
Ted Kremenekc887d132009-04-29 18:50:19 +00002120 public StoreManager::BindingsHandler {
2121 SymbolRef Sym;
2122 const MemRegion* Binding;
2123 bool First;
Mike Stump1eb44332009-09-09 15:08:12 +00002124
Ted Kremenekc887d132009-04-29 18:50:19 +00002125 public:
2126 FindUniqueBinding(SymbolRef sym) : Sym(sym), Binding(0), First(true) {}
Mike Stump1eb44332009-09-09 15:08:12 +00002127
Ted Kremenekc887d132009-04-29 18:50:19 +00002128 bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
2129 SVal val) {
Mike Stump1eb44332009-09-09 15:08:12 +00002130
2131 SymbolRef SymV = val.getAsSymbol();
Ted Kremenekc887d132009-04-29 18:50:19 +00002132 if (!SymV || SymV != Sym)
2133 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002134
Ted Kremenekc887d132009-04-29 18:50:19 +00002135 if (Binding) {
2136 First = false;
2137 return false;
2138 }
2139 else
2140 Binding = R;
Mike Stump1eb44332009-09-09 15:08:12 +00002141
2142 return true;
Ted Kremenekc887d132009-04-29 18:50:19 +00002143 }
Mike Stump1eb44332009-09-09 15:08:12 +00002144
Ted Kremenekc887d132009-04-29 18:50:19 +00002145 operator bool() { return First && Binding; }
Ted Kremenek0507f7e2012-01-04 00:35:45 +00002146 const MemRegion *getRegion() { return Binding; }
Mike Stump1eb44332009-09-09 15:08:12 +00002147 };
Ted Kremenekc887d132009-04-29 18:50:19 +00002148}
2149
Anna Zakse7e01682012-02-28 22:39:22 +00002150// Find the first node in the current function context that referred to the
2151// tracked symbol and the memory location that value was stored to. Note, the
2152// value is only reported if the allocation occurred in the same function as
2153// the leak.
Zhongxing Xuc5619d92009-08-06 01:32:16 +00002154static std::pair<const ExplodedNode*,const MemRegion*>
Ted Kremenek18c66fd2011-08-15 22:09:50 +00002155GetAllocationSite(ProgramStateManager& StateMgr, const ExplodedNode *N,
Ted Kremenekc887d132009-04-29 18:50:19 +00002156 SymbolRef Sym) {
Ted Kremenek9c378f72011-08-12 23:37:29 +00002157 const ExplodedNode *Last = N;
Mike Stump1eb44332009-09-09 15:08:12 +00002158 const MemRegion* FirstBinding = 0;
Anna Zakse7e01682012-02-28 22:39:22 +00002159 const LocationContext *LeakContext = N->getLocationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002160
Ted Kremenekc887d132009-04-29 18:50:19 +00002161 while (N) {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002162 ProgramStateRef St = N->getState();
Ted Kremenekc887d132009-04-29 18:50:19 +00002163 RefBindings B = St->get<RefBindings>();
Mike Stump1eb44332009-09-09 15:08:12 +00002164
Ted Kremenekc887d132009-04-29 18:50:19 +00002165 if (!B.lookup(Sym))
2166 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002167
Ted Kremenekc887d132009-04-29 18:50:19 +00002168 FindUniqueBinding FB(Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002169 StateMgr.iterBindings(St, FB);
2170 if (FB) FirstBinding = FB.getRegion();
2171
Anna Zakse7e01682012-02-28 22:39:22 +00002172 // Allocation node, is the last node in the current context in which the
2173 // symbol was tracked.
2174 if (N->getLocationContext() == LeakContext)
2175 Last = N;
2176
Mike Stump1eb44332009-09-09 15:08:12 +00002177 N = N->pred_empty() ? NULL : *(N->pred_begin());
Ted Kremenekc887d132009-04-29 18:50:19 +00002178 }
Mike Stump1eb44332009-09-09 15:08:12 +00002179
Anna Zakse7e01682012-02-28 22:39:22 +00002180 // If allocation happened in a function different from the leak node context,
2181 // do not report the binding.
2182 if (N->getLocationContext() != LeakContext) {
2183 FirstBinding = 0;
2184 }
2185
Ted Kremenekc887d132009-04-29 18:50:19 +00002186 return std::make_pair(Last, FirstBinding);
2187}
2188
2189PathDiagnosticPiece*
Anna Zaks23f395e2011-08-20 01:27:22 +00002190CFRefReportVisitor::getEndPath(BugReporterContext &BRC,
2191 const ExplodedNode *EndN,
2192 BugReport &BR) {
Ted Kremenek76aadc32012-03-09 01:13:14 +00002193 BR.markInteresting(Sym);
Anna Zaks23f395e2011-08-20 01:27:22 +00002194 return BugReporterVisitor::getDefaultEndPath(BRC, EndN, BR);
Ted Kremenekc887d132009-04-29 18:50:19 +00002195}
2196
2197PathDiagnosticPiece*
Anna Zaks23f395e2011-08-20 01:27:22 +00002198CFRefLeakReportVisitor::getEndPath(BugReporterContext &BRC,
2199 const ExplodedNode *EndN,
2200 BugReport &BR) {
Mike Stump1eb44332009-09-09 15:08:12 +00002201
Ted Kremenek8966bc12009-05-06 21:39:49 +00002202 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenekc887d132009-04-29 18:50:19 +00002203 // assigned to different variables, etc.
Ted Kremenek76aadc32012-03-09 01:13:14 +00002204 BR.markInteresting(Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002205
Ted Kremenekc887d132009-04-29 18:50:19 +00002206 // We are reporting a leak. Walk up the graph to get to the first node where
2207 // the symbol appeared, and also get the first VarDecl that tracked object
2208 // is stored to.
Ted Kremenek9c378f72011-08-12 23:37:29 +00002209 const ExplodedNode *AllocNode = 0;
Ted Kremenekc887d132009-04-29 18:50:19 +00002210 const MemRegion* FirstBinding = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002211
Ted Kremenekc887d132009-04-29 18:50:19 +00002212 llvm::tie(AllocNode, FirstBinding) =
Ted Kremenekf04dced2009-05-08 23:32:51 +00002213 GetAllocationSite(BRC.getStateManager(), EndN, Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002214
Anna Zaks4fdf97b2011-09-15 18:56:07 +00002215 SourceManager& SM = BRC.getSourceManager();
Mike Stump1eb44332009-09-09 15:08:12 +00002216
Ted Kremenekc887d132009-04-29 18:50:19 +00002217 // Compute an actual location for the leak. Sometimes a leak doesn't
2218 // occur at an actual statement (e.g., transition between blocks; end
2219 // of function) so we need to walk the graph and compute a real location.
Ted Kremenek9c378f72011-08-12 23:37:29 +00002220 const ExplodedNode *LeakN = EndN;
Anna Zaks4fdf97b2011-09-15 18:56:07 +00002221 PathDiagnosticLocation L = PathDiagnosticLocation::createEndOfPath(LeakN, SM);
Mike Stump1eb44332009-09-09 15:08:12 +00002222
Ted Kremenekc887d132009-04-29 18:50:19 +00002223 std::string sbuf;
2224 llvm::raw_string_ostream os(sbuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002225
Ted Kremenekf1365462011-05-26 18:45:44 +00002226 os << "Object leaked: ";
Mike Stump1eb44332009-09-09 15:08:12 +00002227
Ted Kremenekf1365462011-05-26 18:45:44 +00002228 if (FirstBinding) {
2229 os << "object allocated and stored into '"
2230 << FirstBinding->getString() << '\'';
2231 }
2232 else
2233 os << "allocated object";
Mike Stump1eb44332009-09-09 15:08:12 +00002234
Ted Kremenekc887d132009-04-29 18:50:19 +00002235 // Get the retain count.
2236 const RefVal* RV = EndN->getState()->get<RefBindings>(Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002237
Ted Kremenekc887d132009-04-29 18:50:19 +00002238 if (RV->getKind() == RefVal::ErrorLeakReturned) {
2239 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
Jordy Rose5b5402b2011-07-15 22:17:54 +00002240 // objects. Only "copy", "alloc", "retain" and "new" transfer ownership
Ted Kremenekc887d132009-04-29 18:50:19 +00002241 // to the caller for NS objects.
Ted Kremenekd368d712011-05-25 06:19:45 +00002242 const Decl *D = &EndN->getCodeDecl();
2243 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2244 os << " is returned from a method whose name ('"
2245 << MD->getSelector().getAsString()
2246 << "') does not start with 'copy', 'mutableCopy', 'alloc' or 'new'."
Jordy Rose5b5402b2011-07-15 22:17:54 +00002247 " This violates the naming convention rules"
Ted Kremenekf1365462011-05-26 18:45:44 +00002248 " given in the Memory Management Guide for Cocoa";
Ted Kremenekd368d712011-05-25 06:19:45 +00002249 }
2250 else {
2251 const FunctionDecl *FD = cast<FunctionDecl>(D);
Ted Kremenekb7dcddf2011-12-22 06:35:52 +00002252 os << " is returned from a function whose name ('"
Benjamin Kramera59d20b2012-02-07 11:57:57 +00002253 << *FD
Ted Kremenekd368d712011-05-25 06:19:45 +00002254 << "') does not contain 'Copy' or 'Create'. This violates the naming"
Ted Kremenekb7dcddf2011-12-22 06:35:52 +00002255 " convention rules given in the Memory Management Guide for Core"
Ted Kremenekf1365462011-05-26 18:45:44 +00002256 " Foundation";
Ted Kremenekd368d712011-05-25 06:19:45 +00002257 }
Ted Kremenekc887d132009-04-29 18:50:19 +00002258 }
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002259 else if (RV->getKind() == RefVal::ErrorGCLeakReturned) {
Ted Kremenek9c378f72011-08-12 23:37:29 +00002260 ObjCMethodDecl &MD = cast<ObjCMethodDecl>(EndN->getCodeDecl());
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002261 os << " and returned from method '" << MD.getSelector().getAsString()
Ted Kremenek82f2be52009-05-10 16:52:15 +00002262 << "' is potentially leaked when using garbage collection. Callers "
2263 "of this method do not expect a returned object with a +1 retain "
2264 "count since they expect the object to be managed by the garbage "
2265 "collector";
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002266 }
Ted Kremenekc887d132009-04-29 18:50:19 +00002267 else
Ted Kremenekabf517c2010-10-15 22:50:23 +00002268 os << " is not referenced later in this execution path and has a retain "
Ted Kremenekf1365462011-05-26 18:45:44 +00002269 "count of +" << RV->getCount();
Mike Stump1eb44332009-09-09 15:08:12 +00002270
Ted Kremenekc887d132009-04-29 18:50:19 +00002271 return new PathDiagnosticEventPiece(L, os.str());
2272}
2273
Jordy Rose20589562011-08-24 22:39:09 +00002274CFRefLeakReport::CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts,
2275 bool GCEnabled, const SummaryLogTy &Log,
2276 ExplodedNode *n, SymbolRef sym,
Anna Zaks6a93bd52011-10-25 19:57:11 +00002277 CheckerContext &Ctx)
Jordy Rose20589562011-08-24 22:39:09 +00002278: CFRefReport(D, LOpts, GCEnabled, Log, n, sym, false) {
Mike Stump1eb44332009-09-09 15:08:12 +00002279
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00002280 // Most bug reports are cached at the location where they occurred.
Ted Kremenekc887d132009-04-29 18:50:19 +00002281 // With leaks, we want to unique them by the location where they were
2282 // allocated, and only report a single path. To do this, we need to find
2283 // the allocation site of a piece of tracked memory, which we do via a
2284 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2285 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2286 // that all ancestor nodes that represent the allocation site have the
2287 // same SourceLocation.
Ted Kremenek9c378f72011-08-12 23:37:29 +00002288 const ExplodedNode *AllocNode = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002289
Anna Zaks6a93bd52011-10-25 19:57:11 +00002290 const SourceManager& SMgr = Ctx.getSourceManager();
Anna Zaks590dd8e2011-09-20 21:38:35 +00002291
Ted Kremenekc887d132009-04-29 18:50:19 +00002292 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding.
Anna Zaks6a93bd52011-10-25 19:57:11 +00002293 GetAllocationSite(Ctx.getStateManager(), getErrorNode(), sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002294
Ted Kremenekc887d132009-04-29 18:50:19 +00002295 // Get the SourceLocation for the allocation site.
2296 ProgramPoint P = AllocNode->getLocation();
Anna Zaks590dd8e2011-09-20 21:38:35 +00002297 const Stmt *AllocStmt = cast<PostStmt>(P).getStmt();
2298 Location = PathDiagnosticLocation::createBegin(AllocStmt, SMgr,
2299 n->getLocationContext());
Ted Kremenekc887d132009-04-29 18:50:19 +00002300 // Fill in the description of the bug.
2301 Description.clear();
2302 llvm::raw_string_ostream os(Description);
Ted Kremenekdd924e22009-05-02 19:05:19 +00002303 os << "Potential leak ";
Jordy Rose20589562011-08-24 22:39:09 +00002304 if (GCEnabled)
Ted Kremenekdd924e22009-05-02 19:05:19 +00002305 os << "(when using garbage collection) ";
Anna Zaks212000e2012-02-28 21:49:08 +00002306 os << "of an object";
Mike Stump1eb44332009-09-09 15:08:12 +00002307
Ted Kremenekc887d132009-04-29 18:50:19 +00002308 // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2309 if (AllocBinding)
Anna Zaks212000e2012-02-28 21:49:08 +00002310 os << " stored into '" << AllocBinding->getString() << '\'';
Anna Zaksdc757b02011-08-19 23:21:56 +00002311
Jordy Rose20589562011-08-24 22:39:09 +00002312 addVisitor(new CFRefLeakReportVisitor(sym, GCEnabled, Log));
Ted Kremenekc887d132009-04-29 18:50:19 +00002313}
2314
2315//===----------------------------------------------------------------------===//
2316// Main checker logic.
2317//===----------------------------------------------------------------------===//
2318
Ted Kremenekd593eb92009-11-25 22:17:44 +00002319namespace {
Jordy Rose910c4052011-09-02 06:44:22 +00002320class RetainCountChecker
Jordy Rose9c083b72011-08-24 18:56:32 +00002321 : public Checker< check::Bind,
Jordy Rose38f17d62011-08-23 19:01:07 +00002322 check::DeadSymbols,
Jordy Rose9c083b72011-08-24 18:56:32 +00002323 check::EndAnalysis,
Jordy Rose38f17d62011-08-23 19:01:07 +00002324 check::EndPath,
Jordy Rose67044292011-08-17 21:27:39 +00002325 check::PostStmt<BlockExpr>,
John McCallf85e1932011-06-15 23:02:42 +00002326 check::PostStmt<CastExpr>,
Jordy Rose294396b2011-08-22 23:48:23 +00002327 check::PostStmt<CallExpr>,
Jordy Rose537716a2011-08-27 22:51:26 +00002328 check::PostStmt<CXXConstructExpr>,
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002329 check::PostStmt<ObjCArrayLiteral>,
2330 check::PostStmt<ObjCDictionaryLiteral>,
Jordy Rose294396b2011-08-22 23:48:23 +00002331 check::PostObjCMessage,
Jordy Rosef53e8c72011-08-23 19:43:16 +00002332 check::PreStmt<ReturnStmt>,
Jordy Rose67044292011-08-17 21:27:39 +00002333 check::RegionChanges,
Jordy Rose76c506f2011-08-21 21:58:18 +00002334 eval::Assume,
2335 eval::Call > {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002336 mutable OwningPtr<CFRefBug> useAfterRelease, releaseNotOwned;
2337 mutable OwningPtr<CFRefBug> deallocGC, deallocNotOwned;
2338 mutable OwningPtr<CFRefBug> overAutorelease, returnNotOwnedForOwned;
2339 mutable OwningPtr<CFRefBug> leakWithinFunction, leakAtReturn;
2340 mutable OwningPtr<CFRefBug> leakWithinFunctionGC, leakAtReturnGC;
Jordy Rose38f17d62011-08-23 19:01:07 +00002341
2342 typedef llvm::DenseMap<SymbolRef, const SimpleProgramPointTag *> SymbolTagMap;
2343
2344 // This map is only used to ensure proper deletion of any allocated tags.
2345 mutable SymbolTagMap DeadSymbolTags;
2346
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002347 mutable OwningPtr<RetainSummaryManager> Summaries;
2348 mutable OwningPtr<RetainSummaryManager> SummariesGC;
Jordy Roseb6cfc092011-08-25 00:10:37 +00002349
Jordy Rosee0a5d322011-08-23 20:27:16 +00002350 mutable ARCounts::Factory ARCountFactory;
2351
Jordy Rose9c083b72011-08-24 18:56:32 +00002352 mutable SummaryLogTy SummaryLog;
2353 mutable bool ShouldResetSummaryLog;
2354
Jordy Rose2f9a66d2011-08-20 21:17:59 +00002355public:
Jordy Rose910c4052011-09-02 06:44:22 +00002356 RetainCountChecker() : ShouldResetSummaryLog(false) {}
Jordy Rose38f17d62011-08-23 19:01:07 +00002357
Jordy Rose910c4052011-09-02 06:44:22 +00002358 virtual ~RetainCountChecker() {
Jordy Rose38f17d62011-08-23 19:01:07 +00002359 DeleteContainerSeconds(DeadSymbolTags);
2360 }
2361
Jordy Rose9c083b72011-08-24 18:56:32 +00002362 void checkEndAnalysis(ExplodedGraph &G, BugReporter &BR,
2363 ExprEngine &Eng) const {
2364 // FIXME: This is a hack to make sure the summary log gets cleared between
2365 // analyses of different code bodies.
2366 //
2367 // Why is this necessary? Because a checker's lifetime is tied to a
2368 // translation unit, but an ExplodedGraph's lifetime is just a code body.
2369 // Once in a blue moon, a new ExplodedNode will have the same address as an
2370 // old one with an associated summary, and the bug report visitor gets very
2371 // confused. (To make things worse, the summary lifetime is currently also
2372 // tied to a code body, so we get a crash instead of incorrect results.)
Jordy Rose1ab51c72011-08-24 09:27:24 +00002373 //
2374 // Why is this a bad solution? Because if the lifetime of the ExplodedGraph
2375 // changes, things will start going wrong again. Really the lifetime of this
2376 // log needs to be tied to either the specific nodes in it or the entire
2377 // ExplodedGraph, not to a specific part of the code being analyzed.
2378 //
Jordy Rose9c083b72011-08-24 18:56:32 +00002379 // (Also, having stateful local data means that the same checker can't be
2380 // used from multiple threads, but a lot of checkers have incorrect
2381 // assumptions about that anyway. So that wasn't a priority at the time of
2382 // this fix.)
Jordy Rose1ab51c72011-08-24 09:27:24 +00002383 //
Jordy Rose9c083b72011-08-24 18:56:32 +00002384 // This happens at the end of analysis, but bug reports are emitted /after/
2385 // this point. So we can't just clear the summary log now. Instead, we mark
2386 // that the next time we access the summary log, it should be cleared.
2387
2388 // If we never reset the summary log during /this/ code body analysis,
2389 // there were no new summaries. There might still have been summaries from
2390 // the /last/ analysis, so clear them out to make sure the bug report
2391 // visitors don't get confused.
2392 if (ShouldResetSummaryLog)
2393 SummaryLog.clear();
2394
2395 ShouldResetSummaryLog = !SummaryLog.empty();
Jordy Rose1ab51c72011-08-24 09:27:24 +00002396 }
2397
Jordy Rose17a38e22011-09-02 05:55:19 +00002398 CFRefBug *getLeakWithinFunctionBug(const LangOptions &LOpts,
2399 bool GCEnabled) const {
2400 if (GCEnabled) {
Jordy Rosedb92bb62011-08-25 01:14:38 +00002401 if (!leakWithinFunctionGC)
2402 leakWithinFunctionGC.reset(new LeakWithinFunction("Leak of object when "
2403 "using garbage "
2404 "collection"));
Jordy Rose17a38e22011-09-02 05:55:19 +00002405 return leakWithinFunctionGC.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002406 } else {
2407 if (!leakWithinFunction) {
Douglas Gregore289d812011-09-13 17:21:33 +00002408 if (LOpts.getGC() == LangOptions::HybridGC) {
Jordy Rosedb92bb62011-08-25 01:14:38 +00002409 leakWithinFunction.reset(new LeakWithinFunction("Leak of object when "
2410 "not using garbage "
2411 "collection (GC) in "
2412 "dual GC/non-GC "
2413 "code"));
2414 } else {
2415 leakWithinFunction.reset(new LeakWithinFunction("Leak"));
2416 }
2417 }
Jordy Rose17a38e22011-09-02 05:55:19 +00002418 return leakWithinFunction.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002419 }
2420 }
2421
Jordy Rose17a38e22011-09-02 05:55:19 +00002422 CFRefBug *getLeakAtReturnBug(const LangOptions &LOpts, bool GCEnabled) const {
2423 if (GCEnabled) {
Jordy Rosedb92bb62011-08-25 01:14:38 +00002424 if (!leakAtReturnGC)
2425 leakAtReturnGC.reset(new LeakAtReturn("Leak of returned object when "
2426 "using garbage collection"));
Jordy Rose17a38e22011-09-02 05:55:19 +00002427 return leakAtReturnGC.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002428 } else {
2429 if (!leakAtReturn) {
Douglas Gregore289d812011-09-13 17:21:33 +00002430 if (LOpts.getGC() == LangOptions::HybridGC) {
Jordy Rosedb92bb62011-08-25 01:14:38 +00002431 leakAtReturn.reset(new LeakAtReturn("Leak of returned object when "
2432 "not using garbage collection "
2433 "(GC) in dual GC/non-GC code"));
2434 } else {
2435 leakAtReturn.reset(new LeakAtReturn("Leak of returned object"));
2436 }
2437 }
Jordy Rose17a38e22011-09-02 05:55:19 +00002438 return leakAtReturn.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002439 }
2440 }
2441
Jordy Rose17a38e22011-09-02 05:55:19 +00002442 RetainSummaryManager &getSummaryManager(ASTContext &Ctx,
2443 bool GCEnabled) const {
2444 // FIXME: We don't support ARC being turned on and off during one analysis.
2445 // (nor, for that matter, do we support changing ASTContexts)
David Blaikie4e4d0842012-03-11 07:00:24 +00002446 bool ARCEnabled = (bool)Ctx.getLangOpts().ObjCAutoRefCount;
Jordy Rose17a38e22011-09-02 05:55:19 +00002447 if (GCEnabled) {
2448 if (!SummariesGC)
Jordy Roseb6cfc092011-08-25 00:10:37 +00002449 SummariesGC.reset(new RetainSummaryManager(Ctx, true, ARCEnabled));
Jordy Rose17a38e22011-09-02 05:55:19 +00002450 else
2451 assert(SummariesGC->isARCEnabled() == ARCEnabled);
Jordy Roseb6cfc092011-08-25 00:10:37 +00002452 return *SummariesGC;
2453 } else {
Jordy Rose17a38e22011-09-02 05:55:19 +00002454 if (!Summaries)
Jordy Roseb6cfc092011-08-25 00:10:37 +00002455 Summaries.reset(new RetainSummaryManager(Ctx, false, ARCEnabled));
Jordy Rose17a38e22011-09-02 05:55:19 +00002456 else
2457 assert(Summaries->isARCEnabled() == ARCEnabled);
Jordy Roseb6cfc092011-08-25 00:10:37 +00002458 return *Summaries;
2459 }
2460 }
2461
Jordy Rose17a38e22011-09-02 05:55:19 +00002462 RetainSummaryManager &getSummaryManager(CheckerContext &C) const {
2463 return getSummaryManager(C.getASTContext(), C.isObjCGCEnabled());
2464 }
2465
Ted Kremenek8bef8232012-01-26 21:29:00 +00002466 void printState(raw_ostream &Out, ProgramStateRef State,
Jordy Rosedbd658e2011-08-28 19:11:56 +00002467 const char *NL, const char *Sep) const;
2468
Anna Zaks390909c2011-10-06 00:43:15 +00002469 void checkBind(SVal loc, SVal val, const Stmt *S, CheckerContext &C) const;
Jordy Roseab027fd2011-08-20 21:16:58 +00002470 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
2471 void checkPostStmt(const CastExpr *CE, CheckerContext &C) const;
John McCallf85e1932011-06-15 23:02:42 +00002472
Jordy Rose294396b2011-08-22 23:48:23 +00002473 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
Jordy Rose537716a2011-08-27 22:51:26 +00002474 void checkPostStmt(const CXXConstructExpr *CE, CheckerContext &C) const;
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002475 void checkPostStmt(const ObjCArrayLiteral *AL, CheckerContext &C) const;
2476 void checkPostStmt(const ObjCDictionaryLiteral *DL, CheckerContext &C) const;
Jordy Rose294396b2011-08-22 23:48:23 +00002477 void checkPostObjCMessage(const ObjCMessage &Msg, CheckerContext &C) const;
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002478
Jordy Rose294396b2011-08-22 23:48:23 +00002479 void checkSummary(const RetainSummary &Summ, const CallOrObjCMessage &Call,
Jordy Rosee38dd952011-08-28 05:16:28 +00002480 CheckerContext &C) const;
Jordy Rose294396b2011-08-22 23:48:23 +00002481
Jordy Rose76c506f2011-08-21 21:58:18 +00002482 bool evalCall(const CallExpr *CE, CheckerContext &C) const;
2483
Ted Kremenek8bef8232012-01-26 21:29:00 +00002484 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Jordy Roseab027fd2011-08-20 21:16:58 +00002485 bool Assumption) const;
Jordy Rose67044292011-08-17 21:27:39 +00002486
Ted Kremenek8bef8232012-01-26 21:29:00 +00002487 ProgramStateRef
2488 checkRegionChanges(ProgramStateRef state,
Jordy Rose537716a2011-08-27 22:51:26 +00002489 const StoreManager::InvalidatedSymbols *invalidated,
2490 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00002491 ArrayRef<const MemRegion *> Regions,
2492 const CallOrObjCMessage *Call) const;
Jordy Roseab027fd2011-08-20 21:16:58 +00002493
Ted Kremenek8bef8232012-01-26 21:29:00 +00002494 bool wantsRegionChangeUpdate(ProgramStateRef state) const {
Jordy Rose2f9a66d2011-08-20 21:17:59 +00002495 return true;
Jordy Roseab027fd2011-08-20 21:16:58 +00002496 }
Jordy Rose294396b2011-08-22 23:48:23 +00002497
Jordy Rosef53e8c72011-08-23 19:43:16 +00002498 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
2499 void checkReturnWithRetEffect(const ReturnStmt *S, CheckerContext &C,
2500 ExplodedNode *Pred, RetEffect RE, RefVal X,
Ted Kremenek8bef8232012-01-26 21:29:00 +00002501 SymbolRef Sym, ProgramStateRef state) const;
Jordy Rosef53e8c72011-08-23 19:43:16 +00002502
Jordy Rose38f17d62011-08-23 19:01:07 +00002503 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Anna Zaksaf498a22011-10-25 19:56:48 +00002504 void checkEndPath(CheckerContext &C) const;
Jordy Rose38f17d62011-08-23 19:01:07 +00002505
Ted Kremenek8bef8232012-01-26 21:29:00 +00002506 ProgramStateRef updateSymbol(ProgramStateRef state, SymbolRef sym,
Jordy Rose17a38e22011-09-02 05:55:19 +00002507 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
2508 CheckerContext &C) const;
Jordy Rosee0a5d322011-08-23 20:27:16 +00002509
Ted Kremenek8bef8232012-01-26 21:29:00 +00002510 void processNonLeakError(ProgramStateRef St, SourceRange ErrorRange,
Jordy Rose294396b2011-08-22 23:48:23 +00002511 RefVal::Kind ErrorKind, SymbolRef Sym,
2512 CheckerContext &C) const;
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002513
2514 void processObjCLiterals(CheckerContext &C, const Expr *Ex) const;
Jordy Rose294396b2011-08-22 23:48:23 +00002515
Jordy Rose38f17d62011-08-23 19:01:07 +00002516 const ProgramPointTag *getDeadSymbolTag(SymbolRef sym) const;
2517
Ted Kremenek8bef8232012-01-26 21:29:00 +00002518 ProgramStateRef handleSymbolDeath(ProgramStateRef state,
Jordy Rose38f17d62011-08-23 19:01:07 +00002519 SymbolRef sid, RefVal V,
2520 SmallVectorImpl<SymbolRef> &Leaked) const;
2521
Ted Kremenek8bef8232012-01-26 21:29:00 +00002522 std::pair<ExplodedNode *, ProgramStateRef >
2523 handleAutoreleaseCounts(ProgramStateRef state,
Jordy Rose8d228632011-08-23 20:07:14 +00002524 GenericNodeBuilderRefCount Bd, ExplodedNode *Pred,
Anna Zaks6a93bd52011-10-25 19:57:11 +00002525 CheckerContext &Ctx, SymbolRef Sym, RefVal V) const;
Jordy Rose8d228632011-08-23 20:07:14 +00002526
Ted Kremenek8bef8232012-01-26 21:29:00 +00002527 ExplodedNode *processLeaks(ProgramStateRef state,
Jordy Rose38f17d62011-08-23 19:01:07 +00002528 SmallVectorImpl<SymbolRef> &Leaked,
2529 GenericNodeBuilderRefCount &Builder,
Anna Zaks6a93bd52011-10-25 19:57:11 +00002530 CheckerContext &Ctx,
Jordy Rose38f17d62011-08-23 19:01:07 +00002531 ExplodedNode *Pred = 0) const;
Ted Kremenekd593eb92009-11-25 22:17:44 +00002532};
2533} // end anonymous namespace
2534
Jordy Rose67044292011-08-17 21:27:39 +00002535namespace {
2536class StopTrackingCallback : public SymbolVisitor {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002537 ProgramStateRef state;
Jordy Rose67044292011-08-17 21:27:39 +00002538public:
Ted Kremenek8bef8232012-01-26 21:29:00 +00002539 StopTrackingCallback(ProgramStateRef st) : state(st) {}
2540 ProgramStateRef getState() const { return state; }
Jordy Rose67044292011-08-17 21:27:39 +00002541
2542 bool VisitSymbol(SymbolRef sym) {
2543 state = state->remove<RefBindings>(sym);
2544 return true;
2545 }
2546};
2547} // end anonymous namespace
2548
Jordy Rose910c4052011-09-02 06:44:22 +00002549//===----------------------------------------------------------------------===//
2550// Handle statements that may have an effect on refcounts.
2551//===----------------------------------------------------------------------===//
Jordy Rose67044292011-08-17 21:27:39 +00002552
Jordy Rose910c4052011-09-02 06:44:22 +00002553void RetainCountChecker::checkPostStmt(const BlockExpr *BE,
2554 CheckerContext &C) const {
Jordy Rose67044292011-08-17 21:27:39 +00002555
Jordy Rose910c4052011-09-02 06:44:22 +00002556 // Scan the BlockDecRefExprs for any object the retain count checker
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002557 // may be tracking.
John McCall469a1eb2011-02-02 13:00:07 +00002558 if (!BE->getBlockDecl()->hasCaptures())
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002559 return;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002560
Ted Kremenek8bef8232012-01-26 21:29:00 +00002561 ProgramStateRef state = C.getState();
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002562 const BlockDataRegion *R =
Ted Kremenek5eca4822012-01-06 22:09:28 +00002563 cast<BlockDataRegion>(state->getSVal(BE,
2564 C.getLocationContext()).getAsRegion());
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002565
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002566 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
2567 E = R->referenced_vars_end();
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002568
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002569 if (I == E)
2570 return;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002571
Ted Kremenek67d12872009-12-07 22:05:27 +00002572 // FIXME: For now we invalidate the tracking of all symbols passed to blocks
2573 // via captured variables, even though captured variables result in a copy
2574 // and in implicit increment/decrement of a retain count.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002575 SmallVector<const MemRegion*, 10> Regions;
Anna Zaks39ac1872011-10-26 21:06:44 +00002576 const LocationContext *LC = C.getLocationContext();
Ted Kremenekc8413fd2010-12-02 07:49:45 +00002577 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002578
Ted Kremenek67d12872009-12-07 22:05:27 +00002579 for ( ; I != E; ++I) {
2580 const VarRegion *VR = *I;
2581 if (VR->getSuperRegion() == R) {
2582 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2583 }
2584 Regions.push_back(VR);
2585 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002586
Ted Kremenek67d12872009-12-07 22:05:27 +00002587 state =
2588 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
2589 Regions.data() + Regions.size()).getState();
Anna Zaks0bd6b112011-10-26 21:06:34 +00002590 C.addTransition(state);
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002591}
2592
Jordy Rose910c4052011-09-02 06:44:22 +00002593void RetainCountChecker::checkPostStmt(const CastExpr *CE,
2594 CheckerContext &C) const {
John McCallf85e1932011-06-15 23:02:42 +00002595 const ObjCBridgedCastExpr *BE = dyn_cast<ObjCBridgedCastExpr>(CE);
2596 if (!BE)
2597 return;
2598
John McCall71c482c2011-06-17 06:50:50 +00002599 ArgEffect AE = IncRef;
John McCallf85e1932011-06-15 23:02:42 +00002600
2601 switch (BE->getBridgeKind()) {
2602 case clang::OBC_Bridge:
2603 // Do nothing.
2604 return;
2605 case clang::OBC_BridgeRetained:
2606 AE = IncRef;
2607 break;
2608 case clang::OBC_BridgeTransfer:
2609 AE = DecRefBridgedTransfered;
2610 break;
2611 }
2612
Ted Kremenek8bef8232012-01-26 21:29:00 +00002613 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00002614 SymbolRef Sym = state->getSVal(CE, C.getLocationContext()).getAsLocSymbol();
John McCallf85e1932011-06-15 23:02:42 +00002615 if (!Sym)
2616 return;
2617 const RefVal* T = state->get<RefBindings>(Sym);
2618 if (!T)
2619 return;
2620
John McCallf85e1932011-06-15 23:02:42 +00002621 RefVal::Kind hasErr = (RefVal::Kind) 0;
Jordy Rose17a38e22011-09-02 05:55:19 +00002622 state = updateSymbol(state, Sym, *T, AE, hasErr, C);
John McCallf85e1932011-06-15 23:02:42 +00002623
2624 if (hasErr) {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002625 // FIXME: If we get an error during a bridge cast, should we report it?
2626 // Should we assert that there is no error?
John McCallf85e1932011-06-15 23:02:42 +00002627 return;
2628 }
2629
Anna Zaks0bd6b112011-10-26 21:06:34 +00002630 C.addTransition(state);
John McCallf85e1932011-06-15 23:02:42 +00002631}
2632
Jordy Rose910c4052011-09-02 06:44:22 +00002633void RetainCountChecker::checkPostStmt(const CallExpr *CE,
2634 CheckerContext &C) const {
Jordy Rose294396b2011-08-22 23:48:23 +00002635 // Get the callee.
Ted Kremenek8bef8232012-01-26 21:29:00 +00002636 ProgramStateRef state = C.getState();
Jordy Rose294396b2011-08-22 23:48:23 +00002637 const Expr *Callee = CE->getCallee();
Ted Kremenek5eca4822012-01-06 22:09:28 +00002638 SVal L = state->getSVal(Callee, C.getLocationContext());
Jordy Rose294396b2011-08-22 23:48:23 +00002639
Jordy Rose17a38e22011-09-02 05:55:19 +00002640 RetainSummaryManager &Summaries = getSummaryManager(C);
Ted Kremenek93edbc52011-10-05 23:54:29 +00002641 const RetainSummary *Summ = 0;
Jordy Rose294396b2011-08-22 23:48:23 +00002642
2643 // FIXME: Better support for blocks. For now we stop tracking anything
2644 // that is passed to blocks.
2645 // FIXME: Need to handle variables that are "captured" by the block.
2646 if (dyn_cast_or_null<BlockDataRegion>(L.getAsRegion())) {
2647 Summ = Summaries.getPersistentStopSummary();
2648 } else if (const FunctionDecl *FD = L.getAsFunctionDecl()) {
2649 Summ = Summaries.getSummary(FD);
2650 } else if (const CXXMemberCallExpr *me = dyn_cast<CXXMemberCallExpr>(CE)) {
2651 if (const CXXMethodDecl *MD = me->getMethodDecl())
2652 Summ = Summaries.getSummary(MD);
2653 }
2654
Jordy Rose294396b2011-08-22 23:48:23 +00002655 if (!Summ)
Ted Kremenek93edbc52011-10-05 23:54:29 +00002656 Summ = Summaries.getDefaultSummary();
Jordy Rose294396b2011-08-22 23:48:23 +00002657
Ted Kremenek5eca4822012-01-06 22:09:28 +00002658 checkSummary(*Summ, CallOrObjCMessage(CE, state, C.getLocationContext()), C);
Jordy Rose294396b2011-08-22 23:48:23 +00002659}
2660
Jordy Rose910c4052011-09-02 06:44:22 +00002661void RetainCountChecker::checkPostStmt(const CXXConstructExpr *CE,
2662 CheckerContext &C) const {
Jordy Rose537716a2011-08-27 22:51:26 +00002663 const CXXConstructorDecl *Ctor = CE->getConstructor();
2664 if (!Ctor)
2665 return;
2666
Jordy Rose17a38e22011-09-02 05:55:19 +00002667 RetainSummaryManager &Summaries = getSummaryManager(C);
Ted Kremenek93edbc52011-10-05 23:54:29 +00002668 const RetainSummary *Summ = Summaries.getSummary(Ctor);
Jordy Rose537716a2011-08-27 22:51:26 +00002669
2670 // If we didn't get a summary, this constructor doesn't affect retain counts.
2671 if (!Summ)
2672 return;
2673
Ted Kremenek8bef8232012-01-26 21:29:00 +00002674 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00002675 checkSummary(*Summ, CallOrObjCMessage(CE, state, C.getLocationContext()), C);
Jordy Rose537716a2011-08-27 22:51:26 +00002676}
2677
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002678void RetainCountChecker::processObjCLiterals(CheckerContext &C,
2679 const Expr *Ex) const {
2680 ProgramStateRef state = C.getState();
2681 const ExplodedNode *pred = C.getPredecessor();
2682 for (Stmt::const_child_iterator it = Ex->child_begin(), et = Ex->child_end() ;
2683 it != et ; ++it) {
2684 const Stmt *child = *it;
2685 SVal V = state->getSVal(child, pred->getLocationContext());
2686 if (SymbolRef sym = V.getAsSymbol())
2687 if (const RefVal* T = state->get<RefBindings>(sym)) {
2688 RefVal::Kind hasErr = (RefVal::Kind) 0;
2689 state = updateSymbol(state, sym, *T, MayEscape, hasErr, C);
2690 if (hasErr) {
2691 processNonLeakError(state, child->getSourceRange(), hasErr, sym, C);
2692 return;
2693 }
2694 }
2695 }
2696
2697 // Return the object as autoreleased.
2698 // RetEffect RE = RetEffect::MakeNotOwned(RetEffect::ObjC);
2699 if (SymbolRef sym =
2700 state->getSVal(Ex, pred->getLocationContext()).getAsSymbol()) {
2701 QualType ResultTy = Ex->getType();
2702 state = state->set<RefBindings>(sym, RefVal::makeNotOwned(RetEffect::ObjC,
2703 ResultTy));
2704 }
2705
2706 C.addTransition(state);
2707}
2708
2709void RetainCountChecker::checkPostStmt(const ObjCArrayLiteral *AL,
2710 CheckerContext &C) const {
2711 // Apply the 'MayEscape' to all values.
2712 processObjCLiterals(C, AL);
2713}
2714
2715void RetainCountChecker::checkPostStmt(const ObjCDictionaryLiteral *DL,
2716 CheckerContext &C) const {
2717 // Apply the 'MayEscape' to all keys and values.
2718 processObjCLiterals(C, DL);
2719}
2720
Jordy Rose910c4052011-09-02 06:44:22 +00002721void RetainCountChecker::checkPostObjCMessage(const ObjCMessage &Msg,
2722 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002723 ProgramStateRef state = C.getState();
Jordy Rose294396b2011-08-22 23:48:23 +00002724
Jordy Rose17a38e22011-09-02 05:55:19 +00002725 RetainSummaryManager &Summaries = getSummaryManager(C);
Jordy Roseb6cfc092011-08-25 00:10:37 +00002726
Ted Kremenek93edbc52011-10-05 23:54:29 +00002727 const RetainSummary *Summ;
Jordy Rose294396b2011-08-22 23:48:23 +00002728 if (Msg.isInstanceMessage()) {
Anna Zaksa2a86032011-11-01 22:41:01 +00002729 const LocationContext *LC = C.getLocationContext();
Jordy Rose294396b2011-08-22 23:48:23 +00002730 Summ = Summaries.getInstanceMethodSummary(Msg, state, LC);
2731 } else {
2732 Summ = Summaries.getClassMethodSummary(Msg);
2733 }
2734
2735 // If we didn't get a summary, this message doesn't affect retain counts.
2736 if (!Summ)
2737 return;
2738
Ted Kremenek5eca4822012-01-06 22:09:28 +00002739 checkSummary(*Summ, CallOrObjCMessage(Msg, state, C.getLocationContext()), C);
Jordy Rose294396b2011-08-22 23:48:23 +00002740}
2741
Jordy Rose910c4052011-09-02 06:44:22 +00002742/// GetReturnType - Used to get the return type of a message expression or
2743/// function call with the intention of affixing that type to a tracked symbol.
2744/// While the the return type can be queried directly from RetEx, when
2745/// invoking class methods we augment to the return type to be that of
2746/// a pointer to the class (as opposed it just being id).
2747// FIXME: We may be able to do this with related result types instead.
2748// This function is probably overestimating.
2749static QualType GetReturnType(const Expr *RetE, ASTContext &Ctx) {
2750 QualType RetTy = RetE->getType();
2751 // If RetE is not a message expression just return its type.
2752 // If RetE is a message expression, return its types if it is something
2753 /// more specific than id.
2754 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RetE))
2755 if (const ObjCObjectPointerType *PT = RetTy->getAs<ObjCObjectPointerType>())
2756 if (PT->isObjCQualifiedIdType() || PT->isObjCIdType() ||
2757 PT->isObjCClassType()) {
2758 // At this point we know the return type of the message expression is
2759 // id, id<...>, or Class. If we have an ObjCInterfaceDecl, we know this
2760 // is a call to a class method whose type we can resolve. In such
2761 // cases, promote the return type to XXX* (where XXX is the class).
2762 const ObjCInterfaceDecl *D = ME->getReceiverInterface();
2763 return !D ? RetTy :
2764 Ctx.getObjCObjectPointerType(Ctx.getObjCInterfaceType(D));
2765 }
2766
2767 return RetTy;
2768}
2769
2770void RetainCountChecker::checkSummary(const RetainSummary &Summ,
2771 const CallOrObjCMessage &CallOrMsg,
2772 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002773 ProgramStateRef state = C.getState();
Jordy Rose294396b2011-08-22 23:48:23 +00002774
2775 // Evaluate the effect of the arguments.
2776 RefVal::Kind hasErr = (RefVal::Kind) 0;
2777 SourceRange ErrorRange;
2778 SymbolRef ErrorSym = 0;
2779
2780 for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
Jordy Rose537716a2011-08-27 22:51:26 +00002781 SVal V = CallOrMsg.getArgSVal(idx);
Jordy Rose294396b2011-08-22 23:48:23 +00002782
2783 if (SymbolRef Sym = V.getAsLocSymbol()) {
2784 if (RefBindings::data_type *T = state->get<RefBindings>(Sym)) {
Jordy Rose17a38e22011-09-02 05:55:19 +00002785 state = updateSymbol(state, Sym, *T, Summ.getArg(idx), hasErr, C);
Jordy Rose294396b2011-08-22 23:48:23 +00002786 if (hasErr) {
2787 ErrorRange = CallOrMsg.getArgSourceRange(idx);
2788 ErrorSym = Sym;
2789 break;
2790 }
2791 }
2792 }
2793 }
2794
2795 // Evaluate the effect on the message receiver.
2796 bool ReceiverIsTracked = false;
Jordy Rosee38dd952011-08-28 05:16:28 +00002797 if (!hasErr && CallOrMsg.isObjCMessage()) {
Anna Zaks39ac1872011-10-26 21:06:44 +00002798 const LocationContext *LC = C.getLocationContext();
Jordy Rosee38dd952011-08-28 05:16:28 +00002799 SVal Receiver = CallOrMsg.getInstanceMessageReceiver(LC);
2800 if (SymbolRef Sym = Receiver.getAsLocSymbol()) {
Jordy Rose294396b2011-08-22 23:48:23 +00002801 if (const RefVal *T = state->get<RefBindings>(Sym)) {
2802 ReceiverIsTracked = true;
Jordy Rose17a38e22011-09-02 05:55:19 +00002803 state = updateSymbol(state, Sym, *T, Summ.getReceiverEffect(),
2804 hasErr, C);
Jordy Rose294396b2011-08-22 23:48:23 +00002805 if (hasErr) {
Jordy Rosee38dd952011-08-28 05:16:28 +00002806 ErrorRange = CallOrMsg.getReceiverSourceRange();
Jordy Rose294396b2011-08-22 23:48:23 +00002807 ErrorSym = Sym;
2808 }
2809 }
2810 }
2811 }
2812
2813 // Process any errors.
2814 if (hasErr) {
2815 processNonLeakError(state, ErrorRange, hasErr, ErrorSym, C);
2816 return;
2817 }
2818
2819 // Consult the summary for the return value.
2820 RetEffect RE = Summ.getRetEffect();
2821
2822 if (RE.getKind() == RetEffect::OwnedWhenTrackedReceiver) {
Jordy Roseb6cfc092011-08-25 00:10:37 +00002823 if (ReceiverIsTracked)
Jordy Rose17a38e22011-09-02 05:55:19 +00002824 RE = getSummaryManager(C).getObjAllocRetEffect();
Jordy Roseb6cfc092011-08-25 00:10:37 +00002825 else
Jordy Rose294396b2011-08-22 23:48:23 +00002826 RE = RetEffect::MakeNoRet();
2827 }
2828
2829 switch (RE.getKind()) {
2830 default:
David Blaikie7530c032012-01-17 06:56:22 +00002831 llvm_unreachable("Unhandled RetEffect.");
Jordy Rose294396b2011-08-22 23:48:23 +00002832
2833 case RetEffect::NoRet:
2834 // No work necessary.
2835 break;
2836
2837 case RetEffect::OwnedAllocatedSymbol:
2838 case RetEffect::OwnedSymbol: {
Ted Kremenek5eca4822012-01-06 22:09:28 +00002839 SymbolRef Sym = state->getSVal(CallOrMsg.getOriginExpr(),
2840 C.getLocationContext()).getAsSymbol();
Jordy Rose294396b2011-08-22 23:48:23 +00002841 if (!Sym)
2842 break;
2843
2844 // Use the result type from callOrMsg as it automatically adjusts
2845 // for methods/functions that return references.
2846 QualType ResultTy = CallOrMsg.getResultType(C.getASTContext());
2847 state = state->set<RefBindings>(Sym, RefVal::makeOwned(RE.getObjKind(),
2848 ResultTy));
2849
2850 // FIXME: Add a flag to the checker where allocations are assumed to
2851 // *not* fail. (The code below is out-of-date, though.)
2852#if 0
2853 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) {
2854 bool isFeasible;
2855 state = state.assume(loc::SymbolVal(Sym), true, isFeasible);
2856 assert(isFeasible && "Cannot assume fresh symbol is non-null.");
2857 }
2858#endif
2859
2860 break;
2861 }
2862
2863 case RetEffect::GCNotOwnedSymbol:
2864 case RetEffect::ARCNotOwnedSymbol:
2865 case RetEffect::NotOwnedSymbol: {
2866 const Expr *Ex = CallOrMsg.getOriginExpr();
Ted Kremenek5eca4822012-01-06 22:09:28 +00002867 SymbolRef Sym = state->getSVal(Ex, C.getLocationContext()).getAsSymbol();
Jordy Rose294396b2011-08-22 23:48:23 +00002868 if (!Sym)
2869 break;
2870
2871 // Use GetReturnType in order to give [NSFoo alloc] the type NSFoo *.
2872 QualType ResultTy = GetReturnType(Ex, C.getASTContext());
2873 state = state->set<RefBindings>(Sym, RefVal::makeNotOwned(RE.getObjKind(),
2874 ResultTy));
2875 break;
2876 }
2877 }
2878
2879 // This check is actually necessary; otherwise the statement builder thinks
2880 // we've hit a previously-found path.
2881 // Normally addTransition takes care of this, but we want the node pointer.
2882 ExplodedNode *NewNode;
2883 if (state == C.getState()) {
2884 NewNode = C.getPredecessor();
2885 } else {
Anna Zaks0bd6b112011-10-26 21:06:34 +00002886 NewNode = C.addTransition(state);
Jordy Rose294396b2011-08-22 23:48:23 +00002887 }
2888
Jordy Rose9c083b72011-08-24 18:56:32 +00002889 // Annotate the node with summary we used.
2890 if (NewNode) {
2891 // FIXME: This is ugly. See checkEndAnalysis for why it's necessary.
2892 if (ShouldResetSummaryLog) {
2893 SummaryLog.clear();
2894 ShouldResetSummaryLog = false;
2895 }
Jordy Roseec9ef852011-08-23 20:55:48 +00002896 SummaryLog[NewNode] = &Summ;
Jordy Rose9c083b72011-08-24 18:56:32 +00002897 }
Jordy Rose294396b2011-08-22 23:48:23 +00002898}
2899
Jordy Rosee0a5d322011-08-23 20:27:16 +00002900
Ted Kremenek8bef8232012-01-26 21:29:00 +00002901ProgramStateRef
2902RetainCountChecker::updateSymbol(ProgramStateRef state, SymbolRef sym,
Jordy Rose910c4052011-09-02 06:44:22 +00002903 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
2904 CheckerContext &C) const {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002905 // In GC mode [... release] and [... retain] do nothing.
Jordy Rose910c4052011-09-02 06:44:22 +00002906 // In ARC mode they shouldn't exist at all, but we just ignore them.
Jordy Rose17a38e22011-09-02 05:55:19 +00002907 bool IgnoreRetainMsg = C.isObjCGCEnabled();
2908 if (!IgnoreRetainMsg)
David Blaikie4e4d0842012-03-11 07:00:24 +00002909 IgnoreRetainMsg = (bool)C.getASTContext().getLangOpts().ObjCAutoRefCount;
Jordy Rose17a38e22011-09-02 05:55:19 +00002910
Jordy Rosee0a5d322011-08-23 20:27:16 +00002911 switch (E) {
2912 default: break;
Jordy Rose17a38e22011-09-02 05:55:19 +00002913 case IncRefMsg: E = IgnoreRetainMsg ? DoNothing : IncRef; break;
2914 case DecRefMsg: E = IgnoreRetainMsg ? DoNothing : DecRef; break;
2915 case MakeCollectable: E = C.isObjCGCEnabled() ? DecRef : DoNothing; break;
2916 case NewAutoreleasePool: E = C.isObjCGCEnabled() ? DoNothing :
2917 NewAutoreleasePool; break;
Jordy Rosee0a5d322011-08-23 20:27:16 +00002918 }
2919
2920 // Handle all use-after-releases.
Jordy Rose17a38e22011-09-02 05:55:19 +00002921 if (!C.isObjCGCEnabled() && V.getKind() == RefVal::Released) {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002922 V = V ^ RefVal::ErrorUseAfterRelease;
2923 hasErr = V.getKind();
2924 return state->set<RefBindings>(sym, V);
2925 }
2926
2927 switch (E) {
2928 case DecRefMsg:
2929 case IncRefMsg:
2930 case MakeCollectable:
2931 llvm_unreachable("DecRefMsg/IncRefMsg/MakeCollectable already converted");
Jordy Rosee0a5d322011-08-23 20:27:16 +00002932
2933 case Dealloc:
2934 // Any use of -dealloc in GC is *bad*.
Jordy Rose17a38e22011-09-02 05:55:19 +00002935 if (C.isObjCGCEnabled()) {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002936 V = V ^ RefVal::ErrorDeallocGC;
2937 hasErr = V.getKind();
2938 break;
2939 }
2940
2941 switch (V.getKind()) {
2942 default:
2943 llvm_unreachable("Invalid RefVal state for an explicit dealloc.");
Jordy Rosee0a5d322011-08-23 20:27:16 +00002944 case RefVal::Owned:
2945 // The object immediately transitions to the released state.
2946 V = V ^ RefVal::Released;
2947 V.clearCounts();
2948 return state->set<RefBindings>(sym, V);
2949 case RefVal::NotOwned:
2950 V = V ^ RefVal::ErrorDeallocNotOwned;
2951 hasErr = V.getKind();
2952 break;
2953 }
2954 break;
2955
2956 case NewAutoreleasePool:
Jordy Rose17a38e22011-09-02 05:55:19 +00002957 assert(!C.isObjCGCEnabled());
Jordy Rosee0a5d322011-08-23 20:27:16 +00002958 return state->add<AutoreleaseStack>(sym);
2959
2960 case MayEscape:
2961 if (V.getKind() == RefVal::Owned) {
2962 V = V ^ RefVal::NotOwned;
2963 break;
2964 }
2965
2966 // Fall-through.
2967
Jordy Rosee0a5d322011-08-23 20:27:16 +00002968 case DoNothing:
2969 return state;
2970
2971 case Autorelease:
Jordy Rose17a38e22011-09-02 05:55:19 +00002972 if (C.isObjCGCEnabled())
Jordy Rosee0a5d322011-08-23 20:27:16 +00002973 return state;
2974
2975 // Update the autorelease counts.
2976 state = SendAutorelease(state, ARCountFactory, sym);
2977 V = V.autorelease();
2978 break;
2979
2980 case StopTracking:
2981 return state->remove<RefBindings>(sym);
2982
2983 case IncRef:
2984 switch (V.getKind()) {
2985 default:
2986 llvm_unreachable("Invalid RefVal state for a retain.");
Jordy Rosee0a5d322011-08-23 20:27:16 +00002987 case RefVal::Owned:
2988 case RefVal::NotOwned:
2989 V = V + 1;
2990 break;
2991 case RefVal::Released:
2992 // Non-GC cases are handled above.
Jordy Rose17a38e22011-09-02 05:55:19 +00002993 assert(C.isObjCGCEnabled());
Jordy Rosee0a5d322011-08-23 20:27:16 +00002994 V = (V ^ RefVal::Owned) + 1;
2995 break;
2996 }
2997 break;
2998
2999 case SelfOwn:
3000 V = V ^ RefVal::NotOwned;
3001 // Fall-through.
3002 case DecRef:
3003 case DecRefBridgedTransfered:
3004 switch (V.getKind()) {
3005 default:
3006 // case 'RefVal::Released' handled above.
3007 llvm_unreachable("Invalid RefVal state for a release.");
Jordy Rosee0a5d322011-08-23 20:27:16 +00003008
3009 case RefVal::Owned:
3010 assert(V.getCount() > 0);
3011 if (V.getCount() == 1)
3012 V = V ^ (E == DecRefBridgedTransfered ?
3013 RefVal::NotOwned : RefVal::Released);
3014 V = V - 1;
3015 break;
3016
3017 case RefVal::NotOwned:
3018 if (V.getCount() > 0)
3019 V = V - 1;
3020 else {
3021 V = V ^ RefVal::ErrorReleaseNotOwned;
3022 hasErr = V.getKind();
3023 }
3024 break;
3025
3026 case RefVal::Released:
3027 // Non-GC cases are handled above.
Jordy Rose17a38e22011-09-02 05:55:19 +00003028 assert(C.isObjCGCEnabled());
Jordy Rosee0a5d322011-08-23 20:27:16 +00003029 V = V ^ RefVal::ErrorUseAfterRelease;
3030 hasErr = V.getKind();
3031 break;
3032 }
3033 break;
3034 }
3035 return state->set<RefBindings>(sym, V);
3036}
3037
Ted Kremenek8bef8232012-01-26 21:29:00 +00003038void RetainCountChecker::processNonLeakError(ProgramStateRef St,
Jordy Rose910c4052011-09-02 06:44:22 +00003039 SourceRange ErrorRange,
3040 RefVal::Kind ErrorKind,
3041 SymbolRef Sym,
3042 CheckerContext &C) const {
Jordy Rose294396b2011-08-22 23:48:23 +00003043 ExplodedNode *N = C.generateSink(St);
3044 if (!N)
3045 return;
3046
Jordy Rose294396b2011-08-22 23:48:23 +00003047 CFRefBug *BT;
3048 switch (ErrorKind) {
3049 default:
3050 llvm_unreachable("Unhandled error.");
Jordy Rose294396b2011-08-22 23:48:23 +00003051 case RefVal::ErrorUseAfterRelease:
Jordy Rosed6334e12011-08-25 00:34:03 +00003052 if (!useAfterRelease)
3053 useAfterRelease.reset(new UseAfterRelease());
3054 BT = &*useAfterRelease;
Jordy Rose294396b2011-08-22 23:48:23 +00003055 break;
3056 case RefVal::ErrorReleaseNotOwned:
Jordy Rosed6334e12011-08-25 00:34:03 +00003057 if (!releaseNotOwned)
3058 releaseNotOwned.reset(new BadRelease());
3059 BT = &*releaseNotOwned;
Jordy Rose294396b2011-08-22 23:48:23 +00003060 break;
3061 case RefVal::ErrorDeallocGC:
Jordy Rosed6334e12011-08-25 00:34:03 +00003062 if (!deallocGC)
3063 deallocGC.reset(new DeallocGC());
3064 BT = &*deallocGC;
Jordy Rose294396b2011-08-22 23:48:23 +00003065 break;
3066 case RefVal::ErrorDeallocNotOwned:
Jordy Rosed6334e12011-08-25 00:34:03 +00003067 if (!deallocNotOwned)
3068 deallocNotOwned.reset(new DeallocNotOwned());
3069 BT = &*deallocNotOwned;
Jordy Rose294396b2011-08-22 23:48:23 +00003070 break;
3071 }
3072
Jordy Rosed6334e12011-08-25 00:34:03 +00003073 assert(BT);
David Blaikie4e4d0842012-03-11 07:00:24 +00003074 CFRefReport *report = new CFRefReport(*BT, C.getASTContext().getLangOpts(),
Jordy Rose17a38e22011-09-02 05:55:19 +00003075 C.isObjCGCEnabled(), SummaryLog,
3076 N, Sym);
Jordy Rose294396b2011-08-22 23:48:23 +00003077 report->addRange(ErrorRange);
3078 C.EmitReport(report);
3079}
3080
Jordy Rose910c4052011-09-02 06:44:22 +00003081//===----------------------------------------------------------------------===//
3082// Handle the return values of retain-count-related functions.
3083//===----------------------------------------------------------------------===//
3084
3085bool RetainCountChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
Jordy Rose76c506f2011-08-21 21:58:18 +00003086 // Get the callee. We're only interested in simple C functions.
Ted Kremenek8bef8232012-01-26 21:29:00 +00003087 ProgramStateRef state = C.getState();
Anna Zaksb805c8f2011-12-01 05:57:37 +00003088 const FunctionDecl *FD = C.getCalleeDecl(CE);
Jordy Rose76c506f2011-08-21 21:58:18 +00003089 if (!FD)
3090 return false;
3091
3092 IdentifierInfo *II = FD->getIdentifier();
3093 if (!II)
3094 return false;
3095
3096 // For now, we're only handling the functions that return aliases of their
3097 // arguments: CFRetain and CFMakeCollectable (and their families).
3098 // Eventually we should add other functions we can model entirely,
3099 // such as CFRelease, which don't invalidate their arguments or globals.
3100 if (CE->getNumArgs() != 1)
3101 return false;
3102
3103 // Get the name of the function.
3104 StringRef FName = II->getName();
3105 FName = FName.substr(FName.find_first_not_of('_'));
3106
3107 // See if it's one of the specific functions we know how to eval.
3108 bool canEval = false;
3109
Anna Zaksb805c8f2011-12-01 05:57:37 +00003110 QualType ResultTy = CE->getCallReturnType();
Jordy Rose76c506f2011-08-21 21:58:18 +00003111 if (ResultTy->isObjCIdType()) {
3112 // Handle: id NSMakeCollectable(CFTypeRef)
3113 canEval = II->isStr("NSMakeCollectable");
3114 } else if (ResultTy->isPointerType()) {
3115 // Handle: (CF|CG)Retain
3116 // CFMakeCollectable
3117 // It's okay to be a little sloppy here (CGMakeCollectable doesn't exist).
3118 if (cocoa::isRefType(ResultTy, "CF", FName) ||
3119 cocoa::isRefType(ResultTy, "CG", FName)) {
3120 canEval = isRetain(FD, FName) || isMakeCollectable(FD, FName);
3121 }
3122 }
3123
3124 if (!canEval)
3125 return false;
3126
3127 // Bind the return value.
Ted Kremenek5eca4822012-01-06 22:09:28 +00003128 const LocationContext *LCtx = C.getLocationContext();
3129 SVal RetVal = state->getSVal(CE->getArg(0), LCtx);
Jordy Rose76c506f2011-08-21 21:58:18 +00003130 if (RetVal.isUnknown()) {
3131 // If the receiver is unknown, conjure a return value.
3132 SValBuilder &SVB = C.getSValBuilder();
Anna Zaks5d0ea6d2011-10-04 20:43:05 +00003133 unsigned Count = C.getCurrentBlockCount();
Ted Kremenek3133f792012-02-17 23:13:45 +00003134 SVal RetVal = SVB.getConjuredSymbolVal(0, CE, LCtx, ResultTy, Count);
Jordy Rose76c506f2011-08-21 21:58:18 +00003135 }
Ted Kremenek5eca4822012-01-06 22:09:28 +00003136 state = state->BindExpr(CE, LCtx, RetVal, false);
Jordy Rose76c506f2011-08-21 21:58:18 +00003137
Jordy Rose294396b2011-08-22 23:48:23 +00003138 // FIXME: This should not be necessary, but otherwise the argument seems to be
3139 // considered alive during the next statement.
3140 if (const MemRegion *ArgRegion = RetVal.getAsRegion()) {
3141 // Save the refcount status of the argument.
3142 SymbolRef Sym = RetVal.getAsLocSymbol();
3143 RefBindings::data_type *Binding = 0;
3144 if (Sym)
3145 Binding = state->get<RefBindings>(Sym);
Jordy Rose76c506f2011-08-21 21:58:18 +00003146
Jordy Rose294396b2011-08-22 23:48:23 +00003147 // Invalidate the argument region.
Anna Zaks5d0ea6d2011-10-04 20:43:05 +00003148 unsigned Count = C.getCurrentBlockCount();
Ted Kremenek3133f792012-02-17 23:13:45 +00003149 state = state->invalidateRegions(ArgRegion, CE, Count, LCtx);
Jordy Rose76c506f2011-08-21 21:58:18 +00003150
Jordy Rose294396b2011-08-22 23:48:23 +00003151 // Restore the refcount status of the argument.
3152 if (Binding)
3153 state = state->set<RefBindings>(Sym, *Binding);
3154 }
3155
Anna Zaks0bd6b112011-10-26 21:06:34 +00003156 C.addTransition(state);
Jordy Rose76c506f2011-08-21 21:58:18 +00003157 return true;
3158}
3159
Jordy Rose910c4052011-09-02 06:44:22 +00003160//===----------------------------------------------------------------------===//
3161// Handle return statements.
3162//===----------------------------------------------------------------------===//
Jordy Rosef53e8c72011-08-23 19:43:16 +00003163
Ted Kremeneke5715782012-02-25 02:09:09 +00003164// Return true if the current LocationContext has no caller context.
3165static bool inTopFrame(CheckerContext &C) {
3166 const LocationContext *LC = C.getLocationContext();
3167 return LC->getParent() == 0;
3168}
3169
Jordy Rose910c4052011-09-02 06:44:22 +00003170void RetainCountChecker::checkPreStmt(const ReturnStmt *S,
3171 CheckerContext &C) const {
Ted Kremeneke5715782012-02-25 02:09:09 +00003172
3173 // Only adjust the reference count if this is the top-level call frame,
3174 // and not the result of inlining. In the future, we should do
3175 // better checking even for inlined calls, and see if they match
3176 // with their expected semantics (e.g., the method should return a retained
3177 // object, etc.).
3178 if (!inTopFrame(C))
3179 return;
3180
Jordy Rosef53e8c72011-08-23 19:43:16 +00003181 const Expr *RetE = S->getRetValue();
3182 if (!RetE)
3183 return;
3184
Ted Kremenek8bef8232012-01-26 21:29:00 +00003185 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00003186 SymbolRef Sym =
3187 state->getSValAsScalarOrLoc(RetE, C.getLocationContext()).getAsLocSymbol();
Jordy Rosef53e8c72011-08-23 19:43:16 +00003188 if (!Sym)
3189 return;
3190
3191 // Get the reference count binding (if any).
3192 const RefVal *T = state->get<RefBindings>(Sym);
3193 if (!T)
3194 return;
3195
3196 // Change the reference count.
3197 RefVal X = *T;
3198
3199 switch (X.getKind()) {
3200 case RefVal::Owned: {
3201 unsigned cnt = X.getCount();
3202 assert(cnt > 0);
3203 X.setCount(cnt - 1);
3204 X = X ^ RefVal::ReturnedOwned;
3205 break;
3206 }
3207
3208 case RefVal::NotOwned: {
3209 unsigned cnt = X.getCount();
3210 if (cnt) {
3211 X.setCount(cnt - 1);
3212 X = X ^ RefVal::ReturnedOwned;
3213 }
3214 else {
3215 X = X ^ RefVal::ReturnedNotOwned;
3216 }
3217 break;
3218 }
3219
3220 default:
3221 return;
3222 }
3223
3224 // Update the binding.
3225 state = state->set<RefBindings>(Sym, X);
Anna Zaks0bd6b112011-10-26 21:06:34 +00003226 ExplodedNode *Pred = C.addTransition(state);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003227
3228 // At this point we have updated the state properly.
3229 // Everything after this is merely checking to see if the return value has
3230 // been over- or under-retained.
3231
3232 // Did we cache out?
3233 if (!Pred)
3234 return;
3235
Jordy Rosef53e8c72011-08-23 19:43:16 +00003236 // Update the autorelease counts.
3237 static SimpleProgramPointTag
Jordy Rose910c4052011-09-02 06:44:22 +00003238 AutoreleaseTag("RetainCountChecker : Autorelease");
Anna Zaks4eff8232011-10-05 23:44:11 +00003239 GenericNodeBuilderRefCount Bd(C, &AutoreleaseTag);
Anna Zaks6a93bd52011-10-25 19:57:11 +00003240 llvm::tie(Pred, state) = handleAutoreleaseCounts(state, Bd, Pred, C, Sym, X);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003241
3242 // Did we cache out?
Jordy Rose8d228632011-08-23 20:07:14 +00003243 if (!Pred)
Jordy Rosef53e8c72011-08-23 19:43:16 +00003244 return;
3245
3246 // Get the updated binding.
3247 T = state->get<RefBindings>(Sym);
3248 assert(T);
3249 X = *T;
3250
3251 // Consult the summary of the enclosing method.
Jordy Rose17a38e22011-09-02 05:55:19 +00003252 RetainSummaryManager &Summaries = getSummaryManager(C);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003253 const Decl *CD = &Pred->getCodeDecl();
3254
3255 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CD)) {
3256 // Unlike regular functions, /all/ ObjC methods are assumed to always
3257 // follow Cocoa retain-count conventions, not just those with special
3258 // names or attributes.
Jordy Roseb6cfc092011-08-25 00:10:37 +00003259 const RetainSummary *Summ = Summaries.getMethodSummary(MD);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003260 RetEffect RE = Summ ? Summ->getRetEffect() : RetEffect::MakeNoRet();
3261 checkReturnWithRetEffect(S, C, Pred, RE, X, Sym, state);
3262 }
3263
3264 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) {
3265 if (!isa<CXXMethodDecl>(FD))
Jordy Roseb6cfc092011-08-25 00:10:37 +00003266 if (const RetainSummary *Summ = Summaries.getSummary(FD))
Jordy Rosef53e8c72011-08-23 19:43:16 +00003267 checkReturnWithRetEffect(S, C, Pred, Summ->getRetEffect(), X,
3268 Sym, state);
3269 }
3270}
3271
Jordy Rose910c4052011-09-02 06:44:22 +00003272void RetainCountChecker::checkReturnWithRetEffect(const ReturnStmt *S,
3273 CheckerContext &C,
3274 ExplodedNode *Pred,
3275 RetEffect RE, RefVal X,
3276 SymbolRef Sym,
Ted Kremenek8bef8232012-01-26 21:29:00 +00003277 ProgramStateRef state) const {
Jordy Rosef53e8c72011-08-23 19:43:16 +00003278 // Any leaks or other errors?
3279 if (X.isReturnedOwned() && X.getCount() == 0) {
3280 if (RE.getKind() != RetEffect::NoRet) {
3281 bool hasError = false;
Jordy Rose17a38e22011-09-02 05:55:19 +00003282 if (C.isObjCGCEnabled() && RE.getObjKind() == RetEffect::ObjC) {
Jordy Rosef53e8c72011-08-23 19:43:16 +00003283 // Things are more complicated with garbage collection. If the
3284 // returned object is suppose to be an Objective-C object, we have
3285 // a leak (as the caller expects a GC'ed object) because no
3286 // method should return ownership unless it returns a CF object.
3287 hasError = true;
3288 X = X ^ RefVal::ErrorGCLeakReturned;
3289 }
3290 else if (!RE.isOwned()) {
3291 // Either we are using GC and the returned object is a CF type
3292 // or we aren't using GC. In either case, we expect that the
3293 // enclosing method is expected to return ownership.
3294 hasError = true;
3295 X = X ^ RefVal::ErrorLeakReturned;
3296 }
3297
3298 if (hasError) {
3299 // Generate an error node.
3300 state = state->set<RefBindings>(Sym, X);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003301
3302 static SimpleProgramPointTag
Jordy Rose910c4052011-09-02 06:44:22 +00003303 ReturnOwnLeakTag("RetainCountChecker : ReturnsOwnLeak");
Anna Zaks0bd6b112011-10-26 21:06:34 +00003304 ExplodedNode *N = C.addTransition(state, Pred, &ReturnOwnLeakTag);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003305 if (N) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003306 const LangOptions &LOpts = C.getASTContext().getLangOpts();
Jordy Rose17a38e22011-09-02 05:55:19 +00003307 bool GCEnabled = C.isObjCGCEnabled();
Jordy Rosef53e8c72011-08-23 19:43:16 +00003308 CFRefReport *report =
Jordy Rose17a38e22011-09-02 05:55:19 +00003309 new CFRefLeakReport(*getLeakAtReturnBug(LOpts, GCEnabled),
3310 LOpts, GCEnabled, SummaryLog,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003311 N, Sym, C);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003312 C.EmitReport(report);
3313 }
3314 }
3315 }
3316 } else if (X.isReturnedNotOwned()) {
3317 if (RE.isOwned()) {
3318 // Trying to return a not owned object to a caller expecting an
3319 // owned object.
3320 state = state->set<RefBindings>(Sym, X ^ RefVal::ErrorReturnedNotOwned);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003321
3322 static SimpleProgramPointTag
Jordy Rose910c4052011-09-02 06:44:22 +00003323 ReturnNotOwnedTag("RetainCountChecker : ReturnNotOwnedForOwned");
Anna Zaks0bd6b112011-10-26 21:06:34 +00003324 ExplodedNode *N = C.addTransition(state, Pred, &ReturnNotOwnedTag);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003325 if (N) {
Jordy Rosed6334e12011-08-25 00:34:03 +00003326 if (!returnNotOwnedForOwned)
3327 returnNotOwnedForOwned.reset(new ReturnedNotOwnedForOwned());
3328
Jordy Rosef53e8c72011-08-23 19:43:16 +00003329 CFRefReport *report =
Jordy Rosed6334e12011-08-25 00:34:03 +00003330 new CFRefReport(*returnNotOwnedForOwned,
David Blaikie4e4d0842012-03-11 07:00:24 +00003331 C.getASTContext().getLangOpts(),
Jordy Rose17a38e22011-09-02 05:55:19 +00003332 C.isObjCGCEnabled(), SummaryLog, N, Sym);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003333 C.EmitReport(report);
3334 }
3335 }
3336 }
3337}
3338
Jordy Rose8d228632011-08-23 20:07:14 +00003339//===----------------------------------------------------------------------===//
Jordy Rose910c4052011-09-02 06:44:22 +00003340// Check various ways a symbol can be invalidated.
3341//===----------------------------------------------------------------------===//
3342
Anna Zaks390909c2011-10-06 00:43:15 +00003343void RetainCountChecker::checkBind(SVal loc, SVal val, const Stmt *S,
Jordy Rose910c4052011-09-02 06:44:22 +00003344 CheckerContext &C) const {
3345 // Are we storing to something that causes the value to "escape"?
3346 bool escapes = true;
3347
3348 // A value escapes in three possible cases (this may change):
3349 //
3350 // (1) we are binding to something that is not a memory region.
3351 // (2) we are binding to a memregion that does not have stack storage
3352 // (3) we are binding to a memregion with stack storage that the store
3353 // does not understand.
Ted Kremenek8bef8232012-01-26 21:29:00 +00003354 ProgramStateRef state = C.getState();
Jordy Rose910c4052011-09-02 06:44:22 +00003355
3356 if (loc::MemRegionVal *regionLoc = dyn_cast<loc::MemRegionVal>(&loc)) {
3357 escapes = !regionLoc->getRegion()->hasStackStorage();
3358
3359 if (!escapes) {
3360 // To test (3), generate a new state with the binding added. If it is
3361 // the same state, then it escapes (since the store cannot represent
3362 // the binding).
3363 escapes = (state == (state->bindLoc(*regionLoc, val)));
3364 }
3365 }
3366
3367 // If our store can represent the binding and we aren't storing to something
3368 // that doesn't have local storage then just return and have the simulation
3369 // state continue as is.
3370 if (!escapes)
3371 return;
3372
3373 // Otherwise, find all symbols referenced by 'val' that we are tracking
3374 // and stop tracking them.
3375 state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
Anna Zaks0bd6b112011-10-26 21:06:34 +00003376 C.addTransition(state);
Jordy Rose910c4052011-09-02 06:44:22 +00003377}
3378
Ted Kremenek8bef8232012-01-26 21:29:00 +00003379ProgramStateRef RetainCountChecker::evalAssume(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003380 SVal Cond,
3381 bool Assumption) const {
3382
3383 // FIXME: We may add to the interface of evalAssume the list of symbols
3384 // whose assumptions have changed. For now we just iterate through the
3385 // bindings and check if any of the tracked symbols are NULL. This isn't
3386 // too bad since the number of symbols we will track in practice are
3387 // probably small and evalAssume is only called at branches and a few
3388 // other places.
3389 RefBindings B = state->get<RefBindings>();
3390
3391 if (B.isEmpty())
3392 return state;
3393
3394 bool changed = false;
3395 RefBindings::Factory &RefBFactory = state->get_context<RefBindings>();
3396
3397 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
3398 // Check if the symbol is null (or equal to any constant).
3399 // If this is the case, stop tracking the symbol.
3400 if (state->getSymVal(I.getKey())) {
3401 changed = true;
3402 B = RefBFactory.remove(B, I.getKey());
3403 }
3404 }
3405
3406 if (changed)
3407 state = state->set<RefBindings>(B);
3408
3409 return state;
3410}
3411
Ted Kremenek8bef8232012-01-26 21:29:00 +00003412ProgramStateRef
3413RetainCountChecker::checkRegionChanges(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003414 const StoreManager::InvalidatedSymbols *invalidated,
3415 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00003416 ArrayRef<const MemRegion *> Regions,
3417 const CallOrObjCMessage *Call) const {
Jordy Rose910c4052011-09-02 06:44:22 +00003418 if (!invalidated)
3419 return state;
3420
3421 llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
3422 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
3423 E = ExplicitRegions.end(); I != E; ++I) {
3424 if (const SymbolicRegion *SR = (*I)->StripCasts()->getAs<SymbolicRegion>())
3425 WhitelistedSymbols.insert(SR->getSymbol());
3426 }
3427
3428 for (StoreManager::InvalidatedSymbols::const_iterator I=invalidated->begin(),
3429 E = invalidated->end(); I!=E; ++I) {
3430 SymbolRef sym = *I;
3431 if (WhitelistedSymbols.count(sym))
3432 continue;
3433 // Remove any existing reference-count binding.
3434 state = state->remove<RefBindings>(sym);
3435 }
3436 return state;
3437}
3438
3439//===----------------------------------------------------------------------===//
Jordy Rose8d228632011-08-23 20:07:14 +00003440// Handle dead symbols and end-of-path.
3441//===----------------------------------------------------------------------===//
3442
Ted Kremenek8bef8232012-01-26 21:29:00 +00003443std::pair<ExplodedNode *, ProgramStateRef >
3444RetainCountChecker::handleAutoreleaseCounts(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003445 GenericNodeBuilderRefCount Bd,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003446 ExplodedNode *Pred,
3447 CheckerContext &Ctx,
Jordy Rose910c4052011-09-02 06:44:22 +00003448 SymbolRef Sym, RefVal V) const {
Jordy Rose8d228632011-08-23 20:07:14 +00003449 unsigned ACnt = V.getAutoreleaseCount();
3450
3451 // No autorelease counts? Nothing to be done.
3452 if (!ACnt)
3453 return std::make_pair(Pred, state);
3454
Anna Zaks6a93bd52011-10-25 19:57:11 +00003455 assert(!Ctx.isObjCGCEnabled() && "Autorelease counts in GC mode?");
Jordy Rose8d228632011-08-23 20:07:14 +00003456 unsigned Cnt = V.getCount();
3457
3458 // FIXME: Handle sending 'autorelease' to already released object.
3459
3460 if (V.getKind() == RefVal::ReturnedOwned)
3461 ++Cnt;
3462
3463 if (ACnt <= Cnt) {
3464 if (ACnt == Cnt) {
3465 V.clearCounts();
3466 if (V.getKind() == RefVal::ReturnedOwned)
3467 V = V ^ RefVal::ReturnedNotOwned;
3468 else
3469 V = V ^ RefVal::NotOwned;
3470 } else {
3471 V.setCount(Cnt - ACnt);
3472 V.setAutoreleaseCount(0);
3473 }
3474 state = state->set<RefBindings>(Sym, V);
3475 ExplodedNode *N = Bd.MakeNode(state, Pred);
3476 if (N == 0)
3477 state = 0;
3478 return std::make_pair(N, state);
3479 }
3480
3481 // Woah! More autorelease counts then retain counts left.
3482 // Emit hard error.
3483 V = V ^ RefVal::ErrorOverAutorelease;
3484 state = state->set<RefBindings>(Sym, V);
3485
Anna Zaksf05aac82011-10-18 23:05:58 +00003486 if (ExplodedNode *N = Bd.MakeNode(state, Pred, true)) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003487 SmallString<128> sbuf;
Jordy Rose8d228632011-08-23 20:07:14 +00003488 llvm::raw_svector_ostream os(sbuf);
3489 os << "Object over-autoreleased: object was sent -autorelease ";
3490 if (V.getAutoreleaseCount() > 1)
3491 os << V.getAutoreleaseCount() << " times ";
3492 os << "but the object has a +" << V.getCount() << " retain count";
3493
Jordy Rosed6334e12011-08-25 00:34:03 +00003494 if (!overAutorelease)
3495 overAutorelease.reset(new OverAutorelease());
3496
David Blaikie4e4d0842012-03-11 07:00:24 +00003497 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
Jordy Rose8d228632011-08-23 20:07:14 +00003498 CFRefReport *report =
Jordy Rosed6334e12011-08-25 00:34:03 +00003499 new CFRefReport(*overAutorelease, LOpts, /* GCEnabled = */ false,
3500 SummaryLog, N, Sym, os.str());
Anna Zaks6a93bd52011-10-25 19:57:11 +00003501 Ctx.EmitReport(report);
Jordy Rose8d228632011-08-23 20:07:14 +00003502 }
3503
Ted Kremenek8bef8232012-01-26 21:29:00 +00003504 return std::make_pair((ExplodedNode *)0, (ProgramStateRef )0);
Jordy Rose8d228632011-08-23 20:07:14 +00003505}
Jordy Rose38f17d62011-08-23 19:01:07 +00003506
Ted Kremenek8bef8232012-01-26 21:29:00 +00003507ProgramStateRef
3508RetainCountChecker::handleSymbolDeath(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003509 SymbolRef sid, RefVal V,
Jordy Rose38f17d62011-08-23 19:01:07 +00003510 SmallVectorImpl<SymbolRef> &Leaked) const {
Jordy Rose53376122011-08-24 04:48:19 +00003511 bool hasLeak = false;
Jordy Rose38f17d62011-08-23 19:01:07 +00003512 if (V.isOwned())
3513 hasLeak = true;
3514 else if (V.isNotOwned() || V.isReturnedOwned())
3515 hasLeak = (V.getCount() > 0);
3516
3517 if (!hasLeak)
3518 return state->remove<RefBindings>(sid);
3519
3520 Leaked.push_back(sid);
3521 return state->set<RefBindings>(sid, V ^ RefVal::ErrorLeak);
3522}
3523
3524ExplodedNode *
Ted Kremenek8bef8232012-01-26 21:29:00 +00003525RetainCountChecker::processLeaks(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003526 SmallVectorImpl<SymbolRef> &Leaked,
3527 GenericNodeBuilderRefCount &Builder,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003528 CheckerContext &Ctx,
3529 ExplodedNode *Pred) const {
Jordy Rose38f17d62011-08-23 19:01:07 +00003530 if (Leaked.empty())
3531 return Pred;
3532
3533 // Generate an intermediate node representing the leak point.
3534 ExplodedNode *N = Builder.MakeNode(state, Pred);
3535
3536 if (N) {
3537 for (SmallVectorImpl<SymbolRef>::iterator
3538 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3539
David Blaikie4e4d0842012-03-11 07:00:24 +00003540 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
Anna Zaks6a93bd52011-10-25 19:57:11 +00003541 bool GCEnabled = Ctx.isObjCGCEnabled();
Jordy Rose17a38e22011-09-02 05:55:19 +00003542 CFRefBug *BT = Pred ? getLeakWithinFunctionBug(LOpts, GCEnabled)
3543 : getLeakAtReturnBug(LOpts, GCEnabled);
Jordy Rose38f17d62011-08-23 19:01:07 +00003544 assert(BT && "BugType not initialized.");
Jordy Rose20589562011-08-24 22:39:09 +00003545
Jordy Rose17a38e22011-09-02 05:55:19 +00003546 CFRefLeakReport *report = new CFRefLeakReport(*BT, LOpts, GCEnabled,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003547 SummaryLog, N, *I, Ctx);
3548 Ctx.EmitReport(report);
Jordy Rose38f17d62011-08-23 19:01:07 +00003549 }
3550 }
3551
3552 return N;
3553}
3554
Anna Zaksaf498a22011-10-25 19:56:48 +00003555void RetainCountChecker::checkEndPath(CheckerContext &Ctx) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +00003556 ProgramStateRef state = Ctx.getState();
Anna Zaksaf498a22011-10-25 19:56:48 +00003557 GenericNodeBuilderRefCount Bd(Ctx);
Jordy Rose38f17d62011-08-23 19:01:07 +00003558 RefBindings B = state->get<RefBindings>();
Anna Zaksaf498a22011-10-25 19:56:48 +00003559 ExplodedNode *Pred = Ctx.getPredecessor();
Jordy Rose38f17d62011-08-23 19:01:07 +00003560
3561 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Anna Zaks6a93bd52011-10-25 19:57:11 +00003562 llvm::tie(Pred, state) = handleAutoreleaseCounts(state, Bd, Pred, Ctx,
Jordy Rose8d228632011-08-23 20:07:14 +00003563 I->first, I->second);
3564 if (!state)
Jordy Rose38f17d62011-08-23 19:01:07 +00003565 return;
3566 }
3567
Ted Kremenek0cf3d472012-02-07 00:24:33 +00003568 // If the current LocationContext has a parent, don't check for leaks.
3569 // We will do that later.
3570 // FIXME: we should instead check for imblances of the retain/releases,
3571 // and suggest annotations.
3572 if (Ctx.getLocationContext()->getParent())
3573 return;
3574
Jordy Rose38f17d62011-08-23 19:01:07 +00003575 B = state->get<RefBindings>();
3576 SmallVector<SymbolRef, 10> Leaked;
3577
3578 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I)
Jordy Rose8d228632011-08-23 20:07:14 +00003579 state = handleSymbolDeath(state, I->first, I->second, Leaked);
Jordy Rose38f17d62011-08-23 19:01:07 +00003580
Anna Zaks6a93bd52011-10-25 19:57:11 +00003581 processLeaks(state, Leaked, Bd, Ctx, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003582}
3583
3584const ProgramPointTag *
Jordy Rose910c4052011-09-02 06:44:22 +00003585RetainCountChecker::getDeadSymbolTag(SymbolRef sym) const {
Jordy Rose38f17d62011-08-23 19:01:07 +00003586 const SimpleProgramPointTag *&tag = DeadSymbolTags[sym];
3587 if (!tag) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003588 SmallString<64> buf;
Jordy Rose38f17d62011-08-23 19:01:07 +00003589 llvm::raw_svector_ostream out(buf);
Anna Zaksf62ceec2011-12-05 18:58:11 +00003590 out << "RetainCountChecker : Dead Symbol : ";
3591 sym->dumpToStream(out);
Jordy Rose38f17d62011-08-23 19:01:07 +00003592 tag = new SimpleProgramPointTag(out.str());
3593 }
3594 return tag;
3595}
3596
Jordy Rose910c4052011-09-02 06:44:22 +00003597void RetainCountChecker::checkDeadSymbols(SymbolReaper &SymReaper,
3598 CheckerContext &C) const {
Jordy Rose38f17d62011-08-23 19:01:07 +00003599 ExplodedNode *Pred = C.getPredecessor();
3600
Ted Kremenek8bef8232012-01-26 21:29:00 +00003601 ProgramStateRef state = C.getState();
Jordy Rose38f17d62011-08-23 19:01:07 +00003602 RefBindings B = state->get<RefBindings>();
3603
3604 // Update counts from autorelease pools
3605 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3606 E = SymReaper.dead_end(); I != E; ++I) {
3607 SymbolRef Sym = *I;
3608 if (const RefVal *T = B.lookup(Sym)){
3609 // Use the symbol as the tag.
3610 // FIXME: This might not be as unique as we would like.
Anna Zaks4eff8232011-10-05 23:44:11 +00003611 GenericNodeBuilderRefCount Bd(C, getDeadSymbolTag(Sym));
Anna Zaks6a93bd52011-10-25 19:57:11 +00003612 llvm::tie(Pred, state) = handleAutoreleaseCounts(state, Bd, Pred, C,
Jordy Rose8d228632011-08-23 20:07:14 +00003613 Sym, *T);
3614 if (!state)
Jordy Rose38f17d62011-08-23 19:01:07 +00003615 return;
3616 }
3617 }
3618
3619 B = state->get<RefBindings>();
3620 SmallVector<SymbolRef, 10> Leaked;
3621
3622 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3623 E = SymReaper.dead_end(); I != E; ++I) {
3624 if (const RefVal *T = B.lookup(*I))
3625 state = handleSymbolDeath(state, *I, *T, Leaked);
3626 }
3627
3628 {
Anna Zaks4eff8232011-10-05 23:44:11 +00003629 GenericNodeBuilderRefCount Bd(C, this);
Anna Zaks6a93bd52011-10-25 19:57:11 +00003630 Pred = processLeaks(state, Leaked, Bd, C, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003631 }
3632
3633 // Did we cache out?
3634 if (!Pred)
3635 return;
3636
3637 // Now generate a new node that nukes the old bindings.
3638 RefBindings::Factory &F = state->get_context<RefBindings>();
3639
3640 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3641 E = SymReaper.dead_end(); I != E; ++I)
3642 B = F.remove(B, *I);
3643
3644 state = state->set<RefBindings>(B);
Anna Zaks0bd6b112011-10-26 21:06:34 +00003645 C.addTransition(state, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003646}
3647
Ted Kremenekd593eb92009-11-25 22:17:44 +00003648//===----------------------------------------------------------------------===//
Jordy Rosedbd658e2011-08-28 19:11:56 +00003649// Debug printing of refcount bindings and autorelease pools.
3650//===----------------------------------------------------------------------===//
3651
3652static void PrintPool(raw_ostream &Out, SymbolRef Sym,
Ted Kremenek8bef8232012-01-26 21:29:00 +00003653 ProgramStateRef State) {
Jordy Rosedbd658e2011-08-28 19:11:56 +00003654 Out << ' ';
3655 if (Sym)
Anna Zaksf62ceec2011-12-05 18:58:11 +00003656 Sym->dumpToStream(Out);
Jordy Rosedbd658e2011-08-28 19:11:56 +00003657 else
3658 Out << "<pool>";
3659 Out << ":{";
3660
3661 // Get the contents of the pool.
3662 if (const ARCounts *Cnts = State->get<AutoreleasePoolContents>(Sym))
3663 for (ARCounts::iterator I = Cnts->begin(), E = Cnts->end(); I != E; ++I)
3664 Out << '(' << I.getKey() << ',' << I.getData() << ')';
3665
3666 Out << '}';
3667}
3668
Ted Kremenek8bef8232012-01-26 21:29:00 +00003669static bool UsesAutorelease(ProgramStateRef state) {
Jordy Rosedbd658e2011-08-28 19:11:56 +00003670 // A state uses autorelease if it allocated an autorelease pool or if it has
3671 // objects in the caller's autorelease pool.
3672 return !state->get<AutoreleaseStack>().isEmpty() ||
3673 state->get<AutoreleasePoolContents>(SymbolRef());
3674}
3675
Ted Kremenek8bef8232012-01-26 21:29:00 +00003676void RetainCountChecker::printState(raw_ostream &Out, ProgramStateRef State,
Jordy Rose910c4052011-09-02 06:44:22 +00003677 const char *NL, const char *Sep) const {
Jordy Rosedbd658e2011-08-28 19:11:56 +00003678
3679 RefBindings B = State->get<RefBindings>();
3680
3681 if (!B.isEmpty())
3682 Out << Sep << NL;
3683
3684 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
3685 Out << I->first << " : ";
3686 I->second.print(Out);
3687 Out << NL;
3688 }
3689
3690 // Print the autorelease stack.
3691 if (UsesAutorelease(State)) {
3692 Out << Sep << NL << "AR pool stack:";
3693 ARStack Stack = State->get<AutoreleaseStack>();
3694
3695 PrintPool(Out, SymbolRef(), State); // Print the caller's pool.
3696 for (ARStack::iterator I = Stack.begin(), E = Stack.end(); I != E; ++I)
3697 PrintPool(Out, *I, State);
3698
3699 Out << NL;
3700 }
3701}
3702
3703//===----------------------------------------------------------------------===//
Jordy Rose910c4052011-09-02 06:44:22 +00003704// Checker registration.
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00003705//===----------------------------------------------------------------------===//
3706
Jordy Rose17a38e22011-09-02 05:55:19 +00003707void ento::registerRetainCountChecker(CheckerManager &Mgr) {
Jordy Rose910c4052011-09-02 06:44:22 +00003708 Mgr.registerChecker<RetainCountChecker>();
Jordy Rose17a38e22011-09-02 05:55:19 +00003709}
3710