blob: e731e034d8524735fa5391e92e68e41174944ea5 [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
54 // Stop tracking the argument - the effect of the call is
55 // unknown.
56 StopTracking,
57
58 // In some cases, we obtain a better summary for this checker
59 // by looking at the call site than by inlining the function.
60 // Signifies that we should stop tracking the symbol even if
61 // the function is inlined.
62 StopTrackingHard,
63
64 // The function decrements the reference count and the checker
65 // should stop tracking the argument.
66 DecRefAndStopTrackingHard, DecRefMsgAndStopTrackingHard
67 };
Ted Kremenek553cf182008-06-25 21:21:56 +000068
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000069namespace llvm {
Ted Kremenekb77449c2009-05-03 05:20:50 +000070template <> struct FoldingSetTrait<ArgEffect> {
71static inline void Profile(const ArgEffect X, FoldingSetNodeID& ID) {
72 ID.AddInteger((unsigned) X);
73}
Ted Kremenek553cf182008-06-25 21:21:56 +000074};
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000075} // end llvm namespace
76
Ted Kremenekb77449c2009-05-03 05:20:50 +000077/// ArgEffects summarizes the effects of a function/method call on all of
78/// its arguments.
79typedef llvm::ImmutableMap<unsigned,ArgEffect> ArgEffects;
80
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000081namespace {
Ted Kremenek553cf182008-06-25 21:21:56 +000082
83/// RetEffect is used to summarize a function/method call's behavior with
Mike Stump1eb44332009-09-09 15:08:12 +000084/// respect to its return value.
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +000085class RetEffect {
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000086public:
Jordy Rose76c506f2011-08-21 21:58:18 +000087 enum Kind { NoRet, OwnedSymbol, OwnedAllocatedSymbol,
John McCallf85e1932011-06-15 23:02:42 +000088 NotOwnedSymbol, GCNotOwnedSymbol, ARCNotOwnedSymbol,
Anna Zaks554067f2012-08-29 23:23:43 +000089 OwnedWhenTrackedReceiver,
90 // Treat this function as returning a non-tracked symbol even if
91 // the function has been inlined. This is used where the call
92 // site summary is more presise than the summary indirectly produced
93 // by inlining the function
94 NoRetHard
95 };
Mike Stump1eb44332009-09-09 15:08:12 +000096
97 enum ObjKind { CF, ObjC, AnyObj };
Ted Kremenek2d1652e2009-01-28 05:56:51 +000098
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000099private:
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000100 Kind K;
101 ObjKind O;
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000102
Jordy Rose76c506f2011-08-21 21:58:18 +0000103 RetEffect(Kind k, ObjKind o = AnyObj) : K(k), O(o) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000104
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000105public:
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000106 Kind getKind() const { return K; }
107
108 ObjKind getObjKind() const { return O; }
Mike Stump1eb44332009-09-09 15:08:12 +0000109
Ted Kremeneka8833552009-04-29 23:03:22 +0000110 bool isOwned() const {
Ted Kremenek78a35a32009-05-12 20:06:54 +0000111 return K == OwnedSymbol || K == OwnedAllocatedSymbol ||
112 K == OwnedWhenTrackedReceiver;
Ted Kremeneka8833552009-04-29 23:03:22 +0000113 }
Mike Stump1eb44332009-09-09 15:08:12 +0000114
Jordy Rose4df54fe2011-08-23 04:27:15 +0000115 bool operator==(const RetEffect &Other) const {
116 return K == Other.K && O == Other.O;
117 }
118
Ted Kremenek78a35a32009-05-12 20:06:54 +0000119 static RetEffect MakeOwnedWhenTrackedReceiver() {
120 return RetEffect(OwnedWhenTrackedReceiver, ObjC);
121 }
Mike Stump1eb44332009-09-09 15:08:12 +0000122
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000123 static RetEffect MakeOwned(ObjKind o, bool isAllocated = false) {
124 return RetEffect(isAllocated ? OwnedAllocatedSymbol : OwnedSymbol, o);
Mike Stump1eb44332009-09-09 15:08:12 +0000125 }
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000126 static RetEffect MakeNotOwned(ObjKind o) {
127 return RetEffect(NotOwnedSymbol, o);
Ted Kremeneke798e7c2009-04-27 19:14:45 +0000128 }
129 static RetEffect MakeGCNotOwned() {
130 return RetEffect(GCNotOwnedSymbol, ObjC);
131 }
John McCallf85e1932011-06-15 23:02:42 +0000132 static RetEffect MakeARCNotOwned() {
133 return RetEffect(ARCNotOwnedSymbol, ObjC);
134 }
Ted Kremenek553cf182008-06-25 21:21:56 +0000135 static RetEffect MakeNoRet() {
136 return RetEffect(NoRet);
Ted Kremeneka7344702008-06-23 18:02:52 +0000137 }
Anna Zaks554067f2012-08-29 23:23:43 +0000138 static RetEffect MakeNoRetHard() {
139 return RetEffect(NoRetHard);
140 }
Jordy Roseef945882012-03-18 01:26:10 +0000141
142 void Profile(llvm::FoldingSetNodeID& ID) const {
143 ID.AddInteger((unsigned) K);
144 ID.AddInteger((unsigned) O);
145 }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000146};
Mike Stump1eb44332009-09-09 15:08:12 +0000147
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000148//===----------------------------------------------------------------------===//
149// Reference-counting logic (typestate + counts).
150//===----------------------------------------------------------------------===//
Mike Stump1eb44332009-09-09 15:08:12 +0000151
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000152class RefVal {
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000153public:
154 enum Kind {
155 Owned = 0, // Owning reference.
156 NotOwned, // Reference is not owned by still valid (not freed).
157 Released, // Object has been released.
158 ReturnedOwned, // Returned object passes ownership to caller.
159 ReturnedNotOwned, // Return object does not pass ownership to caller.
160 ERROR_START,
161 ErrorDeallocNotOwned, // -dealloc called on non-owned object.
162 ErrorDeallocGC, // Calling -dealloc with GC enabled.
163 ErrorUseAfterRelease, // Object used after released.
164 ErrorReleaseNotOwned, // Release of an object that was not owned.
165 ERROR_LEAK_START,
166 ErrorLeak, // A memory leak due to excessive reference counts.
167 ErrorLeakReturned, // A memory leak due to the returning method not having
168 // the correct naming conventions.
169 ErrorGCLeakReturned,
170 ErrorOverAutorelease,
171 ErrorReturnedNotOwned
172 };
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000173
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000174private:
175 Kind kind;
176 RetEffect::ObjKind okind;
177 unsigned Cnt;
178 unsigned ACnt;
179 QualType T;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000180
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000181 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, unsigned acnt, QualType t)
182 : kind(k), okind(o), Cnt(cnt), ACnt(acnt), T(t) {}
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000183
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000184public:
185 Kind getKind() const { return kind; }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000186
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000187 RetEffect::ObjKind getObjKind() const { return okind; }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000188
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000189 unsigned getCount() const { return Cnt; }
190 unsigned getAutoreleaseCount() const { return ACnt; }
191 unsigned getCombinedCounts() const { return Cnt + ACnt; }
192 void clearCounts() { Cnt = 0; ACnt = 0; }
193 void setCount(unsigned i) { Cnt = i; }
194 void setAutoreleaseCount(unsigned i) { ACnt = i; }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000195
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000196 QualType getType() const { return T; }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000197
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000198 bool isOwned() const {
199 return getKind() == Owned;
200 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000201
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000202 bool isNotOwned() const {
203 return getKind() == NotOwned;
204 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000205
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000206 bool isReturnedOwned() const {
207 return getKind() == ReturnedOwned;
208 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000209
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000210 bool isReturnedNotOwned() const {
211 return getKind() == ReturnedNotOwned;
212 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000213
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000214 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
215 unsigned Count = 1) {
216 return RefVal(Owned, o, Count, 0, t);
217 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000218
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000219 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
220 unsigned Count = 0) {
221 return RefVal(NotOwned, o, Count, 0, t);
222 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000223
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000224 // Comparison, profiling, and pretty-printing.
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000225
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000226 bool operator==(const RefVal& X) const {
227 return kind == X.kind && Cnt == X.Cnt && T == X.T && ACnt == X.ACnt;
228 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000229
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000230 RefVal operator-(size_t i) const {
231 return RefVal(getKind(), getObjKind(), getCount() - i,
232 getAutoreleaseCount(), getType());
233 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000234
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000235 RefVal operator+(size_t i) const {
236 return RefVal(getKind(), getObjKind(), getCount() + i,
237 getAutoreleaseCount(), getType());
238 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000239
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000240 RefVal operator^(Kind k) const {
241 return RefVal(k, getObjKind(), getCount(), getAutoreleaseCount(),
242 getType());
243 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000244
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000245 RefVal autorelease() const {
246 return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount()+1,
247 getType());
248 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000249
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000250 void Profile(llvm::FoldingSetNodeID& ID) const {
251 ID.AddInteger((unsigned) kind);
252 ID.AddInteger(Cnt);
253 ID.AddInteger(ACnt);
254 ID.Add(T);
255 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000256
Ted Kremenek9c378f72011-08-12 23:37:29 +0000257 void print(raw_ostream &Out) const;
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000258};
259
Ted Kremenek9c378f72011-08-12 23:37:29 +0000260void RefVal::print(raw_ostream &Out) const {
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000261 if (!T.isNull())
Jordy Rosedbd658e2011-08-28 19:11:56 +0000262 Out << "Tracked " << T.getAsString() << '/';
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000263
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000264 switch (getKind()) {
Jordy Rose910c4052011-09-02 06:44:22 +0000265 default: llvm_unreachable("Invalid RefVal kind");
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000266 case Owned: {
267 Out << "Owned";
268 unsigned cnt = getCount();
269 if (cnt) Out << " (+ " << cnt << ")";
270 break;
271 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000272
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000273 case NotOwned: {
274 Out << "NotOwned";
275 unsigned cnt = getCount();
276 if (cnt) Out << " (+ " << cnt << ")";
277 break;
278 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000279
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000280 case ReturnedOwned: {
281 Out << "ReturnedOwned";
282 unsigned cnt = getCount();
283 if (cnt) Out << " (+ " << cnt << ")";
284 break;
285 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000286
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000287 case ReturnedNotOwned: {
288 Out << "ReturnedNotOwned";
289 unsigned cnt = getCount();
290 if (cnt) Out << " (+ " << cnt << ")";
291 break;
292 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000293
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000294 case Released:
295 Out << "Released";
296 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000297
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000298 case ErrorDeallocGC:
299 Out << "-dealloc (GC)";
300 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000301
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000302 case ErrorDeallocNotOwned:
303 Out << "-dealloc (not-owned)";
304 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000305
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000306 case ErrorLeak:
307 Out << "Leaked";
308 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000309
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000310 case ErrorLeakReturned:
311 Out << "Leaked (Bad naming)";
312 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000313
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000314 case ErrorGCLeakReturned:
315 Out << "Leaked (GC-ed at return)";
316 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000317
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000318 case ErrorUseAfterRelease:
319 Out << "Use-After-Release [ERROR]";
320 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000321
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000322 case ErrorReleaseNotOwned:
323 Out << "Release of Not-Owned [ERROR]";
324 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000325
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000326 case RefVal::ErrorOverAutorelease:
327 Out << "Over autoreleased";
328 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000329
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000330 case RefVal::ErrorReturnedNotOwned:
331 Out << "Non-owned object returned instead of owned";
332 break;
333 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000334
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000335 if (ACnt) {
336 Out << " [ARC +" << ACnt << ']';
337 }
338}
339} //end anonymous namespace
340
341//===----------------------------------------------------------------------===//
342// RefBindings - State used to track object reference counts.
343//===----------------------------------------------------------------------===//
344
Jordan Rose166d5022012-11-02 01:54:06 +0000345REGISTER_MAP_WITH_PROGRAMSTATE(RefBindings, SymbolRef, RefVal)
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000346
Anna Zaks8d6b43c2012-08-14 00:36:15 +0000347static inline const RefVal *getRefBinding(ProgramStateRef State,
348 SymbolRef Sym) {
349 return State->get<RefBindings>(Sym);
350}
351
352static inline ProgramStateRef setRefBinding(ProgramStateRef State,
353 SymbolRef Sym, RefVal Val) {
354 return State->set<RefBindings>(Sym, Val);
355}
356
357static ProgramStateRef removeRefBinding(ProgramStateRef State, SymbolRef Sym) {
358 return State->remove<RefBindings>(Sym);
359}
360
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000361//===----------------------------------------------------------------------===//
Jordy Rose910c4052011-09-02 06:44:22 +0000362// Function/Method behavior summaries.
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000363//===----------------------------------------------------------------------===//
364
365namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000366class RetainSummary {
Jordy Roseef945882012-03-18 01:26:10 +0000367 /// Args - a map of (index, ArgEffect) pairs, where index
Ted Kremenek1bffd742008-05-06 15:44:25 +0000368 /// specifies the argument (starting from 0). This can be sparsely
369 /// populated; arguments with no entry in Args use 'DefaultArgEffect'.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000370 ArgEffects Args;
Mike Stump1eb44332009-09-09 15:08:12 +0000371
Ted Kremenek1bffd742008-05-06 15:44:25 +0000372 /// DefaultArgEffect - The default ArgEffect to apply to arguments that
373 /// do not have an entry in Args.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000374 ArgEffect DefaultArgEffect;
Mike Stump1eb44332009-09-09 15:08:12 +0000375
Ted Kremenek553cf182008-06-25 21:21:56 +0000376 /// Receiver - If this summary applies to an Objective-C message expression,
377 /// this is the effect applied to the state of the receiver.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000378 ArgEffect Receiver;
Mike Stump1eb44332009-09-09 15:08:12 +0000379
Ted Kremenek553cf182008-06-25 21:21:56 +0000380 /// Ret - The effect on the return value. Used to indicate if the
Jordy Rose76c506f2011-08-21 21:58:18 +0000381 /// function/method call returns a new tracked symbol.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000382 RetEffect Ret;
Mike Stump1eb44332009-09-09 15:08:12 +0000383
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000384public:
Ted Kremenekb77449c2009-05-03 05:20:50 +0000385 RetainSummary(ArgEffects A, RetEffect R, ArgEffect defaultEff,
Jordy Rosee62e87b2011-08-20 20:55:40 +0000386 ArgEffect ReceiverEff)
387 : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000388
Ted Kremenek553cf182008-06-25 21:21:56 +0000389 /// getArg - Return the argument effect on the argument specified by
390 /// idx (starting from 0).
Ted Kremenek1ac08d62008-03-11 17:48:22 +0000391 ArgEffect getArg(unsigned idx) const {
Ted Kremenekb77449c2009-05-03 05:20:50 +0000392 if (const ArgEffect *AE = Args.lookup(idx))
393 return *AE;
Mike Stump1eb44332009-09-09 15:08:12 +0000394
Ted Kremenek1bffd742008-05-06 15:44:25 +0000395 return DefaultArgEffect;
Ted Kremenek1ac08d62008-03-11 17:48:22 +0000396 }
Ted Kremenek11fe1752011-01-27 18:43:03 +0000397
398 void addArg(ArgEffects::Factory &af, unsigned idx, ArgEffect e) {
399 Args = af.add(Args, idx, e);
400 }
Mike Stump1eb44332009-09-09 15:08:12 +0000401
Ted Kremenek885c27b2009-05-04 05:31:22 +0000402 /// setDefaultArgEffect - Set the default argument effect.
403 void setDefaultArgEffect(ArgEffect E) {
404 DefaultArgEffect = E;
405 }
Mike Stump1eb44332009-09-09 15:08:12 +0000406
Ted Kremenek553cf182008-06-25 21:21:56 +0000407 /// getRetEffect - Returns the effect on the return value of the call.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000408 RetEffect getRetEffect() const { return Ret; }
Mike Stump1eb44332009-09-09 15:08:12 +0000409
Ted Kremenek885c27b2009-05-04 05:31:22 +0000410 /// setRetEffect - Set the effect of the return value of the call.
411 void setRetEffect(RetEffect E) { Ret = E; }
Mike Stump1eb44332009-09-09 15:08:12 +0000412
Ted Kremenek12b94342011-01-27 06:54:14 +0000413
414 /// Sets the effect on the receiver of the message.
415 void setReceiverEffect(ArgEffect e) { Receiver = e; }
416
Ted Kremenek553cf182008-06-25 21:21:56 +0000417 /// getReceiverEffect - Returns the effect on the receiver of the call.
418 /// This is only meaningful if the summary applies to an ObjCMessageExpr*.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000419 ArgEffect getReceiverEffect() const { return Receiver; }
Jordy Rose4df54fe2011-08-23 04:27:15 +0000420
421 /// Test if two retain summaries are identical. Note that merely equivalent
422 /// summaries are not necessarily identical (for example, if an explicit
423 /// argument effect matches the default effect).
424 bool operator==(const RetainSummary &Other) const {
425 return Args == Other.Args && DefaultArgEffect == Other.DefaultArgEffect &&
426 Receiver == Other.Receiver && Ret == Other.Ret;
427 }
Jordy Roseef945882012-03-18 01:26:10 +0000428
429 /// Profile this summary for inclusion in a FoldingSet.
430 void Profile(llvm::FoldingSetNodeID& ID) const {
431 ID.Add(Args);
432 ID.Add(DefaultArgEffect);
433 ID.Add(Receiver);
434 ID.Add(Ret);
435 }
436
437 /// A retain summary is simple if it has no ArgEffects other than the default.
438 bool isSimple() const {
439 return Args.isEmpty();
440 }
Jordan Rose4531b7d2012-07-02 19:27:43 +0000441
442private:
443 ArgEffects getArgEffects() const { return Args; }
444 ArgEffect getDefaultArgEffect() const { return DefaultArgEffect; }
445
446 friend class RetainSummaryManager;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000447};
Ted Kremenek4f22a782008-06-23 23:30:29 +0000448} // end anonymous namespace
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000449
Ted Kremenek553cf182008-06-25 21:21:56 +0000450//===----------------------------------------------------------------------===//
451// Data structures for constructing summaries.
452//===----------------------------------------------------------------------===//
Ted Kremenek53301ba2008-06-24 03:49:48 +0000453
Ted Kremenek553cf182008-06-25 21:21:56 +0000454namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000455class ObjCSummaryKey {
Ted Kremenek553cf182008-06-25 21:21:56 +0000456 IdentifierInfo* II;
457 Selector S;
Mike Stump1eb44332009-09-09 15:08:12 +0000458public:
Ted Kremenek553cf182008-06-25 21:21:56 +0000459 ObjCSummaryKey(IdentifierInfo* ii, Selector s)
460 : II(ii), S(s) {}
461
Ted Kremenek9c378f72011-08-12 23:37:29 +0000462 ObjCSummaryKey(const ObjCInterfaceDecl *d, Selector s)
Ted Kremenek553cf182008-06-25 21:21:56 +0000463 : II(d ? d->getIdentifier() : 0), S(s) {}
Ted Kremenek70b6a832009-05-13 18:16:01 +0000464
Ted Kremenek553cf182008-06-25 21:21:56 +0000465 ObjCSummaryKey(Selector s)
466 : II(0), S(s) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000467
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000468 IdentifierInfo *getIdentifier() const { return II; }
Ted Kremenek553cf182008-06-25 21:21:56 +0000469 Selector getSelector() const { return S; }
470};
Ted Kremenek4f22a782008-06-23 23:30:29 +0000471}
472
473namespace llvm {
Ted Kremenek553cf182008-06-25 21:21:56 +0000474template <> struct DenseMapInfo<ObjCSummaryKey> {
475 static inline ObjCSummaryKey getEmptyKey() {
476 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
477 DenseMapInfo<Selector>::getEmptyKey());
478 }
Mike Stump1eb44332009-09-09 15:08:12 +0000479
Ted Kremenek553cf182008-06-25 21:21:56 +0000480 static inline ObjCSummaryKey getTombstoneKey() {
481 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
Mike Stump1eb44332009-09-09 15:08:12 +0000482 DenseMapInfo<Selector>::getTombstoneKey());
Ted Kremenek553cf182008-06-25 21:21:56 +0000483 }
Mike Stump1eb44332009-09-09 15:08:12 +0000484
Ted Kremenek553cf182008-06-25 21:21:56 +0000485 static unsigned getHashValue(const ObjCSummaryKey &V) {
Benjamin Kramer28b23072012-05-27 13:28:44 +0000486 typedef std::pair<IdentifierInfo*, Selector> PairTy;
487 return DenseMapInfo<PairTy>::getHashValue(PairTy(V.getIdentifier(),
488 V.getSelector()));
Ted Kremenek553cf182008-06-25 21:21:56 +0000489 }
Mike Stump1eb44332009-09-09 15:08:12 +0000490
Ted Kremenek553cf182008-06-25 21:21:56 +0000491 static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
Benjamin Kramer28b23072012-05-27 13:28:44 +0000492 return LHS.getIdentifier() == RHS.getIdentifier() &&
493 LHS.getSelector() == RHS.getSelector();
Ted Kremenek553cf182008-06-25 21:21:56 +0000494 }
Mike Stump1eb44332009-09-09 15:08:12 +0000495
Ted Kremenek553cf182008-06-25 21:21:56 +0000496};
Chris Lattner06159e82009-12-15 07:26:51 +0000497template <>
498struct isPodLike<ObjCSummaryKey> { static const bool value = true; };
Ted Kremenek4f22a782008-06-23 23:30:29 +0000499} // end llvm namespace
Mike Stump1eb44332009-09-09 15:08:12 +0000500
Ted Kremenek4f22a782008-06-23 23:30:29 +0000501namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000502class ObjCSummaryCache {
Ted Kremenek93edbc52011-10-05 23:54:29 +0000503 typedef llvm::DenseMap<ObjCSummaryKey, const RetainSummary *> MapTy;
Ted Kremenek553cf182008-06-25 21:21:56 +0000504 MapTy M;
505public:
506 ObjCSummaryCache() {}
Mike Stump1eb44332009-09-09 15:08:12 +0000507
Ted Kremenek93edbc52011-10-05 23:54:29 +0000508 const RetainSummary * find(const ObjCInterfaceDecl *D, Selector S) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000509 // Do a lookup with the (D,S) pair. If we find a match return
510 // the iterator.
511 ObjCSummaryKey K(D, S);
512 MapTy::iterator I = M.find(K);
Mike Stump1eb44332009-09-09 15:08:12 +0000513
Jordan Rose4531b7d2012-07-02 19:27:43 +0000514 if (I != M.end())
Ted Kremenek614cc542009-07-21 23:27:57 +0000515 return I->second;
Jordan Rose4531b7d2012-07-02 19:27:43 +0000516 if (!D)
517 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +0000518
Ted Kremenek553cf182008-06-25 21:21:56 +0000519 // Walk the super chain. If we find a hit with a parent, we'll end
520 // up returning that summary. We actually allow that key (null,S), as
521 // we cache summaries for the null ObjCInterfaceDecl* to allow us to
522 // generate initial summaries without having to worry about NSObject
523 // being declared.
524 // FIXME: We may change this at some point.
Ted Kremenek9c378f72011-08-12 23:37:29 +0000525 for (ObjCInterfaceDecl *C=D->getSuperClass() ;; C=C->getSuperClass()) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000526 if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
527 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000528
Ted Kremenek553cf182008-06-25 21:21:56 +0000529 if (!C)
Ted Kremenek614cc542009-07-21 23:27:57 +0000530 return NULL;
Ted Kremenek553cf182008-06-25 21:21:56 +0000531 }
Mike Stump1eb44332009-09-09 15:08:12 +0000532
533 // Cache the summary with original key to make the next lookup faster
Ted Kremenek553cf182008-06-25 21:21:56 +0000534 // and return the iterator.
Ted Kremenek93edbc52011-10-05 23:54:29 +0000535 const RetainSummary *Summ = I->second;
Ted Kremenek614cc542009-07-21 23:27:57 +0000536 M[K] = Summ;
537 return Summ;
Ted Kremenek553cf182008-06-25 21:21:56 +0000538 }
Mike Stump1eb44332009-09-09 15:08:12 +0000539
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000540 const RetainSummary *find(IdentifierInfo* II, Selector S) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000541 // FIXME: Class method lookup. Right now we dont' have a good way
542 // of going between IdentifierInfo* and the class hierarchy.
Ted Kremenek614cc542009-07-21 23:27:57 +0000543 MapTy::iterator I = M.find(ObjCSummaryKey(II, S));
Mike Stump1eb44332009-09-09 15:08:12 +0000544
Ted Kremenek614cc542009-07-21 23:27:57 +0000545 if (I == M.end())
546 I = M.find(ObjCSummaryKey(S));
Mike Stump1eb44332009-09-09 15:08:12 +0000547
Ted Kremenek614cc542009-07-21 23:27:57 +0000548 return I == M.end() ? NULL : I->second;
Ted Kremenek553cf182008-06-25 21:21:56 +0000549 }
Mike Stump1eb44332009-09-09 15:08:12 +0000550
Ted Kremenek93edbc52011-10-05 23:54:29 +0000551 const RetainSummary *& operator[](ObjCSummaryKey K) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000552 return M[K];
553 }
Mike Stump1eb44332009-09-09 15:08:12 +0000554
Ted Kremenek93edbc52011-10-05 23:54:29 +0000555 const RetainSummary *& operator[](Selector S) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000556 return M[ ObjCSummaryKey(S) ];
557 }
Mike Stump1eb44332009-09-09 15:08:12 +0000558};
Ted Kremenek553cf182008-06-25 21:21:56 +0000559} // end anonymous namespace
560
561//===----------------------------------------------------------------------===//
562// Data structures for managing collections of summaries.
563//===----------------------------------------------------------------------===//
564
565namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000566class RetainSummaryManager {
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000567
568 //==-----------------------------------------------------------------==//
569 // Typedefs.
570 //==-----------------------------------------------------------------==//
Mike Stump1eb44332009-09-09 15:08:12 +0000571
Ted Kremenek93edbc52011-10-05 23:54:29 +0000572 typedef llvm::DenseMap<const FunctionDecl*, const RetainSummary *>
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000573 FuncSummariesTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000574
Ted Kremenek4f22a782008-06-23 23:30:29 +0000575 typedef ObjCSummaryCache ObjCMethodSummariesTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000576
Jordy Roseef945882012-03-18 01:26:10 +0000577 typedef llvm::FoldingSetNodeWrapper<RetainSummary> CachedSummaryNode;
578
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000579 //==-----------------------------------------------------------------==//
580 // Data.
581 //==-----------------------------------------------------------------==//
Mike Stump1eb44332009-09-09 15:08:12 +0000582
Ted Kremenek553cf182008-06-25 21:21:56 +0000583 /// Ctx - The ASTContext object for the analyzed ASTs.
Ted Kremenek9c378f72011-08-12 23:37:29 +0000584 ASTContext &Ctx;
Ted Kremenek179064e2008-07-01 17:21:27 +0000585
Ted Kremenek553cf182008-06-25 21:21:56 +0000586 /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
Ted Kremenek377e2302008-04-29 05:33:51 +0000587 const bool GCEnabled;
Mike Stump1eb44332009-09-09 15:08:12 +0000588
John McCallf85e1932011-06-15 23:02:42 +0000589 /// Records whether or not the analyzed code runs in ARC mode.
590 const bool ARCEnabled;
591
Ted Kremenek553cf182008-06-25 21:21:56 +0000592 /// FuncSummaries - A map from FunctionDecls to summaries.
Mike Stump1eb44332009-09-09 15:08:12 +0000593 FuncSummariesTy FuncSummaries;
594
Ted Kremenek553cf182008-06-25 21:21:56 +0000595 /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
596 /// to summaries.
Ted Kremenek1f180c32008-06-23 22:21:20 +0000597 ObjCMethodSummariesTy ObjCClassMethodSummaries;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000598
Ted Kremenek553cf182008-06-25 21:21:56 +0000599 /// ObjCMethodSummaries - A map from selectors to summaries.
Ted Kremenek1f180c32008-06-23 22:21:20 +0000600 ObjCMethodSummariesTy ObjCMethodSummaries;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000601
Ted Kremenek553cf182008-06-25 21:21:56 +0000602 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
603 /// and all other data used by the checker.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000604 llvm::BumpPtrAllocator BPAlloc;
Mike Stump1eb44332009-09-09 15:08:12 +0000605
Ted Kremenekb77449c2009-05-03 05:20:50 +0000606 /// AF - A factory for ArgEffects objects.
Mike Stump1eb44332009-09-09 15:08:12 +0000607 ArgEffects::Factory AF;
608
Ted Kremenek553cf182008-06-25 21:21:56 +0000609 /// ScratchArgs - A holding buffer for construct ArgEffects.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000610 ArgEffects ScratchArgs;
Mike Stump1eb44332009-09-09 15:08:12 +0000611
Ted Kremenekec315332009-05-07 23:40:42 +0000612 /// ObjCAllocRetE - Default return effect for methods returning Objective-C
613 /// objects.
614 RetEffect ObjCAllocRetE;
Ted Kremenek547d4952009-06-05 23:18:01 +0000615
Mike Stump1eb44332009-09-09 15:08:12 +0000616 /// ObjCInitRetE - Default return effect for init methods returning
Ted Kremenekac02f202009-08-20 05:13:36 +0000617 /// Objective-C objects.
Ted Kremenek547d4952009-06-05 23:18:01 +0000618 RetEffect ObjCInitRetE;
Mike Stump1eb44332009-09-09 15:08:12 +0000619
Jordy Roseef945882012-03-18 01:26:10 +0000620 /// SimpleSummaries - Used for uniquing summaries that don't have special
621 /// effects.
622 llvm::FoldingSet<CachedSummaryNode> SimpleSummaries;
Mike Stump1eb44332009-09-09 15:08:12 +0000623
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000624 //==-----------------------------------------------------------------==//
625 // Methods.
626 //==-----------------------------------------------------------------==//
Mike Stump1eb44332009-09-09 15:08:12 +0000627
Ted Kremenek553cf182008-06-25 21:21:56 +0000628 /// getArgEffects - Returns a persistent ArgEffects object based on the
629 /// data in ScratchArgs.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000630 ArgEffects getArgEffects();
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000631
Mike Stump1eb44332009-09-09 15:08:12 +0000632 enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
Ted Kremenek93edbc52011-10-05 23:54:29 +0000633
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000634 const RetainSummary *getUnarySummary(const FunctionType* FT,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000635 UnaryFuncKind func);
Mike Stump1eb44332009-09-09 15:08:12 +0000636
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000637 const RetainSummary *getCFSummaryCreateRule(const FunctionDecl *FD);
638 const RetainSummary *getCFSummaryGetRule(const FunctionDecl *FD);
639 const RetainSummary *getCFCreateGetRuleSummary(const FunctionDecl *FD);
Mike Stump1eb44332009-09-09 15:08:12 +0000640
Jordy Roseef945882012-03-18 01:26:10 +0000641 const RetainSummary *getPersistentSummary(const RetainSummary &OldSumm);
Ted Kremenek706522f2008-10-29 04:07:07 +0000642
Jordy Roseef945882012-03-18 01:26:10 +0000643 const RetainSummary *getPersistentSummary(RetEffect RetEff,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000644 ArgEffect ReceiverEff = DoNothing,
645 ArgEffect DefaultEff = MayEscape) {
Jordy Roseef945882012-03-18 01:26:10 +0000646 RetainSummary Summ(getArgEffects(), RetEff, DefaultEff, ReceiverEff);
647 return getPersistentSummary(Summ);
648 }
649
Ted Kremenekc91fdf62012-05-08 00:12:09 +0000650 const RetainSummary *getDoNothingSummary() {
651 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
652 }
653
Jordy Roseef945882012-03-18 01:26:10 +0000654 const RetainSummary *getDefaultSummary() {
655 return getPersistentSummary(RetEffect::MakeNoRet(),
656 DoNothing, MayEscape);
Ted Kremenek9c32d082008-05-06 00:30:21 +0000657 }
Mike Stump1eb44332009-09-09 15:08:12 +0000658
Ted Kremenek93edbc52011-10-05 23:54:29 +0000659 const RetainSummary *getPersistentStopSummary() {
Jordy Roseef945882012-03-18 01:26:10 +0000660 return getPersistentSummary(RetEffect::MakeNoRet(),
661 StopTracking, StopTracking);
Mike Stump1eb44332009-09-09 15:08:12 +0000662 }
Ted Kremenekb3095252008-05-06 04:20:12 +0000663
Ted Kremenek1f180c32008-06-23 22:21:20 +0000664 void InitializeClassMethodSummaries();
665 void InitializeMethodSummaries();
Ted Kremenek896cd9d2008-10-23 01:56:15 +0000666private:
Ted Kremenek93edbc52011-10-05 23:54:29 +0000667 void addNSObjectClsMethSummary(Selector S, const RetainSummary *Summ) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000668 ObjCClassMethodSummaries[S] = Summ;
669 }
Mike Stump1eb44332009-09-09 15:08:12 +0000670
Ted Kremenek93edbc52011-10-05 23:54:29 +0000671 void addNSObjectMethSummary(Selector S, const RetainSummary *Summ) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000672 ObjCMethodSummaries[S] = Summ;
673 }
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +0000674
Ted Kremeneka9797122012-02-18 21:37:48 +0000675 void addClassMethSummary(const char* Cls, const char* name,
676 const RetainSummary *Summ, bool isNullary = true) {
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +0000677 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
Ted Kremeneka9797122012-02-18 21:37:48 +0000678 Selector S = isNullary ? GetNullarySelector(name, Ctx)
679 : GetUnarySelector(name, Ctx);
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +0000680 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
681 }
Mike Stump1eb44332009-09-09 15:08:12 +0000682
Ted Kremenek6c4becb2009-02-25 02:54:57 +0000683 void addInstMethSummary(const char* Cls, const char* nullaryName,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000684 const RetainSummary *Summ) {
Ted Kremenek6c4becb2009-02-25 02:54:57 +0000685 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
686 Selector S = GetNullarySelector(nullaryName, Ctx);
687 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
688 }
Mike Stump1eb44332009-09-09 15:08:12 +0000689
Ted Kremenekde4d5332009-04-24 17:50:11 +0000690 Selector generateSelector(va_list argp) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000691 SmallVector<IdentifierInfo*, 10> II;
Ted Kremenekde4d5332009-04-24 17:50:11 +0000692
Ted Kremenek9e476de2008-08-12 18:30:56 +0000693 while (const char* s = va_arg(argp, const char*))
694 II.push_back(&Ctx.Idents.get(s));
Ted Kremenekde4d5332009-04-24 17:50:11 +0000695
Mike Stump1eb44332009-09-09 15:08:12 +0000696 return Ctx.Selectors.getSelector(II.size(), &II[0]);
Ted Kremenekde4d5332009-04-24 17:50:11 +0000697 }
Mike Stump1eb44332009-09-09 15:08:12 +0000698
Ted Kremenekde4d5332009-04-24 17:50:11 +0000699 void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy& Summaries,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000700 const RetainSummary * Summ, va_list argp) {
Ted Kremenekde4d5332009-04-24 17:50:11 +0000701 Selector S = generateSelector(argp);
702 Summaries[ObjCSummaryKey(ClsII, S)] = Summ;
Ted Kremenek70a733e2008-07-18 17:24:20 +0000703 }
Mike Stump1eb44332009-09-09 15:08:12 +0000704
Ted Kremenek93edbc52011-10-05 23:54:29 +0000705 void addInstMethSummary(const char* Cls, const RetainSummary * Summ, ...) {
Ted Kremenekaf9dc272008-08-12 18:48:50 +0000706 va_list argp;
707 va_start(argp, Summ);
Ted Kremenekde4d5332009-04-24 17:50:11 +0000708 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Mike Stump1eb44332009-09-09 15:08:12 +0000709 va_end(argp);
Ted Kremenekaf9dc272008-08-12 18:48:50 +0000710 }
Mike Stump1eb44332009-09-09 15:08:12 +0000711
Ted Kremenek93edbc52011-10-05 23:54:29 +0000712 void addClsMethSummary(const char* Cls, const RetainSummary * Summ, ...) {
Ted Kremenekde4d5332009-04-24 17:50:11 +0000713 va_list argp;
714 va_start(argp, Summ);
715 addMethodSummary(&Ctx.Idents.get(Cls),ObjCClassMethodSummaries, Summ, argp);
716 va_end(argp);
717 }
Mike Stump1eb44332009-09-09 15:08:12 +0000718
Ted Kremenek93edbc52011-10-05 23:54:29 +0000719 void addClsMethSummary(IdentifierInfo *II, const RetainSummary * Summ, ...) {
Ted Kremenekde4d5332009-04-24 17:50:11 +0000720 va_list argp;
721 va_start(argp, Summ);
722 addMethodSummary(II, ObjCClassMethodSummaries, Summ, argp);
723 va_end(argp);
724 }
725
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000726public:
Mike Stump1eb44332009-09-09 15:08:12 +0000727
Ted Kremenek9c378f72011-08-12 23:37:29 +0000728 RetainSummaryManager(ASTContext &ctx, bool gcenabled, bool usesARC)
Ted Kremenek179064e2008-07-01 17:21:27 +0000729 : Ctx(ctx),
John McCallf85e1932011-06-15 23:02:42 +0000730 GCEnabled(gcenabled),
731 ARCEnabled(usesARC),
732 AF(BPAlloc), ScratchArgs(AF.getEmptyMap()),
733 ObjCAllocRetE(gcenabled
734 ? RetEffect::MakeGCNotOwned()
735 : (usesARC ? RetEffect::MakeARCNotOwned()
736 : RetEffect::MakeOwned(RetEffect::ObjC, true))),
737 ObjCInitRetE(gcenabled
738 ? RetEffect::MakeGCNotOwned()
739 : (usesARC ? RetEffect::MakeARCNotOwned()
Jordy Roseef945882012-03-18 01:26:10 +0000740 : RetEffect::MakeOwnedWhenTrackedReceiver())) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000741 InitializeClassMethodSummaries();
742 InitializeMethodSummaries();
743 }
Mike Stump1eb44332009-09-09 15:08:12 +0000744
Jordan Rose4531b7d2012-07-02 19:27:43 +0000745 const RetainSummary *getSummary(const CallEvent &Call,
746 ProgramStateRef State = 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000747
Jordan Rose4531b7d2012-07-02 19:27:43 +0000748 const RetainSummary *getFunctionSummary(const FunctionDecl *FD);
749
750 const RetainSummary *getMethodSummary(Selector S, const ObjCInterfaceDecl *ID,
Jordy Rosef3aae582012-03-17 21:13:07 +0000751 const ObjCMethodDecl *MD,
752 QualType RetTy,
753 ObjCMethodSummariesTy &CachedSummaries);
754
Jordan Rosecde8cdb2012-07-02 19:27:56 +0000755 const RetainSummary *getInstanceMethodSummary(const ObjCMethodCall &M,
Jordan Rose4531b7d2012-07-02 19:27:43 +0000756 ProgramStateRef State);
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000757
Jordan Rosecde8cdb2012-07-02 19:27:56 +0000758 const RetainSummary *getClassMethodSummary(const ObjCMethodCall &M) {
Jordan Rose4531b7d2012-07-02 19:27:43 +0000759 assert(!M.isInstanceMessage());
760 const ObjCInterfaceDecl *Class = M.getReceiverInterface();
Mike Stump1eb44332009-09-09 15:08:12 +0000761
Jordan Rose4531b7d2012-07-02 19:27:43 +0000762 return getMethodSummary(M.getSelector(), Class, M.getDecl(),
763 M.getResultType(), ObjCClassMethodSummaries);
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +0000764 }
Ted Kremenek552333c2009-04-29 17:17:48 +0000765
766 /// getMethodSummary - This version of getMethodSummary is used to query
767 /// the summary for the current method being analyzed.
Ted Kremenek93edbc52011-10-05 23:54:29 +0000768 const RetainSummary *getMethodSummary(const ObjCMethodDecl *MD) {
Ted Kremeneka8833552009-04-29 23:03:22 +0000769 const ObjCInterfaceDecl *ID = MD->getClassInterface();
Ted Kremenek70a65762009-04-30 05:41:14 +0000770 Selector S = MD->getSelector();
Ted Kremenek552333c2009-04-29 17:17:48 +0000771 QualType ResultTy = MD->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +0000772
Jordy Rosef3aae582012-03-17 21:13:07 +0000773 ObjCMethodSummariesTy *CachedSummaries;
Ted Kremenek552333c2009-04-29 17:17:48 +0000774 if (MD->isInstanceMethod())
Jordy Rosef3aae582012-03-17 21:13:07 +0000775 CachedSummaries = &ObjCMethodSummaries;
Ted Kremenek552333c2009-04-29 17:17:48 +0000776 else
Jordy Rosef3aae582012-03-17 21:13:07 +0000777 CachedSummaries = &ObjCClassMethodSummaries;
778
Jordan Rose4531b7d2012-07-02 19:27:43 +0000779 return getMethodSummary(S, ID, MD, ResultTy, *CachedSummaries);
Ted Kremenek552333c2009-04-29 17:17:48 +0000780 }
Mike Stump1eb44332009-09-09 15:08:12 +0000781
Jordy Rosef3aae582012-03-17 21:13:07 +0000782 const RetainSummary *getStandardMethodSummary(const ObjCMethodDecl *MD,
Jordan Rose4531b7d2012-07-02 19:27:43 +0000783 Selector S, QualType RetTy);
Ted Kremeneka8833552009-04-29 23:03:22 +0000784
Ted Kremenek93edbc52011-10-05 23:54:29 +0000785 void updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenek4dd8fb42009-05-09 02:58:13 +0000786 const ObjCMethodDecl *MD);
787
Ted Kremenek93edbc52011-10-05 23:54:29 +0000788 void updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenek4dd8fb42009-05-09 02:58:13 +0000789 const FunctionDecl *FD);
790
Jordan Rose4531b7d2012-07-02 19:27:43 +0000791 void updateSummaryForCall(const RetainSummary *&Summ,
792 const CallEvent &Call);
793
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000794 bool isGCEnabled() const { return GCEnabled; }
Mike Stump1eb44332009-09-09 15:08:12 +0000795
John McCallf85e1932011-06-15 23:02:42 +0000796 bool isARCEnabled() const { return ARCEnabled; }
797
798 bool isARCorGCEnabled() const { return GCEnabled || ARCEnabled; }
Jordan Rose4531b7d2012-07-02 19:27:43 +0000799
800 RetEffect getObjAllocRetEffect() const { return ObjCAllocRetE; }
801
802 friend class RetainSummaryTemplate;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000803};
Mike Stump1eb44332009-09-09 15:08:12 +0000804
Jordy Rose0fe62f82011-08-24 09:02:37 +0000805// Used to avoid allocating long-term (BPAlloc'd) memory for default retain
806// summaries. If a function or method looks like it has a default summary, but
807// it has annotations, the annotations are added to the stack-based template
808// and then copied into managed memory.
809class RetainSummaryTemplate {
810 RetainSummaryManager &Manager;
Ted Kremenek93edbc52011-10-05 23:54:29 +0000811 const RetainSummary *&RealSummary;
Jordy Rose0fe62f82011-08-24 09:02:37 +0000812 RetainSummary ScratchSummary;
813 bool Accessed;
814public:
Jordan Rose4531b7d2012-07-02 19:27:43 +0000815 RetainSummaryTemplate(const RetainSummary *&real, RetainSummaryManager &mgr)
816 : Manager(mgr), RealSummary(real), ScratchSummary(*real), Accessed(false) {}
Jordy Rose0fe62f82011-08-24 09:02:37 +0000817
818 ~RetainSummaryTemplate() {
Ted Kremenek93edbc52011-10-05 23:54:29 +0000819 if (Accessed)
Jordy Roseef945882012-03-18 01:26:10 +0000820 RealSummary = Manager.getPersistentSummary(ScratchSummary);
Jordy Rose0fe62f82011-08-24 09:02:37 +0000821 }
822
823 RetainSummary &operator*() {
824 Accessed = true;
Ted Kremenek93edbc52011-10-05 23:54:29 +0000825 return ScratchSummary;
Jordy Rose0fe62f82011-08-24 09:02:37 +0000826 }
827
828 RetainSummary *operator->() {
829 Accessed = true;
Ted Kremenek93edbc52011-10-05 23:54:29 +0000830 return &ScratchSummary;
Jordy Rose0fe62f82011-08-24 09:02:37 +0000831 }
832};
833
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000834} // end anonymous namespace
835
836//===----------------------------------------------------------------------===//
837// Implementation of checker data structures.
838//===----------------------------------------------------------------------===//
839
Ted Kremenekb77449c2009-05-03 05:20:50 +0000840ArgEffects RetainSummaryManager::getArgEffects() {
841 ArgEffects AE = ScratchArgs;
Ted Kremenek3baf6722010-11-24 00:54:37 +0000842 ScratchArgs = AF.getEmptyMap();
Ted Kremenekb77449c2009-05-03 05:20:50 +0000843 return AE;
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000844}
845
Ted Kremenek93edbc52011-10-05 23:54:29 +0000846const RetainSummary *
Jordy Roseef945882012-03-18 01:26:10 +0000847RetainSummaryManager::getPersistentSummary(const RetainSummary &OldSumm) {
848 // Unique "simple" summaries -- those without ArgEffects.
849 if (OldSumm.isSimple()) {
850 llvm::FoldingSetNodeID ID;
851 OldSumm.Profile(ID);
852
853 void *Pos;
854 CachedSummaryNode *N = SimpleSummaries.FindNodeOrInsertPos(ID, Pos);
855
856 if (!N) {
857 N = (CachedSummaryNode *) BPAlloc.Allocate<CachedSummaryNode>();
858 new (N) CachedSummaryNode(OldSumm);
859 SimpleSummaries.InsertNode(N, Pos);
860 }
861
862 return &N->getValue();
863 }
864
Ted Kremenek93edbc52011-10-05 23:54:29 +0000865 RetainSummary *Summ = (RetainSummary *) BPAlloc.Allocate<RetainSummary>();
Jordy Roseef945882012-03-18 01:26:10 +0000866 new (Summ) RetainSummary(OldSumm);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000867 return Summ;
868}
869
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000870//===----------------------------------------------------------------------===//
871// Summary creation for functions (largely uses of Core Foundation).
872//===----------------------------------------------------------------------===//
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000873
Ted Kremenek9c378f72011-08-12 23:37:29 +0000874static bool isRetain(const FunctionDecl *FD, StringRef FName) {
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000875 return FName.endswith("Retain");
Ted Kremenek12619382009-01-12 21:45:02 +0000876}
877
Ted Kremenek9c378f72011-08-12 23:37:29 +0000878static bool isRelease(const FunctionDecl *FD, StringRef FName) {
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000879 return FName.endswith("Release");
Ted Kremenek12619382009-01-12 21:45:02 +0000880}
881
Jordy Rose76c506f2011-08-21 21:58:18 +0000882static bool isMakeCollectable(const FunctionDecl *FD, StringRef FName) {
883 // FIXME: Remove FunctionDecl parameter.
884 // FIXME: Is it really okay if MakeCollectable isn't a suffix?
885 return FName.find("MakeCollectable") != StringRef::npos;
886}
887
Anna Zaks554067f2012-08-29 23:23:43 +0000888static ArgEffect getStopTrackingHardEquivalent(ArgEffect E) {
Jordan Rose4531b7d2012-07-02 19:27:43 +0000889 switch (E) {
890 case DoNothing:
891 case Autorelease:
892 case DecRefBridgedTransfered:
893 case IncRef:
894 case IncRefMsg:
895 case MakeCollectable:
896 case MayEscape:
Jordan Rose4531b7d2012-07-02 19:27:43 +0000897 case StopTracking:
Anna Zaks554067f2012-08-29 23:23:43 +0000898 case StopTrackingHard:
899 return StopTrackingHard;
Jordan Rose4531b7d2012-07-02 19:27:43 +0000900 case DecRef:
Anna Zaks554067f2012-08-29 23:23:43 +0000901 case DecRefAndStopTrackingHard:
902 return DecRefAndStopTrackingHard;
Jordan Rose4531b7d2012-07-02 19:27:43 +0000903 case DecRefMsg:
Anna Zaks554067f2012-08-29 23:23:43 +0000904 case DecRefMsgAndStopTrackingHard:
905 return DecRefMsgAndStopTrackingHard;
Jordan Rose4531b7d2012-07-02 19:27:43 +0000906 case Dealloc:
907 return Dealloc;
908 }
909
910 llvm_unreachable("Unknown ArgEffect kind");
911}
912
913void RetainSummaryManager::updateSummaryForCall(const RetainSummary *&S,
914 const CallEvent &Call) {
915 if (Call.hasNonZeroCallbackArg()) {
Anna Zaks554067f2012-08-29 23:23:43 +0000916 ArgEffect RecEffect =
917 getStopTrackingHardEquivalent(S->getReceiverEffect());
918 ArgEffect DefEffect =
919 getStopTrackingHardEquivalent(S->getDefaultArgEffect());
Jordan Rose4531b7d2012-07-02 19:27:43 +0000920
921 ArgEffects CustomArgEffects = S->getArgEffects();
922 for (ArgEffects::iterator I = CustomArgEffects.begin(),
923 E = CustomArgEffects.end();
924 I != E; ++I) {
Anna Zaks554067f2012-08-29 23:23:43 +0000925 ArgEffect Translated = getStopTrackingHardEquivalent(I->second);
Jordan Rose4531b7d2012-07-02 19:27:43 +0000926 if (Translated != DefEffect)
927 ScratchArgs = AF.add(ScratchArgs, I->first, Translated);
928 }
929
Anna Zaks554067f2012-08-29 23:23:43 +0000930 RetEffect RE = RetEffect::MakeNoRetHard();
Jordan Rose4531b7d2012-07-02 19:27:43 +0000931
932 // Special cases where the callback argument CANNOT free the return value.
933 // This can generally only happen if we know that the callback will only be
934 // called when the return value is already being deallocated.
935 if (const FunctionCall *FC = dyn_cast<FunctionCall>(&Call)) {
Jordan Rose4a25f302012-09-01 17:39:13 +0000936 if (IdentifierInfo *Name = FC->getDecl()->getIdentifier()) {
937 // When the CGBitmapContext is deallocated, the callback here will free
938 // the associated data buffer.
Jordan Rosea89f7192012-08-31 18:19:18 +0000939 if (Name->isStr("CGBitmapContextCreateWithData"))
940 RE = S->getRetEffect();
Jordan Rose4a25f302012-09-01 17:39:13 +0000941 }
Jordan Rose4531b7d2012-07-02 19:27:43 +0000942 }
943
944 S = getPersistentSummary(RE, RecEffect, DefEffect);
945 }
Anna Zaks5a901932012-08-24 00:06:12 +0000946
947 // Special case '[super init];' and '[self init];'
948 //
949 // Even though calling '[super init]' without assigning the result to self
950 // and checking if the parent returns 'nil' is a bad pattern, it is common.
951 // Additionally, our Self Init checker already warns about it. To avoid
952 // overwhelming the user with messages from both checkers, we model the case
953 // of '[super init]' in cases when it is not consumed by another expression
954 // as if the call preserves the value of 'self'; essentially, assuming it can
955 // never fail and return 'nil'.
956 // Note, we don't want to just stop tracking the value since we want the
957 // RetainCount checker to report leaks and use-after-free if SelfInit checker
958 // is turned off.
959 if (const ObjCMethodCall *MC = dyn_cast<ObjCMethodCall>(&Call)) {
960 if (MC->getMethodFamily() == OMF_init && MC->isReceiverSelfOrSuper()) {
961
962 // Check if the message is not consumed, we know it will not be used in
963 // an assignment, ex: "self = [super init]".
964 const Expr *ME = MC->getOriginExpr();
965 const LocationContext *LCtx = MC->getLocationContext();
966 ParentMap &PM = LCtx->getAnalysisDeclContext()->getParentMap();
967 if (!PM.isConsumedExpr(ME)) {
968 RetainSummaryTemplate ModifiableSummaryTemplate(S, *this);
969 ModifiableSummaryTemplate->setReceiverEffect(DoNothing);
970 ModifiableSummaryTemplate->setRetEffect(RetEffect::MakeNoRet());
971 }
972 }
973
974 }
Jordan Rose4531b7d2012-07-02 19:27:43 +0000975}
976
Anna Zaks58822c42012-05-04 22:18:39 +0000977const RetainSummary *
Jordan Rose4531b7d2012-07-02 19:27:43 +0000978RetainSummaryManager::getSummary(const CallEvent &Call,
979 ProgramStateRef State) {
980 const RetainSummary *Summ;
981 switch (Call.getKind()) {
982 case CE_Function:
983 Summ = getFunctionSummary(cast<FunctionCall>(Call).getDecl());
984 break;
985 case CE_CXXMember:
Jordan Rosefdaa3382012-07-03 22:55:57 +0000986 case CE_CXXMemberOperator:
Jordan Rose4531b7d2012-07-02 19:27:43 +0000987 case CE_Block:
988 case CE_CXXConstructor:
Jordan Rose8d276d32012-07-10 22:07:47 +0000989 case CE_CXXDestructor:
Jordan Rose70cbf3c2012-07-02 22:21:47 +0000990 case CE_CXXAllocator:
Jordan Rose4531b7d2012-07-02 19:27:43 +0000991 // FIXME: These calls are currently unsupported.
992 return getPersistentStopSummary();
Jordan Rose8919e682012-07-18 21:59:51 +0000993 case CE_ObjCMessage: {
Jordan Rosecde8cdb2012-07-02 19:27:56 +0000994 const ObjCMethodCall &Msg = cast<ObjCMethodCall>(Call);
Jordan Rose4531b7d2012-07-02 19:27:43 +0000995 if (Msg.isInstanceMessage())
996 Summ = getInstanceMethodSummary(Msg, State);
997 else
998 Summ = getClassMethodSummary(Msg);
999 break;
1000 }
1001 }
1002
1003 updateSummaryForCall(Summ, Call);
1004
1005 assert(Summ && "Unknown call type?");
1006 return Summ;
1007}
1008
1009const RetainSummary *
1010RetainSummaryManager::getFunctionSummary(const FunctionDecl *FD) {
1011 // If we don't know what function we're calling, use our default summary.
1012 if (!FD)
1013 return getDefaultSummary();
1014
Ted Kremenek891d5cc2008-04-24 17:22:33 +00001015 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001016 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001017 if (I != FuncSummaries.end())
Ted Kremenek891d5cc2008-04-24 17:22:33 +00001018 return I->second;
1019
Ted Kremeneke401a0c2009-05-04 15:34:07 +00001020 // No summary? Generate one.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001021 const RetainSummary *S = 0;
Jordan Rose15d18e12012-08-06 21:28:02 +00001022 bool AllowAnnotations = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001023
Ted Kremenek37d785b2008-07-15 16:50:12 +00001024 do {
Ted Kremenek12619382009-01-12 21:45:02 +00001025 // We generate "stop" summaries for implicitly defined functions.
1026 if (FD->isImplicit()) {
1027 S = getPersistentStopSummary();
1028 break;
Ted Kremenek37d785b2008-07-15 16:50:12 +00001029 }
Mike Stump1eb44332009-09-09 15:08:12 +00001030
John McCall183700f2009-09-21 23:43:11 +00001031 // [PR 3337] Use 'getAs<FunctionType>' to strip away any typedefs on the
Ted Kremenek99890652009-01-16 18:40:33 +00001032 // function's type.
John McCall183700f2009-09-21 23:43:11 +00001033 const FunctionType* FT = FD->getType()->getAs<FunctionType>();
Ted Kremenek48c6d182009-12-16 06:06:43 +00001034 const IdentifierInfo *II = FD->getIdentifier();
1035 if (!II)
1036 break;
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001037
1038 StringRef FName = II->getName();
Mike Stump1eb44332009-09-09 15:08:12 +00001039
Ted Kremenekbf0a4dd2009-03-05 22:11:14 +00001040 // Strip away preceding '_'. Doing this here will effect all the checks
1041 // down below.
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001042 FName = FName.substr(FName.find_first_not_of('_'));
Mike Stump1eb44332009-09-09 15:08:12 +00001043
Ted Kremenek12619382009-01-12 21:45:02 +00001044 // Inspect the result type.
1045 QualType RetTy = FT->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00001046
Ted Kremenek12619382009-01-12 21:45:02 +00001047 // FIXME: This should all be refactored into a chain of "summary lookup"
1048 // filters.
Ted Kremenek008636a2009-10-14 00:27:24 +00001049 assert(ScratchArgs.isEmpty());
Ted Kremenek39d88b02009-06-15 20:36:07 +00001050
Ted Kremenekbefc6d22012-04-26 04:32:23 +00001051 if (FName == "pthread_create" || FName == "pthread_setspecific") {
1052 // Part of: <rdar://problem/7299394> and <rdar://problem/11282706>.
1053 // This will be addressed better with IPA.
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001054 S = getPersistentStopSummary();
1055 } else if (FName == "NSMakeCollectable") {
1056 // Handle: id NSMakeCollectable(CFTypeRef)
1057 S = (RetTy->isObjCIdType())
1058 ? getUnarySummary(FT, cfmakecollectable)
1059 : getPersistentStopSummary();
Jordan Rose15d18e12012-08-06 21:28:02 +00001060 // The headers on OS X 10.8 use cf_consumed/ns_returns_retained,
1061 // but we can fully model NSMakeCollectable ourselves.
1062 AllowAnnotations = false;
Ted Kremenek061707a2012-09-06 23:47:02 +00001063 } else if (FName == "CFPlugInInstanceCreate") {
1064 S = getPersistentSummary(RetEffect::MakeNoRet());
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001065 } else if (FName == "IOBSDNameMatching" ||
1066 FName == "IOServiceMatching" ||
1067 FName == "IOServiceNameMatching" ||
Ted Kremenek537dd3a2012-05-01 05:28:27 +00001068 FName == "IORegistryEntrySearchCFProperty" ||
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001069 FName == "IORegistryEntryIDMatching" ||
1070 FName == "IOOpenFirmwarePathMatching") {
1071 // Part of <rdar://problem/6961230>. (IOKit)
1072 // This should be addressed using a API table.
1073 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1074 DoNothing, DoNothing);
1075 } else if (FName == "IOServiceGetMatchingService" ||
1076 FName == "IOServiceGetMatchingServices") {
1077 // FIXES: <rdar://problem/6326900>
1078 // This should be addressed using a API table. This strcmp is also
1079 // a little gross, but there is no need to super optimize here.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001080 ScratchArgs = AF.add(ScratchArgs, 1, DecRef);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001081 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1082 } else if (FName == "IOServiceAddNotification" ||
1083 FName == "IOServiceAddMatchingNotification") {
1084 // Part of <rdar://problem/6961230>. (IOKit)
1085 // This should be addressed using a API table.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001086 ScratchArgs = AF.add(ScratchArgs, 2, DecRef);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001087 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1088 } else if (FName == "CVPixelBufferCreateWithBytes") {
1089 // FIXES: <rdar://problem/7283567>
1090 // Eventually this can be improved by recognizing that the pixel
1091 // buffer passed to CVPixelBufferCreateWithBytes is released via
1092 // a callback and doing full IPA to make sure this is done correctly.
1093 // FIXME: This function has an out parameter that returns an
1094 // allocated object.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001095 ScratchArgs = AF.add(ScratchArgs, 7, StopTracking);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001096 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1097 } else if (FName == "CGBitmapContextCreateWithData") {
1098 // FIXES: <rdar://problem/7358899>
1099 // Eventually this can be improved by recognizing that 'releaseInfo'
1100 // passed to CGBitmapContextCreateWithData is released via
1101 // a callback and doing full IPA to make sure this is done correctly.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001102 ScratchArgs = AF.add(ScratchArgs, 8, StopTracking);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001103 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1104 DoNothing, DoNothing);
1105 } else if (FName == "CVPixelBufferCreateWithPlanarBytes") {
1106 // FIXES: <rdar://problem/7283567>
1107 // Eventually this can be improved by recognizing that the pixel
1108 // buffer passed to CVPixelBufferCreateWithPlanarBytes is released
1109 // via a callback and doing full IPA to make sure this is done
1110 // correctly.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001111 ScratchArgs = AF.add(ScratchArgs, 12, StopTracking);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001112 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenek06911d42012-03-22 06:29:41 +00001113 } else if (FName == "dispatch_set_context") {
1114 // <rdar://problem/11059275> - The analyzer currently doesn't have
1115 // a good way to reason about the finalizer function for libdispatch.
1116 // If we pass a context object that is memory managed, stop tracking it.
1117 // FIXME: this hack should possibly go away once we can handle
1118 // libdispatch finalizers.
1119 ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
1120 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenekc91fdf62012-05-08 00:12:09 +00001121 } else if (FName.startswith("NSLog")) {
1122 S = getDoNothingSummary();
Anna Zaks62a5c342012-03-30 05:48:16 +00001123 } else if (FName.startswith("NS") &&
1124 (FName.find("Insert") != StringRef::npos)) {
1125 // Whitelist NSXXInsertXX, for example NSMapInsertIfAbsent, since they can
1126 // be deallocated by NSMapRemove. (radar://11152419)
1127 ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
1128 ScratchArgs = AF.add(ScratchArgs, 2, StopTracking);
1129 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenekb04cb592009-06-11 18:17:24 +00001130 }
Mike Stump1eb44332009-09-09 15:08:12 +00001131
Ted Kremenekb04cb592009-06-11 18:17:24 +00001132 // Did we get a summary?
1133 if (S)
1134 break;
Ted Kremenek61991902009-03-17 22:43:44 +00001135
Ted Kremenek12619382009-01-12 21:45:02 +00001136 if (RetTy->isPointerType()) {
Ted Kremeneke7883652012-08-30 19:27:02 +00001137 if (FD->getAttr<CFAuditedTransferAttr>()) {
1138 S = getCFCreateGetRuleSummary(FD);
1139 break;
1140 }
1141
Ted Kremenek12619382009-01-12 21:45:02 +00001142 // For CoreFoundation ('CF') types.
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001143 if (cocoa::isRefType(RetTy, "CF", FName)) {
Ted Kremenek12619382009-01-12 21:45:02 +00001144 if (isRetain(FD, FName))
1145 S = getUnarySummary(FT, cfretain);
Jordy Rose76c506f2011-08-21 21:58:18 +00001146 else if (isMakeCollectable(FD, FName))
Ted Kremenek12619382009-01-12 21:45:02 +00001147 S = getUnarySummary(FT, cfmakecollectable);
Mike Stump1eb44332009-09-09 15:08:12 +00001148 else
John McCall7df2ff42011-10-01 00:48:56 +00001149 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek12619382009-01-12 21:45:02 +00001150
1151 break;
1152 }
1153
1154 // For CoreGraphics ('CG') types.
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001155 if (cocoa::isRefType(RetTy, "CG", FName)) {
Ted Kremenek12619382009-01-12 21:45:02 +00001156 if (isRetain(FD, FName))
1157 S = getUnarySummary(FT, cfretain);
1158 else
John McCall7df2ff42011-10-01 00:48:56 +00001159 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek12619382009-01-12 21:45:02 +00001160
1161 break;
1162 }
1163
1164 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001165 if (cocoa::isRefType(RetTy, "DADisk") ||
1166 cocoa::isRefType(RetTy, "DADissenter") ||
1167 cocoa::isRefType(RetTy, "DASessionRef")) {
John McCall7df2ff42011-10-01 00:48:56 +00001168 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek12619382009-01-12 21:45:02 +00001169 break;
1170 }
Mike Stump1eb44332009-09-09 15:08:12 +00001171
Ted Kremenek12619382009-01-12 21:45:02 +00001172 break;
1173 }
1174
1175 // Check for release functions, the only kind of functions that we care
1176 // about that don't return a pointer type.
1177 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
Ted Kremeneke7d03122010-02-08 16:45:01 +00001178 // Test for 'CGCF'.
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001179 FName = FName.substr(FName.startswith("CGCF") ? 4 : 2);
Ted Kremeneke7d03122010-02-08 16:45:01 +00001180
Ted Kremenekbf0a4dd2009-03-05 22:11:14 +00001181 if (isRelease(FD, FName))
Ted Kremenek12619382009-01-12 21:45:02 +00001182 S = getUnarySummary(FT, cfrelease);
1183 else {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001184 assert (ScratchArgs.isEmpty());
Ted Kremenek68189282009-01-29 22:45:13 +00001185 // Remaining CoreFoundation and CoreGraphics functions.
1186 // We use to assume that they all strictly followed the ownership idiom
1187 // and that ownership cannot be transferred. While this is technically
1188 // correct, many methods allow a tracked object to escape. For example:
1189 //
Mike Stump1eb44332009-09-09 15:08:12 +00001190 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
Ted Kremenek68189282009-01-29 22:45:13 +00001191 // CFDictionaryAddValue(y, key, x);
Mike Stump1eb44332009-09-09 15:08:12 +00001192 // CFRelease(x);
Ted Kremenek68189282009-01-29 22:45:13 +00001193 // ... it is okay to use 'x' since 'y' has a reference to it
1194 //
1195 // We handle this and similar cases with the follow heuristic. If the
Ted Kremenekc4843812009-08-20 00:57:22 +00001196 // function name contains "InsertValue", "SetValue", "AddValue",
1197 // "AppendValue", or "SetAttribute", then we assume that arguments may
1198 // "escape." This means that something else holds on to the object,
1199 // allowing it be used even after its local retain count drops to 0.
Benjamin Kramere45c1492010-01-11 19:46:28 +00001200 ArgEffect E = (StrInStrNoCase(FName, "InsertValue") != StringRef::npos||
1201 StrInStrNoCase(FName, "AddValue") != StringRef::npos ||
1202 StrInStrNoCase(FName, "SetValue") != StringRef::npos ||
1203 StrInStrNoCase(FName, "AppendValue") != StringRef::npos||
Benjamin Kramerc027e542010-01-11 20:15:06 +00001204 StrInStrNoCase(FName, "SetAttribute") != StringRef::npos)
Ted Kremenek68189282009-01-29 22:45:13 +00001205 ? MayEscape : DoNothing;
Mike Stump1eb44332009-09-09 15:08:12 +00001206
Ted Kremenek68189282009-01-29 22:45:13 +00001207 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek12619382009-01-12 21:45:02 +00001208 }
1209 }
Ted Kremenek37d785b2008-07-15 16:50:12 +00001210 }
1211 while (0);
Mike Stump1eb44332009-09-09 15:08:12 +00001212
Jordan Rose4531b7d2012-07-02 19:27:43 +00001213 // If we got all the way here without any luck, use a default summary.
1214 if (!S)
1215 S = getDefaultSummary();
1216
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001217 // Annotations override defaults.
Jordan Rose15d18e12012-08-06 21:28:02 +00001218 if (AllowAnnotations)
1219 updateSummaryFromAnnotations(S, FD);
Mike Stump1eb44332009-09-09 15:08:12 +00001220
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001221 FuncSummaries[FD] = S;
Mike Stump1eb44332009-09-09 15:08:12 +00001222 return S;
Ted Kremenek2fff37e2008-03-06 00:08:09 +00001223}
1224
Ted Kremenek93edbc52011-10-05 23:54:29 +00001225const RetainSummary *
John McCall7df2ff42011-10-01 00:48:56 +00001226RetainSummaryManager::getCFCreateGetRuleSummary(const FunctionDecl *FD) {
1227 if (coreFoundation::followsCreateRule(FD))
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001228 return getCFSummaryCreateRule(FD);
Mike Stump1eb44332009-09-09 15:08:12 +00001229
Ted Kremenekd368d712011-05-25 06:19:45 +00001230 return getCFSummaryGetRule(FD);
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001231}
1232
Ted Kremenek93edbc52011-10-05 23:54:29 +00001233const RetainSummary *
Ted Kremenek6ad315a2009-02-23 16:51:39 +00001234RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1235 UnaryFuncKind func) {
1236
Ted Kremenek12619382009-01-12 21:45:02 +00001237 // Sanity check that this is *really* a unary function. This can
1238 // happen if people do weird things.
Douglas Gregor72564e72009-02-26 23:50:07 +00001239 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
Ted Kremenek12619382009-01-12 21:45:02 +00001240 if (!FTP || FTP->getNumArgs() != 1)
1241 return getPersistentStopSummary();
Mike Stump1eb44332009-09-09 15:08:12 +00001242
Ted Kremenekb77449c2009-05-03 05:20:50 +00001243 assert (ScratchArgs.isEmpty());
Mike Stump1eb44332009-09-09 15:08:12 +00001244
Jordy Rose76c506f2011-08-21 21:58:18 +00001245 ArgEffect Effect;
Ted Kremenek377e2302008-04-29 05:33:51 +00001246 switch (func) {
Jordy Rose76c506f2011-08-21 21:58:18 +00001247 case cfretain: Effect = IncRef; break;
1248 case cfrelease: Effect = DecRef; break;
1249 case cfmakecollectable: Effect = MakeCollectable; break;
Ted Kremenek940b1d82008-04-10 23:44:06 +00001250 }
Jordy Rose76c506f2011-08-21 21:58:18 +00001251
1252 ScratchArgs = AF.add(ScratchArgs, 0, Effect);
1253 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001254}
1255
Ted Kremenek93edbc52011-10-05 23:54:29 +00001256const RetainSummary *
Ted Kremenek9c378f72011-08-12 23:37:29 +00001257RetainSummaryManager::getCFSummaryCreateRule(const FunctionDecl *FD) {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001258 assert (ScratchArgs.isEmpty());
Mike Stump1eb44332009-09-09 15:08:12 +00001259
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001260 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001261}
1262
Ted Kremenek93edbc52011-10-05 23:54:29 +00001263const RetainSummary *
Ted Kremenek9c378f72011-08-12 23:37:29 +00001264RetainSummaryManager::getCFSummaryGetRule(const FunctionDecl *FD) {
Mike Stump1eb44332009-09-09 15:08:12 +00001265 assert (ScratchArgs.isEmpty());
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001266 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1267 DoNothing, DoNothing);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001268}
1269
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001270//===----------------------------------------------------------------------===//
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001271// Summary creation for Selectors.
1272//===----------------------------------------------------------------------===//
1273
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001274void
Ted Kremenek93edbc52011-10-05 23:54:29 +00001275RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001276 const FunctionDecl *FD) {
1277 if (!FD)
1278 return;
1279
Jordan Rose4531b7d2012-07-02 19:27:43 +00001280 assert(Summ && "Must have a summary to add annotations to.");
1281 RetainSummaryTemplate Template(Summ, *this);
Jordy Rose4df54fe2011-08-23 04:27:15 +00001282
Ted Kremenek11fe1752011-01-27 18:43:03 +00001283 // Effects on the parameters.
1284 unsigned parm_idx = 0;
1285 for (FunctionDecl::param_const_iterator pi = FD->param_begin(),
John McCall98b8f162011-04-06 09:02:12 +00001286 pe = FD->param_end(); pi != pe; ++pi, ++parm_idx) {
Ted Kremenek11fe1752011-01-27 18:43:03 +00001287 const ParmVarDecl *pd = *pi;
1288 if (pd->getAttr<NSConsumedAttr>()) {
Jordy Rose4df54fe2011-08-23 04:27:15 +00001289 if (!GCEnabled) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001290 Template->addArg(AF, parm_idx, DecRef);
Jordy Rose4df54fe2011-08-23 04:27:15 +00001291 }
1292 } else if (pd->getAttr<CFConsumedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001293 Template->addArg(AF, parm_idx, DecRef);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001294 }
1295 }
1296
Ted Kremenekb04cb592009-06-11 18:17:24 +00001297 QualType RetTy = FD->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00001298
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001299 // Determine if there is a special return effect for this method.
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001300 if (cocoa::isCocoaObjectRef(RetTy)) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001301 if (FD->getAttr<NSReturnsRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001302 Template->setRetEffect(ObjCAllocRetE);
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001303 }
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001304 else if (FD->getAttr<CFReturnsRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001305 Template->setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenekb04cb592009-06-11 18:17:24 +00001306 }
Ted Kremenekbbf4d532012-12-20 19:36:22 +00001307 else if (FD->getAttr<NSReturnsNotRetainedAttr>() ||
1308 FD->getAttr<NSReturnsAutoreleasedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001309 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::ObjC));
Ted Kremenek60411112010-02-18 00:06:12 +00001310 }
Ted Kremenekbbf4d532012-12-20 19:36:22 +00001311 else if (FD->getAttr<CFReturnsNotRetainedAttr>())
Jordy Rose0fe62f82011-08-24 09:02:37 +00001312 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::CF));
Jordy Rose4df54fe2011-08-23 04:27:15 +00001313 }
Ted Kremenekbbf4d532012-12-20 19:36:22 +00001314 else if (RetTy->getAs<PointerType>()) {
Jordy Rose4df54fe2011-08-23 04:27:15 +00001315 if (FD->getAttr<CFReturnsRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001316 Template->setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
Jordy Rose4df54fe2011-08-23 04:27:15 +00001317 }
1318 else if (FD->getAttr<CFReturnsNotRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001319 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::CF));
Ted Kremenek60411112010-02-18 00:06:12 +00001320 }
Ted Kremenekb04cb592009-06-11 18:17:24 +00001321 }
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001322}
1323
1324void
Ted Kremenek93edbc52011-10-05 23:54:29 +00001325RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
1326 const ObjCMethodDecl *MD) {
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001327 if (!MD)
1328 return;
1329
Jordan Rose4531b7d2012-07-02 19:27:43 +00001330 assert(Summ && "Must have a valid summary to add annotations to");
1331 RetainSummaryTemplate Template(Summ, *this);
Ted Kremenek6d4b76d2009-07-06 18:30:43 +00001332 bool isTrackedLoc = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001333
Ted Kremenek12b94342011-01-27 06:54:14 +00001334 // Effects on the receiver.
1335 if (MD->getAttr<NSConsumesSelfAttr>()) {
Ted Kremenek11fe1752011-01-27 18:43:03 +00001336 if (!GCEnabled)
Jordy Rose0fe62f82011-08-24 09:02:37 +00001337 Template->setReceiverEffect(DecRefMsg);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001338 }
1339
1340 // Effects on the parameters.
1341 unsigned parm_idx = 0;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00001342 for (ObjCMethodDecl::param_const_iterator
1343 pi=MD->param_begin(), pe=MD->param_end();
Ted Kremenek11fe1752011-01-27 18:43:03 +00001344 pi != pe; ++pi, ++parm_idx) {
1345 const ParmVarDecl *pd = *pi;
1346 if (pd->getAttr<NSConsumedAttr>()) {
1347 if (!GCEnabled)
Jordy Rose0fe62f82011-08-24 09:02:37 +00001348 Template->addArg(AF, parm_idx, DecRef);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001349 }
1350 else if(pd->getAttr<CFConsumedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001351 Template->addArg(AF, parm_idx, DecRef);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001352 }
Ted Kremenek12b94342011-01-27 06:54:14 +00001353 }
1354
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001355 // Determine if there is a special return effect for this method.
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001356 if (cocoa::isCocoaObjectRef(MD->getResultType())) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001357 if (MD->getAttr<NSReturnsRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001358 Template->setRetEffect(ObjCAllocRetE);
Ted Kremenek6d4b76d2009-07-06 18:30:43 +00001359 return;
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001360 }
Ted Kremenekbbf4d532012-12-20 19:36:22 +00001361 if (MD->getAttr<NSReturnsNotRetainedAttr>() ||
1362 MD->getAttr<NSReturnsAutoreleasedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001363 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::ObjC));
Ted Kremenek60411112010-02-18 00:06:12 +00001364 return;
1365 }
Mike Stump1eb44332009-09-09 15:08:12 +00001366
Ted Kremenek6d4b76d2009-07-06 18:30:43 +00001367 isTrackedLoc = true;
Jordy Rose0fe62f82011-08-24 09:02:37 +00001368 } else {
Ted Kremenek6217b802009-07-29 21:53:49 +00001369 isTrackedLoc = MD->getResultType()->getAs<PointerType>() != NULL;
Jordy Rose0fe62f82011-08-24 09:02:37 +00001370 }
Mike Stump1eb44332009-09-09 15:08:12 +00001371
Ted Kremenek60411112010-02-18 00:06:12 +00001372 if (isTrackedLoc) {
1373 if (MD->getAttr<CFReturnsRetainedAttr>())
Jordy Rose0fe62f82011-08-24 09:02:37 +00001374 Template->setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenek60411112010-02-18 00:06:12 +00001375 else if (MD->getAttr<CFReturnsNotRetainedAttr>())
Jordy Rose0fe62f82011-08-24 09:02:37 +00001376 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::CF));
Ted Kremenek60411112010-02-18 00:06:12 +00001377 }
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001378}
1379
Ted Kremenek93edbc52011-10-05 23:54:29 +00001380const RetainSummary *
Jordy Rosef3aae582012-03-17 21:13:07 +00001381RetainSummaryManager::getStandardMethodSummary(const ObjCMethodDecl *MD,
1382 Selector S, QualType RetTy) {
Jordy Rosee921b1a2012-03-17 19:53:04 +00001383 // Any special effects?
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001384 ArgEffect ReceiverEff = DoNothing;
Jordy Rosee921b1a2012-03-17 19:53:04 +00001385 RetEffect ResultEff = RetEffect::MakeNoRet();
1386
1387 // Check the method family, and apply any default annotations.
1388 switch (MD ? MD->getMethodFamily() : S.getMethodFamily()) {
1389 case OMF_None:
1390 case OMF_performSelector:
1391 // Assume all Objective-C methods follow Cocoa Memory Management rules.
1392 // FIXME: Does the non-threaded performSelector family really belong here?
1393 // The selector could be, say, @selector(copy).
1394 if (cocoa::isCocoaObjectRef(RetTy))
1395 ResultEff = RetEffect::MakeNotOwned(RetEffect::ObjC);
1396 else if (coreFoundation::isCFObjectRef(RetTy)) {
1397 // ObjCMethodDecl currently doesn't consider CF objects as valid return
1398 // values for alloc, new, copy, or mutableCopy, so we have to
1399 // double-check with the selector. This is ugly, but there aren't that
1400 // many Objective-C methods that return CF objects, right?
1401 if (MD) {
1402 switch (S.getMethodFamily()) {
1403 case OMF_alloc:
1404 case OMF_new:
1405 case OMF_copy:
1406 case OMF_mutableCopy:
1407 ResultEff = RetEffect::MakeOwned(RetEffect::CF, true);
1408 break;
1409 default:
1410 ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1411 break;
1412 }
1413 } else {
1414 ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1415 }
1416 }
1417 break;
1418 case OMF_init:
1419 ResultEff = ObjCInitRetE;
1420 ReceiverEff = DecRefMsg;
1421 break;
1422 case OMF_alloc:
1423 case OMF_new:
1424 case OMF_copy:
1425 case OMF_mutableCopy:
1426 if (cocoa::isCocoaObjectRef(RetTy))
1427 ResultEff = ObjCAllocRetE;
1428 else if (coreFoundation::isCFObjectRef(RetTy))
1429 ResultEff = RetEffect::MakeOwned(RetEffect::CF, true);
1430 break;
1431 case OMF_autorelease:
1432 ReceiverEff = Autorelease;
1433 break;
1434 case OMF_retain:
1435 ReceiverEff = IncRefMsg;
1436 break;
1437 case OMF_release:
1438 ReceiverEff = DecRefMsg;
1439 break;
1440 case OMF_dealloc:
1441 ReceiverEff = Dealloc;
1442 break;
1443 case OMF_self:
1444 // -self is handled specially by the ExprEngine to propagate the receiver.
1445 break;
1446 case OMF_retainCount:
1447 case OMF_finalize:
1448 // These methods don't return objects.
1449 break;
1450 }
Mike Stump1eb44332009-09-09 15:08:12 +00001451
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001452 // If one of the arguments in the selector has the keyword 'delegate' we
1453 // should stop tracking the reference count for the receiver. This is
1454 // because the reference count is quite possibly handled by a delegate
1455 // method.
1456 if (S.isKeywordSelector()) {
Jordan Rose50571a92012-06-15 18:19:52 +00001457 for (unsigned i = 0, e = S.getNumArgs(); i != e; ++i) {
1458 StringRef Slot = S.getNameForSlot(i);
1459 if (Slot.substr(Slot.size() - 8).equals_lower("delegate")) {
1460 if (ResultEff == ObjCInitRetE)
Anna Zaks554067f2012-08-29 23:23:43 +00001461 ResultEff = RetEffect::MakeNoRetHard();
Jordan Rose50571a92012-06-15 18:19:52 +00001462 else
Anna Zaks554067f2012-08-29 23:23:43 +00001463 ReceiverEff = StopTrackingHard;
Jordan Rose50571a92012-06-15 18:19:52 +00001464 }
1465 }
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001466 }
Mike Stump1eb44332009-09-09 15:08:12 +00001467
Jordy Rosee921b1a2012-03-17 19:53:04 +00001468 if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing &&
1469 ResultEff.getKind() == RetEffect::NoRet)
Ted Kremenek93edbc52011-10-05 23:54:29 +00001470 return getDefaultSummary();
Mike Stump1eb44332009-09-09 15:08:12 +00001471
Jordy Rosee921b1a2012-03-17 19:53:04 +00001472 return getPersistentSummary(ResultEff, ReceiverEff, MayEscape);
Ted Kremenek250b1fa2009-04-23 23:08:22 +00001473}
1474
Ted Kremenek93edbc52011-10-05 23:54:29 +00001475const RetainSummary *
Jordan Rosecde8cdb2012-07-02 19:27:56 +00001476RetainSummaryManager::getInstanceMethodSummary(const ObjCMethodCall &Msg,
Jordan Rose4531b7d2012-07-02 19:27:43 +00001477 ProgramStateRef State) {
1478 const ObjCInterfaceDecl *ReceiverClass = 0;
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001479
Jordan Rose4531b7d2012-07-02 19:27:43 +00001480 // We do better tracking of the type of the object than the core ExprEngine.
1481 // See if we have its type in our private state.
1482 // FIXME: Eventually replace the use of state->get<RefBindings> with
1483 // a generic API for reasoning about the Objective-C types of symbolic
1484 // objects.
1485 SVal ReceiverV = Msg.getReceiverSVal();
1486 if (SymbolRef Sym = ReceiverV.getAsLocSymbol())
Anna Zaks8d6b43c2012-08-14 00:36:15 +00001487 if (const RefVal *T = getRefBinding(State, Sym))
Douglas Gregor04badcf2010-04-21 00:45:42 +00001488 if (const ObjCObjectPointerType *PT =
Jordan Rose4531b7d2012-07-02 19:27:43 +00001489 T->getType()->getAs<ObjCObjectPointerType>())
1490 ReceiverClass = PT->getInterfaceDecl();
1491
1492 // If we don't know what kind of object this is, fall back to its static type.
1493 if (!ReceiverClass)
1494 ReceiverClass = Msg.getReceiverInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00001495
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001496 // FIXME: The receiver could be a reference to a class, meaning that
1497 // we should use the class method.
Jordan Rose4531b7d2012-07-02 19:27:43 +00001498 // id x = [NSObject class];
1499 // [x performSelector:... withObject:... afterDelay:...];
1500 Selector S = Msg.getSelector();
1501 const ObjCMethodDecl *Method = Msg.getDecl();
1502 if (!Method && ReceiverClass)
1503 Method = ReceiverClass->getInstanceMethod(S);
1504
1505 return getMethodSummary(S, ReceiverClass, Method, Msg.getResultType(),
1506 ObjCMethodSummaries);
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001507}
1508
Ted Kremenek93edbc52011-10-05 23:54:29 +00001509const RetainSummary *
Jordan Rose4531b7d2012-07-02 19:27:43 +00001510RetainSummaryManager::getMethodSummary(Selector S, const ObjCInterfaceDecl *ID,
Jordy Rosef3aae582012-03-17 21:13:07 +00001511 const ObjCMethodDecl *MD, QualType RetTy,
1512 ObjCMethodSummariesTy &CachedSummaries) {
Ted Kremenek1bffd742008-05-06 15:44:25 +00001513
Ted Kremenek8711c032009-04-29 05:04:30 +00001514 // Look up a summary in our summary cache.
Jordan Rose4531b7d2012-07-02 19:27:43 +00001515 const RetainSummary *Summ = CachedSummaries.find(ID, S);
Mike Stump1eb44332009-09-09 15:08:12 +00001516
Ted Kremenek614cc542009-07-21 23:27:57 +00001517 if (!Summ) {
Jordy Rosef3aae582012-03-17 21:13:07 +00001518 Summ = getStandardMethodSummary(MD, S, RetTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001519
Ted Kremenek614cc542009-07-21 23:27:57 +00001520 // Annotations override defaults.
Jordy Rose4df54fe2011-08-23 04:27:15 +00001521 updateSummaryFromAnnotations(Summ, MD);
Mike Stump1eb44332009-09-09 15:08:12 +00001522
Ted Kremenek614cc542009-07-21 23:27:57 +00001523 // Memoize the summary.
Jordan Rose4531b7d2012-07-02 19:27:43 +00001524 CachedSummaries[ObjCSummaryKey(ID, S)] = Summ;
Ted Kremenek614cc542009-07-21 23:27:57 +00001525 }
Mike Stump1eb44332009-09-09 15:08:12 +00001526
Ted Kremeneke87450e2009-04-23 19:11:35 +00001527 return Summ;
Ted Kremenekc8395602008-05-06 21:26:51 +00001528}
1529
Mike Stump1eb44332009-09-09 15:08:12 +00001530void RetainSummaryManager::InitializeClassMethodSummaries() {
Ted Kremenekec315332009-05-07 23:40:42 +00001531 assert(ScratchArgs.isEmpty());
Mike Stump1eb44332009-09-09 15:08:12 +00001532 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek6fe2b7a2009-10-15 22:25:12 +00001533 addClassMethSummary("NSAssertionHandler", "currentHandler",
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001534 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Mike Stump1eb44332009-09-09 15:08:12 +00001535
Ted Kremenek6d348932008-10-21 15:53:15 +00001536 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001537 ScratchArgs = AF.add(ScratchArgs, 0, Autorelease);
Ted Kremenek6fe2b7a2009-10-15 22:25:12 +00001538 addClassMethSummary("NSAutoreleasePool", "addObject",
1539 getPersistentSummary(RetEffect::MakeNoRet(),
1540 DoNothing, Autorelease));
Ted Kremenek9c32d082008-05-06 00:30:21 +00001541}
1542
Ted Kremenek1f180c32008-06-23 22:21:20 +00001543void RetainSummaryManager::InitializeMethodSummaries() {
Mike Stump1eb44332009-09-09 15:08:12 +00001544
1545 assert (ScratchArgs.isEmpty());
1546
Ted Kremenekc8395602008-05-06 21:26:51 +00001547 // Create the "init" selector. It just acts as a pass-through for the
1548 // receiver.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001549 const RetainSummary *InitSumm = getPersistentSummary(ObjCInitRetE, DecRefMsg);
Ted Kremenekac02f202009-08-20 05:13:36 +00001550 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
1551
1552 // awakeAfterUsingCoder: behaves basically like an 'init' method. It
1553 // claims the receiver and returns a retained object.
1554 addNSObjectMethSummary(GetUnarySelector("awakeAfterUsingCoder", Ctx),
1555 InitSumm);
Mike Stump1eb44332009-09-09 15:08:12 +00001556
Ted Kremenekc8395602008-05-06 21:26:51 +00001557 // The next methods are allocators.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001558 const RetainSummary *AllocSumm = getPersistentSummary(ObjCAllocRetE);
1559 const RetainSummary *CFAllocSumm =
Ted Kremeneka834fb42009-08-28 19:52:12 +00001560 getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Mike Stump1eb44332009-09-09 15:08:12 +00001561
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001562 // Create the "retain" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001563 RetEffect NoRet = RetEffect::MakeNoRet();
Ted Kremenek93edbc52011-10-05 23:54:29 +00001564 const RetainSummary *Summ = getPersistentSummary(NoRet, IncRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001565 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001566
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001567 // Create the "release" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001568 Summ = getPersistentSummary(NoRet, DecRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001569 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001570
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001571 // Create the -dealloc summary.
Jordy Rose500abad2011-08-21 19:41:36 +00001572 Summ = getPersistentSummary(NoRet, Dealloc);
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001573 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001574
1575 // Create the "autorelease" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001576 Summ = getPersistentSummary(NoRet, Autorelease);
Ted Kremenek553cf182008-06-25 21:21:56 +00001577 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001578
Mike Stump1eb44332009-09-09 15:08:12 +00001579 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremenek89e202d2009-02-23 02:51:29 +00001580 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1581 // self-own themselves. However, they only do this once they are displayed.
1582 // Thus, we need to track an NSWindow's display status.
1583 // This is tracked in <rdar://problem/6062711>.
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +00001584 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001585 const RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenek78a35a32009-05-12 20:06:54 +00001586 StopTracking,
1587 StopTracking);
Mike Stump1eb44332009-09-09 15:08:12 +00001588
Ted Kremenek99d02692009-04-03 19:02:51 +00001589 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1590
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001591 // For NSPanel (which subclasses NSWindow), allocated objects are not
1592 // self-owned.
Ted Kremenek99d02692009-04-03 19:02:51 +00001593 // FIXME: For now we don't track NSPanels. object for the same reason
1594 // as for NSWindow objects.
1595 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
Mike Stump1eb44332009-09-09 15:08:12 +00001596
Jordan Rosee36d81b2013-01-31 22:06:02 +00001597 // Don't track allocated autorelease pools, as it is okay to prematurely
Ted Kremenekba67f6a2009-05-18 23:14:34 +00001598 // exit a method.
1599 addClassMethSummary("NSAutoreleasePool", "alloc", NoTrackYet);
Ted Kremeneka9797122012-02-18 21:37:48 +00001600 addClassMethSummary("NSAutoreleasePool", "allocWithZone", NoTrackYet, false);
Jordan Rosee36d81b2013-01-31 22:06:02 +00001601 addClassMethSummary("NSAutoreleasePool", "new", NoTrackYet);
Ted Kremenek553cf182008-06-25 21:21:56 +00001602
Ted Kremenek767d6492009-05-20 22:39:57 +00001603 // Create summaries QCRenderer/QCView -createSnapShotImageOfType:
1604 addInstMethSummary("QCRenderer", AllocSumm,
1605 "createSnapshotImageOfType", NULL);
1606 addInstMethSummary("QCView", AllocSumm,
1607 "createSnapshotImageOfType", NULL);
1608
Ted Kremenek211a9c62009-06-15 20:58:58 +00001609 // Create summaries for CIContext, 'createCGImage' and
Ted Kremeneka834fb42009-08-28 19:52:12 +00001610 // 'createCGLayerWithSize'. These objects are CF objects, and are not
1611 // automatically garbage collected.
1612 addInstMethSummary("CIContext", CFAllocSumm,
Ted Kremenek767d6492009-05-20 22:39:57 +00001613 "createCGImage", "fromRect", NULL);
Ted Kremeneka834fb42009-08-28 19:52:12 +00001614 addInstMethSummary("CIContext", CFAllocSumm,
Mike Stump1eb44332009-09-09 15:08:12 +00001615 "createCGImage", "fromRect", "format", "colorSpace", NULL);
Ted Kremeneka834fb42009-08-28 19:52:12 +00001616 addInstMethSummary("CIContext", CFAllocSumm, "createCGLayerWithSize",
Ted Kremenek211a9c62009-06-15 20:58:58 +00001617 "info", NULL);
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001618}
1619
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001620//===----------------------------------------------------------------------===//
Ted Kremenekc887d132009-04-29 18:50:19 +00001621// Error reporting.
1622//===----------------------------------------------------------------------===//
Ted Kremenekc887d132009-04-29 18:50:19 +00001623namespace {
Jordy Roseec9ef852011-08-23 20:55:48 +00001624 typedef llvm::DenseMap<const ExplodedNode *, const RetainSummary *>
1625 SummaryLogTy;
1626
Ted Kremenekc887d132009-04-29 18:50:19 +00001627 //===-------------===//
1628 // Bug Descriptions. //
Mike Stump1eb44332009-09-09 15:08:12 +00001629 //===-------------===//
1630
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001631 class CFRefBug : public BugType {
Ted Kremenekc887d132009-04-29 18:50:19 +00001632 protected:
Jordy Rose35c86952011-08-24 05:47:39 +00001633 CFRefBug(StringRef name)
Ted Kremenek6fd45052012-04-05 20:43:28 +00001634 : BugType(name, categories::MemoryCoreFoundationObjectiveC) {}
Ted Kremenekc887d132009-04-29 18:50:19 +00001635 public:
Mike Stump1eb44332009-09-09 15:08:12 +00001636
Ted Kremenekc887d132009-04-29 18:50:19 +00001637 // FIXME: Eventually remove.
Jordy Rose35c86952011-08-24 05:47:39 +00001638 virtual const char *getDescription() const = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001639
Ted Kremenekc887d132009-04-29 18:50:19 +00001640 virtual bool isLeak() const { return false; }
1641 };
Mike Stump1eb44332009-09-09 15:08:12 +00001642
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001643 class UseAfterRelease : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001644 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001645 UseAfterRelease() : CFRefBug("Use-after-release") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001646
Jordy Rose35c86952011-08-24 05:47:39 +00001647 const char *getDescription() const {
Ted Kremenekc887d132009-04-29 18:50:19 +00001648 return "Reference-counted object is used after it is released";
Mike Stump1eb44332009-09-09 15:08:12 +00001649 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001650 };
Mike Stump1eb44332009-09-09 15:08:12 +00001651
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001652 class BadRelease : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001653 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001654 BadRelease() : CFRefBug("Bad release") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001655
Jordy Rose35c86952011-08-24 05:47:39 +00001656 const char *getDescription() const {
Ted Kremenekbb206fd2009-10-01 17:31:50 +00001657 return "Incorrect decrement of the reference count of an object that is "
1658 "not owned at this point by the caller";
Ted Kremenekc887d132009-04-29 18:50:19 +00001659 }
1660 };
Mike Stump1eb44332009-09-09 15:08:12 +00001661
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001662 class DeallocGC : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001663 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001664 DeallocGC()
1665 : CFRefBug("-dealloc called while using garbage collection") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001666
Ted Kremenekc887d132009-04-29 18:50:19 +00001667 const char *getDescription() const {
Ted Kremenek369de562009-05-09 00:10:05 +00001668 return "-dealloc called while using garbage collection";
Ted Kremenekc887d132009-04-29 18:50:19 +00001669 }
1670 };
Mike Stump1eb44332009-09-09 15:08:12 +00001671
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001672 class DeallocNotOwned : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001673 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001674 DeallocNotOwned()
1675 : CFRefBug("-dealloc sent to non-exclusively owned object") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001676
Ted Kremenekc887d132009-04-29 18:50:19 +00001677 const char *getDescription() const {
1678 return "-dealloc sent to object that may be referenced elsewhere";
1679 }
Mike Stump1eb44332009-09-09 15:08:12 +00001680 };
1681
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001682 class OverAutorelease : public CFRefBug {
Ted Kremenek369de562009-05-09 00:10:05 +00001683 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001684 OverAutorelease()
1685 : CFRefBug("Object sent -autorelease too many times") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001686
Ted Kremenek369de562009-05-09 00:10:05 +00001687 const char *getDescription() const {
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001688 return "Object sent -autorelease too many times";
Ted Kremenek369de562009-05-09 00:10:05 +00001689 }
1690 };
Mike Stump1eb44332009-09-09 15:08:12 +00001691
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001692 class ReturnedNotOwnedForOwned : public CFRefBug {
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001693 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001694 ReturnedNotOwnedForOwned()
1695 : CFRefBug("Method should return an owned object") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001696
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001697 const char *getDescription() const {
Jordy Rose5b5402b2011-07-15 22:17:54 +00001698 return "Object with a +0 retain count returned to caller where a +1 "
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001699 "(owning) retain count is expected";
1700 }
1701 };
Mike Stump1eb44332009-09-09 15:08:12 +00001702
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001703 class Leak : public CFRefBug {
Benjamin Kramerfacde172012-06-06 17:32:50 +00001704 public:
1705 Leak(StringRef name)
1706 : CFRefBug(name) {
Jordy Rosedb92bb62011-08-25 01:14:38 +00001707 // Leaks should not be reported if they are post-dominated by a sink.
1708 setSuppressOnSink(true);
1709 }
Mike Stump1eb44332009-09-09 15:08:12 +00001710
Jordy Rose35c86952011-08-24 05:47:39 +00001711 const char *getDescription() const { return ""; }
Mike Stump1eb44332009-09-09 15:08:12 +00001712
Ted Kremenekc887d132009-04-29 18:50:19 +00001713 bool isLeak() const { return true; }
1714 };
Mike Stump1eb44332009-09-09 15:08:12 +00001715
Ted Kremenekc887d132009-04-29 18:50:19 +00001716 //===---------===//
1717 // Bug Reports. //
1718 //===---------===//
Mike Stump1eb44332009-09-09 15:08:12 +00001719
Jordy Rose01153492012-03-24 02:45:35 +00001720 class CFRefReportVisitor : public BugReporterVisitorImpl<CFRefReportVisitor> {
Anna Zaks23f395e2011-08-20 01:27:22 +00001721 protected:
Anna Zaksdc757b02011-08-19 23:21:56 +00001722 SymbolRef Sym;
Jordy Roseec9ef852011-08-23 20:55:48 +00001723 const SummaryLogTy &SummaryLog;
Jordy Rose35c86952011-08-24 05:47:39 +00001724 bool GCEnabled;
Anna Zaks23f395e2011-08-20 01:27:22 +00001725
Anna Zaksdc757b02011-08-19 23:21:56 +00001726 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001727 CFRefReportVisitor(SymbolRef sym, bool gcEnabled, const SummaryLogTy &log)
1728 : Sym(sym), SummaryLog(log), GCEnabled(gcEnabled) {}
Anna Zaksdc757b02011-08-19 23:21:56 +00001729
Anna Zaks23f395e2011-08-20 01:27:22 +00001730 virtual void Profile(llvm::FoldingSetNodeID &ID) const {
Anna Zaksdc757b02011-08-19 23:21:56 +00001731 static int x = 0;
1732 ID.AddPointer(&x);
1733 ID.AddPointer(Sym);
1734 }
1735
Anna Zaks23f395e2011-08-20 01:27:22 +00001736 virtual PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
1737 const ExplodedNode *PrevN,
1738 BugReporterContext &BRC,
1739 BugReport &BR);
1740
1741 virtual PathDiagnosticPiece *getEndPath(BugReporterContext &BRC,
1742 const ExplodedNode *N,
1743 BugReport &BR);
1744 };
1745
1746 class CFRefLeakReportVisitor : public CFRefReportVisitor {
1747 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001748 CFRefLeakReportVisitor(SymbolRef sym, bool GCEnabled,
Jordy Roseec9ef852011-08-23 20:55:48 +00001749 const SummaryLogTy &log)
Jordy Rose35c86952011-08-24 05:47:39 +00001750 : CFRefReportVisitor(sym, GCEnabled, log) {}
Anna Zaks23f395e2011-08-20 01:27:22 +00001751
1752 PathDiagnosticPiece *getEndPath(BugReporterContext &BRC,
1753 const ExplodedNode *N,
1754 BugReport &BR);
Jordy Rose01153492012-03-24 02:45:35 +00001755
1756 virtual BugReporterVisitor *clone() const {
1757 // The curiously-recurring template pattern only works for one level of
1758 // subclassing. Rather than make a new template base for
1759 // CFRefReportVisitor, we simply override clone() to do the right thing.
1760 // This could be trouble someday if BugReporterVisitorImpl is ever
1761 // used for something else besides a convenient implementation of clone().
1762 return new CFRefLeakReportVisitor(*this);
1763 }
Anna Zaksdc757b02011-08-19 23:21:56 +00001764 };
1765
Anna Zakse172e8b2011-08-17 23:00:25 +00001766 class CFRefReport : public BugReport {
Jordy Rose20589562011-08-24 22:39:09 +00001767 void addGCModeDescription(const LangOptions &LOpts, bool GCEnabled);
Jordy Rose35c86952011-08-24 05:47:39 +00001768
Ted Kremenekc887d132009-04-29 18:50:19 +00001769 public:
Jordy Rose20589562011-08-24 22:39:09 +00001770 CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1771 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1772 bool registerVisitor = true)
Anna Zaksedf4dae2011-08-22 18:54:07 +00001773 : BugReport(D, D.getDescription(), n) {
Anna Zaks23f395e2011-08-20 01:27:22 +00001774 if (registerVisitor)
Jordy Rose20589562011-08-24 22:39:09 +00001775 addVisitor(new CFRefReportVisitor(sym, GCEnabled, Log));
1776 addGCModeDescription(LOpts, GCEnabled);
Anna Zaksdc757b02011-08-19 23:21:56 +00001777 }
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001778
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 StringRef endText)
Anna Zaksedf4dae2011-08-22 18:54:07 +00001782 : BugReport(D, D.getDescription(), endText, n) {
Jordy Rose20589562011-08-24 22:39:09 +00001783 addVisitor(new CFRefReportVisitor(sym, GCEnabled, Log));
1784 addGCModeDescription(LOpts, GCEnabled);
Anna Zaksdc757b02011-08-19 23:21:56 +00001785 }
Mike Stump1eb44332009-09-09 15:08:12 +00001786
Anna Zakse172e8b2011-08-17 23:00:25 +00001787 virtual std::pair<ranges_iterator, ranges_iterator> getRanges() {
Anna Zaksedf4dae2011-08-22 18:54:07 +00001788 const CFRefBug& BugTy = static_cast<CFRefBug&>(getBugType());
1789 if (!BugTy.isLeak())
Anna Zakse172e8b2011-08-17 23:00:25 +00001790 return BugReport::getRanges();
Ted Kremenekc887d132009-04-29 18:50:19 +00001791 else
Argyrios Kyrtzidis640ccf02010-12-04 01:12:15 +00001792 return std::make_pair(ranges_iterator(), ranges_iterator());
Ted Kremenekc887d132009-04-29 18:50:19 +00001793 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001794 };
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001795
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001796 class CFRefLeakReport : public CFRefReport {
Ted Kremenekc887d132009-04-29 18:50:19 +00001797 const MemRegion* AllocBinding;
Anna Zaks23f395e2011-08-20 01:27:22 +00001798
Ted Kremenekc887d132009-04-29 18:50:19 +00001799 public:
Jordy Rose20589562011-08-24 22:39:09 +00001800 CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1801 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
Anna Zaks6a93bd52011-10-25 19:57:11 +00001802 CheckerContext &Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001803
Anna Zaks590dd8e2011-09-20 21:38:35 +00001804 PathDiagnosticLocation getLocation(const SourceManager &SM) const {
1805 assert(Location.isValid());
1806 return Location;
1807 }
Mike Stump1eb44332009-09-09 15:08:12 +00001808 };
Ted Kremenekc887d132009-04-29 18:50:19 +00001809} // end anonymous namespace
1810
Jordy Rose20589562011-08-24 22:39:09 +00001811void CFRefReport::addGCModeDescription(const LangOptions &LOpts,
1812 bool GCEnabled) {
Jordy Rosef95b19d2011-08-24 20:38:42 +00001813 const char *GCModeDescription = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001814
Douglas Gregore289d812011-09-13 17:21:33 +00001815 switch (LOpts.getGC()) {
Anna Zaks7f2531c2011-08-22 20:31:28 +00001816 case LangOptions::GCOnly:
Jordy Rose20589562011-08-24 22:39:09 +00001817 assert(GCEnabled);
Jordy Rose35c86952011-08-24 05:47:39 +00001818 GCModeDescription = "Code is compiled to only use garbage collection";
1819 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001820
Anna Zaks7f2531c2011-08-22 20:31:28 +00001821 case LangOptions::NonGC:
Jordy Rose20589562011-08-24 22:39:09 +00001822 assert(!GCEnabled);
Jordy Rose35c86952011-08-24 05:47:39 +00001823 GCModeDescription = "Code is compiled to use reference counts";
1824 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001825
Anna Zaks7f2531c2011-08-22 20:31:28 +00001826 case LangOptions::HybridGC:
Jordy Rose20589562011-08-24 22:39:09 +00001827 if (GCEnabled) {
Jordy Rose35c86952011-08-24 05:47:39 +00001828 GCModeDescription = "Code is compiled to use either garbage collection "
1829 "(GC) or reference counts (non-GC). The bug occurs "
1830 "with GC enabled";
1831 break;
1832 } else {
1833 GCModeDescription = "Code is compiled to use either garbage collection "
1834 "(GC) or reference counts (non-GC). The bug occurs "
1835 "in non-GC mode";
1836 break;
Anna Zaks7f2531c2011-08-22 20:31:28 +00001837 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001838 }
Jordy Rose35c86952011-08-24 05:47:39 +00001839
Jordy Rosef95b19d2011-08-24 20:38:42 +00001840 assert(GCModeDescription && "invalid/unknown GC mode");
Jordy Rose35c86952011-08-24 05:47:39 +00001841 addExtraText(GCModeDescription);
Ted Kremenekc887d132009-04-29 18:50:19 +00001842}
1843
Jordy Rose910c4052011-09-02 06:44:22 +00001844// FIXME: This should be a method on SmallVector.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001845static inline bool contains(const SmallVectorImpl<ArgEffect>& V,
Ted Kremenekc887d132009-04-29 18:50:19 +00001846 ArgEffect X) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001847 for (SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
Ted Kremenekc887d132009-04-29 18:50:19 +00001848 I!=E; ++I)
1849 if (*I == X) return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001850
Ted Kremenekc887d132009-04-29 18:50:19 +00001851 return false;
1852}
1853
Jordy Rose70fdbc32012-05-12 05:10:43 +00001854static bool isNumericLiteralExpression(const Expr *E) {
1855 // FIXME: This set of cases was copied from SemaExprObjC.
1856 return isa<IntegerLiteral>(E) ||
1857 isa<CharacterLiteral>(E) ||
1858 isa<FloatingLiteral>(E) ||
1859 isa<ObjCBoolLiteralExpr>(E) ||
1860 isa<CXXBoolLiteralExpr>(E);
1861}
1862
Anna Zaksdc757b02011-08-19 23:21:56 +00001863PathDiagnosticPiece *CFRefReportVisitor::VisitNode(const ExplodedNode *N,
1864 const ExplodedNode *PrevN,
1865 BugReporterContext &BRC,
1866 BugReport &BR) {
Jordan Rose28038f32012-07-10 22:07:42 +00001867 // FIXME: We will eventually need to handle non-statement-based events
1868 // (__attribute__((cleanup))).
Jordy Rosef53e8c72011-08-23 19:43:16 +00001869 if (!isa<StmtPoint>(N->getLocation()))
Ted Kremenek2033a952009-05-13 07:12:33 +00001870 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001871
Ted Kremenek8966bc12009-05-06 21:39:49 +00001872 // Check if the type state has changed.
Ted Kremenek8bef8232012-01-26 21:29:00 +00001873 ProgramStateRef PrevSt = PrevN->getState();
1874 ProgramStateRef CurrSt = N->getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001875 const LocationContext *LCtx = N->getLocationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00001876
Anna Zaks8d6b43c2012-08-14 00:36:15 +00001877 const RefVal* CurrT = getRefBinding(CurrSt, Sym);
Ted Kremenekc887d132009-04-29 18:50:19 +00001878 if (!CurrT) return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001879
Ted Kremenekb65be702009-06-18 01:23:53 +00001880 const RefVal &CurrV = *CurrT;
Anna Zaks8d6b43c2012-08-14 00:36:15 +00001881 const RefVal *PrevT = getRefBinding(PrevSt, Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00001882
Ted Kremenekc887d132009-04-29 18:50:19 +00001883 // Create a string buffer to constain all the useful things we want
1884 // to tell the user.
1885 std::string sbuf;
1886 llvm::raw_string_ostream os(sbuf);
Mike Stump1eb44332009-09-09 15:08:12 +00001887
Ted Kremenekc887d132009-04-29 18:50:19 +00001888 // This is the allocation site since the previous node had no bindings
1889 // for this symbol.
1890 if (!PrevT) {
Jordy Rosef53e8c72011-08-23 19:43:16 +00001891 const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
Mike Stump1eb44332009-09-09 15:08:12 +00001892
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001893 if (isa<ObjCArrayLiteral>(S)) {
1894 os << "NSArray literal is an object with a +0 retain count";
Mike Stump1eb44332009-09-09 15:08:12 +00001895 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001896 else if (isa<ObjCDictionaryLiteral>(S)) {
1897 os << "NSDictionary literal is an object with a +0 retain count";
Ted Kremenekc887d132009-04-29 18:50:19 +00001898 }
Jordy Rose70fdbc32012-05-12 05:10:43 +00001899 else if (const ObjCBoxedExpr *BL = dyn_cast<ObjCBoxedExpr>(S)) {
1900 if (isNumericLiteralExpression(BL->getSubExpr()))
1901 os << "NSNumber literal is an object with a +0 retain count";
1902 else {
1903 const ObjCInterfaceDecl *BoxClass = 0;
1904 if (const ObjCMethodDecl *Method = BL->getBoxingMethod())
1905 BoxClass = Method->getClassInterface();
1906
1907 // We should always be able to find the boxing class interface,
1908 // but consider this future-proofing.
1909 if (BoxClass)
1910 os << *BoxClass << " b";
1911 else
1912 os << "B";
1913
1914 os << "oxed expression produces an object with a +0 retain count";
1915 }
1916 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001917 else {
1918 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
1919 // Get the name of the callee (if it is available).
1920 SVal X = CurrSt->getSValAsScalarOrLoc(CE->getCallee(), LCtx);
1921 if (const FunctionDecl *FD = X.getAsFunctionDecl())
1922 os << "Call to function '" << *FD << '\'';
1923 else
1924 os << "function call";
Ted Kremenekc887d132009-04-29 18:50:19 +00001925 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001926 else {
Jordan Rose8919e682012-07-18 21:59:51 +00001927 assert(isa<ObjCMessageExpr>(S));
Jordan Rosed563d3f2012-07-30 20:22:09 +00001928 CallEventManager &Mgr = CurrSt->getStateManager().getCallEventManager();
1929 CallEventRef<ObjCMethodCall> Call
1930 = Mgr.getObjCMethodCall(cast<ObjCMessageExpr>(S), CurrSt, LCtx);
1931
1932 switch (Call->getMessageKind()) {
Jordan Rose8919e682012-07-18 21:59:51 +00001933 case OCM_Message:
1934 os << "Method";
1935 break;
1936 case OCM_PropertyAccess:
1937 os << "Property";
1938 break;
1939 case OCM_Subscript:
1940 os << "Subscript";
1941 break;
1942 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001943 }
1944
1945 if (CurrV.getObjKind() == RetEffect::CF) {
1946 os << " returns a Core Foundation object with a ";
1947 }
1948 else {
1949 assert (CurrV.getObjKind() == RetEffect::ObjC);
1950 os << " returns an Objective-C object with a ";
1951 }
1952
1953 if (CurrV.isOwned()) {
1954 os << "+1 retain count";
1955
1956 if (GCEnabled) {
1957 assert(CurrV.getObjKind() == RetEffect::CF);
1958 os << ". "
1959 "Core Foundation objects are not automatically garbage collected.";
1960 }
1961 }
1962 else {
1963 assert (CurrV.isNotOwned());
1964 os << "+0 retain count";
1965 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001966 }
Mike Stump1eb44332009-09-09 15:08:12 +00001967
Anna Zaks220ac8c2011-09-15 01:08:34 +00001968 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
1969 N->getLocationContext());
Ted Kremenekc887d132009-04-29 18:50:19 +00001970 return new PathDiagnosticEventPiece(Pos, os.str());
1971 }
Mike Stump1eb44332009-09-09 15:08:12 +00001972
Ted Kremenekc887d132009-04-29 18:50:19 +00001973 // Gather up the effects that were performed on the object at this
1974 // program point
Chris Lattner5f9e2722011-07-23 10:55:15 +00001975 SmallVector<ArgEffect, 2> AEffects;
Mike Stump1eb44332009-09-09 15:08:12 +00001976
Jordy Roseec9ef852011-08-23 20:55:48 +00001977 const ExplodedNode *OrigNode = BRC.getNodeResolver().getOriginalNode(N);
1978 if (const RetainSummary *Summ = SummaryLog.lookup(OrigNode)) {
Ted Kremenekc887d132009-04-29 18:50:19 +00001979 // We only have summaries attached to nodes after evaluating CallExpr and
1980 // ObjCMessageExprs.
Jordy Rosef53e8c72011-08-23 19:43:16 +00001981 const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
Mike Stump1eb44332009-09-09 15:08:12 +00001982
Ted Kremenek5f85e172009-07-22 22:35:28 +00001983 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
Ted Kremenekc887d132009-04-29 18:50:19 +00001984 // Iterate through the parameter expressions and see if the symbol
1985 // was ever passed as an argument.
1986 unsigned i = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001987
Ted Kremenek5f85e172009-07-22 22:35:28 +00001988 for (CallExpr::const_arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
Ted Kremenekc887d132009-04-29 18:50:19 +00001989 AI!=AE; ++AI, ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00001990
Ted Kremenekc887d132009-04-29 18:50:19 +00001991 // Retrieve the value of the argument. Is it the symbol
1992 // we are interested in?
Ted Kremenek5eca4822012-01-06 22:09:28 +00001993 if (CurrSt->getSValAsScalarOrLoc(*AI, LCtx).getAsLocSymbol() != Sym)
Ted Kremenekc887d132009-04-29 18:50:19 +00001994 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001995
Ted Kremenekc887d132009-04-29 18:50:19 +00001996 // We have an argument. Get the effect!
1997 AEffects.push_back(Summ->getArg(i));
1998 }
1999 }
Mike Stump1eb44332009-09-09 15:08:12 +00002000 else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002001 if (const Expr *receiver = ME->getInstanceReceiver())
Ted Kremenek5eca4822012-01-06 22:09:28 +00002002 if (CurrSt->getSValAsScalarOrLoc(receiver, LCtx)
2003 .getAsLocSymbol() == Sym) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002004 // The symbol we are tracking is the receiver.
2005 AEffects.push_back(Summ->getReceiverEffect());
2006 }
2007 }
2008 }
Mike Stump1eb44332009-09-09 15:08:12 +00002009
Ted Kremenekc887d132009-04-29 18:50:19 +00002010 do {
2011 // Get the previous type state.
2012 RefVal PrevV = *PrevT;
Mike Stump1eb44332009-09-09 15:08:12 +00002013
Ted Kremenekc887d132009-04-29 18:50:19 +00002014 // Specially handle -dealloc.
Jordy Rose35c86952011-08-24 05:47:39 +00002015 if (!GCEnabled && contains(AEffects, Dealloc)) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002016 // Determine if the object's reference count was pushed to zero.
2017 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2018 // We may not have transitioned to 'release' if we hit an error.
2019 // This case is handled elsewhere.
2020 if (CurrV.getKind() == RefVal::Released) {
Ted Kremenekf21332e2009-05-08 20:01:42 +00002021 assert(CurrV.getCombinedCounts() == 0);
Ted Kremenekc887d132009-04-29 18:50:19 +00002022 os << "Object released by directly sending the '-dealloc' message";
2023 break;
2024 }
2025 }
Mike Stump1eb44332009-09-09 15:08:12 +00002026
Ted Kremenekc887d132009-04-29 18:50:19 +00002027 // Specially handle CFMakeCollectable and friends.
2028 if (contains(AEffects, MakeCollectable)) {
2029 // Get the name of the function.
Jordy Rosef53e8c72011-08-23 19:43:16 +00002030 const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
Ted Kremenek5eca4822012-01-06 22:09:28 +00002031 SVal X =
2032 CurrSt->getSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee(), LCtx);
Ted Kremenek9c378f72011-08-12 23:37:29 +00002033 const FunctionDecl *FD = X.getAsFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002034
Jordy Rose35c86952011-08-24 05:47:39 +00002035 if (GCEnabled) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002036 // Determine if the object's reference count was pushed to zero.
2037 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
Mike Stump1eb44332009-09-09 15:08:12 +00002038
Benjamin Kramerb8989f22011-10-14 18:45:37 +00002039 os << "In GC mode a call to '" << *FD
Ted Kremenekc887d132009-04-29 18:50:19 +00002040 << "' decrements an object's retain count and registers the "
2041 "object with the garbage collector. ";
Mike Stump1eb44332009-09-09 15:08:12 +00002042
Ted Kremenekc887d132009-04-29 18:50:19 +00002043 if (CurrV.getKind() == RefVal::Released) {
2044 assert(CurrV.getCount() == 0);
2045 os << "Since it now has a 0 retain count the object can be "
2046 "automatically collected by the garbage collector.";
2047 }
2048 else
2049 os << "An object must have a 0 retain count to be garbage collected. "
2050 "After this call its retain count is +" << CurrV.getCount()
2051 << '.';
2052 }
Mike Stump1eb44332009-09-09 15:08:12 +00002053 else
Benjamin Kramerb8989f22011-10-14 18:45:37 +00002054 os << "When GC is not enabled a call to '" << *FD
Ted Kremenekc887d132009-04-29 18:50:19 +00002055 << "' has no effect on its argument.";
Mike Stump1eb44332009-09-09 15:08:12 +00002056
Ted Kremenekc887d132009-04-29 18:50:19 +00002057 // Nothing more to say.
2058 break;
2059 }
Mike Stump1eb44332009-09-09 15:08:12 +00002060
2061 // Determine if the typestate has changed.
Ted Kremenekc887d132009-04-29 18:50:19 +00002062 if (!(PrevV == CurrV))
2063 switch (CurrV.getKind()) {
2064 case RefVal::Owned:
2065 case RefVal::NotOwned:
Mike Stump1eb44332009-09-09 15:08:12 +00002066
Ted Kremenekf21332e2009-05-08 20:01:42 +00002067 if (PrevV.getCount() == CurrV.getCount()) {
2068 // Did an autorelease message get sent?
2069 if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
2070 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002071
Zhongxing Xu264e9372009-05-12 10:10:00 +00002072 assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount());
Ted Kremenekeaedfea2009-05-10 05:11:21 +00002073 os << "Object sent -autorelease message";
Ted Kremenekf21332e2009-05-08 20:01:42 +00002074 break;
2075 }
Mike Stump1eb44332009-09-09 15:08:12 +00002076
Ted Kremenekc887d132009-04-29 18:50:19 +00002077 if (PrevV.getCount() > CurrV.getCount())
2078 os << "Reference count decremented.";
2079 else
2080 os << "Reference count incremented.";
Mike Stump1eb44332009-09-09 15:08:12 +00002081
Ted Kremenekc887d132009-04-29 18:50:19 +00002082 if (unsigned Count = CurrV.getCount())
2083 os << " The object now has a +" << Count << " retain count.";
Mike Stump1eb44332009-09-09 15:08:12 +00002084
Ted Kremenekc887d132009-04-29 18:50:19 +00002085 if (PrevV.getKind() == RefVal::Released) {
Jordy Rose35c86952011-08-24 05:47:39 +00002086 assert(GCEnabled && CurrV.getCount() > 0);
Jordy Rose74b7b2b2012-03-17 05:49:15 +00002087 os << " The object is not eligible for garbage collection until "
2088 "the retain count reaches 0 again.";
Ted Kremenekc887d132009-04-29 18:50:19 +00002089 }
Mike Stump1eb44332009-09-09 15:08:12 +00002090
Ted Kremenekc887d132009-04-29 18:50:19 +00002091 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002092
Ted Kremenekc887d132009-04-29 18:50:19 +00002093 case RefVal::Released:
2094 os << "Object released.";
2095 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002096
Ted Kremenekc887d132009-04-29 18:50:19 +00002097 case RefVal::ReturnedOwned:
Jordy Rose74b7b2b2012-03-17 05:49:15 +00002098 // Autoreleases can be applied after marking a node ReturnedOwned.
2099 if (CurrV.getAutoreleaseCount())
2100 return NULL;
2101
2102 os << "Object returned to caller as an owning reference (single "
2103 "retain count transferred to caller)";
Ted Kremenekc887d132009-04-29 18:50:19 +00002104 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002105
Ted Kremenekc887d132009-04-29 18:50:19 +00002106 case RefVal::ReturnedNotOwned:
Ted Kremenekf1365462011-05-26 18:45:44 +00002107 os << "Object returned to caller with a +0 retain count";
Ted Kremenekc887d132009-04-29 18:50:19 +00002108 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002109
Ted Kremenekc887d132009-04-29 18:50:19 +00002110 default:
2111 return NULL;
2112 }
Mike Stump1eb44332009-09-09 15:08:12 +00002113
Ted Kremenekc887d132009-04-29 18:50:19 +00002114 // Emit any remaining diagnostics for the argument effects (if any).
Chris Lattner5f9e2722011-07-23 10:55:15 +00002115 for (SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
Ted Kremenekc887d132009-04-29 18:50:19 +00002116 E=AEffects.end(); I != E; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +00002117
Ted Kremenekc887d132009-04-29 18:50:19 +00002118 // A bunch of things have alternate behavior under GC.
Jordy Rose35c86952011-08-24 05:47:39 +00002119 if (GCEnabled)
Ted Kremenekc887d132009-04-29 18:50:19 +00002120 switch (*I) {
2121 default: break;
2122 case Autorelease:
2123 os << "In GC mode an 'autorelease' has no effect.";
2124 continue;
2125 case IncRefMsg:
2126 os << "In GC mode the 'retain' message has no effect.";
2127 continue;
2128 case DecRefMsg:
2129 os << "In GC mode the 'release' message has no effect.";
2130 continue;
2131 }
2132 }
Mike Stump1eb44332009-09-09 15:08:12 +00002133 } while (0);
2134
Ted Kremenekc887d132009-04-29 18:50:19 +00002135 if (os.str().empty())
2136 return 0; // We have nothing to say!
Ted Kremenek2033a952009-05-13 07:12:33 +00002137
Jordy Rosef53e8c72011-08-23 19:43:16 +00002138 const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
Anna Zaks220ac8c2011-09-15 01:08:34 +00002139 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
2140 N->getLocationContext());
Ted Kremenek9c378f72011-08-12 23:37:29 +00002141 PathDiagnosticPiece *P = new PathDiagnosticEventPiece(Pos, os.str());
Mike Stump1eb44332009-09-09 15:08:12 +00002142
Ted Kremenekc887d132009-04-29 18:50:19 +00002143 // Add the range by scanning the children of the statement for any bindings
2144 // to Sym.
Mike Stump1eb44332009-09-09 15:08:12 +00002145 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
Ted Kremenek5f85e172009-07-22 22:35:28 +00002146 I!=E; ++I)
Ted Kremenek9c378f72011-08-12 23:37:29 +00002147 if (const Expr *Exp = dyn_cast_or_null<Expr>(*I))
Ted Kremenek5eca4822012-01-06 22:09:28 +00002148 if (CurrSt->getSValAsScalarOrLoc(Exp, LCtx).getAsLocSymbol() == Sym) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002149 P->addRange(Exp->getSourceRange());
2150 break;
2151 }
Mike Stump1eb44332009-09-09 15:08:12 +00002152
Ted Kremenekc887d132009-04-29 18:50:19 +00002153 return P;
2154}
2155
Anna Zakse7e01682012-02-28 22:39:22 +00002156// Find the first node in the current function context that referred to the
2157// tracked symbol and the memory location that value was stored to. Note, the
2158// value is only reported if the allocation occurred in the same function as
2159// the leak.
Zhongxing Xuc5619d92009-08-06 01:32:16 +00002160static std::pair<const ExplodedNode*,const MemRegion*>
Ted Kremenek18c66fd2011-08-15 22:09:50 +00002161GetAllocationSite(ProgramStateManager& StateMgr, const ExplodedNode *N,
Ted Kremenekc887d132009-04-29 18:50:19 +00002162 SymbolRef Sym) {
Ted Kremenek9c378f72011-08-12 23:37:29 +00002163 const ExplodedNode *Last = N;
Mike Stump1eb44332009-09-09 15:08:12 +00002164 const MemRegion* FirstBinding = 0;
Anna Zakse7e01682012-02-28 22:39:22 +00002165 const LocationContext *LeakContext = N->getLocationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002166
Ted Kremenekc887d132009-04-29 18:50:19 +00002167 while (N) {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002168 ProgramStateRef St = N->getState();
Mike Stump1eb44332009-09-09 15:08:12 +00002169
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002170 if (!getRefBinding(St, Sym))
Ted Kremenekc887d132009-04-29 18:50:19 +00002171 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002172
Anna Zaks27b867e2012-03-21 19:45:01 +00002173 StoreManager::FindUniqueBinding FB(Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002174 StateMgr.iterBindings(St, FB);
2175 if (FB) FirstBinding = FB.getRegion();
2176
Anna Zakse7e01682012-02-28 22:39:22 +00002177 // Allocation node, is the last node in the current context in which the
2178 // symbol was tracked.
2179 if (N->getLocationContext() == LeakContext)
2180 Last = N;
2181
Mike Stump1eb44332009-09-09 15:08:12 +00002182 N = N->pred_empty() ? NULL : *(N->pred_begin());
Ted Kremenekc887d132009-04-29 18:50:19 +00002183 }
Mike Stump1eb44332009-09-09 15:08:12 +00002184
Anna Zakse7e01682012-02-28 22:39:22 +00002185 // If allocation happened in a function different from the leak node context,
2186 // do not report the binding.
Ted Kremenek5a8fc882012-10-12 22:56:40 +00002187 assert(N && "Could not find allocation node");
Anna Zakse7e01682012-02-28 22:39:22 +00002188 if (N->getLocationContext() != LeakContext) {
2189 FirstBinding = 0;
2190 }
2191
Ted Kremenekc887d132009-04-29 18:50:19 +00002192 return std::make_pair(Last, FirstBinding);
2193}
2194
2195PathDiagnosticPiece*
Anna Zaks23f395e2011-08-20 01:27:22 +00002196CFRefReportVisitor::getEndPath(BugReporterContext &BRC,
2197 const ExplodedNode *EndN,
2198 BugReport &BR) {
Ted Kremenek76aadc32012-03-09 01:13:14 +00002199 BR.markInteresting(Sym);
Anna Zaks23f395e2011-08-20 01:27:22 +00002200 return BugReporterVisitor::getDefaultEndPath(BRC, EndN, BR);
Ted Kremenekc887d132009-04-29 18:50:19 +00002201}
2202
2203PathDiagnosticPiece*
Anna Zaks23f395e2011-08-20 01:27:22 +00002204CFRefLeakReportVisitor::getEndPath(BugReporterContext &BRC,
2205 const ExplodedNode *EndN,
2206 BugReport &BR) {
Mike Stump1eb44332009-09-09 15:08:12 +00002207
Ted Kremenek8966bc12009-05-06 21:39:49 +00002208 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenekc887d132009-04-29 18:50:19 +00002209 // assigned to different variables, etc.
Ted Kremenek76aadc32012-03-09 01:13:14 +00002210 BR.markInteresting(Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002211
Ted Kremenekc887d132009-04-29 18:50:19 +00002212 // We are reporting a leak. Walk up the graph to get to the first node where
2213 // the symbol appeared, and also get the first VarDecl that tracked object
2214 // is stored to.
Ted Kremenek9c378f72011-08-12 23:37:29 +00002215 const ExplodedNode *AllocNode = 0;
Ted Kremenekc887d132009-04-29 18:50:19 +00002216 const MemRegion* FirstBinding = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002217
Ted Kremenekc887d132009-04-29 18:50:19 +00002218 llvm::tie(AllocNode, FirstBinding) =
Ted Kremenekf04dced2009-05-08 23:32:51 +00002219 GetAllocationSite(BRC.getStateManager(), EndN, Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002220
Anna Zaks4fdf97b2011-09-15 18:56:07 +00002221 SourceManager& SM = BRC.getSourceManager();
Mike Stump1eb44332009-09-09 15:08:12 +00002222
Ted Kremenekc887d132009-04-29 18:50:19 +00002223 // Compute an actual location for the leak. Sometimes a leak doesn't
2224 // occur at an actual statement (e.g., transition between blocks; end
2225 // of function) so we need to walk the graph and compute a real location.
Ted Kremenek9c378f72011-08-12 23:37:29 +00002226 const ExplodedNode *LeakN = EndN;
Anna Zaks4fdf97b2011-09-15 18:56:07 +00002227 PathDiagnosticLocation L = PathDiagnosticLocation::createEndOfPath(LeakN, SM);
Mike Stump1eb44332009-09-09 15:08:12 +00002228
Ted Kremenekc887d132009-04-29 18:50:19 +00002229 std::string sbuf;
2230 llvm::raw_string_ostream os(sbuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002231
Ted Kremenekf1365462011-05-26 18:45:44 +00002232 os << "Object leaked: ";
Mike Stump1eb44332009-09-09 15:08:12 +00002233
Ted Kremenekf1365462011-05-26 18:45:44 +00002234 if (FirstBinding) {
2235 os << "object allocated and stored into '"
2236 << FirstBinding->getString() << '\'';
2237 }
2238 else
2239 os << "allocated object";
Mike Stump1eb44332009-09-09 15:08:12 +00002240
Ted Kremenekc887d132009-04-29 18:50:19 +00002241 // Get the retain count.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002242 const RefVal* RV = getRefBinding(EndN->getState(), Sym);
Ted Kremenek5a8fc882012-10-12 22:56:40 +00002243 assert(RV);
Mike Stump1eb44332009-09-09 15:08:12 +00002244
Ted Kremenekc887d132009-04-29 18:50:19 +00002245 if (RV->getKind() == RefVal::ErrorLeakReturned) {
2246 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
Jordy Rose5b5402b2011-07-15 22:17:54 +00002247 // objects. Only "copy", "alloc", "retain" and "new" transfer ownership
Ted Kremenekc887d132009-04-29 18:50:19 +00002248 // to the caller for NS objects.
Ted Kremenekd368d712011-05-25 06:19:45 +00002249 const Decl *D = &EndN->getCodeDecl();
Ted Kremenekec9f36e2012-09-06 23:03:07 +00002250
2251 os << (isa<ObjCMethodDecl>(D) ? " is returned from a method "
2252 : " is returned from a function ");
2253
2254 if (D->getAttr<CFReturnsNotRetainedAttr>())
2255 os << "that is annotated as CF_RETURNS_NOT_RETAINED";
2256 else if (D->getAttr<NSReturnsNotRetainedAttr>())
2257 os << "that is annotated as NS_RETURNS_NOT_RETAINED";
Ted Kremenekd368d712011-05-25 06:19:45 +00002258 else {
Ted Kremenekec9f36e2012-09-06 23:03:07 +00002259 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2260 os << "whose name ('" << MD->getSelector().getAsString()
2261 << "') does not start with 'copy', 'mutableCopy', 'alloc' or 'new'."
2262 " This violates the naming convention rules"
2263 " given in the Memory Management Guide for Cocoa";
2264 }
2265 else {
2266 const FunctionDecl *FD = cast<FunctionDecl>(D);
2267 os << "whose name ('" << *FD
2268 << "') does not contain 'Copy' or 'Create'. This violates the naming"
2269 " convention rules given in the Memory Management Guide for Core"
2270 " Foundation";
2271 }
2272 }
Ted Kremenekc887d132009-04-29 18:50:19 +00002273 }
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002274 else if (RV->getKind() == RefVal::ErrorGCLeakReturned) {
Ted Kremenek9c378f72011-08-12 23:37:29 +00002275 ObjCMethodDecl &MD = cast<ObjCMethodDecl>(EndN->getCodeDecl());
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002276 os << " and returned from method '" << MD.getSelector().getAsString()
Ted Kremenek82f2be52009-05-10 16:52:15 +00002277 << "' is potentially leaked when using garbage collection. Callers "
2278 "of this method do not expect a returned object with a +1 retain "
2279 "count since they expect the object to be managed by the garbage "
2280 "collector";
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002281 }
Ted Kremenekc887d132009-04-29 18:50:19 +00002282 else
Ted Kremenekabf517c2010-10-15 22:50:23 +00002283 os << " is not referenced later in this execution path and has a retain "
Ted Kremenekf1365462011-05-26 18:45:44 +00002284 "count of +" << RV->getCount();
Mike Stump1eb44332009-09-09 15:08:12 +00002285
Ted Kremenekc887d132009-04-29 18:50:19 +00002286 return new PathDiagnosticEventPiece(L, os.str());
2287}
2288
Jordy Rose20589562011-08-24 22:39:09 +00002289CFRefLeakReport::CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts,
2290 bool GCEnabled, const SummaryLogTy &Log,
2291 ExplodedNode *n, SymbolRef sym,
Anna Zaks6a93bd52011-10-25 19:57:11 +00002292 CheckerContext &Ctx)
Jordy Rose20589562011-08-24 22:39:09 +00002293: CFRefReport(D, LOpts, GCEnabled, Log, n, sym, false) {
Mike Stump1eb44332009-09-09 15:08:12 +00002294
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00002295 // Most bug reports are cached at the location where they occurred.
Ted Kremenekc887d132009-04-29 18:50:19 +00002296 // With leaks, we want to unique them by the location where they were
2297 // allocated, and only report a single path. To do this, we need to find
2298 // the allocation site of a piece of tracked memory, which we do via a
2299 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2300 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2301 // that all ancestor nodes that represent the allocation site have the
2302 // same SourceLocation.
Ted Kremenek9c378f72011-08-12 23:37:29 +00002303 const ExplodedNode *AllocNode = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002304
Anna Zaks6a93bd52011-10-25 19:57:11 +00002305 const SourceManager& SMgr = Ctx.getSourceManager();
Anna Zaks590dd8e2011-09-20 21:38:35 +00002306
Ted Kremenekc887d132009-04-29 18:50:19 +00002307 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding.
Anna Zaks6a93bd52011-10-25 19:57:11 +00002308 GetAllocationSite(Ctx.getStateManager(), getErrorNode(), sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002309
Ted Kremenekc887d132009-04-29 18:50:19 +00002310 // Get the SourceLocation for the allocation site.
Jordan Rose852aa0d2012-07-10 22:07:52 +00002311 // FIXME: This will crash the analyzer if an allocation comes from an
2312 // implicit call. (Currently there are no such allocations in Cocoa, though.)
2313 const Stmt *AllocStmt;
Ted Kremenekc887d132009-04-29 18:50:19 +00002314 ProgramPoint P = AllocNode->getLocation();
Jordan Rose852aa0d2012-07-10 22:07:52 +00002315 if (CallExitEnd *Exit = dyn_cast<CallExitEnd>(&P))
2316 AllocStmt = Exit->getCalleeContext()->getCallSite();
2317 else
2318 AllocStmt = cast<PostStmt>(P).getStmt();
2319 assert(AllocStmt && "All allocations must come from explicit calls");
Anna Zaks590dd8e2011-09-20 21:38:35 +00002320 Location = PathDiagnosticLocation::createBegin(AllocStmt, SMgr,
2321 n->getLocationContext());
Ted Kremenekc887d132009-04-29 18:50:19 +00002322 // Fill in the description of the bug.
2323 Description.clear();
2324 llvm::raw_string_ostream os(Description);
Ted Kremenekdd924e22009-05-02 19:05:19 +00002325 os << "Potential leak ";
Jordy Rose20589562011-08-24 22:39:09 +00002326 if (GCEnabled)
Ted Kremenekdd924e22009-05-02 19:05:19 +00002327 os << "(when using garbage collection) ";
Anna Zaks212000e2012-02-28 21:49:08 +00002328 os << "of an object";
Mike Stump1eb44332009-09-09 15:08:12 +00002329
Ted Kremenekc887d132009-04-29 18:50:19 +00002330 // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2331 if (AllocBinding)
Anna Zaks212000e2012-02-28 21:49:08 +00002332 os << " stored into '" << AllocBinding->getString() << '\'';
Anna Zaksdc757b02011-08-19 23:21:56 +00002333
Jordy Rose20589562011-08-24 22:39:09 +00002334 addVisitor(new CFRefLeakReportVisitor(sym, GCEnabled, Log));
Ted Kremenekc887d132009-04-29 18:50:19 +00002335}
2336
2337//===----------------------------------------------------------------------===//
2338// Main checker logic.
2339//===----------------------------------------------------------------------===//
2340
Ted Kremenekd593eb92009-11-25 22:17:44 +00002341namespace {
Jordy Rose910c4052011-09-02 06:44:22 +00002342class RetainCountChecker
Jordy Rose9c083b72011-08-24 18:56:32 +00002343 : public Checker< check::Bind,
Jordy Rose38f17d62011-08-23 19:01:07 +00002344 check::DeadSymbols,
Jordy Rose9c083b72011-08-24 18:56:32 +00002345 check::EndAnalysis,
Anna Zaks344c77a2013-01-03 00:25:29 +00002346 check::EndFunction,
Jordy Rose67044292011-08-17 21:27:39 +00002347 check::PostStmt<BlockExpr>,
John McCallf85e1932011-06-15 23:02:42 +00002348 check::PostStmt<CastExpr>,
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002349 check::PostStmt<ObjCArrayLiteral>,
2350 check::PostStmt<ObjCDictionaryLiteral>,
Jordy Rose70fdbc32012-05-12 05:10:43 +00002351 check::PostStmt<ObjCBoxedExpr>,
Jordan Rosefe6a0112012-07-02 19:28:21 +00002352 check::PostCall,
Jordy Rosef53e8c72011-08-23 19:43:16 +00002353 check::PreStmt<ReturnStmt>,
Jordy Rose67044292011-08-17 21:27:39 +00002354 check::RegionChanges,
Jordy Rose76c506f2011-08-21 21:58:18 +00002355 eval::Assume,
2356 eval::Call > {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002357 mutable OwningPtr<CFRefBug> useAfterRelease, releaseNotOwned;
2358 mutable OwningPtr<CFRefBug> deallocGC, deallocNotOwned;
2359 mutable OwningPtr<CFRefBug> overAutorelease, returnNotOwnedForOwned;
2360 mutable OwningPtr<CFRefBug> leakWithinFunction, leakAtReturn;
2361 mutable OwningPtr<CFRefBug> leakWithinFunctionGC, leakAtReturnGC;
Jordy Rose38f17d62011-08-23 19:01:07 +00002362
2363 typedef llvm::DenseMap<SymbolRef, const SimpleProgramPointTag *> SymbolTagMap;
2364
2365 // This map is only used to ensure proper deletion of any allocated tags.
2366 mutable SymbolTagMap DeadSymbolTags;
2367
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002368 mutable OwningPtr<RetainSummaryManager> Summaries;
2369 mutable OwningPtr<RetainSummaryManager> SummariesGC;
Jordy Rose9c083b72011-08-24 18:56:32 +00002370 mutable SummaryLogTy SummaryLog;
2371 mutable bool ShouldResetSummaryLog;
2372
Jordy Rose2f9a66d2011-08-20 21:17:59 +00002373public:
Jordy Rose910c4052011-09-02 06:44:22 +00002374 RetainCountChecker() : ShouldResetSummaryLog(false) {}
Jordy Rose38f17d62011-08-23 19:01:07 +00002375
Jordy Rose910c4052011-09-02 06:44:22 +00002376 virtual ~RetainCountChecker() {
Jordy Rose38f17d62011-08-23 19:01:07 +00002377 DeleteContainerSeconds(DeadSymbolTags);
2378 }
2379
Jordy Rose9c083b72011-08-24 18:56:32 +00002380 void checkEndAnalysis(ExplodedGraph &G, BugReporter &BR,
2381 ExprEngine &Eng) const {
2382 // FIXME: This is a hack to make sure the summary log gets cleared between
2383 // analyses of different code bodies.
2384 //
2385 // Why is this necessary? Because a checker's lifetime is tied to a
2386 // translation unit, but an ExplodedGraph's lifetime is just a code body.
2387 // Once in a blue moon, a new ExplodedNode will have the same address as an
2388 // old one with an associated summary, and the bug report visitor gets very
2389 // confused. (To make things worse, the summary lifetime is currently also
2390 // tied to a code body, so we get a crash instead of incorrect results.)
Jordy Rose1ab51c72011-08-24 09:27:24 +00002391 //
2392 // Why is this a bad solution? Because if the lifetime of the ExplodedGraph
2393 // changes, things will start going wrong again. Really the lifetime of this
2394 // log needs to be tied to either the specific nodes in it or the entire
2395 // ExplodedGraph, not to a specific part of the code being analyzed.
2396 //
Jordy Rose9c083b72011-08-24 18:56:32 +00002397 // (Also, having stateful local data means that the same checker can't be
2398 // used from multiple threads, but a lot of checkers have incorrect
2399 // assumptions about that anyway. So that wasn't a priority at the time of
2400 // this fix.)
Jordy Rose1ab51c72011-08-24 09:27:24 +00002401 //
Jordy Rose9c083b72011-08-24 18:56:32 +00002402 // This happens at the end of analysis, but bug reports are emitted /after/
2403 // this point. So we can't just clear the summary log now. Instead, we mark
2404 // that the next time we access the summary log, it should be cleared.
2405
2406 // If we never reset the summary log during /this/ code body analysis,
2407 // there were no new summaries. There might still have been summaries from
2408 // the /last/ analysis, so clear them out to make sure the bug report
2409 // visitors don't get confused.
2410 if (ShouldResetSummaryLog)
2411 SummaryLog.clear();
2412
2413 ShouldResetSummaryLog = !SummaryLog.empty();
Jordy Rose1ab51c72011-08-24 09:27:24 +00002414 }
2415
Jordy Rose17a38e22011-09-02 05:55:19 +00002416 CFRefBug *getLeakWithinFunctionBug(const LangOptions &LOpts,
2417 bool GCEnabled) const {
2418 if (GCEnabled) {
Jordy Rosedb92bb62011-08-25 01:14:38 +00002419 if (!leakWithinFunctionGC)
Benjamin Kramerfacde172012-06-06 17:32:50 +00002420 leakWithinFunctionGC.reset(new Leak("Leak of object when using "
2421 "garbage collection"));
Jordy Rose17a38e22011-09-02 05:55:19 +00002422 return leakWithinFunctionGC.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002423 } else {
2424 if (!leakWithinFunction) {
Douglas Gregore289d812011-09-13 17:21:33 +00002425 if (LOpts.getGC() == LangOptions::HybridGC) {
Benjamin Kramerfacde172012-06-06 17:32:50 +00002426 leakWithinFunction.reset(new Leak("Leak of object when not using "
2427 "garbage collection (GC) in "
2428 "dual GC/non-GC code"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002429 } else {
Benjamin Kramerfacde172012-06-06 17:32:50 +00002430 leakWithinFunction.reset(new Leak("Leak"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002431 }
2432 }
Jordy Rose17a38e22011-09-02 05:55:19 +00002433 return leakWithinFunction.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002434 }
2435 }
2436
Jordy Rose17a38e22011-09-02 05:55:19 +00002437 CFRefBug *getLeakAtReturnBug(const LangOptions &LOpts, bool GCEnabled) const {
2438 if (GCEnabled) {
Jordy Rosedb92bb62011-08-25 01:14:38 +00002439 if (!leakAtReturnGC)
Benjamin Kramerfacde172012-06-06 17:32:50 +00002440 leakAtReturnGC.reset(new Leak("Leak of returned object when using "
2441 "garbage collection"));
Jordy Rose17a38e22011-09-02 05:55:19 +00002442 return leakAtReturnGC.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002443 } else {
2444 if (!leakAtReturn) {
Douglas Gregore289d812011-09-13 17:21:33 +00002445 if (LOpts.getGC() == LangOptions::HybridGC) {
Benjamin Kramerfacde172012-06-06 17:32:50 +00002446 leakAtReturn.reset(new Leak("Leak of returned object when not using "
2447 "garbage collection (GC) in dual "
2448 "GC/non-GC code"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002449 } else {
Benjamin Kramerfacde172012-06-06 17:32:50 +00002450 leakAtReturn.reset(new Leak("Leak of returned object"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002451 }
2452 }
Jordy Rose17a38e22011-09-02 05:55:19 +00002453 return leakAtReturn.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002454 }
2455 }
2456
Jordy Rose17a38e22011-09-02 05:55:19 +00002457 RetainSummaryManager &getSummaryManager(ASTContext &Ctx,
2458 bool GCEnabled) const {
2459 // FIXME: We don't support ARC being turned on and off during one analysis.
2460 // (nor, for that matter, do we support changing ASTContexts)
David Blaikie4e4d0842012-03-11 07:00:24 +00002461 bool ARCEnabled = (bool)Ctx.getLangOpts().ObjCAutoRefCount;
Jordy Rose17a38e22011-09-02 05:55:19 +00002462 if (GCEnabled) {
2463 if (!SummariesGC)
Jordy Roseb6cfc092011-08-25 00:10:37 +00002464 SummariesGC.reset(new RetainSummaryManager(Ctx, true, ARCEnabled));
Jordy Rose17a38e22011-09-02 05:55:19 +00002465 else
2466 assert(SummariesGC->isARCEnabled() == ARCEnabled);
Jordy Roseb6cfc092011-08-25 00:10:37 +00002467 return *SummariesGC;
2468 } else {
Jordy Rose17a38e22011-09-02 05:55:19 +00002469 if (!Summaries)
Jordy Roseb6cfc092011-08-25 00:10:37 +00002470 Summaries.reset(new RetainSummaryManager(Ctx, false, ARCEnabled));
Jordy Rose17a38e22011-09-02 05:55:19 +00002471 else
2472 assert(Summaries->isARCEnabled() == ARCEnabled);
Jordy Roseb6cfc092011-08-25 00:10:37 +00002473 return *Summaries;
2474 }
2475 }
2476
Jordy Rose17a38e22011-09-02 05:55:19 +00002477 RetainSummaryManager &getSummaryManager(CheckerContext &C) const {
2478 return getSummaryManager(C.getASTContext(), C.isObjCGCEnabled());
2479 }
2480
Ted Kremenek8bef8232012-01-26 21:29:00 +00002481 void printState(raw_ostream &Out, ProgramStateRef State,
Jordy Rosedbd658e2011-08-28 19:11:56 +00002482 const char *NL, const char *Sep) const;
2483
Anna Zaks390909c2011-10-06 00:43:15 +00002484 void checkBind(SVal loc, SVal val, const Stmt *S, CheckerContext &C) const;
Jordy Roseab027fd2011-08-20 21:16:58 +00002485 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
2486 void checkPostStmt(const CastExpr *CE, CheckerContext &C) const;
John McCallf85e1932011-06-15 23:02:42 +00002487
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002488 void checkPostStmt(const ObjCArrayLiteral *AL, CheckerContext &C) const;
2489 void checkPostStmt(const ObjCDictionaryLiteral *DL, CheckerContext &C) const;
Jordy Rose70fdbc32012-05-12 05:10:43 +00002490 void checkPostStmt(const ObjCBoxedExpr *BE, CheckerContext &C) const;
2491
Jordan Rosefe6a0112012-07-02 19:28:21 +00002492 void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002493
Jordan Rose4531b7d2012-07-02 19:27:43 +00002494 void checkSummary(const RetainSummary &Summ, const CallEvent &Call,
Jordy Rosee38dd952011-08-28 05:16:28 +00002495 CheckerContext &C) const;
Jordy Rose294396b2011-08-22 23:48:23 +00002496
Anna Zaks554067f2012-08-29 23:23:43 +00002497 void processSummaryOfInlined(const RetainSummary &Summ,
2498 const CallEvent &Call,
2499 CheckerContext &C) const;
2500
Jordy Rose76c506f2011-08-21 21:58:18 +00002501 bool evalCall(const CallExpr *CE, CheckerContext &C) const;
2502
Ted Kremenek8bef8232012-01-26 21:29:00 +00002503 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Jordy Roseab027fd2011-08-20 21:16:58 +00002504 bool Assumption) const;
Jordy Rose67044292011-08-17 21:27:39 +00002505
Ted Kremenek8bef8232012-01-26 21:29:00 +00002506 ProgramStateRef
2507 checkRegionChanges(ProgramStateRef state,
Anna Zaksbf53dfa2012-12-20 00:38:25 +00002508 const InvalidatedSymbols *invalidated,
Jordy Rose537716a2011-08-27 22:51:26 +00002509 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00002510 ArrayRef<const MemRegion *> Regions,
Jordan Rose740d4902012-07-02 19:27:35 +00002511 const CallEvent *Call) const;
Jordy Roseab027fd2011-08-20 21:16:58 +00002512
Ted Kremenek8bef8232012-01-26 21:29:00 +00002513 bool wantsRegionChangeUpdate(ProgramStateRef state) const {
Jordy Rose2f9a66d2011-08-20 21:17:59 +00002514 return true;
Jordy Roseab027fd2011-08-20 21:16:58 +00002515 }
Jordy Rose294396b2011-08-22 23:48:23 +00002516
Jordy Rosef53e8c72011-08-23 19:43:16 +00002517 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
2518 void checkReturnWithRetEffect(const ReturnStmt *S, CheckerContext &C,
2519 ExplodedNode *Pred, RetEffect RE, RefVal X,
Ted Kremenek8bef8232012-01-26 21:29:00 +00002520 SymbolRef Sym, ProgramStateRef state) const;
Jordy Rosef53e8c72011-08-23 19:43:16 +00002521
Jordy Rose38f17d62011-08-23 19:01:07 +00002522 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Anna Zaks344c77a2013-01-03 00:25:29 +00002523 void checkEndFunction(CheckerContext &C) const;
Jordy Rose38f17d62011-08-23 19:01:07 +00002524
Ted Kremenek8bef8232012-01-26 21:29:00 +00002525 ProgramStateRef updateSymbol(ProgramStateRef state, SymbolRef sym,
Anna Zaks554067f2012-08-29 23:23:43 +00002526 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
2527 CheckerContext &C) const;
Jordy Rosee0a5d322011-08-23 20:27:16 +00002528
Ted Kremenek8bef8232012-01-26 21:29:00 +00002529 void processNonLeakError(ProgramStateRef St, SourceRange ErrorRange,
Jordy Rose294396b2011-08-22 23:48:23 +00002530 RefVal::Kind ErrorKind, SymbolRef Sym,
2531 CheckerContext &C) const;
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002532
2533 void processObjCLiterals(CheckerContext &C, const Expr *Ex) const;
Jordy Rose294396b2011-08-22 23:48:23 +00002534
Jordy Rose38f17d62011-08-23 19:01:07 +00002535 const ProgramPointTag *getDeadSymbolTag(SymbolRef sym) const;
2536
Ted Kremenek8bef8232012-01-26 21:29:00 +00002537 ProgramStateRef handleSymbolDeath(ProgramStateRef state,
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002538 SymbolRef sid, RefVal V,
2539 SmallVectorImpl<SymbolRef> &Leaked) const;
Jordy Rose38f17d62011-08-23 19:01:07 +00002540
Jordan Rose4ee1c552012-12-06 18:58:18 +00002541 ProgramStateRef
Jordan Rose2bce86c2012-08-18 00:30:16 +00002542 handleAutoreleaseCounts(ProgramStateRef state, ExplodedNode *Pred,
2543 const ProgramPointTag *Tag, CheckerContext &Ctx,
2544 SymbolRef Sym, RefVal V) const;
Jordy Rose8d228632011-08-23 20:07:14 +00002545
Ted Kremenek8bef8232012-01-26 21:29:00 +00002546 ExplodedNode *processLeaks(ProgramStateRef state,
Jordy Rose38f17d62011-08-23 19:01:07 +00002547 SmallVectorImpl<SymbolRef> &Leaked,
Anna Zaks6a93bd52011-10-25 19:57:11 +00002548 CheckerContext &Ctx,
Jordy Rose38f17d62011-08-23 19:01:07 +00002549 ExplodedNode *Pred = 0) const;
Ted Kremenekd593eb92009-11-25 22:17:44 +00002550};
2551} // end anonymous namespace
2552
Jordy Rose67044292011-08-17 21:27:39 +00002553namespace {
2554class StopTrackingCallback : public SymbolVisitor {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002555 ProgramStateRef state;
Jordy Rose67044292011-08-17 21:27:39 +00002556public:
Ted Kremenek8bef8232012-01-26 21:29:00 +00002557 StopTrackingCallback(ProgramStateRef st) : state(st) {}
2558 ProgramStateRef getState() const { return state; }
Jordy Rose67044292011-08-17 21:27:39 +00002559
2560 bool VisitSymbol(SymbolRef sym) {
2561 state = state->remove<RefBindings>(sym);
2562 return true;
2563 }
2564};
2565} // end anonymous namespace
2566
Jordy Rose910c4052011-09-02 06:44:22 +00002567//===----------------------------------------------------------------------===//
2568// Handle statements that may have an effect on refcounts.
2569//===----------------------------------------------------------------------===//
Jordy Rose67044292011-08-17 21:27:39 +00002570
Jordy Rose910c4052011-09-02 06:44:22 +00002571void RetainCountChecker::checkPostStmt(const BlockExpr *BE,
2572 CheckerContext &C) const {
Jordy Rose67044292011-08-17 21:27:39 +00002573
Jordy Rose910c4052011-09-02 06:44:22 +00002574 // Scan the BlockDecRefExprs for any object the retain count checker
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002575 // may be tracking.
John McCall469a1eb2011-02-02 13:00:07 +00002576 if (!BE->getBlockDecl()->hasCaptures())
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002577 return;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002578
Ted Kremenek8bef8232012-01-26 21:29:00 +00002579 ProgramStateRef state = C.getState();
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002580 const BlockDataRegion *R =
Ted Kremenek5eca4822012-01-06 22:09:28 +00002581 cast<BlockDataRegion>(state->getSVal(BE,
2582 C.getLocationContext()).getAsRegion());
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002583
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002584 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
2585 E = R->referenced_vars_end();
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002586
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002587 if (I == E)
2588 return;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002589
Ted Kremenek67d12872009-12-07 22:05:27 +00002590 // FIXME: For now we invalidate the tracking of all symbols passed to blocks
2591 // via captured variables, even though captured variables result in a copy
2592 // and in implicit increment/decrement of a retain count.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002593 SmallVector<const MemRegion*, 10> Regions;
Anna Zaks39ac1872011-10-26 21:06:44 +00002594 const LocationContext *LC = C.getLocationContext();
Ted Kremenekc8413fd2010-12-02 07:49:45 +00002595 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002596
Ted Kremenek67d12872009-12-07 22:05:27 +00002597 for ( ; I != E; ++I) {
Ted Kremeneke3ce2c12012-12-06 07:17:20 +00002598 const VarRegion *VR = I.getCapturedRegion();
Ted Kremenek67d12872009-12-07 22:05:27 +00002599 if (VR->getSuperRegion() == R) {
2600 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2601 }
2602 Regions.push_back(VR);
2603 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002604
Ted Kremenek67d12872009-12-07 22:05:27 +00002605 state =
2606 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
2607 Regions.data() + Regions.size()).getState();
Anna Zaks0bd6b112011-10-26 21:06:34 +00002608 C.addTransition(state);
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002609}
2610
Jordy Rose910c4052011-09-02 06:44:22 +00002611void RetainCountChecker::checkPostStmt(const CastExpr *CE,
2612 CheckerContext &C) const {
John McCallf85e1932011-06-15 23:02:42 +00002613 const ObjCBridgedCastExpr *BE = dyn_cast<ObjCBridgedCastExpr>(CE);
2614 if (!BE)
2615 return;
2616
John McCall71c482c2011-06-17 06:50:50 +00002617 ArgEffect AE = IncRef;
John McCallf85e1932011-06-15 23:02:42 +00002618
2619 switch (BE->getBridgeKind()) {
2620 case clang::OBC_Bridge:
2621 // Do nothing.
2622 return;
2623 case clang::OBC_BridgeRetained:
2624 AE = IncRef;
2625 break;
2626 case clang::OBC_BridgeTransfer:
2627 AE = DecRefBridgedTransfered;
2628 break;
2629 }
2630
Ted Kremenek8bef8232012-01-26 21:29:00 +00002631 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00002632 SymbolRef Sym = state->getSVal(CE, C.getLocationContext()).getAsLocSymbol();
John McCallf85e1932011-06-15 23:02:42 +00002633 if (!Sym)
2634 return;
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002635 const RefVal* T = getRefBinding(state, Sym);
John McCallf85e1932011-06-15 23:02:42 +00002636 if (!T)
2637 return;
2638
John McCallf85e1932011-06-15 23:02:42 +00002639 RefVal::Kind hasErr = (RefVal::Kind) 0;
Jordy Rose17a38e22011-09-02 05:55:19 +00002640 state = updateSymbol(state, Sym, *T, AE, hasErr, C);
John McCallf85e1932011-06-15 23:02:42 +00002641
2642 if (hasErr) {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002643 // FIXME: If we get an error during a bridge cast, should we report it?
2644 // Should we assert that there is no error?
John McCallf85e1932011-06-15 23:02:42 +00002645 return;
2646 }
2647
Anna Zaks0bd6b112011-10-26 21:06:34 +00002648 C.addTransition(state);
John McCallf85e1932011-06-15 23:02:42 +00002649}
2650
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002651void RetainCountChecker::processObjCLiterals(CheckerContext &C,
2652 const Expr *Ex) const {
2653 ProgramStateRef state = C.getState();
2654 const ExplodedNode *pred = C.getPredecessor();
2655 for (Stmt::const_child_iterator it = Ex->child_begin(), et = Ex->child_end() ;
2656 it != et ; ++it) {
2657 const Stmt *child = *it;
2658 SVal V = state->getSVal(child, pred->getLocationContext());
2659 if (SymbolRef sym = V.getAsSymbol())
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002660 if (const RefVal* T = getRefBinding(state, sym)) {
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002661 RefVal::Kind hasErr = (RefVal::Kind) 0;
2662 state = updateSymbol(state, sym, *T, MayEscape, hasErr, C);
2663 if (hasErr) {
2664 processNonLeakError(state, child->getSourceRange(), hasErr, sym, C);
2665 return;
2666 }
2667 }
2668 }
2669
2670 // Return the object as autoreleased.
2671 // RetEffect RE = RetEffect::MakeNotOwned(RetEffect::ObjC);
2672 if (SymbolRef sym =
2673 state->getSVal(Ex, pred->getLocationContext()).getAsSymbol()) {
2674 QualType ResultTy = Ex->getType();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002675 state = setRefBinding(state, sym,
2676 RefVal::makeNotOwned(RetEffect::ObjC, ResultTy));
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002677 }
2678
2679 C.addTransition(state);
2680}
2681
2682void RetainCountChecker::checkPostStmt(const ObjCArrayLiteral *AL,
2683 CheckerContext &C) const {
2684 // Apply the 'MayEscape' to all values.
2685 processObjCLiterals(C, AL);
2686}
2687
2688void RetainCountChecker::checkPostStmt(const ObjCDictionaryLiteral *DL,
2689 CheckerContext &C) const {
2690 // Apply the 'MayEscape' to all keys and values.
2691 processObjCLiterals(C, DL);
2692}
2693
Jordy Rose70fdbc32012-05-12 05:10:43 +00002694void RetainCountChecker::checkPostStmt(const ObjCBoxedExpr *Ex,
2695 CheckerContext &C) const {
2696 const ExplodedNode *Pred = C.getPredecessor();
2697 const LocationContext *LCtx = Pred->getLocationContext();
2698 ProgramStateRef State = Pred->getState();
2699
2700 if (SymbolRef Sym = State->getSVal(Ex, LCtx).getAsSymbol()) {
2701 QualType ResultTy = Ex->getType();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002702 State = setRefBinding(State, Sym,
2703 RefVal::makeNotOwned(RetEffect::ObjC, ResultTy));
Jordy Rose70fdbc32012-05-12 05:10:43 +00002704 }
2705
2706 C.addTransition(State);
2707}
2708
Jordan Rosefe6a0112012-07-02 19:28:21 +00002709void RetainCountChecker::checkPostCall(const CallEvent &Call,
2710 CheckerContext &C) const {
Jordan Rosefe6a0112012-07-02 19:28:21 +00002711 RetainSummaryManager &Summaries = getSummaryManager(C);
2712 const RetainSummary *Summ = Summaries.getSummary(Call, C.getState());
Anna Zaks554067f2012-08-29 23:23:43 +00002713
2714 if (C.wasInlined) {
2715 processSummaryOfInlined(*Summ, Call, C);
2716 return;
2717 }
Jordan Rosefe6a0112012-07-02 19:28:21 +00002718 checkSummary(*Summ, Call, C);
Jordy Rose294396b2011-08-22 23:48:23 +00002719}
2720
Jordy Rose910c4052011-09-02 06:44:22 +00002721/// GetReturnType - Used to get the return type of a message expression or
2722/// function call with the intention of affixing that type to a tracked symbol.
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +00002723/// While the return type can be queried directly from RetEx, when
Jordy Rose910c4052011-09-02 06:44:22 +00002724/// invoking class methods we augment to the return type to be that of
2725/// a pointer to the class (as opposed it just being id).
2726// FIXME: We may be able to do this with related result types instead.
2727// This function is probably overestimating.
2728static QualType GetReturnType(const Expr *RetE, ASTContext &Ctx) {
2729 QualType RetTy = RetE->getType();
2730 // If RetE is not a message expression just return its type.
2731 // If RetE is a message expression, return its types if it is something
2732 /// more specific than id.
2733 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RetE))
2734 if (const ObjCObjectPointerType *PT = RetTy->getAs<ObjCObjectPointerType>())
2735 if (PT->isObjCQualifiedIdType() || PT->isObjCIdType() ||
2736 PT->isObjCClassType()) {
2737 // At this point we know the return type of the message expression is
2738 // id, id<...>, or Class. If we have an ObjCInterfaceDecl, we know this
2739 // is a call to a class method whose type we can resolve. In such
2740 // cases, promote the return type to XXX* (where XXX is the class).
2741 const ObjCInterfaceDecl *D = ME->getReceiverInterface();
2742 return !D ? RetTy :
2743 Ctx.getObjCObjectPointerType(Ctx.getObjCInterfaceType(D));
2744 }
2745
2746 return RetTy;
2747}
2748
Anna Zaks554067f2012-08-29 23:23:43 +00002749// We don't always get the exact modeling of the function with regards to the
2750// retain count checker even when the function is inlined. For example, we need
2751// to stop tracking the symbols which were marked with StopTrackingHard.
2752void RetainCountChecker::processSummaryOfInlined(const RetainSummary &Summ,
2753 const CallEvent &CallOrMsg,
2754 CheckerContext &C) const {
2755 ProgramStateRef state = C.getState();
2756
2757 // Evaluate the effect of the arguments.
2758 for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
2759 if (Summ.getArg(idx) == StopTrackingHard) {
2760 SVal V = CallOrMsg.getArgSVal(idx);
2761 if (SymbolRef Sym = V.getAsLocSymbol()) {
2762 state = removeRefBinding(state, Sym);
2763 }
2764 }
2765 }
2766
2767 // Evaluate the effect on the message receiver.
2768 const ObjCMethodCall *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg);
2769 if (MsgInvocation) {
2770 if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
2771 if (Summ.getReceiverEffect() == StopTrackingHard) {
2772 state = removeRefBinding(state, Sym);
2773 }
2774 }
2775 }
2776
2777 // Consult the summary for the return value.
2778 RetEffect RE = Summ.getRetEffect();
2779 if (RE.getKind() == RetEffect::NoRetHard) {
Jordan Rose2f3017f2012-11-02 23:49:29 +00002780 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
Anna Zaks554067f2012-08-29 23:23:43 +00002781 if (Sym)
2782 state = removeRefBinding(state, Sym);
2783 }
2784
2785 C.addTransition(state);
2786}
2787
Jordy Rose910c4052011-09-02 06:44:22 +00002788void RetainCountChecker::checkSummary(const RetainSummary &Summ,
Jordan Rose4531b7d2012-07-02 19:27:43 +00002789 const CallEvent &CallOrMsg,
Jordy Rose910c4052011-09-02 06:44:22 +00002790 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002791 ProgramStateRef state = C.getState();
Jordy Rose294396b2011-08-22 23:48:23 +00002792
2793 // Evaluate the effect of the arguments.
2794 RefVal::Kind hasErr = (RefVal::Kind) 0;
2795 SourceRange ErrorRange;
2796 SymbolRef ErrorSym = 0;
2797
2798 for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
Jordy Rose537716a2011-08-27 22:51:26 +00002799 SVal V = CallOrMsg.getArgSVal(idx);
Jordy Rose294396b2011-08-22 23:48:23 +00002800
2801 if (SymbolRef Sym = V.getAsLocSymbol()) {
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002802 if (const RefVal *T = getRefBinding(state, Sym)) {
Jordy Rose17a38e22011-09-02 05:55:19 +00002803 state = updateSymbol(state, Sym, *T, Summ.getArg(idx), hasErr, C);
Jordy Rose294396b2011-08-22 23:48:23 +00002804 if (hasErr) {
2805 ErrorRange = CallOrMsg.getArgSourceRange(idx);
2806 ErrorSym = Sym;
2807 break;
2808 }
2809 }
2810 }
2811 }
2812
2813 // Evaluate the effect on the message receiver.
2814 bool ReceiverIsTracked = false;
Jordan Rose4531b7d2012-07-02 19:27:43 +00002815 if (!hasErr) {
Jordan Rosecde8cdb2012-07-02 19:27:56 +00002816 const ObjCMethodCall *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg);
Jordan Rose4531b7d2012-07-02 19:27:43 +00002817 if (MsgInvocation) {
2818 if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002819 if (const RefVal *T = getRefBinding(state, Sym)) {
Jordan Rose4531b7d2012-07-02 19:27:43 +00002820 ReceiverIsTracked = true;
2821 state = updateSymbol(state, Sym, *T, Summ.getReceiverEffect(),
Anna Zaks554067f2012-08-29 23:23:43 +00002822 hasErr, C);
Jordan Rose4531b7d2012-07-02 19:27:43 +00002823 if (hasErr) {
Jordan Rose8919e682012-07-18 21:59:51 +00002824 ErrorRange = MsgInvocation->getOriginExpr()->getReceiverRange();
Jordan Rose4531b7d2012-07-02 19:27:43 +00002825 ErrorSym = Sym;
2826 }
Jordy Rose294396b2011-08-22 23:48:23 +00002827 }
2828 }
2829 }
2830 }
2831
2832 // Process any errors.
2833 if (hasErr) {
2834 processNonLeakError(state, ErrorRange, hasErr, ErrorSym, C);
2835 return;
2836 }
2837
2838 // Consult the summary for the return value.
2839 RetEffect RE = Summ.getRetEffect();
2840
2841 if (RE.getKind() == RetEffect::OwnedWhenTrackedReceiver) {
Jordy Roseb6cfc092011-08-25 00:10:37 +00002842 if (ReceiverIsTracked)
Jordy Rose17a38e22011-09-02 05:55:19 +00002843 RE = getSummaryManager(C).getObjAllocRetEffect();
Jordy Roseb6cfc092011-08-25 00:10:37 +00002844 else
Jordy Rose294396b2011-08-22 23:48:23 +00002845 RE = RetEffect::MakeNoRet();
2846 }
2847
2848 switch (RE.getKind()) {
2849 default:
David Blaikie7530c032012-01-17 06:56:22 +00002850 llvm_unreachable("Unhandled RetEffect.");
Jordy Rose294396b2011-08-22 23:48:23 +00002851
2852 case RetEffect::NoRet:
Anna Zaks554067f2012-08-29 23:23:43 +00002853 case RetEffect::NoRetHard:
Jordy Rose294396b2011-08-22 23:48:23 +00002854 // No work necessary.
2855 break;
2856
2857 case RetEffect::OwnedAllocatedSymbol:
2858 case RetEffect::OwnedSymbol: {
Jordan Rose2f3017f2012-11-02 23:49:29 +00002859 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
Jordy Rose294396b2011-08-22 23:48:23 +00002860 if (!Sym)
2861 break;
2862
Jordan Rose4531b7d2012-07-02 19:27:43 +00002863 // Use the result type from the CallEvent as it automatically adjusts
Jordy Rose294396b2011-08-22 23:48:23 +00002864 // for methods/functions that return references.
Jordan Rose4531b7d2012-07-02 19:27:43 +00002865 QualType ResultTy = CallOrMsg.getResultType();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002866 state = setRefBinding(state, Sym, RefVal::makeOwned(RE.getObjKind(),
2867 ResultTy));
Jordy Rose294396b2011-08-22 23:48:23 +00002868
2869 // FIXME: Add a flag to the checker where allocations are assumed to
Anna Zaksc6ba23f2012-08-14 15:39:13 +00002870 // *not* fail.
Jordy Rose294396b2011-08-22 23:48:23 +00002871 break;
2872 }
2873
2874 case RetEffect::GCNotOwnedSymbol:
2875 case RetEffect::ARCNotOwnedSymbol:
2876 case RetEffect::NotOwnedSymbol: {
2877 const Expr *Ex = CallOrMsg.getOriginExpr();
Jordan Rose2f3017f2012-11-02 23:49:29 +00002878 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
Jordy Rose294396b2011-08-22 23:48:23 +00002879 if (!Sym)
2880 break;
Ted Kremenek74616822012-10-12 22:56:45 +00002881 assert(Ex);
Jordy Rose294396b2011-08-22 23:48:23 +00002882 // Use GetReturnType in order to give [NSFoo alloc] the type NSFoo *.
2883 QualType ResultTy = GetReturnType(Ex, C.getASTContext());
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002884 state = setRefBinding(state, Sym, RefVal::makeNotOwned(RE.getObjKind(),
2885 ResultTy));
Jordy Rose294396b2011-08-22 23:48:23 +00002886 break;
2887 }
2888 }
2889
2890 // This check is actually necessary; otherwise the statement builder thinks
2891 // we've hit a previously-found path.
2892 // Normally addTransition takes care of this, but we want the node pointer.
2893 ExplodedNode *NewNode;
2894 if (state == C.getState()) {
2895 NewNode = C.getPredecessor();
2896 } else {
Anna Zaks0bd6b112011-10-26 21:06:34 +00002897 NewNode = C.addTransition(state);
Jordy Rose294396b2011-08-22 23:48:23 +00002898 }
2899
Jordy Rose9c083b72011-08-24 18:56:32 +00002900 // Annotate the node with summary we used.
2901 if (NewNode) {
2902 // FIXME: This is ugly. See checkEndAnalysis for why it's necessary.
2903 if (ShouldResetSummaryLog) {
2904 SummaryLog.clear();
2905 ShouldResetSummaryLog = false;
2906 }
Jordy Roseec9ef852011-08-23 20:55:48 +00002907 SummaryLog[NewNode] = &Summ;
Jordy Rose9c083b72011-08-24 18:56:32 +00002908 }
Jordy Rose294396b2011-08-22 23:48:23 +00002909}
2910
Jordy Rosee0a5d322011-08-23 20:27:16 +00002911
Ted Kremenek8bef8232012-01-26 21:29:00 +00002912ProgramStateRef
2913RetainCountChecker::updateSymbol(ProgramStateRef state, SymbolRef sym,
Jordy Rose910c4052011-09-02 06:44:22 +00002914 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
2915 CheckerContext &C) const {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002916 // In GC mode [... release] and [... retain] do nothing.
Jordy Rose910c4052011-09-02 06:44:22 +00002917 // In ARC mode they shouldn't exist at all, but we just ignore them.
Jordy Rose17a38e22011-09-02 05:55:19 +00002918 bool IgnoreRetainMsg = C.isObjCGCEnabled();
2919 if (!IgnoreRetainMsg)
David Blaikie4e4d0842012-03-11 07:00:24 +00002920 IgnoreRetainMsg = (bool)C.getASTContext().getLangOpts().ObjCAutoRefCount;
Jordy Rose17a38e22011-09-02 05:55:19 +00002921
Jordy Rosee0a5d322011-08-23 20:27:16 +00002922 switch (E) {
Jordan Rose4531b7d2012-07-02 19:27:43 +00002923 default:
2924 break;
2925 case IncRefMsg:
2926 E = IgnoreRetainMsg ? DoNothing : IncRef;
2927 break;
2928 case DecRefMsg:
2929 E = IgnoreRetainMsg ? DoNothing : DecRef;
2930 break;
Anna Zaks554067f2012-08-29 23:23:43 +00002931 case DecRefMsgAndStopTrackingHard:
2932 E = IgnoreRetainMsg ? StopTracking : DecRefAndStopTrackingHard;
Jordan Rose4531b7d2012-07-02 19:27:43 +00002933 break;
2934 case MakeCollectable:
2935 E = C.isObjCGCEnabled() ? DecRef : DoNothing;
2936 break;
Jordy Rosee0a5d322011-08-23 20:27:16 +00002937 }
2938
2939 // Handle all use-after-releases.
Jordy Rose17a38e22011-09-02 05:55:19 +00002940 if (!C.isObjCGCEnabled() && V.getKind() == RefVal::Released) {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002941 V = V ^ RefVal::ErrorUseAfterRelease;
2942 hasErr = V.getKind();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002943 return setRefBinding(state, sym, V);
Jordy Rosee0a5d322011-08-23 20:27:16 +00002944 }
2945
2946 switch (E) {
2947 case DecRefMsg:
2948 case IncRefMsg:
2949 case MakeCollectable:
Anna Zaks554067f2012-08-29 23:23:43 +00002950 case DecRefMsgAndStopTrackingHard:
Jordy Rosee0a5d322011-08-23 20:27:16 +00002951 llvm_unreachable("DecRefMsg/IncRefMsg/MakeCollectable already converted");
Jordy Rosee0a5d322011-08-23 20:27:16 +00002952
2953 case Dealloc:
2954 // Any use of -dealloc in GC is *bad*.
Jordy Rose17a38e22011-09-02 05:55:19 +00002955 if (C.isObjCGCEnabled()) {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002956 V = V ^ RefVal::ErrorDeallocGC;
2957 hasErr = V.getKind();
2958 break;
2959 }
2960
2961 switch (V.getKind()) {
2962 default:
2963 llvm_unreachable("Invalid RefVal state for an explicit dealloc.");
Jordy Rosee0a5d322011-08-23 20:27:16 +00002964 case RefVal::Owned:
2965 // The object immediately transitions to the released state.
2966 V = V ^ RefVal::Released;
2967 V.clearCounts();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002968 return setRefBinding(state, sym, V);
Jordy Rosee0a5d322011-08-23 20:27:16 +00002969 case RefVal::NotOwned:
2970 V = V ^ RefVal::ErrorDeallocNotOwned;
2971 hasErr = V.getKind();
2972 break;
2973 }
2974 break;
2975
Jordy Rosee0a5d322011-08-23 20:27:16 +00002976 case MayEscape:
2977 if (V.getKind() == RefVal::Owned) {
2978 V = V ^ RefVal::NotOwned;
2979 break;
2980 }
2981
2982 // Fall-through.
2983
Jordy Rosee0a5d322011-08-23 20:27:16 +00002984 case DoNothing:
2985 return state;
2986
2987 case Autorelease:
Jordy Rose17a38e22011-09-02 05:55:19 +00002988 if (C.isObjCGCEnabled())
Jordy Rosee0a5d322011-08-23 20:27:16 +00002989 return state;
Jordy Rosee0a5d322011-08-23 20:27:16 +00002990 // Update the autorelease counts.
Jordy Rosee0a5d322011-08-23 20:27:16 +00002991 V = V.autorelease();
2992 break;
2993
2994 case StopTracking:
Anna Zaks554067f2012-08-29 23:23:43 +00002995 case StopTrackingHard:
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002996 return removeRefBinding(state, sym);
Jordy Rosee0a5d322011-08-23 20:27:16 +00002997
2998 case IncRef:
2999 switch (V.getKind()) {
3000 default:
3001 llvm_unreachable("Invalid RefVal state for a retain.");
Jordy Rosee0a5d322011-08-23 20:27:16 +00003002 case RefVal::Owned:
3003 case RefVal::NotOwned:
3004 V = V + 1;
3005 break;
3006 case RefVal::Released:
3007 // Non-GC cases are handled above.
Jordy Rose17a38e22011-09-02 05:55:19 +00003008 assert(C.isObjCGCEnabled());
Jordy Rosee0a5d322011-08-23 20:27:16 +00003009 V = (V ^ RefVal::Owned) + 1;
3010 break;
3011 }
3012 break;
3013
Jordy Rosee0a5d322011-08-23 20:27:16 +00003014 case DecRef:
3015 case DecRefBridgedTransfered:
Anna Zaks554067f2012-08-29 23:23:43 +00003016 case DecRefAndStopTrackingHard:
Jordy Rosee0a5d322011-08-23 20:27:16 +00003017 switch (V.getKind()) {
3018 default:
3019 // case 'RefVal::Released' handled above.
3020 llvm_unreachable("Invalid RefVal state for a release.");
Jordy Rosee0a5d322011-08-23 20:27:16 +00003021
3022 case RefVal::Owned:
3023 assert(V.getCount() > 0);
3024 if (V.getCount() == 1)
3025 V = V ^ (E == DecRefBridgedTransfered ?
3026 RefVal::NotOwned : RefVal::Released);
Anna Zaks554067f2012-08-29 23:23:43 +00003027 else if (E == DecRefAndStopTrackingHard)
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003028 return removeRefBinding(state, sym);
Jordan Rose4531b7d2012-07-02 19:27:43 +00003029
Jordy Rosee0a5d322011-08-23 20:27:16 +00003030 V = V - 1;
3031 break;
3032
3033 case RefVal::NotOwned:
Jordan Rose4531b7d2012-07-02 19:27:43 +00003034 if (V.getCount() > 0) {
Anna Zaks554067f2012-08-29 23:23:43 +00003035 if (E == DecRefAndStopTrackingHard)
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003036 return removeRefBinding(state, sym);
Jordy Rosee0a5d322011-08-23 20:27:16 +00003037 V = V - 1;
Jordan Rose4531b7d2012-07-02 19:27:43 +00003038 } else {
Jordy Rosee0a5d322011-08-23 20:27:16 +00003039 V = V ^ RefVal::ErrorReleaseNotOwned;
3040 hasErr = V.getKind();
3041 }
3042 break;
3043
3044 case RefVal::Released:
3045 // Non-GC cases are handled above.
Jordy Rose17a38e22011-09-02 05:55:19 +00003046 assert(C.isObjCGCEnabled());
Jordy Rosee0a5d322011-08-23 20:27:16 +00003047 V = V ^ RefVal::ErrorUseAfterRelease;
3048 hasErr = V.getKind();
3049 break;
3050 }
3051 break;
3052 }
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003053 return setRefBinding(state, sym, V);
Jordy Rosee0a5d322011-08-23 20:27:16 +00003054}
3055
Ted Kremenek8bef8232012-01-26 21:29:00 +00003056void RetainCountChecker::processNonLeakError(ProgramStateRef St,
Jordy Rose910c4052011-09-02 06:44:22 +00003057 SourceRange ErrorRange,
3058 RefVal::Kind ErrorKind,
3059 SymbolRef Sym,
3060 CheckerContext &C) const {
Jordy Rose294396b2011-08-22 23:48:23 +00003061 ExplodedNode *N = C.generateSink(St);
3062 if (!N)
3063 return;
3064
Jordy Rose294396b2011-08-22 23:48:23 +00003065 CFRefBug *BT;
3066 switch (ErrorKind) {
3067 default:
3068 llvm_unreachable("Unhandled error.");
Jordy Rose294396b2011-08-22 23:48:23 +00003069 case RefVal::ErrorUseAfterRelease:
Jordy Rosed6334e12011-08-25 00:34:03 +00003070 if (!useAfterRelease)
3071 useAfterRelease.reset(new UseAfterRelease());
3072 BT = &*useAfterRelease;
Jordy Rose294396b2011-08-22 23:48:23 +00003073 break;
3074 case RefVal::ErrorReleaseNotOwned:
Jordy Rosed6334e12011-08-25 00:34:03 +00003075 if (!releaseNotOwned)
3076 releaseNotOwned.reset(new BadRelease());
3077 BT = &*releaseNotOwned;
Jordy Rose294396b2011-08-22 23:48:23 +00003078 break;
3079 case RefVal::ErrorDeallocGC:
Jordy Rosed6334e12011-08-25 00:34:03 +00003080 if (!deallocGC)
3081 deallocGC.reset(new DeallocGC());
3082 BT = &*deallocGC;
Jordy Rose294396b2011-08-22 23:48:23 +00003083 break;
3084 case RefVal::ErrorDeallocNotOwned:
Jordy Rosed6334e12011-08-25 00:34:03 +00003085 if (!deallocNotOwned)
3086 deallocNotOwned.reset(new DeallocNotOwned());
3087 BT = &*deallocNotOwned;
Jordy Rose294396b2011-08-22 23:48:23 +00003088 break;
3089 }
3090
Jordy Rosed6334e12011-08-25 00:34:03 +00003091 assert(BT);
David Blaikie4e4d0842012-03-11 07:00:24 +00003092 CFRefReport *report = new CFRefReport(*BT, C.getASTContext().getLangOpts(),
Jordy Rose17a38e22011-09-02 05:55:19 +00003093 C.isObjCGCEnabled(), SummaryLog,
3094 N, Sym);
Jordy Rose294396b2011-08-22 23:48:23 +00003095 report->addRange(ErrorRange);
Jordan Rose785950e2012-11-02 01:53:40 +00003096 C.emitReport(report);
Jordy Rose294396b2011-08-22 23:48:23 +00003097}
3098
Jordy Rose910c4052011-09-02 06:44:22 +00003099//===----------------------------------------------------------------------===//
3100// Handle the return values of retain-count-related functions.
3101//===----------------------------------------------------------------------===//
3102
3103bool RetainCountChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
Jordy Rose76c506f2011-08-21 21:58:18 +00003104 // Get the callee. We're only interested in simple C functions.
Ted Kremenek8bef8232012-01-26 21:29:00 +00003105 ProgramStateRef state = C.getState();
Anna Zaksb805c8f2011-12-01 05:57:37 +00003106 const FunctionDecl *FD = C.getCalleeDecl(CE);
Jordy Rose76c506f2011-08-21 21:58:18 +00003107 if (!FD)
3108 return false;
3109
3110 IdentifierInfo *II = FD->getIdentifier();
3111 if (!II)
3112 return false;
3113
3114 // For now, we're only handling the functions that return aliases of their
3115 // arguments: CFRetain and CFMakeCollectable (and their families).
3116 // Eventually we should add other functions we can model entirely,
3117 // such as CFRelease, which don't invalidate their arguments or globals.
3118 if (CE->getNumArgs() != 1)
3119 return false;
3120
3121 // Get the name of the function.
3122 StringRef FName = II->getName();
3123 FName = FName.substr(FName.find_first_not_of('_'));
3124
3125 // See if it's one of the specific functions we know how to eval.
3126 bool canEval = false;
3127
Anna Zaksb805c8f2011-12-01 05:57:37 +00003128 QualType ResultTy = CE->getCallReturnType();
Jordy Rose76c506f2011-08-21 21:58:18 +00003129 if (ResultTy->isObjCIdType()) {
3130 // Handle: id NSMakeCollectable(CFTypeRef)
3131 canEval = II->isStr("NSMakeCollectable");
3132 } else if (ResultTy->isPointerType()) {
3133 // Handle: (CF|CG)Retain
3134 // CFMakeCollectable
3135 // It's okay to be a little sloppy here (CGMakeCollectable doesn't exist).
3136 if (cocoa::isRefType(ResultTy, "CF", FName) ||
3137 cocoa::isRefType(ResultTy, "CG", FName)) {
3138 canEval = isRetain(FD, FName) || isMakeCollectable(FD, FName);
3139 }
3140 }
3141
3142 if (!canEval)
3143 return false;
3144
3145 // Bind the return value.
Ted Kremenek5eca4822012-01-06 22:09:28 +00003146 const LocationContext *LCtx = C.getLocationContext();
3147 SVal RetVal = state->getSVal(CE->getArg(0), LCtx);
Jordy Rose76c506f2011-08-21 21:58:18 +00003148 if (RetVal.isUnknown()) {
3149 // If the receiver is unknown, conjure a return value.
3150 SValBuilder &SVB = C.getSValBuilder();
Ted Kremenek66c486f2012-08-22 06:26:15 +00003151 RetVal = SVB.conjureSymbolVal(0, CE, LCtx, ResultTy, C.blockCount());
Jordy Rose76c506f2011-08-21 21:58:18 +00003152 }
Ted Kremenek5eca4822012-01-06 22:09:28 +00003153 state = state->BindExpr(CE, LCtx, RetVal, false);
Jordy Rose76c506f2011-08-21 21:58:18 +00003154
Jordy Rose294396b2011-08-22 23:48:23 +00003155 // FIXME: This should not be necessary, but otherwise the argument seems to be
3156 // considered alive during the next statement.
3157 if (const MemRegion *ArgRegion = RetVal.getAsRegion()) {
3158 // Save the refcount status of the argument.
3159 SymbolRef Sym = RetVal.getAsLocSymbol();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003160 const RefVal *Binding = 0;
Jordy Rose294396b2011-08-22 23:48:23 +00003161 if (Sym)
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003162 Binding = getRefBinding(state, Sym);
Jordy Rose76c506f2011-08-21 21:58:18 +00003163
Jordy Rose294396b2011-08-22 23:48:23 +00003164 // Invalidate the argument region.
Anna Zaksbf53dfa2012-12-20 00:38:25 +00003165 state = state->invalidateRegions(ArgRegion, CE, C.blockCount(), LCtx,
Anna Zaks64eb0702013-01-16 01:35:54 +00003166 /*CausesPointerEscape*/ false);
Jordy Rose76c506f2011-08-21 21:58:18 +00003167
Jordy Rose294396b2011-08-22 23:48:23 +00003168 // Restore the refcount status of the argument.
3169 if (Binding)
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003170 state = setRefBinding(state, Sym, *Binding);
Jordy Rose294396b2011-08-22 23:48:23 +00003171 }
3172
Anna Zaks0bd6b112011-10-26 21:06:34 +00003173 C.addTransition(state);
Jordy Rose76c506f2011-08-21 21:58:18 +00003174 return true;
3175}
3176
Jordy Rose910c4052011-09-02 06:44:22 +00003177//===----------------------------------------------------------------------===//
3178// Handle return statements.
3179//===----------------------------------------------------------------------===//
Jordy Rosef53e8c72011-08-23 19:43:16 +00003180
Jordy Rose910c4052011-09-02 06:44:22 +00003181void RetainCountChecker::checkPreStmt(const ReturnStmt *S,
3182 CheckerContext &C) const {
Ted Kremeneke5715782012-02-25 02:09:09 +00003183
3184 // Only adjust the reference count if this is the top-level call frame,
3185 // and not the result of inlining. In the future, we should do
3186 // better checking even for inlined calls, and see if they match
3187 // with their expected semantics (e.g., the method should return a retained
3188 // object, etc.).
Anna Zaksfadcd5d2012-11-03 02:54:16 +00003189 if (!C.inTopFrame())
Ted Kremeneke5715782012-02-25 02:09:09 +00003190 return;
3191
Jordy Rosef53e8c72011-08-23 19:43:16 +00003192 const Expr *RetE = S->getRetValue();
3193 if (!RetE)
3194 return;
3195
Ted Kremenek8bef8232012-01-26 21:29:00 +00003196 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00003197 SymbolRef Sym =
3198 state->getSValAsScalarOrLoc(RetE, C.getLocationContext()).getAsLocSymbol();
Jordy Rosef53e8c72011-08-23 19:43:16 +00003199 if (!Sym)
3200 return;
3201
3202 // Get the reference count binding (if any).
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003203 const RefVal *T = getRefBinding(state, Sym);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003204 if (!T)
3205 return;
3206
3207 // Change the reference count.
3208 RefVal X = *T;
3209
3210 switch (X.getKind()) {
3211 case RefVal::Owned: {
3212 unsigned cnt = X.getCount();
3213 assert(cnt > 0);
3214 X.setCount(cnt - 1);
3215 X = X ^ RefVal::ReturnedOwned;
3216 break;
3217 }
3218
3219 case RefVal::NotOwned: {
3220 unsigned cnt = X.getCount();
3221 if (cnt) {
3222 X.setCount(cnt - 1);
3223 X = X ^ RefVal::ReturnedOwned;
3224 }
3225 else {
3226 X = X ^ RefVal::ReturnedNotOwned;
3227 }
3228 break;
3229 }
3230
3231 default:
3232 return;
3233 }
3234
3235 // Update the binding.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003236 state = setRefBinding(state, Sym, X);
Anna Zaks0bd6b112011-10-26 21:06:34 +00003237 ExplodedNode *Pred = C.addTransition(state);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003238
3239 // At this point we have updated the state properly.
3240 // Everything after this is merely checking to see if the return value has
3241 // been over- or under-retained.
3242
3243 // Did we cache out?
3244 if (!Pred)
3245 return;
3246
Jordy Rosef53e8c72011-08-23 19:43:16 +00003247 // Update the autorelease counts.
3248 static SimpleProgramPointTag
Jordy Rose910c4052011-09-02 06:44:22 +00003249 AutoreleaseTag("RetainCountChecker : Autorelease");
Jordan Rose4ee1c552012-12-06 18:58:18 +00003250 state = handleAutoreleaseCounts(state, Pred, &AutoreleaseTag, C, Sym, X);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003251
3252 // Did we cache out?
Jordan Rose4ee1c552012-12-06 18:58:18 +00003253 if (!state)
Jordy Rosef53e8c72011-08-23 19:43:16 +00003254 return;
3255
3256 // Get the updated binding.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003257 T = getRefBinding(state, Sym);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003258 assert(T);
3259 X = *T;
3260
3261 // Consult the summary of the enclosing method.
Jordy Rose17a38e22011-09-02 05:55:19 +00003262 RetainSummaryManager &Summaries = getSummaryManager(C);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003263 const Decl *CD = &Pred->getCodeDecl();
Jordan Rose4531b7d2012-07-02 19:27:43 +00003264 RetEffect RE = RetEffect::MakeNoRet();
Jordy Rosef53e8c72011-08-23 19:43:16 +00003265
Jordan Rose4531b7d2012-07-02 19:27:43 +00003266 // FIXME: What is the convention for blocks? Is there one?
Jordy Rosef53e8c72011-08-23 19:43:16 +00003267 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CD)) {
Jordy Roseb6cfc092011-08-25 00:10:37 +00003268 const RetainSummary *Summ = Summaries.getMethodSummary(MD);
Jordan Rose4531b7d2012-07-02 19:27:43 +00003269 RE = Summ->getRetEffect();
3270 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) {
3271 if (!isa<CXXMethodDecl>(FD)) {
3272 const RetainSummary *Summ = Summaries.getFunctionSummary(FD);
3273 RE = Summ->getRetEffect();
3274 }
Jordy Rosef53e8c72011-08-23 19:43:16 +00003275 }
3276
Jordan Rose4531b7d2012-07-02 19:27:43 +00003277 checkReturnWithRetEffect(S, C, Pred, RE, X, Sym, state);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003278}
3279
Jordy Rose910c4052011-09-02 06:44:22 +00003280void RetainCountChecker::checkReturnWithRetEffect(const ReturnStmt *S,
3281 CheckerContext &C,
3282 ExplodedNode *Pred,
3283 RetEffect RE, RefVal X,
3284 SymbolRef Sym,
Ted Kremenek8bef8232012-01-26 21:29:00 +00003285 ProgramStateRef state) const {
Jordy Rosef53e8c72011-08-23 19:43:16 +00003286 // Any leaks or other errors?
3287 if (X.isReturnedOwned() && X.getCount() == 0) {
3288 if (RE.getKind() != RetEffect::NoRet) {
3289 bool hasError = false;
Jordy Rose17a38e22011-09-02 05:55:19 +00003290 if (C.isObjCGCEnabled() && RE.getObjKind() == RetEffect::ObjC) {
Jordy Rosef53e8c72011-08-23 19:43:16 +00003291 // Things are more complicated with garbage collection. If the
3292 // returned object is suppose to be an Objective-C object, we have
3293 // a leak (as the caller expects a GC'ed object) because no
3294 // method should return ownership unless it returns a CF object.
3295 hasError = true;
3296 X = X ^ RefVal::ErrorGCLeakReturned;
3297 }
3298 else if (!RE.isOwned()) {
3299 // Either we are using GC and the returned object is a CF type
3300 // or we aren't using GC. In either case, we expect that the
3301 // enclosing method is expected to return ownership.
3302 hasError = true;
3303 X = X ^ RefVal::ErrorLeakReturned;
3304 }
3305
3306 if (hasError) {
3307 // Generate an error node.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003308 state = setRefBinding(state, Sym, X);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003309
3310 static SimpleProgramPointTag
Jordy Rose910c4052011-09-02 06:44:22 +00003311 ReturnOwnLeakTag("RetainCountChecker : ReturnsOwnLeak");
Anna Zaks0bd6b112011-10-26 21:06:34 +00003312 ExplodedNode *N = C.addTransition(state, Pred, &ReturnOwnLeakTag);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003313 if (N) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003314 const LangOptions &LOpts = C.getASTContext().getLangOpts();
Jordy Rose17a38e22011-09-02 05:55:19 +00003315 bool GCEnabled = C.isObjCGCEnabled();
Jordy Rosef53e8c72011-08-23 19:43:16 +00003316 CFRefReport *report =
Jordy Rose17a38e22011-09-02 05:55:19 +00003317 new CFRefLeakReport(*getLeakAtReturnBug(LOpts, GCEnabled),
3318 LOpts, GCEnabled, SummaryLog,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003319 N, Sym, C);
Jordan Rose785950e2012-11-02 01:53:40 +00003320 C.emitReport(report);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003321 }
3322 }
3323 }
3324 } else if (X.isReturnedNotOwned()) {
3325 if (RE.isOwned()) {
3326 // Trying to return a not owned object to a caller expecting an
3327 // owned object.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003328 state = setRefBinding(state, Sym, X ^ RefVal::ErrorReturnedNotOwned);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003329
3330 static SimpleProgramPointTag
Jordy Rose910c4052011-09-02 06:44:22 +00003331 ReturnNotOwnedTag("RetainCountChecker : ReturnNotOwnedForOwned");
Anna Zaks0bd6b112011-10-26 21:06:34 +00003332 ExplodedNode *N = C.addTransition(state, Pred, &ReturnNotOwnedTag);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003333 if (N) {
Jordy Rosed6334e12011-08-25 00:34:03 +00003334 if (!returnNotOwnedForOwned)
3335 returnNotOwnedForOwned.reset(new ReturnedNotOwnedForOwned());
3336
Jordy Rosef53e8c72011-08-23 19:43:16 +00003337 CFRefReport *report =
Jordy Rosed6334e12011-08-25 00:34:03 +00003338 new CFRefReport(*returnNotOwnedForOwned,
David Blaikie4e4d0842012-03-11 07:00:24 +00003339 C.getASTContext().getLangOpts(),
Jordy Rose17a38e22011-09-02 05:55:19 +00003340 C.isObjCGCEnabled(), SummaryLog, N, Sym);
Jordan Rose785950e2012-11-02 01:53:40 +00003341 C.emitReport(report);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003342 }
3343 }
3344 }
3345}
3346
Jordy Rose8d228632011-08-23 20:07:14 +00003347//===----------------------------------------------------------------------===//
Jordy Rose910c4052011-09-02 06:44:22 +00003348// Check various ways a symbol can be invalidated.
3349//===----------------------------------------------------------------------===//
3350
Anna Zaks390909c2011-10-06 00:43:15 +00003351void RetainCountChecker::checkBind(SVal loc, SVal val, const Stmt *S,
Jordy Rose910c4052011-09-02 06:44:22 +00003352 CheckerContext &C) const {
3353 // Are we storing to something that causes the value to "escape"?
3354 bool escapes = true;
3355
3356 // A value escapes in three possible cases (this may change):
3357 //
3358 // (1) we are binding to something that is not a memory region.
3359 // (2) we are binding to a memregion that does not have stack storage
3360 // (3) we are binding to a memregion with stack storage that the store
3361 // does not understand.
Ted Kremenek8bef8232012-01-26 21:29:00 +00003362 ProgramStateRef state = C.getState();
Jordy Rose910c4052011-09-02 06:44:22 +00003363
3364 if (loc::MemRegionVal *regionLoc = dyn_cast<loc::MemRegionVal>(&loc)) {
3365 escapes = !regionLoc->getRegion()->hasStackStorage();
3366
3367 if (!escapes) {
3368 // To test (3), generate a new state with the binding added. If it is
3369 // the same state, then it escapes (since the store cannot represent
3370 // the binding).
Anna Zakse7958da2012-05-02 00:15:40 +00003371 // Do this only if we know that the store is not supposed to generate the
3372 // same state.
3373 SVal StoredVal = state->getSVal(regionLoc->getRegion());
3374 if (StoredVal != val)
3375 escapes = (state == (state->bindLoc(*regionLoc, val)));
Jordy Rose910c4052011-09-02 06:44:22 +00003376 }
Ted Kremenekde5b4fb2012-03-27 01:12:45 +00003377 if (!escapes) {
3378 // Case 4: We do not currently model what happens when a symbol is
3379 // assigned to a struct field, so be conservative here and let the symbol
3380 // go. TODO: This could definitely be improved upon.
3381 escapes = !isa<VarRegion>(regionLoc->getRegion());
3382 }
Jordy Rose910c4052011-09-02 06:44:22 +00003383 }
3384
3385 // If our store can represent the binding and we aren't storing to something
3386 // that doesn't have local storage then just return and have the simulation
3387 // state continue as is.
3388 if (!escapes)
3389 return;
3390
3391 // Otherwise, find all symbols referenced by 'val' that we are tracking
3392 // and stop tracking them.
3393 state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
Anna Zaks0bd6b112011-10-26 21:06:34 +00003394 C.addTransition(state);
Jordy Rose910c4052011-09-02 06:44:22 +00003395}
3396
Ted Kremenek8bef8232012-01-26 21:29:00 +00003397ProgramStateRef RetainCountChecker::evalAssume(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003398 SVal Cond,
3399 bool Assumption) const {
3400
3401 // FIXME: We may add to the interface of evalAssume the list of symbols
3402 // whose assumptions have changed. For now we just iterate through the
3403 // bindings and check if any of the tracked symbols are NULL. This isn't
3404 // too bad since the number of symbols we will track in practice are
3405 // probably small and evalAssume is only called at branches and a few
3406 // other places.
Jordan Rose166d5022012-11-02 01:54:06 +00003407 RefBindingsTy B = state->get<RefBindings>();
Jordy Rose910c4052011-09-02 06:44:22 +00003408
3409 if (B.isEmpty())
3410 return state;
3411
3412 bool changed = false;
Jordan Rose166d5022012-11-02 01:54:06 +00003413 RefBindingsTy::Factory &RefBFactory = state->get_context<RefBindings>();
Jordy Rose910c4052011-09-02 06:44:22 +00003414
Jordan Rose166d5022012-11-02 01:54:06 +00003415 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Ted Kremenek47cbd0f2012-09-07 22:31:01 +00003416 // Check if the symbol is null stop tracking the symbol.
Jordan Roseec8d4202012-11-01 00:18:27 +00003417 ConstraintManager &CMgr = state->getConstraintManager();
3418 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
3419 if (AllocFailed.isConstrainedTrue()) {
Jordy Rose910c4052011-09-02 06:44:22 +00003420 changed = true;
3421 B = RefBFactory.remove(B, I.getKey());
3422 }
3423 }
3424
3425 if (changed)
3426 state = state->set<RefBindings>(B);
3427
3428 return state;
3429}
3430
Ted Kremenek8bef8232012-01-26 21:29:00 +00003431ProgramStateRef
3432RetainCountChecker::checkRegionChanges(ProgramStateRef state,
Anna Zaksbf53dfa2012-12-20 00:38:25 +00003433 const InvalidatedSymbols *invalidated,
Jordy Rose910c4052011-09-02 06:44:22 +00003434 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00003435 ArrayRef<const MemRegion *> Regions,
Jordan Rose740d4902012-07-02 19:27:35 +00003436 const CallEvent *Call) const {
Jordy Rose910c4052011-09-02 06:44:22 +00003437 if (!invalidated)
3438 return state;
3439
3440 llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
3441 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
3442 E = ExplicitRegions.end(); I != E; ++I) {
3443 if (const SymbolicRegion *SR = (*I)->StripCasts()->getAs<SymbolicRegion>())
3444 WhitelistedSymbols.insert(SR->getSymbol());
3445 }
3446
Anna Zaksbf53dfa2012-12-20 00:38:25 +00003447 for (InvalidatedSymbols::const_iterator I=invalidated->begin(),
Jordy Rose910c4052011-09-02 06:44:22 +00003448 E = invalidated->end(); I!=E; ++I) {
3449 SymbolRef sym = *I;
3450 if (WhitelistedSymbols.count(sym))
3451 continue;
3452 // Remove any existing reference-count binding.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003453 state = removeRefBinding(state, sym);
Jordy Rose910c4052011-09-02 06:44:22 +00003454 }
3455 return state;
3456}
3457
3458//===----------------------------------------------------------------------===//
Jordy Rose8d228632011-08-23 20:07:14 +00003459// Handle dead symbols and end-of-path.
3460//===----------------------------------------------------------------------===//
3461
Jordan Rose4ee1c552012-12-06 18:58:18 +00003462ProgramStateRef
3463RetainCountChecker::handleAutoreleaseCounts(ProgramStateRef state,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003464 ExplodedNode *Pred,
Jordan Rose2bce86c2012-08-18 00:30:16 +00003465 const ProgramPointTag *Tag,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003466 CheckerContext &Ctx,
Jordy Rose910c4052011-09-02 06:44:22 +00003467 SymbolRef Sym, RefVal V) const {
Jordy Rose8d228632011-08-23 20:07:14 +00003468 unsigned ACnt = V.getAutoreleaseCount();
3469
3470 // No autorelease counts? Nothing to be done.
3471 if (!ACnt)
Jordan Rose4ee1c552012-12-06 18:58:18 +00003472 return state;
Jordy Rose8d228632011-08-23 20:07:14 +00003473
Anna Zaks6a93bd52011-10-25 19:57:11 +00003474 assert(!Ctx.isObjCGCEnabled() && "Autorelease counts in GC mode?");
Jordy Rose8d228632011-08-23 20:07:14 +00003475 unsigned Cnt = V.getCount();
3476
3477 // FIXME: Handle sending 'autorelease' to already released object.
3478
3479 if (V.getKind() == RefVal::ReturnedOwned)
3480 ++Cnt;
3481
3482 if (ACnt <= Cnt) {
3483 if (ACnt == Cnt) {
3484 V.clearCounts();
3485 if (V.getKind() == RefVal::ReturnedOwned)
3486 V = V ^ RefVal::ReturnedNotOwned;
3487 else
3488 V = V ^ RefVal::NotOwned;
3489 } else {
3490 V.setCount(Cnt - ACnt);
3491 V.setAutoreleaseCount(0);
3492 }
Jordan Rose4ee1c552012-12-06 18:58:18 +00003493 return setRefBinding(state, Sym, V);
Jordy Rose8d228632011-08-23 20:07:14 +00003494 }
3495
3496 // Woah! More autorelease counts then retain counts left.
3497 // Emit hard error.
3498 V = V ^ RefVal::ErrorOverAutorelease;
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003499 state = setRefBinding(state, Sym, V);
Jordy Rose8d228632011-08-23 20:07:14 +00003500
Jordan Rosefa06f042012-08-20 18:43:42 +00003501 ExplodedNode *N = Ctx.generateSink(state, Pred, Tag);
Jordan Rose2bce86c2012-08-18 00:30:16 +00003502 if (N) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003503 SmallString<128> sbuf;
Jordy Rose8d228632011-08-23 20:07:14 +00003504 llvm::raw_svector_ostream os(sbuf);
3505 os << "Object over-autoreleased: object was sent -autorelease ";
3506 if (V.getAutoreleaseCount() > 1)
3507 os << V.getAutoreleaseCount() << " times ";
3508 os << "but the object has a +" << V.getCount() << " retain count";
3509
Jordy Rosed6334e12011-08-25 00:34:03 +00003510 if (!overAutorelease)
3511 overAutorelease.reset(new OverAutorelease());
3512
David Blaikie4e4d0842012-03-11 07:00:24 +00003513 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
Jordy Rose8d228632011-08-23 20:07:14 +00003514 CFRefReport *report =
Jordy Rosed6334e12011-08-25 00:34:03 +00003515 new CFRefReport(*overAutorelease, LOpts, /* GCEnabled = */ false,
3516 SummaryLog, N, Sym, os.str());
Jordan Rose785950e2012-11-02 01:53:40 +00003517 Ctx.emitReport(report);
Jordy Rose8d228632011-08-23 20:07:14 +00003518 }
3519
Jordan Rose4ee1c552012-12-06 18:58:18 +00003520 return 0;
Jordy Rose8d228632011-08-23 20:07:14 +00003521}
Jordy Rose38f17d62011-08-23 19:01:07 +00003522
Ted Kremenek8bef8232012-01-26 21:29:00 +00003523ProgramStateRef
3524RetainCountChecker::handleSymbolDeath(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003525 SymbolRef sid, RefVal V,
Jordy Rose38f17d62011-08-23 19:01:07 +00003526 SmallVectorImpl<SymbolRef> &Leaked) const {
Jordy Rose53376122011-08-24 04:48:19 +00003527 bool hasLeak = false;
Jordy Rose38f17d62011-08-23 19:01:07 +00003528 if (V.isOwned())
3529 hasLeak = true;
3530 else if (V.isNotOwned() || V.isReturnedOwned())
3531 hasLeak = (V.getCount() > 0);
3532
3533 if (!hasLeak)
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003534 return removeRefBinding(state, sid);
Jordy Rose38f17d62011-08-23 19:01:07 +00003535
3536 Leaked.push_back(sid);
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003537 return setRefBinding(state, sid, V ^ RefVal::ErrorLeak);
Jordy Rose38f17d62011-08-23 19:01:07 +00003538}
3539
3540ExplodedNode *
Ted Kremenek8bef8232012-01-26 21:29:00 +00003541RetainCountChecker::processLeaks(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003542 SmallVectorImpl<SymbolRef> &Leaked,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003543 CheckerContext &Ctx,
3544 ExplodedNode *Pred) const {
Jordy Rose38f17d62011-08-23 19:01:07 +00003545 // Generate an intermediate node representing the leak point.
Jordan Rose2bce86c2012-08-18 00:30:16 +00003546 ExplodedNode *N = Ctx.addTransition(state, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003547
3548 if (N) {
3549 for (SmallVectorImpl<SymbolRef>::iterator
3550 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3551
David Blaikie4e4d0842012-03-11 07:00:24 +00003552 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
Anna Zaks6a93bd52011-10-25 19:57:11 +00003553 bool GCEnabled = Ctx.isObjCGCEnabled();
Jordy Rose17a38e22011-09-02 05:55:19 +00003554 CFRefBug *BT = Pred ? getLeakWithinFunctionBug(LOpts, GCEnabled)
3555 : getLeakAtReturnBug(LOpts, GCEnabled);
Jordy Rose38f17d62011-08-23 19:01:07 +00003556 assert(BT && "BugType not initialized.");
Jordy Rose20589562011-08-24 22:39:09 +00003557
Jordy Rose17a38e22011-09-02 05:55:19 +00003558 CFRefLeakReport *report = new CFRefLeakReport(*BT, LOpts, GCEnabled,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003559 SummaryLog, N, *I, Ctx);
Jordan Rose785950e2012-11-02 01:53:40 +00003560 Ctx.emitReport(report);
Jordy Rose38f17d62011-08-23 19:01:07 +00003561 }
3562 }
3563
3564 return N;
3565}
3566
Anna Zaks344c77a2013-01-03 00:25:29 +00003567void RetainCountChecker::checkEndFunction(CheckerContext &Ctx) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +00003568 ProgramStateRef state = Ctx.getState();
Jordan Rose166d5022012-11-02 01:54:06 +00003569 RefBindingsTy B = state->get<RefBindings>();
Anna Zaksaf498a22011-10-25 19:56:48 +00003570 ExplodedNode *Pred = Ctx.getPredecessor();
Jordy Rose38f17d62011-08-23 19:01:07 +00003571
Jordan Rose166d5022012-11-02 01:54:06 +00003572 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Jordan Rose4ee1c552012-12-06 18:58:18 +00003573 state = handleAutoreleaseCounts(state, Pred, /*Tag=*/0, Ctx,
3574 I->first, I->second);
Jordy Rose8d228632011-08-23 20:07:14 +00003575 if (!state)
Jordy Rose38f17d62011-08-23 19:01:07 +00003576 return;
3577 }
3578
Ted Kremenek0cf3d472012-02-07 00:24:33 +00003579 // If the current LocationContext has a parent, don't check for leaks.
3580 // We will do that later.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003581 // FIXME: we should instead check for imbalances of the retain/releases,
Ted Kremenek0cf3d472012-02-07 00:24:33 +00003582 // and suggest annotations.
3583 if (Ctx.getLocationContext()->getParent())
3584 return;
3585
Jordy Rose38f17d62011-08-23 19:01:07 +00003586 B = state->get<RefBindings>();
3587 SmallVector<SymbolRef, 10> Leaked;
3588
Jordan Rose166d5022012-11-02 01:54:06 +00003589 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I)
Jordy Rose8d228632011-08-23 20:07:14 +00003590 state = handleSymbolDeath(state, I->first, I->second, Leaked);
Jordy Rose38f17d62011-08-23 19:01:07 +00003591
Jordan Rose2bce86c2012-08-18 00:30:16 +00003592 processLeaks(state, Leaked, Ctx, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003593}
3594
3595const ProgramPointTag *
Jordy Rose910c4052011-09-02 06:44:22 +00003596RetainCountChecker::getDeadSymbolTag(SymbolRef sym) const {
Jordy Rose38f17d62011-08-23 19:01:07 +00003597 const SimpleProgramPointTag *&tag = DeadSymbolTags[sym];
3598 if (!tag) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003599 SmallString<64> buf;
Jordy Rose38f17d62011-08-23 19:01:07 +00003600 llvm::raw_svector_ostream out(buf);
Anna Zaksf62ceec2011-12-05 18:58:11 +00003601 out << "RetainCountChecker : Dead Symbol : ";
3602 sym->dumpToStream(out);
Jordy Rose38f17d62011-08-23 19:01:07 +00003603 tag = new SimpleProgramPointTag(out.str());
3604 }
3605 return tag;
3606}
3607
Jordy Rose910c4052011-09-02 06:44:22 +00003608void RetainCountChecker::checkDeadSymbols(SymbolReaper &SymReaper,
3609 CheckerContext &C) const {
Jordy Rose38f17d62011-08-23 19:01:07 +00003610 ExplodedNode *Pred = C.getPredecessor();
3611
Ted Kremenek8bef8232012-01-26 21:29:00 +00003612 ProgramStateRef state = C.getState();
Jordan Rose166d5022012-11-02 01:54:06 +00003613 RefBindingsTy B = state->get<RefBindings>();
Jordan Rose4ee1c552012-12-06 18:58:18 +00003614 SmallVector<SymbolRef, 10> Leaked;
Jordy Rose38f17d62011-08-23 19:01:07 +00003615
3616 // Update counts from autorelease pools
3617 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3618 E = SymReaper.dead_end(); I != E; ++I) {
3619 SymbolRef Sym = *I;
3620 if (const RefVal *T = B.lookup(Sym)){
3621 // Use the symbol as the tag.
3622 // FIXME: This might not be as unique as we would like.
Jordan Rose2bce86c2012-08-18 00:30:16 +00003623 const ProgramPointTag *Tag = getDeadSymbolTag(Sym);
Jordan Rose4ee1c552012-12-06 18:58:18 +00003624 state = handleAutoreleaseCounts(state, Pred, Tag, C, Sym, *T);
Jordy Rose8d228632011-08-23 20:07:14 +00003625 if (!state)
Jordy Rose38f17d62011-08-23 19:01:07 +00003626 return;
Jordan Rose4ee1c552012-12-06 18:58:18 +00003627
3628 // Fetch the new reference count from the state, and use it to handle
3629 // this symbol.
3630 state = handleSymbolDeath(state, *I, *getRefBinding(state, Sym), Leaked);
Jordy Rose38f17d62011-08-23 19:01:07 +00003631 }
3632 }
3633
Jordan Rose4ee1c552012-12-06 18:58:18 +00003634 if (Leaked.empty()) {
3635 C.addTransition(state);
3636 return;
Jordy Rose38f17d62011-08-23 19:01:07 +00003637 }
3638
Jordan Rose2bce86c2012-08-18 00:30:16 +00003639 Pred = processLeaks(state, Leaked, C, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003640
3641 // Did we cache out?
3642 if (!Pred)
3643 return;
3644
3645 // Now generate a new node that nukes the old bindings.
Jordan Rose4ee1c552012-12-06 18:58:18 +00003646 // The only bindings left at this point are the leaked symbols.
Jordan Rose166d5022012-11-02 01:54:06 +00003647 RefBindingsTy::Factory &F = state->get_context<RefBindings>();
Jordan Rose4ee1c552012-12-06 18:58:18 +00003648 B = state->get<RefBindings>();
Jordy Rose38f17d62011-08-23 19:01:07 +00003649
Jordan Rose4ee1c552012-12-06 18:58:18 +00003650 for (SmallVectorImpl<SymbolRef>::iterator I = Leaked.begin(),
3651 E = Leaked.end();
3652 I != E; ++I)
Jordy Rose38f17d62011-08-23 19:01:07 +00003653 B = F.remove(B, *I);
3654
3655 state = state->set<RefBindings>(B);
Anna Zaks0bd6b112011-10-26 21:06:34 +00003656 C.addTransition(state, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003657}
3658
Ted Kremenek8bef8232012-01-26 21:29:00 +00003659void RetainCountChecker::printState(raw_ostream &Out, ProgramStateRef State,
Jordy Rose910c4052011-09-02 06:44:22 +00003660 const char *NL, const char *Sep) const {
Jordy Rosedbd658e2011-08-28 19:11:56 +00003661
Jordan Rose166d5022012-11-02 01:54:06 +00003662 RefBindingsTy B = State->get<RefBindings>();
Jordy Rosedbd658e2011-08-28 19:11:56 +00003663
3664 if (!B.isEmpty())
3665 Out << Sep << NL;
3666
Jordan Rose166d5022012-11-02 01:54:06 +00003667 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Jordy Rosedbd658e2011-08-28 19:11:56 +00003668 Out << I->first << " : ";
3669 I->second.print(Out);
3670 Out << NL;
3671 }
Jordy Rosedbd658e2011-08-28 19:11:56 +00003672}
3673
3674//===----------------------------------------------------------------------===//
Jordy Rose910c4052011-09-02 06:44:22 +00003675// Checker registration.
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00003676//===----------------------------------------------------------------------===//
3677
Jordy Rose17a38e22011-09-02 05:55:19 +00003678void ento::registerRetainCountChecker(CheckerManager &Mgr) {
Jordy Rose910c4052011-09-02 06:44:22 +00003679 Mgr.registerChecker<RetainCountChecker>();
Jordy Rose17a38e22011-09-02 05:55:19 +00003680}
3681