blob: 2a97e1c24a72a07add17c94008e7782df25c7c06 [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 }
Jordy Roseef945882012-03-18 01:26:10 +0000135
136 void Profile(llvm::FoldingSetNodeID& ID) const {
137 ID.AddInteger((unsigned) K);
138 ID.AddInteger((unsigned) O);
139 }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000140};
Mike Stump1eb44332009-09-09 15:08:12 +0000141
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000142//===----------------------------------------------------------------------===//
143// Reference-counting logic (typestate + counts).
144//===----------------------------------------------------------------------===//
Mike Stump1eb44332009-09-09 15:08:12 +0000145
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000146class RefVal {
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000147public:
148 enum Kind {
149 Owned = 0, // Owning reference.
150 NotOwned, // Reference is not owned by still valid (not freed).
151 Released, // Object has been released.
152 ReturnedOwned, // Returned object passes ownership to caller.
153 ReturnedNotOwned, // Return object does not pass ownership to caller.
154 ERROR_START,
155 ErrorDeallocNotOwned, // -dealloc called on non-owned object.
156 ErrorDeallocGC, // Calling -dealloc with GC enabled.
157 ErrorUseAfterRelease, // Object used after released.
158 ErrorReleaseNotOwned, // Release of an object that was not owned.
159 ERROR_LEAK_START,
160 ErrorLeak, // A memory leak due to excessive reference counts.
161 ErrorLeakReturned, // A memory leak due to the returning method not having
162 // the correct naming conventions.
163 ErrorGCLeakReturned,
164 ErrorOverAutorelease,
165 ErrorReturnedNotOwned
166 };
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000167
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000168private:
169 Kind kind;
170 RetEffect::ObjKind okind;
171 unsigned Cnt;
172 unsigned ACnt;
173 QualType T;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000174
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000175 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, unsigned acnt, QualType t)
176 : kind(k), okind(o), Cnt(cnt), ACnt(acnt), T(t) {}
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000177
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000178public:
179 Kind getKind() const { return kind; }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000180
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000181 RetEffect::ObjKind getObjKind() const { return okind; }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000182
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000183 unsigned getCount() const { return Cnt; }
184 unsigned getAutoreleaseCount() const { return ACnt; }
185 unsigned getCombinedCounts() const { return Cnt + ACnt; }
186 void clearCounts() { Cnt = 0; ACnt = 0; }
187 void setCount(unsigned i) { Cnt = i; }
188 void setAutoreleaseCount(unsigned i) { ACnt = i; }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000189
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000190 QualType getType() const { return T; }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000191
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000192 bool isOwned() const {
193 return getKind() == Owned;
194 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000195
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000196 bool isNotOwned() const {
197 return getKind() == NotOwned;
198 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000199
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000200 bool isReturnedOwned() const {
201 return getKind() == ReturnedOwned;
202 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000203
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000204 bool isReturnedNotOwned() const {
205 return getKind() == ReturnedNotOwned;
206 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000207
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000208 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
209 unsigned Count = 1) {
210 return RefVal(Owned, o, Count, 0, t);
211 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000212
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000213 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
214 unsigned Count = 0) {
215 return RefVal(NotOwned, o, Count, 0, t);
216 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000217
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000218 // Comparison, profiling, and pretty-printing.
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000219
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000220 bool operator==(const RefVal& X) const {
221 return kind == X.kind && Cnt == X.Cnt && T == X.T && ACnt == X.ACnt;
222 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000223
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000224 RefVal operator-(size_t i) const {
225 return RefVal(getKind(), getObjKind(), getCount() - i,
226 getAutoreleaseCount(), getType());
227 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000228
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000229 RefVal operator+(size_t i) const {
230 return RefVal(getKind(), getObjKind(), getCount() + i,
231 getAutoreleaseCount(), getType());
232 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000233
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000234 RefVal operator^(Kind k) const {
235 return RefVal(k, getObjKind(), getCount(), getAutoreleaseCount(),
236 getType());
237 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000238
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000239 RefVal autorelease() const {
240 return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount()+1,
241 getType());
242 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000243
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000244 void Profile(llvm::FoldingSetNodeID& ID) const {
245 ID.AddInteger((unsigned) kind);
246 ID.AddInteger(Cnt);
247 ID.AddInteger(ACnt);
248 ID.Add(T);
249 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000250
Ted Kremenek9c378f72011-08-12 23:37:29 +0000251 void print(raw_ostream &Out) const;
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000252};
253
Ted Kremenek9c378f72011-08-12 23:37:29 +0000254void RefVal::print(raw_ostream &Out) const {
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000255 if (!T.isNull())
Jordy Rosedbd658e2011-08-28 19:11:56 +0000256 Out << "Tracked " << T.getAsString() << '/';
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000257
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000258 switch (getKind()) {
Jordy Rose910c4052011-09-02 06:44:22 +0000259 default: llvm_unreachable("Invalid RefVal kind");
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000260 case Owned: {
261 Out << "Owned";
262 unsigned cnt = getCount();
263 if (cnt) Out << " (+ " << cnt << ")";
264 break;
265 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000266
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000267 case NotOwned: {
268 Out << "NotOwned";
269 unsigned cnt = getCount();
270 if (cnt) Out << " (+ " << cnt << ")";
271 break;
272 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000273
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000274 case ReturnedOwned: {
275 Out << "ReturnedOwned";
276 unsigned cnt = getCount();
277 if (cnt) Out << " (+ " << cnt << ")";
278 break;
279 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000280
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000281 case ReturnedNotOwned: {
282 Out << "ReturnedNotOwned";
283 unsigned cnt = getCount();
284 if (cnt) Out << " (+ " << cnt << ")";
285 break;
286 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000287
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000288 case Released:
289 Out << "Released";
290 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000291
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000292 case ErrorDeallocGC:
293 Out << "-dealloc (GC)";
294 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000295
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000296 case ErrorDeallocNotOwned:
297 Out << "-dealloc (not-owned)";
298 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000299
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000300 case ErrorLeak:
301 Out << "Leaked";
302 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000303
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000304 case ErrorLeakReturned:
305 Out << "Leaked (Bad naming)";
306 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000307
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000308 case ErrorGCLeakReturned:
309 Out << "Leaked (GC-ed at return)";
310 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000311
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000312 case ErrorUseAfterRelease:
313 Out << "Use-After-Release [ERROR]";
314 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000315
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000316 case ErrorReleaseNotOwned:
317 Out << "Release of Not-Owned [ERROR]";
318 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000319
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000320 case RefVal::ErrorOverAutorelease:
321 Out << "Over autoreleased";
322 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000323
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000324 case RefVal::ErrorReturnedNotOwned:
325 Out << "Non-owned object returned instead of owned";
326 break;
327 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000328
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000329 if (ACnt) {
330 Out << " [ARC +" << ACnt << ']';
331 }
332}
333} //end anonymous namespace
334
335//===----------------------------------------------------------------------===//
336// RefBindings - State used to track object reference counts.
337//===----------------------------------------------------------------------===//
338
339typedef llvm::ImmutableMap<SymbolRef, RefVal> RefBindings;
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000340
341namespace clang {
Ted Kremenek9ef65372010-12-23 07:20:52 +0000342namespace ento {
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000343template<>
344struct ProgramStateTrait<RefBindings>
345 : public ProgramStatePartialTrait<RefBindings> {
346 static void *GDMIndex() {
347 static int RefBIndex = 0;
348 return &RefBIndex;
349 }
350};
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000351}
Argyrios Kyrtzidis5a4f98f2010-12-22 18:53:20 +0000352}
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000353
354//===----------------------------------------------------------------------===//
Jordy Rose910c4052011-09-02 06:44:22 +0000355// Function/Method behavior summaries.
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000356//===----------------------------------------------------------------------===//
357
358namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000359class RetainSummary {
Jordy Roseef945882012-03-18 01:26:10 +0000360 /// Args - a map of (index, ArgEffect) pairs, where index
Ted Kremenek1bffd742008-05-06 15:44:25 +0000361 /// specifies the argument (starting from 0). This can be sparsely
362 /// populated; arguments with no entry in Args use 'DefaultArgEffect'.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000363 ArgEffects Args;
Mike Stump1eb44332009-09-09 15:08:12 +0000364
Ted Kremenek1bffd742008-05-06 15:44:25 +0000365 /// DefaultArgEffect - The default ArgEffect to apply to arguments that
366 /// do not have an entry in Args.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000367 ArgEffect DefaultArgEffect;
Mike Stump1eb44332009-09-09 15:08:12 +0000368
Ted Kremenek553cf182008-06-25 21:21:56 +0000369 /// Receiver - If this summary applies to an Objective-C message expression,
370 /// this is the effect applied to the state of the receiver.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000371 ArgEffect Receiver;
Mike Stump1eb44332009-09-09 15:08:12 +0000372
Ted Kremenek553cf182008-06-25 21:21:56 +0000373 /// Ret - The effect on the return value. Used to indicate if the
Jordy Rose76c506f2011-08-21 21:58:18 +0000374 /// function/method call returns a new tracked symbol.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000375 RetEffect Ret;
Mike Stump1eb44332009-09-09 15:08:12 +0000376
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000377public:
Ted Kremenekb77449c2009-05-03 05:20:50 +0000378 RetainSummary(ArgEffects A, RetEffect R, ArgEffect defaultEff,
Jordy Rosee62e87b2011-08-20 20:55:40 +0000379 ArgEffect ReceiverEff)
380 : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000381
Ted Kremenek553cf182008-06-25 21:21:56 +0000382 /// getArg - Return the argument effect on the argument specified by
383 /// idx (starting from 0).
Ted Kremenek1ac08d62008-03-11 17:48:22 +0000384 ArgEffect getArg(unsigned idx) const {
Ted Kremenekb77449c2009-05-03 05:20:50 +0000385 if (const ArgEffect *AE = Args.lookup(idx))
386 return *AE;
Mike Stump1eb44332009-09-09 15:08:12 +0000387
Ted Kremenek1bffd742008-05-06 15:44:25 +0000388 return DefaultArgEffect;
Ted Kremenek1ac08d62008-03-11 17:48:22 +0000389 }
Ted Kremenek11fe1752011-01-27 18:43:03 +0000390
391 void addArg(ArgEffects::Factory &af, unsigned idx, ArgEffect e) {
392 Args = af.add(Args, idx, e);
393 }
Mike Stump1eb44332009-09-09 15:08:12 +0000394
Ted Kremenek885c27b2009-05-04 05:31:22 +0000395 /// setDefaultArgEffect - Set the default argument effect.
396 void setDefaultArgEffect(ArgEffect E) {
397 DefaultArgEffect = E;
398 }
Mike Stump1eb44332009-09-09 15:08:12 +0000399
Ted Kremenek553cf182008-06-25 21:21:56 +0000400 /// getRetEffect - Returns the effect on the return value of the call.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000401 RetEffect getRetEffect() const { return Ret; }
Mike Stump1eb44332009-09-09 15:08:12 +0000402
Ted Kremenek885c27b2009-05-04 05:31:22 +0000403 /// setRetEffect - Set the effect of the return value of the call.
404 void setRetEffect(RetEffect E) { Ret = E; }
Mike Stump1eb44332009-09-09 15:08:12 +0000405
Ted Kremenek12b94342011-01-27 06:54:14 +0000406
407 /// Sets the effect on the receiver of the message.
408 void setReceiverEffect(ArgEffect e) { Receiver = e; }
409
Ted Kremenek553cf182008-06-25 21:21:56 +0000410 /// getReceiverEffect - Returns the effect on the receiver of the call.
411 /// This is only meaningful if the summary applies to an ObjCMessageExpr*.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000412 ArgEffect getReceiverEffect() const { return Receiver; }
Jordy Rose4df54fe2011-08-23 04:27:15 +0000413
414 /// Test if two retain summaries are identical. Note that merely equivalent
415 /// summaries are not necessarily identical (for example, if an explicit
416 /// argument effect matches the default effect).
417 bool operator==(const RetainSummary &Other) const {
418 return Args == Other.Args && DefaultArgEffect == Other.DefaultArgEffect &&
419 Receiver == Other.Receiver && Ret == Other.Ret;
420 }
Jordy Roseef945882012-03-18 01:26:10 +0000421
422 /// Profile this summary for inclusion in a FoldingSet.
423 void Profile(llvm::FoldingSetNodeID& ID) const {
424 ID.Add(Args);
425 ID.Add(DefaultArgEffect);
426 ID.Add(Receiver);
427 ID.Add(Ret);
428 }
429
430 /// A retain summary is simple if it has no ArgEffects other than the default.
431 bool isSimple() const {
432 return Args.isEmpty();
433 }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000434};
Ted Kremenek4f22a782008-06-23 23:30:29 +0000435} // end anonymous namespace
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000436
Ted Kremenek553cf182008-06-25 21:21:56 +0000437//===----------------------------------------------------------------------===//
438// Data structures for constructing summaries.
439//===----------------------------------------------------------------------===//
Ted Kremenek53301ba2008-06-24 03:49:48 +0000440
Ted Kremenek553cf182008-06-25 21:21:56 +0000441namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000442class ObjCSummaryKey {
Ted Kremenek553cf182008-06-25 21:21:56 +0000443 IdentifierInfo* II;
444 Selector S;
Mike Stump1eb44332009-09-09 15:08:12 +0000445public:
Ted Kremenek553cf182008-06-25 21:21:56 +0000446 ObjCSummaryKey(IdentifierInfo* ii, Selector s)
447 : II(ii), S(s) {}
448
Ted Kremenek9c378f72011-08-12 23:37:29 +0000449 ObjCSummaryKey(const ObjCInterfaceDecl *d, Selector s)
Ted Kremenek553cf182008-06-25 21:21:56 +0000450 : II(d ? d->getIdentifier() : 0), S(s) {}
Ted Kremenek70b6a832009-05-13 18:16:01 +0000451
Ted Kremenek9c378f72011-08-12 23:37:29 +0000452 ObjCSummaryKey(const ObjCInterfaceDecl *d, IdentifierInfo *ii, Selector s)
Ted Kremenek70b6a832009-05-13 18:16:01 +0000453 : II(d ? d->getIdentifier() : ii), S(s) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000454
Ted Kremenek553cf182008-06-25 21:21:56 +0000455 ObjCSummaryKey(Selector s)
456 : II(0), S(s) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000457
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000458 IdentifierInfo *getIdentifier() const { return II; }
Ted Kremenek553cf182008-06-25 21:21:56 +0000459 Selector getSelector() const { return S; }
460};
Ted Kremenek4f22a782008-06-23 23:30:29 +0000461}
462
463namespace llvm {
Ted Kremenek553cf182008-06-25 21:21:56 +0000464template <> struct DenseMapInfo<ObjCSummaryKey> {
465 static inline ObjCSummaryKey getEmptyKey() {
466 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
467 DenseMapInfo<Selector>::getEmptyKey());
468 }
Mike Stump1eb44332009-09-09 15:08:12 +0000469
Ted Kremenek553cf182008-06-25 21:21:56 +0000470 static inline ObjCSummaryKey getTombstoneKey() {
471 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
Mike Stump1eb44332009-09-09 15:08:12 +0000472 DenseMapInfo<Selector>::getTombstoneKey());
Ted Kremenek553cf182008-06-25 21:21:56 +0000473 }
Mike Stump1eb44332009-09-09 15:08:12 +0000474
Ted Kremenek553cf182008-06-25 21:21:56 +0000475 static unsigned getHashValue(const ObjCSummaryKey &V) {
476 return (DenseMapInfo<IdentifierInfo*>::getHashValue(V.getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000477 & 0x88888888)
Ted Kremenek553cf182008-06-25 21:21:56 +0000478 | (DenseMapInfo<Selector>::getHashValue(V.getSelector())
479 & 0x55555555);
480 }
Mike Stump1eb44332009-09-09 15:08:12 +0000481
Ted Kremenek553cf182008-06-25 21:21:56 +0000482 static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
483 return DenseMapInfo<IdentifierInfo*>::isEqual(LHS.getIdentifier(),
484 RHS.getIdentifier()) &&
485 DenseMapInfo<Selector>::isEqual(LHS.getSelector(),
486 RHS.getSelector());
487 }
Mike Stump1eb44332009-09-09 15:08:12 +0000488
Ted Kremenek553cf182008-06-25 21:21:56 +0000489};
Chris Lattner06159e82009-12-15 07:26:51 +0000490template <>
491struct isPodLike<ObjCSummaryKey> { static const bool value = true; };
Ted Kremenek4f22a782008-06-23 23:30:29 +0000492} // end llvm namespace
Mike Stump1eb44332009-09-09 15:08:12 +0000493
Ted Kremenek4f22a782008-06-23 23:30:29 +0000494namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000495class ObjCSummaryCache {
Ted Kremenek93edbc52011-10-05 23:54:29 +0000496 typedef llvm::DenseMap<ObjCSummaryKey, const RetainSummary *> MapTy;
Ted Kremenek553cf182008-06-25 21:21:56 +0000497 MapTy M;
498public:
499 ObjCSummaryCache() {}
Mike Stump1eb44332009-09-09 15:08:12 +0000500
Ted Kremenek93edbc52011-10-05 23:54:29 +0000501 const RetainSummary * find(const ObjCInterfaceDecl *D, IdentifierInfo *ClsName,
Ted Kremeneka8833552009-04-29 23:03:22 +0000502 Selector S) {
Ted Kremenek8711c032009-04-29 05:04:30 +0000503 // Lookup the method using the decl for the class @interface. If we
504 // have no decl, lookup using the class name.
505 return D ? find(D, S) : find(ClsName, S);
506 }
Mike Stump1eb44332009-09-09 15:08:12 +0000507
Ted Kremenek93edbc52011-10-05 23:54:29 +0000508 const RetainSummary * find(const ObjCInterfaceDecl *D, Selector S) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000509 // Do a lookup with the (D,S) pair. If we find a match return
510 // the iterator.
511 ObjCSummaryKey K(D, S);
512 MapTy::iterator I = M.find(K);
Mike Stump1eb44332009-09-09 15:08:12 +0000513
Ted Kremenek553cf182008-06-25 21:21:56 +0000514 if (I != M.end() || !D)
Ted Kremenek614cc542009-07-21 23:27:57 +0000515 return I->second;
Mike Stump1eb44332009-09-09 15:08:12 +0000516
Ted Kremenek553cf182008-06-25 21:21:56 +0000517 // Walk the super chain. If we find a hit with a parent, we'll end
518 // up returning that summary. We actually allow that key (null,S), as
519 // we cache summaries for the null ObjCInterfaceDecl* to allow us to
520 // generate initial summaries without having to worry about NSObject
521 // being declared.
522 // FIXME: We may change this at some point.
Ted Kremenek9c378f72011-08-12 23:37:29 +0000523 for (ObjCInterfaceDecl *C=D->getSuperClass() ;; C=C->getSuperClass()) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000524 if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
525 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000526
Ted Kremenek553cf182008-06-25 21:21:56 +0000527 if (!C)
Ted Kremenek614cc542009-07-21 23:27:57 +0000528 return NULL;
Ted Kremenek553cf182008-06-25 21:21:56 +0000529 }
Mike Stump1eb44332009-09-09 15:08:12 +0000530
531 // Cache the summary with original key to make the next lookup faster
Ted Kremenek553cf182008-06-25 21:21:56 +0000532 // and return the iterator.
Ted Kremenek93edbc52011-10-05 23:54:29 +0000533 const RetainSummary *Summ = I->second;
Ted Kremenek614cc542009-07-21 23:27:57 +0000534 M[K] = Summ;
535 return Summ;
Ted Kremenek553cf182008-06-25 21:21:56 +0000536 }
Mike Stump1eb44332009-09-09 15:08:12 +0000537
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000538 const RetainSummary *find(IdentifierInfo* II, Selector S) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000539 // FIXME: Class method lookup. Right now we dont' have a good way
540 // of going between IdentifierInfo* and the class hierarchy.
Ted Kremenek614cc542009-07-21 23:27:57 +0000541 MapTy::iterator I = M.find(ObjCSummaryKey(II, S));
Mike Stump1eb44332009-09-09 15:08:12 +0000542
Ted Kremenek614cc542009-07-21 23:27:57 +0000543 if (I == M.end())
544 I = M.find(ObjCSummaryKey(S));
Mike Stump1eb44332009-09-09 15:08:12 +0000545
Ted Kremenek614cc542009-07-21 23:27:57 +0000546 return I == M.end() ? NULL : I->second;
Ted Kremenek553cf182008-06-25 21:21:56 +0000547 }
Mike Stump1eb44332009-09-09 15:08:12 +0000548
Ted Kremenek93edbc52011-10-05 23:54:29 +0000549 const RetainSummary *& operator[](ObjCSummaryKey K) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000550 return M[K];
551 }
Mike Stump1eb44332009-09-09 15:08:12 +0000552
Ted Kremenek93edbc52011-10-05 23:54:29 +0000553 const RetainSummary *& operator[](Selector S) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000554 return M[ ObjCSummaryKey(S) ];
555 }
Mike Stump1eb44332009-09-09 15:08:12 +0000556};
Ted Kremenek553cf182008-06-25 21:21:56 +0000557} // end anonymous namespace
558
559//===----------------------------------------------------------------------===//
560// Data structures for managing collections of summaries.
561//===----------------------------------------------------------------------===//
562
563namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000564class RetainSummaryManager {
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000565
566 //==-----------------------------------------------------------------==//
567 // Typedefs.
568 //==-----------------------------------------------------------------==//
Mike Stump1eb44332009-09-09 15:08:12 +0000569
Ted Kremenek93edbc52011-10-05 23:54:29 +0000570 typedef llvm::DenseMap<const FunctionDecl*, const RetainSummary *>
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000571 FuncSummariesTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000572
Ted Kremenek4f22a782008-06-23 23:30:29 +0000573 typedef ObjCSummaryCache ObjCMethodSummariesTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000574
Jordy Roseef945882012-03-18 01:26:10 +0000575 typedef llvm::FoldingSetNodeWrapper<RetainSummary> CachedSummaryNode;
576
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000577 //==-----------------------------------------------------------------==//
578 // Data.
579 //==-----------------------------------------------------------------==//
Mike Stump1eb44332009-09-09 15:08:12 +0000580
Ted Kremenek553cf182008-06-25 21:21:56 +0000581 /// Ctx - The ASTContext object for the analyzed ASTs.
Ted Kremenek9c378f72011-08-12 23:37:29 +0000582 ASTContext &Ctx;
Ted Kremenek179064e2008-07-01 17:21:27 +0000583
Ted Kremenek553cf182008-06-25 21:21:56 +0000584 /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
Ted Kremenek377e2302008-04-29 05:33:51 +0000585 const bool GCEnabled;
Mike Stump1eb44332009-09-09 15:08:12 +0000586
John McCallf85e1932011-06-15 23:02:42 +0000587 /// Records whether or not the analyzed code runs in ARC mode.
588 const bool ARCEnabled;
589
Ted Kremenek553cf182008-06-25 21:21:56 +0000590 /// FuncSummaries - A map from FunctionDecls to summaries.
Mike Stump1eb44332009-09-09 15:08:12 +0000591 FuncSummariesTy FuncSummaries;
592
Ted Kremenek553cf182008-06-25 21:21:56 +0000593 /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
594 /// to summaries.
Ted Kremenek1f180c32008-06-23 22:21:20 +0000595 ObjCMethodSummariesTy ObjCClassMethodSummaries;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000596
Ted Kremenek553cf182008-06-25 21:21:56 +0000597 /// ObjCMethodSummaries - A map from selectors to summaries.
Ted Kremenek1f180c32008-06-23 22:21:20 +0000598 ObjCMethodSummariesTy ObjCMethodSummaries;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000599
Ted Kremenek553cf182008-06-25 21:21:56 +0000600 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
601 /// and all other data used by the checker.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000602 llvm::BumpPtrAllocator BPAlloc;
Mike Stump1eb44332009-09-09 15:08:12 +0000603
Ted Kremenekb77449c2009-05-03 05:20:50 +0000604 /// AF - A factory for ArgEffects objects.
Mike Stump1eb44332009-09-09 15:08:12 +0000605 ArgEffects::Factory AF;
606
Ted Kremenek553cf182008-06-25 21:21:56 +0000607 /// ScratchArgs - A holding buffer for construct ArgEffects.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000608 ArgEffects ScratchArgs;
Mike Stump1eb44332009-09-09 15:08:12 +0000609
Ted Kremenekec315332009-05-07 23:40:42 +0000610 /// ObjCAllocRetE - Default return effect for methods returning Objective-C
611 /// objects.
612 RetEffect ObjCAllocRetE;
Ted Kremenek547d4952009-06-05 23:18:01 +0000613
Mike Stump1eb44332009-09-09 15:08:12 +0000614 /// ObjCInitRetE - Default return effect for init methods returning
Ted Kremenekac02f202009-08-20 05:13:36 +0000615 /// Objective-C objects.
Ted Kremenek547d4952009-06-05 23:18:01 +0000616 RetEffect ObjCInitRetE;
Mike Stump1eb44332009-09-09 15:08:12 +0000617
Jordy Roseef945882012-03-18 01:26:10 +0000618 /// SimpleSummaries - Used for uniquing summaries that don't have special
619 /// effects.
620 llvm::FoldingSet<CachedSummaryNode> SimpleSummaries;
Mike Stump1eb44332009-09-09 15:08:12 +0000621
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000622 //==-----------------------------------------------------------------==//
623 // Methods.
624 //==-----------------------------------------------------------------==//
Mike Stump1eb44332009-09-09 15:08:12 +0000625
Ted Kremenek553cf182008-06-25 21:21:56 +0000626 /// getArgEffects - Returns a persistent ArgEffects object based on the
627 /// data in ScratchArgs.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000628 ArgEffects getArgEffects();
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000629
Mike Stump1eb44332009-09-09 15:08:12 +0000630 enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
631
Ted Kremenek896cd9d2008-10-23 01:56:15 +0000632public:
Ted Kremenek78a35a32009-05-12 20:06:54 +0000633 RetEffect getObjAllocRetEffect() const { return ObjCAllocRetE; }
Ted Kremenek93edbc52011-10-05 23:54:29 +0000634
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000635 const RetainSummary *getUnarySummary(const FunctionType* FT,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000636 UnaryFuncKind func);
Mike Stump1eb44332009-09-09 15:08:12 +0000637
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000638 const RetainSummary *getCFSummaryCreateRule(const FunctionDecl *FD);
639 const RetainSummary *getCFSummaryGetRule(const FunctionDecl *FD);
640 const RetainSummary *getCFCreateGetRuleSummary(const FunctionDecl *FD);
Mike Stump1eb44332009-09-09 15:08:12 +0000641
Jordy Roseef945882012-03-18 01:26:10 +0000642 const RetainSummary *getPersistentSummary(const RetainSummary &OldSumm);
Ted Kremenek706522f2008-10-29 04:07:07 +0000643
Jordy Roseef945882012-03-18 01:26:10 +0000644 const RetainSummary *getPersistentSummary(RetEffect RetEff,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000645 ArgEffect ReceiverEff = DoNothing,
646 ArgEffect DefaultEff = MayEscape) {
Jordy Roseef945882012-03-18 01:26:10 +0000647 RetainSummary Summ(getArgEffects(), RetEff, DefaultEff, ReceiverEff);
648 return getPersistentSummary(Summ);
649 }
650
651 const RetainSummary *getDefaultSummary() {
652 return getPersistentSummary(RetEffect::MakeNoRet(),
653 DoNothing, MayEscape);
Ted Kremenek9c32d082008-05-06 00:30:21 +0000654 }
Mike Stump1eb44332009-09-09 15:08:12 +0000655
Ted Kremenek93edbc52011-10-05 23:54:29 +0000656 const RetainSummary *getPersistentStopSummary() {
Jordy Roseef945882012-03-18 01:26:10 +0000657 return getPersistentSummary(RetEffect::MakeNoRet(),
658 StopTracking, StopTracking);
Mike Stump1eb44332009-09-09 15:08:12 +0000659 }
Ted Kremenekb3095252008-05-06 04:20:12 +0000660
Ted Kremenek1f180c32008-06-23 22:21:20 +0000661 void InitializeClassMethodSummaries();
662 void InitializeMethodSummaries();
Ted Kremenek896cd9d2008-10-23 01:56:15 +0000663private:
Ted Kremenek93edbc52011-10-05 23:54:29 +0000664 void addNSObjectClsMethSummary(Selector S, const RetainSummary *Summ) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000665 ObjCClassMethodSummaries[S] = Summ;
666 }
Mike Stump1eb44332009-09-09 15:08:12 +0000667
Ted Kremenek93edbc52011-10-05 23:54:29 +0000668 void addNSObjectMethSummary(Selector S, const RetainSummary *Summ) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000669 ObjCMethodSummaries[S] = Summ;
670 }
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +0000671
Ted Kremeneka9797122012-02-18 21:37:48 +0000672 void addClassMethSummary(const char* Cls, const char* name,
673 const RetainSummary *Summ, bool isNullary = true) {
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +0000674 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
Ted Kremeneka9797122012-02-18 21:37:48 +0000675 Selector S = isNullary ? GetNullarySelector(name, Ctx)
676 : GetUnarySelector(name, Ctx);
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +0000677 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
678 }
Mike Stump1eb44332009-09-09 15:08:12 +0000679
Ted Kremenek6c4becb2009-02-25 02:54:57 +0000680 void addInstMethSummary(const char* Cls, const char* nullaryName,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000681 const RetainSummary *Summ) {
Ted Kremenek6c4becb2009-02-25 02:54:57 +0000682 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
683 Selector S = GetNullarySelector(nullaryName, Ctx);
684 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
685 }
Mike Stump1eb44332009-09-09 15:08:12 +0000686
Ted Kremenekde4d5332009-04-24 17:50:11 +0000687 Selector generateSelector(va_list argp) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000688 SmallVector<IdentifierInfo*, 10> II;
Ted Kremenekde4d5332009-04-24 17:50:11 +0000689
Ted Kremenek9e476de2008-08-12 18:30:56 +0000690 while (const char* s = va_arg(argp, const char*))
691 II.push_back(&Ctx.Idents.get(s));
Ted Kremenekde4d5332009-04-24 17:50:11 +0000692
Mike Stump1eb44332009-09-09 15:08:12 +0000693 return Ctx.Selectors.getSelector(II.size(), &II[0]);
Ted Kremenekde4d5332009-04-24 17:50:11 +0000694 }
Mike Stump1eb44332009-09-09 15:08:12 +0000695
Ted Kremenekde4d5332009-04-24 17:50:11 +0000696 void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy& Summaries,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000697 const RetainSummary * Summ, va_list argp) {
Ted Kremenekde4d5332009-04-24 17:50:11 +0000698 Selector S = generateSelector(argp);
699 Summaries[ObjCSummaryKey(ClsII, S)] = Summ;
Ted Kremenek70a733e2008-07-18 17:24:20 +0000700 }
Mike Stump1eb44332009-09-09 15:08:12 +0000701
Ted Kremenek93edbc52011-10-05 23:54:29 +0000702 void addInstMethSummary(const char* Cls, const RetainSummary * Summ, ...) {
Ted Kremenekaf9dc272008-08-12 18:48:50 +0000703 va_list argp;
704 va_start(argp, Summ);
Ted Kremenekde4d5332009-04-24 17:50:11 +0000705 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Mike Stump1eb44332009-09-09 15:08:12 +0000706 va_end(argp);
Ted Kremenekaf9dc272008-08-12 18:48:50 +0000707 }
Mike Stump1eb44332009-09-09 15:08:12 +0000708
Ted Kremenek93edbc52011-10-05 23:54:29 +0000709 void addClsMethSummary(const char* Cls, const RetainSummary * Summ, ...) {
Ted Kremenekde4d5332009-04-24 17:50:11 +0000710 va_list argp;
711 va_start(argp, Summ);
712 addMethodSummary(&Ctx.Idents.get(Cls),ObjCClassMethodSummaries, Summ, argp);
713 va_end(argp);
714 }
Mike Stump1eb44332009-09-09 15:08:12 +0000715
Ted Kremenek93edbc52011-10-05 23:54:29 +0000716 void addClsMethSummary(IdentifierInfo *II, const RetainSummary * Summ, ...) {
Ted Kremenekde4d5332009-04-24 17:50:11 +0000717 va_list argp;
718 va_start(argp, Summ);
719 addMethodSummary(II, ObjCClassMethodSummaries, Summ, argp);
720 va_end(argp);
721 }
722
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000723public:
Mike Stump1eb44332009-09-09 15:08:12 +0000724
Ted Kremenek9c378f72011-08-12 23:37:29 +0000725 RetainSummaryManager(ASTContext &ctx, bool gcenabled, bool usesARC)
Ted Kremenek179064e2008-07-01 17:21:27 +0000726 : Ctx(ctx),
John McCallf85e1932011-06-15 23:02:42 +0000727 GCEnabled(gcenabled),
728 ARCEnabled(usesARC),
729 AF(BPAlloc), ScratchArgs(AF.getEmptyMap()),
730 ObjCAllocRetE(gcenabled
731 ? RetEffect::MakeGCNotOwned()
732 : (usesARC ? RetEffect::MakeARCNotOwned()
733 : RetEffect::MakeOwned(RetEffect::ObjC, true))),
734 ObjCInitRetE(gcenabled
735 ? RetEffect::MakeGCNotOwned()
736 : (usesARC ? RetEffect::MakeARCNotOwned()
Jordy Roseef945882012-03-18 01:26:10 +0000737 : RetEffect::MakeOwnedWhenTrackedReceiver())) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000738 InitializeClassMethodSummaries();
739 InitializeMethodSummaries();
740 }
Mike Stump1eb44332009-09-09 15:08:12 +0000741
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000742 const RetainSummary *getSummary(const FunctionDecl *FD);
Mike Stump1eb44332009-09-09 15:08:12 +0000743
Jordy Rosef3aae582012-03-17 21:13:07 +0000744 const RetainSummary *getMethodSummary(Selector S, IdentifierInfo *ClsName,
745 const ObjCInterfaceDecl *ID,
746 const ObjCMethodDecl *MD,
747 QualType RetTy,
748 ObjCMethodSummariesTy &CachedSummaries);
749
Ted Kremenek93edbc52011-10-05 23:54:29 +0000750 const RetainSummary *getInstanceMethodSummary(const ObjCMessage &msg,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000751 ProgramStateRef state,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000752 const LocationContext *LC);
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000753
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000754 const RetainSummary *getInstanceMethodSummary(const ObjCMessage &msg,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000755 const ObjCInterfaceDecl *ID) {
Jordy Rosef3aae582012-03-17 21:13:07 +0000756 return getMethodSummary(msg.getSelector(), 0, ID, msg.getMethodDecl(),
757 msg.getType(Ctx), ObjCMethodSummaries);
Ted Kremenek8711c032009-04-29 05:04:30 +0000758 }
Mike Stump1eb44332009-09-09 15:08:12 +0000759
Ted Kremenek93edbc52011-10-05 23:54:29 +0000760 const RetainSummary *getClassMethodSummary(const ObjCMessage &msg) {
Argyrios Kyrtzidis432424d2011-01-25 00:03:53 +0000761 const ObjCInterfaceDecl *Class = 0;
762 if (!msg.isInstanceMessage())
763 Class = msg.getReceiverInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +0000764
Jordy Rosef3aae582012-03-17 21:13:07 +0000765 return getMethodSummary(msg.getSelector(), Class->getIdentifier(),
766 Class, msg.getMethodDecl(), msg.getType(Ctx),
767 ObjCClassMethodSummaries);
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +0000768 }
Ted Kremenek552333c2009-04-29 17:17:48 +0000769
770 /// getMethodSummary - This version of getMethodSummary is used to query
771 /// the summary for the current method being analyzed.
Ted Kremenek93edbc52011-10-05 23:54:29 +0000772 const RetainSummary *getMethodSummary(const ObjCMethodDecl *MD) {
Ted Kremeneka8833552009-04-29 23:03:22 +0000773 // FIXME: Eventually this should be unneeded.
Ted Kremeneka8833552009-04-29 23:03:22 +0000774 const ObjCInterfaceDecl *ID = MD->getClassInterface();
Ted Kremenek70a65762009-04-30 05:41:14 +0000775 Selector S = MD->getSelector();
Ted Kremenek552333c2009-04-29 17:17:48 +0000776 IdentifierInfo *ClsName = ID->getIdentifier();
777 QualType ResultTy = MD->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +0000778
Jordy Rosef3aae582012-03-17 21:13:07 +0000779 ObjCMethodSummariesTy *CachedSummaries;
Ted Kremenek552333c2009-04-29 17:17:48 +0000780 if (MD->isInstanceMethod())
Jordy Rosef3aae582012-03-17 21:13:07 +0000781 CachedSummaries = &ObjCMethodSummaries;
Ted Kremenek552333c2009-04-29 17:17:48 +0000782 else
Jordy Rosef3aae582012-03-17 21:13:07 +0000783 CachedSummaries = &ObjCClassMethodSummaries;
784
785 return getMethodSummary(S, ClsName, ID, MD, ResultTy, *CachedSummaries);
Ted Kremenek552333c2009-04-29 17:17:48 +0000786 }
Mike Stump1eb44332009-09-09 15:08:12 +0000787
Jordy Rosef3aae582012-03-17 21:13:07 +0000788 const RetainSummary *getStandardMethodSummary(const ObjCMethodDecl *MD,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000789 Selector S, QualType RetTy);
Ted Kremeneka8833552009-04-29 23:03:22 +0000790
Ted Kremenek93edbc52011-10-05 23:54:29 +0000791 void updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenek4dd8fb42009-05-09 02:58:13 +0000792 const ObjCMethodDecl *MD);
793
Ted Kremenek93edbc52011-10-05 23:54:29 +0000794 void updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenek4dd8fb42009-05-09 02:58:13 +0000795 const FunctionDecl *FD);
796
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000797 bool isGCEnabled() const { return GCEnabled; }
Mike Stump1eb44332009-09-09 15:08:12 +0000798
John McCallf85e1932011-06-15 23:02:42 +0000799 bool isARCEnabled() const { return ARCEnabled; }
800
801 bool isARCorGCEnabled() const { return GCEnabled || ARCEnabled; }
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 Roseef945882012-03-18 01:26:10 +0000821 RealSummary = Manager.getPersistentSummary(ScratchSummary);
Jordy Rose0fe62f82011-08-24 09:02:37 +0000822 }
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 *
Jordy Roseef945882012-03-18 01:26:10 +0000848RetainSummaryManager::getPersistentSummary(const RetainSummary &OldSumm) {
849 // Unique "simple" summaries -- those without ArgEffects.
850 if (OldSumm.isSimple()) {
851 llvm::FoldingSetNodeID ID;
852 OldSumm.Profile(ID);
853
854 void *Pos;
855 CachedSummaryNode *N = SimpleSummaries.FindNodeOrInsertPos(ID, Pos);
856
857 if (!N) {
858 N = (CachedSummaryNode *) BPAlloc.Allocate<CachedSummaryNode>();
859 new (N) CachedSummaryNode(OldSumm);
860 SimpleSummaries.InsertNode(N, Pos);
861 }
862
863 return &N->getValue();
864 }
865
Ted Kremenek93edbc52011-10-05 23:54:29 +0000866 RetainSummary *Summ = (RetainSummary *) BPAlloc.Allocate<RetainSummary>();
Jordy Roseef945882012-03-18 01:26:10 +0000867 new (Summ) RetainSummary(OldSumm);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000868 return Summ;
869}
870
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000871//===----------------------------------------------------------------------===//
872// Summary creation for functions (largely uses of Core Foundation).
873//===----------------------------------------------------------------------===//
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000874
Ted Kremenek9c378f72011-08-12 23:37:29 +0000875static bool isRetain(const FunctionDecl *FD, StringRef FName) {
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000876 return FName.endswith("Retain");
Ted Kremenek12619382009-01-12 21:45:02 +0000877}
878
Ted Kremenek9c378f72011-08-12 23:37:29 +0000879static bool isRelease(const FunctionDecl *FD, StringRef FName) {
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000880 return FName.endswith("Release");
Ted Kremenek12619382009-01-12 21:45:02 +0000881}
882
Jordy Rose76c506f2011-08-21 21:58:18 +0000883static bool isMakeCollectable(const FunctionDecl *FD, StringRef FName) {
884 // FIXME: Remove FunctionDecl parameter.
885 // FIXME: Is it really okay if MakeCollectable isn't a suffix?
886 return FName.find("MakeCollectable") != StringRef::npos;
887}
888
Ted Kremenek93edbc52011-10-05 23:54:29 +0000889const RetainSummary * RetainSummaryManager::getSummary(const FunctionDecl *FD) {
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000890 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000891 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000892 if (I != FuncSummaries.end())
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000893 return I->second;
894
Ted Kremeneke401a0c2009-05-04 15:34:07 +0000895 // No summary? Generate one.
Ted Kremenek93edbc52011-10-05 23:54:29 +0000896 const RetainSummary *S = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000897
Ted Kremenek37d785b2008-07-15 16:50:12 +0000898 do {
Ted Kremenek12619382009-01-12 21:45:02 +0000899 // We generate "stop" summaries for implicitly defined functions.
900 if (FD->isImplicit()) {
901 S = getPersistentStopSummary();
902 break;
Ted Kremenek37d785b2008-07-15 16:50:12 +0000903 }
Ted Kremenek9ca28512011-05-02 21:21:42 +0000904 // For C++ methods, generate an implicit "stop" summary as well. We
905 // can relax this once we have a clear policy for C++ methods and
906 // ownership attributes.
907 if (isa<CXXMethodDecl>(FD)) {
908 S = getPersistentStopSummary();
909 break;
910 }
Mike Stump1eb44332009-09-09 15:08:12 +0000911
John McCall183700f2009-09-21 23:43:11 +0000912 // [PR 3337] Use 'getAs<FunctionType>' to strip away any typedefs on the
Ted Kremenek99890652009-01-16 18:40:33 +0000913 // function's type.
John McCall183700f2009-09-21 23:43:11 +0000914 const FunctionType* FT = FD->getType()->getAs<FunctionType>();
Ted Kremenek48c6d182009-12-16 06:06:43 +0000915 const IdentifierInfo *II = FD->getIdentifier();
916 if (!II)
917 break;
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000918
919 StringRef FName = II->getName();
Mike Stump1eb44332009-09-09 15:08:12 +0000920
Ted Kremenekbf0a4dd2009-03-05 22:11:14 +0000921 // Strip away preceding '_'. Doing this here will effect all the checks
922 // down below.
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000923 FName = FName.substr(FName.find_first_not_of('_'));
Mike Stump1eb44332009-09-09 15:08:12 +0000924
Ted Kremenek12619382009-01-12 21:45:02 +0000925 // Inspect the result type.
926 QualType RetTy = FT->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +0000927
Ted Kremenek12619382009-01-12 21:45:02 +0000928 // FIXME: This should all be refactored into a chain of "summary lookup"
929 // filters.
Ted Kremenek008636a2009-10-14 00:27:24 +0000930 assert(ScratchArgs.isEmpty());
Ted Kremenek39d88b02009-06-15 20:36:07 +0000931
Ted Kremenekbefc6d22012-04-26 04:32:23 +0000932 if (FName == "pthread_create" || FName == "pthread_setspecific") {
933 // Part of: <rdar://problem/7299394> and <rdar://problem/11282706>.
934 // This will be addressed better with IPA.
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000935 S = getPersistentStopSummary();
936 } else if (FName == "NSMakeCollectable") {
937 // Handle: id NSMakeCollectable(CFTypeRef)
938 S = (RetTy->isObjCIdType())
939 ? getUnarySummary(FT, cfmakecollectable)
940 : getPersistentStopSummary();
941 } else if (FName == "IOBSDNameMatching" ||
942 FName == "IOServiceMatching" ||
943 FName == "IOServiceNameMatching" ||
Ted Kremenek537dd3a2012-05-01 05:28:27 +0000944 FName == "IORegistryEntrySearchCFProperty" ||
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000945 FName == "IORegistryEntryIDMatching" ||
946 FName == "IOOpenFirmwarePathMatching") {
947 // Part of <rdar://problem/6961230>. (IOKit)
948 // This should be addressed using a API table.
949 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
950 DoNothing, DoNothing);
951 } else if (FName == "IOServiceGetMatchingService" ||
952 FName == "IOServiceGetMatchingServices") {
953 // FIXES: <rdar://problem/6326900>
954 // This should be addressed using a API table. This strcmp is also
955 // a little gross, but there is no need to super optimize here.
Ted Kremenek3baf6722010-11-24 00:54:37 +0000956 ScratchArgs = AF.add(ScratchArgs, 1, DecRef);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000957 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
958 } else if (FName == "IOServiceAddNotification" ||
959 FName == "IOServiceAddMatchingNotification") {
960 // Part of <rdar://problem/6961230>. (IOKit)
961 // This should be addressed using a API table.
Ted Kremenek3baf6722010-11-24 00:54:37 +0000962 ScratchArgs = AF.add(ScratchArgs, 2, DecRef);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000963 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
964 } else if (FName == "CVPixelBufferCreateWithBytes") {
965 // FIXES: <rdar://problem/7283567>
966 // Eventually this can be improved by recognizing that the pixel
967 // buffer passed to CVPixelBufferCreateWithBytes is released via
968 // a callback and doing full IPA to make sure this is done correctly.
969 // FIXME: This function has an out parameter that returns an
970 // allocated object.
Ted Kremenek3baf6722010-11-24 00:54:37 +0000971 ScratchArgs = AF.add(ScratchArgs, 7, StopTracking);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000972 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
973 } else if (FName == "CGBitmapContextCreateWithData") {
974 // FIXES: <rdar://problem/7358899>
975 // Eventually this can be improved by recognizing that 'releaseInfo'
976 // passed to CGBitmapContextCreateWithData is released via
977 // a callback and doing full IPA to make sure this is done correctly.
Ted Kremenek3baf6722010-11-24 00:54:37 +0000978 ScratchArgs = AF.add(ScratchArgs, 8, StopTracking);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000979 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
980 DoNothing, DoNothing);
981 } else if (FName == "CVPixelBufferCreateWithPlanarBytes") {
982 // FIXES: <rdar://problem/7283567>
983 // Eventually this can be improved by recognizing that the pixel
984 // buffer passed to CVPixelBufferCreateWithPlanarBytes is released
985 // via a callback and doing full IPA to make sure this is done
986 // correctly.
Ted Kremenek3baf6722010-11-24 00:54:37 +0000987 ScratchArgs = AF.add(ScratchArgs, 12, StopTracking);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000988 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenek06911d42012-03-22 06:29:41 +0000989 } else if (FName == "dispatch_set_context") {
990 // <rdar://problem/11059275> - The analyzer currently doesn't have
991 // a good way to reason about the finalizer function for libdispatch.
992 // If we pass a context object that is memory managed, stop tracking it.
993 // FIXME: this hack should possibly go away once we can handle
994 // libdispatch finalizers.
995 ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
996 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Anna Zaks62a5c342012-03-30 05:48:16 +0000997 } else if (FName.startswith("NS") &&
998 (FName.find("Insert") != StringRef::npos)) {
999 // Whitelist NSXXInsertXX, for example NSMapInsertIfAbsent, since they can
1000 // be deallocated by NSMapRemove. (radar://11152419)
1001 ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
1002 ScratchArgs = AF.add(ScratchArgs, 2, StopTracking);
1003 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenekb04cb592009-06-11 18:17:24 +00001004 }
Mike Stump1eb44332009-09-09 15:08:12 +00001005
Ted Kremenekb04cb592009-06-11 18:17:24 +00001006 // Did we get a summary?
1007 if (S)
1008 break;
Ted Kremenek61991902009-03-17 22:43:44 +00001009
1010 // Enable this code once the semantics of NSDeallocateObject are resolved
1011 // for GC. <rdar://problem/6619988>
1012#if 0
1013 // Handle: NSDeallocateObject(id anObject);
1014 // This method does allow 'nil' (although we don't check it now).
Mike Stump1eb44332009-09-09 15:08:12 +00001015 if (strcmp(FName, "NSDeallocateObject") == 0) {
Ted Kremenek61991902009-03-17 22:43:44 +00001016 return RetTy == Ctx.VoidTy
1017 ? getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, Dealloc)
1018 : getPersistentStopSummary();
1019 }
1020#endif
Ted Kremenek12619382009-01-12 21:45:02 +00001021
1022 if (RetTy->isPointerType()) {
1023 // For CoreFoundation ('CF') types.
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001024 if (cocoa::isRefType(RetTy, "CF", FName)) {
Ted Kremenek12619382009-01-12 21:45:02 +00001025 if (isRetain(FD, FName))
1026 S = getUnarySummary(FT, cfretain);
Jordy Rose76c506f2011-08-21 21:58:18 +00001027 else if (isMakeCollectable(FD, FName))
Ted Kremenek12619382009-01-12 21:45:02 +00001028 S = getUnarySummary(FT, cfmakecollectable);
Mike Stump1eb44332009-09-09 15:08:12 +00001029 else
John McCall7df2ff42011-10-01 00:48:56 +00001030 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek12619382009-01-12 21:45:02 +00001031
1032 break;
1033 }
1034
1035 // For CoreGraphics ('CG') types.
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001036 if (cocoa::isRefType(RetTy, "CG", FName)) {
Ted Kremenek12619382009-01-12 21:45:02 +00001037 if (isRetain(FD, FName))
1038 S = getUnarySummary(FT, cfretain);
1039 else
John McCall7df2ff42011-10-01 00:48:56 +00001040 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek12619382009-01-12 21:45:02 +00001041
1042 break;
1043 }
1044
1045 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001046 if (cocoa::isRefType(RetTy, "DADisk") ||
1047 cocoa::isRefType(RetTy, "DADissenter") ||
1048 cocoa::isRefType(RetTy, "DASessionRef")) {
John McCall7df2ff42011-10-01 00:48:56 +00001049 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek12619382009-01-12 21:45:02 +00001050 break;
1051 }
Mike Stump1eb44332009-09-09 15:08:12 +00001052
Ted Kremenek12619382009-01-12 21:45:02 +00001053 break;
1054 }
1055
1056 // Check for release functions, the only kind of functions that we care
1057 // about that don't return a pointer type.
1058 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
Ted Kremeneke7d03122010-02-08 16:45:01 +00001059 // Test for 'CGCF'.
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001060 FName = FName.substr(FName.startswith("CGCF") ? 4 : 2);
Ted Kremeneke7d03122010-02-08 16:45:01 +00001061
Ted Kremenekbf0a4dd2009-03-05 22:11:14 +00001062 if (isRelease(FD, FName))
Ted Kremenek12619382009-01-12 21:45:02 +00001063 S = getUnarySummary(FT, cfrelease);
1064 else {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001065 assert (ScratchArgs.isEmpty());
Ted Kremenek68189282009-01-29 22:45:13 +00001066 // Remaining CoreFoundation and CoreGraphics functions.
1067 // We use to assume that they all strictly followed the ownership idiom
1068 // and that ownership cannot be transferred. While this is technically
1069 // correct, many methods allow a tracked object to escape. For example:
1070 //
Mike Stump1eb44332009-09-09 15:08:12 +00001071 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
Ted Kremenek68189282009-01-29 22:45:13 +00001072 // CFDictionaryAddValue(y, key, x);
Mike Stump1eb44332009-09-09 15:08:12 +00001073 // CFRelease(x);
Ted Kremenek68189282009-01-29 22:45:13 +00001074 // ... it is okay to use 'x' since 'y' has a reference to it
1075 //
1076 // We handle this and similar cases with the follow heuristic. If the
Ted Kremenekc4843812009-08-20 00:57:22 +00001077 // function name contains "InsertValue", "SetValue", "AddValue",
1078 // "AppendValue", or "SetAttribute", then we assume that arguments may
1079 // "escape." This means that something else holds on to the object,
1080 // allowing it be used even after its local retain count drops to 0.
Benjamin Kramere45c1492010-01-11 19:46:28 +00001081 ArgEffect E = (StrInStrNoCase(FName, "InsertValue") != StringRef::npos||
1082 StrInStrNoCase(FName, "AddValue") != StringRef::npos ||
1083 StrInStrNoCase(FName, "SetValue") != StringRef::npos ||
1084 StrInStrNoCase(FName, "AppendValue") != StringRef::npos||
Benjamin Kramerc027e542010-01-11 20:15:06 +00001085 StrInStrNoCase(FName, "SetAttribute") != StringRef::npos)
Ted Kremenek68189282009-01-29 22:45:13 +00001086 ? MayEscape : DoNothing;
Mike Stump1eb44332009-09-09 15:08:12 +00001087
Ted Kremenek68189282009-01-29 22:45:13 +00001088 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek12619382009-01-12 21:45:02 +00001089 }
1090 }
Ted Kremenek37d785b2008-07-15 16:50:12 +00001091 }
1092 while (0);
Mike Stump1eb44332009-09-09 15:08:12 +00001093
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001094 // Annotations override defaults.
Jordy Rose4df54fe2011-08-23 04:27:15 +00001095 updateSummaryFromAnnotations(S, FD);
Mike Stump1eb44332009-09-09 15:08:12 +00001096
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001097 FuncSummaries[FD] = S;
Mike Stump1eb44332009-09-09 15:08:12 +00001098 return S;
Ted Kremenek2fff37e2008-03-06 00:08:09 +00001099}
1100
Ted Kremenek93edbc52011-10-05 23:54:29 +00001101const RetainSummary *
John McCall7df2ff42011-10-01 00:48:56 +00001102RetainSummaryManager::getCFCreateGetRuleSummary(const FunctionDecl *FD) {
1103 if (coreFoundation::followsCreateRule(FD))
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001104 return getCFSummaryCreateRule(FD);
Mike Stump1eb44332009-09-09 15:08:12 +00001105
Ted Kremenekd368d712011-05-25 06:19:45 +00001106 return getCFSummaryGetRule(FD);
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001107}
1108
Ted Kremenek93edbc52011-10-05 23:54:29 +00001109const RetainSummary *
Ted Kremenek6ad315a2009-02-23 16:51:39 +00001110RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1111 UnaryFuncKind func) {
1112
Ted Kremenek12619382009-01-12 21:45:02 +00001113 // Sanity check that this is *really* a unary function. This can
1114 // happen if people do weird things.
Douglas Gregor72564e72009-02-26 23:50:07 +00001115 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
Ted Kremenek12619382009-01-12 21:45:02 +00001116 if (!FTP || FTP->getNumArgs() != 1)
1117 return getPersistentStopSummary();
Mike Stump1eb44332009-09-09 15:08:12 +00001118
Ted Kremenekb77449c2009-05-03 05:20:50 +00001119 assert (ScratchArgs.isEmpty());
Mike Stump1eb44332009-09-09 15:08:12 +00001120
Jordy Rose76c506f2011-08-21 21:58:18 +00001121 ArgEffect Effect;
Ted Kremenek377e2302008-04-29 05:33:51 +00001122 switch (func) {
Jordy Rose76c506f2011-08-21 21:58:18 +00001123 case cfretain: Effect = IncRef; break;
1124 case cfrelease: Effect = DecRef; break;
1125 case cfmakecollectable: Effect = MakeCollectable; break;
Ted Kremenek940b1d82008-04-10 23:44:06 +00001126 }
Jordy Rose76c506f2011-08-21 21:58:18 +00001127
1128 ScratchArgs = AF.add(ScratchArgs, 0, Effect);
1129 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001130}
1131
Ted Kremenek93edbc52011-10-05 23:54:29 +00001132const RetainSummary *
Ted Kremenek9c378f72011-08-12 23:37:29 +00001133RetainSummaryManager::getCFSummaryCreateRule(const FunctionDecl *FD) {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001134 assert (ScratchArgs.isEmpty());
Mike Stump1eb44332009-09-09 15:08:12 +00001135
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001136 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001137}
1138
Ted Kremenek93edbc52011-10-05 23:54:29 +00001139const RetainSummary *
Ted Kremenek9c378f72011-08-12 23:37:29 +00001140RetainSummaryManager::getCFSummaryGetRule(const FunctionDecl *FD) {
Mike Stump1eb44332009-09-09 15:08:12 +00001141 assert (ScratchArgs.isEmpty());
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001142 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1143 DoNothing, DoNothing);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001144}
1145
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001146//===----------------------------------------------------------------------===//
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001147// Summary creation for Selectors.
1148//===----------------------------------------------------------------------===//
1149
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001150void
Ted Kremenek93edbc52011-10-05 23:54:29 +00001151RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001152 const FunctionDecl *FD) {
1153 if (!FD)
1154 return;
1155
Jordy Roseef945882012-03-18 01:26:10 +00001156 RetainSummaryTemplate Template(Summ, *getDefaultSummary(), *this);
Jordy Rose4df54fe2011-08-23 04:27:15 +00001157
Ted Kremenek11fe1752011-01-27 18:43:03 +00001158 // Effects on the parameters.
1159 unsigned parm_idx = 0;
1160 for (FunctionDecl::param_const_iterator pi = FD->param_begin(),
John McCall98b8f162011-04-06 09:02:12 +00001161 pe = FD->param_end(); pi != pe; ++pi, ++parm_idx) {
Ted Kremenek11fe1752011-01-27 18:43:03 +00001162 const ParmVarDecl *pd = *pi;
1163 if (pd->getAttr<NSConsumedAttr>()) {
Jordy Rose4df54fe2011-08-23 04:27:15 +00001164 if (!GCEnabled) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001165 Template->addArg(AF, parm_idx, DecRef);
Jordy Rose4df54fe2011-08-23 04:27:15 +00001166 }
1167 } else if (pd->getAttr<CFConsumedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001168 Template->addArg(AF, parm_idx, DecRef);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001169 }
1170 }
1171
Ted Kremenekb04cb592009-06-11 18:17:24 +00001172 QualType RetTy = FD->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00001173
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001174 // Determine if there is a special return effect for this method.
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001175 if (cocoa::isCocoaObjectRef(RetTy)) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001176 if (FD->getAttr<NSReturnsRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001177 Template->setRetEffect(ObjCAllocRetE);
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001178 }
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001179 else if (FD->getAttr<CFReturnsRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001180 Template->setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenekb04cb592009-06-11 18:17:24 +00001181 }
Ted Kremenek60411112010-02-18 00:06:12 +00001182 else if (FD->getAttr<NSReturnsNotRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001183 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::ObjC));
Ted Kremenek60411112010-02-18 00:06:12 +00001184 }
1185 else if (FD->getAttr<CFReturnsNotRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001186 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::CF));
Jordy Rose4df54fe2011-08-23 04:27:15 +00001187 }
1188 } else if (RetTy->getAs<PointerType>()) {
1189 if (FD->getAttr<CFReturnsRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001190 Template->setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
Jordy Rose4df54fe2011-08-23 04:27:15 +00001191 }
1192 else if (FD->getAttr<CFReturnsNotRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001193 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::CF));
Ted Kremenek60411112010-02-18 00:06:12 +00001194 }
Ted Kremenekb04cb592009-06-11 18:17:24 +00001195 }
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001196}
1197
1198void
Ted Kremenek93edbc52011-10-05 23:54:29 +00001199RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
1200 const ObjCMethodDecl *MD) {
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001201 if (!MD)
1202 return;
1203
Jordy Roseef945882012-03-18 01:26:10 +00001204 RetainSummaryTemplate Template(Summ, *getDefaultSummary(), *this);
Ted Kremenek6d4b76d2009-07-06 18:30:43 +00001205 bool isTrackedLoc = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001206
Ted Kremenek12b94342011-01-27 06:54:14 +00001207 // Effects on the receiver.
1208 if (MD->getAttr<NSConsumesSelfAttr>()) {
Ted Kremenek11fe1752011-01-27 18:43:03 +00001209 if (!GCEnabled)
Jordy Rose0fe62f82011-08-24 09:02:37 +00001210 Template->setReceiverEffect(DecRefMsg);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001211 }
1212
1213 // Effects on the parameters.
1214 unsigned parm_idx = 0;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00001215 for (ObjCMethodDecl::param_const_iterator
1216 pi=MD->param_begin(), pe=MD->param_end();
Ted Kremenek11fe1752011-01-27 18:43:03 +00001217 pi != pe; ++pi, ++parm_idx) {
1218 const ParmVarDecl *pd = *pi;
1219 if (pd->getAttr<NSConsumedAttr>()) {
1220 if (!GCEnabled)
Jordy Rose0fe62f82011-08-24 09:02:37 +00001221 Template->addArg(AF, parm_idx, DecRef);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001222 }
1223 else if(pd->getAttr<CFConsumedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001224 Template->addArg(AF, parm_idx, DecRef);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001225 }
Ted Kremenek12b94342011-01-27 06:54:14 +00001226 }
1227
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001228 // Determine if there is a special return effect for this method.
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001229 if (cocoa::isCocoaObjectRef(MD->getResultType())) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001230 if (MD->getAttr<NSReturnsRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001231 Template->setRetEffect(ObjCAllocRetE);
Ted Kremenek6d4b76d2009-07-06 18:30:43 +00001232 return;
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001233 }
Ted Kremenek60411112010-02-18 00:06:12 +00001234 if (MD->getAttr<NSReturnsNotRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001235 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::ObjC));
Ted Kremenek60411112010-02-18 00:06:12 +00001236 return;
1237 }
Mike Stump1eb44332009-09-09 15:08:12 +00001238
Ted Kremenek6d4b76d2009-07-06 18:30:43 +00001239 isTrackedLoc = true;
Jordy Rose0fe62f82011-08-24 09:02:37 +00001240 } else {
Ted Kremenek6217b802009-07-29 21:53:49 +00001241 isTrackedLoc = MD->getResultType()->getAs<PointerType>() != NULL;
Jordy Rose0fe62f82011-08-24 09:02:37 +00001242 }
Mike Stump1eb44332009-09-09 15:08:12 +00001243
Ted Kremenek60411112010-02-18 00:06:12 +00001244 if (isTrackedLoc) {
1245 if (MD->getAttr<CFReturnsRetainedAttr>())
Jordy Rose0fe62f82011-08-24 09:02:37 +00001246 Template->setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenek60411112010-02-18 00:06:12 +00001247 else if (MD->getAttr<CFReturnsNotRetainedAttr>())
Jordy Rose0fe62f82011-08-24 09:02:37 +00001248 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::CF));
Ted Kremenek60411112010-02-18 00:06:12 +00001249 }
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001250}
1251
Ted Kremenek93edbc52011-10-05 23:54:29 +00001252const RetainSummary *
Jordy Rosef3aae582012-03-17 21:13:07 +00001253RetainSummaryManager::getStandardMethodSummary(const ObjCMethodDecl *MD,
1254 Selector S, QualType RetTy) {
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001255
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +00001256 if (MD) {
Ted Kremenek376d1e72009-04-24 18:00:17 +00001257 // Scan the method decl for 'void*' arguments. These should be treated
1258 // as 'StopTracking' because they are often used with delegates.
1259 // Delegates are a frequent form of false positives with the retain
1260 // count checker.
1261 unsigned i = 0;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00001262 for (ObjCMethodDecl::param_const_iterator I = MD->param_begin(),
Ted Kremenek376d1e72009-04-24 18:00:17 +00001263 E = MD->param_end(); I != E; ++I, ++i)
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00001264 if (const ParmVarDecl *PD = *I) {
Ted Kremenek376d1e72009-04-24 18:00:17 +00001265 QualType Ty = Ctx.getCanonicalType(PD->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001266 if (Ty.getLocalUnqualifiedType() == Ctx.VoidPtrTy)
Ted Kremenek3baf6722010-11-24 00:54:37 +00001267 ScratchArgs = AF.add(ScratchArgs, i, StopTracking);
Ted Kremenek376d1e72009-04-24 18:00:17 +00001268 }
1269 }
Mike Stump1eb44332009-09-09 15:08:12 +00001270
Jordy Rosee921b1a2012-03-17 19:53:04 +00001271 // Any special effects?
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001272 ArgEffect ReceiverEff = DoNothing;
Jordy Rosee921b1a2012-03-17 19:53:04 +00001273 RetEffect ResultEff = RetEffect::MakeNoRet();
1274
1275 // Check the method family, and apply any default annotations.
1276 switch (MD ? MD->getMethodFamily() : S.getMethodFamily()) {
1277 case OMF_None:
1278 case OMF_performSelector:
1279 // Assume all Objective-C methods follow Cocoa Memory Management rules.
1280 // FIXME: Does the non-threaded performSelector family really belong here?
1281 // The selector could be, say, @selector(copy).
1282 if (cocoa::isCocoaObjectRef(RetTy))
1283 ResultEff = RetEffect::MakeNotOwned(RetEffect::ObjC);
1284 else if (coreFoundation::isCFObjectRef(RetTy)) {
1285 // ObjCMethodDecl currently doesn't consider CF objects as valid return
1286 // values for alloc, new, copy, or mutableCopy, so we have to
1287 // double-check with the selector. This is ugly, but there aren't that
1288 // many Objective-C methods that return CF objects, right?
1289 if (MD) {
1290 switch (S.getMethodFamily()) {
1291 case OMF_alloc:
1292 case OMF_new:
1293 case OMF_copy:
1294 case OMF_mutableCopy:
1295 ResultEff = RetEffect::MakeOwned(RetEffect::CF, true);
1296 break;
1297 default:
1298 ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1299 break;
1300 }
1301 } else {
1302 ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1303 }
1304 }
1305 break;
1306 case OMF_init:
1307 ResultEff = ObjCInitRetE;
1308 ReceiverEff = DecRefMsg;
1309 break;
1310 case OMF_alloc:
1311 case OMF_new:
1312 case OMF_copy:
1313 case OMF_mutableCopy:
1314 if (cocoa::isCocoaObjectRef(RetTy))
1315 ResultEff = ObjCAllocRetE;
1316 else if (coreFoundation::isCFObjectRef(RetTy))
1317 ResultEff = RetEffect::MakeOwned(RetEffect::CF, true);
1318 break;
1319 case OMF_autorelease:
1320 ReceiverEff = Autorelease;
1321 break;
1322 case OMF_retain:
1323 ReceiverEff = IncRefMsg;
1324 break;
1325 case OMF_release:
1326 ReceiverEff = DecRefMsg;
1327 break;
1328 case OMF_dealloc:
1329 ReceiverEff = Dealloc;
1330 break;
1331 case OMF_self:
1332 // -self is handled specially by the ExprEngine to propagate the receiver.
1333 break;
1334 case OMF_retainCount:
1335 case OMF_finalize:
1336 // These methods don't return objects.
1337 break;
1338 }
Mike Stump1eb44332009-09-09 15:08:12 +00001339
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001340 // If one of the arguments in the selector has the keyword 'delegate' we
1341 // should stop tracking the reference count for the receiver. This is
1342 // because the reference count is quite possibly handled by a delegate
1343 // method.
1344 if (S.isKeywordSelector()) {
1345 const std::string &str = S.getAsString();
1346 assert(!str.empty());
Benjamin Kramere45c1492010-01-11 19:46:28 +00001347 if (StrInStrNoCase(str, "delegate:") != StringRef::npos)
1348 ReceiverEff = StopTracking;
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001349 }
Mike Stump1eb44332009-09-09 15:08:12 +00001350
Jordy Rosee921b1a2012-03-17 19:53:04 +00001351 if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing &&
1352 ResultEff.getKind() == RetEffect::NoRet)
Ted Kremenek93edbc52011-10-05 23:54:29 +00001353 return getDefaultSummary();
Mike Stump1eb44332009-09-09 15:08:12 +00001354
Jordy Rosee921b1a2012-03-17 19:53:04 +00001355 return getPersistentSummary(ResultEff, ReceiverEff, MayEscape);
Ted Kremenek250b1fa2009-04-23 23:08:22 +00001356}
1357
Ted Kremenek93edbc52011-10-05 23:54:29 +00001358const RetainSummary *
Argyrios Kyrtzidis432424d2011-01-25 00:03:53 +00001359RetainSummaryManager::getInstanceMethodSummary(const ObjCMessage &msg,
Ted Kremenek8bef8232012-01-26 21:29:00 +00001360 ProgramStateRef state,
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001361 const LocationContext *LC) {
1362
1363 // We need the type-information of the tracked receiver object
1364 // Retrieve it from the state.
Argyrios Kyrtzidis432424d2011-01-25 00:03:53 +00001365 const Expr *Receiver = msg.getInstanceReceiver();
Ted Kremenek9c378f72011-08-12 23:37:29 +00001366 const ObjCInterfaceDecl *ID = 0;
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001367
1368 // FIXME: Is this really working as expected? There are cases where
1369 // we just use the 'ID' from the message expression.
Douglas Gregor04badcf2010-04-21 00:45:42 +00001370 SVal receiverV;
1371
Ted Kremenek8f326752010-05-21 21:56:53 +00001372 if (Receiver) {
Ted Kremenek5eca4822012-01-06 22:09:28 +00001373 receiverV = state->getSValAsScalarOrLoc(Receiver, LC);
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00001374
Douglas Gregor04badcf2010-04-21 00:45:42 +00001375 // FIXME: Eventually replace the use of state->get<RefBindings> with
1376 // a generic API for reasoning about the Objective-C types of symbolic
1377 // objects.
1378 if (SymbolRef Sym = receiverV.getAsLocSymbol())
1379 if (const RefVal *T = state->get<RefBindings>(Sym))
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00001380 if (const ObjCObjectPointerType* PT =
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001381 T->getType()->getAs<ObjCObjectPointerType>())
Douglas Gregor04badcf2010-04-21 00:45:42 +00001382 ID = PT->getInterfaceDecl();
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00001383
Douglas Gregor04badcf2010-04-21 00:45:42 +00001384 // FIXME: this is a hack. This may or may not be the actual method
1385 // that is called.
1386 if (!ID) {
1387 if (const ObjCObjectPointerType *PT =
1388 Receiver->getType()->getAs<ObjCObjectPointerType>())
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001389 ID = PT->getInterfaceDecl();
Douglas Gregor04badcf2010-04-21 00:45:42 +00001390 }
1391 } else {
1392 // FIXME: Hack for 'super'.
Argyrios Kyrtzidis432424d2011-01-25 00:03:53 +00001393 ID = msg.getReceiverInterface();
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001394 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001395
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001396 // FIXME: The receiver could be a reference to a class, meaning that
1397 // we should use the class method.
Jordy Rose4df54fe2011-08-23 04:27:15 +00001398 return getInstanceMethodSummary(msg, ID);
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001399}
1400
Ted Kremenek93edbc52011-10-05 23:54:29 +00001401const RetainSummary *
Jordy Rosef3aae582012-03-17 21:13:07 +00001402RetainSummaryManager::getMethodSummary(Selector S, IdentifierInfo *ClsName,
1403 const ObjCInterfaceDecl *ID,
1404 const ObjCMethodDecl *MD, QualType RetTy,
1405 ObjCMethodSummariesTy &CachedSummaries) {
Ted Kremenek1bffd742008-05-06 15:44:25 +00001406
Ted Kremenek8711c032009-04-29 05:04:30 +00001407 // Look up a summary in our summary cache.
Jordy Rosef3aae582012-03-17 21:13:07 +00001408 const RetainSummary *Summ = CachedSummaries.find(ID, ClsName, S);
Mike Stump1eb44332009-09-09 15:08:12 +00001409
Ted Kremenek614cc542009-07-21 23:27:57 +00001410 if (!Summ) {
Jordy Rosef3aae582012-03-17 21:13:07 +00001411 Summ = getStandardMethodSummary(MD, S, RetTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001412
Ted Kremenek614cc542009-07-21 23:27:57 +00001413 // Annotations override defaults.
Jordy Rose4df54fe2011-08-23 04:27:15 +00001414 updateSummaryFromAnnotations(Summ, MD);
Mike Stump1eb44332009-09-09 15:08:12 +00001415
Ted Kremenek614cc542009-07-21 23:27:57 +00001416 // Memoize the summary.
Jordy Rosef3aae582012-03-17 21:13:07 +00001417 CachedSummaries[ObjCSummaryKey(ID, ClsName, S)] = Summ;
Ted Kremenek614cc542009-07-21 23:27:57 +00001418 }
Mike Stump1eb44332009-09-09 15:08:12 +00001419
Ted Kremeneke87450e2009-04-23 19:11:35 +00001420 return Summ;
Ted Kremenekc8395602008-05-06 21:26:51 +00001421}
1422
Mike Stump1eb44332009-09-09 15:08:12 +00001423void RetainSummaryManager::InitializeClassMethodSummaries() {
Ted Kremenekec315332009-05-07 23:40:42 +00001424 assert(ScratchArgs.isEmpty());
Mike Stump1eb44332009-09-09 15:08:12 +00001425 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek6fe2b7a2009-10-15 22:25:12 +00001426 addClassMethSummary("NSAssertionHandler", "currentHandler",
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001427 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Mike Stump1eb44332009-09-09 15:08:12 +00001428
Ted Kremenek6d348932008-10-21 15:53:15 +00001429 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001430 ScratchArgs = AF.add(ScratchArgs, 0, Autorelease);
Ted Kremenek6fe2b7a2009-10-15 22:25:12 +00001431 addClassMethSummary("NSAutoreleasePool", "addObject",
1432 getPersistentSummary(RetEffect::MakeNoRet(),
1433 DoNothing, Autorelease));
Mike Stump1eb44332009-09-09 15:08:12 +00001434
Ted Kremenekde4d5332009-04-24 17:50:11 +00001435 // Create the summaries for [NSObject performSelector...]. We treat
1436 // these as 'stop tracking' for the arguments because they are often
1437 // used for delegates that can release the object. When we have better
1438 // inter-procedural analysis we can potentially do something better. This
1439 // workaround is to remove false positives.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001440 const RetainSummary *Summ =
Ted Kremenek012614e2011-08-17 21:04:19 +00001441 getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, StopTracking);
Ted Kremenekde4d5332009-04-24 17:50:11 +00001442 IdentifierInfo *NSObjectII = &Ctx.Idents.get("NSObject");
1443 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1444 "afterDelay", NULL);
1445 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1446 "afterDelay", "inModes", NULL);
1447 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1448 "withObject", "waitUntilDone", NULL);
1449 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1450 "withObject", "waitUntilDone", "modes", NULL);
1451 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1452 "withObject", "waitUntilDone", NULL);
1453 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1454 "withObject", "waitUntilDone", "modes", NULL);
1455 addClsMethSummary(NSObjectII, Summ, "performSelectorInBackground",
1456 "withObject", NULL);
Ted Kremenek9c32d082008-05-06 00:30:21 +00001457}
1458
Ted Kremenek1f180c32008-06-23 22:21:20 +00001459void RetainSummaryManager::InitializeMethodSummaries() {
Mike Stump1eb44332009-09-09 15:08:12 +00001460
1461 assert (ScratchArgs.isEmpty());
1462
Ted Kremenekc8395602008-05-06 21:26:51 +00001463 // Create the "init" selector. It just acts as a pass-through for the
1464 // receiver.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001465 const RetainSummary *InitSumm = getPersistentSummary(ObjCInitRetE, DecRefMsg);
Ted Kremenekac02f202009-08-20 05:13:36 +00001466 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
1467
1468 // awakeAfterUsingCoder: behaves basically like an 'init' method. It
1469 // claims the receiver and returns a retained object.
1470 addNSObjectMethSummary(GetUnarySelector("awakeAfterUsingCoder", Ctx),
1471 InitSumm);
Mike Stump1eb44332009-09-09 15:08:12 +00001472
Ted Kremenekc8395602008-05-06 21:26:51 +00001473 // The next methods are allocators.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001474 const RetainSummary *AllocSumm = getPersistentSummary(ObjCAllocRetE);
1475 const RetainSummary *CFAllocSumm =
Ted Kremeneka834fb42009-08-28 19:52:12 +00001476 getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Mike Stump1eb44332009-09-09 15:08:12 +00001477
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001478 // Create the "retain" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001479 RetEffect NoRet = RetEffect::MakeNoRet();
Ted Kremenek93edbc52011-10-05 23:54:29 +00001480 const RetainSummary *Summ = getPersistentSummary(NoRet, IncRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001481 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001482
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001483 // Create the "release" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001484 Summ = getPersistentSummary(NoRet, DecRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001485 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001486
Ted Kremenek299e8152008-05-07 21:17:39 +00001487 // Create the "drain" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001488 Summ = getPersistentSummary(NoRet, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek553cf182008-06-25 21:21:56 +00001489 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001490
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001491 // Create the -dealloc summary.
Jordy Rose500abad2011-08-21 19:41:36 +00001492 Summ = getPersistentSummary(NoRet, Dealloc);
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001493 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001494
1495 // Create the "autorelease" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001496 Summ = getPersistentSummary(NoRet, Autorelease);
Ted Kremenek553cf182008-06-25 21:21:56 +00001497 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001498
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00001499 // Specially handle NSAutoreleasePool.
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001500 addInstMethSummary("NSAutoreleasePool", "init",
Jordy Rose500abad2011-08-21 19:41:36 +00001501 getPersistentSummary(NoRet, NewAutoreleasePool));
Mike Stump1eb44332009-09-09 15:08:12 +00001502
1503 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremenek89e202d2009-02-23 02:51:29 +00001504 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1505 // self-own themselves. However, they only do this once they are displayed.
1506 // Thus, we need to track an NSWindow's display status.
1507 // This is tracked in <rdar://problem/6062711>.
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +00001508 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001509 const RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenek78a35a32009-05-12 20:06:54 +00001510 StopTracking,
1511 StopTracking);
Mike Stump1eb44332009-09-09 15:08:12 +00001512
Ted Kremenek99d02692009-04-03 19:02:51 +00001513 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1514
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +00001515#if 0
Ted Kremenek78a35a32009-05-12 20:06:54 +00001516 addInstMethSummary("NSWindow", NoTrackYet, "initWithContentRect",
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001517 "styleMask", "backing", "defer", NULL);
Mike Stump1eb44332009-09-09 15:08:12 +00001518
Ted Kremenek78a35a32009-05-12 20:06:54 +00001519 addInstMethSummary("NSWindow", NoTrackYet, "initWithContentRect",
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001520 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +00001521#endif
Mike Stump1eb44332009-09-09 15:08:12 +00001522
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001523 // For NSPanel (which subclasses NSWindow), allocated objects are not
1524 // self-owned.
Ted Kremenek99d02692009-04-03 19:02:51 +00001525 // FIXME: For now we don't track NSPanels. object for the same reason
1526 // as for NSWindow objects.
1527 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
Mike Stump1eb44332009-09-09 15:08:12 +00001528
Ted Kremenek78a35a32009-05-12 20:06:54 +00001529#if 0
1530 addInstMethSummary("NSPanel", NoTrackYet, "initWithContentRect",
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001531 "styleMask", "backing", "defer", NULL);
Mike Stump1eb44332009-09-09 15:08:12 +00001532
Ted Kremenek78a35a32009-05-12 20:06:54 +00001533 addInstMethSummary("NSPanel", NoTrackYet, "initWithContentRect",
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001534 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek78a35a32009-05-12 20:06:54 +00001535#endif
Mike Stump1eb44332009-09-09 15:08:12 +00001536
Ted Kremenekba67f6a2009-05-18 23:14:34 +00001537 // Don't track allocated autorelease pools yet, as it is okay to prematurely
1538 // exit a method.
1539 addClassMethSummary("NSAutoreleasePool", "alloc", NoTrackYet);
Ted Kremeneka9797122012-02-18 21:37:48 +00001540 addClassMethSummary("NSAutoreleasePool", "allocWithZone", NoTrackYet, false);
Ted Kremenek553cf182008-06-25 21:21:56 +00001541
Ted Kremenek767d6492009-05-20 22:39:57 +00001542 // Create summaries QCRenderer/QCView -createSnapShotImageOfType:
1543 addInstMethSummary("QCRenderer", AllocSumm,
1544 "createSnapshotImageOfType", NULL);
1545 addInstMethSummary("QCView", AllocSumm,
1546 "createSnapshotImageOfType", NULL);
1547
Ted Kremenek211a9c62009-06-15 20:58:58 +00001548 // Create summaries for CIContext, 'createCGImage' and
Ted Kremeneka834fb42009-08-28 19:52:12 +00001549 // 'createCGLayerWithSize'. These objects are CF objects, and are not
1550 // automatically garbage collected.
1551 addInstMethSummary("CIContext", CFAllocSumm,
Ted Kremenek767d6492009-05-20 22:39:57 +00001552 "createCGImage", "fromRect", NULL);
Ted Kremeneka834fb42009-08-28 19:52:12 +00001553 addInstMethSummary("CIContext", CFAllocSumm,
Mike Stump1eb44332009-09-09 15:08:12 +00001554 "createCGImage", "fromRect", "format", "colorSpace", NULL);
Ted Kremeneka834fb42009-08-28 19:52:12 +00001555 addInstMethSummary("CIContext", CFAllocSumm, "createCGLayerWithSize",
Ted Kremenek211a9c62009-06-15 20:58:58 +00001556 "info", NULL);
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001557}
1558
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001559//===----------------------------------------------------------------------===//
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001560// AutoreleaseBindings - State used to track objects in autorelease pools.
Ted Kremenek6d348932008-10-21 15:53:15 +00001561//===----------------------------------------------------------------------===//
1562
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001563typedef llvm::ImmutableMap<SymbolRef, unsigned> ARCounts;
1564typedef llvm::ImmutableMap<SymbolRef, ARCounts> ARPoolContents;
1565typedef llvm::ImmutableList<SymbolRef> ARStack;
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00001566
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001567static int AutoRCIndex = 0;
Ted Kremenek6d348932008-10-21 15:53:15 +00001568static int AutoRBIndex = 0;
1569
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001570namespace { class AutoreleasePoolContents {}; }
1571namespace { class AutoreleaseStack {}; }
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001572
Ted Kremenek6d348932008-10-21 15:53:15 +00001573namespace clang {
Ted Kremenek9ef65372010-12-23 07:20:52 +00001574namespace ento {
Ted Kremenek18c66fd2011-08-15 22:09:50 +00001575template<> struct ProgramStateTrait<AutoreleaseStack>
1576 : public ProgramStatePartialTrait<ARStack> {
Ted Kremenek9c378f72011-08-12 23:37:29 +00001577 static inline void *GDMIndex() { return &AutoRBIndex; }
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001578};
1579
Ted Kremenek18c66fd2011-08-15 22:09:50 +00001580template<> struct ProgramStateTrait<AutoreleasePoolContents>
1581 : public ProgramStatePartialTrait<ARPoolContents> {
Ted Kremenek9c378f72011-08-12 23:37:29 +00001582 static inline void *GDMIndex() { return &AutoRCIndex; }
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001583};
Argyrios Kyrtzidis5a4f98f2010-12-22 18:53:20 +00001584} // end GR namespace
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001585} // end clang namespace
Ted Kremenek6d348932008-10-21 15:53:15 +00001586
Ted Kremenek8bef8232012-01-26 21:29:00 +00001587static SymbolRef GetCurrentAutoreleasePool(ProgramStateRef state) {
Ted Kremenek7037ab82009-03-20 17:34:15 +00001588 ARStack stack = state->get<AutoreleaseStack>();
1589 return stack.isEmpty() ? SymbolRef() : stack.getHead();
1590}
1591
Ted Kremenek8bef8232012-01-26 21:29:00 +00001592static ProgramStateRef
1593SendAutorelease(ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +00001594 ARCounts::Factory &F,
1595 SymbolRef sym) {
Ted Kremenek7037ab82009-03-20 17:34:15 +00001596 SymbolRef pool = GetCurrentAutoreleasePool(state);
Ted Kremenekb65be702009-06-18 01:23:53 +00001597 const ARCounts *cnts = state->get<AutoreleasePoolContents>(pool);
Ted Kremenek7037ab82009-03-20 17:34:15 +00001598 ARCounts newCnts(0);
Mike Stump1eb44332009-09-09 15:08:12 +00001599
Ted Kremenek7037ab82009-03-20 17:34:15 +00001600 if (cnts) {
1601 const unsigned *cnt = (*cnts).lookup(sym);
Ted Kremenek3baf6722010-11-24 00:54:37 +00001602 newCnts = F.add(*cnts, sym, cnt ? *cnt + 1 : 1);
Ted Kremenek7037ab82009-03-20 17:34:15 +00001603 }
1604 else
Ted Kremenek3baf6722010-11-24 00:54:37 +00001605 newCnts = F.add(F.getEmptyMap(), sym, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001606
Ted Kremenekb65be702009-06-18 01:23:53 +00001607 return state->set<AutoreleasePoolContents>(pool, newCnts);
Ted Kremenek7037ab82009-03-20 17:34:15 +00001608}
1609
Ted Kremenek13922612008-04-16 20:40:59 +00001610//===----------------------------------------------------------------------===//
Ted Kremenekc887d132009-04-29 18:50:19 +00001611// Error reporting.
1612//===----------------------------------------------------------------------===//
Ted Kremenekc887d132009-04-29 18:50:19 +00001613namespace {
Jordy Roseec9ef852011-08-23 20:55:48 +00001614 typedef llvm::DenseMap<const ExplodedNode *, const RetainSummary *>
1615 SummaryLogTy;
1616
Ted Kremenekc887d132009-04-29 18:50:19 +00001617 //===-------------===//
1618 // Bug Descriptions. //
Mike Stump1eb44332009-09-09 15:08:12 +00001619 //===-------------===//
1620
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001621 class CFRefBug : public BugType {
Ted Kremenekc887d132009-04-29 18:50:19 +00001622 protected:
Jordy Rose35c86952011-08-24 05:47:39 +00001623 CFRefBug(StringRef name)
Ted Kremenek6fd45052012-04-05 20:43:28 +00001624 : BugType(name, categories::MemoryCoreFoundationObjectiveC) {}
Ted Kremenekc887d132009-04-29 18:50:19 +00001625 public:
Mike Stump1eb44332009-09-09 15:08:12 +00001626
Ted Kremenekc887d132009-04-29 18:50:19 +00001627 // FIXME: Eventually remove.
Jordy Rose35c86952011-08-24 05:47:39 +00001628 virtual const char *getDescription() const = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001629
Ted Kremenekc887d132009-04-29 18:50:19 +00001630 virtual bool isLeak() const { return false; }
1631 };
Mike Stump1eb44332009-09-09 15:08:12 +00001632
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001633 class UseAfterRelease : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001634 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001635 UseAfterRelease() : CFRefBug("Use-after-release") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001636
Jordy Rose35c86952011-08-24 05:47:39 +00001637 const char *getDescription() const {
Ted Kremenekc887d132009-04-29 18:50:19 +00001638 return "Reference-counted object is used after it is released";
Mike Stump1eb44332009-09-09 15:08:12 +00001639 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001640 };
Mike Stump1eb44332009-09-09 15:08:12 +00001641
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001642 class BadRelease : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001643 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001644 BadRelease() : CFRefBug("Bad release") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001645
Jordy Rose35c86952011-08-24 05:47:39 +00001646 const char *getDescription() const {
Ted Kremenekbb206fd2009-10-01 17:31:50 +00001647 return "Incorrect decrement of the reference count of an object that is "
1648 "not owned at this point by the caller";
Ted Kremenekc887d132009-04-29 18:50:19 +00001649 }
1650 };
Mike Stump1eb44332009-09-09 15:08:12 +00001651
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001652 class DeallocGC : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001653 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001654 DeallocGC()
1655 : CFRefBug("-dealloc called while using garbage collection") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001656
Ted Kremenekc887d132009-04-29 18:50:19 +00001657 const char *getDescription() const {
Ted Kremenek369de562009-05-09 00:10:05 +00001658 return "-dealloc called while using garbage collection";
Ted Kremenekc887d132009-04-29 18:50:19 +00001659 }
1660 };
Mike Stump1eb44332009-09-09 15:08:12 +00001661
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001662 class DeallocNotOwned : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001663 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001664 DeallocNotOwned()
1665 : CFRefBug("-dealloc sent to non-exclusively owned object") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001666
Ted Kremenekc887d132009-04-29 18:50:19 +00001667 const char *getDescription() const {
1668 return "-dealloc sent to object that may be referenced elsewhere";
1669 }
Mike Stump1eb44332009-09-09 15:08:12 +00001670 };
1671
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001672 class OverAutorelease : public CFRefBug {
Ted Kremenek369de562009-05-09 00:10:05 +00001673 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001674 OverAutorelease()
1675 : CFRefBug("Object sent -autorelease too many times") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001676
Ted Kremenek369de562009-05-09 00:10:05 +00001677 const char *getDescription() const {
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001678 return "Object sent -autorelease too many times";
Ted Kremenek369de562009-05-09 00:10:05 +00001679 }
1680 };
Mike Stump1eb44332009-09-09 15:08:12 +00001681
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001682 class ReturnedNotOwnedForOwned : public CFRefBug {
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001683 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001684 ReturnedNotOwnedForOwned()
1685 : CFRefBug("Method should return an owned object") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001686
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001687 const char *getDescription() const {
Jordy Rose5b5402b2011-07-15 22:17:54 +00001688 return "Object with a +0 retain count returned to caller where a +1 "
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001689 "(owning) retain count is expected";
1690 }
1691 };
Mike Stump1eb44332009-09-09 15:08:12 +00001692
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001693 class Leak : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001694 const bool isReturn;
1695 protected:
Jordy Rose35c86952011-08-24 05:47:39 +00001696 Leak(StringRef name, bool isRet)
Jordy Rosedb92bb62011-08-25 01:14:38 +00001697 : CFRefBug(name), isReturn(isRet) {
1698 // Leaks should not be reported if they are post-dominated by a sink.
1699 setSuppressOnSink(true);
1700 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001701 public:
Mike Stump1eb44332009-09-09 15:08:12 +00001702
Jordy Rose35c86952011-08-24 05:47:39 +00001703 const char *getDescription() const { return ""; }
Mike Stump1eb44332009-09-09 15:08:12 +00001704
Ted Kremenekc887d132009-04-29 18:50:19 +00001705 bool isLeak() const { return true; }
1706 };
Mike Stump1eb44332009-09-09 15:08:12 +00001707
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001708 class LeakAtReturn : public Leak {
Ted Kremenekc887d132009-04-29 18:50:19 +00001709 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001710 LeakAtReturn(StringRef name)
1711 : Leak(name, true) {}
Ted Kremenekc887d132009-04-29 18:50:19 +00001712 };
Mike Stump1eb44332009-09-09 15:08:12 +00001713
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001714 class LeakWithinFunction : public Leak {
Ted Kremenekc887d132009-04-29 18:50:19 +00001715 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001716 LeakWithinFunction(StringRef name)
1717 : Leak(name, false) {}
Mike Stump1eb44332009-09-09 15:08:12 +00001718 };
1719
Ted Kremenekc887d132009-04-29 18:50:19 +00001720 //===---------===//
1721 // Bug Reports. //
1722 //===---------===//
Mike Stump1eb44332009-09-09 15:08:12 +00001723
Jordy Rose01153492012-03-24 02:45:35 +00001724 class CFRefReportVisitor : public BugReporterVisitorImpl<CFRefReportVisitor> {
Anna Zaks23f395e2011-08-20 01:27:22 +00001725 protected:
Anna Zaksdc757b02011-08-19 23:21:56 +00001726 SymbolRef Sym;
Jordy Roseec9ef852011-08-23 20:55:48 +00001727 const SummaryLogTy &SummaryLog;
Jordy Rose35c86952011-08-24 05:47:39 +00001728 bool GCEnabled;
Anna Zaks23f395e2011-08-20 01:27:22 +00001729
Anna Zaksdc757b02011-08-19 23:21:56 +00001730 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001731 CFRefReportVisitor(SymbolRef sym, bool gcEnabled, const SummaryLogTy &log)
1732 : Sym(sym), SummaryLog(log), GCEnabled(gcEnabled) {}
Anna Zaksdc757b02011-08-19 23:21:56 +00001733
Anna Zaks23f395e2011-08-20 01:27:22 +00001734 virtual void Profile(llvm::FoldingSetNodeID &ID) const {
Anna Zaksdc757b02011-08-19 23:21:56 +00001735 static int x = 0;
1736 ID.AddPointer(&x);
1737 ID.AddPointer(Sym);
1738 }
1739
Anna Zaks23f395e2011-08-20 01:27:22 +00001740 virtual PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
1741 const ExplodedNode *PrevN,
1742 BugReporterContext &BRC,
1743 BugReport &BR);
1744
1745 virtual PathDiagnosticPiece *getEndPath(BugReporterContext &BRC,
1746 const ExplodedNode *N,
1747 BugReport &BR);
1748 };
1749
1750 class CFRefLeakReportVisitor : public CFRefReportVisitor {
1751 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001752 CFRefLeakReportVisitor(SymbolRef sym, bool GCEnabled,
Jordy Roseec9ef852011-08-23 20:55:48 +00001753 const SummaryLogTy &log)
Jordy Rose35c86952011-08-24 05:47:39 +00001754 : CFRefReportVisitor(sym, GCEnabled, log) {}
Anna Zaks23f395e2011-08-20 01:27:22 +00001755
1756 PathDiagnosticPiece *getEndPath(BugReporterContext &BRC,
1757 const ExplodedNode *N,
1758 BugReport &BR);
Jordy Rose01153492012-03-24 02:45:35 +00001759
1760 virtual BugReporterVisitor *clone() const {
1761 // The curiously-recurring template pattern only works for one level of
1762 // subclassing. Rather than make a new template base for
1763 // CFRefReportVisitor, we simply override clone() to do the right thing.
1764 // This could be trouble someday if BugReporterVisitorImpl is ever
1765 // used for something else besides a convenient implementation of clone().
1766 return new CFRefLeakReportVisitor(*this);
1767 }
Anna Zaksdc757b02011-08-19 23:21:56 +00001768 };
1769
Anna Zakse172e8b2011-08-17 23:00:25 +00001770 class CFRefReport : public BugReport {
Jordy Rose20589562011-08-24 22:39:09 +00001771 void addGCModeDescription(const LangOptions &LOpts, bool GCEnabled);
Jordy Rose35c86952011-08-24 05:47:39 +00001772
Ted Kremenekc887d132009-04-29 18:50:19 +00001773 public:
Jordy Rose20589562011-08-24 22:39:09 +00001774 CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1775 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1776 bool registerVisitor = true)
Anna Zaksedf4dae2011-08-22 18:54:07 +00001777 : BugReport(D, D.getDescription(), n) {
Anna Zaks23f395e2011-08-20 01:27:22 +00001778 if (registerVisitor)
Jordy Rose20589562011-08-24 22:39:09 +00001779 addVisitor(new CFRefReportVisitor(sym, GCEnabled, Log));
1780 addGCModeDescription(LOpts, GCEnabled);
Anna Zaksdc757b02011-08-19 23:21:56 +00001781 }
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001782
Jordy Rose20589562011-08-24 22:39:09 +00001783 CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1784 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1785 StringRef endText)
Anna Zaksedf4dae2011-08-22 18:54:07 +00001786 : BugReport(D, D.getDescription(), endText, n) {
Jordy Rose20589562011-08-24 22:39:09 +00001787 addVisitor(new CFRefReportVisitor(sym, GCEnabled, Log));
1788 addGCModeDescription(LOpts, GCEnabled);
Anna Zaksdc757b02011-08-19 23:21:56 +00001789 }
Mike Stump1eb44332009-09-09 15:08:12 +00001790
Anna Zakse172e8b2011-08-17 23:00:25 +00001791 virtual std::pair<ranges_iterator, ranges_iterator> getRanges() {
Anna Zaksedf4dae2011-08-22 18:54:07 +00001792 const CFRefBug& BugTy = static_cast<CFRefBug&>(getBugType());
1793 if (!BugTy.isLeak())
Anna Zakse172e8b2011-08-17 23:00:25 +00001794 return BugReport::getRanges();
Ted Kremenekc887d132009-04-29 18:50:19 +00001795 else
Argyrios Kyrtzidis640ccf02010-12-04 01:12:15 +00001796 return std::make_pair(ranges_iterator(), ranges_iterator());
Ted Kremenekc887d132009-04-29 18:50:19 +00001797 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001798 };
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001799
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001800 class CFRefLeakReport : public CFRefReport {
Ted Kremenekc887d132009-04-29 18:50:19 +00001801 const MemRegion* AllocBinding;
Anna Zaks23f395e2011-08-20 01:27:22 +00001802
Ted Kremenekc887d132009-04-29 18:50:19 +00001803 public:
Jordy Rose20589562011-08-24 22:39:09 +00001804 CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1805 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
Anna Zaks6a93bd52011-10-25 19:57:11 +00001806 CheckerContext &Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001807
Anna Zaks590dd8e2011-09-20 21:38:35 +00001808 PathDiagnosticLocation getLocation(const SourceManager &SM) const {
1809 assert(Location.isValid());
1810 return Location;
1811 }
Mike Stump1eb44332009-09-09 15:08:12 +00001812 };
Ted Kremenekc887d132009-04-29 18:50:19 +00001813} // end anonymous namespace
1814
Jordy Rose20589562011-08-24 22:39:09 +00001815void CFRefReport::addGCModeDescription(const LangOptions &LOpts,
1816 bool GCEnabled) {
Jordy Rosef95b19d2011-08-24 20:38:42 +00001817 const char *GCModeDescription = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001818
Douglas Gregore289d812011-09-13 17:21:33 +00001819 switch (LOpts.getGC()) {
Anna Zaks7f2531c2011-08-22 20:31:28 +00001820 case LangOptions::GCOnly:
Jordy Rose20589562011-08-24 22:39:09 +00001821 assert(GCEnabled);
Jordy Rose35c86952011-08-24 05:47:39 +00001822 GCModeDescription = "Code is compiled to only use garbage collection";
1823 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001824
Anna Zaks7f2531c2011-08-22 20:31:28 +00001825 case LangOptions::NonGC:
Jordy Rose20589562011-08-24 22:39:09 +00001826 assert(!GCEnabled);
Jordy Rose35c86952011-08-24 05:47:39 +00001827 GCModeDescription = "Code is compiled to use reference counts";
1828 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001829
Anna Zaks7f2531c2011-08-22 20:31:28 +00001830 case LangOptions::HybridGC:
Jordy Rose20589562011-08-24 22:39:09 +00001831 if (GCEnabled) {
Jordy Rose35c86952011-08-24 05:47:39 +00001832 GCModeDescription = "Code is compiled to use either garbage collection "
1833 "(GC) or reference counts (non-GC). The bug occurs "
1834 "with GC enabled";
1835 break;
1836 } else {
1837 GCModeDescription = "Code is compiled to use either garbage collection "
1838 "(GC) or reference counts (non-GC). The bug occurs "
1839 "in non-GC mode";
1840 break;
Anna Zaks7f2531c2011-08-22 20:31:28 +00001841 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001842 }
Jordy Rose35c86952011-08-24 05:47:39 +00001843
Jordy Rosef95b19d2011-08-24 20:38:42 +00001844 assert(GCModeDescription && "invalid/unknown GC mode");
Jordy Rose35c86952011-08-24 05:47:39 +00001845 addExtraText(GCModeDescription);
Ted Kremenekc887d132009-04-29 18:50:19 +00001846}
1847
Jordy Rose910c4052011-09-02 06:44:22 +00001848// FIXME: This should be a method on SmallVector.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001849static inline bool contains(const SmallVectorImpl<ArgEffect>& V,
Ted Kremenekc887d132009-04-29 18:50:19 +00001850 ArgEffect X) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001851 for (SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
Ted Kremenekc887d132009-04-29 18:50:19 +00001852 I!=E; ++I)
1853 if (*I == X) return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001854
Ted Kremenekc887d132009-04-29 18:50:19 +00001855 return false;
1856}
1857
Ted Kremenek4c42bb72011-11-14 21:59:21 +00001858static bool isPropertyAccess(const Stmt *S, ParentMap &PM) {
1859 unsigned maxDepth = 4;
1860 while (S && maxDepth) {
1861 if (const PseudoObjectExpr *PO = dyn_cast<PseudoObjectExpr>(S)) {
1862 if (!isa<ObjCMessageExpr>(PO->getSyntacticForm()))
1863 return true;
1864 return false;
1865 }
1866 S = PM.getParent(S);
1867 --maxDepth;
1868 }
1869 return false;
1870}
1871
Anna Zaksdc757b02011-08-19 23:21:56 +00001872PathDiagnosticPiece *CFRefReportVisitor::VisitNode(const ExplodedNode *N,
1873 const ExplodedNode *PrevN,
1874 BugReporterContext &BRC,
1875 BugReport &BR) {
Mike Stump1eb44332009-09-09 15:08:12 +00001876
Jordy Rosef53e8c72011-08-23 19:43:16 +00001877 if (!isa<StmtPoint>(N->getLocation()))
Ted Kremenek2033a952009-05-13 07:12:33 +00001878 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001879
Ted Kremenek8966bc12009-05-06 21:39:49 +00001880 // Check if the type state has changed.
Ted Kremenek8bef8232012-01-26 21:29:00 +00001881 ProgramStateRef PrevSt = PrevN->getState();
1882 ProgramStateRef CurrSt = N->getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001883 const LocationContext *LCtx = N->getLocationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00001884
1885 const RefVal* CurrT = CurrSt->get<RefBindings>(Sym);
Ted Kremenekc887d132009-04-29 18:50:19 +00001886 if (!CurrT) return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001887
Ted Kremenekb65be702009-06-18 01:23:53 +00001888 const RefVal &CurrV = *CurrT;
1889 const RefVal *PrevT = PrevSt->get<RefBindings>(Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00001890
Ted Kremenekc887d132009-04-29 18:50:19 +00001891 // Create a string buffer to constain all the useful things we want
1892 // to tell the user.
1893 std::string sbuf;
1894 llvm::raw_string_ostream os(sbuf);
Mike Stump1eb44332009-09-09 15:08:12 +00001895
Ted Kremenekc887d132009-04-29 18:50:19 +00001896 // This is the allocation site since the previous node had no bindings
1897 // for this symbol.
1898 if (!PrevT) {
Jordy Rosef53e8c72011-08-23 19:43:16 +00001899 const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
Mike Stump1eb44332009-09-09 15:08:12 +00001900
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001901 if (isa<ObjCArrayLiteral>(S)) {
1902 os << "NSArray literal is an object with a +0 retain count";
Mike Stump1eb44332009-09-09 15:08:12 +00001903 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001904 else if (isa<ObjCDictionaryLiteral>(S)) {
1905 os << "NSDictionary literal is an object with a +0 retain count";
Ted Kremenekc887d132009-04-29 18:50:19 +00001906 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001907 else {
1908 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
1909 // Get the name of the callee (if it is available).
1910 SVal X = CurrSt->getSValAsScalarOrLoc(CE->getCallee(), LCtx);
1911 if (const FunctionDecl *FD = X.getAsFunctionDecl())
1912 os << "Call to function '" << *FD << '\'';
1913 else
1914 os << "function call";
Ted Kremenekc887d132009-04-29 18:50:19 +00001915 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001916 else {
1917 assert(isa<ObjCMessageExpr>(S));
1918 // The message expression may have between written directly or as
1919 // a property access. Lazily determine which case we are looking at.
1920 os << (isPropertyAccess(S, N->getParentMap()) ? "Property" : "Method");
1921 }
1922
1923 if (CurrV.getObjKind() == RetEffect::CF) {
1924 os << " returns a Core Foundation object with a ";
1925 }
1926 else {
1927 assert (CurrV.getObjKind() == RetEffect::ObjC);
1928 os << " returns an Objective-C object with a ";
1929 }
1930
1931 if (CurrV.isOwned()) {
1932 os << "+1 retain count";
1933
1934 if (GCEnabled) {
1935 assert(CurrV.getObjKind() == RetEffect::CF);
1936 os << ". "
1937 "Core Foundation objects are not automatically garbage collected.";
1938 }
1939 }
1940 else {
1941 assert (CurrV.isNotOwned());
1942 os << "+0 retain count";
1943 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001944 }
Mike Stump1eb44332009-09-09 15:08:12 +00001945
Anna Zaks220ac8c2011-09-15 01:08:34 +00001946 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
1947 N->getLocationContext());
Ted Kremenekc887d132009-04-29 18:50:19 +00001948 return new PathDiagnosticEventPiece(Pos, os.str());
1949 }
Mike Stump1eb44332009-09-09 15:08:12 +00001950
Ted Kremenekc887d132009-04-29 18:50:19 +00001951 // Gather up the effects that were performed on the object at this
1952 // program point
Chris Lattner5f9e2722011-07-23 10:55:15 +00001953 SmallVector<ArgEffect, 2> AEffects;
Mike Stump1eb44332009-09-09 15:08:12 +00001954
Jordy Roseec9ef852011-08-23 20:55:48 +00001955 const ExplodedNode *OrigNode = BRC.getNodeResolver().getOriginalNode(N);
1956 if (const RetainSummary *Summ = SummaryLog.lookup(OrigNode)) {
Ted Kremenekc887d132009-04-29 18:50:19 +00001957 // We only have summaries attached to nodes after evaluating CallExpr and
1958 // ObjCMessageExprs.
Jordy Rosef53e8c72011-08-23 19:43:16 +00001959 const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
Mike Stump1eb44332009-09-09 15:08:12 +00001960
Ted Kremenek5f85e172009-07-22 22:35:28 +00001961 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
Ted Kremenekc887d132009-04-29 18:50:19 +00001962 // Iterate through the parameter expressions and see if the symbol
1963 // was ever passed as an argument.
1964 unsigned i = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001965
Ted Kremenek5f85e172009-07-22 22:35:28 +00001966 for (CallExpr::const_arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
Ted Kremenekc887d132009-04-29 18:50:19 +00001967 AI!=AE; ++AI, ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00001968
Ted Kremenekc887d132009-04-29 18:50:19 +00001969 // Retrieve the value of the argument. Is it the symbol
1970 // we are interested in?
Ted Kremenek5eca4822012-01-06 22:09:28 +00001971 if (CurrSt->getSValAsScalarOrLoc(*AI, LCtx).getAsLocSymbol() != Sym)
Ted Kremenekc887d132009-04-29 18:50:19 +00001972 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001973
Ted Kremenekc887d132009-04-29 18:50:19 +00001974 // We have an argument. Get the effect!
1975 AEffects.push_back(Summ->getArg(i));
1976 }
1977 }
Mike Stump1eb44332009-09-09 15:08:12 +00001978 else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00001979 if (const Expr *receiver = ME->getInstanceReceiver())
Ted Kremenek5eca4822012-01-06 22:09:28 +00001980 if (CurrSt->getSValAsScalarOrLoc(receiver, LCtx)
1981 .getAsLocSymbol() == Sym) {
Ted Kremenekc887d132009-04-29 18:50:19 +00001982 // The symbol we are tracking is the receiver.
1983 AEffects.push_back(Summ->getReceiverEffect());
1984 }
1985 }
1986 }
Mike Stump1eb44332009-09-09 15:08:12 +00001987
Ted Kremenekc887d132009-04-29 18:50:19 +00001988 do {
1989 // Get the previous type state.
1990 RefVal PrevV = *PrevT;
Mike Stump1eb44332009-09-09 15:08:12 +00001991
Ted Kremenekc887d132009-04-29 18:50:19 +00001992 // Specially handle -dealloc.
Jordy Rose35c86952011-08-24 05:47:39 +00001993 if (!GCEnabled && contains(AEffects, Dealloc)) {
Ted Kremenekc887d132009-04-29 18:50:19 +00001994 // Determine if the object's reference count was pushed to zero.
1995 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
1996 // We may not have transitioned to 'release' if we hit an error.
1997 // This case is handled elsewhere.
1998 if (CurrV.getKind() == RefVal::Released) {
Ted Kremenekf21332e2009-05-08 20:01:42 +00001999 assert(CurrV.getCombinedCounts() == 0);
Ted Kremenekc887d132009-04-29 18:50:19 +00002000 os << "Object released by directly sending the '-dealloc' message";
2001 break;
2002 }
2003 }
Mike Stump1eb44332009-09-09 15:08:12 +00002004
Ted Kremenekc887d132009-04-29 18:50:19 +00002005 // Specially handle CFMakeCollectable and friends.
2006 if (contains(AEffects, MakeCollectable)) {
2007 // Get the name of the function.
Jordy Rosef53e8c72011-08-23 19:43:16 +00002008 const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
Ted Kremenek5eca4822012-01-06 22:09:28 +00002009 SVal X =
2010 CurrSt->getSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee(), LCtx);
Ted Kremenek9c378f72011-08-12 23:37:29 +00002011 const FunctionDecl *FD = X.getAsFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002012
Jordy Rose35c86952011-08-24 05:47:39 +00002013 if (GCEnabled) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002014 // Determine if the object's reference count was pushed to zero.
2015 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
Mike Stump1eb44332009-09-09 15:08:12 +00002016
Benjamin Kramerb8989f22011-10-14 18:45:37 +00002017 os << "In GC mode a call to '" << *FD
Ted Kremenekc887d132009-04-29 18:50:19 +00002018 << "' decrements an object's retain count and registers the "
2019 "object with the garbage collector. ";
Mike Stump1eb44332009-09-09 15:08:12 +00002020
Ted Kremenekc887d132009-04-29 18:50:19 +00002021 if (CurrV.getKind() == RefVal::Released) {
2022 assert(CurrV.getCount() == 0);
2023 os << "Since it now has a 0 retain count the object can be "
2024 "automatically collected by the garbage collector.";
2025 }
2026 else
2027 os << "An object must have a 0 retain count to be garbage collected. "
2028 "After this call its retain count is +" << CurrV.getCount()
2029 << '.';
2030 }
Mike Stump1eb44332009-09-09 15:08:12 +00002031 else
Benjamin Kramerb8989f22011-10-14 18:45:37 +00002032 os << "When GC is not enabled a call to '" << *FD
Ted Kremenekc887d132009-04-29 18:50:19 +00002033 << "' has no effect on its argument.";
Mike Stump1eb44332009-09-09 15:08:12 +00002034
Ted Kremenekc887d132009-04-29 18:50:19 +00002035 // Nothing more to say.
2036 break;
2037 }
Mike Stump1eb44332009-09-09 15:08:12 +00002038
2039 // Determine if the typestate has changed.
Ted Kremenekc887d132009-04-29 18:50:19 +00002040 if (!(PrevV == CurrV))
2041 switch (CurrV.getKind()) {
2042 case RefVal::Owned:
2043 case RefVal::NotOwned:
Mike Stump1eb44332009-09-09 15:08:12 +00002044
Ted Kremenekf21332e2009-05-08 20:01:42 +00002045 if (PrevV.getCount() == CurrV.getCount()) {
2046 // Did an autorelease message get sent?
2047 if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
2048 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002049
Zhongxing Xu264e9372009-05-12 10:10:00 +00002050 assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount());
Ted Kremenekeaedfea2009-05-10 05:11:21 +00002051 os << "Object sent -autorelease message";
Ted Kremenekf21332e2009-05-08 20:01:42 +00002052 break;
2053 }
Mike Stump1eb44332009-09-09 15:08:12 +00002054
Ted Kremenekc887d132009-04-29 18:50:19 +00002055 if (PrevV.getCount() > CurrV.getCount())
2056 os << "Reference count decremented.";
2057 else
2058 os << "Reference count incremented.";
Mike Stump1eb44332009-09-09 15:08:12 +00002059
Ted Kremenekc887d132009-04-29 18:50:19 +00002060 if (unsigned Count = CurrV.getCount())
2061 os << " The object now has a +" << Count << " retain count.";
Mike Stump1eb44332009-09-09 15:08:12 +00002062
Ted Kremenekc887d132009-04-29 18:50:19 +00002063 if (PrevV.getKind() == RefVal::Released) {
Jordy Rose35c86952011-08-24 05:47:39 +00002064 assert(GCEnabled && CurrV.getCount() > 0);
Jordy Rose74b7b2b2012-03-17 05:49:15 +00002065 os << " The object is not eligible for garbage collection until "
2066 "the retain count reaches 0 again.";
Ted Kremenekc887d132009-04-29 18:50:19 +00002067 }
Mike Stump1eb44332009-09-09 15:08:12 +00002068
Ted Kremenekc887d132009-04-29 18:50:19 +00002069 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002070
Ted Kremenekc887d132009-04-29 18:50:19 +00002071 case RefVal::Released:
2072 os << "Object released.";
2073 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002074
Ted Kremenekc887d132009-04-29 18:50:19 +00002075 case RefVal::ReturnedOwned:
Jordy Rose74b7b2b2012-03-17 05:49:15 +00002076 // Autoreleases can be applied after marking a node ReturnedOwned.
2077 if (CurrV.getAutoreleaseCount())
2078 return NULL;
2079
2080 os << "Object returned to caller as an owning reference (single "
2081 "retain count transferred to caller)";
Ted Kremenekc887d132009-04-29 18:50:19 +00002082 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002083
Ted Kremenekc887d132009-04-29 18:50:19 +00002084 case RefVal::ReturnedNotOwned:
Ted Kremenekf1365462011-05-26 18:45:44 +00002085 os << "Object returned to caller with a +0 retain count";
Ted Kremenekc887d132009-04-29 18:50:19 +00002086 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002087
Ted Kremenekc887d132009-04-29 18:50:19 +00002088 default:
2089 return NULL;
2090 }
Mike Stump1eb44332009-09-09 15:08:12 +00002091
Ted Kremenekc887d132009-04-29 18:50:19 +00002092 // Emit any remaining diagnostics for the argument effects (if any).
Chris Lattner5f9e2722011-07-23 10:55:15 +00002093 for (SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
Ted Kremenekc887d132009-04-29 18:50:19 +00002094 E=AEffects.end(); I != E; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +00002095
Ted Kremenekc887d132009-04-29 18:50:19 +00002096 // A bunch of things have alternate behavior under GC.
Jordy Rose35c86952011-08-24 05:47:39 +00002097 if (GCEnabled)
Ted Kremenekc887d132009-04-29 18:50:19 +00002098 switch (*I) {
2099 default: break;
2100 case Autorelease:
2101 os << "In GC mode an 'autorelease' has no effect.";
2102 continue;
2103 case IncRefMsg:
2104 os << "In GC mode the 'retain' message has no effect.";
2105 continue;
2106 case DecRefMsg:
2107 os << "In GC mode the 'release' message has no effect.";
2108 continue;
2109 }
2110 }
Mike Stump1eb44332009-09-09 15:08:12 +00002111 } while (0);
2112
Ted Kremenekc887d132009-04-29 18:50:19 +00002113 if (os.str().empty())
2114 return 0; // We have nothing to say!
Ted Kremenek2033a952009-05-13 07:12:33 +00002115
Jordy Rosef53e8c72011-08-23 19:43:16 +00002116 const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
Anna Zaks220ac8c2011-09-15 01:08:34 +00002117 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
2118 N->getLocationContext());
Ted Kremenek9c378f72011-08-12 23:37:29 +00002119 PathDiagnosticPiece *P = new PathDiagnosticEventPiece(Pos, os.str());
Mike Stump1eb44332009-09-09 15:08:12 +00002120
Ted Kremenekc887d132009-04-29 18:50:19 +00002121 // Add the range by scanning the children of the statement for any bindings
2122 // to Sym.
Mike Stump1eb44332009-09-09 15:08:12 +00002123 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
Ted Kremenek5f85e172009-07-22 22:35:28 +00002124 I!=E; ++I)
Ted Kremenek9c378f72011-08-12 23:37:29 +00002125 if (const Expr *Exp = dyn_cast_or_null<Expr>(*I))
Ted Kremenek5eca4822012-01-06 22:09:28 +00002126 if (CurrSt->getSValAsScalarOrLoc(Exp, LCtx).getAsLocSymbol() == Sym) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002127 P->addRange(Exp->getSourceRange());
2128 break;
2129 }
Mike Stump1eb44332009-09-09 15:08:12 +00002130
Ted Kremenekc887d132009-04-29 18:50:19 +00002131 return P;
2132}
2133
Anna Zakse7e01682012-02-28 22:39:22 +00002134// Find the first node in the current function context that referred to the
2135// tracked symbol and the memory location that value was stored to. Note, the
2136// value is only reported if the allocation occurred in the same function as
2137// the leak.
Zhongxing Xuc5619d92009-08-06 01:32:16 +00002138static std::pair<const ExplodedNode*,const MemRegion*>
Ted Kremenek18c66fd2011-08-15 22:09:50 +00002139GetAllocationSite(ProgramStateManager& StateMgr, const ExplodedNode *N,
Ted Kremenekc887d132009-04-29 18:50:19 +00002140 SymbolRef Sym) {
Ted Kremenek9c378f72011-08-12 23:37:29 +00002141 const ExplodedNode *Last = N;
Mike Stump1eb44332009-09-09 15:08:12 +00002142 const MemRegion* FirstBinding = 0;
Anna Zakse7e01682012-02-28 22:39:22 +00002143 const LocationContext *LeakContext = N->getLocationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002144
Ted Kremenekc887d132009-04-29 18:50:19 +00002145 while (N) {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002146 ProgramStateRef St = N->getState();
Ted Kremenekc887d132009-04-29 18:50:19 +00002147 RefBindings B = St->get<RefBindings>();
Mike Stump1eb44332009-09-09 15:08:12 +00002148
Ted Kremenekc887d132009-04-29 18:50:19 +00002149 if (!B.lookup(Sym))
2150 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002151
Anna Zaks27b867e2012-03-21 19:45:01 +00002152 StoreManager::FindUniqueBinding FB(Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002153 StateMgr.iterBindings(St, FB);
2154 if (FB) FirstBinding = FB.getRegion();
2155
Anna Zakse7e01682012-02-28 22:39:22 +00002156 // Allocation node, is the last node in the current context in which the
2157 // symbol was tracked.
2158 if (N->getLocationContext() == LeakContext)
2159 Last = N;
2160
Mike Stump1eb44332009-09-09 15:08:12 +00002161 N = N->pred_empty() ? NULL : *(N->pred_begin());
Ted Kremenekc887d132009-04-29 18:50:19 +00002162 }
Mike Stump1eb44332009-09-09 15:08:12 +00002163
Anna Zakse7e01682012-02-28 22:39:22 +00002164 // If allocation happened in a function different from the leak node context,
2165 // do not report the binding.
2166 if (N->getLocationContext() != LeakContext) {
2167 FirstBinding = 0;
2168 }
2169
Ted Kremenekc887d132009-04-29 18:50:19 +00002170 return std::make_pair(Last, FirstBinding);
2171}
2172
2173PathDiagnosticPiece*
Anna Zaks23f395e2011-08-20 01:27:22 +00002174CFRefReportVisitor::getEndPath(BugReporterContext &BRC,
2175 const ExplodedNode *EndN,
2176 BugReport &BR) {
Ted Kremenek76aadc32012-03-09 01:13:14 +00002177 BR.markInteresting(Sym);
Anna Zaks23f395e2011-08-20 01:27:22 +00002178 return BugReporterVisitor::getDefaultEndPath(BRC, EndN, BR);
Ted Kremenekc887d132009-04-29 18:50:19 +00002179}
2180
2181PathDiagnosticPiece*
Anna Zaks23f395e2011-08-20 01:27:22 +00002182CFRefLeakReportVisitor::getEndPath(BugReporterContext &BRC,
2183 const ExplodedNode *EndN,
2184 BugReport &BR) {
Mike Stump1eb44332009-09-09 15:08:12 +00002185
Ted Kremenek8966bc12009-05-06 21:39:49 +00002186 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenekc887d132009-04-29 18:50:19 +00002187 // assigned to different variables, etc.
Ted Kremenek76aadc32012-03-09 01:13:14 +00002188 BR.markInteresting(Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002189
Ted Kremenekc887d132009-04-29 18:50:19 +00002190 // We are reporting a leak. Walk up the graph to get to the first node where
2191 // the symbol appeared, and also get the first VarDecl that tracked object
2192 // is stored to.
Ted Kremenek9c378f72011-08-12 23:37:29 +00002193 const ExplodedNode *AllocNode = 0;
Ted Kremenekc887d132009-04-29 18:50:19 +00002194 const MemRegion* FirstBinding = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002195
Ted Kremenekc887d132009-04-29 18:50:19 +00002196 llvm::tie(AllocNode, FirstBinding) =
Ted Kremenekf04dced2009-05-08 23:32:51 +00002197 GetAllocationSite(BRC.getStateManager(), EndN, Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002198
Anna Zaks4fdf97b2011-09-15 18:56:07 +00002199 SourceManager& SM = BRC.getSourceManager();
Mike Stump1eb44332009-09-09 15:08:12 +00002200
Ted Kremenekc887d132009-04-29 18:50:19 +00002201 // Compute an actual location for the leak. Sometimes a leak doesn't
2202 // occur at an actual statement (e.g., transition between blocks; end
2203 // of function) so we need to walk the graph and compute a real location.
Ted Kremenek9c378f72011-08-12 23:37:29 +00002204 const ExplodedNode *LeakN = EndN;
Anna Zaks4fdf97b2011-09-15 18:56:07 +00002205 PathDiagnosticLocation L = PathDiagnosticLocation::createEndOfPath(LeakN, SM);
Mike Stump1eb44332009-09-09 15:08:12 +00002206
Ted Kremenekc887d132009-04-29 18:50:19 +00002207 std::string sbuf;
2208 llvm::raw_string_ostream os(sbuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002209
Ted Kremenekf1365462011-05-26 18:45:44 +00002210 os << "Object leaked: ";
Mike Stump1eb44332009-09-09 15:08:12 +00002211
Ted Kremenekf1365462011-05-26 18:45:44 +00002212 if (FirstBinding) {
2213 os << "object allocated and stored into '"
2214 << FirstBinding->getString() << '\'';
2215 }
2216 else
2217 os << "allocated object";
Mike Stump1eb44332009-09-09 15:08:12 +00002218
Ted Kremenekc887d132009-04-29 18:50:19 +00002219 // Get the retain count.
2220 const RefVal* RV = EndN->getState()->get<RefBindings>(Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002221
Ted Kremenekc887d132009-04-29 18:50:19 +00002222 if (RV->getKind() == RefVal::ErrorLeakReturned) {
2223 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
Jordy Rose5b5402b2011-07-15 22:17:54 +00002224 // objects. Only "copy", "alloc", "retain" and "new" transfer ownership
Ted Kremenekc887d132009-04-29 18:50:19 +00002225 // to the caller for NS objects.
Ted Kremenekd368d712011-05-25 06:19:45 +00002226 const Decl *D = &EndN->getCodeDecl();
2227 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2228 os << " is returned from a method whose name ('"
2229 << MD->getSelector().getAsString()
2230 << "') does not start with 'copy', 'mutableCopy', 'alloc' or 'new'."
Jordy Rose5b5402b2011-07-15 22:17:54 +00002231 " This violates the naming convention rules"
Ted Kremenekf1365462011-05-26 18:45:44 +00002232 " given in the Memory Management Guide for Cocoa";
Ted Kremenekd368d712011-05-25 06:19:45 +00002233 }
2234 else {
2235 const FunctionDecl *FD = cast<FunctionDecl>(D);
Ted Kremenekb7dcddf2011-12-22 06:35:52 +00002236 os << " is returned from a function whose name ('"
Benjamin Kramera59d20b2012-02-07 11:57:57 +00002237 << *FD
Ted Kremenekd368d712011-05-25 06:19:45 +00002238 << "') does not contain 'Copy' or 'Create'. This violates the naming"
Ted Kremenekb7dcddf2011-12-22 06:35:52 +00002239 " convention rules given in the Memory Management Guide for Core"
Ted Kremenekf1365462011-05-26 18:45:44 +00002240 " Foundation";
Ted Kremenekd368d712011-05-25 06:19:45 +00002241 }
Ted Kremenekc887d132009-04-29 18:50:19 +00002242 }
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002243 else if (RV->getKind() == RefVal::ErrorGCLeakReturned) {
Ted Kremenek9c378f72011-08-12 23:37:29 +00002244 ObjCMethodDecl &MD = cast<ObjCMethodDecl>(EndN->getCodeDecl());
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002245 os << " and returned from method '" << MD.getSelector().getAsString()
Ted Kremenek82f2be52009-05-10 16:52:15 +00002246 << "' is potentially leaked when using garbage collection. Callers "
2247 "of this method do not expect a returned object with a +1 retain "
2248 "count since they expect the object to be managed by the garbage "
2249 "collector";
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002250 }
Ted Kremenekc887d132009-04-29 18:50:19 +00002251 else
Ted Kremenekabf517c2010-10-15 22:50:23 +00002252 os << " is not referenced later in this execution path and has a retain "
Ted Kremenekf1365462011-05-26 18:45:44 +00002253 "count of +" << RV->getCount();
Mike Stump1eb44332009-09-09 15:08:12 +00002254
Ted Kremenekc887d132009-04-29 18:50:19 +00002255 return new PathDiagnosticEventPiece(L, os.str());
2256}
2257
Jordy Rose20589562011-08-24 22:39:09 +00002258CFRefLeakReport::CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts,
2259 bool GCEnabled, const SummaryLogTy &Log,
2260 ExplodedNode *n, SymbolRef sym,
Anna Zaks6a93bd52011-10-25 19:57:11 +00002261 CheckerContext &Ctx)
Jordy Rose20589562011-08-24 22:39:09 +00002262: CFRefReport(D, LOpts, GCEnabled, Log, n, sym, false) {
Mike Stump1eb44332009-09-09 15:08:12 +00002263
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00002264 // Most bug reports are cached at the location where they occurred.
Ted Kremenekc887d132009-04-29 18:50:19 +00002265 // With leaks, we want to unique them by the location where they were
2266 // allocated, and only report a single path. To do this, we need to find
2267 // the allocation site of a piece of tracked memory, which we do via a
2268 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2269 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2270 // that all ancestor nodes that represent the allocation site have the
2271 // same SourceLocation.
Ted Kremenek9c378f72011-08-12 23:37:29 +00002272 const ExplodedNode *AllocNode = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002273
Anna Zaks6a93bd52011-10-25 19:57:11 +00002274 const SourceManager& SMgr = Ctx.getSourceManager();
Anna Zaks590dd8e2011-09-20 21:38:35 +00002275
Ted Kremenekc887d132009-04-29 18:50:19 +00002276 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding.
Anna Zaks6a93bd52011-10-25 19:57:11 +00002277 GetAllocationSite(Ctx.getStateManager(), getErrorNode(), sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002278
Ted Kremenekc887d132009-04-29 18:50:19 +00002279 // Get the SourceLocation for the allocation site.
2280 ProgramPoint P = AllocNode->getLocation();
Anna Zaks590dd8e2011-09-20 21:38:35 +00002281 const Stmt *AllocStmt = cast<PostStmt>(P).getStmt();
2282 Location = PathDiagnosticLocation::createBegin(AllocStmt, SMgr,
2283 n->getLocationContext());
Ted Kremenekc887d132009-04-29 18:50:19 +00002284 // Fill in the description of the bug.
2285 Description.clear();
2286 llvm::raw_string_ostream os(Description);
Ted Kremenekdd924e22009-05-02 19:05:19 +00002287 os << "Potential leak ";
Jordy Rose20589562011-08-24 22:39:09 +00002288 if (GCEnabled)
Ted Kremenekdd924e22009-05-02 19:05:19 +00002289 os << "(when using garbage collection) ";
Anna Zaks212000e2012-02-28 21:49:08 +00002290 os << "of an object";
Mike Stump1eb44332009-09-09 15:08:12 +00002291
Ted Kremenekc887d132009-04-29 18:50:19 +00002292 // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2293 if (AllocBinding)
Anna Zaks212000e2012-02-28 21:49:08 +00002294 os << " stored into '" << AllocBinding->getString() << '\'';
Anna Zaksdc757b02011-08-19 23:21:56 +00002295
Jordy Rose20589562011-08-24 22:39:09 +00002296 addVisitor(new CFRefLeakReportVisitor(sym, GCEnabled, Log));
Ted Kremenekc887d132009-04-29 18:50:19 +00002297}
2298
2299//===----------------------------------------------------------------------===//
2300// Main checker logic.
2301//===----------------------------------------------------------------------===//
2302
Ted Kremenekd593eb92009-11-25 22:17:44 +00002303namespace {
Jordy Rose910c4052011-09-02 06:44:22 +00002304class RetainCountChecker
Jordy Rose9c083b72011-08-24 18:56:32 +00002305 : public Checker< check::Bind,
Jordy Rose38f17d62011-08-23 19:01:07 +00002306 check::DeadSymbols,
Jordy Rose9c083b72011-08-24 18:56:32 +00002307 check::EndAnalysis,
Jordy Rose38f17d62011-08-23 19:01:07 +00002308 check::EndPath,
Jordy Rose67044292011-08-17 21:27:39 +00002309 check::PostStmt<BlockExpr>,
John McCallf85e1932011-06-15 23:02:42 +00002310 check::PostStmt<CastExpr>,
Jordy Rose294396b2011-08-22 23:48:23 +00002311 check::PostStmt<CallExpr>,
Jordy Rose537716a2011-08-27 22:51:26 +00002312 check::PostStmt<CXXConstructExpr>,
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002313 check::PostStmt<ObjCArrayLiteral>,
2314 check::PostStmt<ObjCDictionaryLiteral>,
Jordy Rose294396b2011-08-22 23:48:23 +00002315 check::PostObjCMessage,
Jordy Rosef53e8c72011-08-23 19:43:16 +00002316 check::PreStmt<ReturnStmt>,
Jordy Rose67044292011-08-17 21:27:39 +00002317 check::RegionChanges,
Jordy Rose76c506f2011-08-21 21:58:18 +00002318 eval::Assume,
2319 eval::Call > {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002320 mutable OwningPtr<CFRefBug> useAfterRelease, releaseNotOwned;
2321 mutable OwningPtr<CFRefBug> deallocGC, deallocNotOwned;
2322 mutable OwningPtr<CFRefBug> overAutorelease, returnNotOwnedForOwned;
2323 mutable OwningPtr<CFRefBug> leakWithinFunction, leakAtReturn;
2324 mutable OwningPtr<CFRefBug> leakWithinFunctionGC, leakAtReturnGC;
Jordy Rose38f17d62011-08-23 19:01:07 +00002325
2326 typedef llvm::DenseMap<SymbolRef, const SimpleProgramPointTag *> SymbolTagMap;
2327
2328 // This map is only used to ensure proper deletion of any allocated tags.
2329 mutable SymbolTagMap DeadSymbolTags;
2330
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002331 mutable OwningPtr<RetainSummaryManager> Summaries;
2332 mutable OwningPtr<RetainSummaryManager> SummariesGC;
Jordy Roseb6cfc092011-08-25 00:10:37 +00002333
Jordy Rosee0a5d322011-08-23 20:27:16 +00002334 mutable ARCounts::Factory ARCountFactory;
2335
Jordy Rose9c083b72011-08-24 18:56:32 +00002336 mutable SummaryLogTy SummaryLog;
2337 mutable bool ShouldResetSummaryLog;
2338
Jordy Rose2f9a66d2011-08-20 21:17:59 +00002339public:
Jordy Rose910c4052011-09-02 06:44:22 +00002340 RetainCountChecker() : ShouldResetSummaryLog(false) {}
Jordy Rose38f17d62011-08-23 19:01:07 +00002341
Jordy Rose910c4052011-09-02 06:44:22 +00002342 virtual ~RetainCountChecker() {
Jordy Rose38f17d62011-08-23 19:01:07 +00002343 DeleteContainerSeconds(DeadSymbolTags);
2344 }
2345
Jordy Rose9c083b72011-08-24 18:56:32 +00002346 void checkEndAnalysis(ExplodedGraph &G, BugReporter &BR,
2347 ExprEngine &Eng) const {
2348 // FIXME: This is a hack to make sure the summary log gets cleared between
2349 // analyses of different code bodies.
2350 //
2351 // Why is this necessary? Because a checker's lifetime is tied to a
2352 // translation unit, but an ExplodedGraph's lifetime is just a code body.
2353 // Once in a blue moon, a new ExplodedNode will have the same address as an
2354 // old one with an associated summary, and the bug report visitor gets very
2355 // confused. (To make things worse, the summary lifetime is currently also
2356 // tied to a code body, so we get a crash instead of incorrect results.)
Jordy Rose1ab51c72011-08-24 09:27:24 +00002357 //
2358 // Why is this a bad solution? Because if the lifetime of the ExplodedGraph
2359 // changes, things will start going wrong again. Really the lifetime of this
2360 // log needs to be tied to either the specific nodes in it or the entire
2361 // ExplodedGraph, not to a specific part of the code being analyzed.
2362 //
Jordy Rose9c083b72011-08-24 18:56:32 +00002363 // (Also, having stateful local data means that the same checker can't be
2364 // used from multiple threads, but a lot of checkers have incorrect
2365 // assumptions about that anyway. So that wasn't a priority at the time of
2366 // this fix.)
Jordy Rose1ab51c72011-08-24 09:27:24 +00002367 //
Jordy Rose9c083b72011-08-24 18:56:32 +00002368 // This happens at the end of analysis, but bug reports are emitted /after/
2369 // this point. So we can't just clear the summary log now. Instead, we mark
2370 // that the next time we access the summary log, it should be cleared.
2371
2372 // If we never reset the summary log during /this/ code body analysis,
2373 // there were no new summaries. There might still have been summaries from
2374 // the /last/ analysis, so clear them out to make sure the bug report
2375 // visitors don't get confused.
2376 if (ShouldResetSummaryLog)
2377 SummaryLog.clear();
2378
2379 ShouldResetSummaryLog = !SummaryLog.empty();
Jordy Rose1ab51c72011-08-24 09:27:24 +00002380 }
2381
Jordy Rose17a38e22011-09-02 05:55:19 +00002382 CFRefBug *getLeakWithinFunctionBug(const LangOptions &LOpts,
2383 bool GCEnabled) const {
2384 if (GCEnabled) {
Jordy Rosedb92bb62011-08-25 01:14:38 +00002385 if (!leakWithinFunctionGC)
2386 leakWithinFunctionGC.reset(new LeakWithinFunction("Leak of object when "
2387 "using garbage "
2388 "collection"));
Jordy Rose17a38e22011-09-02 05:55:19 +00002389 return leakWithinFunctionGC.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002390 } else {
2391 if (!leakWithinFunction) {
Douglas Gregore289d812011-09-13 17:21:33 +00002392 if (LOpts.getGC() == LangOptions::HybridGC) {
Jordy Rosedb92bb62011-08-25 01:14:38 +00002393 leakWithinFunction.reset(new LeakWithinFunction("Leak of object when "
2394 "not using garbage "
2395 "collection (GC) in "
2396 "dual GC/non-GC "
2397 "code"));
2398 } else {
2399 leakWithinFunction.reset(new LeakWithinFunction("Leak"));
2400 }
2401 }
Jordy Rose17a38e22011-09-02 05:55:19 +00002402 return leakWithinFunction.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002403 }
2404 }
2405
Jordy Rose17a38e22011-09-02 05:55:19 +00002406 CFRefBug *getLeakAtReturnBug(const LangOptions &LOpts, bool GCEnabled) const {
2407 if (GCEnabled) {
Jordy Rosedb92bb62011-08-25 01:14:38 +00002408 if (!leakAtReturnGC)
2409 leakAtReturnGC.reset(new LeakAtReturn("Leak of returned object when "
2410 "using garbage collection"));
Jordy Rose17a38e22011-09-02 05:55:19 +00002411 return leakAtReturnGC.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002412 } else {
2413 if (!leakAtReturn) {
Douglas Gregore289d812011-09-13 17:21:33 +00002414 if (LOpts.getGC() == LangOptions::HybridGC) {
Jordy Rosedb92bb62011-08-25 01:14:38 +00002415 leakAtReturn.reset(new LeakAtReturn("Leak of returned object when "
2416 "not using garbage collection "
2417 "(GC) in dual GC/non-GC code"));
2418 } else {
2419 leakAtReturn.reset(new LeakAtReturn("Leak of returned object"));
2420 }
2421 }
Jordy Rose17a38e22011-09-02 05:55:19 +00002422 return leakAtReturn.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002423 }
2424 }
2425
Jordy Rose17a38e22011-09-02 05:55:19 +00002426 RetainSummaryManager &getSummaryManager(ASTContext &Ctx,
2427 bool GCEnabled) const {
2428 // FIXME: We don't support ARC being turned on and off during one analysis.
2429 // (nor, for that matter, do we support changing ASTContexts)
David Blaikie4e4d0842012-03-11 07:00:24 +00002430 bool ARCEnabled = (bool)Ctx.getLangOpts().ObjCAutoRefCount;
Jordy Rose17a38e22011-09-02 05:55:19 +00002431 if (GCEnabled) {
2432 if (!SummariesGC)
Jordy Roseb6cfc092011-08-25 00:10:37 +00002433 SummariesGC.reset(new RetainSummaryManager(Ctx, true, ARCEnabled));
Jordy Rose17a38e22011-09-02 05:55:19 +00002434 else
2435 assert(SummariesGC->isARCEnabled() == ARCEnabled);
Jordy Roseb6cfc092011-08-25 00:10:37 +00002436 return *SummariesGC;
2437 } else {
Jordy Rose17a38e22011-09-02 05:55:19 +00002438 if (!Summaries)
Jordy Roseb6cfc092011-08-25 00:10:37 +00002439 Summaries.reset(new RetainSummaryManager(Ctx, false, ARCEnabled));
Jordy Rose17a38e22011-09-02 05:55:19 +00002440 else
2441 assert(Summaries->isARCEnabled() == ARCEnabled);
Jordy Roseb6cfc092011-08-25 00:10:37 +00002442 return *Summaries;
2443 }
2444 }
2445
Jordy Rose17a38e22011-09-02 05:55:19 +00002446 RetainSummaryManager &getSummaryManager(CheckerContext &C) const {
2447 return getSummaryManager(C.getASTContext(), C.isObjCGCEnabled());
2448 }
2449
Ted Kremenek8bef8232012-01-26 21:29:00 +00002450 void printState(raw_ostream &Out, ProgramStateRef State,
Jordy Rosedbd658e2011-08-28 19:11:56 +00002451 const char *NL, const char *Sep) const;
2452
Anna Zaks390909c2011-10-06 00:43:15 +00002453 void checkBind(SVal loc, SVal val, const Stmt *S, CheckerContext &C) const;
Jordy Roseab027fd2011-08-20 21:16:58 +00002454 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
2455 void checkPostStmt(const CastExpr *CE, CheckerContext &C) const;
John McCallf85e1932011-06-15 23:02:42 +00002456
Jordy Rose294396b2011-08-22 23:48:23 +00002457 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
Jordy Rose537716a2011-08-27 22:51:26 +00002458 void checkPostStmt(const CXXConstructExpr *CE, CheckerContext &C) const;
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002459 void checkPostStmt(const ObjCArrayLiteral *AL, CheckerContext &C) const;
2460 void checkPostStmt(const ObjCDictionaryLiteral *DL, CheckerContext &C) const;
Jordy Rose294396b2011-08-22 23:48:23 +00002461 void checkPostObjCMessage(const ObjCMessage &Msg, CheckerContext &C) const;
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002462
Jordy Rose294396b2011-08-22 23:48:23 +00002463 void checkSummary(const RetainSummary &Summ, const CallOrObjCMessage &Call,
Jordy Rosee38dd952011-08-28 05:16:28 +00002464 CheckerContext &C) const;
Jordy Rose294396b2011-08-22 23:48:23 +00002465
Jordy Rose76c506f2011-08-21 21:58:18 +00002466 bool evalCall(const CallExpr *CE, CheckerContext &C) const;
2467
Ted Kremenek8bef8232012-01-26 21:29:00 +00002468 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Jordy Roseab027fd2011-08-20 21:16:58 +00002469 bool Assumption) const;
Jordy Rose67044292011-08-17 21:27:39 +00002470
Ted Kremenek8bef8232012-01-26 21:29:00 +00002471 ProgramStateRef
2472 checkRegionChanges(ProgramStateRef state,
Jordy Rose537716a2011-08-27 22:51:26 +00002473 const StoreManager::InvalidatedSymbols *invalidated,
2474 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00002475 ArrayRef<const MemRegion *> Regions,
2476 const CallOrObjCMessage *Call) const;
Jordy Roseab027fd2011-08-20 21:16:58 +00002477
Ted Kremenek8bef8232012-01-26 21:29:00 +00002478 bool wantsRegionChangeUpdate(ProgramStateRef state) const {
Jordy Rose2f9a66d2011-08-20 21:17:59 +00002479 return true;
Jordy Roseab027fd2011-08-20 21:16:58 +00002480 }
Jordy Rose294396b2011-08-22 23:48:23 +00002481
Jordy Rosef53e8c72011-08-23 19:43:16 +00002482 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
2483 void checkReturnWithRetEffect(const ReturnStmt *S, CheckerContext &C,
2484 ExplodedNode *Pred, RetEffect RE, RefVal X,
Ted Kremenek8bef8232012-01-26 21:29:00 +00002485 SymbolRef Sym, ProgramStateRef state) const;
Jordy Rosef53e8c72011-08-23 19:43:16 +00002486
Jordy Rose38f17d62011-08-23 19:01:07 +00002487 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Anna Zaksaf498a22011-10-25 19:56:48 +00002488 void checkEndPath(CheckerContext &C) const;
Jordy Rose38f17d62011-08-23 19:01:07 +00002489
Ted Kremenek8bef8232012-01-26 21:29:00 +00002490 ProgramStateRef updateSymbol(ProgramStateRef state, SymbolRef sym,
Jordy Rose17a38e22011-09-02 05:55:19 +00002491 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
2492 CheckerContext &C) const;
Jordy Rosee0a5d322011-08-23 20:27:16 +00002493
Ted Kremenek8bef8232012-01-26 21:29:00 +00002494 void processNonLeakError(ProgramStateRef St, SourceRange ErrorRange,
Jordy Rose294396b2011-08-22 23:48:23 +00002495 RefVal::Kind ErrorKind, SymbolRef Sym,
2496 CheckerContext &C) const;
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002497
2498 void processObjCLiterals(CheckerContext &C, const Expr *Ex) const;
Jordy Rose294396b2011-08-22 23:48:23 +00002499
Jordy Rose38f17d62011-08-23 19:01:07 +00002500 const ProgramPointTag *getDeadSymbolTag(SymbolRef sym) const;
2501
Ted Kremenek8bef8232012-01-26 21:29:00 +00002502 ProgramStateRef handleSymbolDeath(ProgramStateRef state,
Jordy Rose38f17d62011-08-23 19:01:07 +00002503 SymbolRef sid, RefVal V,
2504 SmallVectorImpl<SymbolRef> &Leaked) const;
2505
Ted Kremenek8bef8232012-01-26 21:29:00 +00002506 std::pair<ExplodedNode *, ProgramStateRef >
2507 handleAutoreleaseCounts(ProgramStateRef state,
Jordy Rose8d228632011-08-23 20:07:14 +00002508 GenericNodeBuilderRefCount Bd, ExplodedNode *Pred,
Anna Zaks6a93bd52011-10-25 19:57:11 +00002509 CheckerContext &Ctx, SymbolRef Sym, RefVal V) const;
Jordy Rose8d228632011-08-23 20:07:14 +00002510
Ted Kremenek8bef8232012-01-26 21:29:00 +00002511 ExplodedNode *processLeaks(ProgramStateRef state,
Jordy Rose38f17d62011-08-23 19:01:07 +00002512 SmallVectorImpl<SymbolRef> &Leaked,
2513 GenericNodeBuilderRefCount &Builder,
Anna Zaks6a93bd52011-10-25 19:57:11 +00002514 CheckerContext &Ctx,
Jordy Rose38f17d62011-08-23 19:01:07 +00002515 ExplodedNode *Pred = 0) const;
Ted Kremenekd593eb92009-11-25 22:17:44 +00002516};
2517} // end anonymous namespace
2518
Jordy Rose67044292011-08-17 21:27:39 +00002519namespace {
2520class StopTrackingCallback : public SymbolVisitor {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002521 ProgramStateRef state;
Jordy Rose67044292011-08-17 21:27:39 +00002522public:
Ted Kremenek8bef8232012-01-26 21:29:00 +00002523 StopTrackingCallback(ProgramStateRef st) : state(st) {}
2524 ProgramStateRef getState() const { return state; }
Jordy Rose67044292011-08-17 21:27:39 +00002525
2526 bool VisitSymbol(SymbolRef sym) {
2527 state = state->remove<RefBindings>(sym);
2528 return true;
2529 }
2530};
2531} // end anonymous namespace
2532
Jordy Rose910c4052011-09-02 06:44:22 +00002533//===----------------------------------------------------------------------===//
2534// Handle statements that may have an effect on refcounts.
2535//===----------------------------------------------------------------------===//
Jordy Rose67044292011-08-17 21:27:39 +00002536
Jordy Rose910c4052011-09-02 06:44:22 +00002537void RetainCountChecker::checkPostStmt(const BlockExpr *BE,
2538 CheckerContext &C) const {
Jordy Rose67044292011-08-17 21:27:39 +00002539
Jordy Rose910c4052011-09-02 06:44:22 +00002540 // Scan the BlockDecRefExprs for any object the retain count checker
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002541 // may be tracking.
John McCall469a1eb2011-02-02 13:00:07 +00002542 if (!BE->getBlockDecl()->hasCaptures())
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002543 return;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002544
Ted Kremenek8bef8232012-01-26 21:29:00 +00002545 ProgramStateRef state = C.getState();
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002546 const BlockDataRegion *R =
Ted Kremenek5eca4822012-01-06 22:09:28 +00002547 cast<BlockDataRegion>(state->getSVal(BE,
2548 C.getLocationContext()).getAsRegion());
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002549
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002550 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
2551 E = R->referenced_vars_end();
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002552
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002553 if (I == E)
2554 return;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002555
Ted Kremenek67d12872009-12-07 22:05:27 +00002556 // FIXME: For now we invalidate the tracking of all symbols passed to blocks
2557 // via captured variables, even though captured variables result in a copy
2558 // and in implicit increment/decrement of a retain count.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002559 SmallVector<const MemRegion*, 10> Regions;
Anna Zaks39ac1872011-10-26 21:06:44 +00002560 const LocationContext *LC = C.getLocationContext();
Ted Kremenekc8413fd2010-12-02 07:49:45 +00002561 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002562
Ted Kremenek67d12872009-12-07 22:05:27 +00002563 for ( ; I != E; ++I) {
2564 const VarRegion *VR = *I;
2565 if (VR->getSuperRegion() == R) {
2566 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2567 }
2568 Regions.push_back(VR);
2569 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002570
Ted Kremenek67d12872009-12-07 22:05:27 +00002571 state =
2572 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
2573 Regions.data() + Regions.size()).getState();
Anna Zaks0bd6b112011-10-26 21:06:34 +00002574 C.addTransition(state);
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002575}
2576
Jordy Rose910c4052011-09-02 06:44:22 +00002577void RetainCountChecker::checkPostStmt(const CastExpr *CE,
2578 CheckerContext &C) const {
John McCallf85e1932011-06-15 23:02:42 +00002579 const ObjCBridgedCastExpr *BE = dyn_cast<ObjCBridgedCastExpr>(CE);
2580 if (!BE)
2581 return;
2582
John McCall71c482c2011-06-17 06:50:50 +00002583 ArgEffect AE = IncRef;
John McCallf85e1932011-06-15 23:02:42 +00002584
2585 switch (BE->getBridgeKind()) {
2586 case clang::OBC_Bridge:
2587 // Do nothing.
2588 return;
2589 case clang::OBC_BridgeRetained:
2590 AE = IncRef;
2591 break;
2592 case clang::OBC_BridgeTransfer:
2593 AE = DecRefBridgedTransfered;
2594 break;
2595 }
2596
Ted Kremenek8bef8232012-01-26 21:29:00 +00002597 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00002598 SymbolRef Sym = state->getSVal(CE, C.getLocationContext()).getAsLocSymbol();
John McCallf85e1932011-06-15 23:02:42 +00002599 if (!Sym)
2600 return;
2601 const RefVal* T = state->get<RefBindings>(Sym);
2602 if (!T)
2603 return;
2604
John McCallf85e1932011-06-15 23:02:42 +00002605 RefVal::Kind hasErr = (RefVal::Kind) 0;
Jordy Rose17a38e22011-09-02 05:55:19 +00002606 state = updateSymbol(state, Sym, *T, AE, hasErr, C);
John McCallf85e1932011-06-15 23:02:42 +00002607
2608 if (hasErr) {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002609 // FIXME: If we get an error during a bridge cast, should we report it?
2610 // Should we assert that there is no error?
John McCallf85e1932011-06-15 23:02:42 +00002611 return;
2612 }
2613
Anna Zaks0bd6b112011-10-26 21:06:34 +00002614 C.addTransition(state);
John McCallf85e1932011-06-15 23:02:42 +00002615}
2616
Jordy Rose910c4052011-09-02 06:44:22 +00002617void RetainCountChecker::checkPostStmt(const CallExpr *CE,
2618 CheckerContext &C) const {
Ted Kremenek514f2c92012-03-23 06:26:56 +00002619 if (C.wasInlined)
2620 return;
2621
Jordy Rose294396b2011-08-22 23:48:23 +00002622 // Get the callee.
Ted Kremenek8bef8232012-01-26 21:29:00 +00002623 ProgramStateRef state = C.getState();
Jordy Rose294396b2011-08-22 23:48:23 +00002624 const Expr *Callee = CE->getCallee();
Ted Kremenek5eca4822012-01-06 22:09:28 +00002625 SVal L = state->getSVal(Callee, C.getLocationContext());
Jordy Rose294396b2011-08-22 23:48:23 +00002626
Jordy Rose17a38e22011-09-02 05:55:19 +00002627 RetainSummaryManager &Summaries = getSummaryManager(C);
Ted Kremenek93edbc52011-10-05 23:54:29 +00002628 const RetainSummary *Summ = 0;
Jordy Rose294396b2011-08-22 23:48:23 +00002629
2630 // FIXME: Better support for blocks. For now we stop tracking anything
2631 // that is passed to blocks.
2632 // FIXME: Need to handle variables that are "captured" by the block.
2633 if (dyn_cast_or_null<BlockDataRegion>(L.getAsRegion())) {
2634 Summ = Summaries.getPersistentStopSummary();
2635 } else if (const FunctionDecl *FD = L.getAsFunctionDecl()) {
2636 Summ = Summaries.getSummary(FD);
2637 } else if (const CXXMemberCallExpr *me = dyn_cast<CXXMemberCallExpr>(CE)) {
2638 if (const CXXMethodDecl *MD = me->getMethodDecl())
2639 Summ = Summaries.getSummary(MD);
2640 }
2641
Jordy Rose294396b2011-08-22 23:48:23 +00002642 if (!Summ)
Ted Kremenek93edbc52011-10-05 23:54:29 +00002643 Summ = Summaries.getDefaultSummary();
Jordy Rose294396b2011-08-22 23:48:23 +00002644
Ted Kremenek5eca4822012-01-06 22:09:28 +00002645 checkSummary(*Summ, CallOrObjCMessage(CE, state, C.getLocationContext()), C);
Jordy Rose294396b2011-08-22 23:48:23 +00002646}
2647
Jordy Rose910c4052011-09-02 06:44:22 +00002648void RetainCountChecker::checkPostStmt(const CXXConstructExpr *CE,
2649 CheckerContext &C) const {
Jordy Rose537716a2011-08-27 22:51:26 +00002650 const CXXConstructorDecl *Ctor = CE->getConstructor();
2651 if (!Ctor)
2652 return;
2653
Jordy Rose17a38e22011-09-02 05:55:19 +00002654 RetainSummaryManager &Summaries = getSummaryManager(C);
Ted Kremenek93edbc52011-10-05 23:54:29 +00002655 const RetainSummary *Summ = Summaries.getSummary(Ctor);
Jordy Rose537716a2011-08-27 22:51:26 +00002656
2657 // If we didn't get a summary, this constructor doesn't affect retain counts.
2658 if (!Summ)
2659 return;
2660
Ted Kremenek8bef8232012-01-26 21:29:00 +00002661 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00002662 checkSummary(*Summ, CallOrObjCMessage(CE, state, C.getLocationContext()), C);
Jordy Rose537716a2011-08-27 22:51:26 +00002663}
2664
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002665void RetainCountChecker::processObjCLiterals(CheckerContext &C,
2666 const Expr *Ex) const {
2667 ProgramStateRef state = C.getState();
2668 const ExplodedNode *pred = C.getPredecessor();
2669 for (Stmt::const_child_iterator it = Ex->child_begin(), et = Ex->child_end() ;
2670 it != et ; ++it) {
2671 const Stmt *child = *it;
2672 SVal V = state->getSVal(child, pred->getLocationContext());
2673 if (SymbolRef sym = V.getAsSymbol())
2674 if (const RefVal* T = state->get<RefBindings>(sym)) {
2675 RefVal::Kind hasErr = (RefVal::Kind) 0;
2676 state = updateSymbol(state, sym, *T, MayEscape, hasErr, C);
2677 if (hasErr) {
2678 processNonLeakError(state, child->getSourceRange(), hasErr, sym, C);
2679 return;
2680 }
2681 }
2682 }
2683
2684 // Return the object as autoreleased.
2685 // RetEffect RE = RetEffect::MakeNotOwned(RetEffect::ObjC);
2686 if (SymbolRef sym =
2687 state->getSVal(Ex, pred->getLocationContext()).getAsSymbol()) {
2688 QualType ResultTy = Ex->getType();
2689 state = state->set<RefBindings>(sym, RefVal::makeNotOwned(RetEffect::ObjC,
2690 ResultTy));
2691 }
2692
2693 C.addTransition(state);
2694}
2695
2696void RetainCountChecker::checkPostStmt(const ObjCArrayLiteral *AL,
2697 CheckerContext &C) const {
2698 // Apply the 'MayEscape' to all values.
2699 processObjCLiterals(C, AL);
2700}
2701
2702void RetainCountChecker::checkPostStmt(const ObjCDictionaryLiteral *DL,
2703 CheckerContext &C) const {
2704 // Apply the 'MayEscape' to all keys and values.
2705 processObjCLiterals(C, DL);
2706}
2707
Jordy Rose910c4052011-09-02 06:44:22 +00002708void RetainCountChecker::checkPostObjCMessage(const ObjCMessage &Msg,
2709 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002710 ProgramStateRef state = C.getState();
Jordy Rose294396b2011-08-22 23:48:23 +00002711
Jordy Rose17a38e22011-09-02 05:55:19 +00002712 RetainSummaryManager &Summaries = getSummaryManager(C);
Jordy Roseb6cfc092011-08-25 00:10:37 +00002713
Ted Kremenek93edbc52011-10-05 23:54:29 +00002714 const RetainSummary *Summ;
Jordy Rose294396b2011-08-22 23:48:23 +00002715 if (Msg.isInstanceMessage()) {
Anna Zaksa2a86032011-11-01 22:41:01 +00002716 const LocationContext *LC = C.getLocationContext();
Jordy Rose294396b2011-08-22 23:48:23 +00002717 Summ = Summaries.getInstanceMethodSummary(Msg, state, LC);
2718 } else {
2719 Summ = Summaries.getClassMethodSummary(Msg);
2720 }
2721
2722 // If we didn't get a summary, this message doesn't affect retain counts.
2723 if (!Summ)
2724 return;
2725
Ted Kremenek5eca4822012-01-06 22:09:28 +00002726 checkSummary(*Summ, CallOrObjCMessage(Msg, state, C.getLocationContext()), C);
Jordy Rose294396b2011-08-22 23:48:23 +00002727}
2728
Jordy Rose910c4052011-09-02 06:44:22 +00002729/// GetReturnType - Used to get the return type of a message expression or
2730/// function call with the intention of affixing that type to a tracked symbol.
2731/// While the the return type can be queried directly from RetEx, when
2732/// invoking class methods we augment to the return type to be that of
2733/// a pointer to the class (as opposed it just being id).
2734// FIXME: We may be able to do this with related result types instead.
2735// This function is probably overestimating.
2736static QualType GetReturnType(const Expr *RetE, ASTContext &Ctx) {
2737 QualType RetTy = RetE->getType();
2738 // If RetE is not a message expression just return its type.
2739 // If RetE is a message expression, return its types if it is something
2740 /// more specific than id.
2741 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RetE))
2742 if (const ObjCObjectPointerType *PT = RetTy->getAs<ObjCObjectPointerType>())
2743 if (PT->isObjCQualifiedIdType() || PT->isObjCIdType() ||
2744 PT->isObjCClassType()) {
2745 // At this point we know the return type of the message expression is
2746 // id, id<...>, or Class. If we have an ObjCInterfaceDecl, we know this
2747 // is a call to a class method whose type we can resolve. In such
2748 // cases, promote the return type to XXX* (where XXX is the class).
2749 const ObjCInterfaceDecl *D = ME->getReceiverInterface();
2750 return !D ? RetTy :
2751 Ctx.getObjCObjectPointerType(Ctx.getObjCInterfaceType(D));
2752 }
2753
2754 return RetTy;
2755}
2756
2757void RetainCountChecker::checkSummary(const RetainSummary &Summ,
2758 const CallOrObjCMessage &CallOrMsg,
2759 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002760 ProgramStateRef state = C.getState();
Jordy Rose294396b2011-08-22 23:48:23 +00002761
2762 // Evaluate the effect of the arguments.
2763 RefVal::Kind hasErr = (RefVal::Kind) 0;
2764 SourceRange ErrorRange;
2765 SymbolRef ErrorSym = 0;
2766
2767 for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
Jordy Rose537716a2011-08-27 22:51:26 +00002768 SVal V = CallOrMsg.getArgSVal(idx);
Jordy Rose294396b2011-08-22 23:48:23 +00002769
2770 if (SymbolRef Sym = V.getAsLocSymbol()) {
2771 if (RefBindings::data_type *T = state->get<RefBindings>(Sym)) {
Jordy Rose17a38e22011-09-02 05:55:19 +00002772 state = updateSymbol(state, Sym, *T, Summ.getArg(idx), hasErr, C);
Jordy Rose294396b2011-08-22 23:48:23 +00002773 if (hasErr) {
2774 ErrorRange = CallOrMsg.getArgSourceRange(idx);
2775 ErrorSym = Sym;
2776 break;
2777 }
2778 }
2779 }
2780 }
2781
2782 // Evaluate the effect on the message receiver.
2783 bool ReceiverIsTracked = false;
Jordy Rosee38dd952011-08-28 05:16:28 +00002784 if (!hasErr && CallOrMsg.isObjCMessage()) {
Anna Zaks39ac1872011-10-26 21:06:44 +00002785 const LocationContext *LC = C.getLocationContext();
Jordy Rosee38dd952011-08-28 05:16:28 +00002786 SVal Receiver = CallOrMsg.getInstanceMessageReceiver(LC);
2787 if (SymbolRef Sym = Receiver.getAsLocSymbol()) {
Jordy Rose294396b2011-08-22 23:48:23 +00002788 if (const RefVal *T = state->get<RefBindings>(Sym)) {
2789 ReceiverIsTracked = true;
Jordy Rose17a38e22011-09-02 05:55:19 +00002790 state = updateSymbol(state, Sym, *T, Summ.getReceiverEffect(),
2791 hasErr, C);
Jordy Rose294396b2011-08-22 23:48:23 +00002792 if (hasErr) {
Jordy Rosee38dd952011-08-28 05:16:28 +00002793 ErrorRange = CallOrMsg.getReceiverSourceRange();
Jordy Rose294396b2011-08-22 23:48:23 +00002794 ErrorSym = Sym;
2795 }
2796 }
2797 }
2798 }
2799
2800 // Process any errors.
2801 if (hasErr) {
2802 processNonLeakError(state, ErrorRange, hasErr, ErrorSym, C);
2803 return;
2804 }
2805
2806 // Consult the summary for the return value.
2807 RetEffect RE = Summ.getRetEffect();
2808
2809 if (RE.getKind() == RetEffect::OwnedWhenTrackedReceiver) {
Jordy Roseb6cfc092011-08-25 00:10:37 +00002810 if (ReceiverIsTracked)
Jordy Rose17a38e22011-09-02 05:55:19 +00002811 RE = getSummaryManager(C).getObjAllocRetEffect();
Jordy Roseb6cfc092011-08-25 00:10:37 +00002812 else
Jordy Rose294396b2011-08-22 23:48:23 +00002813 RE = RetEffect::MakeNoRet();
2814 }
2815
2816 switch (RE.getKind()) {
2817 default:
David Blaikie7530c032012-01-17 06:56:22 +00002818 llvm_unreachable("Unhandled RetEffect.");
Jordy Rose294396b2011-08-22 23:48:23 +00002819
2820 case RetEffect::NoRet:
2821 // No work necessary.
2822 break;
2823
2824 case RetEffect::OwnedAllocatedSymbol:
2825 case RetEffect::OwnedSymbol: {
Ted Kremenek5eca4822012-01-06 22:09:28 +00002826 SymbolRef Sym = state->getSVal(CallOrMsg.getOriginExpr(),
2827 C.getLocationContext()).getAsSymbol();
Jordy Rose294396b2011-08-22 23:48:23 +00002828 if (!Sym)
2829 break;
2830
2831 // Use the result type from callOrMsg as it automatically adjusts
2832 // for methods/functions that return references.
2833 QualType ResultTy = CallOrMsg.getResultType(C.getASTContext());
2834 state = state->set<RefBindings>(Sym, RefVal::makeOwned(RE.getObjKind(),
2835 ResultTy));
2836
2837 // FIXME: Add a flag to the checker where allocations are assumed to
2838 // *not* fail. (The code below is out-of-date, though.)
2839#if 0
2840 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) {
2841 bool isFeasible;
2842 state = state.assume(loc::SymbolVal(Sym), true, isFeasible);
2843 assert(isFeasible && "Cannot assume fresh symbol is non-null.");
2844 }
2845#endif
2846
2847 break;
2848 }
2849
2850 case RetEffect::GCNotOwnedSymbol:
2851 case RetEffect::ARCNotOwnedSymbol:
2852 case RetEffect::NotOwnedSymbol: {
2853 const Expr *Ex = CallOrMsg.getOriginExpr();
Ted Kremenek5eca4822012-01-06 22:09:28 +00002854 SymbolRef Sym = state->getSVal(Ex, C.getLocationContext()).getAsSymbol();
Jordy Rose294396b2011-08-22 23:48:23 +00002855 if (!Sym)
2856 break;
2857
2858 // Use GetReturnType in order to give [NSFoo alloc] the type NSFoo *.
2859 QualType ResultTy = GetReturnType(Ex, C.getASTContext());
2860 state = state->set<RefBindings>(Sym, RefVal::makeNotOwned(RE.getObjKind(),
2861 ResultTy));
2862 break;
2863 }
2864 }
2865
2866 // This check is actually necessary; otherwise the statement builder thinks
2867 // we've hit a previously-found path.
2868 // Normally addTransition takes care of this, but we want the node pointer.
2869 ExplodedNode *NewNode;
2870 if (state == C.getState()) {
2871 NewNode = C.getPredecessor();
2872 } else {
Anna Zaks0bd6b112011-10-26 21:06:34 +00002873 NewNode = C.addTransition(state);
Jordy Rose294396b2011-08-22 23:48:23 +00002874 }
2875
Jordy Rose9c083b72011-08-24 18:56:32 +00002876 // Annotate the node with summary we used.
2877 if (NewNode) {
2878 // FIXME: This is ugly. See checkEndAnalysis for why it's necessary.
2879 if (ShouldResetSummaryLog) {
2880 SummaryLog.clear();
2881 ShouldResetSummaryLog = false;
2882 }
Jordy Roseec9ef852011-08-23 20:55:48 +00002883 SummaryLog[NewNode] = &Summ;
Jordy Rose9c083b72011-08-24 18:56:32 +00002884 }
Jordy Rose294396b2011-08-22 23:48:23 +00002885}
2886
Jordy Rosee0a5d322011-08-23 20:27:16 +00002887
Ted Kremenek8bef8232012-01-26 21:29:00 +00002888ProgramStateRef
2889RetainCountChecker::updateSymbol(ProgramStateRef state, SymbolRef sym,
Jordy Rose910c4052011-09-02 06:44:22 +00002890 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
2891 CheckerContext &C) const {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002892 // In GC mode [... release] and [... retain] do nothing.
Jordy Rose910c4052011-09-02 06:44:22 +00002893 // In ARC mode they shouldn't exist at all, but we just ignore them.
Jordy Rose17a38e22011-09-02 05:55:19 +00002894 bool IgnoreRetainMsg = C.isObjCGCEnabled();
2895 if (!IgnoreRetainMsg)
David Blaikie4e4d0842012-03-11 07:00:24 +00002896 IgnoreRetainMsg = (bool)C.getASTContext().getLangOpts().ObjCAutoRefCount;
Jordy Rose17a38e22011-09-02 05:55:19 +00002897
Jordy Rosee0a5d322011-08-23 20:27:16 +00002898 switch (E) {
2899 default: break;
Jordy Rose17a38e22011-09-02 05:55:19 +00002900 case IncRefMsg: E = IgnoreRetainMsg ? DoNothing : IncRef; break;
2901 case DecRefMsg: E = IgnoreRetainMsg ? DoNothing : DecRef; break;
2902 case MakeCollectable: E = C.isObjCGCEnabled() ? DecRef : DoNothing; break;
2903 case NewAutoreleasePool: E = C.isObjCGCEnabled() ? DoNothing :
2904 NewAutoreleasePool; break;
Jordy Rosee0a5d322011-08-23 20:27:16 +00002905 }
2906
2907 // Handle all use-after-releases.
Jordy Rose17a38e22011-09-02 05:55:19 +00002908 if (!C.isObjCGCEnabled() && V.getKind() == RefVal::Released) {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002909 V = V ^ RefVal::ErrorUseAfterRelease;
2910 hasErr = V.getKind();
2911 return state->set<RefBindings>(sym, V);
2912 }
2913
2914 switch (E) {
2915 case DecRefMsg:
2916 case IncRefMsg:
2917 case MakeCollectable:
2918 llvm_unreachable("DecRefMsg/IncRefMsg/MakeCollectable already converted");
Jordy Rosee0a5d322011-08-23 20:27:16 +00002919
2920 case Dealloc:
2921 // Any use of -dealloc in GC is *bad*.
Jordy Rose17a38e22011-09-02 05:55:19 +00002922 if (C.isObjCGCEnabled()) {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002923 V = V ^ RefVal::ErrorDeallocGC;
2924 hasErr = V.getKind();
2925 break;
2926 }
2927
2928 switch (V.getKind()) {
2929 default:
2930 llvm_unreachable("Invalid RefVal state for an explicit dealloc.");
Jordy Rosee0a5d322011-08-23 20:27:16 +00002931 case RefVal::Owned:
2932 // The object immediately transitions to the released state.
2933 V = V ^ RefVal::Released;
2934 V.clearCounts();
2935 return state->set<RefBindings>(sym, V);
2936 case RefVal::NotOwned:
2937 V = V ^ RefVal::ErrorDeallocNotOwned;
2938 hasErr = V.getKind();
2939 break;
2940 }
2941 break;
2942
2943 case NewAutoreleasePool:
Jordy Rose17a38e22011-09-02 05:55:19 +00002944 assert(!C.isObjCGCEnabled());
Jordy Rosee0a5d322011-08-23 20:27:16 +00002945 return state->add<AutoreleaseStack>(sym);
2946
2947 case MayEscape:
2948 if (V.getKind() == RefVal::Owned) {
2949 V = V ^ RefVal::NotOwned;
2950 break;
2951 }
2952
2953 // Fall-through.
2954
Jordy Rosee0a5d322011-08-23 20:27:16 +00002955 case DoNothing:
2956 return state;
2957
2958 case Autorelease:
Jordy Rose17a38e22011-09-02 05:55:19 +00002959 if (C.isObjCGCEnabled())
Jordy Rosee0a5d322011-08-23 20:27:16 +00002960 return state;
2961
2962 // Update the autorelease counts.
2963 state = SendAutorelease(state, ARCountFactory, sym);
2964 V = V.autorelease();
2965 break;
2966
2967 case StopTracking:
2968 return state->remove<RefBindings>(sym);
2969
2970 case IncRef:
2971 switch (V.getKind()) {
2972 default:
2973 llvm_unreachable("Invalid RefVal state for a retain.");
Jordy Rosee0a5d322011-08-23 20:27:16 +00002974 case RefVal::Owned:
2975 case RefVal::NotOwned:
2976 V = V + 1;
2977 break;
2978 case RefVal::Released:
2979 // Non-GC cases are handled above.
Jordy Rose17a38e22011-09-02 05:55:19 +00002980 assert(C.isObjCGCEnabled());
Jordy Rosee0a5d322011-08-23 20:27:16 +00002981 V = (V ^ RefVal::Owned) + 1;
2982 break;
2983 }
2984 break;
2985
2986 case SelfOwn:
2987 V = V ^ RefVal::NotOwned;
2988 // Fall-through.
2989 case DecRef:
2990 case DecRefBridgedTransfered:
2991 switch (V.getKind()) {
2992 default:
2993 // case 'RefVal::Released' handled above.
2994 llvm_unreachable("Invalid RefVal state for a release.");
Jordy Rosee0a5d322011-08-23 20:27:16 +00002995
2996 case RefVal::Owned:
2997 assert(V.getCount() > 0);
2998 if (V.getCount() == 1)
2999 V = V ^ (E == DecRefBridgedTransfered ?
3000 RefVal::NotOwned : RefVal::Released);
3001 V = V - 1;
3002 break;
3003
3004 case RefVal::NotOwned:
3005 if (V.getCount() > 0)
3006 V = V - 1;
3007 else {
3008 V = V ^ RefVal::ErrorReleaseNotOwned;
3009 hasErr = V.getKind();
3010 }
3011 break;
3012
3013 case RefVal::Released:
3014 // Non-GC cases are handled above.
Jordy Rose17a38e22011-09-02 05:55:19 +00003015 assert(C.isObjCGCEnabled());
Jordy Rosee0a5d322011-08-23 20:27:16 +00003016 V = V ^ RefVal::ErrorUseAfterRelease;
3017 hasErr = V.getKind();
3018 break;
3019 }
3020 break;
3021 }
3022 return state->set<RefBindings>(sym, V);
3023}
3024
Ted Kremenek8bef8232012-01-26 21:29:00 +00003025void RetainCountChecker::processNonLeakError(ProgramStateRef St,
Jordy Rose910c4052011-09-02 06:44:22 +00003026 SourceRange ErrorRange,
3027 RefVal::Kind ErrorKind,
3028 SymbolRef Sym,
3029 CheckerContext &C) const {
Jordy Rose294396b2011-08-22 23:48:23 +00003030 ExplodedNode *N = C.generateSink(St);
3031 if (!N)
3032 return;
3033
Jordy Rose294396b2011-08-22 23:48:23 +00003034 CFRefBug *BT;
3035 switch (ErrorKind) {
3036 default:
3037 llvm_unreachable("Unhandled error.");
Jordy Rose294396b2011-08-22 23:48:23 +00003038 case RefVal::ErrorUseAfterRelease:
Jordy Rosed6334e12011-08-25 00:34:03 +00003039 if (!useAfterRelease)
3040 useAfterRelease.reset(new UseAfterRelease());
3041 BT = &*useAfterRelease;
Jordy Rose294396b2011-08-22 23:48:23 +00003042 break;
3043 case RefVal::ErrorReleaseNotOwned:
Jordy Rosed6334e12011-08-25 00:34:03 +00003044 if (!releaseNotOwned)
3045 releaseNotOwned.reset(new BadRelease());
3046 BT = &*releaseNotOwned;
Jordy Rose294396b2011-08-22 23:48:23 +00003047 break;
3048 case RefVal::ErrorDeallocGC:
Jordy Rosed6334e12011-08-25 00:34:03 +00003049 if (!deallocGC)
3050 deallocGC.reset(new DeallocGC());
3051 BT = &*deallocGC;
Jordy Rose294396b2011-08-22 23:48:23 +00003052 break;
3053 case RefVal::ErrorDeallocNotOwned:
Jordy Rosed6334e12011-08-25 00:34:03 +00003054 if (!deallocNotOwned)
3055 deallocNotOwned.reset(new DeallocNotOwned());
3056 BT = &*deallocNotOwned;
Jordy Rose294396b2011-08-22 23:48:23 +00003057 break;
3058 }
3059
Jordy Rosed6334e12011-08-25 00:34:03 +00003060 assert(BT);
David Blaikie4e4d0842012-03-11 07:00:24 +00003061 CFRefReport *report = new CFRefReport(*BT, C.getASTContext().getLangOpts(),
Jordy Rose17a38e22011-09-02 05:55:19 +00003062 C.isObjCGCEnabled(), SummaryLog,
3063 N, Sym);
Jordy Rose294396b2011-08-22 23:48:23 +00003064 report->addRange(ErrorRange);
3065 C.EmitReport(report);
3066}
3067
Jordy Rose910c4052011-09-02 06:44:22 +00003068//===----------------------------------------------------------------------===//
3069// Handle the return values of retain-count-related functions.
3070//===----------------------------------------------------------------------===//
3071
3072bool RetainCountChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
Jordy Rose76c506f2011-08-21 21:58:18 +00003073 // Get the callee. We're only interested in simple C functions.
Ted Kremenek8bef8232012-01-26 21:29:00 +00003074 ProgramStateRef state = C.getState();
Anna Zaksb805c8f2011-12-01 05:57:37 +00003075 const FunctionDecl *FD = C.getCalleeDecl(CE);
Jordy Rose76c506f2011-08-21 21:58:18 +00003076 if (!FD)
3077 return false;
3078
3079 IdentifierInfo *II = FD->getIdentifier();
3080 if (!II)
3081 return false;
3082
3083 // For now, we're only handling the functions that return aliases of their
3084 // arguments: CFRetain and CFMakeCollectable (and their families).
3085 // Eventually we should add other functions we can model entirely,
3086 // such as CFRelease, which don't invalidate their arguments or globals.
3087 if (CE->getNumArgs() != 1)
3088 return false;
3089
3090 // Get the name of the function.
3091 StringRef FName = II->getName();
3092 FName = FName.substr(FName.find_first_not_of('_'));
3093
3094 // See if it's one of the specific functions we know how to eval.
3095 bool canEval = false;
3096
Anna Zaksb805c8f2011-12-01 05:57:37 +00003097 QualType ResultTy = CE->getCallReturnType();
Jordy Rose76c506f2011-08-21 21:58:18 +00003098 if (ResultTy->isObjCIdType()) {
3099 // Handle: id NSMakeCollectable(CFTypeRef)
3100 canEval = II->isStr("NSMakeCollectable");
3101 } else if (ResultTy->isPointerType()) {
3102 // Handle: (CF|CG)Retain
3103 // CFMakeCollectable
3104 // It's okay to be a little sloppy here (CGMakeCollectable doesn't exist).
3105 if (cocoa::isRefType(ResultTy, "CF", FName) ||
3106 cocoa::isRefType(ResultTy, "CG", FName)) {
3107 canEval = isRetain(FD, FName) || isMakeCollectable(FD, FName);
3108 }
3109 }
3110
3111 if (!canEval)
3112 return false;
3113
3114 // Bind the return value.
Ted Kremenek5eca4822012-01-06 22:09:28 +00003115 const LocationContext *LCtx = C.getLocationContext();
3116 SVal RetVal = state->getSVal(CE->getArg(0), LCtx);
Jordy Rose76c506f2011-08-21 21:58:18 +00003117 if (RetVal.isUnknown()) {
3118 // If the receiver is unknown, conjure a return value.
3119 SValBuilder &SVB = C.getSValBuilder();
Anna Zaks5d0ea6d2011-10-04 20:43:05 +00003120 unsigned Count = C.getCurrentBlockCount();
Ted Kremenek3133f792012-02-17 23:13:45 +00003121 SVal RetVal = SVB.getConjuredSymbolVal(0, CE, LCtx, ResultTy, Count);
Jordy Rose76c506f2011-08-21 21:58:18 +00003122 }
Ted Kremenek5eca4822012-01-06 22:09:28 +00003123 state = state->BindExpr(CE, LCtx, RetVal, false);
Jordy Rose76c506f2011-08-21 21:58:18 +00003124
Jordy Rose294396b2011-08-22 23:48:23 +00003125 // FIXME: This should not be necessary, but otherwise the argument seems to be
3126 // considered alive during the next statement.
3127 if (const MemRegion *ArgRegion = RetVal.getAsRegion()) {
3128 // Save the refcount status of the argument.
3129 SymbolRef Sym = RetVal.getAsLocSymbol();
3130 RefBindings::data_type *Binding = 0;
3131 if (Sym)
3132 Binding = state->get<RefBindings>(Sym);
Jordy Rose76c506f2011-08-21 21:58:18 +00003133
Jordy Rose294396b2011-08-22 23:48:23 +00003134 // Invalidate the argument region.
Anna Zaks5d0ea6d2011-10-04 20:43:05 +00003135 unsigned Count = C.getCurrentBlockCount();
Ted Kremenek3133f792012-02-17 23:13:45 +00003136 state = state->invalidateRegions(ArgRegion, CE, Count, LCtx);
Jordy Rose76c506f2011-08-21 21:58:18 +00003137
Jordy Rose294396b2011-08-22 23:48:23 +00003138 // Restore the refcount status of the argument.
3139 if (Binding)
3140 state = state->set<RefBindings>(Sym, *Binding);
3141 }
3142
Anna Zaks0bd6b112011-10-26 21:06:34 +00003143 C.addTransition(state);
Jordy Rose76c506f2011-08-21 21:58:18 +00003144 return true;
3145}
3146
Jordy Rose910c4052011-09-02 06:44:22 +00003147//===----------------------------------------------------------------------===//
3148// Handle return statements.
3149//===----------------------------------------------------------------------===//
Jordy Rosef53e8c72011-08-23 19:43:16 +00003150
Ted Kremeneke5715782012-02-25 02:09:09 +00003151// Return true if the current LocationContext has no caller context.
3152static bool inTopFrame(CheckerContext &C) {
3153 const LocationContext *LC = C.getLocationContext();
3154 return LC->getParent() == 0;
3155}
3156
Jordy Rose910c4052011-09-02 06:44:22 +00003157void RetainCountChecker::checkPreStmt(const ReturnStmt *S,
3158 CheckerContext &C) const {
Ted Kremeneke5715782012-02-25 02:09:09 +00003159
3160 // Only adjust the reference count if this is the top-level call frame,
3161 // and not the result of inlining. In the future, we should do
3162 // better checking even for inlined calls, and see if they match
3163 // with their expected semantics (e.g., the method should return a retained
3164 // object, etc.).
3165 if (!inTopFrame(C))
3166 return;
3167
Jordy Rosef53e8c72011-08-23 19:43:16 +00003168 const Expr *RetE = S->getRetValue();
3169 if (!RetE)
3170 return;
3171
Ted Kremenek8bef8232012-01-26 21:29:00 +00003172 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00003173 SymbolRef Sym =
3174 state->getSValAsScalarOrLoc(RetE, C.getLocationContext()).getAsLocSymbol();
Jordy Rosef53e8c72011-08-23 19:43:16 +00003175 if (!Sym)
3176 return;
3177
3178 // Get the reference count binding (if any).
3179 const RefVal *T = state->get<RefBindings>(Sym);
3180 if (!T)
3181 return;
3182
3183 // Change the reference count.
3184 RefVal X = *T;
3185
3186 switch (X.getKind()) {
3187 case RefVal::Owned: {
3188 unsigned cnt = X.getCount();
3189 assert(cnt > 0);
3190 X.setCount(cnt - 1);
3191 X = X ^ RefVal::ReturnedOwned;
3192 break;
3193 }
3194
3195 case RefVal::NotOwned: {
3196 unsigned cnt = X.getCount();
3197 if (cnt) {
3198 X.setCount(cnt - 1);
3199 X = X ^ RefVal::ReturnedOwned;
3200 }
3201 else {
3202 X = X ^ RefVal::ReturnedNotOwned;
3203 }
3204 break;
3205 }
3206
3207 default:
3208 return;
3209 }
3210
3211 // Update the binding.
3212 state = state->set<RefBindings>(Sym, X);
Anna Zaks0bd6b112011-10-26 21:06:34 +00003213 ExplodedNode *Pred = C.addTransition(state);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003214
3215 // At this point we have updated the state properly.
3216 // Everything after this is merely checking to see if the return value has
3217 // been over- or under-retained.
3218
3219 // Did we cache out?
3220 if (!Pred)
3221 return;
3222
Jordy Rosef53e8c72011-08-23 19:43:16 +00003223 // Update the autorelease counts.
3224 static SimpleProgramPointTag
Jordy Rose910c4052011-09-02 06:44:22 +00003225 AutoreleaseTag("RetainCountChecker : Autorelease");
Anna Zaks4eff8232011-10-05 23:44:11 +00003226 GenericNodeBuilderRefCount Bd(C, &AutoreleaseTag);
Anna Zaks6a93bd52011-10-25 19:57:11 +00003227 llvm::tie(Pred, state) = handleAutoreleaseCounts(state, Bd, Pred, C, Sym, X);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003228
3229 // Did we cache out?
Jordy Rose8d228632011-08-23 20:07:14 +00003230 if (!Pred)
Jordy Rosef53e8c72011-08-23 19:43:16 +00003231 return;
3232
3233 // Get the updated binding.
3234 T = state->get<RefBindings>(Sym);
3235 assert(T);
3236 X = *T;
3237
3238 // Consult the summary of the enclosing method.
Jordy Rose17a38e22011-09-02 05:55:19 +00003239 RetainSummaryManager &Summaries = getSummaryManager(C);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003240 const Decl *CD = &Pred->getCodeDecl();
3241
3242 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CD)) {
3243 // Unlike regular functions, /all/ ObjC methods are assumed to always
3244 // follow Cocoa retain-count conventions, not just those with special
3245 // names or attributes.
Jordy Roseb6cfc092011-08-25 00:10:37 +00003246 const RetainSummary *Summ = Summaries.getMethodSummary(MD);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003247 RetEffect RE = Summ ? Summ->getRetEffect() : RetEffect::MakeNoRet();
3248 checkReturnWithRetEffect(S, C, Pred, RE, X, Sym, state);
3249 }
3250
3251 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) {
3252 if (!isa<CXXMethodDecl>(FD))
Jordy Roseb6cfc092011-08-25 00:10:37 +00003253 if (const RetainSummary *Summ = Summaries.getSummary(FD))
Jordy Rosef53e8c72011-08-23 19:43:16 +00003254 checkReturnWithRetEffect(S, C, Pred, Summ->getRetEffect(), X,
3255 Sym, state);
3256 }
3257}
3258
Jordy Rose910c4052011-09-02 06:44:22 +00003259void RetainCountChecker::checkReturnWithRetEffect(const ReturnStmt *S,
3260 CheckerContext &C,
3261 ExplodedNode *Pred,
3262 RetEffect RE, RefVal X,
3263 SymbolRef Sym,
Ted Kremenek8bef8232012-01-26 21:29:00 +00003264 ProgramStateRef state) const {
Jordy Rosef53e8c72011-08-23 19:43:16 +00003265 // Any leaks or other errors?
3266 if (X.isReturnedOwned() && X.getCount() == 0) {
3267 if (RE.getKind() != RetEffect::NoRet) {
3268 bool hasError = false;
Jordy Rose17a38e22011-09-02 05:55:19 +00003269 if (C.isObjCGCEnabled() && RE.getObjKind() == RetEffect::ObjC) {
Jordy Rosef53e8c72011-08-23 19:43:16 +00003270 // Things are more complicated with garbage collection. If the
3271 // returned object is suppose to be an Objective-C object, we have
3272 // a leak (as the caller expects a GC'ed object) because no
3273 // method should return ownership unless it returns a CF object.
3274 hasError = true;
3275 X = X ^ RefVal::ErrorGCLeakReturned;
3276 }
3277 else if (!RE.isOwned()) {
3278 // Either we are using GC and the returned object is a CF type
3279 // or we aren't using GC. In either case, we expect that the
3280 // enclosing method is expected to return ownership.
3281 hasError = true;
3282 X = X ^ RefVal::ErrorLeakReturned;
3283 }
3284
3285 if (hasError) {
3286 // Generate an error node.
3287 state = state->set<RefBindings>(Sym, X);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003288
3289 static SimpleProgramPointTag
Jordy Rose910c4052011-09-02 06:44:22 +00003290 ReturnOwnLeakTag("RetainCountChecker : ReturnsOwnLeak");
Anna Zaks0bd6b112011-10-26 21:06:34 +00003291 ExplodedNode *N = C.addTransition(state, Pred, &ReturnOwnLeakTag);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003292 if (N) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003293 const LangOptions &LOpts = C.getASTContext().getLangOpts();
Jordy Rose17a38e22011-09-02 05:55:19 +00003294 bool GCEnabled = C.isObjCGCEnabled();
Jordy Rosef53e8c72011-08-23 19:43:16 +00003295 CFRefReport *report =
Jordy Rose17a38e22011-09-02 05:55:19 +00003296 new CFRefLeakReport(*getLeakAtReturnBug(LOpts, GCEnabled),
3297 LOpts, GCEnabled, SummaryLog,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003298 N, Sym, C);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003299 C.EmitReport(report);
3300 }
3301 }
3302 }
3303 } else if (X.isReturnedNotOwned()) {
3304 if (RE.isOwned()) {
3305 // Trying to return a not owned object to a caller expecting an
3306 // owned object.
3307 state = state->set<RefBindings>(Sym, X ^ RefVal::ErrorReturnedNotOwned);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003308
3309 static SimpleProgramPointTag
Jordy Rose910c4052011-09-02 06:44:22 +00003310 ReturnNotOwnedTag("RetainCountChecker : ReturnNotOwnedForOwned");
Anna Zaks0bd6b112011-10-26 21:06:34 +00003311 ExplodedNode *N = C.addTransition(state, Pred, &ReturnNotOwnedTag);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003312 if (N) {
Jordy Rosed6334e12011-08-25 00:34:03 +00003313 if (!returnNotOwnedForOwned)
3314 returnNotOwnedForOwned.reset(new ReturnedNotOwnedForOwned());
3315
Jordy Rosef53e8c72011-08-23 19:43:16 +00003316 CFRefReport *report =
Jordy Rosed6334e12011-08-25 00:34:03 +00003317 new CFRefReport(*returnNotOwnedForOwned,
David Blaikie4e4d0842012-03-11 07:00:24 +00003318 C.getASTContext().getLangOpts(),
Jordy Rose17a38e22011-09-02 05:55:19 +00003319 C.isObjCGCEnabled(), SummaryLog, N, Sym);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003320 C.EmitReport(report);
3321 }
3322 }
3323 }
3324}
3325
Jordy Rose8d228632011-08-23 20:07:14 +00003326//===----------------------------------------------------------------------===//
Jordy Rose910c4052011-09-02 06:44:22 +00003327// Check various ways a symbol can be invalidated.
3328//===----------------------------------------------------------------------===//
3329
Anna Zaks390909c2011-10-06 00:43:15 +00003330void RetainCountChecker::checkBind(SVal loc, SVal val, const Stmt *S,
Jordy Rose910c4052011-09-02 06:44:22 +00003331 CheckerContext &C) const {
3332 // Are we storing to something that causes the value to "escape"?
3333 bool escapes = true;
3334
3335 // A value escapes in three possible cases (this may change):
3336 //
3337 // (1) we are binding to something that is not a memory region.
3338 // (2) we are binding to a memregion that does not have stack storage
3339 // (3) we are binding to a memregion with stack storage that the store
3340 // does not understand.
Ted Kremenek8bef8232012-01-26 21:29:00 +00003341 ProgramStateRef state = C.getState();
Jordy Rose910c4052011-09-02 06:44:22 +00003342
3343 if (loc::MemRegionVal *regionLoc = dyn_cast<loc::MemRegionVal>(&loc)) {
3344 escapes = !regionLoc->getRegion()->hasStackStorage();
3345
3346 if (!escapes) {
3347 // To test (3), generate a new state with the binding added. If it is
3348 // the same state, then it escapes (since the store cannot represent
3349 // the binding).
3350 escapes = (state == (state->bindLoc(*regionLoc, val)));
3351 }
Ted Kremenekde5b4fb2012-03-27 01:12:45 +00003352 if (!escapes) {
3353 // Case 4: We do not currently model what happens when a symbol is
3354 // assigned to a struct field, so be conservative here and let the symbol
3355 // go. TODO: This could definitely be improved upon.
3356 escapes = !isa<VarRegion>(regionLoc->getRegion());
3357 }
Jordy Rose910c4052011-09-02 06:44:22 +00003358 }
3359
3360 // If our store can represent the binding and we aren't storing to something
3361 // that doesn't have local storage then just return and have the simulation
3362 // state continue as is.
3363 if (!escapes)
3364 return;
3365
3366 // Otherwise, find all symbols referenced by 'val' that we are tracking
3367 // and stop tracking them.
3368 state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
Anna Zaks0bd6b112011-10-26 21:06:34 +00003369 C.addTransition(state);
Jordy Rose910c4052011-09-02 06:44:22 +00003370}
3371
Ted Kremenek8bef8232012-01-26 21:29:00 +00003372ProgramStateRef RetainCountChecker::evalAssume(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003373 SVal Cond,
3374 bool Assumption) const {
3375
3376 // FIXME: We may add to the interface of evalAssume the list of symbols
3377 // whose assumptions have changed. For now we just iterate through the
3378 // bindings and check if any of the tracked symbols are NULL. This isn't
3379 // too bad since the number of symbols we will track in practice are
3380 // probably small and evalAssume is only called at branches and a few
3381 // other places.
3382 RefBindings B = state->get<RefBindings>();
3383
3384 if (B.isEmpty())
3385 return state;
3386
3387 bool changed = false;
3388 RefBindings::Factory &RefBFactory = state->get_context<RefBindings>();
3389
3390 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
3391 // Check if the symbol is null (or equal to any constant).
3392 // If this is the case, stop tracking the symbol.
3393 if (state->getSymVal(I.getKey())) {
3394 changed = true;
3395 B = RefBFactory.remove(B, I.getKey());
3396 }
3397 }
3398
3399 if (changed)
3400 state = state->set<RefBindings>(B);
3401
3402 return state;
3403}
3404
Ted Kremenek8bef8232012-01-26 21:29:00 +00003405ProgramStateRef
3406RetainCountChecker::checkRegionChanges(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003407 const StoreManager::InvalidatedSymbols *invalidated,
3408 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00003409 ArrayRef<const MemRegion *> Regions,
3410 const CallOrObjCMessage *Call) const {
Jordy Rose910c4052011-09-02 06:44:22 +00003411 if (!invalidated)
3412 return state;
3413
3414 llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
3415 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
3416 E = ExplicitRegions.end(); I != E; ++I) {
3417 if (const SymbolicRegion *SR = (*I)->StripCasts()->getAs<SymbolicRegion>())
3418 WhitelistedSymbols.insert(SR->getSymbol());
3419 }
3420
3421 for (StoreManager::InvalidatedSymbols::const_iterator I=invalidated->begin(),
3422 E = invalidated->end(); I!=E; ++I) {
3423 SymbolRef sym = *I;
3424 if (WhitelistedSymbols.count(sym))
3425 continue;
3426 // Remove any existing reference-count binding.
3427 state = state->remove<RefBindings>(sym);
3428 }
3429 return state;
3430}
3431
3432//===----------------------------------------------------------------------===//
Jordy Rose8d228632011-08-23 20:07:14 +00003433// Handle dead symbols and end-of-path.
3434//===----------------------------------------------------------------------===//
3435
Ted Kremenek8bef8232012-01-26 21:29:00 +00003436std::pair<ExplodedNode *, ProgramStateRef >
3437RetainCountChecker::handleAutoreleaseCounts(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003438 GenericNodeBuilderRefCount Bd,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003439 ExplodedNode *Pred,
3440 CheckerContext &Ctx,
Jordy Rose910c4052011-09-02 06:44:22 +00003441 SymbolRef Sym, RefVal V) const {
Jordy Rose8d228632011-08-23 20:07:14 +00003442 unsigned ACnt = V.getAutoreleaseCount();
3443
3444 // No autorelease counts? Nothing to be done.
3445 if (!ACnt)
3446 return std::make_pair(Pred, state);
3447
Anna Zaks6a93bd52011-10-25 19:57:11 +00003448 assert(!Ctx.isObjCGCEnabled() && "Autorelease counts in GC mode?");
Jordy Rose8d228632011-08-23 20:07:14 +00003449 unsigned Cnt = V.getCount();
3450
3451 // FIXME: Handle sending 'autorelease' to already released object.
3452
3453 if (V.getKind() == RefVal::ReturnedOwned)
3454 ++Cnt;
3455
3456 if (ACnt <= Cnt) {
3457 if (ACnt == Cnt) {
3458 V.clearCounts();
3459 if (V.getKind() == RefVal::ReturnedOwned)
3460 V = V ^ RefVal::ReturnedNotOwned;
3461 else
3462 V = V ^ RefVal::NotOwned;
3463 } else {
3464 V.setCount(Cnt - ACnt);
3465 V.setAutoreleaseCount(0);
3466 }
3467 state = state->set<RefBindings>(Sym, V);
3468 ExplodedNode *N = Bd.MakeNode(state, Pred);
3469 if (N == 0)
3470 state = 0;
3471 return std::make_pair(N, state);
3472 }
3473
3474 // Woah! More autorelease counts then retain counts left.
3475 // Emit hard error.
3476 V = V ^ RefVal::ErrorOverAutorelease;
3477 state = state->set<RefBindings>(Sym, V);
3478
Anna Zaksf05aac82011-10-18 23:05:58 +00003479 if (ExplodedNode *N = Bd.MakeNode(state, Pred, true)) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003480 SmallString<128> sbuf;
Jordy Rose8d228632011-08-23 20:07:14 +00003481 llvm::raw_svector_ostream os(sbuf);
3482 os << "Object over-autoreleased: object was sent -autorelease ";
3483 if (V.getAutoreleaseCount() > 1)
3484 os << V.getAutoreleaseCount() << " times ";
3485 os << "but the object has a +" << V.getCount() << " retain count";
3486
Jordy Rosed6334e12011-08-25 00:34:03 +00003487 if (!overAutorelease)
3488 overAutorelease.reset(new OverAutorelease());
3489
David Blaikie4e4d0842012-03-11 07:00:24 +00003490 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
Jordy Rose8d228632011-08-23 20:07:14 +00003491 CFRefReport *report =
Jordy Rosed6334e12011-08-25 00:34:03 +00003492 new CFRefReport(*overAutorelease, LOpts, /* GCEnabled = */ false,
3493 SummaryLog, N, Sym, os.str());
Anna Zaks6a93bd52011-10-25 19:57:11 +00003494 Ctx.EmitReport(report);
Jordy Rose8d228632011-08-23 20:07:14 +00003495 }
3496
Ted Kremenek8bef8232012-01-26 21:29:00 +00003497 return std::make_pair((ExplodedNode *)0, (ProgramStateRef )0);
Jordy Rose8d228632011-08-23 20:07:14 +00003498}
Jordy Rose38f17d62011-08-23 19:01:07 +00003499
Ted Kremenek8bef8232012-01-26 21:29:00 +00003500ProgramStateRef
3501RetainCountChecker::handleSymbolDeath(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003502 SymbolRef sid, RefVal V,
Jordy Rose38f17d62011-08-23 19:01:07 +00003503 SmallVectorImpl<SymbolRef> &Leaked) const {
Jordy Rose53376122011-08-24 04:48:19 +00003504 bool hasLeak = false;
Jordy Rose38f17d62011-08-23 19:01:07 +00003505 if (V.isOwned())
3506 hasLeak = true;
3507 else if (V.isNotOwned() || V.isReturnedOwned())
3508 hasLeak = (V.getCount() > 0);
3509
3510 if (!hasLeak)
3511 return state->remove<RefBindings>(sid);
3512
3513 Leaked.push_back(sid);
3514 return state->set<RefBindings>(sid, V ^ RefVal::ErrorLeak);
3515}
3516
3517ExplodedNode *
Ted Kremenek8bef8232012-01-26 21:29:00 +00003518RetainCountChecker::processLeaks(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003519 SmallVectorImpl<SymbolRef> &Leaked,
3520 GenericNodeBuilderRefCount &Builder,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003521 CheckerContext &Ctx,
3522 ExplodedNode *Pred) const {
Jordy Rose38f17d62011-08-23 19:01:07 +00003523 if (Leaked.empty())
3524 return Pred;
3525
3526 // Generate an intermediate node representing the leak point.
3527 ExplodedNode *N = Builder.MakeNode(state, Pred);
3528
3529 if (N) {
3530 for (SmallVectorImpl<SymbolRef>::iterator
3531 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3532
David Blaikie4e4d0842012-03-11 07:00:24 +00003533 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
Anna Zaks6a93bd52011-10-25 19:57:11 +00003534 bool GCEnabled = Ctx.isObjCGCEnabled();
Jordy Rose17a38e22011-09-02 05:55:19 +00003535 CFRefBug *BT = Pred ? getLeakWithinFunctionBug(LOpts, GCEnabled)
3536 : getLeakAtReturnBug(LOpts, GCEnabled);
Jordy Rose38f17d62011-08-23 19:01:07 +00003537 assert(BT && "BugType not initialized.");
Jordy Rose20589562011-08-24 22:39:09 +00003538
Jordy Rose17a38e22011-09-02 05:55:19 +00003539 CFRefLeakReport *report = new CFRefLeakReport(*BT, LOpts, GCEnabled,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003540 SummaryLog, N, *I, Ctx);
3541 Ctx.EmitReport(report);
Jordy Rose38f17d62011-08-23 19:01:07 +00003542 }
3543 }
3544
3545 return N;
3546}
3547
Anna Zaksaf498a22011-10-25 19:56:48 +00003548void RetainCountChecker::checkEndPath(CheckerContext &Ctx) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +00003549 ProgramStateRef state = Ctx.getState();
Anna Zaksaf498a22011-10-25 19:56:48 +00003550 GenericNodeBuilderRefCount Bd(Ctx);
Jordy Rose38f17d62011-08-23 19:01:07 +00003551 RefBindings B = state->get<RefBindings>();
Anna Zaksaf498a22011-10-25 19:56:48 +00003552 ExplodedNode *Pred = Ctx.getPredecessor();
Jordy Rose38f17d62011-08-23 19:01:07 +00003553
3554 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Anna Zaks6a93bd52011-10-25 19:57:11 +00003555 llvm::tie(Pred, state) = handleAutoreleaseCounts(state, Bd, Pred, Ctx,
Jordy Rose8d228632011-08-23 20:07:14 +00003556 I->first, I->second);
3557 if (!state)
Jordy Rose38f17d62011-08-23 19:01:07 +00003558 return;
3559 }
3560
Ted Kremenek0cf3d472012-02-07 00:24:33 +00003561 // If the current LocationContext has a parent, don't check for leaks.
3562 // We will do that later.
3563 // FIXME: we should instead check for imblances of the retain/releases,
3564 // and suggest annotations.
3565 if (Ctx.getLocationContext()->getParent())
3566 return;
3567
Jordy Rose38f17d62011-08-23 19:01:07 +00003568 B = state->get<RefBindings>();
3569 SmallVector<SymbolRef, 10> Leaked;
3570
3571 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I)
Jordy Rose8d228632011-08-23 20:07:14 +00003572 state = handleSymbolDeath(state, I->first, I->second, Leaked);
Jordy Rose38f17d62011-08-23 19:01:07 +00003573
Anna Zaks6a93bd52011-10-25 19:57:11 +00003574 processLeaks(state, Leaked, Bd, Ctx, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003575}
3576
3577const ProgramPointTag *
Jordy Rose910c4052011-09-02 06:44:22 +00003578RetainCountChecker::getDeadSymbolTag(SymbolRef sym) const {
Jordy Rose38f17d62011-08-23 19:01:07 +00003579 const SimpleProgramPointTag *&tag = DeadSymbolTags[sym];
3580 if (!tag) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003581 SmallString<64> buf;
Jordy Rose38f17d62011-08-23 19:01:07 +00003582 llvm::raw_svector_ostream out(buf);
Anna Zaksf62ceec2011-12-05 18:58:11 +00003583 out << "RetainCountChecker : Dead Symbol : ";
3584 sym->dumpToStream(out);
Jordy Rose38f17d62011-08-23 19:01:07 +00003585 tag = new SimpleProgramPointTag(out.str());
3586 }
3587 return tag;
3588}
3589
Jordy Rose910c4052011-09-02 06:44:22 +00003590void RetainCountChecker::checkDeadSymbols(SymbolReaper &SymReaper,
3591 CheckerContext &C) const {
Jordy Rose38f17d62011-08-23 19:01:07 +00003592 ExplodedNode *Pred = C.getPredecessor();
3593
Ted Kremenek8bef8232012-01-26 21:29:00 +00003594 ProgramStateRef state = C.getState();
Jordy Rose38f17d62011-08-23 19:01:07 +00003595 RefBindings B = state->get<RefBindings>();
3596
3597 // Update counts from autorelease pools
3598 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3599 E = SymReaper.dead_end(); I != E; ++I) {
3600 SymbolRef Sym = *I;
3601 if (const RefVal *T = B.lookup(Sym)){
3602 // Use the symbol as the tag.
3603 // FIXME: This might not be as unique as we would like.
Anna Zaks4eff8232011-10-05 23:44:11 +00003604 GenericNodeBuilderRefCount Bd(C, getDeadSymbolTag(Sym));
Anna Zaks6a93bd52011-10-25 19:57:11 +00003605 llvm::tie(Pred, state) = handleAutoreleaseCounts(state, Bd, Pred, C,
Jordy Rose8d228632011-08-23 20:07:14 +00003606 Sym, *T);
3607 if (!state)
Jordy Rose38f17d62011-08-23 19:01:07 +00003608 return;
3609 }
3610 }
3611
3612 B = state->get<RefBindings>();
3613 SmallVector<SymbolRef, 10> Leaked;
3614
3615 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3616 E = SymReaper.dead_end(); I != E; ++I) {
3617 if (const RefVal *T = B.lookup(*I))
3618 state = handleSymbolDeath(state, *I, *T, Leaked);
3619 }
3620
3621 {
Anna Zaks4eff8232011-10-05 23:44:11 +00003622 GenericNodeBuilderRefCount Bd(C, this);
Anna Zaks6a93bd52011-10-25 19:57:11 +00003623 Pred = processLeaks(state, Leaked, Bd, C, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003624 }
3625
3626 // Did we cache out?
3627 if (!Pred)
3628 return;
3629
3630 // Now generate a new node that nukes the old bindings.
3631 RefBindings::Factory &F = state->get_context<RefBindings>();
3632
3633 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3634 E = SymReaper.dead_end(); I != E; ++I)
3635 B = F.remove(B, *I);
3636
3637 state = state->set<RefBindings>(B);
Anna Zaks0bd6b112011-10-26 21:06:34 +00003638 C.addTransition(state, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003639}
3640
Ted Kremenekd593eb92009-11-25 22:17:44 +00003641//===----------------------------------------------------------------------===//
Jordy Rosedbd658e2011-08-28 19:11:56 +00003642// Debug printing of refcount bindings and autorelease pools.
3643//===----------------------------------------------------------------------===//
3644
3645static void PrintPool(raw_ostream &Out, SymbolRef Sym,
Ted Kremenek8bef8232012-01-26 21:29:00 +00003646 ProgramStateRef State) {
Jordy Rosedbd658e2011-08-28 19:11:56 +00003647 Out << ' ';
3648 if (Sym)
Anna Zaksf62ceec2011-12-05 18:58:11 +00003649 Sym->dumpToStream(Out);
Jordy Rosedbd658e2011-08-28 19:11:56 +00003650 else
3651 Out << "<pool>";
3652 Out << ":{";
3653
3654 // Get the contents of the pool.
3655 if (const ARCounts *Cnts = State->get<AutoreleasePoolContents>(Sym))
3656 for (ARCounts::iterator I = Cnts->begin(), E = Cnts->end(); I != E; ++I)
3657 Out << '(' << I.getKey() << ',' << I.getData() << ')';
3658
3659 Out << '}';
3660}
3661
Ted Kremenek8bef8232012-01-26 21:29:00 +00003662static bool UsesAutorelease(ProgramStateRef state) {
Jordy Rosedbd658e2011-08-28 19:11:56 +00003663 // A state uses autorelease if it allocated an autorelease pool or if it has
3664 // objects in the caller's autorelease pool.
3665 return !state->get<AutoreleaseStack>().isEmpty() ||
3666 state->get<AutoreleasePoolContents>(SymbolRef());
3667}
3668
Ted Kremenek8bef8232012-01-26 21:29:00 +00003669void RetainCountChecker::printState(raw_ostream &Out, ProgramStateRef State,
Jordy Rose910c4052011-09-02 06:44:22 +00003670 const char *NL, const char *Sep) const {
Jordy Rosedbd658e2011-08-28 19:11:56 +00003671
3672 RefBindings B = State->get<RefBindings>();
3673
3674 if (!B.isEmpty())
3675 Out << Sep << NL;
3676
3677 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
3678 Out << I->first << " : ";
3679 I->second.print(Out);
3680 Out << NL;
3681 }
3682
3683 // Print the autorelease stack.
3684 if (UsesAutorelease(State)) {
3685 Out << Sep << NL << "AR pool stack:";
3686 ARStack Stack = State->get<AutoreleaseStack>();
3687
3688 PrintPool(Out, SymbolRef(), State); // Print the caller's pool.
3689 for (ARStack::iterator I = Stack.begin(), E = Stack.end(); I != E; ++I)
3690 PrintPool(Out, *I, State);
3691
3692 Out << NL;
3693 }
3694}
3695
3696//===----------------------------------------------------------------------===//
Jordy Rose910c4052011-09-02 06:44:22 +00003697// Checker registration.
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00003698//===----------------------------------------------------------------------===//
3699
Jordy Rose17a38e22011-09-02 05:55:19 +00003700void ento::registerRetainCountChecker(CheckerManager &Mgr) {
Jordy Rose910c4052011-09-02 06:44:22 +00003701 Mgr.registerChecker<RetainCountChecker>();
Jordy Rose17a38e22011-09-02 05:55:19 +00003702}
3703