blob: 0896782265ee5f827a395bc2d005d6d52908484c [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 Rosef540c542012-07-26 21:39:41 +000026#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.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
Anna Zaks8d6b43c2012-08-14 00:36:15 +0000355static inline const RefVal *getRefBinding(ProgramStateRef State,
356 SymbolRef Sym) {
357 return State->get<RefBindings>(Sym);
358}
359
360static inline ProgramStateRef setRefBinding(ProgramStateRef State,
361 SymbolRef Sym, RefVal Val) {
362 return State->set<RefBindings>(Sym, Val);
363}
364
365static ProgramStateRef removeRefBinding(ProgramStateRef State, SymbolRef Sym) {
366 return State->remove<RefBindings>(Sym);
367}
368
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000369//===----------------------------------------------------------------------===//
Jordy Rose910c4052011-09-02 06:44:22 +0000370// Function/Method behavior summaries.
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000371//===----------------------------------------------------------------------===//
372
373namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000374class RetainSummary {
Jordy Roseef945882012-03-18 01:26:10 +0000375 /// Args - a map of (index, ArgEffect) pairs, where index
Ted Kremenek1bffd742008-05-06 15:44:25 +0000376 /// specifies the argument (starting from 0). This can be sparsely
377 /// populated; arguments with no entry in Args use 'DefaultArgEffect'.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000378 ArgEffects Args;
Mike Stump1eb44332009-09-09 15:08:12 +0000379
Ted Kremenek1bffd742008-05-06 15:44:25 +0000380 /// DefaultArgEffect - The default ArgEffect to apply to arguments that
381 /// do not have an entry in Args.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000382 ArgEffect DefaultArgEffect;
Mike Stump1eb44332009-09-09 15:08:12 +0000383
Ted Kremenek553cf182008-06-25 21:21:56 +0000384 /// Receiver - If this summary applies to an Objective-C message expression,
385 /// this is the effect applied to the state of the receiver.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000386 ArgEffect Receiver;
Mike Stump1eb44332009-09-09 15:08:12 +0000387
Ted Kremenek553cf182008-06-25 21:21:56 +0000388 /// Ret - The effect on the return value. Used to indicate if the
Jordy Rose76c506f2011-08-21 21:58:18 +0000389 /// function/method call returns a new tracked symbol.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000390 RetEffect Ret;
Mike Stump1eb44332009-09-09 15:08:12 +0000391
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000392public:
Ted Kremenekb77449c2009-05-03 05:20:50 +0000393 RetainSummary(ArgEffects A, RetEffect R, ArgEffect defaultEff,
Jordy Rosee62e87b2011-08-20 20:55:40 +0000394 ArgEffect ReceiverEff)
395 : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000396
Ted Kremenek553cf182008-06-25 21:21:56 +0000397 /// getArg - Return the argument effect on the argument specified by
398 /// idx (starting from 0).
Ted Kremenek1ac08d62008-03-11 17:48:22 +0000399 ArgEffect getArg(unsigned idx) const {
Ted Kremenekb77449c2009-05-03 05:20:50 +0000400 if (const ArgEffect *AE = Args.lookup(idx))
401 return *AE;
Mike Stump1eb44332009-09-09 15:08:12 +0000402
Ted Kremenek1bffd742008-05-06 15:44:25 +0000403 return DefaultArgEffect;
Ted Kremenek1ac08d62008-03-11 17:48:22 +0000404 }
Ted Kremenek11fe1752011-01-27 18:43:03 +0000405
406 void addArg(ArgEffects::Factory &af, unsigned idx, ArgEffect e) {
407 Args = af.add(Args, idx, e);
408 }
Mike Stump1eb44332009-09-09 15:08:12 +0000409
Ted Kremenek885c27b2009-05-04 05:31:22 +0000410 /// setDefaultArgEffect - Set the default argument effect.
411 void setDefaultArgEffect(ArgEffect E) {
412 DefaultArgEffect = E;
413 }
Mike Stump1eb44332009-09-09 15:08:12 +0000414
Ted Kremenek553cf182008-06-25 21:21:56 +0000415 /// getRetEffect - Returns the effect on the return value of the call.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000416 RetEffect getRetEffect() const { return Ret; }
Mike Stump1eb44332009-09-09 15:08:12 +0000417
Ted Kremenek885c27b2009-05-04 05:31:22 +0000418 /// setRetEffect - Set the effect of the return value of the call.
419 void setRetEffect(RetEffect E) { Ret = E; }
Mike Stump1eb44332009-09-09 15:08:12 +0000420
Ted Kremenek12b94342011-01-27 06:54:14 +0000421
422 /// Sets the effect on the receiver of the message.
423 void setReceiverEffect(ArgEffect e) { Receiver = e; }
424
Ted Kremenek553cf182008-06-25 21:21:56 +0000425 /// getReceiverEffect - Returns the effect on the receiver of the call.
426 /// This is only meaningful if the summary applies to an ObjCMessageExpr*.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000427 ArgEffect getReceiverEffect() const { return Receiver; }
Jordy Rose4df54fe2011-08-23 04:27:15 +0000428
429 /// Test if two retain summaries are identical. Note that merely equivalent
430 /// summaries are not necessarily identical (for example, if an explicit
431 /// argument effect matches the default effect).
432 bool operator==(const RetainSummary &Other) const {
433 return Args == Other.Args && DefaultArgEffect == Other.DefaultArgEffect &&
434 Receiver == Other.Receiver && Ret == Other.Ret;
435 }
Jordy Roseef945882012-03-18 01:26:10 +0000436
437 /// Profile this summary for inclusion in a FoldingSet.
438 void Profile(llvm::FoldingSetNodeID& ID) const {
439 ID.Add(Args);
440 ID.Add(DefaultArgEffect);
441 ID.Add(Receiver);
442 ID.Add(Ret);
443 }
444
445 /// A retain summary is simple if it has no ArgEffects other than the default.
446 bool isSimple() const {
447 return Args.isEmpty();
448 }
Jordan Rose4531b7d2012-07-02 19:27:43 +0000449
450private:
451 ArgEffects getArgEffects() const { return Args; }
452 ArgEffect getDefaultArgEffect() const { return DefaultArgEffect; }
453
454 friend class RetainSummaryManager;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000455};
Ted Kremenek4f22a782008-06-23 23:30:29 +0000456} // end anonymous namespace
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000457
Ted Kremenek553cf182008-06-25 21:21:56 +0000458//===----------------------------------------------------------------------===//
459// Data structures for constructing summaries.
460//===----------------------------------------------------------------------===//
Ted Kremenek53301ba2008-06-24 03:49:48 +0000461
Ted Kremenek553cf182008-06-25 21:21:56 +0000462namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000463class ObjCSummaryKey {
Ted Kremenek553cf182008-06-25 21:21:56 +0000464 IdentifierInfo* II;
465 Selector S;
Mike Stump1eb44332009-09-09 15:08:12 +0000466public:
Ted Kremenek553cf182008-06-25 21:21:56 +0000467 ObjCSummaryKey(IdentifierInfo* ii, Selector s)
468 : II(ii), S(s) {}
469
Ted Kremenek9c378f72011-08-12 23:37:29 +0000470 ObjCSummaryKey(const ObjCInterfaceDecl *d, Selector s)
Ted Kremenek553cf182008-06-25 21:21:56 +0000471 : II(d ? d->getIdentifier() : 0), S(s) {}
Ted Kremenek70b6a832009-05-13 18:16:01 +0000472
Ted Kremenek553cf182008-06-25 21:21:56 +0000473 ObjCSummaryKey(Selector s)
474 : II(0), S(s) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000475
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000476 IdentifierInfo *getIdentifier() const { return II; }
Ted Kremenek553cf182008-06-25 21:21:56 +0000477 Selector getSelector() const { return S; }
478};
Ted Kremenek4f22a782008-06-23 23:30:29 +0000479}
480
481namespace llvm {
Ted Kremenek553cf182008-06-25 21:21:56 +0000482template <> struct DenseMapInfo<ObjCSummaryKey> {
483 static inline ObjCSummaryKey getEmptyKey() {
484 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
485 DenseMapInfo<Selector>::getEmptyKey());
486 }
Mike Stump1eb44332009-09-09 15:08:12 +0000487
Ted Kremenek553cf182008-06-25 21:21:56 +0000488 static inline ObjCSummaryKey getTombstoneKey() {
489 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
Mike Stump1eb44332009-09-09 15:08:12 +0000490 DenseMapInfo<Selector>::getTombstoneKey());
Ted Kremenek553cf182008-06-25 21:21:56 +0000491 }
Mike Stump1eb44332009-09-09 15:08:12 +0000492
Ted Kremenek553cf182008-06-25 21:21:56 +0000493 static unsigned getHashValue(const ObjCSummaryKey &V) {
Benjamin Kramer28b23072012-05-27 13:28:44 +0000494 typedef std::pair<IdentifierInfo*, Selector> PairTy;
495 return DenseMapInfo<PairTy>::getHashValue(PairTy(V.getIdentifier(),
496 V.getSelector()));
Ted Kremenek553cf182008-06-25 21:21:56 +0000497 }
Mike Stump1eb44332009-09-09 15:08:12 +0000498
Ted Kremenek553cf182008-06-25 21:21:56 +0000499 static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
Benjamin Kramer28b23072012-05-27 13:28:44 +0000500 return LHS.getIdentifier() == RHS.getIdentifier() &&
501 LHS.getSelector() == RHS.getSelector();
Ted Kremenek553cf182008-06-25 21:21:56 +0000502 }
Mike Stump1eb44332009-09-09 15:08:12 +0000503
Ted Kremenek553cf182008-06-25 21:21:56 +0000504};
Chris Lattner06159e82009-12-15 07:26:51 +0000505template <>
506struct isPodLike<ObjCSummaryKey> { static const bool value = true; };
Ted Kremenek4f22a782008-06-23 23:30:29 +0000507} // end llvm namespace
Mike Stump1eb44332009-09-09 15:08:12 +0000508
Ted Kremenek4f22a782008-06-23 23:30:29 +0000509namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000510class ObjCSummaryCache {
Ted Kremenek93edbc52011-10-05 23:54:29 +0000511 typedef llvm::DenseMap<ObjCSummaryKey, const RetainSummary *> MapTy;
Ted Kremenek553cf182008-06-25 21:21:56 +0000512 MapTy M;
513public:
514 ObjCSummaryCache() {}
Mike Stump1eb44332009-09-09 15:08:12 +0000515
Ted Kremenek93edbc52011-10-05 23:54:29 +0000516 const RetainSummary * find(const ObjCInterfaceDecl *D, Selector S) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000517 // Do a lookup with the (D,S) pair. If we find a match return
518 // the iterator.
519 ObjCSummaryKey K(D, S);
520 MapTy::iterator I = M.find(K);
Mike Stump1eb44332009-09-09 15:08:12 +0000521
Jordan Rose4531b7d2012-07-02 19:27:43 +0000522 if (I != M.end())
Ted Kremenek614cc542009-07-21 23:27:57 +0000523 return I->second;
Jordan Rose4531b7d2012-07-02 19:27:43 +0000524 if (!D)
525 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +0000526
Ted Kremenek553cf182008-06-25 21:21:56 +0000527 // Walk the super chain. If we find a hit with a parent, we'll end
528 // up returning that summary. We actually allow that key (null,S), as
529 // we cache summaries for the null ObjCInterfaceDecl* to allow us to
530 // generate initial summaries without having to worry about NSObject
531 // being declared.
532 // FIXME: We may change this at some point.
Ted Kremenek9c378f72011-08-12 23:37:29 +0000533 for (ObjCInterfaceDecl *C=D->getSuperClass() ;; C=C->getSuperClass()) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000534 if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
535 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000536
Ted Kremenek553cf182008-06-25 21:21:56 +0000537 if (!C)
Ted Kremenek614cc542009-07-21 23:27:57 +0000538 return NULL;
Ted Kremenek553cf182008-06-25 21:21:56 +0000539 }
Mike Stump1eb44332009-09-09 15:08:12 +0000540
541 // Cache the summary with original key to make the next lookup faster
Ted Kremenek553cf182008-06-25 21:21:56 +0000542 // and return the iterator.
Ted Kremenek93edbc52011-10-05 23:54:29 +0000543 const RetainSummary *Summ = I->second;
Ted Kremenek614cc542009-07-21 23:27:57 +0000544 M[K] = Summ;
545 return Summ;
Ted Kremenek553cf182008-06-25 21:21:56 +0000546 }
Mike Stump1eb44332009-09-09 15:08:12 +0000547
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000548 const RetainSummary *find(IdentifierInfo* II, Selector S) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000549 // FIXME: Class method lookup. Right now we dont' have a good way
550 // of going between IdentifierInfo* and the class hierarchy.
Ted Kremenek614cc542009-07-21 23:27:57 +0000551 MapTy::iterator I = M.find(ObjCSummaryKey(II, S));
Mike Stump1eb44332009-09-09 15:08:12 +0000552
Ted Kremenek614cc542009-07-21 23:27:57 +0000553 if (I == M.end())
554 I = M.find(ObjCSummaryKey(S));
Mike Stump1eb44332009-09-09 15:08:12 +0000555
Ted Kremenek614cc542009-07-21 23:27:57 +0000556 return I == M.end() ? NULL : I->second;
Ted Kremenek553cf182008-06-25 21:21:56 +0000557 }
Mike Stump1eb44332009-09-09 15:08:12 +0000558
Ted Kremenek93edbc52011-10-05 23:54:29 +0000559 const RetainSummary *& operator[](ObjCSummaryKey K) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000560 return M[K];
561 }
Mike Stump1eb44332009-09-09 15:08:12 +0000562
Ted Kremenek93edbc52011-10-05 23:54:29 +0000563 const RetainSummary *& operator[](Selector S) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000564 return M[ ObjCSummaryKey(S) ];
565 }
Mike Stump1eb44332009-09-09 15:08:12 +0000566};
Ted Kremenek553cf182008-06-25 21:21:56 +0000567} // end anonymous namespace
568
569//===----------------------------------------------------------------------===//
570// Data structures for managing collections of summaries.
571//===----------------------------------------------------------------------===//
572
573namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000574class RetainSummaryManager {
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000575
576 //==-----------------------------------------------------------------==//
577 // Typedefs.
578 //==-----------------------------------------------------------------==//
Mike Stump1eb44332009-09-09 15:08:12 +0000579
Ted Kremenek93edbc52011-10-05 23:54:29 +0000580 typedef llvm::DenseMap<const FunctionDecl*, const RetainSummary *>
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000581 FuncSummariesTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000582
Ted Kremenek4f22a782008-06-23 23:30:29 +0000583 typedef ObjCSummaryCache ObjCMethodSummariesTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000584
Jordy Roseef945882012-03-18 01:26:10 +0000585 typedef llvm::FoldingSetNodeWrapper<RetainSummary> CachedSummaryNode;
586
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000587 //==-----------------------------------------------------------------==//
588 // Data.
589 //==-----------------------------------------------------------------==//
Mike Stump1eb44332009-09-09 15:08:12 +0000590
Ted Kremenek553cf182008-06-25 21:21:56 +0000591 /// Ctx - The ASTContext object for the analyzed ASTs.
Ted Kremenek9c378f72011-08-12 23:37:29 +0000592 ASTContext &Ctx;
Ted Kremenek179064e2008-07-01 17:21:27 +0000593
Ted Kremenek553cf182008-06-25 21:21:56 +0000594 /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
Ted Kremenek377e2302008-04-29 05:33:51 +0000595 const bool GCEnabled;
Mike Stump1eb44332009-09-09 15:08:12 +0000596
John McCallf85e1932011-06-15 23:02:42 +0000597 /// Records whether or not the analyzed code runs in ARC mode.
598 const bool ARCEnabled;
599
Ted Kremenek553cf182008-06-25 21:21:56 +0000600 /// FuncSummaries - A map from FunctionDecls to summaries.
Mike Stump1eb44332009-09-09 15:08:12 +0000601 FuncSummariesTy FuncSummaries;
602
Ted Kremenek553cf182008-06-25 21:21:56 +0000603 /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
604 /// to summaries.
Ted Kremenek1f180c32008-06-23 22:21:20 +0000605 ObjCMethodSummariesTy ObjCClassMethodSummaries;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000606
Ted Kremenek553cf182008-06-25 21:21:56 +0000607 /// ObjCMethodSummaries - A map from selectors to summaries.
Ted Kremenek1f180c32008-06-23 22:21:20 +0000608 ObjCMethodSummariesTy ObjCMethodSummaries;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000609
Ted Kremenek553cf182008-06-25 21:21:56 +0000610 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
611 /// and all other data used by the checker.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000612 llvm::BumpPtrAllocator BPAlloc;
Mike Stump1eb44332009-09-09 15:08:12 +0000613
Ted Kremenekb77449c2009-05-03 05:20:50 +0000614 /// AF - A factory for ArgEffects objects.
Mike Stump1eb44332009-09-09 15:08:12 +0000615 ArgEffects::Factory AF;
616
Ted Kremenek553cf182008-06-25 21:21:56 +0000617 /// ScratchArgs - A holding buffer for construct ArgEffects.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000618 ArgEffects ScratchArgs;
Mike Stump1eb44332009-09-09 15:08:12 +0000619
Ted Kremenekec315332009-05-07 23:40:42 +0000620 /// ObjCAllocRetE - Default return effect for methods returning Objective-C
621 /// objects.
622 RetEffect ObjCAllocRetE;
Ted Kremenek547d4952009-06-05 23:18:01 +0000623
Mike Stump1eb44332009-09-09 15:08:12 +0000624 /// ObjCInitRetE - Default return effect for init methods returning
Ted Kremenekac02f202009-08-20 05:13:36 +0000625 /// Objective-C objects.
Ted Kremenek547d4952009-06-05 23:18:01 +0000626 RetEffect ObjCInitRetE;
Mike Stump1eb44332009-09-09 15:08:12 +0000627
Jordy Roseef945882012-03-18 01:26:10 +0000628 /// SimpleSummaries - Used for uniquing summaries that don't have special
629 /// effects.
630 llvm::FoldingSet<CachedSummaryNode> SimpleSummaries;
Mike Stump1eb44332009-09-09 15:08:12 +0000631
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000632 //==-----------------------------------------------------------------==//
633 // Methods.
634 //==-----------------------------------------------------------------==//
Mike Stump1eb44332009-09-09 15:08:12 +0000635
Ted Kremenek553cf182008-06-25 21:21:56 +0000636 /// getArgEffects - Returns a persistent ArgEffects object based on the
637 /// data in ScratchArgs.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000638 ArgEffects getArgEffects();
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000639
Mike Stump1eb44332009-09-09 15:08:12 +0000640 enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
Ted Kremenek93edbc52011-10-05 23:54:29 +0000641
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000642 const RetainSummary *getUnarySummary(const FunctionType* FT,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000643 UnaryFuncKind func);
Mike Stump1eb44332009-09-09 15:08:12 +0000644
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000645 const RetainSummary *getCFSummaryCreateRule(const FunctionDecl *FD);
646 const RetainSummary *getCFSummaryGetRule(const FunctionDecl *FD);
647 const RetainSummary *getCFCreateGetRuleSummary(const FunctionDecl *FD);
Mike Stump1eb44332009-09-09 15:08:12 +0000648
Jordy Roseef945882012-03-18 01:26:10 +0000649 const RetainSummary *getPersistentSummary(const RetainSummary &OldSumm);
Ted Kremenek706522f2008-10-29 04:07:07 +0000650
Jordy Roseef945882012-03-18 01:26:10 +0000651 const RetainSummary *getPersistentSummary(RetEffect RetEff,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000652 ArgEffect ReceiverEff = DoNothing,
653 ArgEffect DefaultEff = MayEscape) {
Jordy Roseef945882012-03-18 01:26:10 +0000654 RetainSummary Summ(getArgEffects(), RetEff, DefaultEff, ReceiverEff);
655 return getPersistentSummary(Summ);
656 }
657
Ted Kremenekc91fdf62012-05-08 00:12:09 +0000658 const RetainSummary *getDoNothingSummary() {
659 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
660 }
661
Jordy Roseef945882012-03-18 01:26:10 +0000662 const RetainSummary *getDefaultSummary() {
663 return getPersistentSummary(RetEffect::MakeNoRet(),
664 DoNothing, MayEscape);
Ted Kremenek9c32d082008-05-06 00:30:21 +0000665 }
Mike Stump1eb44332009-09-09 15:08:12 +0000666
Ted Kremenek93edbc52011-10-05 23:54:29 +0000667 const RetainSummary *getPersistentStopSummary() {
Jordy Roseef945882012-03-18 01:26:10 +0000668 return getPersistentSummary(RetEffect::MakeNoRet(),
669 StopTracking, StopTracking);
Mike Stump1eb44332009-09-09 15:08:12 +0000670 }
Ted Kremenekb3095252008-05-06 04:20:12 +0000671
Ted Kremenek1f180c32008-06-23 22:21:20 +0000672 void InitializeClassMethodSummaries();
673 void InitializeMethodSummaries();
Ted Kremenek896cd9d2008-10-23 01:56:15 +0000674private:
Ted Kremenek93edbc52011-10-05 23:54:29 +0000675 void addNSObjectClsMethSummary(Selector S, const RetainSummary *Summ) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000676 ObjCClassMethodSummaries[S] = Summ;
677 }
Mike Stump1eb44332009-09-09 15:08:12 +0000678
Ted Kremenek93edbc52011-10-05 23:54:29 +0000679 void addNSObjectMethSummary(Selector S, const RetainSummary *Summ) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000680 ObjCMethodSummaries[S] = Summ;
681 }
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +0000682
Ted Kremeneka9797122012-02-18 21:37:48 +0000683 void addClassMethSummary(const char* Cls, const char* name,
684 const RetainSummary *Summ, bool isNullary = true) {
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +0000685 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
Ted Kremeneka9797122012-02-18 21:37:48 +0000686 Selector S = isNullary ? GetNullarySelector(name, Ctx)
687 : GetUnarySelector(name, Ctx);
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +0000688 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
689 }
Mike Stump1eb44332009-09-09 15:08:12 +0000690
Ted Kremenek6c4becb2009-02-25 02:54:57 +0000691 void addInstMethSummary(const char* Cls, const char* nullaryName,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000692 const RetainSummary *Summ) {
Ted Kremenek6c4becb2009-02-25 02:54:57 +0000693 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
694 Selector S = GetNullarySelector(nullaryName, Ctx);
695 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
696 }
Mike Stump1eb44332009-09-09 15:08:12 +0000697
Ted Kremenekde4d5332009-04-24 17:50:11 +0000698 Selector generateSelector(va_list argp) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000699 SmallVector<IdentifierInfo*, 10> II;
Ted Kremenekde4d5332009-04-24 17:50:11 +0000700
Ted Kremenek9e476de2008-08-12 18:30:56 +0000701 while (const char* s = va_arg(argp, const char*))
702 II.push_back(&Ctx.Idents.get(s));
Ted Kremenekde4d5332009-04-24 17:50:11 +0000703
Mike Stump1eb44332009-09-09 15:08:12 +0000704 return Ctx.Selectors.getSelector(II.size(), &II[0]);
Ted Kremenekde4d5332009-04-24 17:50:11 +0000705 }
Mike Stump1eb44332009-09-09 15:08:12 +0000706
Ted Kremenekde4d5332009-04-24 17:50:11 +0000707 void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy& Summaries,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000708 const RetainSummary * Summ, va_list argp) {
Ted Kremenekde4d5332009-04-24 17:50:11 +0000709 Selector S = generateSelector(argp);
710 Summaries[ObjCSummaryKey(ClsII, S)] = Summ;
Ted Kremenek70a733e2008-07-18 17:24:20 +0000711 }
Mike Stump1eb44332009-09-09 15:08:12 +0000712
Ted Kremenek93edbc52011-10-05 23:54:29 +0000713 void addInstMethSummary(const char* Cls, const RetainSummary * Summ, ...) {
Ted Kremenekaf9dc272008-08-12 18:48:50 +0000714 va_list argp;
715 va_start(argp, Summ);
Ted Kremenekde4d5332009-04-24 17:50:11 +0000716 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Mike Stump1eb44332009-09-09 15:08:12 +0000717 va_end(argp);
Ted Kremenekaf9dc272008-08-12 18:48:50 +0000718 }
Mike Stump1eb44332009-09-09 15:08:12 +0000719
Ted Kremenek93edbc52011-10-05 23:54:29 +0000720 void addClsMethSummary(const char* Cls, const RetainSummary * Summ, ...) {
Ted Kremenekde4d5332009-04-24 17:50:11 +0000721 va_list argp;
722 va_start(argp, Summ);
723 addMethodSummary(&Ctx.Idents.get(Cls),ObjCClassMethodSummaries, Summ, argp);
724 va_end(argp);
725 }
Mike Stump1eb44332009-09-09 15:08:12 +0000726
Ted Kremenek93edbc52011-10-05 23:54:29 +0000727 void addClsMethSummary(IdentifierInfo *II, const RetainSummary * Summ, ...) {
Ted Kremenekde4d5332009-04-24 17:50:11 +0000728 va_list argp;
729 va_start(argp, Summ);
730 addMethodSummary(II, ObjCClassMethodSummaries, Summ, argp);
731 va_end(argp);
732 }
733
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000734public:
Mike Stump1eb44332009-09-09 15:08:12 +0000735
Ted Kremenek9c378f72011-08-12 23:37:29 +0000736 RetainSummaryManager(ASTContext &ctx, bool gcenabled, bool usesARC)
Ted Kremenek179064e2008-07-01 17:21:27 +0000737 : Ctx(ctx),
John McCallf85e1932011-06-15 23:02:42 +0000738 GCEnabled(gcenabled),
739 ARCEnabled(usesARC),
740 AF(BPAlloc), ScratchArgs(AF.getEmptyMap()),
741 ObjCAllocRetE(gcenabled
742 ? RetEffect::MakeGCNotOwned()
743 : (usesARC ? RetEffect::MakeARCNotOwned()
744 : RetEffect::MakeOwned(RetEffect::ObjC, true))),
745 ObjCInitRetE(gcenabled
746 ? RetEffect::MakeGCNotOwned()
747 : (usesARC ? RetEffect::MakeARCNotOwned()
Jordy Roseef945882012-03-18 01:26:10 +0000748 : RetEffect::MakeOwnedWhenTrackedReceiver())) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000749 InitializeClassMethodSummaries();
750 InitializeMethodSummaries();
751 }
Mike Stump1eb44332009-09-09 15:08:12 +0000752
Jordan Rose4531b7d2012-07-02 19:27:43 +0000753 const RetainSummary *getSummary(const CallEvent &Call,
754 ProgramStateRef State = 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000755
Jordan Rose4531b7d2012-07-02 19:27:43 +0000756 const RetainSummary *getFunctionSummary(const FunctionDecl *FD);
757
758 const RetainSummary *getMethodSummary(Selector S, const ObjCInterfaceDecl *ID,
Jordy Rosef3aae582012-03-17 21:13:07 +0000759 const ObjCMethodDecl *MD,
760 QualType RetTy,
761 ObjCMethodSummariesTy &CachedSummaries);
762
Jordan Rosecde8cdb2012-07-02 19:27:56 +0000763 const RetainSummary *getInstanceMethodSummary(const ObjCMethodCall &M,
Jordan Rose4531b7d2012-07-02 19:27:43 +0000764 ProgramStateRef State);
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000765
Jordan Rosecde8cdb2012-07-02 19:27:56 +0000766 const RetainSummary *getClassMethodSummary(const ObjCMethodCall &M) {
Jordan Rose4531b7d2012-07-02 19:27:43 +0000767 assert(!M.isInstanceMessage());
768 const ObjCInterfaceDecl *Class = M.getReceiverInterface();
Mike Stump1eb44332009-09-09 15:08:12 +0000769
Jordan Rose4531b7d2012-07-02 19:27:43 +0000770 return getMethodSummary(M.getSelector(), Class, M.getDecl(),
771 M.getResultType(), ObjCClassMethodSummaries);
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +0000772 }
Ted Kremenek552333c2009-04-29 17:17:48 +0000773
774 /// getMethodSummary - This version of getMethodSummary is used to query
775 /// the summary for the current method being analyzed.
Ted Kremenek93edbc52011-10-05 23:54:29 +0000776 const RetainSummary *getMethodSummary(const ObjCMethodDecl *MD) {
Ted Kremeneka8833552009-04-29 23:03:22 +0000777 const ObjCInterfaceDecl *ID = MD->getClassInterface();
Ted Kremenek70a65762009-04-30 05:41:14 +0000778 Selector S = MD->getSelector();
Ted Kremenek552333c2009-04-29 17:17:48 +0000779 QualType ResultTy = MD->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +0000780
Jordy Rosef3aae582012-03-17 21:13:07 +0000781 ObjCMethodSummariesTy *CachedSummaries;
Ted Kremenek552333c2009-04-29 17:17:48 +0000782 if (MD->isInstanceMethod())
Jordy Rosef3aae582012-03-17 21:13:07 +0000783 CachedSummaries = &ObjCMethodSummaries;
Ted Kremenek552333c2009-04-29 17:17:48 +0000784 else
Jordy Rosef3aae582012-03-17 21:13:07 +0000785 CachedSummaries = &ObjCClassMethodSummaries;
786
Jordan Rose4531b7d2012-07-02 19:27:43 +0000787 return getMethodSummary(S, ID, MD, ResultTy, *CachedSummaries);
Ted Kremenek552333c2009-04-29 17:17:48 +0000788 }
Mike Stump1eb44332009-09-09 15:08:12 +0000789
Jordy Rosef3aae582012-03-17 21:13:07 +0000790 const RetainSummary *getStandardMethodSummary(const ObjCMethodDecl *MD,
Jordan Rose4531b7d2012-07-02 19:27:43 +0000791 Selector S, QualType RetTy);
Ted Kremeneka8833552009-04-29 23:03:22 +0000792
Ted Kremenek93edbc52011-10-05 23:54:29 +0000793 void updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenek4dd8fb42009-05-09 02:58:13 +0000794 const ObjCMethodDecl *MD);
795
Ted Kremenek93edbc52011-10-05 23:54:29 +0000796 void updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenek4dd8fb42009-05-09 02:58:13 +0000797 const FunctionDecl *FD);
798
Jordan Rose4531b7d2012-07-02 19:27:43 +0000799 void updateSummaryForCall(const RetainSummary *&Summ,
800 const CallEvent &Call);
801
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000802 bool isGCEnabled() const { return GCEnabled; }
Mike Stump1eb44332009-09-09 15:08:12 +0000803
John McCallf85e1932011-06-15 23:02:42 +0000804 bool isARCEnabled() const { return ARCEnabled; }
805
806 bool isARCorGCEnabled() const { return GCEnabled || ARCEnabled; }
Jordan Rose4531b7d2012-07-02 19:27:43 +0000807
808 RetEffect getObjAllocRetEffect() const { return ObjCAllocRetE; }
809
810 friend class RetainSummaryTemplate;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000811};
Mike Stump1eb44332009-09-09 15:08:12 +0000812
Jordy Rose0fe62f82011-08-24 09:02:37 +0000813// Used to avoid allocating long-term (BPAlloc'd) memory for default retain
814// summaries. If a function or method looks like it has a default summary, but
815// it has annotations, the annotations are added to the stack-based template
816// and then copied into managed memory.
817class RetainSummaryTemplate {
818 RetainSummaryManager &Manager;
Ted Kremenek93edbc52011-10-05 23:54:29 +0000819 const RetainSummary *&RealSummary;
Jordy Rose0fe62f82011-08-24 09:02:37 +0000820 RetainSummary ScratchSummary;
821 bool Accessed;
822public:
Jordan Rose4531b7d2012-07-02 19:27:43 +0000823 RetainSummaryTemplate(const RetainSummary *&real, RetainSummaryManager &mgr)
824 : Manager(mgr), RealSummary(real), ScratchSummary(*real), Accessed(false) {}
Jordy Rose0fe62f82011-08-24 09:02:37 +0000825
826 ~RetainSummaryTemplate() {
Ted Kremenek93edbc52011-10-05 23:54:29 +0000827 if (Accessed)
Jordy Roseef945882012-03-18 01:26:10 +0000828 RealSummary = Manager.getPersistentSummary(ScratchSummary);
Jordy Rose0fe62f82011-08-24 09:02:37 +0000829 }
830
831 RetainSummary &operator*() {
832 Accessed = true;
Ted Kremenek93edbc52011-10-05 23:54:29 +0000833 return ScratchSummary;
Jordy Rose0fe62f82011-08-24 09:02:37 +0000834 }
835
836 RetainSummary *operator->() {
837 Accessed = true;
Ted Kremenek93edbc52011-10-05 23:54:29 +0000838 return &ScratchSummary;
Jordy Rose0fe62f82011-08-24 09:02:37 +0000839 }
840};
841
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000842} // end anonymous namespace
843
844//===----------------------------------------------------------------------===//
845// Implementation of checker data structures.
846//===----------------------------------------------------------------------===//
847
Ted Kremenekb77449c2009-05-03 05:20:50 +0000848ArgEffects RetainSummaryManager::getArgEffects() {
849 ArgEffects AE = ScratchArgs;
Ted Kremenek3baf6722010-11-24 00:54:37 +0000850 ScratchArgs = AF.getEmptyMap();
Ted Kremenekb77449c2009-05-03 05:20:50 +0000851 return AE;
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000852}
853
Ted Kremenek93edbc52011-10-05 23:54:29 +0000854const RetainSummary *
Jordy Roseef945882012-03-18 01:26:10 +0000855RetainSummaryManager::getPersistentSummary(const RetainSummary &OldSumm) {
856 // Unique "simple" summaries -- those without ArgEffects.
857 if (OldSumm.isSimple()) {
858 llvm::FoldingSetNodeID ID;
859 OldSumm.Profile(ID);
860
861 void *Pos;
862 CachedSummaryNode *N = SimpleSummaries.FindNodeOrInsertPos(ID, Pos);
863
864 if (!N) {
865 N = (CachedSummaryNode *) BPAlloc.Allocate<CachedSummaryNode>();
866 new (N) CachedSummaryNode(OldSumm);
867 SimpleSummaries.InsertNode(N, Pos);
868 }
869
870 return &N->getValue();
871 }
872
Ted Kremenek93edbc52011-10-05 23:54:29 +0000873 RetainSummary *Summ = (RetainSummary *) BPAlloc.Allocate<RetainSummary>();
Jordy Roseef945882012-03-18 01:26:10 +0000874 new (Summ) RetainSummary(OldSumm);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000875 return Summ;
876}
877
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000878//===----------------------------------------------------------------------===//
879// Summary creation for functions (largely uses of Core Foundation).
880//===----------------------------------------------------------------------===//
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000881
Ted Kremenek9c378f72011-08-12 23:37:29 +0000882static bool isRetain(const FunctionDecl *FD, StringRef FName) {
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000883 return FName.endswith("Retain");
Ted Kremenek12619382009-01-12 21:45:02 +0000884}
885
Ted Kremenek9c378f72011-08-12 23:37:29 +0000886static bool isRelease(const FunctionDecl *FD, StringRef FName) {
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000887 return FName.endswith("Release");
Ted Kremenek12619382009-01-12 21:45:02 +0000888}
889
Jordy Rose76c506f2011-08-21 21:58:18 +0000890static bool isMakeCollectable(const FunctionDecl *FD, StringRef FName) {
891 // FIXME: Remove FunctionDecl parameter.
892 // FIXME: Is it really okay if MakeCollectable isn't a suffix?
893 return FName.find("MakeCollectable") != StringRef::npos;
894}
895
Jordan Rose4531b7d2012-07-02 19:27:43 +0000896static ArgEffect getStopTrackingEquivalent(ArgEffect E) {
897 switch (E) {
898 case DoNothing:
899 case Autorelease:
900 case DecRefBridgedTransfered:
901 case IncRef:
902 case IncRefMsg:
903 case MakeCollectable:
904 case MayEscape:
905 case NewAutoreleasePool:
906 case StopTracking:
907 return StopTracking;
908 case DecRef:
909 case DecRefAndStopTracking:
910 return DecRefAndStopTracking;
911 case DecRefMsg:
912 case DecRefMsgAndStopTracking:
913 return DecRefMsgAndStopTracking;
914 case Dealloc:
915 return Dealloc;
916 }
917
918 llvm_unreachable("Unknown ArgEffect kind");
919}
920
921void RetainSummaryManager::updateSummaryForCall(const RetainSummary *&S,
922 const CallEvent &Call) {
923 if (Call.hasNonZeroCallbackArg()) {
924 ArgEffect RecEffect = getStopTrackingEquivalent(S->getReceiverEffect());
925 ArgEffect DefEffect = getStopTrackingEquivalent(S->getDefaultArgEffect());
926
927 ArgEffects CustomArgEffects = S->getArgEffects();
928 for (ArgEffects::iterator I = CustomArgEffects.begin(),
929 E = CustomArgEffects.end();
930 I != E; ++I) {
931 ArgEffect Translated = getStopTrackingEquivalent(I->second);
932 if (Translated != DefEffect)
933 ScratchArgs = AF.add(ScratchArgs, I->first, Translated);
934 }
935
936 RetEffect RE = RetEffect::MakeNoRet();
937
938 // Special cases where the callback argument CANNOT free the return value.
939 // This can generally only happen if we know that the callback will only be
940 // called when the return value is already being deallocated.
941 if (const FunctionCall *FC = dyn_cast<FunctionCall>(&Call)) {
942 IdentifierInfo *Name = FC->getDecl()->getIdentifier();
943
944 // This callback frees the associated buffer.
945 if (Name->isStr("CGBitmapContextCreateWithData"))
946 RE = S->getRetEffect();
947 }
948
949 S = getPersistentSummary(RE, RecEffect, DefEffect);
950 }
951}
952
Anna Zaks58822c42012-05-04 22:18:39 +0000953const RetainSummary *
Jordan Rose4531b7d2012-07-02 19:27:43 +0000954RetainSummaryManager::getSummary(const CallEvent &Call,
955 ProgramStateRef State) {
956 const RetainSummary *Summ;
957 switch (Call.getKind()) {
958 case CE_Function:
959 Summ = getFunctionSummary(cast<FunctionCall>(Call).getDecl());
960 break;
961 case CE_CXXMember:
Jordan Rosefdaa3382012-07-03 22:55:57 +0000962 case CE_CXXMemberOperator:
Jordan Rose4531b7d2012-07-02 19:27:43 +0000963 case CE_Block:
964 case CE_CXXConstructor:
Jordan Rose8d276d32012-07-10 22:07:47 +0000965 case CE_CXXDestructor:
Jordan Rose70cbf3c2012-07-02 22:21:47 +0000966 case CE_CXXAllocator:
Jordan Rose4531b7d2012-07-02 19:27:43 +0000967 // FIXME: These calls are currently unsupported.
968 return getPersistentStopSummary();
Jordan Rose8919e682012-07-18 21:59:51 +0000969 case CE_ObjCMessage: {
Jordan Rosecde8cdb2012-07-02 19:27:56 +0000970 const ObjCMethodCall &Msg = cast<ObjCMethodCall>(Call);
Jordan Rose4531b7d2012-07-02 19:27:43 +0000971 if (Msg.isInstanceMessage())
972 Summ = getInstanceMethodSummary(Msg, State);
973 else
974 Summ = getClassMethodSummary(Msg);
975 break;
976 }
977 }
978
979 updateSummaryForCall(Summ, Call);
980
981 assert(Summ && "Unknown call type?");
982 return Summ;
983}
984
985const RetainSummary *
986RetainSummaryManager::getFunctionSummary(const FunctionDecl *FD) {
987 // If we don't know what function we're calling, use our default summary.
988 if (!FD)
989 return getDefaultSummary();
990
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000991 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000992 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000993 if (I != FuncSummaries.end())
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000994 return I->second;
995
Ted Kremeneke401a0c2009-05-04 15:34:07 +0000996 // No summary? Generate one.
Ted Kremenek93edbc52011-10-05 23:54:29 +0000997 const RetainSummary *S = 0;
Jordan Rose15d18e12012-08-06 21:28:02 +0000998 bool AllowAnnotations = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000999
Ted Kremenek37d785b2008-07-15 16:50:12 +00001000 do {
Ted Kremenek12619382009-01-12 21:45:02 +00001001 // We generate "stop" summaries for implicitly defined functions.
1002 if (FD->isImplicit()) {
1003 S = getPersistentStopSummary();
1004 break;
Ted Kremenek37d785b2008-07-15 16:50:12 +00001005 }
Mike Stump1eb44332009-09-09 15:08:12 +00001006
John McCall183700f2009-09-21 23:43:11 +00001007 // [PR 3337] Use 'getAs<FunctionType>' to strip away any typedefs on the
Ted Kremenek99890652009-01-16 18:40:33 +00001008 // function's type.
John McCall183700f2009-09-21 23:43:11 +00001009 const FunctionType* FT = FD->getType()->getAs<FunctionType>();
Ted Kremenek48c6d182009-12-16 06:06:43 +00001010 const IdentifierInfo *II = FD->getIdentifier();
1011 if (!II)
1012 break;
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001013
1014 StringRef FName = II->getName();
Mike Stump1eb44332009-09-09 15:08:12 +00001015
Ted Kremenekbf0a4dd2009-03-05 22:11:14 +00001016 // Strip away preceding '_'. Doing this here will effect all the checks
1017 // down below.
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001018 FName = FName.substr(FName.find_first_not_of('_'));
Mike Stump1eb44332009-09-09 15:08:12 +00001019
Ted Kremenek12619382009-01-12 21:45:02 +00001020 // Inspect the result type.
1021 QualType RetTy = FT->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00001022
Ted Kremenek12619382009-01-12 21:45:02 +00001023 // FIXME: This should all be refactored into a chain of "summary lookup"
1024 // filters.
Ted Kremenek008636a2009-10-14 00:27:24 +00001025 assert(ScratchArgs.isEmpty());
Ted Kremenek39d88b02009-06-15 20:36:07 +00001026
Ted Kremenekbefc6d22012-04-26 04:32:23 +00001027 if (FName == "pthread_create" || FName == "pthread_setspecific") {
1028 // Part of: <rdar://problem/7299394> and <rdar://problem/11282706>.
1029 // This will be addressed better with IPA.
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001030 S = getPersistentStopSummary();
1031 } else if (FName == "NSMakeCollectable") {
1032 // Handle: id NSMakeCollectable(CFTypeRef)
1033 S = (RetTy->isObjCIdType())
1034 ? getUnarySummary(FT, cfmakecollectable)
1035 : getPersistentStopSummary();
Jordan Rose15d18e12012-08-06 21:28:02 +00001036 // The headers on OS X 10.8 use cf_consumed/ns_returns_retained,
1037 // but we can fully model NSMakeCollectable ourselves.
1038 AllowAnnotations = false;
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001039 } else if (FName == "IOBSDNameMatching" ||
1040 FName == "IOServiceMatching" ||
1041 FName == "IOServiceNameMatching" ||
Ted Kremenek537dd3a2012-05-01 05:28:27 +00001042 FName == "IORegistryEntrySearchCFProperty" ||
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001043 FName == "IORegistryEntryIDMatching" ||
1044 FName == "IOOpenFirmwarePathMatching") {
1045 // Part of <rdar://problem/6961230>. (IOKit)
1046 // This should be addressed using a API table.
1047 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1048 DoNothing, DoNothing);
1049 } else if (FName == "IOServiceGetMatchingService" ||
1050 FName == "IOServiceGetMatchingServices") {
1051 // FIXES: <rdar://problem/6326900>
1052 // This should be addressed using a API table. This strcmp is also
1053 // a little gross, but there is no need to super optimize here.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001054 ScratchArgs = AF.add(ScratchArgs, 1, DecRef);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001055 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1056 } else if (FName == "IOServiceAddNotification" ||
1057 FName == "IOServiceAddMatchingNotification") {
1058 // Part of <rdar://problem/6961230>. (IOKit)
1059 // This should be addressed using a API table.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001060 ScratchArgs = AF.add(ScratchArgs, 2, DecRef);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001061 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1062 } else if (FName == "CVPixelBufferCreateWithBytes") {
1063 // FIXES: <rdar://problem/7283567>
1064 // Eventually this can be improved by recognizing that the pixel
1065 // buffer passed to CVPixelBufferCreateWithBytes is released via
1066 // a callback and doing full IPA to make sure this is done correctly.
1067 // FIXME: This function has an out parameter that returns an
1068 // allocated object.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001069 ScratchArgs = AF.add(ScratchArgs, 7, StopTracking);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001070 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1071 } else if (FName == "CGBitmapContextCreateWithData") {
1072 // FIXES: <rdar://problem/7358899>
1073 // Eventually this can be improved by recognizing that 'releaseInfo'
1074 // passed to CGBitmapContextCreateWithData is released via
1075 // a callback and doing full IPA to make sure this is done correctly.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001076 ScratchArgs = AF.add(ScratchArgs, 8, StopTracking);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001077 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1078 DoNothing, DoNothing);
1079 } else if (FName == "CVPixelBufferCreateWithPlanarBytes") {
1080 // FIXES: <rdar://problem/7283567>
1081 // Eventually this can be improved by recognizing that the pixel
1082 // buffer passed to CVPixelBufferCreateWithPlanarBytes is released
1083 // via a callback and doing full IPA to make sure this is done
1084 // correctly.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001085 ScratchArgs = AF.add(ScratchArgs, 12, StopTracking);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001086 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenek06911d42012-03-22 06:29:41 +00001087 } else if (FName == "dispatch_set_context") {
1088 // <rdar://problem/11059275> - The analyzer currently doesn't have
1089 // a good way to reason about the finalizer function for libdispatch.
1090 // If we pass a context object that is memory managed, stop tracking it.
1091 // FIXME: this hack should possibly go away once we can handle
1092 // libdispatch finalizers.
1093 ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
1094 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenekc91fdf62012-05-08 00:12:09 +00001095 } else if (FName.startswith("NSLog")) {
1096 S = getDoNothingSummary();
Anna Zaks62a5c342012-03-30 05:48:16 +00001097 } else if (FName.startswith("NS") &&
1098 (FName.find("Insert") != StringRef::npos)) {
1099 // Whitelist NSXXInsertXX, for example NSMapInsertIfAbsent, since they can
1100 // be deallocated by NSMapRemove. (radar://11152419)
1101 ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
1102 ScratchArgs = AF.add(ScratchArgs, 2, StopTracking);
1103 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenekb04cb592009-06-11 18:17:24 +00001104 }
Mike Stump1eb44332009-09-09 15:08:12 +00001105
Ted Kremenekb04cb592009-06-11 18:17:24 +00001106 // Did we get a summary?
1107 if (S)
1108 break;
Ted Kremenek61991902009-03-17 22:43:44 +00001109
1110 // Enable this code once the semantics of NSDeallocateObject are resolved
1111 // for GC. <rdar://problem/6619988>
1112#if 0
1113 // Handle: NSDeallocateObject(id anObject);
1114 // This method does allow 'nil' (although we don't check it now).
Mike Stump1eb44332009-09-09 15:08:12 +00001115 if (strcmp(FName, "NSDeallocateObject") == 0) {
Ted Kremenek61991902009-03-17 22:43:44 +00001116 return RetTy == Ctx.VoidTy
1117 ? getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, Dealloc)
1118 : getPersistentStopSummary();
1119 }
1120#endif
Ted Kremenek12619382009-01-12 21:45:02 +00001121
1122 if (RetTy->isPointerType()) {
1123 // For CoreFoundation ('CF') types.
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001124 if (cocoa::isRefType(RetTy, "CF", FName)) {
Ted Kremenek12619382009-01-12 21:45:02 +00001125 if (isRetain(FD, FName))
1126 S = getUnarySummary(FT, cfretain);
Jordy Rose76c506f2011-08-21 21:58:18 +00001127 else if (isMakeCollectable(FD, FName))
Ted Kremenek12619382009-01-12 21:45:02 +00001128 S = getUnarySummary(FT, cfmakecollectable);
Mike Stump1eb44332009-09-09 15:08:12 +00001129 else
John McCall7df2ff42011-10-01 00:48:56 +00001130 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek12619382009-01-12 21:45:02 +00001131
1132 break;
1133 }
1134
1135 // For CoreGraphics ('CG') types.
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001136 if (cocoa::isRefType(RetTy, "CG", FName)) {
Ted Kremenek12619382009-01-12 21:45:02 +00001137 if (isRetain(FD, FName))
1138 S = getUnarySummary(FT, cfretain);
1139 else
John McCall7df2ff42011-10-01 00:48:56 +00001140 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek12619382009-01-12 21:45:02 +00001141
1142 break;
1143 }
1144
1145 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001146 if (cocoa::isRefType(RetTy, "DADisk") ||
1147 cocoa::isRefType(RetTy, "DADissenter") ||
1148 cocoa::isRefType(RetTy, "DASessionRef")) {
John McCall7df2ff42011-10-01 00:48:56 +00001149 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek12619382009-01-12 21:45:02 +00001150 break;
1151 }
Mike Stump1eb44332009-09-09 15:08:12 +00001152
Ted Kremenek12619382009-01-12 21:45:02 +00001153 break;
1154 }
1155
1156 // Check for release functions, the only kind of functions that we care
1157 // about that don't return a pointer type.
1158 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
Ted Kremeneke7d03122010-02-08 16:45:01 +00001159 // Test for 'CGCF'.
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001160 FName = FName.substr(FName.startswith("CGCF") ? 4 : 2);
Ted Kremeneke7d03122010-02-08 16:45:01 +00001161
Ted Kremenekbf0a4dd2009-03-05 22:11:14 +00001162 if (isRelease(FD, FName))
Ted Kremenek12619382009-01-12 21:45:02 +00001163 S = getUnarySummary(FT, cfrelease);
1164 else {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001165 assert (ScratchArgs.isEmpty());
Ted Kremenek68189282009-01-29 22:45:13 +00001166 // Remaining CoreFoundation and CoreGraphics functions.
1167 // We use to assume that they all strictly followed the ownership idiom
1168 // and that ownership cannot be transferred. While this is technically
1169 // correct, many methods allow a tracked object to escape. For example:
1170 //
Mike Stump1eb44332009-09-09 15:08:12 +00001171 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
Ted Kremenek68189282009-01-29 22:45:13 +00001172 // CFDictionaryAddValue(y, key, x);
Mike Stump1eb44332009-09-09 15:08:12 +00001173 // CFRelease(x);
Ted Kremenek68189282009-01-29 22:45:13 +00001174 // ... it is okay to use 'x' since 'y' has a reference to it
1175 //
1176 // We handle this and similar cases with the follow heuristic. If the
Ted Kremenekc4843812009-08-20 00:57:22 +00001177 // function name contains "InsertValue", "SetValue", "AddValue",
1178 // "AppendValue", or "SetAttribute", then we assume that arguments may
1179 // "escape." This means that something else holds on to the object,
1180 // allowing it be used even after its local retain count drops to 0.
Benjamin Kramere45c1492010-01-11 19:46:28 +00001181 ArgEffect E = (StrInStrNoCase(FName, "InsertValue") != StringRef::npos||
1182 StrInStrNoCase(FName, "AddValue") != StringRef::npos ||
1183 StrInStrNoCase(FName, "SetValue") != StringRef::npos ||
1184 StrInStrNoCase(FName, "AppendValue") != StringRef::npos||
Benjamin Kramerc027e542010-01-11 20:15:06 +00001185 StrInStrNoCase(FName, "SetAttribute") != StringRef::npos)
Ted Kremenek68189282009-01-29 22:45:13 +00001186 ? MayEscape : DoNothing;
Mike Stump1eb44332009-09-09 15:08:12 +00001187
Ted Kremenek68189282009-01-29 22:45:13 +00001188 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek12619382009-01-12 21:45:02 +00001189 }
1190 }
Ted Kremenek37d785b2008-07-15 16:50:12 +00001191 }
1192 while (0);
Mike Stump1eb44332009-09-09 15:08:12 +00001193
Jordan Rose4531b7d2012-07-02 19:27:43 +00001194 // If we got all the way here without any luck, use a default summary.
1195 if (!S)
1196 S = getDefaultSummary();
1197
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001198 // Annotations override defaults.
Jordan Rose15d18e12012-08-06 21:28:02 +00001199 if (AllowAnnotations)
1200 updateSummaryFromAnnotations(S, FD);
Mike Stump1eb44332009-09-09 15:08:12 +00001201
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001202 FuncSummaries[FD] = S;
Mike Stump1eb44332009-09-09 15:08:12 +00001203 return S;
Ted Kremenek2fff37e2008-03-06 00:08:09 +00001204}
1205
Ted Kremenek93edbc52011-10-05 23:54:29 +00001206const RetainSummary *
John McCall7df2ff42011-10-01 00:48:56 +00001207RetainSummaryManager::getCFCreateGetRuleSummary(const FunctionDecl *FD) {
1208 if (coreFoundation::followsCreateRule(FD))
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001209 return getCFSummaryCreateRule(FD);
Mike Stump1eb44332009-09-09 15:08:12 +00001210
Ted Kremenekd368d712011-05-25 06:19:45 +00001211 return getCFSummaryGetRule(FD);
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001212}
1213
Ted Kremenek93edbc52011-10-05 23:54:29 +00001214const RetainSummary *
Ted Kremenek6ad315a2009-02-23 16:51:39 +00001215RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1216 UnaryFuncKind func) {
1217
Ted Kremenek12619382009-01-12 21:45:02 +00001218 // Sanity check that this is *really* a unary function. This can
1219 // happen if people do weird things.
Douglas Gregor72564e72009-02-26 23:50:07 +00001220 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
Ted Kremenek12619382009-01-12 21:45:02 +00001221 if (!FTP || FTP->getNumArgs() != 1)
1222 return getPersistentStopSummary();
Mike Stump1eb44332009-09-09 15:08:12 +00001223
Ted Kremenekb77449c2009-05-03 05:20:50 +00001224 assert (ScratchArgs.isEmpty());
Mike Stump1eb44332009-09-09 15:08:12 +00001225
Jordy Rose76c506f2011-08-21 21:58:18 +00001226 ArgEffect Effect;
Ted Kremenek377e2302008-04-29 05:33:51 +00001227 switch (func) {
Jordy Rose76c506f2011-08-21 21:58:18 +00001228 case cfretain: Effect = IncRef; break;
1229 case cfrelease: Effect = DecRef; break;
1230 case cfmakecollectable: Effect = MakeCollectable; break;
Ted Kremenek940b1d82008-04-10 23:44:06 +00001231 }
Jordy Rose76c506f2011-08-21 21:58:18 +00001232
1233 ScratchArgs = AF.add(ScratchArgs, 0, Effect);
1234 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001235}
1236
Ted Kremenek93edbc52011-10-05 23:54:29 +00001237const RetainSummary *
Ted Kremenek9c378f72011-08-12 23:37:29 +00001238RetainSummaryManager::getCFSummaryCreateRule(const FunctionDecl *FD) {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001239 assert (ScratchArgs.isEmpty());
Mike Stump1eb44332009-09-09 15:08:12 +00001240
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001241 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001242}
1243
Ted Kremenek93edbc52011-10-05 23:54:29 +00001244const RetainSummary *
Ted Kremenek9c378f72011-08-12 23:37:29 +00001245RetainSummaryManager::getCFSummaryGetRule(const FunctionDecl *FD) {
Mike Stump1eb44332009-09-09 15:08:12 +00001246 assert (ScratchArgs.isEmpty());
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001247 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1248 DoNothing, DoNothing);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001249}
1250
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001251//===----------------------------------------------------------------------===//
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001252// Summary creation for Selectors.
1253//===----------------------------------------------------------------------===//
1254
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001255void
Ted Kremenek93edbc52011-10-05 23:54:29 +00001256RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001257 const FunctionDecl *FD) {
1258 if (!FD)
1259 return;
1260
Jordan Rose4531b7d2012-07-02 19:27:43 +00001261 assert(Summ && "Must have a summary to add annotations to.");
1262 RetainSummaryTemplate Template(Summ, *this);
Jordy Rose4df54fe2011-08-23 04:27:15 +00001263
Ted Kremenek11fe1752011-01-27 18:43:03 +00001264 // Effects on the parameters.
1265 unsigned parm_idx = 0;
1266 for (FunctionDecl::param_const_iterator pi = FD->param_begin(),
John McCall98b8f162011-04-06 09:02:12 +00001267 pe = FD->param_end(); pi != pe; ++pi, ++parm_idx) {
Ted Kremenek11fe1752011-01-27 18:43:03 +00001268 const ParmVarDecl *pd = *pi;
1269 if (pd->getAttr<NSConsumedAttr>()) {
Jordy Rose4df54fe2011-08-23 04:27:15 +00001270 if (!GCEnabled) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001271 Template->addArg(AF, parm_idx, DecRef);
Jordy Rose4df54fe2011-08-23 04:27:15 +00001272 }
1273 } else if (pd->getAttr<CFConsumedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001274 Template->addArg(AF, parm_idx, DecRef);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001275 }
1276 }
1277
Ted Kremenekb04cb592009-06-11 18:17:24 +00001278 QualType RetTy = FD->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00001279
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001280 // Determine if there is a special return effect for this method.
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001281 if (cocoa::isCocoaObjectRef(RetTy)) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001282 if (FD->getAttr<NSReturnsRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001283 Template->setRetEffect(ObjCAllocRetE);
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001284 }
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001285 else if (FD->getAttr<CFReturnsRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001286 Template->setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenekb04cb592009-06-11 18:17:24 +00001287 }
Ted Kremenek60411112010-02-18 00:06:12 +00001288 else if (FD->getAttr<NSReturnsNotRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001289 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::ObjC));
Ted Kremenek60411112010-02-18 00:06:12 +00001290 }
1291 else if (FD->getAttr<CFReturnsNotRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001292 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::CF));
Jordy Rose4df54fe2011-08-23 04:27:15 +00001293 }
1294 } else if (RetTy->getAs<PointerType>()) {
1295 if (FD->getAttr<CFReturnsRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001296 Template->setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
Jordy Rose4df54fe2011-08-23 04:27:15 +00001297 }
1298 else if (FD->getAttr<CFReturnsNotRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001299 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::CF));
Ted Kremenek60411112010-02-18 00:06:12 +00001300 }
Ted Kremenekb04cb592009-06-11 18:17:24 +00001301 }
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001302}
1303
1304void
Ted Kremenek93edbc52011-10-05 23:54:29 +00001305RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
1306 const ObjCMethodDecl *MD) {
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001307 if (!MD)
1308 return;
1309
Jordan Rose4531b7d2012-07-02 19:27:43 +00001310 assert(Summ && "Must have a valid summary to add annotations to");
1311 RetainSummaryTemplate Template(Summ, *this);
Ted Kremenek6d4b76d2009-07-06 18:30:43 +00001312 bool isTrackedLoc = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001313
Ted Kremenek12b94342011-01-27 06:54:14 +00001314 // Effects on the receiver.
1315 if (MD->getAttr<NSConsumesSelfAttr>()) {
Ted Kremenek11fe1752011-01-27 18:43:03 +00001316 if (!GCEnabled)
Jordy Rose0fe62f82011-08-24 09:02:37 +00001317 Template->setReceiverEffect(DecRefMsg);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001318 }
1319
1320 // Effects on the parameters.
1321 unsigned parm_idx = 0;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00001322 for (ObjCMethodDecl::param_const_iterator
1323 pi=MD->param_begin(), pe=MD->param_end();
Ted Kremenek11fe1752011-01-27 18:43:03 +00001324 pi != pe; ++pi, ++parm_idx) {
1325 const ParmVarDecl *pd = *pi;
1326 if (pd->getAttr<NSConsumedAttr>()) {
1327 if (!GCEnabled)
Jordy Rose0fe62f82011-08-24 09:02:37 +00001328 Template->addArg(AF, parm_idx, DecRef);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001329 }
1330 else if(pd->getAttr<CFConsumedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001331 Template->addArg(AF, parm_idx, DecRef);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001332 }
Ted Kremenek12b94342011-01-27 06:54:14 +00001333 }
1334
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001335 // Determine if there is a special return effect for this method.
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001336 if (cocoa::isCocoaObjectRef(MD->getResultType())) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001337 if (MD->getAttr<NSReturnsRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001338 Template->setRetEffect(ObjCAllocRetE);
Ted Kremenek6d4b76d2009-07-06 18:30:43 +00001339 return;
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001340 }
Ted Kremenek60411112010-02-18 00:06:12 +00001341 if (MD->getAttr<NSReturnsNotRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001342 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::ObjC));
Ted Kremenek60411112010-02-18 00:06:12 +00001343 return;
1344 }
Mike Stump1eb44332009-09-09 15:08:12 +00001345
Ted Kremenek6d4b76d2009-07-06 18:30:43 +00001346 isTrackedLoc = true;
Jordy Rose0fe62f82011-08-24 09:02:37 +00001347 } else {
Ted Kremenek6217b802009-07-29 21:53:49 +00001348 isTrackedLoc = MD->getResultType()->getAs<PointerType>() != NULL;
Jordy Rose0fe62f82011-08-24 09:02:37 +00001349 }
Mike Stump1eb44332009-09-09 15:08:12 +00001350
Ted Kremenek60411112010-02-18 00:06:12 +00001351 if (isTrackedLoc) {
1352 if (MD->getAttr<CFReturnsRetainedAttr>())
Jordy Rose0fe62f82011-08-24 09:02:37 +00001353 Template->setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenek60411112010-02-18 00:06:12 +00001354 else if (MD->getAttr<CFReturnsNotRetainedAttr>())
Jordy Rose0fe62f82011-08-24 09:02:37 +00001355 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::CF));
Ted Kremenek60411112010-02-18 00:06:12 +00001356 }
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001357}
1358
Ted Kremenek93edbc52011-10-05 23:54:29 +00001359const RetainSummary *
Jordy Rosef3aae582012-03-17 21:13:07 +00001360RetainSummaryManager::getStandardMethodSummary(const ObjCMethodDecl *MD,
1361 Selector S, QualType RetTy) {
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001362
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +00001363 if (MD) {
Ted Kremenek376d1e72009-04-24 18:00:17 +00001364 // Scan the method decl for 'void*' arguments. These should be treated
1365 // as 'StopTracking' because they are often used with delegates.
1366 // Delegates are a frequent form of false positives with the retain
1367 // count checker.
1368 unsigned i = 0;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00001369 for (ObjCMethodDecl::param_const_iterator I = MD->param_begin(),
Ted Kremenek376d1e72009-04-24 18:00:17 +00001370 E = MD->param_end(); I != E; ++I, ++i)
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00001371 if (const ParmVarDecl *PD = *I) {
Ted Kremenek376d1e72009-04-24 18:00:17 +00001372 QualType Ty = Ctx.getCanonicalType(PD->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001373 if (Ty.getLocalUnqualifiedType() == Ctx.VoidPtrTy)
Ted Kremenek3baf6722010-11-24 00:54:37 +00001374 ScratchArgs = AF.add(ScratchArgs, i, StopTracking);
Ted Kremenek376d1e72009-04-24 18:00:17 +00001375 }
1376 }
Mike Stump1eb44332009-09-09 15:08:12 +00001377
Jordy Rosee921b1a2012-03-17 19:53:04 +00001378 // Any special effects?
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001379 ArgEffect ReceiverEff = DoNothing;
Jordy Rosee921b1a2012-03-17 19:53:04 +00001380 RetEffect ResultEff = RetEffect::MakeNoRet();
1381
1382 // Check the method family, and apply any default annotations.
1383 switch (MD ? MD->getMethodFamily() : S.getMethodFamily()) {
1384 case OMF_None:
1385 case OMF_performSelector:
1386 // Assume all Objective-C methods follow Cocoa Memory Management rules.
1387 // FIXME: Does the non-threaded performSelector family really belong here?
1388 // The selector could be, say, @selector(copy).
1389 if (cocoa::isCocoaObjectRef(RetTy))
1390 ResultEff = RetEffect::MakeNotOwned(RetEffect::ObjC);
1391 else if (coreFoundation::isCFObjectRef(RetTy)) {
1392 // ObjCMethodDecl currently doesn't consider CF objects as valid return
1393 // values for alloc, new, copy, or mutableCopy, so we have to
1394 // double-check with the selector. This is ugly, but there aren't that
1395 // many Objective-C methods that return CF objects, right?
1396 if (MD) {
1397 switch (S.getMethodFamily()) {
1398 case OMF_alloc:
1399 case OMF_new:
1400 case OMF_copy:
1401 case OMF_mutableCopy:
1402 ResultEff = RetEffect::MakeOwned(RetEffect::CF, true);
1403 break;
1404 default:
1405 ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1406 break;
1407 }
1408 } else {
1409 ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1410 }
1411 }
1412 break;
1413 case OMF_init:
1414 ResultEff = ObjCInitRetE;
1415 ReceiverEff = DecRefMsg;
1416 break;
1417 case OMF_alloc:
1418 case OMF_new:
1419 case OMF_copy:
1420 case OMF_mutableCopy:
1421 if (cocoa::isCocoaObjectRef(RetTy))
1422 ResultEff = ObjCAllocRetE;
1423 else if (coreFoundation::isCFObjectRef(RetTy))
1424 ResultEff = RetEffect::MakeOwned(RetEffect::CF, true);
1425 break;
1426 case OMF_autorelease:
1427 ReceiverEff = Autorelease;
1428 break;
1429 case OMF_retain:
1430 ReceiverEff = IncRefMsg;
1431 break;
1432 case OMF_release:
1433 ReceiverEff = DecRefMsg;
1434 break;
1435 case OMF_dealloc:
1436 ReceiverEff = Dealloc;
1437 break;
1438 case OMF_self:
1439 // -self is handled specially by the ExprEngine to propagate the receiver.
1440 break;
1441 case OMF_retainCount:
1442 case OMF_finalize:
1443 // These methods don't return objects.
1444 break;
1445 }
Mike Stump1eb44332009-09-09 15:08:12 +00001446
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001447 // If one of the arguments in the selector has the keyword 'delegate' we
1448 // should stop tracking the reference count for the receiver. This is
1449 // because the reference count is quite possibly handled by a delegate
1450 // method.
1451 if (S.isKeywordSelector()) {
Jordan Rose50571a92012-06-15 18:19:52 +00001452 for (unsigned i = 0, e = S.getNumArgs(); i != e; ++i) {
1453 StringRef Slot = S.getNameForSlot(i);
1454 if (Slot.substr(Slot.size() - 8).equals_lower("delegate")) {
1455 if (ResultEff == ObjCInitRetE)
1456 ResultEff = RetEffect::MakeNoRet();
1457 else
1458 ReceiverEff = StopTracking;
1459 }
1460 }
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001461 }
Mike Stump1eb44332009-09-09 15:08:12 +00001462
Jordy Rosee921b1a2012-03-17 19:53:04 +00001463 if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing &&
1464 ResultEff.getKind() == RetEffect::NoRet)
Ted Kremenek93edbc52011-10-05 23:54:29 +00001465 return getDefaultSummary();
Mike Stump1eb44332009-09-09 15:08:12 +00001466
Jordy Rosee921b1a2012-03-17 19:53:04 +00001467 return getPersistentSummary(ResultEff, ReceiverEff, MayEscape);
Ted Kremenek250b1fa2009-04-23 23:08:22 +00001468}
1469
Ted Kremenek93edbc52011-10-05 23:54:29 +00001470const RetainSummary *
Jordan Rosecde8cdb2012-07-02 19:27:56 +00001471RetainSummaryManager::getInstanceMethodSummary(const ObjCMethodCall &Msg,
Jordan Rose4531b7d2012-07-02 19:27:43 +00001472 ProgramStateRef State) {
1473 const ObjCInterfaceDecl *ReceiverClass = 0;
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001474
Jordan Rose4531b7d2012-07-02 19:27:43 +00001475 // We do better tracking of the type of the object than the core ExprEngine.
1476 // See if we have its type in our private state.
1477 // FIXME: Eventually replace the use of state->get<RefBindings> with
1478 // a generic API for reasoning about the Objective-C types of symbolic
1479 // objects.
1480 SVal ReceiverV = Msg.getReceiverSVal();
1481 if (SymbolRef Sym = ReceiverV.getAsLocSymbol())
Anna Zaks8d6b43c2012-08-14 00:36:15 +00001482 if (const RefVal *T = getRefBinding(State, Sym))
Douglas Gregor04badcf2010-04-21 00:45:42 +00001483 if (const ObjCObjectPointerType *PT =
Jordan Rose4531b7d2012-07-02 19:27:43 +00001484 T->getType()->getAs<ObjCObjectPointerType>())
1485 ReceiverClass = PT->getInterfaceDecl();
1486
1487 // If we don't know what kind of object this is, fall back to its static type.
1488 if (!ReceiverClass)
1489 ReceiverClass = Msg.getReceiverInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00001490
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001491 // FIXME: The receiver could be a reference to a class, meaning that
1492 // we should use the class method.
Jordan Rose4531b7d2012-07-02 19:27:43 +00001493 // id x = [NSObject class];
1494 // [x performSelector:... withObject:... afterDelay:...];
1495 Selector S = Msg.getSelector();
1496 const ObjCMethodDecl *Method = Msg.getDecl();
1497 if (!Method && ReceiverClass)
1498 Method = ReceiverClass->getInstanceMethod(S);
1499
1500 return getMethodSummary(S, ReceiverClass, Method, Msg.getResultType(),
1501 ObjCMethodSummaries);
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001502}
1503
Ted Kremenek93edbc52011-10-05 23:54:29 +00001504const RetainSummary *
Jordan Rose4531b7d2012-07-02 19:27:43 +00001505RetainSummaryManager::getMethodSummary(Selector S, const ObjCInterfaceDecl *ID,
Jordy Rosef3aae582012-03-17 21:13:07 +00001506 const ObjCMethodDecl *MD, QualType RetTy,
1507 ObjCMethodSummariesTy &CachedSummaries) {
Ted Kremenek1bffd742008-05-06 15:44:25 +00001508
Ted Kremenek8711c032009-04-29 05:04:30 +00001509 // Look up a summary in our summary cache.
Jordan Rose4531b7d2012-07-02 19:27:43 +00001510 const RetainSummary *Summ = CachedSummaries.find(ID, S);
Mike Stump1eb44332009-09-09 15:08:12 +00001511
Ted Kremenek614cc542009-07-21 23:27:57 +00001512 if (!Summ) {
Jordy Rosef3aae582012-03-17 21:13:07 +00001513 Summ = getStandardMethodSummary(MD, S, RetTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001514
Ted Kremenek614cc542009-07-21 23:27:57 +00001515 // Annotations override defaults.
Jordy Rose4df54fe2011-08-23 04:27:15 +00001516 updateSummaryFromAnnotations(Summ, MD);
Mike Stump1eb44332009-09-09 15:08:12 +00001517
Ted Kremenek614cc542009-07-21 23:27:57 +00001518 // Memoize the summary.
Jordan Rose4531b7d2012-07-02 19:27:43 +00001519 CachedSummaries[ObjCSummaryKey(ID, S)] = Summ;
Ted Kremenek614cc542009-07-21 23:27:57 +00001520 }
Mike Stump1eb44332009-09-09 15:08:12 +00001521
Ted Kremeneke87450e2009-04-23 19:11:35 +00001522 return Summ;
Ted Kremenekc8395602008-05-06 21:26:51 +00001523}
1524
Mike Stump1eb44332009-09-09 15:08:12 +00001525void RetainSummaryManager::InitializeClassMethodSummaries() {
Ted Kremenekec315332009-05-07 23:40:42 +00001526 assert(ScratchArgs.isEmpty());
Mike Stump1eb44332009-09-09 15:08:12 +00001527 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek6fe2b7a2009-10-15 22:25:12 +00001528 addClassMethSummary("NSAssertionHandler", "currentHandler",
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001529 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Mike Stump1eb44332009-09-09 15:08:12 +00001530
Ted Kremenek6d348932008-10-21 15:53:15 +00001531 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001532 ScratchArgs = AF.add(ScratchArgs, 0, Autorelease);
Ted Kremenek6fe2b7a2009-10-15 22:25:12 +00001533 addClassMethSummary("NSAutoreleasePool", "addObject",
1534 getPersistentSummary(RetEffect::MakeNoRet(),
1535 DoNothing, Autorelease));
Ted Kremenek9c32d082008-05-06 00:30:21 +00001536}
1537
Ted Kremenek1f180c32008-06-23 22:21:20 +00001538void RetainSummaryManager::InitializeMethodSummaries() {
Mike Stump1eb44332009-09-09 15:08:12 +00001539
1540 assert (ScratchArgs.isEmpty());
1541
Ted Kremenekc8395602008-05-06 21:26:51 +00001542 // Create the "init" selector. It just acts as a pass-through for the
1543 // receiver.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001544 const RetainSummary *InitSumm = getPersistentSummary(ObjCInitRetE, DecRefMsg);
Ted Kremenekac02f202009-08-20 05:13:36 +00001545 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
1546
1547 // awakeAfterUsingCoder: behaves basically like an 'init' method. It
1548 // claims the receiver and returns a retained object.
1549 addNSObjectMethSummary(GetUnarySelector("awakeAfterUsingCoder", Ctx),
1550 InitSumm);
Mike Stump1eb44332009-09-09 15:08:12 +00001551
Ted Kremenekc8395602008-05-06 21:26:51 +00001552 // The next methods are allocators.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001553 const RetainSummary *AllocSumm = getPersistentSummary(ObjCAllocRetE);
1554 const RetainSummary *CFAllocSumm =
Ted Kremeneka834fb42009-08-28 19:52:12 +00001555 getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Mike Stump1eb44332009-09-09 15:08:12 +00001556
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001557 // Create the "retain" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001558 RetEffect NoRet = RetEffect::MakeNoRet();
Ted Kremenek93edbc52011-10-05 23:54:29 +00001559 const RetainSummary *Summ = getPersistentSummary(NoRet, IncRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001560 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001561
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001562 // Create the "release" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001563 Summ = getPersistentSummary(NoRet, DecRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001564 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001565
Ted Kremenek299e8152008-05-07 21:17:39 +00001566 // Create the "drain" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001567 Summ = getPersistentSummary(NoRet, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek553cf182008-06-25 21:21:56 +00001568 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001569
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001570 // Create the -dealloc summary.
Jordy Rose500abad2011-08-21 19:41:36 +00001571 Summ = getPersistentSummary(NoRet, Dealloc);
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001572 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001573
1574 // Create the "autorelease" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001575 Summ = getPersistentSummary(NoRet, Autorelease);
Ted Kremenek553cf182008-06-25 21:21:56 +00001576 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001577
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00001578 // Specially handle NSAutoreleasePool.
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001579 addInstMethSummary("NSAutoreleasePool", "init",
Jordy Rose500abad2011-08-21 19:41:36 +00001580 getPersistentSummary(NoRet, NewAutoreleasePool));
Mike Stump1eb44332009-09-09 15:08:12 +00001581
1582 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremenek89e202d2009-02-23 02:51:29 +00001583 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1584 // self-own themselves. However, they only do this once they are displayed.
1585 // Thus, we need to track an NSWindow's display status.
1586 // This is tracked in <rdar://problem/6062711>.
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +00001587 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001588 const RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenek78a35a32009-05-12 20:06:54 +00001589 StopTracking,
1590 StopTracking);
Mike Stump1eb44332009-09-09 15:08:12 +00001591
Ted Kremenek99d02692009-04-03 19:02:51 +00001592 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1593
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +00001594#if 0
Ted Kremenek78a35a32009-05-12 20:06:54 +00001595 addInstMethSummary("NSWindow", NoTrackYet, "initWithContentRect",
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001596 "styleMask", "backing", "defer", NULL);
Mike Stump1eb44332009-09-09 15:08:12 +00001597
Ted Kremenek78a35a32009-05-12 20:06:54 +00001598 addInstMethSummary("NSWindow", NoTrackYet, "initWithContentRect",
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001599 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +00001600#endif
Mike Stump1eb44332009-09-09 15:08:12 +00001601
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001602 // For NSPanel (which subclasses NSWindow), allocated objects are not
1603 // self-owned.
Ted Kremenek99d02692009-04-03 19:02:51 +00001604 // FIXME: For now we don't track NSPanels. object for the same reason
1605 // as for NSWindow objects.
1606 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
Mike Stump1eb44332009-09-09 15:08:12 +00001607
Ted Kremenek78a35a32009-05-12 20:06:54 +00001608#if 0
1609 addInstMethSummary("NSPanel", NoTrackYet, "initWithContentRect",
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001610 "styleMask", "backing", "defer", NULL);
Mike Stump1eb44332009-09-09 15:08:12 +00001611
Ted Kremenek78a35a32009-05-12 20:06:54 +00001612 addInstMethSummary("NSPanel", NoTrackYet, "initWithContentRect",
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001613 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek78a35a32009-05-12 20:06:54 +00001614#endif
Mike Stump1eb44332009-09-09 15:08:12 +00001615
Ted Kremenekba67f6a2009-05-18 23:14:34 +00001616 // Don't track allocated autorelease pools yet, as it is okay to prematurely
1617 // exit a method.
1618 addClassMethSummary("NSAutoreleasePool", "alloc", NoTrackYet);
Ted Kremeneka9797122012-02-18 21:37:48 +00001619 addClassMethSummary("NSAutoreleasePool", "allocWithZone", NoTrackYet, false);
Ted Kremenek553cf182008-06-25 21:21:56 +00001620
Ted Kremenek767d6492009-05-20 22:39:57 +00001621 // Create summaries QCRenderer/QCView -createSnapShotImageOfType:
1622 addInstMethSummary("QCRenderer", AllocSumm,
1623 "createSnapshotImageOfType", NULL);
1624 addInstMethSummary("QCView", AllocSumm,
1625 "createSnapshotImageOfType", NULL);
1626
Ted Kremenek211a9c62009-06-15 20:58:58 +00001627 // Create summaries for CIContext, 'createCGImage' and
Ted Kremeneka834fb42009-08-28 19:52:12 +00001628 // 'createCGLayerWithSize'. These objects are CF objects, and are not
1629 // automatically garbage collected.
1630 addInstMethSummary("CIContext", CFAllocSumm,
Ted Kremenek767d6492009-05-20 22:39:57 +00001631 "createCGImage", "fromRect", NULL);
Ted Kremeneka834fb42009-08-28 19:52:12 +00001632 addInstMethSummary("CIContext", CFAllocSumm,
Mike Stump1eb44332009-09-09 15:08:12 +00001633 "createCGImage", "fromRect", "format", "colorSpace", NULL);
Ted Kremeneka834fb42009-08-28 19:52:12 +00001634 addInstMethSummary("CIContext", CFAllocSumm, "createCGLayerWithSize",
Ted Kremenek211a9c62009-06-15 20:58:58 +00001635 "info", NULL);
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001636}
1637
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001638//===----------------------------------------------------------------------===//
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001639// AutoreleaseBindings - State used to track objects in autorelease pools.
Ted Kremenek6d348932008-10-21 15:53:15 +00001640//===----------------------------------------------------------------------===//
1641
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001642typedef llvm::ImmutableMap<SymbolRef, unsigned> ARCounts;
1643typedef llvm::ImmutableMap<SymbolRef, ARCounts> ARPoolContents;
1644typedef llvm::ImmutableList<SymbolRef> ARStack;
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00001645
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001646static int AutoRCIndex = 0;
Ted Kremenek6d348932008-10-21 15:53:15 +00001647static int AutoRBIndex = 0;
1648
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001649namespace { class AutoreleasePoolContents {}; }
1650namespace { class AutoreleaseStack {}; }
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001651
Ted Kremenek6d348932008-10-21 15:53:15 +00001652namespace clang {
Ted Kremenek9ef65372010-12-23 07:20:52 +00001653namespace ento {
Ted Kremenek18c66fd2011-08-15 22:09:50 +00001654template<> struct ProgramStateTrait<AutoreleaseStack>
1655 : public ProgramStatePartialTrait<ARStack> {
Ted Kremenek9c378f72011-08-12 23:37:29 +00001656 static inline void *GDMIndex() { return &AutoRBIndex; }
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001657};
1658
Ted Kremenek18c66fd2011-08-15 22:09:50 +00001659template<> struct ProgramStateTrait<AutoreleasePoolContents>
1660 : public ProgramStatePartialTrait<ARPoolContents> {
Ted Kremenek9c378f72011-08-12 23:37:29 +00001661 static inline void *GDMIndex() { return &AutoRCIndex; }
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001662};
Argyrios Kyrtzidis5a4f98f2010-12-22 18:53:20 +00001663} // end GR namespace
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001664} // end clang namespace
Ted Kremenek6d348932008-10-21 15:53:15 +00001665
Ted Kremenek8bef8232012-01-26 21:29:00 +00001666static SymbolRef GetCurrentAutoreleasePool(ProgramStateRef state) {
Ted Kremenek7037ab82009-03-20 17:34:15 +00001667 ARStack stack = state->get<AutoreleaseStack>();
1668 return stack.isEmpty() ? SymbolRef() : stack.getHead();
1669}
1670
Ted Kremenek8bef8232012-01-26 21:29:00 +00001671static ProgramStateRef
1672SendAutorelease(ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +00001673 ARCounts::Factory &F,
1674 SymbolRef sym) {
Ted Kremenek7037ab82009-03-20 17:34:15 +00001675 SymbolRef pool = GetCurrentAutoreleasePool(state);
Ted Kremenekb65be702009-06-18 01:23:53 +00001676 const ARCounts *cnts = state->get<AutoreleasePoolContents>(pool);
Ted Kremenek7037ab82009-03-20 17:34:15 +00001677 ARCounts newCnts(0);
Mike Stump1eb44332009-09-09 15:08:12 +00001678
Ted Kremenek7037ab82009-03-20 17:34:15 +00001679 if (cnts) {
1680 const unsigned *cnt = (*cnts).lookup(sym);
Ted Kremenek3baf6722010-11-24 00:54:37 +00001681 newCnts = F.add(*cnts, sym, cnt ? *cnt + 1 : 1);
Ted Kremenek7037ab82009-03-20 17:34:15 +00001682 }
1683 else
Ted Kremenek3baf6722010-11-24 00:54:37 +00001684 newCnts = F.add(F.getEmptyMap(), sym, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001685
Ted Kremenekb65be702009-06-18 01:23:53 +00001686 return state->set<AutoreleasePoolContents>(pool, newCnts);
Ted Kremenek7037ab82009-03-20 17:34:15 +00001687}
1688
Ted Kremenek13922612008-04-16 20:40:59 +00001689//===----------------------------------------------------------------------===//
Ted Kremenekc887d132009-04-29 18:50:19 +00001690// Error reporting.
1691//===----------------------------------------------------------------------===//
Ted Kremenekc887d132009-04-29 18:50:19 +00001692namespace {
Jordy Roseec9ef852011-08-23 20:55:48 +00001693 typedef llvm::DenseMap<const ExplodedNode *, const RetainSummary *>
1694 SummaryLogTy;
1695
Ted Kremenekc887d132009-04-29 18:50:19 +00001696 //===-------------===//
1697 // Bug Descriptions. //
Mike Stump1eb44332009-09-09 15:08:12 +00001698 //===-------------===//
1699
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001700 class CFRefBug : public BugType {
Ted Kremenekc887d132009-04-29 18:50:19 +00001701 protected:
Jordy Rose35c86952011-08-24 05:47:39 +00001702 CFRefBug(StringRef name)
Ted Kremenek6fd45052012-04-05 20:43:28 +00001703 : BugType(name, categories::MemoryCoreFoundationObjectiveC) {}
Ted Kremenekc887d132009-04-29 18:50:19 +00001704 public:
Mike Stump1eb44332009-09-09 15:08:12 +00001705
Ted Kremenekc887d132009-04-29 18:50:19 +00001706 // FIXME: Eventually remove.
Jordy Rose35c86952011-08-24 05:47:39 +00001707 virtual const char *getDescription() const = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001708
Ted Kremenekc887d132009-04-29 18:50:19 +00001709 virtual bool isLeak() const { return false; }
1710 };
Mike Stump1eb44332009-09-09 15:08:12 +00001711
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001712 class UseAfterRelease : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001713 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001714 UseAfterRelease() : CFRefBug("Use-after-release") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001715
Jordy Rose35c86952011-08-24 05:47:39 +00001716 const char *getDescription() const {
Ted Kremenekc887d132009-04-29 18:50:19 +00001717 return "Reference-counted object is used after it is released";
Mike Stump1eb44332009-09-09 15:08:12 +00001718 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001719 };
Mike Stump1eb44332009-09-09 15:08:12 +00001720
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001721 class BadRelease : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001722 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001723 BadRelease() : CFRefBug("Bad release") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001724
Jordy Rose35c86952011-08-24 05:47:39 +00001725 const char *getDescription() const {
Ted Kremenekbb206fd2009-10-01 17:31:50 +00001726 return "Incorrect decrement of the reference count of an object that is "
1727 "not owned at this point by the caller";
Ted Kremenekc887d132009-04-29 18:50:19 +00001728 }
1729 };
Mike Stump1eb44332009-09-09 15:08:12 +00001730
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001731 class DeallocGC : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001732 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001733 DeallocGC()
1734 : CFRefBug("-dealloc called while using garbage collection") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001735
Ted Kremenekc887d132009-04-29 18:50:19 +00001736 const char *getDescription() const {
Ted Kremenek369de562009-05-09 00:10:05 +00001737 return "-dealloc called while using garbage collection";
Ted Kremenekc887d132009-04-29 18:50:19 +00001738 }
1739 };
Mike Stump1eb44332009-09-09 15:08:12 +00001740
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001741 class DeallocNotOwned : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001742 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001743 DeallocNotOwned()
1744 : CFRefBug("-dealloc sent to non-exclusively owned object") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001745
Ted Kremenekc887d132009-04-29 18:50:19 +00001746 const char *getDescription() const {
1747 return "-dealloc sent to object that may be referenced elsewhere";
1748 }
Mike Stump1eb44332009-09-09 15:08:12 +00001749 };
1750
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001751 class OverAutorelease : public CFRefBug {
Ted Kremenek369de562009-05-09 00:10:05 +00001752 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001753 OverAutorelease()
1754 : CFRefBug("Object sent -autorelease too many times") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001755
Ted Kremenek369de562009-05-09 00:10:05 +00001756 const char *getDescription() const {
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001757 return "Object sent -autorelease too many times";
Ted Kremenek369de562009-05-09 00:10:05 +00001758 }
1759 };
Mike Stump1eb44332009-09-09 15:08:12 +00001760
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001761 class ReturnedNotOwnedForOwned : public CFRefBug {
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001762 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001763 ReturnedNotOwnedForOwned()
1764 : CFRefBug("Method should return an owned object") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001765
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001766 const char *getDescription() const {
Jordy Rose5b5402b2011-07-15 22:17:54 +00001767 return "Object with a +0 retain count returned to caller where a +1 "
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001768 "(owning) retain count is expected";
1769 }
1770 };
Mike Stump1eb44332009-09-09 15:08:12 +00001771
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001772 class Leak : public CFRefBug {
Benjamin Kramerfacde172012-06-06 17:32:50 +00001773 public:
1774 Leak(StringRef name)
1775 : CFRefBug(name) {
Jordy Rosedb92bb62011-08-25 01:14:38 +00001776 // Leaks should not be reported if they are post-dominated by a sink.
1777 setSuppressOnSink(true);
1778 }
Mike Stump1eb44332009-09-09 15:08:12 +00001779
Jordy Rose35c86952011-08-24 05:47:39 +00001780 const char *getDescription() const { return ""; }
Mike Stump1eb44332009-09-09 15:08:12 +00001781
Ted Kremenekc887d132009-04-29 18:50:19 +00001782 bool isLeak() const { return true; }
1783 };
Mike Stump1eb44332009-09-09 15:08:12 +00001784
Ted Kremenekc887d132009-04-29 18:50:19 +00001785 //===---------===//
1786 // Bug Reports. //
1787 //===---------===//
Mike Stump1eb44332009-09-09 15:08:12 +00001788
Jordy Rose01153492012-03-24 02:45:35 +00001789 class CFRefReportVisitor : public BugReporterVisitorImpl<CFRefReportVisitor> {
Anna Zaks23f395e2011-08-20 01:27:22 +00001790 protected:
Anna Zaksdc757b02011-08-19 23:21:56 +00001791 SymbolRef Sym;
Jordy Roseec9ef852011-08-23 20:55:48 +00001792 const SummaryLogTy &SummaryLog;
Jordy Rose35c86952011-08-24 05:47:39 +00001793 bool GCEnabled;
Anna Zaks23f395e2011-08-20 01:27:22 +00001794
Anna Zaksdc757b02011-08-19 23:21:56 +00001795 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001796 CFRefReportVisitor(SymbolRef sym, bool gcEnabled, const SummaryLogTy &log)
1797 : Sym(sym), SummaryLog(log), GCEnabled(gcEnabled) {}
Anna Zaksdc757b02011-08-19 23:21:56 +00001798
Anna Zaks23f395e2011-08-20 01:27:22 +00001799 virtual void Profile(llvm::FoldingSetNodeID &ID) const {
Anna Zaksdc757b02011-08-19 23:21:56 +00001800 static int x = 0;
1801 ID.AddPointer(&x);
1802 ID.AddPointer(Sym);
1803 }
1804
Anna Zaks23f395e2011-08-20 01:27:22 +00001805 virtual PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
1806 const ExplodedNode *PrevN,
1807 BugReporterContext &BRC,
1808 BugReport &BR);
1809
1810 virtual PathDiagnosticPiece *getEndPath(BugReporterContext &BRC,
1811 const ExplodedNode *N,
1812 BugReport &BR);
1813 };
1814
1815 class CFRefLeakReportVisitor : public CFRefReportVisitor {
1816 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001817 CFRefLeakReportVisitor(SymbolRef sym, bool GCEnabled,
Jordy Roseec9ef852011-08-23 20:55:48 +00001818 const SummaryLogTy &log)
Jordy Rose35c86952011-08-24 05:47:39 +00001819 : CFRefReportVisitor(sym, GCEnabled, log) {}
Anna Zaks23f395e2011-08-20 01:27:22 +00001820
1821 PathDiagnosticPiece *getEndPath(BugReporterContext &BRC,
1822 const ExplodedNode *N,
1823 BugReport &BR);
Jordy Rose01153492012-03-24 02:45:35 +00001824
1825 virtual BugReporterVisitor *clone() const {
1826 // The curiously-recurring template pattern only works for one level of
1827 // subclassing. Rather than make a new template base for
1828 // CFRefReportVisitor, we simply override clone() to do the right thing.
1829 // This could be trouble someday if BugReporterVisitorImpl is ever
1830 // used for something else besides a convenient implementation of clone().
1831 return new CFRefLeakReportVisitor(*this);
1832 }
Anna Zaksdc757b02011-08-19 23:21:56 +00001833 };
1834
Anna Zakse172e8b2011-08-17 23:00:25 +00001835 class CFRefReport : public BugReport {
Jordy Rose20589562011-08-24 22:39:09 +00001836 void addGCModeDescription(const LangOptions &LOpts, bool GCEnabled);
Jordy Rose35c86952011-08-24 05:47:39 +00001837
Ted Kremenekc887d132009-04-29 18:50:19 +00001838 public:
Jordy Rose20589562011-08-24 22:39:09 +00001839 CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1840 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1841 bool registerVisitor = true)
Anna Zaksedf4dae2011-08-22 18:54:07 +00001842 : BugReport(D, D.getDescription(), n) {
Anna Zaks23f395e2011-08-20 01:27:22 +00001843 if (registerVisitor)
Jordy Rose20589562011-08-24 22:39:09 +00001844 addVisitor(new CFRefReportVisitor(sym, GCEnabled, Log));
1845 addGCModeDescription(LOpts, GCEnabled);
Anna Zaksdc757b02011-08-19 23:21:56 +00001846 }
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001847
Jordy Rose20589562011-08-24 22:39:09 +00001848 CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1849 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1850 StringRef endText)
Anna Zaksedf4dae2011-08-22 18:54:07 +00001851 : BugReport(D, D.getDescription(), endText, n) {
Jordy Rose20589562011-08-24 22:39:09 +00001852 addVisitor(new CFRefReportVisitor(sym, GCEnabled, Log));
1853 addGCModeDescription(LOpts, GCEnabled);
Anna Zaksdc757b02011-08-19 23:21:56 +00001854 }
Mike Stump1eb44332009-09-09 15:08:12 +00001855
Anna Zakse172e8b2011-08-17 23:00:25 +00001856 virtual std::pair<ranges_iterator, ranges_iterator> getRanges() {
Anna Zaksedf4dae2011-08-22 18:54:07 +00001857 const CFRefBug& BugTy = static_cast<CFRefBug&>(getBugType());
1858 if (!BugTy.isLeak())
Anna Zakse172e8b2011-08-17 23:00:25 +00001859 return BugReport::getRanges();
Ted Kremenekc887d132009-04-29 18:50:19 +00001860 else
Argyrios Kyrtzidis640ccf02010-12-04 01:12:15 +00001861 return std::make_pair(ranges_iterator(), ranges_iterator());
Ted Kremenekc887d132009-04-29 18:50:19 +00001862 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001863 };
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001864
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001865 class CFRefLeakReport : public CFRefReport {
Ted Kremenekc887d132009-04-29 18:50:19 +00001866 const MemRegion* AllocBinding;
Anna Zaks23f395e2011-08-20 01:27:22 +00001867
Ted Kremenekc887d132009-04-29 18:50:19 +00001868 public:
Jordy Rose20589562011-08-24 22:39:09 +00001869 CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1870 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
Anna Zaks6a93bd52011-10-25 19:57:11 +00001871 CheckerContext &Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001872
Anna Zaks590dd8e2011-09-20 21:38:35 +00001873 PathDiagnosticLocation getLocation(const SourceManager &SM) const {
1874 assert(Location.isValid());
1875 return Location;
1876 }
Mike Stump1eb44332009-09-09 15:08:12 +00001877 };
Ted Kremenekc887d132009-04-29 18:50:19 +00001878} // end anonymous namespace
1879
Jordy Rose20589562011-08-24 22:39:09 +00001880void CFRefReport::addGCModeDescription(const LangOptions &LOpts,
1881 bool GCEnabled) {
Jordy Rosef95b19d2011-08-24 20:38:42 +00001882 const char *GCModeDescription = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001883
Douglas Gregore289d812011-09-13 17:21:33 +00001884 switch (LOpts.getGC()) {
Anna Zaks7f2531c2011-08-22 20:31:28 +00001885 case LangOptions::GCOnly:
Jordy Rose20589562011-08-24 22:39:09 +00001886 assert(GCEnabled);
Jordy Rose35c86952011-08-24 05:47:39 +00001887 GCModeDescription = "Code is compiled to only use garbage collection";
1888 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001889
Anna Zaks7f2531c2011-08-22 20:31:28 +00001890 case LangOptions::NonGC:
Jordy Rose20589562011-08-24 22:39:09 +00001891 assert(!GCEnabled);
Jordy Rose35c86952011-08-24 05:47:39 +00001892 GCModeDescription = "Code is compiled to use reference counts";
1893 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001894
Anna Zaks7f2531c2011-08-22 20:31:28 +00001895 case LangOptions::HybridGC:
Jordy Rose20589562011-08-24 22:39:09 +00001896 if (GCEnabled) {
Jordy Rose35c86952011-08-24 05:47:39 +00001897 GCModeDescription = "Code is compiled to use either garbage collection "
1898 "(GC) or reference counts (non-GC). The bug occurs "
1899 "with GC enabled";
1900 break;
1901 } else {
1902 GCModeDescription = "Code is compiled to use either garbage collection "
1903 "(GC) or reference counts (non-GC). The bug occurs "
1904 "in non-GC mode";
1905 break;
Anna Zaks7f2531c2011-08-22 20:31:28 +00001906 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001907 }
Jordy Rose35c86952011-08-24 05:47:39 +00001908
Jordy Rosef95b19d2011-08-24 20:38:42 +00001909 assert(GCModeDescription && "invalid/unknown GC mode");
Jordy Rose35c86952011-08-24 05:47:39 +00001910 addExtraText(GCModeDescription);
Ted Kremenekc887d132009-04-29 18:50:19 +00001911}
1912
Jordy Rose910c4052011-09-02 06:44:22 +00001913// FIXME: This should be a method on SmallVector.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001914static inline bool contains(const SmallVectorImpl<ArgEffect>& V,
Ted Kremenekc887d132009-04-29 18:50:19 +00001915 ArgEffect X) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001916 for (SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
Ted Kremenekc887d132009-04-29 18:50:19 +00001917 I!=E; ++I)
1918 if (*I == X) return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001919
Ted Kremenekc887d132009-04-29 18:50:19 +00001920 return false;
1921}
1922
Jordy Rose70fdbc32012-05-12 05:10:43 +00001923static bool isNumericLiteralExpression(const Expr *E) {
1924 // FIXME: This set of cases was copied from SemaExprObjC.
1925 return isa<IntegerLiteral>(E) ||
1926 isa<CharacterLiteral>(E) ||
1927 isa<FloatingLiteral>(E) ||
1928 isa<ObjCBoolLiteralExpr>(E) ||
1929 isa<CXXBoolLiteralExpr>(E);
1930}
1931
Anna Zaksdc757b02011-08-19 23:21:56 +00001932PathDiagnosticPiece *CFRefReportVisitor::VisitNode(const ExplodedNode *N,
1933 const ExplodedNode *PrevN,
1934 BugReporterContext &BRC,
1935 BugReport &BR) {
Jordan Rose28038f32012-07-10 22:07:42 +00001936 // FIXME: We will eventually need to handle non-statement-based events
1937 // (__attribute__((cleanup))).
Jordy Rosef53e8c72011-08-23 19:43:16 +00001938 if (!isa<StmtPoint>(N->getLocation()))
Ted Kremenek2033a952009-05-13 07:12:33 +00001939 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001940
Ted Kremenek8966bc12009-05-06 21:39:49 +00001941 // Check if the type state has changed.
Ted Kremenek8bef8232012-01-26 21:29:00 +00001942 ProgramStateRef PrevSt = PrevN->getState();
1943 ProgramStateRef CurrSt = N->getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001944 const LocationContext *LCtx = N->getLocationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00001945
Anna Zaks8d6b43c2012-08-14 00:36:15 +00001946 const RefVal* CurrT = getRefBinding(CurrSt, Sym);
Ted Kremenekc887d132009-04-29 18:50:19 +00001947 if (!CurrT) return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001948
Ted Kremenekb65be702009-06-18 01:23:53 +00001949 const RefVal &CurrV = *CurrT;
Anna Zaks8d6b43c2012-08-14 00:36:15 +00001950 const RefVal *PrevT = getRefBinding(PrevSt, Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00001951
Ted Kremenekc887d132009-04-29 18:50:19 +00001952 // Create a string buffer to constain all the useful things we want
1953 // to tell the user.
1954 std::string sbuf;
1955 llvm::raw_string_ostream os(sbuf);
Mike Stump1eb44332009-09-09 15:08:12 +00001956
Ted Kremenekc887d132009-04-29 18:50:19 +00001957 // This is the allocation site since the previous node had no bindings
1958 // for this symbol.
1959 if (!PrevT) {
Jordy Rosef53e8c72011-08-23 19:43:16 +00001960 const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
Mike Stump1eb44332009-09-09 15:08:12 +00001961
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001962 if (isa<ObjCArrayLiteral>(S)) {
1963 os << "NSArray literal is an object with a +0 retain count";
Mike Stump1eb44332009-09-09 15:08:12 +00001964 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001965 else if (isa<ObjCDictionaryLiteral>(S)) {
1966 os << "NSDictionary literal is an object with a +0 retain count";
Ted Kremenekc887d132009-04-29 18:50:19 +00001967 }
Jordy Rose70fdbc32012-05-12 05:10:43 +00001968 else if (const ObjCBoxedExpr *BL = dyn_cast<ObjCBoxedExpr>(S)) {
1969 if (isNumericLiteralExpression(BL->getSubExpr()))
1970 os << "NSNumber literal is an object with a +0 retain count";
1971 else {
1972 const ObjCInterfaceDecl *BoxClass = 0;
1973 if (const ObjCMethodDecl *Method = BL->getBoxingMethod())
1974 BoxClass = Method->getClassInterface();
1975
1976 // We should always be able to find the boxing class interface,
1977 // but consider this future-proofing.
1978 if (BoxClass)
1979 os << *BoxClass << " b";
1980 else
1981 os << "B";
1982
1983 os << "oxed expression produces an object with a +0 retain count";
1984 }
1985 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001986 else {
1987 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
1988 // Get the name of the callee (if it is available).
1989 SVal X = CurrSt->getSValAsScalarOrLoc(CE->getCallee(), LCtx);
1990 if (const FunctionDecl *FD = X.getAsFunctionDecl())
1991 os << "Call to function '" << *FD << '\'';
1992 else
1993 os << "function call";
Ted Kremenekc887d132009-04-29 18:50:19 +00001994 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001995 else {
Jordan Rose8919e682012-07-18 21:59:51 +00001996 assert(isa<ObjCMessageExpr>(S));
Jordan Rosed563d3f2012-07-30 20:22:09 +00001997 CallEventManager &Mgr = CurrSt->getStateManager().getCallEventManager();
1998 CallEventRef<ObjCMethodCall> Call
1999 = Mgr.getObjCMethodCall(cast<ObjCMessageExpr>(S), CurrSt, LCtx);
2000
2001 switch (Call->getMessageKind()) {
Jordan Rose8919e682012-07-18 21:59:51 +00002002 case OCM_Message:
2003 os << "Method";
2004 break;
2005 case OCM_PropertyAccess:
2006 os << "Property";
2007 break;
2008 case OCM_Subscript:
2009 os << "Subscript";
2010 break;
2011 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002012 }
2013
2014 if (CurrV.getObjKind() == RetEffect::CF) {
2015 os << " returns a Core Foundation object with a ";
2016 }
2017 else {
2018 assert (CurrV.getObjKind() == RetEffect::ObjC);
2019 os << " returns an Objective-C object with a ";
2020 }
2021
2022 if (CurrV.isOwned()) {
2023 os << "+1 retain count";
2024
2025 if (GCEnabled) {
2026 assert(CurrV.getObjKind() == RetEffect::CF);
2027 os << ". "
2028 "Core Foundation objects are not automatically garbage collected.";
2029 }
2030 }
2031 else {
2032 assert (CurrV.isNotOwned());
2033 os << "+0 retain count";
2034 }
Ted Kremenekc887d132009-04-29 18:50:19 +00002035 }
Mike Stump1eb44332009-09-09 15:08:12 +00002036
Anna Zaks220ac8c2011-09-15 01:08:34 +00002037 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
2038 N->getLocationContext());
Ted Kremenekc887d132009-04-29 18:50:19 +00002039 return new PathDiagnosticEventPiece(Pos, os.str());
2040 }
Mike Stump1eb44332009-09-09 15:08:12 +00002041
Ted Kremenekc887d132009-04-29 18:50:19 +00002042 // Gather up the effects that were performed on the object at this
2043 // program point
Chris Lattner5f9e2722011-07-23 10:55:15 +00002044 SmallVector<ArgEffect, 2> AEffects;
Mike Stump1eb44332009-09-09 15:08:12 +00002045
Jordy Roseec9ef852011-08-23 20:55:48 +00002046 const ExplodedNode *OrigNode = BRC.getNodeResolver().getOriginalNode(N);
2047 if (const RetainSummary *Summ = SummaryLog.lookup(OrigNode)) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002048 // We only have summaries attached to nodes after evaluating CallExpr and
2049 // ObjCMessageExprs.
Jordy Rosef53e8c72011-08-23 19:43:16 +00002050 const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
Mike Stump1eb44332009-09-09 15:08:12 +00002051
Ted Kremenek5f85e172009-07-22 22:35:28 +00002052 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002053 // Iterate through the parameter expressions and see if the symbol
2054 // was ever passed as an argument.
2055 unsigned i = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002056
Ted Kremenek5f85e172009-07-22 22:35:28 +00002057 for (CallExpr::const_arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
Ted Kremenekc887d132009-04-29 18:50:19 +00002058 AI!=AE; ++AI, ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002059
Ted Kremenekc887d132009-04-29 18:50:19 +00002060 // Retrieve the value of the argument. Is it the symbol
2061 // we are interested in?
Ted Kremenek5eca4822012-01-06 22:09:28 +00002062 if (CurrSt->getSValAsScalarOrLoc(*AI, LCtx).getAsLocSymbol() != Sym)
Ted Kremenekc887d132009-04-29 18:50:19 +00002063 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00002064
Ted Kremenekc887d132009-04-29 18:50:19 +00002065 // We have an argument. Get the effect!
2066 AEffects.push_back(Summ->getArg(i));
2067 }
2068 }
Mike Stump1eb44332009-09-09 15:08:12 +00002069 else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002070 if (const Expr *receiver = ME->getInstanceReceiver())
Ted Kremenek5eca4822012-01-06 22:09:28 +00002071 if (CurrSt->getSValAsScalarOrLoc(receiver, LCtx)
2072 .getAsLocSymbol() == Sym) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002073 // The symbol we are tracking is the receiver.
2074 AEffects.push_back(Summ->getReceiverEffect());
2075 }
2076 }
2077 }
Mike Stump1eb44332009-09-09 15:08:12 +00002078
Ted Kremenekc887d132009-04-29 18:50:19 +00002079 do {
2080 // Get the previous type state.
2081 RefVal PrevV = *PrevT;
Mike Stump1eb44332009-09-09 15:08:12 +00002082
Ted Kremenekc887d132009-04-29 18:50:19 +00002083 // Specially handle -dealloc.
Jordy Rose35c86952011-08-24 05:47:39 +00002084 if (!GCEnabled && contains(AEffects, Dealloc)) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002085 // Determine if the object's reference count was pushed to zero.
2086 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2087 // We may not have transitioned to 'release' if we hit an error.
2088 // This case is handled elsewhere.
2089 if (CurrV.getKind() == RefVal::Released) {
Ted Kremenekf21332e2009-05-08 20:01:42 +00002090 assert(CurrV.getCombinedCounts() == 0);
Ted Kremenekc887d132009-04-29 18:50:19 +00002091 os << "Object released by directly sending the '-dealloc' message";
2092 break;
2093 }
2094 }
Mike Stump1eb44332009-09-09 15:08:12 +00002095
Ted Kremenekc887d132009-04-29 18:50:19 +00002096 // Specially handle CFMakeCollectable and friends.
2097 if (contains(AEffects, MakeCollectable)) {
2098 // Get the name of the function.
Jordy Rosef53e8c72011-08-23 19:43:16 +00002099 const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
Ted Kremenek5eca4822012-01-06 22:09:28 +00002100 SVal X =
2101 CurrSt->getSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee(), LCtx);
Ted Kremenek9c378f72011-08-12 23:37:29 +00002102 const FunctionDecl *FD = X.getAsFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002103
Jordy Rose35c86952011-08-24 05:47:39 +00002104 if (GCEnabled) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002105 // Determine if the object's reference count was pushed to zero.
2106 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
Mike Stump1eb44332009-09-09 15:08:12 +00002107
Benjamin Kramerb8989f22011-10-14 18:45:37 +00002108 os << "In GC mode a call to '" << *FD
Ted Kremenekc887d132009-04-29 18:50:19 +00002109 << "' decrements an object's retain count and registers the "
2110 "object with the garbage collector. ";
Mike Stump1eb44332009-09-09 15:08:12 +00002111
Ted Kremenekc887d132009-04-29 18:50:19 +00002112 if (CurrV.getKind() == RefVal::Released) {
2113 assert(CurrV.getCount() == 0);
2114 os << "Since it now has a 0 retain count the object can be "
2115 "automatically collected by the garbage collector.";
2116 }
2117 else
2118 os << "An object must have a 0 retain count to be garbage collected. "
2119 "After this call its retain count is +" << CurrV.getCount()
2120 << '.';
2121 }
Mike Stump1eb44332009-09-09 15:08:12 +00002122 else
Benjamin Kramerb8989f22011-10-14 18:45:37 +00002123 os << "When GC is not enabled a call to '" << *FD
Ted Kremenekc887d132009-04-29 18:50:19 +00002124 << "' has no effect on its argument.";
Mike Stump1eb44332009-09-09 15:08:12 +00002125
Ted Kremenekc887d132009-04-29 18:50:19 +00002126 // Nothing more to say.
2127 break;
2128 }
Mike Stump1eb44332009-09-09 15:08:12 +00002129
2130 // Determine if the typestate has changed.
Ted Kremenekc887d132009-04-29 18:50:19 +00002131 if (!(PrevV == CurrV))
2132 switch (CurrV.getKind()) {
2133 case RefVal::Owned:
2134 case RefVal::NotOwned:
Mike Stump1eb44332009-09-09 15:08:12 +00002135
Ted Kremenekf21332e2009-05-08 20:01:42 +00002136 if (PrevV.getCount() == CurrV.getCount()) {
2137 // Did an autorelease message get sent?
2138 if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
2139 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002140
Zhongxing Xu264e9372009-05-12 10:10:00 +00002141 assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount());
Ted Kremenekeaedfea2009-05-10 05:11:21 +00002142 os << "Object sent -autorelease message";
Ted Kremenekf21332e2009-05-08 20:01:42 +00002143 break;
2144 }
Mike Stump1eb44332009-09-09 15:08:12 +00002145
Ted Kremenekc887d132009-04-29 18:50:19 +00002146 if (PrevV.getCount() > CurrV.getCount())
2147 os << "Reference count decremented.";
2148 else
2149 os << "Reference count incremented.";
Mike Stump1eb44332009-09-09 15:08:12 +00002150
Ted Kremenekc887d132009-04-29 18:50:19 +00002151 if (unsigned Count = CurrV.getCount())
2152 os << " The object now has a +" << Count << " retain count.";
Mike Stump1eb44332009-09-09 15:08:12 +00002153
Ted Kremenekc887d132009-04-29 18:50:19 +00002154 if (PrevV.getKind() == RefVal::Released) {
Jordy Rose35c86952011-08-24 05:47:39 +00002155 assert(GCEnabled && CurrV.getCount() > 0);
Jordy Rose74b7b2b2012-03-17 05:49:15 +00002156 os << " The object is not eligible for garbage collection until "
2157 "the retain count reaches 0 again.";
Ted Kremenekc887d132009-04-29 18:50:19 +00002158 }
Mike Stump1eb44332009-09-09 15:08:12 +00002159
Ted Kremenekc887d132009-04-29 18:50:19 +00002160 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002161
Ted Kremenekc887d132009-04-29 18:50:19 +00002162 case RefVal::Released:
2163 os << "Object released.";
2164 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002165
Ted Kremenekc887d132009-04-29 18:50:19 +00002166 case RefVal::ReturnedOwned:
Jordy Rose74b7b2b2012-03-17 05:49:15 +00002167 // Autoreleases can be applied after marking a node ReturnedOwned.
2168 if (CurrV.getAutoreleaseCount())
2169 return NULL;
2170
2171 os << "Object returned to caller as an owning reference (single "
2172 "retain count transferred to caller)";
Ted Kremenekc887d132009-04-29 18:50:19 +00002173 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002174
Ted Kremenekc887d132009-04-29 18:50:19 +00002175 case RefVal::ReturnedNotOwned:
Ted Kremenekf1365462011-05-26 18:45:44 +00002176 os << "Object returned to caller with a +0 retain count";
Ted Kremenekc887d132009-04-29 18:50:19 +00002177 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002178
Ted Kremenekc887d132009-04-29 18:50:19 +00002179 default:
2180 return NULL;
2181 }
Mike Stump1eb44332009-09-09 15:08:12 +00002182
Ted Kremenekc887d132009-04-29 18:50:19 +00002183 // Emit any remaining diagnostics for the argument effects (if any).
Chris Lattner5f9e2722011-07-23 10:55:15 +00002184 for (SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
Ted Kremenekc887d132009-04-29 18:50:19 +00002185 E=AEffects.end(); I != E; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +00002186
Ted Kremenekc887d132009-04-29 18:50:19 +00002187 // A bunch of things have alternate behavior under GC.
Jordy Rose35c86952011-08-24 05:47:39 +00002188 if (GCEnabled)
Ted Kremenekc887d132009-04-29 18:50:19 +00002189 switch (*I) {
2190 default: break;
2191 case Autorelease:
2192 os << "In GC mode an 'autorelease' has no effect.";
2193 continue;
2194 case IncRefMsg:
2195 os << "In GC mode the 'retain' message has no effect.";
2196 continue;
2197 case DecRefMsg:
2198 os << "In GC mode the 'release' message has no effect.";
2199 continue;
2200 }
2201 }
Mike Stump1eb44332009-09-09 15:08:12 +00002202 } while (0);
2203
Ted Kremenekc887d132009-04-29 18:50:19 +00002204 if (os.str().empty())
2205 return 0; // We have nothing to say!
Ted Kremenek2033a952009-05-13 07:12:33 +00002206
Jordy Rosef53e8c72011-08-23 19:43:16 +00002207 const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
Anna Zaks220ac8c2011-09-15 01:08:34 +00002208 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
2209 N->getLocationContext());
Ted Kremenek9c378f72011-08-12 23:37:29 +00002210 PathDiagnosticPiece *P = new PathDiagnosticEventPiece(Pos, os.str());
Mike Stump1eb44332009-09-09 15:08:12 +00002211
Ted Kremenekc887d132009-04-29 18:50:19 +00002212 // Add the range by scanning the children of the statement for any bindings
2213 // to Sym.
Mike Stump1eb44332009-09-09 15:08:12 +00002214 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
Ted Kremenek5f85e172009-07-22 22:35:28 +00002215 I!=E; ++I)
Ted Kremenek9c378f72011-08-12 23:37:29 +00002216 if (const Expr *Exp = dyn_cast_or_null<Expr>(*I))
Ted Kremenek5eca4822012-01-06 22:09:28 +00002217 if (CurrSt->getSValAsScalarOrLoc(Exp, LCtx).getAsLocSymbol() == Sym) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002218 P->addRange(Exp->getSourceRange());
2219 break;
2220 }
Mike Stump1eb44332009-09-09 15:08:12 +00002221
Ted Kremenekc887d132009-04-29 18:50:19 +00002222 return P;
2223}
2224
Anna Zakse7e01682012-02-28 22:39:22 +00002225// Find the first node in the current function context that referred to the
2226// tracked symbol and the memory location that value was stored to. Note, the
2227// value is only reported if the allocation occurred in the same function as
2228// the leak.
Zhongxing Xuc5619d92009-08-06 01:32:16 +00002229static std::pair<const ExplodedNode*,const MemRegion*>
Ted Kremenek18c66fd2011-08-15 22:09:50 +00002230GetAllocationSite(ProgramStateManager& StateMgr, const ExplodedNode *N,
Ted Kremenekc887d132009-04-29 18:50:19 +00002231 SymbolRef Sym) {
Ted Kremenek9c378f72011-08-12 23:37:29 +00002232 const ExplodedNode *Last = N;
Mike Stump1eb44332009-09-09 15:08:12 +00002233 const MemRegion* FirstBinding = 0;
Anna Zakse7e01682012-02-28 22:39:22 +00002234 const LocationContext *LeakContext = N->getLocationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002235
Ted Kremenekc887d132009-04-29 18:50:19 +00002236 while (N) {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002237 ProgramStateRef St = N->getState();
Mike Stump1eb44332009-09-09 15:08:12 +00002238
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002239 if (!getRefBinding(St, Sym))
Ted Kremenekc887d132009-04-29 18:50:19 +00002240 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002241
Anna Zaks27b867e2012-03-21 19:45:01 +00002242 StoreManager::FindUniqueBinding FB(Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002243 StateMgr.iterBindings(St, FB);
2244 if (FB) FirstBinding = FB.getRegion();
2245
Anna Zakse7e01682012-02-28 22:39:22 +00002246 // Allocation node, is the last node in the current context in which the
2247 // symbol was tracked.
2248 if (N->getLocationContext() == LeakContext)
2249 Last = N;
2250
Mike Stump1eb44332009-09-09 15:08:12 +00002251 N = N->pred_empty() ? NULL : *(N->pred_begin());
Ted Kremenekc887d132009-04-29 18:50:19 +00002252 }
Mike Stump1eb44332009-09-09 15:08:12 +00002253
Anna Zakse7e01682012-02-28 22:39:22 +00002254 // If allocation happened in a function different from the leak node context,
2255 // do not report the binding.
2256 if (N->getLocationContext() != LeakContext) {
2257 FirstBinding = 0;
2258 }
2259
Ted Kremenekc887d132009-04-29 18:50:19 +00002260 return std::make_pair(Last, FirstBinding);
2261}
2262
2263PathDiagnosticPiece*
Anna Zaks23f395e2011-08-20 01:27:22 +00002264CFRefReportVisitor::getEndPath(BugReporterContext &BRC,
2265 const ExplodedNode *EndN,
2266 BugReport &BR) {
Ted Kremenek76aadc32012-03-09 01:13:14 +00002267 BR.markInteresting(Sym);
Anna Zaks23f395e2011-08-20 01:27:22 +00002268 return BugReporterVisitor::getDefaultEndPath(BRC, EndN, BR);
Ted Kremenekc887d132009-04-29 18:50:19 +00002269}
2270
2271PathDiagnosticPiece*
Anna Zaks23f395e2011-08-20 01:27:22 +00002272CFRefLeakReportVisitor::getEndPath(BugReporterContext &BRC,
2273 const ExplodedNode *EndN,
2274 BugReport &BR) {
Mike Stump1eb44332009-09-09 15:08:12 +00002275
Ted Kremenek8966bc12009-05-06 21:39:49 +00002276 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenekc887d132009-04-29 18:50:19 +00002277 // assigned to different variables, etc.
Ted Kremenek76aadc32012-03-09 01:13:14 +00002278 BR.markInteresting(Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002279
Ted Kremenekc887d132009-04-29 18:50:19 +00002280 // We are reporting a leak. Walk up the graph to get to the first node where
2281 // the symbol appeared, and also get the first VarDecl that tracked object
2282 // is stored to.
Ted Kremenek9c378f72011-08-12 23:37:29 +00002283 const ExplodedNode *AllocNode = 0;
Ted Kremenekc887d132009-04-29 18:50:19 +00002284 const MemRegion* FirstBinding = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002285
Ted Kremenekc887d132009-04-29 18:50:19 +00002286 llvm::tie(AllocNode, FirstBinding) =
Ted Kremenekf04dced2009-05-08 23:32:51 +00002287 GetAllocationSite(BRC.getStateManager(), EndN, Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002288
Anna Zaks4fdf97b2011-09-15 18:56:07 +00002289 SourceManager& SM = BRC.getSourceManager();
Mike Stump1eb44332009-09-09 15:08:12 +00002290
Ted Kremenekc887d132009-04-29 18:50:19 +00002291 // Compute an actual location for the leak. Sometimes a leak doesn't
2292 // occur at an actual statement (e.g., transition between blocks; end
2293 // of function) so we need to walk the graph and compute a real location.
Ted Kremenek9c378f72011-08-12 23:37:29 +00002294 const ExplodedNode *LeakN = EndN;
Anna Zaks4fdf97b2011-09-15 18:56:07 +00002295 PathDiagnosticLocation L = PathDiagnosticLocation::createEndOfPath(LeakN, SM);
Mike Stump1eb44332009-09-09 15:08:12 +00002296
Ted Kremenekc887d132009-04-29 18:50:19 +00002297 std::string sbuf;
2298 llvm::raw_string_ostream os(sbuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002299
Ted Kremenekf1365462011-05-26 18:45:44 +00002300 os << "Object leaked: ";
Mike Stump1eb44332009-09-09 15:08:12 +00002301
Ted Kremenekf1365462011-05-26 18:45:44 +00002302 if (FirstBinding) {
2303 os << "object allocated and stored into '"
2304 << FirstBinding->getString() << '\'';
2305 }
2306 else
2307 os << "allocated object";
Mike Stump1eb44332009-09-09 15:08:12 +00002308
Ted Kremenekc887d132009-04-29 18:50:19 +00002309 // Get the retain count.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002310 const RefVal* RV = getRefBinding(EndN->getState(), Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002311
Ted Kremenekc887d132009-04-29 18:50:19 +00002312 if (RV->getKind() == RefVal::ErrorLeakReturned) {
2313 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
Jordy Rose5b5402b2011-07-15 22:17:54 +00002314 // objects. Only "copy", "alloc", "retain" and "new" transfer ownership
Ted Kremenekc887d132009-04-29 18:50:19 +00002315 // to the caller for NS objects.
Ted Kremenekd368d712011-05-25 06:19:45 +00002316 const Decl *D = &EndN->getCodeDecl();
2317 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2318 os << " is returned from a method whose name ('"
2319 << MD->getSelector().getAsString()
2320 << "') does not start with 'copy', 'mutableCopy', 'alloc' or 'new'."
Jordy Rose5b5402b2011-07-15 22:17:54 +00002321 " This violates the naming convention rules"
Ted Kremenekf1365462011-05-26 18:45:44 +00002322 " given in the Memory Management Guide for Cocoa";
Ted Kremenekd368d712011-05-25 06:19:45 +00002323 }
2324 else {
2325 const FunctionDecl *FD = cast<FunctionDecl>(D);
Ted Kremenekb7dcddf2011-12-22 06:35:52 +00002326 os << " is returned from a function whose name ('"
Benjamin Kramera59d20b2012-02-07 11:57:57 +00002327 << *FD
Ted Kremenekd368d712011-05-25 06:19:45 +00002328 << "') does not contain 'Copy' or 'Create'. This violates the naming"
Ted Kremenekb7dcddf2011-12-22 06:35:52 +00002329 " convention rules given in the Memory Management Guide for Core"
Ted Kremenekf1365462011-05-26 18:45:44 +00002330 " Foundation";
Ted Kremenekd368d712011-05-25 06:19:45 +00002331 }
Ted Kremenekc887d132009-04-29 18:50:19 +00002332 }
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002333 else if (RV->getKind() == RefVal::ErrorGCLeakReturned) {
Ted Kremenek9c378f72011-08-12 23:37:29 +00002334 ObjCMethodDecl &MD = cast<ObjCMethodDecl>(EndN->getCodeDecl());
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002335 os << " and returned from method '" << MD.getSelector().getAsString()
Ted Kremenek82f2be52009-05-10 16:52:15 +00002336 << "' is potentially leaked when using garbage collection. Callers "
2337 "of this method do not expect a returned object with a +1 retain "
2338 "count since they expect the object to be managed by the garbage "
2339 "collector";
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002340 }
Ted Kremenekc887d132009-04-29 18:50:19 +00002341 else
Ted Kremenekabf517c2010-10-15 22:50:23 +00002342 os << " is not referenced later in this execution path and has a retain "
Ted Kremenekf1365462011-05-26 18:45:44 +00002343 "count of +" << RV->getCount();
Mike Stump1eb44332009-09-09 15:08:12 +00002344
Ted Kremenekc887d132009-04-29 18:50:19 +00002345 return new PathDiagnosticEventPiece(L, os.str());
2346}
2347
Jordy Rose20589562011-08-24 22:39:09 +00002348CFRefLeakReport::CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts,
2349 bool GCEnabled, const SummaryLogTy &Log,
2350 ExplodedNode *n, SymbolRef sym,
Anna Zaks6a93bd52011-10-25 19:57:11 +00002351 CheckerContext &Ctx)
Jordy Rose20589562011-08-24 22:39:09 +00002352: CFRefReport(D, LOpts, GCEnabled, Log, n, sym, false) {
Mike Stump1eb44332009-09-09 15:08:12 +00002353
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00002354 // Most bug reports are cached at the location where they occurred.
Ted Kremenekc887d132009-04-29 18:50:19 +00002355 // With leaks, we want to unique them by the location where they were
2356 // allocated, and only report a single path. To do this, we need to find
2357 // the allocation site of a piece of tracked memory, which we do via a
2358 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2359 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2360 // that all ancestor nodes that represent the allocation site have the
2361 // same SourceLocation.
Ted Kremenek9c378f72011-08-12 23:37:29 +00002362 const ExplodedNode *AllocNode = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002363
Anna Zaks6a93bd52011-10-25 19:57:11 +00002364 const SourceManager& SMgr = Ctx.getSourceManager();
Anna Zaks590dd8e2011-09-20 21:38:35 +00002365
Ted Kremenekc887d132009-04-29 18:50:19 +00002366 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding.
Anna Zaks6a93bd52011-10-25 19:57:11 +00002367 GetAllocationSite(Ctx.getStateManager(), getErrorNode(), sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002368
Ted Kremenekc887d132009-04-29 18:50:19 +00002369 // Get the SourceLocation for the allocation site.
Jordan Rose852aa0d2012-07-10 22:07:52 +00002370 // FIXME: This will crash the analyzer if an allocation comes from an
2371 // implicit call. (Currently there are no such allocations in Cocoa, though.)
2372 const Stmt *AllocStmt;
Ted Kremenekc887d132009-04-29 18:50:19 +00002373 ProgramPoint P = AllocNode->getLocation();
Jordan Rose852aa0d2012-07-10 22:07:52 +00002374 if (CallExitEnd *Exit = dyn_cast<CallExitEnd>(&P))
2375 AllocStmt = Exit->getCalleeContext()->getCallSite();
2376 else
2377 AllocStmt = cast<PostStmt>(P).getStmt();
2378 assert(AllocStmt && "All allocations must come from explicit calls");
Anna Zaks590dd8e2011-09-20 21:38:35 +00002379 Location = PathDiagnosticLocation::createBegin(AllocStmt, SMgr,
2380 n->getLocationContext());
Ted Kremenekc887d132009-04-29 18:50:19 +00002381 // Fill in the description of the bug.
2382 Description.clear();
2383 llvm::raw_string_ostream os(Description);
Ted Kremenekdd924e22009-05-02 19:05:19 +00002384 os << "Potential leak ";
Jordy Rose20589562011-08-24 22:39:09 +00002385 if (GCEnabled)
Ted Kremenekdd924e22009-05-02 19:05:19 +00002386 os << "(when using garbage collection) ";
Anna Zaks212000e2012-02-28 21:49:08 +00002387 os << "of an object";
Mike Stump1eb44332009-09-09 15:08:12 +00002388
Ted Kremenekc887d132009-04-29 18:50:19 +00002389 // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2390 if (AllocBinding)
Anna Zaks212000e2012-02-28 21:49:08 +00002391 os << " stored into '" << AllocBinding->getString() << '\'';
Anna Zaksdc757b02011-08-19 23:21:56 +00002392
Jordy Rose20589562011-08-24 22:39:09 +00002393 addVisitor(new CFRefLeakReportVisitor(sym, GCEnabled, Log));
Ted Kremenekc887d132009-04-29 18:50:19 +00002394}
2395
2396//===----------------------------------------------------------------------===//
2397// Main checker logic.
2398//===----------------------------------------------------------------------===//
2399
Ted Kremenekd593eb92009-11-25 22:17:44 +00002400namespace {
Jordy Rose910c4052011-09-02 06:44:22 +00002401class RetainCountChecker
Jordy Rose9c083b72011-08-24 18:56:32 +00002402 : public Checker< check::Bind,
Jordy Rose38f17d62011-08-23 19:01:07 +00002403 check::DeadSymbols,
Jordy Rose9c083b72011-08-24 18:56:32 +00002404 check::EndAnalysis,
Jordy Rose38f17d62011-08-23 19:01:07 +00002405 check::EndPath,
Jordy Rose67044292011-08-17 21:27:39 +00002406 check::PostStmt<BlockExpr>,
John McCallf85e1932011-06-15 23:02:42 +00002407 check::PostStmt<CastExpr>,
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002408 check::PostStmt<ObjCArrayLiteral>,
2409 check::PostStmt<ObjCDictionaryLiteral>,
Jordy Rose70fdbc32012-05-12 05:10:43 +00002410 check::PostStmt<ObjCBoxedExpr>,
Jordan Rosefe6a0112012-07-02 19:28:21 +00002411 check::PostCall,
Jordy Rosef53e8c72011-08-23 19:43:16 +00002412 check::PreStmt<ReturnStmt>,
Jordy Rose67044292011-08-17 21:27:39 +00002413 check::RegionChanges,
Jordy Rose76c506f2011-08-21 21:58:18 +00002414 eval::Assume,
2415 eval::Call > {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002416 mutable OwningPtr<CFRefBug> useAfterRelease, releaseNotOwned;
2417 mutable OwningPtr<CFRefBug> deallocGC, deallocNotOwned;
2418 mutable OwningPtr<CFRefBug> overAutorelease, returnNotOwnedForOwned;
2419 mutable OwningPtr<CFRefBug> leakWithinFunction, leakAtReturn;
2420 mutable OwningPtr<CFRefBug> leakWithinFunctionGC, leakAtReturnGC;
Jordy Rose38f17d62011-08-23 19:01:07 +00002421
2422 typedef llvm::DenseMap<SymbolRef, const SimpleProgramPointTag *> SymbolTagMap;
2423
2424 // This map is only used to ensure proper deletion of any allocated tags.
2425 mutable SymbolTagMap DeadSymbolTags;
2426
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002427 mutable OwningPtr<RetainSummaryManager> Summaries;
2428 mutable OwningPtr<RetainSummaryManager> SummariesGC;
Jordy Roseb6cfc092011-08-25 00:10:37 +00002429
Jordy Rosee0a5d322011-08-23 20:27:16 +00002430 mutable ARCounts::Factory ARCountFactory;
2431
Jordy Rose9c083b72011-08-24 18:56:32 +00002432 mutable SummaryLogTy SummaryLog;
2433 mutable bool ShouldResetSummaryLog;
2434
Jordy Rose2f9a66d2011-08-20 21:17:59 +00002435public:
Jordy Rose910c4052011-09-02 06:44:22 +00002436 RetainCountChecker() : ShouldResetSummaryLog(false) {}
Jordy Rose38f17d62011-08-23 19:01:07 +00002437
Jordy Rose910c4052011-09-02 06:44:22 +00002438 virtual ~RetainCountChecker() {
Jordy Rose38f17d62011-08-23 19:01:07 +00002439 DeleteContainerSeconds(DeadSymbolTags);
2440 }
2441
Jordy Rose9c083b72011-08-24 18:56:32 +00002442 void checkEndAnalysis(ExplodedGraph &G, BugReporter &BR,
2443 ExprEngine &Eng) const {
2444 // FIXME: This is a hack to make sure the summary log gets cleared between
2445 // analyses of different code bodies.
2446 //
2447 // Why is this necessary? Because a checker's lifetime is tied to a
2448 // translation unit, but an ExplodedGraph's lifetime is just a code body.
2449 // Once in a blue moon, a new ExplodedNode will have the same address as an
2450 // old one with an associated summary, and the bug report visitor gets very
2451 // confused. (To make things worse, the summary lifetime is currently also
2452 // tied to a code body, so we get a crash instead of incorrect results.)
Jordy Rose1ab51c72011-08-24 09:27:24 +00002453 //
2454 // Why is this a bad solution? Because if the lifetime of the ExplodedGraph
2455 // changes, things will start going wrong again. Really the lifetime of this
2456 // log needs to be tied to either the specific nodes in it or the entire
2457 // ExplodedGraph, not to a specific part of the code being analyzed.
2458 //
Jordy Rose9c083b72011-08-24 18:56:32 +00002459 // (Also, having stateful local data means that the same checker can't be
2460 // used from multiple threads, but a lot of checkers have incorrect
2461 // assumptions about that anyway. So that wasn't a priority at the time of
2462 // this fix.)
Jordy Rose1ab51c72011-08-24 09:27:24 +00002463 //
Jordy Rose9c083b72011-08-24 18:56:32 +00002464 // This happens at the end of analysis, but bug reports are emitted /after/
2465 // this point. So we can't just clear the summary log now. Instead, we mark
2466 // that the next time we access the summary log, it should be cleared.
2467
2468 // If we never reset the summary log during /this/ code body analysis,
2469 // there were no new summaries. There might still have been summaries from
2470 // the /last/ analysis, so clear them out to make sure the bug report
2471 // visitors don't get confused.
2472 if (ShouldResetSummaryLog)
2473 SummaryLog.clear();
2474
2475 ShouldResetSummaryLog = !SummaryLog.empty();
Jordy Rose1ab51c72011-08-24 09:27:24 +00002476 }
2477
Jordy Rose17a38e22011-09-02 05:55:19 +00002478 CFRefBug *getLeakWithinFunctionBug(const LangOptions &LOpts,
2479 bool GCEnabled) const {
2480 if (GCEnabled) {
Jordy Rosedb92bb62011-08-25 01:14:38 +00002481 if (!leakWithinFunctionGC)
Benjamin Kramerfacde172012-06-06 17:32:50 +00002482 leakWithinFunctionGC.reset(new Leak("Leak of object when using "
2483 "garbage collection"));
Jordy Rose17a38e22011-09-02 05:55:19 +00002484 return leakWithinFunctionGC.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002485 } else {
2486 if (!leakWithinFunction) {
Douglas Gregore289d812011-09-13 17:21:33 +00002487 if (LOpts.getGC() == LangOptions::HybridGC) {
Benjamin Kramerfacde172012-06-06 17:32:50 +00002488 leakWithinFunction.reset(new Leak("Leak of object when not using "
2489 "garbage collection (GC) in "
2490 "dual GC/non-GC code"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002491 } else {
Benjamin Kramerfacde172012-06-06 17:32:50 +00002492 leakWithinFunction.reset(new Leak("Leak"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002493 }
2494 }
Jordy Rose17a38e22011-09-02 05:55:19 +00002495 return leakWithinFunction.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002496 }
2497 }
2498
Jordy Rose17a38e22011-09-02 05:55:19 +00002499 CFRefBug *getLeakAtReturnBug(const LangOptions &LOpts, bool GCEnabled) const {
2500 if (GCEnabled) {
Jordy Rosedb92bb62011-08-25 01:14:38 +00002501 if (!leakAtReturnGC)
Benjamin Kramerfacde172012-06-06 17:32:50 +00002502 leakAtReturnGC.reset(new Leak("Leak of returned object when using "
2503 "garbage collection"));
Jordy Rose17a38e22011-09-02 05:55:19 +00002504 return leakAtReturnGC.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002505 } else {
2506 if (!leakAtReturn) {
Douglas Gregore289d812011-09-13 17:21:33 +00002507 if (LOpts.getGC() == LangOptions::HybridGC) {
Benjamin Kramerfacde172012-06-06 17:32:50 +00002508 leakAtReturn.reset(new Leak("Leak of returned object when not using "
2509 "garbage collection (GC) in dual "
2510 "GC/non-GC code"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002511 } else {
Benjamin Kramerfacde172012-06-06 17:32:50 +00002512 leakAtReturn.reset(new Leak("Leak of returned object"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002513 }
2514 }
Jordy Rose17a38e22011-09-02 05:55:19 +00002515 return leakAtReturn.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002516 }
2517 }
2518
Jordy Rose17a38e22011-09-02 05:55:19 +00002519 RetainSummaryManager &getSummaryManager(ASTContext &Ctx,
2520 bool GCEnabled) const {
2521 // FIXME: We don't support ARC being turned on and off during one analysis.
2522 // (nor, for that matter, do we support changing ASTContexts)
David Blaikie4e4d0842012-03-11 07:00:24 +00002523 bool ARCEnabled = (bool)Ctx.getLangOpts().ObjCAutoRefCount;
Jordy Rose17a38e22011-09-02 05:55:19 +00002524 if (GCEnabled) {
2525 if (!SummariesGC)
Jordy Roseb6cfc092011-08-25 00:10:37 +00002526 SummariesGC.reset(new RetainSummaryManager(Ctx, true, ARCEnabled));
Jordy Rose17a38e22011-09-02 05:55:19 +00002527 else
2528 assert(SummariesGC->isARCEnabled() == ARCEnabled);
Jordy Roseb6cfc092011-08-25 00:10:37 +00002529 return *SummariesGC;
2530 } else {
Jordy Rose17a38e22011-09-02 05:55:19 +00002531 if (!Summaries)
Jordy Roseb6cfc092011-08-25 00:10:37 +00002532 Summaries.reset(new RetainSummaryManager(Ctx, false, ARCEnabled));
Jordy Rose17a38e22011-09-02 05:55:19 +00002533 else
2534 assert(Summaries->isARCEnabled() == ARCEnabled);
Jordy Roseb6cfc092011-08-25 00:10:37 +00002535 return *Summaries;
2536 }
2537 }
2538
Jordy Rose17a38e22011-09-02 05:55:19 +00002539 RetainSummaryManager &getSummaryManager(CheckerContext &C) const {
2540 return getSummaryManager(C.getASTContext(), C.isObjCGCEnabled());
2541 }
2542
Ted Kremenek8bef8232012-01-26 21:29:00 +00002543 void printState(raw_ostream &Out, ProgramStateRef State,
Jordy Rosedbd658e2011-08-28 19:11:56 +00002544 const char *NL, const char *Sep) const;
2545
Anna Zaks390909c2011-10-06 00:43:15 +00002546 void checkBind(SVal loc, SVal val, const Stmt *S, CheckerContext &C) const;
Jordy Roseab027fd2011-08-20 21:16:58 +00002547 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
2548 void checkPostStmt(const CastExpr *CE, CheckerContext &C) const;
John McCallf85e1932011-06-15 23:02:42 +00002549
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002550 void checkPostStmt(const ObjCArrayLiteral *AL, CheckerContext &C) const;
2551 void checkPostStmt(const ObjCDictionaryLiteral *DL, CheckerContext &C) const;
Jordy Rose70fdbc32012-05-12 05:10:43 +00002552 void checkPostStmt(const ObjCBoxedExpr *BE, CheckerContext &C) const;
2553
Jordan Rosefe6a0112012-07-02 19:28:21 +00002554 void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002555
Jordan Rose4531b7d2012-07-02 19:27:43 +00002556 void checkSummary(const RetainSummary &Summ, const CallEvent &Call,
Jordy Rosee38dd952011-08-28 05:16:28 +00002557 CheckerContext &C) const;
Jordy Rose294396b2011-08-22 23:48:23 +00002558
Jordy Rose76c506f2011-08-21 21:58:18 +00002559 bool evalCall(const CallExpr *CE, CheckerContext &C) const;
2560
Ted Kremenek8bef8232012-01-26 21:29:00 +00002561 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Jordy Roseab027fd2011-08-20 21:16:58 +00002562 bool Assumption) const;
Jordy Rose67044292011-08-17 21:27:39 +00002563
Ted Kremenek8bef8232012-01-26 21:29:00 +00002564 ProgramStateRef
2565 checkRegionChanges(ProgramStateRef state,
Jordy Rose537716a2011-08-27 22:51:26 +00002566 const StoreManager::InvalidatedSymbols *invalidated,
2567 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00002568 ArrayRef<const MemRegion *> Regions,
Jordan Rose740d4902012-07-02 19:27:35 +00002569 const CallEvent *Call) const;
Jordy Roseab027fd2011-08-20 21:16:58 +00002570
Ted Kremenek8bef8232012-01-26 21:29:00 +00002571 bool wantsRegionChangeUpdate(ProgramStateRef state) const {
Jordy Rose2f9a66d2011-08-20 21:17:59 +00002572 return true;
Jordy Roseab027fd2011-08-20 21:16:58 +00002573 }
Jordy Rose294396b2011-08-22 23:48:23 +00002574
Jordy Rosef53e8c72011-08-23 19:43:16 +00002575 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
2576 void checkReturnWithRetEffect(const ReturnStmt *S, CheckerContext &C,
2577 ExplodedNode *Pred, RetEffect RE, RefVal X,
Ted Kremenek8bef8232012-01-26 21:29:00 +00002578 SymbolRef Sym, ProgramStateRef state) const;
Jordy Rosef53e8c72011-08-23 19:43:16 +00002579
Jordy Rose38f17d62011-08-23 19:01:07 +00002580 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Anna Zaksaf498a22011-10-25 19:56:48 +00002581 void checkEndPath(CheckerContext &C) const;
Jordy Rose38f17d62011-08-23 19:01:07 +00002582
Ted Kremenek8bef8232012-01-26 21:29:00 +00002583 ProgramStateRef updateSymbol(ProgramStateRef state, SymbolRef sym,
Jordy Rose17a38e22011-09-02 05:55:19 +00002584 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
2585 CheckerContext &C) const;
Jordy Rosee0a5d322011-08-23 20:27:16 +00002586
Ted Kremenek8bef8232012-01-26 21:29:00 +00002587 void processNonLeakError(ProgramStateRef St, SourceRange ErrorRange,
Jordy Rose294396b2011-08-22 23:48:23 +00002588 RefVal::Kind ErrorKind, SymbolRef Sym,
2589 CheckerContext &C) const;
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002590
2591 void processObjCLiterals(CheckerContext &C, const Expr *Ex) const;
Jordy Rose294396b2011-08-22 23:48:23 +00002592
Jordy Rose38f17d62011-08-23 19:01:07 +00002593 const ProgramPointTag *getDeadSymbolTag(SymbolRef sym) const;
2594
Ted Kremenek8bef8232012-01-26 21:29:00 +00002595 ProgramStateRef handleSymbolDeath(ProgramStateRef state,
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002596 SymbolRef sid, RefVal V,
2597 SmallVectorImpl<SymbolRef> &Leaked) const;
Jordy Rose38f17d62011-08-23 19:01:07 +00002598
Ted Kremenek8bef8232012-01-26 21:29:00 +00002599 std::pair<ExplodedNode *, ProgramStateRef >
2600 handleAutoreleaseCounts(ProgramStateRef state,
Jordy Rose8d228632011-08-23 20:07:14 +00002601 GenericNodeBuilderRefCount Bd, ExplodedNode *Pred,
Anna Zaks6a93bd52011-10-25 19:57:11 +00002602 CheckerContext &Ctx, SymbolRef Sym, RefVal V) const;
Jordy Rose8d228632011-08-23 20:07:14 +00002603
Ted Kremenek8bef8232012-01-26 21:29:00 +00002604 ExplodedNode *processLeaks(ProgramStateRef state,
Jordy Rose38f17d62011-08-23 19:01:07 +00002605 SmallVectorImpl<SymbolRef> &Leaked,
2606 GenericNodeBuilderRefCount &Builder,
Anna Zaks6a93bd52011-10-25 19:57:11 +00002607 CheckerContext &Ctx,
Jordy Rose38f17d62011-08-23 19:01:07 +00002608 ExplodedNode *Pred = 0) const;
Ted Kremenekd593eb92009-11-25 22:17:44 +00002609};
2610} // end anonymous namespace
2611
Jordy Rose67044292011-08-17 21:27:39 +00002612namespace {
2613class StopTrackingCallback : public SymbolVisitor {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002614 ProgramStateRef state;
Jordy Rose67044292011-08-17 21:27:39 +00002615public:
Ted Kremenek8bef8232012-01-26 21:29:00 +00002616 StopTrackingCallback(ProgramStateRef st) : state(st) {}
2617 ProgramStateRef getState() const { return state; }
Jordy Rose67044292011-08-17 21:27:39 +00002618
2619 bool VisitSymbol(SymbolRef sym) {
2620 state = state->remove<RefBindings>(sym);
2621 return true;
2622 }
2623};
2624} // end anonymous namespace
2625
Jordy Rose910c4052011-09-02 06:44:22 +00002626//===----------------------------------------------------------------------===//
2627// Handle statements that may have an effect on refcounts.
2628//===----------------------------------------------------------------------===//
Jordy Rose67044292011-08-17 21:27:39 +00002629
Jordy Rose910c4052011-09-02 06:44:22 +00002630void RetainCountChecker::checkPostStmt(const BlockExpr *BE,
2631 CheckerContext &C) const {
Jordy Rose67044292011-08-17 21:27:39 +00002632
Jordy Rose910c4052011-09-02 06:44:22 +00002633 // Scan the BlockDecRefExprs for any object the retain count checker
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002634 // may be tracking.
John McCall469a1eb2011-02-02 13:00:07 +00002635 if (!BE->getBlockDecl()->hasCaptures())
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002636 return;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002637
Ted Kremenek8bef8232012-01-26 21:29:00 +00002638 ProgramStateRef state = C.getState();
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002639 const BlockDataRegion *R =
Ted Kremenek5eca4822012-01-06 22:09:28 +00002640 cast<BlockDataRegion>(state->getSVal(BE,
2641 C.getLocationContext()).getAsRegion());
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002642
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002643 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
2644 E = R->referenced_vars_end();
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002645
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002646 if (I == E)
2647 return;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002648
Ted Kremenek67d12872009-12-07 22:05:27 +00002649 // FIXME: For now we invalidate the tracking of all symbols passed to blocks
2650 // via captured variables, even though captured variables result in a copy
2651 // and in implicit increment/decrement of a retain count.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002652 SmallVector<const MemRegion*, 10> Regions;
Anna Zaks39ac1872011-10-26 21:06:44 +00002653 const LocationContext *LC = C.getLocationContext();
Ted Kremenekc8413fd2010-12-02 07:49:45 +00002654 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002655
Ted Kremenek67d12872009-12-07 22:05:27 +00002656 for ( ; I != E; ++I) {
2657 const VarRegion *VR = *I;
2658 if (VR->getSuperRegion() == R) {
2659 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2660 }
2661 Regions.push_back(VR);
2662 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002663
Ted Kremenek67d12872009-12-07 22:05:27 +00002664 state =
2665 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
2666 Regions.data() + Regions.size()).getState();
Anna Zaks0bd6b112011-10-26 21:06:34 +00002667 C.addTransition(state);
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002668}
2669
Jordy Rose910c4052011-09-02 06:44:22 +00002670void RetainCountChecker::checkPostStmt(const CastExpr *CE,
2671 CheckerContext &C) const {
John McCallf85e1932011-06-15 23:02:42 +00002672 const ObjCBridgedCastExpr *BE = dyn_cast<ObjCBridgedCastExpr>(CE);
2673 if (!BE)
2674 return;
2675
John McCall71c482c2011-06-17 06:50:50 +00002676 ArgEffect AE = IncRef;
John McCallf85e1932011-06-15 23:02:42 +00002677
2678 switch (BE->getBridgeKind()) {
2679 case clang::OBC_Bridge:
2680 // Do nothing.
2681 return;
2682 case clang::OBC_BridgeRetained:
2683 AE = IncRef;
2684 break;
2685 case clang::OBC_BridgeTransfer:
2686 AE = DecRefBridgedTransfered;
2687 break;
2688 }
2689
Ted Kremenek8bef8232012-01-26 21:29:00 +00002690 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00002691 SymbolRef Sym = state->getSVal(CE, C.getLocationContext()).getAsLocSymbol();
John McCallf85e1932011-06-15 23:02:42 +00002692 if (!Sym)
2693 return;
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002694 const RefVal* T = getRefBinding(state, Sym);
John McCallf85e1932011-06-15 23:02:42 +00002695 if (!T)
2696 return;
2697
John McCallf85e1932011-06-15 23:02:42 +00002698 RefVal::Kind hasErr = (RefVal::Kind) 0;
Jordy Rose17a38e22011-09-02 05:55:19 +00002699 state = updateSymbol(state, Sym, *T, AE, hasErr, C);
John McCallf85e1932011-06-15 23:02:42 +00002700
2701 if (hasErr) {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002702 // FIXME: If we get an error during a bridge cast, should we report it?
2703 // Should we assert that there is no error?
John McCallf85e1932011-06-15 23:02:42 +00002704 return;
2705 }
2706
Anna Zaks0bd6b112011-10-26 21:06:34 +00002707 C.addTransition(state);
John McCallf85e1932011-06-15 23:02:42 +00002708}
2709
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002710void RetainCountChecker::processObjCLiterals(CheckerContext &C,
2711 const Expr *Ex) const {
2712 ProgramStateRef state = C.getState();
2713 const ExplodedNode *pred = C.getPredecessor();
2714 for (Stmt::const_child_iterator it = Ex->child_begin(), et = Ex->child_end() ;
2715 it != et ; ++it) {
2716 const Stmt *child = *it;
2717 SVal V = state->getSVal(child, pred->getLocationContext());
2718 if (SymbolRef sym = V.getAsSymbol())
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002719 if (const RefVal* T = getRefBinding(state, sym)) {
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002720 RefVal::Kind hasErr = (RefVal::Kind) 0;
2721 state = updateSymbol(state, sym, *T, MayEscape, hasErr, C);
2722 if (hasErr) {
2723 processNonLeakError(state, child->getSourceRange(), hasErr, sym, C);
2724 return;
2725 }
2726 }
2727 }
2728
2729 // Return the object as autoreleased.
2730 // RetEffect RE = RetEffect::MakeNotOwned(RetEffect::ObjC);
2731 if (SymbolRef sym =
2732 state->getSVal(Ex, pred->getLocationContext()).getAsSymbol()) {
2733 QualType ResultTy = Ex->getType();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002734 state = setRefBinding(state, sym,
2735 RefVal::makeNotOwned(RetEffect::ObjC, ResultTy));
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002736 }
2737
2738 C.addTransition(state);
2739}
2740
2741void RetainCountChecker::checkPostStmt(const ObjCArrayLiteral *AL,
2742 CheckerContext &C) const {
2743 // Apply the 'MayEscape' to all values.
2744 processObjCLiterals(C, AL);
2745}
2746
2747void RetainCountChecker::checkPostStmt(const ObjCDictionaryLiteral *DL,
2748 CheckerContext &C) const {
2749 // Apply the 'MayEscape' to all keys and values.
2750 processObjCLiterals(C, DL);
2751}
2752
Jordy Rose70fdbc32012-05-12 05:10:43 +00002753void RetainCountChecker::checkPostStmt(const ObjCBoxedExpr *Ex,
2754 CheckerContext &C) const {
2755 const ExplodedNode *Pred = C.getPredecessor();
2756 const LocationContext *LCtx = Pred->getLocationContext();
2757 ProgramStateRef State = Pred->getState();
2758
2759 if (SymbolRef Sym = State->getSVal(Ex, LCtx).getAsSymbol()) {
2760 QualType ResultTy = Ex->getType();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002761 State = setRefBinding(State, Sym,
2762 RefVal::makeNotOwned(RetEffect::ObjC, ResultTy));
Jordy Rose70fdbc32012-05-12 05:10:43 +00002763 }
2764
2765 C.addTransition(State);
2766}
2767
Jordan Rosefe6a0112012-07-02 19:28:21 +00002768void RetainCountChecker::checkPostCall(const CallEvent &Call,
2769 CheckerContext &C) const {
2770 if (C.wasInlined)
2771 return;
Jordy Roseb6cfc092011-08-25 00:10:37 +00002772
Jordan Rosefe6a0112012-07-02 19:28:21 +00002773 RetainSummaryManager &Summaries = getSummaryManager(C);
2774 const RetainSummary *Summ = Summaries.getSummary(Call, C.getState());
2775 checkSummary(*Summ, Call, C);
Jordy Rose294396b2011-08-22 23:48:23 +00002776}
2777
Jordy Rose910c4052011-09-02 06:44:22 +00002778/// GetReturnType - Used to get the return type of a message expression or
2779/// function call with the intention of affixing that type to a tracked symbol.
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +00002780/// While the return type can be queried directly from RetEx, when
Jordy Rose910c4052011-09-02 06:44:22 +00002781/// invoking class methods we augment to the return type to be that of
2782/// a pointer to the class (as opposed it just being id).
2783// FIXME: We may be able to do this with related result types instead.
2784// This function is probably overestimating.
2785static QualType GetReturnType(const Expr *RetE, ASTContext &Ctx) {
2786 QualType RetTy = RetE->getType();
2787 // If RetE is not a message expression just return its type.
2788 // If RetE is a message expression, return its types if it is something
2789 /// more specific than id.
2790 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RetE))
2791 if (const ObjCObjectPointerType *PT = RetTy->getAs<ObjCObjectPointerType>())
2792 if (PT->isObjCQualifiedIdType() || PT->isObjCIdType() ||
2793 PT->isObjCClassType()) {
2794 // At this point we know the return type of the message expression is
2795 // id, id<...>, or Class. If we have an ObjCInterfaceDecl, we know this
2796 // is a call to a class method whose type we can resolve. In such
2797 // cases, promote the return type to XXX* (where XXX is the class).
2798 const ObjCInterfaceDecl *D = ME->getReceiverInterface();
2799 return !D ? RetTy :
2800 Ctx.getObjCObjectPointerType(Ctx.getObjCInterfaceType(D));
2801 }
2802
2803 return RetTy;
2804}
2805
2806void RetainCountChecker::checkSummary(const RetainSummary &Summ,
Jordan Rose4531b7d2012-07-02 19:27:43 +00002807 const CallEvent &CallOrMsg,
Jordy Rose910c4052011-09-02 06:44:22 +00002808 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002809 ProgramStateRef state = C.getState();
Jordy Rose294396b2011-08-22 23:48:23 +00002810
2811 // Evaluate the effect of the arguments.
2812 RefVal::Kind hasErr = (RefVal::Kind) 0;
2813 SourceRange ErrorRange;
2814 SymbolRef ErrorSym = 0;
2815
2816 for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
Jordy Rose537716a2011-08-27 22:51:26 +00002817 SVal V = CallOrMsg.getArgSVal(idx);
Jordy Rose294396b2011-08-22 23:48:23 +00002818
2819 if (SymbolRef Sym = V.getAsLocSymbol()) {
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002820 if (const RefVal *T = getRefBinding(state, Sym)) {
Jordy Rose17a38e22011-09-02 05:55:19 +00002821 state = updateSymbol(state, Sym, *T, Summ.getArg(idx), hasErr, C);
Jordy Rose294396b2011-08-22 23:48:23 +00002822 if (hasErr) {
2823 ErrorRange = CallOrMsg.getArgSourceRange(idx);
2824 ErrorSym = Sym;
2825 break;
2826 }
2827 }
2828 }
2829 }
2830
2831 // Evaluate the effect on the message receiver.
2832 bool ReceiverIsTracked = false;
Jordan Rose4531b7d2012-07-02 19:27:43 +00002833 if (!hasErr) {
Jordan Rosecde8cdb2012-07-02 19:27:56 +00002834 const ObjCMethodCall *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg);
Jordan Rose4531b7d2012-07-02 19:27:43 +00002835 if (MsgInvocation) {
2836 if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002837 if (const RefVal *T = getRefBinding(state, Sym)) {
Jordan Rose4531b7d2012-07-02 19:27:43 +00002838 ReceiverIsTracked = true;
2839 state = updateSymbol(state, Sym, *T, Summ.getReceiverEffect(),
2840 hasErr, C);
2841 if (hasErr) {
Jordan Rose8919e682012-07-18 21:59:51 +00002842 ErrorRange = MsgInvocation->getOriginExpr()->getReceiverRange();
Jordan Rose4531b7d2012-07-02 19:27:43 +00002843 ErrorSym = Sym;
2844 }
Jordy Rose294396b2011-08-22 23:48:23 +00002845 }
2846 }
2847 }
2848 }
2849
2850 // Process any errors.
2851 if (hasErr) {
2852 processNonLeakError(state, ErrorRange, hasErr, ErrorSym, C);
2853 return;
2854 }
2855
2856 // Consult the summary for the return value.
2857 RetEffect RE = Summ.getRetEffect();
2858
2859 if (RE.getKind() == RetEffect::OwnedWhenTrackedReceiver) {
Jordy Roseb6cfc092011-08-25 00:10:37 +00002860 if (ReceiverIsTracked)
Jordy Rose17a38e22011-09-02 05:55:19 +00002861 RE = getSummaryManager(C).getObjAllocRetEffect();
Jordy Roseb6cfc092011-08-25 00:10:37 +00002862 else
Jordy Rose294396b2011-08-22 23:48:23 +00002863 RE = RetEffect::MakeNoRet();
2864 }
2865
2866 switch (RE.getKind()) {
2867 default:
David Blaikie7530c032012-01-17 06:56:22 +00002868 llvm_unreachable("Unhandled RetEffect.");
Jordy Rose294396b2011-08-22 23:48:23 +00002869
2870 case RetEffect::NoRet:
2871 // No work necessary.
2872 break;
2873
2874 case RetEffect::OwnedAllocatedSymbol:
2875 case RetEffect::OwnedSymbol: {
Ted Kremenek5eca4822012-01-06 22:09:28 +00002876 SymbolRef Sym = state->getSVal(CallOrMsg.getOriginExpr(),
2877 C.getLocationContext()).getAsSymbol();
Jordy Rose294396b2011-08-22 23:48:23 +00002878 if (!Sym)
2879 break;
2880
Jordan Rose4531b7d2012-07-02 19:27:43 +00002881 // Use the result type from the CallEvent as it automatically adjusts
Jordy Rose294396b2011-08-22 23:48:23 +00002882 // for methods/functions that return references.
Jordan Rose4531b7d2012-07-02 19:27:43 +00002883 QualType ResultTy = CallOrMsg.getResultType();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002884 state = setRefBinding(state, Sym, RefVal::makeOwned(RE.getObjKind(),
2885 ResultTy));
Jordy Rose294396b2011-08-22 23:48:23 +00002886
2887 // FIXME: Add a flag to the checker where allocations are assumed to
2888 // *not* fail. (The code below is out-of-date, though.)
2889#if 0
2890 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) {
2891 bool isFeasible;
2892 state = state.assume(loc::SymbolVal(Sym), true, isFeasible);
2893 assert(isFeasible && "Cannot assume fresh symbol is non-null.");
2894 }
2895#endif
2896
2897 break;
2898 }
2899
2900 case RetEffect::GCNotOwnedSymbol:
2901 case RetEffect::ARCNotOwnedSymbol:
2902 case RetEffect::NotOwnedSymbol: {
2903 const Expr *Ex = CallOrMsg.getOriginExpr();
Ted Kremenek5eca4822012-01-06 22:09:28 +00002904 SymbolRef Sym = state->getSVal(Ex, C.getLocationContext()).getAsSymbol();
Jordy Rose294396b2011-08-22 23:48:23 +00002905 if (!Sym)
2906 break;
2907
2908 // Use GetReturnType in order to give [NSFoo alloc] the type NSFoo *.
2909 QualType ResultTy = GetReturnType(Ex, C.getASTContext());
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002910 state = setRefBinding(state, Sym, RefVal::makeNotOwned(RE.getObjKind(),
2911 ResultTy));
Jordy Rose294396b2011-08-22 23:48:23 +00002912 break;
2913 }
2914 }
2915
2916 // This check is actually necessary; otherwise the statement builder thinks
2917 // we've hit a previously-found path.
2918 // Normally addTransition takes care of this, but we want the node pointer.
2919 ExplodedNode *NewNode;
2920 if (state == C.getState()) {
2921 NewNode = C.getPredecessor();
2922 } else {
Anna Zaks0bd6b112011-10-26 21:06:34 +00002923 NewNode = C.addTransition(state);
Jordy Rose294396b2011-08-22 23:48:23 +00002924 }
2925
Jordy Rose9c083b72011-08-24 18:56:32 +00002926 // Annotate the node with summary we used.
2927 if (NewNode) {
2928 // FIXME: This is ugly. See checkEndAnalysis for why it's necessary.
2929 if (ShouldResetSummaryLog) {
2930 SummaryLog.clear();
2931 ShouldResetSummaryLog = false;
2932 }
Jordy Roseec9ef852011-08-23 20:55:48 +00002933 SummaryLog[NewNode] = &Summ;
Jordy Rose9c083b72011-08-24 18:56:32 +00002934 }
Jordy Rose294396b2011-08-22 23:48:23 +00002935}
2936
Jordy Rosee0a5d322011-08-23 20:27:16 +00002937
Ted Kremenek8bef8232012-01-26 21:29:00 +00002938ProgramStateRef
2939RetainCountChecker::updateSymbol(ProgramStateRef state, SymbolRef sym,
Jordy Rose910c4052011-09-02 06:44:22 +00002940 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
2941 CheckerContext &C) const {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002942 // In GC mode [... release] and [... retain] do nothing.
Jordy Rose910c4052011-09-02 06:44:22 +00002943 // In ARC mode they shouldn't exist at all, but we just ignore them.
Jordy Rose17a38e22011-09-02 05:55:19 +00002944 bool IgnoreRetainMsg = C.isObjCGCEnabled();
2945 if (!IgnoreRetainMsg)
David Blaikie4e4d0842012-03-11 07:00:24 +00002946 IgnoreRetainMsg = (bool)C.getASTContext().getLangOpts().ObjCAutoRefCount;
Jordy Rose17a38e22011-09-02 05:55:19 +00002947
Jordy Rosee0a5d322011-08-23 20:27:16 +00002948 switch (E) {
Jordan Rose4531b7d2012-07-02 19:27:43 +00002949 default:
2950 break;
2951 case IncRefMsg:
2952 E = IgnoreRetainMsg ? DoNothing : IncRef;
2953 break;
2954 case DecRefMsg:
2955 E = IgnoreRetainMsg ? DoNothing : DecRef;
2956 break;
2957 case DecRefMsgAndStopTracking:
2958 E = IgnoreRetainMsg ? StopTracking : DecRefAndStopTracking;
2959 break;
2960 case MakeCollectable:
2961 E = C.isObjCGCEnabled() ? DecRef : DoNothing;
2962 break;
2963 case NewAutoreleasePool:
2964 E = C.isObjCGCEnabled() ? DoNothing : NewAutoreleasePool;
2965 break;
Jordy Rosee0a5d322011-08-23 20:27:16 +00002966 }
2967
2968 // Handle all use-after-releases.
Jordy Rose17a38e22011-09-02 05:55:19 +00002969 if (!C.isObjCGCEnabled() && V.getKind() == RefVal::Released) {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002970 V = V ^ RefVal::ErrorUseAfterRelease;
2971 hasErr = V.getKind();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002972 return setRefBinding(state, sym, V);
Jordy Rosee0a5d322011-08-23 20:27:16 +00002973 }
2974
2975 switch (E) {
2976 case DecRefMsg:
2977 case IncRefMsg:
2978 case MakeCollectable:
Jordan Rose4531b7d2012-07-02 19:27:43 +00002979 case DecRefMsgAndStopTracking:
Jordy Rosee0a5d322011-08-23 20:27:16 +00002980 llvm_unreachable("DecRefMsg/IncRefMsg/MakeCollectable already converted");
Jordy Rosee0a5d322011-08-23 20:27:16 +00002981
2982 case Dealloc:
2983 // Any use of -dealloc in GC is *bad*.
Jordy Rose17a38e22011-09-02 05:55:19 +00002984 if (C.isObjCGCEnabled()) {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002985 V = V ^ RefVal::ErrorDeallocGC;
2986 hasErr = V.getKind();
2987 break;
2988 }
2989
2990 switch (V.getKind()) {
2991 default:
2992 llvm_unreachable("Invalid RefVal state for an explicit dealloc.");
Jordy Rosee0a5d322011-08-23 20:27:16 +00002993 case RefVal::Owned:
2994 // The object immediately transitions to the released state.
2995 V = V ^ RefVal::Released;
2996 V.clearCounts();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002997 return setRefBinding(state, sym, V);
Jordy Rosee0a5d322011-08-23 20:27:16 +00002998 case RefVal::NotOwned:
2999 V = V ^ RefVal::ErrorDeallocNotOwned;
3000 hasErr = V.getKind();
3001 break;
3002 }
3003 break;
3004
3005 case NewAutoreleasePool:
Jordy Rose17a38e22011-09-02 05:55:19 +00003006 assert(!C.isObjCGCEnabled());
Jordy Rosee0a5d322011-08-23 20:27:16 +00003007 return state->add<AutoreleaseStack>(sym);
3008
3009 case MayEscape:
3010 if (V.getKind() == RefVal::Owned) {
3011 V = V ^ RefVal::NotOwned;
3012 break;
3013 }
3014
3015 // Fall-through.
3016
Jordy Rosee0a5d322011-08-23 20:27:16 +00003017 case DoNothing:
3018 return state;
3019
3020 case Autorelease:
Jordy Rose17a38e22011-09-02 05:55:19 +00003021 if (C.isObjCGCEnabled())
Jordy Rosee0a5d322011-08-23 20:27:16 +00003022 return state;
3023
3024 // Update the autorelease counts.
3025 state = SendAutorelease(state, ARCountFactory, sym);
3026 V = V.autorelease();
3027 break;
3028
3029 case StopTracking:
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003030 return removeRefBinding(state, sym);
Jordy Rosee0a5d322011-08-23 20:27:16 +00003031
3032 case IncRef:
3033 switch (V.getKind()) {
3034 default:
3035 llvm_unreachable("Invalid RefVal state for a retain.");
Jordy Rosee0a5d322011-08-23 20:27:16 +00003036 case RefVal::Owned:
3037 case RefVal::NotOwned:
3038 V = V + 1;
3039 break;
3040 case RefVal::Released:
3041 // Non-GC cases are handled above.
Jordy Rose17a38e22011-09-02 05:55:19 +00003042 assert(C.isObjCGCEnabled());
Jordy Rosee0a5d322011-08-23 20:27:16 +00003043 V = (V ^ RefVal::Owned) + 1;
3044 break;
3045 }
3046 break;
3047
Jordy Rosee0a5d322011-08-23 20:27:16 +00003048 case DecRef:
3049 case DecRefBridgedTransfered:
Jordan Rose4531b7d2012-07-02 19:27:43 +00003050 case DecRefAndStopTracking:
Jordy Rosee0a5d322011-08-23 20:27:16 +00003051 switch (V.getKind()) {
3052 default:
3053 // case 'RefVal::Released' handled above.
3054 llvm_unreachable("Invalid RefVal state for a release.");
Jordy Rosee0a5d322011-08-23 20:27:16 +00003055
3056 case RefVal::Owned:
3057 assert(V.getCount() > 0);
3058 if (V.getCount() == 1)
3059 V = V ^ (E == DecRefBridgedTransfered ?
3060 RefVal::NotOwned : RefVal::Released);
Jordan Rose4531b7d2012-07-02 19:27:43 +00003061 else if (E == DecRefAndStopTracking)
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003062 return removeRefBinding(state, sym);
Jordan Rose4531b7d2012-07-02 19:27:43 +00003063
Jordy Rosee0a5d322011-08-23 20:27:16 +00003064 V = V - 1;
3065 break;
3066
3067 case RefVal::NotOwned:
Jordan Rose4531b7d2012-07-02 19:27:43 +00003068 if (V.getCount() > 0) {
3069 if (E == DecRefAndStopTracking)
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003070 return removeRefBinding(state, sym);
Jordy Rosee0a5d322011-08-23 20:27:16 +00003071 V = V - 1;
Jordan Rose4531b7d2012-07-02 19:27:43 +00003072 } else {
Jordy Rosee0a5d322011-08-23 20:27:16 +00003073 V = V ^ RefVal::ErrorReleaseNotOwned;
3074 hasErr = V.getKind();
3075 }
3076 break;
3077
3078 case RefVal::Released:
3079 // Non-GC cases are handled above.
Jordy Rose17a38e22011-09-02 05:55:19 +00003080 assert(C.isObjCGCEnabled());
Jordy Rosee0a5d322011-08-23 20:27:16 +00003081 V = V ^ RefVal::ErrorUseAfterRelease;
3082 hasErr = V.getKind();
3083 break;
3084 }
3085 break;
3086 }
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003087 return setRefBinding(state, sym, V);
Jordy Rosee0a5d322011-08-23 20:27:16 +00003088}
3089
Ted Kremenek8bef8232012-01-26 21:29:00 +00003090void RetainCountChecker::processNonLeakError(ProgramStateRef St,
Jordy Rose910c4052011-09-02 06:44:22 +00003091 SourceRange ErrorRange,
3092 RefVal::Kind ErrorKind,
3093 SymbolRef Sym,
3094 CheckerContext &C) const {
Jordy Rose294396b2011-08-22 23:48:23 +00003095 ExplodedNode *N = C.generateSink(St);
3096 if (!N)
3097 return;
3098
Jordy Rose294396b2011-08-22 23:48:23 +00003099 CFRefBug *BT;
3100 switch (ErrorKind) {
3101 default:
3102 llvm_unreachable("Unhandled error.");
Jordy Rose294396b2011-08-22 23:48:23 +00003103 case RefVal::ErrorUseAfterRelease:
Jordy Rosed6334e12011-08-25 00:34:03 +00003104 if (!useAfterRelease)
3105 useAfterRelease.reset(new UseAfterRelease());
3106 BT = &*useAfterRelease;
Jordy Rose294396b2011-08-22 23:48:23 +00003107 break;
3108 case RefVal::ErrorReleaseNotOwned:
Jordy Rosed6334e12011-08-25 00:34:03 +00003109 if (!releaseNotOwned)
3110 releaseNotOwned.reset(new BadRelease());
3111 BT = &*releaseNotOwned;
Jordy Rose294396b2011-08-22 23:48:23 +00003112 break;
3113 case RefVal::ErrorDeallocGC:
Jordy Rosed6334e12011-08-25 00:34:03 +00003114 if (!deallocGC)
3115 deallocGC.reset(new DeallocGC());
3116 BT = &*deallocGC;
Jordy Rose294396b2011-08-22 23:48:23 +00003117 break;
3118 case RefVal::ErrorDeallocNotOwned:
Jordy Rosed6334e12011-08-25 00:34:03 +00003119 if (!deallocNotOwned)
3120 deallocNotOwned.reset(new DeallocNotOwned());
3121 BT = &*deallocNotOwned;
Jordy Rose294396b2011-08-22 23:48:23 +00003122 break;
3123 }
3124
Jordy Rosed6334e12011-08-25 00:34:03 +00003125 assert(BT);
David Blaikie4e4d0842012-03-11 07:00:24 +00003126 CFRefReport *report = new CFRefReport(*BT, C.getASTContext().getLangOpts(),
Jordy Rose17a38e22011-09-02 05:55:19 +00003127 C.isObjCGCEnabled(), SummaryLog,
3128 N, Sym);
Jordy Rose294396b2011-08-22 23:48:23 +00003129 report->addRange(ErrorRange);
3130 C.EmitReport(report);
3131}
3132
Jordy Rose910c4052011-09-02 06:44:22 +00003133//===----------------------------------------------------------------------===//
3134// Handle the return values of retain-count-related functions.
3135//===----------------------------------------------------------------------===//
3136
3137bool RetainCountChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
Jordy Rose76c506f2011-08-21 21:58:18 +00003138 // Get the callee. We're only interested in simple C functions.
Ted Kremenek8bef8232012-01-26 21:29:00 +00003139 ProgramStateRef state = C.getState();
Anna Zaksb805c8f2011-12-01 05:57:37 +00003140 const FunctionDecl *FD = C.getCalleeDecl(CE);
Jordy Rose76c506f2011-08-21 21:58:18 +00003141 if (!FD)
3142 return false;
3143
3144 IdentifierInfo *II = FD->getIdentifier();
3145 if (!II)
3146 return false;
3147
3148 // For now, we're only handling the functions that return aliases of their
3149 // arguments: CFRetain and CFMakeCollectable (and their families).
3150 // Eventually we should add other functions we can model entirely,
3151 // such as CFRelease, which don't invalidate their arguments or globals.
3152 if (CE->getNumArgs() != 1)
3153 return false;
3154
3155 // Get the name of the function.
3156 StringRef FName = II->getName();
3157 FName = FName.substr(FName.find_first_not_of('_'));
3158
3159 // See if it's one of the specific functions we know how to eval.
3160 bool canEval = false;
3161
Anna Zaksb805c8f2011-12-01 05:57:37 +00003162 QualType ResultTy = CE->getCallReturnType();
Jordy Rose76c506f2011-08-21 21:58:18 +00003163 if (ResultTy->isObjCIdType()) {
3164 // Handle: id NSMakeCollectable(CFTypeRef)
3165 canEval = II->isStr("NSMakeCollectable");
3166 } else if (ResultTy->isPointerType()) {
3167 // Handle: (CF|CG)Retain
3168 // CFMakeCollectable
3169 // It's okay to be a little sloppy here (CGMakeCollectable doesn't exist).
3170 if (cocoa::isRefType(ResultTy, "CF", FName) ||
3171 cocoa::isRefType(ResultTy, "CG", FName)) {
3172 canEval = isRetain(FD, FName) || isMakeCollectable(FD, FName);
3173 }
3174 }
3175
3176 if (!canEval)
3177 return false;
3178
3179 // Bind the return value.
Ted Kremenek5eca4822012-01-06 22:09:28 +00003180 const LocationContext *LCtx = C.getLocationContext();
3181 SVal RetVal = state->getSVal(CE->getArg(0), LCtx);
Jordy Rose76c506f2011-08-21 21:58:18 +00003182 if (RetVal.isUnknown()) {
3183 // If the receiver is unknown, conjure a return value.
3184 SValBuilder &SVB = C.getSValBuilder();
Anna Zaks5d0ea6d2011-10-04 20:43:05 +00003185 unsigned Count = C.getCurrentBlockCount();
Benjamin Kramer7373ead2012-07-18 19:08:44 +00003186 RetVal = SVB.getConjuredSymbolVal(0, CE, LCtx, ResultTy, Count);
Jordy Rose76c506f2011-08-21 21:58:18 +00003187 }
Ted Kremenek5eca4822012-01-06 22:09:28 +00003188 state = state->BindExpr(CE, LCtx, RetVal, false);
Jordy Rose76c506f2011-08-21 21:58:18 +00003189
Jordy Rose294396b2011-08-22 23:48:23 +00003190 // FIXME: This should not be necessary, but otherwise the argument seems to be
3191 // considered alive during the next statement.
3192 if (const MemRegion *ArgRegion = RetVal.getAsRegion()) {
3193 // Save the refcount status of the argument.
3194 SymbolRef Sym = RetVal.getAsLocSymbol();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003195 const RefVal *Binding = 0;
Jordy Rose294396b2011-08-22 23:48:23 +00003196 if (Sym)
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003197 Binding = getRefBinding(state, Sym);
Jordy Rose76c506f2011-08-21 21:58:18 +00003198
Jordy Rose294396b2011-08-22 23:48:23 +00003199 // Invalidate the argument region.
Anna Zaks5d0ea6d2011-10-04 20:43:05 +00003200 unsigned Count = C.getCurrentBlockCount();
Ted Kremenek3133f792012-02-17 23:13:45 +00003201 state = state->invalidateRegions(ArgRegion, CE, Count, LCtx);
Jordy Rose76c506f2011-08-21 21:58:18 +00003202
Jordy Rose294396b2011-08-22 23:48:23 +00003203 // Restore the refcount status of the argument.
3204 if (Binding)
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003205 state = setRefBinding(state, Sym, *Binding);
Jordy Rose294396b2011-08-22 23:48:23 +00003206 }
3207
Anna Zaks0bd6b112011-10-26 21:06:34 +00003208 C.addTransition(state);
Jordy Rose76c506f2011-08-21 21:58:18 +00003209 return true;
3210}
3211
Jordy Rose910c4052011-09-02 06:44:22 +00003212//===----------------------------------------------------------------------===//
3213// Handle return statements.
3214//===----------------------------------------------------------------------===//
Jordy Rosef53e8c72011-08-23 19:43:16 +00003215
Ted Kremeneke5715782012-02-25 02:09:09 +00003216// Return true if the current LocationContext has no caller context.
3217static bool inTopFrame(CheckerContext &C) {
3218 const LocationContext *LC = C.getLocationContext();
3219 return LC->getParent() == 0;
3220}
3221
Jordy Rose910c4052011-09-02 06:44:22 +00003222void RetainCountChecker::checkPreStmt(const ReturnStmt *S,
3223 CheckerContext &C) const {
Ted Kremeneke5715782012-02-25 02:09:09 +00003224
3225 // Only adjust the reference count if this is the top-level call frame,
3226 // and not the result of inlining. In the future, we should do
3227 // better checking even for inlined calls, and see if they match
3228 // with their expected semantics (e.g., the method should return a retained
3229 // object, etc.).
3230 if (!inTopFrame(C))
3231 return;
3232
Jordy Rosef53e8c72011-08-23 19:43:16 +00003233 const Expr *RetE = S->getRetValue();
3234 if (!RetE)
3235 return;
3236
Ted Kremenek8bef8232012-01-26 21:29:00 +00003237 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00003238 SymbolRef Sym =
3239 state->getSValAsScalarOrLoc(RetE, C.getLocationContext()).getAsLocSymbol();
Jordy Rosef53e8c72011-08-23 19:43:16 +00003240 if (!Sym)
3241 return;
3242
3243 // Get the reference count binding (if any).
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003244 const RefVal *T = getRefBinding(state, Sym);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003245 if (!T)
3246 return;
3247
3248 // Change the reference count.
3249 RefVal X = *T;
3250
3251 switch (X.getKind()) {
3252 case RefVal::Owned: {
3253 unsigned cnt = X.getCount();
3254 assert(cnt > 0);
3255 X.setCount(cnt - 1);
3256 X = X ^ RefVal::ReturnedOwned;
3257 break;
3258 }
3259
3260 case RefVal::NotOwned: {
3261 unsigned cnt = X.getCount();
3262 if (cnt) {
3263 X.setCount(cnt - 1);
3264 X = X ^ RefVal::ReturnedOwned;
3265 }
3266 else {
3267 X = X ^ RefVal::ReturnedNotOwned;
3268 }
3269 break;
3270 }
3271
3272 default:
3273 return;
3274 }
3275
3276 // Update the binding.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003277 state = setRefBinding(state, Sym, X);
Anna Zaks0bd6b112011-10-26 21:06:34 +00003278 ExplodedNode *Pred = C.addTransition(state);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003279
3280 // At this point we have updated the state properly.
3281 // Everything after this is merely checking to see if the return value has
3282 // been over- or under-retained.
3283
3284 // Did we cache out?
3285 if (!Pred)
3286 return;
3287
Jordy Rosef53e8c72011-08-23 19:43:16 +00003288 // Update the autorelease counts.
3289 static SimpleProgramPointTag
Jordy Rose910c4052011-09-02 06:44:22 +00003290 AutoreleaseTag("RetainCountChecker : Autorelease");
Anna Zaks4eff8232011-10-05 23:44:11 +00003291 GenericNodeBuilderRefCount Bd(C, &AutoreleaseTag);
Anna Zaks6a93bd52011-10-25 19:57:11 +00003292 llvm::tie(Pred, state) = handleAutoreleaseCounts(state, Bd, Pred, C, Sym, X);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003293
3294 // Did we cache out?
Jordy Rose8d228632011-08-23 20:07:14 +00003295 if (!Pred)
Jordy Rosef53e8c72011-08-23 19:43:16 +00003296 return;
3297
3298 // Get the updated binding.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003299 T = getRefBinding(state, Sym);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003300 assert(T);
3301 X = *T;
3302
3303 // Consult the summary of the enclosing method.
Jordy Rose17a38e22011-09-02 05:55:19 +00003304 RetainSummaryManager &Summaries = getSummaryManager(C);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003305 const Decl *CD = &Pred->getCodeDecl();
Jordan Rose4531b7d2012-07-02 19:27:43 +00003306 RetEffect RE = RetEffect::MakeNoRet();
Jordy Rosef53e8c72011-08-23 19:43:16 +00003307
Jordan Rose4531b7d2012-07-02 19:27:43 +00003308 // FIXME: What is the convention for blocks? Is there one?
Jordy Rosef53e8c72011-08-23 19:43:16 +00003309 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CD)) {
Jordy Roseb6cfc092011-08-25 00:10:37 +00003310 const RetainSummary *Summ = Summaries.getMethodSummary(MD);
Jordan Rose4531b7d2012-07-02 19:27:43 +00003311 RE = Summ->getRetEffect();
3312 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) {
3313 if (!isa<CXXMethodDecl>(FD)) {
3314 const RetainSummary *Summ = Summaries.getFunctionSummary(FD);
3315 RE = Summ->getRetEffect();
3316 }
Jordy Rosef53e8c72011-08-23 19:43:16 +00003317 }
3318
Jordan Rose4531b7d2012-07-02 19:27:43 +00003319 checkReturnWithRetEffect(S, C, Pred, RE, X, Sym, state);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003320}
3321
Jordy Rose910c4052011-09-02 06:44:22 +00003322void RetainCountChecker::checkReturnWithRetEffect(const ReturnStmt *S,
3323 CheckerContext &C,
3324 ExplodedNode *Pred,
3325 RetEffect RE, RefVal X,
3326 SymbolRef Sym,
Ted Kremenek8bef8232012-01-26 21:29:00 +00003327 ProgramStateRef state) const {
Jordy Rosef53e8c72011-08-23 19:43:16 +00003328 // Any leaks or other errors?
3329 if (X.isReturnedOwned() && X.getCount() == 0) {
3330 if (RE.getKind() != RetEffect::NoRet) {
3331 bool hasError = false;
Jordy Rose17a38e22011-09-02 05:55:19 +00003332 if (C.isObjCGCEnabled() && RE.getObjKind() == RetEffect::ObjC) {
Jordy Rosef53e8c72011-08-23 19:43:16 +00003333 // Things are more complicated with garbage collection. If the
3334 // returned object is suppose to be an Objective-C object, we have
3335 // a leak (as the caller expects a GC'ed object) because no
3336 // method should return ownership unless it returns a CF object.
3337 hasError = true;
3338 X = X ^ RefVal::ErrorGCLeakReturned;
3339 }
3340 else if (!RE.isOwned()) {
3341 // Either we are using GC and the returned object is a CF type
3342 // or we aren't using GC. In either case, we expect that the
3343 // enclosing method is expected to return ownership.
3344 hasError = true;
3345 X = X ^ RefVal::ErrorLeakReturned;
3346 }
3347
3348 if (hasError) {
3349 // Generate an error node.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003350 state = setRefBinding(state, Sym, X);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003351
3352 static SimpleProgramPointTag
Jordy Rose910c4052011-09-02 06:44:22 +00003353 ReturnOwnLeakTag("RetainCountChecker : ReturnsOwnLeak");
Anna Zaks0bd6b112011-10-26 21:06:34 +00003354 ExplodedNode *N = C.addTransition(state, Pred, &ReturnOwnLeakTag);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003355 if (N) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003356 const LangOptions &LOpts = C.getASTContext().getLangOpts();
Jordy Rose17a38e22011-09-02 05:55:19 +00003357 bool GCEnabled = C.isObjCGCEnabled();
Jordy Rosef53e8c72011-08-23 19:43:16 +00003358 CFRefReport *report =
Jordy Rose17a38e22011-09-02 05:55:19 +00003359 new CFRefLeakReport(*getLeakAtReturnBug(LOpts, GCEnabled),
3360 LOpts, GCEnabled, SummaryLog,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003361 N, Sym, C);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003362 C.EmitReport(report);
3363 }
3364 }
3365 }
3366 } else if (X.isReturnedNotOwned()) {
3367 if (RE.isOwned()) {
3368 // Trying to return a not owned object to a caller expecting an
3369 // owned object.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003370 state = setRefBinding(state, Sym, X ^ RefVal::ErrorReturnedNotOwned);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003371
3372 static SimpleProgramPointTag
Jordy Rose910c4052011-09-02 06:44:22 +00003373 ReturnNotOwnedTag("RetainCountChecker : ReturnNotOwnedForOwned");
Anna Zaks0bd6b112011-10-26 21:06:34 +00003374 ExplodedNode *N = C.addTransition(state, Pred, &ReturnNotOwnedTag);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003375 if (N) {
Jordy Rosed6334e12011-08-25 00:34:03 +00003376 if (!returnNotOwnedForOwned)
3377 returnNotOwnedForOwned.reset(new ReturnedNotOwnedForOwned());
3378
Jordy Rosef53e8c72011-08-23 19:43:16 +00003379 CFRefReport *report =
Jordy Rosed6334e12011-08-25 00:34:03 +00003380 new CFRefReport(*returnNotOwnedForOwned,
David Blaikie4e4d0842012-03-11 07:00:24 +00003381 C.getASTContext().getLangOpts(),
Jordy Rose17a38e22011-09-02 05:55:19 +00003382 C.isObjCGCEnabled(), SummaryLog, N, Sym);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003383 C.EmitReport(report);
3384 }
3385 }
3386 }
3387}
3388
Jordy Rose8d228632011-08-23 20:07:14 +00003389//===----------------------------------------------------------------------===//
Jordy Rose910c4052011-09-02 06:44:22 +00003390// Check various ways a symbol can be invalidated.
3391//===----------------------------------------------------------------------===//
3392
Anna Zaks390909c2011-10-06 00:43:15 +00003393void RetainCountChecker::checkBind(SVal loc, SVal val, const Stmt *S,
Jordy Rose910c4052011-09-02 06:44:22 +00003394 CheckerContext &C) const {
3395 // Are we storing to something that causes the value to "escape"?
3396 bool escapes = true;
3397
3398 // A value escapes in three possible cases (this may change):
3399 //
3400 // (1) we are binding to something that is not a memory region.
3401 // (2) we are binding to a memregion that does not have stack storage
3402 // (3) we are binding to a memregion with stack storage that the store
3403 // does not understand.
Ted Kremenek8bef8232012-01-26 21:29:00 +00003404 ProgramStateRef state = C.getState();
Jordy Rose910c4052011-09-02 06:44:22 +00003405
3406 if (loc::MemRegionVal *regionLoc = dyn_cast<loc::MemRegionVal>(&loc)) {
3407 escapes = !regionLoc->getRegion()->hasStackStorage();
3408
3409 if (!escapes) {
3410 // To test (3), generate a new state with the binding added. If it is
3411 // the same state, then it escapes (since the store cannot represent
3412 // the binding).
Anna Zakse7958da2012-05-02 00:15:40 +00003413 // Do this only if we know that the store is not supposed to generate the
3414 // same state.
3415 SVal StoredVal = state->getSVal(regionLoc->getRegion());
3416 if (StoredVal != val)
3417 escapes = (state == (state->bindLoc(*regionLoc, val)));
Jordy Rose910c4052011-09-02 06:44:22 +00003418 }
Ted Kremenekde5b4fb2012-03-27 01:12:45 +00003419 if (!escapes) {
3420 // Case 4: We do not currently model what happens when a symbol is
3421 // assigned to a struct field, so be conservative here and let the symbol
3422 // go. TODO: This could definitely be improved upon.
3423 escapes = !isa<VarRegion>(regionLoc->getRegion());
3424 }
Jordy Rose910c4052011-09-02 06:44:22 +00003425 }
3426
3427 // If our store can represent the binding and we aren't storing to something
3428 // that doesn't have local storage then just return and have the simulation
3429 // state continue as is.
3430 if (!escapes)
3431 return;
3432
3433 // Otherwise, find all symbols referenced by 'val' that we are tracking
3434 // and stop tracking them.
3435 state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
Anna Zaks0bd6b112011-10-26 21:06:34 +00003436 C.addTransition(state);
Jordy Rose910c4052011-09-02 06:44:22 +00003437}
3438
Ted Kremenek8bef8232012-01-26 21:29:00 +00003439ProgramStateRef RetainCountChecker::evalAssume(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003440 SVal Cond,
3441 bool Assumption) const {
3442
3443 // FIXME: We may add to the interface of evalAssume the list of symbols
3444 // whose assumptions have changed. For now we just iterate through the
3445 // bindings and check if any of the tracked symbols are NULL. This isn't
3446 // too bad since the number of symbols we will track in practice are
3447 // probably small and evalAssume is only called at branches and a few
3448 // other places.
3449 RefBindings B = state->get<RefBindings>();
3450
3451 if (B.isEmpty())
3452 return state;
3453
3454 bool changed = false;
3455 RefBindings::Factory &RefBFactory = state->get_context<RefBindings>();
3456
3457 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
3458 // Check if the symbol is null (or equal to any constant).
3459 // If this is the case, stop tracking the symbol.
3460 if (state->getSymVal(I.getKey())) {
3461 changed = true;
3462 B = RefBFactory.remove(B, I.getKey());
3463 }
3464 }
3465
3466 if (changed)
3467 state = state->set<RefBindings>(B);
3468
3469 return state;
3470}
3471
Ted Kremenek8bef8232012-01-26 21:29:00 +00003472ProgramStateRef
3473RetainCountChecker::checkRegionChanges(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003474 const StoreManager::InvalidatedSymbols *invalidated,
3475 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00003476 ArrayRef<const MemRegion *> Regions,
Jordan Rose740d4902012-07-02 19:27:35 +00003477 const CallEvent *Call) const {
Jordy Rose910c4052011-09-02 06:44:22 +00003478 if (!invalidated)
3479 return state;
3480
3481 llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
3482 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
3483 E = ExplicitRegions.end(); I != E; ++I) {
3484 if (const SymbolicRegion *SR = (*I)->StripCasts()->getAs<SymbolicRegion>())
3485 WhitelistedSymbols.insert(SR->getSymbol());
3486 }
3487
3488 for (StoreManager::InvalidatedSymbols::const_iterator I=invalidated->begin(),
3489 E = invalidated->end(); I!=E; ++I) {
3490 SymbolRef sym = *I;
3491 if (WhitelistedSymbols.count(sym))
3492 continue;
3493 // Remove any existing reference-count binding.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003494 state = removeRefBinding(state, sym);
Jordy Rose910c4052011-09-02 06:44:22 +00003495 }
3496 return state;
3497}
3498
3499//===----------------------------------------------------------------------===//
Jordy Rose8d228632011-08-23 20:07:14 +00003500// Handle dead symbols and end-of-path.
3501//===----------------------------------------------------------------------===//
3502
Ted Kremenek8bef8232012-01-26 21:29:00 +00003503std::pair<ExplodedNode *, ProgramStateRef >
3504RetainCountChecker::handleAutoreleaseCounts(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003505 GenericNodeBuilderRefCount Bd,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003506 ExplodedNode *Pred,
3507 CheckerContext &Ctx,
Jordy Rose910c4052011-09-02 06:44:22 +00003508 SymbolRef Sym, RefVal V) const {
Jordy Rose8d228632011-08-23 20:07:14 +00003509 unsigned ACnt = V.getAutoreleaseCount();
3510
3511 // No autorelease counts? Nothing to be done.
3512 if (!ACnt)
3513 return std::make_pair(Pred, state);
3514
Anna Zaks6a93bd52011-10-25 19:57:11 +00003515 assert(!Ctx.isObjCGCEnabled() && "Autorelease counts in GC mode?");
Jordy Rose8d228632011-08-23 20:07:14 +00003516 unsigned Cnt = V.getCount();
3517
3518 // FIXME: Handle sending 'autorelease' to already released object.
3519
3520 if (V.getKind() == RefVal::ReturnedOwned)
3521 ++Cnt;
3522
3523 if (ACnt <= Cnt) {
3524 if (ACnt == Cnt) {
3525 V.clearCounts();
3526 if (V.getKind() == RefVal::ReturnedOwned)
3527 V = V ^ RefVal::ReturnedNotOwned;
3528 else
3529 V = V ^ RefVal::NotOwned;
3530 } else {
3531 V.setCount(Cnt - ACnt);
3532 V.setAutoreleaseCount(0);
3533 }
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003534 state = setRefBinding(state, Sym, V);
Jordy Rose8d228632011-08-23 20:07:14 +00003535 ExplodedNode *N = Bd.MakeNode(state, Pred);
3536 if (N == 0)
3537 state = 0;
3538 return std::make_pair(N, state);
3539 }
3540
3541 // Woah! More autorelease counts then retain counts left.
3542 // Emit hard error.
3543 V = V ^ RefVal::ErrorOverAutorelease;
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003544 state = setRefBinding(state, Sym, V);
Jordy Rose8d228632011-08-23 20:07:14 +00003545
Anna Zaksf05aac82011-10-18 23:05:58 +00003546 if (ExplodedNode *N = Bd.MakeNode(state, Pred, true)) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003547 SmallString<128> sbuf;
Jordy Rose8d228632011-08-23 20:07:14 +00003548 llvm::raw_svector_ostream os(sbuf);
3549 os << "Object over-autoreleased: object was sent -autorelease ";
3550 if (V.getAutoreleaseCount() > 1)
3551 os << V.getAutoreleaseCount() << " times ";
3552 os << "but the object has a +" << V.getCount() << " retain count";
3553
Jordy Rosed6334e12011-08-25 00:34:03 +00003554 if (!overAutorelease)
3555 overAutorelease.reset(new OverAutorelease());
3556
David Blaikie4e4d0842012-03-11 07:00:24 +00003557 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
Jordy Rose8d228632011-08-23 20:07:14 +00003558 CFRefReport *report =
Jordy Rosed6334e12011-08-25 00:34:03 +00003559 new CFRefReport(*overAutorelease, LOpts, /* GCEnabled = */ false,
3560 SummaryLog, N, Sym, os.str());
Anna Zaks6a93bd52011-10-25 19:57:11 +00003561 Ctx.EmitReport(report);
Jordy Rose8d228632011-08-23 20:07:14 +00003562 }
3563
Ted Kremenek8bef8232012-01-26 21:29:00 +00003564 return std::make_pair((ExplodedNode *)0, (ProgramStateRef )0);
Jordy Rose8d228632011-08-23 20:07:14 +00003565}
Jordy Rose38f17d62011-08-23 19:01:07 +00003566
Ted Kremenek8bef8232012-01-26 21:29:00 +00003567ProgramStateRef
3568RetainCountChecker::handleSymbolDeath(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003569 SymbolRef sid, RefVal V,
Jordy Rose38f17d62011-08-23 19:01:07 +00003570 SmallVectorImpl<SymbolRef> &Leaked) const {
Jordy Rose53376122011-08-24 04:48:19 +00003571 bool hasLeak = false;
Jordy Rose38f17d62011-08-23 19:01:07 +00003572 if (V.isOwned())
3573 hasLeak = true;
3574 else if (V.isNotOwned() || V.isReturnedOwned())
3575 hasLeak = (V.getCount() > 0);
3576
3577 if (!hasLeak)
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003578 return removeRefBinding(state, sid);
Jordy Rose38f17d62011-08-23 19:01:07 +00003579
3580 Leaked.push_back(sid);
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003581 return setRefBinding(state, sid, V ^ RefVal::ErrorLeak);
Jordy Rose38f17d62011-08-23 19:01:07 +00003582}
3583
3584ExplodedNode *
Ted Kremenek8bef8232012-01-26 21:29:00 +00003585RetainCountChecker::processLeaks(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003586 SmallVectorImpl<SymbolRef> &Leaked,
3587 GenericNodeBuilderRefCount &Builder,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003588 CheckerContext &Ctx,
3589 ExplodedNode *Pred) const {
Jordy Rose38f17d62011-08-23 19:01:07 +00003590 if (Leaked.empty())
3591 return Pred;
3592
3593 // Generate an intermediate node representing the leak point.
3594 ExplodedNode *N = Builder.MakeNode(state, Pred);
3595
3596 if (N) {
3597 for (SmallVectorImpl<SymbolRef>::iterator
3598 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3599
David Blaikie4e4d0842012-03-11 07:00:24 +00003600 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
Anna Zaks6a93bd52011-10-25 19:57:11 +00003601 bool GCEnabled = Ctx.isObjCGCEnabled();
Jordy Rose17a38e22011-09-02 05:55:19 +00003602 CFRefBug *BT = Pred ? getLeakWithinFunctionBug(LOpts, GCEnabled)
3603 : getLeakAtReturnBug(LOpts, GCEnabled);
Jordy Rose38f17d62011-08-23 19:01:07 +00003604 assert(BT && "BugType not initialized.");
Jordy Rose20589562011-08-24 22:39:09 +00003605
Jordy Rose17a38e22011-09-02 05:55:19 +00003606 CFRefLeakReport *report = new CFRefLeakReport(*BT, LOpts, GCEnabled,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003607 SummaryLog, N, *I, Ctx);
3608 Ctx.EmitReport(report);
Jordy Rose38f17d62011-08-23 19:01:07 +00003609 }
3610 }
3611
3612 return N;
3613}
3614
Anna Zaksaf498a22011-10-25 19:56:48 +00003615void RetainCountChecker::checkEndPath(CheckerContext &Ctx) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +00003616 ProgramStateRef state = Ctx.getState();
Anna Zaksaf498a22011-10-25 19:56:48 +00003617 GenericNodeBuilderRefCount Bd(Ctx);
Jordy Rose38f17d62011-08-23 19:01:07 +00003618 RefBindings B = state->get<RefBindings>();
Anna Zaksaf498a22011-10-25 19:56:48 +00003619 ExplodedNode *Pred = Ctx.getPredecessor();
Jordy Rose38f17d62011-08-23 19:01:07 +00003620
3621 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Anna Zaks6a93bd52011-10-25 19:57:11 +00003622 llvm::tie(Pred, state) = handleAutoreleaseCounts(state, Bd, Pred, Ctx,
Jordy Rose8d228632011-08-23 20:07:14 +00003623 I->first, I->second);
3624 if (!state)
Jordy Rose38f17d62011-08-23 19:01:07 +00003625 return;
3626 }
3627
Ted Kremenek0cf3d472012-02-07 00:24:33 +00003628 // If the current LocationContext has a parent, don't check for leaks.
3629 // We will do that later.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003630 // FIXME: we should instead check for imbalances of the retain/releases,
Ted Kremenek0cf3d472012-02-07 00:24:33 +00003631 // and suggest annotations.
3632 if (Ctx.getLocationContext()->getParent())
3633 return;
3634
Jordy Rose38f17d62011-08-23 19:01:07 +00003635 B = state->get<RefBindings>();
3636 SmallVector<SymbolRef, 10> Leaked;
3637
3638 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I)
Jordy Rose8d228632011-08-23 20:07:14 +00003639 state = handleSymbolDeath(state, I->first, I->second, Leaked);
Jordy Rose38f17d62011-08-23 19:01:07 +00003640
Anna Zaks6a93bd52011-10-25 19:57:11 +00003641 processLeaks(state, Leaked, Bd, Ctx, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003642}
3643
3644const ProgramPointTag *
Jordy Rose910c4052011-09-02 06:44:22 +00003645RetainCountChecker::getDeadSymbolTag(SymbolRef sym) const {
Jordy Rose38f17d62011-08-23 19:01:07 +00003646 const SimpleProgramPointTag *&tag = DeadSymbolTags[sym];
3647 if (!tag) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003648 SmallString<64> buf;
Jordy Rose38f17d62011-08-23 19:01:07 +00003649 llvm::raw_svector_ostream out(buf);
Anna Zaksf62ceec2011-12-05 18:58:11 +00003650 out << "RetainCountChecker : Dead Symbol : ";
3651 sym->dumpToStream(out);
Jordy Rose38f17d62011-08-23 19:01:07 +00003652 tag = new SimpleProgramPointTag(out.str());
3653 }
3654 return tag;
3655}
3656
Jordy Rose910c4052011-09-02 06:44:22 +00003657void RetainCountChecker::checkDeadSymbols(SymbolReaper &SymReaper,
3658 CheckerContext &C) const {
Jordy Rose38f17d62011-08-23 19:01:07 +00003659 ExplodedNode *Pred = C.getPredecessor();
3660
Ted Kremenek8bef8232012-01-26 21:29:00 +00003661 ProgramStateRef state = C.getState();
Jordy Rose38f17d62011-08-23 19:01:07 +00003662 RefBindings B = state->get<RefBindings>();
3663
3664 // Update counts from autorelease pools
3665 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3666 E = SymReaper.dead_end(); I != E; ++I) {
3667 SymbolRef Sym = *I;
3668 if (const RefVal *T = B.lookup(Sym)){
3669 // Use the symbol as the tag.
3670 // FIXME: This might not be as unique as we would like.
Anna Zaks4eff8232011-10-05 23:44:11 +00003671 GenericNodeBuilderRefCount Bd(C, getDeadSymbolTag(Sym));
Anna Zaks6a93bd52011-10-25 19:57:11 +00003672 llvm::tie(Pred, state) = handleAutoreleaseCounts(state, Bd, Pred, C,
Jordy Rose8d228632011-08-23 20:07:14 +00003673 Sym, *T);
3674 if (!state)
Jordy Rose38f17d62011-08-23 19:01:07 +00003675 return;
3676 }
3677 }
3678
3679 B = state->get<RefBindings>();
3680 SmallVector<SymbolRef, 10> Leaked;
3681
3682 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3683 E = SymReaper.dead_end(); I != E; ++I) {
3684 if (const RefVal *T = B.lookup(*I))
3685 state = handleSymbolDeath(state, *I, *T, Leaked);
3686 }
3687
3688 {
Anna Zaks4eff8232011-10-05 23:44:11 +00003689 GenericNodeBuilderRefCount Bd(C, this);
Anna Zaks6a93bd52011-10-25 19:57:11 +00003690 Pred = processLeaks(state, Leaked, Bd, C, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003691 }
3692
3693 // Did we cache out?
3694 if (!Pred)
3695 return;
3696
3697 // Now generate a new node that nukes the old bindings.
3698 RefBindings::Factory &F = state->get_context<RefBindings>();
3699
3700 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3701 E = SymReaper.dead_end(); I != E; ++I)
3702 B = F.remove(B, *I);
3703
3704 state = state->set<RefBindings>(B);
Anna Zaks0bd6b112011-10-26 21:06:34 +00003705 C.addTransition(state, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003706}
3707
Ted Kremenekd593eb92009-11-25 22:17:44 +00003708//===----------------------------------------------------------------------===//
Jordy Rosedbd658e2011-08-28 19:11:56 +00003709// Debug printing of refcount bindings and autorelease pools.
3710//===----------------------------------------------------------------------===//
3711
3712static void PrintPool(raw_ostream &Out, SymbolRef Sym,
Ted Kremenek8bef8232012-01-26 21:29:00 +00003713 ProgramStateRef State) {
Jordy Rosedbd658e2011-08-28 19:11:56 +00003714 Out << ' ';
3715 if (Sym)
Anna Zaksf62ceec2011-12-05 18:58:11 +00003716 Sym->dumpToStream(Out);
Jordy Rosedbd658e2011-08-28 19:11:56 +00003717 else
3718 Out << "<pool>";
3719 Out << ":{";
3720
3721 // Get the contents of the pool.
3722 if (const ARCounts *Cnts = State->get<AutoreleasePoolContents>(Sym))
3723 for (ARCounts::iterator I = Cnts->begin(), E = Cnts->end(); I != E; ++I)
3724 Out << '(' << I.getKey() << ',' << I.getData() << ')';
3725
3726 Out << '}';
3727}
3728
Ted Kremenek8bef8232012-01-26 21:29:00 +00003729static bool UsesAutorelease(ProgramStateRef state) {
Jordy Rosedbd658e2011-08-28 19:11:56 +00003730 // A state uses autorelease if it allocated an autorelease pool or if it has
3731 // objects in the caller's autorelease pool.
3732 return !state->get<AutoreleaseStack>().isEmpty() ||
3733 state->get<AutoreleasePoolContents>(SymbolRef());
3734}
3735
Ted Kremenek8bef8232012-01-26 21:29:00 +00003736void RetainCountChecker::printState(raw_ostream &Out, ProgramStateRef State,
Jordy Rose910c4052011-09-02 06:44:22 +00003737 const char *NL, const char *Sep) const {
Jordy Rosedbd658e2011-08-28 19:11:56 +00003738
3739 RefBindings B = State->get<RefBindings>();
3740
3741 if (!B.isEmpty())
3742 Out << Sep << NL;
3743
3744 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
3745 Out << I->first << " : ";
3746 I->second.print(Out);
3747 Out << NL;
3748 }
3749
3750 // Print the autorelease stack.
3751 if (UsesAutorelease(State)) {
3752 Out << Sep << NL << "AR pool stack:";
3753 ARStack Stack = State->get<AutoreleaseStack>();
3754
3755 PrintPool(Out, SymbolRef(), State); // Print the caller's pool.
3756 for (ARStack::iterator I = Stack.begin(), E = Stack.end(); I != E; ++I)
3757 PrintPool(Out, *I, State);
3758
3759 Out << NL;
3760 }
3761}
3762
3763//===----------------------------------------------------------------------===//
Jordy Rose910c4052011-09-02 06:44:22 +00003764// Checker registration.
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00003765//===----------------------------------------------------------------------===//
3766
Jordy Rose17a38e22011-09-02 05:55:19 +00003767void ento::registerRetainCountChecker(CheckerManager &Mgr) {
Jordy Rose910c4052011-09-02 06:44:22 +00003768 Mgr.registerChecker<RetainCountChecker>();
Jordy Rose17a38e22011-09-02 05:55:19 +00003769}
3770