blob: 325a7657e616f9707a4a5008809a502bb652163b [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
Anna Zaks58822c42012-05-04 22:18:39 +0000742 const RetainSummary *getSummary(const FunctionDecl *FD,
743 const CallOrObjCMessage *CME = 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000744
Jordy Rosef3aae582012-03-17 21:13:07 +0000745 const RetainSummary *getMethodSummary(Selector S, IdentifierInfo *ClsName,
746 const ObjCInterfaceDecl *ID,
747 const ObjCMethodDecl *MD,
748 QualType RetTy,
749 ObjCMethodSummariesTy &CachedSummaries);
750
Ted Kremenek93edbc52011-10-05 23:54:29 +0000751 const RetainSummary *getInstanceMethodSummary(const ObjCMessage &msg,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000752 ProgramStateRef state,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000753 const LocationContext *LC);
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000754
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000755 const RetainSummary *getInstanceMethodSummary(const ObjCMessage &msg,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000756 const ObjCInterfaceDecl *ID) {
Jordy Rosef3aae582012-03-17 21:13:07 +0000757 return getMethodSummary(msg.getSelector(), 0, ID, msg.getMethodDecl(),
758 msg.getType(Ctx), ObjCMethodSummaries);
Ted Kremenek8711c032009-04-29 05:04:30 +0000759 }
Mike Stump1eb44332009-09-09 15:08:12 +0000760
Ted Kremenek93edbc52011-10-05 23:54:29 +0000761 const RetainSummary *getClassMethodSummary(const ObjCMessage &msg) {
Argyrios Kyrtzidis432424d2011-01-25 00:03:53 +0000762 const ObjCInterfaceDecl *Class = 0;
763 if (!msg.isInstanceMessage())
764 Class = msg.getReceiverInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +0000765
Jordy Rosef3aae582012-03-17 21:13:07 +0000766 return getMethodSummary(msg.getSelector(), Class->getIdentifier(),
767 Class, msg.getMethodDecl(), msg.getType(Ctx),
768 ObjCClassMethodSummaries);
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +0000769 }
Ted Kremenek552333c2009-04-29 17:17:48 +0000770
771 /// getMethodSummary - This version of getMethodSummary is used to query
772 /// the summary for the current method being analyzed.
Ted Kremenek93edbc52011-10-05 23:54:29 +0000773 const RetainSummary *getMethodSummary(const ObjCMethodDecl *MD) {
Ted Kremeneka8833552009-04-29 23:03:22 +0000774 // FIXME: Eventually this should be unneeded.
Ted Kremeneka8833552009-04-29 23:03:22 +0000775 const ObjCInterfaceDecl *ID = MD->getClassInterface();
Ted Kremenek70a65762009-04-30 05:41:14 +0000776 Selector S = MD->getSelector();
Ted Kremenek552333c2009-04-29 17:17:48 +0000777 IdentifierInfo *ClsName = ID->getIdentifier();
778 QualType ResultTy = MD->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +0000779
Jordy Rosef3aae582012-03-17 21:13:07 +0000780 ObjCMethodSummariesTy *CachedSummaries;
Ted Kremenek552333c2009-04-29 17:17:48 +0000781 if (MD->isInstanceMethod())
Jordy Rosef3aae582012-03-17 21:13:07 +0000782 CachedSummaries = &ObjCMethodSummaries;
Ted Kremenek552333c2009-04-29 17:17:48 +0000783 else
Jordy Rosef3aae582012-03-17 21:13:07 +0000784 CachedSummaries = &ObjCClassMethodSummaries;
785
786 return getMethodSummary(S, ClsName, ID, MD, ResultTy, *CachedSummaries);
Ted Kremenek552333c2009-04-29 17:17:48 +0000787 }
Mike Stump1eb44332009-09-09 15:08:12 +0000788
Jordy Rosef3aae582012-03-17 21:13:07 +0000789 const RetainSummary *getStandardMethodSummary(const ObjCMethodDecl *MD,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000790 Selector S, QualType RetTy);
Ted Kremeneka8833552009-04-29 23:03:22 +0000791
Ted Kremenek93edbc52011-10-05 23:54:29 +0000792 void updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenek4dd8fb42009-05-09 02:58:13 +0000793 const ObjCMethodDecl *MD);
794
Ted Kremenek93edbc52011-10-05 23:54:29 +0000795 void updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenek4dd8fb42009-05-09 02:58:13 +0000796 const FunctionDecl *FD);
797
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000798 bool isGCEnabled() const { return GCEnabled; }
Mike Stump1eb44332009-09-09 15:08:12 +0000799
John McCallf85e1932011-06-15 23:02:42 +0000800 bool isARCEnabled() const { return ARCEnabled; }
801
802 bool isARCorGCEnabled() const { return GCEnabled || ARCEnabled; }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000803};
Mike Stump1eb44332009-09-09 15:08:12 +0000804
Jordy Rose0fe62f82011-08-24 09:02:37 +0000805// Used to avoid allocating long-term (BPAlloc'd) memory for default retain
806// summaries. If a function or method looks like it has a default summary, but
807// it has annotations, the annotations are added to the stack-based template
808// and then copied into managed memory.
809class RetainSummaryTemplate {
810 RetainSummaryManager &Manager;
Ted Kremenek93edbc52011-10-05 23:54:29 +0000811 const RetainSummary *&RealSummary;
Jordy Rose0fe62f82011-08-24 09:02:37 +0000812 RetainSummary ScratchSummary;
813 bool Accessed;
814public:
Jordy Rosee921b1a2012-03-17 19:53:04 +0000815 RetainSummaryTemplate(const RetainSummary *&real, const RetainSummary &base,
816 RetainSummaryManager &mgr)
817 : Manager(mgr), RealSummary(real), ScratchSummary(real ? *real : base),
Ted Kremenek93edbc52011-10-05 23:54:29 +0000818 Accessed(false) {}
Jordy Rose0fe62f82011-08-24 09:02:37 +0000819
820 ~RetainSummaryTemplate() {
Ted Kremenek93edbc52011-10-05 23:54:29 +0000821 if (Accessed)
Jordy Roseef945882012-03-18 01:26:10 +0000822 RealSummary = Manager.getPersistentSummary(ScratchSummary);
Jordy Rose0fe62f82011-08-24 09:02:37 +0000823 }
824
825 RetainSummary &operator*() {
826 Accessed = true;
Ted Kremenek93edbc52011-10-05 23:54:29 +0000827 return ScratchSummary;
Jordy Rose0fe62f82011-08-24 09:02:37 +0000828 }
829
830 RetainSummary *operator->() {
831 Accessed = true;
Ted Kremenek93edbc52011-10-05 23:54:29 +0000832 return &ScratchSummary;
Jordy Rose0fe62f82011-08-24 09:02:37 +0000833 }
834};
835
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000836} // end anonymous namespace
837
838//===----------------------------------------------------------------------===//
839// Implementation of checker data structures.
840//===----------------------------------------------------------------------===//
841
Ted Kremenekb77449c2009-05-03 05:20:50 +0000842ArgEffects RetainSummaryManager::getArgEffects() {
843 ArgEffects AE = ScratchArgs;
Ted Kremenek3baf6722010-11-24 00:54:37 +0000844 ScratchArgs = AF.getEmptyMap();
Ted Kremenekb77449c2009-05-03 05:20:50 +0000845 return AE;
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000846}
847
Ted Kremenek93edbc52011-10-05 23:54:29 +0000848const RetainSummary *
Jordy Roseef945882012-03-18 01:26:10 +0000849RetainSummaryManager::getPersistentSummary(const RetainSummary &OldSumm) {
850 // Unique "simple" summaries -- those without ArgEffects.
851 if (OldSumm.isSimple()) {
852 llvm::FoldingSetNodeID ID;
853 OldSumm.Profile(ID);
854
855 void *Pos;
856 CachedSummaryNode *N = SimpleSummaries.FindNodeOrInsertPos(ID, Pos);
857
858 if (!N) {
859 N = (CachedSummaryNode *) BPAlloc.Allocate<CachedSummaryNode>();
860 new (N) CachedSummaryNode(OldSumm);
861 SimpleSummaries.InsertNode(N, Pos);
862 }
863
864 return &N->getValue();
865 }
866
Ted Kremenek93edbc52011-10-05 23:54:29 +0000867 RetainSummary *Summ = (RetainSummary *) BPAlloc.Allocate<RetainSummary>();
Jordy Roseef945882012-03-18 01:26:10 +0000868 new (Summ) RetainSummary(OldSumm);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000869 return Summ;
870}
871
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000872//===----------------------------------------------------------------------===//
873// Summary creation for functions (largely uses of Core Foundation).
874//===----------------------------------------------------------------------===//
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000875
Ted Kremenek9c378f72011-08-12 23:37:29 +0000876static bool isRetain(const FunctionDecl *FD, StringRef FName) {
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000877 return FName.endswith("Retain");
Ted Kremenek12619382009-01-12 21:45:02 +0000878}
879
Ted Kremenek9c378f72011-08-12 23:37:29 +0000880static bool isRelease(const FunctionDecl *FD, StringRef FName) {
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000881 return FName.endswith("Release");
Ted Kremenek12619382009-01-12 21:45:02 +0000882}
883
Jordy Rose76c506f2011-08-21 21:58:18 +0000884static bool isMakeCollectable(const FunctionDecl *FD, StringRef FName) {
885 // FIXME: Remove FunctionDecl parameter.
886 // FIXME: Is it really okay if MakeCollectable isn't a suffix?
887 return FName.find("MakeCollectable") != StringRef::npos;
888}
889
Anna Zaks58822c42012-05-04 22:18:39 +0000890const RetainSummary *
891RetainSummaryManager::getSummary(const FunctionDecl *FD,
892 const CallOrObjCMessage *CME) {
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000893 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000894 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000895 if (I != FuncSummaries.end())
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000896 return I->second;
897
Ted Kremeneke401a0c2009-05-04 15:34:07 +0000898 // No summary? Generate one.
Ted Kremenek93edbc52011-10-05 23:54:29 +0000899 const RetainSummary *S = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000900
Ted Kremenek37d785b2008-07-15 16:50:12 +0000901 do {
Ted Kremenek12619382009-01-12 21:45:02 +0000902 // We generate "stop" summaries for implicitly defined functions.
903 if (FD->isImplicit()) {
904 S = getPersistentStopSummary();
905 break;
Ted Kremenek37d785b2008-07-15 16:50:12 +0000906 }
Ted Kremenek9ca28512011-05-02 21:21:42 +0000907 // For C++ methods, generate an implicit "stop" summary as well. We
908 // can relax this once we have a clear policy for C++ methods and
909 // ownership attributes.
910 if (isa<CXXMethodDecl>(FD)) {
911 S = getPersistentStopSummary();
912 break;
913 }
Mike Stump1eb44332009-09-09 15:08:12 +0000914
John McCall183700f2009-09-21 23:43:11 +0000915 // [PR 3337] Use 'getAs<FunctionType>' to strip away any typedefs on the
Ted Kremenek99890652009-01-16 18:40:33 +0000916 // function's type.
John McCall183700f2009-09-21 23:43:11 +0000917 const FunctionType* FT = FD->getType()->getAs<FunctionType>();
Ted Kremenek48c6d182009-12-16 06:06:43 +0000918 const IdentifierInfo *II = FD->getIdentifier();
919 if (!II)
920 break;
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000921
922 StringRef FName = II->getName();
Mike Stump1eb44332009-09-09 15:08:12 +0000923
Ted Kremenekbf0a4dd2009-03-05 22:11:14 +0000924 // Strip away preceding '_'. Doing this here will effect all the checks
925 // down below.
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000926 FName = FName.substr(FName.find_first_not_of('_'));
Mike Stump1eb44332009-09-09 15:08:12 +0000927
Ted Kremenek12619382009-01-12 21:45:02 +0000928 // Inspect the result type.
929 QualType RetTy = FT->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +0000930
Ted Kremenek12619382009-01-12 21:45:02 +0000931 // FIXME: This should all be refactored into a chain of "summary lookup"
932 // filters.
Ted Kremenek008636a2009-10-14 00:27:24 +0000933 assert(ScratchArgs.isEmpty());
Ted Kremenek39d88b02009-06-15 20:36:07 +0000934
Ted Kremenekbefc6d22012-04-26 04:32:23 +0000935 if (FName == "pthread_create" || FName == "pthread_setspecific") {
936 // Part of: <rdar://problem/7299394> and <rdar://problem/11282706>.
937 // This will be addressed better with IPA.
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000938 S = getPersistentStopSummary();
939 } else if (FName == "NSMakeCollectable") {
940 // Handle: id NSMakeCollectable(CFTypeRef)
941 S = (RetTy->isObjCIdType())
942 ? getUnarySummary(FT, cfmakecollectable)
943 : getPersistentStopSummary();
944 } else if (FName == "IOBSDNameMatching" ||
945 FName == "IOServiceMatching" ||
946 FName == "IOServiceNameMatching" ||
Ted Kremenek537dd3a2012-05-01 05:28:27 +0000947 FName == "IORegistryEntrySearchCFProperty" ||
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000948 FName == "IORegistryEntryIDMatching" ||
949 FName == "IOOpenFirmwarePathMatching") {
950 // Part of <rdar://problem/6961230>. (IOKit)
951 // This should be addressed using a API table.
952 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
953 DoNothing, DoNothing);
954 } else if (FName == "IOServiceGetMatchingService" ||
955 FName == "IOServiceGetMatchingServices") {
956 // FIXES: <rdar://problem/6326900>
957 // This should be addressed using a API table. This strcmp is also
958 // a little gross, but there is no need to super optimize here.
Ted Kremenek3baf6722010-11-24 00:54:37 +0000959 ScratchArgs = AF.add(ScratchArgs, 1, DecRef);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000960 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
961 } else if (FName == "IOServiceAddNotification" ||
962 FName == "IOServiceAddMatchingNotification") {
963 // Part of <rdar://problem/6961230>. (IOKit)
964 // This should be addressed using a API table.
Ted Kremenek3baf6722010-11-24 00:54:37 +0000965 ScratchArgs = AF.add(ScratchArgs, 2, DecRef);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000966 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
967 } else if (FName == "CVPixelBufferCreateWithBytes") {
968 // FIXES: <rdar://problem/7283567>
969 // Eventually this can be improved by recognizing that the pixel
970 // buffer passed to CVPixelBufferCreateWithBytes is released via
971 // a callback and doing full IPA to make sure this is done correctly.
972 // FIXME: This function has an out parameter that returns an
973 // allocated object.
Ted Kremenek3baf6722010-11-24 00:54:37 +0000974 ScratchArgs = AF.add(ScratchArgs, 7, StopTracking);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000975 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
976 } else if (FName == "CGBitmapContextCreateWithData") {
977 // FIXES: <rdar://problem/7358899>
978 // Eventually this can be improved by recognizing that 'releaseInfo'
979 // passed to CGBitmapContextCreateWithData is released via
980 // a callback and doing full IPA to make sure this is done correctly.
Ted Kremenek3baf6722010-11-24 00:54:37 +0000981 ScratchArgs = AF.add(ScratchArgs, 8, StopTracking);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000982 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
983 DoNothing, DoNothing);
984 } else if (FName == "CVPixelBufferCreateWithPlanarBytes") {
985 // FIXES: <rdar://problem/7283567>
986 // Eventually this can be improved by recognizing that the pixel
987 // buffer passed to CVPixelBufferCreateWithPlanarBytes is released
988 // via a callback and doing full IPA to make sure this is done
989 // correctly.
Ted Kremenek3baf6722010-11-24 00:54:37 +0000990 ScratchArgs = AF.add(ScratchArgs, 12, StopTracking);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000991 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenek06911d42012-03-22 06:29:41 +0000992 } else if (FName == "dispatch_set_context") {
993 // <rdar://problem/11059275> - The analyzer currently doesn't have
994 // a good way to reason about the finalizer function for libdispatch.
995 // If we pass a context object that is memory managed, stop tracking it.
996 // FIXME: this hack should possibly go away once we can handle
997 // libdispatch finalizers.
998 ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
999 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Anna Zaks62a5c342012-03-30 05:48:16 +00001000 } else if (FName.startswith("NS") &&
1001 (FName.find("Insert") != StringRef::npos)) {
1002 // Whitelist NSXXInsertXX, for example NSMapInsertIfAbsent, since they can
1003 // be deallocated by NSMapRemove. (radar://11152419)
1004 ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
1005 ScratchArgs = AF.add(ScratchArgs, 2, StopTracking);
1006 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Anna Zaks58822c42012-05-04 22:18:39 +00001007 } else if (CME && CME->hasNonZeroCallbackArg()) {
Anna Zaks41a669a2012-05-07 17:47:09 +00001008 // Allow objects to escape through callbacks. radar://10973977
1009 S = getPersistentStopSummary();
Ted Kremenekb04cb592009-06-11 18:17:24 +00001010 }
Mike Stump1eb44332009-09-09 15:08:12 +00001011
Ted Kremenekb04cb592009-06-11 18:17:24 +00001012 // Did we get a summary?
1013 if (S)
1014 break;
Ted Kremenek61991902009-03-17 22:43:44 +00001015
1016 // Enable this code once the semantics of NSDeallocateObject are resolved
1017 // for GC. <rdar://problem/6619988>
1018#if 0
1019 // Handle: NSDeallocateObject(id anObject);
1020 // This method does allow 'nil' (although we don't check it now).
Mike Stump1eb44332009-09-09 15:08:12 +00001021 if (strcmp(FName, "NSDeallocateObject") == 0) {
Ted Kremenek61991902009-03-17 22:43:44 +00001022 return RetTy == Ctx.VoidTy
1023 ? getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, Dealloc)
1024 : getPersistentStopSummary();
1025 }
1026#endif
Ted Kremenek12619382009-01-12 21:45:02 +00001027
1028 if (RetTy->isPointerType()) {
1029 // For CoreFoundation ('CF') types.
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001030 if (cocoa::isRefType(RetTy, "CF", FName)) {
Ted Kremenek12619382009-01-12 21:45:02 +00001031 if (isRetain(FD, FName))
1032 S = getUnarySummary(FT, cfretain);
Jordy Rose76c506f2011-08-21 21:58:18 +00001033 else if (isMakeCollectable(FD, FName))
Ted Kremenek12619382009-01-12 21:45:02 +00001034 S = getUnarySummary(FT, cfmakecollectable);
Mike Stump1eb44332009-09-09 15:08:12 +00001035 else
John McCall7df2ff42011-10-01 00:48:56 +00001036 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek12619382009-01-12 21:45:02 +00001037
1038 break;
1039 }
1040
1041 // For CoreGraphics ('CG') types.
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001042 if (cocoa::isRefType(RetTy, "CG", FName)) {
Ted Kremenek12619382009-01-12 21:45:02 +00001043 if (isRetain(FD, FName))
1044 S = getUnarySummary(FT, cfretain);
1045 else
John McCall7df2ff42011-10-01 00:48:56 +00001046 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek12619382009-01-12 21:45:02 +00001047
1048 break;
1049 }
1050
1051 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001052 if (cocoa::isRefType(RetTy, "DADisk") ||
1053 cocoa::isRefType(RetTy, "DADissenter") ||
1054 cocoa::isRefType(RetTy, "DASessionRef")) {
John McCall7df2ff42011-10-01 00:48:56 +00001055 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek12619382009-01-12 21:45:02 +00001056 break;
1057 }
Mike Stump1eb44332009-09-09 15:08:12 +00001058
Ted Kremenek12619382009-01-12 21:45:02 +00001059 break;
1060 }
1061
1062 // Check for release functions, the only kind of functions that we care
1063 // about that don't return a pointer type.
1064 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
Ted Kremeneke7d03122010-02-08 16:45:01 +00001065 // Test for 'CGCF'.
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001066 FName = FName.substr(FName.startswith("CGCF") ? 4 : 2);
Ted Kremeneke7d03122010-02-08 16:45:01 +00001067
Ted Kremenekbf0a4dd2009-03-05 22:11:14 +00001068 if (isRelease(FD, FName))
Ted Kremenek12619382009-01-12 21:45:02 +00001069 S = getUnarySummary(FT, cfrelease);
1070 else {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001071 assert (ScratchArgs.isEmpty());
Ted Kremenek68189282009-01-29 22:45:13 +00001072 // Remaining CoreFoundation and CoreGraphics functions.
1073 // We use to assume that they all strictly followed the ownership idiom
1074 // and that ownership cannot be transferred. While this is technically
1075 // correct, many methods allow a tracked object to escape. For example:
1076 //
Mike Stump1eb44332009-09-09 15:08:12 +00001077 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
Ted Kremenek68189282009-01-29 22:45:13 +00001078 // CFDictionaryAddValue(y, key, x);
Mike Stump1eb44332009-09-09 15:08:12 +00001079 // CFRelease(x);
Ted Kremenek68189282009-01-29 22:45:13 +00001080 // ... it is okay to use 'x' since 'y' has a reference to it
1081 //
1082 // We handle this and similar cases with the follow heuristic. If the
Ted Kremenekc4843812009-08-20 00:57:22 +00001083 // function name contains "InsertValue", "SetValue", "AddValue",
1084 // "AppendValue", or "SetAttribute", then we assume that arguments may
1085 // "escape." This means that something else holds on to the object,
1086 // allowing it be used even after its local retain count drops to 0.
Benjamin Kramere45c1492010-01-11 19:46:28 +00001087 ArgEffect E = (StrInStrNoCase(FName, "InsertValue") != StringRef::npos||
1088 StrInStrNoCase(FName, "AddValue") != StringRef::npos ||
1089 StrInStrNoCase(FName, "SetValue") != StringRef::npos ||
1090 StrInStrNoCase(FName, "AppendValue") != StringRef::npos||
Benjamin Kramerc027e542010-01-11 20:15:06 +00001091 StrInStrNoCase(FName, "SetAttribute") != StringRef::npos)
Ted Kremenek68189282009-01-29 22:45:13 +00001092 ? MayEscape : DoNothing;
Mike Stump1eb44332009-09-09 15:08:12 +00001093
Ted Kremenek68189282009-01-29 22:45:13 +00001094 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek12619382009-01-12 21:45:02 +00001095 }
1096 }
Ted Kremenek37d785b2008-07-15 16:50:12 +00001097 }
1098 while (0);
Mike Stump1eb44332009-09-09 15:08:12 +00001099
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001100 // Annotations override defaults.
Jordy Rose4df54fe2011-08-23 04:27:15 +00001101 updateSummaryFromAnnotations(S, FD);
Mike Stump1eb44332009-09-09 15:08:12 +00001102
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001103 FuncSummaries[FD] = S;
Mike Stump1eb44332009-09-09 15:08:12 +00001104 return S;
Ted Kremenek2fff37e2008-03-06 00:08:09 +00001105}
1106
Ted Kremenek93edbc52011-10-05 23:54:29 +00001107const RetainSummary *
John McCall7df2ff42011-10-01 00:48:56 +00001108RetainSummaryManager::getCFCreateGetRuleSummary(const FunctionDecl *FD) {
1109 if (coreFoundation::followsCreateRule(FD))
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001110 return getCFSummaryCreateRule(FD);
Mike Stump1eb44332009-09-09 15:08:12 +00001111
Ted Kremenekd368d712011-05-25 06:19:45 +00001112 return getCFSummaryGetRule(FD);
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001113}
1114
Ted Kremenek93edbc52011-10-05 23:54:29 +00001115const RetainSummary *
Ted Kremenek6ad315a2009-02-23 16:51:39 +00001116RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1117 UnaryFuncKind func) {
1118
Ted Kremenek12619382009-01-12 21:45:02 +00001119 // Sanity check that this is *really* a unary function. This can
1120 // happen if people do weird things.
Douglas Gregor72564e72009-02-26 23:50:07 +00001121 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
Ted Kremenek12619382009-01-12 21:45:02 +00001122 if (!FTP || FTP->getNumArgs() != 1)
1123 return getPersistentStopSummary();
Mike Stump1eb44332009-09-09 15:08:12 +00001124
Ted Kremenekb77449c2009-05-03 05:20:50 +00001125 assert (ScratchArgs.isEmpty());
Mike Stump1eb44332009-09-09 15:08:12 +00001126
Jordy Rose76c506f2011-08-21 21:58:18 +00001127 ArgEffect Effect;
Ted Kremenek377e2302008-04-29 05:33:51 +00001128 switch (func) {
Jordy Rose76c506f2011-08-21 21:58:18 +00001129 case cfretain: Effect = IncRef; break;
1130 case cfrelease: Effect = DecRef; break;
1131 case cfmakecollectable: Effect = MakeCollectable; break;
Ted Kremenek940b1d82008-04-10 23:44:06 +00001132 }
Jordy Rose76c506f2011-08-21 21:58:18 +00001133
1134 ScratchArgs = AF.add(ScratchArgs, 0, Effect);
1135 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001136}
1137
Ted Kremenek93edbc52011-10-05 23:54:29 +00001138const RetainSummary *
Ted Kremenek9c378f72011-08-12 23:37:29 +00001139RetainSummaryManager::getCFSummaryCreateRule(const FunctionDecl *FD) {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001140 assert (ScratchArgs.isEmpty());
Mike Stump1eb44332009-09-09 15:08:12 +00001141
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001142 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001143}
1144
Ted Kremenek93edbc52011-10-05 23:54:29 +00001145const RetainSummary *
Ted Kremenek9c378f72011-08-12 23:37:29 +00001146RetainSummaryManager::getCFSummaryGetRule(const FunctionDecl *FD) {
Mike Stump1eb44332009-09-09 15:08:12 +00001147 assert (ScratchArgs.isEmpty());
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001148 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1149 DoNothing, DoNothing);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001150}
1151
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001152//===----------------------------------------------------------------------===//
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001153// Summary creation for Selectors.
1154//===----------------------------------------------------------------------===//
1155
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001156void
Ted Kremenek93edbc52011-10-05 23:54:29 +00001157RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001158 const FunctionDecl *FD) {
1159 if (!FD)
1160 return;
1161
Jordy Roseef945882012-03-18 01:26:10 +00001162 RetainSummaryTemplate Template(Summ, *getDefaultSummary(), *this);
Jordy Rose4df54fe2011-08-23 04:27:15 +00001163
Ted Kremenek11fe1752011-01-27 18:43:03 +00001164 // Effects on the parameters.
1165 unsigned parm_idx = 0;
1166 for (FunctionDecl::param_const_iterator pi = FD->param_begin(),
John McCall98b8f162011-04-06 09:02:12 +00001167 pe = FD->param_end(); pi != pe; ++pi, ++parm_idx) {
Ted Kremenek11fe1752011-01-27 18:43:03 +00001168 const ParmVarDecl *pd = *pi;
1169 if (pd->getAttr<NSConsumedAttr>()) {
Jordy Rose4df54fe2011-08-23 04:27:15 +00001170 if (!GCEnabled) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001171 Template->addArg(AF, parm_idx, DecRef);
Jordy Rose4df54fe2011-08-23 04:27:15 +00001172 }
1173 } else if (pd->getAttr<CFConsumedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001174 Template->addArg(AF, parm_idx, DecRef);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001175 }
1176 }
1177
Ted Kremenekb04cb592009-06-11 18:17:24 +00001178 QualType RetTy = FD->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00001179
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001180 // Determine if there is a special return effect for this method.
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001181 if (cocoa::isCocoaObjectRef(RetTy)) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001182 if (FD->getAttr<NSReturnsRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001183 Template->setRetEffect(ObjCAllocRetE);
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001184 }
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001185 else if (FD->getAttr<CFReturnsRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001186 Template->setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenekb04cb592009-06-11 18:17:24 +00001187 }
Ted Kremenek60411112010-02-18 00:06:12 +00001188 else if (FD->getAttr<NSReturnsNotRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001189 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::ObjC));
Ted Kremenek60411112010-02-18 00:06:12 +00001190 }
1191 else if (FD->getAttr<CFReturnsNotRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001192 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::CF));
Jordy Rose4df54fe2011-08-23 04:27:15 +00001193 }
1194 } else if (RetTy->getAs<PointerType>()) {
1195 if (FD->getAttr<CFReturnsRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001196 Template->setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
Jordy Rose4df54fe2011-08-23 04:27:15 +00001197 }
1198 else if (FD->getAttr<CFReturnsNotRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001199 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::CF));
Ted Kremenek60411112010-02-18 00:06:12 +00001200 }
Ted Kremenekb04cb592009-06-11 18:17:24 +00001201 }
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001202}
1203
1204void
Ted Kremenek93edbc52011-10-05 23:54:29 +00001205RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
1206 const ObjCMethodDecl *MD) {
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001207 if (!MD)
1208 return;
1209
Jordy Roseef945882012-03-18 01:26:10 +00001210 RetainSummaryTemplate Template(Summ, *getDefaultSummary(), *this);
Ted Kremenek6d4b76d2009-07-06 18:30:43 +00001211 bool isTrackedLoc = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001212
Ted Kremenek12b94342011-01-27 06:54:14 +00001213 // Effects on the receiver.
1214 if (MD->getAttr<NSConsumesSelfAttr>()) {
Ted Kremenek11fe1752011-01-27 18:43:03 +00001215 if (!GCEnabled)
Jordy Rose0fe62f82011-08-24 09:02:37 +00001216 Template->setReceiverEffect(DecRefMsg);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001217 }
1218
1219 // Effects on the parameters.
1220 unsigned parm_idx = 0;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00001221 for (ObjCMethodDecl::param_const_iterator
1222 pi=MD->param_begin(), pe=MD->param_end();
Ted Kremenek11fe1752011-01-27 18:43:03 +00001223 pi != pe; ++pi, ++parm_idx) {
1224 const ParmVarDecl *pd = *pi;
1225 if (pd->getAttr<NSConsumedAttr>()) {
1226 if (!GCEnabled)
Jordy Rose0fe62f82011-08-24 09:02:37 +00001227 Template->addArg(AF, parm_idx, DecRef);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001228 }
1229 else if(pd->getAttr<CFConsumedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001230 Template->addArg(AF, parm_idx, DecRef);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001231 }
Ted Kremenek12b94342011-01-27 06:54:14 +00001232 }
1233
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001234 // Determine if there is a special return effect for this method.
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001235 if (cocoa::isCocoaObjectRef(MD->getResultType())) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001236 if (MD->getAttr<NSReturnsRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001237 Template->setRetEffect(ObjCAllocRetE);
Ted Kremenek6d4b76d2009-07-06 18:30:43 +00001238 return;
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001239 }
Ted Kremenek60411112010-02-18 00:06:12 +00001240 if (MD->getAttr<NSReturnsNotRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001241 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::ObjC));
Ted Kremenek60411112010-02-18 00:06:12 +00001242 return;
1243 }
Mike Stump1eb44332009-09-09 15:08:12 +00001244
Ted Kremenek6d4b76d2009-07-06 18:30:43 +00001245 isTrackedLoc = true;
Jordy Rose0fe62f82011-08-24 09:02:37 +00001246 } else {
Ted Kremenek6217b802009-07-29 21:53:49 +00001247 isTrackedLoc = MD->getResultType()->getAs<PointerType>() != NULL;
Jordy Rose0fe62f82011-08-24 09:02:37 +00001248 }
Mike Stump1eb44332009-09-09 15:08:12 +00001249
Ted Kremenek60411112010-02-18 00:06:12 +00001250 if (isTrackedLoc) {
1251 if (MD->getAttr<CFReturnsRetainedAttr>())
Jordy Rose0fe62f82011-08-24 09:02:37 +00001252 Template->setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenek60411112010-02-18 00:06:12 +00001253 else if (MD->getAttr<CFReturnsNotRetainedAttr>())
Jordy Rose0fe62f82011-08-24 09:02:37 +00001254 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::CF));
Ted Kremenek60411112010-02-18 00:06:12 +00001255 }
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001256}
1257
Ted Kremenek93edbc52011-10-05 23:54:29 +00001258const RetainSummary *
Jordy Rosef3aae582012-03-17 21:13:07 +00001259RetainSummaryManager::getStandardMethodSummary(const ObjCMethodDecl *MD,
1260 Selector S, QualType RetTy) {
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001261
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +00001262 if (MD) {
Ted Kremenek376d1e72009-04-24 18:00:17 +00001263 // Scan the method decl for 'void*' arguments. These should be treated
1264 // as 'StopTracking' because they are often used with delegates.
1265 // Delegates are a frequent form of false positives with the retain
1266 // count checker.
1267 unsigned i = 0;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00001268 for (ObjCMethodDecl::param_const_iterator I = MD->param_begin(),
Ted Kremenek376d1e72009-04-24 18:00:17 +00001269 E = MD->param_end(); I != E; ++I, ++i)
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00001270 if (const ParmVarDecl *PD = *I) {
Ted Kremenek376d1e72009-04-24 18:00:17 +00001271 QualType Ty = Ctx.getCanonicalType(PD->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001272 if (Ty.getLocalUnqualifiedType() == Ctx.VoidPtrTy)
Ted Kremenek3baf6722010-11-24 00:54:37 +00001273 ScratchArgs = AF.add(ScratchArgs, i, StopTracking);
Ted Kremenek376d1e72009-04-24 18:00:17 +00001274 }
1275 }
Mike Stump1eb44332009-09-09 15:08:12 +00001276
Jordy Rosee921b1a2012-03-17 19:53:04 +00001277 // Any special effects?
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001278 ArgEffect ReceiverEff = DoNothing;
Jordy Rosee921b1a2012-03-17 19:53:04 +00001279 RetEffect ResultEff = RetEffect::MakeNoRet();
1280
1281 // Check the method family, and apply any default annotations.
1282 switch (MD ? MD->getMethodFamily() : S.getMethodFamily()) {
1283 case OMF_None:
1284 case OMF_performSelector:
1285 // Assume all Objective-C methods follow Cocoa Memory Management rules.
1286 // FIXME: Does the non-threaded performSelector family really belong here?
1287 // The selector could be, say, @selector(copy).
1288 if (cocoa::isCocoaObjectRef(RetTy))
1289 ResultEff = RetEffect::MakeNotOwned(RetEffect::ObjC);
1290 else if (coreFoundation::isCFObjectRef(RetTy)) {
1291 // ObjCMethodDecl currently doesn't consider CF objects as valid return
1292 // values for alloc, new, copy, or mutableCopy, so we have to
1293 // double-check with the selector. This is ugly, but there aren't that
1294 // many Objective-C methods that return CF objects, right?
1295 if (MD) {
1296 switch (S.getMethodFamily()) {
1297 case OMF_alloc:
1298 case OMF_new:
1299 case OMF_copy:
1300 case OMF_mutableCopy:
1301 ResultEff = RetEffect::MakeOwned(RetEffect::CF, true);
1302 break;
1303 default:
1304 ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1305 break;
1306 }
1307 } else {
1308 ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1309 }
1310 }
1311 break;
1312 case OMF_init:
1313 ResultEff = ObjCInitRetE;
1314 ReceiverEff = DecRefMsg;
1315 break;
1316 case OMF_alloc:
1317 case OMF_new:
1318 case OMF_copy:
1319 case OMF_mutableCopy:
1320 if (cocoa::isCocoaObjectRef(RetTy))
1321 ResultEff = ObjCAllocRetE;
1322 else if (coreFoundation::isCFObjectRef(RetTy))
1323 ResultEff = RetEffect::MakeOwned(RetEffect::CF, true);
1324 break;
1325 case OMF_autorelease:
1326 ReceiverEff = Autorelease;
1327 break;
1328 case OMF_retain:
1329 ReceiverEff = IncRefMsg;
1330 break;
1331 case OMF_release:
1332 ReceiverEff = DecRefMsg;
1333 break;
1334 case OMF_dealloc:
1335 ReceiverEff = Dealloc;
1336 break;
1337 case OMF_self:
1338 // -self is handled specially by the ExprEngine to propagate the receiver.
1339 break;
1340 case OMF_retainCount:
1341 case OMF_finalize:
1342 // These methods don't return objects.
1343 break;
1344 }
Mike Stump1eb44332009-09-09 15:08:12 +00001345
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001346 // If one of the arguments in the selector has the keyword 'delegate' we
1347 // should stop tracking the reference count for the receiver. This is
1348 // because the reference count is quite possibly handled by a delegate
1349 // method.
1350 if (S.isKeywordSelector()) {
1351 const std::string &str = S.getAsString();
1352 assert(!str.empty());
Benjamin Kramere45c1492010-01-11 19:46:28 +00001353 if (StrInStrNoCase(str, "delegate:") != StringRef::npos)
1354 ReceiverEff = StopTracking;
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001355 }
Mike Stump1eb44332009-09-09 15:08:12 +00001356
Jordy Rosee921b1a2012-03-17 19:53:04 +00001357 if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing &&
1358 ResultEff.getKind() == RetEffect::NoRet)
Ted Kremenek93edbc52011-10-05 23:54:29 +00001359 return getDefaultSummary();
Mike Stump1eb44332009-09-09 15:08:12 +00001360
Jordy Rosee921b1a2012-03-17 19:53:04 +00001361 return getPersistentSummary(ResultEff, ReceiverEff, MayEscape);
Ted Kremenek250b1fa2009-04-23 23:08:22 +00001362}
1363
Ted Kremenek93edbc52011-10-05 23:54:29 +00001364const RetainSummary *
Argyrios Kyrtzidis432424d2011-01-25 00:03:53 +00001365RetainSummaryManager::getInstanceMethodSummary(const ObjCMessage &msg,
Ted Kremenek8bef8232012-01-26 21:29:00 +00001366 ProgramStateRef state,
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001367 const LocationContext *LC) {
1368
1369 // We need the type-information of the tracked receiver object
1370 // Retrieve it from the state.
Argyrios Kyrtzidis432424d2011-01-25 00:03:53 +00001371 const Expr *Receiver = msg.getInstanceReceiver();
Ted Kremenek9c378f72011-08-12 23:37:29 +00001372 const ObjCInterfaceDecl *ID = 0;
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001373
1374 // FIXME: Is this really working as expected? There are cases where
1375 // we just use the 'ID' from the message expression.
Douglas Gregor04badcf2010-04-21 00:45:42 +00001376 SVal receiverV;
1377
Ted Kremenek8f326752010-05-21 21:56:53 +00001378 if (Receiver) {
Ted Kremenek5eca4822012-01-06 22:09:28 +00001379 receiverV = state->getSValAsScalarOrLoc(Receiver, LC);
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00001380
Douglas Gregor04badcf2010-04-21 00:45:42 +00001381 // FIXME: Eventually replace the use of state->get<RefBindings> with
1382 // a generic API for reasoning about the Objective-C types of symbolic
1383 // objects.
1384 if (SymbolRef Sym = receiverV.getAsLocSymbol())
1385 if (const RefVal *T = state->get<RefBindings>(Sym))
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00001386 if (const ObjCObjectPointerType* PT =
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001387 T->getType()->getAs<ObjCObjectPointerType>())
Douglas Gregor04badcf2010-04-21 00:45:42 +00001388 ID = PT->getInterfaceDecl();
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00001389
Douglas Gregor04badcf2010-04-21 00:45:42 +00001390 // FIXME: this is a hack. This may or may not be the actual method
1391 // that is called.
1392 if (!ID) {
1393 if (const ObjCObjectPointerType *PT =
1394 Receiver->getType()->getAs<ObjCObjectPointerType>())
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001395 ID = PT->getInterfaceDecl();
Douglas Gregor04badcf2010-04-21 00:45:42 +00001396 }
1397 } else {
1398 // FIXME: Hack for 'super'.
Argyrios Kyrtzidis432424d2011-01-25 00:03:53 +00001399 ID = msg.getReceiverInterface();
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001400 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001401
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001402 // FIXME: The receiver could be a reference to a class, meaning that
1403 // we should use the class method.
Jordy Rose4df54fe2011-08-23 04:27:15 +00001404 return getInstanceMethodSummary(msg, ID);
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001405}
1406
Ted Kremenek93edbc52011-10-05 23:54:29 +00001407const RetainSummary *
Jordy Rosef3aae582012-03-17 21:13:07 +00001408RetainSummaryManager::getMethodSummary(Selector S, IdentifierInfo *ClsName,
1409 const ObjCInterfaceDecl *ID,
1410 const ObjCMethodDecl *MD, QualType RetTy,
1411 ObjCMethodSummariesTy &CachedSummaries) {
Ted Kremenek1bffd742008-05-06 15:44:25 +00001412
Ted Kremenek8711c032009-04-29 05:04:30 +00001413 // Look up a summary in our summary cache.
Jordy Rosef3aae582012-03-17 21:13:07 +00001414 const RetainSummary *Summ = CachedSummaries.find(ID, ClsName, S);
Mike Stump1eb44332009-09-09 15:08:12 +00001415
Ted Kremenek614cc542009-07-21 23:27:57 +00001416 if (!Summ) {
Jordy Rosef3aae582012-03-17 21:13:07 +00001417 Summ = getStandardMethodSummary(MD, S, RetTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001418
Ted Kremenek614cc542009-07-21 23:27:57 +00001419 // Annotations override defaults.
Jordy Rose4df54fe2011-08-23 04:27:15 +00001420 updateSummaryFromAnnotations(Summ, MD);
Mike Stump1eb44332009-09-09 15:08:12 +00001421
Ted Kremenek614cc542009-07-21 23:27:57 +00001422 // Memoize the summary.
Jordy Rosef3aae582012-03-17 21:13:07 +00001423 CachedSummaries[ObjCSummaryKey(ID, ClsName, S)] = Summ;
Ted Kremenek614cc542009-07-21 23:27:57 +00001424 }
Mike Stump1eb44332009-09-09 15:08:12 +00001425
Ted Kremeneke87450e2009-04-23 19:11:35 +00001426 return Summ;
Ted Kremenekc8395602008-05-06 21:26:51 +00001427}
1428
Mike Stump1eb44332009-09-09 15:08:12 +00001429void RetainSummaryManager::InitializeClassMethodSummaries() {
Ted Kremenekec315332009-05-07 23:40:42 +00001430 assert(ScratchArgs.isEmpty());
Mike Stump1eb44332009-09-09 15:08:12 +00001431 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek6fe2b7a2009-10-15 22:25:12 +00001432 addClassMethSummary("NSAssertionHandler", "currentHandler",
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001433 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Mike Stump1eb44332009-09-09 15:08:12 +00001434
Ted Kremenek6d348932008-10-21 15:53:15 +00001435 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001436 ScratchArgs = AF.add(ScratchArgs, 0, Autorelease);
Ted Kremenek6fe2b7a2009-10-15 22:25:12 +00001437 addClassMethSummary("NSAutoreleasePool", "addObject",
1438 getPersistentSummary(RetEffect::MakeNoRet(),
1439 DoNothing, Autorelease));
Mike Stump1eb44332009-09-09 15:08:12 +00001440
Ted Kremenekde4d5332009-04-24 17:50:11 +00001441 // Create the summaries for [NSObject performSelector...]. We treat
1442 // these as 'stop tracking' for the arguments because they are often
1443 // used for delegates that can release the object. When we have better
1444 // inter-procedural analysis we can potentially do something better. This
1445 // workaround is to remove false positives.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001446 const RetainSummary *Summ =
Ted Kremenek012614e2011-08-17 21:04:19 +00001447 getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, StopTracking);
Ted Kremenekde4d5332009-04-24 17:50:11 +00001448 IdentifierInfo *NSObjectII = &Ctx.Idents.get("NSObject");
1449 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1450 "afterDelay", NULL);
1451 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1452 "afterDelay", "inModes", NULL);
1453 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1454 "withObject", "waitUntilDone", NULL);
1455 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1456 "withObject", "waitUntilDone", "modes", NULL);
1457 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1458 "withObject", "waitUntilDone", NULL);
1459 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1460 "withObject", "waitUntilDone", "modes", NULL);
1461 addClsMethSummary(NSObjectII, Summ, "performSelectorInBackground",
1462 "withObject", NULL);
Ted Kremenek9c32d082008-05-06 00:30:21 +00001463}
1464
Ted Kremenek1f180c32008-06-23 22:21:20 +00001465void RetainSummaryManager::InitializeMethodSummaries() {
Mike Stump1eb44332009-09-09 15:08:12 +00001466
1467 assert (ScratchArgs.isEmpty());
1468
Ted Kremenekc8395602008-05-06 21:26:51 +00001469 // Create the "init" selector. It just acts as a pass-through for the
1470 // receiver.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001471 const RetainSummary *InitSumm = getPersistentSummary(ObjCInitRetE, DecRefMsg);
Ted Kremenekac02f202009-08-20 05:13:36 +00001472 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
1473
1474 // awakeAfterUsingCoder: behaves basically like an 'init' method. It
1475 // claims the receiver and returns a retained object.
1476 addNSObjectMethSummary(GetUnarySelector("awakeAfterUsingCoder", Ctx),
1477 InitSumm);
Mike Stump1eb44332009-09-09 15:08:12 +00001478
Ted Kremenekc8395602008-05-06 21:26:51 +00001479 // The next methods are allocators.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001480 const RetainSummary *AllocSumm = getPersistentSummary(ObjCAllocRetE);
1481 const RetainSummary *CFAllocSumm =
Ted Kremeneka834fb42009-08-28 19:52:12 +00001482 getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Mike Stump1eb44332009-09-09 15:08:12 +00001483
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001484 // Create the "retain" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001485 RetEffect NoRet = RetEffect::MakeNoRet();
Ted Kremenek93edbc52011-10-05 23:54:29 +00001486 const RetainSummary *Summ = getPersistentSummary(NoRet, IncRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001487 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001488
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001489 // Create the "release" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001490 Summ = getPersistentSummary(NoRet, DecRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001491 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001492
Ted Kremenek299e8152008-05-07 21:17:39 +00001493 // Create the "drain" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001494 Summ = getPersistentSummary(NoRet, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek553cf182008-06-25 21:21:56 +00001495 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001496
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001497 // Create the -dealloc summary.
Jordy Rose500abad2011-08-21 19:41:36 +00001498 Summ = getPersistentSummary(NoRet, Dealloc);
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001499 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001500
1501 // Create the "autorelease" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001502 Summ = getPersistentSummary(NoRet, Autorelease);
Ted Kremenek553cf182008-06-25 21:21:56 +00001503 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001504
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00001505 // Specially handle NSAutoreleasePool.
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001506 addInstMethSummary("NSAutoreleasePool", "init",
Jordy Rose500abad2011-08-21 19:41:36 +00001507 getPersistentSummary(NoRet, NewAutoreleasePool));
Mike Stump1eb44332009-09-09 15:08:12 +00001508
1509 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremenek89e202d2009-02-23 02:51:29 +00001510 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1511 // self-own themselves. However, they only do this once they are displayed.
1512 // Thus, we need to track an NSWindow's display status.
1513 // This is tracked in <rdar://problem/6062711>.
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +00001514 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001515 const RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenek78a35a32009-05-12 20:06:54 +00001516 StopTracking,
1517 StopTracking);
Mike Stump1eb44332009-09-09 15:08:12 +00001518
Ted Kremenek99d02692009-04-03 19:02:51 +00001519 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1520
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +00001521#if 0
Ted Kremenek78a35a32009-05-12 20:06:54 +00001522 addInstMethSummary("NSWindow", NoTrackYet, "initWithContentRect",
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001523 "styleMask", "backing", "defer", NULL);
Mike Stump1eb44332009-09-09 15:08:12 +00001524
Ted Kremenek78a35a32009-05-12 20:06:54 +00001525 addInstMethSummary("NSWindow", NoTrackYet, "initWithContentRect",
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001526 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +00001527#endif
Mike Stump1eb44332009-09-09 15:08:12 +00001528
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001529 // For NSPanel (which subclasses NSWindow), allocated objects are not
1530 // self-owned.
Ted Kremenek99d02692009-04-03 19:02:51 +00001531 // FIXME: For now we don't track NSPanels. object for the same reason
1532 // as for NSWindow objects.
1533 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
Mike Stump1eb44332009-09-09 15:08:12 +00001534
Ted Kremenek78a35a32009-05-12 20:06:54 +00001535#if 0
1536 addInstMethSummary("NSPanel", NoTrackYet, "initWithContentRect",
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001537 "styleMask", "backing", "defer", NULL);
Mike Stump1eb44332009-09-09 15:08:12 +00001538
Ted Kremenek78a35a32009-05-12 20:06:54 +00001539 addInstMethSummary("NSPanel", NoTrackYet, "initWithContentRect",
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001540 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek78a35a32009-05-12 20:06:54 +00001541#endif
Mike Stump1eb44332009-09-09 15:08:12 +00001542
Ted Kremenekba67f6a2009-05-18 23:14:34 +00001543 // Don't track allocated autorelease pools yet, as it is okay to prematurely
1544 // exit a method.
1545 addClassMethSummary("NSAutoreleasePool", "alloc", NoTrackYet);
Ted Kremeneka9797122012-02-18 21:37:48 +00001546 addClassMethSummary("NSAutoreleasePool", "allocWithZone", NoTrackYet, false);
Ted Kremenek553cf182008-06-25 21:21:56 +00001547
Ted Kremenek767d6492009-05-20 22:39:57 +00001548 // Create summaries QCRenderer/QCView -createSnapShotImageOfType:
1549 addInstMethSummary("QCRenderer", AllocSumm,
1550 "createSnapshotImageOfType", NULL);
1551 addInstMethSummary("QCView", AllocSumm,
1552 "createSnapshotImageOfType", NULL);
1553
Ted Kremenek211a9c62009-06-15 20:58:58 +00001554 // Create summaries for CIContext, 'createCGImage' and
Ted Kremeneka834fb42009-08-28 19:52:12 +00001555 // 'createCGLayerWithSize'. These objects are CF objects, and are not
1556 // automatically garbage collected.
1557 addInstMethSummary("CIContext", CFAllocSumm,
Ted Kremenek767d6492009-05-20 22:39:57 +00001558 "createCGImage", "fromRect", NULL);
Ted Kremeneka834fb42009-08-28 19:52:12 +00001559 addInstMethSummary("CIContext", CFAllocSumm,
Mike Stump1eb44332009-09-09 15:08:12 +00001560 "createCGImage", "fromRect", "format", "colorSpace", NULL);
Ted Kremeneka834fb42009-08-28 19:52:12 +00001561 addInstMethSummary("CIContext", CFAllocSumm, "createCGLayerWithSize",
Ted Kremenek211a9c62009-06-15 20:58:58 +00001562 "info", NULL);
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001563}
1564
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001565//===----------------------------------------------------------------------===//
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001566// AutoreleaseBindings - State used to track objects in autorelease pools.
Ted Kremenek6d348932008-10-21 15:53:15 +00001567//===----------------------------------------------------------------------===//
1568
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001569typedef llvm::ImmutableMap<SymbolRef, unsigned> ARCounts;
1570typedef llvm::ImmutableMap<SymbolRef, ARCounts> ARPoolContents;
1571typedef llvm::ImmutableList<SymbolRef> ARStack;
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00001572
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001573static int AutoRCIndex = 0;
Ted Kremenek6d348932008-10-21 15:53:15 +00001574static int AutoRBIndex = 0;
1575
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001576namespace { class AutoreleasePoolContents {}; }
1577namespace { class AutoreleaseStack {}; }
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001578
Ted Kremenek6d348932008-10-21 15:53:15 +00001579namespace clang {
Ted Kremenek9ef65372010-12-23 07:20:52 +00001580namespace ento {
Ted Kremenek18c66fd2011-08-15 22:09:50 +00001581template<> struct ProgramStateTrait<AutoreleaseStack>
1582 : public ProgramStatePartialTrait<ARStack> {
Ted Kremenek9c378f72011-08-12 23:37:29 +00001583 static inline void *GDMIndex() { return &AutoRBIndex; }
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001584};
1585
Ted Kremenek18c66fd2011-08-15 22:09:50 +00001586template<> struct ProgramStateTrait<AutoreleasePoolContents>
1587 : public ProgramStatePartialTrait<ARPoolContents> {
Ted Kremenek9c378f72011-08-12 23:37:29 +00001588 static inline void *GDMIndex() { return &AutoRCIndex; }
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001589};
Argyrios Kyrtzidis5a4f98f2010-12-22 18:53:20 +00001590} // end GR namespace
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001591} // end clang namespace
Ted Kremenek6d348932008-10-21 15:53:15 +00001592
Ted Kremenek8bef8232012-01-26 21:29:00 +00001593static SymbolRef GetCurrentAutoreleasePool(ProgramStateRef state) {
Ted Kremenek7037ab82009-03-20 17:34:15 +00001594 ARStack stack = state->get<AutoreleaseStack>();
1595 return stack.isEmpty() ? SymbolRef() : stack.getHead();
1596}
1597
Ted Kremenek8bef8232012-01-26 21:29:00 +00001598static ProgramStateRef
1599SendAutorelease(ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +00001600 ARCounts::Factory &F,
1601 SymbolRef sym) {
Ted Kremenek7037ab82009-03-20 17:34:15 +00001602 SymbolRef pool = GetCurrentAutoreleasePool(state);
Ted Kremenekb65be702009-06-18 01:23:53 +00001603 const ARCounts *cnts = state->get<AutoreleasePoolContents>(pool);
Ted Kremenek7037ab82009-03-20 17:34:15 +00001604 ARCounts newCnts(0);
Mike Stump1eb44332009-09-09 15:08:12 +00001605
Ted Kremenek7037ab82009-03-20 17:34:15 +00001606 if (cnts) {
1607 const unsigned *cnt = (*cnts).lookup(sym);
Ted Kremenek3baf6722010-11-24 00:54:37 +00001608 newCnts = F.add(*cnts, sym, cnt ? *cnt + 1 : 1);
Ted Kremenek7037ab82009-03-20 17:34:15 +00001609 }
1610 else
Ted Kremenek3baf6722010-11-24 00:54:37 +00001611 newCnts = F.add(F.getEmptyMap(), sym, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001612
Ted Kremenekb65be702009-06-18 01:23:53 +00001613 return state->set<AutoreleasePoolContents>(pool, newCnts);
Ted Kremenek7037ab82009-03-20 17:34:15 +00001614}
1615
Ted Kremenek13922612008-04-16 20:40:59 +00001616//===----------------------------------------------------------------------===//
Ted Kremenekc887d132009-04-29 18:50:19 +00001617// Error reporting.
1618//===----------------------------------------------------------------------===//
Ted Kremenekc887d132009-04-29 18:50:19 +00001619namespace {
Jordy Roseec9ef852011-08-23 20:55:48 +00001620 typedef llvm::DenseMap<const ExplodedNode *, const RetainSummary *>
1621 SummaryLogTy;
1622
Ted Kremenekc887d132009-04-29 18:50:19 +00001623 //===-------------===//
1624 // Bug Descriptions. //
Mike Stump1eb44332009-09-09 15:08:12 +00001625 //===-------------===//
1626
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001627 class CFRefBug : public BugType {
Ted Kremenekc887d132009-04-29 18:50:19 +00001628 protected:
Jordy Rose35c86952011-08-24 05:47:39 +00001629 CFRefBug(StringRef name)
Ted Kremenek6fd45052012-04-05 20:43:28 +00001630 : BugType(name, categories::MemoryCoreFoundationObjectiveC) {}
Ted Kremenekc887d132009-04-29 18:50:19 +00001631 public:
Mike Stump1eb44332009-09-09 15:08:12 +00001632
Ted Kremenekc887d132009-04-29 18:50:19 +00001633 // FIXME: Eventually remove.
Jordy Rose35c86952011-08-24 05:47:39 +00001634 virtual const char *getDescription() const = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001635
Ted Kremenekc887d132009-04-29 18:50:19 +00001636 virtual bool isLeak() const { return false; }
1637 };
Mike Stump1eb44332009-09-09 15:08:12 +00001638
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001639 class UseAfterRelease : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001640 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001641 UseAfterRelease() : CFRefBug("Use-after-release") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001642
Jordy Rose35c86952011-08-24 05:47:39 +00001643 const char *getDescription() const {
Ted Kremenekc887d132009-04-29 18:50:19 +00001644 return "Reference-counted object is used after it is released";
Mike Stump1eb44332009-09-09 15:08:12 +00001645 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001646 };
Mike Stump1eb44332009-09-09 15:08:12 +00001647
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001648 class BadRelease : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001649 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001650 BadRelease() : CFRefBug("Bad release") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001651
Jordy Rose35c86952011-08-24 05:47:39 +00001652 const char *getDescription() const {
Ted Kremenekbb206fd2009-10-01 17:31:50 +00001653 return "Incorrect decrement of the reference count of an object that is "
1654 "not owned at this point by the caller";
Ted Kremenekc887d132009-04-29 18:50:19 +00001655 }
1656 };
Mike Stump1eb44332009-09-09 15:08:12 +00001657
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001658 class DeallocGC : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001659 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001660 DeallocGC()
1661 : CFRefBug("-dealloc called while using garbage collection") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001662
Ted Kremenekc887d132009-04-29 18:50:19 +00001663 const char *getDescription() const {
Ted Kremenek369de562009-05-09 00:10:05 +00001664 return "-dealloc called while using garbage collection";
Ted Kremenekc887d132009-04-29 18:50:19 +00001665 }
1666 };
Mike Stump1eb44332009-09-09 15:08:12 +00001667
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001668 class DeallocNotOwned : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001669 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001670 DeallocNotOwned()
1671 : CFRefBug("-dealloc sent to non-exclusively owned object") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001672
Ted Kremenekc887d132009-04-29 18:50:19 +00001673 const char *getDescription() const {
1674 return "-dealloc sent to object that may be referenced elsewhere";
1675 }
Mike Stump1eb44332009-09-09 15:08:12 +00001676 };
1677
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001678 class OverAutorelease : public CFRefBug {
Ted Kremenek369de562009-05-09 00:10:05 +00001679 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001680 OverAutorelease()
1681 : CFRefBug("Object sent -autorelease too many times") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001682
Ted Kremenek369de562009-05-09 00:10:05 +00001683 const char *getDescription() const {
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001684 return "Object sent -autorelease too many times";
Ted Kremenek369de562009-05-09 00:10:05 +00001685 }
1686 };
Mike Stump1eb44332009-09-09 15:08:12 +00001687
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001688 class ReturnedNotOwnedForOwned : public CFRefBug {
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001689 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001690 ReturnedNotOwnedForOwned()
1691 : CFRefBug("Method should return an owned object") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001692
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001693 const char *getDescription() const {
Jordy Rose5b5402b2011-07-15 22:17:54 +00001694 return "Object with a +0 retain count returned to caller where a +1 "
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001695 "(owning) retain count is expected";
1696 }
1697 };
Mike Stump1eb44332009-09-09 15:08:12 +00001698
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001699 class Leak : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001700 const bool isReturn;
1701 protected:
Jordy Rose35c86952011-08-24 05:47:39 +00001702 Leak(StringRef name, bool isRet)
Jordy Rosedb92bb62011-08-25 01:14:38 +00001703 : CFRefBug(name), isReturn(isRet) {
1704 // Leaks should not be reported if they are post-dominated by a sink.
1705 setSuppressOnSink(true);
1706 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001707 public:
Mike Stump1eb44332009-09-09 15:08:12 +00001708
Jordy Rose35c86952011-08-24 05:47:39 +00001709 const char *getDescription() const { return ""; }
Mike Stump1eb44332009-09-09 15:08:12 +00001710
Ted Kremenekc887d132009-04-29 18:50:19 +00001711 bool isLeak() const { return true; }
1712 };
Mike Stump1eb44332009-09-09 15:08:12 +00001713
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001714 class LeakAtReturn : public Leak {
Ted Kremenekc887d132009-04-29 18:50:19 +00001715 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001716 LeakAtReturn(StringRef name)
1717 : Leak(name, true) {}
Ted Kremenekc887d132009-04-29 18:50:19 +00001718 };
Mike Stump1eb44332009-09-09 15:08:12 +00001719
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001720 class LeakWithinFunction : public Leak {
Ted Kremenekc887d132009-04-29 18:50:19 +00001721 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001722 LeakWithinFunction(StringRef name)
1723 : Leak(name, false) {}
Mike Stump1eb44332009-09-09 15:08:12 +00001724 };
1725
Ted Kremenekc887d132009-04-29 18:50:19 +00001726 //===---------===//
1727 // Bug Reports. //
1728 //===---------===//
Mike Stump1eb44332009-09-09 15:08:12 +00001729
Jordy Rose01153492012-03-24 02:45:35 +00001730 class CFRefReportVisitor : public BugReporterVisitorImpl<CFRefReportVisitor> {
Anna Zaks23f395e2011-08-20 01:27:22 +00001731 protected:
Anna Zaksdc757b02011-08-19 23:21:56 +00001732 SymbolRef Sym;
Jordy Roseec9ef852011-08-23 20:55:48 +00001733 const SummaryLogTy &SummaryLog;
Jordy Rose35c86952011-08-24 05:47:39 +00001734 bool GCEnabled;
Anna Zaks23f395e2011-08-20 01:27:22 +00001735
Anna Zaksdc757b02011-08-19 23:21:56 +00001736 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001737 CFRefReportVisitor(SymbolRef sym, bool gcEnabled, const SummaryLogTy &log)
1738 : Sym(sym), SummaryLog(log), GCEnabled(gcEnabled) {}
Anna Zaksdc757b02011-08-19 23:21:56 +00001739
Anna Zaks23f395e2011-08-20 01:27:22 +00001740 virtual void Profile(llvm::FoldingSetNodeID &ID) const {
Anna Zaksdc757b02011-08-19 23:21:56 +00001741 static int x = 0;
1742 ID.AddPointer(&x);
1743 ID.AddPointer(Sym);
1744 }
1745
Anna Zaks23f395e2011-08-20 01:27:22 +00001746 virtual PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
1747 const ExplodedNode *PrevN,
1748 BugReporterContext &BRC,
1749 BugReport &BR);
1750
1751 virtual PathDiagnosticPiece *getEndPath(BugReporterContext &BRC,
1752 const ExplodedNode *N,
1753 BugReport &BR);
1754 };
1755
1756 class CFRefLeakReportVisitor : public CFRefReportVisitor {
1757 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001758 CFRefLeakReportVisitor(SymbolRef sym, bool GCEnabled,
Jordy Roseec9ef852011-08-23 20:55:48 +00001759 const SummaryLogTy &log)
Jordy Rose35c86952011-08-24 05:47:39 +00001760 : CFRefReportVisitor(sym, GCEnabled, log) {}
Anna Zaks23f395e2011-08-20 01:27:22 +00001761
1762 PathDiagnosticPiece *getEndPath(BugReporterContext &BRC,
1763 const ExplodedNode *N,
1764 BugReport &BR);
Jordy Rose01153492012-03-24 02:45:35 +00001765
1766 virtual BugReporterVisitor *clone() const {
1767 // The curiously-recurring template pattern only works for one level of
1768 // subclassing. Rather than make a new template base for
1769 // CFRefReportVisitor, we simply override clone() to do the right thing.
1770 // This could be trouble someday if BugReporterVisitorImpl is ever
1771 // used for something else besides a convenient implementation of clone().
1772 return new CFRefLeakReportVisitor(*this);
1773 }
Anna Zaksdc757b02011-08-19 23:21:56 +00001774 };
1775
Anna Zakse172e8b2011-08-17 23:00:25 +00001776 class CFRefReport : public BugReport {
Jordy Rose20589562011-08-24 22:39:09 +00001777 void addGCModeDescription(const LangOptions &LOpts, bool GCEnabled);
Jordy Rose35c86952011-08-24 05:47:39 +00001778
Ted Kremenekc887d132009-04-29 18:50:19 +00001779 public:
Jordy Rose20589562011-08-24 22:39:09 +00001780 CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1781 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1782 bool registerVisitor = true)
Anna Zaksedf4dae2011-08-22 18:54:07 +00001783 : BugReport(D, D.getDescription(), n) {
Anna Zaks23f395e2011-08-20 01:27:22 +00001784 if (registerVisitor)
Jordy Rose20589562011-08-24 22:39:09 +00001785 addVisitor(new CFRefReportVisitor(sym, GCEnabled, Log));
1786 addGCModeDescription(LOpts, GCEnabled);
Anna Zaksdc757b02011-08-19 23:21:56 +00001787 }
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001788
Jordy Rose20589562011-08-24 22:39:09 +00001789 CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1790 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1791 StringRef endText)
Anna Zaksedf4dae2011-08-22 18:54:07 +00001792 : BugReport(D, D.getDescription(), endText, n) {
Jordy Rose20589562011-08-24 22:39:09 +00001793 addVisitor(new CFRefReportVisitor(sym, GCEnabled, Log));
1794 addGCModeDescription(LOpts, GCEnabled);
Anna Zaksdc757b02011-08-19 23:21:56 +00001795 }
Mike Stump1eb44332009-09-09 15:08:12 +00001796
Anna Zakse172e8b2011-08-17 23:00:25 +00001797 virtual std::pair<ranges_iterator, ranges_iterator> getRanges() {
Anna Zaksedf4dae2011-08-22 18:54:07 +00001798 const CFRefBug& BugTy = static_cast<CFRefBug&>(getBugType());
1799 if (!BugTy.isLeak())
Anna Zakse172e8b2011-08-17 23:00:25 +00001800 return BugReport::getRanges();
Ted Kremenekc887d132009-04-29 18:50:19 +00001801 else
Argyrios Kyrtzidis640ccf02010-12-04 01:12:15 +00001802 return std::make_pair(ranges_iterator(), ranges_iterator());
Ted Kremenekc887d132009-04-29 18:50:19 +00001803 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001804 };
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001805
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001806 class CFRefLeakReport : public CFRefReport {
Ted Kremenekc887d132009-04-29 18:50:19 +00001807 const MemRegion* AllocBinding;
Anna Zaks23f395e2011-08-20 01:27:22 +00001808
Ted Kremenekc887d132009-04-29 18:50:19 +00001809 public:
Jordy Rose20589562011-08-24 22:39:09 +00001810 CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1811 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
Anna Zaks6a93bd52011-10-25 19:57:11 +00001812 CheckerContext &Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001813
Anna Zaks590dd8e2011-09-20 21:38:35 +00001814 PathDiagnosticLocation getLocation(const SourceManager &SM) const {
1815 assert(Location.isValid());
1816 return Location;
1817 }
Mike Stump1eb44332009-09-09 15:08:12 +00001818 };
Ted Kremenekc887d132009-04-29 18:50:19 +00001819} // end anonymous namespace
1820
Jordy Rose20589562011-08-24 22:39:09 +00001821void CFRefReport::addGCModeDescription(const LangOptions &LOpts,
1822 bool GCEnabled) {
Jordy Rosef95b19d2011-08-24 20:38:42 +00001823 const char *GCModeDescription = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001824
Douglas Gregore289d812011-09-13 17:21:33 +00001825 switch (LOpts.getGC()) {
Anna Zaks7f2531c2011-08-22 20:31:28 +00001826 case LangOptions::GCOnly:
Jordy Rose20589562011-08-24 22:39:09 +00001827 assert(GCEnabled);
Jordy Rose35c86952011-08-24 05:47:39 +00001828 GCModeDescription = "Code is compiled to only use garbage collection";
1829 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001830
Anna Zaks7f2531c2011-08-22 20:31:28 +00001831 case LangOptions::NonGC:
Jordy Rose20589562011-08-24 22:39:09 +00001832 assert(!GCEnabled);
Jordy Rose35c86952011-08-24 05:47:39 +00001833 GCModeDescription = "Code is compiled to use reference counts";
1834 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001835
Anna Zaks7f2531c2011-08-22 20:31:28 +00001836 case LangOptions::HybridGC:
Jordy Rose20589562011-08-24 22:39:09 +00001837 if (GCEnabled) {
Jordy Rose35c86952011-08-24 05:47:39 +00001838 GCModeDescription = "Code is compiled to use either garbage collection "
1839 "(GC) or reference counts (non-GC). The bug occurs "
1840 "with GC enabled";
1841 break;
1842 } else {
1843 GCModeDescription = "Code is compiled to use either garbage collection "
1844 "(GC) or reference counts (non-GC). The bug occurs "
1845 "in non-GC mode";
1846 break;
Anna Zaks7f2531c2011-08-22 20:31:28 +00001847 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001848 }
Jordy Rose35c86952011-08-24 05:47:39 +00001849
Jordy Rosef95b19d2011-08-24 20:38:42 +00001850 assert(GCModeDescription && "invalid/unknown GC mode");
Jordy Rose35c86952011-08-24 05:47:39 +00001851 addExtraText(GCModeDescription);
Ted Kremenekc887d132009-04-29 18:50:19 +00001852}
1853
Jordy Rose910c4052011-09-02 06:44:22 +00001854// FIXME: This should be a method on SmallVector.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001855static inline bool contains(const SmallVectorImpl<ArgEffect>& V,
Ted Kremenekc887d132009-04-29 18:50:19 +00001856 ArgEffect X) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001857 for (SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
Ted Kremenekc887d132009-04-29 18:50:19 +00001858 I!=E; ++I)
1859 if (*I == X) return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001860
Ted Kremenekc887d132009-04-29 18:50:19 +00001861 return false;
1862}
1863
Ted Kremenek4c42bb72011-11-14 21:59:21 +00001864static bool isPropertyAccess(const Stmt *S, ParentMap &PM) {
1865 unsigned maxDepth = 4;
1866 while (S && maxDepth) {
1867 if (const PseudoObjectExpr *PO = dyn_cast<PseudoObjectExpr>(S)) {
1868 if (!isa<ObjCMessageExpr>(PO->getSyntacticForm()))
1869 return true;
1870 return false;
1871 }
1872 S = PM.getParent(S);
1873 --maxDepth;
1874 }
1875 return false;
1876}
1877
Anna Zaksdc757b02011-08-19 23:21:56 +00001878PathDiagnosticPiece *CFRefReportVisitor::VisitNode(const ExplodedNode *N,
1879 const ExplodedNode *PrevN,
1880 BugReporterContext &BRC,
1881 BugReport &BR) {
Mike Stump1eb44332009-09-09 15:08:12 +00001882
Jordy Rosef53e8c72011-08-23 19:43:16 +00001883 if (!isa<StmtPoint>(N->getLocation()))
Ted Kremenek2033a952009-05-13 07:12:33 +00001884 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001885
Ted Kremenek8966bc12009-05-06 21:39:49 +00001886 // Check if the type state has changed.
Ted Kremenek8bef8232012-01-26 21:29:00 +00001887 ProgramStateRef PrevSt = PrevN->getState();
1888 ProgramStateRef CurrSt = N->getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001889 const LocationContext *LCtx = N->getLocationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00001890
1891 const RefVal* CurrT = CurrSt->get<RefBindings>(Sym);
Ted Kremenekc887d132009-04-29 18:50:19 +00001892 if (!CurrT) return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001893
Ted Kremenekb65be702009-06-18 01:23:53 +00001894 const RefVal &CurrV = *CurrT;
1895 const RefVal *PrevT = PrevSt->get<RefBindings>(Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00001896
Ted Kremenekc887d132009-04-29 18:50:19 +00001897 // Create a string buffer to constain all the useful things we want
1898 // to tell the user.
1899 std::string sbuf;
1900 llvm::raw_string_ostream os(sbuf);
Mike Stump1eb44332009-09-09 15:08:12 +00001901
Ted Kremenekc887d132009-04-29 18:50:19 +00001902 // This is the allocation site since the previous node had no bindings
1903 // for this symbol.
1904 if (!PrevT) {
Jordy Rosef53e8c72011-08-23 19:43:16 +00001905 const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
Mike Stump1eb44332009-09-09 15:08:12 +00001906
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001907 if (isa<ObjCArrayLiteral>(S)) {
1908 os << "NSArray literal is an object with a +0 retain count";
Mike Stump1eb44332009-09-09 15:08:12 +00001909 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001910 else if (isa<ObjCDictionaryLiteral>(S)) {
1911 os << "NSDictionary literal is an object with a +0 retain count";
Ted Kremenekc887d132009-04-29 18:50:19 +00001912 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001913 else {
1914 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
1915 // Get the name of the callee (if it is available).
1916 SVal X = CurrSt->getSValAsScalarOrLoc(CE->getCallee(), LCtx);
1917 if (const FunctionDecl *FD = X.getAsFunctionDecl())
1918 os << "Call to function '" << *FD << '\'';
1919 else
1920 os << "function call";
Ted Kremenekc887d132009-04-29 18:50:19 +00001921 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001922 else {
1923 assert(isa<ObjCMessageExpr>(S));
1924 // The message expression may have between written directly or as
1925 // a property access. Lazily determine which case we are looking at.
1926 os << (isPropertyAccess(S, N->getParentMap()) ? "Property" : "Method");
1927 }
1928
1929 if (CurrV.getObjKind() == RetEffect::CF) {
1930 os << " returns a Core Foundation object with a ";
1931 }
1932 else {
1933 assert (CurrV.getObjKind() == RetEffect::ObjC);
1934 os << " returns an Objective-C object with a ";
1935 }
1936
1937 if (CurrV.isOwned()) {
1938 os << "+1 retain count";
1939
1940 if (GCEnabled) {
1941 assert(CurrV.getObjKind() == RetEffect::CF);
1942 os << ". "
1943 "Core Foundation objects are not automatically garbage collected.";
1944 }
1945 }
1946 else {
1947 assert (CurrV.isNotOwned());
1948 os << "+0 retain count";
1949 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001950 }
Mike Stump1eb44332009-09-09 15:08:12 +00001951
Anna Zaks220ac8c2011-09-15 01:08:34 +00001952 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
1953 N->getLocationContext());
Ted Kremenekc887d132009-04-29 18:50:19 +00001954 return new PathDiagnosticEventPiece(Pos, os.str());
1955 }
Mike Stump1eb44332009-09-09 15:08:12 +00001956
Ted Kremenekc887d132009-04-29 18:50:19 +00001957 // Gather up the effects that were performed on the object at this
1958 // program point
Chris Lattner5f9e2722011-07-23 10:55:15 +00001959 SmallVector<ArgEffect, 2> AEffects;
Mike Stump1eb44332009-09-09 15:08:12 +00001960
Jordy Roseec9ef852011-08-23 20:55:48 +00001961 const ExplodedNode *OrigNode = BRC.getNodeResolver().getOriginalNode(N);
1962 if (const RetainSummary *Summ = SummaryLog.lookup(OrigNode)) {
Ted Kremenekc887d132009-04-29 18:50:19 +00001963 // We only have summaries attached to nodes after evaluating CallExpr and
1964 // ObjCMessageExprs.
Jordy Rosef53e8c72011-08-23 19:43:16 +00001965 const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
Mike Stump1eb44332009-09-09 15:08:12 +00001966
Ted Kremenek5f85e172009-07-22 22:35:28 +00001967 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
Ted Kremenekc887d132009-04-29 18:50:19 +00001968 // Iterate through the parameter expressions and see if the symbol
1969 // was ever passed as an argument.
1970 unsigned i = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001971
Ted Kremenek5f85e172009-07-22 22:35:28 +00001972 for (CallExpr::const_arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
Ted Kremenekc887d132009-04-29 18:50:19 +00001973 AI!=AE; ++AI, ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00001974
Ted Kremenekc887d132009-04-29 18:50:19 +00001975 // Retrieve the value of the argument. Is it the symbol
1976 // we are interested in?
Ted Kremenek5eca4822012-01-06 22:09:28 +00001977 if (CurrSt->getSValAsScalarOrLoc(*AI, LCtx).getAsLocSymbol() != Sym)
Ted Kremenekc887d132009-04-29 18:50:19 +00001978 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001979
Ted Kremenekc887d132009-04-29 18:50:19 +00001980 // We have an argument. Get the effect!
1981 AEffects.push_back(Summ->getArg(i));
1982 }
1983 }
Mike Stump1eb44332009-09-09 15:08:12 +00001984 else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00001985 if (const Expr *receiver = ME->getInstanceReceiver())
Ted Kremenek5eca4822012-01-06 22:09:28 +00001986 if (CurrSt->getSValAsScalarOrLoc(receiver, LCtx)
1987 .getAsLocSymbol() == Sym) {
Ted Kremenekc887d132009-04-29 18:50:19 +00001988 // The symbol we are tracking is the receiver.
1989 AEffects.push_back(Summ->getReceiverEffect());
1990 }
1991 }
1992 }
Mike Stump1eb44332009-09-09 15:08:12 +00001993
Ted Kremenekc887d132009-04-29 18:50:19 +00001994 do {
1995 // Get the previous type state.
1996 RefVal PrevV = *PrevT;
Mike Stump1eb44332009-09-09 15:08:12 +00001997
Ted Kremenekc887d132009-04-29 18:50:19 +00001998 // Specially handle -dealloc.
Jordy Rose35c86952011-08-24 05:47:39 +00001999 if (!GCEnabled && contains(AEffects, Dealloc)) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002000 // Determine if the object's reference count was pushed to zero.
2001 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2002 // We may not have transitioned to 'release' if we hit an error.
2003 // This case is handled elsewhere.
2004 if (CurrV.getKind() == RefVal::Released) {
Ted Kremenekf21332e2009-05-08 20:01:42 +00002005 assert(CurrV.getCombinedCounts() == 0);
Ted Kremenekc887d132009-04-29 18:50:19 +00002006 os << "Object released by directly sending the '-dealloc' message";
2007 break;
2008 }
2009 }
Mike Stump1eb44332009-09-09 15:08:12 +00002010
Ted Kremenekc887d132009-04-29 18:50:19 +00002011 // Specially handle CFMakeCollectable and friends.
2012 if (contains(AEffects, MakeCollectable)) {
2013 // Get the name of the function.
Jordy Rosef53e8c72011-08-23 19:43:16 +00002014 const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
Ted Kremenek5eca4822012-01-06 22:09:28 +00002015 SVal X =
2016 CurrSt->getSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee(), LCtx);
Ted Kremenek9c378f72011-08-12 23:37:29 +00002017 const FunctionDecl *FD = X.getAsFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002018
Jordy Rose35c86952011-08-24 05:47:39 +00002019 if (GCEnabled) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002020 // Determine if the object's reference count was pushed to zero.
2021 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
Mike Stump1eb44332009-09-09 15:08:12 +00002022
Benjamin Kramerb8989f22011-10-14 18:45:37 +00002023 os << "In GC mode a call to '" << *FD
Ted Kremenekc887d132009-04-29 18:50:19 +00002024 << "' decrements an object's retain count and registers the "
2025 "object with the garbage collector. ";
Mike Stump1eb44332009-09-09 15:08:12 +00002026
Ted Kremenekc887d132009-04-29 18:50:19 +00002027 if (CurrV.getKind() == RefVal::Released) {
2028 assert(CurrV.getCount() == 0);
2029 os << "Since it now has a 0 retain count the object can be "
2030 "automatically collected by the garbage collector.";
2031 }
2032 else
2033 os << "An object must have a 0 retain count to be garbage collected. "
2034 "After this call its retain count is +" << CurrV.getCount()
2035 << '.';
2036 }
Mike Stump1eb44332009-09-09 15:08:12 +00002037 else
Benjamin Kramerb8989f22011-10-14 18:45:37 +00002038 os << "When GC is not enabled a call to '" << *FD
Ted Kremenekc887d132009-04-29 18:50:19 +00002039 << "' has no effect on its argument.";
Mike Stump1eb44332009-09-09 15:08:12 +00002040
Ted Kremenekc887d132009-04-29 18:50:19 +00002041 // Nothing more to say.
2042 break;
2043 }
Mike Stump1eb44332009-09-09 15:08:12 +00002044
2045 // Determine if the typestate has changed.
Ted Kremenekc887d132009-04-29 18:50:19 +00002046 if (!(PrevV == CurrV))
2047 switch (CurrV.getKind()) {
2048 case RefVal::Owned:
2049 case RefVal::NotOwned:
Mike Stump1eb44332009-09-09 15:08:12 +00002050
Ted Kremenekf21332e2009-05-08 20:01:42 +00002051 if (PrevV.getCount() == CurrV.getCount()) {
2052 // Did an autorelease message get sent?
2053 if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
2054 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002055
Zhongxing Xu264e9372009-05-12 10:10:00 +00002056 assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount());
Ted Kremenekeaedfea2009-05-10 05:11:21 +00002057 os << "Object sent -autorelease message";
Ted Kremenekf21332e2009-05-08 20:01:42 +00002058 break;
2059 }
Mike Stump1eb44332009-09-09 15:08:12 +00002060
Ted Kremenekc887d132009-04-29 18:50:19 +00002061 if (PrevV.getCount() > CurrV.getCount())
2062 os << "Reference count decremented.";
2063 else
2064 os << "Reference count incremented.";
Mike Stump1eb44332009-09-09 15:08:12 +00002065
Ted Kremenekc887d132009-04-29 18:50:19 +00002066 if (unsigned Count = CurrV.getCount())
2067 os << " The object now has a +" << Count << " retain count.";
Mike Stump1eb44332009-09-09 15:08:12 +00002068
Ted Kremenekc887d132009-04-29 18:50:19 +00002069 if (PrevV.getKind() == RefVal::Released) {
Jordy Rose35c86952011-08-24 05:47:39 +00002070 assert(GCEnabled && CurrV.getCount() > 0);
Jordy Rose74b7b2b2012-03-17 05:49:15 +00002071 os << " The object is not eligible for garbage collection until "
2072 "the retain count reaches 0 again.";
Ted Kremenekc887d132009-04-29 18:50:19 +00002073 }
Mike Stump1eb44332009-09-09 15:08:12 +00002074
Ted Kremenekc887d132009-04-29 18:50:19 +00002075 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002076
Ted Kremenekc887d132009-04-29 18:50:19 +00002077 case RefVal::Released:
2078 os << "Object released.";
2079 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002080
Ted Kremenekc887d132009-04-29 18:50:19 +00002081 case RefVal::ReturnedOwned:
Jordy Rose74b7b2b2012-03-17 05:49:15 +00002082 // Autoreleases can be applied after marking a node ReturnedOwned.
2083 if (CurrV.getAutoreleaseCount())
2084 return NULL;
2085
2086 os << "Object returned to caller as an owning reference (single "
2087 "retain count transferred to caller)";
Ted Kremenekc887d132009-04-29 18:50:19 +00002088 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002089
Ted Kremenekc887d132009-04-29 18:50:19 +00002090 case RefVal::ReturnedNotOwned:
Ted Kremenekf1365462011-05-26 18:45:44 +00002091 os << "Object returned to caller with a +0 retain count";
Ted Kremenekc887d132009-04-29 18:50:19 +00002092 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002093
Ted Kremenekc887d132009-04-29 18:50:19 +00002094 default:
2095 return NULL;
2096 }
Mike Stump1eb44332009-09-09 15:08:12 +00002097
Ted Kremenekc887d132009-04-29 18:50:19 +00002098 // Emit any remaining diagnostics for the argument effects (if any).
Chris Lattner5f9e2722011-07-23 10:55:15 +00002099 for (SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
Ted Kremenekc887d132009-04-29 18:50:19 +00002100 E=AEffects.end(); I != E; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +00002101
Ted Kremenekc887d132009-04-29 18:50:19 +00002102 // A bunch of things have alternate behavior under GC.
Jordy Rose35c86952011-08-24 05:47:39 +00002103 if (GCEnabled)
Ted Kremenekc887d132009-04-29 18:50:19 +00002104 switch (*I) {
2105 default: break;
2106 case Autorelease:
2107 os << "In GC mode an 'autorelease' has no effect.";
2108 continue;
2109 case IncRefMsg:
2110 os << "In GC mode the 'retain' message has no effect.";
2111 continue;
2112 case DecRefMsg:
2113 os << "In GC mode the 'release' message has no effect.";
2114 continue;
2115 }
2116 }
Mike Stump1eb44332009-09-09 15:08:12 +00002117 } while (0);
2118
Ted Kremenekc887d132009-04-29 18:50:19 +00002119 if (os.str().empty())
2120 return 0; // We have nothing to say!
Ted Kremenek2033a952009-05-13 07:12:33 +00002121
Jordy Rosef53e8c72011-08-23 19:43:16 +00002122 const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
Anna Zaks220ac8c2011-09-15 01:08:34 +00002123 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
2124 N->getLocationContext());
Ted Kremenek9c378f72011-08-12 23:37:29 +00002125 PathDiagnosticPiece *P = new PathDiagnosticEventPiece(Pos, os.str());
Mike Stump1eb44332009-09-09 15:08:12 +00002126
Ted Kremenekc887d132009-04-29 18:50:19 +00002127 // Add the range by scanning the children of the statement for any bindings
2128 // to Sym.
Mike Stump1eb44332009-09-09 15:08:12 +00002129 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
Ted Kremenek5f85e172009-07-22 22:35:28 +00002130 I!=E; ++I)
Ted Kremenek9c378f72011-08-12 23:37:29 +00002131 if (const Expr *Exp = dyn_cast_or_null<Expr>(*I))
Ted Kremenek5eca4822012-01-06 22:09:28 +00002132 if (CurrSt->getSValAsScalarOrLoc(Exp, LCtx).getAsLocSymbol() == Sym) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002133 P->addRange(Exp->getSourceRange());
2134 break;
2135 }
Mike Stump1eb44332009-09-09 15:08:12 +00002136
Ted Kremenekc887d132009-04-29 18:50:19 +00002137 return P;
2138}
2139
Anna Zakse7e01682012-02-28 22:39:22 +00002140// Find the first node in the current function context that referred to the
2141// tracked symbol and the memory location that value was stored to. Note, the
2142// value is only reported if the allocation occurred in the same function as
2143// the leak.
Zhongxing Xuc5619d92009-08-06 01:32:16 +00002144static std::pair<const ExplodedNode*,const MemRegion*>
Ted Kremenek18c66fd2011-08-15 22:09:50 +00002145GetAllocationSite(ProgramStateManager& StateMgr, const ExplodedNode *N,
Ted Kremenekc887d132009-04-29 18:50:19 +00002146 SymbolRef Sym) {
Ted Kremenek9c378f72011-08-12 23:37:29 +00002147 const ExplodedNode *Last = N;
Mike Stump1eb44332009-09-09 15:08:12 +00002148 const MemRegion* FirstBinding = 0;
Anna Zakse7e01682012-02-28 22:39:22 +00002149 const LocationContext *LeakContext = N->getLocationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002150
Ted Kremenekc887d132009-04-29 18:50:19 +00002151 while (N) {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002152 ProgramStateRef St = N->getState();
Ted Kremenekc887d132009-04-29 18:50:19 +00002153 RefBindings B = St->get<RefBindings>();
Mike Stump1eb44332009-09-09 15:08:12 +00002154
Ted Kremenekc887d132009-04-29 18:50:19 +00002155 if (!B.lookup(Sym))
2156 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002157
Anna Zaks27b867e2012-03-21 19:45:01 +00002158 StoreManager::FindUniqueBinding FB(Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002159 StateMgr.iterBindings(St, FB);
2160 if (FB) FirstBinding = FB.getRegion();
2161
Anna Zakse7e01682012-02-28 22:39:22 +00002162 // Allocation node, is the last node in the current context in which the
2163 // symbol was tracked.
2164 if (N->getLocationContext() == LeakContext)
2165 Last = N;
2166
Mike Stump1eb44332009-09-09 15:08:12 +00002167 N = N->pred_empty() ? NULL : *(N->pred_begin());
Ted Kremenekc887d132009-04-29 18:50:19 +00002168 }
Mike Stump1eb44332009-09-09 15:08:12 +00002169
Anna Zakse7e01682012-02-28 22:39:22 +00002170 // If allocation happened in a function different from the leak node context,
2171 // do not report the binding.
2172 if (N->getLocationContext() != LeakContext) {
2173 FirstBinding = 0;
2174 }
2175
Ted Kremenekc887d132009-04-29 18:50:19 +00002176 return std::make_pair(Last, FirstBinding);
2177}
2178
2179PathDiagnosticPiece*
Anna Zaks23f395e2011-08-20 01:27:22 +00002180CFRefReportVisitor::getEndPath(BugReporterContext &BRC,
2181 const ExplodedNode *EndN,
2182 BugReport &BR) {
Ted Kremenek76aadc32012-03-09 01:13:14 +00002183 BR.markInteresting(Sym);
Anna Zaks23f395e2011-08-20 01:27:22 +00002184 return BugReporterVisitor::getDefaultEndPath(BRC, EndN, BR);
Ted Kremenekc887d132009-04-29 18:50:19 +00002185}
2186
2187PathDiagnosticPiece*
Anna Zaks23f395e2011-08-20 01:27:22 +00002188CFRefLeakReportVisitor::getEndPath(BugReporterContext &BRC,
2189 const ExplodedNode *EndN,
2190 BugReport &BR) {
Mike Stump1eb44332009-09-09 15:08:12 +00002191
Ted Kremenek8966bc12009-05-06 21:39:49 +00002192 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenekc887d132009-04-29 18:50:19 +00002193 // assigned to different variables, etc.
Ted Kremenek76aadc32012-03-09 01:13:14 +00002194 BR.markInteresting(Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002195
Ted Kremenekc887d132009-04-29 18:50:19 +00002196 // We are reporting a leak. Walk up the graph to get to the first node where
2197 // the symbol appeared, and also get the first VarDecl that tracked object
2198 // is stored to.
Ted Kremenek9c378f72011-08-12 23:37:29 +00002199 const ExplodedNode *AllocNode = 0;
Ted Kremenekc887d132009-04-29 18:50:19 +00002200 const MemRegion* FirstBinding = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002201
Ted Kremenekc887d132009-04-29 18:50:19 +00002202 llvm::tie(AllocNode, FirstBinding) =
Ted Kremenekf04dced2009-05-08 23:32:51 +00002203 GetAllocationSite(BRC.getStateManager(), EndN, Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002204
Anna Zaks4fdf97b2011-09-15 18:56:07 +00002205 SourceManager& SM = BRC.getSourceManager();
Mike Stump1eb44332009-09-09 15:08:12 +00002206
Ted Kremenekc887d132009-04-29 18:50:19 +00002207 // Compute an actual location for the leak. Sometimes a leak doesn't
2208 // occur at an actual statement (e.g., transition between blocks; end
2209 // of function) so we need to walk the graph and compute a real location.
Ted Kremenek9c378f72011-08-12 23:37:29 +00002210 const ExplodedNode *LeakN = EndN;
Anna Zaks4fdf97b2011-09-15 18:56:07 +00002211 PathDiagnosticLocation L = PathDiagnosticLocation::createEndOfPath(LeakN, SM);
Mike Stump1eb44332009-09-09 15:08:12 +00002212
Ted Kremenekc887d132009-04-29 18:50:19 +00002213 std::string sbuf;
2214 llvm::raw_string_ostream os(sbuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002215
Ted Kremenekf1365462011-05-26 18:45:44 +00002216 os << "Object leaked: ";
Mike Stump1eb44332009-09-09 15:08:12 +00002217
Ted Kremenekf1365462011-05-26 18:45:44 +00002218 if (FirstBinding) {
2219 os << "object allocated and stored into '"
2220 << FirstBinding->getString() << '\'';
2221 }
2222 else
2223 os << "allocated object";
Mike Stump1eb44332009-09-09 15:08:12 +00002224
Ted Kremenekc887d132009-04-29 18:50:19 +00002225 // Get the retain count.
2226 const RefVal* RV = EndN->getState()->get<RefBindings>(Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002227
Ted Kremenekc887d132009-04-29 18:50:19 +00002228 if (RV->getKind() == RefVal::ErrorLeakReturned) {
2229 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
Jordy Rose5b5402b2011-07-15 22:17:54 +00002230 // objects. Only "copy", "alloc", "retain" and "new" transfer ownership
Ted Kremenekc887d132009-04-29 18:50:19 +00002231 // to the caller for NS objects.
Ted Kremenekd368d712011-05-25 06:19:45 +00002232 const Decl *D = &EndN->getCodeDecl();
2233 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2234 os << " is returned from a method whose name ('"
2235 << MD->getSelector().getAsString()
2236 << "') does not start with 'copy', 'mutableCopy', 'alloc' or 'new'."
Jordy Rose5b5402b2011-07-15 22:17:54 +00002237 " This violates the naming convention rules"
Ted Kremenekf1365462011-05-26 18:45:44 +00002238 " given in the Memory Management Guide for Cocoa";
Ted Kremenekd368d712011-05-25 06:19:45 +00002239 }
2240 else {
2241 const FunctionDecl *FD = cast<FunctionDecl>(D);
Ted Kremenekb7dcddf2011-12-22 06:35:52 +00002242 os << " is returned from a function whose name ('"
Benjamin Kramera59d20b2012-02-07 11:57:57 +00002243 << *FD
Ted Kremenekd368d712011-05-25 06:19:45 +00002244 << "') does not contain 'Copy' or 'Create'. This violates the naming"
Ted Kremenekb7dcddf2011-12-22 06:35:52 +00002245 " convention rules given in the Memory Management Guide for Core"
Ted Kremenekf1365462011-05-26 18:45:44 +00002246 " Foundation";
Ted Kremenekd368d712011-05-25 06:19:45 +00002247 }
Ted Kremenekc887d132009-04-29 18:50:19 +00002248 }
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002249 else if (RV->getKind() == RefVal::ErrorGCLeakReturned) {
Ted Kremenek9c378f72011-08-12 23:37:29 +00002250 ObjCMethodDecl &MD = cast<ObjCMethodDecl>(EndN->getCodeDecl());
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002251 os << " and returned from method '" << MD.getSelector().getAsString()
Ted Kremenek82f2be52009-05-10 16:52:15 +00002252 << "' is potentially leaked when using garbage collection. Callers "
2253 "of this method do not expect a returned object with a +1 retain "
2254 "count since they expect the object to be managed by the garbage "
2255 "collector";
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002256 }
Ted Kremenekc887d132009-04-29 18:50:19 +00002257 else
Ted Kremenekabf517c2010-10-15 22:50:23 +00002258 os << " is not referenced later in this execution path and has a retain "
Ted Kremenekf1365462011-05-26 18:45:44 +00002259 "count of +" << RV->getCount();
Mike Stump1eb44332009-09-09 15:08:12 +00002260
Ted Kremenekc887d132009-04-29 18:50:19 +00002261 return new PathDiagnosticEventPiece(L, os.str());
2262}
2263
Jordy Rose20589562011-08-24 22:39:09 +00002264CFRefLeakReport::CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts,
2265 bool GCEnabled, const SummaryLogTy &Log,
2266 ExplodedNode *n, SymbolRef sym,
Anna Zaks6a93bd52011-10-25 19:57:11 +00002267 CheckerContext &Ctx)
Jordy Rose20589562011-08-24 22:39:09 +00002268: CFRefReport(D, LOpts, GCEnabled, Log, n, sym, false) {
Mike Stump1eb44332009-09-09 15:08:12 +00002269
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00002270 // Most bug reports are cached at the location where they occurred.
Ted Kremenekc887d132009-04-29 18:50:19 +00002271 // With leaks, we want to unique them by the location where they were
2272 // allocated, and only report a single path. To do this, we need to find
2273 // the allocation site of a piece of tracked memory, which we do via a
2274 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2275 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2276 // that all ancestor nodes that represent the allocation site have the
2277 // same SourceLocation.
Ted Kremenek9c378f72011-08-12 23:37:29 +00002278 const ExplodedNode *AllocNode = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002279
Anna Zaks6a93bd52011-10-25 19:57:11 +00002280 const SourceManager& SMgr = Ctx.getSourceManager();
Anna Zaks590dd8e2011-09-20 21:38:35 +00002281
Ted Kremenekc887d132009-04-29 18:50:19 +00002282 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding.
Anna Zaks6a93bd52011-10-25 19:57:11 +00002283 GetAllocationSite(Ctx.getStateManager(), getErrorNode(), sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002284
Ted Kremenekc887d132009-04-29 18:50:19 +00002285 // Get the SourceLocation for the allocation site.
2286 ProgramPoint P = AllocNode->getLocation();
Anna Zaks590dd8e2011-09-20 21:38:35 +00002287 const Stmt *AllocStmt = cast<PostStmt>(P).getStmt();
2288 Location = PathDiagnosticLocation::createBegin(AllocStmt, SMgr,
2289 n->getLocationContext());
Ted Kremenekc887d132009-04-29 18:50:19 +00002290 // Fill in the description of the bug.
2291 Description.clear();
2292 llvm::raw_string_ostream os(Description);
Ted Kremenekdd924e22009-05-02 19:05:19 +00002293 os << "Potential leak ";
Jordy Rose20589562011-08-24 22:39:09 +00002294 if (GCEnabled)
Ted Kremenekdd924e22009-05-02 19:05:19 +00002295 os << "(when using garbage collection) ";
Anna Zaks212000e2012-02-28 21:49:08 +00002296 os << "of an object";
Mike Stump1eb44332009-09-09 15:08:12 +00002297
Ted Kremenekc887d132009-04-29 18:50:19 +00002298 // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2299 if (AllocBinding)
Anna Zaks212000e2012-02-28 21:49:08 +00002300 os << " stored into '" << AllocBinding->getString() << '\'';
Anna Zaksdc757b02011-08-19 23:21:56 +00002301
Jordy Rose20589562011-08-24 22:39:09 +00002302 addVisitor(new CFRefLeakReportVisitor(sym, GCEnabled, Log));
Ted Kremenekc887d132009-04-29 18:50:19 +00002303}
2304
2305//===----------------------------------------------------------------------===//
2306// Main checker logic.
2307//===----------------------------------------------------------------------===//
2308
Ted Kremenekd593eb92009-11-25 22:17:44 +00002309namespace {
Jordy Rose910c4052011-09-02 06:44:22 +00002310class RetainCountChecker
Jordy Rose9c083b72011-08-24 18:56:32 +00002311 : public Checker< check::Bind,
Jordy Rose38f17d62011-08-23 19:01:07 +00002312 check::DeadSymbols,
Jordy Rose9c083b72011-08-24 18:56:32 +00002313 check::EndAnalysis,
Jordy Rose38f17d62011-08-23 19:01:07 +00002314 check::EndPath,
Jordy Rose67044292011-08-17 21:27:39 +00002315 check::PostStmt<BlockExpr>,
John McCallf85e1932011-06-15 23:02:42 +00002316 check::PostStmt<CastExpr>,
Jordy Rose294396b2011-08-22 23:48:23 +00002317 check::PostStmt<CallExpr>,
Jordy Rose537716a2011-08-27 22:51:26 +00002318 check::PostStmt<CXXConstructExpr>,
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002319 check::PostStmt<ObjCArrayLiteral>,
2320 check::PostStmt<ObjCDictionaryLiteral>,
Jordy Rose294396b2011-08-22 23:48:23 +00002321 check::PostObjCMessage,
Jordy Rosef53e8c72011-08-23 19:43:16 +00002322 check::PreStmt<ReturnStmt>,
Jordy Rose67044292011-08-17 21:27:39 +00002323 check::RegionChanges,
Jordy Rose76c506f2011-08-21 21:58:18 +00002324 eval::Assume,
2325 eval::Call > {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002326 mutable OwningPtr<CFRefBug> useAfterRelease, releaseNotOwned;
2327 mutable OwningPtr<CFRefBug> deallocGC, deallocNotOwned;
2328 mutable OwningPtr<CFRefBug> overAutorelease, returnNotOwnedForOwned;
2329 mutable OwningPtr<CFRefBug> leakWithinFunction, leakAtReturn;
2330 mutable OwningPtr<CFRefBug> leakWithinFunctionGC, leakAtReturnGC;
Jordy Rose38f17d62011-08-23 19:01:07 +00002331
2332 typedef llvm::DenseMap<SymbolRef, const SimpleProgramPointTag *> SymbolTagMap;
2333
2334 // This map is only used to ensure proper deletion of any allocated tags.
2335 mutable SymbolTagMap DeadSymbolTags;
2336
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002337 mutable OwningPtr<RetainSummaryManager> Summaries;
2338 mutable OwningPtr<RetainSummaryManager> SummariesGC;
Jordy Roseb6cfc092011-08-25 00:10:37 +00002339
Jordy Rosee0a5d322011-08-23 20:27:16 +00002340 mutable ARCounts::Factory ARCountFactory;
2341
Jordy Rose9c083b72011-08-24 18:56:32 +00002342 mutable SummaryLogTy SummaryLog;
2343 mutable bool ShouldResetSummaryLog;
2344
Jordy Rose2f9a66d2011-08-20 21:17:59 +00002345public:
Jordy Rose910c4052011-09-02 06:44:22 +00002346 RetainCountChecker() : ShouldResetSummaryLog(false) {}
Jordy Rose38f17d62011-08-23 19:01:07 +00002347
Jordy Rose910c4052011-09-02 06:44:22 +00002348 virtual ~RetainCountChecker() {
Jordy Rose38f17d62011-08-23 19:01:07 +00002349 DeleteContainerSeconds(DeadSymbolTags);
2350 }
2351
Jordy Rose9c083b72011-08-24 18:56:32 +00002352 void checkEndAnalysis(ExplodedGraph &G, BugReporter &BR,
2353 ExprEngine &Eng) const {
2354 // FIXME: This is a hack to make sure the summary log gets cleared between
2355 // analyses of different code bodies.
2356 //
2357 // Why is this necessary? Because a checker's lifetime is tied to a
2358 // translation unit, but an ExplodedGraph's lifetime is just a code body.
2359 // Once in a blue moon, a new ExplodedNode will have the same address as an
2360 // old one with an associated summary, and the bug report visitor gets very
2361 // confused. (To make things worse, the summary lifetime is currently also
2362 // tied to a code body, so we get a crash instead of incorrect results.)
Jordy Rose1ab51c72011-08-24 09:27:24 +00002363 //
2364 // Why is this a bad solution? Because if the lifetime of the ExplodedGraph
2365 // changes, things will start going wrong again. Really the lifetime of this
2366 // log needs to be tied to either the specific nodes in it or the entire
2367 // ExplodedGraph, not to a specific part of the code being analyzed.
2368 //
Jordy Rose9c083b72011-08-24 18:56:32 +00002369 // (Also, having stateful local data means that the same checker can't be
2370 // used from multiple threads, but a lot of checkers have incorrect
2371 // assumptions about that anyway. So that wasn't a priority at the time of
2372 // this fix.)
Jordy Rose1ab51c72011-08-24 09:27:24 +00002373 //
Jordy Rose9c083b72011-08-24 18:56:32 +00002374 // This happens at the end of analysis, but bug reports are emitted /after/
2375 // this point. So we can't just clear the summary log now. Instead, we mark
2376 // that the next time we access the summary log, it should be cleared.
2377
2378 // If we never reset the summary log during /this/ code body analysis,
2379 // there were no new summaries. There might still have been summaries from
2380 // the /last/ analysis, so clear them out to make sure the bug report
2381 // visitors don't get confused.
2382 if (ShouldResetSummaryLog)
2383 SummaryLog.clear();
2384
2385 ShouldResetSummaryLog = !SummaryLog.empty();
Jordy Rose1ab51c72011-08-24 09:27:24 +00002386 }
2387
Jordy Rose17a38e22011-09-02 05:55:19 +00002388 CFRefBug *getLeakWithinFunctionBug(const LangOptions &LOpts,
2389 bool GCEnabled) const {
2390 if (GCEnabled) {
Jordy Rosedb92bb62011-08-25 01:14:38 +00002391 if (!leakWithinFunctionGC)
2392 leakWithinFunctionGC.reset(new LeakWithinFunction("Leak of object when "
2393 "using garbage "
2394 "collection"));
Jordy Rose17a38e22011-09-02 05:55:19 +00002395 return leakWithinFunctionGC.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002396 } else {
2397 if (!leakWithinFunction) {
Douglas Gregore289d812011-09-13 17:21:33 +00002398 if (LOpts.getGC() == LangOptions::HybridGC) {
Jordy Rosedb92bb62011-08-25 01:14:38 +00002399 leakWithinFunction.reset(new LeakWithinFunction("Leak of object when "
2400 "not using garbage "
2401 "collection (GC) in "
2402 "dual GC/non-GC "
2403 "code"));
2404 } else {
2405 leakWithinFunction.reset(new LeakWithinFunction("Leak"));
2406 }
2407 }
Jordy Rose17a38e22011-09-02 05:55:19 +00002408 return leakWithinFunction.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002409 }
2410 }
2411
Jordy Rose17a38e22011-09-02 05:55:19 +00002412 CFRefBug *getLeakAtReturnBug(const LangOptions &LOpts, bool GCEnabled) const {
2413 if (GCEnabled) {
Jordy Rosedb92bb62011-08-25 01:14:38 +00002414 if (!leakAtReturnGC)
2415 leakAtReturnGC.reset(new LeakAtReturn("Leak of returned object when "
2416 "using garbage collection"));
Jordy Rose17a38e22011-09-02 05:55:19 +00002417 return leakAtReturnGC.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002418 } else {
2419 if (!leakAtReturn) {
Douglas Gregore289d812011-09-13 17:21:33 +00002420 if (LOpts.getGC() == LangOptions::HybridGC) {
Jordy Rosedb92bb62011-08-25 01:14:38 +00002421 leakAtReturn.reset(new LeakAtReturn("Leak of returned object when "
2422 "not using garbage collection "
2423 "(GC) in dual GC/non-GC code"));
2424 } else {
2425 leakAtReturn.reset(new LeakAtReturn("Leak of returned object"));
2426 }
2427 }
Jordy Rose17a38e22011-09-02 05:55:19 +00002428 return leakAtReturn.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002429 }
2430 }
2431
Jordy Rose17a38e22011-09-02 05:55:19 +00002432 RetainSummaryManager &getSummaryManager(ASTContext &Ctx,
2433 bool GCEnabled) const {
2434 // FIXME: We don't support ARC being turned on and off during one analysis.
2435 // (nor, for that matter, do we support changing ASTContexts)
David Blaikie4e4d0842012-03-11 07:00:24 +00002436 bool ARCEnabled = (bool)Ctx.getLangOpts().ObjCAutoRefCount;
Jordy Rose17a38e22011-09-02 05:55:19 +00002437 if (GCEnabled) {
2438 if (!SummariesGC)
Jordy Roseb6cfc092011-08-25 00:10:37 +00002439 SummariesGC.reset(new RetainSummaryManager(Ctx, true, ARCEnabled));
Jordy Rose17a38e22011-09-02 05:55:19 +00002440 else
2441 assert(SummariesGC->isARCEnabled() == ARCEnabled);
Jordy Roseb6cfc092011-08-25 00:10:37 +00002442 return *SummariesGC;
2443 } else {
Jordy Rose17a38e22011-09-02 05:55:19 +00002444 if (!Summaries)
Jordy Roseb6cfc092011-08-25 00:10:37 +00002445 Summaries.reset(new RetainSummaryManager(Ctx, false, ARCEnabled));
Jordy Rose17a38e22011-09-02 05:55:19 +00002446 else
2447 assert(Summaries->isARCEnabled() == ARCEnabled);
Jordy Roseb6cfc092011-08-25 00:10:37 +00002448 return *Summaries;
2449 }
2450 }
2451
Jordy Rose17a38e22011-09-02 05:55:19 +00002452 RetainSummaryManager &getSummaryManager(CheckerContext &C) const {
2453 return getSummaryManager(C.getASTContext(), C.isObjCGCEnabled());
2454 }
2455
Ted Kremenek8bef8232012-01-26 21:29:00 +00002456 void printState(raw_ostream &Out, ProgramStateRef State,
Jordy Rosedbd658e2011-08-28 19:11:56 +00002457 const char *NL, const char *Sep) const;
2458
Anna Zaks390909c2011-10-06 00:43:15 +00002459 void checkBind(SVal loc, SVal val, const Stmt *S, CheckerContext &C) const;
Jordy Roseab027fd2011-08-20 21:16:58 +00002460 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
2461 void checkPostStmt(const CastExpr *CE, CheckerContext &C) const;
John McCallf85e1932011-06-15 23:02:42 +00002462
Jordy Rose294396b2011-08-22 23:48:23 +00002463 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
Jordy Rose537716a2011-08-27 22:51:26 +00002464 void checkPostStmt(const CXXConstructExpr *CE, CheckerContext &C) const;
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002465 void checkPostStmt(const ObjCArrayLiteral *AL, CheckerContext &C) const;
2466 void checkPostStmt(const ObjCDictionaryLiteral *DL, CheckerContext &C) const;
Jordy Rose294396b2011-08-22 23:48:23 +00002467 void checkPostObjCMessage(const ObjCMessage &Msg, CheckerContext &C) const;
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002468
Jordy Rose294396b2011-08-22 23:48:23 +00002469 void checkSummary(const RetainSummary &Summ, const CallOrObjCMessage &Call,
Jordy Rosee38dd952011-08-28 05:16:28 +00002470 CheckerContext &C) const;
Jordy Rose294396b2011-08-22 23:48:23 +00002471
Jordy Rose76c506f2011-08-21 21:58:18 +00002472 bool evalCall(const CallExpr *CE, CheckerContext &C) const;
2473
Ted Kremenek8bef8232012-01-26 21:29:00 +00002474 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Jordy Roseab027fd2011-08-20 21:16:58 +00002475 bool Assumption) const;
Jordy Rose67044292011-08-17 21:27:39 +00002476
Ted Kremenek8bef8232012-01-26 21:29:00 +00002477 ProgramStateRef
2478 checkRegionChanges(ProgramStateRef state,
Jordy Rose537716a2011-08-27 22:51:26 +00002479 const StoreManager::InvalidatedSymbols *invalidated,
2480 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00002481 ArrayRef<const MemRegion *> Regions,
2482 const CallOrObjCMessage *Call) const;
Jordy Roseab027fd2011-08-20 21:16:58 +00002483
Ted Kremenek8bef8232012-01-26 21:29:00 +00002484 bool wantsRegionChangeUpdate(ProgramStateRef state) const {
Jordy Rose2f9a66d2011-08-20 21:17:59 +00002485 return true;
Jordy Roseab027fd2011-08-20 21:16:58 +00002486 }
Jordy Rose294396b2011-08-22 23:48:23 +00002487
Jordy Rosef53e8c72011-08-23 19:43:16 +00002488 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
2489 void checkReturnWithRetEffect(const ReturnStmt *S, CheckerContext &C,
2490 ExplodedNode *Pred, RetEffect RE, RefVal X,
Ted Kremenek8bef8232012-01-26 21:29:00 +00002491 SymbolRef Sym, ProgramStateRef state) const;
Jordy Rosef53e8c72011-08-23 19:43:16 +00002492
Jordy Rose38f17d62011-08-23 19:01:07 +00002493 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Anna Zaksaf498a22011-10-25 19:56:48 +00002494 void checkEndPath(CheckerContext &C) const;
Jordy Rose38f17d62011-08-23 19:01:07 +00002495
Ted Kremenek8bef8232012-01-26 21:29:00 +00002496 ProgramStateRef updateSymbol(ProgramStateRef state, SymbolRef sym,
Jordy Rose17a38e22011-09-02 05:55:19 +00002497 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
2498 CheckerContext &C) const;
Jordy Rosee0a5d322011-08-23 20:27:16 +00002499
Ted Kremenek8bef8232012-01-26 21:29:00 +00002500 void processNonLeakError(ProgramStateRef St, SourceRange ErrorRange,
Jordy Rose294396b2011-08-22 23:48:23 +00002501 RefVal::Kind ErrorKind, SymbolRef Sym,
2502 CheckerContext &C) const;
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002503
2504 void processObjCLiterals(CheckerContext &C, const Expr *Ex) const;
Jordy Rose294396b2011-08-22 23:48:23 +00002505
Jordy Rose38f17d62011-08-23 19:01:07 +00002506 const ProgramPointTag *getDeadSymbolTag(SymbolRef sym) const;
2507
Ted Kremenek8bef8232012-01-26 21:29:00 +00002508 ProgramStateRef handleSymbolDeath(ProgramStateRef state,
Jordy Rose38f17d62011-08-23 19:01:07 +00002509 SymbolRef sid, RefVal V,
2510 SmallVectorImpl<SymbolRef> &Leaked) const;
2511
Ted Kremenek8bef8232012-01-26 21:29:00 +00002512 std::pair<ExplodedNode *, ProgramStateRef >
2513 handleAutoreleaseCounts(ProgramStateRef state,
Jordy Rose8d228632011-08-23 20:07:14 +00002514 GenericNodeBuilderRefCount Bd, ExplodedNode *Pred,
Anna Zaks6a93bd52011-10-25 19:57:11 +00002515 CheckerContext &Ctx, SymbolRef Sym, RefVal V) const;
Jordy Rose8d228632011-08-23 20:07:14 +00002516
Ted Kremenek8bef8232012-01-26 21:29:00 +00002517 ExplodedNode *processLeaks(ProgramStateRef state,
Jordy Rose38f17d62011-08-23 19:01:07 +00002518 SmallVectorImpl<SymbolRef> &Leaked,
2519 GenericNodeBuilderRefCount &Builder,
Anna Zaks6a93bd52011-10-25 19:57:11 +00002520 CheckerContext &Ctx,
Jordy Rose38f17d62011-08-23 19:01:07 +00002521 ExplodedNode *Pred = 0) const;
Ted Kremenekd593eb92009-11-25 22:17:44 +00002522};
2523} // end anonymous namespace
2524
Jordy Rose67044292011-08-17 21:27:39 +00002525namespace {
2526class StopTrackingCallback : public SymbolVisitor {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002527 ProgramStateRef state;
Jordy Rose67044292011-08-17 21:27:39 +00002528public:
Ted Kremenek8bef8232012-01-26 21:29:00 +00002529 StopTrackingCallback(ProgramStateRef st) : state(st) {}
2530 ProgramStateRef getState() const { return state; }
Jordy Rose67044292011-08-17 21:27:39 +00002531
2532 bool VisitSymbol(SymbolRef sym) {
2533 state = state->remove<RefBindings>(sym);
2534 return true;
2535 }
2536};
2537} // end anonymous namespace
2538
Jordy Rose910c4052011-09-02 06:44:22 +00002539//===----------------------------------------------------------------------===//
2540// Handle statements that may have an effect on refcounts.
2541//===----------------------------------------------------------------------===//
Jordy Rose67044292011-08-17 21:27:39 +00002542
Jordy Rose910c4052011-09-02 06:44:22 +00002543void RetainCountChecker::checkPostStmt(const BlockExpr *BE,
2544 CheckerContext &C) const {
Jordy Rose67044292011-08-17 21:27:39 +00002545
Jordy Rose910c4052011-09-02 06:44:22 +00002546 // Scan the BlockDecRefExprs for any object the retain count checker
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002547 // may be tracking.
John McCall469a1eb2011-02-02 13:00:07 +00002548 if (!BE->getBlockDecl()->hasCaptures())
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002549 return;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002550
Ted Kremenek8bef8232012-01-26 21:29:00 +00002551 ProgramStateRef state = C.getState();
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002552 const BlockDataRegion *R =
Ted Kremenek5eca4822012-01-06 22:09:28 +00002553 cast<BlockDataRegion>(state->getSVal(BE,
2554 C.getLocationContext()).getAsRegion());
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002555
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002556 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
2557 E = R->referenced_vars_end();
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002558
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002559 if (I == E)
2560 return;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002561
Ted Kremenek67d12872009-12-07 22:05:27 +00002562 // FIXME: For now we invalidate the tracking of all symbols passed to blocks
2563 // via captured variables, even though captured variables result in a copy
2564 // and in implicit increment/decrement of a retain count.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002565 SmallVector<const MemRegion*, 10> Regions;
Anna Zaks39ac1872011-10-26 21:06:44 +00002566 const LocationContext *LC = C.getLocationContext();
Ted Kremenekc8413fd2010-12-02 07:49:45 +00002567 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002568
Ted Kremenek67d12872009-12-07 22:05:27 +00002569 for ( ; I != E; ++I) {
2570 const VarRegion *VR = *I;
2571 if (VR->getSuperRegion() == R) {
2572 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2573 }
2574 Regions.push_back(VR);
2575 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002576
Ted Kremenek67d12872009-12-07 22:05:27 +00002577 state =
2578 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
2579 Regions.data() + Regions.size()).getState();
Anna Zaks0bd6b112011-10-26 21:06:34 +00002580 C.addTransition(state);
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002581}
2582
Jordy Rose910c4052011-09-02 06:44:22 +00002583void RetainCountChecker::checkPostStmt(const CastExpr *CE,
2584 CheckerContext &C) const {
John McCallf85e1932011-06-15 23:02:42 +00002585 const ObjCBridgedCastExpr *BE = dyn_cast<ObjCBridgedCastExpr>(CE);
2586 if (!BE)
2587 return;
2588
John McCall71c482c2011-06-17 06:50:50 +00002589 ArgEffect AE = IncRef;
John McCallf85e1932011-06-15 23:02:42 +00002590
2591 switch (BE->getBridgeKind()) {
2592 case clang::OBC_Bridge:
2593 // Do nothing.
2594 return;
2595 case clang::OBC_BridgeRetained:
2596 AE = IncRef;
2597 break;
2598 case clang::OBC_BridgeTransfer:
2599 AE = DecRefBridgedTransfered;
2600 break;
2601 }
2602
Ted Kremenek8bef8232012-01-26 21:29:00 +00002603 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00002604 SymbolRef Sym = state->getSVal(CE, C.getLocationContext()).getAsLocSymbol();
John McCallf85e1932011-06-15 23:02:42 +00002605 if (!Sym)
2606 return;
2607 const RefVal* T = state->get<RefBindings>(Sym);
2608 if (!T)
2609 return;
2610
John McCallf85e1932011-06-15 23:02:42 +00002611 RefVal::Kind hasErr = (RefVal::Kind) 0;
Jordy Rose17a38e22011-09-02 05:55:19 +00002612 state = updateSymbol(state, Sym, *T, AE, hasErr, C);
John McCallf85e1932011-06-15 23:02:42 +00002613
2614 if (hasErr) {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002615 // FIXME: If we get an error during a bridge cast, should we report it?
2616 // Should we assert that there is no error?
John McCallf85e1932011-06-15 23:02:42 +00002617 return;
2618 }
2619
Anna Zaks0bd6b112011-10-26 21:06:34 +00002620 C.addTransition(state);
John McCallf85e1932011-06-15 23:02:42 +00002621}
2622
Jordy Rose910c4052011-09-02 06:44:22 +00002623void RetainCountChecker::checkPostStmt(const CallExpr *CE,
2624 CheckerContext &C) const {
Ted Kremenek514f2c92012-03-23 06:26:56 +00002625 if (C.wasInlined)
2626 return;
2627
Jordy Rose294396b2011-08-22 23:48:23 +00002628 // Get the callee.
Ted Kremenek8bef8232012-01-26 21:29:00 +00002629 ProgramStateRef state = C.getState();
Jordy Rose294396b2011-08-22 23:48:23 +00002630 const Expr *Callee = CE->getCallee();
Ted Kremenek5eca4822012-01-06 22:09:28 +00002631 SVal L = state->getSVal(Callee, C.getLocationContext());
Jordy Rose294396b2011-08-22 23:48:23 +00002632
Jordy Rose17a38e22011-09-02 05:55:19 +00002633 RetainSummaryManager &Summaries = getSummaryManager(C);
Ted Kremenek93edbc52011-10-05 23:54:29 +00002634 const RetainSummary *Summ = 0;
Jordy Rose294396b2011-08-22 23:48:23 +00002635
2636 // FIXME: Better support for blocks. For now we stop tracking anything
2637 // that is passed to blocks.
2638 // FIXME: Need to handle variables that are "captured" by the block.
2639 if (dyn_cast_or_null<BlockDataRegion>(L.getAsRegion())) {
2640 Summ = Summaries.getPersistentStopSummary();
2641 } else if (const FunctionDecl *FD = L.getAsFunctionDecl()) {
Anna Zaks58822c42012-05-04 22:18:39 +00002642 CallOrObjCMessage CME(CE, state, C.getLocationContext());
2643 Summ = Summaries.getSummary(FD, &CME);
Jordy Rose294396b2011-08-22 23:48:23 +00002644 } else if (const CXXMemberCallExpr *me = dyn_cast<CXXMemberCallExpr>(CE)) {
Anna Zaks58822c42012-05-04 22:18:39 +00002645 if (const CXXMethodDecl *MD = me->getMethodDecl()) {
2646 CallOrObjCMessage CME(CE, state, C.getLocationContext());
2647 Summ = Summaries.getSummary(MD, &CME);
2648 }
Jordy Rose294396b2011-08-22 23:48:23 +00002649 }
2650
Jordy Rose294396b2011-08-22 23:48:23 +00002651 if (!Summ)
Ted Kremenek93edbc52011-10-05 23:54:29 +00002652 Summ = Summaries.getDefaultSummary();
Jordy Rose294396b2011-08-22 23:48:23 +00002653
Ted Kremenek5eca4822012-01-06 22:09:28 +00002654 checkSummary(*Summ, CallOrObjCMessage(CE, state, C.getLocationContext()), C);
Jordy Rose294396b2011-08-22 23:48:23 +00002655}
2656
Jordy Rose910c4052011-09-02 06:44:22 +00002657void RetainCountChecker::checkPostStmt(const CXXConstructExpr *CE,
2658 CheckerContext &C) const {
Jordy Rose537716a2011-08-27 22:51:26 +00002659 const CXXConstructorDecl *Ctor = CE->getConstructor();
2660 if (!Ctor)
2661 return;
2662
Jordy Rose17a38e22011-09-02 05:55:19 +00002663 RetainSummaryManager &Summaries = getSummaryManager(C);
Anna Zaks58822c42012-05-04 22:18:39 +00002664 ProgramStateRef state = C.getState();
2665 CallOrObjCMessage CME(CE, state, C.getLocationContext());
2666 const RetainSummary *Summ = Summaries.getSummary(Ctor, &CME);
Jordy Rose537716a2011-08-27 22:51:26 +00002667
2668 // If we didn't get a summary, this constructor doesn't affect retain counts.
2669 if (!Summ)
2670 return;
2671
Ted Kremenek5eca4822012-01-06 22:09:28 +00002672 checkSummary(*Summ, CallOrObjCMessage(CE, state, C.getLocationContext()), C);
Jordy Rose537716a2011-08-27 22:51:26 +00002673}
2674
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002675void RetainCountChecker::processObjCLiterals(CheckerContext &C,
2676 const Expr *Ex) const {
2677 ProgramStateRef state = C.getState();
2678 const ExplodedNode *pred = C.getPredecessor();
2679 for (Stmt::const_child_iterator it = Ex->child_begin(), et = Ex->child_end() ;
2680 it != et ; ++it) {
2681 const Stmt *child = *it;
2682 SVal V = state->getSVal(child, pred->getLocationContext());
2683 if (SymbolRef sym = V.getAsSymbol())
2684 if (const RefVal* T = state->get<RefBindings>(sym)) {
2685 RefVal::Kind hasErr = (RefVal::Kind) 0;
2686 state = updateSymbol(state, sym, *T, MayEscape, hasErr, C);
2687 if (hasErr) {
2688 processNonLeakError(state, child->getSourceRange(), hasErr, sym, C);
2689 return;
2690 }
2691 }
2692 }
2693
2694 // Return the object as autoreleased.
2695 // RetEffect RE = RetEffect::MakeNotOwned(RetEffect::ObjC);
2696 if (SymbolRef sym =
2697 state->getSVal(Ex, pred->getLocationContext()).getAsSymbol()) {
2698 QualType ResultTy = Ex->getType();
2699 state = state->set<RefBindings>(sym, RefVal::makeNotOwned(RetEffect::ObjC,
2700 ResultTy));
2701 }
2702
2703 C.addTransition(state);
2704}
2705
2706void RetainCountChecker::checkPostStmt(const ObjCArrayLiteral *AL,
2707 CheckerContext &C) const {
2708 // Apply the 'MayEscape' to all values.
2709 processObjCLiterals(C, AL);
2710}
2711
2712void RetainCountChecker::checkPostStmt(const ObjCDictionaryLiteral *DL,
2713 CheckerContext &C) const {
2714 // Apply the 'MayEscape' to all keys and values.
2715 processObjCLiterals(C, DL);
2716}
2717
Jordy Rose910c4052011-09-02 06:44:22 +00002718void RetainCountChecker::checkPostObjCMessage(const ObjCMessage &Msg,
2719 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002720 ProgramStateRef state = C.getState();
Jordy Rose294396b2011-08-22 23:48:23 +00002721
Jordy Rose17a38e22011-09-02 05:55:19 +00002722 RetainSummaryManager &Summaries = getSummaryManager(C);
Jordy Roseb6cfc092011-08-25 00:10:37 +00002723
Ted Kremenek93edbc52011-10-05 23:54:29 +00002724 const RetainSummary *Summ;
Jordy Rose294396b2011-08-22 23:48:23 +00002725 if (Msg.isInstanceMessage()) {
Anna Zaksa2a86032011-11-01 22:41:01 +00002726 const LocationContext *LC = C.getLocationContext();
Jordy Rose294396b2011-08-22 23:48:23 +00002727 Summ = Summaries.getInstanceMethodSummary(Msg, state, LC);
2728 } else {
2729 Summ = Summaries.getClassMethodSummary(Msg);
2730 }
2731
2732 // If we didn't get a summary, this message doesn't affect retain counts.
2733 if (!Summ)
2734 return;
2735
Ted Kremenek5eca4822012-01-06 22:09:28 +00002736 checkSummary(*Summ, CallOrObjCMessage(Msg, state, C.getLocationContext()), C);
Jordy Rose294396b2011-08-22 23:48:23 +00002737}
2738
Jordy Rose910c4052011-09-02 06:44:22 +00002739/// GetReturnType - Used to get the return type of a message expression or
2740/// function call with the intention of affixing that type to a tracked symbol.
2741/// While the the return type can be queried directly from RetEx, when
2742/// invoking class methods we augment to the return type to be that of
2743/// a pointer to the class (as opposed it just being id).
2744// FIXME: We may be able to do this with related result types instead.
2745// This function is probably overestimating.
2746static QualType GetReturnType(const Expr *RetE, ASTContext &Ctx) {
2747 QualType RetTy = RetE->getType();
2748 // If RetE is not a message expression just return its type.
2749 // If RetE is a message expression, return its types if it is something
2750 /// more specific than id.
2751 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RetE))
2752 if (const ObjCObjectPointerType *PT = RetTy->getAs<ObjCObjectPointerType>())
2753 if (PT->isObjCQualifiedIdType() || PT->isObjCIdType() ||
2754 PT->isObjCClassType()) {
2755 // At this point we know the return type of the message expression is
2756 // id, id<...>, or Class. If we have an ObjCInterfaceDecl, we know this
2757 // is a call to a class method whose type we can resolve. In such
2758 // cases, promote the return type to XXX* (where XXX is the class).
2759 const ObjCInterfaceDecl *D = ME->getReceiverInterface();
2760 return !D ? RetTy :
2761 Ctx.getObjCObjectPointerType(Ctx.getObjCInterfaceType(D));
2762 }
2763
2764 return RetTy;
2765}
2766
2767void RetainCountChecker::checkSummary(const RetainSummary &Summ,
2768 const CallOrObjCMessage &CallOrMsg,
2769 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002770 ProgramStateRef state = C.getState();
Jordy Rose294396b2011-08-22 23:48:23 +00002771
2772 // Evaluate the effect of the arguments.
2773 RefVal::Kind hasErr = (RefVal::Kind) 0;
2774 SourceRange ErrorRange;
2775 SymbolRef ErrorSym = 0;
2776
2777 for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
Jordy Rose537716a2011-08-27 22:51:26 +00002778 SVal V = CallOrMsg.getArgSVal(idx);
Jordy Rose294396b2011-08-22 23:48:23 +00002779
2780 if (SymbolRef Sym = V.getAsLocSymbol()) {
2781 if (RefBindings::data_type *T = state->get<RefBindings>(Sym)) {
Jordy Rose17a38e22011-09-02 05:55:19 +00002782 state = updateSymbol(state, Sym, *T, Summ.getArg(idx), hasErr, C);
Jordy Rose294396b2011-08-22 23:48:23 +00002783 if (hasErr) {
2784 ErrorRange = CallOrMsg.getArgSourceRange(idx);
2785 ErrorSym = Sym;
2786 break;
2787 }
2788 }
2789 }
2790 }
2791
2792 // Evaluate the effect on the message receiver.
2793 bool ReceiverIsTracked = false;
Jordy Rosee38dd952011-08-28 05:16:28 +00002794 if (!hasErr && CallOrMsg.isObjCMessage()) {
Anna Zaks39ac1872011-10-26 21:06:44 +00002795 const LocationContext *LC = C.getLocationContext();
Jordy Rosee38dd952011-08-28 05:16:28 +00002796 SVal Receiver = CallOrMsg.getInstanceMessageReceiver(LC);
2797 if (SymbolRef Sym = Receiver.getAsLocSymbol()) {
Jordy Rose294396b2011-08-22 23:48:23 +00002798 if (const RefVal *T = state->get<RefBindings>(Sym)) {
2799 ReceiverIsTracked = true;
Jordy Rose17a38e22011-09-02 05:55:19 +00002800 state = updateSymbol(state, Sym, *T, Summ.getReceiverEffect(),
2801 hasErr, C);
Jordy Rose294396b2011-08-22 23:48:23 +00002802 if (hasErr) {
Jordy Rosee38dd952011-08-28 05:16:28 +00002803 ErrorRange = CallOrMsg.getReceiverSourceRange();
Jordy Rose294396b2011-08-22 23:48:23 +00002804 ErrorSym = Sym;
2805 }
2806 }
2807 }
2808 }
2809
2810 // Process any errors.
2811 if (hasErr) {
2812 processNonLeakError(state, ErrorRange, hasErr, ErrorSym, C);
2813 return;
2814 }
2815
2816 // Consult the summary for the return value.
2817 RetEffect RE = Summ.getRetEffect();
2818
2819 if (RE.getKind() == RetEffect::OwnedWhenTrackedReceiver) {
Jordy Roseb6cfc092011-08-25 00:10:37 +00002820 if (ReceiverIsTracked)
Jordy Rose17a38e22011-09-02 05:55:19 +00002821 RE = getSummaryManager(C).getObjAllocRetEffect();
Jordy Roseb6cfc092011-08-25 00:10:37 +00002822 else
Jordy Rose294396b2011-08-22 23:48:23 +00002823 RE = RetEffect::MakeNoRet();
2824 }
2825
2826 switch (RE.getKind()) {
2827 default:
David Blaikie7530c032012-01-17 06:56:22 +00002828 llvm_unreachable("Unhandled RetEffect.");
Jordy Rose294396b2011-08-22 23:48:23 +00002829
2830 case RetEffect::NoRet:
2831 // No work necessary.
2832 break;
2833
2834 case RetEffect::OwnedAllocatedSymbol:
2835 case RetEffect::OwnedSymbol: {
Ted Kremenek5eca4822012-01-06 22:09:28 +00002836 SymbolRef Sym = state->getSVal(CallOrMsg.getOriginExpr(),
2837 C.getLocationContext()).getAsSymbol();
Jordy Rose294396b2011-08-22 23:48:23 +00002838 if (!Sym)
2839 break;
2840
2841 // Use the result type from callOrMsg as it automatically adjusts
2842 // for methods/functions that return references.
2843 QualType ResultTy = CallOrMsg.getResultType(C.getASTContext());
2844 state = state->set<RefBindings>(Sym, RefVal::makeOwned(RE.getObjKind(),
2845 ResultTy));
2846
2847 // FIXME: Add a flag to the checker where allocations are assumed to
2848 // *not* fail. (The code below is out-of-date, though.)
2849#if 0
2850 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) {
2851 bool isFeasible;
2852 state = state.assume(loc::SymbolVal(Sym), true, isFeasible);
2853 assert(isFeasible && "Cannot assume fresh symbol is non-null.");
2854 }
2855#endif
2856
2857 break;
2858 }
2859
2860 case RetEffect::GCNotOwnedSymbol:
2861 case RetEffect::ARCNotOwnedSymbol:
2862 case RetEffect::NotOwnedSymbol: {
2863 const Expr *Ex = CallOrMsg.getOriginExpr();
Ted Kremenek5eca4822012-01-06 22:09:28 +00002864 SymbolRef Sym = state->getSVal(Ex, C.getLocationContext()).getAsSymbol();
Jordy Rose294396b2011-08-22 23:48:23 +00002865 if (!Sym)
2866 break;
2867
2868 // Use GetReturnType in order to give [NSFoo alloc] the type NSFoo *.
2869 QualType ResultTy = GetReturnType(Ex, C.getASTContext());
2870 state = state->set<RefBindings>(Sym, RefVal::makeNotOwned(RE.getObjKind(),
2871 ResultTy));
2872 break;
2873 }
2874 }
2875
2876 // This check is actually necessary; otherwise the statement builder thinks
2877 // we've hit a previously-found path.
2878 // Normally addTransition takes care of this, but we want the node pointer.
2879 ExplodedNode *NewNode;
2880 if (state == C.getState()) {
2881 NewNode = C.getPredecessor();
2882 } else {
Anna Zaks0bd6b112011-10-26 21:06:34 +00002883 NewNode = C.addTransition(state);
Jordy Rose294396b2011-08-22 23:48:23 +00002884 }
2885
Jordy Rose9c083b72011-08-24 18:56:32 +00002886 // Annotate the node with summary we used.
2887 if (NewNode) {
2888 // FIXME: This is ugly. See checkEndAnalysis for why it's necessary.
2889 if (ShouldResetSummaryLog) {
2890 SummaryLog.clear();
2891 ShouldResetSummaryLog = false;
2892 }
Jordy Roseec9ef852011-08-23 20:55:48 +00002893 SummaryLog[NewNode] = &Summ;
Jordy Rose9c083b72011-08-24 18:56:32 +00002894 }
Jordy Rose294396b2011-08-22 23:48:23 +00002895}
2896
Jordy Rosee0a5d322011-08-23 20:27:16 +00002897
Ted Kremenek8bef8232012-01-26 21:29:00 +00002898ProgramStateRef
2899RetainCountChecker::updateSymbol(ProgramStateRef state, SymbolRef sym,
Jordy Rose910c4052011-09-02 06:44:22 +00002900 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
2901 CheckerContext &C) const {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002902 // In GC mode [... release] and [... retain] do nothing.
Jordy Rose910c4052011-09-02 06:44:22 +00002903 // In ARC mode they shouldn't exist at all, but we just ignore them.
Jordy Rose17a38e22011-09-02 05:55:19 +00002904 bool IgnoreRetainMsg = C.isObjCGCEnabled();
2905 if (!IgnoreRetainMsg)
David Blaikie4e4d0842012-03-11 07:00:24 +00002906 IgnoreRetainMsg = (bool)C.getASTContext().getLangOpts().ObjCAutoRefCount;
Jordy Rose17a38e22011-09-02 05:55:19 +00002907
Jordy Rosee0a5d322011-08-23 20:27:16 +00002908 switch (E) {
2909 default: break;
Jordy Rose17a38e22011-09-02 05:55:19 +00002910 case IncRefMsg: E = IgnoreRetainMsg ? DoNothing : IncRef; break;
2911 case DecRefMsg: E = IgnoreRetainMsg ? DoNothing : DecRef; break;
2912 case MakeCollectable: E = C.isObjCGCEnabled() ? DecRef : DoNothing; break;
2913 case NewAutoreleasePool: E = C.isObjCGCEnabled() ? DoNothing :
2914 NewAutoreleasePool; break;
Jordy Rosee0a5d322011-08-23 20:27:16 +00002915 }
2916
2917 // Handle all use-after-releases.
Jordy Rose17a38e22011-09-02 05:55:19 +00002918 if (!C.isObjCGCEnabled() && V.getKind() == RefVal::Released) {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002919 V = V ^ RefVal::ErrorUseAfterRelease;
2920 hasErr = V.getKind();
2921 return state->set<RefBindings>(sym, V);
2922 }
2923
2924 switch (E) {
2925 case DecRefMsg:
2926 case IncRefMsg:
2927 case MakeCollectable:
2928 llvm_unreachable("DecRefMsg/IncRefMsg/MakeCollectable already converted");
Jordy Rosee0a5d322011-08-23 20:27:16 +00002929
2930 case Dealloc:
2931 // Any use of -dealloc in GC is *bad*.
Jordy Rose17a38e22011-09-02 05:55:19 +00002932 if (C.isObjCGCEnabled()) {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002933 V = V ^ RefVal::ErrorDeallocGC;
2934 hasErr = V.getKind();
2935 break;
2936 }
2937
2938 switch (V.getKind()) {
2939 default:
2940 llvm_unreachable("Invalid RefVal state for an explicit dealloc.");
Jordy Rosee0a5d322011-08-23 20:27:16 +00002941 case RefVal::Owned:
2942 // The object immediately transitions to the released state.
2943 V = V ^ RefVal::Released;
2944 V.clearCounts();
2945 return state->set<RefBindings>(sym, V);
2946 case RefVal::NotOwned:
2947 V = V ^ RefVal::ErrorDeallocNotOwned;
2948 hasErr = V.getKind();
2949 break;
2950 }
2951 break;
2952
2953 case NewAutoreleasePool:
Jordy Rose17a38e22011-09-02 05:55:19 +00002954 assert(!C.isObjCGCEnabled());
Jordy Rosee0a5d322011-08-23 20:27:16 +00002955 return state->add<AutoreleaseStack>(sym);
2956
2957 case MayEscape:
2958 if (V.getKind() == RefVal::Owned) {
2959 V = V ^ RefVal::NotOwned;
2960 break;
2961 }
2962
2963 // Fall-through.
2964
Jordy Rosee0a5d322011-08-23 20:27:16 +00002965 case DoNothing:
2966 return state;
2967
2968 case Autorelease:
Jordy Rose17a38e22011-09-02 05:55:19 +00002969 if (C.isObjCGCEnabled())
Jordy Rosee0a5d322011-08-23 20:27:16 +00002970 return state;
2971
2972 // Update the autorelease counts.
2973 state = SendAutorelease(state, ARCountFactory, sym);
2974 V = V.autorelease();
2975 break;
2976
2977 case StopTracking:
2978 return state->remove<RefBindings>(sym);
2979
2980 case IncRef:
2981 switch (V.getKind()) {
2982 default:
2983 llvm_unreachable("Invalid RefVal state for a retain.");
Jordy Rosee0a5d322011-08-23 20:27:16 +00002984 case RefVal::Owned:
2985 case RefVal::NotOwned:
2986 V = V + 1;
2987 break;
2988 case RefVal::Released:
2989 // Non-GC cases are handled above.
Jordy Rose17a38e22011-09-02 05:55:19 +00002990 assert(C.isObjCGCEnabled());
Jordy Rosee0a5d322011-08-23 20:27:16 +00002991 V = (V ^ RefVal::Owned) + 1;
2992 break;
2993 }
2994 break;
2995
2996 case SelfOwn:
2997 V = V ^ RefVal::NotOwned;
2998 // Fall-through.
2999 case DecRef:
3000 case DecRefBridgedTransfered:
3001 switch (V.getKind()) {
3002 default:
3003 // case 'RefVal::Released' handled above.
3004 llvm_unreachable("Invalid RefVal state for a release.");
Jordy Rosee0a5d322011-08-23 20:27:16 +00003005
3006 case RefVal::Owned:
3007 assert(V.getCount() > 0);
3008 if (V.getCount() == 1)
3009 V = V ^ (E == DecRefBridgedTransfered ?
3010 RefVal::NotOwned : RefVal::Released);
3011 V = V - 1;
3012 break;
3013
3014 case RefVal::NotOwned:
3015 if (V.getCount() > 0)
3016 V = V - 1;
3017 else {
3018 V = V ^ RefVal::ErrorReleaseNotOwned;
3019 hasErr = V.getKind();
3020 }
3021 break;
3022
3023 case RefVal::Released:
3024 // Non-GC cases are handled above.
Jordy Rose17a38e22011-09-02 05:55:19 +00003025 assert(C.isObjCGCEnabled());
Jordy Rosee0a5d322011-08-23 20:27:16 +00003026 V = V ^ RefVal::ErrorUseAfterRelease;
3027 hasErr = V.getKind();
3028 break;
3029 }
3030 break;
3031 }
3032 return state->set<RefBindings>(sym, V);
3033}
3034
Ted Kremenek8bef8232012-01-26 21:29:00 +00003035void RetainCountChecker::processNonLeakError(ProgramStateRef St,
Jordy Rose910c4052011-09-02 06:44:22 +00003036 SourceRange ErrorRange,
3037 RefVal::Kind ErrorKind,
3038 SymbolRef Sym,
3039 CheckerContext &C) const {
Jordy Rose294396b2011-08-22 23:48:23 +00003040 ExplodedNode *N = C.generateSink(St);
3041 if (!N)
3042 return;
3043
Jordy Rose294396b2011-08-22 23:48:23 +00003044 CFRefBug *BT;
3045 switch (ErrorKind) {
3046 default:
3047 llvm_unreachable("Unhandled error.");
Jordy Rose294396b2011-08-22 23:48:23 +00003048 case RefVal::ErrorUseAfterRelease:
Jordy Rosed6334e12011-08-25 00:34:03 +00003049 if (!useAfterRelease)
3050 useAfterRelease.reset(new UseAfterRelease());
3051 BT = &*useAfterRelease;
Jordy Rose294396b2011-08-22 23:48:23 +00003052 break;
3053 case RefVal::ErrorReleaseNotOwned:
Jordy Rosed6334e12011-08-25 00:34:03 +00003054 if (!releaseNotOwned)
3055 releaseNotOwned.reset(new BadRelease());
3056 BT = &*releaseNotOwned;
Jordy Rose294396b2011-08-22 23:48:23 +00003057 break;
3058 case RefVal::ErrorDeallocGC:
Jordy Rosed6334e12011-08-25 00:34:03 +00003059 if (!deallocGC)
3060 deallocGC.reset(new DeallocGC());
3061 BT = &*deallocGC;
Jordy Rose294396b2011-08-22 23:48:23 +00003062 break;
3063 case RefVal::ErrorDeallocNotOwned:
Jordy Rosed6334e12011-08-25 00:34:03 +00003064 if (!deallocNotOwned)
3065 deallocNotOwned.reset(new DeallocNotOwned());
3066 BT = &*deallocNotOwned;
Jordy Rose294396b2011-08-22 23:48:23 +00003067 break;
3068 }
3069
Jordy Rosed6334e12011-08-25 00:34:03 +00003070 assert(BT);
David Blaikie4e4d0842012-03-11 07:00:24 +00003071 CFRefReport *report = new CFRefReport(*BT, C.getASTContext().getLangOpts(),
Jordy Rose17a38e22011-09-02 05:55:19 +00003072 C.isObjCGCEnabled(), SummaryLog,
3073 N, Sym);
Jordy Rose294396b2011-08-22 23:48:23 +00003074 report->addRange(ErrorRange);
3075 C.EmitReport(report);
3076}
3077
Jordy Rose910c4052011-09-02 06:44:22 +00003078//===----------------------------------------------------------------------===//
3079// Handle the return values of retain-count-related functions.
3080//===----------------------------------------------------------------------===//
3081
3082bool RetainCountChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
Jordy Rose76c506f2011-08-21 21:58:18 +00003083 // Get the callee. We're only interested in simple C functions.
Ted Kremenek8bef8232012-01-26 21:29:00 +00003084 ProgramStateRef state = C.getState();
Anna Zaksb805c8f2011-12-01 05:57:37 +00003085 const FunctionDecl *FD = C.getCalleeDecl(CE);
Jordy Rose76c506f2011-08-21 21:58:18 +00003086 if (!FD)
3087 return false;
3088
3089 IdentifierInfo *II = FD->getIdentifier();
3090 if (!II)
3091 return false;
3092
3093 // For now, we're only handling the functions that return aliases of their
3094 // arguments: CFRetain and CFMakeCollectable (and their families).
3095 // Eventually we should add other functions we can model entirely,
3096 // such as CFRelease, which don't invalidate their arguments or globals.
3097 if (CE->getNumArgs() != 1)
3098 return false;
3099
3100 // Get the name of the function.
3101 StringRef FName = II->getName();
3102 FName = FName.substr(FName.find_first_not_of('_'));
3103
3104 // See if it's one of the specific functions we know how to eval.
3105 bool canEval = false;
3106
Anna Zaksb805c8f2011-12-01 05:57:37 +00003107 QualType ResultTy = CE->getCallReturnType();
Jordy Rose76c506f2011-08-21 21:58:18 +00003108 if (ResultTy->isObjCIdType()) {
3109 // Handle: id NSMakeCollectable(CFTypeRef)
3110 canEval = II->isStr("NSMakeCollectable");
3111 } else if (ResultTy->isPointerType()) {
3112 // Handle: (CF|CG)Retain
3113 // CFMakeCollectable
3114 // It's okay to be a little sloppy here (CGMakeCollectable doesn't exist).
3115 if (cocoa::isRefType(ResultTy, "CF", FName) ||
3116 cocoa::isRefType(ResultTy, "CG", FName)) {
3117 canEval = isRetain(FD, FName) || isMakeCollectable(FD, FName);
3118 }
3119 }
3120
3121 if (!canEval)
3122 return false;
3123
3124 // Bind the return value.
Ted Kremenek5eca4822012-01-06 22:09:28 +00003125 const LocationContext *LCtx = C.getLocationContext();
3126 SVal RetVal = state->getSVal(CE->getArg(0), LCtx);
Jordy Rose76c506f2011-08-21 21:58:18 +00003127 if (RetVal.isUnknown()) {
3128 // If the receiver is unknown, conjure a return value.
3129 SValBuilder &SVB = C.getSValBuilder();
Anna Zaks5d0ea6d2011-10-04 20:43:05 +00003130 unsigned Count = C.getCurrentBlockCount();
Ted Kremenek3133f792012-02-17 23:13:45 +00003131 SVal RetVal = SVB.getConjuredSymbolVal(0, CE, LCtx, ResultTy, Count);
Jordy Rose76c506f2011-08-21 21:58:18 +00003132 }
Ted Kremenek5eca4822012-01-06 22:09:28 +00003133 state = state->BindExpr(CE, LCtx, RetVal, false);
Jordy Rose76c506f2011-08-21 21:58:18 +00003134
Jordy Rose294396b2011-08-22 23:48:23 +00003135 // FIXME: This should not be necessary, but otherwise the argument seems to be
3136 // considered alive during the next statement.
3137 if (const MemRegion *ArgRegion = RetVal.getAsRegion()) {
3138 // Save the refcount status of the argument.
3139 SymbolRef Sym = RetVal.getAsLocSymbol();
3140 RefBindings::data_type *Binding = 0;
3141 if (Sym)
3142 Binding = state->get<RefBindings>(Sym);
Jordy Rose76c506f2011-08-21 21:58:18 +00003143
Jordy Rose294396b2011-08-22 23:48:23 +00003144 // Invalidate the argument region.
Anna Zaks5d0ea6d2011-10-04 20:43:05 +00003145 unsigned Count = C.getCurrentBlockCount();
Ted Kremenek3133f792012-02-17 23:13:45 +00003146 state = state->invalidateRegions(ArgRegion, CE, Count, LCtx);
Jordy Rose76c506f2011-08-21 21:58:18 +00003147
Jordy Rose294396b2011-08-22 23:48:23 +00003148 // Restore the refcount status of the argument.
3149 if (Binding)
3150 state = state->set<RefBindings>(Sym, *Binding);
3151 }
3152
Anna Zaks0bd6b112011-10-26 21:06:34 +00003153 C.addTransition(state);
Jordy Rose76c506f2011-08-21 21:58:18 +00003154 return true;
3155}
3156
Jordy Rose910c4052011-09-02 06:44:22 +00003157//===----------------------------------------------------------------------===//
3158// Handle return statements.
3159//===----------------------------------------------------------------------===//
Jordy Rosef53e8c72011-08-23 19:43:16 +00003160
Ted Kremeneke5715782012-02-25 02:09:09 +00003161// Return true if the current LocationContext has no caller context.
3162static bool inTopFrame(CheckerContext &C) {
3163 const LocationContext *LC = C.getLocationContext();
3164 return LC->getParent() == 0;
3165}
3166
Jordy Rose910c4052011-09-02 06:44:22 +00003167void RetainCountChecker::checkPreStmt(const ReturnStmt *S,
3168 CheckerContext &C) const {
Ted Kremeneke5715782012-02-25 02:09:09 +00003169
3170 // Only adjust the reference count if this is the top-level call frame,
3171 // and not the result of inlining. In the future, we should do
3172 // better checking even for inlined calls, and see if they match
3173 // with their expected semantics (e.g., the method should return a retained
3174 // object, etc.).
3175 if (!inTopFrame(C))
3176 return;
3177
Jordy Rosef53e8c72011-08-23 19:43:16 +00003178 const Expr *RetE = S->getRetValue();
3179 if (!RetE)
3180 return;
3181
Ted Kremenek8bef8232012-01-26 21:29:00 +00003182 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00003183 SymbolRef Sym =
3184 state->getSValAsScalarOrLoc(RetE, C.getLocationContext()).getAsLocSymbol();
Jordy Rosef53e8c72011-08-23 19:43:16 +00003185 if (!Sym)
3186 return;
3187
3188 // Get the reference count binding (if any).
3189 const RefVal *T = state->get<RefBindings>(Sym);
3190 if (!T)
3191 return;
3192
3193 // Change the reference count.
3194 RefVal X = *T;
3195
3196 switch (X.getKind()) {
3197 case RefVal::Owned: {
3198 unsigned cnt = X.getCount();
3199 assert(cnt > 0);
3200 X.setCount(cnt - 1);
3201 X = X ^ RefVal::ReturnedOwned;
3202 break;
3203 }
3204
3205 case RefVal::NotOwned: {
3206 unsigned cnt = X.getCount();
3207 if (cnt) {
3208 X.setCount(cnt - 1);
3209 X = X ^ RefVal::ReturnedOwned;
3210 }
3211 else {
3212 X = X ^ RefVal::ReturnedNotOwned;
3213 }
3214 break;
3215 }
3216
3217 default:
3218 return;
3219 }
3220
3221 // Update the binding.
3222 state = state->set<RefBindings>(Sym, X);
Anna Zaks0bd6b112011-10-26 21:06:34 +00003223 ExplodedNode *Pred = C.addTransition(state);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003224
3225 // At this point we have updated the state properly.
3226 // Everything after this is merely checking to see if the return value has
3227 // been over- or under-retained.
3228
3229 // Did we cache out?
3230 if (!Pred)
3231 return;
3232
Jordy Rosef53e8c72011-08-23 19:43:16 +00003233 // Update the autorelease counts.
3234 static SimpleProgramPointTag
Jordy Rose910c4052011-09-02 06:44:22 +00003235 AutoreleaseTag("RetainCountChecker : Autorelease");
Anna Zaks4eff8232011-10-05 23:44:11 +00003236 GenericNodeBuilderRefCount Bd(C, &AutoreleaseTag);
Anna Zaks6a93bd52011-10-25 19:57:11 +00003237 llvm::tie(Pred, state) = handleAutoreleaseCounts(state, Bd, Pred, C, Sym, X);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003238
3239 // Did we cache out?
Jordy Rose8d228632011-08-23 20:07:14 +00003240 if (!Pred)
Jordy Rosef53e8c72011-08-23 19:43:16 +00003241 return;
3242
3243 // Get the updated binding.
3244 T = state->get<RefBindings>(Sym);
3245 assert(T);
3246 X = *T;
3247
3248 // Consult the summary of the enclosing method.
Jordy Rose17a38e22011-09-02 05:55:19 +00003249 RetainSummaryManager &Summaries = getSummaryManager(C);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003250 const Decl *CD = &Pred->getCodeDecl();
3251
3252 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CD)) {
3253 // Unlike regular functions, /all/ ObjC methods are assumed to always
3254 // follow Cocoa retain-count conventions, not just those with special
3255 // names or attributes.
Jordy Roseb6cfc092011-08-25 00:10:37 +00003256 const RetainSummary *Summ = Summaries.getMethodSummary(MD);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003257 RetEffect RE = Summ ? Summ->getRetEffect() : RetEffect::MakeNoRet();
3258 checkReturnWithRetEffect(S, C, Pred, RE, X, Sym, state);
3259 }
3260
3261 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) {
3262 if (!isa<CXXMethodDecl>(FD))
Anna Zaks58822c42012-05-04 22:18:39 +00003263 if (const RetainSummary *Summ = Summaries.getSummary(FD, 0))
Jordy Rosef53e8c72011-08-23 19:43:16 +00003264 checkReturnWithRetEffect(S, C, Pred, Summ->getRetEffect(), X,
3265 Sym, state);
3266 }
3267}
3268
Jordy Rose910c4052011-09-02 06:44:22 +00003269void RetainCountChecker::checkReturnWithRetEffect(const ReturnStmt *S,
3270 CheckerContext &C,
3271 ExplodedNode *Pred,
3272 RetEffect RE, RefVal X,
3273 SymbolRef Sym,
Ted Kremenek8bef8232012-01-26 21:29:00 +00003274 ProgramStateRef state) const {
Jordy Rosef53e8c72011-08-23 19:43:16 +00003275 // Any leaks or other errors?
3276 if (X.isReturnedOwned() && X.getCount() == 0) {
3277 if (RE.getKind() != RetEffect::NoRet) {
3278 bool hasError = false;
Jordy Rose17a38e22011-09-02 05:55:19 +00003279 if (C.isObjCGCEnabled() && RE.getObjKind() == RetEffect::ObjC) {
Jordy Rosef53e8c72011-08-23 19:43:16 +00003280 // Things are more complicated with garbage collection. If the
3281 // returned object is suppose to be an Objective-C object, we have
3282 // a leak (as the caller expects a GC'ed object) because no
3283 // method should return ownership unless it returns a CF object.
3284 hasError = true;
3285 X = X ^ RefVal::ErrorGCLeakReturned;
3286 }
3287 else if (!RE.isOwned()) {
3288 // Either we are using GC and the returned object is a CF type
3289 // or we aren't using GC. In either case, we expect that the
3290 // enclosing method is expected to return ownership.
3291 hasError = true;
3292 X = X ^ RefVal::ErrorLeakReturned;
3293 }
3294
3295 if (hasError) {
3296 // Generate an error node.
3297 state = state->set<RefBindings>(Sym, X);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003298
3299 static SimpleProgramPointTag
Jordy Rose910c4052011-09-02 06:44:22 +00003300 ReturnOwnLeakTag("RetainCountChecker : ReturnsOwnLeak");
Anna Zaks0bd6b112011-10-26 21:06:34 +00003301 ExplodedNode *N = C.addTransition(state, Pred, &ReturnOwnLeakTag);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003302 if (N) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003303 const LangOptions &LOpts = C.getASTContext().getLangOpts();
Jordy Rose17a38e22011-09-02 05:55:19 +00003304 bool GCEnabled = C.isObjCGCEnabled();
Jordy Rosef53e8c72011-08-23 19:43:16 +00003305 CFRefReport *report =
Jordy Rose17a38e22011-09-02 05:55:19 +00003306 new CFRefLeakReport(*getLeakAtReturnBug(LOpts, GCEnabled),
3307 LOpts, GCEnabled, SummaryLog,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003308 N, Sym, C);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003309 C.EmitReport(report);
3310 }
3311 }
3312 }
3313 } else if (X.isReturnedNotOwned()) {
3314 if (RE.isOwned()) {
3315 // Trying to return a not owned object to a caller expecting an
3316 // owned object.
3317 state = state->set<RefBindings>(Sym, X ^ RefVal::ErrorReturnedNotOwned);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003318
3319 static SimpleProgramPointTag
Jordy Rose910c4052011-09-02 06:44:22 +00003320 ReturnNotOwnedTag("RetainCountChecker : ReturnNotOwnedForOwned");
Anna Zaks0bd6b112011-10-26 21:06:34 +00003321 ExplodedNode *N = C.addTransition(state, Pred, &ReturnNotOwnedTag);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003322 if (N) {
Jordy Rosed6334e12011-08-25 00:34:03 +00003323 if (!returnNotOwnedForOwned)
3324 returnNotOwnedForOwned.reset(new ReturnedNotOwnedForOwned());
3325
Jordy Rosef53e8c72011-08-23 19:43:16 +00003326 CFRefReport *report =
Jordy Rosed6334e12011-08-25 00:34:03 +00003327 new CFRefReport(*returnNotOwnedForOwned,
David Blaikie4e4d0842012-03-11 07:00:24 +00003328 C.getASTContext().getLangOpts(),
Jordy Rose17a38e22011-09-02 05:55:19 +00003329 C.isObjCGCEnabled(), SummaryLog, N, Sym);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003330 C.EmitReport(report);
3331 }
3332 }
3333 }
3334}
3335
Jordy Rose8d228632011-08-23 20:07:14 +00003336//===----------------------------------------------------------------------===//
Jordy Rose910c4052011-09-02 06:44:22 +00003337// Check various ways a symbol can be invalidated.
3338//===----------------------------------------------------------------------===//
3339
Anna Zaks390909c2011-10-06 00:43:15 +00003340void RetainCountChecker::checkBind(SVal loc, SVal val, const Stmt *S,
Jordy Rose910c4052011-09-02 06:44:22 +00003341 CheckerContext &C) const {
3342 // Are we storing to something that causes the value to "escape"?
3343 bool escapes = true;
3344
3345 // A value escapes in three possible cases (this may change):
3346 //
3347 // (1) we are binding to something that is not a memory region.
3348 // (2) we are binding to a memregion that does not have stack storage
3349 // (3) we are binding to a memregion with stack storage that the store
3350 // does not understand.
Ted Kremenek8bef8232012-01-26 21:29:00 +00003351 ProgramStateRef state = C.getState();
Jordy Rose910c4052011-09-02 06:44:22 +00003352
3353 if (loc::MemRegionVal *regionLoc = dyn_cast<loc::MemRegionVal>(&loc)) {
3354 escapes = !regionLoc->getRegion()->hasStackStorage();
3355
3356 if (!escapes) {
3357 // To test (3), generate a new state with the binding added. If it is
3358 // the same state, then it escapes (since the store cannot represent
3359 // the binding).
Anna Zakse7958da2012-05-02 00:15:40 +00003360 // Do this only if we know that the store is not supposed to generate the
3361 // same state.
3362 SVal StoredVal = state->getSVal(regionLoc->getRegion());
3363 if (StoredVal != val)
3364 escapes = (state == (state->bindLoc(*regionLoc, val)));
Jordy Rose910c4052011-09-02 06:44:22 +00003365 }
Ted Kremenekde5b4fb2012-03-27 01:12:45 +00003366 if (!escapes) {
3367 // Case 4: We do not currently model what happens when a symbol is
3368 // assigned to a struct field, so be conservative here and let the symbol
3369 // go. TODO: This could definitely be improved upon.
3370 escapes = !isa<VarRegion>(regionLoc->getRegion());
3371 }
Jordy Rose910c4052011-09-02 06:44:22 +00003372 }
3373
3374 // If our store can represent the binding and we aren't storing to something
3375 // that doesn't have local storage then just return and have the simulation
3376 // state continue as is.
3377 if (!escapes)
3378 return;
3379
3380 // Otherwise, find all symbols referenced by 'val' that we are tracking
3381 // and stop tracking them.
3382 state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
Anna Zaks0bd6b112011-10-26 21:06:34 +00003383 C.addTransition(state);
Jordy Rose910c4052011-09-02 06:44:22 +00003384}
3385
Ted Kremenek8bef8232012-01-26 21:29:00 +00003386ProgramStateRef RetainCountChecker::evalAssume(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003387 SVal Cond,
3388 bool Assumption) const {
3389
3390 // FIXME: We may add to the interface of evalAssume the list of symbols
3391 // whose assumptions have changed. For now we just iterate through the
3392 // bindings and check if any of the tracked symbols are NULL. This isn't
3393 // too bad since the number of symbols we will track in practice are
3394 // probably small and evalAssume is only called at branches and a few
3395 // other places.
3396 RefBindings B = state->get<RefBindings>();
3397
3398 if (B.isEmpty())
3399 return state;
3400
3401 bool changed = false;
3402 RefBindings::Factory &RefBFactory = state->get_context<RefBindings>();
3403
3404 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
3405 // Check if the symbol is null (or equal to any constant).
3406 // If this is the case, stop tracking the symbol.
3407 if (state->getSymVal(I.getKey())) {
3408 changed = true;
3409 B = RefBFactory.remove(B, I.getKey());
3410 }
3411 }
3412
3413 if (changed)
3414 state = state->set<RefBindings>(B);
3415
3416 return state;
3417}
3418
Ted Kremenek8bef8232012-01-26 21:29:00 +00003419ProgramStateRef
3420RetainCountChecker::checkRegionChanges(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003421 const StoreManager::InvalidatedSymbols *invalidated,
3422 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00003423 ArrayRef<const MemRegion *> Regions,
3424 const CallOrObjCMessage *Call) const {
Jordy Rose910c4052011-09-02 06:44:22 +00003425 if (!invalidated)
3426 return state;
3427
3428 llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
3429 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
3430 E = ExplicitRegions.end(); I != E; ++I) {
3431 if (const SymbolicRegion *SR = (*I)->StripCasts()->getAs<SymbolicRegion>())
3432 WhitelistedSymbols.insert(SR->getSymbol());
3433 }
3434
3435 for (StoreManager::InvalidatedSymbols::const_iterator I=invalidated->begin(),
3436 E = invalidated->end(); I!=E; ++I) {
3437 SymbolRef sym = *I;
3438 if (WhitelistedSymbols.count(sym))
3439 continue;
3440 // Remove any existing reference-count binding.
3441 state = state->remove<RefBindings>(sym);
3442 }
3443 return state;
3444}
3445
3446//===----------------------------------------------------------------------===//
Jordy Rose8d228632011-08-23 20:07:14 +00003447// Handle dead symbols and end-of-path.
3448//===----------------------------------------------------------------------===//
3449
Ted Kremenek8bef8232012-01-26 21:29:00 +00003450std::pair<ExplodedNode *, ProgramStateRef >
3451RetainCountChecker::handleAutoreleaseCounts(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003452 GenericNodeBuilderRefCount Bd,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003453 ExplodedNode *Pred,
3454 CheckerContext &Ctx,
Jordy Rose910c4052011-09-02 06:44:22 +00003455 SymbolRef Sym, RefVal V) const {
Jordy Rose8d228632011-08-23 20:07:14 +00003456 unsigned ACnt = V.getAutoreleaseCount();
3457
3458 // No autorelease counts? Nothing to be done.
3459 if (!ACnt)
3460 return std::make_pair(Pred, state);
3461
Anna Zaks6a93bd52011-10-25 19:57:11 +00003462 assert(!Ctx.isObjCGCEnabled() && "Autorelease counts in GC mode?");
Jordy Rose8d228632011-08-23 20:07:14 +00003463 unsigned Cnt = V.getCount();
3464
3465 // FIXME: Handle sending 'autorelease' to already released object.
3466
3467 if (V.getKind() == RefVal::ReturnedOwned)
3468 ++Cnt;
3469
3470 if (ACnt <= Cnt) {
3471 if (ACnt == Cnt) {
3472 V.clearCounts();
3473 if (V.getKind() == RefVal::ReturnedOwned)
3474 V = V ^ RefVal::ReturnedNotOwned;
3475 else
3476 V = V ^ RefVal::NotOwned;
3477 } else {
3478 V.setCount(Cnt - ACnt);
3479 V.setAutoreleaseCount(0);
3480 }
3481 state = state->set<RefBindings>(Sym, V);
3482 ExplodedNode *N = Bd.MakeNode(state, Pred);
3483 if (N == 0)
3484 state = 0;
3485 return std::make_pair(N, state);
3486 }
3487
3488 // Woah! More autorelease counts then retain counts left.
3489 // Emit hard error.
3490 V = V ^ RefVal::ErrorOverAutorelease;
3491 state = state->set<RefBindings>(Sym, V);
3492
Anna Zaksf05aac82011-10-18 23:05:58 +00003493 if (ExplodedNode *N = Bd.MakeNode(state, Pred, true)) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003494 SmallString<128> sbuf;
Jordy Rose8d228632011-08-23 20:07:14 +00003495 llvm::raw_svector_ostream os(sbuf);
3496 os << "Object over-autoreleased: object was sent -autorelease ";
3497 if (V.getAutoreleaseCount() > 1)
3498 os << V.getAutoreleaseCount() << " times ";
3499 os << "but the object has a +" << V.getCount() << " retain count";
3500
Jordy Rosed6334e12011-08-25 00:34:03 +00003501 if (!overAutorelease)
3502 overAutorelease.reset(new OverAutorelease());
3503
David Blaikie4e4d0842012-03-11 07:00:24 +00003504 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
Jordy Rose8d228632011-08-23 20:07:14 +00003505 CFRefReport *report =
Jordy Rosed6334e12011-08-25 00:34:03 +00003506 new CFRefReport(*overAutorelease, LOpts, /* GCEnabled = */ false,
3507 SummaryLog, N, Sym, os.str());
Anna Zaks6a93bd52011-10-25 19:57:11 +00003508 Ctx.EmitReport(report);
Jordy Rose8d228632011-08-23 20:07:14 +00003509 }
3510
Ted Kremenek8bef8232012-01-26 21:29:00 +00003511 return std::make_pair((ExplodedNode *)0, (ProgramStateRef )0);
Jordy Rose8d228632011-08-23 20:07:14 +00003512}
Jordy Rose38f17d62011-08-23 19:01:07 +00003513
Ted Kremenek8bef8232012-01-26 21:29:00 +00003514ProgramStateRef
3515RetainCountChecker::handleSymbolDeath(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003516 SymbolRef sid, RefVal V,
Jordy Rose38f17d62011-08-23 19:01:07 +00003517 SmallVectorImpl<SymbolRef> &Leaked) const {
Jordy Rose53376122011-08-24 04:48:19 +00003518 bool hasLeak = false;
Jordy Rose38f17d62011-08-23 19:01:07 +00003519 if (V.isOwned())
3520 hasLeak = true;
3521 else if (V.isNotOwned() || V.isReturnedOwned())
3522 hasLeak = (V.getCount() > 0);
3523
3524 if (!hasLeak)
3525 return state->remove<RefBindings>(sid);
3526
3527 Leaked.push_back(sid);
3528 return state->set<RefBindings>(sid, V ^ RefVal::ErrorLeak);
3529}
3530
3531ExplodedNode *
Ted Kremenek8bef8232012-01-26 21:29:00 +00003532RetainCountChecker::processLeaks(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003533 SmallVectorImpl<SymbolRef> &Leaked,
3534 GenericNodeBuilderRefCount &Builder,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003535 CheckerContext &Ctx,
3536 ExplodedNode *Pred) const {
Jordy Rose38f17d62011-08-23 19:01:07 +00003537 if (Leaked.empty())
3538 return Pred;
3539
3540 // Generate an intermediate node representing the leak point.
3541 ExplodedNode *N = Builder.MakeNode(state, Pred);
3542
3543 if (N) {
3544 for (SmallVectorImpl<SymbolRef>::iterator
3545 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3546
David Blaikie4e4d0842012-03-11 07:00:24 +00003547 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
Anna Zaks6a93bd52011-10-25 19:57:11 +00003548 bool GCEnabled = Ctx.isObjCGCEnabled();
Jordy Rose17a38e22011-09-02 05:55:19 +00003549 CFRefBug *BT = Pred ? getLeakWithinFunctionBug(LOpts, GCEnabled)
3550 : getLeakAtReturnBug(LOpts, GCEnabled);
Jordy Rose38f17d62011-08-23 19:01:07 +00003551 assert(BT && "BugType not initialized.");
Jordy Rose20589562011-08-24 22:39:09 +00003552
Jordy Rose17a38e22011-09-02 05:55:19 +00003553 CFRefLeakReport *report = new CFRefLeakReport(*BT, LOpts, GCEnabled,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003554 SummaryLog, N, *I, Ctx);
3555 Ctx.EmitReport(report);
Jordy Rose38f17d62011-08-23 19:01:07 +00003556 }
3557 }
3558
3559 return N;
3560}
3561
Anna Zaksaf498a22011-10-25 19:56:48 +00003562void RetainCountChecker::checkEndPath(CheckerContext &Ctx) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +00003563 ProgramStateRef state = Ctx.getState();
Anna Zaksaf498a22011-10-25 19:56:48 +00003564 GenericNodeBuilderRefCount Bd(Ctx);
Jordy Rose38f17d62011-08-23 19:01:07 +00003565 RefBindings B = state->get<RefBindings>();
Anna Zaksaf498a22011-10-25 19:56:48 +00003566 ExplodedNode *Pred = Ctx.getPredecessor();
Jordy Rose38f17d62011-08-23 19:01:07 +00003567
3568 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Anna Zaks6a93bd52011-10-25 19:57:11 +00003569 llvm::tie(Pred, state) = handleAutoreleaseCounts(state, Bd, Pred, Ctx,
Jordy Rose8d228632011-08-23 20:07:14 +00003570 I->first, I->second);
3571 if (!state)
Jordy Rose38f17d62011-08-23 19:01:07 +00003572 return;
3573 }
3574
Ted Kremenek0cf3d472012-02-07 00:24:33 +00003575 // If the current LocationContext has a parent, don't check for leaks.
3576 // We will do that later.
3577 // FIXME: we should instead check for imblances of the retain/releases,
3578 // and suggest annotations.
3579 if (Ctx.getLocationContext()->getParent())
3580 return;
3581
Jordy Rose38f17d62011-08-23 19:01:07 +00003582 B = state->get<RefBindings>();
3583 SmallVector<SymbolRef, 10> Leaked;
3584
3585 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I)
Jordy Rose8d228632011-08-23 20:07:14 +00003586 state = handleSymbolDeath(state, I->first, I->second, Leaked);
Jordy Rose38f17d62011-08-23 19:01:07 +00003587
Anna Zaks6a93bd52011-10-25 19:57:11 +00003588 processLeaks(state, Leaked, Bd, Ctx, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003589}
3590
3591const ProgramPointTag *
Jordy Rose910c4052011-09-02 06:44:22 +00003592RetainCountChecker::getDeadSymbolTag(SymbolRef sym) const {
Jordy Rose38f17d62011-08-23 19:01:07 +00003593 const SimpleProgramPointTag *&tag = DeadSymbolTags[sym];
3594 if (!tag) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003595 SmallString<64> buf;
Jordy Rose38f17d62011-08-23 19:01:07 +00003596 llvm::raw_svector_ostream out(buf);
Anna Zaksf62ceec2011-12-05 18:58:11 +00003597 out << "RetainCountChecker : Dead Symbol : ";
3598 sym->dumpToStream(out);
Jordy Rose38f17d62011-08-23 19:01:07 +00003599 tag = new SimpleProgramPointTag(out.str());
3600 }
3601 return tag;
3602}
3603
Jordy Rose910c4052011-09-02 06:44:22 +00003604void RetainCountChecker::checkDeadSymbols(SymbolReaper &SymReaper,
3605 CheckerContext &C) const {
Jordy Rose38f17d62011-08-23 19:01:07 +00003606 ExplodedNode *Pred = C.getPredecessor();
3607
Ted Kremenek8bef8232012-01-26 21:29:00 +00003608 ProgramStateRef state = C.getState();
Jordy Rose38f17d62011-08-23 19:01:07 +00003609 RefBindings B = state->get<RefBindings>();
3610
3611 // Update counts from autorelease pools
3612 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3613 E = SymReaper.dead_end(); I != E; ++I) {
3614 SymbolRef Sym = *I;
3615 if (const RefVal *T = B.lookup(Sym)){
3616 // Use the symbol as the tag.
3617 // FIXME: This might not be as unique as we would like.
Anna Zaks4eff8232011-10-05 23:44:11 +00003618 GenericNodeBuilderRefCount Bd(C, getDeadSymbolTag(Sym));
Anna Zaks6a93bd52011-10-25 19:57:11 +00003619 llvm::tie(Pred, state) = handleAutoreleaseCounts(state, Bd, Pred, C,
Jordy Rose8d228632011-08-23 20:07:14 +00003620 Sym, *T);
3621 if (!state)
Jordy Rose38f17d62011-08-23 19:01:07 +00003622 return;
3623 }
3624 }
3625
3626 B = state->get<RefBindings>();
3627 SmallVector<SymbolRef, 10> Leaked;
3628
3629 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3630 E = SymReaper.dead_end(); I != E; ++I) {
3631 if (const RefVal *T = B.lookup(*I))
3632 state = handleSymbolDeath(state, *I, *T, Leaked);
3633 }
3634
3635 {
Anna Zaks4eff8232011-10-05 23:44:11 +00003636 GenericNodeBuilderRefCount Bd(C, this);
Anna Zaks6a93bd52011-10-25 19:57:11 +00003637 Pred = processLeaks(state, Leaked, Bd, C, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003638 }
3639
3640 // Did we cache out?
3641 if (!Pred)
3642 return;
3643
3644 // Now generate a new node that nukes the old bindings.
3645 RefBindings::Factory &F = state->get_context<RefBindings>();
3646
3647 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3648 E = SymReaper.dead_end(); I != E; ++I)
3649 B = F.remove(B, *I);
3650
3651 state = state->set<RefBindings>(B);
Anna Zaks0bd6b112011-10-26 21:06:34 +00003652 C.addTransition(state, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003653}
3654
Ted Kremenekd593eb92009-11-25 22:17:44 +00003655//===----------------------------------------------------------------------===//
Jordy Rosedbd658e2011-08-28 19:11:56 +00003656// Debug printing of refcount bindings and autorelease pools.
3657//===----------------------------------------------------------------------===//
3658
3659static void PrintPool(raw_ostream &Out, SymbolRef Sym,
Ted Kremenek8bef8232012-01-26 21:29:00 +00003660 ProgramStateRef State) {
Jordy Rosedbd658e2011-08-28 19:11:56 +00003661 Out << ' ';
3662 if (Sym)
Anna Zaksf62ceec2011-12-05 18:58:11 +00003663 Sym->dumpToStream(Out);
Jordy Rosedbd658e2011-08-28 19:11:56 +00003664 else
3665 Out << "<pool>";
3666 Out << ":{";
3667
3668 // Get the contents of the pool.
3669 if (const ARCounts *Cnts = State->get<AutoreleasePoolContents>(Sym))
3670 for (ARCounts::iterator I = Cnts->begin(), E = Cnts->end(); I != E; ++I)
3671 Out << '(' << I.getKey() << ',' << I.getData() << ')';
3672
3673 Out << '}';
3674}
3675
Ted Kremenek8bef8232012-01-26 21:29:00 +00003676static bool UsesAutorelease(ProgramStateRef state) {
Jordy Rosedbd658e2011-08-28 19:11:56 +00003677 // A state uses autorelease if it allocated an autorelease pool or if it has
3678 // objects in the caller's autorelease pool.
3679 return !state->get<AutoreleaseStack>().isEmpty() ||
3680 state->get<AutoreleasePoolContents>(SymbolRef());
3681}
3682
Ted Kremenek8bef8232012-01-26 21:29:00 +00003683void RetainCountChecker::printState(raw_ostream &Out, ProgramStateRef State,
Jordy Rose910c4052011-09-02 06:44:22 +00003684 const char *NL, const char *Sep) const {
Jordy Rosedbd658e2011-08-28 19:11:56 +00003685
3686 RefBindings B = State->get<RefBindings>();
3687
3688 if (!B.isEmpty())
3689 Out << Sep << NL;
3690
3691 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
3692 Out << I->first << " : ";
3693 I->second.print(Out);
3694 Out << NL;
3695 }
3696
3697 // Print the autorelease stack.
3698 if (UsesAutorelease(State)) {
3699 Out << Sep << NL << "AR pool stack:";
3700 ARStack Stack = State->get<AutoreleaseStack>();
3701
3702 PrintPool(Out, SymbolRef(), State); // Print the caller's pool.
3703 for (ARStack::iterator I = Stack.begin(), E = Stack.end(); I != E; ++I)
3704 PrintPool(Out, *I, State);
3705
3706 Out << NL;
3707 }
3708}
3709
3710//===----------------------------------------------------------------------===//
Jordy Rose910c4052011-09-02 06:44:22 +00003711// Checker registration.
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00003712//===----------------------------------------------------------------------===//
3713
Jordy Rose17a38e22011-09-02 05:55:19 +00003714void ento::registerRetainCountChecker(CheckerManager &Mgr) {
Jordy Rose910c4052011-09-02 06:44:22 +00003715 Mgr.registerChecker<RetainCountChecker>();
Jordy Rose17a38e22011-09-02 05:55:19 +00003716}
3717