blob: fa864b44e7c9a67a170bf27dea3c246f7c44666c [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
Jordan Rose44405b72013-04-04 22:31:48 +0000785 /// Determine if there is a special return effect for this function or method.
786 Optional<RetEffect> getRetEffectFromAnnotations(QualType RetTy,
787 const Decl *D);
788
Ted Kremenek93edbc52011-10-05 23:54:29 +0000789 void updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenek4dd8fb42009-05-09 02:58:13 +0000790 const ObjCMethodDecl *MD);
791
Ted Kremenek93edbc52011-10-05 23:54:29 +0000792 void updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenek4dd8fb42009-05-09 02:58:13 +0000793 const FunctionDecl *FD);
794
Jordan Rose4531b7d2012-07-02 19:27:43 +0000795 void updateSummaryForCall(const RetainSummary *&Summ,
796 const CallEvent &Call);
797
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000798 bool isGCEnabled() const { return GCEnabled; }
Mike Stump1eb44332009-09-09 15:08:12 +0000799
John McCallf85e1932011-06-15 23:02:42 +0000800 bool isARCEnabled() const { return ARCEnabled; }
801
802 bool isARCorGCEnabled() const { return GCEnabled || ARCEnabled; }
Jordan Rose4531b7d2012-07-02 19:27:43 +0000803
804 RetEffect getObjAllocRetEffect() const { return ObjCAllocRetE; }
805
806 friend class RetainSummaryTemplate;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000807};
Mike Stump1eb44332009-09-09 15:08:12 +0000808
Jordy Rose0fe62f82011-08-24 09:02:37 +0000809// Used to avoid allocating long-term (BPAlloc'd) memory for default retain
810// summaries. If a function or method looks like it has a default summary, but
811// it has annotations, the annotations are added to the stack-based template
812// and then copied into managed memory.
813class RetainSummaryTemplate {
814 RetainSummaryManager &Manager;
Ted Kremenek93edbc52011-10-05 23:54:29 +0000815 const RetainSummary *&RealSummary;
Jordy Rose0fe62f82011-08-24 09:02:37 +0000816 RetainSummary ScratchSummary;
817 bool Accessed;
818public:
Jordan Rose4531b7d2012-07-02 19:27:43 +0000819 RetainSummaryTemplate(const RetainSummary *&real, RetainSummaryManager &mgr)
820 : Manager(mgr), RealSummary(real), ScratchSummary(*real), Accessed(false) {}
Jordy Rose0fe62f82011-08-24 09:02:37 +0000821
822 ~RetainSummaryTemplate() {
Ted Kremenek93edbc52011-10-05 23:54:29 +0000823 if (Accessed)
Jordy Roseef945882012-03-18 01:26:10 +0000824 RealSummary = Manager.getPersistentSummary(ScratchSummary);
Jordy Rose0fe62f82011-08-24 09:02:37 +0000825 }
826
827 RetainSummary &operator*() {
828 Accessed = true;
Ted Kremenek93edbc52011-10-05 23:54:29 +0000829 return ScratchSummary;
Jordy Rose0fe62f82011-08-24 09:02:37 +0000830 }
831
832 RetainSummary *operator->() {
833 Accessed = true;
Ted Kremenek93edbc52011-10-05 23:54:29 +0000834 return &ScratchSummary;
Jordy Rose0fe62f82011-08-24 09:02:37 +0000835 }
836};
837
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000838} // end anonymous namespace
839
840//===----------------------------------------------------------------------===//
841// Implementation of checker data structures.
842//===----------------------------------------------------------------------===//
843
Ted Kremenekb77449c2009-05-03 05:20:50 +0000844ArgEffects RetainSummaryManager::getArgEffects() {
845 ArgEffects AE = ScratchArgs;
Ted Kremenek3baf6722010-11-24 00:54:37 +0000846 ScratchArgs = AF.getEmptyMap();
Ted Kremenekb77449c2009-05-03 05:20:50 +0000847 return AE;
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000848}
849
Ted Kremenek93edbc52011-10-05 23:54:29 +0000850const RetainSummary *
Jordy Roseef945882012-03-18 01:26:10 +0000851RetainSummaryManager::getPersistentSummary(const RetainSummary &OldSumm) {
852 // Unique "simple" summaries -- those without ArgEffects.
853 if (OldSumm.isSimple()) {
854 llvm::FoldingSetNodeID ID;
855 OldSumm.Profile(ID);
856
857 void *Pos;
858 CachedSummaryNode *N = SimpleSummaries.FindNodeOrInsertPos(ID, Pos);
859
860 if (!N) {
861 N = (CachedSummaryNode *) BPAlloc.Allocate<CachedSummaryNode>();
862 new (N) CachedSummaryNode(OldSumm);
863 SimpleSummaries.InsertNode(N, Pos);
864 }
865
866 return &N->getValue();
867 }
868
Ted Kremenek93edbc52011-10-05 23:54:29 +0000869 RetainSummary *Summ = (RetainSummary *) BPAlloc.Allocate<RetainSummary>();
Jordy Roseef945882012-03-18 01:26:10 +0000870 new (Summ) RetainSummary(OldSumm);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000871 return Summ;
872}
873
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000874//===----------------------------------------------------------------------===//
875// Summary creation for functions (largely uses of Core Foundation).
876//===----------------------------------------------------------------------===//
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000877
Ted Kremenek9c378f72011-08-12 23:37:29 +0000878static bool isRetain(const FunctionDecl *FD, StringRef FName) {
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000879 return FName.endswith("Retain");
Ted Kremenek12619382009-01-12 21:45:02 +0000880}
881
Ted Kremenek9c378f72011-08-12 23:37:29 +0000882static bool isRelease(const FunctionDecl *FD, StringRef FName) {
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000883 return FName.endswith("Release");
Ted Kremenek12619382009-01-12 21:45:02 +0000884}
885
Jordy Rose76c506f2011-08-21 21:58:18 +0000886static bool isMakeCollectable(const FunctionDecl *FD, StringRef FName) {
887 // FIXME: Remove FunctionDecl parameter.
888 // FIXME: Is it really okay if MakeCollectable isn't a suffix?
889 return FName.find("MakeCollectable") != StringRef::npos;
890}
891
Anna Zaks554067f2012-08-29 23:23:43 +0000892static ArgEffect getStopTrackingHardEquivalent(ArgEffect E) {
Jordan Rose4531b7d2012-07-02 19:27:43 +0000893 switch (E) {
894 case DoNothing:
895 case Autorelease:
896 case DecRefBridgedTransfered:
897 case IncRef:
898 case IncRefMsg:
899 case MakeCollectable:
900 case MayEscape:
Jordan Rose4531b7d2012-07-02 19:27:43 +0000901 case StopTracking:
Anna Zaks554067f2012-08-29 23:23:43 +0000902 case StopTrackingHard:
903 return StopTrackingHard;
Jordan Rose4531b7d2012-07-02 19:27:43 +0000904 case DecRef:
Anna Zaks554067f2012-08-29 23:23:43 +0000905 case DecRefAndStopTrackingHard:
906 return DecRefAndStopTrackingHard;
Jordan Rose4531b7d2012-07-02 19:27:43 +0000907 case DecRefMsg:
Anna Zaks554067f2012-08-29 23:23:43 +0000908 case DecRefMsgAndStopTrackingHard:
909 return DecRefMsgAndStopTrackingHard;
Jordan Rose4531b7d2012-07-02 19:27:43 +0000910 case Dealloc:
911 return Dealloc;
912 }
913
914 llvm_unreachable("Unknown ArgEffect kind");
915}
916
917void RetainSummaryManager::updateSummaryForCall(const RetainSummary *&S,
918 const CallEvent &Call) {
919 if (Call.hasNonZeroCallbackArg()) {
Anna Zaks554067f2012-08-29 23:23:43 +0000920 ArgEffect RecEffect =
921 getStopTrackingHardEquivalent(S->getReceiverEffect());
922 ArgEffect DefEffect =
923 getStopTrackingHardEquivalent(S->getDefaultArgEffect());
Jordan Rose4531b7d2012-07-02 19:27:43 +0000924
925 ArgEffects CustomArgEffects = S->getArgEffects();
926 for (ArgEffects::iterator I = CustomArgEffects.begin(),
927 E = CustomArgEffects.end();
928 I != E; ++I) {
Anna Zaks554067f2012-08-29 23:23:43 +0000929 ArgEffect Translated = getStopTrackingHardEquivalent(I->second);
Jordan Rose4531b7d2012-07-02 19:27:43 +0000930 if (Translated != DefEffect)
931 ScratchArgs = AF.add(ScratchArgs, I->first, Translated);
932 }
933
Anna Zaks554067f2012-08-29 23:23:43 +0000934 RetEffect RE = RetEffect::MakeNoRetHard();
Jordan Rose4531b7d2012-07-02 19:27:43 +0000935
936 // Special cases where the callback argument CANNOT free the return value.
937 // This can generally only happen if we know that the callback will only be
938 // called when the return value is already being deallocated.
939 if (const FunctionCall *FC = dyn_cast<FunctionCall>(&Call)) {
Jordan Rose4a25f302012-09-01 17:39:13 +0000940 if (IdentifierInfo *Name = FC->getDecl()->getIdentifier()) {
941 // When the CGBitmapContext is deallocated, the callback here will free
942 // the associated data buffer.
Jordan Rosea89f7192012-08-31 18:19:18 +0000943 if (Name->isStr("CGBitmapContextCreateWithData"))
944 RE = S->getRetEffect();
Jordan Rose4a25f302012-09-01 17:39:13 +0000945 }
Jordan Rose4531b7d2012-07-02 19:27:43 +0000946 }
947
948 S = getPersistentSummary(RE, RecEffect, DefEffect);
949 }
Anna Zaks5a901932012-08-24 00:06:12 +0000950
951 // Special case '[super init];' and '[self init];'
952 //
953 // Even though calling '[super init]' without assigning the result to self
954 // and checking if the parent returns 'nil' is a bad pattern, it is common.
955 // Additionally, our Self Init checker already warns about it. To avoid
956 // overwhelming the user with messages from both checkers, we model the case
957 // of '[super init]' in cases when it is not consumed by another expression
958 // as if the call preserves the value of 'self'; essentially, assuming it can
959 // never fail and return 'nil'.
960 // Note, we don't want to just stop tracking the value since we want the
961 // RetainCount checker to report leaks and use-after-free if SelfInit checker
962 // is turned off.
963 if (const ObjCMethodCall *MC = dyn_cast<ObjCMethodCall>(&Call)) {
964 if (MC->getMethodFamily() == OMF_init && MC->isReceiverSelfOrSuper()) {
965
966 // Check if the message is not consumed, we know it will not be used in
967 // an assignment, ex: "self = [super init]".
968 const Expr *ME = MC->getOriginExpr();
969 const LocationContext *LCtx = MC->getLocationContext();
970 ParentMap &PM = LCtx->getAnalysisDeclContext()->getParentMap();
971 if (!PM.isConsumedExpr(ME)) {
972 RetainSummaryTemplate ModifiableSummaryTemplate(S, *this);
973 ModifiableSummaryTemplate->setReceiverEffect(DoNothing);
974 ModifiableSummaryTemplate->setRetEffect(RetEffect::MakeNoRet());
975 }
976 }
977
978 }
Jordan Rose4531b7d2012-07-02 19:27:43 +0000979}
980
Anna Zaks58822c42012-05-04 22:18:39 +0000981const RetainSummary *
Jordan Rose4531b7d2012-07-02 19:27:43 +0000982RetainSummaryManager::getSummary(const CallEvent &Call,
983 ProgramStateRef State) {
984 const RetainSummary *Summ;
985 switch (Call.getKind()) {
986 case CE_Function:
987 Summ = getFunctionSummary(cast<FunctionCall>(Call).getDecl());
988 break;
989 case CE_CXXMember:
Jordan Rosefdaa3382012-07-03 22:55:57 +0000990 case CE_CXXMemberOperator:
Jordan Rose4531b7d2012-07-02 19:27:43 +0000991 case CE_Block:
992 case CE_CXXConstructor:
Jordan Rose8d276d32012-07-10 22:07:47 +0000993 case CE_CXXDestructor:
Jordan Rose70cbf3c2012-07-02 22:21:47 +0000994 case CE_CXXAllocator:
Jordan Rose4531b7d2012-07-02 19:27:43 +0000995 // FIXME: These calls are currently unsupported.
996 return getPersistentStopSummary();
Jordan Rose8919e682012-07-18 21:59:51 +0000997 case CE_ObjCMessage: {
Jordan Rosecde8cdb2012-07-02 19:27:56 +0000998 const ObjCMethodCall &Msg = cast<ObjCMethodCall>(Call);
Jordan Rose4531b7d2012-07-02 19:27:43 +0000999 if (Msg.isInstanceMessage())
1000 Summ = getInstanceMethodSummary(Msg, State);
1001 else
1002 Summ = getClassMethodSummary(Msg);
1003 break;
1004 }
1005 }
1006
1007 updateSummaryForCall(Summ, Call);
1008
1009 assert(Summ && "Unknown call type?");
1010 return Summ;
1011}
1012
1013const RetainSummary *
1014RetainSummaryManager::getFunctionSummary(const FunctionDecl *FD) {
1015 // If we don't know what function we're calling, use our default summary.
1016 if (!FD)
1017 return getDefaultSummary();
1018
Ted Kremenek891d5cc2008-04-24 17:22:33 +00001019 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001020 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001021 if (I != FuncSummaries.end())
Ted Kremenek891d5cc2008-04-24 17:22:33 +00001022 return I->second;
1023
Ted Kremeneke401a0c2009-05-04 15:34:07 +00001024 // No summary? Generate one.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001025 const RetainSummary *S = 0;
Jordan Rose15d18e12012-08-06 21:28:02 +00001026 bool AllowAnnotations = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001027
Ted Kremenek37d785b2008-07-15 16:50:12 +00001028 do {
Ted Kremenek12619382009-01-12 21:45:02 +00001029 // We generate "stop" summaries for implicitly defined functions.
1030 if (FD->isImplicit()) {
1031 S = getPersistentStopSummary();
1032 break;
Ted Kremenek37d785b2008-07-15 16:50:12 +00001033 }
Mike Stump1eb44332009-09-09 15:08:12 +00001034
John McCall183700f2009-09-21 23:43:11 +00001035 // [PR 3337] Use 'getAs<FunctionType>' to strip away any typedefs on the
Ted Kremenek99890652009-01-16 18:40:33 +00001036 // function's type.
John McCall183700f2009-09-21 23:43:11 +00001037 const FunctionType* FT = FD->getType()->getAs<FunctionType>();
Ted Kremenek48c6d182009-12-16 06:06:43 +00001038 const IdentifierInfo *II = FD->getIdentifier();
1039 if (!II)
1040 break;
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001041
1042 StringRef FName = II->getName();
Mike Stump1eb44332009-09-09 15:08:12 +00001043
Ted Kremenekbf0a4dd2009-03-05 22:11:14 +00001044 // Strip away preceding '_'. Doing this here will effect all the checks
1045 // down below.
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001046 FName = FName.substr(FName.find_first_not_of('_'));
Mike Stump1eb44332009-09-09 15:08:12 +00001047
Ted Kremenek12619382009-01-12 21:45:02 +00001048 // Inspect the result type.
1049 QualType RetTy = FT->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00001050
Ted Kremenek12619382009-01-12 21:45:02 +00001051 // FIXME: This should all be refactored into a chain of "summary lookup"
1052 // filters.
Ted Kremenek008636a2009-10-14 00:27:24 +00001053 assert(ScratchArgs.isEmpty());
Ted Kremenek39d88b02009-06-15 20:36:07 +00001054
Ted Kremenekbefc6d22012-04-26 04:32:23 +00001055 if (FName == "pthread_create" || FName == "pthread_setspecific") {
1056 // Part of: <rdar://problem/7299394> and <rdar://problem/11282706>.
1057 // This will be addressed better with IPA.
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001058 S = getPersistentStopSummary();
1059 } else if (FName == "NSMakeCollectable") {
1060 // Handle: id NSMakeCollectable(CFTypeRef)
1061 S = (RetTy->isObjCIdType())
1062 ? getUnarySummary(FT, cfmakecollectable)
1063 : getPersistentStopSummary();
Jordan Rose15d18e12012-08-06 21:28:02 +00001064 // The headers on OS X 10.8 use cf_consumed/ns_returns_retained,
1065 // but we can fully model NSMakeCollectable ourselves.
1066 AllowAnnotations = false;
Ted Kremenek061707a2012-09-06 23:47:02 +00001067 } else if (FName == "CFPlugInInstanceCreate") {
1068 S = getPersistentSummary(RetEffect::MakeNoRet());
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001069 } else if (FName == "IOBSDNameMatching" ||
1070 FName == "IOServiceMatching" ||
1071 FName == "IOServiceNameMatching" ||
Ted Kremenek537dd3a2012-05-01 05:28:27 +00001072 FName == "IORegistryEntrySearchCFProperty" ||
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001073 FName == "IORegistryEntryIDMatching" ||
1074 FName == "IOOpenFirmwarePathMatching") {
1075 // Part of <rdar://problem/6961230>. (IOKit)
1076 // This should be addressed using a API table.
1077 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1078 DoNothing, DoNothing);
1079 } else if (FName == "IOServiceGetMatchingService" ||
1080 FName == "IOServiceGetMatchingServices") {
1081 // FIXES: <rdar://problem/6326900>
1082 // This should be addressed using a API table. This strcmp is also
1083 // a little gross, but there is no need to super optimize here.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001084 ScratchArgs = AF.add(ScratchArgs, 1, DecRef);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001085 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1086 } else if (FName == "IOServiceAddNotification" ||
1087 FName == "IOServiceAddMatchingNotification") {
1088 // Part of <rdar://problem/6961230>. (IOKit)
1089 // This should be addressed using a API table.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001090 ScratchArgs = AF.add(ScratchArgs, 2, DecRef);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001091 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1092 } else if (FName == "CVPixelBufferCreateWithBytes") {
1093 // FIXES: <rdar://problem/7283567>
1094 // Eventually this can be improved by recognizing that the pixel
1095 // buffer passed to CVPixelBufferCreateWithBytes is released via
1096 // a callback and doing full IPA to make sure this is done correctly.
1097 // FIXME: This function has an out parameter that returns an
1098 // allocated object.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001099 ScratchArgs = AF.add(ScratchArgs, 7, StopTracking);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001100 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1101 } else if (FName == "CGBitmapContextCreateWithData") {
1102 // FIXES: <rdar://problem/7358899>
1103 // Eventually this can be improved by recognizing that 'releaseInfo'
1104 // passed to CGBitmapContextCreateWithData is released via
1105 // a callback and doing full IPA to make sure this is done correctly.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001106 ScratchArgs = AF.add(ScratchArgs, 8, StopTracking);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001107 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1108 DoNothing, DoNothing);
1109 } else if (FName == "CVPixelBufferCreateWithPlanarBytes") {
1110 // FIXES: <rdar://problem/7283567>
1111 // Eventually this can be improved by recognizing that the pixel
1112 // buffer passed to CVPixelBufferCreateWithPlanarBytes is released
1113 // via a callback and doing full IPA to make sure this is done
1114 // correctly.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001115 ScratchArgs = AF.add(ScratchArgs, 12, StopTracking);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001116 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenek06911d42012-03-22 06:29:41 +00001117 } else if (FName == "dispatch_set_context") {
1118 // <rdar://problem/11059275> - The analyzer currently doesn't have
1119 // a good way to reason about the finalizer function for libdispatch.
1120 // If we pass a context object that is memory managed, stop tracking it.
1121 // FIXME: this hack should possibly go away once we can handle
1122 // libdispatch finalizers.
1123 ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
1124 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenekc91fdf62012-05-08 00:12:09 +00001125 } else if (FName.startswith("NSLog")) {
1126 S = getDoNothingSummary();
Anna Zaks62a5c342012-03-30 05:48:16 +00001127 } else if (FName.startswith("NS") &&
1128 (FName.find("Insert") != StringRef::npos)) {
1129 // Whitelist NSXXInsertXX, for example NSMapInsertIfAbsent, since they can
1130 // be deallocated by NSMapRemove. (radar://11152419)
1131 ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
1132 ScratchArgs = AF.add(ScratchArgs, 2, StopTracking);
1133 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenekb04cb592009-06-11 18:17:24 +00001134 }
Mike Stump1eb44332009-09-09 15:08:12 +00001135
Ted Kremenekb04cb592009-06-11 18:17:24 +00001136 // Did we get a summary?
1137 if (S)
1138 break;
Ted Kremenek61991902009-03-17 22:43:44 +00001139
Jordan Rose5aff3f12013-03-04 23:21:32 +00001140 if (RetTy->isPointerType()) {
Ted Kremenek12619382009-01-12 21:45:02 +00001141 // For CoreFoundation ('CF') types.
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001142 if (cocoa::isRefType(RetTy, "CF", FName)) {
Ted Kremenek12619382009-01-12 21:45:02 +00001143 if (isRetain(FD, FName))
1144 S = getUnarySummary(FT, cfretain);
Jordy Rose76c506f2011-08-21 21:58:18 +00001145 else if (isMakeCollectable(FD, FName))
Ted Kremenek12619382009-01-12 21:45:02 +00001146 S = getUnarySummary(FT, cfmakecollectable);
Mike Stump1eb44332009-09-09 15:08:12 +00001147 else
John McCall7df2ff42011-10-01 00:48:56 +00001148 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek12619382009-01-12 21:45:02 +00001149
1150 break;
1151 }
1152
1153 // For CoreGraphics ('CG') types.
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001154 if (cocoa::isRefType(RetTy, "CG", FName)) {
Ted Kremenek12619382009-01-12 21:45:02 +00001155 if (isRetain(FD, FName))
1156 S = getUnarySummary(FT, cfretain);
1157 else
John McCall7df2ff42011-10-01 00:48:56 +00001158 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek12619382009-01-12 21:45:02 +00001159
1160 break;
1161 }
1162
1163 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001164 if (cocoa::isRefType(RetTy, "DADisk") ||
1165 cocoa::isRefType(RetTy, "DADissenter") ||
1166 cocoa::isRefType(RetTy, "DASessionRef")) {
John McCall7df2ff42011-10-01 00:48:56 +00001167 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek12619382009-01-12 21:45:02 +00001168 break;
1169 }
Mike Stump1eb44332009-09-09 15:08:12 +00001170
Jordan Rose5aff3f12013-03-04 23:21:32 +00001171 if (FD->getAttr<CFAuditedTransferAttr>()) {
1172 S = getCFCreateGetRuleSummary(FD);
1173 break;
1174 }
1175
Ted Kremenek12619382009-01-12 21:45:02 +00001176 break;
1177 }
1178
1179 // Check for release functions, the only kind of functions that we care
1180 // about that don't return a pointer type.
1181 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
Ted Kremeneke7d03122010-02-08 16:45:01 +00001182 // Test for 'CGCF'.
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001183 FName = FName.substr(FName.startswith("CGCF") ? 4 : 2);
Ted Kremeneke7d03122010-02-08 16:45:01 +00001184
Ted Kremenekbf0a4dd2009-03-05 22:11:14 +00001185 if (isRelease(FD, FName))
Ted Kremenek12619382009-01-12 21:45:02 +00001186 S = getUnarySummary(FT, cfrelease);
1187 else {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001188 assert (ScratchArgs.isEmpty());
Ted Kremenek68189282009-01-29 22:45:13 +00001189 // Remaining CoreFoundation and CoreGraphics functions.
1190 // We use to assume that they all strictly followed the ownership idiom
1191 // and that ownership cannot be transferred. While this is technically
1192 // correct, many methods allow a tracked object to escape. For example:
1193 //
Mike Stump1eb44332009-09-09 15:08:12 +00001194 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
Ted Kremenek68189282009-01-29 22:45:13 +00001195 // CFDictionaryAddValue(y, key, x);
Mike Stump1eb44332009-09-09 15:08:12 +00001196 // CFRelease(x);
Ted Kremenek68189282009-01-29 22:45:13 +00001197 // ... it is okay to use 'x' since 'y' has a reference to it
1198 //
1199 // We handle this and similar cases with the follow heuristic. If the
Ted Kremenekc4843812009-08-20 00:57:22 +00001200 // function name contains "InsertValue", "SetValue", "AddValue",
1201 // "AppendValue", or "SetAttribute", then we assume that arguments may
1202 // "escape." This means that something else holds on to the object,
1203 // allowing it be used even after its local retain count drops to 0.
Benjamin Kramere45c1492010-01-11 19:46:28 +00001204 ArgEffect E = (StrInStrNoCase(FName, "InsertValue") != StringRef::npos||
1205 StrInStrNoCase(FName, "AddValue") != StringRef::npos ||
1206 StrInStrNoCase(FName, "SetValue") != StringRef::npos ||
1207 StrInStrNoCase(FName, "AppendValue") != StringRef::npos||
Benjamin Kramerc027e542010-01-11 20:15:06 +00001208 StrInStrNoCase(FName, "SetAttribute") != StringRef::npos)
Ted Kremenek68189282009-01-29 22:45:13 +00001209 ? MayEscape : DoNothing;
Mike Stump1eb44332009-09-09 15:08:12 +00001210
Ted Kremenek68189282009-01-29 22:45:13 +00001211 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek12619382009-01-12 21:45:02 +00001212 }
1213 }
Ted Kremenek37d785b2008-07-15 16:50:12 +00001214 }
1215 while (0);
Mike Stump1eb44332009-09-09 15:08:12 +00001216
Jordan Rose4531b7d2012-07-02 19:27:43 +00001217 // If we got all the way here without any luck, use a default summary.
1218 if (!S)
1219 S = getDefaultSummary();
1220
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001221 // Annotations override defaults.
Jordan Rose15d18e12012-08-06 21:28:02 +00001222 if (AllowAnnotations)
1223 updateSummaryFromAnnotations(S, FD);
Mike Stump1eb44332009-09-09 15:08:12 +00001224
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001225 FuncSummaries[FD] = S;
Mike Stump1eb44332009-09-09 15:08:12 +00001226 return S;
Ted Kremenek2fff37e2008-03-06 00:08:09 +00001227}
1228
Ted Kremenek93edbc52011-10-05 23:54:29 +00001229const RetainSummary *
John McCall7df2ff42011-10-01 00:48:56 +00001230RetainSummaryManager::getCFCreateGetRuleSummary(const FunctionDecl *FD) {
1231 if (coreFoundation::followsCreateRule(FD))
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001232 return getCFSummaryCreateRule(FD);
Mike Stump1eb44332009-09-09 15:08:12 +00001233
Ted Kremenekd368d712011-05-25 06:19:45 +00001234 return getCFSummaryGetRule(FD);
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001235}
1236
Ted Kremenek93edbc52011-10-05 23:54:29 +00001237const RetainSummary *
Ted Kremenek6ad315a2009-02-23 16:51:39 +00001238RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1239 UnaryFuncKind func) {
1240
Ted Kremenek12619382009-01-12 21:45:02 +00001241 // Sanity check that this is *really* a unary function. This can
1242 // happen if people do weird things.
Douglas Gregor72564e72009-02-26 23:50:07 +00001243 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
Ted Kremenek12619382009-01-12 21:45:02 +00001244 if (!FTP || FTP->getNumArgs() != 1)
1245 return getPersistentStopSummary();
Mike Stump1eb44332009-09-09 15:08:12 +00001246
Ted Kremenekb77449c2009-05-03 05:20:50 +00001247 assert (ScratchArgs.isEmpty());
Mike Stump1eb44332009-09-09 15:08:12 +00001248
Jordy Rose76c506f2011-08-21 21:58:18 +00001249 ArgEffect Effect;
Ted Kremenek377e2302008-04-29 05:33:51 +00001250 switch (func) {
Jordy Rose76c506f2011-08-21 21:58:18 +00001251 case cfretain: Effect = IncRef; break;
1252 case cfrelease: Effect = DecRef; break;
1253 case cfmakecollectable: Effect = MakeCollectable; break;
Ted Kremenek940b1d82008-04-10 23:44:06 +00001254 }
Jordy Rose76c506f2011-08-21 21:58:18 +00001255
1256 ScratchArgs = AF.add(ScratchArgs, 0, Effect);
1257 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001258}
1259
Ted Kremenek93edbc52011-10-05 23:54:29 +00001260const RetainSummary *
Ted Kremenek9c378f72011-08-12 23:37:29 +00001261RetainSummaryManager::getCFSummaryCreateRule(const FunctionDecl *FD) {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001262 assert (ScratchArgs.isEmpty());
Mike Stump1eb44332009-09-09 15:08:12 +00001263
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001264 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001265}
1266
Ted Kremenek93edbc52011-10-05 23:54:29 +00001267const RetainSummary *
Ted Kremenek9c378f72011-08-12 23:37:29 +00001268RetainSummaryManager::getCFSummaryGetRule(const FunctionDecl *FD) {
Mike Stump1eb44332009-09-09 15:08:12 +00001269 assert (ScratchArgs.isEmpty());
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001270 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1271 DoNothing, DoNothing);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001272}
1273
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001274//===----------------------------------------------------------------------===//
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001275// Summary creation for Selectors.
1276//===----------------------------------------------------------------------===//
1277
Jordan Rose44405b72013-04-04 22:31:48 +00001278Optional<RetEffect>
1279RetainSummaryManager::getRetEffectFromAnnotations(QualType RetTy,
1280 const Decl *D) {
1281 if (cocoa::isCocoaObjectRef(RetTy)) {
1282 if (D->getAttr<NSReturnsRetainedAttr>())
1283 return ObjCAllocRetE;
1284
1285 if (D->getAttr<NSReturnsNotRetainedAttr>() ||
1286 D->getAttr<NSReturnsAutoreleasedAttr>())
1287 return RetEffect::MakeNotOwned(RetEffect::ObjC);
1288
1289 } else if (!RetTy->isPointerType()) {
1290 return None;
1291 }
1292
1293 if (D->getAttr<CFReturnsRetainedAttr>())
1294 return RetEffect::MakeOwned(RetEffect::CF, true);
1295
1296 if (D->getAttr<CFReturnsNotRetainedAttr>())
1297 return RetEffect::MakeNotOwned(RetEffect::CF);
1298
1299 return None;
1300}
1301
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001302void
Ted Kremenek93edbc52011-10-05 23:54:29 +00001303RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001304 const FunctionDecl *FD) {
1305 if (!FD)
1306 return;
1307
Jordan Rose4531b7d2012-07-02 19:27:43 +00001308 assert(Summ && "Must have a summary to add annotations to.");
1309 RetainSummaryTemplate Template(Summ, *this);
Jordy Rose4df54fe2011-08-23 04:27:15 +00001310
Ted Kremenek11fe1752011-01-27 18:43:03 +00001311 // Effects on the parameters.
1312 unsigned parm_idx = 0;
1313 for (FunctionDecl::param_const_iterator pi = FD->param_begin(),
John McCall98b8f162011-04-06 09:02:12 +00001314 pe = FD->param_end(); pi != pe; ++pi, ++parm_idx) {
Ted Kremenek11fe1752011-01-27 18:43:03 +00001315 const ParmVarDecl *pd = *pi;
Jordan Rose44405b72013-04-04 22:31:48 +00001316 if (pd->getAttr<NSConsumedAttr>())
1317 Template->addArg(AF, parm_idx, DecRefMsg);
1318 else if (pd->getAttr<CFConsumedAttr>())
Jordy Rose0fe62f82011-08-24 09:02:37 +00001319 Template->addArg(AF, parm_idx, DecRef);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001320 }
1321
Ted Kremenekb04cb592009-06-11 18:17:24 +00001322 QualType RetTy = FD->getResultType();
Jordan Rose44405b72013-04-04 22:31:48 +00001323 if (Optional<RetEffect> RetE = getRetEffectFromAnnotations(RetTy, FD))
1324 Template->setRetEffect(*RetE);
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001325}
1326
1327void
Ted Kremenek93edbc52011-10-05 23:54:29 +00001328RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
1329 const ObjCMethodDecl *MD) {
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001330 if (!MD)
1331 return;
1332
Jordan Rose4531b7d2012-07-02 19:27:43 +00001333 assert(Summ && "Must have a valid summary to add annotations to");
1334 RetainSummaryTemplate Template(Summ, *this);
Mike Stump1eb44332009-09-09 15:08:12 +00001335
Ted Kremenek12b94342011-01-27 06:54:14 +00001336 // Effects on the receiver.
Jordan Rose44405b72013-04-04 22:31:48 +00001337 if (MD->getAttr<NSConsumesSelfAttr>())
1338 Template->setReceiverEffect(DecRefMsg);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001339
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;
Jordan Rose44405b72013-04-04 22:31:48 +00001346 if (pd->getAttr<NSConsumedAttr>())
1347 Template->addArg(AF, parm_idx, DecRefMsg);
1348 else if (pd->getAttr<CFConsumedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001349 Template->addArg(AF, parm_idx, DecRef);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001350 }
Ted Kremenek12b94342011-01-27 06:54:14 +00001351 }
1352
Jordan Rose44405b72013-04-04 22:31:48 +00001353 QualType RetTy = MD->getResultType();
1354 if (Optional<RetEffect> RetE = getRetEffectFromAnnotations(RetTy, MD))
1355 Template->setRetEffect(*RetE);
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001356}
1357
Ted Kremenek93edbc52011-10-05 23:54:29 +00001358const RetainSummary *
Jordy Rosef3aae582012-03-17 21:13:07 +00001359RetainSummaryManager::getStandardMethodSummary(const ObjCMethodDecl *MD,
1360 Selector S, QualType RetTy) {
Jordy Rosee921b1a2012-03-17 19:53:04 +00001361 // Any special effects?
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001362 ArgEffect ReceiverEff = DoNothing;
Jordy Rosee921b1a2012-03-17 19:53:04 +00001363 RetEffect ResultEff = RetEffect::MakeNoRet();
1364
1365 // Check the method family, and apply any default annotations.
1366 switch (MD ? MD->getMethodFamily() : S.getMethodFamily()) {
1367 case OMF_None:
1368 case OMF_performSelector:
1369 // Assume all Objective-C methods follow Cocoa Memory Management rules.
1370 // FIXME: Does the non-threaded performSelector family really belong here?
1371 // The selector could be, say, @selector(copy).
1372 if (cocoa::isCocoaObjectRef(RetTy))
1373 ResultEff = RetEffect::MakeNotOwned(RetEffect::ObjC);
1374 else if (coreFoundation::isCFObjectRef(RetTy)) {
1375 // ObjCMethodDecl currently doesn't consider CF objects as valid return
1376 // values for alloc, new, copy, or mutableCopy, so we have to
1377 // double-check with the selector. This is ugly, but there aren't that
1378 // many Objective-C methods that return CF objects, right?
1379 if (MD) {
1380 switch (S.getMethodFamily()) {
1381 case OMF_alloc:
1382 case OMF_new:
1383 case OMF_copy:
1384 case OMF_mutableCopy:
1385 ResultEff = RetEffect::MakeOwned(RetEffect::CF, true);
1386 break;
1387 default:
1388 ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1389 break;
1390 }
1391 } else {
1392 ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1393 }
1394 }
1395 break;
1396 case OMF_init:
1397 ResultEff = ObjCInitRetE;
1398 ReceiverEff = DecRefMsg;
1399 break;
1400 case OMF_alloc:
1401 case OMF_new:
1402 case OMF_copy:
1403 case OMF_mutableCopy:
1404 if (cocoa::isCocoaObjectRef(RetTy))
1405 ResultEff = ObjCAllocRetE;
1406 else if (coreFoundation::isCFObjectRef(RetTy))
1407 ResultEff = RetEffect::MakeOwned(RetEffect::CF, true);
1408 break;
1409 case OMF_autorelease:
1410 ReceiverEff = Autorelease;
1411 break;
1412 case OMF_retain:
1413 ReceiverEff = IncRefMsg;
1414 break;
1415 case OMF_release:
1416 ReceiverEff = DecRefMsg;
1417 break;
1418 case OMF_dealloc:
1419 ReceiverEff = Dealloc;
1420 break;
1421 case OMF_self:
1422 // -self is handled specially by the ExprEngine to propagate the receiver.
1423 break;
1424 case OMF_retainCount:
1425 case OMF_finalize:
1426 // These methods don't return objects.
1427 break;
1428 }
Mike Stump1eb44332009-09-09 15:08:12 +00001429
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001430 // If one of the arguments in the selector has the keyword 'delegate' we
1431 // should stop tracking the reference count for the receiver. This is
1432 // because the reference count is quite possibly handled by a delegate
1433 // method.
1434 if (S.isKeywordSelector()) {
Jordan Rose50571a92012-06-15 18:19:52 +00001435 for (unsigned i = 0, e = S.getNumArgs(); i != e; ++i) {
1436 StringRef Slot = S.getNameForSlot(i);
1437 if (Slot.substr(Slot.size() - 8).equals_lower("delegate")) {
1438 if (ResultEff == ObjCInitRetE)
Anna Zaks554067f2012-08-29 23:23:43 +00001439 ResultEff = RetEffect::MakeNoRetHard();
Jordan Rose50571a92012-06-15 18:19:52 +00001440 else
Anna Zaks554067f2012-08-29 23:23:43 +00001441 ReceiverEff = StopTrackingHard;
Jordan Rose50571a92012-06-15 18:19:52 +00001442 }
1443 }
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001444 }
Mike Stump1eb44332009-09-09 15:08:12 +00001445
Jordy Rosee921b1a2012-03-17 19:53:04 +00001446 if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing &&
1447 ResultEff.getKind() == RetEffect::NoRet)
Ted Kremenek93edbc52011-10-05 23:54:29 +00001448 return getDefaultSummary();
Mike Stump1eb44332009-09-09 15:08:12 +00001449
Jordy Rosee921b1a2012-03-17 19:53:04 +00001450 return getPersistentSummary(ResultEff, ReceiverEff, MayEscape);
Ted Kremenek250b1fa2009-04-23 23:08:22 +00001451}
1452
Ted Kremenek93edbc52011-10-05 23:54:29 +00001453const RetainSummary *
Jordan Rosecde8cdb2012-07-02 19:27:56 +00001454RetainSummaryManager::getInstanceMethodSummary(const ObjCMethodCall &Msg,
Jordan Rose4531b7d2012-07-02 19:27:43 +00001455 ProgramStateRef State) {
1456 const ObjCInterfaceDecl *ReceiverClass = 0;
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001457
Jordan Rose4531b7d2012-07-02 19:27:43 +00001458 // We do better tracking of the type of the object than the core ExprEngine.
1459 // See if we have its type in our private state.
1460 // FIXME: Eventually replace the use of state->get<RefBindings> with
1461 // a generic API for reasoning about the Objective-C types of symbolic
1462 // objects.
1463 SVal ReceiverV = Msg.getReceiverSVal();
1464 if (SymbolRef Sym = ReceiverV.getAsLocSymbol())
Anna Zaks8d6b43c2012-08-14 00:36:15 +00001465 if (const RefVal *T = getRefBinding(State, Sym))
Douglas Gregor04badcf2010-04-21 00:45:42 +00001466 if (const ObjCObjectPointerType *PT =
Jordan Rose4531b7d2012-07-02 19:27:43 +00001467 T->getType()->getAs<ObjCObjectPointerType>())
1468 ReceiverClass = PT->getInterfaceDecl();
1469
1470 // If we don't know what kind of object this is, fall back to its static type.
1471 if (!ReceiverClass)
1472 ReceiverClass = Msg.getReceiverInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00001473
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001474 // FIXME: The receiver could be a reference to a class, meaning that
1475 // we should use the class method.
Jordan Rose4531b7d2012-07-02 19:27:43 +00001476 // id x = [NSObject class];
1477 // [x performSelector:... withObject:... afterDelay:...];
1478 Selector S = Msg.getSelector();
1479 const ObjCMethodDecl *Method = Msg.getDecl();
1480 if (!Method && ReceiverClass)
1481 Method = ReceiverClass->getInstanceMethod(S);
1482
1483 return getMethodSummary(S, ReceiverClass, Method, Msg.getResultType(),
1484 ObjCMethodSummaries);
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001485}
1486
Ted Kremenek93edbc52011-10-05 23:54:29 +00001487const RetainSummary *
Jordan Rose4531b7d2012-07-02 19:27:43 +00001488RetainSummaryManager::getMethodSummary(Selector S, const ObjCInterfaceDecl *ID,
Jordy Rosef3aae582012-03-17 21:13:07 +00001489 const ObjCMethodDecl *MD, QualType RetTy,
1490 ObjCMethodSummariesTy &CachedSummaries) {
Ted Kremenek1bffd742008-05-06 15:44:25 +00001491
Ted Kremenek8711c032009-04-29 05:04:30 +00001492 // Look up a summary in our summary cache.
Jordan Rose4531b7d2012-07-02 19:27:43 +00001493 const RetainSummary *Summ = CachedSummaries.find(ID, S);
Mike Stump1eb44332009-09-09 15:08:12 +00001494
Ted Kremenek614cc542009-07-21 23:27:57 +00001495 if (!Summ) {
Jordy Rosef3aae582012-03-17 21:13:07 +00001496 Summ = getStandardMethodSummary(MD, S, RetTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001497
Ted Kremenek614cc542009-07-21 23:27:57 +00001498 // Annotations override defaults.
Jordy Rose4df54fe2011-08-23 04:27:15 +00001499 updateSummaryFromAnnotations(Summ, MD);
Mike Stump1eb44332009-09-09 15:08:12 +00001500
Ted Kremenek614cc542009-07-21 23:27:57 +00001501 // Memoize the summary.
Jordan Rose4531b7d2012-07-02 19:27:43 +00001502 CachedSummaries[ObjCSummaryKey(ID, S)] = Summ;
Ted Kremenek614cc542009-07-21 23:27:57 +00001503 }
Mike Stump1eb44332009-09-09 15:08:12 +00001504
Ted Kremeneke87450e2009-04-23 19:11:35 +00001505 return Summ;
Ted Kremenekc8395602008-05-06 21:26:51 +00001506}
1507
Mike Stump1eb44332009-09-09 15:08:12 +00001508void RetainSummaryManager::InitializeClassMethodSummaries() {
Ted Kremenekec315332009-05-07 23:40:42 +00001509 assert(ScratchArgs.isEmpty());
Mike Stump1eb44332009-09-09 15:08:12 +00001510 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek6fe2b7a2009-10-15 22:25:12 +00001511 addClassMethSummary("NSAssertionHandler", "currentHandler",
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001512 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Mike Stump1eb44332009-09-09 15:08:12 +00001513
Ted Kremenek6d348932008-10-21 15:53:15 +00001514 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001515 ScratchArgs = AF.add(ScratchArgs, 0, Autorelease);
Ted Kremenek6fe2b7a2009-10-15 22:25:12 +00001516 addClassMethSummary("NSAutoreleasePool", "addObject",
1517 getPersistentSummary(RetEffect::MakeNoRet(),
1518 DoNothing, Autorelease));
Ted Kremenek9c32d082008-05-06 00:30:21 +00001519}
1520
Ted Kremenek1f180c32008-06-23 22:21:20 +00001521void RetainSummaryManager::InitializeMethodSummaries() {
Mike Stump1eb44332009-09-09 15:08:12 +00001522
1523 assert (ScratchArgs.isEmpty());
1524
Ted Kremenekc8395602008-05-06 21:26:51 +00001525 // Create the "init" selector. It just acts as a pass-through for the
1526 // receiver.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001527 const RetainSummary *InitSumm = getPersistentSummary(ObjCInitRetE, DecRefMsg);
Ted Kremenekac02f202009-08-20 05:13:36 +00001528 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
1529
1530 // awakeAfterUsingCoder: behaves basically like an 'init' method. It
1531 // claims the receiver and returns a retained object.
1532 addNSObjectMethSummary(GetUnarySelector("awakeAfterUsingCoder", Ctx),
1533 InitSumm);
Mike Stump1eb44332009-09-09 15:08:12 +00001534
Ted Kremenekc8395602008-05-06 21:26:51 +00001535 // The next methods are allocators.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001536 const RetainSummary *AllocSumm = getPersistentSummary(ObjCAllocRetE);
1537 const RetainSummary *CFAllocSumm =
Ted Kremeneka834fb42009-08-28 19:52:12 +00001538 getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Mike Stump1eb44332009-09-09 15:08:12 +00001539
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001540 // Create the "retain" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001541 RetEffect NoRet = RetEffect::MakeNoRet();
Ted Kremenek93edbc52011-10-05 23:54:29 +00001542 const RetainSummary *Summ = getPersistentSummary(NoRet, IncRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001543 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001544
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001545 // Create the "release" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001546 Summ = getPersistentSummary(NoRet, DecRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001547 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001548
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001549 // Create the -dealloc summary.
Jordy Rose500abad2011-08-21 19:41:36 +00001550 Summ = getPersistentSummary(NoRet, Dealloc);
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001551 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001552
1553 // Create the "autorelease" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001554 Summ = getPersistentSummary(NoRet, Autorelease);
Ted Kremenek553cf182008-06-25 21:21:56 +00001555 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001556
Mike Stump1eb44332009-09-09 15:08:12 +00001557 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremenek89e202d2009-02-23 02:51:29 +00001558 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1559 // self-own themselves. However, they only do this once they are displayed.
1560 // Thus, we need to track an NSWindow's display status.
1561 // This is tracked in <rdar://problem/6062711>.
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +00001562 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001563 const RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenek78a35a32009-05-12 20:06:54 +00001564 StopTracking,
1565 StopTracking);
Mike Stump1eb44332009-09-09 15:08:12 +00001566
Ted Kremenek99d02692009-04-03 19:02:51 +00001567 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1568
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001569 // For NSPanel (which subclasses NSWindow), allocated objects are not
1570 // self-owned.
Ted Kremenek99d02692009-04-03 19:02:51 +00001571 // FIXME: For now we don't track NSPanels. object for the same reason
1572 // as for NSWindow objects.
1573 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
Mike Stump1eb44332009-09-09 15:08:12 +00001574
Jordan Rosee36d81b2013-01-31 22:06:02 +00001575 // Don't track allocated autorelease pools, as it is okay to prematurely
Ted Kremenekba67f6a2009-05-18 23:14:34 +00001576 // exit a method.
1577 addClassMethSummary("NSAutoreleasePool", "alloc", NoTrackYet);
Ted Kremeneka9797122012-02-18 21:37:48 +00001578 addClassMethSummary("NSAutoreleasePool", "allocWithZone", NoTrackYet, false);
Jordan Rosee36d81b2013-01-31 22:06:02 +00001579 addClassMethSummary("NSAutoreleasePool", "new", NoTrackYet);
Ted Kremenek553cf182008-06-25 21:21:56 +00001580
Ted Kremenek767d6492009-05-20 22:39:57 +00001581 // Create summaries QCRenderer/QCView -createSnapShotImageOfType:
1582 addInstMethSummary("QCRenderer", AllocSumm,
1583 "createSnapshotImageOfType", NULL);
1584 addInstMethSummary("QCView", AllocSumm,
1585 "createSnapshotImageOfType", NULL);
1586
Ted Kremenek211a9c62009-06-15 20:58:58 +00001587 // Create summaries for CIContext, 'createCGImage' and
Ted Kremeneka834fb42009-08-28 19:52:12 +00001588 // 'createCGLayerWithSize'. These objects are CF objects, and are not
1589 // automatically garbage collected.
1590 addInstMethSummary("CIContext", CFAllocSumm,
Ted Kremenek767d6492009-05-20 22:39:57 +00001591 "createCGImage", "fromRect", NULL);
Ted Kremeneka834fb42009-08-28 19:52:12 +00001592 addInstMethSummary("CIContext", CFAllocSumm,
Mike Stump1eb44332009-09-09 15:08:12 +00001593 "createCGImage", "fromRect", "format", "colorSpace", NULL);
Ted Kremeneka834fb42009-08-28 19:52:12 +00001594 addInstMethSummary("CIContext", CFAllocSumm, "createCGLayerWithSize",
Ted Kremenek211a9c62009-06-15 20:58:58 +00001595 "info", NULL);
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001596}
1597
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001598//===----------------------------------------------------------------------===//
Ted Kremenekc887d132009-04-29 18:50:19 +00001599// Error reporting.
1600//===----------------------------------------------------------------------===//
Ted Kremenekc887d132009-04-29 18:50:19 +00001601namespace {
Jordy Roseec9ef852011-08-23 20:55:48 +00001602 typedef llvm::DenseMap<const ExplodedNode *, const RetainSummary *>
1603 SummaryLogTy;
1604
Ted Kremenekc887d132009-04-29 18:50:19 +00001605 //===-------------===//
1606 // Bug Descriptions. //
Mike Stump1eb44332009-09-09 15:08:12 +00001607 //===-------------===//
1608
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001609 class CFRefBug : public BugType {
Ted Kremenekc887d132009-04-29 18:50:19 +00001610 protected:
Jordy Rose35c86952011-08-24 05:47:39 +00001611 CFRefBug(StringRef name)
Ted Kremenek6fd45052012-04-05 20:43:28 +00001612 : BugType(name, categories::MemoryCoreFoundationObjectiveC) {}
Ted Kremenekc887d132009-04-29 18:50:19 +00001613 public:
Mike Stump1eb44332009-09-09 15:08:12 +00001614
Ted Kremenekc887d132009-04-29 18:50:19 +00001615 // FIXME: Eventually remove.
Jordy Rose35c86952011-08-24 05:47:39 +00001616 virtual const char *getDescription() const = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001617
Ted Kremenekc887d132009-04-29 18:50:19 +00001618 virtual bool isLeak() const { return false; }
1619 };
Mike Stump1eb44332009-09-09 15:08:12 +00001620
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001621 class UseAfterRelease : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001622 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001623 UseAfterRelease() : CFRefBug("Use-after-release") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001624
Jordy Rose35c86952011-08-24 05:47:39 +00001625 const char *getDescription() const {
Ted Kremenekc887d132009-04-29 18:50:19 +00001626 return "Reference-counted object is used after it is released";
Mike Stump1eb44332009-09-09 15:08:12 +00001627 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001628 };
Mike Stump1eb44332009-09-09 15:08:12 +00001629
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001630 class BadRelease : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001631 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001632 BadRelease() : CFRefBug("Bad release") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001633
Jordy Rose35c86952011-08-24 05:47:39 +00001634 const char *getDescription() const {
Ted Kremenekbb206fd2009-10-01 17:31:50 +00001635 return "Incorrect decrement of the reference count of an object that is "
1636 "not owned at this point by the caller";
Ted Kremenekc887d132009-04-29 18:50:19 +00001637 }
1638 };
Mike Stump1eb44332009-09-09 15:08:12 +00001639
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001640 class DeallocGC : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001641 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001642 DeallocGC()
1643 : CFRefBug("-dealloc called while using garbage collection") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001644
Ted Kremenekc887d132009-04-29 18:50:19 +00001645 const char *getDescription() const {
Ted Kremenek369de562009-05-09 00:10:05 +00001646 return "-dealloc called while using garbage collection";
Ted Kremenekc887d132009-04-29 18:50:19 +00001647 }
1648 };
Mike Stump1eb44332009-09-09 15:08:12 +00001649
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001650 class DeallocNotOwned : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001651 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001652 DeallocNotOwned()
1653 : CFRefBug("-dealloc sent to non-exclusively owned object") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001654
Ted Kremenekc887d132009-04-29 18:50:19 +00001655 const char *getDescription() const {
1656 return "-dealloc sent to object that may be referenced elsewhere";
1657 }
Mike Stump1eb44332009-09-09 15:08:12 +00001658 };
1659
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001660 class OverAutorelease : public CFRefBug {
Ted Kremenek369de562009-05-09 00:10:05 +00001661 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001662 OverAutorelease()
1663 : CFRefBug("Object sent -autorelease too many times") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001664
Ted Kremenek369de562009-05-09 00:10:05 +00001665 const char *getDescription() const {
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001666 return "Object sent -autorelease too many times";
Ted Kremenek369de562009-05-09 00:10:05 +00001667 }
1668 };
Mike Stump1eb44332009-09-09 15:08:12 +00001669
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001670 class ReturnedNotOwnedForOwned : public CFRefBug {
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001671 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001672 ReturnedNotOwnedForOwned()
1673 : CFRefBug("Method should return an owned object") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001674
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001675 const char *getDescription() const {
Jordy Rose5b5402b2011-07-15 22:17:54 +00001676 return "Object with a +0 retain count returned to caller where a +1 "
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001677 "(owning) retain count is expected";
1678 }
1679 };
Mike Stump1eb44332009-09-09 15:08:12 +00001680
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001681 class Leak : public CFRefBug {
Benjamin Kramerfacde172012-06-06 17:32:50 +00001682 public:
1683 Leak(StringRef name)
1684 : CFRefBug(name) {
Jordy Rosedb92bb62011-08-25 01:14:38 +00001685 // Leaks should not be reported if they are post-dominated by a sink.
1686 setSuppressOnSink(true);
1687 }
Mike Stump1eb44332009-09-09 15:08:12 +00001688
Jordy Rose35c86952011-08-24 05:47:39 +00001689 const char *getDescription() const { return ""; }
Mike Stump1eb44332009-09-09 15:08:12 +00001690
Ted Kremenekc887d132009-04-29 18:50:19 +00001691 bool isLeak() const { return true; }
1692 };
Mike Stump1eb44332009-09-09 15:08:12 +00001693
Ted Kremenekc887d132009-04-29 18:50:19 +00001694 //===---------===//
1695 // Bug Reports. //
1696 //===---------===//
Mike Stump1eb44332009-09-09 15:08:12 +00001697
Jordy Rose01153492012-03-24 02:45:35 +00001698 class CFRefReportVisitor : public BugReporterVisitorImpl<CFRefReportVisitor> {
Anna Zaks23f395e2011-08-20 01:27:22 +00001699 protected:
Anna Zaksdc757b02011-08-19 23:21:56 +00001700 SymbolRef Sym;
Jordy Roseec9ef852011-08-23 20:55:48 +00001701 const SummaryLogTy &SummaryLog;
Jordy Rose35c86952011-08-24 05:47:39 +00001702 bool GCEnabled;
Anna Zaks23f395e2011-08-20 01:27:22 +00001703
Anna Zaksdc757b02011-08-19 23:21:56 +00001704 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001705 CFRefReportVisitor(SymbolRef sym, bool gcEnabled, const SummaryLogTy &log)
1706 : Sym(sym), SummaryLog(log), GCEnabled(gcEnabled) {}
Anna Zaksdc757b02011-08-19 23:21:56 +00001707
Anna Zaks23f395e2011-08-20 01:27:22 +00001708 virtual void Profile(llvm::FoldingSetNodeID &ID) const {
Anna Zaksdc757b02011-08-19 23:21:56 +00001709 static int x = 0;
1710 ID.AddPointer(&x);
1711 ID.AddPointer(Sym);
1712 }
1713
Anna Zaks23f395e2011-08-20 01:27:22 +00001714 virtual PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
1715 const ExplodedNode *PrevN,
1716 BugReporterContext &BRC,
1717 BugReport &BR);
1718
1719 virtual PathDiagnosticPiece *getEndPath(BugReporterContext &BRC,
1720 const ExplodedNode *N,
1721 BugReport &BR);
1722 };
1723
1724 class CFRefLeakReportVisitor : public CFRefReportVisitor {
1725 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001726 CFRefLeakReportVisitor(SymbolRef sym, bool GCEnabled,
Jordy Roseec9ef852011-08-23 20:55:48 +00001727 const SummaryLogTy &log)
Jordy Rose35c86952011-08-24 05:47:39 +00001728 : CFRefReportVisitor(sym, GCEnabled, log) {}
Anna Zaks23f395e2011-08-20 01:27:22 +00001729
1730 PathDiagnosticPiece *getEndPath(BugReporterContext &BRC,
1731 const ExplodedNode *N,
1732 BugReport &BR);
Jordy Rose01153492012-03-24 02:45:35 +00001733
1734 virtual BugReporterVisitor *clone() const {
1735 // The curiously-recurring template pattern only works for one level of
1736 // subclassing. Rather than make a new template base for
1737 // CFRefReportVisitor, we simply override clone() to do the right thing.
1738 // This could be trouble someday if BugReporterVisitorImpl is ever
1739 // used for something else besides a convenient implementation of clone().
1740 return new CFRefLeakReportVisitor(*this);
1741 }
Anna Zaksdc757b02011-08-19 23:21:56 +00001742 };
1743
Anna Zakse172e8b2011-08-17 23:00:25 +00001744 class CFRefReport : public BugReport {
Jordy Rose20589562011-08-24 22:39:09 +00001745 void addGCModeDescription(const LangOptions &LOpts, bool GCEnabled);
Jordy Rose35c86952011-08-24 05:47:39 +00001746
Ted Kremenekc887d132009-04-29 18:50:19 +00001747 public:
Jordy Rose20589562011-08-24 22:39:09 +00001748 CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1749 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1750 bool registerVisitor = true)
Anna Zaksedf4dae2011-08-22 18:54:07 +00001751 : BugReport(D, D.getDescription(), n) {
Anna Zaks23f395e2011-08-20 01:27:22 +00001752 if (registerVisitor)
Jordy Rose20589562011-08-24 22:39:09 +00001753 addVisitor(new CFRefReportVisitor(sym, GCEnabled, Log));
1754 addGCModeDescription(LOpts, GCEnabled);
Anna Zaksdc757b02011-08-19 23:21:56 +00001755 }
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001756
Jordy Rose20589562011-08-24 22:39:09 +00001757 CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1758 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1759 StringRef endText)
Anna Zaksedf4dae2011-08-22 18:54:07 +00001760 : BugReport(D, D.getDescription(), endText, n) {
Jordy Rose20589562011-08-24 22:39:09 +00001761 addVisitor(new CFRefReportVisitor(sym, GCEnabled, Log));
1762 addGCModeDescription(LOpts, GCEnabled);
Anna Zaksdc757b02011-08-19 23:21:56 +00001763 }
Mike Stump1eb44332009-09-09 15:08:12 +00001764
Anna Zakse172e8b2011-08-17 23:00:25 +00001765 virtual std::pair<ranges_iterator, ranges_iterator> getRanges() {
Anna Zaksedf4dae2011-08-22 18:54:07 +00001766 const CFRefBug& BugTy = static_cast<CFRefBug&>(getBugType());
1767 if (!BugTy.isLeak())
Anna Zakse172e8b2011-08-17 23:00:25 +00001768 return BugReport::getRanges();
Ted Kremenekc887d132009-04-29 18:50:19 +00001769 else
Argyrios Kyrtzidis640ccf02010-12-04 01:12:15 +00001770 return std::make_pair(ranges_iterator(), ranges_iterator());
Ted Kremenekc887d132009-04-29 18:50:19 +00001771 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001772 };
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001773
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001774 class CFRefLeakReport : public CFRefReport {
Ted Kremenekc887d132009-04-29 18:50:19 +00001775 const MemRegion* AllocBinding;
Anna Zaks23f395e2011-08-20 01:27:22 +00001776
Ted Kremenekc887d132009-04-29 18:50:19 +00001777 public:
Jordy Rose20589562011-08-24 22:39:09 +00001778 CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1779 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
Anna Zaks6a93bd52011-10-25 19:57:11 +00001780 CheckerContext &Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001781
Anna Zaks590dd8e2011-09-20 21:38:35 +00001782 PathDiagnosticLocation getLocation(const SourceManager &SM) const {
1783 assert(Location.isValid());
1784 return Location;
1785 }
Mike Stump1eb44332009-09-09 15:08:12 +00001786 };
Ted Kremenekc887d132009-04-29 18:50:19 +00001787} // end anonymous namespace
1788
Jordy Rose20589562011-08-24 22:39:09 +00001789void CFRefReport::addGCModeDescription(const LangOptions &LOpts,
1790 bool GCEnabled) {
Jordy Rosef95b19d2011-08-24 20:38:42 +00001791 const char *GCModeDescription = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001792
Douglas Gregore289d812011-09-13 17:21:33 +00001793 switch (LOpts.getGC()) {
Anna Zaks7f2531c2011-08-22 20:31:28 +00001794 case LangOptions::GCOnly:
Jordy Rose20589562011-08-24 22:39:09 +00001795 assert(GCEnabled);
Jordy Rose35c86952011-08-24 05:47:39 +00001796 GCModeDescription = "Code is compiled to only use garbage collection";
1797 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001798
Anna Zaks7f2531c2011-08-22 20:31:28 +00001799 case LangOptions::NonGC:
Jordy Rose20589562011-08-24 22:39:09 +00001800 assert(!GCEnabled);
Jordy Rose35c86952011-08-24 05:47:39 +00001801 GCModeDescription = "Code is compiled to use reference counts";
1802 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001803
Anna Zaks7f2531c2011-08-22 20:31:28 +00001804 case LangOptions::HybridGC:
Jordy Rose20589562011-08-24 22:39:09 +00001805 if (GCEnabled) {
Jordy Rose35c86952011-08-24 05:47:39 +00001806 GCModeDescription = "Code is compiled to use either garbage collection "
1807 "(GC) or reference counts (non-GC). The bug occurs "
1808 "with GC enabled";
1809 break;
1810 } else {
1811 GCModeDescription = "Code is compiled to use either garbage collection "
1812 "(GC) or reference counts (non-GC). The bug occurs "
1813 "in non-GC mode";
1814 break;
Anna Zaks7f2531c2011-08-22 20:31:28 +00001815 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001816 }
Jordy Rose35c86952011-08-24 05:47:39 +00001817
Jordy Rosef95b19d2011-08-24 20:38:42 +00001818 assert(GCModeDescription && "invalid/unknown GC mode");
Jordy Rose35c86952011-08-24 05:47:39 +00001819 addExtraText(GCModeDescription);
Ted Kremenekc887d132009-04-29 18:50:19 +00001820}
1821
Jordy Rose910c4052011-09-02 06:44:22 +00001822// FIXME: This should be a method on SmallVector.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001823static inline bool contains(const SmallVectorImpl<ArgEffect>& V,
Ted Kremenekc887d132009-04-29 18:50:19 +00001824 ArgEffect X) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001825 for (SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
Ted Kremenekc887d132009-04-29 18:50:19 +00001826 I!=E; ++I)
1827 if (*I == X) return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001828
Ted Kremenekc887d132009-04-29 18:50:19 +00001829 return false;
1830}
1831
Jordy Rose70fdbc32012-05-12 05:10:43 +00001832static bool isNumericLiteralExpression(const Expr *E) {
1833 // FIXME: This set of cases was copied from SemaExprObjC.
1834 return isa<IntegerLiteral>(E) ||
1835 isa<CharacterLiteral>(E) ||
1836 isa<FloatingLiteral>(E) ||
1837 isa<ObjCBoolLiteralExpr>(E) ||
1838 isa<CXXBoolLiteralExpr>(E);
1839}
1840
Anna Zaksdc757b02011-08-19 23:21:56 +00001841PathDiagnosticPiece *CFRefReportVisitor::VisitNode(const ExplodedNode *N,
1842 const ExplodedNode *PrevN,
1843 BugReporterContext &BRC,
1844 BugReport &BR) {
Jordan Rose28038f32012-07-10 22:07:42 +00001845 // FIXME: We will eventually need to handle non-statement-based events
1846 // (__attribute__((cleanup))).
David Blaikie7a95de62013-02-21 22:23:56 +00001847 if (!N->getLocation().getAs<StmtPoint>())
Ted Kremenek2033a952009-05-13 07:12:33 +00001848 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001849
Ted Kremenek8966bc12009-05-06 21:39:49 +00001850 // Check if the type state has changed.
Ted Kremenek8bef8232012-01-26 21:29:00 +00001851 ProgramStateRef PrevSt = PrevN->getState();
1852 ProgramStateRef CurrSt = N->getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001853 const LocationContext *LCtx = N->getLocationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00001854
Anna Zaks8d6b43c2012-08-14 00:36:15 +00001855 const RefVal* CurrT = getRefBinding(CurrSt, Sym);
Ted Kremenekc887d132009-04-29 18:50:19 +00001856 if (!CurrT) return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001857
Ted Kremenekb65be702009-06-18 01:23:53 +00001858 const RefVal &CurrV = *CurrT;
Anna Zaks8d6b43c2012-08-14 00:36:15 +00001859 const RefVal *PrevT = getRefBinding(PrevSt, Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00001860
Ted Kremenekc887d132009-04-29 18:50:19 +00001861 // Create a string buffer to constain all the useful things we want
1862 // to tell the user.
1863 std::string sbuf;
1864 llvm::raw_string_ostream os(sbuf);
Mike Stump1eb44332009-09-09 15:08:12 +00001865
Ted Kremenekc887d132009-04-29 18:50:19 +00001866 // This is the allocation site since the previous node had no bindings
1867 // for this symbol.
1868 if (!PrevT) {
David Blaikie7a95de62013-02-21 22:23:56 +00001869 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
Mike Stump1eb44332009-09-09 15:08:12 +00001870
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001871 if (isa<ObjCArrayLiteral>(S)) {
1872 os << "NSArray literal is an object with a +0 retain count";
Mike Stump1eb44332009-09-09 15:08:12 +00001873 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001874 else if (isa<ObjCDictionaryLiteral>(S)) {
1875 os << "NSDictionary literal is an object with a +0 retain count";
Ted Kremenekc887d132009-04-29 18:50:19 +00001876 }
Jordy Rose70fdbc32012-05-12 05:10:43 +00001877 else if (const ObjCBoxedExpr *BL = dyn_cast<ObjCBoxedExpr>(S)) {
1878 if (isNumericLiteralExpression(BL->getSubExpr()))
1879 os << "NSNumber literal is an object with a +0 retain count";
1880 else {
1881 const ObjCInterfaceDecl *BoxClass = 0;
1882 if (const ObjCMethodDecl *Method = BL->getBoxingMethod())
1883 BoxClass = Method->getClassInterface();
1884
1885 // We should always be able to find the boxing class interface,
1886 // but consider this future-proofing.
1887 if (BoxClass)
1888 os << *BoxClass << " b";
1889 else
1890 os << "B";
1891
1892 os << "oxed expression produces an object with a +0 retain count";
1893 }
1894 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001895 else {
1896 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
1897 // Get the name of the callee (if it is available).
1898 SVal X = CurrSt->getSValAsScalarOrLoc(CE->getCallee(), LCtx);
1899 if (const FunctionDecl *FD = X.getAsFunctionDecl())
1900 os << "Call to function '" << *FD << '\'';
1901 else
1902 os << "function call";
Ted Kremenekc887d132009-04-29 18:50:19 +00001903 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001904 else {
Jordan Rose8919e682012-07-18 21:59:51 +00001905 assert(isa<ObjCMessageExpr>(S));
Jordan Rosed563d3f2012-07-30 20:22:09 +00001906 CallEventManager &Mgr = CurrSt->getStateManager().getCallEventManager();
1907 CallEventRef<ObjCMethodCall> Call
1908 = Mgr.getObjCMethodCall(cast<ObjCMessageExpr>(S), CurrSt, LCtx);
1909
1910 switch (Call->getMessageKind()) {
Jordan Rose8919e682012-07-18 21:59:51 +00001911 case OCM_Message:
1912 os << "Method";
1913 break;
1914 case OCM_PropertyAccess:
1915 os << "Property";
1916 break;
1917 case OCM_Subscript:
1918 os << "Subscript";
1919 break;
1920 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001921 }
1922
1923 if (CurrV.getObjKind() == RetEffect::CF) {
1924 os << " returns a Core Foundation object with a ";
1925 }
1926 else {
1927 assert (CurrV.getObjKind() == RetEffect::ObjC);
1928 os << " returns an Objective-C object with a ";
1929 }
1930
1931 if (CurrV.isOwned()) {
1932 os << "+1 retain count";
1933
1934 if (GCEnabled) {
1935 assert(CurrV.getObjKind() == RetEffect::CF);
1936 os << ". "
1937 "Core Foundation objects are not automatically garbage collected.";
1938 }
1939 }
1940 else {
1941 assert (CurrV.isNotOwned());
1942 os << "+0 retain count";
1943 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001944 }
Mike Stump1eb44332009-09-09 15:08:12 +00001945
Anna Zaks220ac8c2011-09-15 01:08:34 +00001946 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
1947 N->getLocationContext());
Ted Kremenekc887d132009-04-29 18:50:19 +00001948 return new PathDiagnosticEventPiece(Pos, os.str());
1949 }
Mike Stump1eb44332009-09-09 15:08:12 +00001950
Ted Kremenekc887d132009-04-29 18:50:19 +00001951 // Gather up the effects that were performed on the object at this
1952 // program point
Chris Lattner5f9e2722011-07-23 10:55:15 +00001953 SmallVector<ArgEffect, 2> AEffects;
Mike Stump1eb44332009-09-09 15:08:12 +00001954
Jordy Roseec9ef852011-08-23 20:55:48 +00001955 const ExplodedNode *OrigNode = BRC.getNodeResolver().getOriginalNode(N);
1956 if (const RetainSummary *Summ = SummaryLog.lookup(OrigNode)) {
Ted Kremenekc887d132009-04-29 18:50:19 +00001957 // We only have summaries attached to nodes after evaluating CallExpr and
1958 // ObjCMessageExprs.
David Blaikie7a95de62013-02-21 22:23:56 +00001959 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
Mike Stump1eb44332009-09-09 15:08:12 +00001960
Ted Kremenek5f85e172009-07-22 22:35:28 +00001961 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
Ted Kremenekc887d132009-04-29 18:50:19 +00001962 // Iterate through the parameter expressions and see if the symbol
1963 // was ever passed as an argument.
1964 unsigned i = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001965
Ted Kremenek5f85e172009-07-22 22:35:28 +00001966 for (CallExpr::const_arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
Ted Kremenekc887d132009-04-29 18:50:19 +00001967 AI!=AE; ++AI, ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00001968
Ted Kremenekc887d132009-04-29 18:50:19 +00001969 // Retrieve the value of the argument. Is it the symbol
1970 // we are interested in?
Ted Kremenek5eca4822012-01-06 22:09:28 +00001971 if (CurrSt->getSValAsScalarOrLoc(*AI, LCtx).getAsLocSymbol() != Sym)
Ted Kremenekc887d132009-04-29 18:50:19 +00001972 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001973
Ted Kremenekc887d132009-04-29 18:50:19 +00001974 // We have an argument. Get the effect!
1975 AEffects.push_back(Summ->getArg(i));
1976 }
1977 }
Mike Stump1eb44332009-09-09 15:08:12 +00001978 else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00001979 if (const Expr *receiver = ME->getInstanceReceiver())
Ted Kremenek5eca4822012-01-06 22:09:28 +00001980 if (CurrSt->getSValAsScalarOrLoc(receiver, LCtx)
1981 .getAsLocSymbol() == Sym) {
Ted Kremenekc887d132009-04-29 18:50:19 +00001982 // The symbol we are tracking is the receiver.
1983 AEffects.push_back(Summ->getReceiverEffect());
1984 }
1985 }
1986 }
Mike Stump1eb44332009-09-09 15:08:12 +00001987
Ted Kremenekc887d132009-04-29 18:50:19 +00001988 do {
1989 // Get the previous type state.
1990 RefVal PrevV = *PrevT;
Mike Stump1eb44332009-09-09 15:08:12 +00001991
Ted Kremenekc887d132009-04-29 18:50:19 +00001992 // Specially handle -dealloc.
Jordy Rose35c86952011-08-24 05:47:39 +00001993 if (!GCEnabled && contains(AEffects, Dealloc)) {
Ted Kremenekc887d132009-04-29 18:50:19 +00001994 // Determine if the object's reference count was pushed to zero.
1995 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
1996 // We may not have transitioned to 'release' if we hit an error.
1997 // This case is handled elsewhere.
1998 if (CurrV.getKind() == RefVal::Released) {
Ted Kremenekf21332e2009-05-08 20:01:42 +00001999 assert(CurrV.getCombinedCounts() == 0);
Ted Kremenekc887d132009-04-29 18:50:19 +00002000 os << "Object released by directly sending the '-dealloc' message";
2001 break;
2002 }
2003 }
Mike Stump1eb44332009-09-09 15:08:12 +00002004
Ted Kremenekc887d132009-04-29 18:50:19 +00002005 // Specially handle CFMakeCollectable and friends.
2006 if (contains(AEffects, MakeCollectable)) {
2007 // Get the name of the function.
David Blaikie7a95de62013-02-21 22:23:56 +00002008 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
Ted Kremenek5eca4822012-01-06 22:09:28 +00002009 SVal X =
2010 CurrSt->getSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee(), LCtx);
Ted Kremenek9c378f72011-08-12 23:37:29 +00002011 const FunctionDecl *FD = X.getAsFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002012
Jordy Rose35c86952011-08-24 05:47:39 +00002013 if (GCEnabled) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002014 // Determine if the object's reference count was pushed to zero.
2015 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
Mike Stump1eb44332009-09-09 15:08:12 +00002016
Benjamin Kramerb8989f22011-10-14 18:45:37 +00002017 os << "In GC mode a call to '" << *FD
Ted Kremenekc887d132009-04-29 18:50:19 +00002018 << "' decrements an object's retain count and registers the "
2019 "object with the garbage collector. ";
Mike Stump1eb44332009-09-09 15:08:12 +00002020
Ted Kremenekc887d132009-04-29 18:50:19 +00002021 if (CurrV.getKind() == RefVal::Released) {
2022 assert(CurrV.getCount() == 0);
2023 os << "Since it now has a 0 retain count the object can be "
2024 "automatically collected by the garbage collector.";
2025 }
2026 else
2027 os << "An object must have a 0 retain count to be garbage collected. "
2028 "After this call its retain count is +" << CurrV.getCount()
2029 << '.';
2030 }
Mike Stump1eb44332009-09-09 15:08:12 +00002031 else
Benjamin Kramerb8989f22011-10-14 18:45:37 +00002032 os << "When GC is not enabled a call to '" << *FD
Ted Kremenekc887d132009-04-29 18:50:19 +00002033 << "' has no effect on its argument.";
Mike Stump1eb44332009-09-09 15:08:12 +00002034
Ted Kremenekc887d132009-04-29 18:50:19 +00002035 // Nothing more to say.
2036 break;
2037 }
Mike Stump1eb44332009-09-09 15:08:12 +00002038
2039 // Determine if the typestate has changed.
Ted Kremenekc887d132009-04-29 18:50:19 +00002040 if (!(PrevV == CurrV))
2041 switch (CurrV.getKind()) {
2042 case RefVal::Owned:
2043 case RefVal::NotOwned:
Mike Stump1eb44332009-09-09 15:08:12 +00002044
Ted Kremenekf21332e2009-05-08 20:01:42 +00002045 if (PrevV.getCount() == CurrV.getCount()) {
2046 // Did an autorelease message get sent?
2047 if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
2048 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002049
Zhongxing Xu264e9372009-05-12 10:10:00 +00002050 assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount());
Ted Kremenekeaedfea2009-05-10 05:11:21 +00002051 os << "Object sent -autorelease message";
Ted Kremenekf21332e2009-05-08 20:01:42 +00002052 break;
2053 }
Mike Stump1eb44332009-09-09 15:08:12 +00002054
Ted Kremenekc887d132009-04-29 18:50:19 +00002055 if (PrevV.getCount() > CurrV.getCount())
2056 os << "Reference count decremented.";
2057 else
2058 os << "Reference count incremented.";
Mike Stump1eb44332009-09-09 15:08:12 +00002059
Ted Kremenekc887d132009-04-29 18:50:19 +00002060 if (unsigned Count = CurrV.getCount())
2061 os << " The object now has a +" << Count << " retain count.";
Mike Stump1eb44332009-09-09 15:08:12 +00002062
Ted Kremenekc887d132009-04-29 18:50:19 +00002063 if (PrevV.getKind() == RefVal::Released) {
Jordy Rose35c86952011-08-24 05:47:39 +00002064 assert(GCEnabled && CurrV.getCount() > 0);
Jordy Rose74b7b2b2012-03-17 05:49:15 +00002065 os << " The object is not eligible for garbage collection until "
2066 "the retain count reaches 0 again.";
Ted Kremenekc887d132009-04-29 18:50:19 +00002067 }
Mike Stump1eb44332009-09-09 15:08:12 +00002068
Ted Kremenekc887d132009-04-29 18:50:19 +00002069 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002070
Ted Kremenekc887d132009-04-29 18:50:19 +00002071 case RefVal::Released:
2072 os << "Object released.";
2073 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002074
Ted Kremenekc887d132009-04-29 18:50:19 +00002075 case RefVal::ReturnedOwned:
Jordy Rose74b7b2b2012-03-17 05:49:15 +00002076 // Autoreleases can be applied after marking a node ReturnedOwned.
2077 if (CurrV.getAutoreleaseCount())
2078 return NULL;
2079
2080 os << "Object returned to caller as an owning reference (single "
2081 "retain count transferred to caller)";
Ted Kremenekc887d132009-04-29 18:50:19 +00002082 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002083
Ted Kremenekc887d132009-04-29 18:50:19 +00002084 case RefVal::ReturnedNotOwned:
Ted Kremenekf1365462011-05-26 18:45:44 +00002085 os << "Object returned to caller with a +0 retain count";
Ted Kremenekc887d132009-04-29 18:50:19 +00002086 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002087
Ted Kremenekc887d132009-04-29 18:50:19 +00002088 default:
2089 return NULL;
2090 }
Mike Stump1eb44332009-09-09 15:08:12 +00002091
Ted Kremenekc887d132009-04-29 18:50:19 +00002092 // Emit any remaining diagnostics for the argument effects (if any).
Chris Lattner5f9e2722011-07-23 10:55:15 +00002093 for (SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
Ted Kremenekc887d132009-04-29 18:50:19 +00002094 E=AEffects.end(); I != E; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +00002095
Ted Kremenekc887d132009-04-29 18:50:19 +00002096 // A bunch of things have alternate behavior under GC.
Jordy Rose35c86952011-08-24 05:47:39 +00002097 if (GCEnabled)
Ted Kremenekc887d132009-04-29 18:50:19 +00002098 switch (*I) {
2099 default: break;
2100 case Autorelease:
2101 os << "In GC mode an 'autorelease' has no effect.";
2102 continue;
2103 case IncRefMsg:
2104 os << "In GC mode the 'retain' message has no effect.";
2105 continue;
2106 case DecRefMsg:
2107 os << "In GC mode the 'release' message has no effect.";
2108 continue;
2109 }
2110 }
Mike Stump1eb44332009-09-09 15:08:12 +00002111 } while (0);
2112
Ted Kremenekc887d132009-04-29 18:50:19 +00002113 if (os.str().empty())
2114 return 0; // We have nothing to say!
Ted Kremenek2033a952009-05-13 07:12:33 +00002115
David Blaikie7a95de62013-02-21 22:23:56 +00002116 const Stmt *S = N->getLocation().castAs<StmtPoint>().getStmt();
Anna Zaks220ac8c2011-09-15 01:08:34 +00002117 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
2118 N->getLocationContext());
Ted Kremenek9c378f72011-08-12 23:37:29 +00002119 PathDiagnosticPiece *P = new PathDiagnosticEventPiece(Pos, os.str());
Mike Stump1eb44332009-09-09 15:08:12 +00002120
Ted Kremenekc887d132009-04-29 18:50:19 +00002121 // Add the range by scanning the children of the statement for any bindings
2122 // to Sym.
Mike Stump1eb44332009-09-09 15:08:12 +00002123 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
Ted Kremenek5f85e172009-07-22 22:35:28 +00002124 I!=E; ++I)
Ted Kremenek9c378f72011-08-12 23:37:29 +00002125 if (const Expr *Exp = dyn_cast_or_null<Expr>(*I))
Ted Kremenek5eca4822012-01-06 22:09:28 +00002126 if (CurrSt->getSValAsScalarOrLoc(Exp, LCtx).getAsLocSymbol() == Sym) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002127 P->addRange(Exp->getSourceRange());
2128 break;
2129 }
Mike Stump1eb44332009-09-09 15:08:12 +00002130
Ted Kremenekc887d132009-04-29 18:50:19 +00002131 return P;
2132}
2133
Anna Zakse7e01682012-02-28 22:39:22 +00002134// Find the first node in the current function context that referred to the
2135// tracked symbol and the memory location that value was stored to. Note, the
2136// value is only reported if the allocation occurred in the same function as
2137// the leak.
Zhongxing Xuc5619d92009-08-06 01:32:16 +00002138static std::pair<const ExplodedNode*,const MemRegion*>
Ted Kremenek18c66fd2011-08-15 22:09:50 +00002139GetAllocationSite(ProgramStateManager& StateMgr, const ExplodedNode *N,
Ted Kremenekc887d132009-04-29 18:50:19 +00002140 SymbolRef Sym) {
Ted Kremenek9c378f72011-08-12 23:37:29 +00002141 const ExplodedNode *Last = N;
Mike Stump1eb44332009-09-09 15:08:12 +00002142 const MemRegion* FirstBinding = 0;
Anna Zakse7e01682012-02-28 22:39:22 +00002143 const LocationContext *LeakContext = N->getLocationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002144
Ted Kremenekc887d132009-04-29 18:50:19 +00002145 while (N) {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002146 ProgramStateRef St = N->getState();
Mike Stump1eb44332009-09-09 15:08:12 +00002147
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002148 if (!getRefBinding(St, Sym))
Ted Kremenekc887d132009-04-29 18:50:19 +00002149 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002150
Anna Zaks27b867e2012-03-21 19:45:01 +00002151 StoreManager::FindUniqueBinding FB(Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002152 StateMgr.iterBindings(St, FB);
Anna Zaks27d99dd2013-04-10 21:42:02 +00002153 if (FB) {
2154 const MemRegion *R = FB.getRegion();
2155 const VarRegion *VR = R->getAs<VarRegion>();
2156 // Do not show local variables belonging to a function other than
2157 // where the error is reported.
2158 if (!VR || VR->getStackFrame() == LeakContext->getCurrentStackFrame())
2159 FirstBinding = R;
2160 }
Mike Stump1eb44332009-09-09 15:08:12 +00002161
Anna Zakse7e01682012-02-28 22:39:22 +00002162 // Allocation node, is the last node in the current context in which the
2163 // symbol was tracked.
2164 if (N->getLocationContext() == LeakContext)
2165 Last = N;
2166
Mike Stump1eb44332009-09-09 15:08:12 +00002167 N = N->pred_empty() ? NULL : *(N->pred_begin());
Ted Kremenekc887d132009-04-29 18:50:19 +00002168 }
Mike Stump1eb44332009-09-09 15:08:12 +00002169
Anna Zakse7e01682012-02-28 22:39:22 +00002170 // If allocation happened in a function different from the leak node context,
2171 // do not report the binding.
Ted Kremenek5a8fc882012-10-12 22:56:40 +00002172 assert(N && "Could not find allocation node");
Anna Zakse7e01682012-02-28 22:39:22 +00002173 if (N->getLocationContext() != LeakContext) {
2174 FirstBinding = 0;
2175 }
2176
Ted Kremenekc887d132009-04-29 18:50:19 +00002177 return std::make_pair(Last, FirstBinding);
2178}
2179
2180PathDiagnosticPiece*
Anna Zaks23f395e2011-08-20 01:27:22 +00002181CFRefReportVisitor::getEndPath(BugReporterContext &BRC,
2182 const ExplodedNode *EndN,
2183 BugReport &BR) {
Ted Kremenek76aadc32012-03-09 01:13:14 +00002184 BR.markInteresting(Sym);
Anna Zaks23f395e2011-08-20 01:27:22 +00002185 return BugReporterVisitor::getDefaultEndPath(BRC, EndN, BR);
Ted Kremenekc887d132009-04-29 18:50:19 +00002186}
2187
2188PathDiagnosticPiece*
Anna Zaks23f395e2011-08-20 01:27:22 +00002189CFRefLeakReportVisitor::getEndPath(BugReporterContext &BRC,
2190 const ExplodedNode *EndN,
2191 BugReport &BR) {
Mike Stump1eb44332009-09-09 15:08:12 +00002192
Ted Kremenek8966bc12009-05-06 21:39:49 +00002193 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenekc887d132009-04-29 18:50:19 +00002194 // assigned to different variables, etc.
Ted Kremenek76aadc32012-03-09 01:13:14 +00002195 BR.markInteresting(Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002196
Ted Kremenekc887d132009-04-29 18:50:19 +00002197 // We are reporting a leak. Walk up the graph to get to the first node where
2198 // the symbol appeared, and also get the first VarDecl that tracked object
2199 // is stored to.
Ted Kremenek9c378f72011-08-12 23:37:29 +00002200 const ExplodedNode *AllocNode = 0;
Ted Kremenekc887d132009-04-29 18:50:19 +00002201 const MemRegion* FirstBinding = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002202
Ted Kremenekc887d132009-04-29 18:50:19 +00002203 llvm::tie(AllocNode, FirstBinding) =
Ted Kremenekf04dced2009-05-08 23:32:51 +00002204 GetAllocationSite(BRC.getStateManager(), EndN, Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002205
Anna Zaks4fdf97b2011-09-15 18:56:07 +00002206 SourceManager& SM = BRC.getSourceManager();
Mike Stump1eb44332009-09-09 15:08:12 +00002207
Ted Kremenekc887d132009-04-29 18:50:19 +00002208 // Compute an actual location for the leak. Sometimes a leak doesn't
2209 // occur at an actual statement (e.g., transition between blocks; end
2210 // of function) so we need to walk the graph and compute a real location.
Ted Kremenek9c378f72011-08-12 23:37:29 +00002211 const ExplodedNode *LeakN = EndN;
Anna Zaks4fdf97b2011-09-15 18:56:07 +00002212 PathDiagnosticLocation L = PathDiagnosticLocation::createEndOfPath(LeakN, SM);
Mike Stump1eb44332009-09-09 15:08:12 +00002213
Ted Kremenekc887d132009-04-29 18:50:19 +00002214 std::string sbuf;
2215 llvm::raw_string_ostream os(sbuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002216
Ted Kremenekf1365462011-05-26 18:45:44 +00002217 os << "Object leaked: ";
Mike Stump1eb44332009-09-09 15:08:12 +00002218
Ted Kremenekf1365462011-05-26 18:45:44 +00002219 if (FirstBinding) {
2220 os << "object allocated and stored into '"
2221 << FirstBinding->getString() << '\'';
2222 }
2223 else
2224 os << "allocated object";
Mike Stump1eb44332009-09-09 15:08:12 +00002225
Ted Kremenekc887d132009-04-29 18:50:19 +00002226 // Get the retain count.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002227 const RefVal* RV = getRefBinding(EndN->getState(), Sym);
Ted Kremenek5a8fc882012-10-12 22:56:40 +00002228 assert(RV);
Mike Stump1eb44332009-09-09 15:08:12 +00002229
Ted Kremenekc887d132009-04-29 18:50:19 +00002230 if (RV->getKind() == RefVal::ErrorLeakReturned) {
2231 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
Jordy Rose5b5402b2011-07-15 22:17:54 +00002232 // objects. Only "copy", "alloc", "retain" and "new" transfer ownership
Ted Kremenekc887d132009-04-29 18:50:19 +00002233 // to the caller for NS objects.
Ted Kremenekd368d712011-05-25 06:19:45 +00002234 const Decl *D = &EndN->getCodeDecl();
Ted Kremenekec9f36e2012-09-06 23:03:07 +00002235
2236 os << (isa<ObjCMethodDecl>(D) ? " is returned from a method "
2237 : " is returned from a function ");
2238
2239 if (D->getAttr<CFReturnsNotRetainedAttr>())
2240 os << "that is annotated as CF_RETURNS_NOT_RETAINED";
2241 else if (D->getAttr<NSReturnsNotRetainedAttr>())
2242 os << "that is annotated as NS_RETURNS_NOT_RETAINED";
Ted Kremenekd368d712011-05-25 06:19:45 +00002243 else {
Ted Kremenekec9f36e2012-09-06 23:03:07 +00002244 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2245 os << "whose name ('" << MD->getSelector().getAsString()
2246 << "') does not start with 'copy', 'mutableCopy', 'alloc' or 'new'."
2247 " This violates the naming convention rules"
2248 " given in the Memory Management Guide for Cocoa";
2249 }
2250 else {
2251 const FunctionDecl *FD = cast<FunctionDecl>(D);
2252 os << "whose name ('" << *FD
2253 << "') does not contain 'Copy' or 'Create'. This violates the naming"
2254 " convention rules given in the Memory Management Guide for Core"
2255 " Foundation";
2256 }
2257 }
Ted Kremenekc887d132009-04-29 18:50:19 +00002258 }
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002259 else if (RV->getKind() == RefVal::ErrorGCLeakReturned) {
David Blaikiee1300142013-02-21 22:37:44 +00002260 const ObjCMethodDecl &MD = cast<ObjCMethodDecl>(EndN->getCodeDecl());
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002261 os << " and returned from method '" << MD.getSelector().getAsString()
Ted Kremenek82f2be52009-05-10 16:52:15 +00002262 << "' is potentially leaked when using garbage collection. Callers "
2263 "of this method do not expect a returned object with a +1 retain "
2264 "count since they expect the object to be managed by the garbage "
2265 "collector";
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002266 }
Ted Kremenekc887d132009-04-29 18:50:19 +00002267 else
Ted Kremenekabf517c2010-10-15 22:50:23 +00002268 os << " is not referenced later in this execution path and has a retain "
Ted Kremenekf1365462011-05-26 18:45:44 +00002269 "count of +" << RV->getCount();
Mike Stump1eb44332009-09-09 15:08:12 +00002270
Ted Kremenekc887d132009-04-29 18:50:19 +00002271 return new PathDiagnosticEventPiece(L, os.str());
2272}
2273
Jordy Rose20589562011-08-24 22:39:09 +00002274CFRefLeakReport::CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts,
2275 bool GCEnabled, const SummaryLogTy &Log,
2276 ExplodedNode *n, SymbolRef sym,
Anna Zaks6a93bd52011-10-25 19:57:11 +00002277 CheckerContext &Ctx)
Jordy Rose20589562011-08-24 22:39:09 +00002278: CFRefReport(D, LOpts, GCEnabled, Log, n, sym, false) {
Mike Stump1eb44332009-09-09 15:08:12 +00002279
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00002280 // Most bug reports are cached at the location where they occurred.
Ted Kremenekc887d132009-04-29 18:50:19 +00002281 // With leaks, we want to unique them by the location where they were
2282 // allocated, and only report a single path. To do this, we need to find
2283 // the allocation site of a piece of tracked memory, which we do via a
2284 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2285 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2286 // that all ancestor nodes that represent the allocation site have the
2287 // same SourceLocation.
Ted Kremenek9c378f72011-08-12 23:37:29 +00002288 const ExplodedNode *AllocNode = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002289
Anna Zaks6a93bd52011-10-25 19:57:11 +00002290 const SourceManager& SMgr = Ctx.getSourceManager();
Anna Zaks590dd8e2011-09-20 21:38:35 +00002291
Ted Kremenekc887d132009-04-29 18:50:19 +00002292 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding.
Anna Zaks6a93bd52011-10-25 19:57:11 +00002293 GetAllocationSite(Ctx.getStateManager(), getErrorNode(), sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002294
Ted Kremenekc887d132009-04-29 18:50:19 +00002295 // Get the SourceLocation for the allocation site.
Jordan Rose852aa0d2012-07-10 22:07:52 +00002296 // FIXME: This will crash the analyzer if an allocation comes from an
2297 // implicit call. (Currently there are no such allocations in Cocoa, though.)
2298 const Stmt *AllocStmt;
Ted Kremenekc887d132009-04-29 18:50:19 +00002299 ProgramPoint P = AllocNode->getLocation();
David Blaikie7a95de62013-02-21 22:23:56 +00002300 if (Optional<CallExitEnd> Exit = P.getAs<CallExitEnd>())
Jordan Rose852aa0d2012-07-10 22:07:52 +00002301 AllocStmt = Exit->getCalleeContext()->getCallSite();
2302 else
David Blaikie7a95de62013-02-21 22:23:56 +00002303 AllocStmt = P.castAs<PostStmt>().getStmt();
Jordan Rose852aa0d2012-07-10 22:07:52 +00002304 assert(AllocStmt && "All allocations must come from explicit calls");
Anna Zaks590dd8e2011-09-20 21:38:35 +00002305 Location = PathDiagnosticLocation::createBegin(AllocStmt, SMgr,
2306 n->getLocationContext());
Ted Kremenekc887d132009-04-29 18:50:19 +00002307 // Fill in the description of the bug.
2308 Description.clear();
2309 llvm::raw_string_ostream os(Description);
Ted Kremenekdd924e22009-05-02 19:05:19 +00002310 os << "Potential leak ";
Jordy Rose20589562011-08-24 22:39:09 +00002311 if (GCEnabled)
Ted Kremenekdd924e22009-05-02 19:05:19 +00002312 os << "(when using garbage collection) ";
Anna Zaks212000e2012-02-28 21:49:08 +00002313 os << "of an object";
Mike Stump1eb44332009-09-09 15:08:12 +00002314
Ted Kremenekc887d132009-04-29 18:50:19 +00002315 // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2316 if (AllocBinding)
Anna Zaks212000e2012-02-28 21:49:08 +00002317 os << " stored into '" << AllocBinding->getString() << '\'';
Anna Zaksdc757b02011-08-19 23:21:56 +00002318
Jordy Rose20589562011-08-24 22:39:09 +00002319 addVisitor(new CFRefLeakReportVisitor(sym, GCEnabled, Log));
Ted Kremenekc887d132009-04-29 18:50:19 +00002320}
2321
2322//===----------------------------------------------------------------------===//
2323// Main checker logic.
2324//===----------------------------------------------------------------------===//
2325
Ted Kremenekd593eb92009-11-25 22:17:44 +00002326namespace {
Jordy Rose910c4052011-09-02 06:44:22 +00002327class RetainCountChecker
Jordy Rose9c083b72011-08-24 18:56:32 +00002328 : public Checker< check::Bind,
Jordy Rose38f17d62011-08-23 19:01:07 +00002329 check::DeadSymbols,
Jordy Rose9c083b72011-08-24 18:56:32 +00002330 check::EndAnalysis,
Anna Zaks344c77a2013-01-03 00:25:29 +00002331 check::EndFunction,
Jordy Rose67044292011-08-17 21:27:39 +00002332 check::PostStmt<BlockExpr>,
John McCallf85e1932011-06-15 23:02:42 +00002333 check::PostStmt<CastExpr>,
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002334 check::PostStmt<ObjCArrayLiteral>,
2335 check::PostStmt<ObjCDictionaryLiteral>,
Jordy Rose70fdbc32012-05-12 05:10:43 +00002336 check::PostStmt<ObjCBoxedExpr>,
Jordan Rosefe6a0112012-07-02 19:28:21 +00002337 check::PostCall,
Jordy Rosef53e8c72011-08-23 19:43:16 +00002338 check::PreStmt<ReturnStmt>,
Jordy Rose67044292011-08-17 21:27:39 +00002339 check::RegionChanges,
Jordy Rose76c506f2011-08-21 21:58:18 +00002340 eval::Assume,
2341 eval::Call > {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002342 mutable OwningPtr<CFRefBug> useAfterRelease, releaseNotOwned;
2343 mutable OwningPtr<CFRefBug> deallocGC, deallocNotOwned;
2344 mutable OwningPtr<CFRefBug> overAutorelease, returnNotOwnedForOwned;
2345 mutable OwningPtr<CFRefBug> leakWithinFunction, leakAtReturn;
2346 mutable OwningPtr<CFRefBug> leakWithinFunctionGC, leakAtReturnGC;
Jordy Rose38f17d62011-08-23 19:01:07 +00002347
2348 typedef llvm::DenseMap<SymbolRef, const SimpleProgramPointTag *> SymbolTagMap;
2349
2350 // This map is only used to ensure proper deletion of any allocated tags.
2351 mutable SymbolTagMap DeadSymbolTags;
2352
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002353 mutable OwningPtr<RetainSummaryManager> Summaries;
2354 mutable OwningPtr<RetainSummaryManager> SummariesGC;
Jordy Rose9c083b72011-08-24 18:56:32 +00002355 mutable SummaryLogTy SummaryLog;
2356 mutable bool ShouldResetSummaryLog;
2357
Jordy Rose2f9a66d2011-08-20 21:17:59 +00002358public:
Jordy Rose910c4052011-09-02 06:44:22 +00002359 RetainCountChecker() : ShouldResetSummaryLog(false) {}
Jordy Rose38f17d62011-08-23 19:01:07 +00002360
Jordy Rose910c4052011-09-02 06:44:22 +00002361 virtual ~RetainCountChecker() {
Jordy Rose38f17d62011-08-23 19:01:07 +00002362 DeleteContainerSeconds(DeadSymbolTags);
2363 }
2364
Jordy Rose9c083b72011-08-24 18:56:32 +00002365 void checkEndAnalysis(ExplodedGraph &G, BugReporter &BR,
2366 ExprEngine &Eng) const {
2367 // FIXME: This is a hack to make sure the summary log gets cleared between
2368 // analyses of different code bodies.
2369 //
2370 // Why is this necessary? Because a checker's lifetime is tied to a
2371 // translation unit, but an ExplodedGraph's lifetime is just a code body.
2372 // Once in a blue moon, a new ExplodedNode will have the same address as an
2373 // old one with an associated summary, and the bug report visitor gets very
2374 // confused. (To make things worse, the summary lifetime is currently also
2375 // tied to a code body, so we get a crash instead of incorrect results.)
Jordy Rose1ab51c72011-08-24 09:27:24 +00002376 //
2377 // Why is this a bad solution? Because if the lifetime of the ExplodedGraph
2378 // changes, things will start going wrong again. Really the lifetime of this
2379 // log needs to be tied to either the specific nodes in it or the entire
2380 // ExplodedGraph, not to a specific part of the code being analyzed.
2381 //
Jordy Rose9c083b72011-08-24 18:56:32 +00002382 // (Also, having stateful local data means that the same checker can't be
2383 // used from multiple threads, but a lot of checkers have incorrect
2384 // assumptions about that anyway. So that wasn't a priority at the time of
2385 // this fix.)
Jordy Rose1ab51c72011-08-24 09:27:24 +00002386 //
Jordy Rose9c083b72011-08-24 18:56:32 +00002387 // This happens at the end of analysis, but bug reports are emitted /after/
2388 // this point. So we can't just clear the summary log now. Instead, we mark
2389 // that the next time we access the summary log, it should be cleared.
2390
2391 // If we never reset the summary log during /this/ code body analysis,
2392 // there were no new summaries. There might still have been summaries from
2393 // the /last/ analysis, so clear them out to make sure the bug report
2394 // visitors don't get confused.
2395 if (ShouldResetSummaryLog)
2396 SummaryLog.clear();
2397
2398 ShouldResetSummaryLog = !SummaryLog.empty();
Jordy Rose1ab51c72011-08-24 09:27:24 +00002399 }
2400
Jordy Rose17a38e22011-09-02 05:55:19 +00002401 CFRefBug *getLeakWithinFunctionBug(const LangOptions &LOpts,
2402 bool GCEnabled) const {
2403 if (GCEnabled) {
Jordy Rosedb92bb62011-08-25 01:14:38 +00002404 if (!leakWithinFunctionGC)
Benjamin Kramerfacde172012-06-06 17:32:50 +00002405 leakWithinFunctionGC.reset(new Leak("Leak of object when using "
2406 "garbage collection"));
Jordy Rose17a38e22011-09-02 05:55:19 +00002407 return leakWithinFunctionGC.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002408 } else {
2409 if (!leakWithinFunction) {
Douglas Gregore289d812011-09-13 17:21:33 +00002410 if (LOpts.getGC() == LangOptions::HybridGC) {
Benjamin Kramerfacde172012-06-06 17:32:50 +00002411 leakWithinFunction.reset(new Leak("Leak of object when not using "
2412 "garbage collection (GC) in "
2413 "dual GC/non-GC code"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002414 } else {
Benjamin Kramerfacde172012-06-06 17:32:50 +00002415 leakWithinFunction.reset(new Leak("Leak"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002416 }
2417 }
Jordy Rose17a38e22011-09-02 05:55:19 +00002418 return leakWithinFunction.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002419 }
2420 }
2421
Jordy Rose17a38e22011-09-02 05:55:19 +00002422 CFRefBug *getLeakAtReturnBug(const LangOptions &LOpts, bool GCEnabled) const {
2423 if (GCEnabled) {
Jordy Rosedb92bb62011-08-25 01:14:38 +00002424 if (!leakAtReturnGC)
Benjamin Kramerfacde172012-06-06 17:32:50 +00002425 leakAtReturnGC.reset(new Leak("Leak of returned object when using "
2426 "garbage collection"));
Jordy Rose17a38e22011-09-02 05:55:19 +00002427 return leakAtReturnGC.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002428 } else {
2429 if (!leakAtReturn) {
Douglas Gregore289d812011-09-13 17:21:33 +00002430 if (LOpts.getGC() == LangOptions::HybridGC) {
Benjamin Kramerfacde172012-06-06 17:32:50 +00002431 leakAtReturn.reset(new Leak("Leak of returned object when not using "
2432 "garbage collection (GC) in dual "
2433 "GC/non-GC code"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002434 } else {
Benjamin Kramerfacde172012-06-06 17:32:50 +00002435 leakAtReturn.reset(new Leak("Leak of returned object"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002436 }
2437 }
Jordy Rose17a38e22011-09-02 05:55:19 +00002438 return leakAtReturn.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002439 }
2440 }
2441
Jordy Rose17a38e22011-09-02 05:55:19 +00002442 RetainSummaryManager &getSummaryManager(ASTContext &Ctx,
2443 bool GCEnabled) const {
2444 // FIXME: We don't support ARC being turned on and off during one analysis.
2445 // (nor, for that matter, do we support changing ASTContexts)
David Blaikie4e4d0842012-03-11 07:00:24 +00002446 bool ARCEnabled = (bool)Ctx.getLangOpts().ObjCAutoRefCount;
Jordy Rose17a38e22011-09-02 05:55:19 +00002447 if (GCEnabled) {
2448 if (!SummariesGC)
Jordy Roseb6cfc092011-08-25 00:10:37 +00002449 SummariesGC.reset(new RetainSummaryManager(Ctx, true, ARCEnabled));
Jordy Rose17a38e22011-09-02 05:55:19 +00002450 else
2451 assert(SummariesGC->isARCEnabled() == ARCEnabled);
Jordy Roseb6cfc092011-08-25 00:10:37 +00002452 return *SummariesGC;
2453 } else {
Jordy Rose17a38e22011-09-02 05:55:19 +00002454 if (!Summaries)
Jordy Roseb6cfc092011-08-25 00:10:37 +00002455 Summaries.reset(new RetainSummaryManager(Ctx, false, ARCEnabled));
Jordy Rose17a38e22011-09-02 05:55:19 +00002456 else
2457 assert(Summaries->isARCEnabled() == ARCEnabled);
Jordy Roseb6cfc092011-08-25 00:10:37 +00002458 return *Summaries;
2459 }
2460 }
2461
Jordy Rose17a38e22011-09-02 05:55:19 +00002462 RetainSummaryManager &getSummaryManager(CheckerContext &C) const {
2463 return getSummaryManager(C.getASTContext(), C.isObjCGCEnabled());
2464 }
2465
Ted Kremenek8bef8232012-01-26 21:29:00 +00002466 void printState(raw_ostream &Out, ProgramStateRef State,
Jordy Rosedbd658e2011-08-28 19:11:56 +00002467 const char *NL, const char *Sep) const;
2468
Anna Zaks390909c2011-10-06 00:43:15 +00002469 void checkBind(SVal loc, SVal val, const Stmt *S, CheckerContext &C) const;
Jordy Roseab027fd2011-08-20 21:16:58 +00002470 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
2471 void checkPostStmt(const CastExpr *CE, CheckerContext &C) const;
John McCallf85e1932011-06-15 23:02:42 +00002472
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002473 void checkPostStmt(const ObjCArrayLiteral *AL, CheckerContext &C) const;
2474 void checkPostStmt(const ObjCDictionaryLiteral *DL, CheckerContext &C) const;
Jordy Rose70fdbc32012-05-12 05:10:43 +00002475 void checkPostStmt(const ObjCBoxedExpr *BE, CheckerContext &C) const;
2476
Jordan Rosefe6a0112012-07-02 19:28:21 +00002477 void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002478
Jordan Rose4531b7d2012-07-02 19:27:43 +00002479 void checkSummary(const RetainSummary &Summ, const CallEvent &Call,
Jordy Rosee38dd952011-08-28 05:16:28 +00002480 CheckerContext &C) const;
Jordy Rose294396b2011-08-22 23:48:23 +00002481
Anna Zaks554067f2012-08-29 23:23:43 +00002482 void processSummaryOfInlined(const RetainSummary &Summ,
2483 const CallEvent &Call,
2484 CheckerContext &C) const;
2485
Jordy Rose76c506f2011-08-21 21:58:18 +00002486 bool evalCall(const CallExpr *CE, CheckerContext &C) const;
2487
Ted Kremenek8bef8232012-01-26 21:29:00 +00002488 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Jordy Roseab027fd2011-08-20 21:16:58 +00002489 bool Assumption) const;
Jordy Rose67044292011-08-17 21:27:39 +00002490
Ted Kremenek8bef8232012-01-26 21:29:00 +00002491 ProgramStateRef
2492 checkRegionChanges(ProgramStateRef state,
Anna Zaksbf53dfa2012-12-20 00:38:25 +00002493 const InvalidatedSymbols *invalidated,
Jordy Rose537716a2011-08-27 22:51:26 +00002494 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00002495 ArrayRef<const MemRegion *> Regions,
Jordan Rose740d4902012-07-02 19:27:35 +00002496 const CallEvent *Call) const;
Jordy Roseab027fd2011-08-20 21:16:58 +00002497
Ted Kremenek8bef8232012-01-26 21:29:00 +00002498 bool wantsRegionChangeUpdate(ProgramStateRef state) const {
Jordy Rose2f9a66d2011-08-20 21:17:59 +00002499 return true;
Jordy Roseab027fd2011-08-20 21:16:58 +00002500 }
Jordy Rose294396b2011-08-22 23:48:23 +00002501
Jordy Rosef53e8c72011-08-23 19:43:16 +00002502 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
2503 void checkReturnWithRetEffect(const ReturnStmt *S, CheckerContext &C,
2504 ExplodedNode *Pred, RetEffect RE, RefVal X,
Ted Kremenek8bef8232012-01-26 21:29:00 +00002505 SymbolRef Sym, ProgramStateRef state) const;
Jordy Rosef53e8c72011-08-23 19:43:16 +00002506
Jordy Rose38f17d62011-08-23 19:01:07 +00002507 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Anna Zaks344c77a2013-01-03 00:25:29 +00002508 void checkEndFunction(CheckerContext &C) const;
Jordy Rose38f17d62011-08-23 19:01:07 +00002509
Ted Kremenek8bef8232012-01-26 21:29:00 +00002510 ProgramStateRef updateSymbol(ProgramStateRef state, SymbolRef sym,
Anna Zaks554067f2012-08-29 23:23:43 +00002511 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
2512 CheckerContext &C) const;
Jordy Rosee0a5d322011-08-23 20:27:16 +00002513
Ted Kremenek8bef8232012-01-26 21:29:00 +00002514 void processNonLeakError(ProgramStateRef St, SourceRange ErrorRange,
Jordy Rose294396b2011-08-22 23:48:23 +00002515 RefVal::Kind ErrorKind, SymbolRef Sym,
2516 CheckerContext &C) const;
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002517
2518 void processObjCLiterals(CheckerContext &C, const Expr *Ex) const;
Jordy Rose294396b2011-08-22 23:48:23 +00002519
Jordy Rose38f17d62011-08-23 19:01:07 +00002520 const ProgramPointTag *getDeadSymbolTag(SymbolRef sym) const;
2521
Ted Kremenek8bef8232012-01-26 21:29:00 +00002522 ProgramStateRef handleSymbolDeath(ProgramStateRef state,
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002523 SymbolRef sid, RefVal V,
2524 SmallVectorImpl<SymbolRef> &Leaked) const;
Jordy Rose38f17d62011-08-23 19:01:07 +00002525
Jordan Rose4ee1c552012-12-06 18:58:18 +00002526 ProgramStateRef
Jordan Rose2bce86c2012-08-18 00:30:16 +00002527 handleAutoreleaseCounts(ProgramStateRef state, ExplodedNode *Pred,
2528 const ProgramPointTag *Tag, CheckerContext &Ctx,
2529 SymbolRef Sym, RefVal V) const;
Jordy Rose8d228632011-08-23 20:07:14 +00002530
Ted Kremenek8bef8232012-01-26 21:29:00 +00002531 ExplodedNode *processLeaks(ProgramStateRef state,
Jordy Rose38f17d62011-08-23 19:01:07 +00002532 SmallVectorImpl<SymbolRef> &Leaked,
Anna Zaks6a93bd52011-10-25 19:57:11 +00002533 CheckerContext &Ctx,
Jordy Rose38f17d62011-08-23 19:01:07 +00002534 ExplodedNode *Pred = 0) const;
Ted Kremenekd593eb92009-11-25 22:17:44 +00002535};
2536} // end anonymous namespace
2537
Jordy Rose67044292011-08-17 21:27:39 +00002538namespace {
2539class StopTrackingCallback : public SymbolVisitor {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002540 ProgramStateRef state;
Jordy Rose67044292011-08-17 21:27:39 +00002541public:
Ted Kremenek8bef8232012-01-26 21:29:00 +00002542 StopTrackingCallback(ProgramStateRef st) : state(st) {}
2543 ProgramStateRef getState() const { return state; }
Jordy Rose67044292011-08-17 21:27:39 +00002544
2545 bool VisitSymbol(SymbolRef sym) {
2546 state = state->remove<RefBindings>(sym);
2547 return true;
2548 }
2549};
2550} // end anonymous namespace
2551
Jordy Rose910c4052011-09-02 06:44:22 +00002552//===----------------------------------------------------------------------===//
2553// Handle statements that may have an effect on refcounts.
2554//===----------------------------------------------------------------------===//
Jordy Rose67044292011-08-17 21:27:39 +00002555
Jordy Rose910c4052011-09-02 06:44:22 +00002556void RetainCountChecker::checkPostStmt(const BlockExpr *BE,
2557 CheckerContext &C) const {
Jordy Rose67044292011-08-17 21:27:39 +00002558
Jordy Rose910c4052011-09-02 06:44:22 +00002559 // Scan the BlockDecRefExprs for any object the retain count checker
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002560 // may be tracking.
John McCall469a1eb2011-02-02 13:00:07 +00002561 if (!BE->getBlockDecl()->hasCaptures())
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002562 return;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002563
Ted Kremenek8bef8232012-01-26 21:29:00 +00002564 ProgramStateRef state = C.getState();
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002565 const BlockDataRegion *R =
Ted Kremenek5eca4822012-01-06 22:09:28 +00002566 cast<BlockDataRegion>(state->getSVal(BE,
2567 C.getLocationContext()).getAsRegion());
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002568
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002569 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
2570 E = R->referenced_vars_end();
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002571
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002572 if (I == E)
2573 return;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002574
Ted Kremenek67d12872009-12-07 22:05:27 +00002575 // FIXME: For now we invalidate the tracking of all symbols passed to blocks
2576 // via captured variables, even though captured variables result in a copy
2577 // and in implicit increment/decrement of a retain count.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002578 SmallVector<const MemRegion*, 10> Regions;
Anna Zaks39ac1872011-10-26 21:06:44 +00002579 const LocationContext *LC = C.getLocationContext();
Ted Kremenekc8413fd2010-12-02 07:49:45 +00002580 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002581
Ted Kremenek67d12872009-12-07 22:05:27 +00002582 for ( ; I != E; ++I) {
Ted Kremeneke3ce2c12012-12-06 07:17:20 +00002583 const VarRegion *VR = I.getCapturedRegion();
Ted Kremenek67d12872009-12-07 22:05:27 +00002584 if (VR->getSuperRegion() == R) {
2585 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2586 }
2587 Regions.push_back(VR);
2588 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002589
Ted Kremenek67d12872009-12-07 22:05:27 +00002590 state =
2591 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
2592 Regions.data() + Regions.size()).getState();
Anna Zaks0bd6b112011-10-26 21:06:34 +00002593 C.addTransition(state);
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002594}
2595
Jordy Rose910c4052011-09-02 06:44:22 +00002596void RetainCountChecker::checkPostStmt(const CastExpr *CE,
2597 CheckerContext &C) const {
John McCallf85e1932011-06-15 23:02:42 +00002598 const ObjCBridgedCastExpr *BE = dyn_cast<ObjCBridgedCastExpr>(CE);
2599 if (!BE)
2600 return;
2601
John McCall71c482c2011-06-17 06:50:50 +00002602 ArgEffect AE = IncRef;
John McCallf85e1932011-06-15 23:02:42 +00002603
2604 switch (BE->getBridgeKind()) {
2605 case clang::OBC_Bridge:
2606 // Do nothing.
2607 return;
2608 case clang::OBC_BridgeRetained:
2609 AE = IncRef;
2610 break;
2611 case clang::OBC_BridgeTransfer:
2612 AE = DecRefBridgedTransfered;
2613 break;
2614 }
2615
Ted Kremenek8bef8232012-01-26 21:29:00 +00002616 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00002617 SymbolRef Sym = state->getSVal(CE, C.getLocationContext()).getAsLocSymbol();
John McCallf85e1932011-06-15 23:02:42 +00002618 if (!Sym)
2619 return;
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002620 const RefVal* T = getRefBinding(state, Sym);
John McCallf85e1932011-06-15 23:02:42 +00002621 if (!T)
2622 return;
2623
John McCallf85e1932011-06-15 23:02:42 +00002624 RefVal::Kind hasErr = (RefVal::Kind) 0;
Jordy Rose17a38e22011-09-02 05:55:19 +00002625 state = updateSymbol(state, Sym, *T, AE, hasErr, C);
John McCallf85e1932011-06-15 23:02:42 +00002626
2627 if (hasErr) {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002628 // FIXME: If we get an error during a bridge cast, should we report it?
2629 // Should we assert that there is no error?
John McCallf85e1932011-06-15 23:02:42 +00002630 return;
2631 }
2632
Anna Zaks0bd6b112011-10-26 21:06:34 +00002633 C.addTransition(state);
John McCallf85e1932011-06-15 23:02:42 +00002634}
2635
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002636void RetainCountChecker::processObjCLiterals(CheckerContext &C,
2637 const Expr *Ex) const {
2638 ProgramStateRef state = C.getState();
2639 const ExplodedNode *pred = C.getPredecessor();
2640 for (Stmt::const_child_iterator it = Ex->child_begin(), et = Ex->child_end() ;
2641 it != et ; ++it) {
2642 const Stmt *child = *it;
2643 SVal V = state->getSVal(child, pred->getLocationContext());
2644 if (SymbolRef sym = V.getAsSymbol())
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002645 if (const RefVal* T = getRefBinding(state, sym)) {
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002646 RefVal::Kind hasErr = (RefVal::Kind) 0;
2647 state = updateSymbol(state, sym, *T, MayEscape, hasErr, C);
2648 if (hasErr) {
2649 processNonLeakError(state, child->getSourceRange(), hasErr, sym, C);
2650 return;
2651 }
2652 }
2653 }
2654
2655 // Return the object as autoreleased.
2656 // RetEffect RE = RetEffect::MakeNotOwned(RetEffect::ObjC);
2657 if (SymbolRef sym =
2658 state->getSVal(Ex, pred->getLocationContext()).getAsSymbol()) {
2659 QualType ResultTy = Ex->getType();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002660 state = setRefBinding(state, sym,
2661 RefVal::makeNotOwned(RetEffect::ObjC, ResultTy));
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002662 }
2663
2664 C.addTransition(state);
2665}
2666
2667void RetainCountChecker::checkPostStmt(const ObjCArrayLiteral *AL,
2668 CheckerContext &C) const {
2669 // Apply the 'MayEscape' to all values.
2670 processObjCLiterals(C, AL);
2671}
2672
2673void RetainCountChecker::checkPostStmt(const ObjCDictionaryLiteral *DL,
2674 CheckerContext &C) const {
2675 // Apply the 'MayEscape' to all keys and values.
2676 processObjCLiterals(C, DL);
2677}
2678
Jordy Rose70fdbc32012-05-12 05:10:43 +00002679void RetainCountChecker::checkPostStmt(const ObjCBoxedExpr *Ex,
2680 CheckerContext &C) const {
2681 const ExplodedNode *Pred = C.getPredecessor();
2682 const LocationContext *LCtx = Pred->getLocationContext();
2683 ProgramStateRef State = Pred->getState();
2684
2685 if (SymbolRef Sym = State->getSVal(Ex, LCtx).getAsSymbol()) {
2686 QualType ResultTy = Ex->getType();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002687 State = setRefBinding(State, Sym,
2688 RefVal::makeNotOwned(RetEffect::ObjC, ResultTy));
Jordy Rose70fdbc32012-05-12 05:10:43 +00002689 }
2690
2691 C.addTransition(State);
2692}
2693
Jordan Rosefe6a0112012-07-02 19:28:21 +00002694void RetainCountChecker::checkPostCall(const CallEvent &Call,
2695 CheckerContext &C) const {
Jordan Rosefe6a0112012-07-02 19:28:21 +00002696 RetainSummaryManager &Summaries = getSummaryManager(C);
2697 const RetainSummary *Summ = Summaries.getSummary(Call, C.getState());
Anna Zaks554067f2012-08-29 23:23:43 +00002698
2699 if (C.wasInlined) {
2700 processSummaryOfInlined(*Summ, Call, C);
2701 return;
2702 }
Jordan Rosefe6a0112012-07-02 19:28:21 +00002703 checkSummary(*Summ, Call, C);
Jordy Rose294396b2011-08-22 23:48:23 +00002704}
2705
Jordy Rose910c4052011-09-02 06:44:22 +00002706/// GetReturnType - Used to get the return type of a message expression or
2707/// function call with the intention of affixing that type to a tracked symbol.
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +00002708/// While the return type can be queried directly from RetEx, when
Jordy Rose910c4052011-09-02 06:44:22 +00002709/// invoking class methods we augment to the return type to be that of
2710/// a pointer to the class (as opposed it just being id).
2711// FIXME: We may be able to do this with related result types instead.
2712// This function is probably overestimating.
2713static QualType GetReturnType(const Expr *RetE, ASTContext &Ctx) {
2714 QualType RetTy = RetE->getType();
2715 // If RetE is not a message expression just return its type.
2716 // If RetE is a message expression, return its types if it is something
2717 /// more specific than id.
2718 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RetE))
2719 if (const ObjCObjectPointerType *PT = RetTy->getAs<ObjCObjectPointerType>())
2720 if (PT->isObjCQualifiedIdType() || PT->isObjCIdType() ||
2721 PT->isObjCClassType()) {
2722 // At this point we know the return type of the message expression is
2723 // id, id<...>, or Class. If we have an ObjCInterfaceDecl, we know this
2724 // is a call to a class method whose type we can resolve. In such
2725 // cases, promote the return type to XXX* (where XXX is the class).
2726 const ObjCInterfaceDecl *D = ME->getReceiverInterface();
2727 return !D ? RetTy :
2728 Ctx.getObjCObjectPointerType(Ctx.getObjCInterfaceType(D));
2729 }
2730
2731 return RetTy;
2732}
2733
Anna Zaks554067f2012-08-29 23:23:43 +00002734// We don't always get the exact modeling of the function with regards to the
2735// retain count checker even when the function is inlined. For example, we need
2736// to stop tracking the symbols which were marked with StopTrackingHard.
2737void RetainCountChecker::processSummaryOfInlined(const RetainSummary &Summ,
2738 const CallEvent &CallOrMsg,
2739 CheckerContext &C) const {
2740 ProgramStateRef state = C.getState();
2741
2742 // Evaluate the effect of the arguments.
2743 for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
2744 if (Summ.getArg(idx) == StopTrackingHard) {
2745 SVal V = CallOrMsg.getArgSVal(idx);
2746 if (SymbolRef Sym = V.getAsLocSymbol()) {
2747 state = removeRefBinding(state, Sym);
2748 }
2749 }
2750 }
2751
2752 // Evaluate the effect on the message receiver.
2753 const ObjCMethodCall *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg);
2754 if (MsgInvocation) {
2755 if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
2756 if (Summ.getReceiverEffect() == StopTrackingHard) {
2757 state = removeRefBinding(state, Sym);
2758 }
2759 }
2760 }
2761
2762 // Consult the summary for the return value.
2763 RetEffect RE = Summ.getRetEffect();
2764 if (RE.getKind() == RetEffect::NoRetHard) {
Jordan Rose2f3017f2012-11-02 23:49:29 +00002765 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
Anna Zaks554067f2012-08-29 23:23:43 +00002766 if (Sym)
2767 state = removeRefBinding(state, Sym);
2768 }
2769
2770 C.addTransition(state);
2771}
2772
Jordy Rose910c4052011-09-02 06:44:22 +00002773void RetainCountChecker::checkSummary(const RetainSummary &Summ,
Jordan Rose4531b7d2012-07-02 19:27:43 +00002774 const CallEvent &CallOrMsg,
Jordy Rose910c4052011-09-02 06:44:22 +00002775 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002776 ProgramStateRef state = C.getState();
Jordy Rose294396b2011-08-22 23:48:23 +00002777
2778 // Evaluate the effect of the arguments.
2779 RefVal::Kind hasErr = (RefVal::Kind) 0;
2780 SourceRange ErrorRange;
2781 SymbolRef ErrorSym = 0;
2782
2783 for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
Jordy Rose537716a2011-08-27 22:51:26 +00002784 SVal V = CallOrMsg.getArgSVal(idx);
Jordy Rose294396b2011-08-22 23:48:23 +00002785
2786 if (SymbolRef Sym = V.getAsLocSymbol()) {
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002787 if (const RefVal *T = getRefBinding(state, Sym)) {
Jordy Rose17a38e22011-09-02 05:55:19 +00002788 state = updateSymbol(state, Sym, *T, Summ.getArg(idx), hasErr, C);
Jordy Rose294396b2011-08-22 23:48:23 +00002789 if (hasErr) {
2790 ErrorRange = CallOrMsg.getArgSourceRange(idx);
2791 ErrorSym = Sym;
2792 break;
2793 }
2794 }
2795 }
2796 }
2797
2798 // Evaluate the effect on the message receiver.
2799 bool ReceiverIsTracked = false;
Jordan Rose4531b7d2012-07-02 19:27:43 +00002800 if (!hasErr) {
Jordan Rosecde8cdb2012-07-02 19:27:56 +00002801 const ObjCMethodCall *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg);
Jordan Rose4531b7d2012-07-02 19:27:43 +00002802 if (MsgInvocation) {
2803 if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002804 if (const RefVal *T = getRefBinding(state, Sym)) {
Jordan Rose4531b7d2012-07-02 19:27:43 +00002805 ReceiverIsTracked = true;
2806 state = updateSymbol(state, Sym, *T, Summ.getReceiverEffect(),
Anna Zaks554067f2012-08-29 23:23:43 +00002807 hasErr, C);
Jordan Rose4531b7d2012-07-02 19:27:43 +00002808 if (hasErr) {
Jordan Rose8919e682012-07-18 21:59:51 +00002809 ErrorRange = MsgInvocation->getOriginExpr()->getReceiverRange();
Jordan Rose4531b7d2012-07-02 19:27:43 +00002810 ErrorSym = Sym;
2811 }
Jordy Rose294396b2011-08-22 23:48:23 +00002812 }
2813 }
2814 }
2815 }
2816
2817 // Process any errors.
2818 if (hasErr) {
2819 processNonLeakError(state, ErrorRange, hasErr, ErrorSym, C);
2820 return;
2821 }
2822
2823 // Consult the summary for the return value.
2824 RetEffect RE = Summ.getRetEffect();
2825
2826 if (RE.getKind() == RetEffect::OwnedWhenTrackedReceiver) {
Jordy Roseb6cfc092011-08-25 00:10:37 +00002827 if (ReceiverIsTracked)
Jordy Rose17a38e22011-09-02 05:55:19 +00002828 RE = getSummaryManager(C).getObjAllocRetEffect();
Jordy Roseb6cfc092011-08-25 00:10:37 +00002829 else
Jordy Rose294396b2011-08-22 23:48:23 +00002830 RE = RetEffect::MakeNoRet();
2831 }
2832
2833 switch (RE.getKind()) {
2834 default:
David Blaikie7530c032012-01-17 06:56:22 +00002835 llvm_unreachable("Unhandled RetEffect.");
Jordy Rose294396b2011-08-22 23:48:23 +00002836
2837 case RetEffect::NoRet:
Anna Zaks554067f2012-08-29 23:23:43 +00002838 case RetEffect::NoRetHard:
Jordy Rose294396b2011-08-22 23:48:23 +00002839 // No work necessary.
2840 break;
2841
2842 case RetEffect::OwnedAllocatedSymbol:
2843 case RetEffect::OwnedSymbol: {
Jordan Rose2f3017f2012-11-02 23:49:29 +00002844 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
Jordy Rose294396b2011-08-22 23:48:23 +00002845 if (!Sym)
2846 break;
2847
Jordan Rose4531b7d2012-07-02 19:27:43 +00002848 // Use the result type from the CallEvent as it automatically adjusts
Jordy Rose294396b2011-08-22 23:48:23 +00002849 // for methods/functions that return references.
Jordan Rose4531b7d2012-07-02 19:27:43 +00002850 QualType ResultTy = CallOrMsg.getResultType();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002851 state = setRefBinding(state, Sym, RefVal::makeOwned(RE.getObjKind(),
2852 ResultTy));
Jordy Rose294396b2011-08-22 23:48:23 +00002853
2854 // FIXME: Add a flag to the checker where allocations are assumed to
Anna Zaksc6ba23f2012-08-14 15:39:13 +00002855 // *not* fail.
Jordy Rose294396b2011-08-22 23:48:23 +00002856 break;
2857 }
2858
2859 case RetEffect::GCNotOwnedSymbol:
2860 case RetEffect::ARCNotOwnedSymbol:
2861 case RetEffect::NotOwnedSymbol: {
2862 const Expr *Ex = CallOrMsg.getOriginExpr();
Jordan Rose2f3017f2012-11-02 23:49:29 +00002863 SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol();
Jordy Rose294396b2011-08-22 23:48:23 +00002864 if (!Sym)
2865 break;
Ted Kremenek74616822012-10-12 22:56:45 +00002866 assert(Ex);
Jordy Rose294396b2011-08-22 23:48:23 +00002867 // Use GetReturnType in order to give [NSFoo alloc] the type NSFoo *.
2868 QualType ResultTy = GetReturnType(Ex, C.getASTContext());
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002869 state = setRefBinding(state, Sym, RefVal::makeNotOwned(RE.getObjKind(),
2870 ResultTy));
Jordy Rose294396b2011-08-22 23:48:23 +00002871 break;
2872 }
2873 }
2874
2875 // This check is actually necessary; otherwise the statement builder thinks
2876 // we've hit a previously-found path.
2877 // Normally addTransition takes care of this, but we want the node pointer.
2878 ExplodedNode *NewNode;
2879 if (state == C.getState()) {
2880 NewNode = C.getPredecessor();
2881 } else {
Anna Zaks0bd6b112011-10-26 21:06:34 +00002882 NewNode = C.addTransition(state);
Jordy Rose294396b2011-08-22 23:48:23 +00002883 }
2884
Jordy Rose9c083b72011-08-24 18:56:32 +00002885 // Annotate the node with summary we used.
2886 if (NewNode) {
2887 // FIXME: This is ugly. See checkEndAnalysis for why it's necessary.
2888 if (ShouldResetSummaryLog) {
2889 SummaryLog.clear();
2890 ShouldResetSummaryLog = false;
2891 }
Jordy Roseec9ef852011-08-23 20:55:48 +00002892 SummaryLog[NewNode] = &Summ;
Jordy Rose9c083b72011-08-24 18:56:32 +00002893 }
Jordy Rose294396b2011-08-22 23:48:23 +00002894}
2895
Jordy Rosee0a5d322011-08-23 20:27:16 +00002896
Ted Kremenek8bef8232012-01-26 21:29:00 +00002897ProgramStateRef
2898RetainCountChecker::updateSymbol(ProgramStateRef state, SymbolRef sym,
Jordy Rose910c4052011-09-02 06:44:22 +00002899 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
2900 CheckerContext &C) const {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002901 // In GC mode [... release] and [... retain] do nothing.
Jordy Rose910c4052011-09-02 06:44:22 +00002902 // In ARC mode they shouldn't exist at all, but we just ignore them.
Jordy Rose17a38e22011-09-02 05:55:19 +00002903 bool IgnoreRetainMsg = C.isObjCGCEnabled();
2904 if (!IgnoreRetainMsg)
David Blaikie4e4d0842012-03-11 07:00:24 +00002905 IgnoreRetainMsg = (bool)C.getASTContext().getLangOpts().ObjCAutoRefCount;
Jordy Rose17a38e22011-09-02 05:55:19 +00002906
Jordy Rosee0a5d322011-08-23 20:27:16 +00002907 switch (E) {
Jordan Rose4531b7d2012-07-02 19:27:43 +00002908 default:
2909 break;
2910 case IncRefMsg:
2911 E = IgnoreRetainMsg ? DoNothing : IncRef;
2912 break;
2913 case DecRefMsg:
2914 E = IgnoreRetainMsg ? DoNothing : DecRef;
2915 break;
Anna Zaks554067f2012-08-29 23:23:43 +00002916 case DecRefMsgAndStopTrackingHard:
2917 E = IgnoreRetainMsg ? StopTracking : DecRefAndStopTrackingHard;
Jordan Rose4531b7d2012-07-02 19:27:43 +00002918 break;
2919 case MakeCollectable:
2920 E = C.isObjCGCEnabled() ? DecRef : DoNothing;
2921 break;
Jordy Rosee0a5d322011-08-23 20:27:16 +00002922 }
2923
2924 // Handle all use-after-releases.
Jordy Rose17a38e22011-09-02 05:55:19 +00002925 if (!C.isObjCGCEnabled() && V.getKind() == RefVal::Released) {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002926 V = V ^ RefVal::ErrorUseAfterRelease;
2927 hasErr = V.getKind();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002928 return setRefBinding(state, sym, V);
Jordy Rosee0a5d322011-08-23 20:27:16 +00002929 }
2930
2931 switch (E) {
2932 case DecRefMsg:
2933 case IncRefMsg:
2934 case MakeCollectable:
Anna Zaks554067f2012-08-29 23:23:43 +00002935 case DecRefMsgAndStopTrackingHard:
Jordy Rosee0a5d322011-08-23 20:27:16 +00002936 llvm_unreachable("DecRefMsg/IncRefMsg/MakeCollectable already converted");
Jordy Rosee0a5d322011-08-23 20:27:16 +00002937
2938 case Dealloc:
2939 // Any use of -dealloc in GC is *bad*.
Jordy Rose17a38e22011-09-02 05:55:19 +00002940 if (C.isObjCGCEnabled()) {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002941 V = V ^ RefVal::ErrorDeallocGC;
2942 hasErr = V.getKind();
2943 break;
2944 }
2945
2946 switch (V.getKind()) {
2947 default:
2948 llvm_unreachable("Invalid RefVal state for an explicit dealloc.");
Jordy Rosee0a5d322011-08-23 20:27:16 +00002949 case RefVal::Owned:
2950 // The object immediately transitions to the released state.
2951 V = V ^ RefVal::Released;
2952 V.clearCounts();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002953 return setRefBinding(state, sym, V);
Jordy Rosee0a5d322011-08-23 20:27:16 +00002954 case RefVal::NotOwned:
2955 V = V ^ RefVal::ErrorDeallocNotOwned;
2956 hasErr = V.getKind();
2957 break;
2958 }
2959 break;
2960
Jordy Rosee0a5d322011-08-23 20:27:16 +00002961 case MayEscape:
2962 if (V.getKind() == RefVal::Owned) {
2963 V = V ^ RefVal::NotOwned;
2964 break;
2965 }
2966
2967 // Fall-through.
2968
Jordy Rosee0a5d322011-08-23 20:27:16 +00002969 case DoNothing:
2970 return state;
2971
2972 case Autorelease:
Jordy Rose17a38e22011-09-02 05:55:19 +00002973 if (C.isObjCGCEnabled())
Jordy Rosee0a5d322011-08-23 20:27:16 +00002974 return state;
Jordy Rosee0a5d322011-08-23 20:27:16 +00002975 // Update the autorelease counts.
Jordy Rosee0a5d322011-08-23 20:27:16 +00002976 V = V.autorelease();
2977 break;
2978
2979 case StopTracking:
Anna Zaks554067f2012-08-29 23:23:43 +00002980 case StopTrackingHard:
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002981 return removeRefBinding(state, sym);
Jordy Rosee0a5d322011-08-23 20:27:16 +00002982
2983 case IncRef:
2984 switch (V.getKind()) {
2985 default:
2986 llvm_unreachable("Invalid RefVal state for a retain.");
Jordy Rosee0a5d322011-08-23 20:27:16 +00002987 case RefVal::Owned:
2988 case RefVal::NotOwned:
2989 V = V + 1;
2990 break;
2991 case RefVal::Released:
2992 // Non-GC cases are handled above.
Jordy Rose17a38e22011-09-02 05:55:19 +00002993 assert(C.isObjCGCEnabled());
Jordy Rosee0a5d322011-08-23 20:27:16 +00002994 V = (V ^ RefVal::Owned) + 1;
2995 break;
2996 }
2997 break;
2998
Jordy Rosee0a5d322011-08-23 20:27:16 +00002999 case DecRef:
3000 case DecRefBridgedTransfered:
Anna Zaks554067f2012-08-29 23:23:43 +00003001 case DecRefAndStopTrackingHard:
Jordy Rosee0a5d322011-08-23 20:27:16 +00003002 switch (V.getKind()) {
3003 default:
3004 // case 'RefVal::Released' handled above.
3005 llvm_unreachable("Invalid RefVal state for a release.");
Jordy Rosee0a5d322011-08-23 20:27:16 +00003006
3007 case RefVal::Owned:
3008 assert(V.getCount() > 0);
3009 if (V.getCount() == 1)
3010 V = V ^ (E == DecRefBridgedTransfered ?
3011 RefVal::NotOwned : RefVal::Released);
Anna Zaks554067f2012-08-29 23:23:43 +00003012 else if (E == DecRefAndStopTrackingHard)
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003013 return removeRefBinding(state, sym);
Jordan Rose4531b7d2012-07-02 19:27:43 +00003014
Jordy Rosee0a5d322011-08-23 20:27:16 +00003015 V = V - 1;
3016 break;
3017
3018 case RefVal::NotOwned:
Jordan Rose4531b7d2012-07-02 19:27:43 +00003019 if (V.getCount() > 0) {
Anna Zaks554067f2012-08-29 23:23:43 +00003020 if (E == DecRefAndStopTrackingHard)
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003021 return removeRefBinding(state, sym);
Jordy Rosee0a5d322011-08-23 20:27:16 +00003022 V = V - 1;
Jordan Rose4531b7d2012-07-02 19:27:43 +00003023 } else {
Jordy Rosee0a5d322011-08-23 20:27:16 +00003024 V = V ^ RefVal::ErrorReleaseNotOwned;
3025 hasErr = V.getKind();
3026 }
3027 break;
3028
3029 case RefVal::Released:
3030 // Non-GC cases are handled above.
Jordy Rose17a38e22011-09-02 05:55:19 +00003031 assert(C.isObjCGCEnabled());
Jordy Rosee0a5d322011-08-23 20:27:16 +00003032 V = V ^ RefVal::ErrorUseAfterRelease;
3033 hasErr = V.getKind();
3034 break;
3035 }
3036 break;
3037 }
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003038 return setRefBinding(state, sym, V);
Jordy Rosee0a5d322011-08-23 20:27:16 +00003039}
3040
Ted Kremenek8bef8232012-01-26 21:29:00 +00003041void RetainCountChecker::processNonLeakError(ProgramStateRef St,
Jordy Rose910c4052011-09-02 06:44:22 +00003042 SourceRange ErrorRange,
3043 RefVal::Kind ErrorKind,
3044 SymbolRef Sym,
3045 CheckerContext &C) const {
Jordy Rose294396b2011-08-22 23:48:23 +00003046 ExplodedNode *N = C.generateSink(St);
3047 if (!N)
3048 return;
3049
Jordy Rose294396b2011-08-22 23:48:23 +00003050 CFRefBug *BT;
3051 switch (ErrorKind) {
3052 default:
3053 llvm_unreachable("Unhandled error.");
Jordy Rose294396b2011-08-22 23:48:23 +00003054 case RefVal::ErrorUseAfterRelease:
Jordy Rosed6334e12011-08-25 00:34:03 +00003055 if (!useAfterRelease)
3056 useAfterRelease.reset(new UseAfterRelease());
3057 BT = &*useAfterRelease;
Jordy Rose294396b2011-08-22 23:48:23 +00003058 break;
3059 case RefVal::ErrorReleaseNotOwned:
Jordy Rosed6334e12011-08-25 00:34:03 +00003060 if (!releaseNotOwned)
3061 releaseNotOwned.reset(new BadRelease());
3062 BT = &*releaseNotOwned;
Jordy Rose294396b2011-08-22 23:48:23 +00003063 break;
3064 case RefVal::ErrorDeallocGC:
Jordy Rosed6334e12011-08-25 00:34:03 +00003065 if (!deallocGC)
3066 deallocGC.reset(new DeallocGC());
3067 BT = &*deallocGC;
Jordy Rose294396b2011-08-22 23:48:23 +00003068 break;
3069 case RefVal::ErrorDeallocNotOwned:
Jordy Rosed6334e12011-08-25 00:34:03 +00003070 if (!deallocNotOwned)
3071 deallocNotOwned.reset(new DeallocNotOwned());
3072 BT = &*deallocNotOwned;
Jordy Rose294396b2011-08-22 23:48:23 +00003073 break;
3074 }
3075
Jordy Rosed6334e12011-08-25 00:34:03 +00003076 assert(BT);
David Blaikie4e4d0842012-03-11 07:00:24 +00003077 CFRefReport *report = new CFRefReport(*BT, C.getASTContext().getLangOpts(),
Jordy Rose17a38e22011-09-02 05:55:19 +00003078 C.isObjCGCEnabled(), SummaryLog,
3079 N, Sym);
Jordy Rose294396b2011-08-22 23:48:23 +00003080 report->addRange(ErrorRange);
Jordan Rose785950e2012-11-02 01:53:40 +00003081 C.emitReport(report);
Jordy Rose294396b2011-08-22 23:48:23 +00003082}
3083
Jordy Rose910c4052011-09-02 06:44:22 +00003084//===----------------------------------------------------------------------===//
3085// Handle the return values of retain-count-related functions.
3086//===----------------------------------------------------------------------===//
3087
3088bool RetainCountChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
Jordy Rose76c506f2011-08-21 21:58:18 +00003089 // Get the callee. We're only interested in simple C functions.
Ted Kremenek8bef8232012-01-26 21:29:00 +00003090 ProgramStateRef state = C.getState();
Anna Zaksb805c8f2011-12-01 05:57:37 +00003091 const FunctionDecl *FD = C.getCalleeDecl(CE);
Jordy Rose76c506f2011-08-21 21:58:18 +00003092 if (!FD)
3093 return false;
3094
3095 IdentifierInfo *II = FD->getIdentifier();
3096 if (!II)
3097 return false;
3098
3099 // For now, we're only handling the functions that return aliases of their
3100 // arguments: CFRetain and CFMakeCollectable (and their families).
3101 // Eventually we should add other functions we can model entirely,
3102 // such as CFRelease, which don't invalidate their arguments or globals.
3103 if (CE->getNumArgs() != 1)
3104 return false;
3105
3106 // Get the name of the function.
3107 StringRef FName = II->getName();
3108 FName = FName.substr(FName.find_first_not_of('_'));
3109
3110 // See if it's one of the specific functions we know how to eval.
3111 bool canEval = false;
3112
Anna Zaksb805c8f2011-12-01 05:57:37 +00003113 QualType ResultTy = CE->getCallReturnType();
Jordy Rose76c506f2011-08-21 21:58:18 +00003114 if (ResultTy->isObjCIdType()) {
3115 // Handle: id NSMakeCollectable(CFTypeRef)
3116 canEval = II->isStr("NSMakeCollectable");
3117 } else if (ResultTy->isPointerType()) {
3118 // Handle: (CF|CG)Retain
3119 // CFMakeCollectable
3120 // It's okay to be a little sloppy here (CGMakeCollectable doesn't exist).
3121 if (cocoa::isRefType(ResultTy, "CF", FName) ||
3122 cocoa::isRefType(ResultTy, "CG", FName)) {
3123 canEval = isRetain(FD, FName) || isMakeCollectable(FD, FName);
3124 }
3125 }
3126
3127 if (!canEval)
3128 return false;
3129
3130 // Bind the return value.
Ted Kremenek5eca4822012-01-06 22:09:28 +00003131 const LocationContext *LCtx = C.getLocationContext();
3132 SVal RetVal = state->getSVal(CE->getArg(0), LCtx);
Jordy Rose76c506f2011-08-21 21:58:18 +00003133 if (RetVal.isUnknown()) {
3134 // If the receiver is unknown, conjure a return value.
3135 SValBuilder &SVB = C.getSValBuilder();
Ted Kremenek66c486f2012-08-22 06:26:15 +00003136 RetVal = SVB.conjureSymbolVal(0, CE, LCtx, ResultTy, C.blockCount());
Jordy Rose76c506f2011-08-21 21:58:18 +00003137 }
Ted Kremenek5eca4822012-01-06 22:09:28 +00003138 state = state->BindExpr(CE, LCtx, RetVal, false);
Jordy Rose76c506f2011-08-21 21:58:18 +00003139
Jordy Rose294396b2011-08-22 23:48:23 +00003140 // FIXME: This should not be necessary, but otherwise the argument seems to be
3141 // considered alive during the next statement.
3142 if (const MemRegion *ArgRegion = RetVal.getAsRegion()) {
3143 // Save the refcount status of the argument.
3144 SymbolRef Sym = RetVal.getAsLocSymbol();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003145 const RefVal *Binding = 0;
Jordy Rose294396b2011-08-22 23:48:23 +00003146 if (Sym)
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003147 Binding = getRefBinding(state, Sym);
Jordy Rose76c506f2011-08-21 21:58:18 +00003148
Jordy Rose294396b2011-08-22 23:48:23 +00003149 // Invalidate the argument region.
Anna Zaksbf53dfa2012-12-20 00:38:25 +00003150 state = state->invalidateRegions(ArgRegion, CE, C.blockCount(), LCtx,
Anna Zaks64eb0702013-01-16 01:35:54 +00003151 /*CausesPointerEscape*/ false);
Jordy Rose76c506f2011-08-21 21:58:18 +00003152
Jordy Rose294396b2011-08-22 23:48:23 +00003153 // Restore the refcount status of the argument.
3154 if (Binding)
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003155 state = setRefBinding(state, Sym, *Binding);
Jordy Rose294396b2011-08-22 23:48:23 +00003156 }
3157
Anna Zaks0bd6b112011-10-26 21:06:34 +00003158 C.addTransition(state);
Jordy Rose76c506f2011-08-21 21:58:18 +00003159 return true;
3160}
3161
Jordy Rose910c4052011-09-02 06:44:22 +00003162//===----------------------------------------------------------------------===//
3163// Handle return statements.
3164//===----------------------------------------------------------------------===//
Jordy Rosef53e8c72011-08-23 19:43:16 +00003165
Jordy Rose910c4052011-09-02 06:44:22 +00003166void RetainCountChecker::checkPreStmt(const ReturnStmt *S,
3167 CheckerContext &C) const {
Ted Kremeneke5715782012-02-25 02:09:09 +00003168
3169 // Only adjust the reference count if this is the top-level call frame,
3170 // and not the result of inlining. In the future, we should do
3171 // better checking even for inlined calls, and see if they match
3172 // with their expected semantics (e.g., the method should return a retained
3173 // object, etc.).
Anna Zaksfadcd5d2012-11-03 02:54:16 +00003174 if (!C.inTopFrame())
Ted Kremeneke5715782012-02-25 02:09:09 +00003175 return;
3176
Jordy Rosef53e8c72011-08-23 19:43:16 +00003177 const Expr *RetE = S->getRetValue();
3178 if (!RetE)
3179 return;
3180
Ted Kremenek8bef8232012-01-26 21:29:00 +00003181 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00003182 SymbolRef Sym =
3183 state->getSValAsScalarOrLoc(RetE, C.getLocationContext()).getAsLocSymbol();
Jordy Rosef53e8c72011-08-23 19:43:16 +00003184 if (!Sym)
3185 return;
3186
3187 // Get the reference count binding (if any).
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003188 const RefVal *T = getRefBinding(state, Sym);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003189 if (!T)
3190 return;
3191
3192 // Change the reference count.
3193 RefVal X = *T;
3194
3195 switch (X.getKind()) {
3196 case RefVal::Owned: {
3197 unsigned cnt = X.getCount();
3198 assert(cnt > 0);
3199 X.setCount(cnt - 1);
3200 X = X ^ RefVal::ReturnedOwned;
3201 break;
3202 }
3203
3204 case RefVal::NotOwned: {
3205 unsigned cnt = X.getCount();
3206 if (cnt) {
3207 X.setCount(cnt - 1);
3208 X = X ^ RefVal::ReturnedOwned;
3209 }
3210 else {
3211 X = X ^ RefVal::ReturnedNotOwned;
3212 }
3213 break;
3214 }
3215
3216 default:
3217 return;
3218 }
3219
3220 // Update the binding.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003221 state = setRefBinding(state, Sym, X);
Anna Zaks0bd6b112011-10-26 21:06:34 +00003222 ExplodedNode *Pred = C.addTransition(state);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003223
3224 // At this point we have updated the state properly.
3225 // Everything after this is merely checking to see if the return value has
3226 // been over- or under-retained.
3227
3228 // Did we cache out?
3229 if (!Pred)
3230 return;
3231
Jordy Rosef53e8c72011-08-23 19:43:16 +00003232 // Update the autorelease counts.
3233 static SimpleProgramPointTag
Jordy Rose910c4052011-09-02 06:44:22 +00003234 AutoreleaseTag("RetainCountChecker : Autorelease");
Jordan Rose4ee1c552012-12-06 18:58:18 +00003235 state = handleAutoreleaseCounts(state, Pred, &AutoreleaseTag, C, Sym, X);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003236
3237 // Did we cache out?
Jordan Rose4ee1c552012-12-06 18:58:18 +00003238 if (!state)
Jordy Rosef53e8c72011-08-23 19:43:16 +00003239 return;
3240
3241 // Get the updated binding.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003242 T = getRefBinding(state, Sym);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003243 assert(T);
3244 X = *T;
3245
3246 // Consult the summary of the enclosing method.
Jordy Rose17a38e22011-09-02 05:55:19 +00003247 RetainSummaryManager &Summaries = getSummaryManager(C);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003248 const Decl *CD = &Pred->getCodeDecl();
Jordan Rose4531b7d2012-07-02 19:27:43 +00003249 RetEffect RE = RetEffect::MakeNoRet();
Jordy Rosef53e8c72011-08-23 19:43:16 +00003250
Jordan Rose4531b7d2012-07-02 19:27:43 +00003251 // FIXME: What is the convention for blocks? Is there one?
Jordy Rosef53e8c72011-08-23 19:43:16 +00003252 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CD)) {
Jordy Roseb6cfc092011-08-25 00:10:37 +00003253 const RetainSummary *Summ = Summaries.getMethodSummary(MD);
Jordan Rose4531b7d2012-07-02 19:27:43 +00003254 RE = Summ->getRetEffect();
3255 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) {
3256 if (!isa<CXXMethodDecl>(FD)) {
3257 const RetainSummary *Summ = Summaries.getFunctionSummary(FD);
3258 RE = Summ->getRetEffect();
3259 }
Jordy Rosef53e8c72011-08-23 19:43:16 +00003260 }
3261
Jordan Rose4531b7d2012-07-02 19:27:43 +00003262 checkReturnWithRetEffect(S, C, Pred, RE, X, Sym, state);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003263}
3264
Jordy Rose910c4052011-09-02 06:44:22 +00003265void RetainCountChecker::checkReturnWithRetEffect(const ReturnStmt *S,
3266 CheckerContext &C,
3267 ExplodedNode *Pred,
3268 RetEffect RE, RefVal X,
3269 SymbolRef Sym,
Ted Kremenek8bef8232012-01-26 21:29:00 +00003270 ProgramStateRef state) const {
Jordy Rosef53e8c72011-08-23 19:43:16 +00003271 // Any leaks or other errors?
3272 if (X.isReturnedOwned() && X.getCount() == 0) {
3273 if (RE.getKind() != RetEffect::NoRet) {
3274 bool hasError = false;
Jordy Rose17a38e22011-09-02 05:55:19 +00003275 if (C.isObjCGCEnabled() && RE.getObjKind() == RetEffect::ObjC) {
Jordy Rosef53e8c72011-08-23 19:43:16 +00003276 // Things are more complicated with garbage collection. If the
3277 // returned object is suppose to be an Objective-C object, we have
3278 // a leak (as the caller expects a GC'ed object) because no
3279 // method should return ownership unless it returns a CF object.
3280 hasError = true;
3281 X = X ^ RefVal::ErrorGCLeakReturned;
3282 }
3283 else if (!RE.isOwned()) {
3284 // Either we are using GC and the returned object is a CF type
3285 // or we aren't using GC. In either case, we expect that the
3286 // enclosing method is expected to return ownership.
3287 hasError = true;
3288 X = X ^ RefVal::ErrorLeakReturned;
3289 }
3290
3291 if (hasError) {
3292 // Generate an error node.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003293 state = setRefBinding(state, Sym, X);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003294
3295 static SimpleProgramPointTag
Jordy Rose910c4052011-09-02 06:44:22 +00003296 ReturnOwnLeakTag("RetainCountChecker : ReturnsOwnLeak");
Anna Zaks0bd6b112011-10-26 21:06:34 +00003297 ExplodedNode *N = C.addTransition(state, Pred, &ReturnOwnLeakTag);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003298 if (N) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003299 const LangOptions &LOpts = C.getASTContext().getLangOpts();
Jordy Rose17a38e22011-09-02 05:55:19 +00003300 bool GCEnabled = C.isObjCGCEnabled();
Jordy Rosef53e8c72011-08-23 19:43:16 +00003301 CFRefReport *report =
Jordy Rose17a38e22011-09-02 05:55:19 +00003302 new CFRefLeakReport(*getLeakAtReturnBug(LOpts, GCEnabled),
3303 LOpts, GCEnabled, SummaryLog,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003304 N, Sym, C);
Jordan Rose785950e2012-11-02 01:53:40 +00003305 C.emitReport(report);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003306 }
3307 }
3308 }
3309 } else if (X.isReturnedNotOwned()) {
3310 if (RE.isOwned()) {
3311 // Trying to return a not owned object to a caller expecting an
3312 // owned object.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003313 state = setRefBinding(state, Sym, X ^ RefVal::ErrorReturnedNotOwned);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003314
3315 static SimpleProgramPointTag
Jordy Rose910c4052011-09-02 06:44:22 +00003316 ReturnNotOwnedTag("RetainCountChecker : ReturnNotOwnedForOwned");
Anna Zaks0bd6b112011-10-26 21:06:34 +00003317 ExplodedNode *N = C.addTransition(state, Pred, &ReturnNotOwnedTag);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003318 if (N) {
Jordy Rosed6334e12011-08-25 00:34:03 +00003319 if (!returnNotOwnedForOwned)
3320 returnNotOwnedForOwned.reset(new ReturnedNotOwnedForOwned());
3321
Jordy Rosef53e8c72011-08-23 19:43:16 +00003322 CFRefReport *report =
Jordy Rosed6334e12011-08-25 00:34:03 +00003323 new CFRefReport(*returnNotOwnedForOwned,
David Blaikie4e4d0842012-03-11 07:00:24 +00003324 C.getASTContext().getLangOpts(),
Jordy Rose17a38e22011-09-02 05:55:19 +00003325 C.isObjCGCEnabled(), SummaryLog, N, Sym);
Jordan Rose785950e2012-11-02 01:53:40 +00003326 C.emitReport(report);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003327 }
3328 }
3329 }
3330}
3331
Jordy Rose8d228632011-08-23 20:07:14 +00003332//===----------------------------------------------------------------------===//
Jordy Rose910c4052011-09-02 06:44:22 +00003333// Check various ways a symbol can be invalidated.
3334//===----------------------------------------------------------------------===//
3335
Anna Zaks390909c2011-10-06 00:43:15 +00003336void RetainCountChecker::checkBind(SVal loc, SVal val, const Stmt *S,
Jordy Rose910c4052011-09-02 06:44:22 +00003337 CheckerContext &C) const {
3338 // Are we storing to something that causes the value to "escape"?
3339 bool escapes = true;
3340
3341 // A value escapes in three possible cases (this may change):
3342 //
3343 // (1) we are binding to something that is not a memory region.
3344 // (2) we are binding to a memregion that does not have stack storage
3345 // (3) we are binding to a memregion with stack storage that the store
3346 // does not understand.
Ted Kremenek8bef8232012-01-26 21:29:00 +00003347 ProgramStateRef state = C.getState();
Jordy Rose910c4052011-09-02 06:44:22 +00003348
David Blaikiedc84cd52013-02-20 22:23:23 +00003349 if (Optional<loc::MemRegionVal> regionLoc = loc.getAs<loc::MemRegionVal>()) {
Jordy Rose910c4052011-09-02 06:44:22 +00003350 escapes = !regionLoc->getRegion()->hasStackStorage();
3351
3352 if (!escapes) {
3353 // To test (3), generate a new state with the binding added. If it is
3354 // the same state, then it escapes (since the store cannot represent
3355 // the binding).
Anna Zakse7958da2012-05-02 00:15:40 +00003356 // Do this only if we know that the store is not supposed to generate the
3357 // same state.
3358 SVal StoredVal = state->getSVal(regionLoc->getRegion());
3359 if (StoredVal != val)
3360 escapes = (state == (state->bindLoc(*regionLoc, val)));
Jordy Rose910c4052011-09-02 06:44:22 +00003361 }
Ted Kremenekde5b4fb2012-03-27 01:12:45 +00003362 if (!escapes) {
3363 // Case 4: We do not currently model what happens when a symbol is
3364 // assigned to a struct field, so be conservative here and let the symbol
3365 // go. TODO: This could definitely be improved upon.
3366 escapes = !isa<VarRegion>(regionLoc->getRegion());
3367 }
Jordy Rose910c4052011-09-02 06:44:22 +00003368 }
3369
3370 // If our store can represent the binding and we aren't storing to something
3371 // that doesn't have local storage then just return and have the simulation
3372 // state continue as is.
3373 if (!escapes)
3374 return;
3375
3376 // Otherwise, find all symbols referenced by 'val' that we are tracking
3377 // and stop tracking them.
3378 state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
Anna Zaks0bd6b112011-10-26 21:06:34 +00003379 C.addTransition(state);
Jordy Rose910c4052011-09-02 06:44:22 +00003380}
3381
Ted Kremenek8bef8232012-01-26 21:29:00 +00003382ProgramStateRef RetainCountChecker::evalAssume(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003383 SVal Cond,
3384 bool Assumption) const {
3385
3386 // FIXME: We may add to the interface of evalAssume the list of symbols
3387 // whose assumptions have changed. For now we just iterate through the
3388 // bindings and check if any of the tracked symbols are NULL. This isn't
3389 // too bad since the number of symbols we will track in practice are
3390 // probably small and evalAssume is only called at branches and a few
3391 // other places.
Jordan Rose166d5022012-11-02 01:54:06 +00003392 RefBindingsTy B = state->get<RefBindings>();
Jordy Rose910c4052011-09-02 06:44:22 +00003393
3394 if (B.isEmpty())
3395 return state;
3396
3397 bool changed = false;
Jordan Rose166d5022012-11-02 01:54:06 +00003398 RefBindingsTy::Factory &RefBFactory = state->get_context<RefBindings>();
Jordy Rose910c4052011-09-02 06:44:22 +00003399
Jordan Rose166d5022012-11-02 01:54:06 +00003400 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Ted Kremenek47cbd0f2012-09-07 22:31:01 +00003401 // Check if the symbol is null stop tracking the symbol.
Jordan Roseec8d4202012-11-01 00:18:27 +00003402 ConstraintManager &CMgr = state->getConstraintManager();
3403 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
3404 if (AllocFailed.isConstrainedTrue()) {
Jordy Rose910c4052011-09-02 06:44:22 +00003405 changed = true;
3406 B = RefBFactory.remove(B, I.getKey());
3407 }
3408 }
3409
3410 if (changed)
3411 state = state->set<RefBindings>(B);
3412
3413 return state;
3414}
3415
Ted Kremenek8bef8232012-01-26 21:29:00 +00003416ProgramStateRef
3417RetainCountChecker::checkRegionChanges(ProgramStateRef state,
Anna Zaksbf53dfa2012-12-20 00:38:25 +00003418 const InvalidatedSymbols *invalidated,
Jordy Rose910c4052011-09-02 06:44:22 +00003419 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00003420 ArrayRef<const MemRegion *> Regions,
Jordan Rose740d4902012-07-02 19:27:35 +00003421 const CallEvent *Call) const {
Jordy Rose910c4052011-09-02 06:44:22 +00003422 if (!invalidated)
3423 return state;
3424
3425 llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
3426 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
3427 E = ExplicitRegions.end(); I != E; ++I) {
3428 if (const SymbolicRegion *SR = (*I)->StripCasts()->getAs<SymbolicRegion>())
3429 WhitelistedSymbols.insert(SR->getSymbol());
3430 }
3431
Anna Zaksbf53dfa2012-12-20 00:38:25 +00003432 for (InvalidatedSymbols::const_iterator I=invalidated->begin(),
Jordy Rose910c4052011-09-02 06:44:22 +00003433 E = invalidated->end(); I!=E; ++I) {
3434 SymbolRef sym = *I;
3435 if (WhitelistedSymbols.count(sym))
3436 continue;
3437 // Remove any existing reference-count binding.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003438 state = removeRefBinding(state, sym);
Jordy Rose910c4052011-09-02 06:44:22 +00003439 }
3440 return state;
3441}
3442
3443//===----------------------------------------------------------------------===//
Jordy Rose8d228632011-08-23 20:07:14 +00003444// Handle dead symbols and end-of-path.
3445//===----------------------------------------------------------------------===//
3446
Jordan Rose4ee1c552012-12-06 18:58:18 +00003447ProgramStateRef
3448RetainCountChecker::handleAutoreleaseCounts(ProgramStateRef state,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003449 ExplodedNode *Pred,
Jordan Rose2bce86c2012-08-18 00:30:16 +00003450 const ProgramPointTag *Tag,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003451 CheckerContext &Ctx,
Jordy Rose910c4052011-09-02 06:44:22 +00003452 SymbolRef Sym, RefVal V) const {
Jordy Rose8d228632011-08-23 20:07:14 +00003453 unsigned ACnt = V.getAutoreleaseCount();
3454
3455 // No autorelease counts? Nothing to be done.
3456 if (!ACnt)
Jordan Rose4ee1c552012-12-06 18:58:18 +00003457 return state;
Jordy Rose8d228632011-08-23 20:07:14 +00003458
Anna Zaks6a93bd52011-10-25 19:57:11 +00003459 assert(!Ctx.isObjCGCEnabled() && "Autorelease counts in GC mode?");
Jordy Rose8d228632011-08-23 20:07:14 +00003460 unsigned Cnt = V.getCount();
3461
3462 // FIXME: Handle sending 'autorelease' to already released object.
3463
3464 if (V.getKind() == RefVal::ReturnedOwned)
3465 ++Cnt;
3466
3467 if (ACnt <= Cnt) {
3468 if (ACnt == Cnt) {
3469 V.clearCounts();
3470 if (V.getKind() == RefVal::ReturnedOwned)
3471 V = V ^ RefVal::ReturnedNotOwned;
3472 else
3473 V = V ^ RefVal::NotOwned;
3474 } else {
Anna Zaks0217b1d2013-01-31 22:36:17 +00003475 V.setCount(V.getCount() - ACnt);
Jordy Rose8d228632011-08-23 20:07:14 +00003476 V.setAutoreleaseCount(0);
3477 }
Jordan Rose4ee1c552012-12-06 18:58:18 +00003478 return setRefBinding(state, Sym, V);
Jordy Rose8d228632011-08-23 20:07:14 +00003479 }
3480
3481 // Woah! More autorelease counts then retain counts left.
3482 // Emit hard error.
3483 V = V ^ RefVal::ErrorOverAutorelease;
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003484 state = setRefBinding(state, Sym, V);
Jordy Rose8d228632011-08-23 20:07:14 +00003485
Jordan Rosefa06f042012-08-20 18:43:42 +00003486 ExplodedNode *N = Ctx.generateSink(state, Pred, Tag);
Jordan Rose2bce86c2012-08-18 00:30:16 +00003487 if (N) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003488 SmallString<128> sbuf;
Jordy Rose8d228632011-08-23 20:07:14 +00003489 llvm::raw_svector_ostream os(sbuf);
3490 os << "Object over-autoreleased: object was sent -autorelease ";
3491 if (V.getAutoreleaseCount() > 1)
3492 os << V.getAutoreleaseCount() << " times ";
3493 os << "but the object has a +" << V.getCount() << " retain count";
3494
Jordy Rosed6334e12011-08-25 00:34:03 +00003495 if (!overAutorelease)
3496 overAutorelease.reset(new OverAutorelease());
3497
David Blaikie4e4d0842012-03-11 07:00:24 +00003498 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
Jordy Rose8d228632011-08-23 20:07:14 +00003499 CFRefReport *report =
Jordy Rosed6334e12011-08-25 00:34:03 +00003500 new CFRefReport(*overAutorelease, LOpts, /* GCEnabled = */ false,
3501 SummaryLog, N, Sym, os.str());
Jordan Rose785950e2012-11-02 01:53:40 +00003502 Ctx.emitReport(report);
Jordy Rose8d228632011-08-23 20:07:14 +00003503 }
3504
Jordan Rose4ee1c552012-12-06 18:58:18 +00003505 return 0;
Jordy Rose8d228632011-08-23 20:07:14 +00003506}
Jordy Rose38f17d62011-08-23 19:01:07 +00003507
Ted Kremenek8bef8232012-01-26 21:29:00 +00003508ProgramStateRef
3509RetainCountChecker::handleSymbolDeath(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003510 SymbolRef sid, RefVal V,
Jordy Rose38f17d62011-08-23 19:01:07 +00003511 SmallVectorImpl<SymbolRef> &Leaked) const {
Jordy Rose53376122011-08-24 04:48:19 +00003512 bool hasLeak = false;
Jordy Rose38f17d62011-08-23 19:01:07 +00003513 if (V.isOwned())
3514 hasLeak = true;
3515 else if (V.isNotOwned() || V.isReturnedOwned())
3516 hasLeak = (V.getCount() > 0);
3517
3518 if (!hasLeak)
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003519 return removeRefBinding(state, sid);
Jordy Rose38f17d62011-08-23 19:01:07 +00003520
3521 Leaked.push_back(sid);
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003522 return setRefBinding(state, sid, V ^ RefVal::ErrorLeak);
Jordy Rose38f17d62011-08-23 19:01:07 +00003523}
3524
3525ExplodedNode *
Ted Kremenek8bef8232012-01-26 21:29:00 +00003526RetainCountChecker::processLeaks(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003527 SmallVectorImpl<SymbolRef> &Leaked,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003528 CheckerContext &Ctx,
3529 ExplodedNode *Pred) const {
Jordy Rose38f17d62011-08-23 19:01:07 +00003530 // Generate an intermediate node representing the leak point.
Jordan Rose2bce86c2012-08-18 00:30:16 +00003531 ExplodedNode *N = Ctx.addTransition(state, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003532
3533 if (N) {
3534 for (SmallVectorImpl<SymbolRef>::iterator
3535 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3536
David Blaikie4e4d0842012-03-11 07:00:24 +00003537 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
Anna Zaks6a93bd52011-10-25 19:57:11 +00003538 bool GCEnabled = Ctx.isObjCGCEnabled();
Jordy Rose17a38e22011-09-02 05:55:19 +00003539 CFRefBug *BT = Pred ? getLeakWithinFunctionBug(LOpts, GCEnabled)
3540 : getLeakAtReturnBug(LOpts, GCEnabled);
Jordy Rose38f17d62011-08-23 19:01:07 +00003541 assert(BT && "BugType not initialized.");
Jordy Rose20589562011-08-24 22:39:09 +00003542
Jordy Rose17a38e22011-09-02 05:55:19 +00003543 CFRefLeakReport *report = new CFRefLeakReport(*BT, LOpts, GCEnabled,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003544 SummaryLog, N, *I, Ctx);
Jordan Rose785950e2012-11-02 01:53:40 +00003545 Ctx.emitReport(report);
Jordy Rose38f17d62011-08-23 19:01:07 +00003546 }
3547 }
3548
3549 return N;
3550}
3551
Anna Zaks344c77a2013-01-03 00:25:29 +00003552void RetainCountChecker::checkEndFunction(CheckerContext &Ctx) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +00003553 ProgramStateRef state = Ctx.getState();
Jordan Rose166d5022012-11-02 01:54:06 +00003554 RefBindingsTy B = state->get<RefBindings>();
Anna Zaksaf498a22011-10-25 19:56:48 +00003555 ExplodedNode *Pred = Ctx.getPredecessor();
Jordy Rose38f17d62011-08-23 19:01:07 +00003556
Jordan Rose166d5022012-11-02 01:54:06 +00003557 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Jordan Rose4ee1c552012-12-06 18:58:18 +00003558 state = handleAutoreleaseCounts(state, Pred, /*Tag=*/0, Ctx,
3559 I->first, I->second);
Jordy Rose8d228632011-08-23 20:07:14 +00003560 if (!state)
Jordy Rose38f17d62011-08-23 19:01:07 +00003561 return;
3562 }
3563
Ted Kremenek0cf3d472012-02-07 00:24:33 +00003564 // If the current LocationContext has a parent, don't check for leaks.
3565 // We will do that later.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003566 // FIXME: we should instead check for imbalances of the retain/releases,
Ted Kremenek0cf3d472012-02-07 00:24:33 +00003567 // and suggest annotations.
3568 if (Ctx.getLocationContext()->getParent())
3569 return;
3570
Jordy Rose38f17d62011-08-23 19:01:07 +00003571 B = state->get<RefBindings>();
3572 SmallVector<SymbolRef, 10> Leaked;
3573
Jordan Rose166d5022012-11-02 01:54:06 +00003574 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I)
Jordy Rose8d228632011-08-23 20:07:14 +00003575 state = handleSymbolDeath(state, I->first, I->second, Leaked);
Jordy Rose38f17d62011-08-23 19:01:07 +00003576
Jordan Rose2bce86c2012-08-18 00:30:16 +00003577 processLeaks(state, Leaked, Ctx, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003578}
3579
3580const ProgramPointTag *
Jordy Rose910c4052011-09-02 06:44:22 +00003581RetainCountChecker::getDeadSymbolTag(SymbolRef sym) const {
Jordy Rose38f17d62011-08-23 19:01:07 +00003582 const SimpleProgramPointTag *&tag = DeadSymbolTags[sym];
3583 if (!tag) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003584 SmallString<64> buf;
Jordy Rose38f17d62011-08-23 19:01:07 +00003585 llvm::raw_svector_ostream out(buf);
Anna Zaksf62ceec2011-12-05 18:58:11 +00003586 out << "RetainCountChecker : Dead Symbol : ";
3587 sym->dumpToStream(out);
Jordy Rose38f17d62011-08-23 19:01:07 +00003588 tag = new SimpleProgramPointTag(out.str());
3589 }
3590 return tag;
3591}
3592
Jordy Rose910c4052011-09-02 06:44:22 +00003593void RetainCountChecker::checkDeadSymbols(SymbolReaper &SymReaper,
3594 CheckerContext &C) const {
Jordy Rose38f17d62011-08-23 19:01:07 +00003595 ExplodedNode *Pred = C.getPredecessor();
3596
Ted Kremenek8bef8232012-01-26 21:29:00 +00003597 ProgramStateRef state = C.getState();
Jordan Rose166d5022012-11-02 01:54:06 +00003598 RefBindingsTy B = state->get<RefBindings>();
Jordan Rose4ee1c552012-12-06 18:58:18 +00003599 SmallVector<SymbolRef, 10> Leaked;
Jordy Rose38f17d62011-08-23 19:01:07 +00003600
3601 // Update counts from autorelease pools
3602 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3603 E = SymReaper.dead_end(); I != E; ++I) {
3604 SymbolRef Sym = *I;
3605 if (const RefVal *T = B.lookup(Sym)){
3606 // Use the symbol as the tag.
3607 // FIXME: This might not be as unique as we would like.
Jordan Rose2bce86c2012-08-18 00:30:16 +00003608 const ProgramPointTag *Tag = getDeadSymbolTag(Sym);
Jordan Rose4ee1c552012-12-06 18:58:18 +00003609 state = handleAutoreleaseCounts(state, Pred, Tag, C, Sym, *T);
Jordy Rose8d228632011-08-23 20:07:14 +00003610 if (!state)
Jordy Rose38f17d62011-08-23 19:01:07 +00003611 return;
Jordan Rose4ee1c552012-12-06 18:58:18 +00003612
3613 // Fetch the new reference count from the state, and use it to handle
3614 // this symbol.
3615 state = handleSymbolDeath(state, *I, *getRefBinding(state, Sym), Leaked);
Jordy Rose38f17d62011-08-23 19:01:07 +00003616 }
3617 }
3618
Jordan Rose4ee1c552012-12-06 18:58:18 +00003619 if (Leaked.empty()) {
3620 C.addTransition(state);
3621 return;
Jordy Rose38f17d62011-08-23 19:01:07 +00003622 }
3623
Jordan Rose2bce86c2012-08-18 00:30:16 +00003624 Pred = processLeaks(state, Leaked, C, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003625
3626 // Did we cache out?
3627 if (!Pred)
3628 return;
3629
3630 // Now generate a new node that nukes the old bindings.
Jordan Rose4ee1c552012-12-06 18:58:18 +00003631 // The only bindings left at this point are the leaked symbols.
Jordan Rose166d5022012-11-02 01:54:06 +00003632 RefBindingsTy::Factory &F = state->get_context<RefBindings>();
Jordan Rose4ee1c552012-12-06 18:58:18 +00003633 B = state->get<RefBindings>();
Jordy Rose38f17d62011-08-23 19:01:07 +00003634
Jordan Rose4ee1c552012-12-06 18:58:18 +00003635 for (SmallVectorImpl<SymbolRef>::iterator I = Leaked.begin(),
3636 E = Leaked.end();
3637 I != E; ++I)
Jordy Rose38f17d62011-08-23 19:01:07 +00003638 B = F.remove(B, *I);
3639
3640 state = state->set<RefBindings>(B);
Anna Zaks0bd6b112011-10-26 21:06:34 +00003641 C.addTransition(state, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003642}
3643
Ted Kremenek8bef8232012-01-26 21:29:00 +00003644void RetainCountChecker::printState(raw_ostream &Out, ProgramStateRef State,
Jordy Rose910c4052011-09-02 06:44:22 +00003645 const char *NL, const char *Sep) const {
Jordy Rosedbd658e2011-08-28 19:11:56 +00003646
Jordan Rose166d5022012-11-02 01:54:06 +00003647 RefBindingsTy B = State->get<RefBindings>();
Jordy Rosedbd658e2011-08-28 19:11:56 +00003648
Ted Kremenek65a08922013-03-28 18:43:18 +00003649 if (B.isEmpty())
3650 return;
3651
3652 Out << Sep << NL;
Jordy Rosedbd658e2011-08-28 19:11:56 +00003653
Jordan Rose166d5022012-11-02 01:54:06 +00003654 for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Jordy Rosedbd658e2011-08-28 19:11:56 +00003655 Out << I->first << " : ";
3656 I->second.print(Out);
3657 Out << NL;
3658 }
Jordy Rosedbd658e2011-08-28 19:11:56 +00003659}
3660
3661//===----------------------------------------------------------------------===//
Jordy Rose910c4052011-09-02 06:44:22 +00003662// Checker registration.
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00003663//===----------------------------------------------------------------------===//
3664
Jordy Rose17a38e22011-09-02 05:55:19 +00003665void ento::registerRetainCountChecker(CheckerManager &Mgr) {
Jordy Rose910c4052011-09-02 06:44:22 +00003666 Mgr.registerChecker<RetainCountChecker>();
Jordy Rose17a38e22011-09-02 05:55:19 +00003667}
3668