blob: 940228e679539455281043eec7fb952f542e65bd [file] [log] [blame]
Jordy Rose910c4052011-09-02 06:44:22 +00001//==-- RetainCountChecker.cpp - Checks for leaks and other issues -*- C++ -*--//
Ted Kremenek2fff37e2008-03-06 00:08:09 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Jordy Rose910c4052011-09-02 06:44:22 +000010// This file defines the methods for RetainCountChecker, which implements
11// a reference count checker for Core Foundation and Cocoa on (Mac OS X).
Ted Kremenek2fff37e2008-03-06 00:08:09 +000012//
13//===----------------------------------------------------------------------===//
14
Jordy Rose910c4052011-09-02 06:44:22 +000015#include "ClangSACheckers.h"
Mike Stump1eb44332009-09-09 15:08:12 +000016#include "clang/AST/DeclObjC.h"
Ted Kremenekb2771592011-03-30 17:41:19 +000017#include "clang/AST/DeclCXX.h"
Ted Kremenek0b526b42010-02-18 00:05:58 +000018#include "clang/Basic/LangOptions.h"
19#include "clang/Basic/SourceManager.h"
Jordy Rose910c4052011-09-02 06:44:22 +000020#include "clang/Analysis/DomainSpecific/CocoaConventions.h"
Ted Kremenek4c42bb72011-11-14 21:59:21 +000021#include "clang/AST/ParentMap.h"
Jordy Rose910c4052011-09-02 06:44:22 +000022#include "clang/StaticAnalyzer/Core/Checker.h"
23#include "clang/StaticAnalyzer/Core/CheckerManager.h"
Ted Kremenek9b663712011-02-10 01:03:03 +000024#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
25#include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
Jordy Rose910c4052011-09-02 06:44:22 +000026#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
Ted Kremenek18c66fd2011-08-15 22:09:50 +000027#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
Ted Kremenek9b663712011-02-10 01:03:03 +000028#include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
Jordy Rosed1e5a892011-09-02 08:02:59 +000029#include "clang/StaticAnalyzer/Core/PathSensitive/ObjCMessage.h"
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000030#include "llvm/ADT/DenseMap.h"
31#include "llvm/ADT/FoldingSet.h"
Ted Kremenek6d348932008-10-21 15:53:15 +000032#include "llvm/ADT/ImmutableList.h"
Ted Kremenek0b526b42010-02-18 00:05:58 +000033#include "llvm/ADT/ImmutableMap.h"
Benjamin Kramer8fe83e12012-02-04 13:45:25 +000034#include "llvm/ADT/SmallString.h"
Ted Kremenek6ed9afc2008-05-16 18:33:44 +000035#include "llvm/ADT/STLExtras.h"
Ted Kremenek0b526b42010-02-18 00:05:58 +000036#include "llvm/ADT/StringExtras.h"
Chris Lattner5f9e2722011-07-23 10:55:15 +000037#include <cstdarg>
Ted Kremenek2fff37e2008-03-06 00:08:09 +000038
39using namespace clang;
Ted Kremenek9ef65372010-12-23 07:20:52 +000040using namespace ento;
Ted Kremeneka64e89b2010-01-27 06:13:48 +000041using llvm::StrInStrNoCase;
Ted Kremenek4c79e552008-11-05 16:54:44 +000042
Ted Kremenekd775c662010-05-21 21:57:00 +000043namespace {
Jordy Rose910c4052011-09-02 06:44:22 +000044/// Wrapper around different kinds of node builder, so that helper functions
45/// can have a common interface.
Francois Pichetea097852011-01-11 10:41:37 +000046class GenericNodeBuilderRefCount {
Anna Zaks4eff8232011-10-05 23:44:11 +000047 CheckerContext *C;
Ted Kremenekca804532011-08-12 23:04:46 +000048 const ProgramPointTag *tag;
Ted Kremenek9d9d3a62009-05-08 23:09:42 +000049public:
Anna Zaks4eff8232011-10-05 23:44:11 +000050 GenericNodeBuilderRefCount(CheckerContext &c,
Anna Zaksaf498a22011-10-25 19:56:48 +000051 const ProgramPointTag *t = 0)
Anna Zaks6a93bd52011-10-25 19:57:11 +000052 : C(&c), tag(t){}
Zhongxing Xu031ccc02009-08-06 12:48:26 +000053
Ted Kremenek8bef8232012-01-26 21:29:00 +000054 ExplodedNode *MakeNode(ProgramStateRef state, ExplodedNode *Pred,
Anna Zaksf05aac82011-10-18 23:05:58 +000055 bool MarkAsSink = false) {
Anna Zaks0bd6b112011-10-26 21:06:34 +000056 return C->addTransition(state, Pred, tag, MarkAsSink);
Ted Kremenek9d9d3a62009-05-08 23:09:42 +000057 }
58};
59} // end anonymous namespace
60
Ted Kremenek05cbe1a2008-04-09 23:49:11 +000061//===----------------------------------------------------------------------===//
Ted Kremenek553cf182008-06-25 21:21:56 +000062// Primitives used for constructing summaries for function/method calls.
Ted Kremenek05cbe1a2008-04-09 23:49:11 +000063//===----------------------------------------------------------------------===//
64
Ted Kremenek553cf182008-06-25 21:21:56 +000065/// ArgEffect is used to summarize a function/method call's effect on a
66/// particular argument.
Jordy Rosebd85b132011-08-24 19:10:50 +000067enum ArgEffect { DoNothing, Autorelease, Dealloc, DecRef, DecRefMsg,
John McCallf85e1932011-06-15 23:02:42 +000068 DecRefBridgedTransfered,
Jordy Rosebd85b132011-08-24 19:10:50 +000069 IncRefMsg, IncRef, MakeCollectable, MayEscape,
Ted Kremenekf95e9fc2009-03-17 19:42:23 +000070 NewAutoreleasePool, SelfOwn, StopTracking };
Ted Kremenek553cf182008-06-25 21:21:56 +000071
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000072namespace llvm {
Ted Kremenekb77449c2009-05-03 05:20:50 +000073template <> struct FoldingSetTrait<ArgEffect> {
74static inline void Profile(const ArgEffect X, FoldingSetNodeID& ID) {
75 ID.AddInteger((unsigned) X);
76}
Ted Kremenek553cf182008-06-25 21:21:56 +000077};
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000078} // end llvm namespace
79
Ted Kremenekb77449c2009-05-03 05:20:50 +000080/// ArgEffects summarizes the effects of a function/method call on all of
81/// its arguments.
82typedef llvm::ImmutableMap<unsigned,ArgEffect> ArgEffects;
83
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000084namespace {
Ted Kremenek553cf182008-06-25 21:21:56 +000085
86/// RetEffect is used to summarize a function/method call's behavior with
Mike Stump1eb44332009-09-09 15:08:12 +000087/// respect to its return value.
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +000088class RetEffect {
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000089public:
Jordy Rose76c506f2011-08-21 21:58:18 +000090 enum Kind { NoRet, OwnedSymbol, OwnedAllocatedSymbol,
John McCallf85e1932011-06-15 23:02:42 +000091 NotOwnedSymbol, GCNotOwnedSymbol, ARCNotOwnedSymbol,
Ted Kremenek78a35a32009-05-12 20:06:54 +000092 OwnedWhenTrackedReceiver };
Mike Stump1eb44332009-09-09 15:08:12 +000093
94 enum ObjKind { CF, ObjC, AnyObj };
Ted Kremenek2d1652e2009-01-28 05:56:51 +000095
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000096private:
Ted Kremenek2d1652e2009-01-28 05:56:51 +000097 Kind K;
98 ObjKind O;
Ted Kremenek2d1652e2009-01-28 05:56:51 +000099
Jordy Rose76c506f2011-08-21 21:58:18 +0000100 RetEffect(Kind k, ObjKind o = AnyObj) : K(k), O(o) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000101
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000102public:
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000103 Kind getKind() const { return K; }
104
105 ObjKind getObjKind() const { return O; }
Mike Stump1eb44332009-09-09 15:08:12 +0000106
Ted Kremeneka8833552009-04-29 23:03:22 +0000107 bool isOwned() const {
Ted Kremenek78a35a32009-05-12 20:06:54 +0000108 return K == OwnedSymbol || K == OwnedAllocatedSymbol ||
109 K == OwnedWhenTrackedReceiver;
Ted Kremeneka8833552009-04-29 23:03:22 +0000110 }
Mike Stump1eb44332009-09-09 15:08:12 +0000111
Jordy Rose4df54fe2011-08-23 04:27:15 +0000112 bool operator==(const RetEffect &Other) const {
113 return K == Other.K && O == Other.O;
114 }
115
Ted Kremenek78a35a32009-05-12 20:06:54 +0000116 static RetEffect MakeOwnedWhenTrackedReceiver() {
117 return RetEffect(OwnedWhenTrackedReceiver, ObjC);
118 }
Mike Stump1eb44332009-09-09 15:08:12 +0000119
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000120 static RetEffect MakeOwned(ObjKind o, bool isAllocated = false) {
121 return RetEffect(isAllocated ? OwnedAllocatedSymbol : OwnedSymbol, o);
Mike Stump1eb44332009-09-09 15:08:12 +0000122 }
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000123 static RetEffect MakeNotOwned(ObjKind o) {
124 return RetEffect(NotOwnedSymbol, o);
Ted Kremeneke798e7c2009-04-27 19:14:45 +0000125 }
126 static RetEffect MakeGCNotOwned() {
127 return RetEffect(GCNotOwnedSymbol, ObjC);
128 }
John McCallf85e1932011-06-15 23:02:42 +0000129 static RetEffect MakeARCNotOwned() {
130 return RetEffect(ARCNotOwnedSymbol, ObjC);
131 }
Ted Kremenek553cf182008-06-25 21:21:56 +0000132 static RetEffect MakeNoRet() {
133 return RetEffect(NoRet);
Ted Kremeneka7344702008-06-23 18:02:52 +0000134 }
Jordy Roseef945882012-03-18 01:26:10 +0000135
136 void Profile(llvm::FoldingSetNodeID& ID) const {
137 ID.AddInteger((unsigned) K);
138 ID.AddInteger((unsigned) O);
139 }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000140};
Mike Stump1eb44332009-09-09 15:08:12 +0000141
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000142//===----------------------------------------------------------------------===//
143// Reference-counting logic (typestate + counts).
144//===----------------------------------------------------------------------===//
Mike Stump1eb44332009-09-09 15:08:12 +0000145
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000146class RefVal {
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000147public:
148 enum Kind {
149 Owned = 0, // Owning reference.
150 NotOwned, // Reference is not owned by still valid (not freed).
151 Released, // Object has been released.
152 ReturnedOwned, // Returned object passes ownership to caller.
153 ReturnedNotOwned, // Return object does not pass ownership to caller.
154 ERROR_START,
155 ErrorDeallocNotOwned, // -dealloc called on non-owned object.
156 ErrorDeallocGC, // Calling -dealloc with GC enabled.
157 ErrorUseAfterRelease, // Object used after released.
158 ErrorReleaseNotOwned, // Release of an object that was not owned.
159 ERROR_LEAK_START,
160 ErrorLeak, // A memory leak due to excessive reference counts.
161 ErrorLeakReturned, // A memory leak due to the returning method not having
162 // the correct naming conventions.
163 ErrorGCLeakReturned,
164 ErrorOverAutorelease,
165 ErrorReturnedNotOwned
166 };
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000167
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000168private:
169 Kind kind;
170 RetEffect::ObjKind okind;
171 unsigned Cnt;
172 unsigned ACnt;
173 QualType T;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000174
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000175 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, unsigned acnt, QualType t)
176 : kind(k), okind(o), Cnt(cnt), ACnt(acnt), T(t) {}
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000177
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000178public:
179 Kind getKind() const { return kind; }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000180
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000181 RetEffect::ObjKind getObjKind() const { return okind; }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000182
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000183 unsigned getCount() const { return Cnt; }
184 unsigned getAutoreleaseCount() const { return ACnt; }
185 unsigned getCombinedCounts() const { return Cnt + ACnt; }
186 void clearCounts() { Cnt = 0; ACnt = 0; }
187 void setCount(unsigned i) { Cnt = i; }
188 void setAutoreleaseCount(unsigned i) { ACnt = i; }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000189
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000190 QualType getType() const { return T; }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000191
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000192 bool isOwned() const {
193 return getKind() == Owned;
194 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000195
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000196 bool isNotOwned() const {
197 return getKind() == NotOwned;
198 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000199
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000200 bool isReturnedOwned() const {
201 return getKind() == ReturnedOwned;
202 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000203
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000204 bool isReturnedNotOwned() const {
205 return getKind() == ReturnedNotOwned;
206 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000207
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000208 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
209 unsigned Count = 1) {
210 return RefVal(Owned, o, Count, 0, t);
211 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000212
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000213 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
214 unsigned Count = 0) {
215 return RefVal(NotOwned, o, Count, 0, t);
216 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000217
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000218 // Comparison, profiling, and pretty-printing.
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000219
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000220 bool operator==(const RefVal& X) const {
221 return kind == X.kind && Cnt == X.Cnt && T == X.T && ACnt == X.ACnt;
222 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000223
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000224 RefVal operator-(size_t i) const {
225 return RefVal(getKind(), getObjKind(), getCount() - i,
226 getAutoreleaseCount(), getType());
227 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000228
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000229 RefVal operator+(size_t i) const {
230 return RefVal(getKind(), getObjKind(), getCount() + i,
231 getAutoreleaseCount(), getType());
232 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000233
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000234 RefVal operator^(Kind k) const {
235 return RefVal(k, getObjKind(), getCount(), getAutoreleaseCount(),
236 getType());
237 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000238
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000239 RefVal autorelease() const {
240 return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount()+1,
241 getType());
242 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000243
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000244 void Profile(llvm::FoldingSetNodeID& ID) const {
245 ID.AddInteger((unsigned) kind);
246 ID.AddInteger(Cnt);
247 ID.AddInteger(ACnt);
248 ID.Add(T);
249 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000250
Ted Kremenek9c378f72011-08-12 23:37:29 +0000251 void print(raw_ostream &Out) const;
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000252};
253
Ted Kremenek9c378f72011-08-12 23:37:29 +0000254void RefVal::print(raw_ostream &Out) const {
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000255 if (!T.isNull())
Jordy Rosedbd658e2011-08-28 19:11:56 +0000256 Out << "Tracked " << T.getAsString() << '/';
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000257
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000258 switch (getKind()) {
Jordy Rose910c4052011-09-02 06:44:22 +0000259 default: llvm_unreachable("Invalid RefVal kind");
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000260 case Owned: {
261 Out << "Owned";
262 unsigned cnt = getCount();
263 if (cnt) Out << " (+ " << cnt << ")";
264 break;
265 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000266
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000267 case NotOwned: {
268 Out << "NotOwned";
269 unsigned cnt = getCount();
270 if (cnt) Out << " (+ " << cnt << ")";
271 break;
272 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000273
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000274 case ReturnedOwned: {
275 Out << "ReturnedOwned";
276 unsigned cnt = getCount();
277 if (cnt) Out << " (+ " << cnt << ")";
278 break;
279 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000280
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000281 case ReturnedNotOwned: {
282 Out << "ReturnedNotOwned";
283 unsigned cnt = getCount();
284 if (cnt) Out << " (+ " << cnt << ")";
285 break;
286 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000287
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000288 case Released:
289 Out << "Released";
290 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000291
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000292 case ErrorDeallocGC:
293 Out << "-dealloc (GC)";
294 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000295
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000296 case ErrorDeallocNotOwned:
297 Out << "-dealloc (not-owned)";
298 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000299
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000300 case ErrorLeak:
301 Out << "Leaked";
302 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000303
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000304 case ErrorLeakReturned:
305 Out << "Leaked (Bad naming)";
306 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000307
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000308 case ErrorGCLeakReturned:
309 Out << "Leaked (GC-ed at return)";
310 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000311
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000312 case ErrorUseAfterRelease:
313 Out << "Use-After-Release [ERROR]";
314 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000315
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000316 case ErrorReleaseNotOwned:
317 Out << "Release of Not-Owned [ERROR]";
318 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000319
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000320 case RefVal::ErrorOverAutorelease:
321 Out << "Over autoreleased";
322 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000323
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000324 case RefVal::ErrorReturnedNotOwned:
325 Out << "Non-owned object returned instead of owned";
326 break;
327 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000328
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000329 if (ACnt) {
330 Out << " [ARC +" << ACnt << ']';
331 }
332}
333} //end anonymous namespace
334
335//===----------------------------------------------------------------------===//
336// RefBindings - State used to track object reference counts.
337//===----------------------------------------------------------------------===//
338
339typedef llvm::ImmutableMap<SymbolRef, RefVal> RefBindings;
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000340
341namespace clang {
Ted Kremenek9ef65372010-12-23 07:20:52 +0000342namespace ento {
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000343template<>
344struct ProgramStateTrait<RefBindings>
345 : public ProgramStatePartialTrait<RefBindings> {
346 static void *GDMIndex() {
347 static int RefBIndex = 0;
348 return &RefBIndex;
349 }
350};
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000351}
Argyrios Kyrtzidis5a4f98f2010-12-22 18:53:20 +0000352}
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000353
354//===----------------------------------------------------------------------===//
Jordy Rose910c4052011-09-02 06:44:22 +0000355// Function/Method behavior summaries.
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000356//===----------------------------------------------------------------------===//
357
358namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000359class RetainSummary {
Jordy Roseef945882012-03-18 01:26:10 +0000360 /// Args - a map of (index, ArgEffect) pairs, where index
Ted Kremenek1bffd742008-05-06 15:44:25 +0000361 /// specifies the argument (starting from 0). This can be sparsely
362 /// populated; arguments with no entry in Args use 'DefaultArgEffect'.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000363 ArgEffects Args;
Mike Stump1eb44332009-09-09 15:08:12 +0000364
Ted Kremenek1bffd742008-05-06 15:44:25 +0000365 /// DefaultArgEffect - The default ArgEffect to apply to arguments that
366 /// do not have an entry in Args.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000367 ArgEffect DefaultArgEffect;
Mike Stump1eb44332009-09-09 15:08:12 +0000368
Ted Kremenek553cf182008-06-25 21:21:56 +0000369 /// Receiver - If this summary applies to an Objective-C message expression,
370 /// this is the effect applied to the state of the receiver.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000371 ArgEffect Receiver;
Mike Stump1eb44332009-09-09 15:08:12 +0000372
Ted Kremenek553cf182008-06-25 21:21:56 +0000373 /// Ret - The effect on the return value. Used to indicate if the
Jordy Rose76c506f2011-08-21 21:58:18 +0000374 /// function/method call returns a new tracked symbol.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000375 RetEffect Ret;
Mike Stump1eb44332009-09-09 15:08:12 +0000376
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000377public:
Ted Kremenekb77449c2009-05-03 05:20:50 +0000378 RetainSummary(ArgEffects A, RetEffect R, ArgEffect defaultEff,
Jordy Rosee62e87b2011-08-20 20:55:40 +0000379 ArgEffect ReceiverEff)
380 : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000381
Ted Kremenek553cf182008-06-25 21:21:56 +0000382 /// getArg - Return the argument effect on the argument specified by
383 /// idx (starting from 0).
Ted Kremenek1ac08d62008-03-11 17:48:22 +0000384 ArgEffect getArg(unsigned idx) const {
Ted Kremenekb77449c2009-05-03 05:20:50 +0000385 if (const ArgEffect *AE = Args.lookup(idx))
386 return *AE;
Mike Stump1eb44332009-09-09 15:08:12 +0000387
Ted Kremenek1bffd742008-05-06 15:44:25 +0000388 return DefaultArgEffect;
Ted Kremenek1ac08d62008-03-11 17:48:22 +0000389 }
Ted Kremenek11fe1752011-01-27 18:43:03 +0000390
391 void addArg(ArgEffects::Factory &af, unsigned idx, ArgEffect e) {
392 Args = af.add(Args, idx, e);
393 }
Mike Stump1eb44332009-09-09 15:08:12 +0000394
Ted Kremenek885c27b2009-05-04 05:31:22 +0000395 /// setDefaultArgEffect - Set the default argument effect.
396 void setDefaultArgEffect(ArgEffect E) {
397 DefaultArgEffect = E;
398 }
Mike Stump1eb44332009-09-09 15:08:12 +0000399
Ted Kremenek553cf182008-06-25 21:21:56 +0000400 /// getRetEffect - Returns the effect on the return value of the call.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000401 RetEffect getRetEffect() const { return Ret; }
Mike Stump1eb44332009-09-09 15:08:12 +0000402
Ted Kremenek885c27b2009-05-04 05:31:22 +0000403 /// setRetEffect - Set the effect of the return value of the call.
404 void setRetEffect(RetEffect E) { Ret = E; }
Mike Stump1eb44332009-09-09 15:08:12 +0000405
Ted Kremenek12b94342011-01-27 06:54:14 +0000406
407 /// Sets the effect on the receiver of the message.
408 void setReceiverEffect(ArgEffect e) { Receiver = e; }
409
Ted Kremenek553cf182008-06-25 21:21:56 +0000410 /// getReceiverEffect - Returns the effect on the receiver of the call.
411 /// This is only meaningful if the summary applies to an ObjCMessageExpr*.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000412 ArgEffect getReceiverEffect() const { return Receiver; }
Jordy Rose4df54fe2011-08-23 04:27:15 +0000413
414 /// Test if two retain summaries are identical. Note that merely equivalent
415 /// summaries are not necessarily identical (for example, if an explicit
416 /// argument effect matches the default effect).
417 bool operator==(const RetainSummary &Other) const {
418 return Args == Other.Args && DefaultArgEffect == Other.DefaultArgEffect &&
419 Receiver == Other.Receiver && Ret == Other.Ret;
420 }
Jordy Roseef945882012-03-18 01:26:10 +0000421
422 /// Profile this summary for inclusion in a FoldingSet.
423 void Profile(llvm::FoldingSetNodeID& ID) const {
424 ID.Add(Args);
425 ID.Add(DefaultArgEffect);
426 ID.Add(Receiver);
427 ID.Add(Ret);
428 }
429
430 /// A retain summary is simple if it has no ArgEffects other than the default.
431 bool isSimple() const {
432 return Args.isEmpty();
433 }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000434};
Ted Kremenek4f22a782008-06-23 23:30:29 +0000435} // end anonymous namespace
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000436
Ted Kremenek553cf182008-06-25 21:21:56 +0000437//===----------------------------------------------------------------------===//
438// Data structures for constructing summaries.
439//===----------------------------------------------------------------------===//
Ted Kremenek53301ba2008-06-24 03:49:48 +0000440
Ted Kremenek553cf182008-06-25 21:21:56 +0000441namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000442class ObjCSummaryKey {
Ted Kremenek553cf182008-06-25 21:21:56 +0000443 IdentifierInfo* II;
444 Selector S;
Mike Stump1eb44332009-09-09 15:08:12 +0000445public:
Ted Kremenek553cf182008-06-25 21:21:56 +0000446 ObjCSummaryKey(IdentifierInfo* ii, Selector s)
447 : II(ii), S(s) {}
448
Ted Kremenek9c378f72011-08-12 23:37:29 +0000449 ObjCSummaryKey(const ObjCInterfaceDecl *d, Selector s)
Ted Kremenek553cf182008-06-25 21:21:56 +0000450 : II(d ? d->getIdentifier() : 0), S(s) {}
Ted Kremenek70b6a832009-05-13 18:16:01 +0000451
Ted Kremenek9c378f72011-08-12 23:37:29 +0000452 ObjCSummaryKey(const ObjCInterfaceDecl *d, IdentifierInfo *ii, Selector s)
Ted Kremenek70b6a832009-05-13 18:16:01 +0000453 : II(d ? d->getIdentifier() : ii), S(s) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000454
Ted Kremenek553cf182008-06-25 21:21:56 +0000455 ObjCSummaryKey(Selector s)
456 : II(0), S(s) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000457
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000458 IdentifierInfo *getIdentifier() const { return II; }
Ted Kremenek553cf182008-06-25 21:21:56 +0000459 Selector getSelector() const { return S; }
460};
Ted Kremenek4f22a782008-06-23 23:30:29 +0000461}
462
463namespace llvm {
Ted Kremenek553cf182008-06-25 21:21:56 +0000464template <> struct DenseMapInfo<ObjCSummaryKey> {
465 static inline ObjCSummaryKey getEmptyKey() {
466 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
467 DenseMapInfo<Selector>::getEmptyKey());
468 }
Mike Stump1eb44332009-09-09 15:08:12 +0000469
Ted Kremenek553cf182008-06-25 21:21:56 +0000470 static inline ObjCSummaryKey getTombstoneKey() {
471 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
Mike Stump1eb44332009-09-09 15:08:12 +0000472 DenseMapInfo<Selector>::getTombstoneKey());
Ted Kremenek553cf182008-06-25 21:21:56 +0000473 }
Mike Stump1eb44332009-09-09 15:08:12 +0000474
Ted Kremenek553cf182008-06-25 21:21:56 +0000475 static unsigned getHashValue(const ObjCSummaryKey &V) {
476 return (DenseMapInfo<IdentifierInfo*>::getHashValue(V.getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000477 & 0x88888888)
Ted Kremenek553cf182008-06-25 21:21:56 +0000478 | (DenseMapInfo<Selector>::getHashValue(V.getSelector())
479 & 0x55555555);
480 }
Mike Stump1eb44332009-09-09 15:08:12 +0000481
Ted Kremenek553cf182008-06-25 21:21:56 +0000482 static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
483 return DenseMapInfo<IdentifierInfo*>::isEqual(LHS.getIdentifier(),
484 RHS.getIdentifier()) &&
485 DenseMapInfo<Selector>::isEqual(LHS.getSelector(),
486 RHS.getSelector());
487 }
Mike Stump1eb44332009-09-09 15:08:12 +0000488
Ted Kremenek553cf182008-06-25 21:21:56 +0000489};
Chris Lattner06159e82009-12-15 07:26:51 +0000490template <>
491struct isPodLike<ObjCSummaryKey> { static const bool value = true; };
Ted Kremenek4f22a782008-06-23 23:30:29 +0000492} // end llvm namespace
Mike Stump1eb44332009-09-09 15:08:12 +0000493
Ted Kremenek4f22a782008-06-23 23:30:29 +0000494namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000495class ObjCSummaryCache {
Ted Kremenek93edbc52011-10-05 23:54:29 +0000496 typedef llvm::DenseMap<ObjCSummaryKey, const RetainSummary *> MapTy;
Ted Kremenek553cf182008-06-25 21:21:56 +0000497 MapTy M;
498public:
499 ObjCSummaryCache() {}
Mike Stump1eb44332009-09-09 15:08:12 +0000500
Ted Kremenek93edbc52011-10-05 23:54:29 +0000501 const RetainSummary * find(const ObjCInterfaceDecl *D, IdentifierInfo *ClsName,
Ted Kremeneka8833552009-04-29 23:03:22 +0000502 Selector S) {
Ted Kremenek8711c032009-04-29 05:04:30 +0000503 // Lookup the method using the decl for the class @interface. If we
504 // have no decl, lookup using the class name.
505 return D ? find(D, S) : find(ClsName, S);
506 }
Mike Stump1eb44332009-09-09 15:08:12 +0000507
Ted Kremenek93edbc52011-10-05 23:54:29 +0000508 const RetainSummary * find(const ObjCInterfaceDecl *D, Selector S) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000509 // Do a lookup with the (D,S) pair. If we find a match return
510 // the iterator.
511 ObjCSummaryKey K(D, S);
512 MapTy::iterator I = M.find(K);
Mike Stump1eb44332009-09-09 15:08:12 +0000513
Ted Kremenek553cf182008-06-25 21:21:56 +0000514 if (I != M.end() || !D)
Ted Kremenek614cc542009-07-21 23:27:57 +0000515 return I->second;
Mike Stump1eb44332009-09-09 15:08:12 +0000516
Ted Kremenek553cf182008-06-25 21:21:56 +0000517 // Walk the super chain. If we find a hit with a parent, we'll end
518 // up returning that summary. We actually allow that key (null,S), as
519 // we cache summaries for the null ObjCInterfaceDecl* to allow us to
520 // generate initial summaries without having to worry about NSObject
521 // being declared.
522 // FIXME: We may change this at some point.
Ted Kremenek9c378f72011-08-12 23:37:29 +0000523 for (ObjCInterfaceDecl *C=D->getSuperClass() ;; C=C->getSuperClass()) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000524 if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
525 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000526
Ted Kremenek553cf182008-06-25 21:21:56 +0000527 if (!C)
Ted Kremenek614cc542009-07-21 23:27:57 +0000528 return NULL;
Ted Kremenek553cf182008-06-25 21:21:56 +0000529 }
Mike Stump1eb44332009-09-09 15:08:12 +0000530
531 // Cache the summary with original key to make the next lookup faster
Ted Kremenek553cf182008-06-25 21:21:56 +0000532 // and return the iterator.
Ted Kremenek93edbc52011-10-05 23:54:29 +0000533 const RetainSummary *Summ = I->second;
Ted Kremenek614cc542009-07-21 23:27:57 +0000534 M[K] = Summ;
535 return Summ;
Ted Kremenek553cf182008-06-25 21:21:56 +0000536 }
Mike Stump1eb44332009-09-09 15:08:12 +0000537
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000538 const RetainSummary *find(IdentifierInfo* II, Selector S) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000539 // FIXME: Class method lookup. Right now we dont' have a good way
540 // of going between IdentifierInfo* and the class hierarchy.
Ted Kremenek614cc542009-07-21 23:27:57 +0000541 MapTy::iterator I = M.find(ObjCSummaryKey(II, S));
Mike Stump1eb44332009-09-09 15:08:12 +0000542
Ted Kremenek614cc542009-07-21 23:27:57 +0000543 if (I == M.end())
544 I = M.find(ObjCSummaryKey(S));
Mike Stump1eb44332009-09-09 15:08:12 +0000545
Ted Kremenek614cc542009-07-21 23:27:57 +0000546 return I == M.end() ? NULL : I->second;
Ted Kremenek553cf182008-06-25 21:21:56 +0000547 }
Mike Stump1eb44332009-09-09 15:08:12 +0000548
Ted Kremenek93edbc52011-10-05 23:54:29 +0000549 const RetainSummary *& operator[](ObjCSummaryKey K) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000550 return M[K];
551 }
Mike Stump1eb44332009-09-09 15:08:12 +0000552
Ted Kremenek93edbc52011-10-05 23:54:29 +0000553 const RetainSummary *& operator[](Selector S) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000554 return M[ ObjCSummaryKey(S) ];
555 }
Mike Stump1eb44332009-09-09 15:08:12 +0000556};
Ted Kremenek553cf182008-06-25 21:21:56 +0000557} // end anonymous namespace
558
559//===----------------------------------------------------------------------===//
560// Data structures for managing collections of summaries.
561//===----------------------------------------------------------------------===//
562
563namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000564class RetainSummaryManager {
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000565
566 //==-----------------------------------------------------------------==//
567 // Typedefs.
568 //==-----------------------------------------------------------------==//
Mike Stump1eb44332009-09-09 15:08:12 +0000569
Ted Kremenek93edbc52011-10-05 23:54:29 +0000570 typedef llvm::DenseMap<const FunctionDecl*, const RetainSummary *>
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000571 FuncSummariesTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000572
Ted Kremenek4f22a782008-06-23 23:30:29 +0000573 typedef ObjCSummaryCache ObjCMethodSummariesTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000574
Jordy Roseef945882012-03-18 01:26:10 +0000575 typedef llvm::FoldingSetNodeWrapper<RetainSummary> CachedSummaryNode;
576
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000577 //==-----------------------------------------------------------------==//
578 // Data.
579 //==-----------------------------------------------------------------==//
Mike Stump1eb44332009-09-09 15:08:12 +0000580
Ted Kremenek553cf182008-06-25 21:21:56 +0000581 /// Ctx - The ASTContext object for the analyzed ASTs.
Ted Kremenek9c378f72011-08-12 23:37:29 +0000582 ASTContext &Ctx;
Ted Kremenek179064e2008-07-01 17:21:27 +0000583
Ted Kremenek553cf182008-06-25 21:21:56 +0000584 /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
Ted Kremenek377e2302008-04-29 05:33:51 +0000585 const bool GCEnabled;
Mike Stump1eb44332009-09-09 15:08:12 +0000586
John McCallf85e1932011-06-15 23:02:42 +0000587 /// Records whether or not the analyzed code runs in ARC mode.
588 const bool ARCEnabled;
589
Ted Kremenek553cf182008-06-25 21:21:56 +0000590 /// FuncSummaries - A map from FunctionDecls to summaries.
Mike Stump1eb44332009-09-09 15:08:12 +0000591 FuncSummariesTy FuncSummaries;
592
Ted Kremenek553cf182008-06-25 21:21:56 +0000593 /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
594 /// to summaries.
Ted Kremenek1f180c32008-06-23 22:21:20 +0000595 ObjCMethodSummariesTy ObjCClassMethodSummaries;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000596
Ted Kremenek553cf182008-06-25 21:21:56 +0000597 /// ObjCMethodSummaries - A map from selectors to summaries.
Ted Kremenek1f180c32008-06-23 22:21:20 +0000598 ObjCMethodSummariesTy ObjCMethodSummaries;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000599
Ted Kremenek553cf182008-06-25 21:21:56 +0000600 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
601 /// and all other data used by the checker.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000602 llvm::BumpPtrAllocator BPAlloc;
Mike Stump1eb44332009-09-09 15:08:12 +0000603
Ted Kremenekb77449c2009-05-03 05:20:50 +0000604 /// AF - A factory for ArgEffects objects.
Mike Stump1eb44332009-09-09 15:08:12 +0000605 ArgEffects::Factory AF;
606
Ted Kremenek553cf182008-06-25 21:21:56 +0000607 /// ScratchArgs - A holding buffer for construct ArgEffects.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000608 ArgEffects ScratchArgs;
Mike Stump1eb44332009-09-09 15:08:12 +0000609
Ted Kremenekec315332009-05-07 23:40:42 +0000610 /// ObjCAllocRetE - Default return effect for methods returning Objective-C
611 /// objects.
612 RetEffect ObjCAllocRetE;
Ted Kremenek547d4952009-06-05 23:18:01 +0000613
Mike Stump1eb44332009-09-09 15:08:12 +0000614 /// ObjCInitRetE - Default return effect for init methods returning
Ted Kremenekac02f202009-08-20 05:13:36 +0000615 /// Objective-C objects.
Ted Kremenek547d4952009-06-05 23:18:01 +0000616 RetEffect ObjCInitRetE;
Mike Stump1eb44332009-09-09 15:08:12 +0000617
Jordy Roseef945882012-03-18 01:26:10 +0000618 /// SimpleSummaries - Used for uniquing summaries that don't have special
619 /// effects.
620 llvm::FoldingSet<CachedSummaryNode> SimpleSummaries;
Mike Stump1eb44332009-09-09 15:08:12 +0000621
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000622 //==-----------------------------------------------------------------==//
623 // Methods.
624 //==-----------------------------------------------------------------==//
Mike Stump1eb44332009-09-09 15:08:12 +0000625
Ted Kremenek553cf182008-06-25 21:21:56 +0000626 /// getArgEffects - Returns a persistent ArgEffects object based on the
627 /// data in ScratchArgs.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000628 ArgEffects getArgEffects();
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000629
Mike Stump1eb44332009-09-09 15:08:12 +0000630 enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
631
Ted Kremenek896cd9d2008-10-23 01:56:15 +0000632public:
Ted Kremenek78a35a32009-05-12 20:06:54 +0000633 RetEffect getObjAllocRetEffect() const { return ObjCAllocRetE; }
Ted Kremenek93edbc52011-10-05 23:54:29 +0000634
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000635 const RetainSummary *getUnarySummary(const FunctionType* FT,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000636 UnaryFuncKind func);
Mike Stump1eb44332009-09-09 15:08:12 +0000637
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000638 const RetainSummary *getCFSummaryCreateRule(const FunctionDecl *FD);
639 const RetainSummary *getCFSummaryGetRule(const FunctionDecl *FD);
640 const RetainSummary *getCFCreateGetRuleSummary(const FunctionDecl *FD);
Mike Stump1eb44332009-09-09 15:08:12 +0000641
Jordy Roseef945882012-03-18 01:26:10 +0000642 const RetainSummary *getPersistentSummary(const RetainSummary &OldSumm);
Ted Kremenek706522f2008-10-29 04:07:07 +0000643
Jordy Roseef945882012-03-18 01:26:10 +0000644 const RetainSummary *getPersistentSummary(RetEffect RetEff,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000645 ArgEffect ReceiverEff = DoNothing,
646 ArgEffect DefaultEff = MayEscape) {
Jordy Roseef945882012-03-18 01:26:10 +0000647 RetainSummary Summ(getArgEffects(), RetEff, DefaultEff, ReceiverEff);
648 return getPersistentSummary(Summ);
649 }
650
651 const RetainSummary *getDefaultSummary() {
652 return getPersistentSummary(RetEffect::MakeNoRet(),
653 DoNothing, MayEscape);
Ted Kremenek9c32d082008-05-06 00:30:21 +0000654 }
Mike Stump1eb44332009-09-09 15:08:12 +0000655
Ted Kremenek93edbc52011-10-05 23:54:29 +0000656 const RetainSummary *getPersistentStopSummary() {
Jordy Roseef945882012-03-18 01:26:10 +0000657 return getPersistentSummary(RetEffect::MakeNoRet(),
658 StopTracking, StopTracking);
Mike Stump1eb44332009-09-09 15:08:12 +0000659 }
Ted Kremenekb3095252008-05-06 04:20:12 +0000660
Ted Kremenek1f180c32008-06-23 22:21:20 +0000661 void InitializeClassMethodSummaries();
662 void InitializeMethodSummaries();
Ted Kremenek896cd9d2008-10-23 01:56:15 +0000663private:
Ted Kremenek93edbc52011-10-05 23:54:29 +0000664 void addNSObjectClsMethSummary(Selector S, const RetainSummary *Summ) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000665 ObjCClassMethodSummaries[S] = Summ;
666 }
Mike Stump1eb44332009-09-09 15:08:12 +0000667
Ted Kremenek93edbc52011-10-05 23:54:29 +0000668 void addNSObjectMethSummary(Selector S, const RetainSummary *Summ) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000669 ObjCMethodSummaries[S] = Summ;
670 }
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +0000671
Ted Kremeneka9797122012-02-18 21:37:48 +0000672 void addClassMethSummary(const char* Cls, const char* name,
673 const RetainSummary *Summ, bool isNullary = true) {
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +0000674 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
Ted Kremeneka9797122012-02-18 21:37:48 +0000675 Selector S = isNullary ? GetNullarySelector(name, Ctx)
676 : GetUnarySelector(name, Ctx);
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +0000677 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
678 }
Mike Stump1eb44332009-09-09 15:08:12 +0000679
Ted Kremenek6c4becb2009-02-25 02:54:57 +0000680 void addInstMethSummary(const char* Cls, const char* nullaryName,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000681 const RetainSummary *Summ) {
Ted Kremenek6c4becb2009-02-25 02:54:57 +0000682 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
683 Selector S = GetNullarySelector(nullaryName, Ctx);
684 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
685 }
Mike Stump1eb44332009-09-09 15:08:12 +0000686
Ted Kremenekde4d5332009-04-24 17:50:11 +0000687 Selector generateSelector(va_list argp) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000688 SmallVector<IdentifierInfo*, 10> II;
Ted Kremenekde4d5332009-04-24 17:50:11 +0000689
Ted Kremenek9e476de2008-08-12 18:30:56 +0000690 while (const char* s = va_arg(argp, const char*))
691 II.push_back(&Ctx.Idents.get(s));
Ted Kremenekde4d5332009-04-24 17:50:11 +0000692
Mike Stump1eb44332009-09-09 15:08:12 +0000693 return Ctx.Selectors.getSelector(II.size(), &II[0]);
Ted Kremenekde4d5332009-04-24 17:50:11 +0000694 }
Mike Stump1eb44332009-09-09 15:08:12 +0000695
Ted Kremenekde4d5332009-04-24 17:50:11 +0000696 void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy& Summaries,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000697 const RetainSummary * Summ, va_list argp) {
Ted Kremenekde4d5332009-04-24 17:50:11 +0000698 Selector S = generateSelector(argp);
699 Summaries[ObjCSummaryKey(ClsII, S)] = Summ;
Ted Kremenek70a733e2008-07-18 17:24:20 +0000700 }
Mike Stump1eb44332009-09-09 15:08:12 +0000701
Ted Kremenek93edbc52011-10-05 23:54:29 +0000702 void addInstMethSummary(const char* Cls, const RetainSummary * Summ, ...) {
Ted Kremenekaf9dc272008-08-12 18:48:50 +0000703 va_list argp;
704 va_start(argp, Summ);
Ted Kremenekde4d5332009-04-24 17:50:11 +0000705 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Mike Stump1eb44332009-09-09 15:08:12 +0000706 va_end(argp);
Ted Kremenekaf9dc272008-08-12 18:48:50 +0000707 }
Mike Stump1eb44332009-09-09 15:08:12 +0000708
Ted Kremenek93edbc52011-10-05 23:54:29 +0000709 void addClsMethSummary(const char* Cls, const RetainSummary * Summ, ...) {
Ted Kremenekde4d5332009-04-24 17:50:11 +0000710 va_list argp;
711 va_start(argp, Summ);
712 addMethodSummary(&Ctx.Idents.get(Cls),ObjCClassMethodSummaries, Summ, argp);
713 va_end(argp);
714 }
Mike Stump1eb44332009-09-09 15:08:12 +0000715
Ted Kremenek93edbc52011-10-05 23:54:29 +0000716 void addClsMethSummary(IdentifierInfo *II, const RetainSummary * Summ, ...) {
Ted Kremenekde4d5332009-04-24 17:50:11 +0000717 va_list argp;
718 va_start(argp, Summ);
719 addMethodSummary(II, ObjCClassMethodSummaries, Summ, argp);
720 va_end(argp);
721 }
722
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000723public:
Mike Stump1eb44332009-09-09 15:08:12 +0000724
Ted Kremenek9c378f72011-08-12 23:37:29 +0000725 RetainSummaryManager(ASTContext &ctx, bool gcenabled, bool usesARC)
Ted Kremenek179064e2008-07-01 17:21:27 +0000726 : Ctx(ctx),
John McCallf85e1932011-06-15 23:02:42 +0000727 GCEnabled(gcenabled),
728 ARCEnabled(usesARC),
729 AF(BPAlloc), ScratchArgs(AF.getEmptyMap()),
730 ObjCAllocRetE(gcenabled
731 ? RetEffect::MakeGCNotOwned()
732 : (usesARC ? RetEffect::MakeARCNotOwned()
733 : RetEffect::MakeOwned(RetEffect::ObjC, true))),
734 ObjCInitRetE(gcenabled
735 ? RetEffect::MakeGCNotOwned()
736 : (usesARC ? RetEffect::MakeARCNotOwned()
Jordy Roseef945882012-03-18 01:26:10 +0000737 : RetEffect::MakeOwnedWhenTrackedReceiver())) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000738 InitializeClassMethodSummaries();
739 InitializeMethodSummaries();
740 }
Mike Stump1eb44332009-09-09 15:08:12 +0000741
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000742 const RetainSummary *getSummary(const FunctionDecl *FD);
Mike Stump1eb44332009-09-09 15:08:12 +0000743
Jordy Rosef3aae582012-03-17 21:13:07 +0000744 const RetainSummary *getMethodSummary(Selector S, IdentifierInfo *ClsName,
745 const ObjCInterfaceDecl *ID,
746 const ObjCMethodDecl *MD,
747 QualType RetTy,
748 ObjCMethodSummariesTy &CachedSummaries);
749
Ted Kremenek93edbc52011-10-05 23:54:29 +0000750 const RetainSummary *getInstanceMethodSummary(const ObjCMessage &msg,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000751 ProgramStateRef state,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000752 const LocationContext *LC);
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000753
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000754 const RetainSummary *getInstanceMethodSummary(const ObjCMessage &msg,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000755 const ObjCInterfaceDecl *ID) {
Jordy Rosef3aae582012-03-17 21:13:07 +0000756 return getMethodSummary(msg.getSelector(), 0, ID, msg.getMethodDecl(),
757 msg.getType(Ctx), ObjCMethodSummaries);
Ted Kremenek8711c032009-04-29 05:04:30 +0000758 }
Mike Stump1eb44332009-09-09 15:08:12 +0000759
Ted Kremenek93edbc52011-10-05 23:54:29 +0000760 const RetainSummary *getClassMethodSummary(const ObjCMessage &msg) {
Argyrios Kyrtzidis432424d2011-01-25 00:03:53 +0000761 const ObjCInterfaceDecl *Class = 0;
762 if (!msg.isInstanceMessage())
763 Class = msg.getReceiverInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +0000764
Jordy Rosef3aae582012-03-17 21:13:07 +0000765 return getMethodSummary(msg.getSelector(), Class->getIdentifier(),
766 Class, msg.getMethodDecl(), msg.getType(Ctx),
767 ObjCClassMethodSummaries);
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +0000768 }
Ted Kremenek552333c2009-04-29 17:17:48 +0000769
770 /// getMethodSummary - This version of getMethodSummary is used to query
771 /// the summary for the current method being analyzed.
Ted Kremenek93edbc52011-10-05 23:54:29 +0000772 const RetainSummary *getMethodSummary(const ObjCMethodDecl *MD) {
Ted Kremeneka8833552009-04-29 23:03:22 +0000773 // FIXME: Eventually this should be unneeded.
Ted Kremeneka8833552009-04-29 23:03:22 +0000774 const ObjCInterfaceDecl *ID = MD->getClassInterface();
Ted Kremenek70a65762009-04-30 05:41:14 +0000775 Selector S = MD->getSelector();
Ted Kremenek552333c2009-04-29 17:17:48 +0000776 IdentifierInfo *ClsName = ID->getIdentifier();
777 QualType ResultTy = MD->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +0000778
Jordy Rosef3aae582012-03-17 21:13:07 +0000779 ObjCMethodSummariesTy *CachedSummaries;
Ted Kremenek552333c2009-04-29 17:17:48 +0000780 if (MD->isInstanceMethod())
Jordy Rosef3aae582012-03-17 21:13:07 +0000781 CachedSummaries = &ObjCMethodSummaries;
Ted Kremenek552333c2009-04-29 17:17:48 +0000782 else
Jordy Rosef3aae582012-03-17 21:13:07 +0000783 CachedSummaries = &ObjCClassMethodSummaries;
784
785 return getMethodSummary(S, ClsName, ID, MD, ResultTy, *CachedSummaries);
Ted Kremenek552333c2009-04-29 17:17:48 +0000786 }
Mike Stump1eb44332009-09-09 15:08:12 +0000787
Jordy Rosef3aae582012-03-17 21:13:07 +0000788 const RetainSummary *getStandardMethodSummary(const ObjCMethodDecl *MD,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000789 Selector S, QualType RetTy);
Ted Kremeneka8833552009-04-29 23:03:22 +0000790
Ted Kremenek93edbc52011-10-05 23:54:29 +0000791 void updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenek4dd8fb42009-05-09 02:58:13 +0000792 const ObjCMethodDecl *MD);
793
Ted Kremenek93edbc52011-10-05 23:54:29 +0000794 void updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenek4dd8fb42009-05-09 02:58:13 +0000795 const FunctionDecl *FD);
796
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000797 bool isGCEnabled() const { return GCEnabled; }
Mike Stump1eb44332009-09-09 15:08:12 +0000798
John McCallf85e1932011-06-15 23:02:42 +0000799 bool isARCEnabled() const { return ARCEnabled; }
800
801 bool isARCorGCEnabled() const { return GCEnabled || ARCEnabled; }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000802};
Mike Stump1eb44332009-09-09 15:08:12 +0000803
Jordy Rose0fe62f82011-08-24 09:02:37 +0000804// Used to avoid allocating long-term (BPAlloc'd) memory for default retain
805// summaries. If a function or method looks like it has a default summary, but
806// it has annotations, the annotations are added to the stack-based template
807// and then copied into managed memory.
808class RetainSummaryTemplate {
809 RetainSummaryManager &Manager;
Ted Kremenek93edbc52011-10-05 23:54:29 +0000810 const RetainSummary *&RealSummary;
Jordy Rose0fe62f82011-08-24 09:02:37 +0000811 RetainSummary ScratchSummary;
812 bool Accessed;
813public:
Jordy Rosee921b1a2012-03-17 19:53:04 +0000814 RetainSummaryTemplate(const RetainSummary *&real, const RetainSummary &base,
815 RetainSummaryManager &mgr)
816 : Manager(mgr), RealSummary(real), ScratchSummary(real ? *real : base),
Ted Kremenek93edbc52011-10-05 23:54:29 +0000817 Accessed(false) {}
Jordy Rose0fe62f82011-08-24 09:02:37 +0000818
819 ~RetainSummaryTemplate() {
Ted Kremenek93edbc52011-10-05 23:54:29 +0000820 if (Accessed)
Jordy Roseef945882012-03-18 01:26:10 +0000821 RealSummary = Manager.getPersistentSummary(ScratchSummary);
Jordy Rose0fe62f82011-08-24 09:02:37 +0000822 }
823
824 RetainSummary &operator*() {
825 Accessed = true;
Ted Kremenek93edbc52011-10-05 23:54:29 +0000826 return ScratchSummary;
Jordy Rose0fe62f82011-08-24 09:02:37 +0000827 }
828
829 RetainSummary *operator->() {
830 Accessed = true;
Ted Kremenek93edbc52011-10-05 23:54:29 +0000831 return &ScratchSummary;
Jordy Rose0fe62f82011-08-24 09:02:37 +0000832 }
833};
834
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000835} // end anonymous namespace
836
837//===----------------------------------------------------------------------===//
838// Implementation of checker data structures.
839//===----------------------------------------------------------------------===//
840
Ted Kremenekb77449c2009-05-03 05:20:50 +0000841ArgEffects RetainSummaryManager::getArgEffects() {
842 ArgEffects AE = ScratchArgs;
Ted Kremenek3baf6722010-11-24 00:54:37 +0000843 ScratchArgs = AF.getEmptyMap();
Ted Kremenekb77449c2009-05-03 05:20:50 +0000844 return AE;
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000845}
846
Ted Kremenek93edbc52011-10-05 23:54:29 +0000847const RetainSummary *
Jordy Roseef945882012-03-18 01:26:10 +0000848RetainSummaryManager::getPersistentSummary(const RetainSummary &OldSumm) {
849 // Unique "simple" summaries -- those without ArgEffects.
850 if (OldSumm.isSimple()) {
851 llvm::FoldingSetNodeID ID;
852 OldSumm.Profile(ID);
853
854 void *Pos;
855 CachedSummaryNode *N = SimpleSummaries.FindNodeOrInsertPos(ID, Pos);
856
857 if (!N) {
858 N = (CachedSummaryNode *) BPAlloc.Allocate<CachedSummaryNode>();
859 new (N) CachedSummaryNode(OldSumm);
860 SimpleSummaries.InsertNode(N, Pos);
861 }
862
863 return &N->getValue();
864 }
865
Ted Kremenek93edbc52011-10-05 23:54:29 +0000866 RetainSummary *Summ = (RetainSummary *) BPAlloc.Allocate<RetainSummary>();
Jordy Roseef945882012-03-18 01:26:10 +0000867 new (Summ) RetainSummary(OldSumm);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000868 return Summ;
869}
870
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000871//===----------------------------------------------------------------------===//
872// Summary creation for functions (largely uses of Core Foundation).
873//===----------------------------------------------------------------------===//
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000874
Ted Kremenek9c378f72011-08-12 23:37:29 +0000875static bool isRetain(const FunctionDecl *FD, StringRef FName) {
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000876 return FName.endswith("Retain");
Ted Kremenek12619382009-01-12 21:45:02 +0000877}
878
Ted Kremenek9c378f72011-08-12 23:37:29 +0000879static bool isRelease(const FunctionDecl *FD, StringRef FName) {
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000880 return FName.endswith("Release");
Ted Kremenek12619382009-01-12 21:45:02 +0000881}
882
Jordy Rose76c506f2011-08-21 21:58:18 +0000883static bool isMakeCollectable(const FunctionDecl *FD, StringRef FName) {
884 // FIXME: Remove FunctionDecl parameter.
885 // FIXME: Is it really okay if MakeCollectable isn't a suffix?
886 return FName.find("MakeCollectable") != StringRef::npos;
887}
888
Ted Kremenek93edbc52011-10-05 23:54:29 +0000889const RetainSummary * RetainSummaryManager::getSummary(const FunctionDecl *FD) {
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000890 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000891 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000892 if (I != FuncSummaries.end())
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000893 return I->second;
894
Ted Kremeneke401a0c2009-05-04 15:34:07 +0000895 // No summary? Generate one.
Ted Kremenek93edbc52011-10-05 23:54:29 +0000896 const RetainSummary *S = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000897
Ted Kremenek37d785b2008-07-15 16:50:12 +0000898 do {
Ted Kremenek12619382009-01-12 21:45:02 +0000899 // We generate "stop" summaries for implicitly defined functions.
900 if (FD->isImplicit()) {
901 S = getPersistentStopSummary();
902 break;
Ted Kremenek37d785b2008-07-15 16:50:12 +0000903 }
Ted Kremenek9ca28512011-05-02 21:21:42 +0000904 // For C++ methods, generate an implicit "stop" summary as well. We
905 // can relax this once we have a clear policy for C++ methods and
906 // ownership attributes.
907 if (isa<CXXMethodDecl>(FD)) {
908 S = getPersistentStopSummary();
909 break;
910 }
Mike Stump1eb44332009-09-09 15:08:12 +0000911
John McCall183700f2009-09-21 23:43:11 +0000912 // [PR 3337] Use 'getAs<FunctionType>' to strip away any typedefs on the
Ted Kremenek99890652009-01-16 18:40:33 +0000913 // function's type.
John McCall183700f2009-09-21 23:43:11 +0000914 const FunctionType* FT = FD->getType()->getAs<FunctionType>();
Ted Kremenek48c6d182009-12-16 06:06:43 +0000915 const IdentifierInfo *II = FD->getIdentifier();
916 if (!II)
917 break;
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000918
919 StringRef FName = II->getName();
Mike Stump1eb44332009-09-09 15:08:12 +0000920
Ted Kremenekbf0a4dd2009-03-05 22:11:14 +0000921 // Strip away preceding '_'. Doing this here will effect all the checks
922 // down below.
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000923 FName = FName.substr(FName.find_first_not_of('_'));
Mike Stump1eb44332009-09-09 15:08:12 +0000924
Ted Kremenek12619382009-01-12 21:45:02 +0000925 // Inspect the result type.
926 QualType RetTy = FT->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +0000927
Ted Kremenek12619382009-01-12 21:45:02 +0000928 // FIXME: This should all be refactored into a chain of "summary lookup"
929 // filters.
Ted Kremenek008636a2009-10-14 00:27:24 +0000930 assert(ScratchArgs.isEmpty());
Ted Kremenek39d88b02009-06-15 20:36:07 +0000931
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000932 if (FName == "pthread_create") {
933 // Part of: <rdar://problem/7299394>. This will be addressed
934 // better with IPA.
935 S = getPersistentStopSummary();
936 } else if (FName == "NSMakeCollectable") {
937 // Handle: id NSMakeCollectable(CFTypeRef)
938 S = (RetTy->isObjCIdType())
939 ? getUnarySummary(FT, cfmakecollectable)
940 : getPersistentStopSummary();
941 } else if (FName == "IOBSDNameMatching" ||
942 FName == "IOServiceMatching" ||
943 FName == "IOServiceNameMatching" ||
944 FName == "IORegistryEntryIDMatching" ||
945 FName == "IOOpenFirmwarePathMatching") {
946 // Part of <rdar://problem/6961230>. (IOKit)
947 // This should be addressed using a API table.
948 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
949 DoNothing, DoNothing);
950 } else if (FName == "IOServiceGetMatchingService" ||
951 FName == "IOServiceGetMatchingServices") {
952 // FIXES: <rdar://problem/6326900>
953 // This should be addressed using a API table. This strcmp is also
954 // a little gross, but there is no need to super optimize here.
Ted Kremenek3baf6722010-11-24 00:54:37 +0000955 ScratchArgs = AF.add(ScratchArgs, 1, DecRef);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000956 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
957 } else if (FName == "IOServiceAddNotification" ||
958 FName == "IOServiceAddMatchingNotification") {
959 // Part of <rdar://problem/6961230>. (IOKit)
960 // This should be addressed using a API table.
Ted Kremenek3baf6722010-11-24 00:54:37 +0000961 ScratchArgs = AF.add(ScratchArgs, 2, DecRef);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000962 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
963 } else if (FName == "CVPixelBufferCreateWithBytes") {
964 // FIXES: <rdar://problem/7283567>
965 // Eventually this can be improved by recognizing that the pixel
966 // buffer passed to CVPixelBufferCreateWithBytes is released via
967 // a callback and doing full IPA to make sure this is done correctly.
968 // FIXME: This function has an out parameter that returns an
969 // allocated object.
Ted Kremenek3baf6722010-11-24 00:54:37 +0000970 ScratchArgs = AF.add(ScratchArgs, 7, StopTracking);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000971 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
972 } else if (FName == "CGBitmapContextCreateWithData") {
973 // FIXES: <rdar://problem/7358899>
974 // Eventually this can be improved by recognizing that 'releaseInfo'
975 // passed to CGBitmapContextCreateWithData is released via
976 // a callback and doing full IPA to make sure this is done correctly.
Ted Kremenek3baf6722010-11-24 00:54:37 +0000977 ScratchArgs = AF.add(ScratchArgs, 8, StopTracking);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000978 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
979 DoNothing, DoNothing);
980 } else if (FName == "CVPixelBufferCreateWithPlanarBytes") {
981 // FIXES: <rdar://problem/7283567>
982 // Eventually this can be improved by recognizing that the pixel
983 // buffer passed to CVPixelBufferCreateWithPlanarBytes is released
984 // via a callback and doing full IPA to make sure this is done
985 // correctly.
Ted Kremenek3baf6722010-11-24 00:54:37 +0000986 ScratchArgs = AF.add(ScratchArgs, 12, StopTracking);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000987 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenek06911d42012-03-22 06:29:41 +0000988 } else if (FName == "dispatch_set_context") {
989 // <rdar://problem/11059275> - The analyzer currently doesn't have
990 // a good way to reason about the finalizer function for libdispatch.
991 // If we pass a context object that is memory managed, stop tracking it.
992 // FIXME: this hack should possibly go away once we can handle
993 // libdispatch finalizers.
994 ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
995 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenekb04cb592009-06-11 18:17:24 +0000996 }
Mike Stump1eb44332009-09-09 15:08:12 +0000997
Ted Kremenekb04cb592009-06-11 18:17:24 +0000998 // Did we get a summary?
999 if (S)
1000 break;
Ted Kremenek61991902009-03-17 22:43:44 +00001001
1002 // Enable this code once the semantics of NSDeallocateObject are resolved
1003 // for GC. <rdar://problem/6619988>
1004#if 0
1005 // Handle: NSDeallocateObject(id anObject);
1006 // This method does allow 'nil' (although we don't check it now).
Mike Stump1eb44332009-09-09 15:08:12 +00001007 if (strcmp(FName, "NSDeallocateObject") == 0) {
Ted Kremenek61991902009-03-17 22:43:44 +00001008 return RetTy == Ctx.VoidTy
1009 ? getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, Dealloc)
1010 : getPersistentStopSummary();
1011 }
1012#endif
Ted Kremenek12619382009-01-12 21:45:02 +00001013
1014 if (RetTy->isPointerType()) {
1015 // For CoreFoundation ('CF') types.
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001016 if (cocoa::isRefType(RetTy, "CF", FName)) {
Ted Kremenek12619382009-01-12 21:45:02 +00001017 if (isRetain(FD, FName))
1018 S = getUnarySummary(FT, cfretain);
Jordy Rose76c506f2011-08-21 21:58:18 +00001019 else if (isMakeCollectable(FD, FName))
Ted Kremenek12619382009-01-12 21:45:02 +00001020 S = getUnarySummary(FT, cfmakecollectable);
Mike Stump1eb44332009-09-09 15:08:12 +00001021 else
John McCall7df2ff42011-10-01 00:48:56 +00001022 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek12619382009-01-12 21:45:02 +00001023
1024 break;
1025 }
1026
1027 // For CoreGraphics ('CG') types.
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001028 if (cocoa::isRefType(RetTy, "CG", FName)) {
Ted Kremenek12619382009-01-12 21:45:02 +00001029 if (isRetain(FD, FName))
1030 S = getUnarySummary(FT, cfretain);
1031 else
John McCall7df2ff42011-10-01 00:48:56 +00001032 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek12619382009-01-12 21:45:02 +00001033
1034 break;
1035 }
1036
1037 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001038 if (cocoa::isRefType(RetTy, "DADisk") ||
1039 cocoa::isRefType(RetTy, "DADissenter") ||
1040 cocoa::isRefType(RetTy, "DASessionRef")) {
John McCall7df2ff42011-10-01 00:48:56 +00001041 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek12619382009-01-12 21:45:02 +00001042 break;
1043 }
Mike Stump1eb44332009-09-09 15:08:12 +00001044
Ted Kremenek12619382009-01-12 21:45:02 +00001045 break;
1046 }
1047
1048 // Check for release functions, the only kind of functions that we care
1049 // about that don't return a pointer type.
1050 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
Ted Kremeneke7d03122010-02-08 16:45:01 +00001051 // Test for 'CGCF'.
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001052 FName = FName.substr(FName.startswith("CGCF") ? 4 : 2);
Ted Kremeneke7d03122010-02-08 16:45:01 +00001053
Ted Kremenekbf0a4dd2009-03-05 22:11:14 +00001054 if (isRelease(FD, FName))
Ted Kremenek12619382009-01-12 21:45:02 +00001055 S = getUnarySummary(FT, cfrelease);
1056 else {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001057 assert (ScratchArgs.isEmpty());
Ted Kremenek68189282009-01-29 22:45:13 +00001058 // Remaining CoreFoundation and CoreGraphics functions.
1059 // We use to assume that they all strictly followed the ownership idiom
1060 // and that ownership cannot be transferred. While this is technically
1061 // correct, many methods allow a tracked object to escape. For example:
1062 //
Mike Stump1eb44332009-09-09 15:08:12 +00001063 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
Ted Kremenek68189282009-01-29 22:45:13 +00001064 // CFDictionaryAddValue(y, key, x);
Mike Stump1eb44332009-09-09 15:08:12 +00001065 // CFRelease(x);
Ted Kremenek68189282009-01-29 22:45:13 +00001066 // ... it is okay to use 'x' since 'y' has a reference to it
1067 //
1068 // We handle this and similar cases with the follow heuristic. If the
Ted Kremenekc4843812009-08-20 00:57:22 +00001069 // function name contains "InsertValue", "SetValue", "AddValue",
1070 // "AppendValue", or "SetAttribute", then we assume that arguments may
1071 // "escape." This means that something else holds on to the object,
1072 // allowing it be used even after its local retain count drops to 0.
Benjamin Kramere45c1492010-01-11 19:46:28 +00001073 ArgEffect E = (StrInStrNoCase(FName, "InsertValue") != StringRef::npos||
1074 StrInStrNoCase(FName, "AddValue") != StringRef::npos ||
1075 StrInStrNoCase(FName, "SetValue") != StringRef::npos ||
1076 StrInStrNoCase(FName, "AppendValue") != StringRef::npos||
Benjamin Kramerc027e542010-01-11 20:15:06 +00001077 StrInStrNoCase(FName, "SetAttribute") != StringRef::npos)
Ted Kremenek68189282009-01-29 22:45:13 +00001078 ? MayEscape : DoNothing;
Mike Stump1eb44332009-09-09 15:08:12 +00001079
Ted Kremenek68189282009-01-29 22:45:13 +00001080 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek12619382009-01-12 21:45:02 +00001081 }
1082 }
Ted Kremenek37d785b2008-07-15 16:50:12 +00001083 }
1084 while (0);
Mike Stump1eb44332009-09-09 15:08:12 +00001085
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001086 // Annotations override defaults.
Jordy Rose4df54fe2011-08-23 04:27:15 +00001087 updateSummaryFromAnnotations(S, FD);
Mike Stump1eb44332009-09-09 15:08:12 +00001088
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001089 FuncSummaries[FD] = S;
Mike Stump1eb44332009-09-09 15:08:12 +00001090 return S;
Ted Kremenek2fff37e2008-03-06 00:08:09 +00001091}
1092
Ted Kremenek93edbc52011-10-05 23:54:29 +00001093const RetainSummary *
John McCall7df2ff42011-10-01 00:48:56 +00001094RetainSummaryManager::getCFCreateGetRuleSummary(const FunctionDecl *FD) {
1095 if (coreFoundation::followsCreateRule(FD))
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001096 return getCFSummaryCreateRule(FD);
Mike Stump1eb44332009-09-09 15:08:12 +00001097
Ted Kremenekd368d712011-05-25 06:19:45 +00001098 return getCFSummaryGetRule(FD);
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001099}
1100
Ted Kremenek93edbc52011-10-05 23:54:29 +00001101const RetainSummary *
Ted Kremenek6ad315a2009-02-23 16:51:39 +00001102RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1103 UnaryFuncKind func) {
1104
Ted Kremenek12619382009-01-12 21:45:02 +00001105 // Sanity check that this is *really* a unary function. This can
1106 // happen if people do weird things.
Douglas Gregor72564e72009-02-26 23:50:07 +00001107 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
Ted Kremenek12619382009-01-12 21:45:02 +00001108 if (!FTP || FTP->getNumArgs() != 1)
1109 return getPersistentStopSummary();
Mike Stump1eb44332009-09-09 15:08:12 +00001110
Ted Kremenekb77449c2009-05-03 05:20:50 +00001111 assert (ScratchArgs.isEmpty());
Mike Stump1eb44332009-09-09 15:08:12 +00001112
Jordy Rose76c506f2011-08-21 21:58:18 +00001113 ArgEffect Effect;
Ted Kremenek377e2302008-04-29 05:33:51 +00001114 switch (func) {
Jordy Rose76c506f2011-08-21 21:58:18 +00001115 case cfretain: Effect = IncRef; break;
1116 case cfrelease: Effect = DecRef; break;
1117 case cfmakecollectable: Effect = MakeCollectable; break;
Ted Kremenek940b1d82008-04-10 23:44:06 +00001118 }
Jordy Rose76c506f2011-08-21 21:58:18 +00001119
1120 ScratchArgs = AF.add(ScratchArgs, 0, Effect);
1121 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001122}
1123
Ted Kremenek93edbc52011-10-05 23:54:29 +00001124const RetainSummary *
Ted Kremenek9c378f72011-08-12 23:37:29 +00001125RetainSummaryManager::getCFSummaryCreateRule(const FunctionDecl *FD) {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001126 assert (ScratchArgs.isEmpty());
Mike Stump1eb44332009-09-09 15:08:12 +00001127
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001128 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001129}
1130
Ted Kremenek93edbc52011-10-05 23:54:29 +00001131const RetainSummary *
Ted Kremenek9c378f72011-08-12 23:37:29 +00001132RetainSummaryManager::getCFSummaryGetRule(const FunctionDecl *FD) {
Mike Stump1eb44332009-09-09 15:08:12 +00001133 assert (ScratchArgs.isEmpty());
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001134 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1135 DoNothing, DoNothing);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001136}
1137
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001138//===----------------------------------------------------------------------===//
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001139// Summary creation for Selectors.
1140//===----------------------------------------------------------------------===//
1141
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001142void
Ted Kremenek93edbc52011-10-05 23:54:29 +00001143RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001144 const FunctionDecl *FD) {
1145 if (!FD)
1146 return;
1147
Jordy Roseef945882012-03-18 01:26:10 +00001148 RetainSummaryTemplate Template(Summ, *getDefaultSummary(), *this);
Jordy Rose4df54fe2011-08-23 04:27:15 +00001149
Ted Kremenek11fe1752011-01-27 18:43:03 +00001150 // Effects on the parameters.
1151 unsigned parm_idx = 0;
1152 for (FunctionDecl::param_const_iterator pi = FD->param_begin(),
John McCall98b8f162011-04-06 09:02:12 +00001153 pe = FD->param_end(); pi != pe; ++pi, ++parm_idx) {
Ted Kremenek11fe1752011-01-27 18:43:03 +00001154 const ParmVarDecl *pd = *pi;
1155 if (pd->getAttr<NSConsumedAttr>()) {
Jordy Rose4df54fe2011-08-23 04:27:15 +00001156 if (!GCEnabled) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001157 Template->addArg(AF, parm_idx, DecRef);
Jordy Rose4df54fe2011-08-23 04:27:15 +00001158 }
1159 } else if (pd->getAttr<CFConsumedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001160 Template->addArg(AF, parm_idx, DecRef);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001161 }
1162 }
1163
Ted Kremenekb04cb592009-06-11 18:17:24 +00001164 QualType RetTy = FD->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00001165
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001166 // Determine if there is a special return effect for this method.
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001167 if (cocoa::isCocoaObjectRef(RetTy)) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001168 if (FD->getAttr<NSReturnsRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001169 Template->setRetEffect(ObjCAllocRetE);
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001170 }
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001171 else if (FD->getAttr<CFReturnsRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001172 Template->setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenekb04cb592009-06-11 18:17:24 +00001173 }
Ted Kremenek60411112010-02-18 00:06:12 +00001174 else if (FD->getAttr<NSReturnsNotRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001175 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::ObjC));
Ted Kremenek60411112010-02-18 00:06:12 +00001176 }
1177 else if (FD->getAttr<CFReturnsNotRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001178 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::CF));
Jordy Rose4df54fe2011-08-23 04:27:15 +00001179 }
1180 } else if (RetTy->getAs<PointerType>()) {
1181 if (FD->getAttr<CFReturnsRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001182 Template->setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
Jordy Rose4df54fe2011-08-23 04:27:15 +00001183 }
1184 else if (FD->getAttr<CFReturnsNotRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001185 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::CF));
Ted Kremenek60411112010-02-18 00:06:12 +00001186 }
Ted Kremenekb04cb592009-06-11 18:17:24 +00001187 }
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001188}
1189
1190void
Ted Kremenek93edbc52011-10-05 23:54:29 +00001191RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
1192 const ObjCMethodDecl *MD) {
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001193 if (!MD)
1194 return;
1195
Jordy Roseef945882012-03-18 01:26:10 +00001196 RetainSummaryTemplate Template(Summ, *getDefaultSummary(), *this);
Ted Kremenek6d4b76d2009-07-06 18:30:43 +00001197 bool isTrackedLoc = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001198
Ted Kremenek12b94342011-01-27 06:54:14 +00001199 // Effects on the receiver.
1200 if (MD->getAttr<NSConsumesSelfAttr>()) {
Ted Kremenek11fe1752011-01-27 18:43:03 +00001201 if (!GCEnabled)
Jordy Rose0fe62f82011-08-24 09:02:37 +00001202 Template->setReceiverEffect(DecRefMsg);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001203 }
1204
1205 // Effects on the parameters.
1206 unsigned parm_idx = 0;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00001207 for (ObjCMethodDecl::param_const_iterator
1208 pi=MD->param_begin(), pe=MD->param_end();
Ted Kremenek11fe1752011-01-27 18:43:03 +00001209 pi != pe; ++pi, ++parm_idx) {
1210 const ParmVarDecl *pd = *pi;
1211 if (pd->getAttr<NSConsumedAttr>()) {
1212 if (!GCEnabled)
Jordy Rose0fe62f82011-08-24 09:02:37 +00001213 Template->addArg(AF, parm_idx, DecRef);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001214 }
1215 else if(pd->getAttr<CFConsumedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001216 Template->addArg(AF, parm_idx, DecRef);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001217 }
Ted Kremenek12b94342011-01-27 06:54:14 +00001218 }
1219
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001220 // Determine if there is a special return effect for this method.
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001221 if (cocoa::isCocoaObjectRef(MD->getResultType())) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001222 if (MD->getAttr<NSReturnsRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001223 Template->setRetEffect(ObjCAllocRetE);
Ted Kremenek6d4b76d2009-07-06 18:30:43 +00001224 return;
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001225 }
Ted Kremenek60411112010-02-18 00:06:12 +00001226 if (MD->getAttr<NSReturnsNotRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001227 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::ObjC));
Ted Kremenek60411112010-02-18 00:06:12 +00001228 return;
1229 }
Mike Stump1eb44332009-09-09 15:08:12 +00001230
Ted Kremenek6d4b76d2009-07-06 18:30:43 +00001231 isTrackedLoc = true;
Jordy Rose0fe62f82011-08-24 09:02:37 +00001232 } else {
Ted Kremenek6217b802009-07-29 21:53:49 +00001233 isTrackedLoc = MD->getResultType()->getAs<PointerType>() != NULL;
Jordy Rose0fe62f82011-08-24 09:02:37 +00001234 }
Mike Stump1eb44332009-09-09 15:08:12 +00001235
Ted Kremenek60411112010-02-18 00:06:12 +00001236 if (isTrackedLoc) {
1237 if (MD->getAttr<CFReturnsRetainedAttr>())
Jordy Rose0fe62f82011-08-24 09:02:37 +00001238 Template->setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenek60411112010-02-18 00:06:12 +00001239 else if (MD->getAttr<CFReturnsNotRetainedAttr>())
Jordy Rose0fe62f82011-08-24 09:02:37 +00001240 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::CF));
Ted Kremenek60411112010-02-18 00:06:12 +00001241 }
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001242}
1243
Ted Kremenek93edbc52011-10-05 23:54:29 +00001244const RetainSummary *
Jordy Rosef3aae582012-03-17 21:13:07 +00001245RetainSummaryManager::getStandardMethodSummary(const ObjCMethodDecl *MD,
1246 Selector S, QualType RetTy) {
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001247
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +00001248 if (MD) {
Ted Kremenek376d1e72009-04-24 18:00:17 +00001249 // Scan the method decl for 'void*' arguments. These should be treated
1250 // as 'StopTracking' because they are often used with delegates.
1251 // Delegates are a frequent form of false positives with the retain
1252 // count checker.
1253 unsigned i = 0;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00001254 for (ObjCMethodDecl::param_const_iterator I = MD->param_begin(),
Ted Kremenek376d1e72009-04-24 18:00:17 +00001255 E = MD->param_end(); I != E; ++I, ++i)
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00001256 if (const ParmVarDecl *PD = *I) {
Ted Kremenek376d1e72009-04-24 18:00:17 +00001257 QualType Ty = Ctx.getCanonicalType(PD->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001258 if (Ty.getLocalUnqualifiedType() == Ctx.VoidPtrTy)
Ted Kremenek3baf6722010-11-24 00:54:37 +00001259 ScratchArgs = AF.add(ScratchArgs, i, StopTracking);
Ted Kremenek376d1e72009-04-24 18:00:17 +00001260 }
1261 }
Mike Stump1eb44332009-09-09 15:08:12 +00001262
Jordy Rosee921b1a2012-03-17 19:53:04 +00001263 // Any special effects?
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001264 ArgEffect ReceiverEff = DoNothing;
Jordy Rosee921b1a2012-03-17 19:53:04 +00001265 RetEffect ResultEff = RetEffect::MakeNoRet();
1266
1267 // Check the method family, and apply any default annotations.
1268 switch (MD ? MD->getMethodFamily() : S.getMethodFamily()) {
1269 case OMF_None:
1270 case OMF_performSelector:
1271 // Assume all Objective-C methods follow Cocoa Memory Management rules.
1272 // FIXME: Does the non-threaded performSelector family really belong here?
1273 // The selector could be, say, @selector(copy).
1274 if (cocoa::isCocoaObjectRef(RetTy))
1275 ResultEff = RetEffect::MakeNotOwned(RetEffect::ObjC);
1276 else if (coreFoundation::isCFObjectRef(RetTy)) {
1277 // ObjCMethodDecl currently doesn't consider CF objects as valid return
1278 // values for alloc, new, copy, or mutableCopy, so we have to
1279 // double-check with the selector. This is ugly, but there aren't that
1280 // many Objective-C methods that return CF objects, right?
1281 if (MD) {
1282 switch (S.getMethodFamily()) {
1283 case OMF_alloc:
1284 case OMF_new:
1285 case OMF_copy:
1286 case OMF_mutableCopy:
1287 ResultEff = RetEffect::MakeOwned(RetEffect::CF, true);
1288 break;
1289 default:
1290 ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1291 break;
1292 }
1293 } else {
1294 ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1295 }
1296 }
1297 break;
1298 case OMF_init:
1299 ResultEff = ObjCInitRetE;
1300 ReceiverEff = DecRefMsg;
1301 break;
1302 case OMF_alloc:
1303 case OMF_new:
1304 case OMF_copy:
1305 case OMF_mutableCopy:
1306 if (cocoa::isCocoaObjectRef(RetTy))
1307 ResultEff = ObjCAllocRetE;
1308 else if (coreFoundation::isCFObjectRef(RetTy))
1309 ResultEff = RetEffect::MakeOwned(RetEffect::CF, true);
1310 break;
1311 case OMF_autorelease:
1312 ReceiverEff = Autorelease;
1313 break;
1314 case OMF_retain:
1315 ReceiverEff = IncRefMsg;
1316 break;
1317 case OMF_release:
1318 ReceiverEff = DecRefMsg;
1319 break;
1320 case OMF_dealloc:
1321 ReceiverEff = Dealloc;
1322 break;
1323 case OMF_self:
1324 // -self is handled specially by the ExprEngine to propagate the receiver.
1325 break;
1326 case OMF_retainCount:
1327 case OMF_finalize:
1328 // These methods don't return objects.
1329 break;
1330 }
Mike Stump1eb44332009-09-09 15:08:12 +00001331
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001332 // If one of the arguments in the selector has the keyword 'delegate' we
1333 // should stop tracking the reference count for the receiver. This is
1334 // because the reference count is quite possibly handled by a delegate
1335 // method.
1336 if (S.isKeywordSelector()) {
1337 const std::string &str = S.getAsString();
1338 assert(!str.empty());
Benjamin Kramere45c1492010-01-11 19:46:28 +00001339 if (StrInStrNoCase(str, "delegate:") != StringRef::npos)
1340 ReceiverEff = StopTracking;
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001341 }
Mike Stump1eb44332009-09-09 15:08:12 +00001342
Jordy Rosee921b1a2012-03-17 19:53:04 +00001343 if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing &&
1344 ResultEff.getKind() == RetEffect::NoRet)
Ted Kremenek93edbc52011-10-05 23:54:29 +00001345 return getDefaultSummary();
Mike Stump1eb44332009-09-09 15:08:12 +00001346
Jordy Rosee921b1a2012-03-17 19:53:04 +00001347 return getPersistentSummary(ResultEff, ReceiverEff, MayEscape);
Ted Kremenek250b1fa2009-04-23 23:08:22 +00001348}
1349
Ted Kremenek93edbc52011-10-05 23:54:29 +00001350const RetainSummary *
Argyrios Kyrtzidis432424d2011-01-25 00:03:53 +00001351RetainSummaryManager::getInstanceMethodSummary(const ObjCMessage &msg,
Ted Kremenek8bef8232012-01-26 21:29:00 +00001352 ProgramStateRef state,
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001353 const LocationContext *LC) {
1354
1355 // We need the type-information of the tracked receiver object
1356 // Retrieve it from the state.
Argyrios Kyrtzidis432424d2011-01-25 00:03:53 +00001357 const Expr *Receiver = msg.getInstanceReceiver();
Ted Kremenek9c378f72011-08-12 23:37:29 +00001358 const ObjCInterfaceDecl *ID = 0;
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001359
1360 // FIXME: Is this really working as expected? There are cases where
1361 // we just use the 'ID' from the message expression.
Douglas Gregor04badcf2010-04-21 00:45:42 +00001362 SVal receiverV;
1363
Ted Kremenek8f326752010-05-21 21:56:53 +00001364 if (Receiver) {
Ted Kremenek5eca4822012-01-06 22:09:28 +00001365 receiverV = state->getSValAsScalarOrLoc(Receiver, LC);
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00001366
Douglas Gregor04badcf2010-04-21 00:45:42 +00001367 // FIXME: Eventually replace the use of state->get<RefBindings> with
1368 // a generic API for reasoning about the Objective-C types of symbolic
1369 // objects.
1370 if (SymbolRef Sym = receiverV.getAsLocSymbol())
1371 if (const RefVal *T = state->get<RefBindings>(Sym))
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00001372 if (const ObjCObjectPointerType* PT =
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001373 T->getType()->getAs<ObjCObjectPointerType>())
Douglas Gregor04badcf2010-04-21 00:45:42 +00001374 ID = PT->getInterfaceDecl();
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00001375
Douglas Gregor04badcf2010-04-21 00:45:42 +00001376 // FIXME: this is a hack. This may or may not be the actual method
1377 // that is called.
1378 if (!ID) {
1379 if (const ObjCObjectPointerType *PT =
1380 Receiver->getType()->getAs<ObjCObjectPointerType>())
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001381 ID = PT->getInterfaceDecl();
Douglas Gregor04badcf2010-04-21 00:45:42 +00001382 }
1383 } else {
1384 // FIXME: Hack for 'super'.
Argyrios Kyrtzidis432424d2011-01-25 00:03:53 +00001385 ID = msg.getReceiverInterface();
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001386 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001387
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001388 // FIXME: The receiver could be a reference to a class, meaning that
1389 // we should use the class method.
Jordy Rose4df54fe2011-08-23 04:27:15 +00001390 return getInstanceMethodSummary(msg, ID);
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001391}
1392
Ted Kremenek93edbc52011-10-05 23:54:29 +00001393const RetainSummary *
Jordy Rosef3aae582012-03-17 21:13:07 +00001394RetainSummaryManager::getMethodSummary(Selector S, IdentifierInfo *ClsName,
1395 const ObjCInterfaceDecl *ID,
1396 const ObjCMethodDecl *MD, QualType RetTy,
1397 ObjCMethodSummariesTy &CachedSummaries) {
Ted Kremenek1bffd742008-05-06 15:44:25 +00001398
Ted Kremenek8711c032009-04-29 05:04:30 +00001399 // Look up a summary in our summary cache.
Jordy Rosef3aae582012-03-17 21:13:07 +00001400 const RetainSummary *Summ = CachedSummaries.find(ID, ClsName, S);
Mike Stump1eb44332009-09-09 15:08:12 +00001401
Ted Kremenek614cc542009-07-21 23:27:57 +00001402 if (!Summ) {
Jordy Rosef3aae582012-03-17 21:13:07 +00001403 Summ = getStandardMethodSummary(MD, S, RetTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001404
Ted Kremenek614cc542009-07-21 23:27:57 +00001405 // Annotations override defaults.
Jordy Rose4df54fe2011-08-23 04:27:15 +00001406 updateSummaryFromAnnotations(Summ, MD);
Mike Stump1eb44332009-09-09 15:08:12 +00001407
Ted Kremenek614cc542009-07-21 23:27:57 +00001408 // Memoize the summary.
Jordy Rosef3aae582012-03-17 21:13:07 +00001409 CachedSummaries[ObjCSummaryKey(ID, ClsName, S)] = Summ;
Ted Kremenek614cc542009-07-21 23:27:57 +00001410 }
Mike Stump1eb44332009-09-09 15:08:12 +00001411
Ted Kremeneke87450e2009-04-23 19:11:35 +00001412 return Summ;
Ted Kremenekc8395602008-05-06 21:26:51 +00001413}
1414
Mike Stump1eb44332009-09-09 15:08:12 +00001415void RetainSummaryManager::InitializeClassMethodSummaries() {
Ted Kremenekec315332009-05-07 23:40:42 +00001416 assert(ScratchArgs.isEmpty());
Mike Stump1eb44332009-09-09 15:08:12 +00001417 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek6fe2b7a2009-10-15 22:25:12 +00001418 addClassMethSummary("NSAssertionHandler", "currentHandler",
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001419 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Mike Stump1eb44332009-09-09 15:08:12 +00001420
Ted Kremenek6d348932008-10-21 15:53:15 +00001421 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001422 ScratchArgs = AF.add(ScratchArgs, 0, Autorelease);
Ted Kremenek6fe2b7a2009-10-15 22:25:12 +00001423 addClassMethSummary("NSAutoreleasePool", "addObject",
1424 getPersistentSummary(RetEffect::MakeNoRet(),
1425 DoNothing, Autorelease));
Mike Stump1eb44332009-09-09 15:08:12 +00001426
Ted Kremenekde4d5332009-04-24 17:50:11 +00001427 // Create the summaries for [NSObject performSelector...]. We treat
1428 // these as 'stop tracking' for the arguments because they are often
1429 // used for delegates that can release the object. When we have better
1430 // inter-procedural analysis we can potentially do something better. This
1431 // workaround is to remove false positives.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001432 const RetainSummary *Summ =
Ted Kremenek012614e2011-08-17 21:04:19 +00001433 getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, StopTracking);
Ted Kremenekde4d5332009-04-24 17:50:11 +00001434 IdentifierInfo *NSObjectII = &Ctx.Idents.get("NSObject");
1435 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1436 "afterDelay", NULL);
1437 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1438 "afterDelay", "inModes", NULL);
1439 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1440 "withObject", "waitUntilDone", NULL);
1441 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1442 "withObject", "waitUntilDone", "modes", NULL);
1443 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1444 "withObject", "waitUntilDone", NULL);
1445 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1446 "withObject", "waitUntilDone", "modes", NULL);
1447 addClsMethSummary(NSObjectII, Summ, "performSelectorInBackground",
1448 "withObject", NULL);
Ted Kremenek9c32d082008-05-06 00:30:21 +00001449}
1450
Ted Kremenek1f180c32008-06-23 22:21:20 +00001451void RetainSummaryManager::InitializeMethodSummaries() {
Mike Stump1eb44332009-09-09 15:08:12 +00001452
1453 assert (ScratchArgs.isEmpty());
1454
Ted Kremenekc8395602008-05-06 21:26:51 +00001455 // Create the "init" selector. It just acts as a pass-through for the
1456 // receiver.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001457 const RetainSummary *InitSumm = getPersistentSummary(ObjCInitRetE, DecRefMsg);
Ted Kremenekac02f202009-08-20 05:13:36 +00001458 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
1459
1460 // awakeAfterUsingCoder: behaves basically like an 'init' method. It
1461 // claims the receiver and returns a retained object.
1462 addNSObjectMethSummary(GetUnarySelector("awakeAfterUsingCoder", Ctx),
1463 InitSumm);
Mike Stump1eb44332009-09-09 15:08:12 +00001464
Ted Kremenekc8395602008-05-06 21:26:51 +00001465 // The next methods are allocators.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001466 const RetainSummary *AllocSumm = getPersistentSummary(ObjCAllocRetE);
1467 const RetainSummary *CFAllocSumm =
Ted Kremeneka834fb42009-08-28 19:52:12 +00001468 getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Mike Stump1eb44332009-09-09 15:08:12 +00001469
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001470 // Create the "retain" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001471 RetEffect NoRet = RetEffect::MakeNoRet();
Ted Kremenek93edbc52011-10-05 23:54:29 +00001472 const RetainSummary *Summ = getPersistentSummary(NoRet, IncRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001473 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001474
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001475 // Create the "release" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001476 Summ = getPersistentSummary(NoRet, DecRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001477 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001478
Ted Kremenek299e8152008-05-07 21:17:39 +00001479 // Create the "drain" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001480 Summ = getPersistentSummary(NoRet, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek553cf182008-06-25 21:21:56 +00001481 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001482
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001483 // Create the -dealloc summary.
Jordy Rose500abad2011-08-21 19:41:36 +00001484 Summ = getPersistentSummary(NoRet, Dealloc);
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001485 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001486
1487 // Create the "autorelease" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001488 Summ = getPersistentSummary(NoRet, Autorelease);
Ted Kremenek553cf182008-06-25 21:21:56 +00001489 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001490
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00001491 // Specially handle NSAutoreleasePool.
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001492 addInstMethSummary("NSAutoreleasePool", "init",
Jordy Rose500abad2011-08-21 19:41:36 +00001493 getPersistentSummary(NoRet, NewAutoreleasePool));
Mike Stump1eb44332009-09-09 15:08:12 +00001494
1495 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremenek89e202d2009-02-23 02:51:29 +00001496 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1497 // self-own themselves. However, they only do this once they are displayed.
1498 // Thus, we need to track an NSWindow's display status.
1499 // This is tracked in <rdar://problem/6062711>.
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +00001500 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001501 const RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenek78a35a32009-05-12 20:06:54 +00001502 StopTracking,
1503 StopTracking);
Mike Stump1eb44332009-09-09 15:08:12 +00001504
Ted Kremenek99d02692009-04-03 19:02:51 +00001505 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1506
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +00001507#if 0
Ted Kremenek78a35a32009-05-12 20:06:54 +00001508 addInstMethSummary("NSWindow", NoTrackYet, "initWithContentRect",
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001509 "styleMask", "backing", "defer", NULL);
Mike Stump1eb44332009-09-09 15:08:12 +00001510
Ted Kremenek78a35a32009-05-12 20:06:54 +00001511 addInstMethSummary("NSWindow", NoTrackYet, "initWithContentRect",
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001512 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +00001513#endif
Mike Stump1eb44332009-09-09 15:08:12 +00001514
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001515 // For NSPanel (which subclasses NSWindow), allocated objects are not
1516 // self-owned.
Ted Kremenek99d02692009-04-03 19:02:51 +00001517 // FIXME: For now we don't track NSPanels. object for the same reason
1518 // as for NSWindow objects.
1519 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
Mike Stump1eb44332009-09-09 15:08:12 +00001520
Ted Kremenek78a35a32009-05-12 20:06:54 +00001521#if 0
1522 addInstMethSummary("NSPanel", 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("NSPanel", NoTrackYet, "initWithContentRect",
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001526 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek78a35a32009-05-12 20:06:54 +00001527#endif
Mike Stump1eb44332009-09-09 15:08:12 +00001528
Ted Kremenekba67f6a2009-05-18 23:14:34 +00001529 // Don't track allocated autorelease pools yet, as it is okay to prematurely
1530 // exit a method.
1531 addClassMethSummary("NSAutoreleasePool", "alloc", NoTrackYet);
Ted Kremeneka9797122012-02-18 21:37:48 +00001532 addClassMethSummary("NSAutoreleasePool", "allocWithZone", NoTrackYet, false);
Ted Kremenek553cf182008-06-25 21:21:56 +00001533
Ted Kremenek767d6492009-05-20 22:39:57 +00001534 // Create summaries QCRenderer/QCView -createSnapShotImageOfType:
1535 addInstMethSummary("QCRenderer", AllocSumm,
1536 "createSnapshotImageOfType", NULL);
1537 addInstMethSummary("QCView", AllocSumm,
1538 "createSnapshotImageOfType", NULL);
1539
Ted Kremenek211a9c62009-06-15 20:58:58 +00001540 // Create summaries for CIContext, 'createCGImage' and
Ted Kremeneka834fb42009-08-28 19:52:12 +00001541 // 'createCGLayerWithSize'. These objects are CF objects, and are not
1542 // automatically garbage collected.
1543 addInstMethSummary("CIContext", CFAllocSumm,
Ted Kremenek767d6492009-05-20 22:39:57 +00001544 "createCGImage", "fromRect", NULL);
Ted Kremeneka834fb42009-08-28 19:52:12 +00001545 addInstMethSummary("CIContext", CFAllocSumm,
Mike Stump1eb44332009-09-09 15:08:12 +00001546 "createCGImage", "fromRect", "format", "colorSpace", NULL);
Ted Kremeneka834fb42009-08-28 19:52:12 +00001547 addInstMethSummary("CIContext", CFAllocSumm, "createCGLayerWithSize",
Ted Kremenek211a9c62009-06-15 20:58:58 +00001548 "info", NULL);
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001549}
1550
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001551//===----------------------------------------------------------------------===//
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001552// AutoreleaseBindings - State used to track objects in autorelease pools.
Ted Kremenek6d348932008-10-21 15:53:15 +00001553//===----------------------------------------------------------------------===//
1554
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001555typedef llvm::ImmutableMap<SymbolRef, unsigned> ARCounts;
1556typedef llvm::ImmutableMap<SymbolRef, ARCounts> ARPoolContents;
1557typedef llvm::ImmutableList<SymbolRef> ARStack;
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00001558
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001559static int AutoRCIndex = 0;
Ted Kremenek6d348932008-10-21 15:53:15 +00001560static int AutoRBIndex = 0;
1561
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001562namespace { class AutoreleasePoolContents {}; }
1563namespace { class AutoreleaseStack {}; }
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001564
Ted Kremenek6d348932008-10-21 15:53:15 +00001565namespace clang {
Ted Kremenek9ef65372010-12-23 07:20:52 +00001566namespace ento {
Ted Kremenek18c66fd2011-08-15 22:09:50 +00001567template<> struct ProgramStateTrait<AutoreleaseStack>
1568 : public ProgramStatePartialTrait<ARStack> {
Ted Kremenek9c378f72011-08-12 23:37:29 +00001569 static inline void *GDMIndex() { return &AutoRBIndex; }
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001570};
1571
Ted Kremenek18c66fd2011-08-15 22:09:50 +00001572template<> struct ProgramStateTrait<AutoreleasePoolContents>
1573 : public ProgramStatePartialTrait<ARPoolContents> {
Ted Kremenek9c378f72011-08-12 23:37:29 +00001574 static inline void *GDMIndex() { return &AutoRCIndex; }
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001575};
Argyrios Kyrtzidis5a4f98f2010-12-22 18:53:20 +00001576} // end GR namespace
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001577} // end clang namespace
Ted Kremenek6d348932008-10-21 15:53:15 +00001578
Ted Kremenek8bef8232012-01-26 21:29:00 +00001579static SymbolRef GetCurrentAutoreleasePool(ProgramStateRef state) {
Ted Kremenek7037ab82009-03-20 17:34:15 +00001580 ARStack stack = state->get<AutoreleaseStack>();
1581 return stack.isEmpty() ? SymbolRef() : stack.getHead();
1582}
1583
Ted Kremenek8bef8232012-01-26 21:29:00 +00001584static ProgramStateRef
1585SendAutorelease(ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +00001586 ARCounts::Factory &F,
1587 SymbolRef sym) {
Ted Kremenek7037ab82009-03-20 17:34:15 +00001588 SymbolRef pool = GetCurrentAutoreleasePool(state);
Ted Kremenekb65be702009-06-18 01:23:53 +00001589 const ARCounts *cnts = state->get<AutoreleasePoolContents>(pool);
Ted Kremenek7037ab82009-03-20 17:34:15 +00001590 ARCounts newCnts(0);
Mike Stump1eb44332009-09-09 15:08:12 +00001591
Ted Kremenek7037ab82009-03-20 17:34:15 +00001592 if (cnts) {
1593 const unsigned *cnt = (*cnts).lookup(sym);
Ted Kremenek3baf6722010-11-24 00:54:37 +00001594 newCnts = F.add(*cnts, sym, cnt ? *cnt + 1 : 1);
Ted Kremenek7037ab82009-03-20 17:34:15 +00001595 }
1596 else
Ted Kremenek3baf6722010-11-24 00:54:37 +00001597 newCnts = F.add(F.getEmptyMap(), sym, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001598
Ted Kremenekb65be702009-06-18 01:23:53 +00001599 return state->set<AutoreleasePoolContents>(pool, newCnts);
Ted Kremenek7037ab82009-03-20 17:34:15 +00001600}
1601
Ted Kremenek13922612008-04-16 20:40:59 +00001602//===----------------------------------------------------------------------===//
Ted Kremenekc887d132009-04-29 18:50:19 +00001603// Error reporting.
1604//===----------------------------------------------------------------------===//
Ted Kremenekc887d132009-04-29 18:50:19 +00001605namespace {
Jordy Roseec9ef852011-08-23 20:55:48 +00001606 typedef llvm::DenseMap<const ExplodedNode *, const RetainSummary *>
1607 SummaryLogTy;
1608
Ted Kremenekc887d132009-04-29 18:50:19 +00001609 //===-------------===//
1610 // Bug Descriptions. //
Mike Stump1eb44332009-09-09 15:08:12 +00001611 //===-------------===//
1612
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001613 class CFRefBug : public BugType {
Ted Kremenekc887d132009-04-29 18:50:19 +00001614 protected:
Jordy Rose35c86952011-08-24 05:47:39 +00001615 CFRefBug(StringRef name)
1616 : BugType(name, "Memory (Core Foundation/Objective-C)") {}
Ted Kremenekc887d132009-04-29 18:50:19 +00001617 public:
Mike Stump1eb44332009-09-09 15:08:12 +00001618
Ted Kremenekc887d132009-04-29 18:50:19 +00001619 // FIXME: Eventually remove.
Jordy Rose35c86952011-08-24 05:47:39 +00001620 virtual const char *getDescription() const = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001621
Ted Kremenekc887d132009-04-29 18:50:19 +00001622 virtual bool isLeak() const { return false; }
1623 };
Mike Stump1eb44332009-09-09 15:08:12 +00001624
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001625 class UseAfterRelease : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001626 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001627 UseAfterRelease() : CFRefBug("Use-after-release") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001628
Jordy Rose35c86952011-08-24 05:47:39 +00001629 const char *getDescription() const {
Ted Kremenekc887d132009-04-29 18:50:19 +00001630 return "Reference-counted object is used after it is released";
Mike Stump1eb44332009-09-09 15:08:12 +00001631 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001632 };
Mike Stump1eb44332009-09-09 15:08:12 +00001633
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001634 class BadRelease : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001635 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001636 BadRelease() : CFRefBug("Bad release") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001637
Jordy Rose35c86952011-08-24 05:47:39 +00001638 const char *getDescription() const {
Ted Kremenekbb206fd2009-10-01 17:31:50 +00001639 return "Incorrect decrement of the reference count of an object that is "
1640 "not owned at this point by the caller";
Ted Kremenekc887d132009-04-29 18:50:19 +00001641 }
1642 };
Mike Stump1eb44332009-09-09 15:08:12 +00001643
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001644 class DeallocGC : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001645 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001646 DeallocGC()
1647 : CFRefBug("-dealloc called while using garbage collection") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001648
Ted Kremenekc887d132009-04-29 18:50:19 +00001649 const char *getDescription() const {
Ted Kremenek369de562009-05-09 00:10:05 +00001650 return "-dealloc called while using garbage collection";
Ted Kremenekc887d132009-04-29 18:50:19 +00001651 }
1652 };
Mike Stump1eb44332009-09-09 15:08:12 +00001653
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001654 class DeallocNotOwned : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001655 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001656 DeallocNotOwned()
1657 : CFRefBug("-dealloc sent to non-exclusively owned object") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001658
Ted Kremenekc887d132009-04-29 18:50:19 +00001659 const char *getDescription() const {
1660 return "-dealloc sent to object that may be referenced elsewhere";
1661 }
Mike Stump1eb44332009-09-09 15:08:12 +00001662 };
1663
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001664 class OverAutorelease : public CFRefBug {
Ted Kremenek369de562009-05-09 00:10:05 +00001665 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001666 OverAutorelease()
1667 : CFRefBug("Object sent -autorelease too many times") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001668
Ted Kremenek369de562009-05-09 00:10:05 +00001669 const char *getDescription() const {
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001670 return "Object sent -autorelease too many times";
Ted Kremenek369de562009-05-09 00:10:05 +00001671 }
1672 };
Mike Stump1eb44332009-09-09 15:08:12 +00001673
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001674 class ReturnedNotOwnedForOwned : public CFRefBug {
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001675 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001676 ReturnedNotOwnedForOwned()
1677 : CFRefBug("Method should return an owned object") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001678
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001679 const char *getDescription() const {
Jordy Rose5b5402b2011-07-15 22:17:54 +00001680 return "Object with a +0 retain count returned to caller where a +1 "
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001681 "(owning) retain count is expected";
1682 }
1683 };
Mike Stump1eb44332009-09-09 15:08:12 +00001684
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001685 class Leak : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001686 const bool isReturn;
1687 protected:
Jordy Rose35c86952011-08-24 05:47:39 +00001688 Leak(StringRef name, bool isRet)
Jordy Rosedb92bb62011-08-25 01:14:38 +00001689 : CFRefBug(name), isReturn(isRet) {
1690 // Leaks should not be reported if they are post-dominated by a sink.
1691 setSuppressOnSink(true);
1692 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001693 public:
Mike Stump1eb44332009-09-09 15:08:12 +00001694
Jordy Rose35c86952011-08-24 05:47:39 +00001695 const char *getDescription() const { return ""; }
Mike Stump1eb44332009-09-09 15:08:12 +00001696
Ted Kremenekc887d132009-04-29 18:50:19 +00001697 bool isLeak() const { return true; }
1698 };
Mike Stump1eb44332009-09-09 15:08:12 +00001699
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001700 class LeakAtReturn : public Leak {
Ted Kremenekc887d132009-04-29 18:50:19 +00001701 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001702 LeakAtReturn(StringRef name)
1703 : Leak(name, true) {}
Ted Kremenekc887d132009-04-29 18:50:19 +00001704 };
Mike Stump1eb44332009-09-09 15:08:12 +00001705
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001706 class LeakWithinFunction : public Leak {
Ted Kremenekc887d132009-04-29 18:50:19 +00001707 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001708 LeakWithinFunction(StringRef name)
1709 : Leak(name, false) {}
Mike Stump1eb44332009-09-09 15:08:12 +00001710 };
1711
Ted Kremenekc887d132009-04-29 18:50:19 +00001712 //===---------===//
1713 // Bug Reports. //
1714 //===---------===//
Mike Stump1eb44332009-09-09 15:08:12 +00001715
Anna Zaksdc757b02011-08-19 23:21:56 +00001716 class CFRefReportVisitor : public BugReporterVisitor {
Anna Zaks23f395e2011-08-20 01:27:22 +00001717 protected:
Anna Zaksdc757b02011-08-19 23:21:56 +00001718 SymbolRef Sym;
Jordy Roseec9ef852011-08-23 20:55:48 +00001719 const SummaryLogTy &SummaryLog;
Jordy Rose35c86952011-08-24 05:47:39 +00001720 bool GCEnabled;
Anna Zaks23f395e2011-08-20 01:27:22 +00001721
Anna Zaksdc757b02011-08-19 23:21:56 +00001722 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001723 CFRefReportVisitor(SymbolRef sym, bool gcEnabled, const SummaryLogTy &log)
1724 : Sym(sym), SummaryLog(log), GCEnabled(gcEnabled) {}
Anna Zaksdc757b02011-08-19 23:21:56 +00001725
Anna Zaks23f395e2011-08-20 01:27:22 +00001726 virtual void Profile(llvm::FoldingSetNodeID &ID) const {
Anna Zaksdc757b02011-08-19 23:21:56 +00001727 static int x = 0;
1728 ID.AddPointer(&x);
1729 ID.AddPointer(Sym);
1730 }
1731
Anna Zaks23f395e2011-08-20 01:27:22 +00001732 virtual PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
1733 const ExplodedNode *PrevN,
1734 BugReporterContext &BRC,
1735 BugReport &BR);
1736
1737 virtual PathDiagnosticPiece *getEndPath(BugReporterContext &BRC,
1738 const ExplodedNode *N,
1739 BugReport &BR);
1740 };
1741
1742 class CFRefLeakReportVisitor : public CFRefReportVisitor {
1743 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001744 CFRefLeakReportVisitor(SymbolRef sym, bool GCEnabled,
Jordy Roseec9ef852011-08-23 20:55:48 +00001745 const SummaryLogTy &log)
Jordy Rose35c86952011-08-24 05:47:39 +00001746 : CFRefReportVisitor(sym, GCEnabled, log) {}
Anna Zaks23f395e2011-08-20 01:27:22 +00001747
1748 PathDiagnosticPiece *getEndPath(BugReporterContext &BRC,
1749 const ExplodedNode *N,
1750 BugReport &BR);
Anna Zaksdc757b02011-08-19 23:21:56 +00001751 };
1752
Anna Zakse172e8b2011-08-17 23:00:25 +00001753 class CFRefReport : public BugReport {
Jordy Rose20589562011-08-24 22:39:09 +00001754 void addGCModeDescription(const LangOptions &LOpts, bool GCEnabled);
Jordy Rose35c86952011-08-24 05:47:39 +00001755
Ted Kremenekc887d132009-04-29 18:50:19 +00001756 public:
Jordy Rose20589562011-08-24 22:39:09 +00001757 CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1758 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1759 bool registerVisitor = true)
Anna Zaksedf4dae2011-08-22 18:54:07 +00001760 : BugReport(D, D.getDescription(), n) {
Anna Zaks23f395e2011-08-20 01:27:22 +00001761 if (registerVisitor)
Jordy Rose20589562011-08-24 22:39:09 +00001762 addVisitor(new CFRefReportVisitor(sym, GCEnabled, Log));
1763 addGCModeDescription(LOpts, GCEnabled);
Anna Zaksdc757b02011-08-19 23:21:56 +00001764 }
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001765
Jordy Rose20589562011-08-24 22:39:09 +00001766 CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1767 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1768 StringRef endText)
Anna Zaksedf4dae2011-08-22 18:54:07 +00001769 : BugReport(D, D.getDescription(), endText, n) {
Jordy Rose20589562011-08-24 22:39:09 +00001770 addVisitor(new CFRefReportVisitor(sym, GCEnabled, Log));
1771 addGCModeDescription(LOpts, GCEnabled);
Anna Zaksdc757b02011-08-19 23:21:56 +00001772 }
Mike Stump1eb44332009-09-09 15:08:12 +00001773
Anna Zakse172e8b2011-08-17 23:00:25 +00001774 virtual std::pair<ranges_iterator, ranges_iterator> getRanges() {
Anna Zaksedf4dae2011-08-22 18:54:07 +00001775 const CFRefBug& BugTy = static_cast<CFRefBug&>(getBugType());
1776 if (!BugTy.isLeak())
Anna Zakse172e8b2011-08-17 23:00:25 +00001777 return BugReport::getRanges();
Ted Kremenekc887d132009-04-29 18:50:19 +00001778 else
Argyrios Kyrtzidis640ccf02010-12-04 01:12:15 +00001779 return std::make_pair(ranges_iterator(), ranges_iterator());
Ted Kremenekc887d132009-04-29 18:50:19 +00001780 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001781 };
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001782
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001783 class CFRefLeakReport : public CFRefReport {
Ted Kremenekc887d132009-04-29 18:50:19 +00001784 const MemRegion* AllocBinding;
Anna Zaks23f395e2011-08-20 01:27:22 +00001785
Ted Kremenekc887d132009-04-29 18:50:19 +00001786 public:
Jordy Rose20589562011-08-24 22:39:09 +00001787 CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1788 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
Anna Zaks6a93bd52011-10-25 19:57:11 +00001789 CheckerContext &Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001790
Anna Zaks590dd8e2011-09-20 21:38:35 +00001791 PathDiagnosticLocation getLocation(const SourceManager &SM) const {
1792 assert(Location.isValid());
1793 return Location;
1794 }
Mike Stump1eb44332009-09-09 15:08:12 +00001795 };
Ted Kremenekc887d132009-04-29 18:50:19 +00001796} // end anonymous namespace
1797
Jordy Rose20589562011-08-24 22:39:09 +00001798void CFRefReport::addGCModeDescription(const LangOptions &LOpts,
1799 bool GCEnabled) {
Jordy Rosef95b19d2011-08-24 20:38:42 +00001800 const char *GCModeDescription = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001801
Douglas Gregore289d812011-09-13 17:21:33 +00001802 switch (LOpts.getGC()) {
Anna Zaks7f2531c2011-08-22 20:31:28 +00001803 case LangOptions::GCOnly:
Jordy Rose20589562011-08-24 22:39:09 +00001804 assert(GCEnabled);
Jordy Rose35c86952011-08-24 05:47:39 +00001805 GCModeDescription = "Code is compiled to only use garbage collection";
1806 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001807
Anna Zaks7f2531c2011-08-22 20:31:28 +00001808 case LangOptions::NonGC:
Jordy Rose20589562011-08-24 22:39:09 +00001809 assert(!GCEnabled);
Jordy Rose35c86952011-08-24 05:47:39 +00001810 GCModeDescription = "Code is compiled to use reference counts";
1811 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001812
Anna Zaks7f2531c2011-08-22 20:31:28 +00001813 case LangOptions::HybridGC:
Jordy Rose20589562011-08-24 22:39:09 +00001814 if (GCEnabled) {
Jordy Rose35c86952011-08-24 05:47:39 +00001815 GCModeDescription = "Code is compiled to use either garbage collection "
1816 "(GC) or reference counts (non-GC). The bug occurs "
1817 "with GC enabled";
1818 break;
1819 } else {
1820 GCModeDescription = "Code is compiled to use either garbage collection "
1821 "(GC) or reference counts (non-GC). The bug occurs "
1822 "in non-GC mode";
1823 break;
Anna Zaks7f2531c2011-08-22 20:31:28 +00001824 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001825 }
Jordy Rose35c86952011-08-24 05:47:39 +00001826
Jordy Rosef95b19d2011-08-24 20:38:42 +00001827 assert(GCModeDescription && "invalid/unknown GC mode");
Jordy Rose35c86952011-08-24 05:47:39 +00001828 addExtraText(GCModeDescription);
Ted Kremenekc887d132009-04-29 18:50:19 +00001829}
1830
Jordy Rose910c4052011-09-02 06:44:22 +00001831// FIXME: This should be a method on SmallVector.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001832static inline bool contains(const SmallVectorImpl<ArgEffect>& V,
Ted Kremenekc887d132009-04-29 18:50:19 +00001833 ArgEffect X) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001834 for (SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
Ted Kremenekc887d132009-04-29 18:50:19 +00001835 I!=E; ++I)
1836 if (*I == X) return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001837
Ted Kremenekc887d132009-04-29 18:50:19 +00001838 return false;
1839}
1840
Ted Kremenek4c42bb72011-11-14 21:59:21 +00001841static bool isPropertyAccess(const Stmt *S, ParentMap &PM) {
1842 unsigned maxDepth = 4;
1843 while (S && maxDepth) {
1844 if (const PseudoObjectExpr *PO = dyn_cast<PseudoObjectExpr>(S)) {
1845 if (!isa<ObjCMessageExpr>(PO->getSyntacticForm()))
1846 return true;
1847 return false;
1848 }
1849 S = PM.getParent(S);
1850 --maxDepth;
1851 }
1852 return false;
1853}
1854
Anna Zaksdc757b02011-08-19 23:21:56 +00001855PathDiagnosticPiece *CFRefReportVisitor::VisitNode(const ExplodedNode *N,
1856 const ExplodedNode *PrevN,
1857 BugReporterContext &BRC,
1858 BugReport &BR) {
Mike Stump1eb44332009-09-09 15:08:12 +00001859
Jordy Rosef53e8c72011-08-23 19:43:16 +00001860 if (!isa<StmtPoint>(N->getLocation()))
Ted Kremenek2033a952009-05-13 07:12:33 +00001861 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001862
Ted Kremenek8966bc12009-05-06 21:39:49 +00001863 // Check if the type state has changed.
Ted Kremenek8bef8232012-01-26 21:29:00 +00001864 ProgramStateRef PrevSt = PrevN->getState();
1865 ProgramStateRef CurrSt = N->getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001866 const LocationContext *LCtx = N->getLocationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00001867
1868 const RefVal* CurrT = CurrSt->get<RefBindings>(Sym);
Ted Kremenekc887d132009-04-29 18:50:19 +00001869 if (!CurrT) return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001870
Ted Kremenekb65be702009-06-18 01:23:53 +00001871 const RefVal &CurrV = *CurrT;
1872 const RefVal *PrevT = PrevSt->get<RefBindings>(Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00001873
Ted Kremenekc887d132009-04-29 18:50:19 +00001874 // Create a string buffer to constain all the useful things we want
1875 // to tell the user.
1876 std::string sbuf;
1877 llvm::raw_string_ostream os(sbuf);
Mike Stump1eb44332009-09-09 15:08:12 +00001878
Ted Kremenekc887d132009-04-29 18:50:19 +00001879 // This is the allocation site since the previous node had no bindings
1880 // for this symbol.
1881 if (!PrevT) {
Jordy Rosef53e8c72011-08-23 19:43:16 +00001882 const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
Mike Stump1eb44332009-09-09 15:08:12 +00001883
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001884 if (isa<ObjCArrayLiteral>(S)) {
1885 os << "NSArray literal is an object with a +0 retain count";
Mike Stump1eb44332009-09-09 15:08:12 +00001886 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001887 else if (isa<ObjCDictionaryLiteral>(S)) {
1888 os << "NSDictionary literal is an object with a +0 retain count";
Ted Kremenekc887d132009-04-29 18:50:19 +00001889 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001890 else {
1891 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
1892 // Get the name of the callee (if it is available).
1893 SVal X = CurrSt->getSValAsScalarOrLoc(CE->getCallee(), LCtx);
1894 if (const FunctionDecl *FD = X.getAsFunctionDecl())
1895 os << "Call to function '" << *FD << '\'';
1896 else
1897 os << "function call";
Ted Kremenekc887d132009-04-29 18:50:19 +00001898 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001899 else {
1900 assert(isa<ObjCMessageExpr>(S));
1901 // The message expression may have between written directly or as
1902 // a property access. Lazily determine which case we are looking at.
1903 os << (isPropertyAccess(S, N->getParentMap()) ? "Property" : "Method");
1904 }
1905
1906 if (CurrV.getObjKind() == RetEffect::CF) {
1907 os << " returns a Core Foundation object with a ";
1908 }
1909 else {
1910 assert (CurrV.getObjKind() == RetEffect::ObjC);
1911 os << " returns an Objective-C object with a ";
1912 }
1913
1914 if (CurrV.isOwned()) {
1915 os << "+1 retain count";
1916
1917 if (GCEnabled) {
1918 assert(CurrV.getObjKind() == RetEffect::CF);
1919 os << ". "
1920 "Core Foundation objects are not automatically garbage collected.";
1921 }
1922 }
1923 else {
1924 assert (CurrV.isNotOwned());
1925 os << "+0 retain count";
1926 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001927 }
Mike Stump1eb44332009-09-09 15:08:12 +00001928
Anna Zaks220ac8c2011-09-15 01:08:34 +00001929 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
1930 N->getLocationContext());
Ted Kremenekc887d132009-04-29 18:50:19 +00001931 return new PathDiagnosticEventPiece(Pos, os.str());
1932 }
Mike Stump1eb44332009-09-09 15:08:12 +00001933
Ted Kremenekc887d132009-04-29 18:50:19 +00001934 // Gather up the effects that were performed on the object at this
1935 // program point
Chris Lattner5f9e2722011-07-23 10:55:15 +00001936 SmallVector<ArgEffect, 2> AEffects;
Mike Stump1eb44332009-09-09 15:08:12 +00001937
Jordy Roseec9ef852011-08-23 20:55:48 +00001938 const ExplodedNode *OrigNode = BRC.getNodeResolver().getOriginalNode(N);
1939 if (const RetainSummary *Summ = SummaryLog.lookup(OrigNode)) {
Ted Kremenekc887d132009-04-29 18:50:19 +00001940 // We only have summaries attached to nodes after evaluating CallExpr and
1941 // ObjCMessageExprs.
Jordy Rosef53e8c72011-08-23 19:43:16 +00001942 const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
Mike Stump1eb44332009-09-09 15:08:12 +00001943
Ted Kremenek5f85e172009-07-22 22:35:28 +00001944 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
Ted Kremenekc887d132009-04-29 18:50:19 +00001945 // Iterate through the parameter expressions and see if the symbol
1946 // was ever passed as an argument.
1947 unsigned i = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001948
Ted Kremenek5f85e172009-07-22 22:35:28 +00001949 for (CallExpr::const_arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
Ted Kremenekc887d132009-04-29 18:50:19 +00001950 AI!=AE; ++AI, ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00001951
Ted Kremenekc887d132009-04-29 18:50:19 +00001952 // Retrieve the value of the argument. Is it the symbol
1953 // we are interested in?
Ted Kremenek5eca4822012-01-06 22:09:28 +00001954 if (CurrSt->getSValAsScalarOrLoc(*AI, LCtx).getAsLocSymbol() != Sym)
Ted Kremenekc887d132009-04-29 18:50:19 +00001955 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001956
Ted Kremenekc887d132009-04-29 18:50:19 +00001957 // We have an argument. Get the effect!
1958 AEffects.push_back(Summ->getArg(i));
1959 }
1960 }
Mike Stump1eb44332009-09-09 15:08:12 +00001961 else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00001962 if (const Expr *receiver = ME->getInstanceReceiver())
Ted Kremenek5eca4822012-01-06 22:09:28 +00001963 if (CurrSt->getSValAsScalarOrLoc(receiver, LCtx)
1964 .getAsLocSymbol() == Sym) {
Ted Kremenekc887d132009-04-29 18:50:19 +00001965 // The symbol we are tracking is the receiver.
1966 AEffects.push_back(Summ->getReceiverEffect());
1967 }
1968 }
1969 }
Mike Stump1eb44332009-09-09 15:08:12 +00001970
Ted Kremenekc887d132009-04-29 18:50:19 +00001971 do {
1972 // Get the previous type state.
1973 RefVal PrevV = *PrevT;
Mike Stump1eb44332009-09-09 15:08:12 +00001974
Ted Kremenekc887d132009-04-29 18:50:19 +00001975 // Specially handle -dealloc.
Jordy Rose35c86952011-08-24 05:47:39 +00001976 if (!GCEnabled && contains(AEffects, Dealloc)) {
Ted Kremenekc887d132009-04-29 18:50:19 +00001977 // Determine if the object's reference count was pushed to zero.
1978 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
1979 // We may not have transitioned to 'release' if we hit an error.
1980 // This case is handled elsewhere.
1981 if (CurrV.getKind() == RefVal::Released) {
Ted Kremenekf21332e2009-05-08 20:01:42 +00001982 assert(CurrV.getCombinedCounts() == 0);
Ted Kremenekc887d132009-04-29 18:50:19 +00001983 os << "Object released by directly sending the '-dealloc' message";
1984 break;
1985 }
1986 }
Mike Stump1eb44332009-09-09 15:08:12 +00001987
Ted Kremenekc887d132009-04-29 18:50:19 +00001988 // Specially handle CFMakeCollectable and friends.
1989 if (contains(AEffects, MakeCollectable)) {
1990 // Get the name of the function.
Jordy Rosef53e8c72011-08-23 19:43:16 +00001991 const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001992 SVal X =
1993 CurrSt->getSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee(), LCtx);
Ted Kremenek9c378f72011-08-12 23:37:29 +00001994 const FunctionDecl *FD = X.getAsFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001995
Jordy Rose35c86952011-08-24 05:47:39 +00001996 if (GCEnabled) {
Ted Kremenekc887d132009-04-29 18:50:19 +00001997 // Determine if the object's reference count was pushed to zero.
1998 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
Mike Stump1eb44332009-09-09 15:08:12 +00001999
Benjamin Kramerb8989f22011-10-14 18:45:37 +00002000 os << "In GC mode a call to '" << *FD
Ted Kremenekc887d132009-04-29 18:50:19 +00002001 << "' decrements an object's retain count and registers the "
2002 "object with the garbage collector. ";
Mike Stump1eb44332009-09-09 15:08:12 +00002003
Ted Kremenekc887d132009-04-29 18:50:19 +00002004 if (CurrV.getKind() == RefVal::Released) {
2005 assert(CurrV.getCount() == 0);
2006 os << "Since it now has a 0 retain count the object can be "
2007 "automatically collected by the garbage collector.";
2008 }
2009 else
2010 os << "An object must have a 0 retain count to be garbage collected. "
2011 "After this call its retain count is +" << CurrV.getCount()
2012 << '.';
2013 }
Mike Stump1eb44332009-09-09 15:08:12 +00002014 else
Benjamin Kramerb8989f22011-10-14 18:45:37 +00002015 os << "When GC is not enabled a call to '" << *FD
Ted Kremenekc887d132009-04-29 18:50:19 +00002016 << "' has no effect on its argument.";
Mike Stump1eb44332009-09-09 15:08:12 +00002017
Ted Kremenekc887d132009-04-29 18:50:19 +00002018 // Nothing more to say.
2019 break;
2020 }
Mike Stump1eb44332009-09-09 15:08:12 +00002021
2022 // Determine if the typestate has changed.
Ted Kremenekc887d132009-04-29 18:50:19 +00002023 if (!(PrevV == CurrV))
2024 switch (CurrV.getKind()) {
2025 case RefVal::Owned:
2026 case RefVal::NotOwned:
Mike Stump1eb44332009-09-09 15:08:12 +00002027
Ted Kremenekf21332e2009-05-08 20:01:42 +00002028 if (PrevV.getCount() == CurrV.getCount()) {
2029 // Did an autorelease message get sent?
2030 if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
2031 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002032
Zhongxing Xu264e9372009-05-12 10:10:00 +00002033 assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount());
Ted Kremenekeaedfea2009-05-10 05:11:21 +00002034 os << "Object sent -autorelease message";
Ted Kremenekf21332e2009-05-08 20:01:42 +00002035 break;
2036 }
Mike Stump1eb44332009-09-09 15:08:12 +00002037
Ted Kremenekc887d132009-04-29 18:50:19 +00002038 if (PrevV.getCount() > CurrV.getCount())
2039 os << "Reference count decremented.";
2040 else
2041 os << "Reference count incremented.";
Mike Stump1eb44332009-09-09 15:08:12 +00002042
Ted Kremenekc887d132009-04-29 18:50:19 +00002043 if (unsigned Count = CurrV.getCount())
2044 os << " The object now has a +" << Count << " retain count.";
Mike Stump1eb44332009-09-09 15:08:12 +00002045
Ted Kremenekc887d132009-04-29 18:50:19 +00002046 if (PrevV.getKind() == RefVal::Released) {
Jordy Rose35c86952011-08-24 05:47:39 +00002047 assert(GCEnabled && CurrV.getCount() > 0);
Jordy Rose74b7b2b2012-03-17 05:49:15 +00002048 os << " The object is not eligible for garbage collection until "
2049 "the retain count reaches 0 again.";
Ted Kremenekc887d132009-04-29 18:50:19 +00002050 }
Mike Stump1eb44332009-09-09 15:08:12 +00002051
Ted Kremenekc887d132009-04-29 18:50:19 +00002052 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002053
Ted Kremenekc887d132009-04-29 18:50:19 +00002054 case RefVal::Released:
2055 os << "Object released.";
2056 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002057
Ted Kremenekc887d132009-04-29 18:50:19 +00002058 case RefVal::ReturnedOwned:
Jordy Rose74b7b2b2012-03-17 05:49:15 +00002059 // Autoreleases can be applied after marking a node ReturnedOwned.
2060 if (CurrV.getAutoreleaseCount())
2061 return NULL;
2062
2063 os << "Object returned to caller as an owning reference (single "
2064 "retain count transferred to caller)";
Ted Kremenekc887d132009-04-29 18:50:19 +00002065 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002066
Ted Kremenekc887d132009-04-29 18:50:19 +00002067 case RefVal::ReturnedNotOwned:
Ted Kremenekf1365462011-05-26 18:45:44 +00002068 os << "Object returned to caller with a +0 retain count";
Ted Kremenekc887d132009-04-29 18:50:19 +00002069 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002070
Ted Kremenekc887d132009-04-29 18:50:19 +00002071 default:
2072 return NULL;
2073 }
Mike Stump1eb44332009-09-09 15:08:12 +00002074
Ted Kremenekc887d132009-04-29 18:50:19 +00002075 // Emit any remaining diagnostics for the argument effects (if any).
Chris Lattner5f9e2722011-07-23 10:55:15 +00002076 for (SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
Ted Kremenekc887d132009-04-29 18:50:19 +00002077 E=AEffects.end(); I != E; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +00002078
Ted Kremenekc887d132009-04-29 18:50:19 +00002079 // A bunch of things have alternate behavior under GC.
Jordy Rose35c86952011-08-24 05:47:39 +00002080 if (GCEnabled)
Ted Kremenekc887d132009-04-29 18:50:19 +00002081 switch (*I) {
2082 default: break;
2083 case Autorelease:
2084 os << "In GC mode an 'autorelease' has no effect.";
2085 continue;
2086 case IncRefMsg:
2087 os << "In GC mode the 'retain' message has no effect.";
2088 continue;
2089 case DecRefMsg:
2090 os << "In GC mode the 'release' message has no effect.";
2091 continue;
2092 }
2093 }
Mike Stump1eb44332009-09-09 15:08:12 +00002094 } while (0);
2095
Ted Kremenekc887d132009-04-29 18:50:19 +00002096 if (os.str().empty())
2097 return 0; // We have nothing to say!
Ted Kremenek2033a952009-05-13 07:12:33 +00002098
Jordy Rosef53e8c72011-08-23 19:43:16 +00002099 const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
Anna Zaks220ac8c2011-09-15 01:08:34 +00002100 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
2101 N->getLocationContext());
Ted Kremenek9c378f72011-08-12 23:37:29 +00002102 PathDiagnosticPiece *P = new PathDiagnosticEventPiece(Pos, os.str());
Mike Stump1eb44332009-09-09 15:08:12 +00002103
Ted Kremenekc887d132009-04-29 18:50:19 +00002104 // Add the range by scanning the children of the statement for any bindings
2105 // to Sym.
Mike Stump1eb44332009-09-09 15:08:12 +00002106 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
Ted Kremenek5f85e172009-07-22 22:35:28 +00002107 I!=E; ++I)
Ted Kremenek9c378f72011-08-12 23:37:29 +00002108 if (const Expr *Exp = dyn_cast_or_null<Expr>(*I))
Ted Kremenek5eca4822012-01-06 22:09:28 +00002109 if (CurrSt->getSValAsScalarOrLoc(Exp, LCtx).getAsLocSymbol() == Sym) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002110 P->addRange(Exp->getSourceRange());
2111 break;
2112 }
Mike Stump1eb44332009-09-09 15:08:12 +00002113
Ted Kremenekc887d132009-04-29 18:50:19 +00002114 return P;
2115}
2116
Anna Zakse7e01682012-02-28 22:39:22 +00002117// Find the first node in the current function context that referred to the
2118// tracked symbol and the memory location that value was stored to. Note, the
2119// value is only reported if the allocation occurred in the same function as
2120// the leak.
Zhongxing Xuc5619d92009-08-06 01:32:16 +00002121static std::pair<const ExplodedNode*,const MemRegion*>
Ted Kremenek18c66fd2011-08-15 22:09:50 +00002122GetAllocationSite(ProgramStateManager& StateMgr, const ExplodedNode *N,
Ted Kremenekc887d132009-04-29 18:50:19 +00002123 SymbolRef Sym) {
Ted Kremenek9c378f72011-08-12 23:37:29 +00002124 const ExplodedNode *Last = N;
Mike Stump1eb44332009-09-09 15:08:12 +00002125 const MemRegion* FirstBinding = 0;
Anna Zakse7e01682012-02-28 22:39:22 +00002126 const LocationContext *LeakContext = N->getLocationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002127
Ted Kremenekc887d132009-04-29 18:50:19 +00002128 while (N) {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002129 ProgramStateRef St = N->getState();
Ted Kremenekc887d132009-04-29 18:50:19 +00002130 RefBindings B = St->get<RefBindings>();
Mike Stump1eb44332009-09-09 15:08:12 +00002131
Ted Kremenekc887d132009-04-29 18:50:19 +00002132 if (!B.lookup(Sym))
2133 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002134
Anna Zaks27b867e2012-03-21 19:45:01 +00002135 StoreManager::FindUniqueBinding FB(Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002136 StateMgr.iterBindings(St, FB);
2137 if (FB) FirstBinding = FB.getRegion();
2138
Anna Zakse7e01682012-02-28 22:39:22 +00002139 // Allocation node, is the last node in the current context in which the
2140 // symbol was tracked.
2141 if (N->getLocationContext() == LeakContext)
2142 Last = N;
2143
Mike Stump1eb44332009-09-09 15:08:12 +00002144 N = N->pred_empty() ? NULL : *(N->pred_begin());
Ted Kremenekc887d132009-04-29 18:50:19 +00002145 }
Mike Stump1eb44332009-09-09 15:08:12 +00002146
Anna Zakse7e01682012-02-28 22:39:22 +00002147 // If allocation happened in a function different from the leak node context,
2148 // do not report the binding.
2149 if (N->getLocationContext() != LeakContext) {
2150 FirstBinding = 0;
2151 }
2152
Ted Kremenekc887d132009-04-29 18:50:19 +00002153 return std::make_pair(Last, FirstBinding);
2154}
2155
2156PathDiagnosticPiece*
Anna Zaks23f395e2011-08-20 01:27:22 +00002157CFRefReportVisitor::getEndPath(BugReporterContext &BRC,
2158 const ExplodedNode *EndN,
2159 BugReport &BR) {
Ted Kremenek76aadc32012-03-09 01:13:14 +00002160 BR.markInteresting(Sym);
Anna Zaks23f395e2011-08-20 01:27:22 +00002161 return BugReporterVisitor::getDefaultEndPath(BRC, EndN, BR);
Ted Kremenekc887d132009-04-29 18:50:19 +00002162}
2163
2164PathDiagnosticPiece*
Anna Zaks23f395e2011-08-20 01:27:22 +00002165CFRefLeakReportVisitor::getEndPath(BugReporterContext &BRC,
2166 const ExplodedNode *EndN,
2167 BugReport &BR) {
Mike Stump1eb44332009-09-09 15:08:12 +00002168
Ted Kremenek8966bc12009-05-06 21:39:49 +00002169 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenekc887d132009-04-29 18:50:19 +00002170 // assigned to different variables, etc.
Ted Kremenek76aadc32012-03-09 01:13:14 +00002171 BR.markInteresting(Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002172
Ted Kremenekc887d132009-04-29 18:50:19 +00002173 // We are reporting a leak. Walk up the graph to get to the first node where
2174 // the symbol appeared, and also get the first VarDecl that tracked object
2175 // is stored to.
Ted Kremenek9c378f72011-08-12 23:37:29 +00002176 const ExplodedNode *AllocNode = 0;
Ted Kremenekc887d132009-04-29 18:50:19 +00002177 const MemRegion* FirstBinding = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002178
Ted Kremenekc887d132009-04-29 18:50:19 +00002179 llvm::tie(AllocNode, FirstBinding) =
Ted Kremenekf04dced2009-05-08 23:32:51 +00002180 GetAllocationSite(BRC.getStateManager(), EndN, Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002181
Anna Zaks4fdf97b2011-09-15 18:56:07 +00002182 SourceManager& SM = BRC.getSourceManager();
Mike Stump1eb44332009-09-09 15:08:12 +00002183
Ted Kremenekc887d132009-04-29 18:50:19 +00002184 // Compute an actual location for the leak. Sometimes a leak doesn't
2185 // occur at an actual statement (e.g., transition between blocks; end
2186 // of function) so we need to walk the graph and compute a real location.
Ted Kremenek9c378f72011-08-12 23:37:29 +00002187 const ExplodedNode *LeakN = EndN;
Anna Zaks4fdf97b2011-09-15 18:56:07 +00002188 PathDiagnosticLocation L = PathDiagnosticLocation::createEndOfPath(LeakN, SM);
Mike Stump1eb44332009-09-09 15:08:12 +00002189
Ted Kremenekc887d132009-04-29 18:50:19 +00002190 std::string sbuf;
2191 llvm::raw_string_ostream os(sbuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002192
Ted Kremenekf1365462011-05-26 18:45:44 +00002193 os << "Object leaked: ";
Mike Stump1eb44332009-09-09 15:08:12 +00002194
Ted Kremenekf1365462011-05-26 18:45:44 +00002195 if (FirstBinding) {
2196 os << "object allocated and stored into '"
2197 << FirstBinding->getString() << '\'';
2198 }
2199 else
2200 os << "allocated object";
Mike Stump1eb44332009-09-09 15:08:12 +00002201
Ted Kremenekc887d132009-04-29 18:50:19 +00002202 // Get the retain count.
2203 const RefVal* RV = EndN->getState()->get<RefBindings>(Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002204
Ted Kremenekc887d132009-04-29 18:50:19 +00002205 if (RV->getKind() == RefVal::ErrorLeakReturned) {
2206 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
Jordy Rose5b5402b2011-07-15 22:17:54 +00002207 // objects. Only "copy", "alloc", "retain" and "new" transfer ownership
Ted Kremenekc887d132009-04-29 18:50:19 +00002208 // to the caller for NS objects.
Ted Kremenekd368d712011-05-25 06:19:45 +00002209 const Decl *D = &EndN->getCodeDecl();
2210 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2211 os << " is returned from a method whose name ('"
2212 << MD->getSelector().getAsString()
2213 << "') does not start with 'copy', 'mutableCopy', 'alloc' or 'new'."
Jordy Rose5b5402b2011-07-15 22:17:54 +00002214 " This violates the naming convention rules"
Ted Kremenekf1365462011-05-26 18:45:44 +00002215 " given in the Memory Management Guide for Cocoa";
Ted Kremenekd368d712011-05-25 06:19:45 +00002216 }
2217 else {
2218 const FunctionDecl *FD = cast<FunctionDecl>(D);
Ted Kremenekb7dcddf2011-12-22 06:35:52 +00002219 os << " is returned from a function whose name ('"
Benjamin Kramera59d20b2012-02-07 11:57:57 +00002220 << *FD
Ted Kremenekd368d712011-05-25 06:19:45 +00002221 << "') does not contain 'Copy' or 'Create'. This violates the naming"
Ted Kremenekb7dcddf2011-12-22 06:35:52 +00002222 " convention rules given in the Memory Management Guide for Core"
Ted Kremenekf1365462011-05-26 18:45:44 +00002223 " Foundation";
Ted Kremenekd368d712011-05-25 06:19:45 +00002224 }
Ted Kremenekc887d132009-04-29 18:50:19 +00002225 }
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002226 else if (RV->getKind() == RefVal::ErrorGCLeakReturned) {
Ted Kremenek9c378f72011-08-12 23:37:29 +00002227 ObjCMethodDecl &MD = cast<ObjCMethodDecl>(EndN->getCodeDecl());
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002228 os << " and returned from method '" << MD.getSelector().getAsString()
Ted Kremenek82f2be52009-05-10 16:52:15 +00002229 << "' is potentially leaked when using garbage collection. Callers "
2230 "of this method do not expect a returned object with a +1 retain "
2231 "count since they expect the object to be managed by the garbage "
2232 "collector";
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002233 }
Ted Kremenekc887d132009-04-29 18:50:19 +00002234 else
Ted Kremenekabf517c2010-10-15 22:50:23 +00002235 os << " is not referenced later in this execution path and has a retain "
Ted Kremenekf1365462011-05-26 18:45:44 +00002236 "count of +" << RV->getCount();
Mike Stump1eb44332009-09-09 15:08:12 +00002237
Ted Kremenekc887d132009-04-29 18:50:19 +00002238 return new PathDiagnosticEventPiece(L, os.str());
2239}
2240
Jordy Rose20589562011-08-24 22:39:09 +00002241CFRefLeakReport::CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts,
2242 bool GCEnabled, const SummaryLogTy &Log,
2243 ExplodedNode *n, SymbolRef sym,
Anna Zaks6a93bd52011-10-25 19:57:11 +00002244 CheckerContext &Ctx)
Jordy Rose20589562011-08-24 22:39:09 +00002245: CFRefReport(D, LOpts, GCEnabled, Log, n, sym, false) {
Mike Stump1eb44332009-09-09 15:08:12 +00002246
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00002247 // Most bug reports are cached at the location where they occurred.
Ted Kremenekc887d132009-04-29 18:50:19 +00002248 // With leaks, we want to unique them by the location where they were
2249 // allocated, and only report a single path. To do this, we need to find
2250 // the allocation site of a piece of tracked memory, which we do via a
2251 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2252 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2253 // that all ancestor nodes that represent the allocation site have the
2254 // same SourceLocation.
Ted Kremenek9c378f72011-08-12 23:37:29 +00002255 const ExplodedNode *AllocNode = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002256
Anna Zaks6a93bd52011-10-25 19:57:11 +00002257 const SourceManager& SMgr = Ctx.getSourceManager();
Anna Zaks590dd8e2011-09-20 21:38:35 +00002258
Ted Kremenekc887d132009-04-29 18:50:19 +00002259 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding.
Anna Zaks6a93bd52011-10-25 19:57:11 +00002260 GetAllocationSite(Ctx.getStateManager(), getErrorNode(), sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002261
Ted Kremenekc887d132009-04-29 18:50:19 +00002262 // Get the SourceLocation for the allocation site.
2263 ProgramPoint P = AllocNode->getLocation();
Anna Zaks590dd8e2011-09-20 21:38:35 +00002264 const Stmt *AllocStmt = cast<PostStmt>(P).getStmt();
2265 Location = PathDiagnosticLocation::createBegin(AllocStmt, SMgr,
2266 n->getLocationContext());
Ted Kremenekc887d132009-04-29 18:50:19 +00002267 // Fill in the description of the bug.
2268 Description.clear();
2269 llvm::raw_string_ostream os(Description);
Ted Kremenekdd924e22009-05-02 19:05:19 +00002270 os << "Potential leak ";
Jordy Rose20589562011-08-24 22:39:09 +00002271 if (GCEnabled)
Ted Kremenekdd924e22009-05-02 19:05:19 +00002272 os << "(when using garbage collection) ";
Anna Zaks212000e2012-02-28 21:49:08 +00002273 os << "of an object";
Mike Stump1eb44332009-09-09 15:08:12 +00002274
Ted Kremenekc887d132009-04-29 18:50:19 +00002275 // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2276 if (AllocBinding)
Anna Zaks212000e2012-02-28 21:49:08 +00002277 os << " stored into '" << AllocBinding->getString() << '\'';
Anna Zaksdc757b02011-08-19 23:21:56 +00002278
Jordy Rose20589562011-08-24 22:39:09 +00002279 addVisitor(new CFRefLeakReportVisitor(sym, GCEnabled, Log));
Ted Kremenekc887d132009-04-29 18:50:19 +00002280}
2281
2282//===----------------------------------------------------------------------===//
2283// Main checker logic.
2284//===----------------------------------------------------------------------===//
2285
Ted Kremenekd593eb92009-11-25 22:17:44 +00002286namespace {
Jordy Rose910c4052011-09-02 06:44:22 +00002287class RetainCountChecker
Jordy Rose9c083b72011-08-24 18:56:32 +00002288 : public Checker< check::Bind,
Jordy Rose38f17d62011-08-23 19:01:07 +00002289 check::DeadSymbols,
Jordy Rose9c083b72011-08-24 18:56:32 +00002290 check::EndAnalysis,
Jordy Rose38f17d62011-08-23 19:01:07 +00002291 check::EndPath,
Jordy Rose67044292011-08-17 21:27:39 +00002292 check::PostStmt<BlockExpr>,
John McCallf85e1932011-06-15 23:02:42 +00002293 check::PostStmt<CastExpr>,
Jordy Rose294396b2011-08-22 23:48:23 +00002294 check::PostStmt<CallExpr>,
Jordy Rose537716a2011-08-27 22:51:26 +00002295 check::PostStmt<CXXConstructExpr>,
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002296 check::PostStmt<ObjCArrayLiteral>,
2297 check::PostStmt<ObjCDictionaryLiteral>,
Jordy Rose294396b2011-08-22 23:48:23 +00002298 check::PostObjCMessage,
Jordy Rosef53e8c72011-08-23 19:43:16 +00002299 check::PreStmt<ReturnStmt>,
Jordy Rose67044292011-08-17 21:27:39 +00002300 check::RegionChanges,
Jordy Rose76c506f2011-08-21 21:58:18 +00002301 eval::Assume,
2302 eval::Call > {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002303 mutable OwningPtr<CFRefBug> useAfterRelease, releaseNotOwned;
2304 mutable OwningPtr<CFRefBug> deallocGC, deallocNotOwned;
2305 mutable OwningPtr<CFRefBug> overAutorelease, returnNotOwnedForOwned;
2306 mutable OwningPtr<CFRefBug> leakWithinFunction, leakAtReturn;
2307 mutable OwningPtr<CFRefBug> leakWithinFunctionGC, leakAtReturnGC;
Jordy Rose38f17d62011-08-23 19:01:07 +00002308
2309 typedef llvm::DenseMap<SymbolRef, const SimpleProgramPointTag *> SymbolTagMap;
2310
2311 // This map is only used to ensure proper deletion of any allocated tags.
2312 mutable SymbolTagMap DeadSymbolTags;
2313
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002314 mutable OwningPtr<RetainSummaryManager> Summaries;
2315 mutable OwningPtr<RetainSummaryManager> SummariesGC;
Jordy Roseb6cfc092011-08-25 00:10:37 +00002316
Jordy Rosee0a5d322011-08-23 20:27:16 +00002317 mutable ARCounts::Factory ARCountFactory;
2318
Jordy Rose9c083b72011-08-24 18:56:32 +00002319 mutable SummaryLogTy SummaryLog;
2320 mutable bool ShouldResetSummaryLog;
2321
Jordy Rose2f9a66d2011-08-20 21:17:59 +00002322public:
Jordy Rose910c4052011-09-02 06:44:22 +00002323 RetainCountChecker() : ShouldResetSummaryLog(false) {}
Jordy Rose38f17d62011-08-23 19:01:07 +00002324
Jordy Rose910c4052011-09-02 06:44:22 +00002325 virtual ~RetainCountChecker() {
Jordy Rose38f17d62011-08-23 19:01:07 +00002326 DeleteContainerSeconds(DeadSymbolTags);
2327 }
2328
Jordy Rose9c083b72011-08-24 18:56:32 +00002329 void checkEndAnalysis(ExplodedGraph &G, BugReporter &BR,
2330 ExprEngine &Eng) const {
2331 // FIXME: This is a hack to make sure the summary log gets cleared between
2332 // analyses of different code bodies.
2333 //
2334 // Why is this necessary? Because a checker's lifetime is tied to a
2335 // translation unit, but an ExplodedGraph's lifetime is just a code body.
2336 // Once in a blue moon, a new ExplodedNode will have the same address as an
2337 // old one with an associated summary, and the bug report visitor gets very
2338 // confused. (To make things worse, the summary lifetime is currently also
2339 // tied to a code body, so we get a crash instead of incorrect results.)
Jordy Rose1ab51c72011-08-24 09:27:24 +00002340 //
2341 // Why is this a bad solution? Because if the lifetime of the ExplodedGraph
2342 // changes, things will start going wrong again. Really the lifetime of this
2343 // log needs to be tied to either the specific nodes in it or the entire
2344 // ExplodedGraph, not to a specific part of the code being analyzed.
2345 //
Jordy Rose9c083b72011-08-24 18:56:32 +00002346 // (Also, having stateful local data means that the same checker can't be
2347 // used from multiple threads, but a lot of checkers have incorrect
2348 // assumptions about that anyway. So that wasn't a priority at the time of
2349 // this fix.)
Jordy Rose1ab51c72011-08-24 09:27:24 +00002350 //
Jordy Rose9c083b72011-08-24 18:56:32 +00002351 // This happens at the end of analysis, but bug reports are emitted /after/
2352 // this point. So we can't just clear the summary log now. Instead, we mark
2353 // that the next time we access the summary log, it should be cleared.
2354
2355 // If we never reset the summary log during /this/ code body analysis,
2356 // there were no new summaries. There might still have been summaries from
2357 // the /last/ analysis, so clear them out to make sure the bug report
2358 // visitors don't get confused.
2359 if (ShouldResetSummaryLog)
2360 SummaryLog.clear();
2361
2362 ShouldResetSummaryLog = !SummaryLog.empty();
Jordy Rose1ab51c72011-08-24 09:27:24 +00002363 }
2364
Jordy Rose17a38e22011-09-02 05:55:19 +00002365 CFRefBug *getLeakWithinFunctionBug(const LangOptions &LOpts,
2366 bool GCEnabled) const {
2367 if (GCEnabled) {
Jordy Rosedb92bb62011-08-25 01:14:38 +00002368 if (!leakWithinFunctionGC)
2369 leakWithinFunctionGC.reset(new LeakWithinFunction("Leak of object when "
2370 "using garbage "
2371 "collection"));
Jordy Rose17a38e22011-09-02 05:55:19 +00002372 return leakWithinFunctionGC.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002373 } else {
2374 if (!leakWithinFunction) {
Douglas Gregore289d812011-09-13 17:21:33 +00002375 if (LOpts.getGC() == LangOptions::HybridGC) {
Jordy Rosedb92bb62011-08-25 01:14:38 +00002376 leakWithinFunction.reset(new LeakWithinFunction("Leak of object when "
2377 "not using garbage "
2378 "collection (GC) in "
2379 "dual GC/non-GC "
2380 "code"));
2381 } else {
2382 leakWithinFunction.reset(new LeakWithinFunction("Leak"));
2383 }
2384 }
Jordy Rose17a38e22011-09-02 05:55:19 +00002385 return leakWithinFunction.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002386 }
2387 }
2388
Jordy Rose17a38e22011-09-02 05:55:19 +00002389 CFRefBug *getLeakAtReturnBug(const LangOptions &LOpts, bool GCEnabled) const {
2390 if (GCEnabled) {
Jordy Rosedb92bb62011-08-25 01:14:38 +00002391 if (!leakAtReturnGC)
2392 leakAtReturnGC.reset(new LeakAtReturn("Leak of returned object when "
2393 "using garbage collection"));
Jordy Rose17a38e22011-09-02 05:55:19 +00002394 return leakAtReturnGC.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002395 } else {
2396 if (!leakAtReturn) {
Douglas Gregore289d812011-09-13 17:21:33 +00002397 if (LOpts.getGC() == LangOptions::HybridGC) {
Jordy Rosedb92bb62011-08-25 01:14:38 +00002398 leakAtReturn.reset(new LeakAtReturn("Leak of returned object when "
2399 "not using garbage collection "
2400 "(GC) in dual GC/non-GC code"));
2401 } else {
2402 leakAtReturn.reset(new LeakAtReturn("Leak of returned object"));
2403 }
2404 }
Jordy Rose17a38e22011-09-02 05:55:19 +00002405 return leakAtReturn.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002406 }
2407 }
2408
Jordy Rose17a38e22011-09-02 05:55:19 +00002409 RetainSummaryManager &getSummaryManager(ASTContext &Ctx,
2410 bool GCEnabled) const {
2411 // FIXME: We don't support ARC being turned on and off during one analysis.
2412 // (nor, for that matter, do we support changing ASTContexts)
David Blaikie4e4d0842012-03-11 07:00:24 +00002413 bool ARCEnabled = (bool)Ctx.getLangOpts().ObjCAutoRefCount;
Jordy Rose17a38e22011-09-02 05:55:19 +00002414 if (GCEnabled) {
2415 if (!SummariesGC)
Jordy Roseb6cfc092011-08-25 00:10:37 +00002416 SummariesGC.reset(new RetainSummaryManager(Ctx, true, ARCEnabled));
Jordy Rose17a38e22011-09-02 05:55:19 +00002417 else
2418 assert(SummariesGC->isARCEnabled() == ARCEnabled);
Jordy Roseb6cfc092011-08-25 00:10:37 +00002419 return *SummariesGC;
2420 } else {
Jordy Rose17a38e22011-09-02 05:55:19 +00002421 if (!Summaries)
Jordy Roseb6cfc092011-08-25 00:10:37 +00002422 Summaries.reset(new RetainSummaryManager(Ctx, false, ARCEnabled));
Jordy Rose17a38e22011-09-02 05:55:19 +00002423 else
2424 assert(Summaries->isARCEnabled() == ARCEnabled);
Jordy Roseb6cfc092011-08-25 00:10:37 +00002425 return *Summaries;
2426 }
2427 }
2428
Jordy Rose17a38e22011-09-02 05:55:19 +00002429 RetainSummaryManager &getSummaryManager(CheckerContext &C) const {
2430 return getSummaryManager(C.getASTContext(), C.isObjCGCEnabled());
2431 }
2432
Ted Kremenek8bef8232012-01-26 21:29:00 +00002433 void printState(raw_ostream &Out, ProgramStateRef State,
Jordy Rosedbd658e2011-08-28 19:11:56 +00002434 const char *NL, const char *Sep) const;
2435
Anna Zaks390909c2011-10-06 00:43:15 +00002436 void checkBind(SVal loc, SVal val, const Stmt *S, CheckerContext &C) const;
Jordy Roseab027fd2011-08-20 21:16:58 +00002437 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
2438 void checkPostStmt(const CastExpr *CE, CheckerContext &C) const;
John McCallf85e1932011-06-15 23:02:42 +00002439
Jordy Rose294396b2011-08-22 23:48:23 +00002440 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
Jordy Rose537716a2011-08-27 22:51:26 +00002441 void checkPostStmt(const CXXConstructExpr *CE, CheckerContext &C) const;
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002442 void checkPostStmt(const ObjCArrayLiteral *AL, CheckerContext &C) const;
2443 void checkPostStmt(const ObjCDictionaryLiteral *DL, CheckerContext &C) const;
Jordy Rose294396b2011-08-22 23:48:23 +00002444 void checkPostObjCMessage(const ObjCMessage &Msg, CheckerContext &C) const;
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002445
Jordy Rose294396b2011-08-22 23:48:23 +00002446 void checkSummary(const RetainSummary &Summ, const CallOrObjCMessage &Call,
Jordy Rosee38dd952011-08-28 05:16:28 +00002447 CheckerContext &C) const;
Jordy Rose294396b2011-08-22 23:48:23 +00002448
Jordy Rose76c506f2011-08-21 21:58:18 +00002449 bool evalCall(const CallExpr *CE, CheckerContext &C) const;
2450
Ted Kremenek8bef8232012-01-26 21:29:00 +00002451 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Jordy Roseab027fd2011-08-20 21:16:58 +00002452 bool Assumption) const;
Jordy Rose67044292011-08-17 21:27:39 +00002453
Ted Kremenek8bef8232012-01-26 21:29:00 +00002454 ProgramStateRef
2455 checkRegionChanges(ProgramStateRef state,
Jordy Rose537716a2011-08-27 22:51:26 +00002456 const StoreManager::InvalidatedSymbols *invalidated,
2457 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00002458 ArrayRef<const MemRegion *> Regions,
2459 const CallOrObjCMessage *Call) const;
Jordy Roseab027fd2011-08-20 21:16:58 +00002460
Ted Kremenek8bef8232012-01-26 21:29:00 +00002461 bool wantsRegionChangeUpdate(ProgramStateRef state) const {
Jordy Rose2f9a66d2011-08-20 21:17:59 +00002462 return true;
Jordy Roseab027fd2011-08-20 21:16:58 +00002463 }
Jordy Rose294396b2011-08-22 23:48:23 +00002464
Jordy Rosef53e8c72011-08-23 19:43:16 +00002465 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
2466 void checkReturnWithRetEffect(const ReturnStmt *S, CheckerContext &C,
2467 ExplodedNode *Pred, RetEffect RE, RefVal X,
Ted Kremenek8bef8232012-01-26 21:29:00 +00002468 SymbolRef Sym, ProgramStateRef state) const;
Jordy Rosef53e8c72011-08-23 19:43:16 +00002469
Jordy Rose38f17d62011-08-23 19:01:07 +00002470 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Anna Zaksaf498a22011-10-25 19:56:48 +00002471 void checkEndPath(CheckerContext &C) const;
Jordy Rose38f17d62011-08-23 19:01:07 +00002472
Ted Kremenek8bef8232012-01-26 21:29:00 +00002473 ProgramStateRef updateSymbol(ProgramStateRef state, SymbolRef sym,
Jordy Rose17a38e22011-09-02 05:55:19 +00002474 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
2475 CheckerContext &C) const;
Jordy Rosee0a5d322011-08-23 20:27:16 +00002476
Ted Kremenek8bef8232012-01-26 21:29:00 +00002477 void processNonLeakError(ProgramStateRef St, SourceRange ErrorRange,
Jordy Rose294396b2011-08-22 23:48:23 +00002478 RefVal::Kind ErrorKind, SymbolRef Sym,
2479 CheckerContext &C) const;
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002480
2481 void processObjCLiterals(CheckerContext &C, const Expr *Ex) const;
Jordy Rose294396b2011-08-22 23:48:23 +00002482
Jordy Rose38f17d62011-08-23 19:01:07 +00002483 const ProgramPointTag *getDeadSymbolTag(SymbolRef sym) const;
2484
Ted Kremenek8bef8232012-01-26 21:29:00 +00002485 ProgramStateRef handleSymbolDeath(ProgramStateRef state,
Jordy Rose38f17d62011-08-23 19:01:07 +00002486 SymbolRef sid, RefVal V,
2487 SmallVectorImpl<SymbolRef> &Leaked) const;
2488
Ted Kremenek8bef8232012-01-26 21:29:00 +00002489 std::pair<ExplodedNode *, ProgramStateRef >
2490 handleAutoreleaseCounts(ProgramStateRef state,
Jordy Rose8d228632011-08-23 20:07:14 +00002491 GenericNodeBuilderRefCount Bd, ExplodedNode *Pred,
Anna Zaks6a93bd52011-10-25 19:57:11 +00002492 CheckerContext &Ctx, SymbolRef Sym, RefVal V) const;
Jordy Rose8d228632011-08-23 20:07:14 +00002493
Ted Kremenek8bef8232012-01-26 21:29:00 +00002494 ExplodedNode *processLeaks(ProgramStateRef state,
Jordy Rose38f17d62011-08-23 19:01:07 +00002495 SmallVectorImpl<SymbolRef> &Leaked,
2496 GenericNodeBuilderRefCount &Builder,
Anna Zaks6a93bd52011-10-25 19:57:11 +00002497 CheckerContext &Ctx,
Jordy Rose38f17d62011-08-23 19:01:07 +00002498 ExplodedNode *Pred = 0) const;
Ted Kremenekd593eb92009-11-25 22:17:44 +00002499};
2500} // end anonymous namespace
2501
Jordy Rose67044292011-08-17 21:27:39 +00002502namespace {
2503class StopTrackingCallback : public SymbolVisitor {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002504 ProgramStateRef state;
Jordy Rose67044292011-08-17 21:27:39 +00002505public:
Ted Kremenek8bef8232012-01-26 21:29:00 +00002506 StopTrackingCallback(ProgramStateRef st) : state(st) {}
2507 ProgramStateRef getState() const { return state; }
Jordy Rose67044292011-08-17 21:27:39 +00002508
2509 bool VisitSymbol(SymbolRef sym) {
2510 state = state->remove<RefBindings>(sym);
2511 return true;
2512 }
2513};
2514} // end anonymous namespace
2515
Jordy Rose910c4052011-09-02 06:44:22 +00002516//===----------------------------------------------------------------------===//
2517// Handle statements that may have an effect on refcounts.
2518//===----------------------------------------------------------------------===//
Jordy Rose67044292011-08-17 21:27:39 +00002519
Jordy Rose910c4052011-09-02 06:44:22 +00002520void RetainCountChecker::checkPostStmt(const BlockExpr *BE,
2521 CheckerContext &C) const {
Jordy Rose67044292011-08-17 21:27:39 +00002522
Jordy Rose910c4052011-09-02 06:44:22 +00002523 // Scan the BlockDecRefExprs for any object the retain count checker
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002524 // may be tracking.
John McCall469a1eb2011-02-02 13:00:07 +00002525 if (!BE->getBlockDecl()->hasCaptures())
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002526 return;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002527
Ted Kremenek8bef8232012-01-26 21:29:00 +00002528 ProgramStateRef state = C.getState();
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002529 const BlockDataRegion *R =
Ted Kremenek5eca4822012-01-06 22:09:28 +00002530 cast<BlockDataRegion>(state->getSVal(BE,
2531 C.getLocationContext()).getAsRegion());
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002532
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002533 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
2534 E = R->referenced_vars_end();
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002535
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002536 if (I == E)
2537 return;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002538
Ted Kremenek67d12872009-12-07 22:05:27 +00002539 // FIXME: For now we invalidate the tracking of all symbols passed to blocks
2540 // via captured variables, even though captured variables result in a copy
2541 // and in implicit increment/decrement of a retain count.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002542 SmallVector<const MemRegion*, 10> Regions;
Anna Zaks39ac1872011-10-26 21:06:44 +00002543 const LocationContext *LC = C.getLocationContext();
Ted Kremenekc8413fd2010-12-02 07:49:45 +00002544 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002545
Ted Kremenek67d12872009-12-07 22:05:27 +00002546 for ( ; I != E; ++I) {
2547 const VarRegion *VR = *I;
2548 if (VR->getSuperRegion() == R) {
2549 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2550 }
2551 Regions.push_back(VR);
2552 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002553
Ted Kremenek67d12872009-12-07 22:05:27 +00002554 state =
2555 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
2556 Regions.data() + Regions.size()).getState();
Anna Zaks0bd6b112011-10-26 21:06:34 +00002557 C.addTransition(state);
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002558}
2559
Jordy Rose910c4052011-09-02 06:44:22 +00002560void RetainCountChecker::checkPostStmt(const CastExpr *CE,
2561 CheckerContext &C) const {
John McCallf85e1932011-06-15 23:02:42 +00002562 const ObjCBridgedCastExpr *BE = dyn_cast<ObjCBridgedCastExpr>(CE);
2563 if (!BE)
2564 return;
2565
John McCall71c482c2011-06-17 06:50:50 +00002566 ArgEffect AE = IncRef;
John McCallf85e1932011-06-15 23:02:42 +00002567
2568 switch (BE->getBridgeKind()) {
2569 case clang::OBC_Bridge:
2570 // Do nothing.
2571 return;
2572 case clang::OBC_BridgeRetained:
2573 AE = IncRef;
2574 break;
2575 case clang::OBC_BridgeTransfer:
2576 AE = DecRefBridgedTransfered;
2577 break;
2578 }
2579
Ted Kremenek8bef8232012-01-26 21:29:00 +00002580 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00002581 SymbolRef Sym = state->getSVal(CE, C.getLocationContext()).getAsLocSymbol();
John McCallf85e1932011-06-15 23:02:42 +00002582 if (!Sym)
2583 return;
2584 const RefVal* T = state->get<RefBindings>(Sym);
2585 if (!T)
2586 return;
2587
John McCallf85e1932011-06-15 23:02:42 +00002588 RefVal::Kind hasErr = (RefVal::Kind) 0;
Jordy Rose17a38e22011-09-02 05:55:19 +00002589 state = updateSymbol(state, Sym, *T, AE, hasErr, C);
John McCallf85e1932011-06-15 23:02:42 +00002590
2591 if (hasErr) {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002592 // FIXME: If we get an error during a bridge cast, should we report it?
2593 // Should we assert that there is no error?
John McCallf85e1932011-06-15 23:02:42 +00002594 return;
2595 }
2596
Anna Zaks0bd6b112011-10-26 21:06:34 +00002597 C.addTransition(state);
John McCallf85e1932011-06-15 23:02:42 +00002598}
2599
Jordy Rose910c4052011-09-02 06:44:22 +00002600void RetainCountChecker::checkPostStmt(const CallExpr *CE,
2601 CheckerContext &C) const {
Jordy Rose294396b2011-08-22 23:48:23 +00002602 // Get the callee.
Ted Kremenek8bef8232012-01-26 21:29:00 +00002603 ProgramStateRef state = C.getState();
Jordy Rose294396b2011-08-22 23:48:23 +00002604 const Expr *Callee = CE->getCallee();
Ted Kremenek5eca4822012-01-06 22:09:28 +00002605 SVal L = state->getSVal(Callee, C.getLocationContext());
Jordy Rose294396b2011-08-22 23:48:23 +00002606
Jordy Rose17a38e22011-09-02 05:55:19 +00002607 RetainSummaryManager &Summaries = getSummaryManager(C);
Ted Kremenek93edbc52011-10-05 23:54:29 +00002608 const RetainSummary *Summ = 0;
Jordy Rose294396b2011-08-22 23:48:23 +00002609
2610 // FIXME: Better support for blocks. For now we stop tracking anything
2611 // that is passed to blocks.
2612 // FIXME: Need to handle variables that are "captured" by the block.
2613 if (dyn_cast_or_null<BlockDataRegion>(L.getAsRegion())) {
2614 Summ = Summaries.getPersistentStopSummary();
2615 } else if (const FunctionDecl *FD = L.getAsFunctionDecl()) {
2616 Summ = Summaries.getSummary(FD);
2617 } else if (const CXXMemberCallExpr *me = dyn_cast<CXXMemberCallExpr>(CE)) {
2618 if (const CXXMethodDecl *MD = me->getMethodDecl())
2619 Summ = Summaries.getSummary(MD);
2620 }
2621
Jordy Rose294396b2011-08-22 23:48:23 +00002622 if (!Summ)
Ted Kremenek93edbc52011-10-05 23:54:29 +00002623 Summ = Summaries.getDefaultSummary();
Jordy Rose294396b2011-08-22 23:48:23 +00002624
Ted Kremenek5eca4822012-01-06 22:09:28 +00002625 checkSummary(*Summ, CallOrObjCMessage(CE, state, C.getLocationContext()), C);
Jordy Rose294396b2011-08-22 23:48:23 +00002626}
2627
Jordy Rose910c4052011-09-02 06:44:22 +00002628void RetainCountChecker::checkPostStmt(const CXXConstructExpr *CE,
2629 CheckerContext &C) const {
Jordy Rose537716a2011-08-27 22:51:26 +00002630 const CXXConstructorDecl *Ctor = CE->getConstructor();
2631 if (!Ctor)
2632 return;
2633
Jordy Rose17a38e22011-09-02 05:55:19 +00002634 RetainSummaryManager &Summaries = getSummaryManager(C);
Ted Kremenek93edbc52011-10-05 23:54:29 +00002635 const RetainSummary *Summ = Summaries.getSummary(Ctor);
Jordy Rose537716a2011-08-27 22:51:26 +00002636
2637 // If we didn't get a summary, this constructor doesn't affect retain counts.
2638 if (!Summ)
2639 return;
2640
Ted Kremenek8bef8232012-01-26 21:29:00 +00002641 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00002642 checkSummary(*Summ, CallOrObjCMessage(CE, state, C.getLocationContext()), C);
Jordy Rose537716a2011-08-27 22:51:26 +00002643}
2644
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002645void RetainCountChecker::processObjCLiterals(CheckerContext &C,
2646 const Expr *Ex) const {
2647 ProgramStateRef state = C.getState();
2648 const ExplodedNode *pred = C.getPredecessor();
2649 for (Stmt::const_child_iterator it = Ex->child_begin(), et = Ex->child_end() ;
2650 it != et ; ++it) {
2651 const Stmt *child = *it;
2652 SVal V = state->getSVal(child, pred->getLocationContext());
2653 if (SymbolRef sym = V.getAsSymbol())
2654 if (const RefVal* T = state->get<RefBindings>(sym)) {
2655 RefVal::Kind hasErr = (RefVal::Kind) 0;
2656 state = updateSymbol(state, sym, *T, MayEscape, hasErr, C);
2657 if (hasErr) {
2658 processNonLeakError(state, child->getSourceRange(), hasErr, sym, C);
2659 return;
2660 }
2661 }
2662 }
2663
2664 // Return the object as autoreleased.
2665 // RetEffect RE = RetEffect::MakeNotOwned(RetEffect::ObjC);
2666 if (SymbolRef sym =
2667 state->getSVal(Ex, pred->getLocationContext()).getAsSymbol()) {
2668 QualType ResultTy = Ex->getType();
2669 state = state->set<RefBindings>(sym, RefVal::makeNotOwned(RetEffect::ObjC,
2670 ResultTy));
2671 }
2672
2673 C.addTransition(state);
2674}
2675
2676void RetainCountChecker::checkPostStmt(const ObjCArrayLiteral *AL,
2677 CheckerContext &C) const {
2678 // Apply the 'MayEscape' to all values.
2679 processObjCLiterals(C, AL);
2680}
2681
2682void RetainCountChecker::checkPostStmt(const ObjCDictionaryLiteral *DL,
2683 CheckerContext &C) const {
2684 // Apply the 'MayEscape' to all keys and values.
2685 processObjCLiterals(C, DL);
2686}
2687
Jordy Rose910c4052011-09-02 06:44:22 +00002688void RetainCountChecker::checkPostObjCMessage(const ObjCMessage &Msg,
2689 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002690 ProgramStateRef state = C.getState();
Jordy Rose294396b2011-08-22 23:48:23 +00002691
Jordy Rose17a38e22011-09-02 05:55:19 +00002692 RetainSummaryManager &Summaries = getSummaryManager(C);
Jordy Roseb6cfc092011-08-25 00:10:37 +00002693
Ted Kremenek93edbc52011-10-05 23:54:29 +00002694 const RetainSummary *Summ;
Jordy Rose294396b2011-08-22 23:48:23 +00002695 if (Msg.isInstanceMessage()) {
Anna Zaksa2a86032011-11-01 22:41:01 +00002696 const LocationContext *LC = C.getLocationContext();
Jordy Rose294396b2011-08-22 23:48:23 +00002697 Summ = Summaries.getInstanceMethodSummary(Msg, state, LC);
2698 } else {
2699 Summ = Summaries.getClassMethodSummary(Msg);
2700 }
2701
2702 // If we didn't get a summary, this message doesn't affect retain counts.
2703 if (!Summ)
2704 return;
2705
Ted Kremenek5eca4822012-01-06 22:09:28 +00002706 checkSummary(*Summ, CallOrObjCMessage(Msg, state, C.getLocationContext()), C);
Jordy Rose294396b2011-08-22 23:48:23 +00002707}
2708
Jordy Rose910c4052011-09-02 06:44:22 +00002709/// GetReturnType - Used to get the return type of a message expression or
2710/// function call with the intention of affixing that type to a tracked symbol.
2711/// While the the return type can be queried directly from RetEx, when
2712/// invoking class methods we augment to the return type to be that of
2713/// a pointer to the class (as opposed it just being id).
2714// FIXME: We may be able to do this with related result types instead.
2715// This function is probably overestimating.
2716static QualType GetReturnType(const Expr *RetE, ASTContext &Ctx) {
2717 QualType RetTy = RetE->getType();
2718 // If RetE is not a message expression just return its type.
2719 // If RetE is a message expression, return its types if it is something
2720 /// more specific than id.
2721 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RetE))
2722 if (const ObjCObjectPointerType *PT = RetTy->getAs<ObjCObjectPointerType>())
2723 if (PT->isObjCQualifiedIdType() || PT->isObjCIdType() ||
2724 PT->isObjCClassType()) {
2725 // At this point we know the return type of the message expression is
2726 // id, id<...>, or Class. If we have an ObjCInterfaceDecl, we know this
2727 // is a call to a class method whose type we can resolve. In such
2728 // cases, promote the return type to XXX* (where XXX is the class).
2729 const ObjCInterfaceDecl *D = ME->getReceiverInterface();
2730 return !D ? RetTy :
2731 Ctx.getObjCObjectPointerType(Ctx.getObjCInterfaceType(D));
2732 }
2733
2734 return RetTy;
2735}
2736
2737void RetainCountChecker::checkSummary(const RetainSummary &Summ,
2738 const CallOrObjCMessage &CallOrMsg,
2739 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002740 ProgramStateRef state = C.getState();
Jordy Rose294396b2011-08-22 23:48:23 +00002741
2742 // Evaluate the effect of the arguments.
2743 RefVal::Kind hasErr = (RefVal::Kind) 0;
2744 SourceRange ErrorRange;
2745 SymbolRef ErrorSym = 0;
2746
2747 for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
Jordy Rose537716a2011-08-27 22:51:26 +00002748 SVal V = CallOrMsg.getArgSVal(idx);
Jordy Rose294396b2011-08-22 23:48:23 +00002749
2750 if (SymbolRef Sym = V.getAsLocSymbol()) {
2751 if (RefBindings::data_type *T = state->get<RefBindings>(Sym)) {
Jordy Rose17a38e22011-09-02 05:55:19 +00002752 state = updateSymbol(state, Sym, *T, Summ.getArg(idx), hasErr, C);
Jordy Rose294396b2011-08-22 23:48:23 +00002753 if (hasErr) {
2754 ErrorRange = CallOrMsg.getArgSourceRange(idx);
2755 ErrorSym = Sym;
2756 break;
2757 }
2758 }
2759 }
2760 }
2761
2762 // Evaluate the effect on the message receiver.
2763 bool ReceiverIsTracked = false;
Jordy Rosee38dd952011-08-28 05:16:28 +00002764 if (!hasErr && CallOrMsg.isObjCMessage()) {
Anna Zaks39ac1872011-10-26 21:06:44 +00002765 const LocationContext *LC = C.getLocationContext();
Jordy Rosee38dd952011-08-28 05:16:28 +00002766 SVal Receiver = CallOrMsg.getInstanceMessageReceiver(LC);
2767 if (SymbolRef Sym = Receiver.getAsLocSymbol()) {
Jordy Rose294396b2011-08-22 23:48:23 +00002768 if (const RefVal *T = state->get<RefBindings>(Sym)) {
2769 ReceiverIsTracked = true;
Jordy Rose17a38e22011-09-02 05:55:19 +00002770 state = updateSymbol(state, Sym, *T, Summ.getReceiverEffect(),
2771 hasErr, C);
Jordy Rose294396b2011-08-22 23:48:23 +00002772 if (hasErr) {
Jordy Rosee38dd952011-08-28 05:16:28 +00002773 ErrorRange = CallOrMsg.getReceiverSourceRange();
Jordy Rose294396b2011-08-22 23:48:23 +00002774 ErrorSym = Sym;
2775 }
2776 }
2777 }
2778 }
2779
2780 // Process any errors.
2781 if (hasErr) {
2782 processNonLeakError(state, ErrorRange, hasErr, ErrorSym, C);
2783 return;
2784 }
2785
2786 // Consult the summary for the return value.
2787 RetEffect RE = Summ.getRetEffect();
2788
2789 if (RE.getKind() == RetEffect::OwnedWhenTrackedReceiver) {
Jordy Roseb6cfc092011-08-25 00:10:37 +00002790 if (ReceiverIsTracked)
Jordy Rose17a38e22011-09-02 05:55:19 +00002791 RE = getSummaryManager(C).getObjAllocRetEffect();
Jordy Roseb6cfc092011-08-25 00:10:37 +00002792 else
Jordy Rose294396b2011-08-22 23:48:23 +00002793 RE = RetEffect::MakeNoRet();
2794 }
2795
2796 switch (RE.getKind()) {
2797 default:
David Blaikie7530c032012-01-17 06:56:22 +00002798 llvm_unreachable("Unhandled RetEffect.");
Jordy Rose294396b2011-08-22 23:48:23 +00002799
2800 case RetEffect::NoRet:
2801 // No work necessary.
2802 break;
2803
2804 case RetEffect::OwnedAllocatedSymbol:
2805 case RetEffect::OwnedSymbol: {
Ted Kremenek5eca4822012-01-06 22:09:28 +00002806 SymbolRef Sym = state->getSVal(CallOrMsg.getOriginExpr(),
2807 C.getLocationContext()).getAsSymbol();
Jordy Rose294396b2011-08-22 23:48:23 +00002808 if (!Sym)
2809 break;
2810
2811 // Use the result type from callOrMsg as it automatically adjusts
2812 // for methods/functions that return references.
2813 QualType ResultTy = CallOrMsg.getResultType(C.getASTContext());
2814 state = state->set<RefBindings>(Sym, RefVal::makeOwned(RE.getObjKind(),
2815 ResultTy));
2816
2817 // FIXME: Add a flag to the checker where allocations are assumed to
2818 // *not* fail. (The code below is out-of-date, though.)
2819#if 0
2820 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) {
2821 bool isFeasible;
2822 state = state.assume(loc::SymbolVal(Sym), true, isFeasible);
2823 assert(isFeasible && "Cannot assume fresh symbol is non-null.");
2824 }
2825#endif
2826
2827 break;
2828 }
2829
2830 case RetEffect::GCNotOwnedSymbol:
2831 case RetEffect::ARCNotOwnedSymbol:
2832 case RetEffect::NotOwnedSymbol: {
2833 const Expr *Ex = CallOrMsg.getOriginExpr();
Ted Kremenek5eca4822012-01-06 22:09:28 +00002834 SymbolRef Sym = state->getSVal(Ex, C.getLocationContext()).getAsSymbol();
Jordy Rose294396b2011-08-22 23:48:23 +00002835 if (!Sym)
2836 break;
2837
2838 // Use GetReturnType in order to give [NSFoo alloc] the type NSFoo *.
2839 QualType ResultTy = GetReturnType(Ex, C.getASTContext());
2840 state = state->set<RefBindings>(Sym, RefVal::makeNotOwned(RE.getObjKind(),
2841 ResultTy));
2842 break;
2843 }
2844 }
2845
2846 // This check is actually necessary; otherwise the statement builder thinks
2847 // we've hit a previously-found path.
2848 // Normally addTransition takes care of this, but we want the node pointer.
2849 ExplodedNode *NewNode;
2850 if (state == C.getState()) {
2851 NewNode = C.getPredecessor();
2852 } else {
Anna Zaks0bd6b112011-10-26 21:06:34 +00002853 NewNode = C.addTransition(state);
Jordy Rose294396b2011-08-22 23:48:23 +00002854 }
2855
Jordy Rose9c083b72011-08-24 18:56:32 +00002856 // Annotate the node with summary we used.
2857 if (NewNode) {
2858 // FIXME: This is ugly. See checkEndAnalysis for why it's necessary.
2859 if (ShouldResetSummaryLog) {
2860 SummaryLog.clear();
2861 ShouldResetSummaryLog = false;
2862 }
Jordy Roseec9ef852011-08-23 20:55:48 +00002863 SummaryLog[NewNode] = &Summ;
Jordy Rose9c083b72011-08-24 18:56:32 +00002864 }
Jordy Rose294396b2011-08-22 23:48:23 +00002865}
2866
Jordy Rosee0a5d322011-08-23 20:27:16 +00002867
Ted Kremenek8bef8232012-01-26 21:29:00 +00002868ProgramStateRef
2869RetainCountChecker::updateSymbol(ProgramStateRef state, SymbolRef sym,
Jordy Rose910c4052011-09-02 06:44:22 +00002870 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
2871 CheckerContext &C) const {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002872 // In GC mode [... release] and [... retain] do nothing.
Jordy Rose910c4052011-09-02 06:44:22 +00002873 // In ARC mode they shouldn't exist at all, but we just ignore them.
Jordy Rose17a38e22011-09-02 05:55:19 +00002874 bool IgnoreRetainMsg = C.isObjCGCEnabled();
2875 if (!IgnoreRetainMsg)
David Blaikie4e4d0842012-03-11 07:00:24 +00002876 IgnoreRetainMsg = (bool)C.getASTContext().getLangOpts().ObjCAutoRefCount;
Jordy Rose17a38e22011-09-02 05:55:19 +00002877
Jordy Rosee0a5d322011-08-23 20:27:16 +00002878 switch (E) {
2879 default: break;
Jordy Rose17a38e22011-09-02 05:55:19 +00002880 case IncRefMsg: E = IgnoreRetainMsg ? DoNothing : IncRef; break;
2881 case DecRefMsg: E = IgnoreRetainMsg ? DoNothing : DecRef; break;
2882 case MakeCollectable: E = C.isObjCGCEnabled() ? DecRef : DoNothing; break;
2883 case NewAutoreleasePool: E = C.isObjCGCEnabled() ? DoNothing :
2884 NewAutoreleasePool; break;
Jordy Rosee0a5d322011-08-23 20:27:16 +00002885 }
2886
2887 // Handle all use-after-releases.
Jordy Rose17a38e22011-09-02 05:55:19 +00002888 if (!C.isObjCGCEnabled() && V.getKind() == RefVal::Released) {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002889 V = V ^ RefVal::ErrorUseAfterRelease;
2890 hasErr = V.getKind();
2891 return state->set<RefBindings>(sym, V);
2892 }
2893
2894 switch (E) {
2895 case DecRefMsg:
2896 case IncRefMsg:
2897 case MakeCollectable:
2898 llvm_unreachable("DecRefMsg/IncRefMsg/MakeCollectable already converted");
Jordy Rosee0a5d322011-08-23 20:27:16 +00002899
2900 case Dealloc:
2901 // Any use of -dealloc in GC is *bad*.
Jordy Rose17a38e22011-09-02 05:55:19 +00002902 if (C.isObjCGCEnabled()) {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002903 V = V ^ RefVal::ErrorDeallocGC;
2904 hasErr = V.getKind();
2905 break;
2906 }
2907
2908 switch (V.getKind()) {
2909 default:
2910 llvm_unreachable("Invalid RefVal state for an explicit dealloc.");
Jordy Rosee0a5d322011-08-23 20:27:16 +00002911 case RefVal::Owned:
2912 // The object immediately transitions to the released state.
2913 V = V ^ RefVal::Released;
2914 V.clearCounts();
2915 return state->set<RefBindings>(sym, V);
2916 case RefVal::NotOwned:
2917 V = V ^ RefVal::ErrorDeallocNotOwned;
2918 hasErr = V.getKind();
2919 break;
2920 }
2921 break;
2922
2923 case NewAutoreleasePool:
Jordy Rose17a38e22011-09-02 05:55:19 +00002924 assert(!C.isObjCGCEnabled());
Jordy Rosee0a5d322011-08-23 20:27:16 +00002925 return state->add<AutoreleaseStack>(sym);
2926
2927 case MayEscape:
2928 if (V.getKind() == RefVal::Owned) {
2929 V = V ^ RefVal::NotOwned;
2930 break;
2931 }
2932
2933 // Fall-through.
2934
Jordy Rosee0a5d322011-08-23 20:27:16 +00002935 case DoNothing:
2936 return state;
2937
2938 case Autorelease:
Jordy Rose17a38e22011-09-02 05:55:19 +00002939 if (C.isObjCGCEnabled())
Jordy Rosee0a5d322011-08-23 20:27:16 +00002940 return state;
2941
2942 // Update the autorelease counts.
2943 state = SendAutorelease(state, ARCountFactory, sym);
2944 V = V.autorelease();
2945 break;
2946
2947 case StopTracking:
2948 return state->remove<RefBindings>(sym);
2949
2950 case IncRef:
2951 switch (V.getKind()) {
2952 default:
2953 llvm_unreachable("Invalid RefVal state for a retain.");
Jordy Rosee0a5d322011-08-23 20:27:16 +00002954 case RefVal::Owned:
2955 case RefVal::NotOwned:
2956 V = V + 1;
2957 break;
2958 case RefVal::Released:
2959 // Non-GC cases are handled above.
Jordy Rose17a38e22011-09-02 05:55:19 +00002960 assert(C.isObjCGCEnabled());
Jordy Rosee0a5d322011-08-23 20:27:16 +00002961 V = (V ^ RefVal::Owned) + 1;
2962 break;
2963 }
2964 break;
2965
2966 case SelfOwn:
2967 V = V ^ RefVal::NotOwned;
2968 // Fall-through.
2969 case DecRef:
2970 case DecRefBridgedTransfered:
2971 switch (V.getKind()) {
2972 default:
2973 // case 'RefVal::Released' handled above.
2974 llvm_unreachable("Invalid RefVal state for a release.");
Jordy Rosee0a5d322011-08-23 20:27:16 +00002975
2976 case RefVal::Owned:
2977 assert(V.getCount() > 0);
2978 if (V.getCount() == 1)
2979 V = V ^ (E == DecRefBridgedTransfered ?
2980 RefVal::NotOwned : RefVal::Released);
2981 V = V - 1;
2982 break;
2983
2984 case RefVal::NotOwned:
2985 if (V.getCount() > 0)
2986 V = V - 1;
2987 else {
2988 V = V ^ RefVal::ErrorReleaseNotOwned;
2989 hasErr = V.getKind();
2990 }
2991 break;
2992
2993 case RefVal::Released:
2994 // Non-GC cases are handled above.
Jordy Rose17a38e22011-09-02 05:55:19 +00002995 assert(C.isObjCGCEnabled());
Jordy Rosee0a5d322011-08-23 20:27:16 +00002996 V = V ^ RefVal::ErrorUseAfterRelease;
2997 hasErr = V.getKind();
2998 break;
2999 }
3000 break;
3001 }
3002 return state->set<RefBindings>(sym, V);
3003}
3004
Ted Kremenek8bef8232012-01-26 21:29:00 +00003005void RetainCountChecker::processNonLeakError(ProgramStateRef St,
Jordy Rose910c4052011-09-02 06:44:22 +00003006 SourceRange ErrorRange,
3007 RefVal::Kind ErrorKind,
3008 SymbolRef Sym,
3009 CheckerContext &C) const {
Jordy Rose294396b2011-08-22 23:48:23 +00003010 ExplodedNode *N = C.generateSink(St);
3011 if (!N)
3012 return;
3013
Jordy Rose294396b2011-08-22 23:48:23 +00003014 CFRefBug *BT;
3015 switch (ErrorKind) {
3016 default:
3017 llvm_unreachable("Unhandled error.");
Jordy Rose294396b2011-08-22 23:48:23 +00003018 case RefVal::ErrorUseAfterRelease:
Jordy Rosed6334e12011-08-25 00:34:03 +00003019 if (!useAfterRelease)
3020 useAfterRelease.reset(new UseAfterRelease());
3021 BT = &*useAfterRelease;
Jordy Rose294396b2011-08-22 23:48:23 +00003022 break;
3023 case RefVal::ErrorReleaseNotOwned:
Jordy Rosed6334e12011-08-25 00:34:03 +00003024 if (!releaseNotOwned)
3025 releaseNotOwned.reset(new BadRelease());
3026 BT = &*releaseNotOwned;
Jordy Rose294396b2011-08-22 23:48:23 +00003027 break;
3028 case RefVal::ErrorDeallocGC:
Jordy Rosed6334e12011-08-25 00:34:03 +00003029 if (!deallocGC)
3030 deallocGC.reset(new DeallocGC());
3031 BT = &*deallocGC;
Jordy Rose294396b2011-08-22 23:48:23 +00003032 break;
3033 case RefVal::ErrorDeallocNotOwned:
Jordy Rosed6334e12011-08-25 00:34:03 +00003034 if (!deallocNotOwned)
3035 deallocNotOwned.reset(new DeallocNotOwned());
3036 BT = &*deallocNotOwned;
Jordy Rose294396b2011-08-22 23:48:23 +00003037 break;
3038 }
3039
Jordy Rosed6334e12011-08-25 00:34:03 +00003040 assert(BT);
David Blaikie4e4d0842012-03-11 07:00:24 +00003041 CFRefReport *report = new CFRefReport(*BT, C.getASTContext().getLangOpts(),
Jordy Rose17a38e22011-09-02 05:55:19 +00003042 C.isObjCGCEnabled(), SummaryLog,
3043 N, Sym);
Jordy Rose294396b2011-08-22 23:48:23 +00003044 report->addRange(ErrorRange);
3045 C.EmitReport(report);
3046}
3047
Jordy Rose910c4052011-09-02 06:44:22 +00003048//===----------------------------------------------------------------------===//
3049// Handle the return values of retain-count-related functions.
3050//===----------------------------------------------------------------------===//
3051
3052bool RetainCountChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
Jordy Rose76c506f2011-08-21 21:58:18 +00003053 // Get the callee. We're only interested in simple C functions.
Ted Kremenek8bef8232012-01-26 21:29:00 +00003054 ProgramStateRef state = C.getState();
Anna Zaksb805c8f2011-12-01 05:57:37 +00003055 const FunctionDecl *FD = C.getCalleeDecl(CE);
Jordy Rose76c506f2011-08-21 21:58:18 +00003056 if (!FD)
3057 return false;
3058
3059 IdentifierInfo *II = FD->getIdentifier();
3060 if (!II)
3061 return false;
3062
3063 // For now, we're only handling the functions that return aliases of their
3064 // arguments: CFRetain and CFMakeCollectable (and their families).
3065 // Eventually we should add other functions we can model entirely,
3066 // such as CFRelease, which don't invalidate their arguments or globals.
3067 if (CE->getNumArgs() != 1)
3068 return false;
3069
3070 // Get the name of the function.
3071 StringRef FName = II->getName();
3072 FName = FName.substr(FName.find_first_not_of('_'));
3073
3074 // See if it's one of the specific functions we know how to eval.
3075 bool canEval = false;
3076
Anna Zaksb805c8f2011-12-01 05:57:37 +00003077 QualType ResultTy = CE->getCallReturnType();
Jordy Rose76c506f2011-08-21 21:58:18 +00003078 if (ResultTy->isObjCIdType()) {
3079 // Handle: id NSMakeCollectable(CFTypeRef)
3080 canEval = II->isStr("NSMakeCollectable");
3081 } else if (ResultTy->isPointerType()) {
3082 // Handle: (CF|CG)Retain
3083 // CFMakeCollectable
3084 // It's okay to be a little sloppy here (CGMakeCollectable doesn't exist).
3085 if (cocoa::isRefType(ResultTy, "CF", FName) ||
3086 cocoa::isRefType(ResultTy, "CG", FName)) {
3087 canEval = isRetain(FD, FName) || isMakeCollectable(FD, FName);
3088 }
3089 }
3090
3091 if (!canEval)
3092 return false;
3093
3094 // Bind the return value.
Ted Kremenek5eca4822012-01-06 22:09:28 +00003095 const LocationContext *LCtx = C.getLocationContext();
3096 SVal RetVal = state->getSVal(CE->getArg(0), LCtx);
Jordy Rose76c506f2011-08-21 21:58:18 +00003097 if (RetVal.isUnknown()) {
3098 // If the receiver is unknown, conjure a return value.
3099 SValBuilder &SVB = C.getSValBuilder();
Anna Zaks5d0ea6d2011-10-04 20:43:05 +00003100 unsigned Count = C.getCurrentBlockCount();
Ted Kremenek3133f792012-02-17 23:13:45 +00003101 SVal RetVal = SVB.getConjuredSymbolVal(0, CE, LCtx, ResultTy, Count);
Jordy Rose76c506f2011-08-21 21:58:18 +00003102 }
Ted Kremenek5eca4822012-01-06 22:09:28 +00003103 state = state->BindExpr(CE, LCtx, RetVal, false);
Jordy Rose76c506f2011-08-21 21:58:18 +00003104
Jordy Rose294396b2011-08-22 23:48:23 +00003105 // FIXME: This should not be necessary, but otherwise the argument seems to be
3106 // considered alive during the next statement.
3107 if (const MemRegion *ArgRegion = RetVal.getAsRegion()) {
3108 // Save the refcount status of the argument.
3109 SymbolRef Sym = RetVal.getAsLocSymbol();
3110 RefBindings::data_type *Binding = 0;
3111 if (Sym)
3112 Binding = state->get<RefBindings>(Sym);
Jordy Rose76c506f2011-08-21 21:58:18 +00003113
Jordy Rose294396b2011-08-22 23:48:23 +00003114 // Invalidate the argument region.
Anna Zaks5d0ea6d2011-10-04 20:43:05 +00003115 unsigned Count = C.getCurrentBlockCount();
Ted Kremenek3133f792012-02-17 23:13:45 +00003116 state = state->invalidateRegions(ArgRegion, CE, Count, LCtx);
Jordy Rose76c506f2011-08-21 21:58:18 +00003117
Jordy Rose294396b2011-08-22 23:48:23 +00003118 // Restore the refcount status of the argument.
3119 if (Binding)
3120 state = state->set<RefBindings>(Sym, *Binding);
3121 }
3122
Anna Zaks0bd6b112011-10-26 21:06:34 +00003123 C.addTransition(state);
Jordy Rose76c506f2011-08-21 21:58:18 +00003124 return true;
3125}
3126
Jordy Rose910c4052011-09-02 06:44:22 +00003127//===----------------------------------------------------------------------===//
3128// Handle return statements.
3129//===----------------------------------------------------------------------===//
Jordy Rosef53e8c72011-08-23 19:43:16 +00003130
Ted Kremeneke5715782012-02-25 02:09:09 +00003131// Return true if the current LocationContext has no caller context.
3132static bool inTopFrame(CheckerContext &C) {
3133 const LocationContext *LC = C.getLocationContext();
3134 return LC->getParent() == 0;
3135}
3136
Jordy Rose910c4052011-09-02 06:44:22 +00003137void RetainCountChecker::checkPreStmt(const ReturnStmt *S,
3138 CheckerContext &C) const {
Ted Kremeneke5715782012-02-25 02:09:09 +00003139
3140 // Only adjust the reference count if this is the top-level call frame,
3141 // and not the result of inlining. In the future, we should do
3142 // better checking even for inlined calls, and see if they match
3143 // with their expected semantics (e.g., the method should return a retained
3144 // object, etc.).
3145 if (!inTopFrame(C))
3146 return;
3147
Jordy Rosef53e8c72011-08-23 19:43:16 +00003148 const Expr *RetE = S->getRetValue();
3149 if (!RetE)
3150 return;
3151
Ted Kremenek8bef8232012-01-26 21:29:00 +00003152 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00003153 SymbolRef Sym =
3154 state->getSValAsScalarOrLoc(RetE, C.getLocationContext()).getAsLocSymbol();
Jordy Rosef53e8c72011-08-23 19:43:16 +00003155 if (!Sym)
3156 return;
3157
3158 // Get the reference count binding (if any).
3159 const RefVal *T = state->get<RefBindings>(Sym);
3160 if (!T)
3161 return;
3162
3163 // Change the reference count.
3164 RefVal X = *T;
3165
3166 switch (X.getKind()) {
3167 case RefVal::Owned: {
3168 unsigned cnt = X.getCount();
3169 assert(cnt > 0);
3170 X.setCount(cnt - 1);
3171 X = X ^ RefVal::ReturnedOwned;
3172 break;
3173 }
3174
3175 case RefVal::NotOwned: {
3176 unsigned cnt = X.getCount();
3177 if (cnt) {
3178 X.setCount(cnt - 1);
3179 X = X ^ RefVal::ReturnedOwned;
3180 }
3181 else {
3182 X = X ^ RefVal::ReturnedNotOwned;
3183 }
3184 break;
3185 }
3186
3187 default:
3188 return;
3189 }
3190
3191 // Update the binding.
3192 state = state->set<RefBindings>(Sym, X);
Anna Zaks0bd6b112011-10-26 21:06:34 +00003193 ExplodedNode *Pred = C.addTransition(state);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003194
3195 // At this point we have updated the state properly.
3196 // Everything after this is merely checking to see if the return value has
3197 // been over- or under-retained.
3198
3199 // Did we cache out?
3200 if (!Pred)
3201 return;
3202
Jordy Rosef53e8c72011-08-23 19:43:16 +00003203 // Update the autorelease counts.
3204 static SimpleProgramPointTag
Jordy Rose910c4052011-09-02 06:44:22 +00003205 AutoreleaseTag("RetainCountChecker : Autorelease");
Anna Zaks4eff8232011-10-05 23:44:11 +00003206 GenericNodeBuilderRefCount Bd(C, &AutoreleaseTag);
Anna Zaks6a93bd52011-10-25 19:57:11 +00003207 llvm::tie(Pred, state) = handleAutoreleaseCounts(state, Bd, Pred, C, Sym, X);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003208
3209 // Did we cache out?
Jordy Rose8d228632011-08-23 20:07:14 +00003210 if (!Pred)
Jordy Rosef53e8c72011-08-23 19:43:16 +00003211 return;
3212
3213 // Get the updated binding.
3214 T = state->get<RefBindings>(Sym);
3215 assert(T);
3216 X = *T;
3217
3218 // Consult the summary of the enclosing method.
Jordy Rose17a38e22011-09-02 05:55:19 +00003219 RetainSummaryManager &Summaries = getSummaryManager(C);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003220 const Decl *CD = &Pred->getCodeDecl();
3221
3222 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CD)) {
3223 // Unlike regular functions, /all/ ObjC methods are assumed to always
3224 // follow Cocoa retain-count conventions, not just those with special
3225 // names or attributes.
Jordy Roseb6cfc092011-08-25 00:10:37 +00003226 const RetainSummary *Summ = Summaries.getMethodSummary(MD);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003227 RetEffect RE = Summ ? Summ->getRetEffect() : RetEffect::MakeNoRet();
3228 checkReturnWithRetEffect(S, C, Pred, RE, X, Sym, state);
3229 }
3230
3231 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) {
3232 if (!isa<CXXMethodDecl>(FD))
Jordy Roseb6cfc092011-08-25 00:10:37 +00003233 if (const RetainSummary *Summ = Summaries.getSummary(FD))
Jordy Rosef53e8c72011-08-23 19:43:16 +00003234 checkReturnWithRetEffect(S, C, Pred, Summ->getRetEffect(), X,
3235 Sym, state);
3236 }
3237}
3238
Jordy Rose910c4052011-09-02 06:44:22 +00003239void RetainCountChecker::checkReturnWithRetEffect(const ReturnStmt *S,
3240 CheckerContext &C,
3241 ExplodedNode *Pred,
3242 RetEffect RE, RefVal X,
3243 SymbolRef Sym,
Ted Kremenek8bef8232012-01-26 21:29:00 +00003244 ProgramStateRef state) const {
Jordy Rosef53e8c72011-08-23 19:43:16 +00003245 // Any leaks or other errors?
3246 if (X.isReturnedOwned() && X.getCount() == 0) {
3247 if (RE.getKind() != RetEffect::NoRet) {
3248 bool hasError = false;
Jordy Rose17a38e22011-09-02 05:55:19 +00003249 if (C.isObjCGCEnabled() && RE.getObjKind() == RetEffect::ObjC) {
Jordy Rosef53e8c72011-08-23 19:43:16 +00003250 // Things are more complicated with garbage collection. If the
3251 // returned object is suppose to be an Objective-C object, we have
3252 // a leak (as the caller expects a GC'ed object) because no
3253 // method should return ownership unless it returns a CF object.
3254 hasError = true;
3255 X = X ^ RefVal::ErrorGCLeakReturned;
3256 }
3257 else if (!RE.isOwned()) {
3258 // Either we are using GC and the returned object is a CF type
3259 // or we aren't using GC. In either case, we expect that the
3260 // enclosing method is expected to return ownership.
3261 hasError = true;
3262 X = X ^ RefVal::ErrorLeakReturned;
3263 }
3264
3265 if (hasError) {
3266 // Generate an error node.
3267 state = state->set<RefBindings>(Sym, X);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003268
3269 static SimpleProgramPointTag
Jordy Rose910c4052011-09-02 06:44:22 +00003270 ReturnOwnLeakTag("RetainCountChecker : ReturnsOwnLeak");
Anna Zaks0bd6b112011-10-26 21:06:34 +00003271 ExplodedNode *N = C.addTransition(state, Pred, &ReturnOwnLeakTag);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003272 if (N) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003273 const LangOptions &LOpts = C.getASTContext().getLangOpts();
Jordy Rose17a38e22011-09-02 05:55:19 +00003274 bool GCEnabled = C.isObjCGCEnabled();
Jordy Rosef53e8c72011-08-23 19:43:16 +00003275 CFRefReport *report =
Jordy Rose17a38e22011-09-02 05:55:19 +00003276 new CFRefLeakReport(*getLeakAtReturnBug(LOpts, GCEnabled),
3277 LOpts, GCEnabled, SummaryLog,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003278 N, Sym, C);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003279 C.EmitReport(report);
3280 }
3281 }
3282 }
3283 } else if (X.isReturnedNotOwned()) {
3284 if (RE.isOwned()) {
3285 // Trying to return a not owned object to a caller expecting an
3286 // owned object.
3287 state = state->set<RefBindings>(Sym, X ^ RefVal::ErrorReturnedNotOwned);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003288
3289 static SimpleProgramPointTag
Jordy Rose910c4052011-09-02 06:44:22 +00003290 ReturnNotOwnedTag("RetainCountChecker : ReturnNotOwnedForOwned");
Anna Zaks0bd6b112011-10-26 21:06:34 +00003291 ExplodedNode *N = C.addTransition(state, Pred, &ReturnNotOwnedTag);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003292 if (N) {
Jordy Rosed6334e12011-08-25 00:34:03 +00003293 if (!returnNotOwnedForOwned)
3294 returnNotOwnedForOwned.reset(new ReturnedNotOwnedForOwned());
3295
Jordy Rosef53e8c72011-08-23 19:43:16 +00003296 CFRefReport *report =
Jordy Rosed6334e12011-08-25 00:34:03 +00003297 new CFRefReport(*returnNotOwnedForOwned,
David Blaikie4e4d0842012-03-11 07:00:24 +00003298 C.getASTContext().getLangOpts(),
Jordy Rose17a38e22011-09-02 05:55:19 +00003299 C.isObjCGCEnabled(), SummaryLog, N, Sym);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003300 C.EmitReport(report);
3301 }
3302 }
3303 }
3304}
3305
Jordy Rose8d228632011-08-23 20:07:14 +00003306//===----------------------------------------------------------------------===//
Jordy Rose910c4052011-09-02 06:44:22 +00003307// Check various ways a symbol can be invalidated.
3308//===----------------------------------------------------------------------===//
3309
Anna Zaks390909c2011-10-06 00:43:15 +00003310void RetainCountChecker::checkBind(SVal loc, SVal val, const Stmt *S,
Jordy Rose910c4052011-09-02 06:44:22 +00003311 CheckerContext &C) const {
3312 // Are we storing to something that causes the value to "escape"?
3313 bool escapes = true;
3314
3315 // A value escapes in three possible cases (this may change):
3316 //
3317 // (1) we are binding to something that is not a memory region.
3318 // (2) we are binding to a memregion that does not have stack storage
3319 // (3) we are binding to a memregion with stack storage that the store
3320 // does not understand.
Ted Kremenek8bef8232012-01-26 21:29:00 +00003321 ProgramStateRef state = C.getState();
Jordy Rose910c4052011-09-02 06:44:22 +00003322
3323 if (loc::MemRegionVal *regionLoc = dyn_cast<loc::MemRegionVal>(&loc)) {
3324 escapes = !regionLoc->getRegion()->hasStackStorage();
3325
3326 if (!escapes) {
3327 // To test (3), generate a new state with the binding added. If it is
3328 // the same state, then it escapes (since the store cannot represent
3329 // the binding).
3330 escapes = (state == (state->bindLoc(*regionLoc, val)));
3331 }
3332 }
3333
3334 // If our store can represent the binding and we aren't storing to something
3335 // that doesn't have local storage then just return and have the simulation
3336 // state continue as is.
3337 if (!escapes)
3338 return;
3339
3340 // Otherwise, find all symbols referenced by 'val' that we are tracking
3341 // and stop tracking them.
3342 state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
Anna Zaks0bd6b112011-10-26 21:06:34 +00003343 C.addTransition(state);
Jordy Rose910c4052011-09-02 06:44:22 +00003344}
3345
Ted Kremenek8bef8232012-01-26 21:29:00 +00003346ProgramStateRef RetainCountChecker::evalAssume(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003347 SVal Cond,
3348 bool Assumption) const {
3349
3350 // FIXME: We may add to the interface of evalAssume the list of symbols
3351 // whose assumptions have changed. For now we just iterate through the
3352 // bindings and check if any of the tracked symbols are NULL. This isn't
3353 // too bad since the number of symbols we will track in practice are
3354 // probably small and evalAssume is only called at branches and a few
3355 // other places.
3356 RefBindings B = state->get<RefBindings>();
3357
3358 if (B.isEmpty())
3359 return state;
3360
3361 bool changed = false;
3362 RefBindings::Factory &RefBFactory = state->get_context<RefBindings>();
3363
3364 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
3365 // Check if the symbol is null (or equal to any constant).
3366 // If this is the case, stop tracking the symbol.
3367 if (state->getSymVal(I.getKey())) {
3368 changed = true;
3369 B = RefBFactory.remove(B, I.getKey());
3370 }
3371 }
3372
3373 if (changed)
3374 state = state->set<RefBindings>(B);
3375
3376 return state;
3377}
3378
Ted Kremenek8bef8232012-01-26 21:29:00 +00003379ProgramStateRef
3380RetainCountChecker::checkRegionChanges(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003381 const StoreManager::InvalidatedSymbols *invalidated,
3382 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00003383 ArrayRef<const MemRegion *> Regions,
3384 const CallOrObjCMessage *Call) const {
Jordy Rose910c4052011-09-02 06:44:22 +00003385 if (!invalidated)
3386 return state;
3387
3388 llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
3389 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
3390 E = ExplicitRegions.end(); I != E; ++I) {
3391 if (const SymbolicRegion *SR = (*I)->StripCasts()->getAs<SymbolicRegion>())
3392 WhitelistedSymbols.insert(SR->getSymbol());
3393 }
3394
3395 for (StoreManager::InvalidatedSymbols::const_iterator I=invalidated->begin(),
3396 E = invalidated->end(); I!=E; ++I) {
3397 SymbolRef sym = *I;
3398 if (WhitelistedSymbols.count(sym))
3399 continue;
3400 // Remove any existing reference-count binding.
3401 state = state->remove<RefBindings>(sym);
3402 }
3403 return state;
3404}
3405
3406//===----------------------------------------------------------------------===//
Jordy Rose8d228632011-08-23 20:07:14 +00003407// Handle dead symbols and end-of-path.
3408//===----------------------------------------------------------------------===//
3409
Ted Kremenek8bef8232012-01-26 21:29:00 +00003410std::pair<ExplodedNode *, ProgramStateRef >
3411RetainCountChecker::handleAutoreleaseCounts(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003412 GenericNodeBuilderRefCount Bd,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003413 ExplodedNode *Pred,
3414 CheckerContext &Ctx,
Jordy Rose910c4052011-09-02 06:44:22 +00003415 SymbolRef Sym, RefVal V) const {
Jordy Rose8d228632011-08-23 20:07:14 +00003416 unsigned ACnt = V.getAutoreleaseCount();
3417
3418 // No autorelease counts? Nothing to be done.
3419 if (!ACnt)
3420 return std::make_pair(Pred, state);
3421
Anna Zaks6a93bd52011-10-25 19:57:11 +00003422 assert(!Ctx.isObjCGCEnabled() && "Autorelease counts in GC mode?");
Jordy Rose8d228632011-08-23 20:07:14 +00003423 unsigned Cnt = V.getCount();
3424
3425 // FIXME: Handle sending 'autorelease' to already released object.
3426
3427 if (V.getKind() == RefVal::ReturnedOwned)
3428 ++Cnt;
3429
3430 if (ACnt <= Cnt) {
3431 if (ACnt == Cnt) {
3432 V.clearCounts();
3433 if (V.getKind() == RefVal::ReturnedOwned)
3434 V = V ^ RefVal::ReturnedNotOwned;
3435 else
3436 V = V ^ RefVal::NotOwned;
3437 } else {
3438 V.setCount(Cnt - ACnt);
3439 V.setAutoreleaseCount(0);
3440 }
3441 state = state->set<RefBindings>(Sym, V);
3442 ExplodedNode *N = Bd.MakeNode(state, Pred);
3443 if (N == 0)
3444 state = 0;
3445 return std::make_pair(N, state);
3446 }
3447
3448 // Woah! More autorelease counts then retain counts left.
3449 // Emit hard error.
3450 V = V ^ RefVal::ErrorOverAutorelease;
3451 state = state->set<RefBindings>(Sym, V);
3452
Anna Zaksf05aac82011-10-18 23:05:58 +00003453 if (ExplodedNode *N = Bd.MakeNode(state, Pred, true)) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003454 SmallString<128> sbuf;
Jordy Rose8d228632011-08-23 20:07:14 +00003455 llvm::raw_svector_ostream os(sbuf);
3456 os << "Object over-autoreleased: object was sent -autorelease ";
3457 if (V.getAutoreleaseCount() > 1)
3458 os << V.getAutoreleaseCount() << " times ";
3459 os << "but the object has a +" << V.getCount() << " retain count";
3460
Jordy Rosed6334e12011-08-25 00:34:03 +00003461 if (!overAutorelease)
3462 overAutorelease.reset(new OverAutorelease());
3463
David Blaikie4e4d0842012-03-11 07:00:24 +00003464 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
Jordy Rose8d228632011-08-23 20:07:14 +00003465 CFRefReport *report =
Jordy Rosed6334e12011-08-25 00:34:03 +00003466 new CFRefReport(*overAutorelease, LOpts, /* GCEnabled = */ false,
3467 SummaryLog, N, Sym, os.str());
Anna Zaks6a93bd52011-10-25 19:57:11 +00003468 Ctx.EmitReport(report);
Jordy Rose8d228632011-08-23 20:07:14 +00003469 }
3470
Ted Kremenek8bef8232012-01-26 21:29:00 +00003471 return std::make_pair((ExplodedNode *)0, (ProgramStateRef )0);
Jordy Rose8d228632011-08-23 20:07:14 +00003472}
Jordy Rose38f17d62011-08-23 19:01:07 +00003473
Ted Kremenek8bef8232012-01-26 21:29:00 +00003474ProgramStateRef
3475RetainCountChecker::handleSymbolDeath(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003476 SymbolRef sid, RefVal V,
Jordy Rose38f17d62011-08-23 19:01:07 +00003477 SmallVectorImpl<SymbolRef> &Leaked) const {
Jordy Rose53376122011-08-24 04:48:19 +00003478 bool hasLeak = false;
Jordy Rose38f17d62011-08-23 19:01:07 +00003479 if (V.isOwned())
3480 hasLeak = true;
3481 else if (V.isNotOwned() || V.isReturnedOwned())
3482 hasLeak = (V.getCount() > 0);
3483
3484 if (!hasLeak)
3485 return state->remove<RefBindings>(sid);
3486
3487 Leaked.push_back(sid);
3488 return state->set<RefBindings>(sid, V ^ RefVal::ErrorLeak);
3489}
3490
3491ExplodedNode *
Ted Kremenek8bef8232012-01-26 21:29:00 +00003492RetainCountChecker::processLeaks(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003493 SmallVectorImpl<SymbolRef> &Leaked,
3494 GenericNodeBuilderRefCount &Builder,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003495 CheckerContext &Ctx,
3496 ExplodedNode *Pred) const {
Jordy Rose38f17d62011-08-23 19:01:07 +00003497 if (Leaked.empty())
3498 return Pred;
3499
3500 // Generate an intermediate node representing the leak point.
3501 ExplodedNode *N = Builder.MakeNode(state, Pred);
3502
3503 if (N) {
3504 for (SmallVectorImpl<SymbolRef>::iterator
3505 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3506
David Blaikie4e4d0842012-03-11 07:00:24 +00003507 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
Anna Zaks6a93bd52011-10-25 19:57:11 +00003508 bool GCEnabled = Ctx.isObjCGCEnabled();
Jordy Rose17a38e22011-09-02 05:55:19 +00003509 CFRefBug *BT = Pred ? getLeakWithinFunctionBug(LOpts, GCEnabled)
3510 : getLeakAtReturnBug(LOpts, GCEnabled);
Jordy Rose38f17d62011-08-23 19:01:07 +00003511 assert(BT && "BugType not initialized.");
Jordy Rose20589562011-08-24 22:39:09 +00003512
Jordy Rose17a38e22011-09-02 05:55:19 +00003513 CFRefLeakReport *report = new CFRefLeakReport(*BT, LOpts, GCEnabled,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003514 SummaryLog, N, *I, Ctx);
3515 Ctx.EmitReport(report);
Jordy Rose38f17d62011-08-23 19:01:07 +00003516 }
3517 }
3518
3519 return N;
3520}
3521
Anna Zaksaf498a22011-10-25 19:56:48 +00003522void RetainCountChecker::checkEndPath(CheckerContext &Ctx) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +00003523 ProgramStateRef state = Ctx.getState();
Anna Zaksaf498a22011-10-25 19:56:48 +00003524 GenericNodeBuilderRefCount Bd(Ctx);
Jordy Rose38f17d62011-08-23 19:01:07 +00003525 RefBindings B = state->get<RefBindings>();
Anna Zaksaf498a22011-10-25 19:56:48 +00003526 ExplodedNode *Pred = Ctx.getPredecessor();
Jordy Rose38f17d62011-08-23 19:01:07 +00003527
3528 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Anna Zaks6a93bd52011-10-25 19:57:11 +00003529 llvm::tie(Pred, state) = handleAutoreleaseCounts(state, Bd, Pred, Ctx,
Jordy Rose8d228632011-08-23 20:07:14 +00003530 I->first, I->second);
3531 if (!state)
Jordy Rose38f17d62011-08-23 19:01:07 +00003532 return;
3533 }
3534
Ted Kremenek0cf3d472012-02-07 00:24:33 +00003535 // If the current LocationContext has a parent, don't check for leaks.
3536 // We will do that later.
3537 // FIXME: we should instead check for imblances of the retain/releases,
3538 // and suggest annotations.
3539 if (Ctx.getLocationContext()->getParent())
3540 return;
3541
Jordy Rose38f17d62011-08-23 19:01:07 +00003542 B = state->get<RefBindings>();
3543 SmallVector<SymbolRef, 10> Leaked;
3544
3545 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I)
Jordy Rose8d228632011-08-23 20:07:14 +00003546 state = handleSymbolDeath(state, I->first, I->second, Leaked);
Jordy Rose38f17d62011-08-23 19:01:07 +00003547
Anna Zaks6a93bd52011-10-25 19:57:11 +00003548 processLeaks(state, Leaked, Bd, Ctx, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003549}
3550
3551const ProgramPointTag *
Jordy Rose910c4052011-09-02 06:44:22 +00003552RetainCountChecker::getDeadSymbolTag(SymbolRef sym) const {
Jordy Rose38f17d62011-08-23 19:01:07 +00003553 const SimpleProgramPointTag *&tag = DeadSymbolTags[sym];
3554 if (!tag) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003555 SmallString<64> buf;
Jordy Rose38f17d62011-08-23 19:01:07 +00003556 llvm::raw_svector_ostream out(buf);
Anna Zaksf62ceec2011-12-05 18:58:11 +00003557 out << "RetainCountChecker : Dead Symbol : ";
3558 sym->dumpToStream(out);
Jordy Rose38f17d62011-08-23 19:01:07 +00003559 tag = new SimpleProgramPointTag(out.str());
3560 }
3561 return tag;
3562}
3563
Jordy Rose910c4052011-09-02 06:44:22 +00003564void RetainCountChecker::checkDeadSymbols(SymbolReaper &SymReaper,
3565 CheckerContext &C) const {
Jordy Rose38f17d62011-08-23 19:01:07 +00003566 ExplodedNode *Pred = C.getPredecessor();
3567
Ted Kremenek8bef8232012-01-26 21:29:00 +00003568 ProgramStateRef state = C.getState();
Jordy Rose38f17d62011-08-23 19:01:07 +00003569 RefBindings B = state->get<RefBindings>();
3570
3571 // Update counts from autorelease pools
3572 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3573 E = SymReaper.dead_end(); I != E; ++I) {
3574 SymbolRef Sym = *I;
3575 if (const RefVal *T = B.lookup(Sym)){
3576 // Use the symbol as the tag.
3577 // FIXME: This might not be as unique as we would like.
Anna Zaks4eff8232011-10-05 23:44:11 +00003578 GenericNodeBuilderRefCount Bd(C, getDeadSymbolTag(Sym));
Anna Zaks6a93bd52011-10-25 19:57:11 +00003579 llvm::tie(Pred, state) = handleAutoreleaseCounts(state, Bd, Pred, C,
Jordy Rose8d228632011-08-23 20:07:14 +00003580 Sym, *T);
3581 if (!state)
Jordy Rose38f17d62011-08-23 19:01:07 +00003582 return;
3583 }
3584 }
3585
3586 B = state->get<RefBindings>();
3587 SmallVector<SymbolRef, 10> Leaked;
3588
3589 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3590 E = SymReaper.dead_end(); I != E; ++I) {
3591 if (const RefVal *T = B.lookup(*I))
3592 state = handleSymbolDeath(state, *I, *T, Leaked);
3593 }
3594
3595 {
Anna Zaks4eff8232011-10-05 23:44:11 +00003596 GenericNodeBuilderRefCount Bd(C, this);
Anna Zaks6a93bd52011-10-25 19:57:11 +00003597 Pred = processLeaks(state, Leaked, Bd, C, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003598 }
3599
3600 // Did we cache out?
3601 if (!Pred)
3602 return;
3603
3604 // Now generate a new node that nukes the old bindings.
3605 RefBindings::Factory &F = state->get_context<RefBindings>();
3606
3607 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3608 E = SymReaper.dead_end(); I != E; ++I)
3609 B = F.remove(B, *I);
3610
3611 state = state->set<RefBindings>(B);
Anna Zaks0bd6b112011-10-26 21:06:34 +00003612 C.addTransition(state, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003613}
3614
Ted Kremenekd593eb92009-11-25 22:17:44 +00003615//===----------------------------------------------------------------------===//
Jordy Rosedbd658e2011-08-28 19:11:56 +00003616// Debug printing of refcount bindings and autorelease pools.
3617//===----------------------------------------------------------------------===//
3618
3619static void PrintPool(raw_ostream &Out, SymbolRef Sym,
Ted Kremenek8bef8232012-01-26 21:29:00 +00003620 ProgramStateRef State) {
Jordy Rosedbd658e2011-08-28 19:11:56 +00003621 Out << ' ';
3622 if (Sym)
Anna Zaksf62ceec2011-12-05 18:58:11 +00003623 Sym->dumpToStream(Out);
Jordy Rosedbd658e2011-08-28 19:11:56 +00003624 else
3625 Out << "<pool>";
3626 Out << ":{";
3627
3628 // Get the contents of the pool.
3629 if (const ARCounts *Cnts = State->get<AutoreleasePoolContents>(Sym))
3630 for (ARCounts::iterator I = Cnts->begin(), E = Cnts->end(); I != E; ++I)
3631 Out << '(' << I.getKey() << ',' << I.getData() << ')';
3632
3633 Out << '}';
3634}
3635
Ted Kremenek8bef8232012-01-26 21:29:00 +00003636static bool UsesAutorelease(ProgramStateRef state) {
Jordy Rosedbd658e2011-08-28 19:11:56 +00003637 // A state uses autorelease if it allocated an autorelease pool or if it has
3638 // objects in the caller's autorelease pool.
3639 return !state->get<AutoreleaseStack>().isEmpty() ||
3640 state->get<AutoreleasePoolContents>(SymbolRef());
3641}
3642
Ted Kremenek8bef8232012-01-26 21:29:00 +00003643void RetainCountChecker::printState(raw_ostream &Out, ProgramStateRef State,
Jordy Rose910c4052011-09-02 06:44:22 +00003644 const char *NL, const char *Sep) const {
Jordy Rosedbd658e2011-08-28 19:11:56 +00003645
3646 RefBindings B = State->get<RefBindings>();
3647
3648 if (!B.isEmpty())
3649 Out << Sep << NL;
3650
3651 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
3652 Out << I->first << " : ";
3653 I->second.print(Out);
3654 Out << NL;
3655 }
3656
3657 // Print the autorelease stack.
3658 if (UsesAutorelease(State)) {
3659 Out << Sep << NL << "AR pool stack:";
3660 ARStack Stack = State->get<AutoreleaseStack>();
3661
3662 PrintPool(Out, SymbolRef(), State); // Print the caller's pool.
3663 for (ARStack::iterator I = Stack.begin(), E = Stack.end(); I != E; ++I)
3664 PrintPool(Out, *I, State);
3665
3666 Out << NL;
3667 }
3668}
3669
3670//===----------------------------------------------------------------------===//
Jordy Rose910c4052011-09-02 06:44:22 +00003671// Checker registration.
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00003672//===----------------------------------------------------------------------===//
3673
Jordy Rose17a38e22011-09-02 05:55:19 +00003674void ento::registerRetainCountChecker(CheckerManager &Mgr) {
Jordy Rose910c4052011-09-02 06:44:22 +00003675 Mgr.registerChecker<RetainCountChecker>();
Jordy Rose17a38e22011-09-02 05:55:19 +00003676}
3677