blob: c84365e4a9ee655e8e8b4d0b1a60ecd342bdb9dd [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,
Jordy Rosebd85b132011-08-24 19:10:50 +000051 IncRefMsg, IncRef, MakeCollectable, MayEscape,
Anna Zaks554067f2012-08-29 23:23:43 +000052 NewAutoreleasePool,
53
54 // Stop tracking the argument - the effect of the call is
55 // unknown.
56 StopTracking,
57
58 // In some cases, we obtain a better summary for this checker
59 // by looking at the call site than by inlining the function.
60 // Signifies that we should stop tracking the symbol even if
61 // the function is inlined.
62 StopTrackingHard,
63
64 // The function decrements the reference count and the checker
65 // should stop tracking the argument.
66 DecRefAndStopTrackingHard, DecRefMsgAndStopTrackingHard
67 };
Ted Kremenek553cf182008-06-25 21:21:56 +000068
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000069namespace llvm {
Ted Kremenekb77449c2009-05-03 05:20:50 +000070template <> struct FoldingSetTrait<ArgEffect> {
71static inline void Profile(const ArgEffect X, FoldingSetNodeID& ID) {
72 ID.AddInteger((unsigned) X);
73}
Ted Kremenek553cf182008-06-25 21:21:56 +000074};
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000075} // end llvm namespace
76
Ted Kremenekb77449c2009-05-03 05:20:50 +000077/// ArgEffects summarizes the effects of a function/method call on all of
78/// its arguments.
79typedef llvm::ImmutableMap<unsigned,ArgEffect> ArgEffects;
80
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000081namespace {
Ted Kremenek553cf182008-06-25 21:21:56 +000082
83/// RetEffect is used to summarize a function/method call's behavior with
Mike Stump1eb44332009-09-09 15:08:12 +000084/// respect to its return value.
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +000085class RetEffect {
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000086public:
Jordy Rose76c506f2011-08-21 21:58:18 +000087 enum Kind { NoRet, OwnedSymbol, OwnedAllocatedSymbol,
John McCallf85e1932011-06-15 23:02:42 +000088 NotOwnedSymbol, GCNotOwnedSymbol, ARCNotOwnedSymbol,
Anna Zaks554067f2012-08-29 23:23:43 +000089 OwnedWhenTrackedReceiver,
90 // Treat this function as returning a non-tracked symbol even if
91 // the function has been inlined. This is used where the call
92 // site summary is more presise than the summary indirectly produced
93 // by inlining the function
94 NoRetHard
95 };
Mike Stump1eb44332009-09-09 15:08:12 +000096
97 enum ObjKind { CF, ObjC, AnyObj };
Ted Kremenek2d1652e2009-01-28 05:56:51 +000098
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000099private:
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000100 Kind K;
101 ObjKind O;
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000102
Jordy Rose76c506f2011-08-21 21:58:18 +0000103 RetEffect(Kind k, ObjKind o = AnyObj) : K(k), O(o) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000104
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000105public:
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000106 Kind getKind() const { return K; }
107
108 ObjKind getObjKind() const { return O; }
Mike Stump1eb44332009-09-09 15:08:12 +0000109
Ted Kremeneka8833552009-04-29 23:03:22 +0000110 bool isOwned() const {
Ted Kremenek78a35a32009-05-12 20:06:54 +0000111 return K == OwnedSymbol || K == OwnedAllocatedSymbol ||
112 K == OwnedWhenTrackedReceiver;
Ted Kremeneka8833552009-04-29 23:03:22 +0000113 }
Mike Stump1eb44332009-09-09 15:08:12 +0000114
Jordy Rose4df54fe2011-08-23 04:27:15 +0000115 bool operator==(const RetEffect &Other) const {
116 return K == Other.K && O == Other.O;
117 }
118
Ted Kremenek78a35a32009-05-12 20:06:54 +0000119 static RetEffect MakeOwnedWhenTrackedReceiver() {
120 return RetEffect(OwnedWhenTrackedReceiver, ObjC);
121 }
Mike Stump1eb44332009-09-09 15:08:12 +0000122
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000123 static RetEffect MakeOwned(ObjKind o, bool isAllocated = false) {
124 return RetEffect(isAllocated ? OwnedAllocatedSymbol : OwnedSymbol, o);
Mike Stump1eb44332009-09-09 15:08:12 +0000125 }
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000126 static RetEffect MakeNotOwned(ObjKind o) {
127 return RetEffect(NotOwnedSymbol, o);
Ted Kremeneke798e7c2009-04-27 19:14:45 +0000128 }
129 static RetEffect MakeGCNotOwned() {
130 return RetEffect(GCNotOwnedSymbol, ObjC);
131 }
John McCallf85e1932011-06-15 23:02:42 +0000132 static RetEffect MakeARCNotOwned() {
133 return RetEffect(ARCNotOwnedSymbol, ObjC);
134 }
Ted Kremenek553cf182008-06-25 21:21:56 +0000135 static RetEffect MakeNoRet() {
136 return RetEffect(NoRet);
Ted Kremeneka7344702008-06-23 18:02:52 +0000137 }
Anna Zaks554067f2012-08-29 23:23:43 +0000138 static RetEffect MakeNoRetHard() {
139 return RetEffect(NoRetHard);
140 }
Jordy Roseef945882012-03-18 01:26:10 +0000141
142 void Profile(llvm::FoldingSetNodeID& ID) const {
143 ID.AddInteger((unsigned) K);
144 ID.AddInteger((unsigned) O);
145 }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000146};
Mike Stump1eb44332009-09-09 15:08:12 +0000147
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000148//===----------------------------------------------------------------------===//
149// Reference-counting logic (typestate + counts).
150//===----------------------------------------------------------------------===//
Mike Stump1eb44332009-09-09 15:08:12 +0000151
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000152class RefVal {
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000153public:
154 enum Kind {
155 Owned = 0, // Owning reference.
156 NotOwned, // Reference is not owned by still valid (not freed).
157 Released, // Object has been released.
158 ReturnedOwned, // Returned object passes ownership to caller.
159 ReturnedNotOwned, // Return object does not pass ownership to caller.
160 ERROR_START,
161 ErrorDeallocNotOwned, // -dealloc called on non-owned object.
162 ErrorDeallocGC, // Calling -dealloc with GC enabled.
163 ErrorUseAfterRelease, // Object used after released.
164 ErrorReleaseNotOwned, // Release of an object that was not owned.
165 ERROR_LEAK_START,
166 ErrorLeak, // A memory leak due to excessive reference counts.
167 ErrorLeakReturned, // A memory leak due to the returning method not having
168 // the correct naming conventions.
169 ErrorGCLeakReturned,
170 ErrorOverAutorelease,
171 ErrorReturnedNotOwned
172 };
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000173
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000174private:
175 Kind kind;
176 RetEffect::ObjKind okind;
177 unsigned Cnt;
178 unsigned ACnt;
179 QualType T;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000180
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000181 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, unsigned acnt, QualType t)
182 : kind(k), okind(o), Cnt(cnt), ACnt(acnt), T(t) {}
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000183
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000184public:
185 Kind getKind() const { return kind; }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000186
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000187 RetEffect::ObjKind getObjKind() const { return okind; }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000188
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000189 unsigned getCount() const { return Cnt; }
190 unsigned getAutoreleaseCount() const { return ACnt; }
191 unsigned getCombinedCounts() const { return Cnt + ACnt; }
192 void clearCounts() { Cnt = 0; ACnt = 0; }
193 void setCount(unsigned i) { Cnt = i; }
194 void setAutoreleaseCount(unsigned i) { ACnt = i; }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000195
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000196 QualType getType() const { return T; }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000197
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000198 bool isOwned() const {
199 return getKind() == Owned;
200 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000201
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000202 bool isNotOwned() const {
203 return getKind() == NotOwned;
204 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000205
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000206 bool isReturnedOwned() const {
207 return getKind() == ReturnedOwned;
208 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000209
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000210 bool isReturnedNotOwned() const {
211 return getKind() == ReturnedNotOwned;
212 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000213
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000214 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
215 unsigned Count = 1) {
216 return RefVal(Owned, o, Count, 0, t);
217 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000218
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000219 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
220 unsigned Count = 0) {
221 return RefVal(NotOwned, o, Count, 0, t);
222 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000223
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000224 // Comparison, profiling, and pretty-printing.
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000225
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000226 bool operator==(const RefVal& X) const {
227 return kind == X.kind && Cnt == X.Cnt && T == X.T && ACnt == X.ACnt;
228 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000229
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000230 RefVal operator-(size_t i) const {
231 return RefVal(getKind(), getObjKind(), getCount() - i,
232 getAutoreleaseCount(), getType());
233 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000234
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000235 RefVal operator+(size_t i) const {
236 return RefVal(getKind(), getObjKind(), getCount() + i,
237 getAutoreleaseCount(), getType());
238 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000239
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000240 RefVal operator^(Kind k) const {
241 return RefVal(k, getObjKind(), getCount(), getAutoreleaseCount(),
242 getType());
243 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000244
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000245 RefVal autorelease() const {
246 return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount()+1,
247 getType());
248 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000249
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000250 void Profile(llvm::FoldingSetNodeID& ID) const {
251 ID.AddInteger((unsigned) kind);
252 ID.AddInteger(Cnt);
253 ID.AddInteger(ACnt);
254 ID.Add(T);
255 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000256
Ted Kremenek9c378f72011-08-12 23:37:29 +0000257 void print(raw_ostream &Out) const;
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000258};
259
Ted Kremenek9c378f72011-08-12 23:37:29 +0000260void RefVal::print(raw_ostream &Out) const {
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000261 if (!T.isNull())
Jordy Rosedbd658e2011-08-28 19:11:56 +0000262 Out << "Tracked " << T.getAsString() << '/';
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000263
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000264 switch (getKind()) {
Jordy Rose910c4052011-09-02 06:44:22 +0000265 default: llvm_unreachable("Invalid RefVal kind");
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000266 case Owned: {
267 Out << "Owned";
268 unsigned cnt = getCount();
269 if (cnt) Out << " (+ " << cnt << ")";
270 break;
271 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000272
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000273 case NotOwned: {
274 Out << "NotOwned";
275 unsigned cnt = getCount();
276 if (cnt) Out << " (+ " << cnt << ")";
277 break;
278 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000279
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000280 case ReturnedOwned: {
281 Out << "ReturnedOwned";
282 unsigned cnt = getCount();
283 if (cnt) Out << " (+ " << cnt << ")";
284 break;
285 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000286
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000287 case ReturnedNotOwned: {
288 Out << "ReturnedNotOwned";
289 unsigned cnt = getCount();
290 if (cnt) Out << " (+ " << cnt << ")";
291 break;
292 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000293
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000294 case Released:
295 Out << "Released";
296 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000297
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000298 case ErrorDeallocGC:
299 Out << "-dealloc (GC)";
300 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000301
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000302 case ErrorDeallocNotOwned:
303 Out << "-dealloc (not-owned)";
304 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000305
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000306 case ErrorLeak:
307 Out << "Leaked";
308 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000309
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000310 case ErrorLeakReturned:
311 Out << "Leaked (Bad naming)";
312 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000313
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000314 case ErrorGCLeakReturned:
315 Out << "Leaked (GC-ed at return)";
316 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000317
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000318 case ErrorUseAfterRelease:
319 Out << "Use-After-Release [ERROR]";
320 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000321
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000322 case ErrorReleaseNotOwned:
323 Out << "Release of Not-Owned [ERROR]";
324 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000325
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000326 case RefVal::ErrorOverAutorelease:
327 Out << "Over autoreleased";
328 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000329
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000330 case RefVal::ErrorReturnedNotOwned:
331 Out << "Non-owned object returned instead of owned";
332 break;
333 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000334
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000335 if (ACnt) {
336 Out << " [ARC +" << ACnt << ']';
337 }
338}
339} //end anonymous namespace
340
341//===----------------------------------------------------------------------===//
342// RefBindings - State used to track object reference counts.
343//===----------------------------------------------------------------------===//
344
345typedef llvm::ImmutableMap<SymbolRef, RefVal> RefBindings;
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000346
347namespace clang {
Ted Kremenek9ef65372010-12-23 07:20:52 +0000348namespace ento {
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000349template<>
350struct ProgramStateTrait<RefBindings>
351 : public ProgramStatePartialTrait<RefBindings> {
352 static void *GDMIndex() {
353 static int RefBIndex = 0;
354 return &RefBIndex;
355 }
356};
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000357}
Argyrios Kyrtzidis5a4f98f2010-12-22 18:53:20 +0000358}
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000359
Anna Zaks8d6b43c2012-08-14 00:36:15 +0000360static inline const RefVal *getRefBinding(ProgramStateRef State,
361 SymbolRef Sym) {
362 return State->get<RefBindings>(Sym);
363}
364
365static inline ProgramStateRef setRefBinding(ProgramStateRef State,
366 SymbolRef Sym, RefVal Val) {
367 return State->set<RefBindings>(Sym, Val);
368}
369
370static ProgramStateRef removeRefBinding(ProgramStateRef State, SymbolRef Sym) {
371 return State->remove<RefBindings>(Sym);
372}
373
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000374//===----------------------------------------------------------------------===//
Jordy Rose910c4052011-09-02 06:44:22 +0000375// Function/Method behavior summaries.
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000376//===----------------------------------------------------------------------===//
377
378namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000379class RetainSummary {
Jordy Roseef945882012-03-18 01:26:10 +0000380 /// Args - a map of (index, ArgEffect) pairs, where index
Ted Kremenek1bffd742008-05-06 15:44:25 +0000381 /// specifies the argument (starting from 0). This can be sparsely
382 /// populated; arguments with no entry in Args use 'DefaultArgEffect'.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000383 ArgEffects Args;
Mike Stump1eb44332009-09-09 15:08:12 +0000384
Ted Kremenek1bffd742008-05-06 15:44:25 +0000385 /// DefaultArgEffect - The default ArgEffect to apply to arguments that
386 /// do not have an entry in Args.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000387 ArgEffect DefaultArgEffect;
Mike Stump1eb44332009-09-09 15:08:12 +0000388
Ted Kremenek553cf182008-06-25 21:21:56 +0000389 /// Receiver - If this summary applies to an Objective-C message expression,
390 /// this is the effect applied to the state of the receiver.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000391 ArgEffect Receiver;
Mike Stump1eb44332009-09-09 15:08:12 +0000392
Ted Kremenek553cf182008-06-25 21:21:56 +0000393 /// Ret - The effect on the return value. Used to indicate if the
Jordy Rose76c506f2011-08-21 21:58:18 +0000394 /// function/method call returns a new tracked symbol.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000395 RetEffect Ret;
Mike Stump1eb44332009-09-09 15:08:12 +0000396
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000397public:
Ted Kremenekb77449c2009-05-03 05:20:50 +0000398 RetainSummary(ArgEffects A, RetEffect R, ArgEffect defaultEff,
Jordy Rosee62e87b2011-08-20 20:55:40 +0000399 ArgEffect ReceiverEff)
400 : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000401
Ted Kremenek553cf182008-06-25 21:21:56 +0000402 /// getArg - Return the argument effect on the argument specified by
403 /// idx (starting from 0).
Ted Kremenek1ac08d62008-03-11 17:48:22 +0000404 ArgEffect getArg(unsigned idx) const {
Ted Kremenekb77449c2009-05-03 05:20:50 +0000405 if (const ArgEffect *AE = Args.lookup(idx))
406 return *AE;
Mike Stump1eb44332009-09-09 15:08:12 +0000407
Ted Kremenek1bffd742008-05-06 15:44:25 +0000408 return DefaultArgEffect;
Ted Kremenek1ac08d62008-03-11 17:48:22 +0000409 }
Ted Kremenek11fe1752011-01-27 18:43:03 +0000410
411 void addArg(ArgEffects::Factory &af, unsigned idx, ArgEffect e) {
412 Args = af.add(Args, idx, e);
413 }
Mike Stump1eb44332009-09-09 15:08:12 +0000414
Ted Kremenek885c27b2009-05-04 05:31:22 +0000415 /// setDefaultArgEffect - Set the default argument effect.
416 void setDefaultArgEffect(ArgEffect E) {
417 DefaultArgEffect = E;
418 }
Mike Stump1eb44332009-09-09 15:08:12 +0000419
Ted Kremenek553cf182008-06-25 21:21:56 +0000420 /// getRetEffect - Returns the effect on the return value of the call.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000421 RetEffect getRetEffect() const { return Ret; }
Mike Stump1eb44332009-09-09 15:08:12 +0000422
Ted Kremenek885c27b2009-05-04 05:31:22 +0000423 /// setRetEffect - Set the effect of the return value of the call.
424 void setRetEffect(RetEffect E) { Ret = E; }
Mike Stump1eb44332009-09-09 15:08:12 +0000425
Ted Kremenek12b94342011-01-27 06:54:14 +0000426
427 /// Sets the effect on the receiver of the message.
428 void setReceiverEffect(ArgEffect e) { Receiver = e; }
429
Ted Kremenek553cf182008-06-25 21:21:56 +0000430 /// getReceiverEffect - Returns the effect on the receiver of the call.
431 /// This is only meaningful if the summary applies to an ObjCMessageExpr*.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000432 ArgEffect getReceiverEffect() const { return Receiver; }
Jordy Rose4df54fe2011-08-23 04:27:15 +0000433
434 /// Test if two retain summaries are identical. Note that merely equivalent
435 /// summaries are not necessarily identical (for example, if an explicit
436 /// argument effect matches the default effect).
437 bool operator==(const RetainSummary &Other) const {
438 return Args == Other.Args && DefaultArgEffect == Other.DefaultArgEffect &&
439 Receiver == Other.Receiver && Ret == Other.Ret;
440 }
Jordy Roseef945882012-03-18 01:26:10 +0000441
442 /// Profile this summary for inclusion in a FoldingSet.
443 void Profile(llvm::FoldingSetNodeID& ID) const {
444 ID.Add(Args);
445 ID.Add(DefaultArgEffect);
446 ID.Add(Receiver);
447 ID.Add(Ret);
448 }
449
450 /// A retain summary is simple if it has no ArgEffects other than the default.
451 bool isSimple() const {
452 return Args.isEmpty();
453 }
Jordan Rose4531b7d2012-07-02 19:27:43 +0000454
455private:
456 ArgEffects getArgEffects() const { return Args; }
457 ArgEffect getDefaultArgEffect() const { return DefaultArgEffect; }
458
459 friend class RetainSummaryManager;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000460};
Ted Kremenek4f22a782008-06-23 23:30:29 +0000461} // end anonymous namespace
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000462
Ted Kremenek553cf182008-06-25 21:21:56 +0000463//===----------------------------------------------------------------------===//
464// Data structures for constructing summaries.
465//===----------------------------------------------------------------------===//
Ted Kremenek53301ba2008-06-24 03:49:48 +0000466
Ted Kremenek553cf182008-06-25 21:21:56 +0000467namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000468class ObjCSummaryKey {
Ted Kremenek553cf182008-06-25 21:21:56 +0000469 IdentifierInfo* II;
470 Selector S;
Mike Stump1eb44332009-09-09 15:08:12 +0000471public:
Ted Kremenek553cf182008-06-25 21:21:56 +0000472 ObjCSummaryKey(IdentifierInfo* ii, Selector s)
473 : II(ii), S(s) {}
474
Ted Kremenek9c378f72011-08-12 23:37:29 +0000475 ObjCSummaryKey(const ObjCInterfaceDecl *d, Selector s)
Ted Kremenek553cf182008-06-25 21:21:56 +0000476 : II(d ? d->getIdentifier() : 0), S(s) {}
Ted Kremenek70b6a832009-05-13 18:16:01 +0000477
Ted Kremenek553cf182008-06-25 21:21:56 +0000478 ObjCSummaryKey(Selector s)
479 : II(0), S(s) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000480
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000481 IdentifierInfo *getIdentifier() const { return II; }
Ted Kremenek553cf182008-06-25 21:21:56 +0000482 Selector getSelector() const { return S; }
483};
Ted Kremenek4f22a782008-06-23 23:30:29 +0000484}
485
486namespace llvm {
Ted Kremenek553cf182008-06-25 21:21:56 +0000487template <> struct DenseMapInfo<ObjCSummaryKey> {
488 static inline ObjCSummaryKey getEmptyKey() {
489 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
490 DenseMapInfo<Selector>::getEmptyKey());
491 }
Mike Stump1eb44332009-09-09 15:08:12 +0000492
Ted Kremenek553cf182008-06-25 21:21:56 +0000493 static inline ObjCSummaryKey getTombstoneKey() {
494 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
Mike Stump1eb44332009-09-09 15:08:12 +0000495 DenseMapInfo<Selector>::getTombstoneKey());
Ted Kremenek553cf182008-06-25 21:21:56 +0000496 }
Mike Stump1eb44332009-09-09 15:08:12 +0000497
Ted Kremenek553cf182008-06-25 21:21:56 +0000498 static unsigned getHashValue(const ObjCSummaryKey &V) {
Benjamin Kramer28b23072012-05-27 13:28:44 +0000499 typedef std::pair<IdentifierInfo*, Selector> PairTy;
500 return DenseMapInfo<PairTy>::getHashValue(PairTy(V.getIdentifier(),
501 V.getSelector()));
Ted Kremenek553cf182008-06-25 21:21:56 +0000502 }
Mike Stump1eb44332009-09-09 15:08:12 +0000503
Ted Kremenek553cf182008-06-25 21:21:56 +0000504 static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
Benjamin Kramer28b23072012-05-27 13:28:44 +0000505 return LHS.getIdentifier() == RHS.getIdentifier() &&
506 LHS.getSelector() == RHS.getSelector();
Ted Kremenek553cf182008-06-25 21:21:56 +0000507 }
Mike Stump1eb44332009-09-09 15:08:12 +0000508
Ted Kremenek553cf182008-06-25 21:21:56 +0000509};
Chris Lattner06159e82009-12-15 07:26:51 +0000510template <>
511struct isPodLike<ObjCSummaryKey> { static const bool value = true; };
Ted Kremenek4f22a782008-06-23 23:30:29 +0000512} // end llvm namespace
Mike Stump1eb44332009-09-09 15:08:12 +0000513
Ted Kremenek4f22a782008-06-23 23:30:29 +0000514namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000515class ObjCSummaryCache {
Ted Kremenek93edbc52011-10-05 23:54:29 +0000516 typedef llvm::DenseMap<ObjCSummaryKey, const RetainSummary *> MapTy;
Ted Kremenek553cf182008-06-25 21:21:56 +0000517 MapTy M;
518public:
519 ObjCSummaryCache() {}
Mike Stump1eb44332009-09-09 15:08:12 +0000520
Ted Kremenek93edbc52011-10-05 23:54:29 +0000521 const RetainSummary * find(const ObjCInterfaceDecl *D, Selector S) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000522 // Do a lookup with the (D,S) pair. If we find a match return
523 // the iterator.
524 ObjCSummaryKey K(D, S);
525 MapTy::iterator I = M.find(K);
Mike Stump1eb44332009-09-09 15:08:12 +0000526
Jordan Rose4531b7d2012-07-02 19:27:43 +0000527 if (I != M.end())
Ted Kremenek614cc542009-07-21 23:27:57 +0000528 return I->second;
Jordan Rose4531b7d2012-07-02 19:27:43 +0000529 if (!D)
530 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +0000531
Ted Kremenek553cf182008-06-25 21:21:56 +0000532 // Walk the super chain. If we find a hit with a parent, we'll end
533 // up returning that summary. We actually allow that key (null,S), as
534 // we cache summaries for the null ObjCInterfaceDecl* to allow us to
535 // generate initial summaries without having to worry about NSObject
536 // being declared.
537 // FIXME: We may change this at some point.
Ted Kremenek9c378f72011-08-12 23:37:29 +0000538 for (ObjCInterfaceDecl *C=D->getSuperClass() ;; C=C->getSuperClass()) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000539 if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
540 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000541
Ted Kremenek553cf182008-06-25 21:21:56 +0000542 if (!C)
Ted Kremenek614cc542009-07-21 23:27:57 +0000543 return NULL;
Ted Kremenek553cf182008-06-25 21:21:56 +0000544 }
Mike Stump1eb44332009-09-09 15:08:12 +0000545
546 // Cache the summary with original key to make the next lookup faster
Ted Kremenek553cf182008-06-25 21:21:56 +0000547 // and return the iterator.
Ted Kremenek93edbc52011-10-05 23:54:29 +0000548 const RetainSummary *Summ = I->second;
Ted Kremenek614cc542009-07-21 23:27:57 +0000549 M[K] = Summ;
550 return Summ;
Ted Kremenek553cf182008-06-25 21:21:56 +0000551 }
Mike Stump1eb44332009-09-09 15:08:12 +0000552
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000553 const RetainSummary *find(IdentifierInfo* II, Selector S) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000554 // FIXME: Class method lookup. Right now we dont' have a good way
555 // of going between IdentifierInfo* and the class hierarchy.
Ted Kremenek614cc542009-07-21 23:27:57 +0000556 MapTy::iterator I = M.find(ObjCSummaryKey(II, S));
Mike Stump1eb44332009-09-09 15:08:12 +0000557
Ted Kremenek614cc542009-07-21 23:27:57 +0000558 if (I == M.end())
559 I = M.find(ObjCSummaryKey(S));
Mike Stump1eb44332009-09-09 15:08:12 +0000560
Ted Kremenek614cc542009-07-21 23:27:57 +0000561 return I == M.end() ? NULL : I->second;
Ted Kremenek553cf182008-06-25 21:21:56 +0000562 }
Mike Stump1eb44332009-09-09 15:08:12 +0000563
Ted Kremenek93edbc52011-10-05 23:54:29 +0000564 const RetainSummary *& operator[](ObjCSummaryKey K) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000565 return M[K];
566 }
Mike Stump1eb44332009-09-09 15:08:12 +0000567
Ted Kremenek93edbc52011-10-05 23:54:29 +0000568 const RetainSummary *& operator[](Selector S) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000569 return M[ ObjCSummaryKey(S) ];
570 }
Mike Stump1eb44332009-09-09 15:08:12 +0000571};
Ted Kremenek553cf182008-06-25 21:21:56 +0000572} // end anonymous namespace
573
574//===----------------------------------------------------------------------===//
575// Data structures for managing collections of summaries.
576//===----------------------------------------------------------------------===//
577
578namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000579class RetainSummaryManager {
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000580
581 //==-----------------------------------------------------------------==//
582 // Typedefs.
583 //==-----------------------------------------------------------------==//
Mike Stump1eb44332009-09-09 15:08:12 +0000584
Ted Kremenek93edbc52011-10-05 23:54:29 +0000585 typedef llvm::DenseMap<const FunctionDecl*, const RetainSummary *>
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000586 FuncSummariesTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000587
Ted Kremenek4f22a782008-06-23 23:30:29 +0000588 typedef ObjCSummaryCache ObjCMethodSummariesTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000589
Jordy Roseef945882012-03-18 01:26:10 +0000590 typedef llvm::FoldingSetNodeWrapper<RetainSummary> CachedSummaryNode;
591
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000592 //==-----------------------------------------------------------------==//
593 // Data.
594 //==-----------------------------------------------------------------==//
Mike Stump1eb44332009-09-09 15:08:12 +0000595
Ted Kremenek553cf182008-06-25 21:21:56 +0000596 /// Ctx - The ASTContext object for the analyzed ASTs.
Ted Kremenek9c378f72011-08-12 23:37:29 +0000597 ASTContext &Ctx;
Ted Kremenek179064e2008-07-01 17:21:27 +0000598
Ted Kremenek553cf182008-06-25 21:21:56 +0000599 /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
Ted Kremenek377e2302008-04-29 05:33:51 +0000600 const bool GCEnabled;
Mike Stump1eb44332009-09-09 15:08:12 +0000601
John McCallf85e1932011-06-15 23:02:42 +0000602 /// Records whether or not the analyzed code runs in ARC mode.
603 const bool ARCEnabled;
604
Ted Kremenek553cf182008-06-25 21:21:56 +0000605 /// FuncSummaries - A map from FunctionDecls to summaries.
Mike Stump1eb44332009-09-09 15:08:12 +0000606 FuncSummariesTy FuncSummaries;
607
Ted Kremenek553cf182008-06-25 21:21:56 +0000608 /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
609 /// to summaries.
Ted Kremenek1f180c32008-06-23 22:21:20 +0000610 ObjCMethodSummariesTy ObjCClassMethodSummaries;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000611
Ted Kremenek553cf182008-06-25 21:21:56 +0000612 /// ObjCMethodSummaries - A map from selectors to summaries.
Ted Kremenek1f180c32008-06-23 22:21:20 +0000613 ObjCMethodSummariesTy ObjCMethodSummaries;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000614
Ted Kremenek553cf182008-06-25 21:21:56 +0000615 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
616 /// and all other data used by the checker.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000617 llvm::BumpPtrAllocator BPAlloc;
Mike Stump1eb44332009-09-09 15:08:12 +0000618
Ted Kremenekb77449c2009-05-03 05:20:50 +0000619 /// AF - A factory for ArgEffects objects.
Mike Stump1eb44332009-09-09 15:08:12 +0000620 ArgEffects::Factory AF;
621
Ted Kremenek553cf182008-06-25 21:21:56 +0000622 /// ScratchArgs - A holding buffer for construct ArgEffects.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000623 ArgEffects ScratchArgs;
Mike Stump1eb44332009-09-09 15:08:12 +0000624
Ted Kremenekec315332009-05-07 23:40:42 +0000625 /// ObjCAllocRetE - Default return effect for methods returning Objective-C
626 /// objects.
627 RetEffect ObjCAllocRetE;
Ted Kremenek547d4952009-06-05 23:18:01 +0000628
Mike Stump1eb44332009-09-09 15:08:12 +0000629 /// ObjCInitRetE - Default return effect for init methods returning
Ted Kremenekac02f202009-08-20 05:13:36 +0000630 /// Objective-C objects.
Ted Kremenek547d4952009-06-05 23:18:01 +0000631 RetEffect ObjCInitRetE;
Mike Stump1eb44332009-09-09 15:08:12 +0000632
Jordy Roseef945882012-03-18 01:26:10 +0000633 /// SimpleSummaries - Used for uniquing summaries that don't have special
634 /// effects.
635 llvm::FoldingSet<CachedSummaryNode> SimpleSummaries;
Mike Stump1eb44332009-09-09 15:08:12 +0000636
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000637 //==-----------------------------------------------------------------==//
638 // Methods.
639 //==-----------------------------------------------------------------==//
Mike Stump1eb44332009-09-09 15:08:12 +0000640
Ted Kremenek553cf182008-06-25 21:21:56 +0000641 /// getArgEffects - Returns a persistent ArgEffects object based on the
642 /// data in ScratchArgs.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000643 ArgEffects getArgEffects();
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000644
Mike Stump1eb44332009-09-09 15:08:12 +0000645 enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
Ted Kremenek93edbc52011-10-05 23:54:29 +0000646
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000647 const RetainSummary *getUnarySummary(const FunctionType* FT,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000648 UnaryFuncKind func);
Mike Stump1eb44332009-09-09 15:08:12 +0000649
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000650 const RetainSummary *getCFSummaryCreateRule(const FunctionDecl *FD);
651 const RetainSummary *getCFSummaryGetRule(const FunctionDecl *FD);
652 const RetainSummary *getCFCreateGetRuleSummary(const FunctionDecl *FD);
Mike Stump1eb44332009-09-09 15:08:12 +0000653
Jordy Roseef945882012-03-18 01:26:10 +0000654 const RetainSummary *getPersistentSummary(const RetainSummary &OldSumm);
Ted Kremenek706522f2008-10-29 04:07:07 +0000655
Jordy Roseef945882012-03-18 01:26:10 +0000656 const RetainSummary *getPersistentSummary(RetEffect RetEff,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000657 ArgEffect ReceiverEff = DoNothing,
658 ArgEffect DefaultEff = MayEscape) {
Jordy Roseef945882012-03-18 01:26:10 +0000659 RetainSummary Summ(getArgEffects(), RetEff, DefaultEff, ReceiverEff);
660 return getPersistentSummary(Summ);
661 }
662
Ted Kremenekc91fdf62012-05-08 00:12:09 +0000663 const RetainSummary *getDoNothingSummary() {
664 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
665 }
666
Jordy Roseef945882012-03-18 01:26:10 +0000667 const RetainSummary *getDefaultSummary() {
668 return getPersistentSummary(RetEffect::MakeNoRet(),
669 DoNothing, MayEscape);
Ted Kremenek9c32d082008-05-06 00:30:21 +0000670 }
Mike Stump1eb44332009-09-09 15:08:12 +0000671
Ted Kremenek93edbc52011-10-05 23:54:29 +0000672 const RetainSummary *getPersistentStopSummary() {
Jordy Roseef945882012-03-18 01:26:10 +0000673 return getPersistentSummary(RetEffect::MakeNoRet(),
674 StopTracking, StopTracking);
Mike Stump1eb44332009-09-09 15:08:12 +0000675 }
Ted Kremenekb3095252008-05-06 04:20:12 +0000676
Ted Kremenek1f180c32008-06-23 22:21:20 +0000677 void InitializeClassMethodSummaries();
678 void InitializeMethodSummaries();
Ted Kremenek896cd9d2008-10-23 01:56:15 +0000679private:
Ted Kremenek93edbc52011-10-05 23:54:29 +0000680 void addNSObjectClsMethSummary(Selector S, const RetainSummary *Summ) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000681 ObjCClassMethodSummaries[S] = Summ;
682 }
Mike Stump1eb44332009-09-09 15:08:12 +0000683
Ted Kremenek93edbc52011-10-05 23:54:29 +0000684 void addNSObjectMethSummary(Selector S, const RetainSummary *Summ) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000685 ObjCMethodSummaries[S] = Summ;
686 }
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +0000687
Ted Kremeneka9797122012-02-18 21:37:48 +0000688 void addClassMethSummary(const char* Cls, const char* name,
689 const RetainSummary *Summ, bool isNullary = true) {
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +0000690 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
Ted Kremeneka9797122012-02-18 21:37:48 +0000691 Selector S = isNullary ? GetNullarySelector(name, Ctx)
692 : GetUnarySelector(name, Ctx);
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +0000693 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
694 }
Mike Stump1eb44332009-09-09 15:08:12 +0000695
Ted Kremenek6c4becb2009-02-25 02:54:57 +0000696 void addInstMethSummary(const char* Cls, const char* nullaryName,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000697 const RetainSummary *Summ) {
Ted Kremenek6c4becb2009-02-25 02:54:57 +0000698 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
699 Selector S = GetNullarySelector(nullaryName, Ctx);
700 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
701 }
Mike Stump1eb44332009-09-09 15:08:12 +0000702
Ted Kremenekde4d5332009-04-24 17:50:11 +0000703 Selector generateSelector(va_list argp) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000704 SmallVector<IdentifierInfo*, 10> II;
Ted Kremenekde4d5332009-04-24 17:50:11 +0000705
Ted Kremenek9e476de2008-08-12 18:30:56 +0000706 while (const char* s = va_arg(argp, const char*))
707 II.push_back(&Ctx.Idents.get(s));
Ted Kremenekde4d5332009-04-24 17:50:11 +0000708
Mike Stump1eb44332009-09-09 15:08:12 +0000709 return Ctx.Selectors.getSelector(II.size(), &II[0]);
Ted Kremenekde4d5332009-04-24 17:50:11 +0000710 }
Mike Stump1eb44332009-09-09 15:08:12 +0000711
Ted Kremenekde4d5332009-04-24 17:50:11 +0000712 void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy& Summaries,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000713 const RetainSummary * Summ, va_list argp) {
Ted Kremenekde4d5332009-04-24 17:50:11 +0000714 Selector S = generateSelector(argp);
715 Summaries[ObjCSummaryKey(ClsII, S)] = Summ;
Ted Kremenek70a733e2008-07-18 17:24:20 +0000716 }
Mike Stump1eb44332009-09-09 15:08:12 +0000717
Ted Kremenek93edbc52011-10-05 23:54:29 +0000718 void addInstMethSummary(const char* Cls, const RetainSummary * Summ, ...) {
Ted Kremenekaf9dc272008-08-12 18:48:50 +0000719 va_list argp;
720 va_start(argp, Summ);
Ted Kremenekde4d5332009-04-24 17:50:11 +0000721 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Mike Stump1eb44332009-09-09 15:08:12 +0000722 va_end(argp);
Ted Kremenekaf9dc272008-08-12 18:48:50 +0000723 }
Mike Stump1eb44332009-09-09 15:08:12 +0000724
Ted Kremenek93edbc52011-10-05 23:54:29 +0000725 void addClsMethSummary(const char* Cls, const RetainSummary * Summ, ...) {
Ted Kremenekde4d5332009-04-24 17:50:11 +0000726 va_list argp;
727 va_start(argp, Summ);
728 addMethodSummary(&Ctx.Idents.get(Cls),ObjCClassMethodSummaries, Summ, argp);
729 va_end(argp);
730 }
Mike Stump1eb44332009-09-09 15:08:12 +0000731
Ted Kremenek93edbc52011-10-05 23:54:29 +0000732 void addClsMethSummary(IdentifierInfo *II, const RetainSummary * Summ, ...) {
Ted Kremenekde4d5332009-04-24 17:50:11 +0000733 va_list argp;
734 va_start(argp, Summ);
735 addMethodSummary(II, ObjCClassMethodSummaries, Summ, argp);
736 va_end(argp);
737 }
738
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000739public:
Mike Stump1eb44332009-09-09 15:08:12 +0000740
Ted Kremenek9c378f72011-08-12 23:37:29 +0000741 RetainSummaryManager(ASTContext &ctx, bool gcenabled, bool usesARC)
Ted Kremenek179064e2008-07-01 17:21:27 +0000742 : Ctx(ctx),
John McCallf85e1932011-06-15 23:02:42 +0000743 GCEnabled(gcenabled),
744 ARCEnabled(usesARC),
745 AF(BPAlloc), ScratchArgs(AF.getEmptyMap()),
746 ObjCAllocRetE(gcenabled
747 ? RetEffect::MakeGCNotOwned()
748 : (usesARC ? RetEffect::MakeARCNotOwned()
749 : RetEffect::MakeOwned(RetEffect::ObjC, true))),
750 ObjCInitRetE(gcenabled
751 ? RetEffect::MakeGCNotOwned()
752 : (usesARC ? RetEffect::MakeARCNotOwned()
Jordy Roseef945882012-03-18 01:26:10 +0000753 : RetEffect::MakeOwnedWhenTrackedReceiver())) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000754 InitializeClassMethodSummaries();
755 InitializeMethodSummaries();
756 }
Mike Stump1eb44332009-09-09 15:08:12 +0000757
Jordan Rose4531b7d2012-07-02 19:27:43 +0000758 const RetainSummary *getSummary(const CallEvent &Call,
759 ProgramStateRef State = 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000760
Jordan Rose4531b7d2012-07-02 19:27:43 +0000761 const RetainSummary *getFunctionSummary(const FunctionDecl *FD);
762
763 const RetainSummary *getMethodSummary(Selector S, const ObjCInterfaceDecl *ID,
Jordy Rosef3aae582012-03-17 21:13:07 +0000764 const ObjCMethodDecl *MD,
765 QualType RetTy,
766 ObjCMethodSummariesTy &CachedSummaries);
767
Jordan Rosecde8cdb2012-07-02 19:27:56 +0000768 const RetainSummary *getInstanceMethodSummary(const ObjCMethodCall &M,
Jordan Rose4531b7d2012-07-02 19:27:43 +0000769 ProgramStateRef State);
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000770
Jordan Rosecde8cdb2012-07-02 19:27:56 +0000771 const RetainSummary *getClassMethodSummary(const ObjCMethodCall &M) {
Jordan Rose4531b7d2012-07-02 19:27:43 +0000772 assert(!M.isInstanceMessage());
773 const ObjCInterfaceDecl *Class = M.getReceiverInterface();
Mike Stump1eb44332009-09-09 15:08:12 +0000774
Jordan Rose4531b7d2012-07-02 19:27:43 +0000775 return getMethodSummary(M.getSelector(), Class, M.getDecl(),
776 M.getResultType(), ObjCClassMethodSummaries);
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +0000777 }
Ted Kremenek552333c2009-04-29 17:17:48 +0000778
779 /// getMethodSummary - This version of getMethodSummary is used to query
780 /// the summary for the current method being analyzed.
Ted Kremenek93edbc52011-10-05 23:54:29 +0000781 const RetainSummary *getMethodSummary(const ObjCMethodDecl *MD) {
Ted Kremeneka8833552009-04-29 23:03:22 +0000782 const ObjCInterfaceDecl *ID = MD->getClassInterface();
Ted Kremenek70a65762009-04-30 05:41:14 +0000783 Selector S = MD->getSelector();
Ted Kremenek552333c2009-04-29 17:17:48 +0000784 QualType ResultTy = MD->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +0000785
Jordy Rosef3aae582012-03-17 21:13:07 +0000786 ObjCMethodSummariesTy *CachedSummaries;
Ted Kremenek552333c2009-04-29 17:17:48 +0000787 if (MD->isInstanceMethod())
Jordy Rosef3aae582012-03-17 21:13:07 +0000788 CachedSummaries = &ObjCMethodSummaries;
Ted Kremenek552333c2009-04-29 17:17:48 +0000789 else
Jordy Rosef3aae582012-03-17 21:13:07 +0000790 CachedSummaries = &ObjCClassMethodSummaries;
791
Jordan Rose4531b7d2012-07-02 19:27:43 +0000792 return getMethodSummary(S, ID, MD, ResultTy, *CachedSummaries);
Ted Kremenek552333c2009-04-29 17:17:48 +0000793 }
Mike Stump1eb44332009-09-09 15:08:12 +0000794
Jordy Rosef3aae582012-03-17 21:13:07 +0000795 const RetainSummary *getStandardMethodSummary(const ObjCMethodDecl *MD,
Jordan Rose4531b7d2012-07-02 19:27:43 +0000796 Selector S, QualType RetTy);
Ted Kremeneka8833552009-04-29 23:03:22 +0000797
Ted Kremenek93edbc52011-10-05 23:54:29 +0000798 void updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenek4dd8fb42009-05-09 02:58:13 +0000799 const ObjCMethodDecl *MD);
800
Ted Kremenek93edbc52011-10-05 23:54:29 +0000801 void updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenek4dd8fb42009-05-09 02:58:13 +0000802 const FunctionDecl *FD);
803
Jordan Rose4531b7d2012-07-02 19:27:43 +0000804 void updateSummaryForCall(const RetainSummary *&Summ,
805 const CallEvent &Call);
806
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000807 bool isGCEnabled() const { return GCEnabled; }
Mike Stump1eb44332009-09-09 15:08:12 +0000808
John McCallf85e1932011-06-15 23:02:42 +0000809 bool isARCEnabled() const { return ARCEnabled; }
810
811 bool isARCorGCEnabled() const { return GCEnabled || ARCEnabled; }
Jordan Rose4531b7d2012-07-02 19:27:43 +0000812
813 RetEffect getObjAllocRetEffect() const { return ObjCAllocRetE; }
814
815 friend class RetainSummaryTemplate;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000816};
Mike Stump1eb44332009-09-09 15:08:12 +0000817
Jordy Rose0fe62f82011-08-24 09:02:37 +0000818// Used to avoid allocating long-term (BPAlloc'd) memory for default retain
819// summaries. If a function or method looks like it has a default summary, but
820// it has annotations, the annotations are added to the stack-based template
821// and then copied into managed memory.
822class RetainSummaryTemplate {
823 RetainSummaryManager &Manager;
Ted Kremenek93edbc52011-10-05 23:54:29 +0000824 const RetainSummary *&RealSummary;
Jordy Rose0fe62f82011-08-24 09:02:37 +0000825 RetainSummary ScratchSummary;
826 bool Accessed;
827public:
Jordan Rose4531b7d2012-07-02 19:27:43 +0000828 RetainSummaryTemplate(const RetainSummary *&real, RetainSummaryManager &mgr)
829 : Manager(mgr), RealSummary(real), ScratchSummary(*real), Accessed(false) {}
Jordy Rose0fe62f82011-08-24 09:02:37 +0000830
831 ~RetainSummaryTemplate() {
Ted Kremenek93edbc52011-10-05 23:54:29 +0000832 if (Accessed)
Jordy Roseef945882012-03-18 01:26:10 +0000833 RealSummary = Manager.getPersistentSummary(ScratchSummary);
Jordy Rose0fe62f82011-08-24 09:02:37 +0000834 }
835
836 RetainSummary &operator*() {
837 Accessed = true;
Ted Kremenek93edbc52011-10-05 23:54:29 +0000838 return ScratchSummary;
Jordy Rose0fe62f82011-08-24 09:02:37 +0000839 }
840
841 RetainSummary *operator->() {
842 Accessed = true;
Ted Kremenek93edbc52011-10-05 23:54:29 +0000843 return &ScratchSummary;
Jordy Rose0fe62f82011-08-24 09:02:37 +0000844 }
845};
846
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000847} // end anonymous namespace
848
849//===----------------------------------------------------------------------===//
850// Implementation of checker data structures.
851//===----------------------------------------------------------------------===//
852
Ted Kremenekb77449c2009-05-03 05:20:50 +0000853ArgEffects RetainSummaryManager::getArgEffects() {
854 ArgEffects AE = ScratchArgs;
Ted Kremenek3baf6722010-11-24 00:54:37 +0000855 ScratchArgs = AF.getEmptyMap();
Ted Kremenekb77449c2009-05-03 05:20:50 +0000856 return AE;
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000857}
858
Ted Kremenek93edbc52011-10-05 23:54:29 +0000859const RetainSummary *
Jordy Roseef945882012-03-18 01:26:10 +0000860RetainSummaryManager::getPersistentSummary(const RetainSummary &OldSumm) {
861 // Unique "simple" summaries -- those without ArgEffects.
862 if (OldSumm.isSimple()) {
863 llvm::FoldingSetNodeID ID;
864 OldSumm.Profile(ID);
865
866 void *Pos;
867 CachedSummaryNode *N = SimpleSummaries.FindNodeOrInsertPos(ID, Pos);
868
869 if (!N) {
870 N = (CachedSummaryNode *) BPAlloc.Allocate<CachedSummaryNode>();
871 new (N) CachedSummaryNode(OldSumm);
872 SimpleSummaries.InsertNode(N, Pos);
873 }
874
875 return &N->getValue();
876 }
877
Ted Kremenek93edbc52011-10-05 23:54:29 +0000878 RetainSummary *Summ = (RetainSummary *) BPAlloc.Allocate<RetainSummary>();
Jordy Roseef945882012-03-18 01:26:10 +0000879 new (Summ) RetainSummary(OldSumm);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000880 return Summ;
881}
882
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000883//===----------------------------------------------------------------------===//
884// Summary creation for functions (largely uses of Core Foundation).
885//===----------------------------------------------------------------------===//
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000886
Ted Kremenek9c378f72011-08-12 23:37:29 +0000887static bool isRetain(const FunctionDecl *FD, StringRef FName) {
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000888 return FName.endswith("Retain");
Ted Kremenek12619382009-01-12 21:45:02 +0000889}
890
Ted Kremenek9c378f72011-08-12 23:37:29 +0000891static bool isRelease(const FunctionDecl *FD, StringRef FName) {
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000892 return FName.endswith("Release");
Ted Kremenek12619382009-01-12 21:45:02 +0000893}
894
Jordy Rose76c506f2011-08-21 21:58:18 +0000895static bool isMakeCollectable(const FunctionDecl *FD, StringRef FName) {
896 // FIXME: Remove FunctionDecl parameter.
897 // FIXME: Is it really okay if MakeCollectable isn't a suffix?
898 return FName.find("MakeCollectable") != StringRef::npos;
899}
900
Anna Zaks554067f2012-08-29 23:23:43 +0000901static ArgEffect getStopTrackingHardEquivalent(ArgEffect E) {
Jordan Rose4531b7d2012-07-02 19:27:43 +0000902 switch (E) {
903 case DoNothing:
904 case Autorelease:
905 case DecRefBridgedTransfered:
906 case IncRef:
907 case IncRefMsg:
908 case MakeCollectable:
909 case MayEscape:
910 case NewAutoreleasePool:
911 case StopTracking:
Anna Zaks554067f2012-08-29 23:23:43 +0000912 case StopTrackingHard:
913 return StopTrackingHard;
Jordan Rose4531b7d2012-07-02 19:27:43 +0000914 case DecRef:
Anna Zaks554067f2012-08-29 23:23:43 +0000915 case DecRefAndStopTrackingHard:
916 return DecRefAndStopTrackingHard;
Jordan Rose4531b7d2012-07-02 19:27:43 +0000917 case DecRefMsg:
Anna Zaks554067f2012-08-29 23:23:43 +0000918 case DecRefMsgAndStopTrackingHard:
919 return DecRefMsgAndStopTrackingHard;
Jordan Rose4531b7d2012-07-02 19:27:43 +0000920 case Dealloc:
921 return Dealloc;
922 }
923
924 llvm_unreachable("Unknown ArgEffect kind");
925}
926
927void RetainSummaryManager::updateSummaryForCall(const RetainSummary *&S,
928 const CallEvent &Call) {
929 if (Call.hasNonZeroCallbackArg()) {
Anna Zaks554067f2012-08-29 23:23:43 +0000930 ArgEffect RecEffect =
931 getStopTrackingHardEquivalent(S->getReceiverEffect());
932 ArgEffect DefEffect =
933 getStopTrackingHardEquivalent(S->getDefaultArgEffect());
Jordan Rose4531b7d2012-07-02 19:27:43 +0000934
935 ArgEffects CustomArgEffects = S->getArgEffects();
936 for (ArgEffects::iterator I = CustomArgEffects.begin(),
937 E = CustomArgEffects.end();
938 I != E; ++I) {
Anna Zaks554067f2012-08-29 23:23:43 +0000939 ArgEffect Translated = getStopTrackingHardEquivalent(I->second);
Jordan Rose4531b7d2012-07-02 19:27:43 +0000940 if (Translated != DefEffect)
941 ScratchArgs = AF.add(ScratchArgs, I->first, Translated);
942 }
943
Anna Zaks554067f2012-08-29 23:23:43 +0000944 RetEffect RE = RetEffect::MakeNoRetHard();
Jordan Rose4531b7d2012-07-02 19:27:43 +0000945
946 // Special cases where the callback argument CANNOT free the return value.
947 // This can generally only happen if we know that the callback will only be
948 // called when the return value is already being deallocated.
949 if (const FunctionCall *FC = dyn_cast<FunctionCall>(&Call)) {
Jordan Rose4a25f302012-09-01 17:39:13 +0000950 if (IdentifierInfo *Name = FC->getDecl()->getIdentifier()) {
951 // When the CGBitmapContext is deallocated, the callback here will free
952 // the associated data buffer.
Jordan Rosea89f7192012-08-31 18:19:18 +0000953 if (Name->isStr("CGBitmapContextCreateWithData"))
954 RE = S->getRetEffect();
Jordan Rose4a25f302012-09-01 17:39:13 +0000955 }
Jordan Rose4531b7d2012-07-02 19:27:43 +0000956 }
957
958 S = getPersistentSummary(RE, RecEffect, DefEffect);
959 }
Anna Zaks5a901932012-08-24 00:06:12 +0000960
961 // Special case '[super init];' and '[self init];'
962 //
963 // Even though calling '[super init]' without assigning the result to self
964 // and checking if the parent returns 'nil' is a bad pattern, it is common.
965 // Additionally, our Self Init checker already warns about it. To avoid
966 // overwhelming the user with messages from both checkers, we model the case
967 // of '[super init]' in cases when it is not consumed by another expression
968 // as if the call preserves the value of 'self'; essentially, assuming it can
969 // never fail and return 'nil'.
970 // Note, we don't want to just stop tracking the value since we want the
971 // RetainCount checker to report leaks and use-after-free if SelfInit checker
972 // is turned off.
973 if (const ObjCMethodCall *MC = dyn_cast<ObjCMethodCall>(&Call)) {
974 if (MC->getMethodFamily() == OMF_init && MC->isReceiverSelfOrSuper()) {
975
976 // Check if the message is not consumed, we know it will not be used in
977 // an assignment, ex: "self = [super init]".
978 const Expr *ME = MC->getOriginExpr();
979 const LocationContext *LCtx = MC->getLocationContext();
980 ParentMap &PM = LCtx->getAnalysisDeclContext()->getParentMap();
981 if (!PM.isConsumedExpr(ME)) {
982 RetainSummaryTemplate ModifiableSummaryTemplate(S, *this);
983 ModifiableSummaryTemplate->setReceiverEffect(DoNothing);
984 ModifiableSummaryTemplate->setRetEffect(RetEffect::MakeNoRet());
985 }
986 }
987
988 }
Jordan Rose4531b7d2012-07-02 19:27:43 +0000989}
990
Anna Zaks58822c42012-05-04 22:18:39 +0000991const RetainSummary *
Jordan Rose4531b7d2012-07-02 19:27:43 +0000992RetainSummaryManager::getSummary(const CallEvent &Call,
993 ProgramStateRef State) {
994 const RetainSummary *Summ;
995 switch (Call.getKind()) {
996 case CE_Function:
997 Summ = getFunctionSummary(cast<FunctionCall>(Call).getDecl());
998 break;
999 case CE_CXXMember:
Jordan Rosefdaa3382012-07-03 22:55:57 +00001000 case CE_CXXMemberOperator:
Jordan Rose4531b7d2012-07-02 19:27:43 +00001001 case CE_Block:
1002 case CE_CXXConstructor:
Jordan Rose8d276d32012-07-10 22:07:47 +00001003 case CE_CXXDestructor:
Jordan Rose70cbf3c2012-07-02 22:21:47 +00001004 case CE_CXXAllocator:
Jordan Rose4531b7d2012-07-02 19:27:43 +00001005 // FIXME: These calls are currently unsupported.
1006 return getPersistentStopSummary();
Jordan Rose8919e682012-07-18 21:59:51 +00001007 case CE_ObjCMessage: {
Jordan Rosecde8cdb2012-07-02 19:27:56 +00001008 const ObjCMethodCall &Msg = cast<ObjCMethodCall>(Call);
Jordan Rose4531b7d2012-07-02 19:27:43 +00001009 if (Msg.isInstanceMessage())
1010 Summ = getInstanceMethodSummary(Msg, State);
1011 else
1012 Summ = getClassMethodSummary(Msg);
1013 break;
1014 }
1015 }
1016
1017 updateSummaryForCall(Summ, Call);
1018
1019 assert(Summ && "Unknown call type?");
1020 return Summ;
1021}
1022
1023const RetainSummary *
1024RetainSummaryManager::getFunctionSummary(const FunctionDecl *FD) {
1025 // If we don't know what function we're calling, use our default summary.
1026 if (!FD)
1027 return getDefaultSummary();
1028
Ted Kremenek891d5cc2008-04-24 17:22:33 +00001029 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001030 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001031 if (I != FuncSummaries.end())
Ted Kremenek891d5cc2008-04-24 17:22:33 +00001032 return I->second;
1033
Ted Kremeneke401a0c2009-05-04 15:34:07 +00001034 // No summary? Generate one.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001035 const RetainSummary *S = 0;
Jordan Rose15d18e12012-08-06 21:28:02 +00001036 bool AllowAnnotations = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001037
Ted Kremenek37d785b2008-07-15 16:50:12 +00001038 do {
Ted Kremenek12619382009-01-12 21:45:02 +00001039 // We generate "stop" summaries for implicitly defined functions.
1040 if (FD->isImplicit()) {
1041 S = getPersistentStopSummary();
1042 break;
Ted Kremenek37d785b2008-07-15 16:50:12 +00001043 }
Mike Stump1eb44332009-09-09 15:08:12 +00001044
John McCall183700f2009-09-21 23:43:11 +00001045 // [PR 3337] Use 'getAs<FunctionType>' to strip away any typedefs on the
Ted Kremenek99890652009-01-16 18:40:33 +00001046 // function's type.
John McCall183700f2009-09-21 23:43:11 +00001047 const FunctionType* FT = FD->getType()->getAs<FunctionType>();
Ted Kremenek48c6d182009-12-16 06:06:43 +00001048 const IdentifierInfo *II = FD->getIdentifier();
1049 if (!II)
1050 break;
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001051
1052 StringRef FName = II->getName();
Mike Stump1eb44332009-09-09 15:08:12 +00001053
Ted Kremenekbf0a4dd2009-03-05 22:11:14 +00001054 // Strip away preceding '_'. Doing this here will effect all the checks
1055 // down below.
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001056 FName = FName.substr(FName.find_first_not_of('_'));
Mike Stump1eb44332009-09-09 15:08:12 +00001057
Ted Kremenek12619382009-01-12 21:45:02 +00001058 // Inspect the result type.
1059 QualType RetTy = FT->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00001060
Ted Kremenek12619382009-01-12 21:45:02 +00001061 // FIXME: This should all be refactored into a chain of "summary lookup"
1062 // filters.
Ted Kremenek008636a2009-10-14 00:27:24 +00001063 assert(ScratchArgs.isEmpty());
Ted Kremenek39d88b02009-06-15 20:36:07 +00001064
Ted Kremenekbefc6d22012-04-26 04:32:23 +00001065 if (FName == "pthread_create" || FName == "pthread_setspecific") {
1066 // Part of: <rdar://problem/7299394> and <rdar://problem/11282706>.
1067 // This will be addressed better with IPA.
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001068 S = getPersistentStopSummary();
1069 } else if (FName == "NSMakeCollectable") {
1070 // Handle: id NSMakeCollectable(CFTypeRef)
1071 S = (RetTy->isObjCIdType())
1072 ? getUnarySummary(FT, cfmakecollectable)
1073 : getPersistentStopSummary();
Jordan Rose15d18e12012-08-06 21:28:02 +00001074 // The headers on OS X 10.8 use cf_consumed/ns_returns_retained,
1075 // but we can fully model NSMakeCollectable ourselves.
1076 AllowAnnotations = false;
Ted Kremenek061707a2012-09-06 23:47:02 +00001077 } else if (FName == "CFPlugInInstanceCreate") {
1078 S = getPersistentSummary(RetEffect::MakeNoRet());
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001079 } else if (FName == "IOBSDNameMatching" ||
1080 FName == "IOServiceMatching" ||
1081 FName == "IOServiceNameMatching" ||
Ted Kremenek537dd3a2012-05-01 05:28:27 +00001082 FName == "IORegistryEntrySearchCFProperty" ||
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001083 FName == "IORegistryEntryIDMatching" ||
1084 FName == "IOOpenFirmwarePathMatching") {
1085 // Part of <rdar://problem/6961230>. (IOKit)
1086 // This should be addressed using a API table.
1087 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1088 DoNothing, DoNothing);
1089 } else if (FName == "IOServiceGetMatchingService" ||
1090 FName == "IOServiceGetMatchingServices") {
1091 // FIXES: <rdar://problem/6326900>
1092 // This should be addressed using a API table. This strcmp is also
1093 // a little gross, but there is no need to super optimize here.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001094 ScratchArgs = AF.add(ScratchArgs, 1, DecRef);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001095 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1096 } else if (FName == "IOServiceAddNotification" ||
1097 FName == "IOServiceAddMatchingNotification") {
1098 // Part of <rdar://problem/6961230>. (IOKit)
1099 // This should be addressed using a API table.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001100 ScratchArgs = AF.add(ScratchArgs, 2, DecRef);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001101 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1102 } else if (FName == "CVPixelBufferCreateWithBytes") {
1103 // FIXES: <rdar://problem/7283567>
1104 // Eventually this can be improved by recognizing that the pixel
1105 // buffer passed to CVPixelBufferCreateWithBytes is released via
1106 // a callback and doing full IPA to make sure this is done correctly.
1107 // FIXME: This function has an out parameter that returns an
1108 // allocated object.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001109 ScratchArgs = AF.add(ScratchArgs, 7, StopTracking);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001110 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1111 } else if (FName == "CGBitmapContextCreateWithData") {
1112 // FIXES: <rdar://problem/7358899>
1113 // Eventually this can be improved by recognizing that 'releaseInfo'
1114 // passed to CGBitmapContextCreateWithData is released via
1115 // a callback and doing full IPA to make sure this is done correctly.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001116 ScratchArgs = AF.add(ScratchArgs, 8, StopTracking);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001117 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1118 DoNothing, DoNothing);
1119 } else if (FName == "CVPixelBufferCreateWithPlanarBytes") {
1120 // FIXES: <rdar://problem/7283567>
1121 // Eventually this can be improved by recognizing that the pixel
1122 // buffer passed to CVPixelBufferCreateWithPlanarBytes is released
1123 // via a callback and doing full IPA to make sure this is done
1124 // correctly.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001125 ScratchArgs = AF.add(ScratchArgs, 12, StopTracking);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001126 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenek06911d42012-03-22 06:29:41 +00001127 } else if (FName == "dispatch_set_context") {
1128 // <rdar://problem/11059275> - The analyzer currently doesn't have
1129 // a good way to reason about the finalizer function for libdispatch.
1130 // If we pass a context object that is memory managed, stop tracking it.
1131 // FIXME: this hack should possibly go away once we can handle
1132 // libdispatch finalizers.
1133 ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
1134 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenekc91fdf62012-05-08 00:12:09 +00001135 } else if (FName.startswith("NSLog")) {
1136 S = getDoNothingSummary();
Anna Zaks62a5c342012-03-30 05:48:16 +00001137 } else if (FName.startswith("NS") &&
1138 (FName.find("Insert") != StringRef::npos)) {
1139 // Whitelist NSXXInsertXX, for example NSMapInsertIfAbsent, since they can
1140 // be deallocated by NSMapRemove. (radar://11152419)
1141 ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
1142 ScratchArgs = AF.add(ScratchArgs, 2, StopTracking);
1143 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenekb04cb592009-06-11 18:17:24 +00001144 }
Mike Stump1eb44332009-09-09 15:08:12 +00001145
Ted Kremenekb04cb592009-06-11 18:17:24 +00001146 // Did we get a summary?
1147 if (S)
1148 break;
Ted Kremenek61991902009-03-17 22:43:44 +00001149
Ted Kremenek12619382009-01-12 21:45:02 +00001150 if (RetTy->isPointerType()) {
Ted Kremeneke7883652012-08-30 19:27:02 +00001151 if (FD->getAttr<CFAuditedTransferAttr>()) {
1152 S = getCFCreateGetRuleSummary(FD);
1153 break;
1154 }
1155
Ted Kremenek12619382009-01-12 21:45:02 +00001156 // For CoreFoundation ('CF') types.
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001157 if (cocoa::isRefType(RetTy, "CF", FName)) {
Ted Kremenek12619382009-01-12 21:45:02 +00001158 if (isRetain(FD, FName))
1159 S = getUnarySummary(FT, cfretain);
Jordy Rose76c506f2011-08-21 21:58:18 +00001160 else if (isMakeCollectable(FD, FName))
Ted Kremenek12619382009-01-12 21:45:02 +00001161 S = getUnarySummary(FT, cfmakecollectable);
Mike Stump1eb44332009-09-09 15:08:12 +00001162 else
John McCall7df2ff42011-10-01 00:48:56 +00001163 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek12619382009-01-12 21:45:02 +00001164
1165 break;
1166 }
1167
1168 // For CoreGraphics ('CG') types.
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001169 if (cocoa::isRefType(RetTy, "CG", FName)) {
Ted Kremenek12619382009-01-12 21:45:02 +00001170 if (isRetain(FD, FName))
1171 S = getUnarySummary(FT, cfretain);
1172 else
John McCall7df2ff42011-10-01 00:48:56 +00001173 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek12619382009-01-12 21:45:02 +00001174
1175 break;
1176 }
1177
1178 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001179 if (cocoa::isRefType(RetTy, "DADisk") ||
1180 cocoa::isRefType(RetTy, "DADissenter") ||
1181 cocoa::isRefType(RetTy, "DASessionRef")) {
John McCall7df2ff42011-10-01 00:48:56 +00001182 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek12619382009-01-12 21:45:02 +00001183 break;
1184 }
Mike Stump1eb44332009-09-09 15:08:12 +00001185
Ted Kremenek12619382009-01-12 21:45:02 +00001186 break;
1187 }
1188
1189 // Check for release functions, the only kind of functions that we care
1190 // about that don't return a pointer type.
1191 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
Ted Kremeneke7d03122010-02-08 16:45:01 +00001192 // Test for 'CGCF'.
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001193 FName = FName.substr(FName.startswith("CGCF") ? 4 : 2);
Ted Kremeneke7d03122010-02-08 16:45:01 +00001194
Ted Kremenekbf0a4dd2009-03-05 22:11:14 +00001195 if (isRelease(FD, FName))
Ted Kremenek12619382009-01-12 21:45:02 +00001196 S = getUnarySummary(FT, cfrelease);
1197 else {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001198 assert (ScratchArgs.isEmpty());
Ted Kremenek68189282009-01-29 22:45:13 +00001199 // Remaining CoreFoundation and CoreGraphics functions.
1200 // We use to assume that they all strictly followed the ownership idiom
1201 // and that ownership cannot be transferred. While this is technically
1202 // correct, many methods allow a tracked object to escape. For example:
1203 //
Mike Stump1eb44332009-09-09 15:08:12 +00001204 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
Ted Kremenek68189282009-01-29 22:45:13 +00001205 // CFDictionaryAddValue(y, key, x);
Mike Stump1eb44332009-09-09 15:08:12 +00001206 // CFRelease(x);
Ted Kremenek68189282009-01-29 22:45:13 +00001207 // ... it is okay to use 'x' since 'y' has a reference to it
1208 //
1209 // We handle this and similar cases with the follow heuristic. If the
Ted Kremenekc4843812009-08-20 00:57:22 +00001210 // function name contains "InsertValue", "SetValue", "AddValue",
1211 // "AppendValue", or "SetAttribute", then we assume that arguments may
1212 // "escape." This means that something else holds on to the object,
1213 // allowing it be used even after its local retain count drops to 0.
Benjamin Kramere45c1492010-01-11 19:46:28 +00001214 ArgEffect E = (StrInStrNoCase(FName, "InsertValue") != StringRef::npos||
1215 StrInStrNoCase(FName, "AddValue") != StringRef::npos ||
1216 StrInStrNoCase(FName, "SetValue") != StringRef::npos ||
1217 StrInStrNoCase(FName, "AppendValue") != StringRef::npos||
Benjamin Kramerc027e542010-01-11 20:15:06 +00001218 StrInStrNoCase(FName, "SetAttribute") != StringRef::npos)
Ted Kremenek68189282009-01-29 22:45:13 +00001219 ? MayEscape : DoNothing;
Mike Stump1eb44332009-09-09 15:08:12 +00001220
Ted Kremenek68189282009-01-29 22:45:13 +00001221 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek12619382009-01-12 21:45:02 +00001222 }
1223 }
Ted Kremenek37d785b2008-07-15 16:50:12 +00001224 }
1225 while (0);
Mike Stump1eb44332009-09-09 15:08:12 +00001226
Jordan Rose4531b7d2012-07-02 19:27:43 +00001227 // If we got all the way here without any luck, use a default summary.
1228 if (!S)
1229 S = getDefaultSummary();
1230
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001231 // Annotations override defaults.
Jordan Rose15d18e12012-08-06 21:28:02 +00001232 if (AllowAnnotations)
1233 updateSummaryFromAnnotations(S, FD);
Mike Stump1eb44332009-09-09 15:08:12 +00001234
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001235 FuncSummaries[FD] = S;
Mike Stump1eb44332009-09-09 15:08:12 +00001236 return S;
Ted Kremenek2fff37e2008-03-06 00:08:09 +00001237}
1238
Ted Kremenek93edbc52011-10-05 23:54:29 +00001239const RetainSummary *
John McCall7df2ff42011-10-01 00:48:56 +00001240RetainSummaryManager::getCFCreateGetRuleSummary(const FunctionDecl *FD) {
1241 if (coreFoundation::followsCreateRule(FD))
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001242 return getCFSummaryCreateRule(FD);
Mike Stump1eb44332009-09-09 15:08:12 +00001243
Ted Kremenekd368d712011-05-25 06:19:45 +00001244 return getCFSummaryGetRule(FD);
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001245}
1246
Ted Kremenek93edbc52011-10-05 23:54:29 +00001247const RetainSummary *
Ted Kremenek6ad315a2009-02-23 16:51:39 +00001248RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1249 UnaryFuncKind func) {
1250
Ted Kremenek12619382009-01-12 21:45:02 +00001251 // Sanity check that this is *really* a unary function. This can
1252 // happen if people do weird things.
Douglas Gregor72564e72009-02-26 23:50:07 +00001253 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
Ted Kremenek12619382009-01-12 21:45:02 +00001254 if (!FTP || FTP->getNumArgs() != 1)
1255 return getPersistentStopSummary();
Mike Stump1eb44332009-09-09 15:08:12 +00001256
Ted Kremenekb77449c2009-05-03 05:20:50 +00001257 assert (ScratchArgs.isEmpty());
Mike Stump1eb44332009-09-09 15:08:12 +00001258
Jordy Rose76c506f2011-08-21 21:58:18 +00001259 ArgEffect Effect;
Ted Kremenek377e2302008-04-29 05:33:51 +00001260 switch (func) {
Jordy Rose76c506f2011-08-21 21:58:18 +00001261 case cfretain: Effect = IncRef; break;
1262 case cfrelease: Effect = DecRef; break;
1263 case cfmakecollectable: Effect = MakeCollectable; break;
Ted Kremenek940b1d82008-04-10 23:44:06 +00001264 }
Jordy Rose76c506f2011-08-21 21:58:18 +00001265
1266 ScratchArgs = AF.add(ScratchArgs, 0, Effect);
1267 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001268}
1269
Ted Kremenek93edbc52011-10-05 23:54:29 +00001270const RetainSummary *
Ted Kremenek9c378f72011-08-12 23:37:29 +00001271RetainSummaryManager::getCFSummaryCreateRule(const FunctionDecl *FD) {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001272 assert (ScratchArgs.isEmpty());
Mike Stump1eb44332009-09-09 15:08:12 +00001273
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001274 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001275}
1276
Ted Kremenek93edbc52011-10-05 23:54:29 +00001277const RetainSummary *
Ted Kremenek9c378f72011-08-12 23:37:29 +00001278RetainSummaryManager::getCFSummaryGetRule(const FunctionDecl *FD) {
Mike Stump1eb44332009-09-09 15:08:12 +00001279 assert (ScratchArgs.isEmpty());
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001280 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1281 DoNothing, DoNothing);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001282}
1283
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001284//===----------------------------------------------------------------------===//
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001285// Summary creation for Selectors.
1286//===----------------------------------------------------------------------===//
1287
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001288void
Ted Kremenek93edbc52011-10-05 23:54:29 +00001289RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001290 const FunctionDecl *FD) {
1291 if (!FD)
1292 return;
1293
Jordan Rose4531b7d2012-07-02 19:27:43 +00001294 assert(Summ && "Must have a summary to add annotations to.");
1295 RetainSummaryTemplate Template(Summ, *this);
Jordy Rose4df54fe2011-08-23 04:27:15 +00001296
Ted Kremenek11fe1752011-01-27 18:43:03 +00001297 // Effects on the parameters.
1298 unsigned parm_idx = 0;
1299 for (FunctionDecl::param_const_iterator pi = FD->param_begin(),
John McCall98b8f162011-04-06 09:02:12 +00001300 pe = FD->param_end(); pi != pe; ++pi, ++parm_idx) {
Ted Kremenek11fe1752011-01-27 18:43:03 +00001301 const ParmVarDecl *pd = *pi;
1302 if (pd->getAttr<NSConsumedAttr>()) {
Jordy Rose4df54fe2011-08-23 04:27:15 +00001303 if (!GCEnabled) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001304 Template->addArg(AF, parm_idx, DecRef);
Jordy Rose4df54fe2011-08-23 04:27:15 +00001305 }
1306 } else if (pd->getAttr<CFConsumedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001307 Template->addArg(AF, parm_idx, DecRef);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001308 }
1309 }
1310
Ted Kremenekb04cb592009-06-11 18:17:24 +00001311 QualType RetTy = FD->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00001312
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001313 // Determine if there is a special return effect for this method.
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001314 if (cocoa::isCocoaObjectRef(RetTy)) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001315 if (FD->getAttr<NSReturnsRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001316 Template->setRetEffect(ObjCAllocRetE);
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001317 }
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001318 else if (FD->getAttr<CFReturnsRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001319 Template->setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenekb04cb592009-06-11 18:17:24 +00001320 }
Ted Kremenek60411112010-02-18 00:06:12 +00001321 else if (FD->getAttr<NSReturnsNotRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001322 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::ObjC));
Ted Kremenek60411112010-02-18 00:06:12 +00001323 }
1324 else if (FD->getAttr<CFReturnsNotRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001325 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::CF));
Jordy Rose4df54fe2011-08-23 04:27:15 +00001326 }
1327 } else if (RetTy->getAs<PointerType>()) {
1328 if (FD->getAttr<CFReturnsRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001329 Template->setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
Jordy Rose4df54fe2011-08-23 04:27:15 +00001330 }
1331 else if (FD->getAttr<CFReturnsNotRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001332 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::CF));
Ted Kremenek60411112010-02-18 00:06:12 +00001333 }
Ted Kremenekb04cb592009-06-11 18:17:24 +00001334 }
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001335}
1336
1337void
Ted Kremenek93edbc52011-10-05 23:54:29 +00001338RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
1339 const ObjCMethodDecl *MD) {
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001340 if (!MD)
1341 return;
1342
Jordan Rose4531b7d2012-07-02 19:27:43 +00001343 assert(Summ && "Must have a valid summary to add annotations to");
1344 RetainSummaryTemplate Template(Summ, *this);
Ted Kremenek6d4b76d2009-07-06 18:30:43 +00001345 bool isTrackedLoc = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001346
Ted Kremenek12b94342011-01-27 06:54:14 +00001347 // Effects on the receiver.
1348 if (MD->getAttr<NSConsumesSelfAttr>()) {
Ted Kremenek11fe1752011-01-27 18:43:03 +00001349 if (!GCEnabled)
Jordy Rose0fe62f82011-08-24 09:02:37 +00001350 Template->setReceiverEffect(DecRefMsg);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001351 }
1352
1353 // Effects on the parameters.
1354 unsigned parm_idx = 0;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00001355 for (ObjCMethodDecl::param_const_iterator
1356 pi=MD->param_begin(), pe=MD->param_end();
Ted Kremenek11fe1752011-01-27 18:43:03 +00001357 pi != pe; ++pi, ++parm_idx) {
1358 const ParmVarDecl *pd = *pi;
1359 if (pd->getAttr<NSConsumedAttr>()) {
1360 if (!GCEnabled)
Jordy Rose0fe62f82011-08-24 09:02:37 +00001361 Template->addArg(AF, parm_idx, DecRef);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001362 }
1363 else if(pd->getAttr<CFConsumedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001364 Template->addArg(AF, parm_idx, DecRef);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001365 }
Ted Kremenek12b94342011-01-27 06:54:14 +00001366 }
1367
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001368 // Determine if there is a special return effect for this method.
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001369 if (cocoa::isCocoaObjectRef(MD->getResultType())) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001370 if (MD->getAttr<NSReturnsRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001371 Template->setRetEffect(ObjCAllocRetE);
Ted Kremenek6d4b76d2009-07-06 18:30:43 +00001372 return;
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001373 }
Ted Kremenek60411112010-02-18 00:06:12 +00001374 if (MD->getAttr<NSReturnsNotRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001375 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::ObjC));
Ted Kremenek60411112010-02-18 00:06:12 +00001376 return;
1377 }
Mike Stump1eb44332009-09-09 15:08:12 +00001378
Ted Kremenek6d4b76d2009-07-06 18:30:43 +00001379 isTrackedLoc = true;
Jordy Rose0fe62f82011-08-24 09:02:37 +00001380 } else {
Ted Kremenek6217b802009-07-29 21:53:49 +00001381 isTrackedLoc = MD->getResultType()->getAs<PointerType>() != NULL;
Jordy Rose0fe62f82011-08-24 09:02:37 +00001382 }
Mike Stump1eb44332009-09-09 15:08:12 +00001383
Ted Kremenek60411112010-02-18 00:06:12 +00001384 if (isTrackedLoc) {
1385 if (MD->getAttr<CFReturnsRetainedAttr>())
Jordy Rose0fe62f82011-08-24 09:02:37 +00001386 Template->setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenek60411112010-02-18 00:06:12 +00001387 else if (MD->getAttr<CFReturnsNotRetainedAttr>())
Jordy Rose0fe62f82011-08-24 09:02:37 +00001388 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::CF));
Ted Kremenek60411112010-02-18 00:06:12 +00001389 }
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001390}
1391
Ted Kremenek93edbc52011-10-05 23:54:29 +00001392const RetainSummary *
Jordy Rosef3aae582012-03-17 21:13:07 +00001393RetainSummaryManager::getStandardMethodSummary(const ObjCMethodDecl *MD,
1394 Selector S, QualType RetTy) {
Jordy Rosee921b1a2012-03-17 19:53:04 +00001395 // Any special effects?
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001396 ArgEffect ReceiverEff = DoNothing;
Jordy Rosee921b1a2012-03-17 19:53:04 +00001397 RetEffect ResultEff = RetEffect::MakeNoRet();
1398
1399 // Check the method family, and apply any default annotations.
1400 switch (MD ? MD->getMethodFamily() : S.getMethodFamily()) {
1401 case OMF_None:
1402 case OMF_performSelector:
1403 // Assume all Objective-C methods follow Cocoa Memory Management rules.
1404 // FIXME: Does the non-threaded performSelector family really belong here?
1405 // The selector could be, say, @selector(copy).
1406 if (cocoa::isCocoaObjectRef(RetTy))
1407 ResultEff = RetEffect::MakeNotOwned(RetEffect::ObjC);
1408 else if (coreFoundation::isCFObjectRef(RetTy)) {
1409 // ObjCMethodDecl currently doesn't consider CF objects as valid return
1410 // values for alloc, new, copy, or mutableCopy, so we have to
1411 // double-check with the selector. This is ugly, but there aren't that
1412 // many Objective-C methods that return CF objects, right?
1413 if (MD) {
1414 switch (S.getMethodFamily()) {
1415 case OMF_alloc:
1416 case OMF_new:
1417 case OMF_copy:
1418 case OMF_mutableCopy:
1419 ResultEff = RetEffect::MakeOwned(RetEffect::CF, true);
1420 break;
1421 default:
1422 ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1423 break;
1424 }
1425 } else {
1426 ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1427 }
1428 }
1429 break;
1430 case OMF_init:
1431 ResultEff = ObjCInitRetE;
1432 ReceiverEff = DecRefMsg;
1433 break;
1434 case OMF_alloc:
1435 case OMF_new:
1436 case OMF_copy:
1437 case OMF_mutableCopy:
1438 if (cocoa::isCocoaObjectRef(RetTy))
1439 ResultEff = ObjCAllocRetE;
1440 else if (coreFoundation::isCFObjectRef(RetTy))
1441 ResultEff = RetEffect::MakeOwned(RetEffect::CF, true);
1442 break;
1443 case OMF_autorelease:
1444 ReceiverEff = Autorelease;
1445 break;
1446 case OMF_retain:
1447 ReceiverEff = IncRefMsg;
1448 break;
1449 case OMF_release:
1450 ReceiverEff = DecRefMsg;
1451 break;
1452 case OMF_dealloc:
1453 ReceiverEff = Dealloc;
1454 break;
1455 case OMF_self:
1456 // -self is handled specially by the ExprEngine to propagate the receiver.
1457 break;
1458 case OMF_retainCount:
1459 case OMF_finalize:
1460 // These methods don't return objects.
1461 break;
1462 }
Mike Stump1eb44332009-09-09 15:08:12 +00001463
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001464 // If one of the arguments in the selector has the keyword 'delegate' we
1465 // should stop tracking the reference count for the receiver. This is
1466 // because the reference count is quite possibly handled by a delegate
1467 // method.
1468 if (S.isKeywordSelector()) {
Jordan Rose50571a92012-06-15 18:19:52 +00001469 for (unsigned i = 0, e = S.getNumArgs(); i != e; ++i) {
1470 StringRef Slot = S.getNameForSlot(i);
1471 if (Slot.substr(Slot.size() - 8).equals_lower("delegate")) {
1472 if (ResultEff == ObjCInitRetE)
Anna Zaks554067f2012-08-29 23:23:43 +00001473 ResultEff = RetEffect::MakeNoRetHard();
Jordan Rose50571a92012-06-15 18:19:52 +00001474 else
Anna Zaks554067f2012-08-29 23:23:43 +00001475 ReceiverEff = StopTrackingHard;
Jordan Rose50571a92012-06-15 18:19:52 +00001476 }
1477 }
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001478 }
Mike Stump1eb44332009-09-09 15:08:12 +00001479
Jordy Rosee921b1a2012-03-17 19:53:04 +00001480 if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing &&
1481 ResultEff.getKind() == RetEffect::NoRet)
Ted Kremenek93edbc52011-10-05 23:54:29 +00001482 return getDefaultSummary();
Mike Stump1eb44332009-09-09 15:08:12 +00001483
Jordy Rosee921b1a2012-03-17 19:53:04 +00001484 return getPersistentSummary(ResultEff, ReceiverEff, MayEscape);
Ted Kremenek250b1fa2009-04-23 23:08:22 +00001485}
1486
Ted Kremenek93edbc52011-10-05 23:54:29 +00001487const RetainSummary *
Jordan Rosecde8cdb2012-07-02 19:27:56 +00001488RetainSummaryManager::getInstanceMethodSummary(const ObjCMethodCall &Msg,
Jordan Rose4531b7d2012-07-02 19:27:43 +00001489 ProgramStateRef State) {
1490 const ObjCInterfaceDecl *ReceiverClass = 0;
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001491
Jordan Rose4531b7d2012-07-02 19:27:43 +00001492 // We do better tracking of the type of the object than the core ExprEngine.
1493 // See if we have its type in our private state.
1494 // FIXME: Eventually replace the use of state->get<RefBindings> with
1495 // a generic API for reasoning about the Objective-C types of symbolic
1496 // objects.
1497 SVal ReceiverV = Msg.getReceiverSVal();
1498 if (SymbolRef Sym = ReceiverV.getAsLocSymbol())
Anna Zaks8d6b43c2012-08-14 00:36:15 +00001499 if (const RefVal *T = getRefBinding(State, Sym))
Douglas Gregor04badcf2010-04-21 00:45:42 +00001500 if (const ObjCObjectPointerType *PT =
Jordan Rose4531b7d2012-07-02 19:27:43 +00001501 T->getType()->getAs<ObjCObjectPointerType>())
1502 ReceiverClass = PT->getInterfaceDecl();
1503
1504 // If we don't know what kind of object this is, fall back to its static type.
1505 if (!ReceiverClass)
1506 ReceiverClass = Msg.getReceiverInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00001507
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001508 // FIXME: The receiver could be a reference to a class, meaning that
1509 // we should use the class method.
Jordan Rose4531b7d2012-07-02 19:27:43 +00001510 // id x = [NSObject class];
1511 // [x performSelector:... withObject:... afterDelay:...];
1512 Selector S = Msg.getSelector();
1513 const ObjCMethodDecl *Method = Msg.getDecl();
1514 if (!Method && ReceiverClass)
1515 Method = ReceiverClass->getInstanceMethod(S);
1516
1517 return getMethodSummary(S, ReceiverClass, Method, Msg.getResultType(),
1518 ObjCMethodSummaries);
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001519}
1520
Ted Kremenek93edbc52011-10-05 23:54:29 +00001521const RetainSummary *
Jordan Rose4531b7d2012-07-02 19:27:43 +00001522RetainSummaryManager::getMethodSummary(Selector S, const ObjCInterfaceDecl *ID,
Jordy Rosef3aae582012-03-17 21:13:07 +00001523 const ObjCMethodDecl *MD, QualType RetTy,
1524 ObjCMethodSummariesTy &CachedSummaries) {
Ted Kremenek1bffd742008-05-06 15:44:25 +00001525
Ted Kremenek8711c032009-04-29 05:04:30 +00001526 // Look up a summary in our summary cache.
Jordan Rose4531b7d2012-07-02 19:27:43 +00001527 const RetainSummary *Summ = CachedSummaries.find(ID, S);
Mike Stump1eb44332009-09-09 15:08:12 +00001528
Ted Kremenek614cc542009-07-21 23:27:57 +00001529 if (!Summ) {
Jordy Rosef3aae582012-03-17 21:13:07 +00001530 Summ = getStandardMethodSummary(MD, S, RetTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001531
Ted Kremenek614cc542009-07-21 23:27:57 +00001532 // Annotations override defaults.
Jordy Rose4df54fe2011-08-23 04:27:15 +00001533 updateSummaryFromAnnotations(Summ, MD);
Mike Stump1eb44332009-09-09 15:08:12 +00001534
Ted Kremenek614cc542009-07-21 23:27:57 +00001535 // Memoize the summary.
Jordan Rose4531b7d2012-07-02 19:27:43 +00001536 CachedSummaries[ObjCSummaryKey(ID, S)] = Summ;
Ted Kremenek614cc542009-07-21 23:27:57 +00001537 }
Mike Stump1eb44332009-09-09 15:08:12 +00001538
Ted Kremeneke87450e2009-04-23 19:11:35 +00001539 return Summ;
Ted Kremenekc8395602008-05-06 21:26:51 +00001540}
1541
Mike Stump1eb44332009-09-09 15:08:12 +00001542void RetainSummaryManager::InitializeClassMethodSummaries() {
Ted Kremenekec315332009-05-07 23:40:42 +00001543 assert(ScratchArgs.isEmpty());
Mike Stump1eb44332009-09-09 15:08:12 +00001544 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek6fe2b7a2009-10-15 22:25:12 +00001545 addClassMethSummary("NSAssertionHandler", "currentHandler",
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001546 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Mike Stump1eb44332009-09-09 15:08:12 +00001547
Ted Kremenek6d348932008-10-21 15:53:15 +00001548 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001549 ScratchArgs = AF.add(ScratchArgs, 0, Autorelease);
Ted Kremenek6fe2b7a2009-10-15 22:25:12 +00001550 addClassMethSummary("NSAutoreleasePool", "addObject",
1551 getPersistentSummary(RetEffect::MakeNoRet(),
1552 DoNothing, Autorelease));
Ted Kremenek9c32d082008-05-06 00:30:21 +00001553}
1554
Ted Kremenek1f180c32008-06-23 22:21:20 +00001555void RetainSummaryManager::InitializeMethodSummaries() {
Mike Stump1eb44332009-09-09 15:08:12 +00001556
1557 assert (ScratchArgs.isEmpty());
1558
Ted Kremenekc8395602008-05-06 21:26:51 +00001559 // Create the "init" selector. It just acts as a pass-through for the
1560 // receiver.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001561 const RetainSummary *InitSumm = getPersistentSummary(ObjCInitRetE, DecRefMsg);
Ted Kremenekac02f202009-08-20 05:13:36 +00001562 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
1563
1564 // awakeAfterUsingCoder: behaves basically like an 'init' method. It
1565 // claims the receiver and returns a retained object.
1566 addNSObjectMethSummary(GetUnarySelector("awakeAfterUsingCoder", Ctx),
1567 InitSumm);
Mike Stump1eb44332009-09-09 15:08:12 +00001568
Ted Kremenekc8395602008-05-06 21:26:51 +00001569 // The next methods are allocators.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001570 const RetainSummary *AllocSumm = getPersistentSummary(ObjCAllocRetE);
1571 const RetainSummary *CFAllocSumm =
Ted Kremeneka834fb42009-08-28 19:52:12 +00001572 getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Mike Stump1eb44332009-09-09 15:08:12 +00001573
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001574 // Create the "retain" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001575 RetEffect NoRet = RetEffect::MakeNoRet();
Ted Kremenek93edbc52011-10-05 23:54:29 +00001576 const RetainSummary *Summ = getPersistentSummary(NoRet, IncRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001577 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001578
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001579 // Create the "release" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001580 Summ = getPersistentSummary(NoRet, DecRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001581 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001582
Ted Kremenek299e8152008-05-07 21:17:39 +00001583 // Create the "drain" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001584 Summ = getPersistentSummary(NoRet, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek553cf182008-06-25 21:21:56 +00001585 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001586
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001587 // Create the -dealloc summary.
Jordy Rose500abad2011-08-21 19:41:36 +00001588 Summ = getPersistentSummary(NoRet, Dealloc);
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001589 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001590
1591 // Create the "autorelease" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001592 Summ = getPersistentSummary(NoRet, Autorelease);
Ted Kremenek553cf182008-06-25 21:21:56 +00001593 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001594
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00001595 // Specially handle NSAutoreleasePool.
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001596 addInstMethSummary("NSAutoreleasePool", "init",
Jordy Rose500abad2011-08-21 19:41:36 +00001597 getPersistentSummary(NoRet, NewAutoreleasePool));
Mike Stump1eb44332009-09-09 15:08:12 +00001598
1599 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremenek89e202d2009-02-23 02:51:29 +00001600 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1601 // self-own themselves. However, they only do this once they are displayed.
1602 // Thus, we need to track an NSWindow's display status.
1603 // This is tracked in <rdar://problem/6062711>.
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +00001604 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001605 const RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenek78a35a32009-05-12 20:06:54 +00001606 StopTracking,
1607 StopTracking);
Mike Stump1eb44332009-09-09 15:08:12 +00001608
Ted Kremenek99d02692009-04-03 19:02:51 +00001609 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1610
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001611 // For NSPanel (which subclasses NSWindow), allocated objects are not
1612 // self-owned.
Ted Kremenek99d02692009-04-03 19:02:51 +00001613 // FIXME: For now we don't track NSPanels. object for the same reason
1614 // as for NSWindow objects.
1615 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
Mike Stump1eb44332009-09-09 15:08:12 +00001616
Ted Kremenekba67f6a2009-05-18 23:14:34 +00001617 // Don't track allocated autorelease pools yet, as it is okay to prematurely
1618 // exit a method.
1619 addClassMethSummary("NSAutoreleasePool", "alloc", NoTrackYet);
Ted Kremeneka9797122012-02-18 21:37:48 +00001620 addClassMethSummary("NSAutoreleasePool", "allocWithZone", NoTrackYet, false);
Ted Kremenek553cf182008-06-25 21:21:56 +00001621
Ted Kremenek767d6492009-05-20 22:39:57 +00001622 // Create summaries QCRenderer/QCView -createSnapShotImageOfType:
1623 addInstMethSummary("QCRenderer", AllocSumm,
1624 "createSnapshotImageOfType", NULL);
1625 addInstMethSummary("QCView", AllocSumm,
1626 "createSnapshotImageOfType", NULL);
1627
Ted Kremenek211a9c62009-06-15 20:58:58 +00001628 // Create summaries for CIContext, 'createCGImage' and
Ted Kremeneka834fb42009-08-28 19:52:12 +00001629 // 'createCGLayerWithSize'. These objects are CF objects, and are not
1630 // automatically garbage collected.
1631 addInstMethSummary("CIContext", CFAllocSumm,
Ted Kremenek767d6492009-05-20 22:39:57 +00001632 "createCGImage", "fromRect", NULL);
Ted Kremeneka834fb42009-08-28 19:52:12 +00001633 addInstMethSummary("CIContext", CFAllocSumm,
Mike Stump1eb44332009-09-09 15:08:12 +00001634 "createCGImage", "fromRect", "format", "colorSpace", NULL);
Ted Kremeneka834fb42009-08-28 19:52:12 +00001635 addInstMethSummary("CIContext", CFAllocSumm, "createCGLayerWithSize",
Ted Kremenek211a9c62009-06-15 20:58:58 +00001636 "info", NULL);
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001637}
1638
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001639//===----------------------------------------------------------------------===//
Ted Kremenekc887d132009-04-29 18:50:19 +00001640// Error reporting.
1641//===----------------------------------------------------------------------===//
Ted Kremenekc887d132009-04-29 18:50:19 +00001642namespace {
Jordy Roseec9ef852011-08-23 20:55:48 +00001643 typedef llvm::DenseMap<const ExplodedNode *, const RetainSummary *>
1644 SummaryLogTy;
1645
Ted Kremenekc887d132009-04-29 18:50:19 +00001646 //===-------------===//
1647 // Bug Descriptions. //
Mike Stump1eb44332009-09-09 15:08:12 +00001648 //===-------------===//
1649
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001650 class CFRefBug : public BugType {
Ted Kremenekc887d132009-04-29 18:50:19 +00001651 protected:
Jordy Rose35c86952011-08-24 05:47:39 +00001652 CFRefBug(StringRef name)
Ted Kremenek6fd45052012-04-05 20:43:28 +00001653 : BugType(name, categories::MemoryCoreFoundationObjectiveC) {}
Ted Kremenekc887d132009-04-29 18:50:19 +00001654 public:
Mike Stump1eb44332009-09-09 15:08:12 +00001655
Ted Kremenekc887d132009-04-29 18:50:19 +00001656 // FIXME: Eventually remove.
Jordy Rose35c86952011-08-24 05:47:39 +00001657 virtual const char *getDescription() const = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001658
Ted Kremenekc887d132009-04-29 18:50:19 +00001659 virtual bool isLeak() const { return false; }
1660 };
Mike Stump1eb44332009-09-09 15:08:12 +00001661
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001662 class UseAfterRelease : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001663 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001664 UseAfterRelease() : CFRefBug("Use-after-release") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001665
Jordy Rose35c86952011-08-24 05:47:39 +00001666 const char *getDescription() const {
Ted Kremenekc887d132009-04-29 18:50:19 +00001667 return "Reference-counted object is used after it is released";
Mike Stump1eb44332009-09-09 15:08:12 +00001668 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001669 };
Mike Stump1eb44332009-09-09 15:08:12 +00001670
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001671 class BadRelease : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001672 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001673 BadRelease() : CFRefBug("Bad release") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001674
Jordy Rose35c86952011-08-24 05:47:39 +00001675 const char *getDescription() const {
Ted Kremenekbb206fd2009-10-01 17:31:50 +00001676 return "Incorrect decrement of the reference count of an object that is "
1677 "not owned at this point by the caller";
Ted Kremenekc887d132009-04-29 18:50:19 +00001678 }
1679 };
Mike Stump1eb44332009-09-09 15:08:12 +00001680
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001681 class DeallocGC : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001682 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001683 DeallocGC()
1684 : CFRefBug("-dealloc called while using garbage collection") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001685
Ted Kremenekc887d132009-04-29 18:50:19 +00001686 const char *getDescription() const {
Ted Kremenek369de562009-05-09 00:10:05 +00001687 return "-dealloc called while using garbage collection";
Ted Kremenekc887d132009-04-29 18:50:19 +00001688 }
1689 };
Mike Stump1eb44332009-09-09 15:08:12 +00001690
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001691 class DeallocNotOwned : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001692 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001693 DeallocNotOwned()
1694 : CFRefBug("-dealloc sent to non-exclusively owned object") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001695
Ted Kremenekc887d132009-04-29 18:50:19 +00001696 const char *getDescription() const {
1697 return "-dealloc sent to object that may be referenced elsewhere";
1698 }
Mike Stump1eb44332009-09-09 15:08:12 +00001699 };
1700
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001701 class OverAutorelease : public CFRefBug {
Ted Kremenek369de562009-05-09 00:10:05 +00001702 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001703 OverAutorelease()
1704 : CFRefBug("Object sent -autorelease too many times") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001705
Ted Kremenek369de562009-05-09 00:10:05 +00001706 const char *getDescription() const {
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001707 return "Object sent -autorelease too many times";
Ted Kremenek369de562009-05-09 00:10:05 +00001708 }
1709 };
Mike Stump1eb44332009-09-09 15:08:12 +00001710
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001711 class ReturnedNotOwnedForOwned : public CFRefBug {
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001712 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001713 ReturnedNotOwnedForOwned()
1714 : CFRefBug("Method should return an owned object") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001715
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001716 const char *getDescription() const {
Jordy Rose5b5402b2011-07-15 22:17:54 +00001717 return "Object with a +0 retain count returned to caller where a +1 "
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001718 "(owning) retain count is expected";
1719 }
1720 };
Mike Stump1eb44332009-09-09 15:08:12 +00001721
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001722 class Leak : public CFRefBug {
Benjamin Kramerfacde172012-06-06 17:32:50 +00001723 public:
1724 Leak(StringRef name)
1725 : CFRefBug(name) {
Jordy Rosedb92bb62011-08-25 01:14:38 +00001726 // Leaks should not be reported if they are post-dominated by a sink.
1727 setSuppressOnSink(true);
1728 }
Mike Stump1eb44332009-09-09 15:08:12 +00001729
Jordy Rose35c86952011-08-24 05:47:39 +00001730 const char *getDescription() const { return ""; }
Mike Stump1eb44332009-09-09 15:08:12 +00001731
Ted Kremenekc887d132009-04-29 18:50:19 +00001732 bool isLeak() const { return true; }
1733 };
Mike Stump1eb44332009-09-09 15:08:12 +00001734
Ted Kremenekc887d132009-04-29 18:50:19 +00001735 //===---------===//
1736 // Bug Reports. //
1737 //===---------===//
Mike Stump1eb44332009-09-09 15:08:12 +00001738
Jordy Rose01153492012-03-24 02:45:35 +00001739 class CFRefReportVisitor : public BugReporterVisitorImpl<CFRefReportVisitor> {
Anna Zaks23f395e2011-08-20 01:27:22 +00001740 protected:
Anna Zaksdc757b02011-08-19 23:21:56 +00001741 SymbolRef Sym;
Jordy Roseec9ef852011-08-23 20:55:48 +00001742 const SummaryLogTy &SummaryLog;
Jordy Rose35c86952011-08-24 05:47:39 +00001743 bool GCEnabled;
Anna Zaks23f395e2011-08-20 01:27:22 +00001744
Anna Zaksdc757b02011-08-19 23:21:56 +00001745 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001746 CFRefReportVisitor(SymbolRef sym, bool gcEnabled, const SummaryLogTy &log)
1747 : Sym(sym), SummaryLog(log), GCEnabled(gcEnabled) {}
Anna Zaksdc757b02011-08-19 23:21:56 +00001748
Anna Zaks23f395e2011-08-20 01:27:22 +00001749 virtual void Profile(llvm::FoldingSetNodeID &ID) const {
Anna Zaksdc757b02011-08-19 23:21:56 +00001750 static int x = 0;
1751 ID.AddPointer(&x);
1752 ID.AddPointer(Sym);
1753 }
1754
Anna Zaks23f395e2011-08-20 01:27:22 +00001755 virtual PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
1756 const ExplodedNode *PrevN,
1757 BugReporterContext &BRC,
1758 BugReport &BR);
1759
1760 virtual PathDiagnosticPiece *getEndPath(BugReporterContext &BRC,
1761 const ExplodedNode *N,
1762 BugReport &BR);
1763 };
1764
1765 class CFRefLeakReportVisitor : public CFRefReportVisitor {
1766 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001767 CFRefLeakReportVisitor(SymbolRef sym, bool GCEnabled,
Jordy Roseec9ef852011-08-23 20:55:48 +00001768 const SummaryLogTy &log)
Jordy Rose35c86952011-08-24 05:47:39 +00001769 : CFRefReportVisitor(sym, GCEnabled, log) {}
Anna Zaks23f395e2011-08-20 01:27:22 +00001770
1771 PathDiagnosticPiece *getEndPath(BugReporterContext &BRC,
1772 const ExplodedNode *N,
1773 BugReport &BR);
Jordy Rose01153492012-03-24 02:45:35 +00001774
1775 virtual BugReporterVisitor *clone() const {
1776 // The curiously-recurring template pattern only works for one level of
1777 // subclassing. Rather than make a new template base for
1778 // CFRefReportVisitor, we simply override clone() to do the right thing.
1779 // This could be trouble someday if BugReporterVisitorImpl is ever
1780 // used for something else besides a convenient implementation of clone().
1781 return new CFRefLeakReportVisitor(*this);
1782 }
Anna Zaksdc757b02011-08-19 23:21:56 +00001783 };
1784
Anna Zakse172e8b2011-08-17 23:00:25 +00001785 class CFRefReport : public BugReport {
Jordy Rose20589562011-08-24 22:39:09 +00001786 void addGCModeDescription(const LangOptions &LOpts, bool GCEnabled);
Jordy Rose35c86952011-08-24 05:47:39 +00001787
Ted Kremenekc887d132009-04-29 18:50:19 +00001788 public:
Jordy Rose20589562011-08-24 22:39:09 +00001789 CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1790 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1791 bool registerVisitor = true)
Anna Zaksedf4dae2011-08-22 18:54:07 +00001792 : BugReport(D, D.getDescription(), n) {
Anna Zaks23f395e2011-08-20 01:27:22 +00001793 if (registerVisitor)
Jordy Rose20589562011-08-24 22:39:09 +00001794 addVisitor(new CFRefReportVisitor(sym, GCEnabled, Log));
1795 addGCModeDescription(LOpts, GCEnabled);
Anna Zaksdc757b02011-08-19 23:21:56 +00001796 }
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001797
Jordy Rose20589562011-08-24 22:39:09 +00001798 CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1799 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1800 StringRef endText)
Anna Zaksedf4dae2011-08-22 18:54:07 +00001801 : BugReport(D, D.getDescription(), endText, n) {
Jordy Rose20589562011-08-24 22:39:09 +00001802 addVisitor(new CFRefReportVisitor(sym, GCEnabled, Log));
1803 addGCModeDescription(LOpts, GCEnabled);
Anna Zaksdc757b02011-08-19 23:21:56 +00001804 }
Mike Stump1eb44332009-09-09 15:08:12 +00001805
Anna Zakse172e8b2011-08-17 23:00:25 +00001806 virtual std::pair<ranges_iterator, ranges_iterator> getRanges() {
Anna Zaksedf4dae2011-08-22 18:54:07 +00001807 const CFRefBug& BugTy = static_cast<CFRefBug&>(getBugType());
1808 if (!BugTy.isLeak())
Anna Zakse172e8b2011-08-17 23:00:25 +00001809 return BugReport::getRanges();
Ted Kremenekc887d132009-04-29 18:50:19 +00001810 else
Argyrios Kyrtzidis640ccf02010-12-04 01:12:15 +00001811 return std::make_pair(ranges_iterator(), ranges_iterator());
Ted Kremenekc887d132009-04-29 18:50:19 +00001812 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001813 };
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001814
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001815 class CFRefLeakReport : public CFRefReport {
Ted Kremenekc887d132009-04-29 18:50:19 +00001816 const MemRegion* AllocBinding;
Anna Zaks23f395e2011-08-20 01:27:22 +00001817
Ted Kremenekc887d132009-04-29 18:50:19 +00001818 public:
Jordy Rose20589562011-08-24 22:39:09 +00001819 CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1820 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
Anna Zaks6a93bd52011-10-25 19:57:11 +00001821 CheckerContext &Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001822
Anna Zaks590dd8e2011-09-20 21:38:35 +00001823 PathDiagnosticLocation getLocation(const SourceManager &SM) const {
1824 assert(Location.isValid());
1825 return Location;
1826 }
Mike Stump1eb44332009-09-09 15:08:12 +00001827 };
Ted Kremenekc887d132009-04-29 18:50:19 +00001828} // end anonymous namespace
1829
Jordy Rose20589562011-08-24 22:39:09 +00001830void CFRefReport::addGCModeDescription(const LangOptions &LOpts,
1831 bool GCEnabled) {
Jordy Rosef95b19d2011-08-24 20:38:42 +00001832 const char *GCModeDescription = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001833
Douglas Gregore289d812011-09-13 17:21:33 +00001834 switch (LOpts.getGC()) {
Anna Zaks7f2531c2011-08-22 20:31:28 +00001835 case LangOptions::GCOnly:
Jordy Rose20589562011-08-24 22:39:09 +00001836 assert(GCEnabled);
Jordy Rose35c86952011-08-24 05:47:39 +00001837 GCModeDescription = "Code is compiled to only use garbage collection";
1838 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001839
Anna Zaks7f2531c2011-08-22 20:31:28 +00001840 case LangOptions::NonGC:
Jordy Rose20589562011-08-24 22:39:09 +00001841 assert(!GCEnabled);
Jordy Rose35c86952011-08-24 05:47:39 +00001842 GCModeDescription = "Code is compiled to use reference counts";
1843 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001844
Anna Zaks7f2531c2011-08-22 20:31:28 +00001845 case LangOptions::HybridGC:
Jordy Rose20589562011-08-24 22:39:09 +00001846 if (GCEnabled) {
Jordy Rose35c86952011-08-24 05:47:39 +00001847 GCModeDescription = "Code is compiled to use either garbage collection "
1848 "(GC) or reference counts (non-GC). The bug occurs "
1849 "with GC enabled";
1850 break;
1851 } else {
1852 GCModeDescription = "Code is compiled to use either garbage collection "
1853 "(GC) or reference counts (non-GC). The bug occurs "
1854 "in non-GC mode";
1855 break;
Anna Zaks7f2531c2011-08-22 20:31:28 +00001856 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001857 }
Jordy Rose35c86952011-08-24 05:47:39 +00001858
Jordy Rosef95b19d2011-08-24 20:38:42 +00001859 assert(GCModeDescription && "invalid/unknown GC mode");
Jordy Rose35c86952011-08-24 05:47:39 +00001860 addExtraText(GCModeDescription);
Ted Kremenekc887d132009-04-29 18:50:19 +00001861}
1862
Jordy Rose910c4052011-09-02 06:44:22 +00001863// FIXME: This should be a method on SmallVector.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001864static inline bool contains(const SmallVectorImpl<ArgEffect>& V,
Ted Kremenekc887d132009-04-29 18:50:19 +00001865 ArgEffect X) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001866 for (SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
Ted Kremenekc887d132009-04-29 18:50:19 +00001867 I!=E; ++I)
1868 if (*I == X) return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001869
Ted Kremenekc887d132009-04-29 18:50:19 +00001870 return false;
1871}
1872
Jordy Rose70fdbc32012-05-12 05:10:43 +00001873static bool isNumericLiteralExpression(const Expr *E) {
1874 // FIXME: This set of cases was copied from SemaExprObjC.
1875 return isa<IntegerLiteral>(E) ||
1876 isa<CharacterLiteral>(E) ||
1877 isa<FloatingLiteral>(E) ||
1878 isa<ObjCBoolLiteralExpr>(E) ||
1879 isa<CXXBoolLiteralExpr>(E);
1880}
1881
Anna Zaksdc757b02011-08-19 23:21:56 +00001882PathDiagnosticPiece *CFRefReportVisitor::VisitNode(const ExplodedNode *N,
1883 const ExplodedNode *PrevN,
1884 BugReporterContext &BRC,
1885 BugReport &BR) {
Jordan Rose28038f32012-07-10 22:07:42 +00001886 // FIXME: We will eventually need to handle non-statement-based events
1887 // (__attribute__((cleanup))).
Jordy Rosef53e8c72011-08-23 19:43:16 +00001888 if (!isa<StmtPoint>(N->getLocation()))
Ted Kremenek2033a952009-05-13 07:12:33 +00001889 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001890
Ted Kremenek8966bc12009-05-06 21:39:49 +00001891 // Check if the type state has changed.
Ted Kremenek8bef8232012-01-26 21:29:00 +00001892 ProgramStateRef PrevSt = PrevN->getState();
1893 ProgramStateRef CurrSt = N->getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001894 const LocationContext *LCtx = N->getLocationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00001895
Anna Zaks8d6b43c2012-08-14 00:36:15 +00001896 const RefVal* CurrT = getRefBinding(CurrSt, Sym);
Ted Kremenekc887d132009-04-29 18:50:19 +00001897 if (!CurrT) return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001898
Ted Kremenekb65be702009-06-18 01:23:53 +00001899 const RefVal &CurrV = *CurrT;
Anna Zaks8d6b43c2012-08-14 00:36:15 +00001900 const RefVal *PrevT = getRefBinding(PrevSt, Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00001901
Ted Kremenekc887d132009-04-29 18:50:19 +00001902 // Create a string buffer to constain all the useful things we want
1903 // to tell the user.
1904 std::string sbuf;
1905 llvm::raw_string_ostream os(sbuf);
Mike Stump1eb44332009-09-09 15:08:12 +00001906
Ted Kremenekc887d132009-04-29 18:50:19 +00001907 // This is the allocation site since the previous node had no bindings
1908 // for this symbol.
1909 if (!PrevT) {
Jordy Rosef53e8c72011-08-23 19:43:16 +00001910 const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
Mike Stump1eb44332009-09-09 15:08:12 +00001911
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001912 if (isa<ObjCArrayLiteral>(S)) {
1913 os << "NSArray literal is an object with a +0 retain count";
Mike Stump1eb44332009-09-09 15:08:12 +00001914 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001915 else if (isa<ObjCDictionaryLiteral>(S)) {
1916 os << "NSDictionary literal is an object with a +0 retain count";
Ted Kremenekc887d132009-04-29 18:50:19 +00001917 }
Jordy Rose70fdbc32012-05-12 05:10:43 +00001918 else if (const ObjCBoxedExpr *BL = dyn_cast<ObjCBoxedExpr>(S)) {
1919 if (isNumericLiteralExpression(BL->getSubExpr()))
1920 os << "NSNumber literal is an object with a +0 retain count";
1921 else {
1922 const ObjCInterfaceDecl *BoxClass = 0;
1923 if (const ObjCMethodDecl *Method = BL->getBoxingMethod())
1924 BoxClass = Method->getClassInterface();
1925
1926 // We should always be able to find the boxing class interface,
1927 // but consider this future-proofing.
1928 if (BoxClass)
1929 os << *BoxClass << " b";
1930 else
1931 os << "B";
1932
1933 os << "oxed expression produces an object with a +0 retain count";
1934 }
1935 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001936 else {
1937 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
1938 // Get the name of the callee (if it is available).
1939 SVal X = CurrSt->getSValAsScalarOrLoc(CE->getCallee(), LCtx);
1940 if (const FunctionDecl *FD = X.getAsFunctionDecl())
1941 os << "Call to function '" << *FD << '\'';
1942 else
1943 os << "function call";
Ted Kremenekc887d132009-04-29 18:50:19 +00001944 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001945 else {
Jordan Rose8919e682012-07-18 21:59:51 +00001946 assert(isa<ObjCMessageExpr>(S));
Jordan Rosed563d3f2012-07-30 20:22:09 +00001947 CallEventManager &Mgr = CurrSt->getStateManager().getCallEventManager();
1948 CallEventRef<ObjCMethodCall> Call
1949 = Mgr.getObjCMethodCall(cast<ObjCMessageExpr>(S), CurrSt, LCtx);
1950
1951 switch (Call->getMessageKind()) {
Jordan Rose8919e682012-07-18 21:59:51 +00001952 case OCM_Message:
1953 os << "Method";
1954 break;
1955 case OCM_PropertyAccess:
1956 os << "Property";
1957 break;
1958 case OCM_Subscript:
1959 os << "Subscript";
1960 break;
1961 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001962 }
1963
1964 if (CurrV.getObjKind() == RetEffect::CF) {
1965 os << " returns a Core Foundation object with a ";
1966 }
1967 else {
1968 assert (CurrV.getObjKind() == RetEffect::ObjC);
1969 os << " returns an Objective-C object with a ";
1970 }
1971
1972 if (CurrV.isOwned()) {
1973 os << "+1 retain count";
1974
1975 if (GCEnabled) {
1976 assert(CurrV.getObjKind() == RetEffect::CF);
1977 os << ". "
1978 "Core Foundation objects are not automatically garbage collected.";
1979 }
1980 }
1981 else {
1982 assert (CurrV.isNotOwned());
1983 os << "+0 retain count";
1984 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001985 }
Mike Stump1eb44332009-09-09 15:08:12 +00001986
Anna Zaks220ac8c2011-09-15 01:08:34 +00001987 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
1988 N->getLocationContext());
Ted Kremenekc887d132009-04-29 18:50:19 +00001989 return new PathDiagnosticEventPiece(Pos, os.str());
1990 }
Mike Stump1eb44332009-09-09 15:08:12 +00001991
Ted Kremenekc887d132009-04-29 18:50:19 +00001992 // Gather up the effects that were performed on the object at this
1993 // program point
Chris Lattner5f9e2722011-07-23 10:55:15 +00001994 SmallVector<ArgEffect, 2> AEffects;
Mike Stump1eb44332009-09-09 15:08:12 +00001995
Jordy Roseec9ef852011-08-23 20:55:48 +00001996 const ExplodedNode *OrigNode = BRC.getNodeResolver().getOriginalNode(N);
1997 if (const RetainSummary *Summ = SummaryLog.lookup(OrigNode)) {
Ted Kremenekc887d132009-04-29 18:50:19 +00001998 // We only have summaries attached to nodes after evaluating CallExpr and
1999 // ObjCMessageExprs.
Jordy Rosef53e8c72011-08-23 19:43:16 +00002000 const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
Mike Stump1eb44332009-09-09 15:08:12 +00002001
Ted Kremenek5f85e172009-07-22 22:35:28 +00002002 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002003 // Iterate through the parameter expressions and see if the symbol
2004 // was ever passed as an argument.
2005 unsigned i = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002006
Ted Kremenek5f85e172009-07-22 22:35:28 +00002007 for (CallExpr::const_arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
Ted Kremenekc887d132009-04-29 18:50:19 +00002008 AI!=AE; ++AI, ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002009
Ted Kremenekc887d132009-04-29 18:50:19 +00002010 // Retrieve the value of the argument. Is it the symbol
2011 // we are interested in?
Ted Kremenek5eca4822012-01-06 22:09:28 +00002012 if (CurrSt->getSValAsScalarOrLoc(*AI, LCtx).getAsLocSymbol() != Sym)
Ted Kremenekc887d132009-04-29 18:50:19 +00002013 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00002014
Ted Kremenekc887d132009-04-29 18:50:19 +00002015 // We have an argument. Get the effect!
2016 AEffects.push_back(Summ->getArg(i));
2017 }
2018 }
Mike Stump1eb44332009-09-09 15:08:12 +00002019 else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002020 if (const Expr *receiver = ME->getInstanceReceiver())
Ted Kremenek5eca4822012-01-06 22:09:28 +00002021 if (CurrSt->getSValAsScalarOrLoc(receiver, LCtx)
2022 .getAsLocSymbol() == Sym) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002023 // The symbol we are tracking is the receiver.
2024 AEffects.push_back(Summ->getReceiverEffect());
2025 }
2026 }
2027 }
Mike Stump1eb44332009-09-09 15:08:12 +00002028
Ted Kremenekc887d132009-04-29 18:50:19 +00002029 do {
2030 // Get the previous type state.
2031 RefVal PrevV = *PrevT;
Mike Stump1eb44332009-09-09 15:08:12 +00002032
Ted Kremenekc887d132009-04-29 18:50:19 +00002033 // Specially handle -dealloc.
Jordy Rose35c86952011-08-24 05:47:39 +00002034 if (!GCEnabled && contains(AEffects, Dealloc)) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002035 // Determine if the object's reference count was pushed to zero.
2036 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2037 // We may not have transitioned to 'release' if we hit an error.
2038 // This case is handled elsewhere.
2039 if (CurrV.getKind() == RefVal::Released) {
Ted Kremenekf21332e2009-05-08 20:01:42 +00002040 assert(CurrV.getCombinedCounts() == 0);
Ted Kremenekc887d132009-04-29 18:50:19 +00002041 os << "Object released by directly sending the '-dealloc' message";
2042 break;
2043 }
2044 }
Mike Stump1eb44332009-09-09 15:08:12 +00002045
Ted Kremenekc887d132009-04-29 18:50:19 +00002046 // Specially handle CFMakeCollectable and friends.
2047 if (contains(AEffects, MakeCollectable)) {
2048 // Get the name of the function.
Jordy Rosef53e8c72011-08-23 19:43:16 +00002049 const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
Ted Kremenek5eca4822012-01-06 22:09:28 +00002050 SVal X =
2051 CurrSt->getSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee(), LCtx);
Ted Kremenek9c378f72011-08-12 23:37:29 +00002052 const FunctionDecl *FD = X.getAsFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002053
Jordy Rose35c86952011-08-24 05:47:39 +00002054 if (GCEnabled) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002055 // Determine if the object's reference count was pushed to zero.
2056 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
Mike Stump1eb44332009-09-09 15:08:12 +00002057
Benjamin Kramerb8989f22011-10-14 18:45:37 +00002058 os << "In GC mode a call to '" << *FD
Ted Kremenekc887d132009-04-29 18:50:19 +00002059 << "' decrements an object's retain count and registers the "
2060 "object with the garbage collector. ";
Mike Stump1eb44332009-09-09 15:08:12 +00002061
Ted Kremenekc887d132009-04-29 18:50:19 +00002062 if (CurrV.getKind() == RefVal::Released) {
2063 assert(CurrV.getCount() == 0);
2064 os << "Since it now has a 0 retain count the object can be "
2065 "automatically collected by the garbage collector.";
2066 }
2067 else
2068 os << "An object must have a 0 retain count to be garbage collected. "
2069 "After this call its retain count is +" << CurrV.getCount()
2070 << '.';
2071 }
Mike Stump1eb44332009-09-09 15:08:12 +00002072 else
Benjamin Kramerb8989f22011-10-14 18:45:37 +00002073 os << "When GC is not enabled a call to '" << *FD
Ted Kremenekc887d132009-04-29 18:50:19 +00002074 << "' has no effect on its argument.";
Mike Stump1eb44332009-09-09 15:08:12 +00002075
Ted Kremenekc887d132009-04-29 18:50:19 +00002076 // Nothing more to say.
2077 break;
2078 }
Mike Stump1eb44332009-09-09 15:08:12 +00002079
2080 // Determine if the typestate has changed.
Ted Kremenekc887d132009-04-29 18:50:19 +00002081 if (!(PrevV == CurrV))
2082 switch (CurrV.getKind()) {
2083 case RefVal::Owned:
2084 case RefVal::NotOwned:
Mike Stump1eb44332009-09-09 15:08:12 +00002085
Ted Kremenekf21332e2009-05-08 20:01:42 +00002086 if (PrevV.getCount() == CurrV.getCount()) {
2087 // Did an autorelease message get sent?
2088 if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
2089 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002090
Zhongxing Xu264e9372009-05-12 10:10:00 +00002091 assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount());
Ted Kremenekeaedfea2009-05-10 05:11:21 +00002092 os << "Object sent -autorelease message";
Ted Kremenekf21332e2009-05-08 20:01:42 +00002093 break;
2094 }
Mike Stump1eb44332009-09-09 15:08:12 +00002095
Ted Kremenekc887d132009-04-29 18:50:19 +00002096 if (PrevV.getCount() > CurrV.getCount())
2097 os << "Reference count decremented.";
2098 else
2099 os << "Reference count incremented.";
Mike Stump1eb44332009-09-09 15:08:12 +00002100
Ted Kremenekc887d132009-04-29 18:50:19 +00002101 if (unsigned Count = CurrV.getCount())
2102 os << " The object now has a +" << Count << " retain count.";
Mike Stump1eb44332009-09-09 15:08:12 +00002103
Ted Kremenekc887d132009-04-29 18:50:19 +00002104 if (PrevV.getKind() == RefVal::Released) {
Jordy Rose35c86952011-08-24 05:47:39 +00002105 assert(GCEnabled && CurrV.getCount() > 0);
Jordy Rose74b7b2b2012-03-17 05:49:15 +00002106 os << " The object is not eligible for garbage collection until "
2107 "the retain count reaches 0 again.";
Ted Kremenekc887d132009-04-29 18:50:19 +00002108 }
Mike Stump1eb44332009-09-09 15:08:12 +00002109
Ted Kremenekc887d132009-04-29 18:50:19 +00002110 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002111
Ted Kremenekc887d132009-04-29 18:50:19 +00002112 case RefVal::Released:
2113 os << "Object released.";
2114 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002115
Ted Kremenekc887d132009-04-29 18:50:19 +00002116 case RefVal::ReturnedOwned:
Jordy Rose74b7b2b2012-03-17 05:49:15 +00002117 // Autoreleases can be applied after marking a node ReturnedOwned.
2118 if (CurrV.getAutoreleaseCount())
2119 return NULL;
2120
2121 os << "Object returned to caller as an owning reference (single "
2122 "retain count transferred to caller)";
Ted Kremenekc887d132009-04-29 18:50:19 +00002123 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002124
Ted Kremenekc887d132009-04-29 18:50:19 +00002125 case RefVal::ReturnedNotOwned:
Ted Kremenekf1365462011-05-26 18:45:44 +00002126 os << "Object returned to caller with a +0 retain count";
Ted Kremenekc887d132009-04-29 18:50:19 +00002127 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002128
Ted Kremenekc887d132009-04-29 18:50:19 +00002129 default:
2130 return NULL;
2131 }
Mike Stump1eb44332009-09-09 15:08:12 +00002132
Ted Kremenekc887d132009-04-29 18:50:19 +00002133 // Emit any remaining diagnostics for the argument effects (if any).
Chris Lattner5f9e2722011-07-23 10:55:15 +00002134 for (SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
Ted Kremenekc887d132009-04-29 18:50:19 +00002135 E=AEffects.end(); I != E; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +00002136
Ted Kremenekc887d132009-04-29 18:50:19 +00002137 // A bunch of things have alternate behavior under GC.
Jordy Rose35c86952011-08-24 05:47:39 +00002138 if (GCEnabled)
Ted Kremenekc887d132009-04-29 18:50:19 +00002139 switch (*I) {
2140 default: break;
2141 case Autorelease:
2142 os << "In GC mode an 'autorelease' has no effect.";
2143 continue;
2144 case IncRefMsg:
2145 os << "In GC mode the 'retain' message has no effect.";
2146 continue;
2147 case DecRefMsg:
2148 os << "In GC mode the 'release' message has no effect.";
2149 continue;
2150 }
2151 }
Mike Stump1eb44332009-09-09 15:08:12 +00002152 } while (0);
2153
Ted Kremenekc887d132009-04-29 18:50:19 +00002154 if (os.str().empty())
2155 return 0; // We have nothing to say!
Ted Kremenek2033a952009-05-13 07:12:33 +00002156
Jordy Rosef53e8c72011-08-23 19:43:16 +00002157 const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
Anna Zaks220ac8c2011-09-15 01:08:34 +00002158 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
2159 N->getLocationContext());
Ted Kremenek9c378f72011-08-12 23:37:29 +00002160 PathDiagnosticPiece *P = new PathDiagnosticEventPiece(Pos, os.str());
Mike Stump1eb44332009-09-09 15:08:12 +00002161
Ted Kremenekc887d132009-04-29 18:50:19 +00002162 // Add the range by scanning the children of the statement for any bindings
2163 // to Sym.
Mike Stump1eb44332009-09-09 15:08:12 +00002164 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
Ted Kremenek5f85e172009-07-22 22:35:28 +00002165 I!=E; ++I)
Ted Kremenek9c378f72011-08-12 23:37:29 +00002166 if (const Expr *Exp = dyn_cast_or_null<Expr>(*I))
Ted Kremenek5eca4822012-01-06 22:09:28 +00002167 if (CurrSt->getSValAsScalarOrLoc(Exp, LCtx).getAsLocSymbol() == Sym) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002168 P->addRange(Exp->getSourceRange());
2169 break;
2170 }
Mike Stump1eb44332009-09-09 15:08:12 +00002171
Ted Kremenekc887d132009-04-29 18:50:19 +00002172 return P;
2173}
2174
Anna Zakse7e01682012-02-28 22:39:22 +00002175// Find the first node in the current function context that referred to the
2176// tracked symbol and the memory location that value was stored to. Note, the
2177// value is only reported if the allocation occurred in the same function as
2178// the leak.
Zhongxing Xuc5619d92009-08-06 01:32:16 +00002179static std::pair<const ExplodedNode*,const MemRegion*>
Ted Kremenek18c66fd2011-08-15 22:09:50 +00002180GetAllocationSite(ProgramStateManager& StateMgr, const ExplodedNode *N,
Ted Kremenekc887d132009-04-29 18:50:19 +00002181 SymbolRef Sym) {
Ted Kremenek9c378f72011-08-12 23:37:29 +00002182 const ExplodedNode *Last = N;
Mike Stump1eb44332009-09-09 15:08:12 +00002183 const MemRegion* FirstBinding = 0;
Anna Zakse7e01682012-02-28 22:39:22 +00002184 const LocationContext *LeakContext = N->getLocationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002185
Ted Kremenekc887d132009-04-29 18:50:19 +00002186 while (N) {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002187 ProgramStateRef St = N->getState();
Mike Stump1eb44332009-09-09 15:08:12 +00002188
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002189 if (!getRefBinding(St, Sym))
Ted Kremenekc887d132009-04-29 18:50:19 +00002190 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002191
Anna Zaks27b867e2012-03-21 19:45:01 +00002192 StoreManager::FindUniqueBinding FB(Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002193 StateMgr.iterBindings(St, FB);
2194 if (FB) FirstBinding = FB.getRegion();
2195
Anna Zakse7e01682012-02-28 22:39:22 +00002196 // Allocation node, is the last node in the current context in which the
2197 // symbol was tracked.
2198 if (N->getLocationContext() == LeakContext)
2199 Last = N;
2200
Mike Stump1eb44332009-09-09 15:08:12 +00002201 N = N->pred_empty() ? NULL : *(N->pred_begin());
Ted Kremenekc887d132009-04-29 18:50:19 +00002202 }
Mike Stump1eb44332009-09-09 15:08:12 +00002203
Anna Zakse7e01682012-02-28 22:39:22 +00002204 // If allocation happened in a function different from the leak node context,
2205 // do not report the binding.
Ted Kremenek5a8fc882012-10-12 22:56:40 +00002206 assert(N && "Could not find allocation node");
Anna Zakse7e01682012-02-28 22:39:22 +00002207 if (N->getLocationContext() != LeakContext) {
2208 FirstBinding = 0;
2209 }
2210
Ted Kremenekc887d132009-04-29 18:50:19 +00002211 return std::make_pair(Last, FirstBinding);
2212}
2213
2214PathDiagnosticPiece*
Anna Zaks23f395e2011-08-20 01:27:22 +00002215CFRefReportVisitor::getEndPath(BugReporterContext &BRC,
2216 const ExplodedNode *EndN,
2217 BugReport &BR) {
Ted Kremenek76aadc32012-03-09 01:13:14 +00002218 BR.markInteresting(Sym);
Anna Zaks23f395e2011-08-20 01:27:22 +00002219 return BugReporterVisitor::getDefaultEndPath(BRC, EndN, BR);
Ted Kremenekc887d132009-04-29 18:50:19 +00002220}
2221
2222PathDiagnosticPiece*
Anna Zaks23f395e2011-08-20 01:27:22 +00002223CFRefLeakReportVisitor::getEndPath(BugReporterContext &BRC,
2224 const ExplodedNode *EndN,
2225 BugReport &BR) {
Mike Stump1eb44332009-09-09 15:08:12 +00002226
Ted Kremenek8966bc12009-05-06 21:39:49 +00002227 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenekc887d132009-04-29 18:50:19 +00002228 // assigned to different variables, etc.
Ted Kremenek76aadc32012-03-09 01:13:14 +00002229 BR.markInteresting(Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002230
Ted Kremenekc887d132009-04-29 18:50:19 +00002231 // We are reporting a leak. Walk up the graph to get to the first node where
2232 // the symbol appeared, and also get the first VarDecl that tracked object
2233 // is stored to.
Ted Kremenek9c378f72011-08-12 23:37:29 +00002234 const ExplodedNode *AllocNode = 0;
Ted Kremenekc887d132009-04-29 18:50:19 +00002235 const MemRegion* FirstBinding = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002236
Ted Kremenekc887d132009-04-29 18:50:19 +00002237 llvm::tie(AllocNode, FirstBinding) =
Ted Kremenekf04dced2009-05-08 23:32:51 +00002238 GetAllocationSite(BRC.getStateManager(), EndN, Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002239
Anna Zaks4fdf97b2011-09-15 18:56:07 +00002240 SourceManager& SM = BRC.getSourceManager();
Mike Stump1eb44332009-09-09 15:08:12 +00002241
Ted Kremenekc887d132009-04-29 18:50:19 +00002242 // Compute an actual location for the leak. Sometimes a leak doesn't
2243 // occur at an actual statement (e.g., transition between blocks; end
2244 // of function) so we need to walk the graph and compute a real location.
Ted Kremenek9c378f72011-08-12 23:37:29 +00002245 const ExplodedNode *LeakN = EndN;
Anna Zaks4fdf97b2011-09-15 18:56:07 +00002246 PathDiagnosticLocation L = PathDiagnosticLocation::createEndOfPath(LeakN, SM);
Mike Stump1eb44332009-09-09 15:08:12 +00002247
Ted Kremenekc887d132009-04-29 18:50:19 +00002248 std::string sbuf;
2249 llvm::raw_string_ostream os(sbuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002250
Ted Kremenekf1365462011-05-26 18:45:44 +00002251 os << "Object leaked: ";
Mike Stump1eb44332009-09-09 15:08:12 +00002252
Ted Kremenekf1365462011-05-26 18:45:44 +00002253 if (FirstBinding) {
2254 os << "object allocated and stored into '"
2255 << FirstBinding->getString() << '\'';
2256 }
2257 else
2258 os << "allocated object";
Mike Stump1eb44332009-09-09 15:08:12 +00002259
Ted Kremenekc887d132009-04-29 18:50:19 +00002260 // Get the retain count.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002261 const RefVal* RV = getRefBinding(EndN->getState(), Sym);
Ted Kremenek5a8fc882012-10-12 22:56:40 +00002262 assert(RV);
Mike Stump1eb44332009-09-09 15:08:12 +00002263
Ted Kremenekc887d132009-04-29 18:50:19 +00002264 if (RV->getKind() == RefVal::ErrorLeakReturned) {
2265 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
Jordy Rose5b5402b2011-07-15 22:17:54 +00002266 // objects. Only "copy", "alloc", "retain" and "new" transfer ownership
Ted Kremenekc887d132009-04-29 18:50:19 +00002267 // to the caller for NS objects.
Ted Kremenekd368d712011-05-25 06:19:45 +00002268 const Decl *D = &EndN->getCodeDecl();
Ted Kremenekec9f36e2012-09-06 23:03:07 +00002269
2270 os << (isa<ObjCMethodDecl>(D) ? " is returned from a method "
2271 : " is returned from a function ");
2272
2273 if (D->getAttr<CFReturnsNotRetainedAttr>())
2274 os << "that is annotated as CF_RETURNS_NOT_RETAINED";
2275 else if (D->getAttr<NSReturnsNotRetainedAttr>())
2276 os << "that is annotated as NS_RETURNS_NOT_RETAINED";
Ted Kremenekd368d712011-05-25 06:19:45 +00002277 else {
Ted Kremenekec9f36e2012-09-06 23:03:07 +00002278 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2279 os << "whose name ('" << MD->getSelector().getAsString()
2280 << "') does not start with 'copy', 'mutableCopy', 'alloc' or 'new'."
2281 " This violates the naming convention rules"
2282 " given in the Memory Management Guide for Cocoa";
2283 }
2284 else {
2285 const FunctionDecl *FD = cast<FunctionDecl>(D);
2286 os << "whose name ('" << *FD
2287 << "') does not contain 'Copy' or 'Create'. This violates the naming"
2288 " convention rules given in the Memory Management Guide for Core"
2289 " Foundation";
2290 }
2291 }
Ted Kremenekc887d132009-04-29 18:50:19 +00002292 }
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002293 else if (RV->getKind() == RefVal::ErrorGCLeakReturned) {
Ted Kremenek9c378f72011-08-12 23:37:29 +00002294 ObjCMethodDecl &MD = cast<ObjCMethodDecl>(EndN->getCodeDecl());
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002295 os << " and returned from method '" << MD.getSelector().getAsString()
Ted Kremenek82f2be52009-05-10 16:52:15 +00002296 << "' is potentially leaked when using garbage collection. Callers "
2297 "of this method do not expect a returned object with a +1 retain "
2298 "count since they expect the object to be managed by the garbage "
2299 "collector";
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002300 }
Ted Kremenekc887d132009-04-29 18:50:19 +00002301 else
Ted Kremenekabf517c2010-10-15 22:50:23 +00002302 os << " is not referenced later in this execution path and has a retain "
Ted Kremenekf1365462011-05-26 18:45:44 +00002303 "count of +" << RV->getCount();
Mike Stump1eb44332009-09-09 15:08:12 +00002304
Ted Kremenekc887d132009-04-29 18:50:19 +00002305 return new PathDiagnosticEventPiece(L, os.str());
2306}
2307
Jordy Rose20589562011-08-24 22:39:09 +00002308CFRefLeakReport::CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts,
2309 bool GCEnabled, const SummaryLogTy &Log,
2310 ExplodedNode *n, SymbolRef sym,
Anna Zaks6a93bd52011-10-25 19:57:11 +00002311 CheckerContext &Ctx)
Jordy Rose20589562011-08-24 22:39:09 +00002312: CFRefReport(D, LOpts, GCEnabled, Log, n, sym, false) {
Mike Stump1eb44332009-09-09 15:08:12 +00002313
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00002314 // Most bug reports are cached at the location where they occurred.
Ted Kremenekc887d132009-04-29 18:50:19 +00002315 // With leaks, we want to unique them by the location where they were
2316 // allocated, and only report a single path. To do this, we need to find
2317 // the allocation site of a piece of tracked memory, which we do via a
2318 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2319 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2320 // that all ancestor nodes that represent the allocation site have the
2321 // same SourceLocation.
Ted Kremenek9c378f72011-08-12 23:37:29 +00002322 const ExplodedNode *AllocNode = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002323
Anna Zaks6a93bd52011-10-25 19:57:11 +00002324 const SourceManager& SMgr = Ctx.getSourceManager();
Anna Zaks590dd8e2011-09-20 21:38:35 +00002325
Ted Kremenekc887d132009-04-29 18:50:19 +00002326 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding.
Anna Zaks6a93bd52011-10-25 19:57:11 +00002327 GetAllocationSite(Ctx.getStateManager(), getErrorNode(), sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002328
Ted Kremenekc887d132009-04-29 18:50:19 +00002329 // Get the SourceLocation for the allocation site.
Jordan Rose852aa0d2012-07-10 22:07:52 +00002330 // FIXME: This will crash the analyzer if an allocation comes from an
2331 // implicit call. (Currently there are no such allocations in Cocoa, though.)
2332 const Stmt *AllocStmt;
Ted Kremenekc887d132009-04-29 18:50:19 +00002333 ProgramPoint P = AllocNode->getLocation();
Jordan Rose852aa0d2012-07-10 22:07:52 +00002334 if (CallExitEnd *Exit = dyn_cast<CallExitEnd>(&P))
2335 AllocStmt = Exit->getCalleeContext()->getCallSite();
2336 else
2337 AllocStmt = cast<PostStmt>(P).getStmt();
2338 assert(AllocStmt && "All allocations must come from explicit calls");
Anna Zaks590dd8e2011-09-20 21:38:35 +00002339 Location = PathDiagnosticLocation::createBegin(AllocStmt, SMgr,
2340 n->getLocationContext());
Ted Kremenekc887d132009-04-29 18:50:19 +00002341 // Fill in the description of the bug.
2342 Description.clear();
2343 llvm::raw_string_ostream os(Description);
Ted Kremenekdd924e22009-05-02 19:05:19 +00002344 os << "Potential leak ";
Jordy Rose20589562011-08-24 22:39:09 +00002345 if (GCEnabled)
Ted Kremenekdd924e22009-05-02 19:05:19 +00002346 os << "(when using garbage collection) ";
Anna Zaks212000e2012-02-28 21:49:08 +00002347 os << "of an object";
Mike Stump1eb44332009-09-09 15:08:12 +00002348
Ted Kremenekc887d132009-04-29 18:50:19 +00002349 // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2350 if (AllocBinding)
Anna Zaks212000e2012-02-28 21:49:08 +00002351 os << " stored into '" << AllocBinding->getString() << '\'';
Anna Zaksdc757b02011-08-19 23:21:56 +00002352
Jordy Rose20589562011-08-24 22:39:09 +00002353 addVisitor(new CFRefLeakReportVisitor(sym, GCEnabled, Log));
Ted Kremenekc887d132009-04-29 18:50:19 +00002354}
2355
2356//===----------------------------------------------------------------------===//
2357// Main checker logic.
2358//===----------------------------------------------------------------------===//
2359
Ted Kremenekd593eb92009-11-25 22:17:44 +00002360namespace {
Jordy Rose910c4052011-09-02 06:44:22 +00002361class RetainCountChecker
Jordy Rose9c083b72011-08-24 18:56:32 +00002362 : public Checker< check::Bind,
Jordy Rose38f17d62011-08-23 19:01:07 +00002363 check::DeadSymbols,
Jordy Rose9c083b72011-08-24 18:56:32 +00002364 check::EndAnalysis,
Jordy Rose38f17d62011-08-23 19:01:07 +00002365 check::EndPath,
Jordy Rose67044292011-08-17 21:27:39 +00002366 check::PostStmt<BlockExpr>,
John McCallf85e1932011-06-15 23:02:42 +00002367 check::PostStmt<CastExpr>,
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002368 check::PostStmt<ObjCArrayLiteral>,
2369 check::PostStmt<ObjCDictionaryLiteral>,
Jordy Rose70fdbc32012-05-12 05:10:43 +00002370 check::PostStmt<ObjCBoxedExpr>,
Jordan Rosefe6a0112012-07-02 19:28:21 +00002371 check::PostCall,
Jordy Rosef53e8c72011-08-23 19:43:16 +00002372 check::PreStmt<ReturnStmt>,
Jordy Rose67044292011-08-17 21:27:39 +00002373 check::RegionChanges,
Jordy Rose76c506f2011-08-21 21:58:18 +00002374 eval::Assume,
2375 eval::Call > {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002376 mutable OwningPtr<CFRefBug> useAfterRelease, releaseNotOwned;
2377 mutable OwningPtr<CFRefBug> deallocGC, deallocNotOwned;
2378 mutable OwningPtr<CFRefBug> overAutorelease, returnNotOwnedForOwned;
2379 mutable OwningPtr<CFRefBug> leakWithinFunction, leakAtReturn;
2380 mutable OwningPtr<CFRefBug> leakWithinFunctionGC, leakAtReturnGC;
Jordy Rose38f17d62011-08-23 19:01:07 +00002381
2382 typedef llvm::DenseMap<SymbolRef, const SimpleProgramPointTag *> SymbolTagMap;
2383
2384 // This map is only used to ensure proper deletion of any allocated tags.
2385 mutable SymbolTagMap DeadSymbolTags;
2386
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002387 mutable OwningPtr<RetainSummaryManager> Summaries;
2388 mutable OwningPtr<RetainSummaryManager> SummariesGC;
Jordy Rose9c083b72011-08-24 18:56:32 +00002389 mutable SummaryLogTy SummaryLog;
2390 mutable bool ShouldResetSummaryLog;
2391
Jordy Rose2f9a66d2011-08-20 21:17:59 +00002392public:
Jordy Rose910c4052011-09-02 06:44:22 +00002393 RetainCountChecker() : ShouldResetSummaryLog(false) {}
Jordy Rose38f17d62011-08-23 19:01:07 +00002394
Jordy Rose910c4052011-09-02 06:44:22 +00002395 virtual ~RetainCountChecker() {
Jordy Rose38f17d62011-08-23 19:01:07 +00002396 DeleteContainerSeconds(DeadSymbolTags);
2397 }
2398
Jordy Rose9c083b72011-08-24 18:56:32 +00002399 void checkEndAnalysis(ExplodedGraph &G, BugReporter &BR,
2400 ExprEngine &Eng) const {
2401 // FIXME: This is a hack to make sure the summary log gets cleared between
2402 // analyses of different code bodies.
2403 //
2404 // Why is this necessary? Because a checker's lifetime is tied to a
2405 // translation unit, but an ExplodedGraph's lifetime is just a code body.
2406 // Once in a blue moon, a new ExplodedNode will have the same address as an
2407 // old one with an associated summary, and the bug report visitor gets very
2408 // confused. (To make things worse, the summary lifetime is currently also
2409 // tied to a code body, so we get a crash instead of incorrect results.)
Jordy Rose1ab51c72011-08-24 09:27:24 +00002410 //
2411 // Why is this a bad solution? Because if the lifetime of the ExplodedGraph
2412 // changes, things will start going wrong again. Really the lifetime of this
2413 // log needs to be tied to either the specific nodes in it or the entire
2414 // ExplodedGraph, not to a specific part of the code being analyzed.
2415 //
Jordy Rose9c083b72011-08-24 18:56:32 +00002416 // (Also, having stateful local data means that the same checker can't be
2417 // used from multiple threads, but a lot of checkers have incorrect
2418 // assumptions about that anyway. So that wasn't a priority at the time of
2419 // this fix.)
Jordy Rose1ab51c72011-08-24 09:27:24 +00002420 //
Jordy Rose9c083b72011-08-24 18:56:32 +00002421 // This happens at the end of analysis, but bug reports are emitted /after/
2422 // this point. So we can't just clear the summary log now. Instead, we mark
2423 // that the next time we access the summary log, it should be cleared.
2424
2425 // If we never reset the summary log during /this/ code body analysis,
2426 // there were no new summaries. There might still have been summaries from
2427 // the /last/ analysis, so clear them out to make sure the bug report
2428 // visitors don't get confused.
2429 if (ShouldResetSummaryLog)
2430 SummaryLog.clear();
2431
2432 ShouldResetSummaryLog = !SummaryLog.empty();
Jordy Rose1ab51c72011-08-24 09:27:24 +00002433 }
2434
Jordy Rose17a38e22011-09-02 05:55:19 +00002435 CFRefBug *getLeakWithinFunctionBug(const LangOptions &LOpts,
2436 bool GCEnabled) const {
2437 if (GCEnabled) {
Jordy Rosedb92bb62011-08-25 01:14:38 +00002438 if (!leakWithinFunctionGC)
Benjamin Kramerfacde172012-06-06 17:32:50 +00002439 leakWithinFunctionGC.reset(new Leak("Leak of object when using "
2440 "garbage collection"));
Jordy Rose17a38e22011-09-02 05:55:19 +00002441 return leakWithinFunctionGC.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002442 } else {
2443 if (!leakWithinFunction) {
Douglas Gregore289d812011-09-13 17:21:33 +00002444 if (LOpts.getGC() == LangOptions::HybridGC) {
Benjamin Kramerfacde172012-06-06 17:32:50 +00002445 leakWithinFunction.reset(new Leak("Leak of object when not using "
2446 "garbage collection (GC) in "
2447 "dual GC/non-GC code"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002448 } else {
Benjamin Kramerfacde172012-06-06 17:32:50 +00002449 leakWithinFunction.reset(new Leak("Leak"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002450 }
2451 }
Jordy Rose17a38e22011-09-02 05:55:19 +00002452 return leakWithinFunction.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002453 }
2454 }
2455
Jordy Rose17a38e22011-09-02 05:55:19 +00002456 CFRefBug *getLeakAtReturnBug(const LangOptions &LOpts, bool GCEnabled) const {
2457 if (GCEnabled) {
Jordy Rosedb92bb62011-08-25 01:14:38 +00002458 if (!leakAtReturnGC)
Benjamin Kramerfacde172012-06-06 17:32:50 +00002459 leakAtReturnGC.reset(new Leak("Leak of returned object when using "
2460 "garbage collection"));
Jordy Rose17a38e22011-09-02 05:55:19 +00002461 return leakAtReturnGC.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002462 } else {
2463 if (!leakAtReturn) {
Douglas Gregore289d812011-09-13 17:21:33 +00002464 if (LOpts.getGC() == LangOptions::HybridGC) {
Benjamin Kramerfacde172012-06-06 17:32:50 +00002465 leakAtReturn.reset(new Leak("Leak of returned object when not using "
2466 "garbage collection (GC) in dual "
2467 "GC/non-GC code"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002468 } else {
Benjamin Kramerfacde172012-06-06 17:32:50 +00002469 leakAtReturn.reset(new Leak("Leak of returned object"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002470 }
2471 }
Jordy Rose17a38e22011-09-02 05:55:19 +00002472 return leakAtReturn.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002473 }
2474 }
2475
Jordy Rose17a38e22011-09-02 05:55:19 +00002476 RetainSummaryManager &getSummaryManager(ASTContext &Ctx,
2477 bool GCEnabled) const {
2478 // FIXME: We don't support ARC being turned on and off during one analysis.
2479 // (nor, for that matter, do we support changing ASTContexts)
David Blaikie4e4d0842012-03-11 07:00:24 +00002480 bool ARCEnabled = (bool)Ctx.getLangOpts().ObjCAutoRefCount;
Jordy Rose17a38e22011-09-02 05:55:19 +00002481 if (GCEnabled) {
2482 if (!SummariesGC)
Jordy Roseb6cfc092011-08-25 00:10:37 +00002483 SummariesGC.reset(new RetainSummaryManager(Ctx, true, ARCEnabled));
Jordy Rose17a38e22011-09-02 05:55:19 +00002484 else
2485 assert(SummariesGC->isARCEnabled() == ARCEnabled);
Jordy Roseb6cfc092011-08-25 00:10:37 +00002486 return *SummariesGC;
2487 } else {
Jordy Rose17a38e22011-09-02 05:55:19 +00002488 if (!Summaries)
Jordy Roseb6cfc092011-08-25 00:10:37 +00002489 Summaries.reset(new RetainSummaryManager(Ctx, false, ARCEnabled));
Jordy Rose17a38e22011-09-02 05:55:19 +00002490 else
2491 assert(Summaries->isARCEnabled() == ARCEnabled);
Jordy Roseb6cfc092011-08-25 00:10:37 +00002492 return *Summaries;
2493 }
2494 }
2495
Jordy Rose17a38e22011-09-02 05:55:19 +00002496 RetainSummaryManager &getSummaryManager(CheckerContext &C) const {
2497 return getSummaryManager(C.getASTContext(), C.isObjCGCEnabled());
2498 }
2499
Ted Kremenek8bef8232012-01-26 21:29:00 +00002500 void printState(raw_ostream &Out, ProgramStateRef State,
Jordy Rosedbd658e2011-08-28 19:11:56 +00002501 const char *NL, const char *Sep) const;
2502
Anna Zaks390909c2011-10-06 00:43:15 +00002503 void checkBind(SVal loc, SVal val, const Stmt *S, CheckerContext &C) const;
Jordy Roseab027fd2011-08-20 21:16:58 +00002504 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
2505 void checkPostStmt(const CastExpr *CE, CheckerContext &C) const;
John McCallf85e1932011-06-15 23:02:42 +00002506
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002507 void checkPostStmt(const ObjCArrayLiteral *AL, CheckerContext &C) const;
2508 void checkPostStmt(const ObjCDictionaryLiteral *DL, CheckerContext &C) const;
Jordy Rose70fdbc32012-05-12 05:10:43 +00002509 void checkPostStmt(const ObjCBoxedExpr *BE, CheckerContext &C) const;
2510
Jordan Rosefe6a0112012-07-02 19:28:21 +00002511 void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002512
Jordan Rose4531b7d2012-07-02 19:27:43 +00002513 void checkSummary(const RetainSummary &Summ, const CallEvent &Call,
Jordy Rosee38dd952011-08-28 05:16:28 +00002514 CheckerContext &C) const;
Jordy Rose294396b2011-08-22 23:48:23 +00002515
Anna Zaks554067f2012-08-29 23:23:43 +00002516 void processSummaryOfInlined(const RetainSummary &Summ,
2517 const CallEvent &Call,
2518 CheckerContext &C) const;
2519
Jordy Rose76c506f2011-08-21 21:58:18 +00002520 bool evalCall(const CallExpr *CE, CheckerContext &C) const;
2521
Ted Kremenek8bef8232012-01-26 21:29:00 +00002522 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Jordy Roseab027fd2011-08-20 21:16:58 +00002523 bool Assumption) const;
Jordy Rose67044292011-08-17 21:27:39 +00002524
Ted Kremenek8bef8232012-01-26 21:29:00 +00002525 ProgramStateRef
2526 checkRegionChanges(ProgramStateRef state,
Jordy Rose537716a2011-08-27 22:51:26 +00002527 const StoreManager::InvalidatedSymbols *invalidated,
2528 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00002529 ArrayRef<const MemRegion *> Regions,
Jordan Rose740d4902012-07-02 19:27:35 +00002530 const CallEvent *Call) const;
Jordy Roseab027fd2011-08-20 21:16:58 +00002531
Ted Kremenek8bef8232012-01-26 21:29:00 +00002532 bool wantsRegionChangeUpdate(ProgramStateRef state) const {
Jordy Rose2f9a66d2011-08-20 21:17:59 +00002533 return true;
Jordy Roseab027fd2011-08-20 21:16:58 +00002534 }
Jordy Rose294396b2011-08-22 23:48:23 +00002535
Jordy Rosef53e8c72011-08-23 19:43:16 +00002536 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
2537 void checkReturnWithRetEffect(const ReturnStmt *S, CheckerContext &C,
2538 ExplodedNode *Pred, RetEffect RE, RefVal X,
Ted Kremenek8bef8232012-01-26 21:29:00 +00002539 SymbolRef Sym, ProgramStateRef state) const;
Jordy Rosef53e8c72011-08-23 19:43:16 +00002540
Jordy Rose38f17d62011-08-23 19:01:07 +00002541 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Anna Zaksaf498a22011-10-25 19:56:48 +00002542 void checkEndPath(CheckerContext &C) const;
Jordy Rose38f17d62011-08-23 19:01:07 +00002543
Ted Kremenek8bef8232012-01-26 21:29:00 +00002544 ProgramStateRef updateSymbol(ProgramStateRef state, SymbolRef sym,
Anna Zaks554067f2012-08-29 23:23:43 +00002545 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
2546 CheckerContext &C) const;
Jordy Rosee0a5d322011-08-23 20:27:16 +00002547
Ted Kremenek8bef8232012-01-26 21:29:00 +00002548 void processNonLeakError(ProgramStateRef St, SourceRange ErrorRange,
Jordy Rose294396b2011-08-22 23:48:23 +00002549 RefVal::Kind ErrorKind, SymbolRef Sym,
2550 CheckerContext &C) const;
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002551
2552 void processObjCLiterals(CheckerContext &C, const Expr *Ex) const;
Jordy Rose294396b2011-08-22 23:48:23 +00002553
Jordy Rose38f17d62011-08-23 19:01:07 +00002554 const ProgramPointTag *getDeadSymbolTag(SymbolRef sym) const;
2555
Ted Kremenek8bef8232012-01-26 21:29:00 +00002556 ProgramStateRef handleSymbolDeath(ProgramStateRef state,
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002557 SymbolRef sid, RefVal V,
2558 SmallVectorImpl<SymbolRef> &Leaked) const;
Jordy Rose38f17d62011-08-23 19:01:07 +00002559
Ted Kremenek8bef8232012-01-26 21:29:00 +00002560 std::pair<ExplodedNode *, ProgramStateRef >
Jordan Rose2bce86c2012-08-18 00:30:16 +00002561 handleAutoreleaseCounts(ProgramStateRef state, ExplodedNode *Pred,
2562 const ProgramPointTag *Tag, CheckerContext &Ctx,
2563 SymbolRef Sym, RefVal V) const;
Jordy Rose8d228632011-08-23 20:07:14 +00002564
Ted Kremenek8bef8232012-01-26 21:29:00 +00002565 ExplodedNode *processLeaks(ProgramStateRef state,
Jordy Rose38f17d62011-08-23 19:01:07 +00002566 SmallVectorImpl<SymbolRef> &Leaked,
Anna Zaks6a93bd52011-10-25 19:57:11 +00002567 CheckerContext &Ctx,
Jordy Rose38f17d62011-08-23 19:01:07 +00002568 ExplodedNode *Pred = 0) const;
Ted Kremenekd593eb92009-11-25 22:17:44 +00002569};
2570} // end anonymous namespace
2571
Jordy Rose67044292011-08-17 21:27:39 +00002572namespace {
2573class StopTrackingCallback : public SymbolVisitor {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002574 ProgramStateRef state;
Jordy Rose67044292011-08-17 21:27:39 +00002575public:
Ted Kremenek8bef8232012-01-26 21:29:00 +00002576 StopTrackingCallback(ProgramStateRef st) : state(st) {}
2577 ProgramStateRef getState() const { return state; }
Jordy Rose67044292011-08-17 21:27:39 +00002578
2579 bool VisitSymbol(SymbolRef sym) {
2580 state = state->remove<RefBindings>(sym);
2581 return true;
2582 }
2583};
2584} // end anonymous namespace
2585
Jordy Rose910c4052011-09-02 06:44:22 +00002586//===----------------------------------------------------------------------===//
2587// Handle statements that may have an effect on refcounts.
2588//===----------------------------------------------------------------------===//
Jordy Rose67044292011-08-17 21:27:39 +00002589
Jordy Rose910c4052011-09-02 06:44:22 +00002590void RetainCountChecker::checkPostStmt(const BlockExpr *BE,
2591 CheckerContext &C) const {
Jordy Rose67044292011-08-17 21:27:39 +00002592
Jordy Rose910c4052011-09-02 06:44:22 +00002593 // Scan the BlockDecRefExprs for any object the retain count checker
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002594 // may be tracking.
John McCall469a1eb2011-02-02 13:00:07 +00002595 if (!BE->getBlockDecl()->hasCaptures())
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002596 return;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002597
Ted Kremenek8bef8232012-01-26 21:29:00 +00002598 ProgramStateRef state = C.getState();
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002599 const BlockDataRegion *R =
Ted Kremenek5eca4822012-01-06 22:09:28 +00002600 cast<BlockDataRegion>(state->getSVal(BE,
2601 C.getLocationContext()).getAsRegion());
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002602
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002603 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
2604 E = R->referenced_vars_end();
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002605
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002606 if (I == E)
2607 return;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002608
Ted Kremenek67d12872009-12-07 22:05:27 +00002609 // FIXME: For now we invalidate the tracking of all symbols passed to blocks
2610 // via captured variables, even though captured variables result in a copy
2611 // and in implicit increment/decrement of a retain count.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002612 SmallVector<const MemRegion*, 10> Regions;
Anna Zaks39ac1872011-10-26 21:06:44 +00002613 const LocationContext *LC = C.getLocationContext();
Ted Kremenekc8413fd2010-12-02 07:49:45 +00002614 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002615
Ted Kremenek67d12872009-12-07 22:05:27 +00002616 for ( ; I != E; ++I) {
2617 const VarRegion *VR = *I;
2618 if (VR->getSuperRegion() == R) {
2619 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2620 }
2621 Regions.push_back(VR);
2622 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002623
Ted Kremenek67d12872009-12-07 22:05:27 +00002624 state =
2625 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
2626 Regions.data() + Regions.size()).getState();
Anna Zaks0bd6b112011-10-26 21:06:34 +00002627 C.addTransition(state);
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002628}
2629
Jordy Rose910c4052011-09-02 06:44:22 +00002630void RetainCountChecker::checkPostStmt(const CastExpr *CE,
2631 CheckerContext &C) const {
John McCallf85e1932011-06-15 23:02:42 +00002632 const ObjCBridgedCastExpr *BE = dyn_cast<ObjCBridgedCastExpr>(CE);
2633 if (!BE)
2634 return;
2635
John McCall71c482c2011-06-17 06:50:50 +00002636 ArgEffect AE = IncRef;
John McCallf85e1932011-06-15 23:02:42 +00002637
2638 switch (BE->getBridgeKind()) {
2639 case clang::OBC_Bridge:
2640 // Do nothing.
2641 return;
2642 case clang::OBC_BridgeRetained:
2643 AE = IncRef;
2644 break;
2645 case clang::OBC_BridgeTransfer:
2646 AE = DecRefBridgedTransfered;
2647 break;
2648 }
2649
Ted Kremenek8bef8232012-01-26 21:29:00 +00002650 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00002651 SymbolRef Sym = state->getSVal(CE, C.getLocationContext()).getAsLocSymbol();
John McCallf85e1932011-06-15 23:02:42 +00002652 if (!Sym)
2653 return;
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002654 const RefVal* T = getRefBinding(state, Sym);
John McCallf85e1932011-06-15 23:02:42 +00002655 if (!T)
2656 return;
2657
John McCallf85e1932011-06-15 23:02:42 +00002658 RefVal::Kind hasErr = (RefVal::Kind) 0;
Jordy Rose17a38e22011-09-02 05:55:19 +00002659 state = updateSymbol(state, Sym, *T, AE, hasErr, C);
John McCallf85e1932011-06-15 23:02:42 +00002660
2661 if (hasErr) {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002662 // FIXME: If we get an error during a bridge cast, should we report it?
2663 // Should we assert that there is no error?
John McCallf85e1932011-06-15 23:02:42 +00002664 return;
2665 }
2666
Anna Zaks0bd6b112011-10-26 21:06:34 +00002667 C.addTransition(state);
John McCallf85e1932011-06-15 23:02:42 +00002668}
2669
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002670void RetainCountChecker::processObjCLiterals(CheckerContext &C,
2671 const Expr *Ex) const {
2672 ProgramStateRef state = C.getState();
2673 const ExplodedNode *pred = C.getPredecessor();
2674 for (Stmt::const_child_iterator it = Ex->child_begin(), et = Ex->child_end() ;
2675 it != et ; ++it) {
2676 const Stmt *child = *it;
2677 SVal V = state->getSVal(child, pred->getLocationContext());
2678 if (SymbolRef sym = V.getAsSymbol())
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002679 if (const RefVal* T = getRefBinding(state, sym)) {
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002680 RefVal::Kind hasErr = (RefVal::Kind) 0;
2681 state = updateSymbol(state, sym, *T, MayEscape, hasErr, C);
2682 if (hasErr) {
2683 processNonLeakError(state, child->getSourceRange(), hasErr, sym, C);
2684 return;
2685 }
2686 }
2687 }
2688
2689 // Return the object as autoreleased.
2690 // RetEffect RE = RetEffect::MakeNotOwned(RetEffect::ObjC);
2691 if (SymbolRef sym =
2692 state->getSVal(Ex, pred->getLocationContext()).getAsSymbol()) {
2693 QualType ResultTy = Ex->getType();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002694 state = setRefBinding(state, sym,
2695 RefVal::makeNotOwned(RetEffect::ObjC, ResultTy));
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002696 }
2697
2698 C.addTransition(state);
2699}
2700
2701void RetainCountChecker::checkPostStmt(const ObjCArrayLiteral *AL,
2702 CheckerContext &C) const {
2703 // Apply the 'MayEscape' to all values.
2704 processObjCLiterals(C, AL);
2705}
2706
2707void RetainCountChecker::checkPostStmt(const ObjCDictionaryLiteral *DL,
2708 CheckerContext &C) const {
2709 // Apply the 'MayEscape' to all keys and values.
2710 processObjCLiterals(C, DL);
2711}
2712
Jordy Rose70fdbc32012-05-12 05:10:43 +00002713void RetainCountChecker::checkPostStmt(const ObjCBoxedExpr *Ex,
2714 CheckerContext &C) const {
2715 const ExplodedNode *Pred = C.getPredecessor();
2716 const LocationContext *LCtx = Pred->getLocationContext();
2717 ProgramStateRef State = Pred->getState();
2718
2719 if (SymbolRef Sym = State->getSVal(Ex, LCtx).getAsSymbol()) {
2720 QualType ResultTy = Ex->getType();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002721 State = setRefBinding(State, Sym,
2722 RefVal::makeNotOwned(RetEffect::ObjC, ResultTy));
Jordy Rose70fdbc32012-05-12 05:10:43 +00002723 }
2724
2725 C.addTransition(State);
2726}
2727
Jordan Rosefe6a0112012-07-02 19:28:21 +00002728void RetainCountChecker::checkPostCall(const CallEvent &Call,
2729 CheckerContext &C) const {
Jordan Rosefe6a0112012-07-02 19:28:21 +00002730 RetainSummaryManager &Summaries = getSummaryManager(C);
2731 const RetainSummary *Summ = Summaries.getSummary(Call, C.getState());
Anna Zaks554067f2012-08-29 23:23:43 +00002732
2733 if (C.wasInlined) {
2734 processSummaryOfInlined(*Summ, Call, C);
2735 return;
2736 }
Jordan Rosefe6a0112012-07-02 19:28:21 +00002737 checkSummary(*Summ, Call, C);
Jordy Rose294396b2011-08-22 23:48:23 +00002738}
2739
Jordy Rose910c4052011-09-02 06:44:22 +00002740/// GetReturnType - Used to get the return type of a message expression or
2741/// function call with the intention of affixing that type to a tracked symbol.
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +00002742/// While the return type can be queried directly from RetEx, when
Jordy Rose910c4052011-09-02 06:44:22 +00002743/// invoking class methods we augment to the return type to be that of
2744/// a pointer to the class (as opposed it just being id).
2745// FIXME: We may be able to do this with related result types instead.
2746// This function is probably overestimating.
2747static QualType GetReturnType(const Expr *RetE, ASTContext &Ctx) {
2748 QualType RetTy = RetE->getType();
2749 // If RetE is not a message expression just return its type.
2750 // If RetE is a message expression, return its types if it is something
2751 /// more specific than id.
2752 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RetE))
2753 if (const ObjCObjectPointerType *PT = RetTy->getAs<ObjCObjectPointerType>())
2754 if (PT->isObjCQualifiedIdType() || PT->isObjCIdType() ||
2755 PT->isObjCClassType()) {
2756 // At this point we know the return type of the message expression is
2757 // id, id<...>, or Class. If we have an ObjCInterfaceDecl, we know this
2758 // is a call to a class method whose type we can resolve. In such
2759 // cases, promote the return type to XXX* (where XXX is the class).
2760 const ObjCInterfaceDecl *D = ME->getReceiverInterface();
2761 return !D ? RetTy :
2762 Ctx.getObjCObjectPointerType(Ctx.getObjCInterfaceType(D));
2763 }
2764
2765 return RetTy;
2766}
2767
Anna Zaks554067f2012-08-29 23:23:43 +00002768// We don't always get the exact modeling of the function with regards to the
2769// retain count checker even when the function is inlined. For example, we need
2770// to stop tracking the symbols which were marked with StopTrackingHard.
2771void RetainCountChecker::processSummaryOfInlined(const RetainSummary &Summ,
2772 const CallEvent &CallOrMsg,
2773 CheckerContext &C) const {
2774 ProgramStateRef state = C.getState();
2775
2776 // Evaluate the effect of the arguments.
2777 for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
2778 if (Summ.getArg(idx) == StopTrackingHard) {
2779 SVal V = CallOrMsg.getArgSVal(idx);
2780 if (SymbolRef Sym = V.getAsLocSymbol()) {
2781 state = removeRefBinding(state, Sym);
2782 }
2783 }
2784 }
2785
2786 // Evaluate the effect on the message receiver.
2787 const ObjCMethodCall *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg);
2788 if (MsgInvocation) {
2789 if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
2790 if (Summ.getReceiverEffect() == StopTrackingHard) {
2791 state = removeRefBinding(state, Sym);
2792 }
2793 }
2794 }
2795
2796 // Consult the summary for the return value.
2797 RetEffect RE = Summ.getRetEffect();
2798 if (RE.getKind() == RetEffect::NoRetHard) {
2799 SymbolRef Sym = state->getSVal(CallOrMsg.getOriginExpr(),
2800 C.getLocationContext()).getAsSymbol();
2801 if (Sym)
2802 state = removeRefBinding(state, Sym);
2803 }
2804
2805 C.addTransition(state);
2806}
2807
Jordy Rose910c4052011-09-02 06:44:22 +00002808void RetainCountChecker::checkSummary(const RetainSummary &Summ,
Jordan Rose4531b7d2012-07-02 19:27:43 +00002809 const CallEvent &CallOrMsg,
Jordy Rose910c4052011-09-02 06:44:22 +00002810 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002811 ProgramStateRef state = C.getState();
Jordy Rose294396b2011-08-22 23:48:23 +00002812
2813 // Evaluate the effect of the arguments.
2814 RefVal::Kind hasErr = (RefVal::Kind) 0;
2815 SourceRange ErrorRange;
2816 SymbolRef ErrorSym = 0;
2817
2818 for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
Jordy Rose537716a2011-08-27 22:51:26 +00002819 SVal V = CallOrMsg.getArgSVal(idx);
Jordy Rose294396b2011-08-22 23:48:23 +00002820
2821 if (SymbolRef Sym = V.getAsLocSymbol()) {
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002822 if (const RefVal *T = getRefBinding(state, Sym)) {
Jordy Rose17a38e22011-09-02 05:55:19 +00002823 state = updateSymbol(state, Sym, *T, Summ.getArg(idx), hasErr, C);
Jordy Rose294396b2011-08-22 23:48:23 +00002824 if (hasErr) {
2825 ErrorRange = CallOrMsg.getArgSourceRange(idx);
2826 ErrorSym = Sym;
2827 break;
2828 }
2829 }
2830 }
2831 }
2832
2833 // Evaluate the effect on the message receiver.
2834 bool ReceiverIsTracked = false;
Jordan Rose4531b7d2012-07-02 19:27:43 +00002835 if (!hasErr) {
Jordan Rosecde8cdb2012-07-02 19:27:56 +00002836 const ObjCMethodCall *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg);
Jordan Rose4531b7d2012-07-02 19:27:43 +00002837 if (MsgInvocation) {
2838 if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002839 if (const RefVal *T = getRefBinding(state, Sym)) {
Jordan Rose4531b7d2012-07-02 19:27:43 +00002840 ReceiverIsTracked = true;
2841 state = updateSymbol(state, Sym, *T, Summ.getReceiverEffect(),
Anna Zaks554067f2012-08-29 23:23:43 +00002842 hasErr, C);
Jordan Rose4531b7d2012-07-02 19:27:43 +00002843 if (hasErr) {
Jordan Rose8919e682012-07-18 21:59:51 +00002844 ErrorRange = MsgInvocation->getOriginExpr()->getReceiverRange();
Jordan Rose4531b7d2012-07-02 19:27:43 +00002845 ErrorSym = Sym;
2846 }
Jordy Rose294396b2011-08-22 23:48:23 +00002847 }
2848 }
2849 }
2850 }
2851
2852 // Process any errors.
2853 if (hasErr) {
2854 processNonLeakError(state, ErrorRange, hasErr, ErrorSym, C);
2855 return;
2856 }
2857
2858 // Consult the summary for the return value.
2859 RetEffect RE = Summ.getRetEffect();
Ted Kremenek5a8fc882012-10-12 22:56:40 +00002860 assert(CallOrMsg.getOriginExpr());
Jordy Rose294396b2011-08-22 23:48:23 +00002861
2862 if (RE.getKind() == RetEffect::OwnedWhenTrackedReceiver) {
Jordy Roseb6cfc092011-08-25 00:10:37 +00002863 if (ReceiverIsTracked)
Jordy Rose17a38e22011-09-02 05:55:19 +00002864 RE = getSummaryManager(C).getObjAllocRetEffect();
Jordy Roseb6cfc092011-08-25 00:10:37 +00002865 else
Jordy Rose294396b2011-08-22 23:48:23 +00002866 RE = RetEffect::MakeNoRet();
2867 }
2868
2869 switch (RE.getKind()) {
2870 default:
David Blaikie7530c032012-01-17 06:56:22 +00002871 llvm_unreachable("Unhandled RetEffect.");
Jordy Rose294396b2011-08-22 23:48:23 +00002872
2873 case RetEffect::NoRet:
Anna Zaks554067f2012-08-29 23:23:43 +00002874 case RetEffect::NoRetHard:
Jordy Rose294396b2011-08-22 23:48:23 +00002875 // No work necessary.
2876 break;
2877
2878 case RetEffect::OwnedAllocatedSymbol:
2879 case RetEffect::OwnedSymbol: {
Ted Kremenek5eca4822012-01-06 22:09:28 +00002880 SymbolRef Sym = state->getSVal(CallOrMsg.getOriginExpr(),
2881 C.getLocationContext()).getAsSymbol();
Jordy Rose294396b2011-08-22 23:48:23 +00002882 if (!Sym)
2883 break;
2884
Jordan Rose4531b7d2012-07-02 19:27:43 +00002885 // Use the result type from the CallEvent as it automatically adjusts
Jordy Rose294396b2011-08-22 23:48:23 +00002886 // for methods/functions that return references.
Jordan Rose4531b7d2012-07-02 19:27:43 +00002887 QualType ResultTy = CallOrMsg.getResultType();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002888 state = setRefBinding(state, Sym, RefVal::makeOwned(RE.getObjKind(),
2889 ResultTy));
Jordy Rose294396b2011-08-22 23:48:23 +00002890
2891 // FIXME: Add a flag to the checker where allocations are assumed to
Anna Zaksc6ba23f2012-08-14 15:39:13 +00002892 // *not* fail.
Jordy Rose294396b2011-08-22 23:48:23 +00002893 break;
2894 }
2895
2896 case RetEffect::GCNotOwnedSymbol:
2897 case RetEffect::ARCNotOwnedSymbol:
2898 case RetEffect::NotOwnedSymbol: {
2899 const Expr *Ex = CallOrMsg.getOriginExpr();
Ted Kremenek5eca4822012-01-06 22:09:28 +00002900 SymbolRef Sym = state->getSVal(Ex, C.getLocationContext()).getAsSymbol();
Jordy Rose294396b2011-08-22 23:48:23 +00002901 if (!Sym)
2902 break;
2903
2904 // Use GetReturnType in order to give [NSFoo alloc] the type NSFoo *.
2905 QualType ResultTy = GetReturnType(Ex, C.getASTContext());
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002906 state = setRefBinding(state, Sym, RefVal::makeNotOwned(RE.getObjKind(),
2907 ResultTy));
Jordy Rose294396b2011-08-22 23:48:23 +00002908 break;
2909 }
2910 }
2911
2912 // This check is actually necessary; otherwise the statement builder thinks
2913 // we've hit a previously-found path.
2914 // Normally addTransition takes care of this, but we want the node pointer.
2915 ExplodedNode *NewNode;
2916 if (state == C.getState()) {
2917 NewNode = C.getPredecessor();
2918 } else {
Anna Zaks0bd6b112011-10-26 21:06:34 +00002919 NewNode = C.addTransition(state);
Jordy Rose294396b2011-08-22 23:48:23 +00002920 }
2921
Jordy Rose9c083b72011-08-24 18:56:32 +00002922 // Annotate the node with summary we used.
2923 if (NewNode) {
2924 // FIXME: This is ugly. See checkEndAnalysis for why it's necessary.
2925 if (ShouldResetSummaryLog) {
2926 SummaryLog.clear();
2927 ShouldResetSummaryLog = false;
2928 }
Jordy Roseec9ef852011-08-23 20:55:48 +00002929 SummaryLog[NewNode] = &Summ;
Jordy Rose9c083b72011-08-24 18:56:32 +00002930 }
Jordy Rose294396b2011-08-22 23:48:23 +00002931}
2932
Jordy Rosee0a5d322011-08-23 20:27:16 +00002933
Ted Kremenek8bef8232012-01-26 21:29:00 +00002934ProgramStateRef
2935RetainCountChecker::updateSymbol(ProgramStateRef state, SymbolRef sym,
Jordy Rose910c4052011-09-02 06:44:22 +00002936 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
2937 CheckerContext &C) const {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002938 // In GC mode [... release] and [... retain] do nothing.
Jordy Rose910c4052011-09-02 06:44:22 +00002939 // In ARC mode they shouldn't exist at all, but we just ignore them.
Jordy Rose17a38e22011-09-02 05:55:19 +00002940 bool IgnoreRetainMsg = C.isObjCGCEnabled();
2941 if (!IgnoreRetainMsg)
David Blaikie4e4d0842012-03-11 07:00:24 +00002942 IgnoreRetainMsg = (bool)C.getASTContext().getLangOpts().ObjCAutoRefCount;
Jordy Rose17a38e22011-09-02 05:55:19 +00002943
Jordy Rosee0a5d322011-08-23 20:27:16 +00002944 switch (E) {
Jordan Rose4531b7d2012-07-02 19:27:43 +00002945 default:
2946 break;
2947 case IncRefMsg:
2948 E = IgnoreRetainMsg ? DoNothing : IncRef;
2949 break;
2950 case DecRefMsg:
2951 E = IgnoreRetainMsg ? DoNothing : DecRef;
2952 break;
Anna Zaks554067f2012-08-29 23:23:43 +00002953 case DecRefMsgAndStopTrackingHard:
2954 E = IgnoreRetainMsg ? StopTracking : DecRefAndStopTrackingHard;
Jordan Rose4531b7d2012-07-02 19:27:43 +00002955 break;
2956 case MakeCollectable:
2957 E = C.isObjCGCEnabled() ? DecRef : DoNothing;
2958 break;
2959 case NewAutoreleasePool:
2960 E = C.isObjCGCEnabled() ? DoNothing : NewAutoreleasePool;
2961 break;
Jordy Rosee0a5d322011-08-23 20:27:16 +00002962 }
2963
2964 // Handle all use-after-releases.
Jordy Rose17a38e22011-09-02 05:55:19 +00002965 if (!C.isObjCGCEnabled() && V.getKind() == RefVal::Released) {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002966 V = V ^ RefVal::ErrorUseAfterRelease;
2967 hasErr = V.getKind();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002968 return setRefBinding(state, sym, V);
Jordy Rosee0a5d322011-08-23 20:27:16 +00002969 }
2970
2971 switch (E) {
2972 case DecRefMsg:
2973 case IncRefMsg:
2974 case MakeCollectable:
Anna Zaks554067f2012-08-29 23:23:43 +00002975 case DecRefMsgAndStopTrackingHard:
Jordy Rosee0a5d322011-08-23 20:27:16 +00002976 llvm_unreachable("DecRefMsg/IncRefMsg/MakeCollectable already converted");
Jordy Rosee0a5d322011-08-23 20:27:16 +00002977
2978 case Dealloc:
2979 // Any use of -dealloc in GC is *bad*.
Jordy Rose17a38e22011-09-02 05:55:19 +00002980 if (C.isObjCGCEnabled()) {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002981 V = V ^ RefVal::ErrorDeallocGC;
2982 hasErr = V.getKind();
2983 break;
2984 }
2985
2986 switch (V.getKind()) {
2987 default:
2988 llvm_unreachable("Invalid RefVal state for an explicit dealloc.");
Jordy Rosee0a5d322011-08-23 20:27:16 +00002989 case RefVal::Owned:
2990 // The object immediately transitions to the released state.
2991 V = V ^ RefVal::Released;
2992 V.clearCounts();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00002993 return setRefBinding(state, sym, V);
Jordy Rosee0a5d322011-08-23 20:27:16 +00002994 case RefVal::NotOwned:
2995 V = V ^ RefVal::ErrorDeallocNotOwned;
2996 hasErr = V.getKind();
2997 break;
2998 }
2999 break;
3000
3001 case NewAutoreleasePool:
Jordy Rose17a38e22011-09-02 05:55:19 +00003002 assert(!C.isObjCGCEnabled());
Anna Zaksc95bb762012-08-14 00:36:17 +00003003 return state;
Jordy Rosee0a5d322011-08-23 20:27:16 +00003004
3005 case MayEscape:
3006 if (V.getKind() == RefVal::Owned) {
3007 V = V ^ RefVal::NotOwned;
3008 break;
3009 }
3010
3011 // Fall-through.
3012
Jordy Rosee0a5d322011-08-23 20:27:16 +00003013 case DoNothing:
3014 return state;
3015
3016 case Autorelease:
Jordy Rose17a38e22011-09-02 05:55:19 +00003017 if (C.isObjCGCEnabled())
Jordy Rosee0a5d322011-08-23 20:27:16 +00003018 return state;
Jordy Rosee0a5d322011-08-23 20:27:16 +00003019 // Update the autorelease counts.
Jordy Rosee0a5d322011-08-23 20:27:16 +00003020 V = V.autorelease();
3021 break;
3022
3023 case StopTracking:
Anna Zaks554067f2012-08-29 23:23:43 +00003024 case StopTrackingHard:
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003025 return removeRefBinding(state, sym);
Jordy Rosee0a5d322011-08-23 20:27:16 +00003026
3027 case IncRef:
3028 switch (V.getKind()) {
3029 default:
3030 llvm_unreachable("Invalid RefVal state for a retain.");
Jordy Rosee0a5d322011-08-23 20:27:16 +00003031 case RefVal::Owned:
3032 case RefVal::NotOwned:
3033 V = V + 1;
3034 break;
3035 case RefVal::Released:
3036 // Non-GC cases are handled above.
Jordy Rose17a38e22011-09-02 05:55:19 +00003037 assert(C.isObjCGCEnabled());
Jordy Rosee0a5d322011-08-23 20:27:16 +00003038 V = (V ^ RefVal::Owned) + 1;
3039 break;
3040 }
3041 break;
3042
Jordy Rosee0a5d322011-08-23 20:27:16 +00003043 case DecRef:
3044 case DecRefBridgedTransfered:
Anna Zaks554067f2012-08-29 23:23:43 +00003045 case DecRefAndStopTrackingHard:
Jordy Rosee0a5d322011-08-23 20:27:16 +00003046 switch (V.getKind()) {
3047 default:
3048 // case 'RefVal::Released' handled above.
3049 llvm_unreachable("Invalid RefVal state for a release.");
Jordy Rosee0a5d322011-08-23 20:27:16 +00003050
3051 case RefVal::Owned:
3052 assert(V.getCount() > 0);
3053 if (V.getCount() == 1)
3054 V = V ^ (E == DecRefBridgedTransfered ?
3055 RefVal::NotOwned : RefVal::Released);
Anna Zaks554067f2012-08-29 23:23:43 +00003056 else if (E == DecRefAndStopTrackingHard)
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003057 return removeRefBinding(state, sym);
Jordan Rose4531b7d2012-07-02 19:27:43 +00003058
Jordy Rosee0a5d322011-08-23 20:27:16 +00003059 V = V - 1;
3060 break;
3061
3062 case RefVal::NotOwned:
Jordan Rose4531b7d2012-07-02 19:27:43 +00003063 if (V.getCount() > 0) {
Anna Zaks554067f2012-08-29 23:23:43 +00003064 if (E == DecRefAndStopTrackingHard)
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003065 return removeRefBinding(state, sym);
Jordy Rosee0a5d322011-08-23 20:27:16 +00003066 V = V - 1;
Jordan Rose4531b7d2012-07-02 19:27:43 +00003067 } else {
Jordy Rosee0a5d322011-08-23 20:27:16 +00003068 V = V ^ RefVal::ErrorReleaseNotOwned;
3069 hasErr = V.getKind();
3070 }
3071 break;
3072
3073 case RefVal::Released:
3074 // Non-GC cases are handled above.
Jordy Rose17a38e22011-09-02 05:55:19 +00003075 assert(C.isObjCGCEnabled());
Jordy Rosee0a5d322011-08-23 20:27:16 +00003076 V = V ^ RefVal::ErrorUseAfterRelease;
3077 hasErr = V.getKind();
3078 break;
3079 }
3080 break;
3081 }
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003082 return setRefBinding(state, sym, V);
Jordy Rosee0a5d322011-08-23 20:27:16 +00003083}
3084
Ted Kremenek8bef8232012-01-26 21:29:00 +00003085void RetainCountChecker::processNonLeakError(ProgramStateRef St,
Jordy Rose910c4052011-09-02 06:44:22 +00003086 SourceRange ErrorRange,
3087 RefVal::Kind ErrorKind,
3088 SymbolRef Sym,
3089 CheckerContext &C) const {
Jordy Rose294396b2011-08-22 23:48:23 +00003090 ExplodedNode *N = C.generateSink(St);
3091 if (!N)
3092 return;
3093
Jordy Rose294396b2011-08-22 23:48:23 +00003094 CFRefBug *BT;
3095 switch (ErrorKind) {
3096 default:
3097 llvm_unreachable("Unhandled error.");
Jordy Rose294396b2011-08-22 23:48:23 +00003098 case RefVal::ErrorUseAfterRelease:
Jordy Rosed6334e12011-08-25 00:34:03 +00003099 if (!useAfterRelease)
3100 useAfterRelease.reset(new UseAfterRelease());
3101 BT = &*useAfterRelease;
Jordy Rose294396b2011-08-22 23:48:23 +00003102 break;
3103 case RefVal::ErrorReleaseNotOwned:
Jordy Rosed6334e12011-08-25 00:34:03 +00003104 if (!releaseNotOwned)
3105 releaseNotOwned.reset(new BadRelease());
3106 BT = &*releaseNotOwned;
Jordy Rose294396b2011-08-22 23:48:23 +00003107 break;
3108 case RefVal::ErrorDeallocGC:
Jordy Rosed6334e12011-08-25 00:34:03 +00003109 if (!deallocGC)
3110 deallocGC.reset(new DeallocGC());
3111 BT = &*deallocGC;
Jordy Rose294396b2011-08-22 23:48:23 +00003112 break;
3113 case RefVal::ErrorDeallocNotOwned:
Jordy Rosed6334e12011-08-25 00:34:03 +00003114 if (!deallocNotOwned)
3115 deallocNotOwned.reset(new DeallocNotOwned());
3116 BT = &*deallocNotOwned;
Jordy Rose294396b2011-08-22 23:48:23 +00003117 break;
3118 }
3119
Jordy Rosed6334e12011-08-25 00:34:03 +00003120 assert(BT);
David Blaikie4e4d0842012-03-11 07:00:24 +00003121 CFRefReport *report = new CFRefReport(*BT, C.getASTContext().getLangOpts(),
Jordy Rose17a38e22011-09-02 05:55:19 +00003122 C.isObjCGCEnabled(), SummaryLog,
3123 N, Sym);
Jordy Rose294396b2011-08-22 23:48:23 +00003124 report->addRange(ErrorRange);
3125 C.EmitReport(report);
3126}
3127
Jordy Rose910c4052011-09-02 06:44:22 +00003128//===----------------------------------------------------------------------===//
3129// Handle the return values of retain-count-related functions.
3130//===----------------------------------------------------------------------===//
3131
3132bool RetainCountChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
Jordy Rose76c506f2011-08-21 21:58:18 +00003133 // Get the callee. We're only interested in simple C functions.
Ted Kremenek8bef8232012-01-26 21:29:00 +00003134 ProgramStateRef state = C.getState();
Anna Zaksb805c8f2011-12-01 05:57:37 +00003135 const FunctionDecl *FD = C.getCalleeDecl(CE);
Jordy Rose76c506f2011-08-21 21:58:18 +00003136 if (!FD)
3137 return false;
3138
3139 IdentifierInfo *II = FD->getIdentifier();
3140 if (!II)
3141 return false;
3142
3143 // For now, we're only handling the functions that return aliases of their
3144 // arguments: CFRetain and CFMakeCollectable (and their families).
3145 // Eventually we should add other functions we can model entirely,
3146 // such as CFRelease, which don't invalidate their arguments or globals.
3147 if (CE->getNumArgs() != 1)
3148 return false;
3149
3150 // Get the name of the function.
3151 StringRef FName = II->getName();
3152 FName = FName.substr(FName.find_first_not_of('_'));
3153
3154 // See if it's one of the specific functions we know how to eval.
3155 bool canEval = false;
3156
Anna Zaksb805c8f2011-12-01 05:57:37 +00003157 QualType ResultTy = CE->getCallReturnType();
Jordy Rose76c506f2011-08-21 21:58:18 +00003158 if (ResultTy->isObjCIdType()) {
3159 // Handle: id NSMakeCollectable(CFTypeRef)
3160 canEval = II->isStr("NSMakeCollectable");
3161 } else if (ResultTy->isPointerType()) {
3162 // Handle: (CF|CG)Retain
3163 // CFMakeCollectable
3164 // It's okay to be a little sloppy here (CGMakeCollectable doesn't exist).
3165 if (cocoa::isRefType(ResultTy, "CF", FName) ||
3166 cocoa::isRefType(ResultTy, "CG", FName)) {
3167 canEval = isRetain(FD, FName) || isMakeCollectable(FD, FName);
3168 }
3169 }
3170
3171 if (!canEval)
3172 return false;
3173
3174 // Bind the return value.
Ted Kremenek5eca4822012-01-06 22:09:28 +00003175 const LocationContext *LCtx = C.getLocationContext();
3176 SVal RetVal = state->getSVal(CE->getArg(0), LCtx);
Jordy Rose76c506f2011-08-21 21:58:18 +00003177 if (RetVal.isUnknown()) {
3178 // If the receiver is unknown, conjure a return value.
3179 SValBuilder &SVB = C.getSValBuilder();
Ted Kremenek66c486f2012-08-22 06:26:15 +00003180 RetVal = SVB.conjureSymbolVal(0, CE, LCtx, ResultTy, C.blockCount());
Jordy Rose76c506f2011-08-21 21:58:18 +00003181 }
Ted Kremenek5eca4822012-01-06 22:09:28 +00003182 state = state->BindExpr(CE, LCtx, RetVal, false);
Jordy Rose76c506f2011-08-21 21:58:18 +00003183
Jordy Rose294396b2011-08-22 23:48:23 +00003184 // FIXME: This should not be necessary, but otherwise the argument seems to be
3185 // considered alive during the next statement.
3186 if (const MemRegion *ArgRegion = RetVal.getAsRegion()) {
3187 // Save the refcount status of the argument.
3188 SymbolRef Sym = RetVal.getAsLocSymbol();
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003189 const RefVal *Binding = 0;
Jordy Rose294396b2011-08-22 23:48:23 +00003190 if (Sym)
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003191 Binding = getRefBinding(state, Sym);
Jordy Rose76c506f2011-08-21 21:58:18 +00003192
Jordy Rose294396b2011-08-22 23:48:23 +00003193 // Invalidate the argument region.
Ted Kremenek66c486f2012-08-22 06:26:15 +00003194 state = state->invalidateRegions(ArgRegion, CE, C.blockCount(), LCtx);
Jordy Rose76c506f2011-08-21 21:58:18 +00003195
Jordy Rose294396b2011-08-22 23:48:23 +00003196 // Restore the refcount status of the argument.
3197 if (Binding)
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003198 state = setRefBinding(state, Sym, *Binding);
Jordy Rose294396b2011-08-22 23:48:23 +00003199 }
3200
Anna Zaks0bd6b112011-10-26 21:06:34 +00003201 C.addTransition(state);
Jordy Rose76c506f2011-08-21 21:58:18 +00003202 return true;
3203}
3204
Jordy Rose910c4052011-09-02 06:44:22 +00003205//===----------------------------------------------------------------------===//
3206// Handle return statements.
3207//===----------------------------------------------------------------------===//
Jordy Rosef53e8c72011-08-23 19:43:16 +00003208
Ted Kremeneke5715782012-02-25 02:09:09 +00003209// Return true if the current LocationContext has no caller context.
3210static bool inTopFrame(CheckerContext &C) {
3211 const LocationContext *LC = C.getLocationContext();
3212 return LC->getParent() == 0;
3213}
3214
Jordy Rose910c4052011-09-02 06:44:22 +00003215void RetainCountChecker::checkPreStmt(const ReturnStmt *S,
3216 CheckerContext &C) const {
Ted Kremeneke5715782012-02-25 02:09:09 +00003217
3218 // Only adjust the reference count if this is the top-level call frame,
3219 // and not the result of inlining. In the future, we should do
3220 // better checking even for inlined calls, and see if they match
3221 // with their expected semantics (e.g., the method should return a retained
3222 // object, etc.).
3223 if (!inTopFrame(C))
3224 return;
3225
Jordy Rosef53e8c72011-08-23 19:43:16 +00003226 const Expr *RetE = S->getRetValue();
3227 if (!RetE)
3228 return;
3229
Ted Kremenek8bef8232012-01-26 21:29:00 +00003230 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00003231 SymbolRef Sym =
3232 state->getSValAsScalarOrLoc(RetE, C.getLocationContext()).getAsLocSymbol();
Jordy Rosef53e8c72011-08-23 19:43:16 +00003233 if (!Sym)
3234 return;
3235
3236 // Get the reference count binding (if any).
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003237 const RefVal *T = getRefBinding(state, Sym);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003238 if (!T)
3239 return;
3240
3241 // Change the reference count.
3242 RefVal X = *T;
3243
3244 switch (X.getKind()) {
3245 case RefVal::Owned: {
3246 unsigned cnt = X.getCount();
3247 assert(cnt > 0);
3248 X.setCount(cnt - 1);
3249 X = X ^ RefVal::ReturnedOwned;
3250 break;
3251 }
3252
3253 case RefVal::NotOwned: {
3254 unsigned cnt = X.getCount();
3255 if (cnt) {
3256 X.setCount(cnt - 1);
3257 X = X ^ RefVal::ReturnedOwned;
3258 }
3259 else {
3260 X = X ^ RefVal::ReturnedNotOwned;
3261 }
3262 break;
3263 }
3264
3265 default:
3266 return;
3267 }
3268
3269 // Update the binding.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003270 state = setRefBinding(state, Sym, X);
Anna Zaks0bd6b112011-10-26 21:06:34 +00003271 ExplodedNode *Pred = C.addTransition(state);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003272
3273 // At this point we have updated the state properly.
3274 // Everything after this is merely checking to see if the return value has
3275 // been over- or under-retained.
3276
3277 // Did we cache out?
3278 if (!Pred)
3279 return;
3280
Jordy Rosef53e8c72011-08-23 19:43:16 +00003281 // Update the autorelease counts.
3282 static SimpleProgramPointTag
Jordy Rose910c4052011-09-02 06:44:22 +00003283 AutoreleaseTag("RetainCountChecker : Autorelease");
Jordan Rose2bce86c2012-08-18 00:30:16 +00003284 llvm::tie(Pred, state) = handleAutoreleaseCounts(state, Pred, &AutoreleaseTag,
3285 C, Sym, X);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003286
3287 // Did we cache out?
Jordy Rose8d228632011-08-23 20:07:14 +00003288 if (!Pred)
Jordy Rosef53e8c72011-08-23 19:43:16 +00003289 return;
3290
3291 // Get the updated binding.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003292 T = getRefBinding(state, Sym);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003293 assert(T);
3294 X = *T;
3295
3296 // Consult the summary of the enclosing method.
Jordy Rose17a38e22011-09-02 05:55:19 +00003297 RetainSummaryManager &Summaries = getSummaryManager(C);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003298 const Decl *CD = &Pred->getCodeDecl();
Jordan Rose4531b7d2012-07-02 19:27:43 +00003299 RetEffect RE = RetEffect::MakeNoRet();
Jordy Rosef53e8c72011-08-23 19:43:16 +00003300
Jordan Rose4531b7d2012-07-02 19:27:43 +00003301 // FIXME: What is the convention for blocks? Is there one?
Jordy Rosef53e8c72011-08-23 19:43:16 +00003302 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CD)) {
Jordy Roseb6cfc092011-08-25 00:10:37 +00003303 const RetainSummary *Summ = Summaries.getMethodSummary(MD);
Jordan Rose4531b7d2012-07-02 19:27:43 +00003304 RE = Summ->getRetEffect();
3305 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) {
3306 if (!isa<CXXMethodDecl>(FD)) {
3307 const RetainSummary *Summ = Summaries.getFunctionSummary(FD);
3308 RE = Summ->getRetEffect();
3309 }
Jordy Rosef53e8c72011-08-23 19:43:16 +00003310 }
3311
Jordan Rose4531b7d2012-07-02 19:27:43 +00003312 checkReturnWithRetEffect(S, C, Pred, RE, X, Sym, state);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003313}
3314
Jordy Rose910c4052011-09-02 06:44:22 +00003315void RetainCountChecker::checkReturnWithRetEffect(const ReturnStmt *S,
3316 CheckerContext &C,
3317 ExplodedNode *Pred,
3318 RetEffect RE, RefVal X,
3319 SymbolRef Sym,
Ted Kremenek8bef8232012-01-26 21:29:00 +00003320 ProgramStateRef state) const {
Jordy Rosef53e8c72011-08-23 19:43:16 +00003321 // Any leaks or other errors?
3322 if (X.isReturnedOwned() && X.getCount() == 0) {
3323 if (RE.getKind() != RetEffect::NoRet) {
3324 bool hasError = false;
Jordy Rose17a38e22011-09-02 05:55:19 +00003325 if (C.isObjCGCEnabled() && RE.getObjKind() == RetEffect::ObjC) {
Jordy Rosef53e8c72011-08-23 19:43:16 +00003326 // Things are more complicated with garbage collection. If the
3327 // returned object is suppose to be an Objective-C object, we have
3328 // a leak (as the caller expects a GC'ed object) because no
3329 // method should return ownership unless it returns a CF object.
3330 hasError = true;
3331 X = X ^ RefVal::ErrorGCLeakReturned;
3332 }
3333 else if (!RE.isOwned()) {
3334 // Either we are using GC and the returned object is a CF type
3335 // or we aren't using GC. In either case, we expect that the
3336 // enclosing method is expected to return ownership.
3337 hasError = true;
3338 X = X ^ RefVal::ErrorLeakReturned;
3339 }
3340
3341 if (hasError) {
3342 // Generate an error node.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003343 state = setRefBinding(state, Sym, X);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003344
3345 static SimpleProgramPointTag
Jordy Rose910c4052011-09-02 06:44:22 +00003346 ReturnOwnLeakTag("RetainCountChecker : ReturnsOwnLeak");
Anna Zaks0bd6b112011-10-26 21:06:34 +00003347 ExplodedNode *N = C.addTransition(state, Pred, &ReturnOwnLeakTag);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003348 if (N) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003349 const LangOptions &LOpts = C.getASTContext().getLangOpts();
Jordy Rose17a38e22011-09-02 05:55:19 +00003350 bool GCEnabled = C.isObjCGCEnabled();
Jordy Rosef53e8c72011-08-23 19:43:16 +00003351 CFRefReport *report =
Jordy Rose17a38e22011-09-02 05:55:19 +00003352 new CFRefLeakReport(*getLeakAtReturnBug(LOpts, GCEnabled),
3353 LOpts, GCEnabled, SummaryLog,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003354 N, Sym, C);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003355 C.EmitReport(report);
3356 }
3357 }
3358 }
3359 } else if (X.isReturnedNotOwned()) {
3360 if (RE.isOwned()) {
3361 // Trying to return a not owned object to a caller expecting an
3362 // owned object.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003363 state = setRefBinding(state, Sym, X ^ RefVal::ErrorReturnedNotOwned);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003364
3365 static SimpleProgramPointTag
Jordy Rose910c4052011-09-02 06:44:22 +00003366 ReturnNotOwnedTag("RetainCountChecker : ReturnNotOwnedForOwned");
Anna Zaks0bd6b112011-10-26 21:06:34 +00003367 ExplodedNode *N = C.addTransition(state, Pred, &ReturnNotOwnedTag);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003368 if (N) {
Jordy Rosed6334e12011-08-25 00:34:03 +00003369 if (!returnNotOwnedForOwned)
3370 returnNotOwnedForOwned.reset(new ReturnedNotOwnedForOwned());
3371
Jordy Rosef53e8c72011-08-23 19:43:16 +00003372 CFRefReport *report =
Jordy Rosed6334e12011-08-25 00:34:03 +00003373 new CFRefReport(*returnNotOwnedForOwned,
David Blaikie4e4d0842012-03-11 07:00:24 +00003374 C.getASTContext().getLangOpts(),
Jordy Rose17a38e22011-09-02 05:55:19 +00003375 C.isObjCGCEnabled(), SummaryLog, N, Sym);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003376 C.EmitReport(report);
3377 }
3378 }
3379 }
3380}
3381
Jordy Rose8d228632011-08-23 20:07:14 +00003382//===----------------------------------------------------------------------===//
Jordy Rose910c4052011-09-02 06:44:22 +00003383// Check various ways a symbol can be invalidated.
3384//===----------------------------------------------------------------------===//
3385
Anna Zaks390909c2011-10-06 00:43:15 +00003386void RetainCountChecker::checkBind(SVal loc, SVal val, const Stmt *S,
Jordy Rose910c4052011-09-02 06:44:22 +00003387 CheckerContext &C) const {
3388 // Are we storing to something that causes the value to "escape"?
3389 bool escapes = true;
3390
3391 // A value escapes in three possible cases (this may change):
3392 //
3393 // (1) we are binding to something that is not a memory region.
3394 // (2) we are binding to a memregion that does not have stack storage
3395 // (3) we are binding to a memregion with stack storage that the store
3396 // does not understand.
Ted Kremenek8bef8232012-01-26 21:29:00 +00003397 ProgramStateRef state = C.getState();
Jordy Rose910c4052011-09-02 06:44:22 +00003398
3399 if (loc::MemRegionVal *regionLoc = dyn_cast<loc::MemRegionVal>(&loc)) {
3400 escapes = !regionLoc->getRegion()->hasStackStorage();
3401
3402 if (!escapes) {
3403 // To test (3), generate a new state with the binding added. If it is
3404 // the same state, then it escapes (since the store cannot represent
3405 // the binding).
Anna Zakse7958da2012-05-02 00:15:40 +00003406 // Do this only if we know that the store is not supposed to generate the
3407 // same state.
3408 SVal StoredVal = state->getSVal(regionLoc->getRegion());
3409 if (StoredVal != val)
3410 escapes = (state == (state->bindLoc(*regionLoc, val)));
Jordy Rose910c4052011-09-02 06:44:22 +00003411 }
Ted Kremenekde5b4fb2012-03-27 01:12:45 +00003412 if (!escapes) {
3413 // Case 4: We do not currently model what happens when a symbol is
3414 // assigned to a struct field, so be conservative here and let the symbol
3415 // go. TODO: This could definitely be improved upon.
3416 escapes = !isa<VarRegion>(regionLoc->getRegion());
3417 }
Jordy Rose910c4052011-09-02 06:44:22 +00003418 }
3419
3420 // If our store can represent the binding and we aren't storing to something
3421 // that doesn't have local storage then just return and have the simulation
3422 // state continue as is.
3423 if (!escapes)
3424 return;
3425
3426 // Otherwise, find all symbols referenced by 'val' that we are tracking
3427 // and stop tracking them.
3428 state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
Anna Zaks0bd6b112011-10-26 21:06:34 +00003429 C.addTransition(state);
Jordy Rose910c4052011-09-02 06:44:22 +00003430}
3431
Ted Kremenek8bef8232012-01-26 21:29:00 +00003432ProgramStateRef RetainCountChecker::evalAssume(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003433 SVal Cond,
3434 bool Assumption) const {
3435
3436 // FIXME: We may add to the interface of evalAssume the list of symbols
3437 // whose assumptions have changed. For now we just iterate through the
3438 // bindings and check if any of the tracked symbols are NULL. This isn't
3439 // too bad since the number of symbols we will track in practice are
3440 // probably small and evalAssume is only called at branches and a few
3441 // other places.
3442 RefBindings B = state->get<RefBindings>();
3443
3444 if (B.isEmpty())
3445 return state;
3446
3447 bool changed = false;
3448 RefBindings::Factory &RefBFactory = state->get_context<RefBindings>();
3449
3450 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Ted Kremenek47cbd0f2012-09-07 22:31:01 +00003451 // Check if the symbol is null stop tracking the symbol.
3452 if (state->getConstraintManager().isNull(state, I.getKey()).isTrue()) {
Jordy Rose910c4052011-09-02 06:44:22 +00003453 changed = true;
3454 B = RefBFactory.remove(B, I.getKey());
3455 }
3456 }
3457
3458 if (changed)
3459 state = state->set<RefBindings>(B);
3460
3461 return state;
3462}
3463
Ted Kremenek8bef8232012-01-26 21:29:00 +00003464ProgramStateRef
3465RetainCountChecker::checkRegionChanges(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003466 const StoreManager::InvalidatedSymbols *invalidated,
3467 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00003468 ArrayRef<const MemRegion *> Regions,
Jordan Rose740d4902012-07-02 19:27:35 +00003469 const CallEvent *Call) const {
Jordy Rose910c4052011-09-02 06:44:22 +00003470 if (!invalidated)
3471 return state;
3472
3473 llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
3474 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
3475 E = ExplicitRegions.end(); I != E; ++I) {
3476 if (const SymbolicRegion *SR = (*I)->StripCasts()->getAs<SymbolicRegion>())
3477 WhitelistedSymbols.insert(SR->getSymbol());
3478 }
3479
3480 for (StoreManager::InvalidatedSymbols::const_iterator I=invalidated->begin(),
3481 E = invalidated->end(); I!=E; ++I) {
3482 SymbolRef sym = *I;
3483 if (WhitelistedSymbols.count(sym))
3484 continue;
3485 // Remove any existing reference-count binding.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003486 state = removeRefBinding(state, sym);
Jordy Rose910c4052011-09-02 06:44:22 +00003487 }
3488 return state;
3489}
3490
3491//===----------------------------------------------------------------------===//
Jordy Rose8d228632011-08-23 20:07:14 +00003492// Handle dead symbols and end-of-path.
3493//===----------------------------------------------------------------------===//
3494
Ted Kremenek8bef8232012-01-26 21:29:00 +00003495std::pair<ExplodedNode *, ProgramStateRef >
3496RetainCountChecker::handleAutoreleaseCounts(ProgramStateRef state,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003497 ExplodedNode *Pred,
Jordan Rose2bce86c2012-08-18 00:30:16 +00003498 const ProgramPointTag *Tag,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003499 CheckerContext &Ctx,
Jordy Rose910c4052011-09-02 06:44:22 +00003500 SymbolRef Sym, RefVal V) const {
Jordy Rose8d228632011-08-23 20:07:14 +00003501 unsigned ACnt = V.getAutoreleaseCount();
3502
3503 // No autorelease counts? Nothing to be done.
3504 if (!ACnt)
3505 return std::make_pair(Pred, state);
3506
Anna Zaks6a93bd52011-10-25 19:57:11 +00003507 assert(!Ctx.isObjCGCEnabled() && "Autorelease counts in GC mode?");
Jordy Rose8d228632011-08-23 20:07:14 +00003508 unsigned Cnt = V.getCount();
3509
3510 // FIXME: Handle sending 'autorelease' to already released object.
3511
3512 if (V.getKind() == RefVal::ReturnedOwned)
3513 ++Cnt;
3514
3515 if (ACnt <= Cnt) {
3516 if (ACnt == Cnt) {
3517 V.clearCounts();
3518 if (V.getKind() == RefVal::ReturnedOwned)
3519 V = V ^ RefVal::ReturnedNotOwned;
3520 else
3521 V = V ^ RefVal::NotOwned;
3522 } else {
3523 V.setCount(Cnt - ACnt);
3524 V.setAutoreleaseCount(0);
3525 }
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003526 state = setRefBinding(state, Sym, V);
Jordan Rose2bce86c2012-08-18 00:30:16 +00003527 ExplodedNode *N = Ctx.addTransition(state, Pred, Tag);
Jordy Rose8d228632011-08-23 20:07:14 +00003528 if (N == 0)
3529 state = 0;
3530 return std::make_pair(N, state);
3531 }
3532
3533 // Woah! More autorelease counts then retain counts left.
3534 // Emit hard error.
3535 V = V ^ RefVal::ErrorOverAutorelease;
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003536 state = setRefBinding(state, Sym, V);
Jordy Rose8d228632011-08-23 20:07:14 +00003537
Jordan Rosefa06f042012-08-20 18:43:42 +00003538 ExplodedNode *N = Ctx.generateSink(state, Pred, Tag);
Jordan Rose2bce86c2012-08-18 00:30:16 +00003539 if (N) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003540 SmallString<128> sbuf;
Jordy Rose8d228632011-08-23 20:07:14 +00003541 llvm::raw_svector_ostream os(sbuf);
3542 os << "Object over-autoreleased: object was sent -autorelease ";
3543 if (V.getAutoreleaseCount() > 1)
3544 os << V.getAutoreleaseCount() << " times ";
3545 os << "but the object has a +" << V.getCount() << " retain count";
3546
Jordy Rosed6334e12011-08-25 00:34:03 +00003547 if (!overAutorelease)
3548 overAutorelease.reset(new OverAutorelease());
3549
David Blaikie4e4d0842012-03-11 07:00:24 +00003550 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
Jordy Rose8d228632011-08-23 20:07:14 +00003551 CFRefReport *report =
Jordy Rosed6334e12011-08-25 00:34:03 +00003552 new CFRefReport(*overAutorelease, LOpts, /* GCEnabled = */ false,
3553 SummaryLog, N, Sym, os.str());
Anna Zaks6a93bd52011-10-25 19:57:11 +00003554 Ctx.EmitReport(report);
Jordy Rose8d228632011-08-23 20:07:14 +00003555 }
3556
Ted Kremenek8bef8232012-01-26 21:29:00 +00003557 return std::make_pair((ExplodedNode *)0, (ProgramStateRef )0);
Jordy Rose8d228632011-08-23 20:07:14 +00003558}
Jordy Rose38f17d62011-08-23 19:01:07 +00003559
Ted Kremenek8bef8232012-01-26 21:29:00 +00003560ProgramStateRef
3561RetainCountChecker::handleSymbolDeath(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003562 SymbolRef sid, RefVal V,
Jordy Rose38f17d62011-08-23 19:01:07 +00003563 SmallVectorImpl<SymbolRef> &Leaked) const {
Jordy Rose53376122011-08-24 04:48:19 +00003564 bool hasLeak = false;
Jordy Rose38f17d62011-08-23 19:01:07 +00003565 if (V.isOwned())
3566 hasLeak = true;
3567 else if (V.isNotOwned() || V.isReturnedOwned())
3568 hasLeak = (V.getCount() > 0);
3569
3570 if (!hasLeak)
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003571 return removeRefBinding(state, sid);
Jordy Rose38f17d62011-08-23 19:01:07 +00003572
3573 Leaked.push_back(sid);
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003574 return setRefBinding(state, sid, V ^ RefVal::ErrorLeak);
Jordy Rose38f17d62011-08-23 19:01:07 +00003575}
3576
3577ExplodedNode *
Ted Kremenek8bef8232012-01-26 21:29:00 +00003578RetainCountChecker::processLeaks(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003579 SmallVectorImpl<SymbolRef> &Leaked,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003580 CheckerContext &Ctx,
3581 ExplodedNode *Pred) const {
Jordy Rose38f17d62011-08-23 19:01:07 +00003582 if (Leaked.empty())
3583 return Pred;
3584
3585 // Generate an intermediate node representing the leak point.
Jordan Rose2bce86c2012-08-18 00:30:16 +00003586 ExplodedNode *N = Ctx.addTransition(state, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003587
3588 if (N) {
3589 for (SmallVectorImpl<SymbolRef>::iterator
3590 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3591
David Blaikie4e4d0842012-03-11 07:00:24 +00003592 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
Anna Zaks6a93bd52011-10-25 19:57:11 +00003593 bool GCEnabled = Ctx.isObjCGCEnabled();
Jordy Rose17a38e22011-09-02 05:55:19 +00003594 CFRefBug *BT = Pred ? getLeakWithinFunctionBug(LOpts, GCEnabled)
3595 : getLeakAtReturnBug(LOpts, GCEnabled);
Jordy Rose38f17d62011-08-23 19:01:07 +00003596 assert(BT && "BugType not initialized.");
Jordy Rose20589562011-08-24 22:39:09 +00003597
Jordy Rose17a38e22011-09-02 05:55:19 +00003598 CFRefLeakReport *report = new CFRefLeakReport(*BT, LOpts, GCEnabled,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003599 SummaryLog, N, *I, Ctx);
3600 Ctx.EmitReport(report);
Jordy Rose38f17d62011-08-23 19:01:07 +00003601 }
3602 }
3603
3604 return N;
3605}
3606
Anna Zaksaf498a22011-10-25 19:56:48 +00003607void RetainCountChecker::checkEndPath(CheckerContext &Ctx) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +00003608 ProgramStateRef state = Ctx.getState();
Jordy Rose38f17d62011-08-23 19:01:07 +00003609 RefBindings B = state->get<RefBindings>();
Anna Zaksaf498a22011-10-25 19:56:48 +00003610 ExplodedNode *Pred = Ctx.getPredecessor();
Jordy Rose38f17d62011-08-23 19:01:07 +00003611
3612 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Jordan Rose2bce86c2012-08-18 00:30:16 +00003613 llvm::tie(Pred, state) = handleAutoreleaseCounts(state, Pred, /*Tag=*/0,
3614 Ctx, I->first, I->second);
Jordy Rose8d228632011-08-23 20:07:14 +00003615 if (!state)
Jordy Rose38f17d62011-08-23 19:01:07 +00003616 return;
3617 }
3618
Ted Kremenek0cf3d472012-02-07 00:24:33 +00003619 // If the current LocationContext has a parent, don't check for leaks.
3620 // We will do that later.
Anna Zaks8d6b43c2012-08-14 00:36:15 +00003621 // FIXME: we should instead check for imbalances of the retain/releases,
Ted Kremenek0cf3d472012-02-07 00:24:33 +00003622 // and suggest annotations.
3623 if (Ctx.getLocationContext()->getParent())
3624 return;
3625
Jordy Rose38f17d62011-08-23 19:01:07 +00003626 B = state->get<RefBindings>();
3627 SmallVector<SymbolRef, 10> Leaked;
3628
3629 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I)
Jordy Rose8d228632011-08-23 20:07:14 +00003630 state = handleSymbolDeath(state, I->first, I->second, Leaked);
Jordy Rose38f17d62011-08-23 19:01:07 +00003631
Jordan Rose2bce86c2012-08-18 00:30:16 +00003632 processLeaks(state, Leaked, Ctx, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003633}
3634
3635const ProgramPointTag *
Jordy Rose910c4052011-09-02 06:44:22 +00003636RetainCountChecker::getDeadSymbolTag(SymbolRef sym) const {
Jordy Rose38f17d62011-08-23 19:01:07 +00003637 const SimpleProgramPointTag *&tag = DeadSymbolTags[sym];
3638 if (!tag) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003639 SmallString<64> buf;
Jordy Rose38f17d62011-08-23 19:01:07 +00003640 llvm::raw_svector_ostream out(buf);
Anna Zaksf62ceec2011-12-05 18:58:11 +00003641 out << "RetainCountChecker : Dead Symbol : ";
3642 sym->dumpToStream(out);
Jordy Rose38f17d62011-08-23 19:01:07 +00003643 tag = new SimpleProgramPointTag(out.str());
3644 }
3645 return tag;
3646}
3647
Jordy Rose910c4052011-09-02 06:44:22 +00003648void RetainCountChecker::checkDeadSymbols(SymbolReaper &SymReaper,
3649 CheckerContext &C) const {
Jordy Rose38f17d62011-08-23 19:01:07 +00003650 ExplodedNode *Pred = C.getPredecessor();
3651
Ted Kremenek8bef8232012-01-26 21:29:00 +00003652 ProgramStateRef state = C.getState();
Jordy Rose38f17d62011-08-23 19:01:07 +00003653 RefBindings B = state->get<RefBindings>();
3654
3655 // Update counts from autorelease pools
3656 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3657 E = SymReaper.dead_end(); I != E; ++I) {
3658 SymbolRef Sym = *I;
3659 if (const RefVal *T = B.lookup(Sym)){
3660 // Use the symbol as the tag.
3661 // FIXME: This might not be as unique as we would like.
Jordan Rose2bce86c2012-08-18 00:30:16 +00003662 const ProgramPointTag *Tag = getDeadSymbolTag(Sym);
3663 llvm::tie(Pred, state) = handleAutoreleaseCounts(state, Pred, Tag, C,
Jordy Rose8d228632011-08-23 20:07:14 +00003664 Sym, *T);
3665 if (!state)
Jordy Rose38f17d62011-08-23 19:01:07 +00003666 return;
3667 }
3668 }
3669
3670 B = state->get<RefBindings>();
3671 SmallVector<SymbolRef, 10> Leaked;
3672
3673 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3674 E = SymReaper.dead_end(); I != E; ++I) {
3675 if (const RefVal *T = B.lookup(*I))
3676 state = handleSymbolDeath(state, *I, *T, Leaked);
3677 }
3678
Jordan Rose2bce86c2012-08-18 00:30:16 +00003679 Pred = processLeaks(state, Leaked, C, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003680
3681 // Did we cache out?
3682 if (!Pred)
3683 return;
3684
3685 // Now generate a new node that nukes the old bindings.
3686 RefBindings::Factory &F = state->get_context<RefBindings>();
3687
3688 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3689 E = SymReaper.dead_end(); I != E; ++I)
3690 B = F.remove(B, *I);
3691
3692 state = state->set<RefBindings>(B);
Anna Zaks0bd6b112011-10-26 21:06:34 +00003693 C.addTransition(state, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003694}
3695
Ted Kremenek8bef8232012-01-26 21:29:00 +00003696void RetainCountChecker::printState(raw_ostream &Out, ProgramStateRef State,
Jordy Rose910c4052011-09-02 06:44:22 +00003697 const char *NL, const char *Sep) const {
Jordy Rosedbd658e2011-08-28 19:11:56 +00003698
3699 RefBindings B = State->get<RefBindings>();
3700
3701 if (!B.isEmpty())
3702 Out << Sep << NL;
3703
3704 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
3705 Out << I->first << " : ";
3706 I->second.print(Out);
3707 Out << NL;
3708 }
Jordy Rosedbd658e2011-08-28 19:11:56 +00003709}
3710
3711//===----------------------------------------------------------------------===//
Jordy Rose910c4052011-09-02 06:44:22 +00003712// Checker registration.
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00003713//===----------------------------------------------------------------------===//
3714
Jordy Rose17a38e22011-09-02 05:55:19 +00003715void ento::registerRetainCountChecker(CheckerManager &Mgr) {
Jordy Rose910c4052011-09-02 06:44:22 +00003716 Mgr.registerChecker<RetainCountChecker>();
Jordy Rose17a38e22011-09-02 05:55:19 +00003717}
3718