blob: 4c6301908371579a82c2c0a310863b575ad7cb03 [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"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000016#include "clang/AST/Attr.h"
Ted Kremenekb2771592011-03-30 17:41:19 +000017#include "clang/AST/DeclCXX.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000018#include "clang/AST/DeclObjC.h"
19#include "clang/AST/ParentMap.h"
20#include "clang/Analysis/DomainSpecific/CocoaConventions.h"
Ted Kremenek0b526b42010-02-18 00:05:58 +000021#include "clang/Basic/LangOptions.h"
22#include "clang/Basic/SourceManager.h"
Ted Kremenek9b663712011-02-10 01:03:03 +000023#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
24#include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000025#include "clang/StaticAnalyzer/Core/Checker.h"
26#include "clang/StaticAnalyzer/Core/CheckerManager.h"
Jordan Rosef540c542012-07-26 21:39:41 +000027#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
Jordy Rose910c4052011-09-02 06:44:22 +000028#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
Ted Kremenek18c66fd2011-08-15 22:09:50 +000029#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
Ted Kremenek9b663712011-02-10 01:03:03 +000030#include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000031#include "llvm/ADT/DenseMap.h"
32#include "llvm/ADT/FoldingSet.h"
Ted Kremenek6d348932008-10-21 15:53:15 +000033#include "llvm/ADT/ImmutableList.h"
Ted Kremenek0b526b42010-02-18 00:05:58 +000034#include "llvm/ADT/ImmutableMap.h"
Ted Kremenek6ed9afc2008-05-16 18:33:44 +000035#include "llvm/ADT/STLExtras.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000036#include "llvm/ADT/SmallString.h"
Ted Kremenek0b526b42010-02-18 00:05:58 +000037#include "llvm/ADT/StringExtras.h"
Chris Lattner5f9e2722011-07-23 10:55:15 +000038#include <cstdarg>
Ted Kremenek2fff37e2008-03-06 00:08:09 +000039
Ted Kremenek08a838d2013-04-16 21:44:22 +000040#include "AllocationDiagnostics.h"
41
Ted Kremenek2fff37e2008-03-06 00:08:09 +000042using namespace clang;
Ted Kremenek9ef65372010-12-23 07:20:52 +000043using namespace ento;
Ted Kremeneka64e89b2010-01-27 06:13:48 +000044using llvm::StrInStrNoCase;
Ted Kremenek4c79e552008-11-05 16:54:44 +000045
Ted Kremenek05cbe1a2008-04-09 23:49:11 +000046//===----------------------------------------------------------------------===//
Ted Kremenek553cf182008-06-25 21:21:56 +000047// Primitives used for constructing summaries for function/method calls.
Ted Kremenek05cbe1a2008-04-09 23:49:11 +000048//===----------------------------------------------------------------------===//
49
Ted Kremenek553cf182008-06-25 21:21:56 +000050/// ArgEffect is used to summarize a function/method call's effect on a
51/// particular argument.
Jordy Rosebd85b132011-08-24 19:10:50 +000052enum ArgEffect { DoNothing, Autorelease, Dealloc, DecRef, DecRefMsg,
John McCallf85e1932011-06-15 23:02:42 +000053 DecRefBridgedTransfered,
Jordy Rosebd85b132011-08-24 19:10:50 +000054 IncRefMsg, IncRef, MakeCollectable, MayEscape,
Anna Zaks554067f2012-08-29 23:23:43 +000055
56 // Stop tracking the argument - the effect of the call is
57 // unknown.
58 StopTracking,
59
60 // In some cases, we obtain a better summary for this checker
61 // by looking at the call site than by inlining the function.
62 // Signifies that we should stop tracking the symbol even if
63 // the function is inlined.
64 StopTrackingHard,
65
66 // The function decrements the reference count and the checker
67 // should stop tracking the argument.
68 DecRefAndStopTrackingHard, DecRefMsgAndStopTrackingHard
69 };
Ted Kremenek553cf182008-06-25 21:21:56 +000070
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000071namespace llvm {
Ted Kremenekb77449c2009-05-03 05:20:50 +000072template <> struct FoldingSetTrait<ArgEffect> {
73static inline void Profile(const ArgEffect X, FoldingSetNodeID& ID) {
74 ID.AddInteger((unsigned) X);
75}
Ted Kremenek553cf182008-06-25 21:21:56 +000076};
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000077} // end llvm namespace
78
Ted Kremenekb77449c2009-05-03 05:20:50 +000079/// ArgEffects summarizes the effects of a function/method call on all of
80/// its arguments.
81typedef llvm::ImmutableMap<unsigned,ArgEffect> ArgEffects;
82
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000083namespace {
Ted Kremenek553cf182008-06-25 21:21:56 +000084
85/// RetEffect is used to summarize a function/method call's behavior with
Mike Stump1eb44332009-09-09 15:08:12 +000086/// respect to its return value.
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +000087class RetEffect {
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000088public:
Jordy Rose76c506f2011-08-21 21:58:18 +000089 enum Kind { NoRet, OwnedSymbol, OwnedAllocatedSymbol,
John McCallf85e1932011-06-15 23:02:42 +000090 NotOwnedSymbol, GCNotOwnedSymbol, ARCNotOwnedSymbol,
Anna Zaks554067f2012-08-29 23:23:43 +000091 OwnedWhenTrackedReceiver,
92 // Treat this function as returning a non-tracked symbol even if
93 // the function has been inlined. This is used where the call
94 // site summary is more presise than the summary indirectly produced
95 // by inlining the function
96 NoRetHard
97 };
Mike Stump1eb44332009-09-09 15:08:12 +000098
99 enum ObjKind { CF, ObjC, AnyObj };
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000100
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000101private:
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000102 Kind K;
103 ObjKind O;
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000104
Jordy Rose76c506f2011-08-21 21:58:18 +0000105 RetEffect(Kind k, ObjKind o = AnyObj) : K(k), O(o) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000106
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000107public:
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000108 Kind getKind() const { return K; }
109
110 ObjKind getObjKind() const { return O; }
Mike Stump1eb44332009-09-09 15:08:12 +0000111
Ted Kremeneka8833552009-04-29 23:03:22 +0000112 bool isOwned() const {
Ted Kremenek78a35a32009-05-12 20:06:54 +0000113 return K == OwnedSymbol || K == OwnedAllocatedSymbol ||
114 K == OwnedWhenTrackedReceiver;
Ted Kremeneka8833552009-04-29 23:03:22 +0000115 }
Mike Stump1eb44332009-09-09 15:08:12 +0000116
Jordy Rose4df54fe2011-08-23 04:27:15 +0000117 bool operator==(const RetEffect &Other) const {
118 return K == Other.K && O == Other.O;
119 }
120
Ted Kremenek78a35a32009-05-12 20:06:54 +0000121 static RetEffect MakeOwnedWhenTrackedReceiver() {
122 return RetEffect(OwnedWhenTrackedReceiver, ObjC);
123 }
Mike Stump1eb44332009-09-09 15:08:12 +0000124
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000125 static RetEffect MakeOwned(ObjKind o, bool isAllocated = false) {
126 return RetEffect(isAllocated ? OwnedAllocatedSymbol : OwnedSymbol, o);
Mike Stump1eb44332009-09-09 15:08:12 +0000127 }
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000128 static RetEffect MakeNotOwned(ObjKind o) {
129 return RetEffect(NotOwnedSymbol, o);
Ted Kremeneke798e7c2009-04-27 19:14:45 +0000130 }
131 static RetEffect MakeGCNotOwned() {
132 return RetEffect(GCNotOwnedSymbol, ObjC);
133 }
John McCallf85e1932011-06-15 23:02:42 +0000134 static RetEffect MakeARCNotOwned() {
135 return RetEffect(ARCNotOwnedSymbol, ObjC);
136 }
Ted Kremenek553cf182008-06-25 21:21:56 +0000137 static RetEffect MakeNoRet() {
138 return RetEffect(NoRet);
Ted Kremeneka7344702008-06-23 18:02:52 +0000139 }
Anna Zaks554067f2012-08-29 23:23:43 +0000140 static RetEffect MakeNoRetHard() {
141 return RetEffect(NoRetHard);
142 }
Jordy Roseef945882012-03-18 01:26:10 +0000143
144 void Profile(llvm::FoldingSetNodeID& ID) const {
145 ID.AddInteger((unsigned) K);
146 ID.AddInteger((unsigned) O);
147 }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000148};
Mike Stump1eb44332009-09-09 15:08:12 +0000149
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000150//===----------------------------------------------------------------------===//
151// Reference-counting logic (typestate + counts).
152//===----------------------------------------------------------------------===//
Mike Stump1eb44332009-09-09 15:08:12 +0000153
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000154class RefVal {
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000155public:
156 enum Kind {
157 Owned = 0, // Owning reference.
158 NotOwned, // Reference is not owned by still valid (not freed).
159 Released, // Object has been released.
160 ReturnedOwned, // Returned object passes ownership to caller.
161 ReturnedNotOwned, // Return object does not pass ownership to caller.
162 ERROR_START,
163 ErrorDeallocNotOwned, // -dealloc called on non-owned object.
164 ErrorDeallocGC, // Calling -dealloc with GC enabled.
165 ErrorUseAfterRelease, // Object used after released.
166 ErrorReleaseNotOwned, // Release of an object that was not owned.
167 ERROR_LEAK_START,
168 ErrorLeak, // A memory leak due to excessive reference counts.
169 ErrorLeakReturned, // A memory leak due to the returning method not having
170 // the correct naming conventions.
171 ErrorGCLeakReturned,
172 ErrorOverAutorelease,
173 ErrorReturnedNotOwned
174 };
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000175
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000176private:
177 Kind kind;
178 RetEffect::ObjKind okind;
179 unsigned Cnt;
180 unsigned ACnt;
181 QualType T;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000182
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000183 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, unsigned acnt, QualType t)
184 : kind(k), okind(o), Cnt(cnt), ACnt(acnt), T(t) {}
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000185
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000186public:
187 Kind getKind() const { return kind; }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000188
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000189 RetEffect::ObjKind getObjKind() const { return okind; }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000190
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000191 unsigned getCount() const { return Cnt; }
192 unsigned getAutoreleaseCount() const { return ACnt; }
193 unsigned getCombinedCounts() const { return Cnt + ACnt; }
194 void clearCounts() { Cnt = 0; ACnt = 0; }
195 void setCount(unsigned i) { Cnt = i; }
196 void setAutoreleaseCount(unsigned i) { ACnt = i; }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000197
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000198 QualType getType() const { return T; }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000199
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000200 bool isOwned() const {
201 return getKind() == Owned;
202 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000203
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000204 bool isNotOwned() const {
205 return getKind() == NotOwned;
206 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000207
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000208 bool isReturnedOwned() const {
209 return getKind() == ReturnedOwned;
210 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000211
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000212 bool isReturnedNotOwned() const {
213 return getKind() == ReturnedNotOwned;
214 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000215
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000216 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
217 unsigned Count = 1) {
218 return RefVal(Owned, o, Count, 0, t);
219 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000220
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000221 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
222 unsigned Count = 0) {
223 return RefVal(NotOwned, o, Count, 0, t);
224 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000225
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000226 // Comparison, profiling, and pretty-printing.
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000227
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000228 bool operator==(const RefVal& X) const {
229 return kind == X.kind && Cnt == X.Cnt && T == X.T && ACnt == X.ACnt;
230 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000231
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000232 RefVal operator-(size_t i) const {
233 return RefVal(getKind(), getObjKind(), getCount() - i,
234 getAutoreleaseCount(), getType());
235 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000236
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000237 RefVal operator+(size_t i) const {
238 return RefVal(getKind(), getObjKind(), getCount() + i,
239 getAutoreleaseCount(), getType());
240 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000241
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000242 RefVal operator^(Kind k) const {
243 return RefVal(k, getObjKind(), getCount(), getAutoreleaseCount(),
244 getType());
245 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000246
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000247 RefVal autorelease() const {
248 return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount()+1,
249 getType());
250 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000251
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000252 void Profile(llvm::FoldingSetNodeID& ID) const {
253 ID.AddInteger((unsigned) kind);
254 ID.AddInteger(Cnt);
255 ID.AddInteger(ACnt);
256 ID.Add(T);
257 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000258
Ted Kremenek9c378f72011-08-12 23:37:29 +0000259 void print(raw_ostream &Out) const;
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000260};
261
Ted Kremenek9c378f72011-08-12 23:37:29 +0000262void RefVal::print(raw_ostream &Out) const {
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000263 if (!T.isNull())
Jordy Rosedbd658e2011-08-28 19:11:56 +0000264 Out << "Tracked " << T.getAsString() << '/';
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000265
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000266 switch (getKind()) {
Jordy Rose910c4052011-09-02 06:44:22 +0000267 default: llvm_unreachable("Invalid RefVal kind");
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000268 case Owned: {
269 Out << "Owned";
270 unsigned cnt = getCount();
271 if (cnt) Out << " (+ " << cnt << ")";
272 break;
273 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000274
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000275 case NotOwned: {
276 Out << "NotOwned";
277 unsigned cnt = getCount();
278 if (cnt) Out << " (+ " << cnt << ")";
279 break;
280 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000281
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000282 case ReturnedOwned: {
283 Out << "ReturnedOwned";
284 unsigned cnt = getCount();
285 if (cnt) Out << " (+ " << cnt << ")";
286 break;
287 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000288
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000289 case ReturnedNotOwned: {
290 Out << "ReturnedNotOwned";
291 unsigned cnt = getCount();
292 if (cnt) Out << " (+ " << cnt << ")";
293 break;
294 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000295
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000296 case Released:
297 Out << "Released";
298 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000299
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000300 case ErrorDeallocGC:
301 Out << "-dealloc (GC)";
302 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000303
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000304 case ErrorDeallocNotOwned:
305 Out << "-dealloc (not-owned)";
306 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000307
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000308 case ErrorLeak:
309 Out << "Leaked";
310 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000311
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000312 case ErrorLeakReturned:
313 Out << "Leaked (Bad naming)";
314 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000315
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000316 case ErrorGCLeakReturned:
317 Out << "Leaked (GC-ed at return)";
318 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000319
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000320 case ErrorUseAfterRelease:
321 Out << "Use-After-Release [ERROR]";
322 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000323
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000324 case ErrorReleaseNotOwned:
325 Out << "Release of Not-Owned [ERROR]";
326 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000327
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000328 case RefVal::ErrorOverAutorelease:
329 Out << "Over autoreleased";
330 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000331
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000332 case RefVal::ErrorReturnedNotOwned:
333 Out << "Non-owned object returned instead of owned";
334 break;
335 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000336
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000337 if (ACnt) {
338 Out << " [ARC +" << ACnt << ']';
339 }
340}
341} //end anonymous namespace
342
343//===----------------------------------------------------------------------===//
344// RefBindings - State used to track object reference counts.
345//===----------------------------------------------------------------------===//
346
Jordan Rose166d5022012-11-02 01:54:06 +0000347REGISTER_MAP_WITH_PROGRAMSTATE(RefBindings, SymbolRef, RefVal)
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000348
Anna Zaks8d6b43c2012-08-14 00:36:15 +0000349static inline const RefVal *getRefBinding(ProgramStateRef State,
350 SymbolRef Sym) {
351 return State->get<RefBindings>(Sym);
352}
353
354static inline ProgramStateRef setRefBinding(ProgramStateRef State,
355 SymbolRef Sym, RefVal Val) {
356 return State->set<RefBindings>(Sym, Val);
357}
358
359static ProgramStateRef removeRefBinding(ProgramStateRef State, SymbolRef Sym) {
360 return State->remove<RefBindings>(Sym);
361}
362
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000363//===----------------------------------------------------------------------===//
Jordy Rose910c4052011-09-02 06:44:22 +0000364// Function/Method behavior summaries.
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000365//===----------------------------------------------------------------------===//
366
367namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000368class RetainSummary {
Jordy Roseef945882012-03-18 01:26:10 +0000369 /// Args - a map of (index, ArgEffect) pairs, where index
Ted Kremenek1bffd742008-05-06 15:44:25 +0000370 /// specifies the argument (starting from 0). This can be sparsely
371 /// populated; arguments with no entry in Args use 'DefaultArgEffect'.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000372 ArgEffects Args;
Mike Stump1eb44332009-09-09 15:08:12 +0000373
Ted Kremenek1bffd742008-05-06 15:44:25 +0000374 /// DefaultArgEffect - The default ArgEffect to apply to arguments that
375 /// do not have an entry in Args.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000376 ArgEffect DefaultArgEffect;
Mike Stump1eb44332009-09-09 15:08:12 +0000377
Ted Kremenek553cf182008-06-25 21:21:56 +0000378 /// Receiver - If this summary applies to an Objective-C message expression,
379 /// this is the effect applied to the state of the receiver.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000380 ArgEffect Receiver;
Mike Stump1eb44332009-09-09 15:08:12 +0000381
Ted Kremenek553cf182008-06-25 21:21:56 +0000382 /// Ret - The effect on the return value. Used to indicate if the
Jordy Rose76c506f2011-08-21 21:58:18 +0000383 /// function/method call returns a new tracked symbol.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000384 RetEffect Ret;
Mike Stump1eb44332009-09-09 15:08:12 +0000385
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000386public:
Ted Kremenekb77449c2009-05-03 05:20:50 +0000387 RetainSummary(ArgEffects A, RetEffect R, ArgEffect defaultEff,
Jordy Rosee62e87b2011-08-20 20:55:40 +0000388 ArgEffect ReceiverEff)
389 : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000390
Ted Kremenek553cf182008-06-25 21:21:56 +0000391 /// getArg - Return the argument effect on the argument specified by
392 /// idx (starting from 0).
Ted Kremenek1ac08d62008-03-11 17:48:22 +0000393 ArgEffect getArg(unsigned idx) const {
Ted Kremenekb77449c2009-05-03 05:20:50 +0000394 if (const ArgEffect *AE = Args.lookup(idx))
395 return *AE;
Mike Stump1eb44332009-09-09 15:08:12 +0000396
Ted Kremenek1bffd742008-05-06 15:44:25 +0000397 return DefaultArgEffect;
Ted Kremenek1ac08d62008-03-11 17:48:22 +0000398 }
Ted Kremenek11fe1752011-01-27 18:43:03 +0000399
400 void addArg(ArgEffects::Factory &af, unsigned idx, ArgEffect e) {
401 Args = af.add(Args, idx, e);
402 }
Mike Stump1eb44332009-09-09 15:08:12 +0000403
Ted Kremenek885c27b2009-05-04 05:31:22 +0000404 /// setDefaultArgEffect - Set the default argument effect.
405 void setDefaultArgEffect(ArgEffect E) {
406 DefaultArgEffect = E;
407 }
Mike Stump1eb44332009-09-09 15:08:12 +0000408
Ted Kremenek553cf182008-06-25 21:21:56 +0000409 /// getRetEffect - Returns the effect on the return value of the call.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000410 RetEffect getRetEffect() const { return Ret; }
Mike Stump1eb44332009-09-09 15:08:12 +0000411
Ted Kremenek885c27b2009-05-04 05:31:22 +0000412 /// setRetEffect - Set the effect of the return value of the call.
413 void setRetEffect(RetEffect E) { Ret = E; }
Mike Stump1eb44332009-09-09 15:08:12 +0000414
Ted Kremenek12b94342011-01-27 06:54:14 +0000415
416 /// Sets the effect on the receiver of the message.
417 void setReceiverEffect(ArgEffect e) { Receiver = e; }
418
Ted Kremenek553cf182008-06-25 21:21:56 +0000419 /// getReceiverEffect - Returns the effect on the receiver of the call.
420 /// This is only meaningful if the summary applies to an ObjCMessageExpr*.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000421 ArgEffect getReceiverEffect() const { return Receiver; }
Jordy Rose4df54fe2011-08-23 04:27:15 +0000422
423 /// Test if two retain summaries are identical. Note that merely equivalent
424 /// summaries are not necessarily identical (for example, if an explicit
425 /// argument effect matches the default effect).
426 bool operator==(const RetainSummary &Other) const {
427 return Args == Other.Args && DefaultArgEffect == Other.DefaultArgEffect &&
428 Receiver == Other.Receiver && Ret == Other.Ret;
429 }
Jordy Roseef945882012-03-18 01:26:10 +0000430
431 /// Profile this summary for inclusion in a FoldingSet.
432 void Profile(llvm::FoldingSetNodeID& ID) const {
433 ID.Add(Args);
434 ID.Add(DefaultArgEffect);
435 ID.Add(Receiver);
436 ID.Add(Ret);
437 }
438
439 /// A retain summary is simple if it has no ArgEffects other than the default.
440 bool isSimple() const {
441 return Args.isEmpty();
442 }
Jordan Rose4531b7d2012-07-02 19:27:43 +0000443
444private:
445 ArgEffects getArgEffects() const { return Args; }
446 ArgEffect getDefaultArgEffect() const { return DefaultArgEffect; }
447
448 friend class RetainSummaryManager;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000449};
Ted Kremenek4f22a782008-06-23 23:30:29 +0000450} // end anonymous namespace
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000451
Ted Kremenek553cf182008-06-25 21:21:56 +0000452//===----------------------------------------------------------------------===//
453// Data structures for constructing summaries.
454//===----------------------------------------------------------------------===//
Ted Kremenek53301ba2008-06-24 03:49:48 +0000455
Ted Kremenek553cf182008-06-25 21:21:56 +0000456namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000457class ObjCSummaryKey {
Ted Kremenek553cf182008-06-25 21:21:56 +0000458 IdentifierInfo* II;
459 Selector S;
Mike Stump1eb44332009-09-09 15:08:12 +0000460public:
Ted Kremenek553cf182008-06-25 21:21:56 +0000461 ObjCSummaryKey(IdentifierInfo* ii, Selector s)
462 : II(ii), S(s) {}
463
Ted Kremenek9c378f72011-08-12 23:37:29 +0000464 ObjCSummaryKey(const ObjCInterfaceDecl *d, Selector s)
Ted Kremenek553cf182008-06-25 21:21:56 +0000465 : II(d ? d->getIdentifier() : 0), S(s) {}
Ted Kremenek70b6a832009-05-13 18:16:01 +0000466
Ted Kremenek553cf182008-06-25 21:21:56 +0000467 ObjCSummaryKey(Selector s)
468 : II(0), S(s) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000469
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000470 IdentifierInfo *getIdentifier() const { return II; }
Ted Kremenek553cf182008-06-25 21:21:56 +0000471 Selector getSelector() const { return S; }
472};
Ted Kremenek4f22a782008-06-23 23:30:29 +0000473}
474
475namespace llvm {
Ted Kremenek553cf182008-06-25 21:21:56 +0000476template <> struct DenseMapInfo<ObjCSummaryKey> {
477 static inline ObjCSummaryKey getEmptyKey() {
478 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
479 DenseMapInfo<Selector>::getEmptyKey());
480 }
Mike Stump1eb44332009-09-09 15:08:12 +0000481
Ted Kremenek553cf182008-06-25 21:21:56 +0000482 static inline ObjCSummaryKey getTombstoneKey() {
483 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
Mike Stump1eb44332009-09-09 15:08:12 +0000484 DenseMapInfo<Selector>::getTombstoneKey());
Ted Kremenek553cf182008-06-25 21:21:56 +0000485 }
Mike Stump1eb44332009-09-09 15:08:12 +0000486
Ted Kremenek553cf182008-06-25 21:21:56 +0000487 static unsigned getHashValue(const ObjCSummaryKey &V) {
Benjamin Kramer28b23072012-05-27 13:28:44 +0000488 typedef std::pair<IdentifierInfo*, Selector> PairTy;
489 return DenseMapInfo<PairTy>::getHashValue(PairTy(V.getIdentifier(),
490 V.getSelector()));
Ted Kremenek553cf182008-06-25 21:21:56 +0000491 }
Mike Stump1eb44332009-09-09 15:08:12 +0000492
Ted Kremenek553cf182008-06-25 21:21:56 +0000493 static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
Benjamin Kramer28b23072012-05-27 13:28:44 +0000494 return LHS.getIdentifier() == RHS.getIdentifier() &&
495 LHS.getSelector() == RHS.getSelector();
Ted Kremenek553cf182008-06-25 21:21:56 +0000496 }
Mike Stump1eb44332009-09-09 15:08:12 +0000497
Ted Kremenek553cf182008-06-25 21:21:56 +0000498};
Chris Lattner06159e82009-12-15 07:26:51 +0000499template <>
500struct isPodLike<ObjCSummaryKey> { static const bool value = true; };
Ted Kremenek4f22a782008-06-23 23:30:29 +0000501} // end llvm namespace
Mike Stump1eb44332009-09-09 15:08:12 +0000502
Ted Kremenek4f22a782008-06-23 23:30:29 +0000503namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000504class ObjCSummaryCache {
Ted Kremenek93edbc52011-10-05 23:54:29 +0000505 typedef llvm::DenseMap<ObjCSummaryKey, const RetainSummary *> MapTy;
Ted Kremenek553cf182008-06-25 21:21:56 +0000506 MapTy M;
507public:
508 ObjCSummaryCache() {}
Mike Stump1eb44332009-09-09 15:08:12 +0000509
Ted Kremenek93edbc52011-10-05 23:54:29 +0000510 const RetainSummary * find(const ObjCInterfaceDecl *D, Selector S) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000511 // Do a lookup with the (D,S) pair. If we find a match return
512 // the iterator.
513 ObjCSummaryKey K(D, S);
514 MapTy::iterator I = M.find(K);
Mike Stump1eb44332009-09-09 15:08:12 +0000515
Jordan Rose4531b7d2012-07-02 19:27:43 +0000516 if (I != M.end())
Ted Kremenek614cc542009-07-21 23:27:57 +0000517 return I->second;
Jordan Rose4531b7d2012-07-02 19:27:43 +0000518 if (!D)
519 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +0000520
Ted Kremenek553cf182008-06-25 21:21:56 +0000521 // Walk the super chain. If we find a hit with a parent, we'll end
522 // up returning that summary. We actually allow that key (null,S), as
523 // we cache summaries for the null ObjCInterfaceDecl* to allow us to
524 // generate initial summaries without having to worry about NSObject
525 // being declared.
526 // FIXME: We may change this at some point.
Ted Kremenek9c378f72011-08-12 23:37:29 +0000527 for (ObjCInterfaceDecl *C=D->getSuperClass() ;; C=C->getSuperClass()) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000528 if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
529 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000530
Ted Kremenek553cf182008-06-25 21:21:56 +0000531 if (!C)
Ted Kremenek614cc542009-07-21 23:27:57 +0000532 return NULL;
Ted Kremenek553cf182008-06-25 21:21:56 +0000533 }
Mike Stump1eb44332009-09-09 15:08:12 +0000534
535 // Cache the summary with original key to make the next lookup faster
Ted Kremenek553cf182008-06-25 21:21:56 +0000536 // and return the iterator.
Ted Kremenek93edbc52011-10-05 23:54:29 +0000537 const RetainSummary *Summ = I->second;
Ted Kremenek614cc542009-07-21 23:27:57 +0000538 M[K] = Summ;
539 return Summ;
Ted Kremenek553cf182008-06-25 21:21:56 +0000540 }
Mike Stump1eb44332009-09-09 15:08:12 +0000541
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000542 const RetainSummary *find(IdentifierInfo* II, Selector S) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000543 // FIXME: Class method lookup. Right now we dont' have a good way
544 // of going between IdentifierInfo* and the class hierarchy.
Ted Kremenek614cc542009-07-21 23:27:57 +0000545 MapTy::iterator I = M.find(ObjCSummaryKey(II, S));
Mike Stump1eb44332009-09-09 15:08:12 +0000546
Ted Kremenek614cc542009-07-21 23:27:57 +0000547 if (I == M.end())
548 I = M.find(ObjCSummaryKey(S));
Mike Stump1eb44332009-09-09 15:08:12 +0000549
Ted Kremenek614cc542009-07-21 23:27:57 +0000550 return I == M.end() ? NULL : I->second;
Ted Kremenek553cf182008-06-25 21:21:56 +0000551 }
Mike Stump1eb44332009-09-09 15:08:12 +0000552
Ted Kremenek93edbc52011-10-05 23:54:29 +0000553 const RetainSummary *& operator[](ObjCSummaryKey K) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000554 return M[K];
555 }
Mike Stump1eb44332009-09-09 15:08:12 +0000556
Ted Kremenek93edbc52011-10-05 23:54:29 +0000557 const RetainSummary *& operator[](Selector S) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000558 return M[ ObjCSummaryKey(S) ];
559 }
Mike Stump1eb44332009-09-09 15:08:12 +0000560};
Ted Kremenek553cf182008-06-25 21:21:56 +0000561} // end anonymous namespace
562
563//===----------------------------------------------------------------------===//
564// Data structures for managing collections of summaries.
565//===----------------------------------------------------------------------===//
566
567namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000568class RetainSummaryManager {
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000569
570 //==-----------------------------------------------------------------==//
571 // Typedefs.
572 //==-----------------------------------------------------------------==//
Mike Stump1eb44332009-09-09 15:08:12 +0000573
Ted Kremenek93edbc52011-10-05 23:54:29 +0000574 typedef llvm::DenseMap<const FunctionDecl*, const RetainSummary *>
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000575 FuncSummariesTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000576
Ted Kremenek4f22a782008-06-23 23:30:29 +0000577 typedef ObjCSummaryCache ObjCMethodSummariesTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000578
Jordy Roseef945882012-03-18 01:26:10 +0000579 typedef llvm::FoldingSetNodeWrapper<RetainSummary> CachedSummaryNode;
580
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000581 //==-----------------------------------------------------------------==//
582 // Data.
583 //==-----------------------------------------------------------------==//
Mike Stump1eb44332009-09-09 15:08:12 +0000584
Ted Kremenek553cf182008-06-25 21:21:56 +0000585 /// Ctx - The ASTContext object for the analyzed ASTs.
Ted Kremenek9c378f72011-08-12 23:37:29 +0000586 ASTContext &Ctx;
Ted Kremenek179064e2008-07-01 17:21:27 +0000587
Ted Kremenek553cf182008-06-25 21:21:56 +0000588 /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
Ted Kremenek377e2302008-04-29 05:33:51 +0000589 const bool GCEnabled;
Mike Stump1eb44332009-09-09 15:08:12 +0000590
John McCallf85e1932011-06-15 23:02:42 +0000591 /// Records whether or not the analyzed code runs in ARC mode.
592 const bool ARCEnabled;
593
Ted Kremenek553cf182008-06-25 21:21:56 +0000594 /// FuncSummaries - A map from FunctionDecls to summaries.
Mike Stump1eb44332009-09-09 15:08:12 +0000595 FuncSummariesTy FuncSummaries;
596
Ted Kremenek553cf182008-06-25 21:21:56 +0000597 /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
598 /// to summaries.
Ted Kremenek1f180c32008-06-23 22:21:20 +0000599 ObjCMethodSummariesTy ObjCClassMethodSummaries;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000600
Ted Kremenek553cf182008-06-25 21:21:56 +0000601 /// ObjCMethodSummaries - A map from selectors to summaries.
Ted Kremenek1f180c32008-06-23 22:21:20 +0000602 ObjCMethodSummariesTy ObjCMethodSummaries;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000603
Ted Kremenek553cf182008-06-25 21:21:56 +0000604 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
605 /// and all other data used by the checker.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000606 llvm::BumpPtrAllocator BPAlloc;
Mike Stump1eb44332009-09-09 15:08:12 +0000607
Ted Kremenekb77449c2009-05-03 05:20:50 +0000608 /// AF - A factory for ArgEffects objects.
Mike Stump1eb44332009-09-09 15:08:12 +0000609 ArgEffects::Factory AF;
610
Ted Kremenek553cf182008-06-25 21:21:56 +0000611 /// ScratchArgs - A holding buffer for construct ArgEffects.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000612 ArgEffects ScratchArgs;
Mike Stump1eb44332009-09-09 15:08:12 +0000613
Ted Kremenekec315332009-05-07 23:40:42 +0000614 /// ObjCAllocRetE - Default return effect for methods returning Objective-C
615 /// objects.
616 RetEffect ObjCAllocRetE;
Ted Kremenek547d4952009-06-05 23:18:01 +0000617
Mike Stump1eb44332009-09-09 15:08:12 +0000618 /// ObjCInitRetE - Default return effect for init methods returning
Ted Kremenekac02f202009-08-20 05:13:36 +0000619 /// Objective-C objects.
Ted Kremenek547d4952009-06-05 23:18:01 +0000620 RetEffect ObjCInitRetE;
Mike Stump1eb44332009-09-09 15:08:12 +0000621
Jordy Roseef945882012-03-18 01:26:10 +0000622 /// SimpleSummaries - Used for uniquing summaries that don't have special
623 /// effects.
624 llvm::FoldingSet<CachedSummaryNode> SimpleSummaries;
Mike Stump1eb44332009-09-09 15:08:12 +0000625
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000626 //==-----------------------------------------------------------------==//
627 // Methods.
628 //==-----------------------------------------------------------------==//
Mike Stump1eb44332009-09-09 15:08:12 +0000629
Ted Kremenek553cf182008-06-25 21:21:56 +0000630 /// getArgEffects - Returns a persistent ArgEffects object based on the
631 /// data in ScratchArgs.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000632 ArgEffects getArgEffects();
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000633
Mike Stump1eb44332009-09-09 15:08:12 +0000634 enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
Ted Kremenek93edbc52011-10-05 23:54:29 +0000635
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000636 const RetainSummary *getUnarySummary(const FunctionType* FT,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000637 UnaryFuncKind func);
Mike Stump1eb44332009-09-09 15:08:12 +0000638
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000639 const RetainSummary *getCFSummaryCreateRule(const FunctionDecl *FD);
640 const RetainSummary *getCFSummaryGetRule(const FunctionDecl *FD);
641 const RetainSummary *getCFCreateGetRuleSummary(const FunctionDecl *FD);
Mike Stump1eb44332009-09-09 15:08:12 +0000642
Jordy Roseef945882012-03-18 01:26:10 +0000643 const RetainSummary *getPersistentSummary(const RetainSummary &OldSumm);
Ted Kremenek706522f2008-10-29 04:07:07 +0000644
Jordy Roseef945882012-03-18 01:26:10 +0000645 const RetainSummary *getPersistentSummary(RetEffect RetEff,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000646 ArgEffect ReceiverEff = DoNothing,
647 ArgEffect DefaultEff = MayEscape) {
Jordy Roseef945882012-03-18 01:26:10 +0000648 RetainSummary Summ(getArgEffects(), RetEff, DefaultEff, ReceiverEff);
649 return getPersistentSummary(Summ);
650 }
651
Ted Kremenekc91fdf62012-05-08 00:12:09 +0000652 const RetainSummary *getDoNothingSummary() {
653 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
654 }
655
Jordy Roseef945882012-03-18 01:26:10 +0000656 const RetainSummary *getDefaultSummary() {
657 return getPersistentSummary(RetEffect::MakeNoRet(),
658 DoNothing, MayEscape);
Ted Kremenek9c32d082008-05-06 00:30:21 +0000659 }
Mike Stump1eb44332009-09-09 15:08:12 +0000660
Ted Kremenek93edbc52011-10-05 23:54:29 +0000661 const RetainSummary *getPersistentStopSummary() {
Jordy Roseef945882012-03-18 01:26:10 +0000662 return getPersistentSummary(RetEffect::MakeNoRet(),
663 StopTracking, StopTracking);
Mike Stump1eb44332009-09-09 15:08:12 +0000664 }
Ted Kremenekb3095252008-05-06 04:20:12 +0000665
Ted Kremenek1f180c32008-06-23 22:21:20 +0000666 void InitializeClassMethodSummaries();
667 void InitializeMethodSummaries();
Ted Kremenek896cd9d2008-10-23 01:56:15 +0000668private:
Ted Kremenek93edbc52011-10-05 23:54:29 +0000669 void addNSObjectClsMethSummary(Selector S, const RetainSummary *Summ) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000670 ObjCClassMethodSummaries[S] = Summ;
671 }
Mike Stump1eb44332009-09-09 15:08:12 +0000672
Ted Kremenek93edbc52011-10-05 23:54:29 +0000673 void addNSObjectMethSummary(Selector S, const RetainSummary *Summ) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000674 ObjCMethodSummaries[S] = Summ;
675 }
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +0000676
Ted Kremeneka9797122012-02-18 21:37:48 +0000677 void addClassMethSummary(const char* Cls, const char* name,
678 const RetainSummary *Summ, bool isNullary = true) {
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +0000679 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
Ted Kremeneka9797122012-02-18 21:37:48 +0000680 Selector S = isNullary ? GetNullarySelector(name, Ctx)
681 : GetUnarySelector(name, Ctx);
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +0000682 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
683 }
Mike Stump1eb44332009-09-09 15:08:12 +0000684
Ted Kremenek6c4becb2009-02-25 02:54:57 +0000685 void addInstMethSummary(const char* Cls, const char* nullaryName,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000686 const RetainSummary *Summ) {
Ted Kremenek6c4becb2009-02-25 02:54:57 +0000687 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
688 Selector S = GetNullarySelector(nullaryName, Ctx);
689 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
690 }
Mike Stump1eb44332009-09-09 15:08:12 +0000691
Ted Kremenekde4d5332009-04-24 17:50:11 +0000692 Selector generateSelector(va_list argp) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000693 SmallVector<IdentifierInfo*, 10> II;
Ted Kremenekde4d5332009-04-24 17:50:11 +0000694
Ted Kremenek9e476de2008-08-12 18:30:56 +0000695 while (const char* s = va_arg(argp, const char*))
696 II.push_back(&Ctx.Idents.get(s));
Ted Kremenekde4d5332009-04-24 17:50:11 +0000697
Mike Stump1eb44332009-09-09 15:08:12 +0000698 return Ctx.Selectors.getSelector(II.size(), &II[0]);
Ted Kremenekde4d5332009-04-24 17:50:11 +0000699 }
Mike Stump1eb44332009-09-09 15:08:12 +0000700
Ted Kremenekde4d5332009-04-24 17:50:11 +0000701 void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy& Summaries,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000702 const RetainSummary * Summ, va_list argp) {
Ted Kremenekde4d5332009-04-24 17:50:11 +0000703 Selector S = generateSelector(argp);
704 Summaries[ObjCSummaryKey(ClsII, S)] = Summ;
Ted Kremenek70a733e2008-07-18 17:24:20 +0000705 }
Mike Stump1eb44332009-09-09 15:08:12 +0000706
Ted Kremenek93edbc52011-10-05 23:54:29 +0000707 void addInstMethSummary(const char* Cls, const RetainSummary * Summ, ...) {
Ted Kremenekaf9dc272008-08-12 18:48:50 +0000708 va_list argp;
709 va_start(argp, Summ);
Ted Kremenekde4d5332009-04-24 17:50:11 +0000710 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Mike Stump1eb44332009-09-09 15:08:12 +0000711 va_end(argp);
Ted Kremenekaf9dc272008-08-12 18:48:50 +0000712 }
Mike Stump1eb44332009-09-09 15:08:12 +0000713
Ted Kremenek93edbc52011-10-05 23:54:29 +0000714 void addClsMethSummary(const char* Cls, const RetainSummary * Summ, ...) {
Ted Kremenekde4d5332009-04-24 17:50:11 +0000715 va_list argp;
716 va_start(argp, Summ);
717 addMethodSummary(&Ctx.Idents.get(Cls),ObjCClassMethodSummaries, Summ, argp);
718 va_end(argp);
719 }
Mike Stump1eb44332009-09-09 15:08:12 +0000720
Ted Kremenek93edbc52011-10-05 23:54:29 +0000721 void addClsMethSummary(IdentifierInfo *II, const RetainSummary * Summ, ...) {
Ted Kremenekde4d5332009-04-24 17:50:11 +0000722 va_list argp;
723 va_start(argp, Summ);
724 addMethodSummary(II, ObjCClassMethodSummaries, Summ, argp);
725 va_end(argp);
726 }
727
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000728public:
Mike Stump1eb44332009-09-09 15:08:12 +0000729
Ted Kremenek9c378f72011-08-12 23:37:29 +0000730 RetainSummaryManager(ASTContext &ctx, bool gcenabled, bool usesARC)
Ted Kremenek179064e2008-07-01 17:21:27 +0000731 : Ctx(ctx),
John McCallf85e1932011-06-15 23:02:42 +0000732 GCEnabled(gcenabled),
733 ARCEnabled(usesARC),
734 AF(BPAlloc), ScratchArgs(AF.getEmptyMap()),
735 ObjCAllocRetE(gcenabled
736 ? RetEffect::MakeGCNotOwned()
737 : (usesARC ? RetEffect::MakeARCNotOwned()
738 : RetEffect::MakeOwned(RetEffect::ObjC, true))),
739 ObjCInitRetE(gcenabled
740 ? RetEffect::MakeGCNotOwned()
741 : (usesARC ? RetEffect::MakeARCNotOwned()
Jordy Roseef945882012-03-18 01:26:10 +0000742 : RetEffect::MakeOwnedWhenTrackedReceiver())) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000743 InitializeClassMethodSummaries();
744 InitializeMethodSummaries();
745 }
Mike Stump1eb44332009-09-09 15:08:12 +0000746
Jordan Rose4531b7d2012-07-02 19:27:43 +0000747 const RetainSummary *getSummary(const CallEvent &Call,
748 ProgramStateRef State = 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000749
Jordan Rose4531b7d2012-07-02 19:27:43 +0000750 const RetainSummary *getFunctionSummary(const FunctionDecl *FD);
751
752 const RetainSummary *getMethodSummary(Selector S, const ObjCInterfaceDecl *ID,
Jordy Rosef3aae582012-03-17 21:13:07 +0000753 const ObjCMethodDecl *MD,
754 QualType RetTy,
755 ObjCMethodSummariesTy &CachedSummaries);
756
Jordan Rosecde8cdb2012-07-02 19:27:56 +0000757 const RetainSummary *getInstanceMethodSummary(const ObjCMethodCall &M,
Jordan Rose4531b7d2012-07-02 19:27:43 +0000758 ProgramStateRef State);
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000759
Jordan Rosecde8cdb2012-07-02 19:27:56 +0000760 const RetainSummary *getClassMethodSummary(const ObjCMethodCall &M) {
Jordan Rose4531b7d2012-07-02 19:27:43 +0000761 assert(!M.isInstanceMessage());
762 const ObjCInterfaceDecl *Class = M.getReceiverInterface();
Mike Stump1eb44332009-09-09 15:08:12 +0000763
Jordan Rose4531b7d2012-07-02 19:27:43 +0000764 return getMethodSummary(M.getSelector(), Class, M.getDecl(),
765 M.getResultType(), ObjCClassMethodSummaries);
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +0000766 }
Ted Kremenek552333c2009-04-29 17:17:48 +0000767
768 /// getMethodSummary - This version of getMethodSummary is used to query
769 /// the summary for the current method being analyzed.
Ted Kremenek93edbc52011-10-05 23:54:29 +0000770 const RetainSummary *getMethodSummary(const ObjCMethodDecl *MD) {
Ted Kremeneka8833552009-04-29 23:03:22 +0000771 const ObjCInterfaceDecl *ID = MD->getClassInterface();
Ted Kremenek70a65762009-04-30 05:41:14 +0000772 Selector S = MD->getSelector();
Ted Kremenek552333c2009-04-29 17:17:48 +0000773 QualType ResultTy = MD->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +0000774
Jordy Rosef3aae582012-03-17 21:13:07 +0000775 ObjCMethodSummariesTy *CachedSummaries;
Ted Kremenek552333c2009-04-29 17:17:48 +0000776 if (MD->isInstanceMethod())
Jordy Rosef3aae582012-03-17 21:13:07 +0000777 CachedSummaries = &ObjCMethodSummaries;
Ted Kremenek552333c2009-04-29 17:17:48 +0000778 else
Jordy Rosef3aae582012-03-17 21:13:07 +0000779 CachedSummaries = &ObjCClassMethodSummaries;
780
Jordan Rose4531b7d2012-07-02 19:27:43 +0000781 return getMethodSummary(S, ID, MD, ResultTy, *CachedSummaries);
Ted Kremenek552333c2009-04-29 17:17:48 +0000782 }
Mike Stump1eb44332009-09-09 15:08:12 +0000783
Jordy Rosef3aae582012-03-17 21:13:07 +0000784 const RetainSummary *getStandardMethodSummary(const ObjCMethodDecl *MD,
Jordan Rose4531b7d2012-07-02 19:27:43 +0000785 Selector S, QualType RetTy);
Ted Kremeneka8833552009-04-29 23:03:22 +0000786
Jordan Rose44405b72013-04-04 22:31:48 +0000787 /// Determine if there is a special return effect for this function or method.
788 Optional<RetEffect> getRetEffectFromAnnotations(QualType RetTy,
789 const Decl *D);
790
Ted Kremenek93edbc52011-10-05 23:54:29 +0000791 void updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenek4dd8fb42009-05-09 02:58:13 +0000792 const ObjCMethodDecl *MD);
793
Ted Kremenek93edbc52011-10-05 23:54:29 +0000794 void updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenek4dd8fb42009-05-09 02:58:13 +0000795 const FunctionDecl *FD);
796
Jordan Rose4531b7d2012-07-02 19:27:43 +0000797 void updateSummaryForCall(const RetainSummary *&Summ,
798 const CallEvent &Call);
799
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000800 bool isGCEnabled() const { return GCEnabled; }
Mike Stump1eb44332009-09-09 15:08:12 +0000801
John McCallf85e1932011-06-15 23:02:42 +0000802 bool isARCEnabled() const { return ARCEnabled; }
803
804 bool isARCorGCEnabled() const { return GCEnabled || ARCEnabled; }
Jordan Rose4531b7d2012-07-02 19:27:43 +0000805
806 RetEffect getObjAllocRetEffect() const { return ObjCAllocRetE; }
807
808 friend class RetainSummaryTemplate;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000809};
Mike Stump1eb44332009-09-09 15:08:12 +0000810
Jordy Rose0fe62f82011-08-24 09:02:37 +0000811// Used to avoid allocating long-term (BPAlloc'd) memory for default retain
812// summaries. If a function or method looks like it has a default summary, but
813// it has annotations, the annotations are added to the stack-based template
814// and then copied into managed memory.
815class RetainSummaryTemplate {
816 RetainSummaryManager &Manager;
Ted Kremenek93edbc52011-10-05 23:54:29 +0000817 const RetainSummary *&RealSummary;
Jordy Rose0fe62f82011-08-24 09:02:37 +0000818 RetainSummary ScratchSummary;
819 bool Accessed;
820public:
Jordan Rose4531b7d2012-07-02 19:27:43 +0000821 RetainSummaryTemplate(const RetainSummary *&real, RetainSummaryManager &mgr)
822 : Manager(mgr), RealSummary(real), ScratchSummary(*real), Accessed(false) {}
Jordy Rose0fe62f82011-08-24 09:02:37 +0000823
824 ~RetainSummaryTemplate() {
Ted Kremenek93edbc52011-10-05 23:54:29 +0000825 if (Accessed)
Jordy Roseef945882012-03-18 01:26:10 +0000826 RealSummary = Manager.getPersistentSummary(ScratchSummary);
Jordy Rose0fe62f82011-08-24 09:02:37 +0000827 }
828
829 RetainSummary &operator*() {
830 Accessed = true;
Ted Kremenek93edbc52011-10-05 23:54:29 +0000831 return ScratchSummary;
Jordy Rose0fe62f82011-08-24 09:02:37 +0000832 }
833
834 RetainSummary *operator->() {
835 Accessed = true;
Ted Kremenek93edbc52011-10-05 23:54:29 +0000836 return &ScratchSummary;
Jordy Rose0fe62f82011-08-24 09:02:37 +0000837 }
838};
839
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000840} // end anonymous namespace
841
842//===----------------------------------------------------------------------===//
843// Implementation of checker data structures.
844//===----------------------------------------------------------------------===//
845
Ted Kremenekb77449c2009-05-03 05:20:50 +0000846ArgEffects RetainSummaryManager::getArgEffects() {
847 ArgEffects AE = ScratchArgs;
Ted Kremenek3baf6722010-11-24 00:54:37 +0000848 ScratchArgs = AF.getEmptyMap();
Ted Kremenekb77449c2009-05-03 05:20:50 +0000849 return AE;
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000850}
851
Ted Kremenek93edbc52011-10-05 23:54:29 +0000852const RetainSummary *
Jordy Roseef945882012-03-18 01:26:10 +0000853RetainSummaryManager::getPersistentSummary(const RetainSummary &OldSumm) {
854 // Unique "simple" summaries -- those without ArgEffects.
855 if (OldSumm.isSimple()) {
856 llvm::FoldingSetNodeID ID;
857 OldSumm.Profile(ID);
858
859 void *Pos;
860 CachedSummaryNode *N = SimpleSummaries.FindNodeOrInsertPos(ID, Pos);
861
862 if (!N) {
863 N = (CachedSummaryNode *) BPAlloc.Allocate<CachedSummaryNode>();
864 new (N) CachedSummaryNode(OldSumm);
865 SimpleSummaries.InsertNode(N, Pos);
866 }
867
868 return &N->getValue();
869 }
870
Ted Kremenek93edbc52011-10-05 23:54:29 +0000871 RetainSummary *Summ = (RetainSummary *) BPAlloc.Allocate<RetainSummary>();
Jordy Roseef945882012-03-18 01:26:10 +0000872 new (Summ) RetainSummary(OldSumm);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000873 return Summ;
874}
875
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000876//===----------------------------------------------------------------------===//
877// Summary creation for functions (largely uses of Core Foundation).
878//===----------------------------------------------------------------------===//
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000879
Ted Kremenek9c378f72011-08-12 23:37:29 +0000880static bool isRetain(const FunctionDecl *FD, StringRef FName) {
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000881 return FName.endswith("Retain");
Ted Kremenek12619382009-01-12 21:45:02 +0000882}
883
Ted Kremenek9c378f72011-08-12 23:37:29 +0000884static bool isRelease(const FunctionDecl *FD, StringRef FName) {
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000885 return FName.endswith("Release");
Ted Kremenek12619382009-01-12 21:45:02 +0000886}
887
Jordy Rose76c506f2011-08-21 21:58:18 +0000888static bool isMakeCollectable(const FunctionDecl *FD, StringRef FName) {
889 // FIXME: Remove FunctionDecl parameter.
890 // FIXME: Is it really okay if MakeCollectable isn't a suffix?
891 return FName.find("MakeCollectable") != StringRef::npos;
892}
893
Anna Zaks554067f2012-08-29 23:23:43 +0000894static ArgEffect getStopTrackingHardEquivalent(ArgEffect E) {
Jordan Rose4531b7d2012-07-02 19:27:43 +0000895 switch (E) {
896 case DoNothing:
897 case Autorelease:
898 case DecRefBridgedTransfered:
899 case IncRef:
900 case IncRefMsg:
901 case MakeCollectable:
902 case MayEscape:
Jordan Rose4531b7d2012-07-02 19:27:43 +0000903 case StopTracking:
Anna Zaks554067f2012-08-29 23:23:43 +0000904 case StopTrackingHard:
905 return StopTrackingHard;
Jordan Rose4531b7d2012-07-02 19:27:43 +0000906 case DecRef:
Anna Zaks554067f2012-08-29 23:23:43 +0000907 case DecRefAndStopTrackingHard:
908 return DecRefAndStopTrackingHard;
Jordan Rose4531b7d2012-07-02 19:27:43 +0000909 case DecRefMsg:
Anna Zaks554067f2012-08-29 23:23:43 +0000910 case DecRefMsgAndStopTrackingHard:
911 return DecRefMsgAndStopTrackingHard;
Jordan Rose4531b7d2012-07-02 19:27:43 +0000912 case Dealloc:
913 return Dealloc;
914 }
915
916 llvm_unreachable("Unknown ArgEffect kind");
917}
918
919void RetainSummaryManager::updateSummaryForCall(const RetainSummary *&S,
920 const CallEvent &Call) {
921 if (Call.hasNonZeroCallbackArg()) {
Anna Zaks554067f2012-08-29 23:23:43 +0000922 ArgEffect RecEffect =
923 getStopTrackingHardEquivalent(S->getReceiverEffect());
924 ArgEffect DefEffect =
925 getStopTrackingHardEquivalent(S->getDefaultArgEffect());
Jordan Rose4531b7d2012-07-02 19:27:43 +0000926
927 ArgEffects CustomArgEffects = S->getArgEffects();
928 for (ArgEffects::iterator I = CustomArgEffects.begin(),
929 E = CustomArgEffects.end();
930 I != E; ++I) {
Anna Zaks554067f2012-08-29 23:23:43 +0000931 ArgEffect Translated = getStopTrackingHardEquivalent(I->second);
Jordan Rose4531b7d2012-07-02 19:27:43 +0000932 if (Translated != DefEffect)
933 ScratchArgs = AF.add(ScratchArgs, I->first, Translated);
934 }
935
Anna Zaks554067f2012-08-29 23:23:43 +0000936 RetEffect RE = RetEffect::MakeNoRetHard();
Jordan Rose4531b7d2012-07-02 19:27:43 +0000937
938 // Special cases where the callback argument CANNOT free the return value.
939 // This can generally only happen if we know that the callback will only be
940 // called when the return value is already being deallocated.
941 if (const FunctionCall *FC = dyn_cast<FunctionCall>(&Call)) {
Jordan Rose4a25f302012-09-01 17:39:13 +0000942 if (IdentifierInfo *Name = FC->getDecl()->getIdentifier()) {
943 // When the CGBitmapContext is deallocated, the callback here will free
944 // the associated data buffer.
Jordan Rosea89f7192012-08-31 18:19:18 +0000945 if (Name->isStr("CGBitmapContextCreateWithData"))
946 RE = S->getRetEffect();
Jordan Rose4a25f302012-09-01 17:39:13 +0000947 }
Jordan Rose4531b7d2012-07-02 19:27:43 +0000948 }
949
950 S = getPersistentSummary(RE, RecEffect, DefEffect);
951 }
Anna Zaks5a901932012-08-24 00:06:12 +0000952
953 // Special case '[super init];' and '[self init];'
954 //
955 // Even though calling '[super init]' without assigning the result to self
956 // and checking if the parent returns 'nil' is a bad pattern, it is common.
957 // Additionally, our Self Init checker already warns about it. To avoid
958 // overwhelming the user with messages from both checkers, we model the case
959 // of '[super init]' in cases when it is not consumed by another expression
960 // as if the call preserves the value of 'self'; essentially, assuming it can
961 // never fail and return 'nil'.
962 // Note, we don't want to just stop tracking the value since we want the
963 // RetainCount checker to report leaks and use-after-free if SelfInit checker
964 // is turned off.
965 if (const ObjCMethodCall *MC = dyn_cast<ObjCMethodCall>(&Call)) {
966 if (MC->getMethodFamily() == OMF_init && MC->isReceiverSelfOrSuper()) {
967
968 // Check if the message is not consumed, we know it will not be used in
969 // an assignment, ex: "self = [super init]".
970 const Expr *ME = MC->getOriginExpr();
971 const LocationContext *LCtx = MC->getLocationContext();
972 ParentMap &PM = LCtx->getAnalysisDeclContext()->getParentMap();
973 if (!PM.isConsumedExpr(ME)) {
974 RetainSummaryTemplate ModifiableSummaryTemplate(S, *this);
975 ModifiableSummaryTemplate->setReceiverEffect(DoNothing);
976 ModifiableSummaryTemplate->setRetEffect(RetEffect::MakeNoRet());
977 }
978 }
979
980 }
Jordan Rose4531b7d2012-07-02 19:27:43 +0000981}
982
Anna Zaks58822c42012-05-04 22:18:39 +0000983const RetainSummary *
Jordan Rose4531b7d2012-07-02 19:27:43 +0000984RetainSummaryManager::getSummary(const CallEvent &Call,
985 ProgramStateRef State) {
986 const RetainSummary *Summ;
987 switch (Call.getKind()) {
988 case CE_Function:
989 Summ = getFunctionSummary(cast<FunctionCall>(Call).getDecl());
990 break;
991 case CE_CXXMember:
Jordan Rosefdaa3382012-07-03 22:55:57 +0000992 case CE_CXXMemberOperator:
Jordan Rose4531b7d2012-07-02 19:27:43 +0000993 case CE_Block:
994 case CE_CXXConstructor:
Jordan Rose8d276d32012-07-10 22:07:47 +0000995 case CE_CXXDestructor:
Jordan Rose70cbf3c2012-07-02 22:21:47 +0000996 case CE_CXXAllocator:
Jordan Rose4531b7d2012-07-02 19:27:43 +0000997 // FIXME: These calls are currently unsupported.
998 return getPersistentStopSummary();
Jordan Rose8919e682012-07-18 21:59:51 +0000999 case CE_ObjCMessage: {
Jordan Rosecde8cdb2012-07-02 19:27:56 +00001000 const ObjCMethodCall &Msg = cast<ObjCMethodCall>(Call);
Jordan Rose4531b7d2012-07-02 19:27:43 +00001001 if (Msg.isInstanceMessage())
1002 Summ = getInstanceMethodSummary(Msg, State);
1003 else
1004 Summ = getClassMethodSummary(Msg);
1005 break;
1006 }
1007 }
1008
1009 updateSummaryForCall(Summ, Call);
1010
1011 assert(Summ && "Unknown call type?");
1012 return Summ;
1013}
1014
1015const RetainSummary *
1016RetainSummaryManager::getFunctionSummary(const FunctionDecl *FD) {
1017 // If we don't know what function we're calling, use our default summary.
1018 if (!FD)
1019 return getDefaultSummary();
1020
Ted Kremenek891d5cc2008-04-24 17:22:33 +00001021 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001022 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001023 if (I != FuncSummaries.end())
Ted Kremenek891d5cc2008-04-24 17:22:33 +00001024 return I->second;
1025
Ted Kremeneke401a0c2009-05-04 15:34:07 +00001026 // No summary? Generate one.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001027 const RetainSummary *S = 0;
Jordan Rose15d18e12012-08-06 21:28:02 +00001028 bool AllowAnnotations = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001029
Ted Kremenek37d785b2008-07-15 16:50:12 +00001030 do {
Ted Kremenek12619382009-01-12 21:45:02 +00001031 // We generate "stop" summaries for implicitly defined functions.
1032 if (FD->isImplicit()) {
1033 S = getPersistentStopSummary();
1034 break;
Ted Kremenek37d785b2008-07-15 16:50:12 +00001035 }
Mike Stump1eb44332009-09-09 15:08:12 +00001036
John McCall183700f2009-09-21 23:43:11 +00001037 // [PR 3337] Use 'getAs<FunctionType>' to strip away any typedefs on the
Ted Kremenek99890652009-01-16 18:40:33 +00001038 // function's type.
John McCall183700f2009-09-21 23:43:11 +00001039 const FunctionType* FT = FD->getType()->getAs<FunctionType>();
Ted Kremenek48c6d182009-12-16 06:06:43 +00001040 const IdentifierInfo *II = FD->getIdentifier();
1041 if (!II)
1042 break;
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001043
1044 StringRef FName = II->getName();
Mike Stump1eb44332009-09-09 15:08:12 +00001045
Ted Kremenekbf0a4dd2009-03-05 22:11:14 +00001046 // Strip away preceding '_'. Doing this here will effect all the checks
1047 // down below.
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001048 FName = FName.substr(FName.find_first_not_of('_'));
Mike Stump1eb44332009-09-09 15:08:12 +00001049
Ted Kremenek12619382009-01-12 21:45:02 +00001050 // Inspect the result type.
1051 QualType RetTy = FT->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00001052
Ted Kremenek12619382009-01-12 21:45:02 +00001053 // FIXME: This should all be refactored into a chain of "summary lookup"
1054 // filters.
Ted Kremenek008636a2009-10-14 00:27:24 +00001055 assert(ScratchArgs.isEmpty());
Ted Kremenek39d88b02009-06-15 20:36:07 +00001056
Ted Kremenekbefc6d22012-04-26 04:32:23 +00001057 if (FName == "pthread_create" || FName == "pthread_setspecific") {
1058 // Part of: <rdar://problem/7299394> and <rdar://problem/11282706>.
1059 // This will be addressed better with IPA.
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001060 S = getPersistentStopSummary();
1061 } else if (FName == "NSMakeCollectable") {
1062 // Handle: id NSMakeCollectable(CFTypeRef)
1063 S = (RetTy->isObjCIdType())
1064 ? getUnarySummary(FT, cfmakecollectable)
1065 : getPersistentStopSummary();
Jordan Rose15d18e12012-08-06 21:28:02 +00001066 // The headers on OS X 10.8 use cf_consumed/ns_returns_retained,
1067 // but we can fully model NSMakeCollectable ourselves.
1068 AllowAnnotations = false;
Ted Kremenek061707a2012-09-06 23:47:02 +00001069 } else if (FName == "CFPlugInInstanceCreate") {
1070 S = getPersistentSummary(RetEffect::MakeNoRet());
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001071 } else if (FName == "IOBSDNameMatching" ||
1072 FName == "IOServiceMatching" ||
1073 FName == "IOServiceNameMatching" ||
Ted Kremenek537dd3a2012-05-01 05:28:27 +00001074 FName == "IORegistryEntrySearchCFProperty" ||
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001075 FName == "IORegistryEntryIDMatching" ||
1076 FName == "IOOpenFirmwarePathMatching") {
1077 // Part of <rdar://problem/6961230>. (IOKit)
1078 // This should be addressed using a API table.
1079 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1080 DoNothing, DoNothing);
1081 } else if (FName == "IOServiceGetMatchingService" ||
1082 FName == "IOServiceGetMatchingServices") {
1083 // FIXES: <rdar://problem/6326900>
1084 // This should be addressed using a API table. This strcmp is also
1085 // a little gross, but there is no need to super optimize here.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001086 ScratchArgs = AF.add(ScratchArgs, 1, DecRef);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001087 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1088 } else if (FName == "IOServiceAddNotification" ||
1089 FName == "IOServiceAddMatchingNotification") {
1090 // Part of <rdar://problem/6961230>. (IOKit)
1091 // This should be addressed using a API table.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001092 ScratchArgs = AF.add(ScratchArgs, 2, DecRef);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001093 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1094 } else if (FName == "CVPixelBufferCreateWithBytes") {
1095 // FIXES: <rdar://problem/7283567>
1096 // Eventually this can be improved by recognizing that the pixel
1097 // buffer passed to CVPixelBufferCreateWithBytes is released via
1098 // a callback and doing full IPA to make sure this is done correctly.
1099 // FIXME: This function has an out parameter that returns an
1100 // allocated object.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001101 ScratchArgs = AF.add(ScratchArgs, 7, StopTracking);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001102 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1103 } else if (FName == "CGBitmapContextCreateWithData") {
1104 // FIXES: <rdar://problem/7358899>
1105 // Eventually this can be improved by recognizing that 'releaseInfo'
1106 // passed to CGBitmapContextCreateWithData is released via
1107 // a callback and doing full IPA to make sure this is done correctly.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001108 ScratchArgs = AF.add(ScratchArgs, 8, StopTracking);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001109 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1110 DoNothing, DoNothing);
1111 } else if (FName == "CVPixelBufferCreateWithPlanarBytes") {
1112 // FIXES: <rdar://problem/7283567>
1113 // Eventually this can be improved by recognizing that the pixel
1114 // buffer passed to CVPixelBufferCreateWithPlanarBytes is released
1115 // via a callback and doing full IPA to make sure this is done
1116 // correctly.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001117 ScratchArgs = AF.add(ScratchArgs, 12, StopTracking);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001118 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenek06911d42012-03-22 06:29:41 +00001119 } else if (FName == "dispatch_set_context") {
1120 // <rdar://problem/11059275> - The analyzer currently doesn't have
1121 // a good way to reason about the finalizer function for libdispatch.
1122 // If we pass a context object that is memory managed, stop tracking it.
1123 // FIXME: this hack should possibly go away once we can handle
1124 // libdispatch finalizers.
1125 ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
1126 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenekc91fdf62012-05-08 00:12:09 +00001127 } else if (FName.startswith("NSLog")) {
1128 S = getDoNothingSummary();
Anna Zaks62a5c342012-03-30 05:48:16 +00001129 } else if (FName.startswith("NS") &&
1130 (FName.find("Insert") != StringRef::npos)) {
1131 // Whitelist NSXXInsertXX, for example NSMapInsertIfAbsent, since they can
1132 // be deallocated by NSMapRemove. (radar://11152419)
1133 ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
1134 ScratchArgs = AF.add(ScratchArgs, 2, StopTracking);
1135 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenekb04cb592009-06-11 18:17:24 +00001136 }
Mike Stump1eb44332009-09-09 15:08:12 +00001137
Ted Kremenekb04cb592009-06-11 18:17:24 +00001138 // Did we get a summary?
1139 if (S)
1140 break;
Ted Kremenek61991902009-03-17 22:43:44 +00001141
Jordan Rose5aff3f12013-03-04 23:21:32 +00001142 if (RetTy->isPointerType()) {
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
Jordan Rose5aff3f12013-03-04 23:21:32 +00001173 if (FD->getAttr<CFAuditedTransferAttr>()) {
1174 S = getCFCreateGetRuleSummary(FD);
1175 break;
1176 }
1177
Ted Kremenek12619382009-01-12 21:45:02 +00001178 break;
1179 }
1180
1181 // Check for release functions, the only kind of functions that we care
1182 // about that don't return a pointer type.
1183 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
Ted Kremeneke7d03122010-02-08 16:45:01 +00001184 // Test for 'CGCF'.
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001185 FName = FName.substr(FName.startswith("CGCF") ? 4 : 2);
Ted Kremeneke7d03122010-02-08 16:45:01 +00001186
Ted Kremenekbf0a4dd2009-03-05 22:11:14 +00001187 if (isRelease(FD, FName))
Ted Kremenek12619382009-01-12 21:45:02 +00001188 S = getUnarySummary(FT, cfrelease);
1189 else {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001190 assert (ScratchArgs.isEmpty());
Ted Kremenek68189282009-01-29 22:45:13 +00001191 // Remaining CoreFoundation and CoreGraphics functions.
1192 // We use to assume that they all strictly followed the ownership idiom
1193 // and that ownership cannot be transferred. While this is technically
1194 // correct, many methods allow a tracked object to escape. For example:
1195 //
Mike Stump1eb44332009-09-09 15:08:12 +00001196 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
Ted Kremenek68189282009-01-29 22:45:13 +00001197 // CFDictionaryAddValue(y, key, x);
Mike Stump1eb44332009-09-09 15:08:12 +00001198 // CFRelease(x);
Ted Kremenek68189282009-01-29 22:45:13 +00001199 // ... it is okay to use 'x' since 'y' has a reference to it
1200 //
1201 // We handle this and similar cases with the follow heuristic. If the
Ted Kremenekc4843812009-08-20 00:57:22 +00001202 // function name contains "InsertValue", "SetValue", "AddValue",
1203 // "AppendValue", or "SetAttribute", then we assume that arguments may
1204 // "escape." This means that something else holds on to the object,
1205 // allowing it be used even after its local retain count drops to 0.
Benjamin Kramere45c1492010-01-11 19:46:28 +00001206 ArgEffect E = (StrInStrNoCase(FName, "InsertValue") != StringRef::npos||
1207 StrInStrNoCase(FName, "AddValue") != StringRef::npos ||
1208 StrInStrNoCase(FName, "SetValue") != StringRef::npos ||
1209 StrInStrNoCase(FName, "AppendValue") != StringRef::npos||
Benjamin Kramerc027e542010-01-11 20:15:06 +00001210 StrInStrNoCase(FName, "SetAttribute") != StringRef::npos)
Ted Kremenek68189282009-01-29 22:45:13 +00001211 ? MayEscape : DoNothing;
Mike Stump1eb44332009-09-09 15:08:12 +00001212
Ted Kremenek68189282009-01-29 22:45:13 +00001213 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek12619382009-01-12 21:45:02 +00001214 }
1215 }
Ted Kremenek37d785b2008-07-15 16:50:12 +00001216 }
1217 while (0);
Mike Stump1eb44332009-09-09 15:08:12 +00001218
Jordan Rose4531b7d2012-07-02 19:27:43 +00001219 // If we got all the way here without any luck, use a default summary.
1220 if (!S)
1221 S = getDefaultSummary();
1222
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001223 // Annotations override defaults.
Jordan Rose15d18e12012-08-06 21:28:02 +00001224 if (AllowAnnotations)
1225 updateSummaryFromAnnotations(S, FD);
Mike Stump1eb44332009-09-09 15:08:12 +00001226
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001227 FuncSummaries[FD] = S;
Mike Stump1eb44332009-09-09 15:08:12 +00001228 return S;
Ted Kremenek2fff37e2008-03-06 00:08:09 +00001229}
1230
Ted Kremenek93edbc52011-10-05 23:54:29 +00001231const RetainSummary *
John McCall7df2ff42011-10-01 00:48:56 +00001232RetainSummaryManager::getCFCreateGetRuleSummary(const FunctionDecl *FD) {
1233 if (coreFoundation::followsCreateRule(FD))
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001234 return getCFSummaryCreateRule(FD);
Mike Stump1eb44332009-09-09 15:08:12 +00001235
Ted Kremenekd368d712011-05-25 06:19:45 +00001236 return getCFSummaryGetRule(FD);
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001237}
1238
Ted Kremenek93edbc52011-10-05 23:54:29 +00001239const RetainSummary *
Ted Kremenek6ad315a2009-02-23 16:51:39 +00001240RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1241 UnaryFuncKind func) {
1242
Ted Kremenek12619382009-01-12 21:45:02 +00001243 // Sanity check that this is *really* a unary function. This can
1244 // happen if people do weird things.
Douglas Gregor72564e72009-02-26 23:50:07 +00001245 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
Ted Kremenek12619382009-01-12 21:45:02 +00001246 if (!FTP || FTP->getNumArgs() != 1)
1247 return getPersistentStopSummary();
Mike Stump1eb44332009-09-09 15:08:12 +00001248
Ted Kremenekb77449c2009-05-03 05:20:50 +00001249 assert (ScratchArgs.isEmpty());
Mike Stump1eb44332009-09-09 15:08:12 +00001250
Jordy Rose76c506f2011-08-21 21:58:18 +00001251 ArgEffect Effect;
Ted Kremenek377e2302008-04-29 05:33:51 +00001252 switch (func) {
Jordy Rose76c506f2011-08-21 21:58:18 +00001253 case cfretain: Effect = IncRef; break;
1254 case cfrelease: Effect = DecRef; break;
1255 case cfmakecollectable: Effect = MakeCollectable; break;
Ted Kremenek940b1d82008-04-10 23:44:06 +00001256 }
Jordy Rose76c506f2011-08-21 21:58:18 +00001257
1258 ScratchArgs = AF.add(ScratchArgs, 0, Effect);
1259 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001260}
1261
Ted Kremenek93edbc52011-10-05 23:54:29 +00001262const RetainSummary *
Ted Kremenek9c378f72011-08-12 23:37:29 +00001263RetainSummaryManager::getCFSummaryCreateRule(const FunctionDecl *FD) {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001264 assert (ScratchArgs.isEmpty());
Mike Stump1eb44332009-09-09 15:08:12 +00001265
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001266 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001267}
1268
Ted Kremenek93edbc52011-10-05 23:54:29 +00001269const RetainSummary *
Ted Kremenek9c378f72011-08-12 23:37:29 +00001270RetainSummaryManager::getCFSummaryGetRule(const FunctionDecl *FD) {
Mike Stump1eb44332009-09-09 15:08:12 +00001271 assert (ScratchArgs.isEmpty());
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001272 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1273 DoNothing, DoNothing);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001274}
1275
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001276//===----------------------------------------------------------------------===//
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001277// Summary creation for Selectors.
1278//===----------------------------------------------------------------------===//
1279
Jordan Rose44405b72013-04-04 22:31:48 +00001280Optional<RetEffect>
1281RetainSummaryManager::getRetEffectFromAnnotations(QualType RetTy,
1282 const Decl *D) {
1283 if (cocoa::isCocoaObjectRef(RetTy)) {
1284 if (D->getAttr<NSReturnsRetainedAttr>())
1285 return ObjCAllocRetE;
1286
1287 if (D->getAttr<NSReturnsNotRetainedAttr>() ||
1288 D->getAttr<NSReturnsAutoreleasedAttr>())
1289 return RetEffect::MakeNotOwned(RetEffect::ObjC);
1290
1291 } else if (!RetTy->isPointerType()) {
1292 return None;
1293 }
1294
1295 if (D->getAttr<CFReturnsRetainedAttr>())
1296 return RetEffect::MakeOwned(RetEffect::CF, true);
1297
1298 if (D->getAttr<CFReturnsNotRetainedAttr>())
1299 return RetEffect::MakeNotOwned(RetEffect::CF);
1300
1301 return None;
1302}
1303
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001304void
Ted Kremenek93edbc52011-10-05 23:54:29 +00001305RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001306 const FunctionDecl *FD) {
1307 if (!FD)
1308 return;
1309
Jordan Rose4531b7d2012-07-02 19:27:43 +00001310 assert(Summ && "Must have a summary to add annotations to.");
1311 RetainSummaryTemplate Template(Summ, *this);
Jordy Rose4df54fe2011-08-23 04:27:15 +00001312
Ted Kremenek11fe1752011-01-27 18:43:03 +00001313 // Effects on the parameters.
1314 unsigned parm_idx = 0;
1315 for (FunctionDecl::param_const_iterator pi = FD->param_begin(),
John McCall98b8f162011-04-06 09:02:12 +00001316 pe = FD->param_end(); pi != pe; ++pi, ++parm_idx) {
Ted Kremenek11fe1752011-01-27 18:43:03 +00001317 const ParmVarDecl *pd = *pi;
Jordan Rose44405b72013-04-04 22:31:48 +00001318 if (pd->getAttr<NSConsumedAttr>())
1319 Template->addArg(AF, parm_idx, DecRefMsg);
1320 else if (pd->getAttr<CFConsumedAttr>())
Jordy Rose0fe62f82011-08-24 09:02:37 +00001321 Template->addArg(AF, parm_idx, DecRef);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001322 }
1323
Ted Kremenekb04cb592009-06-11 18:17:24 +00001324 QualType RetTy = FD->getResultType();
Jordan Rose44405b72013-04-04 22:31:48 +00001325 if (Optional<RetEffect> RetE = getRetEffectFromAnnotations(RetTy, FD))
1326 Template->setRetEffect(*RetE);
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001327}
1328
1329void
Ted Kremenek93edbc52011-10-05 23:54:29 +00001330RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
1331 const ObjCMethodDecl *MD) {
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001332 if (!MD)
1333 return;
1334
Jordan Rose4531b7d2012-07-02 19:27:43 +00001335 assert(Summ && "Must have a valid summary to add annotations to");
1336 RetainSummaryTemplate Template(Summ, *this);
Mike Stump1eb44332009-09-09 15:08:12 +00001337
Ted Kremenek12b94342011-01-27 06:54:14 +00001338 // Effects on the receiver.
Jordan Rose44405b72013-04-04 22:31:48 +00001339 if (MD->getAttr<NSConsumesSelfAttr>())
1340 Template->setReceiverEffect(DecRefMsg);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001341
1342 // Effects on the parameters.
1343 unsigned parm_idx = 0;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00001344 for (ObjCMethodDecl::param_const_iterator
1345 pi=MD->param_begin(), pe=MD->param_end();
Ted Kremenek11fe1752011-01-27 18:43:03 +00001346 pi != pe; ++pi, ++parm_idx) {
1347 const ParmVarDecl *pd = *pi;
Jordan Rose44405b72013-04-04 22:31:48 +00001348 if (pd->getAttr<NSConsumedAttr>())
1349 Template->addArg(AF, parm_idx, DecRefMsg);
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
Jordan Rose44405b72013-04-04 22:31:48 +00001355 QualType RetTy = MD->getResultType();
1356 if (Optional<RetEffect> RetE = getRetEffectFromAnnotations(RetTy, MD))
1357 Template->setRetEffect(*RetE);
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001358}
1359
Ted Kremenek93edbc52011-10-05 23:54:29 +00001360const RetainSummary *
Jordy Rosef3aae582012-03-17 21:13:07 +00001361RetainSummaryManager::getStandardMethodSummary(const ObjCMethodDecl *MD,
1362 Selector S, QualType RetTy) {
Jordy Rosee921b1a2012-03-17 19:53:04 +00001363 // Any special effects?
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001364 ArgEffect ReceiverEff = DoNothing;
Jordy Rosee921b1a2012-03-17 19:53:04 +00001365 RetEffect ResultEff = RetEffect::MakeNoRet();
1366
1367 // Check the method family, and apply any default annotations.
1368 switch (MD ? MD->getMethodFamily() : S.getMethodFamily()) {
1369 case OMF_None:
1370 case OMF_performSelector:
1371 // Assume all Objective-C methods follow Cocoa Memory Management rules.
1372 // FIXME: Does the non-threaded performSelector family really belong here?
1373 // The selector could be, say, @selector(copy).
1374 if (cocoa::isCocoaObjectRef(RetTy))
1375 ResultEff = RetEffect::MakeNotOwned(RetEffect::ObjC);
1376 else if (coreFoundation::isCFObjectRef(RetTy)) {
1377 // ObjCMethodDecl currently doesn't consider CF objects as valid return
1378 // values for alloc, new, copy, or mutableCopy, so we have to
1379 // double-check with the selector. This is ugly, but there aren't that
1380 // many Objective-C methods that return CF objects, right?
1381 if (MD) {
1382 switch (S.getMethodFamily()) {
1383 case OMF_alloc:
1384 case OMF_new:
1385 case OMF_copy:
1386 case OMF_mutableCopy:
1387 ResultEff = RetEffect::MakeOwned(RetEffect::CF, true);
1388 break;
1389 default:
1390 ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1391 break;
1392 }
1393 } else {
1394 ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1395 }
1396 }
1397 break;
1398 case OMF_init:
1399 ResultEff = ObjCInitRetE;
1400 ReceiverEff = DecRefMsg;
1401 break;
1402 case OMF_alloc:
1403 case OMF_new:
1404 case OMF_copy:
1405 case OMF_mutableCopy:
1406 if (cocoa::isCocoaObjectRef(RetTy))
1407 ResultEff = ObjCAllocRetE;
1408 else if (coreFoundation::isCFObjectRef(RetTy))
1409 ResultEff = RetEffect::MakeOwned(RetEffect::CF, true);
1410 break;
1411 case OMF_autorelease:
1412 ReceiverEff = Autorelease;
1413 break;
1414 case OMF_retain:
1415 ReceiverEff = IncRefMsg;
1416 break;
1417 case OMF_release:
1418 ReceiverEff = DecRefMsg;
1419 break;
1420 case OMF_dealloc:
1421 ReceiverEff = Dealloc;
1422 break;
1423 case OMF_self:
1424 // -self is handled specially by the ExprEngine to propagate the receiver.
1425 break;
1426 case OMF_retainCount:
1427 case OMF_finalize:
1428 // These methods don't return objects.
1429 break;
1430 }
Mike Stump1eb44332009-09-09 15:08:12 +00001431
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001432 // If one of the arguments in the selector has the keyword 'delegate' we
1433 // should stop tracking the reference count for the receiver. This is
1434 // because the reference count is quite possibly handled by a delegate
1435 // method.
1436 if (S.isKeywordSelector()) {
Jordan Rose50571a92012-06-15 18:19:52 +00001437 for (unsigned i = 0, e = S.getNumArgs(); i != e; ++i) {
1438 StringRef Slot = S.getNameForSlot(i);
1439 if (Slot.substr(Slot.size() - 8).equals_lower("delegate")) {
1440 if (ResultEff == ObjCInitRetE)
Anna Zaks554067f2012-08-29 23:23:43 +00001441 ResultEff = RetEffect::MakeNoRetHard();
Jordan Rose50571a92012-06-15 18:19:52 +00001442 else
Anna Zaks554067f2012-08-29 23:23:43 +00001443 ReceiverEff = StopTrackingHard;
Jordan Rose50571a92012-06-15 18:19:52 +00001444 }
1445 }
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001446 }
Mike Stump1eb44332009-09-09 15:08:12 +00001447
Jordy Rosee921b1a2012-03-17 19:53:04 +00001448 if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing &&
1449 ResultEff.getKind() == RetEffect::NoRet)
Ted Kremenek93edbc52011-10-05 23:54:29 +00001450 return getDefaultSummary();
Mike Stump1eb44332009-09-09 15:08:12 +00001451
Jordy Rosee921b1a2012-03-17 19:53:04 +00001452 return getPersistentSummary(ResultEff, ReceiverEff, MayEscape);
Ted Kremenek250b1fa2009-04-23 23:08:22 +00001453}
1454
Ted Kremenek93edbc52011-10-05 23:54:29 +00001455const RetainSummary *
Jordan Rosecde8cdb2012-07-02 19:27:56 +00001456RetainSummaryManager::getInstanceMethodSummary(const ObjCMethodCall &Msg,
Jordan Rose4531b7d2012-07-02 19:27:43 +00001457 ProgramStateRef State) {
1458 const ObjCInterfaceDecl *ReceiverClass = 0;
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001459
Jordan Rose4531b7d2012-07-02 19:27:43 +00001460 // We do better tracking of the type of the object than the core ExprEngine.
1461 // See if we have its type in our private state.
1462 // FIXME: Eventually replace the use of state->get<RefBindings> with
1463 // a generic API for reasoning about the Objective-C types of symbolic
1464 // objects.
1465 SVal ReceiverV = Msg.getReceiverSVal();
1466 if (SymbolRef Sym = ReceiverV.getAsLocSymbol())
Anna Zaks8d6b43c2012-08-14 00:36:15 +00001467 if (const RefVal *T = getRefBinding(State, Sym))
Douglas Gregor04badcf2010-04-21 00:45:42 +00001468 if (const ObjCObjectPointerType *PT =
Jordan Rose4531b7d2012-07-02 19:27:43 +00001469 T->getType()->getAs<ObjCObjectPointerType>())
1470 ReceiverClass = PT->getInterfaceDecl();
1471
1472 // If we don't know what kind of object this is, fall back to its static type.
1473 if (!ReceiverClass)
1474 ReceiverClass = Msg.getReceiverInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00001475
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001476 // FIXME: The receiver could be a reference to a class, meaning that
1477 // we should use the class method.
Jordan Rose4531b7d2012-07-02 19:27:43 +00001478 // id x = [NSObject class];
1479 // [x performSelector:... withObject:... afterDelay:...];
1480 Selector S = Msg.getSelector();
1481 const ObjCMethodDecl *Method = Msg.getDecl();
1482 if (!Method && ReceiverClass)
1483 Method = ReceiverClass->getInstanceMethod(S);
1484
1485 return getMethodSummary(S, ReceiverClass, Method, Msg.getResultType(),
1486 ObjCMethodSummaries);
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001487}
1488
Ted Kremenek93edbc52011-10-05 23:54:29 +00001489const RetainSummary *
Jordan Rose4531b7d2012-07-02 19:27:43 +00001490RetainSummaryManager::getMethodSummary(Selector S, const ObjCInterfaceDecl *ID,
Jordy Rosef3aae582012-03-17 21:13:07 +00001491 const ObjCMethodDecl *MD, QualType RetTy,
1492 ObjCMethodSummariesTy &CachedSummaries) {
Ted Kremenek1bffd742008-05-06 15:44:25 +00001493
Ted Kremenek8711c032009-04-29 05:04:30 +00001494 // Look up a summary in our summary cache.
Jordan Rose4531b7d2012-07-02 19:27:43 +00001495 const RetainSummary *Summ = CachedSummaries.find(ID, S);
Mike Stump1eb44332009-09-09 15:08:12 +00001496
Ted Kremenek614cc542009-07-21 23:27:57 +00001497 if (!Summ) {
Jordy Rosef3aae582012-03-17 21:13:07 +00001498 Summ = getStandardMethodSummary(MD, S, RetTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001499
Ted Kremenek614cc542009-07-21 23:27:57 +00001500 // Annotations override defaults.
Jordy Rose4df54fe2011-08-23 04:27:15 +00001501 updateSummaryFromAnnotations(Summ, MD);
Mike Stump1eb44332009-09-09 15:08:12 +00001502
Ted Kremenek614cc542009-07-21 23:27:57 +00001503 // Memoize the summary.
Jordan Rose4531b7d2012-07-02 19:27:43 +00001504 CachedSummaries[ObjCSummaryKey(ID, S)] = Summ;
Ted Kremenek614cc542009-07-21 23:27:57 +00001505 }
Mike Stump1eb44332009-09-09 15:08:12 +00001506
Ted Kremeneke87450e2009-04-23 19:11:35 +00001507 return Summ;
Ted Kremenekc8395602008-05-06 21:26:51 +00001508}
1509
Mike Stump1eb44332009-09-09 15:08:12 +00001510void RetainSummaryManager::InitializeClassMethodSummaries() {
Ted Kremenekec315332009-05-07 23:40:42 +00001511 assert(ScratchArgs.isEmpty());
Mike Stump1eb44332009-09-09 15:08:12 +00001512 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek6fe2b7a2009-10-15 22:25:12 +00001513 addClassMethSummary("NSAssertionHandler", "currentHandler",
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001514 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Mike Stump1eb44332009-09-09 15:08:12 +00001515
Ted Kremenek6d348932008-10-21 15:53:15 +00001516 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001517 ScratchArgs = AF.add(ScratchArgs, 0, Autorelease);
Ted Kremenek6fe2b7a2009-10-15 22:25:12 +00001518 addClassMethSummary("NSAutoreleasePool", "addObject",
1519 getPersistentSummary(RetEffect::MakeNoRet(),
1520 DoNothing, Autorelease));
Ted Kremenek9c32d082008-05-06 00:30:21 +00001521}
1522
Ted Kremenek1f180c32008-06-23 22:21:20 +00001523void RetainSummaryManager::InitializeMethodSummaries() {
Mike Stump1eb44332009-09-09 15:08:12 +00001524
1525 assert (ScratchArgs.isEmpty());
1526
Ted Kremenekc8395602008-05-06 21:26:51 +00001527 // Create the "init" selector. It just acts as a pass-through for the
1528 // receiver.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001529 const RetainSummary *InitSumm = getPersistentSummary(ObjCInitRetE, DecRefMsg);
Ted Kremenekac02f202009-08-20 05:13:36 +00001530 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
1531
1532 // awakeAfterUsingCoder: behaves basically like an 'init' method. It
1533 // claims the receiver and returns a retained object.
1534 addNSObjectMethSummary(GetUnarySelector("awakeAfterUsingCoder", Ctx),
1535 InitSumm);
Mike Stump1eb44332009-09-09 15:08:12 +00001536
Ted Kremenekc8395602008-05-06 21:26:51 +00001537 // The next methods are allocators.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001538 const RetainSummary *AllocSumm = getPersistentSummary(ObjCAllocRetE);
1539 const RetainSummary *CFAllocSumm =
Ted Kremeneka834fb42009-08-28 19:52:12 +00001540 getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Mike Stump1eb44332009-09-09 15:08:12 +00001541
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001542 // Create the "retain" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001543 RetEffect NoRet = RetEffect::MakeNoRet();
Ted Kremenek93edbc52011-10-05 23:54:29 +00001544 const RetainSummary *Summ = getPersistentSummary(NoRet, IncRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001545 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001546
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001547 // Create the "release" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001548 Summ = getPersistentSummary(NoRet, DecRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001549 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001550
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001551 // Create the -dealloc summary.
Jordy Rose500abad2011-08-21 19:41:36 +00001552 Summ = getPersistentSummary(NoRet, Dealloc);
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001553 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001554
1555 // Create the "autorelease" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001556 Summ = getPersistentSummary(NoRet, Autorelease);
Ted Kremenek553cf182008-06-25 21:21:56 +00001557 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001558
Mike Stump1eb44332009-09-09 15:08:12 +00001559 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremenek89e202d2009-02-23 02:51:29 +00001560 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1561 // self-own themselves. However, they only do this once they are displayed.
1562 // Thus, we need to track an NSWindow's display status.
1563 // This is tracked in <rdar://problem/6062711>.
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +00001564 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001565 const RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenek78a35a32009-05-12 20:06:54 +00001566 StopTracking,
1567 StopTracking);
Mike Stump1eb44332009-09-09 15:08:12 +00001568
Ted Kremenek99d02692009-04-03 19:02:51 +00001569 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1570
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001571 // For NSPanel (which subclasses NSWindow), allocated objects are not
1572 // self-owned.
Ted Kremenek99d02692009-04-03 19:02:51 +00001573 // FIXME: For now we don't track NSPanels. object for the same reason
1574 // as for NSWindow objects.
1575 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
Mike Stump1eb44332009-09-09 15:08:12 +00001576
Jordan Rosee36d81b2013-01-31 22:06:02 +00001577 // Don't track allocated autorelease pools, as it is okay to prematurely
Ted Kremenekba67f6a2009-05-18 23:14:34 +00001578 // exit a method.
1579 addClassMethSummary("NSAutoreleasePool", "alloc", NoTrackYet);
Ted Kremeneka9797122012-02-18 21:37:48 +00001580 addClassMethSummary("NSAutoreleasePool", "allocWithZone", NoTrackYet, false);
Jordan Rosee36d81b2013-01-31 22:06:02 +00001581 addClassMethSummary("NSAutoreleasePool", "new", NoTrackYet);
Ted Kremenek553cf182008-06-25 21:21:56 +00001582
Ted Kremenek767d6492009-05-20 22:39:57 +00001583 // Create summaries QCRenderer/QCView -createSnapShotImageOfType:
1584 addInstMethSummary("QCRenderer", AllocSumm,
1585 "createSnapshotImageOfType", NULL);
1586 addInstMethSummary("QCView", AllocSumm,
1587 "createSnapshotImageOfType", NULL);
1588
Ted Kremenek211a9c62009-06-15 20:58:58 +00001589 // Create summaries for CIContext, 'createCGImage' and
Ted Kremeneka834fb42009-08-28 19:52:12 +00001590 // 'createCGLayerWithSize'. These objects are CF objects, and are not
1591 // automatically garbage collected.
1592 addInstMethSummary("CIContext", CFAllocSumm,
Ted Kremenek767d6492009-05-20 22:39:57 +00001593 "createCGImage", "fromRect", NULL);
Ted Kremeneka834fb42009-08-28 19:52:12 +00001594 addInstMethSummary("CIContext", CFAllocSumm,
Mike Stump1eb44332009-09-09 15:08:12 +00001595 "createCGImage", "fromRect", "format", "colorSpace", NULL);
Ted Kremeneka834fb42009-08-28 19:52:12 +00001596 addInstMethSummary("CIContext", CFAllocSumm, "createCGLayerWithSize",
Ted Kremenek211a9c62009-06-15 20:58:58 +00001597 "info", NULL);
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001598}
1599
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001600//===----------------------------------------------------------------------===//
Ted Kremenekc887d132009-04-29 18:50:19 +00001601// Error reporting.
1602//===----------------------------------------------------------------------===//
Ted Kremenekc887d132009-04-29 18:50:19 +00001603namespace {
Jordy Roseec9ef852011-08-23 20:55:48 +00001604 typedef llvm::DenseMap<const ExplodedNode *, const RetainSummary *>
1605 SummaryLogTy;
1606
Ted Kremenekc887d132009-04-29 18:50:19 +00001607 //===-------------===//
1608 // Bug Descriptions. //
Mike Stump1eb44332009-09-09 15:08:12 +00001609 //===-------------===//
1610
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001611 class CFRefBug : public BugType {
Ted Kremenekc887d132009-04-29 18:50:19 +00001612 protected:
Jordy Rose35c86952011-08-24 05:47:39 +00001613 CFRefBug(StringRef name)
Ted Kremenek6fd45052012-04-05 20:43:28 +00001614 : BugType(name, categories::MemoryCoreFoundationObjectiveC) {}
Ted Kremenekc887d132009-04-29 18:50:19 +00001615 public:
Mike Stump1eb44332009-09-09 15:08:12 +00001616
Ted Kremenekc887d132009-04-29 18:50:19 +00001617 // FIXME: Eventually remove.
Jordy Rose35c86952011-08-24 05:47:39 +00001618 virtual const char *getDescription() const = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001619
Ted Kremenekc887d132009-04-29 18:50:19 +00001620 virtual bool isLeak() const { return false; }
1621 };
Mike Stump1eb44332009-09-09 15:08:12 +00001622
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001623 class UseAfterRelease : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001624 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001625 UseAfterRelease() : CFRefBug("Use-after-release") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001626
Jordy Rose35c86952011-08-24 05:47:39 +00001627 const char *getDescription() const {
Ted Kremenekc887d132009-04-29 18:50:19 +00001628 return "Reference-counted object is used after it is released";
Mike Stump1eb44332009-09-09 15:08:12 +00001629 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001630 };
Mike Stump1eb44332009-09-09 15:08:12 +00001631
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001632 class BadRelease : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001633 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001634 BadRelease() : CFRefBug("Bad release") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001635
Jordy Rose35c86952011-08-24 05:47:39 +00001636 const char *getDescription() const {
Ted Kremenekbb206fd2009-10-01 17:31:50 +00001637 return "Incorrect decrement of the reference count of an object that is "
1638 "not owned at this point by the caller";
Ted Kremenekc887d132009-04-29 18:50:19 +00001639 }
1640 };
Mike Stump1eb44332009-09-09 15:08:12 +00001641
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001642 class DeallocGC : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001643 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001644 DeallocGC()
1645 : CFRefBug("-dealloc called while using garbage collection") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001646
Ted Kremenekc887d132009-04-29 18:50:19 +00001647 const char *getDescription() const {
Ted Kremenek369de562009-05-09 00:10:05 +00001648 return "-dealloc called while using garbage collection";
Ted Kremenekc887d132009-04-29 18:50:19 +00001649 }
1650 };
Mike Stump1eb44332009-09-09 15:08:12 +00001651
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001652 class DeallocNotOwned : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001653 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001654 DeallocNotOwned()
1655 : CFRefBug("-dealloc sent to non-exclusively owned object") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001656
Ted Kremenekc887d132009-04-29 18:50:19 +00001657 const char *getDescription() const {
1658 return "-dealloc sent to object that may be referenced elsewhere";
1659 }
Mike Stump1eb44332009-09-09 15:08:12 +00001660 };
1661
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001662 class OverAutorelease : public CFRefBug {
Ted Kremenek369de562009-05-09 00:10:05 +00001663 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001664 OverAutorelease()
1665 : CFRefBug("Object sent -autorelease too many times") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001666
Ted Kremenek369de562009-05-09 00:10:05 +00001667 const char *getDescription() const {
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001668 return "Object sent -autorelease too many times";
Ted Kremenek369de562009-05-09 00:10:05 +00001669 }
1670 };
Mike Stump1eb44332009-09-09 15:08:12 +00001671
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001672 class ReturnedNotOwnedForOwned : public CFRefBug {
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001673 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001674 ReturnedNotOwnedForOwned()
1675 : CFRefBug("Method should return an owned object") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001676
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001677 const char *getDescription() const {
Jordy Rose5b5402b2011-07-15 22:17:54 +00001678 return "Object with a +0 retain count returned to caller where a +1 "
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001679 "(owning) retain count is expected";
1680 }
1681 };
Mike Stump1eb44332009-09-09 15:08:12 +00001682
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001683 class Leak : public CFRefBug {
Benjamin Kramerfacde172012-06-06 17:32:50 +00001684 public:
1685 Leak(StringRef name)
1686 : CFRefBug(name) {
Jordy Rosedb92bb62011-08-25 01:14:38 +00001687 // Leaks should not be reported if they are post-dominated by a sink.
1688 setSuppressOnSink(true);
1689 }
Mike Stump1eb44332009-09-09 15:08:12 +00001690
Jordy Rose35c86952011-08-24 05:47:39 +00001691 const char *getDescription() const { return ""; }
Mike Stump1eb44332009-09-09 15:08:12 +00001692
Ted Kremenekc887d132009-04-29 18:50:19 +00001693 bool isLeak() const { return true; }
1694 };
Mike Stump1eb44332009-09-09 15:08:12 +00001695
Ted Kremenekc887d132009-04-29 18:50:19 +00001696 //===---------===//
1697 // Bug Reports. //
1698 //===---------===//
Mike Stump1eb44332009-09-09 15:08:12 +00001699
Jordy Rose01153492012-03-24 02:45:35 +00001700 class CFRefReportVisitor : public BugReporterVisitorImpl<CFRefReportVisitor> {
Anna Zaks23f395e2011-08-20 01:27:22 +00001701 protected:
Anna Zaksdc757b02011-08-19 23:21:56 +00001702 SymbolRef Sym;
Jordy Roseec9ef852011-08-23 20:55:48 +00001703 const SummaryLogTy &SummaryLog;
Jordy Rose35c86952011-08-24 05:47:39 +00001704 bool GCEnabled;
Anna Zaks23f395e2011-08-20 01:27:22 +00001705
Anna Zaksdc757b02011-08-19 23:21:56 +00001706 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001707 CFRefReportVisitor(SymbolRef sym, bool gcEnabled, const SummaryLogTy &log)
1708 : Sym(sym), SummaryLog(log), GCEnabled(gcEnabled) {}
Anna Zaksdc757b02011-08-19 23:21:56 +00001709
Anna Zaks23f395e2011-08-20 01:27:22 +00001710 virtual void Profile(llvm::FoldingSetNodeID &ID) const {
Anna Zaksdc757b02011-08-19 23:21:56 +00001711 static int x = 0;
1712 ID.AddPointer(&x);
1713 ID.AddPointer(Sym);
1714 }
1715
Anna Zaks23f395e2011-08-20 01:27:22 +00001716 virtual PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
1717 const ExplodedNode *PrevN,
1718 BugReporterContext &BRC,
1719 BugReport &BR);
1720
1721 virtual PathDiagnosticPiece *getEndPath(BugReporterContext &BRC,
1722 const ExplodedNode *N,
1723 BugReport &BR);
1724 };
1725
1726 class CFRefLeakReportVisitor : public CFRefReportVisitor {
1727 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001728 CFRefLeakReportVisitor(SymbolRef sym, bool GCEnabled,
Jordy Roseec9ef852011-08-23 20:55:48 +00001729 const SummaryLogTy &log)
Jordy Rose35c86952011-08-24 05:47:39 +00001730 : CFRefReportVisitor(sym, GCEnabled, log) {}
Anna Zaks23f395e2011-08-20 01:27:22 +00001731
1732 PathDiagnosticPiece *getEndPath(BugReporterContext &BRC,
1733 const ExplodedNode *N,
1734 BugReport &BR);
Jordy Rose01153492012-03-24 02:45:35 +00001735
1736 virtual BugReporterVisitor *clone() const {
1737 // The curiously-recurring template pattern only works for one level of
1738 // subclassing. Rather than make a new template base for
1739 // CFRefReportVisitor, we simply override clone() to do the right thing.
1740 // This could be trouble someday if BugReporterVisitorImpl is ever
1741 // used for something else besides a convenient implementation of clone().
1742 return new CFRefLeakReportVisitor(*this);
1743 }
Anna Zaksdc757b02011-08-19 23:21:56 +00001744 };
1745
Anna Zakse172e8b2011-08-17 23:00:25 +00001746 class CFRefReport : public BugReport {
Jordy Rose20589562011-08-24 22:39:09 +00001747 void addGCModeDescription(const LangOptions &LOpts, bool GCEnabled);
Jordy Rose35c86952011-08-24 05:47:39 +00001748
Ted Kremenekc887d132009-04-29 18:50:19 +00001749 public:
Jordy Rose20589562011-08-24 22:39:09 +00001750 CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1751 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1752 bool registerVisitor = true)
Anna Zaksedf4dae2011-08-22 18:54:07 +00001753 : BugReport(D, D.getDescription(), n) {
Anna Zaks23f395e2011-08-20 01:27:22 +00001754 if (registerVisitor)
Jordy Rose20589562011-08-24 22:39:09 +00001755 addVisitor(new CFRefReportVisitor(sym, GCEnabled, Log));
1756 addGCModeDescription(LOpts, GCEnabled);
Anna Zaksdc757b02011-08-19 23:21:56 +00001757 }
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001758
Jordy Rose20589562011-08-24 22:39:09 +00001759 CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1760 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1761 StringRef endText)
Anna Zaksedf4dae2011-08-22 18:54:07 +00001762 : BugReport(D, D.getDescription(), endText, n) {
Jordy Rose20589562011-08-24 22:39:09 +00001763 addVisitor(new CFRefReportVisitor(sym, GCEnabled, Log));
1764 addGCModeDescription(LOpts, GCEnabled);
Anna Zaksdc757b02011-08-19 23:21:56 +00001765 }
Mike Stump1eb44332009-09-09 15:08:12 +00001766
Anna Zakse172e8b2011-08-17 23:00:25 +00001767 virtual std::pair<ranges_iterator, ranges_iterator> getRanges() {
Anna Zaksedf4dae2011-08-22 18:54:07 +00001768 const CFRefBug& BugTy = static_cast<CFRefBug&>(getBugType());
1769 if (!BugTy.isLeak())
Anna Zakse172e8b2011-08-17 23:00:25 +00001770 return BugReport::getRanges();
Ted Kremenekc887d132009-04-29 18:50:19 +00001771 else
Argyrios Kyrtzidis640ccf02010-12-04 01:12:15 +00001772 return std::make_pair(ranges_iterator(), ranges_iterator());
Ted Kremenekc887d132009-04-29 18:50:19 +00001773 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001774 };
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001775
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001776 class CFRefLeakReport : public CFRefReport {
Ted Kremenekc887d132009-04-29 18:50:19 +00001777 const MemRegion* AllocBinding;
1778 public:
Jordy Rose20589562011-08-24 22:39:09 +00001779 CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1780 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
Ted Kremenek08a838d2013-04-16 21:44:22 +00001781 CheckerContext &Ctx,
1782 bool IncludeAllocationLine);
Mike Stump1eb44332009-09-09 15:08:12 +00001783
Anna Zaks590dd8e2011-09-20 21:38:35 +00001784 PathDiagnosticLocation getLocation(const SourceManager &SM) const {
1785 assert(Location.isValid());
1786 return Location;
1787 }
Mike Stump1eb44332009-09-09 15:08:12 +00001788 };
Ted Kremenekc887d132009-04-29 18:50:19 +00001789} // end anonymous namespace
1790
Jordy Rose20589562011-08-24 22:39:09 +00001791void CFRefReport::addGCModeDescription(const LangOptions &LOpts,
1792 bool GCEnabled) {
Jordy Rosef95b19d2011-08-24 20:38:42 +00001793 const char *GCModeDescription = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001794
Douglas Gregore289d812011-09-13 17:21:33 +00001795 switch (LOpts.getGC()) {
Anna Zaks7f2531c2011-08-22 20:31:28 +00001796 case LangOptions::GCOnly:
Jordy Rose20589562011-08-24 22:39:09 +00001797 assert(GCEnabled);
Jordy Rose35c86952011-08-24 05:47:39 +00001798 GCModeDescription = "Code is compiled to only use garbage collection";
1799 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001800
Anna Zaks7f2531c2011-08-22 20:31:28 +00001801 case LangOptions::NonGC:
Jordy Rose20589562011-08-24 22:39:09 +00001802 assert(!GCEnabled);
Jordy Rose35c86952011-08-24 05:47:39 +00001803 GCModeDescription = "Code is compiled to use reference counts";
1804 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001805
Anna Zaks7f2531c2011-08-22 20:31:28 +00001806 case LangOptions::HybridGC:
Jordy Rose20589562011-08-24 22:39:09 +00001807 if (GCEnabled) {
Jordy Rose35c86952011-08-24 05:47:39 +00001808 GCModeDescription = "Code is compiled to use either garbage collection "
1809 "(GC) or reference counts (non-GC). The bug occurs "
1810 "with GC enabled";
1811 break;
1812 } else {
1813 GCModeDescription = "Code is compiled to use either garbage collection "
1814 "(GC) or reference counts (non-GC). The bug occurs "
1815 "in non-GC mode";
1816 break;
Anna Zaks7f2531c2011-08-22 20:31:28 +00001817 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001818 }
Jordy Rose35c86952011-08-24 05:47:39 +00001819
Jordy Rosef95b19d2011-08-24 20:38:42 +00001820 assert(GCModeDescription && "invalid/unknown GC mode");
Jordy Rose35c86952011-08-24 05:47:39 +00001821 addExtraText(GCModeDescription);
Ted Kremenekc887d132009-04-29 18:50:19 +00001822}
1823
Jordy Rose910c4052011-09-02 06:44:22 +00001824// FIXME: This should be a method on SmallVector.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001825static inline bool contains(const SmallVectorImpl<ArgEffect>& V,
Ted Kremenekc887d132009-04-29 18:50:19 +00001826 ArgEffect X) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001827 for (SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
Ted Kremenekc887d132009-04-29 18:50:19 +00001828 I!=E; ++I)
1829 if (*I == X) return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001830
Ted Kremenekc887d132009-04-29 18:50:19 +00001831 return false;
1832}
1833
Jordy Rose70fdbc32012-05-12 05:10:43 +00001834static bool isNumericLiteralExpression(const Expr *E) {
1835 // FIXME: This set of cases was copied from SemaExprObjC.
1836 return isa<IntegerLiteral>(E) ||
1837 isa<CharacterLiteral>(E) ||
1838 isa<FloatingLiteral>(E) ||
1839 isa<ObjCBoolLiteralExpr>(E) ||
1840 isa<CXXBoolLiteralExpr>(E);
1841}
1842
Anna Zaksdc757b02011-08-19 23:21:56 +00001843PathDiagnosticPiece *CFRefReportVisitor::VisitNode(const ExplodedNode *N,
1844 const ExplodedNode *PrevN,
1845 BugReporterContext &BRC,
1846 BugReport &BR) {
Jordan Rose28038f32012-07-10 22:07:42 +00001847 // FIXME: We will eventually need to handle non-statement-based events
1848 // (__attribute__((cleanup))).
David Blaikie7a95de62013-02-21 22:23:56 +00001849 if (!N->getLocation().getAs<StmtPoint>())
Ted Kremenek2033a952009-05-13 07:12:33 +00001850 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001851
Ted Kremenek8966bc12009-05-06 21:39:49 +00001852 // Check if the type state has changed.
Ted Kremenek8bef8232012-01-26 21:29:00 +00001853 ProgramStateRef PrevSt = PrevN->getState();
1854 ProgramStateRef CurrSt = N->getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001855 const LocationContext *LCtx = N->getLocationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00001856
Anna Zaks8d6b43c2012-08-14 00:36:15 +00001857 const RefVal* CurrT = getRefBinding(CurrSt, Sym);
Ted Kremenekc887d132009-04-29 18:50:19 +00001858 if (!CurrT) return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001859
Ted Kremenekb65be702009-06-18 01:23:53 +00001860 const RefVal &CurrV = *CurrT;
Anna Zaks8d6b43c2012-08-14 00:36:15 +00001861 const RefVal *PrevT = getRefBinding(PrevSt, Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00001862
Ted Kremenekc887d132009-04-29 18:50:19 +00001863 // Create a string buffer to constain all the useful things we want
1864 // to tell the user.
1865 std::string sbuf;
1866 llvm::raw_string_ostream os(sbuf);
Mike Stump1eb44332009-09-09 15:08:12 +00001867
Ted Kremenekc887d132009-04-29 18:50:19 +00001868 // This is the allocation site since the previous node had no bindings
1869 // for this symbol.
1870 if (!PrevT) {
David Blaikie7a95de62013-02-21 22:23:56 +00001871 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
Mike Stump1eb44332009-09-09 15:08:12 +00001872
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001873 if (isa<ObjCArrayLiteral>(S)) {
1874 os << "NSArray literal is an object with a +0 retain count";
Mike Stump1eb44332009-09-09 15:08:12 +00001875 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001876 else if (isa<ObjCDictionaryLiteral>(S)) {
1877 os << "NSDictionary literal is an object with a +0 retain count";
Ted Kremenekc887d132009-04-29 18:50:19 +00001878 }
Jordy Rose70fdbc32012-05-12 05:10:43 +00001879 else if (const ObjCBoxedExpr *BL = dyn_cast<ObjCBoxedExpr>(S)) {
1880 if (isNumericLiteralExpression(BL->getSubExpr()))
1881 os << "NSNumber literal is an object with a +0 retain count";
1882 else {
1883 const ObjCInterfaceDecl *BoxClass = 0;
1884 if (const ObjCMethodDecl *Method = BL->getBoxingMethod())
1885 BoxClass = Method->getClassInterface();
1886
1887 // We should always be able to find the boxing class interface,
1888 // but consider this future-proofing.
1889 if (BoxClass)
1890 os << *BoxClass << " b";
1891 else
1892 os << "B";
1893
1894 os << "oxed expression produces an object with a +0 retain count";
1895 }
1896 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001897 else {
1898 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
1899 // Get the name of the callee (if it is available).
1900 SVal X = CurrSt->getSValAsScalarOrLoc(CE->getCallee(), LCtx);
1901 if (const FunctionDecl *FD = X.getAsFunctionDecl())
1902 os << "Call to function '" << *FD << '\'';
1903 else
1904 os << "function call";
Ted Kremenekc887d132009-04-29 18:50:19 +00001905 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001906 else {
Jordan Rose8919e682012-07-18 21:59:51 +00001907 assert(isa<ObjCMessageExpr>(S));
Jordan Rosed563d3f2012-07-30 20:22:09 +00001908 CallEventManager &Mgr = CurrSt->getStateManager().getCallEventManager();
1909 CallEventRef<ObjCMethodCall> Call
1910 = Mgr.getObjCMethodCall(cast<ObjCMessageExpr>(S), CurrSt, LCtx);
1911
1912 switch (Call->getMessageKind()) {
Jordan Rose8919e682012-07-18 21:59:51 +00001913 case OCM_Message:
1914 os << "Method";
1915 break;
1916 case OCM_PropertyAccess:
1917 os << "Property";
1918 break;
1919 case OCM_Subscript:
1920 os << "Subscript";
1921 break;
1922 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001923 }
1924
1925 if (CurrV.getObjKind() == RetEffect::CF) {
1926 os << " returns a Core Foundation object with a ";
1927 }
1928 else {
1929 assert (CurrV.getObjKind() == RetEffect::ObjC);
1930 os << " returns an Objective-C object with a ";
1931 }
1932
1933 if (CurrV.isOwned()) {
1934 os << "+1 retain count";
1935
1936 if (GCEnabled) {
1937 assert(CurrV.getObjKind() == RetEffect::CF);
1938 os << ". "
1939 "Core Foundation objects are not automatically garbage collected.";
1940 }
1941 }
1942 else {
1943 assert (CurrV.isNotOwned());
1944 os << "+0 retain count";
1945 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001946 }
Mike Stump1eb44332009-09-09 15:08:12 +00001947
Anna Zaks220ac8c2011-09-15 01:08:34 +00001948 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
1949 N->getLocationContext());
Ted Kremenekc887d132009-04-29 18:50:19 +00001950 return new PathDiagnosticEventPiece(Pos, os.str());
1951 }
Mike Stump1eb44332009-09-09 15:08:12 +00001952
Ted Kremenekc887d132009-04-29 18:50:19 +00001953 // Gather up the effects that were performed on the object at this
1954 // program point
Chris Lattner5f9e2722011-07-23 10:55:15 +00001955 SmallVector<ArgEffect, 2> AEffects;
Mike Stump1eb44332009-09-09 15:08:12 +00001956
Jordy Roseec9ef852011-08-23 20:55:48 +00001957 const ExplodedNode *OrigNode = BRC.getNodeResolver().getOriginalNode(N);
1958 if (const RetainSummary *Summ = SummaryLog.lookup(OrigNode)) {
Ted Kremenekc887d132009-04-29 18:50:19 +00001959 // We only have summaries attached to nodes after evaluating CallExpr and
1960 // ObjCMessageExprs.
David Blaikie7a95de62013-02-21 22:23:56 +00001961 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
Mike Stump1eb44332009-09-09 15:08:12 +00001962
Ted Kremenek5f85e172009-07-22 22:35:28 +00001963 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
Ted Kremenekc887d132009-04-29 18:50:19 +00001964 // Iterate through the parameter expressions and see if the symbol
1965 // was ever passed as an argument.
1966 unsigned i = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001967
Ted Kremenek5f85e172009-07-22 22:35:28 +00001968 for (CallExpr::const_arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
Ted Kremenekc887d132009-04-29 18:50:19 +00001969 AI!=AE; ++AI, ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00001970
Ted Kremenekc887d132009-04-29 18:50:19 +00001971 // Retrieve the value of the argument. Is it the symbol
1972 // we are interested in?
Ted Kremenek5eca4822012-01-06 22:09:28 +00001973 if (CurrSt->getSValAsScalarOrLoc(*AI, LCtx).getAsLocSymbol() != Sym)
Ted Kremenekc887d132009-04-29 18:50:19 +00001974 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001975
Ted Kremenekc887d132009-04-29 18:50:19 +00001976 // We have an argument. Get the effect!
1977 AEffects.push_back(Summ->getArg(i));
1978 }
1979 }
Mike Stump1eb44332009-09-09 15:08:12 +00001980 else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00001981 if (const Expr *receiver = ME->getInstanceReceiver())
Ted Kremenek5eca4822012-01-06 22:09:28 +00001982 if (CurrSt->getSValAsScalarOrLoc(receiver, LCtx)
1983 .getAsLocSymbol() == Sym) {
Ted Kremenekc887d132009-04-29 18:50:19 +00001984 // The symbol we are tracking is the receiver.
1985 AEffects.push_back(Summ->getReceiverEffect());
1986 }
1987 }
1988 }
Mike Stump1eb44332009-09-09 15:08:12 +00001989
Ted Kremenekc887d132009-04-29 18:50:19 +00001990 do {
1991 // Get the previous type state.
1992 RefVal PrevV = *PrevT;
Mike Stump1eb44332009-09-09 15:08:12 +00001993
Ted Kremenekc887d132009-04-29 18:50:19 +00001994 // Specially handle -dealloc.
Jordy Rose35c86952011-08-24 05:47:39 +00001995 if (!GCEnabled && contains(AEffects, Dealloc)) {
Ted Kremenekc887d132009-04-29 18:50:19 +00001996 // Determine if the object's reference count was pushed to zero.
1997 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
1998 // We may not have transitioned to 'release' if we hit an error.
1999 // This case is handled elsewhere.
2000 if (CurrV.getKind() == RefVal::Released) {
Ted Kremenekf21332e2009-05-08 20:01:42 +00002001 assert(CurrV.getCombinedCounts() == 0);
Ted Kremenekc887d132009-04-29 18:50:19 +00002002 os << "Object released by directly sending the '-dealloc' message";
2003 break;
2004 }
2005 }
Mike Stump1eb44332009-09-09 15:08:12 +00002006
Ted Kremenekc887d132009-04-29 18:50:19 +00002007 // Specially handle CFMakeCollectable and friends.
2008 if (contains(AEffects, MakeCollectable)) {
2009 // Get the name of the function.
David Blaikie7a95de62013-02-21 22:23:56 +00002010 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
Ted Kremenek5eca4822012-01-06 22:09:28 +00002011 SVal X =
2012 CurrSt->getSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee(), LCtx);
Ted Kremenek9c378f72011-08-12 23:37:29 +00002013 const FunctionDecl *FD = X.getAsFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002014
Jordy Rose35c86952011-08-24 05:47:39 +00002015 if (GCEnabled) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002016 // Determine if the object's reference count was pushed to zero.
2017 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
Mike Stump1eb44332009-09-09 15:08:12 +00002018
Benjamin Kramerb8989f22011-10-14 18:45:37 +00002019 os << "In GC mode a call to '" << *FD
Ted Kremenekc887d132009-04-29 18:50:19 +00002020 << "' decrements an object's retain count and registers the "
2021 "object with the garbage collector. ";
Mike Stump1eb44332009-09-09 15:08:12 +00002022
Ted Kremenekc887d132009-04-29 18:50:19 +00002023 if (CurrV.getKind() == RefVal::Released) {
2024 assert(CurrV.getCount() == 0);
2025 os << "Since it now has a 0 retain count the object can be "
2026 "automatically collected by the garbage collector.";
2027 }
2028 else
2029 os << "An object must have a 0 retain count to be garbage collected. "
2030 "After this call its retain count is +" << CurrV.getCount()
2031 << '.';
2032 }
Mike Stump1eb44332009-09-09 15:08:12 +00002033 else
Benjamin Kramerb8989f22011-10-14 18:45:37 +00002034 os << "When GC is not enabled a call to '" << *FD
Ted Kremenekc887d132009-04-29 18:50:19 +00002035 << "' has no effect on its argument.";
Mike Stump1eb44332009-09-09 15:08:12 +00002036
Ted Kremenekc887d132009-04-29 18:50:19 +00002037 // Nothing more to say.
2038 break;
2039 }
Mike Stump1eb44332009-09-09 15:08:12 +00002040
2041 // Determine if the typestate has changed.
Ted Kremenekc887d132009-04-29 18:50:19 +00002042 if (!(PrevV == CurrV))
2043 switch (CurrV.getKind()) {
2044 case RefVal::Owned:
2045 case RefVal::NotOwned:
Mike Stump1eb44332009-09-09 15:08:12 +00002046
Ted Kremenekf21332e2009-05-08 20:01:42 +00002047 if (PrevV.getCount() == CurrV.getCount()) {
2048 // Did an autorelease message get sent?
2049 if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
2050 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002051
Zhongxing Xu264e9372009-05-12 10:10:00 +00002052 assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount());
Ted Kremenekeaedfea2009-05-10 05:11:21 +00002053 os << "Object sent -autorelease message";
Ted Kremenekf21332e2009-05-08 20:01:42 +00002054 break;
2055 }
Mike Stump1eb44332009-09-09 15:08:12 +00002056
Ted Kremenekc887d132009-04-29 18:50:19 +00002057 if (PrevV.getCount() > CurrV.getCount())
2058 os << "Reference count decremented.";
2059 else
2060 os << "Reference count incremented.";
Mike Stump1eb44332009-09-09 15:08:12 +00002061
Ted Kremenekc887d132009-04-29 18:50:19 +00002062 if (unsigned Count = CurrV.getCount())
2063 os << " The object now has a +" << Count << " retain count.";
Mike Stump1eb44332009-09-09 15:08:12 +00002064
Ted Kremenekc887d132009-04-29 18:50:19 +00002065 if (PrevV.getKind() == RefVal::Released) {
Jordy Rose35c86952011-08-24 05:47:39 +00002066 assert(GCEnabled && CurrV.getCount() > 0);
Jordy Rose74b7b2b2012-03-17 05:49:15 +00002067 os << " The object is not eligible for garbage collection until "
2068 "the retain count reaches 0 again.";
Ted Kremenekc887d132009-04-29 18:50:19 +00002069 }
Mike Stump1eb44332009-09-09 15:08:12 +00002070
Ted Kremenekc887d132009-04-29 18:50:19 +00002071 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002072
Ted Kremenekc887d132009-04-29 18:50:19 +00002073 case RefVal::Released:
2074 os << "Object released.";
2075 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002076
Ted Kremenekc887d132009-04-29 18:50:19 +00002077 case RefVal::ReturnedOwned:
Jordy Rose74b7b2b2012-03-17 05:49:15 +00002078 // Autoreleases can be applied after marking a node ReturnedOwned.
2079 if (CurrV.getAutoreleaseCount())
2080 return NULL;
2081
2082 os << "Object returned to caller as an owning reference (single "
2083 "retain count transferred to caller)";
Ted Kremenekc887d132009-04-29 18:50:19 +00002084 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002085
Ted Kremenekc887d132009-04-29 18:50:19 +00002086 case RefVal::ReturnedNotOwned:
Ted Kremenekf1365462011-05-26 18:45:44 +00002087 os << "Object returned to caller with a +0 retain count";
Ted Kremenekc887d132009-04-29 18:50:19 +00002088 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002089
Ted Kremenekc887d132009-04-29 18:50:19 +00002090 default:
2091 return NULL;
2092 }
Mike Stump1eb44332009-09-09 15:08:12 +00002093
Ted Kremenekc887d132009-04-29 18:50:19 +00002094 // Emit any remaining diagnostics for the argument effects (if any).
Chris Lattner5f9e2722011-07-23 10:55:15 +00002095 for (SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
Ted Kremenekc887d132009-04-29 18:50:19 +00002096 E=AEffects.end(); I != E; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +00002097
Ted Kremenekc887d132009-04-29 18:50:19 +00002098 // A bunch of things have alternate behavior under GC.
Jordy Rose35c86952011-08-24 05:47:39 +00002099 if (GCEnabled)
Ted Kremenekc887d132009-04-29 18:50:19 +00002100 switch (*I) {
2101 default: break;
2102 case Autorelease:
2103 os << "In GC mode an 'autorelease' has no effect.";
2104 continue;
2105 case IncRefMsg:
2106 os << "In GC mode the 'retain' message has no effect.";
2107 continue;
2108 case DecRefMsg:
2109 os << "In GC mode the 'release' message has no effect.";
2110 continue;
2111 }
2112 }
Mike Stump1eb44332009-09-09 15:08:12 +00002113 } while (0);
2114
Ted Kremenekc887d132009-04-29 18:50:19 +00002115 if (os.str().empty())
2116 return 0; // We have nothing to say!
Ted Kremenek2033a952009-05-13 07:12:33 +00002117
David Blaikie7a95de62013-02-21 22:23:56 +00002118 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
Anna Zaks220ac8c2011-09-15 01:08:34 +00002119 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
2120 N->getLocationContext());
Ted Kremenek9c378f72011-08-12 23:37:29 +00002121 PathDiagnosticPiece *P = new PathDiagnosticEventPiece(Pos, os.str());
Mike Stump1eb44332009-09-09 15:08:12 +00002122
Ted Kremenekc887d132009-04-29 18:50:19 +00002123 // Add the range by scanning the children of the statement for any bindings
2124 // to Sym.
Mike Stump1eb44332009-09-09 15:08:12 +00002125 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
Ted Kremenek5f85e172009-07-22 22:35:28 +00002126 I!=E; ++I)
Ted Kremenek9c378f72011-08-12 23:37:29 +00002127 if (const Expr *Exp = dyn_cast_or_null<Expr>(*I))
Ted Kremenek5eca4822012-01-06 22:09:28 +00002128 if (CurrSt->getSValAsScalarOrLoc(Exp, LCtx).getAsLocSymbol() == Sym) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002129 P->addRange(Exp->getSourceRange());
2130 break;
2131 }
Mike Stump1eb44332009-09-09 15:08:12 +00002132
Ted Kremenekc887d132009-04-29 18:50:19 +00002133 return P;
2134}
2135
Anna Zakse7e01682012-02-28 22:39:22 +00002136// Find the first node in the current function context that referred to the
2137// tracked symbol and the memory location that value was stored to. Note, the
2138// value is only reported if the allocation occurred in the same function as
Anna Zaks7a87e522013-04-10 21:42:06 +00002139// the leak. The function can also return a location context, which should be
2140// treated as interesting.
2141struct AllocationInfo {
2142 const ExplodedNode* N;
Anna Zaksee9043b2013-04-10 22:56:30 +00002143 const MemRegion *R;
Anna Zaks7a87e522013-04-10 21:42:06 +00002144 const LocationContext *InterestingMethodContext;
Anna Zaksee9043b2013-04-10 22:56:30 +00002145 AllocationInfo(const ExplodedNode *InN,
2146 const MemRegion *InR,
Anna Zaks7a87e522013-04-10 21:42:06 +00002147 const LocationContext *InInterestingMethodContext) :
2148 N(InN), R(InR), InterestingMethodContext(InInterestingMethodContext) {}
2149};
2150
2151static AllocationInfo
Ted Kremenek18c66fd2011-08-15 22:09:50 +00002152GetAllocationSite(ProgramStateManager& StateMgr, const ExplodedNode *N,
Ted Kremenekc887d132009-04-29 18:50:19 +00002153 SymbolRef Sym) {
Anna Zaks7a87e522013-04-10 21:42:06 +00002154 const ExplodedNode *AllocationNode = N;
2155 const ExplodedNode *AllocationNodeInCurrentContext = N;
Mike Stump1eb44332009-09-09 15:08:12 +00002156 const MemRegion* FirstBinding = 0;
Anna Zakse7e01682012-02-28 22:39:22 +00002157 const LocationContext *LeakContext = N->getLocationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002158
Anna Zaks7a87e522013-04-10 21:42:06 +00002159 // The location context of the init method called on the leaked object, if
2160 // available.
2161 const LocationContext *InitMethodContext = 0;
2162
Ted Kremenekc887d132009-04-29 18:50:19 +00002163 while (N) {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002164 ProgramStateRef St = N->getState();
Anna Zaks7a87e522013-04-10 21:42:06 +00002165 const LocationContext *NContext = N->getLocationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002166
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002167 if (!getRefBinding(St, Sym))
Ted Kremenekc887d132009-04-29 18:50:19 +00002168 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002169
Anna Zaks27b867e2012-03-21 19:45:01 +00002170 StoreManager::FindUniqueBinding FB(Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002171 StateMgr.iterBindings(St, FB);
Anna Zaks7a87e522013-04-10 21:42:06 +00002172
Anna Zaks27d99dd2013-04-10 21:42:02 +00002173 if (FB) {
2174 const MemRegion *R = FB.getRegion();
Anna Zaks8cf91f72013-04-10 22:56:33 +00002175 const VarRegion *VR = R->getBaseRegion()->getAs<VarRegion>();
Anna Zaks27d99dd2013-04-10 21:42:02 +00002176 // Do not show local variables belonging to a function other than
2177 // where the error is reported.
2178 if (!VR || VR->getStackFrame() == LeakContext->getCurrentStackFrame())
Anna Zaks7a87e522013-04-10 21:42:06 +00002179 FirstBinding = R;
Anna Zaks27d99dd2013-04-10 21:42:02 +00002180 }
Mike Stump1eb44332009-09-09 15:08:12 +00002181
Anna Zaks7a87e522013-04-10 21:42:06 +00002182 // AllocationNode is the last node in which the symbol was tracked.
2183 AllocationNode = N;
2184
2185 // AllocationNodeInCurrentContext, is the last node in the current context
2186 // in which the symbol was tracked.
2187 if (NContext == LeakContext)
2188 AllocationNodeInCurrentContext = N;
2189
Anna Zaksee9043b2013-04-10 22:56:30 +00002190 // Find the last init that was called on the given symbol and store the
2191 // init method's location context.
2192 if (!InitMethodContext)
2193 if (Optional<CallEnter> CEP = N->getLocation().getAs<CallEnter>()) {
2194 const Stmt *CE = CEP->getCallExpr();
2195 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(CE)) {
2196 const Stmt *RecExpr = ME->getInstanceReceiver();
2197 if (RecExpr) {
2198 SVal RecV = St->getSVal(RecExpr, NContext);
2199 if (ME->getMethodFamily() == OMF_init && RecV.getAsSymbol() == Sym)
2200 InitMethodContext = CEP->getCalleeContext();
2201 }
2202 }
Anna Zaks7a87e522013-04-10 21:42:06 +00002203 }
Anna Zakse7e01682012-02-28 22:39:22 +00002204
Mike Stump1eb44332009-09-09 15:08:12 +00002205 N = N->pred_empty() ? NULL : *(N->pred_begin());
Ted Kremenekc887d132009-04-29 18:50:19 +00002206 }
Mike Stump1eb44332009-09-09 15:08:12 +00002207
Anna Zaks7a87e522013-04-10 21:42:06 +00002208 // If we are reporting a leak of the object that was allocated with alloc,
Anna Zaksee9043b2013-04-10 22:56:30 +00002209 // mark its init method as interesting.
Anna Zaks7a87e522013-04-10 21:42:06 +00002210 const LocationContext *InterestingMethodContext = 0;
2211 if (InitMethodContext) {
2212 const ProgramPoint AllocPP = AllocationNode->getLocation();
2213 if (Optional<StmtPoint> SP = AllocPP.getAs<StmtPoint>())
2214 if (const ObjCMessageExpr *ME = SP->getStmtAs<ObjCMessageExpr>())
2215 if (ME->getMethodFamily() == OMF_alloc)
2216 InterestingMethodContext = InitMethodContext;
2217 }
2218
Anna Zakse7e01682012-02-28 22:39:22 +00002219 // If allocation happened in a function different from the leak node context,
2220 // do not report the binding.
Ted Kremenek5a8fc882012-10-12 22:56:40 +00002221 assert(N && "Could not find allocation node");
Anna Zakse7e01682012-02-28 22:39:22 +00002222 if (N->getLocationContext() != LeakContext) {
2223 FirstBinding = 0;
2224 }
2225
Anna Zaks7a87e522013-04-10 21:42:06 +00002226 return AllocationInfo(AllocationNodeInCurrentContext,
2227 FirstBinding,
2228 InterestingMethodContext);
Ted Kremenekc887d132009-04-29 18:50:19 +00002229}
2230
2231PathDiagnosticPiece*
Anna Zaks23f395e2011-08-20 01:27:22 +00002232CFRefReportVisitor::getEndPath(BugReporterContext &BRC,
2233 const ExplodedNode *EndN,
2234 BugReport &BR) {
Ted Kremenek76aadc32012-03-09 01:13:14 +00002235 BR.markInteresting(Sym);
Anna Zaks23f395e2011-08-20 01:27:22 +00002236 return BugReporterVisitor::getDefaultEndPath(BRC, EndN, BR);
Ted Kremenekc887d132009-04-29 18:50:19 +00002237}
2238
2239PathDiagnosticPiece*
Anna Zaks23f395e2011-08-20 01:27:22 +00002240CFRefLeakReportVisitor::getEndPath(BugReporterContext &BRC,
2241 const ExplodedNode *EndN,
2242 BugReport &BR) {
Mike Stump1eb44332009-09-09 15:08:12 +00002243
Ted Kremenek8966bc12009-05-06 21:39:49 +00002244 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenekc887d132009-04-29 18:50:19 +00002245 // assigned to different variables, etc.
Ted Kremenek76aadc32012-03-09 01:13:14 +00002246 BR.markInteresting(Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002247
Ted Kremenekc887d132009-04-29 18:50:19 +00002248 // We are reporting a leak. Walk up the graph to get to the first node where
2249 // the symbol appeared, and also get the first VarDecl that tracked object
2250 // is stored to.
Anna Zaks7a87e522013-04-10 21:42:06 +00002251 AllocationInfo AllocI =
Ted Kremenekf04dced2009-05-08 23:32:51 +00002252 GetAllocationSite(BRC.getStateManager(), EndN, Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002253
Anna Zaks7a87e522013-04-10 21:42:06 +00002254 const MemRegion* FirstBinding = AllocI.R;
2255 BR.markInteresting(AllocI.InterestingMethodContext);
2256
Anna Zaks4fdf97b2011-09-15 18:56:07 +00002257 SourceManager& SM = BRC.getSourceManager();
Mike Stump1eb44332009-09-09 15:08:12 +00002258
Ted Kremenekc887d132009-04-29 18:50:19 +00002259 // Compute an actual location for the leak. Sometimes a leak doesn't
2260 // occur at an actual statement (e.g., transition between blocks; end
2261 // of function) so we need to walk the graph and compute a real location.
Ted Kremenek9c378f72011-08-12 23:37:29 +00002262 const ExplodedNode *LeakN = EndN;
Anna Zaks4fdf97b2011-09-15 18:56:07 +00002263 PathDiagnosticLocation L = PathDiagnosticLocation::createEndOfPath(LeakN, SM);
Mike Stump1eb44332009-09-09 15:08:12 +00002264
Ted Kremenekc887d132009-04-29 18:50:19 +00002265 std::string sbuf;
2266 llvm::raw_string_ostream os(sbuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002267
Ted Kremenekf1365462011-05-26 18:45:44 +00002268 os << "Object leaked: ";
Mike Stump1eb44332009-09-09 15:08:12 +00002269
Ted Kremenekf1365462011-05-26 18:45:44 +00002270 if (FirstBinding) {
2271 os << "object allocated and stored into '"
2272 << FirstBinding->getString() << '\'';
2273 }
2274 else
2275 os << "allocated object";
Mike Stump1eb44332009-09-09 15:08:12 +00002276
Ted Kremenekc887d132009-04-29 18:50:19 +00002277 // Get the retain count.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002278 const RefVal* RV = getRefBinding(EndN->getState(), Sym);
Ted Kremenek5a8fc882012-10-12 22:56:40 +00002279 assert(RV);
Mike Stump1eb44332009-09-09 15:08:12 +00002280
Ted Kremenekc887d132009-04-29 18:50:19 +00002281 if (RV->getKind() == RefVal::ErrorLeakReturned) {
2282 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
Jordy Rose5b5402b2011-07-15 22:17:54 +00002283 // objects. Only "copy", "alloc", "retain" and "new" transfer ownership
Ted Kremenekc887d132009-04-29 18:50:19 +00002284 // to the caller for NS objects.
Ted Kremenekd368d712011-05-25 06:19:45 +00002285 const Decl *D = &EndN->getCodeDecl();
Ted Kremenekec9f36e2012-09-06 23:03:07 +00002286
2287 os << (isa<ObjCMethodDecl>(D) ? " is returned from a method "
2288 : " is returned from a function ");
2289
2290 if (D->getAttr<CFReturnsNotRetainedAttr>())
2291 os << "that is annotated as CF_RETURNS_NOT_RETAINED";
2292 else if (D->getAttr<NSReturnsNotRetainedAttr>())
2293 os << "that is annotated as NS_RETURNS_NOT_RETAINED";
Ted Kremenekd368d712011-05-25 06:19:45 +00002294 else {
Ted Kremenekec9f36e2012-09-06 23:03:07 +00002295 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2296 os << "whose name ('" << MD->getSelector().getAsString()
2297 << "') does not start with 'copy', 'mutableCopy', 'alloc' or 'new'."
2298 " This violates the naming convention rules"
2299 " given in the Memory Management Guide for Cocoa";
2300 }
2301 else {
2302 const FunctionDecl *FD = cast<FunctionDecl>(D);
2303 os << "whose name ('" << *FD
2304 << "') does not contain 'Copy' or 'Create'. This violates the naming"
2305 " convention rules given in the Memory Management Guide for Core"
2306 " Foundation";
2307 }
2308 }
Ted Kremenekc887d132009-04-29 18:50:19 +00002309 }
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002310 else if (RV->getKind() == RefVal::ErrorGCLeakReturned) {
David Blaikiee1300142013-02-21 22:37:44 +00002311 const ObjCMethodDecl &MD = cast<ObjCMethodDecl>(EndN->getCodeDecl());
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002312 os << " and returned from method '" << MD.getSelector().getAsString()
Ted Kremenek82f2be52009-05-10 16:52:15 +00002313 << "' is potentially leaked when using garbage collection. Callers "
2314 "of this method do not expect a returned object with a +1 retain "
2315 "count since they expect the object to be managed by the garbage "
2316 "collector";
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002317 }
Ted Kremenekc887d132009-04-29 18:50:19 +00002318 else
Ted Kremenekabf517c2010-10-15 22:50:23 +00002319 os << " is not referenced later in this execution path and has a retain "
Ted Kremenekf1365462011-05-26 18:45:44 +00002320 "count of +" << RV->getCount();
Mike Stump1eb44332009-09-09 15:08:12 +00002321
Ted Kremenekc887d132009-04-29 18:50:19 +00002322 return new PathDiagnosticEventPiece(L, os.str());
2323}
2324
Jordy Rose20589562011-08-24 22:39:09 +00002325CFRefLeakReport::CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts,
2326 bool GCEnabled, const SummaryLogTy &Log,
2327 ExplodedNode *n, SymbolRef sym,
Ted Kremenek08a838d2013-04-16 21:44:22 +00002328 CheckerContext &Ctx,
2329 bool IncludeAllocationLine)
2330 : CFRefReport(D, LOpts, GCEnabled, Log, n, sym, false) {
Mike Stump1eb44332009-09-09 15:08:12 +00002331
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00002332 // Most bug reports are cached at the location where they occurred.
Ted Kremenekc887d132009-04-29 18:50:19 +00002333 // With leaks, we want to unique them by the location where they were
2334 // allocated, and only report a single path. To do this, we need to find
2335 // the allocation site of a piece of tracked memory, which we do via a
2336 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2337 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2338 // that all ancestor nodes that represent the allocation site have the
2339 // same SourceLocation.
Ted Kremenek9c378f72011-08-12 23:37:29 +00002340 const ExplodedNode *AllocNode = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002341
Anna Zaks6a93bd52011-10-25 19:57:11 +00002342 const SourceManager& SMgr = Ctx.getSourceManager();
Anna Zaks590dd8e2011-09-20 21:38:35 +00002343
Anna Zaks7a87e522013-04-10 21:42:06 +00002344 AllocationInfo AllocI =
Anna Zaks6a93bd52011-10-25 19:57:11 +00002345 GetAllocationSite(Ctx.getStateManager(), getErrorNode(), sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002346
Anna Zaks7a87e522013-04-10 21:42:06 +00002347 AllocNode = AllocI.N;
2348 AllocBinding = AllocI.R;
2349 markInteresting(AllocI.InterestingMethodContext);
2350
Ted Kremenekc887d132009-04-29 18:50:19 +00002351 // Get the SourceLocation for the allocation site.
Jordan Rose852aa0d2012-07-10 22:07:52 +00002352 // FIXME: This will crash the analyzer if an allocation comes from an
2353 // implicit call. (Currently there are no such allocations in Cocoa, though.)
2354 const Stmt *AllocStmt;
Ted Kremenekc887d132009-04-29 18:50:19 +00002355 ProgramPoint P = AllocNode->getLocation();
David Blaikie7a95de62013-02-21 22:23:56 +00002356 if (Optional<CallExitEnd> Exit = P.getAs<CallExitEnd>())
Jordan Rose852aa0d2012-07-10 22:07:52 +00002357 AllocStmt = Exit->getCalleeContext()->getCallSite();
2358 else
David Blaikie7a95de62013-02-21 22:23:56 +00002359 AllocStmt = P.castAs<PostStmt>().getStmt();
Jordan Rose852aa0d2012-07-10 22:07:52 +00002360 assert(AllocStmt && "All allocations must come from explicit calls");
Anna Zaks590dd8e2011-09-20 21:38:35 +00002361 Location = PathDiagnosticLocation::createBegin(AllocStmt, SMgr,
2362 n->getLocationContext());
Ted Kremenekc887d132009-04-29 18:50:19 +00002363 // Fill in the description of the bug.
2364 Description.clear();
2365 llvm::raw_string_ostream os(Description);
Ted Kremenekdd924e22009-05-02 19:05:19 +00002366 os << "Potential leak ";
Jordy Rose20589562011-08-24 22:39:09 +00002367 if (GCEnabled)
Ted Kremenekdd924e22009-05-02 19:05:19 +00002368 os << "(when using garbage collection) ";
Anna Zaks212000e2012-02-28 21:49:08 +00002369 os << "of an object";
Mike Stump1eb44332009-09-09 15:08:12 +00002370
Ted Kremenek08a838d2013-04-16 21:44:22 +00002371 if (AllocBinding) {
Anna Zaks212000e2012-02-28 21:49:08 +00002372 os << " stored into '" << AllocBinding->getString() << '\'';
Ted Kremenek08a838d2013-04-16 21:44:22 +00002373 if (IncludeAllocationLine) {
2374 FullSourceLoc SL(AllocStmt->getLocStart(), Ctx.getSourceManager());
2375 os << " (allocated on line " << SL.getSpellingLineNumber() << ")";
2376 }
2377 }
Anna Zaksdc757b02011-08-19 23:21:56 +00002378
Jordy Rose20589562011-08-24 22:39:09 +00002379 addVisitor(new CFRefLeakReportVisitor(sym, GCEnabled, Log));
Ted Kremenekc887d132009-04-29 18:50:19 +00002380}
2381
2382//===----------------------------------------------------------------------===//
2383// Main checker logic.
2384//===----------------------------------------------------------------------===//
2385
Ted Kremenekd593eb92009-11-25 22:17:44 +00002386namespace {
Jordy Rose910c4052011-09-02 06:44:22 +00002387class RetainCountChecker
Jordy Rose9c083b72011-08-24 18:56:32 +00002388 : public Checker< check::Bind,
Jordy Rose38f17d62011-08-23 19:01:07 +00002389 check::DeadSymbols,
Jordy Rose9c083b72011-08-24 18:56:32 +00002390 check::EndAnalysis,
Anna Zaks344c77a2013-01-03 00:25:29 +00002391 check::EndFunction,
Jordy Rose67044292011-08-17 21:27:39 +00002392 check::PostStmt<BlockExpr>,
John McCallf85e1932011-06-15 23:02:42 +00002393 check::PostStmt<CastExpr>,
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002394 check::PostStmt<ObjCArrayLiteral>,
2395 check::PostStmt<ObjCDictionaryLiteral>,
Jordy Rose70fdbc32012-05-12 05:10:43 +00002396 check::PostStmt<ObjCBoxedExpr>,
Jordan Rosefe6a0112012-07-02 19:28:21 +00002397 check::PostCall,
Jordy Rosef53e8c72011-08-23 19:43:16 +00002398 check::PreStmt<ReturnStmt>,
Jordy Rose67044292011-08-17 21:27:39 +00002399 check::RegionChanges,
Jordy Rose76c506f2011-08-21 21:58:18 +00002400 eval::Assume,
2401 eval::Call > {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002402 mutable OwningPtr<CFRefBug> useAfterRelease, releaseNotOwned;
2403 mutable OwningPtr<CFRefBug> deallocGC, deallocNotOwned;
2404 mutable OwningPtr<CFRefBug> overAutorelease, returnNotOwnedForOwned;
2405 mutable OwningPtr<CFRefBug> leakWithinFunction, leakAtReturn;
2406 mutable OwningPtr<CFRefBug> leakWithinFunctionGC, leakAtReturnGC;
Jordy Rose38f17d62011-08-23 19:01:07 +00002407
2408 typedef llvm::DenseMap<SymbolRef, const SimpleProgramPointTag *> SymbolTagMap;
2409
2410 // This map is only used to ensure proper deletion of any allocated tags.
2411 mutable SymbolTagMap DeadSymbolTags;
2412
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002413 mutable OwningPtr<RetainSummaryManager> Summaries;
2414 mutable OwningPtr<RetainSummaryManager> SummariesGC;
Jordy Rose9c083b72011-08-24 18:56:32 +00002415 mutable SummaryLogTy SummaryLog;
2416 mutable bool ShouldResetSummaryLog;
2417
Ted Kremenek08a838d2013-04-16 21:44:22 +00002418 /// Optional setting to indicate if leak reports should include
2419 /// the allocation line.
2420 mutable bool IncludeAllocationLine;
2421
Jordy Rose2f9a66d2011-08-20 21:17:59 +00002422public:
Ted Kremenek08a838d2013-04-16 21:44:22 +00002423 RetainCountChecker(AnalyzerOptions &AO)
2424 : ShouldResetSummaryLog(false),
2425 IncludeAllocationLine(shouldIncludeAllocationSiteInLeakDiagnostics(AO)) {}
Jordy Rose38f17d62011-08-23 19:01:07 +00002426
Jordy Rose910c4052011-09-02 06:44:22 +00002427 virtual ~RetainCountChecker() {
Jordy Rose38f17d62011-08-23 19:01:07 +00002428 DeleteContainerSeconds(DeadSymbolTags);
2429 }
2430
Jordy Rose9c083b72011-08-24 18:56:32 +00002431 void checkEndAnalysis(ExplodedGraph &G, BugReporter &BR,
2432 ExprEngine &Eng) const {
2433 // FIXME: This is a hack to make sure the summary log gets cleared between
2434 // analyses of different code bodies.
2435 //
2436 // Why is this necessary? Because a checker's lifetime is tied to a
2437 // translation unit, but an ExplodedGraph's lifetime is just a code body.
2438 // Once in a blue moon, a new ExplodedNode will have the same address as an
2439 // old one with an associated summary, and the bug report visitor gets very
2440 // confused. (To make things worse, the summary lifetime is currently also
2441 // tied to a code body, so we get a crash instead of incorrect results.)
Jordy Rose1ab51c72011-08-24 09:27:24 +00002442 //
2443 // Why is this a bad solution? Because if the lifetime of the ExplodedGraph
2444 // changes, things will start going wrong again. Really the lifetime of this
2445 // log needs to be tied to either the specific nodes in it or the entire
2446 // ExplodedGraph, not to a specific part of the code being analyzed.
2447 //
Jordy Rose9c083b72011-08-24 18:56:32 +00002448 // (Also, having stateful local data means that the same checker can't be
2449 // used from multiple threads, but a lot of checkers have incorrect
2450 // assumptions about that anyway. So that wasn't a priority at the time of
2451 // this fix.)
Jordy Rose1ab51c72011-08-24 09:27:24 +00002452 //
Jordy Rose9c083b72011-08-24 18:56:32 +00002453 // This happens at the end of analysis, but bug reports are emitted /after/
2454 // this point. So we can't just clear the summary log now. Instead, we mark
2455 // that the next time we access the summary log, it should be cleared.
2456
2457 // If we never reset the summary log during /this/ code body analysis,
2458 // there were no new summaries. There might still have been summaries from
2459 // the /last/ analysis, so clear them out to make sure the bug report
2460 // visitors don't get confused.
2461 if (ShouldResetSummaryLog)
2462 SummaryLog.clear();
2463
2464 ShouldResetSummaryLog = !SummaryLog.empty();
Jordy Rose1ab51c72011-08-24 09:27:24 +00002465 }
2466
Jordy Rose17a38e22011-09-02 05:55:19 +00002467 CFRefBug *getLeakWithinFunctionBug(const LangOptions &LOpts,
2468 bool GCEnabled) const {
2469 if (GCEnabled) {
Jordy Rosedb92bb62011-08-25 01:14:38 +00002470 if (!leakWithinFunctionGC)
Benjamin Kramerfacde172012-06-06 17:32:50 +00002471 leakWithinFunctionGC.reset(new Leak("Leak of object when using "
2472 "garbage collection"));
Jordy Rose17a38e22011-09-02 05:55:19 +00002473 return leakWithinFunctionGC.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002474 } else {
2475 if (!leakWithinFunction) {
Douglas Gregore289d812011-09-13 17:21:33 +00002476 if (LOpts.getGC() == LangOptions::HybridGC) {
Benjamin Kramerfacde172012-06-06 17:32:50 +00002477 leakWithinFunction.reset(new Leak("Leak of object when not using "
2478 "garbage collection (GC) in "
2479 "dual GC/non-GC code"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002480 } else {
Benjamin Kramerfacde172012-06-06 17:32:50 +00002481 leakWithinFunction.reset(new Leak("Leak"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002482 }
2483 }
Jordy Rose17a38e22011-09-02 05:55:19 +00002484 return leakWithinFunction.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002485 }
2486 }
2487
Jordy Rose17a38e22011-09-02 05:55:19 +00002488 CFRefBug *getLeakAtReturnBug(const LangOptions &LOpts, bool GCEnabled) const {
2489 if (GCEnabled) {
Jordy Rosedb92bb62011-08-25 01:14:38 +00002490 if (!leakAtReturnGC)
Benjamin Kramerfacde172012-06-06 17:32:50 +00002491 leakAtReturnGC.reset(new Leak("Leak of returned object when using "
2492 "garbage collection"));
Jordy Rose17a38e22011-09-02 05:55:19 +00002493 return leakAtReturnGC.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002494 } else {
2495 if (!leakAtReturn) {
Douglas Gregore289d812011-09-13 17:21:33 +00002496 if (LOpts.getGC() == LangOptions::HybridGC) {
Benjamin Kramerfacde172012-06-06 17:32:50 +00002497 leakAtReturn.reset(new Leak("Leak of returned object when not using "
2498 "garbage collection (GC) in dual "
2499 "GC/non-GC code"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002500 } else {
Benjamin Kramerfacde172012-06-06 17:32:50 +00002501 leakAtReturn.reset(new Leak("Leak of returned object"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002502 }
2503 }
Jordy Rose17a38e22011-09-02 05:55:19 +00002504 return leakAtReturn.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002505 }
2506 }
2507
Jordy Rose17a38e22011-09-02 05:55:19 +00002508 RetainSummaryManager &getSummaryManager(ASTContext &Ctx,
2509 bool GCEnabled) const {
2510 // FIXME: We don't support ARC being turned on and off during one analysis.
2511 // (nor, for that matter, do we support changing ASTContexts)
David Blaikie4e4d0842012-03-11 07:00:24 +00002512 bool ARCEnabled = (bool)Ctx.getLangOpts().ObjCAutoRefCount;
Jordy Rose17a38e22011-09-02 05:55:19 +00002513 if (GCEnabled) {
2514 if (!SummariesGC)
Jordy Roseb6cfc092011-08-25 00:10:37 +00002515 SummariesGC.reset(new RetainSummaryManager(Ctx, true, ARCEnabled));
Jordy Rose17a38e22011-09-02 05:55:19 +00002516 else
2517 assert(SummariesGC->isARCEnabled() == ARCEnabled);
Jordy Roseb6cfc092011-08-25 00:10:37 +00002518 return *SummariesGC;
2519 } else {
Jordy Rose17a38e22011-09-02 05:55:19 +00002520 if (!Summaries)
Jordy Roseb6cfc092011-08-25 00:10:37 +00002521 Summaries.reset(new RetainSummaryManager(Ctx, false, ARCEnabled));
Jordy Rose17a38e22011-09-02 05:55:19 +00002522 else
2523 assert(Summaries->isARCEnabled() == ARCEnabled);
Jordy Roseb6cfc092011-08-25 00:10:37 +00002524 return *Summaries;
2525 }
2526 }
2527
Jordy Rose17a38e22011-09-02 05:55:19 +00002528 RetainSummaryManager &getSummaryManager(CheckerContext &C) const {
2529 return getSummaryManager(C.getASTContext(), C.isObjCGCEnabled());
2530 }
2531
Ted Kremenek8bef8232012-01-26 21:29:00 +00002532 void printState(raw_ostream &Out, ProgramStateRef State,
Jordy Rosedbd658e2011-08-28 19:11:56 +00002533 const char *NL, const char *Sep) const;
2534
Anna Zaks390909c2011-10-06 00:43:15 +00002535 void checkBind(SVal loc, SVal val, const Stmt *S, CheckerContext &C) const;
Jordy Roseab027fd2011-08-20 21:16:58 +00002536 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
2537 void checkPostStmt(const CastExpr *CE, CheckerContext &C) const;
John McCallf85e1932011-06-15 23:02:42 +00002538
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002539 void checkPostStmt(const ObjCArrayLiteral *AL, CheckerContext &C) const;
2540 void checkPostStmt(const ObjCDictionaryLiteral *DL, CheckerContext &C) const;
Jordy Rose70fdbc32012-05-12 05:10:43 +00002541 void checkPostStmt(const ObjCBoxedExpr *BE, CheckerContext &C) const;
2542
Jordan Rosefe6a0112012-07-02 19:28:21 +00002543 void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002544
Jordan Rose4531b7d2012-07-02 19:27:43 +00002545 void checkSummary(const RetainSummary &Summ, const CallEvent &Call,
Jordy Rosee38dd952011-08-28 05:16:28 +00002546 CheckerContext &C) const;
Jordy Rose294396b2011-08-22 23:48:23 +00002547
Anna Zaks554067f2012-08-29 23:23:43 +00002548 void processSummaryOfInlined(const RetainSummary &Summ,
2549 const CallEvent &Call,
2550 CheckerContext &C) const;
2551
Jordy Rose76c506f2011-08-21 21:58:18 +00002552 bool evalCall(const CallExpr *CE, CheckerContext &C) const;
2553
Ted Kremenek8bef8232012-01-26 21:29:00 +00002554 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Jordy Roseab027fd2011-08-20 21:16:58 +00002555 bool Assumption) const;
Jordy Rose67044292011-08-17 21:27:39 +00002556
Ted Kremenek8bef8232012-01-26 21:29:00 +00002557 ProgramStateRef
2558 checkRegionChanges(ProgramStateRef state,
Anna Zaksbf53dfa2012-12-20 00:38:25 +00002559 const InvalidatedSymbols *invalidated,
Jordy Rose537716a2011-08-27 22:51:26 +00002560 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00002561 ArrayRef<const MemRegion *> Regions,
Jordan Rose740d4902012-07-02 19:27:35 +00002562 const CallEvent *Call) const;
Jordy Roseab027fd2011-08-20 21:16:58 +00002563
Ted Kremenek8bef8232012-01-26 21:29:00 +00002564 bool wantsRegionChangeUpdate(ProgramStateRef state) const {
Jordy Rose2f9a66d2011-08-20 21:17:59 +00002565 return true;
Jordy Roseab027fd2011-08-20 21:16:58 +00002566 }
Jordy Rose294396b2011-08-22 23:48:23 +00002567
Jordy Rosef53e8c72011-08-23 19:43:16 +00002568 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
2569 void checkReturnWithRetEffect(const ReturnStmt *S, CheckerContext &C,
2570 ExplodedNode *Pred, RetEffect RE, RefVal X,
Ted Kremenek8bef8232012-01-26 21:29:00 +00002571 SymbolRef Sym, ProgramStateRef state) const;
Jordy Rosef53e8c72011-08-23 19:43:16 +00002572
Jordy Rose38f17d62011-08-23 19:01:07 +00002573 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Anna Zaks344c77a2013-01-03 00:25:29 +00002574 void checkEndFunction(CheckerContext &C) const;
Jordy Rose38f17d62011-08-23 19:01:07 +00002575
Ted Kremenek8bef8232012-01-26 21:29:00 +00002576 ProgramStateRef updateSymbol(ProgramStateRef state, SymbolRef sym,
Anna Zaks554067f2012-08-29 23:23:43 +00002577 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
2578 CheckerContext &C) const;
Jordy Rosee0a5d322011-08-23 20:27:16 +00002579
Ted Kremenek8bef8232012-01-26 21:29:00 +00002580 void processNonLeakError(ProgramStateRef St, SourceRange ErrorRange,
Jordy Rose294396b2011-08-22 23:48:23 +00002581 RefVal::Kind ErrorKind, SymbolRef Sym,
2582 CheckerContext &C) const;
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002583
2584 void processObjCLiterals(CheckerContext &C, const Expr *Ex) const;
Jordy Rose294396b2011-08-22 23:48:23 +00002585
Jordy Rose38f17d62011-08-23 19:01:07 +00002586 const ProgramPointTag *getDeadSymbolTag(SymbolRef sym) const;
2587
Ted Kremenek8bef8232012-01-26 21:29:00 +00002588 ProgramStateRef handleSymbolDeath(ProgramStateRef state,
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002589 SymbolRef sid, RefVal V,
2590 SmallVectorImpl<SymbolRef> &Leaked) const;
Jordy Rose38f17d62011-08-23 19:01:07 +00002591
Jordan Rose4ee1c552012-12-06 18:58:18 +00002592 ProgramStateRef
Jordan Rose2bce86c2012-08-18 00:30:16 +00002593 handleAutoreleaseCounts(ProgramStateRef state, ExplodedNode *Pred,
2594 const ProgramPointTag *Tag, CheckerContext &Ctx,
2595 SymbolRef Sym, RefVal V) const;
Jordy Rose8d228632011-08-23 20:07:14 +00002596
Ted Kremenek8bef8232012-01-26 21:29:00 +00002597 ExplodedNode *processLeaks(ProgramStateRef state,
Jordy Rose38f17d62011-08-23 19:01:07 +00002598 SmallVectorImpl<SymbolRef> &Leaked,
Anna Zaks6a93bd52011-10-25 19:57:11 +00002599 CheckerContext &Ctx,
Jordy Rose38f17d62011-08-23 19:01:07 +00002600 ExplodedNode *Pred = 0) const;
Ted Kremenekd593eb92009-11-25 22:17:44 +00002601};
2602} // end anonymous namespace
2603
Jordy Rose67044292011-08-17 21:27:39 +00002604namespace {
2605class StopTrackingCallback : public SymbolVisitor {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002606 ProgramStateRef state;
Jordy Rose67044292011-08-17 21:27:39 +00002607public:
Ted Kremenek8bef8232012-01-26 21:29:00 +00002608 StopTrackingCallback(ProgramStateRef st) : state(st) {}
2609 ProgramStateRef getState() const { return state; }
Jordy Rose67044292011-08-17 21:27:39 +00002610
2611 bool VisitSymbol(SymbolRef sym) {
2612 state = state->remove<RefBindings>(sym);
2613 return true;
2614 }
2615};
2616} // end anonymous namespace
2617
Jordy Rose910c4052011-09-02 06:44:22 +00002618//===----------------------------------------------------------------------===//
2619// Handle statements that may have an effect on refcounts.
2620//===----------------------------------------------------------------------===//
Jordy Rose67044292011-08-17 21:27:39 +00002621
Jordy Rose910c4052011-09-02 06:44:22 +00002622void RetainCountChecker::checkPostStmt(const BlockExpr *BE,
2623 CheckerContext &C) const {
Jordy Rose67044292011-08-17 21:27:39 +00002624
Jordy Rose910c4052011-09-02 06:44:22 +00002625 // Scan the BlockDecRefExprs for any object the retain count checker
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002626 // may be tracking.
John McCall469a1eb2011-02-02 13:00:07 +00002627 if (!BE->getBlockDecl()->hasCaptures())
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002628 return;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002629
Ted Kremenek8bef8232012-01-26 21:29:00 +00002630 ProgramStateRef state = C.getState();
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002631 const BlockDataRegion *R =
Ted Kremenek5eca4822012-01-06 22:09:28 +00002632 cast<BlockDataRegion>(state->getSVal(BE,
2633 C.getLocationContext()).getAsRegion());
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002634
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002635 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
2636 E = R->referenced_vars_end();
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002637
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002638 if (I == E)
2639 return;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002640
Ted Kremenek67d12872009-12-07 22:05:27 +00002641 // FIXME: For now we invalidate the tracking of all symbols passed to blocks
2642 // via captured variables, even though captured variables result in a copy
2643 // and in implicit increment/decrement of a retain count.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002644 SmallVector<const MemRegion*, 10> Regions;
Anna Zaks39ac1872011-10-26 21:06:44 +00002645 const LocationContext *LC = C.getLocationContext();
Ted Kremenekc8413fd2010-12-02 07:49:45 +00002646 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002647
Ted Kremenek67d12872009-12-07 22:05:27 +00002648 for ( ; I != E; ++I) {
Ted Kremeneke3ce2c12012-12-06 07:17:20 +00002649 const VarRegion *VR = I.getCapturedRegion();
Ted Kremenek67d12872009-12-07 22:05:27 +00002650 if (VR->getSuperRegion() == R) {
2651 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2652 }
2653 Regions.push_back(VR);
2654 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002655
Ted Kremenek67d12872009-12-07 22:05:27 +00002656 state =
2657 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
2658 Regions.data() + Regions.size()).getState();
Anna Zaks0bd6b112011-10-26 21:06:34 +00002659 C.addTransition(state);
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002660}
2661
Jordy Rose910c4052011-09-02 06:44:22 +00002662void RetainCountChecker::checkPostStmt(const CastExpr *CE,
2663 CheckerContext &C) const {
John McCallf85e1932011-06-15 23:02:42 +00002664 const ObjCBridgedCastExpr *BE = dyn_cast<ObjCBridgedCastExpr>(CE);
2665 if (!BE)
2666 return;
2667
John McCall71c482c2011-06-17 06:50:50 +00002668 ArgEffect AE = IncRef;
John McCallf85e1932011-06-15 23:02:42 +00002669
2670 switch (BE->getBridgeKind()) {
2671 case clang::OBC_Bridge:
2672 // Do nothing.
2673 return;
2674 case clang::OBC_BridgeRetained:
2675 AE = IncRef;
2676 break;
2677 case clang::OBC_BridgeTransfer:
2678 AE = DecRefBridgedTransfered;
2679 break;
2680 }
2681
Ted Kremenek8bef8232012-01-26 21:29:00 +00002682 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00002683 SymbolRef Sym = state->getSVal(CE, C.getLocationContext()).getAsLocSymbol();
John McCallf85e1932011-06-15 23:02:42 +00002684 if (!Sym)
2685 return;
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002686 const RefVal* T = getRefBinding(state, Sym);
John McCallf85e1932011-06-15 23:02:42 +00002687 if (!T)
2688 return;
2689
John McCallf85e1932011-06-15 23:02:42 +00002690 RefVal::Kind hasErr = (RefVal::Kind) 0;
Jordy Rose17a38e22011-09-02 05:55:19 +00002691 state = updateSymbol(state, Sym, *T, AE, hasErr, C);
John McCallf85e1932011-06-15 23:02:42 +00002692
2693 if (hasErr) {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002694 // FIXME: If we get an error during a bridge cast, should we report it?
2695 // Should we assert that there is no error?
John McCallf85e1932011-06-15 23:02:42 +00002696 return;
2697 }
2698
Anna Zaks0bd6b112011-10-26 21:06:34 +00002699 C.addTransition(state);
John McCallf85e1932011-06-15 23:02:42 +00002700}
2701
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002702void RetainCountChecker::processObjCLiterals(CheckerContext &C,
2703 const Expr *Ex) const {
2704 ProgramStateRef state = C.getState();
2705 const ExplodedNode *pred = C.getPredecessor();
2706 for (Stmt::const_child_iterator it = Ex->child_begin(), et = Ex->child_end() ;
2707 it != et ; ++it) {
2708 const Stmt *child = *it;
2709 SVal V = state->getSVal(child, pred->getLocationContext());
2710 if (SymbolRef sym = V.getAsSymbol())
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002711 if (const RefVal* T = getRefBinding(state, sym)) {
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002712 RefVal::Kind hasErr = (RefVal::Kind) 0;
2713 state = updateSymbol(state, sym, *T, MayEscape, hasErr, C);
2714 if (hasErr) {
2715 processNonLeakError(state, child->getSourceRange(), hasErr, sym, C);
2716 return;
2717 }
2718 }
2719 }
2720
2721 // Return the object as autoreleased.
2722 // RetEffect RE = RetEffect::MakeNotOwned(RetEffect::ObjC);
2723 if (SymbolRef sym =
2724 state->getSVal(Ex, pred->getLocationContext()).getAsSymbol()) {
2725 QualType ResultTy = Ex->getType();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002726 state = setRefBinding(state, sym,
2727 RefVal::makeNotOwned(RetEffect::ObjC, ResultTy));
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002728 }
2729
2730 C.addTransition(state);
2731}
2732
2733void RetainCountChecker::checkPostStmt(const ObjCArrayLiteral *AL,
2734 CheckerContext &C) const {
2735 // Apply the 'MayEscape' to all values.
2736 processObjCLiterals(C, AL);
2737}
2738
2739void RetainCountChecker::checkPostStmt(const ObjCDictionaryLiteral *DL,
2740 CheckerContext &C) const {
2741 // Apply the 'MayEscape' to all keys and values.
2742 processObjCLiterals(C, DL);
2743}
2744
Jordy Rose70fdbc32012-05-12 05:10:43 +00002745void RetainCountChecker::checkPostStmt(const ObjCBoxedExpr *Ex,
2746 CheckerContext &C) const {
2747 const ExplodedNode *Pred = C.getPredecessor();
2748 const LocationContext *LCtx = Pred->getLocationContext();
2749 ProgramStateRef State = Pred->getState();
2750
2751 if (SymbolRef Sym = State->getSVal(Ex, LCtx).getAsSymbol()) {
2752 QualType ResultTy = Ex->getType();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002753 State = setRefBinding(State, Sym,
2754 RefVal::makeNotOwned(RetEffect::ObjC, ResultTy));
Jordy Rose70fdbc32012-05-12 05:10:43 +00002755 }
2756
2757 C.addTransition(State);
2758}
2759
Jordan Rosefe6a0112012-07-02 19:28:21 +00002760void RetainCountChecker::checkPostCall(const CallEvent &Call,
2761 CheckerContext &C) const {
Jordan Rosefe6a0112012-07-02 19:28:21 +00002762 RetainSummaryManager &Summaries = getSummaryManager(C);
2763 const RetainSummary *Summ = Summaries.getSummary(Call, C.getState());
Anna Zaks554067f2012-08-29 23:23:43 +00002764
2765 if (C.wasInlined) {
2766 processSummaryOfInlined(*Summ, Call, C);
2767 return;
2768 }
Jordan Rosefe6a0112012-07-02 19:28:21 +00002769 checkSummary(*Summ, Call, C);
Jordy Rose294396b2011-08-22 23:48:23 +00002770}
2771
Jordy Rose910c4052011-09-02 06:44:22 +00002772/// GetReturnType - Used to get the return type of a message expression or
2773/// function call with the intention of affixing that type to a tracked symbol.
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +00002774/// While the return type can be queried directly from RetEx, when
Jordy Rose910c4052011-09-02 06:44:22 +00002775/// invoking class methods we augment to the return type to be that of
2776/// a pointer to the class (as opposed it just being id).
2777// FIXME: We may be able to do this with related result types instead.
2778// This function is probably overestimating.
2779static QualType GetReturnType(const Expr *RetE, ASTContext &Ctx) {
2780 QualType RetTy = RetE->getType();
2781 // If RetE is not a message expression just return its type.
2782 // If RetE is a message expression, return its types if it is something
2783 /// more specific than id.
2784 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RetE))
2785 if (const ObjCObjectPointerType *PT = RetTy->getAs<ObjCObjectPointerType>())
2786 if (PT->isObjCQualifiedIdType() || PT->isObjCIdType() ||
2787 PT->isObjCClassType()) {
2788 // At this point we know the return type of the message expression is
2789 // id, id<...>, or Class. If we have an ObjCInterfaceDecl, we know this
2790 // is a call to a class method whose type we can resolve. In such
2791 // cases, promote the return type to XXX* (where XXX is the class).
2792 const ObjCInterfaceDecl *D = ME->getReceiverInterface();
2793 return !D ? RetTy :
2794 Ctx.getObjCObjectPointerType(Ctx.getObjCInterfaceType(D));
2795 }
2796
2797 return RetTy;
2798}
2799
Anna Zaks554067f2012-08-29 23:23:43 +00002800// We don't always get the exact modeling of the function with regards to the
2801// retain count checker even when the function is inlined. For example, we need
2802// to stop tracking the symbols which were marked with StopTrackingHard.
2803void RetainCountChecker::processSummaryOfInlined(const RetainSummary &Summ,
2804 const CallEvent &CallOrMsg,
2805 CheckerContext &C) const {
2806 ProgramStateRef state = C.getState();
2807
2808 // Evaluate the effect of the arguments.
2809 for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
2810 if (Summ.getArg(idx) == StopTrackingHard) {
2811 SVal V = CallOrMsg.getArgSVal(idx);
2812 if (SymbolRef Sym = V.getAsLocSymbol()) {
2813 state = removeRefBinding(state, Sym);
2814 }
2815 }
2816 }
2817
2818 // Evaluate the effect on the message receiver.
2819 const ObjCMethodCall *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg);
2820 if (MsgInvocation) {
2821 if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
2822 if (Summ.getReceiverEffect() == StopTrackingHard) {
2823 state = removeRefBinding(state, Sym);
2824 }
2825 }
2826 }
2827
2828 // Consult the summary for the return value.
2829 RetEffect RE = Summ.getRetEffect();
2830 if (RE.getKind() == RetEffect::NoRetHard) {
Jordan Rose2f3017f2012-11-02 23:49:29 +00002831 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
Anna Zaks554067f2012-08-29 23:23:43 +00002832 if (Sym)
2833 state = removeRefBinding(state, Sym);
2834 }
2835
2836 C.addTransition(state);
2837}
2838
Jordy Rose910c4052011-09-02 06:44:22 +00002839void RetainCountChecker::checkSummary(const RetainSummary &Summ,
Jordan Rose4531b7d2012-07-02 19:27:43 +00002840 const CallEvent &CallOrMsg,
Jordy Rose910c4052011-09-02 06:44:22 +00002841 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002842 ProgramStateRef state = C.getState();
Jordy Rose294396b2011-08-22 23:48:23 +00002843
2844 // Evaluate the effect of the arguments.
2845 RefVal::Kind hasErr = (RefVal::Kind) 0;
2846 SourceRange ErrorRange;
2847 SymbolRef ErrorSym = 0;
2848
2849 for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
Jordy Rose537716a2011-08-27 22:51:26 +00002850 SVal V = CallOrMsg.getArgSVal(idx);
Jordy Rose294396b2011-08-22 23:48:23 +00002851
2852 if (SymbolRef Sym = V.getAsLocSymbol()) {
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002853 if (const RefVal *T = getRefBinding(state, Sym)) {
Jordy Rose17a38e22011-09-02 05:55:19 +00002854 state = updateSymbol(state, Sym, *T, Summ.getArg(idx), hasErr, C);
Jordy Rose294396b2011-08-22 23:48:23 +00002855 if (hasErr) {
2856 ErrorRange = CallOrMsg.getArgSourceRange(idx);
2857 ErrorSym = Sym;
2858 break;
2859 }
2860 }
2861 }
2862 }
2863
2864 // Evaluate the effect on the message receiver.
2865 bool ReceiverIsTracked = false;
Jordan Rose4531b7d2012-07-02 19:27:43 +00002866 if (!hasErr) {
Jordan Rosecde8cdb2012-07-02 19:27:56 +00002867 const ObjCMethodCall *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg);
Jordan Rose4531b7d2012-07-02 19:27:43 +00002868 if (MsgInvocation) {
2869 if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002870 if (const RefVal *T = getRefBinding(state, Sym)) {
Jordan Rose4531b7d2012-07-02 19:27:43 +00002871 ReceiverIsTracked = true;
2872 state = updateSymbol(state, Sym, *T, Summ.getReceiverEffect(),
Anna Zaks554067f2012-08-29 23:23:43 +00002873 hasErr, C);
Jordan Rose4531b7d2012-07-02 19:27:43 +00002874 if (hasErr) {
Jordan Rose8919e682012-07-18 21:59:51 +00002875 ErrorRange = MsgInvocation->getOriginExpr()->getReceiverRange();
Jordan Rose4531b7d2012-07-02 19:27:43 +00002876 ErrorSym = Sym;
2877 }
Jordy Rose294396b2011-08-22 23:48:23 +00002878 }
2879 }
2880 }
2881 }
2882
2883 // Process any errors.
2884 if (hasErr) {
2885 processNonLeakError(state, ErrorRange, hasErr, ErrorSym, C);
2886 return;
2887 }
2888
2889 // Consult the summary for the return value.
2890 RetEffect RE = Summ.getRetEffect();
2891
2892 if (RE.getKind() == RetEffect::OwnedWhenTrackedReceiver) {
Jordy Roseb6cfc092011-08-25 00:10:37 +00002893 if (ReceiverIsTracked)
Jordy Rose17a38e22011-09-02 05:55:19 +00002894 RE = getSummaryManager(C).getObjAllocRetEffect();
Jordy Roseb6cfc092011-08-25 00:10:37 +00002895 else
Jordy Rose294396b2011-08-22 23:48:23 +00002896 RE = RetEffect::MakeNoRet();
2897 }
2898
2899 switch (RE.getKind()) {
2900 default:
David Blaikie7530c032012-01-17 06:56:22 +00002901 llvm_unreachable("Unhandled RetEffect.");
Jordy Rose294396b2011-08-22 23:48:23 +00002902
2903 case RetEffect::NoRet:
Anna Zaks554067f2012-08-29 23:23:43 +00002904 case RetEffect::NoRetHard:
Jordy Rose294396b2011-08-22 23:48:23 +00002905 // No work necessary.
2906 break;
2907
2908 case RetEffect::OwnedAllocatedSymbol:
2909 case RetEffect::OwnedSymbol: {
Jordan Rose2f3017f2012-11-02 23:49:29 +00002910 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
Jordy Rose294396b2011-08-22 23:48:23 +00002911 if (!Sym)
2912 break;
2913
Jordan Rose4531b7d2012-07-02 19:27:43 +00002914 // Use the result type from the CallEvent as it automatically adjusts
Jordy Rose294396b2011-08-22 23:48:23 +00002915 // for methods/functions that return references.
Jordan Rose4531b7d2012-07-02 19:27:43 +00002916 QualType ResultTy = CallOrMsg.getResultType();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002917 state = setRefBinding(state, Sym, RefVal::makeOwned(RE.getObjKind(),
2918 ResultTy));
Jordy Rose294396b2011-08-22 23:48:23 +00002919
2920 // FIXME: Add a flag to the checker where allocations are assumed to
Anna Zaksc6ba23f2012-08-14 15:39:13 +00002921 // *not* fail.
Jordy Rose294396b2011-08-22 23:48:23 +00002922 break;
2923 }
2924
2925 case RetEffect::GCNotOwnedSymbol:
2926 case RetEffect::ARCNotOwnedSymbol:
2927 case RetEffect::NotOwnedSymbol: {
2928 const Expr *Ex = CallOrMsg.getOriginExpr();
Jordan Rose2f3017f2012-11-02 23:49:29 +00002929 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
Jordy Rose294396b2011-08-22 23:48:23 +00002930 if (!Sym)
2931 break;
Ted Kremenek74616822012-10-12 22:56:45 +00002932 assert(Ex);
Jordy Rose294396b2011-08-22 23:48:23 +00002933 // Use GetReturnType in order to give [NSFoo alloc] the type NSFoo *.
2934 QualType ResultTy = GetReturnType(Ex, C.getASTContext());
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002935 state = setRefBinding(state, Sym, RefVal::makeNotOwned(RE.getObjKind(),
2936 ResultTy));
Jordy Rose294396b2011-08-22 23:48:23 +00002937 break;
2938 }
2939 }
2940
2941 // This check is actually necessary; otherwise the statement builder thinks
2942 // we've hit a previously-found path.
2943 // Normally addTransition takes care of this, but we want the node pointer.
2944 ExplodedNode *NewNode;
2945 if (state == C.getState()) {
2946 NewNode = C.getPredecessor();
2947 } else {
Anna Zaks0bd6b112011-10-26 21:06:34 +00002948 NewNode = C.addTransition(state);
Jordy Rose294396b2011-08-22 23:48:23 +00002949 }
2950
Jordy Rose9c083b72011-08-24 18:56:32 +00002951 // Annotate the node with summary we used.
2952 if (NewNode) {
2953 // FIXME: This is ugly. See checkEndAnalysis for why it's necessary.
2954 if (ShouldResetSummaryLog) {
2955 SummaryLog.clear();
2956 ShouldResetSummaryLog = false;
2957 }
Jordy Roseec9ef852011-08-23 20:55:48 +00002958 SummaryLog[NewNode] = &Summ;
Jordy Rose9c083b72011-08-24 18:56:32 +00002959 }
Jordy Rose294396b2011-08-22 23:48:23 +00002960}
2961
Jordy Rosee0a5d322011-08-23 20:27:16 +00002962
Ted Kremenek8bef8232012-01-26 21:29:00 +00002963ProgramStateRef
2964RetainCountChecker::updateSymbol(ProgramStateRef state, SymbolRef sym,
Jordy Rose910c4052011-09-02 06:44:22 +00002965 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
2966 CheckerContext &C) const {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002967 // In GC mode [... release] and [... retain] do nothing.
Jordy Rose910c4052011-09-02 06:44:22 +00002968 // In ARC mode they shouldn't exist at all, but we just ignore them.
Jordy Rose17a38e22011-09-02 05:55:19 +00002969 bool IgnoreRetainMsg = C.isObjCGCEnabled();
2970 if (!IgnoreRetainMsg)
David Blaikie4e4d0842012-03-11 07:00:24 +00002971 IgnoreRetainMsg = (bool)C.getASTContext().getLangOpts().ObjCAutoRefCount;
Jordy Rose17a38e22011-09-02 05:55:19 +00002972
Jordy Rosee0a5d322011-08-23 20:27:16 +00002973 switch (E) {
Jordan Rose4531b7d2012-07-02 19:27:43 +00002974 default:
2975 break;
2976 case IncRefMsg:
2977 E = IgnoreRetainMsg ? DoNothing : IncRef;
2978 break;
2979 case DecRefMsg:
2980 E = IgnoreRetainMsg ? DoNothing : DecRef;
2981 break;
Anna Zaks554067f2012-08-29 23:23:43 +00002982 case DecRefMsgAndStopTrackingHard:
2983 E = IgnoreRetainMsg ? StopTracking : DecRefAndStopTrackingHard;
Jordan Rose4531b7d2012-07-02 19:27:43 +00002984 break;
2985 case MakeCollectable:
2986 E = C.isObjCGCEnabled() ? DecRef : DoNothing;
2987 break;
Jordy Rosee0a5d322011-08-23 20:27:16 +00002988 }
2989
2990 // Handle all use-after-releases.
Jordy Rose17a38e22011-09-02 05:55:19 +00002991 if (!C.isObjCGCEnabled() && V.getKind() == RefVal::Released) {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002992 V = V ^ RefVal::ErrorUseAfterRelease;
2993 hasErr = V.getKind();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002994 return setRefBinding(state, sym, V);
Jordy Rosee0a5d322011-08-23 20:27:16 +00002995 }
2996
2997 switch (E) {
2998 case DecRefMsg:
2999 case IncRefMsg:
3000 case MakeCollectable:
Anna Zaks554067f2012-08-29 23:23:43 +00003001 case DecRefMsgAndStopTrackingHard:
Jordy Rosee0a5d322011-08-23 20:27:16 +00003002 llvm_unreachable("DecRefMsg/IncRefMsg/MakeCollectable already converted");
Jordy Rosee0a5d322011-08-23 20:27:16 +00003003
3004 case Dealloc:
3005 // Any use of -dealloc in GC is *bad*.
Jordy Rose17a38e22011-09-02 05:55:19 +00003006 if (C.isObjCGCEnabled()) {
Jordy Rosee0a5d322011-08-23 20:27:16 +00003007 V = V ^ RefVal::ErrorDeallocGC;
3008 hasErr = V.getKind();
3009 break;
3010 }
3011
3012 switch (V.getKind()) {
3013 default:
3014 llvm_unreachable("Invalid RefVal state for an explicit dealloc.");
Jordy Rosee0a5d322011-08-23 20:27:16 +00003015 case RefVal::Owned:
3016 // The object immediately transitions to the released state.
3017 V = V ^ RefVal::Released;
3018 V.clearCounts();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003019 return setRefBinding(state, sym, V);
Jordy Rosee0a5d322011-08-23 20:27:16 +00003020 case RefVal::NotOwned:
3021 V = V ^ RefVal::ErrorDeallocNotOwned;
3022 hasErr = V.getKind();
3023 break;
3024 }
3025 break;
3026
Jordy Rosee0a5d322011-08-23 20:27:16 +00003027 case MayEscape:
3028 if (V.getKind() == RefVal::Owned) {
3029 V = V ^ RefVal::NotOwned;
3030 break;
3031 }
3032
3033 // Fall-through.
3034
Jordy Rosee0a5d322011-08-23 20:27:16 +00003035 case DoNothing:
3036 return state;
3037
3038 case Autorelease:
Jordy Rose17a38e22011-09-02 05:55:19 +00003039 if (C.isObjCGCEnabled())
Jordy Rosee0a5d322011-08-23 20:27:16 +00003040 return state;
Jordy Rosee0a5d322011-08-23 20:27:16 +00003041 // Update the autorelease counts.
Jordy Rosee0a5d322011-08-23 20:27:16 +00003042 V = V.autorelease();
3043 break;
3044
3045 case StopTracking:
Anna Zaks554067f2012-08-29 23:23:43 +00003046 case StopTrackingHard:
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003047 return removeRefBinding(state, sym);
Jordy Rosee0a5d322011-08-23 20:27:16 +00003048
3049 case IncRef:
3050 switch (V.getKind()) {
3051 default:
3052 llvm_unreachable("Invalid RefVal state for a retain.");
Jordy Rosee0a5d322011-08-23 20:27:16 +00003053 case RefVal::Owned:
3054 case RefVal::NotOwned:
3055 V = V + 1;
3056 break;
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::Owned) + 1;
3061 break;
3062 }
3063 break;
3064
Jordy Rosee0a5d322011-08-23 20:27:16 +00003065 case DecRef:
3066 case DecRefBridgedTransfered:
Anna Zaks554067f2012-08-29 23:23:43 +00003067 case DecRefAndStopTrackingHard:
Jordy Rosee0a5d322011-08-23 20:27:16 +00003068 switch (V.getKind()) {
3069 default:
3070 // case 'RefVal::Released' handled above.
3071 llvm_unreachable("Invalid RefVal state for a release.");
Jordy Rosee0a5d322011-08-23 20:27:16 +00003072
3073 case RefVal::Owned:
3074 assert(V.getCount() > 0);
3075 if (V.getCount() == 1)
3076 V = V ^ (E == DecRefBridgedTransfered ?
3077 RefVal::NotOwned : RefVal::Released);
Anna Zaks554067f2012-08-29 23:23:43 +00003078 else if (E == DecRefAndStopTrackingHard)
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003079 return removeRefBinding(state, sym);
Jordan Rose4531b7d2012-07-02 19:27:43 +00003080
Jordy Rosee0a5d322011-08-23 20:27:16 +00003081 V = V - 1;
3082 break;
3083
3084 case RefVal::NotOwned:
Jordan Rose4531b7d2012-07-02 19:27:43 +00003085 if (V.getCount() > 0) {
Anna Zaks554067f2012-08-29 23:23:43 +00003086 if (E == DecRefAndStopTrackingHard)
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003087 return removeRefBinding(state, sym);
Jordy Rosee0a5d322011-08-23 20:27:16 +00003088 V = V - 1;
Jordan Rose4531b7d2012-07-02 19:27:43 +00003089 } else {
Jordy Rosee0a5d322011-08-23 20:27:16 +00003090 V = V ^ RefVal::ErrorReleaseNotOwned;
3091 hasErr = V.getKind();
3092 }
3093 break;
3094
3095 case RefVal::Released:
3096 // Non-GC cases are handled above.
Jordy Rose17a38e22011-09-02 05:55:19 +00003097 assert(C.isObjCGCEnabled());
Jordy Rosee0a5d322011-08-23 20:27:16 +00003098 V = V ^ RefVal::ErrorUseAfterRelease;
3099 hasErr = V.getKind();
3100 break;
3101 }
3102 break;
3103 }
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003104 return setRefBinding(state, sym, V);
Jordy Rosee0a5d322011-08-23 20:27:16 +00003105}
3106
Ted Kremenek8bef8232012-01-26 21:29:00 +00003107void RetainCountChecker::processNonLeakError(ProgramStateRef St,
Jordy Rose910c4052011-09-02 06:44:22 +00003108 SourceRange ErrorRange,
3109 RefVal::Kind ErrorKind,
3110 SymbolRef Sym,
3111 CheckerContext &C) const {
Jordy Rose294396b2011-08-22 23:48:23 +00003112 ExplodedNode *N = C.generateSink(St);
3113 if (!N)
3114 return;
3115
Jordy Rose294396b2011-08-22 23:48:23 +00003116 CFRefBug *BT;
3117 switch (ErrorKind) {
3118 default:
3119 llvm_unreachable("Unhandled error.");
Jordy Rose294396b2011-08-22 23:48:23 +00003120 case RefVal::ErrorUseAfterRelease:
Jordy Rosed6334e12011-08-25 00:34:03 +00003121 if (!useAfterRelease)
3122 useAfterRelease.reset(new UseAfterRelease());
3123 BT = &*useAfterRelease;
Jordy Rose294396b2011-08-22 23:48:23 +00003124 break;
3125 case RefVal::ErrorReleaseNotOwned:
Jordy Rosed6334e12011-08-25 00:34:03 +00003126 if (!releaseNotOwned)
3127 releaseNotOwned.reset(new BadRelease());
3128 BT = &*releaseNotOwned;
Jordy Rose294396b2011-08-22 23:48:23 +00003129 break;
3130 case RefVal::ErrorDeallocGC:
Jordy Rosed6334e12011-08-25 00:34:03 +00003131 if (!deallocGC)
3132 deallocGC.reset(new DeallocGC());
3133 BT = &*deallocGC;
Jordy Rose294396b2011-08-22 23:48:23 +00003134 break;
3135 case RefVal::ErrorDeallocNotOwned:
Jordy Rosed6334e12011-08-25 00:34:03 +00003136 if (!deallocNotOwned)
3137 deallocNotOwned.reset(new DeallocNotOwned());
3138 BT = &*deallocNotOwned;
Jordy Rose294396b2011-08-22 23:48:23 +00003139 break;
3140 }
3141
Jordy Rosed6334e12011-08-25 00:34:03 +00003142 assert(BT);
David Blaikie4e4d0842012-03-11 07:00:24 +00003143 CFRefReport *report = new CFRefReport(*BT, C.getASTContext().getLangOpts(),
Jordy Rose17a38e22011-09-02 05:55:19 +00003144 C.isObjCGCEnabled(), SummaryLog,
3145 N, Sym);
Jordy Rose294396b2011-08-22 23:48:23 +00003146 report->addRange(ErrorRange);
Jordan Rose785950e2012-11-02 01:53:40 +00003147 C.emitReport(report);
Jordy Rose294396b2011-08-22 23:48:23 +00003148}
3149
Jordy Rose910c4052011-09-02 06:44:22 +00003150//===----------------------------------------------------------------------===//
3151// Handle the return values of retain-count-related functions.
3152//===----------------------------------------------------------------------===//
3153
3154bool RetainCountChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
Jordy Rose76c506f2011-08-21 21:58:18 +00003155 // Get the callee. We're only interested in simple C functions.
Ted Kremenek8bef8232012-01-26 21:29:00 +00003156 ProgramStateRef state = C.getState();
Anna Zaksb805c8f2011-12-01 05:57:37 +00003157 const FunctionDecl *FD = C.getCalleeDecl(CE);
Jordy Rose76c506f2011-08-21 21:58:18 +00003158 if (!FD)
3159 return false;
3160
3161 IdentifierInfo *II = FD->getIdentifier();
3162 if (!II)
3163 return false;
3164
3165 // For now, we're only handling the functions that return aliases of their
3166 // arguments: CFRetain and CFMakeCollectable (and their families).
3167 // Eventually we should add other functions we can model entirely,
3168 // such as CFRelease, which don't invalidate their arguments or globals.
3169 if (CE->getNumArgs() != 1)
3170 return false;
3171
3172 // Get the name of the function.
3173 StringRef FName = II->getName();
3174 FName = FName.substr(FName.find_first_not_of('_'));
3175
3176 // See if it's one of the specific functions we know how to eval.
3177 bool canEval = false;
3178
Anna Zaksb805c8f2011-12-01 05:57:37 +00003179 QualType ResultTy = CE->getCallReturnType();
Jordy Rose76c506f2011-08-21 21:58:18 +00003180 if (ResultTy->isObjCIdType()) {
3181 // Handle: id NSMakeCollectable(CFTypeRef)
3182 canEval = II->isStr("NSMakeCollectable");
3183 } else if (ResultTy->isPointerType()) {
3184 // Handle: (CF|CG)Retain
3185 // CFMakeCollectable
3186 // It's okay to be a little sloppy here (CGMakeCollectable doesn't exist).
3187 if (cocoa::isRefType(ResultTy, "CF", FName) ||
3188 cocoa::isRefType(ResultTy, "CG", FName)) {
3189 canEval = isRetain(FD, FName) || isMakeCollectable(FD, FName);
3190 }
3191 }
3192
3193 if (!canEval)
3194 return false;
3195
3196 // Bind the return value.
Ted Kremenek5eca4822012-01-06 22:09:28 +00003197 const LocationContext *LCtx = C.getLocationContext();
3198 SVal RetVal = state->getSVal(CE->getArg(0), LCtx);
Jordy Rose76c506f2011-08-21 21:58:18 +00003199 if (RetVal.isUnknown()) {
3200 // If the receiver is unknown, conjure a return value.
3201 SValBuilder &SVB = C.getSValBuilder();
Ted Kremenek66c486f2012-08-22 06:26:15 +00003202 RetVal = SVB.conjureSymbolVal(0, CE, LCtx, ResultTy, C.blockCount());
Jordy Rose76c506f2011-08-21 21:58:18 +00003203 }
Ted Kremenek5eca4822012-01-06 22:09:28 +00003204 state = state->BindExpr(CE, LCtx, RetVal, false);
Jordy Rose76c506f2011-08-21 21:58:18 +00003205
Jordy Rose294396b2011-08-22 23:48:23 +00003206 // FIXME: This should not be necessary, but otherwise the argument seems to be
3207 // considered alive during the next statement.
3208 if (const MemRegion *ArgRegion = RetVal.getAsRegion()) {
3209 // Save the refcount status of the argument.
3210 SymbolRef Sym = RetVal.getAsLocSymbol();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003211 const RefVal *Binding = 0;
Jordy Rose294396b2011-08-22 23:48:23 +00003212 if (Sym)
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003213 Binding = getRefBinding(state, Sym);
Jordy Rose76c506f2011-08-21 21:58:18 +00003214
Jordy Rose294396b2011-08-22 23:48:23 +00003215 // Invalidate the argument region.
Anna Zaksbf53dfa2012-12-20 00:38:25 +00003216 state = state->invalidateRegions(ArgRegion, CE, C.blockCount(), LCtx,
Anna Zaks64eb0702013-01-16 01:35:54 +00003217 /*CausesPointerEscape*/ false);
Jordy Rose76c506f2011-08-21 21:58:18 +00003218
Jordy Rose294396b2011-08-22 23:48:23 +00003219 // Restore the refcount status of the argument.
3220 if (Binding)
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003221 state = setRefBinding(state, Sym, *Binding);
Jordy Rose294396b2011-08-22 23:48:23 +00003222 }
3223
Anna Zaks0bd6b112011-10-26 21:06:34 +00003224 C.addTransition(state);
Jordy Rose76c506f2011-08-21 21:58:18 +00003225 return true;
3226}
3227
Jordy Rose910c4052011-09-02 06:44:22 +00003228//===----------------------------------------------------------------------===//
3229// Handle return statements.
3230//===----------------------------------------------------------------------===//
Jordy Rosef53e8c72011-08-23 19:43:16 +00003231
Jordy Rose910c4052011-09-02 06:44:22 +00003232void RetainCountChecker::checkPreStmt(const ReturnStmt *S,
3233 CheckerContext &C) const {
Ted Kremeneke5715782012-02-25 02:09:09 +00003234
3235 // Only adjust the reference count if this is the top-level call frame,
3236 // and not the result of inlining. In the future, we should do
3237 // better checking even for inlined calls, and see if they match
3238 // with their expected semantics (e.g., the method should return a retained
3239 // object, etc.).
Anna Zaksfadcd5d2012-11-03 02:54:16 +00003240 if (!C.inTopFrame())
Ted Kremeneke5715782012-02-25 02:09:09 +00003241 return;
3242
Jordy Rosef53e8c72011-08-23 19:43:16 +00003243 const Expr *RetE = S->getRetValue();
3244 if (!RetE)
3245 return;
3246
Ted Kremenek8bef8232012-01-26 21:29:00 +00003247 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00003248 SymbolRef Sym =
3249 state->getSValAsScalarOrLoc(RetE, C.getLocationContext()).getAsLocSymbol();
Jordy Rosef53e8c72011-08-23 19:43:16 +00003250 if (!Sym)
3251 return;
3252
3253 // Get the reference count binding (if any).
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003254 const RefVal *T = getRefBinding(state, Sym);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003255 if (!T)
3256 return;
3257
3258 // Change the reference count.
3259 RefVal X = *T;
3260
3261 switch (X.getKind()) {
3262 case RefVal::Owned: {
3263 unsigned cnt = X.getCount();
3264 assert(cnt > 0);
3265 X.setCount(cnt - 1);
3266 X = X ^ RefVal::ReturnedOwned;
3267 break;
3268 }
3269
3270 case RefVal::NotOwned: {
3271 unsigned cnt = X.getCount();
3272 if (cnt) {
3273 X.setCount(cnt - 1);
3274 X = X ^ RefVal::ReturnedOwned;
3275 }
3276 else {
3277 X = X ^ RefVal::ReturnedNotOwned;
3278 }
3279 break;
3280 }
3281
3282 default:
3283 return;
3284 }
3285
3286 // Update the binding.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003287 state = setRefBinding(state, Sym, X);
Anna Zaks0bd6b112011-10-26 21:06:34 +00003288 ExplodedNode *Pred = C.addTransition(state);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003289
3290 // At this point we have updated the state properly.
3291 // Everything after this is merely checking to see if the return value has
3292 // been over- or under-retained.
3293
3294 // Did we cache out?
3295 if (!Pred)
3296 return;
3297
Jordy Rosef53e8c72011-08-23 19:43:16 +00003298 // Update the autorelease counts.
3299 static SimpleProgramPointTag
Jordy Rose910c4052011-09-02 06:44:22 +00003300 AutoreleaseTag("RetainCountChecker : Autorelease");
Jordan Rose4ee1c552012-12-06 18:58:18 +00003301 state = handleAutoreleaseCounts(state, Pred, &AutoreleaseTag, C, Sym, X);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003302
3303 // Did we cache out?
Jordan Rose4ee1c552012-12-06 18:58:18 +00003304 if (!state)
Jordy Rosef53e8c72011-08-23 19:43:16 +00003305 return;
3306
3307 // Get the updated binding.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003308 T = getRefBinding(state, Sym);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003309 assert(T);
3310 X = *T;
3311
3312 // Consult the summary of the enclosing method.
Jordy Rose17a38e22011-09-02 05:55:19 +00003313 RetainSummaryManager &Summaries = getSummaryManager(C);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003314 const Decl *CD = &Pred->getCodeDecl();
Jordan Rose4531b7d2012-07-02 19:27:43 +00003315 RetEffect RE = RetEffect::MakeNoRet();
Jordy Rosef53e8c72011-08-23 19:43:16 +00003316
Jordan Rose4531b7d2012-07-02 19:27:43 +00003317 // FIXME: What is the convention for blocks? Is there one?
Jordy Rosef53e8c72011-08-23 19:43:16 +00003318 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CD)) {
Jordy Roseb6cfc092011-08-25 00:10:37 +00003319 const RetainSummary *Summ = Summaries.getMethodSummary(MD);
Jordan Rose4531b7d2012-07-02 19:27:43 +00003320 RE = Summ->getRetEffect();
3321 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) {
3322 if (!isa<CXXMethodDecl>(FD)) {
3323 const RetainSummary *Summ = Summaries.getFunctionSummary(FD);
3324 RE = Summ->getRetEffect();
3325 }
Jordy Rosef53e8c72011-08-23 19:43:16 +00003326 }
3327
Jordan Rose4531b7d2012-07-02 19:27:43 +00003328 checkReturnWithRetEffect(S, C, Pred, RE, X, Sym, state);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003329}
3330
Jordy Rose910c4052011-09-02 06:44:22 +00003331void RetainCountChecker::checkReturnWithRetEffect(const ReturnStmt *S,
3332 CheckerContext &C,
3333 ExplodedNode *Pred,
3334 RetEffect RE, RefVal X,
3335 SymbolRef Sym,
Ted Kremenek8bef8232012-01-26 21:29:00 +00003336 ProgramStateRef state) const {
Jordy Rosef53e8c72011-08-23 19:43:16 +00003337 // Any leaks or other errors?
3338 if (X.isReturnedOwned() && X.getCount() == 0) {
3339 if (RE.getKind() != RetEffect::NoRet) {
3340 bool hasError = false;
Jordy Rose17a38e22011-09-02 05:55:19 +00003341 if (C.isObjCGCEnabled() && RE.getObjKind() == RetEffect::ObjC) {
Jordy Rosef53e8c72011-08-23 19:43:16 +00003342 // Things are more complicated with garbage collection. If the
3343 // returned object is suppose to be an Objective-C object, we have
3344 // a leak (as the caller expects a GC'ed object) because no
3345 // method should return ownership unless it returns a CF object.
3346 hasError = true;
3347 X = X ^ RefVal::ErrorGCLeakReturned;
3348 }
3349 else if (!RE.isOwned()) {
3350 // Either we are using GC and the returned object is a CF type
3351 // or we aren't using GC. In either case, we expect that the
3352 // enclosing method is expected to return ownership.
3353 hasError = true;
3354 X = X ^ RefVal::ErrorLeakReturned;
3355 }
3356
3357 if (hasError) {
3358 // Generate an error node.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003359 state = setRefBinding(state, Sym, X);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003360
3361 static SimpleProgramPointTag
Jordy Rose910c4052011-09-02 06:44:22 +00003362 ReturnOwnLeakTag("RetainCountChecker : ReturnsOwnLeak");
Anna Zaks0bd6b112011-10-26 21:06:34 +00003363 ExplodedNode *N = C.addTransition(state, Pred, &ReturnOwnLeakTag);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003364 if (N) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003365 const LangOptions &LOpts = C.getASTContext().getLangOpts();
Jordy Rose17a38e22011-09-02 05:55:19 +00003366 bool GCEnabled = C.isObjCGCEnabled();
Jordy Rosef53e8c72011-08-23 19:43:16 +00003367 CFRefReport *report =
Jordy Rose17a38e22011-09-02 05:55:19 +00003368 new CFRefLeakReport(*getLeakAtReturnBug(LOpts, GCEnabled),
3369 LOpts, GCEnabled, SummaryLog,
Ted Kremenek08a838d2013-04-16 21:44:22 +00003370 N, Sym, C, IncludeAllocationLine);
3371
Jordan Rose785950e2012-11-02 01:53:40 +00003372 C.emitReport(report);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003373 }
3374 }
3375 }
3376 } else if (X.isReturnedNotOwned()) {
3377 if (RE.isOwned()) {
3378 // Trying to return a not owned object to a caller expecting an
3379 // owned object.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003380 state = setRefBinding(state, Sym, X ^ RefVal::ErrorReturnedNotOwned);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003381
3382 static SimpleProgramPointTag
Jordy Rose910c4052011-09-02 06:44:22 +00003383 ReturnNotOwnedTag("RetainCountChecker : ReturnNotOwnedForOwned");
Anna Zaks0bd6b112011-10-26 21:06:34 +00003384 ExplodedNode *N = C.addTransition(state, Pred, &ReturnNotOwnedTag);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003385 if (N) {
Jordy Rosed6334e12011-08-25 00:34:03 +00003386 if (!returnNotOwnedForOwned)
3387 returnNotOwnedForOwned.reset(new ReturnedNotOwnedForOwned());
3388
Jordy Rosef53e8c72011-08-23 19:43:16 +00003389 CFRefReport *report =
Jordy Rosed6334e12011-08-25 00:34:03 +00003390 new CFRefReport(*returnNotOwnedForOwned,
David Blaikie4e4d0842012-03-11 07:00:24 +00003391 C.getASTContext().getLangOpts(),
Jordy Rose17a38e22011-09-02 05:55:19 +00003392 C.isObjCGCEnabled(), SummaryLog, N, Sym);
Jordan Rose785950e2012-11-02 01:53:40 +00003393 C.emitReport(report);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003394 }
3395 }
3396 }
3397}
3398
Jordy Rose8d228632011-08-23 20:07:14 +00003399//===----------------------------------------------------------------------===//
Jordy Rose910c4052011-09-02 06:44:22 +00003400// Check various ways a symbol can be invalidated.
3401//===----------------------------------------------------------------------===//
3402
Anna Zaks390909c2011-10-06 00:43:15 +00003403void RetainCountChecker::checkBind(SVal loc, SVal val, const Stmt *S,
Jordy Rose910c4052011-09-02 06:44:22 +00003404 CheckerContext &C) const {
3405 // Are we storing to something that causes the value to "escape"?
3406 bool escapes = true;
3407
3408 // A value escapes in three possible cases (this may change):
3409 //
3410 // (1) we are binding to something that is not a memory region.
3411 // (2) we are binding to a memregion that does not have stack storage
3412 // (3) we are binding to a memregion with stack storage that the store
3413 // does not understand.
Ted Kremenek8bef8232012-01-26 21:29:00 +00003414 ProgramStateRef state = C.getState();
Jordy Rose910c4052011-09-02 06:44:22 +00003415
David Blaikiedc84cd52013-02-20 22:23:23 +00003416 if (Optional<loc::MemRegionVal> regionLoc = loc.getAs<loc::MemRegionVal>()) {
Jordy Rose910c4052011-09-02 06:44:22 +00003417 escapes = !regionLoc->getRegion()->hasStackStorage();
3418
3419 if (!escapes) {
3420 // To test (3), generate a new state with the binding added. If it is
3421 // the same state, then it escapes (since the store cannot represent
3422 // the binding).
Anna Zakse7958da2012-05-02 00:15:40 +00003423 // Do this only if we know that the store is not supposed to generate the
3424 // same state.
3425 SVal StoredVal = state->getSVal(regionLoc->getRegion());
3426 if (StoredVal != val)
3427 escapes = (state == (state->bindLoc(*regionLoc, val)));
Jordy Rose910c4052011-09-02 06:44:22 +00003428 }
Ted Kremenekde5b4fb2012-03-27 01:12:45 +00003429 if (!escapes) {
3430 // Case 4: We do not currently model what happens when a symbol is
3431 // assigned to a struct field, so be conservative here and let the symbol
3432 // go. TODO: This could definitely be improved upon.
3433 escapes = !isa<VarRegion>(regionLoc->getRegion());
3434 }
Jordy Rose910c4052011-09-02 06:44:22 +00003435 }
3436
3437 // If our store can represent the binding and we aren't storing to something
3438 // that doesn't have local storage then just return and have the simulation
3439 // state continue as is.
3440 if (!escapes)
3441 return;
3442
3443 // Otherwise, find all symbols referenced by 'val' that we are tracking
3444 // and stop tracking them.
3445 state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
Anna Zaks0bd6b112011-10-26 21:06:34 +00003446 C.addTransition(state);
Jordy Rose910c4052011-09-02 06:44:22 +00003447}
3448
Ted Kremenek8bef8232012-01-26 21:29:00 +00003449ProgramStateRef RetainCountChecker::evalAssume(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003450 SVal Cond,
3451 bool Assumption) const {
3452
3453 // FIXME: We may add to the interface of evalAssume the list of symbols
3454 // whose assumptions have changed. For now we just iterate through the
3455 // bindings and check if any of the tracked symbols are NULL. This isn't
3456 // too bad since the number of symbols we will track in practice are
3457 // probably small and evalAssume is only called at branches and a few
3458 // other places.
Jordan Rose166d5022012-11-02 01:54:06 +00003459 RefBindingsTy B = state->get<RefBindings>();
Jordy Rose910c4052011-09-02 06:44:22 +00003460
3461 if (B.isEmpty())
3462 return state;
3463
3464 bool changed = false;
Jordan Rose166d5022012-11-02 01:54:06 +00003465 RefBindingsTy::Factory &RefBFactory = state->get_context<RefBindings>();
Jordy Rose910c4052011-09-02 06:44:22 +00003466
Jordan Rose166d5022012-11-02 01:54:06 +00003467 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Ted Kremenek47cbd0f2012-09-07 22:31:01 +00003468 // Check if the symbol is null stop tracking the symbol.
Jordan Roseec8d4202012-11-01 00:18:27 +00003469 ConstraintManager &CMgr = state->getConstraintManager();
3470 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
3471 if (AllocFailed.isConstrainedTrue()) {
Jordy Rose910c4052011-09-02 06:44:22 +00003472 changed = true;
3473 B = RefBFactory.remove(B, I.getKey());
3474 }
3475 }
3476
3477 if (changed)
3478 state = state->set<RefBindings>(B);
3479
3480 return state;
3481}
3482
Ted Kremenek8bef8232012-01-26 21:29:00 +00003483ProgramStateRef
3484RetainCountChecker::checkRegionChanges(ProgramStateRef state,
Anna Zaksbf53dfa2012-12-20 00:38:25 +00003485 const InvalidatedSymbols *invalidated,
Jordy Rose910c4052011-09-02 06:44:22 +00003486 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00003487 ArrayRef<const MemRegion *> Regions,
Jordan Rose740d4902012-07-02 19:27:35 +00003488 const CallEvent *Call) const {
Jordy Rose910c4052011-09-02 06:44:22 +00003489 if (!invalidated)
3490 return state;
3491
3492 llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
3493 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
3494 E = ExplicitRegions.end(); I != E; ++I) {
3495 if (const SymbolicRegion *SR = (*I)->StripCasts()->getAs<SymbolicRegion>())
3496 WhitelistedSymbols.insert(SR->getSymbol());
3497 }
3498
Anna Zaksbf53dfa2012-12-20 00:38:25 +00003499 for (InvalidatedSymbols::const_iterator I=invalidated->begin(),
Jordy Rose910c4052011-09-02 06:44:22 +00003500 E = invalidated->end(); I!=E; ++I) {
3501 SymbolRef sym = *I;
3502 if (WhitelistedSymbols.count(sym))
3503 continue;
3504 // Remove any existing reference-count binding.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003505 state = removeRefBinding(state, sym);
Jordy Rose910c4052011-09-02 06:44:22 +00003506 }
3507 return state;
3508}
3509
3510//===----------------------------------------------------------------------===//
Jordy Rose8d228632011-08-23 20:07:14 +00003511// Handle dead symbols and end-of-path.
3512//===----------------------------------------------------------------------===//
3513
Jordan Rose4ee1c552012-12-06 18:58:18 +00003514ProgramStateRef
3515RetainCountChecker::handleAutoreleaseCounts(ProgramStateRef state,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003516 ExplodedNode *Pred,
Jordan Rose2bce86c2012-08-18 00:30:16 +00003517 const ProgramPointTag *Tag,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003518 CheckerContext &Ctx,
Jordy Rose910c4052011-09-02 06:44:22 +00003519 SymbolRef Sym, RefVal V) const {
Jordy Rose8d228632011-08-23 20:07:14 +00003520 unsigned ACnt = V.getAutoreleaseCount();
3521
3522 // No autorelease counts? Nothing to be done.
3523 if (!ACnt)
Jordan Rose4ee1c552012-12-06 18:58:18 +00003524 return state;
Jordy Rose8d228632011-08-23 20:07:14 +00003525
Anna Zaks6a93bd52011-10-25 19:57:11 +00003526 assert(!Ctx.isObjCGCEnabled() && "Autorelease counts in GC mode?");
Jordy Rose8d228632011-08-23 20:07:14 +00003527 unsigned Cnt = V.getCount();
3528
3529 // FIXME: Handle sending 'autorelease' to already released object.
3530
3531 if (V.getKind() == RefVal::ReturnedOwned)
3532 ++Cnt;
3533
3534 if (ACnt <= Cnt) {
3535 if (ACnt == Cnt) {
3536 V.clearCounts();
3537 if (V.getKind() == RefVal::ReturnedOwned)
3538 V = V ^ RefVal::ReturnedNotOwned;
3539 else
3540 V = V ^ RefVal::NotOwned;
3541 } else {
Anna Zaks0217b1d2013-01-31 22:36:17 +00003542 V.setCount(V.getCount() - ACnt);
Jordy Rose8d228632011-08-23 20:07:14 +00003543 V.setAutoreleaseCount(0);
3544 }
Jordan Rose4ee1c552012-12-06 18:58:18 +00003545 return setRefBinding(state, Sym, V);
Jordy Rose8d228632011-08-23 20:07:14 +00003546 }
3547
3548 // Woah! More autorelease counts then retain counts left.
3549 // Emit hard error.
3550 V = V ^ RefVal::ErrorOverAutorelease;
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003551 state = setRefBinding(state, Sym, V);
Jordy Rose8d228632011-08-23 20:07:14 +00003552
Jordan Rosefa06f042012-08-20 18:43:42 +00003553 ExplodedNode *N = Ctx.generateSink(state, Pred, Tag);
Jordan Rose2bce86c2012-08-18 00:30:16 +00003554 if (N) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003555 SmallString<128> sbuf;
Jordy Rose8d228632011-08-23 20:07:14 +00003556 llvm::raw_svector_ostream os(sbuf);
3557 os << "Object over-autoreleased: object was sent -autorelease ";
3558 if (V.getAutoreleaseCount() > 1)
3559 os << V.getAutoreleaseCount() << " times ";
3560 os << "but the object has a +" << V.getCount() << " retain count";
3561
Jordy Rosed6334e12011-08-25 00:34:03 +00003562 if (!overAutorelease)
3563 overAutorelease.reset(new OverAutorelease());
3564
David Blaikie4e4d0842012-03-11 07:00:24 +00003565 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
Jordy Rose8d228632011-08-23 20:07:14 +00003566 CFRefReport *report =
Jordy Rosed6334e12011-08-25 00:34:03 +00003567 new CFRefReport(*overAutorelease, LOpts, /* GCEnabled = */ false,
3568 SummaryLog, N, Sym, os.str());
Jordan Rose785950e2012-11-02 01:53:40 +00003569 Ctx.emitReport(report);
Jordy Rose8d228632011-08-23 20:07:14 +00003570 }
3571
Jordan Rose4ee1c552012-12-06 18:58:18 +00003572 return 0;
Jordy Rose8d228632011-08-23 20:07:14 +00003573}
Jordy Rose38f17d62011-08-23 19:01:07 +00003574
Ted Kremenek8bef8232012-01-26 21:29:00 +00003575ProgramStateRef
3576RetainCountChecker::handleSymbolDeath(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003577 SymbolRef sid, RefVal V,
Jordy Rose38f17d62011-08-23 19:01:07 +00003578 SmallVectorImpl<SymbolRef> &Leaked) const {
Jordy Rose53376122011-08-24 04:48:19 +00003579 bool hasLeak = false;
Jordy Rose38f17d62011-08-23 19:01:07 +00003580 if (V.isOwned())
3581 hasLeak = true;
3582 else if (V.isNotOwned() || V.isReturnedOwned())
3583 hasLeak = (V.getCount() > 0);
3584
3585 if (!hasLeak)
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003586 return removeRefBinding(state, sid);
Jordy Rose38f17d62011-08-23 19:01:07 +00003587
3588 Leaked.push_back(sid);
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003589 return setRefBinding(state, sid, V ^ RefVal::ErrorLeak);
Jordy Rose38f17d62011-08-23 19:01:07 +00003590}
3591
3592ExplodedNode *
Ted Kremenek8bef8232012-01-26 21:29:00 +00003593RetainCountChecker::processLeaks(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003594 SmallVectorImpl<SymbolRef> &Leaked,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003595 CheckerContext &Ctx,
3596 ExplodedNode *Pred) const {
Jordy Rose38f17d62011-08-23 19:01:07 +00003597 // Generate an intermediate node representing the leak point.
Jordan Rose2bce86c2012-08-18 00:30:16 +00003598 ExplodedNode *N = Ctx.addTransition(state, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003599
3600 if (N) {
3601 for (SmallVectorImpl<SymbolRef>::iterator
3602 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3603
David Blaikie4e4d0842012-03-11 07:00:24 +00003604 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
Anna Zaks6a93bd52011-10-25 19:57:11 +00003605 bool GCEnabled = Ctx.isObjCGCEnabled();
Jordy Rose17a38e22011-09-02 05:55:19 +00003606 CFRefBug *BT = Pred ? getLeakWithinFunctionBug(LOpts, GCEnabled)
3607 : getLeakAtReturnBug(LOpts, GCEnabled);
Jordy Rose38f17d62011-08-23 19:01:07 +00003608 assert(BT && "BugType not initialized.");
Jordy Rose20589562011-08-24 22:39:09 +00003609
Jordy Rose17a38e22011-09-02 05:55:19 +00003610 CFRefLeakReport *report = new CFRefLeakReport(*BT, LOpts, GCEnabled,
Ted Kremenek08a838d2013-04-16 21:44:22 +00003611 SummaryLog, N, *I, Ctx,
3612 IncludeAllocationLine);
Jordan Rose785950e2012-11-02 01:53:40 +00003613 Ctx.emitReport(report);
Jordy Rose38f17d62011-08-23 19:01:07 +00003614 }
3615 }
3616
3617 return N;
3618}
3619
Anna Zaks344c77a2013-01-03 00:25:29 +00003620void RetainCountChecker::checkEndFunction(CheckerContext &Ctx) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +00003621 ProgramStateRef state = Ctx.getState();
Jordan Rose166d5022012-11-02 01:54:06 +00003622 RefBindingsTy B = state->get<RefBindings>();
Anna Zaksaf498a22011-10-25 19:56:48 +00003623 ExplodedNode *Pred = Ctx.getPredecessor();
Jordy Rose38f17d62011-08-23 19:01:07 +00003624
Jordan Rose166d5022012-11-02 01:54:06 +00003625 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Jordan Rose4ee1c552012-12-06 18:58:18 +00003626 state = handleAutoreleaseCounts(state, Pred, /*Tag=*/0, Ctx,
3627 I->first, I->second);
Jordy Rose8d228632011-08-23 20:07:14 +00003628 if (!state)
Jordy Rose38f17d62011-08-23 19:01:07 +00003629 return;
3630 }
3631
Ted Kremenek0cf3d472012-02-07 00:24:33 +00003632 // If the current LocationContext has a parent, don't check for leaks.
3633 // We will do that later.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003634 // FIXME: we should instead check for imbalances of the retain/releases,
Ted Kremenek0cf3d472012-02-07 00:24:33 +00003635 // and suggest annotations.
3636 if (Ctx.getLocationContext()->getParent())
3637 return;
3638
Jordy Rose38f17d62011-08-23 19:01:07 +00003639 B = state->get<RefBindings>();
3640 SmallVector<SymbolRef, 10> Leaked;
3641
Jordan Rose166d5022012-11-02 01:54:06 +00003642 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I)
Jordy Rose8d228632011-08-23 20:07:14 +00003643 state = handleSymbolDeath(state, I->first, I->second, Leaked);
Jordy Rose38f17d62011-08-23 19:01:07 +00003644
Jordan Rose2bce86c2012-08-18 00:30:16 +00003645 processLeaks(state, Leaked, Ctx, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003646}
3647
3648const ProgramPointTag *
Jordy Rose910c4052011-09-02 06:44:22 +00003649RetainCountChecker::getDeadSymbolTag(SymbolRef sym) const {
Jordy Rose38f17d62011-08-23 19:01:07 +00003650 const SimpleProgramPointTag *&tag = DeadSymbolTags[sym];
3651 if (!tag) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003652 SmallString<64> buf;
Jordy Rose38f17d62011-08-23 19:01:07 +00003653 llvm::raw_svector_ostream out(buf);
Anna Zaksf62ceec2011-12-05 18:58:11 +00003654 out << "RetainCountChecker : Dead Symbol : ";
3655 sym->dumpToStream(out);
Jordy Rose38f17d62011-08-23 19:01:07 +00003656 tag = new SimpleProgramPointTag(out.str());
3657 }
3658 return tag;
3659}
3660
Jordy Rose910c4052011-09-02 06:44:22 +00003661void RetainCountChecker::checkDeadSymbols(SymbolReaper &SymReaper,
3662 CheckerContext &C) const {
Jordy Rose38f17d62011-08-23 19:01:07 +00003663 ExplodedNode *Pred = C.getPredecessor();
3664
Ted Kremenek8bef8232012-01-26 21:29:00 +00003665 ProgramStateRef state = C.getState();
Jordan Rose166d5022012-11-02 01:54:06 +00003666 RefBindingsTy B = state->get<RefBindings>();
Jordan Rose4ee1c552012-12-06 18:58:18 +00003667 SmallVector<SymbolRef, 10> Leaked;
Jordy Rose38f17d62011-08-23 19:01:07 +00003668
3669 // Update counts from autorelease pools
3670 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3671 E = SymReaper.dead_end(); I != E; ++I) {
3672 SymbolRef Sym = *I;
3673 if (const RefVal *T = B.lookup(Sym)){
3674 // Use the symbol as the tag.
3675 // FIXME: This might not be as unique as we would like.
Jordan Rose2bce86c2012-08-18 00:30:16 +00003676 const ProgramPointTag *Tag = getDeadSymbolTag(Sym);
Jordan Rose4ee1c552012-12-06 18:58:18 +00003677 state = handleAutoreleaseCounts(state, Pred, Tag, C, Sym, *T);
Jordy Rose8d228632011-08-23 20:07:14 +00003678 if (!state)
Jordy Rose38f17d62011-08-23 19:01:07 +00003679 return;
Jordan Rose4ee1c552012-12-06 18:58:18 +00003680
3681 // Fetch the new reference count from the state, and use it to handle
3682 // this symbol.
3683 state = handleSymbolDeath(state, *I, *getRefBinding(state, Sym), Leaked);
Jordy Rose38f17d62011-08-23 19:01:07 +00003684 }
3685 }
3686
Jordan Rose4ee1c552012-12-06 18:58:18 +00003687 if (Leaked.empty()) {
3688 C.addTransition(state);
3689 return;
Jordy Rose38f17d62011-08-23 19:01:07 +00003690 }
3691
Jordan Rose2bce86c2012-08-18 00:30:16 +00003692 Pred = processLeaks(state, Leaked, C, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003693
3694 // Did we cache out?
3695 if (!Pred)
3696 return;
3697
3698 // Now generate a new node that nukes the old bindings.
Jordan Rose4ee1c552012-12-06 18:58:18 +00003699 // The only bindings left at this point are the leaked symbols.
Jordan Rose166d5022012-11-02 01:54:06 +00003700 RefBindingsTy::Factory &F = state->get_context<RefBindings>();
Jordan Rose4ee1c552012-12-06 18:58:18 +00003701 B = state->get<RefBindings>();
Jordy Rose38f17d62011-08-23 19:01:07 +00003702
Jordan Rose4ee1c552012-12-06 18:58:18 +00003703 for (SmallVectorImpl<SymbolRef>::iterator I = Leaked.begin(),
3704 E = Leaked.end();
3705 I != E; ++I)
Jordy Rose38f17d62011-08-23 19:01:07 +00003706 B = F.remove(B, *I);
3707
3708 state = state->set<RefBindings>(B);
Anna Zaks0bd6b112011-10-26 21:06:34 +00003709 C.addTransition(state, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003710}
3711
Ted Kremenek8bef8232012-01-26 21:29:00 +00003712void RetainCountChecker::printState(raw_ostream &Out, ProgramStateRef State,
Jordy Rose910c4052011-09-02 06:44:22 +00003713 const char *NL, const char *Sep) const {
Jordy Rosedbd658e2011-08-28 19:11:56 +00003714
Jordan Rose166d5022012-11-02 01:54:06 +00003715 RefBindingsTy B = State->get<RefBindings>();
Jordy Rosedbd658e2011-08-28 19:11:56 +00003716
Ted Kremenek65a08922013-03-28 18:43:18 +00003717 if (B.isEmpty())
3718 return;
3719
3720 Out << Sep << NL;
Jordy Rosedbd658e2011-08-28 19:11:56 +00003721
Jordan Rose166d5022012-11-02 01:54:06 +00003722 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Jordy Rosedbd658e2011-08-28 19:11:56 +00003723 Out << I->first << " : ";
3724 I->second.print(Out);
3725 Out << NL;
3726 }
Jordy Rosedbd658e2011-08-28 19:11:56 +00003727}
3728
3729//===----------------------------------------------------------------------===//
Jordy Rose910c4052011-09-02 06:44:22 +00003730// Checker registration.
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00003731//===----------------------------------------------------------------------===//
3732
Jordy Rose17a38e22011-09-02 05:55:19 +00003733void ento::registerRetainCountChecker(CheckerManager &Mgr) {
Ted Kremenek08a838d2013-04-16 21:44:22 +00003734 Mgr.registerChecker<RetainCountChecker>(Mgr.getAnalyzerOptions());
Jordy Rose17a38e22011-09-02 05:55:19 +00003735}
3736