blob: 541a8b7c15760ac082ae2f4ba1a15d6e125844e7 [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"
Jordan Rose4531b7d2012-07-02 19:27:43 +000026#include "clang/StaticAnalyzer/Core/PathSensitive/Calls.h"
Jordy Rose910c4052011-09-02 06:44:22 +000027#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
Ted Kremenek18c66fd2011-08-15 22:09:50 +000028#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
Ted Kremenek9b663712011-02-10 01:03:03 +000029#include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.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,
Jordan Rose4531b7d2012-07-02 19:27:43 +000069 DecRefAndStopTracking, DecRefMsgAndStopTracking,
Jordy Rosebd85b132011-08-24 19:10:50 +000070 IncRefMsg, IncRef, MakeCollectable, MayEscape,
Jordan Rose29299c62012-06-27 00:51:18 +000071 NewAutoreleasePool, StopTracking };
Ted Kremenek553cf182008-06-25 21:21:56 +000072
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000073namespace llvm {
Ted Kremenekb77449c2009-05-03 05:20:50 +000074template <> struct FoldingSetTrait<ArgEffect> {
75static inline void Profile(const ArgEffect X, FoldingSetNodeID& ID) {
76 ID.AddInteger((unsigned) X);
77}
Ted Kremenek553cf182008-06-25 21:21:56 +000078};
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000079} // end llvm namespace
80
Ted Kremenekb77449c2009-05-03 05:20:50 +000081/// ArgEffects summarizes the effects of a function/method call on all of
82/// its arguments.
83typedef llvm::ImmutableMap<unsigned,ArgEffect> ArgEffects;
84
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000085namespace {
Ted Kremenek553cf182008-06-25 21:21:56 +000086
87/// RetEffect is used to summarize a function/method call's behavior with
Mike Stump1eb44332009-09-09 15:08:12 +000088/// respect to its return value.
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +000089class RetEffect {
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000090public:
Jordy Rose76c506f2011-08-21 21:58:18 +000091 enum Kind { NoRet, OwnedSymbol, OwnedAllocatedSymbol,
John McCallf85e1932011-06-15 23:02:42 +000092 NotOwnedSymbol, GCNotOwnedSymbol, ARCNotOwnedSymbol,
Ted Kremenek78a35a32009-05-12 20:06:54 +000093 OwnedWhenTrackedReceiver };
Mike Stump1eb44332009-09-09 15:08:12 +000094
95 enum ObjKind { CF, ObjC, AnyObj };
Ted Kremenek2d1652e2009-01-28 05:56:51 +000096
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000097private:
Ted Kremenek2d1652e2009-01-28 05:56:51 +000098 Kind K;
99 ObjKind O;
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000100
Jordy Rose76c506f2011-08-21 21:58:18 +0000101 RetEffect(Kind k, ObjKind o = AnyObj) : K(k), O(o) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000102
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000103public:
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000104 Kind getKind() const { return K; }
105
106 ObjKind getObjKind() const { return O; }
Mike Stump1eb44332009-09-09 15:08:12 +0000107
Ted Kremeneka8833552009-04-29 23:03:22 +0000108 bool isOwned() const {
Ted Kremenek78a35a32009-05-12 20:06:54 +0000109 return K == OwnedSymbol || K == OwnedAllocatedSymbol ||
110 K == OwnedWhenTrackedReceiver;
Ted Kremeneka8833552009-04-29 23:03:22 +0000111 }
Mike Stump1eb44332009-09-09 15:08:12 +0000112
Jordy Rose4df54fe2011-08-23 04:27:15 +0000113 bool operator==(const RetEffect &Other) const {
114 return K == Other.K && O == Other.O;
115 }
116
Ted Kremenek78a35a32009-05-12 20:06:54 +0000117 static RetEffect MakeOwnedWhenTrackedReceiver() {
118 return RetEffect(OwnedWhenTrackedReceiver, ObjC);
119 }
Mike Stump1eb44332009-09-09 15:08:12 +0000120
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000121 static RetEffect MakeOwned(ObjKind o, bool isAllocated = false) {
122 return RetEffect(isAllocated ? OwnedAllocatedSymbol : OwnedSymbol, o);
Mike Stump1eb44332009-09-09 15:08:12 +0000123 }
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000124 static RetEffect MakeNotOwned(ObjKind o) {
125 return RetEffect(NotOwnedSymbol, o);
Ted Kremeneke798e7c2009-04-27 19:14:45 +0000126 }
127 static RetEffect MakeGCNotOwned() {
128 return RetEffect(GCNotOwnedSymbol, ObjC);
129 }
John McCallf85e1932011-06-15 23:02:42 +0000130 static RetEffect MakeARCNotOwned() {
131 return RetEffect(ARCNotOwnedSymbol, ObjC);
132 }
Ted Kremenek553cf182008-06-25 21:21:56 +0000133 static RetEffect MakeNoRet() {
134 return RetEffect(NoRet);
Ted Kremeneka7344702008-06-23 18:02:52 +0000135 }
Jordy Roseef945882012-03-18 01:26:10 +0000136
137 void Profile(llvm::FoldingSetNodeID& ID) const {
138 ID.AddInteger((unsigned) K);
139 ID.AddInteger((unsigned) O);
140 }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000141};
Mike Stump1eb44332009-09-09 15:08:12 +0000142
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000143//===----------------------------------------------------------------------===//
144// Reference-counting logic (typestate + counts).
145//===----------------------------------------------------------------------===//
Mike Stump1eb44332009-09-09 15:08:12 +0000146
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000147class RefVal {
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000148public:
149 enum Kind {
150 Owned = 0, // Owning reference.
151 NotOwned, // Reference is not owned by still valid (not freed).
152 Released, // Object has been released.
153 ReturnedOwned, // Returned object passes ownership to caller.
154 ReturnedNotOwned, // Return object does not pass ownership to caller.
155 ERROR_START,
156 ErrorDeallocNotOwned, // -dealloc called on non-owned object.
157 ErrorDeallocGC, // Calling -dealloc with GC enabled.
158 ErrorUseAfterRelease, // Object used after released.
159 ErrorReleaseNotOwned, // Release of an object that was not owned.
160 ERROR_LEAK_START,
161 ErrorLeak, // A memory leak due to excessive reference counts.
162 ErrorLeakReturned, // A memory leak due to the returning method not having
163 // the correct naming conventions.
164 ErrorGCLeakReturned,
165 ErrorOverAutorelease,
166 ErrorReturnedNotOwned
167 };
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000168
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000169private:
170 Kind kind;
171 RetEffect::ObjKind okind;
172 unsigned Cnt;
173 unsigned ACnt;
174 QualType T;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000175
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000176 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, unsigned acnt, QualType t)
177 : kind(k), okind(o), Cnt(cnt), ACnt(acnt), T(t) {}
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000178
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000179public:
180 Kind getKind() const { return kind; }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000181
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000182 RetEffect::ObjKind getObjKind() const { return okind; }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000183
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000184 unsigned getCount() const { return Cnt; }
185 unsigned getAutoreleaseCount() const { return ACnt; }
186 unsigned getCombinedCounts() const { return Cnt + ACnt; }
187 void clearCounts() { Cnt = 0; ACnt = 0; }
188 void setCount(unsigned i) { Cnt = i; }
189 void setAutoreleaseCount(unsigned i) { ACnt = i; }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000190
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000191 QualType getType() const { return T; }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000192
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000193 bool isOwned() const {
194 return getKind() == Owned;
195 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000196
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000197 bool isNotOwned() const {
198 return getKind() == NotOwned;
199 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000200
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000201 bool isReturnedOwned() const {
202 return getKind() == ReturnedOwned;
203 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000204
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000205 bool isReturnedNotOwned() const {
206 return getKind() == ReturnedNotOwned;
207 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000208
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000209 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
210 unsigned Count = 1) {
211 return RefVal(Owned, o, Count, 0, t);
212 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000213
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000214 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
215 unsigned Count = 0) {
216 return RefVal(NotOwned, o, Count, 0, t);
217 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000218
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000219 // Comparison, profiling, and pretty-printing.
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000220
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000221 bool operator==(const RefVal& X) const {
222 return kind == X.kind && Cnt == X.Cnt && T == X.T && ACnt == X.ACnt;
223 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000224
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000225 RefVal operator-(size_t i) const {
226 return RefVal(getKind(), getObjKind(), getCount() - i,
227 getAutoreleaseCount(), getType());
228 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000229
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000230 RefVal operator+(size_t i) const {
231 return RefVal(getKind(), getObjKind(), getCount() + i,
232 getAutoreleaseCount(), getType());
233 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000234
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000235 RefVal operator^(Kind k) const {
236 return RefVal(k, getObjKind(), getCount(), getAutoreleaseCount(),
237 getType());
238 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000239
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000240 RefVal autorelease() const {
241 return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount()+1,
242 getType());
243 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000244
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000245 void Profile(llvm::FoldingSetNodeID& ID) const {
246 ID.AddInteger((unsigned) kind);
247 ID.AddInteger(Cnt);
248 ID.AddInteger(ACnt);
249 ID.Add(T);
250 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000251
Ted Kremenek9c378f72011-08-12 23:37:29 +0000252 void print(raw_ostream &Out) const;
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000253};
254
Ted Kremenek9c378f72011-08-12 23:37:29 +0000255void RefVal::print(raw_ostream &Out) const {
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000256 if (!T.isNull())
Jordy Rosedbd658e2011-08-28 19:11:56 +0000257 Out << "Tracked " << T.getAsString() << '/';
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000258
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000259 switch (getKind()) {
Jordy Rose910c4052011-09-02 06:44:22 +0000260 default: llvm_unreachable("Invalid RefVal kind");
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000261 case Owned: {
262 Out << "Owned";
263 unsigned cnt = getCount();
264 if (cnt) Out << " (+ " << cnt << ")";
265 break;
266 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000267
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000268 case NotOwned: {
269 Out << "NotOwned";
270 unsigned cnt = getCount();
271 if (cnt) Out << " (+ " << cnt << ")";
272 break;
273 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000274
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000275 case ReturnedOwned: {
276 Out << "ReturnedOwned";
277 unsigned cnt = getCount();
278 if (cnt) Out << " (+ " << cnt << ")";
279 break;
280 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000281
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000282 case ReturnedNotOwned: {
283 Out << "ReturnedNotOwned";
284 unsigned cnt = getCount();
285 if (cnt) Out << " (+ " << cnt << ")";
286 break;
287 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000288
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000289 case Released:
290 Out << "Released";
291 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000292
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000293 case ErrorDeallocGC:
294 Out << "-dealloc (GC)";
295 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000296
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000297 case ErrorDeallocNotOwned:
298 Out << "-dealloc (not-owned)";
299 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000300
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000301 case ErrorLeak:
302 Out << "Leaked";
303 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000304
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000305 case ErrorLeakReturned:
306 Out << "Leaked (Bad naming)";
307 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000308
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000309 case ErrorGCLeakReturned:
310 Out << "Leaked (GC-ed at return)";
311 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000312
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000313 case ErrorUseAfterRelease:
314 Out << "Use-After-Release [ERROR]";
315 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000316
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000317 case ErrorReleaseNotOwned:
318 Out << "Release of Not-Owned [ERROR]";
319 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000320
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000321 case RefVal::ErrorOverAutorelease:
322 Out << "Over autoreleased";
323 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000324
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000325 case RefVal::ErrorReturnedNotOwned:
326 Out << "Non-owned object returned instead of owned";
327 break;
328 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000329
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000330 if (ACnt) {
331 Out << " [ARC +" << ACnt << ']';
332 }
333}
334} //end anonymous namespace
335
336//===----------------------------------------------------------------------===//
337// RefBindings - State used to track object reference counts.
338//===----------------------------------------------------------------------===//
339
340typedef llvm::ImmutableMap<SymbolRef, RefVal> RefBindings;
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000341
342namespace clang {
Ted Kremenek9ef65372010-12-23 07:20:52 +0000343namespace ento {
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000344template<>
345struct ProgramStateTrait<RefBindings>
346 : public ProgramStatePartialTrait<RefBindings> {
347 static void *GDMIndex() {
348 static int RefBIndex = 0;
349 return &RefBIndex;
350 }
351};
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000352}
Argyrios Kyrtzidis5a4f98f2010-12-22 18:53:20 +0000353}
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000354
355//===----------------------------------------------------------------------===//
Jordy Rose910c4052011-09-02 06:44:22 +0000356// Function/Method behavior summaries.
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000357//===----------------------------------------------------------------------===//
358
359namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000360class RetainSummary {
Jordy Roseef945882012-03-18 01:26:10 +0000361 /// Args - a map of (index, ArgEffect) pairs, where index
Ted Kremenek1bffd742008-05-06 15:44:25 +0000362 /// specifies the argument (starting from 0). This can be sparsely
363 /// populated; arguments with no entry in Args use 'DefaultArgEffect'.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000364 ArgEffects Args;
Mike Stump1eb44332009-09-09 15:08:12 +0000365
Ted Kremenek1bffd742008-05-06 15:44:25 +0000366 /// DefaultArgEffect - The default ArgEffect to apply to arguments that
367 /// do not have an entry in Args.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000368 ArgEffect DefaultArgEffect;
Mike Stump1eb44332009-09-09 15:08:12 +0000369
Ted Kremenek553cf182008-06-25 21:21:56 +0000370 /// Receiver - If this summary applies to an Objective-C message expression,
371 /// this is the effect applied to the state of the receiver.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000372 ArgEffect Receiver;
Mike Stump1eb44332009-09-09 15:08:12 +0000373
Ted Kremenek553cf182008-06-25 21:21:56 +0000374 /// Ret - The effect on the return value. Used to indicate if the
Jordy Rose76c506f2011-08-21 21:58:18 +0000375 /// function/method call returns a new tracked symbol.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000376 RetEffect Ret;
Mike Stump1eb44332009-09-09 15:08:12 +0000377
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000378public:
Ted Kremenekb77449c2009-05-03 05:20:50 +0000379 RetainSummary(ArgEffects A, RetEffect R, ArgEffect defaultEff,
Jordy Rosee62e87b2011-08-20 20:55:40 +0000380 ArgEffect ReceiverEff)
381 : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000382
Ted Kremenek553cf182008-06-25 21:21:56 +0000383 /// getArg - Return the argument effect on the argument specified by
384 /// idx (starting from 0).
Ted Kremenek1ac08d62008-03-11 17:48:22 +0000385 ArgEffect getArg(unsigned idx) const {
Ted Kremenekb77449c2009-05-03 05:20:50 +0000386 if (const ArgEffect *AE = Args.lookup(idx))
387 return *AE;
Mike Stump1eb44332009-09-09 15:08:12 +0000388
Ted Kremenek1bffd742008-05-06 15:44:25 +0000389 return DefaultArgEffect;
Ted Kremenek1ac08d62008-03-11 17:48:22 +0000390 }
Ted Kremenek11fe1752011-01-27 18:43:03 +0000391
392 void addArg(ArgEffects::Factory &af, unsigned idx, ArgEffect e) {
393 Args = af.add(Args, idx, e);
394 }
Mike Stump1eb44332009-09-09 15:08:12 +0000395
Ted Kremenek885c27b2009-05-04 05:31:22 +0000396 /// setDefaultArgEffect - Set the default argument effect.
397 void setDefaultArgEffect(ArgEffect E) {
398 DefaultArgEffect = E;
399 }
Mike Stump1eb44332009-09-09 15:08:12 +0000400
Ted Kremenek553cf182008-06-25 21:21:56 +0000401 /// getRetEffect - Returns the effect on the return value of the call.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000402 RetEffect getRetEffect() const { return Ret; }
Mike Stump1eb44332009-09-09 15:08:12 +0000403
Ted Kremenek885c27b2009-05-04 05:31:22 +0000404 /// setRetEffect - Set the effect of the return value of the call.
405 void setRetEffect(RetEffect E) { Ret = E; }
Mike Stump1eb44332009-09-09 15:08:12 +0000406
Ted Kremenek12b94342011-01-27 06:54:14 +0000407
408 /// Sets the effect on the receiver of the message.
409 void setReceiverEffect(ArgEffect e) { Receiver = e; }
410
Ted Kremenek553cf182008-06-25 21:21:56 +0000411 /// getReceiverEffect - Returns the effect on the receiver of the call.
412 /// This is only meaningful if the summary applies to an ObjCMessageExpr*.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000413 ArgEffect getReceiverEffect() const { return Receiver; }
Jordy Rose4df54fe2011-08-23 04:27:15 +0000414
415 /// Test if two retain summaries are identical. Note that merely equivalent
416 /// summaries are not necessarily identical (for example, if an explicit
417 /// argument effect matches the default effect).
418 bool operator==(const RetainSummary &Other) const {
419 return Args == Other.Args && DefaultArgEffect == Other.DefaultArgEffect &&
420 Receiver == Other.Receiver && Ret == Other.Ret;
421 }
Jordy Roseef945882012-03-18 01:26:10 +0000422
423 /// Profile this summary for inclusion in a FoldingSet.
424 void Profile(llvm::FoldingSetNodeID& ID) const {
425 ID.Add(Args);
426 ID.Add(DefaultArgEffect);
427 ID.Add(Receiver);
428 ID.Add(Ret);
429 }
430
431 /// A retain summary is simple if it has no ArgEffects other than the default.
432 bool isSimple() const {
433 return Args.isEmpty();
434 }
Jordan Rose4531b7d2012-07-02 19:27:43 +0000435
436private:
437 ArgEffects getArgEffects() const { return Args; }
438 ArgEffect getDefaultArgEffect() const { return DefaultArgEffect; }
439
440 friend class RetainSummaryManager;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000441};
Ted Kremenek4f22a782008-06-23 23:30:29 +0000442} // end anonymous namespace
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000443
Ted Kremenek553cf182008-06-25 21:21:56 +0000444//===----------------------------------------------------------------------===//
445// Data structures for constructing summaries.
446//===----------------------------------------------------------------------===//
Ted Kremenek53301ba2008-06-24 03:49:48 +0000447
Ted Kremenek553cf182008-06-25 21:21:56 +0000448namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000449class ObjCSummaryKey {
Ted Kremenek553cf182008-06-25 21:21:56 +0000450 IdentifierInfo* II;
451 Selector S;
Mike Stump1eb44332009-09-09 15:08:12 +0000452public:
Ted Kremenek553cf182008-06-25 21:21:56 +0000453 ObjCSummaryKey(IdentifierInfo* ii, Selector s)
454 : II(ii), S(s) {}
455
Ted Kremenek9c378f72011-08-12 23:37:29 +0000456 ObjCSummaryKey(const ObjCInterfaceDecl *d, Selector s)
Ted Kremenek553cf182008-06-25 21:21:56 +0000457 : II(d ? d->getIdentifier() : 0), S(s) {}
Ted Kremenek70b6a832009-05-13 18:16:01 +0000458
Ted Kremenek553cf182008-06-25 21:21:56 +0000459 ObjCSummaryKey(Selector s)
460 : II(0), S(s) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000461
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000462 IdentifierInfo *getIdentifier() const { return II; }
Ted Kremenek553cf182008-06-25 21:21:56 +0000463 Selector getSelector() const { return S; }
464};
Ted Kremenek4f22a782008-06-23 23:30:29 +0000465}
466
467namespace llvm {
Ted Kremenek553cf182008-06-25 21:21:56 +0000468template <> struct DenseMapInfo<ObjCSummaryKey> {
469 static inline ObjCSummaryKey getEmptyKey() {
470 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
471 DenseMapInfo<Selector>::getEmptyKey());
472 }
Mike Stump1eb44332009-09-09 15:08:12 +0000473
Ted Kremenek553cf182008-06-25 21:21:56 +0000474 static inline ObjCSummaryKey getTombstoneKey() {
475 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
Mike Stump1eb44332009-09-09 15:08:12 +0000476 DenseMapInfo<Selector>::getTombstoneKey());
Ted Kremenek553cf182008-06-25 21:21:56 +0000477 }
Mike Stump1eb44332009-09-09 15:08:12 +0000478
Ted Kremenek553cf182008-06-25 21:21:56 +0000479 static unsigned getHashValue(const ObjCSummaryKey &V) {
Benjamin Kramer28b23072012-05-27 13:28:44 +0000480 typedef std::pair<IdentifierInfo*, Selector> PairTy;
481 return DenseMapInfo<PairTy>::getHashValue(PairTy(V.getIdentifier(),
482 V.getSelector()));
Ted Kremenek553cf182008-06-25 21:21:56 +0000483 }
Mike Stump1eb44332009-09-09 15:08:12 +0000484
Ted Kremenek553cf182008-06-25 21:21:56 +0000485 static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
Benjamin Kramer28b23072012-05-27 13:28:44 +0000486 return LHS.getIdentifier() == RHS.getIdentifier() &&
487 LHS.getSelector() == RHS.getSelector();
Ted Kremenek553cf182008-06-25 21:21:56 +0000488 }
Mike Stump1eb44332009-09-09 15:08:12 +0000489
Ted Kremenek553cf182008-06-25 21:21:56 +0000490};
Chris Lattner06159e82009-12-15 07:26:51 +0000491template <>
492struct isPodLike<ObjCSummaryKey> { static const bool value = true; };
Ted Kremenek4f22a782008-06-23 23:30:29 +0000493} // end llvm namespace
Mike Stump1eb44332009-09-09 15:08:12 +0000494
Ted Kremenek4f22a782008-06-23 23:30:29 +0000495namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000496class ObjCSummaryCache {
Ted Kremenek93edbc52011-10-05 23:54:29 +0000497 typedef llvm::DenseMap<ObjCSummaryKey, const RetainSummary *> MapTy;
Ted Kremenek553cf182008-06-25 21:21:56 +0000498 MapTy M;
499public:
500 ObjCSummaryCache() {}
Mike Stump1eb44332009-09-09 15:08:12 +0000501
Ted Kremenek93edbc52011-10-05 23:54:29 +0000502 const RetainSummary * find(const ObjCInterfaceDecl *D, Selector S) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000503 // Do a lookup with the (D,S) pair. If we find a match return
504 // the iterator.
505 ObjCSummaryKey K(D, S);
506 MapTy::iterator I = M.find(K);
Mike Stump1eb44332009-09-09 15:08:12 +0000507
Jordan Rose4531b7d2012-07-02 19:27:43 +0000508 if (I != M.end())
Ted Kremenek614cc542009-07-21 23:27:57 +0000509 return I->second;
Jordan Rose4531b7d2012-07-02 19:27:43 +0000510 if (!D)
511 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +0000512
Ted Kremenek553cf182008-06-25 21:21:56 +0000513 // Walk the super chain. If we find a hit with a parent, we'll end
514 // up returning that summary. We actually allow that key (null,S), as
515 // we cache summaries for the null ObjCInterfaceDecl* to allow us to
516 // generate initial summaries without having to worry about NSObject
517 // being declared.
518 // FIXME: We may change this at some point.
Ted Kremenek9c378f72011-08-12 23:37:29 +0000519 for (ObjCInterfaceDecl *C=D->getSuperClass() ;; C=C->getSuperClass()) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000520 if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
521 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000522
Ted Kremenek553cf182008-06-25 21:21:56 +0000523 if (!C)
Ted Kremenek614cc542009-07-21 23:27:57 +0000524 return NULL;
Ted Kremenek553cf182008-06-25 21:21:56 +0000525 }
Mike Stump1eb44332009-09-09 15:08:12 +0000526
527 // Cache the summary with original key to make the next lookup faster
Ted Kremenek553cf182008-06-25 21:21:56 +0000528 // and return the iterator.
Ted Kremenek93edbc52011-10-05 23:54:29 +0000529 const RetainSummary *Summ = I->second;
Ted Kremenek614cc542009-07-21 23:27:57 +0000530 M[K] = Summ;
531 return Summ;
Ted Kremenek553cf182008-06-25 21:21:56 +0000532 }
Mike Stump1eb44332009-09-09 15:08:12 +0000533
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000534 const RetainSummary *find(IdentifierInfo* II, Selector S) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000535 // FIXME: Class method lookup. Right now we dont' have a good way
536 // of going between IdentifierInfo* and the class hierarchy.
Ted Kremenek614cc542009-07-21 23:27:57 +0000537 MapTy::iterator I = M.find(ObjCSummaryKey(II, S));
Mike Stump1eb44332009-09-09 15:08:12 +0000538
Ted Kremenek614cc542009-07-21 23:27:57 +0000539 if (I == M.end())
540 I = M.find(ObjCSummaryKey(S));
Mike Stump1eb44332009-09-09 15:08:12 +0000541
Ted Kremenek614cc542009-07-21 23:27:57 +0000542 return I == M.end() ? NULL : I->second;
Ted Kremenek553cf182008-06-25 21:21:56 +0000543 }
Mike Stump1eb44332009-09-09 15:08:12 +0000544
Ted Kremenek93edbc52011-10-05 23:54:29 +0000545 const RetainSummary *& operator[](ObjCSummaryKey K) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000546 return M[K];
547 }
Mike Stump1eb44332009-09-09 15:08:12 +0000548
Ted Kremenek93edbc52011-10-05 23:54:29 +0000549 const RetainSummary *& operator[](Selector S) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000550 return M[ ObjCSummaryKey(S) ];
551 }
Mike Stump1eb44332009-09-09 15:08:12 +0000552};
Ted Kremenek553cf182008-06-25 21:21:56 +0000553} // end anonymous namespace
554
555//===----------------------------------------------------------------------===//
556// Data structures for managing collections of summaries.
557//===----------------------------------------------------------------------===//
558
559namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000560class RetainSummaryManager {
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000561
562 //==-----------------------------------------------------------------==//
563 // Typedefs.
564 //==-----------------------------------------------------------------==//
Mike Stump1eb44332009-09-09 15:08:12 +0000565
Ted Kremenek93edbc52011-10-05 23:54:29 +0000566 typedef llvm::DenseMap<const FunctionDecl*, const RetainSummary *>
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000567 FuncSummariesTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000568
Ted Kremenek4f22a782008-06-23 23:30:29 +0000569 typedef ObjCSummaryCache ObjCMethodSummariesTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000570
Jordy Roseef945882012-03-18 01:26:10 +0000571 typedef llvm::FoldingSetNodeWrapper<RetainSummary> CachedSummaryNode;
572
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000573 //==-----------------------------------------------------------------==//
574 // Data.
575 //==-----------------------------------------------------------------==//
Mike Stump1eb44332009-09-09 15:08:12 +0000576
Ted Kremenek553cf182008-06-25 21:21:56 +0000577 /// Ctx - The ASTContext object for the analyzed ASTs.
Ted Kremenek9c378f72011-08-12 23:37:29 +0000578 ASTContext &Ctx;
Ted Kremenek179064e2008-07-01 17:21:27 +0000579
Ted Kremenek553cf182008-06-25 21:21:56 +0000580 /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
Ted Kremenek377e2302008-04-29 05:33:51 +0000581 const bool GCEnabled;
Mike Stump1eb44332009-09-09 15:08:12 +0000582
John McCallf85e1932011-06-15 23:02:42 +0000583 /// Records whether or not the analyzed code runs in ARC mode.
584 const bool ARCEnabled;
585
Ted Kremenek553cf182008-06-25 21:21:56 +0000586 /// FuncSummaries - A map from FunctionDecls to summaries.
Mike Stump1eb44332009-09-09 15:08:12 +0000587 FuncSummariesTy FuncSummaries;
588
Ted Kremenek553cf182008-06-25 21:21:56 +0000589 /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
590 /// to summaries.
Ted Kremenek1f180c32008-06-23 22:21:20 +0000591 ObjCMethodSummariesTy ObjCClassMethodSummaries;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000592
Ted Kremenek553cf182008-06-25 21:21:56 +0000593 /// ObjCMethodSummaries - A map from selectors to summaries.
Ted Kremenek1f180c32008-06-23 22:21:20 +0000594 ObjCMethodSummariesTy ObjCMethodSummaries;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000595
Ted Kremenek553cf182008-06-25 21:21:56 +0000596 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
597 /// and all other data used by the checker.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000598 llvm::BumpPtrAllocator BPAlloc;
Mike Stump1eb44332009-09-09 15:08:12 +0000599
Ted Kremenekb77449c2009-05-03 05:20:50 +0000600 /// AF - A factory for ArgEffects objects.
Mike Stump1eb44332009-09-09 15:08:12 +0000601 ArgEffects::Factory AF;
602
Ted Kremenek553cf182008-06-25 21:21:56 +0000603 /// ScratchArgs - A holding buffer for construct ArgEffects.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000604 ArgEffects ScratchArgs;
Mike Stump1eb44332009-09-09 15:08:12 +0000605
Ted Kremenekec315332009-05-07 23:40:42 +0000606 /// ObjCAllocRetE - Default return effect for methods returning Objective-C
607 /// objects.
608 RetEffect ObjCAllocRetE;
Ted Kremenek547d4952009-06-05 23:18:01 +0000609
Mike Stump1eb44332009-09-09 15:08:12 +0000610 /// ObjCInitRetE - Default return effect for init methods returning
Ted Kremenekac02f202009-08-20 05:13:36 +0000611 /// Objective-C objects.
Ted Kremenek547d4952009-06-05 23:18:01 +0000612 RetEffect ObjCInitRetE;
Mike Stump1eb44332009-09-09 15:08:12 +0000613
Jordy Roseef945882012-03-18 01:26:10 +0000614 /// SimpleSummaries - Used for uniquing summaries that don't have special
615 /// effects.
616 llvm::FoldingSet<CachedSummaryNode> SimpleSummaries;
Mike Stump1eb44332009-09-09 15:08:12 +0000617
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000618 //==-----------------------------------------------------------------==//
619 // Methods.
620 //==-----------------------------------------------------------------==//
Mike Stump1eb44332009-09-09 15:08:12 +0000621
Ted Kremenek553cf182008-06-25 21:21:56 +0000622 /// getArgEffects - Returns a persistent ArgEffects object based on the
623 /// data in ScratchArgs.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000624 ArgEffects getArgEffects();
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000625
Mike Stump1eb44332009-09-09 15:08:12 +0000626 enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
Ted Kremenek93edbc52011-10-05 23:54:29 +0000627
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000628 const RetainSummary *getUnarySummary(const FunctionType* FT,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000629 UnaryFuncKind func);
Mike Stump1eb44332009-09-09 15:08:12 +0000630
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000631 const RetainSummary *getCFSummaryCreateRule(const FunctionDecl *FD);
632 const RetainSummary *getCFSummaryGetRule(const FunctionDecl *FD);
633 const RetainSummary *getCFCreateGetRuleSummary(const FunctionDecl *FD);
Mike Stump1eb44332009-09-09 15:08:12 +0000634
Jordy Roseef945882012-03-18 01:26:10 +0000635 const RetainSummary *getPersistentSummary(const RetainSummary &OldSumm);
Ted Kremenek706522f2008-10-29 04:07:07 +0000636
Jordy Roseef945882012-03-18 01:26:10 +0000637 const RetainSummary *getPersistentSummary(RetEffect RetEff,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000638 ArgEffect ReceiverEff = DoNothing,
639 ArgEffect DefaultEff = MayEscape) {
Jordy Roseef945882012-03-18 01:26:10 +0000640 RetainSummary Summ(getArgEffects(), RetEff, DefaultEff, ReceiverEff);
641 return getPersistentSummary(Summ);
642 }
643
Ted Kremenekc91fdf62012-05-08 00:12:09 +0000644 const RetainSummary *getDoNothingSummary() {
645 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
646 }
647
Jordy Roseef945882012-03-18 01:26:10 +0000648 const RetainSummary *getDefaultSummary() {
649 return getPersistentSummary(RetEffect::MakeNoRet(),
650 DoNothing, MayEscape);
Ted Kremenek9c32d082008-05-06 00:30:21 +0000651 }
Mike Stump1eb44332009-09-09 15:08:12 +0000652
Ted Kremenek93edbc52011-10-05 23:54:29 +0000653 const RetainSummary *getPersistentStopSummary() {
Jordy Roseef945882012-03-18 01:26:10 +0000654 return getPersistentSummary(RetEffect::MakeNoRet(),
655 StopTracking, StopTracking);
Mike Stump1eb44332009-09-09 15:08:12 +0000656 }
Ted Kremenekb3095252008-05-06 04:20:12 +0000657
Ted Kremenek1f180c32008-06-23 22:21:20 +0000658 void InitializeClassMethodSummaries();
659 void InitializeMethodSummaries();
Ted Kremenek896cd9d2008-10-23 01:56:15 +0000660private:
Ted Kremenek93edbc52011-10-05 23:54:29 +0000661 void addNSObjectClsMethSummary(Selector S, const RetainSummary *Summ) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000662 ObjCClassMethodSummaries[S] = Summ;
663 }
Mike Stump1eb44332009-09-09 15:08:12 +0000664
Ted Kremenek93edbc52011-10-05 23:54:29 +0000665 void addNSObjectMethSummary(Selector S, const RetainSummary *Summ) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000666 ObjCMethodSummaries[S] = Summ;
667 }
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +0000668
Ted Kremeneka9797122012-02-18 21:37:48 +0000669 void addClassMethSummary(const char* Cls, const char* name,
670 const RetainSummary *Summ, bool isNullary = true) {
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +0000671 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
Ted Kremeneka9797122012-02-18 21:37:48 +0000672 Selector S = isNullary ? GetNullarySelector(name, Ctx)
673 : GetUnarySelector(name, Ctx);
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +0000674 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
675 }
Mike Stump1eb44332009-09-09 15:08:12 +0000676
Ted Kremenek6c4becb2009-02-25 02:54:57 +0000677 void addInstMethSummary(const char* Cls, const char* nullaryName,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000678 const RetainSummary *Summ) {
Ted Kremenek6c4becb2009-02-25 02:54:57 +0000679 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
680 Selector S = GetNullarySelector(nullaryName, Ctx);
681 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
682 }
Mike Stump1eb44332009-09-09 15:08:12 +0000683
Ted Kremenekde4d5332009-04-24 17:50:11 +0000684 Selector generateSelector(va_list argp) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000685 SmallVector<IdentifierInfo*, 10> II;
Ted Kremenekde4d5332009-04-24 17:50:11 +0000686
Ted Kremenek9e476de2008-08-12 18:30:56 +0000687 while (const char* s = va_arg(argp, const char*))
688 II.push_back(&Ctx.Idents.get(s));
Ted Kremenekde4d5332009-04-24 17:50:11 +0000689
Mike Stump1eb44332009-09-09 15:08:12 +0000690 return Ctx.Selectors.getSelector(II.size(), &II[0]);
Ted Kremenekde4d5332009-04-24 17:50:11 +0000691 }
Mike Stump1eb44332009-09-09 15:08:12 +0000692
Ted Kremenekde4d5332009-04-24 17:50:11 +0000693 void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy& Summaries,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000694 const RetainSummary * Summ, va_list argp) {
Ted Kremenekde4d5332009-04-24 17:50:11 +0000695 Selector S = generateSelector(argp);
696 Summaries[ObjCSummaryKey(ClsII, S)] = Summ;
Ted Kremenek70a733e2008-07-18 17:24:20 +0000697 }
Mike Stump1eb44332009-09-09 15:08:12 +0000698
Ted Kremenek93edbc52011-10-05 23:54:29 +0000699 void addInstMethSummary(const char* Cls, const RetainSummary * Summ, ...) {
Ted Kremenekaf9dc272008-08-12 18:48:50 +0000700 va_list argp;
701 va_start(argp, Summ);
Ted Kremenekde4d5332009-04-24 17:50:11 +0000702 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Mike Stump1eb44332009-09-09 15:08:12 +0000703 va_end(argp);
Ted Kremenekaf9dc272008-08-12 18:48:50 +0000704 }
Mike Stump1eb44332009-09-09 15:08:12 +0000705
Ted Kremenek93edbc52011-10-05 23:54:29 +0000706 void addClsMethSummary(const char* Cls, const RetainSummary * Summ, ...) {
Ted Kremenekde4d5332009-04-24 17:50:11 +0000707 va_list argp;
708 va_start(argp, Summ);
709 addMethodSummary(&Ctx.Idents.get(Cls),ObjCClassMethodSummaries, Summ, argp);
710 va_end(argp);
711 }
Mike Stump1eb44332009-09-09 15:08:12 +0000712
Ted Kremenek93edbc52011-10-05 23:54:29 +0000713 void addClsMethSummary(IdentifierInfo *II, const RetainSummary * Summ, ...) {
Ted Kremenekde4d5332009-04-24 17:50:11 +0000714 va_list argp;
715 va_start(argp, Summ);
716 addMethodSummary(II, ObjCClassMethodSummaries, Summ, argp);
717 va_end(argp);
718 }
719
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000720public:
Mike Stump1eb44332009-09-09 15:08:12 +0000721
Ted Kremenek9c378f72011-08-12 23:37:29 +0000722 RetainSummaryManager(ASTContext &ctx, bool gcenabled, bool usesARC)
Ted Kremenek179064e2008-07-01 17:21:27 +0000723 : Ctx(ctx),
John McCallf85e1932011-06-15 23:02:42 +0000724 GCEnabled(gcenabled),
725 ARCEnabled(usesARC),
726 AF(BPAlloc), ScratchArgs(AF.getEmptyMap()),
727 ObjCAllocRetE(gcenabled
728 ? RetEffect::MakeGCNotOwned()
729 : (usesARC ? RetEffect::MakeARCNotOwned()
730 : RetEffect::MakeOwned(RetEffect::ObjC, true))),
731 ObjCInitRetE(gcenabled
732 ? RetEffect::MakeGCNotOwned()
733 : (usesARC ? RetEffect::MakeARCNotOwned()
Jordy Roseef945882012-03-18 01:26:10 +0000734 : RetEffect::MakeOwnedWhenTrackedReceiver())) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000735 InitializeClassMethodSummaries();
736 InitializeMethodSummaries();
737 }
Mike Stump1eb44332009-09-09 15:08:12 +0000738
Jordan Rose4531b7d2012-07-02 19:27:43 +0000739 const RetainSummary *getSummary(const CallEvent &Call,
740 ProgramStateRef State = 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000741
Jordan Rose4531b7d2012-07-02 19:27:43 +0000742 const RetainSummary *getFunctionSummary(const FunctionDecl *FD);
743
744 const RetainSummary *getMethodSummary(Selector S, const ObjCInterfaceDecl *ID,
Jordy Rosef3aae582012-03-17 21:13:07 +0000745 const ObjCMethodDecl *MD,
746 QualType RetTy,
747 ObjCMethodSummariesTy &CachedSummaries);
748
Jordan Rosecde8cdb2012-07-02 19:27:56 +0000749 const RetainSummary *getInstanceMethodSummary(const ObjCMethodCall &M,
Jordan Rose4531b7d2012-07-02 19:27:43 +0000750 ProgramStateRef State);
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000751
Jordan Rosecde8cdb2012-07-02 19:27:56 +0000752 const RetainSummary *getClassMethodSummary(const ObjCMethodCall &M) {
Jordan Rose4531b7d2012-07-02 19:27:43 +0000753 assert(!M.isInstanceMessage());
754 const ObjCInterfaceDecl *Class = M.getReceiverInterface();
Mike Stump1eb44332009-09-09 15:08:12 +0000755
Jordan Rose4531b7d2012-07-02 19:27:43 +0000756 return getMethodSummary(M.getSelector(), Class, M.getDecl(),
757 M.getResultType(), ObjCClassMethodSummaries);
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +0000758 }
Ted Kremenek552333c2009-04-29 17:17:48 +0000759
760 /// getMethodSummary - This version of getMethodSummary is used to query
761 /// the summary for the current method being analyzed.
Ted Kremenek93edbc52011-10-05 23:54:29 +0000762 const RetainSummary *getMethodSummary(const ObjCMethodDecl *MD) {
Ted Kremeneka8833552009-04-29 23:03:22 +0000763 const ObjCInterfaceDecl *ID = MD->getClassInterface();
Ted Kremenek70a65762009-04-30 05:41:14 +0000764 Selector S = MD->getSelector();
Ted Kremenek552333c2009-04-29 17:17:48 +0000765 QualType ResultTy = MD->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +0000766
Jordy Rosef3aae582012-03-17 21:13:07 +0000767 ObjCMethodSummariesTy *CachedSummaries;
Ted Kremenek552333c2009-04-29 17:17:48 +0000768 if (MD->isInstanceMethod())
Jordy Rosef3aae582012-03-17 21:13:07 +0000769 CachedSummaries = &ObjCMethodSummaries;
Ted Kremenek552333c2009-04-29 17:17:48 +0000770 else
Jordy Rosef3aae582012-03-17 21:13:07 +0000771 CachedSummaries = &ObjCClassMethodSummaries;
772
Jordan Rose4531b7d2012-07-02 19:27:43 +0000773 return getMethodSummary(S, ID, MD, ResultTy, *CachedSummaries);
Ted Kremenek552333c2009-04-29 17:17:48 +0000774 }
Mike Stump1eb44332009-09-09 15:08:12 +0000775
Jordy Rosef3aae582012-03-17 21:13:07 +0000776 const RetainSummary *getStandardMethodSummary(const ObjCMethodDecl *MD,
Jordan Rose4531b7d2012-07-02 19:27:43 +0000777 Selector S, QualType RetTy);
Ted Kremeneka8833552009-04-29 23:03:22 +0000778
Ted Kremenek93edbc52011-10-05 23:54:29 +0000779 void updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenek4dd8fb42009-05-09 02:58:13 +0000780 const ObjCMethodDecl *MD);
781
Ted Kremenek93edbc52011-10-05 23:54:29 +0000782 void updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenek4dd8fb42009-05-09 02:58:13 +0000783 const FunctionDecl *FD);
784
Jordan Rose4531b7d2012-07-02 19:27:43 +0000785 void updateSummaryForCall(const RetainSummary *&Summ,
786 const CallEvent &Call);
787
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000788 bool isGCEnabled() const { return GCEnabled; }
Mike Stump1eb44332009-09-09 15:08:12 +0000789
John McCallf85e1932011-06-15 23:02:42 +0000790 bool isARCEnabled() const { return ARCEnabled; }
791
792 bool isARCorGCEnabled() const { return GCEnabled || ARCEnabled; }
Jordan Rose4531b7d2012-07-02 19:27:43 +0000793
794 RetEffect getObjAllocRetEffect() const { return ObjCAllocRetE; }
795
796 friend class RetainSummaryTemplate;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000797};
Mike Stump1eb44332009-09-09 15:08:12 +0000798
Jordy Rose0fe62f82011-08-24 09:02:37 +0000799// Used to avoid allocating long-term (BPAlloc'd) memory for default retain
800// summaries. If a function or method looks like it has a default summary, but
801// it has annotations, the annotations are added to the stack-based template
802// and then copied into managed memory.
803class RetainSummaryTemplate {
804 RetainSummaryManager &Manager;
Ted Kremenek93edbc52011-10-05 23:54:29 +0000805 const RetainSummary *&RealSummary;
Jordy Rose0fe62f82011-08-24 09:02:37 +0000806 RetainSummary ScratchSummary;
807 bool Accessed;
808public:
Jordan Rose4531b7d2012-07-02 19:27:43 +0000809 RetainSummaryTemplate(const RetainSummary *&real, RetainSummaryManager &mgr)
810 : Manager(mgr), RealSummary(real), ScratchSummary(*real), Accessed(false) {}
Jordy Rose0fe62f82011-08-24 09:02:37 +0000811
812 ~RetainSummaryTemplate() {
Ted Kremenek93edbc52011-10-05 23:54:29 +0000813 if (Accessed)
Jordy Roseef945882012-03-18 01:26:10 +0000814 RealSummary = Manager.getPersistentSummary(ScratchSummary);
Jordy Rose0fe62f82011-08-24 09:02:37 +0000815 }
816
817 RetainSummary &operator*() {
818 Accessed = true;
Ted Kremenek93edbc52011-10-05 23:54:29 +0000819 return ScratchSummary;
Jordy Rose0fe62f82011-08-24 09:02:37 +0000820 }
821
822 RetainSummary *operator->() {
823 Accessed = true;
Ted Kremenek93edbc52011-10-05 23:54:29 +0000824 return &ScratchSummary;
Jordy Rose0fe62f82011-08-24 09:02:37 +0000825 }
826};
827
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000828} // end anonymous namespace
829
830//===----------------------------------------------------------------------===//
831// Implementation of checker data structures.
832//===----------------------------------------------------------------------===//
833
Ted Kremenekb77449c2009-05-03 05:20:50 +0000834ArgEffects RetainSummaryManager::getArgEffects() {
835 ArgEffects AE = ScratchArgs;
Ted Kremenek3baf6722010-11-24 00:54:37 +0000836 ScratchArgs = AF.getEmptyMap();
Ted Kremenekb77449c2009-05-03 05:20:50 +0000837 return AE;
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000838}
839
Ted Kremenek93edbc52011-10-05 23:54:29 +0000840const RetainSummary *
Jordy Roseef945882012-03-18 01:26:10 +0000841RetainSummaryManager::getPersistentSummary(const RetainSummary &OldSumm) {
842 // Unique "simple" summaries -- those without ArgEffects.
843 if (OldSumm.isSimple()) {
844 llvm::FoldingSetNodeID ID;
845 OldSumm.Profile(ID);
846
847 void *Pos;
848 CachedSummaryNode *N = SimpleSummaries.FindNodeOrInsertPos(ID, Pos);
849
850 if (!N) {
851 N = (CachedSummaryNode *) BPAlloc.Allocate<CachedSummaryNode>();
852 new (N) CachedSummaryNode(OldSumm);
853 SimpleSummaries.InsertNode(N, Pos);
854 }
855
856 return &N->getValue();
857 }
858
Ted Kremenek93edbc52011-10-05 23:54:29 +0000859 RetainSummary *Summ = (RetainSummary *) BPAlloc.Allocate<RetainSummary>();
Jordy Roseef945882012-03-18 01:26:10 +0000860 new (Summ) RetainSummary(OldSumm);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000861 return Summ;
862}
863
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000864//===----------------------------------------------------------------------===//
865// Summary creation for functions (largely uses of Core Foundation).
866//===----------------------------------------------------------------------===//
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000867
Ted Kremenek9c378f72011-08-12 23:37:29 +0000868static bool isRetain(const FunctionDecl *FD, StringRef FName) {
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000869 return FName.endswith("Retain");
Ted Kremenek12619382009-01-12 21:45:02 +0000870}
871
Ted Kremenek9c378f72011-08-12 23:37:29 +0000872static bool isRelease(const FunctionDecl *FD, StringRef FName) {
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000873 return FName.endswith("Release");
Ted Kremenek12619382009-01-12 21:45:02 +0000874}
875
Jordy Rose76c506f2011-08-21 21:58:18 +0000876static bool isMakeCollectable(const FunctionDecl *FD, StringRef FName) {
877 // FIXME: Remove FunctionDecl parameter.
878 // FIXME: Is it really okay if MakeCollectable isn't a suffix?
879 return FName.find("MakeCollectable") != StringRef::npos;
880}
881
Jordan Rose4531b7d2012-07-02 19:27:43 +0000882static ArgEffect getStopTrackingEquivalent(ArgEffect E) {
883 switch (E) {
884 case DoNothing:
885 case Autorelease:
886 case DecRefBridgedTransfered:
887 case IncRef:
888 case IncRefMsg:
889 case MakeCollectable:
890 case MayEscape:
891 case NewAutoreleasePool:
892 case StopTracking:
893 return StopTracking;
894 case DecRef:
895 case DecRefAndStopTracking:
896 return DecRefAndStopTracking;
897 case DecRefMsg:
898 case DecRefMsgAndStopTracking:
899 return DecRefMsgAndStopTracking;
900 case Dealloc:
901 return Dealloc;
902 }
903
904 llvm_unreachable("Unknown ArgEffect kind");
905}
906
907void RetainSummaryManager::updateSummaryForCall(const RetainSummary *&S,
908 const CallEvent &Call) {
909 if (Call.hasNonZeroCallbackArg()) {
910 ArgEffect RecEffect = getStopTrackingEquivalent(S->getReceiverEffect());
911 ArgEffect DefEffect = getStopTrackingEquivalent(S->getDefaultArgEffect());
912
913 ArgEffects CustomArgEffects = S->getArgEffects();
914 for (ArgEffects::iterator I = CustomArgEffects.begin(),
915 E = CustomArgEffects.end();
916 I != E; ++I) {
917 ArgEffect Translated = getStopTrackingEquivalent(I->second);
918 if (Translated != DefEffect)
919 ScratchArgs = AF.add(ScratchArgs, I->first, Translated);
920 }
921
922 RetEffect RE = RetEffect::MakeNoRet();
923
924 // Special cases where the callback argument CANNOT free the return value.
925 // This can generally only happen if we know that the callback will only be
926 // called when the return value is already being deallocated.
927 if (const FunctionCall *FC = dyn_cast<FunctionCall>(&Call)) {
928 IdentifierInfo *Name = FC->getDecl()->getIdentifier();
929
930 // This callback frees the associated buffer.
931 if (Name->isStr("CGBitmapContextCreateWithData"))
932 RE = S->getRetEffect();
933 }
934
935 S = getPersistentSummary(RE, RecEffect, DefEffect);
936 }
937}
938
Anna Zaks58822c42012-05-04 22:18:39 +0000939const RetainSummary *
Jordan Rose4531b7d2012-07-02 19:27:43 +0000940RetainSummaryManager::getSummary(const CallEvent &Call,
941 ProgramStateRef State) {
942 const RetainSummary *Summ;
943 switch (Call.getKind()) {
944 case CE_Function:
945 Summ = getFunctionSummary(cast<FunctionCall>(Call).getDecl());
946 break;
947 case CE_CXXMember:
Jordan Rosefdaa3382012-07-03 22:55:57 +0000948 case CE_CXXMemberOperator:
Jordan Rose4531b7d2012-07-02 19:27:43 +0000949 case CE_Block:
950 case CE_CXXConstructor:
Jordan Rose8d276d32012-07-10 22:07:47 +0000951 case CE_CXXDestructor:
Jordan Rose70cbf3c2012-07-02 22:21:47 +0000952 case CE_CXXAllocator:
Jordan Rose4531b7d2012-07-02 19:27:43 +0000953 // FIXME: These calls are currently unsupported.
954 return getPersistentStopSummary();
Jordan Rosecde8cdb2012-07-02 19:27:56 +0000955 case CE_ObjCMessage:
956 case CE_ObjCPropertyAccess: {
957 const ObjCMethodCall &Msg = cast<ObjCMethodCall>(Call);
Jordan Rose4531b7d2012-07-02 19:27:43 +0000958 if (Msg.isInstanceMessage())
959 Summ = getInstanceMethodSummary(Msg, State);
960 else
961 Summ = getClassMethodSummary(Msg);
962 break;
963 }
964 }
965
966 updateSummaryForCall(Summ, Call);
967
968 assert(Summ && "Unknown call type?");
969 return Summ;
970}
971
972const RetainSummary *
973RetainSummaryManager::getFunctionSummary(const FunctionDecl *FD) {
974 // If we don't know what function we're calling, use our default summary.
975 if (!FD)
976 return getDefaultSummary();
977
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000978 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000979 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000980 if (I != FuncSummaries.end())
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000981 return I->second;
982
Ted Kremeneke401a0c2009-05-04 15:34:07 +0000983 // No summary? Generate one.
Ted Kremenek93edbc52011-10-05 23:54:29 +0000984 const RetainSummary *S = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000985
Ted Kremenek37d785b2008-07-15 16:50:12 +0000986 do {
Ted Kremenek12619382009-01-12 21:45:02 +0000987 // We generate "stop" summaries for implicitly defined functions.
988 if (FD->isImplicit()) {
989 S = getPersistentStopSummary();
990 break;
Ted Kremenek37d785b2008-07-15 16:50:12 +0000991 }
Mike Stump1eb44332009-09-09 15:08:12 +0000992
John McCall183700f2009-09-21 23:43:11 +0000993 // [PR 3337] Use 'getAs<FunctionType>' to strip away any typedefs on the
Ted Kremenek99890652009-01-16 18:40:33 +0000994 // function's type.
John McCall183700f2009-09-21 23:43:11 +0000995 const FunctionType* FT = FD->getType()->getAs<FunctionType>();
Ted Kremenek48c6d182009-12-16 06:06:43 +0000996 const IdentifierInfo *II = FD->getIdentifier();
997 if (!II)
998 break;
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000999
1000 StringRef FName = II->getName();
Mike Stump1eb44332009-09-09 15:08:12 +00001001
Ted Kremenekbf0a4dd2009-03-05 22:11:14 +00001002 // Strip away preceding '_'. Doing this here will effect all the checks
1003 // down below.
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001004 FName = FName.substr(FName.find_first_not_of('_'));
Mike Stump1eb44332009-09-09 15:08:12 +00001005
Ted Kremenek12619382009-01-12 21:45:02 +00001006 // Inspect the result type.
1007 QualType RetTy = FT->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00001008
Ted Kremenek12619382009-01-12 21:45:02 +00001009 // FIXME: This should all be refactored into a chain of "summary lookup"
1010 // filters.
Ted Kremenek008636a2009-10-14 00:27:24 +00001011 assert(ScratchArgs.isEmpty());
Ted Kremenek39d88b02009-06-15 20:36:07 +00001012
Ted Kremenekbefc6d22012-04-26 04:32:23 +00001013 if (FName == "pthread_create" || FName == "pthread_setspecific") {
1014 // Part of: <rdar://problem/7299394> and <rdar://problem/11282706>.
1015 // This will be addressed better with IPA.
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001016 S = getPersistentStopSummary();
1017 } else if (FName == "NSMakeCollectable") {
1018 // Handle: id NSMakeCollectable(CFTypeRef)
1019 S = (RetTy->isObjCIdType())
1020 ? getUnarySummary(FT, cfmakecollectable)
1021 : getPersistentStopSummary();
1022 } else if (FName == "IOBSDNameMatching" ||
1023 FName == "IOServiceMatching" ||
1024 FName == "IOServiceNameMatching" ||
Ted Kremenek537dd3a2012-05-01 05:28:27 +00001025 FName == "IORegistryEntrySearchCFProperty" ||
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001026 FName == "IORegistryEntryIDMatching" ||
1027 FName == "IOOpenFirmwarePathMatching") {
1028 // Part of <rdar://problem/6961230>. (IOKit)
1029 // This should be addressed using a API table.
1030 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1031 DoNothing, DoNothing);
1032 } else if (FName == "IOServiceGetMatchingService" ||
1033 FName == "IOServiceGetMatchingServices") {
1034 // FIXES: <rdar://problem/6326900>
1035 // This should be addressed using a API table. This strcmp is also
1036 // a little gross, but there is no need to super optimize here.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001037 ScratchArgs = AF.add(ScratchArgs, 1, DecRef);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001038 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1039 } else if (FName == "IOServiceAddNotification" ||
1040 FName == "IOServiceAddMatchingNotification") {
1041 // Part of <rdar://problem/6961230>. (IOKit)
1042 // This should be addressed using a API table.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001043 ScratchArgs = AF.add(ScratchArgs, 2, DecRef);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001044 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1045 } else if (FName == "CVPixelBufferCreateWithBytes") {
1046 // FIXES: <rdar://problem/7283567>
1047 // Eventually this can be improved by recognizing that the pixel
1048 // buffer passed to CVPixelBufferCreateWithBytes is released via
1049 // a callback and doing full IPA to make sure this is done correctly.
1050 // FIXME: This function has an out parameter that returns an
1051 // allocated object.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001052 ScratchArgs = AF.add(ScratchArgs, 7, StopTracking);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001053 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1054 } else if (FName == "CGBitmapContextCreateWithData") {
1055 // FIXES: <rdar://problem/7358899>
1056 // Eventually this can be improved by recognizing that 'releaseInfo'
1057 // passed to CGBitmapContextCreateWithData is released via
1058 // a callback and doing full IPA to make sure this is done correctly.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001059 ScratchArgs = AF.add(ScratchArgs, 8, StopTracking);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001060 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1061 DoNothing, DoNothing);
1062 } else if (FName == "CVPixelBufferCreateWithPlanarBytes") {
1063 // FIXES: <rdar://problem/7283567>
1064 // Eventually this can be improved by recognizing that the pixel
1065 // buffer passed to CVPixelBufferCreateWithPlanarBytes is released
1066 // via a callback and doing full IPA to make sure this is done
1067 // correctly.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001068 ScratchArgs = AF.add(ScratchArgs, 12, StopTracking);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001069 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenek06911d42012-03-22 06:29:41 +00001070 } else if (FName == "dispatch_set_context") {
1071 // <rdar://problem/11059275> - The analyzer currently doesn't have
1072 // a good way to reason about the finalizer function for libdispatch.
1073 // If we pass a context object that is memory managed, stop tracking it.
1074 // FIXME: this hack should possibly go away once we can handle
1075 // libdispatch finalizers.
1076 ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
1077 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenekc91fdf62012-05-08 00:12:09 +00001078 } else if (FName.startswith("NSLog")) {
1079 S = getDoNothingSummary();
Anna Zaks62a5c342012-03-30 05:48:16 +00001080 } else if (FName.startswith("NS") &&
1081 (FName.find("Insert") != StringRef::npos)) {
1082 // Whitelist NSXXInsertXX, for example NSMapInsertIfAbsent, since they can
1083 // be deallocated by NSMapRemove. (radar://11152419)
1084 ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
1085 ScratchArgs = AF.add(ScratchArgs, 2, StopTracking);
1086 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenekb04cb592009-06-11 18:17:24 +00001087 }
Mike Stump1eb44332009-09-09 15:08:12 +00001088
Ted Kremenekb04cb592009-06-11 18:17:24 +00001089 // Did we get a summary?
1090 if (S)
1091 break;
Ted Kremenek61991902009-03-17 22:43:44 +00001092
1093 // Enable this code once the semantics of NSDeallocateObject are resolved
1094 // for GC. <rdar://problem/6619988>
1095#if 0
1096 // Handle: NSDeallocateObject(id anObject);
1097 // This method does allow 'nil' (although we don't check it now).
Mike Stump1eb44332009-09-09 15:08:12 +00001098 if (strcmp(FName, "NSDeallocateObject") == 0) {
Ted Kremenek61991902009-03-17 22:43:44 +00001099 return RetTy == Ctx.VoidTy
1100 ? getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, Dealloc)
1101 : getPersistentStopSummary();
1102 }
1103#endif
Ted Kremenek12619382009-01-12 21:45:02 +00001104
1105 if (RetTy->isPointerType()) {
1106 // For CoreFoundation ('CF') types.
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001107 if (cocoa::isRefType(RetTy, "CF", FName)) {
Ted Kremenek12619382009-01-12 21:45:02 +00001108 if (isRetain(FD, FName))
1109 S = getUnarySummary(FT, cfretain);
Jordy Rose76c506f2011-08-21 21:58:18 +00001110 else if (isMakeCollectable(FD, FName))
Ted Kremenek12619382009-01-12 21:45:02 +00001111 S = getUnarySummary(FT, cfmakecollectable);
Mike Stump1eb44332009-09-09 15:08:12 +00001112 else
John McCall7df2ff42011-10-01 00:48:56 +00001113 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek12619382009-01-12 21:45:02 +00001114
1115 break;
1116 }
1117
1118 // For CoreGraphics ('CG') types.
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001119 if (cocoa::isRefType(RetTy, "CG", FName)) {
Ted Kremenek12619382009-01-12 21:45:02 +00001120 if (isRetain(FD, FName))
1121 S = getUnarySummary(FT, cfretain);
1122 else
John McCall7df2ff42011-10-01 00:48:56 +00001123 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek12619382009-01-12 21:45:02 +00001124
1125 break;
1126 }
1127
1128 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001129 if (cocoa::isRefType(RetTy, "DADisk") ||
1130 cocoa::isRefType(RetTy, "DADissenter") ||
1131 cocoa::isRefType(RetTy, "DASessionRef")) {
John McCall7df2ff42011-10-01 00:48:56 +00001132 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek12619382009-01-12 21:45:02 +00001133 break;
1134 }
Mike Stump1eb44332009-09-09 15:08:12 +00001135
Ted Kremenek12619382009-01-12 21:45:02 +00001136 break;
1137 }
1138
1139 // Check for release functions, the only kind of functions that we care
1140 // about that don't return a pointer type.
1141 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
Ted Kremeneke7d03122010-02-08 16:45:01 +00001142 // Test for 'CGCF'.
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001143 FName = FName.substr(FName.startswith("CGCF") ? 4 : 2);
Ted Kremeneke7d03122010-02-08 16:45:01 +00001144
Ted Kremenekbf0a4dd2009-03-05 22:11:14 +00001145 if (isRelease(FD, FName))
Ted Kremenek12619382009-01-12 21:45:02 +00001146 S = getUnarySummary(FT, cfrelease);
1147 else {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001148 assert (ScratchArgs.isEmpty());
Ted Kremenek68189282009-01-29 22:45:13 +00001149 // Remaining CoreFoundation and CoreGraphics functions.
1150 // We use to assume that they all strictly followed the ownership idiom
1151 // and that ownership cannot be transferred. While this is technically
1152 // correct, many methods allow a tracked object to escape. For example:
1153 //
Mike Stump1eb44332009-09-09 15:08:12 +00001154 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
Ted Kremenek68189282009-01-29 22:45:13 +00001155 // CFDictionaryAddValue(y, key, x);
Mike Stump1eb44332009-09-09 15:08:12 +00001156 // CFRelease(x);
Ted Kremenek68189282009-01-29 22:45:13 +00001157 // ... it is okay to use 'x' since 'y' has a reference to it
1158 //
1159 // We handle this and similar cases with the follow heuristic. If the
Ted Kremenekc4843812009-08-20 00:57:22 +00001160 // function name contains "InsertValue", "SetValue", "AddValue",
1161 // "AppendValue", or "SetAttribute", then we assume that arguments may
1162 // "escape." This means that something else holds on to the object,
1163 // allowing it be used even after its local retain count drops to 0.
Benjamin Kramere45c1492010-01-11 19:46:28 +00001164 ArgEffect E = (StrInStrNoCase(FName, "InsertValue") != StringRef::npos||
1165 StrInStrNoCase(FName, "AddValue") != StringRef::npos ||
1166 StrInStrNoCase(FName, "SetValue") != StringRef::npos ||
1167 StrInStrNoCase(FName, "AppendValue") != StringRef::npos||
Benjamin Kramerc027e542010-01-11 20:15:06 +00001168 StrInStrNoCase(FName, "SetAttribute") != StringRef::npos)
Ted Kremenek68189282009-01-29 22:45:13 +00001169 ? MayEscape : DoNothing;
Mike Stump1eb44332009-09-09 15:08:12 +00001170
Ted Kremenek68189282009-01-29 22:45:13 +00001171 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek12619382009-01-12 21:45:02 +00001172 }
1173 }
Ted Kremenek37d785b2008-07-15 16:50:12 +00001174 }
1175 while (0);
Mike Stump1eb44332009-09-09 15:08:12 +00001176
Jordan Rose4531b7d2012-07-02 19:27:43 +00001177 // If we got all the way here without any luck, use a default summary.
1178 if (!S)
1179 S = getDefaultSummary();
1180
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001181 // Annotations override defaults.
Jordy Rose4df54fe2011-08-23 04:27:15 +00001182 updateSummaryFromAnnotations(S, FD);
Mike Stump1eb44332009-09-09 15:08:12 +00001183
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001184 FuncSummaries[FD] = S;
Mike Stump1eb44332009-09-09 15:08:12 +00001185 return S;
Ted Kremenek2fff37e2008-03-06 00:08:09 +00001186}
1187
Ted Kremenek93edbc52011-10-05 23:54:29 +00001188const RetainSummary *
John McCall7df2ff42011-10-01 00:48:56 +00001189RetainSummaryManager::getCFCreateGetRuleSummary(const FunctionDecl *FD) {
1190 if (coreFoundation::followsCreateRule(FD))
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001191 return getCFSummaryCreateRule(FD);
Mike Stump1eb44332009-09-09 15:08:12 +00001192
Ted Kremenekd368d712011-05-25 06:19:45 +00001193 return getCFSummaryGetRule(FD);
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001194}
1195
Ted Kremenek93edbc52011-10-05 23:54:29 +00001196const RetainSummary *
Ted Kremenek6ad315a2009-02-23 16:51:39 +00001197RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1198 UnaryFuncKind func) {
1199
Ted Kremenek12619382009-01-12 21:45:02 +00001200 // Sanity check that this is *really* a unary function. This can
1201 // happen if people do weird things.
Douglas Gregor72564e72009-02-26 23:50:07 +00001202 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
Ted Kremenek12619382009-01-12 21:45:02 +00001203 if (!FTP || FTP->getNumArgs() != 1)
1204 return getPersistentStopSummary();
Mike Stump1eb44332009-09-09 15:08:12 +00001205
Ted Kremenekb77449c2009-05-03 05:20:50 +00001206 assert (ScratchArgs.isEmpty());
Mike Stump1eb44332009-09-09 15:08:12 +00001207
Jordy Rose76c506f2011-08-21 21:58:18 +00001208 ArgEffect Effect;
Ted Kremenek377e2302008-04-29 05:33:51 +00001209 switch (func) {
Jordy Rose76c506f2011-08-21 21:58:18 +00001210 case cfretain: Effect = IncRef; break;
1211 case cfrelease: Effect = DecRef; break;
1212 case cfmakecollectable: Effect = MakeCollectable; break;
Ted Kremenek940b1d82008-04-10 23:44:06 +00001213 }
Jordy Rose76c506f2011-08-21 21:58:18 +00001214
1215 ScratchArgs = AF.add(ScratchArgs, 0, Effect);
1216 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001217}
1218
Ted Kremenek93edbc52011-10-05 23:54:29 +00001219const RetainSummary *
Ted Kremenek9c378f72011-08-12 23:37:29 +00001220RetainSummaryManager::getCFSummaryCreateRule(const FunctionDecl *FD) {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001221 assert (ScratchArgs.isEmpty());
Mike Stump1eb44332009-09-09 15:08:12 +00001222
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001223 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001224}
1225
Ted Kremenek93edbc52011-10-05 23:54:29 +00001226const RetainSummary *
Ted Kremenek9c378f72011-08-12 23:37:29 +00001227RetainSummaryManager::getCFSummaryGetRule(const FunctionDecl *FD) {
Mike Stump1eb44332009-09-09 15:08:12 +00001228 assert (ScratchArgs.isEmpty());
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001229 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1230 DoNothing, DoNothing);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001231}
1232
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001233//===----------------------------------------------------------------------===//
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001234// Summary creation for Selectors.
1235//===----------------------------------------------------------------------===//
1236
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001237void
Ted Kremenek93edbc52011-10-05 23:54:29 +00001238RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001239 const FunctionDecl *FD) {
1240 if (!FD)
1241 return;
1242
Jordan Rose4531b7d2012-07-02 19:27:43 +00001243 assert(Summ && "Must have a summary to add annotations to.");
1244 RetainSummaryTemplate Template(Summ, *this);
Jordy Rose4df54fe2011-08-23 04:27:15 +00001245
Ted Kremenek11fe1752011-01-27 18:43:03 +00001246 // Effects on the parameters.
1247 unsigned parm_idx = 0;
1248 for (FunctionDecl::param_const_iterator pi = FD->param_begin(),
John McCall98b8f162011-04-06 09:02:12 +00001249 pe = FD->param_end(); pi != pe; ++pi, ++parm_idx) {
Ted Kremenek11fe1752011-01-27 18:43:03 +00001250 const ParmVarDecl *pd = *pi;
1251 if (pd->getAttr<NSConsumedAttr>()) {
Jordy Rose4df54fe2011-08-23 04:27:15 +00001252 if (!GCEnabled) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001253 Template->addArg(AF, parm_idx, DecRef);
Jordy Rose4df54fe2011-08-23 04:27:15 +00001254 }
1255 } else if (pd->getAttr<CFConsumedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001256 Template->addArg(AF, parm_idx, DecRef);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001257 }
1258 }
1259
Ted Kremenekb04cb592009-06-11 18:17:24 +00001260 QualType RetTy = FD->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00001261
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001262 // Determine if there is a special return effect for this method.
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001263 if (cocoa::isCocoaObjectRef(RetTy)) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001264 if (FD->getAttr<NSReturnsRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001265 Template->setRetEffect(ObjCAllocRetE);
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001266 }
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001267 else if (FD->getAttr<CFReturnsRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001268 Template->setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenekb04cb592009-06-11 18:17:24 +00001269 }
Ted Kremenek60411112010-02-18 00:06:12 +00001270 else if (FD->getAttr<NSReturnsNotRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001271 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::ObjC));
Ted Kremenek60411112010-02-18 00:06:12 +00001272 }
1273 else if (FD->getAttr<CFReturnsNotRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001274 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::CF));
Jordy Rose4df54fe2011-08-23 04:27:15 +00001275 }
1276 } else if (RetTy->getAs<PointerType>()) {
1277 if (FD->getAttr<CFReturnsRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001278 Template->setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
Jordy Rose4df54fe2011-08-23 04:27:15 +00001279 }
1280 else if (FD->getAttr<CFReturnsNotRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001281 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::CF));
Ted Kremenek60411112010-02-18 00:06:12 +00001282 }
Ted Kremenekb04cb592009-06-11 18:17:24 +00001283 }
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001284}
1285
1286void
Ted Kremenek93edbc52011-10-05 23:54:29 +00001287RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
1288 const ObjCMethodDecl *MD) {
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001289 if (!MD)
1290 return;
1291
Jordan Rose4531b7d2012-07-02 19:27:43 +00001292 assert(Summ && "Must have a valid summary to add annotations to");
1293 RetainSummaryTemplate Template(Summ, *this);
Ted Kremenek6d4b76d2009-07-06 18:30:43 +00001294 bool isTrackedLoc = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001295
Ted Kremenek12b94342011-01-27 06:54:14 +00001296 // Effects on the receiver.
1297 if (MD->getAttr<NSConsumesSelfAttr>()) {
Ted Kremenek11fe1752011-01-27 18:43:03 +00001298 if (!GCEnabled)
Jordy Rose0fe62f82011-08-24 09:02:37 +00001299 Template->setReceiverEffect(DecRefMsg);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001300 }
1301
1302 // Effects on the parameters.
1303 unsigned parm_idx = 0;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00001304 for (ObjCMethodDecl::param_const_iterator
1305 pi=MD->param_begin(), pe=MD->param_end();
Ted Kremenek11fe1752011-01-27 18:43:03 +00001306 pi != pe; ++pi, ++parm_idx) {
1307 const ParmVarDecl *pd = *pi;
1308 if (pd->getAttr<NSConsumedAttr>()) {
1309 if (!GCEnabled)
Jordy Rose0fe62f82011-08-24 09:02:37 +00001310 Template->addArg(AF, parm_idx, DecRef);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001311 }
1312 else if(pd->getAttr<CFConsumedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001313 Template->addArg(AF, parm_idx, DecRef);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001314 }
Ted Kremenek12b94342011-01-27 06:54:14 +00001315 }
1316
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001317 // Determine if there is a special return effect for this method.
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001318 if (cocoa::isCocoaObjectRef(MD->getResultType())) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001319 if (MD->getAttr<NSReturnsRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001320 Template->setRetEffect(ObjCAllocRetE);
Ted Kremenek6d4b76d2009-07-06 18:30:43 +00001321 return;
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001322 }
Ted Kremenek60411112010-02-18 00:06:12 +00001323 if (MD->getAttr<NSReturnsNotRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001324 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::ObjC));
Ted Kremenek60411112010-02-18 00:06:12 +00001325 return;
1326 }
Mike Stump1eb44332009-09-09 15:08:12 +00001327
Ted Kremenek6d4b76d2009-07-06 18:30:43 +00001328 isTrackedLoc = true;
Jordy Rose0fe62f82011-08-24 09:02:37 +00001329 } else {
Ted Kremenek6217b802009-07-29 21:53:49 +00001330 isTrackedLoc = MD->getResultType()->getAs<PointerType>() != NULL;
Jordy Rose0fe62f82011-08-24 09:02:37 +00001331 }
Mike Stump1eb44332009-09-09 15:08:12 +00001332
Ted Kremenek60411112010-02-18 00:06:12 +00001333 if (isTrackedLoc) {
1334 if (MD->getAttr<CFReturnsRetainedAttr>())
Jordy Rose0fe62f82011-08-24 09:02:37 +00001335 Template->setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenek60411112010-02-18 00:06:12 +00001336 else if (MD->getAttr<CFReturnsNotRetainedAttr>())
Jordy Rose0fe62f82011-08-24 09:02:37 +00001337 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::CF));
Ted Kremenek60411112010-02-18 00:06:12 +00001338 }
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001339}
1340
Ted Kremenek93edbc52011-10-05 23:54:29 +00001341const RetainSummary *
Jordy Rosef3aae582012-03-17 21:13:07 +00001342RetainSummaryManager::getStandardMethodSummary(const ObjCMethodDecl *MD,
1343 Selector S, QualType RetTy) {
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001344
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +00001345 if (MD) {
Ted Kremenek376d1e72009-04-24 18:00:17 +00001346 // Scan the method decl for 'void*' arguments. These should be treated
1347 // as 'StopTracking' because they are often used with delegates.
1348 // Delegates are a frequent form of false positives with the retain
1349 // count checker.
1350 unsigned i = 0;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00001351 for (ObjCMethodDecl::param_const_iterator I = MD->param_begin(),
Ted Kremenek376d1e72009-04-24 18:00:17 +00001352 E = MD->param_end(); I != E; ++I, ++i)
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00001353 if (const ParmVarDecl *PD = *I) {
Ted Kremenek376d1e72009-04-24 18:00:17 +00001354 QualType Ty = Ctx.getCanonicalType(PD->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001355 if (Ty.getLocalUnqualifiedType() == Ctx.VoidPtrTy)
Ted Kremenek3baf6722010-11-24 00:54:37 +00001356 ScratchArgs = AF.add(ScratchArgs, i, StopTracking);
Ted Kremenek376d1e72009-04-24 18:00:17 +00001357 }
1358 }
Mike Stump1eb44332009-09-09 15:08:12 +00001359
Jordy Rosee921b1a2012-03-17 19:53:04 +00001360 // Any special effects?
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001361 ArgEffect ReceiverEff = DoNothing;
Jordy Rosee921b1a2012-03-17 19:53:04 +00001362 RetEffect ResultEff = RetEffect::MakeNoRet();
1363
1364 // Check the method family, and apply any default annotations.
1365 switch (MD ? MD->getMethodFamily() : S.getMethodFamily()) {
1366 case OMF_None:
1367 case OMF_performSelector:
1368 // Assume all Objective-C methods follow Cocoa Memory Management rules.
1369 // FIXME: Does the non-threaded performSelector family really belong here?
1370 // The selector could be, say, @selector(copy).
1371 if (cocoa::isCocoaObjectRef(RetTy))
1372 ResultEff = RetEffect::MakeNotOwned(RetEffect::ObjC);
1373 else if (coreFoundation::isCFObjectRef(RetTy)) {
1374 // ObjCMethodDecl currently doesn't consider CF objects as valid return
1375 // values for alloc, new, copy, or mutableCopy, so we have to
1376 // double-check with the selector. This is ugly, but there aren't that
1377 // many Objective-C methods that return CF objects, right?
1378 if (MD) {
1379 switch (S.getMethodFamily()) {
1380 case OMF_alloc:
1381 case OMF_new:
1382 case OMF_copy:
1383 case OMF_mutableCopy:
1384 ResultEff = RetEffect::MakeOwned(RetEffect::CF, true);
1385 break;
1386 default:
1387 ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1388 break;
1389 }
1390 } else {
1391 ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1392 }
1393 }
1394 break;
1395 case OMF_init:
1396 ResultEff = ObjCInitRetE;
1397 ReceiverEff = DecRefMsg;
1398 break;
1399 case OMF_alloc:
1400 case OMF_new:
1401 case OMF_copy:
1402 case OMF_mutableCopy:
1403 if (cocoa::isCocoaObjectRef(RetTy))
1404 ResultEff = ObjCAllocRetE;
1405 else if (coreFoundation::isCFObjectRef(RetTy))
1406 ResultEff = RetEffect::MakeOwned(RetEffect::CF, true);
1407 break;
1408 case OMF_autorelease:
1409 ReceiverEff = Autorelease;
1410 break;
1411 case OMF_retain:
1412 ReceiverEff = IncRefMsg;
1413 break;
1414 case OMF_release:
1415 ReceiverEff = DecRefMsg;
1416 break;
1417 case OMF_dealloc:
1418 ReceiverEff = Dealloc;
1419 break;
1420 case OMF_self:
1421 // -self is handled specially by the ExprEngine to propagate the receiver.
1422 break;
1423 case OMF_retainCount:
1424 case OMF_finalize:
1425 // These methods don't return objects.
1426 break;
1427 }
Mike Stump1eb44332009-09-09 15:08:12 +00001428
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001429 // If one of the arguments in the selector has the keyword 'delegate' we
1430 // should stop tracking the reference count for the receiver. This is
1431 // because the reference count is quite possibly handled by a delegate
1432 // method.
1433 if (S.isKeywordSelector()) {
Jordan Rose50571a92012-06-15 18:19:52 +00001434 for (unsigned i = 0, e = S.getNumArgs(); i != e; ++i) {
1435 StringRef Slot = S.getNameForSlot(i);
1436 if (Slot.substr(Slot.size() - 8).equals_lower("delegate")) {
1437 if (ResultEff == ObjCInitRetE)
1438 ResultEff = RetEffect::MakeNoRet();
1439 else
1440 ReceiverEff = StopTracking;
1441 }
1442 }
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001443 }
Mike Stump1eb44332009-09-09 15:08:12 +00001444
Jordy Rosee921b1a2012-03-17 19:53:04 +00001445 if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing &&
1446 ResultEff.getKind() == RetEffect::NoRet)
Ted Kremenek93edbc52011-10-05 23:54:29 +00001447 return getDefaultSummary();
Mike Stump1eb44332009-09-09 15:08:12 +00001448
Jordy Rosee921b1a2012-03-17 19:53:04 +00001449 return getPersistentSummary(ResultEff, ReceiverEff, MayEscape);
Ted Kremenek250b1fa2009-04-23 23:08:22 +00001450}
1451
Ted Kremenek93edbc52011-10-05 23:54:29 +00001452const RetainSummary *
Jordan Rosecde8cdb2012-07-02 19:27:56 +00001453RetainSummaryManager::getInstanceMethodSummary(const ObjCMethodCall &Msg,
Jordan Rose4531b7d2012-07-02 19:27:43 +00001454 ProgramStateRef State) {
1455 const ObjCInterfaceDecl *ReceiverClass = 0;
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001456
Jordan Rose4531b7d2012-07-02 19:27:43 +00001457 // We do better tracking of the type of the object than the core ExprEngine.
1458 // See if we have its type in our private state.
1459 // FIXME: Eventually replace the use of state->get<RefBindings> with
1460 // a generic API for reasoning about the Objective-C types of symbolic
1461 // objects.
1462 SVal ReceiverV = Msg.getReceiverSVal();
1463 if (SymbolRef Sym = ReceiverV.getAsLocSymbol())
1464 if (const RefVal *T = State->get<RefBindings>(Sym))
Douglas Gregor04badcf2010-04-21 00:45:42 +00001465 if (const ObjCObjectPointerType *PT =
Jordan Rose4531b7d2012-07-02 19:27:43 +00001466 T->getType()->getAs<ObjCObjectPointerType>())
1467 ReceiverClass = PT->getInterfaceDecl();
1468
1469 // If we don't know what kind of object this is, fall back to its static type.
1470 if (!ReceiverClass)
1471 ReceiverClass = Msg.getReceiverInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00001472
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001473 // FIXME: The receiver could be a reference to a class, meaning that
1474 // we should use the class method.
Jordan Rose4531b7d2012-07-02 19:27:43 +00001475 // id x = [NSObject class];
1476 // [x performSelector:... withObject:... afterDelay:...];
1477 Selector S = Msg.getSelector();
1478 const ObjCMethodDecl *Method = Msg.getDecl();
1479 if (!Method && ReceiverClass)
1480 Method = ReceiverClass->getInstanceMethod(S);
1481
1482 return getMethodSummary(S, ReceiverClass, Method, Msg.getResultType(),
1483 ObjCMethodSummaries);
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001484}
1485
Ted Kremenek93edbc52011-10-05 23:54:29 +00001486const RetainSummary *
Jordan Rose4531b7d2012-07-02 19:27:43 +00001487RetainSummaryManager::getMethodSummary(Selector S, const ObjCInterfaceDecl *ID,
Jordy Rosef3aae582012-03-17 21:13:07 +00001488 const ObjCMethodDecl *MD, QualType RetTy,
1489 ObjCMethodSummariesTy &CachedSummaries) {
Ted Kremenek1bffd742008-05-06 15:44:25 +00001490
Ted Kremenek8711c032009-04-29 05:04:30 +00001491 // Look up a summary in our summary cache.
Jordan Rose4531b7d2012-07-02 19:27:43 +00001492 const RetainSummary *Summ = CachedSummaries.find(ID, S);
Mike Stump1eb44332009-09-09 15:08:12 +00001493
Ted Kremenek614cc542009-07-21 23:27:57 +00001494 if (!Summ) {
Jordy Rosef3aae582012-03-17 21:13:07 +00001495 Summ = getStandardMethodSummary(MD, S, RetTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001496
Ted Kremenek614cc542009-07-21 23:27:57 +00001497 // Annotations override defaults.
Jordy Rose4df54fe2011-08-23 04:27:15 +00001498 updateSummaryFromAnnotations(Summ, MD);
Mike Stump1eb44332009-09-09 15:08:12 +00001499
Ted Kremenek614cc542009-07-21 23:27:57 +00001500 // Memoize the summary.
Jordan Rose4531b7d2012-07-02 19:27:43 +00001501 CachedSummaries[ObjCSummaryKey(ID, S)] = Summ;
Ted Kremenek614cc542009-07-21 23:27:57 +00001502 }
Mike Stump1eb44332009-09-09 15:08:12 +00001503
Ted Kremeneke87450e2009-04-23 19:11:35 +00001504 return Summ;
Ted Kremenekc8395602008-05-06 21:26:51 +00001505}
1506
Mike Stump1eb44332009-09-09 15:08:12 +00001507void RetainSummaryManager::InitializeClassMethodSummaries() {
Ted Kremenekec315332009-05-07 23:40:42 +00001508 assert(ScratchArgs.isEmpty());
Mike Stump1eb44332009-09-09 15:08:12 +00001509 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek6fe2b7a2009-10-15 22:25:12 +00001510 addClassMethSummary("NSAssertionHandler", "currentHandler",
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001511 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Mike Stump1eb44332009-09-09 15:08:12 +00001512
Ted Kremenek6d348932008-10-21 15:53:15 +00001513 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001514 ScratchArgs = AF.add(ScratchArgs, 0, Autorelease);
Ted Kremenek6fe2b7a2009-10-15 22:25:12 +00001515 addClassMethSummary("NSAutoreleasePool", "addObject",
1516 getPersistentSummary(RetEffect::MakeNoRet(),
1517 DoNothing, Autorelease));
Ted Kremenek9c32d082008-05-06 00:30:21 +00001518}
1519
Ted Kremenek1f180c32008-06-23 22:21:20 +00001520void RetainSummaryManager::InitializeMethodSummaries() {
Mike Stump1eb44332009-09-09 15:08:12 +00001521
1522 assert (ScratchArgs.isEmpty());
1523
Ted Kremenekc8395602008-05-06 21:26:51 +00001524 // Create the "init" selector. It just acts as a pass-through for the
1525 // receiver.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001526 const RetainSummary *InitSumm = getPersistentSummary(ObjCInitRetE, DecRefMsg);
Ted Kremenekac02f202009-08-20 05:13:36 +00001527 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
1528
1529 // awakeAfterUsingCoder: behaves basically like an 'init' method. It
1530 // claims the receiver and returns a retained object.
1531 addNSObjectMethSummary(GetUnarySelector("awakeAfterUsingCoder", Ctx),
1532 InitSumm);
Mike Stump1eb44332009-09-09 15:08:12 +00001533
Ted Kremenekc8395602008-05-06 21:26:51 +00001534 // The next methods are allocators.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001535 const RetainSummary *AllocSumm = getPersistentSummary(ObjCAllocRetE);
1536 const RetainSummary *CFAllocSumm =
Ted Kremeneka834fb42009-08-28 19:52:12 +00001537 getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Mike Stump1eb44332009-09-09 15:08:12 +00001538
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001539 // Create the "retain" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001540 RetEffect NoRet = RetEffect::MakeNoRet();
Ted Kremenek93edbc52011-10-05 23:54:29 +00001541 const RetainSummary *Summ = getPersistentSummary(NoRet, IncRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001542 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001543
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001544 // Create the "release" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001545 Summ = getPersistentSummary(NoRet, DecRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001546 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001547
Ted Kremenek299e8152008-05-07 21:17:39 +00001548 // Create the "drain" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001549 Summ = getPersistentSummary(NoRet, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek553cf182008-06-25 21:21:56 +00001550 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001551
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001552 // Create the -dealloc summary.
Jordy Rose500abad2011-08-21 19:41:36 +00001553 Summ = getPersistentSummary(NoRet, Dealloc);
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001554 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001555
1556 // Create the "autorelease" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001557 Summ = getPersistentSummary(NoRet, Autorelease);
Ted Kremenek553cf182008-06-25 21:21:56 +00001558 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001559
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00001560 // Specially handle NSAutoreleasePool.
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001561 addInstMethSummary("NSAutoreleasePool", "init",
Jordy Rose500abad2011-08-21 19:41:36 +00001562 getPersistentSummary(NoRet, NewAutoreleasePool));
Mike Stump1eb44332009-09-09 15:08:12 +00001563
1564 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremenek89e202d2009-02-23 02:51:29 +00001565 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1566 // self-own themselves. However, they only do this once they are displayed.
1567 // Thus, we need to track an NSWindow's display status.
1568 // This is tracked in <rdar://problem/6062711>.
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +00001569 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001570 const RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenek78a35a32009-05-12 20:06:54 +00001571 StopTracking,
1572 StopTracking);
Mike Stump1eb44332009-09-09 15:08:12 +00001573
Ted Kremenek99d02692009-04-03 19:02:51 +00001574 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1575
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +00001576#if 0
Ted Kremenek78a35a32009-05-12 20:06:54 +00001577 addInstMethSummary("NSWindow", NoTrackYet, "initWithContentRect",
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001578 "styleMask", "backing", "defer", NULL);
Mike Stump1eb44332009-09-09 15:08:12 +00001579
Ted Kremenek78a35a32009-05-12 20:06:54 +00001580 addInstMethSummary("NSWindow", NoTrackYet, "initWithContentRect",
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001581 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +00001582#endif
Mike Stump1eb44332009-09-09 15:08:12 +00001583
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001584 // For NSPanel (which subclasses NSWindow), allocated objects are not
1585 // self-owned.
Ted Kremenek99d02692009-04-03 19:02:51 +00001586 // FIXME: For now we don't track NSPanels. object for the same reason
1587 // as for NSWindow objects.
1588 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
Mike Stump1eb44332009-09-09 15:08:12 +00001589
Ted Kremenek78a35a32009-05-12 20:06:54 +00001590#if 0
1591 addInstMethSummary("NSPanel", NoTrackYet, "initWithContentRect",
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001592 "styleMask", "backing", "defer", NULL);
Mike Stump1eb44332009-09-09 15:08:12 +00001593
Ted Kremenek78a35a32009-05-12 20:06:54 +00001594 addInstMethSummary("NSPanel", NoTrackYet, "initWithContentRect",
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001595 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek78a35a32009-05-12 20:06:54 +00001596#endif
Mike Stump1eb44332009-09-09 15:08:12 +00001597
Ted Kremenekba67f6a2009-05-18 23:14:34 +00001598 // Don't track allocated autorelease pools yet, as it is okay to prematurely
1599 // exit a method.
1600 addClassMethSummary("NSAutoreleasePool", "alloc", NoTrackYet);
Ted Kremeneka9797122012-02-18 21:37:48 +00001601 addClassMethSummary("NSAutoreleasePool", "allocWithZone", NoTrackYet, false);
Ted Kremenek553cf182008-06-25 21:21:56 +00001602
Ted Kremenek767d6492009-05-20 22:39:57 +00001603 // Create summaries QCRenderer/QCView -createSnapShotImageOfType:
1604 addInstMethSummary("QCRenderer", AllocSumm,
1605 "createSnapshotImageOfType", NULL);
1606 addInstMethSummary("QCView", AllocSumm,
1607 "createSnapshotImageOfType", NULL);
1608
Ted Kremenek211a9c62009-06-15 20:58:58 +00001609 // Create summaries for CIContext, 'createCGImage' and
Ted Kremeneka834fb42009-08-28 19:52:12 +00001610 // 'createCGLayerWithSize'. These objects are CF objects, and are not
1611 // automatically garbage collected.
1612 addInstMethSummary("CIContext", CFAllocSumm,
Ted Kremenek767d6492009-05-20 22:39:57 +00001613 "createCGImage", "fromRect", NULL);
Ted Kremeneka834fb42009-08-28 19:52:12 +00001614 addInstMethSummary("CIContext", CFAllocSumm,
Mike Stump1eb44332009-09-09 15:08:12 +00001615 "createCGImage", "fromRect", "format", "colorSpace", NULL);
Ted Kremeneka834fb42009-08-28 19:52:12 +00001616 addInstMethSummary("CIContext", CFAllocSumm, "createCGLayerWithSize",
Ted Kremenek211a9c62009-06-15 20:58:58 +00001617 "info", NULL);
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001618}
1619
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001620//===----------------------------------------------------------------------===//
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001621// AutoreleaseBindings - State used to track objects in autorelease pools.
Ted Kremenek6d348932008-10-21 15:53:15 +00001622//===----------------------------------------------------------------------===//
1623
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001624typedef llvm::ImmutableMap<SymbolRef, unsigned> ARCounts;
1625typedef llvm::ImmutableMap<SymbolRef, ARCounts> ARPoolContents;
1626typedef llvm::ImmutableList<SymbolRef> ARStack;
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00001627
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001628static int AutoRCIndex = 0;
Ted Kremenek6d348932008-10-21 15:53:15 +00001629static int AutoRBIndex = 0;
1630
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001631namespace { class AutoreleasePoolContents {}; }
1632namespace { class AutoreleaseStack {}; }
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001633
Ted Kremenek6d348932008-10-21 15:53:15 +00001634namespace clang {
Ted Kremenek9ef65372010-12-23 07:20:52 +00001635namespace ento {
Ted Kremenek18c66fd2011-08-15 22:09:50 +00001636template<> struct ProgramStateTrait<AutoreleaseStack>
1637 : public ProgramStatePartialTrait<ARStack> {
Ted Kremenek9c378f72011-08-12 23:37:29 +00001638 static inline void *GDMIndex() { return &AutoRBIndex; }
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001639};
1640
Ted Kremenek18c66fd2011-08-15 22:09:50 +00001641template<> struct ProgramStateTrait<AutoreleasePoolContents>
1642 : public ProgramStatePartialTrait<ARPoolContents> {
Ted Kremenek9c378f72011-08-12 23:37:29 +00001643 static inline void *GDMIndex() { return &AutoRCIndex; }
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001644};
Argyrios Kyrtzidis5a4f98f2010-12-22 18:53:20 +00001645} // end GR namespace
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001646} // end clang namespace
Ted Kremenek6d348932008-10-21 15:53:15 +00001647
Ted Kremenek8bef8232012-01-26 21:29:00 +00001648static SymbolRef GetCurrentAutoreleasePool(ProgramStateRef state) {
Ted Kremenek7037ab82009-03-20 17:34:15 +00001649 ARStack stack = state->get<AutoreleaseStack>();
1650 return stack.isEmpty() ? SymbolRef() : stack.getHead();
1651}
1652
Ted Kremenek8bef8232012-01-26 21:29:00 +00001653static ProgramStateRef
1654SendAutorelease(ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +00001655 ARCounts::Factory &F,
1656 SymbolRef sym) {
Ted Kremenek7037ab82009-03-20 17:34:15 +00001657 SymbolRef pool = GetCurrentAutoreleasePool(state);
Ted Kremenekb65be702009-06-18 01:23:53 +00001658 const ARCounts *cnts = state->get<AutoreleasePoolContents>(pool);
Ted Kremenek7037ab82009-03-20 17:34:15 +00001659 ARCounts newCnts(0);
Mike Stump1eb44332009-09-09 15:08:12 +00001660
Ted Kremenek7037ab82009-03-20 17:34:15 +00001661 if (cnts) {
1662 const unsigned *cnt = (*cnts).lookup(sym);
Ted Kremenek3baf6722010-11-24 00:54:37 +00001663 newCnts = F.add(*cnts, sym, cnt ? *cnt + 1 : 1);
Ted Kremenek7037ab82009-03-20 17:34:15 +00001664 }
1665 else
Ted Kremenek3baf6722010-11-24 00:54:37 +00001666 newCnts = F.add(F.getEmptyMap(), sym, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001667
Ted Kremenekb65be702009-06-18 01:23:53 +00001668 return state->set<AutoreleasePoolContents>(pool, newCnts);
Ted Kremenek7037ab82009-03-20 17:34:15 +00001669}
1670
Ted Kremenek13922612008-04-16 20:40:59 +00001671//===----------------------------------------------------------------------===//
Ted Kremenekc887d132009-04-29 18:50:19 +00001672// Error reporting.
1673//===----------------------------------------------------------------------===//
Ted Kremenekc887d132009-04-29 18:50:19 +00001674namespace {
Jordy Roseec9ef852011-08-23 20:55:48 +00001675 typedef llvm::DenseMap<const ExplodedNode *, const RetainSummary *>
1676 SummaryLogTy;
1677
Ted Kremenekc887d132009-04-29 18:50:19 +00001678 //===-------------===//
1679 // Bug Descriptions. //
Mike Stump1eb44332009-09-09 15:08:12 +00001680 //===-------------===//
1681
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001682 class CFRefBug : public BugType {
Ted Kremenekc887d132009-04-29 18:50:19 +00001683 protected:
Jordy Rose35c86952011-08-24 05:47:39 +00001684 CFRefBug(StringRef name)
Ted Kremenek6fd45052012-04-05 20:43:28 +00001685 : BugType(name, categories::MemoryCoreFoundationObjectiveC) {}
Ted Kremenekc887d132009-04-29 18:50:19 +00001686 public:
Mike Stump1eb44332009-09-09 15:08:12 +00001687
Ted Kremenekc887d132009-04-29 18:50:19 +00001688 // FIXME: Eventually remove.
Jordy Rose35c86952011-08-24 05:47:39 +00001689 virtual const char *getDescription() const = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001690
Ted Kremenekc887d132009-04-29 18:50:19 +00001691 virtual bool isLeak() const { return false; }
1692 };
Mike Stump1eb44332009-09-09 15:08:12 +00001693
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001694 class UseAfterRelease : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001695 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001696 UseAfterRelease() : CFRefBug("Use-after-release") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001697
Jordy Rose35c86952011-08-24 05:47:39 +00001698 const char *getDescription() const {
Ted Kremenekc887d132009-04-29 18:50:19 +00001699 return "Reference-counted object is used after it is released";
Mike Stump1eb44332009-09-09 15:08:12 +00001700 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001701 };
Mike Stump1eb44332009-09-09 15:08:12 +00001702
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001703 class BadRelease : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001704 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001705 BadRelease() : CFRefBug("Bad release") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001706
Jordy Rose35c86952011-08-24 05:47:39 +00001707 const char *getDescription() const {
Ted Kremenekbb206fd2009-10-01 17:31:50 +00001708 return "Incorrect decrement of the reference count of an object that is "
1709 "not owned at this point by the caller";
Ted Kremenekc887d132009-04-29 18:50:19 +00001710 }
1711 };
Mike Stump1eb44332009-09-09 15:08:12 +00001712
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001713 class DeallocGC : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001714 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001715 DeallocGC()
1716 : CFRefBug("-dealloc called while using garbage collection") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001717
Ted Kremenekc887d132009-04-29 18:50:19 +00001718 const char *getDescription() const {
Ted Kremenek369de562009-05-09 00:10:05 +00001719 return "-dealloc called while using garbage collection";
Ted Kremenekc887d132009-04-29 18:50:19 +00001720 }
1721 };
Mike Stump1eb44332009-09-09 15:08:12 +00001722
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001723 class DeallocNotOwned : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001724 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001725 DeallocNotOwned()
1726 : CFRefBug("-dealloc sent to non-exclusively owned object") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001727
Ted Kremenekc887d132009-04-29 18:50:19 +00001728 const char *getDescription() const {
1729 return "-dealloc sent to object that may be referenced elsewhere";
1730 }
Mike Stump1eb44332009-09-09 15:08:12 +00001731 };
1732
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001733 class OverAutorelease : public CFRefBug {
Ted Kremenek369de562009-05-09 00:10:05 +00001734 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001735 OverAutorelease()
1736 : CFRefBug("Object sent -autorelease too many times") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001737
Ted Kremenek369de562009-05-09 00:10:05 +00001738 const char *getDescription() const {
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001739 return "Object sent -autorelease too many times";
Ted Kremenek369de562009-05-09 00:10:05 +00001740 }
1741 };
Mike Stump1eb44332009-09-09 15:08:12 +00001742
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001743 class ReturnedNotOwnedForOwned : public CFRefBug {
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001744 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001745 ReturnedNotOwnedForOwned()
1746 : CFRefBug("Method should return an owned object") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001747
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001748 const char *getDescription() const {
Jordy Rose5b5402b2011-07-15 22:17:54 +00001749 return "Object with a +0 retain count returned to caller where a +1 "
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001750 "(owning) retain count is expected";
1751 }
1752 };
Mike Stump1eb44332009-09-09 15:08:12 +00001753
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001754 class Leak : public CFRefBug {
Benjamin Kramerfacde172012-06-06 17:32:50 +00001755 public:
1756 Leak(StringRef name)
1757 : CFRefBug(name) {
Jordy Rosedb92bb62011-08-25 01:14:38 +00001758 // Leaks should not be reported if they are post-dominated by a sink.
1759 setSuppressOnSink(true);
1760 }
Mike Stump1eb44332009-09-09 15:08:12 +00001761
Jordy Rose35c86952011-08-24 05:47:39 +00001762 const char *getDescription() const { return ""; }
Mike Stump1eb44332009-09-09 15:08:12 +00001763
Ted Kremenekc887d132009-04-29 18:50:19 +00001764 bool isLeak() const { return true; }
1765 };
Mike Stump1eb44332009-09-09 15:08:12 +00001766
Ted Kremenekc887d132009-04-29 18:50:19 +00001767 //===---------===//
1768 // Bug Reports. //
1769 //===---------===//
Mike Stump1eb44332009-09-09 15:08:12 +00001770
Jordy Rose01153492012-03-24 02:45:35 +00001771 class CFRefReportVisitor : public BugReporterVisitorImpl<CFRefReportVisitor> {
Anna Zaks23f395e2011-08-20 01:27:22 +00001772 protected:
Anna Zaksdc757b02011-08-19 23:21:56 +00001773 SymbolRef Sym;
Jordy Roseec9ef852011-08-23 20:55:48 +00001774 const SummaryLogTy &SummaryLog;
Jordy Rose35c86952011-08-24 05:47:39 +00001775 bool GCEnabled;
Anna Zaks23f395e2011-08-20 01:27:22 +00001776
Anna Zaksdc757b02011-08-19 23:21:56 +00001777 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001778 CFRefReportVisitor(SymbolRef sym, bool gcEnabled, const SummaryLogTy &log)
1779 : Sym(sym), SummaryLog(log), GCEnabled(gcEnabled) {}
Anna Zaksdc757b02011-08-19 23:21:56 +00001780
Anna Zaks23f395e2011-08-20 01:27:22 +00001781 virtual void Profile(llvm::FoldingSetNodeID &ID) const {
Anna Zaksdc757b02011-08-19 23:21:56 +00001782 static int x = 0;
1783 ID.AddPointer(&x);
1784 ID.AddPointer(Sym);
1785 }
1786
Anna Zaks23f395e2011-08-20 01:27:22 +00001787 virtual PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
1788 const ExplodedNode *PrevN,
1789 BugReporterContext &BRC,
1790 BugReport &BR);
1791
1792 virtual PathDiagnosticPiece *getEndPath(BugReporterContext &BRC,
1793 const ExplodedNode *N,
1794 BugReport &BR);
1795 };
1796
1797 class CFRefLeakReportVisitor : public CFRefReportVisitor {
1798 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001799 CFRefLeakReportVisitor(SymbolRef sym, bool GCEnabled,
Jordy Roseec9ef852011-08-23 20:55:48 +00001800 const SummaryLogTy &log)
Jordy Rose35c86952011-08-24 05:47:39 +00001801 : CFRefReportVisitor(sym, GCEnabled, log) {}
Anna Zaks23f395e2011-08-20 01:27:22 +00001802
1803 PathDiagnosticPiece *getEndPath(BugReporterContext &BRC,
1804 const ExplodedNode *N,
1805 BugReport &BR);
Jordy Rose01153492012-03-24 02:45:35 +00001806
1807 virtual BugReporterVisitor *clone() const {
1808 // The curiously-recurring template pattern only works for one level of
1809 // subclassing. Rather than make a new template base for
1810 // CFRefReportVisitor, we simply override clone() to do the right thing.
1811 // This could be trouble someday if BugReporterVisitorImpl is ever
1812 // used for something else besides a convenient implementation of clone().
1813 return new CFRefLeakReportVisitor(*this);
1814 }
Anna Zaksdc757b02011-08-19 23:21:56 +00001815 };
1816
Anna Zakse172e8b2011-08-17 23:00:25 +00001817 class CFRefReport : public BugReport {
Jordy Rose20589562011-08-24 22:39:09 +00001818 void addGCModeDescription(const LangOptions &LOpts, bool GCEnabled);
Jordy Rose35c86952011-08-24 05:47:39 +00001819
Ted Kremenekc887d132009-04-29 18:50:19 +00001820 public:
Jordy Rose20589562011-08-24 22:39:09 +00001821 CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1822 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1823 bool registerVisitor = true)
Anna Zaksedf4dae2011-08-22 18:54:07 +00001824 : BugReport(D, D.getDescription(), n) {
Anna Zaks23f395e2011-08-20 01:27:22 +00001825 if (registerVisitor)
Jordy Rose20589562011-08-24 22:39:09 +00001826 addVisitor(new CFRefReportVisitor(sym, GCEnabled, Log));
1827 addGCModeDescription(LOpts, GCEnabled);
Anna Zaksdc757b02011-08-19 23:21:56 +00001828 }
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001829
Jordy Rose20589562011-08-24 22:39:09 +00001830 CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1831 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1832 StringRef endText)
Anna Zaksedf4dae2011-08-22 18:54:07 +00001833 : BugReport(D, D.getDescription(), endText, n) {
Jordy Rose20589562011-08-24 22:39:09 +00001834 addVisitor(new CFRefReportVisitor(sym, GCEnabled, Log));
1835 addGCModeDescription(LOpts, GCEnabled);
Anna Zaksdc757b02011-08-19 23:21:56 +00001836 }
Mike Stump1eb44332009-09-09 15:08:12 +00001837
Anna Zakse172e8b2011-08-17 23:00:25 +00001838 virtual std::pair<ranges_iterator, ranges_iterator> getRanges() {
Anna Zaksedf4dae2011-08-22 18:54:07 +00001839 const CFRefBug& BugTy = static_cast<CFRefBug&>(getBugType());
1840 if (!BugTy.isLeak())
Anna Zakse172e8b2011-08-17 23:00:25 +00001841 return BugReport::getRanges();
Ted Kremenekc887d132009-04-29 18:50:19 +00001842 else
Argyrios Kyrtzidis640ccf02010-12-04 01:12:15 +00001843 return std::make_pair(ranges_iterator(), ranges_iterator());
Ted Kremenekc887d132009-04-29 18:50:19 +00001844 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001845 };
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001846
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001847 class CFRefLeakReport : public CFRefReport {
Ted Kremenekc887d132009-04-29 18:50:19 +00001848 const MemRegion* AllocBinding;
Anna Zaks23f395e2011-08-20 01:27:22 +00001849
Ted Kremenekc887d132009-04-29 18:50:19 +00001850 public:
Jordy Rose20589562011-08-24 22:39:09 +00001851 CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1852 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
Anna Zaks6a93bd52011-10-25 19:57:11 +00001853 CheckerContext &Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001854
Anna Zaks590dd8e2011-09-20 21:38:35 +00001855 PathDiagnosticLocation getLocation(const SourceManager &SM) const {
1856 assert(Location.isValid());
1857 return Location;
1858 }
Mike Stump1eb44332009-09-09 15:08:12 +00001859 };
Ted Kremenekc887d132009-04-29 18:50:19 +00001860} // end anonymous namespace
1861
Jordy Rose20589562011-08-24 22:39:09 +00001862void CFRefReport::addGCModeDescription(const LangOptions &LOpts,
1863 bool GCEnabled) {
Jordy Rosef95b19d2011-08-24 20:38:42 +00001864 const char *GCModeDescription = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001865
Douglas Gregore289d812011-09-13 17:21:33 +00001866 switch (LOpts.getGC()) {
Anna Zaks7f2531c2011-08-22 20:31:28 +00001867 case LangOptions::GCOnly:
Jordy Rose20589562011-08-24 22:39:09 +00001868 assert(GCEnabled);
Jordy Rose35c86952011-08-24 05:47:39 +00001869 GCModeDescription = "Code is compiled to only use garbage collection";
1870 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001871
Anna Zaks7f2531c2011-08-22 20:31:28 +00001872 case LangOptions::NonGC:
Jordy Rose20589562011-08-24 22:39:09 +00001873 assert(!GCEnabled);
Jordy Rose35c86952011-08-24 05:47:39 +00001874 GCModeDescription = "Code is compiled to use reference counts";
1875 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001876
Anna Zaks7f2531c2011-08-22 20:31:28 +00001877 case LangOptions::HybridGC:
Jordy Rose20589562011-08-24 22:39:09 +00001878 if (GCEnabled) {
Jordy Rose35c86952011-08-24 05:47:39 +00001879 GCModeDescription = "Code is compiled to use either garbage collection "
1880 "(GC) or reference counts (non-GC). The bug occurs "
1881 "with GC enabled";
1882 break;
1883 } else {
1884 GCModeDescription = "Code is compiled to use either garbage collection "
1885 "(GC) or reference counts (non-GC). The bug occurs "
1886 "in non-GC mode";
1887 break;
Anna Zaks7f2531c2011-08-22 20:31:28 +00001888 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001889 }
Jordy Rose35c86952011-08-24 05:47:39 +00001890
Jordy Rosef95b19d2011-08-24 20:38:42 +00001891 assert(GCModeDescription && "invalid/unknown GC mode");
Jordy Rose35c86952011-08-24 05:47:39 +00001892 addExtraText(GCModeDescription);
Ted Kremenekc887d132009-04-29 18:50:19 +00001893}
1894
Jordy Rose910c4052011-09-02 06:44:22 +00001895// FIXME: This should be a method on SmallVector.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001896static inline bool contains(const SmallVectorImpl<ArgEffect>& V,
Ted Kremenekc887d132009-04-29 18:50:19 +00001897 ArgEffect X) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001898 for (SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
Ted Kremenekc887d132009-04-29 18:50:19 +00001899 I!=E; ++I)
1900 if (*I == X) return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001901
Ted Kremenekc887d132009-04-29 18:50:19 +00001902 return false;
1903}
1904
Jordy Rose70fdbc32012-05-12 05:10:43 +00001905static bool isNumericLiteralExpression(const Expr *E) {
1906 // FIXME: This set of cases was copied from SemaExprObjC.
1907 return isa<IntegerLiteral>(E) ||
1908 isa<CharacterLiteral>(E) ||
1909 isa<FloatingLiteral>(E) ||
1910 isa<ObjCBoolLiteralExpr>(E) ||
1911 isa<CXXBoolLiteralExpr>(E);
1912}
1913
Ted Kremenek4c42bb72011-11-14 21:59:21 +00001914static bool isPropertyAccess(const Stmt *S, ParentMap &PM) {
1915 unsigned maxDepth = 4;
1916 while (S && maxDepth) {
1917 if (const PseudoObjectExpr *PO = dyn_cast<PseudoObjectExpr>(S)) {
1918 if (!isa<ObjCMessageExpr>(PO->getSyntacticForm()))
1919 return true;
1920 return false;
1921 }
1922 S = PM.getParent(S);
1923 --maxDepth;
1924 }
1925 return false;
1926}
1927
Anna Zaksdc757b02011-08-19 23:21:56 +00001928PathDiagnosticPiece *CFRefReportVisitor::VisitNode(const ExplodedNode *N,
1929 const ExplodedNode *PrevN,
1930 BugReporterContext &BRC,
1931 BugReport &BR) {
Jordan Rose28038f32012-07-10 22:07:42 +00001932 // FIXME: We will eventually need to handle non-statement-based events
1933 // (__attribute__((cleanup))).
Jordy Rosef53e8c72011-08-23 19:43:16 +00001934 if (!isa<StmtPoint>(N->getLocation()))
Ted Kremenek2033a952009-05-13 07:12:33 +00001935 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001936
Ted Kremenek8966bc12009-05-06 21:39:49 +00001937 // Check if the type state has changed.
Ted Kremenek8bef8232012-01-26 21:29:00 +00001938 ProgramStateRef PrevSt = PrevN->getState();
1939 ProgramStateRef CurrSt = N->getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001940 const LocationContext *LCtx = N->getLocationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00001941
1942 const RefVal* CurrT = CurrSt->get<RefBindings>(Sym);
Ted Kremenekc887d132009-04-29 18:50:19 +00001943 if (!CurrT) return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001944
Ted Kremenekb65be702009-06-18 01:23:53 +00001945 const RefVal &CurrV = *CurrT;
1946 const RefVal *PrevT = PrevSt->get<RefBindings>(Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00001947
Ted Kremenekc887d132009-04-29 18:50:19 +00001948 // Create a string buffer to constain all the useful things we want
1949 // to tell the user.
1950 std::string sbuf;
1951 llvm::raw_string_ostream os(sbuf);
Mike Stump1eb44332009-09-09 15:08:12 +00001952
Ted Kremenekc887d132009-04-29 18:50:19 +00001953 // This is the allocation site since the previous node had no bindings
1954 // for this symbol.
1955 if (!PrevT) {
Jordy Rosef53e8c72011-08-23 19:43:16 +00001956 const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
Mike Stump1eb44332009-09-09 15:08:12 +00001957
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001958 if (isa<ObjCArrayLiteral>(S)) {
1959 os << "NSArray literal is an object with a +0 retain count";
Mike Stump1eb44332009-09-09 15:08:12 +00001960 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001961 else if (isa<ObjCDictionaryLiteral>(S)) {
1962 os << "NSDictionary literal is an object with a +0 retain count";
Ted Kremenekc887d132009-04-29 18:50:19 +00001963 }
Jordy Rose70fdbc32012-05-12 05:10:43 +00001964 else if (const ObjCBoxedExpr *BL = dyn_cast<ObjCBoxedExpr>(S)) {
1965 if (isNumericLiteralExpression(BL->getSubExpr()))
1966 os << "NSNumber literal is an object with a +0 retain count";
1967 else {
1968 const ObjCInterfaceDecl *BoxClass = 0;
1969 if (const ObjCMethodDecl *Method = BL->getBoxingMethod())
1970 BoxClass = Method->getClassInterface();
1971
1972 // We should always be able to find the boxing class interface,
1973 // but consider this future-proofing.
1974 if (BoxClass)
1975 os << *BoxClass << " b";
1976 else
1977 os << "B";
1978
1979 os << "oxed expression produces an object with a +0 retain count";
1980 }
1981 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001982 else {
1983 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
1984 // Get the name of the callee (if it is available).
1985 SVal X = CurrSt->getSValAsScalarOrLoc(CE->getCallee(), LCtx);
1986 if (const FunctionDecl *FD = X.getAsFunctionDecl())
1987 os << "Call to function '" << *FD << '\'';
1988 else
1989 os << "function call";
Ted Kremenekc887d132009-04-29 18:50:19 +00001990 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001991 else {
1992 assert(isa<ObjCMessageExpr>(S));
1993 // The message expression may have between written directly or as
1994 // a property access. Lazily determine which case we are looking at.
1995 os << (isPropertyAccess(S, N->getParentMap()) ? "Property" : "Method");
1996 }
1997
1998 if (CurrV.getObjKind() == RetEffect::CF) {
1999 os << " returns a Core Foundation object with a ";
2000 }
2001 else {
2002 assert (CurrV.getObjKind() == RetEffect::ObjC);
2003 os << " returns an Objective-C object with a ";
2004 }
2005
2006 if (CurrV.isOwned()) {
2007 os << "+1 retain count";
2008
2009 if (GCEnabled) {
2010 assert(CurrV.getObjKind() == RetEffect::CF);
2011 os << ". "
2012 "Core Foundation objects are not automatically garbage collected.";
2013 }
2014 }
2015 else {
2016 assert (CurrV.isNotOwned());
2017 os << "+0 retain count";
2018 }
Ted Kremenekc887d132009-04-29 18:50:19 +00002019 }
Mike Stump1eb44332009-09-09 15:08:12 +00002020
Anna Zaks220ac8c2011-09-15 01:08:34 +00002021 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
2022 N->getLocationContext());
Ted Kremenekc887d132009-04-29 18:50:19 +00002023 return new PathDiagnosticEventPiece(Pos, os.str());
2024 }
Mike Stump1eb44332009-09-09 15:08:12 +00002025
Ted Kremenekc887d132009-04-29 18:50:19 +00002026 // Gather up the effects that were performed on the object at this
2027 // program point
Chris Lattner5f9e2722011-07-23 10:55:15 +00002028 SmallVector<ArgEffect, 2> AEffects;
Mike Stump1eb44332009-09-09 15:08:12 +00002029
Jordy Roseec9ef852011-08-23 20:55:48 +00002030 const ExplodedNode *OrigNode = BRC.getNodeResolver().getOriginalNode(N);
2031 if (const RetainSummary *Summ = SummaryLog.lookup(OrigNode)) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002032 // We only have summaries attached to nodes after evaluating CallExpr and
2033 // ObjCMessageExprs.
Jordy Rosef53e8c72011-08-23 19:43:16 +00002034 const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
Mike Stump1eb44332009-09-09 15:08:12 +00002035
Ted Kremenek5f85e172009-07-22 22:35:28 +00002036 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002037 // Iterate through the parameter expressions and see if the symbol
2038 // was ever passed as an argument.
2039 unsigned i = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002040
Ted Kremenek5f85e172009-07-22 22:35:28 +00002041 for (CallExpr::const_arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
Ted Kremenekc887d132009-04-29 18:50:19 +00002042 AI!=AE; ++AI, ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002043
Ted Kremenekc887d132009-04-29 18:50:19 +00002044 // Retrieve the value of the argument. Is it the symbol
2045 // we are interested in?
Ted Kremenek5eca4822012-01-06 22:09:28 +00002046 if (CurrSt->getSValAsScalarOrLoc(*AI, LCtx).getAsLocSymbol() != Sym)
Ted Kremenekc887d132009-04-29 18:50:19 +00002047 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00002048
Ted Kremenekc887d132009-04-29 18:50:19 +00002049 // We have an argument. Get the effect!
2050 AEffects.push_back(Summ->getArg(i));
2051 }
2052 }
Mike Stump1eb44332009-09-09 15:08:12 +00002053 else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002054 if (const Expr *receiver = ME->getInstanceReceiver())
Ted Kremenek5eca4822012-01-06 22:09:28 +00002055 if (CurrSt->getSValAsScalarOrLoc(receiver, LCtx)
2056 .getAsLocSymbol() == Sym) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002057 // The symbol we are tracking is the receiver.
2058 AEffects.push_back(Summ->getReceiverEffect());
2059 }
2060 }
2061 }
Mike Stump1eb44332009-09-09 15:08:12 +00002062
Ted Kremenekc887d132009-04-29 18:50:19 +00002063 do {
2064 // Get the previous type state.
2065 RefVal PrevV = *PrevT;
Mike Stump1eb44332009-09-09 15:08:12 +00002066
Ted Kremenekc887d132009-04-29 18:50:19 +00002067 // Specially handle -dealloc.
Jordy Rose35c86952011-08-24 05:47:39 +00002068 if (!GCEnabled && contains(AEffects, Dealloc)) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002069 // Determine if the object's reference count was pushed to zero.
2070 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2071 // We may not have transitioned to 'release' if we hit an error.
2072 // This case is handled elsewhere.
2073 if (CurrV.getKind() == RefVal::Released) {
Ted Kremenekf21332e2009-05-08 20:01:42 +00002074 assert(CurrV.getCombinedCounts() == 0);
Ted Kremenekc887d132009-04-29 18:50:19 +00002075 os << "Object released by directly sending the '-dealloc' message";
2076 break;
2077 }
2078 }
Mike Stump1eb44332009-09-09 15:08:12 +00002079
Ted Kremenekc887d132009-04-29 18:50:19 +00002080 // Specially handle CFMakeCollectable and friends.
2081 if (contains(AEffects, MakeCollectable)) {
2082 // Get the name of the function.
Jordy Rosef53e8c72011-08-23 19:43:16 +00002083 const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
Ted Kremenek5eca4822012-01-06 22:09:28 +00002084 SVal X =
2085 CurrSt->getSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee(), LCtx);
Ted Kremenek9c378f72011-08-12 23:37:29 +00002086 const FunctionDecl *FD = X.getAsFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002087
Jordy Rose35c86952011-08-24 05:47:39 +00002088 if (GCEnabled) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002089 // Determine if the object's reference count was pushed to zero.
2090 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
Mike Stump1eb44332009-09-09 15:08:12 +00002091
Benjamin Kramerb8989f22011-10-14 18:45:37 +00002092 os << "In GC mode a call to '" << *FD
Ted Kremenekc887d132009-04-29 18:50:19 +00002093 << "' decrements an object's retain count and registers the "
2094 "object with the garbage collector. ";
Mike Stump1eb44332009-09-09 15:08:12 +00002095
Ted Kremenekc887d132009-04-29 18:50:19 +00002096 if (CurrV.getKind() == RefVal::Released) {
2097 assert(CurrV.getCount() == 0);
2098 os << "Since it now has a 0 retain count the object can be "
2099 "automatically collected by the garbage collector.";
2100 }
2101 else
2102 os << "An object must have a 0 retain count to be garbage collected. "
2103 "After this call its retain count is +" << CurrV.getCount()
2104 << '.';
2105 }
Mike Stump1eb44332009-09-09 15:08:12 +00002106 else
Benjamin Kramerb8989f22011-10-14 18:45:37 +00002107 os << "When GC is not enabled a call to '" << *FD
Ted Kremenekc887d132009-04-29 18:50:19 +00002108 << "' has no effect on its argument.";
Mike Stump1eb44332009-09-09 15:08:12 +00002109
Ted Kremenekc887d132009-04-29 18:50:19 +00002110 // Nothing more to say.
2111 break;
2112 }
Mike Stump1eb44332009-09-09 15:08:12 +00002113
2114 // Determine if the typestate has changed.
Ted Kremenekc887d132009-04-29 18:50:19 +00002115 if (!(PrevV == CurrV))
2116 switch (CurrV.getKind()) {
2117 case RefVal::Owned:
2118 case RefVal::NotOwned:
Mike Stump1eb44332009-09-09 15:08:12 +00002119
Ted Kremenekf21332e2009-05-08 20:01:42 +00002120 if (PrevV.getCount() == CurrV.getCount()) {
2121 // Did an autorelease message get sent?
2122 if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
2123 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002124
Zhongxing Xu264e9372009-05-12 10:10:00 +00002125 assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount());
Ted Kremenekeaedfea2009-05-10 05:11:21 +00002126 os << "Object sent -autorelease message";
Ted Kremenekf21332e2009-05-08 20:01:42 +00002127 break;
2128 }
Mike Stump1eb44332009-09-09 15:08:12 +00002129
Ted Kremenekc887d132009-04-29 18:50:19 +00002130 if (PrevV.getCount() > CurrV.getCount())
2131 os << "Reference count decremented.";
2132 else
2133 os << "Reference count incremented.";
Mike Stump1eb44332009-09-09 15:08:12 +00002134
Ted Kremenekc887d132009-04-29 18:50:19 +00002135 if (unsigned Count = CurrV.getCount())
2136 os << " The object now has a +" << Count << " retain count.";
Mike Stump1eb44332009-09-09 15:08:12 +00002137
Ted Kremenekc887d132009-04-29 18:50:19 +00002138 if (PrevV.getKind() == RefVal::Released) {
Jordy Rose35c86952011-08-24 05:47:39 +00002139 assert(GCEnabled && CurrV.getCount() > 0);
Jordy Rose74b7b2b2012-03-17 05:49:15 +00002140 os << " The object is not eligible for garbage collection until "
2141 "the retain count reaches 0 again.";
Ted Kremenekc887d132009-04-29 18:50:19 +00002142 }
Mike Stump1eb44332009-09-09 15:08:12 +00002143
Ted Kremenekc887d132009-04-29 18:50:19 +00002144 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002145
Ted Kremenekc887d132009-04-29 18:50:19 +00002146 case RefVal::Released:
2147 os << "Object released.";
2148 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002149
Ted Kremenekc887d132009-04-29 18:50:19 +00002150 case RefVal::ReturnedOwned:
Jordy Rose74b7b2b2012-03-17 05:49:15 +00002151 // Autoreleases can be applied after marking a node ReturnedOwned.
2152 if (CurrV.getAutoreleaseCount())
2153 return NULL;
2154
2155 os << "Object returned to caller as an owning reference (single "
2156 "retain count transferred to caller)";
Ted Kremenekc887d132009-04-29 18:50:19 +00002157 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002158
Ted Kremenekc887d132009-04-29 18:50:19 +00002159 case RefVal::ReturnedNotOwned:
Ted Kremenekf1365462011-05-26 18:45:44 +00002160 os << "Object returned to caller with a +0 retain count";
Ted Kremenekc887d132009-04-29 18:50:19 +00002161 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002162
Ted Kremenekc887d132009-04-29 18:50:19 +00002163 default:
2164 return NULL;
2165 }
Mike Stump1eb44332009-09-09 15:08:12 +00002166
Ted Kremenekc887d132009-04-29 18:50:19 +00002167 // Emit any remaining diagnostics for the argument effects (if any).
Chris Lattner5f9e2722011-07-23 10:55:15 +00002168 for (SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
Ted Kremenekc887d132009-04-29 18:50:19 +00002169 E=AEffects.end(); I != E; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +00002170
Ted Kremenekc887d132009-04-29 18:50:19 +00002171 // A bunch of things have alternate behavior under GC.
Jordy Rose35c86952011-08-24 05:47:39 +00002172 if (GCEnabled)
Ted Kremenekc887d132009-04-29 18:50:19 +00002173 switch (*I) {
2174 default: break;
2175 case Autorelease:
2176 os << "In GC mode an 'autorelease' has no effect.";
2177 continue;
2178 case IncRefMsg:
2179 os << "In GC mode the 'retain' message has no effect.";
2180 continue;
2181 case DecRefMsg:
2182 os << "In GC mode the 'release' message has no effect.";
2183 continue;
2184 }
2185 }
Mike Stump1eb44332009-09-09 15:08:12 +00002186 } while (0);
2187
Ted Kremenekc887d132009-04-29 18:50:19 +00002188 if (os.str().empty())
2189 return 0; // We have nothing to say!
Ted Kremenek2033a952009-05-13 07:12:33 +00002190
Jordy Rosef53e8c72011-08-23 19:43:16 +00002191 const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
Anna Zaks220ac8c2011-09-15 01:08:34 +00002192 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
2193 N->getLocationContext());
Ted Kremenek9c378f72011-08-12 23:37:29 +00002194 PathDiagnosticPiece *P = new PathDiagnosticEventPiece(Pos, os.str());
Mike Stump1eb44332009-09-09 15:08:12 +00002195
Ted Kremenekc887d132009-04-29 18:50:19 +00002196 // Add the range by scanning the children of the statement for any bindings
2197 // to Sym.
Mike Stump1eb44332009-09-09 15:08:12 +00002198 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
Ted Kremenek5f85e172009-07-22 22:35:28 +00002199 I!=E; ++I)
Ted Kremenek9c378f72011-08-12 23:37:29 +00002200 if (const Expr *Exp = dyn_cast_or_null<Expr>(*I))
Ted Kremenek5eca4822012-01-06 22:09:28 +00002201 if (CurrSt->getSValAsScalarOrLoc(Exp, LCtx).getAsLocSymbol() == Sym) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002202 P->addRange(Exp->getSourceRange());
2203 break;
2204 }
Mike Stump1eb44332009-09-09 15:08:12 +00002205
Ted Kremenekc887d132009-04-29 18:50:19 +00002206 return P;
2207}
2208
Anna Zakse7e01682012-02-28 22:39:22 +00002209// Find the first node in the current function context that referred to the
2210// tracked symbol and the memory location that value was stored to. Note, the
2211// value is only reported if the allocation occurred in the same function as
2212// the leak.
Zhongxing Xuc5619d92009-08-06 01:32:16 +00002213static std::pair<const ExplodedNode*,const MemRegion*>
Ted Kremenek18c66fd2011-08-15 22:09:50 +00002214GetAllocationSite(ProgramStateManager& StateMgr, const ExplodedNode *N,
Ted Kremenekc887d132009-04-29 18:50:19 +00002215 SymbolRef Sym) {
Ted Kremenek9c378f72011-08-12 23:37:29 +00002216 const ExplodedNode *Last = N;
Mike Stump1eb44332009-09-09 15:08:12 +00002217 const MemRegion* FirstBinding = 0;
Anna Zakse7e01682012-02-28 22:39:22 +00002218 const LocationContext *LeakContext = N->getLocationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002219
Ted Kremenekc887d132009-04-29 18:50:19 +00002220 while (N) {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002221 ProgramStateRef St = N->getState();
Ted Kremenekc887d132009-04-29 18:50:19 +00002222 RefBindings B = St->get<RefBindings>();
Mike Stump1eb44332009-09-09 15:08:12 +00002223
Ted Kremenekc887d132009-04-29 18:50:19 +00002224 if (!B.lookup(Sym))
2225 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002226
Anna Zaks27b867e2012-03-21 19:45:01 +00002227 StoreManager::FindUniqueBinding FB(Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002228 StateMgr.iterBindings(St, FB);
2229 if (FB) FirstBinding = FB.getRegion();
2230
Anna Zakse7e01682012-02-28 22:39:22 +00002231 // Allocation node, is the last node in the current context in which the
2232 // symbol was tracked.
2233 if (N->getLocationContext() == LeakContext)
2234 Last = N;
2235
Mike Stump1eb44332009-09-09 15:08:12 +00002236 N = N->pred_empty() ? NULL : *(N->pred_begin());
Ted Kremenekc887d132009-04-29 18:50:19 +00002237 }
Mike Stump1eb44332009-09-09 15:08:12 +00002238
Anna Zakse7e01682012-02-28 22:39:22 +00002239 // If allocation happened in a function different from the leak node context,
2240 // do not report the binding.
2241 if (N->getLocationContext() != LeakContext) {
2242 FirstBinding = 0;
2243 }
2244
Ted Kremenekc887d132009-04-29 18:50:19 +00002245 return std::make_pair(Last, FirstBinding);
2246}
2247
2248PathDiagnosticPiece*
Anna Zaks23f395e2011-08-20 01:27:22 +00002249CFRefReportVisitor::getEndPath(BugReporterContext &BRC,
2250 const ExplodedNode *EndN,
2251 BugReport &BR) {
Ted Kremenek76aadc32012-03-09 01:13:14 +00002252 BR.markInteresting(Sym);
Anna Zaks23f395e2011-08-20 01:27:22 +00002253 return BugReporterVisitor::getDefaultEndPath(BRC, EndN, BR);
Ted Kremenekc887d132009-04-29 18:50:19 +00002254}
2255
2256PathDiagnosticPiece*
Anna Zaks23f395e2011-08-20 01:27:22 +00002257CFRefLeakReportVisitor::getEndPath(BugReporterContext &BRC,
2258 const ExplodedNode *EndN,
2259 BugReport &BR) {
Mike Stump1eb44332009-09-09 15:08:12 +00002260
Ted Kremenek8966bc12009-05-06 21:39:49 +00002261 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenekc887d132009-04-29 18:50:19 +00002262 // assigned to different variables, etc.
Ted Kremenek76aadc32012-03-09 01:13:14 +00002263 BR.markInteresting(Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002264
Ted Kremenekc887d132009-04-29 18:50:19 +00002265 // We are reporting a leak. Walk up the graph to get to the first node where
2266 // the symbol appeared, and also get the first VarDecl that tracked object
2267 // is stored to.
Ted Kremenek9c378f72011-08-12 23:37:29 +00002268 const ExplodedNode *AllocNode = 0;
Ted Kremenekc887d132009-04-29 18:50:19 +00002269 const MemRegion* FirstBinding = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002270
Ted Kremenekc887d132009-04-29 18:50:19 +00002271 llvm::tie(AllocNode, FirstBinding) =
Ted Kremenekf04dced2009-05-08 23:32:51 +00002272 GetAllocationSite(BRC.getStateManager(), EndN, Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002273
Anna Zaks4fdf97b2011-09-15 18:56:07 +00002274 SourceManager& SM = BRC.getSourceManager();
Mike Stump1eb44332009-09-09 15:08:12 +00002275
Ted Kremenekc887d132009-04-29 18:50:19 +00002276 // Compute an actual location for the leak. Sometimes a leak doesn't
2277 // occur at an actual statement (e.g., transition between blocks; end
2278 // of function) so we need to walk the graph and compute a real location.
Ted Kremenek9c378f72011-08-12 23:37:29 +00002279 const ExplodedNode *LeakN = EndN;
Anna Zaks4fdf97b2011-09-15 18:56:07 +00002280 PathDiagnosticLocation L = PathDiagnosticLocation::createEndOfPath(LeakN, SM);
Mike Stump1eb44332009-09-09 15:08:12 +00002281
Ted Kremenekc887d132009-04-29 18:50:19 +00002282 std::string sbuf;
2283 llvm::raw_string_ostream os(sbuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002284
Ted Kremenekf1365462011-05-26 18:45:44 +00002285 os << "Object leaked: ";
Mike Stump1eb44332009-09-09 15:08:12 +00002286
Ted Kremenekf1365462011-05-26 18:45:44 +00002287 if (FirstBinding) {
2288 os << "object allocated and stored into '"
2289 << FirstBinding->getString() << '\'';
2290 }
2291 else
2292 os << "allocated object";
Mike Stump1eb44332009-09-09 15:08:12 +00002293
Ted Kremenekc887d132009-04-29 18:50:19 +00002294 // Get the retain count.
2295 const RefVal* RV = EndN->getState()->get<RefBindings>(Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002296
Ted Kremenekc887d132009-04-29 18:50:19 +00002297 if (RV->getKind() == RefVal::ErrorLeakReturned) {
2298 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
Jordy Rose5b5402b2011-07-15 22:17:54 +00002299 // objects. Only "copy", "alloc", "retain" and "new" transfer ownership
Ted Kremenekc887d132009-04-29 18:50:19 +00002300 // to the caller for NS objects.
Ted Kremenekd368d712011-05-25 06:19:45 +00002301 const Decl *D = &EndN->getCodeDecl();
2302 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2303 os << " is returned from a method whose name ('"
2304 << MD->getSelector().getAsString()
2305 << "') does not start with 'copy', 'mutableCopy', 'alloc' or 'new'."
Jordy Rose5b5402b2011-07-15 22:17:54 +00002306 " This violates the naming convention rules"
Ted Kremenekf1365462011-05-26 18:45:44 +00002307 " given in the Memory Management Guide for Cocoa";
Ted Kremenekd368d712011-05-25 06:19:45 +00002308 }
2309 else {
2310 const FunctionDecl *FD = cast<FunctionDecl>(D);
Ted Kremenekb7dcddf2011-12-22 06:35:52 +00002311 os << " is returned from a function whose name ('"
Benjamin Kramera59d20b2012-02-07 11:57:57 +00002312 << *FD
Ted Kremenekd368d712011-05-25 06:19:45 +00002313 << "') does not contain 'Copy' or 'Create'. This violates the naming"
Ted Kremenekb7dcddf2011-12-22 06:35:52 +00002314 " convention rules given in the Memory Management Guide for Core"
Ted Kremenekf1365462011-05-26 18:45:44 +00002315 " Foundation";
Ted Kremenekd368d712011-05-25 06:19:45 +00002316 }
Ted Kremenekc887d132009-04-29 18:50:19 +00002317 }
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002318 else if (RV->getKind() == RefVal::ErrorGCLeakReturned) {
Ted Kremenek9c378f72011-08-12 23:37:29 +00002319 ObjCMethodDecl &MD = cast<ObjCMethodDecl>(EndN->getCodeDecl());
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002320 os << " and returned from method '" << MD.getSelector().getAsString()
Ted Kremenek82f2be52009-05-10 16:52:15 +00002321 << "' is potentially leaked when using garbage collection. Callers "
2322 "of this method do not expect a returned object with a +1 retain "
2323 "count since they expect the object to be managed by the garbage "
2324 "collector";
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002325 }
Ted Kremenekc887d132009-04-29 18:50:19 +00002326 else
Ted Kremenekabf517c2010-10-15 22:50:23 +00002327 os << " is not referenced later in this execution path and has a retain "
Ted Kremenekf1365462011-05-26 18:45:44 +00002328 "count of +" << RV->getCount();
Mike Stump1eb44332009-09-09 15:08:12 +00002329
Ted Kremenekc887d132009-04-29 18:50:19 +00002330 return new PathDiagnosticEventPiece(L, os.str());
2331}
2332
Jordy Rose20589562011-08-24 22:39:09 +00002333CFRefLeakReport::CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts,
2334 bool GCEnabled, const SummaryLogTy &Log,
2335 ExplodedNode *n, SymbolRef sym,
Anna Zaks6a93bd52011-10-25 19:57:11 +00002336 CheckerContext &Ctx)
Jordy Rose20589562011-08-24 22:39:09 +00002337: CFRefReport(D, LOpts, GCEnabled, Log, n, sym, false) {
Mike Stump1eb44332009-09-09 15:08:12 +00002338
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00002339 // Most bug reports are cached at the location where they occurred.
Ted Kremenekc887d132009-04-29 18:50:19 +00002340 // With leaks, we want to unique them by the location where they were
2341 // allocated, and only report a single path. To do this, we need to find
2342 // the allocation site of a piece of tracked memory, which we do via a
2343 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2344 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2345 // that all ancestor nodes that represent the allocation site have the
2346 // same SourceLocation.
Ted Kremenek9c378f72011-08-12 23:37:29 +00002347 const ExplodedNode *AllocNode = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002348
Anna Zaks6a93bd52011-10-25 19:57:11 +00002349 const SourceManager& SMgr = Ctx.getSourceManager();
Anna Zaks590dd8e2011-09-20 21:38:35 +00002350
Ted Kremenekc887d132009-04-29 18:50:19 +00002351 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding.
Anna Zaks6a93bd52011-10-25 19:57:11 +00002352 GetAllocationSite(Ctx.getStateManager(), getErrorNode(), sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002353
Ted Kremenekc887d132009-04-29 18:50:19 +00002354 // Get the SourceLocation for the allocation site.
2355 ProgramPoint P = AllocNode->getLocation();
Anna Zaks590dd8e2011-09-20 21:38:35 +00002356 const Stmt *AllocStmt = cast<PostStmt>(P).getStmt();
2357 Location = PathDiagnosticLocation::createBegin(AllocStmt, SMgr,
2358 n->getLocationContext());
Ted Kremenekc887d132009-04-29 18:50:19 +00002359 // Fill in the description of the bug.
2360 Description.clear();
2361 llvm::raw_string_ostream os(Description);
Ted Kremenekdd924e22009-05-02 19:05:19 +00002362 os << "Potential leak ";
Jordy Rose20589562011-08-24 22:39:09 +00002363 if (GCEnabled)
Ted Kremenekdd924e22009-05-02 19:05:19 +00002364 os << "(when using garbage collection) ";
Anna Zaks212000e2012-02-28 21:49:08 +00002365 os << "of an object";
Mike Stump1eb44332009-09-09 15:08:12 +00002366
Ted Kremenekc887d132009-04-29 18:50:19 +00002367 // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2368 if (AllocBinding)
Anna Zaks212000e2012-02-28 21:49:08 +00002369 os << " stored into '" << AllocBinding->getString() << '\'';
Anna Zaksdc757b02011-08-19 23:21:56 +00002370
Jordy Rose20589562011-08-24 22:39:09 +00002371 addVisitor(new CFRefLeakReportVisitor(sym, GCEnabled, Log));
Ted Kremenekc887d132009-04-29 18:50:19 +00002372}
2373
2374//===----------------------------------------------------------------------===//
2375// Main checker logic.
2376//===----------------------------------------------------------------------===//
2377
Ted Kremenekd593eb92009-11-25 22:17:44 +00002378namespace {
Jordy Rose910c4052011-09-02 06:44:22 +00002379class RetainCountChecker
Jordy Rose9c083b72011-08-24 18:56:32 +00002380 : public Checker< check::Bind,
Jordy Rose38f17d62011-08-23 19:01:07 +00002381 check::DeadSymbols,
Jordy Rose9c083b72011-08-24 18:56:32 +00002382 check::EndAnalysis,
Jordy Rose38f17d62011-08-23 19:01:07 +00002383 check::EndPath,
Jordy Rose67044292011-08-17 21:27:39 +00002384 check::PostStmt<BlockExpr>,
John McCallf85e1932011-06-15 23:02:42 +00002385 check::PostStmt<CastExpr>,
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002386 check::PostStmt<ObjCArrayLiteral>,
2387 check::PostStmt<ObjCDictionaryLiteral>,
Jordy Rose70fdbc32012-05-12 05:10:43 +00002388 check::PostStmt<ObjCBoxedExpr>,
Jordan Rosefe6a0112012-07-02 19:28:21 +00002389 check::PostCall,
Jordy Rosef53e8c72011-08-23 19:43:16 +00002390 check::PreStmt<ReturnStmt>,
Jordy Rose67044292011-08-17 21:27:39 +00002391 check::RegionChanges,
Jordy Rose76c506f2011-08-21 21:58:18 +00002392 eval::Assume,
2393 eval::Call > {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002394 mutable OwningPtr<CFRefBug> useAfterRelease, releaseNotOwned;
2395 mutable OwningPtr<CFRefBug> deallocGC, deallocNotOwned;
2396 mutable OwningPtr<CFRefBug> overAutorelease, returnNotOwnedForOwned;
2397 mutable OwningPtr<CFRefBug> leakWithinFunction, leakAtReturn;
2398 mutable OwningPtr<CFRefBug> leakWithinFunctionGC, leakAtReturnGC;
Jordy Rose38f17d62011-08-23 19:01:07 +00002399
2400 typedef llvm::DenseMap<SymbolRef, const SimpleProgramPointTag *> SymbolTagMap;
2401
2402 // This map is only used to ensure proper deletion of any allocated tags.
2403 mutable SymbolTagMap DeadSymbolTags;
2404
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002405 mutable OwningPtr<RetainSummaryManager> Summaries;
2406 mutable OwningPtr<RetainSummaryManager> SummariesGC;
Jordy Roseb6cfc092011-08-25 00:10:37 +00002407
Jordy Rosee0a5d322011-08-23 20:27:16 +00002408 mutable ARCounts::Factory ARCountFactory;
2409
Jordy Rose9c083b72011-08-24 18:56:32 +00002410 mutable SummaryLogTy SummaryLog;
2411 mutable bool ShouldResetSummaryLog;
2412
Jordy Rose2f9a66d2011-08-20 21:17:59 +00002413public:
Jordy Rose910c4052011-09-02 06:44:22 +00002414 RetainCountChecker() : ShouldResetSummaryLog(false) {}
Jordy Rose38f17d62011-08-23 19:01:07 +00002415
Jordy Rose910c4052011-09-02 06:44:22 +00002416 virtual ~RetainCountChecker() {
Jordy Rose38f17d62011-08-23 19:01:07 +00002417 DeleteContainerSeconds(DeadSymbolTags);
2418 }
2419
Jordy Rose9c083b72011-08-24 18:56:32 +00002420 void checkEndAnalysis(ExplodedGraph &G, BugReporter &BR,
2421 ExprEngine &Eng) const {
2422 // FIXME: This is a hack to make sure the summary log gets cleared between
2423 // analyses of different code bodies.
2424 //
2425 // Why is this necessary? Because a checker's lifetime is tied to a
2426 // translation unit, but an ExplodedGraph's lifetime is just a code body.
2427 // Once in a blue moon, a new ExplodedNode will have the same address as an
2428 // old one with an associated summary, and the bug report visitor gets very
2429 // confused. (To make things worse, the summary lifetime is currently also
2430 // tied to a code body, so we get a crash instead of incorrect results.)
Jordy Rose1ab51c72011-08-24 09:27:24 +00002431 //
2432 // Why is this a bad solution? Because if the lifetime of the ExplodedGraph
2433 // changes, things will start going wrong again. Really the lifetime of this
2434 // log needs to be tied to either the specific nodes in it or the entire
2435 // ExplodedGraph, not to a specific part of the code being analyzed.
2436 //
Jordy Rose9c083b72011-08-24 18:56:32 +00002437 // (Also, having stateful local data means that the same checker can't be
2438 // used from multiple threads, but a lot of checkers have incorrect
2439 // assumptions about that anyway. So that wasn't a priority at the time of
2440 // this fix.)
Jordy Rose1ab51c72011-08-24 09:27:24 +00002441 //
Jordy Rose9c083b72011-08-24 18:56:32 +00002442 // This happens at the end of analysis, but bug reports are emitted /after/
2443 // this point. So we can't just clear the summary log now. Instead, we mark
2444 // that the next time we access the summary log, it should be cleared.
2445
2446 // If we never reset the summary log during /this/ code body analysis,
2447 // there were no new summaries. There might still have been summaries from
2448 // the /last/ analysis, so clear them out to make sure the bug report
2449 // visitors don't get confused.
2450 if (ShouldResetSummaryLog)
2451 SummaryLog.clear();
2452
2453 ShouldResetSummaryLog = !SummaryLog.empty();
Jordy Rose1ab51c72011-08-24 09:27:24 +00002454 }
2455
Jordy Rose17a38e22011-09-02 05:55:19 +00002456 CFRefBug *getLeakWithinFunctionBug(const LangOptions &LOpts,
2457 bool GCEnabled) const {
2458 if (GCEnabled) {
Jordy Rosedb92bb62011-08-25 01:14:38 +00002459 if (!leakWithinFunctionGC)
Benjamin Kramerfacde172012-06-06 17:32:50 +00002460 leakWithinFunctionGC.reset(new Leak("Leak of object when using "
2461 "garbage collection"));
Jordy Rose17a38e22011-09-02 05:55:19 +00002462 return leakWithinFunctionGC.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002463 } else {
2464 if (!leakWithinFunction) {
Douglas Gregore289d812011-09-13 17:21:33 +00002465 if (LOpts.getGC() == LangOptions::HybridGC) {
Benjamin Kramerfacde172012-06-06 17:32:50 +00002466 leakWithinFunction.reset(new Leak("Leak of object when not using "
2467 "garbage collection (GC) in "
2468 "dual GC/non-GC code"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002469 } else {
Benjamin Kramerfacde172012-06-06 17:32:50 +00002470 leakWithinFunction.reset(new Leak("Leak"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002471 }
2472 }
Jordy Rose17a38e22011-09-02 05:55:19 +00002473 return leakWithinFunction.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002474 }
2475 }
2476
Jordy Rose17a38e22011-09-02 05:55:19 +00002477 CFRefBug *getLeakAtReturnBug(const LangOptions &LOpts, bool GCEnabled) const {
2478 if (GCEnabled) {
Jordy Rosedb92bb62011-08-25 01:14:38 +00002479 if (!leakAtReturnGC)
Benjamin Kramerfacde172012-06-06 17:32:50 +00002480 leakAtReturnGC.reset(new Leak("Leak of returned object when using "
2481 "garbage collection"));
Jordy Rose17a38e22011-09-02 05:55:19 +00002482 return leakAtReturnGC.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002483 } else {
2484 if (!leakAtReturn) {
Douglas Gregore289d812011-09-13 17:21:33 +00002485 if (LOpts.getGC() == LangOptions::HybridGC) {
Benjamin Kramerfacde172012-06-06 17:32:50 +00002486 leakAtReturn.reset(new Leak("Leak of returned object when not using "
2487 "garbage collection (GC) in dual "
2488 "GC/non-GC code"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002489 } else {
Benjamin Kramerfacde172012-06-06 17:32:50 +00002490 leakAtReturn.reset(new Leak("Leak of returned object"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002491 }
2492 }
Jordy Rose17a38e22011-09-02 05:55:19 +00002493 return leakAtReturn.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002494 }
2495 }
2496
Jordy Rose17a38e22011-09-02 05:55:19 +00002497 RetainSummaryManager &getSummaryManager(ASTContext &Ctx,
2498 bool GCEnabled) const {
2499 // FIXME: We don't support ARC being turned on and off during one analysis.
2500 // (nor, for that matter, do we support changing ASTContexts)
David Blaikie4e4d0842012-03-11 07:00:24 +00002501 bool ARCEnabled = (bool)Ctx.getLangOpts().ObjCAutoRefCount;
Jordy Rose17a38e22011-09-02 05:55:19 +00002502 if (GCEnabled) {
2503 if (!SummariesGC)
Jordy Roseb6cfc092011-08-25 00:10:37 +00002504 SummariesGC.reset(new RetainSummaryManager(Ctx, true, ARCEnabled));
Jordy Rose17a38e22011-09-02 05:55:19 +00002505 else
2506 assert(SummariesGC->isARCEnabled() == ARCEnabled);
Jordy Roseb6cfc092011-08-25 00:10:37 +00002507 return *SummariesGC;
2508 } else {
Jordy Rose17a38e22011-09-02 05:55:19 +00002509 if (!Summaries)
Jordy Roseb6cfc092011-08-25 00:10:37 +00002510 Summaries.reset(new RetainSummaryManager(Ctx, false, ARCEnabled));
Jordy Rose17a38e22011-09-02 05:55:19 +00002511 else
2512 assert(Summaries->isARCEnabled() == ARCEnabled);
Jordy Roseb6cfc092011-08-25 00:10:37 +00002513 return *Summaries;
2514 }
2515 }
2516
Jordy Rose17a38e22011-09-02 05:55:19 +00002517 RetainSummaryManager &getSummaryManager(CheckerContext &C) const {
2518 return getSummaryManager(C.getASTContext(), C.isObjCGCEnabled());
2519 }
2520
Ted Kremenek8bef8232012-01-26 21:29:00 +00002521 void printState(raw_ostream &Out, ProgramStateRef State,
Jordy Rosedbd658e2011-08-28 19:11:56 +00002522 const char *NL, const char *Sep) const;
2523
Anna Zaks390909c2011-10-06 00:43:15 +00002524 void checkBind(SVal loc, SVal val, const Stmt *S, CheckerContext &C) const;
Jordy Roseab027fd2011-08-20 21:16:58 +00002525 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
2526 void checkPostStmt(const CastExpr *CE, CheckerContext &C) const;
John McCallf85e1932011-06-15 23:02:42 +00002527
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002528 void checkPostStmt(const ObjCArrayLiteral *AL, CheckerContext &C) const;
2529 void checkPostStmt(const ObjCDictionaryLiteral *DL, CheckerContext &C) const;
Jordy Rose70fdbc32012-05-12 05:10:43 +00002530 void checkPostStmt(const ObjCBoxedExpr *BE, CheckerContext &C) const;
2531
Jordan Rosefe6a0112012-07-02 19:28:21 +00002532 void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002533
Jordan Rose4531b7d2012-07-02 19:27:43 +00002534 void checkSummary(const RetainSummary &Summ, const CallEvent &Call,
Jordy Rosee38dd952011-08-28 05:16:28 +00002535 CheckerContext &C) const;
Jordy Rose294396b2011-08-22 23:48:23 +00002536
Jordy Rose76c506f2011-08-21 21:58:18 +00002537 bool evalCall(const CallExpr *CE, CheckerContext &C) const;
2538
Ted Kremenek8bef8232012-01-26 21:29:00 +00002539 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Jordy Roseab027fd2011-08-20 21:16:58 +00002540 bool Assumption) const;
Jordy Rose67044292011-08-17 21:27:39 +00002541
Ted Kremenek8bef8232012-01-26 21:29:00 +00002542 ProgramStateRef
2543 checkRegionChanges(ProgramStateRef state,
Jordy Rose537716a2011-08-27 22:51:26 +00002544 const StoreManager::InvalidatedSymbols *invalidated,
2545 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00002546 ArrayRef<const MemRegion *> Regions,
Jordan Rose740d4902012-07-02 19:27:35 +00002547 const CallEvent *Call) const;
Jordy Roseab027fd2011-08-20 21:16:58 +00002548
Ted Kremenek8bef8232012-01-26 21:29:00 +00002549 bool wantsRegionChangeUpdate(ProgramStateRef state) const {
Jordy Rose2f9a66d2011-08-20 21:17:59 +00002550 return true;
Jordy Roseab027fd2011-08-20 21:16:58 +00002551 }
Jordy Rose294396b2011-08-22 23:48:23 +00002552
Jordy Rosef53e8c72011-08-23 19:43:16 +00002553 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
2554 void checkReturnWithRetEffect(const ReturnStmt *S, CheckerContext &C,
2555 ExplodedNode *Pred, RetEffect RE, RefVal X,
Ted Kremenek8bef8232012-01-26 21:29:00 +00002556 SymbolRef Sym, ProgramStateRef state) const;
Jordy Rosef53e8c72011-08-23 19:43:16 +00002557
Jordy Rose38f17d62011-08-23 19:01:07 +00002558 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Anna Zaksaf498a22011-10-25 19:56:48 +00002559 void checkEndPath(CheckerContext &C) const;
Jordy Rose38f17d62011-08-23 19:01:07 +00002560
Ted Kremenek8bef8232012-01-26 21:29:00 +00002561 ProgramStateRef updateSymbol(ProgramStateRef state, SymbolRef sym,
Jordy Rose17a38e22011-09-02 05:55:19 +00002562 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
2563 CheckerContext &C) const;
Jordy Rosee0a5d322011-08-23 20:27:16 +00002564
Ted Kremenek8bef8232012-01-26 21:29:00 +00002565 void processNonLeakError(ProgramStateRef St, SourceRange ErrorRange,
Jordy Rose294396b2011-08-22 23:48:23 +00002566 RefVal::Kind ErrorKind, SymbolRef Sym,
2567 CheckerContext &C) const;
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002568
2569 void processObjCLiterals(CheckerContext &C, const Expr *Ex) const;
Jordy Rose294396b2011-08-22 23:48:23 +00002570
Jordy Rose38f17d62011-08-23 19:01:07 +00002571 const ProgramPointTag *getDeadSymbolTag(SymbolRef sym) const;
2572
Ted Kremenek8bef8232012-01-26 21:29:00 +00002573 ProgramStateRef handleSymbolDeath(ProgramStateRef state,
Jordy Rose38f17d62011-08-23 19:01:07 +00002574 SymbolRef sid, RefVal V,
2575 SmallVectorImpl<SymbolRef> &Leaked) const;
2576
Ted Kremenek8bef8232012-01-26 21:29:00 +00002577 std::pair<ExplodedNode *, ProgramStateRef >
2578 handleAutoreleaseCounts(ProgramStateRef state,
Jordy Rose8d228632011-08-23 20:07:14 +00002579 GenericNodeBuilderRefCount Bd, ExplodedNode *Pred,
Anna Zaks6a93bd52011-10-25 19:57:11 +00002580 CheckerContext &Ctx, SymbolRef Sym, RefVal V) const;
Jordy Rose8d228632011-08-23 20:07:14 +00002581
Ted Kremenek8bef8232012-01-26 21:29:00 +00002582 ExplodedNode *processLeaks(ProgramStateRef state,
Jordy Rose38f17d62011-08-23 19:01:07 +00002583 SmallVectorImpl<SymbolRef> &Leaked,
2584 GenericNodeBuilderRefCount &Builder,
Anna Zaks6a93bd52011-10-25 19:57:11 +00002585 CheckerContext &Ctx,
Jordy Rose38f17d62011-08-23 19:01:07 +00002586 ExplodedNode *Pred = 0) const;
Ted Kremenekd593eb92009-11-25 22:17:44 +00002587};
2588} // end anonymous namespace
2589
Jordy Rose67044292011-08-17 21:27:39 +00002590namespace {
2591class StopTrackingCallback : public SymbolVisitor {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002592 ProgramStateRef state;
Jordy Rose67044292011-08-17 21:27:39 +00002593public:
Ted Kremenek8bef8232012-01-26 21:29:00 +00002594 StopTrackingCallback(ProgramStateRef st) : state(st) {}
2595 ProgramStateRef getState() const { return state; }
Jordy Rose67044292011-08-17 21:27:39 +00002596
2597 bool VisitSymbol(SymbolRef sym) {
2598 state = state->remove<RefBindings>(sym);
2599 return true;
2600 }
2601};
2602} // end anonymous namespace
2603
Jordy Rose910c4052011-09-02 06:44:22 +00002604//===----------------------------------------------------------------------===//
2605// Handle statements that may have an effect on refcounts.
2606//===----------------------------------------------------------------------===//
Jordy Rose67044292011-08-17 21:27:39 +00002607
Jordy Rose910c4052011-09-02 06:44:22 +00002608void RetainCountChecker::checkPostStmt(const BlockExpr *BE,
2609 CheckerContext &C) const {
Jordy Rose67044292011-08-17 21:27:39 +00002610
Jordy Rose910c4052011-09-02 06:44:22 +00002611 // Scan the BlockDecRefExprs for any object the retain count checker
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002612 // may be tracking.
John McCall469a1eb2011-02-02 13:00:07 +00002613 if (!BE->getBlockDecl()->hasCaptures())
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002614 return;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002615
Ted Kremenek8bef8232012-01-26 21:29:00 +00002616 ProgramStateRef state = C.getState();
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002617 const BlockDataRegion *R =
Ted Kremenek5eca4822012-01-06 22:09:28 +00002618 cast<BlockDataRegion>(state->getSVal(BE,
2619 C.getLocationContext()).getAsRegion());
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002620
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002621 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
2622 E = R->referenced_vars_end();
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002623
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002624 if (I == E)
2625 return;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002626
Ted Kremenek67d12872009-12-07 22:05:27 +00002627 // FIXME: For now we invalidate the tracking of all symbols passed to blocks
2628 // via captured variables, even though captured variables result in a copy
2629 // and in implicit increment/decrement of a retain count.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002630 SmallVector<const MemRegion*, 10> Regions;
Anna Zaks39ac1872011-10-26 21:06:44 +00002631 const LocationContext *LC = C.getLocationContext();
Ted Kremenekc8413fd2010-12-02 07:49:45 +00002632 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002633
Ted Kremenek67d12872009-12-07 22:05:27 +00002634 for ( ; I != E; ++I) {
2635 const VarRegion *VR = *I;
2636 if (VR->getSuperRegion() == R) {
2637 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2638 }
2639 Regions.push_back(VR);
2640 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002641
Ted Kremenek67d12872009-12-07 22:05:27 +00002642 state =
2643 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
2644 Regions.data() + Regions.size()).getState();
Anna Zaks0bd6b112011-10-26 21:06:34 +00002645 C.addTransition(state);
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002646}
2647
Jordy Rose910c4052011-09-02 06:44:22 +00002648void RetainCountChecker::checkPostStmt(const CastExpr *CE,
2649 CheckerContext &C) const {
John McCallf85e1932011-06-15 23:02:42 +00002650 const ObjCBridgedCastExpr *BE = dyn_cast<ObjCBridgedCastExpr>(CE);
2651 if (!BE)
2652 return;
2653
John McCall71c482c2011-06-17 06:50:50 +00002654 ArgEffect AE = IncRef;
John McCallf85e1932011-06-15 23:02:42 +00002655
2656 switch (BE->getBridgeKind()) {
2657 case clang::OBC_Bridge:
2658 // Do nothing.
2659 return;
2660 case clang::OBC_BridgeRetained:
2661 AE = IncRef;
2662 break;
2663 case clang::OBC_BridgeTransfer:
2664 AE = DecRefBridgedTransfered;
2665 break;
2666 }
2667
Ted Kremenek8bef8232012-01-26 21:29:00 +00002668 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00002669 SymbolRef Sym = state->getSVal(CE, C.getLocationContext()).getAsLocSymbol();
John McCallf85e1932011-06-15 23:02:42 +00002670 if (!Sym)
2671 return;
2672 const RefVal* T = state->get<RefBindings>(Sym);
2673 if (!T)
2674 return;
2675
John McCallf85e1932011-06-15 23:02:42 +00002676 RefVal::Kind hasErr = (RefVal::Kind) 0;
Jordy Rose17a38e22011-09-02 05:55:19 +00002677 state = updateSymbol(state, Sym, *T, AE, hasErr, C);
John McCallf85e1932011-06-15 23:02:42 +00002678
2679 if (hasErr) {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002680 // FIXME: If we get an error during a bridge cast, should we report it?
2681 // Should we assert that there is no error?
John McCallf85e1932011-06-15 23:02:42 +00002682 return;
2683 }
2684
Anna Zaks0bd6b112011-10-26 21:06:34 +00002685 C.addTransition(state);
John McCallf85e1932011-06-15 23:02:42 +00002686}
2687
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002688void RetainCountChecker::processObjCLiterals(CheckerContext &C,
2689 const Expr *Ex) const {
2690 ProgramStateRef state = C.getState();
2691 const ExplodedNode *pred = C.getPredecessor();
2692 for (Stmt::const_child_iterator it = Ex->child_begin(), et = Ex->child_end() ;
2693 it != et ; ++it) {
2694 const Stmt *child = *it;
2695 SVal V = state->getSVal(child, pred->getLocationContext());
2696 if (SymbolRef sym = V.getAsSymbol())
2697 if (const RefVal* T = state->get<RefBindings>(sym)) {
2698 RefVal::Kind hasErr = (RefVal::Kind) 0;
2699 state = updateSymbol(state, sym, *T, MayEscape, hasErr, C);
2700 if (hasErr) {
2701 processNonLeakError(state, child->getSourceRange(), hasErr, sym, C);
2702 return;
2703 }
2704 }
2705 }
2706
2707 // Return the object as autoreleased.
2708 // RetEffect RE = RetEffect::MakeNotOwned(RetEffect::ObjC);
2709 if (SymbolRef sym =
2710 state->getSVal(Ex, pred->getLocationContext()).getAsSymbol()) {
2711 QualType ResultTy = Ex->getType();
2712 state = state->set<RefBindings>(sym, RefVal::makeNotOwned(RetEffect::ObjC,
2713 ResultTy));
2714 }
2715
2716 C.addTransition(state);
2717}
2718
2719void RetainCountChecker::checkPostStmt(const ObjCArrayLiteral *AL,
2720 CheckerContext &C) const {
2721 // Apply the 'MayEscape' to all values.
2722 processObjCLiterals(C, AL);
2723}
2724
2725void RetainCountChecker::checkPostStmt(const ObjCDictionaryLiteral *DL,
2726 CheckerContext &C) const {
2727 // Apply the 'MayEscape' to all keys and values.
2728 processObjCLiterals(C, DL);
2729}
2730
Jordy Rose70fdbc32012-05-12 05:10:43 +00002731void RetainCountChecker::checkPostStmt(const ObjCBoxedExpr *Ex,
2732 CheckerContext &C) const {
2733 const ExplodedNode *Pred = C.getPredecessor();
2734 const LocationContext *LCtx = Pred->getLocationContext();
2735 ProgramStateRef State = Pred->getState();
2736
2737 if (SymbolRef Sym = State->getSVal(Ex, LCtx).getAsSymbol()) {
2738 QualType ResultTy = Ex->getType();
2739 State = State->set<RefBindings>(Sym, RefVal::makeNotOwned(RetEffect::ObjC,
2740 ResultTy));
2741 }
2742
2743 C.addTransition(State);
2744}
2745
Jordan Rosefe6a0112012-07-02 19:28:21 +00002746void RetainCountChecker::checkPostCall(const CallEvent &Call,
2747 CheckerContext &C) const {
2748 if (C.wasInlined)
2749 return;
Jordy Roseb6cfc092011-08-25 00:10:37 +00002750
Jordan Rosefe6a0112012-07-02 19:28:21 +00002751 RetainSummaryManager &Summaries = getSummaryManager(C);
2752 const RetainSummary *Summ = Summaries.getSummary(Call, C.getState());
2753 checkSummary(*Summ, Call, C);
Jordy Rose294396b2011-08-22 23:48:23 +00002754}
2755
Jordy Rose910c4052011-09-02 06:44:22 +00002756/// GetReturnType - Used to get the return type of a message expression or
2757/// function call with the intention of affixing that type to a tracked symbol.
2758/// While the the return type can be queried directly from RetEx, when
2759/// invoking class methods we augment to the return type to be that of
2760/// a pointer to the class (as opposed it just being id).
2761// FIXME: We may be able to do this with related result types instead.
2762// This function is probably overestimating.
2763static QualType GetReturnType(const Expr *RetE, ASTContext &Ctx) {
2764 QualType RetTy = RetE->getType();
2765 // If RetE is not a message expression just return its type.
2766 // If RetE is a message expression, return its types if it is something
2767 /// more specific than id.
2768 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RetE))
2769 if (const ObjCObjectPointerType *PT = RetTy->getAs<ObjCObjectPointerType>())
2770 if (PT->isObjCQualifiedIdType() || PT->isObjCIdType() ||
2771 PT->isObjCClassType()) {
2772 // At this point we know the return type of the message expression is
2773 // id, id<...>, or Class. If we have an ObjCInterfaceDecl, we know this
2774 // is a call to a class method whose type we can resolve. In such
2775 // cases, promote the return type to XXX* (where XXX is the class).
2776 const ObjCInterfaceDecl *D = ME->getReceiverInterface();
2777 return !D ? RetTy :
2778 Ctx.getObjCObjectPointerType(Ctx.getObjCInterfaceType(D));
2779 }
2780
2781 return RetTy;
2782}
2783
2784void RetainCountChecker::checkSummary(const RetainSummary &Summ,
Jordan Rose4531b7d2012-07-02 19:27:43 +00002785 const CallEvent &CallOrMsg,
Jordy Rose910c4052011-09-02 06:44:22 +00002786 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002787 ProgramStateRef state = C.getState();
Jordy Rose294396b2011-08-22 23:48:23 +00002788
2789 // Evaluate the effect of the arguments.
2790 RefVal::Kind hasErr = (RefVal::Kind) 0;
2791 SourceRange ErrorRange;
2792 SymbolRef ErrorSym = 0;
2793
2794 for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
Jordy Rose537716a2011-08-27 22:51:26 +00002795 SVal V = CallOrMsg.getArgSVal(idx);
Jordy Rose294396b2011-08-22 23:48:23 +00002796
2797 if (SymbolRef Sym = V.getAsLocSymbol()) {
2798 if (RefBindings::data_type *T = state->get<RefBindings>(Sym)) {
Jordy Rose17a38e22011-09-02 05:55:19 +00002799 state = updateSymbol(state, Sym, *T, Summ.getArg(idx), hasErr, C);
Jordy Rose294396b2011-08-22 23:48:23 +00002800 if (hasErr) {
2801 ErrorRange = CallOrMsg.getArgSourceRange(idx);
2802 ErrorSym = Sym;
2803 break;
2804 }
2805 }
2806 }
2807 }
2808
2809 // Evaluate the effect on the message receiver.
2810 bool ReceiverIsTracked = false;
Jordan Rose4531b7d2012-07-02 19:27:43 +00002811 if (!hasErr) {
Jordan Rosecde8cdb2012-07-02 19:27:56 +00002812 const ObjCMethodCall *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg);
Jordan Rose4531b7d2012-07-02 19:27:43 +00002813 if (MsgInvocation) {
2814 if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
2815 if (const RefVal *T = state->get<RefBindings>(Sym)) {
2816 ReceiverIsTracked = true;
2817 state = updateSymbol(state, Sym, *T, Summ.getReceiverEffect(),
2818 hasErr, C);
2819 if (hasErr) {
2820 ErrorRange = MsgInvocation->getReceiverSourceRange();
2821 ErrorSym = Sym;
2822 }
Jordy Rose294396b2011-08-22 23:48:23 +00002823 }
2824 }
2825 }
2826 }
2827
2828 // Process any errors.
2829 if (hasErr) {
2830 processNonLeakError(state, ErrorRange, hasErr, ErrorSym, C);
2831 return;
2832 }
2833
2834 // Consult the summary for the return value.
2835 RetEffect RE = Summ.getRetEffect();
2836
2837 if (RE.getKind() == RetEffect::OwnedWhenTrackedReceiver) {
Jordy Roseb6cfc092011-08-25 00:10:37 +00002838 if (ReceiverIsTracked)
Jordy Rose17a38e22011-09-02 05:55:19 +00002839 RE = getSummaryManager(C).getObjAllocRetEffect();
Jordy Roseb6cfc092011-08-25 00:10:37 +00002840 else
Jordy Rose294396b2011-08-22 23:48:23 +00002841 RE = RetEffect::MakeNoRet();
2842 }
2843
2844 switch (RE.getKind()) {
2845 default:
David Blaikie7530c032012-01-17 06:56:22 +00002846 llvm_unreachable("Unhandled RetEffect.");
Jordy Rose294396b2011-08-22 23:48:23 +00002847
2848 case RetEffect::NoRet:
2849 // No work necessary.
2850 break;
2851
2852 case RetEffect::OwnedAllocatedSymbol:
2853 case RetEffect::OwnedSymbol: {
Ted Kremenek5eca4822012-01-06 22:09:28 +00002854 SymbolRef Sym = state->getSVal(CallOrMsg.getOriginExpr(),
2855 C.getLocationContext()).getAsSymbol();
Jordy Rose294396b2011-08-22 23:48:23 +00002856 if (!Sym)
2857 break;
2858
Jordan Rose4531b7d2012-07-02 19:27:43 +00002859 // Use the result type from the CallEvent as it automatically adjusts
Jordy Rose294396b2011-08-22 23:48:23 +00002860 // for methods/functions that return references.
Jordan Rose4531b7d2012-07-02 19:27:43 +00002861 QualType ResultTy = CallOrMsg.getResultType();
Jordy Rose294396b2011-08-22 23:48:23 +00002862 state = state->set<RefBindings>(Sym, RefVal::makeOwned(RE.getObjKind(),
2863 ResultTy));
2864
2865 // FIXME: Add a flag to the checker where allocations are assumed to
2866 // *not* fail. (The code below is out-of-date, though.)
2867#if 0
2868 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) {
2869 bool isFeasible;
2870 state = state.assume(loc::SymbolVal(Sym), true, isFeasible);
2871 assert(isFeasible && "Cannot assume fresh symbol is non-null.");
2872 }
2873#endif
2874
2875 break;
2876 }
2877
2878 case RetEffect::GCNotOwnedSymbol:
2879 case RetEffect::ARCNotOwnedSymbol:
2880 case RetEffect::NotOwnedSymbol: {
2881 const Expr *Ex = CallOrMsg.getOriginExpr();
Ted Kremenek5eca4822012-01-06 22:09:28 +00002882 SymbolRef Sym = state->getSVal(Ex, C.getLocationContext()).getAsSymbol();
Jordy Rose294396b2011-08-22 23:48:23 +00002883 if (!Sym)
2884 break;
2885
2886 // Use GetReturnType in order to give [NSFoo alloc] the type NSFoo *.
2887 QualType ResultTy = GetReturnType(Ex, C.getASTContext());
2888 state = state->set<RefBindings>(Sym, RefVal::makeNotOwned(RE.getObjKind(),
2889 ResultTy));
2890 break;
2891 }
2892 }
2893
2894 // This check is actually necessary; otherwise the statement builder thinks
2895 // we've hit a previously-found path.
2896 // Normally addTransition takes care of this, but we want the node pointer.
2897 ExplodedNode *NewNode;
2898 if (state == C.getState()) {
2899 NewNode = C.getPredecessor();
2900 } else {
Anna Zaks0bd6b112011-10-26 21:06:34 +00002901 NewNode = C.addTransition(state);
Jordy Rose294396b2011-08-22 23:48:23 +00002902 }
2903
Jordy Rose9c083b72011-08-24 18:56:32 +00002904 // Annotate the node with summary we used.
2905 if (NewNode) {
2906 // FIXME: This is ugly. See checkEndAnalysis for why it's necessary.
2907 if (ShouldResetSummaryLog) {
2908 SummaryLog.clear();
2909 ShouldResetSummaryLog = false;
2910 }
Jordy Roseec9ef852011-08-23 20:55:48 +00002911 SummaryLog[NewNode] = &Summ;
Jordy Rose9c083b72011-08-24 18:56:32 +00002912 }
Jordy Rose294396b2011-08-22 23:48:23 +00002913}
2914
Jordy Rosee0a5d322011-08-23 20:27:16 +00002915
Ted Kremenek8bef8232012-01-26 21:29:00 +00002916ProgramStateRef
2917RetainCountChecker::updateSymbol(ProgramStateRef state, SymbolRef sym,
Jordy Rose910c4052011-09-02 06:44:22 +00002918 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
2919 CheckerContext &C) const {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002920 // In GC mode [... release] and [... retain] do nothing.
Jordy Rose910c4052011-09-02 06:44:22 +00002921 // In ARC mode they shouldn't exist at all, but we just ignore them.
Jordy Rose17a38e22011-09-02 05:55:19 +00002922 bool IgnoreRetainMsg = C.isObjCGCEnabled();
2923 if (!IgnoreRetainMsg)
David Blaikie4e4d0842012-03-11 07:00:24 +00002924 IgnoreRetainMsg = (bool)C.getASTContext().getLangOpts().ObjCAutoRefCount;
Jordy Rose17a38e22011-09-02 05:55:19 +00002925
Jordy Rosee0a5d322011-08-23 20:27:16 +00002926 switch (E) {
Jordan Rose4531b7d2012-07-02 19:27:43 +00002927 default:
2928 break;
2929 case IncRefMsg:
2930 E = IgnoreRetainMsg ? DoNothing : IncRef;
2931 break;
2932 case DecRefMsg:
2933 E = IgnoreRetainMsg ? DoNothing : DecRef;
2934 break;
2935 case DecRefMsgAndStopTracking:
2936 E = IgnoreRetainMsg ? StopTracking : DecRefAndStopTracking;
2937 break;
2938 case MakeCollectable:
2939 E = C.isObjCGCEnabled() ? DecRef : DoNothing;
2940 break;
2941 case NewAutoreleasePool:
2942 E = C.isObjCGCEnabled() ? DoNothing : NewAutoreleasePool;
2943 break;
Jordy Rosee0a5d322011-08-23 20:27:16 +00002944 }
2945
2946 // Handle all use-after-releases.
Jordy Rose17a38e22011-09-02 05:55:19 +00002947 if (!C.isObjCGCEnabled() && V.getKind() == RefVal::Released) {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002948 V = V ^ RefVal::ErrorUseAfterRelease;
2949 hasErr = V.getKind();
2950 return state->set<RefBindings>(sym, V);
2951 }
2952
2953 switch (E) {
2954 case DecRefMsg:
2955 case IncRefMsg:
2956 case MakeCollectable:
Jordan Rose4531b7d2012-07-02 19:27:43 +00002957 case DecRefMsgAndStopTracking:
Jordy Rosee0a5d322011-08-23 20:27:16 +00002958 llvm_unreachable("DecRefMsg/IncRefMsg/MakeCollectable already converted");
Jordy Rosee0a5d322011-08-23 20:27:16 +00002959
2960 case Dealloc:
2961 // Any use of -dealloc in GC is *bad*.
Jordy Rose17a38e22011-09-02 05:55:19 +00002962 if (C.isObjCGCEnabled()) {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002963 V = V ^ RefVal::ErrorDeallocGC;
2964 hasErr = V.getKind();
2965 break;
2966 }
2967
2968 switch (V.getKind()) {
2969 default:
2970 llvm_unreachable("Invalid RefVal state for an explicit dealloc.");
Jordy Rosee0a5d322011-08-23 20:27:16 +00002971 case RefVal::Owned:
2972 // The object immediately transitions to the released state.
2973 V = V ^ RefVal::Released;
2974 V.clearCounts();
2975 return state->set<RefBindings>(sym, V);
2976 case RefVal::NotOwned:
2977 V = V ^ RefVal::ErrorDeallocNotOwned;
2978 hasErr = V.getKind();
2979 break;
2980 }
2981 break;
2982
2983 case NewAutoreleasePool:
Jordy Rose17a38e22011-09-02 05:55:19 +00002984 assert(!C.isObjCGCEnabled());
Jordy Rosee0a5d322011-08-23 20:27:16 +00002985 return state->add<AutoreleaseStack>(sym);
2986
2987 case MayEscape:
2988 if (V.getKind() == RefVal::Owned) {
2989 V = V ^ RefVal::NotOwned;
2990 break;
2991 }
2992
2993 // Fall-through.
2994
Jordy Rosee0a5d322011-08-23 20:27:16 +00002995 case DoNothing:
2996 return state;
2997
2998 case Autorelease:
Jordy Rose17a38e22011-09-02 05:55:19 +00002999 if (C.isObjCGCEnabled())
Jordy Rosee0a5d322011-08-23 20:27:16 +00003000 return state;
3001
3002 // Update the autorelease counts.
3003 state = SendAutorelease(state, ARCountFactory, sym);
3004 V = V.autorelease();
3005 break;
3006
3007 case StopTracking:
3008 return state->remove<RefBindings>(sym);
3009
3010 case IncRef:
3011 switch (V.getKind()) {
3012 default:
3013 llvm_unreachable("Invalid RefVal state for a retain.");
Jordy Rosee0a5d322011-08-23 20:27:16 +00003014 case RefVal::Owned:
3015 case RefVal::NotOwned:
3016 V = V + 1;
3017 break;
3018 case RefVal::Released:
3019 // Non-GC cases are handled above.
Jordy Rose17a38e22011-09-02 05:55:19 +00003020 assert(C.isObjCGCEnabled());
Jordy Rosee0a5d322011-08-23 20:27:16 +00003021 V = (V ^ RefVal::Owned) + 1;
3022 break;
3023 }
3024 break;
3025
Jordy Rosee0a5d322011-08-23 20:27:16 +00003026 case DecRef:
3027 case DecRefBridgedTransfered:
Jordan Rose4531b7d2012-07-02 19:27:43 +00003028 case DecRefAndStopTracking:
Jordy Rosee0a5d322011-08-23 20:27:16 +00003029 switch (V.getKind()) {
3030 default:
3031 // case 'RefVal::Released' handled above.
3032 llvm_unreachable("Invalid RefVal state for a release.");
Jordy Rosee0a5d322011-08-23 20:27:16 +00003033
3034 case RefVal::Owned:
3035 assert(V.getCount() > 0);
3036 if (V.getCount() == 1)
3037 V = V ^ (E == DecRefBridgedTransfered ?
3038 RefVal::NotOwned : RefVal::Released);
Jordan Rose4531b7d2012-07-02 19:27:43 +00003039 else if (E == DecRefAndStopTracking)
3040 return state->remove<RefBindings>(sym);
3041
Jordy Rosee0a5d322011-08-23 20:27:16 +00003042 V = V - 1;
3043 break;
3044
3045 case RefVal::NotOwned:
Jordan Rose4531b7d2012-07-02 19:27:43 +00003046 if (V.getCount() > 0) {
3047 if (E == DecRefAndStopTracking)
3048 return state->remove<RefBindings>(sym);
Jordy Rosee0a5d322011-08-23 20:27:16 +00003049 V = V - 1;
Jordan Rose4531b7d2012-07-02 19:27:43 +00003050 } else {
Jordy Rosee0a5d322011-08-23 20:27:16 +00003051 V = V ^ RefVal::ErrorReleaseNotOwned;
3052 hasErr = V.getKind();
3053 }
3054 break;
3055
3056 case RefVal::Released:
3057 // Non-GC cases are handled above.
Jordy Rose17a38e22011-09-02 05:55:19 +00003058 assert(C.isObjCGCEnabled());
Jordy Rosee0a5d322011-08-23 20:27:16 +00003059 V = V ^ RefVal::ErrorUseAfterRelease;
3060 hasErr = V.getKind();
3061 break;
3062 }
3063 break;
3064 }
3065 return state->set<RefBindings>(sym, V);
3066}
3067
Ted Kremenek8bef8232012-01-26 21:29:00 +00003068void RetainCountChecker::processNonLeakError(ProgramStateRef St,
Jordy Rose910c4052011-09-02 06:44:22 +00003069 SourceRange ErrorRange,
3070 RefVal::Kind ErrorKind,
3071 SymbolRef Sym,
3072 CheckerContext &C) const {
Jordy Rose294396b2011-08-22 23:48:23 +00003073 ExplodedNode *N = C.generateSink(St);
3074 if (!N)
3075 return;
3076
Jordy Rose294396b2011-08-22 23:48:23 +00003077 CFRefBug *BT;
3078 switch (ErrorKind) {
3079 default:
3080 llvm_unreachable("Unhandled error.");
Jordy Rose294396b2011-08-22 23:48:23 +00003081 case RefVal::ErrorUseAfterRelease:
Jordy Rosed6334e12011-08-25 00:34:03 +00003082 if (!useAfterRelease)
3083 useAfterRelease.reset(new UseAfterRelease());
3084 BT = &*useAfterRelease;
Jordy Rose294396b2011-08-22 23:48:23 +00003085 break;
3086 case RefVal::ErrorReleaseNotOwned:
Jordy Rosed6334e12011-08-25 00:34:03 +00003087 if (!releaseNotOwned)
3088 releaseNotOwned.reset(new BadRelease());
3089 BT = &*releaseNotOwned;
Jordy Rose294396b2011-08-22 23:48:23 +00003090 break;
3091 case RefVal::ErrorDeallocGC:
Jordy Rosed6334e12011-08-25 00:34:03 +00003092 if (!deallocGC)
3093 deallocGC.reset(new DeallocGC());
3094 BT = &*deallocGC;
Jordy Rose294396b2011-08-22 23:48:23 +00003095 break;
3096 case RefVal::ErrorDeallocNotOwned:
Jordy Rosed6334e12011-08-25 00:34:03 +00003097 if (!deallocNotOwned)
3098 deallocNotOwned.reset(new DeallocNotOwned());
3099 BT = &*deallocNotOwned;
Jordy Rose294396b2011-08-22 23:48:23 +00003100 break;
3101 }
3102
Jordy Rosed6334e12011-08-25 00:34:03 +00003103 assert(BT);
David Blaikie4e4d0842012-03-11 07:00:24 +00003104 CFRefReport *report = new CFRefReport(*BT, C.getASTContext().getLangOpts(),
Jordy Rose17a38e22011-09-02 05:55:19 +00003105 C.isObjCGCEnabled(), SummaryLog,
3106 N, Sym);
Jordy Rose294396b2011-08-22 23:48:23 +00003107 report->addRange(ErrorRange);
3108 C.EmitReport(report);
3109}
3110
Jordy Rose910c4052011-09-02 06:44:22 +00003111//===----------------------------------------------------------------------===//
3112// Handle the return values of retain-count-related functions.
3113//===----------------------------------------------------------------------===//
3114
3115bool RetainCountChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
Jordy Rose76c506f2011-08-21 21:58:18 +00003116 // Get the callee. We're only interested in simple C functions.
Ted Kremenek8bef8232012-01-26 21:29:00 +00003117 ProgramStateRef state = C.getState();
Anna Zaksb805c8f2011-12-01 05:57:37 +00003118 const FunctionDecl *FD = C.getCalleeDecl(CE);
Jordy Rose76c506f2011-08-21 21:58:18 +00003119 if (!FD)
3120 return false;
3121
3122 IdentifierInfo *II = FD->getIdentifier();
3123 if (!II)
3124 return false;
3125
3126 // For now, we're only handling the functions that return aliases of their
3127 // arguments: CFRetain and CFMakeCollectable (and their families).
3128 // Eventually we should add other functions we can model entirely,
3129 // such as CFRelease, which don't invalidate their arguments or globals.
3130 if (CE->getNumArgs() != 1)
3131 return false;
3132
3133 // Get the name of the function.
3134 StringRef FName = II->getName();
3135 FName = FName.substr(FName.find_first_not_of('_'));
3136
3137 // See if it's one of the specific functions we know how to eval.
3138 bool canEval = false;
3139
Anna Zaksb805c8f2011-12-01 05:57:37 +00003140 QualType ResultTy = CE->getCallReturnType();
Jordy Rose76c506f2011-08-21 21:58:18 +00003141 if (ResultTy->isObjCIdType()) {
3142 // Handle: id NSMakeCollectable(CFTypeRef)
3143 canEval = II->isStr("NSMakeCollectable");
3144 } else if (ResultTy->isPointerType()) {
3145 // Handle: (CF|CG)Retain
3146 // CFMakeCollectable
3147 // It's okay to be a little sloppy here (CGMakeCollectable doesn't exist).
3148 if (cocoa::isRefType(ResultTy, "CF", FName) ||
3149 cocoa::isRefType(ResultTy, "CG", FName)) {
3150 canEval = isRetain(FD, FName) || isMakeCollectable(FD, FName);
3151 }
3152 }
3153
3154 if (!canEval)
3155 return false;
3156
3157 // Bind the return value.
Ted Kremenek5eca4822012-01-06 22:09:28 +00003158 const LocationContext *LCtx = C.getLocationContext();
3159 SVal RetVal = state->getSVal(CE->getArg(0), LCtx);
Jordy Rose76c506f2011-08-21 21:58:18 +00003160 if (RetVal.isUnknown()) {
3161 // If the receiver is unknown, conjure a return value.
3162 SValBuilder &SVB = C.getSValBuilder();
Anna Zaks5d0ea6d2011-10-04 20:43:05 +00003163 unsigned Count = C.getCurrentBlockCount();
Ted Kremenek3133f792012-02-17 23:13:45 +00003164 SVal RetVal = SVB.getConjuredSymbolVal(0, CE, LCtx, ResultTy, Count);
Jordy Rose76c506f2011-08-21 21:58:18 +00003165 }
Ted Kremenek5eca4822012-01-06 22:09:28 +00003166 state = state->BindExpr(CE, LCtx, RetVal, false);
Jordy Rose76c506f2011-08-21 21:58:18 +00003167
Jordy Rose294396b2011-08-22 23:48:23 +00003168 // FIXME: This should not be necessary, but otherwise the argument seems to be
3169 // considered alive during the next statement.
3170 if (const MemRegion *ArgRegion = RetVal.getAsRegion()) {
3171 // Save the refcount status of the argument.
3172 SymbolRef Sym = RetVal.getAsLocSymbol();
3173 RefBindings::data_type *Binding = 0;
3174 if (Sym)
3175 Binding = state->get<RefBindings>(Sym);
Jordy Rose76c506f2011-08-21 21:58:18 +00003176
Jordy Rose294396b2011-08-22 23:48:23 +00003177 // Invalidate the argument region.
Anna Zaks5d0ea6d2011-10-04 20:43:05 +00003178 unsigned Count = C.getCurrentBlockCount();
Ted Kremenek3133f792012-02-17 23:13:45 +00003179 state = state->invalidateRegions(ArgRegion, CE, Count, LCtx);
Jordy Rose76c506f2011-08-21 21:58:18 +00003180
Jordy Rose294396b2011-08-22 23:48:23 +00003181 // Restore the refcount status of the argument.
3182 if (Binding)
3183 state = state->set<RefBindings>(Sym, *Binding);
3184 }
3185
Anna Zaks0bd6b112011-10-26 21:06:34 +00003186 C.addTransition(state);
Jordy Rose76c506f2011-08-21 21:58:18 +00003187 return true;
3188}
3189
Jordy Rose910c4052011-09-02 06:44:22 +00003190//===----------------------------------------------------------------------===//
3191// Handle return statements.
3192//===----------------------------------------------------------------------===//
Jordy Rosef53e8c72011-08-23 19:43:16 +00003193
Ted Kremeneke5715782012-02-25 02:09:09 +00003194// Return true if the current LocationContext has no caller context.
3195static bool inTopFrame(CheckerContext &C) {
3196 const LocationContext *LC = C.getLocationContext();
3197 return LC->getParent() == 0;
3198}
3199
Jordy Rose910c4052011-09-02 06:44:22 +00003200void RetainCountChecker::checkPreStmt(const ReturnStmt *S,
3201 CheckerContext &C) const {
Ted Kremeneke5715782012-02-25 02:09:09 +00003202
3203 // Only adjust the reference count if this is the top-level call frame,
3204 // and not the result of inlining. In the future, we should do
3205 // better checking even for inlined calls, and see if they match
3206 // with their expected semantics (e.g., the method should return a retained
3207 // object, etc.).
3208 if (!inTopFrame(C))
3209 return;
3210
Jordy Rosef53e8c72011-08-23 19:43:16 +00003211 const Expr *RetE = S->getRetValue();
3212 if (!RetE)
3213 return;
3214
Ted Kremenek8bef8232012-01-26 21:29:00 +00003215 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00003216 SymbolRef Sym =
3217 state->getSValAsScalarOrLoc(RetE, C.getLocationContext()).getAsLocSymbol();
Jordy Rosef53e8c72011-08-23 19:43:16 +00003218 if (!Sym)
3219 return;
3220
3221 // Get the reference count binding (if any).
3222 const RefVal *T = state->get<RefBindings>(Sym);
3223 if (!T)
3224 return;
3225
3226 // Change the reference count.
3227 RefVal X = *T;
3228
3229 switch (X.getKind()) {
3230 case RefVal::Owned: {
3231 unsigned cnt = X.getCount();
3232 assert(cnt > 0);
3233 X.setCount(cnt - 1);
3234 X = X ^ RefVal::ReturnedOwned;
3235 break;
3236 }
3237
3238 case RefVal::NotOwned: {
3239 unsigned cnt = X.getCount();
3240 if (cnt) {
3241 X.setCount(cnt - 1);
3242 X = X ^ RefVal::ReturnedOwned;
3243 }
3244 else {
3245 X = X ^ RefVal::ReturnedNotOwned;
3246 }
3247 break;
3248 }
3249
3250 default:
3251 return;
3252 }
3253
3254 // Update the binding.
3255 state = state->set<RefBindings>(Sym, X);
Anna Zaks0bd6b112011-10-26 21:06:34 +00003256 ExplodedNode *Pred = C.addTransition(state);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003257
3258 // At this point we have updated the state properly.
3259 // Everything after this is merely checking to see if the return value has
3260 // been over- or under-retained.
3261
3262 // Did we cache out?
3263 if (!Pred)
3264 return;
3265
Jordy Rosef53e8c72011-08-23 19:43:16 +00003266 // Update the autorelease counts.
3267 static SimpleProgramPointTag
Jordy Rose910c4052011-09-02 06:44:22 +00003268 AutoreleaseTag("RetainCountChecker : Autorelease");
Anna Zaks4eff8232011-10-05 23:44:11 +00003269 GenericNodeBuilderRefCount Bd(C, &AutoreleaseTag);
Anna Zaks6a93bd52011-10-25 19:57:11 +00003270 llvm::tie(Pred, state) = handleAutoreleaseCounts(state, Bd, Pred, C, Sym, X);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003271
3272 // Did we cache out?
Jordy Rose8d228632011-08-23 20:07:14 +00003273 if (!Pred)
Jordy Rosef53e8c72011-08-23 19:43:16 +00003274 return;
3275
3276 // Get the updated binding.
3277 T = state->get<RefBindings>(Sym);
3278 assert(T);
3279 X = *T;
3280
3281 // Consult the summary of the enclosing method.
Jordy Rose17a38e22011-09-02 05:55:19 +00003282 RetainSummaryManager &Summaries = getSummaryManager(C);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003283 const Decl *CD = &Pred->getCodeDecl();
Jordan Rose4531b7d2012-07-02 19:27:43 +00003284 RetEffect RE = RetEffect::MakeNoRet();
Jordy Rosef53e8c72011-08-23 19:43:16 +00003285
Jordan Rose4531b7d2012-07-02 19:27:43 +00003286 // FIXME: What is the convention for blocks? Is there one?
Jordy Rosef53e8c72011-08-23 19:43:16 +00003287 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CD)) {
Jordy Roseb6cfc092011-08-25 00:10:37 +00003288 const RetainSummary *Summ = Summaries.getMethodSummary(MD);
Jordan Rose4531b7d2012-07-02 19:27:43 +00003289 RE = Summ->getRetEffect();
3290 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) {
3291 if (!isa<CXXMethodDecl>(FD)) {
3292 const RetainSummary *Summ = Summaries.getFunctionSummary(FD);
3293 RE = Summ->getRetEffect();
3294 }
Jordy Rosef53e8c72011-08-23 19:43:16 +00003295 }
3296
Jordan Rose4531b7d2012-07-02 19:27:43 +00003297 checkReturnWithRetEffect(S, C, Pred, RE, X, Sym, state);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003298}
3299
Jordy Rose910c4052011-09-02 06:44:22 +00003300void RetainCountChecker::checkReturnWithRetEffect(const ReturnStmt *S,
3301 CheckerContext &C,
3302 ExplodedNode *Pred,
3303 RetEffect RE, RefVal X,
3304 SymbolRef Sym,
Ted Kremenek8bef8232012-01-26 21:29:00 +00003305 ProgramStateRef state) const {
Jordy Rosef53e8c72011-08-23 19:43:16 +00003306 // Any leaks or other errors?
3307 if (X.isReturnedOwned() && X.getCount() == 0) {
3308 if (RE.getKind() != RetEffect::NoRet) {
3309 bool hasError = false;
Jordy Rose17a38e22011-09-02 05:55:19 +00003310 if (C.isObjCGCEnabled() && RE.getObjKind() == RetEffect::ObjC) {
Jordy Rosef53e8c72011-08-23 19:43:16 +00003311 // Things are more complicated with garbage collection. If the
3312 // returned object is suppose to be an Objective-C object, we have
3313 // a leak (as the caller expects a GC'ed object) because no
3314 // method should return ownership unless it returns a CF object.
3315 hasError = true;
3316 X = X ^ RefVal::ErrorGCLeakReturned;
3317 }
3318 else if (!RE.isOwned()) {
3319 // Either we are using GC and the returned object is a CF type
3320 // or we aren't using GC. In either case, we expect that the
3321 // enclosing method is expected to return ownership.
3322 hasError = true;
3323 X = X ^ RefVal::ErrorLeakReturned;
3324 }
3325
3326 if (hasError) {
3327 // Generate an error node.
3328 state = state->set<RefBindings>(Sym, X);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003329
3330 static SimpleProgramPointTag
Jordy Rose910c4052011-09-02 06:44:22 +00003331 ReturnOwnLeakTag("RetainCountChecker : ReturnsOwnLeak");
Anna Zaks0bd6b112011-10-26 21:06:34 +00003332 ExplodedNode *N = C.addTransition(state, Pred, &ReturnOwnLeakTag);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003333 if (N) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003334 const LangOptions &LOpts = C.getASTContext().getLangOpts();
Jordy Rose17a38e22011-09-02 05:55:19 +00003335 bool GCEnabled = C.isObjCGCEnabled();
Jordy Rosef53e8c72011-08-23 19:43:16 +00003336 CFRefReport *report =
Jordy Rose17a38e22011-09-02 05:55:19 +00003337 new CFRefLeakReport(*getLeakAtReturnBug(LOpts, GCEnabled),
3338 LOpts, GCEnabled, SummaryLog,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003339 N, Sym, C);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003340 C.EmitReport(report);
3341 }
3342 }
3343 }
3344 } else if (X.isReturnedNotOwned()) {
3345 if (RE.isOwned()) {
3346 // Trying to return a not owned object to a caller expecting an
3347 // owned object.
3348 state = state->set<RefBindings>(Sym, X ^ RefVal::ErrorReturnedNotOwned);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003349
3350 static SimpleProgramPointTag
Jordy Rose910c4052011-09-02 06:44:22 +00003351 ReturnNotOwnedTag("RetainCountChecker : ReturnNotOwnedForOwned");
Anna Zaks0bd6b112011-10-26 21:06:34 +00003352 ExplodedNode *N = C.addTransition(state, Pred, &ReturnNotOwnedTag);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003353 if (N) {
Jordy Rosed6334e12011-08-25 00:34:03 +00003354 if (!returnNotOwnedForOwned)
3355 returnNotOwnedForOwned.reset(new ReturnedNotOwnedForOwned());
3356
Jordy Rosef53e8c72011-08-23 19:43:16 +00003357 CFRefReport *report =
Jordy Rosed6334e12011-08-25 00:34:03 +00003358 new CFRefReport(*returnNotOwnedForOwned,
David Blaikie4e4d0842012-03-11 07:00:24 +00003359 C.getASTContext().getLangOpts(),
Jordy Rose17a38e22011-09-02 05:55:19 +00003360 C.isObjCGCEnabled(), SummaryLog, N, Sym);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003361 C.EmitReport(report);
3362 }
3363 }
3364 }
3365}
3366
Jordy Rose8d228632011-08-23 20:07:14 +00003367//===----------------------------------------------------------------------===//
Jordy Rose910c4052011-09-02 06:44:22 +00003368// Check various ways a symbol can be invalidated.
3369//===----------------------------------------------------------------------===//
3370
Anna Zaks390909c2011-10-06 00:43:15 +00003371void RetainCountChecker::checkBind(SVal loc, SVal val, const Stmt *S,
Jordy Rose910c4052011-09-02 06:44:22 +00003372 CheckerContext &C) const {
3373 // Are we storing to something that causes the value to "escape"?
3374 bool escapes = true;
3375
3376 // A value escapes in three possible cases (this may change):
3377 //
3378 // (1) we are binding to something that is not a memory region.
3379 // (2) we are binding to a memregion that does not have stack storage
3380 // (3) we are binding to a memregion with stack storage that the store
3381 // does not understand.
Ted Kremenek8bef8232012-01-26 21:29:00 +00003382 ProgramStateRef state = C.getState();
Jordy Rose910c4052011-09-02 06:44:22 +00003383
3384 if (loc::MemRegionVal *regionLoc = dyn_cast<loc::MemRegionVal>(&loc)) {
3385 escapes = !regionLoc->getRegion()->hasStackStorage();
3386
3387 if (!escapes) {
3388 // To test (3), generate a new state with the binding added. If it is
3389 // the same state, then it escapes (since the store cannot represent
3390 // the binding).
Anna Zakse7958da2012-05-02 00:15:40 +00003391 // Do this only if we know that the store is not supposed to generate the
3392 // same state.
3393 SVal StoredVal = state->getSVal(regionLoc->getRegion());
3394 if (StoredVal != val)
3395 escapes = (state == (state->bindLoc(*regionLoc, val)));
Jordy Rose910c4052011-09-02 06:44:22 +00003396 }
Ted Kremenekde5b4fb2012-03-27 01:12:45 +00003397 if (!escapes) {
3398 // Case 4: We do not currently model what happens when a symbol is
3399 // assigned to a struct field, so be conservative here and let the symbol
3400 // go. TODO: This could definitely be improved upon.
3401 escapes = !isa<VarRegion>(regionLoc->getRegion());
3402 }
Jordy Rose910c4052011-09-02 06:44:22 +00003403 }
3404
3405 // If our store can represent the binding and we aren't storing to something
3406 // that doesn't have local storage then just return and have the simulation
3407 // state continue as is.
3408 if (!escapes)
3409 return;
3410
3411 // Otherwise, find all symbols referenced by 'val' that we are tracking
3412 // and stop tracking them.
3413 state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
Anna Zaks0bd6b112011-10-26 21:06:34 +00003414 C.addTransition(state);
Jordy Rose910c4052011-09-02 06:44:22 +00003415}
3416
Ted Kremenek8bef8232012-01-26 21:29:00 +00003417ProgramStateRef RetainCountChecker::evalAssume(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003418 SVal Cond,
3419 bool Assumption) const {
3420
3421 // FIXME: We may add to the interface of evalAssume the list of symbols
3422 // whose assumptions have changed. For now we just iterate through the
3423 // bindings and check if any of the tracked symbols are NULL. This isn't
3424 // too bad since the number of symbols we will track in practice are
3425 // probably small and evalAssume is only called at branches and a few
3426 // other places.
3427 RefBindings B = state->get<RefBindings>();
3428
3429 if (B.isEmpty())
3430 return state;
3431
3432 bool changed = false;
3433 RefBindings::Factory &RefBFactory = state->get_context<RefBindings>();
3434
3435 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
3436 // Check if the symbol is null (or equal to any constant).
3437 // If this is the case, stop tracking the symbol.
3438 if (state->getSymVal(I.getKey())) {
3439 changed = true;
3440 B = RefBFactory.remove(B, I.getKey());
3441 }
3442 }
3443
3444 if (changed)
3445 state = state->set<RefBindings>(B);
3446
3447 return state;
3448}
3449
Ted Kremenek8bef8232012-01-26 21:29:00 +00003450ProgramStateRef
3451RetainCountChecker::checkRegionChanges(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003452 const StoreManager::InvalidatedSymbols *invalidated,
3453 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00003454 ArrayRef<const MemRegion *> Regions,
Jordan Rose740d4902012-07-02 19:27:35 +00003455 const CallEvent *Call) const {
Jordy Rose910c4052011-09-02 06:44:22 +00003456 if (!invalidated)
3457 return state;
3458
3459 llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
3460 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
3461 E = ExplicitRegions.end(); I != E; ++I) {
3462 if (const SymbolicRegion *SR = (*I)->StripCasts()->getAs<SymbolicRegion>())
3463 WhitelistedSymbols.insert(SR->getSymbol());
3464 }
3465
3466 for (StoreManager::InvalidatedSymbols::const_iterator I=invalidated->begin(),
3467 E = invalidated->end(); I!=E; ++I) {
3468 SymbolRef sym = *I;
3469 if (WhitelistedSymbols.count(sym))
3470 continue;
3471 // Remove any existing reference-count binding.
3472 state = state->remove<RefBindings>(sym);
3473 }
3474 return state;
3475}
3476
3477//===----------------------------------------------------------------------===//
Jordy Rose8d228632011-08-23 20:07:14 +00003478// Handle dead symbols and end-of-path.
3479//===----------------------------------------------------------------------===//
3480
Ted Kremenek8bef8232012-01-26 21:29:00 +00003481std::pair<ExplodedNode *, ProgramStateRef >
3482RetainCountChecker::handleAutoreleaseCounts(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003483 GenericNodeBuilderRefCount Bd,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003484 ExplodedNode *Pred,
3485 CheckerContext &Ctx,
Jordy Rose910c4052011-09-02 06:44:22 +00003486 SymbolRef Sym, RefVal V) const {
Jordy Rose8d228632011-08-23 20:07:14 +00003487 unsigned ACnt = V.getAutoreleaseCount();
3488
3489 // No autorelease counts? Nothing to be done.
3490 if (!ACnt)
3491 return std::make_pair(Pred, state);
3492
Anna Zaks6a93bd52011-10-25 19:57:11 +00003493 assert(!Ctx.isObjCGCEnabled() && "Autorelease counts in GC mode?");
Jordy Rose8d228632011-08-23 20:07:14 +00003494 unsigned Cnt = V.getCount();
3495
3496 // FIXME: Handle sending 'autorelease' to already released object.
3497
3498 if (V.getKind() == RefVal::ReturnedOwned)
3499 ++Cnt;
3500
3501 if (ACnt <= Cnt) {
3502 if (ACnt == Cnt) {
3503 V.clearCounts();
3504 if (V.getKind() == RefVal::ReturnedOwned)
3505 V = V ^ RefVal::ReturnedNotOwned;
3506 else
3507 V = V ^ RefVal::NotOwned;
3508 } else {
3509 V.setCount(Cnt - ACnt);
3510 V.setAutoreleaseCount(0);
3511 }
3512 state = state->set<RefBindings>(Sym, V);
3513 ExplodedNode *N = Bd.MakeNode(state, Pred);
3514 if (N == 0)
3515 state = 0;
3516 return std::make_pair(N, state);
3517 }
3518
3519 // Woah! More autorelease counts then retain counts left.
3520 // Emit hard error.
3521 V = V ^ RefVal::ErrorOverAutorelease;
3522 state = state->set<RefBindings>(Sym, V);
3523
Anna Zaksf05aac82011-10-18 23:05:58 +00003524 if (ExplodedNode *N = Bd.MakeNode(state, Pred, true)) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003525 SmallString<128> sbuf;
Jordy Rose8d228632011-08-23 20:07:14 +00003526 llvm::raw_svector_ostream os(sbuf);
3527 os << "Object over-autoreleased: object was sent -autorelease ";
3528 if (V.getAutoreleaseCount() > 1)
3529 os << V.getAutoreleaseCount() << " times ";
3530 os << "but the object has a +" << V.getCount() << " retain count";
3531
Jordy Rosed6334e12011-08-25 00:34:03 +00003532 if (!overAutorelease)
3533 overAutorelease.reset(new OverAutorelease());
3534
David Blaikie4e4d0842012-03-11 07:00:24 +00003535 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
Jordy Rose8d228632011-08-23 20:07:14 +00003536 CFRefReport *report =
Jordy Rosed6334e12011-08-25 00:34:03 +00003537 new CFRefReport(*overAutorelease, LOpts, /* GCEnabled = */ false,
3538 SummaryLog, N, Sym, os.str());
Anna Zaks6a93bd52011-10-25 19:57:11 +00003539 Ctx.EmitReport(report);
Jordy Rose8d228632011-08-23 20:07:14 +00003540 }
3541
Ted Kremenek8bef8232012-01-26 21:29:00 +00003542 return std::make_pair((ExplodedNode *)0, (ProgramStateRef )0);
Jordy Rose8d228632011-08-23 20:07:14 +00003543}
Jordy Rose38f17d62011-08-23 19:01:07 +00003544
Ted Kremenek8bef8232012-01-26 21:29:00 +00003545ProgramStateRef
3546RetainCountChecker::handleSymbolDeath(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003547 SymbolRef sid, RefVal V,
Jordy Rose38f17d62011-08-23 19:01:07 +00003548 SmallVectorImpl<SymbolRef> &Leaked) const {
Jordy Rose53376122011-08-24 04:48:19 +00003549 bool hasLeak = false;
Jordy Rose38f17d62011-08-23 19:01:07 +00003550 if (V.isOwned())
3551 hasLeak = true;
3552 else if (V.isNotOwned() || V.isReturnedOwned())
3553 hasLeak = (V.getCount() > 0);
3554
3555 if (!hasLeak)
3556 return state->remove<RefBindings>(sid);
3557
3558 Leaked.push_back(sid);
3559 return state->set<RefBindings>(sid, V ^ RefVal::ErrorLeak);
3560}
3561
3562ExplodedNode *
Ted Kremenek8bef8232012-01-26 21:29:00 +00003563RetainCountChecker::processLeaks(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003564 SmallVectorImpl<SymbolRef> &Leaked,
3565 GenericNodeBuilderRefCount &Builder,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003566 CheckerContext &Ctx,
3567 ExplodedNode *Pred) const {
Jordy Rose38f17d62011-08-23 19:01:07 +00003568 if (Leaked.empty())
3569 return Pred;
3570
3571 // Generate an intermediate node representing the leak point.
3572 ExplodedNode *N = Builder.MakeNode(state, Pred);
3573
3574 if (N) {
3575 for (SmallVectorImpl<SymbolRef>::iterator
3576 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3577
David Blaikie4e4d0842012-03-11 07:00:24 +00003578 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
Anna Zaks6a93bd52011-10-25 19:57:11 +00003579 bool GCEnabled = Ctx.isObjCGCEnabled();
Jordy Rose17a38e22011-09-02 05:55:19 +00003580 CFRefBug *BT = Pred ? getLeakWithinFunctionBug(LOpts, GCEnabled)
3581 : getLeakAtReturnBug(LOpts, GCEnabled);
Jordy Rose38f17d62011-08-23 19:01:07 +00003582 assert(BT && "BugType not initialized.");
Jordy Rose20589562011-08-24 22:39:09 +00003583
Jordy Rose17a38e22011-09-02 05:55:19 +00003584 CFRefLeakReport *report = new CFRefLeakReport(*BT, LOpts, GCEnabled,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003585 SummaryLog, N, *I, Ctx);
3586 Ctx.EmitReport(report);
Jordy Rose38f17d62011-08-23 19:01:07 +00003587 }
3588 }
3589
3590 return N;
3591}
3592
Anna Zaksaf498a22011-10-25 19:56:48 +00003593void RetainCountChecker::checkEndPath(CheckerContext &Ctx) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +00003594 ProgramStateRef state = Ctx.getState();
Anna Zaksaf498a22011-10-25 19:56:48 +00003595 GenericNodeBuilderRefCount Bd(Ctx);
Jordy Rose38f17d62011-08-23 19:01:07 +00003596 RefBindings B = state->get<RefBindings>();
Anna Zaksaf498a22011-10-25 19:56:48 +00003597 ExplodedNode *Pred = Ctx.getPredecessor();
Jordy Rose38f17d62011-08-23 19:01:07 +00003598
3599 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Anna Zaks6a93bd52011-10-25 19:57:11 +00003600 llvm::tie(Pred, state) = handleAutoreleaseCounts(state, Bd, Pred, Ctx,
Jordy Rose8d228632011-08-23 20:07:14 +00003601 I->first, I->second);
3602 if (!state)
Jordy Rose38f17d62011-08-23 19:01:07 +00003603 return;
3604 }
3605
Ted Kremenek0cf3d472012-02-07 00:24:33 +00003606 // If the current LocationContext has a parent, don't check for leaks.
3607 // We will do that later.
3608 // FIXME: we should instead check for imblances of the retain/releases,
3609 // and suggest annotations.
3610 if (Ctx.getLocationContext()->getParent())
3611 return;
3612
Jordy Rose38f17d62011-08-23 19:01:07 +00003613 B = state->get<RefBindings>();
3614 SmallVector<SymbolRef, 10> Leaked;
3615
3616 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I)
Jordy Rose8d228632011-08-23 20:07:14 +00003617 state = handleSymbolDeath(state, I->first, I->second, Leaked);
Jordy Rose38f17d62011-08-23 19:01:07 +00003618
Anna Zaks6a93bd52011-10-25 19:57:11 +00003619 processLeaks(state, Leaked, Bd, Ctx, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003620}
3621
3622const ProgramPointTag *
Jordy Rose910c4052011-09-02 06:44:22 +00003623RetainCountChecker::getDeadSymbolTag(SymbolRef sym) const {
Jordy Rose38f17d62011-08-23 19:01:07 +00003624 const SimpleProgramPointTag *&tag = DeadSymbolTags[sym];
3625 if (!tag) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003626 SmallString<64> buf;
Jordy Rose38f17d62011-08-23 19:01:07 +00003627 llvm::raw_svector_ostream out(buf);
Anna Zaksf62ceec2011-12-05 18:58:11 +00003628 out << "RetainCountChecker : Dead Symbol : ";
3629 sym->dumpToStream(out);
Jordy Rose38f17d62011-08-23 19:01:07 +00003630 tag = new SimpleProgramPointTag(out.str());
3631 }
3632 return tag;
3633}
3634
Jordy Rose910c4052011-09-02 06:44:22 +00003635void RetainCountChecker::checkDeadSymbols(SymbolReaper &SymReaper,
3636 CheckerContext &C) const {
Jordy Rose38f17d62011-08-23 19:01:07 +00003637 ExplodedNode *Pred = C.getPredecessor();
3638
Ted Kremenek8bef8232012-01-26 21:29:00 +00003639 ProgramStateRef state = C.getState();
Jordy Rose38f17d62011-08-23 19:01:07 +00003640 RefBindings B = state->get<RefBindings>();
3641
3642 // Update counts from autorelease pools
3643 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3644 E = SymReaper.dead_end(); I != E; ++I) {
3645 SymbolRef Sym = *I;
3646 if (const RefVal *T = B.lookup(Sym)){
3647 // Use the symbol as the tag.
3648 // FIXME: This might not be as unique as we would like.
Anna Zaks4eff8232011-10-05 23:44:11 +00003649 GenericNodeBuilderRefCount Bd(C, getDeadSymbolTag(Sym));
Anna Zaks6a93bd52011-10-25 19:57:11 +00003650 llvm::tie(Pred, state) = handleAutoreleaseCounts(state, Bd, Pred, C,
Jordy Rose8d228632011-08-23 20:07:14 +00003651 Sym, *T);
3652 if (!state)
Jordy Rose38f17d62011-08-23 19:01:07 +00003653 return;
3654 }
3655 }
3656
3657 B = state->get<RefBindings>();
3658 SmallVector<SymbolRef, 10> Leaked;
3659
3660 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3661 E = SymReaper.dead_end(); I != E; ++I) {
3662 if (const RefVal *T = B.lookup(*I))
3663 state = handleSymbolDeath(state, *I, *T, Leaked);
3664 }
3665
3666 {
Anna Zaks4eff8232011-10-05 23:44:11 +00003667 GenericNodeBuilderRefCount Bd(C, this);
Anna Zaks6a93bd52011-10-25 19:57:11 +00003668 Pred = processLeaks(state, Leaked, Bd, C, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003669 }
3670
3671 // Did we cache out?
3672 if (!Pred)
3673 return;
3674
3675 // Now generate a new node that nukes the old bindings.
3676 RefBindings::Factory &F = state->get_context<RefBindings>();
3677
3678 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3679 E = SymReaper.dead_end(); I != E; ++I)
3680 B = F.remove(B, *I);
3681
3682 state = state->set<RefBindings>(B);
Anna Zaks0bd6b112011-10-26 21:06:34 +00003683 C.addTransition(state, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003684}
3685
Ted Kremenekd593eb92009-11-25 22:17:44 +00003686//===----------------------------------------------------------------------===//
Jordy Rosedbd658e2011-08-28 19:11:56 +00003687// Debug printing of refcount bindings and autorelease pools.
3688//===----------------------------------------------------------------------===//
3689
3690static void PrintPool(raw_ostream &Out, SymbolRef Sym,
Ted Kremenek8bef8232012-01-26 21:29:00 +00003691 ProgramStateRef State) {
Jordy Rosedbd658e2011-08-28 19:11:56 +00003692 Out << ' ';
3693 if (Sym)
Anna Zaksf62ceec2011-12-05 18:58:11 +00003694 Sym->dumpToStream(Out);
Jordy Rosedbd658e2011-08-28 19:11:56 +00003695 else
3696 Out << "<pool>";
3697 Out << ":{";
3698
3699 // Get the contents of the pool.
3700 if (const ARCounts *Cnts = State->get<AutoreleasePoolContents>(Sym))
3701 for (ARCounts::iterator I = Cnts->begin(), E = Cnts->end(); I != E; ++I)
3702 Out << '(' << I.getKey() << ',' << I.getData() << ')';
3703
3704 Out << '}';
3705}
3706
Ted Kremenek8bef8232012-01-26 21:29:00 +00003707static bool UsesAutorelease(ProgramStateRef state) {
Jordy Rosedbd658e2011-08-28 19:11:56 +00003708 // A state uses autorelease if it allocated an autorelease pool or if it has
3709 // objects in the caller's autorelease pool.
3710 return !state->get<AutoreleaseStack>().isEmpty() ||
3711 state->get<AutoreleasePoolContents>(SymbolRef());
3712}
3713
Ted Kremenek8bef8232012-01-26 21:29:00 +00003714void RetainCountChecker::printState(raw_ostream &Out, ProgramStateRef State,
Jordy Rose910c4052011-09-02 06:44:22 +00003715 const char *NL, const char *Sep) const {
Jordy Rosedbd658e2011-08-28 19:11:56 +00003716
3717 RefBindings B = State->get<RefBindings>();
3718
3719 if (!B.isEmpty())
3720 Out << Sep << NL;
3721
3722 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
3723 Out << I->first << " : ";
3724 I->second.print(Out);
3725 Out << NL;
3726 }
3727
3728 // Print the autorelease stack.
3729 if (UsesAutorelease(State)) {
3730 Out << Sep << NL << "AR pool stack:";
3731 ARStack Stack = State->get<AutoreleaseStack>();
3732
3733 PrintPool(Out, SymbolRef(), State); // Print the caller's pool.
3734 for (ARStack::iterator I = Stack.begin(), E = Stack.end(); I != E; ++I)
3735 PrintPool(Out, *I, State);
3736
3737 Out << NL;
3738 }
3739}
3740
3741//===----------------------------------------------------------------------===//
Jordy Rose910c4052011-09-02 06:44:22 +00003742// Checker registration.
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00003743//===----------------------------------------------------------------------===//
3744
Jordy Rose17a38e22011-09-02 05:55:19 +00003745void ento::registerRetainCountChecker(CheckerManager &Mgr) {
Jordy Rose910c4052011-09-02 06:44:22 +00003746 Mgr.registerChecker<RetainCountChecker>();
Jordy Rose17a38e22011-09-02 05:55:19 +00003747}
3748