blob: d0618d0dddfe0b8e369ee99cca3507b9d85c7fe7 [file] [log] [blame]
Jordy Rose910c4052011-09-02 06:44:22 +00001//==-- RetainCountChecker.cpp - Checks for leaks and other issues -*- C++ -*--//
Ted Kremenek2fff37e2008-03-06 00:08:09 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Jordy Rose910c4052011-09-02 06:44:22 +000010// This file defines the methods for RetainCountChecker, which implements
11// a reference count checker for Core Foundation and Cocoa on (Mac OS X).
Ted Kremenek2fff37e2008-03-06 00:08:09 +000012//
13//===----------------------------------------------------------------------===//
14
Jordy Rose910c4052011-09-02 06:44:22 +000015#include "ClangSACheckers.h"
Mike Stump1eb44332009-09-09 15:08:12 +000016#include "clang/AST/DeclObjC.h"
Ted Kremenekb2771592011-03-30 17:41:19 +000017#include "clang/AST/DeclCXX.h"
Ted Kremenek0b526b42010-02-18 00:05:58 +000018#include "clang/Basic/LangOptions.h"
19#include "clang/Basic/SourceManager.h"
Jordy Rose910c4052011-09-02 06:44:22 +000020#include "clang/Analysis/DomainSpecific/CocoaConventions.h"
Ted Kremenek4c42bb72011-11-14 21:59:21 +000021#include "clang/AST/ParentMap.h"
Jordy Rose910c4052011-09-02 06:44:22 +000022#include "clang/StaticAnalyzer/Core/Checker.h"
23#include "clang/StaticAnalyzer/Core/CheckerManager.h"
Ted Kremenek9b663712011-02-10 01:03:03 +000024#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
25#include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
Jordan Rose4531b7d2012-07-02 19:27:43 +000026#include "clang/StaticAnalyzer/Core/PathSensitive/Calls.h"
Jordy Rose910c4052011-09-02 06:44:22 +000027#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
Ted Kremenek18c66fd2011-08-15 22:09:50 +000028#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
Ted Kremenek9b663712011-02-10 01:03:03 +000029#include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000030#include "llvm/ADT/DenseMap.h"
31#include "llvm/ADT/FoldingSet.h"
Ted Kremenek6d348932008-10-21 15:53:15 +000032#include "llvm/ADT/ImmutableList.h"
Ted Kremenek0b526b42010-02-18 00:05:58 +000033#include "llvm/ADT/ImmutableMap.h"
Benjamin Kramer8fe83e12012-02-04 13:45:25 +000034#include "llvm/ADT/SmallString.h"
Ted Kremenek6ed9afc2008-05-16 18:33:44 +000035#include "llvm/ADT/STLExtras.h"
Ted Kremenek0b526b42010-02-18 00:05:58 +000036#include "llvm/ADT/StringExtras.h"
Chris Lattner5f9e2722011-07-23 10:55:15 +000037#include <cstdarg>
Ted Kremenek2fff37e2008-03-06 00:08:09 +000038
39using namespace clang;
Ted Kremenek9ef65372010-12-23 07:20:52 +000040using namespace ento;
Ted Kremeneka64e89b2010-01-27 06:13:48 +000041using llvm::StrInStrNoCase;
Ted Kremenek4c79e552008-11-05 16:54:44 +000042
Ted Kremenekd775c662010-05-21 21:57:00 +000043namespace {
Jordy Rose910c4052011-09-02 06:44:22 +000044/// Wrapper around different kinds of node builder, so that helper functions
45/// can have a common interface.
Francois Pichetea097852011-01-11 10:41:37 +000046class GenericNodeBuilderRefCount {
Anna Zaks4eff8232011-10-05 23:44:11 +000047 CheckerContext *C;
Ted Kremenekca804532011-08-12 23:04:46 +000048 const ProgramPointTag *tag;
Ted Kremenek9d9d3a62009-05-08 23:09:42 +000049public:
Anna Zaks4eff8232011-10-05 23:44:11 +000050 GenericNodeBuilderRefCount(CheckerContext &c,
Anna Zaksaf498a22011-10-25 19:56:48 +000051 const ProgramPointTag *t = 0)
Anna Zaks6a93bd52011-10-25 19:57:11 +000052 : C(&c), tag(t){}
Zhongxing Xu031ccc02009-08-06 12:48:26 +000053
Ted Kremenek8bef8232012-01-26 21:29:00 +000054 ExplodedNode *MakeNode(ProgramStateRef state, ExplodedNode *Pred,
Anna Zaksf05aac82011-10-18 23:05:58 +000055 bool MarkAsSink = false) {
Anna Zaks0bd6b112011-10-26 21:06:34 +000056 return C->addTransition(state, Pred, tag, MarkAsSink);
Ted Kremenek9d9d3a62009-05-08 23:09:42 +000057 }
58};
59} // end anonymous namespace
60
Ted Kremenek05cbe1a2008-04-09 23:49:11 +000061//===----------------------------------------------------------------------===//
Ted Kremenek553cf182008-06-25 21:21:56 +000062// Primitives used for constructing summaries for function/method calls.
Ted Kremenek05cbe1a2008-04-09 23:49:11 +000063//===----------------------------------------------------------------------===//
64
Ted Kremenek553cf182008-06-25 21:21:56 +000065/// ArgEffect is used to summarize a function/method call's effect on a
66/// particular argument.
Jordy Rosebd85b132011-08-24 19:10:50 +000067enum ArgEffect { DoNothing, Autorelease, Dealloc, DecRef, DecRefMsg,
John McCallf85e1932011-06-15 23:02:42 +000068 DecRefBridgedTransfered,
Jordan Rose4531b7d2012-07-02 19:27:43 +000069 DecRefAndStopTracking, DecRefMsgAndStopTracking,
Jordy Rosebd85b132011-08-24 19:10:50 +000070 IncRefMsg, IncRef, MakeCollectable, MayEscape,
Jordan Rose29299c62012-06-27 00:51:18 +000071 NewAutoreleasePool, StopTracking };
Ted Kremenek553cf182008-06-25 21:21:56 +000072
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000073namespace llvm {
Ted Kremenekb77449c2009-05-03 05:20:50 +000074template <> struct FoldingSetTrait<ArgEffect> {
75static inline void Profile(const ArgEffect X, FoldingSetNodeID& ID) {
76 ID.AddInteger((unsigned) X);
77}
Ted Kremenek553cf182008-06-25 21:21:56 +000078};
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000079} // end llvm namespace
80
Ted Kremenekb77449c2009-05-03 05:20:50 +000081/// ArgEffects summarizes the effects of a function/method call on all of
82/// its arguments.
83typedef llvm::ImmutableMap<unsigned,ArgEffect> ArgEffects;
84
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000085namespace {
Ted Kremenek553cf182008-06-25 21:21:56 +000086
87/// RetEffect is used to summarize a function/method call's behavior with
Mike Stump1eb44332009-09-09 15:08:12 +000088/// respect to its return value.
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +000089class RetEffect {
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000090public:
Jordy Rose76c506f2011-08-21 21:58:18 +000091 enum Kind { NoRet, OwnedSymbol, OwnedAllocatedSymbol,
John McCallf85e1932011-06-15 23:02:42 +000092 NotOwnedSymbol, GCNotOwnedSymbol, ARCNotOwnedSymbol,
Ted Kremenek78a35a32009-05-12 20:06:54 +000093 OwnedWhenTrackedReceiver };
Mike Stump1eb44332009-09-09 15:08:12 +000094
95 enum ObjKind { CF, ObjC, AnyObj };
Ted Kremenek2d1652e2009-01-28 05:56:51 +000096
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000097private:
Ted Kremenek2d1652e2009-01-28 05:56:51 +000098 Kind K;
99 ObjKind O;
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000100
Jordy Rose76c506f2011-08-21 21:58:18 +0000101 RetEffect(Kind k, ObjKind o = AnyObj) : K(k), O(o) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000102
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000103public:
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000104 Kind getKind() const { return K; }
105
106 ObjKind getObjKind() const { return O; }
Mike Stump1eb44332009-09-09 15:08:12 +0000107
Ted Kremeneka8833552009-04-29 23:03:22 +0000108 bool isOwned() const {
Ted Kremenek78a35a32009-05-12 20:06:54 +0000109 return K == OwnedSymbol || K == OwnedAllocatedSymbol ||
110 K == OwnedWhenTrackedReceiver;
Ted Kremeneka8833552009-04-29 23:03:22 +0000111 }
Mike Stump1eb44332009-09-09 15:08:12 +0000112
Jordy Rose4df54fe2011-08-23 04:27:15 +0000113 bool operator==(const RetEffect &Other) const {
114 return K == Other.K && O == Other.O;
115 }
116
Ted Kremenek78a35a32009-05-12 20:06:54 +0000117 static RetEffect MakeOwnedWhenTrackedReceiver() {
118 return RetEffect(OwnedWhenTrackedReceiver, ObjC);
119 }
Mike Stump1eb44332009-09-09 15:08:12 +0000120
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000121 static RetEffect MakeOwned(ObjKind o, bool isAllocated = false) {
122 return RetEffect(isAllocated ? OwnedAllocatedSymbol : OwnedSymbol, o);
Mike Stump1eb44332009-09-09 15:08:12 +0000123 }
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000124 static RetEffect MakeNotOwned(ObjKind o) {
125 return RetEffect(NotOwnedSymbol, o);
Ted Kremeneke798e7c2009-04-27 19:14:45 +0000126 }
127 static RetEffect MakeGCNotOwned() {
128 return RetEffect(GCNotOwnedSymbol, ObjC);
129 }
John McCallf85e1932011-06-15 23:02:42 +0000130 static RetEffect MakeARCNotOwned() {
131 return RetEffect(ARCNotOwnedSymbol, ObjC);
132 }
Ted Kremenek553cf182008-06-25 21:21:56 +0000133 static RetEffect MakeNoRet() {
134 return RetEffect(NoRet);
Ted Kremeneka7344702008-06-23 18:02:52 +0000135 }
Jordy Roseef945882012-03-18 01:26:10 +0000136
137 void Profile(llvm::FoldingSetNodeID& ID) const {
138 ID.AddInteger((unsigned) K);
139 ID.AddInteger((unsigned) O);
140 }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000141};
Mike Stump1eb44332009-09-09 15:08:12 +0000142
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000143//===----------------------------------------------------------------------===//
144// Reference-counting logic (typestate + counts).
145//===----------------------------------------------------------------------===//
Mike Stump1eb44332009-09-09 15:08:12 +0000146
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000147class RefVal {
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000148public:
149 enum Kind {
150 Owned = 0, // Owning reference.
151 NotOwned, // Reference is not owned by still valid (not freed).
152 Released, // Object has been released.
153 ReturnedOwned, // Returned object passes ownership to caller.
154 ReturnedNotOwned, // Return object does not pass ownership to caller.
155 ERROR_START,
156 ErrorDeallocNotOwned, // -dealloc called on non-owned object.
157 ErrorDeallocGC, // Calling -dealloc with GC enabled.
158 ErrorUseAfterRelease, // Object used after released.
159 ErrorReleaseNotOwned, // Release of an object that was not owned.
160 ERROR_LEAK_START,
161 ErrorLeak, // A memory leak due to excessive reference counts.
162 ErrorLeakReturned, // A memory leak due to the returning method not having
163 // the correct naming conventions.
164 ErrorGCLeakReturned,
165 ErrorOverAutorelease,
166 ErrorReturnedNotOwned
167 };
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000168
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000169private:
170 Kind kind;
171 RetEffect::ObjKind okind;
172 unsigned Cnt;
173 unsigned ACnt;
174 QualType T;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000175
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000176 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, unsigned acnt, QualType t)
177 : kind(k), okind(o), Cnt(cnt), ACnt(acnt), T(t) {}
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000178
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000179public:
180 Kind getKind() const { return kind; }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000181
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000182 RetEffect::ObjKind getObjKind() const { return okind; }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000183
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000184 unsigned getCount() const { return Cnt; }
185 unsigned getAutoreleaseCount() const { return ACnt; }
186 unsigned getCombinedCounts() const { return Cnt + ACnt; }
187 void clearCounts() { Cnt = 0; ACnt = 0; }
188 void setCount(unsigned i) { Cnt = i; }
189 void setAutoreleaseCount(unsigned i) { ACnt = i; }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000190
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000191 QualType getType() const { return T; }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000192
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000193 bool isOwned() const {
194 return getKind() == Owned;
195 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000196
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000197 bool isNotOwned() const {
198 return getKind() == NotOwned;
199 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000200
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000201 bool isReturnedOwned() const {
202 return getKind() == ReturnedOwned;
203 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000204
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000205 bool isReturnedNotOwned() const {
206 return getKind() == ReturnedNotOwned;
207 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000208
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000209 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
210 unsigned Count = 1) {
211 return RefVal(Owned, o, Count, 0, t);
212 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000213
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000214 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
215 unsigned Count = 0) {
216 return RefVal(NotOwned, o, Count, 0, t);
217 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000218
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000219 // Comparison, profiling, and pretty-printing.
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000220
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000221 bool operator==(const RefVal& X) const {
222 return kind == X.kind && Cnt == X.Cnt && T == X.T && ACnt == X.ACnt;
223 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000224
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000225 RefVal operator-(size_t i) const {
226 return RefVal(getKind(), getObjKind(), getCount() - i,
227 getAutoreleaseCount(), getType());
228 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000229
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000230 RefVal operator+(size_t i) const {
231 return RefVal(getKind(), getObjKind(), getCount() + i,
232 getAutoreleaseCount(), getType());
233 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000234
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000235 RefVal operator^(Kind k) const {
236 return RefVal(k, getObjKind(), getCount(), getAutoreleaseCount(),
237 getType());
238 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000239
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000240 RefVal autorelease() const {
241 return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount()+1,
242 getType());
243 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000244
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000245 void Profile(llvm::FoldingSetNodeID& ID) const {
246 ID.AddInteger((unsigned) kind);
247 ID.AddInteger(Cnt);
248 ID.AddInteger(ACnt);
249 ID.Add(T);
250 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000251
Ted Kremenek9c378f72011-08-12 23:37:29 +0000252 void print(raw_ostream &Out) const;
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000253};
254
Ted Kremenek9c378f72011-08-12 23:37:29 +0000255void RefVal::print(raw_ostream &Out) const {
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000256 if (!T.isNull())
Jordy Rosedbd658e2011-08-28 19:11:56 +0000257 Out << "Tracked " << T.getAsString() << '/';
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000258
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000259 switch (getKind()) {
Jordy Rose910c4052011-09-02 06:44:22 +0000260 default: llvm_unreachable("Invalid RefVal kind");
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000261 case Owned: {
262 Out << "Owned";
263 unsigned cnt = getCount();
264 if (cnt) Out << " (+ " << cnt << ")";
265 break;
266 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000267
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000268 case NotOwned: {
269 Out << "NotOwned";
270 unsigned cnt = getCount();
271 if (cnt) Out << " (+ " << cnt << ")";
272 break;
273 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000274
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000275 case ReturnedOwned: {
276 Out << "ReturnedOwned";
277 unsigned cnt = getCount();
278 if (cnt) Out << " (+ " << cnt << ")";
279 break;
280 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000281
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000282 case ReturnedNotOwned: {
283 Out << "ReturnedNotOwned";
284 unsigned cnt = getCount();
285 if (cnt) Out << " (+ " << cnt << ")";
286 break;
287 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000288
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000289 case Released:
290 Out << "Released";
291 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000292
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000293 case ErrorDeallocGC:
294 Out << "-dealloc (GC)";
295 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000296
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000297 case ErrorDeallocNotOwned:
298 Out << "-dealloc (not-owned)";
299 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000300
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000301 case ErrorLeak:
302 Out << "Leaked";
303 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000304
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000305 case ErrorLeakReturned:
306 Out << "Leaked (Bad naming)";
307 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000308
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000309 case ErrorGCLeakReturned:
310 Out << "Leaked (GC-ed at return)";
311 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000312
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000313 case ErrorUseAfterRelease:
314 Out << "Use-After-Release [ERROR]";
315 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000316
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000317 case ErrorReleaseNotOwned:
318 Out << "Release of Not-Owned [ERROR]";
319 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000320
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000321 case RefVal::ErrorOverAutorelease:
322 Out << "Over autoreleased";
323 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000324
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000325 case RefVal::ErrorReturnedNotOwned:
326 Out << "Non-owned object returned instead of owned";
327 break;
328 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000329
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000330 if (ACnt) {
331 Out << " [ARC +" << ACnt << ']';
332 }
333}
334} //end anonymous namespace
335
336//===----------------------------------------------------------------------===//
337// RefBindings - State used to track object reference counts.
338//===----------------------------------------------------------------------===//
339
340typedef llvm::ImmutableMap<SymbolRef, RefVal> RefBindings;
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000341
342namespace clang {
Ted Kremenek9ef65372010-12-23 07:20:52 +0000343namespace ento {
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000344template<>
345struct ProgramStateTrait<RefBindings>
346 : public ProgramStatePartialTrait<RefBindings> {
347 static void *GDMIndex() {
348 static int RefBIndex = 0;
349 return &RefBIndex;
350 }
351};
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000352}
Argyrios Kyrtzidis5a4f98f2010-12-22 18:53:20 +0000353}
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000354
355//===----------------------------------------------------------------------===//
Jordy Rose910c4052011-09-02 06:44:22 +0000356// Function/Method behavior summaries.
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000357//===----------------------------------------------------------------------===//
358
359namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000360class RetainSummary {
Jordy Roseef945882012-03-18 01:26:10 +0000361 /// Args - a map of (index, ArgEffect) pairs, where index
Ted Kremenek1bffd742008-05-06 15:44:25 +0000362 /// specifies the argument (starting from 0). This can be sparsely
363 /// populated; arguments with no entry in Args use 'DefaultArgEffect'.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000364 ArgEffects Args;
Mike Stump1eb44332009-09-09 15:08:12 +0000365
Ted Kremenek1bffd742008-05-06 15:44:25 +0000366 /// DefaultArgEffect - The default ArgEffect to apply to arguments that
367 /// do not have an entry in Args.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000368 ArgEffect DefaultArgEffect;
Mike Stump1eb44332009-09-09 15:08:12 +0000369
Ted Kremenek553cf182008-06-25 21:21:56 +0000370 /// Receiver - If this summary applies to an Objective-C message expression,
371 /// this is the effect applied to the state of the receiver.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000372 ArgEffect Receiver;
Mike Stump1eb44332009-09-09 15:08:12 +0000373
Ted Kremenek553cf182008-06-25 21:21:56 +0000374 /// Ret - The effect on the return value. Used to indicate if the
Jordy Rose76c506f2011-08-21 21:58:18 +0000375 /// function/method call returns a new tracked symbol.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000376 RetEffect Ret;
Mike Stump1eb44332009-09-09 15:08:12 +0000377
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000378public:
Ted Kremenekb77449c2009-05-03 05:20:50 +0000379 RetainSummary(ArgEffects A, RetEffect R, ArgEffect defaultEff,
Jordy Rosee62e87b2011-08-20 20:55:40 +0000380 ArgEffect ReceiverEff)
381 : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000382
Ted Kremenek553cf182008-06-25 21:21:56 +0000383 /// getArg - Return the argument effect on the argument specified by
384 /// idx (starting from 0).
Ted Kremenek1ac08d62008-03-11 17:48:22 +0000385 ArgEffect getArg(unsigned idx) const {
Ted Kremenekb77449c2009-05-03 05:20:50 +0000386 if (const ArgEffect *AE = Args.lookup(idx))
387 return *AE;
Mike Stump1eb44332009-09-09 15:08:12 +0000388
Ted Kremenek1bffd742008-05-06 15:44:25 +0000389 return DefaultArgEffect;
Ted Kremenek1ac08d62008-03-11 17:48:22 +0000390 }
Ted Kremenek11fe1752011-01-27 18:43:03 +0000391
392 void addArg(ArgEffects::Factory &af, unsigned idx, ArgEffect e) {
393 Args = af.add(Args, idx, e);
394 }
Mike Stump1eb44332009-09-09 15:08:12 +0000395
Ted Kremenek885c27b2009-05-04 05:31:22 +0000396 /// setDefaultArgEffect - Set the default argument effect.
397 void setDefaultArgEffect(ArgEffect E) {
398 DefaultArgEffect = E;
399 }
Mike Stump1eb44332009-09-09 15:08:12 +0000400
Ted Kremenek553cf182008-06-25 21:21:56 +0000401 /// getRetEffect - Returns the effect on the return value of the call.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000402 RetEffect getRetEffect() const { return Ret; }
Mike Stump1eb44332009-09-09 15:08:12 +0000403
Ted Kremenek885c27b2009-05-04 05:31:22 +0000404 /// setRetEffect - Set the effect of the return value of the call.
405 void setRetEffect(RetEffect E) { Ret = E; }
Mike Stump1eb44332009-09-09 15:08:12 +0000406
Ted Kremenek12b94342011-01-27 06:54:14 +0000407
408 /// Sets the effect on the receiver of the message.
409 void setReceiverEffect(ArgEffect e) { Receiver = e; }
410
Ted Kremenek553cf182008-06-25 21:21:56 +0000411 /// getReceiverEffect - Returns the effect on the receiver of the call.
412 /// This is only meaningful if the summary applies to an ObjCMessageExpr*.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000413 ArgEffect getReceiverEffect() const { return Receiver; }
Jordy Rose4df54fe2011-08-23 04:27:15 +0000414
415 /// Test if two retain summaries are identical. Note that merely equivalent
416 /// summaries are not necessarily identical (for example, if an explicit
417 /// argument effect matches the default effect).
418 bool operator==(const RetainSummary &Other) const {
419 return Args == Other.Args && DefaultArgEffect == Other.DefaultArgEffect &&
420 Receiver == Other.Receiver && Ret == Other.Ret;
421 }
Jordy Roseef945882012-03-18 01:26:10 +0000422
423 /// Profile this summary for inclusion in a FoldingSet.
424 void Profile(llvm::FoldingSetNodeID& ID) const {
425 ID.Add(Args);
426 ID.Add(DefaultArgEffect);
427 ID.Add(Receiver);
428 ID.Add(Ret);
429 }
430
431 /// A retain summary is simple if it has no ArgEffects other than the default.
432 bool isSimple() const {
433 return Args.isEmpty();
434 }
Jordan Rose4531b7d2012-07-02 19:27:43 +0000435
436private:
437 ArgEffects getArgEffects() const { return Args; }
438 ArgEffect getDefaultArgEffect() const { return DefaultArgEffect; }
439
440 friend class RetainSummaryManager;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000441};
Ted Kremenek4f22a782008-06-23 23:30:29 +0000442} // end anonymous namespace
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000443
Ted Kremenek553cf182008-06-25 21:21:56 +0000444//===----------------------------------------------------------------------===//
445// Data structures for constructing summaries.
446//===----------------------------------------------------------------------===//
Ted Kremenek53301ba2008-06-24 03:49:48 +0000447
Ted Kremenek553cf182008-06-25 21:21:56 +0000448namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000449class ObjCSummaryKey {
Ted Kremenek553cf182008-06-25 21:21:56 +0000450 IdentifierInfo* II;
451 Selector S;
Mike Stump1eb44332009-09-09 15:08:12 +0000452public:
Ted Kremenek553cf182008-06-25 21:21:56 +0000453 ObjCSummaryKey(IdentifierInfo* ii, Selector s)
454 : II(ii), S(s) {}
455
Ted Kremenek9c378f72011-08-12 23:37:29 +0000456 ObjCSummaryKey(const ObjCInterfaceDecl *d, Selector s)
Ted Kremenek553cf182008-06-25 21:21:56 +0000457 : II(d ? d->getIdentifier() : 0), S(s) {}
Ted Kremenek70b6a832009-05-13 18:16:01 +0000458
Ted Kremenek553cf182008-06-25 21:21:56 +0000459 ObjCSummaryKey(Selector s)
460 : II(0), S(s) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000461
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000462 IdentifierInfo *getIdentifier() const { return II; }
Ted Kremenek553cf182008-06-25 21:21:56 +0000463 Selector getSelector() const { return S; }
464};
Ted Kremenek4f22a782008-06-23 23:30:29 +0000465}
466
467namespace llvm {
Ted Kremenek553cf182008-06-25 21:21:56 +0000468template <> struct DenseMapInfo<ObjCSummaryKey> {
469 static inline ObjCSummaryKey getEmptyKey() {
470 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
471 DenseMapInfo<Selector>::getEmptyKey());
472 }
Mike Stump1eb44332009-09-09 15:08:12 +0000473
Ted Kremenek553cf182008-06-25 21:21:56 +0000474 static inline ObjCSummaryKey getTombstoneKey() {
475 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
Mike Stump1eb44332009-09-09 15:08:12 +0000476 DenseMapInfo<Selector>::getTombstoneKey());
Ted Kremenek553cf182008-06-25 21:21:56 +0000477 }
Mike Stump1eb44332009-09-09 15:08:12 +0000478
Ted Kremenek553cf182008-06-25 21:21:56 +0000479 static unsigned getHashValue(const ObjCSummaryKey &V) {
Benjamin Kramer28b23072012-05-27 13:28:44 +0000480 typedef std::pair<IdentifierInfo*, Selector> PairTy;
481 return DenseMapInfo<PairTy>::getHashValue(PairTy(V.getIdentifier(),
482 V.getSelector()));
Ted Kremenek553cf182008-06-25 21:21:56 +0000483 }
Mike Stump1eb44332009-09-09 15:08:12 +0000484
Ted Kremenek553cf182008-06-25 21:21:56 +0000485 static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
Benjamin Kramer28b23072012-05-27 13:28:44 +0000486 return LHS.getIdentifier() == RHS.getIdentifier() &&
487 LHS.getSelector() == RHS.getSelector();
Ted Kremenek553cf182008-06-25 21:21:56 +0000488 }
Mike Stump1eb44332009-09-09 15:08:12 +0000489
Ted Kremenek553cf182008-06-25 21:21:56 +0000490};
Chris Lattner06159e82009-12-15 07:26:51 +0000491template <>
492struct isPodLike<ObjCSummaryKey> { static const bool value = true; };
Ted Kremenek4f22a782008-06-23 23:30:29 +0000493} // end llvm namespace
Mike Stump1eb44332009-09-09 15:08:12 +0000494
Ted Kremenek4f22a782008-06-23 23:30:29 +0000495namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000496class ObjCSummaryCache {
Ted Kremenek93edbc52011-10-05 23:54:29 +0000497 typedef llvm::DenseMap<ObjCSummaryKey, const RetainSummary *> MapTy;
Ted Kremenek553cf182008-06-25 21:21:56 +0000498 MapTy M;
499public:
500 ObjCSummaryCache() {}
Mike Stump1eb44332009-09-09 15:08:12 +0000501
Ted Kremenek93edbc52011-10-05 23:54:29 +0000502 const RetainSummary * find(const ObjCInterfaceDecl *D, Selector S) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000503 // Do a lookup with the (D,S) pair. If we find a match return
504 // the iterator.
505 ObjCSummaryKey K(D, S);
506 MapTy::iterator I = M.find(K);
Mike Stump1eb44332009-09-09 15:08:12 +0000507
Jordan Rose4531b7d2012-07-02 19:27:43 +0000508 if (I != M.end())
Ted Kremenek614cc542009-07-21 23:27:57 +0000509 return I->second;
Jordan Rose4531b7d2012-07-02 19:27:43 +0000510 if (!D)
511 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +0000512
Ted Kremenek553cf182008-06-25 21:21:56 +0000513 // Walk the super chain. If we find a hit with a parent, we'll end
514 // up returning that summary. We actually allow that key (null,S), as
515 // we cache summaries for the null ObjCInterfaceDecl* to allow us to
516 // generate initial summaries without having to worry about NSObject
517 // being declared.
518 // FIXME: We may change this at some point.
Ted Kremenek9c378f72011-08-12 23:37:29 +0000519 for (ObjCInterfaceDecl *C=D->getSuperClass() ;; C=C->getSuperClass()) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000520 if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
521 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000522
Ted Kremenek553cf182008-06-25 21:21:56 +0000523 if (!C)
Ted Kremenek614cc542009-07-21 23:27:57 +0000524 return NULL;
Ted Kremenek553cf182008-06-25 21:21:56 +0000525 }
Mike Stump1eb44332009-09-09 15:08:12 +0000526
527 // Cache the summary with original key to make the next lookup faster
Ted Kremenek553cf182008-06-25 21:21:56 +0000528 // and return the iterator.
Ted Kremenek93edbc52011-10-05 23:54:29 +0000529 const RetainSummary *Summ = I->second;
Ted Kremenek614cc542009-07-21 23:27:57 +0000530 M[K] = Summ;
531 return Summ;
Ted Kremenek553cf182008-06-25 21:21:56 +0000532 }
Mike Stump1eb44332009-09-09 15:08:12 +0000533
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000534 const RetainSummary *find(IdentifierInfo* II, Selector S) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000535 // FIXME: Class method lookup. Right now we dont' have a good way
536 // of going between IdentifierInfo* and the class hierarchy.
Ted Kremenek614cc542009-07-21 23:27:57 +0000537 MapTy::iterator I = M.find(ObjCSummaryKey(II, S));
Mike Stump1eb44332009-09-09 15:08:12 +0000538
Ted Kremenek614cc542009-07-21 23:27:57 +0000539 if (I == M.end())
540 I = M.find(ObjCSummaryKey(S));
Mike Stump1eb44332009-09-09 15:08:12 +0000541
Ted Kremenek614cc542009-07-21 23:27:57 +0000542 return I == M.end() ? NULL : I->second;
Ted Kremenek553cf182008-06-25 21:21:56 +0000543 }
Mike Stump1eb44332009-09-09 15:08:12 +0000544
Ted Kremenek93edbc52011-10-05 23:54:29 +0000545 const RetainSummary *& operator[](ObjCSummaryKey K) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000546 return M[K];
547 }
Mike Stump1eb44332009-09-09 15:08:12 +0000548
Ted Kremenek93edbc52011-10-05 23:54:29 +0000549 const RetainSummary *& operator[](Selector S) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000550 return M[ ObjCSummaryKey(S) ];
551 }
Mike Stump1eb44332009-09-09 15:08:12 +0000552};
Ted Kremenek553cf182008-06-25 21:21:56 +0000553} // end anonymous namespace
554
555//===----------------------------------------------------------------------===//
556// Data structures for managing collections of summaries.
557//===----------------------------------------------------------------------===//
558
559namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000560class RetainSummaryManager {
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000561
562 //==-----------------------------------------------------------------==//
563 // Typedefs.
564 //==-----------------------------------------------------------------==//
Mike Stump1eb44332009-09-09 15:08:12 +0000565
Ted Kremenek93edbc52011-10-05 23:54:29 +0000566 typedef llvm::DenseMap<const FunctionDecl*, const RetainSummary *>
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000567 FuncSummariesTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000568
Ted Kremenek4f22a782008-06-23 23:30:29 +0000569 typedef ObjCSummaryCache ObjCMethodSummariesTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000570
Jordy Roseef945882012-03-18 01:26:10 +0000571 typedef llvm::FoldingSetNodeWrapper<RetainSummary> CachedSummaryNode;
572
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000573 //==-----------------------------------------------------------------==//
574 // Data.
575 //==-----------------------------------------------------------------==//
Mike Stump1eb44332009-09-09 15:08:12 +0000576
Ted Kremenek553cf182008-06-25 21:21:56 +0000577 /// Ctx - The ASTContext object for the analyzed ASTs.
Ted Kremenek9c378f72011-08-12 23:37:29 +0000578 ASTContext &Ctx;
Ted Kremenek179064e2008-07-01 17:21:27 +0000579
Ted Kremenek553cf182008-06-25 21:21:56 +0000580 /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
Ted Kremenek377e2302008-04-29 05:33:51 +0000581 const bool GCEnabled;
Mike Stump1eb44332009-09-09 15:08:12 +0000582
John McCallf85e1932011-06-15 23:02:42 +0000583 /// Records whether or not the analyzed code runs in ARC mode.
584 const bool ARCEnabled;
585
Ted Kremenek553cf182008-06-25 21:21:56 +0000586 /// FuncSummaries - A map from FunctionDecls to summaries.
Mike Stump1eb44332009-09-09 15:08:12 +0000587 FuncSummariesTy FuncSummaries;
588
Ted Kremenek553cf182008-06-25 21:21:56 +0000589 /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
590 /// to summaries.
Ted Kremenek1f180c32008-06-23 22:21:20 +0000591 ObjCMethodSummariesTy ObjCClassMethodSummaries;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000592
Ted Kremenek553cf182008-06-25 21:21:56 +0000593 /// ObjCMethodSummaries - A map from selectors to summaries.
Ted Kremenek1f180c32008-06-23 22:21:20 +0000594 ObjCMethodSummariesTy ObjCMethodSummaries;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000595
Ted Kremenek553cf182008-06-25 21:21:56 +0000596 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
597 /// and all other data used by the checker.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000598 llvm::BumpPtrAllocator BPAlloc;
Mike Stump1eb44332009-09-09 15:08:12 +0000599
Ted Kremenekb77449c2009-05-03 05:20:50 +0000600 /// AF - A factory for ArgEffects objects.
Mike Stump1eb44332009-09-09 15:08:12 +0000601 ArgEffects::Factory AF;
602
Ted Kremenek553cf182008-06-25 21:21:56 +0000603 /// ScratchArgs - A holding buffer for construct ArgEffects.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000604 ArgEffects ScratchArgs;
Mike Stump1eb44332009-09-09 15:08:12 +0000605
Ted Kremenekec315332009-05-07 23:40:42 +0000606 /// ObjCAllocRetE - Default return effect for methods returning Objective-C
607 /// objects.
608 RetEffect ObjCAllocRetE;
Ted Kremenek547d4952009-06-05 23:18:01 +0000609
Mike Stump1eb44332009-09-09 15:08:12 +0000610 /// ObjCInitRetE - Default return effect for init methods returning
Ted Kremenekac02f202009-08-20 05:13:36 +0000611 /// Objective-C objects.
Ted Kremenek547d4952009-06-05 23:18:01 +0000612 RetEffect ObjCInitRetE;
Mike Stump1eb44332009-09-09 15:08:12 +0000613
Jordy Roseef945882012-03-18 01:26:10 +0000614 /// SimpleSummaries - Used for uniquing summaries that don't have special
615 /// effects.
616 llvm::FoldingSet<CachedSummaryNode> SimpleSummaries;
Mike Stump1eb44332009-09-09 15:08:12 +0000617
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000618 //==-----------------------------------------------------------------==//
619 // Methods.
620 //==-----------------------------------------------------------------==//
Mike Stump1eb44332009-09-09 15:08:12 +0000621
Ted Kremenek553cf182008-06-25 21:21:56 +0000622 /// getArgEffects - Returns a persistent ArgEffects object based on the
623 /// data in ScratchArgs.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000624 ArgEffects getArgEffects();
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000625
Mike Stump1eb44332009-09-09 15:08:12 +0000626 enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
Ted Kremenek93edbc52011-10-05 23:54:29 +0000627
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000628 const RetainSummary *getUnarySummary(const FunctionType* FT,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000629 UnaryFuncKind func);
Mike Stump1eb44332009-09-09 15:08:12 +0000630
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000631 const RetainSummary *getCFSummaryCreateRule(const FunctionDecl *FD);
632 const RetainSummary *getCFSummaryGetRule(const FunctionDecl *FD);
633 const RetainSummary *getCFCreateGetRuleSummary(const FunctionDecl *FD);
Mike Stump1eb44332009-09-09 15:08:12 +0000634
Jordy Roseef945882012-03-18 01:26:10 +0000635 const RetainSummary *getPersistentSummary(const RetainSummary &OldSumm);
Ted Kremenek706522f2008-10-29 04:07:07 +0000636
Jordy Roseef945882012-03-18 01:26:10 +0000637 const RetainSummary *getPersistentSummary(RetEffect RetEff,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000638 ArgEffect ReceiverEff = DoNothing,
639 ArgEffect DefaultEff = MayEscape) {
Jordy Roseef945882012-03-18 01:26:10 +0000640 RetainSummary Summ(getArgEffects(), RetEff, DefaultEff, ReceiverEff);
641 return getPersistentSummary(Summ);
642 }
643
Ted Kremenekc91fdf62012-05-08 00:12:09 +0000644 const RetainSummary *getDoNothingSummary() {
645 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
646 }
647
Jordy Roseef945882012-03-18 01:26:10 +0000648 const RetainSummary *getDefaultSummary() {
649 return getPersistentSummary(RetEffect::MakeNoRet(),
650 DoNothing, MayEscape);
Ted Kremenek9c32d082008-05-06 00:30:21 +0000651 }
Mike Stump1eb44332009-09-09 15:08:12 +0000652
Ted Kremenek93edbc52011-10-05 23:54:29 +0000653 const RetainSummary *getPersistentStopSummary() {
Jordy Roseef945882012-03-18 01:26:10 +0000654 return getPersistentSummary(RetEffect::MakeNoRet(),
655 StopTracking, StopTracking);
Mike Stump1eb44332009-09-09 15:08:12 +0000656 }
Ted Kremenekb3095252008-05-06 04:20:12 +0000657
Ted Kremenek1f180c32008-06-23 22:21:20 +0000658 void InitializeClassMethodSummaries();
659 void InitializeMethodSummaries();
Ted Kremenek896cd9d2008-10-23 01:56:15 +0000660private:
Ted Kremenek93edbc52011-10-05 23:54:29 +0000661 void addNSObjectClsMethSummary(Selector S, const RetainSummary *Summ) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000662 ObjCClassMethodSummaries[S] = Summ;
663 }
Mike Stump1eb44332009-09-09 15:08:12 +0000664
Ted Kremenek93edbc52011-10-05 23:54:29 +0000665 void addNSObjectMethSummary(Selector S, const RetainSummary *Summ) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000666 ObjCMethodSummaries[S] = Summ;
667 }
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +0000668
Ted Kremeneka9797122012-02-18 21:37:48 +0000669 void addClassMethSummary(const char* Cls, const char* name,
670 const RetainSummary *Summ, bool isNullary = true) {
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +0000671 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
Ted Kremeneka9797122012-02-18 21:37:48 +0000672 Selector S = isNullary ? GetNullarySelector(name, Ctx)
673 : GetUnarySelector(name, Ctx);
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +0000674 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
675 }
Mike Stump1eb44332009-09-09 15:08:12 +0000676
Ted Kremenek6c4becb2009-02-25 02:54:57 +0000677 void addInstMethSummary(const char* Cls, const char* nullaryName,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000678 const RetainSummary *Summ) {
Ted Kremenek6c4becb2009-02-25 02:54:57 +0000679 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
680 Selector S = GetNullarySelector(nullaryName, Ctx);
681 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
682 }
Mike Stump1eb44332009-09-09 15:08:12 +0000683
Ted Kremenekde4d5332009-04-24 17:50:11 +0000684 Selector generateSelector(va_list argp) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000685 SmallVector<IdentifierInfo*, 10> II;
Ted Kremenekde4d5332009-04-24 17:50:11 +0000686
Ted Kremenek9e476de2008-08-12 18:30:56 +0000687 while (const char* s = va_arg(argp, const char*))
688 II.push_back(&Ctx.Idents.get(s));
Ted Kremenekde4d5332009-04-24 17:50:11 +0000689
Mike Stump1eb44332009-09-09 15:08:12 +0000690 return Ctx.Selectors.getSelector(II.size(), &II[0]);
Ted Kremenekde4d5332009-04-24 17:50:11 +0000691 }
Mike Stump1eb44332009-09-09 15:08:12 +0000692
Ted Kremenekde4d5332009-04-24 17:50:11 +0000693 void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy& Summaries,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000694 const RetainSummary * Summ, va_list argp) {
Ted Kremenekde4d5332009-04-24 17:50:11 +0000695 Selector S = generateSelector(argp);
696 Summaries[ObjCSummaryKey(ClsII, S)] = Summ;
Ted Kremenek70a733e2008-07-18 17:24:20 +0000697 }
Mike Stump1eb44332009-09-09 15:08:12 +0000698
Ted Kremenek93edbc52011-10-05 23:54:29 +0000699 void addInstMethSummary(const char* Cls, const RetainSummary * Summ, ...) {
Ted Kremenekaf9dc272008-08-12 18:48:50 +0000700 va_list argp;
701 va_start(argp, Summ);
Ted Kremenekde4d5332009-04-24 17:50:11 +0000702 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Mike Stump1eb44332009-09-09 15:08:12 +0000703 va_end(argp);
Ted Kremenekaf9dc272008-08-12 18:48:50 +0000704 }
Mike Stump1eb44332009-09-09 15:08:12 +0000705
Ted Kremenek93edbc52011-10-05 23:54:29 +0000706 void addClsMethSummary(const char* Cls, const RetainSummary * Summ, ...) {
Ted Kremenekde4d5332009-04-24 17:50:11 +0000707 va_list argp;
708 va_start(argp, Summ);
709 addMethodSummary(&Ctx.Idents.get(Cls),ObjCClassMethodSummaries, Summ, argp);
710 va_end(argp);
711 }
Mike Stump1eb44332009-09-09 15:08:12 +0000712
Ted Kremenek93edbc52011-10-05 23:54:29 +0000713 void addClsMethSummary(IdentifierInfo *II, const RetainSummary * Summ, ...) {
Ted Kremenekde4d5332009-04-24 17:50:11 +0000714 va_list argp;
715 va_start(argp, Summ);
716 addMethodSummary(II, ObjCClassMethodSummaries, Summ, argp);
717 va_end(argp);
718 }
719
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000720public:
Mike Stump1eb44332009-09-09 15:08:12 +0000721
Ted Kremenek9c378f72011-08-12 23:37:29 +0000722 RetainSummaryManager(ASTContext &ctx, bool gcenabled, bool usesARC)
Ted Kremenek179064e2008-07-01 17:21:27 +0000723 : Ctx(ctx),
John McCallf85e1932011-06-15 23:02:42 +0000724 GCEnabled(gcenabled),
725 ARCEnabled(usesARC),
726 AF(BPAlloc), ScratchArgs(AF.getEmptyMap()),
727 ObjCAllocRetE(gcenabled
728 ? RetEffect::MakeGCNotOwned()
729 : (usesARC ? RetEffect::MakeARCNotOwned()
730 : RetEffect::MakeOwned(RetEffect::ObjC, true))),
731 ObjCInitRetE(gcenabled
732 ? RetEffect::MakeGCNotOwned()
733 : (usesARC ? RetEffect::MakeARCNotOwned()
Jordy Roseef945882012-03-18 01:26:10 +0000734 : RetEffect::MakeOwnedWhenTrackedReceiver())) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000735 InitializeClassMethodSummaries();
736 InitializeMethodSummaries();
737 }
Mike Stump1eb44332009-09-09 15:08:12 +0000738
Jordan Rose4531b7d2012-07-02 19:27:43 +0000739 const RetainSummary *getSummary(const CallEvent &Call,
740 ProgramStateRef State = 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000741
Jordan Rose4531b7d2012-07-02 19:27:43 +0000742 const RetainSummary *getFunctionSummary(const FunctionDecl *FD);
743
744 const RetainSummary *getMethodSummary(Selector S, const ObjCInterfaceDecl *ID,
Jordy Rosef3aae582012-03-17 21:13:07 +0000745 const ObjCMethodDecl *MD,
746 QualType RetTy,
747 ObjCMethodSummariesTy &CachedSummaries);
748
Jordan Rosecde8cdb2012-07-02 19:27:56 +0000749 const RetainSummary *getInstanceMethodSummary(const ObjCMethodCall &M,
Jordan Rose4531b7d2012-07-02 19:27:43 +0000750 ProgramStateRef State);
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000751
Jordan Rosecde8cdb2012-07-02 19:27:56 +0000752 const RetainSummary *getClassMethodSummary(const ObjCMethodCall &M) {
Jordan Rose4531b7d2012-07-02 19:27:43 +0000753 assert(!M.isInstanceMessage());
754 const ObjCInterfaceDecl *Class = M.getReceiverInterface();
Mike Stump1eb44332009-09-09 15:08:12 +0000755
Jordan Rose4531b7d2012-07-02 19:27:43 +0000756 return getMethodSummary(M.getSelector(), Class, M.getDecl(),
757 M.getResultType(), ObjCClassMethodSummaries);
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +0000758 }
Ted Kremenek552333c2009-04-29 17:17:48 +0000759
760 /// getMethodSummary - This version of getMethodSummary is used to query
761 /// the summary for the current method being analyzed.
Ted Kremenek93edbc52011-10-05 23:54:29 +0000762 const RetainSummary *getMethodSummary(const ObjCMethodDecl *MD) {
Ted Kremeneka8833552009-04-29 23:03:22 +0000763 const ObjCInterfaceDecl *ID = MD->getClassInterface();
Ted Kremenek70a65762009-04-30 05:41:14 +0000764 Selector S = MD->getSelector();
Ted Kremenek552333c2009-04-29 17:17:48 +0000765 QualType ResultTy = MD->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +0000766
Jordy Rosef3aae582012-03-17 21:13:07 +0000767 ObjCMethodSummariesTy *CachedSummaries;
Ted Kremenek552333c2009-04-29 17:17:48 +0000768 if (MD->isInstanceMethod())
Jordy Rosef3aae582012-03-17 21:13:07 +0000769 CachedSummaries = &ObjCMethodSummaries;
Ted Kremenek552333c2009-04-29 17:17:48 +0000770 else
Jordy Rosef3aae582012-03-17 21:13:07 +0000771 CachedSummaries = &ObjCClassMethodSummaries;
772
Jordan Rose4531b7d2012-07-02 19:27:43 +0000773 return getMethodSummary(S, ID, MD, ResultTy, *CachedSummaries);
Ted Kremenek552333c2009-04-29 17:17:48 +0000774 }
Mike Stump1eb44332009-09-09 15:08:12 +0000775
Jordy Rosef3aae582012-03-17 21:13:07 +0000776 const RetainSummary *getStandardMethodSummary(const ObjCMethodDecl *MD,
Jordan Rose4531b7d2012-07-02 19:27:43 +0000777 Selector S, QualType RetTy);
Ted Kremeneka8833552009-04-29 23:03:22 +0000778
Ted Kremenek93edbc52011-10-05 23:54:29 +0000779 void updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenek4dd8fb42009-05-09 02:58:13 +0000780 const ObjCMethodDecl *MD);
781
Ted Kremenek93edbc52011-10-05 23:54:29 +0000782 void updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenek4dd8fb42009-05-09 02:58:13 +0000783 const FunctionDecl *FD);
784
Jordan Rose4531b7d2012-07-02 19:27:43 +0000785 void updateSummaryForCall(const RetainSummary *&Summ,
786 const CallEvent &Call);
787
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000788 bool isGCEnabled() const { return GCEnabled; }
Mike Stump1eb44332009-09-09 15:08:12 +0000789
John McCallf85e1932011-06-15 23:02:42 +0000790 bool isARCEnabled() const { return ARCEnabled; }
791
792 bool isARCorGCEnabled() const { return GCEnabled || ARCEnabled; }
Jordan Rose4531b7d2012-07-02 19:27:43 +0000793
794 RetEffect getObjAllocRetEffect() const { return ObjCAllocRetE; }
795
796 friend class RetainSummaryTemplate;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000797};
Mike Stump1eb44332009-09-09 15:08:12 +0000798
Jordy Rose0fe62f82011-08-24 09:02:37 +0000799// Used to avoid allocating long-term (BPAlloc'd) memory for default retain
800// summaries. If a function or method looks like it has a default summary, but
801// it has annotations, the annotations are added to the stack-based template
802// and then copied into managed memory.
803class RetainSummaryTemplate {
804 RetainSummaryManager &Manager;
Ted Kremenek93edbc52011-10-05 23:54:29 +0000805 const RetainSummary *&RealSummary;
Jordy Rose0fe62f82011-08-24 09:02:37 +0000806 RetainSummary ScratchSummary;
807 bool Accessed;
808public:
Jordan Rose4531b7d2012-07-02 19:27:43 +0000809 RetainSummaryTemplate(const RetainSummary *&real, RetainSummaryManager &mgr)
810 : Manager(mgr), RealSummary(real), ScratchSummary(*real), Accessed(false) {}
Jordy Rose0fe62f82011-08-24 09:02:37 +0000811
812 ~RetainSummaryTemplate() {
Ted Kremenek93edbc52011-10-05 23:54:29 +0000813 if (Accessed)
Jordy Roseef945882012-03-18 01:26:10 +0000814 RealSummary = Manager.getPersistentSummary(ScratchSummary);
Jordy Rose0fe62f82011-08-24 09:02:37 +0000815 }
816
817 RetainSummary &operator*() {
818 Accessed = true;
Ted Kremenek93edbc52011-10-05 23:54:29 +0000819 return ScratchSummary;
Jordy Rose0fe62f82011-08-24 09:02:37 +0000820 }
821
822 RetainSummary *operator->() {
823 Accessed = true;
Ted Kremenek93edbc52011-10-05 23:54:29 +0000824 return &ScratchSummary;
Jordy Rose0fe62f82011-08-24 09:02:37 +0000825 }
826};
827
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000828} // end anonymous namespace
829
830//===----------------------------------------------------------------------===//
831// Implementation of checker data structures.
832//===----------------------------------------------------------------------===//
833
Ted Kremenekb77449c2009-05-03 05:20:50 +0000834ArgEffects RetainSummaryManager::getArgEffects() {
835 ArgEffects AE = ScratchArgs;
Ted Kremenek3baf6722010-11-24 00:54:37 +0000836 ScratchArgs = AF.getEmptyMap();
Ted Kremenekb77449c2009-05-03 05:20:50 +0000837 return AE;
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000838}
839
Ted Kremenek93edbc52011-10-05 23:54:29 +0000840const RetainSummary *
Jordy Roseef945882012-03-18 01:26:10 +0000841RetainSummaryManager::getPersistentSummary(const RetainSummary &OldSumm) {
842 // Unique "simple" summaries -- those without ArgEffects.
843 if (OldSumm.isSimple()) {
844 llvm::FoldingSetNodeID ID;
845 OldSumm.Profile(ID);
846
847 void *Pos;
848 CachedSummaryNode *N = SimpleSummaries.FindNodeOrInsertPos(ID, Pos);
849
850 if (!N) {
851 N = (CachedSummaryNode *) BPAlloc.Allocate<CachedSummaryNode>();
852 new (N) CachedSummaryNode(OldSumm);
853 SimpleSummaries.InsertNode(N, Pos);
854 }
855
856 return &N->getValue();
857 }
858
Ted Kremenek93edbc52011-10-05 23:54:29 +0000859 RetainSummary *Summ = (RetainSummary *) BPAlloc.Allocate<RetainSummary>();
Jordy Roseef945882012-03-18 01:26:10 +0000860 new (Summ) RetainSummary(OldSumm);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000861 return Summ;
862}
863
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000864//===----------------------------------------------------------------------===//
865// Summary creation for functions (largely uses of Core Foundation).
866//===----------------------------------------------------------------------===//
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000867
Ted Kremenek9c378f72011-08-12 23:37:29 +0000868static bool isRetain(const FunctionDecl *FD, StringRef FName) {
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000869 return FName.endswith("Retain");
Ted Kremenek12619382009-01-12 21:45:02 +0000870}
871
Ted Kremenek9c378f72011-08-12 23:37:29 +0000872static bool isRelease(const FunctionDecl *FD, StringRef FName) {
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000873 return FName.endswith("Release");
Ted Kremenek12619382009-01-12 21:45:02 +0000874}
875
Jordy Rose76c506f2011-08-21 21:58:18 +0000876static bool isMakeCollectable(const FunctionDecl *FD, StringRef FName) {
877 // FIXME: Remove FunctionDecl parameter.
878 // FIXME: Is it really okay if MakeCollectable isn't a suffix?
879 return FName.find("MakeCollectable") != StringRef::npos;
880}
881
Jordan Rose4531b7d2012-07-02 19:27:43 +0000882static ArgEffect getStopTrackingEquivalent(ArgEffect E) {
883 switch (E) {
884 case DoNothing:
885 case Autorelease:
886 case DecRefBridgedTransfered:
887 case IncRef:
888 case IncRefMsg:
889 case MakeCollectable:
890 case MayEscape:
891 case NewAutoreleasePool:
892 case StopTracking:
893 return StopTracking;
894 case DecRef:
895 case DecRefAndStopTracking:
896 return DecRefAndStopTracking;
897 case DecRefMsg:
898 case DecRefMsgAndStopTracking:
899 return DecRefMsgAndStopTracking;
900 case Dealloc:
901 return Dealloc;
902 }
903
904 llvm_unreachable("Unknown ArgEffect kind");
905}
906
907void RetainSummaryManager::updateSummaryForCall(const RetainSummary *&S,
908 const CallEvent &Call) {
909 if (Call.hasNonZeroCallbackArg()) {
910 ArgEffect RecEffect = getStopTrackingEquivalent(S->getReceiverEffect());
911 ArgEffect DefEffect = getStopTrackingEquivalent(S->getDefaultArgEffect());
912
913 ArgEffects CustomArgEffects = S->getArgEffects();
914 for (ArgEffects::iterator I = CustomArgEffects.begin(),
915 E = CustomArgEffects.end();
916 I != E; ++I) {
917 ArgEffect Translated = getStopTrackingEquivalent(I->second);
918 if (Translated != DefEffect)
919 ScratchArgs = AF.add(ScratchArgs, I->first, Translated);
920 }
921
922 RetEffect RE = RetEffect::MakeNoRet();
923
924 // Special cases where the callback argument CANNOT free the return value.
925 // This can generally only happen if we know that the callback will only be
926 // called when the return value is already being deallocated.
927 if (const FunctionCall *FC = dyn_cast<FunctionCall>(&Call)) {
928 IdentifierInfo *Name = FC->getDecl()->getIdentifier();
929
930 // This callback frees the associated buffer.
931 if (Name->isStr("CGBitmapContextCreateWithData"))
932 RE = S->getRetEffect();
933 }
934
935 S = getPersistentSummary(RE, RecEffect, DefEffect);
936 }
937}
938
Anna Zaks58822c42012-05-04 22:18:39 +0000939const RetainSummary *
Jordan Rose4531b7d2012-07-02 19:27:43 +0000940RetainSummaryManager::getSummary(const CallEvent &Call,
941 ProgramStateRef State) {
942 const RetainSummary *Summ;
943 switch (Call.getKind()) {
944 case CE_Function:
945 Summ = getFunctionSummary(cast<FunctionCall>(Call).getDecl());
946 break;
947 case CE_CXXMember:
Jordan Rosefdaa3382012-07-03 22:55:57 +0000948 case CE_CXXMemberOperator:
Jordan Rose4531b7d2012-07-02 19:27:43 +0000949 case CE_Block:
950 case CE_CXXConstructor:
Jordan Rose70cbf3c2012-07-02 22:21:47 +0000951 case CE_CXXAllocator:
Jordan Rose4531b7d2012-07-02 19:27:43 +0000952 // FIXME: These calls are currently unsupported.
953 return getPersistentStopSummary();
Jordan Rosecde8cdb2012-07-02 19:27:56 +0000954 case CE_ObjCMessage:
955 case CE_ObjCPropertyAccess: {
956 const ObjCMethodCall &Msg = cast<ObjCMethodCall>(Call);
Jordan Rose4531b7d2012-07-02 19:27:43 +0000957 if (Msg.isInstanceMessage())
958 Summ = getInstanceMethodSummary(Msg, State);
959 else
960 Summ = getClassMethodSummary(Msg);
961 break;
962 }
963 }
964
965 updateSummaryForCall(Summ, Call);
966
967 assert(Summ && "Unknown call type?");
968 return Summ;
969}
970
971const RetainSummary *
972RetainSummaryManager::getFunctionSummary(const FunctionDecl *FD) {
973 // If we don't know what function we're calling, use our default summary.
974 if (!FD)
975 return getDefaultSummary();
976
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000977 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000978 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000979 if (I != FuncSummaries.end())
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000980 return I->second;
981
Ted Kremeneke401a0c2009-05-04 15:34:07 +0000982 // No summary? Generate one.
Ted Kremenek93edbc52011-10-05 23:54:29 +0000983 const RetainSummary *S = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000984
Ted Kremenek37d785b2008-07-15 16:50:12 +0000985 do {
Ted Kremenek12619382009-01-12 21:45:02 +0000986 // We generate "stop" summaries for implicitly defined functions.
987 if (FD->isImplicit()) {
988 S = getPersistentStopSummary();
989 break;
Ted Kremenek37d785b2008-07-15 16:50:12 +0000990 }
Mike Stump1eb44332009-09-09 15:08:12 +0000991
John McCall183700f2009-09-21 23:43:11 +0000992 // [PR 3337] Use 'getAs<FunctionType>' to strip away any typedefs on the
Ted Kremenek99890652009-01-16 18:40:33 +0000993 // function's type.
John McCall183700f2009-09-21 23:43:11 +0000994 const FunctionType* FT = FD->getType()->getAs<FunctionType>();
Ted Kremenek48c6d182009-12-16 06:06:43 +0000995 const IdentifierInfo *II = FD->getIdentifier();
996 if (!II)
997 break;
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000998
999 StringRef FName = II->getName();
Mike Stump1eb44332009-09-09 15:08:12 +00001000
Ted Kremenekbf0a4dd2009-03-05 22:11:14 +00001001 // Strip away preceding '_'. Doing this here will effect all the checks
1002 // down below.
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001003 FName = FName.substr(FName.find_first_not_of('_'));
Mike Stump1eb44332009-09-09 15:08:12 +00001004
Ted Kremenek12619382009-01-12 21:45:02 +00001005 // Inspect the result type.
1006 QualType RetTy = FT->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00001007
Ted Kremenek12619382009-01-12 21:45:02 +00001008 // FIXME: This should all be refactored into a chain of "summary lookup"
1009 // filters.
Ted Kremenek008636a2009-10-14 00:27:24 +00001010 assert(ScratchArgs.isEmpty());
Ted Kremenek39d88b02009-06-15 20:36:07 +00001011
Ted Kremenekbefc6d22012-04-26 04:32:23 +00001012 if (FName == "pthread_create" || FName == "pthread_setspecific") {
1013 // Part of: <rdar://problem/7299394> and <rdar://problem/11282706>.
1014 // This will be addressed better with IPA.
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001015 S = getPersistentStopSummary();
1016 } else if (FName == "NSMakeCollectable") {
1017 // Handle: id NSMakeCollectable(CFTypeRef)
1018 S = (RetTy->isObjCIdType())
1019 ? getUnarySummary(FT, cfmakecollectable)
1020 : getPersistentStopSummary();
1021 } else if (FName == "IOBSDNameMatching" ||
1022 FName == "IOServiceMatching" ||
1023 FName == "IOServiceNameMatching" ||
Ted Kremenek537dd3a2012-05-01 05:28:27 +00001024 FName == "IORegistryEntrySearchCFProperty" ||
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001025 FName == "IORegistryEntryIDMatching" ||
1026 FName == "IOOpenFirmwarePathMatching") {
1027 // Part of <rdar://problem/6961230>. (IOKit)
1028 // This should be addressed using a API table.
1029 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1030 DoNothing, DoNothing);
1031 } else if (FName == "IOServiceGetMatchingService" ||
1032 FName == "IOServiceGetMatchingServices") {
1033 // FIXES: <rdar://problem/6326900>
1034 // This should be addressed using a API table. This strcmp is also
1035 // a little gross, but there is no need to super optimize here.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001036 ScratchArgs = AF.add(ScratchArgs, 1, DecRef);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001037 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1038 } else if (FName == "IOServiceAddNotification" ||
1039 FName == "IOServiceAddMatchingNotification") {
1040 // Part of <rdar://problem/6961230>. (IOKit)
1041 // This should be addressed using a API table.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001042 ScratchArgs = AF.add(ScratchArgs, 2, DecRef);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001043 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1044 } else if (FName == "CVPixelBufferCreateWithBytes") {
1045 // FIXES: <rdar://problem/7283567>
1046 // Eventually this can be improved by recognizing that the pixel
1047 // buffer passed to CVPixelBufferCreateWithBytes is released via
1048 // a callback and doing full IPA to make sure this is done correctly.
1049 // FIXME: This function has an out parameter that returns an
1050 // allocated object.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001051 ScratchArgs = AF.add(ScratchArgs, 7, StopTracking);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001052 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1053 } else if (FName == "CGBitmapContextCreateWithData") {
1054 // FIXES: <rdar://problem/7358899>
1055 // Eventually this can be improved by recognizing that 'releaseInfo'
1056 // passed to CGBitmapContextCreateWithData is released via
1057 // a callback and doing full IPA to make sure this is done correctly.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001058 ScratchArgs = AF.add(ScratchArgs, 8, StopTracking);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001059 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1060 DoNothing, DoNothing);
1061 } else if (FName == "CVPixelBufferCreateWithPlanarBytes") {
1062 // FIXES: <rdar://problem/7283567>
1063 // Eventually this can be improved by recognizing that the pixel
1064 // buffer passed to CVPixelBufferCreateWithPlanarBytes is released
1065 // via a callback and doing full IPA to make sure this is done
1066 // correctly.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001067 ScratchArgs = AF.add(ScratchArgs, 12, StopTracking);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001068 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenek06911d42012-03-22 06:29:41 +00001069 } else if (FName == "dispatch_set_context") {
1070 // <rdar://problem/11059275> - The analyzer currently doesn't have
1071 // a good way to reason about the finalizer function for libdispatch.
1072 // If we pass a context object that is memory managed, stop tracking it.
1073 // FIXME: this hack should possibly go away once we can handle
1074 // libdispatch finalizers.
1075 ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
1076 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenekc91fdf62012-05-08 00:12:09 +00001077 } else if (FName.startswith("NSLog")) {
1078 S = getDoNothingSummary();
Anna Zaks62a5c342012-03-30 05:48:16 +00001079 } else if (FName.startswith("NS") &&
1080 (FName.find("Insert") != StringRef::npos)) {
1081 // Whitelist NSXXInsertXX, for example NSMapInsertIfAbsent, since they can
1082 // be deallocated by NSMapRemove. (radar://11152419)
1083 ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
1084 ScratchArgs = AF.add(ScratchArgs, 2, StopTracking);
1085 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenekb04cb592009-06-11 18:17:24 +00001086 }
Mike Stump1eb44332009-09-09 15:08:12 +00001087
Ted Kremenekb04cb592009-06-11 18:17:24 +00001088 // Did we get a summary?
1089 if (S)
1090 break;
Ted Kremenek61991902009-03-17 22:43:44 +00001091
1092 // Enable this code once the semantics of NSDeallocateObject are resolved
1093 // for GC. <rdar://problem/6619988>
1094#if 0
1095 // Handle: NSDeallocateObject(id anObject);
1096 // This method does allow 'nil' (although we don't check it now).
Mike Stump1eb44332009-09-09 15:08:12 +00001097 if (strcmp(FName, "NSDeallocateObject") == 0) {
Ted Kremenek61991902009-03-17 22:43:44 +00001098 return RetTy == Ctx.VoidTy
1099 ? getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, Dealloc)
1100 : getPersistentStopSummary();
1101 }
1102#endif
Ted Kremenek12619382009-01-12 21:45:02 +00001103
1104 if (RetTy->isPointerType()) {
1105 // For CoreFoundation ('CF') types.
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001106 if (cocoa::isRefType(RetTy, "CF", FName)) {
Ted Kremenek12619382009-01-12 21:45:02 +00001107 if (isRetain(FD, FName))
1108 S = getUnarySummary(FT, cfretain);
Jordy Rose76c506f2011-08-21 21:58:18 +00001109 else if (isMakeCollectable(FD, FName))
Ted Kremenek12619382009-01-12 21:45:02 +00001110 S = getUnarySummary(FT, cfmakecollectable);
Mike Stump1eb44332009-09-09 15:08:12 +00001111 else
John McCall7df2ff42011-10-01 00:48:56 +00001112 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek12619382009-01-12 21:45:02 +00001113
1114 break;
1115 }
1116
1117 // For CoreGraphics ('CG') types.
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001118 if (cocoa::isRefType(RetTy, "CG", FName)) {
Ted Kremenek12619382009-01-12 21:45:02 +00001119 if (isRetain(FD, FName))
1120 S = getUnarySummary(FT, cfretain);
1121 else
John McCall7df2ff42011-10-01 00:48:56 +00001122 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek12619382009-01-12 21:45:02 +00001123
1124 break;
1125 }
1126
1127 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001128 if (cocoa::isRefType(RetTy, "DADisk") ||
1129 cocoa::isRefType(RetTy, "DADissenter") ||
1130 cocoa::isRefType(RetTy, "DASessionRef")) {
John McCall7df2ff42011-10-01 00:48:56 +00001131 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek12619382009-01-12 21:45:02 +00001132 break;
1133 }
Mike Stump1eb44332009-09-09 15:08:12 +00001134
Ted Kremenek12619382009-01-12 21:45:02 +00001135 break;
1136 }
1137
1138 // Check for release functions, the only kind of functions that we care
1139 // about that don't return a pointer type.
1140 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
Ted Kremeneke7d03122010-02-08 16:45:01 +00001141 // Test for 'CGCF'.
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001142 FName = FName.substr(FName.startswith("CGCF") ? 4 : 2);
Ted Kremeneke7d03122010-02-08 16:45:01 +00001143
Ted Kremenekbf0a4dd2009-03-05 22:11:14 +00001144 if (isRelease(FD, FName))
Ted Kremenek12619382009-01-12 21:45:02 +00001145 S = getUnarySummary(FT, cfrelease);
1146 else {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001147 assert (ScratchArgs.isEmpty());
Ted Kremenek68189282009-01-29 22:45:13 +00001148 // Remaining CoreFoundation and CoreGraphics functions.
1149 // We use to assume that they all strictly followed the ownership idiom
1150 // and that ownership cannot be transferred. While this is technically
1151 // correct, many methods allow a tracked object to escape. For example:
1152 //
Mike Stump1eb44332009-09-09 15:08:12 +00001153 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
Ted Kremenek68189282009-01-29 22:45:13 +00001154 // CFDictionaryAddValue(y, key, x);
Mike Stump1eb44332009-09-09 15:08:12 +00001155 // CFRelease(x);
Ted Kremenek68189282009-01-29 22:45:13 +00001156 // ... it is okay to use 'x' since 'y' has a reference to it
1157 //
1158 // We handle this and similar cases with the follow heuristic. If the
Ted Kremenekc4843812009-08-20 00:57:22 +00001159 // function name contains "InsertValue", "SetValue", "AddValue",
1160 // "AppendValue", or "SetAttribute", then we assume that arguments may
1161 // "escape." This means that something else holds on to the object,
1162 // allowing it be used even after its local retain count drops to 0.
Benjamin Kramere45c1492010-01-11 19:46:28 +00001163 ArgEffect E = (StrInStrNoCase(FName, "InsertValue") != StringRef::npos||
1164 StrInStrNoCase(FName, "AddValue") != StringRef::npos ||
1165 StrInStrNoCase(FName, "SetValue") != StringRef::npos ||
1166 StrInStrNoCase(FName, "AppendValue") != StringRef::npos||
Benjamin Kramerc027e542010-01-11 20:15:06 +00001167 StrInStrNoCase(FName, "SetAttribute") != StringRef::npos)
Ted Kremenek68189282009-01-29 22:45:13 +00001168 ? MayEscape : DoNothing;
Mike Stump1eb44332009-09-09 15:08:12 +00001169
Ted Kremenek68189282009-01-29 22:45:13 +00001170 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek12619382009-01-12 21:45:02 +00001171 }
1172 }
Ted Kremenek37d785b2008-07-15 16:50:12 +00001173 }
1174 while (0);
Mike Stump1eb44332009-09-09 15:08:12 +00001175
Jordan Rose4531b7d2012-07-02 19:27:43 +00001176 // If we got all the way here without any luck, use a default summary.
1177 if (!S)
1178 S = getDefaultSummary();
1179
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001180 // Annotations override defaults.
Jordy Rose4df54fe2011-08-23 04:27:15 +00001181 updateSummaryFromAnnotations(S, FD);
Mike Stump1eb44332009-09-09 15:08:12 +00001182
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001183 FuncSummaries[FD] = S;
Mike Stump1eb44332009-09-09 15:08:12 +00001184 return S;
Ted Kremenek2fff37e2008-03-06 00:08:09 +00001185}
1186
Ted Kremenek93edbc52011-10-05 23:54:29 +00001187const RetainSummary *
John McCall7df2ff42011-10-01 00:48:56 +00001188RetainSummaryManager::getCFCreateGetRuleSummary(const FunctionDecl *FD) {
1189 if (coreFoundation::followsCreateRule(FD))
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001190 return getCFSummaryCreateRule(FD);
Mike Stump1eb44332009-09-09 15:08:12 +00001191
Ted Kremenekd368d712011-05-25 06:19:45 +00001192 return getCFSummaryGetRule(FD);
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001193}
1194
Ted Kremenek93edbc52011-10-05 23:54:29 +00001195const RetainSummary *
Ted Kremenek6ad315a2009-02-23 16:51:39 +00001196RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1197 UnaryFuncKind func) {
1198
Ted Kremenek12619382009-01-12 21:45:02 +00001199 // Sanity check that this is *really* a unary function. This can
1200 // happen if people do weird things.
Douglas Gregor72564e72009-02-26 23:50:07 +00001201 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
Ted Kremenek12619382009-01-12 21:45:02 +00001202 if (!FTP || FTP->getNumArgs() != 1)
1203 return getPersistentStopSummary();
Mike Stump1eb44332009-09-09 15:08:12 +00001204
Ted Kremenekb77449c2009-05-03 05:20:50 +00001205 assert (ScratchArgs.isEmpty());
Mike Stump1eb44332009-09-09 15:08:12 +00001206
Jordy Rose76c506f2011-08-21 21:58:18 +00001207 ArgEffect Effect;
Ted Kremenek377e2302008-04-29 05:33:51 +00001208 switch (func) {
Jordy Rose76c506f2011-08-21 21:58:18 +00001209 case cfretain: Effect = IncRef; break;
1210 case cfrelease: Effect = DecRef; break;
1211 case cfmakecollectable: Effect = MakeCollectable; break;
Ted Kremenek940b1d82008-04-10 23:44:06 +00001212 }
Jordy Rose76c506f2011-08-21 21:58:18 +00001213
1214 ScratchArgs = AF.add(ScratchArgs, 0, Effect);
1215 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001216}
1217
Ted Kremenek93edbc52011-10-05 23:54:29 +00001218const RetainSummary *
Ted Kremenek9c378f72011-08-12 23:37:29 +00001219RetainSummaryManager::getCFSummaryCreateRule(const FunctionDecl *FD) {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001220 assert (ScratchArgs.isEmpty());
Mike Stump1eb44332009-09-09 15:08:12 +00001221
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001222 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001223}
1224
Ted Kremenek93edbc52011-10-05 23:54:29 +00001225const RetainSummary *
Ted Kremenek9c378f72011-08-12 23:37:29 +00001226RetainSummaryManager::getCFSummaryGetRule(const FunctionDecl *FD) {
Mike Stump1eb44332009-09-09 15:08:12 +00001227 assert (ScratchArgs.isEmpty());
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001228 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1229 DoNothing, DoNothing);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001230}
1231
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001232//===----------------------------------------------------------------------===//
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001233// Summary creation for Selectors.
1234//===----------------------------------------------------------------------===//
1235
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001236void
Ted Kremenek93edbc52011-10-05 23:54:29 +00001237RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001238 const FunctionDecl *FD) {
1239 if (!FD)
1240 return;
1241
Jordan Rose4531b7d2012-07-02 19:27:43 +00001242 assert(Summ && "Must have a summary to add annotations to.");
1243 RetainSummaryTemplate Template(Summ, *this);
Jordy Rose4df54fe2011-08-23 04:27:15 +00001244
Ted Kremenek11fe1752011-01-27 18:43:03 +00001245 // Effects on the parameters.
1246 unsigned parm_idx = 0;
1247 for (FunctionDecl::param_const_iterator pi = FD->param_begin(),
John McCall98b8f162011-04-06 09:02:12 +00001248 pe = FD->param_end(); pi != pe; ++pi, ++parm_idx) {
Ted Kremenek11fe1752011-01-27 18:43:03 +00001249 const ParmVarDecl *pd = *pi;
1250 if (pd->getAttr<NSConsumedAttr>()) {
Jordy Rose4df54fe2011-08-23 04:27:15 +00001251 if (!GCEnabled) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001252 Template->addArg(AF, parm_idx, DecRef);
Jordy Rose4df54fe2011-08-23 04:27:15 +00001253 }
1254 } else if (pd->getAttr<CFConsumedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001255 Template->addArg(AF, parm_idx, DecRef);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001256 }
1257 }
1258
Ted Kremenekb04cb592009-06-11 18:17:24 +00001259 QualType RetTy = FD->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00001260
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001261 // Determine if there is a special return effect for this method.
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001262 if (cocoa::isCocoaObjectRef(RetTy)) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001263 if (FD->getAttr<NSReturnsRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001264 Template->setRetEffect(ObjCAllocRetE);
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001265 }
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001266 else if (FD->getAttr<CFReturnsRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001267 Template->setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenekb04cb592009-06-11 18:17:24 +00001268 }
Ted Kremenek60411112010-02-18 00:06:12 +00001269 else if (FD->getAttr<NSReturnsNotRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001270 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::ObjC));
Ted Kremenek60411112010-02-18 00:06:12 +00001271 }
1272 else if (FD->getAttr<CFReturnsNotRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001273 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::CF));
Jordy Rose4df54fe2011-08-23 04:27:15 +00001274 }
1275 } else if (RetTy->getAs<PointerType>()) {
1276 if (FD->getAttr<CFReturnsRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001277 Template->setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
Jordy Rose4df54fe2011-08-23 04:27:15 +00001278 }
1279 else if (FD->getAttr<CFReturnsNotRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001280 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::CF));
Ted Kremenek60411112010-02-18 00:06:12 +00001281 }
Ted Kremenekb04cb592009-06-11 18:17:24 +00001282 }
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001283}
1284
1285void
Ted Kremenek93edbc52011-10-05 23:54:29 +00001286RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
1287 const ObjCMethodDecl *MD) {
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001288 if (!MD)
1289 return;
1290
Jordan Rose4531b7d2012-07-02 19:27:43 +00001291 assert(Summ && "Must have a valid summary to add annotations to");
1292 RetainSummaryTemplate Template(Summ, *this);
Ted Kremenek6d4b76d2009-07-06 18:30:43 +00001293 bool isTrackedLoc = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001294
Ted Kremenek12b94342011-01-27 06:54:14 +00001295 // Effects on the receiver.
1296 if (MD->getAttr<NSConsumesSelfAttr>()) {
Ted Kremenek11fe1752011-01-27 18:43:03 +00001297 if (!GCEnabled)
Jordy Rose0fe62f82011-08-24 09:02:37 +00001298 Template->setReceiverEffect(DecRefMsg);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001299 }
1300
1301 // Effects on the parameters.
1302 unsigned parm_idx = 0;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00001303 for (ObjCMethodDecl::param_const_iterator
1304 pi=MD->param_begin(), pe=MD->param_end();
Ted Kremenek11fe1752011-01-27 18:43:03 +00001305 pi != pe; ++pi, ++parm_idx) {
1306 const ParmVarDecl *pd = *pi;
1307 if (pd->getAttr<NSConsumedAttr>()) {
1308 if (!GCEnabled)
Jordy Rose0fe62f82011-08-24 09:02:37 +00001309 Template->addArg(AF, parm_idx, DecRef);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001310 }
1311 else if(pd->getAttr<CFConsumedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001312 Template->addArg(AF, parm_idx, DecRef);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001313 }
Ted Kremenek12b94342011-01-27 06:54:14 +00001314 }
1315
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001316 // Determine if there is a special return effect for this method.
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001317 if (cocoa::isCocoaObjectRef(MD->getResultType())) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001318 if (MD->getAttr<NSReturnsRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001319 Template->setRetEffect(ObjCAllocRetE);
Ted Kremenek6d4b76d2009-07-06 18:30:43 +00001320 return;
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001321 }
Ted Kremenek60411112010-02-18 00:06:12 +00001322 if (MD->getAttr<NSReturnsNotRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001323 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::ObjC));
Ted Kremenek60411112010-02-18 00:06:12 +00001324 return;
1325 }
Mike Stump1eb44332009-09-09 15:08:12 +00001326
Ted Kremenek6d4b76d2009-07-06 18:30:43 +00001327 isTrackedLoc = true;
Jordy Rose0fe62f82011-08-24 09:02:37 +00001328 } else {
Ted Kremenek6217b802009-07-29 21:53:49 +00001329 isTrackedLoc = MD->getResultType()->getAs<PointerType>() != NULL;
Jordy Rose0fe62f82011-08-24 09:02:37 +00001330 }
Mike Stump1eb44332009-09-09 15:08:12 +00001331
Ted Kremenek60411112010-02-18 00:06:12 +00001332 if (isTrackedLoc) {
1333 if (MD->getAttr<CFReturnsRetainedAttr>())
Jordy Rose0fe62f82011-08-24 09:02:37 +00001334 Template->setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenek60411112010-02-18 00:06:12 +00001335 else if (MD->getAttr<CFReturnsNotRetainedAttr>())
Jordy Rose0fe62f82011-08-24 09:02:37 +00001336 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::CF));
Ted Kremenek60411112010-02-18 00:06:12 +00001337 }
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001338}
1339
Ted Kremenek93edbc52011-10-05 23:54:29 +00001340const RetainSummary *
Jordy Rosef3aae582012-03-17 21:13:07 +00001341RetainSummaryManager::getStandardMethodSummary(const ObjCMethodDecl *MD,
1342 Selector S, QualType RetTy) {
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001343
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +00001344 if (MD) {
Ted Kremenek376d1e72009-04-24 18:00:17 +00001345 // Scan the method decl for 'void*' arguments. These should be treated
1346 // as 'StopTracking' because they are often used with delegates.
1347 // Delegates are a frequent form of false positives with the retain
1348 // count checker.
1349 unsigned i = 0;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00001350 for (ObjCMethodDecl::param_const_iterator I = MD->param_begin(),
Ted Kremenek376d1e72009-04-24 18:00:17 +00001351 E = MD->param_end(); I != E; ++I, ++i)
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00001352 if (const ParmVarDecl *PD = *I) {
Ted Kremenek376d1e72009-04-24 18:00:17 +00001353 QualType Ty = Ctx.getCanonicalType(PD->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001354 if (Ty.getLocalUnqualifiedType() == Ctx.VoidPtrTy)
Ted Kremenek3baf6722010-11-24 00:54:37 +00001355 ScratchArgs = AF.add(ScratchArgs, i, StopTracking);
Ted Kremenek376d1e72009-04-24 18:00:17 +00001356 }
1357 }
Mike Stump1eb44332009-09-09 15:08:12 +00001358
Jordy Rosee921b1a2012-03-17 19:53:04 +00001359 // Any special effects?
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001360 ArgEffect ReceiverEff = DoNothing;
Jordy Rosee921b1a2012-03-17 19:53:04 +00001361 RetEffect ResultEff = RetEffect::MakeNoRet();
1362
1363 // Check the method family, and apply any default annotations.
1364 switch (MD ? MD->getMethodFamily() : S.getMethodFamily()) {
1365 case OMF_None:
1366 case OMF_performSelector:
1367 // Assume all Objective-C methods follow Cocoa Memory Management rules.
1368 // FIXME: Does the non-threaded performSelector family really belong here?
1369 // The selector could be, say, @selector(copy).
1370 if (cocoa::isCocoaObjectRef(RetTy))
1371 ResultEff = RetEffect::MakeNotOwned(RetEffect::ObjC);
1372 else if (coreFoundation::isCFObjectRef(RetTy)) {
1373 // ObjCMethodDecl currently doesn't consider CF objects as valid return
1374 // values for alloc, new, copy, or mutableCopy, so we have to
1375 // double-check with the selector. This is ugly, but there aren't that
1376 // many Objective-C methods that return CF objects, right?
1377 if (MD) {
1378 switch (S.getMethodFamily()) {
1379 case OMF_alloc:
1380 case OMF_new:
1381 case OMF_copy:
1382 case OMF_mutableCopy:
1383 ResultEff = RetEffect::MakeOwned(RetEffect::CF, true);
1384 break;
1385 default:
1386 ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1387 break;
1388 }
1389 } else {
1390 ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1391 }
1392 }
1393 break;
1394 case OMF_init:
1395 ResultEff = ObjCInitRetE;
1396 ReceiverEff = DecRefMsg;
1397 break;
1398 case OMF_alloc:
1399 case OMF_new:
1400 case OMF_copy:
1401 case OMF_mutableCopy:
1402 if (cocoa::isCocoaObjectRef(RetTy))
1403 ResultEff = ObjCAllocRetE;
1404 else if (coreFoundation::isCFObjectRef(RetTy))
1405 ResultEff = RetEffect::MakeOwned(RetEffect::CF, true);
1406 break;
1407 case OMF_autorelease:
1408 ReceiverEff = Autorelease;
1409 break;
1410 case OMF_retain:
1411 ReceiverEff = IncRefMsg;
1412 break;
1413 case OMF_release:
1414 ReceiverEff = DecRefMsg;
1415 break;
1416 case OMF_dealloc:
1417 ReceiverEff = Dealloc;
1418 break;
1419 case OMF_self:
1420 // -self is handled specially by the ExprEngine to propagate the receiver.
1421 break;
1422 case OMF_retainCount:
1423 case OMF_finalize:
1424 // These methods don't return objects.
1425 break;
1426 }
Mike Stump1eb44332009-09-09 15:08:12 +00001427
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001428 // If one of the arguments in the selector has the keyword 'delegate' we
1429 // should stop tracking the reference count for the receiver. This is
1430 // because the reference count is quite possibly handled by a delegate
1431 // method.
1432 if (S.isKeywordSelector()) {
Jordan Rose50571a92012-06-15 18:19:52 +00001433 for (unsigned i = 0, e = S.getNumArgs(); i != e; ++i) {
1434 StringRef Slot = S.getNameForSlot(i);
1435 if (Slot.substr(Slot.size() - 8).equals_lower("delegate")) {
1436 if (ResultEff == ObjCInitRetE)
1437 ResultEff = RetEffect::MakeNoRet();
1438 else
1439 ReceiverEff = StopTracking;
1440 }
1441 }
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001442 }
Mike Stump1eb44332009-09-09 15:08:12 +00001443
Jordy Rosee921b1a2012-03-17 19:53:04 +00001444 if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing &&
1445 ResultEff.getKind() == RetEffect::NoRet)
Ted Kremenek93edbc52011-10-05 23:54:29 +00001446 return getDefaultSummary();
Mike Stump1eb44332009-09-09 15:08:12 +00001447
Jordy Rosee921b1a2012-03-17 19:53:04 +00001448 return getPersistentSummary(ResultEff, ReceiverEff, MayEscape);
Ted Kremenek250b1fa2009-04-23 23:08:22 +00001449}
1450
Ted Kremenek93edbc52011-10-05 23:54:29 +00001451const RetainSummary *
Jordan Rosecde8cdb2012-07-02 19:27:56 +00001452RetainSummaryManager::getInstanceMethodSummary(const ObjCMethodCall &Msg,
Jordan Rose4531b7d2012-07-02 19:27:43 +00001453 ProgramStateRef State) {
1454 const ObjCInterfaceDecl *ReceiverClass = 0;
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001455
Jordan Rose4531b7d2012-07-02 19:27:43 +00001456 // We do better tracking of the type of the object than the core ExprEngine.
1457 // See if we have its type in our private state.
1458 // FIXME: Eventually replace the use of state->get<RefBindings> with
1459 // a generic API for reasoning about the Objective-C types of symbolic
1460 // objects.
1461 SVal ReceiverV = Msg.getReceiverSVal();
1462 if (SymbolRef Sym = ReceiverV.getAsLocSymbol())
1463 if (const RefVal *T = State->get<RefBindings>(Sym))
Douglas Gregor04badcf2010-04-21 00:45:42 +00001464 if (const ObjCObjectPointerType *PT =
Jordan Rose4531b7d2012-07-02 19:27:43 +00001465 T->getType()->getAs<ObjCObjectPointerType>())
1466 ReceiverClass = PT->getInterfaceDecl();
1467
1468 // If we don't know what kind of object this is, fall back to its static type.
1469 if (!ReceiverClass)
1470 ReceiverClass = Msg.getReceiverInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00001471
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001472 // FIXME: The receiver could be a reference to a class, meaning that
1473 // we should use the class method.
Jordan Rose4531b7d2012-07-02 19:27:43 +00001474 // id x = [NSObject class];
1475 // [x performSelector:... withObject:... afterDelay:...];
1476 Selector S = Msg.getSelector();
1477 const ObjCMethodDecl *Method = Msg.getDecl();
1478 if (!Method && ReceiverClass)
1479 Method = ReceiverClass->getInstanceMethod(S);
1480
1481 return getMethodSummary(S, ReceiverClass, Method, Msg.getResultType(),
1482 ObjCMethodSummaries);
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001483}
1484
Ted Kremenek93edbc52011-10-05 23:54:29 +00001485const RetainSummary *
Jordan Rose4531b7d2012-07-02 19:27:43 +00001486RetainSummaryManager::getMethodSummary(Selector S, const ObjCInterfaceDecl *ID,
Jordy Rosef3aae582012-03-17 21:13:07 +00001487 const ObjCMethodDecl *MD, QualType RetTy,
1488 ObjCMethodSummariesTy &CachedSummaries) {
Ted Kremenek1bffd742008-05-06 15:44:25 +00001489
Ted Kremenek8711c032009-04-29 05:04:30 +00001490 // Look up a summary in our summary cache.
Jordan Rose4531b7d2012-07-02 19:27:43 +00001491 const RetainSummary *Summ = CachedSummaries.find(ID, S);
Mike Stump1eb44332009-09-09 15:08:12 +00001492
Ted Kremenek614cc542009-07-21 23:27:57 +00001493 if (!Summ) {
Jordy Rosef3aae582012-03-17 21:13:07 +00001494 Summ = getStandardMethodSummary(MD, S, RetTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001495
Ted Kremenek614cc542009-07-21 23:27:57 +00001496 // Annotations override defaults.
Jordy Rose4df54fe2011-08-23 04:27:15 +00001497 updateSummaryFromAnnotations(Summ, MD);
Mike Stump1eb44332009-09-09 15:08:12 +00001498
Ted Kremenek614cc542009-07-21 23:27:57 +00001499 // Memoize the summary.
Jordan Rose4531b7d2012-07-02 19:27:43 +00001500 CachedSummaries[ObjCSummaryKey(ID, S)] = Summ;
Ted Kremenek614cc542009-07-21 23:27:57 +00001501 }
Mike Stump1eb44332009-09-09 15:08:12 +00001502
Ted Kremeneke87450e2009-04-23 19:11:35 +00001503 return Summ;
Ted Kremenekc8395602008-05-06 21:26:51 +00001504}
1505
Mike Stump1eb44332009-09-09 15:08:12 +00001506void RetainSummaryManager::InitializeClassMethodSummaries() {
Ted Kremenekec315332009-05-07 23:40:42 +00001507 assert(ScratchArgs.isEmpty());
Mike Stump1eb44332009-09-09 15:08:12 +00001508 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek6fe2b7a2009-10-15 22:25:12 +00001509 addClassMethSummary("NSAssertionHandler", "currentHandler",
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001510 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Mike Stump1eb44332009-09-09 15:08:12 +00001511
Ted Kremenek6d348932008-10-21 15:53:15 +00001512 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001513 ScratchArgs = AF.add(ScratchArgs, 0, Autorelease);
Ted Kremenek6fe2b7a2009-10-15 22:25:12 +00001514 addClassMethSummary("NSAutoreleasePool", "addObject",
1515 getPersistentSummary(RetEffect::MakeNoRet(),
1516 DoNothing, Autorelease));
Ted Kremenek9c32d082008-05-06 00:30:21 +00001517}
1518
Ted Kremenek1f180c32008-06-23 22:21:20 +00001519void RetainSummaryManager::InitializeMethodSummaries() {
Mike Stump1eb44332009-09-09 15:08:12 +00001520
1521 assert (ScratchArgs.isEmpty());
1522
Ted Kremenekc8395602008-05-06 21:26:51 +00001523 // Create the "init" selector. It just acts as a pass-through for the
1524 // receiver.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001525 const RetainSummary *InitSumm = getPersistentSummary(ObjCInitRetE, DecRefMsg);
Ted Kremenekac02f202009-08-20 05:13:36 +00001526 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
1527
1528 // awakeAfterUsingCoder: behaves basically like an 'init' method. It
1529 // claims the receiver and returns a retained object.
1530 addNSObjectMethSummary(GetUnarySelector("awakeAfterUsingCoder", Ctx),
1531 InitSumm);
Mike Stump1eb44332009-09-09 15:08:12 +00001532
Ted Kremenekc8395602008-05-06 21:26:51 +00001533 // The next methods are allocators.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001534 const RetainSummary *AllocSumm = getPersistentSummary(ObjCAllocRetE);
1535 const RetainSummary *CFAllocSumm =
Ted Kremeneka834fb42009-08-28 19:52:12 +00001536 getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Mike Stump1eb44332009-09-09 15:08:12 +00001537
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001538 // Create the "retain" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001539 RetEffect NoRet = RetEffect::MakeNoRet();
Ted Kremenek93edbc52011-10-05 23:54:29 +00001540 const RetainSummary *Summ = getPersistentSummary(NoRet, IncRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001541 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001542
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001543 // Create the "release" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001544 Summ = getPersistentSummary(NoRet, DecRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001545 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001546
Ted Kremenek299e8152008-05-07 21:17:39 +00001547 // Create the "drain" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001548 Summ = getPersistentSummary(NoRet, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek553cf182008-06-25 21:21:56 +00001549 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001550
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001551 // Create the -dealloc summary.
Jordy Rose500abad2011-08-21 19:41:36 +00001552 Summ = getPersistentSummary(NoRet, Dealloc);
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001553 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001554
1555 // Create the "autorelease" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001556 Summ = getPersistentSummary(NoRet, Autorelease);
Ted Kremenek553cf182008-06-25 21:21:56 +00001557 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001558
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00001559 // Specially handle NSAutoreleasePool.
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001560 addInstMethSummary("NSAutoreleasePool", "init",
Jordy Rose500abad2011-08-21 19:41:36 +00001561 getPersistentSummary(NoRet, NewAutoreleasePool));
Mike Stump1eb44332009-09-09 15:08:12 +00001562
1563 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremenek89e202d2009-02-23 02:51:29 +00001564 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1565 // self-own themselves. However, they only do this once they are displayed.
1566 // Thus, we need to track an NSWindow's display status.
1567 // This is tracked in <rdar://problem/6062711>.
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +00001568 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001569 const RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenek78a35a32009-05-12 20:06:54 +00001570 StopTracking,
1571 StopTracking);
Mike Stump1eb44332009-09-09 15:08:12 +00001572
Ted Kremenek99d02692009-04-03 19:02:51 +00001573 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1574
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +00001575#if 0
Ted Kremenek78a35a32009-05-12 20:06:54 +00001576 addInstMethSummary("NSWindow", NoTrackYet, "initWithContentRect",
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001577 "styleMask", "backing", "defer", NULL);
Mike Stump1eb44332009-09-09 15:08:12 +00001578
Ted Kremenek78a35a32009-05-12 20:06:54 +00001579 addInstMethSummary("NSWindow", NoTrackYet, "initWithContentRect",
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001580 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +00001581#endif
Mike Stump1eb44332009-09-09 15:08:12 +00001582
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001583 // For NSPanel (which subclasses NSWindow), allocated objects are not
1584 // self-owned.
Ted Kremenek99d02692009-04-03 19:02:51 +00001585 // FIXME: For now we don't track NSPanels. object for the same reason
1586 // as for NSWindow objects.
1587 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
Mike Stump1eb44332009-09-09 15:08:12 +00001588
Ted Kremenek78a35a32009-05-12 20:06:54 +00001589#if 0
1590 addInstMethSummary("NSPanel", NoTrackYet, "initWithContentRect",
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001591 "styleMask", "backing", "defer", NULL);
Mike Stump1eb44332009-09-09 15:08:12 +00001592
Ted Kremenek78a35a32009-05-12 20:06:54 +00001593 addInstMethSummary("NSPanel", NoTrackYet, "initWithContentRect",
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001594 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek78a35a32009-05-12 20:06:54 +00001595#endif
Mike Stump1eb44332009-09-09 15:08:12 +00001596
Ted Kremenekba67f6a2009-05-18 23:14:34 +00001597 // Don't track allocated autorelease pools yet, as it is okay to prematurely
1598 // exit a method.
1599 addClassMethSummary("NSAutoreleasePool", "alloc", NoTrackYet);
Ted Kremeneka9797122012-02-18 21:37:48 +00001600 addClassMethSummary("NSAutoreleasePool", "allocWithZone", NoTrackYet, false);
Ted Kremenek553cf182008-06-25 21:21:56 +00001601
Ted Kremenek767d6492009-05-20 22:39:57 +00001602 // Create summaries QCRenderer/QCView -createSnapShotImageOfType:
1603 addInstMethSummary("QCRenderer", AllocSumm,
1604 "createSnapshotImageOfType", NULL);
1605 addInstMethSummary("QCView", AllocSumm,
1606 "createSnapshotImageOfType", NULL);
1607
Ted Kremenek211a9c62009-06-15 20:58:58 +00001608 // Create summaries for CIContext, 'createCGImage' and
Ted Kremeneka834fb42009-08-28 19:52:12 +00001609 // 'createCGLayerWithSize'. These objects are CF objects, and are not
1610 // automatically garbage collected.
1611 addInstMethSummary("CIContext", CFAllocSumm,
Ted Kremenek767d6492009-05-20 22:39:57 +00001612 "createCGImage", "fromRect", NULL);
Ted Kremeneka834fb42009-08-28 19:52:12 +00001613 addInstMethSummary("CIContext", CFAllocSumm,
Mike Stump1eb44332009-09-09 15:08:12 +00001614 "createCGImage", "fromRect", "format", "colorSpace", NULL);
Ted Kremeneka834fb42009-08-28 19:52:12 +00001615 addInstMethSummary("CIContext", CFAllocSumm, "createCGLayerWithSize",
Ted Kremenek211a9c62009-06-15 20:58:58 +00001616 "info", NULL);
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001617}
1618
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001619//===----------------------------------------------------------------------===//
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001620// AutoreleaseBindings - State used to track objects in autorelease pools.
Ted Kremenek6d348932008-10-21 15:53:15 +00001621//===----------------------------------------------------------------------===//
1622
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001623typedef llvm::ImmutableMap<SymbolRef, unsigned> ARCounts;
1624typedef llvm::ImmutableMap<SymbolRef, ARCounts> ARPoolContents;
1625typedef llvm::ImmutableList<SymbolRef> ARStack;
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00001626
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001627static int AutoRCIndex = 0;
Ted Kremenek6d348932008-10-21 15:53:15 +00001628static int AutoRBIndex = 0;
1629
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001630namespace { class AutoreleasePoolContents {}; }
1631namespace { class AutoreleaseStack {}; }
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001632
Ted Kremenek6d348932008-10-21 15:53:15 +00001633namespace clang {
Ted Kremenek9ef65372010-12-23 07:20:52 +00001634namespace ento {
Ted Kremenek18c66fd2011-08-15 22:09:50 +00001635template<> struct ProgramStateTrait<AutoreleaseStack>
1636 : public ProgramStatePartialTrait<ARStack> {
Ted Kremenek9c378f72011-08-12 23:37:29 +00001637 static inline void *GDMIndex() { return &AutoRBIndex; }
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001638};
1639
Ted Kremenek18c66fd2011-08-15 22:09:50 +00001640template<> struct ProgramStateTrait<AutoreleasePoolContents>
1641 : public ProgramStatePartialTrait<ARPoolContents> {
Ted Kremenek9c378f72011-08-12 23:37:29 +00001642 static inline void *GDMIndex() { return &AutoRCIndex; }
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001643};
Argyrios Kyrtzidis5a4f98f2010-12-22 18:53:20 +00001644} // end GR namespace
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001645} // end clang namespace
Ted Kremenek6d348932008-10-21 15:53:15 +00001646
Ted Kremenek8bef8232012-01-26 21:29:00 +00001647static SymbolRef GetCurrentAutoreleasePool(ProgramStateRef state) {
Ted Kremenek7037ab82009-03-20 17:34:15 +00001648 ARStack stack = state->get<AutoreleaseStack>();
1649 return stack.isEmpty() ? SymbolRef() : stack.getHead();
1650}
1651
Ted Kremenek8bef8232012-01-26 21:29:00 +00001652static ProgramStateRef
1653SendAutorelease(ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +00001654 ARCounts::Factory &F,
1655 SymbolRef sym) {
Ted Kremenek7037ab82009-03-20 17:34:15 +00001656 SymbolRef pool = GetCurrentAutoreleasePool(state);
Ted Kremenekb65be702009-06-18 01:23:53 +00001657 const ARCounts *cnts = state->get<AutoreleasePoolContents>(pool);
Ted Kremenek7037ab82009-03-20 17:34:15 +00001658 ARCounts newCnts(0);
Mike Stump1eb44332009-09-09 15:08:12 +00001659
Ted Kremenek7037ab82009-03-20 17:34:15 +00001660 if (cnts) {
1661 const unsigned *cnt = (*cnts).lookup(sym);
Ted Kremenek3baf6722010-11-24 00:54:37 +00001662 newCnts = F.add(*cnts, sym, cnt ? *cnt + 1 : 1);
Ted Kremenek7037ab82009-03-20 17:34:15 +00001663 }
1664 else
Ted Kremenek3baf6722010-11-24 00:54:37 +00001665 newCnts = F.add(F.getEmptyMap(), sym, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001666
Ted Kremenekb65be702009-06-18 01:23:53 +00001667 return state->set<AutoreleasePoolContents>(pool, newCnts);
Ted Kremenek7037ab82009-03-20 17:34:15 +00001668}
1669
Ted Kremenek13922612008-04-16 20:40:59 +00001670//===----------------------------------------------------------------------===//
Ted Kremenekc887d132009-04-29 18:50:19 +00001671// Error reporting.
1672//===----------------------------------------------------------------------===//
Ted Kremenekc887d132009-04-29 18:50:19 +00001673namespace {
Jordy Roseec9ef852011-08-23 20:55:48 +00001674 typedef llvm::DenseMap<const ExplodedNode *, const RetainSummary *>
1675 SummaryLogTy;
1676
Ted Kremenekc887d132009-04-29 18:50:19 +00001677 //===-------------===//
1678 // Bug Descriptions. //
Mike Stump1eb44332009-09-09 15:08:12 +00001679 //===-------------===//
1680
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001681 class CFRefBug : public BugType {
Ted Kremenekc887d132009-04-29 18:50:19 +00001682 protected:
Jordy Rose35c86952011-08-24 05:47:39 +00001683 CFRefBug(StringRef name)
Ted Kremenek6fd45052012-04-05 20:43:28 +00001684 : BugType(name, categories::MemoryCoreFoundationObjectiveC) {}
Ted Kremenekc887d132009-04-29 18:50:19 +00001685 public:
Mike Stump1eb44332009-09-09 15:08:12 +00001686
Ted Kremenekc887d132009-04-29 18:50:19 +00001687 // FIXME: Eventually remove.
Jordy Rose35c86952011-08-24 05:47:39 +00001688 virtual const char *getDescription() const = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001689
Ted Kremenekc887d132009-04-29 18:50:19 +00001690 virtual bool isLeak() const { return false; }
1691 };
Mike Stump1eb44332009-09-09 15:08:12 +00001692
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001693 class UseAfterRelease : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001694 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001695 UseAfterRelease() : CFRefBug("Use-after-release") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001696
Jordy Rose35c86952011-08-24 05:47:39 +00001697 const char *getDescription() const {
Ted Kremenekc887d132009-04-29 18:50:19 +00001698 return "Reference-counted object is used after it is released";
Mike Stump1eb44332009-09-09 15:08:12 +00001699 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001700 };
Mike Stump1eb44332009-09-09 15:08:12 +00001701
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001702 class BadRelease : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001703 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001704 BadRelease() : CFRefBug("Bad release") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001705
Jordy Rose35c86952011-08-24 05:47:39 +00001706 const char *getDescription() const {
Ted Kremenekbb206fd2009-10-01 17:31:50 +00001707 return "Incorrect decrement of the reference count of an object that is "
1708 "not owned at this point by the caller";
Ted Kremenekc887d132009-04-29 18:50:19 +00001709 }
1710 };
Mike Stump1eb44332009-09-09 15:08:12 +00001711
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001712 class DeallocGC : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001713 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001714 DeallocGC()
1715 : CFRefBug("-dealloc called while using garbage collection") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001716
Ted Kremenekc887d132009-04-29 18:50:19 +00001717 const char *getDescription() const {
Ted Kremenek369de562009-05-09 00:10:05 +00001718 return "-dealloc called while using garbage collection";
Ted Kremenekc887d132009-04-29 18:50:19 +00001719 }
1720 };
Mike Stump1eb44332009-09-09 15:08:12 +00001721
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001722 class DeallocNotOwned : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001723 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001724 DeallocNotOwned()
1725 : CFRefBug("-dealloc sent to non-exclusively owned object") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001726
Ted Kremenekc887d132009-04-29 18:50:19 +00001727 const char *getDescription() const {
1728 return "-dealloc sent to object that may be referenced elsewhere";
1729 }
Mike Stump1eb44332009-09-09 15:08:12 +00001730 };
1731
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001732 class OverAutorelease : public CFRefBug {
Ted Kremenek369de562009-05-09 00:10:05 +00001733 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001734 OverAutorelease()
1735 : CFRefBug("Object sent -autorelease too many times") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001736
Ted Kremenek369de562009-05-09 00:10:05 +00001737 const char *getDescription() const {
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001738 return "Object sent -autorelease too many times";
Ted Kremenek369de562009-05-09 00:10:05 +00001739 }
1740 };
Mike Stump1eb44332009-09-09 15:08:12 +00001741
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001742 class ReturnedNotOwnedForOwned : public CFRefBug {
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001743 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001744 ReturnedNotOwnedForOwned()
1745 : CFRefBug("Method should return an owned object") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001746
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001747 const char *getDescription() const {
Jordy Rose5b5402b2011-07-15 22:17:54 +00001748 return "Object with a +0 retain count returned to caller where a +1 "
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001749 "(owning) retain count is expected";
1750 }
1751 };
Mike Stump1eb44332009-09-09 15:08:12 +00001752
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001753 class Leak : public CFRefBug {
Benjamin Kramerfacde172012-06-06 17:32:50 +00001754 public:
1755 Leak(StringRef name)
1756 : CFRefBug(name) {
Jordy Rosedb92bb62011-08-25 01:14:38 +00001757 // Leaks should not be reported if they are post-dominated by a sink.
1758 setSuppressOnSink(true);
1759 }
Mike Stump1eb44332009-09-09 15:08:12 +00001760
Jordy Rose35c86952011-08-24 05:47:39 +00001761 const char *getDescription() const { return ""; }
Mike Stump1eb44332009-09-09 15:08:12 +00001762
Ted Kremenekc887d132009-04-29 18:50:19 +00001763 bool isLeak() const { return true; }
1764 };
Mike Stump1eb44332009-09-09 15:08:12 +00001765
Ted Kremenekc887d132009-04-29 18:50:19 +00001766 //===---------===//
1767 // Bug Reports. //
1768 //===---------===//
Mike Stump1eb44332009-09-09 15:08:12 +00001769
Jordy Rose01153492012-03-24 02:45:35 +00001770 class CFRefReportVisitor : public BugReporterVisitorImpl<CFRefReportVisitor> {
Anna Zaks23f395e2011-08-20 01:27:22 +00001771 protected:
Anna Zaksdc757b02011-08-19 23:21:56 +00001772 SymbolRef Sym;
Jordy Roseec9ef852011-08-23 20:55:48 +00001773 const SummaryLogTy &SummaryLog;
Jordy Rose35c86952011-08-24 05:47:39 +00001774 bool GCEnabled;
Anna Zaks23f395e2011-08-20 01:27:22 +00001775
Anna Zaksdc757b02011-08-19 23:21:56 +00001776 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001777 CFRefReportVisitor(SymbolRef sym, bool gcEnabled, const SummaryLogTy &log)
1778 : Sym(sym), SummaryLog(log), GCEnabled(gcEnabled) {}
Anna Zaksdc757b02011-08-19 23:21:56 +00001779
Anna Zaks23f395e2011-08-20 01:27:22 +00001780 virtual void Profile(llvm::FoldingSetNodeID &ID) const {
Anna Zaksdc757b02011-08-19 23:21:56 +00001781 static int x = 0;
1782 ID.AddPointer(&x);
1783 ID.AddPointer(Sym);
1784 }
1785
Anna Zaks23f395e2011-08-20 01:27:22 +00001786 virtual PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
1787 const ExplodedNode *PrevN,
1788 BugReporterContext &BRC,
1789 BugReport &BR);
1790
1791 virtual PathDiagnosticPiece *getEndPath(BugReporterContext &BRC,
1792 const ExplodedNode *N,
1793 BugReport &BR);
1794 };
1795
1796 class CFRefLeakReportVisitor : public CFRefReportVisitor {
1797 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001798 CFRefLeakReportVisitor(SymbolRef sym, bool GCEnabled,
Jordy Roseec9ef852011-08-23 20:55:48 +00001799 const SummaryLogTy &log)
Jordy Rose35c86952011-08-24 05:47:39 +00001800 : CFRefReportVisitor(sym, GCEnabled, log) {}
Anna Zaks23f395e2011-08-20 01:27:22 +00001801
1802 PathDiagnosticPiece *getEndPath(BugReporterContext &BRC,
1803 const ExplodedNode *N,
1804 BugReport &BR);
Jordy Rose01153492012-03-24 02:45:35 +00001805
1806 virtual BugReporterVisitor *clone() const {
1807 // The curiously-recurring template pattern only works for one level of
1808 // subclassing. Rather than make a new template base for
1809 // CFRefReportVisitor, we simply override clone() to do the right thing.
1810 // This could be trouble someday if BugReporterVisitorImpl is ever
1811 // used for something else besides a convenient implementation of clone().
1812 return new CFRefLeakReportVisitor(*this);
1813 }
Anna Zaksdc757b02011-08-19 23:21:56 +00001814 };
1815
Anna Zakse172e8b2011-08-17 23:00:25 +00001816 class CFRefReport : public BugReport {
Jordy Rose20589562011-08-24 22:39:09 +00001817 void addGCModeDescription(const LangOptions &LOpts, bool GCEnabled);
Jordy Rose35c86952011-08-24 05:47:39 +00001818
Ted Kremenekc887d132009-04-29 18:50:19 +00001819 public:
Jordy Rose20589562011-08-24 22:39:09 +00001820 CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1821 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1822 bool registerVisitor = true)
Anna Zaksedf4dae2011-08-22 18:54:07 +00001823 : BugReport(D, D.getDescription(), n) {
Anna Zaks23f395e2011-08-20 01:27:22 +00001824 if (registerVisitor)
Jordy Rose20589562011-08-24 22:39:09 +00001825 addVisitor(new CFRefReportVisitor(sym, GCEnabled, Log));
1826 addGCModeDescription(LOpts, GCEnabled);
Anna Zaksdc757b02011-08-19 23:21:56 +00001827 }
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001828
Jordy Rose20589562011-08-24 22:39:09 +00001829 CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1830 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1831 StringRef endText)
Anna Zaksedf4dae2011-08-22 18:54:07 +00001832 : BugReport(D, D.getDescription(), endText, n) {
Jordy Rose20589562011-08-24 22:39:09 +00001833 addVisitor(new CFRefReportVisitor(sym, GCEnabled, Log));
1834 addGCModeDescription(LOpts, GCEnabled);
Anna Zaksdc757b02011-08-19 23:21:56 +00001835 }
Mike Stump1eb44332009-09-09 15:08:12 +00001836
Anna Zakse172e8b2011-08-17 23:00:25 +00001837 virtual std::pair<ranges_iterator, ranges_iterator> getRanges() {
Anna Zaksedf4dae2011-08-22 18:54:07 +00001838 const CFRefBug& BugTy = static_cast<CFRefBug&>(getBugType());
1839 if (!BugTy.isLeak())
Anna Zakse172e8b2011-08-17 23:00:25 +00001840 return BugReport::getRanges();
Ted Kremenekc887d132009-04-29 18:50:19 +00001841 else
Argyrios Kyrtzidis640ccf02010-12-04 01:12:15 +00001842 return std::make_pair(ranges_iterator(), ranges_iterator());
Ted Kremenekc887d132009-04-29 18:50:19 +00001843 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001844 };
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001845
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001846 class CFRefLeakReport : public CFRefReport {
Ted Kremenekc887d132009-04-29 18:50:19 +00001847 const MemRegion* AllocBinding;
Anna Zaks23f395e2011-08-20 01:27:22 +00001848
Ted Kremenekc887d132009-04-29 18:50:19 +00001849 public:
Jordy Rose20589562011-08-24 22:39:09 +00001850 CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1851 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
Anna Zaks6a93bd52011-10-25 19:57:11 +00001852 CheckerContext &Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001853
Anna Zaks590dd8e2011-09-20 21:38:35 +00001854 PathDiagnosticLocation getLocation(const SourceManager &SM) const {
1855 assert(Location.isValid());
1856 return Location;
1857 }
Mike Stump1eb44332009-09-09 15:08:12 +00001858 };
Ted Kremenekc887d132009-04-29 18:50:19 +00001859} // end anonymous namespace
1860
Jordy Rose20589562011-08-24 22:39:09 +00001861void CFRefReport::addGCModeDescription(const LangOptions &LOpts,
1862 bool GCEnabled) {
Jordy Rosef95b19d2011-08-24 20:38:42 +00001863 const char *GCModeDescription = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001864
Douglas Gregore289d812011-09-13 17:21:33 +00001865 switch (LOpts.getGC()) {
Anna Zaks7f2531c2011-08-22 20:31:28 +00001866 case LangOptions::GCOnly:
Jordy Rose20589562011-08-24 22:39:09 +00001867 assert(GCEnabled);
Jordy Rose35c86952011-08-24 05:47:39 +00001868 GCModeDescription = "Code is compiled to only use garbage collection";
1869 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001870
Anna Zaks7f2531c2011-08-22 20:31:28 +00001871 case LangOptions::NonGC:
Jordy Rose20589562011-08-24 22:39:09 +00001872 assert(!GCEnabled);
Jordy Rose35c86952011-08-24 05:47:39 +00001873 GCModeDescription = "Code is compiled to use reference counts";
1874 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001875
Anna Zaks7f2531c2011-08-22 20:31:28 +00001876 case LangOptions::HybridGC:
Jordy Rose20589562011-08-24 22:39:09 +00001877 if (GCEnabled) {
Jordy Rose35c86952011-08-24 05:47:39 +00001878 GCModeDescription = "Code is compiled to use either garbage collection "
1879 "(GC) or reference counts (non-GC). The bug occurs "
1880 "with GC enabled";
1881 break;
1882 } else {
1883 GCModeDescription = "Code is compiled to use either garbage collection "
1884 "(GC) or reference counts (non-GC). The bug occurs "
1885 "in non-GC mode";
1886 break;
Anna Zaks7f2531c2011-08-22 20:31:28 +00001887 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001888 }
Jordy Rose35c86952011-08-24 05:47:39 +00001889
Jordy Rosef95b19d2011-08-24 20:38:42 +00001890 assert(GCModeDescription && "invalid/unknown GC mode");
Jordy Rose35c86952011-08-24 05:47:39 +00001891 addExtraText(GCModeDescription);
Ted Kremenekc887d132009-04-29 18:50:19 +00001892}
1893
Jordy Rose910c4052011-09-02 06:44:22 +00001894// FIXME: This should be a method on SmallVector.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001895static inline bool contains(const SmallVectorImpl<ArgEffect>& V,
Ted Kremenekc887d132009-04-29 18:50:19 +00001896 ArgEffect X) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001897 for (SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
Ted Kremenekc887d132009-04-29 18:50:19 +00001898 I!=E; ++I)
1899 if (*I == X) return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001900
Ted Kremenekc887d132009-04-29 18:50:19 +00001901 return false;
1902}
1903
Jordy Rose70fdbc32012-05-12 05:10:43 +00001904static bool isNumericLiteralExpression(const Expr *E) {
1905 // FIXME: This set of cases was copied from SemaExprObjC.
1906 return isa<IntegerLiteral>(E) ||
1907 isa<CharacterLiteral>(E) ||
1908 isa<FloatingLiteral>(E) ||
1909 isa<ObjCBoolLiteralExpr>(E) ||
1910 isa<CXXBoolLiteralExpr>(E);
1911}
1912
Ted Kremenek4c42bb72011-11-14 21:59:21 +00001913static bool isPropertyAccess(const Stmt *S, ParentMap &PM) {
1914 unsigned maxDepth = 4;
1915 while (S && maxDepth) {
1916 if (const PseudoObjectExpr *PO = dyn_cast<PseudoObjectExpr>(S)) {
1917 if (!isa<ObjCMessageExpr>(PO->getSyntacticForm()))
1918 return true;
1919 return false;
1920 }
1921 S = PM.getParent(S);
1922 --maxDepth;
1923 }
1924 return false;
1925}
1926
Anna Zaksdc757b02011-08-19 23:21:56 +00001927PathDiagnosticPiece *CFRefReportVisitor::VisitNode(const ExplodedNode *N,
1928 const ExplodedNode *PrevN,
1929 BugReporterContext &BRC,
1930 BugReport &BR) {
Mike Stump1eb44332009-09-09 15:08:12 +00001931
Jordy Rosef53e8c72011-08-23 19:43:16 +00001932 if (!isa<StmtPoint>(N->getLocation()))
Ted Kremenek2033a952009-05-13 07:12:33 +00001933 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001934
Ted Kremenek8966bc12009-05-06 21:39:49 +00001935 // Check if the type state has changed.
Ted Kremenek8bef8232012-01-26 21:29:00 +00001936 ProgramStateRef PrevSt = PrevN->getState();
1937 ProgramStateRef CurrSt = N->getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001938 const LocationContext *LCtx = N->getLocationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00001939
1940 const RefVal* CurrT = CurrSt->get<RefBindings>(Sym);
Ted Kremenekc887d132009-04-29 18:50:19 +00001941 if (!CurrT) return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001942
Ted Kremenekb65be702009-06-18 01:23:53 +00001943 const RefVal &CurrV = *CurrT;
1944 const RefVal *PrevT = PrevSt->get<RefBindings>(Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00001945
Ted Kremenekc887d132009-04-29 18:50:19 +00001946 // Create a string buffer to constain all the useful things we want
1947 // to tell the user.
1948 std::string sbuf;
1949 llvm::raw_string_ostream os(sbuf);
Mike Stump1eb44332009-09-09 15:08:12 +00001950
Ted Kremenekc887d132009-04-29 18:50:19 +00001951 // This is the allocation site since the previous node had no bindings
1952 // for this symbol.
1953 if (!PrevT) {
Jordy Rosef53e8c72011-08-23 19:43:16 +00001954 const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
Mike Stump1eb44332009-09-09 15:08:12 +00001955
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001956 if (isa<ObjCArrayLiteral>(S)) {
1957 os << "NSArray literal is an object with a +0 retain count";
Mike Stump1eb44332009-09-09 15:08:12 +00001958 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001959 else if (isa<ObjCDictionaryLiteral>(S)) {
1960 os << "NSDictionary literal is an object with a +0 retain count";
Ted Kremenekc887d132009-04-29 18:50:19 +00001961 }
Jordy Rose70fdbc32012-05-12 05:10:43 +00001962 else if (const ObjCBoxedExpr *BL = dyn_cast<ObjCBoxedExpr>(S)) {
1963 if (isNumericLiteralExpression(BL->getSubExpr()))
1964 os << "NSNumber literal is an object with a +0 retain count";
1965 else {
1966 const ObjCInterfaceDecl *BoxClass = 0;
1967 if (const ObjCMethodDecl *Method = BL->getBoxingMethod())
1968 BoxClass = Method->getClassInterface();
1969
1970 // We should always be able to find the boxing class interface,
1971 // but consider this future-proofing.
1972 if (BoxClass)
1973 os << *BoxClass << " b";
1974 else
1975 os << "B";
1976
1977 os << "oxed expression produces an object with a +0 retain count";
1978 }
1979 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001980 else {
1981 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
1982 // Get the name of the callee (if it is available).
1983 SVal X = CurrSt->getSValAsScalarOrLoc(CE->getCallee(), LCtx);
1984 if (const FunctionDecl *FD = X.getAsFunctionDecl())
1985 os << "Call to function '" << *FD << '\'';
1986 else
1987 os << "function call";
Ted Kremenekc887d132009-04-29 18:50:19 +00001988 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001989 else {
1990 assert(isa<ObjCMessageExpr>(S));
1991 // The message expression may have between written directly or as
1992 // a property access. Lazily determine which case we are looking at.
1993 os << (isPropertyAccess(S, N->getParentMap()) ? "Property" : "Method");
1994 }
1995
1996 if (CurrV.getObjKind() == RetEffect::CF) {
1997 os << " returns a Core Foundation object with a ";
1998 }
1999 else {
2000 assert (CurrV.getObjKind() == RetEffect::ObjC);
2001 os << " returns an Objective-C object with a ";
2002 }
2003
2004 if (CurrV.isOwned()) {
2005 os << "+1 retain count";
2006
2007 if (GCEnabled) {
2008 assert(CurrV.getObjKind() == RetEffect::CF);
2009 os << ". "
2010 "Core Foundation objects are not automatically garbage collected.";
2011 }
2012 }
2013 else {
2014 assert (CurrV.isNotOwned());
2015 os << "+0 retain count";
2016 }
Ted Kremenekc887d132009-04-29 18:50:19 +00002017 }
Mike Stump1eb44332009-09-09 15:08:12 +00002018
Anna Zaks220ac8c2011-09-15 01:08:34 +00002019 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
2020 N->getLocationContext());
Ted Kremenekc887d132009-04-29 18:50:19 +00002021 return new PathDiagnosticEventPiece(Pos, os.str());
2022 }
Mike Stump1eb44332009-09-09 15:08:12 +00002023
Ted Kremenekc887d132009-04-29 18:50:19 +00002024 // Gather up the effects that were performed on the object at this
2025 // program point
Chris Lattner5f9e2722011-07-23 10:55:15 +00002026 SmallVector<ArgEffect, 2> AEffects;
Mike Stump1eb44332009-09-09 15:08:12 +00002027
Jordy Roseec9ef852011-08-23 20:55:48 +00002028 const ExplodedNode *OrigNode = BRC.getNodeResolver().getOriginalNode(N);
2029 if (const RetainSummary *Summ = SummaryLog.lookup(OrigNode)) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002030 // We only have summaries attached to nodes after evaluating CallExpr and
2031 // ObjCMessageExprs.
Jordy Rosef53e8c72011-08-23 19:43:16 +00002032 const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
Mike Stump1eb44332009-09-09 15:08:12 +00002033
Ted Kremenek5f85e172009-07-22 22:35:28 +00002034 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002035 // Iterate through the parameter expressions and see if the symbol
2036 // was ever passed as an argument.
2037 unsigned i = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002038
Ted Kremenek5f85e172009-07-22 22:35:28 +00002039 for (CallExpr::const_arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
Ted Kremenekc887d132009-04-29 18:50:19 +00002040 AI!=AE; ++AI, ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002041
Ted Kremenekc887d132009-04-29 18:50:19 +00002042 // Retrieve the value of the argument. Is it the symbol
2043 // we are interested in?
Ted Kremenek5eca4822012-01-06 22:09:28 +00002044 if (CurrSt->getSValAsScalarOrLoc(*AI, LCtx).getAsLocSymbol() != Sym)
Ted Kremenekc887d132009-04-29 18:50:19 +00002045 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00002046
Ted Kremenekc887d132009-04-29 18:50:19 +00002047 // We have an argument. Get the effect!
2048 AEffects.push_back(Summ->getArg(i));
2049 }
2050 }
Mike Stump1eb44332009-09-09 15:08:12 +00002051 else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002052 if (const Expr *receiver = ME->getInstanceReceiver())
Ted Kremenek5eca4822012-01-06 22:09:28 +00002053 if (CurrSt->getSValAsScalarOrLoc(receiver, LCtx)
2054 .getAsLocSymbol() == Sym) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002055 // The symbol we are tracking is the receiver.
2056 AEffects.push_back(Summ->getReceiverEffect());
2057 }
2058 }
2059 }
Mike Stump1eb44332009-09-09 15:08:12 +00002060
Ted Kremenekc887d132009-04-29 18:50:19 +00002061 do {
2062 // Get the previous type state.
2063 RefVal PrevV = *PrevT;
Mike Stump1eb44332009-09-09 15:08:12 +00002064
Ted Kremenekc887d132009-04-29 18:50:19 +00002065 // Specially handle -dealloc.
Jordy Rose35c86952011-08-24 05:47:39 +00002066 if (!GCEnabled && contains(AEffects, Dealloc)) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002067 // Determine if the object's reference count was pushed to zero.
2068 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2069 // We may not have transitioned to 'release' if we hit an error.
2070 // This case is handled elsewhere.
2071 if (CurrV.getKind() == RefVal::Released) {
Ted Kremenekf21332e2009-05-08 20:01:42 +00002072 assert(CurrV.getCombinedCounts() == 0);
Ted Kremenekc887d132009-04-29 18:50:19 +00002073 os << "Object released by directly sending the '-dealloc' message";
2074 break;
2075 }
2076 }
Mike Stump1eb44332009-09-09 15:08:12 +00002077
Ted Kremenekc887d132009-04-29 18:50:19 +00002078 // Specially handle CFMakeCollectable and friends.
2079 if (contains(AEffects, MakeCollectable)) {
2080 // Get the name of the function.
Jordy Rosef53e8c72011-08-23 19:43:16 +00002081 const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
Ted Kremenek5eca4822012-01-06 22:09:28 +00002082 SVal X =
2083 CurrSt->getSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee(), LCtx);
Ted Kremenek9c378f72011-08-12 23:37:29 +00002084 const FunctionDecl *FD = X.getAsFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002085
Jordy Rose35c86952011-08-24 05:47:39 +00002086 if (GCEnabled) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002087 // Determine if the object's reference count was pushed to zero.
2088 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
Mike Stump1eb44332009-09-09 15:08:12 +00002089
Benjamin Kramerb8989f22011-10-14 18:45:37 +00002090 os << "In GC mode a call to '" << *FD
Ted Kremenekc887d132009-04-29 18:50:19 +00002091 << "' decrements an object's retain count and registers the "
2092 "object with the garbage collector. ";
Mike Stump1eb44332009-09-09 15:08:12 +00002093
Ted Kremenekc887d132009-04-29 18:50:19 +00002094 if (CurrV.getKind() == RefVal::Released) {
2095 assert(CurrV.getCount() == 0);
2096 os << "Since it now has a 0 retain count the object can be "
2097 "automatically collected by the garbage collector.";
2098 }
2099 else
2100 os << "An object must have a 0 retain count to be garbage collected. "
2101 "After this call its retain count is +" << CurrV.getCount()
2102 << '.';
2103 }
Mike Stump1eb44332009-09-09 15:08:12 +00002104 else
Benjamin Kramerb8989f22011-10-14 18:45:37 +00002105 os << "When GC is not enabled a call to '" << *FD
Ted Kremenekc887d132009-04-29 18:50:19 +00002106 << "' has no effect on its argument.";
Mike Stump1eb44332009-09-09 15:08:12 +00002107
Ted Kremenekc887d132009-04-29 18:50:19 +00002108 // Nothing more to say.
2109 break;
2110 }
Mike Stump1eb44332009-09-09 15:08:12 +00002111
2112 // Determine if the typestate has changed.
Ted Kremenekc887d132009-04-29 18:50:19 +00002113 if (!(PrevV == CurrV))
2114 switch (CurrV.getKind()) {
2115 case RefVal::Owned:
2116 case RefVal::NotOwned:
Mike Stump1eb44332009-09-09 15:08:12 +00002117
Ted Kremenekf21332e2009-05-08 20:01:42 +00002118 if (PrevV.getCount() == CurrV.getCount()) {
2119 // Did an autorelease message get sent?
2120 if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
2121 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002122
Zhongxing Xu264e9372009-05-12 10:10:00 +00002123 assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount());
Ted Kremenekeaedfea2009-05-10 05:11:21 +00002124 os << "Object sent -autorelease message";
Ted Kremenekf21332e2009-05-08 20:01:42 +00002125 break;
2126 }
Mike Stump1eb44332009-09-09 15:08:12 +00002127
Ted Kremenekc887d132009-04-29 18:50:19 +00002128 if (PrevV.getCount() > CurrV.getCount())
2129 os << "Reference count decremented.";
2130 else
2131 os << "Reference count incremented.";
Mike Stump1eb44332009-09-09 15:08:12 +00002132
Ted Kremenekc887d132009-04-29 18:50:19 +00002133 if (unsigned Count = CurrV.getCount())
2134 os << " The object now has a +" << Count << " retain count.";
Mike Stump1eb44332009-09-09 15:08:12 +00002135
Ted Kremenekc887d132009-04-29 18:50:19 +00002136 if (PrevV.getKind() == RefVal::Released) {
Jordy Rose35c86952011-08-24 05:47:39 +00002137 assert(GCEnabled && CurrV.getCount() > 0);
Jordy Rose74b7b2b2012-03-17 05:49:15 +00002138 os << " The object is not eligible for garbage collection until "
2139 "the retain count reaches 0 again.";
Ted Kremenekc887d132009-04-29 18:50:19 +00002140 }
Mike Stump1eb44332009-09-09 15:08:12 +00002141
Ted Kremenekc887d132009-04-29 18:50:19 +00002142 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002143
Ted Kremenekc887d132009-04-29 18:50:19 +00002144 case RefVal::Released:
2145 os << "Object released.";
2146 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002147
Ted Kremenekc887d132009-04-29 18:50:19 +00002148 case RefVal::ReturnedOwned:
Jordy Rose74b7b2b2012-03-17 05:49:15 +00002149 // Autoreleases can be applied after marking a node ReturnedOwned.
2150 if (CurrV.getAutoreleaseCount())
2151 return NULL;
2152
2153 os << "Object returned to caller as an owning reference (single "
2154 "retain count transferred to caller)";
Ted Kremenekc887d132009-04-29 18:50:19 +00002155 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002156
Ted Kremenekc887d132009-04-29 18:50:19 +00002157 case RefVal::ReturnedNotOwned:
Ted Kremenekf1365462011-05-26 18:45:44 +00002158 os << "Object returned to caller with a +0 retain count";
Ted Kremenekc887d132009-04-29 18:50:19 +00002159 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002160
Ted Kremenekc887d132009-04-29 18:50:19 +00002161 default:
2162 return NULL;
2163 }
Mike Stump1eb44332009-09-09 15:08:12 +00002164
Ted Kremenekc887d132009-04-29 18:50:19 +00002165 // Emit any remaining diagnostics for the argument effects (if any).
Chris Lattner5f9e2722011-07-23 10:55:15 +00002166 for (SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
Ted Kremenekc887d132009-04-29 18:50:19 +00002167 E=AEffects.end(); I != E; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +00002168
Ted Kremenekc887d132009-04-29 18:50:19 +00002169 // A bunch of things have alternate behavior under GC.
Jordy Rose35c86952011-08-24 05:47:39 +00002170 if (GCEnabled)
Ted Kremenekc887d132009-04-29 18:50:19 +00002171 switch (*I) {
2172 default: break;
2173 case Autorelease:
2174 os << "In GC mode an 'autorelease' has no effect.";
2175 continue;
2176 case IncRefMsg:
2177 os << "In GC mode the 'retain' message has no effect.";
2178 continue;
2179 case DecRefMsg:
2180 os << "In GC mode the 'release' message has no effect.";
2181 continue;
2182 }
2183 }
Mike Stump1eb44332009-09-09 15:08:12 +00002184 } while (0);
2185
Ted Kremenekc887d132009-04-29 18:50:19 +00002186 if (os.str().empty())
2187 return 0; // We have nothing to say!
Ted Kremenek2033a952009-05-13 07:12:33 +00002188
Jordy Rosef53e8c72011-08-23 19:43:16 +00002189 const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
Anna Zaks220ac8c2011-09-15 01:08:34 +00002190 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
2191 N->getLocationContext());
Ted Kremenek9c378f72011-08-12 23:37:29 +00002192 PathDiagnosticPiece *P = new PathDiagnosticEventPiece(Pos, os.str());
Mike Stump1eb44332009-09-09 15:08:12 +00002193
Ted Kremenekc887d132009-04-29 18:50:19 +00002194 // Add the range by scanning the children of the statement for any bindings
2195 // to Sym.
Mike Stump1eb44332009-09-09 15:08:12 +00002196 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
Ted Kremenek5f85e172009-07-22 22:35:28 +00002197 I!=E; ++I)
Ted Kremenek9c378f72011-08-12 23:37:29 +00002198 if (const Expr *Exp = dyn_cast_or_null<Expr>(*I))
Ted Kremenek5eca4822012-01-06 22:09:28 +00002199 if (CurrSt->getSValAsScalarOrLoc(Exp, LCtx).getAsLocSymbol() == Sym) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002200 P->addRange(Exp->getSourceRange());
2201 break;
2202 }
Mike Stump1eb44332009-09-09 15:08:12 +00002203
Ted Kremenekc887d132009-04-29 18:50:19 +00002204 return P;
2205}
2206
Anna Zakse7e01682012-02-28 22:39:22 +00002207// Find the first node in the current function context that referred to the
2208// tracked symbol and the memory location that value was stored to. Note, the
2209// value is only reported if the allocation occurred in the same function as
2210// the leak.
Zhongxing Xuc5619d92009-08-06 01:32:16 +00002211static std::pair<const ExplodedNode*,const MemRegion*>
Ted Kremenek18c66fd2011-08-15 22:09:50 +00002212GetAllocationSite(ProgramStateManager& StateMgr, const ExplodedNode *N,
Ted Kremenekc887d132009-04-29 18:50:19 +00002213 SymbolRef Sym) {
Ted Kremenek9c378f72011-08-12 23:37:29 +00002214 const ExplodedNode *Last = N;
Mike Stump1eb44332009-09-09 15:08:12 +00002215 const MemRegion* FirstBinding = 0;
Anna Zakse7e01682012-02-28 22:39:22 +00002216 const LocationContext *LeakContext = N->getLocationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002217
Ted Kremenekc887d132009-04-29 18:50:19 +00002218 while (N) {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002219 ProgramStateRef St = N->getState();
Ted Kremenekc887d132009-04-29 18:50:19 +00002220 RefBindings B = St->get<RefBindings>();
Mike Stump1eb44332009-09-09 15:08:12 +00002221
Ted Kremenekc887d132009-04-29 18:50:19 +00002222 if (!B.lookup(Sym))
2223 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002224
Anna Zaks27b867e2012-03-21 19:45:01 +00002225 StoreManager::FindUniqueBinding FB(Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002226 StateMgr.iterBindings(St, FB);
2227 if (FB) FirstBinding = FB.getRegion();
2228
Anna Zakse7e01682012-02-28 22:39:22 +00002229 // Allocation node, is the last node in the current context in which the
2230 // symbol was tracked.
2231 if (N->getLocationContext() == LeakContext)
2232 Last = N;
2233
Mike Stump1eb44332009-09-09 15:08:12 +00002234 N = N->pred_empty() ? NULL : *(N->pred_begin());
Ted Kremenekc887d132009-04-29 18:50:19 +00002235 }
Mike Stump1eb44332009-09-09 15:08:12 +00002236
Anna Zakse7e01682012-02-28 22:39:22 +00002237 // If allocation happened in a function different from the leak node context,
2238 // do not report the binding.
2239 if (N->getLocationContext() != LeakContext) {
2240 FirstBinding = 0;
2241 }
2242
Ted Kremenekc887d132009-04-29 18:50:19 +00002243 return std::make_pair(Last, FirstBinding);
2244}
2245
2246PathDiagnosticPiece*
Anna Zaks23f395e2011-08-20 01:27:22 +00002247CFRefReportVisitor::getEndPath(BugReporterContext &BRC,
2248 const ExplodedNode *EndN,
2249 BugReport &BR) {
Ted Kremenek76aadc32012-03-09 01:13:14 +00002250 BR.markInteresting(Sym);
Anna Zaks23f395e2011-08-20 01:27:22 +00002251 return BugReporterVisitor::getDefaultEndPath(BRC, EndN, BR);
Ted Kremenekc887d132009-04-29 18:50:19 +00002252}
2253
2254PathDiagnosticPiece*
Anna Zaks23f395e2011-08-20 01:27:22 +00002255CFRefLeakReportVisitor::getEndPath(BugReporterContext &BRC,
2256 const ExplodedNode *EndN,
2257 BugReport &BR) {
Mike Stump1eb44332009-09-09 15:08:12 +00002258
Ted Kremenek8966bc12009-05-06 21:39:49 +00002259 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenekc887d132009-04-29 18:50:19 +00002260 // assigned to different variables, etc.
Ted Kremenek76aadc32012-03-09 01:13:14 +00002261 BR.markInteresting(Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002262
Ted Kremenekc887d132009-04-29 18:50:19 +00002263 // We are reporting a leak. Walk up the graph to get to the first node where
2264 // the symbol appeared, and also get the first VarDecl that tracked object
2265 // is stored to.
Ted Kremenek9c378f72011-08-12 23:37:29 +00002266 const ExplodedNode *AllocNode = 0;
Ted Kremenekc887d132009-04-29 18:50:19 +00002267 const MemRegion* FirstBinding = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002268
Ted Kremenekc887d132009-04-29 18:50:19 +00002269 llvm::tie(AllocNode, FirstBinding) =
Ted Kremenekf04dced2009-05-08 23:32:51 +00002270 GetAllocationSite(BRC.getStateManager(), EndN, Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002271
Anna Zaks4fdf97b2011-09-15 18:56:07 +00002272 SourceManager& SM = BRC.getSourceManager();
Mike Stump1eb44332009-09-09 15:08:12 +00002273
Ted Kremenekc887d132009-04-29 18:50:19 +00002274 // Compute an actual location for the leak. Sometimes a leak doesn't
2275 // occur at an actual statement (e.g., transition between blocks; end
2276 // of function) so we need to walk the graph and compute a real location.
Ted Kremenek9c378f72011-08-12 23:37:29 +00002277 const ExplodedNode *LeakN = EndN;
Anna Zaks4fdf97b2011-09-15 18:56:07 +00002278 PathDiagnosticLocation L = PathDiagnosticLocation::createEndOfPath(LeakN, SM);
Mike Stump1eb44332009-09-09 15:08:12 +00002279
Ted Kremenekc887d132009-04-29 18:50:19 +00002280 std::string sbuf;
2281 llvm::raw_string_ostream os(sbuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002282
Ted Kremenekf1365462011-05-26 18:45:44 +00002283 os << "Object leaked: ";
Mike Stump1eb44332009-09-09 15:08:12 +00002284
Ted Kremenekf1365462011-05-26 18:45:44 +00002285 if (FirstBinding) {
2286 os << "object allocated and stored into '"
2287 << FirstBinding->getString() << '\'';
2288 }
2289 else
2290 os << "allocated object";
Mike Stump1eb44332009-09-09 15:08:12 +00002291
Ted Kremenekc887d132009-04-29 18:50:19 +00002292 // Get the retain count.
2293 const RefVal* RV = EndN->getState()->get<RefBindings>(Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002294
Ted Kremenekc887d132009-04-29 18:50:19 +00002295 if (RV->getKind() == RefVal::ErrorLeakReturned) {
2296 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
Jordy Rose5b5402b2011-07-15 22:17:54 +00002297 // objects. Only "copy", "alloc", "retain" and "new" transfer ownership
Ted Kremenekc887d132009-04-29 18:50:19 +00002298 // to the caller for NS objects.
Ted Kremenekd368d712011-05-25 06:19:45 +00002299 const Decl *D = &EndN->getCodeDecl();
2300 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2301 os << " is returned from a method whose name ('"
2302 << MD->getSelector().getAsString()
2303 << "') does not start with 'copy', 'mutableCopy', 'alloc' or 'new'."
Jordy Rose5b5402b2011-07-15 22:17:54 +00002304 " This violates the naming convention rules"
Ted Kremenekf1365462011-05-26 18:45:44 +00002305 " given in the Memory Management Guide for Cocoa";
Ted Kremenekd368d712011-05-25 06:19:45 +00002306 }
2307 else {
2308 const FunctionDecl *FD = cast<FunctionDecl>(D);
Ted Kremenekb7dcddf2011-12-22 06:35:52 +00002309 os << " is returned from a function whose name ('"
Benjamin Kramera59d20b2012-02-07 11:57:57 +00002310 << *FD
Ted Kremenekd368d712011-05-25 06:19:45 +00002311 << "') does not contain 'Copy' or 'Create'. This violates the naming"
Ted Kremenekb7dcddf2011-12-22 06:35:52 +00002312 " convention rules given in the Memory Management Guide for Core"
Ted Kremenekf1365462011-05-26 18:45:44 +00002313 " Foundation";
Ted Kremenekd368d712011-05-25 06:19:45 +00002314 }
Ted Kremenekc887d132009-04-29 18:50:19 +00002315 }
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002316 else if (RV->getKind() == RefVal::ErrorGCLeakReturned) {
Ted Kremenek9c378f72011-08-12 23:37:29 +00002317 ObjCMethodDecl &MD = cast<ObjCMethodDecl>(EndN->getCodeDecl());
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002318 os << " and returned from method '" << MD.getSelector().getAsString()
Ted Kremenek82f2be52009-05-10 16:52:15 +00002319 << "' is potentially leaked when using garbage collection. Callers "
2320 "of this method do not expect a returned object with a +1 retain "
2321 "count since they expect the object to be managed by the garbage "
2322 "collector";
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002323 }
Ted Kremenekc887d132009-04-29 18:50:19 +00002324 else
Ted Kremenekabf517c2010-10-15 22:50:23 +00002325 os << " is not referenced later in this execution path and has a retain "
Ted Kremenekf1365462011-05-26 18:45:44 +00002326 "count of +" << RV->getCount();
Mike Stump1eb44332009-09-09 15:08:12 +00002327
Ted Kremenekc887d132009-04-29 18:50:19 +00002328 return new PathDiagnosticEventPiece(L, os.str());
2329}
2330
Jordy Rose20589562011-08-24 22:39:09 +00002331CFRefLeakReport::CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts,
2332 bool GCEnabled, const SummaryLogTy &Log,
2333 ExplodedNode *n, SymbolRef sym,
Anna Zaks6a93bd52011-10-25 19:57:11 +00002334 CheckerContext &Ctx)
Jordy Rose20589562011-08-24 22:39:09 +00002335: CFRefReport(D, LOpts, GCEnabled, Log, n, sym, false) {
Mike Stump1eb44332009-09-09 15:08:12 +00002336
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00002337 // Most bug reports are cached at the location where they occurred.
Ted Kremenekc887d132009-04-29 18:50:19 +00002338 // With leaks, we want to unique them by the location where they were
2339 // allocated, and only report a single path. To do this, we need to find
2340 // the allocation site of a piece of tracked memory, which we do via a
2341 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2342 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2343 // that all ancestor nodes that represent the allocation site have the
2344 // same SourceLocation.
Ted Kremenek9c378f72011-08-12 23:37:29 +00002345 const ExplodedNode *AllocNode = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002346
Anna Zaks6a93bd52011-10-25 19:57:11 +00002347 const SourceManager& SMgr = Ctx.getSourceManager();
Anna Zaks590dd8e2011-09-20 21:38:35 +00002348
Ted Kremenekc887d132009-04-29 18:50:19 +00002349 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding.
Anna Zaks6a93bd52011-10-25 19:57:11 +00002350 GetAllocationSite(Ctx.getStateManager(), getErrorNode(), sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002351
Ted Kremenekc887d132009-04-29 18:50:19 +00002352 // Get the SourceLocation for the allocation site.
2353 ProgramPoint P = AllocNode->getLocation();
Anna Zaks590dd8e2011-09-20 21:38:35 +00002354 const Stmt *AllocStmt = cast<PostStmt>(P).getStmt();
2355 Location = PathDiagnosticLocation::createBegin(AllocStmt, SMgr,
2356 n->getLocationContext());
Ted Kremenekc887d132009-04-29 18:50:19 +00002357 // Fill in the description of the bug.
2358 Description.clear();
2359 llvm::raw_string_ostream os(Description);
Ted Kremenekdd924e22009-05-02 19:05:19 +00002360 os << "Potential leak ";
Jordy Rose20589562011-08-24 22:39:09 +00002361 if (GCEnabled)
Ted Kremenekdd924e22009-05-02 19:05:19 +00002362 os << "(when using garbage collection) ";
Anna Zaks212000e2012-02-28 21:49:08 +00002363 os << "of an object";
Mike Stump1eb44332009-09-09 15:08:12 +00002364
Ted Kremenekc887d132009-04-29 18:50:19 +00002365 // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2366 if (AllocBinding)
Anna Zaks212000e2012-02-28 21:49:08 +00002367 os << " stored into '" << AllocBinding->getString() << '\'';
Anna Zaksdc757b02011-08-19 23:21:56 +00002368
Jordy Rose20589562011-08-24 22:39:09 +00002369 addVisitor(new CFRefLeakReportVisitor(sym, GCEnabled, Log));
Ted Kremenekc887d132009-04-29 18:50:19 +00002370}
2371
2372//===----------------------------------------------------------------------===//
2373// Main checker logic.
2374//===----------------------------------------------------------------------===//
2375
Ted Kremenekd593eb92009-11-25 22:17:44 +00002376namespace {
Jordy Rose910c4052011-09-02 06:44:22 +00002377class RetainCountChecker
Jordy Rose9c083b72011-08-24 18:56:32 +00002378 : public Checker< check::Bind,
Jordy Rose38f17d62011-08-23 19:01:07 +00002379 check::DeadSymbols,
Jordy Rose9c083b72011-08-24 18:56:32 +00002380 check::EndAnalysis,
Jordy Rose38f17d62011-08-23 19:01:07 +00002381 check::EndPath,
Jordy Rose67044292011-08-17 21:27:39 +00002382 check::PostStmt<BlockExpr>,
John McCallf85e1932011-06-15 23:02:42 +00002383 check::PostStmt<CastExpr>,
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002384 check::PostStmt<ObjCArrayLiteral>,
2385 check::PostStmt<ObjCDictionaryLiteral>,
Jordy Rose70fdbc32012-05-12 05:10:43 +00002386 check::PostStmt<ObjCBoxedExpr>,
Jordan Rosefe6a0112012-07-02 19:28:21 +00002387 check::PostCall,
Jordy Rosef53e8c72011-08-23 19:43:16 +00002388 check::PreStmt<ReturnStmt>,
Jordy Rose67044292011-08-17 21:27:39 +00002389 check::RegionChanges,
Jordy Rose76c506f2011-08-21 21:58:18 +00002390 eval::Assume,
2391 eval::Call > {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002392 mutable OwningPtr<CFRefBug> useAfterRelease, releaseNotOwned;
2393 mutable OwningPtr<CFRefBug> deallocGC, deallocNotOwned;
2394 mutable OwningPtr<CFRefBug> overAutorelease, returnNotOwnedForOwned;
2395 mutable OwningPtr<CFRefBug> leakWithinFunction, leakAtReturn;
2396 mutable OwningPtr<CFRefBug> leakWithinFunctionGC, leakAtReturnGC;
Jordy Rose38f17d62011-08-23 19:01:07 +00002397
2398 typedef llvm::DenseMap<SymbolRef, const SimpleProgramPointTag *> SymbolTagMap;
2399
2400 // This map is only used to ensure proper deletion of any allocated tags.
2401 mutable SymbolTagMap DeadSymbolTags;
2402
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002403 mutable OwningPtr<RetainSummaryManager> Summaries;
2404 mutable OwningPtr<RetainSummaryManager> SummariesGC;
Jordy Roseb6cfc092011-08-25 00:10:37 +00002405
Jordy Rosee0a5d322011-08-23 20:27:16 +00002406 mutable ARCounts::Factory ARCountFactory;
2407
Jordy Rose9c083b72011-08-24 18:56:32 +00002408 mutable SummaryLogTy SummaryLog;
2409 mutable bool ShouldResetSummaryLog;
2410
Jordy Rose2f9a66d2011-08-20 21:17:59 +00002411public:
Jordy Rose910c4052011-09-02 06:44:22 +00002412 RetainCountChecker() : ShouldResetSummaryLog(false) {}
Jordy Rose38f17d62011-08-23 19:01:07 +00002413
Jordy Rose910c4052011-09-02 06:44:22 +00002414 virtual ~RetainCountChecker() {
Jordy Rose38f17d62011-08-23 19:01:07 +00002415 DeleteContainerSeconds(DeadSymbolTags);
2416 }
2417
Jordy Rose9c083b72011-08-24 18:56:32 +00002418 void checkEndAnalysis(ExplodedGraph &G, BugReporter &BR,
2419 ExprEngine &Eng) const {
2420 // FIXME: This is a hack to make sure the summary log gets cleared between
2421 // analyses of different code bodies.
2422 //
2423 // Why is this necessary? Because a checker's lifetime is tied to a
2424 // translation unit, but an ExplodedGraph's lifetime is just a code body.
2425 // Once in a blue moon, a new ExplodedNode will have the same address as an
2426 // old one with an associated summary, and the bug report visitor gets very
2427 // confused. (To make things worse, the summary lifetime is currently also
2428 // tied to a code body, so we get a crash instead of incorrect results.)
Jordy Rose1ab51c72011-08-24 09:27:24 +00002429 //
2430 // Why is this a bad solution? Because if the lifetime of the ExplodedGraph
2431 // changes, things will start going wrong again. Really the lifetime of this
2432 // log needs to be tied to either the specific nodes in it or the entire
2433 // ExplodedGraph, not to a specific part of the code being analyzed.
2434 //
Jordy Rose9c083b72011-08-24 18:56:32 +00002435 // (Also, having stateful local data means that the same checker can't be
2436 // used from multiple threads, but a lot of checkers have incorrect
2437 // assumptions about that anyway. So that wasn't a priority at the time of
2438 // this fix.)
Jordy Rose1ab51c72011-08-24 09:27:24 +00002439 //
Jordy Rose9c083b72011-08-24 18:56:32 +00002440 // This happens at the end of analysis, but bug reports are emitted /after/
2441 // this point. So we can't just clear the summary log now. Instead, we mark
2442 // that the next time we access the summary log, it should be cleared.
2443
2444 // If we never reset the summary log during /this/ code body analysis,
2445 // there were no new summaries. There might still have been summaries from
2446 // the /last/ analysis, so clear them out to make sure the bug report
2447 // visitors don't get confused.
2448 if (ShouldResetSummaryLog)
2449 SummaryLog.clear();
2450
2451 ShouldResetSummaryLog = !SummaryLog.empty();
Jordy Rose1ab51c72011-08-24 09:27:24 +00002452 }
2453
Jordy Rose17a38e22011-09-02 05:55:19 +00002454 CFRefBug *getLeakWithinFunctionBug(const LangOptions &LOpts,
2455 bool GCEnabled) const {
2456 if (GCEnabled) {
Jordy Rosedb92bb62011-08-25 01:14:38 +00002457 if (!leakWithinFunctionGC)
Benjamin Kramerfacde172012-06-06 17:32:50 +00002458 leakWithinFunctionGC.reset(new Leak("Leak of object when using "
2459 "garbage collection"));
Jordy Rose17a38e22011-09-02 05:55:19 +00002460 return leakWithinFunctionGC.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002461 } else {
2462 if (!leakWithinFunction) {
Douglas Gregore289d812011-09-13 17:21:33 +00002463 if (LOpts.getGC() == LangOptions::HybridGC) {
Benjamin Kramerfacde172012-06-06 17:32:50 +00002464 leakWithinFunction.reset(new Leak("Leak of object when not using "
2465 "garbage collection (GC) in "
2466 "dual GC/non-GC code"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002467 } else {
Benjamin Kramerfacde172012-06-06 17:32:50 +00002468 leakWithinFunction.reset(new Leak("Leak"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002469 }
2470 }
Jordy Rose17a38e22011-09-02 05:55:19 +00002471 return leakWithinFunction.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002472 }
2473 }
2474
Jordy Rose17a38e22011-09-02 05:55:19 +00002475 CFRefBug *getLeakAtReturnBug(const LangOptions &LOpts, bool GCEnabled) const {
2476 if (GCEnabled) {
Jordy Rosedb92bb62011-08-25 01:14:38 +00002477 if (!leakAtReturnGC)
Benjamin Kramerfacde172012-06-06 17:32:50 +00002478 leakAtReturnGC.reset(new Leak("Leak of returned object when using "
2479 "garbage collection"));
Jordy Rose17a38e22011-09-02 05:55:19 +00002480 return leakAtReturnGC.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002481 } else {
2482 if (!leakAtReturn) {
Douglas Gregore289d812011-09-13 17:21:33 +00002483 if (LOpts.getGC() == LangOptions::HybridGC) {
Benjamin Kramerfacde172012-06-06 17:32:50 +00002484 leakAtReturn.reset(new Leak("Leak of returned object when not using "
2485 "garbage collection (GC) in dual "
2486 "GC/non-GC code"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002487 } else {
Benjamin Kramerfacde172012-06-06 17:32:50 +00002488 leakAtReturn.reset(new Leak("Leak of returned object"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002489 }
2490 }
Jordy Rose17a38e22011-09-02 05:55:19 +00002491 return leakAtReturn.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002492 }
2493 }
2494
Jordy Rose17a38e22011-09-02 05:55:19 +00002495 RetainSummaryManager &getSummaryManager(ASTContext &Ctx,
2496 bool GCEnabled) const {
2497 // FIXME: We don't support ARC being turned on and off during one analysis.
2498 // (nor, for that matter, do we support changing ASTContexts)
David Blaikie4e4d0842012-03-11 07:00:24 +00002499 bool ARCEnabled = (bool)Ctx.getLangOpts().ObjCAutoRefCount;
Jordy Rose17a38e22011-09-02 05:55:19 +00002500 if (GCEnabled) {
2501 if (!SummariesGC)
Jordy Roseb6cfc092011-08-25 00:10:37 +00002502 SummariesGC.reset(new RetainSummaryManager(Ctx, true, ARCEnabled));
Jordy Rose17a38e22011-09-02 05:55:19 +00002503 else
2504 assert(SummariesGC->isARCEnabled() == ARCEnabled);
Jordy Roseb6cfc092011-08-25 00:10:37 +00002505 return *SummariesGC;
2506 } else {
Jordy Rose17a38e22011-09-02 05:55:19 +00002507 if (!Summaries)
Jordy Roseb6cfc092011-08-25 00:10:37 +00002508 Summaries.reset(new RetainSummaryManager(Ctx, false, ARCEnabled));
Jordy Rose17a38e22011-09-02 05:55:19 +00002509 else
2510 assert(Summaries->isARCEnabled() == ARCEnabled);
Jordy Roseb6cfc092011-08-25 00:10:37 +00002511 return *Summaries;
2512 }
2513 }
2514
Jordy Rose17a38e22011-09-02 05:55:19 +00002515 RetainSummaryManager &getSummaryManager(CheckerContext &C) const {
2516 return getSummaryManager(C.getASTContext(), C.isObjCGCEnabled());
2517 }
2518
Ted Kremenek8bef8232012-01-26 21:29:00 +00002519 void printState(raw_ostream &Out, ProgramStateRef State,
Jordy Rosedbd658e2011-08-28 19:11:56 +00002520 const char *NL, const char *Sep) const;
2521
Anna Zaks390909c2011-10-06 00:43:15 +00002522 void checkBind(SVal loc, SVal val, const Stmt *S, CheckerContext &C) const;
Jordy Roseab027fd2011-08-20 21:16:58 +00002523 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
2524 void checkPostStmt(const CastExpr *CE, CheckerContext &C) const;
John McCallf85e1932011-06-15 23:02:42 +00002525
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002526 void checkPostStmt(const ObjCArrayLiteral *AL, CheckerContext &C) const;
2527 void checkPostStmt(const ObjCDictionaryLiteral *DL, CheckerContext &C) const;
Jordy Rose70fdbc32012-05-12 05:10:43 +00002528 void checkPostStmt(const ObjCBoxedExpr *BE, CheckerContext &C) const;
2529
Jordan Rosefe6a0112012-07-02 19:28:21 +00002530 void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002531
Jordan Rose4531b7d2012-07-02 19:27:43 +00002532 void checkSummary(const RetainSummary &Summ, const CallEvent &Call,
Jordy Rosee38dd952011-08-28 05:16:28 +00002533 CheckerContext &C) const;
Jordy Rose294396b2011-08-22 23:48:23 +00002534
Jordy Rose76c506f2011-08-21 21:58:18 +00002535 bool evalCall(const CallExpr *CE, CheckerContext &C) const;
2536
Ted Kremenek8bef8232012-01-26 21:29:00 +00002537 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Jordy Roseab027fd2011-08-20 21:16:58 +00002538 bool Assumption) const;
Jordy Rose67044292011-08-17 21:27:39 +00002539
Ted Kremenek8bef8232012-01-26 21:29:00 +00002540 ProgramStateRef
2541 checkRegionChanges(ProgramStateRef state,
Jordy Rose537716a2011-08-27 22:51:26 +00002542 const StoreManager::InvalidatedSymbols *invalidated,
2543 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00002544 ArrayRef<const MemRegion *> Regions,
Jordan Rose740d4902012-07-02 19:27:35 +00002545 const CallEvent *Call) const;
Jordy Roseab027fd2011-08-20 21:16:58 +00002546
Ted Kremenek8bef8232012-01-26 21:29:00 +00002547 bool wantsRegionChangeUpdate(ProgramStateRef state) const {
Jordy Rose2f9a66d2011-08-20 21:17:59 +00002548 return true;
Jordy Roseab027fd2011-08-20 21:16:58 +00002549 }
Jordy Rose294396b2011-08-22 23:48:23 +00002550
Jordy Rosef53e8c72011-08-23 19:43:16 +00002551 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
2552 void checkReturnWithRetEffect(const ReturnStmt *S, CheckerContext &C,
2553 ExplodedNode *Pred, RetEffect RE, RefVal X,
Ted Kremenek8bef8232012-01-26 21:29:00 +00002554 SymbolRef Sym, ProgramStateRef state) const;
Jordy Rosef53e8c72011-08-23 19:43:16 +00002555
Jordy Rose38f17d62011-08-23 19:01:07 +00002556 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Anna Zaksaf498a22011-10-25 19:56:48 +00002557 void checkEndPath(CheckerContext &C) const;
Jordy Rose38f17d62011-08-23 19:01:07 +00002558
Ted Kremenek8bef8232012-01-26 21:29:00 +00002559 ProgramStateRef updateSymbol(ProgramStateRef state, SymbolRef sym,
Jordy Rose17a38e22011-09-02 05:55:19 +00002560 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
2561 CheckerContext &C) const;
Jordy Rosee0a5d322011-08-23 20:27:16 +00002562
Ted Kremenek8bef8232012-01-26 21:29:00 +00002563 void processNonLeakError(ProgramStateRef St, SourceRange ErrorRange,
Jordy Rose294396b2011-08-22 23:48:23 +00002564 RefVal::Kind ErrorKind, SymbolRef Sym,
2565 CheckerContext &C) const;
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002566
2567 void processObjCLiterals(CheckerContext &C, const Expr *Ex) const;
Jordy Rose294396b2011-08-22 23:48:23 +00002568
Jordy Rose38f17d62011-08-23 19:01:07 +00002569 const ProgramPointTag *getDeadSymbolTag(SymbolRef sym) const;
2570
Ted Kremenek8bef8232012-01-26 21:29:00 +00002571 ProgramStateRef handleSymbolDeath(ProgramStateRef state,
Jordy Rose38f17d62011-08-23 19:01:07 +00002572 SymbolRef sid, RefVal V,
2573 SmallVectorImpl<SymbolRef> &Leaked) const;
2574
Ted Kremenek8bef8232012-01-26 21:29:00 +00002575 std::pair<ExplodedNode *, ProgramStateRef >
2576 handleAutoreleaseCounts(ProgramStateRef state,
Jordy Rose8d228632011-08-23 20:07:14 +00002577 GenericNodeBuilderRefCount Bd, ExplodedNode *Pred,
Anna Zaks6a93bd52011-10-25 19:57:11 +00002578 CheckerContext &Ctx, SymbolRef Sym, RefVal V) const;
Jordy Rose8d228632011-08-23 20:07:14 +00002579
Ted Kremenek8bef8232012-01-26 21:29:00 +00002580 ExplodedNode *processLeaks(ProgramStateRef state,
Jordy Rose38f17d62011-08-23 19:01:07 +00002581 SmallVectorImpl<SymbolRef> &Leaked,
2582 GenericNodeBuilderRefCount &Builder,
Anna Zaks6a93bd52011-10-25 19:57:11 +00002583 CheckerContext &Ctx,
Jordy Rose38f17d62011-08-23 19:01:07 +00002584 ExplodedNode *Pred = 0) const;
Ted Kremenekd593eb92009-11-25 22:17:44 +00002585};
2586} // end anonymous namespace
2587
Jordy Rose67044292011-08-17 21:27:39 +00002588namespace {
2589class StopTrackingCallback : public SymbolVisitor {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002590 ProgramStateRef state;
Jordy Rose67044292011-08-17 21:27:39 +00002591public:
Ted Kremenek8bef8232012-01-26 21:29:00 +00002592 StopTrackingCallback(ProgramStateRef st) : state(st) {}
2593 ProgramStateRef getState() const { return state; }
Jordy Rose67044292011-08-17 21:27:39 +00002594
2595 bool VisitSymbol(SymbolRef sym) {
2596 state = state->remove<RefBindings>(sym);
2597 return true;
2598 }
2599};
2600} // end anonymous namespace
2601
Jordy Rose910c4052011-09-02 06:44:22 +00002602//===----------------------------------------------------------------------===//
2603// Handle statements that may have an effect on refcounts.
2604//===----------------------------------------------------------------------===//
Jordy Rose67044292011-08-17 21:27:39 +00002605
Jordy Rose910c4052011-09-02 06:44:22 +00002606void RetainCountChecker::checkPostStmt(const BlockExpr *BE,
2607 CheckerContext &C) const {
Jordy Rose67044292011-08-17 21:27:39 +00002608
Jordy Rose910c4052011-09-02 06:44:22 +00002609 // Scan the BlockDecRefExprs for any object the retain count checker
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002610 // may be tracking.
John McCall469a1eb2011-02-02 13:00:07 +00002611 if (!BE->getBlockDecl()->hasCaptures())
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002612 return;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002613
Ted Kremenek8bef8232012-01-26 21:29:00 +00002614 ProgramStateRef state = C.getState();
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002615 const BlockDataRegion *R =
Ted Kremenek5eca4822012-01-06 22:09:28 +00002616 cast<BlockDataRegion>(state->getSVal(BE,
2617 C.getLocationContext()).getAsRegion());
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002618
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002619 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
2620 E = R->referenced_vars_end();
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002621
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002622 if (I == E)
2623 return;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002624
Ted Kremenek67d12872009-12-07 22:05:27 +00002625 // FIXME: For now we invalidate the tracking of all symbols passed to blocks
2626 // via captured variables, even though captured variables result in a copy
2627 // and in implicit increment/decrement of a retain count.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002628 SmallVector<const MemRegion*, 10> Regions;
Anna Zaks39ac1872011-10-26 21:06:44 +00002629 const LocationContext *LC = C.getLocationContext();
Ted Kremenekc8413fd2010-12-02 07:49:45 +00002630 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002631
Ted Kremenek67d12872009-12-07 22:05:27 +00002632 for ( ; I != E; ++I) {
2633 const VarRegion *VR = *I;
2634 if (VR->getSuperRegion() == R) {
2635 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2636 }
2637 Regions.push_back(VR);
2638 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002639
Ted Kremenek67d12872009-12-07 22:05:27 +00002640 state =
2641 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
2642 Regions.data() + Regions.size()).getState();
Anna Zaks0bd6b112011-10-26 21:06:34 +00002643 C.addTransition(state);
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002644}
2645
Jordy Rose910c4052011-09-02 06:44:22 +00002646void RetainCountChecker::checkPostStmt(const CastExpr *CE,
2647 CheckerContext &C) const {
John McCallf85e1932011-06-15 23:02:42 +00002648 const ObjCBridgedCastExpr *BE = dyn_cast<ObjCBridgedCastExpr>(CE);
2649 if (!BE)
2650 return;
2651
John McCall71c482c2011-06-17 06:50:50 +00002652 ArgEffect AE = IncRef;
John McCallf85e1932011-06-15 23:02:42 +00002653
2654 switch (BE->getBridgeKind()) {
2655 case clang::OBC_Bridge:
2656 // Do nothing.
2657 return;
2658 case clang::OBC_BridgeRetained:
2659 AE = IncRef;
2660 break;
2661 case clang::OBC_BridgeTransfer:
2662 AE = DecRefBridgedTransfered;
2663 break;
2664 }
2665
Ted Kremenek8bef8232012-01-26 21:29:00 +00002666 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00002667 SymbolRef Sym = state->getSVal(CE, C.getLocationContext()).getAsLocSymbol();
John McCallf85e1932011-06-15 23:02:42 +00002668 if (!Sym)
2669 return;
2670 const RefVal* T = state->get<RefBindings>(Sym);
2671 if (!T)
2672 return;
2673
John McCallf85e1932011-06-15 23:02:42 +00002674 RefVal::Kind hasErr = (RefVal::Kind) 0;
Jordy Rose17a38e22011-09-02 05:55:19 +00002675 state = updateSymbol(state, Sym, *T, AE, hasErr, C);
John McCallf85e1932011-06-15 23:02:42 +00002676
2677 if (hasErr) {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002678 // FIXME: If we get an error during a bridge cast, should we report it?
2679 // Should we assert that there is no error?
John McCallf85e1932011-06-15 23:02:42 +00002680 return;
2681 }
2682
Anna Zaks0bd6b112011-10-26 21:06:34 +00002683 C.addTransition(state);
John McCallf85e1932011-06-15 23:02:42 +00002684}
2685
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002686void RetainCountChecker::processObjCLiterals(CheckerContext &C,
2687 const Expr *Ex) const {
2688 ProgramStateRef state = C.getState();
2689 const ExplodedNode *pred = C.getPredecessor();
2690 for (Stmt::const_child_iterator it = Ex->child_begin(), et = Ex->child_end() ;
2691 it != et ; ++it) {
2692 const Stmt *child = *it;
2693 SVal V = state->getSVal(child, pred->getLocationContext());
2694 if (SymbolRef sym = V.getAsSymbol())
2695 if (const RefVal* T = state->get<RefBindings>(sym)) {
2696 RefVal::Kind hasErr = (RefVal::Kind) 0;
2697 state = updateSymbol(state, sym, *T, MayEscape, hasErr, C);
2698 if (hasErr) {
2699 processNonLeakError(state, child->getSourceRange(), hasErr, sym, C);
2700 return;
2701 }
2702 }
2703 }
2704
2705 // Return the object as autoreleased.
2706 // RetEffect RE = RetEffect::MakeNotOwned(RetEffect::ObjC);
2707 if (SymbolRef sym =
2708 state->getSVal(Ex, pred->getLocationContext()).getAsSymbol()) {
2709 QualType ResultTy = Ex->getType();
2710 state = state->set<RefBindings>(sym, RefVal::makeNotOwned(RetEffect::ObjC,
2711 ResultTy));
2712 }
2713
2714 C.addTransition(state);
2715}
2716
2717void RetainCountChecker::checkPostStmt(const ObjCArrayLiteral *AL,
2718 CheckerContext &C) const {
2719 // Apply the 'MayEscape' to all values.
2720 processObjCLiterals(C, AL);
2721}
2722
2723void RetainCountChecker::checkPostStmt(const ObjCDictionaryLiteral *DL,
2724 CheckerContext &C) const {
2725 // Apply the 'MayEscape' to all keys and values.
2726 processObjCLiterals(C, DL);
2727}
2728
Jordy Rose70fdbc32012-05-12 05:10:43 +00002729void RetainCountChecker::checkPostStmt(const ObjCBoxedExpr *Ex,
2730 CheckerContext &C) const {
2731 const ExplodedNode *Pred = C.getPredecessor();
2732 const LocationContext *LCtx = Pred->getLocationContext();
2733 ProgramStateRef State = Pred->getState();
2734
2735 if (SymbolRef Sym = State->getSVal(Ex, LCtx).getAsSymbol()) {
2736 QualType ResultTy = Ex->getType();
2737 State = State->set<RefBindings>(Sym, RefVal::makeNotOwned(RetEffect::ObjC,
2738 ResultTy));
2739 }
2740
2741 C.addTransition(State);
2742}
2743
Jordan Rosefe6a0112012-07-02 19:28:21 +00002744void RetainCountChecker::checkPostCall(const CallEvent &Call,
2745 CheckerContext &C) const {
2746 if (C.wasInlined)
2747 return;
Jordy Roseb6cfc092011-08-25 00:10:37 +00002748
Jordan Rosefe6a0112012-07-02 19:28:21 +00002749 RetainSummaryManager &Summaries = getSummaryManager(C);
2750 const RetainSummary *Summ = Summaries.getSummary(Call, C.getState());
2751 checkSummary(*Summ, Call, C);
Jordy Rose294396b2011-08-22 23:48:23 +00002752}
2753
Jordy Rose910c4052011-09-02 06:44:22 +00002754/// GetReturnType - Used to get the return type of a message expression or
2755/// function call with the intention of affixing that type to a tracked symbol.
2756/// While the the return type can be queried directly from RetEx, when
2757/// invoking class methods we augment to the return type to be that of
2758/// a pointer to the class (as opposed it just being id).
2759// FIXME: We may be able to do this with related result types instead.
2760// This function is probably overestimating.
2761static QualType GetReturnType(const Expr *RetE, ASTContext &Ctx) {
2762 QualType RetTy = RetE->getType();
2763 // If RetE is not a message expression just return its type.
2764 // If RetE is a message expression, return its types if it is something
2765 /// more specific than id.
2766 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RetE))
2767 if (const ObjCObjectPointerType *PT = RetTy->getAs<ObjCObjectPointerType>())
2768 if (PT->isObjCQualifiedIdType() || PT->isObjCIdType() ||
2769 PT->isObjCClassType()) {
2770 // At this point we know the return type of the message expression is
2771 // id, id<...>, or Class. If we have an ObjCInterfaceDecl, we know this
2772 // is a call to a class method whose type we can resolve. In such
2773 // cases, promote the return type to XXX* (where XXX is the class).
2774 const ObjCInterfaceDecl *D = ME->getReceiverInterface();
2775 return !D ? RetTy :
2776 Ctx.getObjCObjectPointerType(Ctx.getObjCInterfaceType(D));
2777 }
2778
2779 return RetTy;
2780}
2781
2782void RetainCountChecker::checkSummary(const RetainSummary &Summ,
Jordan Rose4531b7d2012-07-02 19:27:43 +00002783 const CallEvent &CallOrMsg,
Jordy Rose910c4052011-09-02 06:44:22 +00002784 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002785 ProgramStateRef state = C.getState();
Jordy Rose294396b2011-08-22 23:48:23 +00002786
2787 // Evaluate the effect of the arguments.
2788 RefVal::Kind hasErr = (RefVal::Kind) 0;
2789 SourceRange ErrorRange;
2790 SymbolRef ErrorSym = 0;
2791
2792 for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
Jordy Rose537716a2011-08-27 22:51:26 +00002793 SVal V = CallOrMsg.getArgSVal(idx);
Jordy Rose294396b2011-08-22 23:48:23 +00002794
2795 if (SymbolRef Sym = V.getAsLocSymbol()) {
2796 if (RefBindings::data_type *T = state->get<RefBindings>(Sym)) {
Jordy Rose17a38e22011-09-02 05:55:19 +00002797 state = updateSymbol(state, Sym, *T, Summ.getArg(idx), hasErr, C);
Jordy Rose294396b2011-08-22 23:48:23 +00002798 if (hasErr) {
2799 ErrorRange = CallOrMsg.getArgSourceRange(idx);
2800 ErrorSym = Sym;
2801 break;
2802 }
2803 }
2804 }
2805 }
2806
2807 // Evaluate the effect on the message receiver.
2808 bool ReceiverIsTracked = false;
Jordan Rose4531b7d2012-07-02 19:27:43 +00002809 if (!hasErr) {
Jordan Rosecde8cdb2012-07-02 19:27:56 +00002810 const ObjCMethodCall *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg);
Jordan Rose4531b7d2012-07-02 19:27:43 +00002811 if (MsgInvocation) {
2812 if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
2813 if (const RefVal *T = state->get<RefBindings>(Sym)) {
2814 ReceiverIsTracked = true;
2815 state = updateSymbol(state, Sym, *T, Summ.getReceiverEffect(),
2816 hasErr, C);
2817 if (hasErr) {
2818 ErrorRange = MsgInvocation->getReceiverSourceRange();
2819 ErrorSym = Sym;
2820 }
Jordy Rose294396b2011-08-22 23:48:23 +00002821 }
2822 }
2823 }
2824 }
2825
2826 // Process any errors.
2827 if (hasErr) {
2828 processNonLeakError(state, ErrorRange, hasErr, ErrorSym, C);
2829 return;
2830 }
2831
2832 // Consult the summary for the return value.
2833 RetEffect RE = Summ.getRetEffect();
2834
2835 if (RE.getKind() == RetEffect::OwnedWhenTrackedReceiver) {
Jordy Roseb6cfc092011-08-25 00:10:37 +00002836 if (ReceiverIsTracked)
Jordy Rose17a38e22011-09-02 05:55:19 +00002837 RE = getSummaryManager(C).getObjAllocRetEffect();
Jordy Roseb6cfc092011-08-25 00:10:37 +00002838 else
Jordy Rose294396b2011-08-22 23:48:23 +00002839 RE = RetEffect::MakeNoRet();
2840 }
2841
2842 switch (RE.getKind()) {
2843 default:
David Blaikie7530c032012-01-17 06:56:22 +00002844 llvm_unreachable("Unhandled RetEffect.");
Jordy Rose294396b2011-08-22 23:48:23 +00002845
2846 case RetEffect::NoRet:
2847 // No work necessary.
2848 break;
2849
2850 case RetEffect::OwnedAllocatedSymbol:
2851 case RetEffect::OwnedSymbol: {
Ted Kremenek5eca4822012-01-06 22:09:28 +00002852 SymbolRef Sym = state->getSVal(CallOrMsg.getOriginExpr(),
2853 C.getLocationContext()).getAsSymbol();
Jordy Rose294396b2011-08-22 23:48:23 +00002854 if (!Sym)
2855 break;
2856
Jordan Rose4531b7d2012-07-02 19:27:43 +00002857 // Use the result type from the CallEvent as it automatically adjusts
Jordy Rose294396b2011-08-22 23:48:23 +00002858 // for methods/functions that return references.
Jordan Rose4531b7d2012-07-02 19:27:43 +00002859 QualType ResultTy = CallOrMsg.getResultType();
Jordy Rose294396b2011-08-22 23:48:23 +00002860 state = state->set<RefBindings>(Sym, RefVal::makeOwned(RE.getObjKind(),
2861 ResultTy));
2862
2863 // FIXME: Add a flag to the checker where allocations are assumed to
2864 // *not* fail. (The code below is out-of-date, though.)
2865#if 0
2866 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) {
2867 bool isFeasible;
2868 state = state.assume(loc::SymbolVal(Sym), true, isFeasible);
2869 assert(isFeasible && "Cannot assume fresh symbol is non-null.");
2870 }
2871#endif
2872
2873 break;
2874 }
2875
2876 case RetEffect::GCNotOwnedSymbol:
2877 case RetEffect::ARCNotOwnedSymbol:
2878 case RetEffect::NotOwnedSymbol: {
2879 const Expr *Ex = CallOrMsg.getOriginExpr();
Ted Kremenek5eca4822012-01-06 22:09:28 +00002880 SymbolRef Sym = state->getSVal(Ex, C.getLocationContext()).getAsSymbol();
Jordy Rose294396b2011-08-22 23:48:23 +00002881 if (!Sym)
2882 break;
2883
2884 // Use GetReturnType in order to give [NSFoo alloc] the type NSFoo *.
2885 QualType ResultTy = GetReturnType(Ex, C.getASTContext());
2886 state = state->set<RefBindings>(Sym, RefVal::makeNotOwned(RE.getObjKind(),
2887 ResultTy));
2888 break;
2889 }
2890 }
2891
2892 // This check is actually necessary; otherwise the statement builder thinks
2893 // we've hit a previously-found path.
2894 // Normally addTransition takes care of this, but we want the node pointer.
2895 ExplodedNode *NewNode;
2896 if (state == C.getState()) {
2897 NewNode = C.getPredecessor();
2898 } else {
Anna Zaks0bd6b112011-10-26 21:06:34 +00002899 NewNode = C.addTransition(state);
Jordy Rose294396b2011-08-22 23:48:23 +00002900 }
2901
Jordy Rose9c083b72011-08-24 18:56:32 +00002902 // Annotate the node with summary we used.
2903 if (NewNode) {
2904 // FIXME: This is ugly. See checkEndAnalysis for why it's necessary.
2905 if (ShouldResetSummaryLog) {
2906 SummaryLog.clear();
2907 ShouldResetSummaryLog = false;
2908 }
Jordy Roseec9ef852011-08-23 20:55:48 +00002909 SummaryLog[NewNode] = &Summ;
Jordy Rose9c083b72011-08-24 18:56:32 +00002910 }
Jordy Rose294396b2011-08-22 23:48:23 +00002911}
2912
Jordy Rosee0a5d322011-08-23 20:27:16 +00002913
Ted Kremenek8bef8232012-01-26 21:29:00 +00002914ProgramStateRef
2915RetainCountChecker::updateSymbol(ProgramStateRef state, SymbolRef sym,
Jordy Rose910c4052011-09-02 06:44:22 +00002916 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
2917 CheckerContext &C) const {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002918 // In GC mode [... release] and [... retain] do nothing.
Jordy Rose910c4052011-09-02 06:44:22 +00002919 // In ARC mode they shouldn't exist at all, but we just ignore them.
Jordy Rose17a38e22011-09-02 05:55:19 +00002920 bool IgnoreRetainMsg = C.isObjCGCEnabled();
2921 if (!IgnoreRetainMsg)
David Blaikie4e4d0842012-03-11 07:00:24 +00002922 IgnoreRetainMsg = (bool)C.getASTContext().getLangOpts().ObjCAutoRefCount;
Jordy Rose17a38e22011-09-02 05:55:19 +00002923
Jordy Rosee0a5d322011-08-23 20:27:16 +00002924 switch (E) {
Jordan Rose4531b7d2012-07-02 19:27:43 +00002925 default:
2926 break;
2927 case IncRefMsg:
2928 E = IgnoreRetainMsg ? DoNothing : IncRef;
2929 break;
2930 case DecRefMsg:
2931 E = IgnoreRetainMsg ? DoNothing : DecRef;
2932 break;
2933 case DecRefMsgAndStopTracking:
2934 E = IgnoreRetainMsg ? StopTracking : DecRefAndStopTracking;
2935 break;
2936 case MakeCollectable:
2937 E = C.isObjCGCEnabled() ? DecRef : DoNothing;
2938 break;
2939 case NewAutoreleasePool:
2940 E = C.isObjCGCEnabled() ? DoNothing : NewAutoreleasePool;
2941 break;
Jordy Rosee0a5d322011-08-23 20:27:16 +00002942 }
2943
2944 // Handle all use-after-releases.
Jordy Rose17a38e22011-09-02 05:55:19 +00002945 if (!C.isObjCGCEnabled() && V.getKind() == RefVal::Released) {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002946 V = V ^ RefVal::ErrorUseAfterRelease;
2947 hasErr = V.getKind();
2948 return state->set<RefBindings>(sym, V);
2949 }
2950
2951 switch (E) {
2952 case DecRefMsg:
2953 case IncRefMsg:
2954 case MakeCollectable:
Jordan Rose4531b7d2012-07-02 19:27:43 +00002955 case DecRefMsgAndStopTracking:
Jordy Rosee0a5d322011-08-23 20:27:16 +00002956 llvm_unreachable("DecRefMsg/IncRefMsg/MakeCollectable already converted");
Jordy Rosee0a5d322011-08-23 20:27:16 +00002957
2958 case Dealloc:
2959 // Any use of -dealloc in GC is *bad*.
Jordy Rose17a38e22011-09-02 05:55:19 +00002960 if (C.isObjCGCEnabled()) {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002961 V = V ^ RefVal::ErrorDeallocGC;
2962 hasErr = V.getKind();
2963 break;
2964 }
2965
2966 switch (V.getKind()) {
2967 default:
2968 llvm_unreachable("Invalid RefVal state for an explicit dealloc.");
Jordy Rosee0a5d322011-08-23 20:27:16 +00002969 case RefVal::Owned:
2970 // The object immediately transitions to the released state.
2971 V = V ^ RefVal::Released;
2972 V.clearCounts();
2973 return state->set<RefBindings>(sym, V);
2974 case RefVal::NotOwned:
2975 V = V ^ RefVal::ErrorDeallocNotOwned;
2976 hasErr = V.getKind();
2977 break;
2978 }
2979 break;
2980
2981 case NewAutoreleasePool:
Jordy Rose17a38e22011-09-02 05:55:19 +00002982 assert(!C.isObjCGCEnabled());
Jordy Rosee0a5d322011-08-23 20:27:16 +00002983 return state->add<AutoreleaseStack>(sym);
2984
2985 case MayEscape:
2986 if (V.getKind() == RefVal::Owned) {
2987 V = V ^ RefVal::NotOwned;
2988 break;
2989 }
2990
2991 // Fall-through.
2992
Jordy Rosee0a5d322011-08-23 20:27:16 +00002993 case DoNothing:
2994 return state;
2995
2996 case Autorelease:
Jordy Rose17a38e22011-09-02 05:55:19 +00002997 if (C.isObjCGCEnabled())
Jordy Rosee0a5d322011-08-23 20:27:16 +00002998 return state;
2999
3000 // Update the autorelease counts.
3001 state = SendAutorelease(state, ARCountFactory, sym);
3002 V = V.autorelease();
3003 break;
3004
3005 case StopTracking:
3006 return state->remove<RefBindings>(sym);
3007
3008 case IncRef:
3009 switch (V.getKind()) {
3010 default:
3011 llvm_unreachable("Invalid RefVal state for a retain.");
Jordy Rosee0a5d322011-08-23 20:27:16 +00003012 case RefVal::Owned:
3013 case RefVal::NotOwned:
3014 V = V + 1;
3015 break;
3016 case RefVal::Released:
3017 // Non-GC cases are handled above.
Jordy Rose17a38e22011-09-02 05:55:19 +00003018 assert(C.isObjCGCEnabled());
Jordy Rosee0a5d322011-08-23 20:27:16 +00003019 V = (V ^ RefVal::Owned) + 1;
3020 break;
3021 }
3022 break;
3023
Jordy Rosee0a5d322011-08-23 20:27:16 +00003024 case DecRef:
3025 case DecRefBridgedTransfered:
Jordan Rose4531b7d2012-07-02 19:27:43 +00003026 case DecRefAndStopTracking:
Jordy Rosee0a5d322011-08-23 20:27:16 +00003027 switch (V.getKind()) {
3028 default:
3029 // case 'RefVal::Released' handled above.
3030 llvm_unreachable("Invalid RefVal state for a release.");
Jordy Rosee0a5d322011-08-23 20:27:16 +00003031
3032 case RefVal::Owned:
3033 assert(V.getCount() > 0);
3034 if (V.getCount() == 1)
3035 V = V ^ (E == DecRefBridgedTransfered ?
3036 RefVal::NotOwned : RefVal::Released);
Jordan Rose4531b7d2012-07-02 19:27:43 +00003037 else if (E == DecRefAndStopTracking)
3038 return state->remove<RefBindings>(sym);
3039
Jordy Rosee0a5d322011-08-23 20:27:16 +00003040 V = V - 1;
3041 break;
3042
3043 case RefVal::NotOwned:
Jordan Rose4531b7d2012-07-02 19:27:43 +00003044 if (V.getCount() > 0) {
3045 if (E == DecRefAndStopTracking)
3046 return state->remove<RefBindings>(sym);
Jordy Rosee0a5d322011-08-23 20:27:16 +00003047 V = V - 1;
Jordan Rose4531b7d2012-07-02 19:27:43 +00003048 } else {
Jordy Rosee0a5d322011-08-23 20:27:16 +00003049 V = V ^ RefVal::ErrorReleaseNotOwned;
3050 hasErr = V.getKind();
3051 }
3052 break;
3053
3054 case RefVal::Released:
3055 // Non-GC cases are handled above.
Jordy Rose17a38e22011-09-02 05:55:19 +00003056 assert(C.isObjCGCEnabled());
Jordy Rosee0a5d322011-08-23 20:27:16 +00003057 V = V ^ RefVal::ErrorUseAfterRelease;
3058 hasErr = V.getKind();
3059 break;
3060 }
3061 break;
3062 }
3063 return state->set<RefBindings>(sym, V);
3064}
3065
Ted Kremenek8bef8232012-01-26 21:29:00 +00003066void RetainCountChecker::processNonLeakError(ProgramStateRef St,
Jordy Rose910c4052011-09-02 06:44:22 +00003067 SourceRange ErrorRange,
3068 RefVal::Kind ErrorKind,
3069 SymbolRef Sym,
3070 CheckerContext &C) const {
Jordy Rose294396b2011-08-22 23:48:23 +00003071 ExplodedNode *N = C.generateSink(St);
3072 if (!N)
3073 return;
3074
Jordy Rose294396b2011-08-22 23:48:23 +00003075 CFRefBug *BT;
3076 switch (ErrorKind) {
3077 default:
3078 llvm_unreachable("Unhandled error.");
Jordy Rose294396b2011-08-22 23:48:23 +00003079 case RefVal::ErrorUseAfterRelease:
Jordy Rosed6334e12011-08-25 00:34:03 +00003080 if (!useAfterRelease)
3081 useAfterRelease.reset(new UseAfterRelease());
3082 BT = &*useAfterRelease;
Jordy Rose294396b2011-08-22 23:48:23 +00003083 break;
3084 case RefVal::ErrorReleaseNotOwned:
Jordy Rosed6334e12011-08-25 00:34:03 +00003085 if (!releaseNotOwned)
3086 releaseNotOwned.reset(new BadRelease());
3087 BT = &*releaseNotOwned;
Jordy Rose294396b2011-08-22 23:48:23 +00003088 break;
3089 case RefVal::ErrorDeallocGC:
Jordy Rosed6334e12011-08-25 00:34:03 +00003090 if (!deallocGC)
3091 deallocGC.reset(new DeallocGC());
3092 BT = &*deallocGC;
Jordy Rose294396b2011-08-22 23:48:23 +00003093 break;
3094 case RefVal::ErrorDeallocNotOwned:
Jordy Rosed6334e12011-08-25 00:34:03 +00003095 if (!deallocNotOwned)
3096 deallocNotOwned.reset(new DeallocNotOwned());
3097 BT = &*deallocNotOwned;
Jordy Rose294396b2011-08-22 23:48:23 +00003098 break;
3099 }
3100
Jordy Rosed6334e12011-08-25 00:34:03 +00003101 assert(BT);
David Blaikie4e4d0842012-03-11 07:00:24 +00003102 CFRefReport *report = new CFRefReport(*BT, C.getASTContext().getLangOpts(),
Jordy Rose17a38e22011-09-02 05:55:19 +00003103 C.isObjCGCEnabled(), SummaryLog,
3104 N, Sym);
Jordy Rose294396b2011-08-22 23:48:23 +00003105 report->addRange(ErrorRange);
3106 C.EmitReport(report);
3107}
3108
Jordy Rose910c4052011-09-02 06:44:22 +00003109//===----------------------------------------------------------------------===//
3110// Handle the return values of retain-count-related functions.
3111//===----------------------------------------------------------------------===//
3112
3113bool RetainCountChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
Jordy Rose76c506f2011-08-21 21:58:18 +00003114 // Get the callee. We're only interested in simple C functions.
Ted Kremenek8bef8232012-01-26 21:29:00 +00003115 ProgramStateRef state = C.getState();
Anna Zaksb805c8f2011-12-01 05:57:37 +00003116 const FunctionDecl *FD = C.getCalleeDecl(CE);
Jordy Rose76c506f2011-08-21 21:58:18 +00003117 if (!FD)
3118 return false;
3119
3120 IdentifierInfo *II = FD->getIdentifier();
3121 if (!II)
3122 return false;
3123
3124 // For now, we're only handling the functions that return aliases of their
3125 // arguments: CFRetain and CFMakeCollectable (and their families).
3126 // Eventually we should add other functions we can model entirely,
3127 // such as CFRelease, which don't invalidate their arguments or globals.
3128 if (CE->getNumArgs() != 1)
3129 return false;
3130
3131 // Get the name of the function.
3132 StringRef FName = II->getName();
3133 FName = FName.substr(FName.find_first_not_of('_'));
3134
3135 // See if it's one of the specific functions we know how to eval.
3136 bool canEval = false;
3137
Anna Zaksb805c8f2011-12-01 05:57:37 +00003138 QualType ResultTy = CE->getCallReturnType();
Jordy Rose76c506f2011-08-21 21:58:18 +00003139 if (ResultTy->isObjCIdType()) {
3140 // Handle: id NSMakeCollectable(CFTypeRef)
3141 canEval = II->isStr("NSMakeCollectable");
3142 } else if (ResultTy->isPointerType()) {
3143 // Handle: (CF|CG)Retain
3144 // CFMakeCollectable
3145 // It's okay to be a little sloppy here (CGMakeCollectable doesn't exist).
3146 if (cocoa::isRefType(ResultTy, "CF", FName) ||
3147 cocoa::isRefType(ResultTy, "CG", FName)) {
3148 canEval = isRetain(FD, FName) || isMakeCollectable(FD, FName);
3149 }
3150 }
3151
3152 if (!canEval)
3153 return false;
3154
3155 // Bind the return value.
Ted Kremenek5eca4822012-01-06 22:09:28 +00003156 const LocationContext *LCtx = C.getLocationContext();
3157 SVal RetVal = state->getSVal(CE->getArg(0), LCtx);
Jordy Rose76c506f2011-08-21 21:58:18 +00003158 if (RetVal.isUnknown()) {
3159 // If the receiver is unknown, conjure a return value.
3160 SValBuilder &SVB = C.getSValBuilder();
Anna Zaks5d0ea6d2011-10-04 20:43:05 +00003161 unsigned Count = C.getCurrentBlockCount();
Ted Kremenek3133f792012-02-17 23:13:45 +00003162 SVal RetVal = SVB.getConjuredSymbolVal(0, CE, LCtx, ResultTy, Count);
Jordy Rose76c506f2011-08-21 21:58:18 +00003163 }
Ted Kremenek5eca4822012-01-06 22:09:28 +00003164 state = state->BindExpr(CE, LCtx, RetVal, false);
Jordy Rose76c506f2011-08-21 21:58:18 +00003165
Jordy Rose294396b2011-08-22 23:48:23 +00003166 // FIXME: This should not be necessary, but otherwise the argument seems to be
3167 // considered alive during the next statement.
3168 if (const MemRegion *ArgRegion = RetVal.getAsRegion()) {
3169 // Save the refcount status of the argument.
3170 SymbolRef Sym = RetVal.getAsLocSymbol();
3171 RefBindings::data_type *Binding = 0;
3172 if (Sym)
3173 Binding = state->get<RefBindings>(Sym);
Jordy Rose76c506f2011-08-21 21:58:18 +00003174
Jordy Rose294396b2011-08-22 23:48:23 +00003175 // Invalidate the argument region.
Anna Zaks5d0ea6d2011-10-04 20:43:05 +00003176 unsigned Count = C.getCurrentBlockCount();
Ted Kremenek3133f792012-02-17 23:13:45 +00003177 state = state->invalidateRegions(ArgRegion, CE, Count, LCtx);
Jordy Rose76c506f2011-08-21 21:58:18 +00003178
Jordy Rose294396b2011-08-22 23:48:23 +00003179 // Restore the refcount status of the argument.
3180 if (Binding)
3181 state = state->set<RefBindings>(Sym, *Binding);
3182 }
3183
Anna Zaks0bd6b112011-10-26 21:06:34 +00003184 C.addTransition(state);
Jordy Rose76c506f2011-08-21 21:58:18 +00003185 return true;
3186}
3187
Jordy Rose910c4052011-09-02 06:44:22 +00003188//===----------------------------------------------------------------------===//
3189// Handle return statements.
3190//===----------------------------------------------------------------------===//
Jordy Rosef53e8c72011-08-23 19:43:16 +00003191
Ted Kremeneke5715782012-02-25 02:09:09 +00003192// Return true if the current LocationContext has no caller context.
3193static bool inTopFrame(CheckerContext &C) {
3194 const LocationContext *LC = C.getLocationContext();
3195 return LC->getParent() == 0;
3196}
3197
Jordy Rose910c4052011-09-02 06:44:22 +00003198void RetainCountChecker::checkPreStmt(const ReturnStmt *S,
3199 CheckerContext &C) const {
Ted Kremeneke5715782012-02-25 02:09:09 +00003200
3201 // Only adjust the reference count if this is the top-level call frame,
3202 // and not the result of inlining. In the future, we should do
3203 // better checking even for inlined calls, and see if they match
3204 // with their expected semantics (e.g., the method should return a retained
3205 // object, etc.).
3206 if (!inTopFrame(C))
3207 return;
3208
Jordy Rosef53e8c72011-08-23 19:43:16 +00003209 const Expr *RetE = S->getRetValue();
3210 if (!RetE)
3211 return;
3212
Ted Kremenek8bef8232012-01-26 21:29:00 +00003213 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00003214 SymbolRef Sym =
3215 state->getSValAsScalarOrLoc(RetE, C.getLocationContext()).getAsLocSymbol();
Jordy Rosef53e8c72011-08-23 19:43:16 +00003216 if (!Sym)
3217 return;
3218
3219 // Get the reference count binding (if any).
3220 const RefVal *T = state->get<RefBindings>(Sym);
3221 if (!T)
3222 return;
3223
3224 // Change the reference count.
3225 RefVal X = *T;
3226
3227 switch (X.getKind()) {
3228 case RefVal::Owned: {
3229 unsigned cnt = X.getCount();
3230 assert(cnt > 0);
3231 X.setCount(cnt - 1);
3232 X = X ^ RefVal::ReturnedOwned;
3233 break;
3234 }
3235
3236 case RefVal::NotOwned: {
3237 unsigned cnt = X.getCount();
3238 if (cnt) {
3239 X.setCount(cnt - 1);
3240 X = X ^ RefVal::ReturnedOwned;
3241 }
3242 else {
3243 X = X ^ RefVal::ReturnedNotOwned;
3244 }
3245 break;
3246 }
3247
3248 default:
3249 return;
3250 }
3251
3252 // Update the binding.
3253 state = state->set<RefBindings>(Sym, X);
Anna Zaks0bd6b112011-10-26 21:06:34 +00003254 ExplodedNode *Pred = C.addTransition(state);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003255
3256 // At this point we have updated the state properly.
3257 // Everything after this is merely checking to see if the return value has
3258 // been over- or under-retained.
3259
3260 // Did we cache out?
3261 if (!Pred)
3262 return;
3263
Jordy Rosef53e8c72011-08-23 19:43:16 +00003264 // Update the autorelease counts.
3265 static SimpleProgramPointTag
Jordy Rose910c4052011-09-02 06:44:22 +00003266 AutoreleaseTag("RetainCountChecker : Autorelease");
Anna Zaks4eff8232011-10-05 23:44:11 +00003267 GenericNodeBuilderRefCount Bd(C, &AutoreleaseTag);
Anna Zaks6a93bd52011-10-25 19:57:11 +00003268 llvm::tie(Pred, state) = handleAutoreleaseCounts(state, Bd, Pred, C, Sym, X);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003269
3270 // Did we cache out?
Jordy Rose8d228632011-08-23 20:07:14 +00003271 if (!Pred)
Jordy Rosef53e8c72011-08-23 19:43:16 +00003272 return;
3273
3274 // Get the updated binding.
3275 T = state->get<RefBindings>(Sym);
3276 assert(T);
3277 X = *T;
3278
3279 // Consult the summary of the enclosing method.
Jordy Rose17a38e22011-09-02 05:55:19 +00003280 RetainSummaryManager &Summaries = getSummaryManager(C);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003281 const Decl *CD = &Pred->getCodeDecl();
Jordan Rose4531b7d2012-07-02 19:27:43 +00003282 RetEffect RE = RetEffect::MakeNoRet();
Jordy Rosef53e8c72011-08-23 19:43:16 +00003283
Jordan Rose4531b7d2012-07-02 19:27:43 +00003284 // FIXME: What is the convention for blocks? Is there one?
Jordy Rosef53e8c72011-08-23 19:43:16 +00003285 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CD)) {
Jordy Roseb6cfc092011-08-25 00:10:37 +00003286 const RetainSummary *Summ = Summaries.getMethodSummary(MD);
Jordan Rose4531b7d2012-07-02 19:27:43 +00003287 RE = Summ->getRetEffect();
3288 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) {
3289 if (!isa<CXXMethodDecl>(FD)) {
3290 const RetainSummary *Summ = Summaries.getFunctionSummary(FD);
3291 RE = Summ->getRetEffect();
3292 }
Jordy Rosef53e8c72011-08-23 19:43:16 +00003293 }
3294
Jordan Rose4531b7d2012-07-02 19:27:43 +00003295 checkReturnWithRetEffect(S, C, Pred, RE, X, Sym, state);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003296}
3297
Jordy Rose910c4052011-09-02 06:44:22 +00003298void RetainCountChecker::checkReturnWithRetEffect(const ReturnStmt *S,
3299 CheckerContext &C,
3300 ExplodedNode *Pred,
3301 RetEffect RE, RefVal X,
3302 SymbolRef Sym,
Ted Kremenek8bef8232012-01-26 21:29:00 +00003303 ProgramStateRef state) const {
Jordy Rosef53e8c72011-08-23 19:43:16 +00003304 // Any leaks or other errors?
3305 if (X.isReturnedOwned() && X.getCount() == 0) {
3306 if (RE.getKind() != RetEffect::NoRet) {
3307 bool hasError = false;
Jordy Rose17a38e22011-09-02 05:55:19 +00003308 if (C.isObjCGCEnabled() && RE.getObjKind() == RetEffect::ObjC) {
Jordy Rosef53e8c72011-08-23 19:43:16 +00003309 // Things are more complicated with garbage collection. If the
3310 // returned object is suppose to be an Objective-C object, we have
3311 // a leak (as the caller expects a GC'ed object) because no
3312 // method should return ownership unless it returns a CF object.
3313 hasError = true;
3314 X = X ^ RefVal::ErrorGCLeakReturned;
3315 }
3316 else if (!RE.isOwned()) {
3317 // Either we are using GC and the returned object is a CF type
3318 // or we aren't using GC. In either case, we expect that the
3319 // enclosing method is expected to return ownership.
3320 hasError = true;
3321 X = X ^ RefVal::ErrorLeakReturned;
3322 }
3323
3324 if (hasError) {
3325 // Generate an error node.
3326 state = state->set<RefBindings>(Sym, X);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003327
3328 static SimpleProgramPointTag
Jordy Rose910c4052011-09-02 06:44:22 +00003329 ReturnOwnLeakTag("RetainCountChecker : ReturnsOwnLeak");
Anna Zaks0bd6b112011-10-26 21:06:34 +00003330 ExplodedNode *N = C.addTransition(state, Pred, &ReturnOwnLeakTag);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003331 if (N) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003332 const LangOptions &LOpts = C.getASTContext().getLangOpts();
Jordy Rose17a38e22011-09-02 05:55:19 +00003333 bool GCEnabled = C.isObjCGCEnabled();
Jordy Rosef53e8c72011-08-23 19:43:16 +00003334 CFRefReport *report =
Jordy Rose17a38e22011-09-02 05:55:19 +00003335 new CFRefLeakReport(*getLeakAtReturnBug(LOpts, GCEnabled),
3336 LOpts, GCEnabled, SummaryLog,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003337 N, Sym, C);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003338 C.EmitReport(report);
3339 }
3340 }
3341 }
3342 } else if (X.isReturnedNotOwned()) {
3343 if (RE.isOwned()) {
3344 // Trying to return a not owned object to a caller expecting an
3345 // owned object.
3346 state = state->set<RefBindings>(Sym, X ^ RefVal::ErrorReturnedNotOwned);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003347
3348 static SimpleProgramPointTag
Jordy Rose910c4052011-09-02 06:44:22 +00003349 ReturnNotOwnedTag("RetainCountChecker : ReturnNotOwnedForOwned");
Anna Zaks0bd6b112011-10-26 21:06:34 +00003350 ExplodedNode *N = C.addTransition(state, Pred, &ReturnNotOwnedTag);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003351 if (N) {
Jordy Rosed6334e12011-08-25 00:34:03 +00003352 if (!returnNotOwnedForOwned)
3353 returnNotOwnedForOwned.reset(new ReturnedNotOwnedForOwned());
3354
Jordy Rosef53e8c72011-08-23 19:43:16 +00003355 CFRefReport *report =
Jordy Rosed6334e12011-08-25 00:34:03 +00003356 new CFRefReport(*returnNotOwnedForOwned,
David Blaikie4e4d0842012-03-11 07:00:24 +00003357 C.getASTContext().getLangOpts(),
Jordy Rose17a38e22011-09-02 05:55:19 +00003358 C.isObjCGCEnabled(), SummaryLog, N, Sym);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003359 C.EmitReport(report);
3360 }
3361 }
3362 }
3363}
3364
Jordy Rose8d228632011-08-23 20:07:14 +00003365//===----------------------------------------------------------------------===//
Jordy Rose910c4052011-09-02 06:44:22 +00003366// Check various ways a symbol can be invalidated.
3367//===----------------------------------------------------------------------===//
3368
Anna Zaks390909c2011-10-06 00:43:15 +00003369void RetainCountChecker::checkBind(SVal loc, SVal val, const Stmt *S,
Jordy Rose910c4052011-09-02 06:44:22 +00003370 CheckerContext &C) const {
3371 // Are we storing to something that causes the value to "escape"?
3372 bool escapes = true;
3373
3374 // A value escapes in three possible cases (this may change):
3375 //
3376 // (1) we are binding to something that is not a memory region.
3377 // (2) we are binding to a memregion that does not have stack storage
3378 // (3) we are binding to a memregion with stack storage that the store
3379 // does not understand.
Ted Kremenek8bef8232012-01-26 21:29:00 +00003380 ProgramStateRef state = C.getState();
Jordy Rose910c4052011-09-02 06:44:22 +00003381
3382 if (loc::MemRegionVal *regionLoc = dyn_cast<loc::MemRegionVal>(&loc)) {
3383 escapes = !regionLoc->getRegion()->hasStackStorage();
3384
3385 if (!escapes) {
3386 // To test (3), generate a new state with the binding added. If it is
3387 // the same state, then it escapes (since the store cannot represent
3388 // the binding).
Anna Zakse7958da2012-05-02 00:15:40 +00003389 // Do this only if we know that the store is not supposed to generate the
3390 // same state.
3391 SVal StoredVal = state->getSVal(regionLoc->getRegion());
3392 if (StoredVal != val)
3393 escapes = (state == (state->bindLoc(*regionLoc, val)));
Jordy Rose910c4052011-09-02 06:44:22 +00003394 }
Ted Kremenekde5b4fb2012-03-27 01:12:45 +00003395 if (!escapes) {
3396 // Case 4: We do not currently model what happens when a symbol is
3397 // assigned to a struct field, so be conservative here and let the symbol
3398 // go. TODO: This could definitely be improved upon.
3399 escapes = !isa<VarRegion>(regionLoc->getRegion());
3400 }
Jordy Rose910c4052011-09-02 06:44:22 +00003401 }
3402
3403 // If our store can represent the binding and we aren't storing to something
3404 // that doesn't have local storage then just return and have the simulation
3405 // state continue as is.
3406 if (!escapes)
3407 return;
3408
3409 // Otherwise, find all symbols referenced by 'val' that we are tracking
3410 // and stop tracking them.
3411 state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
Anna Zaks0bd6b112011-10-26 21:06:34 +00003412 C.addTransition(state);
Jordy Rose910c4052011-09-02 06:44:22 +00003413}
3414
Ted Kremenek8bef8232012-01-26 21:29:00 +00003415ProgramStateRef RetainCountChecker::evalAssume(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003416 SVal Cond,
3417 bool Assumption) const {
3418
3419 // FIXME: We may add to the interface of evalAssume the list of symbols
3420 // whose assumptions have changed. For now we just iterate through the
3421 // bindings and check if any of the tracked symbols are NULL. This isn't
3422 // too bad since the number of symbols we will track in practice are
3423 // probably small and evalAssume is only called at branches and a few
3424 // other places.
3425 RefBindings B = state->get<RefBindings>();
3426
3427 if (B.isEmpty())
3428 return state;
3429
3430 bool changed = false;
3431 RefBindings::Factory &RefBFactory = state->get_context<RefBindings>();
3432
3433 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
3434 // Check if the symbol is null (or equal to any constant).
3435 // If this is the case, stop tracking the symbol.
3436 if (state->getSymVal(I.getKey())) {
3437 changed = true;
3438 B = RefBFactory.remove(B, I.getKey());
3439 }
3440 }
3441
3442 if (changed)
3443 state = state->set<RefBindings>(B);
3444
3445 return state;
3446}
3447
Ted Kremenek8bef8232012-01-26 21:29:00 +00003448ProgramStateRef
3449RetainCountChecker::checkRegionChanges(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003450 const StoreManager::InvalidatedSymbols *invalidated,
3451 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00003452 ArrayRef<const MemRegion *> Regions,
Jordan Rose740d4902012-07-02 19:27:35 +00003453 const CallEvent *Call) const {
Jordy Rose910c4052011-09-02 06:44:22 +00003454 if (!invalidated)
3455 return state;
3456
3457 llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
3458 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
3459 E = ExplicitRegions.end(); I != E; ++I) {
3460 if (const SymbolicRegion *SR = (*I)->StripCasts()->getAs<SymbolicRegion>())
3461 WhitelistedSymbols.insert(SR->getSymbol());
3462 }
3463
3464 for (StoreManager::InvalidatedSymbols::const_iterator I=invalidated->begin(),
3465 E = invalidated->end(); I!=E; ++I) {
3466 SymbolRef sym = *I;
3467 if (WhitelistedSymbols.count(sym))
3468 continue;
3469 // Remove any existing reference-count binding.
3470 state = state->remove<RefBindings>(sym);
3471 }
3472 return state;
3473}
3474
3475//===----------------------------------------------------------------------===//
Jordy Rose8d228632011-08-23 20:07:14 +00003476// Handle dead symbols and end-of-path.
3477//===----------------------------------------------------------------------===//
3478
Ted Kremenek8bef8232012-01-26 21:29:00 +00003479std::pair<ExplodedNode *, ProgramStateRef >
3480RetainCountChecker::handleAutoreleaseCounts(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003481 GenericNodeBuilderRefCount Bd,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003482 ExplodedNode *Pred,
3483 CheckerContext &Ctx,
Jordy Rose910c4052011-09-02 06:44:22 +00003484 SymbolRef Sym, RefVal V) const {
Jordy Rose8d228632011-08-23 20:07:14 +00003485 unsigned ACnt = V.getAutoreleaseCount();
3486
3487 // No autorelease counts? Nothing to be done.
3488 if (!ACnt)
3489 return std::make_pair(Pred, state);
3490
Anna Zaks6a93bd52011-10-25 19:57:11 +00003491 assert(!Ctx.isObjCGCEnabled() && "Autorelease counts in GC mode?");
Jordy Rose8d228632011-08-23 20:07:14 +00003492 unsigned Cnt = V.getCount();
3493
3494 // FIXME: Handle sending 'autorelease' to already released object.
3495
3496 if (V.getKind() == RefVal::ReturnedOwned)
3497 ++Cnt;
3498
3499 if (ACnt <= Cnt) {
3500 if (ACnt == Cnt) {
3501 V.clearCounts();
3502 if (V.getKind() == RefVal::ReturnedOwned)
3503 V = V ^ RefVal::ReturnedNotOwned;
3504 else
3505 V = V ^ RefVal::NotOwned;
3506 } else {
3507 V.setCount(Cnt - ACnt);
3508 V.setAutoreleaseCount(0);
3509 }
3510 state = state->set<RefBindings>(Sym, V);
3511 ExplodedNode *N = Bd.MakeNode(state, Pred);
3512 if (N == 0)
3513 state = 0;
3514 return std::make_pair(N, state);
3515 }
3516
3517 // Woah! More autorelease counts then retain counts left.
3518 // Emit hard error.
3519 V = V ^ RefVal::ErrorOverAutorelease;
3520 state = state->set<RefBindings>(Sym, V);
3521
Anna Zaksf05aac82011-10-18 23:05:58 +00003522 if (ExplodedNode *N = Bd.MakeNode(state, Pred, true)) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003523 SmallString<128> sbuf;
Jordy Rose8d228632011-08-23 20:07:14 +00003524 llvm::raw_svector_ostream os(sbuf);
3525 os << "Object over-autoreleased: object was sent -autorelease ";
3526 if (V.getAutoreleaseCount() > 1)
3527 os << V.getAutoreleaseCount() << " times ";
3528 os << "but the object has a +" << V.getCount() << " retain count";
3529
Jordy Rosed6334e12011-08-25 00:34:03 +00003530 if (!overAutorelease)
3531 overAutorelease.reset(new OverAutorelease());
3532
David Blaikie4e4d0842012-03-11 07:00:24 +00003533 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
Jordy Rose8d228632011-08-23 20:07:14 +00003534 CFRefReport *report =
Jordy Rosed6334e12011-08-25 00:34:03 +00003535 new CFRefReport(*overAutorelease, LOpts, /* GCEnabled = */ false,
3536 SummaryLog, N, Sym, os.str());
Anna Zaks6a93bd52011-10-25 19:57:11 +00003537 Ctx.EmitReport(report);
Jordy Rose8d228632011-08-23 20:07:14 +00003538 }
3539
Ted Kremenek8bef8232012-01-26 21:29:00 +00003540 return std::make_pair((ExplodedNode *)0, (ProgramStateRef )0);
Jordy Rose8d228632011-08-23 20:07:14 +00003541}
Jordy Rose38f17d62011-08-23 19:01:07 +00003542
Ted Kremenek8bef8232012-01-26 21:29:00 +00003543ProgramStateRef
3544RetainCountChecker::handleSymbolDeath(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003545 SymbolRef sid, RefVal V,
Jordy Rose38f17d62011-08-23 19:01:07 +00003546 SmallVectorImpl<SymbolRef> &Leaked) const {
Jordy Rose53376122011-08-24 04:48:19 +00003547 bool hasLeak = false;
Jordy Rose38f17d62011-08-23 19:01:07 +00003548 if (V.isOwned())
3549 hasLeak = true;
3550 else if (V.isNotOwned() || V.isReturnedOwned())
3551 hasLeak = (V.getCount() > 0);
3552
3553 if (!hasLeak)
3554 return state->remove<RefBindings>(sid);
3555
3556 Leaked.push_back(sid);
3557 return state->set<RefBindings>(sid, V ^ RefVal::ErrorLeak);
3558}
3559
3560ExplodedNode *
Ted Kremenek8bef8232012-01-26 21:29:00 +00003561RetainCountChecker::processLeaks(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003562 SmallVectorImpl<SymbolRef> &Leaked,
3563 GenericNodeBuilderRefCount &Builder,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003564 CheckerContext &Ctx,
3565 ExplodedNode *Pred) const {
Jordy Rose38f17d62011-08-23 19:01:07 +00003566 if (Leaked.empty())
3567 return Pred;
3568
3569 // Generate an intermediate node representing the leak point.
3570 ExplodedNode *N = Builder.MakeNode(state, Pred);
3571
3572 if (N) {
3573 for (SmallVectorImpl<SymbolRef>::iterator
3574 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3575
David Blaikie4e4d0842012-03-11 07:00:24 +00003576 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
Anna Zaks6a93bd52011-10-25 19:57:11 +00003577 bool GCEnabled = Ctx.isObjCGCEnabled();
Jordy Rose17a38e22011-09-02 05:55:19 +00003578 CFRefBug *BT = Pred ? getLeakWithinFunctionBug(LOpts, GCEnabled)
3579 : getLeakAtReturnBug(LOpts, GCEnabled);
Jordy Rose38f17d62011-08-23 19:01:07 +00003580 assert(BT && "BugType not initialized.");
Jordy Rose20589562011-08-24 22:39:09 +00003581
Jordy Rose17a38e22011-09-02 05:55:19 +00003582 CFRefLeakReport *report = new CFRefLeakReport(*BT, LOpts, GCEnabled,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003583 SummaryLog, N, *I, Ctx);
3584 Ctx.EmitReport(report);
Jordy Rose38f17d62011-08-23 19:01:07 +00003585 }
3586 }
3587
3588 return N;
3589}
3590
Anna Zaksaf498a22011-10-25 19:56:48 +00003591void RetainCountChecker::checkEndPath(CheckerContext &Ctx) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +00003592 ProgramStateRef state = Ctx.getState();
Anna Zaksaf498a22011-10-25 19:56:48 +00003593 GenericNodeBuilderRefCount Bd(Ctx);
Jordy Rose38f17d62011-08-23 19:01:07 +00003594 RefBindings B = state->get<RefBindings>();
Anna Zaksaf498a22011-10-25 19:56:48 +00003595 ExplodedNode *Pred = Ctx.getPredecessor();
Jordy Rose38f17d62011-08-23 19:01:07 +00003596
3597 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Anna Zaks6a93bd52011-10-25 19:57:11 +00003598 llvm::tie(Pred, state) = handleAutoreleaseCounts(state, Bd, Pred, Ctx,
Jordy Rose8d228632011-08-23 20:07:14 +00003599 I->first, I->second);
3600 if (!state)
Jordy Rose38f17d62011-08-23 19:01:07 +00003601 return;
3602 }
3603
Ted Kremenek0cf3d472012-02-07 00:24:33 +00003604 // If the current LocationContext has a parent, don't check for leaks.
3605 // We will do that later.
3606 // FIXME: we should instead check for imblances of the retain/releases,
3607 // and suggest annotations.
3608 if (Ctx.getLocationContext()->getParent())
3609 return;
3610
Jordy Rose38f17d62011-08-23 19:01:07 +00003611 B = state->get<RefBindings>();
3612 SmallVector<SymbolRef, 10> Leaked;
3613
3614 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I)
Jordy Rose8d228632011-08-23 20:07:14 +00003615 state = handleSymbolDeath(state, I->first, I->second, Leaked);
Jordy Rose38f17d62011-08-23 19:01:07 +00003616
Anna Zaks6a93bd52011-10-25 19:57:11 +00003617 processLeaks(state, Leaked, Bd, Ctx, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003618}
3619
3620const ProgramPointTag *
Jordy Rose910c4052011-09-02 06:44:22 +00003621RetainCountChecker::getDeadSymbolTag(SymbolRef sym) const {
Jordy Rose38f17d62011-08-23 19:01:07 +00003622 const SimpleProgramPointTag *&tag = DeadSymbolTags[sym];
3623 if (!tag) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003624 SmallString<64> buf;
Jordy Rose38f17d62011-08-23 19:01:07 +00003625 llvm::raw_svector_ostream out(buf);
Anna Zaksf62ceec2011-12-05 18:58:11 +00003626 out << "RetainCountChecker : Dead Symbol : ";
3627 sym->dumpToStream(out);
Jordy Rose38f17d62011-08-23 19:01:07 +00003628 tag = new SimpleProgramPointTag(out.str());
3629 }
3630 return tag;
3631}
3632
Jordy Rose910c4052011-09-02 06:44:22 +00003633void RetainCountChecker::checkDeadSymbols(SymbolReaper &SymReaper,
3634 CheckerContext &C) const {
Jordy Rose38f17d62011-08-23 19:01:07 +00003635 ExplodedNode *Pred = C.getPredecessor();
3636
Ted Kremenek8bef8232012-01-26 21:29:00 +00003637 ProgramStateRef state = C.getState();
Jordy Rose38f17d62011-08-23 19:01:07 +00003638 RefBindings B = state->get<RefBindings>();
3639
3640 // Update counts from autorelease pools
3641 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3642 E = SymReaper.dead_end(); I != E; ++I) {
3643 SymbolRef Sym = *I;
3644 if (const RefVal *T = B.lookup(Sym)){
3645 // Use the symbol as the tag.
3646 // FIXME: This might not be as unique as we would like.
Anna Zaks4eff8232011-10-05 23:44:11 +00003647 GenericNodeBuilderRefCount Bd(C, getDeadSymbolTag(Sym));
Anna Zaks6a93bd52011-10-25 19:57:11 +00003648 llvm::tie(Pred, state) = handleAutoreleaseCounts(state, Bd, Pred, C,
Jordy Rose8d228632011-08-23 20:07:14 +00003649 Sym, *T);
3650 if (!state)
Jordy Rose38f17d62011-08-23 19:01:07 +00003651 return;
3652 }
3653 }
3654
3655 B = state->get<RefBindings>();
3656 SmallVector<SymbolRef, 10> Leaked;
3657
3658 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3659 E = SymReaper.dead_end(); I != E; ++I) {
3660 if (const RefVal *T = B.lookup(*I))
3661 state = handleSymbolDeath(state, *I, *T, Leaked);
3662 }
3663
3664 {
Anna Zaks4eff8232011-10-05 23:44:11 +00003665 GenericNodeBuilderRefCount Bd(C, this);
Anna Zaks6a93bd52011-10-25 19:57:11 +00003666 Pred = processLeaks(state, Leaked, Bd, C, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003667 }
3668
3669 // Did we cache out?
3670 if (!Pred)
3671 return;
3672
3673 // Now generate a new node that nukes the old bindings.
3674 RefBindings::Factory &F = state->get_context<RefBindings>();
3675
3676 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3677 E = SymReaper.dead_end(); I != E; ++I)
3678 B = F.remove(B, *I);
3679
3680 state = state->set<RefBindings>(B);
Anna Zaks0bd6b112011-10-26 21:06:34 +00003681 C.addTransition(state, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003682}
3683
Ted Kremenekd593eb92009-11-25 22:17:44 +00003684//===----------------------------------------------------------------------===//
Jordy Rosedbd658e2011-08-28 19:11:56 +00003685// Debug printing of refcount bindings and autorelease pools.
3686//===----------------------------------------------------------------------===//
3687
3688static void PrintPool(raw_ostream &Out, SymbolRef Sym,
Ted Kremenek8bef8232012-01-26 21:29:00 +00003689 ProgramStateRef State) {
Jordy Rosedbd658e2011-08-28 19:11:56 +00003690 Out << ' ';
3691 if (Sym)
Anna Zaksf62ceec2011-12-05 18:58:11 +00003692 Sym->dumpToStream(Out);
Jordy Rosedbd658e2011-08-28 19:11:56 +00003693 else
3694 Out << "<pool>";
3695 Out << ":{";
3696
3697 // Get the contents of the pool.
3698 if (const ARCounts *Cnts = State->get<AutoreleasePoolContents>(Sym))
3699 for (ARCounts::iterator I = Cnts->begin(), E = Cnts->end(); I != E; ++I)
3700 Out << '(' << I.getKey() << ',' << I.getData() << ')';
3701
3702 Out << '}';
3703}
3704
Ted Kremenek8bef8232012-01-26 21:29:00 +00003705static bool UsesAutorelease(ProgramStateRef state) {
Jordy Rosedbd658e2011-08-28 19:11:56 +00003706 // A state uses autorelease if it allocated an autorelease pool or if it has
3707 // objects in the caller's autorelease pool.
3708 return !state->get<AutoreleaseStack>().isEmpty() ||
3709 state->get<AutoreleasePoolContents>(SymbolRef());
3710}
3711
Ted Kremenek8bef8232012-01-26 21:29:00 +00003712void RetainCountChecker::printState(raw_ostream &Out, ProgramStateRef State,
Jordy Rose910c4052011-09-02 06:44:22 +00003713 const char *NL, const char *Sep) const {
Jordy Rosedbd658e2011-08-28 19:11:56 +00003714
3715 RefBindings B = State->get<RefBindings>();
3716
3717 if (!B.isEmpty())
3718 Out << Sep << NL;
3719
3720 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
3721 Out << I->first << " : ";
3722 I->second.print(Out);
3723 Out << NL;
3724 }
3725
3726 // Print the autorelease stack.
3727 if (UsesAutorelease(State)) {
3728 Out << Sep << NL << "AR pool stack:";
3729 ARStack Stack = State->get<AutoreleaseStack>();
3730
3731 PrintPool(Out, SymbolRef(), State); // Print the caller's pool.
3732 for (ARStack::iterator I = Stack.begin(), E = Stack.end(); I != E; ++I)
3733 PrintPool(Out, *I, State);
3734
3735 Out << NL;
3736 }
3737}
3738
3739//===----------------------------------------------------------------------===//
Jordy Rose910c4052011-09-02 06:44:22 +00003740// Checker registration.
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00003741//===----------------------------------------------------------------------===//
3742
Jordy Rose17a38e22011-09-02 05:55:19 +00003743void ento::registerRetainCountChecker(CheckerManager &Mgr) {
Jordy Rose910c4052011-09-02 06:44:22 +00003744 Mgr.registerChecker<RetainCountChecker>();
Jordy Rose17a38e22011-09-02 05:55:19 +00003745}
3746