blob: b57c6e2b4fbcc01aa15b63db2473000bb3c0bf32 [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
40using namespace clang;
Ted Kremenek9ef65372010-12-23 07:20:52 +000041using namespace ento;
Ted Kremeneka64e89b2010-01-27 06:13:48 +000042using llvm::StrInStrNoCase;
Ted Kremenek4c79e552008-11-05 16:54:44 +000043
Ted Kremenek05cbe1a2008-04-09 23:49:11 +000044//===----------------------------------------------------------------------===//
Ted Kremenek553cf182008-06-25 21:21:56 +000045// Primitives used for constructing summaries for function/method calls.
Ted Kremenek05cbe1a2008-04-09 23:49:11 +000046//===----------------------------------------------------------------------===//
47
Ted Kremenek553cf182008-06-25 21:21:56 +000048/// ArgEffect is used to summarize a function/method call's effect on a
49/// particular argument.
Jordy Rosebd85b132011-08-24 19:10:50 +000050enum ArgEffect { DoNothing, Autorelease, Dealloc, DecRef, DecRefMsg,
John McCallf85e1932011-06-15 23:02:42 +000051 DecRefBridgedTransfered,
Jordy Rosebd85b132011-08-24 19:10:50 +000052 IncRefMsg, IncRef, MakeCollectable, MayEscape,
Anna Zaks554067f2012-08-29 23:23:43 +000053 NewAutoreleasePool,
54
55 // Stop tracking the argument - the effect of the call is
56 // unknown.
57 StopTracking,
58
59 // In some cases, we obtain a better summary for this checker
60 // by looking at the call site than by inlining the function.
61 // Signifies that we should stop tracking the symbol even if
62 // the function is inlined.
63 StopTrackingHard,
64
65 // The function decrements the reference count and the checker
66 // should stop tracking the argument.
67 DecRefAndStopTrackingHard, DecRefMsgAndStopTrackingHard
68 };
Ted Kremenek553cf182008-06-25 21:21:56 +000069
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000070namespace llvm {
Ted Kremenekb77449c2009-05-03 05:20:50 +000071template <> struct FoldingSetTrait<ArgEffect> {
72static inline void Profile(const ArgEffect X, FoldingSetNodeID& ID) {
73 ID.AddInteger((unsigned) X);
74}
Ted Kremenek553cf182008-06-25 21:21:56 +000075};
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000076} // end llvm namespace
77
Ted Kremenekb77449c2009-05-03 05:20:50 +000078/// ArgEffects summarizes the effects of a function/method call on all of
79/// its arguments.
80typedef llvm::ImmutableMap<unsigned,ArgEffect> ArgEffects;
81
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000082namespace {
Ted Kremenek553cf182008-06-25 21:21:56 +000083
84/// RetEffect is used to summarize a function/method call's behavior with
Mike Stump1eb44332009-09-09 15:08:12 +000085/// respect to its return value.
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +000086class RetEffect {
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000087public:
Jordy Rose76c506f2011-08-21 21:58:18 +000088 enum Kind { NoRet, OwnedSymbol, OwnedAllocatedSymbol,
John McCallf85e1932011-06-15 23:02:42 +000089 NotOwnedSymbol, GCNotOwnedSymbol, ARCNotOwnedSymbol,
Anna Zaks554067f2012-08-29 23:23:43 +000090 OwnedWhenTrackedReceiver,
91 // Treat this function as returning a non-tracked symbol even if
92 // the function has been inlined. This is used where the call
93 // site summary is more presise than the summary indirectly produced
94 // by inlining the function
95 NoRetHard
96 };
Mike Stump1eb44332009-09-09 15:08:12 +000097
98 enum ObjKind { CF, ObjC, AnyObj };
Ted Kremenek2d1652e2009-01-28 05:56:51 +000099
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000100private:
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000101 Kind K;
102 ObjKind O;
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000103
Jordy Rose76c506f2011-08-21 21:58:18 +0000104 RetEffect(Kind k, ObjKind o = AnyObj) : K(k), O(o) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000105
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000106public:
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000107 Kind getKind() const { return K; }
108
109 ObjKind getObjKind() const { return O; }
Mike Stump1eb44332009-09-09 15:08:12 +0000110
Ted Kremeneka8833552009-04-29 23:03:22 +0000111 bool isOwned() const {
Ted Kremenek78a35a32009-05-12 20:06:54 +0000112 return K == OwnedSymbol || K == OwnedAllocatedSymbol ||
113 K == OwnedWhenTrackedReceiver;
Ted Kremeneka8833552009-04-29 23:03:22 +0000114 }
Mike Stump1eb44332009-09-09 15:08:12 +0000115
Jordy Rose4df54fe2011-08-23 04:27:15 +0000116 bool operator==(const RetEffect &Other) const {
117 return K == Other.K && O == Other.O;
118 }
119
Ted Kremenek78a35a32009-05-12 20:06:54 +0000120 static RetEffect MakeOwnedWhenTrackedReceiver() {
121 return RetEffect(OwnedWhenTrackedReceiver, ObjC);
122 }
Mike Stump1eb44332009-09-09 15:08:12 +0000123
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000124 static RetEffect MakeOwned(ObjKind o, bool isAllocated = false) {
125 return RetEffect(isAllocated ? OwnedAllocatedSymbol : OwnedSymbol, o);
Mike Stump1eb44332009-09-09 15:08:12 +0000126 }
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000127 static RetEffect MakeNotOwned(ObjKind o) {
128 return RetEffect(NotOwnedSymbol, o);
Ted Kremeneke798e7c2009-04-27 19:14:45 +0000129 }
130 static RetEffect MakeGCNotOwned() {
131 return RetEffect(GCNotOwnedSymbol, ObjC);
132 }
John McCallf85e1932011-06-15 23:02:42 +0000133 static RetEffect MakeARCNotOwned() {
134 return RetEffect(ARCNotOwnedSymbol, ObjC);
135 }
Ted Kremenek553cf182008-06-25 21:21:56 +0000136 static RetEffect MakeNoRet() {
137 return RetEffect(NoRet);
Ted Kremeneka7344702008-06-23 18:02:52 +0000138 }
Anna Zaks554067f2012-08-29 23:23:43 +0000139 static RetEffect MakeNoRetHard() {
140 return RetEffect(NoRetHard);
141 }
Jordy Roseef945882012-03-18 01:26:10 +0000142
143 void Profile(llvm::FoldingSetNodeID& ID) const {
144 ID.AddInteger((unsigned) K);
145 ID.AddInteger((unsigned) O);
146 }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000147};
Mike Stump1eb44332009-09-09 15:08:12 +0000148
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000149//===----------------------------------------------------------------------===//
150// Reference-counting logic (typestate + counts).
151//===----------------------------------------------------------------------===//
Mike Stump1eb44332009-09-09 15:08:12 +0000152
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000153class RefVal {
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000154public:
155 enum Kind {
156 Owned = 0, // Owning reference.
157 NotOwned, // Reference is not owned by still valid (not freed).
158 Released, // Object has been released.
159 ReturnedOwned, // Returned object passes ownership to caller.
160 ReturnedNotOwned, // Return object does not pass ownership to caller.
161 ERROR_START,
162 ErrorDeallocNotOwned, // -dealloc called on non-owned object.
163 ErrorDeallocGC, // Calling -dealloc with GC enabled.
164 ErrorUseAfterRelease, // Object used after released.
165 ErrorReleaseNotOwned, // Release of an object that was not owned.
166 ERROR_LEAK_START,
167 ErrorLeak, // A memory leak due to excessive reference counts.
168 ErrorLeakReturned, // A memory leak due to the returning method not having
169 // the correct naming conventions.
170 ErrorGCLeakReturned,
171 ErrorOverAutorelease,
172 ErrorReturnedNotOwned
173 };
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000174
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000175private:
176 Kind kind;
177 RetEffect::ObjKind okind;
178 unsigned Cnt;
179 unsigned ACnt;
180 QualType T;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000181
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000182 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, unsigned acnt, QualType t)
183 : kind(k), okind(o), Cnt(cnt), ACnt(acnt), T(t) {}
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000184
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000185public:
186 Kind getKind() const { return kind; }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000187
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000188 RetEffect::ObjKind getObjKind() const { return okind; }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000189
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000190 unsigned getCount() const { return Cnt; }
191 unsigned getAutoreleaseCount() const { return ACnt; }
192 unsigned getCombinedCounts() const { return Cnt + ACnt; }
193 void clearCounts() { Cnt = 0; ACnt = 0; }
194 void setCount(unsigned i) { Cnt = i; }
195 void setAutoreleaseCount(unsigned i) { ACnt = i; }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000196
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000197 QualType getType() const { return T; }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000198
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000199 bool isOwned() const {
200 return getKind() == Owned;
201 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000202
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000203 bool isNotOwned() const {
204 return getKind() == NotOwned;
205 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000206
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000207 bool isReturnedOwned() const {
208 return getKind() == ReturnedOwned;
209 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000210
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000211 bool isReturnedNotOwned() const {
212 return getKind() == ReturnedNotOwned;
213 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000214
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000215 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
216 unsigned Count = 1) {
217 return RefVal(Owned, o, Count, 0, t);
218 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000219
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000220 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
221 unsigned Count = 0) {
222 return RefVal(NotOwned, o, Count, 0, t);
223 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000224
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000225 // Comparison, profiling, and pretty-printing.
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000226
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000227 bool operator==(const RefVal& X) const {
228 return kind == X.kind && Cnt == X.Cnt && T == X.T && ACnt == X.ACnt;
229 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000230
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000231 RefVal operator-(size_t i) const {
232 return RefVal(getKind(), getObjKind(), getCount() - i,
233 getAutoreleaseCount(), getType());
234 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000235
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000236 RefVal operator+(size_t i) const {
237 return RefVal(getKind(), getObjKind(), getCount() + i,
238 getAutoreleaseCount(), getType());
239 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000240
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000241 RefVal operator^(Kind k) const {
242 return RefVal(k, getObjKind(), getCount(), getAutoreleaseCount(),
243 getType());
244 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000245
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000246 RefVal autorelease() const {
247 return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount()+1,
248 getType());
249 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000250
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000251 void Profile(llvm::FoldingSetNodeID& ID) const {
252 ID.AddInteger((unsigned) kind);
253 ID.AddInteger(Cnt);
254 ID.AddInteger(ACnt);
255 ID.Add(T);
256 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000257
Ted Kremenek9c378f72011-08-12 23:37:29 +0000258 void print(raw_ostream &Out) const;
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000259};
260
Ted Kremenek9c378f72011-08-12 23:37:29 +0000261void RefVal::print(raw_ostream &Out) const {
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000262 if (!T.isNull())
Jordy Rosedbd658e2011-08-28 19:11:56 +0000263 Out << "Tracked " << T.getAsString() << '/';
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000264
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000265 switch (getKind()) {
Jordy Rose910c4052011-09-02 06:44:22 +0000266 default: llvm_unreachable("Invalid RefVal kind");
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000267 case Owned: {
268 Out << "Owned";
269 unsigned cnt = getCount();
270 if (cnt) Out << " (+ " << cnt << ")";
271 break;
272 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000273
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000274 case NotOwned: {
275 Out << "NotOwned";
276 unsigned cnt = getCount();
277 if (cnt) Out << " (+ " << cnt << ")";
278 break;
279 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000280
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000281 case ReturnedOwned: {
282 Out << "ReturnedOwned";
283 unsigned cnt = getCount();
284 if (cnt) Out << " (+ " << cnt << ")";
285 break;
286 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000287
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000288 case ReturnedNotOwned: {
289 Out << "ReturnedNotOwned";
290 unsigned cnt = getCount();
291 if (cnt) Out << " (+ " << cnt << ")";
292 break;
293 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000294
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000295 case Released:
296 Out << "Released";
297 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000298
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000299 case ErrorDeallocGC:
300 Out << "-dealloc (GC)";
301 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000302
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000303 case ErrorDeallocNotOwned:
304 Out << "-dealloc (not-owned)";
305 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000306
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000307 case ErrorLeak:
308 Out << "Leaked";
309 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000310
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000311 case ErrorLeakReturned:
312 Out << "Leaked (Bad naming)";
313 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000314
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000315 case ErrorGCLeakReturned:
316 Out << "Leaked (GC-ed at return)";
317 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000318
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000319 case ErrorUseAfterRelease:
320 Out << "Use-After-Release [ERROR]";
321 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000322
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000323 case ErrorReleaseNotOwned:
324 Out << "Release of Not-Owned [ERROR]";
325 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000326
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000327 case RefVal::ErrorOverAutorelease:
328 Out << "Over autoreleased";
329 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000330
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000331 case RefVal::ErrorReturnedNotOwned:
332 Out << "Non-owned object returned instead of owned";
333 break;
334 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000335
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000336 if (ACnt) {
337 Out << " [ARC +" << ACnt << ']';
338 }
339}
340} //end anonymous namespace
341
342//===----------------------------------------------------------------------===//
343// RefBindings - State used to track object reference counts.
344//===----------------------------------------------------------------------===//
345
Jordan Rose166d5022012-11-02 01:54:06 +0000346REGISTER_MAP_WITH_PROGRAMSTATE(RefBindings, SymbolRef, RefVal)
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000347
Anna Zaks8d6b43c2012-08-14 00:36:15 +0000348static inline const RefVal *getRefBinding(ProgramStateRef State,
349 SymbolRef Sym) {
350 return State->get<RefBindings>(Sym);
351}
352
353static inline ProgramStateRef setRefBinding(ProgramStateRef State,
354 SymbolRef Sym, RefVal Val) {
355 return State->set<RefBindings>(Sym, Val);
356}
357
358static ProgramStateRef removeRefBinding(ProgramStateRef State, SymbolRef Sym) {
359 return State->remove<RefBindings>(Sym);
360}
361
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000362//===----------------------------------------------------------------------===//
Jordy Rose910c4052011-09-02 06:44:22 +0000363// Function/Method behavior summaries.
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000364//===----------------------------------------------------------------------===//
365
366namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000367class RetainSummary {
Jordy Roseef945882012-03-18 01:26:10 +0000368 /// Args - a map of (index, ArgEffect) pairs, where index
Ted Kremenek1bffd742008-05-06 15:44:25 +0000369 /// specifies the argument (starting from 0). This can be sparsely
370 /// populated; arguments with no entry in Args use 'DefaultArgEffect'.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000371 ArgEffects Args;
Mike Stump1eb44332009-09-09 15:08:12 +0000372
Ted Kremenek1bffd742008-05-06 15:44:25 +0000373 /// DefaultArgEffect - The default ArgEffect to apply to arguments that
374 /// do not have an entry in Args.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000375 ArgEffect DefaultArgEffect;
Mike Stump1eb44332009-09-09 15:08:12 +0000376
Ted Kremenek553cf182008-06-25 21:21:56 +0000377 /// Receiver - If this summary applies to an Objective-C message expression,
378 /// this is the effect applied to the state of the receiver.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000379 ArgEffect Receiver;
Mike Stump1eb44332009-09-09 15:08:12 +0000380
Ted Kremenek553cf182008-06-25 21:21:56 +0000381 /// Ret - The effect on the return value. Used to indicate if the
Jordy Rose76c506f2011-08-21 21:58:18 +0000382 /// function/method call returns a new tracked symbol.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000383 RetEffect Ret;
Mike Stump1eb44332009-09-09 15:08:12 +0000384
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000385public:
Ted Kremenekb77449c2009-05-03 05:20:50 +0000386 RetainSummary(ArgEffects A, RetEffect R, ArgEffect defaultEff,
Jordy Rosee62e87b2011-08-20 20:55:40 +0000387 ArgEffect ReceiverEff)
388 : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000389
Ted Kremenek553cf182008-06-25 21:21:56 +0000390 /// getArg - Return the argument effect on the argument specified by
391 /// idx (starting from 0).
Ted Kremenek1ac08d62008-03-11 17:48:22 +0000392 ArgEffect getArg(unsigned idx) const {
Ted Kremenekb77449c2009-05-03 05:20:50 +0000393 if (const ArgEffect *AE = Args.lookup(idx))
394 return *AE;
Mike Stump1eb44332009-09-09 15:08:12 +0000395
Ted Kremenek1bffd742008-05-06 15:44:25 +0000396 return DefaultArgEffect;
Ted Kremenek1ac08d62008-03-11 17:48:22 +0000397 }
Ted Kremenek11fe1752011-01-27 18:43:03 +0000398
399 void addArg(ArgEffects::Factory &af, unsigned idx, ArgEffect e) {
400 Args = af.add(Args, idx, e);
401 }
Mike Stump1eb44332009-09-09 15:08:12 +0000402
Ted Kremenek885c27b2009-05-04 05:31:22 +0000403 /// setDefaultArgEffect - Set the default argument effect.
404 void setDefaultArgEffect(ArgEffect E) {
405 DefaultArgEffect = E;
406 }
Mike Stump1eb44332009-09-09 15:08:12 +0000407
Ted Kremenek553cf182008-06-25 21:21:56 +0000408 /// getRetEffect - Returns the effect on the return value of the call.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000409 RetEffect getRetEffect() const { return Ret; }
Mike Stump1eb44332009-09-09 15:08:12 +0000410
Ted Kremenek885c27b2009-05-04 05:31:22 +0000411 /// setRetEffect - Set the effect of the return value of the call.
412 void setRetEffect(RetEffect E) { Ret = E; }
Mike Stump1eb44332009-09-09 15:08:12 +0000413
Ted Kremenek12b94342011-01-27 06:54:14 +0000414
415 /// Sets the effect on the receiver of the message.
416 void setReceiverEffect(ArgEffect e) { Receiver = e; }
417
Ted Kremenek553cf182008-06-25 21:21:56 +0000418 /// getReceiverEffect - Returns the effect on the receiver of the call.
419 /// This is only meaningful if the summary applies to an ObjCMessageExpr*.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000420 ArgEffect getReceiverEffect() const { return Receiver; }
Jordy Rose4df54fe2011-08-23 04:27:15 +0000421
422 /// Test if two retain summaries are identical. Note that merely equivalent
423 /// summaries are not necessarily identical (for example, if an explicit
424 /// argument effect matches the default effect).
425 bool operator==(const RetainSummary &Other) const {
426 return Args == Other.Args && DefaultArgEffect == Other.DefaultArgEffect &&
427 Receiver == Other.Receiver && Ret == Other.Ret;
428 }
Jordy Roseef945882012-03-18 01:26:10 +0000429
430 /// Profile this summary for inclusion in a FoldingSet.
431 void Profile(llvm::FoldingSetNodeID& ID) const {
432 ID.Add(Args);
433 ID.Add(DefaultArgEffect);
434 ID.Add(Receiver);
435 ID.Add(Ret);
436 }
437
438 /// A retain summary is simple if it has no ArgEffects other than the default.
439 bool isSimple() const {
440 return Args.isEmpty();
441 }
Jordan Rose4531b7d2012-07-02 19:27:43 +0000442
443private:
444 ArgEffects getArgEffects() const { return Args; }
445 ArgEffect getDefaultArgEffect() const { return DefaultArgEffect; }
446
447 friend class RetainSummaryManager;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000448};
Ted Kremenek4f22a782008-06-23 23:30:29 +0000449} // end anonymous namespace
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000450
Ted Kremenek553cf182008-06-25 21:21:56 +0000451//===----------------------------------------------------------------------===//
452// Data structures for constructing summaries.
453//===----------------------------------------------------------------------===//
Ted Kremenek53301ba2008-06-24 03:49:48 +0000454
Ted Kremenek553cf182008-06-25 21:21:56 +0000455namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000456class ObjCSummaryKey {
Ted Kremenek553cf182008-06-25 21:21:56 +0000457 IdentifierInfo* II;
458 Selector S;
Mike Stump1eb44332009-09-09 15:08:12 +0000459public:
Ted Kremenek553cf182008-06-25 21:21:56 +0000460 ObjCSummaryKey(IdentifierInfo* ii, Selector s)
461 : II(ii), S(s) {}
462
Ted Kremenek9c378f72011-08-12 23:37:29 +0000463 ObjCSummaryKey(const ObjCInterfaceDecl *d, Selector s)
Ted Kremenek553cf182008-06-25 21:21:56 +0000464 : II(d ? d->getIdentifier() : 0), S(s) {}
Ted Kremenek70b6a832009-05-13 18:16:01 +0000465
Ted Kremenek553cf182008-06-25 21:21:56 +0000466 ObjCSummaryKey(Selector s)
467 : II(0), S(s) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000468
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000469 IdentifierInfo *getIdentifier() const { return II; }
Ted Kremenek553cf182008-06-25 21:21:56 +0000470 Selector getSelector() const { return S; }
471};
Ted Kremenek4f22a782008-06-23 23:30:29 +0000472}
473
474namespace llvm {
Ted Kremenek553cf182008-06-25 21:21:56 +0000475template <> struct DenseMapInfo<ObjCSummaryKey> {
476 static inline ObjCSummaryKey getEmptyKey() {
477 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
478 DenseMapInfo<Selector>::getEmptyKey());
479 }
Mike Stump1eb44332009-09-09 15:08:12 +0000480
Ted Kremenek553cf182008-06-25 21:21:56 +0000481 static inline ObjCSummaryKey getTombstoneKey() {
482 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
Mike Stump1eb44332009-09-09 15:08:12 +0000483 DenseMapInfo<Selector>::getTombstoneKey());
Ted Kremenek553cf182008-06-25 21:21:56 +0000484 }
Mike Stump1eb44332009-09-09 15:08:12 +0000485
Ted Kremenek553cf182008-06-25 21:21:56 +0000486 static unsigned getHashValue(const ObjCSummaryKey &V) {
Benjamin Kramer28b23072012-05-27 13:28:44 +0000487 typedef std::pair<IdentifierInfo*, Selector> PairTy;
488 return DenseMapInfo<PairTy>::getHashValue(PairTy(V.getIdentifier(),
489 V.getSelector()));
Ted Kremenek553cf182008-06-25 21:21:56 +0000490 }
Mike Stump1eb44332009-09-09 15:08:12 +0000491
Ted Kremenek553cf182008-06-25 21:21:56 +0000492 static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
Benjamin Kramer28b23072012-05-27 13:28:44 +0000493 return LHS.getIdentifier() == RHS.getIdentifier() &&
494 LHS.getSelector() == RHS.getSelector();
Ted Kremenek553cf182008-06-25 21:21:56 +0000495 }
Mike Stump1eb44332009-09-09 15:08:12 +0000496
Ted Kremenek553cf182008-06-25 21:21:56 +0000497};
Chris Lattner06159e82009-12-15 07:26:51 +0000498template <>
499struct isPodLike<ObjCSummaryKey> { static const bool value = true; };
Ted Kremenek4f22a782008-06-23 23:30:29 +0000500} // end llvm namespace
Mike Stump1eb44332009-09-09 15:08:12 +0000501
Ted Kremenek4f22a782008-06-23 23:30:29 +0000502namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000503class ObjCSummaryCache {
Ted Kremenek93edbc52011-10-05 23:54:29 +0000504 typedef llvm::DenseMap<ObjCSummaryKey, const RetainSummary *> MapTy;
Ted Kremenek553cf182008-06-25 21:21:56 +0000505 MapTy M;
506public:
507 ObjCSummaryCache() {}
Mike Stump1eb44332009-09-09 15:08:12 +0000508
Ted Kremenek93edbc52011-10-05 23:54:29 +0000509 const RetainSummary * find(const ObjCInterfaceDecl *D, Selector S) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000510 // Do a lookup with the (D,S) pair. If we find a match return
511 // the iterator.
512 ObjCSummaryKey K(D, S);
513 MapTy::iterator I = M.find(K);
Mike Stump1eb44332009-09-09 15:08:12 +0000514
Jordan Rose4531b7d2012-07-02 19:27:43 +0000515 if (I != M.end())
Ted Kremenek614cc542009-07-21 23:27:57 +0000516 return I->second;
Jordan Rose4531b7d2012-07-02 19:27:43 +0000517 if (!D)
518 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +0000519
Ted Kremenek553cf182008-06-25 21:21:56 +0000520 // Walk the super chain. If we find a hit with a parent, we'll end
521 // up returning that summary. We actually allow that key (null,S), as
522 // we cache summaries for the null ObjCInterfaceDecl* to allow us to
523 // generate initial summaries without having to worry about NSObject
524 // being declared.
525 // FIXME: We may change this at some point.
Ted Kremenek9c378f72011-08-12 23:37:29 +0000526 for (ObjCInterfaceDecl *C=D->getSuperClass() ;; C=C->getSuperClass()) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000527 if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
528 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000529
Ted Kremenek553cf182008-06-25 21:21:56 +0000530 if (!C)
Ted Kremenek614cc542009-07-21 23:27:57 +0000531 return NULL;
Ted Kremenek553cf182008-06-25 21:21:56 +0000532 }
Mike Stump1eb44332009-09-09 15:08:12 +0000533
534 // Cache the summary with original key to make the next lookup faster
Ted Kremenek553cf182008-06-25 21:21:56 +0000535 // and return the iterator.
Ted Kremenek93edbc52011-10-05 23:54:29 +0000536 const RetainSummary *Summ = I->second;
Ted Kremenek614cc542009-07-21 23:27:57 +0000537 M[K] = Summ;
538 return Summ;
Ted Kremenek553cf182008-06-25 21:21:56 +0000539 }
Mike Stump1eb44332009-09-09 15:08:12 +0000540
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000541 const RetainSummary *find(IdentifierInfo* II, Selector S) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000542 // FIXME: Class method lookup. Right now we dont' have a good way
543 // of going between IdentifierInfo* and the class hierarchy.
Ted Kremenek614cc542009-07-21 23:27:57 +0000544 MapTy::iterator I = M.find(ObjCSummaryKey(II, S));
Mike Stump1eb44332009-09-09 15:08:12 +0000545
Ted Kremenek614cc542009-07-21 23:27:57 +0000546 if (I == M.end())
547 I = M.find(ObjCSummaryKey(S));
Mike Stump1eb44332009-09-09 15:08:12 +0000548
Ted Kremenek614cc542009-07-21 23:27:57 +0000549 return I == M.end() ? NULL : I->second;
Ted Kremenek553cf182008-06-25 21:21:56 +0000550 }
Mike Stump1eb44332009-09-09 15:08:12 +0000551
Ted Kremenek93edbc52011-10-05 23:54:29 +0000552 const RetainSummary *& operator[](ObjCSummaryKey K) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000553 return M[K];
554 }
Mike Stump1eb44332009-09-09 15:08:12 +0000555
Ted Kremenek93edbc52011-10-05 23:54:29 +0000556 const RetainSummary *& operator[](Selector S) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000557 return M[ ObjCSummaryKey(S) ];
558 }
Mike Stump1eb44332009-09-09 15:08:12 +0000559};
Ted Kremenek553cf182008-06-25 21:21:56 +0000560} // end anonymous namespace
561
562//===----------------------------------------------------------------------===//
563// Data structures for managing collections of summaries.
564//===----------------------------------------------------------------------===//
565
566namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000567class RetainSummaryManager {
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000568
569 //==-----------------------------------------------------------------==//
570 // Typedefs.
571 //==-----------------------------------------------------------------==//
Mike Stump1eb44332009-09-09 15:08:12 +0000572
Ted Kremenek93edbc52011-10-05 23:54:29 +0000573 typedef llvm::DenseMap<const FunctionDecl*, const RetainSummary *>
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000574 FuncSummariesTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000575
Ted Kremenek4f22a782008-06-23 23:30:29 +0000576 typedef ObjCSummaryCache ObjCMethodSummariesTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000577
Jordy Roseef945882012-03-18 01:26:10 +0000578 typedef llvm::FoldingSetNodeWrapper<RetainSummary> CachedSummaryNode;
579
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000580 //==-----------------------------------------------------------------==//
581 // Data.
582 //==-----------------------------------------------------------------==//
Mike Stump1eb44332009-09-09 15:08:12 +0000583
Ted Kremenek553cf182008-06-25 21:21:56 +0000584 /// Ctx - The ASTContext object for the analyzed ASTs.
Ted Kremenek9c378f72011-08-12 23:37:29 +0000585 ASTContext &Ctx;
Ted Kremenek179064e2008-07-01 17:21:27 +0000586
Ted Kremenek553cf182008-06-25 21:21:56 +0000587 /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
Ted Kremenek377e2302008-04-29 05:33:51 +0000588 const bool GCEnabled;
Mike Stump1eb44332009-09-09 15:08:12 +0000589
John McCallf85e1932011-06-15 23:02:42 +0000590 /// Records whether or not the analyzed code runs in ARC mode.
591 const bool ARCEnabled;
592
Ted Kremenek553cf182008-06-25 21:21:56 +0000593 /// FuncSummaries - A map from FunctionDecls to summaries.
Mike Stump1eb44332009-09-09 15:08:12 +0000594 FuncSummariesTy FuncSummaries;
595
Ted Kremenek553cf182008-06-25 21:21:56 +0000596 /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
597 /// to summaries.
Ted Kremenek1f180c32008-06-23 22:21:20 +0000598 ObjCMethodSummariesTy ObjCClassMethodSummaries;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000599
Ted Kremenek553cf182008-06-25 21:21:56 +0000600 /// ObjCMethodSummaries - A map from selectors to summaries.
Ted Kremenek1f180c32008-06-23 22:21:20 +0000601 ObjCMethodSummariesTy ObjCMethodSummaries;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000602
Ted Kremenek553cf182008-06-25 21:21:56 +0000603 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
604 /// and all other data used by the checker.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000605 llvm::BumpPtrAllocator BPAlloc;
Mike Stump1eb44332009-09-09 15:08:12 +0000606
Ted Kremenekb77449c2009-05-03 05:20:50 +0000607 /// AF - A factory for ArgEffects objects.
Mike Stump1eb44332009-09-09 15:08:12 +0000608 ArgEffects::Factory AF;
609
Ted Kremenek553cf182008-06-25 21:21:56 +0000610 /// ScratchArgs - A holding buffer for construct ArgEffects.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000611 ArgEffects ScratchArgs;
Mike Stump1eb44332009-09-09 15:08:12 +0000612
Ted Kremenekec315332009-05-07 23:40:42 +0000613 /// ObjCAllocRetE - Default return effect for methods returning Objective-C
614 /// objects.
615 RetEffect ObjCAllocRetE;
Ted Kremenek547d4952009-06-05 23:18:01 +0000616
Mike Stump1eb44332009-09-09 15:08:12 +0000617 /// ObjCInitRetE - Default return effect for init methods returning
Ted Kremenekac02f202009-08-20 05:13:36 +0000618 /// Objective-C objects.
Ted Kremenek547d4952009-06-05 23:18:01 +0000619 RetEffect ObjCInitRetE;
Mike Stump1eb44332009-09-09 15:08:12 +0000620
Jordy Roseef945882012-03-18 01:26:10 +0000621 /// SimpleSummaries - Used for uniquing summaries that don't have special
622 /// effects.
623 llvm::FoldingSet<CachedSummaryNode> SimpleSummaries;
Mike Stump1eb44332009-09-09 15:08:12 +0000624
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000625 //==-----------------------------------------------------------------==//
626 // Methods.
627 //==-----------------------------------------------------------------==//
Mike Stump1eb44332009-09-09 15:08:12 +0000628
Ted Kremenek553cf182008-06-25 21:21:56 +0000629 /// getArgEffects - Returns a persistent ArgEffects object based on the
630 /// data in ScratchArgs.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000631 ArgEffects getArgEffects();
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000632
Mike Stump1eb44332009-09-09 15:08:12 +0000633 enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
Ted Kremenek93edbc52011-10-05 23:54:29 +0000634
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000635 const RetainSummary *getUnarySummary(const FunctionType* FT,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000636 UnaryFuncKind func);
Mike Stump1eb44332009-09-09 15:08:12 +0000637
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000638 const RetainSummary *getCFSummaryCreateRule(const FunctionDecl *FD);
639 const RetainSummary *getCFSummaryGetRule(const FunctionDecl *FD);
640 const RetainSummary *getCFCreateGetRuleSummary(const FunctionDecl *FD);
Mike Stump1eb44332009-09-09 15:08:12 +0000641
Jordy Roseef945882012-03-18 01:26:10 +0000642 const RetainSummary *getPersistentSummary(const RetainSummary &OldSumm);
Ted Kremenek706522f2008-10-29 04:07:07 +0000643
Jordy Roseef945882012-03-18 01:26:10 +0000644 const RetainSummary *getPersistentSummary(RetEffect RetEff,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000645 ArgEffect ReceiverEff = DoNothing,
646 ArgEffect DefaultEff = MayEscape) {
Jordy Roseef945882012-03-18 01:26:10 +0000647 RetainSummary Summ(getArgEffects(), RetEff, DefaultEff, ReceiverEff);
648 return getPersistentSummary(Summ);
649 }
650
Ted Kremenekc91fdf62012-05-08 00:12:09 +0000651 const RetainSummary *getDoNothingSummary() {
652 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
653 }
654
Jordy Roseef945882012-03-18 01:26:10 +0000655 const RetainSummary *getDefaultSummary() {
656 return getPersistentSummary(RetEffect::MakeNoRet(),
657 DoNothing, MayEscape);
Ted Kremenek9c32d082008-05-06 00:30:21 +0000658 }
Mike Stump1eb44332009-09-09 15:08:12 +0000659
Ted Kremenek93edbc52011-10-05 23:54:29 +0000660 const RetainSummary *getPersistentStopSummary() {
Jordy Roseef945882012-03-18 01:26:10 +0000661 return getPersistentSummary(RetEffect::MakeNoRet(),
662 StopTracking, StopTracking);
Mike Stump1eb44332009-09-09 15:08:12 +0000663 }
Ted Kremenekb3095252008-05-06 04:20:12 +0000664
Ted Kremenek1f180c32008-06-23 22:21:20 +0000665 void InitializeClassMethodSummaries();
666 void InitializeMethodSummaries();
Ted Kremenek896cd9d2008-10-23 01:56:15 +0000667private:
Ted Kremenek93edbc52011-10-05 23:54:29 +0000668 void addNSObjectClsMethSummary(Selector S, const RetainSummary *Summ) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000669 ObjCClassMethodSummaries[S] = Summ;
670 }
Mike Stump1eb44332009-09-09 15:08:12 +0000671
Ted Kremenek93edbc52011-10-05 23:54:29 +0000672 void addNSObjectMethSummary(Selector S, const RetainSummary *Summ) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000673 ObjCMethodSummaries[S] = Summ;
674 }
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +0000675
Ted Kremeneka9797122012-02-18 21:37:48 +0000676 void addClassMethSummary(const char* Cls, const char* name,
677 const RetainSummary *Summ, bool isNullary = true) {
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +0000678 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
Ted Kremeneka9797122012-02-18 21:37:48 +0000679 Selector S = isNullary ? GetNullarySelector(name, Ctx)
680 : GetUnarySelector(name, Ctx);
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +0000681 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
682 }
Mike Stump1eb44332009-09-09 15:08:12 +0000683
Ted Kremenek6c4becb2009-02-25 02:54:57 +0000684 void addInstMethSummary(const char* Cls, const char* nullaryName,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000685 const RetainSummary *Summ) {
Ted Kremenek6c4becb2009-02-25 02:54:57 +0000686 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
687 Selector S = GetNullarySelector(nullaryName, Ctx);
688 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
689 }
Mike Stump1eb44332009-09-09 15:08:12 +0000690
Ted Kremenekde4d5332009-04-24 17:50:11 +0000691 Selector generateSelector(va_list argp) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000692 SmallVector<IdentifierInfo*, 10> II;
Ted Kremenekde4d5332009-04-24 17:50:11 +0000693
Ted Kremenek9e476de2008-08-12 18:30:56 +0000694 while (const char* s = va_arg(argp, const char*))
695 II.push_back(&Ctx.Idents.get(s));
Ted Kremenekde4d5332009-04-24 17:50:11 +0000696
Mike Stump1eb44332009-09-09 15:08:12 +0000697 return Ctx.Selectors.getSelector(II.size(), &II[0]);
Ted Kremenekde4d5332009-04-24 17:50:11 +0000698 }
Mike Stump1eb44332009-09-09 15:08:12 +0000699
Ted Kremenekde4d5332009-04-24 17:50:11 +0000700 void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy& Summaries,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000701 const RetainSummary * Summ, va_list argp) {
Ted Kremenekde4d5332009-04-24 17:50:11 +0000702 Selector S = generateSelector(argp);
703 Summaries[ObjCSummaryKey(ClsII, S)] = Summ;
Ted Kremenek70a733e2008-07-18 17:24:20 +0000704 }
Mike Stump1eb44332009-09-09 15:08:12 +0000705
Ted Kremenek93edbc52011-10-05 23:54:29 +0000706 void addInstMethSummary(const char* Cls, const RetainSummary * Summ, ...) {
Ted Kremenekaf9dc272008-08-12 18:48:50 +0000707 va_list argp;
708 va_start(argp, Summ);
Ted Kremenekde4d5332009-04-24 17:50:11 +0000709 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Mike Stump1eb44332009-09-09 15:08:12 +0000710 va_end(argp);
Ted Kremenekaf9dc272008-08-12 18:48:50 +0000711 }
Mike Stump1eb44332009-09-09 15:08:12 +0000712
Ted Kremenek93edbc52011-10-05 23:54:29 +0000713 void addClsMethSummary(const char* Cls, const RetainSummary * Summ, ...) {
Ted Kremenekde4d5332009-04-24 17:50:11 +0000714 va_list argp;
715 va_start(argp, Summ);
716 addMethodSummary(&Ctx.Idents.get(Cls),ObjCClassMethodSummaries, Summ, argp);
717 va_end(argp);
718 }
Mike Stump1eb44332009-09-09 15:08:12 +0000719
Ted Kremenek93edbc52011-10-05 23:54:29 +0000720 void addClsMethSummary(IdentifierInfo *II, const RetainSummary * Summ, ...) {
Ted Kremenekde4d5332009-04-24 17:50:11 +0000721 va_list argp;
722 va_start(argp, Summ);
723 addMethodSummary(II, ObjCClassMethodSummaries, Summ, argp);
724 va_end(argp);
725 }
726
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000727public:
Mike Stump1eb44332009-09-09 15:08:12 +0000728
Ted Kremenek9c378f72011-08-12 23:37:29 +0000729 RetainSummaryManager(ASTContext &ctx, bool gcenabled, bool usesARC)
Ted Kremenek179064e2008-07-01 17:21:27 +0000730 : Ctx(ctx),
John McCallf85e1932011-06-15 23:02:42 +0000731 GCEnabled(gcenabled),
732 ARCEnabled(usesARC),
733 AF(BPAlloc), ScratchArgs(AF.getEmptyMap()),
734 ObjCAllocRetE(gcenabled
735 ? RetEffect::MakeGCNotOwned()
736 : (usesARC ? RetEffect::MakeARCNotOwned()
737 : RetEffect::MakeOwned(RetEffect::ObjC, true))),
738 ObjCInitRetE(gcenabled
739 ? RetEffect::MakeGCNotOwned()
740 : (usesARC ? RetEffect::MakeARCNotOwned()
Jordy Roseef945882012-03-18 01:26:10 +0000741 : RetEffect::MakeOwnedWhenTrackedReceiver())) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000742 InitializeClassMethodSummaries();
743 InitializeMethodSummaries();
744 }
Mike Stump1eb44332009-09-09 15:08:12 +0000745
Jordan Rose4531b7d2012-07-02 19:27:43 +0000746 const RetainSummary *getSummary(const CallEvent &Call,
747 ProgramStateRef State = 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000748
Jordan Rose4531b7d2012-07-02 19:27:43 +0000749 const RetainSummary *getFunctionSummary(const FunctionDecl *FD);
750
751 const RetainSummary *getMethodSummary(Selector S, const ObjCInterfaceDecl *ID,
Jordy Rosef3aae582012-03-17 21:13:07 +0000752 const ObjCMethodDecl *MD,
753 QualType RetTy,
754 ObjCMethodSummariesTy &CachedSummaries);
755
Jordan Rosecde8cdb2012-07-02 19:27:56 +0000756 const RetainSummary *getInstanceMethodSummary(const ObjCMethodCall &M,
Jordan Rose4531b7d2012-07-02 19:27:43 +0000757 ProgramStateRef State);
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000758
Jordan Rosecde8cdb2012-07-02 19:27:56 +0000759 const RetainSummary *getClassMethodSummary(const ObjCMethodCall &M) {
Jordan Rose4531b7d2012-07-02 19:27:43 +0000760 assert(!M.isInstanceMessage());
761 const ObjCInterfaceDecl *Class = M.getReceiverInterface();
Mike Stump1eb44332009-09-09 15:08:12 +0000762
Jordan Rose4531b7d2012-07-02 19:27:43 +0000763 return getMethodSummary(M.getSelector(), Class, M.getDecl(),
764 M.getResultType(), ObjCClassMethodSummaries);
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +0000765 }
Ted Kremenek552333c2009-04-29 17:17:48 +0000766
767 /// getMethodSummary - This version of getMethodSummary is used to query
768 /// the summary for the current method being analyzed.
Ted Kremenek93edbc52011-10-05 23:54:29 +0000769 const RetainSummary *getMethodSummary(const ObjCMethodDecl *MD) {
Ted Kremeneka8833552009-04-29 23:03:22 +0000770 const ObjCInterfaceDecl *ID = MD->getClassInterface();
Ted Kremenek70a65762009-04-30 05:41:14 +0000771 Selector S = MD->getSelector();
Ted Kremenek552333c2009-04-29 17:17:48 +0000772 QualType ResultTy = MD->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +0000773
Jordy Rosef3aae582012-03-17 21:13:07 +0000774 ObjCMethodSummariesTy *CachedSummaries;
Ted Kremenek552333c2009-04-29 17:17:48 +0000775 if (MD->isInstanceMethod())
Jordy Rosef3aae582012-03-17 21:13:07 +0000776 CachedSummaries = &ObjCMethodSummaries;
Ted Kremenek552333c2009-04-29 17:17:48 +0000777 else
Jordy Rosef3aae582012-03-17 21:13:07 +0000778 CachedSummaries = &ObjCClassMethodSummaries;
779
Jordan Rose4531b7d2012-07-02 19:27:43 +0000780 return getMethodSummary(S, ID, MD, ResultTy, *CachedSummaries);
Ted Kremenek552333c2009-04-29 17:17:48 +0000781 }
Mike Stump1eb44332009-09-09 15:08:12 +0000782
Jordy Rosef3aae582012-03-17 21:13:07 +0000783 const RetainSummary *getStandardMethodSummary(const ObjCMethodDecl *MD,
Jordan Rose4531b7d2012-07-02 19:27:43 +0000784 Selector S, QualType RetTy);
Ted Kremeneka8833552009-04-29 23:03:22 +0000785
Ted Kremenek93edbc52011-10-05 23:54:29 +0000786 void updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenek4dd8fb42009-05-09 02:58:13 +0000787 const ObjCMethodDecl *MD);
788
Ted Kremenek93edbc52011-10-05 23:54:29 +0000789 void updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenek4dd8fb42009-05-09 02:58:13 +0000790 const FunctionDecl *FD);
791
Jordan Rose4531b7d2012-07-02 19:27:43 +0000792 void updateSummaryForCall(const RetainSummary *&Summ,
793 const CallEvent &Call);
794
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000795 bool isGCEnabled() const { return GCEnabled; }
Mike Stump1eb44332009-09-09 15:08:12 +0000796
John McCallf85e1932011-06-15 23:02:42 +0000797 bool isARCEnabled() const { return ARCEnabled; }
798
799 bool isARCorGCEnabled() const { return GCEnabled || ARCEnabled; }
Jordan Rose4531b7d2012-07-02 19:27:43 +0000800
801 RetEffect getObjAllocRetEffect() const { return ObjCAllocRetE; }
802
803 friend class RetainSummaryTemplate;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000804};
Mike Stump1eb44332009-09-09 15:08:12 +0000805
Jordy Rose0fe62f82011-08-24 09:02:37 +0000806// Used to avoid allocating long-term (BPAlloc'd) memory for default retain
807// summaries. If a function or method looks like it has a default summary, but
808// it has annotations, the annotations are added to the stack-based template
809// and then copied into managed memory.
810class RetainSummaryTemplate {
811 RetainSummaryManager &Manager;
Ted Kremenek93edbc52011-10-05 23:54:29 +0000812 const RetainSummary *&RealSummary;
Jordy Rose0fe62f82011-08-24 09:02:37 +0000813 RetainSummary ScratchSummary;
814 bool Accessed;
815public:
Jordan Rose4531b7d2012-07-02 19:27:43 +0000816 RetainSummaryTemplate(const RetainSummary *&real, RetainSummaryManager &mgr)
817 : Manager(mgr), RealSummary(real), ScratchSummary(*real), Accessed(false) {}
Jordy Rose0fe62f82011-08-24 09:02:37 +0000818
819 ~RetainSummaryTemplate() {
Ted Kremenek93edbc52011-10-05 23:54:29 +0000820 if (Accessed)
Jordy Roseef945882012-03-18 01:26:10 +0000821 RealSummary = Manager.getPersistentSummary(ScratchSummary);
Jordy Rose0fe62f82011-08-24 09:02:37 +0000822 }
823
824 RetainSummary &operator*() {
825 Accessed = true;
Ted Kremenek93edbc52011-10-05 23:54:29 +0000826 return 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
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000835} // end anonymous namespace
836
837//===----------------------------------------------------------------------===//
838// Implementation of checker data structures.
839//===----------------------------------------------------------------------===//
840
Ted Kremenekb77449c2009-05-03 05:20:50 +0000841ArgEffects RetainSummaryManager::getArgEffects() {
842 ArgEffects AE = ScratchArgs;
Ted Kremenek3baf6722010-11-24 00:54:37 +0000843 ScratchArgs = AF.getEmptyMap();
Ted Kremenekb77449c2009-05-03 05:20:50 +0000844 return AE;
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000845}
846
Ted Kremenek93edbc52011-10-05 23:54:29 +0000847const RetainSummary *
Jordy Roseef945882012-03-18 01:26:10 +0000848RetainSummaryManager::getPersistentSummary(const RetainSummary &OldSumm) {
849 // Unique "simple" summaries -- those without ArgEffects.
850 if (OldSumm.isSimple()) {
851 llvm::FoldingSetNodeID ID;
852 OldSumm.Profile(ID);
853
854 void *Pos;
855 CachedSummaryNode *N = SimpleSummaries.FindNodeOrInsertPos(ID, Pos);
856
857 if (!N) {
858 N = (CachedSummaryNode *) BPAlloc.Allocate<CachedSummaryNode>();
859 new (N) CachedSummaryNode(OldSumm);
860 SimpleSummaries.InsertNode(N, Pos);
861 }
862
863 return &N->getValue();
864 }
865
Ted Kremenek93edbc52011-10-05 23:54:29 +0000866 RetainSummary *Summ = (RetainSummary *) BPAlloc.Allocate<RetainSummary>();
Jordy Roseef945882012-03-18 01:26:10 +0000867 new (Summ) RetainSummary(OldSumm);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000868 return Summ;
869}
870
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000871//===----------------------------------------------------------------------===//
872// Summary creation for functions (largely uses of Core Foundation).
873//===----------------------------------------------------------------------===//
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000874
Ted Kremenek9c378f72011-08-12 23:37:29 +0000875static bool isRetain(const FunctionDecl *FD, StringRef FName) {
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000876 return FName.endswith("Retain");
Ted Kremenek12619382009-01-12 21:45:02 +0000877}
878
Ted Kremenek9c378f72011-08-12 23:37:29 +0000879static bool isRelease(const FunctionDecl *FD, StringRef FName) {
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000880 return FName.endswith("Release");
Ted Kremenek12619382009-01-12 21:45:02 +0000881}
882
Jordy Rose76c506f2011-08-21 21:58:18 +0000883static bool isMakeCollectable(const FunctionDecl *FD, StringRef FName) {
884 // FIXME: Remove FunctionDecl parameter.
885 // FIXME: Is it really okay if MakeCollectable isn't a suffix?
886 return FName.find("MakeCollectable") != StringRef::npos;
887}
888
Anna Zaks554067f2012-08-29 23:23:43 +0000889static ArgEffect getStopTrackingHardEquivalent(ArgEffect E) {
Jordan Rose4531b7d2012-07-02 19:27:43 +0000890 switch (E) {
891 case DoNothing:
892 case Autorelease:
893 case DecRefBridgedTransfered:
894 case IncRef:
895 case IncRefMsg:
896 case MakeCollectable:
897 case MayEscape:
898 case NewAutoreleasePool:
899 case StopTracking:
Anna Zaks554067f2012-08-29 23:23:43 +0000900 case StopTrackingHard:
901 return StopTrackingHard;
Jordan Rose4531b7d2012-07-02 19:27:43 +0000902 case DecRef:
Anna Zaks554067f2012-08-29 23:23:43 +0000903 case DecRefAndStopTrackingHard:
904 return DecRefAndStopTrackingHard;
Jordan Rose4531b7d2012-07-02 19:27:43 +0000905 case DecRefMsg:
Anna Zaks554067f2012-08-29 23:23:43 +0000906 case DecRefMsgAndStopTrackingHard:
907 return DecRefMsgAndStopTrackingHard;
Jordan Rose4531b7d2012-07-02 19:27:43 +0000908 case Dealloc:
909 return Dealloc;
910 }
911
912 llvm_unreachable("Unknown ArgEffect kind");
913}
914
915void RetainSummaryManager::updateSummaryForCall(const RetainSummary *&S,
916 const CallEvent &Call) {
917 if (Call.hasNonZeroCallbackArg()) {
Anna Zaks554067f2012-08-29 23:23:43 +0000918 ArgEffect RecEffect =
919 getStopTrackingHardEquivalent(S->getReceiverEffect());
920 ArgEffect DefEffect =
921 getStopTrackingHardEquivalent(S->getDefaultArgEffect());
Jordan Rose4531b7d2012-07-02 19:27:43 +0000922
923 ArgEffects CustomArgEffects = S->getArgEffects();
924 for (ArgEffects::iterator I = CustomArgEffects.begin(),
925 E = CustomArgEffects.end();
926 I != E; ++I) {
Anna Zaks554067f2012-08-29 23:23:43 +0000927 ArgEffect Translated = getStopTrackingHardEquivalent(I->second);
Jordan Rose4531b7d2012-07-02 19:27:43 +0000928 if (Translated != DefEffect)
929 ScratchArgs = AF.add(ScratchArgs, I->first, Translated);
930 }
931
Anna Zaks554067f2012-08-29 23:23:43 +0000932 RetEffect RE = RetEffect::MakeNoRetHard();
Jordan Rose4531b7d2012-07-02 19:27:43 +0000933
934 // Special cases where the callback argument CANNOT free the return value.
935 // This can generally only happen if we know that the callback will only be
936 // called when the return value is already being deallocated.
937 if (const FunctionCall *FC = dyn_cast<FunctionCall>(&Call)) {
Jordan Rose4a25f302012-09-01 17:39:13 +0000938 if (IdentifierInfo *Name = FC->getDecl()->getIdentifier()) {
939 // When the CGBitmapContext is deallocated, the callback here will free
940 // the associated data buffer.
Jordan Rosea89f7192012-08-31 18:19:18 +0000941 if (Name->isStr("CGBitmapContextCreateWithData"))
942 RE = S->getRetEffect();
Jordan Rose4a25f302012-09-01 17:39:13 +0000943 }
Jordan Rose4531b7d2012-07-02 19:27:43 +0000944 }
945
946 S = getPersistentSummary(RE, RecEffect, DefEffect);
947 }
Anna Zaks5a901932012-08-24 00:06:12 +0000948
949 // Special case '[super init];' and '[self init];'
950 //
951 // Even though calling '[super init]' without assigning the result to self
952 // and checking if the parent returns 'nil' is a bad pattern, it is common.
953 // Additionally, our Self Init checker already warns about it. To avoid
954 // overwhelming the user with messages from both checkers, we model the case
955 // of '[super init]' in cases when it is not consumed by another expression
956 // as if the call preserves the value of 'self'; essentially, assuming it can
957 // never fail and return 'nil'.
958 // Note, we don't want to just stop tracking the value since we want the
959 // RetainCount checker to report leaks and use-after-free if SelfInit checker
960 // is turned off.
961 if (const ObjCMethodCall *MC = dyn_cast<ObjCMethodCall>(&Call)) {
962 if (MC->getMethodFamily() == OMF_init && MC->isReceiverSelfOrSuper()) {
963
964 // Check if the message is not consumed, we know it will not be used in
965 // an assignment, ex: "self = [super init]".
966 const Expr *ME = MC->getOriginExpr();
967 const LocationContext *LCtx = MC->getLocationContext();
968 ParentMap &PM = LCtx->getAnalysisDeclContext()->getParentMap();
969 if (!PM.isConsumedExpr(ME)) {
970 RetainSummaryTemplate ModifiableSummaryTemplate(S, *this);
971 ModifiableSummaryTemplate->setReceiverEffect(DoNothing);
972 ModifiableSummaryTemplate->setRetEffect(RetEffect::MakeNoRet());
973 }
974 }
975
976 }
Jordan Rose4531b7d2012-07-02 19:27:43 +0000977}
978
Anna Zaks58822c42012-05-04 22:18:39 +0000979const RetainSummary *
Jordan Rose4531b7d2012-07-02 19:27:43 +0000980RetainSummaryManager::getSummary(const CallEvent &Call,
981 ProgramStateRef State) {
982 const RetainSummary *Summ;
983 switch (Call.getKind()) {
984 case CE_Function:
985 Summ = getFunctionSummary(cast<FunctionCall>(Call).getDecl());
986 break;
987 case CE_CXXMember:
Jordan Rosefdaa3382012-07-03 22:55:57 +0000988 case CE_CXXMemberOperator:
Jordan Rose4531b7d2012-07-02 19:27:43 +0000989 case CE_Block:
990 case CE_CXXConstructor:
Jordan Rose8d276d32012-07-10 22:07:47 +0000991 case CE_CXXDestructor:
Jordan Rose70cbf3c2012-07-02 22:21:47 +0000992 case CE_CXXAllocator:
Jordan Rose4531b7d2012-07-02 19:27:43 +0000993 // FIXME: These calls are currently unsupported.
994 return getPersistentStopSummary();
Jordan Rose8919e682012-07-18 21:59:51 +0000995 case CE_ObjCMessage: {
Jordan Rosecde8cdb2012-07-02 19:27:56 +0000996 const ObjCMethodCall &Msg = cast<ObjCMethodCall>(Call);
Jordan Rose4531b7d2012-07-02 19:27:43 +0000997 if (Msg.isInstanceMessage())
998 Summ = getInstanceMethodSummary(Msg, State);
999 else
1000 Summ = getClassMethodSummary(Msg);
1001 break;
1002 }
1003 }
1004
1005 updateSummaryForCall(Summ, Call);
1006
1007 assert(Summ && "Unknown call type?");
1008 return Summ;
1009}
1010
1011const RetainSummary *
1012RetainSummaryManager::getFunctionSummary(const FunctionDecl *FD) {
1013 // If we don't know what function we're calling, use our default summary.
1014 if (!FD)
1015 return getDefaultSummary();
1016
Ted Kremenek891d5cc2008-04-24 17:22:33 +00001017 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001018 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001019 if (I != FuncSummaries.end())
Ted Kremenek891d5cc2008-04-24 17:22:33 +00001020 return I->second;
1021
Ted Kremeneke401a0c2009-05-04 15:34:07 +00001022 // No summary? Generate one.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001023 const RetainSummary *S = 0;
Jordan Rose15d18e12012-08-06 21:28:02 +00001024 bool AllowAnnotations = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001025
Ted Kremenek37d785b2008-07-15 16:50:12 +00001026 do {
Ted Kremenek12619382009-01-12 21:45:02 +00001027 // We generate "stop" summaries for implicitly defined functions.
1028 if (FD->isImplicit()) {
1029 S = getPersistentStopSummary();
1030 break;
Ted Kremenek37d785b2008-07-15 16:50:12 +00001031 }
Mike Stump1eb44332009-09-09 15:08:12 +00001032
John McCall183700f2009-09-21 23:43:11 +00001033 // [PR 3337] Use 'getAs<FunctionType>' to strip away any typedefs on the
Ted Kremenek99890652009-01-16 18:40:33 +00001034 // function's type.
John McCall183700f2009-09-21 23:43:11 +00001035 const FunctionType* FT = FD->getType()->getAs<FunctionType>();
Ted Kremenek48c6d182009-12-16 06:06:43 +00001036 const IdentifierInfo *II = FD->getIdentifier();
1037 if (!II)
1038 break;
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001039
1040 StringRef FName = II->getName();
Mike Stump1eb44332009-09-09 15:08:12 +00001041
Ted Kremenekbf0a4dd2009-03-05 22:11:14 +00001042 // Strip away preceding '_'. Doing this here will effect all the checks
1043 // down below.
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001044 FName = FName.substr(FName.find_first_not_of('_'));
Mike Stump1eb44332009-09-09 15:08:12 +00001045
Ted Kremenek12619382009-01-12 21:45:02 +00001046 // Inspect the result type.
1047 QualType RetTy = FT->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00001048
Ted Kremenek12619382009-01-12 21:45:02 +00001049 // FIXME: This should all be refactored into a chain of "summary lookup"
1050 // filters.
Ted Kremenek008636a2009-10-14 00:27:24 +00001051 assert(ScratchArgs.isEmpty());
Ted Kremenek39d88b02009-06-15 20:36:07 +00001052
Ted Kremenekbefc6d22012-04-26 04:32:23 +00001053 if (FName == "pthread_create" || FName == "pthread_setspecific") {
1054 // Part of: <rdar://problem/7299394> and <rdar://problem/11282706>.
1055 // This will be addressed better with IPA.
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001056 S = getPersistentStopSummary();
1057 } else if (FName == "NSMakeCollectable") {
1058 // Handle: id NSMakeCollectable(CFTypeRef)
1059 S = (RetTy->isObjCIdType())
1060 ? getUnarySummary(FT, cfmakecollectable)
1061 : getPersistentStopSummary();
Jordan Rose15d18e12012-08-06 21:28:02 +00001062 // The headers on OS X 10.8 use cf_consumed/ns_returns_retained,
1063 // but we can fully model NSMakeCollectable ourselves.
1064 AllowAnnotations = false;
Ted Kremenek061707a2012-09-06 23:47:02 +00001065 } else if (FName == "CFPlugInInstanceCreate") {
1066 S = getPersistentSummary(RetEffect::MakeNoRet());
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001067 } else if (FName == "IOBSDNameMatching" ||
1068 FName == "IOServiceMatching" ||
1069 FName == "IOServiceNameMatching" ||
Ted Kremenek537dd3a2012-05-01 05:28:27 +00001070 FName == "IORegistryEntrySearchCFProperty" ||
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001071 FName == "IORegistryEntryIDMatching" ||
1072 FName == "IOOpenFirmwarePathMatching") {
1073 // Part of <rdar://problem/6961230>. (IOKit)
1074 // This should be addressed using a API table.
1075 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1076 DoNothing, DoNothing);
1077 } else if (FName == "IOServiceGetMatchingService" ||
1078 FName == "IOServiceGetMatchingServices") {
1079 // FIXES: <rdar://problem/6326900>
1080 // This should be addressed using a API table. This strcmp is also
1081 // a little gross, but there is no need to super optimize here.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001082 ScratchArgs = AF.add(ScratchArgs, 1, DecRef);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001083 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1084 } else if (FName == "IOServiceAddNotification" ||
1085 FName == "IOServiceAddMatchingNotification") {
1086 // Part of <rdar://problem/6961230>. (IOKit)
1087 // This should be addressed using a API table.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001088 ScratchArgs = AF.add(ScratchArgs, 2, DecRef);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001089 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1090 } else if (FName == "CVPixelBufferCreateWithBytes") {
1091 // FIXES: <rdar://problem/7283567>
1092 // Eventually this can be improved by recognizing that the pixel
1093 // buffer passed to CVPixelBufferCreateWithBytes is released via
1094 // a callback and doing full IPA to make sure this is done correctly.
1095 // FIXME: This function has an out parameter that returns an
1096 // allocated object.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001097 ScratchArgs = AF.add(ScratchArgs, 7, StopTracking);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001098 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1099 } else if (FName == "CGBitmapContextCreateWithData") {
1100 // FIXES: <rdar://problem/7358899>
1101 // Eventually this can be improved by recognizing that 'releaseInfo'
1102 // passed to CGBitmapContextCreateWithData is released via
1103 // a callback and doing full IPA to make sure this is done correctly.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001104 ScratchArgs = AF.add(ScratchArgs, 8, StopTracking);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001105 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1106 DoNothing, DoNothing);
1107 } else if (FName == "CVPixelBufferCreateWithPlanarBytes") {
1108 // FIXES: <rdar://problem/7283567>
1109 // Eventually this can be improved by recognizing that the pixel
1110 // buffer passed to CVPixelBufferCreateWithPlanarBytes is released
1111 // via a callback and doing full IPA to make sure this is done
1112 // correctly.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001113 ScratchArgs = AF.add(ScratchArgs, 12, StopTracking);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001114 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenek06911d42012-03-22 06:29:41 +00001115 } else if (FName == "dispatch_set_context") {
1116 // <rdar://problem/11059275> - The analyzer currently doesn't have
1117 // a good way to reason about the finalizer function for libdispatch.
1118 // If we pass a context object that is memory managed, stop tracking it.
1119 // FIXME: this hack should possibly go away once we can handle
1120 // libdispatch finalizers.
1121 ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
1122 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenekc91fdf62012-05-08 00:12:09 +00001123 } else if (FName.startswith("NSLog")) {
1124 S = getDoNothingSummary();
Anna Zaks62a5c342012-03-30 05:48:16 +00001125 } else if (FName.startswith("NS") &&
1126 (FName.find("Insert") != StringRef::npos)) {
1127 // Whitelist NSXXInsertXX, for example NSMapInsertIfAbsent, since they can
1128 // be deallocated by NSMapRemove. (radar://11152419)
1129 ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
1130 ScratchArgs = AF.add(ScratchArgs, 2, StopTracking);
1131 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenekb04cb592009-06-11 18:17:24 +00001132 }
Mike Stump1eb44332009-09-09 15:08:12 +00001133
Ted Kremenekb04cb592009-06-11 18:17:24 +00001134 // Did we get a summary?
1135 if (S)
1136 break;
Ted Kremenek61991902009-03-17 22:43:44 +00001137
Ted Kremenek12619382009-01-12 21:45:02 +00001138 if (RetTy->isPointerType()) {
Ted Kremeneke7883652012-08-30 19:27:02 +00001139 if (FD->getAttr<CFAuditedTransferAttr>()) {
1140 S = getCFCreateGetRuleSummary(FD);
1141 break;
1142 }
1143
Ted Kremenek12619382009-01-12 21:45:02 +00001144 // For CoreFoundation ('CF') types.
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001145 if (cocoa::isRefType(RetTy, "CF", FName)) {
Ted Kremenek12619382009-01-12 21:45:02 +00001146 if (isRetain(FD, FName))
1147 S = getUnarySummary(FT, cfretain);
Jordy Rose76c506f2011-08-21 21:58:18 +00001148 else if (isMakeCollectable(FD, FName))
Ted Kremenek12619382009-01-12 21:45:02 +00001149 S = getUnarySummary(FT, cfmakecollectable);
Mike Stump1eb44332009-09-09 15:08:12 +00001150 else
John McCall7df2ff42011-10-01 00:48:56 +00001151 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek12619382009-01-12 21:45:02 +00001152
1153 break;
1154 }
1155
1156 // For CoreGraphics ('CG') types.
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001157 if (cocoa::isRefType(RetTy, "CG", FName)) {
Ted Kremenek12619382009-01-12 21:45:02 +00001158 if (isRetain(FD, FName))
1159 S = getUnarySummary(FT, cfretain);
1160 else
John McCall7df2ff42011-10-01 00:48:56 +00001161 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek12619382009-01-12 21:45:02 +00001162
1163 break;
1164 }
1165
1166 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001167 if (cocoa::isRefType(RetTy, "DADisk") ||
1168 cocoa::isRefType(RetTy, "DADissenter") ||
1169 cocoa::isRefType(RetTy, "DASessionRef")) {
John McCall7df2ff42011-10-01 00:48:56 +00001170 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek12619382009-01-12 21:45:02 +00001171 break;
1172 }
Mike Stump1eb44332009-09-09 15:08:12 +00001173
Ted Kremenek12619382009-01-12 21:45:02 +00001174 break;
1175 }
1176
1177 // Check for release functions, the only kind of functions that we care
1178 // about that don't return a pointer type.
1179 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
Ted Kremeneke7d03122010-02-08 16:45:01 +00001180 // Test for 'CGCF'.
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001181 FName = FName.substr(FName.startswith("CGCF") ? 4 : 2);
Ted Kremeneke7d03122010-02-08 16:45:01 +00001182
Ted Kremenekbf0a4dd2009-03-05 22:11:14 +00001183 if (isRelease(FD, FName))
Ted Kremenek12619382009-01-12 21:45:02 +00001184 S = getUnarySummary(FT, cfrelease);
1185 else {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001186 assert (ScratchArgs.isEmpty());
Ted Kremenek68189282009-01-29 22:45:13 +00001187 // Remaining CoreFoundation and CoreGraphics functions.
1188 // We use to assume that they all strictly followed the ownership idiom
1189 // and that ownership cannot be transferred. While this is technically
1190 // correct, many methods allow a tracked object to escape. For example:
1191 //
Mike Stump1eb44332009-09-09 15:08:12 +00001192 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
Ted Kremenek68189282009-01-29 22:45:13 +00001193 // CFDictionaryAddValue(y, key, x);
Mike Stump1eb44332009-09-09 15:08:12 +00001194 // CFRelease(x);
Ted Kremenek68189282009-01-29 22:45:13 +00001195 // ... it is okay to use 'x' since 'y' has a reference to it
1196 //
1197 // We handle this and similar cases with the follow heuristic. If the
Ted Kremenekc4843812009-08-20 00:57:22 +00001198 // function name contains "InsertValue", "SetValue", "AddValue",
1199 // "AppendValue", or "SetAttribute", then we assume that arguments may
1200 // "escape." This means that something else holds on to the object,
1201 // allowing it be used even after its local retain count drops to 0.
Benjamin Kramere45c1492010-01-11 19:46:28 +00001202 ArgEffect E = (StrInStrNoCase(FName, "InsertValue") != StringRef::npos||
1203 StrInStrNoCase(FName, "AddValue") != StringRef::npos ||
1204 StrInStrNoCase(FName, "SetValue") != StringRef::npos ||
1205 StrInStrNoCase(FName, "AppendValue") != StringRef::npos||
Benjamin Kramerc027e542010-01-11 20:15:06 +00001206 StrInStrNoCase(FName, "SetAttribute") != StringRef::npos)
Ted Kremenek68189282009-01-29 22:45:13 +00001207 ? MayEscape : DoNothing;
Mike Stump1eb44332009-09-09 15:08:12 +00001208
Ted Kremenek68189282009-01-29 22:45:13 +00001209 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek12619382009-01-12 21:45:02 +00001210 }
1211 }
Ted Kremenek37d785b2008-07-15 16:50:12 +00001212 }
1213 while (0);
Mike Stump1eb44332009-09-09 15:08:12 +00001214
Jordan Rose4531b7d2012-07-02 19:27:43 +00001215 // If we got all the way here without any luck, use a default summary.
1216 if (!S)
1217 S = getDefaultSummary();
1218
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001219 // Annotations override defaults.
Jordan Rose15d18e12012-08-06 21:28:02 +00001220 if (AllowAnnotations)
1221 updateSummaryFromAnnotations(S, FD);
Mike Stump1eb44332009-09-09 15:08:12 +00001222
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001223 FuncSummaries[FD] = S;
Mike Stump1eb44332009-09-09 15:08:12 +00001224 return S;
Ted Kremenek2fff37e2008-03-06 00:08:09 +00001225}
1226
Ted Kremenek93edbc52011-10-05 23:54:29 +00001227const RetainSummary *
John McCall7df2ff42011-10-01 00:48:56 +00001228RetainSummaryManager::getCFCreateGetRuleSummary(const FunctionDecl *FD) {
1229 if (coreFoundation::followsCreateRule(FD))
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001230 return getCFSummaryCreateRule(FD);
Mike Stump1eb44332009-09-09 15:08:12 +00001231
Ted Kremenekd368d712011-05-25 06:19:45 +00001232 return getCFSummaryGetRule(FD);
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001233}
1234
Ted Kremenek93edbc52011-10-05 23:54:29 +00001235const RetainSummary *
Ted Kremenek6ad315a2009-02-23 16:51:39 +00001236RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1237 UnaryFuncKind func) {
1238
Ted Kremenek12619382009-01-12 21:45:02 +00001239 // Sanity check that this is *really* a unary function. This can
1240 // happen if people do weird things.
Douglas Gregor72564e72009-02-26 23:50:07 +00001241 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
Ted Kremenek12619382009-01-12 21:45:02 +00001242 if (!FTP || FTP->getNumArgs() != 1)
1243 return getPersistentStopSummary();
Mike Stump1eb44332009-09-09 15:08:12 +00001244
Ted Kremenekb77449c2009-05-03 05:20:50 +00001245 assert (ScratchArgs.isEmpty());
Mike Stump1eb44332009-09-09 15:08:12 +00001246
Jordy Rose76c506f2011-08-21 21:58:18 +00001247 ArgEffect Effect;
Ted Kremenek377e2302008-04-29 05:33:51 +00001248 switch (func) {
Jordy Rose76c506f2011-08-21 21:58:18 +00001249 case cfretain: Effect = IncRef; break;
1250 case cfrelease: Effect = DecRef; break;
1251 case cfmakecollectable: Effect = MakeCollectable; break;
Ted Kremenek940b1d82008-04-10 23:44:06 +00001252 }
Jordy Rose76c506f2011-08-21 21:58:18 +00001253
1254 ScratchArgs = AF.add(ScratchArgs, 0, Effect);
1255 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001256}
1257
Ted Kremenek93edbc52011-10-05 23:54:29 +00001258const RetainSummary *
Ted Kremenek9c378f72011-08-12 23:37:29 +00001259RetainSummaryManager::getCFSummaryCreateRule(const FunctionDecl *FD) {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001260 assert (ScratchArgs.isEmpty());
Mike Stump1eb44332009-09-09 15:08:12 +00001261
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001262 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001263}
1264
Ted Kremenek93edbc52011-10-05 23:54:29 +00001265const RetainSummary *
Ted Kremenek9c378f72011-08-12 23:37:29 +00001266RetainSummaryManager::getCFSummaryGetRule(const FunctionDecl *FD) {
Mike Stump1eb44332009-09-09 15:08:12 +00001267 assert (ScratchArgs.isEmpty());
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001268 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1269 DoNothing, DoNothing);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001270}
1271
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001272//===----------------------------------------------------------------------===//
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001273// Summary creation for Selectors.
1274//===----------------------------------------------------------------------===//
1275
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001276void
Ted Kremenek93edbc52011-10-05 23:54:29 +00001277RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001278 const FunctionDecl *FD) {
1279 if (!FD)
1280 return;
1281
Jordan Rose4531b7d2012-07-02 19:27:43 +00001282 assert(Summ && "Must have a summary to add annotations to.");
1283 RetainSummaryTemplate Template(Summ, *this);
Jordy Rose4df54fe2011-08-23 04:27:15 +00001284
Ted Kremenek11fe1752011-01-27 18:43:03 +00001285 // Effects on the parameters.
1286 unsigned parm_idx = 0;
1287 for (FunctionDecl::param_const_iterator pi = FD->param_begin(),
John McCall98b8f162011-04-06 09:02:12 +00001288 pe = FD->param_end(); pi != pe; ++pi, ++parm_idx) {
Ted Kremenek11fe1752011-01-27 18:43:03 +00001289 const ParmVarDecl *pd = *pi;
1290 if (pd->getAttr<NSConsumedAttr>()) {
Jordy Rose4df54fe2011-08-23 04:27:15 +00001291 if (!GCEnabled) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001292 Template->addArg(AF, parm_idx, DecRef);
Jordy Rose4df54fe2011-08-23 04:27:15 +00001293 }
1294 } else if (pd->getAttr<CFConsumedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001295 Template->addArg(AF, parm_idx, DecRef);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001296 }
1297 }
1298
Ted Kremenekb04cb592009-06-11 18:17:24 +00001299 QualType RetTy = FD->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00001300
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001301 // Determine if there is a special return effect for this method.
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001302 if (cocoa::isCocoaObjectRef(RetTy)) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001303 if (FD->getAttr<NSReturnsRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001304 Template->setRetEffect(ObjCAllocRetE);
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001305 }
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001306 else if (FD->getAttr<CFReturnsRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001307 Template->setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenekb04cb592009-06-11 18:17:24 +00001308 }
Ted Kremenekbbf4d532012-12-20 19:36:22 +00001309 else if (FD->getAttr<NSReturnsNotRetainedAttr>() ||
1310 FD->getAttr<NSReturnsAutoreleasedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001311 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::ObjC));
Ted Kremenek60411112010-02-18 00:06:12 +00001312 }
Ted Kremenekbbf4d532012-12-20 19:36:22 +00001313 else if (FD->getAttr<CFReturnsNotRetainedAttr>())
Jordy Rose0fe62f82011-08-24 09:02:37 +00001314 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::CF));
Jordy Rose4df54fe2011-08-23 04:27:15 +00001315 }
Ted Kremenekbbf4d532012-12-20 19:36:22 +00001316 else if (RetTy->getAs<PointerType>()) {
Jordy Rose4df54fe2011-08-23 04:27:15 +00001317 if (FD->getAttr<CFReturnsRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001318 Template->setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
Jordy Rose4df54fe2011-08-23 04:27:15 +00001319 }
1320 else if (FD->getAttr<CFReturnsNotRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001321 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::CF));
Ted Kremenek60411112010-02-18 00:06:12 +00001322 }
Ted Kremenekb04cb592009-06-11 18:17:24 +00001323 }
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001324}
1325
1326void
Ted Kremenek93edbc52011-10-05 23:54:29 +00001327RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
1328 const ObjCMethodDecl *MD) {
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001329 if (!MD)
1330 return;
1331
Jordan Rose4531b7d2012-07-02 19:27:43 +00001332 assert(Summ && "Must have a valid summary to add annotations to");
1333 RetainSummaryTemplate Template(Summ, *this);
Ted Kremenek6d4b76d2009-07-06 18:30:43 +00001334 bool isTrackedLoc = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001335
Ted Kremenek12b94342011-01-27 06:54:14 +00001336 // Effects on the receiver.
1337 if (MD->getAttr<NSConsumesSelfAttr>()) {
Ted Kremenek11fe1752011-01-27 18:43:03 +00001338 if (!GCEnabled)
Jordy Rose0fe62f82011-08-24 09:02:37 +00001339 Template->setReceiverEffect(DecRefMsg);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001340 }
1341
1342 // Effects on the parameters.
1343 unsigned parm_idx = 0;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00001344 for (ObjCMethodDecl::param_const_iterator
1345 pi=MD->param_begin(), pe=MD->param_end();
Ted Kremenek11fe1752011-01-27 18:43:03 +00001346 pi != pe; ++pi, ++parm_idx) {
1347 const ParmVarDecl *pd = *pi;
1348 if (pd->getAttr<NSConsumedAttr>()) {
1349 if (!GCEnabled)
Jordy Rose0fe62f82011-08-24 09:02:37 +00001350 Template->addArg(AF, parm_idx, DecRef);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001351 }
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
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001357 // Determine if there is a special return effect for this method.
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001358 if (cocoa::isCocoaObjectRef(MD->getResultType())) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001359 if (MD->getAttr<NSReturnsRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001360 Template->setRetEffect(ObjCAllocRetE);
Ted Kremenek6d4b76d2009-07-06 18:30:43 +00001361 return;
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001362 }
Ted Kremenekbbf4d532012-12-20 19:36:22 +00001363 if (MD->getAttr<NSReturnsNotRetainedAttr>() ||
1364 MD->getAttr<NSReturnsAutoreleasedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001365 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::ObjC));
Ted Kremenek60411112010-02-18 00:06:12 +00001366 return;
1367 }
Mike Stump1eb44332009-09-09 15:08:12 +00001368
Ted Kremenek6d4b76d2009-07-06 18:30:43 +00001369 isTrackedLoc = true;
Jordy Rose0fe62f82011-08-24 09:02:37 +00001370 } else {
Ted Kremenek6217b802009-07-29 21:53:49 +00001371 isTrackedLoc = MD->getResultType()->getAs<PointerType>() != NULL;
Jordy Rose0fe62f82011-08-24 09:02:37 +00001372 }
Mike Stump1eb44332009-09-09 15:08:12 +00001373
Ted Kremenek60411112010-02-18 00:06:12 +00001374 if (isTrackedLoc) {
1375 if (MD->getAttr<CFReturnsRetainedAttr>())
Jordy Rose0fe62f82011-08-24 09:02:37 +00001376 Template->setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenek60411112010-02-18 00:06:12 +00001377 else if (MD->getAttr<CFReturnsNotRetainedAttr>())
Jordy Rose0fe62f82011-08-24 09:02:37 +00001378 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::CF));
Ted Kremenek60411112010-02-18 00:06:12 +00001379 }
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001380}
1381
Ted Kremenek93edbc52011-10-05 23:54:29 +00001382const RetainSummary *
Jordy Rosef3aae582012-03-17 21:13:07 +00001383RetainSummaryManager::getStandardMethodSummary(const ObjCMethodDecl *MD,
1384 Selector S, QualType RetTy) {
Jordy Rosee921b1a2012-03-17 19:53:04 +00001385 // Any special effects?
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001386 ArgEffect ReceiverEff = DoNothing;
Jordy Rosee921b1a2012-03-17 19:53:04 +00001387 RetEffect ResultEff = RetEffect::MakeNoRet();
1388
1389 // Check the method family, and apply any default annotations.
1390 switch (MD ? MD->getMethodFamily() : S.getMethodFamily()) {
1391 case OMF_None:
1392 case OMF_performSelector:
1393 // Assume all Objective-C methods follow Cocoa Memory Management rules.
1394 // FIXME: Does the non-threaded performSelector family really belong here?
1395 // The selector could be, say, @selector(copy).
1396 if (cocoa::isCocoaObjectRef(RetTy))
1397 ResultEff = RetEffect::MakeNotOwned(RetEffect::ObjC);
1398 else if (coreFoundation::isCFObjectRef(RetTy)) {
1399 // ObjCMethodDecl currently doesn't consider CF objects as valid return
1400 // values for alloc, new, copy, or mutableCopy, so we have to
1401 // double-check with the selector. This is ugly, but there aren't that
1402 // many Objective-C methods that return CF objects, right?
1403 if (MD) {
1404 switch (S.getMethodFamily()) {
1405 case OMF_alloc:
1406 case OMF_new:
1407 case OMF_copy:
1408 case OMF_mutableCopy:
1409 ResultEff = RetEffect::MakeOwned(RetEffect::CF, true);
1410 break;
1411 default:
1412 ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1413 break;
1414 }
1415 } else {
1416 ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1417 }
1418 }
1419 break;
1420 case OMF_init:
1421 ResultEff = ObjCInitRetE;
1422 ReceiverEff = DecRefMsg;
1423 break;
1424 case OMF_alloc:
1425 case OMF_new:
1426 case OMF_copy:
1427 case OMF_mutableCopy:
1428 if (cocoa::isCocoaObjectRef(RetTy))
1429 ResultEff = ObjCAllocRetE;
1430 else if (coreFoundation::isCFObjectRef(RetTy))
1431 ResultEff = RetEffect::MakeOwned(RetEffect::CF, true);
1432 break;
1433 case OMF_autorelease:
1434 ReceiverEff = Autorelease;
1435 break;
1436 case OMF_retain:
1437 ReceiverEff = IncRefMsg;
1438 break;
1439 case OMF_release:
1440 ReceiverEff = DecRefMsg;
1441 break;
1442 case OMF_dealloc:
1443 ReceiverEff = Dealloc;
1444 break;
1445 case OMF_self:
1446 // -self is handled specially by the ExprEngine to propagate the receiver.
1447 break;
1448 case OMF_retainCount:
1449 case OMF_finalize:
1450 // These methods don't return objects.
1451 break;
1452 }
Mike Stump1eb44332009-09-09 15:08:12 +00001453
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001454 // If one of the arguments in the selector has the keyword 'delegate' we
1455 // should stop tracking the reference count for the receiver. This is
1456 // because the reference count is quite possibly handled by a delegate
1457 // method.
1458 if (S.isKeywordSelector()) {
Jordan Rose50571a92012-06-15 18:19:52 +00001459 for (unsigned i = 0, e = S.getNumArgs(); i != e; ++i) {
1460 StringRef Slot = S.getNameForSlot(i);
1461 if (Slot.substr(Slot.size() - 8).equals_lower("delegate")) {
1462 if (ResultEff == ObjCInitRetE)
Anna Zaks554067f2012-08-29 23:23:43 +00001463 ResultEff = RetEffect::MakeNoRetHard();
Jordan Rose50571a92012-06-15 18:19:52 +00001464 else
Anna Zaks554067f2012-08-29 23:23:43 +00001465 ReceiverEff = StopTrackingHard;
Jordan Rose50571a92012-06-15 18:19:52 +00001466 }
1467 }
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001468 }
Mike Stump1eb44332009-09-09 15:08:12 +00001469
Jordy Rosee921b1a2012-03-17 19:53:04 +00001470 if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing &&
1471 ResultEff.getKind() == RetEffect::NoRet)
Ted Kremenek93edbc52011-10-05 23:54:29 +00001472 return getDefaultSummary();
Mike Stump1eb44332009-09-09 15:08:12 +00001473
Jordy Rosee921b1a2012-03-17 19:53:04 +00001474 return getPersistentSummary(ResultEff, ReceiverEff, MayEscape);
Ted Kremenek250b1fa2009-04-23 23:08:22 +00001475}
1476
Ted Kremenek93edbc52011-10-05 23:54:29 +00001477const RetainSummary *
Jordan Rosecde8cdb2012-07-02 19:27:56 +00001478RetainSummaryManager::getInstanceMethodSummary(const ObjCMethodCall &Msg,
Jordan Rose4531b7d2012-07-02 19:27:43 +00001479 ProgramStateRef State) {
1480 const ObjCInterfaceDecl *ReceiverClass = 0;
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001481
Jordan Rose4531b7d2012-07-02 19:27:43 +00001482 // We do better tracking of the type of the object than the core ExprEngine.
1483 // See if we have its type in our private state.
1484 // FIXME: Eventually replace the use of state->get<RefBindings> with
1485 // a generic API for reasoning about the Objective-C types of symbolic
1486 // objects.
1487 SVal ReceiverV = Msg.getReceiverSVal();
1488 if (SymbolRef Sym = ReceiverV.getAsLocSymbol())
Anna Zaks8d6b43c2012-08-14 00:36:15 +00001489 if (const RefVal *T = getRefBinding(State, Sym))
Douglas Gregor04badcf2010-04-21 00:45:42 +00001490 if (const ObjCObjectPointerType *PT =
Jordan Rose4531b7d2012-07-02 19:27:43 +00001491 T->getType()->getAs<ObjCObjectPointerType>())
1492 ReceiverClass = PT->getInterfaceDecl();
1493
1494 // If we don't know what kind of object this is, fall back to its static type.
1495 if (!ReceiverClass)
1496 ReceiverClass = Msg.getReceiverInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00001497
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001498 // FIXME: The receiver could be a reference to a class, meaning that
1499 // we should use the class method.
Jordan Rose4531b7d2012-07-02 19:27:43 +00001500 // id x = [NSObject class];
1501 // [x performSelector:... withObject:... afterDelay:...];
1502 Selector S = Msg.getSelector();
1503 const ObjCMethodDecl *Method = Msg.getDecl();
1504 if (!Method && ReceiverClass)
1505 Method = ReceiverClass->getInstanceMethod(S);
1506
1507 return getMethodSummary(S, ReceiverClass, Method, Msg.getResultType(),
1508 ObjCMethodSummaries);
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001509}
1510
Ted Kremenek93edbc52011-10-05 23:54:29 +00001511const RetainSummary *
Jordan Rose4531b7d2012-07-02 19:27:43 +00001512RetainSummaryManager::getMethodSummary(Selector S, const ObjCInterfaceDecl *ID,
Jordy Rosef3aae582012-03-17 21:13:07 +00001513 const ObjCMethodDecl *MD, QualType RetTy,
1514 ObjCMethodSummariesTy &CachedSummaries) {
Ted Kremenek1bffd742008-05-06 15:44:25 +00001515
Ted Kremenek8711c032009-04-29 05:04:30 +00001516 // Look up a summary in our summary cache.
Jordan Rose4531b7d2012-07-02 19:27:43 +00001517 const RetainSummary *Summ = CachedSummaries.find(ID, S);
Mike Stump1eb44332009-09-09 15:08:12 +00001518
Ted Kremenek614cc542009-07-21 23:27:57 +00001519 if (!Summ) {
Jordy Rosef3aae582012-03-17 21:13:07 +00001520 Summ = getStandardMethodSummary(MD, S, RetTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001521
Ted Kremenek614cc542009-07-21 23:27:57 +00001522 // Annotations override defaults.
Jordy Rose4df54fe2011-08-23 04:27:15 +00001523 updateSummaryFromAnnotations(Summ, MD);
Mike Stump1eb44332009-09-09 15:08:12 +00001524
Ted Kremenek614cc542009-07-21 23:27:57 +00001525 // Memoize the summary.
Jordan Rose4531b7d2012-07-02 19:27:43 +00001526 CachedSummaries[ObjCSummaryKey(ID, S)] = Summ;
Ted Kremenek614cc542009-07-21 23:27:57 +00001527 }
Mike Stump1eb44332009-09-09 15:08:12 +00001528
Ted Kremeneke87450e2009-04-23 19:11:35 +00001529 return Summ;
Ted Kremenekc8395602008-05-06 21:26:51 +00001530}
1531
Mike Stump1eb44332009-09-09 15:08:12 +00001532void RetainSummaryManager::InitializeClassMethodSummaries() {
Ted Kremenekec315332009-05-07 23:40:42 +00001533 assert(ScratchArgs.isEmpty());
Mike Stump1eb44332009-09-09 15:08:12 +00001534 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek6fe2b7a2009-10-15 22:25:12 +00001535 addClassMethSummary("NSAssertionHandler", "currentHandler",
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001536 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Mike Stump1eb44332009-09-09 15:08:12 +00001537
Ted Kremenek6d348932008-10-21 15:53:15 +00001538 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001539 ScratchArgs = AF.add(ScratchArgs, 0, Autorelease);
Ted Kremenek6fe2b7a2009-10-15 22:25:12 +00001540 addClassMethSummary("NSAutoreleasePool", "addObject",
1541 getPersistentSummary(RetEffect::MakeNoRet(),
1542 DoNothing, Autorelease));
Ted Kremenek9c32d082008-05-06 00:30:21 +00001543}
1544
Ted Kremenek1f180c32008-06-23 22:21:20 +00001545void RetainSummaryManager::InitializeMethodSummaries() {
Mike Stump1eb44332009-09-09 15:08:12 +00001546
1547 assert (ScratchArgs.isEmpty());
1548
Ted Kremenekc8395602008-05-06 21:26:51 +00001549 // Create the "init" selector. It just acts as a pass-through for the
1550 // receiver.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001551 const RetainSummary *InitSumm = getPersistentSummary(ObjCInitRetE, DecRefMsg);
Ted Kremenekac02f202009-08-20 05:13:36 +00001552 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
1553
1554 // awakeAfterUsingCoder: behaves basically like an 'init' method. It
1555 // claims the receiver and returns a retained object.
1556 addNSObjectMethSummary(GetUnarySelector("awakeAfterUsingCoder", Ctx),
1557 InitSumm);
Mike Stump1eb44332009-09-09 15:08:12 +00001558
Ted Kremenekc8395602008-05-06 21:26:51 +00001559 // The next methods are allocators.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001560 const RetainSummary *AllocSumm = getPersistentSummary(ObjCAllocRetE);
1561 const RetainSummary *CFAllocSumm =
Ted Kremeneka834fb42009-08-28 19:52:12 +00001562 getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Mike Stump1eb44332009-09-09 15:08:12 +00001563
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001564 // Create the "retain" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001565 RetEffect NoRet = RetEffect::MakeNoRet();
Ted Kremenek93edbc52011-10-05 23:54:29 +00001566 const RetainSummary *Summ = getPersistentSummary(NoRet, IncRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001567 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001568
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001569 // Create the "release" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001570 Summ = getPersistentSummary(NoRet, DecRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001571 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001572
Ted Kremenek299e8152008-05-07 21:17:39 +00001573 // Create the "drain" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001574 Summ = getPersistentSummary(NoRet, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek553cf182008-06-25 21:21:56 +00001575 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001576
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001577 // Create the -dealloc summary.
Jordy Rose500abad2011-08-21 19:41:36 +00001578 Summ = getPersistentSummary(NoRet, Dealloc);
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001579 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001580
1581 // Create the "autorelease" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001582 Summ = getPersistentSummary(NoRet, Autorelease);
Ted Kremenek553cf182008-06-25 21:21:56 +00001583 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001584
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00001585 // Specially handle NSAutoreleasePool.
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001586 addInstMethSummary("NSAutoreleasePool", "init",
Jordy Rose500abad2011-08-21 19:41:36 +00001587 getPersistentSummary(NoRet, NewAutoreleasePool));
Mike Stump1eb44332009-09-09 15:08:12 +00001588
1589 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremenek89e202d2009-02-23 02:51:29 +00001590 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1591 // self-own themselves. However, they only do this once they are displayed.
1592 // Thus, we need to track an NSWindow's display status.
1593 // This is tracked in <rdar://problem/6062711>.
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +00001594 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001595 const RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenek78a35a32009-05-12 20:06:54 +00001596 StopTracking,
1597 StopTracking);
Mike Stump1eb44332009-09-09 15:08:12 +00001598
Ted Kremenek99d02692009-04-03 19:02:51 +00001599 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1600
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001601 // For NSPanel (which subclasses NSWindow), allocated objects are not
1602 // self-owned.
Ted Kremenek99d02692009-04-03 19:02:51 +00001603 // FIXME: For now we don't track NSPanels. object for the same reason
1604 // as for NSWindow objects.
1605 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
Mike Stump1eb44332009-09-09 15:08:12 +00001606
Ted Kremenekba67f6a2009-05-18 23:14:34 +00001607 // Don't track allocated autorelease pools yet, as it is okay to prematurely
1608 // exit a method.
1609 addClassMethSummary("NSAutoreleasePool", "alloc", NoTrackYet);
Ted Kremeneka9797122012-02-18 21:37:48 +00001610 addClassMethSummary("NSAutoreleasePool", "allocWithZone", NoTrackYet, false);
Ted Kremenek553cf182008-06-25 21:21:56 +00001611
Ted Kremenek767d6492009-05-20 22:39:57 +00001612 // Create summaries QCRenderer/QCView -createSnapShotImageOfType:
1613 addInstMethSummary("QCRenderer", AllocSumm,
1614 "createSnapshotImageOfType", NULL);
1615 addInstMethSummary("QCView", AllocSumm,
1616 "createSnapshotImageOfType", NULL);
1617
Ted Kremenek211a9c62009-06-15 20:58:58 +00001618 // Create summaries for CIContext, 'createCGImage' and
Ted Kremeneka834fb42009-08-28 19:52:12 +00001619 // 'createCGLayerWithSize'. These objects are CF objects, and are not
1620 // automatically garbage collected.
1621 addInstMethSummary("CIContext", CFAllocSumm,
Ted Kremenek767d6492009-05-20 22:39:57 +00001622 "createCGImage", "fromRect", NULL);
Ted Kremeneka834fb42009-08-28 19:52:12 +00001623 addInstMethSummary("CIContext", CFAllocSumm,
Mike Stump1eb44332009-09-09 15:08:12 +00001624 "createCGImage", "fromRect", "format", "colorSpace", NULL);
Ted Kremeneka834fb42009-08-28 19:52:12 +00001625 addInstMethSummary("CIContext", CFAllocSumm, "createCGLayerWithSize",
Ted Kremenek211a9c62009-06-15 20:58:58 +00001626 "info", NULL);
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001627}
1628
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001629//===----------------------------------------------------------------------===//
Ted Kremenekc887d132009-04-29 18:50:19 +00001630// Error reporting.
1631//===----------------------------------------------------------------------===//
Ted Kremenekc887d132009-04-29 18:50:19 +00001632namespace {
Jordy Roseec9ef852011-08-23 20:55:48 +00001633 typedef llvm::DenseMap<const ExplodedNode *, const RetainSummary *>
1634 SummaryLogTy;
1635
Ted Kremenekc887d132009-04-29 18:50:19 +00001636 //===-------------===//
1637 // Bug Descriptions. //
Mike Stump1eb44332009-09-09 15:08:12 +00001638 //===-------------===//
1639
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001640 class CFRefBug : public BugType {
Ted Kremenekc887d132009-04-29 18:50:19 +00001641 protected:
Jordy Rose35c86952011-08-24 05:47:39 +00001642 CFRefBug(StringRef name)
Ted Kremenek6fd45052012-04-05 20:43:28 +00001643 : BugType(name, categories::MemoryCoreFoundationObjectiveC) {}
Ted Kremenekc887d132009-04-29 18:50:19 +00001644 public:
Mike Stump1eb44332009-09-09 15:08:12 +00001645
Ted Kremenekc887d132009-04-29 18:50:19 +00001646 // FIXME: Eventually remove.
Jordy Rose35c86952011-08-24 05:47:39 +00001647 virtual const char *getDescription() const = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001648
Ted Kremenekc887d132009-04-29 18:50:19 +00001649 virtual bool isLeak() const { return false; }
1650 };
Mike Stump1eb44332009-09-09 15:08:12 +00001651
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001652 class UseAfterRelease : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001653 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001654 UseAfterRelease() : CFRefBug("Use-after-release") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001655
Jordy Rose35c86952011-08-24 05:47:39 +00001656 const char *getDescription() const {
Ted Kremenekc887d132009-04-29 18:50:19 +00001657 return "Reference-counted object is used after it is released";
Mike Stump1eb44332009-09-09 15:08:12 +00001658 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001659 };
Mike Stump1eb44332009-09-09 15:08:12 +00001660
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001661 class BadRelease : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001662 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001663 BadRelease() : CFRefBug("Bad release") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001664
Jordy Rose35c86952011-08-24 05:47:39 +00001665 const char *getDescription() const {
Ted Kremenekbb206fd2009-10-01 17:31:50 +00001666 return "Incorrect decrement of the reference count of an object that is "
1667 "not owned at this point by the caller";
Ted Kremenekc887d132009-04-29 18:50:19 +00001668 }
1669 };
Mike Stump1eb44332009-09-09 15:08:12 +00001670
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001671 class DeallocGC : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001672 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001673 DeallocGC()
1674 : CFRefBug("-dealloc called while using garbage collection") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001675
Ted Kremenekc887d132009-04-29 18:50:19 +00001676 const char *getDescription() const {
Ted Kremenek369de562009-05-09 00:10:05 +00001677 return "-dealloc called while using garbage collection";
Ted Kremenekc887d132009-04-29 18:50:19 +00001678 }
1679 };
Mike Stump1eb44332009-09-09 15:08:12 +00001680
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001681 class DeallocNotOwned : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001682 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001683 DeallocNotOwned()
1684 : CFRefBug("-dealloc sent to non-exclusively owned object") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001685
Ted Kremenekc887d132009-04-29 18:50:19 +00001686 const char *getDescription() const {
1687 return "-dealloc sent to object that may be referenced elsewhere";
1688 }
Mike Stump1eb44332009-09-09 15:08:12 +00001689 };
1690
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001691 class OverAutorelease : public CFRefBug {
Ted Kremenek369de562009-05-09 00:10:05 +00001692 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001693 OverAutorelease()
1694 : CFRefBug("Object sent -autorelease too many times") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001695
Ted Kremenek369de562009-05-09 00:10:05 +00001696 const char *getDescription() const {
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001697 return "Object sent -autorelease too many times";
Ted Kremenek369de562009-05-09 00:10:05 +00001698 }
1699 };
Mike Stump1eb44332009-09-09 15:08:12 +00001700
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001701 class ReturnedNotOwnedForOwned : public CFRefBug {
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001702 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001703 ReturnedNotOwnedForOwned()
1704 : CFRefBug("Method should return an owned object") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001705
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001706 const char *getDescription() const {
Jordy Rose5b5402b2011-07-15 22:17:54 +00001707 return "Object with a +0 retain count returned to caller where a +1 "
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001708 "(owning) retain count is expected";
1709 }
1710 };
Mike Stump1eb44332009-09-09 15:08:12 +00001711
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001712 class Leak : public CFRefBug {
Benjamin Kramerfacde172012-06-06 17:32:50 +00001713 public:
1714 Leak(StringRef name)
1715 : CFRefBug(name) {
Jordy Rosedb92bb62011-08-25 01:14:38 +00001716 // Leaks should not be reported if they are post-dominated by a sink.
1717 setSuppressOnSink(true);
1718 }
Mike Stump1eb44332009-09-09 15:08:12 +00001719
Jordy Rose35c86952011-08-24 05:47:39 +00001720 const char *getDescription() const { return ""; }
Mike Stump1eb44332009-09-09 15:08:12 +00001721
Ted Kremenekc887d132009-04-29 18:50:19 +00001722 bool isLeak() const { return true; }
1723 };
Mike Stump1eb44332009-09-09 15:08:12 +00001724
Ted Kremenekc887d132009-04-29 18:50:19 +00001725 //===---------===//
1726 // Bug Reports. //
1727 //===---------===//
Mike Stump1eb44332009-09-09 15:08:12 +00001728
Jordy Rose01153492012-03-24 02:45:35 +00001729 class CFRefReportVisitor : public BugReporterVisitorImpl<CFRefReportVisitor> {
Anna Zaks23f395e2011-08-20 01:27:22 +00001730 protected:
Anna Zaksdc757b02011-08-19 23:21:56 +00001731 SymbolRef Sym;
Jordy Roseec9ef852011-08-23 20:55:48 +00001732 const SummaryLogTy &SummaryLog;
Jordy Rose35c86952011-08-24 05:47:39 +00001733 bool GCEnabled;
Anna Zaks23f395e2011-08-20 01:27:22 +00001734
Anna Zaksdc757b02011-08-19 23:21:56 +00001735 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001736 CFRefReportVisitor(SymbolRef sym, bool gcEnabled, const SummaryLogTy &log)
1737 : Sym(sym), SummaryLog(log), GCEnabled(gcEnabled) {}
Anna Zaksdc757b02011-08-19 23:21:56 +00001738
Anna Zaks23f395e2011-08-20 01:27:22 +00001739 virtual void Profile(llvm::FoldingSetNodeID &ID) const {
Anna Zaksdc757b02011-08-19 23:21:56 +00001740 static int x = 0;
1741 ID.AddPointer(&x);
1742 ID.AddPointer(Sym);
1743 }
1744
Anna Zaks23f395e2011-08-20 01:27:22 +00001745 virtual PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
1746 const ExplodedNode *PrevN,
1747 BugReporterContext &BRC,
1748 BugReport &BR);
1749
1750 virtual PathDiagnosticPiece *getEndPath(BugReporterContext &BRC,
1751 const ExplodedNode *N,
1752 BugReport &BR);
1753 };
1754
1755 class CFRefLeakReportVisitor : public CFRefReportVisitor {
1756 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001757 CFRefLeakReportVisitor(SymbolRef sym, bool GCEnabled,
Jordy Roseec9ef852011-08-23 20:55:48 +00001758 const SummaryLogTy &log)
Jordy Rose35c86952011-08-24 05:47:39 +00001759 : CFRefReportVisitor(sym, GCEnabled, log) {}
Anna Zaks23f395e2011-08-20 01:27:22 +00001760
1761 PathDiagnosticPiece *getEndPath(BugReporterContext &BRC,
1762 const ExplodedNode *N,
1763 BugReport &BR);
Jordy Rose01153492012-03-24 02:45:35 +00001764
1765 virtual BugReporterVisitor *clone() const {
1766 // The curiously-recurring template pattern only works for one level of
1767 // subclassing. Rather than make a new template base for
1768 // CFRefReportVisitor, we simply override clone() to do the right thing.
1769 // This could be trouble someday if BugReporterVisitorImpl is ever
1770 // used for something else besides a convenient implementation of clone().
1771 return new CFRefLeakReportVisitor(*this);
1772 }
Anna Zaksdc757b02011-08-19 23:21:56 +00001773 };
1774
Anna Zakse172e8b2011-08-17 23:00:25 +00001775 class CFRefReport : public BugReport {
Jordy Rose20589562011-08-24 22:39:09 +00001776 void addGCModeDescription(const LangOptions &LOpts, bool GCEnabled);
Jordy Rose35c86952011-08-24 05:47:39 +00001777
Ted Kremenekc887d132009-04-29 18:50:19 +00001778 public:
Jordy Rose20589562011-08-24 22:39:09 +00001779 CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1780 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1781 bool registerVisitor = true)
Anna Zaksedf4dae2011-08-22 18:54:07 +00001782 : BugReport(D, D.getDescription(), n) {
Anna Zaks23f395e2011-08-20 01:27:22 +00001783 if (registerVisitor)
Jordy Rose20589562011-08-24 22:39:09 +00001784 addVisitor(new CFRefReportVisitor(sym, GCEnabled, Log));
1785 addGCModeDescription(LOpts, GCEnabled);
Anna Zaksdc757b02011-08-19 23:21:56 +00001786 }
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001787
Jordy Rose20589562011-08-24 22:39:09 +00001788 CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1789 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1790 StringRef endText)
Anna Zaksedf4dae2011-08-22 18:54:07 +00001791 : BugReport(D, D.getDescription(), endText, n) {
Jordy Rose20589562011-08-24 22:39:09 +00001792 addVisitor(new CFRefReportVisitor(sym, GCEnabled, Log));
1793 addGCModeDescription(LOpts, GCEnabled);
Anna Zaksdc757b02011-08-19 23:21:56 +00001794 }
Mike Stump1eb44332009-09-09 15:08:12 +00001795
Anna Zakse172e8b2011-08-17 23:00:25 +00001796 virtual std::pair<ranges_iterator, ranges_iterator> getRanges() {
Anna Zaksedf4dae2011-08-22 18:54:07 +00001797 const CFRefBug& BugTy = static_cast<CFRefBug&>(getBugType());
1798 if (!BugTy.isLeak())
Anna Zakse172e8b2011-08-17 23:00:25 +00001799 return BugReport::getRanges();
Ted Kremenekc887d132009-04-29 18:50:19 +00001800 else
Argyrios Kyrtzidis640ccf02010-12-04 01:12:15 +00001801 return std::make_pair(ranges_iterator(), ranges_iterator());
Ted Kremenekc887d132009-04-29 18:50:19 +00001802 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001803 };
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001804
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001805 class CFRefLeakReport : public CFRefReport {
Ted Kremenekc887d132009-04-29 18:50:19 +00001806 const MemRegion* AllocBinding;
Anna Zaks23f395e2011-08-20 01:27:22 +00001807
Ted Kremenekc887d132009-04-29 18:50:19 +00001808 public:
Jordy Rose20589562011-08-24 22:39:09 +00001809 CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1810 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
Anna Zaks6a93bd52011-10-25 19:57:11 +00001811 CheckerContext &Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001812
Anna Zaks590dd8e2011-09-20 21:38:35 +00001813 PathDiagnosticLocation getLocation(const SourceManager &SM) const {
1814 assert(Location.isValid());
1815 return Location;
1816 }
Mike Stump1eb44332009-09-09 15:08:12 +00001817 };
Ted Kremenekc887d132009-04-29 18:50:19 +00001818} // end anonymous namespace
1819
Jordy Rose20589562011-08-24 22:39:09 +00001820void CFRefReport::addGCModeDescription(const LangOptions &LOpts,
1821 bool GCEnabled) {
Jordy Rosef95b19d2011-08-24 20:38:42 +00001822 const char *GCModeDescription = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001823
Douglas Gregore289d812011-09-13 17:21:33 +00001824 switch (LOpts.getGC()) {
Anna Zaks7f2531c2011-08-22 20:31:28 +00001825 case LangOptions::GCOnly:
Jordy Rose20589562011-08-24 22:39:09 +00001826 assert(GCEnabled);
Jordy Rose35c86952011-08-24 05:47:39 +00001827 GCModeDescription = "Code is compiled to only use garbage collection";
1828 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001829
Anna Zaks7f2531c2011-08-22 20:31:28 +00001830 case LangOptions::NonGC:
Jordy Rose20589562011-08-24 22:39:09 +00001831 assert(!GCEnabled);
Jordy Rose35c86952011-08-24 05:47:39 +00001832 GCModeDescription = "Code is compiled to use reference counts";
1833 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001834
Anna Zaks7f2531c2011-08-22 20:31:28 +00001835 case LangOptions::HybridGC:
Jordy Rose20589562011-08-24 22:39:09 +00001836 if (GCEnabled) {
Jordy Rose35c86952011-08-24 05:47:39 +00001837 GCModeDescription = "Code is compiled to use either garbage collection "
1838 "(GC) or reference counts (non-GC). The bug occurs "
1839 "with GC enabled";
1840 break;
1841 } else {
1842 GCModeDescription = "Code is compiled to use either garbage collection "
1843 "(GC) or reference counts (non-GC). The bug occurs "
1844 "in non-GC mode";
1845 break;
Anna Zaks7f2531c2011-08-22 20:31:28 +00001846 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001847 }
Jordy Rose35c86952011-08-24 05:47:39 +00001848
Jordy Rosef95b19d2011-08-24 20:38:42 +00001849 assert(GCModeDescription && "invalid/unknown GC mode");
Jordy Rose35c86952011-08-24 05:47:39 +00001850 addExtraText(GCModeDescription);
Ted Kremenekc887d132009-04-29 18:50:19 +00001851}
1852
Jordy Rose910c4052011-09-02 06:44:22 +00001853// FIXME: This should be a method on SmallVector.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001854static inline bool contains(const SmallVectorImpl<ArgEffect>& V,
Ted Kremenekc887d132009-04-29 18:50:19 +00001855 ArgEffect X) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001856 for (SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
Ted Kremenekc887d132009-04-29 18:50:19 +00001857 I!=E; ++I)
1858 if (*I == X) return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001859
Ted Kremenekc887d132009-04-29 18:50:19 +00001860 return false;
1861}
1862
Jordy Rose70fdbc32012-05-12 05:10:43 +00001863static bool isNumericLiteralExpression(const Expr *E) {
1864 // FIXME: This set of cases was copied from SemaExprObjC.
1865 return isa<IntegerLiteral>(E) ||
1866 isa<CharacterLiteral>(E) ||
1867 isa<FloatingLiteral>(E) ||
1868 isa<ObjCBoolLiteralExpr>(E) ||
1869 isa<CXXBoolLiteralExpr>(E);
1870}
1871
Anna Zaksdc757b02011-08-19 23:21:56 +00001872PathDiagnosticPiece *CFRefReportVisitor::VisitNode(const ExplodedNode *N,
1873 const ExplodedNode *PrevN,
1874 BugReporterContext &BRC,
1875 BugReport &BR) {
Jordan Rose28038f32012-07-10 22:07:42 +00001876 // FIXME: We will eventually need to handle non-statement-based events
1877 // (__attribute__((cleanup))).
Jordy Rosef53e8c72011-08-23 19:43:16 +00001878 if (!isa<StmtPoint>(N->getLocation()))
Ted Kremenek2033a952009-05-13 07:12:33 +00001879 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001880
Ted Kremenek8966bc12009-05-06 21:39:49 +00001881 // Check if the type state has changed.
Ted Kremenek8bef8232012-01-26 21:29:00 +00001882 ProgramStateRef PrevSt = PrevN->getState();
1883 ProgramStateRef CurrSt = N->getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001884 const LocationContext *LCtx = N->getLocationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00001885
Anna Zaks8d6b43c2012-08-14 00:36:15 +00001886 const RefVal* CurrT = getRefBinding(CurrSt, Sym);
Ted Kremenekc887d132009-04-29 18:50:19 +00001887 if (!CurrT) return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001888
Ted Kremenekb65be702009-06-18 01:23:53 +00001889 const RefVal &CurrV = *CurrT;
Anna Zaks8d6b43c2012-08-14 00:36:15 +00001890 const RefVal *PrevT = getRefBinding(PrevSt, Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00001891
Ted Kremenekc887d132009-04-29 18:50:19 +00001892 // Create a string buffer to constain all the useful things we want
1893 // to tell the user.
1894 std::string sbuf;
1895 llvm::raw_string_ostream os(sbuf);
Mike Stump1eb44332009-09-09 15:08:12 +00001896
Ted Kremenekc887d132009-04-29 18:50:19 +00001897 // This is the allocation site since the previous node had no bindings
1898 // for this symbol.
1899 if (!PrevT) {
Jordy Rosef53e8c72011-08-23 19:43:16 +00001900 const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
Mike Stump1eb44332009-09-09 15:08:12 +00001901
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001902 if (isa<ObjCArrayLiteral>(S)) {
1903 os << "NSArray literal is an object with a +0 retain count";
Mike Stump1eb44332009-09-09 15:08:12 +00001904 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001905 else if (isa<ObjCDictionaryLiteral>(S)) {
1906 os << "NSDictionary literal is an object with a +0 retain count";
Ted Kremenekc887d132009-04-29 18:50:19 +00001907 }
Jordy Rose70fdbc32012-05-12 05:10:43 +00001908 else if (const ObjCBoxedExpr *BL = dyn_cast<ObjCBoxedExpr>(S)) {
1909 if (isNumericLiteralExpression(BL->getSubExpr()))
1910 os << "NSNumber literal is an object with a +0 retain count";
1911 else {
1912 const ObjCInterfaceDecl *BoxClass = 0;
1913 if (const ObjCMethodDecl *Method = BL->getBoxingMethod())
1914 BoxClass = Method->getClassInterface();
1915
1916 // We should always be able to find the boxing class interface,
1917 // but consider this future-proofing.
1918 if (BoxClass)
1919 os << *BoxClass << " b";
1920 else
1921 os << "B";
1922
1923 os << "oxed expression produces an object with a +0 retain count";
1924 }
1925 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001926 else {
1927 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
1928 // Get the name of the callee (if it is available).
1929 SVal X = CurrSt->getSValAsScalarOrLoc(CE->getCallee(), LCtx);
1930 if (const FunctionDecl *FD = X.getAsFunctionDecl())
1931 os << "Call to function '" << *FD << '\'';
1932 else
1933 os << "function call";
Ted Kremenekc887d132009-04-29 18:50:19 +00001934 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001935 else {
Jordan Rose8919e682012-07-18 21:59:51 +00001936 assert(isa<ObjCMessageExpr>(S));
Jordan Rosed563d3f2012-07-30 20:22:09 +00001937 CallEventManager &Mgr = CurrSt->getStateManager().getCallEventManager();
1938 CallEventRef<ObjCMethodCall> Call
1939 = Mgr.getObjCMethodCall(cast<ObjCMessageExpr>(S), CurrSt, LCtx);
1940
1941 switch (Call->getMessageKind()) {
Jordan Rose8919e682012-07-18 21:59:51 +00001942 case OCM_Message:
1943 os << "Method";
1944 break;
1945 case OCM_PropertyAccess:
1946 os << "Property";
1947 break;
1948 case OCM_Subscript:
1949 os << "Subscript";
1950 break;
1951 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001952 }
1953
1954 if (CurrV.getObjKind() == RetEffect::CF) {
1955 os << " returns a Core Foundation object with a ";
1956 }
1957 else {
1958 assert (CurrV.getObjKind() == RetEffect::ObjC);
1959 os << " returns an Objective-C object with a ";
1960 }
1961
1962 if (CurrV.isOwned()) {
1963 os << "+1 retain count";
1964
1965 if (GCEnabled) {
1966 assert(CurrV.getObjKind() == RetEffect::CF);
1967 os << ". "
1968 "Core Foundation objects are not automatically garbage collected.";
1969 }
1970 }
1971 else {
1972 assert (CurrV.isNotOwned());
1973 os << "+0 retain count";
1974 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001975 }
Mike Stump1eb44332009-09-09 15:08:12 +00001976
Anna Zaks220ac8c2011-09-15 01:08:34 +00001977 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
1978 N->getLocationContext());
Ted Kremenekc887d132009-04-29 18:50:19 +00001979 return new PathDiagnosticEventPiece(Pos, os.str());
1980 }
Mike Stump1eb44332009-09-09 15:08:12 +00001981
Ted Kremenekc887d132009-04-29 18:50:19 +00001982 // Gather up the effects that were performed on the object at this
1983 // program point
Chris Lattner5f9e2722011-07-23 10:55:15 +00001984 SmallVector<ArgEffect, 2> AEffects;
Mike Stump1eb44332009-09-09 15:08:12 +00001985
Jordy Roseec9ef852011-08-23 20:55:48 +00001986 const ExplodedNode *OrigNode = BRC.getNodeResolver().getOriginalNode(N);
1987 if (const RetainSummary *Summ = SummaryLog.lookup(OrigNode)) {
Ted Kremenekc887d132009-04-29 18:50:19 +00001988 // We only have summaries attached to nodes after evaluating CallExpr and
1989 // ObjCMessageExprs.
Jordy Rosef53e8c72011-08-23 19:43:16 +00001990 const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
Mike Stump1eb44332009-09-09 15:08:12 +00001991
Ted Kremenek5f85e172009-07-22 22:35:28 +00001992 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
Ted Kremenekc887d132009-04-29 18:50:19 +00001993 // Iterate through the parameter expressions and see if the symbol
1994 // was ever passed as an argument.
1995 unsigned i = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001996
Ted Kremenek5f85e172009-07-22 22:35:28 +00001997 for (CallExpr::const_arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
Ted Kremenekc887d132009-04-29 18:50:19 +00001998 AI!=AE; ++AI, ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00001999
Ted Kremenekc887d132009-04-29 18:50:19 +00002000 // Retrieve the value of the argument. Is it the symbol
2001 // we are interested in?
Ted Kremenek5eca4822012-01-06 22:09:28 +00002002 if (CurrSt->getSValAsScalarOrLoc(*AI, LCtx).getAsLocSymbol() != Sym)
Ted Kremenekc887d132009-04-29 18:50:19 +00002003 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00002004
Ted Kremenekc887d132009-04-29 18:50:19 +00002005 // We have an argument. Get the effect!
2006 AEffects.push_back(Summ->getArg(i));
2007 }
2008 }
Mike Stump1eb44332009-09-09 15:08:12 +00002009 else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002010 if (const Expr *receiver = ME->getInstanceReceiver())
Ted Kremenek5eca4822012-01-06 22:09:28 +00002011 if (CurrSt->getSValAsScalarOrLoc(receiver, LCtx)
2012 .getAsLocSymbol() == Sym) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002013 // The symbol we are tracking is the receiver.
2014 AEffects.push_back(Summ->getReceiverEffect());
2015 }
2016 }
2017 }
Mike Stump1eb44332009-09-09 15:08:12 +00002018
Ted Kremenekc887d132009-04-29 18:50:19 +00002019 do {
2020 // Get the previous type state.
2021 RefVal PrevV = *PrevT;
Mike Stump1eb44332009-09-09 15:08:12 +00002022
Ted Kremenekc887d132009-04-29 18:50:19 +00002023 // Specially handle -dealloc.
Jordy Rose35c86952011-08-24 05:47:39 +00002024 if (!GCEnabled && contains(AEffects, Dealloc)) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002025 // Determine if the object's reference count was pushed to zero.
2026 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2027 // We may not have transitioned to 'release' if we hit an error.
2028 // This case is handled elsewhere.
2029 if (CurrV.getKind() == RefVal::Released) {
Ted Kremenekf21332e2009-05-08 20:01:42 +00002030 assert(CurrV.getCombinedCounts() == 0);
Ted Kremenekc887d132009-04-29 18:50:19 +00002031 os << "Object released by directly sending the '-dealloc' message";
2032 break;
2033 }
2034 }
Mike Stump1eb44332009-09-09 15:08:12 +00002035
Ted Kremenekc887d132009-04-29 18:50:19 +00002036 // Specially handle CFMakeCollectable and friends.
2037 if (contains(AEffects, MakeCollectable)) {
2038 // Get the name of the function.
Jordy Rosef53e8c72011-08-23 19:43:16 +00002039 const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
Ted Kremenek5eca4822012-01-06 22:09:28 +00002040 SVal X =
2041 CurrSt->getSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee(), LCtx);
Ted Kremenek9c378f72011-08-12 23:37:29 +00002042 const FunctionDecl *FD = X.getAsFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002043
Jordy Rose35c86952011-08-24 05:47:39 +00002044 if (GCEnabled) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002045 // Determine if the object's reference count was pushed to zero.
2046 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
Mike Stump1eb44332009-09-09 15:08:12 +00002047
Benjamin Kramerb8989f22011-10-14 18:45:37 +00002048 os << "In GC mode a call to '" << *FD
Ted Kremenekc887d132009-04-29 18:50:19 +00002049 << "' decrements an object's retain count and registers the "
2050 "object with the garbage collector. ";
Mike Stump1eb44332009-09-09 15:08:12 +00002051
Ted Kremenekc887d132009-04-29 18:50:19 +00002052 if (CurrV.getKind() == RefVal::Released) {
2053 assert(CurrV.getCount() == 0);
2054 os << "Since it now has a 0 retain count the object can be "
2055 "automatically collected by the garbage collector.";
2056 }
2057 else
2058 os << "An object must have a 0 retain count to be garbage collected. "
2059 "After this call its retain count is +" << CurrV.getCount()
2060 << '.';
2061 }
Mike Stump1eb44332009-09-09 15:08:12 +00002062 else
Benjamin Kramerb8989f22011-10-14 18:45:37 +00002063 os << "When GC is not enabled a call to '" << *FD
Ted Kremenekc887d132009-04-29 18:50:19 +00002064 << "' has no effect on its argument.";
Mike Stump1eb44332009-09-09 15:08:12 +00002065
Ted Kremenekc887d132009-04-29 18:50:19 +00002066 // Nothing more to say.
2067 break;
2068 }
Mike Stump1eb44332009-09-09 15:08:12 +00002069
2070 // Determine if the typestate has changed.
Ted Kremenekc887d132009-04-29 18:50:19 +00002071 if (!(PrevV == CurrV))
2072 switch (CurrV.getKind()) {
2073 case RefVal::Owned:
2074 case RefVal::NotOwned:
Mike Stump1eb44332009-09-09 15:08:12 +00002075
Ted Kremenekf21332e2009-05-08 20:01:42 +00002076 if (PrevV.getCount() == CurrV.getCount()) {
2077 // Did an autorelease message get sent?
2078 if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
2079 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002080
Zhongxing Xu264e9372009-05-12 10:10:00 +00002081 assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount());
Ted Kremenekeaedfea2009-05-10 05:11:21 +00002082 os << "Object sent -autorelease message";
Ted Kremenekf21332e2009-05-08 20:01:42 +00002083 break;
2084 }
Mike Stump1eb44332009-09-09 15:08:12 +00002085
Ted Kremenekc887d132009-04-29 18:50:19 +00002086 if (PrevV.getCount() > CurrV.getCount())
2087 os << "Reference count decremented.";
2088 else
2089 os << "Reference count incremented.";
Mike Stump1eb44332009-09-09 15:08:12 +00002090
Ted Kremenekc887d132009-04-29 18:50:19 +00002091 if (unsigned Count = CurrV.getCount())
2092 os << " The object now has a +" << Count << " retain count.";
Mike Stump1eb44332009-09-09 15:08:12 +00002093
Ted Kremenekc887d132009-04-29 18:50:19 +00002094 if (PrevV.getKind() == RefVal::Released) {
Jordy Rose35c86952011-08-24 05:47:39 +00002095 assert(GCEnabled && CurrV.getCount() > 0);
Jordy Rose74b7b2b2012-03-17 05:49:15 +00002096 os << " The object is not eligible for garbage collection until "
2097 "the retain count reaches 0 again.";
Ted Kremenekc887d132009-04-29 18:50:19 +00002098 }
Mike Stump1eb44332009-09-09 15:08:12 +00002099
Ted Kremenekc887d132009-04-29 18:50:19 +00002100 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002101
Ted Kremenekc887d132009-04-29 18:50:19 +00002102 case RefVal::Released:
2103 os << "Object released.";
2104 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002105
Ted Kremenekc887d132009-04-29 18:50:19 +00002106 case RefVal::ReturnedOwned:
Jordy Rose74b7b2b2012-03-17 05:49:15 +00002107 // Autoreleases can be applied after marking a node ReturnedOwned.
2108 if (CurrV.getAutoreleaseCount())
2109 return NULL;
2110
2111 os << "Object returned to caller as an owning reference (single "
2112 "retain count transferred to caller)";
Ted Kremenekc887d132009-04-29 18:50:19 +00002113 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002114
Ted Kremenekc887d132009-04-29 18:50:19 +00002115 case RefVal::ReturnedNotOwned:
Ted Kremenekf1365462011-05-26 18:45:44 +00002116 os << "Object returned to caller with a +0 retain count";
Ted Kremenekc887d132009-04-29 18:50:19 +00002117 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002118
Ted Kremenekc887d132009-04-29 18:50:19 +00002119 default:
2120 return NULL;
2121 }
Mike Stump1eb44332009-09-09 15:08:12 +00002122
Ted Kremenekc887d132009-04-29 18:50:19 +00002123 // Emit any remaining diagnostics for the argument effects (if any).
Chris Lattner5f9e2722011-07-23 10:55:15 +00002124 for (SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
Ted Kremenekc887d132009-04-29 18:50:19 +00002125 E=AEffects.end(); I != E; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +00002126
Ted Kremenekc887d132009-04-29 18:50:19 +00002127 // A bunch of things have alternate behavior under GC.
Jordy Rose35c86952011-08-24 05:47:39 +00002128 if (GCEnabled)
Ted Kremenekc887d132009-04-29 18:50:19 +00002129 switch (*I) {
2130 default: break;
2131 case Autorelease:
2132 os << "In GC mode an 'autorelease' has no effect.";
2133 continue;
2134 case IncRefMsg:
2135 os << "In GC mode the 'retain' message has no effect.";
2136 continue;
2137 case DecRefMsg:
2138 os << "In GC mode the 'release' message has no effect.";
2139 continue;
2140 }
2141 }
Mike Stump1eb44332009-09-09 15:08:12 +00002142 } while (0);
2143
Ted Kremenekc887d132009-04-29 18:50:19 +00002144 if (os.str().empty())
2145 return 0; // We have nothing to say!
Ted Kremenek2033a952009-05-13 07:12:33 +00002146
Jordy Rosef53e8c72011-08-23 19:43:16 +00002147 const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
Anna Zaks220ac8c2011-09-15 01:08:34 +00002148 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
2149 N->getLocationContext());
Ted Kremenek9c378f72011-08-12 23:37:29 +00002150 PathDiagnosticPiece *P = new PathDiagnosticEventPiece(Pos, os.str());
Mike Stump1eb44332009-09-09 15:08:12 +00002151
Ted Kremenekc887d132009-04-29 18:50:19 +00002152 // Add the range by scanning the children of the statement for any bindings
2153 // to Sym.
Mike Stump1eb44332009-09-09 15:08:12 +00002154 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
Ted Kremenek5f85e172009-07-22 22:35:28 +00002155 I!=E; ++I)
Ted Kremenek9c378f72011-08-12 23:37:29 +00002156 if (const Expr *Exp = dyn_cast_or_null<Expr>(*I))
Ted Kremenek5eca4822012-01-06 22:09:28 +00002157 if (CurrSt->getSValAsScalarOrLoc(Exp, LCtx).getAsLocSymbol() == Sym) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002158 P->addRange(Exp->getSourceRange());
2159 break;
2160 }
Mike Stump1eb44332009-09-09 15:08:12 +00002161
Ted Kremenekc887d132009-04-29 18:50:19 +00002162 return P;
2163}
2164
Anna Zakse7e01682012-02-28 22:39:22 +00002165// Find the first node in the current function context that referred to the
2166// tracked symbol and the memory location that value was stored to. Note, the
2167// value is only reported if the allocation occurred in the same function as
2168// the leak.
Zhongxing Xuc5619d92009-08-06 01:32:16 +00002169static std::pair<const ExplodedNode*,const MemRegion*>
Ted Kremenek18c66fd2011-08-15 22:09:50 +00002170GetAllocationSite(ProgramStateManager& StateMgr, const ExplodedNode *N,
Ted Kremenekc887d132009-04-29 18:50:19 +00002171 SymbolRef Sym) {
Ted Kremenek9c378f72011-08-12 23:37:29 +00002172 const ExplodedNode *Last = N;
Mike Stump1eb44332009-09-09 15:08:12 +00002173 const MemRegion* FirstBinding = 0;
Anna Zakse7e01682012-02-28 22:39:22 +00002174 const LocationContext *LeakContext = N->getLocationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002175
Ted Kremenekc887d132009-04-29 18:50:19 +00002176 while (N) {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002177 ProgramStateRef St = N->getState();
Mike Stump1eb44332009-09-09 15:08:12 +00002178
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002179 if (!getRefBinding(St, Sym))
Ted Kremenekc887d132009-04-29 18:50:19 +00002180 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002181
Anna Zaks27b867e2012-03-21 19:45:01 +00002182 StoreManager::FindUniqueBinding FB(Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002183 StateMgr.iterBindings(St, FB);
2184 if (FB) FirstBinding = FB.getRegion();
2185
Anna Zakse7e01682012-02-28 22:39:22 +00002186 // Allocation node, is the last node in the current context in which the
2187 // symbol was tracked.
2188 if (N->getLocationContext() == LeakContext)
2189 Last = N;
2190
Mike Stump1eb44332009-09-09 15:08:12 +00002191 N = N->pred_empty() ? NULL : *(N->pred_begin());
Ted Kremenekc887d132009-04-29 18:50:19 +00002192 }
Mike Stump1eb44332009-09-09 15:08:12 +00002193
Anna Zakse7e01682012-02-28 22:39:22 +00002194 // If allocation happened in a function different from the leak node context,
2195 // do not report the binding.
Ted Kremenek5a8fc882012-10-12 22:56:40 +00002196 assert(N && "Could not find allocation node");
Anna Zakse7e01682012-02-28 22:39:22 +00002197 if (N->getLocationContext() != LeakContext) {
2198 FirstBinding = 0;
2199 }
2200
Ted Kremenekc887d132009-04-29 18:50:19 +00002201 return std::make_pair(Last, FirstBinding);
2202}
2203
2204PathDiagnosticPiece*
Anna Zaks23f395e2011-08-20 01:27:22 +00002205CFRefReportVisitor::getEndPath(BugReporterContext &BRC,
2206 const ExplodedNode *EndN,
2207 BugReport &BR) {
Ted Kremenek76aadc32012-03-09 01:13:14 +00002208 BR.markInteresting(Sym);
Anna Zaks23f395e2011-08-20 01:27:22 +00002209 return BugReporterVisitor::getDefaultEndPath(BRC, EndN, BR);
Ted Kremenekc887d132009-04-29 18:50:19 +00002210}
2211
2212PathDiagnosticPiece*
Anna Zaks23f395e2011-08-20 01:27:22 +00002213CFRefLeakReportVisitor::getEndPath(BugReporterContext &BRC,
2214 const ExplodedNode *EndN,
2215 BugReport &BR) {
Mike Stump1eb44332009-09-09 15:08:12 +00002216
Ted Kremenek8966bc12009-05-06 21:39:49 +00002217 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenekc887d132009-04-29 18:50:19 +00002218 // assigned to different variables, etc.
Ted Kremenek76aadc32012-03-09 01:13:14 +00002219 BR.markInteresting(Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002220
Ted Kremenekc887d132009-04-29 18:50:19 +00002221 // We are reporting a leak. Walk up the graph to get to the first node where
2222 // the symbol appeared, and also get the first VarDecl that tracked object
2223 // is stored to.
Ted Kremenek9c378f72011-08-12 23:37:29 +00002224 const ExplodedNode *AllocNode = 0;
Ted Kremenekc887d132009-04-29 18:50:19 +00002225 const MemRegion* FirstBinding = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002226
Ted Kremenekc887d132009-04-29 18:50:19 +00002227 llvm::tie(AllocNode, FirstBinding) =
Ted Kremenekf04dced2009-05-08 23:32:51 +00002228 GetAllocationSite(BRC.getStateManager(), EndN, Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002229
Anna Zaks4fdf97b2011-09-15 18:56:07 +00002230 SourceManager& SM = BRC.getSourceManager();
Mike Stump1eb44332009-09-09 15:08:12 +00002231
Ted Kremenekc887d132009-04-29 18:50:19 +00002232 // Compute an actual location for the leak. Sometimes a leak doesn't
2233 // occur at an actual statement (e.g., transition between blocks; end
2234 // of function) so we need to walk the graph and compute a real location.
Ted Kremenek9c378f72011-08-12 23:37:29 +00002235 const ExplodedNode *LeakN = EndN;
Anna Zaks4fdf97b2011-09-15 18:56:07 +00002236 PathDiagnosticLocation L = PathDiagnosticLocation::createEndOfPath(LeakN, SM);
Mike Stump1eb44332009-09-09 15:08:12 +00002237
Ted Kremenekc887d132009-04-29 18:50:19 +00002238 std::string sbuf;
2239 llvm::raw_string_ostream os(sbuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002240
Ted Kremenekf1365462011-05-26 18:45:44 +00002241 os << "Object leaked: ";
Mike Stump1eb44332009-09-09 15:08:12 +00002242
Ted Kremenekf1365462011-05-26 18:45:44 +00002243 if (FirstBinding) {
2244 os << "object allocated and stored into '"
2245 << FirstBinding->getString() << '\'';
2246 }
2247 else
2248 os << "allocated object";
Mike Stump1eb44332009-09-09 15:08:12 +00002249
Ted Kremenekc887d132009-04-29 18:50:19 +00002250 // Get the retain count.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002251 const RefVal* RV = getRefBinding(EndN->getState(), Sym);
Ted Kremenek5a8fc882012-10-12 22:56:40 +00002252 assert(RV);
Mike Stump1eb44332009-09-09 15:08:12 +00002253
Ted Kremenekc887d132009-04-29 18:50:19 +00002254 if (RV->getKind() == RefVal::ErrorLeakReturned) {
2255 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
Jordy Rose5b5402b2011-07-15 22:17:54 +00002256 // objects. Only "copy", "alloc", "retain" and "new" transfer ownership
Ted Kremenekc887d132009-04-29 18:50:19 +00002257 // to the caller for NS objects.
Ted Kremenekd368d712011-05-25 06:19:45 +00002258 const Decl *D = &EndN->getCodeDecl();
Ted Kremenekec9f36e2012-09-06 23:03:07 +00002259
2260 os << (isa<ObjCMethodDecl>(D) ? " is returned from a method "
2261 : " is returned from a function ");
2262
2263 if (D->getAttr<CFReturnsNotRetainedAttr>())
2264 os << "that is annotated as CF_RETURNS_NOT_RETAINED";
2265 else if (D->getAttr<NSReturnsNotRetainedAttr>())
2266 os << "that is annotated as NS_RETURNS_NOT_RETAINED";
Ted Kremenekd368d712011-05-25 06:19:45 +00002267 else {
Ted Kremenekec9f36e2012-09-06 23:03:07 +00002268 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2269 os << "whose name ('" << MD->getSelector().getAsString()
2270 << "') does not start with 'copy', 'mutableCopy', 'alloc' or 'new'."
2271 " This violates the naming convention rules"
2272 " given in the Memory Management Guide for Cocoa";
2273 }
2274 else {
2275 const FunctionDecl *FD = cast<FunctionDecl>(D);
2276 os << "whose name ('" << *FD
2277 << "') does not contain 'Copy' or 'Create'. This violates the naming"
2278 " convention rules given in the Memory Management Guide for Core"
2279 " Foundation";
2280 }
2281 }
Ted Kremenekc887d132009-04-29 18:50:19 +00002282 }
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002283 else if (RV->getKind() == RefVal::ErrorGCLeakReturned) {
Ted Kremenek9c378f72011-08-12 23:37:29 +00002284 ObjCMethodDecl &MD = cast<ObjCMethodDecl>(EndN->getCodeDecl());
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002285 os << " and returned from method '" << MD.getSelector().getAsString()
Ted Kremenek82f2be52009-05-10 16:52:15 +00002286 << "' is potentially leaked when using garbage collection. Callers "
2287 "of this method do not expect a returned object with a +1 retain "
2288 "count since they expect the object to be managed by the garbage "
2289 "collector";
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002290 }
Ted Kremenekc887d132009-04-29 18:50:19 +00002291 else
Ted Kremenekabf517c2010-10-15 22:50:23 +00002292 os << " is not referenced later in this execution path and has a retain "
Ted Kremenekf1365462011-05-26 18:45:44 +00002293 "count of +" << RV->getCount();
Mike Stump1eb44332009-09-09 15:08:12 +00002294
Ted Kremenekc887d132009-04-29 18:50:19 +00002295 return new PathDiagnosticEventPiece(L, os.str());
2296}
2297
Jordy Rose20589562011-08-24 22:39:09 +00002298CFRefLeakReport::CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts,
2299 bool GCEnabled, const SummaryLogTy &Log,
2300 ExplodedNode *n, SymbolRef sym,
Anna Zaks6a93bd52011-10-25 19:57:11 +00002301 CheckerContext &Ctx)
Jordy Rose20589562011-08-24 22:39:09 +00002302: CFRefReport(D, LOpts, GCEnabled, Log, n, sym, false) {
Mike Stump1eb44332009-09-09 15:08:12 +00002303
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00002304 // Most bug reports are cached at the location where they occurred.
Ted Kremenekc887d132009-04-29 18:50:19 +00002305 // With leaks, we want to unique them by the location where they were
2306 // allocated, and only report a single path. To do this, we need to find
2307 // the allocation site of a piece of tracked memory, which we do via a
2308 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2309 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2310 // that all ancestor nodes that represent the allocation site have the
2311 // same SourceLocation.
Ted Kremenek9c378f72011-08-12 23:37:29 +00002312 const ExplodedNode *AllocNode = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002313
Anna Zaks6a93bd52011-10-25 19:57:11 +00002314 const SourceManager& SMgr = Ctx.getSourceManager();
Anna Zaks590dd8e2011-09-20 21:38:35 +00002315
Ted Kremenekc887d132009-04-29 18:50:19 +00002316 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding.
Anna Zaks6a93bd52011-10-25 19:57:11 +00002317 GetAllocationSite(Ctx.getStateManager(), getErrorNode(), sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002318
Ted Kremenekc887d132009-04-29 18:50:19 +00002319 // Get the SourceLocation for the allocation site.
Jordan Rose852aa0d2012-07-10 22:07:52 +00002320 // FIXME: This will crash the analyzer if an allocation comes from an
2321 // implicit call. (Currently there are no such allocations in Cocoa, though.)
2322 const Stmt *AllocStmt;
Ted Kremenekc887d132009-04-29 18:50:19 +00002323 ProgramPoint P = AllocNode->getLocation();
Jordan Rose852aa0d2012-07-10 22:07:52 +00002324 if (CallExitEnd *Exit = dyn_cast<CallExitEnd>(&P))
2325 AllocStmt = Exit->getCalleeContext()->getCallSite();
2326 else
2327 AllocStmt = cast<PostStmt>(P).getStmt();
2328 assert(AllocStmt && "All allocations must come from explicit calls");
Anna Zaks590dd8e2011-09-20 21:38:35 +00002329 Location = PathDiagnosticLocation::createBegin(AllocStmt, SMgr,
2330 n->getLocationContext());
Ted Kremenekc887d132009-04-29 18:50:19 +00002331 // Fill in the description of the bug.
2332 Description.clear();
2333 llvm::raw_string_ostream os(Description);
Ted Kremenekdd924e22009-05-02 19:05:19 +00002334 os << "Potential leak ";
Jordy Rose20589562011-08-24 22:39:09 +00002335 if (GCEnabled)
Ted Kremenekdd924e22009-05-02 19:05:19 +00002336 os << "(when using garbage collection) ";
Anna Zaks212000e2012-02-28 21:49:08 +00002337 os << "of an object";
Mike Stump1eb44332009-09-09 15:08:12 +00002338
Ted Kremenekc887d132009-04-29 18:50:19 +00002339 // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2340 if (AllocBinding)
Anna Zaks212000e2012-02-28 21:49:08 +00002341 os << " stored into '" << AllocBinding->getString() << '\'';
Anna Zaksdc757b02011-08-19 23:21:56 +00002342
Jordy Rose20589562011-08-24 22:39:09 +00002343 addVisitor(new CFRefLeakReportVisitor(sym, GCEnabled, Log));
Ted Kremenekc887d132009-04-29 18:50:19 +00002344}
2345
2346//===----------------------------------------------------------------------===//
2347// Main checker logic.
2348//===----------------------------------------------------------------------===//
2349
Ted Kremenekd593eb92009-11-25 22:17:44 +00002350namespace {
Jordy Rose910c4052011-09-02 06:44:22 +00002351class RetainCountChecker
Jordy Rose9c083b72011-08-24 18:56:32 +00002352 : public Checker< check::Bind,
Jordy Rose38f17d62011-08-23 19:01:07 +00002353 check::DeadSymbols,
Jordy Rose9c083b72011-08-24 18:56:32 +00002354 check::EndAnalysis,
Jordy Rose38f17d62011-08-23 19:01:07 +00002355 check::EndPath,
Jordy Rose67044292011-08-17 21:27:39 +00002356 check::PostStmt<BlockExpr>,
John McCallf85e1932011-06-15 23:02:42 +00002357 check::PostStmt<CastExpr>,
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002358 check::PostStmt<ObjCArrayLiteral>,
2359 check::PostStmt<ObjCDictionaryLiteral>,
Jordy Rose70fdbc32012-05-12 05:10:43 +00002360 check::PostStmt<ObjCBoxedExpr>,
Jordan Rosefe6a0112012-07-02 19:28:21 +00002361 check::PostCall,
Jordy Rosef53e8c72011-08-23 19:43:16 +00002362 check::PreStmt<ReturnStmt>,
Jordy Rose67044292011-08-17 21:27:39 +00002363 check::RegionChanges,
Jordy Rose76c506f2011-08-21 21:58:18 +00002364 eval::Assume,
2365 eval::Call > {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002366 mutable OwningPtr<CFRefBug> useAfterRelease, releaseNotOwned;
2367 mutable OwningPtr<CFRefBug> deallocGC, deallocNotOwned;
2368 mutable OwningPtr<CFRefBug> overAutorelease, returnNotOwnedForOwned;
2369 mutable OwningPtr<CFRefBug> leakWithinFunction, leakAtReturn;
2370 mutable OwningPtr<CFRefBug> leakWithinFunctionGC, leakAtReturnGC;
Jordy Rose38f17d62011-08-23 19:01:07 +00002371
2372 typedef llvm::DenseMap<SymbolRef, const SimpleProgramPointTag *> SymbolTagMap;
2373
2374 // This map is only used to ensure proper deletion of any allocated tags.
2375 mutable SymbolTagMap DeadSymbolTags;
2376
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002377 mutable OwningPtr<RetainSummaryManager> Summaries;
2378 mutable OwningPtr<RetainSummaryManager> SummariesGC;
Jordy Rose9c083b72011-08-24 18:56:32 +00002379 mutable SummaryLogTy SummaryLog;
2380 mutable bool ShouldResetSummaryLog;
2381
Jordy Rose2f9a66d2011-08-20 21:17:59 +00002382public:
Jordy Rose910c4052011-09-02 06:44:22 +00002383 RetainCountChecker() : ShouldResetSummaryLog(false) {}
Jordy Rose38f17d62011-08-23 19:01:07 +00002384
Jordy Rose910c4052011-09-02 06:44:22 +00002385 virtual ~RetainCountChecker() {
Jordy Rose38f17d62011-08-23 19:01:07 +00002386 DeleteContainerSeconds(DeadSymbolTags);
2387 }
2388
Jordy Rose9c083b72011-08-24 18:56:32 +00002389 void checkEndAnalysis(ExplodedGraph &G, BugReporter &BR,
2390 ExprEngine &Eng) const {
2391 // FIXME: This is a hack to make sure the summary log gets cleared between
2392 // analyses of different code bodies.
2393 //
2394 // Why is this necessary? Because a checker's lifetime is tied to a
2395 // translation unit, but an ExplodedGraph's lifetime is just a code body.
2396 // Once in a blue moon, a new ExplodedNode will have the same address as an
2397 // old one with an associated summary, and the bug report visitor gets very
2398 // confused. (To make things worse, the summary lifetime is currently also
2399 // tied to a code body, so we get a crash instead of incorrect results.)
Jordy Rose1ab51c72011-08-24 09:27:24 +00002400 //
2401 // Why is this a bad solution? Because if the lifetime of the ExplodedGraph
2402 // changes, things will start going wrong again. Really the lifetime of this
2403 // log needs to be tied to either the specific nodes in it or the entire
2404 // ExplodedGraph, not to a specific part of the code being analyzed.
2405 //
Jordy Rose9c083b72011-08-24 18:56:32 +00002406 // (Also, having stateful local data means that the same checker can't be
2407 // used from multiple threads, but a lot of checkers have incorrect
2408 // assumptions about that anyway. So that wasn't a priority at the time of
2409 // this fix.)
Jordy Rose1ab51c72011-08-24 09:27:24 +00002410 //
Jordy Rose9c083b72011-08-24 18:56:32 +00002411 // This happens at the end of analysis, but bug reports are emitted /after/
2412 // this point. So we can't just clear the summary log now. Instead, we mark
2413 // that the next time we access the summary log, it should be cleared.
2414
2415 // If we never reset the summary log during /this/ code body analysis,
2416 // there were no new summaries. There might still have been summaries from
2417 // the /last/ analysis, so clear them out to make sure the bug report
2418 // visitors don't get confused.
2419 if (ShouldResetSummaryLog)
2420 SummaryLog.clear();
2421
2422 ShouldResetSummaryLog = !SummaryLog.empty();
Jordy Rose1ab51c72011-08-24 09:27:24 +00002423 }
2424
Jordy Rose17a38e22011-09-02 05:55:19 +00002425 CFRefBug *getLeakWithinFunctionBug(const LangOptions &LOpts,
2426 bool GCEnabled) const {
2427 if (GCEnabled) {
Jordy Rosedb92bb62011-08-25 01:14:38 +00002428 if (!leakWithinFunctionGC)
Benjamin Kramerfacde172012-06-06 17:32:50 +00002429 leakWithinFunctionGC.reset(new Leak("Leak of object when using "
2430 "garbage collection"));
Jordy Rose17a38e22011-09-02 05:55:19 +00002431 return leakWithinFunctionGC.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002432 } else {
2433 if (!leakWithinFunction) {
Douglas Gregore289d812011-09-13 17:21:33 +00002434 if (LOpts.getGC() == LangOptions::HybridGC) {
Benjamin Kramerfacde172012-06-06 17:32:50 +00002435 leakWithinFunction.reset(new Leak("Leak of object when not using "
2436 "garbage collection (GC) in "
2437 "dual GC/non-GC code"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002438 } else {
Benjamin Kramerfacde172012-06-06 17:32:50 +00002439 leakWithinFunction.reset(new Leak("Leak"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002440 }
2441 }
Jordy Rose17a38e22011-09-02 05:55:19 +00002442 return leakWithinFunction.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002443 }
2444 }
2445
Jordy Rose17a38e22011-09-02 05:55:19 +00002446 CFRefBug *getLeakAtReturnBug(const LangOptions &LOpts, bool GCEnabled) const {
2447 if (GCEnabled) {
Jordy Rosedb92bb62011-08-25 01:14:38 +00002448 if (!leakAtReturnGC)
Benjamin Kramerfacde172012-06-06 17:32:50 +00002449 leakAtReturnGC.reset(new Leak("Leak of returned object when using "
2450 "garbage collection"));
Jordy Rose17a38e22011-09-02 05:55:19 +00002451 return leakAtReturnGC.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002452 } else {
2453 if (!leakAtReturn) {
Douglas Gregore289d812011-09-13 17:21:33 +00002454 if (LOpts.getGC() == LangOptions::HybridGC) {
Benjamin Kramerfacde172012-06-06 17:32:50 +00002455 leakAtReturn.reset(new Leak("Leak of returned object when not using "
2456 "garbage collection (GC) in dual "
2457 "GC/non-GC code"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002458 } else {
Benjamin Kramerfacde172012-06-06 17:32:50 +00002459 leakAtReturn.reset(new Leak("Leak of returned object"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002460 }
2461 }
Jordy Rose17a38e22011-09-02 05:55:19 +00002462 return leakAtReturn.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002463 }
2464 }
2465
Jordy Rose17a38e22011-09-02 05:55:19 +00002466 RetainSummaryManager &getSummaryManager(ASTContext &Ctx,
2467 bool GCEnabled) const {
2468 // FIXME: We don't support ARC being turned on and off during one analysis.
2469 // (nor, for that matter, do we support changing ASTContexts)
David Blaikie4e4d0842012-03-11 07:00:24 +00002470 bool ARCEnabled = (bool)Ctx.getLangOpts().ObjCAutoRefCount;
Jordy Rose17a38e22011-09-02 05:55:19 +00002471 if (GCEnabled) {
2472 if (!SummariesGC)
Jordy Roseb6cfc092011-08-25 00:10:37 +00002473 SummariesGC.reset(new RetainSummaryManager(Ctx, true, ARCEnabled));
Jordy Rose17a38e22011-09-02 05:55:19 +00002474 else
2475 assert(SummariesGC->isARCEnabled() == ARCEnabled);
Jordy Roseb6cfc092011-08-25 00:10:37 +00002476 return *SummariesGC;
2477 } else {
Jordy Rose17a38e22011-09-02 05:55:19 +00002478 if (!Summaries)
Jordy Roseb6cfc092011-08-25 00:10:37 +00002479 Summaries.reset(new RetainSummaryManager(Ctx, false, ARCEnabled));
Jordy Rose17a38e22011-09-02 05:55:19 +00002480 else
2481 assert(Summaries->isARCEnabled() == ARCEnabled);
Jordy Roseb6cfc092011-08-25 00:10:37 +00002482 return *Summaries;
2483 }
2484 }
2485
Jordy Rose17a38e22011-09-02 05:55:19 +00002486 RetainSummaryManager &getSummaryManager(CheckerContext &C) const {
2487 return getSummaryManager(C.getASTContext(), C.isObjCGCEnabled());
2488 }
2489
Ted Kremenek8bef8232012-01-26 21:29:00 +00002490 void printState(raw_ostream &Out, ProgramStateRef State,
Jordy Rosedbd658e2011-08-28 19:11:56 +00002491 const char *NL, const char *Sep) const;
2492
Anna Zaks390909c2011-10-06 00:43:15 +00002493 void checkBind(SVal loc, SVal val, const Stmt *S, CheckerContext &C) const;
Jordy Roseab027fd2011-08-20 21:16:58 +00002494 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
2495 void checkPostStmt(const CastExpr *CE, CheckerContext &C) const;
John McCallf85e1932011-06-15 23:02:42 +00002496
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002497 void checkPostStmt(const ObjCArrayLiteral *AL, CheckerContext &C) const;
2498 void checkPostStmt(const ObjCDictionaryLiteral *DL, CheckerContext &C) const;
Jordy Rose70fdbc32012-05-12 05:10:43 +00002499 void checkPostStmt(const ObjCBoxedExpr *BE, CheckerContext &C) const;
2500
Jordan Rosefe6a0112012-07-02 19:28:21 +00002501 void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002502
Jordan Rose4531b7d2012-07-02 19:27:43 +00002503 void checkSummary(const RetainSummary &Summ, const CallEvent &Call,
Jordy Rosee38dd952011-08-28 05:16:28 +00002504 CheckerContext &C) const;
Jordy Rose294396b2011-08-22 23:48:23 +00002505
Anna Zaks554067f2012-08-29 23:23:43 +00002506 void processSummaryOfInlined(const RetainSummary &Summ,
2507 const CallEvent &Call,
2508 CheckerContext &C) const;
2509
Jordy Rose76c506f2011-08-21 21:58:18 +00002510 bool evalCall(const CallExpr *CE, CheckerContext &C) const;
2511
Ted Kremenek8bef8232012-01-26 21:29:00 +00002512 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Jordy Roseab027fd2011-08-20 21:16:58 +00002513 bool Assumption) const;
Jordy Rose67044292011-08-17 21:27:39 +00002514
Ted Kremenek8bef8232012-01-26 21:29:00 +00002515 ProgramStateRef
2516 checkRegionChanges(ProgramStateRef state,
Anna Zaksbf53dfa2012-12-20 00:38:25 +00002517 const InvalidatedSymbols *invalidated,
Jordy Rose537716a2011-08-27 22:51:26 +00002518 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00002519 ArrayRef<const MemRegion *> Regions,
Jordan Rose740d4902012-07-02 19:27:35 +00002520 const CallEvent *Call) const;
Jordy Roseab027fd2011-08-20 21:16:58 +00002521
Ted Kremenek8bef8232012-01-26 21:29:00 +00002522 bool wantsRegionChangeUpdate(ProgramStateRef state) const {
Jordy Rose2f9a66d2011-08-20 21:17:59 +00002523 return true;
Jordy Roseab027fd2011-08-20 21:16:58 +00002524 }
Jordy Rose294396b2011-08-22 23:48:23 +00002525
Jordy Rosef53e8c72011-08-23 19:43:16 +00002526 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
2527 void checkReturnWithRetEffect(const ReturnStmt *S, CheckerContext &C,
2528 ExplodedNode *Pred, RetEffect RE, RefVal X,
Ted Kremenek8bef8232012-01-26 21:29:00 +00002529 SymbolRef Sym, ProgramStateRef state) const;
Jordy Rosef53e8c72011-08-23 19:43:16 +00002530
Jordy Rose38f17d62011-08-23 19:01:07 +00002531 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Anna Zaksaf498a22011-10-25 19:56:48 +00002532 void checkEndPath(CheckerContext &C) const;
Jordy Rose38f17d62011-08-23 19:01:07 +00002533
Ted Kremenek8bef8232012-01-26 21:29:00 +00002534 ProgramStateRef updateSymbol(ProgramStateRef state, SymbolRef sym,
Anna Zaks554067f2012-08-29 23:23:43 +00002535 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
2536 CheckerContext &C) const;
Jordy Rosee0a5d322011-08-23 20:27:16 +00002537
Ted Kremenek8bef8232012-01-26 21:29:00 +00002538 void processNonLeakError(ProgramStateRef St, SourceRange ErrorRange,
Jordy Rose294396b2011-08-22 23:48:23 +00002539 RefVal::Kind ErrorKind, SymbolRef Sym,
2540 CheckerContext &C) const;
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002541
2542 void processObjCLiterals(CheckerContext &C, const Expr *Ex) const;
Jordy Rose294396b2011-08-22 23:48:23 +00002543
Jordy Rose38f17d62011-08-23 19:01:07 +00002544 const ProgramPointTag *getDeadSymbolTag(SymbolRef sym) const;
2545
Ted Kremenek8bef8232012-01-26 21:29:00 +00002546 ProgramStateRef handleSymbolDeath(ProgramStateRef state,
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002547 SymbolRef sid, RefVal V,
2548 SmallVectorImpl<SymbolRef> &Leaked) const;
Jordy Rose38f17d62011-08-23 19:01:07 +00002549
Jordan Rose4ee1c552012-12-06 18:58:18 +00002550 ProgramStateRef
Jordan Rose2bce86c2012-08-18 00:30:16 +00002551 handleAutoreleaseCounts(ProgramStateRef state, ExplodedNode *Pred,
2552 const ProgramPointTag *Tag, CheckerContext &Ctx,
2553 SymbolRef Sym, RefVal V) const;
Jordy Rose8d228632011-08-23 20:07:14 +00002554
Ted Kremenek8bef8232012-01-26 21:29:00 +00002555 ExplodedNode *processLeaks(ProgramStateRef state,
Jordy Rose38f17d62011-08-23 19:01:07 +00002556 SmallVectorImpl<SymbolRef> &Leaked,
Anna Zaks6a93bd52011-10-25 19:57:11 +00002557 CheckerContext &Ctx,
Jordy Rose38f17d62011-08-23 19:01:07 +00002558 ExplodedNode *Pred = 0) const;
Ted Kremenekd593eb92009-11-25 22:17:44 +00002559};
2560} // end anonymous namespace
2561
Jordy Rose67044292011-08-17 21:27:39 +00002562namespace {
2563class StopTrackingCallback : public SymbolVisitor {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002564 ProgramStateRef state;
Jordy Rose67044292011-08-17 21:27:39 +00002565public:
Ted Kremenek8bef8232012-01-26 21:29:00 +00002566 StopTrackingCallback(ProgramStateRef st) : state(st) {}
2567 ProgramStateRef getState() const { return state; }
Jordy Rose67044292011-08-17 21:27:39 +00002568
2569 bool VisitSymbol(SymbolRef sym) {
2570 state = state->remove<RefBindings>(sym);
2571 return true;
2572 }
2573};
2574} // end anonymous namespace
2575
Jordy Rose910c4052011-09-02 06:44:22 +00002576//===----------------------------------------------------------------------===//
2577// Handle statements that may have an effect on refcounts.
2578//===----------------------------------------------------------------------===//
Jordy Rose67044292011-08-17 21:27:39 +00002579
Jordy Rose910c4052011-09-02 06:44:22 +00002580void RetainCountChecker::checkPostStmt(const BlockExpr *BE,
2581 CheckerContext &C) const {
Jordy Rose67044292011-08-17 21:27:39 +00002582
Jordy Rose910c4052011-09-02 06:44:22 +00002583 // Scan the BlockDecRefExprs for any object the retain count checker
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002584 // may be tracking.
John McCall469a1eb2011-02-02 13:00:07 +00002585 if (!BE->getBlockDecl()->hasCaptures())
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002586 return;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002587
Ted Kremenek8bef8232012-01-26 21:29:00 +00002588 ProgramStateRef state = C.getState();
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002589 const BlockDataRegion *R =
Ted Kremenek5eca4822012-01-06 22:09:28 +00002590 cast<BlockDataRegion>(state->getSVal(BE,
2591 C.getLocationContext()).getAsRegion());
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002592
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002593 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
2594 E = R->referenced_vars_end();
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002595
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002596 if (I == E)
2597 return;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002598
Ted Kremenek67d12872009-12-07 22:05:27 +00002599 // FIXME: For now we invalidate the tracking of all symbols passed to blocks
2600 // via captured variables, even though captured variables result in a copy
2601 // and in implicit increment/decrement of a retain count.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002602 SmallVector<const MemRegion*, 10> Regions;
Anna Zaks39ac1872011-10-26 21:06:44 +00002603 const LocationContext *LC = C.getLocationContext();
Ted Kremenekc8413fd2010-12-02 07:49:45 +00002604 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002605
Ted Kremenek67d12872009-12-07 22:05:27 +00002606 for ( ; I != E; ++I) {
Ted Kremeneke3ce2c12012-12-06 07:17:20 +00002607 const VarRegion *VR = I.getCapturedRegion();
Ted Kremenek67d12872009-12-07 22:05:27 +00002608 if (VR->getSuperRegion() == R) {
2609 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2610 }
2611 Regions.push_back(VR);
2612 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002613
Ted Kremenek67d12872009-12-07 22:05:27 +00002614 state =
2615 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
2616 Regions.data() + Regions.size()).getState();
Anna Zaks0bd6b112011-10-26 21:06:34 +00002617 C.addTransition(state);
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002618}
2619
Jordy Rose910c4052011-09-02 06:44:22 +00002620void RetainCountChecker::checkPostStmt(const CastExpr *CE,
2621 CheckerContext &C) const {
John McCallf85e1932011-06-15 23:02:42 +00002622 const ObjCBridgedCastExpr *BE = dyn_cast<ObjCBridgedCastExpr>(CE);
2623 if (!BE)
2624 return;
2625
John McCall71c482c2011-06-17 06:50:50 +00002626 ArgEffect AE = IncRef;
John McCallf85e1932011-06-15 23:02:42 +00002627
2628 switch (BE->getBridgeKind()) {
2629 case clang::OBC_Bridge:
2630 // Do nothing.
2631 return;
2632 case clang::OBC_BridgeRetained:
2633 AE = IncRef;
2634 break;
2635 case clang::OBC_BridgeTransfer:
2636 AE = DecRefBridgedTransfered;
2637 break;
2638 }
2639
Ted Kremenek8bef8232012-01-26 21:29:00 +00002640 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00002641 SymbolRef Sym = state->getSVal(CE, C.getLocationContext()).getAsLocSymbol();
John McCallf85e1932011-06-15 23:02:42 +00002642 if (!Sym)
2643 return;
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002644 const RefVal* T = getRefBinding(state, Sym);
John McCallf85e1932011-06-15 23:02:42 +00002645 if (!T)
2646 return;
2647
John McCallf85e1932011-06-15 23:02:42 +00002648 RefVal::Kind hasErr = (RefVal::Kind) 0;
Jordy Rose17a38e22011-09-02 05:55:19 +00002649 state = updateSymbol(state, Sym, *T, AE, hasErr, C);
John McCallf85e1932011-06-15 23:02:42 +00002650
2651 if (hasErr) {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002652 // FIXME: If we get an error during a bridge cast, should we report it?
2653 // Should we assert that there is no error?
John McCallf85e1932011-06-15 23:02:42 +00002654 return;
2655 }
2656
Anna Zaks0bd6b112011-10-26 21:06:34 +00002657 C.addTransition(state);
John McCallf85e1932011-06-15 23:02:42 +00002658}
2659
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002660void RetainCountChecker::processObjCLiterals(CheckerContext &C,
2661 const Expr *Ex) const {
2662 ProgramStateRef state = C.getState();
2663 const ExplodedNode *pred = C.getPredecessor();
2664 for (Stmt::const_child_iterator it = Ex->child_begin(), et = Ex->child_end() ;
2665 it != et ; ++it) {
2666 const Stmt *child = *it;
2667 SVal V = state->getSVal(child, pred->getLocationContext());
2668 if (SymbolRef sym = V.getAsSymbol())
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002669 if (const RefVal* T = getRefBinding(state, sym)) {
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002670 RefVal::Kind hasErr = (RefVal::Kind) 0;
2671 state = updateSymbol(state, sym, *T, MayEscape, hasErr, C);
2672 if (hasErr) {
2673 processNonLeakError(state, child->getSourceRange(), hasErr, sym, C);
2674 return;
2675 }
2676 }
2677 }
2678
2679 // Return the object as autoreleased.
2680 // RetEffect RE = RetEffect::MakeNotOwned(RetEffect::ObjC);
2681 if (SymbolRef sym =
2682 state->getSVal(Ex, pred->getLocationContext()).getAsSymbol()) {
2683 QualType ResultTy = Ex->getType();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002684 state = setRefBinding(state, sym,
2685 RefVal::makeNotOwned(RetEffect::ObjC, ResultTy));
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002686 }
2687
2688 C.addTransition(state);
2689}
2690
2691void RetainCountChecker::checkPostStmt(const ObjCArrayLiteral *AL,
2692 CheckerContext &C) const {
2693 // Apply the 'MayEscape' to all values.
2694 processObjCLiterals(C, AL);
2695}
2696
2697void RetainCountChecker::checkPostStmt(const ObjCDictionaryLiteral *DL,
2698 CheckerContext &C) const {
2699 // Apply the 'MayEscape' to all keys and values.
2700 processObjCLiterals(C, DL);
2701}
2702
Jordy Rose70fdbc32012-05-12 05:10:43 +00002703void RetainCountChecker::checkPostStmt(const ObjCBoxedExpr *Ex,
2704 CheckerContext &C) const {
2705 const ExplodedNode *Pred = C.getPredecessor();
2706 const LocationContext *LCtx = Pred->getLocationContext();
2707 ProgramStateRef State = Pred->getState();
2708
2709 if (SymbolRef Sym = State->getSVal(Ex, LCtx).getAsSymbol()) {
2710 QualType ResultTy = Ex->getType();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002711 State = setRefBinding(State, Sym,
2712 RefVal::makeNotOwned(RetEffect::ObjC, ResultTy));
Jordy Rose70fdbc32012-05-12 05:10:43 +00002713 }
2714
2715 C.addTransition(State);
2716}
2717
Jordan Rosefe6a0112012-07-02 19:28:21 +00002718void RetainCountChecker::checkPostCall(const CallEvent &Call,
2719 CheckerContext &C) const {
Jordan Rosefe6a0112012-07-02 19:28:21 +00002720 RetainSummaryManager &Summaries = getSummaryManager(C);
2721 const RetainSummary *Summ = Summaries.getSummary(Call, C.getState());
Anna Zaks554067f2012-08-29 23:23:43 +00002722
2723 if (C.wasInlined) {
2724 processSummaryOfInlined(*Summ, Call, C);
2725 return;
2726 }
Jordan Rosefe6a0112012-07-02 19:28:21 +00002727 checkSummary(*Summ, Call, C);
Jordy Rose294396b2011-08-22 23:48:23 +00002728}
2729
Jordy Rose910c4052011-09-02 06:44:22 +00002730/// GetReturnType - Used to get the return type of a message expression or
2731/// function call with the intention of affixing that type to a tracked symbol.
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +00002732/// While the return type can be queried directly from RetEx, when
Jordy Rose910c4052011-09-02 06:44:22 +00002733/// invoking class methods we augment to the return type to be that of
2734/// a pointer to the class (as opposed it just being id).
2735// FIXME: We may be able to do this with related result types instead.
2736// This function is probably overestimating.
2737static QualType GetReturnType(const Expr *RetE, ASTContext &Ctx) {
2738 QualType RetTy = RetE->getType();
2739 // If RetE is not a message expression just return its type.
2740 // If RetE is a message expression, return its types if it is something
2741 /// more specific than id.
2742 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RetE))
2743 if (const ObjCObjectPointerType *PT = RetTy->getAs<ObjCObjectPointerType>())
2744 if (PT->isObjCQualifiedIdType() || PT->isObjCIdType() ||
2745 PT->isObjCClassType()) {
2746 // At this point we know the return type of the message expression is
2747 // id, id<...>, or Class. If we have an ObjCInterfaceDecl, we know this
2748 // is a call to a class method whose type we can resolve. In such
2749 // cases, promote the return type to XXX* (where XXX is the class).
2750 const ObjCInterfaceDecl *D = ME->getReceiverInterface();
2751 return !D ? RetTy :
2752 Ctx.getObjCObjectPointerType(Ctx.getObjCInterfaceType(D));
2753 }
2754
2755 return RetTy;
2756}
2757
Anna Zaks554067f2012-08-29 23:23:43 +00002758// We don't always get the exact modeling of the function with regards to the
2759// retain count checker even when the function is inlined. For example, we need
2760// to stop tracking the symbols which were marked with StopTrackingHard.
2761void RetainCountChecker::processSummaryOfInlined(const RetainSummary &Summ,
2762 const CallEvent &CallOrMsg,
2763 CheckerContext &C) const {
2764 ProgramStateRef state = C.getState();
2765
2766 // Evaluate the effect of the arguments.
2767 for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
2768 if (Summ.getArg(idx) == StopTrackingHard) {
2769 SVal V = CallOrMsg.getArgSVal(idx);
2770 if (SymbolRef Sym = V.getAsLocSymbol()) {
2771 state = removeRefBinding(state, Sym);
2772 }
2773 }
2774 }
2775
2776 // Evaluate the effect on the message receiver.
2777 const ObjCMethodCall *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg);
2778 if (MsgInvocation) {
2779 if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
2780 if (Summ.getReceiverEffect() == StopTrackingHard) {
2781 state = removeRefBinding(state, Sym);
2782 }
2783 }
2784 }
2785
2786 // Consult the summary for the return value.
2787 RetEffect RE = Summ.getRetEffect();
2788 if (RE.getKind() == RetEffect::NoRetHard) {
Jordan Rose2f3017f2012-11-02 23:49:29 +00002789 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
Anna Zaks554067f2012-08-29 23:23:43 +00002790 if (Sym)
2791 state = removeRefBinding(state, Sym);
2792 }
2793
2794 C.addTransition(state);
2795}
2796
Jordy Rose910c4052011-09-02 06:44:22 +00002797void RetainCountChecker::checkSummary(const RetainSummary &Summ,
Jordan Rose4531b7d2012-07-02 19:27:43 +00002798 const CallEvent &CallOrMsg,
Jordy Rose910c4052011-09-02 06:44:22 +00002799 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002800 ProgramStateRef state = C.getState();
Jordy Rose294396b2011-08-22 23:48:23 +00002801
2802 // Evaluate the effect of the arguments.
2803 RefVal::Kind hasErr = (RefVal::Kind) 0;
2804 SourceRange ErrorRange;
2805 SymbolRef ErrorSym = 0;
2806
2807 for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
Jordy Rose537716a2011-08-27 22:51:26 +00002808 SVal V = CallOrMsg.getArgSVal(idx);
Jordy Rose294396b2011-08-22 23:48:23 +00002809
2810 if (SymbolRef Sym = V.getAsLocSymbol()) {
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002811 if (const RefVal *T = getRefBinding(state, Sym)) {
Jordy Rose17a38e22011-09-02 05:55:19 +00002812 state = updateSymbol(state, Sym, *T, Summ.getArg(idx), hasErr, C);
Jordy Rose294396b2011-08-22 23:48:23 +00002813 if (hasErr) {
2814 ErrorRange = CallOrMsg.getArgSourceRange(idx);
2815 ErrorSym = Sym;
2816 break;
2817 }
2818 }
2819 }
2820 }
2821
2822 // Evaluate the effect on the message receiver.
2823 bool ReceiverIsTracked = false;
Jordan Rose4531b7d2012-07-02 19:27:43 +00002824 if (!hasErr) {
Jordan Rosecde8cdb2012-07-02 19:27:56 +00002825 const ObjCMethodCall *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg);
Jordan Rose4531b7d2012-07-02 19:27:43 +00002826 if (MsgInvocation) {
2827 if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002828 if (const RefVal *T = getRefBinding(state, Sym)) {
Jordan Rose4531b7d2012-07-02 19:27:43 +00002829 ReceiverIsTracked = true;
2830 state = updateSymbol(state, Sym, *T, Summ.getReceiverEffect(),
Anna Zaks554067f2012-08-29 23:23:43 +00002831 hasErr, C);
Jordan Rose4531b7d2012-07-02 19:27:43 +00002832 if (hasErr) {
Jordan Rose8919e682012-07-18 21:59:51 +00002833 ErrorRange = MsgInvocation->getOriginExpr()->getReceiverRange();
Jordan Rose4531b7d2012-07-02 19:27:43 +00002834 ErrorSym = Sym;
2835 }
Jordy Rose294396b2011-08-22 23:48:23 +00002836 }
2837 }
2838 }
2839 }
2840
2841 // Process any errors.
2842 if (hasErr) {
2843 processNonLeakError(state, ErrorRange, hasErr, ErrorSym, C);
2844 return;
2845 }
2846
2847 // Consult the summary for the return value.
2848 RetEffect RE = Summ.getRetEffect();
2849
2850 if (RE.getKind() == RetEffect::OwnedWhenTrackedReceiver) {
Jordy Roseb6cfc092011-08-25 00:10:37 +00002851 if (ReceiverIsTracked)
Jordy Rose17a38e22011-09-02 05:55:19 +00002852 RE = getSummaryManager(C).getObjAllocRetEffect();
Jordy Roseb6cfc092011-08-25 00:10:37 +00002853 else
Jordy Rose294396b2011-08-22 23:48:23 +00002854 RE = RetEffect::MakeNoRet();
2855 }
2856
2857 switch (RE.getKind()) {
2858 default:
David Blaikie7530c032012-01-17 06:56:22 +00002859 llvm_unreachable("Unhandled RetEffect.");
Jordy Rose294396b2011-08-22 23:48:23 +00002860
2861 case RetEffect::NoRet:
Anna Zaks554067f2012-08-29 23:23:43 +00002862 case RetEffect::NoRetHard:
Jordy Rose294396b2011-08-22 23:48:23 +00002863 // No work necessary.
2864 break;
2865
2866 case RetEffect::OwnedAllocatedSymbol:
2867 case RetEffect::OwnedSymbol: {
Jordan Rose2f3017f2012-11-02 23:49:29 +00002868 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
Jordy Rose294396b2011-08-22 23:48:23 +00002869 if (!Sym)
2870 break;
2871
Jordan Rose4531b7d2012-07-02 19:27:43 +00002872 // Use the result type from the CallEvent as it automatically adjusts
Jordy Rose294396b2011-08-22 23:48:23 +00002873 // for methods/functions that return references.
Jordan Rose4531b7d2012-07-02 19:27:43 +00002874 QualType ResultTy = CallOrMsg.getResultType();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002875 state = setRefBinding(state, Sym, RefVal::makeOwned(RE.getObjKind(),
2876 ResultTy));
Jordy Rose294396b2011-08-22 23:48:23 +00002877
2878 // FIXME: Add a flag to the checker where allocations are assumed to
Anna Zaksc6ba23f2012-08-14 15:39:13 +00002879 // *not* fail.
Jordy Rose294396b2011-08-22 23:48:23 +00002880 break;
2881 }
2882
2883 case RetEffect::GCNotOwnedSymbol:
2884 case RetEffect::ARCNotOwnedSymbol:
2885 case RetEffect::NotOwnedSymbol: {
2886 const Expr *Ex = CallOrMsg.getOriginExpr();
Jordan Rose2f3017f2012-11-02 23:49:29 +00002887 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
Jordy Rose294396b2011-08-22 23:48:23 +00002888 if (!Sym)
2889 break;
Ted Kremenek74616822012-10-12 22:56:45 +00002890 assert(Ex);
Jordy Rose294396b2011-08-22 23:48:23 +00002891 // Use GetReturnType in order to give [NSFoo alloc] the type NSFoo *.
2892 QualType ResultTy = GetReturnType(Ex, C.getASTContext());
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002893 state = setRefBinding(state, Sym, RefVal::makeNotOwned(RE.getObjKind(),
2894 ResultTy));
Jordy Rose294396b2011-08-22 23:48:23 +00002895 break;
2896 }
2897 }
2898
2899 // This check is actually necessary; otherwise the statement builder thinks
2900 // we've hit a previously-found path.
2901 // Normally addTransition takes care of this, but we want the node pointer.
2902 ExplodedNode *NewNode;
2903 if (state == C.getState()) {
2904 NewNode = C.getPredecessor();
2905 } else {
Anna Zaks0bd6b112011-10-26 21:06:34 +00002906 NewNode = C.addTransition(state);
Jordy Rose294396b2011-08-22 23:48:23 +00002907 }
2908
Jordy Rose9c083b72011-08-24 18:56:32 +00002909 // Annotate the node with summary we used.
2910 if (NewNode) {
2911 // FIXME: This is ugly. See checkEndAnalysis for why it's necessary.
2912 if (ShouldResetSummaryLog) {
2913 SummaryLog.clear();
2914 ShouldResetSummaryLog = false;
2915 }
Jordy Roseec9ef852011-08-23 20:55:48 +00002916 SummaryLog[NewNode] = &Summ;
Jordy Rose9c083b72011-08-24 18:56:32 +00002917 }
Jordy Rose294396b2011-08-22 23:48:23 +00002918}
2919
Jordy Rosee0a5d322011-08-23 20:27:16 +00002920
Ted Kremenek8bef8232012-01-26 21:29:00 +00002921ProgramStateRef
2922RetainCountChecker::updateSymbol(ProgramStateRef state, SymbolRef sym,
Jordy Rose910c4052011-09-02 06:44:22 +00002923 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
2924 CheckerContext &C) const {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002925 // In GC mode [... release] and [... retain] do nothing.
Jordy Rose910c4052011-09-02 06:44:22 +00002926 // In ARC mode they shouldn't exist at all, but we just ignore them.
Jordy Rose17a38e22011-09-02 05:55:19 +00002927 bool IgnoreRetainMsg = C.isObjCGCEnabled();
2928 if (!IgnoreRetainMsg)
David Blaikie4e4d0842012-03-11 07:00:24 +00002929 IgnoreRetainMsg = (bool)C.getASTContext().getLangOpts().ObjCAutoRefCount;
Jordy Rose17a38e22011-09-02 05:55:19 +00002930
Jordy Rosee0a5d322011-08-23 20:27:16 +00002931 switch (E) {
Jordan Rose4531b7d2012-07-02 19:27:43 +00002932 default:
2933 break;
2934 case IncRefMsg:
2935 E = IgnoreRetainMsg ? DoNothing : IncRef;
2936 break;
2937 case DecRefMsg:
2938 E = IgnoreRetainMsg ? DoNothing : DecRef;
2939 break;
Anna Zaks554067f2012-08-29 23:23:43 +00002940 case DecRefMsgAndStopTrackingHard:
2941 E = IgnoreRetainMsg ? StopTracking : DecRefAndStopTrackingHard;
Jordan Rose4531b7d2012-07-02 19:27:43 +00002942 break;
2943 case MakeCollectable:
2944 E = C.isObjCGCEnabled() ? DecRef : DoNothing;
2945 break;
2946 case NewAutoreleasePool:
2947 E = C.isObjCGCEnabled() ? DoNothing : NewAutoreleasePool;
2948 break;
Jordy Rosee0a5d322011-08-23 20:27:16 +00002949 }
2950
2951 // Handle all use-after-releases.
Jordy Rose17a38e22011-09-02 05:55:19 +00002952 if (!C.isObjCGCEnabled() && V.getKind() == RefVal::Released) {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002953 V = V ^ RefVal::ErrorUseAfterRelease;
2954 hasErr = V.getKind();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002955 return setRefBinding(state, sym, V);
Jordy Rosee0a5d322011-08-23 20:27:16 +00002956 }
2957
2958 switch (E) {
2959 case DecRefMsg:
2960 case IncRefMsg:
2961 case MakeCollectable:
Anna Zaks554067f2012-08-29 23:23:43 +00002962 case DecRefMsgAndStopTrackingHard:
Jordy Rosee0a5d322011-08-23 20:27:16 +00002963 llvm_unreachable("DecRefMsg/IncRefMsg/MakeCollectable already converted");
Jordy Rosee0a5d322011-08-23 20:27:16 +00002964
2965 case Dealloc:
2966 // Any use of -dealloc in GC is *bad*.
Jordy Rose17a38e22011-09-02 05:55:19 +00002967 if (C.isObjCGCEnabled()) {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002968 V = V ^ RefVal::ErrorDeallocGC;
2969 hasErr = V.getKind();
2970 break;
2971 }
2972
2973 switch (V.getKind()) {
2974 default:
2975 llvm_unreachable("Invalid RefVal state for an explicit dealloc.");
Jordy Rosee0a5d322011-08-23 20:27:16 +00002976 case RefVal::Owned:
2977 // The object immediately transitions to the released state.
2978 V = V ^ RefVal::Released;
2979 V.clearCounts();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002980 return setRefBinding(state, sym, V);
Jordy Rosee0a5d322011-08-23 20:27:16 +00002981 case RefVal::NotOwned:
2982 V = V ^ RefVal::ErrorDeallocNotOwned;
2983 hasErr = V.getKind();
2984 break;
2985 }
2986 break;
2987
2988 case NewAutoreleasePool:
Jordy Rose17a38e22011-09-02 05:55:19 +00002989 assert(!C.isObjCGCEnabled());
Anna Zaksc95bb762012-08-14 00:36:17 +00002990 return state;
Jordy Rosee0a5d322011-08-23 20:27:16 +00002991
2992 case MayEscape:
2993 if (V.getKind() == RefVal::Owned) {
2994 V = V ^ RefVal::NotOwned;
2995 break;
2996 }
2997
2998 // Fall-through.
2999
Jordy Rosee0a5d322011-08-23 20:27:16 +00003000 case DoNothing:
3001 return state;
3002
3003 case Autorelease:
Jordy Rose17a38e22011-09-02 05:55:19 +00003004 if (C.isObjCGCEnabled())
Jordy Rosee0a5d322011-08-23 20:27:16 +00003005 return state;
Jordy Rosee0a5d322011-08-23 20:27:16 +00003006 // Update the autorelease counts.
Jordy Rosee0a5d322011-08-23 20:27:16 +00003007 V = V.autorelease();
3008 break;
3009
3010 case StopTracking:
Anna Zaks554067f2012-08-29 23:23:43 +00003011 case StopTrackingHard:
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003012 return removeRefBinding(state, sym);
Jordy Rosee0a5d322011-08-23 20:27:16 +00003013
3014 case IncRef:
3015 switch (V.getKind()) {
3016 default:
3017 llvm_unreachable("Invalid RefVal state for a retain.");
Jordy Rosee0a5d322011-08-23 20:27:16 +00003018 case RefVal::Owned:
3019 case RefVal::NotOwned:
3020 V = V + 1;
3021 break;
3022 case RefVal::Released:
3023 // Non-GC cases are handled above.
Jordy Rose17a38e22011-09-02 05:55:19 +00003024 assert(C.isObjCGCEnabled());
Jordy Rosee0a5d322011-08-23 20:27:16 +00003025 V = (V ^ RefVal::Owned) + 1;
3026 break;
3027 }
3028 break;
3029
Jordy Rosee0a5d322011-08-23 20:27:16 +00003030 case DecRef:
3031 case DecRefBridgedTransfered:
Anna Zaks554067f2012-08-29 23:23:43 +00003032 case DecRefAndStopTrackingHard:
Jordy Rosee0a5d322011-08-23 20:27:16 +00003033 switch (V.getKind()) {
3034 default:
3035 // case 'RefVal::Released' handled above.
3036 llvm_unreachable("Invalid RefVal state for a release.");
Jordy Rosee0a5d322011-08-23 20:27:16 +00003037
3038 case RefVal::Owned:
3039 assert(V.getCount() > 0);
3040 if (V.getCount() == 1)
3041 V = V ^ (E == DecRefBridgedTransfered ?
3042 RefVal::NotOwned : RefVal::Released);
Anna Zaks554067f2012-08-29 23:23:43 +00003043 else if (E == DecRefAndStopTrackingHard)
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003044 return removeRefBinding(state, sym);
Jordan Rose4531b7d2012-07-02 19:27:43 +00003045
Jordy Rosee0a5d322011-08-23 20:27:16 +00003046 V = V - 1;
3047 break;
3048
3049 case RefVal::NotOwned:
Jordan Rose4531b7d2012-07-02 19:27:43 +00003050 if (V.getCount() > 0) {
Anna Zaks554067f2012-08-29 23:23:43 +00003051 if (E == DecRefAndStopTrackingHard)
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003052 return removeRefBinding(state, sym);
Jordy Rosee0a5d322011-08-23 20:27:16 +00003053 V = V - 1;
Jordan Rose4531b7d2012-07-02 19:27:43 +00003054 } else {
Jordy Rosee0a5d322011-08-23 20:27:16 +00003055 V = V ^ RefVal::ErrorReleaseNotOwned;
3056 hasErr = V.getKind();
3057 }
3058 break;
3059
3060 case RefVal::Released:
3061 // Non-GC cases are handled above.
Jordy Rose17a38e22011-09-02 05:55:19 +00003062 assert(C.isObjCGCEnabled());
Jordy Rosee0a5d322011-08-23 20:27:16 +00003063 V = V ^ RefVal::ErrorUseAfterRelease;
3064 hasErr = V.getKind();
3065 break;
3066 }
3067 break;
3068 }
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003069 return setRefBinding(state, sym, V);
Jordy Rosee0a5d322011-08-23 20:27:16 +00003070}
3071
Ted Kremenek8bef8232012-01-26 21:29:00 +00003072void RetainCountChecker::processNonLeakError(ProgramStateRef St,
Jordy Rose910c4052011-09-02 06:44:22 +00003073 SourceRange ErrorRange,
3074 RefVal::Kind ErrorKind,
3075 SymbolRef Sym,
3076 CheckerContext &C) const {
Jordy Rose294396b2011-08-22 23:48:23 +00003077 ExplodedNode *N = C.generateSink(St);
3078 if (!N)
3079 return;
3080
Jordy Rose294396b2011-08-22 23:48:23 +00003081 CFRefBug *BT;
3082 switch (ErrorKind) {
3083 default:
3084 llvm_unreachable("Unhandled error.");
Jordy Rose294396b2011-08-22 23:48:23 +00003085 case RefVal::ErrorUseAfterRelease:
Jordy Rosed6334e12011-08-25 00:34:03 +00003086 if (!useAfterRelease)
3087 useAfterRelease.reset(new UseAfterRelease());
3088 BT = &*useAfterRelease;
Jordy Rose294396b2011-08-22 23:48:23 +00003089 break;
3090 case RefVal::ErrorReleaseNotOwned:
Jordy Rosed6334e12011-08-25 00:34:03 +00003091 if (!releaseNotOwned)
3092 releaseNotOwned.reset(new BadRelease());
3093 BT = &*releaseNotOwned;
Jordy Rose294396b2011-08-22 23:48:23 +00003094 break;
3095 case RefVal::ErrorDeallocGC:
Jordy Rosed6334e12011-08-25 00:34:03 +00003096 if (!deallocGC)
3097 deallocGC.reset(new DeallocGC());
3098 BT = &*deallocGC;
Jordy Rose294396b2011-08-22 23:48:23 +00003099 break;
3100 case RefVal::ErrorDeallocNotOwned:
Jordy Rosed6334e12011-08-25 00:34:03 +00003101 if (!deallocNotOwned)
3102 deallocNotOwned.reset(new DeallocNotOwned());
3103 BT = &*deallocNotOwned;
Jordy Rose294396b2011-08-22 23:48:23 +00003104 break;
3105 }
3106
Jordy Rosed6334e12011-08-25 00:34:03 +00003107 assert(BT);
David Blaikie4e4d0842012-03-11 07:00:24 +00003108 CFRefReport *report = new CFRefReport(*BT, C.getASTContext().getLangOpts(),
Jordy Rose17a38e22011-09-02 05:55:19 +00003109 C.isObjCGCEnabled(), SummaryLog,
3110 N, Sym);
Jordy Rose294396b2011-08-22 23:48:23 +00003111 report->addRange(ErrorRange);
Jordan Rose785950e2012-11-02 01:53:40 +00003112 C.emitReport(report);
Jordy Rose294396b2011-08-22 23:48:23 +00003113}
3114
Jordy Rose910c4052011-09-02 06:44:22 +00003115//===----------------------------------------------------------------------===//
3116// Handle the return values of retain-count-related functions.
3117//===----------------------------------------------------------------------===//
3118
3119bool RetainCountChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
Jordy Rose76c506f2011-08-21 21:58:18 +00003120 // Get the callee. We're only interested in simple C functions.
Ted Kremenek8bef8232012-01-26 21:29:00 +00003121 ProgramStateRef state = C.getState();
Anna Zaksb805c8f2011-12-01 05:57:37 +00003122 const FunctionDecl *FD = C.getCalleeDecl(CE);
Jordy Rose76c506f2011-08-21 21:58:18 +00003123 if (!FD)
3124 return false;
3125
3126 IdentifierInfo *II = FD->getIdentifier();
3127 if (!II)
3128 return false;
3129
3130 // For now, we're only handling the functions that return aliases of their
3131 // arguments: CFRetain and CFMakeCollectable (and their families).
3132 // Eventually we should add other functions we can model entirely,
3133 // such as CFRelease, which don't invalidate their arguments or globals.
3134 if (CE->getNumArgs() != 1)
3135 return false;
3136
3137 // Get the name of the function.
3138 StringRef FName = II->getName();
3139 FName = FName.substr(FName.find_first_not_of('_'));
3140
3141 // See if it's one of the specific functions we know how to eval.
3142 bool canEval = false;
3143
Anna Zaksb805c8f2011-12-01 05:57:37 +00003144 QualType ResultTy = CE->getCallReturnType();
Jordy Rose76c506f2011-08-21 21:58:18 +00003145 if (ResultTy->isObjCIdType()) {
3146 // Handle: id NSMakeCollectable(CFTypeRef)
3147 canEval = II->isStr("NSMakeCollectable");
3148 } else if (ResultTy->isPointerType()) {
3149 // Handle: (CF|CG)Retain
3150 // CFMakeCollectable
3151 // It's okay to be a little sloppy here (CGMakeCollectable doesn't exist).
3152 if (cocoa::isRefType(ResultTy, "CF", FName) ||
3153 cocoa::isRefType(ResultTy, "CG", FName)) {
3154 canEval = isRetain(FD, FName) || isMakeCollectable(FD, FName);
3155 }
3156 }
3157
3158 if (!canEval)
3159 return false;
3160
3161 // Bind the return value.
Ted Kremenek5eca4822012-01-06 22:09:28 +00003162 const LocationContext *LCtx = C.getLocationContext();
3163 SVal RetVal = state->getSVal(CE->getArg(0), LCtx);
Jordy Rose76c506f2011-08-21 21:58:18 +00003164 if (RetVal.isUnknown()) {
3165 // If the receiver is unknown, conjure a return value.
3166 SValBuilder &SVB = C.getSValBuilder();
Ted Kremenek66c486f2012-08-22 06:26:15 +00003167 RetVal = SVB.conjureSymbolVal(0, CE, LCtx, ResultTy, C.blockCount());
Jordy Rose76c506f2011-08-21 21:58:18 +00003168 }
Ted Kremenek5eca4822012-01-06 22:09:28 +00003169 state = state->BindExpr(CE, LCtx, RetVal, false);
Jordy Rose76c506f2011-08-21 21:58:18 +00003170
Jordy Rose294396b2011-08-22 23:48:23 +00003171 // FIXME: This should not be necessary, but otherwise the argument seems to be
3172 // considered alive during the next statement.
3173 if (const MemRegion *ArgRegion = RetVal.getAsRegion()) {
3174 // Save the refcount status of the argument.
3175 SymbolRef Sym = RetVal.getAsLocSymbol();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003176 const RefVal *Binding = 0;
Jordy Rose294396b2011-08-22 23:48:23 +00003177 if (Sym)
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003178 Binding = getRefBinding(state, Sym);
Jordy Rose76c506f2011-08-21 21:58:18 +00003179
Jordy Rose294396b2011-08-22 23:48:23 +00003180 // Invalidate the argument region.
Anna Zaksbf53dfa2012-12-20 00:38:25 +00003181 state = state->invalidateRegions(ArgRegion, CE, C.blockCount(), LCtx,
3182 /*ResultsInPointerEscape*/ false);
Jordy Rose76c506f2011-08-21 21:58:18 +00003183
Jordy Rose294396b2011-08-22 23:48:23 +00003184 // Restore the refcount status of the argument.
3185 if (Binding)
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003186 state = setRefBinding(state, Sym, *Binding);
Jordy Rose294396b2011-08-22 23:48:23 +00003187 }
3188
Anna Zaks0bd6b112011-10-26 21:06:34 +00003189 C.addTransition(state);
Jordy Rose76c506f2011-08-21 21:58:18 +00003190 return true;
3191}
3192
Jordy Rose910c4052011-09-02 06:44:22 +00003193//===----------------------------------------------------------------------===//
3194// Handle return statements.
3195//===----------------------------------------------------------------------===//
Jordy Rosef53e8c72011-08-23 19:43:16 +00003196
Jordy Rose910c4052011-09-02 06:44:22 +00003197void RetainCountChecker::checkPreStmt(const ReturnStmt *S,
3198 CheckerContext &C) const {
Ted Kremeneke5715782012-02-25 02:09:09 +00003199
3200 // Only adjust the reference count if this is the top-level call frame,
3201 // and not the result of inlining. In the future, we should do
3202 // better checking even for inlined calls, and see if they match
3203 // with their expected semantics (e.g., the method should return a retained
3204 // object, etc.).
Anna Zaksfadcd5d2012-11-03 02:54:16 +00003205 if (!C.inTopFrame())
Ted Kremeneke5715782012-02-25 02:09:09 +00003206 return;
3207
Jordy Rosef53e8c72011-08-23 19:43:16 +00003208 const Expr *RetE = S->getRetValue();
3209 if (!RetE)
3210 return;
3211
Ted Kremenek8bef8232012-01-26 21:29:00 +00003212 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00003213 SymbolRef Sym =
3214 state->getSValAsScalarOrLoc(RetE, C.getLocationContext()).getAsLocSymbol();
Jordy Rosef53e8c72011-08-23 19:43:16 +00003215 if (!Sym)
3216 return;
3217
3218 // Get the reference count binding (if any).
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003219 const RefVal *T = getRefBinding(state, Sym);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003220 if (!T)
3221 return;
3222
3223 // Change the reference count.
3224 RefVal X = *T;
3225
3226 switch (X.getKind()) {
3227 case RefVal::Owned: {
3228 unsigned cnt = X.getCount();
3229 assert(cnt > 0);
3230 X.setCount(cnt - 1);
3231 X = X ^ RefVal::ReturnedOwned;
3232 break;
3233 }
3234
3235 case RefVal::NotOwned: {
3236 unsigned cnt = X.getCount();
3237 if (cnt) {
3238 X.setCount(cnt - 1);
3239 X = X ^ RefVal::ReturnedOwned;
3240 }
3241 else {
3242 X = X ^ RefVal::ReturnedNotOwned;
3243 }
3244 break;
3245 }
3246
3247 default:
3248 return;
3249 }
3250
3251 // Update the binding.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003252 state = setRefBinding(state, Sym, X);
Anna Zaks0bd6b112011-10-26 21:06:34 +00003253 ExplodedNode *Pred = C.addTransition(state);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003254
3255 // At this point we have updated the state properly.
3256 // Everything after this is merely checking to see if the return value has
3257 // been over- or under-retained.
3258
3259 // Did we cache out?
3260 if (!Pred)
3261 return;
3262
Jordy Rosef53e8c72011-08-23 19:43:16 +00003263 // Update the autorelease counts.
3264 static SimpleProgramPointTag
Jordy Rose910c4052011-09-02 06:44:22 +00003265 AutoreleaseTag("RetainCountChecker : Autorelease");
Jordan Rose4ee1c552012-12-06 18:58:18 +00003266 state = handleAutoreleaseCounts(state, Pred, &AutoreleaseTag, C, Sym, X);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003267
3268 // Did we cache out?
Jordan Rose4ee1c552012-12-06 18:58:18 +00003269 if (!state)
Jordy Rosef53e8c72011-08-23 19:43:16 +00003270 return;
3271
3272 // Get the updated binding.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003273 T = getRefBinding(state, Sym);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003274 assert(T);
3275 X = *T;
3276
3277 // Consult the summary of the enclosing method.
Jordy Rose17a38e22011-09-02 05:55:19 +00003278 RetainSummaryManager &Summaries = getSummaryManager(C);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003279 const Decl *CD = &Pred->getCodeDecl();
Jordan Rose4531b7d2012-07-02 19:27:43 +00003280 RetEffect RE = RetEffect::MakeNoRet();
Jordy Rosef53e8c72011-08-23 19:43:16 +00003281
Jordan Rose4531b7d2012-07-02 19:27:43 +00003282 // FIXME: What is the convention for blocks? Is there one?
Jordy Rosef53e8c72011-08-23 19:43:16 +00003283 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CD)) {
Jordy Roseb6cfc092011-08-25 00:10:37 +00003284 const RetainSummary *Summ = Summaries.getMethodSummary(MD);
Jordan Rose4531b7d2012-07-02 19:27:43 +00003285 RE = Summ->getRetEffect();
3286 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) {
3287 if (!isa<CXXMethodDecl>(FD)) {
3288 const RetainSummary *Summ = Summaries.getFunctionSummary(FD);
3289 RE = Summ->getRetEffect();
3290 }
Jordy Rosef53e8c72011-08-23 19:43:16 +00003291 }
3292
Jordan Rose4531b7d2012-07-02 19:27:43 +00003293 checkReturnWithRetEffect(S, C, Pred, RE, X, Sym, state);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003294}
3295
Jordy Rose910c4052011-09-02 06:44:22 +00003296void RetainCountChecker::checkReturnWithRetEffect(const ReturnStmt *S,
3297 CheckerContext &C,
3298 ExplodedNode *Pred,
3299 RetEffect RE, RefVal X,
3300 SymbolRef Sym,
Ted Kremenek8bef8232012-01-26 21:29:00 +00003301 ProgramStateRef state) const {
Jordy Rosef53e8c72011-08-23 19:43:16 +00003302 // Any leaks or other errors?
3303 if (X.isReturnedOwned() && X.getCount() == 0) {
3304 if (RE.getKind() != RetEffect::NoRet) {
3305 bool hasError = false;
Jordy Rose17a38e22011-09-02 05:55:19 +00003306 if (C.isObjCGCEnabled() && RE.getObjKind() == RetEffect::ObjC) {
Jordy Rosef53e8c72011-08-23 19:43:16 +00003307 // Things are more complicated with garbage collection. If the
3308 // returned object is suppose to be an Objective-C object, we have
3309 // a leak (as the caller expects a GC'ed object) because no
3310 // method should return ownership unless it returns a CF object.
3311 hasError = true;
3312 X = X ^ RefVal::ErrorGCLeakReturned;
3313 }
3314 else if (!RE.isOwned()) {
3315 // Either we are using GC and the returned object is a CF type
3316 // or we aren't using GC. In either case, we expect that the
3317 // enclosing method is expected to return ownership.
3318 hasError = true;
3319 X = X ^ RefVal::ErrorLeakReturned;
3320 }
3321
3322 if (hasError) {
3323 // Generate an error node.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003324 state = setRefBinding(state, Sym, X);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003325
3326 static SimpleProgramPointTag
Jordy Rose910c4052011-09-02 06:44:22 +00003327 ReturnOwnLeakTag("RetainCountChecker : ReturnsOwnLeak");
Anna Zaks0bd6b112011-10-26 21:06:34 +00003328 ExplodedNode *N = C.addTransition(state, Pred, &ReturnOwnLeakTag);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003329 if (N) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003330 const LangOptions &LOpts = C.getASTContext().getLangOpts();
Jordy Rose17a38e22011-09-02 05:55:19 +00003331 bool GCEnabled = C.isObjCGCEnabled();
Jordy Rosef53e8c72011-08-23 19:43:16 +00003332 CFRefReport *report =
Jordy Rose17a38e22011-09-02 05:55:19 +00003333 new CFRefLeakReport(*getLeakAtReturnBug(LOpts, GCEnabled),
3334 LOpts, GCEnabled, SummaryLog,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003335 N, Sym, C);
Jordan Rose785950e2012-11-02 01:53:40 +00003336 C.emitReport(report);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003337 }
3338 }
3339 }
3340 } else if (X.isReturnedNotOwned()) {
3341 if (RE.isOwned()) {
3342 // Trying to return a not owned object to a caller expecting an
3343 // owned object.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003344 state = setRefBinding(state, Sym, X ^ RefVal::ErrorReturnedNotOwned);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003345
3346 static SimpleProgramPointTag
Jordy Rose910c4052011-09-02 06:44:22 +00003347 ReturnNotOwnedTag("RetainCountChecker : ReturnNotOwnedForOwned");
Anna Zaks0bd6b112011-10-26 21:06:34 +00003348 ExplodedNode *N = C.addTransition(state, Pred, &ReturnNotOwnedTag);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003349 if (N) {
Jordy Rosed6334e12011-08-25 00:34:03 +00003350 if (!returnNotOwnedForOwned)
3351 returnNotOwnedForOwned.reset(new ReturnedNotOwnedForOwned());
3352
Jordy Rosef53e8c72011-08-23 19:43:16 +00003353 CFRefReport *report =
Jordy Rosed6334e12011-08-25 00:34:03 +00003354 new CFRefReport(*returnNotOwnedForOwned,
David Blaikie4e4d0842012-03-11 07:00:24 +00003355 C.getASTContext().getLangOpts(),
Jordy Rose17a38e22011-09-02 05:55:19 +00003356 C.isObjCGCEnabled(), SummaryLog, N, Sym);
Jordan Rose785950e2012-11-02 01:53:40 +00003357 C.emitReport(report);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003358 }
3359 }
3360 }
3361}
3362
Jordy Rose8d228632011-08-23 20:07:14 +00003363//===----------------------------------------------------------------------===//
Jordy Rose910c4052011-09-02 06:44:22 +00003364// Check various ways a symbol can be invalidated.
3365//===----------------------------------------------------------------------===//
3366
Anna Zaks390909c2011-10-06 00:43:15 +00003367void RetainCountChecker::checkBind(SVal loc, SVal val, const Stmt *S,
Jordy Rose910c4052011-09-02 06:44:22 +00003368 CheckerContext &C) const {
3369 // Are we storing to something that causes the value to "escape"?
3370 bool escapes = true;
3371
3372 // A value escapes in three possible cases (this may change):
3373 //
3374 // (1) we are binding to something that is not a memory region.
3375 // (2) we are binding to a memregion that does not have stack storage
3376 // (3) we are binding to a memregion with stack storage that the store
3377 // does not understand.
Ted Kremenek8bef8232012-01-26 21:29:00 +00003378 ProgramStateRef state = C.getState();
Jordy Rose910c4052011-09-02 06:44:22 +00003379
3380 if (loc::MemRegionVal *regionLoc = dyn_cast<loc::MemRegionVal>(&loc)) {
3381 escapes = !regionLoc->getRegion()->hasStackStorage();
3382
3383 if (!escapes) {
3384 // To test (3), generate a new state with the binding added. If it is
3385 // the same state, then it escapes (since the store cannot represent
3386 // the binding).
Anna Zakse7958da2012-05-02 00:15:40 +00003387 // Do this only if we know that the store is not supposed to generate the
3388 // same state.
3389 SVal StoredVal = state->getSVal(regionLoc->getRegion());
3390 if (StoredVal != val)
3391 escapes = (state == (state->bindLoc(*regionLoc, val)));
Jordy Rose910c4052011-09-02 06:44:22 +00003392 }
Ted Kremenekde5b4fb2012-03-27 01:12:45 +00003393 if (!escapes) {
3394 // Case 4: We do not currently model what happens when a symbol is
3395 // assigned to a struct field, so be conservative here and let the symbol
3396 // go. TODO: This could definitely be improved upon.
3397 escapes = !isa<VarRegion>(regionLoc->getRegion());
3398 }
Jordy Rose910c4052011-09-02 06:44:22 +00003399 }
3400
3401 // If our store can represent the binding and we aren't storing to something
3402 // that doesn't have local storage then just return and have the simulation
3403 // state continue as is.
3404 if (!escapes)
3405 return;
3406
3407 // Otherwise, find all symbols referenced by 'val' that we are tracking
3408 // and stop tracking them.
3409 state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
Anna Zaks0bd6b112011-10-26 21:06:34 +00003410 C.addTransition(state);
Jordy Rose910c4052011-09-02 06:44:22 +00003411}
3412
Ted Kremenek8bef8232012-01-26 21:29:00 +00003413ProgramStateRef RetainCountChecker::evalAssume(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003414 SVal Cond,
3415 bool Assumption) const {
3416
3417 // FIXME: We may add to the interface of evalAssume the list of symbols
3418 // whose assumptions have changed. For now we just iterate through the
3419 // bindings and check if any of the tracked symbols are NULL. This isn't
3420 // too bad since the number of symbols we will track in practice are
3421 // probably small and evalAssume is only called at branches and a few
3422 // other places.
Jordan Rose166d5022012-11-02 01:54:06 +00003423 RefBindingsTy B = state->get<RefBindings>();
Jordy Rose910c4052011-09-02 06:44:22 +00003424
3425 if (B.isEmpty())
3426 return state;
3427
3428 bool changed = false;
Jordan Rose166d5022012-11-02 01:54:06 +00003429 RefBindingsTy::Factory &RefBFactory = state->get_context<RefBindings>();
Jordy Rose910c4052011-09-02 06:44:22 +00003430
Jordan Rose166d5022012-11-02 01:54:06 +00003431 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Ted Kremenek47cbd0f2012-09-07 22:31:01 +00003432 // Check if the symbol is null stop tracking the symbol.
Jordan Roseec8d4202012-11-01 00:18:27 +00003433 ConstraintManager &CMgr = state->getConstraintManager();
3434 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
3435 if (AllocFailed.isConstrainedTrue()) {
Jordy Rose910c4052011-09-02 06:44:22 +00003436 changed = true;
3437 B = RefBFactory.remove(B, I.getKey());
3438 }
3439 }
3440
3441 if (changed)
3442 state = state->set<RefBindings>(B);
3443
3444 return state;
3445}
3446
Ted Kremenek8bef8232012-01-26 21:29:00 +00003447ProgramStateRef
3448RetainCountChecker::checkRegionChanges(ProgramStateRef state,
Anna Zaksbf53dfa2012-12-20 00:38:25 +00003449 const InvalidatedSymbols *invalidated,
Jordy Rose910c4052011-09-02 06:44:22 +00003450 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00003451 ArrayRef<const MemRegion *> Regions,
Jordan Rose740d4902012-07-02 19:27:35 +00003452 const CallEvent *Call) const {
Jordy Rose910c4052011-09-02 06:44:22 +00003453 if (!invalidated)
3454 return state;
3455
3456 llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
3457 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
3458 E = ExplicitRegions.end(); I != E; ++I) {
3459 if (const SymbolicRegion *SR = (*I)->StripCasts()->getAs<SymbolicRegion>())
3460 WhitelistedSymbols.insert(SR->getSymbol());
3461 }
3462
Anna Zaksbf53dfa2012-12-20 00:38:25 +00003463 for (InvalidatedSymbols::const_iterator I=invalidated->begin(),
Jordy Rose910c4052011-09-02 06:44:22 +00003464 E = invalidated->end(); I!=E; ++I) {
3465 SymbolRef sym = *I;
3466 if (WhitelistedSymbols.count(sym))
3467 continue;
3468 // Remove any existing reference-count binding.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003469 state = removeRefBinding(state, sym);
Jordy Rose910c4052011-09-02 06:44:22 +00003470 }
3471 return state;
3472}
3473
3474//===----------------------------------------------------------------------===//
Jordy Rose8d228632011-08-23 20:07:14 +00003475// Handle dead symbols and end-of-path.
3476//===----------------------------------------------------------------------===//
3477
Jordan Rose4ee1c552012-12-06 18:58:18 +00003478ProgramStateRef
3479RetainCountChecker::handleAutoreleaseCounts(ProgramStateRef state,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003480 ExplodedNode *Pred,
Jordan Rose2bce86c2012-08-18 00:30:16 +00003481 const ProgramPointTag *Tag,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003482 CheckerContext &Ctx,
Jordy Rose910c4052011-09-02 06:44:22 +00003483 SymbolRef Sym, RefVal V) const {
Jordy Rose8d228632011-08-23 20:07:14 +00003484 unsigned ACnt = V.getAutoreleaseCount();
3485
3486 // No autorelease counts? Nothing to be done.
3487 if (!ACnt)
Jordan Rose4ee1c552012-12-06 18:58:18 +00003488 return state;
Jordy Rose8d228632011-08-23 20:07:14 +00003489
Anna Zaks6a93bd52011-10-25 19:57:11 +00003490 assert(!Ctx.isObjCGCEnabled() && "Autorelease counts in GC mode?");
Jordy Rose8d228632011-08-23 20:07:14 +00003491 unsigned Cnt = V.getCount();
3492
3493 // FIXME: Handle sending 'autorelease' to already released object.
3494
3495 if (V.getKind() == RefVal::ReturnedOwned)
3496 ++Cnt;
3497
3498 if (ACnt <= Cnt) {
3499 if (ACnt == Cnt) {
3500 V.clearCounts();
3501 if (V.getKind() == RefVal::ReturnedOwned)
3502 V = V ^ RefVal::ReturnedNotOwned;
3503 else
3504 V = V ^ RefVal::NotOwned;
3505 } else {
3506 V.setCount(Cnt - ACnt);
3507 V.setAutoreleaseCount(0);
3508 }
Jordan Rose4ee1c552012-12-06 18:58:18 +00003509 return setRefBinding(state, Sym, V);
Jordy Rose8d228632011-08-23 20:07:14 +00003510 }
3511
3512 // Woah! More autorelease counts then retain counts left.
3513 // Emit hard error.
3514 V = V ^ RefVal::ErrorOverAutorelease;
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003515 state = setRefBinding(state, Sym, V);
Jordy Rose8d228632011-08-23 20:07:14 +00003516
Jordan Rosefa06f042012-08-20 18:43:42 +00003517 ExplodedNode *N = Ctx.generateSink(state, Pred, Tag);
Jordan Rose2bce86c2012-08-18 00:30:16 +00003518 if (N) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003519 SmallString<128> sbuf;
Jordy Rose8d228632011-08-23 20:07:14 +00003520 llvm::raw_svector_ostream os(sbuf);
3521 os << "Object over-autoreleased: object was sent -autorelease ";
3522 if (V.getAutoreleaseCount() > 1)
3523 os << V.getAutoreleaseCount() << " times ";
3524 os << "but the object has a +" << V.getCount() << " retain count";
3525
Jordy Rosed6334e12011-08-25 00:34:03 +00003526 if (!overAutorelease)
3527 overAutorelease.reset(new OverAutorelease());
3528
David Blaikie4e4d0842012-03-11 07:00:24 +00003529 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
Jordy Rose8d228632011-08-23 20:07:14 +00003530 CFRefReport *report =
Jordy Rosed6334e12011-08-25 00:34:03 +00003531 new CFRefReport(*overAutorelease, LOpts, /* GCEnabled = */ false,
3532 SummaryLog, N, Sym, os.str());
Jordan Rose785950e2012-11-02 01:53:40 +00003533 Ctx.emitReport(report);
Jordy Rose8d228632011-08-23 20:07:14 +00003534 }
3535
Jordan Rose4ee1c552012-12-06 18:58:18 +00003536 return 0;
Jordy Rose8d228632011-08-23 20:07:14 +00003537}
Jordy Rose38f17d62011-08-23 19:01:07 +00003538
Ted Kremenek8bef8232012-01-26 21:29:00 +00003539ProgramStateRef
3540RetainCountChecker::handleSymbolDeath(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003541 SymbolRef sid, RefVal V,
Jordy Rose38f17d62011-08-23 19:01:07 +00003542 SmallVectorImpl<SymbolRef> &Leaked) const {
Jordy Rose53376122011-08-24 04:48:19 +00003543 bool hasLeak = false;
Jordy Rose38f17d62011-08-23 19:01:07 +00003544 if (V.isOwned())
3545 hasLeak = true;
3546 else if (V.isNotOwned() || V.isReturnedOwned())
3547 hasLeak = (V.getCount() > 0);
3548
3549 if (!hasLeak)
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003550 return removeRefBinding(state, sid);
Jordy Rose38f17d62011-08-23 19:01:07 +00003551
3552 Leaked.push_back(sid);
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003553 return setRefBinding(state, sid, V ^ RefVal::ErrorLeak);
Jordy Rose38f17d62011-08-23 19:01:07 +00003554}
3555
3556ExplodedNode *
Ted Kremenek8bef8232012-01-26 21:29:00 +00003557RetainCountChecker::processLeaks(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003558 SmallVectorImpl<SymbolRef> &Leaked,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003559 CheckerContext &Ctx,
3560 ExplodedNode *Pred) const {
Jordy Rose38f17d62011-08-23 19:01:07 +00003561 // Generate an intermediate node representing the leak point.
Jordan Rose2bce86c2012-08-18 00:30:16 +00003562 ExplodedNode *N = Ctx.addTransition(state, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003563
3564 if (N) {
3565 for (SmallVectorImpl<SymbolRef>::iterator
3566 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3567
David Blaikie4e4d0842012-03-11 07:00:24 +00003568 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
Anna Zaks6a93bd52011-10-25 19:57:11 +00003569 bool GCEnabled = Ctx.isObjCGCEnabled();
Jordy Rose17a38e22011-09-02 05:55:19 +00003570 CFRefBug *BT = Pred ? getLeakWithinFunctionBug(LOpts, GCEnabled)
3571 : getLeakAtReturnBug(LOpts, GCEnabled);
Jordy Rose38f17d62011-08-23 19:01:07 +00003572 assert(BT && "BugType not initialized.");
Jordy Rose20589562011-08-24 22:39:09 +00003573
Jordy Rose17a38e22011-09-02 05:55:19 +00003574 CFRefLeakReport *report = new CFRefLeakReport(*BT, LOpts, GCEnabled,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003575 SummaryLog, N, *I, Ctx);
Jordan Rose785950e2012-11-02 01:53:40 +00003576 Ctx.emitReport(report);
Jordy Rose38f17d62011-08-23 19:01:07 +00003577 }
3578 }
3579
3580 return N;
3581}
3582
Anna Zaksaf498a22011-10-25 19:56:48 +00003583void RetainCountChecker::checkEndPath(CheckerContext &Ctx) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +00003584 ProgramStateRef state = Ctx.getState();
Jordan Rose166d5022012-11-02 01:54:06 +00003585 RefBindingsTy B = state->get<RefBindings>();
Anna Zaksaf498a22011-10-25 19:56:48 +00003586 ExplodedNode *Pred = Ctx.getPredecessor();
Jordy Rose38f17d62011-08-23 19:01:07 +00003587
Jordan Rose166d5022012-11-02 01:54:06 +00003588 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Jordan Rose4ee1c552012-12-06 18:58:18 +00003589 state = handleAutoreleaseCounts(state, Pred, /*Tag=*/0, Ctx,
3590 I->first, I->second);
Jordy Rose8d228632011-08-23 20:07:14 +00003591 if (!state)
Jordy Rose38f17d62011-08-23 19:01:07 +00003592 return;
3593 }
3594
Ted Kremenek0cf3d472012-02-07 00:24:33 +00003595 // If the current LocationContext has a parent, don't check for leaks.
3596 // We will do that later.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003597 // FIXME: we should instead check for imbalances of the retain/releases,
Ted Kremenek0cf3d472012-02-07 00:24:33 +00003598 // and suggest annotations.
3599 if (Ctx.getLocationContext()->getParent())
3600 return;
3601
Jordy Rose38f17d62011-08-23 19:01:07 +00003602 B = state->get<RefBindings>();
3603 SmallVector<SymbolRef, 10> Leaked;
3604
Jordan Rose166d5022012-11-02 01:54:06 +00003605 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I)
Jordy Rose8d228632011-08-23 20:07:14 +00003606 state = handleSymbolDeath(state, I->first, I->second, Leaked);
Jordy Rose38f17d62011-08-23 19:01:07 +00003607
Jordan Rose2bce86c2012-08-18 00:30:16 +00003608 processLeaks(state, Leaked, Ctx, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003609}
3610
3611const ProgramPointTag *
Jordy Rose910c4052011-09-02 06:44:22 +00003612RetainCountChecker::getDeadSymbolTag(SymbolRef sym) const {
Jordy Rose38f17d62011-08-23 19:01:07 +00003613 const SimpleProgramPointTag *&tag = DeadSymbolTags[sym];
3614 if (!tag) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003615 SmallString<64> buf;
Jordy Rose38f17d62011-08-23 19:01:07 +00003616 llvm::raw_svector_ostream out(buf);
Anna Zaksf62ceec2011-12-05 18:58:11 +00003617 out << "RetainCountChecker : Dead Symbol : ";
3618 sym->dumpToStream(out);
Jordy Rose38f17d62011-08-23 19:01:07 +00003619 tag = new SimpleProgramPointTag(out.str());
3620 }
3621 return tag;
3622}
3623
Jordy Rose910c4052011-09-02 06:44:22 +00003624void RetainCountChecker::checkDeadSymbols(SymbolReaper &SymReaper,
3625 CheckerContext &C) const {
Jordy Rose38f17d62011-08-23 19:01:07 +00003626 ExplodedNode *Pred = C.getPredecessor();
3627
Ted Kremenek8bef8232012-01-26 21:29:00 +00003628 ProgramStateRef state = C.getState();
Jordan Rose166d5022012-11-02 01:54:06 +00003629 RefBindingsTy B = state->get<RefBindings>();
Jordan Rose4ee1c552012-12-06 18:58:18 +00003630 SmallVector<SymbolRef, 10> Leaked;
Jordy Rose38f17d62011-08-23 19:01:07 +00003631
3632 // Update counts from autorelease pools
3633 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3634 E = SymReaper.dead_end(); I != E; ++I) {
3635 SymbolRef Sym = *I;
3636 if (const RefVal *T = B.lookup(Sym)){
3637 // Use the symbol as the tag.
3638 // FIXME: This might not be as unique as we would like.
Jordan Rose2bce86c2012-08-18 00:30:16 +00003639 const ProgramPointTag *Tag = getDeadSymbolTag(Sym);
Jordan Rose4ee1c552012-12-06 18:58:18 +00003640 state = handleAutoreleaseCounts(state, Pred, Tag, C, Sym, *T);
Jordy Rose8d228632011-08-23 20:07:14 +00003641 if (!state)
Jordy Rose38f17d62011-08-23 19:01:07 +00003642 return;
Jordan Rose4ee1c552012-12-06 18:58:18 +00003643
3644 // Fetch the new reference count from the state, and use it to handle
3645 // this symbol.
3646 state = handleSymbolDeath(state, *I, *getRefBinding(state, Sym), Leaked);
Jordy Rose38f17d62011-08-23 19:01:07 +00003647 }
3648 }
3649
Jordan Rose4ee1c552012-12-06 18:58:18 +00003650 if (Leaked.empty()) {
3651 C.addTransition(state);
3652 return;
Jordy Rose38f17d62011-08-23 19:01:07 +00003653 }
3654
Jordan Rose2bce86c2012-08-18 00:30:16 +00003655 Pred = processLeaks(state, Leaked, C, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003656
3657 // Did we cache out?
3658 if (!Pred)
3659 return;
3660
3661 // Now generate a new node that nukes the old bindings.
Jordan Rose4ee1c552012-12-06 18:58:18 +00003662 // The only bindings left at this point are the leaked symbols.
Jordan Rose166d5022012-11-02 01:54:06 +00003663 RefBindingsTy::Factory &F = state->get_context<RefBindings>();
Jordan Rose4ee1c552012-12-06 18:58:18 +00003664 B = state->get<RefBindings>();
Jordy Rose38f17d62011-08-23 19:01:07 +00003665
Jordan Rose4ee1c552012-12-06 18:58:18 +00003666 for (SmallVectorImpl<SymbolRef>::iterator I = Leaked.begin(),
3667 E = Leaked.end();
3668 I != E; ++I)
Jordy Rose38f17d62011-08-23 19:01:07 +00003669 B = F.remove(B, *I);
3670
3671 state = state->set<RefBindings>(B);
Anna Zaks0bd6b112011-10-26 21:06:34 +00003672 C.addTransition(state, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003673}
3674
Ted Kremenek8bef8232012-01-26 21:29:00 +00003675void RetainCountChecker::printState(raw_ostream &Out, ProgramStateRef State,
Jordy Rose910c4052011-09-02 06:44:22 +00003676 const char *NL, const char *Sep) const {
Jordy Rosedbd658e2011-08-28 19:11:56 +00003677
Jordan Rose166d5022012-11-02 01:54:06 +00003678 RefBindingsTy B = State->get<RefBindings>();
Jordy Rosedbd658e2011-08-28 19:11:56 +00003679
3680 if (!B.isEmpty())
3681 Out << Sep << NL;
3682
Jordan Rose166d5022012-11-02 01:54:06 +00003683 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Jordy Rosedbd658e2011-08-28 19:11:56 +00003684 Out << I->first << " : ";
3685 I->second.print(Out);
3686 Out << NL;
3687 }
Jordy Rosedbd658e2011-08-28 19:11:56 +00003688}
3689
3690//===----------------------------------------------------------------------===//
Jordy Rose910c4052011-09-02 06:44:22 +00003691// Checker registration.
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00003692//===----------------------------------------------------------------------===//
3693
Jordy Rose17a38e22011-09-02 05:55:19 +00003694void ento::registerRetainCountChecker(CheckerManager &Mgr) {
Jordy Rose910c4052011-09-02 06:44:22 +00003695 Mgr.registerChecker<RetainCountChecker>();
Jordy Rose17a38e22011-09-02 05:55:19 +00003696}
3697