blob: 304051c1394cc20544551d519d9a321a8f255481 [file] [log] [blame]
Jordy Rose910c4052011-09-02 06:44:22 +00001//==-- RetainCountChecker.cpp - Checks for leaks and other issues -*- C++ -*--//
Ted Kremenek2fff37e2008-03-06 00:08:09 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Jordy Rose910c4052011-09-02 06:44:22 +000010// This file defines the methods for RetainCountChecker, which implements
11// a reference count checker for Core Foundation and Cocoa on (Mac OS X).
Ted Kremenek2fff37e2008-03-06 00:08:09 +000012//
13//===----------------------------------------------------------------------===//
14
Jordy Rose910c4052011-09-02 06:44:22 +000015#include "ClangSACheckers.h"
Mike Stump1eb44332009-09-09 15:08:12 +000016#include "clang/AST/DeclObjC.h"
Ted Kremenekb2771592011-03-30 17:41:19 +000017#include "clang/AST/DeclCXX.h"
Ted Kremenek0b526b42010-02-18 00:05:58 +000018#include "clang/Basic/LangOptions.h"
19#include "clang/Basic/SourceManager.h"
Jordy Rose910c4052011-09-02 06:44:22 +000020#include "clang/Analysis/DomainSpecific/CocoaConventions.h"
Ted Kremenek4c42bb72011-11-14 21:59:21 +000021#include "clang/AST/ParentMap.h"
Jordy Rose910c4052011-09-02 06:44:22 +000022#include "clang/StaticAnalyzer/Core/Checker.h"
23#include "clang/StaticAnalyzer/Core/CheckerManager.h"
Ted Kremenek9b663712011-02-10 01:03:03 +000024#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
25#include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
Jordan Rosef540c542012-07-26 21:39:41 +000026#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
Jordy Rose910c4052011-09-02 06:44:22 +000027#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
Ted Kremenek18c66fd2011-08-15 22:09:50 +000028#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
Ted Kremenek9b663712011-02-10 01:03:03 +000029#include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000030#include "llvm/ADT/DenseMap.h"
31#include "llvm/ADT/FoldingSet.h"
Ted Kremenek6d348932008-10-21 15:53:15 +000032#include "llvm/ADT/ImmutableList.h"
Ted Kremenek0b526b42010-02-18 00:05:58 +000033#include "llvm/ADT/ImmutableMap.h"
Benjamin Kramer8fe83e12012-02-04 13:45:25 +000034#include "llvm/ADT/SmallString.h"
Ted Kremenek6ed9afc2008-05-16 18:33:44 +000035#include "llvm/ADT/STLExtras.h"
Ted Kremenek0b526b42010-02-18 00:05:58 +000036#include "llvm/ADT/StringExtras.h"
Chris Lattner5f9e2722011-07-23 10:55:15 +000037#include <cstdarg>
Ted Kremenek2fff37e2008-03-06 00:08:09 +000038
39using namespace clang;
Ted Kremenek9ef65372010-12-23 07:20:52 +000040using namespace ento;
Ted Kremeneka64e89b2010-01-27 06:13:48 +000041using llvm::StrInStrNoCase;
Ted Kremenek4c79e552008-11-05 16:54:44 +000042
Ted Kremenek05cbe1a2008-04-09 23:49:11 +000043//===----------------------------------------------------------------------===//
Ted Kremenek553cf182008-06-25 21:21:56 +000044// Primitives used for constructing summaries for function/method calls.
Ted Kremenek05cbe1a2008-04-09 23:49:11 +000045//===----------------------------------------------------------------------===//
46
Ted Kremenek553cf182008-06-25 21:21:56 +000047/// ArgEffect is used to summarize a function/method call's effect on a
48/// particular argument.
Jordy Rosebd85b132011-08-24 19:10:50 +000049enum ArgEffect { DoNothing, Autorelease, Dealloc, DecRef, DecRefMsg,
John McCallf85e1932011-06-15 23:02:42 +000050 DecRefBridgedTransfered,
Jordy Rosebd85b132011-08-24 19:10:50 +000051 IncRefMsg, IncRef, MakeCollectable, MayEscape,
Anna Zaks554067f2012-08-29 23:23:43 +000052 NewAutoreleasePool,
53
54 // Stop tracking the argument - the effect of the call is
55 // unknown.
56 StopTracking,
57
58 // In some cases, we obtain a better summary for this checker
59 // by looking at the call site than by inlining the function.
60 // Signifies that we should stop tracking the symbol even if
61 // the function is inlined.
62 StopTrackingHard,
63
64 // The function decrements the reference count and the checker
65 // should stop tracking the argument.
66 DecRefAndStopTrackingHard, DecRefMsgAndStopTrackingHard
67 };
Ted Kremenek553cf182008-06-25 21:21:56 +000068
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000069namespace llvm {
Ted Kremenekb77449c2009-05-03 05:20:50 +000070template <> struct FoldingSetTrait<ArgEffect> {
71static inline void Profile(const ArgEffect X, FoldingSetNodeID& ID) {
72 ID.AddInteger((unsigned) X);
73}
Ted Kremenek553cf182008-06-25 21:21:56 +000074};
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000075} // end llvm namespace
76
Ted Kremenekb77449c2009-05-03 05:20:50 +000077/// ArgEffects summarizes the effects of a function/method call on all of
78/// its arguments.
79typedef llvm::ImmutableMap<unsigned,ArgEffect> ArgEffects;
80
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000081namespace {
Ted Kremenek553cf182008-06-25 21:21:56 +000082
83/// RetEffect is used to summarize a function/method call's behavior with
Mike Stump1eb44332009-09-09 15:08:12 +000084/// respect to its return value.
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +000085class RetEffect {
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000086public:
Jordy Rose76c506f2011-08-21 21:58:18 +000087 enum Kind { NoRet, OwnedSymbol, OwnedAllocatedSymbol,
John McCallf85e1932011-06-15 23:02:42 +000088 NotOwnedSymbol, GCNotOwnedSymbol, ARCNotOwnedSymbol,
Anna Zaks554067f2012-08-29 23:23:43 +000089 OwnedWhenTrackedReceiver,
90 // Treat this function as returning a non-tracked symbol even if
91 // the function has been inlined. This is used where the call
92 // site summary is more presise than the summary indirectly produced
93 // by inlining the function
94 NoRetHard
95 };
Mike Stump1eb44332009-09-09 15:08:12 +000096
97 enum ObjKind { CF, ObjC, AnyObj };
Ted Kremenek2d1652e2009-01-28 05:56:51 +000098
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000099private:
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000100 Kind K;
101 ObjKind O;
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000102
Jordy Rose76c506f2011-08-21 21:58:18 +0000103 RetEffect(Kind k, ObjKind o = AnyObj) : K(k), O(o) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000104
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000105public:
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000106 Kind getKind() const { return K; }
107
108 ObjKind getObjKind() const { return O; }
Mike Stump1eb44332009-09-09 15:08:12 +0000109
Ted Kremeneka8833552009-04-29 23:03:22 +0000110 bool isOwned() const {
Ted Kremenek78a35a32009-05-12 20:06:54 +0000111 return K == OwnedSymbol || K == OwnedAllocatedSymbol ||
112 K == OwnedWhenTrackedReceiver;
Ted Kremeneka8833552009-04-29 23:03:22 +0000113 }
Mike Stump1eb44332009-09-09 15:08:12 +0000114
Jordy Rose4df54fe2011-08-23 04:27:15 +0000115 bool operator==(const RetEffect &Other) const {
116 return K == Other.K && O == Other.O;
117 }
118
Ted Kremenek78a35a32009-05-12 20:06:54 +0000119 static RetEffect MakeOwnedWhenTrackedReceiver() {
120 return RetEffect(OwnedWhenTrackedReceiver, ObjC);
121 }
Mike Stump1eb44332009-09-09 15:08:12 +0000122
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000123 static RetEffect MakeOwned(ObjKind o, bool isAllocated = false) {
124 return RetEffect(isAllocated ? OwnedAllocatedSymbol : OwnedSymbol, o);
Mike Stump1eb44332009-09-09 15:08:12 +0000125 }
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000126 static RetEffect MakeNotOwned(ObjKind o) {
127 return RetEffect(NotOwnedSymbol, o);
Ted Kremeneke798e7c2009-04-27 19:14:45 +0000128 }
129 static RetEffect MakeGCNotOwned() {
130 return RetEffect(GCNotOwnedSymbol, ObjC);
131 }
John McCallf85e1932011-06-15 23:02:42 +0000132 static RetEffect MakeARCNotOwned() {
133 return RetEffect(ARCNotOwnedSymbol, ObjC);
134 }
Ted Kremenek553cf182008-06-25 21:21:56 +0000135 static RetEffect MakeNoRet() {
136 return RetEffect(NoRet);
Ted Kremeneka7344702008-06-23 18:02:52 +0000137 }
Anna Zaks554067f2012-08-29 23:23:43 +0000138 static RetEffect MakeNoRetHard() {
139 return RetEffect(NoRetHard);
140 }
Jordy Roseef945882012-03-18 01:26:10 +0000141
142 void Profile(llvm::FoldingSetNodeID& ID) const {
143 ID.AddInteger((unsigned) K);
144 ID.AddInteger((unsigned) O);
145 }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000146};
Mike Stump1eb44332009-09-09 15:08:12 +0000147
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000148//===----------------------------------------------------------------------===//
149// Reference-counting logic (typestate + counts).
150//===----------------------------------------------------------------------===//
Mike Stump1eb44332009-09-09 15:08:12 +0000151
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000152class RefVal {
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000153public:
154 enum Kind {
155 Owned = 0, // Owning reference.
156 NotOwned, // Reference is not owned by still valid (not freed).
157 Released, // Object has been released.
158 ReturnedOwned, // Returned object passes ownership to caller.
159 ReturnedNotOwned, // Return object does not pass ownership to caller.
160 ERROR_START,
161 ErrorDeallocNotOwned, // -dealloc called on non-owned object.
162 ErrorDeallocGC, // Calling -dealloc with GC enabled.
163 ErrorUseAfterRelease, // Object used after released.
164 ErrorReleaseNotOwned, // Release of an object that was not owned.
165 ERROR_LEAK_START,
166 ErrorLeak, // A memory leak due to excessive reference counts.
167 ErrorLeakReturned, // A memory leak due to the returning method not having
168 // the correct naming conventions.
169 ErrorGCLeakReturned,
170 ErrorOverAutorelease,
171 ErrorReturnedNotOwned
172 };
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000173
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000174private:
175 Kind kind;
176 RetEffect::ObjKind okind;
177 unsigned Cnt;
178 unsigned ACnt;
179 QualType T;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000180
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000181 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, unsigned acnt, QualType t)
182 : kind(k), okind(o), Cnt(cnt), ACnt(acnt), T(t) {}
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000183
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000184public:
185 Kind getKind() const { return kind; }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000186
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000187 RetEffect::ObjKind getObjKind() const { return okind; }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000188
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000189 unsigned getCount() const { return Cnt; }
190 unsigned getAutoreleaseCount() const { return ACnt; }
191 unsigned getCombinedCounts() const { return Cnt + ACnt; }
192 void clearCounts() { Cnt = 0; ACnt = 0; }
193 void setCount(unsigned i) { Cnt = i; }
194 void setAutoreleaseCount(unsigned i) { ACnt = i; }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000195
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000196 QualType getType() const { return T; }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000197
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000198 bool isOwned() const {
199 return getKind() == Owned;
200 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000201
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000202 bool isNotOwned() const {
203 return getKind() == NotOwned;
204 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000205
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000206 bool isReturnedOwned() const {
207 return getKind() == ReturnedOwned;
208 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000209
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000210 bool isReturnedNotOwned() const {
211 return getKind() == ReturnedNotOwned;
212 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000213
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000214 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
215 unsigned Count = 1) {
216 return RefVal(Owned, o, Count, 0, t);
217 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000218
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000219 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
220 unsigned Count = 0) {
221 return RefVal(NotOwned, o, Count, 0, t);
222 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000223
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000224 // Comparison, profiling, and pretty-printing.
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000225
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000226 bool operator==(const RefVal& X) const {
227 return kind == X.kind && Cnt == X.Cnt && T == X.T && ACnt == X.ACnt;
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+(size_t i) const {
236 return RefVal(getKind(), getObjKind(), getCount() + i,
237 getAutoreleaseCount(), getType());
238 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000239
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000240 RefVal operator^(Kind k) const {
241 return RefVal(k, getObjKind(), getCount(), getAutoreleaseCount(),
242 getType());
243 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000244
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000245 RefVal autorelease() const {
246 return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount()+1,
247 getType());
248 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000249
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000250 void Profile(llvm::FoldingSetNodeID& ID) const {
251 ID.AddInteger((unsigned) kind);
252 ID.AddInteger(Cnt);
253 ID.AddInteger(ACnt);
254 ID.Add(T);
255 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000256
Ted Kremenek9c378f72011-08-12 23:37:29 +0000257 void print(raw_ostream &Out) const;
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000258};
259
Ted Kremenek9c378f72011-08-12 23:37:29 +0000260void RefVal::print(raw_ostream &Out) const {
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000261 if (!T.isNull())
Jordy Rosedbd658e2011-08-28 19:11:56 +0000262 Out << "Tracked " << T.getAsString() << '/';
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000263
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000264 switch (getKind()) {
Jordy Rose910c4052011-09-02 06:44:22 +0000265 default: llvm_unreachable("Invalid RefVal kind");
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000266 case Owned: {
267 Out << "Owned";
268 unsigned cnt = getCount();
269 if (cnt) Out << " (+ " << cnt << ")";
270 break;
271 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000272
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000273 case NotOwned: {
274 Out << "NotOwned";
275 unsigned cnt = getCount();
276 if (cnt) Out << " (+ " << cnt << ")";
277 break;
278 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000279
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000280 case ReturnedOwned: {
281 Out << "ReturnedOwned";
282 unsigned cnt = getCount();
283 if (cnt) Out << " (+ " << cnt << ")";
284 break;
285 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000286
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000287 case ReturnedNotOwned: {
288 Out << "ReturnedNotOwned";
289 unsigned cnt = getCount();
290 if (cnt) Out << " (+ " << cnt << ")";
291 break;
292 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000293
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000294 case Released:
295 Out << "Released";
296 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000297
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000298 case ErrorDeallocGC:
299 Out << "-dealloc (GC)";
300 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000301
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000302 case ErrorDeallocNotOwned:
303 Out << "-dealloc (not-owned)";
304 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000305
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000306 case ErrorLeak:
307 Out << "Leaked";
308 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000309
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000310 case ErrorLeakReturned:
311 Out << "Leaked (Bad naming)";
312 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000313
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000314 case ErrorGCLeakReturned:
315 Out << "Leaked (GC-ed at return)";
316 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000317
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000318 case ErrorUseAfterRelease:
319 Out << "Use-After-Release [ERROR]";
320 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000321
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000322 case ErrorReleaseNotOwned:
323 Out << "Release of Not-Owned [ERROR]";
324 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000325
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000326 case RefVal::ErrorOverAutorelease:
327 Out << "Over autoreleased";
328 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000329
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000330 case RefVal::ErrorReturnedNotOwned:
331 Out << "Non-owned object returned instead of owned";
332 break;
333 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000334
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000335 if (ACnt) {
336 Out << " [ARC +" << ACnt << ']';
337 }
338}
339} //end anonymous namespace
340
341//===----------------------------------------------------------------------===//
342// RefBindings - State used to track object reference counts.
343//===----------------------------------------------------------------------===//
344
Jordan Rose166d5022012-11-02 01:54:06 +0000345REGISTER_MAP_WITH_PROGRAMSTATE(RefBindings, SymbolRef, RefVal)
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000346
Anna Zaks8d6b43c2012-08-14 00:36:15 +0000347static inline const RefVal *getRefBinding(ProgramStateRef State,
348 SymbolRef Sym) {
349 return State->get<RefBindings>(Sym);
350}
351
352static inline ProgramStateRef setRefBinding(ProgramStateRef State,
353 SymbolRef Sym, RefVal Val) {
354 return State->set<RefBindings>(Sym, Val);
355}
356
357static ProgramStateRef removeRefBinding(ProgramStateRef State, SymbolRef Sym) {
358 return State->remove<RefBindings>(Sym);
359}
360
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000361//===----------------------------------------------------------------------===//
Jordy Rose910c4052011-09-02 06:44:22 +0000362// Function/Method behavior summaries.
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000363//===----------------------------------------------------------------------===//
364
365namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000366class RetainSummary {
Jordy Roseef945882012-03-18 01:26:10 +0000367 /// Args - a map of (index, ArgEffect) pairs, where index
Ted Kremenek1bffd742008-05-06 15:44:25 +0000368 /// specifies the argument (starting from 0). This can be sparsely
369 /// populated; arguments with no entry in Args use 'DefaultArgEffect'.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000370 ArgEffects Args;
Mike Stump1eb44332009-09-09 15:08:12 +0000371
Ted Kremenek1bffd742008-05-06 15:44:25 +0000372 /// DefaultArgEffect - The default ArgEffect to apply to arguments that
373 /// do not have an entry in Args.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000374 ArgEffect DefaultArgEffect;
Mike Stump1eb44332009-09-09 15:08:12 +0000375
Ted Kremenek553cf182008-06-25 21:21:56 +0000376 /// Receiver - If this summary applies to an Objective-C message expression,
377 /// this is the effect applied to the state of the receiver.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000378 ArgEffect Receiver;
Mike Stump1eb44332009-09-09 15:08:12 +0000379
Ted Kremenek553cf182008-06-25 21:21:56 +0000380 /// Ret - The effect on the return value. Used to indicate if the
Jordy Rose76c506f2011-08-21 21:58:18 +0000381 /// function/method call returns a new tracked symbol.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000382 RetEffect Ret;
Mike Stump1eb44332009-09-09 15:08:12 +0000383
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000384public:
Ted Kremenekb77449c2009-05-03 05:20:50 +0000385 RetainSummary(ArgEffects A, RetEffect R, ArgEffect defaultEff,
Jordy Rosee62e87b2011-08-20 20:55:40 +0000386 ArgEffect ReceiverEff)
387 : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000388
Ted Kremenek553cf182008-06-25 21:21:56 +0000389 /// getArg - Return the argument effect on the argument specified by
390 /// idx (starting from 0).
Ted Kremenek1ac08d62008-03-11 17:48:22 +0000391 ArgEffect getArg(unsigned idx) const {
Ted Kremenekb77449c2009-05-03 05:20:50 +0000392 if (const ArgEffect *AE = Args.lookup(idx))
393 return *AE;
Mike Stump1eb44332009-09-09 15:08:12 +0000394
Ted Kremenek1bffd742008-05-06 15:44:25 +0000395 return DefaultArgEffect;
Ted Kremenek1ac08d62008-03-11 17:48:22 +0000396 }
Ted Kremenek11fe1752011-01-27 18:43:03 +0000397
398 void addArg(ArgEffects::Factory &af, unsigned idx, ArgEffect e) {
399 Args = af.add(Args, idx, e);
400 }
Mike Stump1eb44332009-09-09 15:08:12 +0000401
Ted Kremenek885c27b2009-05-04 05:31:22 +0000402 /// setDefaultArgEffect - Set the default argument effect.
403 void setDefaultArgEffect(ArgEffect E) {
404 DefaultArgEffect = E;
405 }
Mike Stump1eb44332009-09-09 15:08:12 +0000406
Ted Kremenek553cf182008-06-25 21:21:56 +0000407 /// getRetEffect - Returns the effect on the return value of the call.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000408 RetEffect getRetEffect() const { return Ret; }
Mike Stump1eb44332009-09-09 15:08:12 +0000409
Ted Kremenek885c27b2009-05-04 05:31:22 +0000410 /// setRetEffect - Set the effect of the return value of the call.
411 void setRetEffect(RetEffect E) { Ret = E; }
Mike Stump1eb44332009-09-09 15:08:12 +0000412
Ted Kremenek12b94342011-01-27 06:54:14 +0000413
414 /// Sets the effect on the receiver of the message.
415 void setReceiverEffect(ArgEffect e) { Receiver = e; }
416
Ted Kremenek553cf182008-06-25 21:21:56 +0000417 /// getReceiverEffect - Returns the effect on the receiver of the call.
418 /// This is only meaningful if the summary applies to an ObjCMessageExpr*.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000419 ArgEffect getReceiverEffect() const { return Receiver; }
Jordy Rose4df54fe2011-08-23 04:27:15 +0000420
421 /// Test if two retain summaries are identical. Note that merely equivalent
422 /// summaries are not necessarily identical (for example, if an explicit
423 /// argument effect matches the default effect).
424 bool operator==(const RetainSummary &Other) const {
425 return Args == Other.Args && DefaultArgEffect == Other.DefaultArgEffect &&
426 Receiver == Other.Receiver && Ret == Other.Ret;
427 }
Jordy Roseef945882012-03-18 01:26:10 +0000428
429 /// Profile this summary for inclusion in a FoldingSet.
430 void Profile(llvm::FoldingSetNodeID& ID) const {
431 ID.Add(Args);
432 ID.Add(DefaultArgEffect);
433 ID.Add(Receiver);
434 ID.Add(Ret);
435 }
436
437 /// A retain summary is simple if it has no ArgEffects other than the default.
438 bool isSimple() const {
439 return Args.isEmpty();
440 }
Jordan Rose4531b7d2012-07-02 19:27:43 +0000441
442private:
443 ArgEffects getArgEffects() const { return Args; }
444 ArgEffect getDefaultArgEffect() const { return DefaultArgEffect; }
445
446 friend class RetainSummaryManager;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000447};
Ted Kremenek4f22a782008-06-23 23:30:29 +0000448} // end anonymous namespace
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000449
Ted Kremenek553cf182008-06-25 21:21:56 +0000450//===----------------------------------------------------------------------===//
451// Data structures for constructing summaries.
452//===----------------------------------------------------------------------===//
Ted Kremenek53301ba2008-06-24 03:49:48 +0000453
Ted Kremenek553cf182008-06-25 21:21:56 +0000454namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000455class ObjCSummaryKey {
Ted Kremenek553cf182008-06-25 21:21:56 +0000456 IdentifierInfo* II;
457 Selector S;
Mike Stump1eb44332009-09-09 15:08:12 +0000458public:
Ted Kremenek553cf182008-06-25 21:21:56 +0000459 ObjCSummaryKey(IdentifierInfo* ii, Selector s)
460 : II(ii), S(s) {}
461
Ted Kremenek9c378f72011-08-12 23:37:29 +0000462 ObjCSummaryKey(const ObjCInterfaceDecl *d, Selector s)
Ted Kremenek553cf182008-06-25 21:21:56 +0000463 : II(d ? d->getIdentifier() : 0), S(s) {}
Ted Kremenek70b6a832009-05-13 18:16:01 +0000464
Ted Kremenek553cf182008-06-25 21:21:56 +0000465 ObjCSummaryKey(Selector s)
466 : II(0), S(s) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000467
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000468 IdentifierInfo *getIdentifier() const { return II; }
Ted Kremenek553cf182008-06-25 21:21:56 +0000469 Selector getSelector() const { return S; }
470};
Ted Kremenek4f22a782008-06-23 23:30:29 +0000471}
472
473namespace llvm {
Ted Kremenek553cf182008-06-25 21:21:56 +0000474template <> struct DenseMapInfo<ObjCSummaryKey> {
475 static inline ObjCSummaryKey getEmptyKey() {
476 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
477 DenseMapInfo<Selector>::getEmptyKey());
478 }
Mike Stump1eb44332009-09-09 15:08:12 +0000479
Ted Kremenek553cf182008-06-25 21:21:56 +0000480 static inline ObjCSummaryKey getTombstoneKey() {
481 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
Mike Stump1eb44332009-09-09 15:08:12 +0000482 DenseMapInfo<Selector>::getTombstoneKey());
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 unsigned getHashValue(const ObjCSummaryKey &V) {
Benjamin Kramer28b23072012-05-27 13:28:44 +0000486 typedef std::pair<IdentifierInfo*, Selector> PairTy;
487 return DenseMapInfo<PairTy>::getHashValue(PairTy(V.getIdentifier(),
488 V.getSelector()));
Ted Kremenek553cf182008-06-25 21:21:56 +0000489 }
Mike Stump1eb44332009-09-09 15:08:12 +0000490
Ted Kremenek553cf182008-06-25 21:21:56 +0000491 static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
Benjamin Kramer28b23072012-05-27 13:28:44 +0000492 return LHS.getIdentifier() == RHS.getIdentifier() &&
493 LHS.getSelector() == RHS.getSelector();
Ted Kremenek553cf182008-06-25 21:21:56 +0000494 }
Mike Stump1eb44332009-09-09 15:08:12 +0000495
Ted Kremenek553cf182008-06-25 21:21:56 +0000496};
Chris Lattner06159e82009-12-15 07:26:51 +0000497template <>
498struct isPodLike<ObjCSummaryKey> { static const bool value = true; };
Ted Kremenek4f22a782008-06-23 23:30:29 +0000499} // end llvm namespace
Mike Stump1eb44332009-09-09 15:08:12 +0000500
Ted Kremenek4f22a782008-06-23 23:30:29 +0000501namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000502class ObjCSummaryCache {
Ted Kremenek93edbc52011-10-05 23:54:29 +0000503 typedef llvm::DenseMap<ObjCSummaryKey, const RetainSummary *> MapTy;
Ted Kremenek553cf182008-06-25 21:21:56 +0000504 MapTy M;
505public:
506 ObjCSummaryCache() {}
Mike Stump1eb44332009-09-09 15:08:12 +0000507
Ted Kremenek93edbc52011-10-05 23:54:29 +0000508 const RetainSummary * find(const ObjCInterfaceDecl *D, Selector S) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000509 // Do a lookup with the (D,S) pair. If we find a match return
510 // the iterator.
511 ObjCSummaryKey K(D, S);
512 MapTy::iterator I = M.find(K);
Mike Stump1eb44332009-09-09 15:08:12 +0000513
Jordan Rose4531b7d2012-07-02 19:27:43 +0000514 if (I != M.end())
Ted Kremenek614cc542009-07-21 23:27:57 +0000515 return I->second;
Jordan Rose4531b7d2012-07-02 19:27:43 +0000516 if (!D)
517 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +0000518
Ted Kremenek553cf182008-06-25 21:21:56 +0000519 // Walk the super chain. If we find a hit with a parent, we'll end
520 // up returning that summary. We actually allow that key (null,S), as
521 // we cache summaries for the null ObjCInterfaceDecl* to allow us to
522 // generate initial summaries without having to worry about NSObject
523 // being declared.
524 // FIXME: We may change this at some point.
Ted Kremenek9c378f72011-08-12 23:37:29 +0000525 for (ObjCInterfaceDecl *C=D->getSuperClass() ;; C=C->getSuperClass()) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000526 if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
527 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000528
Ted Kremenek553cf182008-06-25 21:21:56 +0000529 if (!C)
Ted Kremenek614cc542009-07-21 23:27:57 +0000530 return NULL;
Ted Kremenek553cf182008-06-25 21:21:56 +0000531 }
Mike Stump1eb44332009-09-09 15:08:12 +0000532
533 // Cache the summary with original key to make the next lookup faster
Ted Kremenek553cf182008-06-25 21:21:56 +0000534 // and return the iterator.
Ted Kremenek93edbc52011-10-05 23:54:29 +0000535 const RetainSummary *Summ = I->second;
Ted Kremenek614cc542009-07-21 23:27:57 +0000536 M[K] = Summ;
537 return Summ;
Ted Kremenek553cf182008-06-25 21:21:56 +0000538 }
Mike Stump1eb44332009-09-09 15:08:12 +0000539
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000540 const RetainSummary *find(IdentifierInfo* II, Selector S) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000541 // FIXME: Class method lookup. Right now we dont' have a good way
542 // of going between IdentifierInfo* and the class hierarchy.
Ted Kremenek614cc542009-07-21 23:27:57 +0000543 MapTy::iterator I = M.find(ObjCSummaryKey(II, S));
Mike Stump1eb44332009-09-09 15:08:12 +0000544
Ted Kremenek614cc542009-07-21 23:27:57 +0000545 if (I == M.end())
546 I = M.find(ObjCSummaryKey(S));
Mike Stump1eb44332009-09-09 15:08:12 +0000547
Ted Kremenek614cc542009-07-21 23:27:57 +0000548 return I == M.end() ? NULL : I->second;
Ted Kremenek553cf182008-06-25 21:21:56 +0000549 }
Mike Stump1eb44332009-09-09 15:08:12 +0000550
Ted Kremenek93edbc52011-10-05 23:54:29 +0000551 const RetainSummary *& operator[](ObjCSummaryKey K) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000552 return M[K];
553 }
Mike Stump1eb44332009-09-09 15:08:12 +0000554
Ted Kremenek93edbc52011-10-05 23:54:29 +0000555 const RetainSummary *& operator[](Selector S) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000556 return M[ ObjCSummaryKey(S) ];
557 }
Mike Stump1eb44332009-09-09 15:08:12 +0000558};
Ted Kremenek553cf182008-06-25 21:21:56 +0000559} // end anonymous namespace
560
561//===----------------------------------------------------------------------===//
562// Data structures for managing collections of summaries.
563//===----------------------------------------------------------------------===//
564
565namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000566class RetainSummaryManager {
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000567
568 //==-----------------------------------------------------------------==//
569 // Typedefs.
570 //==-----------------------------------------------------------------==//
Mike Stump1eb44332009-09-09 15:08:12 +0000571
Ted Kremenek93edbc52011-10-05 23:54:29 +0000572 typedef llvm::DenseMap<const FunctionDecl*, const RetainSummary *>
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000573 FuncSummariesTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000574
Ted Kremenek4f22a782008-06-23 23:30:29 +0000575 typedef ObjCSummaryCache ObjCMethodSummariesTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000576
Jordy Roseef945882012-03-18 01:26:10 +0000577 typedef llvm::FoldingSetNodeWrapper<RetainSummary> CachedSummaryNode;
578
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000579 //==-----------------------------------------------------------------==//
580 // Data.
581 //==-----------------------------------------------------------------==//
Mike Stump1eb44332009-09-09 15:08:12 +0000582
Ted Kremenek553cf182008-06-25 21:21:56 +0000583 /// Ctx - The ASTContext object for the analyzed ASTs.
Ted Kremenek9c378f72011-08-12 23:37:29 +0000584 ASTContext &Ctx;
Ted Kremenek179064e2008-07-01 17:21:27 +0000585
Ted Kremenek553cf182008-06-25 21:21:56 +0000586 /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
Ted Kremenek377e2302008-04-29 05:33:51 +0000587 const bool GCEnabled;
Mike Stump1eb44332009-09-09 15:08:12 +0000588
John McCallf85e1932011-06-15 23:02:42 +0000589 /// Records whether or not the analyzed code runs in ARC mode.
590 const bool ARCEnabled;
591
Ted Kremenek553cf182008-06-25 21:21:56 +0000592 /// FuncSummaries - A map from FunctionDecls to summaries.
Mike Stump1eb44332009-09-09 15:08:12 +0000593 FuncSummariesTy FuncSummaries;
594
Ted Kremenek553cf182008-06-25 21:21:56 +0000595 /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
596 /// to summaries.
Ted Kremenek1f180c32008-06-23 22:21:20 +0000597 ObjCMethodSummariesTy ObjCClassMethodSummaries;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000598
Ted Kremenek553cf182008-06-25 21:21:56 +0000599 /// ObjCMethodSummaries - A map from selectors to summaries.
Ted Kremenek1f180c32008-06-23 22:21:20 +0000600 ObjCMethodSummariesTy ObjCMethodSummaries;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000601
Ted Kremenek553cf182008-06-25 21:21:56 +0000602 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
603 /// and all other data used by the checker.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000604 llvm::BumpPtrAllocator BPAlloc;
Mike Stump1eb44332009-09-09 15:08:12 +0000605
Ted Kremenekb77449c2009-05-03 05:20:50 +0000606 /// AF - A factory for ArgEffects objects.
Mike Stump1eb44332009-09-09 15:08:12 +0000607 ArgEffects::Factory AF;
608
Ted Kremenek553cf182008-06-25 21:21:56 +0000609 /// ScratchArgs - A holding buffer for construct ArgEffects.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000610 ArgEffects ScratchArgs;
Mike Stump1eb44332009-09-09 15:08:12 +0000611
Ted Kremenekec315332009-05-07 23:40:42 +0000612 /// ObjCAllocRetE - Default return effect for methods returning Objective-C
613 /// objects.
614 RetEffect ObjCAllocRetE;
Ted Kremenek547d4952009-06-05 23:18:01 +0000615
Mike Stump1eb44332009-09-09 15:08:12 +0000616 /// ObjCInitRetE - Default return effect for init methods returning
Ted Kremenekac02f202009-08-20 05:13:36 +0000617 /// Objective-C objects.
Ted Kremenek547d4952009-06-05 23:18:01 +0000618 RetEffect ObjCInitRetE;
Mike Stump1eb44332009-09-09 15:08:12 +0000619
Jordy Roseef945882012-03-18 01:26:10 +0000620 /// SimpleSummaries - Used for uniquing summaries that don't have special
621 /// effects.
622 llvm::FoldingSet<CachedSummaryNode> SimpleSummaries;
Mike Stump1eb44332009-09-09 15:08:12 +0000623
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000624 //==-----------------------------------------------------------------==//
625 // Methods.
626 //==-----------------------------------------------------------------==//
Mike Stump1eb44332009-09-09 15:08:12 +0000627
Ted Kremenek553cf182008-06-25 21:21:56 +0000628 /// getArgEffects - Returns a persistent ArgEffects object based on the
629 /// data in ScratchArgs.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000630 ArgEffects getArgEffects();
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000631
Mike Stump1eb44332009-09-09 15:08:12 +0000632 enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
Ted Kremenek93edbc52011-10-05 23:54:29 +0000633
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000634 const RetainSummary *getUnarySummary(const FunctionType* FT,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000635 UnaryFuncKind func);
Mike Stump1eb44332009-09-09 15:08:12 +0000636
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000637 const RetainSummary *getCFSummaryCreateRule(const FunctionDecl *FD);
638 const RetainSummary *getCFSummaryGetRule(const FunctionDecl *FD);
639 const RetainSummary *getCFCreateGetRuleSummary(const FunctionDecl *FD);
Mike Stump1eb44332009-09-09 15:08:12 +0000640
Jordy Roseef945882012-03-18 01:26:10 +0000641 const RetainSummary *getPersistentSummary(const RetainSummary &OldSumm);
Ted Kremenek706522f2008-10-29 04:07:07 +0000642
Jordy Roseef945882012-03-18 01:26:10 +0000643 const RetainSummary *getPersistentSummary(RetEffect RetEff,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000644 ArgEffect ReceiverEff = DoNothing,
645 ArgEffect DefaultEff = MayEscape) {
Jordy Roseef945882012-03-18 01:26:10 +0000646 RetainSummary Summ(getArgEffects(), RetEff, DefaultEff, ReceiverEff);
647 return getPersistentSummary(Summ);
648 }
649
Ted Kremenekc91fdf62012-05-08 00:12:09 +0000650 const RetainSummary *getDoNothingSummary() {
651 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
652 }
653
Jordy Roseef945882012-03-18 01:26:10 +0000654 const RetainSummary *getDefaultSummary() {
655 return getPersistentSummary(RetEffect::MakeNoRet(),
656 DoNothing, MayEscape);
Ted Kremenek9c32d082008-05-06 00:30:21 +0000657 }
Mike Stump1eb44332009-09-09 15:08:12 +0000658
Ted Kremenek93edbc52011-10-05 23:54:29 +0000659 const RetainSummary *getPersistentStopSummary() {
Jordy Roseef945882012-03-18 01:26:10 +0000660 return getPersistentSummary(RetEffect::MakeNoRet(),
661 StopTracking, StopTracking);
Mike Stump1eb44332009-09-09 15:08:12 +0000662 }
Ted Kremenekb3095252008-05-06 04:20:12 +0000663
Ted Kremenek1f180c32008-06-23 22:21:20 +0000664 void InitializeClassMethodSummaries();
665 void InitializeMethodSummaries();
Ted Kremenek896cd9d2008-10-23 01:56:15 +0000666private:
Ted Kremenek93edbc52011-10-05 23:54:29 +0000667 void addNSObjectClsMethSummary(Selector S, const RetainSummary *Summ) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000668 ObjCClassMethodSummaries[S] = Summ;
669 }
Mike Stump1eb44332009-09-09 15:08:12 +0000670
Ted Kremenek93edbc52011-10-05 23:54:29 +0000671 void addNSObjectMethSummary(Selector S, const RetainSummary *Summ) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000672 ObjCMethodSummaries[S] = Summ;
673 }
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +0000674
Ted Kremeneka9797122012-02-18 21:37:48 +0000675 void addClassMethSummary(const char* Cls, const char* name,
676 const RetainSummary *Summ, bool isNullary = true) {
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +0000677 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
Ted Kremeneka9797122012-02-18 21:37:48 +0000678 Selector S = isNullary ? GetNullarySelector(name, Ctx)
679 : GetUnarySelector(name, Ctx);
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +0000680 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
681 }
Mike Stump1eb44332009-09-09 15:08:12 +0000682
Ted Kremenek6c4becb2009-02-25 02:54:57 +0000683 void addInstMethSummary(const char* Cls, const char* nullaryName,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000684 const RetainSummary *Summ) {
Ted Kremenek6c4becb2009-02-25 02:54:57 +0000685 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
686 Selector S = GetNullarySelector(nullaryName, Ctx);
687 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
688 }
Mike Stump1eb44332009-09-09 15:08:12 +0000689
Ted Kremenekde4d5332009-04-24 17:50:11 +0000690 Selector generateSelector(va_list argp) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000691 SmallVector<IdentifierInfo*, 10> II;
Ted Kremenekde4d5332009-04-24 17:50:11 +0000692
Ted Kremenek9e476de2008-08-12 18:30:56 +0000693 while (const char* s = va_arg(argp, const char*))
694 II.push_back(&Ctx.Idents.get(s));
Ted Kremenekde4d5332009-04-24 17:50:11 +0000695
Mike Stump1eb44332009-09-09 15:08:12 +0000696 return Ctx.Selectors.getSelector(II.size(), &II[0]);
Ted Kremenekde4d5332009-04-24 17:50:11 +0000697 }
Mike Stump1eb44332009-09-09 15:08:12 +0000698
Ted Kremenekde4d5332009-04-24 17:50:11 +0000699 void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy& Summaries,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000700 const RetainSummary * Summ, va_list argp) {
Ted Kremenekde4d5332009-04-24 17:50:11 +0000701 Selector S = generateSelector(argp);
702 Summaries[ObjCSummaryKey(ClsII, S)] = Summ;
Ted Kremenek70a733e2008-07-18 17:24:20 +0000703 }
Mike Stump1eb44332009-09-09 15:08:12 +0000704
Ted Kremenek93edbc52011-10-05 23:54:29 +0000705 void addInstMethSummary(const char* Cls, const RetainSummary * Summ, ...) {
Ted Kremenekaf9dc272008-08-12 18:48:50 +0000706 va_list argp;
707 va_start(argp, Summ);
Ted Kremenekde4d5332009-04-24 17:50:11 +0000708 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Mike Stump1eb44332009-09-09 15:08:12 +0000709 va_end(argp);
Ted Kremenekaf9dc272008-08-12 18:48:50 +0000710 }
Mike Stump1eb44332009-09-09 15:08:12 +0000711
Ted Kremenek93edbc52011-10-05 23:54:29 +0000712 void addClsMethSummary(const char* Cls, const RetainSummary * Summ, ...) {
Ted Kremenekde4d5332009-04-24 17:50:11 +0000713 va_list argp;
714 va_start(argp, Summ);
715 addMethodSummary(&Ctx.Idents.get(Cls),ObjCClassMethodSummaries, Summ, argp);
716 va_end(argp);
717 }
Mike Stump1eb44332009-09-09 15:08:12 +0000718
Ted Kremenek93edbc52011-10-05 23:54:29 +0000719 void addClsMethSummary(IdentifierInfo *II, const RetainSummary * Summ, ...) {
Ted Kremenekde4d5332009-04-24 17:50:11 +0000720 va_list argp;
721 va_start(argp, Summ);
722 addMethodSummary(II, ObjCClassMethodSummaries, Summ, argp);
723 va_end(argp);
724 }
725
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000726public:
Mike Stump1eb44332009-09-09 15:08:12 +0000727
Ted Kremenek9c378f72011-08-12 23:37:29 +0000728 RetainSummaryManager(ASTContext &ctx, bool gcenabled, bool usesARC)
Ted Kremenek179064e2008-07-01 17:21:27 +0000729 : Ctx(ctx),
John McCallf85e1932011-06-15 23:02:42 +0000730 GCEnabled(gcenabled),
731 ARCEnabled(usesARC),
732 AF(BPAlloc), ScratchArgs(AF.getEmptyMap()),
733 ObjCAllocRetE(gcenabled
734 ? RetEffect::MakeGCNotOwned()
735 : (usesARC ? RetEffect::MakeARCNotOwned()
736 : RetEffect::MakeOwned(RetEffect::ObjC, true))),
737 ObjCInitRetE(gcenabled
738 ? RetEffect::MakeGCNotOwned()
739 : (usesARC ? RetEffect::MakeARCNotOwned()
Jordy Roseef945882012-03-18 01:26:10 +0000740 : RetEffect::MakeOwnedWhenTrackedReceiver())) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000741 InitializeClassMethodSummaries();
742 InitializeMethodSummaries();
743 }
Mike Stump1eb44332009-09-09 15:08:12 +0000744
Jordan Rose4531b7d2012-07-02 19:27:43 +0000745 const RetainSummary *getSummary(const CallEvent &Call,
746 ProgramStateRef State = 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000747
Jordan Rose4531b7d2012-07-02 19:27:43 +0000748 const RetainSummary *getFunctionSummary(const FunctionDecl *FD);
749
750 const RetainSummary *getMethodSummary(Selector S, const ObjCInterfaceDecl *ID,
Jordy Rosef3aae582012-03-17 21:13:07 +0000751 const ObjCMethodDecl *MD,
752 QualType RetTy,
753 ObjCMethodSummariesTy &CachedSummaries);
754
Jordan Rosecde8cdb2012-07-02 19:27:56 +0000755 const RetainSummary *getInstanceMethodSummary(const ObjCMethodCall &M,
Jordan Rose4531b7d2012-07-02 19:27:43 +0000756 ProgramStateRef State);
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000757
Jordan Rosecde8cdb2012-07-02 19:27:56 +0000758 const RetainSummary *getClassMethodSummary(const ObjCMethodCall &M) {
Jordan Rose4531b7d2012-07-02 19:27:43 +0000759 assert(!M.isInstanceMessage());
760 const ObjCInterfaceDecl *Class = M.getReceiverInterface();
Mike Stump1eb44332009-09-09 15:08:12 +0000761
Jordan Rose4531b7d2012-07-02 19:27:43 +0000762 return getMethodSummary(M.getSelector(), Class, M.getDecl(),
763 M.getResultType(), ObjCClassMethodSummaries);
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +0000764 }
Ted Kremenek552333c2009-04-29 17:17:48 +0000765
766 /// getMethodSummary - This version of getMethodSummary is used to query
767 /// the summary for the current method being analyzed.
Ted Kremenek93edbc52011-10-05 23:54:29 +0000768 const RetainSummary *getMethodSummary(const ObjCMethodDecl *MD) {
Ted Kremeneka8833552009-04-29 23:03:22 +0000769 const ObjCInterfaceDecl *ID = MD->getClassInterface();
Ted Kremenek70a65762009-04-30 05:41:14 +0000770 Selector S = MD->getSelector();
Ted Kremenek552333c2009-04-29 17:17:48 +0000771 QualType ResultTy = MD->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +0000772
Jordy Rosef3aae582012-03-17 21:13:07 +0000773 ObjCMethodSummariesTy *CachedSummaries;
Ted Kremenek552333c2009-04-29 17:17:48 +0000774 if (MD->isInstanceMethod())
Jordy Rosef3aae582012-03-17 21:13:07 +0000775 CachedSummaries = &ObjCMethodSummaries;
Ted Kremenek552333c2009-04-29 17:17:48 +0000776 else
Jordy Rosef3aae582012-03-17 21:13:07 +0000777 CachedSummaries = &ObjCClassMethodSummaries;
778
Jordan Rose4531b7d2012-07-02 19:27:43 +0000779 return getMethodSummary(S, ID, MD, ResultTy, *CachedSummaries);
Ted Kremenek552333c2009-04-29 17:17:48 +0000780 }
Mike Stump1eb44332009-09-09 15:08:12 +0000781
Jordy Rosef3aae582012-03-17 21:13:07 +0000782 const RetainSummary *getStandardMethodSummary(const ObjCMethodDecl *MD,
Jordan Rose4531b7d2012-07-02 19:27:43 +0000783 Selector S, QualType RetTy);
Ted Kremeneka8833552009-04-29 23:03:22 +0000784
Ted Kremenek93edbc52011-10-05 23:54:29 +0000785 void updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenek4dd8fb42009-05-09 02:58:13 +0000786 const ObjCMethodDecl *MD);
787
Ted Kremenek93edbc52011-10-05 23:54:29 +0000788 void updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenek4dd8fb42009-05-09 02:58:13 +0000789 const FunctionDecl *FD);
790
Jordan Rose4531b7d2012-07-02 19:27:43 +0000791 void updateSummaryForCall(const RetainSummary *&Summ,
792 const CallEvent &Call);
793
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000794 bool isGCEnabled() const { return GCEnabled; }
Mike Stump1eb44332009-09-09 15:08:12 +0000795
John McCallf85e1932011-06-15 23:02:42 +0000796 bool isARCEnabled() const { return ARCEnabled; }
797
798 bool isARCorGCEnabled() const { return GCEnabled || ARCEnabled; }
Jordan Rose4531b7d2012-07-02 19:27:43 +0000799
800 RetEffect getObjAllocRetEffect() const { return ObjCAllocRetE; }
801
802 friend class RetainSummaryTemplate;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000803};
Mike Stump1eb44332009-09-09 15:08:12 +0000804
Jordy Rose0fe62f82011-08-24 09:02:37 +0000805// Used to avoid allocating long-term (BPAlloc'd) memory for default retain
806// summaries. If a function or method looks like it has a default summary, but
807// it has annotations, the annotations are added to the stack-based template
808// and then copied into managed memory.
809class RetainSummaryTemplate {
810 RetainSummaryManager &Manager;
Ted Kremenek93edbc52011-10-05 23:54:29 +0000811 const RetainSummary *&RealSummary;
Jordy Rose0fe62f82011-08-24 09:02:37 +0000812 RetainSummary ScratchSummary;
813 bool Accessed;
814public:
Jordan Rose4531b7d2012-07-02 19:27:43 +0000815 RetainSummaryTemplate(const RetainSummary *&real, RetainSummaryManager &mgr)
816 : Manager(mgr), RealSummary(real), ScratchSummary(*real), Accessed(false) {}
Jordy Rose0fe62f82011-08-24 09:02:37 +0000817
818 ~RetainSummaryTemplate() {
Ted Kremenek93edbc52011-10-05 23:54:29 +0000819 if (Accessed)
Jordy Roseef945882012-03-18 01:26:10 +0000820 RealSummary = Manager.getPersistentSummary(ScratchSummary);
Jordy Rose0fe62f82011-08-24 09:02:37 +0000821 }
822
823 RetainSummary &operator*() {
824 Accessed = true;
Ted Kremenek93edbc52011-10-05 23:54:29 +0000825 return ScratchSummary;
Jordy Rose0fe62f82011-08-24 09:02:37 +0000826 }
827
828 RetainSummary *operator->() {
829 Accessed = true;
Ted Kremenek93edbc52011-10-05 23:54:29 +0000830 return &ScratchSummary;
Jordy Rose0fe62f82011-08-24 09:02:37 +0000831 }
832};
833
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000834} // end anonymous namespace
835
836//===----------------------------------------------------------------------===//
837// Implementation of checker data structures.
838//===----------------------------------------------------------------------===//
839
Ted Kremenekb77449c2009-05-03 05:20:50 +0000840ArgEffects RetainSummaryManager::getArgEffects() {
841 ArgEffects AE = ScratchArgs;
Ted Kremenek3baf6722010-11-24 00:54:37 +0000842 ScratchArgs = AF.getEmptyMap();
Ted Kremenekb77449c2009-05-03 05:20:50 +0000843 return AE;
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000844}
845
Ted Kremenek93edbc52011-10-05 23:54:29 +0000846const RetainSummary *
Jordy Roseef945882012-03-18 01:26:10 +0000847RetainSummaryManager::getPersistentSummary(const RetainSummary &OldSumm) {
848 // Unique "simple" summaries -- those without ArgEffects.
849 if (OldSumm.isSimple()) {
850 llvm::FoldingSetNodeID ID;
851 OldSumm.Profile(ID);
852
853 void *Pos;
854 CachedSummaryNode *N = SimpleSummaries.FindNodeOrInsertPos(ID, Pos);
855
856 if (!N) {
857 N = (CachedSummaryNode *) BPAlloc.Allocate<CachedSummaryNode>();
858 new (N) CachedSummaryNode(OldSumm);
859 SimpleSummaries.InsertNode(N, Pos);
860 }
861
862 return &N->getValue();
863 }
864
Ted Kremenek93edbc52011-10-05 23:54:29 +0000865 RetainSummary *Summ = (RetainSummary *) BPAlloc.Allocate<RetainSummary>();
Jordy Roseef945882012-03-18 01:26:10 +0000866 new (Summ) RetainSummary(OldSumm);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000867 return Summ;
868}
869
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000870//===----------------------------------------------------------------------===//
871// Summary creation for functions (largely uses of Core Foundation).
872//===----------------------------------------------------------------------===//
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000873
Ted Kremenek9c378f72011-08-12 23:37:29 +0000874static bool isRetain(const FunctionDecl *FD, StringRef FName) {
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000875 return FName.endswith("Retain");
Ted Kremenek12619382009-01-12 21:45:02 +0000876}
877
Ted Kremenek9c378f72011-08-12 23:37:29 +0000878static bool isRelease(const FunctionDecl *FD, StringRef FName) {
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000879 return FName.endswith("Release");
Ted Kremenek12619382009-01-12 21:45:02 +0000880}
881
Jordy Rose76c506f2011-08-21 21:58:18 +0000882static bool isMakeCollectable(const FunctionDecl *FD, StringRef FName) {
883 // FIXME: Remove FunctionDecl parameter.
884 // FIXME: Is it really okay if MakeCollectable isn't a suffix?
885 return FName.find("MakeCollectable") != StringRef::npos;
886}
887
Anna Zaks554067f2012-08-29 23:23:43 +0000888static ArgEffect getStopTrackingHardEquivalent(ArgEffect E) {
Jordan Rose4531b7d2012-07-02 19:27:43 +0000889 switch (E) {
890 case DoNothing:
891 case Autorelease:
892 case DecRefBridgedTransfered:
893 case IncRef:
894 case IncRefMsg:
895 case MakeCollectable:
896 case MayEscape:
897 case NewAutoreleasePool:
898 case StopTracking:
Anna Zaks554067f2012-08-29 23:23:43 +0000899 case StopTrackingHard:
900 return StopTrackingHard;
Jordan Rose4531b7d2012-07-02 19:27:43 +0000901 case DecRef:
Anna Zaks554067f2012-08-29 23:23:43 +0000902 case DecRefAndStopTrackingHard:
903 return DecRefAndStopTrackingHard;
Jordan Rose4531b7d2012-07-02 19:27:43 +0000904 case DecRefMsg:
Anna Zaks554067f2012-08-29 23:23:43 +0000905 case DecRefMsgAndStopTrackingHard:
906 return DecRefMsgAndStopTrackingHard;
Jordan Rose4531b7d2012-07-02 19:27:43 +0000907 case Dealloc:
908 return Dealloc;
909 }
910
911 llvm_unreachable("Unknown ArgEffect kind");
912}
913
914void RetainSummaryManager::updateSummaryForCall(const RetainSummary *&S,
915 const CallEvent &Call) {
916 if (Call.hasNonZeroCallbackArg()) {
Anna Zaks554067f2012-08-29 23:23:43 +0000917 ArgEffect RecEffect =
918 getStopTrackingHardEquivalent(S->getReceiverEffect());
919 ArgEffect DefEffect =
920 getStopTrackingHardEquivalent(S->getDefaultArgEffect());
Jordan Rose4531b7d2012-07-02 19:27:43 +0000921
922 ArgEffects CustomArgEffects = S->getArgEffects();
923 for (ArgEffects::iterator I = CustomArgEffects.begin(),
924 E = CustomArgEffects.end();
925 I != E; ++I) {
Anna Zaks554067f2012-08-29 23:23:43 +0000926 ArgEffect Translated = getStopTrackingHardEquivalent(I->second);
Jordan Rose4531b7d2012-07-02 19:27:43 +0000927 if (Translated != DefEffect)
928 ScratchArgs = AF.add(ScratchArgs, I->first, Translated);
929 }
930
Anna Zaks554067f2012-08-29 23:23:43 +0000931 RetEffect RE = RetEffect::MakeNoRetHard();
Jordan Rose4531b7d2012-07-02 19:27:43 +0000932
933 // Special cases where the callback argument CANNOT free the return value.
934 // This can generally only happen if we know that the callback will only be
935 // called when the return value is already being deallocated.
936 if (const FunctionCall *FC = dyn_cast<FunctionCall>(&Call)) {
Jordan Rose4a25f302012-09-01 17:39:13 +0000937 if (IdentifierInfo *Name = FC->getDecl()->getIdentifier()) {
938 // When the CGBitmapContext is deallocated, the callback here will free
939 // the associated data buffer.
Jordan Rosea89f7192012-08-31 18:19:18 +0000940 if (Name->isStr("CGBitmapContextCreateWithData"))
941 RE = S->getRetEffect();
Jordan Rose4a25f302012-09-01 17:39:13 +0000942 }
Jordan Rose4531b7d2012-07-02 19:27:43 +0000943 }
944
945 S = getPersistentSummary(RE, RecEffect, DefEffect);
946 }
Anna Zaks5a901932012-08-24 00:06:12 +0000947
948 // Special case '[super init];' and '[self init];'
949 //
950 // Even though calling '[super init]' without assigning the result to self
951 // and checking if the parent returns 'nil' is a bad pattern, it is common.
952 // Additionally, our Self Init checker already warns about it. To avoid
953 // overwhelming the user with messages from both checkers, we model the case
954 // of '[super init]' in cases when it is not consumed by another expression
955 // as if the call preserves the value of 'self'; essentially, assuming it can
956 // never fail and return 'nil'.
957 // Note, we don't want to just stop tracking the value since we want the
958 // RetainCount checker to report leaks and use-after-free if SelfInit checker
959 // is turned off.
960 if (const ObjCMethodCall *MC = dyn_cast<ObjCMethodCall>(&Call)) {
961 if (MC->getMethodFamily() == OMF_init && MC->isReceiverSelfOrSuper()) {
962
963 // Check if the message is not consumed, we know it will not be used in
964 // an assignment, ex: "self = [super init]".
965 const Expr *ME = MC->getOriginExpr();
966 const LocationContext *LCtx = MC->getLocationContext();
967 ParentMap &PM = LCtx->getAnalysisDeclContext()->getParentMap();
968 if (!PM.isConsumedExpr(ME)) {
969 RetainSummaryTemplate ModifiableSummaryTemplate(S, *this);
970 ModifiableSummaryTemplate->setReceiverEffect(DoNothing);
971 ModifiableSummaryTemplate->setRetEffect(RetEffect::MakeNoRet());
972 }
973 }
974
975 }
Jordan Rose4531b7d2012-07-02 19:27:43 +0000976}
977
Anna Zaks58822c42012-05-04 22:18:39 +0000978const RetainSummary *
Jordan Rose4531b7d2012-07-02 19:27:43 +0000979RetainSummaryManager::getSummary(const CallEvent &Call,
980 ProgramStateRef State) {
981 const RetainSummary *Summ;
982 switch (Call.getKind()) {
983 case CE_Function:
984 Summ = getFunctionSummary(cast<FunctionCall>(Call).getDecl());
985 break;
986 case CE_CXXMember:
Jordan Rosefdaa3382012-07-03 22:55:57 +0000987 case CE_CXXMemberOperator:
Jordan Rose4531b7d2012-07-02 19:27:43 +0000988 case CE_Block:
989 case CE_CXXConstructor:
Jordan Rose8d276d32012-07-10 22:07:47 +0000990 case CE_CXXDestructor:
Jordan Rose70cbf3c2012-07-02 22:21:47 +0000991 case CE_CXXAllocator:
Jordan Rose4531b7d2012-07-02 19:27:43 +0000992 // FIXME: These calls are currently unsupported.
993 return getPersistentStopSummary();
Jordan Rose8919e682012-07-18 21:59:51 +0000994 case CE_ObjCMessage: {
Jordan Rosecde8cdb2012-07-02 19:27:56 +0000995 const ObjCMethodCall &Msg = cast<ObjCMethodCall>(Call);
Jordan Rose4531b7d2012-07-02 19:27:43 +0000996 if (Msg.isInstanceMessage())
997 Summ = getInstanceMethodSummary(Msg, State);
998 else
999 Summ = getClassMethodSummary(Msg);
1000 break;
1001 }
1002 }
1003
1004 updateSummaryForCall(Summ, Call);
1005
1006 assert(Summ && "Unknown call type?");
1007 return Summ;
1008}
1009
1010const RetainSummary *
1011RetainSummaryManager::getFunctionSummary(const FunctionDecl *FD) {
1012 // If we don't know what function we're calling, use our default summary.
1013 if (!FD)
1014 return getDefaultSummary();
1015
Ted Kremenek891d5cc2008-04-24 17:22:33 +00001016 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001017 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001018 if (I != FuncSummaries.end())
Ted Kremenek891d5cc2008-04-24 17:22:33 +00001019 return I->second;
1020
Ted Kremeneke401a0c2009-05-04 15:34:07 +00001021 // No summary? Generate one.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001022 const RetainSummary *S = 0;
Jordan Rose15d18e12012-08-06 21:28:02 +00001023 bool AllowAnnotations = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001024
Ted Kremenek37d785b2008-07-15 16:50:12 +00001025 do {
Ted Kremenek12619382009-01-12 21:45:02 +00001026 // We generate "stop" summaries for implicitly defined functions.
1027 if (FD->isImplicit()) {
1028 S = getPersistentStopSummary();
1029 break;
Ted Kremenek37d785b2008-07-15 16:50:12 +00001030 }
Mike Stump1eb44332009-09-09 15:08:12 +00001031
John McCall183700f2009-09-21 23:43:11 +00001032 // [PR 3337] Use 'getAs<FunctionType>' to strip away any typedefs on the
Ted Kremenek99890652009-01-16 18:40:33 +00001033 // function's type.
John McCall183700f2009-09-21 23:43:11 +00001034 const FunctionType* FT = FD->getType()->getAs<FunctionType>();
Ted Kremenek48c6d182009-12-16 06:06:43 +00001035 const IdentifierInfo *II = FD->getIdentifier();
1036 if (!II)
1037 break;
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001038
1039 StringRef FName = II->getName();
Mike Stump1eb44332009-09-09 15:08:12 +00001040
Ted Kremenekbf0a4dd2009-03-05 22:11:14 +00001041 // Strip away preceding '_'. Doing this here will effect all the checks
1042 // down below.
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001043 FName = FName.substr(FName.find_first_not_of('_'));
Mike Stump1eb44332009-09-09 15:08:12 +00001044
Ted Kremenek12619382009-01-12 21:45:02 +00001045 // Inspect the result type.
1046 QualType RetTy = FT->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00001047
Ted Kremenek12619382009-01-12 21:45:02 +00001048 // FIXME: This should all be refactored into a chain of "summary lookup"
1049 // filters.
Ted Kremenek008636a2009-10-14 00:27:24 +00001050 assert(ScratchArgs.isEmpty());
Ted Kremenek39d88b02009-06-15 20:36:07 +00001051
Ted Kremenekbefc6d22012-04-26 04:32:23 +00001052 if (FName == "pthread_create" || FName == "pthread_setspecific") {
1053 // Part of: <rdar://problem/7299394> and <rdar://problem/11282706>.
1054 // This will be addressed better with IPA.
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001055 S = getPersistentStopSummary();
1056 } else if (FName == "NSMakeCollectable") {
1057 // Handle: id NSMakeCollectable(CFTypeRef)
1058 S = (RetTy->isObjCIdType())
1059 ? getUnarySummary(FT, cfmakecollectable)
1060 : getPersistentStopSummary();
Jordan Rose15d18e12012-08-06 21:28:02 +00001061 // The headers on OS X 10.8 use cf_consumed/ns_returns_retained,
1062 // but we can fully model NSMakeCollectable ourselves.
1063 AllowAnnotations = false;
Ted Kremenek061707a2012-09-06 23:47:02 +00001064 } else if (FName == "CFPlugInInstanceCreate") {
1065 S = getPersistentSummary(RetEffect::MakeNoRet());
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001066 } else if (FName == "IOBSDNameMatching" ||
1067 FName == "IOServiceMatching" ||
1068 FName == "IOServiceNameMatching" ||
Ted Kremenek537dd3a2012-05-01 05:28:27 +00001069 FName == "IORegistryEntrySearchCFProperty" ||
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001070 FName == "IORegistryEntryIDMatching" ||
1071 FName == "IOOpenFirmwarePathMatching") {
1072 // Part of <rdar://problem/6961230>. (IOKit)
1073 // This should be addressed using a API table.
1074 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1075 DoNothing, DoNothing);
1076 } else if (FName == "IOServiceGetMatchingService" ||
1077 FName == "IOServiceGetMatchingServices") {
1078 // FIXES: <rdar://problem/6326900>
1079 // This should be addressed using a API table. This strcmp is also
1080 // a little gross, but there is no need to super optimize here.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001081 ScratchArgs = AF.add(ScratchArgs, 1, DecRef);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001082 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1083 } else if (FName == "IOServiceAddNotification" ||
1084 FName == "IOServiceAddMatchingNotification") {
1085 // Part of <rdar://problem/6961230>. (IOKit)
1086 // This should be addressed using a API table.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001087 ScratchArgs = AF.add(ScratchArgs, 2, DecRef);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001088 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1089 } else if (FName == "CVPixelBufferCreateWithBytes") {
1090 // FIXES: <rdar://problem/7283567>
1091 // Eventually this can be improved by recognizing that the pixel
1092 // buffer passed to CVPixelBufferCreateWithBytes is released via
1093 // a callback and doing full IPA to make sure this is done correctly.
1094 // FIXME: This function has an out parameter that returns an
1095 // allocated object.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001096 ScratchArgs = AF.add(ScratchArgs, 7, StopTracking);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001097 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1098 } else if (FName == "CGBitmapContextCreateWithData") {
1099 // FIXES: <rdar://problem/7358899>
1100 // Eventually this can be improved by recognizing that 'releaseInfo'
1101 // passed to CGBitmapContextCreateWithData is released via
1102 // a callback and doing full IPA to make sure this is done correctly.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001103 ScratchArgs = AF.add(ScratchArgs, 8, StopTracking);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001104 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1105 DoNothing, DoNothing);
1106 } else if (FName == "CVPixelBufferCreateWithPlanarBytes") {
1107 // FIXES: <rdar://problem/7283567>
1108 // Eventually this can be improved by recognizing that the pixel
1109 // buffer passed to CVPixelBufferCreateWithPlanarBytes is released
1110 // via a callback and doing full IPA to make sure this is done
1111 // correctly.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001112 ScratchArgs = AF.add(ScratchArgs, 12, StopTracking);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001113 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenek06911d42012-03-22 06:29:41 +00001114 } else if (FName == "dispatch_set_context") {
1115 // <rdar://problem/11059275> - The analyzer currently doesn't have
1116 // a good way to reason about the finalizer function for libdispatch.
1117 // If we pass a context object that is memory managed, stop tracking it.
1118 // FIXME: this hack should possibly go away once we can handle
1119 // libdispatch finalizers.
1120 ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
1121 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenekc91fdf62012-05-08 00:12:09 +00001122 } else if (FName.startswith("NSLog")) {
1123 S = getDoNothingSummary();
Anna Zaks62a5c342012-03-30 05:48:16 +00001124 } else if (FName.startswith("NS") &&
1125 (FName.find("Insert") != StringRef::npos)) {
1126 // Whitelist NSXXInsertXX, for example NSMapInsertIfAbsent, since they can
1127 // be deallocated by NSMapRemove. (radar://11152419)
1128 ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
1129 ScratchArgs = AF.add(ScratchArgs, 2, StopTracking);
1130 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenekb04cb592009-06-11 18:17:24 +00001131 }
Mike Stump1eb44332009-09-09 15:08:12 +00001132
Ted Kremenekb04cb592009-06-11 18:17:24 +00001133 // Did we get a summary?
1134 if (S)
1135 break;
Ted Kremenek61991902009-03-17 22:43:44 +00001136
Ted Kremenek12619382009-01-12 21:45:02 +00001137 if (RetTy->isPointerType()) {
Ted Kremeneke7883652012-08-30 19:27:02 +00001138 if (FD->getAttr<CFAuditedTransferAttr>()) {
1139 S = getCFCreateGetRuleSummary(FD);
1140 break;
1141 }
1142
Ted Kremenek12619382009-01-12 21:45:02 +00001143 // For CoreFoundation ('CF') types.
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001144 if (cocoa::isRefType(RetTy, "CF", FName)) {
Ted Kremenek12619382009-01-12 21:45:02 +00001145 if (isRetain(FD, FName))
1146 S = getUnarySummary(FT, cfretain);
Jordy Rose76c506f2011-08-21 21:58:18 +00001147 else if (isMakeCollectable(FD, FName))
Ted Kremenek12619382009-01-12 21:45:02 +00001148 S = getUnarySummary(FT, cfmakecollectable);
Mike Stump1eb44332009-09-09 15:08:12 +00001149 else
John McCall7df2ff42011-10-01 00:48:56 +00001150 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek12619382009-01-12 21:45:02 +00001151
1152 break;
1153 }
1154
1155 // For CoreGraphics ('CG') types.
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001156 if (cocoa::isRefType(RetTy, "CG", FName)) {
Ted Kremenek12619382009-01-12 21:45:02 +00001157 if (isRetain(FD, FName))
1158 S = getUnarySummary(FT, cfretain);
1159 else
John McCall7df2ff42011-10-01 00:48:56 +00001160 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek12619382009-01-12 21:45:02 +00001161
1162 break;
1163 }
1164
1165 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001166 if (cocoa::isRefType(RetTy, "DADisk") ||
1167 cocoa::isRefType(RetTy, "DADissenter") ||
1168 cocoa::isRefType(RetTy, "DASessionRef")) {
John McCall7df2ff42011-10-01 00:48:56 +00001169 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek12619382009-01-12 21:45:02 +00001170 break;
1171 }
Mike Stump1eb44332009-09-09 15:08:12 +00001172
Ted Kremenek12619382009-01-12 21:45:02 +00001173 break;
1174 }
1175
1176 // Check for release functions, the only kind of functions that we care
1177 // about that don't return a pointer type.
1178 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
Ted Kremeneke7d03122010-02-08 16:45:01 +00001179 // Test for 'CGCF'.
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001180 FName = FName.substr(FName.startswith("CGCF") ? 4 : 2);
Ted Kremeneke7d03122010-02-08 16:45:01 +00001181
Ted Kremenekbf0a4dd2009-03-05 22:11:14 +00001182 if (isRelease(FD, FName))
Ted Kremenek12619382009-01-12 21:45:02 +00001183 S = getUnarySummary(FT, cfrelease);
1184 else {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001185 assert (ScratchArgs.isEmpty());
Ted Kremenek68189282009-01-29 22:45:13 +00001186 // Remaining CoreFoundation and CoreGraphics functions.
1187 // We use to assume that they all strictly followed the ownership idiom
1188 // and that ownership cannot be transferred. While this is technically
1189 // correct, many methods allow a tracked object to escape. For example:
1190 //
Mike Stump1eb44332009-09-09 15:08:12 +00001191 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
Ted Kremenek68189282009-01-29 22:45:13 +00001192 // CFDictionaryAddValue(y, key, x);
Mike Stump1eb44332009-09-09 15:08:12 +00001193 // CFRelease(x);
Ted Kremenek68189282009-01-29 22:45:13 +00001194 // ... it is okay to use 'x' since 'y' has a reference to it
1195 //
1196 // We handle this and similar cases with the follow heuristic. If the
Ted Kremenekc4843812009-08-20 00:57:22 +00001197 // function name contains "InsertValue", "SetValue", "AddValue",
1198 // "AppendValue", or "SetAttribute", then we assume that arguments may
1199 // "escape." This means that something else holds on to the object,
1200 // allowing it be used even after its local retain count drops to 0.
Benjamin Kramere45c1492010-01-11 19:46:28 +00001201 ArgEffect E = (StrInStrNoCase(FName, "InsertValue") != StringRef::npos||
1202 StrInStrNoCase(FName, "AddValue") != StringRef::npos ||
1203 StrInStrNoCase(FName, "SetValue") != StringRef::npos ||
1204 StrInStrNoCase(FName, "AppendValue") != StringRef::npos||
Benjamin Kramerc027e542010-01-11 20:15:06 +00001205 StrInStrNoCase(FName, "SetAttribute") != StringRef::npos)
Ted Kremenek68189282009-01-29 22:45:13 +00001206 ? MayEscape : DoNothing;
Mike Stump1eb44332009-09-09 15:08:12 +00001207
Ted Kremenek68189282009-01-29 22:45:13 +00001208 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek12619382009-01-12 21:45:02 +00001209 }
1210 }
Ted Kremenek37d785b2008-07-15 16:50:12 +00001211 }
1212 while (0);
Mike Stump1eb44332009-09-09 15:08:12 +00001213
Jordan Rose4531b7d2012-07-02 19:27:43 +00001214 // If we got all the way here without any luck, use a default summary.
1215 if (!S)
1216 S = getDefaultSummary();
1217
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001218 // Annotations override defaults.
Jordan Rose15d18e12012-08-06 21:28:02 +00001219 if (AllowAnnotations)
1220 updateSummaryFromAnnotations(S, FD);
Mike Stump1eb44332009-09-09 15:08:12 +00001221
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001222 FuncSummaries[FD] = S;
Mike Stump1eb44332009-09-09 15:08:12 +00001223 return S;
Ted Kremenek2fff37e2008-03-06 00:08:09 +00001224}
1225
Ted Kremenek93edbc52011-10-05 23:54:29 +00001226const RetainSummary *
John McCall7df2ff42011-10-01 00:48:56 +00001227RetainSummaryManager::getCFCreateGetRuleSummary(const FunctionDecl *FD) {
1228 if (coreFoundation::followsCreateRule(FD))
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001229 return getCFSummaryCreateRule(FD);
Mike Stump1eb44332009-09-09 15:08:12 +00001230
Ted Kremenekd368d712011-05-25 06:19:45 +00001231 return getCFSummaryGetRule(FD);
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001232}
1233
Ted Kremenek93edbc52011-10-05 23:54:29 +00001234const RetainSummary *
Ted Kremenek6ad315a2009-02-23 16:51:39 +00001235RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1236 UnaryFuncKind func) {
1237
Ted Kremenek12619382009-01-12 21:45:02 +00001238 // Sanity check that this is *really* a unary function. This can
1239 // happen if people do weird things.
Douglas Gregor72564e72009-02-26 23:50:07 +00001240 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
Ted Kremenek12619382009-01-12 21:45:02 +00001241 if (!FTP || FTP->getNumArgs() != 1)
1242 return getPersistentStopSummary();
Mike Stump1eb44332009-09-09 15:08:12 +00001243
Ted Kremenekb77449c2009-05-03 05:20:50 +00001244 assert (ScratchArgs.isEmpty());
Mike Stump1eb44332009-09-09 15:08:12 +00001245
Jordy Rose76c506f2011-08-21 21:58:18 +00001246 ArgEffect Effect;
Ted Kremenek377e2302008-04-29 05:33:51 +00001247 switch (func) {
Jordy Rose76c506f2011-08-21 21:58:18 +00001248 case cfretain: Effect = IncRef; break;
1249 case cfrelease: Effect = DecRef; break;
1250 case cfmakecollectable: Effect = MakeCollectable; break;
Ted Kremenek940b1d82008-04-10 23:44:06 +00001251 }
Jordy Rose76c506f2011-08-21 21:58:18 +00001252
1253 ScratchArgs = AF.add(ScratchArgs, 0, Effect);
1254 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001255}
1256
Ted Kremenek93edbc52011-10-05 23:54:29 +00001257const RetainSummary *
Ted Kremenek9c378f72011-08-12 23:37:29 +00001258RetainSummaryManager::getCFSummaryCreateRule(const FunctionDecl *FD) {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001259 assert (ScratchArgs.isEmpty());
Mike Stump1eb44332009-09-09 15:08:12 +00001260
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001261 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001262}
1263
Ted Kremenek93edbc52011-10-05 23:54:29 +00001264const RetainSummary *
Ted Kremenek9c378f72011-08-12 23:37:29 +00001265RetainSummaryManager::getCFSummaryGetRule(const FunctionDecl *FD) {
Mike Stump1eb44332009-09-09 15:08:12 +00001266 assert (ScratchArgs.isEmpty());
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001267 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1268 DoNothing, DoNothing);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001269}
1270
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001271//===----------------------------------------------------------------------===//
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001272// Summary creation for Selectors.
1273//===----------------------------------------------------------------------===//
1274
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001275void
Ted Kremenek93edbc52011-10-05 23:54:29 +00001276RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001277 const FunctionDecl *FD) {
1278 if (!FD)
1279 return;
1280
Jordan Rose4531b7d2012-07-02 19:27:43 +00001281 assert(Summ && "Must have a summary to add annotations to.");
1282 RetainSummaryTemplate Template(Summ, *this);
Jordy Rose4df54fe2011-08-23 04:27:15 +00001283
Ted Kremenek11fe1752011-01-27 18:43:03 +00001284 // Effects on the parameters.
1285 unsigned parm_idx = 0;
1286 for (FunctionDecl::param_const_iterator pi = FD->param_begin(),
John McCall98b8f162011-04-06 09:02:12 +00001287 pe = FD->param_end(); pi != pe; ++pi, ++parm_idx) {
Ted Kremenek11fe1752011-01-27 18:43:03 +00001288 const ParmVarDecl *pd = *pi;
1289 if (pd->getAttr<NSConsumedAttr>()) {
Jordy Rose4df54fe2011-08-23 04:27:15 +00001290 if (!GCEnabled) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001291 Template->addArg(AF, parm_idx, DecRef);
Jordy Rose4df54fe2011-08-23 04:27:15 +00001292 }
1293 } else if (pd->getAttr<CFConsumedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001294 Template->addArg(AF, parm_idx, DecRef);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001295 }
1296 }
1297
Ted Kremenekb04cb592009-06-11 18:17:24 +00001298 QualType RetTy = FD->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00001299
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001300 // Determine if there is a special return effect for this method.
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001301 if (cocoa::isCocoaObjectRef(RetTy)) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001302 if (FD->getAttr<NSReturnsRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001303 Template->setRetEffect(ObjCAllocRetE);
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001304 }
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001305 else if (FD->getAttr<CFReturnsRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001306 Template->setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenekb04cb592009-06-11 18:17:24 +00001307 }
Ted Kremenek60411112010-02-18 00:06:12 +00001308 else if (FD->getAttr<NSReturnsNotRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001309 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::ObjC));
Ted Kremenek60411112010-02-18 00:06:12 +00001310 }
1311 else if (FD->getAttr<CFReturnsNotRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001312 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::CF));
Jordy Rose4df54fe2011-08-23 04:27:15 +00001313 }
1314 } else if (RetTy->getAs<PointerType>()) {
1315 if (FD->getAttr<CFReturnsRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001316 Template->setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
Jordy Rose4df54fe2011-08-23 04:27:15 +00001317 }
1318 else if (FD->getAttr<CFReturnsNotRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001319 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::CF));
Ted Kremenek60411112010-02-18 00:06:12 +00001320 }
Ted Kremenekb04cb592009-06-11 18:17:24 +00001321 }
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001322}
1323
1324void
Ted Kremenek93edbc52011-10-05 23:54:29 +00001325RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
1326 const ObjCMethodDecl *MD) {
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001327 if (!MD)
1328 return;
1329
Jordan Rose4531b7d2012-07-02 19:27:43 +00001330 assert(Summ && "Must have a valid summary to add annotations to");
1331 RetainSummaryTemplate Template(Summ, *this);
Ted Kremenek6d4b76d2009-07-06 18:30:43 +00001332 bool isTrackedLoc = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001333
Ted Kremenek12b94342011-01-27 06:54:14 +00001334 // Effects on the receiver.
1335 if (MD->getAttr<NSConsumesSelfAttr>()) {
Ted Kremenek11fe1752011-01-27 18:43:03 +00001336 if (!GCEnabled)
Jordy Rose0fe62f82011-08-24 09:02:37 +00001337 Template->setReceiverEffect(DecRefMsg);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001338 }
1339
1340 // Effects on the parameters.
1341 unsigned parm_idx = 0;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00001342 for (ObjCMethodDecl::param_const_iterator
1343 pi=MD->param_begin(), pe=MD->param_end();
Ted Kremenek11fe1752011-01-27 18:43:03 +00001344 pi != pe; ++pi, ++parm_idx) {
1345 const ParmVarDecl *pd = *pi;
1346 if (pd->getAttr<NSConsumedAttr>()) {
1347 if (!GCEnabled)
Jordy Rose0fe62f82011-08-24 09:02:37 +00001348 Template->addArg(AF, parm_idx, DecRef);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001349 }
1350 else if(pd->getAttr<CFConsumedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001351 Template->addArg(AF, parm_idx, DecRef);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001352 }
Ted Kremenek12b94342011-01-27 06:54:14 +00001353 }
1354
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001355 // Determine if there is a special return effect for this method.
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001356 if (cocoa::isCocoaObjectRef(MD->getResultType())) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001357 if (MD->getAttr<NSReturnsRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001358 Template->setRetEffect(ObjCAllocRetE);
Ted Kremenek6d4b76d2009-07-06 18:30:43 +00001359 return;
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001360 }
Ted Kremenek60411112010-02-18 00:06:12 +00001361 if (MD->getAttr<NSReturnsNotRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001362 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::ObjC));
Ted Kremenek60411112010-02-18 00:06:12 +00001363 return;
1364 }
Mike Stump1eb44332009-09-09 15:08:12 +00001365
Ted Kremenek6d4b76d2009-07-06 18:30:43 +00001366 isTrackedLoc = true;
Jordy Rose0fe62f82011-08-24 09:02:37 +00001367 } else {
Ted Kremenek6217b802009-07-29 21:53:49 +00001368 isTrackedLoc = MD->getResultType()->getAs<PointerType>() != NULL;
Jordy Rose0fe62f82011-08-24 09:02:37 +00001369 }
Mike Stump1eb44332009-09-09 15:08:12 +00001370
Ted Kremenek60411112010-02-18 00:06:12 +00001371 if (isTrackedLoc) {
1372 if (MD->getAttr<CFReturnsRetainedAttr>())
Jordy Rose0fe62f82011-08-24 09:02:37 +00001373 Template->setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenek60411112010-02-18 00:06:12 +00001374 else if (MD->getAttr<CFReturnsNotRetainedAttr>())
Jordy Rose0fe62f82011-08-24 09:02:37 +00001375 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::CF));
Ted Kremenek60411112010-02-18 00:06:12 +00001376 }
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001377}
1378
Ted Kremenek93edbc52011-10-05 23:54:29 +00001379const RetainSummary *
Jordy Rosef3aae582012-03-17 21:13:07 +00001380RetainSummaryManager::getStandardMethodSummary(const ObjCMethodDecl *MD,
1381 Selector S, QualType RetTy) {
Jordy Rosee921b1a2012-03-17 19:53:04 +00001382 // Any special effects?
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001383 ArgEffect ReceiverEff = DoNothing;
Jordy Rosee921b1a2012-03-17 19:53:04 +00001384 RetEffect ResultEff = RetEffect::MakeNoRet();
1385
1386 // Check the method family, and apply any default annotations.
1387 switch (MD ? MD->getMethodFamily() : S.getMethodFamily()) {
1388 case OMF_None:
1389 case OMF_performSelector:
1390 // Assume all Objective-C methods follow Cocoa Memory Management rules.
1391 // FIXME: Does the non-threaded performSelector family really belong here?
1392 // The selector could be, say, @selector(copy).
1393 if (cocoa::isCocoaObjectRef(RetTy))
1394 ResultEff = RetEffect::MakeNotOwned(RetEffect::ObjC);
1395 else if (coreFoundation::isCFObjectRef(RetTy)) {
1396 // ObjCMethodDecl currently doesn't consider CF objects as valid return
1397 // values for alloc, new, copy, or mutableCopy, so we have to
1398 // double-check with the selector. This is ugly, but there aren't that
1399 // many Objective-C methods that return CF objects, right?
1400 if (MD) {
1401 switch (S.getMethodFamily()) {
1402 case OMF_alloc:
1403 case OMF_new:
1404 case OMF_copy:
1405 case OMF_mutableCopy:
1406 ResultEff = RetEffect::MakeOwned(RetEffect::CF, true);
1407 break;
1408 default:
1409 ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1410 break;
1411 }
1412 } else {
1413 ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1414 }
1415 }
1416 break;
1417 case OMF_init:
1418 ResultEff = ObjCInitRetE;
1419 ReceiverEff = DecRefMsg;
1420 break;
1421 case OMF_alloc:
1422 case OMF_new:
1423 case OMF_copy:
1424 case OMF_mutableCopy:
1425 if (cocoa::isCocoaObjectRef(RetTy))
1426 ResultEff = ObjCAllocRetE;
1427 else if (coreFoundation::isCFObjectRef(RetTy))
1428 ResultEff = RetEffect::MakeOwned(RetEffect::CF, true);
1429 break;
1430 case OMF_autorelease:
1431 ReceiverEff = Autorelease;
1432 break;
1433 case OMF_retain:
1434 ReceiverEff = IncRefMsg;
1435 break;
1436 case OMF_release:
1437 ReceiverEff = DecRefMsg;
1438 break;
1439 case OMF_dealloc:
1440 ReceiverEff = Dealloc;
1441 break;
1442 case OMF_self:
1443 // -self is handled specially by the ExprEngine to propagate the receiver.
1444 break;
1445 case OMF_retainCount:
1446 case OMF_finalize:
1447 // These methods don't return objects.
1448 break;
1449 }
Mike Stump1eb44332009-09-09 15:08:12 +00001450
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001451 // If one of the arguments in the selector has the keyword 'delegate' we
1452 // should stop tracking the reference count for the receiver. This is
1453 // because the reference count is quite possibly handled by a delegate
1454 // method.
1455 if (S.isKeywordSelector()) {
Jordan Rose50571a92012-06-15 18:19:52 +00001456 for (unsigned i = 0, e = S.getNumArgs(); i != e; ++i) {
1457 StringRef Slot = S.getNameForSlot(i);
1458 if (Slot.substr(Slot.size() - 8).equals_lower("delegate")) {
1459 if (ResultEff == ObjCInitRetE)
Anna Zaks554067f2012-08-29 23:23:43 +00001460 ResultEff = RetEffect::MakeNoRetHard();
Jordan Rose50571a92012-06-15 18:19:52 +00001461 else
Anna Zaks554067f2012-08-29 23:23:43 +00001462 ReceiverEff = StopTrackingHard;
Jordan Rose50571a92012-06-15 18:19:52 +00001463 }
1464 }
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001465 }
Mike Stump1eb44332009-09-09 15:08:12 +00001466
Jordy Rosee921b1a2012-03-17 19:53:04 +00001467 if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing &&
1468 ResultEff.getKind() == RetEffect::NoRet)
Ted Kremenek93edbc52011-10-05 23:54:29 +00001469 return getDefaultSummary();
Mike Stump1eb44332009-09-09 15:08:12 +00001470
Jordy Rosee921b1a2012-03-17 19:53:04 +00001471 return getPersistentSummary(ResultEff, ReceiverEff, MayEscape);
Ted Kremenek250b1fa2009-04-23 23:08:22 +00001472}
1473
Ted Kremenek93edbc52011-10-05 23:54:29 +00001474const RetainSummary *
Jordan Rosecde8cdb2012-07-02 19:27:56 +00001475RetainSummaryManager::getInstanceMethodSummary(const ObjCMethodCall &Msg,
Jordan Rose4531b7d2012-07-02 19:27:43 +00001476 ProgramStateRef State) {
1477 const ObjCInterfaceDecl *ReceiverClass = 0;
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001478
Jordan Rose4531b7d2012-07-02 19:27:43 +00001479 // We do better tracking of the type of the object than the core ExprEngine.
1480 // See if we have its type in our private state.
1481 // FIXME: Eventually replace the use of state->get<RefBindings> with
1482 // a generic API for reasoning about the Objective-C types of symbolic
1483 // objects.
1484 SVal ReceiverV = Msg.getReceiverSVal();
1485 if (SymbolRef Sym = ReceiverV.getAsLocSymbol())
Anna Zaks8d6b43c2012-08-14 00:36:15 +00001486 if (const RefVal *T = getRefBinding(State, Sym))
Douglas Gregor04badcf2010-04-21 00:45:42 +00001487 if (const ObjCObjectPointerType *PT =
Jordan Rose4531b7d2012-07-02 19:27:43 +00001488 T->getType()->getAs<ObjCObjectPointerType>())
1489 ReceiverClass = PT->getInterfaceDecl();
1490
1491 // If we don't know what kind of object this is, fall back to its static type.
1492 if (!ReceiverClass)
1493 ReceiverClass = Msg.getReceiverInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00001494
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001495 // FIXME: The receiver could be a reference to a class, meaning that
1496 // we should use the class method.
Jordan Rose4531b7d2012-07-02 19:27:43 +00001497 // id x = [NSObject class];
1498 // [x performSelector:... withObject:... afterDelay:...];
1499 Selector S = Msg.getSelector();
1500 const ObjCMethodDecl *Method = Msg.getDecl();
1501 if (!Method && ReceiverClass)
1502 Method = ReceiverClass->getInstanceMethod(S);
1503
1504 return getMethodSummary(S, ReceiverClass, Method, Msg.getResultType(),
1505 ObjCMethodSummaries);
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001506}
1507
Ted Kremenek93edbc52011-10-05 23:54:29 +00001508const RetainSummary *
Jordan Rose4531b7d2012-07-02 19:27:43 +00001509RetainSummaryManager::getMethodSummary(Selector S, const ObjCInterfaceDecl *ID,
Jordy Rosef3aae582012-03-17 21:13:07 +00001510 const ObjCMethodDecl *MD, QualType RetTy,
1511 ObjCMethodSummariesTy &CachedSummaries) {
Ted Kremenek1bffd742008-05-06 15:44:25 +00001512
Ted Kremenek8711c032009-04-29 05:04:30 +00001513 // Look up a summary in our summary cache.
Jordan Rose4531b7d2012-07-02 19:27:43 +00001514 const RetainSummary *Summ = CachedSummaries.find(ID, S);
Mike Stump1eb44332009-09-09 15:08:12 +00001515
Ted Kremenek614cc542009-07-21 23:27:57 +00001516 if (!Summ) {
Jordy Rosef3aae582012-03-17 21:13:07 +00001517 Summ = getStandardMethodSummary(MD, S, RetTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001518
Ted Kremenek614cc542009-07-21 23:27:57 +00001519 // Annotations override defaults.
Jordy Rose4df54fe2011-08-23 04:27:15 +00001520 updateSummaryFromAnnotations(Summ, MD);
Mike Stump1eb44332009-09-09 15:08:12 +00001521
Ted Kremenek614cc542009-07-21 23:27:57 +00001522 // Memoize the summary.
Jordan Rose4531b7d2012-07-02 19:27:43 +00001523 CachedSummaries[ObjCSummaryKey(ID, S)] = Summ;
Ted Kremenek614cc542009-07-21 23:27:57 +00001524 }
Mike Stump1eb44332009-09-09 15:08:12 +00001525
Ted Kremeneke87450e2009-04-23 19:11:35 +00001526 return Summ;
Ted Kremenekc8395602008-05-06 21:26:51 +00001527}
1528
Mike Stump1eb44332009-09-09 15:08:12 +00001529void RetainSummaryManager::InitializeClassMethodSummaries() {
Ted Kremenekec315332009-05-07 23:40:42 +00001530 assert(ScratchArgs.isEmpty());
Mike Stump1eb44332009-09-09 15:08:12 +00001531 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek6fe2b7a2009-10-15 22:25:12 +00001532 addClassMethSummary("NSAssertionHandler", "currentHandler",
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001533 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Mike Stump1eb44332009-09-09 15:08:12 +00001534
Ted Kremenek6d348932008-10-21 15:53:15 +00001535 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001536 ScratchArgs = AF.add(ScratchArgs, 0, Autorelease);
Ted Kremenek6fe2b7a2009-10-15 22:25:12 +00001537 addClassMethSummary("NSAutoreleasePool", "addObject",
1538 getPersistentSummary(RetEffect::MakeNoRet(),
1539 DoNothing, Autorelease));
Ted Kremenek9c32d082008-05-06 00:30:21 +00001540}
1541
Ted Kremenek1f180c32008-06-23 22:21:20 +00001542void RetainSummaryManager::InitializeMethodSummaries() {
Mike Stump1eb44332009-09-09 15:08:12 +00001543
1544 assert (ScratchArgs.isEmpty());
1545
Ted Kremenekc8395602008-05-06 21:26:51 +00001546 // Create the "init" selector. It just acts as a pass-through for the
1547 // receiver.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001548 const RetainSummary *InitSumm = getPersistentSummary(ObjCInitRetE, DecRefMsg);
Ted Kremenekac02f202009-08-20 05:13:36 +00001549 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
1550
1551 // awakeAfterUsingCoder: behaves basically like an 'init' method. It
1552 // claims the receiver and returns a retained object.
1553 addNSObjectMethSummary(GetUnarySelector("awakeAfterUsingCoder", Ctx),
1554 InitSumm);
Mike Stump1eb44332009-09-09 15:08:12 +00001555
Ted Kremenekc8395602008-05-06 21:26:51 +00001556 // The next methods are allocators.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001557 const RetainSummary *AllocSumm = getPersistentSummary(ObjCAllocRetE);
1558 const RetainSummary *CFAllocSumm =
Ted Kremeneka834fb42009-08-28 19:52:12 +00001559 getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Mike Stump1eb44332009-09-09 15:08:12 +00001560
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001561 // Create the "retain" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001562 RetEffect NoRet = RetEffect::MakeNoRet();
Ted Kremenek93edbc52011-10-05 23:54:29 +00001563 const RetainSummary *Summ = getPersistentSummary(NoRet, IncRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001564 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001565
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001566 // Create the "release" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001567 Summ = getPersistentSummary(NoRet, DecRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001568 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001569
Ted Kremenek299e8152008-05-07 21:17:39 +00001570 // Create the "drain" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001571 Summ = getPersistentSummary(NoRet, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek553cf182008-06-25 21:21:56 +00001572 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001573
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001574 // Create the -dealloc summary.
Jordy Rose500abad2011-08-21 19:41:36 +00001575 Summ = getPersistentSummary(NoRet, Dealloc);
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001576 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001577
1578 // Create the "autorelease" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001579 Summ = getPersistentSummary(NoRet, Autorelease);
Ted Kremenek553cf182008-06-25 21:21:56 +00001580 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001581
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00001582 // Specially handle NSAutoreleasePool.
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001583 addInstMethSummary("NSAutoreleasePool", "init",
Jordy Rose500abad2011-08-21 19:41:36 +00001584 getPersistentSummary(NoRet, NewAutoreleasePool));
Mike Stump1eb44332009-09-09 15:08:12 +00001585
1586 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremenek89e202d2009-02-23 02:51:29 +00001587 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1588 // self-own themselves. However, they only do this once they are displayed.
1589 // Thus, we need to track an NSWindow's display status.
1590 // This is tracked in <rdar://problem/6062711>.
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +00001591 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001592 const RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenek78a35a32009-05-12 20:06:54 +00001593 StopTracking,
1594 StopTracking);
Mike Stump1eb44332009-09-09 15:08:12 +00001595
Ted Kremenek99d02692009-04-03 19:02:51 +00001596 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1597
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001598 // For NSPanel (which subclasses NSWindow), allocated objects are not
1599 // self-owned.
Ted Kremenek99d02692009-04-03 19:02:51 +00001600 // FIXME: For now we don't track NSPanels. object for the same reason
1601 // as for NSWindow objects.
1602 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
Mike Stump1eb44332009-09-09 15:08:12 +00001603
Ted Kremenekba67f6a2009-05-18 23:14:34 +00001604 // Don't track allocated autorelease pools yet, as it is okay to prematurely
1605 // exit a method.
1606 addClassMethSummary("NSAutoreleasePool", "alloc", NoTrackYet);
Ted Kremeneka9797122012-02-18 21:37:48 +00001607 addClassMethSummary("NSAutoreleasePool", "allocWithZone", NoTrackYet, false);
Ted Kremenek553cf182008-06-25 21:21:56 +00001608
Ted Kremenek767d6492009-05-20 22:39:57 +00001609 // Create summaries QCRenderer/QCView -createSnapShotImageOfType:
1610 addInstMethSummary("QCRenderer", AllocSumm,
1611 "createSnapshotImageOfType", NULL);
1612 addInstMethSummary("QCView", AllocSumm,
1613 "createSnapshotImageOfType", NULL);
1614
Ted Kremenek211a9c62009-06-15 20:58:58 +00001615 // Create summaries for CIContext, 'createCGImage' and
Ted Kremeneka834fb42009-08-28 19:52:12 +00001616 // 'createCGLayerWithSize'. These objects are CF objects, and are not
1617 // automatically garbage collected.
1618 addInstMethSummary("CIContext", CFAllocSumm,
Ted Kremenek767d6492009-05-20 22:39:57 +00001619 "createCGImage", "fromRect", NULL);
Ted Kremeneka834fb42009-08-28 19:52:12 +00001620 addInstMethSummary("CIContext", CFAllocSumm,
Mike Stump1eb44332009-09-09 15:08:12 +00001621 "createCGImage", "fromRect", "format", "colorSpace", NULL);
Ted Kremeneka834fb42009-08-28 19:52:12 +00001622 addInstMethSummary("CIContext", CFAllocSumm, "createCGLayerWithSize",
Ted Kremenek211a9c62009-06-15 20:58:58 +00001623 "info", NULL);
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001624}
1625
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001626//===----------------------------------------------------------------------===//
Ted Kremenekc887d132009-04-29 18:50:19 +00001627// Error reporting.
1628//===----------------------------------------------------------------------===//
Ted Kremenekc887d132009-04-29 18:50:19 +00001629namespace {
Jordy Roseec9ef852011-08-23 20:55:48 +00001630 typedef llvm::DenseMap<const ExplodedNode *, const RetainSummary *>
1631 SummaryLogTy;
1632
Ted Kremenekc887d132009-04-29 18:50:19 +00001633 //===-------------===//
1634 // Bug Descriptions. //
Mike Stump1eb44332009-09-09 15:08:12 +00001635 //===-------------===//
1636
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001637 class CFRefBug : public BugType {
Ted Kremenekc887d132009-04-29 18:50:19 +00001638 protected:
Jordy Rose35c86952011-08-24 05:47:39 +00001639 CFRefBug(StringRef name)
Ted Kremenek6fd45052012-04-05 20:43:28 +00001640 : BugType(name, categories::MemoryCoreFoundationObjectiveC) {}
Ted Kremenekc887d132009-04-29 18:50:19 +00001641 public:
Mike Stump1eb44332009-09-09 15:08:12 +00001642
Ted Kremenekc887d132009-04-29 18:50:19 +00001643 // FIXME: Eventually remove.
Jordy Rose35c86952011-08-24 05:47:39 +00001644 virtual const char *getDescription() const = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001645
Ted Kremenekc887d132009-04-29 18:50:19 +00001646 virtual bool isLeak() const { return false; }
1647 };
Mike Stump1eb44332009-09-09 15:08:12 +00001648
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001649 class UseAfterRelease : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001650 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001651 UseAfterRelease() : CFRefBug("Use-after-release") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001652
Jordy Rose35c86952011-08-24 05:47:39 +00001653 const char *getDescription() const {
Ted Kremenekc887d132009-04-29 18:50:19 +00001654 return "Reference-counted object is used after it is released";
Mike Stump1eb44332009-09-09 15:08:12 +00001655 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001656 };
Mike Stump1eb44332009-09-09 15:08:12 +00001657
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001658 class BadRelease : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001659 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001660 BadRelease() : CFRefBug("Bad release") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001661
Jordy Rose35c86952011-08-24 05:47:39 +00001662 const char *getDescription() const {
Ted Kremenekbb206fd2009-10-01 17:31:50 +00001663 return "Incorrect decrement of the reference count of an object that is "
1664 "not owned at this point by the caller";
Ted Kremenekc887d132009-04-29 18:50:19 +00001665 }
1666 };
Mike Stump1eb44332009-09-09 15:08:12 +00001667
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001668 class DeallocGC : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001669 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001670 DeallocGC()
1671 : CFRefBug("-dealloc called while using garbage collection") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001672
Ted Kremenekc887d132009-04-29 18:50:19 +00001673 const char *getDescription() const {
Ted Kremenek369de562009-05-09 00:10:05 +00001674 return "-dealloc called while using garbage collection";
Ted Kremenekc887d132009-04-29 18:50:19 +00001675 }
1676 };
Mike Stump1eb44332009-09-09 15:08:12 +00001677
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001678 class DeallocNotOwned : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001679 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001680 DeallocNotOwned()
1681 : CFRefBug("-dealloc sent to non-exclusively owned object") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001682
Ted Kremenekc887d132009-04-29 18:50:19 +00001683 const char *getDescription() const {
1684 return "-dealloc sent to object that may be referenced elsewhere";
1685 }
Mike Stump1eb44332009-09-09 15:08:12 +00001686 };
1687
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001688 class OverAutorelease : public CFRefBug {
Ted Kremenek369de562009-05-09 00:10:05 +00001689 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001690 OverAutorelease()
1691 : CFRefBug("Object sent -autorelease too many times") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001692
Ted Kremenek369de562009-05-09 00:10:05 +00001693 const char *getDescription() const {
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001694 return "Object sent -autorelease too many times";
Ted Kremenek369de562009-05-09 00:10:05 +00001695 }
1696 };
Mike Stump1eb44332009-09-09 15:08:12 +00001697
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001698 class ReturnedNotOwnedForOwned : public CFRefBug {
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001699 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001700 ReturnedNotOwnedForOwned()
1701 : CFRefBug("Method should return an owned object") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001702
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001703 const char *getDescription() const {
Jordy Rose5b5402b2011-07-15 22:17:54 +00001704 return "Object with a +0 retain count returned to caller where a +1 "
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001705 "(owning) retain count is expected";
1706 }
1707 };
Mike Stump1eb44332009-09-09 15:08:12 +00001708
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001709 class Leak : public CFRefBug {
Benjamin Kramerfacde172012-06-06 17:32:50 +00001710 public:
1711 Leak(StringRef name)
1712 : CFRefBug(name) {
Jordy Rosedb92bb62011-08-25 01:14:38 +00001713 // Leaks should not be reported if they are post-dominated by a sink.
1714 setSuppressOnSink(true);
1715 }
Mike Stump1eb44332009-09-09 15:08:12 +00001716
Jordy Rose35c86952011-08-24 05:47:39 +00001717 const char *getDescription() const { return ""; }
Mike Stump1eb44332009-09-09 15:08:12 +00001718
Ted Kremenekc887d132009-04-29 18:50:19 +00001719 bool isLeak() const { return true; }
1720 };
Mike Stump1eb44332009-09-09 15:08:12 +00001721
Ted Kremenekc887d132009-04-29 18:50:19 +00001722 //===---------===//
1723 // Bug Reports. //
1724 //===---------===//
Mike Stump1eb44332009-09-09 15:08:12 +00001725
Jordy Rose01153492012-03-24 02:45:35 +00001726 class CFRefReportVisitor : public BugReporterVisitorImpl<CFRefReportVisitor> {
Anna Zaks23f395e2011-08-20 01:27:22 +00001727 protected:
Anna Zaksdc757b02011-08-19 23:21:56 +00001728 SymbolRef Sym;
Jordy Roseec9ef852011-08-23 20:55:48 +00001729 const SummaryLogTy &SummaryLog;
Jordy Rose35c86952011-08-24 05:47:39 +00001730 bool GCEnabled;
Anna Zaks23f395e2011-08-20 01:27:22 +00001731
Anna Zaksdc757b02011-08-19 23:21:56 +00001732 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001733 CFRefReportVisitor(SymbolRef sym, bool gcEnabled, const SummaryLogTy &log)
1734 : Sym(sym), SummaryLog(log), GCEnabled(gcEnabled) {}
Anna Zaksdc757b02011-08-19 23:21:56 +00001735
Anna Zaks23f395e2011-08-20 01:27:22 +00001736 virtual void Profile(llvm::FoldingSetNodeID &ID) const {
Anna Zaksdc757b02011-08-19 23:21:56 +00001737 static int x = 0;
1738 ID.AddPointer(&x);
1739 ID.AddPointer(Sym);
1740 }
1741
Anna Zaks23f395e2011-08-20 01:27:22 +00001742 virtual PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
1743 const ExplodedNode *PrevN,
1744 BugReporterContext &BRC,
1745 BugReport &BR);
1746
1747 virtual PathDiagnosticPiece *getEndPath(BugReporterContext &BRC,
1748 const ExplodedNode *N,
1749 BugReport &BR);
1750 };
1751
1752 class CFRefLeakReportVisitor : public CFRefReportVisitor {
1753 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001754 CFRefLeakReportVisitor(SymbolRef sym, bool GCEnabled,
Jordy Roseec9ef852011-08-23 20:55:48 +00001755 const SummaryLogTy &log)
Jordy Rose35c86952011-08-24 05:47:39 +00001756 : CFRefReportVisitor(sym, GCEnabled, log) {}
Anna Zaks23f395e2011-08-20 01:27:22 +00001757
1758 PathDiagnosticPiece *getEndPath(BugReporterContext &BRC,
1759 const ExplodedNode *N,
1760 BugReport &BR);
Jordy Rose01153492012-03-24 02:45:35 +00001761
1762 virtual BugReporterVisitor *clone() const {
1763 // The curiously-recurring template pattern only works for one level of
1764 // subclassing. Rather than make a new template base for
1765 // CFRefReportVisitor, we simply override clone() to do the right thing.
1766 // This could be trouble someday if BugReporterVisitorImpl is ever
1767 // used for something else besides a convenient implementation of clone().
1768 return new CFRefLeakReportVisitor(*this);
1769 }
Anna Zaksdc757b02011-08-19 23:21:56 +00001770 };
1771
Anna Zakse172e8b2011-08-17 23:00:25 +00001772 class CFRefReport : public BugReport {
Jordy Rose20589562011-08-24 22:39:09 +00001773 void addGCModeDescription(const LangOptions &LOpts, bool GCEnabled);
Jordy Rose35c86952011-08-24 05:47:39 +00001774
Ted Kremenekc887d132009-04-29 18:50:19 +00001775 public:
Jordy Rose20589562011-08-24 22:39:09 +00001776 CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1777 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1778 bool registerVisitor = true)
Anna Zaksedf4dae2011-08-22 18:54:07 +00001779 : BugReport(D, D.getDescription(), n) {
Anna Zaks23f395e2011-08-20 01:27:22 +00001780 if (registerVisitor)
Jordy Rose20589562011-08-24 22:39:09 +00001781 addVisitor(new CFRefReportVisitor(sym, GCEnabled, Log));
1782 addGCModeDescription(LOpts, GCEnabled);
Anna Zaksdc757b02011-08-19 23:21:56 +00001783 }
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001784
Jordy Rose20589562011-08-24 22:39:09 +00001785 CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1786 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1787 StringRef endText)
Anna Zaksedf4dae2011-08-22 18:54:07 +00001788 : BugReport(D, D.getDescription(), endText, n) {
Jordy Rose20589562011-08-24 22:39:09 +00001789 addVisitor(new CFRefReportVisitor(sym, GCEnabled, Log));
1790 addGCModeDescription(LOpts, GCEnabled);
Anna Zaksdc757b02011-08-19 23:21:56 +00001791 }
Mike Stump1eb44332009-09-09 15:08:12 +00001792
Anna Zakse172e8b2011-08-17 23:00:25 +00001793 virtual std::pair<ranges_iterator, ranges_iterator> getRanges() {
Anna Zaksedf4dae2011-08-22 18:54:07 +00001794 const CFRefBug& BugTy = static_cast<CFRefBug&>(getBugType());
1795 if (!BugTy.isLeak())
Anna Zakse172e8b2011-08-17 23:00:25 +00001796 return BugReport::getRanges();
Ted Kremenekc887d132009-04-29 18:50:19 +00001797 else
Argyrios Kyrtzidis640ccf02010-12-04 01:12:15 +00001798 return std::make_pair(ranges_iterator(), ranges_iterator());
Ted Kremenekc887d132009-04-29 18:50:19 +00001799 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001800 };
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001801
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001802 class CFRefLeakReport : public CFRefReport {
Ted Kremenekc887d132009-04-29 18:50:19 +00001803 const MemRegion* AllocBinding;
Anna Zaks23f395e2011-08-20 01:27:22 +00001804
Ted Kremenekc887d132009-04-29 18:50:19 +00001805 public:
Jordy Rose20589562011-08-24 22:39:09 +00001806 CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1807 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
Anna Zaks6a93bd52011-10-25 19:57:11 +00001808 CheckerContext &Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001809
Anna Zaks590dd8e2011-09-20 21:38:35 +00001810 PathDiagnosticLocation getLocation(const SourceManager &SM) const {
1811 assert(Location.isValid());
1812 return Location;
1813 }
Mike Stump1eb44332009-09-09 15:08:12 +00001814 };
Ted Kremenekc887d132009-04-29 18:50:19 +00001815} // end anonymous namespace
1816
Jordy Rose20589562011-08-24 22:39:09 +00001817void CFRefReport::addGCModeDescription(const LangOptions &LOpts,
1818 bool GCEnabled) {
Jordy Rosef95b19d2011-08-24 20:38:42 +00001819 const char *GCModeDescription = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001820
Douglas Gregore289d812011-09-13 17:21:33 +00001821 switch (LOpts.getGC()) {
Anna Zaks7f2531c2011-08-22 20:31:28 +00001822 case LangOptions::GCOnly:
Jordy Rose20589562011-08-24 22:39:09 +00001823 assert(GCEnabled);
Jordy Rose35c86952011-08-24 05:47:39 +00001824 GCModeDescription = "Code is compiled to only use garbage collection";
1825 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001826
Anna Zaks7f2531c2011-08-22 20:31:28 +00001827 case LangOptions::NonGC:
Jordy Rose20589562011-08-24 22:39:09 +00001828 assert(!GCEnabled);
Jordy Rose35c86952011-08-24 05:47:39 +00001829 GCModeDescription = "Code is compiled to use reference counts";
1830 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001831
Anna Zaks7f2531c2011-08-22 20:31:28 +00001832 case LangOptions::HybridGC:
Jordy Rose20589562011-08-24 22:39:09 +00001833 if (GCEnabled) {
Jordy Rose35c86952011-08-24 05:47:39 +00001834 GCModeDescription = "Code is compiled to use either garbage collection "
1835 "(GC) or reference counts (non-GC). The bug occurs "
1836 "with GC enabled";
1837 break;
1838 } else {
1839 GCModeDescription = "Code is compiled to use either garbage collection "
1840 "(GC) or reference counts (non-GC). The bug occurs "
1841 "in non-GC mode";
1842 break;
Anna Zaks7f2531c2011-08-22 20:31:28 +00001843 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001844 }
Jordy Rose35c86952011-08-24 05:47:39 +00001845
Jordy Rosef95b19d2011-08-24 20:38:42 +00001846 assert(GCModeDescription && "invalid/unknown GC mode");
Jordy Rose35c86952011-08-24 05:47:39 +00001847 addExtraText(GCModeDescription);
Ted Kremenekc887d132009-04-29 18:50:19 +00001848}
1849
Jordy Rose910c4052011-09-02 06:44:22 +00001850// FIXME: This should be a method on SmallVector.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001851static inline bool contains(const SmallVectorImpl<ArgEffect>& V,
Ted Kremenekc887d132009-04-29 18:50:19 +00001852 ArgEffect X) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001853 for (SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
Ted Kremenekc887d132009-04-29 18:50:19 +00001854 I!=E; ++I)
1855 if (*I == X) return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001856
Ted Kremenekc887d132009-04-29 18:50:19 +00001857 return false;
1858}
1859
Jordy Rose70fdbc32012-05-12 05:10:43 +00001860static bool isNumericLiteralExpression(const Expr *E) {
1861 // FIXME: This set of cases was copied from SemaExprObjC.
1862 return isa<IntegerLiteral>(E) ||
1863 isa<CharacterLiteral>(E) ||
1864 isa<FloatingLiteral>(E) ||
1865 isa<ObjCBoolLiteralExpr>(E) ||
1866 isa<CXXBoolLiteralExpr>(E);
1867}
1868
Anna Zaksdc757b02011-08-19 23:21:56 +00001869PathDiagnosticPiece *CFRefReportVisitor::VisitNode(const ExplodedNode *N,
1870 const ExplodedNode *PrevN,
1871 BugReporterContext &BRC,
1872 BugReport &BR) {
Jordan Rose28038f32012-07-10 22:07:42 +00001873 // FIXME: We will eventually need to handle non-statement-based events
1874 // (__attribute__((cleanup))).
Jordy Rosef53e8c72011-08-23 19:43:16 +00001875 if (!isa<StmtPoint>(N->getLocation()))
Ted Kremenek2033a952009-05-13 07:12:33 +00001876 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001877
Ted Kremenek8966bc12009-05-06 21:39:49 +00001878 // Check if the type state has changed.
Ted Kremenek8bef8232012-01-26 21:29:00 +00001879 ProgramStateRef PrevSt = PrevN->getState();
1880 ProgramStateRef CurrSt = N->getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001881 const LocationContext *LCtx = N->getLocationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00001882
Anna Zaks8d6b43c2012-08-14 00:36:15 +00001883 const RefVal* CurrT = getRefBinding(CurrSt, Sym);
Ted Kremenekc887d132009-04-29 18:50:19 +00001884 if (!CurrT) return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001885
Ted Kremenekb65be702009-06-18 01:23:53 +00001886 const RefVal &CurrV = *CurrT;
Anna Zaks8d6b43c2012-08-14 00:36:15 +00001887 const RefVal *PrevT = getRefBinding(PrevSt, Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00001888
Ted Kremenekc887d132009-04-29 18:50:19 +00001889 // Create a string buffer to constain all the useful things we want
1890 // to tell the user.
1891 std::string sbuf;
1892 llvm::raw_string_ostream os(sbuf);
Mike Stump1eb44332009-09-09 15:08:12 +00001893
Ted Kremenekc887d132009-04-29 18:50:19 +00001894 // This is the allocation site since the previous node had no bindings
1895 // for this symbol.
1896 if (!PrevT) {
Jordy Rosef53e8c72011-08-23 19:43:16 +00001897 const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
Mike Stump1eb44332009-09-09 15:08:12 +00001898
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001899 if (isa<ObjCArrayLiteral>(S)) {
1900 os << "NSArray literal is an object with a +0 retain count";
Mike Stump1eb44332009-09-09 15:08:12 +00001901 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001902 else if (isa<ObjCDictionaryLiteral>(S)) {
1903 os << "NSDictionary literal is an object with a +0 retain count";
Ted Kremenekc887d132009-04-29 18:50:19 +00001904 }
Jordy Rose70fdbc32012-05-12 05:10:43 +00001905 else if (const ObjCBoxedExpr *BL = dyn_cast<ObjCBoxedExpr>(S)) {
1906 if (isNumericLiteralExpression(BL->getSubExpr()))
1907 os << "NSNumber literal is an object with a +0 retain count";
1908 else {
1909 const ObjCInterfaceDecl *BoxClass = 0;
1910 if (const ObjCMethodDecl *Method = BL->getBoxingMethod())
1911 BoxClass = Method->getClassInterface();
1912
1913 // We should always be able to find the boxing class interface,
1914 // but consider this future-proofing.
1915 if (BoxClass)
1916 os << *BoxClass << " b";
1917 else
1918 os << "B";
1919
1920 os << "oxed expression produces an object with a +0 retain count";
1921 }
1922 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001923 else {
1924 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
1925 // Get the name of the callee (if it is available).
1926 SVal X = CurrSt->getSValAsScalarOrLoc(CE->getCallee(), LCtx);
1927 if (const FunctionDecl *FD = X.getAsFunctionDecl())
1928 os << "Call to function '" << *FD << '\'';
1929 else
1930 os << "function call";
Ted Kremenekc887d132009-04-29 18:50:19 +00001931 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001932 else {
Jordan Rose8919e682012-07-18 21:59:51 +00001933 assert(isa<ObjCMessageExpr>(S));
Jordan Rosed563d3f2012-07-30 20:22:09 +00001934 CallEventManager &Mgr = CurrSt->getStateManager().getCallEventManager();
1935 CallEventRef<ObjCMethodCall> Call
1936 = Mgr.getObjCMethodCall(cast<ObjCMessageExpr>(S), CurrSt, LCtx);
1937
1938 switch (Call->getMessageKind()) {
Jordan Rose8919e682012-07-18 21:59:51 +00001939 case OCM_Message:
1940 os << "Method";
1941 break;
1942 case OCM_PropertyAccess:
1943 os << "Property";
1944 break;
1945 case OCM_Subscript:
1946 os << "Subscript";
1947 break;
1948 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001949 }
1950
1951 if (CurrV.getObjKind() == RetEffect::CF) {
1952 os << " returns a Core Foundation object with a ";
1953 }
1954 else {
1955 assert (CurrV.getObjKind() == RetEffect::ObjC);
1956 os << " returns an Objective-C object with a ";
1957 }
1958
1959 if (CurrV.isOwned()) {
1960 os << "+1 retain count";
1961
1962 if (GCEnabled) {
1963 assert(CurrV.getObjKind() == RetEffect::CF);
1964 os << ". "
1965 "Core Foundation objects are not automatically garbage collected.";
1966 }
1967 }
1968 else {
1969 assert (CurrV.isNotOwned());
1970 os << "+0 retain count";
1971 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001972 }
Mike Stump1eb44332009-09-09 15:08:12 +00001973
Anna Zaks220ac8c2011-09-15 01:08:34 +00001974 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
1975 N->getLocationContext());
Ted Kremenekc887d132009-04-29 18:50:19 +00001976 return new PathDiagnosticEventPiece(Pos, os.str());
1977 }
Mike Stump1eb44332009-09-09 15:08:12 +00001978
Ted Kremenekc887d132009-04-29 18:50:19 +00001979 // Gather up the effects that were performed on the object at this
1980 // program point
Chris Lattner5f9e2722011-07-23 10:55:15 +00001981 SmallVector<ArgEffect, 2> AEffects;
Mike Stump1eb44332009-09-09 15:08:12 +00001982
Jordy Roseec9ef852011-08-23 20:55:48 +00001983 const ExplodedNode *OrigNode = BRC.getNodeResolver().getOriginalNode(N);
1984 if (const RetainSummary *Summ = SummaryLog.lookup(OrigNode)) {
Ted Kremenekc887d132009-04-29 18:50:19 +00001985 // We only have summaries attached to nodes after evaluating CallExpr and
1986 // ObjCMessageExprs.
Jordy Rosef53e8c72011-08-23 19:43:16 +00001987 const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
Mike Stump1eb44332009-09-09 15:08:12 +00001988
Ted Kremenek5f85e172009-07-22 22:35:28 +00001989 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
Ted Kremenekc887d132009-04-29 18:50:19 +00001990 // Iterate through the parameter expressions and see if the symbol
1991 // was ever passed as an argument.
1992 unsigned i = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001993
Ted Kremenek5f85e172009-07-22 22:35:28 +00001994 for (CallExpr::const_arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
Ted Kremenekc887d132009-04-29 18:50:19 +00001995 AI!=AE; ++AI, ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00001996
Ted Kremenekc887d132009-04-29 18:50:19 +00001997 // Retrieve the value of the argument. Is it the symbol
1998 // we are interested in?
Ted Kremenek5eca4822012-01-06 22:09:28 +00001999 if (CurrSt->getSValAsScalarOrLoc(*AI, LCtx).getAsLocSymbol() != Sym)
Ted Kremenekc887d132009-04-29 18:50:19 +00002000 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00002001
Ted Kremenekc887d132009-04-29 18:50:19 +00002002 // We have an argument. Get the effect!
2003 AEffects.push_back(Summ->getArg(i));
2004 }
2005 }
Mike Stump1eb44332009-09-09 15:08:12 +00002006 else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002007 if (const Expr *receiver = ME->getInstanceReceiver())
Ted Kremenek5eca4822012-01-06 22:09:28 +00002008 if (CurrSt->getSValAsScalarOrLoc(receiver, LCtx)
2009 .getAsLocSymbol() == Sym) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002010 // The symbol we are tracking is the receiver.
2011 AEffects.push_back(Summ->getReceiverEffect());
2012 }
2013 }
2014 }
Mike Stump1eb44332009-09-09 15:08:12 +00002015
Ted Kremenekc887d132009-04-29 18:50:19 +00002016 do {
2017 // Get the previous type state.
2018 RefVal PrevV = *PrevT;
Mike Stump1eb44332009-09-09 15:08:12 +00002019
Ted Kremenekc887d132009-04-29 18:50:19 +00002020 // Specially handle -dealloc.
Jordy Rose35c86952011-08-24 05:47:39 +00002021 if (!GCEnabled && contains(AEffects, Dealloc)) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002022 // Determine if the object's reference count was pushed to zero.
2023 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2024 // We may not have transitioned to 'release' if we hit an error.
2025 // This case is handled elsewhere.
2026 if (CurrV.getKind() == RefVal::Released) {
Ted Kremenekf21332e2009-05-08 20:01:42 +00002027 assert(CurrV.getCombinedCounts() == 0);
Ted Kremenekc887d132009-04-29 18:50:19 +00002028 os << "Object released by directly sending the '-dealloc' message";
2029 break;
2030 }
2031 }
Mike Stump1eb44332009-09-09 15:08:12 +00002032
Ted Kremenekc887d132009-04-29 18:50:19 +00002033 // Specially handle CFMakeCollectable and friends.
2034 if (contains(AEffects, MakeCollectable)) {
2035 // Get the name of the function.
Jordy Rosef53e8c72011-08-23 19:43:16 +00002036 const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
Ted Kremenek5eca4822012-01-06 22:09:28 +00002037 SVal X =
2038 CurrSt->getSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee(), LCtx);
Ted Kremenek9c378f72011-08-12 23:37:29 +00002039 const FunctionDecl *FD = X.getAsFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002040
Jordy Rose35c86952011-08-24 05:47:39 +00002041 if (GCEnabled) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002042 // Determine if the object's reference count was pushed to zero.
2043 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
Mike Stump1eb44332009-09-09 15:08:12 +00002044
Benjamin Kramerb8989f22011-10-14 18:45:37 +00002045 os << "In GC mode a call to '" << *FD
Ted Kremenekc887d132009-04-29 18:50:19 +00002046 << "' decrements an object's retain count and registers the "
2047 "object with the garbage collector. ";
Mike Stump1eb44332009-09-09 15:08:12 +00002048
Ted Kremenekc887d132009-04-29 18:50:19 +00002049 if (CurrV.getKind() == RefVal::Released) {
2050 assert(CurrV.getCount() == 0);
2051 os << "Since it now has a 0 retain count the object can be "
2052 "automatically collected by the garbage collector.";
2053 }
2054 else
2055 os << "An object must have a 0 retain count to be garbage collected. "
2056 "After this call its retain count is +" << CurrV.getCount()
2057 << '.';
2058 }
Mike Stump1eb44332009-09-09 15:08:12 +00002059 else
Benjamin Kramerb8989f22011-10-14 18:45:37 +00002060 os << "When GC is not enabled a call to '" << *FD
Ted Kremenekc887d132009-04-29 18:50:19 +00002061 << "' has no effect on its argument.";
Mike Stump1eb44332009-09-09 15:08:12 +00002062
Ted Kremenekc887d132009-04-29 18:50:19 +00002063 // Nothing more to say.
2064 break;
2065 }
Mike Stump1eb44332009-09-09 15:08:12 +00002066
2067 // Determine if the typestate has changed.
Ted Kremenekc887d132009-04-29 18:50:19 +00002068 if (!(PrevV == CurrV))
2069 switch (CurrV.getKind()) {
2070 case RefVal::Owned:
2071 case RefVal::NotOwned:
Mike Stump1eb44332009-09-09 15:08:12 +00002072
Ted Kremenekf21332e2009-05-08 20:01:42 +00002073 if (PrevV.getCount() == CurrV.getCount()) {
2074 // Did an autorelease message get sent?
2075 if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
2076 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002077
Zhongxing Xu264e9372009-05-12 10:10:00 +00002078 assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount());
Ted Kremenekeaedfea2009-05-10 05:11:21 +00002079 os << "Object sent -autorelease message";
Ted Kremenekf21332e2009-05-08 20:01:42 +00002080 break;
2081 }
Mike Stump1eb44332009-09-09 15:08:12 +00002082
Ted Kremenekc887d132009-04-29 18:50:19 +00002083 if (PrevV.getCount() > CurrV.getCount())
2084 os << "Reference count decremented.";
2085 else
2086 os << "Reference count incremented.";
Mike Stump1eb44332009-09-09 15:08:12 +00002087
Ted Kremenekc887d132009-04-29 18:50:19 +00002088 if (unsigned Count = CurrV.getCount())
2089 os << " The object now has a +" << Count << " retain count.";
Mike Stump1eb44332009-09-09 15:08:12 +00002090
Ted Kremenekc887d132009-04-29 18:50:19 +00002091 if (PrevV.getKind() == RefVal::Released) {
Jordy Rose35c86952011-08-24 05:47:39 +00002092 assert(GCEnabled && CurrV.getCount() > 0);
Jordy Rose74b7b2b2012-03-17 05:49:15 +00002093 os << " The object is not eligible for garbage collection until "
2094 "the retain count reaches 0 again.";
Ted Kremenekc887d132009-04-29 18:50:19 +00002095 }
Mike Stump1eb44332009-09-09 15:08:12 +00002096
Ted Kremenekc887d132009-04-29 18:50:19 +00002097 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002098
Ted Kremenekc887d132009-04-29 18:50:19 +00002099 case RefVal::Released:
2100 os << "Object released.";
2101 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002102
Ted Kremenekc887d132009-04-29 18:50:19 +00002103 case RefVal::ReturnedOwned:
Jordy Rose74b7b2b2012-03-17 05:49:15 +00002104 // Autoreleases can be applied after marking a node ReturnedOwned.
2105 if (CurrV.getAutoreleaseCount())
2106 return NULL;
2107
2108 os << "Object returned to caller as an owning reference (single "
2109 "retain count transferred to caller)";
Ted Kremenekc887d132009-04-29 18:50:19 +00002110 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002111
Ted Kremenekc887d132009-04-29 18:50:19 +00002112 case RefVal::ReturnedNotOwned:
Ted Kremenekf1365462011-05-26 18:45:44 +00002113 os << "Object returned to caller with a +0 retain count";
Ted Kremenekc887d132009-04-29 18:50:19 +00002114 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002115
Ted Kremenekc887d132009-04-29 18:50:19 +00002116 default:
2117 return NULL;
2118 }
Mike Stump1eb44332009-09-09 15:08:12 +00002119
Ted Kremenekc887d132009-04-29 18:50:19 +00002120 // Emit any remaining diagnostics for the argument effects (if any).
Chris Lattner5f9e2722011-07-23 10:55:15 +00002121 for (SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
Ted Kremenekc887d132009-04-29 18:50:19 +00002122 E=AEffects.end(); I != E; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +00002123
Ted Kremenekc887d132009-04-29 18:50:19 +00002124 // A bunch of things have alternate behavior under GC.
Jordy Rose35c86952011-08-24 05:47:39 +00002125 if (GCEnabled)
Ted Kremenekc887d132009-04-29 18:50:19 +00002126 switch (*I) {
2127 default: break;
2128 case Autorelease:
2129 os << "In GC mode an 'autorelease' has no effect.";
2130 continue;
2131 case IncRefMsg:
2132 os << "In GC mode the 'retain' message has no effect.";
2133 continue;
2134 case DecRefMsg:
2135 os << "In GC mode the 'release' message has no effect.";
2136 continue;
2137 }
2138 }
Mike Stump1eb44332009-09-09 15:08:12 +00002139 } while (0);
2140
Ted Kremenekc887d132009-04-29 18:50:19 +00002141 if (os.str().empty())
2142 return 0; // We have nothing to say!
Ted Kremenek2033a952009-05-13 07:12:33 +00002143
Jordy Rosef53e8c72011-08-23 19:43:16 +00002144 const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
Anna Zaks220ac8c2011-09-15 01:08:34 +00002145 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
2146 N->getLocationContext());
Ted Kremenek9c378f72011-08-12 23:37:29 +00002147 PathDiagnosticPiece *P = new PathDiagnosticEventPiece(Pos, os.str());
Mike Stump1eb44332009-09-09 15:08:12 +00002148
Ted Kremenekc887d132009-04-29 18:50:19 +00002149 // Add the range by scanning the children of the statement for any bindings
2150 // to Sym.
Mike Stump1eb44332009-09-09 15:08:12 +00002151 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
Ted Kremenek5f85e172009-07-22 22:35:28 +00002152 I!=E; ++I)
Ted Kremenek9c378f72011-08-12 23:37:29 +00002153 if (const Expr *Exp = dyn_cast_or_null<Expr>(*I))
Ted Kremenek5eca4822012-01-06 22:09:28 +00002154 if (CurrSt->getSValAsScalarOrLoc(Exp, LCtx).getAsLocSymbol() == Sym) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002155 P->addRange(Exp->getSourceRange());
2156 break;
2157 }
Mike Stump1eb44332009-09-09 15:08:12 +00002158
Ted Kremenekc887d132009-04-29 18:50:19 +00002159 return P;
2160}
2161
Anna Zakse7e01682012-02-28 22:39:22 +00002162// Find the first node in the current function context that referred to the
2163// tracked symbol and the memory location that value was stored to. Note, the
2164// value is only reported if the allocation occurred in the same function as
2165// the leak.
Zhongxing Xuc5619d92009-08-06 01:32:16 +00002166static std::pair<const ExplodedNode*,const MemRegion*>
Ted Kremenek18c66fd2011-08-15 22:09:50 +00002167GetAllocationSite(ProgramStateManager& StateMgr, const ExplodedNode *N,
Ted Kremenekc887d132009-04-29 18:50:19 +00002168 SymbolRef Sym) {
Ted Kremenek9c378f72011-08-12 23:37:29 +00002169 const ExplodedNode *Last = N;
Mike Stump1eb44332009-09-09 15:08:12 +00002170 const MemRegion* FirstBinding = 0;
Anna Zakse7e01682012-02-28 22:39:22 +00002171 const LocationContext *LeakContext = N->getLocationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002172
Ted Kremenekc887d132009-04-29 18:50:19 +00002173 while (N) {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002174 ProgramStateRef St = N->getState();
Mike Stump1eb44332009-09-09 15:08:12 +00002175
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002176 if (!getRefBinding(St, Sym))
Ted Kremenekc887d132009-04-29 18:50:19 +00002177 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002178
Anna Zaks27b867e2012-03-21 19:45:01 +00002179 StoreManager::FindUniqueBinding FB(Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002180 StateMgr.iterBindings(St, FB);
2181 if (FB) FirstBinding = FB.getRegion();
2182
Anna Zakse7e01682012-02-28 22:39:22 +00002183 // Allocation node, is the last node in the current context in which the
2184 // symbol was tracked.
2185 if (N->getLocationContext() == LeakContext)
2186 Last = N;
2187
Mike Stump1eb44332009-09-09 15:08:12 +00002188 N = N->pred_empty() ? NULL : *(N->pred_begin());
Ted Kremenekc887d132009-04-29 18:50:19 +00002189 }
Mike Stump1eb44332009-09-09 15:08:12 +00002190
Anna Zakse7e01682012-02-28 22:39:22 +00002191 // If allocation happened in a function different from the leak node context,
2192 // do not report the binding.
Ted Kremenek5a8fc882012-10-12 22:56:40 +00002193 assert(N && "Could not find allocation node");
Anna Zakse7e01682012-02-28 22:39:22 +00002194 if (N->getLocationContext() != LeakContext) {
2195 FirstBinding = 0;
2196 }
2197
Ted Kremenekc887d132009-04-29 18:50:19 +00002198 return std::make_pair(Last, FirstBinding);
2199}
2200
2201PathDiagnosticPiece*
Anna Zaks23f395e2011-08-20 01:27:22 +00002202CFRefReportVisitor::getEndPath(BugReporterContext &BRC,
2203 const ExplodedNode *EndN,
2204 BugReport &BR) {
Ted Kremenek76aadc32012-03-09 01:13:14 +00002205 BR.markInteresting(Sym);
Anna Zaks23f395e2011-08-20 01:27:22 +00002206 return BugReporterVisitor::getDefaultEndPath(BRC, EndN, BR);
Ted Kremenekc887d132009-04-29 18:50:19 +00002207}
2208
2209PathDiagnosticPiece*
Anna Zaks23f395e2011-08-20 01:27:22 +00002210CFRefLeakReportVisitor::getEndPath(BugReporterContext &BRC,
2211 const ExplodedNode *EndN,
2212 BugReport &BR) {
Mike Stump1eb44332009-09-09 15:08:12 +00002213
Ted Kremenek8966bc12009-05-06 21:39:49 +00002214 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenekc887d132009-04-29 18:50:19 +00002215 // assigned to different variables, etc.
Ted Kremenek76aadc32012-03-09 01:13:14 +00002216 BR.markInteresting(Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002217
Ted Kremenekc887d132009-04-29 18:50:19 +00002218 // We are reporting a leak. Walk up the graph to get to the first node where
2219 // the symbol appeared, and also get the first VarDecl that tracked object
2220 // is stored to.
Ted Kremenek9c378f72011-08-12 23:37:29 +00002221 const ExplodedNode *AllocNode = 0;
Ted Kremenekc887d132009-04-29 18:50:19 +00002222 const MemRegion* FirstBinding = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002223
Ted Kremenekc887d132009-04-29 18:50:19 +00002224 llvm::tie(AllocNode, FirstBinding) =
Ted Kremenekf04dced2009-05-08 23:32:51 +00002225 GetAllocationSite(BRC.getStateManager(), EndN, Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002226
Anna Zaks4fdf97b2011-09-15 18:56:07 +00002227 SourceManager& SM = BRC.getSourceManager();
Mike Stump1eb44332009-09-09 15:08:12 +00002228
Ted Kremenekc887d132009-04-29 18:50:19 +00002229 // Compute an actual location for the leak. Sometimes a leak doesn't
2230 // occur at an actual statement (e.g., transition between blocks; end
2231 // of function) so we need to walk the graph and compute a real location.
Ted Kremenek9c378f72011-08-12 23:37:29 +00002232 const ExplodedNode *LeakN = EndN;
Anna Zaks4fdf97b2011-09-15 18:56:07 +00002233 PathDiagnosticLocation L = PathDiagnosticLocation::createEndOfPath(LeakN, SM);
Mike Stump1eb44332009-09-09 15:08:12 +00002234
Ted Kremenekc887d132009-04-29 18:50:19 +00002235 std::string sbuf;
2236 llvm::raw_string_ostream os(sbuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002237
Ted Kremenekf1365462011-05-26 18:45:44 +00002238 os << "Object leaked: ";
Mike Stump1eb44332009-09-09 15:08:12 +00002239
Ted Kremenekf1365462011-05-26 18:45:44 +00002240 if (FirstBinding) {
2241 os << "object allocated and stored into '"
2242 << FirstBinding->getString() << '\'';
2243 }
2244 else
2245 os << "allocated object";
Mike Stump1eb44332009-09-09 15:08:12 +00002246
Ted Kremenekc887d132009-04-29 18:50:19 +00002247 // Get the retain count.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002248 const RefVal* RV = getRefBinding(EndN->getState(), Sym);
Ted Kremenek5a8fc882012-10-12 22:56:40 +00002249 assert(RV);
Mike Stump1eb44332009-09-09 15:08:12 +00002250
Ted Kremenekc887d132009-04-29 18:50:19 +00002251 if (RV->getKind() == RefVal::ErrorLeakReturned) {
2252 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
Jordy Rose5b5402b2011-07-15 22:17:54 +00002253 // objects. Only "copy", "alloc", "retain" and "new" transfer ownership
Ted Kremenekc887d132009-04-29 18:50:19 +00002254 // to the caller for NS objects.
Ted Kremenekd368d712011-05-25 06:19:45 +00002255 const Decl *D = &EndN->getCodeDecl();
Ted Kremenekec9f36e2012-09-06 23:03:07 +00002256
2257 os << (isa<ObjCMethodDecl>(D) ? " is returned from a method "
2258 : " is returned from a function ");
2259
2260 if (D->getAttr<CFReturnsNotRetainedAttr>())
2261 os << "that is annotated as CF_RETURNS_NOT_RETAINED";
2262 else if (D->getAttr<NSReturnsNotRetainedAttr>())
2263 os << "that is annotated as NS_RETURNS_NOT_RETAINED";
Ted Kremenekd368d712011-05-25 06:19:45 +00002264 else {
Ted Kremenekec9f36e2012-09-06 23:03:07 +00002265 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2266 os << "whose name ('" << MD->getSelector().getAsString()
2267 << "') does not start with 'copy', 'mutableCopy', 'alloc' or 'new'."
2268 " This violates the naming convention rules"
2269 " given in the Memory Management Guide for Cocoa";
2270 }
2271 else {
2272 const FunctionDecl *FD = cast<FunctionDecl>(D);
2273 os << "whose name ('" << *FD
2274 << "') does not contain 'Copy' or 'Create'. This violates the naming"
2275 " convention rules given in the Memory Management Guide for Core"
2276 " Foundation";
2277 }
2278 }
Ted Kremenekc887d132009-04-29 18:50:19 +00002279 }
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002280 else if (RV->getKind() == RefVal::ErrorGCLeakReturned) {
Ted Kremenek9c378f72011-08-12 23:37:29 +00002281 ObjCMethodDecl &MD = cast<ObjCMethodDecl>(EndN->getCodeDecl());
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002282 os << " and returned from method '" << MD.getSelector().getAsString()
Ted Kremenek82f2be52009-05-10 16:52:15 +00002283 << "' is potentially leaked when using garbage collection. Callers "
2284 "of this method do not expect a returned object with a +1 retain "
2285 "count since they expect the object to be managed by the garbage "
2286 "collector";
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002287 }
Ted Kremenekc887d132009-04-29 18:50:19 +00002288 else
Ted Kremenekabf517c2010-10-15 22:50:23 +00002289 os << " is not referenced later in this execution path and has a retain "
Ted Kremenekf1365462011-05-26 18:45:44 +00002290 "count of +" << RV->getCount();
Mike Stump1eb44332009-09-09 15:08:12 +00002291
Ted Kremenekc887d132009-04-29 18:50:19 +00002292 return new PathDiagnosticEventPiece(L, os.str());
2293}
2294
Jordy Rose20589562011-08-24 22:39:09 +00002295CFRefLeakReport::CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts,
2296 bool GCEnabled, const SummaryLogTy &Log,
2297 ExplodedNode *n, SymbolRef sym,
Anna Zaks6a93bd52011-10-25 19:57:11 +00002298 CheckerContext &Ctx)
Jordy Rose20589562011-08-24 22:39:09 +00002299: CFRefReport(D, LOpts, GCEnabled, Log, n, sym, false) {
Mike Stump1eb44332009-09-09 15:08:12 +00002300
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00002301 // Most bug reports are cached at the location where they occurred.
Ted Kremenekc887d132009-04-29 18:50:19 +00002302 // With leaks, we want to unique them by the location where they were
2303 // allocated, and only report a single path. To do this, we need to find
2304 // the allocation site of a piece of tracked memory, which we do via a
2305 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2306 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2307 // that all ancestor nodes that represent the allocation site have the
2308 // same SourceLocation.
Ted Kremenek9c378f72011-08-12 23:37:29 +00002309 const ExplodedNode *AllocNode = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002310
Anna Zaks6a93bd52011-10-25 19:57:11 +00002311 const SourceManager& SMgr = Ctx.getSourceManager();
Anna Zaks590dd8e2011-09-20 21:38:35 +00002312
Ted Kremenekc887d132009-04-29 18:50:19 +00002313 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding.
Anna Zaks6a93bd52011-10-25 19:57:11 +00002314 GetAllocationSite(Ctx.getStateManager(), getErrorNode(), sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002315
Ted Kremenekc887d132009-04-29 18:50:19 +00002316 // Get the SourceLocation for the allocation site.
Jordan Rose852aa0d2012-07-10 22:07:52 +00002317 // FIXME: This will crash the analyzer if an allocation comes from an
2318 // implicit call. (Currently there are no such allocations in Cocoa, though.)
2319 const Stmt *AllocStmt;
Ted Kremenekc887d132009-04-29 18:50:19 +00002320 ProgramPoint P = AllocNode->getLocation();
Jordan Rose852aa0d2012-07-10 22:07:52 +00002321 if (CallExitEnd *Exit = dyn_cast<CallExitEnd>(&P))
2322 AllocStmt = Exit->getCalleeContext()->getCallSite();
2323 else
2324 AllocStmt = cast<PostStmt>(P).getStmt();
2325 assert(AllocStmt && "All allocations must come from explicit calls");
Anna Zaks590dd8e2011-09-20 21:38:35 +00002326 Location = PathDiagnosticLocation::createBegin(AllocStmt, SMgr,
2327 n->getLocationContext());
Ted Kremenekc887d132009-04-29 18:50:19 +00002328 // Fill in the description of the bug.
2329 Description.clear();
2330 llvm::raw_string_ostream os(Description);
Ted Kremenekdd924e22009-05-02 19:05:19 +00002331 os << "Potential leak ";
Jordy Rose20589562011-08-24 22:39:09 +00002332 if (GCEnabled)
Ted Kremenekdd924e22009-05-02 19:05:19 +00002333 os << "(when using garbage collection) ";
Anna Zaks212000e2012-02-28 21:49:08 +00002334 os << "of an object";
Mike Stump1eb44332009-09-09 15:08:12 +00002335
Ted Kremenekc887d132009-04-29 18:50:19 +00002336 // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2337 if (AllocBinding)
Anna Zaks212000e2012-02-28 21:49:08 +00002338 os << " stored into '" << AllocBinding->getString() << '\'';
Anna Zaksdc757b02011-08-19 23:21:56 +00002339
Jordy Rose20589562011-08-24 22:39:09 +00002340 addVisitor(new CFRefLeakReportVisitor(sym, GCEnabled, Log));
Ted Kremenekc887d132009-04-29 18:50:19 +00002341}
2342
2343//===----------------------------------------------------------------------===//
2344// Main checker logic.
2345//===----------------------------------------------------------------------===//
2346
Ted Kremenekd593eb92009-11-25 22:17:44 +00002347namespace {
Jordy Rose910c4052011-09-02 06:44:22 +00002348class RetainCountChecker
Jordy Rose9c083b72011-08-24 18:56:32 +00002349 : public Checker< check::Bind,
Jordy Rose38f17d62011-08-23 19:01:07 +00002350 check::DeadSymbols,
Jordy Rose9c083b72011-08-24 18:56:32 +00002351 check::EndAnalysis,
Jordy Rose38f17d62011-08-23 19:01:07 +00002352 check::EndPath,
Jordy Rose67044292011-08-17 21:27:39 +00002353 check::PostStmt<BlockExpr>,
John McCallf85e1932011-06-15 23:02:42 +00002354 check::PostStmt<CastExpr>,
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002355 check::PostStmt<ObjCArrayLiteral>,
2356 check::PostStmt<ObjCDictionaryLiteral>,
Jordy Rose70fdbc32012-05-12 05:10:43 +00002357 check::PostStmt<ObjCBoxedExpr>,
Jordan Rosefe6a0112012-07-02 19:28:21 +00002358 check::PostCall,
Jordy Rosef53e8c72011-08-23 19:43:16 +00002359 check::PreStmt<ReturnStmt>,
Jordy Rose67044292011-08-17 21:27:39 +00002360 check::RegionChanges,
Jordy Rose76c506f2011-08-21 21:58:18 +00002361 eval::Assume,
2362 eval::Call > {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002363 mutable OwningPtr<CFRefBug> useAfterRelease, releaseNotOwned;
2364 mutable OwningPtr<CFRefBug> deallocGC, deallocNotOwned;
2365 mutable OwningPtr<CFRefBug> overAutorelease, returnNotOwnedForOwned;
2366 mutable OwningPtr<CFRefBug> leakWithinFunction, leakAtReturn;
2367 mutable OwningPtr<CFRefBug> leakWithinFunctionGC, leakAtReturnGC;
Jordy Rose38f17d62011-08-23 19:01:07 +00002368
2369 typedef llvm::DenseMap<SymbolRef, const SimpleProgramPointTag *> SymbolTagMap;
2370
2371 // This map is only used to ensure proper deletion of any allocated tags.
2372 mutable SymbolTagMap DeadSymbolTags;
2373
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002374 mutable OwningPtr<RetainSummaryManager> Summaries;
2375 mutable OwningPtr<RetainSummaryManager> SummariesGC;
Jordy Rose9c083b72011-08-24 18:56:32 +00002376 mutable SummaryLogTy SummaryLog;
2377 mutable bool ShouldResetSummaryLog;
2378
Jordy Rose2f9a66d2011-08-20 21:17:59 +00002379public:
Jordy Rose910c4052011-09-02 06:44:22 +00002380 RetainCountChecker() : ShouldResetSummaryLog(false) {}
Jordy Rose38f17d62011-08-23 19:01:07 +00002381
Jordy Rose910c4052011-09-02 06:44:22 +00002382 virtual ~RetainCountChecker() {
Jordy Rose38f17d62011-08-23 19:01:07 +00002383 DeleteContainerSeconds(DeadSymbolTags);
2384 }
2385
Jordy Rose9c083b72011-08-24 18:56:32 +00002386 void checkEndAnalysis(ExplodedGraph &G, BugReporter &BR,
2387 ExprEngine &Eng) const {
2388 // FIXME: This is a hack to make sure the summary log gets cleared between
2389 // analyses of different code bodies.
2390 //
2391 // Why is this necessary? Because a checker's lifetime is tied to a
2392 // translation unit, but an ExplodedGraph's lifetime is just a code body.
2393 // Once in a blue moon, a new ExplodedNode will have the same address as an
2394 // old one with an associated summary, and the bug report visitor gets very
2395 // confused. (To make things worse, the summary lifetime is currently also
2396 // tied to a code body, so we get a crash instead of incorrect results.)
Jordy Rose1ab51c72011-08-24 09:27:24 +00002397 //
2398 // Why is this a bad solution? Because if the lifetime of the ExplodedGraph
2399 // changes, things will start going wrong again. Really the lifetime of this
2400 // log needs to be tied to either the specific nodes in it or the entire
2401 // ExplodedGraph, not to a specific part of the code being analyzed.
2402 //
Jordy Rose9c083b72011-08-24 18:56:32 +00002403 // (Also, having stateful local data means that the same checker can't be
2404 // used from multiple threads, but a lot of checkers have incorrect
2405 // assumptions about that anyway. So that wasn't a priority at the time of
2406 // this fix.)
Jordy Rose1ab51c72011-08-24 09:27:24 +00002407 //
Jordy Rose9c083b72011-08-24 18:56:32 +00002408 // This happens at the end of analysis, but bug reports are emitted /after/
2409 // this point. So we can't just clear the summary log now. Instead, we mark
2410 // that the next time we access the summary log, it should be cleared.
2411
2412 // If we never reset the summary log during /this/ code body analysis,
2413 // there were no new summaries. There might still have been summaries from
2414 // the /last/ analysis, so clear them out to make sure the bug report
2415 // visitors don't get confused.
2416 if (ShouldResetSummaryLog)
2417 SummaryLog.clear();
2418
2419 ShouldResetSummaryLog = !SummaryLog.empty();
Jordy Rose1ab51c72011-08-24 09:27:24 +00002420 }
2421
Jordy Rose17a38e22011-09-02 05:55:19 +00002422 CFRefBug *getLeakWithinFunctionBug(const LangOptions &LOpts,
2423 bool GCEnabled) const {
2424 if (GCEnabled) {
Jordy Rosedb92bb62011-08-25 01:14:38 +00002425 if (!leakWithinFunctionGC)
Benjamin Kramerfacde172012-06-06 17:32:50 +00002426 leakWithinFunctionGC.reset(new Leak("Leak of object when using "
2427 "garbage collection"));
Jordy Rose17a38e22011-09-02 05:55:19 +00002428 return leakWithinFunctionGC.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002429 } else {
2430 if (!leakWithinFunction) {
Douglas Gregore289d812011-09-13 17:21:33 +00002431 if (LOpts.getGC() == LangOptions::HybridGC) {
Benjamin Kramerfacde172012-06-06 17:32:50 +00002432 leakWithinFunction.reset(new Leak("Leak of object when not using "
2433 "garbage collection (GC) in "
2434 "dual GC/non-GC code"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002435 } else {
Benjamin Kramerfacde172012-06-06 17:32:50 +00002436 leakWithinFunction.reset(new Leak("Leak"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002437 }
2438 }
Jordy Rose17a38e22011-09-02 05:55:19 +00002439 return leakWithinFunction.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002440 }
2441 }
2442
Jordy Rose17a38e22011-09-02 05:55:19 +00002443 CFRefBug *getLeakAtReturnBug(const LangOptions &LOpts, bool GCEnabled) const {
2444 if (GCEnabled) {
Jordy Rosedb92bb62011-08-25 01:14:38 +00002445 if (!leakAtReturnGC)
Benjamin Kramerfacde172012-06-06 17:32:50 +00002446 leakAtReturnGC.reset(new Leak("Leak of returned object when using "
2447 "garbage collection"));
Jordy Rose17a38e22011-09-02 05:55:19 +00002448 return leakAtReturnGC.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002449 } else {
2450 if (!leakAtReturn) {
Douglas Gregore289d812011-09-13 17:21:33 +00002451 if (LOpts.getGC() == LangOptions::HybridGC) {
Benjamin Kramerfacde172012-06-06 17:32:50 +00002452 leakAtReturn.reset(new Leak("Leak of returned object when not using "
2453 "garbage collection (GC) in dual "
2454 "GC/non-GC code"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002455 } else {
Benjamin Kramerfacde172012-06-06 17:32:50 +00002456 leakAtReturn.reset(new Leak("Leak of returned object"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002457 }
2458 }
Jordy Rose17a38e22011-09-02 05:55:19 +00002459 return leakAtReturn.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002460 }
2461 }
2462
Jordy Rose17a38e22011-09-02 05:55:19 +00002463 RetainSummaryManager &getSummaryManager(ASTContext &Ctx,
2464 bool GCEnabled) const {
2465 // FIXME: We don't support ARC being turned on and off during one analysis.
2466 // (nor, for that matter, do we support changing ASTContexts)
David Blaikie4e4d0842012-03-11 07:00:24 +00002467 bool ARCEnabled = (bool)Ctx.getLangOpts().ObjCAutoRefCount;
Jordy Rose17a38e22011-09-02 05:55:19 +00002468 if (GCEnabled) {
2469 if (!SummariesGC)
Jordy Roseb6cfc092011-08-25 00:10:37 +00002470 SummariesGC.reset(new RetainSummaryManager(Ctx, true, ARCEnabled));
Jordy Rose17a38e22011-09-02 05:55:19 +00002471 else
2472 assert(SummariesGC->isARCEnabled() == ARCEnabled);
Jordy Roseb6cfc092011-08-25 00:10:37 +00002473 return *SummariesGC;
2474 } else {
Jordy Rose17a38e22011-09-02 05:55:19 +00002475 if (!Summaries)
Jordy Roseb6cfc092011-08-25 00:10:37 +00002476 Summaries.reset(new RetainSummaryManager(Ctx, false, ARCEnabled));
Jordy Rose17a38e22011-09-02 05:55:19 +00002477 else
2478 assert(Summaries->isARCEnabled() == ARCEnabled);
Jordy Roseb6cfc092011-08-25 00:10:37 +00002479 return *Summaries;
2480 }
2481 }
2482
Jordy Rose17a38e22011-09-02 05:55:19 +00002483 RetainSummaryManager &getSummaryManager(CheckerContext &C) const {
2484 return getSummaryManager(C.getASTContext(), C.isObjCGCEnabled());
2485 }
2486
Ted Kremenek8bef8232012-01-26 21:29:00 +00002487 void printState(raw_ostream &Out, ProgramStateRef State,
Jordy Rosedbd658e2011-08-28 19:11:56 +00002488 const char *NL, const char *Sep) const;
2489
Anna Zaks390909c2011-10-06 00:43:15 +00002490 void checkBind(SVal loc, SVal val, const Stmt *S, CheckerContext &C) const;
Jordy Roseab027fd2011-08-20 21:16:58 +00002491 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
2492 void checkPostStmt(const CastExpr *CE, CheckerContext &C) const;
John McCallf85e1932011-06-15 23:02:42 +00002493
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002494 void checkPostStmt(const ObjCArrayLiteral *AL, CheckerContext &C) const;
2495 void checkPostStmt(const ObjCDictionaryLiteral *DL, CheckerContext &C) const;
Jordy Rose70fdbc32012-05-12 05:10:43 +00002496 void checkPostStmt(const ObjCBoxedExpr *BE, CheckerContext &C) const;
2497
Jordan Rosefe6a0112012-07-02 19:28:21 +00002498 void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002499
Jordan Rose4531b7d2012-07-02 19:27:43 +00002500 void checkSummary(const RetainSummary &Summ, const CallEvent &Call,
Jordy Rosee38dd952011-08-28 05:16:28 +00002501 CheckerContext &C) const;
Jordy Rose294396b2011-08-22 23:48:23 +00002502
Anna Zaks554067f2012-08-29 23:23:43 +00002503 void processSummaryOfInlined(const RetainSummary &Summ,
2504 const CallEvent &Call,
2505 CheckerContext &C) const;
2506
Jordy Rose76c506f2011-08-21 21:58:18 +00002507 bool evalCall(const CallExpr *CE, CheckerContext &C) const;
2508
Ted Kremenek8bef8232012-01-26 21:29:00 +00002509 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Jordy Roseab027fd2011-08-20 21:16:58 +00002510 bool Assumption) const;
Jordy Rose67044292011-08-17 21:27:39 +00002511
Ted Kremenek8bef8232012-01-26 21:29:00 +00002512 ProgramStateRef
2513 checkRegionChanges(ProgramStateRef state,
Jordy Rose537716a2011-08-27 22:51:26 +00002514 const StoreManager::InvalidatedSymbols *invalidated,
2515 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00002516 ArrayRef<const MemRegion *> Regions,
Jordan Rose740d4902012-07-02 19:27:35 +00002517 const CallEvent *Call) const;
Jordy Roseab027fd2011-08-20 21:16:58 +00002518
Ted Kremenek8bef8232012-01-26 21:29:00 +00002519 bool wantsRegionChangeUpdate(ProgramStateRef state) const {
Jordy Rose2f9a66d2011-08-20 21:17:59 +00002520 return true;
Jordy Roseab027fd2011-08-20 21:16:58 +00002521 }
Jordy Rose294396b2011-08-22 23:48:23 +00002522
Jordy Rosef53e8c72011-08-23 19:43:16 +00002523 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
2524 void checkReturnWithRetEffect(const ReturnStmt *S, CheckerContext &C,
2525 ExplodedNode *Pred, RetEffect RE, RefVal X,
Ted Kremenek8bef8232012-01-26 21:29:00 +00002526 SymbolRef Sym, ProgramStateRef state) const;
Jordy Rosef53e8c72011-08-23 19:43:16 +00002527
Jordy Rose38f17d62011-08-23 19:01:07 +00002528 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Anna Zaksaf498a22011-10-25 19:56:48 +00002529 void checkEndPath(CheckerContext &C) const;
Jordy Rose38f17d62011-08-23 19:01:07 +00002530
Ted Kremenek8bef8232012-01-26 21:29:00 +00002531 ProgramStateRef updateSymbol(ProgramStateRef state, SymbolRef sym,
Anna Zaks554067f2012-08-29 23:23:43 +00002532 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
2533 CheckerContext &C) const;
Jordy Rosee0a5d322011-08-23 20:27:16 +00002534
Ted Kremenek8bef8232012-01-26 21:29:00 +00002535 void processNonLeakError(ProgramStateRef St, SourceRange ErrorRange,
Jordy Rose294396b2011-08-22 23:48:23 +00002536 RefVal::Kind ErrorKind, SymbolRef Sym,
2537 CheckerContext &C) const;
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002538
2539 void processObjCLiterals(CheckerContext &C, const Expr *Ex) const;
Jordy Rose294396b2011-08-22 23:48:23 +00002540
Jordy Rose38f17d62011-08-23 19:01:07 +00002541 const ProgramPointTag *getDeadSymbolTag(SymbolRef sym) const;
2542
Ted Kremenek8bef8232012-01-26 21:29:00 +00002543 ProgramStateRef handleSymbolDeath(ProgramStateRef state,
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002544 SymbolRef sid, RefVal V,
2545 SmallVectorImpl<SymbolRef> &Leaked) const;
Jordy Rose38f17d62011-08-23 19:01:07 +00002546
Ted Kremenek8bef8232012-01-26 21:29:00 +00002547 std::pair<ExplodedNode *, ProgramStateRef >
Jordan Rose2bce86c2012-08-18 00:30:16 +00002548 handleAutoreleaseCounts(ProgramStateRef state, ExplodedNode *Pred,
2549 const ProgramPointTag *Tag, CheckerContext &Ctx,
2550 SymbolRef Sym, RefVal V) const;
Jordy Rose8d228632011-08-23 20:07:14 +00002551
Ted Kremenek8bef8232012-01-26 21:29:00 +00002552 ExplodedNode *processLeaks(ProgramStateRef state,
Jordy Rose38f17d62011-08-23 19:01:07 +00002553 SmallVectorImpl<SymbolRef> &Leaked,
Anna Zaks6a93bd52011-10-25 19:57:11 +00002554 CheckerContext &Ctx,
Jordy Rose38f17d62011-08-23 19:01:07 +00002555 ExplodedNode *Pred = 0) const;
Ted Kremenekd593eb92009-11-25 22:17:44 +00002556};
2557} // end anonymous namespace
2558
Jordy Rose67044292011-08-17 21:27:39 +00002559namespace {
2560class StopTrackingCallback : public SymbolVisitor {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002561 ProgramStateRef state;
Jordy Rose67044292011-08-17 21:27:39 +00002562public:
Ted Kremenek8bef8232012-01-26 21:29:00 +00002563 StopTrackingCallback(ProgramStateRef st) : state(st) {}
2564 ProgramStateRef getState() const { return state; }
Jordy Rose67044292011-08-17 21:27:39 +00002565
2566 bool VisitSymbol(SymbolRef sym) {
2567 state = state->remove<RefBindings>(sym);
2568 return true;
2569 }
2570};
2571} // end anonymous namespace
2572
Jordy Rose910c4052011-09-02 06:44:22 +00002573//===----------------------------------------------------------------------===//
2574// Handle statements that may have an effect on refcounts.
2575//===----------------------------------------------------------------------===//
Jordy Rose67044292011-08-17 21:27:39 +00002576
Jordy Rose910c4052011-09-02 06:44:22 +00002577void RetainCountChecker::checkPostStmt(const BlockExpr *BE,
2578 CheckerContext &C) const {
Jordy Rose67044292011-08-17 21:27:39 +00002579
Jordy Rose910c4052011-09-02 06:44:22 +00002580 // Scan the BlockDecRefExprs for any object the retain count checker
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002581 // may be tracking.
John McCall469a1eb2011-02-02 13:00:07 +00002582 if (!BE->getBlockDecl()->hasCaptures())
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002583 return;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002584
Ted Kremenek8bef8232012-01-26 21:29:00 +00002585 ProgramStateRef state = C.getState();
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002586 const BlockDataRegion *R =
Ted Kremenek5eca4822012-01-06 22:09:28 +00002587 cast<BlockDataRegion>(state->getSVal(BE,
2588 C.getLocationContext()).getAsRegion());
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002589
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002590 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
2591 E = R->referenced_vars_end();
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002592
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002593 if (I == E)
2594 return;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002595
Ted Kremenek67d12872009-12-07 22:05:27 +00002596 // FIXME: For now we invalidate the tracking of all symbols passed to blocks
2597 // via captured variables, even though captured variables result in a copy
2598 // and in implicit increment/decrement of a retain count.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002599 SmallVector<const MemRegion*, 10> Regions;
Anna Zaks39ac1872011-10-26 21:06:44 +00002600 const LocationContext *LC = C.getLocationContext();
Ted Kremenekc8413fd2010-12-02 07:49:45 +00002601 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002602
Ted Kremenek67d12872009-12-07 22:05:27 +00002603 for ( ; I != E; ++I) {
2604 const VarRegion *VR = *I;
2605 if (VR->getSuperRegion() == R) {
2606 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2607 }
2608 Regions.push_back(VR);
2609 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002610
Ted Kremenek67d12872009-12-07 22:05:27 +00002611 state =
2612 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
2613 Regions.data() + Regions.size()).getState();
Anna Zaks0bd6b112011-10-26 21:06:34 +00002614 C.addTransition(state);
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002615}
2616
Jordy Rose910c4052011-09-02 06:44:22 +00002617void RetainCountChecker::checkPostStmt(const CastExpr *CE,
2618 CheckerContext &C) const {
John McCallf85e1932011-06-15 23:02:42 +00002619 const ObjCBridgedCastExpr *BE = dyn_cast<ObjCBridgedCastExpr>(CE);
2620 if (!BE)
2621 return;
2622
John McCall71c482c2011-06-17 06:50:50 +00002623 ArgEffect AE = IncRef;
John McCallf85e1932011-06-15 23:02:42 +00002624
2625 switch (BE->getBridgeKind()) {
2626 case clang::OBC_Bridge:
2627 // Do nothing.
2628 return;
2629 case clang::OBC_BridgeRetained:
2630 AE = IncRef;
2631 break;
2632 case clang::OBC_BridgeTransfer:
2633 AE = DecRefBridgedTransfered;
2634 break;
2635 }
2636
Ted Kremenek8bef8232012-01-26 21:29:00 +00002637 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00002638 SymbolRef Sym = state->getSVal(CE, C.getLocationContext()).getAsLocSymbol();
John McCallf85e1932011-06-15 23:02:42 +00002639 if (!Sym)
2640 return;
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002641 const RefVal* T = getRefBinding(state, Sym);
John McCallf85e1932011-06-15 23:02:42 +00002642 if (!T)
2643 return;
2644
John McCallf85e1932011-06-15 23:02:42 +00002645 RefVal::Kind hasErr = (RefVal::Kind) 0;
Jordy Rose17a38e22011-09-02 05:55:19 +00002646 state = updateSymbol(state, Sym, *T, AE, hasErr, C);
John McCallf85e1932011-06-15 23:02:42 +00002647
2648 if (hasErr) {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002649 // FIXME: If we get an error during a bridge cast, should we report it?
2650 // Should we assert that there is no error?
John McCallf85e1932011-06-15 23:02:42 +00002651 return;
2652 }
2653
Anna Zaks0bd6b112011-10-26 21:06:34 +00002654 C.addTransition(state);
John McCallf85e1932011-06-15 23:02:42 +00002655}
2656
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002657void RetainCountChecker::processObjCLiterals(CheckerContext &C,
2658 const Expr *Ex) const {
2659 ProgramStateRef state = C.getState();
2660 const ExplodedNode *pred = C.getPredecessor();
2661 for (Stmt::const_child_iterator it = Ex->child_begin(), et = Ex->child_end() ;
2662 it != et ; ++it) {
2663 const Stmt *child = *it;
2664 SVal V = state->getSVal(child, pred->getLocationContext());
2665 if (SymbolRef sym = V.getAsSymbol())
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002666 if (const RefVal* T = getRefBinding(state, sym)) {
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002667 RefVal::Kind hasErr = (RefVal::Kind) 0;
2668 state = updateSymbol(state, sym, *T, MayEscape, hasErr, C);
2669 if (hasErr) {
2670 processNonLeakError(state, child->getSourceRange(), hasErr, sym, C);
2671 return;
2672 }
2673 }
2674 }
2675
2676 // Return the object as autoreleased.
2677 // RetEffect RE = RetEffect::MakeNotOwned(RetEffect::ObjC);
2678 if (SymbolRef sym =
2679 state->getSVal(Ex, pred->getLocationContext()).getAsSymbol()) {
2680 QualType ResultTy = Ex->getType();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002681 state = setRefBinding(state, sym,
2682 RefVal::makeNotOwned(RetEffect::ObjC, ResultTy));
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002683 }
2684
2685 C.addTransition(state);
2686}
2687
2688void RetainCountChecker::checkPostStmt(const ObjCArrayLiteral *AL,
2689 CheckerContext &C) const {
2690 // Apply the 'MayEscape' to all values.
2691 processObjCLiterals(C, AL);
2692}
2693
2694void RetainCountChecker::checkPostStmt(const ObjCDictionaryLiteral *DL,
2695 CheckerContext &C) const {
2696 // Apply the 'MayEscape' to all keys and values.
2697 processObjCLiterals(C, DL);
2698}
2699
Jordy Rose70fdbc32012-05-12 05:10:43 +00002700void RetainCountChecker::checkPostStmt(const ObjCBoxedExpr *Ex,
2701 CheckerContext &C) const {
2702 const ExplodedNode *Pred = C.getPredecessor();
2703 const LocationContext *LCtx = Pred->getLocationContext();
2704 ProgramStateRef State = Pred->getState();
2705
2706 if (SymbolRef Sym = State->getSVal(Ex, LCtx).getAsSymbol()) {
2707 QualType ResultTy = Ex->getType();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002708 State = setRefBinding(State, Sym,
2709 RefVal::makeNotOwned(RetEffect::ObjC, ResultTy));
Jordy Rose70fdbc32012-05-12 05:10:43 +00002710 }
2711
2712 C.addTransition(State);
2713}
2714
Jordan Rosefe6a0112012-07-02 19:28:21 +00002715void RetainCountChecker::checkPostCall(const CallEvent &Call,
2716 CheckerContext &C) const {
Jordan Rosefe6a0112012-07-02 19:28:21 +00002717 RetainSummaryManager &Summaries = getSummaryManager(C);
2718 const RetainSummary *Summ = Summaries.getSummary(Call, C.getState());
Anna Zaks554067f2012-08-29 23:23:43 +00002719
2720 if (C.wasInlined) {
2721 processSummaryOfInlined(*Summ, Call, C);
2722 return;
2723 }
Jordan Rosefe6a0112012-07-02 19:28:21 +00002724 checkSummary(*Summ, Call, C);
Jordy Rose294396b2011-08-22 23:48:23 +00002725}
2726
Jordy Rose910c4052011-09-02 06:44:22 +00002727/// GetReturnType - Used to get the return type of a message expression or
2728/// function call with the intention of affixing that type to a tracked symbol.
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +00002729/// While the return type can be queried directly from RetEx, when
Jordy Rose910c4052011-09-02 06:44:22 +00002730/// invoking class methods we augment to the return type to be that of
2731/// a pointer to the class (as opposed it just being id).
2732// FIXME: We may be able to do this with related result types instead.
2733// This function is probably overestimating.
2734static QualType GetReturnType(const Expr *RetE, ASTContext &Ctx) {
2735 QualType RetTy = RetE->getType();
2736 // If RetE is not a message expression just return its type.
2737 // If RetE is a message expression, return its types if it is something
2738 /// more specific than id.
2739 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RetE))
2740 if (const ObjCObjectPointerType *PT = RetTy->getAs<ObjCObjectPointerType>())
2741 if (PT->isObjCQualifiedIdType() || PT->isObjCIdType() ||
2742 PT->isObjCClassType()) {
2743 // At this point we know the return type of the message expression is
2744 // id, id<...>, or Class. If we have an ObjCInterfaceDecl, we know this
2745 // is a call to a class method whose type we can resolve. In such
2746 // cases, promote the return type to XXX* (where XXX is the class).
2747 const ObjCInterfaceDecl *D = ME->getReceiverInterface();
2748 return !D ? RetTy :
2749 Ctx.getObjCObjectPointerType(Ctx.getObjCInterfaceType(D));
2750 }
2751
2752 return RetTy;
2753}
2754
Anna Zaks554067f2012-08-29 23:23:43 +00002755// We don't always get the exact modeling of the function with regards to the
2756// retain count checker even when the function is inlined. For example, we need
2757// to stop tracking the symbols which were marked with StopTrackingHard.
2758void RetainCountChecker::processSummaryOfInlined(const RetainSummary &Summ,
2759 const CallEvent &CallOrMsg,
2760 CheckerContext &C) const {
2761 ProgramStateRef state = C.getState();
2762
2763 // Evaluate the effect of the arguments.
2764 for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
2765 if (Summ.getArg(idx) == StopTrackingHard) {
2766 SVal V = CallOrMsg.getArgSVal(idx);
2767 if (SymbolRef Sym = V.getAsLocSymbol()) {
2768 state = removeRefBinding(state, Sym);
2769 }
2770 }
2771 }
2772
2773 // Evaluate the effect on the message receiver.
2774 const ObjCMethodCall *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg);
2775 if (MsgInvocation) {
2776 if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
2777 if (Summ.getReceiverEffect() == StopTrackingHard) {
2778 state = removeRefBinding(state, Sym);
2779 }
2780 }
2781 }
2782
2783 // Consult the summary for the return value.
2784 RetEffect RE = Summ.getRetEffect();
2785 if (RE.getKind() == RetEffect::NoRetHard) {
Jordan Rose2f3017f2012-11-02 23:49:29 +00002786 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
Anna Zaks554067f2012-08-29 23:23:43 +00002787 if (Sym)
2788 state = removeRefBinding(state, Sym);
2789 }
2790
2791 C.addTransition(state);
2792}
2793
Jordy Rose910c4052011-09-02 06:44:22 +00002794void RetainCountChecker::checkSummary(const RetainSummary &Summ,
Jordan Rose4531b7d2012-07-02 19:27:43 +00002795 const CallEvent &CallOrMsg,
Jordy Rose910c4052011-09-02 06:44:22 +00002796 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002797 ProgramStateRef state = C.getState();
Jordy Rose294396b2011-08-22 23:48:23 +00002798
2799 // Evaluate the effect of the arguments.
2800 RefVal::Kind hasErr = (RefVal::Kind) 0;
2801 SourceRange ErrorRange;
2802 SymbolRef ErrorSym = 0;
2803
2804 for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
Jordy Rose537716a2011-08-27 22:51:26 +00002805 SVal V = CallOrMsg.getArgSVal(idx);
Jordy Rose294396b2011-08-22 23:48:23 +00002806
2807 if (SymbolRef Sym = V.getAsLocSymbol()) {
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002808 if (const RefVal *T = getRefBinding(state, Sym)) {
Jordy Rose17a38e22011-09-02 05:55:19 +00002809 state = updateSymbol(state, Sym, *T, Summ.getArg(idx), hasErr, C);
Jordy Rose294396b2011-08-22 23:48:23 +00002810 if (hasErr) {
2811 ErrorRange = CallOrMsg.getArgSourceRange(idx);
2812 ErrorSym = Sym;
2813 break;
2814 }
2815 }
2816 }
2817 }
2818
2819 // Evaluate the effect on the message receiver.
2820 bool ReceiverIsTracked = false;
Jordan Rose4531b7d2012-07-02 19:27:43 +00002821 if (!hasErr) {
Jordan Rosecde8cdb2012-07-02 19:27:56 +00002822 const ObjCMethodCall *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg);
Jordan Rose4531b7d2012-07-02 19:27:43 +00002823 if (MsgInvocation) {
2824 if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002825 if (const RefVal *T = getRefBinding(state, Sym)) {
Jordan Rose4531b7d2012-07-02 19:27:43 +00002826 ReceiverIsTracked = true;
2827 state = updateSymbol(state, Sym, *T, Summ.getReceiverEffect(),
Anna Zaks554067f2012-08-29 23:23:43 +00002828 hasErr, C);
Jordan Rose4531b7d2012-07-02 19:27:43 +00002829 if (hasErr) {
Jordan Rose8919e682012-07-18 21:59:51 +00002830 ErrorRange = MsgInvocation->getOriginExpr()->getReceiverRange();
Jordan Rose4531b7d2012-07-02 19:27:43 +00002831 ErrorSym = Sym;
2832 }
Jordy Rose294396b2011-08-22 23:48:23 +00002833 }
2834 }
2835 }
2836 }
2837
2838 // Process any errors.
2839 if (hasErr) {
2840 processNonLeakError(state, ErrorRange, hasErr, ErrorSym, C);
2841 return;
2842 }
2843
2844 // Consult the summary for the return value.
2845 RetEffect RE = Summ.getRetEffect();
2846
2847 if (RE.getKind() == RetEffect::OwnedWhenTrackedReceiver) {
Jordy Roseb6cfc092011-08-25 00:10:37 +00002848 if (ReceiverIsTracked)
Jordy Rose17a38e22011-09-02 05:55:19 +00002849 RE = getSummaryManager(C).getObjAllocRetEffect();
Jordy Roseb6cfc092011-08-25 00:10:37 +00002850 else
Jordy Rose294396b2011-08-22 23:48:23 +00002851 RE = RetEffect::MakeNoRet();
2852 }
2853
2854 switch (RE.getKind()) {
2855 default:
David Blaikie7530c032012-01-17 06:56:22 +00002856 llvm_unreachable("Unhandled RetEffect.");
Jordy Rose294396b2011-08-22 23:48:23 +00002857
2858 case RetEffect::NoRet:
Anna Zaks554067f2012-08-29 23:23:43 +00002859 case RetEffect::NoRetHard:
Jordy Rose294396b2011-08-22 23:48:23 +00002860 // No work necessary.
2861 break;
2862
2863 case RetEffect::OwnedAllocatedSymbol:
2864 case RetEffect::OwnedSymbol: {
Jordan Rose2f3017f2012-11-02 23:49:29 +00002865 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
Jordy Rose294396b2011-08-22 23:48:23 +00002866 if (!Sym)
2867 break;
2868
Jordan Rose4531b7d2012-07-02 19:27:43 +00002869 // Use the result type from the CallEvent as it automatically adjusts
Jordy Rose294396b2011-08-22 23:48:23 +00002870 // for methods/functions that return references.
Jordan Rose4531b7d2012-07-02 19:27:43 +00002871 QualType ResultTy = CallOrMsg.getResultType();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002872 state = setRefBinding(state, Sym, RefVal::makeOwned(RE.getObjKind(),
2873 ResultTy));
Jordy Rose294396b2011-08-22 23:48:23 +00002874
2875 // FIXME: Add a flag to the checker where allocations are assumed to
Anna Zaksc6ba23f2012-08-14 15:39:13 +00002876 // *not* fail.
Jordy Rose294396b2011-08-22 23:48:23 +00002877 break;
2878 }
2879
2880 case RetEffect::GCNotOwnedSymbol:
2881 case RetEffect::ARCNotOwnedSymbol:
2882 case RetEffect::NotOwnedSymbol: {
2883 const Expr *Ex = CallOrMsg.getOriginExpr();
Jordan Rose2f3017f2012-11-02 23:49:29 +00002884 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
Jordy Rose294396b2011-08-22 23:48:23 +00002885 if (!Sym)
2886 break;
Ted Kremenek74616822012-10-12 22:56:45 +00002887 assert(Ex);
Jordy Rose294396b2011-08-22 23:48:23 +00002888 // Use GetReturnType in order to give [NSFoo alloc] the type NSFoo *.
2889 QualType ResultTy = GetReturnType(Ex, C.getASTContext());
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002890 state = setRefBinding(state, Sym, RefVal::makeNotOwned(RE.getObjKind(),
2891 ResultTy));
Jordy Rose294396b2011-08-22 23:48:23 +00002892 break;
2893 }
2894 }
2895
2896 // This check is actually necessary; otherwise the statement builder thinks
2897 // we've hit a previously-found path.
2898 // Normally addTransition takes care of this, but we want the node pointer.
2899 ExplodedNode *NewNode;
2900 if (state == C.getState()) {
2901 NewNode = C.getPredecessor();
2902 } else {
Anna Zaks0bd6b112011-10-26 21:06:34 +00002903 NewNode = C.addTransition(state);
Jordy Rose294396b2011-08-22 23:48:23 +00002904 }
2905
Jordy Rose9c083b72011-08-24 18:56:32 +00002906 // Annotate the node with summary we used.
2907 if (NewNode) {
2908 // FIXME: This is ugly. See checkEndAnalysis for why it's necessary.
2909 if (ShouldResetSummaryLog) {
2910 SummaryLog.clear();
2911 ShouldResetSummaryLog = false;
2912 }
Jordy Roseec9ef852011-08-23 20:55:48 +00002913 SummaryLog[NewNode] = &Summ;
Jordy Rose9c083b72011-08-24 18:56:32 +00002914 }
Jordy Rose294396b2011-08-22 23:48:23 +00002915}
2916
Jordy Rosee0a5d322011-08-23 20:27:16 +00002917
Ted Kremenek8bef8232012-01-26 21:29:00 +00002918ProgramStateRef
2919RetainCountChecker::updateSymbol(ProgramStateRef state, SymbolRef sym,
Jordy Rose910c4052011-09-02 06:44:22 +00002920 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
2921 CheckerContext &C) const {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002922 // In GC mode [... release] and [... retain] do nothing.
Jordy Rose910c4052011-09-02 06:44:22 +00002923 // In ARC mode they shouldn't exist at all, but we just ignore them.
Jordy Rose17a38e22011-09-02 05:55:19 +00002924 bool IgnoreRetainMsg = C.isObjCGCEnabled();
2925 if (!IgnoreRetainMsg)
David Blaikie4e4d0842012-03-11 07:00:24 +00002926 IgnoreRetainMsg = (bool)C.getASTContext().getLangOpts().ObjCAutoRefCount;
Jordy Rose17a38e22011-09-02 05:55:19 +00002927
Jordy Rosee0a5d322011-08-23 20:27:16 +00002928 switch (E) {
Jordan Rose4531b7d2012-07-02 19:27:43 +00002929 default:
2930 break;
2931 case IncRefMsg:
2932 E = IgnoreRetainMsg ? DoNothing : IncRef;
2933 break;
2934 case DecRefMsg:
2935 E = IgnoreRetainMsg ? DoNothing : DecRef;
2936 break;
Anna Zaks554067f2012-08-29 23:23:43 +00002937 case DecRefMsgAndStopTrackingHard:
2938 E = IgnoreRetainMsg ? StopTracking : DecRefAndStopTrackingHard;
Jordan Rose4531b7d2012-07-02 19:27:43 +00002939 break;
2940 case MakeCollectable:
2941 E = C.isObjCGCEnabled() ? DecRef : DoNothing;
2942 break;
2943 case NewAutoreleasePool:
2944 E = C.isObjCGCEnabled() ? DoNothing : NewAutoreleasePool;
2945 break;
Jordy Rosee0a5d322011-08-23 20:27:16 +00002946 }
2947
2948 // Handle all use-after-releases.
Jordy Rose17a38e22011-09-02 05:55:19 +00002949 if (!C.isObjCGCEnabled() && V.getKind() == RefVal::Released) {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002950 V = V ^ RefVal::ErrorUseAfterRelease;
2951 hasErr = V.getKind();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002952 return setRefBinding(state, sym, V);
Jordy Rosee0a5d322011-08-23 20:27:16 +00002953 }
2954
2955 switch (E) {
2956 case DecRefMsg:
2957 case IncRefMsg:
2958 case MakeCollectable:
Anna Zaks554067f2012-08-29 23:23:43 +00002959 case DecRefMsgAndStopTrackingHard:
Jordy Rosee0a5d322011-08-23 20:27:16 +00002960 llvm_unreachable("DecRefMsg/IncRefMsg/MakeCollectable already converted");
Jordy Rosee0a5d322011-08-23 20:27:16 +00002961
2962 case Dealloc:
2963 // Any use of -dealloc in GC is *bad*.
Jordy Rose17a38e22011-09-02 05:55:19 +00002964 if (C.isObjCGCEnabled()) {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002965 V = V ^ RefVal::ErrorDeallocGC;
2966 hasErr = V.getKind();
2967 break;
2968 }
2969
2970 switch (V.getKind()) {
2971 default:
2972 llvm_unreachable("Invalid RefVal state for an explicit dealloc.");
Jordy Rosee0a5d322011-08-23 20:27:16 +00002973 case RefVal::Owned:
2974 // The object immediately transitions to the released state.
2975 V = V ^ RefVal::Released;
2976 V.clearCounts();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002977 return setRefBinding(state, sym, V);
Jordy Rosee0a5d322011-08-23 20:27:16 +00002978 case RefVal::NotOwned:
2979 V = V ^ RefVal::ErrorDeallocNotOwned;
2980 hasErr = V.getKind();
2981 break;
2982 }
2983 break;
2984
2985 case NewAutoreleasePool:
Jordy Rose17a38e22011-09-02 05:55:19 +00002986 assert(!C.isObjCGCEnabled());
Anna Zaksc95bb762012-08-14 00:36:17 +00002987 return state;
Jordy Rosee0a5d322011-08-23 20:27:16 +00002988
2989 case MayEscape:
2990 if (V.getKind() == RefVal::Owned) {
2991 V = V ^ RefVal::NotOwned;
2992 break;
2993 }
2994
2995 // Fall-through.
2996
Jordy Rosee0a5d322011-08-23 20:27:16 +00002997 case DoNothing:
2998 return state;
2999
3000 case Autorelease:
Jordy Rose17a38e22011-09-02 05:55:19 +00003001 if (C.isObjCGCEnabled())
Jordy Rosee0a5d322011-08-23 20:27:16 +00003002 return state;
Jordy Rosee0a5d322011-08-23 20:27:16 +00003003 // Update the autorelease counts.
Jordy Rosee0a5d322011-08-23 20:27:16 +00003004 V = V.autorelease();
3005 break;
3006
3007 case StopTracking:
Anna Zaks554067f2012-08-29 23:23:43 +00003008 case StopTrackingHard:
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003009 return removeRefBinding(state, sym);
Jordy Rosee0a5d322011-08-23 20:27:16 +00003010
3011 case IncRef:
3012 switch (V.getKind()) {
3013 default:
3014 llvm_unreachable("Invalid RefVal state for a retain.");
Jordy Rosee0a5d322011-08-23 20:27:16 +00003015 case RefVal::Owned:
3016 case RefVal::NotOwned:
3017 V = V + 1;
3018 break;
3019 case RefVal::Released:
3020 // Non-GC cases are handled above.
Jordy Rose17a38e22011-09-02 05:55:19 +00003021 assert(C.isObjCGCEnabled());
Jordy Rosee0a5d322011-08-23 20:27:16 +00003022 V = (V ^ RefVal::Owned) + 1;
3023 break;
3024 }
3025 break;
3026
Jordy Rosee0a5d322011-08-23 20:27:16 +00003027 case DecRef:
3028 case DecRefBridgedTransfered:
Anna Zaks554067f2012-08-29 23:23:43 +00003029 case DecRefAndStopTrackingHard:
Jordy Rosee0a5d322011-08-23 20:27:16 +00003030 switch (V.getKind()) {
3031 default:
3032 // case 'RefVal::Released' handled above.
3033 llvm_unreachable("Invalid RefVal state for a release.");
Jordy Rosee0a5d322011-08-23 20:27:16 +00003034
3035 case RefVal::Owned:
3036 assert(V.getCount() > 0);
3037 if (V.getCount() == 1)
3038 V = V ^ (E == DecRefBridgedTransfered ?
3039 RefVal::NotOwned : RefVal::Released);
Anna Zaks554067f2012-08-29 23:23:43 +00003040 else if (E == DecRefAndStopTrackingHard)
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003041 return removeRefBinding(state, sym);
Jordan Rose4531b7d2012-07-02 19:27:43 +00003042
Jordy Rosee0a5d322011-08-23 20:27:16 +00003043 V = V - 1;
3044 break;
3045
3046 case RefVal::NotOwned:
Jordan Rose4531b7d2012-07-02 19:27:43 +00003047 if (V.getCount() > 0) {
Anna Zaks554067f2012-08-29 23:23:43 +00003048 if (E == DecRefAndStopTrackingHard)
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003049 return removeRefBinding(state, sym);
Jordy Rosee0a5d322011-08-23 20:27:16 +00003050 V = V - 1;
Jordan Rose4531b7d2012-07-02 19:27:43 +00003051 } else {
Jordy Rosee0a5d322011-08-23 20:27:16 +00003052 V = V ^ RefVal::ErrorReleaseNotOwned;
3053 hasErr = V.getKind();
3054 }
3055 break;
3056
3057 case RefVal::Released:
3058 // Non-GC cases are handled above.
Jordy Rose17a38e22011-09-02 05:55:19 +00003059 assert(C.isObjCGCEnabled());
Jordy Rosee0a5d322011-08-23 20:27:16 +00003060 V = V ^ RefVal::ErrorUseAfterRelease;
3061 hasErr = V.getKind();
3062 break;
3063 }
3064 break;
3065 }
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003066 return setRefBinding(state, sym, V);
Jordy Rosee0a5d322011-08-23 20:27:16 +00003067}
3068
Ted Kremenek8bef8232012-01-26 21:29:00 +00003069void RetainCountChecker::processNonLeakError(ProgramStateRef St,
Jordy Rose910c4052011-09-02 06:44:22 +00003070 SourceRange ErrorRange,
3071 RefVal::Kind ErrorKind,
3072 SymbolRef Sym,
3073 CheckerContext &C) const {
Jordy Rose294396b2011-08-22 23:48:23 +00003074 ExplodedNode *N = C.generateSink(St);
3075 if (!N)
3076 return;
3077
Jordy Rose294396b2011-08-22 23:48:23 +00003078 CFRefBug *BT;
3079 switch (ErrorKind) {
3080 default:
3081 llvm_unreachable("Unhandled error.");
Jordy Rose294396b2011-08-22 23:48:23 +00003082 case RefVal::ErrorUseAfterRelease:
Jordy Rosed6334e12011-08-25 00:34:03 +00003083 if (!useAfterRelease)
3084 useAfterRelease.reset(new UseAfterRelease());
3085 BT = &*useAfterRelease;
Jordy Rose294396b2011-08-22 23:48:23 +00003086 break;
3087 case RefVal::ErrorReleaseNotOwned:
Jordy Rosed6334e12011-08-25 00:34:03 +00003088 if (!releaseNotOwned)
3089 releaseNotOwned.reset(new BadRelease());
3090 BT = &*releaseNotOwned;
Jordy Rose294396b2011-08-22 23:48:23 +00003091 break;
3092 case RefVal::ErrorDeallocGC:
Jordy Rosed6334e12011-08-25 00:34:03 +00003093 if (!deallocGC)
3094 deallocGC.reset(new DeallocGC());
3095 BT = &*deallocGC;
Jordy Rose294396b2011-08-22 23:48:23 +00003096 break;
3097 case RefVal::ErrorDeallocNotOwned:
Jordy Rosed6334e12011-08-25 00:34:03 +00003098 if (!deallocNotOwned)
3099 deallocNotOwned.reset(new DeallocNotOwned());
3100 BT = &*deallocNotOwned;
Jordy Rose294396b2011-08-22 23:48:23 +00003101 break;
3102 }
3103
Jordy Rosed6334e12011-08-25 00:34:03 +00003104 assert(BT);
David Blaikie4e4d0842012-03-11 07:00:24 +00003105 CFRefReport *report = new CFRefReport(*BT, C.getASTContext().getLangOpts(),
Jordy Rose17a38e22011-09-02 05:55:19 +00003106 C.isObjCGCEnabled(), SummaryLog,
3107 N, Sym);
Jordy Rose294396b2011-08-22 23:48:23 +00003108 report->addRange(ErrorRange);
Jordan Rose785950e2012-11-02 01:53:40 +00003109 C.emitReport(report);
Jordy Rose294396b2011-08-22 23:48:23 +00003110}
3111
Jordy Rose910c4052011-09-02 06:44:22 +00003112//===----------------------------------------------------------------------===//
3113// Handle the return values of retain-count-related functions.
3114//===----------------------------------------------------------------------===//
3115
3116bool RetainCountChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
Jordy Rose76c506f2011-08-21 21:58:18 +00003117 // Get the callee. We're only interested in simple C functions.
Ted Kremenek8bef8232012-01-26 21:29:00 +00003118 ProgramStateRef state = C.getState();
Anna Zaksb805c8f2011-12-01 05:57:37 +00003119 const FunctionDecl *FD = C.getCalleeDecl(CE);
Jordy Rose76c506f2011-08-21 21:58:18 +00003120 if (!FD)
3121 return false;
3122
3123 IdentifierInfo *II = FD->getIdentifier();
3124 if (!II)
3125 return false;
3126
3127 // For now, we're only handling the functions that return aliases of their
3128 // arguments: CFRetain and CFMakeCollectable (and their families).
3129 // Eventually we should add other functions we can model entirely,
3130 // such as CFRelease, which don't invalidate their arguments or globals.
3131 if (CE->getNumArgs() != 1)
3132 return false;
3133
3134 // Get the name of the function.
3135 StringRef FName = II->getName();
3136 FName = FName.substr(FName.find_first_not_of('_'));
3137
3138 // See if it's one of the specific functions we know how to eval.
3139 bool canEval = false;
3140
Anna Zaksb805c8f2011-12-01 05:57:37 +00003141 QualType ResultTy = CE->getCallReturnType();
Jordy Rose76c506f2011-08-21 21:58:18 +00003142 if (ResultTy->isObjCIdType()) {
3143 // Handle: id NSMakeCollectable(CFTypeRef)
3144 canEval = II->isStr("NSMakeCollectable");
3145 } else if (ResultTy->isPointerType()) {
3146 // Handle: (CF|CG)Retain
3147 // CFMakeCollectable
3148 // It's okay to be a little sloppy here (CGMakeCollectable doesn't exist).
3149 if (cocoa::isRefType(ResultTy, "CF", FName) ||
3150 cocoa::isRefType(ResultTy, "CG", FName)) {
3151 canEval = isRetain(FD, FName) || isMakeCollectable(FD, FName);
3152 }
3153 }
3154
3155 if (!canEval)
3156 return false;
3157
3158 // Bind the return value.
Ted Kremenek5eca4822012-01-06 22:09:28 +00003159 const LocationContext *LCtx = C.getLocationContext();
3160 SVal RetVal = state->getSVal(CE->getArg(0), LCtx);
Jordy Rose76c506f2011-08-21 21:58:18 +00003161 if (RetVal.isUnknown()) {
3162 // If the receiver is unknown, conjure a return value.
3163 SValBuilder &SVB = C.getSValBuilder();
Ted Kremenek66c486f2012-08-22 06:26:15 +00003164 RetVal = SVB.conjureSymbolVal(0, CE, LCtx, ResultTy, C.blockCount());
Jordy Rose76c506f2011-08-21 21:58:18 +00003165 }
Ted Kremenek5eca4822012-01-06 22:09:28 +00003166 state = state->BindExpr(CE, LCtx, RetVal, false);
Jordy Rose76c506f2011-08-21 21:58:18 +00003167
Jordy Rose294396b2011-08-22 23:48:23 +00003168 // FIXME: This should not be necessary, but otherwise the argument seems to be
3169 // considered alive during the next statement.
3170 if (const MemRegion *ArgRegion = RetVal.getAsRegion()) {
3171 // Save the refcount status of the argument.
3172 SymbolRef Sym = RetVal.getAsLocSymbol();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003173 const RefVal *Binding = 0;
Jordy Rose294396b2011-08-22 23:48:23 +00003174 if (Sym)
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003175 Binding = getRefBinding(state, Sym);
Jordy Rose76c506f2011-08-21 21:58:18 +00003176
Jordy Rose294396b2011-08-22 23:48:23 +00003177 // Invalidate the argument region.
Ted Kremenek66c486f2012-08-22 06:26:15 +00003178 state = state->invalidateRegions(ArgRegion, CE, C.blockCount(), LCtx);
Jordy Rose76c506f2011-08-21 21:58:18 +00003179
Jordy Rose294396b2011-08-22 23:48:23 +00003180 // Restore the refcount status of the argument.
3181 if (Binding)
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003182 state = setRefBinding(state, Sym, *Binding);
Jordy Rose294396b2011-08-22 23:48:23 +00003183 }
3184
Anna Zaks0bd6b112011-10-26 21:06:34 +00003185 C.addTransition(state);
Jordy Rose76c506f2011-08-21 21:58:18 +00003186 return true;
3187}
3188
Jordy Rose910c4052011-09-02 06:44:22 +00003189//===----------------------------------------------------------------------===//
3190// Handle return statements.
3191//===----------------------------------------------------------------------===//
Jordy Rosef53e8c72011-08-23 19:43:16 +00003192
Jordy Rose910c4052011-09-02 06:44:22 +00003193void RetainCountChecker::checkPreStmt(const ReturnStmt *S,
3194 CheckerContext &C) const {
Ted Kremeneke5715782012-02-25 02:09:09 +00003195
3196 // Only adjust the reference count if this is the top-level call frame,
3197 // and not the result of inlining. In the future, we should do
3198 // better checking even for inlined calls, and see if they match
3199 // with their expected semantics (e.g., the method should return a retained
3200 // object, etc.).
Anna Zaksfadcd5d2012-11-03 02:54:16 +00003201 if (!C.inTopFrame())
Ted Kremeneke5715782012-02-25 02:09:09 +00003202 return;
3203
Jordy Rosef53e8c72011-08-23 19:43:16 +00003204 const Expr *RetE = S->getRetValue();
3205 if (!RetE)
3206 return;
3207
Ted Kremenek8bef8232012-01-26 21:29:00 +00003208 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00003209 SymbolRef Sym =
3210 state->getSValAsScalarOrLoc(RetE, C.getLocationContext()).getAsLocSymbol();
Jordy Rosef53e8c72011-08-23 19:43:16 +00003211 if (!Sym)
3212 return;
3213
3214 // Get the reference count binding (if any).
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003215 const RefVal *T = getRefBinding(state, Sym);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003216 if (!T)
3217 return;
3218
3219 // Change the reference count.
3220 RefVal X = *T;
3221
3222 switch (X.getKind()) {
3223 case RefVal::Owned: {
3224 unsigned cnt = X.getCount();
3225 assert(cnt > 0);
3226 X.setCount(cnt - 1);
3227 X = X ^ RefVal::ReturnedOwned;
3228 break;
3229 }
3230
3231 case RefVal::NotOwned: {
3232 unsigned cnt = X.getCount();
3233 if (cnt) {
3234 X.setCount(cnt - 1);
3235 X = X ^ RefVal::ReturnedOwned;
3236 }
3237 else {
3238 X = X ^ RefVal::ReturnedNotOwned;
3239 }
3240 break;
3241 }
3242
3243 default:
3244 return;
3245 }
3246
3247 // Update the binding.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003248 state = setRefBinding(state, Sym, X);
Anna Zaks0bd6b112011-10-26 21:06:34 +00003249 ExplodedNode *Pred = C.addTransition(state);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003250
3251 // At this point we have updated the state properly.
3252 // Everything after this is merely checking to see if the return value has
3253 // been over- or under-retained.
3254
3255 // Did we cache out?
3256 if (!Pred)
3257 return;
3258
Jordy Rosef53e8c72011-08-23 19:43:16 +00003259 // Update the autorelease counts.
3260 static SimpleProgramPointTag
Jordy Rose910c4052011-09-02 06:44:22 +00003261 AutoreleaseTag("RetainCountChecker : Autorelease");
Jordan Rose2bce86c2012-08-18 00:30:16 +00003262 llvm::tie(Pred, state) = handleAutoreleaseCounts(state, Pred, &AutoreleaseTag,
3263 C, Sym, X);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003264
3265 // Did we cache out?
Jordy Rose8d228632011-08-23 20:07:14 +00003266 if (!Pred)
Jordy Rosef53e8c72011-08-23 19:43:16 +00003267 return;
3268
3269 // Get the updated binding.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003270 T = getRefBinding(state, Sym);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003271 assert(T);
3272 X = *T;
3273
3274 // Consult the summary of the enclosing method.
Jordy Rose17a38e22011-09-02 05:55:19 +00003275 RetainSummaryManager &Summaries = getSummaryManager(C);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003276 const Decl *CD = &Pred->getCodeDecl();
Jordan Rose4531b7d2012-07-02 19:27:43 +00003277 RetEffect RE = RetEffect::MakeNoRet();
Jordy Rosef53e8c72011-08-23 19:43:16 +00003278
Jordan Rose4531b7d2012-07-02 19:27:43 +00003279 // FIXME: What is the convention for blocks? Is there one?
Jordy Rosef53e8c72011-08-23 19:43:16 +00003280 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CD)) {
Jordy Roseb6cfc092011-08-25 00:10:37 +00003281 const RetainSummary *Summ = Summaries.getMethodSummary(MD);
Jordan Rose4531b7d2012-07-02 19:27:43 +00003282 RE = Summ->getRetEffect();
3283 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) {
3284 if (!isa<CXXMethodDecl>(FD)) {
3285 const RetainSummary *Summ = Summaries.getFunctionSummary(FD);
3286 RE = Summ->getRetEffect();
3287 }
Jordy Rosef53e8c72011-08-23 19:43:16 +00003288 }
3289
Jordan Rose4531b7d2012-07-02 19:27:43 +00003290 checkReturnWithRetEffect(S, C, Pred, RE, X, Sym, state);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003291}
3292
Jordy Rose910c4052011-09-02 06:44:22 +00003293void RetainCountChecker::checkReturnWithRetEffect(const ReturnStmt *S,
3294 CheckerContext &C,
3295 ExplodedNode *Pred,
3296 RetEffect RE, RefVal X,
3297 SymbolRef Sym,
Ted Kremenek8bef8232012-01-26 21:29:00 +00003298 ProgramStateRef state) const {
Jordy Rosef53e8c72011-08-23 19:43:16 +00003299 // Any leaks or other errors?
3300 if (X.isReturnedOwned() && X.getCount() == 0) {
3301 if (RE.getKind() != RetEffect::NoRet) {
3302 bool hasError = false;
Jordy Rose17a38e22011-09-02 05:55:19 +00003303 if (C.isObjCGCEnabled() && RE.getObjKind() == RetEffect::ObjC) {
Jordy Rosef53e8c72011-08-23 19:43:16 +00003304 // Things are more complicated with garbage collection. If the
3305 // returned object is suppose to be an Objective-C object, we have
3306 // a leak (as the caller expects a GC'ed object) because no
3307 // method should return ownership unless it returns a CF object.
3308 hasError = true;
3309 X = X ^ RefVal::ErrorGCLeakReturned;
3310 }
3311 else if (!RE.isOwned()) {
3312 // Either we are using GC and the returned object is a CF type
3313 // or we aren't using GC. In either case, we expect that the
3314 // enclosing method is expected to return ownership.
3315 hasError = true;
3316 X = X ^ RefVal::ErrorLeakReturned;
3317 }
3318
3319 if (hasError) {
3320 // Generate an error node.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003321 state = setRefBinding(state, Sym, X);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003322
3323 static SimpleProgramPointTag
Jordy Rose910c4052011-09-02 06:44:22 +00003324 ReturnOwnLeakTag("RetainCountChecker : ReturnsOwnLeak");
Anna Zaks0bd6b112011-10-26 21:06:34 +00003325 ExplodedNode *N = C.addTransition(state, Pred, &ReturnOwnLeakTag);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003326 if (N) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003327 const LangOptions &LOpts = C.getASTContext().getLangOpts();
Jordy Rose17a38e22011-09-02 05:55:19 +00003328 bool GCEnabled = C.isObjCGCEnabled();
Jordy Rosef53e8c72011-08-23 19:43:16 +00003329 CFRefReport *report =
Jordy Rose17a38e22011-09-02 05:55:19 +00003330 new CFRefLeakReport(*getLeakAtReturnBug(LOpts, GCEnabled),
3331 LOpts, GCEnabled, SummaryLog,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003332 N, Sym, C);
Jordan Rose785950e2012-11-02 01:53:40 +00003333 C.emitReport(report);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003334 }
3335 }
3336 }
3337 } else if (X.isReturnedNotOwned()) {
3338 if (RE.isOwned()) {
3339 // Trying to return a not owned object to a caller expecting an
3340 // owned object.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003341 state = setRefBinding(state, Sym, X ^ RefVal::ErrorReturnedNotOwned);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003342
3343 static SimpleProgramPointTag
Jordy Rose910c4052011-09-02 06:44:22 +00003344 ReturnNotOwnedTag("RetainCountChecker : ReturnNotOwnedForOwned");
Anna Zaks0bd6b112011-10-26 21:06:34 +00003345 ExplodedNode *N = C.addTransition(state, Pred, &ReturnNotOwnedTag);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003346 if (N) {
Jordy Rosed6334e12011-08-25 00:34:03 +00003347 if (!returnNotOwnedForOwned)
3348 returnNotOwnedForOwned.reset(new ReturnedNotOwnedForOwned());
3349
Jordy Rosef53e8c72011-08-23 19:43:16 +00003350 CFRefReport *report =
Jordy Rosed6334e12011-08-25 00:34:03 +00003351 new CFRefReport(*returnNotOwnedForOwned,
David Blaikie4e4d0842012-03-11 07:00:24 +00003352 C.getASTContext().getLangOpts(),
Jordy Rose17a38e22011-09-02 05:55:19 +00003353 C.isObjCGCEnabled(), SummaryLog, N, Sym);
Jordan Rose785950e2012-11-02 01:53:40 +00003354 C.emitReport(report);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003355 }
3356 }
3357 }
3358}
3359
Jordy Rose8d228632011-08-23 20:07:14 +00003360//===----------------------------------------------------------------------===//
Jordy Rose910c4052011-09-02 06:44:22 +00003361// Check various ways a symbol can be invalidated.
3362//===----------------------------------------------------------------------===//
3363
Anna Zaks390909c2011-10-06 00:43:15 +00003364void RetainCountChecker::checkBind(SVal loc, SVal val, const Stmt *S,
Jordy Rose910c4052011-09-02 06:44:22 +00003365 CheckerContext &C) const {
3366 // Are we storing to something that causes the value to "escape"?
3367 bool escapes = true;
3368
3369 // A value escapes in three possible cases (this may change):
3370 //
3371 // (1) we are binding to something that is not a memory region.
3372 // (2) we are binding to a memregion that does not have stack storage
3373 // (3) we are binding to a memregion with stack storage that the store
3374 // does not understand.
Ted Kremenek8bef8232012-01-26 21:29:00 +00003375 ProgramStateRef state = C.getState();
Jordy Rose910c4052011-09-02 06:44:22 +00003376
3377 if (loc::MemRegionVal *regionLoc = dyn_cast<loc::MemRegionVal>(&loc)) {
3378 escapes = !regionLoc->getRegion()->hasStackStorage();
3379
3380 if (!escapes) {
3381 // To test (3), generate a new state with the binding added. If it is
3382 // the same state, then it escapes (since the store cannot represent
3383 // the binding).
Anna Zakse7958da2012-05-02 00:15:40 +00003384 // Do this only if we know that the store is not supposed to generate the
3385 // same state.
3386 SVal StoredVal = state->getSVal(regionLoc->getRegion());
3387 if (StoredVal != val)
3388 escapes = (state == (state->bindLoc(*regionLoc, val)));
Jordy Rose910c4052011-09-02 06:44:22 +00003389 }
Ted Kremenekde5b4fb2012-03-27 01:12:45 +00003390 if (!escapes) {
3391 // Case 4: We do not currently model what happens when a symbol is
3392 // assigned to a struct field, so be conservative here and let the symbol
3393 // go. TODO: This could definitely be improved upon.
3394 escapes = !isa<VarRegion>(regionLoc->getRegion());
3395 }
Jordy Rose910c4052011-09-02 06:44:22 +00003396 }
3397
3398 // If our store can represent the binding and we aren't storing to something
3399 // that doesn't have local storage then just return and have the simulation
3400 // state continue as is.
3401 if (!escapes)
3402 return;
3403
3404 // Otherwise, find all symbols referenced by 'val' that we are tracking
3405 // and stop tracking them.
3406 state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
Anna Zaks0bd6b112011-10-26 21:06:34 +00003407 C.addTransition(state);
Jordy Rose910c4052011-09-02 06:44:22 +00003408}
3409
Ted Kremenek8bef8232012-01-26 21:29:00 +00003410ProgramStateRef RetainCountChecker::evalAssume(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003411 SVal Cond,
3412 bool Assumption) const {
3413
3414 // FIXME: We may add to the interface of evalAssume the list of symbols
3415 // whose assumptions have changed. For now we just iterate through the
3416 // bindings and check if any of the tracked symbols are NULL. This isn't
3417 // too bad since the number of symbols we will track in practice are
3418 // probably small and evalAssume is only called at branches and a few
3419 // other places.
Jordan Rose166d5022012-11-02 01:54:06 +00003420 RefBindingsTy B = state->get<RefBindings>();
Jordy Rose910c4052011-09-02 06:44:22 +00003421
3422 if (B.isEmpty())
3423 return state;
3424
3425 bool changed = false;
Jordan Rose166d5022012-11-02 01:54:06 +00003426 RefBindingsTy::Factory &RefBFactory = state->get_context<RefBindings>();
Jordy Rose910c4052011-09-02 06:44:22 +00003427
Jordan Rose166d5022012-11-02 01:54:06 +00003428 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Ted Kremenek47cbd0f2012-09-07 22:31:01 +00003429 // Check if the symbol is null stop tracking the symbol.
Jordan Roseec8d4202012-11-01 00:18:27 +00003430 ConstraintManager &CMgr = state->getConstraintManager();
3431 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
3432 if (AllocFailed.isConstrainedTrue()) {
Jordy Rose910c4052011-09-02 06:44:22 +00003433 changed = true;
3434 B = RefBFactory.remove(B, I.getKey());
3435 }
3436 }
3437
3438 if (changed)
3439 state = state->set<RefBindings>(B);
3440
3441 return state;
3442}
3443
Ted Kremenek8bef8232012-01-26 21:29:00 +00003444ProgramStateRef
3445RetainCountChecker::checkRegionChanges(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003446 const StoreManager::InvalidatedSymbols *invalidated,
3447 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00003448 ArrayRef<const MemRegion *> Regions,
Jordan Rose740d4902012-07-02 19:27:35 +00003449 const CallEvent *Call) const {
Jordy Rose910c4052011-09-02 06:44:22 +00003450 if (!invalidated)
3451 return state;
3452
3453 llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
3454 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
3455 E = ExplicitRegions.end(); I != E; ++I) {
3456 if (const SymbolicRegion *SR = (*I)->StripCasts()->getAs<SymbolicRegion>())
3457 WhitelistedSymbols.insert(SR->getSymbol());
3458 }
3459
3460 for (StoreManager::InvalidatedSymbols::const_iterator I=invalidated->begin(),
3461 E = invalidated->end(); I!=E; ++I) {
3462 SymbolRef sym = *I;
3463 if (WhitelistedSymbols.count(sym))
3464 continue;
3465 // Remove any existing reference-count binding.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003466 state = removeRefBinding(state, sym);
Jordy Rose910c4052011-09-02 06:44:22 +00003467 }
3468 return state;
3469}
3470
3471//===----------------------------------------------------------------------===//
Jordy Rose8d228632011-08-23 20:07:14 +00003472// Handle dead symbols and end-of-path.
3473//===----------------------------------------------------------------------===//
3474
Ted Kremenek8bef8232012-01-26 21:29:00 +00003475std::pair<ExplodedNode *, ProgramStateRef >
3476RetainCountChecker::handleAutoreleaseCounts(ProgramStateRef state,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003477 ExplodedNode *Pred,
Jordan Rose2bce86c2012-08-18 00:30:16 +00003478 const ProgramPointTag *Tag,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003479 CheckerContext &Ctx,
Jordy Rose910c4052011-09-02 06:44:22 +00003480 SymbolRef Sym, RefVal V) const {
Jordy Rose8d228632011-08-23 20:07:14 +00003481 unsigned ACnt = V.getAutoreleaseCount();
3482
3483 // No autorelease counts? Nothing to be done.
3484 if (!ACnt)
3485 return std::make_pair(Pred, state);
3486
Anna Zaks6a93bd52011-10-25 19:57:11 +00003487 assert(!Ctx.isObjCGCEnabled() && "Autorelease counts in GC mode?");
Jordy Rose8d228632011-08-23 20:07:14 +00003488 unsigned Cnt = V.getCount();
3489
3490 // FIXME: Handle sending 'autorelease' to already released object.
3491
3492 if (V.getKind() == RefVal::ReturnedOwned)
3493 ++Cnt;
3494
3495 if (ACnt <= Cnt) {
3496 if (ACnt == Cnt) {
3497 V.clearCounts();
3498 if (V.getKind() == RefVal::ReturnedOwned)
3499 V = V ^ RefVal::ReturnedNotOwned;
3500 else
3501 V = V ^ RefVal::NotOwned;
3502 } else {
3503 V.setCount(Cnt - ACnt);
3504 V.setAutoreleaseCount(0);
3505 }
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003506 state = setRefBinding(state, Sym, V);
Jordan Rose2bce86c2012-08-18 00:30:16 +00003507 ExplodedNode *N = Ctx.addTransition(state, Pred, Tag);
Jordy Rose8d228632011-08-23 20:07:14 +00003508 if (N == 0)
3509 state = 0;
3510 return std::make_pair(N, state);
3511 }
3512
3513 // Woah! More autorelease counts then retain counts left.
3514 // Emit hard error.
3515 V = V ^ RefVal::ErrorOverAutorelease;
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003516 state = setRefBinding(state, Sym, V);
Jordy Rose8d228632011-08-23 20:07:14 +00003517
Jordan Rosefa06f042012-08-20 18:43:42 +00003518 ExplodedNode *N = Ctx.generateSink(state, Pred, Tag);
Jordan Rose2bce86c2012-08-18 00:30:16 +00003519 if (N) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003520 SmallString<128> sbuf;
Jordy Rose8d228632011-08-23 20:07:14 +00003521 llvm::raw_svector_ostream os(sbuf);
3522 os << "Object over-autoreleased: object was sent -autorelease ";
3523 if (V.getAutoreleaseCount() > 1)
3524 os << V.getAutoreleaseCount() << " times ";
3525 os << "but the object has a +" << V.getCount() << " retain count";
3526
Jordy Rosed6334e12011-08-25 00:34:03 +00003527 if (!overAutorelease)
3528 overAutorelease.reset(new OverAutorelease());
3529
David Blaikie4e4d0842012-03-11 07:00:24 +00003530 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
Jordy Rose8d228632011-08-23 20:07:14 +00003531 CFRefReport *report =
Jordy Rosed6334e12011-08-25 00:34:03 +00003532 new CFRefReport(*overAutorelease, LOpts, /* GCEnabled = */ false,
3533 SummaryLog, N, Sym, os.str());
Jordan Rose785950e2012-11-02 01:53:40 +00003534 Ctx.emitReport(report);
Jordy Rose8d228632011-08-23 20:07:14 +00003535 }
3536
Ted Kremenek8bef8232012-01-26 21:29:00 +00003537 return std::make_pair((ExplodedNode *)0, (ProgramStateRef )0);
Jordy Rose8d228632011-08-23 20:07:14 +00003538}
Jordy Rose38f17d62011-08-23 19:01:07 +00003539
Ted Kremenek8bef8232012-01-26 21:29:00 +00003540ProgramStateRef
3541RetainCountChecker::handleSymbolDeath(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003542 SymbolRef sid, RefVal V,
Jordy Rose38f17d62011-08-23 19:01:07 +00003543 SmallVectorImpl<SymbolRef> &Leaked) const {
Jordy Rose53376122011-08-24 04:48:19 +00003544 bool hasLeak = false;
Jordy Rose38f17d62011-08-23 19:01:07 +00003545 if (V.isOwned())
3546 hasLeak = true;
3547 else if (V.isNotOwned() || V.isReturnedOwned())
3548 hasLeak = (V.getCount() > 0);
3549
3550 if (!hasLeak)
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003551 return removeRefBinding(state, sid);
Jordy Rose38f17d62011-08-23 19:01:07 +00003552
3553 Leaked.push_back(sid);
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003554 return setRefBinding(state, sid, V ^ RefVal::ErrorLeak);
Jordy Rose38f17d62011-08-23 19:01:07 +00003555}
3556
3557ExplodedNode *
Ted Kremenek8bef8232012-01-26 21:29:00 +00003558RetainCountChecker::processLeaks(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003559 SmallVectorImpl<SymbolRef> &Leaked,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003560 CheckerContext &Ctx,
3561 ExplodedNode *Pred) const {
Jordy Rose38f17d62011-08-23 19:01:07 +00003562 if (Leaked.empty())
3563 return Pred;
3564
3565 // Generate an intermediate node representing the leak point.
Jordan Rose2bce86c2012-08-18 00:30:16 +00003566 ExplodedNode *N = Ctx.addTransition(state, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003567
3568 if (N) {
3569 for (SmallVectorImpl<SymbolRef>::iterator
3570 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3571
David Blaikie4e4d0842012-03-11 07:00:24 +00003572 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
Anna Zaks6a93bd52011-10-25 19:57:11 +00003573 bool GCEnabled = Ctx.isObjCGCEnabled();
Jordy Rose17a38e22011-09-02 05:55:19 +00003574 CFRefBug *BT = Pred ? getLeakWithinFunctionBug(LOpts, GCEnabled)
3575 : getLeakAtReturnBug(LOpts, GCEnabled);
Jordy Rose38f17d62011-08-23 19:01:07 +00003576 assert(BT && "BugType not initialized.");
Jordy Rose20589562011-08-24 22:39:09 +00003577
Jordy Rose17a38e22011-09-02 05:55:19 +00003578 CFRefLeakReport *report = new CFRefLeakReport(*BT, LOpts, GCEnabled,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003579 SummaryLog, N, *I, Ctx);
Jordan Rose785950e2012-11-02 01:53:40 +00003580 Ctx.emitReport(report);
Jordy Rose38f17d62011-08-23 19:01:07 +00003581 }
3582 }
3583
3584 return N;
3585}
3586
Anna Zaksaf498a22011-10-25 19:56:48 +00003587void RetainCountChecker::checkEndPath(CheckerContext &Ctx) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +00003588 ProgramStateRef state = Ctx.getState();
Jordan Rose166d5022012-11-02 01:54:06 +00003589 RefBindingsTy B = state->get<RefBindings>();
Anna Zaksaf498a22011-10-25 19:56:48 +00003590 ExplodedNode *Pred = Ctx.getPredecessor();
Jordy Rose38f17d62011-08-23 19:01:07 +00003591
Jordan Rose166d5022012-11-02 01:54:06 +00003592 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Jordan Rose2bce86c2012-08-18 00:30:16 +00003593 llvm::tie(Pred, state) = handleAutoreleaseCounts(state, Pred, /*Tag=*/0,
3594 Ctx, I->first, I->second);
Jordy Rose8d228632011-08-23 20:07:14 +00003595 if (!state)
Jordy Rose38f17d62011-08-23 19:01:07 +00003596 return;
3597 }
3598
Ted Kremenek0cf3d472012-02-07 00:24:33 +00003599 // If the current LocationContext has a parent, don't check for leaks.
3600 // We will do that later.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003601 // FIXME: we should instead check for imbalances of the retain/releases,
Ted Kremenek0cf3d472012-02-07 00:24:33 +00003602 // and suggest annotations.
3603 if (Ctx.getLocationContext()->getParent())
3604 return;
3605
Jordy Rose38f17d62011-08-23 19:01:07 +00003606 B = state->get<RefBindings>();
3607 SmallVector<SymbolRef, 10> Leaked;
3608
Jordan Rose166d5022012-11-02 01:54:06 +00003609 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I)
Jordy Rose8d228632011-08-23 20:07:14 +00003610 state = handleSymbolDeath(state, I->first, I->second, Leaked);
Jordy Rose38f17d62011-08-23 19:01:07 +00003611
Jordan Rose2bce86c2012-08-18 00:30:16 +00003612 processLeaks(state, Leaked, Ctx, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003613}
3614
3615const ProgramPointTag *
Jordy Rose910c4052011-09-02 06:44:22 +00003616RetainCountChecker::getDeadSymbolTag(SymbolRef sym) const {
Jordy Rose38f17d62011-08-23 19:01:07 +00003617 const SimpleProgramPointTag *&tag = DeadSymbolTags[sym];
3618 if (!tag) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003619 SmallString<64> buf;
Jordy Rose38f17d62011-08-23 19:01:07 +00003620 llvm::raw_svector_ostream out(buf);
Anna Zaksf62ceec2011-12-05 18:58:11 +00003621 out << "RetainCountChecker : Dead Symbol : ";
3622 sym->dumpToStream(out);
Jordy Rose38f17d62011-08-23 19:01:07 +00003623 tag = new SimpleProgramPointTag(out.str());
3624 }
3625 return tag;
3626}
3627
Jordy Rose910c4052011-09-02 06:44:22 +00003628void RetainCountChecker::checkDeadSymbols(SymbolReaper &SymReaper,
3629 CheckerContext &C) const {
Jordy Rose38f17d62011-08-23 19:01:07 +00003630 ExplodedNode *Pred = C.getPredecessor();
3631
Ted Kremenek8bef8232012-01-26 21:29:00 +00003632 ProgramStateRef state = C.getState();
Jordan Rose166d5022012-11-02 01:54:06 +00003633 RefBindingsTy B = state->get<RefBindings>();
Jordy Rose38f17d62011-08-23 19:01:07 +00003634
3635 // Update counts from autorelease pools
3636 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3637 E = SymReaper.dead_end(); I != E; ++I) {
3638 SymbolRef Sym = *I;
3639 if (const RefVal *T = B.lookup(Sym)){
3640 // Use the symbol as the tag.
3641 // FIXME: This might not be as unique as we would like.
Jordan Rose2bce86c2012-08-18 00:30:16 +00003642 const ProgramPointTag *Tag = getDeadSymbolTag(Sym);
3643 llvm::tie(Pred, state) = handleAutoreleaseCounts(state, Pred, Tag, C,
Jordy Rose8d228632011-08-23 20:07:14 +00003644 Sym, *T);
3645 if (!state)
Jordy Rose38f17d62011-08-23 19:01:07 +00003646 return;
3647 }
3648 }
3649
3650 B = state->get<RefBindings>();
3651 SmallVector<SymbolRef, 10> Leaked;
3652
3653 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3654 E = SymReaper.dead_end(); I != E; ++I) {
3655 if (const RefVal *T = B.lookup(*I))
3656 state = handleSymbolDeath(state, *I, *T, Leaked);
3657 }
3658
Jordan Rose2bce86c2012-08-18 00:30:16 +00003659 Pred = processLeaks(state, Leaked, C, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003660
3661 // Did we cache out?
3662 if (!Pred)
3663 return;
3664
3665 // Now generate a new node that nukes the old bindings.
Jordan Rose166d5022012-11-02 01:54:06 +00003666 RefBindingsTy::Factory &F = state->get_context<RefBindings>();
Jordy Rose38f17d62011-08-23 19:01:07 +00003667
3668 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3669 E = SymReaper.dead_end(); I != E; ++I)
3670 B = F.remove(B, *I);
3671
3672 state = state->set<RefBindings>(B);
Anna Zaks0bd6b112011-10-26 21:06:34 +00003673 C.addTransition(state, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003674}
3675
Ted Kremenek8bef8232012-01-26 21:29:00 +00003676void RetainCountChecker::printState(raw_ostream &Out, ProgramStateRef State,
Jordy Rose910c4052011-09-02 06:44:22 +00003677 const char *NL, const char *Sep) const {
Jordy Rosedbd658e2011-08-28 19:11:56 +00003678
Jordan Rose166d5022012-11-02 01:54:06 +00003679 RefBindingsTy B = State->get<RefBindings>();
Jordy Rosedbd658e2011-08-28 19:11:56 +00003680
3681 if (!B.isEmpty())
3682 Out << Sep << NL;
3683
Jordan Rose166d5022012-11-02 01:54:06 +00003684 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Jordy Rosedbd658e2011-08-28 19:11:56 +00003685 Out << I->first << " : ";
3686 I->second.print(Out);
3687 Out << NL;
3688 }
Jordy Rosedbd658e2011-08-28 19:11:56 +00003689}
3690
3691//===----------------------------------------------------------------------===//
Jordy Rose910c4052011-09-02 06:44:22 +00003692// Checker registration.
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00003693//===----------------------------------------------------------------------===//
3694
Jordy Rose17a38e22011-09-02 05:55:19 +00003695void ento::registerRetainCountChecker(CheckerManager &Mgr) {
Jordy Rose910c4052011-09-02 06:44:22 +00003696 Mgr.registerChecker<RetainCountChecker>();
Jordy Rose17a38e22011-09-02 05:55:19 +00003697}
3698