blob: ab8acb18318628b34a6fc438bc53ee42de1ba605 [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"
Mike Stump1eb44332009-09-09 15:08:12 +000016#include "clang/AST/DeclObjC.h"
Ted Kremenekb2771592011-03-30 17:41:19 +000017#include "clang/AST/DeclCXX.h"
Ted Kremenek0b526b42010-02-18 00:05:58 +000018#include "clang/Basic/LangOptions.h"
19#include "clang/Basic/SourceManager.h"
Jordy Rose910c4052011-09-02 06:44:22 +000020#include "clang/Analysis/DomainSpecific/CocoaConventions.h"
Ted Kremenek4c42bb72011-11-14 21:59:21 +000021#include "clang/AST/ParentMap.h"
Jordy Rose910c4052011-09-02 06:44:22 +000022#include "clang/StaticAnalyzer/Core/Checker.h"
23#include "clang/StaticAnalyzer/Core/CheckerManager.h"
Ted Kremenek9b663712011-02-10 01:03:03 +000024#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
25#include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
Jordan Rosef540c542012-07-26 21:39:41 +000026#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
Jordy Rose910c4052011-09-02 06:44:22 +000027#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
Ted Kremenek18c66fd2011-08-15 22:09:50 +000028#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
Ted Kremenek9b663712011-02-10 01:03:03 +000029#include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000030#include "llvm/ADT/DenseMap.h"
31#include "llvm/ADT/FoldingSet.h"
Ted Kremenek6d348932008-10-21 15:53:15 +000032#include "llvm/ADT/ImmutableList.h"
Ted Kremenek0b526b42010-02-18 00:05:58 +000033#include "llvm/ADT/ImmutableMap.h"
Benjamin Kramer8fe83e12012-02-04 13:45:25 +000034#include "llvm/ADT/SmallString.h"
Ted Kremenek6ed9afc2008-05-16 18:33:44 +000035#include "llvm/ADT/STLExtras.h"
Ted Kremenek0b526b42010-02-18 00:05:58 +000036#include "llvm/ADT/StringExtras.h"
Chris Lattner5f9e2722011-07-23 10:55:15 +000037#include <cstdarg>
Ted Kremenek2fff37e2008-03-06 00:08:09 +000038
39using namespace clang;
Ted Kremenek9ef65372010-12-23 07:20:52 +000040using namespace ento;
Ted Kremeneka64e89b2010-01-27 06:13:48 +000041using llvm::StrInStrNoCase;
Ted Kremenek4c79e552008-11-05 16:54:44 +000042
Ted Kremenek05cbe1a2008-04-09 23:49:11 +000043//===----------------------------------------------------------------------===//
Ted Kremenek553cf182008-06-25 21:21:56 +000044// Primitives used for constructing summaries for function/method calls.
Ted Kremenek05cbe1a2008-04-09 23:49:11 +000045//===----------------------------------------------------------------------===//
46
Ted Kremenek553cf182008-06-25 21:21:56 +000047/// ArgEffect is used to summarize a function/method call's effect on a
48/// particular argument.
Jordy Rosebd85b132011-08-24 19:10:50 +000049enum ArgEffect { DoNothing, Autorelease, Dealloc, DecRef, DecRefMsg,
John McCallf85e1932011-06-15 23:02:42 +000050 DecRefBridgedTransfered,
Jordan Rose4531b7d2012-07-02 19:27:43 +000051 DecRefAndStopTracking, DecRefMsgAndStopTracking,
Jordy Rosebd85b132011-08-24 19:10:50 +000052 IncRefMsg, IncRef, MakeCollectable, MayEscape,
Jordan Rose29299c62012-06-27 00:51:18 +000053 NewAutoreleasePool, StopTracking };
Ted Kremenek553cf182008-06-25 21:21:56 +000054
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000055namespace llvm {
Ted Kremenekb77449c2009-05-03 05:20:50 +000056template <> struct FoldingSetTrait<ArgEffect> {
57static inline void Profile(const ArgEffect X, FoldingSetNodeID& ID) {
58 ID.AddInteger((unsigned) X);
59}
Ted Kremenek553cf182008-06-25 21:21:56 +000060};
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000061} // end llvm namespace
62
Ted Kremenekb77449c2009-05-03 05:20:50 +000063/// ArgEffects summarizes the effects of a function/method call on all of
64/// its arguments.
65typedef llvm::ImmutableMap<unsigned,ArgEffect> ArgEffects;
66
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000067namespace {
Ted Kremenek553cf182008-06-25 21:21:56 +000068
69/// RetEffect is used to summarize a function/method call's behavior with
Mike Stump1eb44332009-09-09 15:08:12 +000070/// respect to its return value.
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +000071class RetEffect {
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000072public:
Jordy Rose76c506f2011-08-21 21:58:18 +000073 enum Kind { NoRet, OwnedSymbol, OwnedAllocatedSymbol,
John McCallf85e1932011-06-15 23:02:42 +000074 NotOwnedSymbol, GCNotOwnedSymbol, ARCNotOwnedSymbol,
Ted Kremenek78a35a32009-05-12 20:06:54 +000075 OwnedWhenTrackedReceiver };
Mike Stump1eb44332009-09-09 15:08:12 +000076
77 enum ObjKind { CF, ObjC, AnyObj };
Ted Kremenek2d1652e2009-01-28 05:56:51 +000078
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000079private:
Ted Kremenek2d1652e2009-01-28 05:56:51 +000080 Kind K;
81 ObjKind O;
Ted Kremenek2d1652e2009-01-28 05:56:51 +000082
Jordy Rose76c506f2011-08-21 21:58:18 +000083 RetEffect(Kind k, ObjKind o = AnyObj) : K(k), O(o) {}
Mike Stump1eb44332009-09-09 15:08:12 +000084
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000085public:
Ted Kremenek2d1652e2009-01-28 05:56:51 +000086 Kind getKind() const { return K; }
87
88 ObjKind getObjKind() const { return O; }
Mike Stump1eb44332009-09-09 15:08:12 +000089
Ted Kremeneka8833552009-04-29 23:03:22 +000090 bool isOwned() const {
Ted Kremenek78a35a32009-05-12 20:06:54 +000091 return K == OwnedSymbol || K == OwnedAllocatedSymbol ||
92 K == OwnedWhenTrackedReceiver;
Ted Kremeneka8833552009-04-29 23:03:22 +000093 }
Mike Stump1eb44332009-09-09 15:08:12 +000094
Jordy Rose4df54fe2011-08-23 04:27:15 +000095 bool operator==(const RetEffect &Other) const {
96 return K == Other.K && O == Other.O;
97 }
98
Ted Kremenek78a35a32009-05-12 20:06:54 +000099 static RetEffect MakeOwnedWhenTrackedReceiver() {
100 return RetEffect(OwnedWhenTrackedReceiver, ObjC);
101 }
Mike Stump1eb44332009-09-09 15:08:12 +0000102
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000103 static RetEffect MakeOwned(ObjKind o, bool isAllocated = false) {
104 return RetEffect(isAllocated ? OwnedAllocatedSymbol : OwnedSymbol, o);
Mike Stump1eb44332009-09-09 15:08:12 +0000105 }
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000106 static RetEffect MakeNotOwned(ObjKind o) {
107 return RetEffect(NotOwnedSymbol, o);
Ted Kremeneke798e7c2009-04-27 19:14:45 +0000108 }
109 static RetEffect MakeGCNotOwned() {
110 return RetEffect(GCNotOwnedSymbol, ObjC);
111 }
John McCallf85e1932011-06-15 23:02:42 +0000112 static RetEffect MakeARCNotOwned() {
113 return RetEffect(ARCNotOwnedSymbol, ObjC);
114 }
Ted Kremenek553cf182008-06-25 21:21:56 +0000115 static RetEffect MakeNoRet() {
116 return RetEffect(NoRet);
Ted Kremeneka7344702008-06-23 18:02:52 +0000117 }
Jordy Roseef945882012-03-18 01:26:10 +0000118
119 void Profile(llvm::FoldingSetNodeID& ID) const {
120 ID.AddInteger((unsigned) K);
121 ID.AddInteger((unsigned) O);
122 }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000123};
Mike Stump1eb44332009-09-09 15:08:12 +0000124
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000125//===----------------------------------------------------------------------===//
126// Reference-counting logic (typestate + counts).
127//===----------------------------------------------------------------------===//
Mike Stump1eb44332009-09-09 15:08:12 +0000128
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000129class RefVal {
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000130public:
131 enum Kind {
132 Owned = 0, // Owning reference.
133 NotOwned, // Reference is not owned by still valid (not freed).
134 Released, // Object has been released.
135 ReturnedOwned, // Returned object passes ownership to caller.
136 ReturnedNotOwned, // Return object does not pass ownership to caller.
137 ERROR_START,
138 ErrorDeallocNotOwned, // -dealloc called on non-owned object.
139 ErrorDeallocGC, // Calling -dealloc with GC enabled.
140 ErrorUseAfterRelease, // Object used after released.
141 ErrorReleaseNotOwned, // Release of an object that was not owned.
142 ERROR_LEAK_START,
143 ErrorLeak, // A memory leak due to excessive reference counts.
144 ErrorLeakReturned, // A memory leak due to the returning method not having
145 // the correct naming conventions.
146 ErrorGCLeakReturned,
147 ErrorOverAutorelease,
148 ErrorReturnedNotOwned
149 };
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000150
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000151private:
152 Kind kind;
153 RetEffect::ObjKind okind;
154 unsigned Cnt;
155 unsigned ACnt;
156 QualType T;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000157
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000158 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, unsigned acnt, QualType t)
159 : kind(k), okind(o), Cnt(cnt), ACnt(acnt), T(t) {}
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000160
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000161public:
162 Kind getKind() const { return kind; }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000163
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000164 RetEffect::ObjKind getObjKind() const { return okind; }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000165
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000166 unsigned getCount() const { return Cnt; }
167 unsigned getAutoreleaseCount() const { return ACnt; }
168 unsigned getCombinedCounts() const { return Cnt + ACnt; }
169 void clearCounts() { Cnt = 0; ACnt = 0; }
170 void setCount(unsigned i) { Cnt = i; }
171 void setAutoreleaseCount(unsigned i) { ACnt = i; }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000172
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000173 QualType getType() const { return T; }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000174
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000175 bool isOwned() const {
176 return getKind() == Owned;
177 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000178
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000179 bool isNotOwned() const {
180 return getKind() == NotOwned;
181 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000182
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000183 bool isReturnedOwned() const {
184 return getKind() == ReturnedOwned;
185 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000186
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000187 bool isReturnedNotOwned() const {
188 return getKind() == ReturnedNotOwned;
189 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000190
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000191 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
192 unsigned Count = 1) {
193 return RefVal(Owned, o, Count, 0, t);
194 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000195
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000196 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
197 unsigned Count = 0) {
198 return RefVal(NotOwned, o, Count, 0, t);
199 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000200
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000201 // Comparison, profiling, and pretty-printing.
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000202
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000203 bool operator==(const RefVal& X) const {
204 return kind == X.kind && Cnt == X.Cnt && T == X.T && ACnt == X.ACnt;
205 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000206
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000207 RefVal operator-(size_t i) const {
208 return RefVal(getKind(), getObjKind(), getCount() - i,
209 getAutoreleaseCount(), getType());
210 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000211
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000212 RefVal operator+(size_t i) const {
213 return RefVal(getKind(), getObjKind(), getCount() + i,
214 getAutoreleaseCount(), getType());
215 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000216
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000217 RefVal operator^(Kind k) const {
218 return RefVal(k, getObjKind(), getCount(), getAutoreleaseCount(),
219 getType());
220 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000221
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000222 RefVal autorelease() const {
223 return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount()+1,
224 getType());
225 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000226
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000227 void Profile(llvm::FoldingSetNodeID& ID) const {
228 ID.AddInteger((unsigned) kind);
229 ID.AddInteger(Cnt);
230 ID.AddInteger(ACnt);
231 ID.Add(T);
232 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000233
Ted Kremenek9c378f72011-08-12 23:37:29 +0000234 void print(raw_ostream &Out) const;
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000235};
236
Ted Kremenek9c378f72011-08-12 23:37:29 +0000237void RefVal::print(raw_ostream &Out) const {
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000238 if (!T.isNull())
Jordy Rosedbd658e2011-08-28 19:11:56 +0000239 Out << "Tracked " << T.getAsString() << '/';
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000240
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000241 switch (getKind()) {
Jordy Rose910c4052011-09-02 06:44:22 +0000242 default: llvm_unreachable("Invalid RefVal kind");
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000243 case Owned: {
244 Out << "Owned";
245 unsigned cnt = getCount();
246 if (cnt) Out << " (+ " << cnt << ")";
247 break;
248 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000249
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000250 case NotOwned: {
251 Out << "NotOwned";
252 unsigned cnt = getCount();
253 if (cnt) Out << " (+ " << cnt << ")";
254 break;
255 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000256
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000257 case ReturnedOwned: {
258 Out << "ReturnedOwned";
259 unsigned cnt = getCount();
260 if (cnt) Out << " (+ " << cnt << ")";
261 break;
262 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000263
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000264 case ReturnedNotOwned: {
265 Out << "ReturnedNotOwned";
266 unsigned cnt = getCount();
267 if (cnt) Out << " (+ " << cnt << ")";
268 break;
269 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000270
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000271 case Released:
272 Out << "Released";
273 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000274
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000275 case ErrorDeallocGC:
276 Out << "-dealloc (GC)";
277 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000278
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000279 case ErrorDeallocNotOwned:
280 Out << "-dealloc (not-owned)";
281 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000282
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000283 case ErrorLeak:
284 Out << "Leaked";
285 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000286
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000287 case ErrorLeakReturned:
288 Out << "Leaked (Bad naming)";
289 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000290
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000291 case ErrorGCLeakReturned:
292 Out << "Leaked (GC-ed at return)";
293 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000294
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000295 case ErrorUseAfterRelease:
296 Out << "Use-After-Release [ERROR]";
297 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000298
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000299 case ErrorReleaseNotOwned:
300 Out << "Release of Not-Owned [ERROR]";
301 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000302
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000303 case RefVal::ErrorOverAutorelease:
304 Out << "Over autoreleased";
305 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000306
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000307 case RefVal::ErrorReturnedNotOwned:
308 Out << "Non-owned object returned instead of owned";
309 break;
310 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000311
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000312 if (ACnt) {
313 Out << " [ARC +" << ACnt << ']';
314 }
315}
316} //end anonymous namespace
317
318//===----------------------------------------------------------------------===//
319// RefBindings - State used to track object reference counts.
320//===----------------------------------------------------------------------===//
321
322typedef llvm::ImmutableMap<SymbolRef, RefVal> RefBindings;
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000323
324namespace clang {
Ted Kremenek9ef65372010-12-23 07:20:52 +0000325namespace ento {
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000326template<>
327struct ProgramStateTrait<RefBindings>
328 : public ProgramStatePartialTrait<RefBindings> {
329 static void *GDMIndex() {
330 static int RefBIndex = 0;
331 return &RefBIndex;
332 }
333};
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000334}
Argyrios Kyrtzidis5a4f98f2010-12-22 18:53:20 +0000335}
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000336
Anna Zaks8d6b43c2012-08-14 00:36:15 +0000337static inline const RefVal *getRefBinding(ProgramStateRef State,
338 SymbolRef Sym) {
339 return State->get<RefBindings>(Sym);
340}
341
342static inline ProgramStateRef setRefBinding(ProgramStateRef State,
343 SymbolRef Sym, RefVal Val) {
344 return State->set<RefBindings>(Sym, Val);
345}
346
347static ProgramStateRef removeRefBinding(ProgramStateRef State, SymbolRef Sym) {
348 return State->remove<RefBindings>(Sym);
349}
350
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000351//===----------------------------------------------------------------------===//
Jordy Rose910c4052011-09-02 06:44:22 +0000352// Function/Method behavior summaries.
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000353//===----------------------------------------------------------------------===//
354
355namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000356class RetainSummary {
Jordy Roseef945882012-03-18 01:26:10 +0000357 /// Args - a map of (index, ArgEffect) pairs, where index
Ted Kremenek1bffd742008-05-06 15:44:25 +0000358 /// specifies the argument (starting from 0). This can be sparsely
359 /// populated; arguments with no entry in Args use 'DefaultArgEffect'.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000360 ArgEffects Args;
Mike Stump1eb44332009-09-09 15:08:12 +0000361
Ted Kremenek1bffd742008-05-06 15:44:25 +0000362 /// DefaultArgEffect - The default ArgEffect to apply to arguments that
363 /// do not have an entry in Args.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000364 ArgEffect DefaultArgEffect;
Mike Stump1eb44332009-09-09 15:08:12 +0000365
Ted Kremenek553cf182008-06-25 21:21:56 +0000366 /// Receiver - If this summary applies to an Objective-C message expression,
367 /// this is the effect applied to the state of the receiver.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000368 ArgEffect Receiver;
Mike Stump1eb44332009-09-09 15:08:12 +0000369
Ted Kremenek553cf182008-06-25 21:21:56 +0000370 /// Ret - The effect on the return value. Used to indicate if the
Jordy Rose76c506f2011-08-21 21:58:18 +0000371 /// function/method call returns a new tracked symbol.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000372 RetEffect Ret;
Mike Stump1eb44332009-09-09 15:08:12 +0000373
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000374public:
Ted Kremenekb77449c2009-05-03 05:20:50 +0000375 RetainSummary(ArgEffects A, RetEffect R, ArgEffect defaultEff,
Jordy Rosee62e87b2011-08-20 20:55:40 +0000376 ArgEffect ReceiverEff)
377 : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000378
Ted Kremenek553cf182008-06-25 21:21:56 +0000379 /// getArg - Return the argument effect on the argument specified by
380 /// idx (starting from 0).
Ted Kremenek1ac08d62008-03-11 17:48:22 +0000381 ArgEffect getArg(unsigned idx) const {
Ted Kremenekb77449c2009-05-03 05:20:50 +0000382 if (const ArgEffect *AE = Args.lookup(idx))
383 return *AE;
Mike Stump1eb44332009-09-09 15:08:12 +0000384
Ted Kremenek1bffd742008-05-06 15:44:25 +0000385 return DefaultArgEffect;
Ted Kremenek1ac08d62008-03-11 17:48:22 +0000386 }
Ted Kremenek11fe1752011-01-27 18:43:03 +0000387
388 void addArg(ArgEffects::Factory &af, unsigned idx, ArgEffect e) {
389 Args = af.add(Args, idx, e);
390 }
Mike Stump1eb44332009-09-09 15:08:12 +0000391
Ted Kremenek885c27b2009-05-04 05:31:22 +0000392 /// setDefaultArgEffect - Set the default argument effect.
393 void setDefaultArgEffect(ArgEffect E) {
394 DefaultArgEffect = E;
395 }
Mike Stump1eb44332009-09-09 15:08:12 +0000396
Ted Kremenek553cf182008-06-25 21:21:56 +0000397 /// getRetEffect - Returns the effect on the return value of the call.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000398 RetEffect getRetEffect() const { return Ret; }
Mike Stump1eb44332009-09-09 15:08:12 +0000399
Ted Kremenek885c27b2009-05-04 05:31:22 +0000400 /// setRetEffect - Set the effect of the return value of the call.
401 void setRetEffect(RetEffect E) { Ret = E; }
Mike Stump1eb44332009-09-09 15:08:12 +0000402
Ted Kremenek12b94342011-01-27 06:54:14 +0000403
404 /// Sets the effect on the receiver of the message.
405 void setReceiverEffect(ArgEffect e) { Receiver = e; }
406
Ted Kremenek553cf182008-06-25 21:21:56 +0000407 /// getReceiverEffect - Returns the effect on the receiver of the call.
408 /// This is only meaningful if the summary applies to an ObjCMessageExpr*.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000409 ArgEffect getReceiverEffect() const { return Receiver; }
Jordy Rose4df54fe2011-08-23 04:27:15 +0000410
411 /// Test if two retain summaries are identical. Note that merely equivalent
412 /// summaries are not necessarily identical (for example, if an explicit
413 /// argument effect matches the default effect).
414 bool operator==(const RetainSummary &Other) const {
415 return Args == Other.Args && DefaultArgEffect == Other.DefaultArgEffect &&
416 Receiver == Other.Receiver && Ret == Other.Ret;
417 }
Jordy Roseef945882012-03-18 01:26:10 +0000418
419 /// Profile this summary for inclusion in a FoldingSet.
420 void Profile(llvm::FoldingSetNodeID& ID) const {
421 ID.Add(Args);
422 ID.Add(DefaultArgEffect);
423 ID.Add(Receiver);
424 ID.Add(Ret);
425 }
426
427 /// A retain summary is simple if it has no ArgEffects other than the default.
428 bool isSimple() const {
429 return Args.isEmpty();
430 }
Jordan Rose4531b7d2012-07-02 19:27:43 +0000431
432private:
433 ArgEffects getArgEffects() const { return Args; }
434 ArgEffect getDefaultArgEffect() const { return DefaultArgEffect; }
435
436 friend class RetainSummaryManager;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000437};
Ted Kremenek4f22a782008-06-23 23:30:29 +0000438} // end anonymous namespace
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000439
Ted Kremenek553cf182008-06-25 21:21:56 +0000440//===----------------------------------------------------------------------===//
441// Data structures for constructing summaries.
442//===----------------------------------------------------------------------===//
Ted Kremenek53301ba2008-06-24 03:49:48 +0000443
Ted Kremenek553cf182008-06-25 21:21:56 +0000444namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000445class ObjCSummaryKey {
Ted Kremenek553cf182008-06-25 21:21:56 +0000446 IdentifierInfo* II;
447 Selector S;
Mike Stump1eb44332009-09-09 15:08:12 +0000448public:
Ted Kremenek553cf182008-06-25 21:21:56 +0000449 ObjCSummaryKey(IdentifierInfo* ii, Selector s)
450 : II(ii), S(s) {}
451
Ted Kremenek9c378f72011-08-12 23:37:29 +0000452 ObjCSummaryKey(const ObjCInterfaceDecl *d, Selector s)
Ted Kremenek553cf182008-06-25 21:21:56 +0000453 : II(d ? d->getIdentifier() : 0), S(s) {}
Ted Kremenek70b6a832009-05-13 18:16:01 +0000454
Ted Kremenek553cf182008-06-25 21:21:56 +0000455 ObjCSummaryKey(Selector s)
456 : II(0), S(s) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000457
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000458 IdentifierInfo *getIdentifier() const { return II; }
Ted Kremenek553cf182008-06-25 21:21:56 +0000459 Selector getSelector() const { return S; }
460};
Ted Kremenek4f22a782008-06-23 23:30:29 +0000461}
462
463namespace llvm {
Ted Kremenek553cf182008-06-25 21:21:56 +0000464template <> struct DenseMapInfo<ObjCSummaryKey> {
465 static inline ObjCSummaryKey getEmptyKey() {
466 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
467 DenseMapInfo<Selector>::getEmptyKey());
468 }
Mike Stump1eb44332009-09-09 15:08:12 +0000469
Ted Kremenek553cf182008-06-25 21:21:56 +0000470 static inline ObjCSummaryKey getTombstoneKey() {
471 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
Mike Stump1eb44332009-09-09 15:08:12 +0000472 DenseMapInfo<Selector>::getTombstoneKey());
Ted Kremenek553cf182008-06-25 21:21:56 +0000473 }
Mike Stump1eb44332009-09-09 15:08:12 +0000474
Ted Kremenek553cf182008-06-25 21:21:56 +0000475 static unsigned getHashValue(const ObjCSummaryKey &V) {
Benjamin Kramer28b23072012-05-27 13:28:44 +0000476 typedef std::pair<IdentifierInfo*, Selector> PairTy;
477 return DenseMapInfo<PairTy>::getHashValue(PairTy(V.getIdentifier(),
478 V.getSelector()));
Ted Kremenek553cf182008-06-25 21:21:56 +0000479 }
Mike Stump1eb44332009-09-09 15:08:12 +0000480
Ted Kremenek553cf182008-06-25 21:21:56 +0000481 static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
Benjamin Kramer28b23072012-05-27 13:28:44 +0000482 return LHS.getIdentifier() == RHS.getIdentifier() &&
483 LHS.getSelector() == RHS.getSelector();
Ted Kremenek553cf182008-06-25 21:21:56 +0000484 }
Mike Stump1eb44332009-09-09 15:08:12 +0000485
Ted Kremenek553cf182008-06-25 21:21:56 +0000486};
Chris Lattner06159e82009-12-15 07:26:51 +0000487template <>
488struct isPodLike<ObjCSummaryKey> { static const bool value = true; };
Ted Kremenek4f22a782008-06-23 23:30:29 +0000489} // end llvm namespace
Mike Stump1eb44332009-09-09 15:08:12 +0000490
Ted Kremenek4f22a782008-06-23 23:30:29 +0000491namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000492class ObjCSummaryCache {
Ted Kremenek93edbc52011-10-05 23:54:29 +0000493 typedef llvm::DenseMap<ObjCSummaryKey, const RetainSummary *> MapTy;
Ted Kremenek553cf182008-06-25 21:21:56 +0000494 MapTy M;
495public:
496 ObjCSummaryCache() {}
Mike Stump1eb44332009-09-09 15:08:12 +0000497
Ted Kremenek93edbc52011-10-05 23:54:29 +0000498 const RetainSummary * find(const ObjCInterfaceDecl *D, Selector S) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000499 // Do a lookup with the (D,S) pair. If we find a match return
500 // the iterator.
501 ObjCSummaryKey K(D, S);
502 MapTy::iterator I = M.find(K);
Mike Stump1eb44332009-09-09 15:08:12 +0000503
Jordan Rose4531b7d2012-07-02 19:27:43 +0000504 if (I != M.end())
Ted Kremenek614cc542009-07-21 23:27:57 +0000505 return I->second;
Jordan Rose4531b7d2012-07-02 19:27:43 +0000506 if (!D)
507 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +0000508
Ted Kremenek553cf182008-06-25 21:21:56 +0000509 // Walk the super chain. If we find a hit with a parent, we'll end
510 // up returning that summary. We actually allow that key (null,S), as
511 // we cache summaries for the null ObjCInterfaceDecl* to allow us to
512 // generate initial summaries without having to worry about NSObject
513 // being declared.
514 // FIXME: We may change this at some point.
Ted Kremenek9c378f72011-08-12 23:37:29 +0000515 for (ObjCInterfaceDecl *C=D->getSuperClass() ;; C=C->getSuperClass()) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000516 if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
517 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000518
Ted Kremenek553cf182008-06-25 21:21:56 +0000519 if (!C)
Ted Kremenek614cc542009-07-21 23:27:57 +0000520 return NULL;
Ted Kremenek553cf182008-06-25 21:21:56 +0000521 }
Mike Stump1eb44332009-09-09 15:08:12 +0000522
523 // Cache the summary with original key to make the next lookup faster
Ted Kremenek553cf182008-06-25 21:21:56 +0000524 // and return the iterator.
Ted Kremenek93edbc52011-10-05 23:54:29 +0000525 const RetainSummary *Summ = I->second;
Ted Kremenek614cc542009-07-21 23:27:57 +0000526 M[K] = Summ;
527 return Summ;
Ted Kremenek553cf182008-06-25 21:21:56 +0000528 }
Mike Stump1eb44332009-09-09 15:08:12 +0000529
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000530 const RetainSummary *find(IdentifierInfo* II, Selector S) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000531 // FIXME: Class method lookup. Right now we dont' have a good way
532 // of going between IdentifierInfo* and the class hierarchy.
Ted Kremenek614cc542009-07-21 23:27:57 +0000533 MapTy::iterator I = M.find(ObjCSummaryKey(II, S));
Mike Stump1eb44332009-09-09 15:08:12 +0000534
Ted Kremenek614cc542009-07-21 23:27:57 +0000535 if (I == M.end())
536 I = M.find(ObjCSummaryKey(S));
Mike Stump1eb44332009-09-09 15:08:12 +0000537
Ted Kremenek614cc542009-07-21 23:27:57 +0000538 return I == M.end() ? NULL : I->second;
Ted Kremenek553cf182008-06-25 21:21:56 +0000539 }
Mike Stump1eb44332009-09-09 15:08:12 +0000540
Ted Kremenek93edbc52011-10-05 23:54:29 +0000541 const RetainSummary *& operator[](ObjCSummaryKey K) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000542 return M[K];
543 }
Mike Stump1eb44332009-09-09 15:08:12 +0000544
Ted Kremenek93edbc52011-10-05 23:54:29 +0000545 const RetainSummary *& operator[](Selector S) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000546 return M[ ObjCSummaryKey(S) ];
547 }
Mike Stump1eb44332009-09-09 15:08:12 +0000548};
Ted Kremenek553cf182008-06-25 21:21:56 +0000549} // end anonymous namespace
550
551//===----------------------------------------------------------------------===//
552// Data structures for managing collections of summaries.
553//===----------------------------------------------------------------------===//
554
555namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000556class RetainSummaryManager {
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000557
558 //==-----------------------------------------------------------------==//
559 // Typedefs.
560 //==-----------------------------------------------------------------==//
Mike Stump1eb44332009-09-09 15:08:12 +0000561
Ted Kremenek93edbc52011-10-05 23:54:29 +0000562 typedef llvm::DenseMap<const FunctionDecl*, const RetainSummary *>
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000563 FuncSummariesTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000564
Ted Kremenek4f22a782008-06-23 23:30:29 +0000565 typedef ObjCSummaryCache ObjCMethodSummariesTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000566
Jordy Roseef945882012-03-18 01:26:10 +0000567 typedef llvm::FoldingSetNodeWrapper<RetainSummary> CachedSummaryNode;
568
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000569 //==-----------------------------------------------------------------==//
570 // Data.
571 //==-----------------------------------------------------------------==//
Mike Stump1eb44332009-09-09 15:08:12 +0000572
Ted Kremenek553cf182008-06-25 21:21:56 +0000573 /// Ctx - The ASTContext object for the analyzed ASTs.
Ted Kremenek9c378f72011-08-12 23:37:29 +0000574 ASTContext &Ctx;
Ted Kremenek179064e2008-07-01 17:21:27 +0000575
Ted Kremenek553cf182008-06-25 21:21:56 +0000576 /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
Ted Kremenek377e2302008-04-29 05:33:51 +0000577 const bool GCEnabled;
Mike Stump1eb44332009-09-09 15:08:12 +0000578
John McCallf85e1932011-06-15 23:02:42 +0000579 /// Records whether or not the analyzed code runs in ARC mode.
580 const bool ARCEnabled;
581
Ted Kremenek553cf182008-06-25 21:21:56 +0000582 /// FuncSummaries - A map from FunctionDecls to summaries.
Mike Stump1eb44332009-09-09 15:08:12 +0000583 FuncSummariesTy FuncSummaries;
584
Ted Kremenek553cf182008-06-25 21:21:56 +0000585 /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
586 /// to summaries.
Ted Kremenek1f180c32008-06-23 22:21:20 +0000587 ObjCMethodSummariesTy ObjCClassMethodSummaries;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000588
Ted Kremenek553cf182008-06-25 21:21:56 +0000589 /// ObjCMethodSummaries - A map from selectors to summaries.
Ted Kremenek1f180c32008-06-23 22:21:20 +0000590 ObjCMethodSummariesTy ObjCMethodSummaries;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000591
Ted Kremenek553cf182008-06-25 21:21:56 +0000592 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
593 /// and all other data used by the checker.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000594 llvm::BumpPtrAllocator BPAlloc;
Mike Stump1eb44332009-09-09 15:08:12 +0000595
Ted Kremenekb77449c2009-05-03 05:20:50 +0000596 /// AF - A factory for ArgEffects objects.
Mike Stump1eb44332009-09-09 15:08:12 +0000597 ArgEffects::Factory AF;
598
Ted Kremenek553cf182008-06-25 21:21:56 +0000599 /// ScratchArgs - A holding buffer for construct ArgEffects.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000600 ArgEffects ScratchArgs;
Mike Stump1eb44332009-09-09 15:08:12 +0000601
Ted Kremenekec315332009-05-07 23:40:42 +0000602 /// ObjCAllocRetE - Default return effect for methods returning Objective-C
603 /// objects.
604 RetEffect ObjCAllocRetE;
Ted Kremenek547d4952009-06-05 23:18:01 +0000605
Mike Stump1eb44332009-09-09 15:08:12 +0000606 /// ObjCInitRetE - Default return effect for init methods returning
Ted Kremenekac02f202009-08-20 05:13:36 +0000607 /// Objective-C objects.
Ted Kremenek547d4952009-06-05 23:18:01 +0000608 RetEffect ObjCInitRetE;
Mike Stump1eb44332009-09-09 15:08:12 +0000609
Jordy Roseef945882012-03-18 01:26:10 +0000610 /// SimpleSummaries - Used for uniquing summaries that don't have special
611 /// effects.
612 llvm::FoldingSet<CachedSummaryNode> SimpleSummaries;
Mike Stump1eb44332009-09-09 15:08:12 +0000613
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000614 //==-----------------------------------------------------------------==//
615 // Methods.
616 //==-----------------------------------------------------------------==//
Mike Stump1eb44332009-09-09 15:08:12 +0000617
Ted Kremenek553cf182008-06-25 21:21:56 +0000618 /// getArgEffects - Returns a persistent ArgEffects object based on the
619 /// data in ScratchArgs.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000620 ArgEffects getArgEffects();
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000621
Mike Stump1eb44332009-09-09 15:08:12 +0000622 enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
Ted Kremenek93edbc52011-10-05 23:54:29 +0000623
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000624 const RetainSummary *getUnarySummary(const FunctionType* FT,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000625 UnaryFuncKind func);
Mike Stump1eb44332009-09-09 15:08:12 +0000626
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000627 const RetainSummary *getCFSummaryCreateRule(const FunctionDecl *FD);
628 const RetainSummary *getCFSummaryGetRule(const FunctionDecl *FD);
629 const RetainSummary *getCFCreateGetRuleSummary(const FunctionDecl *FD);
Mike Stump1eb44332009-09-09 15:08:12 +0000630
Jordy Roseef945882012-03-18 01:26:10 +0000631 const RetainSummary *getPersistentSummary(const RetainSummary &OldSumm);
Ted Kremenek706522f2008-10-29 04:07:07 +0000632
Jordy Roseef945882012-03-18 01:26:10 +0000633 const RetainSummary *getPersistentSummary(RetEffect RetEff,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000634 ArgEffect ReceiverEff = DoNothing,
635 ArgEffect DefaultEff = MayEscape) {
Jordy Roseef945882012-03-18 01:26:10 +0000636 RetainSummary Summ(getArgEffects(), RetEff, DefaultEff, ReceiverEff);
637 return getPersistentSummary(Summ);
638 }
639
Ted Kremenekc91fdf62012-05-08 00:12:09 +0000640 const RetainSummary *getDoNothingSummary() {
641 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
642 }
643
Jordy Roseef945882012-03-18 01:26:10 +0000644 const RetainSummary *getDefaultSummary() {
645 return getPersistentSummary(RetEffect::MakeNoRet(),
646 DoNothing, MayEscape);
Ted Kremenek9c32d082008-05-06 00:30:21 +0000647 }
Mike Stump1eb44332009-09-09 15:08:12 +0000648
Ted Kremenek93edbc52011-10-05 23:54:29 +0000649 const RetainSummary *getPersistentStopSummary() {
Jordy Roseef945882012-03-18 01:26:10 +0000650 return getPersistentSummary(RetEffect::MakeNoRet(),
651 StopTracking, StopTracking);
Mike Stump1eb44332009-09-09 15:08:12 +0000652 }
Ted Kremenekb3095252008-05-06 04:20:12 +0000653
Ted Kremenek1f180c32008-06-23 22:21:20 +0000654 void InitializeClassMethodSummaries();
655 void InitializeMethodSummaries();
Ted Kremenek896cd9d2008-10-23 01:56:15 +0000656private:
Ted Kremenek93edbc52011-10-05 23:54:29 +0000657 void addNSObjectClsMethSummary(Selector S, const RetainSummary *Summ) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000658 ObjCClassMethodSummaries[S] = Summ;
659 }
Mike Stump1eb44332009-09-09 15:08:12 +0000660
Ted Kremenek93edbc52011-10-05 23:54:29 +0000661 void addNSObjectMethSummary(Selector S, const RetainSummary *Summ) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000662 ObjCMethodSummaries[S] = Summ;
663 }
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +0000664
Ted Kremeneka9797122012-02-18 21:37:48 +0000665 void addClassMethSummary(const char* Cls, const char* name,
666 const RetainSummary *Summ, bool isNullary = true) {
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +0000667 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
Ted Kremeneka9797122012-02-18 21:37:48 +0000668 Selector S = isNullary ? GetNullarySelector(name, Ctx)
669 : GetUnarySelector(name, Ctx);
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +0000670 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
671 }
Mike Stump1eb44332009-09-09 15:08:12 +0000672
Ted Kremenek6c4becb2009-02-25 02:54:57 +0000673 void addInstMethSummary(const char* Cls, const char* nullaryName,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000674 const RetainSummary *Summ) {
Ted Kremenek6c4becb2009-02-25 02:54:57 +0000675 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
676 Selector S = GetNullarySelector(nullaryName, Ctx);
677 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
678 }
Mike Stump1eb44332009-09-09 15:08:12 +0000679
Ted Kremenekde4d5332009-04-24 17:50:11 +0000680 Selector generateSelector(va_list argp) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000681 SmallVector<IdentifierInfo*, 10> II;
Ted Kremenekde4d5332009-04-24 17:50:11 +0000682
Ted Kremenek9e476de2008-08-12 18:30:56 +0000683 while (const char* s = va_arg(argp, const char*))
684 II.push_back(&Ctx.Idents.get(s));
Ted Kremenekde4d5332009-04-24 17:50:11 +0000685
Mike Stump1eb44332009-09-09 15:08:12 +0000686 return Ctx.Selectors.getSelector(II.size(), &II[0]);
Ted Kremenekde4d5332009-04-24 17:50:11 +0000687 }
Mike Stump1eb44332009-09-09 15:08:12 +0000688
Ted Kremenekde4d5332009-04-24 17:50:11 +0000689 void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy& Summaries,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000690 const RetainSummary * Summ, va_list argp) {
Ted Kremenekde4d5332009-04-24 17:50:11 +0000691 Selector S = generateSelector(argp);
692 Summaries[ObjCSummaryKey(ClsII, S)] = Summ;
Ted Kremenek70a733e2008-07-18 17:24:20 +0000693 }
Mike Stump1eb44332009-09-09 15:08:12 +0000694
Ted Kremenek93edbc52011-10-05 23:54:29 +0000695 void addInstMethSummary(const char* Cls, const RetainSummary * Summ, ...) {
Ted Kremenekaf9dc272008-08-12 18:48:50 +0000696 va_list argp;
697 va_start(argp, Summ);
Ted Kremenekde4d5332009-04-24 17:50:11 +0000698 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Mike Stump1eb44332009-09-09 15:08:12 +0000699 va_end(argp);
Ted Kremenekaf9dc272008-08-12 18:48:50 +0000700 }
Mike Stump1eb44332009-09-09 15:08:12 +0000701
Ted Kremenek93edbc52011-10-05 23:54:29 +0000702 void addClsMethSummary(const char* Cls, const RetainSummary * Summ, ...) {
Ted Kremenekde4d5332009-04-24 17:50:11 +0000703 va_list argp;
704 va_start(argp, Summ);
705 addMethodSummary(&Ctx.Idents.get(Cls),ObjCClassMethodSummaries, Summ, argp);
706 va_end(argp);
707 }
Mike Stump1eb44332009-09-09 15:08:12 +0000708
Ted Kremenek93edbc52011-10-05 23:54:29 +0000709 void addClsMethSummary(IdentifierInfo *II, const RetainSummary * Summ, ...) {
Ted Kremenekde4d5332009-04-24 17:50:11 +0000710 va_list argp;
711 va_start(argp, Summ);
712 addMethodSummary(II, ObjCClassMethodSummaries, Summ, argp);
713 va_end(argp);
714 }
715
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000716public:
Mike Stump1eb44332009-09-09 15:08:12 +0000717
Ted Kremenek9c378f72011-08-12 23:37:29 +0000718 RetainSummaryManager(ASTContext &ctx, bool gcenabled, bool usesARC)
Ted Kremenek179064e2008-07-01 17:21:27 +0000719 : Ctx(ctx),
John McCallf85e1932011-06-15 23:02:42 +0000720 GCEnabled(gcenabled),
721 ARCEnabled(usesARC),
722 AF(BPAlloc), ScratchArgs(AF.getEmptyMap()),
723 ObjCAllocRetE(gcenabled
724 ? RetEffect::MakeGCNotOwned()
725 : (usesARC ? RetEffect::MakeARCNotOwned()
726 : RetEffect::MakeOwned(RetEffect::ObjC, true))),
727 ObjCInitRetE(gcenabled
728 ? RetEffect::MakeGCNotOwned()
729 : (usesARC ? RetEffect::MakeARCNotOwned()
Jordy Roseef945882012-03-18 01:26:10 +0000730 : RetEffect::MakeOwnedWhenTrackedReceiver())) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000731 InitializeClassMethodSummaries();
732 InitializeMethodSummaries();
733 }
Mike Stump1eb44332009-09-09 15:08:12 +0000734
Jordan Rose4531b7d2012-07-02 19:27:43 +0000735 const RetainSummary *getSummary(const CallEvent &Call,
736 ProgramStateRef State = 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000737
Jordan Rose4531b7d2012-07-02 19:27:43 +0000738 const RetainSummary *getFunctionSummary(const FunctionDecl *FD);
739
740 const RetainSummary *getMethodSummary(Selector S, const ObjCInterfaceDecl *ID,
Jordy Rosef3aae582012-03-17 21:13:07 +0000741 const ObjCMethodDecl *MD,
742 QualType RetTy,
743 ObjCMethodSummariesTy &CachedSummaries);
744
Jordan Rosecde8cdb2012-07-02 19:27:56 +0000745 const RetainSummary *getInstanceMethodSummary(const ObjCMethodCall &M,
Jordan Rose4531b7d2012-07-02 19:27:43 +0000746 ProgramStateRef State);
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000747
Jordan Rosecde8cdb2012-07-02 19:27:56 +0000748 const RetainSummary *getClassMethodSummary(const ObjCMethodCall &M) {
Jordan Rose4531b7d2012-07-02 19:27:43 +0000749 assert(!M.isInstanceMessage());
750 const ObjCInterfaceDecl *Class = M.getReceiverInterface();
Mike Stump1eb44332009-09-09 15:08:12 +0000751
Jordan Rose4531b7d2012-07-02 19:27:43 +0000752 return getMethodSummary(M.getSelector(), Class, M.getDecl(),
753 M.getResultType(), ObjCClassMethodSummaries);
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +0000754 }
Ted Kremenek552333c2009-04-29 17:17:48 +0000755
756 /// getMethodSummary - This version of getMethodSummary is used to query
757 /// the summary for the current method being analyzed.
Ted Kremenek93edbc52011-10-05 23:54:29 +0000758 const RetainSummary *getMethodSummary(const ObjCMethodDecl *MD) {
Ted Kremeneka8833552009-04-29 23:03:22 +0000759 const ObjCInterfaceDecl *ID = MD->getClassInterface();
Ted Kremenek70a65762009-04-30 05:41:14 +0000760 Selector S = MD->getSelector();
Ted Kremenek552333c2009-04-29 17:17:48 +0000761 QualType ResultTy = MD->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +0000762
Jordy Rosef3aae582012-03-17 21:13:07 +0000763 ObjCMethodSummariesTy *CachedSummaries;
Ted Kremenek552333c2009-04-29 17:17:48 +0000764 if (MD->isInstanceMethod())
Jordy Rosef3aae582012-03-17 21:13:07 +0000765 CachedSummaries = &ObjCMethodSummaries;
Ted Kremenek552333c2009-04-29 17:17:48 +0000766 else
Jordy Rosef3aae582012-03-17 21:13:07 +0000767 CachedSummaries = &ObjCClassMethodSummaries;
768
Jordan Rose4531b7d2012-07-02 19:27:43 +0000769 return getMethodSummary(S, ID, MD, ResultTy, *CachedSummaries);
Ted Kremenek552333c2009-04-29 17:17:48 +0000770 }
Mike Stump1eb44332009-09-09 15:08:12 +0000771
Jordy Rosef3aae582012-03-17 21:13:07 +0000772 const RetainSummary *getStandardMethodSummary(const ObjCMethodDecl *MD,
Jordan Rose4531b7d2012-07-02 19:27:43 +0000773 Selector S, QualType RetTy);
Ted Kremeneka8833552009-04-29 23:03:22 +0000774
Ted Kremenek93edbc52011-10-05 23:54:29 +0000775 void updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenek4dd8fb42009-05-09 02:58:13 +0000776 const ObjCMethodDecl *MD);
777
Ted Kremenek93edbc52011-10-05 23:54:29 +0000778 void updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenek4dd8fb42009-05-09 02:58:13 +0000779 const FunctionDecl *FD);
780
Jordan Rose4531b7d2012-07-02 19:27:43 +0000781 void updateSummaryForCall(const RetainSummary *&Summ,
782 const CallEvent &Call);
783
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000784 bool isGCEnabled() const { return GCEnabled; }
Mike Stump1eb44332009-09-09 15:08:12 +0000785
John McCallf85e1932011-06-15 23:02:42 +0000786 bool isARCEnabled() const { return ARCEnabled; }
787
788 bool isARCorGCEnabled() const { return GCEnabled || ARCEnabled; }
Jordan Rose4531b7d2012-07-02 19:27:43 +0000789
790 RetEffect getObjAllocRetEffect() const { return ObjCAllocRetE; }
791
792 friend class RetainSummaryTemplate;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000793};
Mike Stump1eb44332009-09-09 15:08:12 +0000794
Jordy Rose0fe62f82011-08-24 09:02:37 +0000795// Used to avoid allocating long-term (BPAlloc'd) memory for default retain
796// summaries. If a function or method looks like it has a default summary, but
797// it has annotations, the annotations are added to the stack-based template
798// and then copied into managed memory.
799class RetainSummaryTemplate {
800 RetainSummaryManager &Manager;
Ted Kremenek93edbc52011-10-05 23:54:29 +0000801 const RetainSummary *&RealSummary;
Jordy Rose0fe62f82011-08-24 09:02:37 +0000802 RetainSummary ScratchSummary;
803 bool Accessed;
804public:
Jordan Rose4531b7d2012-07-02 19:27:43 +0000805 RetainSummaryTemplate(const RetainSummary *&real, RetainSummaryManager &mgr)
806 : Manager(mgr), RealSummary(real), ScratchSummary(*real), Accessed(false) {}
Jordy Rose0fe62f82011-08-24 09:02:37 +0000807
808 ~RetainSummaryTemplate() {
Ted Kremenek93edbc52011-10-05 23:54:29 +0000809 if (Accessed)
Jordy Roseef945882012-03-18 01:26:10 +0000810 RealSummary = Manager.getPersistentSummary(ScratchSummary);
Jordy Rose0fe62f82011-08-24 09:02:37 +0000811 }
812
813 RetainSummary &operator*() {
814 Accessed = true;
Ted Kremenek93edbc52011-10-05 23:54:29 +0000815 return ScratchSummary;
Jordy Rose0fe62f82011-08-24 09:02:37 +0000816 }
817
818 RetainSummary *operator->() {
819 Accessed = true;
Ted Kremenek93edbc52011-10-05 23:54:29 +0000820 return &ScratchSummary;
Jordy Rose0fe62f82011-08-24 09:02:37 +0000821 }
822};
823
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000824} // end anonymous namespace
825
826//===----------------------------------------------------------------------===//
827// Implementation of checker data structures.
828//===----------------------------------------------------------------------===//
829
Ted Kremenekb77449c2009-05-03 05:20:50 +0000830ArgEffects RetainSummaryManager::getArgEffects() {
831 ArgEffects AE = ScratchArgs;
Ted Kremenek3baf6722010-11-24 00:54:37 +0000832 ScratchArgs = AF.getEmptyMap();
Ted Kremenekb77449c2009-05-03 05:20:50 +0000833 return AE;
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000834}
835
Ted Kremenek93edbc52011-10-05 23:54:29 +0000836const RetainSummary *
Jordy Roseef945882012-03-18 01:26:10 +0000837RetainSummaryManager::getPersistentSummary(const RetainSummary &OldSumm) {
838 // Unique "simple" summaries -- those without ArgEffects.
839 if (OldSumm.isSimple()) {
840 llvm::FoldingSetNodeID ID;
841 OldSumm.Profile(ID);
842
843 void *Pos;
844 CachedSummaryNode *N = SimpleSummaries.FindNodeOrInsertPos(ID, Pos);
845
846 if (!N) {
847 N = (CachedSummaryNode *) BPAlloc.Allocate<CachedSummaryNode>();
848 new (N) CachedSummaryNode(OldSumm);
849 SimpleSummaries.InsertNode(N, Pos);
850 }
851
852 return &N->getValue();
853 }
854
Ted Kremenek93edbc52011-10-05 23:54:29 +0000855 RetainSummary *Summ = (RetainSummary *) BPAlloc.Allocate<RetainSummary>();
Jordy Roseef945882012-03-18 01:26:10 +0000856 new (Summ) RetainSummary(OldSumm);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000857 return Summ;
858}
859
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000860//===----------------------------------------------------------------------===//
861// Summary creation for functions (largely uses of Core Foundation).
862//===----------------------------------------------------------------------===//
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000863
Ted Kremenek9c378f72011-08-12 23:37:29 +0000864static bool isRetain(const FunctionDecl *FD, StringRef FName) {
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000865 return FName.endswith("Retain");
Ted Kremenek12619382009-01-12 21:45:02 +0000866}
867
Ted Kremenek9c378f72011-08-12 23:37:29 +0000868static bool isRelease(const FunctionDecl *FD, StringRef FName) {
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000869 return FName.endswith("Release");
Ted Kremenek12619382009-01-12 21:45:02 +0000870}
871
Jordy Rose76c506f2011-08-21 21:58:18 +0000872static bool isMakeCollectable(const FunctionDecl *FD, StringRef FName) {
873 // FIXME: Remove FunctionDecl parameter.
874 // FIXME: Is it really okay if MakeCollectable isn't a suffix?
875 return FName.find("MakeCollectable") != StringRef::npos;
876}
877
Jordan Rose4531b7d2012-07-02 19:27:43 +0000878static ArgEffect getStopTrackingEquivalent(ArgEffect E) {
879 switch (E) {
880 case DoNothing:
881 case Autorelease:
882 case DecRefBridgedTransfered:
883 case IncRef:
884 case IncRefMsg:
885 case MakeCollectable:
886 case MayEscape:
887 case NewAutoreleasePool:
888 case StopTracking:
889 return StopTracking;
890 case DecRef:
891 case DecRefAndStopTracking:
892 return DecRefAndStopTracking;
893 case DecRefMsg:
894 case DecRefMsgAndStopTracking:
895 return DecRefMsgAndStopTracking;
896 case Dealloc:
897 return Dealloc;
898 }
899
900 llvm_unreachable("Unknown ArgEffect kind");
901}
902
903void RetainSummaryManager::updateSummaryForCall(const RetainSummary *&S,
904 const CallEvent &Call) {
905 if (Call.hasNonZeroCallbackArg()) {
906 ArgEffect RecEffect = getStopTrackingEquivalent(S->getReceiverEffect());
907 ArgEffect DefEffect = getStopTrackingEquivalent(S->getDefaultArgEffect());
908
909 ArgEffects CustomArgEffects = S->getArgEffects();
910 for (ArgEffects::iterator I = CustomArgEffects.begin(),
911 E = CustomArgEffects.end();
912 I != E; ++I) {
913 ArgEffect Translated = getStopTrackingEquivalent(I->second);
914 if (Translated != DefEffect)
915 ScratchArgs = AF.add(ScratchArgs, I->first, Translated);
916 }
917
918 RetEffect RE = RetEffect::MakeNoRet();
919
920 // Special cases where the callback argument CANNOT free the return value.
921 // This can generally only happen if we know that the callback will only be
922 // called when the return value is already being deallocated.
923 if (const FunctionCall *FC = dyn_cast<FunctionCall>(&Call)) {
924 IdentifierInfo *Name = FC->getDecl()->getIdentifier();
925
926 // This callback frees the associated buffer.
927 if (Name->isStr("CGBitmapContextCreateWithData"))
928 RE = S->getRetEffect();
929 }
930
931 S = getPersistentSummary(RE, RecEffect, DefEffect);
932 }
Anna Zaks5a901932012-08-24 00:06:12 +0000933
934 // Special case '[super init];' and '[self init];'
935 //
936 // Even though calling '[super init]' without assigning the result to self
937 // and checking if the parent returns 'nil' is a bad pattern, it is common.
938 // Additionally, our Self Init checker already warns about it. To avoid
939 // overwhelming the user with messages from both checkers, we model the case
940 // of '[super init]' in cases when it is not consumed by another expression
941 // as if the call preserves the value of 'self'; essentially, assuming it can
942 // never fail and return 'nil'.
943 // Note, we don't want to just stop tracking the value since we want the
944 // RetainCount checker to report leaks and use-after-free if SelfInit checker
945 // is turned off.
946 if (const ObjCMethodCall *MC = dyn_cast<ObjCMethodCall>(&Call)) {
947 if (MC->getMethodFamily() == OMF_init && MC->isReceiverSelfOrSuper()) {
948
949 // Check if the message is not consumed, we know it will not be used in
950 // an assignment, ex: "self = [super init]".
951 const Expr *ME = MC->getOriginExpr();
952 const LocationContext *LCtx = MC->getLocationContext();
953 ParentMap &PM = LCtx->getAnalysisDeclContext()->getParentMap();
954 if (!PM.isConsumedExpr(ME)) {
955 RetainSummaryTemplate ModifiableSummaryTemplate(S, *this);
956 ModifiableSummaryTemplate->setReceiverEffect(DoNothing);
957 ModifiableSummaryTemplate->setRetEffect(RetEffect::MakeNoRet());
958 }
959 }
960
961 }
Jordan Rose4531b7d2012-07-02 19:27:43 +0000962}
963
Anna Zaks58822c42012-05-04 22:18:39 +0000964const RetainSummary *
Jordan Rose4531b7d2012-07-02 19:27:43 +0000965RetainSummaryManager::getSummary(const CallEvent &Call,
966 ProgramStateRef State) {
967 const RetainSummary *Summ;
968 switch (Call.getKind()) {
969 case CE_Function:
970 Summ = getFunctionSummary(cast<FunctionCall>(Call).getDecl());
971 break;
972 case CE_CXXMember:
Jordan Rosefdaa3382012-07-03 22:55:57 +0000973 case CE_CXXMemberOperator:
Jordan Rose4531b7d2012-07-02 19:27:43 +0000974 case CE_Block:
975 case CE_CXXConstructor:
Jordan Rose8d276d32012-07-10 22:07:47 +0000976 case CE_CXXDestructor:
Jordan Rose70cbf3c2012-07-02 22:21:47 +0000977 case CE_CXXAllocator:
Jordan Rose4531b7d2012-07-02 19:27:43 +0000978 // FIXME: These calls are currently unsupported.
979 return getPersistentStopSummary();
Jordan Rose8919e682012-07-18 21:59:51 +0000980 case CE_ObjCMessage: {
Jordan Rosecde8cdb2012-07-02 19:27:56 +0000981 const ObjCMethodCall &Msg = cast<ObjCMethodCall>(Call);
Jordan Rose4531b7d2012-07-02 19:27:43 +0000982 if (Msg.isInstanceMessage())
983 Summ = getInstanceMethodSummary(Msg, State);
984 else
985 Summ = getClassMethodSummary(Msg);
986 break;
987 }
988 }
989
990 updateSummaryForCall(Summ, Call);
991
992 assert(Summ && "Unknown call type?");
993 return Summ;
994}
995
996const RetainSummary *
997RetainSummaryManager::getFunctionSummary(const FunctionDecl *FD) {
998 // If we don't know what function we're calling, use our default summary.
999 if (!FD)
1000 return getDefaultSummary();
1001
Ted Kremenek891d5cc2008-04-24 17:22:33 +00001002 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001003 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001004 if (I != FuncSummaries.end())
Ted Kremenek891d5cc2008-04-24 17:22:33 +00001005 return I->second;
1006
Ted Kremeneke401a0c2009-05-04 15:34:07 +00001007 // No summary? Generate one.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001008 const RetainSummary *S = 0;
Jordan Rose15d18e12012-08-06 21:28:02 +00001009 bool AllowAnnotations = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001010
Ted Kremenek37d785b2008-07-15 16:50:12 +00001011 do {
Ted Kremenek12619382009-01-12 21:45:02 +00001012 // We generate "stop" summaries for implicitly defined functions.
1013 if (FD->isImplicit()) {
1014 S = getPersistentStopSummary();
1015 break;
Ted Kremenek37d785b2008-07-15 16:50:12 +00001016 }
Mike Stump1eb44332009-09-09 15:08:12 +00001017
John McCall183700f2009-09-21 23:43:11 +00001018 // [PR 3337] Use 'getAs<FunctionType>' to strip away any typedefs on the
Ted Kremenek99890652009-01-16 18:40:33 +00001019 // function's type.
John McCall183700f2009-09-21 23:43:11 +00001020 const FunctionType* FT = FD->getType()->getAs<FunctionType>();
Ted Kremenek48c6d182009-12-16 06:06:43 +00001021 const IdentifierInfo *II = FD->getIdentifier();
1022 if (!II)
1023 break;
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001024
1025 StringRef FName = II->getName();
Mike Stump1eb44332009-09-09 15:08:12 +00001026
Ted Kremenekbf0a4dd2009-03-05 22:11:14 +00001027 // Strip away preceding '_'. Doing this here will effect all the checks
1028 // down below.
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001029 FName = FName.substr(FName.find_first_not_of('_'));
Mike Stump1eb44332009-09-09 15:08:12 +00001030
Ted Kremenek12619382009-01-12 21:45:02 +00001031 // Inspect the result type.
1032 QualType RetTy = FT->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00001033
Ted Kremenek12619382009-01-12 21:45:02 +00001034 // FIXME: This should all be refactored into a chain of "summary lookup"
1035 // filters.
Ted Kremenek008636a2009-10-14 00:27:24 +00001036 assert(ScratchArgs.isEmpty());
Ted Kremenek39d88b02009-06-15 20:36:07 +00001037
Ted Kremenekbefc6d22012-04-26 04:32:23 +00001038 if (FName == "pthread_create" || FName == "pthread_setspecific") {
1039 // Part of: <rdar://problem/7299394> and <rdar://problem/11282706>.
1040 // This will be addressed better with IPA.
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001041 S = getPersistentStopSummary();
1042 } else if (FName == "NSMakeCollectable") {
1043 // Handle: id NSMakeCollectable(CFTypeRef)
1044 S = (RetTy->isObjCIdType())
1045 ? getUnarySummary(FT, cfmakecollectable)
1046 : getPersistentStopSummary();
Jordan Rose15d18e12012-08-06 21:28:02 +00001047 // The headers on OS X 10.8 use cf_consumed/ns_returns_retained,
1048 // but we can fully model NSMakeCollectable ourselves.
1049 AllowAnnotations = false;
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001050 } else if (FName == "IOBSDNameMatching" ||
1051 FName == "IOServiceMatching" ||
1052 FName == "IOServiceNameMatching" ||
Ted Kremenek537dd3a2012-05-01 05:28:27 +00001053 FName == "IORegistryEntrySearchCFProperty" ||
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001054 FName == "IORegistryEntryIDMatching" ||
1055 FName == "IOOpenFirmwarePathMatching") {
1056 // Part of <rdar://problem/6961230>. (IOKit)
1057 // This should be addressed using a API table.
1058 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1059 DoNothing, DoNothing);
1060 } else if (FName == "IOServiceGetMatchingService" ||
1061 FName == "IOServiceGetMatchingServices") {
1062 // FIXES: <rdar://problem/6326900>
1063 // This should be addressed using a API table. This strcmp is also
1064 // a little gross, but there is no need to super optimize here.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001065 ScratchArgs = AF.add(ScratchArgs, 1, DecRef);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001066 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1067 } else if (FName == "IOServiceAddNotification" ||
1068 FName == "IOServiceAddMatchingNotification") {
1069 // Part of <rdar://problem/6961230>. (IOKit)
1070 // This should be addressed using a API table.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001071 ScratchArgs = AF.add(ScratchArgs, 2, DecRef);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001072 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1073 } else if (FName == "CVPixelBufferCreateWithBytes") {
1074 // FIXES: <rdar://problem/7283567>
1075 // Eventually this can be improved by recognizing that the pixel
1076 // buffer passed to CVPixelBufferCreateWithBytes is released via
1077 // a callback and doing full IPA to make sure this is done correctly.
1078 // FIXME: This function has an out parameter that returns an
1079 // allocated object.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001080 ScratchArgs = AF.add(ScratchArgs, 7, StopTracking);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001081 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1082 } else if (FName == "CGBitmapContextCreateWithData") {
1083 // FIXES: <rdar://problem/7358899>
1084 // Eventually this can be improved by recognizing that 'releaseInfo'
1085 // passed to CGBitmapContextCreateWithData is released via
1086 // a callback and doing full IPA to make sure this is done correctly.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001087 ScratchArgs = AF.add(ScratchArgs, 8, StopTracking);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001088 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1089 DoNothing, DoNothing);
1090 } else if (FName == "CVPixelBufferCreateWithPlanarBytes") {
1091 // FIXES: <rdar://problem/7283567>
1092 // Eventually this can be improved by recognizing that the pixel
1093 // buffer passed to CVPixelBufferCreateWithPlanarBytes is released
1094 // via a callback and doing full IPA to make sure this is done
1095 // correctly.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001096 ScratchArgs = AF.add(ScratchArgs, 12, StopTracking);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001097 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenek06911d42012-03-22 06:29:41 +00001098 } else if (FName == "dispatch_set_context") {
1099 // <rdar://problem/11059275> - The analyzer currently doesn't have
1100 // a good way to reason about the finalizer function for libdispatch.
1101 // If we pass a context object that is memory managed, stop tracking it.
1102 // FIXME: this hack should possibly go away once we can handle
1103 // libdispatch finalizers.
1104 ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
1105 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenekc91fdf62012-05-08 00:12:09 +00001106 } else if (FName.startswith("NSLog")) {
1107 S = getDoNothingSummary();
Anna Zaks62a5c342012-03-30 05:48:16 +00001108 } else if (FName.startswith("NS") &&
1109 (FName.find("Insert") != StringRef::npos)) {
1110 // Whitelist NSXXInsertXX, for example NSMapInsertIfAbsent, since they can
1111 // be deallocated by NSMapRemove. (radar://11152419)
1112 ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
1113 ScratchArgs = AF.add(ScratchArgs, 2, StopTracking);
1114 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenekb04cb592009-06-11 18:17:24 +00001115 }
Mike Stump1eb44332009-09-09 15:08:12 +00001116
Ted Kremenekb04cb592009-06-11 18:17:24 +00001117 // Did we get a summary?
1118 if (S)
1119 break;
Ted Kremenek61991902009-03-17 22:43:44 +00001120
Ted Kremenek12619382009-01-12 21:45:02 +00001121 if (RetTy->isPointerType()) {
1122 // For CoreFoundation ('CF') types.
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001123 if (cocoa::isRefType(RetTy, "CF", FName)) {
Ted Kremenek12619382009-01-12 21:45:02 +00001124 if (isRetain(FD, FName))
1125 S = getUnarySummary(FT, cfretain);
Jordy Rose76c506f2011-08-21 21:58:18 +00001126 else if (isMakeCollectable(FD, FName))
Ted Kremenek12619382009-01-12 21:45:02 +00001127 S = getUnarySummary(FT, cfmakecollectable);
Mike Stump1eb44332009-09-09 15:08:12 +00001128 else
John McCall7df2ff42011-10-01 00:48:56 +00001129 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek12619382009-01-12 21:45:02 +00001130
1131 break;
1132 }
1133
1134 // For CoreGraphics ('CG') types.
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001135 if (cocoa::isRefType(RetTy, "CG", FName)) {
Ted Kremenek12619382009-01-12 21:45:02 +00001136 if (isRetain(FD, FName))
1137 S = getUnarySummary(FT, cfretain);
1138 else
John McCall7df2ff42011-10-01 00:48:56 +00001139 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek12619382009-01-12 21:45:02 +00001140
1141 break;
1142 }
1143
1144 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001145 if (cocoa::isRefType(RetTy, "DADisk") ||
1146 cocoa::isRefType(RetTy, "DADissenter") ||
1147 cocoa::isRefType(RetTy, "DASessionRef")) {
John McCall7df2ff42011-10-01 00:48:56 +00001148 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek12619382009-01-12 21:45:02 +00001149 break;
1150 }
Mike Stump1eb44332009-09-09 15:08:12 +00001151
Ted Kremenek12619382009-01-12 21:45:02 +00001152 break;
1153 }
1154
1155 // Check for release functions, the only kind of functions that we care
1156 // about that don't return a pointer type.
1157 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
Ted Kremeneke7d03122010-02-08 16:45:01 +00001158 // Test for 'CGCF'.
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001159 FName = FName.substr(FName.startswith("CGCF") ? 4 : 2);
Ted Kremeneke7d03122010-02-08 16:45:01 +00001160
Ted Kremenekbf0a4dd2009-03-05 22:11:14 +00001161 if (isRelease(FD, FName))
Ted Kremenek12619382009-01-12 21:45:02 +00001162 S = getUnarySummary(FT, cfrelease);
1163 else {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001164 assert (ScratchArgs.isEmpty());
Ted Kremenek68189282009-01-29 22:45:13 +00001165 // Remaining CoreFoundation and CoreGraphics functions.
1166 // We use to assume that they all strictly followed the ownership idiom
1167 // and that ownership cannot be transferred. While this is technically
1168 // correct, many methods allow a tracked object to escape. For example:
1169 //
Mike Stump1eb44332009-09-09 15:08:12 +00001170 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
Ted Kremenek68189282009-01-29 22:45:13 +00001171 // CFDictionaryAddValue(y, key, x);
Mike Stump1eb44332009-09-09 15:08:12 +00001172 // CFRelease(x);
Ted Kremenek68189282009-01-29 22:45:13 +00001173 // ... it is okay to use 'x' since 'y' has a reference to it
1174 //
1175 // We handle this and similar cases with the follow heuristic. If the
Ted Kremenekc4843812009-08-20 00:57:22 +00001176 // function name contains "InsertValue", "SetValue", "AddValue",
1177 // "AppendValue", or "SetAttribute", then we assume that arguments may
1178 // "escape." This means that something else holds on to the object,
1179 // allowing it be used even after its local retain count drops to 0.
Benjamin Kramere45c1492010-01-11 19:46:28 +00001180 ArgEffect E = (StrInStrNoCase(FName, "InsertValue") != StringRef::npos||
1181 StrInStrNoCase(FName, "AddValue") != StringRef::npos ||
1182 StrInStrNoCase(FName, "SetValue") != StringRef::npos ||
1183 StrInStrNoCase(FName, "AppendValue") != StringRef::npos||
Benjamin Kramerc027e542010-01-11 20:15:06 +00001184 StrInStrNoCase(FName, "SetAttribute") != StringRef::npos)
Ted Kremenek68189282009-01-29 22:45:13 +00001185 ? MayEscape : DoNothing;
Mike Stump1eb44332009-09-09 15:08:12 +00001186
Ted Kremenek68189282009-01-29 22:45:13 +00001187 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek12619382009-01-12 21:45:02 +00001188 }
1189 }
Ted Kremenek37d785b2008-07-15 16:50:12 +00001190 }
1191 while (0);
Mike Stump1eb44332009-09-09 15:08:12 +00001192
Jordan Rose4531b7d2012-07-02 19:27:43 +00001193 // If we got all the way here without any luck, use a default summary.
1194 if (!S)
1195 S = getDefaultSummary();
1196
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001197 // Annotations override defaults.
Jordan Rose15d18e12012-08-06 21:28:02 +00001198 if (AllowAnnotations)
1199 updateSummaryFromAnnotations(S, FD);
Mike Stump1eb44332009-09-09 15:08:12 +00001200
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001201 FuncSummaries[FD] = S;
Mike Stump1eb44332009-09-09 15:08:12 +00001202 return S;
Ted Kremenek2fff37e2008-03-06 00:08:09 +00001203}
1204
Ted Kremenek93edbc52011-10-05 23:54:29 +00001205const RetainSummary *
John McCall7df2ff42011-10-01 00:48:56 +00001206RetainSummaryManager::getCFCreateGetRuleSummary(const FunctionDecl *FD) {
1207 if (coreFoundation::followsCreateRule(FD))
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001208 return getCFSummaryCreateRule(FD);
Mike Stump1eb44332009-09-09 15:08:12 +00001209
Ted Kremenekd368d712011-05-25 06:19:45 +00001210 return getCFSummaryGetRule(FD);
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001211}
1212
Ted Kremenek93edbc52011-10-05 23:54:29 +00001213const RetainSummary *
Ted Kremenek6ad315a2009-02-23 16:51:39 +00001214RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1215 UnaryFuncKind func) {
1216
Ted Kremenek12619382009-01-12 21:45:02 +00001217 // Sanity check that this is *really* a unary function. This can
1218 // happen if people do weird things.
Douglas Gregor72564e72009-02-26 23:50:07 +00001219 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
Ted Kremenek12619382009-01-12 21:45:02 +00001220 if (!FTP || FTP->getNumArgs() != 1)
1221 return getPersistentStopSummary();
Mike Stump1eb44332009-09-09 15:08:12 +00001222
Ted Kremenekb77449c2009-05-03 05:20:50 +00001223 assert (ScratchArgs.isEmpty());
Mike Stump1eb44332009-09-09 15:08:12 +00001224
Jordy Rose76c506f2011-08-21 21:58:18 +00001225 ArgEffect Effect;
Ted Kremenek377e2302008-04-29 05:33:51 +00001226 switch (func) {
Jordy Rose76c506f2011-08-21 21:58:18 +00001227 case cfretain: Effect = IncRef; break;
1228 case cfrelease: Effect = DecRef; break;
1229 case cfmakecollectable: Effect = MakeCollectable; break;
Ted Kremenek940b1d82008-04-10 23:44:06 +00001230 }
Jordy Rose76c506f2011-08-21 21:58:18 +00001231
1232 ScratchArgs = AF.add(ScratchArgs, 0, Effect);
1233 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001234}
1235
Ted Kremenek93edbc52011-10-05 23:54:29 +00001236const RetainSummary *
Ted Kremenek9c378f72011-08-12 23:37:29 +00001237RetainSummaryManager::getCFSummaryCreateRule(const FunctionDecl *FD) {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001238 assert (ScratchArgs.isEmpty());
Mike Stump1eb44332009-09-09 15:08:12 +00001239
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001240 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001241}
1242
Ted Kremenek93edbc52011-10-05 23:54:29 +00001243const RetainSummary *
Ted Kremenek9c378f72011-08-12 23:37:29 +00001244RetainSummaryManager::getCFSummaryGetRule(const FunctionDecl *FD) {
Mike Stump1eb44332009-09-09 15:08:12 +00001245 assert (ScratchArgs.isEmpty());
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001246 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1247 DoNothing, DoNothing);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001248}
1249
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001250//===----------------------------------------------------------------------===//
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001251// Summary creation for Selectors.
1252//===----------------------------------------------------------------------===//
1253
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001254void
Ted Kremenek93edbc52011-10-05 23:54:29 +00001255RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001256 const FunctionDecl *FD) {
1257 if (!FD)
1258 return;
1259
Jordan Rose4531b7d2012-07-02 19:27:43 +00001260 assert(Summ && "Must have a summary to add annotations to.");
1261 RetainSummaryTemplate Template(Summ, *this);
Jordy Rose4df54fe2011-08-23 04:27:15 +00001262
Ted Kremenek11fe1752011-01-27 18:43:03 +00001263 // Effects on the parameters.
1264 unsigned parm_idx = 0;
1265 for (FunctionDecl::param_const_iterator pi = FD->param_begin(),
John McCall98b8f162011-04-06 09:02:12 +00001266 pe = FD->param_end(); pi != pe; ++pi, ++parm_idx) {
Ted Kremenek11fe1752011-01-27 18:43:03 +00001267 const ParmVarDecl *pd = *pi;
1268 if (pd->getAttr<NSConsumedAttr>()) {
Jordy Rose4df54fe2011-08-23 04:27:15 +00001269 if (!GCEnabled) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001270 Template->addArg(AF, parm_idx, DecRef);
Jordy Rose4df54fe2011-08-23 04:27:15 +00001271 }
1272 } else if (pd->getAttr<CFConsumedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001273 Template->addArg(AF, parm_idx, DecRef);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001274 }
1275 }
1276
Ted Kremenekb04cb592009-06-11 18:17:24 +00001277 QualType RetTy = FD->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00001278
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001279 // Determine if there is a special return effect for this method.
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001280 if (cocoa::isCocoaObjectRef(RetTy)) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001281 if (FD->getAttr<NSReturnsRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001282 Template->setRetEffect(ObjCAllocRetE);
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001283 }
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001284 else if (FD->getAttr<CFReturnsRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001285 Template->setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenekb04cb592009-06-11 18:17:24 +00001286 }
Ted Kremenek60411112010-02-18 00:06:12 +00001287 else if (FD->getAttr<NSReturnsNotRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001288 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::ObjC));
Ted Kremenek60411112010-02-18 00:06:12 +00001289 }
1290 else if (FD->getAttr<CFReturnsNotRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001291 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::CF));
Jordy Rose4df54fe2011-08-23 04:27:15 +00001292 }
1293 } else if (RetTy->getAs<PointerType>()) {
1294 if (FD->getAttr<CFReturnsRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001295 Template->setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
Jordy Rose4df54fe2011-08-23 04:27:15 +00001296 }
1297 else if (FD->getAttr<CFReturnsNotRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001298 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::CF));
Ted Kremenek60411112010-02-18 00:06:12 +00001299 }
Ted Kremenekb04cb592009-06-11 18:17:24 +00001300 }
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001301}
1302
1303void
Ted Kremenek93edbc52011-10-05 23:54:29 +00001304RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
1305 const ObjCMethodDecl *MD) {
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001306 if (!MD)
1307 return;
1308
Jordan Rose4531b7d2012-07-02 19:27:43 +00001309 assert(Summ && "Must have a valid summary to add annotations to");
1310 RetainSummaryTemplate Template(Summ, *this);
Ted Kremenek6d4b76d2009-07-06 18:30:43 +00001311 bool isTrackedLoc = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001312
Ted Kremenek12b94342011-01-27 06:54:14 +00001313 // Effects on the receiver.
1314 if (MD->getAttr<NSConsumesSelfAttr>()) {
Ted Kremenek11fe1752011-01-27 18:43:03 +00001315 if (!GCEnabled)
Jordy Rose0fe62f82011-08-24 09:02:37 +00001316 Template->setReceiverEffect(DecRefMsg);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001317 }
1318
1319 // Effects on the parameters.
1320 unsigned parm_idx = 0;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00001321 for (ObjCMethodDecl::param_const_iterator
1322 pi=MD->param_begin(), pe=MD->param_end();
Ted Kremenek11fe1752011-01-27 18:43:03 +00001323 pi != pe; ++pi, ++parm_idx) {
1324 const ParmVarDecl *pd = *pi;
1325 if (pd->getAttr<NSConsumedAttr>()) {
1326 if (!GCEnabled)
Jordy Rose0fe62f82011-08-24 09:02:37 +00001327 Template->addArg(AF, parm_idx, DecRef);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001328 }
1329 else if(pd->getAttr<CFConsumedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001330 Template->addArg(AF, parm_idx, DecRef);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001331 }
Ted Kremenek12b94342011-01-27 06:54:14 +00001332 }
1333
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001334 // Determine if there is a special return effect for this method.
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001335 if (cocoa::isCocoaObjectRef(MD->getResultType())) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001336 if (MD->getAttr<NSReturnsRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001337 Template->setRetEffect(ObjCAllocRetE);
Ted Kremenek6d4b76d2009-07-06 18:30:43 +00001338 return;
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001339 }
Ted Kremenek60411112010-02-18 00:06:12 +00001340 if (MD->getAttr<NSReturnsNotRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001341 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::ObjC));
Ted Kremenek60411112010-02-18 00:06:12 +00001342 return;
1343 }
Mike Stump1eb44332009-09-09 15:08:12 +00001344
Ted Kremenek6d4b76d2009-07-06 18:30:43 +00001345 isTrackedLoc = true;
Jordy Rose0fe62f82011-08-24 09:02:37 +00001346 } else {
Ted Kremenek6217b802009-07-29 21:53:49 +00001347 isTrackedLoc = MD->getResultType()->getAs<PointerType>() != NULL;
Jordy Rose0fe62f82011-08-24 09:02:37 +00001348 }
Mike Stump1eb44332009-09-09 15:08:12 +00001349
Ted Kremenek60411112010-02-18 00:06:12 +00001350 if (isTrackedLoc) {
1351 if (MD->getAttr<CFReturnsRetainedAttr>())
Jordy Rose0fe62f82011-08-24 09:02:37 +00001352 Template->setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenek60411112010-02-18 00:06:12 +00001353 else if (MD->getAttr<CFReturnsNotRetainedAttr>())
Jordy Rose0fe62f82011-08-24 09:02:37 +00001354 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::CF));
Ted Kremenek60411112010-02-18 00:06:12 +00001355 }
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) {
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001361
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +00001362 if (MD) {
Ted Kremenek376d1e72009-04-24 18:00:17 +00001363 // Scan the method decl for 'void*' arguments. These should be treated
1364 // as 'StopTracking' because they are often used with delegates.
1365 // Delegates are a frequent form of false positives with the retain
1366 // count checker.
1367 unsigned i = 0;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00001368 for (ObjCMethodDecl::param_const_iterator I = MD->param_begin(),
Ted Kremenek376d1e72009-04-24 18:00:17 +00001369 E = MD->param_end(); I != E; ++I, ++i)
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00001370 if (const ParmVarDecl *PD = *I) {
Ted Kremenek376d1e72009-04-24 18:00:17 +00001371 QualType Ty = Ctx.getCanonicalType(PD->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001372 if (Ty.getLocalUnqualifiedType() == Ctx.VoidPtrTy)
Ted Kremenek3baf6722010-11-24 00:54:37 +00001373 ScratchArgs = AF.add(ScratchArgs, i, StopTracking);
Ted Kremenek376d1e72009-04-24 18:00:17 +00001374 }
1375 }
Mike Stump1eb44332009-09-09 15:08:12 +00001376
Jordy Rosee921b1a2012-03-17 19:53:04 +00001377 // Any special effects?
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001378 ArgEffect ReceiverEff = DoNothing;
Jordy Rosee921b1a2012-03-17 19:53:04 +00001379 RetEffect ResultEff = RetEffect::MakeNoRet();
1380
1381 // Check the method family, and apply any default annotations.
1382 switch (MD ? MD->getMethodFamily() : S.getMethodFamily()) {
1383 case OMF_None:
1384 case OMF_performSelector:
1385 // Assume all Objective-C methods follow Cocoa Memory Management rules.
1386 // FIXME: Does the non-threaded performSelector family really belong here?
1387 // The selector could be, say, @selector(copy).
1388 if (cocoa::isCocoaObjectRef(RetTy))
1389 ResultEff = RetEffect::MakeNotOwned(RetEffect::ObjC);
1390 else if (coreFoundation::isCFObjectRef(RetTy)) {
1391 // ObjCMethodDecl currently doesn't consider CF objects as valid return
1392 // values for alloc, new, copy, or mutableCopy, so we have to
1393 // double-check with the selector. This is ugly, but there aren't that
1394 // many Objective-C methods that return CF objects, right?
1395 if (MD) {
1396 switch (S.getMethodFamily()) {
1397 case OMF_alloc:
1398 case OMF_new:
1399 case OMF_copy:
1400 case OMF_mutableCopy:
1401 ResultEff = RetEffect::MakeOwned(RetEffect::CF, true);
1402 break;
1403 default:
1404 ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1405 break;
1406 }
1407 } else {
1408 ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1409 }
1410 }
1411 break;
1412 case OMF_init:
1413 ResultEff = ObjCInitRetE;
1414 ReceiverEff = DecRefMsg;
1415 break;
1416 case OMF_alloc:
1417 case OMF_new:
1418 case OMF_copy:
1419 case OMF_mutableCopy:
1420 if (cocoa::isCocoaObjectRef(RetTy))
1421 ResultEff = ObjCAllocRetE;
1422 else if (coreFoundation::isCFObjectRef(RetTy))
1423 ResultEff = RetEffect::MakeOwned(RetEffect::CF, true);
1424 break;
1425 case OMF_autorelease:
1426 ReceiverEff = Autorelease;
1427 break;
1428 case OMF_retain:
1429 ReceiverEff = IncRefMsg;
1430 break;
1431 case OMF_release:
1432 ReceiverEff = DecRefMsg;
1433 break;
1434 case OMF_dealloc:
1435 ReceiverEff = Dealloc;
1436 break;
1437 case OMF_self:
1438 // -self is handled specially by the ExprEngine to propagate the receiver.
1439 break;
1440 case OMF_retainCount:
1441 case OMF_finalize:
1442 // These methods don't return objects.
1443 break;
1444 }
Mike Stump1eb44332009-09-09 15:08:12 +00001445
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001446 // If one of the arguments in the selector has the keyword 'delegate' we
1447 // should stop tracking the reference count for the receiver. This is
1448 // because the reference count is quite possibly handled by a delegate
1449 // method.
1450 if (S.isKeywordSelector()) {
Jordan Rose50571a92012-06-15 18:19:52 +00001451 for (unsigned i = 0, e = S.getNumArgs(); i != e; ++i) {
1452 StringRef Slot = S.getNameForSlot(i);
1453 if (Slot.substr(Slot.size() - 8).equals_lower("delegate")) {
1454 if (ResultEff == ObjCInitRetE)
1455 ResultEff = RetEffect::MakeNoRet();
1456 else
1457 ReceiverEff = StopTracking;
1458 }
1459 }
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001460 }
Mike Stump1eb44332009-09-09 15:08:12 +00001461
Jordy Rosee921b1a2012-03-17 19:53:04 +00001462 if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing &&
1463 ResultEff.getKind() == RetEffect::NoRet)
Ted Kremenek93edbc52011-10-05 23:54:29 +00001464 return getDefaultSummary();
Mike Stump1eb44332009-09-09 15:08:12 +00001465
Jordy Rosee921b1a2012-03-17 19:53:04 +00001466 return getPersistentSummary(ResultEff, ReceiverEff, MayEscape);
Ted Kremenek250b1fa2009-04-23 23:08:22 +00001467}
1468
Ted Kremenek93edbc52011-10-05 23:54:29 +00001469const RetainSummary *
Jordan Rosecde8cdb2012-07-02 19:27:56 +00001470RetainSummaryManager::getInstanceMethodSummary(const ObjCMethodCall &Msg,
Jordan Rose4531b7d2012-07-02 19:27:43 +00001471 ProgramStateRef State) {
1472 const ObjCInterfaceDecl *ReceiverClass = 0;
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001473
Jordan Rose4531b7d2012-07-02 19:27:43 +00001474 // We do better tracking of the type of the object than the core ExprEngine.
1475 // See if we have its type in our private state.
1476 // FIXME: Eventually replace the use of state->get<RefBindings> with
1477 // a generic API for reasoning about the Objective-C types of symbolic
1478 // objects.
1479 SVal ReceiverV = Msg.getReceiverSVal();
1480 if (SymbolRef Sym = ReceiverV.getAsLocSymbol())
Anna Zaks8d6b43c2012-08-14 00:36:15 +00001481 if (const RefVal *T = getRefBinding(State, Sym))
Douglas Gregor04badcf2010-04-21 00:45:42 +00001482 if (const ObjCObjectPointerType *PT =
Jordan Rose4531b7d2012-07-02 19:27:43 +00001483 T->getType()->getAs<ObjCObjectPointerType>())
1484 ReceiverClass = PT->getInterfaceDecl();
1485
1486 // If we don't know what kind of object this is, fall back to its static type.
1487 if (!ReceiverClass)
1488 ReceiverClass = Msg.getReceiverInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00001489
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001490 // FIXME: The receiver could be a reference to a class, meaning that
1491 // we should use the class method.
Jordan Rose4531b7d2012-07-02 19:27:43 +00001492 // id x = [NSObject class];
1493 // [x performSelector:... withObject:... afterDelay:...];
1494 Selector S = Msg.getSelector();
1495 const ObjCMethodDecl *Method = Msg.getDecl();
1496 if (!Method && ReceiverClass)
1497 Method = ReceiverClass->getInstanceMethod(S);
1498
1499 return getMethodSummary(S, ReceiverClass, Method, Msg.getResultType(),
1500 ObjCMethodSummaries);
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001501}
1502
Ted Kremenek93edbc52011-10-05 23:54:29 +00001503const RetainSummary *
Jordan Rose4531b7d2012-07-02 19:27:43 +00001504RetainSummaryManager::getMethodSummary(Selector S, const ObjCInterfaceDecl *ID,
Jordy Rosef3aae582012-03-17 21:13:07 +00001505 const ObjCMethodDecl *MD, QualType RetTy,
1506 ObjCMethodSummariesTy &CachedSummaries) {
Ted Kremenek1bffd742008-05-06 15:44:25 +00001507
Ted Kremenek8711c032009-04-29 05:04:30 +00001508 // Look up a summary in our summary cache.
Jordan Rose4531b7d2012-07-02 19:27:43 +00001509 const RetainSummary *Summ = CachedSummaries.find(ID, S);
Mike Stump1eb44332009-09-09 15:08:12 +00001510
Ted Kremenek614cc542009-07-21 23:27:57 +00001511 if (!Summ) {
Jordy Rosef3aae582012-03-17 21:13:07 +00001512 Summ = getStandardMethodSummary(MD, S, RetTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001513
Ted Kremenek614cc542009-07-21 23:27:57 +00001514 // Annotations override defaults.
Jordy Rose4df54fe2011-08-23 04:27:15 +00001515 updateSummaryFromAnnotations(Summ, MD);
Mike Stump1eb44332009-09-09 15:08:12 +00001516
Ted Kremenek614cc542009-07-21 23:27:57 +00001517 // Memoize the summary.
Jordan Rose4531b7d2012-07-02 19:27:43 +00001518 CachedSummaries[ObjCSummaryKey(ID, S)] = Summ;
Ted Kremenek614cc542009-07-21 23:27:57 +00001519 }
Mike Stump1eb44332009-09-09 15:08:12 +00001520
Ted Kremeneke87450e2009-04-23 19:11:35 +00001521 return Summ;
Ted Kremenekc8395602008-05-06 21:26:51 +00001522}
1523
Mike Stump1eb44332009-09-09 15:08:12 +00001524void RetainSummaryManager::InitializeClassMethodSummaries() {
Ted Kremenekec315332009-05-07 23:40:42 +00001525 assert(ScratchArgs.isEmpty());
Mike Stump1eb44332009-09-09 15:08:12 +00001526 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek6fe2b7a2009-10-15 22:25:12 +00001527 addClassMethSummary("NSAssertionHandler", "currentHandler",
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001528 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Mike Stump1eb44332009-09-09 15:08:12 +00001529
Ted Kremenek6d348932008-10-21 15:53:15 +00001530 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001531 ScratchArgs = AF.add(ScratchArgs, 0, Autorelease);
Ted Kremenek6fe2b7a2009-10-15 22:25:12 +00001532 addClassMethSummary("NSAutoreleasePool", "addObject",
1533 getPersistentSummary(RetEffect::MakeNoRet(),
1534 DoNothing, Autorelease));
Ted Kremenek9c32d082008-05-06 00:30:21 +00001535}
1536
Ted Kremenek1f180c32008-06-23 22:21:20 +00001537void RetainSummaryManager::InitializeMethodSummaries() {
Mike Stump1eb44332009-09-09 15:08:12 +00001538
1539 assert (ScratchArgs.isEmpty());
1540
Ted Kremenekc8395602008-05-06 21:26:51 +00001541 // Create the "init" selector. It just acts as a pass-through for the
1542 // receiver.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001543 const RetainSummary *InitSumm = getPersistentSummary(ObjCInitRetE, DecRefMsg);
Ted Kremenekac02f202009-08-20 05:13:36 +00001544 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
1545
1546 // awakeAfterUsingCoder: behaves basically like an 'init' method. It
1547 // claims the receiver and returns a retained object.
1548 addNSObjectMethSummary(GetUnarySelector("awakeAfterUsingCoder", Ctx),
1549 InitSumm);
Mike Stump1eb44332009-09-09 15:08:12 +00001550
Ted Kremenekc8395602008-05-06 21:26:51 +00001551 // The next methods are allocators.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001552 const RetainSummary *AllocSumm = getPersistentSummary(ObjCAllocRetE);
1553 const RetainSummary *CFAllocSumm =
Ted Kremeneka834fb42009-08-28 19:52:12 +00001554 getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Mike Stump1eb44332009-09-09 15:08:12 +00001555
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001556 // Create the "retain" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001557 RetEffect NoRet = RetEffect::MakeNoRet();
Ted Kremenek93edbc52011-10-05 23:54:29 +00001558 const RetainSummary *Summ = getPersistentSummary(NoRet, IncRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001559 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001560
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001561 // Create the "release" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001562 Summ = getPersistentSummary(NoRet, DecRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001563 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001564
Ted Kremenek299e8152008-05-07 21:17:39 +00001565 // Create the "drain" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001566 Summ = getPersistentSummary(NoRet, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek553cf182008-06-25 21:21:56 +00001567 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001568
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001569 // Create the -dealloc summary.
Jordy Rose500abad2011-08-21 19:41:36 +00001570 Summ = getPersistentSummary(NoRet, Dealloc);
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001571 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001572
1573 // Create the "autorelease" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001574 Summ = getPersistentSummary(NoRet, Autorelease);
Ted Kremenek553cf182008-06-25 21:21:56 +00001575 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001576
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00001577 // Specially handle NSAutoreleasePool.
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001578 addInstMethSummary("NSAutoreleasePool", "init",
Jordy Rose500abad2011-08-21 19:41:36 +00001579 getPersistentSummary(NoRet, NewAutoreleasePool));
Mike Stump1eb44332009-09-09 15:08:12 +00001580
1581 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremenek89e202d2009-02-23 02:51:29 +00001582 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1583 // self-own themselves. However, they only do this once they are displayed.
1584 // Thus, we need to track an NSWindow's display status.
1585 // This is tracked in <rdar://problem/6062711>.
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +00001586 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001587 const RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenek78a35a32009-05-12 20:06:54 +00001588 StopTracking,
1589 StopTracking);
Mike Stump1eb44332009-09-09 15:08:12 +00001590
Ted Kremenek99d02692009-04-03 19:02:51 +00001591 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1592
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001593 // For NSPanel (which subclasses NSWindow), allocated objects are not
1594 // self-owned.
Ted Kremenek99d02692009-04-03 19:02:51 +00001595 // FIXME: For now we don't track NSPanels. object for the same reason
1596 // as for NSWindow objects.
1597 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
Mike Stump1eb44332009-09-09 15:08:12 +00001598
Ted Kremenekba67f6a2009-05-18 23:14:34 +00001599 // Don't track allocated autorelease pools yet, as it is okay to prematurely
1600 // exit a method.
1601 addClassMethSummary("NSAutoreleasePool", "alloc", NoTrackYet);
Ted Kremeneka9797122012-02-18 21:37:48 +00001602 addClassMethSummary("NSAutoreleasePool", "allocWithZone", NoTrackYet, false);
Ted Kremenek553cf182008-06-25 21:21:56 +00001603
Ted Kremenek767d6492009-05-20 22:39:57 +00001604 // Create summaries QCRenderer/QCView -createSnapShotImageOfType:
1605 addInstMethSummary("QCRenderer", AllocSumm,
1606 "createSnapshotImageOfType", NULL);
1607 addInstMethSummary("QCView", AllocSumm,
1608 "createSnapshotImageOfType", NULL);
1609
Ted Kremenek211a9c62009-06-15 20:58:58 +00001610 // Create summaries for CIContext, 'createCGImage' and
Ted Kremeneka834fb42009-08-28 19:52:12 +00001611 // 'createCGLayerWithSize'. These objects are CF objects, and are not
1612 // automatically garbage collected.
1613 addInstMethSummary("CIContext", CFAllocSumm,
Ted Kremenek767d6492009-05-20 22:39:57 +00001614 "createCGImage", "fromRect", NULL);
Ted Kremeneka834fb42009-08-28 19:52:12 +00001615 addInstMethSummary("CIContext", CFAllocSumm,
Mike Stump1eb44332009-09-09 15:08:12 +00001616 "createCGImage", "fromRect", "format", "colorSpace", NULL);
Ted Kremeneka834fb42009-08-28 19:52:12 +00001617 addInstMethSummary("CIContext", CFAllocSumm, "createCGLayerWithSize",
Ted Kremenek211a9c62009-06-15 20:58:58 +00001618 "info", NULL);
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001619}
1620
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001621//===----------------------------------------------------------------------===//
Ted Kremenekc887d132009-04-29 18:50:19 +00001622// Error reporting.
1623//===----------------------------------------------------------------------===//
Ted Kremenekc887d132009-04-29 18:50:19 +00001624namespace {
Jordy Roseec9ef852011-08-23 20:55:48 +00001625 typedef llvm::DenseMap<const ExplodedNode *, const RetainSummary *>
1626 SummaryLogTy;
1627
Ted Kremenekc887d132009-04-29 18:50:19 +00001628 //===-------------===//
1629 // Bug Descriptions. //
Mike Stump1eb44332009-09-09 15:08:12 +00001630 //===-------------===//
1631
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001632 class CFRefBug : public BugType {
Ted Kremenekc887d132009-04-29 18:50:19 +00001633 protected:
Jordy Rose35c86952011-08-24 05:47:39 +00001634 CFRefBug(StringRef name)
Ted Kremenek6fd45052012-04-05 20:43:28 +00001635 : BugType(name, categories::MemoryCoreFoundationObjectiveC) {}
Ted Kremenekc887d132009-04-29 18:50:19 +00001636 public:
Mike Stump1eb44332009-09-09 15:08:12 +00001637
Ted Kremenekc887d132009-04-29 18:50:19 +00001638 // FIXME: Eventually remove.
Jordy Rose35c86952011-08-24 05:47:39 +00001639 virtual const char *getDescription() const = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001640
Ted Kremenekc887d132009-04-29 18:50:19 +00001641 virtual bool isLeak() const { return false; }
1642 };
Mike Stump1eb44332009-09-09 15:08:12 +00001643
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001644 class UseAfterRelease : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001645 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001646 UseAfterRelease() : CFRefBug("Use-after-release") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001647
Jordy Rose35c86952011-08-24 05:47:39 +00001648 const char *getDescription() const {
Ted Kremenekc887d132009-04-29 18:50:19 +00001649 return "Reference-counted object is used after it is released";
Mike Stump1eb44332009-09-09 15:08:12 +00001650 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001651 };
Mike Stump1eb44332009-09-09 15:08:12 +00001652
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001653 class BadRelease : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001654 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001655 BadRelease() : CFRefBug("Bad release") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001656
Jordy Rose35c86952011-08-24 05:47:39 +00001657 const char *getDescription() const {
Ted Kremenekbb206fd2009-10-01 17:31:50 +00001658 return "Incorrect decrement of the reference count of an object that is "
1659 "not owned at this point by the caller";
Ted Kremenekc887d132009-04-29 18:50:19 +00001660 }
1661 };
Mike Stump1eb44332009-09-09 15:08:12 +00001662
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001663 class DeallocGC : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001664 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001665 DeallocGC()
1666 : CFRefBug("-dealloc called while using garbage collection") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001667
Ted Kremenekc887d132009-04-29 18:50:19 +00001668 const char *getDescription() const {
Ted Kremenek369de562009-05-09 00:10:05 +00001669 return "-dealloc called while using garbage collection";
Ted Kremenekc887d132009-04-29 18:50:19 +00001670 }
1671 };
Mike Stump1eb44332009-09-09 15:08:12 +00001672
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001673 class DeallocNotOwned : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001674 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001675 DeallocNotOwned()
1676 : CFRefBug("-dealloc sent to non-exclusively owned object") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001677
Ted Kremenekc887d132009-04-29 18:50:19 +00001678 const char *getDescription() const {
1679 return "-dealloc sent to object that may be referenced elsewhere";
1680 }
Mike Stump1eb44332009-09-09 15:08:12 +00001681 };
1682
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001683 class OverAutorelease : public CFRefBug {
Ted Kremenek369de562009-05-09 00:10:05 +00001684 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001685 OverAutorelease()
1686 : CFRefBug("Object sent -autorelease too many times") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001687
Ted Kremenek369de562009-05-09 00:10:05 +00001688 const char *getDescription() const {
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001689 return "Object sent -autorelease too many times";
Ted Kremenek369de562009-05-09 00:10:05 +00001690 }
1691 };
Mike Stump1eb44332009-09-09 15:08:12 +00001692
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001693 class ReturnedNotOwnedForOwned : public CFRefBug {
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001694 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001695 ReturnedNotOwnedForOwned()
1696 : CFRefBug("Method should return an owned object") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001697
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001698 const char *getDescription() const {
Jordy Rose5b5402b2011-07-15 22:17:54 +00001699 return "Object with a +0 retain count returned to caller where a +1 "
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001700 "(owning) retain count is expected";
1701 }
1702 };
Mike Stump1eb44332009-09-09 15:08:12 +00001703
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001704 class Leak : public CFRefBug {
Benjamin Kramerfacde172012-06-06 17:32:50 +00001705 public:
1706 Leak(StringRef name)
1707 : CFRefBug(name) {
Jordy Rosedb92bb62011-08-25 01:14:38 +00001708 // Leaks should not be reported if they are post-dominated by a sink.
1709 setSuppressOnSink(true);
1710 }
Mike Stump1eb44332009-09-09 15:08:12 +00001711
Jordy Rose35c86952011-08-24 05:47:39 +00001712 const char *getDescription() const { return ""; }
Mike Stump1eb44332009-09-09 15:08:12 +00001713
Ted Kremenekc887d132009-04-29 18:50:19 +00001714 bool isLeak() const { return true; }
1715 };
Mike Stump1eb44332009-09-09 15:08:12 +00001716
Ted Kremenekc887d132009-04-29 18:50:19 +00001717 //===---------===//
1718 // Bug Reports. //
1719 //===---------===//
Mike Stump1eb44332009-09-09 15:08:12 +00001720
Jordy Rose01153492012-03-24 02:45:35 +00001721 class CFRefReportVisitor : public BugReporterVisitorImpl<CFRefReportVisitor> {
Anna Zaks23f395e2011-08-20 01:27:22 +00001722 protected:
Anna Zaksdc757b02011-08-19 23:21:56 +00001723 SymbolRef Sym;
Jordy Roseec9ef852011-08-23 20:55:48 +00001724 const SummaryLogTy &SummaryLog;
Jordy Rose35c86952011-08-24 05:47:39 +00001725 bool GCEnabled;
Anna Zaks23f395e2011-08-20 01:27:22 +00001726
Anna Zaksdc757b02011-08-19 23:21:56 +00001727 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001728 CFRefReportVisitor(SymbolRef sym, bool gcEnabled, const SummaryLogTy &log)
1729 : Sym(sym), SummaryLog(log), GCEnabled(gcEnabled) {}
Anna Zaksdc757b02011-08-19 23:21:56 +00001730
Anna Zaks23f395e2011-08-20 01:27:22 +00001731 virtual void Profile(llvm::FoldingSetNodeID &ID) const {
Anna Zaksdc757b02011-08-19 23:21:56 +00001732 static int x = 0;
1733 ID.AddPointer(&x);
1734 ID.AddPointer(Sym);
1735 }
1736
Anna Zaks23f395e2011-08-20 01:27:22 +00001737 virtual PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
1738 const ExplodedNode *PrevN,
1739 BugReporterContext &BRC,
1740 BugReport &BR);
1741
1742 virtual PathDiagnosticPiece *getEndPath(BugReporterContext &BRC,
1743 const ExplodedNode *N,
1744 BugReport &BR);
1745 };
1746
1747 class CFRefLeakReportVisitor : public CFRefReportVisitor {
1748 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001749 CFRefLeakReportVisitor(SymbolRef sym, bool GCEnabled,
Jordy Roseec9ef852011-08-23 20:55:48 +00001750 const SummaryLogTy &log)
Jordy Rose35c86952011-08-24 05:47:39 +00001751 : CFRefReportVisitor(sym, GCEnabled, log) {}
Anna Zaks23f395e2011-08-20 01:27:22 +00001752
1753 PathDiagnosticPiece *getEndPath(BugReporterContext &BRC,
1754 const ExplodedNode *N,
1755 BugReport &BR);
Jordy Rose01153492012-03-24 02:45:35 +00001756
1757 virtual BugReporterVisitor *clone() const {
1758 // The curiously-recurring template pattern only works for one level of
1759 // subclassing. Rather than make a new template base for
1760 // CFRefReportVisitor, we simply override clone() to do the right thing.
1761 // This could be trouble someday if BugReporterVisitorImpl is ever
1762 // used for something else besides a convenient implementation of clone().
1763 return new CFRefLeakReportVisitor(*this);
1764 }
Anna Zaksdc757b02011-08-19 23:21:56 +00001765 };
1766
Anna Zakse172e8b2011-08-17 23:00:25 +00001767 class CFRefReport : public BugReport {
Jordy Rose20589562011-08-24 22:39:09 +00001768 void addGCModeDescription(const LangOptions &LOpts, bool GCEnabled);
Jordy Rose35c86952011-08-24 05:47:39 +00001769
Ted Kremenekc887d132009-04-29 18:50:19 +00001770 public:
Jordy Rose20589562011-08-24 22:39:09 +00001771 CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1772 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1773 bool registerVisitor = true)
Anna Zaksedf4dae2011-08-22 18:54:07 +00001774 : BugReport(D, D.getDescription(), n) {
Anna Zaks23f395e2011-08-20 01:27:22 +00001775 if (registerVisitor)
Jordy Rose20589562011-08-24 22:39:09 +00001776 addVisitor(new CFRefReportVisitor(sym, GCEnabled, Log));
1777 addGCModeDescription(LOpts, GCEnabled);
Anna Zaksdc757b02011-08-19 23:21:56 +00001778 }
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001779
Jordy Rose20589562011-08-24 22:39:09 +00001780 CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1781 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1782 StringRef endText)
Anna Zaksedf4dae2011-08-22 18:54:07 +00001783 : BugReport(D, D.getDescription(), endText, n) {
Jordy Rose20589562011-08-24 22:39:09 +00001784 addVisitor(new CFRefReportVisitor(sym, GCEnabled, Log));
1785 addGCModeDescription(LOpts, GCEnabled);
Anna Zaksdc757b02011-08-19 23:21:56 +00001786 }
Mike Stump1eb44332009-09-09 15:08:12 +00001787
Anna Zakse172e8b2011-08-17 23:00:25 +00001788 virtual std::pair<ranges_iterator, ranges_iterator> getRanges() {
Anna Zaksedf4dae2011-08-22 18:54:07 +00001789 const CFRefBug& BugTy = static_cast<CFRefBug&>(getBugType());
1790 if (!BugTy.isLeak())
Anna Zakse172e8b2011-08-17 23:00:25 +00001791 return BugReport::getRanges();
Ted Kremenekc887d132009-04-29 18:50:19 +00001792 else
Argyrios Kyrtzidis640ccf02010-12-04 01:12:15 +00001793 return std::make_pair(ranges_iterator(), ranges_iterator());
Ted Kremenekc887d132009-04-29 18:50:19 +00001794 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001795 };
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001796
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001797 class CFRefLeakReport : public CFRefReport {
Ted Kremenekc887d132009-04-29 18:50:19 +00001798 const MemRegion* AllocBinding;
Anna Zaks23f395e2011-08-20 01:27:22 +00001799
Ted Kremenekc887d132009-04-29 18:50:19 +00001800 public:
Jordy Rose20589562011-08-24 22:39:09 +00001801 CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1802 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
Anna Zaks6a93bd52011-10-25 19:57:11 +00001803 CheckerContext &Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001804
Anna Zaks590dd8e2011-09-20 21:38:35 +00001805 PathDiagnosticLocation getLocation(const SourceManager &SM) const {
1806 assert(Location.isValid());
1807 return Location;
1808 }
Mike Stump1eb44332009-09-09 15:08:12 +00001809 };
Ted Kremenekc887d132009-04-29 18:50:19 +00001810} // end anonymous namespace
1811
Jordy Rose20589562011-08-24 22:39:09 +00001812void CFRefReport::addGCModeDescription(const LangOptions &LOpts,
1813 bool GCEnabled) {
Jordy Rosef95b19d2011-08-24 20:38:42 +00001814 const char *GCModeDescription = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001815
Douglas Gregore289d812011-09-13 17:21:33 +00001816 switch (LOpts.getGC()) {
Anna Zaks7f2531c2011-08-22 20:31:28 +00001817 case LangOptions::GCOnly:
Jordy Rose20589562011-08-24 22:39:09 +00001818 assert(GCEnabled);
Jordy Rose35c86952011-08-24 05:47:39 +00001819 GCModeDescription = "Code is compiled to only use garbage collection";
1820 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001821
Anna Zaks7f2531c2011-08-22 20:31:28 +00001822 case LangOptions::NonGC:
Jordy Rose20589562011-08-24 22:39:09 +00001823 assert(!GCEnabled);
Jordy Rose35c86952011-08-24 05:47:39 +00001824 GCModeDescription = "Code is compiled to use reference counts";
1825 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001826
Anna Zaks7f2531c2011-08-22 20:31:28 +00001827 case LangOptions::HybridGC:
Jordy Rose20589562011-08-24 22:39:09 +00001828 if (GCEnabled) {
Jordy Rose35c86952011-08-24 05:47:39 +00001829 GCModeDescription = "Code is compiled to use either garbage collection "
1830 "(GC) or reference counts (non-GC). The bug occurs "
1831 "with GC enabled";
1832 break;
1833 } else {
1834 GCModeDescription = "Code is compiled to use either garbage collection "
1835 "(GC) or reference counts (non-GC). The bug occurs "
1836 "in non-GC mode";
1837 break;
Anna Zaks7f2531c2011-08-22 20:31:28 +00001838 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001839 }
Jordy Rose35c86952011-08-24 05:47:39 +00001840
Jordy Rosef95b19d2011-08-24 20:38:42 +00001841 assert(GCModeDescription && "invalid/unknown GC mode");
Jordy Rose35c86952011-08-24 05:47:39 +00001842 addExtraText(GCModeDescription);
Ted Kremenekc887d132009-04-29 18:50:19 +00001843}
1844
Jordy Rose910c4052011-09-02 06:44:22 +00001845// FIXME: This should be a method on SmallVector.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001846static inline bool contains(const SmallVectorImpl<ArgEffect>& V,
Ted Kremenekc887d132009-04-29 18:50:19 +00001847 ArgEffect X) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001848 for (SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
Ted Kremenekc887d132009-04-29 18:50:19 +00001849 I!=E; ++I)
1850 if (*I == X) return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001851
Ted Kremenekc887d132009-04-29 18:50:19 +00001852 return false;
1853}
1854
Jordy Rose70fdbc32012-05-12 05:10:43 +00001855static bool isNumericLiteralExpression(const Expr *E) {
1856 // FIXME: This set of cases was copied from SemaExprObjC.
1857 return isa<IntegerLiteral>(E) ||
1858 isa<CharacterLiteral>(E) ||
1859 isa<FloatingLiteral>(E) ||
1860 isa<ObjCBoolLiteralExpr>(E) ||
1861 isa<CXXBoolLiteralExpr>(E);
1862}
1863
Anna Zaksdc757b02011-08-19 23:21:56 +00001864PathDiagnosticPiece *CFRefReportVisitor::VisitNode(const ExplodedNode *N,
1865 const ExplodedNode *PrevN,
1866 BugReporterContext &BRC,
1867 BugReport &BR) {
Jordan Rose28038f32012-07-10 22:07:42 +00001868 // FIXME: We will eventually need to handle non-statement-based events
1869 // (__attribute__((cleanup))).
Jordy Rosef53e8c72011-08-23 19:43:16 +00001870 if (!isa<StmtPoint>(N->getLocation()))
Ted Kremenek2033a952009-05-13 07:12:33 +00001871 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001872
Ted Kremenek8966bc12009-05-06 21:39:49 +00001873 // Check if the type state has changed.
Ted Kremenek8bef8232012-01-26 21:29:00 +00001874 ProgramStateRef PrevSt = PrevN->getState();
1875 ProgramStateRef CurrSt = N->getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001876 const LocationContext *LCtx = N->getLocationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00001877
Anna Zaks8d6b43c2012-08-14 00:36:15 +00001878 const RefVal* CurrT = getRefBinding(CurrSt, Sym);
Ted Kremenekc887d132009-04-29 18:50:19 +00001879 if (!CurrT) return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001880
Ted Kremenekb65be702009-06-18 01:23:53 +00001881 const RefVal &CurrV = *CurrT;
Anna Zaks8d6b43c2012-08-14 00:36:15 +00001882 const RefVal *PrevT = getRefBinding(PrevSt, Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00001883
Ted Kremenekc887d132009-04-29 18:50:19 +00001884 // Create a string buffer to constain all the useful things we want
1885 // to tell the user.
1886 std::string sbuf;
1887 llvm::raw_string_ostream os(sbuf);
Mike Stump1eb44332009-09-09 15:08:12 +00001888
Ted Kremenekc887d132009-04-29 18:50:19 +00001889 // This is the allocation site since the previous node had no bindings
1890 // for this symbol.
1891 if (!PrevT) {
Jordy Rosef53e8c72011-08-23 19:43:16 +00001892 const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
Mike Stump1eb44332009-09-09 15:08:12 +00001893
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001894 if (isa<ObjCArrayLiteral>(S)) {
1895 os << "NSArray literal is an object with a +0 retain count";
Mike Stump1eb44332009-09-09 15:08:12 +00001896 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001897 else if (isa<ObjCDictionaryLiteral>(S)) {
1898 os << "NSDictionary literal is an object with a +0 retain count";
Ted Kremenekc887d132009-04-29 18:50:19 +00001899 }
Jordy Rose70fdbc32012-05-12 05:10:43 +00001900 else if (const ObjCBoxedExpr *BL = dyn_cast<ObjCBoxedExpr>(S)) {
1901 if (isNumericLiteralExpression(BL->getSubExpr()))
1902 os << "NSNumber literal is an object with a +0 retain count";
1903 else {
1904 const ObjCInterfaceDecl *BoxClass = 0;
1905 if (const ObjCMethodDecl *Method = BL->getBoxingMethod())
1906 BoxClass = Method->getClassInterface();
1907
1908 // We should always be able to find the boxing class interface,
1909 // but consider this future-proofing.
1910 if (BoxClass)
1911 os << *BoxClass << " b";
1912 else
1913 os << "B";
1914
1915 os << "oxed expression produces an object with a +0 retain count";
1916 }
1917 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001918 else {
1919 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
1920 // Get the name of the callee (if it is available).
1921 SVal X = CurrSt->getSValAsScalarOrLoc(CE->getCallee(), LCtx);
1922 if (const FunctionDecl *FD = X.getAsFunctionDecl())
1923 os << "Call to function '" << *FD << '\'';
1924 else
1925 os << "function call";
Ted Kremenekc887d132009-04-29 18:50:19 +00001926 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001927 else {
Jordan Rose8919e682012-07-18 21:59:51 +00001928 assert(isa<ObjCMessageExpr>(S));
Jordan Rosed563d3f2012-07-30 20:22:09 +00001929 CallEventManager &Mgr = CurrSt->getStateManager().getCallEventManager();
1930 CallEventRef<ObjCMethodCall> Call
1931 = Mgr.getObjCMethodCall(cast<ObjCMessageExpr>(S), CurrSt, LCtx);
1932
1933 switch (Call->getMessageKind()) {
Jordan Rose8919e682012-07-18 21:59:51 +00001934 case OCM_Message:
1935 os << "Method";
1936 break;
1937 case OCM_PropertyAccess:
1938 os << "Property";
1939 break;
1940 case OCM_Subscript:
1941 os << "Subscript";
1942 break;
1943 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001944 }
1945
1946 if (CurrV.getObjKind() == RetEffect::CF) {
1947 os << " returns a Core Foundation object with a ";
1948 }
1949 else {
1950 assert (CurrV.getObjKind() == RetEffect::ObjC);
1951 os << " returns an Objective-C object with a ";
1952 }
1953
1954 if (CurrV.isOwned()) {
1955 os << "+1 retain count";
1956
1957 if (GCEnabled) {
1958 assert(CurrV.getObjKind() == RetEffect::CF);
1959 os << ". "
1960 "Core Foundation objects are not automatically garbage collected.";
1961 }
1962 }
1963 else {
1964 assert (CurrV.isNotOwned());
1965 os << "+0 retain count";
1966 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001967 }
Mike Stump1eb44332009-09-09 15:08:12 +00001968
Anna Zaks220ac8c2011-09-15 01:08:34 +00001969 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
1970 N->getLocationContext());
Ted Kremenekc887d132009-04-29 18:50:19 +00001971 return new PathDiagnosticEventPiece(Pos, os.str());
1972 }
Mike Stump1eb44332009-09-09 15:08:12 +00001973
Ted Kremenekc887d132009-04-29 18:50:19 +00001974 // Gather up the effects that were performed on the object at this
1975 // program point
Chris Lattner5f9e2722011-07-23 10:55:15 +00001976 SmallVector<ArgEffect, 2> AEffects;
Mike Stump1eb44332009-09-09 15:08:12 +00001977
Jordy Roseec9ef852011-08-23 20:55:48 +00001978 const ExplodedNode *OrigNode = BRC.getNodeResolver().getOriginalNode(N);
1979 if (const RetainSummary *Summ = SummaryLog.lookup(OrigNode)) {
Ted Kremenekc887d132009-04-29 18:50:19 +00001980 // We only have summaries attached to nodes after evaluating CallExpr and
1981 // ObjCMessageExprs.
Jordy Rosef53e8c72011-08-23 19:43:16 +00001982 const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
Mike Stump1eb44332009-09-09 15:08:12 +00001983
Ted Kremenek5f85e172009-07-22 22:35:28 +00001984 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
Ted Kremenekc887d132009-04-29 18:50:19 +00001985 // Iterate through the parameter expressions and see if the symbol
1986 // was ever passed as an argument.
1987 unsigned i = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001988
Ted Kremenek5f85e172009-07-22 22:35:28 +00001989 for (CallExpr::const_arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
Ted Kremenekc887d132009-04-29 18:50:19 +00001990 AI!=AE; ++AI, ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00001991
Ted Kremenekc887d132009-04-29 18:50:19 +00001992 // Retrieve the value of the argument. Is it the symbol
1993 // we are interested in?
Ted Kremenek5eca4822012-01-06 22:09:28 +00001994 if (CurrSt->getSValAsScalarOrLoc(*AI, LCtx).getAsLocSymbol() != Sym)
Ted Kremenekc887d132009-04-29 18:50:19 +00001995 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001996
Ted Kremenekc887d132009-04-29 18:50:19 +00001997 // We have an argument. Get the effect!
1998 AEffects.push_back(Summ->getArg(i));
1999 }
2000 }
Mike Stump1eb44332009-09-09 15:08:12 +00002001 else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002002 if (const Expr *receiver = ME->getInstanceReceiver())
Ted Kremenek5eca4822012-01-06 22:09:28 +00002003 if (CurrSt->getSValAsScalarOrLoc(receiver, LCtx)
2004 .getAsLocSymbol() == Sym) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002005 // The symbol we are tracking is the receiver.
2006 AEffects.push_back(Summ->getReceiverEffect());
2007 }
2008 }
2009 }
Mike Stump1eb44332009-09-09 15:08:12 +00002010
Ted Kremenekc887d132009-04-29 18:50:19 +00002011 do {
2012 // Get the previous type state.
2013 RefVal PrevV = *PrevT;
Mike Stump1eb44332009-09-09 15:08:12 +00002014
Ted Kremenekc887d132009-04-29 18:50:19 +00002015 // Specially handle -dealloc.
Jordy Rose35c86952011-08-24 05:47:39 +00002016 if (!GCEnabled && contains(AEffects, Dealloc)) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002017 // Determine if the object's reference count was pushed to zero.
2018 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2019 // We may not have transitioned to 'release' if we hit an error.
2020 // This case is handled elsewhere.
2021 if (CurrV.getKind() == RefVal::Released) {
Ted Kremenekf21332e2009-05-08 20:01:42 +00002022 assert(CurrV.getCombinedCounts() == 0);
Ted Kremenekc887d132009-04-29 18:50:19 +00002023 os << "Object released by directly sending the '-dealloc' message";
2024 break;
2025 }
2026 }
Mike Stump1eb44332009-09-09 15:08:12 +00002027
Ted Kremenekc887d132009-04-29 18:50:19 +00002028 // Specially handle CFMakeCollectable and friends.
2029 if (contains(AEffects, MakeCollectable)) {
2030 // Get the name of the function.
Jordy Rosef53e8c72011-08-23 19:43:16 +00002031 const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
Ted Kremenek5eca4822012-01-06 22:09:28 +00002032 SVal X =
2033 CurrSt->getSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee(), LCtx);
Ted Kremenek9c378f72011-08-12 23:37:29 +00002034 const FunctionDecl *FD = X.getAsFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002035
Jordy Rose35c86952011-08-24 05:47:39 +00002036 if (GCEnabled) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002037 // Determine if the object's reference count was pushed to zero.
2038 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
Mike Stump1eb44332009-09-09 15:08:12 +00002039
Benjamin Kramerb8989f22011-10-14 18:45:37 +00002040 os << "In GC mode a call to '" << *FD
Ted Kremenekc887d132009-04-29 18:50:19 +00002041 << "' decrements an object's retain count and registers the "
2042 "object with the garbage collector. ";
Mike Stump1eb44332009-09-09 15:08:12 +00002043
Ted Kremenekc887d132009-04-29 18:50:19 +00002044 if (CurrV.getKind() == RefVal::Released) {
2045 assert(CurrV.getCount() == 0);
2046 os << "Since it now has a 0 retain count the object can be "
2047 "automatically collected by the garbage collector.";
2048 }
2049 else
2050 os << "An object must have a 0 retain count to be garbage collected. "
2051 "After this call its retain count is +" << CurrV.getCount()
2052 << '.';
2053 }
Mike Stump1eb44332009-09-09 15:08:12 +00002054 else
Benjamin Kramerb8989f22011-10-14 18:45:37 +00002055 os << "When GC is not enabled a call to '" << *FD
Ted Kremenekc887d132009-04-29 18:50:19 +00002056 << "' has no effect on its argument.";
Mike Stump1eb44332009-09-09 15:08:12 +00002057
Ted Kremenekc887d132009-04-29 18:50:19 +00002058 // Nothing more to say.
2059 break;
2060 }
Mike Stump1eb44332009-09-09 15:08:12 +00002061
2062 // Determine if the typestate has changed.
Ted Kremenekc887d132009-04-29 18:50:19 +00002063 if (!(PrevV == CurrV))
2064 switch (CurrV.getKind()) {
2065 case RefVal::Owned:
2066 case RefVal::NotOwned:
Mike Stump1eb44332009-09-09 15:08:12 +00002067
Ted Kremenekf21332e2009-05-08 20:01:42 +00002068 if (PrevV.getCount() == CurrV.getCount()) {
2069 // Did an autorelease message get sent?
2070 if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
2071 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002072
Zhongxing Xu264e9372009-05-12 10:10:00 +00002073 assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount());
Ted Kremenekeaedfea2009-05-10 05:11:21 +00002074 os << "Object sent -autorelease message";
Ted Kremenekf21332e2009-05-08 20:01:42 +00002075 break;
2076 }
Mike Stump1eb44332009-09-09 15:08:12 +00002077
Ted Kremenekc887d132009-04-29 18:50:19 +00002078 if (PrevV.getCount() > CurrV.getCount())
2079 os << "Reference count decremented.";
2080 else
2081 os << "Reference count incremented.";
Mike Stump1eb44332009-09-09 15:08:12 +00002082
Ted Kremenekc887d132009-04-29 18:50:19 +00002083 if (unsigned Count = CurrV.getCount())
2084 os << " The object now has a +" << Count << " retain count.";
Mike Stump1eb44332009-09-09 15:08:12 +00002085
Ted Kremenekc887d132009-04-29 18:50:19 +00002086 if (PrevV.getKind() == RefVal::Released) {
Jordy Rose35c86952011-08-24 05:47:39 +00002087 assert(GCEnabled && CurrV.getCount() > 0);
Jordy Rose74b7b2b2012-03-17 05:49:15 +00002088 os << " The object is not eligible for garbage collection until "
2089 "the retain count reaches 0 again.";
Ted Kremenekc887d132009-04-29 18:50:19 +00002090 }
Mike Stump1eb44332009-09-09 15:08:12 +00002091
Ted Kremenekc887d132009-04-29 18:50:19 +00002092 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002093
Ted Kremenekc887d132009-04-29 18:50:19 +00002094 case RefVal::Released:
2095 os << "Object released.";
2096 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002097
Ted Kremenekc887d132009-04-29 18:50:19 +00002098 case RefVal::ReturnedOwned:
Jordy Rose74b7b2b2012-03-17 05:49:15 +00002099 // Autoreleases can be applied after marking a node ReturnedOwned.
2100 if (CurrV.getAutoreleaseCount())
2101 return NULL;
2102
2103 os << "Object returned to caller as an owning reference (single "
2104 "retain count transferred to caller)";
Ted Kremenekc887d132009-04-29 18:50:19 +00002105 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002106
Ted Kremenekc887d132009-04-29 18:50:19 +00002107 case RefVal::ReturnedNotOwned:
Ted Kremenekf1365462011-05-26 18:45:44 +00002108 os << "Object returned to caller with a +0 retain count";
Ted Kremenekc887d132009-04-29 18:50:19 +00002109 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002110
Ted Kremenekc887d132009-04-29 18:50:19 +00002111 default:
2112 return NULL;
2113 }
Mike Stump1eb44332009-09-09 15:08:12 +00002114
Ted Kremenekc887d132009-04-29 18:50:19 +00002115 // Emit any remaining diagnostics for the argument effects (if any).
Chris Lattner5f9e2722011-07-23 10:55:15 +00002116 for (SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
Ted Kremenekc887d132009-04-29 18:50:19 +00002117 E=AEffects.end(); I != E; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +00002118
Ted Kremenekc887d132009-04-29 18:50:19 +00002119 // A bunch of things have alternate behavior under GC.
Jordy Rose35c86952011-08-24 05:47:39 +00002120 if (GCEnabled)
Ted Kremenekc887d132009-04-29 18:50:19 +00002121 switch (*I) {
2122 default: break;
2123 case Autorelease:
2124 os << "In GC mode an 'autorelease' has no effect.";
2125 continue;
2126 case IncRefMsg:
2127 os << "In GC mode the 'retain' message has no effect.";
2128 continue;
2129 case DecRefMsg:
2130 os << "In GC mode the 'release' message has no effect.";
2131 continue;
2132 }
2133 }
Mike Stump1eb44332009-09-09 15:08:12 +00002134 } while (0);
2135
Ted Kremenekc887d132009-04-29 18:50:19 +00002136 if (os.str().empty())
2137 return 0; // We have nothing to say!
Ted Kremenek2033a952009-05-13 07:12:33 +00002138
Jordy Rosef53e8c72011-08-23 19:43:16 +00002139 const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
Anna Zaks220ac8c2011-09-15 01:08:34 +00002140 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
2141 N->getLocationContext());
Ted Kremenek9c378f72011-08-12 23:37:29 +00002142 PathDiagnosticPiece *P = new PathDiagnosticEventPiece(Pos, os.str());
Mike Stump1eb44332009-09-09 15:08:12 +00002143
Ted Kremenekc887d132009-04-29 18:50:19 +00002144 // Add the range by scanning the children of the statement for any bindings
2145 // to Sym.
Mike Stump1eb44332009-09-09 15:08:12 +00002146 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
Ted Kremenek5f85e172009-07-22 22:35:28 +00002147 I!=E; ++I)
Ted Kremenek9c378f72011-08-12 23:37:29 +00002148 if (const Expr *Exp = dyn_cast_or_null<Expr>(*I))
Ted Kremenek5eca4822012-01-06 22:09:28 +00002149 if (CurrSt->getSValAsScalarOrLoc(Exp, LCtx).getAsLocSymbol() == Sym) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002150 P->addRange(Exp->getSourceRange());
2151 break;
2152 }
Mike Stump1eb44332009-09-09 15:08:12 +00002153
Ted Kremenekc887d132009-04-29 18:50:19 +00002154 return P;
2155}
2156
Anna Zakse7e01682012-02-28 22:39:22 +00002157// Find the first node in the current function context that referred to the
2158// tracked symbol and the memory location that value was stored to. Note, the
2159// value is only reported if the allocation occurred in the same function as
2160// the leak.
Zhongxing Xuc5619d92009-08-06 01:32:16 +00002161static std::pair<const ExplodedNode*,const MemRegion*>
Ted Kremenek18c66fd2011-08-15 22:09:50 +00002162GetAllocationSite(ProgramStateManager& StateMgr, const ExplodedNode *N,
Ted Kremenekc887d132009-04-29 18:50:19 +00002163 SymbolRef Sym) {
Ted Kremenek9c378f72011-08-12 23:37:29 +00002164 const ExplodedNode *Last = N;
Mike Stump1eb44332009-09-09 15:08:12 +00002165 const MemRegion* FirstBinding = 0;
Anna Zakse7e01682012-02-28 22:39:22 +00002166 const LocationContext *LeakContext = N->getLocationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002167
Ted Kremenekc887d132009-04-29 18:50:19 +00002168 while (N) {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002169 ProgramStateRef St = N->getState();
Mike Stump1eb44332009-09-09 15:08:12 +00002170
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002171 if (!getRefBinding(St, Sym))
Ted Kremenekc887d132009-04-29 18:50:19 +00002172 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002173
Anna Zaks27b867e2012-03-21 19:45:01 +00002174 StoreManager::FindUniqueBinding FB(Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002175 StateMgr.iterBindings(St, FB);
2176 if (FB) FirstBinding = FB.getRegion();
2177
Anna Zakse7e01682012-02-28 22:39:22 +00002178 // Allocation node, is the last node in the current context in which the
2179 // symbol was tracked.
2180 if (N->getLocationContext() == LeakContext)
2181 Last = N;
2182
Mike Stump1eb44332009-09-09 15:08:12 +00002183 N = N->pred_empty() ? NULL : *(N->pred_begin());
Ted Kremenekc887d132009-04-29 18:50:19 +00002184 }
Mike Stump1eb44332009-09-09 15:08:12 +00002185
Anna Zakse7e01682012-02-28 22:39:22 +00002186 // If allocation happened in a function different from the leak node context,
2187 // do not report the binding.
2188 if (N->getLocationContext() != LeakContext) {
2189 FirstBinding = 0;
2190 }
2191
Ted Kremenekc887d132009-04-29 18:50:19 +00002192 return std::make_pair(Last, FirstBinding);
2193}
2194
2195PathDiagnosticPiece*
Anna Zaks23f395e2011-08-20 01:27:22 +00002196CFRefReportVisitor::getEndPath(BugReporterContext &BRC,
2197 const ExplodedNode *EndN,
2198 BugReport &BR) {
Ted Kremenek76aadc32012-03-09 01:13:14 +00002199 BR.markInteresting(Sym);
Anna Zaks23f395e2011-08-20 01:27:22 +00002200 return BugReporterVisitor::getDefaultEndPath(BRC, EndN, BR);
Ted Kremenekc887d132009-04-29 18:50:19 +00002201}
2202
2203PathDiagnosticPiece*
Anna Zaks23f395e2011-08-20 01:27:22 +00002204CFRefLeakReportVisitor::getEndPath(BugReporterContext &BRC,
2205 const ExplodedNode *EndN,
2206 BugReport &BR) {
Mike Stump1eb44332009-09-09 15:08:12 +00002207
Ted Kremenek8966bc12009-05-06 21:39:49 +00002208 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenekc887d132009-04-29 18:50:19 +00002209 // assigned to different variables, etc.
Ted Kremenek76aadc32012-03-09 01:13:14 +00002210 BR.markInteresting(Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002211
Ted Kremenekc887d132009-04-29 18:50:19 +00002212 // We are reporting a leak. Walk up the graph to get to the first node where
2213 // the symbol appeared, and also get the first VarDecl that tracked object
2214 // is stored to.
Ted Kremenek9c378f72011-08-12 23:37:29 +00002215 const ExplodedNode *AllocNode = 0;
Ted Kremenekc887d132009-04-29 18:50:19 +00002216 const MemRegion* FirstBinding = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002217
Ted Kremenekc887d132009-04-29 18:50:19 +00002218 llvm::tie(AllocNode, FirstBinding) =
Ted Kremenekf04dced2009-05-08 23:32:51 +00002219 GetAllocationSite(BRC.getStateManager(), EndN, Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002220
Anna Zaks4fdf97b2011-09-15 18:56:07 +00002221 SourceManager& SM = BRC.getSourceManager();
Mike Stump1eb44332009-09-09 15:08:12 +00002222
Ted Kremenekc887d132009-04-29 18:50:19 +00002223 // Compute an actual location for the leak. Sometimes a leak doesn't
2224 // occur at an actual statement (e.g., transition between blocks; end
2225 // of function) so we need to walk the graph and compute a real location.
Ted Kremenek9c378f72011-08-12 23:37:29 +00002226 const ExplodedNode *LeakN = EndN;
Anna Zaks4fdf97b2011-09-15 18:56:07 +00002227 PathDiagnosticLocation L = PathDiagnosticLocation::createEndOfPath(LeakN, SM);
Mike Stump1eb44332009-09-09 15:08:12 +00002228
Ted Kremenekc887d132009-04-29 18:50:19 +00002229 std::string sbuf;
2230 llvm::raw_string_ostream os(sbuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002231
Ted Kremenekf1365462011-05-26 18:45:44 +00002232 os << "Object leaked: ";
Mike Stump1eb44332009-09-09 15:08:12 +00002233
Ted Kremenekf1365462011-05-26 18:45:44 +00002234 if (FirstBinding) {
2235 os << "object allocated and stored into '"
2236 << FirstBinding->getString() << '\'';
2237 }
2238 else
2239 os << "allocated object";
Mike Stump1eb44332009-09-09 15:08:12 +00002240
Ted Kremenekc887d132009-04-29 18:50:19 +00002241 // Get the retain count.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002242 const RefVal* RV = getRefBinding(EndN->getState(), Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002243
Ted Kremenekc887d132009-04-29 18:50:19 +00002244 if (RV->getKind() == RefVal::ErrorLeakReturned) {
2245 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
Jordy Rose5b5402b2011-07-15 22:17:54 +00002246 // objects. Only "copy", "alloc", "retain" and "new" transfer ownership
Ted Kremenekc887d132009-04-29 18:50:19 +00002247 // to the caller for NS objects.
Ted Kremenekd368d712011-05-25 06:19:45 +00002248 const Decl *D = &EndN->getCodeDecl();
2249 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2250 os << " is returned from a method whose name ('"
2251 << MD->getSelector().getAsString()
2252 << "') does not start with 'copy', 'mutableCopy', 'alloc' or 'new'."
Jordy Rose5b5402b2011-07-15 22:17:54 +00002253 " This violates the naming convention rules"
Ted Kremenekf1365462011-05-26 18:45:44 +00002254 " given in the Memory Management Guide for Cocoa";
Ted Kremenekd368d712011-05-25 06:19:45 +00002255 }
2256 else {
2257 const FunctionDecl *FD = cast<FunctionDecl>(D);
Ted Kremenekb7dcddf2011-12-22 06:35:52 +00002258 os << " is returned from a function whose name ('"
Benjamin Kramera59d20b2012-02-07 11:57:57 +00002259 << *FD
Ted Kremenekd368d712011-05-25 06:19:45 +00002260 << "') does not contain 'Copy' or 'Create'. This violates the naming"
Ted Kremenekb7dcddf2011-12-22 06:35:52 +00002261 " convention rules given in the Memory Management Guide for Core"
Ted Kremenekf1365462011-05-26 18:45:44 +00002262 " Foundation";
Ted Kremenekd368d712011-05-25 06:19:45 +00002263 }
Ted Kremenekc887d132009-04-29 18:50:19 +00002264 }
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002265 else if (RV->getKind() == RefVal::ErrorGCLeakReturned) {
Ted Kremenek9c378f72011-08-12 23:37:29 +00002266 ObjCMethodDecl &MD = cast<ObjCMethodDecl>(EndN->getCodeDecl());
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002267 os << " and returned from method '" << MD.getSelector().getAsString()
Ted Kremenek82f2be52009-05-10 16:52:15 +00002268 << "' is potentially leaked when using garbage collection. Callers "
2269 "of this method do not expect a returned object with a +1 retain "
2270 "count since they expect the object to be managed by the garbage "
2271 "collector";
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002272 }
Ted Kremenekc887d132009-04-29 18:50:19 +00002273 else
Ted Kremenekabf517c2010-10-15 22:50:23 +00002274 os << " is not referenced later in this execution path and has a retain "
Ted Kremenekf1365462011-05-26 18:45:44 +00002275 "count of +" << RV->getCount();
Mike Stump1eb44332009-09-09 15:08:12 +00002276
Ted Kremenekc887d132009-04-29 18:50:19 +00002277 return new PathDiagnosticEventPiece(L, os.str());
2278}
2279
Jordy Rose20589562011-08-24 22:39:09 +00002280CFRefLeakReport::CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts,
2281 bool GCEnabled, const SummaryLogTy &Log,
2282 ExplodedNode *n, SymbolRef sym,
Anna Zaks6a93bd52011-10-25 19:57:11 +00002283 CheckerContext &Ctx)
Jordy Rose20589562011-08-24 22:39:09 +00002284: CFRefReport(D, LOpts, GCEnabled, Log, n, sym, false) {
Mike Stump1eb44332009-09-09 15:08:12 +00002285
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00002286 // Most bug reports are cached at the location where they occurred.
Ted Kremenekc887d132009-04-29 18:50:19 +00002287 // With leaks, we want to unique them by the location where they were
2288 // allocated, and only report a single path. To do this, we need to find
2289 // the allocation site of a piece of tracked memory, which we do via a
2290 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2291 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2292 // that all ancestor nodes that represent the allocation site have the
2293 // same SourceLocation.
Ted Kremenek9c378f72011-08-12 23:37:29 +00002294 const ExplodedNode *AllocNode = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002295
Anna Zaks6a93bd52011-10-25 19:57:11 +00002296 const SourceManager& SMgr = Ctx.getSourceManager();
Anna Zaks590dd8e2011-09-20 21:38:35 +00002297
Ted Kremenekc887d132009-04-29 18:50:19 +00002298 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding.
Anna Zaks6a93bd52011-10-25 19:57:11 +00002299 GetAllocationSite(Ctx.getStateManager(), getErrorNode(), sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002300
Ted Kremenekc887d132009-04-29 18:50:19 +00002301 // Get the SourceLocation for the allocation site.
Jordan Rose852aa0d2012-07-10 22:07:52 +00002302 // FIXME: This will crash the analyzer if an allocation comes from an
2303 // implicit call. (Currently there are no such allocations in Cocoa, though.)
2304 const Stmt *AllocStmt;
Ted Kremenekc887d132009-04-29 18:50:19 +00002305 ProgramPoint P = AllocNode->getLocation();
Jordan Rose852aa0d2012-07-10 22:07:52 +00002306 if (CallExitEnd *Exit = dyn_cast<CallExitEnd>(&P))
2307 AllocStmt = Exit->getCalleeContext()->getCallSite();
2308 else
2309 AllocStmt = cast<PostStmt>(P).getStmt();
2310 assert(AllocStmt && "All allocations must come from explicit calls");
Anna Zaks590dd8e2011-09-20 21:38:35 +00002311 Location = PathDiagnosticLocation::createBegin(AllocStmt, SMgr,
2312 n->getLocationContext());
Ted Kremenekc887d132009-04-29 18:50:19 +00002313 // Fill in the description of the bug.
2314 Description.clear();
2315 llvm::raw_string_ostream os(Description);
Ted Kremenekdd924e22009-05-02 19:05:19 +00002316 os << "Potential leak ";
Jordy Rose20589562011-08-24 22:39:09 +00002317 if (GCEnabled)
Ted Kremenekdd924e22009-05-02 19:05:19 +00002318 os << "(when using garbage collection) ";
Anna Zaks212000e2012-02-28 21:49:08 +00002319 os << "of an object";
Mike Stump1eb44332009-09-09 15:08:12 +00002320
Ted Kremenekc887d132009-04-29 18:50:19 +00002321 // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2322 if (AllocBinding)
Anna Zaks212000e2012-02-28 21:49:08 +00002323 os << " stored into '" << AllocBinding->getString() << '\'';
Anna Zaksdc757b02011-08-19 23:21:56 +00002324
Jordy Rose20589562011-08-24 22:39:09 +00002325 addVisitor(new CFRefLeakReportVisitor(sym, GCEnabled, Log));
Ted Kremenekc887d132009-04-29 18:50:19 +00002326}
2327
2328//===----------------------------------------------------------------------===//
2329// Main checker logic.
2330//===----------------------------------------------------------------------===//
2331
Ted Kremenekd593eb92009-11-25 22:17:44 +00002332namespace {
Jordy Rose910c4052011-09-02 06:44:22 +00002333class RetainCountChecker
Jordy Rose9c083b72011-08-24 18:56:32 +00002334 : public Checker< check::Bind,
Jordy Rose38f17d62011-08-23 19:01:07 +00002335 check::DeadSymbols,
Jordy Rose9c083b72011-08-24 18:56:32 +00002336 check::EndAnalysis,
Jordy Rose38f17d62011-08-23 19:01:07 +00002337 check::EndPath,
Jordy Rose67044292011-08-17 21:27:39 +00002338 check::PostStmt<BlockExpr>,
John McCallf85e1932011-06-15 23:02:42 +00002339 check::PostStmt<CastExpr>,
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002340 check::PostStmt<ObjCArrayLiteral>,
2341 check::PostStmt<ObjCDictionaryLiteral>,
Jordy Rose70fdbc32012-05-12 05:10:43 +00002342 check::PostStmt<ObjCBoxedExpr>,
Jordan Rosefe6a0112012-07-02 19:28:21 +00002343 check::PostCall,
Jordy Rosef53e8c72011-08-23 19:43:16 +00002344 check::PreStmt<ReturnStmt>,
Jordy Rose67044292011-08-17 21:27:39 +00002345 check::RegionChanges,
Jordy Rose76c506f2011-08-21 21:58:18 +00002346 eval::Assume,
2347 eval::Call > {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002348 mutable OwningPtr<CFRefBug> useAfterRelease, releaseNotOwned;
2349 mutable OwningPtr<CFRefBug> deallocGC, deallocNotOwned;
2350 mutable OwningPtr<CFRefBug> overAutorelease, returnNotOwnedForOwned;
2351 mutable OwningPtr<CFRefBug> leakWithinFunction, leakAtReturn;
2352 mutable OwningPtr<CFRefBug> leakWithinFunctionGC, leakAtReturnGC;
Jordy Rose38f17d62011-08-23 19:01:07 +00002353
2354 typedef llvm::DenseMap<SymbolRef, const SimpleProgramPointTag *> SymbolTagMap;
2355
2356 // This map is only used to ensure proper deletion of any allocated tags.
2357 mutable SymbolTagMap DeadSymbolTags;
2358
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002359 mutable OwningPtr<RetainSummaryManager> Summaries;
2360 mutable OwningPtr<RetainSummaryManager> SummariesGC;
Jordy Rose9c083b72011-08-24 18:56:32 +00002361 mutable SummaryLogTy SummaryLog;
2362 mutable bool ShouldResetSummaryLog;
2363
Jordy Rose2f9a66d2011-08-20 21:17:59 +00002364public:
Jordy Rose910c4052011-09-02 06:44:22 +00002365 RetainCountChecker() : ShouldResetSummaryLog(false) {}
Jordy Rose38f17d62011-08-23 19:01:07 +00002366
Jordy Rose910c4052011-09-02 06:44:22 +00002367 virtual ~RetainCountChecker() {
Jordy Rose38f17d62011-08-23 19:01:07 +00002368 DeleteContainerSeconds(DeadSymbolTags);
2369 }
2370
Jordy Rose9c083b72011-08-24 18:56:32 +00002371 void checkEndAnalysis(ExplodedGraph &G, BugReporter &BR,
2372 ExprEngine &Eng) const {
2373 // FIXME: This is a hack to make sure the summary log gets cleared between
2374 // analyses of different code bodies.
2375 //
2376 // Why is this necessary? Because a checker's lifetime is tied to a
2377 // translation unit, but an ExplodedGraph's lifetime is just a code body.
2378 // Once in a blue moon, a new ExplodedNode will have the same address as an
2379 // old one with an associated summary, and the bug report visitor gets very
2380 // confused. (To make things worse, the summary lifetime is currently also
2381 // tied to a code body, so we get a crash instead of incorrect results.)
Jordy Rose1ab51c72011-08-24 09:27:24 +00002382 //
2383 // Why is this a bad solution? Because if the lifetime of the ExplodedGraph
2384 // changes, things will start going wrong again. Really the lifetime of this
2385 // log needs to be tied to either the specific nodes in it or the entire
2386 // ExplodedGraph, not to a specific part of the code being analyzed.
2387 //
Jordy Rose9c083b72011-08-24 18:56:32 +00002388 // (Also, having stateful local data means that the same checker can't be
2389 // used from multiple threads, but a lot of checkers have incorrect
2390 // assumptions about that anyway. So that wasn't a priority at the time of
2391 // this fix.)
Jordy Rose1ab51c72011-08-24 09:27:24 +00002392 //
Jordy Rose9c083b72011-08-24 18:56:32 +00002393 // This happens at the end of analysis, but bug reports are emitted /after/
2394 // this point. So we can't just clear the summary log now. Instead, we mark
2395 // that the next time we access the summary log, it should be cleared.
2396
2397 // If we never reset the summary log during /this/ code body analysis,
2398 // there were no new summaries. There might still have been summaries from
2399 // the /last/ analysis, so clear them out to make sure the bug report
2400 // visitors don't get confused.
2401 if (ShouldResetSummaryLog)
2402 SummaryLog.clear();
2403
2404 ShouldResetSummaryLog = !SummaryLog.empty();
Jordy Rose1ab51c72011-08-24 09:27:24 +00002405 }
2406
Jordy Rose17a38e22011-09-02 05:55:19 +00002407 CFRefBug *getLeakWithinFunctionBug(const LangOptions &LOpts,
2408 bool GCEnabled) const {
2409 if (GCEnabled) {
Jordy Rosedb92bb62011-08-25 01:14:38 +00002410 if (!leakWithinFunctionGC)
Benjamin Kramerfacde172012-06-06 17:32:50 +00002411 leakWithinFunctionGC.reset(new Leak("Leak of object when using "
2412 "garbage collection"));
Jordy Rose17a38e22011-09-02 05:55:19 +00002413 return leakWithinFunctionGC.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002414 } else {
2415 if (!leakWithinFunction) {
Douglas Gregore289d812011-09-13 17:21:33 +00002416 if (LOpts.getGC() == LangOptions::HybridGC) {
Benjamin Kramerfacde172012-06-06 17:32:50 +00002417 leakWithinFunction.reset(new Leak("Leak of object when not using "
2418 "garbage collection (GC) in "
2419 "dual GC/non-GC code"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002420 } else {
Benjamin Kramerfacde172012-06-06 17:32:50 +00002421 leakWithinFunction.reset(new Leak("Leak"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002422 }
2423 }
Jordy Rose17a38e22011-09-02 05:55:19 +00002424 return leakWithinFunction.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002425 }
2426 }
2427
Jordy Rose17a38e22011-09-02 05:55:19 +00002428 CFRefBug *getLeakAtReturnBug(const LangOptions &LOpts, bool GCEnabled) const {
2429 if (GCEnabled) {
Jordy Rosedb92bb62011-08-25 01:14:38 +00002430 if (!leakAtReturnGC)
Benjamin Kramerfacde172012-06-06 17:32:50 +00002431 leakAtReturnGC.reset(new Leak("Leak of returned object when using "
2432 "garbage collection"));
Jordy Rose17a38e22011-09-02 05:55:19 +00002433 return leakAtReturnGC.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002434 } else {
2435 if (!leakAtReturn) {
Douglas Gregore289d812011-09-13 17:21:33 +00002436 if (LOpts.getGC() == LangOptions::HybridGC) {
Benjamin Kramerfacde172012-06-06 17:32:50 +00002437 leakAtReturn.reset(new Leak("Leak of returned object when not using "
2438 "garbage collection (GC) in dual "
2439 "GC/non-GC code"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002440 } else {
Benjamin Kramerfacde172012-06-06 17:32:50 +00002441 leakAtReturn.reset(new Leak("Leak of returned object"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002442 }
2443 }
Jordy Rose17a38e22011-09-02 05:55:19 +00002444 return leakAtReturn.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002445 }
2446 }
2447
Jordy Rose17a38e22011-09-02 05:55:19 +00002448 RetainSummaryManager &getSummaryManager(ASTContext &Ctx,
2449 bool GCEnabled) const {
2450 // FIXME: We don't support ARC being turned on and off during one analysis.
2451 // (nor, for that matter, do we support changing ASTContexts)
David Blaikie4e4d0842012-03-11 07:00:24 +00002452 bool ARCEnabled = (bool)Ctx.getLangOpts().ObjCAutoRefCount;
Jordy Rose17a38e22011-09-02 05:55:19 +00002453 if (GCEnabled) {
2454 if (!SummariesGC)
Jordy Roseb6cfc092011-08-25 00:10:37 +00002455 SummariesGC.reset(new RetainSummaryManager(Ctx, true, ARCEnabled));
Jordy Rose17a38e22011-09-02 05:55:19 +00002456 else
2457 assert(SummariesGC->isARCEnabled() == ARCEnabled);
Jordy Roseb6cfc092011-08-25 00:10:37 +00002458 return *SummariesGC;
2459 } else {
Jordy Rose17a38e22011-09-02 05:55:19 +00002460 if (!Summaries)
Jordy Roseb6cfc092011-08-25 00:10:37 +00002461 Summaries.reset(new RetainSummaryManager(Ctx, false, ARCEnabled));
Jordy Rose17a38e22011-09-02 05:55:19 +00002462 else
2463 assert(Summaries->isARCEnabled() == ARCEnabled);
Jordy Roseb6cfc092011-08-25 00:10:37 +00002464 return *Summaries;
2465 }
2466 }
2467
Jordy Rose17a38e22011-09-02 05:55:19 +00002468 RetainSummaryManager &getSummaryManager(CheckerContext &C) const {
2469 return getSummaryManager(C.getASTContext(), C.isObjCGCEnabled());
2470 }
2471
Ted Kremenek8bef8232012-01-26 21:29:00 +00002472 void printState(raw_ostream &Out, ProgramStateRef State,
Jordy Rosedbd658e2011-08-28 19:11:56 +00002473 const char *NL, const char *Sep) const;
2474
Anna Zaks390909c2011-10-06 00:43:15 +00002475 void checkBind(SVal loc, SVal val, const Stmt *S, CheckerContext &C) const;
Jordy Roseab027fd2011-08-20 21:16:58 +00002476 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
2477 void checkPostStmt(const CastExpr *CE, CheckerContext &C) const;
John McCallf85e1932011-06-15 23:02:42 +00002478
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002479 void checkPostStmt(const ObjCArrayLiteral *AL, CheckerContext &C) const;
2480 void checkPostStmt(const ObjCDictionaryLiteral *DL, CheckerContext &C) const;
Jordy Rose70fdbc32012-05-12 05:10:43 +00002481 void checkPostStmt(const ObjCBoxedExpr *BE, CheckerContext &C) const;
2482
Jordan Rosefe6a0112012-07-02 19:28:21 +00002483 void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002484
Jordan Rose4531b7d2012-07-02 19:27:43 +00002485 void checkSummary(const RetainSummary &Summ, const CallEvent &Call,
Jordy Rosee38dd952011-08-28 05:16:28 +00002486 CheckerContext &C) const;
Jordy Rose294396b2011-08-22 23:48:23 +00002487
Jordy Rose76c506f2011-08-21 21:58:18 +00002488 bool evalCall(const CallExpr *CE, CheckerContext &C) const;
2489
Ted Kremenek8bef8232012-01-26 21:29:00 +00002490 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Jordy Roseab027fd2011-08-20 21:16:58 +00002491 bool Assumption) const;
Jordy Rose67044292011-08-17 21:27:39 +00002492
Ted Kremenek8bef8232012-01-26 21:29:00 +00002493 ProgramStateRef
2494 checkRegionChanges(ProgramStateRef state,
Jordy Rose537716a2011-08-27 22:51:26 +00002495 const StoreManager::InvalidatedSymbols *invalidated,
2496 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00002497 ArrayRef<const MemRegion *> Regions,
Jordan Rose740d4902012-07-02 19:27:35 +00002498 const CallEvent *Call) const;
Jordy Roseab027fd2011-08-20 21:16:58 +00002499
Ted Kremenek8bef8232012-01-26 21:29:00 +00002500 bool wantsRegionChangeUpdate(ProgramStateRef state) const {
Jordy Rose2f9a66d2011-08-20 21:17:59 +00002501 return true;
Jordy Roseab027fd2011-08-20 21:16:58 +00002502 }
Jordy Rose294396b2011-08-22 23:48:23 +00002503
Jordy Rosef53e8c72011-08-23 19:43:16 +00002504 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
2505 void checkReturnWithRetEffect(const ReturnStmt *S, CheckerContext &C,
2506 ExplodedNode *Pred, RetEffect RE, RefVal X,
Ted Kremenek8bef8232012-01-26 21:29:00 +00002507 SymbolRef Sym, ProgramStateRef state) const;
Jordy Rosef53e8c72011-08-23 19:43:16 +00002508
Jordy Rose38f17d62011-08-23 19:01:07 +00002509 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Anna Zaksaf498a22011-10-25 19:56:48 +00002510 void checkEndPath(CheckerContext &C) const;
Jordy Rose38f17d62011-08-23 19:01:07 +00002511
Ted Kremenek8bef8232012-01-26 21:29:00 +00002512 ProgramStateRef updateSymbol(ProgramStateRef state, SymbolRef sym,
Jordy Rose17a38e22011-09-02 05:55:19 +00002513 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
2514 CheckerContext &C) const;
Jordy Rosee0a5d322011-08-23 20:27:16 +00002515
Ted Kremenek8bef8232012-01-26 21:29:00 +00002516 void processNonLeakError(ProgramStateRef St, SourceRange ErrorRange,
Jordy Rose294396b2011-08-22 23:48:23 +00002517 RefVal::Kind ErrorKind, SymbolRef Sym,
2518 CheckerContext &C) const;
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002519
2520 void processObjCLiterals(CheckerContext &C, const Expr *Ex) const;
Jordy Rose294396b2011-08-22 23:48:23 +00002521
Jordy Rose38f17d62011-08-23 19:01:07 +00002522 const ProgramPointTag *getDeadSymbolTag(SymbolRef sym) const;
2523
Ted Kremenek8bef8232012-01-26 21:29:00 +00002524 ProgramStateRef handleSymbolDeath(ProgramStateRef state,
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002525 SymbolRef sid, RefVal V,
2526 SmallVectorImpl<SymbolRef> &Leaked) const;
Jordy Rose38f17d62011-08-23 19:01:07 +00002527
Ted Kremenek8bef8232012-01-26 21:29:00 +00002528 std::pair<ExplodedNode *, ProgramStateRef >
Jordan Rose2bce86c2012-08-18 00:30:16 +00002529 handleAutoreleaseCounts(ProgramStateRef state, ExplodedNode *Pred,
2530 const ProgramPointTag *Tag, CheckerContext &Ctx,
2531 SymbolRef Sym, RefVal V) const;
Jordy Rose8d228632011-08-23 20:07:14 +00002532
Ted Kremenek8bef8232012-01-26 21:29:00 +00002533 ExplodedNode *processLeaks(ProgramStateRef state,
Jordy Rose38f17d62011-08-23 19:01:07 +00002534 SmallVectorImpl<SymbolRef> &Leaked,
Anna Zaks6a93bd52011-10-25 19:57:11 +00002535 CheckerContext &Ctx,
Jordy Rose38f17d62011-08-23 19:01:07 +00002536 ExplodedNode *Pred = 0) const;
Ted Kremenekd593eb92009-11-25 22:17:44 +00002537};
2538} // end anonymous namespace
2539
Jordy Rose67044292011-08-17 21:27:39 +00002540namespace {
2541class StopTrackingCallback : public SymbolVisitor {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002542 ProgramStateRef state;
Jordy Rose67044292011-08-17 21:27:39 +00002543public:
Ted Kremenek8bef8232012-01-26 21:29:00 +00002544 StopTrackingCallback(ProgramStateRef st) : state(st) {}
2545 ProgramStateRef getState() const { return state; }
Jordy Rose67044292011-08-17 21:27:39 +00002546
2547 bool VisitSymbol(SymbolRef sym) {
2548 state = state->remove<RefBindings>(sym);
2549 return true;
2550 }
2551};
2552} // end anonymous namespace
2553
Jordy Rose910c4052011-09-02 06:44:22 +00002554//===----------------------------------------------------------------------===//
2555// Handle statements that may have an effect on refcounts.
2556//===----------------------------------------------------------------------===//
Jordy Rose67044292011-08-17 21:27:39 +00002557
Jordy Rose910c4052011-09-02 06:44:22 +00002558void RetainCountChecker::checkPostStmt(const BlockExpr *BE,
2559 CheckerContext &C) const {
Jordy Rose67044292011-08-17 21:27:39 +00002560
Jordy Rose910c4052011-09-02 06:44:22 +00002561 // Scan the BlockDecRefExprs for any object the retain count checker
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002562 // may be tracking.
John McCall469a1eb2011-02-02 13:00:07 +00002563 if (!BE->getBlockDecl()->hasCaptures())
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002564 return;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002565
Ted Kremenek8bef8232012-01-26 21:29:00 +00002566 ProgramStateRef state = C.getState();
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002567 const BlockDataRegion *R =
Ted Kremenek5eca4822012-01-06 22:09:28 +00002568 cast<BlockDataRegion>(state->getSVal(BE,
2569 C.getLocationContext()).getAsRegion());
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002570
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002571 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
2572 E = R->referenced_vars_end();
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002573
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002574 if (I == E)
2575 return;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002576
Ted Kremenek67d12872009-12-07 22:05:27 +00002577 // FIXME: For now we invalidate the tracking of all symbols passed to blocks
2578 // via captured variables, even though captured variables result in a copy
2579 // and in implicit increment/decrement of a retain count.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002580 SmallVector<const MemRegion*, 10> Regions;
Anna Zaks39ac1872011-10-26 21:06:44 +00002581 const LocationContext *LC = C.getLocationContext();
Ted Kremenekc8413fd2010-12-02 07:49:45 +00002582 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002583
Ted Kremenek67d12872009-12-07 22:05:27 +00002584 for ( ; I != E; ++I) {
2585 const VarRegion *VR = *I;
2586 if (VR->getSuperRegion() == R) {
2587 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2588 }
2589 Regions.push_back(VR);
2590 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002591
Ted Kremenek67d12872009-12-07 22:05:27 +00002592 state =
2593 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
2594 Regions.data() + Regions.size()).getState();
Anna Zaks0bd6b112011-10-26 21:06:34 +00002595 C.addTransition(state);
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002596}
2597
Jordy Rose910c4052011-09-02 06:44:22 +00002598void RetainCountChecker::checkPostStmt(const CastExpr *CE,
2599 CheckerContext &C) const {
John McCallf85e1932011-06-15 23:02:42 +00002600 const ObjCBridgedCastExpr *BE = dyn_cast<ObjCBridgedCastExpr>(CE);
2601 if (!BE)
2602 return;
2603
John McCall71c482c2011-06-17 06:50:50 +00002604 ArgEffect AE = IncRef;
John McCallf85e1932011-06-15 23:02:42 +00002605
2606 switch (BE->getBridgeKind()) {
2607 case clang::OBC_Bridge:
2608 // Do nothing.
2609 return;
2610 case clang::OBC_BridgeRetained:
2611 AE = IncRef;
2612 break;
2613 case clang::OBC_BridgeTransfer:
2614 AE = DecRefBridgedTransfered;
2615 break;
2616 }
2617
Ted Kremenek8bef8232012-01-26 21:29:00 +00002618 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00002619 SymbolRef Sym = state->getSVal(CE, C.getLocationContext()).getAsLocSymbol();
John McCallf85e1932011-06-15 23:02:42 +00002620 if (!Sym)
2621 return;
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002622 const RefVal* T = getRefBinding(state, Sym);
John McCallf85e1932011-06-15 23:02:42 +00002623 if (!T)
2624 return;
2625
John McCallf85e1932011-06-15 23:02:42 +00002626 RefVal::Kind hasErr = (RefVal::Kind) 0;
Jordy Rose17a38e22011-09-02 05:55:19 +00002627 state = updateSymbol(state, Sym, *T, AE, hasErr, C);
John McCallf85e1932011-06-15 23:02:42 +00002628
2629 if (hasErr) {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002630 // FIXME: If we get an error during a bridge cast, should we report it?
2631 // Should we assert that there is no error?
John McCallf85e1932011-06-15 23:02:42 +00002632 return;
2633 }
2634
Anna Zaks0bd6b112011-10-26 21:06:34 +00002635 C.addTransition(state);
John McCallf85e1932011-06-15 23:02:42 +00002636}
2637
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002638void RetainCountChecker::processObjCLiterals(CheckerContext &C,
2639 const Expr *Ex) const {
2640 ProgramStateRef state = C.getState();
2641 const ExplodedNode *pred = C.getPredecessor();
2642 for (Stmt::const_child_iterator it = Ex->child_begin(), et = Ex->child_end() ;
2643 it != et ; ++it) {
2644 const Stmt *child = *it;
2645 SVal V = state->getSVal(child, pred->getLocationContext());
2646 if (SymbolRef sym = V.getAsSymbol())
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002647 if (const RefVal* T = getRefBinding(state, sym)) {
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002648 RefVal::Kind hasErr = (RefVal::Kind) 0;
2649 state = updateSymbol(state, sym, *T, MayEscape, hasErr, C);
2650 if (hasErr) {
2651 processNonLeakError(state, child->getSourceRange(), hasErr, sym, C);
2652 return;
2653 }
2654 }
2655 }
2656
2657 // Return the object as autoreleased.
2658 // RetEffect RE = RetEffect::MakeNotOwned(RetEffect::ObjC);
2659 if (SymbolRef sym =
2660 state->getSVal(Ex, pred->getLocationContext()).getAsSymbol()) {
2661 QualType ResultTy = Ex->getType();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002662 state = setRefBinding(state, sym,
2663 RefVal::makeNotOwned(RetEffect::ObjC, ResultTy));
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002664 }
2665
2666 C.addTransition(state);
2667}
2668
2669void RetainCountChecker::checkPostStmt(const ObjCArrayLiteral *AL,
2670 CheckerContext &C) const {
2671 // Apply the 'MayEscape' to all values.
2672 processObjCLiterals(C, AL);
2673}
2674
2675void RetainCountChecker::checkPostStmt(const ObjCDictionaryLiteral *DL,
2676 CheckerContext &C) const {
2677 // Apply the 'MayEscape' to all keys and values.
2678 processObjCLiterals(C, DL);
2679}
2680
Jordy Rose70fdbc32012-05-12 05:10:43 +00002681void RetainCountChecker::checkPostStmt(const ObjCBoxedExpr *Ex,
2682 CheckerContext &C) const {
2683 const ExplodedNode *Pred = C.getPredecessor();
2684 const LocationContext *LCtx = Pred->getLocationContext();
2685 ProgramStateRef State = Pred->getState();
2686
2687 if (SymbolRef Sym = State->getSVal(Ex, LCtx).getAsSymbol()) {
2688 QualType ResultTy = Ex->getType();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002689 State = setRefBinding(State, Sym,
2690 RefVal::makeNotOwned(RetEffect::ObjC, ResultTy));
Jordy Rose70fdbc32012-05-12 05:10:43 +00002691 }
2692
2693 C.addTransition(State);
2694}
2695
Jordan Rosefe6a0112012-07-02 19:28:21 +00002696void RetainCountChecker::checkPostCall(const CallEvent &Call,
2697 CheckerContext &C) const {
2698 if (C.wasInlined)
2699 return;
Jordy Roseb6cfc092011-08-25 00:10:37 +00002700
Jordan Rosefe6a0112012-07-02 19:28:21 +00002701 RetainSummaryManager &Summaries = getSummaryManager(C);
2702 const RetainSummary *Summ = Summaries.getSummary(Call, C.getState());
2703 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
2734void RetainCountChecker::checkSummary(const RetainSummary &Summ,
Jordan Rose4531b7d2012-07-02 19:27:43 +00002735 const CallEvent &CallOrMsg,
Jordy Rose910c4052011-09-02 06:44:22 +00002736 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002737 ProgramStateRef state = C.getState();
Jordy Rose294396b2011-08-22 23:48:23 +00002738
2739 // Evaluate the effect of the arguments.
2740 RefVal::Kind hasErr = (RefVal::Kind) 0;
2741 SourceRange ErrorRange;
2742 SymbolRef ErrorSym = 0;
2743
2744 for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
Jordy Rose537716a2011-08-27 22:51:26 +00002745 SVal V = CallOrMsg.getArgSVal(idx);
Jordy Rose294396b2011-08-22 23:48:23 +00002746
2747 if (SymbolRef Sym = V.getAsLocSymbol()) {
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002748 if (const RefVal *T = getRefBinding(state, Sym)) {
Jordy Rose17a38e22011-09-02 05:55:19 +00002749 state = updateSymbol(state, Sym, *T, Summ.getArg(idx), hasErr, C);
Jordy Rose294396b2011-08-22 23:48:23 +00002750 if (hasErr) {
2751 ErrorRange = CallOrMsg.getArgSourceRange(idx);
2752 ErrorSym = Sym;
2753 break;
2754 }
2755 }
2756 }
2757 }
2758
2759 // Evaluate the effect on the message receiver.
2760 bool ReceiverIsTracked = false;
Jordan Rose4531b7d2012-07-02 19:27:43 +00002761 if (!hasErr) {
Jordan Rosecde8cdb2012-07-02 19:27:56 +00002762 const ObjCMethodCall *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg);
Jordan Rose4531b7d2012-07-02 19:27:43 +00002763 if (MsgInvocation) {
2764 if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002765 if (const RefVal *T = getRefBinding(state, Sym)) {
Jordan Rose4531b7d2012-07-02 19:27:43 +00002766 ReceiverIsTracked = true;
2767 state = updateSymbol(state, Sym, *T, Summ.getReceiverEffect(),
2768 hasErr, C);
2769 if (hasErr) {
Jordan Rose8919e682012-07-18 21:59:51 +00002770 ErrorRange = MsgInvocation->getOriginExpr()->getReceiverRange();
Jordan Rose4531b7d2012-07-02 19:27:43 +00002771 ErrorSym = Sym;
2772 }
Jordy Rose294396b2011-08-22 23:48:23 +00002773 }
2774 }
2775 }
2776 }
2777
2778 // Process any errors.
2779 if (hasErr) {
2780 processNonLeakError(state, ErrorRange, hasErr, ErrorSym, C);
2781 return;
2782 }
2783
2784 // Consult the summary for the return value.
2785 RetEffect RE = Summ.getRetEffect();
2786
2787 if (RE.getKind() == RetEffect::OwnedWhenTrackedReceiver) {
Jordy Roseb6cfc092011-08-25 00:10:37 +00002788 if (ReceiverIsTracked)
Jordy Rose17a38e22011-09-02 05:55:19 +00002789 RE = getSummaryManager(C).getObjAllocRetEffect();
Jordy Roseb6cfc092011-08-25 00:10:37 +00002790 else
Jordy Rose294396b2011-08-22 23:48:23 +00002791 RE = RetEffect::MakeNoRet();
2792 }
2793
2794 switch (RE.getKind()) {
2795 default:
David Blaikie7530c032012-01-17 06:56:22 +00002796 llvm_unreachable("Unhandled RetEffect.");
Jordy Rose294396b2011-08-22 23:48:23 +00002797
2798 case RetEffect::NoRet:
2799 // No work necessary.
2800 break;
2801
2802 case RetEffect::OwnedAllocatedSymbol:
2803 case RetEffect::OwnedSymbol: {
Ted Kremenek5eca4822012-01-06 22:09:28 +00002804 SymbolRef Sym = state->getSVal(CallOrMsg.getOriginExpr(),
2805 C.getLocationContext()).getAsSymbol();
Jordy Rose294396b2011-08-22 23:48:23 +00002806 if (!Sym)
2807 break;
2808
Jordan Rose4531b7d2012-07-02 19:27:43 +00002809 // Use the result type from the CallEvent as it automatically adjusts
Jordy Rose294396b2011-08-22 23:48:23 +00002810 // for methods/functions that return references.
Jordan Rose4531b7d2012-07-02 19:27:43 +00002811 QualType ResultTy = CallOrMsg.getResultType();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002812 state = setRefBinding(state, Sym, RefVal::makeOwned(RE.getObjKind(),
2813 ResultTy));
Jordy Rose294396b2011-08-22 23:48:23 +00002814
2815 // FIXME: Add a flag to the checker where allocations are assumed to
Anna Zaksc6ba23f2012-08-14 15:39:13 +00002816 // *not* fail.
Jordy Rose294396b2011-08-22 23:48:23 +00002817 break;
2818 }
2819
2820 case RetEffect::GCNotOwnedSymbol:
2821 case RetEffect::ARCNotOwnedSymbol:
2822 case RetEffect::NotOwnedSymbol: {
2823 const Expr *Ex = CallOrMsg.getOriginExpr();
Ted Kremenek5eca4822012-01-06 22:09:28 +00002824 SymbolRef Sym = state->getSVal(Ex, C.getLocationContext()).getAsSymbol();
Jordy Rose294396b2011-08-22 23:48:23 +00002825 if (!Sym)
2826 break;
2827
2828 // Use GetReturnType in order to give [NSFoo alloc] the type NSFoo *.
2829 QualType ResultTy = GetReturnType(Ex, C.getASTContext());
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002830 state = setRefBinding(state, Sym, RefVal::makeNotOwned(RE.getObjKind(),
2831 ResultTy));
Jordy Rose294396b2011-08-22 23:48:23 +00002832 break;
2833 }
2834 }
2835
2836 // This check is actually necessary; otherwise the statement builder thinks
2837 // we've hit a previously-found path.
2838 // Normally addTransition takes care of this, but we want the node pointer.
2839 ExplodedNode *NewNode;
2840 if (state == C.getState()) {
2841 NewNode = C.getPredecessor();
2842 } else {
Anna Zaks0bd6b112011-10-26 21:06:34 +00002843 NewNode = C.addTransition(state);
Jordy Rose294396b2011-08-22 23:48:23 +00002844 }
2845
Jordy Rose9c083b72011-08-24 18:56:32 +00002846 // Annotate the node with summary we used.
2847 if (NewNode) {
2848 // FIXME: This is ugly. See checkEndAnalysis for why it's necessary.
2849 if (ShouldResetSummaryLog) {
2850 SummaryLog.clear();
2851 ShouldResetSummaryLog = false;
2852 }
Jordy Roseec9ef852011-08-23 20:55:48 +00002853 SummaryLog[NewNode] = &Summ;
Jordy Rose9c083b72011-08-24 18:56:32 +00002854 }
Jordy Rose294396b2011-08-22 23:48:23 +00002855}
2856
Jordy Rosee0a5d322011-08-23 20:27:16 +00002857
Ted Kremenek8bef8232012-01-26 21:29:00 +00002858ProgramStateRef
2859RetainCountChecker::updateSymbol(ProgramStateRef state, SymbolRef sym,
Jordy Rose910c4052011-09-02 06:44:22 +00002860 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
2861 CheckerContext &C) const {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002862 // In GC mode [... release] and [... retain] do nothing.
Jordy Rose910c4052011-09-02 06:44:22 +00002863 // In ARC mode they shouldn't exist at all, but we just ignore them.
Jordy Rose17a38e22011-09-02 05:55:19 +00002864 bool IgnoreRetainMsg = C.isObjCGCEnabled();
2865 if (!IgnoreRetainMsg)
David Blaikie4e4d0842012-03-11 07:00:24 +00002866 IgnoreRetainMsg = (bool)C.getASTContext().getLangOpts().ObjCAutoRefCount;
Jordy Rose17a38e22011-09-02 05:55:19 +00002867
Jordy Rosee0a5d322011-08-23 20:27:16 +00002868 switch (E) {
Jordan Rose4531b7d2012-07-02 19:27:43 +00002869 default:
2870 break;
2871 case IncRefMsg:
2872 E = IgnoreRetainMsg ? DoNothing : IncRef;
2873 break;
2874 case DecRefMsg:
2875 E = IgnoreRetainMsg ? DoNothing : DecRef;
2876 break;
2877 case DecRefMsgAndStopTracking:
2878 E = IgnoreRetainMsg ? StopTracking : DecRefAndStopTracking;
2879 break;
2880 case MakeCollectable:
2881 E = C.isObjCGCEnabled() ? DecRef : DoNothing;
2882 break;
2883 case NewAutoreleasePool:
2884 E = C.isObjCGCEnabled() ? DoNothing : NewAutoreleasePool;
2885 break;
Jordy Rosee0a5d322011-08-23 20:27:16 +00002886 }
2887
2888 // Handle all use-after-releases.
Jordy Rose17a38e22011-09-02 05:55:19 +00002889 if (!C.isObjCGCEnabled() && V.getKind() == RefVal::Released) {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002890 V = V ^ RefVal::ErrorUseAfterRelease;
2891 hasErr = V.getKind();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002892 return setRefBinding(state, sym, V);
Jordy Rosee0a5d322011-08-23 20:27:16 +00002893 }
2894
2895 switch (E) {
2896 case DecRefMsg:
2897 case IncRefMsg:
2898 case MakeCollectable:
Jordan Rose4531b7d2012-07-02 19:27:43 +00002899 case DecRefMsgAndStopTracking:
Jordy Rosee0a5d322011-08-23 20:27:16 +00002900 llvm_unreachable("DecRefMsg/IncRefMsg/MakeCollectable already converted");
Jordy Rosee0a5d322011-08-23 20:27:16 +00002901
2902 case Dealloc:
2903 // Any use of -dealloc in GC is *bad*.
Jordy Rose17a38e22011-09-02 05:55:19 +00002904 if (C.isObjCGCEnabled()) {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002905 V = V ^ RefVal::ErrorDeallocGC;
2906 hasErr = V.getKind();
2907 break;
2908 }
2909
2910 switch (V.getKind()) {
2911 default:
2912 llvm_unreachable("Invalid RefVal state for an explicit dealloc.");
Jordy Rosee0a5d322011-08-23 20:27:16 +00002913 case RefVal::Owned:
2914 // The object immediately transitions to the released state.
2915 V = V ^ RefVal::Released;
2916 V.clearCounts();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002917 return setRefBinding(state, sym, V);
Jordy Rosee0a5d322011-08-23 20:27:16 +00002918 case RefVal::NotOwned:
2919 V = V ^ RefVal::ErrorDeallocNotOwned;
2920 hasErr = V.getKind();
2921 break;
2922 }
2923 break;
2924
2925 case NewAutoreleasePool:
Jordy Rose17a38e22011-09-02 05:55:19 +00002926 assert(!C.isObjCGCEnabled());
Anna Zaksc95bb762012-08-14 00:36:17 +00002927 return state;
Jordy Rosee0a5d322011-08-23 20:27:16 +00002928
2929 case MayEscape:
2930 if (V.getKind() == RefVal::Owned) {
2931 V = V ^ RefVal::NotOwned;
2932 break;
2933 }
2934
2935 // Fall-through.
2936
Jordy Rosee0a5d322011-08-23 20:27:16 +00002937 case DoNothing:
2938 return state;
2939
2940 case Autorelease:
Jordy Rose17a38e22011-09-02 05:55:19 +00002941 if (C.isObjCGCEnabled())
Jordy Rosee0a5d322011-08-23 20:27:16 +00002942 return state;
Jordy Rosee0a5d322011-08-23 20:27:16 +00002943 // Update the autorelease counts.
Jordy Rosee0a5d322011-08-23 20:27:16 +00002944 V = V.autorelease();
2945 break;
2946
2947 case StopTracking:
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002948 return removeRefBinding(state, sym);
Jordy Rosee0a5d322011-08-23 20:27:16 +00002949
2950 case IncRef:
2951 switch (V.getKind()) {
2952 default:
2953 llvm_unreachable("Invalid RefVal state for a retain.");
Jordy Rosee0a5d322011-08-23 20:27:16 +00002954 case RefVal::Owned:
2955 case RefVal::NotOwned:
2956 V = V + 1;
2957 break;
2958 case RefVal::Released:
2959 // Non-GC cases are handled above.
Jordy Rose17a38e22011-09-02 05:55:19 +00002960 assert(C.isObjCGCEnabled());
Jordy Rosee0a5d322011-08-23 20:27:16 +00002961 V = (V ^ RefVal::Owned) + 1;
2962 break;
2963 }
2964 break;
2965
Jordy Rosee0a5d322011-08-23 20:27:16 +00002966 case DecRef:
2967 case DecRefBridgedTransfered:
Jordan Rose4531b7d2012-07-02 19:27:43 +00002968 case DecRefAndStopTracking:
Jordy Rosee0a5d322011-08-23 20:27:16 +00002969 switch (V.getKind()) {
2970 default:
2971 // case 'RefVal::Released' handled above.
2972 llvm_unreachable("Invalid RefVal state for a release.");
Jordy Rosee0a5d322011-08-23 20:27:16 +00002973
2974 case RefVal::Owned:
2975 assert(V.getCount() > 0);
2976 if (V.getCount() == 1)
2977 V = V ^ (E == DecRefBridgedTransfered ?
2978 RefVal::NotOwned : RefVal::Released);
Jordan Rose4531b7d2012-07-02 19:27:43 +00002979 else if (E == DecRefAndStopTracking)
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002980 return removeRefBinding(state, sym);
Jordan Rose4531b7d2012-07-02 19:27:43 +00002981
Jordy Rosee0a5d322011-08-23 20:27:16 +00002982 V = V - 1;
2983 break;
2984
2985 case RefVal::NotOwned:
Jordan Rose4531b7d2012-07-02 19:27:43 +00002986 if (V.getCount() > 0) {
2987 if (E == DecRefAndStopTracking)
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002988 return removeRefBinding(state, sym);
Jordy Rosee0a5d322011-08-23 20:27:16 +00002989 V = V - 1;
Jordan Rose4531b7d2012-07-02 19:27:43 +00002990 } else {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002991 V = V ^ RefVal::ErrorReleaseNotOwned;
2992 hasErr = V.getKind();
2993 }
2994 break;
2995
2996 case RefVal::Released:
2997 // Non-GC cases are handled above.
Jordy Rose17a38e22011-09-02 05:55:19 +00002998 assert(C.isObjCGCEnabled());
Jordy Rosee0a5d322011-08-23 20:27:16 +00002999 V = V ^ RefVal::ErrorUseAfterRelease;
3000 hasErr = V.getKind();
3001 break;
3002 }
3003 break;
3004 }
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003005 return setRefBinding(state, sym, V);
Jordy Rosee0a5d322011-08-23 20:27:16 +00003006}
3007
Ted Kremenek8bef8232012-01-26 21:29:00 +00003008void RetainCountChecker::processNonLeakError(ProgramStateRef St,
Jordy Rose910c4052011-09-02 06:44:22 +00003009 SourceRange ErrorRange,
3010 RefVal::Kind ErrorKind,
3011 SymbolRef Sym,
3012 CheckerContext &C) const {
Jordy Rose294396b2011-08-22 23:48:23 +00003013 ExplodedNode *N = C.generateSink(St);
3014 if (!N)
3015 return;
3016
Jordy Rose294396b2011-08-22 23:48:23 +00003017 CFRefBug *BT;
3018 switch (ErrorKind) {
3019 default:
3020 llvm_unreachable("Unhandled error.");
Jordy Rose294396b2011-08-22 23:48:23 +00003021 case RefVal::ErrorUseAfterRelease:
Jordy Rosed6334e12011-08-25 00:34:03 +00003022 if (!useAfterRelease)
3023 useAfterRelease.reset(new UseAfterRelease());
3024 BT = &*useAfterRelease;
Jordy Rose294396b2011-08-22 23:48:23 +00003025 break;
3026 case RefVal::ErrorReleaseNotOwned:
Jordy Rosed6334e12011-08-25 00:34:03 +00003027 if (!releaseNotOwned)
3028 releaseNotOwned.reset(new BadRelease());
3029 BT = &*releaseNotOwned;
Jordy Rose294396b2011-08-22 23:48:23 +00003030 break;
3031 case RefVal::ErrorDeallocGC:
Jordy Rosed6334e12011-08-25 00:34:03 +00003032 if (!deallocGC)
3033 deallocGC.reset(new DeallocGC());
3034 BT = &*deallocGC;
Jordy Rose294396b2011-08-22 23:48:23 +00003035 break;
3036 case RefVal::ErrorDeallocNotOwned:
Jordy Rosed6334e12011-08-25 00:34:03 +00003037 if (!deallocNotOwned)
3038 deallocNotOwned.reset(new DeallocNotOwned());
3039 BT = &*deallocNotOwned;
Jordy Rose294396b2011-08-22 23:48:23 +00003040 break;
3041 }
3042
Jordy Rosed6334e12011-08-25 00:34:03 +00003043 assert(BT);
David Blaikie4e4d0842012-03-11 07:00:24 +00003044 CFRefReport *report = new CFRefReport(*BT, C.getASTContext().getLangOpts(),
Jordy Rose17a38e22011-09-02 05:55:19 +00003045 C.isObjCGCEnabled(), SummaryLog,
3046 N, Sym);
Jordy Rose294396b2011-08-22 23:48:23 +00003047 report->addRange(ErrorRange);
3048 C.EmitReport(report);
3049}
3050
Jordy Rose910c4052011-09-02 06:44:22 +00003051//===----------------------------------------------------------------------===//
3052// Handle the return values of retain-count-related functions.
3053//===----------------------------------------------------------------------===//
3054
3055bool RetainCountChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
Jordy Rose76c506f2011-08-21 21:58:18 +00003056 // Get the callee. We're only interested in simple C functions.
Ted Kremenek8bef8232012-01-26 21:29:00 +00003057 ProgramStateRef state = C.getState();
Anna Zaksb805c8f2011-12-01 05:57:37 +00003058 const FunctionDecl *FD = C.getCalleeDecl(CE);
Jordy Rose76c506f2011-08-21 21:58:18 +00003059 if (!FD)
3060 return false;
3061
3062 IdentifierInfo *II = FD->getIdentifier();
3063 if (!II)
3064 return false;
3065
3066 // For now, we're only handling the functions that return aliases of their
3067 // arguments: CFRetain and CFMakeCollectable (and their families).
3068 // Eventually we should add other functions we can model entirely,
3069 // such as CFRelease, which don't invalidate their arguments or globals.
3070 if (CE->getNumArgs() != 1)
3071 return false;
3072
3073 // Get the name of the function.
3074 StringRef FName = II->getName();
3075 FName = FName.substr(FName.find_first_not_of('_'));
3076
3077 // See if it's one of the specific functions we know how to eval.
3078 bool canEval = false;
3079
Anna Zaksb805c8f2011-12-01 05:57:37 +00003080 QualType ResultTy = CE->getCallReturnType();
Jordy Rose76c506f2011-08-21 21:58:18 +00003081 if (ResultTy->isObjCIdType()) {
3082 // Handle: id NSMakeCollectable(CFTypeRef)
3083 canEval = II->isStr("NSMakeCollectable");
3084 } else if (ResultTy->isPointerType()) {
3085 // Handle: (CF|CG)Retain
3086 // CFMakeCollectable
3087 // It's okay to be a little sloppy here (CGMakeCollectable doesn't exist).
3088 if (cocoa::isRefType(ResultTy, "CF", FName) ||
3089 cocoa::isRefType(ResultTy, "CG", FName)) {
3090 canEval = isRetain(FD, FName) || isMakeCollectable(FD, FName);
3091 }
3092 }
3093
3094 if (!canEval)
3095 return false;
3096
3097 // Bind the return value.
Ted Kremenek5eca4822012-01-06 22:09:28 +00003098 const LocationContext *LCtx = C.getLocationContext();
3099 SVal RetVal = state->getSVal(CE->getArg(0), LCtx);
Jordy Rose76c506f2011-08-21 21:58:18 +00003100 if (RetVal.isUnknown()) {
3101 // If the receiver is unknown, conjure a return value.
3102 SValBuilder &SVB = C.getSValBuilder();
Ted Kremenek66c486f2012-08-22 06:26:15 +00003103 RetVal = SVB.conjureSymbolVal(0, CE, LCtx, ResultTy, C.blockCount());
Jordy Rose76c506f2011-08-21 21:58:18 +00003104 }
Ted Kremenek5eca4822012-01-06 22:09:28 +00003105 state = state->BindExpr(CE, LCtx, RetVal, false);
Jordy Rose76c506f2011-08-21 21:58:18 +00003106
Jordy Rose294396b2011-08-22 23:48:23 +00003107 // FIXME: This should not be necessary, but otherwise the argument seems to be
3108 // considered alive during the next statement.
3109 if (const MemRegion *ArgRegion = RetVal.getAsRegion()) {
3110 // Save the refcount status of the argument.
3111 SymbolRef Sym = RetVal.getAsLocSymbol();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003112 const RefVal *Binding = 0;
Jordy Rose294396b2011-08-22 23:48:23 +00003113 if (Sym)
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003114 Binding = getRefBinding(state, Sym);
Jordy Rose76c506f2011-08-21 21:58:18 +00003115
Jordy Rose294396b2011-08-22 23:48:23 +00003116 // Invalidate the argument region.
Ted Kremenek66c486f2012-08-22 06:26:15 +00003117 state = state->invalidateRegions(ArgRegion, CE, C.blockCount(), LCtx);
Jordy Rose76c506f2011-08-21 21:58:18 +00003118
Jordy Rose294396b2011-08-22 23:48:23 +00003119 // Restore the refcount status of the argument.
3120 if (Binding)
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003121 state = setRefBinding(state, Sym, *Binding);
Jordy Rose294396b2011-08-22 23:48:23 +00003122 }
3123
Anna Zaks0bd6b112011-10-26 21:06:34 +00003124 C.addTransition(state);
Jordy Rose76c506f2011-08-21 21:58:18 +00003125 return true;
3126}
3127
Jordy Rose910c4052011-09-02 06:44:22 +00003128//===----------------------------------------------------------------------===//
3129// Handle return statements.
3130//===----------------------------------------------------------------------===//
Jordy Rosef53e8c72011-08-23 19:43:16 +00003131
Ted Kremeneke5715782012-02-25 02:09:09 +00003132// Return true if the current LocationContext has no caller context.
3133static bool inTopFrame(CheckerContext &C) {
3134 const LocationContext *LC = C.getLocationContext();
3135 return LC->getParent() == 0;
3136}
3137
Jordy Rose910c4052011-09-02 06:44:22 +00003138void RetainCountChecker::checkPreStmt(const ReturnStmt *S,
3139 CheckerContext &C) const {
Ted Kremeneke5715782012-02-25 02:09:09 +00003140
3141 // Only adjust the reference count if this is the top-level call frame,
3142 // and not the result of inlining. In the future, we should do
3143 // better checking even for inlined calls, and see if they match
3144 // with their expected semantics (e.g., the method should return a retained
3145 // object, etc.).
3146 if (!inTopFrame(C))
3147 return;
3148
Jordy Rosef53e8c72011-08-23 19:43:16 +00003149 const Expr *RetE = S->getRetValue();
3150 if (!RetE)
3151 return;
3152
Ted Kremenek8bef8232012-01-26 21:29:00 +00003153 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00003154 SymbolRef Sym =
3155 state->getSValAsScalarOrLoc(RetE, C.getLocationContext()).getAsLocSymbol();
Jordy Rosef53e8c72011-08-23 19:43:16 +00003156 if (!Sym)
3157 return;
3158
3159 // Get the reference count binding (if any).
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003160 const RefVal *T = getRefBinding(state, Sym);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003161 if (!T)
3162 return;
3163
3164 // Change the reference count.
3165 RefVal X = *T;
3166
3167 switch (X.getKind()) {
3168 case RefVal::Owned: {
3169 unsigned cnt = X.getCount();
3170 assert(cnt > 0);
3171 X.setCount(cnt - 1);
3172 X = X ^ RefVal::ReturnedOwned;
3173 break;
3174 }
3175
3176 case RefVal::NotOwned: {
3177 unsigned cnt = X.getCount();
3178 if (cnt) {
3179 X.setCount(cnt - 1);
3180 X = X ^ RefVal::ReturnedOwned;
3181 }
3182 else {
3183 X = X ^ RefVal::ReturnedNotOwned;
3184 }
3185 break;
3186 }
3187
3188 default:
3189 return;
3190 }
3191
3192 // Update the binding.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003193 state = setRefBinding(state, Sym, X);
Anna Zaks0bd6b112011-10-26 21:06:34 +00003194 ExplodedNode *Pred = C.addTransition(state);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003195
3196 // At this point we have updated the state properly.
3197 // Everything after this is merely checking to see if the return value has
3198 // been over- or under-retained.
3199
3200 // Did we cache out?
3201 if (!Pred)
3202 return;
3203
Jordy Rosef53e8c72011-08-23 19:43:16 +00003204 // Update the autorelease counts.
3205 static SimpleProgramPointTag
Jordy Rose910c4052011-09-02 06:44:22 +00003206 AutoreleaseTag("RetainCountChecker : Autorelease");
Jordan Rose2bce86c2012-08-18 00:30:16 +00003207 llvm::tie(Pred, state) = handleAutoreleaseCounts(state, Pred, &AutoreleaseTag,
3208 C, Sym, X);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003209
3210 // Did we cache out?
Jordy Rose8d228632011-08-23 20:07:14 +00003211 if (!Pred)
Jordy Rosef53e8c72011-08-23 19:43:16 +00003212 return;
3213
3214 // Get the updated binding.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003215 T = getRefBinding(state, Sym);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003216 assert(T);
3217 X = *T;
3218
3219 // Consult the summary of the enclosing method.
Jordy Rose17a38e22011-09-02 05:55:19 +00003220 RetainSummaryManager &Summaries = getSummaryManager(C);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003221 const Decl *CD = &Pred->getCodeDecl();
Jordan Rose4531b7d2012-07-02 19:27:43 +00003222 RetEffect RE = RetEffect::MakeNoRet();
Jordy Rosef53e8c72011-08-23 19:43:16 +00003223
Jordan Rose4531b7d2012-07-02 19:27:43 +00003224 // FIXME: What is the convention for blocks? Is there one?
Jordy Rosef53e8c72011-08-23 19:43:16 +00003225 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CD)) {
Jordy Roseb6cfc092011-08-25 00:10:37 +00003226 const RetainSummary *Summ = Summaries.getMethodSummary(MD);
Jordan Rose4531b7d2012-07-02 19:27:43 +00003227 RE = Summ->getRetEffect();
3228 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) {
3229 if (!isa<CXXMethodDecl>(FD)) {
3230 const RetainSummary *Summ = Summaries.getFunctionSummary(FD);
3231 RE = Summ->getRetEffect();
3232 }
Jordy Rosef53e8c72011-08-23 19:43:16 +00003233 }
3234
Jordan Rose4531b7d2012-07-02 19:27:43 +00003235 checkReturnWithRetEffect(S, C, Pred, RE, X, Sym, state);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003236}
3237
Jordy Rose910c4052011-09-02 06:44:22 +00003238void RetainCountChecker::checkReturnWithRetEffect(const ReturnStmt *S,
3239 CheckerContext &C,
3240 ExplodedNode *Pred,
3241 RetEffect RE, RefVal X,
3242 SymbolRef Sym,
Ted Kremenek8bef8232012-01-26 21:29:00 +00003243 ProgramStateRef state) const {
Jordy Rosef53e8c72011-08-23 19:43:16 +00003244 // Any leaks or other errors?
3245 if (X.isReturnedOwned() && X.getCount() == 0) {
3246 if (RE.getKind() != RetEffect::NoRet) {
3247 bool hasError = false;
Jordy Rose17a38e22011-09-02 05:55:19 +00003248 if (C.isObjCGCEnabled() && RE.getObjKind() == RetEffect::ObjC) {
Jordy Rosef53e8c72011-08-23 19:43:16 +00003249 // Things are more complicated with garbage collection. If the
3250 // returned object is suppose to be an Objective-C object, we have
3251 // a leak (as the caller expects a GC'ed object) because no
3252 // method should return ownership unless it returns a CF object.
3253 hasError = true;
3254 X = X ^ RefVal::ErrorGCLeakReturned;
3255 }
3256 else if (!RE.isOwned()) {
3257 // Either we are using GC and the returned object is a CF type
3258 // or we aren't using GC. In either case, we expect that the
3259 // enclosing method is expected to return ownership.
3260 hasError = true;
3261 X = X ^ RefVal::ErrorLeakReturned;
3262 }
3263
3264 if (hasError) {
3265 // Generate an error node.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003266 state = setRefBinding(state, Sym, X);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003267
3268 static SimpleProgramPointTag
Jordy Rose910c4052011-09-02 06:44:22 +00003269 ReturnOwnLeakTag("RetainCountChecker : ReturnsOwnLeak");
Anna Zaks0bd6b112011-10-26 21:06:34 +00003270 ExplodedNode *N = C.addTransition(state, Pred, &ReturnOwnLeakTag);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003271 if (N) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003272 const LangOptions &LOpts = C.getASTContext().getLangOpts();
Jordy Rose17a38e22011-09-02 05:55:19 +00003273 bool GCEnabled = C.isObjCGCEnabled();
Jordy Rosef53e8c72011-08-23 19:43:16 +00003274 CFRefReport *report =
Jordy Rose17a38e22011-09-02 05:55:19 +00003275 new CFRefLeakReport(*getLeakAtReturnBug(LOpts, GCEnabled),
3276 LOpts, GCEnabled, SummaryLog,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003277 N, Sym, C);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003278 C.EmitReport(report);
3279 }
3280 }
3281 }
3282 } else if (X.isReturnedNotOwned()) {
3283 if (RE.isOwned()) {
3284 // Trying to return a not owned object to a caller expecting an
3285 // owned object.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003286 state = setRefBinding(state, Sym, X ^ RefVal::ErrorReturnedNotOwned);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003287
3288 static SimpleProgramPointTag
Jordy Rose910c4052011-09-02 06:44:22 +00003289 ReturnNotOwnedTag("RetainCountChecker : ReturnNotOwnedForOwned");
Anna Zaks0bd6b112011-10-26 21:06:34 +00003290 ExplodedNode *N = C.addTransition(state, Pred, &ReturnNotOwnedTag);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003291 if (N) {
Jordy Rosed6334e12011-08-25 00:34:03 +00003292 if (!returnNotOwnedForOwned)
3293 returnNotOwnedForOwned.reset(new ReturnedNotOwnedForOwned());
3294
Jordy Rosef53e8c72011-08-23 19:43:16 +00003295 CFRefReport *report =
Jordy Rosed6334e12011-08-25 00:34:03 +00003296 new CFRefReport(*returnNotOwnedForOwned,
David Blaikie4e4d0842012-03-11 07:00:24 +00003297 C.getASTContext().getLangOpts(),
Jordy Rose17a38e22011-09-02 05:55:19 +00003298 C.isObjCGCEnabled(), SummaryLog, N, Sym);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003299 C.EmitReport(report);
3300 }
3301 }
3302 }
3303}
3304
Jordy Rose8d228632011-08-23 20:07:14 +00003305//===----------------------------------------------------------------------===//
Jordy Rose910c4052011-09-02 06:44:22 +00003306// Check various ways a symbol can be invalidated.
3307//===----------------------------------------------------------------------===//
3308
Anna Zaks390909c2011-10-06 00:43:15 +00003309void RetainCountChecker::checkBind(SVal loc, SVal val, const Stmt *S,
Jordy Rose910c4052011-09-02 06:44:22 +00003310 CheckerContext &C) const {
3311 // Are we storing to something that causes the value to "escape"?
3312 bool escapes = true;
3313
3314 // A value escapes in three possible cases (this may change):
3315 //
3316 // (1) we are binding to something that is not a memory region.
3317 // (2) we are binding to a memregion that does not have stack storage
3318 // (3) we are binding to a memregion with stack storage that the store
3319 // does not understand.
Ted Kremenek8bef8232012-01-26 21:29:00 +00003320 ProgramStateRef state = C.getState();
Jordy Rose910c4052011-09-02 06:44:22 +00003321
3322 if (loc::MemRegionVal *regionLoc = dyn_cast<loc::MemRegionVal>(&loc)) {
3323 escapes = !regionLoc->getRegion()->hasStackStorage();
3324
3325 if (!escapes) {
3326 // To test (3), generate a new state with the binding added. If it is
3327 // the same state, then it escapes (since the store cannot represent
3328 // the binding).
Anna Zakse7958da2012-05-02 00:15:40 +00003329 // Do this only if we know that the store is not supposed to generate the
3330 // same state.
3331 SVal StoredVal = state->getSVal(regionLoc->getRegion());
3332 if (StoredVal != val)
3333 escapes = (state == (state->bindLoc(*regionLoc, val)));
Jordy Rose910c4052011-09-02 06:44:22 +00003334 }
Ted Kremenekde5b4fb2012-03-27 01:12:45 +00003335 if (!escapes) {
3336 // Case 4: We do not currently model what happens when a symbol is
3337 // assigned to a struct field, so be conservative here and let the symbol
3338 // go. TODO: This could definitely be improved upon.
3339 escapes = !isa<VarRegion>(regionLoc->getRegion());
3340 }
Jordy Rose910c4052011-09-02 06:44:22 +00003341 }
3342
3343 // If our store can represent the binding and we aren't storing to something
3344 // that doesn't have local storage then just return and have the simulation
3345 // state continue as is.
3346 if (!escapes)
3347 return;
3348
3349 // Otherwise, find all symbols referenced by 'val' that we are tracking
3350 // and stop tracking them.
3351 state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
Anna Zaks0bd6b112011-10-26 21:06:34 +00003352 C.addTransition(state);
Jordy Rose910c4052011-09-02 06:44:22 +00003353}
3354
Ted Kremenek8bef8232012-01-26 21:29:00 +00003355ProgramStateRef RetainCountChecker::evalAssume(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003356 SVal Cond,
3357 bool Assumption) const {
3358
3359 // FIXME: We may add to the interface of evalAssume the list of symbols
3360 // whose assumptions have changed. For now we just iterate through the
3361 // bindings and check if any of the tracked symbols are NULL. This isn't
3362 // too bad since the number of symbols we will track in practice are
3363 // probably small and evalAssume is only called at branches and a few
3364 // other places.
3365 RefBindings B = state->get<RefBindings>();
3366
3367 if (B.isEmpty())
3368 return state;
3369
3370 bool changed = false;
3371 RefBindings::Factory &RefBFactory = state->get_context<RefBindings>();
3372
3373 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
3374 // Check if the symbol is null (or equal to any constant).
3375 // If this is the case, stop tracking the symbol.
3376 if (state->getSymVal(I.getKey())) {
3377 changed = true;
3378 B = RefBFactory.remove(B, I.getKey());
3379 }
3380 }
3381
3382 if (changed)
3383 state = state->set<RefBindings>(B);
3384
3385 return state;
3386}
3387
Ted Kremenek8bef8232012-01-26 21:29:00 +00003388ProgramStateRef
3389RetainCountChecker::checkRegionChanges(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003390 const StoreManager::InvalidatedSymbols *invalidated,
3391 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00003392 ArrayRef<const MemRegion *> Regions,
Jordan Rose740d4902012-07-02 19:27:35 +00003393 const CallEvent *Call) const {
Jordy Rose910c4052011-09-02 06:44:22 +00003394 if (!invalidated)
3395 return state;
3396
3397 llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
3398 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
3399 E = ExplicitRegions.end(); I != E; ++I) {
3400 if (const SymbolicRegion *SR = (*I)->StripCasts()->getAs<SymbolicRegion>())
3401 WhitelistedSymbols.insert(SR->getSymbol());
3402 }
3403
3404 for (StoreManager::InvalidatedSymbols::const_iterator I=invalidated->begin(),
3405 E = invalidated->end(); I!=E; ++I) {
3406 SymbolRef sym = *I;
3407 if (WhitelistedSymbols.count(sym))
3408 continue;
3409 // Remove any existing reference-count binding.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003410 state = removeRefBinding(state, sym);
Jordy Rose910c4052011-09-02 06:44:22 +00003411 }
3412 return state;
3413}
3414
3415//===----------------------------------------------------------------------===//
Jordy Rose8d228632011-08-23 20:07:14 +00003416// Handle dead symbols and end-of-path.
3417//===----------------------------------------------------------------------===//
3418
Ted Kremenek8bef8232012-01-26 21:29:00 +00003419std::pair<ExplodedNode *, ProgramStateRef >
3420RetainCountChecker::handleAutoreleaseCounts(ProgramStateRef state,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003421 ExplodedNode *Pred,
Jordan Rose2bce86c2012-08-18 00:30:16 +00003422 const ProgramPointTag *Tag,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003423 CheckerContext &Ctx,
Jordy Rose910c4052011-09-02 06:44:22 +00003424 SymbolRef Sym, RefVal V) const {
Jordy Rose8d228632011-08-23 20:07:14 +00003425 unsigned ACnt = V.getAutoreleaseCount();
3426
3427 // No autorelease counts? Nothing to be done.
3428 if (!ACnt)
3429 return std::make_pair(Pred, state);
3430
Anna Zaks6a93bd52011-10-25 19:57:11 +00003431 assert(!Ctx.isObjCGCEnabled() && "Autorelease counts in GC mode?");
Jordy Rose8d228632011-08-23 20:07:14 +00003432 unsigned Cnt = V.getCount();
3433
3434 // FIXME: Handle sending 'autorelease' to already released object.
3435
3436 if (V.getKind() == RefVal::ReturnedOwned)
3437 ++Cnt;
3438
3439 if (ACnt <= Cnt) {
3440 if (ACnt == Cnt) {
3441 V.clearCounts();
3442 if (V.getKind() == RefVal::ReturnedOwned)
3443 V = V ^ RefVal::ReturnedNotOwned;
3444 else
3445 V = V ^ RefVal::NotOwned;
3446 } else {
3447 V.setCount(Cnt - ACnt);
3448 V.setAutoreleaseCount(0);
3449 }
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003450 state = setRefBinding(state, Sym, V);
Jordan Rose2bce86c2012-08-18 00:30:16 +00003451 ExplodedNode *N = Ctx.addTransition(state, Pred, Tag);
Jordy Rose8d228632011-08-23 20:07:14 +00003452 if (N == 0)
3453 state = 0;
3454 return std::make_pair(N, state);
3455 }
3456
3457 // Woah! More autorelease counts then retain counts left.
3458 // Emit hard error.
3459 V = V ^ RefVal::ErrorOverAutorelease;
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003460 state = setRefBinding(state, Sym, V);
Jordy Rose8d228632011-08-23 20:07:14 +00003461
Jordan Rosefa06f042012-08-20 18:43:42 +00003462 ExplodedNode *N = Ctx.generateSink(state, Pred, Tag);
Jordan Rose2bce86c2012-08-18 00:30:16 +00003463 if (N) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003464 SmallString<128> sbuf;
Jordy Rose8d228632011-08-23 20:07:14 +00003465 llvm::raw_svector_ostream os(sbuf);
3466 os << "Object over-autoreleased: object was sent -autorelease ";
3467 if (V.getAutoreleaseCount() > 1)
3468 os << V.getAutoreleaseCount() << " times ";
3469 os << "but the object has a +" << V.getCount() << " retain count";
3470
Jordy Rosed6334e12011-08-25 00:34:03 +00003471 if (!overAutorelease)
3472 overAutorelease.reset(new OverAutorelease());
3473
David Blaikie4e4d0842012-03-11 07:00:24 +00003474 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
Jordy Rose8d228632011-08-23 20:07:14 +00003475 CFRefReport *report =
Jordy Rosed6334e12011-08-25 00:34:03 +00003476 new CFRefReport(*overAutorelease, LOpts, /* GCEnabled = */ false,
3477 SummaryLog, N, Sym, os.str());
Anna Zaks6a93bd52011-10-25 19:57:11 +00003478 Ctx.EmitReport(report);
Jordy Rose8d228632011-08-23 20:07:14 +00003479 }
3480
Ted Kremenek8bef8232012-01-26 21:29:00 +00003481 return std::make_pair((ExplodedNode *)0, (ProgramStateRef )0);
Jordy Rose8d228632011-08-23 20:07:14 +00003482}
Jordy Rose38f17d62011-08-23 19:01:07 +00003483
Ted Kremenek8bef8232012-01-26 21:29:00 +00003484ProgramStateRef
3485RetainCountChecker::handleSymbolDeath(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003486 SymbolRef sid, RefVal V,
Jordy Rose38f17d62011-08-23 19:01:07 +00003487 SmallVectorImpl<SymbolRef> &Leaked) const {
Jordy Rose53376122011-08-24 04:48:19 +00003488 bool hasLeak = false;
Jordy Rose38f17d62011-08-23 19:01:07 +00003489 if (V.isOwned())
3490 hasLeak = true;
3491 else if (V.isNotOwned() || V.isReturnedOwned())
3492 hasLeak = (V.getCount() > 0);
3493
3494 if (!hasLeak)
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003495 return removeRefBinding(state, sid);
Jordy Rose38f17d62011-08-23 19:01:07 +00003496
3497 Leaked.push_back(sid);
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003498 return setRefBinding(state, sid, V ^ RefVal::ErrorLeak);
Jordy Rose38f17d62011-08-23 19:01:07 +00003499}
3500
3501ExplodedNode *
Ted Kremenek8bef8232012-01-26 21:29:00 +00003502RetainCountChecker::processLeaks(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003503 SmallVectorImpl<SymbolRef> &Leaked,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003504 CheckerContext &Ctx,
3505 ExplodedNode *Pred) const {
Jordy Rose38f17d62011-08-23 19:01:07 +00003506 if (Leaked.empty())
3507 return Pred;
3508
3509 // Generate an intermediate node representing the leak point.
Jordan Rose2bce86c2012-08-18 00:30:16 +00003510 ExplodedNode *N = Ctx.addTransition(state, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003511
3512 if (N) {
3513 for (SmallVectorImpl<SymbolRef>::iterator
3514 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3515
David Blaikie4e4d0842012-03-11 07:00:24 +00003516 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
Anna Zaks6a93bd52011-10-25 19:57:11 +00003517 bool GCEnabled = Ctx.isObjCGCEnabled();
Jordy Rose17a38e22011-09-02 05:55:19 +00003518 CFRefBug *BT = Pred ? getLeakWithinFunctionBug(LOpts, GCEnabled)
3519 : getLeakAtReturnBug(LOpts, GCEnabled);
Jordy Rose38f17d62011-08-23 19:01:07 +00003520 assert(BT && "BugType not initialized.");
Jordy Rose20589562011-08-24 22:39:09 +00003521
Jordy Rose17a38e22011-09-02 05:55:19 +00003522 CFRefLeakReport *report = new CFRefLeakReport(*BT, LOpts, GCEnabled,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003523 SummaryLog, N, *I, Ctx);
3524 Ctx.EmitReport(report);
Jordy Rose38f17d62011-08-23 19:01:07 +00003525 }
3526 }
3527
3528 return N;
3529}
3530
Anna Zaksaf498a22011-10-25 19:56:48 +00003531void RetainCountChecker::checkEndPath(CheckerContext &Ctx) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +00003532 ProgramStateRef state = Ctx.getState();
Jordy Rose38f17d62011-08-23 19:01:07 +00003533 RefBindings B = state->get<RefBindings>();
Anna Zaksaf498a22011-10-25 19:56:48 +00003534 ExplodedNode *Pred = Ctx.getPredecessor();
Jordy Rose38f17d62011-08-23 19:01:07 +00003535
3536 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Jordan Rose2bce86c2012-08-18 00:30:16 +00003537 llvm::tie(Pred, state) = handleAutoreleaseCounts(state, Pred, /*Tag=*/0,
3538 Ctx, I->first, I->second);
Jordy Rose8d228632011-08-23 20:07:14 +00003539 if (!state)
Jordy Rose38f17d62011-08-23 19:01:07 +00003540 return;
3541 }
3542
Ted Kremenek0cf3d472012-02-07 00:24:33 +00003543 // If the current LocationContext has a parent, don't check for leaks.
3544 // We will do that later.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003545 // FIXME: we should instead check for imbalances of the retain/releases,
Ted Kremenek0cf3d472012-02-07 00:24:33 +00003546 // and suggest annotations.
3547 if (Ctx.getLocationContext()->getParent())
3548 return;
3549
Jordy Rose38f17d62011-08-23 19:01:07 +00003550 B = state->get<RefBindings>();
3551 SmallVector<SymbolRef, 10> Leaked;
3552
3553 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I)
Jordy Rose8d228632011-08-23 20:07:14 +00003554 state = handleSymbolDeath(state, I->first, I->second, Leaked);
Jordy Rose38f17d62011-08-23 19:01:07 +00003555
Jordan Rose2bce86c2012-08-18 00:30:16 +00003556 processLeaks(state, Leaked, Ctx, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003557}
3558
3559const ProgramPointTag *
Jordy Rose910c4052011-09-02 06:44:22 +00003560RetainCountChecker::getDeadSymbolTag(SymbolRef sym) const {
Jordy Rose38f17d62011-08-23 19:01:07 +00003561 const SimpleProgramPointTag *&tag = DeadSymbolTags[sym];
3562 if (!tag) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003563 SmallString<64> buf;
Jordy Rose38f17d62011-08-23 19:01:07 +00003564 llvm::raw_svector_ostream out(buf);
Anna Zaksf62ceec2011-12-05 18:58:11 +00003565 out << "RetainCountChecker : Dead Symbol : ";
3566 sym->dumpToStream(out);
Jordy Rose38f17d62011-08-23 19:01:07 +00003567 tag = new SimpleProgramPointTag(out.str());
3568 }
3569 return tag;
3570}
3571
Jordy Rose910c4052011-09-02 06:44:22 +00003572void RetainCountChecker::checkDeadSymbols(SymbolReaper &SymReaper,
3573 CheckerContext &C) const {
Jordy Rose38f17d62011-08-23 19:01:07 +00003574 ExplodedNode *Pred = C.getPredecessor();
3575
Ted Kremenek8bef8232012-01-26 21:29:00 +00003576 ProgramStateRef state = C.getState();
Jordy Rose38f17d62011-08-23 19:01:07 +00003577 RefBindings B = state->get<RefBindings>();
3578
3579 // Update counts from autorelease pools
3580 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3581 E = SymReaper.dead_end(); I != E; ++I) {
3582 SymbolRef Sym = *I;
3583 if (const RefVal *T = B.lookup(Sym)){
3584 // Use the symbol as the tag.
3585 // FIXME: This might not be as unique as we would like.
Jordan Rose2bce86c2012-08-18 00:30:16 +00003586 const ProgramPointTag *Tag = getDeadSymbolTag(Sym);
3587 llvm::tie(Pred, state) = handleAutoreleaseCounts(state, Pred, Tag, C,
Jordy Rose8d228632011-08-23 20:07:14 +00003588 Sym, *T);
3589 if (!state)
Jordy Rose38f17d62011-08-23 19:01:07 +00003590 return;
3591 }
3592 }
3593
3594 B = state->get<RefBindings>();
3595 SmallVector<SymbolRef, 10> Leaked;
3596
3597 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3598 E = SymReaper.dead_end(); I != E; ++I) {
3599 if (const RefVal *T = B.lookup(*I))
3600 state = handleSymbolDeath(state, *I, *T, Leaked);
3601 }
3602
Jordan Rose2bce86c2012-08-18 00:30:16 +00003603 Pred = processLeaks(state, Leaked, C, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003604
3605 // Did we cache out?
3606 if (!Pred)
3607 return;
3608
3609 // Now generate a new node that nukes the old bindings.
3610 RefBindings::Factory &F = state->get_context<RefBindings>();
3611
3612 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3613 E = SymReaper.dead_end(); I != E; ++I)
3614 B = F.remove(B, *I);
3615
3616 state = state->set<RefBindings>(B);
Anna Zaks0bd6b112011-10-26 21:06:34 +00003617 C.addTransition(state, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003618}
3619
Ted Kremenek8bef8232012-01-26 21:29:00 +00003620void RetainCountChecker::printState(raw_ostream &Out, ProgramStateRef State,
Jordy Rose910c4052011-09-02 06:44:22 +00003621 const char *NL, const char *Sep) const {
Jordy Rosedbd658e2011-08-28 19:11:56 +00003622
3623 RefBindings B = State->get<RefBindings>();
3624
3625 if (!B.isEmpty())
3626 Out << Sep << NL;
3627
3628 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
3629 Out << I->first << " : ";
3630 I->second.print(Out);
3631 Out << NL;
3632 }
Jordy Rosedbd658e2011-08-28 19:11:56 +00003633}
3634
3635//===----------------------------------------------------------------------===//
Jordy Rose910c4052011-09-02 06:44:22 +00003636// Checker registration.
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00003637//===----------------------------------------------------------------------===//
3638
Jordy Rose17a38e22011-09-02 05:55:19 +00003639void ento::registerRetainCountChecker(CheckerManager &Mgr) {
Jordy Rose910c4052011-09-02 06:44:22 +00003640 Mgr.registerChecker<RetainCountChecker>();
Jordy Rose17a38e22011-09-02 05:55:19 +00003641}
3642