blob: c681c81086797164651d290a6d253b7f25efeaee [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:
Jordan Rose2545b1d2013-04-23 01:42:25 +0000329 Out << "Over-autoreleased";
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000330 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);
Jordan Rose8a729b42013-05-02 01:51:40 +00001119 } else if (FName == "dispatch_set_context" ||
1120 FName == "xpc_connection_set_context") {
Ted Kremenek06911d42012-03-22 06:29:41 +00001121 // <rdar://problem/11059275> - The analyzer currently doesn't have
1122 // a good way to reason about the finalizer function for libdispatch.
1123 // If we pass a context object that is memory managed, stop tracking it.
Jordan Rose8a729b42013-05-02 01:51:40 +00001124 // <rdar://problem/13783514> - Same problem, but for XPC.
Ted Kremenek06911d42012-03-22 06:29:41 +00001125 // FIXME: this hack should possibly go away once we can handle
Jordan Rose8a729b42013-05-02 01:51:40 +00001126 // libdispatch and XPC finalizers.
Ted Kremenek06911d42012-03-22 06:29:41 +00001127 ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
1128 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenekc91fdf62012-05-08 00:12:09 +00001129 } else if (FName.startswith("NSLog")) {
1130 S = getDoNothingSummary();
Anna Zaks62a5c342012-03-30 05:48:16 +00001131 } else if (FName.startswith("NS") &&
1132 (FName.find("Insert") != StringRef::npos)) {
1133 // Whitelist NSXXInsertXX, for example NSMapInsertIfAbsent, since they can
1134 // be deallocated by NSMapRemove. (radar://11152419)
1135 ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
1136 ScratchArgs = AF.add(ScratchArgs, 2, StopTracking);
1137 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenekb04cb592009-06-11 18:17:24 +00001138 }
Mike Stump1eb44332009-09-09 15:08:12 +00001139
Ted Kremenekb04cb592009-06-11 18:17:24 +00001140 // Did we get a summary?
1141 if (S)
1142 break;
Ted Kremenek61991902009-03-17 22:43:44 +00001143
Jordan Rose5aff3f12013-03-04 23:21:32 +00001144 if (RetTy->isPointerType()) {
Ted Kremenek12619382009-01-12 21:45:02 +00001145 // For CoreFoundation ('CF') types.
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001146 if (cocoa::isRefType(RetTy, "CF", FName)) {
Ted Kremenek12619382009-01-12 21:45:02 +00001147 if (isRetain(FD, FName))
1148 S = getUnarySummary(FT, cfretain);
Jordy Rose76c506f2011-08-21 21:58:18 +00001149 else if (isMakeCollectable(FD, FName))
Ted Kremenek12619382009-01-12 21:45:02 +00001150 S = getUnarySummary(FT, cfmakecollectable);
Mike Stump1eb44332009-09-09 15:08:12 +00001151 else
John McCall7df2ff42011-10-01 00:48:56 +00001152 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek12619382009-01-12 21:45:02 +00001153
1154 break;
1155 }
1156
1157 // For CoreGraphics ('CG') types.
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001158 if (cocoa::isRefType(RetTy, "CG", FName)) {
Ted Kremenek12619382009-01-12 21:45:02 +00001159 if (isRetain(FD, FName))
1160 S = getUnarySummary(FT, cfretain);
1161 else
John McCall7df2ff42011-10-01 00:48:56 +00001162 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek12619382009-01-12 21:45:02 +00001163
1164 break;
1165 }
1166
1167 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001168 if (cocoa::isRefType(RetTy, "DADisk") ||
1169 cocoa::isRefType(RetTy, "DADissenter") ||
1170 cocoa::isRefType(RetTy, "DASessionRef")) {
John McCall7df2ff42011-10-01 00:48:56 +00001171 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek12619382009-01-12 21:45:02 +00001172 break;
1173 }
Mike Stump1eb44332009-09-09 15:08:12 +00001174
Jordan Rose5aff3f12013-03-04 23:21:32 +00001175 if (FD->getAttr<CFAuditedTransferAttr>()) {
1176 S = getCFCreateGetRuleSummary(FD);
1177 break;
1178 }
1179
Ted Kremenek12619382009-01-12 21:45:02 +00001180 break;
1181 }
1182
1183 // Check for release functions, the only kind of functions that we care
1184 // about that don't return a pointer type.
1185 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
Ted Kremeneke7d03122010-02-08 16:45:01 +00001186 // Test for 'CGCF'.
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001187 FName = FName.substr(FName.startswith("CGCF") ? 4 : 2);
Ted Kremeneke7d03122010-02-08 16:45:01 +00001188
Ted Kremenekbf0a4dd2009-03-05 22:11:14 +00001189 if (isRelease(FD, FName))
Ted Kremenek12619382009-01-12 21:45:02 +00001190 S = getUnarySummary(FT, cfrelease);
1191 else {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001192 assert (ScratchArgs.isEmpty());
Ted Kremenek68189282009-01-29 22:45:13 +00001193 // Remaining CoreFoundation and CoreGraphics functions.
1194 // We use to assume that they all strictly followed the ownership idiom
1195 // and that ownership cannot be transferred. While this is technically
1196 // correct, many methods allow a tracked object to escape. For example:
1197 //
Mike Stump1eb44332009-09-09 15:08:12 +00001198 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
Ted Kremenek68189282009-01-29 22:45:13 +00001199 // CFDictionaryAddValue(y, key, x);
Mike Stump1eb44332009-09-09 15:08:12 +00001200 // CFRelease(x);
Ted Kremenek68189282009-01-29 22:45:13 +00001201 // ... it is okay to use 'x' since 'y' has a reference to it
1202 //
1203 // We handle this and similar cases with the follow heuristic. If the
Ted Kremenekc4843812009-08-20 00:57:22 +00001204 // function name contains "InsertValue", "SetValue", "AddValue",
1205 // "AppendValue", or "SetAttribute", then we assume that arguments may
1206 // "escape." This means that something else holds on to the object,
1207 // allowing it be used even after its local retain count drops to 0.
Benjamin Kramere45c1492010-01-11 19:46:28 +00001208 ArgEffect E = (StrInStrNoCase(FName, "InsertValue") != StringRef::npos||
1209 StrInStrNoCase(FName, "AddValue") != StringRef::npos ||
1210 StrInStrNoCase(FName, "SetValue") != StringRef::npos ||
1211 StrInStrNoCase(FName, "AppendValue") != StringRef::npos||
Benjamin Kramerc027e542010-01-11 20:15:06 +00001212 StrInStrNoCase(FName, "SetAttribute") != StringRef::npos)
Ted Kremenek68189282009-01-29 22:45:13 +00001213 ? MayEscape : DoNothing;
Mike Stump1eb44332009-09-09 15:08:12 +00001214
Ted Kremenek68189282009-01-29 22:45:13 +00001215 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek12619382009-01-12 21:45:02 +00001216 }
1217 }
Ted Kremenek37d785b2008-07-15 16:50:12 +00001218 }
1219 while (0);
Mike Stump1eb44332009-09-09 15:08:12 +00001220
Jordan Rose4531b7d2012-07-02 19:27:43 +00001221 // If we got all the way here without any luck, use a default summary.
1222 if (!S)
1223 S = getDefaultSummary();
1224
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001225 // Annotations override defaults.
Jordan Rose15d18e12012-08-06 21:28:02 +00001226 if (AllowAnnotations)
1227 updateSummaryFromAnnotations(S, FD);
Mike Stump1eb44332009-09-09 15:08:12 +00001228
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001229 FuncSummaries[FD] = S;
Mike Stump1eb44332009-09-09 15:08:12 +00001230 return S;
Ted Kremenek2fff37e2008-03-06 00:08:09 +00001231}
1232
Ted Kremenek93edbc52011-10-05 23:54:29 +00001233const RetainSummary *
John McCall7df2ff42011-10-01 00:48:56 +00001234RetainSummaryManager::getCFCreateGetRuleSummary(const FunctionDecl *FD) {
1235 if (coreFoundation::followsCreateRule(FD))
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001236 return getCFSummaryCreateRule(FD);
Mike Stump1eb44332009-09-09 15:08:12 +00001237
Ted Kremenekd368d712011-05-25 06:19:45 +00001238 return getCFSummaryGetRule(FD);
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001239}
1240
Ted Kremenek93edbc52011-10-05 23:54:29 +00001241const RetainSummary *
Ted Kremenek6ad315a2009-02-23 16:51:39 +00001242RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1243 UnaryFuncKind func) {
1244
Ted Kremenek12619382009-01-12 21:45:02 +00001245 // Sanity check that this is *really* a unary function. This can
1246 // happen if people do weird things.
Douglas Gregor72564e72009-02-26 23:50:07 +00001247 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
Ted Kremenek12619382009-01-12 21:45:02 +00001248 if (!FTP || FTP->getNumArgs() != 1)
1249 return getPersistentStopSummary();
Mike Stump1eb44332009-09-09 15:08:12 +00001250
Ted Kremenekb77449c2009-05-03 05:20:50 +00001251 assert (ScratchArgs.isEmpty());
Mike Stump1eb44332009-09-09 15:08:12 +00001252
Jordy Rose76c506f2011-08-21 21:58:18 +00001253 ArgEffect Effect;
Ted Kremenek377e2302008-04-29 05:33:51 +00001254 switch (func) {
Jordy Rose76c506f2011-08-21 21:58:18 +00001255 case cfretain: Effect = IncRef; break;
1256 case cfrelease: Effect = DecRef; break;
1257 case cfmakecollectable: Effect = MakeCollectable; break;
Ted Kremenek940b1d82008-04-10 23:44:06 +00001258 }
Jordy Rose76c506f2011-08-21 21:58:18 +00001259
1260 ScratchArgs = AF.add(ScratchArgs, 0, Effect);
1261 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001262}
1263
Ted Kremenek93edbc52011-10-05 23:54:29 +00001264const RetainSummary *
Ted Kremenek9c378f72011-08-12 23:37:29 +00001265RetainSummaryManager::getCFSummaryCreateRule(const FunctionDecl *FD) {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001266 assert (ScratchArgs.isEmpty());
Mike Stump1eb44332009-09-09 15:08:12 +00001267
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001268 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001269}
1270
Ted Kremenek93edbc52011-10-05 23:54:29 +00001271const RetainSummary *
Ted Kremenek9c378f72011-08-12 23:37:29 +00001272RetainSummaryManager::getCFSummaryGetRule(const FunctionDecl *FD) {
Mike Stump1eb44332009-09-09 15:08:12 +00001273 assert (ScratchArgs.isEmpty());
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001274 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1275 DoNothing, DoNothing);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001276}
1277
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001278//===----------------------------------------------------------------------===//
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001279// Summary creation for Selectors.
1280//===----------------------------------------------------------------------===//
1281
Jordan Rose44405b72013-04-04 22:31:48 +00001282Optional<RetEffect>
1283RetainSummaryManager::getRetEffectFromAnnotations(QualType RetTy,
1284 const Decl *D) {
1285 if (cocoa::isCocoaObjectRef(RetTy)) {
1286 if (D->getAttr<NSReturnsRetainedAttr>())
1287 return ObjCAllocRetE;
1288
1289 if (D->getAttr<NSReturnsNotRetainedAttr>() ||
1290 D->getAttr<NSReturnsAutoreleasedAttr>())
1291 return RetEffect::MakeNotOwned(RetEffect::ObjC);
1292
1293 } else if (!RetTy->isPointerType()) {
1294 return None;
1295 }
1296
1297 if (D->getAttr<CFReturnsRetainedAttr>())
1298 return RetEffect::MakeOwned(RetEffect::CF, true);
1299
1300 if (D->getAttr<CFReturnsNotRetainedAttr>())
1301 return RetEffect::MakeNotOwned(RetEffect::CF);
1302
1303 return None;
1304}
1305
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001306void
Ted Kremenek93edbc52011-10-05 23:54:29 +00001307RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001308 const FunctionDecl *FD) {
1309 if (!FD)
1310 return;
1311
Jordan Rose4531b7d2012-07-02 19:27:43 +00001312 assert(Summ && "Must have a summary to add annotations to.");
1313 RetainSummaryTemplate Template(Summ, *this);
Jordy Rose4df54fe2011-08-23 04:27:15 +00001314
Ted Kremenek11fe1752011-01-27 18:43:03 +00001315 // Effects on the parameters.
1316 unsigned parm_idx = 0;
1317 for (FunctionDecl::param_const_iterator pi = FD->param_begin(),
John McCall98b8f162011-04-06 09:02:12 +00001318 pe = FD->param_end(); pi != pe; ++pi, ++parm_idx) {
Ted Kremenek11fe1752011-01-27 18:43:03 +00001319 const ParmVarDecl *pd = *pi;
Jordan Rose44405b72013-04-04 22:31:48 +00001320 if (pd->getAttr<NSConsumedAttr>())
1321 Template->addArg(AF, parm_idx, DecRefMsg);
1322 else if (pd->getAttr<CFConsumedAttr>())
Jordy Rose0fe62f82011-08-24 09:02:37 +00001323 Template->addArg(AF, parm_idx, DecRef);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001324 }
1325
Ted Kremenekb04cb592009-06-11 18:17:24 +00001326 QualType RetTy = FD->getResultType();
Jordan Rose44405b72013-04-04 22:31:48 +00001327 if (Optional<RetEffect> RetE = getRetEffectFromAnnotations(RetTy, FD))
1328 Template->setRetEffect(*RetE);
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001329}
1330
1331void
Ted Kremenek93edbc52011-10-05 23:54:29 +00001332RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
1333 const ObjCMethodDecl *MD) {
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001334 if (!MD)
1335 return;
1336
Jordan Rose4531b7d2012-07-02 19:27:43 +00001337 assert(Summ && "Must have a valid summary to add annotations to");
1338 RetainSummaryTemplate Template(Summ, *this);
Mike Stump1eb44332009-09-09 15:08:12 +00001339
Ted Kremenek12b94342011-01-27 06:54:14 +00001340 // Effects on the receiver.
Jordan Rose44405b72013-04-04 22:31:48 +00001341 if (MD->getAttr<NSConsumesSelfAttr>())
1342 Template->setReceiverEffect(DecRefMsg);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001343
1344 // Effects on the parameters.
1345 unsigned parm_idx = 0;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00001346 for (ObjCMethodDecl::param_const_iterator
1347 pi=MD->param_begin(), pe=MD->param_end();
Ted Kremenek11fe1752011-01-27 18:43:03 +00001348 pi != pe; ++pi, ++parm_idx) {
1349 const ParmVarDecl *pd = *pi;
Jordan Rose44405b72013-04-04 22:31:48 +00001350 if (pd->getAttr<NSConsumedAttr>())
1351 Template->addArg(AF, parm_idx, DecRefMsg);
1352 else if (pd->getAttr<CFConsumedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001353 Template->addArg(AF, parm_idx, DecRef);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001354 }
Ted Kremenek12b94342011-01-27 06:54:14 +00001355 }
1356
Jordan Rose44405b72013-04-04 22:31:48 +00001357 QualType RetTy = MD->getResultType();
1358 if (Optional<RetEffect> RetE = getRetEffectFromAnnotations(RetTy, MD))
1359 Template->setRetEffect(*RetE);
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001360}
1361
Ted Kremenek93edbc52011-10-05 23:54:29 +00001362const RetainSummary *
Jordy Rosef3aae582012-03-17 21:13:07 +00001363RetainSummaryManager::getStandardMethodSummary(const ObjCMethodDecl *MD,
1364 Selector S, QualType RetTy) {
Jordy Rosee921b1a2012-03-17 19:53:04 +00001365 // Any special effects?
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001366 ArgEffect ReceiverEff = DoNothing;
Jordy Rosee921b1a2012-03-17 19:53:04 +00001367 RetEffect ResultEff = RetEffect::MakeNoRet();
1368
1369 // Check the method family, and apply any default annotations.
1370 switch (MD ? MD->getMethodFamily() : S.getMethodFamily()) {
1371 case OMF_None:
1372 case OMF_performSelector:
1373 // Assume all Objective-C methods follow Cocoa Memory Management rules.
1374 // FIXME: Does the non-threaded performSelector family really belong here?
1375 // The selector could be, say, @selector(copy).
1376 if (cocoa::isCocoaObjectRef(RetTy))
1377 ResultEff = RetEffect::MakeNotOwned(RetEffect::ObjC);
1378 else if (coreFoundation::isCFObjectRef(RetTy)) {
1379 // ObjCMethodDecl currently doesn't consider CF objects as valid return
1380 // values for alloc, new, copy, or mutableCopy, so we have to
1381 // double-check with the selector. This is ugly, but there aren't that
1382 // many Objective-C methods that return CF objects, right?
1383 if (MD) {
1384 switch (S.getMethodFamily()) {
1385 case OMF_alloc:
1386 case OMF_new:
1387 case OMF_copy:
1388 case OMF_mutableCopy:
1389 ResultEff = RetEffect::MakeOwned(RetEffect::CF, true);
1390 break;
1391 default:
1392 ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1393 break;
1394 }
1395 } else {
1396 ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1397 }
1398 }
1399 break;
1400 case OMF_init:
1401 ResultEff = ObjCInitRetE;
1402 ReceiverEff = DecRefMsg;
1403 break;
1404 case OMF_alloc:
1405 case OMF_new:
1406 case OMF_copy:
1407 case OMF_mutableCopy:
1408 if (cocoa::isCocoaObjectRef(RetTy))
1409 ResultEff = ObjCAllocRetE;
1410 else if (coreFoundation::isCFObjectRef(RetTy))
1411 ResultEff = RetEffect::MakeOwned(RetEffect::CF, true);
1412 break;
1413 case OMF_autorelease:
1414 ReceiverEff = Autorelease;
1415 break;
1416 case OMF_retain:
1417 ReceiverEff = IncRefMsg;
1418 break;
1419 case OMF_release:
1420 ReceiverEff = DecRefMsg;
1421 break;
1422 case OMF_dealloc:
1423 ReceiverEff = Dealloc;
1424 break;
1425 case OMF_self:
1426 // -self is handled specially by the ExprEngine to propagate the receiver.
1427 break;
1428 case OMF_retainCount:
1429 case OMF_finalize:
1430 // These methods don't return objects.
1431 break;
1432 }
Mike Stump1eb44332009-09-09 15:08:12 +00001433
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001434 // If one of the arguments in the selector has the keyword 'delegate' we
1435 // should stop tracking the reference count for the receiver. This is
1436 // because the reference count is quite possibly handled by a delegate
1437 // method.
1438 if (S.isKeywordSelector()) {
Jordan Rose50571a92012-06-15 18:19:52 +00001439 for (unsigned i = 0, e = S.getNumArgs(); i != e; ++i) {
1440 StringRef Slot = S.getNameForSlot(i);
1441 if (Slot.substr(Slot.size() - 8).equals_lower("delegate")) {
1442 if (ResultEff == ObjCInitRetE)
Anna Zaks554067f2012-08-29 23:23:43 +00001443 ResultEff = RetEffect::MakeNoRetHard();
Jordan Rose50571a92012-06-15 18:19:52 +00001444 else
Anna Zaks554067f2012-08-29 23:23:43 +00001445 ReceiverEff = StopTrackingHard;
Jordan Rose50571a92012-06-15 18:19:52 +00001446 }
1447 }
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001448 }
Mike Stump1eb44332009-09-09 15:08:12 +00001449
Jordy Rosee921b1a2012-03-17 19:53:04 +00001450 if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing &&
1451 ResultEff.getKind() == RetEffect::NoRet)
Ted Kremenek93edbc52011-10-05 23:54:29 +00001452 return getDefaultSummary();
Mike Stump1eb44332009-09-09 15:08:12 +00001453
Jordy Rosee921b1a2012-03-17 19:53:04 +00001454 return getPersistentSummary(ResultEff, ReceiverEff, MayEscape);
Ted Kremenek250b1fa2009-04-23 23:08:22 +00001455}
1456
Ted Kremenek93edbc52011-10-05 23:54:29 +00001457const RetainSummary *
Jordan Rosecde8cdb2012-07-02 19:27:56 +00001458RetainSummaryManager::getInstanceMethodSummary(const ObjCMethodCall &Msg,
Jordan Rose4531b7d2012-07-02 19:27:43 +00001459 ProgramStateRef State) {
1460 const ObjCInterfaceDecl *ReceiverClass = 0;
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001461
Jordan Rose4531b7d2012-07-02 19:27:43 +00001462 // We do better tracking of the type of the object than the core ExprEngine.
1463 // See if we have its type in our private state.
1464 // FIXME: Eventually replace the use of state->get<RefBindings> with
1465 // a generic API for reasoning about the Objective-C types of symbolic
1466 // objects.
1467 SVal ReceiverV = Msg.getReceiverSVal();
1468 if (SymbolRef Sym = ReceiverV.getAsLocSymbol())
Anna Zaks8d6b43c2012-08-14 00:36:15 +00001469 if (const RefVal *T = getRefBinding(State, Sym))
Douglas Gregor04badcf2010-04-21 00:45:42 +00001470 if (const ObjCObjectPointerType *PT =
Jordan Rose4531b7d2012-07-02 19:27:43 +00001471 T->getType()->getAs<ObjCObjectPointerType>())
1472 ReceiverClass = PT->getInterfaceDecl();
1473
1474 // If we don't know what kind of object this is, fall back to its static type.
1475 if (!ReceiverClass)
1476 ReceiverClass = Msg.getReceiverInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00001477
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001478 // FIXME: The receiver could be a reference to a class, meaning that
1479 // we should use the class method.
Jordan Rose4531b7d2012-07-02 19:27:43 +00001480 // id x = [NSObject class];
1481 // [x performSelector:... withObject:... afterDelay:...];
1482 Selector S = Msg.getSelector();
1483 const ObjCMethodDecl *Method = Msg.getDecl();
1484 if (!Method && ReceiverClass)
1485 Method = ReceiverClass->getInstanceMethod(S);
1486
1487 return getMethodSummary(S, ReceiverClass, Method, Msg.getResultType(),
1488 ObjCMethodSummaries);
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001489}
1490
Ted Kremenek93edbc52011-10-05 23:54:29 +00001491const RetainSummary *
Jordan Rose4531b7d2012-07-02 19:27:43 +00001492RetainSummaryManager::getMethodSummary(Selector S, const ObjCInterfaceDecl *ID,
Jordy Rosef3aae582012-03-17 21:13:07 +00001493 const ObjCMethodDecl *MD, QualType RetTy,
1494 ObjCMethodSummariesTy &CachedSummaries) {
Ted Kremenek1bffd742008-05-06 15:44:25 +00001495
Ted Kremenek8711c032009-04-29 05:04:30 +00001496 // Look up a summary in our summary cache.
Jordan Rose4531b7d2012-07-02 19:27:43 +00001497 const RetainSummary *Summ = CachedSummaries.find(ID, S);
Mike Stump1eb44332009-09-09 15:08:12 +00001498
Ted Kremenek614cc542009-07-21 23:27:57 +00001499 if (!Summ) {
Jordy Rosef3aae582012-03-17 21:13:07 +00001500 Summ = getStandardMethodSummary(MD, S, RetTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001501
Ted Kremenek614cc542009-07-21 23:27:57 +00001502 // Annotations override defaults.
Jordy Rose4df54fe2011-08-23 04:27:15 +00001503 updateSummaryFromAnnotations(Summ, MD);
Mike Stump1eb44332009-09-09 15:08:12 +00001504
Ted Kremenek614cc542009-07-21 23:27:57 +00001505 // Memoize the summary.
Jordan Rose4531b7d2012-07-02 19:27:43 +00001506 CachedSummaries[ObjCSummaryKey(ID, S)] = Summ;
Ted Kremenek614cc542009-07-21 23:27:57 +00001507 }
Mike Stump1eb44332009-09-09 15:08:12 +00001508
Ted Kremeneke87450e2009-04-23 19:11:35 +00001509 return Summ;
Ted Kremenekc8395602008-05-06 21:26:51 +00001510}
1511
Mike Stump1eb44332009-09-09 15:08:12 +00001512void RetainSummaryManager::InitializeClassMethodSummaries() {
Ted Kremenekec315332009-05-07 23:40:42 +00001513 assert(ScratchArgs.isEmpty());
Mike Stump1eb44332009-09-09 15:08:12 +00001514 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek6fe2b7a2009-10-15 22:25:12 +00001515 addClassMethSummary("NSAssertionHandler", "currentHandler",
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001516 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Mike Stump1eb44332009-09-09 15:08:12 +00001517
Ted Kremenek6d348932008-10-21 15:53:15 +00001518 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001519 ScratchArgs = AF.add(ScratchArgs, 0, Autorelease);
Ted Kremenek6fe2b7a2009-10-15 22:25:12 +00001520 addClassMethSummary("NSAutoreleasePool", "addObject",
1521 getPersistentSummary(RetEffect::MakeNoRet(),
1522 DoNothing, Autorelease));
Ted Kremenek9c32d082008-05-06 00:30:21 +00001523}
1524
Ted Kremenek1f180c32008-06-23 22:21:20 +00001525void RetainSummaryManager::InitializeMethodSummaries() {
Mike Stump1eb44332009-09-09 15:08:12 +00001526
1527 assert (ScratchArgs.isEmpty());
1528
Ted Kremenekc8395602008-05-06 21:26:51 +00001529 // Create the "init" selector. It just acts as a pass-through for the
1530 // receiver.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001531 const RetainSummary *InitSumm = getPersistentSummary(ObjCInitRetE, DecRefMsg);
Ted Kremenekac02f202009-08-20 05:13:36 +00001532 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
1533
1534 // awakeAfterUsingCoder: behaves basically like an 'init' method. It
1535 // claims the receiver and returns a retained object.
1536 addNSObjectMethSummary(GetUnarySelector("awakeAfterUsingCoder", Ctx),
1537 InitSumm);
Mike Stump1eb44332009-09-09 15:08:12 +00001538
Ted Kremenekc8395602008-05-06 21:26:51 +00001539 // The next methods are allocators.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001540 const RetainSummary *AllocSumm = getPersistentSummary(ObjCAllocRetE);
1541 const RetainSummary *CFAllocSumm =
Ted Kremeneka834fb42009-08-28 19:52:12 +00001542 getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Mike Stump1eb44332009-09-09 15:08:12 +00001543
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001544 // Create the "retain" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001545 RetEffect NoRet = RetEffect::MakeNoRet();
Ted Kremenek93edbc52011-10-05 23:54:29 +00001546 const RetainSummary *Summ = getPersistentSummary(NoRet, IncRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001547 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001548
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001549 // Create the "release" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001550 Summ = getPersistentSummary(NoRet, DecRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001551 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001552
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001553 // Create the -dealloc summary.
Jordy Rose500abad2011-08-21 19:41:36 +00001554 Summ = getPersistentSummary(NoRet, Dealloc);
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001555 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001556
1557 // Create the "autorelease" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001558 Summ = getPersistentSummary(NoRet, Autorelease);
Ted Kremenek553cf182008-06-25 21:21:56 +00001559 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001560
Mike Stump1eb44332009-09-09 15:08:12 +00001561 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremenek89e202d2009-02-23 02:51:29 +00001562 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1563 // self-own themselves. However, they only do this once they are displayed.
1564 // Thus, we need to track an NSWindow's display status.
1565 // This is tracked in <rdar://problem/6062711>.
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +00001566 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001567 const RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenek78a35a32009-05-12 20:06:54 +00001568 StopTracking,
1569 StopTracking);
Mike Stump1eb44332009-09-09 15:08:12 +00001570
Ted Kremenek99d02692009-04-03 19:02:51 +00001571 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1572
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001573 // For NSPanel (which subclasses NSWindow), allocated objects are not
1574 // self-owned.
Ted Kremenek99d02692009-04-03 19:02:51 +00001575 // FIXME: For now we don't track NSPanels. object for the same reason
1576 // as for NSWindow objects.
1577 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
Mike Stump1eb44332009-09-09 15:08:12 +00001578
Jordan Rosee36d81b2013-01-31 22:06:02 +00001579 // Don't track allocated autorelease pools, as it is okay to prematurely
Ted Kremenekba67f6a2009-05-18 23:14:34 +00001580 // exit a method.
1581 addClassMethSummary("NSAutoreleasePool", "alloc", NoTrackYet);
Ted Kremeneka9797122012-02-18 21:37:48 +00001582 addClassMethSummary("NSAutoreleasePool", "allocWithZone", NoTrackYet, false);
Jordan Rosee36d81b2013-01-31 22:06:02 +00001583 addClassMethSummary("NSAutoreleasePool", "new", NoTrackYet);
Ted Kremenek553cf182008-06-25 21:21:56 +00001584
Ted Kremenek767d6492009-05-20 22:39:57 +00001585 // Create summaries QCRenderer/QCView -createSnapShotImageOfType:
1586 addInstMethSummary("QCRenderer", AllocSumm,
1587 "createSnapshotImageOfType", NULL);
1588 addInstMethSummary("QCView", AllocSumm,
1589 "createSnapshotImageOfType", NULL);
1590
Ted Kremenek211a9c62009-06-15 20:58:58 +00001591 // Create summaries for CIContext, 'createCGImage' and
Ted Kremeneka834fb42009-08-28 19:52:12 +00001592 // 'createCGLayerWithSize'. These objects are CF objects, and are not
1593 // automatically garbage collected.
1594 addInstMethSummary("CIContext", CFAllocSumm,
Ted Kremenek767d6492009-05-20 22:39:57 +00001595 "createCGImage", "fromRect", NULL);
Ted Kremeneka834fb42009-08-28 19:52:12 +00001596 addInstMethSummary("CIContext", CFAllocSumm,
Mike Stump1eb44332009-09-09 15:08:12 +00001597 "createCGImage", "fromRect", "format", "colorSpace", NULL);
Ted Kremeneka834fb42009-08-28 19:52:12 +00001598 addInstMethSummary("CIContext", CFAllocSumm, "createCGLayerWithSize",
Ted Kremenek211a9c62009-06-15 20:58:58 +00001599 "info", NULL);
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001600}
1601
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001602//===----------------------------------------------------------------------===//
Ted Kremenekc887d132009-04-29 18:50:19 +00001603// Error reporting.
1604//===----------------------------------------------------------------------===//
Ted Kremenekc887d132009-04-29 18:50:19 +00001605namespace {
Jordy Roseec9ef852011-08-23 20:55:48 +00001606 typedef llvm::DenseMap<const ExplodedNode *, const RetainSummary *>
1607 SummaryLogTy;
1608
Ted Kremenekc887d132009-04-29 18:50:19 +00001609 //===-------------===//
1610 // Bug Descriptions. //
Mike Stump1eb44332009-09-09 15:08:12 +00001611 //===-------------===//
1612
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001613 class CFRefBug : public BugType {
Ted Kremenekc887d132009-04-29 18:50:19 +00001614 protected:
Jordy Rose35c86952011-08-24 05:47:39 +00001615 CFRefBug(StringRef name)
Ted Kremenek6fd45052012-04-05 20:43:28 +00001616 : BugType(name, categories::MemoryCoreFoundationObjectiveC) {}
Ted Kremenekc887d132009-04-29 18:50:19 +00001617 public:
Mike Stump1eb44332009-09-09 15:08:12 +00001618
Ted Kremenekc887d132009-04-29 18:50:19 +00001619 // FIXME: Eventually remove.
Jordy Rose35c86952011-08-24 05:47:39 +00001620 virtual const char *getDescription() const = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001621
Ted Kremenekc887d132009-04-29 18:50:19 +00001622 virtual bool isLeak() const { return false; }
1623 };
Mike Stump1eb44332009-09-09 15:08:12 +00001624
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001625 class UseAfterRelease : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001626 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001627 UseAfterRelease() : CFRefBug("Use-after-release") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001628
Jordy Rose35c86952011-08-24 05:47:39 +00001629 const char *getDescription() const {
Ted Kremenekc887d132009-04-29 18:50:19 +00001630 return "Reference-counted object is used after it is released";
Mike Stump1eb44332009-09-09 15:08:12 +00001631 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001632 };
Mike Stump1eb44332009-09-09 15:08:12 +00001633
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001634 class BadRelease : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001635 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001636 BadRelease() : CFRefBug("Bad release") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001637
Jordy Rose35c86952011-08-24 05:47:39 +00001638 const char *getDescription() const {
Ted Kremenekbb206fd2009-10-01 17:31:50 +00001639 return "Incorrect decrement of the reference count of an object that is "
1640 "not owned at this point by the caller";
Ted Kremenekc887d132009-04-29 18:50:19 +00001641 }
1642 };
Mike Stump1eb44332009-09-09 15:08:12 +00001643
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001644 class DeallocGC : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001645 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001646 DeallocGC()
1647 : CFRefBug("-dealloc called while using garbage collection") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001648
Ted Kremenekc887d132009-04-29 18:50:19 +00001649 const char *getDescription() const {
Ted Kremenek369de562009-05-09 00:10:05 +00001650 return "-dealloc called while using garbage collection";
Ted Kremenekc887d132009-04-29 18:50:19 +00001651 }
1652 };
Mike Stump1eb44332009-09-09 15:08:12 +00001653
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001654 class DeallocNotOwned : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001655 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001656 DeallocNotOwned()
1657 : CFRefBug("-dealloc sent to non-exclusively owned object") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001658
Ted Kremenekc887d132009-04-29 18:50:19 +00001659 const char *getDescription() const {
1660 return "-dealloc sent to object that may be referenced elsewhere";
1661 }
Mike Stump1eb44332009-09-09 15:08:12 +00001662 };
1663
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001664 class OverAutorelease : public CFRefBug {
Ted Kremenek369de562009-05-09 00:10:05 +00001665 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001666 OverAutorelease()
Jordan Rose2545b1d2013-04-23 01:42:25 +00001667 : CFRefBug("Object autoreleased too many times") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001668
Ted Kremenek369de562009-05-09 00:10:05 +00001669 const char *getDescription() const {
Jordan Rose2545b1d2013-04-23 01:42:25 +00001670 return "Object autoreleased too many times";
Ted Kremenek369de562009-05-09 00:10:05 +00001671 }
1672 };
Mike Stump1eb44332009-09-09 15:08:12 +00001673
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001674 class ReturnedNotOwnedForOwned : public CFRefBug {
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001675 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001676 ReturnedNotOwnedForOwned()
1677 : CFRefBug("Method should return an owned object") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001678
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001679 const char *getDescription() const {
Jordy Rose5b5402b2011-07-15 22:17:54 +00001680 return "Object with a +0 retain count returned to caller where a +1 "
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001681 "(owning) retain count is expected";
1682 }
1683 };
Mike Stump1eb44332009-09-09 15:08:12 +00001684
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001685 class Leak : public CFRefBug {
Benjamin Kramerfacde172012-06-06 17:32:50 +00001686 public:
1687 Leak(StringRef name)
1688 : CFRefBug(name) {
Jordy Rosedb92bb62011-08-25 01:14:38 +00001689 // Leaks should not be reported if they are post-dominated by a sink.
1690 setSuppressOnSink(true);
1691 }
Mike Stump1eb44332009-09-09 15:08:12 +00001692
Jordy Rose35c86952011-08-24 05:47:39 +00001693 const char *getDescription() const { return ""; }
Mike Stump1eb44332009-09-09 15:08:12 +00001694
Ted Kremenekc887d132009-04-29 18:50:19 +00001695 bool isLeak() const { return true; }
1696 };
Mike Stump1eb44332009-09-09 15:08:12 +00001697
Ted Kremenekc887d132009-04-29 18:50:19 +00001698 //===---------===//
1699 // Bug Reports. //
1700 //===---------===//
Mike Stump1eb44332009-09-09 15:08:12 +00001701
Jordy Rose01153492012-03-24 02:45:35 +00001702 class CFRefReportVisitor : public BugReporterVisitorImpl<CFRefReportVisitor> {
Anna Zaks23f395e2011-08-20 01:27:22 +00001703 protected:
Anna Zaksdc757b02011-08-19 23:21:56 +00001704 SymbolRef Sym;
Jordy Roseec9ef852011-08-23 20:55:48 +00001705 const SummaryLogTy &SummaryLog;
Jordy Rose35c86952011-08-24 05:47:39 +00001706 bool GCEnabled;
Anna Zaks23f395e2011-08-20 01:27:22 +00001707
Anna Zaksdc757b02011-08-19 23:21:56 +00001708 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001709 CFRefReportVisitor(SymbolRef sym, bool gcEnabled, const SummaryLogTy &log)
1710 : Sym(sym), SummaryLog(log), GCEnabled(gcEnabled) {}
Anna Zaksdc757b02011-08-19 23:21:56 +00001711
Anna Zaks23f395e2011-08-20 01:27:22 +00001712 virtual void Profile(llvm::FoldingSetNodeID &ID) const {
Anna Zaksdc757b02011-08-19 23:21:56 +00001713 static int x = 0;
1714 ID.AddPointer(&x);
1715 ID.AddPointer(Sym);
1716 }
1717
Anna Zaks23f395e2011-08-20 01:27:22 +00001718 virtual PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
1719 const ExplodedNode *PrevN,
1720 BugReporterContext &BRC,
1721 BugReport &BR);
1722
1723 virtual PathDiagnosticPiece *getEndPath(BugReporterContext &BRC,
1724 const ExplodedNode *N,
1725 BugReport &BR);
1726 };
1727
1728 class CFRefLeakReportVisitor : public CFRefReportVisitor {
1729 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001730 CFRefLeakReportVisitor(SymbolRef sym, bool GCEnabled,
Jordy Roseec9ef852011-08-23 20:55:48 +00001731 const SummaryLogTy &log)
Jordy Rose35c86952011-08-24 05:47:39 +00001732 : CFRefReportVisitor(sym, GCEnabled, log) {}
Anna Zaks23f395e2011-08-20 01:27:22 +00001733
1734 PathDiagnosticPiece *getEndPath(BugReporterContext &BRC,
1735 const ExplodedNode *N,
1736 BugReport &BR);
Jordy Rose01153492012-03-24 02:45:35 +00001737
1738 virtual BugReporterVisitor *clone() const {
1739 // The curiously-recurring template pattern only works for one level of
1740 // subclassing. Rather than make a new template base for
1741 // CFRefReportVisitor, we simply override clone() to do the right thing.
1742 // This could be trouble someday if BugReporterVisitorImpl is ever
1743 // used for something else besides a convenient implementation of clone().
1744 return new CFRefLeakReportVisitor(*this);
1745 }
Anna Zaksdc757b02011-08-19 23:21:56 +00001746 };
1747
Anna Zakse172e8b2011-08-17 23:00:25 +00001748 class CFRefReport : public BugReport {
Jordy Rose20589562011-08-24 22:39:09 +00001749 void addGCModeDescription(const LangOptions &LOpts, bool GCEnabled);
Jordy Rose35c86952011-08-24 05:47:39 +00001750
Ted Kremenekc887d132009-04-29 18:50:19 +00001751 public:
Jordy Rose20589562011-08-24 22:39:09 +00001752 CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1753 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1754 bool registerVisitor = true)
Anna Zaksedf4dae2011-08-22 18:54:07 +00001755 : BugReport(D, D.getDescription(), n) {
Anna Zaks23f395e2011-08-20 01:27:22 +00001756 if (registerVisitor)
Jordy Rose20589562011-08-24 22:39:09 +00001757 addVisitor(new CFRefReportVisitor(sym, GCEnabled, Log));
1758 addGCModeDescription(LOpts, GCEnabled);
Anna Zaksdc757b02011-08-19 23:21:56 +00001759 }
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001760
Jordy Rose20589562011-08-24 22:39:09 +00001761 CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1762 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1763 StringRef endText)
Anna Zaksedf4dae2011-08-22 18:54:07 +00001764 : BugReport(D, D.getDescription(), endText, n) {
Jordy Rose20589562011-08-24 22:39:09 +00001765 addVisitor(new CFRefReportVisitor(sym, GCEnabled, Log));
1766 addGCModeDescription(LOpts, GCEnabled);
Anna Zaksdc757b02011-08-19 23:21:56 +00001767 }
Mike Stump1eb44332009-09-09 15:08:12 +00001768
Anna Zakse172e8b2011-08-17 23:00:25 +00001769 virtual std::pair<ranges_iterator, ranges_iterator> getRanges() {
Anna Zaksedf4dae2011-08-22 18:54:07 +00001770 const CFRefBug& BugTy = static_cast<CFRefBug&>(getBugType());
1771 if (!BugTy.isLeak())
Anna Zakse172e8b2011-08-17 23:00:25 +00001772 return BugReport::getRanges();
Ted Kremenekc887d132009-04-29 18:50:19 +00001773 else
Argyrios Kyrtzidis640ccf02010-12-04 01:12:15 +00001774 return std::make_pair(ranges_iterator(), ranges_iterator());
Ted Kremenekc887d132009-04-29 18:50:19 +00001775 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001776 };
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001777
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001778 class CFRefLeakReport : public CFRefReport {
Ted Kremenekc887d132009-04-29 18:50:19 +00001779 const MemRegion* AllocBinding;
1780 public:
Jordy Rose20589562011-08-24 22:39:09 +00001781 CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1782 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
Ted Kremenek08a838d2013-04-16 21:44:22 +00001783 CheckerContext &Ctx,
1784 bool IncludeAllocationLine);
Mike Stump1eb44332009-09-09 15:08:12 +00001785
Anna Zaks590dd8e2011-09-20 21:38:35 +00001786 PathDiagnosticLocation getLocation(const SourceManager &SM) const {
1787 assert(Location.isValid());
1788 return Location;
1789 }
Mike Stump1eb44332009-09-09 15:08:12 +00001790 };
Ted Kremenekc887d132009-04-29 18:50:19 +00001791} // end anonymous namespace
1792
Jordy Rose20589562011-08-24 22:39:09 +00001793void CFRefReport::addGCModeDescription(const LangOptions &LOpts,
1794 bool GCEnabled) {
Jordy Rosef95b19d2011-08-24 20:38:42 +00001795 const char *GCModeDescription = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001796
Douglas Gregore289d812011-09-13 17:21:33 +00001797 switch (LOpts.getGC()) {
Anna Zaks7f2531c2011-08-22 20:31:28 +00001798 case LangOptions::GCOnly:
Jordy Rose20589562011-08-24 22:39:09 +00001799 assert(GCEnabled);
Jordy Rose35c86952011-08-24 05:47:39 +00001800 GCModeDescription = "Code is compiled to only use garbage collection";
1801 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001802
Anna Zaks7f2531c2011-08-22 20:31:28 +00001803 case LangOptions::NonGC:
Jordy Rose20589562011-08-24 22:39:09 +00001804 assert(!GCEnabled);
Jordy Rose35c86952011-08-24 05:47:39 +00001805 GCModeDescription = "Code is compiled to use reference counts";
1806 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001807
Anna Zaks7f2531c2011-08-22 20:31:28 +00001808 case LangOptions::HybridGC:
Jordy Rose20589562011-08-24 22:39:09 +00001809 if (GCEnabled) {
Jordy Rose35c86952011-08-24 05:47:39 +00001810 GCModeDescription = "Code is compiled to use either garbage collection "
1811 "(GC) or reference counts (non-GC). The bug occurs "
1812 "with GC enabled";
1813 break;
1814 } else {
1815 GCModeDescription = "Code is compiled to use either garbage collection "
1816 "(GC) or reference counts (non-GC). The bug occurs "
1817 "in non-GC mode";
1818 break;
Anna Zaks7f2531c2011-08-22 20:31:28 +00001819 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001820 }
Jordy Rose35c86952011-08-24 05:47:39 +00001821
Jordy Rosef95b19d2011-08-24 20:38:42 +00001822 assert(GCModeDescription && "invalid/unknown GC mode");
Jordy Rose35c86952011-08-24 05:47:39 +00001823 addExtraText(GCModeDescription);
Ted Kremenekc887d132009-04-29 18:50:19 +00001824}
1825
Jordy Rose910c4052011-09-02 06:44:22 +00001826// FIXME: This should be a method on SmallVector.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001827static inline bool contains(const SmallVectorImpl<ArgEffect>& V,
Ted Kremenekc887d132009-04-29 18:50:19 +00001828 ArgEffect X) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001829 for (SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
Ted Kremenekc887d132009-04-29 18:50:19 +00001830 I!=E; ++I)
1831 if (*I == X) return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001832
Ted Kremenekc887d132009-04-29 18:50:19 +00001833 return false;
1834}
1835
Jordy Rose70fdbc32012-05-12 05:10:43 +00001836static bool isNumericLiteralExpression(const Expr *E) {
1837 // FIXME: This set of cases was copied from SemaExprObjC.
1838 return isa<IntegerLiteral>(E) ||
1839 isa<CharacterLiteral>(E) ||
1840 isa<FloatingLiteral>(E) ||
1841 isa<ObjCBoolLiteralExpr>(E) ||
1842 isa<CXXBoolLiteralExpr>(E);
1843}
1844
Anna Zaksdc757b02011-08-19 23:21:56 +00001845PathDiagnosticPiece *CFRefReportVisitor::VisitNode(const ExplodedNode *N,
1846 const ExplodedNode *PrevN,
1847 BugReporterContext &BRC,
1848 BugReport &BR) {
Jordan Rose28038f32012-07-10 22:07:42 +00001849 // FIXME: We will eventually need to handle non-statement-based events
1850 // (__attribute__((cleanup))).
David Blaikie7a95de62013-02-21 22:23:56 +00001851 if (!N->getLocation().getAs<StmtPoint>())
Ted Kremenek2033a952009-05-13 07:12:33 +00001852 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001853
Ted Kremenek8966bc12009-05-06 21:39:49 +00001854 // Check if the type state has changed.
Ted Kremenek8bef8232012-01-26 21:29:00 +00001855 ProgramStateRef PrevSt = PrevN->getState();
1856 ProgramStateRef CurrSt = N->getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001857 const LocationContext *LCtx = N->getLocationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00001858
Anna Zaks8d6b43c2012-08-14 00:36:15 +00001859 const RefVal* CurrT = getRefBinding(CurrSt, Sym);
Ted Kremenekc887d132009-04-29 18:50:19 +00001860 if (!CurrT) return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001861
Ted Kremenekb65be702009-06-18 01:23:53 +00001862 const RefVal &CurrV = *CurrT;
Anna Zaks8d6b43c2012-08-14 00:36:15 +00001863 const RefVal *PrevT = getRefBinding(PrevSt, Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00001864
Ted Kremenekc887d132009-04-29 18:50:19 +00001865 // Create a string buffer to constain all the useful things we want
1866 // to tell the user.
1867 std::string sbuf;
1868 llvm::raw_string_ostream os(sbuf);
Mike Stump1eb44332009-09-09 15:08:12 +00001869
Ted Kremenekc887d132009-04-29 18:50:19 +00001870 // This is the allocation site since the previous node had no bindings
1871 // for this symbol.
1872 if (!PrevT) {
David Blaikie7a95de62013-02-21 22:23:56 +00001873 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
Mike Stump1eb44332009-09-09 15:08:12 +00001874
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001875 if (isa<ObjCArrayLiteral>(S)) {
1876 os << "NSArray literal is an object with a +0 retain count";
Mike Stump1eb44332009-09-09 15:08:12 +00001877 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001878 else if (isa<ObjCDictionaryLiteral>(S)) {
1879 os << "NSDictionary literal is an object with a +0 retain count";
Ted Kremenekc887d132009-04-29 18:50:19 +00001880 }
Jordy Rose70fdbc32012-05-12 05:10:43 +00001881 else if (const ObjCBoxedExpr *BL = dyn_cast<ObjCBoxedExpr>(S)) {
1882 if (isNumericLiteralExpression(BL->getSubExpr()))
1883 os << "NSNumber literal is an object with a +0 retain count";
1884 else {
1885 const ObjCInterfaceDecl *BoxClass = 0;
1886 if (const ObjCMethodDecl *Method = BL->getBoxingMethod())
1887 BoxClass = Method->getClassInterface();
1888
1889 // We should always be able to find the boxing class interface,
1890 // but consider this future-proofing.
1891 if (BoxClass)
1892 os << *BoxClass << " b";
1893 else
1894 os << "B";
1895
1896 os << "oxed expression produces an object with a +0 retain count";
1897 }
1898 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001899 else {
1900 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
1901 // Get the name of the callee (if it is available).
1902 SVal X = CurrSt->getSValAsScalarOrLoc(CE->getCallee(), LCtx);
1903 if (const FunctionDecl *FD = X.getAsFunctionDecl())
1904 os << "Call to function '" << *FD << '\'';
1905 else
1906 os << "function call";
Ted Kremenekc887d132009-04-29 18:50:19 +00001907 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001908 else {
Jordan Rose8919e682012-07-18 21:59:51 +00001909 assert(isa<ObjCMessageExpr>(S));
Jordan Rosed563d3f2012-07-30 20:22:09 +00001910 CallEventManager &Mgr = CurrSt->getStateManager().getCallEventManager();
1911 CallEventRef<ObjCMethodCall> Call
1912 = Mgr.getObjCMethodCall(cast<ObjCMessageExpr>(S), CurrSt, LCtx);
1913
1914 switch (Call->getMessageKind()) {
Jordan Rose8919e682012-07-18 21:59:51 +00001915 case OCM_Message:
1916 os << "Method";
1917 break;
1918 case OCM_PropertyAccess:
1919 os << "Property";
1920 break;
1921 case OCM_Subscript:
1922 os << "Subscript";
1923 break;
1924 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001925 }
1926
1927 if (CurrV.getObjKind() == RetEffect::CF) {
1928 os << " returns a Core Foundation object with a ";
1929 }
1930 else {
1931 assert (CurrV.getObjKind() == RetEffect::ObjC);
1932 os << " returns an Objective-C object with a ";
1933 }
1934
1935 if (CurrV.isOwned()) {
1936 os << "+1 retain count";
1937
1938 if (GCEnabled) {
1939 assert(CurrV.getObjKind() == RetEffect::CF);
1940 os << ". "
1941 "Core Foundation objects are not automatically garbage collected.";
1942 }
1943 }
1944 else {
1945 assert (CurrV.isNotOwned());
1946 os << "+0 retain count";
1947 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001948 }
Mike Stump1eb44332009-09-09 15:08:12 +00001949
Anna Zaks220ac8c2011-09-15 01:08:34 +00001950 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
1951 N->getLocationContext());
Ted Kremenekc887d132009-04-29 18:50:19 +00001952 return new PathDiagnosticEventPiece(Pos, os.str());
1953 }
Mike Stump1eb44332009-09-09 15:08:12 +00001954
Ted Kremenekc887d132009-04-29 18:50:19 +00001955 // Gather up the effects that were performed on the object at this
1956 // program point
Chris Lattner5f9e2722011-07-23 10:55:15 +00001957 SmallVector<ArgEffect, 2> AEffects;
Mike Stump1eb44332009-09-09 15:08:12 +00001958
Jordy Roseec9ef852011-08-23 20:55:48 +00001959 const ExplodedNode *OrigNode = BRC.getNodeResolver().getOriginalNode(N);
1960 if (const RetainSummary *Summ = SummaryLog.lookup(OrigNode)) {
Ted Kremenekc887d132009-04-29 18:50:19 +00001961 // We only have summaries attached to nodes after evaluating CallExpr and
1962 // ObjCMessageExprs.
David Blaikie7a95de62013-02-21 22:23:56 +00001963 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
Mike Stump1eb44332009-09-09 15:08:12 +00001964
Ted Kremenek5f85e172009-07-22 22:35:28 +00001965 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
Ted Kremenekc887d132009-04-29 18:50:19 +00001966 // Iterate through the parameter expressions and see if the symbol
1967 // was ever passed as an argument.
1968 unsigned i = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001969
Ted Kremenek5f85e172009-07-22 22:35:28 +00001970 for (CallExpr::const_arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
Ted Kremenekc887d132009-04-29 18:50:19 +00001971 AI!=AE; ++AI, ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00001972
Ted Kremenekc887d132009-04-29 18:50:19 +00001973 // Retrieve the value of the argument. Is it the symbol
1974 // we are interested in?
Ted Kremenek5eca4822012-01-06 22:09:28 +00001975 if (CurrSt->getSValAsScalarOrLoc(*AI, LCtx).getAsLocSymbol() != Sym)
Ted Kremenekc887d132009-04-29 18:50:19 +00001976 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001977
Ted Kremenekc887d132009-04-29 18:50:19 +00001978 // We have an argument. Get the effect!
1979 AEffects.push_back(Summ->getArg(i));
1980 }
1981 }
Mike Stump1eb44332009-09-09 15:08:12 +00001982 else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00001983 if (const Expr *receiver = ME->getInstanceReceiver())
Ted Kremenek5eca4822012-01-06 22:09:28 +00001984 if (CurrSt->getSValAsScalarOrLoc(receiver, LCtx)
1985 .getAsLocSymbol() == Sym) {
Ted Kremenekc887d132009-04-29 18:50:19 +00001986 // The symbol we are tracking is the receiver.
1987 AEffects.push_back(Summ->getReceiverEffect());
1988 }
1989 }
1990 }
Mike Stump1eb44332009-09-09 15:08:12 +00001991
Ted Kremenekc887d132009-04-29 18:50:19 +00001992 do {
1993 // Get the previous type state.
1994 RefVal PrevV = *PrevT;
Mike Stump1eb44332009-09-09 15:08:12 +00001995
Ted Kremenekc887d132009-04-29 18:50:19 +00001996 // Specially handle -dealloc.
Jordy Rose35c86952011-08-24 05:47:39 +00001997 if (!GCEnabled && contains(AEffects, Dealloc)) {
Ted Kremenekc887d132009-04-29 18:50:19 +00001998 // Determine if the object's reference count was pushed to zero.
1999 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2000 // We may not have transitioned to 'release' if we hit an error.
2001 // This case is handled elsewhere.
2002 if (CurrV.getKind() == RefVal::Released) {
Ted Kremenekf21332e2009-05-08 20:01:42 +00002003 assert(CurrV.getCombinedCounts() == 0);
Ted Kremenekc887d132009-04-29 18:50:19 +00002004 os << "Object released by directly sending the '-dealloc' message";
2005 break;
2006 }
2007 }
Mike Stump1eb44332009-09-09 15:08:12 +00002008
Ted Kremenekc887d132009-04-29 18:50:19 +00002009 // Specially handle CFMakeCollectable and friends.
2010 if (contains(AEffects, MakeCollectable)) {
2011 // Get the name of the function.
David Blaikie7a95de62013-02-21 22:23:56 +00002012 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
Ted Kremenek5eca4822012-01-06 22:09:28 +00002013 SVal X =
2014 CurrSt->getSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee(), LCtx);
Ted Kremenek9c378f72011-08-12 23:37:29 +00002015 const FunctionDecl *FD = X.getAsFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002016
Jordy Rose35c86952011-08-24 05:47:39 +00002017 if (GCEnabled) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002018 // Determine if the object's reference count was pushed to zero.
2019 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
Mike Stump1eb44332009-09-09 15:08:12 +00002020
Benjamin Kramerb8989f22011-10-14 18:45:37 +00002021 os << "In GC mode a call to '" << *FD
Ted Kremenekc887d132009-04-29 18:50:19 +00002022 << "' decrements an object's retain count and registers the "
2023 "object with the garbage collector. ";
Mike Stump1eb44332009-09-09 15:08:12 +00002024
Ted Kremenekc887d132009-04-29 18:50:19 +00002025 if (CurrV.getKind() == RefVal::Released) {
2026 assert(CurrV.getCount() == 0);
2027 os << "Since it now has a 0 retain count the object can be "
2028 "automatically collected by the garbage collector.";
2029 }
2030 else
2031 os << "An object must have a 0 retain count to be garbage collected. "
2032 "After this call its retain count is +" << CurrV.getCount()
2033 << '.';
2034 }
Mike Stump1eb44332009-09-09 15:08:12 +00002035 else
Benjamin Kramerb8989f22011-10-14 18:45:37 +00002036 os << "When GC is not enabled a call to '" << *FD
Ted Kremenekc887d132009-04-29 18:50:19 +00002037 << "' has no effect on its argument.";
Mike Stump1eb44332009-09-09 15:08:12 +00002038
Ted Kremenekc887d132009-04-29 18:50:19 +00002039 // Nothing more to say.
2040 break;
2041 }
Mike Stump1eb44332009-09-09 15:08:12 +00002042
2043 // Determine if the typestate has changed.
Ted Kremenekc887d132009-04-29 18:50:19 +00002044 if (!(PrevV == CurrV))
2045 switch (CurrV.getKind()) {
2046 case RefVal::Owned:
2047 case RefVal::NotOwned:
Mike Stump1eb44332009-09-09 15:08:12 +00002048
Ted Kremenekf21332e2009-05-08 20:01:42 +00002049 if (PrevV.getCount() == CurrV.getCount()) {
2050 // Did an autorelease message get sent?
2051 if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
2052 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002053
Zhongxing Xu264e9372009-05-12 10:10:00 +00002054 assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount());
Jordan Rose2545b1d2013-04-23 01:42:25 +00002055 os << "Object autoreleased";
Ted Kremenekf21332e2009-05-08 20:01:42 +00002056 break;
2057 }
Mike Stump1eb44332009-09-09 15:08:12 +00002058
Ted Kremenekc887d132009-04-29 18:50:19 +00002059 if (PrevV.getCount() > CurrV.getCount())
2060 os << "Reference count decremented.";
2061 else
2062 os << "Reference count incremented.";
Mike Stump1eb44332009-09-09 15:08:12 +00002063
Ted Kremenekc887d132009-04-29 18:50:19 +00002064 if (unsigned Count = CurrV.getCount())
2065 os << " The object now has a +" << Count << " retain count.";
Mike Stump1eb44332009-09-09 15:08:12 +00002066
Ted Kremenekc887d132009-04-29 18:50:19 +00002067 if (PrevV.getKind() == RefVal::Released) {
Jordy Rose35c86952011-08-24 05:47:39 +00002068 assert(GCEnabled && CurrV.getCount() > 0);
Jordy Rose74b7b2b2012-03-17 05:49:15 +00002069 os << " The object is not eligible for garbage collection until "
2070 "the retain count reaches 0 again.";
Ted Kremenekc887d132009-04-29 18:50:19 +00002071 }
Mike Stump1eb44332009-09-09 15:08:12 +00002072
Ted Kremenekc887d132009-04-29 18:50:19 +00002073 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002074
Ted Kremenekc887d132009-04-29 18:50:19 +00002075 case RefVal::Released:
2076 os << "Object released.";
2077 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002078
Ted Kremenekc887d132009-04-29 18:50:19 +00002079 case RefVal::ReturnedOwned:
Jordy Rose74b7b2b2012-03-17 05:49:15 +00002080 // Autoreleases can be applied after marking a node ReturnedOwned.
2081 if (CurrV.getAutoreleaseCount())
2082 return NULL;
2083
2084 os << "Object returned to caller as an owning reference (single "
2085 "retain count transferred to caller)";
Ted Kremenekc887d132009-04-29 18:50:19 +00002086 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002087
Ted Kremenekc887d132009-04-29 18:50:19 +00002088 case RefVal::ReturnedNotOwned:
Ted Kremenekf1365462011-05-26 18:45:44 +00002089 os << "Object returned to caller with a +0 retain count";
Ted Kremenekc887d132009-04-29 18:50:19 +00002090 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002091
Ted Kremenekc887d132009-04-29 18:50:19 +00002092 default:
2093 return NULL;
2094 }
Mike Stump1eb44332009-09-09 15:08:12 +00002095
Ted Kremenekc887d132009-04-29 18:50:19 +00002096 // Emit any remaining diagnostics for the argument effects (if any).
Chris Lattner5f9e2722011-07-23 10:55:15 +00002097 for (SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
Ted Kremenekc887d132009-04-29 18:50:19 +00002098 E=AEffects.end(); I != E; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +00002099
Ted Kremenekc887d132009-04-29 18:50:19 +00002100 // A bunch of things have alternate behavior under GC.
Jordy Rose35c86952011-08-24 05:47:39 +00002101 if (GCEnabled)
Ted Kremenekc887d132009-04-29 18:50:19 +00002102 switch (*I) {
2103 default: break;
2104 case Autorelease:
2105 os << "In GC mode an 'autorelease' has no effect.";
2106 continue;
2107 case IncRefMsg:
2108 os << "In GC mode the 'retain' message has no effect.";
2109 continue;
2110 case DecRefMsg:
2111 os << "In GC mode the 'release' message has no effect.";
2112 continue;
2113 }
2114 }
Mike Stump1eb44332009-09-09 15:08:12 +00002115 } while (0);
2116
Ted Kremenekc887d132009-04-29 18:50:19 +00002117 if (os.str().empty())
2118 return 0; // We have nothing to say!
Ted Kremenek2033a952009-05-13 07:12:33 +00002119
David Blaikie7a95de62013-02-21 22:23:56 +00002120 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
Anna Zaks220ac8c2011-09-15 01:08:34 +00002121 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
2122 N->getLocationContext());
Ted Kremenek9c378f72011-08-12 23:37:29 +00002123 PathDiagnosticPiece *P = new PathDiagnosticEventPiece(Pos, os.str());
Mike Stump1eb44332009-09-09 15:08:12 +00002124
Ted Kremenekc887d132009-04-29 18:50:19 +00002125 // Add the range by scanning the children of the statement for any bindings
2126 // to Sym.
Mike Stump1eb44332009-09-09 15:08:12 +00002127 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
Ted Kremenek5f85e172009-07-22 22:35:28 +00002128 I!=E; ++I)
Ted Kremenek9c378f72011-08-12 23:37:29 +00002129 if (const Expr *Exp = dyn_cast_or_null<Expr>(*I))
Ted Kremenek5eca4822012-01-06 22:09:28 +00002130 if (CurrSt->getSValAsScalarOrLoc(Exp, LCtx).getAsLocSymbol() == Sym) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002131 P->addRange(Exp->getSourceRange());
2132 break;
2133 }
Mike Stump1eb44332009-09-09 15:08:12 +00002134
Ted Kremenekc887d132009-04-29 18:50:19 +00002135 return P;
2136}
2137
Anna Zakse7e01682012-02-28 22:39:22 +00002138// Find the first node in the current function context that referred to the
2139// tracked symbol and the memory location that value was stored to. Note, the
2140// value is only reported if the allocation occurred in the same function as
Anna Zaks7a87e522013-04-10 21:42:06 +00002141// the leak. The function can also return a location context, which should be
2142// treated as interesting.
2143struct AllocationInfo {
2144 const ExplodedNode* N;
Anna Zaksee9043b2013-04-10 22:56:30 +00002145 const MemRegion *R;
Anna Zaks7a87e522013-04-10 21:42:06 +00002146 const LocationContext *InterestingMethodContext;
Anna Zaksee9043b2013-04-10 22:56:30 +00002147 AllocationInfo(const ExplodedNode *InN,
2148 const MemRegion *InR,
Anna Zaks7a87e522013-04-10 21:42:06 +00002149 const LocationContext *InInterestingMethodContext) :
2150 N(InN), R(InR), InterestingMethodContext(InInterestingMethodContext) {}
2151};
2152
2153static AllocationInfo
Ted Kremenek18c66fd2011-08-15 22:09:50 +00002154GetAllocationSite(ProgramStateManager& StateMgr, const ExplodedNode *N,
Ted Kremenekc887d132009-04-29 18:50:19 +00002155 SymbolRef Sym) {
Anna Zaks7a87e522013-04-10 21:42:06 +00002156 const ExplodedNode *AllocationNode = N;
2157 const ExplodedNode *AllocationNodeInCurrentContext = N;
Mike Stump1eb44332009-09-09 15:08:12 +00002158 const MemRegion* FirstBinding = 0;
Anna Zakse7e01682012-02-28 22:39:22 +00002159 const LocationContext *LeakContext = N->getLocationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002160
Anna Zaks7a87e522013-04-10 21:42:06 +00002161 // The location context of the init method called on the leaked object, if
2162 // available.
2163 const LocationContext *InitMethodContext = 0;
2164
Ted Kremenekc887d132009-04-29 18:50:19 +00002165 while (N) {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002166 ProgramStateRef St = N->getState();
Anna Zaks7a87e522013-04-10 21:42:06 +00002167 const LocationContext *NContext = N->getLocationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002168
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002169 if (!getRefBinding(St, Sym))
Ted Kremenekc887d132009-04-29 18:50:19 +00002170 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002171
Anna Zaks27b867e2012-03-21 19:45:01 +00002172 StoreManager::FindUniqueBinding FB(Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002173 StateMgr.iterBindings(St, FB);
Anna Zaks7a87e522013-04-10 21:42:06 +00002174
Anna Zaks27d99dd2013-04-10 21:42:02 +00002175 if (FB) {
2176 const MemRegion *R = FB.getRegion();
Anna Zaks8cf91f72013-04-10 22:56:33 +00002177 const VarRegion *VR = R->getBaseRegion()->getAs<VarRegion>();
Anna Zaks27d99dd2013-04-10 21:42:02 +00002178 // Do not show local variables belonging to a function other than
2179 // where the error is reported.
2180 if (!VR || VR->getStackFrame() == LeakContext->getCurrentStackFrame())
Anna Zaks7a87e522013-04-10 21:42:06 +00002181 FirstBinding = R;
Anna Zaks27d99dd2013-04-10 21:42:02 +00002182 }
Mike Stump1eb44332009-09-09 15:08:12 +00002183
Anna Zaks7a87e522013-04-10 21:42:06 +00002184 // AllocationNode is the last node in which the symbol was tracked.
2185 AllocationNode = N;
2186
2187 // AllocationNodeInCurrentContext, is the last node in the current context
2188 // in which the symbol was tracked.
2189 if (NContext == LeakContext)
2190 AllocationNodeInCurrentContext = N;
2191
Anna Zaksee9043b2013-04-10 22:56:30 +00002192 // Find the last init that was called on the given symbol and store the
2193 // init method's location context.
2194 if (!InitMethodContext)
2195 if (Optional<CallEnter> CEP = N->getLocation().getAs<CallEnter>()) {
2196 const Stmt *CE = CEP->getCallExpr();
Anna Zaks3d8f4622013-04-25 00:41:32 +00002197 if (const ObjCMessageExpr *ME = dyn_cast_or_null<ObjCMessageExpr>(CE)) {
Anna Zaksee9043b2013-04-10 22:56:30 +00002198 const Stmt *RecExpr = ME->getInstanceReceiver();
2199 if (RecExpr) {
2200 SVal RecV = St->getSVal(RecExpr, NContext);
2201 if (ME->getMethodFamily() == OMF_init && RecV.getAsSymbol() == Sym)
2202 InitMethodContext = CEP->getCalleeContext();
2203 }
2204 }
Anna Zaks7a87e522013-04-10 21:42:06 +00002205 }
Anna Zakse7e01682012-02-28 22:39:22 +00002206
Mike Stump1eb44332009-09-09 15:08:12 +00002207 N = N->pred_empty() ? NULL : *(N->pred_begin());
Ted Kremenekc887d132009-04-29 18:50:19 +00002208 }
Mike Stump1eb44332009-09-09 15:08:12 +00002209
Anna Zaks7a87e522013-04-10 21:42:06 +00002210 // If we are reporting a leak of the object that was allocated with alloc,
Anna Zaksee9043b2013-04-10 22:56:30 +00002211 // mark its init method as interesting.
Anna Zaks7a87e522013-04-10 21:42:06 +00002212 const LocationContext *InterestingMethodContext = 0;
2213 if (InitMethodContext) {
2214 const ProgramPoint AllocPP = AllocationNode->getLocation();
2215 if (Optional<StmtPoint> SP = AllocPP.getAs<StmtPoint>())
2216 if (const ObjCMessageExpr *ME = SP->getStmtAs<ObjCMessageExpr>())
2217 if (ME->getMethodFamily() == OMF_alloc)
2218 InterestingMethodContext = InitMethodContext;
2219 }
2220
Anna Zakse7e01682012-02-28 22:39:22 +00002221 // If allocation happened in a function different from the leak node context,
2222 // do not report the binding.
Ted Kremenek5a8fc882012-10-12 22:56:40 +00002223 assert(N && "Could not find allocation node");
Anna Zakse7e01682012-02-28 22:39:22 +00002224 if (N->getLocationContext() != LeakContext) {
2225 FirstBinding = 0;
2226 }
2227
Anna Zaks7a87e522013-04-10 21:42:06 +00002228 return AllocationInfo(AllocationNodeInCurrentContext,
2229 FirstBinding,
2230 InterestingMethodContext);
Ted Kremenekc887d132009-04-29 18:50:19 +00002231}
2232
2233PathDiagnosticPiece*
Anna Zaks23f395e2011-08-20 01:27:22 +00002234CFRefReportVisitor::getEndPath(BugReporterContext &BRC,
2235 const ExplodedNode *EndN,
2236 BugReport &BR) {
Ted Kremenek76aadc32012-03-09 01:13:14 +00002237 BR.markInteresting(Sym);
Anna Zaks23f395e2011-08-20 01:27:22 +00002238 return BugReporterVisitor::getDefaultEndPath(BRC, EndN, BR);
Ted Kremenekc887d132009-04-29 18:50:19 +00002239}
2240
2241PathDiagnosticPiece*
Anna Zaks23f395e2011-08-20 01:27:22 +00002242CFRefLeakReportVisitor::getEndPath(BugReporterContext &BRC,
2243 const ExplodedNode *EndN,
2244 BugReport &BR) {
Mike Stump1eb44332009-09-09 15:08:12 +00002245
Ted Kremenek8966bc12009-05-06 21:39:49 +00002246 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenekc887d132009-04-29 18:50:19 +00002247 // assigned to different variables, etc.
Ted Kremenek76aadc32012-03-09 01:13:14 +00002248 BR.markInteresting(Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002249
Ted Kremenekc887d132009-04-29 18:50:19 +00002250 // We are reporting a leak. Walk up the graph to get to the first node where
2251 // the symbol appeared, and also get the first VarDecl that tracked object
2252 // is stored to.
Anna Zaks7a87e522013-04-10 21:42:06 +00002253 AllocationInfo AllocI =
Ted Kremenekf04dced2009-05-08 23:32:51 +00002254 GetAllocationSite(BRC.getStateManager(), EndN, Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002255
Anna Zaks7a87e522013-04-10 21:42:06 +00002256 const MemRegion* FirstBinding = AllocI.R;
2257 BR.markInteresting(AllocI.InterestingMethodContext);
2258
Anna Zaks4fdf97b2011-09-15 18:56:07 +00002259 SourceManager& SM = BRC.getSourceManager();
Mike Stump1eb44332009-09-09 15:08:12 +00002260
Ted Kremenekc887d132009-04-29 18:50:19 +00002261 // Compute an actual location for the leak. Sometimes a leak doesn't
2262 // occur at an actual statement (e.g., transition between blocks; end
2263 // of function) so we need to walk the graph and compute a real location.
Ted Kremenek9c378f72011-08-12 23:37:29 +00002264 const ExplodedNode *LeakN = EndN;
Anna Zaks4fdf97b2011-09-15 18:56:07 +00002265 PathDiagnosticLocation L = PathDiagnosticLocation::createEndOfPath(LeakN, SM);
Mike Stump1eb44332009-09-09 15:08:12 +00002266
Ted Kremenekc887d132009-04-29 18:50:19 +00002267 std::string sbuf;
2268 llvm::raw_string_ostream os(sbuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002269
Ted Kremenekf1365462011-05-26 18:45:44 +00002270 os << "Object leaked: ";
Mike Stump1eb44332009-09-09 15:08:12 +00002271
Ted Kremenekf1365462011-05-26 18:45:44 +00002272 if (FirstBinding) {
2273 os << "object allocated and stored into '"
2274 << FirstBinding->getString() << '\'';
2275 }
2276 else
2277 os << "allocated object";
Mike Stump1eb44332009-09-09 15:08:12 +00002278
Ted Kremenekc887d132009-04-29 18:50:19 +00002279 // Get the retain count.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002280 const RefVal* RV = getRefBinding(EndN->getState(), Sym);
Ted Kremenek5a8fc882012-10-12 22:56:40 +00002281 assert(RV);
Mike Stump1eb44332009-09-09 15:08:12 +00002282
Ted Kremenekc887d132009-04-29 18:50:19 +00002283 if (RV->getKind() == RefVal::ErrorLeakReturned) {
2284 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
Jordy Rose5b5402b2011-07-15 22:17:54 +00002285 // objects. Only "copy", "alloc", "retain" and "new" transfer ownership
Ted Kremenekc887d132009-04-29 18:50:19 +00002286 // to the caller for NS objects.
Ted Kremenekd368d712011-05-25 06:19:45 +00002287 const Decl *D = &EndN->getCodeDecl();
Ted Kremenekec9f36e2012-09-06 23:03:07 +00002288
2289 os << (isa<ObjCMethodDecl>(D) ? " is returned from a method "
2290 : " is returned from a function ");
2291
2292 if (D->getAttr<CFReturnsNotRetainedAttr>())
2293 os << "that is annotated as CF_RETURNS_NOT_RETAINED";
2294 else if (D->getAttr<NSReturnsNotRetainedAttr>())
2295 os << "that is annotated as NS_RETURNS_NOT_RETAINED";
Ted Kremenekd368d712011-05-25 06:19:45 +00002296 else {
Ted Kremenekec9f36e2012-09-06 23:03:07 +00002297 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2298 os << "whose name ('" << MD->getSelector().getAsString()
2299 << "') does not start with 'copy', 'mutableCopy', 'alloc' or 'new'."
2300 " This violates the naming convention rules"
2301 " given in the Memory Management Guide for Cocoa";
2302 }
2303 else {
2304 const FunctionDecl *FD = cast<FunctionDecl>(D);
2305 os << "whose name ('" << *FD
2306 << "') does not contain 'Copy' or 'Create'. This violates the naming"
2307 " convention rules given in the Memory Management Guide for Core"
2308 " Foundation";
2309 }
2310 }
Ted Kremenekc887d132009-04-29 18:50:19 +00002311 }
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002312 else if (RV->getKind() == RefVal::ErrorGCLeakReturned) {
David Blaikiee1300142013-02-21 22:37:44 +00002313 const ObjCMethodDecl &MD = cast<ObjCMethodDecl>(EndN->getCodeDecl());
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002314 os << " and returned from method '" << MD.getSelector().getAsString()
Ted Kremenek82f2be52009-05-10 16:52:15 +00002315 << "' is potentially leaked when using garbage collection. Callers "
2316 "of this method do not expect a returned object with a +1 retain "
2317 "count since they expect the object to be managed by the garbage "
2318 "collector";
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002319 }
Ted Kremenekc887d132009-04-29 18:50:19 +00002320 else
Ted Kremenekabf517c2010-10-15 22:50:23 +00002321 os << " is not referenced later in this execution path and has a retain "
Ted Kremenekf1365462011-05-26 18:45:44 +00002322 "count of +" << RV->getCount();
Mike Stump1eb44332009-09-09 15:08:12 +00002323
Ted Kremenekc887d132009-04-29 18:50:19 +00002324 return new PathDiagnosticEventPiece(L, os.str());
2325}
2326
Jordy Rose20589562011-08-24 22:39:09 +00002327CFRefLeakReport::CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts,
2328 bool GCEnabled, const SummaryLogTy &Log,
2329 ExplodedNode *n, SymbolRef sym,
Ted Kremenek08a838d2013-04-16 21:44:22 +00002330 CheckerContext &Ctx,
2331 bool IncludeAllocationLine)
2332 : CFRefReport(D, LOpts, GCEnabled, Log, n, sym, false) {
Mike Stump1eb44332009-09-09 15:08:12 +00002333
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00002334 // Most bug reports are cached at the location where they occurred.
Ted Kremenekc887d132009-04-29 18:50:19 +00002335 // With leaks, we want to unique them by the location where they were
2336 // allocated, and only report a single path. To do this, we need to find
2337 // the allocation site of a piece of tracked memory, which we do via a
2338 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2339 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2340 // that all ancestor nodes that represent the allocation site have the
2341 // same SourceLocation.
Ted Kremenek9c378f72011-08-12 23:37:29 +00002342 const ExplodedNode *AllocNode = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002343
Anna Zaks6a93bd52011-10-25 19:57:11 +00002344 const SourceManager& SMgr = Ctx.getSourceManager();
Anna Zaks590dd8e2011-09-20 21:38:35 +00002345
Anna Zaks7a87e522013-04-10 21:42:06 +00002346 AllocationInfo AllocI =
Anna Zaks6a93bd52011-10-25 19:57:11 +00002347 GetAllocationSite(Ctx.getStateManager(), getErrorNode(), sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002348
Anna Zaks7a87e522013-04-10 21:42:06 +00002349 AllocNode = AllocI.N;
2350 AllocBinding = AllocI.R;
2351 markInteresting(AllocI.InterestingMethodContext);
2352
Ted Kremenekc887d132009-04-29 18:50:19 +00002353 // Get the SourceLocation for the allocation site.
Jordan Rose852aa0d2012-07-10 22:07:52 +00002354 // FIXME: This will crash the analyzer if an allocation comes from an
2355 // implicit call. (Currently there are no such allocations in Cocoa, though.)
2356 const Stmt *AllocStmt;
Ted Kremenekc887d132009-04-29 18:50:19 +00002357 ProgramPoint P = AllocNode->getLocation();
David Blaikie7a95de62013-02-21 22:23:56 +00002358 if (Optional<CallExitEnd> Exit = P.getAs<CallExitEnd>())
Jordan Rose852aa0d2012-07-10 22:07:52 +00002359 AllocStmt = Exit->getCalleeContext()->getCallSite();
2360 else
David Blaikie7a95de62013-02-21 22:23:56 +00002361 AllocStmt = P.castAs<PostStmt>().getStmt();
Jordan Rose852aa0d2012-07-10 22:07:52 +00002362 assert(AllocStmt && "All allocations must come from explicit calls");
Anna Zakse3a813a2013-04-23 23:57:50 +00002363
2364 PathDiagnosticLocation AllocLocation =
2365 PathDiagnosticLocation::createBegin(AllocStmt, SMgr,
2366 AllocNode->getLocationContext());
2367 Location = AllocLocation;
2368
2369 // Set uniqieing info, which will be used for unique the bug reports. The
2370 // leaks should be uniqued on the allocation site.
2371 UniqueingLocation = AllocLocation;
2372 UniqueingDecl = AllocNode->getLocationContext()->getDecl();
2373
Ted Kremenekc887d132009-04-29 18:50:19 +00002374 // Fill in the description of the bug.
2375 Description.clear();
2376 llvm::raw_string_ostream os(Description);
Ted Kremenekdd924e22009-05-02 19:05:19 +00002377 os << "Potential leak ";
Jordy Rose20589562011-08-24 22:39:09 +00002378 if (GCEnabled)
Ted Kremenekdd924e22009-05-02 19:05:19 +00002379 os << "(when using garbage collection) ";
Anna Zaks212000e2012-02-28 21:49:08 +00002380 os << "of an object";
Mike Stump1eb44332009-09-09 15:08:12 +00002381
Ted Kremenek08a838d2013-04-16 21:44:22 +00002382 if (AllocBinding) {
Anna Zaks212000e2012-02-28 21:49:08 +00002383 os << " stored into '" << AllocBinding->getString() << '\'';
Ted Kremenek08a838d2013-04-16 21:44:22 +00002384 if (IncludeAllocationLine) {
2385 FullSourceLoc SL(AllocStmt->getLocStart(), Ctx.getSourceManager());
2386 os << " (allocated on line " << SL.getSpellingLineNumber() << ")";
2387 }
2388 }
Anna Zaksdc757b02011-08-19 23:21:56 +00002389
Jordy Rose20589562011-08-24 22:39:09 +00002390 addVisitor(new CFRefLeakReportVisitor(sym, GCEnabled, Log));
Ted Kremenekc887d132009-04-29 18:50:19 +00002391}
2392
2393//===----------------------------------------------------------------------===//
2394// Main checker logic.
2395//===----------------------------------------------------------------------===//
2396
Ted Kremenekd593eb92009-11-25 22:17:44 +00002397namespace {
Jordy Rose910c4052011-09-02 06:44:22 +00002398class RetainCountChecker
Jordy Rose9c083b72011-08-24 18:56:32 +00002399 : public Checker< check::Bind,
Jordy Rose38f17d62011-08-23 19:01:07 +00002400 check::DeadSymbols,
Jordy Rose9c083b72011-08-24 18:56:32 +00002401 check::EndAnalysis,
Anna Zaks344c77a2013-01-03 00:25:29 +00002402 check::EndFunction,
Jordy Rose67044292011-08-17 21:27:39 +00002403 check::PostStmt<BlockExpr>,
John McCallf85e1932011-06-15 23:02:42 +00002404 check::PostStmt<CastExpr>,
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002405 check::PostStmt<ObjCArrayLiteral>,
2406 check::PostStmt<ObjCDictionaryLiteral>,
Jordy Rose70fdbc32012-05-12 05:10:43 +00002407 check::PostStmt<ObjCBoxedExpr>,
Jordan Rosefe6a0112012-07-02 19:28:21 +00002408 check::PostCall,
Jordy Rosef53e8c72011-08-23 19:43:16 +00002409 check::PreStmt<ReturnStmt>,
Jordy Rose67044292011-08-17 21:27:39 +00002410 check::RegionChanges,
Jordy Rose76c506f2011-08-21 21:58:18 +00002411 eval::Assume,
2412 eval::Call > {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002413 mutable OwningPtr<CFRefBug> useAfterRelease, releaseNotOwned;
2414 mutable OwningPtr<CFRefBug> deallocGC, deallocNotOwned;
2415 mutable OwningPtr<CFRefBug> overAutorelease, returnNotOwnedForOwned;
2416 mutable OwningPtr<CFRefBug> leakWithinFunction, leakAtReturn;
2417 mutable OwningPtr<CFRefBug> leakWithinFunctionGC, leakAtReturnGC;
Jordy Rose38f17d62011-08-23 19:01:07 +00002418
2419 typedef llvm::DenseMap<SymbolRef, const SimpleProgramPointTag *> SymbolTagMap;
2420
2421 // This map is only used to ensure proper deletion of any allocated tags.
2422 mutable SymbolTagMap DeadSymbolTags;
2423
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002424 mutable OwningPtr<RetainSummaryManager> Summaries;
2425 mutable OwningPtr<RetainSummaryManager> SummariesGC;
Jordy Rose9c083b72011-08-24 18:56:32 +00002426 mutable SummaryLogTy SummaryLog;
2427 mutable bool ShouldResetSummaryLog;
2428
Ted Kremenek08a838d2013-04-16 21:44:22 +00002429 /// Optional setting to indicate if leak reports should include
2430 /// the allocation line.
2431 mutable bool IncludeAllocationLine;
2432
Jordy Rose2f9a66d2011-08-20 21:17:59 +00002433public:
Ted Kremenek08a838d2013-04-16 21:44:22 +00002434 RetainCountChecker(AnalyzerOptions &AO)
2435 : ShouldResetSummaryLog(false),
2436 IncludeAllocationLine(shouldIncludeAllocationSiteInLeakDiagnostics(AO)) {}
Jordy Rose38f17d62011-08-23 19:01:07 +00002437
Jordy Rose910c4052011-09-02 06:44:22 +00002438 virtual ~RetainCountChecker() {
Jordy Rose38f17d62011-08-23 19:01:07 +00002439 DeleteContainerSeconds(DeadSymbolTags);
2440 }
2441
Jordy Rose9c083b72011-08-24 18:56:32 +00002442 void checkEndAnalysis(ExplodedGraph &G, BugReporter &BR,
2443 ExprEngine &Eng) const {
2444 // FIXME: This is a hack to make sure the summary log gets cleared between
2445 // analyses of different code bodies.
2446 //
2447 // Why is this necessary? Because a checker's lifetime is tied to a
2448 // translation unit, but an ExplodedGraph's lifetime is just a code body.
2449 // Once in a blue moon, a new ExplodedNode will have the same address as an
2450 // old one with an associated summary, and the bug report visitor gets very
2451 // confused. (To make things worse, the summary lifetime is currently also
2452 // tied to a code body, so we get a crash instead of incorrect results.)
Jordy Rose1ab51c72011-08-24 09:27:24 +00002453 //
2454 // Why is this a bad solution? Because if the lifetime of the ExplodedGraph
2455 // changes, things will start going wrong again. Really the lifetime of this
2456 // log needs to be tied to either the specific nodes in it or the entire
2457 // ExplodedGraph, not to a specific part of the code being analyzed.
2458 //
Jordy Rose9c083b72011-08-24 18:56:32 +00002459 // (Also, having stateful local data means that the same checker can't be
2460 // used from multiple threads, but a lot of checkers have incorrect
2461 // assumptions about that anyway. So that wasn't a priority at the time of
2462 // this fix.)
Jordy Rose1ab51c72011-08-24 09:27:24 +00002463 //
Jordy Rose9c083b72011-08-24 18:56:32 +00002464 // This happens at the end of analysis, but bug reports are emitted /after/
2465 // this point. So we can't just clear the summary log now. Instead, we mark
2466 // that the next time we access the summary log, it should be cleared.
2467
2468 // If we never reset the summary log during /this/ code body analysis,
2469 // there were no new summaries. There might still have been summaries from
2470 // the /last/ analysis, so clear them out to make sure the bug report
2471 // visitors don't get confused.
2472 if (ShouldResetSummaryLog)
2473 SummaryLog.clear();
2474
2475 ShouldResetSummaryLog = !SummaryLog.empty();
Jordy Rose1ab51c72011-08-24 09:27:24 +00002476 }
2477
Jordy Rose17a38e22011-09-02 05:55:19 +00002478 CFRefBug *getLeakWithinFunctionBug(const LangOptions &LOpts,
2479 bool GCEnabled) const {
2480 if (GCEnabled) {
Jordy Rosedb92bb62011-08-25 01:14:38 +00002481 if (!leakWithinFunctionGC)
Benjamin Kramerfacde172012-06-06 17:32:50 +00002482 leakWithinFunctionGC.reset(new Leak("Leak of object when using "
2483 "garbage collection"));
Jordy Rose17a38e22011-09-02 05:55:19 +00002484 return leakWithinFunctionGC.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002485 } else {
2486 if (!leakWithinFunction) {
Douglas Gregore289d812011-09-13 17:21:33 +00002487 if (LOpts.getGC() == LangOptions::HybridGC) {
Benjamin Kramerfacde172012-06-06 17:32:50 +00002488 leakWithinFunction.reset(new Leak("Leak of object when not using "
2489 "garbage collection (GC) in "
2490 "dual GC/non-GC code"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002491 } else {
Benjamin Kramerfacde172012-06-06 17:32:50 +00002492 leakWithinFunction.reset(new Leak("Leak"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002493 }
2494 }
Jordy Rose17a38e22011-09-02 05:55:19 +00002495 return leakWithinFunction.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002496 }
2497 }
2498
Jordy Rose17a38e22011-09-02 05:55:19 +00002499 CFRefBug *getLeakAtReturnBug(const LangOptions &LOpts, bool GCEnabled) const {
2500 if (GCEnabled) {
Jordy Rosedb92bb62011-08-25 01:14:38 +00002501 if (!leakAtReturnGC)
Benjamin Kramerfacde172012-06-06 17:32:50 +00002502 leakAtReturnGC.reset(new Leak("Leak of returned object when using "
2503 "garbage collection"));
Jordy Rose17a38e22011-09-02 05:55:19 +00002504 return leakAtReturnGC.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002505 } else {
2506 if (!leakAtReturn) {
Douglas Gregore289d812011-09-13 17:21:33 +00002507 if (LOpts.getGC() == LangOptions::HybridGC) {
Benjamin Kramerfacde172012-06-06 17:32:50 +00002508 leakAtReturn.reset(new Leak("Leak of returned object when not using "
2509 "garbage collection (GC) in dual "
2510 "GC/non-GC code"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002511 } else {
Benjamin Kramerfacde172012-06-06 17:32:50 +00002512 leakAtReturn.reset(new Leak("Leak of returned object"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002513 }
2514 }
Jordy Rose17a38e22011-09-02 05:55:19 +00002515 return leakAtReturn.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002516 }
2517 }
2518
Jordy Rose17a38e22011-09-02 05:55:19 +00002519 RetainSummaryManager &getSummaryManager(ASTContext &Ctx,
2520 bool GCEnabled) const {
2521 // FIXME: We don't support ARC being turned on and off during one analysis.
2522 // (nor, for that matter, do we support changing ASTContexts)
David Blaikie4e4d0842012-03-11 07:00:24 +00002523 bool ARCEnabled = (bool)Ctx.getLangOpts().ObjCAutoRefCount;
Jordy Rose17a38e22011-09-02 05:55:19 +00002524 if (GCEnabled) {
2525 if (!SummariesGC)
Jordy Roseb6cfc092011-08-25 00:10:37 +00002526 SummariesGC.reset(new RetainSummaryManager(Ctx, true, ARCEnabled));
Jordy Rose17a38e22011-09-02 05:55:19 +00002527 else
2528 assert(SummariesGC->isARCEnabled() == ARCEnabled);
Jordy Roseb6cfc092011-08-25 00:10:37 +00002529 return *SummariesGC;
2530 } else {
Jordy Rose17a38e22011-09-02 05:55:19 +00002531 if (!Summaries)
Jordy Roseb6cfc092011-08-25 00:10:37 +00002532 Summaries.reset(new RetainSummaryManager(Ctx, false, ARCEnabled));
Jordy Rose17a38e22011-09-02 05:55:19 +00002533 else
2534 assert(Summaries->isARCEnabled() == ARCEnabled);
Jordy Roseb6cfc092011-08-25 00:10:37 +00002535 return *Summaries;
2536 }
2537 }
2538
Jordy Rose17a38e22011-09-02 05:55:19 +00002539 RetainSummaryManager &getSummaryManager(CheckerContext &C) const {
2540 return getSummaryManager(C.getASTContext(), C.isObjCGCEnabled());
2541 }
2542
Ted Kremenek8bef8232012-01-26 21:29:00 +00002543 void printState(raw_ostream &Out, ProgramStateRef State,
Jordy Rosedbd658e2011-08-28 19:11:56 +00002544 const char *NL, const char *Sep) const;
2545
Anna Zaks390909c2011-10-06 00:43:15 +00002546 void checkBind(SVal loc, SVal val, const Stmt *S, CheckerContext &C) const;
Jordy Roseab027fd2011-08-20 21:16:58 +00002547 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
2548 void checkPostStmt(const CastExpr *CE, CheckerContext &C) const;
John McCallf85e1932011-06-15 23:02:42 +00002549
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002550 void checkPostStmt(const ObjCArrayLiteral *AL, CheckerContext &C) const;
2551 void checkPostStmt(const ObjCDictionaryLiteral *DL, CheckerContext &C) const;
Jordy Rose70fdbc32012-05-12 05:10:43 +00002552 void checkPostStmt(const ObjCBoxedExpr *BE, CheckerContext &C) const;
2553
Jordan Rosefe6a0112012-07-02 19:28:21 +00002554 void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002555
Jordan Rose4531b7d2012-07-02 19:27:43 +00002556 void checkSummary(const RetainSummary &Summ, const CallEvent &Call,
Jordy Rosee38dd952011-08-28 05:16:28 +00002557 CheckerContext &C) const;
Jordy Rose294396b2011-08-22 23:48:23 +00002558
Anna Zaks554067f2012-08-29 23:23:43 +00002559 void processSummaryOfInlined(const RetainSummary &Summ,
2560 const CallEvent &Call,
2561 CheckerContext &C) const;
2562
Jordy Rose76c506f2011-08-21 21:58:18 +00002563 bool evalCall(const CallExpr *CE, CheckerContext &C) const;
2564
Ted Kremenek8bef8232012-01-26 21:29:00 +00002565 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Jordy Roseab027fd2011-08-20 21:16:58 +00002566 bool Assumption) const;
Jordy Rose67044292011-08-17 21:27:39 +00002567
Ted Kremenek8bef8232012-01-26 21:29:00 +00002568 ProgramStateRef
2569 checkRegionChanges(ProgramStateRef state,
Anna Zaksbf53dfa2012-12-20 00:38:25 +00002570 const InvalidatedSymbols *invalidated,
Jordy Rose537716a2011-08-27 22:51:26 +00002571 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00002572 ArrayRef<const MemRegion *> Regions,
Jordan Rose740d4902012-07-02 19:27:35 +00002573 const CallEvent *Call) const;
Jordy Roseab027fd2011-08-20 21:16:58 +00002574
Ted Kremenek8bef8232012-01-26 21:29:00 +00002575 bool wantsRegionChangeUpdate(ProgramStateRef state) const {
Jordy Rose2f9a66d2011-08-20 21:17:59 +00002576 return true;
Jordy Roseab027fd2011-08-20 21:16:58 +00002577 }
Jordy Rose294396b2011-08-22 23:48:23 +00002578
Jordy Rosef53e8c72011-08-23 19:43:16 +00002579 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
2580 void checkReturnWithRetEffect(const ReturnStmt *S, CheckerContext &C,
2581 ExplodedNode *Pred, RetEffect RE, RefVal X,
Ted Kremenek8bef8232012-01-26 21:29:00 +00002582 SymbolRef Sym, ProgramStateRef state) const;
Jordy Rosef53e8c72011-08-23 19:43:16 +00002583
Jordy Rose38f17d62011-08-23 19:01:07 +00002584 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Anna Zaks344c77a2013-01-03 00:25:29 +00002585 void checkEndFunction(CheckerContext &C) const;
Jordy Rose38f17d62011-08-23 19:01:07 +00002586
Ted Kremenek8bef8232012-01-26 21:29:00 +00002587 ProgramStateRef updateSymbol(ProgramStateRef state, SymbolRef sym,
Anna Zaks554067f2012-08-29 23:23:43 +00002588 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
2589 CheckerContext &C) const;
Jordy Rosee0a5d322011-08-23 20:27:16 +00002590
Ted Kremenek8bef8232012-01-26 21:29:00 +00002591 void processNonLeakError(ProgramStateRef St, SourceRange ErrorRange,
Jordy Rose294396b2011-08-22 23:48:23 +00002592 RefVal::Kind ErrorKind, SymbolRef Sym,
2593 CheckerContext &C) const;
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002594
2595 void processObjCLiterals(CheckerContext &C, const Expr *Ex) const;
Jordy Rose294396b2011-08-22 23:48:23 +00002596
Jordy Rose38f17d62011-08-23 19:01:07 +00002597 const ProgramPointTag *getDeadSymbolTag(SymbolRef sym) const;
2598
Ted Kremenek8bef8232012-01-26 21:29:00 +00002599 ProgramStateRef handleSymbolDeath(ProgramStateRef state,
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002600 SymbolRef sid, RefVal V,
2601 SmallVectorImpl<SymbolRef> &Leaked) const;
Jordy Rose38f17d62011-08-23 19:01:07 +00002602
Jordan Rose4ee1c552012-12-06 18:58:18 +00002603 ProgramStateRef
Jordan Rose2bce86c2012-08-18 00:30:16 +00002604 handleAutoreleaseCounts(ProgramStateRef state, ExplodedNode *Pred,
2605 const ProgramPointTag *Tag, CheckerContext &Ctx,
2606 SymbolRef Sym, RefVal V) const;
Jordy Rose8d228632011-08-23 20:07:14 +00002607
Ted Kremenek8bef8232012-01-26 21:29:00 +00002608 ExplodedNode *processLeaks(ProgramStateRef state,
Jordy Rose38f17d62011-08-23 19:01:07 +00002609 SmallVectorImpl<SymbolRef> &Leaked,
Anna Zaks6a93bd52011-10-25 19:57:11 +00002610 CheckerContext &Ctx,
Jordy Rose38f17d62011-08-23 19:01:07 +00002611 ExplodedNode *Pred = 0) const;
Ted Kremenekd593eb92009-11-25 22:17:44 +00002612};
2613} // end anonymous namespace
2614
Jordy Rose67044292011-08-17 21:27:39 +00002615namespace {
2616class StopTrackingCallback : public SymbolVisitor {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002617 ProgramStateRef state;
Jordy Rose67044292011-08-17 21:27:39 +00002618public:
Ted Kremenek8bef8232012-01-26 21:29:00 +00002619 StopTrackingCallback(ProgramStateRef st) : state(st) {}
2620 ProgramStateRef getState() const { return state; }
Jordy Rose67044292011-08-17 21:27:39 +00002621
2622 bool VisitSymbol(SymbolRef sym) {
2623 state = state->remove<RefBindings>(sym);
2624 return true;
2625 }
2626};
2627} // end anonymous namespace
2628
Jordy Rose910c4052011-09-02 06:44:22 +00002629//===----------------------------------------------------------------------===//
2630// Handle statements that may have an effect on refcounts.
2631//===----------------------------------------------------------------------===//
Jordy Rose67044292011-08-17 21:27:39 +00002632
Jordy Rose910c4052011-09-02 06:44:22 +00002633void RetainCountChecker::checkPostStmt(const BlockExpr *BE,
2634 CheckerContext &C) const {
Jordy Rose67044292011-08-17 21:27:39 +00002635
Jordy Rose910c4052011-09-02 06:44:22 +00002636 // Scan the BlockDecRefExprs for any object the retain count checker
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002637 // may be tracking.
John McCall469a1eb2011-02-02 13:00:07 +00002638 if (!BE->getBlockDecl()->hasCaptures())
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002639 return;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002640
Ted Kremenek8bef8232012-01-26 21:29:00 +00002641 ProgramStateRef state = C.getState();
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002642 const BlockDataRegion *R =
Ted Kremenek5eca4822012-01-06 22:09:28 +00002643 cast<BlockDataRegion>(state->getSVal(BE,
2644 C.getLocationContext()).getAsRegion());
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002645
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002646 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
2647 E = R->referenced_vars_end();
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002648
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002649 if (I == E)
2650 return;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002651
Ted Kremenek67d12872009-12-07 22:05:27 +00002652 // FIXME: For now we invalidate the tracking of all symbols passed to blocks
2653 // via captured variables, even though captured variables result in a copy
2654 // and in implicit increment/decrement of a retain count.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002655 SmallVector<const MemRegion*, 10> Regions;
Anna Zaks39ac1872011-10-26 21:06:44 +00002656 const LocationContext *LC = C.getLocationContext();
Ted Kremenekc8413fd2010-12-02 07:49:45 +00002657 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002658
Ted Kremenek67d12872009-12-07 22:05:27 +00002659 for ( ; I != E; ++I) {
Ted Kremeneke3ce2c12012-12-06 07:17:20 +00002660 const VarRegion *VR = I.getCapturedRegion();
Ted Kremenek67d12872009-12-07 22:05:27 +00002661 if (VR->getSuperRegion() == R) {
2662 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2663 }
2664 Regions.push_back(VR);
2665 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002666
Ted Kremenek67d12872009-12-07 22:05:27 +00002667 state =
2668 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
2669 Regions.data() + Regions.size()).getState();
Anna Zaks0bd6b112011-10-26 21:06:34 +00002670 C.addTransition(state);
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002671}
2672
Jordy Rose910c4052011-09-02 06:44:22 +00002673void RetainCountChecker::checkPostStmt(const CastExpr *CE,
2674 CheckerContext &C) const {
John McCallf85e1932011-06-15 23:02:42 +00002675 const ObjCBridgedCastExpr *BE = dyn_cast<ObjCBridgedCastExpr>(CE);
2676 if (!BE)
2677 return;
2678
John McCall71c482c2011-06-17 06:50:50 +00002679 ArgEffect AE = IncRef;
John McCallf85e1932011-06-15 23:02:42 +00002680
2681 switch (BE->getBridgeKind()) {
2682 case clang::OBC_Bridge:
2683 // Do nothing.
2684 return;
2685 case clang::OBC_BridgeRetained:
2686 AE = IncRef;
2687 break;
2688 case clang::OBC_BridgeTransfer:
2689 AE = DecRefBridgedTransfered;
2690 break;
2691 }
2692
Ted Kremenek8bef8232012-01-26 21:29:00 +00002693 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00002694 SymbolRef Sym = state->getSVal(CE, C.getLocationContext()).getAsLocSymbol();
John McCallf85e1932011-06-15 23:02:42 +00002695 if (!Sym)
2696 return;
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002697 const RefVal* T = getRefBinding(state, Sym);
John McCallf85e1932011-06-15 23:02:42 +00002698 if (!T)
2699 return;
2700
John McCallf85e1932011-06-15 23:02:42 +00002701 RefVal::Kind hasErr = (RefVal::Kind) 0;
Jordy Rose17a38e22011-09-02 05:55:19 +00002702 state = updateSymbol(state, Sym, *T, AE, hasErr, C);
John McCallf85e1932011-06-15 23:02:42 +00002703
2704 if (hasErr) {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002705 // FIXME: If we get an error during a bridge cast, should we report it?
2706 // Should we assert that there is no error?
John McCallf85e1932011-06-15 23:02:42 +00002707 return;
2708 }
2709
Anna Zaks0bd6b112011-10-26 21:06:34 +00002710 C.addTransition(state);
John McCallf85e1932011-06-15 23:02:42 +00002711}
2712
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002713void RetainCountChecker::processObjCLiterals(CheckerContext &C,
2714 const Expr *Ex) const {
2715 ProgramStateRef state = C.getState();
2716 const ExplodedNode *pred = C.getPredecessor();
2717 for (Stmt::const_child_iterator it = Ex->child_begin(), et = Ex->child_end() ;
2718 it != et ; ++it) {
2719 const Stmt *child = *it;
2720 SVal V = state->getSVal(child, pred->getLocationContext());
2721 if (SymbolRef sym = V.getAsSymbol())
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002722 if (const RefVal* T = getRefBinding(state, sym)) {
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002723 RefVal::Kind hasErr = (RefVal::Kind) 0;
2724 state = updateSymbol(state, sym, *T, MayEscape, hasErr, C);
2725 if (hasErr) {
2726 processNonLeakError(state, child->getSourceRange(), hasErr, sym, C);
2727 return;
2728 }
2729 }
2730 }
2731
2732 // Return the object as autoreleased.
2733 // RetEffect RE = RetEffect::MakeNotOwned(RetEffect::ObjC);
2734 if (SymbolRef sym =
2735 state->getSVal(Ex, pred->getLocationContext()).getAsSymbol()) {
2736 QualType ResultTy = Ex->getType();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002737 state = setRefBinding(state, sym,
2738 RefVal::makeNotOwned(RetEffect::ObjC, ResultTy));
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002739 }
2740
2741 C.addTransition(state);
2742}
2743
2744void RetainCountChecker::checkPostStmt(const ObjCArrayLiteral *AL,
2745 CheckerContext &C) const {
2746 // Apply the 'MayEscape' to all values.
2747 processObjCLiterals(C, AL);
2748}
2749
2750void RetainCountChecker::checkPostStmt(const ObjCDictionaryLiteral *DL,
2751 CheckerContext &C) const {
2752 // Apply the 'MayEscape' to all keys and values.
2753 processObjCLiterals(C, DL);
2754}
2755
Jordy Rose70fdbc32012-05-12 05:10:43 +00002756void RetainCountChecker::checkPostStmt(const ObjCBoxedExpr *Ex,
2757 CheckerContext &C) const {
2758 const ExplodedNode *Pred = C.getPredecessor();
2759 const LocationContext *LCtx = Pred->getLocationContext();
2760 ProgramStateRef State = Pred->getState();
2761
2762 if (SymbolRef Sym = State->getSVal(Ex, LCtx).getAsSymbol()) {
2763 QualType ResultTy = Ex->getType();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002764 State = setRefBinding(State, Sym,
2765 RefVal::makeNotOwned(RetEffect::ObjC, ResultTy));
Jordy Rose70fdbc32012-05-12 05:10:43 +00002766 }
2767
2768 C.addTransition(State);
2769}
2770
Jordan Rosefe6a0112012-07-02 19:28:21 +00002771void RetainCountChecker::checkPostCall(const CallEvent &Call,
2772 CheckerContext &C) const {
Jordan Rosefe6a0112012-07-02 19:28:21 +00002773 RetainSummaryManager &Summaries = getSummaryManager(C);
2774 const RetainSummary *Summ = Summaries.getSummary(Call, C.getState());
Anna Zaks554067f2012-08-29 23:23:43 +00002775
2776 if (C.wasInlined) {
2777 processSummaryOfInlined(*Summ, Call, C);
2778 return;
2779 }
Jordan Rosefe6a0112012-07-02 19:28:21 +00002780 checkSummary(*Summ, Call, C);
Jordy Rose294396b2011-08-22 23:48:23 +00002781}
2782
Jordy Rose910c4052011-09-02 06:44:22 +00002783/// GetReturnType - Used to get the return type of a message expression or
2784/// function call with the intention of affixing that type to a tracked symbol.
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +00002785/// While the return type can be queried directly from RetEx, when
Jordy Rose910c4052011-09-02 06:44:22 +00002786/// invoking class methods we augment to the return type to be that of
2787/// a pointer to the class (as opposed it just being id).
2788// FIXME: We may be able to do this with related result types instead.
2789// This function is probably overestimating.
2790static QualType GetReturnType(const Expr *RetE, ASTContext &Ctx) {
2791 QualType RetTy = RetE->getType();
2792 // If RetE is not a message expression just return its type.
2793 // If RetE is a message expression, return its types if it is something
2794 /// more specific than id.
2795 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RetE))
2796 if (const ObjCObjectPointerType *PT = RetTy->getAs<ObjCObjectPointerType>())
2797 if (PT->isObjCQualifiedIdType() || PT->isObjCIdType() ||
2798 PT->isObjCClassType()) {
2799 // At this point we know the return type of the message expression is
2800 // id, id<...>, or Class. If we have an ObjCInterfaceDecl, we know this
2801 // is a call to a class method whose type we can resolve. In such
2802 // cases, promote the return type to XXX* (where XXX is the class).
2803 const ObjCInterfaceDecl *D = ME->getReceiverInterface();
2804 return !D ? RetTy :
2805 Ctx.getObjCObjectPointerType(Ctx.getObjCInterfaceType(D));
2806 }
2807
2808 return RetTy;
2809}
2810
Anna Zaks554067f2012-08-29 23:23:43 +00002811// We don't always get the exact modeling of the function with regards to the
2812// retain count checker even when the function is inlined. For example, we need
2813// to stop tracking the symbols which were marked with StopTrackingHard.
2814void RetainCountChecker::processSummaryOfInlined(const RetainSummary &Summ,
2815 const CallEvent &CallOrMsg,
2816 CheckerContext &C) const {
2817 ProgramStateRef state = C.getState();
2818
2819 // Evaluate the effect of the arguments.
2820 for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
2821 if (Summ.getArg(idx) == StopTrackingHard) {
2822 SVal V = CallOrMsg.getArgSVal(idx);
2823 if (SymbolRef Sym = V.getAsLocSymbol()) {
2824 state = removeRefBinding(state, Sym);
2825 }
2826 }
2827 }
2828
2829 // Evaluate the effect on the message receiver.
2830 const ObjCMethodCall *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg);
2831 if (MsgInvocation) {
2832 if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
2833 if (Summ.getReceiverEffect() == StopTrackingHard) {
2834 state = removeRefBinding(state, Sym);
2835 }
2836 }
2837 }
2838
2839 // Consult the summary for the return value.
2840 RetEffect RE = Summ.getRetEffect();
2841 if (RE.getKind() == RetEffect::NoRetHard) {
Jordan Rose2f3017f2012-11-02 23:49:29 +00002842 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
Anna Zaks554067f2012-08-29 23:23:43 +00002843 if (Sym)
2844 state = removeRefBinding(state, Sym);
2845 }
2846
2847 C.addTransition(state);
2848}
2849
Jordy Rose910c4052011-09-02 06:44:22 +00002850void RetainCountChecker::checkSummary(const RetainSummary &Summ,
Jordan Rose4531b7d2012-07-02 19:27:43 +00002851 const CallEvent &CallOrMsg,
Jordy Rose910c4052011-09-02 06:44:22 +00002852 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002853 ProgramStateRef state = C.getState();
Jordy Rose294396b2011-08-22 23:48:23 +00002854
2855 // Evaluate the effect of the arguments.
2856 RefVal::Kind hasErr = (RefVal::Kind) 0;
2857 SourceRange ErrorRange;
2858 SymbolRef ErrorSym = 0;
2859
2860 for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
Jordy Rose537716a2011-08-27 22:51:26 +00002861 SVal V = CallOrMsg.getArgSVal(idx);
Jordy Rose294396b2011-08-22 23:48:23 +00002862
2863 if (SymbolRef Sym = V.getAsLocSymbol()) {
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002864 if (const RefVal *T = getRefBinding(state, Sym)) {
Jordy Rose17a38e22011-09-02 05:55:19 +00002865 state = updateSymbol(state, Sym, *T, Summ.getArg(idx), hasErr, C);
Jordy Rose294396b2011-08-22 23:48:23 +00002866 if (hasErr) {
2867 ErrorRange = CallOrMsg.getArgSourceRange(idx);
2868 ErrorSym = Sym;
2869 break;
2870 }
2871 }
2872 }
2873 }
2874
2875 // Evaluate the effect on the message receiver.
2876 bool ReceiverIsTracked = false;
Jordan Rose4531b7d2012-07-02 19:27:43 +00002877 if (!hasErr) {
Jordan Rosecde8cdb2012-07-02 19:27:56 +00002878 const ObjCMethodCall *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg);
Jordan Rose4531b7d2012-07-02 19:27:43 +00002879 if (MsgInvocation) {
2880 if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002881 if (const RefVal *T = getRefBinding(state, Sym)) {
Jordan Rose4531b7d2012-07-02 19:27:43 +00002882 ReceiverIsTracked = true;
2883 state = updateSymbol(state, Sym, *T, Summ.getReceiverEffect(),
Anna Zaks554067f2012-08-29 23:23:43 +00002884 hasErr, C);
Jordan Rose4531b7d2012-07-02 19:27:43 +00002885 if (hasErr) {
Jordan Rose8919e682012-07-18 21:59:51 +00002886 ErrorRange = MsgInvocation->getOriginExpr()->getReceiverRange();
Jordan Rose4531b7d2012-07-02 19:27:43 +00002887 ErrorSym = Sym;
2888 }
Jordy Rose294396b2011-08-22 23:48:23 +00002889 }
2890 }
2891 }
2892 }
2893
2894 // Process any errors.
2895 if (hasErr) {
2896 processNonLeakError(state, ErrorRange, hasErr, ErrorSym, C);
2897 return;
2898 }
2899
2900 // Consult the summary for the return value.
2901 RetEffect RE = Summ.getRetEffect();
2902
2903 if (RE.getKind() == RetEffect::OwnedWhenTrackedReceiver) {
Jordy Roseb6cfc092011-08-25 00:10:37 +00002904 if (ReceiverIsTracked)
Jordy Rose17a38e22011-09-02 05:55:19 +00002905 RE = getSummaryManager(C).getObjAllocRetEffect();
Jordy Roseb6cfc092011-08-25 00:10:37 +00002906 else
Jordy Rose294396b2011-08-22 23:48:23 +00002907 RE = RetEffect::MakeNoRet();
2908 }
2909
2910 switch (RE.getKind()) {
2911 default:
David Blaikie7530c032012-01-17 06:56:22 +00002912 llvm_unreachable("Unhandled RetEffect.");
Jordy Rose294396b2011-08-22 23:48:23 +00002913
2914 case RetEffect::NoRet:
Anna Zaks554067f2012-08-29 23:23:43 +00002915 case RetEffect::NoRetHard:
Jordy Rose294396b2011-08-22 23:48:23 +00002916 // No work necessary.
2917 break;
2918
2919 case RetEffect::OwnedAllocatedSymbol:
2920 case RetEffect::OwnedSymbol: {
Jordan Rose2f3017f2012-11-02 23:49:29 +00002921 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
Jordy Rose294396b2011-08-22 23:48:23 +00002922 if (!Sym)
2923 break;
2924
Jordan Rose4531b7d2012-07-02 19:27:43 +00002925 // Use the result type from the CallEvent as it automatically adjusts
Jordy Rose294396b2011-08-22 23:48:23 +00002926 // for methods/functions that return references.
Jordan Rose4531b7d2012-07-02 19:27:43 +00002927 QualType ResultTy = CallOrMsg.getResultType();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002928 state = setRefBinding(state, Sym, RefVal::makeOwned(RE.getObjKind(),
2929 ResultTy));
Jordy Rose294396b2011-08-22 23:48:23 +00002930
2931 // FIXME: Add a flag to the checker where allocations are assumed to
Anna Zaksc6ba23f2012-08-14 15:39:13 +00002932 // *not* fail.
Jordy Rose294396b2011-08-22 23:48:23 +00002933 break;
2934 }
2935
2936 case RetEffect::GCNotOwnedSymbol:
2937 case RetEffect::ARCNotOwnedSymbol:
2938 case RetEffect::NotOwnedSymbol: {
2939 const Expr *Ex = CallOrMsg.getOriginExpr();
Jordan Rose2f3017f2012-11-02 23:49:29 +00002940 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
Jordy Rose294396b2011-08-22 23:48:23 +00002941 if (!Sym)
2942 break;
Ted Kremenek74616822012-10-12 22:56:45 +00002943 assert(Ex);
Jordy Rose294396b2011-08-22 23:48:23 +00002944 // Use GetReturnType in order to give [NSFoo alloc] the type NSFoo *.
2945 QualType ResultTy = GetReturnType(Ex, C.getASTContext());
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002946 state = setRefBinding(state, Sym, RefVal::makeNotOwned(RE.getObjKind(),
2947 ResultTy));
Jordy Rose294396b2011-08-22 23:48:23 +00002948 break;
2949 }
2950 }
2951
2952 // This check is actually necessary; otherwise the statement builder thinks
2953 // we've hit a previously-found path.
2954 // Normally addTransition takes care of this, but we want the node pointer.
2955 ExplodedNode *NewNode;
2956 if (state == C.getState()) {
2957 NewNode = C.getPredecessor();
2958 } else {
Anna Zaks0bd6b112011-10-26 21:06:34 +00002959 NewNode = C.addTransition(state);
Jordy Rose294396b2011-08-22 23:48:23 +00002960 }
2961
Jordy Rose9c083b72011-08-24 18:56:32 +00002962 // Annotate the node with summary we used.
2963 if (NewNode) {
2964 // FIXME: This is ugly. See checkEndAnalysis for why it's necessary.
2965 if (ShouldResetSummaryLog) {
2966 SummaryLog.clear();
2967 ShouldResetSummaryLog = false;
2968 }
Jordy Roseec9ef852011-08-23 20:55:48 +00002969 SummaryLog[NewNode] = &Summ;
Jordy Rose9c083b72011-08-24 18:56:32 +00002970 }
Jordy Rose294396b2011-08-22 23:48:23 +00002971}
2972
Jordy Rosee0a5d322011-08-23 20:27:16 +00002973
Ted Kremenek8bef8232012-01-26 21:29:00 +00002974ProgramStateRef
2975RetainCountChecker::updateSymbol(ProgramStateRef state, SymbolRef sym,
Jordy Rose910c4052011-09-02 06:44:22 +00002976 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
2977 CheckerContext &C) const {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002978 // In GC mode [... release] and [... retain] do nothing.
Jordy Rose910c4052011-09-02 06:44:22 +00002979 // In ARC mode they shouldn't exist at all, but we just ignore them.
Jordy Rose17a38e22011-09-02 05:55:19 +00002980 bool IgnoreRetainMsg = C.isObjCGCEnabled();
2981 if (!IgnoreRetainMsg)
David Blaikie4e4d0842012-03-11 07:00:24 +00002982 IgnoreRetainMsg = (bool)C.getASTContext().getLangOpts().ObjCAutoRefCount;
Jordy Rose17a38e22011-09-02 05:55:19 +00002983
Jordy Rosee0a5d322011-08-23 20:27:16 +00002984 switch (E) {
Jordan Rose4531b7d2012-07-02 19:27:43 +00002985 default:
2986 break;
2987 case IncRefMsg:
2988 E = IgnoreRetainMsg ? DoNothing : IncRef;
2989 break;
2990 case DecRefMsg:
2991 E = IgnoreRetainMsg ? DoNothing : DecRef;
2992 break;
Anna Zaks554067f2012-08-29 23:23:43 +00002993 case DecRefMsgAndStopTrackingHard:
2994 E = IgnoreRetainMsg ? StopTracking : DecRefAndStopTrackingHard;
Jordan Rose4531b7d2012-07-02 19:27:43 +00002995 break;
2996 case MakeCollectable:
2997 E = C.isObjCGCEnabled() ? DecRef : DoNothing;
2998 break;
Jordy Rosee0a5d322011-08-23 20:27:16 +00002999 }
3000
3001 // Handle all use-after-releases.
Jordy Rose17a38e22011-09-02 05:55:19 +00003002 if (!C.isObjCGCEnabled() && V.getKind() == RefVal::Released) {
Jordy Rosee0a5d322011-08-23 20:27:16 +00003003 V = V ^ RefVal::ErrorUseAfterRelease;
3004 hasErr = V.getKind();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003005 return setRefBinding(state, sym, V);
Jordy Rosee0a5d322011-08-23 20:27:16 +00003006 }
3007
3008 switch (E) {
3009 case DecRefMsg:
3010 case IncRefMsg:
3011 case MakeCollectable:
Anna Zaks554067f2012-08-29 23:23:43 +00003012 case DecRefMsgAndStopTrackingHard:
Jordy Rosee0a5d322011-08-23 20:27:16 +00003013 llvm_unreachable("DecRefMsg/IncRefMsg/MakeCollectable already converted");
Jordy Rosee0a5d322011-08-23 20:27:16 +00003014
3015 case Dealloc:
3016 // Any use of -dealloc in GC is *bad*.
Jordy Rose17a38e22011-09-02 05:55:19 +00003017 if (C.isObjCGCEnabled()) {
Jordy Rosee0a5d322011-08-23 20:27:16 +00003018 V = V ^ RefVal::ErrorDeallocGC;
3019 hasErr = V.getKind();
3020 break;
3021 }
3022
3023 switch (V.getKind()) {
3024 default:
3025 llvm_unreachable("Invalid RefVal state for an explicit dealloc.");
Jordy Rosee0a5d322011-08-23 20:27:16 +00003026 case RefVal::Owned:
3027 // The object immediately transitions to the released state.
3028 V = V ^ RefVal::Released;
3029 V.clearCounts();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003030 return setRefBinding(state, sym, V);
Jordy Rosee0a5d322011-08-23 20:27:16 +00003031 case RefVal::NotOwned:
3032 V = V ^ RefVal::ErrorDeallocNotOwned;
3033 hasErr = V.getKind();
3034 break;
3035 }
3036 break;
3037
Jordy Rosee0a5d322011-08-23 20:27:16 +00003038 case MayEscape:
3039 if (V.getKind() == RefVal::Owned) {
3040 V = V ^ RefVal::NotOwned;
3041 break;
3042 }
3043
3044 // Fall-through.
3045
Jordy Rosee0a5d322011-08-23 20:27:16 +00003046 case DoNothing:
3047 return state;
3048
3049 case Autorelease:
Jordy Rose17a38e22011-09-02 05:55:19 +00003050 if (C.isObjCGCEnabled())
Jordy Rosee0a5d322011-08-23 20:27:16 +00003051 return state;
Jordy Rosee0a5d322011-08-23 20:27:16 +00003052 // Update the autorelease counts.
Jordy Rosee0a5d322011-08-23 20:27:16 +00003053 V = V.autorelease();
3054 break;
3055
3056 case StopTracking:
Anna Zaks554067f2012-08-29 23:23:43 +00003057 case StopTrackingHard:
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003058 return removeRefBinding(state, sym);
Jordy Rosee0a5d322011-08-23 20:27:16 +00003059
3060 case IncRef:
3061 switch (V.getKind()) {
3062 default:
3063 llvm_unreachable("Invalid RefVal state for a retain.");
Jordy Rosee0a5d322011-08-23 20:27:16 +00003064 case RefVal::Owned:
3065 case RefVal::NotOwned:
3066 V = V + 1;
3067 break;
3068 case RefVal::Released:
3069 // Non-GC cases are handled above.
Jordy Rose17a38e22011-09-02 05:55:19 +00003070 assert(C.isObjCGCEnabled());
Jordy Rosee0a5d322011-08-23 20:27:16 +00003071 V = (V ^ RefVal::Owned) + 1;
3072 break;
3073 }
3074 break;
3075
Jordy Rosee0a5d322011-08-23 20:27:16 +00003076 case DecRef:
3077 case DecRefBridgedTransfered:
Anna Zaks554067f2012-08-29 23:23:43 +00003078 case DecRefAndStopTrackingHard:
Jordy Rosee0a5d322011-08-23 20:27:16 +00003079 switch (V.getKind()) {
3080 default:
3081 // case 'RefVal::Released' handled above.
3082 llvm_unreachable("Invalid RefVal state for a release.");
Jordy Rosee0a5d322011-08-23 20:27:16 +00003083
3084 case RefVal::Owned:
3085 assert(V.getCount() > 0);
3086 if (V.getCount() == 1)
3087 V = V ^ (E == DecRefBridgedTransfered ?
3088 RefVal::NotOwned : RefVal::Released);
Anna Zaks554067f2012-08-29 23:23:43 +00003089 else if (E == DecRefAndStopTrackingHard)
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003090 return removeRefBinding(state, sym);
Jordan Rose4531b7d2012-07-02 19:27:43 +00003091
Jordy Rosee0a5d322011-08-23 20:27:16 +00003092 V = V - 1;
3093 break;
3094
3095 case RefVal::NotOwned:
Jordan Rose4531b7d2012-07-02 19:27:43 +00003096 if (V.getCount() > 0) {
Anna Zaks554067f2012-08-29 23:23:43 +00003097 if (E == DecRefAndStopTrackingHard)
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003098 return removeRefBinding(state, sym);
Jordy Rosee0a5d322011-08-23 20:27:16 +00003099 V = V - 1;
Jordan Rose4531b7d2012-07-02 19:27:43 +00003100 } else {
Jordy Rosee0a5d322011-08-23 20:27:16 +00003101 V = V ^ RefVal::ErrorReleaseNotOwned;
3102 hasErr = V.getKind();
3103 }
3104 break;
3105
3106 case RefVal::Released:
3107 // Non-GC cases are handled above.
Jordy Rose17a38e22011-09-02 05:55:19 +00003108 assert(C.isObjCGCEnabled());
Jordy Rosee0a5d322011-08-23 20:27:16 +00003109 V = V ^ RefVal::ErrorUseAfterRelease;
3110 hasErr = V.getKind();
3111 break;
3112 }
3113 break;
3114 }
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003115 return setRefBinding(state, sym, V);
Jordy Rosee0a5d322011-08-23 20:27:16 +00003116}
3117
Ted Kremenek8bef8232012-01-26 21:29:00 +00003118void RetainCountChecker::processNonLeakError(ProgramStateRef St,
Jordy Rose910c4052011-09-02 06:44:22 +00003119 SourceRange ErrorRange,
3120 RefVal::Kind ErrorKind,
3121 SymbolRef Sym,
3122 CheckerContext &C) const {
Jordy Rose294396b2011-08-22 23:48:23 +00003123 ExplodedNode *N = C.generateSink(St);
3124 if (!N)
3125 return;
3126
Jordy Rose294396b2011-08-22 23:48:23 +00003127 CFRefBug *BT;
3128 switch (ErrorKind) {
3129 default:
3130 llvm_unreachable("Unhandled error.");
Jordy Rose294396b2011-08-22 23:48:23 +00003131 case RefVal::ErrorUseAfterRelease:
Jordy Rosed6334e12011-08-25 00:34:03 +00003132 if (!useAfterRelease)
3133 useAfterRelease.reset(new UseAfterRelease());
3134 BT = &*useAfterRelease;
Jordy Rose294396b2011-08-22 23:48:23 +00003135 break;
3136 case RefVal::ErrorReleaseNotOwned:
Jordy Rosed6334e12011-08-25 00:34:03 +00003137 if (!releaseNotOwned)
3138 releaseNotOwned.reset(new BadRelease());
3139 BT = &*releaseNotOwned;
Jordy Rose294396b2011-08-22 23:48:23 +00003140 break;
3141 case RefVal::ErrorDeallocGC:
Jordy Rosed6334e12011-08-25 00:34:03 +00003142 if (!deallocGC)
3143 deallocGC.reset(new DeallocGC());
3144 BT = &*deallocGC;
Jordy Rose294396b2011-08-22 23:48:23 +00003145 break;
3146 case RefVal::ErrorDeallocNotOwned:
Jordy Rosed6334e12011-08-25 00:34:03 +00003147 if (!deallocNotOwned)
3148 deallocNotOwned.reset(new DeallocNotOwned());
3149 BT = &*deallocNotOwned;
Jordy Rose294396b2011-08-22 23:48:23 +00003150 break;
3151 }
3152
Jordy Rosed6334e12011-08-25 00:34:03 +00003153 assert(BT);
David Blaikie4e4d0842012-03-11 07:00:24 +00003154 CFRefReport *report = new CFRefReport(*BT, C.getASTContext().getLangOpts(),
Jordy Rose17a38e22011-09-02 05:55:19 +00003155 C.isObjCGCEnabled(), SummaryLog,
3156 N, Sym);
Jordy Rose294396b2011-08-22 23:48:23 +00003157 report->addRange(ErrorRange);
Jordan Rose785950e2012-11-02 01:53:40 +00003158 C.emitReport(report);
Jordy Rose294396b2011-08-22 23:48:23 +00003159}
3160
Jordy Rose910c4052011-09-02 06:44:22 +00003161//===----------------------------------------------------------------------===//
3162// Handle the return values of retain-count-related functions.
3163//===----------------------------------------------------------------------===//
3164
3165bool RetainCountChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
Jordy Rose76c506f2011-08-21 21:58:18 +00003166 // Get the callee. We're only interested in simple C functions.
Ted Kremenek8bef8232012-01-26 21:29:00 +00003167 ProgramStateRef state = C.getState();
Anna Zaksb805c8f2011-12-01 05:57:37 +00003168 const FunctionDecl *FD = C.getCalleeDecl(CE);
Jordy Rose76c506f2011-08-21 21:58:18 +00003169 if (!FD)
3170 return false;
3171
3172 IdentifierInfo *II = FD->getIdentifier();
3173 if (!II)
3174 return false;
3175
3176 // For now, we're only handling the functions that return aliases of their
3177 // arguments: CFRetain and CFMakeCollectable (and their families).
3178 // Eventually we should add other functions we can model entirely,
3179 // such as CFRelease, which don't invalidate their arguments or globals.
3180 if (CE->getNumArgs() != 1)
3181 return false;
3182
3183 // Get the name of the function.
3184 StringRef FName = II->getName();
3185 FName = FName.substr(FName.find_first_not_of('_'));
3186
3187 // See if it's one of the specific functions we know how to eval.
3188 bool canEval = false;
3189
Anna Zaksb805c8f2011-12-01 05:57:37 +00003190 QualType ResultTy = CE->getCallReturnType();
Jordy Rose76c506f2011-08-21 21:58:18 +00003191 if (ResultTy->isObjCIdType()) {
3192 // Handle: id NSMakeCollectable(CFTypeRef)
3193 canEval = II->isStr("NSMakeCollectable");
3194 } else if (ResultTy->isPointerType()) {
3195 // Handle: (CF|CG)Retain
3196 // CFMakeCollectable
3197 // It's okay to be a little sloppy here (CGMakeCollectable doesn't exist).
3198 if (cocoa::isRefType(ResultTy, "CF", FName) ||
3199 cocoa::isRefType(ResultTy, "CG", FName)) {
3200 canEval = isRetain(FD, FName) || isMakeCollectable(FD, FName);
3201 }
3202 }
3203
3204 if (!canEval)
3205 return false;
3206
3207 // Bind the return value.
Ted Kremenek5eca4822012-01-06 22:09:28 +00003208 const LocationContext *LCtx = C.getLocationContext();
3209 SVal RetVal = state->getSVal(CE->getArg(0), LCtx);
Jordy Rose76c506f2011-08-21 21:58:18 +00003210 if (RetVal.isUnknown()) {
3211 // If the receiver is unknown, conjure a return value.
3212 SValBuilder &SVB = C.getSValBuilder();
Ted Kremenek66c486f2012-08-22 06:26:15 +00003213 RetVal = SVB.conjureSymbolVal(0, CE, LCtx, ResultTy, C.blockCount());
Jordy Rose76c506f2011-08-21 21:58:18 +00003214 }
Ted Kremenek5eca4822012-01-06 22:09:28 +00003215 state = state->BindExpr(CE, LCtx, RetVal, false);
Jordy Rose76c506f2011-08-21 21:58:18 +00003216
Jordy Rose294396b2011-08-22 23:48:23 +00003217 // FIXME: This should not be necessary, but otherwise the argument seems to be
3218 // considered alive during the next statement.
3219 if (const MemRegion *ArgRegion = RetVal.getAsRegion()) {
3220 // Save the refcount status of the argument.
3221 SymbolRef Sym = RetVal.getAsLocSymbol();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003222 const RefVal *Binding = 0;
Jordy Rose294396b2011-08-22 23:48:23 +00003223 if (Sym)
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003224 Binding = getRefBinding(state, Sym);
Jordy Rose76c506f2011-08-21 21:58:18 +00003225
Jordy Rose294396b2011-08-22 23:48:23 +00003226 // Invalidate the argument region.
Anna Zaksbf53dfa2012-12-20 00:38:25 +00003227 state = state->invalidateRegions(ArgRegion, CE, C.blockCount(), LCtx,
Anna Zaks64eb0702013-01-16 01:35:54 +00003228 /*CausesPointerEscape*/ false);
Jordy Rose76c506f2011-08-21 21:58:18 +00003229
Jordy Rose294396b2011-08-22 23:48:23 +00003230 // Restore the refcount status of the argument.
3231 if (Binding)
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003232 state = setRefBinding(state, Sym, *Binding);
Jordy Rose294396b2011-08-22 23:48:23 +00003233 }
3234
Anna Zaks0bd6b112011-10-26 21:06:34 +00003235 C.addTransition(state);
Jordy Rose76c506f2011-08-21 21:58:18 +00003236 return true;
3237}
3238
Jordy Rose910c4052011-09-02 06:44:22 +00003239//===----------------------------------------------------------------------===//
3240// Handle return statements.
3241//===----------------------------------------------------------------------===//
Jordy Rosef53e8c72011-08-23 19:43:16 +00003242
Jordy Rose910c4052011-09-02 06:44:22 +00003243void RetainCountChecker::checkPreStmt(const ReturnStmt *S,
3244 CheckerContext &C) const {
Ted Kremeneke5715782012-02-25 02:09:09 +00003245
3246 // Only adjust the reference count if this is the top-level call frame,
3247 // and not the result of inlining. In the future, we should do
3248 // better checking even for inlined calls, and see if they match
3249 // with their expected semantics (e.g., the method should return a retained
3250 // object, etc.).
Anna Zaksfadcd5d2012-11-03 02:54:16 +00003251 if (!C.inTopFrame())
Ted Kremeneke5715782012-02-25 02:09:09 +00003252 return;
3253
Jordy Rosef53e8c72011-08-23 19:43:16 +00003254 const Expr *RetE = S->getRetValue();
3255 if (!RetE)
3256 return;
3257
Ted Kremenek8bef8232012-01-26 21:29:00 +00003258 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00003259 SymbolRef Sym =
3260 state->getSValAsScalarOrLoc(RetE, C.getLocationContext()).getAsLocSymbol();
Jordy Rosef53e8c72011-08-23 19:43:16 +00003261 if (!Sym)
3262 return;
3263
3264 // Get the reference count binding (if any).
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003265 const RefVal *T = getRefBinding(state, Sym);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003266 if (!T)
3267 return;
3268
3269 // Change the reference count.
3270 RefVal X = *T;
3271
3272 switch (X.getKind()) {
3273 case RefVal::Owned: {
3274 unsigned cnt = X.getCount();
3275 assert(cnt > 0);
3276 X.setCount(cnt - 1);
3277 X = X ^ RefVal::ReturnedOwned;
3278 break;
3279 }
3280
3281 case RefVal::NotOwned: {
3282 unsigned cnt = X.getCount();
3283 if (cnt) {
3284 X.setCount(cnt - 1);
3285 X = X ^ RefVal::ReturnedOwned;
3286 }
3287 else {
3288 X = X ^ RefVal::ReturnedNotOwned;
3289 }
3290 break;
3291 }
3292
3293 default:
3294 return;
3295 }
3296
3297 // Update the binding.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003298 state = setRefBinding(state, Sym, X);
Anna Zaks0bd6b112011-10-26 21:06:34 +00003299 ExplodedNode *Pred = C.addTransition(state);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003300
3301 // At this point we have updated the state properly.
3302 // Everything after this is merely checking to see if the return value has
3303 // been over- or under-retained.
3304
3305 // Did we cache out?
3306 if (!Pred)
3307 return;
3308
Jordy Rosef53e8c72011-08-23 19:43:16 +00003309 // Update the autorelease counts.
3310 static SimpleProgramPointTag
Jordy Rose910c4052011-09-02 06:44:22 +00003311 AutoreleaseTag("RetainCountChecker : Autorelease");
Jordan Rose4ee1c552012-12-06 18:58:18 +00003312 state = handleAutoreleaseCounts(state, Pred, &AutoreleaseTag, C, Sym, X);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003313
3314 // Did we cache out?
Jordan Rose4ee1c552012-12-06 18:58:18 +00003315 if (!state)
Jordy Rosef53e8c72011-08-23 19:43:16 +00003316 return;
3317
3318 // Get the updated binding.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003319 T = getRefBinding(state, Sym);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003320 assert(T);
3321 X = *T;
3322
3323 // Consult the summary of the enclosing method.
Jordy Rose17a38e22011-09-02 05:55:19 +00003324 RetainSummaryManager &Summaries = getSummaryManager(C);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003325 const Decl *CD = &Pred->getCodeDecl();
Jordan Rose4531b7d2012-07-02 19:27:43 +00003326 RetEffect RE = RetEffect::MakeNoRet();
Jordy Rosef53e8c72011-08-23 19:43:16 +00003327
Jordan Rose4531b7d2012-07-02 19:27:43 +00003328 // FIXME: What is the convention for blocks? Is there one?
Jordy Rosef53e8c72011-08-23 19:43:16 +00003329 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CD)) {
Jordy Roseb6cfc092011-08-25 00:10:37 +00003330 const RetainSummary *Summ = Summaries.getMethodSummary(MD);
Jordan Rose4531b7d2012-07-02 19:27:43 +00003331 RE = Summ->getRetEffect();
3332 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) {
3333 if (!isa<CXXMethodDecl>(FD)) {
3334 const RetainSummary *Summ = Summaries.getFunctionSummary(FD);
3335 RE = Summ->getRetEffect();
3336 }
Jordy Rosef53e8c72011-08-23 19:43:16 +00003337 }
3338
Jordan Rose4531b7d2012-07-02 19:27:43 +00003339 checkReturnWithRetEffect(S, C, Pred, RE, X, Sym, state);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003340}
3341
Jordy Rose910c4052011-09-02 06:44:22 +00003342void RetainCountChecker::checkReturnWithRetEffect(const ReturnStmt *S,
3343 CheckerContext &C,
3344 ExplodedNode *Pred,
3345 RetEffect RE, RefVal X,
3346 SymbolRef Sym,
Ted Kremenek8bef8232012-01-26 21:29:00 +00003347 ProgramStateRef state) const {
Jordy Rosef53e8c72011-08-23 19:43:16 +00003348 // Any leaks or other errors?
3349 if (X.isReturnedOwned() && X.getCount() == 0) {
3350 if (RE.getKind() != RetEffect::NoRet) {
3351 bool hasError = false;
Jordy Rose17a38e22011-09-02 05:55:19 +00003352 if (C.isObjCGCEnabled() && RE.getObjKind() == RetEffect::ObjC) {
Jordy Rosef53e8c72011-08-23 19:43:16 +00003353 // Things are more complicated with garbage collection. If the
3354 // returned object is suppose to be an Objective-C object, we have
3355 // a leak (as the caller expects a GC'ed object) because no
3356 // method should return ownership unless it returns a CF object.
3357 hasError = true;
3358 X = X ^ RefVal::ErrorGCLeakReturned;
3359 }
3360 else if (!RE.isOwned()) {
3361 // Either we are using GC and the returned object is a CF type
3362 // or we aren't using GC. In either case, we expect that the
3363 // enclosing method is expected to return ownership.
3364 hasError = true;
3365 X = X ^ RefVal::ErrorLeakReturned;
3366 }
3367
3368 if (hasError) {
3369 // Generate an error node.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003370 state = setRefBinding(state, Sym, X);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003371
3372 static SimpleProgramPointTag
Jordy Rose910c4052011-09-02 06:44:22 +00003373 ReturnOwnLeakTag("RetainCountChecker : ReturnsOwnLeak");
Anna Zaks0bd6b112011-10-26 21:06:34 +00003374 ExplodedNode *N = C.addTransition(state, Pred, &ReturnOwnLeakTag);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003375 if (N) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003376 const LangOptions &LOpts = C.getASTContext().getLangOpts();
Jordy Rose17a38e22011-09-02 05:55:19 +00003377 bool GCEnabled = C.isObjCGCEnabled();
Jordy Rosef53e8c72011-08-23 19:43:16 +00003378 CFRefReport *report =
Jordy Rose17a38e22011-09-02 05:55:19 +00003379 new CFRefLeakReport(*getLeakAtReturnBug(LOpts, GCEnabled),
3380 LOpts, GCEnabled, SummaryLog,
Ted Kremenek08a838d2013-04-16 21:44:22 +00003381 N, Sym, C, IncludeAllocationLine);
3382
Jordan Rose785950e2012-11-02 01:53:40 +00003383 C.emitReport(report);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003384 }
3385 }
3386 }
3387 } else if (X.isReturnedNotOwned()) {
3388 if (RE.isOwned()) {
3389 // Trying to return a not owned object to a caller expecting an
3390 // owned object.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003391 state = setRefBinding(state, Sym, X ^ RefVal::ErrorReturnedNotOwned);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003392
3393 static SimpleProgramPointTag
Jordy Rose910c4052011-09-02 06:44:22 +00003394 ReturnNotOwnedTag("RetainCountChecker : ReturnNotOwnedForOwned");
Anna Zaks0bd6b112011-10-26 21:06:34 +00003395 ExplodedNode *N = C.addTransition(state, Pred, &ReturnNotOwnedTag);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003396 if (N) {
Jordy Rosed6334e12011-08-25 00:34:03 +00003397 if (!returnNotOwnedForOwned)
3398 returnNotOwnedForOwned.reset(new ReturnedNotOwnedForOwned());
3399
Jordy Rosef53e8c72011-08-23 19:43:16 +00003400 CFRefReport *report =
Jordy Rosed6334e12011-08-25 00:34:03 +00003401 new CFRefReport(*returnNotOwnedForOwned,
David Blaikie4e4d0842012-03-11 07:00:24 +00003402 C.getASTContext().getLangOpts(),
Jordy Rose17a38e22011-09-02 05:55:19 +00003403 C.isObjCGCEnabled(), SummaryLog, N, Sym);
Jordan Rose785950e2012-11-02 01:53:40 +00003404 C.emitReport(report);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003405 }
3406 }
3407 }
3408}
3409
Jordy Rose8d228632011-08-23 20:07:14 +00003410//===----------------------------------------------------------------------===//
Jordy Rose910c4052011-09-02 06:44:22 +00003411// Check various ways a symbol can be invalidated.
3412//===----------------------------------------------------------------------===//
3413
Anna Zaks390909c2011-10-06 00:43:15 +00003414void RetainCountChecker::checkBind(SVal loc, SVal val, const Stmt *S,
Jordy Rose910c4052011-09-02 06:44:22 +00003415 CheckerContext &C) const {
3416 // Are we storing to something that causes the value to "escape"?
3417 bool escapes = true;
3418
3419 // A value escapes in three possible cases (this may change):
3420 //
3421 // (1) we are binding to something that is not a memory region.
3422 // (2) we are binding to a memregion that does not have stack storage
3423 // (3) we are binding to a memregion with stack storage that the store
3424 // does not understand.
Ted Kremenek8bef8232012-01-26 21:29:00 +00003425 ProgramStateRef state = C.getState();
Jordy Rose910c4052011-09-02 06:44:22 +00003426
David Blaikiedc84cd52013-02-20 22:23:23 +00003427 if (Optional<loc::MemRegionVal> regionLoc = loc.getAs<loc::MemRegionVal>()) {
Jordy Rose910c4052011-09-02 06:44:22 +00003428 escapes = !regionLoc->getRegion()->hasStackStorage();
3429
3430 if (!escapes) {
3431 // To test (3), generate a new state with the binding added. If it is
3432 // the same state, then it escapes (since the store cannot represent
3433 // the binding).
Anna Zakse7958da2012-05-02 00:15:40 +00003434 // Do this only if we know that the store is not supposed to generate the
3435 // same state.
3436 SVal StoredVal = state->getSVal(regionLoc->getRegion());
3437 if (StoredVal != val)
3438 escapes = (state == (state->bindLoc(*regionLoc, val)));
Jordy Rose910c4052011-09-02 06:44:22 +00003439 }
Ted Kremenekde5b4fb2012-03-27 01:12:45 +00003440 if (!escapes) {
3441 // Case 4: We do not currently model what happens when a symbol is
3442 // assigned to a struct field, so be conservative here and let the symbol
3443 // go. TODO: This could definitely be improved upon.
3444 escapes = !isa<VarRegion>(regionLoc->getRegion());
3445 }
Jordy Rose910c4052011-09-02 06:44:22 +00003446 }
3447
3448 // If our store can represent the binding and we aren't storing to something
3449 // that doesn't have local storage then just return and have the simulation
3450 // state continue as is.
3451 if (!escapes)
3452 return;
3453
3454 // Otherwise, find all symbols referenced by 'val' that we are tracking
3455 // and stop tracking them.
3456 state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
Anna Zaks0bd6b112011-10-26 21:06:34 +00003457 C.addTransition(state);
Jordy Rose910c4052011-09-02 06:44:22 +00003458}
3459
Ted Kremenek8bef8232012-01-26 21:29:00 +00003460ProgramStateRef RetainCountChecker::evalAssume(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003461 SVal Cond,
3462 bool Assumption) const {
3463
3464 // FIXME: We may add to the interface of evalAssume the list of symbols
3465 // whose assumptions have changed. For now we just iterate through the
3466 // bindings and check if any of the tracked symbols are NULL. This isn't
3467 // too bad since the number of symbols we will track in practice are
3468 // probably small and evalAssume is only called at branches and a few
3469 // other places.
Jordan Rose166d5022012-11-02 01:54:06 +00003470 RefBindingsTy B = state->get<RefBindings>();
Jordy Rose910c4052011-09-02 06:44:22 +00003471
3472 if (B.isEmpty())
3473 return state;
3474
3475 bool changed = false;
Jordan Rose166d5022012-11-02 01:54:06 +00003476 RefBindingsTy::Factory &RefBFactory = state->get_context<RefBindings>();
Jordy Rose910c4052011-09-02 06:44:22 +00003477
Jordan Rose166d5022012-11-02 01:54:06 +00003478 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Ted Kremenek47cbd0f2012-09-07 22:31:01 +00003479 // Check if the symbol is null stop tracking the symbol.
Jordan Roseec8d4202012-11-01 00:18:27 +00003480 ConstraintManager &CMgr = state->getConstraintManager();
3481 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
3482 if (AllocFailed.isConstrainedTrue()) {
Jordy Rose910c4052011-09-02 06:44:22 +00003483 changed = true;
3484 B = RefBFactory.remove(B, I.getKey());
3485 }
3486 }
3487
3488 if (changed)
3489 state = state->set<RefBindings>(B);
3490
3491 return state;
3492}
3493
Ted Kremenek8bef8232012-01-26 21:29:00 +00003494ProgramStateRef
3495RetainCountChecker::checkRegionChanges(ProgramStateRef state,
Anna Zaksbf53dfa2012-12-20 00:38:25 +00003496 const InvalidatedSymbols *invalidated,
Jordy Rose910c4052011-09-02 06:44:22 +00003497 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00003498 ArrayRef<const MemRegion *> Regions,
Jordan Rose740d4902012-07-02 19:27:35 +00003499 const CallEvent *Call) const {
Jordy Rose910c4052011-09-02 06:44:22 +00003500 if (!invalidated)
3501 return state;
3502
3503 llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
3504 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
3505 E = ExplicitRegions.end(); I != E; ++I) {
3506 if (const SymbolicRegion *SR = (*I)->StripCasts()->getAs<SymbolicRegion>())
3507 WhitelistedSymbols.insert(SR->getSymbol());
3508 }
3509
Anna Zaksbf53dfa2012-12-20 00:38:25 +00003510 for (InvalidatedSymbols::const_iterator I=invalidated->begin(),
Jordy Rose910c4052011-09-02 06:44:22 +00003511 E = invalidated->end(); I!=E; ++I) {
3512 SymbolRef sym = *I;
3513 if (WhitelistedSymbols.count(sym))
3514 continue;
3515 // Remove any existing reference-count binding.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003516 state = removeRefBinding(state, sym);
Jordy Rose910c4052011-09-02 06:44:22 +00003517 }
3518 return state;
3519}
3520
3521//===----------------------------------------------------------------------===//
Jordy Rose8d228632011-08-23 20:07:14 +00003522// Handle dead symbols and end-of-path.
3523//===----------------------------------------------------------------------===//
3524
Jordan Rose4ee1c552012-12-06 18:58:18 +00003525ProgramStateRef
3526RetainCountChecker::handleAutoreleaseCounts(ProgramStateRef state,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003527 ExplodedNode *Pred,
Jordan Rose2bce86c2012-08-18 00:30:16 +00003528 const ProgramPointTag *Tag,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003529 CheckerContext &Ctx,
Jordy Rose910c4052011-09-02 06:44:22 +00003530 SymbolRef Sym, RefVal V) const {
Jordy Rose8d228632011-08-23 20:07:14 +00003531 unsigned ACnt = V.getAutoreleaseCount();
3532
3533 // No autorelease counts? Nothing to be done.
3534 if (!ACnt)
Jordan Rose4ee1c552012-12-06 18:58:18 +00003535 return state;
Jordy Rose8d228632011-08-23 20:07:14 +00003536
Anna Zaks6a93bd52011-10-25 19:57:11 +00003537 assert(!Ctx.isObjCGCEnabled() && "Autorelease counts in GC mode?");
Jordy Rose8d228632011-08-23 20:07:14 +00003538 unsigned Cnt = V.getCount();
3539
3540 // FIXME: Handle sending 'autorelease' to already released object.
3541
3542 if (V.getKind() == RefVal::ReturnedOwned)
3543 ++Cnt;
3544
3545 if (ACnt <= Cnt) {
3546 if (ACnt == Cnt) {
3547 V.clearCounts();
3548 if (V.getKind() == RefVal::ReturnedOwned)
3549 V = V ^ RefVal::ReturnedNotOwned;
3550 else
3551 V = V ^ RefVal::NotOwned;
3552 } else {
Anna Zaks0217b1d2013-01-31 22:36:17 +00003553 V.setCount(V.getCount() - ACnt);
Jordy Rose8d228632011-08-23 20:07:14 +00003554 V.setAutoreleaseCount(0);
3555 }
Jordan Rose4ee1c552012-12-06 18:58:18 +00003556 return setRefBinding(state, Sym, V);
Jordy Rose8d228632011-08-23 20:07:14 +00003557 }
3558
3559 // Woah! More autorelease counts then retain counts left.
3560 // Emit hard error.
3561 V = V ^ RefVal::ErrorOverAutorelease;
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003562 state = setRefBinding(state, Sym, V);
Jordy Rose8d228632011-08-23 20:07:14 +00003563
Jordan Rosefa06f042012-08-20 18:43:42 +00003564 ExplodedNode *N = Ctx.generateSink(state, Pred, Tag);
Jordan Rose2bce86c2012-08-18 00:30:16 +00003565 if (N) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003566 SmallString<128> sbuf;
Jordy Rose8d228632011-08-23 20:07:14 +00003567 llvm::raw_svector_ostream os(sbuf);
Jordan Rose2545b1d2013-04-23 01:42:25 +00003568 os << "Object was autoreleased ";
Jordy Rose8d228632011-08-23 20:07:14 +00003569 if (V.getAutoreleaseCount() > 1)
Jordan Rose2545b1d2013-04-23 01:42:25 +00003570 os << V.getAutoreleaseCount() << " times but the object ";
3571 else
3572 os << "but ";
3573 os << "has a +" << V.getCount() << " retain count";
Jordy Rose8d228632011-08-23 20:07:14 +00003574
Jordy Rosed6334e12011-08-25 00:34:03 +00003575 if (!overAutorelease)
3576 overAutorelease.reset(new OverAutorelease());
3577
David Blaikie4e4d0842012-03-11 07:00:24 +00003578 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
Jordy Rose8d228632011-08-23 20:07:14 +00003579 CFRefReport *report =
Jordy Rosed6334e12011-08-25 00:34:03 +00003580 new CFRefReport(*overAutorelease, LOpts, /* GCEnabled = */ false,
3581 SummaryLog, N, Sym, os.str());
Jordan Rose785950e2012-11-02 01:53:40 +00003582 Ctx.emitReport(report);
Jordy Rose8d228632011-08-23 20:07:14 +00003583 }
3584
Jordan Rose4ee1c552012-12-06 18:58:18 +00003585 return 0;
Jordy Rose8d228632011-08-23 20:07:14 +00003586}
Jordy Rose38f17d62011-08-23 19:01:07 +00003587
Ted Kremenek8bef8232012-01-26 21:29:00 +00003588ProgramStateRef
3589RetainCountChecker::handleSymbolDeath(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003590 SymbolRef sid, RefVal V,
Jordy Rose38f17d62011-08-23 19:01:07 +00003591 SmallVectorImpl<SymbolRef> &Leaked) const {
Jordy Rose53376122011-08-24 04:48:19 +00003592 bool hasLeak = false;
Jordy Rose38f17d62011-08-23 19:01:07 +00003593 if (V.isOwned())
3594 hasLeak = true;
3595 else if (V.isNotOwned() || V.isReturnedOwned())
3596 hasLeak = (V.getCount() > 0);
3597
3598 if (!hasLeak)
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003599 return removeRefBinding(state, sid);
Jordy Rose38f17d62011-08-23 19:01:07 +00003600
3601 Leaked.push_back(sid);
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003602 return setRefBinding(state, sid, V ^ RefVal::ErrorLeak);
Jordy Rose38f17d62011-08-23 19:01:07 +00003603}
3604
3605ExplodedNode *
Ted Kremenek8bef8232012-01-26 21:29:00 +00003606RetainCountChecker::processLeaks(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003607 SmallVectorImpl<SymbolRef> &Leaked,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003608 CheckerContext &Ctx,
3609 ExplodedNode *Pred) const {
Jordy Rose38f17d62011-08-23 19:01:07 +00003610 // Generate an intermediate node representing the leak point.
Jordan Rose2bce86c2012-08-18 00:30:16 +00003611 ExplodedNode *N = Ctx.addTransition(state, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003612
3613 if (N) {
3614 for (SmallVectorImpl<SymbolRef>::iterator
3615 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3616
David Blaikie4e4d0842012-03-11 07:00:24 +00003617 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
Anna Zaks6a93bd52011-10-25 19:57:11 +00003618 bool GCEnabled = Ctx.isObjCGCEnabled();
Jordy Rose17a38e22011-09-02 05:55:19 +00003619 CFRefBug *BT = Pred ? getLeakWithinFunctionBug(LOpts, GCEnabled)
3620 : getLeakAtReturnBug(LOpts, GCEnabled);
Jordy Rose38f17d62011-08-23 19:01:07 +00003621 assert(BT && "BugType not initialized.");
Jordy Rose20589562011-08-24 22:39:09 +00003622
Jordy Rose17a38e22011-09-02 05:55:19 +00003623 CFRefLeakReport *report = new CFRefLeakReport(*BT, LOpts, GCEnabled,
Ted Kremenek08a838d2013-04-16 21:44:22 +00003624 SummaryLog, N, *I, Ctx,
3625 IncludeAllocationLine);
Jordan Rose785950e2012-11-02 01:53:40 +00003626 Ctx.emitReport(report);
Jordy Rose38f17d62011-08-23 19:01:07 +00003627 }
3628 }
3629
3630 return N;
3631}
3632
Anna Zaks344c77a2013-01-03 00:25:29 +00003633void RetainCountChecker::checkEndFunction(CheckerContext &Ctx) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +00003634 ProgramStateRef state = Ctx.getState();
Jordan Rose166d5022012-11-02 01:54:06 +00003635 RefBindingsTy B = state->get<RefBindings>();
Anna Zaksaf498a22011-10-25 19:56:48 +00003636 ExplodedNode *Pred = Ctx.getPredecessor();
Jordy Rose38f17d62011-08-23 19:01:07 +00003637
Jordan Rosed8188f82013-08-01 22:16:36 +00003638 // Don't process anything within synthesized bodies.
3639 const LocationContext *LCtx = Pred->getLocationContext();
3640 if (LCtx->getAnalysisDeclContext()->isBodyAutosynthesized()) {
3641 assert(LCtx->getParent());
3642 return;
3643 }
3644
Jordan Rose166d5022012-11-02 01:54:06 +00003645 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Jordan Rose4ee1c552012-12-06 18:58:18 +00003646 state = handleAutoreleaseCounts(state, Pred, /*Tag=*/0, Ctx,
3647 I->first, I->second);
Jordy Rose8d228632011-08-23 20:07:14 +00003648 if (!state)
Jordy Rose38f17d62011-08-23 19:01:07 +00003649 return;
3650 }
3651
Ted Kremenek0cf3d472012-02-07 00:24:33 +00003652 // If the current LocationContext has a parent, don't check for leaks.
3653 // We will do that later.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003654 // FIXME: we should instead check for imbalances of the retain/releases,
Ted Kremenek0cf3d472012-02-07 00:24:33 +00003655 // and suggest annotations.
Jordan Rosed8188f82013-08-01 22:16:36 +00003656 if (LCtx->getParent())
Ted Kremenek0cf3d472012-02-07 00:24:33 +00003657 return;
3658
Jordy Rose38f17d62011-08-23 19:01:07 +00003659 B = state->get<RefBindings>();
3660 SmallVector<SymbolRef, 10> Leaked;
3661
Jordan Rose166d5022012-11-02 01:54:06 +00003662 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I)
Jordy Rose8d228632011-08-23 20:07:14 +00003663 state = handleSymbolDeath(state, I->first, I->second, Leaked);
Jordy Rose38f17d62011-08-23 19:01:07 +00003664
Jordan Rose2bce86c2012-08-18 00:30:16 +00003665 processLeaks(state, Leaked, Ctx, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003666}
3667
3668const ProgramPointTag *
Jordy Rose910c4052011-09-02 06:44:22 +00003669RetainCountChecker::getDeadSymbolTag(SymbolRef sym) const {
Jordy Rose38f17d62011-08-23 19:01:07 +00003670 const SimpleProgramPointTag *&tag = DeadSymbolTags[sym];
3671 if (!tag) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003672 SmallString<64> buf;
Jordy Rose38f17d62011-08-23 19:01:07 +00003673 llvm::raw_svector_ostream out(buf);
Anna Zaksf62ceec2011-12-05 18:58:11 +00003674 out << "RetainCountChecker : Dead Symbol : ";
3675 sym->dumpToStream(out);
Jordy Rose38f17d62011-08-23 19:01:07 +00003676 tag = new SimpleProgramPointTag(out.str());
3677 }
3678 return tag;
3679}
3680
Jordy Rose910c4052011-09-02 06:44:22 +00003681void RetainCountChecker::checkDeadSymbols(SymbolReaper &SymReaper,
3682 CheckerContext &C) const {
Jordy Rose38f17d62011-08-23 19:01:07 +00003683 ExplodedNode *Pred = C.getPredecessor();
3684
Ted Kremenek8bef8232012-01-26 21:29:00 +00003685 ProgramStateRef state = C.getState();
Jordan Rose166d5022012-11-02 01:54:06 +00003686 RefBindingsTy B = state->get<RefBindings>();
Jordan Rose4ee1c552012-12-06 18:58:18 +00003687 SmallVector<SymbolRef, 10> Leaked;
Jordy Rose38f17d62011-08-23 19:01:07 +00003688
3689 // Update counts from autorelease pools
3690 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3691 E = SymReaper.dead_end(); I != E; ++I) {
3692 SymbolRef Sym = *I;
3693 if (const RefVal *T = B.lookup(Sym)){
3694 // Use the symbol as the tag.
3695 // FIXME: This might not be as unique as we would like.
Jordan Rose2bce86c2012-08-18 00:30:16 +00003696 const ProgramPointTag *Tag = getDeadSymbolTag(Sym);
Jordan Rose4ee1c552012-12-06 18:58:18 +00003697 state = handleAutoreleaseCounts(state, Pred, Tag, C, Sym, *T);
Jordy Rose8d228632011-08-23 20:07:14 +00003698 if (!state)
Jordy Rose38f17d62011-08-23 19:01:07 +00003699 return;
Jordan Rose4ee1c552012-12-06 18:58:18 +00003700
3701 // Fetch the new reference count from the state, and use it to handle
3702 // this symbol.
3703 state = handleSymbolDeath(state, *I, *getRefBinding(state, Sym), Leaked);
Jordy Rose38f17d62011-08-23 19:01:07 +00003704 }
3705 }
3706
Jordan Rose4ee1c552012-12-06 18:58:18 +00003707 if (Leaked.empty()) {
3708 C.addTransition(state);
3709 return;
Jordy Rose38f17d62011-08-23 19:01:07 +00003710 }
3711
Jordan Rose2bce86c2012-08-18 00:30:16 +00003712 Pred = processLeaks(state, Leaked, C, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003713
3714 // Did we cache out?
3715 if (!Pred)
3716 return;
3717
3718 // Now generate a new node that nukes the old bindings.
Jordan Rose4ee1c552012-12-06 18:58:18 +00003719 // The only bindings left at this point are the leaked symbols.
Jordan Rose166d5022012-11-02 01:54:06 +00003720 RefBindingsTy::Factory &F = state->get_context<RefBindings>();
Jordan Rose4ee1c552012-12-06 18:58:18 +00003721 B = state->get<RefBindings>();
Jordy Rose38f17d62011-08-23 19:01:07 +00003722
Jordan Rose4ee1c552012-12-06 18:58:18 +00003723 for (SmallVectorImpl<SymbolRef>::iterator I = Leaked.begin(),
3724 E = Leaked.end();
3725 I != E; ++I)
Jordy Rose38f17d62011-08-23 19:01:07 +00003726 B = F.remove(B, *I);
3727
3728 state = state->set<RefBindings>(B);
Anna Zaks0bd6b112011-10-26 21:06:34 +00003729 C.addTransition(state, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003730}
3731
Ted Kremenek8bef8232012-01-26 21:29:00 +00003732void RetainCountChecker::printState(raw_ostream &Out, ProgramStateRef State,
Jordy Rose910c4052011-09-02 06:44:22 +00003733 const char *NL, const char *Sep) const {
Jordy Rosedbd658e2011-08-28 19:11:56 +00003734
Jordan Rose166d5022012-11-02 01:54:06 +00003735 RefBindingsTy B = State->get<RefBindings>();
Jordy Rosedbd658e2011-08-28 19:11:56 +00003736
Ted Kremenek65a08922013-03-28 18:43:18 +00003737 if (B.isEmpty())
3738 return;
3739
3740 Out << Sep << NL;
Jordy Rosedbd658e2011-08-28 19:11:56 +00003741
Jordan Rose166d5022012-11-02 01:54:06 +00003742 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Jordy Rosedbd658e2011-08-28 19:11:56 +00003743 Out << I->first << " : ";
3744 I->second.print(Out);
3745 Out << NL;
3746 }
Jordy Rosedbd658e2011-08-28 19:11:56 +00003747}
3748
3749//===----------------------------------------------------------------------===//
Jordy Rose910c4052011-09-02 06:44:22 +00003750// Checker registration.
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00003751//===----------------------------------------------------------------------===//
3752
Jordy Rose17a38e22011-09-02 05:55:19 +00003753void ento::registerRetainCountChecker(CheckerManager &Mgr) {
Ted Kremenek08a838d2013-04-16 21:44:22 +00003754 Mgr.registerChecker<RetainCountChecker>(Mgr.getAnalyzerOptions());
Jordy Rose17a38e22011-09-02 05:55:19 +00003755}
3756