blob: 12b74e7e29cff8c276359d6065443a60cec67319 [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 Rose4531b7d2012-07-02 19:27:43 +000026#include "clang/StaticAnalyzer/Core/PathSensitive/Calls.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"
Jordy Rosed1e5a892011-09-02 08:02:59 +000030#include "clang/StaticAnalyzer/Core/PathSensitive/ObjCMessage.h"
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000031#include "llvm/ADT/DenseMap.h"
32#include "llvm/ADT/FoldingSet.h"
Ted Kremenek6d348932008-10-21 15:53:15 +000033#include "llvm/ADT/ImmutableList.h"
Ted Kremenek0b526b42010-02-18 00:05:58 +000034#include "llvm/ADT/ImmutableMap.h"
Benjamin Kramer8fe83e12012-02-04 13:45:25 +000035#include "llvm/ADT/SmallString.h"
Ted Kremenek6ed9afc2008-05-16 18:33:44 +000036#include "llvm/ADT/STLExtras.h"
Ted Kremenek0b526b42010-02-18 00:05:58 +000037#include "llvm/ADT/StringExtras.h"
Chris Lattner5f9e2722011-07-23 10:55:15 +000038#include <cstdarg>
Ted Kremenek2fff37e2008-03-06 00:08:09 +000039
40using namespace clang;
Ted Kremenek9ef65372010-12-23 07:20:52 +000041using namespace ento;
Ted Kremeneka64e89b2010-01-27 06:13:48 +000042using llvm::StrInStrNoCase;
Ted Kremenek4c79e552008-11-05 16:54:44 +000043
Ted Kremenekd775c662010-05-21 21:57:00 +000044namespace {
Jordy Rose910c4052011-09-02 06:44:22 +000045/// Wrapper around different kinds of node builder, so that helper functions
46/// can have a common interface.
Francois Pichetea097852011-01-11 10:41:37 +000047class GenericNodeBuilderRefCount {
Anna Zaks4eff8232011-10-05 23:44:11 +000048 CheckerContext *C;
Ted Kremenekca804532011-08-12 23:04:46 +000049 const ProgramPointTag *tag;
Ted Kremenek9d9d3a62009-05-08 23:09:42 +000050public:
Anna Zaks4eff8232011-10-05 23:44:11 +000051 GenericNodeBuilderRefCount(CheckerContext &c,
Anna Zaksaf498a22011-10-25 19:56:48 +000052 const ProgramPointTag *t = 0)
Anna Zaks6a93bd52011-10-25 19:57:11 +000053 : C(&c), tag(t){}
Zhongxing Xu031ccc02009-08-06 12:48:26 +000054
Ted Kremenek8bef8232012-01-26 21:29:00 +000055 ExplodedNode *MakeNode(ProgramStateRef state, ExplodedNode *Pred,
Anna Zaksf05aac82011-10-18 23:05:58 +000056 bool MarkAsSink = false) {
Anna Zaks0bd6b112011-10-26 21:06:34 +000057 return C->addTransition(state, Pred, tag, MarkAsSink);
Ted Kremenek9d9d3a62009-05-08 23:09:42 +000058 }
59};
60} // end anonymous namespace
61
Ted Kremenek05cbe1a2008-04-09 23:49:11 +000062//===----------------------------------------------------------------------===//
Ted Kremenek553cf182008-06-25 21:21:56 +000063// Primitives used for constructing summaries for function/method calls.
Ted Kremenek05cbe1a2008-04-09 23:49:11 +000064//===----------------------------------------------------------------------===//
65
Ted Kremenek553cf182008-06-25 21:21:56 +000066/// ArgEffect is used to summarize a function/method call's effect on a
67/// particular argument.
Jordy Rosebd85b132011-08-24 19:10:50 +000068enum ArgEffect { DoNothing, Autorelease, Dealloc, DecRef, DecRefMsg,
John McCallf85e1932011-06-15 23:02:42 +000069 DecRefBridgedTransfered,
Jordan Rose4531b7d2012-07-02 19:27:43 +000070 DecRefAndStopTracking, DecRefMsgAndStopTracking,
Jordy Rosebd85b132011-08-24 19:10:50 +000071 IncRefMsg, IncRef, MakeCollectable, MayEscape,
Jordan Rose29299c62012-06-27 00:51:18 +000072 NewAutoreleasePool, StopTracking };
Ted Kremenek553cf182008-06-25 21:21:56 +000073
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000074namespace llvm {
Ted Kremenekb77449c2009-05-03 05:20:50 +000075template <> struct FoldingSetTrait<ArgEffect> {
76static inline void Profile(const ArgEffect X, FoldingSetNodeID& ID) {
77 ID.AddInteger((unsigned) X);
78}
Ted Kremenek553cf182008-06-25 21:21:56 +000079};
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000080} // end llvm namespace
81
Ted Kremenekb77449c2009-05-03 05:20:50 +000082/// ArgEffects summarizes the effects of a function/method call on all of
83/// its arguments.
84typedef llvm::ImmutableMap<unsigned,ArgEffect> ArgEffects;
85
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000086namespace {
Ted Kremenek553cf182008-06-25 21:21:56 +000087
88/// RetEffect is used to summarize a function/method call's behavior with
Mike Stump1eb44332009-09-09 15:08:12 +000089/// respect to its return value.
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +000090class RetEffect {
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000091public:
Jordy Rose76c506f2011-08-21 21:58:18 +000092 enum Kind { NoRet, OwnedSymbol, OwnedAllocatedSymbol,
John McCallf85e1932011-06-15 23:02:42 +000093 NotOwnedSymbol, GCNotOwnedSymbol, ARCNotOwnedSymbol,
Ted Kremenek78a35a32009-05-12 20:06:54 +000094 OwnedWhenTrackedReceiver };
Mike Stump1eb44332009-09-09 15:08:12 +000095
96 enum ObjKind { CF, ObjC, AnyObj };
Ted Kremenek2d1652e2009-01-28 05:56:51 +000097
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000098private:
Ted Kremenek2d1652e2009-01-28 05:56:51 +000099 Kind K;
100 ObjKind O;
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000101
Jordy Rose76c506f2011-08-21 21:58:18 +0000102 RetEffect(Kind k, ObjKind o = AnyObj) : K(k), O(o) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000103
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000104public:
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000105 Kind getKind() const { return K; }
106
107 ObjKind getObjKind() const { return O; }
Mike Stump1eb44332009-09-09 15:08:12 +0000108
Ted Kremeneka8833552009-04-29 23:03:22 +0000109 bool isOwned() const {
Ted Kremenek78a35a32009-05-12 20:06:54 +0000110 return K == OwnedSymbol || K == OwnedAllocatedSymbol ||
111 K == OwnedWhenTrackedReceiver;
Ted Kremeneka8833552009-04-29 23:03:22 +0000112 }
Mike Stump1eb44332009-09-09 15:08:12 +0000113
Jordy Rose4df54fe2011-08-23 04:27:15 +0000114 bool operator==(const RetEffect &Other) const {
115 return K == Other.K && O == Other.O;
116 }
117
Ted Kremenek78a35a32009-05-12 20:06:54 +0000118 static RetEffect MakeOwnedWhenTrackedReceiver() {
119 return RetEffect(OwnedWhenTrackedReceiver, ObjC);
120 }
Mike Stump1eb44332009-09-09 15:08:12 +0000121
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000122 static RetEffect MakeOwned(ObjKind o, bool isAllocated = false) {
123 return RetEffect(isAllocated ? OwnedAllocatedSymbol : OwnedSymbol, o);
Mike Stump1eb44332009-09-09 15:08:12 +0000124 }
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000125 static RetEffect MakeNotOwned(ObjKind o) {
126 return RetEffect(NotOwnedSymbol, o);
Ted Kremeneke798e7c2009-04-27 19:14:45 +0000127 }
128 static RetEffect MakeGCNotOwned() {
129 return RetEffect(GCNotOwnedSymbol, ObjC);
130 }
John McCallf85e1932011-06-15 23:02:42 +0000131 static RetEffect MakeARCNotOwned() {
132 return RetEffect(ARCNotOwnedSymbol, ObjC);
133 }
Ted Kremenek553cf182008-06-25 21:21:56 +0000134 static RetEffect MakeNoRet() {
135 return RetEffect(NoRet);
Ted Kremeneka7344702008-06-23 18:02:52 +0000136 }
Jordy Roseef945882012-03-18 01:26:10 +0000137
138 void Profile(llvm::FoldingSetNodeID& ID) const {
139 ID.AddInteger((unsigned) K);
140 ID.AddInteger((unsigned) O);
141 }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000142};
Mike Stump1eb44332009-09-09 15:08:12 +0000143
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000144//===----------------------------------------------------------------------===//
145// Reference-counting logic (typestate + counts).
146//===----------------------------------------------------------------------===//
Mike Stump1eb44332009-09-09 15:08:12 +0000147
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000148class RefVal {
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000149public:
150 enum Kind {
151 Owned = 0, // Owning reference.
152 NotOwned, // Reference is not owned by still valid (not freed).
153 Released, // Object has been released.
154 ReturnedOwned, // Returned object passes ownership to caller.
155 ReturnedNotOwned, // Return object does not pass ownership to caller.
156 ERROR_START,
157 ErrorDeallocNotOwned, // -dealloc called on non-owned object.
158 ErrorDeallocGC, // Calling -dealloc with GC enabled.
159 ErrorUseAfterRelease, // Object used after released.
160 ErrorReleaseNotOwned, // Release of an object that was not owned.
161 ERROR_LEAK_START,
162 ErrorLeak, // A memory leak due to excessive reference counts.
163 ErrorLeakReturned, // A memory leak due to the returning method not having
164 // the correct naming conventions.
165 ErrorGCLeakReturned,
166 ErrorOverAutorelease,
167 ErrorReturnedNotOwned
168 };
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000169
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000170private:
171 Kind kind;
172 RetEffect::ObjKind okind;
173 unsigned Cnt;
174 unsigned ACnt;
175 QualType T;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000176
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000177 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, unsigned acnt, QualType t)
178 : kind(k), okind(o), Cnt(cnt), ACnt(acnt), T(t) {}
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000179
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000180public:
181 Kind getKind() const { return kind; }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000182
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000183 RetEffect::ObjKind getObjKind() const { return okind; }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000184
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000185 unsigned getCount() const { return Cnt; }
186 unsigned getAutoreleaseCount() const { return ACnt; }
187 unsigned getCombinedCounts() const { return Cnt + ACnt; }
188 void clearCounts() { Cnt = 0; ACnt = 0; }
189 void setCount(unsigned i) { Cnt = i; }
190 void setAutoreleaseCount(unsigned i) { ACnt = i; }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000191
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000192 QualType getType() const { return T; }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000193
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000194 bool isOwned() const {
195 return getKind() == Owned;
196 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000197
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000198 bool isNotOwned() const {
199 return getKind() == NotOwned;
200 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000201
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000202 bool isReturnedOwned() const {
203 return getKind() == ReturnedOwned;
204 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000205
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000206 bool isReturnedNotOwned() const {
207 return getKind() == ReturnedNotOwned;
208 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000209
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000210 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
211 unsigned Count = 1) {
212 return RefVal(Owned, o, Count, 0, t);
213 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000214
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000215 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
216 unsigned Count = 0) {
217 return RefVal(NotOwned, o, Count, 0, t);
218 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000219
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000220 // Comparison, profiling, and pretty-printing.
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000221
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000222 bool operator==(const RefVal& X) const {
223 return kind == X.kind && Cnt == X.Cnt && T == X.T && ACnt == X.ACnt;
224 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000225
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000226 RefVal operator-(size_t i) const {
227 return RefVal(getKind(), getObjKind(), getCount() - i,
228 getAutoreleaseCount(), getType());
229 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000230
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000231 RefVal operator+(size_t i) const {
232 return RefVal(getKind(), getObjKind(), getCount() + i,
233 getAutoreleaseCount(), getType());
234 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000235
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000236 RefVal operator^(Kind k) const {
237 return RefVal(k, getObjKind(), getCount(), getAutoreleaseCount(),
238 getType());
239 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000240
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000241 RefVal autorelease() const {
242 return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount()+1,
243 getType());
244 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000245
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000246 void Profile(llvm::FoldingSetNodeID& ID) const {
247 ID.AddInteger((unsigned) kind);
248 ID.AddInteger(Cnt);
249 ID.AddInteger(ACnt);
250 ID.Add(T);
251 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000252
Ted Kremenek9c378f72011-08-12 23:37:29 +0000253 void print(raw_ostream &Out) const;
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000254};
255
Ted Kremenek9c378f72011-08-12 23:37:29 +0000256void RefVal::print(raw_ostream &Out) const {
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000257 if (!T.isNull())
Jordy Rosedbd658e2011-08-28 19:11:56 +0000258 Out << "Tracked " << T.getAsString() << '/';
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000259
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000260 switch (getKind()) {
Jordy Rose910c4052011-09-02 06:44:22 +0000261 default: llvm_unreachable("Invalid RefVal kind");
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000262 case Owned: {
263 Out << "Owned";
264 unsigned cnt = getCount();
265 if (cnt) Out << " (+ " << cnt << ")";
266 break;
267 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000268
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000269 case NotOwned: {
270 Out << "NotOwned";
271 unsigned cnt = getCount();
272 if (cnt) Out << " (+ " << cnt << ")";
273 break;
274 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000275
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000276 case ReturnedOwned: {
277 Out << "ReturnedOwned";
278 unsigned cnt = getCount();
279 if (cnt) Out << " (+ " << cnt << ")";
280 break;
281 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000282
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000283 case ReturnedNotOwned: {
284 Out << "ReturnedNotOwned";
285 unsigned cnt = getCount();
286 if (cnt) Out << " (+ " << cnt << ")";
287 break;
288 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000289
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000290 case Released:
291 Out << "Released";
292 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000293
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000294 case ErrorDeallocGC:
295 Out << "-dealloc (GC)";
296 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000297
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000298 case ErrorDeallocNotOwned:
299 Out << "-dealloc (not-owned)";
300 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000301
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000302 case ErrorLeak:
303 Out << "Leaked";
304 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000305
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000306 case ErrorLeakReturned:
307 Out << "Leaked (Bad naming)";
308 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000309
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000310 case ErrorGCLeakReturned:
311 Out << "Leaked (GC-ed at return)";
312 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000313
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000314 case ErrorUseAfterRelease:
315 Out << "Use-After-Release [ERROR]";
316 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000317
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000318 case ErrorReleaseNotOwned:
319 Out << "Release of Not-Owned [ERROR]";
320 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000321
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000322 case RefVal::ErrorOverAutorelease:
323 Out << "Over autoreleased";
324 break;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000325
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000326 case RefVal::ErrorReturnedNotOwned:
327 Out << "Non-owned object returned instead of owned";
328 break;
329 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000330
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000331 if (ACnt) {
332 Out << " [ARC +" << ACnt << ']';
333 }
334}
335} //end anonymous namespace
336
337//===----------------------------------------------------------------------===//
338// RefBindings - State used to track object reference counts.
339//===----------------------------------------------------------------------===//
340
341typedef llvm::ImmutableMap<SymbolRef, RefVal> RefBindings;
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000342
343namespace clang {
Ted Kremenek9ef65372010-12-23 07:20:52 +0000344namespace ento {
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000345template<>
346struct ProgramStateTrait<RefBindings>
347 : public ProgramStatePartialTrait<RefBindings> {
348 static void *GDMIndex() {
349 static int RefBIndex = 0;
350 return &RefBIndex;
351 }
352};
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000353}
Argyrios Kyrtzidis5a4f98f2010-12-22 18:53:20 +0000354}
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000355
356//===----------------------------------------------------------------------===//
Jordy Rose910c4052011-09-02 06:44:22 +0000357// Function/Method behavior summaries.
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +0000358//===----------------------------------------------------------------------===//
359
360namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000361class RetainSummary {
Jordy Roseef945882012-03-18 01:26:10 +0000362 /// Args - a map of (index, ArgEffect) pairs, where index
Ted Kremenek1bffd742008-05-06 15:44:25 +0000363 /// specifies the argument (starting from 0). This can be sparsely
364 /// populated; arguments with no entry in Args use 'DefaultArgEffect'.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000365 ArgEffects Args;
Mike Stump1eb44332009-09-09 15:08:12 +0000366
Ted Kremenek1bffd742008-05-06 15:44:25 +0000367 /// DefaultArgEffect - The default ArgEffect to apply to arguments that
368 /// do not have an entry in Args.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000369 ArgEffect DefaultArgEffect;
Mike Stump1eb44332009-09-09 15:08:12 +0000370
Ted Kremenek553cf182008-06-25 21:21:56 +0000371 /// Receiver - If this summary applies to an Objective-C message expression,
372 /// this is the effect applied to the state of the receiver.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000373 ArgEffect Receiver;
Mike Stump1eb44332009-09-09 15:08:12 +0000374
Ted Kremenek553cf182008-06-25 21:21:56 +0000375 /// Ret - The effect on the return value. Used to indicate if the
Jordy Rose76c506f2011-08-21 21:58:18 +0000376 /// function/method call returns a new tracked symbol.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000377 RetEffect Ret;
Mike Stump1eb44332009-09-09 15:08:12 +0000378
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000379public:
Ted Kremenekb77449c2009-05-03 05:20:50 +0000380 RetainSummary(ArgEffects A, RetEffect R, ArgEffect defaultEff,
Jordy Rosee62e87b2011-08-20 20:55:40 +0000381 ArgEffect ReceiverEff)
382 : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000383
Ted Kremenek553cf182008-06-25 21:21:56 +0000384 /// getArg - Return the argument effect on the argument specified by
385 /// idx (starting from 0).
Ted Kremenek1ac08d62008-03-11 17:48:22 +0000386 ArgEffect getArg(unsigned idx) const {
Ted Kremenekb77449c2009-05-03 05:20:50 +0000387 if (const ArgEffect *AE = Args.lookup(idx))
388 return *AE;
Mike Stump1eb44332009-09-09 15:08:12 +0000389
Ted Kremenek1bffd742008-05-06 15:44:25 +0000390 return DefaultArgEffect;
Ted Kremenek1ac08d62008-03-11 17:48:22 +0000391 }
Ted Kremenek11fe1752011-01-27 18:43:03 +0000392
393 void addArg(ArgEffects::Factory &af, unsigned idx, ArgEffect e) {
394 Args = af.add(Args, idx, e);
395 }
Mike Stump1eb44332009-09-09 15:08:12 +0000396
Ted Kremenek885c27b2009-05-04 05:31:22 +0000397 /// setDefaultArgEffect - Set the default argument effect.
398 void setDefaultArgEffect(ArgEffect E) {
399 DefaultArgEffect = E;
400 }
Mike Stump1eb44332009-09-09 15:08:12 +0000401
Ted Kremenek553cf182008-06-25 21:21:56 +0000402 /// getRetEffect - Returns the effect on the return value of the call.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000403 RetEffect getRetEffect() const { return Ret; }
Mike Stump1eb44332009-09-09 15:08:12 +0000404
Ted Kremenek885c27b2009-05-04 05:31:22 +0000405 /// setRetEffect - Set the effect of the return value of the call.
406 void setRetEffect(RetEffect E) { Ret = E; }
Mike Stump1eb44332009-09-09 15:08:12 +0000407
Ted Kremenek12b94342011-01-27 06:54:14 +0000408
409 /// Sets the effect on the receiver of the message.
410 void setReceiverEffect(ArgEffect e) { Receiver = e; }
411
Ted Kremenek553cf182008-06-25 21:21:56 +0000412 /// getReceiverEffect - Returns the effect on the receiver of the call.
413 /// This is only meaningful if the summary applies to an ObjCMessageExpr*.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000414 ArgEffect getReceiverEffect() const { return Receiver; }
Jordy Rose4df54fe2011-08-23 04:27:15 +0000415
416 /// Test if two retain summaries are identical. Note that merely equivalent
417 /// summaries are not necessarily identical (for example, if an explicit
418 /// argument effect matches the default effect).
419 bool operator==(const RetainSummary &Other) const {
420 return Args == Other.Args && DefaultArgEffect == Other.DefaultArgEffect &&
421 Receiver == Other.Receiver && Ret == Other.Ret;
422 }
Jordy Roseef945882012-03-18 01:26:10 +0000423
424 /// Profile this summary for inclusion in a FoldingSet.
425 void Profile(llvm::FoldingSetNodeID& ID) const {
426 ID.Add(Args);
427 ID.Add(DefaultArgEffect);
428 ID.Add(Receiver);
429 ID.Add(Ret);
430 }
431
432 /// A retain summary is simple if it has no ArgEffects other than the default.
433 bool isSimple() const {
434 return Args.isEmpty();
435 }
Jordan Rose4531b7d2012-07-02 19:27:43 +0000436
437private:
438 ArgEffects getArgEffects() const { return Args; }
439 ArgEffect getDefaultArgEffect() const { return DefaultArgEffect; }
440
441 friend class RetainSummaryManager;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000442};
Ted Kremenek4f22a782008-06-23 23:30:29 +0000443} // end anonymous namespace
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000444
Ted Kremenek553cf182008-06-25 21:21:56 +0000445//===----------------------------------------------------------------------===//
446// Data structures for constructing summaries.
447//===----------------------------------------------------------------------===//
Ted Kremenek53301ba2008-06-24 03:49:48 +0000448
Ted Kremenek553cf182008-06-25 21:21:56 +0000449namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000450class ObjCSummaryKey {
Ted Kremenek553cf182008-06-25 21:21:56 +0000451 IdentifierInfo* II;
452 Selector S;
Mike Stump1eb44332009-09-09 15:08:12 +0000453public:
Ted Kremenek553cf182008-06-25 21:21:56 +0000454 ObjCSummaryKey(IdentifierInfo* ii, Selector s)
455 : II(ii), S(s) {}
456
Ted Kremenek9c378f72011-08-12 23:37:29 +0000457 ObjCSummaryKey(const ObjCInterfaceDecl *d, Selector s)
Ted Kremenek553cf182008-06-25 21:21:56 +0000458 : II(d ? d->getIdentifier() : 0), S(s) {}
Ted Kremenek70b6a832009-05-13 18:16:01 +0000459
Ted Kremenek553cf182008-06-25 21:21:56 +0000460 ObjCSummaryKey(Selector s)
461 : II(0), S(s) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000462
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000463 IdentifierInfo *getIdentifier() const { return II; }
Ted Kremenek553cf182008-06-25 21:21:56 +0000464 Selector getSelector() const { return S; }
465};
Ted Kremenek4f22a782008-06-23 23:30:29 +0000466}
467
468namespace llvm {
Ted Kremenek553cf182008-06-25 21:21:56 +0000469template <> struct DenseMapInfo<ObjCSummaryKey> {
470 static inline ObjCSummaryKey getEmptyKey() {
471 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
472 DenseMapInfo<Selector>::getEmptyKey());
473 }
Mike Stump1eb44332009-09-09 15:08:12 +0000474
Ted Kremenek553cf182008-06-25 21:21:56 +0000475 static inline ObjCSummaryKey getTombstoneKey() {
476 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
Mike Stump1eb44332009-09-09 15:08:12 +0000477 DenseMapInfo<Selector>::getTombstoneKey());
Ted Kremenek553cf182008-06-25 21:21:56 +0000478 }
Mike Stump1eb44332009-09-09 15:08:12 +0000479
Ted Kremenek553cf182008-06-25 21:21:56 +0000480 static unsigned getHashValue(const ObjCSummaryKey &V) {
Benjamin Kramer28b23072012-05-27 13:28:44 +0000481 typedef std::pair<IdentifierInfo*, Selector> PairTy;
482 return DenseMapInfo<PairTy>::getHashValue(PairTy(V.getIdentifier(),
483 V.getSelector()));
Ted Kremenek553cf182008-06-25 21:21:56 +0000484 }
Mike Stump1eb44332009-09-09 15:08:12 +0000485
Ted Kremenek553cf182008-06-25 21:21:56 +0000486 static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
Benjamin Kramer28b23072012-05-27 13:28:44 +0000487 return LHS.getIdentifier() == RHS.getIdentifier() &&
488 LHS.getSelector() == RHS.getSelector();
Ted Kremenek553cf182008-06-25 21:21:56 +0000489 }
Mike Stump1eb44332009-09-09 15:08:12 +0000490
Ted Kremenek553cf182008-06-25 21:21:56 +0000491};
Chris Lattner06159e82009-12-15 07:26:51 +0000492template <>
493struct isPodLike<ObjCSummaryKey> { static const bool value = true; };
Ted Kremenek4f22a782008-06-23 23:30:29 +0000494} // end llvm namespace
Mike Stump1eb44332009-09-09 15:08:12 +0000495
Ted Kremenek4f22a782008-06-23 23:30:29 +0000496namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000497class ObjCSummaryCache {
Ted Kremenek93edbc52011-10-05 23:54:29 +0000498 typedef llvm::DenseMap<ObjCSummaryKey, const RetainSummary *> MapTy;
Ted Kremenek553cf182008-06-25 21:21:56 +0000499 MapTy M;
500public:
501 ObjCSummaryCache() {}
Mike Stump1eb44332009-09-09 15:08:12 +0000502
Ted Kremenek93edbc52011-10-05 23:54:29 +0000503 const RetainSummary * find(const ObjCInterfaceDecl *D, Selector S) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000504 // Do a lookup with the (D,S) pair. If we find a match return
505 // the iterator.
506 ObjCSummaryKey K(D, S);
507 MapTy::iterator I = M.find(K);
Mike Stump1eb44332009-09-09 15:08:12 +0000508
Jordan Rose4531b7d2012-07-02 19:27:43 +0000509 if (I != M.end())
Ted Kremenek614cc542009-07-21 23:27:57 +0000510 return I->second;
Jordan Rose4531b7d2012-07-02 19:27:43 +0000511 if (!D)
512 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +0000513
Ted Kremenek553cf182008-06-25 21:21:56 +0000514 // Walk the super chain. If we find a hit with a parent, we'll end
515 // up returning that summary. We actually allow that key (null,S), as
516 // we cache summaries for the null ObjCInterfaceDecl* to allow us to
517 // generate initial summaries without having to worry about NSObject
518 // being declared.
519 // FIXME: We may change this at some point.
Ted Kremenek9c378f72011-08-12 23:37:29 +0000520 for (ObjCInterfaceDecl *C=D->getSuperClass() ;; C=C->getSuperClass()) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000521 if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
522 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000523
Ted Kremenek553cf182008-06-25 21:21:56 +0000524 if (!C)
Ted Kremenek614cc542009-07-21 23:27:57 +0000525 return NULL;
Ted Kremenek553cf182008-06-25 21:21:56 +0000526 }
Mike Stump1eb44332009-09-09 15:08:12 +0000527
528 // Cache the summary with original key to make the next lookup faster
Ted Kremenek553cf182008-06-25 21:21:56 +0000529 // and return the iterator.
Ted Kremenek93edbc52011-10-05 23:54:29 +0000530 const RetainSummary *Summ = I->second;
Ted Kremenek614cc542009-07-21 23:27:57 +0000531 M[K] = Summ;
532 return Summ;
Ted Kremenek553cf182008-06-25 21:21:56 +0000533 }
Mike Stump1eb44332009-09-09 15:08:12 +0000534
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000535 const RetainSummary *find(IdentifierInfo* II, Selector S) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000536 // FIXME: Class method lookup. Right now we dont' have a good way
537 // of going between IdentifierInfo* and the class hierarchy.
Ted Kremenek614cc542009-07-21 23:27:57 +0000538 MapTy::iterator I = M.find(ObjCSummaryKey(II, S));
Mike Stump1eb44332009-09-09 15:08:12 +0000539
Ted Kremenek614cc542009-07-21 23:27:57 +0000540 if (I == M.end())
541 I = M.find(ObjCSummaryKey(S));
Mike Stump1eb44332009-09-09 15:08:12 +0000542
Ted Kremenek614cc542009-07-21 23:27:57 +0000543 return I == M.end() ? NULL : I->second;
Ted Kremenek553cf182008-06-25 21:21:56 +0000544 }
Mike Stump1eb44332009-09-09 15:08:12 +0000545
Ted Kremenek93edbc52011-10-05 23:54:29 +0000546 const RetainSummary *& operator[](ObjCSummaryKey K) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000547 return M[K];
548 }
Mike Stump1eb44332009-09-09 15:08:12 +0000549
Ted Kremenek93edbc52011-10-05 23:54:29 +0000550 const RetainSummary *& operator[](Selector S) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000551 return M[ ObjCSummaryKey(S) ];
552 }
Mike Stump1eb44332009-09-09 15:08:12 +0000553};
Ted Kremenek553cf182008-06-25 21:21:56 +0000554} // end anonymous namespace
555
556//===----------------------------------------------------------------------===//
557// Data structures for managing collections of summaries.
558//===----------------------------------------------------------------------===//
559
560namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000561class RetainSummaryManager {
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000562
563 //==-----------------------------------------------------------------==//
564 // Typedefs.
565 //==-----------------------------------------------------------------==//
Mike Stump1eb44332009-09-09 15:08:12 +0000566
Ted Kremenek93edbc52011-10-05 23:54:29 +0000567 typedef llvm::DenseMap<const FunctionDecl*, const RetainSummary *>
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000568 FuncSummariesTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000569
Ted Kremenek4f22a782008-06-23 23:30:29 +0000570 typedef ObjCSummaryCache ObjCMethodSummariesTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000571
Jordy Roseef945882012-03-18 01:26:10 +0000572 typedef llvm::FoldingSetNodeWrapper<RetainSummary> CachedSummaryNode;
573
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000574 //==-----------------------------------------------------------------==//
575 // Data.
576 //==-----------------------------------------------------------------==//
Mike Stump1eb44332009-09-09 15:08:12 +0000577
Ted Kremenek553cf182008-06-25 21:21:56 +0000578 /// Ctx - The ASTContext object for the analyzed ASTs.
Ted Kremenek9c378f72011-08-12 23:37:29 +0000579 ASTContext &Ctx;
Ted Kremenek179064e2008-07-01 17:21:27 +0000580
Ted Kremenek553cf182008-06-25 21:21:56 +0000581 /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
Ted Kremenek377e2302008-04-29 05:33:51 +0000582 const bool GCEnabled;
Mike Stump1eb44332009-09-09 15:08:12 +0000583
John McCallf85e1932011-06-15 23:02:42 +0000584 /// Records whether or not the analyzed code runs in ARC mode.
585 const bool ARCEnabled;
586
Ted Kremenek553cf182008-06-25 21:21:56 +0000587 /// FuncSummaries - A map from FunctionDecls to summaries.
Mike Stump1eb44332009-09-09 15:08:12 +0000588 FuncSummariesTy FuncSummaries;
589
Ted Kremenek553cf182008-06-25 21:21:56 +0000590 /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
591 /// to summaries.
Ted Kremenek1f180c32008-06-23 22:21:20 +0000592 ObjCMethodSummariesTy ObjCClassMethodSummaries;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000593
Ted Kremenek553cf182008-06-25 21:21:56 +0000594 /// ObjCMethodSummaries - A map from selectors to summaries.
Ted Kremenek1f180c32008-06-23 22:21:20 +0000595 ObjCMethodSummariesTy ObjCMethodSummaries;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000596
Ted Kremenek553cf182008-06-25 21:21:56 +0000597 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
598 /// and all other data used by the checker.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000599 llvm::BumpPtrAllocator BPAlloc;
Mike Stump1eb44332009-09-09 15:08:12 +0000600
Ted Kremenekb77449c2009-05-03 05:20:50 +0000601 /// AF - A factory for ArgEffects objects.
Mike Stump1eb44332009-09-09 15:08:12 +0000602 ArgEffects::Factory AF;
603
Ted Kremenek553cf182008-06-25 21:21:56 +0000604 /// ScratchArgs - A holding buffer for construct ArgEffects.
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000605 ArgEffects ScratchArgs;
Mike Stump1eb44332009-09-09 15:08:12 +0000606
Ted Kremenekec315332009-05-07 23:40:42 +0000607 /// ObjCAllocRetE - Default return effect for methods returning Objective-C
608 /// objects.
609 RetEffect ObjCAllocRetE;
Ted Kremenek547d4952009-06-05 23:18:01 +0000610
Mike Stump1eb44332009-09-09 15:08:12 +0000611 /// ObjCInitRetE - Default return effect for init methods returning
Ted Kremenekac02f202009-08-20 05:13:36 +0000612 /// Objective-C objects.
Ted Kremenek547d4952009-06-05 23:18:01 +0000613 RetEffect ObjCInitRetE;
Mike Stump1eb44332009-09-09 15:08:12 +0000614
Jordy Roseef945882012-03-18 01:26:10 +0000615 /// SimpleSummaries - Used for uniquing summaries that don't have special
616 /// effects.
617 llvm::FoldingSet<CachedSummaryNode> SimpleSummaries;
Mike Stump1eb44332009-09-09 15:08:12 +0000618
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000619 //==-----------------------------------------------------------------==//
620 // Methods.
621 //==-----------------------------------------------------------------==//
Mike Stump1eb44332009-09-09 15:08:12 +0000622
Ted Kremenek553cf182008-06-25 21:21:56 +0000623 /// getArgEffects - Returns a persistent ArgEffects object based on the
624 /// data in ScratchArgs.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000625 ArgEffects getArgEffects();
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000626
Mike Stump1eb44332009-09-09 15:08:12 +0000627 enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
Ted Kremenek93edbc52011-10-05 23:54:29 +0000628
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000629 const RetainSummary *getUnarySummary(const FunctionType* FT,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000630 UnaryFuncKind func);
Mike Stump1eb44332009-09-09 15:08:12 +0000631
Ted Kremenek0507f7e2012-01-04 00:35:45 +0000632 const RetainSummary *getCFSummaryCreateRule(const FunctionDecl *FD);
633 const RetainSummary *getCFSummaryGetRule(const FunctionDecl *FD);
634 const RetainSummary *getCFCreateGetRuleSummary(const FunctionDecl *FD);
Mike Stump1eb44332009-09-09 15:08:12 +0000635
Jordy Roseef945882012-03-18 01:26:10 +0000636 const RetainSummary *getPersistentSummary(const RetainSummary &OldSumm);
Ted Kremenek706522f2008-10-29 04:07:07 +0000637
Jordy Roseef945882012-03-18 01:26:10 +0000638 const RetainSummary *getPersistentSummary(RetEffect RetEff,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000639 ArgEffect ReceiverEff = DoNothing,
640 ArgEffect DefaultEff = MayEscape) {
Jordy Roseef945882012-03-18 01:26:10 +0000641 RetainSummary Summ(getArgEffects(), RetEff, DefaultEff, ReceiverEff);
642 return getPersistentSummary(Summ);
643 }
644
Ted Kremenekc91fdf62012-05-08 00:12:09 +0000645 const RetainSummary *getDoNothingSummary() {
646 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
647 }
648
Jordy Roseef945882012-03-18 01:26:10 +0000649 const RetainSummary *getDefaultSummary() {
650 return getPersistentSummary(RetEffect::MakeNoRet(),
651 DoNothing, MayEscape);
Ted Kremenek9c32d082008-05-06 00:30:21 +0000652 }
Mike Stump1eb44332009-09-09 15:08:12 +0000653
Ted Kremenek93edbc52011-10-05 23:54:29 +0000654 const RetainSummary *getPersistentStopSummary() {
Jordy Roseef945882012-03-18 01:26:10 +0000655 return getPersistentSummary(RetEffect::MakeNoRet(),
656 StopTracking, StopTracking);
Mike Stump1eb44332009-09-09 15:08:12 +0000657 }
Ted Kremenekb3095252008-05-06 04:20:12 +0000658
Ted Kremenek1f180c32008-06-23 22:21:20 +0000659 void InitializeClassMethodSummaries();
660 void InitializeMethodSummaries();
Ted Kremenek896cd9d2008-10-23 01:56:15 +0000661private:
Ted Kremenek93edbc52011-10-05 23:54:29 +0000662 void addNSObjectClsMethSummary(Selector S, const RetainSummary *Summ) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000663 ObjCClassMethodSummaries[S] = Summ;
664 }
Mike Stump1eb44332009-09-09 15:08:12 +0000665
Ted Kremenek93edbc52011-10-05 23:54:29 +0000666 void addNSObjectMethSummary(Selector S, const RetainSummary *Summ) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000667 ObjCMethodSummaries[S] = Summ;
668 }
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +0000669
Ted Kremeneka9797122012-02-18 21:37:48 +0000670 void addClassMethSummary(const char* Cls, const char* name,
671 const RetainSummary *Summ, bool isNullary = true) {
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +0000672 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
Ted Kremeneka9797122012-02-18 21:37:48 +0000673 Selector S = isNullary ? GetNullarySelector(name, Ctx)
674 : GetUnarySelector(name, Ctx);
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +0000675 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
676 }
Mike Stump1eb44332009-09-09 15:08:12 +0000677
Ted Kremenek6c4becb2009-02-25 02:54:57 +0000678 void addInstMethSummary(const char* Cls, const char* nullaryName,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000679 const RetainSummary *Summ) {
Ted Kremenek6c4becb2009-02-25 02:54:57 +0000680 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
681 Selector S = GetNullarySelector(nullaryName, Ctx);
682 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
683 }
Mike Stump1eb44332009-09-09 15:08:12 +0000684
Ted Kremenekde4d5332009-04-24 17:50:11 +0000685 Selector generateSelector(va_list argp) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000686 SmallVector<IdentifierInfo*, 10> II;
Ted Kremenekde4d5332009-04-24 17:50:11 +0000687
Ted Kremenek9e476de2008-08-12 18:30:56 +0000688 while (const char* s = va_arg(argp, const char*))
689 II.push_back(&Ctx.Idents.get(s));
Ted Kremenekde4d5332009-04-24 17:50:11 +0000690
Mike Stump1eb44332009-09-09 15:08:12 +0000691 return Ctx.Selectors.getSelector(II.size(), &II[0]);
Ted Kremenekde4d5332009-04-24 17:50:11 +0000692 }
Mike Stump1eb44332009-09-09 15:08:12 +0000693
Ted Kremenekde4d5332009-04-24 17:50:11 +0000694 void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy& Summaries,
Ted Kremenek93edbc52011-10-05 23:54:29 +0000695 const RetainSummary * Summ, va_list argp) {
Ted Kremenekde4d5332009-04-24 17:50:11 +0000696 Selector S = generateSelector(argp);
697 Summaries[ObjCSummaryKey(ClsII, S)] = Summ;
Ted Kremenek70a733e2008-07-18 17:24:20 +0000698 }
Mike Stump1eb44332009-09-09 15:08:12 +0000699
Ted Kremenek93edbc52011-10-05 23:54:29 +0000700 void addInstMethSummary(const char* Cls, const RetainSummary * Summ, ...) {
Ted Kremenekaf9dc272008-08-12 18:48:50 +0000701 va_list argp;
702 va_start(argp, Summ);
Ted Kremenekde4d5332009-04-24 17:50:11 +0000703 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Mike Stump1eb44332009-09-09 15:08:12 +0000704 va_end(argp);
Ted Kremenekaf9dc272008-08-12 18:48:50 +0000705 }
Mike Stump1eb44332009-09-09 15:08:12 +0000706
Ted Kremenek93edbc52011-10-05 23:54:29 +0000707 void addClsMethSummary(const char* Cls, const RetainSummary * Summ, ...) {
Ted Kremenekde4d5332009-04-24 17:50:11 +0000708 va_list argp;
709 va_start(argp, Summ);
710 addMethodSummary(&Ctx.Idents.get(Cls),ObjCClassMethodSummaries, Summ, argp);
711 va_end(argp);
712 }
Mike Stump1eb44332009-09-09 15:08:12 +0000713
Ted Kremenek93edbc52011-10-05 23:54:29 +0000714 void addClsMethSummary(IdentifierInfo *II, const RetainSummary * Summ, ...) {
Ted Kremenekde4d5332009-04-24 17:50:11 +0000715 va_list argp;
716 va_start(argp, Summ);
717 addMethodSummary(II, ObjCClassMethodSummaries, Summ, argp);
718 va_end(argp);
719 }
720
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000721public:
Mike Stump1eb44332009-09-09 15:08:12 +0000722
Ted Kremenek9c378f72011-08-12 23:37:29 +0000723 RetainSummaryManager(ASTContext &ctx, bool gcenabled, bool usesARC)
Ted Kremenek179064e2008-07-01 17:21:27 +0000724 : Ctx(ctx),
John McCallf85e1932011-06-15 23:02:42 +0000725 GCEnabled(gcenabled),
726 ARCEnabled(usesARC),
727 AF(BPAlloc), ScratchArgs(AF.getEmptyMap()),
728 ObjCAllocRetE(gcenabled
729 ? RetEffect::MakeGCNotOwned()
730 : (usesARC ? RetEffect::MakeARCNotOwned()
731 : RetEffect::MakeOwned(RetEffect::ObjC, true))),
732 ObjCInitRetE(gcenabled
733 ? RetEffect::MakeGCNotOwned()
734 : (usesARC ? RetEffect::MakeARCNotOwned()
Jordy Roseef945882012-03-18 01:26:10 +0000735 : RetEffect::MakeOwnedWhenTrackedReceiver())) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000736 InitializeClassMethodSummaries();
737 InitializeMethodSummaries();
738 }
Mike Stump1eb44332009-09-09 15:08:12 +0000739
Jordan Rose4531b7d2012-07-02 19:27:43 +0000740 const RetainSummary *getSummary(const CallEvent &Call,
741 ProgramStateRef State = 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000742
Jordan Rose4531b7d2012-07-02 19:27:43 +0000743 const RetainSummary *getFunctionSummary(const FunctionDecl *FD);
744
745 const RetainSummary *getMethodSummary(Selector S, const ObjCInterfaceDecl *ID,
Jordy Rosef3aae582012-03-17 21:13:07 +0000746 const ObjCMethodDecl *MD,
747 QualType RetTy,
748 ObjCMethodSummariesTy &CachedSummaries);
749
Jordan Rosecde8cdb2012-07-02 19:27:56 +0000750 const RetainSummary *getInstanceMethodSummary(const ObjCMethodCall &M,
Jordan Rose4531b7d2012-07-02 19:27:43 +0000751 ProgramStateRef State);
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000752
Jordan Rosecde8cdb2012-07-02 19:27:56 +0000753 const RetainSummary *getClassMethodSummary(const ObjCMethodCall &M) {
Jordan Rose4531b7d2012-07-02 19:27:43 +0000754 assert(!M.isInstanceMessage());
755 const ObjCInterfaceDecl *Class = M.getReceiverInterface();
Mike Stump1eb44332009-09-09 15:08:12 +0000756
Jordan Rose4531b7d2012-07-02 19:27:43 +0000757 return getMethodSummary(M.getSelector(), Class, M.getDecl(),
758 M.getResultType(), ObjCClassMethodSummaries);
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +0000759 }
Ted Kremenek552333c2009-04-29 17:17:48 +0000760
761 /// getMethodSummary - This version of getMethodSummary is used to query
762 /// the summary for the current method being analyzed.
Ted Kremenek93edbc52011-10-05 23:54:29 +0000763 const RetainSummary *getMethodSummary(const ObjCMethodDecl *MD) {
Ted Kremeneka8833552009-04-29 23:03:22 +0000764 const ObjCInterfaceDecl *ID = MD->getClassInterface();
Ted Kremenek70a65762009-04-30 05:41:14 +0000765 Selector S = MD->getSelector();
Ted Kremenek552333c2009-04-29 17:17:48 +0000766 QualType ResultTy = MD->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +0000767
Jordy Rosef3aae582012-03-17 21:13:07 +0000768 ObjCMethodSummariesTy *CachedSummaries;
Ted Kremenek552333c2009-04-29 17:17:48 +0000769 if (MD->isInstanceMethod())
Jordy Rosef3aae582012-03-17 21:13:07 +0000770 CachedSummaries = &ObjCMethodSummaries;
Ted Kremenek552333c2009-04-29 17:17:48 +0000771 else
Jordy Rosef3aae582012-03-17 21:13:07 +0000772 CachedSummaries = &ObjCClassMethodSummaries;
773
Jordan Rose4531b7d2012-07-02 19:27:43 +0000774 return getMethodSummary(S, ID, MD, ResultTy, *CachedSummaries);
Ted Kremenek552333c2009-04-29 17:17:48 +0000775 }
Mike Stump1eb44332009-09-09 15:08:12 +0000776
Jordy Rosef3aae582012-03-17 21:13:07 +0000777 const RetainSummary *getStandardMethodSummary(const ObjCMethodDecl *MD,
Jordan Rose4531b7d2012-07-02 19:27:43 +0000778 Selector S, QualType RetTy);
Ted Kremeneka8833552009-04-29 23:03:22 +0000779
Ted Kremenek93edbc52011-10-05 23:54:29 +0000780 void updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenek4dd8fb42009-05-09 02:58:13 +0000781 const ObjCMethodDecl *MD);
782
Ted Kremenek93edbc52011-10-05 23:54:29 +0000783 void updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenek4dd8fb42009-05-09 02:58:13 +0000784 const FunctionDecl *FD);
785
Jordan Rose4531b7d2012-07-02 19:27:43 +0000786 void updateSummaryForCall(const RetainSummary *&Summ,
787 const CallEvent &Call);
788
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000789 bool isGCEnabled() const { return GCEnabled; }
Mike Stump1eb44332009-09-09 15:08:12 +0000790
John McCallf85e1932011-06-15 23:02:42 +0000791 bool isARCEnabled() const { return ARCEnabled; }
792
793 bool isARCorGCEnabled() const { return GCEnabled || ARCEnabled; }
Jordan Rose4531b7d2012-07-02 19:27:43 +0000794
795 RetEffect getObjAllocRetEffect() const { return ObjCAllocRetE; }
796
797 friend class RetainSummaryTemplate;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000798};
Mike Stump1eb44332009-09-09 15:08:12 +0000799
Jordy Rose0fe62f82011-08-24 09:02:37 +0000800// Used to avoid allocating long-term (BPAlloc'd) memory for default retain
801// summaries. If a function or method looks like it has a default summary, but
802// it has annotations, the annotations are added to the stack-based template
803// and then copied into managed memory.
804class RetainSummaryTemplate {
805 RetainSummaryManager &Manager;
Ted Kremenek93edbc52011-10-05 23:54:29 +0000806 const RetainSummary *&RealSummary;
Jordy Rose0fe62f82011-08-24 09:02:37 +0000807 RetainSummary ScratchSummary;
808 bool Accessed;
809public:
Jordan Rose4531b7d2012-07-02 19:27:43 +0000810 RetainSummaryTemplate(const RetainSummary *&real, RetainSummaryManager &mgr)
811 : Manager(mgr), RealSummary(real), ScratchSummary(*real), Accessed(false) {}
Jordy Rose0fe62f82011-08-24 09:02:37 +0000812
813 ~RetainSummaryTemplate() {
Ted Kremenek93edbc52011-10-05 23:54:29 +0000814 if (Accessed)
Jordy Roseef945882012-03-18 01:26:10 +0000815 RealSummary = Manager.getPersistentSummary(ScratchSummary);
Jordy Rose0fe62f82011-08-24 09:02:37 +0000816 }
817
818 RetainSummary &operator*() {
819 Accessed = true;
Ted Kremenek93edbc52011-10-05 23:54:29 +0000820 return ScratchSummary;
Jordy Rose0fe62f82011-08-24 09:02:37 +0000821 }
822
823 RetainSummary *operator->() {
824 Accessed = true;
Ted Kremenek93edbc52011-10-05 23:54:29 +0000825 return &ScratchSummary;
Jordy Rose0fe62f82011-08-24 09:02:37 +0000826 }
827};
828
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000829} // end anonymous namespace
830
831//===----------------------------------------------------------------------===//
832// Implementation of checker data structures.
833//===----------------------------------------------------------------------===//
834
Ted Kremenekb77449c2009-05-03 05:20:50 +0000835ArgEffects RetainSummaryManager::getArgEffects() {
836 ArgEffects AE = ScratchArgs;
Ted Kremenek3baf6722010-11-24 00:54:37 +0000837 ScratchArgs = AF.getEmptyMap();
Ted Kremenekb77449c2009-05-03 05:20:50 +0000838 return AE;
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000839}
840
Ted Kremenek93edbc52011-10-05 23:54:29 +0000841const RetainSummary *
Jordy Roseef945882012-03-18 01:26:10 +0000842RetainSummaryManager::getPersistentSummary(const RetainSummary &OldSumm) {
843 // Unique "simple" summaries -- those without ArgEffects.
844 if (OldSumm.isSimple()) {
845 llvm::FoldingSetNodeID ID;
846 OldSumm.Profile(ID);
847
848 void *Pos;
849 CachedSummaryNode *N = SimpleSummaries.FindNodeOrInsertPos(ID, Pos);
850
851 if (!N) {
852 N = (CachedSummaryNode *) BPAlloc.Allocate<CachedSummaryNode>();
853 new (N) CachedSummaryNode(OldSumm);
854 SimpleSummaries.InsertNode(N, Pos);
855 }
856
857 return &N->getValue();
858 }
859
Ted Kremenek93edbc52011-10-05 23:54:29 +0000860 RetainSummary *Summ = (RetainSummary *) BPAlloc.Allocate<RetainSummary>();
Jordy Roseef945882012-03-18 01:26:10 +0000861 new (Summ) RetainSummary(OldSumm);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000862 return Summ;
863}
864
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000865//===----------------------------------------------------------------------===//
866// Summary creation for functions (largely uses of Core Foundation).
867//===----------------------------------------------------------------------===//
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000868
Ted Kremenek9c378f72011-08-12 23:37:29 +0000869static bool isRetain(const FunctionDecl *FD, StringRef FName) {
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000870 return FName.endswith("Retain");
Ted Kremenek12619382009-01-12 21:45:02 +0000871}
872
Ted Kremenek9c378f72011-08-12 23:37:29 +0000873static bool isRelease(const FunctionDecl *FD, StringRef FName) {
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000874 return FName.endswith("Release");
Ted Kremenek12619382009-01-12 21:45:02 +0000875}
876
Jordy Rose76c506f2011-08-21 21:58:18 +0000877static bool isMakeCollectable(const FunctionDecl *FD, StringRef FName) {
878 // FIXME: Remove FunctionDecl parameter.
879 // FIXME: Is it really okay if MakeCollectable isn't a suffix?
880 return FName.find("MakeCollectable") != StringRef::npos;
881}
882
Jordan Rose4531b7d2012-07-02 19:27:43 +0000883static ArgEffect getStopTrackingEquivalent(ArgEffect E) {
884 switch (E) {
885 case DoNothing:
886 case Autorelease:
887 case DecRefBridgedTransfered:
888 case IncRef:
889 case IncRefMsg:
890 case MakeCollectable:
891 case MayEscape:
892 case NewAutoreleasePool:
893 case StopTracking:
894 return StopTracking;
895 case DecRef:
896 case DecRefAndStopTracking:
897 return DecRefAndStopTracking;
898 case DecRefMsg:
899 case DecRefMsgAndStopTracking:
900 return DecRefMsgAndStopTracking;
901 case Dealloc:
902 return Dealloc;
903 }
904
905 llvm_unreachable("Unknown ArgEffect kind");
906}
907
908void RetainSummaryManager::updateSummaryForCall(const RetainSummary *&S,
909 const CallEvent &Call) {
910 if (Call.hasNonZeroCallbackArg()) {
911 ArgEffect RecEffect = getStopTrackingEquivalent(S->getReceiverEffect());
912 ArgEffect DefEffect = getStopTrackingEquivalent(S->getDefaultArgEffect());
913
914 ArgEffects CustomArgEffects = S->getArgEffects();
915 for (ArgEffects::iterator I = CustomArgEffects.begin(),
916 E = CustomArgEffects.end();
917 I != E; ++I) {
918 ArgEffect Translated = getStopTrackingEquivalent(I->second);
919 if (Translated != DefEffect)
920 ScratchArgs = AF.add(ScratchArgs, I->first, Translated);
921 }
922
923 RetEffect RE = RetEffect::MakeNoRet();
924
925 // Special cases where the callback argument CANNOT free the return value.
926 // This can generally only happen if we know that the callback will only be
927 // called when the return value is already being deallocated.
928 if (const FunctionCall *FC = dyn_cast<FunctionCall>(&Call)) {
929 IdentifierInfo *Name = FC->getDecl()->getIdentifier();
930
931 // This callback frees the associated buffer.
932 if (Name->isStr("CGBitmapContextCreateWithData"))
933 RE = S->getRetEffect();
934 }
935
936 S = getPersistentSummary(RE, RecEffect, DefEffect);
937 }
938}
939
Anna Zaks58822c42012-05-04 22:18:39 +0000940const RetainSummary *
Jordan Rose4531b7d2012-07-02 19:27:43 +0000941RetainSummaryManager::getSummary(const CallEvent &Call,
942 ProgramStateRef State) {
943 const RetainSummary *Summ;
944 switch (Call.getKind()) {
945 case CE_Function:
946 Summ = getFunctionSummary(cast<FunctionCall>(Call).getDecl());
947 break;
948 case CE_CXXMember:
949 case CE_Block:
950 case CE_CXXConstructor:
951 // FIXME: These calls are currently unsupported.
952 return getPersistentStopSummary();
Jordan Rosecde8cdb2012-07-02 19:27:56 +0000953 case CE_ObjCMessage:
954 case CE_ObjCPropertyAccess: {
955 const ObjCMethodCall &Msg = cast<ObjCMethodCall>(Call);
Jordan Rose4531b7d2012-07-02 19:27:43 +0000956 if (Msg.isInstanceMessage())
957 Summ = getInstanceMethodSummary(Msg, State);
958 else
959 Summ = getClassMethodSummary(Msg);
960 break;
961 }
962 }
963
964 updateSummaryForCall(Summ, Call);
965
966 assert(Summ && "Unknown call type?");
967 return Summ;
968}
969
970const RetainSummary *
971RetainSummaryManager::getFunctionSummary(const FunctionDecl *FD) {
972 // If we don't know what function we're calling, use our default summary.
973 if (!FD)
974 return getDefaultSummary();
975
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000976 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000977 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000978 if (I != FuncSummaries.end())
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000979 return I->second;
980
Ted Kremeneke401a0c2009-05-04 15:34:07 +0000981 // No summary? Generate one.
Ted Kremenek93edbc52011-10-05 23:54:29 +0000982 const RetainSummary *S = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000983
Ted Kremenek37d785b2008-07-15 16:50:12 +0000984 do {
Ted Kremenek12619382009-01-12 21:45:02 +0000985 // We generate "stop" summaries for implicitly defined functions.
986 if (FD->isImplicit()) {
987 S = getPersistentStopSummary();
988 break;
Ted Kremenek37d785b2008-07-15 16:50:12 +0000989 }
Mike Stump1eb44332009-09-09 15:08:12 +0000990
John McCall183700f2009-09-21 23:43:11 +0000991 // [PR 3337] Use 'getAs<FunctionType>' to strip away any typedefs on the
Ted Kremenek99890652009-01-16 18:40:33 +0000992 // function's type.
John McCall183700f2009-09-21 23:43:11 +0000993 const FunctionType* FT = FD->getType()->getAs<FunctionType>();
Ted Kremenek48c6d182009-12-16 06:06:43 +0000994 const IdentifierInfo *II = FD->getIdentifier();
995 if (!II)
996 break;
Benjamin Kramerb6f3c702010-02-08 18:38:55 +0000997
998 StringRef FName = II->getName();
Mike Stump1eb44332009-09-09 15:08:12 +0000999
Ted Kremenekbf0a4dd2009-03-05 22:11:14 +00001000 // Strip away preceding '_'. Doing this here will effect all the checks
1001 // down below.
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001002 FName = FName.substr(FName.find_first_not_of('_'));
Mike Stump1eb44332009-09-09 15:08:12 +00001003
Ted Kremenek12619382009-01-12 21:45:02 +00001004 // Inspect the result type.
1005 QualType RetTy = FT->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00001006
Ted Kremenek12619382009-01-12 21:45:02 +00001007 // FIXME: This should all be refactored into a chain of "summary lookup"
1008 // filters.
Ted Kremenek008636a2009-10-14 00:27:24 +00001009 assert(ScratchArgs.isEmpty());
Ted Kremenek39d88b02009-06-15 20:36:07 +00001010
Ted Kremenekbefc6d22012-04-26 04:32:23 +00001011 if (FName == "pthread_create" || FName == "pthread_setspecific") {
1012 // Part of: <rdar://problem/7299394> and <rdar://problem/11282706>.
1013 // This will be addressed better with IPA.
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001014 S = getPersistentStopSummary();
1015 } else if (FName == "NSMakeCollectable") {
1016 // Handle: id NSMakeCollectable(CFTypeRef)
1017 S = (RetTy->isObjCIdType())
1018 ? getUnarySummary(FT, cfmakecollectable)
1019 : getPersistentStopSummary();
1020 } else if (FName == "IOBSDNameMatching" ||
1021 FName == "IOServiceMatching" ||
1022 FName == "IOServiceNameMatching" ||
Ted Kremenek537dd3a2012-05-01 05:28:27 +00001023 FName == "IORegistryEntrySearchCFProperty" ||
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001024 FName == "IORegistryEntryIDMatching" ||
1025 FName == "IOOpenFirmwarePathMatching") {
1026 // Part of <rdar://problem/6961230>. (IOKit)
1027 // This should be addressed using a API table.
1028 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1029 DoNothing, DoNothing);
1030 } else if (FName == "IOServiceGetMatchingService" ||
1031 FName == "IOServiceGetMatchingServices") {
1032 // FIXES: <rdar://problem/6326900>
1033 // This should be addressed using a API table. This strcmp is also
1034 // a little gross, but there is no need to super optimize here.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001035 ScratchArgs = AF.add(ScratchArgs, 1, DecRef);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001036 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1037 } else if (FName == "IOServiceAddNotification" ||
1038 FName == "IOServiceAddMatchingNotification") {
1039 // Part of <rdar://problem/6961230>. (IOKit)
1040 // This should be addressed using a API table.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001041 ScratchArgs = AF.add(ScratchArgs, 2, DecRef);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001042 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1043 } else if (FName == "CVPixelBufferCreateWithBytes") {
1044 // FIXES: <rdar://problem/7283567>
1045 // Eventually this can be improved by recognizing that the pixel
1046 // buffer passed to CVPixelBufferCreateWithBytes is released via
1047 // a callback and doing full IPA to make sure this is done correctly.
1048 // FIXME: This function has an out parameter that returns an
1049 // allocated object.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001050 ScratchArgs = AF.add(ScratchArgs, 7, StopTracking);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001051 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1052 } else if (FName == "CGBitmapContextCreateWithData") {
1053 // FIXES: <rdar://problem/7358899>
1054 // Eventually this can be improved by recognizing that 'releaseInfo'
1055 // passed to CGBitmapContextCreateWithData is released via
1056 // a callback and doing full IPA to make sure this is done correctly.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001057 ScratchArgs = AF.add(ScratchArgs, 8, StopTracking);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001058 S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1059 DoNothing, DoNothing);
1060 } else if (FName == "CVPixelBufferCreateWithPlanarBytes") {
1061 // FIXES: <rdar://problem/7283567>
1062 // Eventually this can be improved by recognizing that the pixel
1063 // buffer passed to CVPixelBufferCreateWithPlanarBytes is released
1064 // via a callback and doing full IPA to make sure this is done
1065 // correctly.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001066 ScratchArgs = AF.add(ScratchArgs, 12, StopTracking);
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001067 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenek06911d42012-03-22 06:29:41 +00001068 } else if (FName == "dispatch_set_context") {
1069 // <rdar://problem/11059275> - The analyzer currently doesn't have
1070 // a good way to reason about the finalizer function for libdispatch.
1071 // If we pass a context object that is memory managed, stop tracking it.
1072 // FIXME: this hack should possibly go away once we can handle
1073 // libdispatch finalizers.
1074 ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
1075 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenekc91fdf62012-05-08 00:12:09 +00001076 } else if (FName.startswith("NSLog")) {
1077 S = getDoNothingSummary();
Anna Zaks62a5c342012-03-30 05:48:16 +00001078 } else if (FName.startswith("NS") &&
1079 (FName.find("Insert") != StringRef::npos)) {
1080 // Whitelist NSXXInsertXX, for example NSMapInsertIfAbsent, since they can
1081 // be deallocated by NSMapRemove. (radar://11152419)
1082 ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
1083 ScratchArgs = AF.add(ScratchArgs, 2, StopTracking);
1084 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenekb04cb592009-06-11 18:17:24 +00001085 }
Mike Stump1eb44332009-09-09 15:08:12 +00001086
Ted Kremenekb04cb592009-06-11 18:17:24 +00001087 // Did we get a summary?
1088 if (S)
1089 break;
Ted Kremenek61991902009-03-17 22:43:44 +00001090
1091 // Enable this code once the semantics of NSDeallocateObject are resolved
1092 // for GC. <rdar://problem/6619988>
1093#if 0
1094 // Handle: NSDeallocateObject(id anObject);
1095 // This method does allow 'nil' (although we don't check it now).
Mike Stump1eb44332009-09-09 15:08:12 +00001096 if (strcmp(FName, "NSDeallocateObject") == 0) {
Ted Kremenek61991902009-03-17 22:43:44 +00001097 return RetTy == Ctx.VoidTy
1098 ? getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, Dealloc)
1099 : getPersistentStopSummary();
1100 }
1101#endif
Ted Kremenek12619382009-01-12 21:45:02 +00001102
1103 if (RetTy->isPointerType()) {
1104 // For CoreFoundation ('CF') types.
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001105 if (cocoa::isRefType(RetTy, "CF", FName)) {
Ted Kremenek12619382009-01-12 21:45:02 +00001106 if (isRetain(FD, FName))
1107 S = getUnarySummary(FT, cfretain);
Jordy Rose76c506f2011-08-21 21:58:18 +00001108 else if (isMakeCollectable(FD, FName))
Ted Kremenek12619382009-01-12 21:45:02 +00001109 S = getUnarySummary(FT, cfmakecollectable);
Mike Stump1eb44332009-09-09 15:08:12 +00001110 else
John McCall7df2ff42011-10-01 00:48:56 +00001111 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek12619382009-01-12 21:45:02 +00001112
1113 break;
1114 }
1115
1116 // For CoreGraphics ('CG') types.
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001117 if (cocoa::isRefType(RetTy, "CG", FName)) {
Ted Kremenek12619382009-01-12 21:45:02 +00001118 if (isRetain(FD, FName))
1119 S = getUnarySummary(FT, cfretain);
1120 else
John McCall7df2ff42011-10-01 00:48:56 +00001121 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek12619382009-01-12 21:45:02 +00001122
1123 break;
1124 }
1125
1126 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001127 if (cocoa::isRefType(RetTy, "DADisk") ||
1128 cocoa::isRefType(RetTy, "DADissenter") ||
1129 cocoa::isRefType(RetTy, "DASessionRef")) {
John McCall7df2ff42011-10-01 00:48:56 +00001130 S = getCFCreateGetRuleSummary(FD);
Ted Kremenek12619382009-01-12 21:45:02 +00001131 break;
1132 }
Mike Stump1eb44332009-09-09 15:08:12 +00001133
Ted Kremenek12619382009-01-12 21:45:02 +00001134 break;
1135 }
1136
1137 // Check for release functions, the only kind of functions that we care
1138 // about that don't return a pointer type.
1139 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
Ted Kremeneke7d03122010-02-08 16:45:01 +00001140 // Test for 'CGCF'.
Benjamin Kramerb6f3c702010-02-08 18:38:55 +00001141 FName = FName.substr(FName.startswith("CGCF") ? 4 : 2);
Ted Kremeneke7d03122010-02-08 16:45:01 +00001142
Ted Kremenekbf0a4dd2009-03-05 22:11:14 +00001143 if (isRelease(FD, FName))
Ted Kremenek12619382009-01-12 21:45:02 +00001144 S = getUnarySummary(FT, cfrelease);
1145 else {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001146 assert (ScratchArgs.isEmpty());
Ted Kremenek68189282009-01-29 22:45:13 +00001147 // Remaining CoreFoundation and CoreGraphics functions.
1148 // We use to assume that they all strictly followed the ownership idiom
1149 // and that ownership cannot be transferred. While this is technically
1150 // correct, many methods allow a tracked object to escape. For example:
1151 //
Mike Stump1eb44332009-09-09 15:08:12 +00001152 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
Ted Kremenek68189282009-01-29 22:45:13 +00001153 // CFDictionaryAddValue(y, key, x);
Mike Stump1eb44332009-09-09 15:08:12 +00001154 // CFRelease(x);
Ted Kremenek68189282009-01-29 22:45:13 +00001155 // ... it is okay to use 'x' since 'y' has a reference to it
1156 //
1157 // We handle this and similar cases with the follow heuristic. If the
Ted Kremenekc4843812009-08-20 00:57:22 +00001158 // function name contains "InsertValue", "SetValue", "AddValue",
1159 // "AppendValue", or "SetAttribute", then we assume that arguments may
1160 // "escape." This means that something else holds on to the object,
1161 // allowing it be used even after its local retain count drops to 0.
Benjamin Kramere45c1492010-01-11 19:46:28 +00001162 ArgEffect E = (StrInStrNoCase(FName, "InsertValue") != StringRef::npos||
1163 StrInStrNoCase(FName, "AddValue") != StringRef::npos ||
1164 StrInStrNoCase(FName, "SetValue") != StringRef::npos ||
1165 StrInStrNoCase(FName, "AppendValue") != StringRef::npos||
Benjamin Kramerc027e542010-01-11 20:15:06 +00001166 StrInStrNoCase(FName, "SetAttribute") != StringRef::npos)
Ted Kremenek68189282009-01-29 22:45:13 +00001167 ? MayEscape : DoNothing;
Mike Stump1eb44332009-09-09 15:08:12 +00001168
Ted Kremenek68189282009-01-29 22:45:13 +00001169 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek12619382009-01-12 21:45:02 +00001170 }
1171 }
Ted Kremenek37d785b2008-07-15 16:50:12 +00001172 }
1173 while (0);
Mike Stump1eb44332009-09-09 15:08:12 +00001174
Jordan Rose4531b7d2012-07-02 19:27:43 +00001175 // If we got all the way here without any luck, use a default summary.
1176 if (!S)
1177 S = getDefaultSummary();
1178
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001179 // Annotations override defaults.
Jordy Rose4df54fe2011-08-23 04:27:15 +00001180 updateSummaryFromAnnotations(S, FD);
Mike Stump1eb44332009-09-09 15:08:12 +00001181
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001182 FuncSummaries[FD] = S;
Mike Stump1eb44332009-09-09 15:08:12 +00001183 return S;
Ted Kremenek2fff37e2008-03-06 00:08:09 +00001184}
1185
Ted Kremenek93edbc52011-10-05 23:54:29 +00001186const RetainSummary *
John McCall7df2ff42011-10-01 00:48:56 +00001187RetainSummaryManager::getCFCreateGetRuleSummary(const FunctionDecl *FD) {
1188 if (coreFoundation::followsCreateRule(FD))
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001189 return getCFSummaryCreateRule(FD);
Mike Stump1eb44332009-09-09 15:08:12 +00001190
Ted Kremenekd368d712011-05-25 06:19:45 +00001191 return getCFSummaryGetRule(FD);
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001192}
1193
Ted Kremenek93edbc52011-10-05 23:54:29 +00001194const RetainSummary *
Ted Kremenek6ad315a2009-02-23 16:51:39 +00001195RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1196 UnaryFuncKind func) {
1197
Ted Kremenek12619382009-01-12 21:45:02 +00001198 // Sanity check that this is *really* a unary function. This can
1199 // happen if people do weird things.
Douglas Gregor72564e72009-02-26 23:50:07 +00001200 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
Ted Kremenek12619382009-01-12 21:45:02 +00001201 if (!FTP || FTP->getNumArgs() != 1)
1202 return getPersistentStopSummary();
Mike Stump1eb44332009-09-09 15:08:12 +00001203
Ted Kremenekb77449c2009-05-03 05:20:50 +00001204 assert (ScratchArgs.isEmpty());
Mike Stump1eb44332009-09-09 15:08:12 +00001205
Jordy Rose76c506f2011-08-21 21:58:18 +00001206 ArgEffect Effect;
Ted Kremenek377e2302008-04-29 05:33:51 +00001207 switch (func) {
Jordy Rose76c506f2011-08-21 21:58:18 +00001208 case cfretain: Effect = IncRef; break;
1209 case cfrelease: Effect = DecRef; break;
1210 case cfmakecollectable: Effect = MakeCollectable; break;
Ted Kremenek940b1d82008-04-10 23:44:06 +00001211 }
Jordy Rose76c506f2011-08-21 21:58:18 +00001212
1213 ScratchArgs = AF.add(ScratchArgs, 0, Effect);
1214 return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001215}
1216
Ted Kremenek93edbc52011-10-05 23:54:29 +00001217const RetainSummary *
Ted Kremenek9c378f72011-08-12 23:37:29 +00001218RetainSummaryManager::getCFSummaryCreateRule(const FunctionDecl *FD) {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001219 assert (ScratchArgs.isEmpty());
Mike Stump1eb44332009-09-09 15:08:12 +00001220
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001221 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001222}
1223
Ted Kremenek93edbc52011-10-05 23:54:29 +00001224const RetainSummary *
Ted Kremenek9c378f72011-08-12 23:37:29 +00001225RetainSummaryManager::getCFSummaryGetRule(const FunctionDecl *FD) {
Mike Stump1eb44332009-09-09 15:08:12 +00001226 assert (ScratchArgs.isEmpty());
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001227 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1228 DoNothing, DoNothing);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001229}
1230
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001231//===----------------------------------------------------------------------===//
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001232// Summary creation for Selectors.
1233//===----------------------------------------------------------------------===//
1234
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001235void
Ted Kremenek93edbc52011-10-05 23:54:29 +00001236RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001237 const FunctionDecl *FD) {
1238 if (!FD)
1239 return;
1240
Jordan Rose4531b7d2012-07-02 19:27:43 +00001241 assert(Summ && "Must have a summary to add annotations to.");
1242 RetainSummaryTemplate Template(Summ, *this);
Jordy Rose4df54fe2011-08-23 04:27:15 +00001243
Ted Kremenek11fe1752011-01-27 18:43:03 +00001244 // Effects on the parameters.
1245 unsigned parm_idx = 0;
1246 for (FunctionDecl::param_const_iterator pi = FD->param_begin(),
John McCall98b8f162011-04-06 09:02:12 +00001247 pe = FD->param_end(); pi != pe; ++pi, ++parm_idx) {
Ted Kremenek11fe1752011-01-27 18:43:03 +00001248 const ParmVarDecl *pd = *pi;
1249 if (pd->getAttr<NSConsumedAttr>()) {
Jordy Rose4df54fe2011-08-23 04:27:15 +00001250 if (!GCEnabled) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001251 Template->addArg(AF, parm_idx, DecRef);
Jordy Rose4df54fe2011-08-23 04:27:15 +00001252 }
1253 } else if (pd->getAttr<CFConsumedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001254 Template->addArg(AF, parm_idx, DecRef);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001255 }
1256 }
1257
Ted Kremenekb04cb592009-06-11 18:17:24 +00001258 QualType RetTy = FD->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00001259
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001260 // Determine if there is a special return effect for this method.
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001261 if (cocoa::isCocoaObjectRef(RetTy)) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001262 if (FD->getAttr<NSReturnsRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001263 Template->setRetEffect(ObjCAllocRetE);
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001264 }
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001265 else if (FD->getAttr<CFReturnsRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001266 Template->setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenekb04cb592009-06-11 18:17:24 +00001267 }
Ted Kremenek60411112010-02-18 00:06:12 +00001268 else if (FD->getAttr<NSReturnsNotRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001269 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::ObjC));
Ted Kremenek60411112010-02-18 00:06:12 +00001270 }
1271 else if (FD->getAttr<CFReturnsNotRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001272 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::CF));
Jordy Rose4df54fe2011-08-23 04:27:15 +00001273 }
1274 } else if (RetTy->getAs<PointerType>()) {
1275 if (FD->getAttr<CFReturnsRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001276 Template->setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
Jordy Rose4df54fe2011-08-23 04:27:15 +00001277 }
1278 else if (FD->getAttr<CFReturnsNotRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001279 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::CF));
Ted Kremenek60411112010-02-18 00:06:12 +00001280 }
Ted Kremenekb04cb592009-06-11 18:17:24 +00001281 }
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001282}
1283
1284void
Ted Kremenek93edbc52011-10-05 23:54:29 +00001285RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
1286 const ObjCMethodDecl *MD) {
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001287 if (!MD)
1288 return;
1289
Jordan Rose4531b7d2012-07-02 19:27:43 +00001290 assert(Summ && "Must have a valid summary to add annotations to");
1291 RetainSummaryTemplate Template(Summ, *this);
Ted Kremenek6d4b76d2009-07-06 18:30:43 +00001292 bool isTrackedLoc = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001293
Ted Kremenek12b94342011-01-27 06:54:14 +00001294 // Effects on the receiver.
1295 if (MD->getAttr<NSConsumesSelfAttr>()) {
Ted Kremenek11fe1752011-01-27 18:43:03 +00001296 if (!GCEnabled)
Jordy Rose0fe62f82011-08-24 09:02:37 +00001297 Template->setReceiverEffect(DecRefMsg);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001298 }
1299
1300 // Effects on the parameters.
1301 unsigned parm_idx = 0;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00001302 for (ObjCMethodDecl::param_const_iterator
1303 pi=MD->param_begin(), pe=MD->param_end();
Ted Kremenek11fe1752011-01-27 18:43:03 +00001304 pi != pe; ++pi, ++parm_idx) {
1305 const ParmVarDecl *pd = *pi;
1306 if (pd->getAttr<NSConsumedAttr>()) {
1307 if (!GCEnabled)
Jordy Rose0fe62f82011-08-24 09:02:37 +00001308 Template->addArg(AF, parm_idx, DecRef);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001309 }
1310 else if(pd->getAttr<CFConsumedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001311 Template->addArg(AF, parm_idx, DecRef);
Ted Kremenek11fe1752011-01-27 18:43:03 +00001312 }
Ted Kremenek12b94342011-01-27 06:54:14 +00001313 }
1314
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001315 // Determine if there is a special return effect for this method.
Ted Kremenek78acdbf2010-01-27 18:00:17 +00001316 if (cocoa::isCocoaObjectRef(MD->getResultType())) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001317 if (MD->getAttr<NSReturnsRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001318 Template->setRetEffect(ObjCAllocRetE);
Ted Kremenek6d4b76d2009-07-06 18:30:43 +00001319 return;
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001320 }
Ted Kremenek60411112010-02-18 00:06:12 +00001321 if (MD->getAttr<NSReturnsNotRetainedAttr>()) {
Jordy Rose0fe62f82011-08-24 09:02:37 +00001322 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::ObjC));
Ted Kremenek60411112010-02-18 00:06:12 +00001323 return;
1324 }
Mike Stump1eb44332009-09-09 15:08:12 +00001325
Ted Kremenek6d4b76d2009-07-06 18:30:43 +00001326 isTrackedLoc = true;
Jordy Rose0fe62f82011-08-24 09:02:37 +00001327 } else {
Ted Kremenek6217b802009-07-29 21:53:49 +00001328 isTrackedLoc = MD->getResultType()->getAs<PointerType>() != NULL;
Jordy Rose0fe62f82011-08-24 09:02:37 +00001329 }
Mike Stump1eb44332009-09-09 15:08:12 +00001330
Ted Kremenek60411112010-02-18 00:06:12 +00001331 if (isTrackedLoc) {
1332 if (MD->getAttr<CFReturnsRetainedAttr>())
Jordy Rose0fe62f82011-08-24 09:02:37 +00001333 Template->setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenek60411112010-02-18 00:06:12 +00001334 else if (MD->getAttr<CFReturnsNotRetainedAttr>())
Jordy Rose0fe62f82011-08-24 09:02:37 +00001335 Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::CF));
Ted Kremenek60411112010-02-18 00:06:12 +00001336 }
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001337}
1338
Ted Kremenek93edbc52011-10-05 23:54:29 +00001339const RetainSummary *
Jordy Rosef3aae582012-03-17 21:13:07 +00001340RetainSummaryManager::getStandardMethodSummary(const ObjCMethodDecl *MD,
1341 Selector S, QualType RetTy) {
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001342
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +00001343 if (MD) {
Ted Kremenek376d1e72009-04-24 18:00:17 +00001344 // Scan the method decl for 'void*' arguments. These should be treated
1345 // as 'StopTracking' because they are often used with delegates.
1346 // Delegates are a frequent form of false positives with the retain
1347 // count checker.
1348 unsigned i = 0;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00001349 for (ObjCMethodDecl::param_const_iterator I = MD->param_begin(),
Ted Kremenek376d1e72009-04-24 18:00:17 +00001350 E = MD->param_end(); I != E; ++I, ++i)
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00001351 if (const ParmVarDecl *PD = *I) {
Ted Kremenek376d1e72009-04-24 18:00:17 +00001352 QualType Ty = Ctx.getCanonicalType(PD->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001353 if (Ty.getLocalUnqualifiedType() == Ctx.VoidPtrTy)
Ted Kremenek3baf6722010-11-24 00:54:37 +00001354 ScratchArgs = AF.add(ScratchArgs, i, StopTracking);
Ted Kremenek376d1e72009-04-24 18:00:17 +00001355 }
1356 }
Mike Stump1eb44332009-09-09 15:08:12 +00001357
Jordy Rosee921b1a2012-03-17 19:53:04 +00001358 // Any special effects?
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001359 ArgEffect ReceiverEff = DoNothing;
Jordy Rosee921b1a2012-03-17 19:53:04 +00001360 RetEffect ResultEff = RetEffect::MakeNoRet();
1361
1362 // Check the method family, and apply any default annotations.
1363 switch (MD ? MD->getMethodFamily() : S.getMethodFamily()) {
1364 case OMF_None:
1365 case OMF_performSelector:
1366 // Assume all Objective-C methods follow Cocoa Memory Management rules.
1367 // FIXME: Does the non-threaded performSelector family really belong here?
1368 // The selector could be, say, @selector(copy).
1369 if (cocoa::isCocoaObjectRef(RetTy))
1370 ResultEff = RetEffect::MakeNotOwned(RetEffect::ObjC);
1371 else if (coreFoundation::isCFObjectRef(RetTy)) {
1372 // ObjCMethodDecl currently doesn't consider CF objects as valid return
1373 // values for alloc, new, copy, or mutableCopy, so we have to
1374 // double-check with the selector. This is ugly, but there aren't that
1375 // many Objective-C methods that return CF objects, right?
1376 if (MD) {
1377 switch (S.getMethodFamily()) {
1378 case OMF_alloc:
1379 case OMF_new:
1380 case OMF_copy:
1381 case OMF_mutableCopy:
1382 ResultEff = RetEffect::MakeOwned(RetEffect::CF, true);
1383 break;
1384 default:
1385 ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1386 break;
1387 }
1388 } else {
1389 ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1390 }
1391 }
1392 break;
1393 case OMF_init:
1394 ResultEff = ObjCInitRetE;
1395 ReceiverEff = DecRefMsg;
1396 break;
1397 case OMF_alloc:
1398 case OMF_new:
1399 case OMF_copy:
1400 case OMF_mutableCopy:
1401 if (cocoa::isCocoaObjectRef(RetTy))
1402 ResultEff = ObjCAllocRetE;
1403 else if (coreFoundation::isCFObjectRef(RetTy))
1404 ResultEff = RetEffect::MakeOwned(RetEffect::CF, true);
1405 break;
1406 case OMF_autorelease:
1407 ReceiverEff = Autorelease;
1408 break;
1409 case OMF_retain:
1410 ReceiverEff = IncRefMsg;
1411 break;
1412 case OMF_release:
1413 ReceiverEff = DecRefMsg;
1414 break;
1415 case OMF_dealloc:
1416 ReceiverEff = Dealloc;
1417 break;
1418 case OMF_self:
1419 // -self is handled specially by the ExprEngine to propagate the receiver.
1420 break;
1421 case OMF_retainCount:
1422 case OMF_finalize:
1423 // These methods don't return objects.
1424 break;
1425 }
Mike Stump1eb44332009-09-09 15:08:12 +00001426
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001427 // If one of the arguments in the selector has the keyword 'delegate' we
1428 // should stop tracking the reference count for the receiver. This is
1429 // because the reference count is quite possibly handled by a delegate
1430 // method.
1431 if (S.isKeywordSelector()) {
Jordan Rose50571a92012-06-15 18:19:52 +00001432 for (unsigned i = 0, e = S.getNumArgs(); i != e; ++i) {
1433 StringRef Slot = S.getNameForSlot(i);
1434 if (Slot.substr(Slot.size() - 8).equals_lower("delegate")) {
1435 if (ResultEff == ObjCInitRetE)
1436 ResultEff = RetEffect::MakeNoRet();
1437 else
1438 ReceiverEff = StopTracking;
1439 }
1440 }
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001441 }
Mike Stump1eb44332009-09-09 15:08:12 +00001442
Jordy Rosee921b1a2012-03-17 19:53:04 +00001443 if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing &&
1444 ResultEff.getKind() == RetEffect::NoRet)
Ted Kremenek93edbc52011-10-05 23:54:29 +00001445 return getDefaultSummary();
Mike Stump1eb44332009-09-09 15:08:12 +00001446
Jordy Rosee921b1a2012-03-17 19:53:04 +00001447 return getPersistentSummary(ResultEff, ReceiverEff, MayEscape);
Ted Kremenek250b1fa2009-04-23 23:08:22 +00001448}
1449
Ted Kremenek93edbc52011-10-05 23:54:29 +00001450const RetainSummary *
Jordan Rosecde8cdb2012-07-02 19:27:56 +00001451RetainSummaryManager::getInstanceMethodSummary(const ObjCMethodCall &Msg,
Jordan Rose4531b7d2012-07-02 19:27:43 +00001452 ProgramStateRef State) {
1453 const ObjCInterfaceDecl *ReceiverClass = 0;
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001454
Jordan Rose4531b7d2012-07-02 19:27:43 +00001455 // We do better tracking of the type of the object than the core ExprEngine.
1456 // See if we have its type in our private state.
1457 // FIXME: Eventually replace the use of state->get<RefBindings> with
1458 // a generic API for reasoning about the Objective-C types of symbolic
1459 // objects.
1460 SVal ReceiverV = Msg.getReceiverSVal();
1461 if (SymbolRef Sym = ReceiverV.getAsLocSymbol())
1462 if (const RefVal *T = State->get<RefBindings>(Sym))
Douglas Gregor04badcf2010-04-21 00:45:42 +00001463 if (const ObjCObjectPointerType *PT =
Jordan Rose4531b7d2012-07-02 19:27:43 +00001464 T->getType()->getAs<ObjCObjectPointerType>())
1465 ReceiverClass = PT->getInterfaceDecl();
1466
1467 // If we don't know what kind of object this is, fall back to its static type.
1468 if (!ReceiverClass)
1469 ReceiverClass = Msg.getReceiverInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00001470
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001471 // FIXME: The receiver could be a reference to a class, meaning that
1472 // we should use the class method.
Jordan Rose4531b7d2012-07-02 19:27:43 +00001473 // id x = [NSObject class];
1474 // [x performSelector:... withObject:... afterDelay:...];
1475 Selector S = Msg.getSelector();
1476 const ObjCMethodDecl *Method = Msg.getDecl();
1477 if (!Method && ReceiverClass)
1478 Method = ReceiverClass->getInstanceMethod(S);
1479
1480 return getMethodSummary(S, ReceiverClass, Method, Msg.getResultType(),
1481 ObjCMethodSummaries);
Ted Kremenekb7ddd9b2009-11-13 01:54:21 +00001482}
1483
Ted Kremenek93edbc52011-10-05 23:54:29 +00001484const RetainSummary *
Jordan Rose4531b7d2012-07-02 19:27:43 +00001485RetainSummaryManager::getMethodSummary(Selector S, const ObjCInterfaceDecl *ID,
Jordy Rosef3aae582012-03-17 21:13:07 +00001486 const ObjCMethodDecl *MD, QualType RetTy,
1487 ObjCMethodSummariesTy &CachedSummaries) {
Ted Kremenek1bffd742008-05-06 15:44:25 +00001488
Ted Kremenek8711c032009-04-29 05:04:30 +00001489 // Look up a summary in our summary cache.
Jordan Rose4531b7d2012-07-02 19:27:43 +00001490 const RetainSummary *Summ = CachedSummaries.find(ID, S);
Mike Stump1eb44332009-09-09 15:08:12 +00001491
Ted Kremenek614cc542009-07-21 23:27:57 +00001492 if (!Summ) {
Jordy Rosef3aae582012-03-17 21:13:07 +00001493 Summ = getStandardMethodSummary(MD, S, RetTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001494
Ted Kremenek614cc542009-07-21 23:27:57 +00001495 // Annotations override defaults.
Jordy Rose4df54fe2011-08-23 04:27:15 +00001496 updateSummaryFromAnnotations(Summ, MD);
Mike Stump1eb44332009-09-09 15:08:12 +00001497
Ted Kremenek614cc542009-07-21 23:27:57 +00001498 // Memoize the summary.
Jordan Rose4531b7d2012-07-02 19:27:43 +00001499 CachedSummaries[ObjCSummaryKey(ID, S)] = Summ;
Ted Kremenek614cc542009-07-21 23:27:57 +00001500 }
Mike Stump1eb44332009-09-09 15:08:12 +00001501
Ted Kremeneke87450e2009-04-23 19:11:35 +00001502 return Summ;
Ted Kremenekc8395602008-05-06 21:26:51 +00001503}
1504
Mike Stump1eb44332009-09-09 15:08:12 +00001505void RetainSummaryManager::InitializeClassMethodSummaries() {
Ted Kremenekec315332009-05-07 23:40:42 +00001506 assert(ScratchArgs.isEmpty());
Mike Stump1eb44332009-09-09 15:08:12 +00001507 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek6fe2b7a2009-10-15 22:25:12 +00001508 addClassMethSummary("NSAssertionHandler", "currentHandler",
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001509 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Mike Stump1eb44332009-09-09 15:08:12 +00001510
Ted Kremenek6d348932008-10-21 15:53:15 +00001511 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001512 ScratchArgs = AF.add(ScratchArgs, 0, Autorelease);
Ted Kremenek6fe2b7a2009-10-15 22:25:12 +00001513 addClassMethSummary("NSAutoreleasePool", "addObject",
1514 getPersistentSummary(RetEffect::MakeNoRet(),
1515 DoNothing, Autorelease));
Ted Kremenek9c32d082008-05-06 00:30:21 +00001516}
1517
Ted Kremenek1f180c32008-06-23 22:21:20 +00001518void RetainSummaryManager::InitializeMethodSummaries() {
Mike Stump1eb44332009-09-09 15:08:12 +00001519
1520 assert (ScratchArgs.isEmpty());
1521
Ted Kremenekc8395602008-05-06 21:26:51 +00001522 // Create the "init" selector. It just acts as a pass-through for the
1523 // receiver.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001524 const RetainSummary *InitSumm = getPersistentSummary(ObjCInitRetE, DecRefMsg);
Ted Kremenekac02f202009-08-20 05:13:36 +00001525 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
1526
1527 // awakeAfterUsingCoder: behaves basically like an 'init' method. It
1528 // claims the receiver and returns a retained object.
1529 addNSObjectMethSummary(GetUnarySelector("awakeAfterUsingCoder", Ctx),
1530 InitSumm);
Mike Stump1eb44332009-09-09 15:08:12 +00001531
Ted Kremenekc8395602008-05-06 21:26:51 +00001532 // The next methods are allocators.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001533 const RetainSummary *AllocSumm = getPersistentSummary(ObjCAllocRetE);
1534 const RetainSummary *CFAllocSumm =
Ted Kremeneka834fb42009-08-28 19:52:12 +00001535 getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Mike Stump1eb44332009-09-09 15:08:12 +00001536
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001537 // Create the "retain" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001538 RetEffect NoRet = RetEffect::MakeNoRet();
Ted Kremenek93edbc52011-10-05 23:54:29 +00001539 const RetainSummary *Summ = getPersistentSummary(NoRet, IncRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001540 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001541
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001542 // Create the "release" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001543 Summ = getPersistentSummary(NoRet, DecRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001544 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001545
Ted Kremenek299e8152008-05-07 21:17:39 +00001546 // Create the "drain" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001547 Summ = getPersistentSummary(NoRet, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek553cf182008-06-25 21:21:56 +00001548 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001549
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001550 // Create the -dealloc summary.
Jordy Rose500abad2011-08-21 19:41:36 +00001551 Summ = getPersistentSummary(NoRet, Dealloc);
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001552 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001553
1554 // Create the "autorelease" selector.
Jordy Rose500abad2011-08-21 19:41:36 +00001555 Summ = getPersistentSummary(NoRet, Autorelease);
Ted Kremenek553cf182008-06-25 21:21:56 +00001556 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Mike Stump1eb44332009-09-09 15:08:12 +00001557
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00001558 // Specially handle NSAutoreleasePool.
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001559 addInstMethSummary("NSAutoreleasePool", "init",
Jordy Rose500abad2011-08-21 19:41:36 +00001560 getPersistentSummary(NoRet, NewAutoreleasePool));
Mike Stump1eb44332009-09-09 15:08:12 +00001561
1562 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremenek89e202d2009-02-23 02:51:29 +00001563 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1564 // self-own themselves. However, they only do this once they are displayed.
1565 // Thus, we need to track an NSWindow's display status.
1566 // This is tracked in <rdar://problem/6062711>.
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +00001567 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
Ted Kremenek93edbc52011-10-05 23:54:29 +00001568 const RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenek78a35a32009-05-12 20:06:54 +00001569 StopTracking,
1570 StopTracking);
Mike Stump1eb44332009-09-09 15:08:12 +00001571
Ted Kremenek99d02692009-04-03 19:02:51 +00001572 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1573
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +00001574#if 0
Ted Kremenek78a35a32009-05-12 20:06:54 +00001575 addInstMethSummary("NSWindow", NoTrackYet, "initWithContentRect",
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001576 "styleMask", "backing", "defer", NULL);
Mike Stump1eb44332009-09-09 15:08:12 +00001577
Ted Kremenek78a35a32009-05-12 20:06:54 +00001578 addInstMethSummary("NSWindow", NoTrackYet, "initWithContentRect",
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001579 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +00001580#endif
Mike Stump1eb44332009-09-09 15:08:12 +00001581
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001582 // For NSPanel (which subclasses NSWindow), allocated objects are not
1583 // self-owned.
Ted Kremenek99d02692009-04-03 19:02:51 +00001584 // FIXME: For now we don't track NSPanels. object for the same reason
1585 // as for NSWindow objects.
1586 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
Mike Stump1eb44332009-09-09 15:08:12 +00001587
Ted Kremenek78a35a32009-05-12 20:06:54 +00001588#if 0
1589 addInstMethSummary("NSPanel", NoTrackYet, "initWithContentRect",
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001590 "styleMask", "backing", "defer", NULL);
Mike Stump1eb44332009-09-09 15:08:12 +00001591
Ted Kremenek78a35a32009-05-12 20:06:54 +00001592 addInstMethSummary("NSPanel", NoTrackYet, "initWithContentRect",
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001593 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek78a35a32009-05-12 20:06:54 +00001594#endif
Mike Stump1eb44332009-09-09 15:08:12 +00001595
Ted Kremenekba67f6a2009-05-18 23:14:34 +00001596 // Don't track allocated autorelease pools yet, as it is okay to prematurely
1597 // exit a method.
1598 addClassMethSummary("NSAutoreleasePool", "alloc", NoTrackYet);
Ted Kremeneka9797122012-02-18 21:37:48 +00001599 addClassMethSummary("NSAutoreleasePool", "allocWithZone", NoTrackYet, false);
Ted Kremenek553cf182008-06-25 21:21:56 +00001600
Ted Kremenek767d6492009-05-20 22:39:57 +00001601 // Create summaries QCRenderer/QCView -createSnapShotImageOfType:
1602 addInstMethSummary("QCRenderer", AllocSumm,
1603 "createSnapshotImageOfType", NULL);
1604 addInstMethSummary("QCView", AllocSumm,
1605 "createSnapshotImageOfType", NULL);
1606
Ted Kremenek211a9c62009-06-15 20:58:58 +00001607 // Create summaries for CIContext, 'createCGImage' and
Ted Kremeneka834fb42009-08-28 19:52:12 +00001608 // 'createCGLayerWithSize'. These objects are CF objects, and are not
1609 // automatically garbage collected.
1610 addInstMethSummary("CIContext", CFAllocSumm,
Ted Kremenek767d6492009-05-20 22:39:57 +00001611 "createCGImage", "fromRect", NULL);
Ted Kremeneka834fb42009-08-28 19:52:12 +00001612 addInstMethSummary("CIContext", CFAllocSumm,
Mike Stump1eb44332009-09-09 15:08:12 +00001613 "createCGImage", "fromRect", "format", "colorSpace", NULL);
Ted Kremeneka834fb42009-08-28 19:52:12 +00001614 addInstMethSummary("CIContext", CFAllocSumm, "createCGLayerWithSize",
Ted Kremenek211a9c62009-06-15 20:58:58 +00001615 "info", NULL);
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001616}
1617
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001618//===----------------------------------------------------------------------===//
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001619// AutoreleaseBindings - State used to track objects in autorelease pools.
Ted Kremenek6d348932008-10-21 15:53:15 +00001620//===----------------------------------------------------------------------===//
1621
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001622typedef llvm::ImmutableMap<SymbolRef, unsigned> ARCounts;
1623typedef llvm::ImmutableMap<SymbolRef, ARCounts> ARPoolContents;
1624typedef llvm::ImmutableList<SymbolRef> ARStack;
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00001625
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001626static int AutoRCIndex = 0;
Ted Kremenek6d348932008-10-21 15:53:15 +00001627static int AutoRBIndex = 0;
1628
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001629namespace { class AutoreleasePoolContents {}; }
1630namespace { class AutoreleaseStack {}; }
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001631
Ted Kremenek6d348932008-10-21 15:53:15 +00001632namespace clang {
Ted Kremenek9ef65372010-12-23 07:20:52 +00001633namespace ento {
Ted Kremenek18c66fd2011-08-15 22:09:50 +00001634template<> struct ProgramStateTrait<AutoreleaseStack>
1635 : public ProgramStatePartialTrait<ARStack> {
Ted Kremenek9c378f72011-08-12 23:37:29 +00001636 static inline void *GDMIndex() { return &AutoRBIndex; }
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001637};
1638
Ted Kremenek18c66fd2011-08-15 22:09:50 +00001639template<> struct ProgramStateTrait<AutoreleasePoolContents>
1640 : public ProgramStatePartialTrait<ARPoolContents> {
Ted Kremenek9c378f72011-08-12 23:37:29 +00001641 static inline void *GDMIndex() { return &AutoRCIndex; }
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001642};
Argyrios Kyrtzidis5a4f98f2010-12-22 18:53:20 +00001643} // end GR namespace
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001644} // end clang namespace
Ted Kremenek6d348932008-10-21 15:53:15 +00001645
Ted Kremenek8bef8232012-01-26 21:29:00 +00001646static SymbolRef GetCurrentAutoreleasePool(ProgramStateRef state) {
Ted Kremenek7037ab82009-03-20 17:34:15 +00001647 ARStack stack = state->get<AutoreleaseStack>();
1648 return stack.isEmpty() ? SymbolRef() : stack.getHead();
1649}
1650
Ted Kremenek8bef8232012-01-26 21:29:00 +00001651static ProgramStateRef
1652SendAutorelease(ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +00001653 ARCounts::Factory &F,
1654 SymbolRef sym) {
Ted Kremenek7037ab82009-03-20 17:34:15 +00001655 SymbolRef pool = GetCurrentAutoreleasePool(state);
Ted Kremenekb65be702009-06-18 01:23:53 +00001656 const ARCounts *cnts = state->get<AutoreleasePoolContents>(pool);
Ted Kremenek7037ab82009-03-20 17:34:15 +00001657 ARCounts newCnts(0);
Mike Stump1eb44332009-09-09 15:08:12 +00001658
Ted Kremenek7037ab82009-03-20 17:34:15 +00001659 if (cnts) {
1660 const unsigned *cnt = (*cnts).lookup(sym);
Ted Kremenek3baf6722010-11-24 00:54:37 +00001661 newCnts = F.add(*cnts, sym, cnt ? *cnt + 1 : 1);
Ted Kremenek7037ab82009-03-20 17:34:15 +00001662 }
1663 else
Ted Kremenek3baf6722010-11-24 00:54:37 +00001664 newCnts = F.add(F.getEmptyMap(), sym, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001665
Ted Kremenekb65be702009-06-18 01:23:53 +00001666 return state->set<AutoreleasePoolContents>(pool, newCnts);
Ted Kremenek7037ab82009-03-20 17:34:15 +00001667}
1668
Ted Kremenek13922612008-04-16 20:40:59 +00001669//===----------------------------------------------------------------------===//
Ted Kremenekc887d132009-04-29 18:50:19 +00001670// Error reporting.
1671//===----------------------------------------------------------------------===//
Ted Kremenekc887d132009-04-29 18:50:19 +00001672namespace {
Jordy Roseec9ef852011-08-23 20:55:48 +00001673 typedef llvm::DenseMap<const ExplodedNode *, const RetainSummary *>
1674 SummaryLogTy;
1675
Ted Kremenekc887d132009-04-29 18:50:19 +00001676 //===-------------===//
1677 // Bug Descriptions. //
Mike Stump1eb44332009-09-09 15:08:12 +00001678 //===-------------===//
1679
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001680 class CFRefBug : public BugType {
Ted Kremenekc887d132009-04-29 18:50:19 +00001681 protected:
Jordy Rose35c86952011-08-24 05:47:39 +00001682 CFRefBug(StringRef name)
Ted Kremenek6fd45052012-04-05 20:43:28 +00001683 : BugType(name, categories::MemoryCoreFoundationObjectiveC) {}
Ted Kremenekc887d132009-04-29 18:50:19 +00001684 public:
Mike Stump1eb44332009-09-09 15:08:12 +00001685
Ted Kremenekc887d132009-04-29 18:50:19 +00001686 // FIXME: Eventually remove.
Jordy Rose35c86952011-08-24 05:47:39 +00001687 virtual const char *getDescription() const = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001688
Ted Kremenekc887d132009-04-29 18:50:19 +00001689 virtual bool isLeak() const { return false; }
1690 };
Mike Stump1eb44332009-09-09 15:08:12 +00001691
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001692 class UseAfterRelease : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001693 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001694 UseAfterRelease() : CFRefBug("Use-after-release") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001695
Jordy Rose35c86952011-08-24 05:47:39 +00001696 const char *getDescription() const {
Ted Kremenekc887d132009-04-29 18:50:19 +00001697 return "Reference-counted object is used after it is released";
Mike Stump1eb44332009-09-09 15:08:12 +00001698 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001699 };
Mike Stump1eb44332009-09-09 15:08:12 +00001700
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001701 class BadRelease : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001702 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001703 BadRelease() : CFRefBug("Bad release") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001704
Jordy Rose35c86952011-08-24 05:47:39 +00001705 const char *getDescription() const {
Ted Kremenekbb206fd2009-10-01 17:31:50 +00001706 return "Incorrect decrement of the reference count of an object that is "
1707 "not owned at this point by the caller";
Ted Kremenekc887d132009-04-29 18:50:19 +00001708 }
1709 };
Mike Stump1eb44332009-09-09 15:08:12 +00001710
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001711 class DeallocGC : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001712 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001713 DeallocGC()
1714 : CFRefBug("-dealloc called while using garbage collection") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001715
Ted Kremenekc887d132009-04-29 18:50:19 +00001716 const char *getDescription() const {
Ted Kremenek369de562009-05-09 00:10:05 +00001717 return "-dealloc called while using garbage collection";
Ted Kremenekc887d132009-04-29 18:50:19 +00001718 }
1719 };
Mike Stump1eb44332009-09-09 15:08:12 +00001720
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001721 class DeallocNotOwned : public CFRefBug {
Ted Kremenekc887d132009-04-29 18:50:19 +00001722 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001723 DeallocNotOwned()
1724 : CFRefBug("-dealloc sent to non-exclusively owned object") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001725
Ted Kremenekc887d132009-04-29 18:50:19 +00001726 const char *getDescription() const {
1727 return "-dealloc sent to object that may be referenced elsewhere";
1728 }
Mike Stump1eb44332009-09-09 15:08:12 +00001729 };
1730
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001731 class OverAutorelease : public CFRefBug {
Ted Kremenek369de562009-05-09 00:10:05 +00001732 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001733 OverAutorelease()
1734 : CFRefBug("Object sent -autorelease too many times") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001735
Ted Kremenek369de562009-05-09 00:10:05 +00001736 const char *getDescription() const {
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001737 return "Object sent -autorelease too many times";
Ted Kremenek369de562009-05-09 00:10:05 +00001738 }
1739 };
Mike Stump1eb44332009-09-09 15:08:12 +00001740
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001741 class ReturnedNotOwnedForOwned : public CFRefBug {
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001742 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001743 ReturnedNotOwnedForOwned()
1744 : CFRefBug("Method should return an owned object") {}
Mike Stump1eb44332009-09-09 15:08:12 +00001745
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001746 const char *getDescription() const {
Jordy Rose5b5402b2011-07-15 22:17:54 +00001747 return "Object with a +0 retain count returned to caller where a +1 "
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001748 "(owning) retain count is expected";
1749 }
1750 };
Mike Stump1eb44332009-09-09 15:08:12 +00001751
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001752 class Leak : public CFRefBug {
Benjamin Kramerfacde172012-06-06 17:32:50 +00001753 public:
1754 Leak(StringRef name)
1755 : CFRefBug(name) {
Jordy Rosedb92bb62011-08-25 01:14:38 +00001756 // Leaks should not be reported if they are post-dominated by a sink.
1757 setSuppressOnSink(true);
1758 }
Mike Stump1eb44332009-09-09 15:08:12 +00001759
Jordy Rose35c86952011-08-24 05:47:39 +00001760 const char *getDescription() const { return ""; }
Mike Stump1eb44332009-09-09 15:08:12 +00001761
Ted Kremenekc887d132009-04-29 18:50:19 +00001762 bool isLeak() const { return true; }
1763 };
Mike Stump1eb44332009-09-09 15:08:12 +00001764
Ted Kremenekc887d132009-04-29 18:50:19 +00001765 //===---------===//
1766 // Bug Reports. //
1767 //===---------===//
Mike Stump1eb44332009-09-09 15:08:12 +00001768
Jordy Rose01153492012-03-24 02:45:35 +00001769 class CFRefReportVisitor : public BugReporterVisitorImpl<CFRefReportVisitor> {
Anna Zaks23f395e2011-08-20 01:27:22 +00001770 protected:
Anna Zaksdc757b02011-08-19 23:21:56 +00001771 SymbolRef Sym;
Jordy Roseec9ef852011-08-23 20:55:48 +00001772 const SummaryLogTy &SummaryLog;
Jordy Rose35c86952011-08-24 05:47:39 +00001773 bool GCEnabled;
Anna Zaks23f395e2011-08-20 01:27:22 +00001774
Anna Zaksdc757b02011-08-19 23:21:56 +00001775 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001776 CFRefReportVisitor(SymbolRef sym, bool gcEnabled, const SummaryLogTy &log)
1777 : Sym(sym), SummaryLog(log), GCEnabled(gcEnabled) {}
Anna Zaksdc757b02011-08-19 23:21:56 +00001778
Anna Zaks23f395e2011-08-20 01:27:22 +00001779 virtual void Profile(llvm::FoldingSetNodeID &ID) const {
Anna Zaksdc757b02011-08-19 23:21:56 +00001780 static int x = 0;
1781 ID.AddPointer(&x);
1782 ID.AddPointer(Sym);
1783 }
1784
Anna Zaks23f395e2011-08-20 01:27:22 +00001785 virtual PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
1786 const ExplodedNode *PrevN,
1787 BugReporterContext &BRC,
1788 BugReport &BR);
1789
1790 virtual PathDiagnosticPiece *getEndPath(BugReporterContext &BRC,
1791 const ExplodedNode *N,
1792 BugReport &BR);
1793 };
1794
1795 class CFRefLeakReportVisitor : public CFRefReportVisitor {
1796 public:
Jordy Rose35c86952011-08-24 05:47:39 +00001797 CFRefLeakReportVisitor(SymbolRef sym, bool GCEnabled,
Jordy Roseec9ef852011-08-23 20:55:48 +00001798 const SummaryLogTy &log)
Jordy Rose35c86952011-08-24 05:47:39 +00001799 : CFRefReportVisitor(sym, GCEnabled, log) {}
Anna Zaks23f395e2011-08-20 01:27:22 +00001800
1801 PathDiagnosticPiece *getEndPath(BugReporterContext &BRC,
1802 const ExplodedNode *N,
1803 BugReport &BR);
Jordy Rose01153492012-03-24 02:45:35 +00001804
1805 virtual BugReporterVisitor *clone() const {
1806 // The curiously-recurring template pattern only works for one level of
1807 // subclassing. Rather than make a new template base for
1808 // CFRefReportVisitor, we simply override clone() to do the right thing.
1809 // This could be trouble someday if BugReporterVisitorImpl is ever
1810 // used for something else besides a convenient implementation of clone().
1811 return new CFRefLeakReportVisitor(*this);
1812 }
Anna Zaksdc757b02011-08-19 23:21:56 +00001813 };
1814
Anna Zakse172e8b2011-08-17 23:00:25 +00001815 class CFRefReport : public BugReport {
Jordy Rose20589562011-08-24 22:39:09 +00001816 void addGCModeDescription(const LangOptions &LOpts, bool GCEnabled);
Jordy Rose35c86952011-08-24 05:47:39 +00001817
Ted Kremenekc887d132009-04-29 18:50:19 +00001818 public:
Jordy Rose20589562011-08-24 22:39:09 +00001819 CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1820 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1821 bool registerVisitor = true)
Anna Zaksedf4dae2011-08-22 18:54:07 +00001822 : BugReport(D, D.getDescription(), n) {
Anna Zaks23f395e2011-08-20 01:27:22 +00001823 if (registerVisitor)
Jordy Rose20589562011-08-24 22:39:09 +00001824 addVisitor(new CFRefReportVisitor(sym, GCEnabled, Log));
1825 addGCModeDescription(LOpts, GCEnabled);
Anna Zaksdc757b02011-08-19 23:21:56 +00001826 }
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001827
Jordy Rose20589562011-08-24 22:39:09 +00001828 CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1829 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1830 StringRef endText)
Anna Zaksedf4dae2011-08-22 18:54:07 +00001831 : BugReport(D, D.getDescription(), endText, n) {
Jordy Rose20589562011-08-24 22:39:09 +00001832 addVisitor(new CFRefReportVisitor(sym, GCEnabled, Log));
1833 addGCModeDescription(LOpts, GCEnabled);
Anna Zaksdc757b02011-08-19 23:21:56 +00001834 }
Mike Stump1eb44332009-09-09 15:08:12 +00001835
Anna Zakse172e8b2011-08-17 23:00:25 +00001836 virtual std::pair<ranges_iterator, ranges_iterator> getRanges() {
Anna Zaksedf4dae2011-08-22 18:54:07 +00001837 const CFRefBug& BugTy = static_cast<CFRefBug&>(getBugType());
1838 if (!BugTy.isLeak())
Anna Zakse172e8b2011-08-17 23:00:25 +00001839 return BugReport::getRanges();
Ted Kremenekc887d132009-04-29 18:50:19 +00001840 else
Argyrios Kyrtzidis640ccf02010-12-04 01:12:15 +00001841 return std::make_pair(ranges_iterator(), ranges_iterator());
Ted Kremenekc887d132009-04-29 18:50:19 +00001842 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001843 };
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001844
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00001845 class CFRefLeakReport : public CFRefReport {
Ted Kremenekc887d132009-04-29 18:50:19 +00001846 const MemRegion* AllocBinding;
Anna Zaks23f395e2011-08-20 01:27:22 +00001847
Ted Kremenekc887d132009-04-29 18:50:19 +00001848 public:
Jordy Rose20589562011-08-24 22:39:09 +00001849 CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1850 const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
Anna Zaks6a93bd52011-10-25 19:57:11 +00001851 CheckerContext &Ctx);
Mike Stump1eb44332009-09-09 15:08:12 +00001852
Anna Zaks590dd8e2011-09-20 21:38:35 +00001853 PathDiagnosticLocation getLocation(const SourceManager &SM) const {
1854 assert(Location.isValid());
1855 return Location;
1856 }
Mike Stump1eb44332009-09-09 15:08:12 +00001857 };
Ted Kremenekc887d132009-04-29 18:50:19 +00001858} // end anonymous namespace
1859
Jordy Rose20589562011-08-24 22:39:09 +00001860void CFRefReport::addGCModeDescription(const LangOptions &LOpts,
1861 bool GCEnabled) {
Jordy Rosef95b19d2011-08-24 20:38:42 +00001862 const char *GCModeDescription = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001863
Douglas Gregore289d812011-09-13 17:21:33 +00001864 switch (LOpts.getGC()) {
Anna Zaks7f2531c2011-08-22 20:31:28 +00001865 case LangOptions::GCOnly:
Jordy Rose20589562011-08-24 22:39:09 +00001866 assert(GCEnabled);
Jordy Rose35c86952011-08-24 05:47:39 +00001867 GCModeDescription = "Code is compiled to only use garbage collection";
1868 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001869
Anna Zaks7f2531c2011-08-22 20:31:28 +00001870 case LangOptions::NonGC:
Jordy Rose20589562011-08-24 22:39:09 +00001871 assert(!GCEnabled);
Jordy Rose35c86952011-08-24 05:47:39 +00001872 GCModeDescription = "Code is compiled to use reference counts";
1873 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001874
Anna Zaks7f2531c2011-08-22 20:31:28 +00001875 case LangOptions::HybridGC:
Jordy Rose20589562011-08-24 22:39:09 +00001876 if (GCEnabled) {
Jordy Rose35c86952011-08-24 05:47:39 +00001877 GCModeDescription = "Code is compiled to use either garbage collection "
1878 "(GC) or reference counts (non-GC). The bug occurs "
1879 "with GC enabled";
1880 break;
1881 } else {
1882 GCModeDescription = "Code is compiled to use either garbage collection "
1883 "(GC) or reference counts (non-GC). The bug occurs "
1884 "in non-GC mode";
1885 break;
Anna Zaks7f2531c2011-08-22 20:31:28 +00001886 }
Ted Kremenekc887d132009-04-29 18:50:19 +00001887 }
Jordy Rose35c86952011-08-24 05:47:39 +00001888
Jordy Rosef95b19d2011-08-24 20:38:42 +00001889 assert(GCModeDescription && "invalid/unknown GC mode");
Jordy Rose35c86952011-08-24 05:47:39 +00001890 addExtraText(GCModeDescription);
Ted Kremenekc887d132009-04-29 18:50:19 +00001891}
1892
Jordy Rose910c4052011-09-02 06:44:22 +00001893// FIXME: This should be a method on SmallVector.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001894static inline bool contains(const SmallVectorImpl<ArgEffect>& V,
Ted Kremenekc887d132009-04-29 18:50:19 +00001895 ArgEffect X) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001896 for (SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
Ted Kremenekc887d132009-04-29 18:50:19 +00001897 I!=E; ++I)
1898 if (*I == X) return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001899
Ted Kremenekc887d132009-04-29 18:50:19 +00001900 return false;
1901}
1902
Jordy Rose70fdbc32012-05-12 05:10:43 +00001903static bool isNumericLiteralExpression(const Expr *E) {
1904 // FIXME: This set of cases was copied from SemaExprObjC.
1905 return isa<IntegerLiteral>(E) ||
1906 isa<CharacterLiteral>(E) ||
1907 isa<FloatingLiteral>(E) ||
1908 isa<ObjCBoolLiteralExpr>(E) ||
1909 isa<CXXBoolLiteralExpr>(E);
1910}
1911
Ted Kremenek4c42bb72011-11-14 21:59:21 +00001912static bool isPropertyAccess(const Stmt *S, ParentMap &PM) {
1913 unsigned maxDepth = 4;
1914 while (S && maxDepth) {
1915 if (const PseudoObjectExpr *PO = dyn_cast<PseudoObjectExpr>(S)) {
1916 if (!isa<ObjCMessageExpr>(PO->getSyntacticForm()))
1917 return true;
1918 return false;
1919 }
1920 S = PM.getParent(S);
1921 --maxDepth;
1922 }
1923 return false;
1924}
1925
Anna Zaksdc757b02011-08-19 23:21:56 +00001926PathDiagnosticPiece *CFRefReportVisitor::VisitNode(const ExplodedNode *N,
1927 const ExplodedNode *PrevN,
1928 BugReporterContext &BRC,
1929 BugReport &BR) {
Mike Stump1eb44332009-09-09 15:08:12 +00001930
Jordy Rosef53e8c72011-08-23 19:43:16 +00001931 if (!isa<StmtPoint>(N->getLocation()))
Ted Kremenek2033a952009-05-13 07:12:33 +00001932 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001933
Ted Kremenek8966bc12009-05-06 21:39:49 +00001934 // Check if the type state has changed.
Ted Kremenek8bef8232012-01-26 21:29:00 +00001935 ProgramStateRef PrevSt = PrevN->getState();
1936 ProgramStateRef CurrSt = N->getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001937 const LocationContext *LCtx = N->getLocationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00001938
1939 const RefVal* CurrT = CurrSt->get<RefBindings>(Sym);
Ted Kremenekc887d132009-04-29 18:50:19 +00001940 if (!CurrT) return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001941
Ted Kremenekb65be702009-06-18 01:23:53 +00001942 const RefVal &CurrV = *CurrT;
1943 const RefVal *PrevT = PrevSt->get<RefBindings>(Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00001944
Ted Kremenekc887d132009-04-29 18:50:19 +00001945 // Create a string buffer to constain all the useful things we want
1946 // to tell the user.
1947 std::string sbuf;
1948 llvm::raw_string_ostream os(sbuf);
Mike Stump1eb44332009-09-09 15:08:12 +00001949
Ted Kremenekc887d132009-04-29 18:50:19 +00001950 // This is the allocation site since the previous node had no bindings
1951 // for this symbol.
1952 if (!PrevT) {
Jordy Rosef53e8c72011-08-23 19:43:16 +00001953 const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
Mike Stump1eb44332009-09-09 15:08:12 +00001954
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001955 if (isa<ObjCArrayLiteral>(S)) {
1956 os << "NSArray literal is an object with a +0 retain count";
Mike Stump1eb44332009-09-09 15:08:12 +00001957 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001958 else if (isa<ObjCDictionaryLiteral>(S)) {
1959 os << "NSDictionary literal is an object with a +0 retain count";
Ted Kremenekc887d132009-04-29 18:50:19 +00001960 }
Jordy Rose70fdbc32012-05-12 05:10:43 +00001961 else if (const ObjCBoxedExpr *BL = dyn_cast<ObjCBoxedExpr>(S)) {
1962 if (isNumericLiteralExpression(BL->getSubExpr()))
1963 os << "NSNumber literal is an object with a +0 retain count";
1964 else {
1965 const ObjCInterfaceDecl *BoxClass = 0;
1966 if (const ObjCMethodDecl *Method = BL->getBoxingMethod())
1967 BoxClass = Method->getClassInterface();
1968
1969 // We should always be able to find the boxing class interface,
1970 // but consider this future-proofing.
1971 if (BoxClass)
1972 os << *BoxClass << " b";
1973 else
1974 os << "B";
1975
1976 os << "oxed expression produces an object with a +0 retain count";
1977 }
1978 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001979 else {
1980 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
1981 // Get the name of the callee (if it is available).
1982 SVal X = CurrSt->getSValAsScalarOrLoc(CE->getCallee(), LCtx);
1983 if (const FunctionDecl *FD = X.getAsFunctionDecl())
1984 os << "Call to function '" << *FD << '\'';
1985 else
1986 os << "function call";
Ted Kremenekc887d132009-04-29 18:50:19 +00001987 }
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00001988 else {
1989 assert(isa<ObjCMessageExpr>(S));
1990 // The message expression may have between written directly or as
1991 // a property access. Lazily determine which case we are looking at.
1992 os << (isPropertyAccess(S, N->getParentMap()) ? "Property" : "Method");
1993 }
1994
1995 if (CurrV.getObjKind() == RetEffect::CF) {
1996 os << " returns a Core Foundation object with a ";
1997 }
1998 else {
1999 assert (CurrV.getObjKind() == RetEffect::ObjC);
2000 os << " returns an Objective-C object with a ";
2001 }
2002
2003 if (CurrV.isOwned()) {
2004 os << "+1 retain count";
2005
2006 if (GCEnabled) {
2007 assert(CurrV.getObjKind() == RetEffect::CF);
2008 os << ". "
2009 "Core Foundation objects are not automatically garbage collected.";
2010 }
2011 }
2012 else {
2013 assert (CurrV.isNotOwned());
2014 os << "+0 retain count";
2015 }
Ted Kremenekc887d132009-04-29 18:50:19 +00002016 }
Mike Stump1eb44332009-09-09 15:08:12 +00002017
Anna Zaks220ac8c2011-09-15 01:08:34 +00002018 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
2019 N->getLocationContext());
Ted Kremenekc887d132009-04-29 18:50:19 +00002020 return new PathDiagnosticEventPiece(Pos, os.str());
2021 }
Mike Stump1eb44332009-09-09 15:08:12 +00002022
Ted Kremenekc887d132009-04-29 18:50:19 +00002023 // Gather up the effects that were performed on the object at this
2024 // program point
Chris Lattner5f9e2722011-07-23 10:55:15 +00002025 SmallVector<ArgEffect, 2> AEffects;
Mike Stump1eb44332009-09-09 15:08:12 +00002026
Jordy Roseec9ef852011-08-23 20:55:48 +00002027 const ExplodedNode *OrigNode = BRC.getNodeResolver().getOriginalNode(N);
2028 if (const RetainSummary *Summ = SummaryLog.lookup(OrigNode)) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002029 // We only have summaries attached to nodes after evaluating CallExpr and
2030 // ObjCMessageExprs.
Jordy Rosef53e8c72011-08-23 19:43:16 +00002031 const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
Mike Stump1eb44332009-09-09 15:08:12 +00002032
Ted Kremenek5f85e172009-07-22 22:35:28 +00002033 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002034 // Iterate through the parameter expressions and see if the symbol
2035 // was ever passed as an argument.
2036 unsigned i = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002037
Ted Kremenek5f85e172009-07-22 22:35:28 +00002038 for (CallExpr::const_arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
Ted Kremenekc887d132009-04-29 18:50:19 +00002039 AI!=AE; ++AI, ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002040
Ted Kremenekc887d132009-04-29 18:50:19 +00002041 // Retrieve the value of the argument. Is it the symbol
2042 // we are interested in?
Ted Kremenek5eca4822012-01-06 22:09:28 +00002043 if (CurrSt->getSValAsScalarOrLoc(*AI, LCtx).getAsLocSymbol() != Sym)
Ted Kremenekc887d132009-04-29 18:50:19 +00002044 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00002045
Ted Kremenekc887d132009-04-29 18:50:19 +00002046 // We have an argument. Get the effect!
2047 AEffects.push_back(Summ->getArg(i));
2048 }
2049 }
Mike Stump1eb44332009-09-09 15:08:12 +00002050 else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002051 if (const Expr *receiver = ME->getInstanceReceiver())
Ted Kremenek5eca4822012-01-06 22:09:28 +00002052 if (CurrSt->getSValAsScalarOrLoc(receiver, LCtx)
2053 .getAsLocSymbol() == Sym) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002054 // The symbol we are tracking is the receiver.
2055 AEffects.push_back(Summ->getReceiverEffect());
2056 }
2057 }
2058 }
Mike Stump1eb44332009-09-09 15:08:12 +00002059
Ted Kremenekc887d132009-04-29 18:50:19 +00002060 do {
2061 // Get the previous type state.
2062 RefVal PrevV = *PrevT;
Mike Stump1eb44332009-09-09 15:08:12 +00002063
Ted Kremenekc887d132009-04-29 18:50:19 +00002064 // Specially handle -dealloc.
Jordy Rose35c86952011-08-24 05:47:39 +00002065 if (!GCEnabled && contains(AEffects, Dealloc)) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002066 // Determine if the object's reference count was pushed to zero.
2067 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2068 // We may not have transitioned to 'release' if we hit an error.
2069 // This case is handled elsewhere.
2070 if (CurrV.getKind() == RefVal::Released) {
Ted Kremenekf21332e2009-05-08 20:01:42 +00002071 assert(CurrV.getCombinedCounts() == 0);
Ted Kremenekc887d132009-04-29 18:50:19 +00002072 os << "Object released by directly sending the '-dealloc' message";
2073 break;
2074 }
2075 }
Mike Stump1eb44332009-09-09 15:08:12 +00002076
Ted Kremenekc887d132009-04-29 18:50:19 +00002077 // Specially handle CFMakeCollectable and friends.
2078 if (contains(AEffects, MakeCollectable)) {
2079 // Get the name of the function.
Jordy Rosef53e8c72011-08-23 19:43:16 +00002080 const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
Ted Kremenek5eca4822012-01-06 22:09:28 +00002081 SVal X =
2082 CurrSt->getSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee(), LCtx);
Ted Kremenek9c378f72011-08-12 23:37:29 +00002083 const FunctionDecl *FD = X.getAsFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002084
Jordy Rose35c86952011-08-24 05:47:39 +00002085 if (GCEnabled) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002086 // Determine if the object's reference count was pushed to zero.
2087 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
Mike Stump1eb44332009-09-09 15:08:12 +00002088
Benjamin Kramerb8989f22011-10-14 18:45:37 +00002089 os << "In GC mode a call to '" << *FD
Ted Kremenekc887d132009-04-29 18:50:19 +00002090 << "' decrements an object's retain count and registers the "
2091 "object with the garbage collector. ";
Mike Stump1eb44332009-09-09 15:08:12 +00002092
Ted Kremenekc887d132009-04-29 18:50:19 +00002093 if (CurrV.getKind() == RefVal::Released) {
2094 assert(CurrV.getCount() == 0);
2095 os << "Since it now has a 0 retain count the object can be "
2096 "automatically collected by the garbage collector.";
2097 }
2098 else
2099 os << "An object must have a 0 retain count to be garbage collected. "
2100 "After this call its retain count is +" << CurrV.getCount()
2101 << '.';
2102 }
Mike Stump1eb44332009-09-09 15:08:12 +00002103 else
Benjamin Kramerb8989f22011-10-14 18:45:37 +00002104 os << "When GC is not enabled a call to '" << *FD
Ted Kremenekc887d132009-04-29 18:50:19 +00002105 << "' has no effect on its argument.";
Mike Stump1eb44332009-09-09 15:08:12 +00002106
Ted Kremenekc887d132009-04-29 18:50:19 +00002107 // Nothing more to say.
2108 break;
2109 }
Mike Stump1eb44332009-09-09 15:08:12 +00002110
2111 // Determine if the typestate has changed.
Ted Kremenekc887d132009-04-29 18:50:19 +00002112 if (!(PrevV == CurrV))
2113 switch (CurrV.getKind()) {
2114 case RefVal::Owned:
2115 case RefVal::NotOwned:
Mike Stump1eb44332009-09-09 15:08:12 +00002116
Ted Kremenekf21332e2009-05-08 20:01:42 +00002117 if (PrevV.getCount() == CurrV.getCount()) {
2118 // Did an autorelease message get sent?
2119 if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
2120 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002121
Zhongxing Xu264e9372009-05-12 10:10:00 +00002122 assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount());
Ted Kremenekeaedfea2009-05-10 05:11:21 +00002123 os << "Object sent -autorelease message";
Ted Kremenekf21332e2009-05-08 20:01:42 +00002124 break;
2125 }
Mike Stump1eb44332009-09-09 15:08:12 +00002126
Ted Kremenekc887d132009-04-29 18:50:19 +00002127 if (PrevV.getCount() > CurrV.getCount())
2128 os << "Reference count decremented.";
2129 else
2130 os << "Reference count incremented.";
Mike Stump1eb44332009-09-09 15:08:12 +00002131
Ted Kremenekc887d132009-04-29 18:50:19 +00002132 if (unsigned Count = CurrV.getCount())
2133 os << " The object now has a +" << Count << " retain count.";
Mike Stump1eb44332009-09-09 15:08:12 +00002134
Ted Kremenekc887d132009-04-29 18:50:19 +00002135 if (PrevV.getKind() == RefVal::Released) {
Jordy Rose35c86952011-08-24 05:47:39 +00002136 assert(GCEnabled && CurrV.getCount() > 0);
Jordy Rose74b7b2b2012-03-17 05:49:15 +00002137 os << " The object is not eligible for garbage collection until "
2138 "the retain count reaches 0 again.";
Ted Kremenekc887d132009-04-29 18:50:19 +00002139 }
Mike Stump1eb44332009-09-09 15:08:12 +00002140
Ted Kremenekc887d132009-04-29 18:50:19 +00002141 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002142
Ted Kremenekc887d132009-04-29 18:50:19 +00002143 case RefVal::Released:
2144 os << "Object released.";
2145 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002146
Ted Kremenekc887d132009-04-29 18:50:19 +00002147 case RefVal::ReturnedOwned:
Jordy Rose74b7b2b2012-03-17 05:49:15 +00002148 // Autoreleases can be applied after marking a node ReturnedOwned.
2149 if (CurrV.getAutoreleaseCount())
2150 return NULL;
2151
2152 os << "Object returned to caller as an owning reference (single "
2153 "retain count transferred to caller)";
Ted Kremenekc887d132009-04-29 18:50:19 +00002154 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002155
Ted Kremenekc887d132009-04-29 18:50:19 +00002156 case RefVal::ReturnedNotOwned:
Ted Kremenekf1365462011-05-26 18:45:44 +00002157 os << "Object returned to caller with a +0 retain count";
Ted Kremenekc887d132009-04-29 18:50:19 +00002158 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002159
Ted Kremenekc887d132009-04-29 18:50:19 +00002160 default:
2161 return NULL;
2162 }
Mike Stump1eb44332009-09-09 15:08:12 +00002163
Ted Kremenekc887d132009-04-29 18:50:19 +00002164 // Emit any remaining diagnostics for the argument effects (if any).
Chris Lattner5f9e2722011-07-23 10:55:15 +00002165 for (SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
Ted Kremenekc887d132009-04-29 18:50:19 +00002166 E=AEffects.end(); I != E; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +00002167
Ted Kremenekc887d132009-04-29 18:50:19 +00002168 // A bunch of things have alternate behavior under GC.
Jordy Rose35c86952011-08-24 05:47:39 +00002169 if (GCEnabled)
Ted Kremenekc887d132009-04-29 18:50:19 +00002170 switch (*I) {
2171 default: break;
2172 case Autorelease:
2173 os << "In GC mode an 'autorelease' has no effect.";
2174 continue;
2175 case IncRefMsg:
2176 os << "In GC mode the 'retain' message has no effect.";
2177 continue;
2178 case DecRefMsg:
2179 os << "In GC mode the 'release' message has no effect.";
2180 continue;
2181 }
2182 }
Mike Stump1eb44332009-09-09 15:08:12 +00002183 } while (0);
2184
Ted Kremenekc887d132009-04-29 18:50:19 +00002185 if (os.str().empty())
2186 return 0; // We have nothing to say!
Ted Kremenek2033a952009-05-13 07:12:33 +00002187
Jordy Rosef53e8c72011-08-23 19:43:16 +00002188 const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
Anna Zaks220ac8c2011-09-15 01:08:34 +00002189 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
2190 N->getLocationContext());
Ted Kremenek9c378f72011-08-12 23:37:29 +00002191 PathDiagnosticPiece *P = new PathDiagnosticEventPiece(Pos, os.str());
Mike Stump1eb44332009-09-09 15:08:12 +00002192
Ted Kremenekc887d132009-04-29 18:50:19 +00002193 // Add the range by scanning the children of the statement for any bindings
2194 // to Sym.
Mike Stump1eb44332009-09-09 15:08:12 +00002195 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
Ted Kremenek5f85e172009-07-22 22:35:28 +00002196 I!=E; ++I)
Ted Kremenek9c378f72011-08-12 23:37:29 +00002197 if (const Expr *Exp = dyn_cast_or_null<Expr>(*I))
Ted Kremenek5eca4822012-01-06 22:09:28 +00002198 if (CurrSt->getSValAsScalarOrLoc(Exp, LCtx).getAsLocSymbol() == Sym) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002199 P->addRange(Exp->getSourceRange());
2200 break;
2201 }
Mike Stump1eb44332009-09-09 15:08:12 +00002202
Ted Kremenekc887d132009-04-29 18:50:19 +00002203 return P;
2204}
2205
Anna Zakse7e01682012-02-28 22:39:22 +00002206// Find the first node in the current function context that referred to the
2207// tracked symbol and the memory location that value was stored to. Note, the
2208// value is only reported if the allocation occurred in the same function as
2209// the leak.
Zhongxing Xuc5619d92009-08-06 01:32:16 +00002210static std::pair<const ExplodedNode*,const MemRegion*>
Ted Kremenek18c66fd2011-08-15 22:09:50 +00002211GetAllocationSite(ProgramStateManager& StateMgr, const ExplodedNode *N,
Ted Kremenekc887d132009-04-29 18:50:19 +00002212 SymbolRef Sym) {
Ted Kremenek9c378f72011-08-12 23:37:29 +00002213 const ExplodedNode *Last = N;
Mike Stump1eb44332009-09-09 15:08:12 +00002214 const MemRegion* FirstBinding = 0;
Anna Zakse7e01682012-02-28 22:39:22 +00002215 const LocationContext *LeakContext = N->getLocationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002216
Ted Kremenekc887d132009-04-29 18:50:19 +00002217 while (N) {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002218 ProgramStateRef St = N->getState();
Ted Kremenekc887d132009-04-29 18:50:19 +00002219 RefBindings B = St->get<RefBindings>();
Mike Stump1eb44332009-09-09 15:08:12 +00002220
Ted Kremenekc887d132009-04-29 18:50:19 +00002221 if (!B.lookup(Sym))
2222 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002223
Anna Zaks27b867e2012-03-21 19:45:01 +00002224 StoreManager::FindUniqueBinding FB(Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002225 StateMgr.iterBindings(St, FB);
2226 if (FB) FirstBinding = FB.getRegion();
2227
Anna Zakse7e01682012-02-28 22:39:22 +00002228 // Allocation node, is the last node in the current context in which the
2229 // symbol was tracked.
2230 if (N->getLocationContext() == LeakContext)
2231 Last = N;
2232
Mike Stump1eb44332009-09-09 15:08:12 +00002233 N = N->pred_empty() ? NULL : *(N->pred_begin());
Ted Kremenekc887d132009-04-29 18:50:19 +00002234 }
Mike Stump1eb44332009-09-09 15:08:12 +00002235
Anna Zakse7e01682012-02-28 22:39:22 +00002236 // If allocation happened in a function different from the leak node context,
2237 // do not report the binding.
2238 if (N->getLocationContext() != LeakContext) {
2239 FirstBinding = 0;
2240 }
2241
Ted Kremenekc887d132009-04-29 18:50:19 +00002242 return std::make_pair(Last, FirstBinding);
2243}
2244
2245PathDiagnosticPiece*
Anna Zaks23f395e2011-08-20 01:27:22 +00002246CFRefReportVisitor::getEndPath(BugReporterContext &BRC,
2247 const ExplodedNode *EndN,
2248 BugReport &BR) {
Ted Kremenek76aadc32012-03-09 01:13:14 +00002249 BR.markInteresting(Sym);
Anna Zaks23f395e2011-08-20 01:27:22 +00002250 return BugReporterVisitor::getDefaultEndPath(BRC, EndN, BR);
Ted Kremenekc887d132009-04-29 18:50:19 +00002251}
2252
2253PathDiagnosticPiece*
Anna Zaks23f395e2011-08-20 01:27:22 +00002254CFRefLeakReportVisitor::getEndPath(BugReporterContext &BRC,
2255 const ExplodedNode *EndN,
2256 BugReport &BR) {
Mike Stump1eb44332009-09-09 15:08:12 +00002257
Ted Kremenek8966bc12009-05-06 21:39:49 +00002258 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenekc887d132009-04-29 18:50:19 +00002259 // assigned to different variables, etc.
Ted Kremenek76aadc32012-03-09 01:13:14 +00002260 BR.markInteresting(Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002261
Ted Kremenekc887d132009-04-29 18:50:19 +00002262 // We are reporting a leak. Walk up the graph to get to the first node where
2263 // the symbol appeared, and also get the first VarDecl that tracked object
2264 // is stored to.
Ted Kremenek9c378f72011-08-12 23:37:29 +00002265 const ExplodedNode *AllocNode = 0;
Ted Kremenekc887d132009-04-29 18:50:19 +00002266 const MemRegion* FirstBinding = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002267
Ted Kremenekc887d132009-04-29 18:50:19 +00002268 llvm::tie(AllocNode, FirstBinding) =
Ted Kremenekf04dced2009-05-08 23:32:51 +00002269 GetAllocationSite(BRC.getStateManager(), EndN, Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002270
Anna Zaks4fdf97b2011-09-15 18:56:07 +00002271 SourceManager& SM = BRC.getSourceManager();
Mike Stump1eb44332009-09-09 15:08:12 +00002272
Ted Kremenekc887d132009-04-29 18:50:19 +00002273 // Compute an actual location for the leak. Sometimes a leak doesn't
2274 // occur at an actual statement (e.g., transition between blocks; end
2275 // of function) so we need to walk the graph and compute a real location.
Ted Kremenek9c378f72011-08-12 23:37:29 +00002276 const ExplodedNode *LeakN = EndN;
Anna Zaks4fdf97b2011-09-15 18:56:07 +00002277 PathDiagnosticLocation L = PathDiagnosticLocation::createEndOfPath(LeakN, SM);
Mike Stump1eb44332009-09-09 15:08:12 +00002278
Ted Kremenekc887d132009-04-29 18:50:19 +00002279 std::string sbuf;
2280 llvm::raw_string_ostream os(sbuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002281
Ted Kremenekf1365462011-05-26 18:45:44 +00002282 os << "Object leaked: ";
Mike Stump1eb44332009-09-09 15:08:12 +00002283
Ted Kremenekf1365462011-05-26 18:45:44 +00002284 if (FirstBinding) {
2285 os << "object allocated and stored into '"
2286 << FirstBinding->getString() << '\'';
2287 }
2288 else
2289 os << "allocated object";
Mike Stump1eb44332009-09-09 15:08:12 +00002290
Ted Kremenekc887d132009-04-29 18:50:19 +00002291 // Get the retain count.
2292 const RefVal* RV = EndN->getState()->get<RefBindings>(Sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002293
Ted Kremenekc887d132009-04-29 18:50:19 +00002294 if (RV->getKind() == RefVal::ErrorLeakReturned) {
2295 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
Jordy Rose5b5402b2011-07-15 22:17:54 +00002296 // objects. Only "copy", "alloc", "retain" and "new" transfer ownership
Ted Kremenekc887d132009-04-29 18:50:19 +00002297 // to the caller for NS objects.
Ted Kremenekd368d712011-05-25 06:19:45 +00002298 const Decl *D = &EndN->getCodeDecl();
2299 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2300 os << " is returned from a method whose name ('"
2301 << MD->getSelector().getAsString()
2302 << "') does not start with 'copy', 'mutableCopy', 'alloc' or 'new'."
Jordy Rose5b5402b2011-07-15 22:17:54 +00002303 " This violates the naming convention rules"
Ted Kremenekf1365462011-05-26 18:45:44 +00002304 " given in the Memory Management Guide for Cocoa";
Ted Kremenekd368d712011-05-25 06:19:45 +00002305 }
2306 else {
2307 const FunctionDecl *FD = cast<FunctionDecl>(D);
Ted Kremenekb7dcddf2011-12-22 06:35:52 +00002308 os << " is returned from a function whose name ('"
Benjamin Kramera59d20b2012-02-07 11:57:57 +00002309 << *FD
Ted Kremenekd368d712011-05-25 06:19:45 +00002310 << "') does not contain 'Copy' or 'Create'. This violates the naming"
Ted Kremenekb7dcddf2011-12-22 06:35:52 +00002311 " convention rules given in the Memory Management Guide for Core"
Ted Kremenekf1365462011-05-26 18:45:44 +00002312 " Foundation";
Ted Kremenekd368d712011-05-25 06:19:45 +00002313 }
Ted Kremenekc887d132009-04-29 18:50:19 +00002314 }
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002315 else if (RV->getKind() == RefVal::ErrorGCLeakReturned) {
Ted Kremenek9c378f72011-08-12 23:37:29 +00002316 ObjCMethodDecl &MD = cast<ObjCMethodDecl>(EndN->getCodeDecl());
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002317 os << " and returned from method '" << MD.getSelector().getAsString()
Ted Kremenek82f2be52009-05-10 16:52:15 +00002318 << "' is potentially leaked when using garbage collection. Callers "
2319 "of this method do not expect a returned object with a +1 retain "
2320 "count since they expect the object to be managed by the garbage "
2321 "collector";
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002322 }
Ted Kremenekc887d132009-04-29 18:50:19 +00002323 else
Ted Kremenekabf517c2010-10-15 22:50:23 +00002324 os << " is not referenced later in this execution path and has a retain "
Ted Kremenekf1365462011-05-26 18:45:44 +00002325 "count of +" << RV->getCount();
Mike Stump1eb44332009-09-09 15:08:12 +00002326
Ted Kremenekc887d132009-04-29 18:50:19 +00002327 return new PathDiagnosticEventPiece(L, os.str());
2328}
2329
Jordy Rose20589562011-08-24 22:39:09 +00002330CFRefLeakReport::CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts,
2331 bool GCEnabled, const SummaryLogTy &Log,
2332 ExplodedNode *n, SymbolRef sym,
Anna Zaks6a93bd52011-10-25 19:57:11 +00002333 CheckerContext &Ctx)
Jordy Rose20589562011-08-24 22:39:09 +00002334: CFRefReport(D, LOpts, GCEnabled, Log, n, sym, false) {
Mike Stump1eb44332009-09-09 15:08:12 +00002335
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00002336 // Most bug reports are cached at the location where they occurred.
Ted Kremenekc887d132009-04-29 18:50:19 +00002337 // With leaks, we want to unique them by the location where they were
2338 // allocated, and only report a single path. To do this, we need to find
2339 // the allocation site of a piece of tracked memory, which we do via a
2340 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2341 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2342 // that all ancestor nodes that represent the allocation site have the
2343 // same SourceLocation.
Ted Kremenek9c378f72011-08-12 23:37:29 +00002344 const ExplodedNode *AllocNode = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002345
Anna Zaks6a93bd52011-10-25 19:57:11 +00002346 const SourceManager& SMgr = Ctx.getSourceManager();
Anna Zaks590dd8e2011-09-20 21:38:35 +00002347
Ted Kremenekc887d132009-04-29 18:50:19 +00002348 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding.
Anna Zaks6a93bd52011-10-25 19:57:11 +00002349 GetAllocationSite(Ctx.getStateManager(), getErrorNode(), sym);
Mike Stump1eb44332009-09-09 15:08:12 +00002350
Ted Kremenekc887d132009-04-29 18:50:19 +00002351 // Get the SourceLocation for the allocation site.
2352 ProgramPoint P = AllocNode->getLocation();
Anna Zaks590dd8e2011-09-20 21:38:35 +00002353 const Stmt *AllocStmt = cast<PostStmt>(P).getStmt();
2354 Location = PathDiagnosticLocation::createBegin(AllocStmt, SMgr,
2355 n->getLocationContext());
Ted Kremenekc887d132009-04-29 18:50:19 +00002356 // Fill in the description of the bug.
2357 Description.clear();
2358 llvm::raw_string_ostream os(Description);
Ted Kremenekdd924e22009-05-02 19:05:19 +00002359 os << "Potential leak ";
Jordy Rose20589562011-08-24 22:39:09 +00002360 if (GCEnabled)
Ted Kremenekdd924e22009-05-02 19:05:19 +00002361 os << "(when using garbage collection) ";
Anna Zaks212000e2012-02-28 21:49:08 +00002362 os << "of an object";
Mike Stump1eb44332009-09-09 15:08:12 +00002363
Ted Kremenekc887d132009-04-29 18:50:19 +00002364 // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2365 if (AllocBinding)
Anna Zaks212000e2012-02-28 21:49:08 +00002366 os << " stored into '" << AllocBinding->getString() << '\'';
Anna Zaksdc757b02011-08-19 23:21:56 +00002367
Jordy Rose20589562011-08-24 22:39:09 +00002368 addVisitor(new CFRefLeakReportVisitor(sym, GCEnabled, Log));
Ted Kremenekc887d132009-04-29 18:50:19 +00002369}
2370
2371//===----------------------------------------------------------------------===//
2372// Main checker logic.
2373//===----------------------------------------------------------------------===//
2374
Ted Kremenekd593eb92009-11-25 22:17:44 +00002375namespace {
Jordy Rose910c4052011-09-02 06:44:22 +00002376class RetainCountChecker
Jordy Rose9c083b72011-08-24 18:56:32 +00002377 : public Checker< check::Bind,
Jordy Rose38f17d62011-08-23 19:01:07 +00002378 check::DeadSymbols,
Jordy Rose9c083b72011-08-24 18:56:32 +00002379 check::EndAnalysis,
Jordy Rose38f17d62011-08-23 19:01:07 +00002380 check::EndPath,
Jordy Rose67044292011-08-17 21:27:39 +00002381 check::PostStmt<BlockExpr>,
John McCallf85e1932011-06-15 23:02:42 +00002382 check::PostStmt<CastExpr>,
Jordy Rose294396b2011-08-22 23:48:23 +00002383 check::PostStmt<CallExpr>,
Jordy Rose537716a2011-08-27 22:51:26 +00002384 check::PostStmt<CXXConstructExpr>,
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002385 check::PostStmt<ObjCArrayLiteral>,
2386 check::PostStmt<ObjCDictionaryLiteral>,
Jordy Rose70fdbc32012-05-12 05:10:43 +00002387 check::PostStmt<ObjCBoxedExpr>,
Jordy Rose294396b2011-08-22 23:48:23 +00002388 check::PostObjCMessage,
Jordy Rosef53e8c72011-08-23 19:43:16 +00002389 check::PreStmt<ReturnStmt>,
Jordy Rose67044292011-08-17 21:27:39 +00002390 check::RegionChanges,
Jordy Rose76c506f2011-08-21 21:58:18 +00002391 eval::Assume,
2392 eval::Call > {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002393 mutable OwningPtr<CFRefBug> useAfterRelease, releaseNotOwned;
2394 mutable OwningPtr<CFRefBug> deallocGC, deallocNotOwned;
2395 mutable OwningPtr<CFRefBug> overAutorelease, returnNotOwnedForOwned;
2396 mutable OwningPtr<CFRefBug> leakWithinFunction, leakAtReturn;
2397 mutable OwningPtr<CFRefBug> leakWithinFunctionGC, leakAtReturnGC;
Jordy Rose38f17d62011-08-23 19:01:07 +00002398
2399 typedef llvm::DenseMap<SymbolRef, const SimpleProgramPointTag *> SymbolTagMap;
2400
2401 // This map is only used to ensure proper deletion of any allocated tags.
2402 mutable SymbolTagMap DeadSymbolTags;
2403
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002404 mutable OwningPtr<RetainSummaryManager> Summaries;
2405 mutable OwningPtr<RetainSummaryManager> SummariesGC;
Jordy Roseb6cfc092011-08-25 00:10:37 +00002406
Jordy Rosee0a5d322011-08-23 20:27:16 +00002407 mutable ARCounts::Factory ARCountFactory;
2408
Jordy Rose9c083b72011-08-24 18:56:32 +00002409 mutable SummaryLogTy SummaryLog;
2410 mutable bool ShouldResetSummaryLog;
2411
Jordy Rose2f9a66d2011-08-20 21:17:59 +00002412public:
Jordy Rose910c4052011-09-02 06:44:22 +00002413 RetainCountChecker() : ShouldResetSummaryLog(false) {}
Jordy Rose38f17d62011-08-23 19:01:07 +00002414
Jordy Rose910c4052011-09-02 06:44:22 +00002415 virtual ~RetainCountChecker() {
Jordy Rose38f17d62011-08-23 19:01:07 +00002416 DeleteContainerSeconds(DeadSymbolTags);
2417 }
2418
Jordy Rose9c083b72011-08-24 18:56:32 +00002419 void checkEndAnalysis(ExplodedGraph &G, BugReporter &BR,
2420 ExprEngine &Eng) const {
2421 // FIXME: This is a hack to make sure the summary log gets cleared between
2422 // analyses of different code bodies.
2423 //
2424 // Why is this necessary? Because a checker's lifetime is tied to a
2425 // translation unit, but an ExplodedGraph's lifetime is just a code body.
2426 // Once in a blue moon, a new ExplodedNode will have the same address as an
2427 // old one with an associated summary, and the bug report visitor gets very
2428 // confused. (To make things worse, the summary lifetime is currently also
2429 // tied to a code body, so we get a crash instead of incorrect results.)
Jordy Rose1ab51c72011-08-24 09:27:24 +00002430 //
2431 // Why is this a bad solution? Because if the lifetime of the ExplodedGraph
2432 // changes, things will start going wrong again. Really the lifetime of this
2433 // log needs to be tied to either the specific nodes in it or the entire
2434 // ExplodedGraph, not to a specific part of the code being analyzed.
2435 //
Jordy Rose9c083b72011-08-24 18:56:32 +00002436 // (Also, having stateful local data means that the same checker can't be
2437 // used from multiple threads, but a lot of checkers have incorrect
2438 // assumptions about that anyway. So that wasn't a priority at the time of
2439 // this fix.)
Jordy Rose1ab51c72011-08-24 09:27:24 +00002440 //
Jordy Rose9c083b72011-08-24 18:56:32 +00002441 // This happens at the end of analysis, but bug reports are emitted /after/
2442 // this point. So we can't just clear the summary log now. Instead, we mark
2443 // that the next time we access the summary log, it should be cleared.
2444
2445 // If we never reset the summary log during /this/ code body analysis,
2446 // there were no new summaries. There might still have been summaries from
2447 // the /last/ analysis, so clear them out to make sure the bug report
2448 // visitors don't get confused.
2449 if (ShouldResetSummaryLog)
2450 SummaryLog.clear();
2451
2452 ShouldResetSummaryLog = !SummaryLog.empty();
Jordy Rose1ab51c72011-08-24 09:27:24 +00002453 }
2454
Jordy Rose17a38e22011-09-02 05:55:19 +00002455 CFRefBug *getLeakWithinFunctionBug(const LangOptions &LOpts,
2456 bool GCEnabled) const {
2457 if (GCEnabled) {
Jordy Rosedb92bb62011-08-25 01:14:38 +00002458 if (!leakWithinFunctionGC)
Benjamin Kramerfacde172012-06-06 17:32:50 +00002459 leakWithinFunctionGC.reset(new Leak("Leak of object when using "
2460 "garbage collection"));
Jordy Rose17a38e22011-09-02 05:55:19 +00002461 return leakWithinFunctionGC.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002462 } else {
2463 if (!leakWithinFunction) {
Douglas Gregore289d812011-09-13 17:21:33 +00002464 if (LOpts.getGC() == LangOptions::HybridGC) {
Benjamin Kramerfacde172012-06-06 17:32:50 +00002465 leakWithinFunction.reset(new Leak("Leak of object when not using "
2466 "garbage collection (GC) in "
2467 "dual GC/non-GC code"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002468 } else {
Benjamin Kramerfacde172012-06-06 17:32:50 +00002469 leakWithinFunction.reset(new Leak("Leak"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002470 }
2471 }
Jordy Rose17a38e22011-09-02 05:55:19 +00002472 return leakWithinFunction.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002473 }
2474 }
2475
Jordy Rose17a38e22011-09-02 05:55:19 +00002476 CFRefBug *getLeakAtReturnBug(const LangOptions &LOpts, bool GCEnabled) const {
2477 if (GCEnabled) {
Jordy Rosedb92bb62011-08-25 01:14:38 +00002478 if (!leakAtReturnGC)
Benjamin Kramerfacde172012-06-06 17:32:50 +00002479 leakAtReturnGC.reset(new Leak("Leak of returned object when using "
2480 "garbage collection"));
Jordy Rose17a38e22011-09-02 05:55:19 +00002481 return leakAtReturnGC.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002482 } else {
2483 if (!leakAtReturn) {
Douglas Gregore289d812011-09-13 17:21:33 +00002484 if (LOpts.getGC() == LangOptions::HybridGC) {
Benjamin Kramerfacde172012-06-06 17:32:50 +00002485 leakAtReturn.reset(new Leak("Leak of returned object when not using "
2486 "garbage collection (GC) in dual "
2487 "GC/non-GC code"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002488 } else {
Benjamin Kramerfacde172012-06-06 17:32:50 +00002489 leakAtReturn.reset(new Leak("Leak of returned object"));
Jordy Rosedb92bb62011-08-25 01:14:38 +00002490 }
2491 }
Jordy Rose17a38e22011-09-02 05:55:19 +00002492 return leakAtReturn.get();
Jordy Rosedb92bb62011-08-25 01:14:38 +00002493 }
2494 }
2495
Jordy Rose17a38e22011-09-02 05:55:19 +00002496 RetainSummaryManager &getSummaryManager(ASTContext &Ctx,
2497 bool GCEnabled) const {
2498 // FIXME: We don't support ARC being turned on and off during one analysis.
2499 // (nor, for that matter, do we support changing ASTContexts)
David Blaikie4e4d0842012-03-11 07:00:24 +00002500 bool ARCEnabled = (bool)Ctx.getLangOpts().ObjCAutoRefCount;
Jordy Rose17a38e22011-09-02 05:55:19 +00002501 if (GCEnabled) {
2502 if (!SummariesGC)
Jordy Roseb6cfc092011-08-25 00:10:37 +00002503 SummariesGC.reset(new RetainSummaryManager(Ctx, true, ARCEnabled));
Jordy Rose17a38e22011-09-02 05:55:19 +00002504 else
2505 assert(SummariesGC->isARCEnabled() == ARCEnabled);
Jordy Roseb6cfc092011-08-25 00:10:37 +00002506 return *SummariesGC;
2507 } else {
Jordy Rose17a38e22011-09-02 05:55:19 +00002508 if (!Summaries)
Jordy Roseb6cfc092011-08-25 00:10:37 +00002509 Summaries.reset(new RetainSummaryManager(Ctx, false, ARCEnabled));
Jordy Rose17a38e22011-09-02 05:55:19 +00002510 else
2511 assert(Summaries->isARCEnabled() == ARCEnabled);
Jordy Roseb6cfc092011-08-25 00:10:37 +00002512 return *Summaries;
2513 }
2514 }
2515
Jordy Rose17a38e22011-09-02 05:55:19 +00002516 RetainSummaryManager &getSummaryManager(CheckerContext &C) const {
2517 return getSummaryManager(C.getASTContext(), C.isObjCGCEnabled());
2518 }
2519
Ted Kremenek8bef8232012-01-26 21:29:00 +00002520 void printState(raw_ostream &Out, ProgramStateRef State,
Jordy Rosedbd658e2011-08-28 19:11:56 +00002521 const char *NL, const char *Sep) const;
2522
Anna Zaks390909c2011-10-06 00:43:15 +00002523 void checkBind(SVal loc, SVal val, const Stmt *S, CheckerContext &C) const;
Jordy Roseab027fd2011-08-20 21:16:58 +00002524 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
2525 void checkPostStmt(const CastExpr *CE, CheckerContext &C) const;
John McCallf85e1932011-06-15 23:02:42 +00002526
Jordy Rose294396b2011-08-22 23:48:23 +00002527 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
Jordy Rose537716a2011-08-27 22:51:26 +00002528 void checkPostStmt(const CXXConstructExpr *CE, CheckerContext &C) const;
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002529 void checkPostStmt(const ObjCArrayLiteral *AL, CheckerContext &C) const;
2530 void checkPostStmt(const ObjCDictionaryLiteral *DL, CheckerContext &C) const;
Jordy Rose70fdbc32012-05-12 05:10:43 +00002531 void checkPostStmt(const ObjCBoxedExpr *BE, CheckerContext &C) const;
2532
Jordy Rose294396b2011-08-22 23:48:23 +00002533 void checkPostObjCMessage(const ObjCMessage &Msg, CheckerContext &C) const;
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002534
Jordan Rose4531b7d2012-07-02 19:27:43 +00002535 void checkSummary(const RetainSummary &Summ, const CallEvent &Call,
Jordy Rosee38dd952011-08-28 05:16:28 +00002536 CheckerContext &C) const;
Jordy Rose294396b2011-08-22 23:48:23 +00002537
Jordy Rose76c506f2011-08-21 21:58:18 +00002538 bool evalCall(const CallExpr *CE, CheckerContext &C) const;
2539
Ted Kremenek8bef8232012-01-26 21:29:00 +00002540 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Jordy Roseab027fd2011-08-20 21:16:58 +00002541 bool Assumption) const;
Jordy Rose67044292011-08-17 21:27:39 +00002542
Ted Kremenek8bef8232012-01-26 21:29:00 +00002543 ProgramStateRef
2544 checkRegionChanges(ProgramStateRef state,
Jordy Rose537716a2011-08-27 22:51:26 +00002545 const StoreManager::InvalidatedSymbols *invalidated,
2546 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00002547 ArrayRef<const MemRegion *> Regions,
Jordan Rose740d4902012-07-02 19:27:35 +00002548 const CallEvent *Call) const;
Jordy Roseab027fd2011-08-20 21:16:58 +00002549
Ted Kremenek8bef8232012-01-26 21:29:00 +00002550 bool wantsRegionChangeUpdate(ProgramStateRef state) const {
Jordy Rose2f9a66d2011-08-20 21:17:59 +00002551 return true;
Jordy Roseab027fd2011-08-20 21:16:58 +00002552 }
Jordy Rose294396b2011-08-22 23:48:23 +00002553
Jordy Rosef53e8c72011-08-23 19:43:16 +00002554 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
2555 void checkReturnWithRetEffect(const ReturnStmt *S, CheckerContext &C,
2556 ExplodedNode *Pred, RetEffect RE, RefVal X,
Ted Kremenek8bef8232012-01-26 21:29:00 +00002557 SymbolRef Sym, ProgramStateRef state) const;
Jordy Rosef53e8c72011-08-23 19:43:16 +00002558
Jordy Rose38f17d62011-08-23 19:01:07 +00002559 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Anna Zaksaf498a22011-10-25 19:56:48 +00002560 void checkEndPath(CheckerContext &C) const;
Jordy Rose38f17d62011-08-23 19:01:07 +00002561
Ted Kremenek8bef8232012-01-26 21:29:00 +00002562 ProgramStateRef updateSymbol(ProgramStateRef state, SymbolRef sym,
Jordy Rose17a38e22011-09-02 05:55:19 +00002563 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
2564 CheckerContext &C) const;
Jordy Rosee0a5d322011-08-23 20:27:16 +00002565
Ted Kremenek8bef8232012-01-26 21:29:00 +00002566 void processNonLeakError(ProgramStateRef St, SourceRange ErrorRange,
Jordy Rose294396b2011-08-22 23:48:23 +00002567 RefVal::Kind ErrorKind, SymbolRef Sym,
2568 CheckerContext &C) const;
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002569
2570 void processObjCLiterals(CheckerContext &C, const Expr *Ex) const;
Jordy Rose294396b2011-08-22 23:48:23 +00002571
Jordy Rose38f17d62011-08-23 19:01:07 +00002572 const ProgramPointTag *getDeadSymbolTag(SymbolRef sym) const;
2573
Ted Kremenek8bef8232012-01-26 21:29:00 +00002574 ProgramStateRef handleSymbolDeath(ProgramStateRef state,
Jordy Rose38f17d62011-08-23 19:01:07 +00002575 SymbolRef sid, RefVal V,
2576 SmallVectorImpl<SymbolRef> &Leaked) const;
2577
Ted Kremenek8bef8232012-01-26 21:29:00 +00002578 std::pair<ExplodedNode *, ProgramStateRef >
2579 handleAutoreleaseCounts(ProgramStateRef state,
Jordy Rose8d228632011-08-23 20:07:14 +00002580 GenericNodeBuilderRefCount Bd, ExplodedNode *Pred,
Anna Zaks6a93bd52011-10-25 19:57:11 +00002581 CheckerContext &Ctx, SymbolRef Sym, RefVal V) const;
Jordy Rose8d228632011-08-23 20:07:14 +00002582
Ted Kremenek8bef8232012-01-26 21:29:00 +00002583 ExplodedNode *processLeaks(ProgramStateRef state,
Jordy Rose38f17d62011-08-23 19:01:07 +00002584 SmallVectorImpl<SymbolRef> &Leaked,
2585 GenericNodeBuilderRefCount &Builder,
Anna Zaks6a93bd52011-10-25 19:57:11 +00002586 CheckerContext &Ctx,
Jordy Rose38f17d62011-08-23 19:01:07 +00002587 ExplodedNode *Pred = 0) const;
Ted Kremenekd593eb92009-11-25 22:17:44 +00002588};
2589} // end anonymous namespace
2590
Jordy Rose67044292011-08-17 21:27:39 +00002591namespace {
2592class StopTrackingCallback : public SymbolVisitor {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002593 ProgramStateRef state;
Jordy Rose67044292011-08-17 21:27:39 +00002594public:
Ted Kremenek8bef8232012-01-26 21:29:00 +00002595 StopTrackingCallback(ProgramStateRef st) : state(st) {}
2596 ProgramStateRef getState() const { return state; }
Jordy Rose67044292011-08-17 21:27:39 +00002597
2598 bool VisitSymbol(SymbolRef sym) {
2599 state = state->remove<RefBindings>(sym);
2600 return true;
2601 }
2602};
2603} // end anonymous namespace
2604
Jordy Rose910c4052011-09-02 06:44:22 +00002605//===----------------------------------------------------------------------===//
2606// Handle statements that may have an effect on refcounts.
2607//===----------------------------------------------------------------------===//
Jordy Rose67044292011-08-17 21:27:39 +00002608
Jordy Rose910c4052011-09-02 06:44:22 +00002609void RetainCountChecker::checkPostStmt(const BlockExpr *BE,
2610 CheckerContext &C) const {
Jordy Rose67044292011-08-17 21:27:39 +00002611
Jordy Rose910c4052011-09-02 06:44:22 +00002612 // Scan the BlockDecRefExprs for any object the retain count checker
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002613 // may be tracking.
John McCall469a1eb2011-02-02 13:00:07 +00002614 if (!BE->getBlockDecl()->hasCaptures())
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002615 return;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002616
Ted Kremenek8bef8232012-01-26 21:29:00 +00002617 ProgramStateRef state = C.getState();
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002618 const BlockDataRegion *R =
Ted Kremenek5eca4822012-01-06 22:09:28 +00002619 cast<BlockDataRegion>(state->getSVal(BE,
2620 C.getLocationContext()).getAsRegion());
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002621
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002622 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
2623 E = R->referenced_vars_end();
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002624
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002625 if (I == E)
2626 return;
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002627
Ted Kremenek67d12872009-12-07 22:05:27 +00002628 // FIXME: For now we invalidate the tracking of all symbols passed to blocks
2629 // via captured variables, even though captured variables result in a copy
2630 // and in implicit increment/decrement of a retain count.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002631 SmallVector<const MemRegion*, 10> Regions;
Anna Zaks39ac1872011-10-26 21:06:44 +00002632 const LocationContext *LC = C.getLocationContext();
Ted Kremenekc8413fd2010-12-02 07:49:45 +00002633 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002634
Ted Kremenek67d12872009-12-07 22:05:27 +00002635 for ( ; I != E; ++I) {
2636 const VarRegion *VR = *I;
2637 if (VR->getSuperRegion() == R) {
2638 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2639 }
2640 Regions.push_back(VR);
2641 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +00002642
Ted Kremenek67d12872009-12-07 22:05:27 +00002643 state =
2644 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
2645 Regions.data() + Regions.size()).getState();
Anna Zaks0bd6b112011-10-26 21:06:34 +00002646 C.addTransition(state);
Ted Kremenek38cc6bc2009-11-26 02:38:19 +00002647}
2648
Jordy Rose910c4052011-09-02 06:44:22 +00002649void RetainCountChecker::checkPostStmt(const CastExpr *CE,
2650 CheckerContext &C) const {
John McCallf85e1932011-06-15 23:02:42 +00002651 const ObjCBridgedCastExpr *BE = dyn_cast<ObjCBridgedCastExpr>(CE);
2652 if (!BE)
2653 return;
2654
John McCall71c482c2011-06-17 06:50:50 +00002655 ArgEffect AE = IncRef;
John McCallf85e1932011-06-15 23:02:42 +00002656
2657 switch (BE->getBridgeKind()) {
2658 case clang::OBC_Bridge:
2659 // Do nothing.
2660 return;
2661 case clang::OBC_BridgeRetained:
2662 AE = IncRef;
2663 break;
2664 case clang::OBC_BridgeTransfer:
2665 AE = DecRefBridgedTransfered;
2666 break;
2667 }
2668
Ted Kremenek8bef8232012-01-26 21:29:00 +00002669 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00002670 SymbolRef Sym = state->getSVal(CE, C.getLocationContext()).getAsLocSymbol();
John McCallf85e1932011-06-15 23:02:42 +00002671 if (!Sym)
2672 return;
2673 const RefVal* T = state->get<RefBindings>(Sym);
2674 if (!T)
2675 return;
2676
John McCallf85e1932011-06-15 23:02:42 +00002677 RefVal::Kind hasErr = (RefVal::Kind) 0;
Jordy Rose17a38e22011-09-02 05:55:19 +00002678 state = updateSymbol(state, Sym, *T, AE, hasErr, C);
John McCallf85e1932011-06-15 23:02:42 +00002679
2680 if (hasErr) {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002681 // FIXME: If we get an error during a bridge cast, should we report it?
2682 // Should we assert that there is no error?
John McCallf85e1932011-06-15 23:02:42 +00002683 return;
2684 }
2685
Anna Zaks0bd6b112011-10-26 21:06:34 +00002686 C.addTransition(state);
John McCallf85e1932011-06-15 23:02:42 +00002687}
2688
Jordy Rose910c4052011-09-02 06:44:22 +00002689void RetainCountChecker::checkPostStmt(const CallExpr *CE,
2690 CheckerContext &C) const {
Ted Kremenek514f2c92012-03-23 06:26:56 +00002691 if (C.wasInlined)
2692 return;
2693
Jordy Rose294396b2011-08-22 23:48:23 +00002694 // Get the callee.
Ted Kremenek8bef8232012-01-26 21:29:00 +00002695 ProgramStateRef state = C.getState();
Jordy Rose294396b2011-08-22 23:48:23 +00002696 const Expr *Callee = CE->getCallee();
Ted Kremenek5eca4822012-01-06 22:09:28 +00002697 SVal L = state->getSVal(Callee, C.getLocationContext());
Jordy Rose294396b2011-08-22 23:48:23 +00002698
Jordy Rose17a38e22011-09-02 05:55:19 +00002699 RetainSummaryManager &Summaries = getSummaryManager(C);
Jordy Rose294396b2011-08-22 23:48:23 +00002700
Jordan Rose4531b7d2012-07-02 19:27:43 +00002701 // FIXME: This tree of switching can go away if/when we add a check::postCall.
Jordy Rose294396b2011-08-22 23:48:23 +00002702 if (dyn_cast_or_null<BlockDataRegion>(L.getAsRegion())) {
Jordan Rose4531b7d2012-07-02 19:27:43 +00002703 // FIXME: Better support for blocks. For now we stop tracking anything
2704 // that is passed to blocks.
2705 // FIXME: Need to handle variables that are "captured" by the block.
2706 BlockCall Call(CE, state, C.getLocationContext());
2707 const RetainSummary *Summ = Summaries.getSummary(Call, state);
2708 checkSummary(*Summ, Call, C);
2709
Jordy Rose294396b2011-08-22 23:48:23 +00002710 } else if (const CXXMemberCallExpr *me = dyn_cast<CXXMemberCallExpr>(CE)) {
Jordan Rose4531b7d2012-07-02 19:27:43 +00002711 CXXMemberCall Call(me, state, C.getLocationContext());
2712 const RetainSummary *Summ = Summaries.getSummary(Call, state);
2713 checkSummary(*Summ, Call, C);
2714
2715 } else {
2716 FunctionCall Call(CE, state, C.getLocationContext());
2717 const RetainSummary *Summ = Summaries.getSummary(Call, state);
2718 checkSummary(*Summ, Call, C);
Jordy Rose294396b2011-08-22 23:48:23 +00002719 }
Jordy Rose294396b2011-08-22 23:48:23 +00002720}
2721
Jordy Rose910c4052011-09-02 06:44:22 +00002722void RetainCountChecker::checkPostStmt(const CXXConstructExpr *CE,
2723 CheckerContext &C) const {
Jordy Rose537716a2011-08-27 22:51:26 +00002724 const CXXConstructorDecl *Ctor = CE->getConstructor();
2725 if (!Ctor)
2726 return;
2727
Jordy Rose17a38e22011-09-02 05:55:19 +00002728 RetainSummaryManager &Summaries = getSummaryManager(C);
Anna Zaks58822c42012-05-04 22:18:39 +00002729 ProgramStateRef state = C.getState();
Jordan Rose4531b7d2012-07-02 19:27:43 +00002730 CXXConstructorCall Call(CE, state, C.getLocationContext());
Jordy Rose537716a2011-08-27 22:51:26 +00002731
Jordan Rose4531b7d2012-07-02 19:27:43 +00002732 const RetainSummary *Summ = Summaries.getSummary(Call, state);
Jordy Rose537716a2011-08-27 22:51:26 +00002733
Jordan Rose4531b7d2012-07-02 19:27:43 +00002734 checkSummary(*Summ, Call, C);
Jordy Rose537716a2011-08-27 22:51:26 +00002735}
2736
Ted Kremenek1a45a5f2012-03-06 20:06:12 +00002737void RetainCountChecker::processObjCLiterals(CheckerContext &C,
2738 const Expr *Ex) const {
2739 ProgramStateRef state = C.getState();
2740 const ExplodedNode *pred = C.getPredecessor();
2741 for (Stmt::const_child_iterator it = Ex->child_begin(), et = Ex->child_end() ;
2742 it != et ; ++it) {
2743 const Stmt *child = *it;
2744 SVal V = state->getSVal(child, pred->getLocationContext());
2745 if (SymbolRef sym = V.getAsSymbol())
2746 if (const RefVal* T = state->get<RefBindings>(sym)) {
2747 RefVal::Kind hasErr = (RefVal::Kind) 0;
2748 state = updateSymbol(state, sym, *T, MayEscape, hasErr, C);
2749 if (hasErr) {
2750 processNonLeakError(state, child->getSourceRange(), hasErr, sym, C);
2751 return;
2752 }
2753 }
2754 }
2755
2756 // Return the object as autoreleased.
2757 // RetEffect RE = RetEffect::MakeNotOwned(RetEffect::ObjC);
2758 if (SymbolRef sym =
2759 state->getSVal(Ex, pred->getLocationContext()).getAsSymbol()) {
2760 QualType ResultTy = Ex->getType();
2761 state = state->set<RefBindings>(sym, RefVal::makeNotOwned(RetEffect::ObjC,
2762 ResultTy));
2763 }
2764
2765 C.addTransition(state);
2766}
2767
2768void RetainCountChecker::checkPostStmt(const ObjCArrayLiteral *AL,
2769 CheckerContext &C) const {
2770 // Apply the 'MayEscape' to all values.
2771 processObjCLiterals(C, AL);
2772}
2773
2774void RetainCountChecker::checkPostStmt(const ObjCDictionaryLiteral *DL,
2775 CheckerContext &C) const {
2776 // Apply the 'MayEscape' to all keys and values.
2777 processObjCLiterals(C, DL);
2778}
2779
Jordy Rose70fdbc32012-05-12 05:10:43 +00002780void RetainCountChecker::checkPostStmt(const ObjCBoxedExpr *Ex,
2781 CheckerContext &C) const {
2782 const ExplodedNode *Pred = C.getPredecessor();
2783 const LocationContext *LCtx = Pred->getLocationContext();
2784 ProgramStateRef State = Pred->getState();
2785
2786 if (SymbolRef Sym = State->getSVal(Ex, LCtx).getAsSymbol()) {
2787 QualType ResultTy = Ex->getType();
2788 State = State->set<RefBindings>(Sym, RefVal::makeNotOwned(RetEffect::ObjC,
2789 ResultTy));
2790 }
2791
2792 C.addTransition(State);
2793}
2794
Jordy Rose910c4052011-09-02 06:44:22 +00002795void RetainCountChecker::checkPostObjCMessage(const ObjCMessage &Msg,
2796 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002797 ProgramStateRef state = C.getState();
Jordan Rose4531b7d2012-07-02 19:27:43 +00002798 const LocationContext *LC = C.getLocationContext();
Jordan Rosecde8cdb2012-07-02 19:27:56 +00002799 // FIXME: ObjCMessage is going away.
2800 ObjCMessageSend Call(Msg.getMessageExpr(), state, LC);
Jordy Rose294396b2011-08-22 23:48:23 +00002801
Jordy Rose17a38e22011-09-02 05:55:19 +00002802 RetainSummaryManager &Summaries = getSummaryManager(C);
Jordan Rose4531b7d2012-07-02 19:27:43 +00002803 const RetainSummary *Summ = Summaries.getSummary(Call, state);
Jordy Roseb6cfc092011-08-25 00:10:37 +00002804
Jordan Rose4531b7d2012-07-02 19:27:43 +00002805 checkSummary(*Summ, Call, C);
Jordy Rose294396b2011-08-22 23:48:23 +00002806}
2807
Jordy Rose910c4052011-09-02 06:44:22 +00002808/// GetReturnType - Used to get the return type of a message expression or
2809/// function call with the intention of affixing that type to a tracked symbol.
2810/// While the the return type can be queried directly from RetEx, when
2811/// invoking class methods we augment to the return type to be that of
2812/// a pointer to the class (as opposed it just being id).
2813// FIXME: We may be able to do this with related result types instead.
2814// This function is probably overestimating.
2815static QualType GetReturnType(const Expr *RetE, ASTContext &Ctx) {
2816 QualType RetTy = RetE->getType();
2817 // If RetE is not a message expression just return its type.
2818 // If RetE is a message expression, return its types if it is something
2819 /// more specific than id.
2820 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RetE))
2821 if (const ObjCObjectPointerType *PT = RetTy->getAs<ObjCObjectPointerType>())
2822 if (PT->isObjCQualifiedIdType() || PT->isObjCIdType() ||
2823 PT->isObjCClassType()) {
2824 // At this point we know the return type of the message expression is
2825 // id, id<...>, or Class. If we have an ObjCInterfaceDecl, we know this
2826 // is a call to a class method whose type we can resolve. In such
2827 // cases, promote the return type to XXX* (where XXX is the class).
2828 const ObjCInterfaceDecl *D = ME->getReceiverInterface();
2829 return !D ? RetTy :
2830 Ctx.getObjCObjectPointerType(Ctx.getObjCInterfaceType(D));
2831 }
2832
2833 return RetTy;
2834}
2835
2836void RetainCountChecker::checkSummary(const RetainSummary &Summ,
Jordan Rose4531b7d2012-07-02 19:27:43 +00002837 const CallEvent &CallOrMsg,
Jordy Rose910c4052011-09-02 06:44:22 +00002838 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +00002839 ProgramStateRef state = C.getState();
Jordy Rose294396b2011-08-22 23:48:23 +00002840
2841 // Evaluate the effect of the arguments.
2842 RefVal::Kind hasErr = (RefVal::Kind) 0;
2843 SourceRange ErrorRange;
2844 SymbolRef ErrorSym = 0;
2845
2846 for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
Jordy Rose537716a2011-08-27 22:51:26 +00002847 SVal V = CallOrMsg.getArgSVal(idx);
Jordy Rose294396b2011-08-22 23:48:23 +00002848
2849 if (SymbolRef Sym = V.getAsLocSymbol()) {
2850 if (RefBindings::data_type *T = state->get<RefBindings>(Sym)) {
Jordy Rose17a38e22011-09-02 05:55:19 +00002851 state = updateSymbol(state, Sym, *T, Summ.getArg(idx), hasErr, C);
Jordy Rose294396b2011-08-22 23:48:23 +00002852 if (hasErr) {
2853 ErrorRange = CallOrMsg.getArgSourceRange(idx);
2854 ErrorSym = Sym;
2855 break;
2856 }
2857 }
2858 }
2859 }
2860
2861 // Evaluate the effect on the message receiver.
2862 bool ReceiverIsTracked = false;
Jordan Rose4531b7d2012-07-02 19:27:43 +00002863 if (!hasErr) {
Jordan Rosecde8cdb2012-07-02 19:27:56 +00002864 const ObjCMethodCall *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg);
Jordan Rose4531b7d2012-07-02 19:27:43 +00002865 if (MsgInvocation) {
2866 if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
2867 if (const RefVal *T = state->get<RefBindings>(Sym)) {
2868 ReceiverIsTracked = true;
2869 state = updateSymbol(state, Sym, *T, Summ.getReceiverEffect(),
2870 hasErr, C);
2871 if (hasErr) {
2872 ErrorRange = MsgInvocation->getReceiverSourceRange();
2873 ErrorSym = Sym;
2874 }
Jordy Rose294396b2011-08-22 23:48:23 +00002875 }
2876 }
2877 }
2878 }
2879
2880 // Process any errors.
2881 if (hasErr) {
2882 processNonLeakError(state, ErrorRange, hasErr, ErrorSym, C);
2883 return;
2884 }
2885
2886 // Consult the summary for the return value.
2887 RetEffect RE = Summ.getRetEffect();
2888
2889 if (RE.getKind() == RetEffect::OwnedWhenTrackedReceiver) {
Jordy Roseb6cfc092011-08-25 00:10:37 +00002890 if (ReceiverIsTracked)
Jordy Rose17a38e22011-09-02 05:55:19 +00002891 RE = getSummaryManager(C).getObjAllocRetEffect();
Jordy Roseb6cfc092011-08-25 00:10:37 +00002892 else
Jordy Rose294396b2011-08-22 23:48:23 +00002893 RE = RetEffect::MakeNoRet();
2894 }
2895
2896 switch (RE.getKind()) {
2897 default:
David Blaikie7530c032012-01-17 06:56:22 +00002898 llvm_unreachable("Unhandled RetEffect.");
Jordy Rose294396b2011-08-22 23:48:23 +00002899
2900 case RetEffect::NoRet:
2901 // No work necessary.
2902 break;
2903
2904 case RetEffect::OwnedAllocatedSymbol:
2905 case RetEffect::OwnedSymbol: {
Ted Kremenek5eca4822012-01-06 22:09:28 +00002906 SymbolRef Sym = state->getSVal(CallOrMsg.getOriginExpr(),
2907 C.getLocationContext()).getAsSymbol();
Jordy Rose294396b2011-08-22 23:48:23 +00002908 if (!Sym)
2909 break;
2910
Jordan Rose4531b7d2012-07-02 19:27:43 +00002911 // Use the result type from the CallEvent as it automatically adjusts
Jordy Rose294396b2011-08-22 23:48:23 +00002912 // for methods/functions that return references.
Jordan Rose4531b7d2012-07-02 19:27:43 +00002913 QualType ResultTy = CallOrMsg.getResultType();
Jordy Rose294396b2011-08-22 23:48:23 +00002914 state = state->set<RefBindings>(Sym, RefVal::makeOwned(RE.getObjKind(),
2915 ResultTy));
2916
2917 // FIXME: Add a flag to the checker where allocations are assumed to
2918 // *not* fail. (The code below is out-of-date, though.)
2919#if 0
2920 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) {
2921 bool isFeasible;
2922 state = state.assume(loc::SymbolVal(Sym), true, isFeasible);
2923 assert(isFeasible && "Cannot assume fresh symbol is non-null.");
2924 }
2925#endif
2926
2927 break;
2928 }
2929
2930 case RetEffect::GCNotOwnedSymbol:
2931 case RetEffect::ARCNotOwnedSymbol:
2932 case RetEffect::NotOwnedSymbol: {
2933 const Expr *Ex = CallOrMsg.getOriginExpr();
Ted Kremenek5eca4822012-01-06 22:09:28 +00002934 SymbolRef Sym = state->getSVal(Ex, C.getLocationContext()).getAsSymbol();
Jordy Rose294396b2011-08-22 23:48:23 +00002935 if (!Sym)
2936 break;
2937
2938 // Use GetReturnType in order to give [NSFoo alloc] the type NSFoo *.
2939 QualType ResultTy = GetReturnType(Ex, C.getASTContext());
2940 state = state->set<RefBindings>(Sym, RefVal::makeNotOwned(RE.getObjKind(),
2941 ResultTy));
2942 break;
2943 }
2944 }
2945
2946 // This check is actually necessary; otherwise the statement builder thinks
2947 // we've hit a previously-found path.
2948 // Normally addTransition takes care of this, but we want the node pointer.
2949 ExplodedNode *NewNode;
2950 if (state == C.getState()) {
2951 NewNode = C.getPredecessor();
2952 } else {
Anna Zaks0bd6b112011-10-26 21:06:34 +00002953 NewNode = C.addTransition(state);
Jordy Rose294396b2011-08-22 23:48:23 +00002954 }
2955
Jordy Rose9c083b72011-08-24 18:56:32 +00002956 // Annotate the node with summary we used.
2957 if (NewNode) {
2958 // FIXME: This is ugly. See checkEndAnalysis for why it's necessary.
2959 if (ShouldResetSummaryLog) {
2960 SummaryLog.clear();
2961 ShouldResetSummaryLog = false;
2962 }
Jordy Roseec9ef852011-08-23 20:55:48 +00002963 SummaryLog[NewNode] = &Summ;
Jordy Rose9c083b72011-08-24 18:56:32 +00002964 }
Jordy Rose294396b2011-08-22 23:48:23 +00002965}
2966
Jordy Rosee0a5d322011-08-23 20:27:16 +00002967
Ted Kremenek8bef8232012-01-26 21:29:00 +00002968ProgramStateRef
2969RetainCountChecker::updateSymbol(ProgramStateRef state, SymbolRef sym,
Jordy Rose910c4052011-09-02 06:44:22 +00002970 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
2971 CheckerContext &C) const {
Jordy Rosee0a5d322011-08-23 20:27:16 +00002972 // In GC mode [... release] and [... retain] do nothing.
Jordy Rose910c4052011-09-02 06:44:22 +00002973 // In ARC mode they shouldn't exist at all, but we just ignore them.
Jordy Rose17a38e22011-09-02 05:55:19 +00002974 bool IgnoreRetainMsg = C.isObjCGCEnabled();
2975 if (!IgnoreRetainMsg)
David Blaikie4e4d0842012-03-11 07:00:24 +00002976 IgnoreRetainMsg = (bool)C.getASTContext().getLangOpts().ObjCAutoRefCount;
Jordy Rose17a38e22011-09-02 05:55:19 +00002977
Jordy Rosee0a5d322011-08-23 20:27:16 +00002978 switch (E) {
Jordan Rose4531b7d2012-07-02 19:27:43 +00002979 default:
2980 break;
2981 case IncRefMsg:
2982 E = IgnoreRetainMsg ? DoNothing : IncRef;
2983 break;
2984 case DecRefMsg:
2985 E = IgnoreRetainMsg ? DoNothing : DecRef;
2986 break;
2987 case DecRefMsgAndStopTracking:
2988 E = IgnoreRetainMsg ? StopTracking : DecRefAndStopTracking;
2989 break;
2990 case MakeCollectable:
2991 E = C.isObjCGCEnabled() ? DecRef : DoNothing;
2992 break;
2993 case NewAutoreleasePool:
2994 E = C.isObjCGCEnabled() ? DoNothing : NewAutoreleasePool;
2995 break;
Jordy Rosee0a5d322011-08-23 20:27:16 +00002996 }
2997
2998 // Handle all use-after-releases.
Jordy Rose17a38e22011-09-02 05:55:19 +00002999 if (!C.isObjCGCEnabled() && V.getKind() == RefVal::Released) {
Jordy Rosee0a5d322011-08-23 20:27:16 +00003000 V = V ^ RefVal::ErrorUseAfterRelease;
3001 hasErr = V.getKind();
3002 return state->set<RefBindings>(sym, V);
3003 }
3004
3005 switch (E) {
3006 case DecRefMsg:
3007 case IncRefMsg:
3008 case MakeCollectable:
Jordan Rose4531b7d2012-07-02 19:27:43 +00003009 case DecRefMsgAndStopTracking:
Jordy Rosee0a5d322011-08-23 20:27:16 +00003010 llvm_unreachable("DecRefMsg/IncRefMsg/MakeCollectable already converted");
Jordy Rosee0a5d322011-08-23 20:27:16 +00003011
3012 case Dealloc:
3013 // Any use of -dealloc in GC is *bad*.
Jordy Rose17a38e22011-09-02 05:55:19 +00003014 if (C.isObjCGCEnabled()) {
Jordy Rosee0a5d322011-08-23 20:27:16 +00003015 V = V ^ RefVal::ErrorDeallocGC;
3016 hasErr = V.getKind();
3017 break;
3018 }
3019
3020 switch (V.getKind()) {
3021 default:
3022 llvm_unreachable("Invalid RefVal state for an explicit dealloc.");
Jordy Rosee0a5d322011-08-23 20:27:16 +00003023 case RefVal::Owned:
3024 // The object immediately transitions to the released state.
3025 V = V ^ RefVal::Released;
3026 V.clearCounts();
3027 return state->set<RefBindings>(sym, V);
3028 case RefVal::NotOwned:
3029 V = V ^ RefVal::ErrorDeallocNotOwned;
3030 hasErr = V.getKind();
3031 break;
3032 }
3033 break;
3034
3035 case NewAutoreleasePool:
Jordy Rose17a38e22011-09-02 05:55:19 +00003036 assert(!C.isObjCGCEnabled());
Jordy Rosee0a5d322011-08-23 20:27:16 +00003037 return state->add<AutoreleaseStack>(sym);
3038
3039 case MayEscape:
3040 if (V.getKind() == RefVal::Owned) {
3041 V = V ^ RefVal::NotOwned;
3042 break;
3043 }
3044
3045 // Fall-through.
3046
Jordy Rosee0a5d322011-08-23 20:27:16 +00003047 case DoNothing:
3048 return state;
3049
3050 case Autorelease:
Jordy Rose17a38e22011-09-02 05:55:19 +00003051 if (C.isObjCGCEnabled())
Jordy Rosee0a5d322011-08-23 20:27:16 +00003052 return state;
3053
3054 // Update the autorelease counts.
3055 state = SendAutorelease(state, ARCountFactory, sym);
3056 V = V.autorelease();
3057 break;
3058
3059 case StopTracking:
3060 return state->remove<RefBindings>(sym);
3061
3062 case IncRef:
3063 switch (V.getKind()) {
3064 default:
3065 llvm_unreachable("Invalid RefVal state for a retain.");
Jordy Rosee0a5d322011-08-23 20:27:16 +00003066 case RefVal::Owned:
3067 case RefVal::NotOwned:
3068 V = V + 1;
3069 break;
3070 case RefVal::Released:
3071 // Non-GC cases are handled above.
Jordy Rose17a38e22011-09-02 05:55:19 +00003072 assert(C.isObjCGCEnabled());
Jordy Rosee0a5d322011-08-23 20:27:16 +00003073 V = (V ^ RefVal::Owned) + 1;
3074 break;
3075 }
3076 break;
3077
Jordy Rosee0a5d322011-08-23 20:27:16 +00003078 case DecRef:
3079 case DecRefBridgedTransfered:
Jordan Rose4531b7d2012-07-02 19:27:43 +00003080 case DecRefAndStopTracking:
Jordy Rosee0a5d322011-08-23 20:27:16 +00003081 switch (V.getKind()) {
3082 default:
3083 // case 'RefVal::Released' handled above.
3084 llvm_unreachable("Invalid RefVal state for a release.");
Jordy Rosee0a5d322011-08-23 20:27:16 +00003085
3086 case RefVal::Owned:
3087 assert(V.getCount() > 0);
3088 if (V.getCount() == 1)
3089 V = V ^ (E == DecRefBridgedTransfered ?
3090 RefVal::NotOwned : RefVal::Released);
Jordan Rose4531b7d2012-07-02 19:27:43 +00003091 else if (E == DecRefAndStopTracking)
3092 return state->remove<RefBindings>(sym);
3093
Jordy Rosee0a5d322011-08-23 20:27:16 +00003094 V = V - 1;
3095 break;
3096
3097 case RefVal::NotOwned:
Jordan Rose4531b7d2012-07-02 19:27:43 +00003098 if (V.getCount() > 0) {
3099 if (E == DecRefAndStopTracking)
3100 return state->remove<RefBindings>(sym);
Jordy Rosee0a5d322011-08-23 20:27:16 +00003101 V = V - 1;
Jordan Rose4531b7d2012-07-02 19:27:43 +00003102 } else {
Jordy Rosee0a5d322011-08-23 20:27:16 +00003103 V = V ^ RefVal::ErrorReleaseNotOwned;
3104 hasErr = V.getKind();
3105 }
3106 break;
3107
3108 case RefVal::Released:
3109 // Non-GC cases are handled above.
Jordy Rose17a38e22011-09-02 05:55:19 +00003110 assert(C.isObjCGCEnabled());
Jordy Rosee0a5d322011-08-23 20:27:16 +00003111 V = V ^ RefVal::ErrorUseAfterRelease;
3112 hasErr = V.getKind();
3113 break;
3114 }
3115 break;
3116 }
3117 return state->set<RefBindings>(sym, V);
3118}
3119
Ted Kremenek8bef8232012-01-26 21:29:00 +00003120void RetainCountChecker::processNonLeakError(ProgramStateRef St,
Jordy Rose910c4052011-09-02 06:44:22 +00003121 SourceRange ErrorRange,
3122 RefVal::Kind ErrorKind,
3123 SymbolRef Sym,
3124 CheckerContext &C) const {
Jordy Rose294396b2011-08-22 23:48:23 +00003125 ExplodedNode *N = C.generateSink(St);
3126 if (!N)
3127 return;
3128
Jordy Rose294396b2011-08-22 23:48:23 +00003129 CFRefBug *BT;
3130 switch (ErrorKind) {
3131 default:
3132 llvm_unreachable("Unhandled error.");
Jordy Rose294396b2011-08-22 23:48:23 +00003133 case RefVal::ErrorUseAfterRelease:
Jordy Rosed6334e12011-08-25 00:34:03 +00003134 if (!useAfterRelease)
3135 useAfterRelease.reset(new UseAfterRelease());
3136 BT = &*useAfterRelease;
Jordy Rose294396b2011-08-22 23:48:23 +00003137 break;
3138 case RefVal::ErrorReleaseNotOwned:
Jordy Rosed6334e12011-08-25 00:34:03 +00003139 if (!releaseNotOwned)
3140 releaseNotOwned.reset(new BadRelease());
3141 BT = &*releaseNotOwned;
Jordy Rose294396b2011-08-22 23:48:23 +00003142 break;
3143 case RefVal::ErrorDeallocGC:
Jordy Rosed6334e12011-08-25 00:34:03 +00003144 if (!deallocGC)
3145 deallocGC.reset(new DeallocGC());
3146 BT = &*deallocGC;
Jordy Rose294396b2011-08-22 23:48:23 +00003147 break;
3148 case RefVal::ErrorDeallocNotOwned:
Jordy Rosed6334e12011-08-25 00:34:03 +00003149 if (!deallocNotOwned)
3150 deallocNotOwned.reset(new DeallocNotOwned());
3151 BT = &*deallocNotOwned;
Jordy Rose294396b2011-08-22 23:48:23 +00003152 break;
3153 }
3154
Jordy Rosed6334e12011-08-25 00:34:03 +00003155 assert(BT);
David Blaikie4e4d0842012-03-11 07:00:24 +00003156 CFRefReport *report = new CFRefReport(*BT, C.getASTContext().getLangOpts(),
Jordy Rose17a38e22011-09-02 05:55:19 +00003157 C.isObjCGCEnabled(), SummaryLog,
3158 N, Sym);
Jordy Rose294396b2011-08-22 23:48:23 +00003159 report->addRange(ErrorRange);
3160 C.EmitReport(report);
3161}
3162
Jordy Rose910c4052011-09-02 06:44:22 +00003163//===----------------------------------------------------------------------===//
3164// Handle the return values of retain-count-related functions.
3165//===----------------------------------------------------------------------===//
3166
3167bool RetainCountChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
Jordy Rose76c506f2011-08-21 21:58:18 +00003168 // Get the callee. We're only interested in simple C functions.
Ted Kremenek8bef8232012-01-26 21:29:00 +00003169 ProgramStateRef state = C.getState();
Anna Zaksb805c8f2011-12-01 05:57:37 +00003170 const FunctionDecl *FD = C.getCalleeDecl(CE);
Jordy Rose76c506f2011-08-21 21:58:18 +00003171 if (!FD)
3172 return false;
3173
3174 IdentifierInfo *II = FD->getIdentifier();
3175 if (!II)
3176 return false;
3177
3178 // For now, we're only handling the functions that return aliases of their
3179 // arguments: CFRetain and CFMakeCollectable (and their families).
3180 // Eventually we should add other functions we can model entirely,
3181 // such as CFRelease, which don't invalidate their arguments or globals.
3182 if (CE->getNumArgs() != 1)
3183 return false;
3184
3185 // Get the name of the function.
3186 StringRef FName = II->getName();
3187 FName = FName.substr(FName.find_first_not_of('_'));
3188
3189 // See if it's one of the specific functions we know how to eval.
3190 bool canEval = false;
3191
Anna Zaksb805c8f2011-12-01 05:57:37 +00003192 QualType ResultTy = CE->getCallReturnType();
Jordy Rose76c506f2011-08-21 21:58:18 +00003193 if (ResultTy->isObjCIdType()) {
3194 // Handle: id NSMakeCollectable(CFTypeRef)
3195 canEval = II->isStr("NSMakeCollectable");
3196 } else if (ResultTy->isPointerType()) {
3197 // Handle: (CF|CG)Retain
3198 // CFMakeCollectable
3199 // It's okay to be a little sloppy here (CGMakeCollectable doesn't exist).
3200 if (cocoa::isRefType(ResultTy, "CF", FName) ||
3201 cocoa::isRefType(ResultTy, "CG", FName)) {
3202 canEval = isRetain(FD, FName) || isMakeCollectable(FD, FName);
3203 }
3204 }
3205
3206 if (!canEval)
3207 return false;
3208
3209 // Bind the return value.
Ted Kremenek5eca4822012-01-06 22:09:28 +00003210 const LocationContext *LCtx = C.getLocationContext();
3211 SVal RetVal = state->getSVal(CE->getArg(0), LCtx);
Jordy Rose76c506f2011-08-21 21:58:18 +00003212 if (RetVal.isUnknown()) {
3213 // If the receiver is unknown, conjure a return value.
3214 SValBuilder &SVB = C.getSValBuilder();
Anna Zaks5d0ea6d2011-10-04 20:43:05 +00003215 unsigned Count = C.getCurrentBlockCount();
Ted Kremenek3133f792012-02-17 23:13:45 +00003216 SVal RetVal = SVB.getConjuredSymbolVal(0, CE, LCtx, ResultTy, Count);
Jordy Rose76c506f2011-08-21 21:58:18 +00003217 }
Ted Kremenek5eca4822012-01-06 22:09:28 +00003218 state = state->BindExpr(CE, LCtx, RetVal, false);
Jordy Rose76c506f2011-08-21 21:58:18 +00003219
Jordy Rose294396b2011-08-22 23:48:23 +00003220 // FIXME: This should not be necessary, but otherwise the argument seems to be
3221 // considered alive during the next statement.
3222 if (const MemRegion *ArgRegion = RetVal.getAsRegion()) {
3223 // Save the refcount status of the argument.
3224 SymbolRef Sym = RetVal.getAsLocSymbol();
3225 RefBindings::data_type *Binding = 0;
3226 if (Sym)
3227 Binding = state->get<RefBindings>(Sym);
Jordy Rose76c506f2011-08-21 21:58:18 +00003228
Jordy Rose294396b2011-08-22 23:48:23 +00003229 // Invalidate the argument region.
Anna Zaks5d0ea6d2011-10-04 20:43:05 +00003230 unsigned Count = C.getCurrentBlockCount();
Ted Kremenek3133f792012-02-17 23:13:45 +00003231 state = state->invalidateRegions(ArgRegion, CE, Count, LCtx);
Jordy Rose76c506f2011-08-21 21:58:18 +00003232
Jordy Rose294396b2011-08-22 23:48:23 +00003233 // Restore the refcount status of the argument.
3234 if (Binding)
3235 state = state->set<RefBindings>(Sym, *Binding);
3236 }
3237
Anna Zaks0bd6b112011-10-26 21:06:34 +00003238 C.addTransition(state);
Jordy Rose76c506f2011-08-21 21:58:18 +00003239 return true;
3240}
3241
Jordy Rose910c4052011-09-02 06:44:22 +00003242//===----------------------------------------------------------------------===//
3243// Handle return statements.
3244//===----------------------------------------------------------------------===//
Jordy Rosef53e8c72011-08-23 19:43:16 +00003245
Ted Kremeneke5715782012-02-25 02:09:09 +00003246// Return true if the current LocationContext has no caller context.
3247static bool inTopFrame(CheckerContext &C) {
3248 const LocationContext *LC = C.getLocationContext();
3249 return LC->getParent() == 0;
3250}
3251
Jordy Rose910c4052011-09-02 06:44:22 +00003252void RetainCountChecker::checkPreStmt(const ReturnStmt *S,
3253 CheckerContext &C) const {
Ted Kremeneke5715782012-02-25 02:09:09 +00003254
3255 // Only adjust the reference count if this is the top-level call frame,
3256 // and not the result of inlining. In the future, we should do
3257 // better checking even for inlined calls, and see if they match
3258 // with their expected semantics (e.g., the method should return a retained
3259 // object, etc.).
3260 if (!inTopFrame(C))
3261 return;
3262
Jordy Rosef53e8c72011-08-23 19:43:16 +00003263 const Expr *RetE = S->getRetValue();
3264 if (!RetE)
3265 return;
3266
Ted Kremenek8bef8232012-01-26 21:29:00 +00003267 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00003268 SymbolRef Sym =
3269 state->getSValAsScalarOrLoc(RetE, C.getLocationContext()).getAsLocSymbol();
Jordy Rosef53e8c72011-08-23 19:43:16 +00003270 if (!Sym)
3271 return;
3272
3273 // Get the reference count binding (if any).
3274 const RefVal *T = state->get<RefBindings>(Sym);
3275 if (!T)
3276 return;
3277
3278 // Change the reference count.
3279 RefVal X = *T;
3280
3281 switch (X.getKind()) {
3282 case RefVal::Owned: {
3283 unsigned cnt = X.getCount();
3284 assert(cnt > 0);
3285 X.setCount(cnt - 1);
3286 X = X ^ RefVal::ReturnedOwned;
3287 break;
3288 }
3289
3290 case RefVal::NotOwned: {
3291 unsigned cnt = X.getCount();
3292 if (cnt) {
3293 X.setCount(cnt - 1);
3294 X = X ^ RefVal::ReturnedOwned;
3295 }
3296 else {
3297 X = X ^ RefVal::ReturnedNotOwned;
3298 }
3299 break;
3300 }
3301
3302 default:
3303 return;
3304 }
3305
3306 // Update the binding.
3307 state = state->set<RefBindings>(Sym, X);
Anna Zaks0bd6b112011-10-26 21:06:34 +00003308 ExplodedNode *Pred = C.addTransition(state);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003309
3310 // At this point we have updated the state properly.
3311 // Everything after this is merely checking to see if the return value has
3312 // been over- or under-retained.
3313
3314 // Did we cache out?
3315 if (!Pred)
3316 return;
3317
Jordy Rosef53e8c72011-08-23 19:43:16 +00003318 // Update the autorelease counts.
3319 static SimpleProgramPointTag
Jordy Rose910c4052011-09-02 06:44:22 +00003320 AutoreleaseTag("RetainCountChecker : Autorelease");
Anna Zaks4eff8232011-10-05 23:44:11 +00003321 GenericNodeBuilderRefCount Bd(C, &AutoreleaseTag);
Anna Zaks6a93bd52011-10-25 19:57:11 +00003322 llvm::tie(Pred, state) = handleAutoreleaseCounts(state, Bd, Pred, C, Sym, X);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003323
3324 // Did we cache out?
Jordy Rose8d228632011-08-23 20:07:14 +00003325 if (!Pred)
Jordy Rosef53e8c72011-08-23 19:43:16 +00003326 return;
3327
3328 // Get the updated binding.
3329 T = state->get<RefBindings>(Sym);
3330 assert(T);
3331 X = *T;
3332
3333 // Consult the summary of the enclosing method.
Jordy Rose17a38e22011-09-02 05:55:19 +00003334 RetainSummaryManager &Summaries = getSummaryManager(C);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003335 const Decl *CD = &Pred->getCodeDecl();
Jordan Rose4531b7d2012-07-02 19:27:43 +00003336 RetEffect RE = RetEffect::MakeNoRet();
Jordy Rosef53e8c72011-08-23 19:43:16 +00003337
Jordan Rose4531b7d2012-07-02 19:27:43 +00003338 // FIXME: What is the convention for blocks? Is there one?
Jordy Rosef53e8c72011-08-23 19:43:16 +00003339 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CD)) {
Jordy Roseb6cfc092011-08-25 00:10:37 +00003340 const RetainSummary *Summ = Summaries.getMethodSummary(MD);
Jordan Rose4531b7d2012-07-02 19:27:43 +00003341 RE = Summ->getRetEffect();
3342 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) {
3343 if (!isa<CXXMethodDecl>(FD)) {
3344 const RetainSummary *Summ = Summaries.getFunctionSummary(FD);
3345 RE = Summ->getRetEffect();
3346 }
Jordy Rosef53e8c72011-08-23 19:43:16 +00003347 }
3348
Jordan Rose4531b7d2012-07-02 19:27:43 +00003349 checkReturnWithRetEffect(S, C, Pred, RE, X, Sym, state);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003350}
3351
Jordy Rose910c4052011-09-02 06:44:22 +00003352void RetainCountChecker::checkReturnWithRetEffect(const ReturnStmt *S,
3353 CheckerContext &C,
3354 ExplodedNode *Pred,
3355 RetEffect RE, RefVal X,
3356 SymbolRef Sym,
Ted Kremenek8bef8232012-01-26 21:29:00 +00003357 ProgramStateRef state) const {
Jordy Rosef53e8c72011-08-23 19:43:16 +00003358 // Any leaks or other errors?
3359 if (X.isReturnedOwned() && X.getCount() == 0) {
3360 if (RE.getKind() != RetEffect::NoRet) {
3361 bool hasError = false;
Jordy Rose17a38e22011-09-02 05:55:19 +00003362 if (C.isObjCGCEnabled() && RE.getObjKind() == RetEffect::ObjC) {
Jordy Rosef53e8c72011-08-23 19:43:16 +00003363 // Things are more complicated with garbage collection. If the
3364 // returned object is suppose to be an Objective-C object, we have
3365 // a leak (as the caller expects a GC'ed object) because no
3366 // method should return ownership unless it returns a CF object.
3367 hasError = true;
3368 X = X ^ RefVal::ErrorGCLeakReturned;
3369 }
3370 else if (!RE.isOwned()) {
3371 // Either we are using GC and the returned object is a CF type
3372 // or we aren't using GC. In either case, we expect that the
3373 // enclosing method is expected to return ownership.
3374 hasError = true;
3375 X = X ^ RefVal::ErrorLeakReturned;
3376 }
3377
3378 if (hasError) {
3379 // Generate an error node.
3380 state = state->set<RefBindings>(Sym, X);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003381
3382 static SimpleProgramPointTag
Jordy Rose910c4052011-09-02 06:44:22 +00003383 ReturnOwnLeakTag("RetainCountChecker : ReturnsOwnLeak");
Anna Zaks0bd6b112011-10-26 21:06:34 +00003384 ExplodedNode *N = C.addTransition(state, Pred, &ReturnOwnLeakTag);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003385 if (N) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003386 const LangOptions &LOpts = C.getASTContext().getLangOpts();
Jordy Rose17a38e22011-09-02 05:55:19 +00003387 bool GCEnabled = C.isObjCGCEnabled();
Jordy Rosef53e8c72011-08-23 19:43:16 +00003388 CFRefReport *report =
Jordy Rose17a38e22011-09-02 05:55:19 +00003389 new CFRefLeakReport(*getLeakAtReturnBug(LOpts, GCEnabled),
3390 LOpts, GCEnabled, SummaryLog,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003391 N, Sym, C);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003392 C.EmitReport(report);
3393 }
3394 }
3395 }
3396 } else if (X.isReturnedNotOwned()) {
3397 if (RE.isOwned()) {
3398 // Trying to return a not owned object to a caller expecting an
3399 // owned object.
3400 state = state->set<RefBindings>(Sym, X ^ RefVal::ErrorReturnedNotOwned);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003401
3402 static SimpleProgramPointTag
Jordy Rose910c4052011-09-02 06:44:22 +00003403 ReturnNotOwnedTag("RetainCountChecker : ReturnNotOwnedForOwned");
Anna Zaks0bd6b112011-10-26 21:06:34 +00003404 ExplodedNode *N = C.addTransition(state, Pred, &ReturnNotOwnedTag);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003405 if (N) {
Jordy Rosed6334e12011-08-25 00:34:03 +00003406 if (!returnNotOwnedForOwned)
3407 returnNotOwnedForOwned.reset(new ReturnedNotOwnedForOwned());
3408
Jordy Rosef53e8c72011-08-23 19:43:16 +00003409 CFRefReport *report =
Jordy Rosed6334e12011-08-25 00:34:03 +00003410 new CFRefReport(*returnNotOwnedForOwned,
David Blaikie4e4d0842012-03-11 07:00:24 +00003411 C.getASTContext().getLangOpts(),
Jordy Rose17a38e22011-09-02 05:55:19 +00003412 C.isObjCGCEnabled(), SummaryLog, N, Sym);
Jordy Rosef53e8c72011-08-23 19:43:16 +00003413 C.EmitReport(report);
3414 }
3415 }
3416 }
3417}
3418
Jordy Rose8d228632011-08-23 20:07:14 +00003419//===----------------------------------------------------------------------===//
Jordy Rose910c4052011-09-02 06:44:22 +00003420// Check various ways a symbol can be invalidated.
3421//===----------------------------------------------------------------------===//
3422
Anna Zaks390909c2011-10-06 00:43:15 +00003423void RetainCountChecker::checkBind(SVal loc, SVal val, const Stmt *S,
Jordy Rose910c4052011-09-02 06:44:22 +00003424 CheckerContext &C) const {
3425 // Are we storing to something that causes the value to "escape"?
3426 bool escapes = true;
3427
3428 // A value escapes in three possible cases (this may change):
3429 //
3430 // (1) we are binding to something that is not a memory region.
3431 // (2) we are binding to a memregion that does not have stack storage
3432 // (3) we are binding to a memregion with stack storage that the store
3433 // does not understand.
Ted Kremenek8bef8232012-01-26 21:29:00 +00003434 ProgramStateRef state = C.getState();
Jordy Rose910c4052011-09-02 06:44:22 +00003435
3436 if (loc::MemRegionVal *regionLoc = dyn_cast<loc::MemRegionVal>(&loc)) {
3437 escapes = !regionLoc->getRegion()->hasStackStorage();
3438
3439 if (!escapes) {
3440 // To test (3), generate a new state with the binding added. If it is
3441 // the same state, then it escapes (since the store cannot represent
3442 // the binding).
Anna Zakse7958da2012-05-02 00:15:40 +00003443 // Do this only if we know that the store is not supposed to generate the
3444 // same state.
3445 SVal StoredVal = state->getSVal(regionLoc->getRegion());
3446 if (StoredVal != val)
3447 escapes = (state == (state->bindLoc(*regionLoc, val)));
Jordy Rose910c4052011-09-02 06:44:22 +00003448 }
Ted Kremenekde5b4fb2012-03-27 01:12:45 +00003449 if (!escapes) {
3450 // Case 4: We do not currently model what happens when a symbol is
3451 // assigned to a struct field, so be conservative here and let the symbol
3452 // go. TODO: This could definitely be improved upon.
3453 escapes = !isa<VarRegion>(regionLoc->getRegion());
3454 }
Jordy Rose910c4052011-09-02 06:44:22 +00003455 }
3456
3457 // If our store can represent the binding and we aren't storing to something
3458 // that doesn't have local storage then just return and have the simulation
3459 // state continue as is.
3460 if (!escapes)
3461 return;
3462
3463 // Otherwise, find all symbols referenced by 'val' that we are tracking
3464 // and stop tracking them.
3465 state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
Anna Zaks0bd6b112011-10-26 21:06:34 +00003466 C.addTransition(state);
Jordy Rose910c4052011-09-02 06:44:22 +00003467}
3468
Ted Kremenek8bef8232012-01-26 21:29:00 +00003469ProgramStateRef RetainCountChecker::evalAssume(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003470 SVal Cond,
3471 bool Assumption) const {
3472
3473 // FIXME: We may add to the interface of evalAssume the list of symbols
3474 // whose assumptions have changed. For now we just iterate through the
3475 // bindings and check if any of the tracked symbols are NULL. This isn't
3476 // too bad since the number of symbols we will track in practice are
3477 // probably small and evalAssume is only called at branches and a few
3478 // other places.
3479 RefBindings B = state->get<RefBindings>();
3480
3481 if (B.isEmpty())
3482 return state;
3483
3484 bool changed = false;
3485 RefBindings::Factory &RefBFactory = state->get_context<RefBindings>();
3486
3487 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
3488 // Check if the symbol is null (or equal to any constant).
3489 // If this is the case, stop tracking the symbol.
3490 if (state->getSymVal(I.getKey())) {
3491 changed = true;
3492 B = RefBFactory.remove(B, I.getKey());
3493 }
3494 }
3495
3496 if (changed)
3497 state = state->set<RefBindings>(B);
3498
3499 return state;
3500}
3501
Ted Kremenek8bef8232012-01-26 21:29:00 +00003502ProgramStateRef
3503RetainCountChecker::checkRegionChanges(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003504 const StoreManager::InvalidatedSymbols *invalidated,
3505 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00003506 ArrayRef<const MemRegion *> Regions,
Jordan Rose740d4902012-07-02 19:27:35 +00003507 const CallEvent *Call) const {
Jordy Rose910c4052011-09-02 06:44:22 +00003508 if (!invalidated)
3509 return state;
3510
3511 llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
3512 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
3513 E = ExplicitRegions.end(); I != E; ++I) {
3514 if (const SymbolicRegion *SR = (*I)->StripCasts()->getAs<SymbolicRegion>())
3515 WhitelistedSymbols.insert(SR->getSymbol());
3516 }
3517
3518 for (StoreManager::InvalidatedSymbols::const_iterator I=invalidated->begin(),
3519 E = invalidated->end(); I!=E; ++I) {
3520 SymbolRef sym = *I;
3521 if (WhitelistedSymbols.count(sym))
3522 continue;
3523 // Remove any existing reference-count binding.
3524 state = state->remove<RefBindings>(sym);
3525 }
3526 return state;
3527}
3528
3529//===----------------------------------------------------------------------===//
Jordy Rose8d228632011-08-23 20:07:14 +00003530// Handle dead symbols and end-of-path.
3531//===----------------------------------------------------------------------===//
3532
Ted Kremenek8bef8232012-01-26 21:29:00 +00003533std::pair<ExplodedNode *, ProgramStateRef >
3534RetainCountChecker::handleAutoreleaseCounts(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003535 GenericNodeBuilderRefCount Bd,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003536 ExplodedNode *Pred,
3537 CheckerContext &Ctx,
Jordy Rose910c4052011-09-02 06:44:22 +00003538 SymbolRef Sym, RefVal V) const {
Jordy Rose8d228632011-08-23 20:07:14 +00003539 unsigned ACnt = V.getAutoreleaseCount();
3540
3541 // No autorelease counts? Nothing to be done.
3542 if (!ACnt)
3543 return std::make_pair(Pred, state);
3544
Anna Zaks6a93bd52011-10-25 19:57:11 +00003545 assert(!Ctx.isObjCGCEnabled() && "Autorelease counts in GC mode?");
Jordy Rose8d228632011-08-23 20:07:14 +00003546 unsigned Cnt = V.getCount();
3547
3548 // FIXME: Handle sending 'autorelease' to already released object.
3549
3550 if (V.getKind() == RefVal::ReturnedOwned)
3551 ++Cnt;
3552
3553 if (ACnt <= Cnt) {
3554 if (ACnt == Cnt) {
3555 V.clearCounts();
3556 if (V.getKind() == RefVal::ReturnedOwned)
3557 V = V ^ RefVal::ReturnedNotOwned;
3558 else
3559 V = V ^ RefVal::NotOwned;
3560 } else {
3561 V.setCount(Cnt - ACnt);
3562 V.setAutoreleaseCount(0);
3563 }
3564 state = state->set<RefBindings>(Sym, V);
3565 ExplodedNode *N = Bd.MakeNode(state, Pred);
3566 if (N == 0)
3567 state = 0;
3568 return std::make_pair(N, state);
3569 }
3570
3571 // Woah! More autorelease counts then retain counts left.
3572 // Emit hard error.
3573 V = V ^ RefVal::ErrorOverAutorelease;
3574 state = state->set<RefBindings>(Sym, V);
3575
Anna Zaksf05aac82011-10-18 23:05:58 +00003576 if (ExplodedNode *N = Bd.MakeNode(state, Pred, true)) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003577 SmallString<128> sbuf;
Jordy Rose8d228632011-08-23 20:07:14 +00003578 llvm::raw_svector_ostream os(sbuf);
3579 os << "Object over-autoreleased: object was sent -autorelease ";
3580 if (V.getAutoreleaseCount() > 1)
3581 os << V.getAutoreleaseCount() << " times ";
3582 os << "but the object has a +" << V.getCount() << " retain count";
3583
Jordy Rosed6334e12011-08-25 00:34:03 +00003584 if (!overAutorelease)
3585 overAutorelease.reset(new OverAutorelease());
3586
David Blaikie4e4d0842012-03-11 07:00:24 +00003587 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
Jordy Rose8d228632011-08-23 20:07:14 +00003588 CFRefReport *report =
Jordy Rosed6334e12011-08-25 00:34:03 +00003589 new CFRefReport(*overAutorelease, LOpts, /* GCEnabled = */ false,
3590 SummaryLog, N, Sym, os.str());
Anna Zaks6a93bd52011-10-25 19:57:11 +00003591 Ctx.EmitReport(report);
Jordy Rose8d228632011-08-23 20:07:14 +00003592 }
3593
Ted Kremenek8bef8232012-01-26 21:29:00 +00003594 return std::make_pair((ExplodedNode *)0, (ProgramStateRef )0);
Jordy Rose8d228632011-08-23 20:07:14 +00003595}
Jordy Rose38f17d62011-08-23 19:01:07 +00003596
Ted Kremenek8bef8232012-01-26 21:29:00 +00003597ProgramStateRef
3598RetainCountChecker::handleSymbolDeath(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003599 SymbolRef sid, RefVal V,
Jordy Rose38f17d62011-08-23 19:01:07 +00003600 SmallVectorImpl<SymbolRef> &Leaked) const {
Jordy Rose53376122011-08-24 04:48:19 +00003601 bool hasLeak = false;
Jordy Rose38f17d62011-08-23 19:01:07 +00003602 if (V.isOwned())
3603 hasLeak = true;
3604 else if (V.isNotOwned() || V.isReturnedOwned())
3605 hasLeak = (V.getCount() > 0);
3606
3607 if (!hasLeak)
3608 return state->remove<RefBindings>(sid);
3609
3610 Leaked.push_back(sid);
3611 return state->set<RefBindings>(sid, V ^ RefVal::ErrorLeak);
3612}
3613
3614ExplodedNode *
Ted Kremenek8bef8232012-01-26 21:29:00 +00003615RetainCountChecker::processLeaks(ProgramStateRef state,
Jordy Rose910c4052011-09-02 06:44:22 +00003616 SmallVectorImpl<SymbolRef> &Leaked,
3617 GenericNodeBuilderRefCount &Builder,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003618 CheckerContext &Ctx,
3619 ExplodedNode *Pred) const {
Jordy Rose38f17d62011-08-23 19:01:07 +00003620 if (Leaked.empty())
3621 return Pred;
3622
3623 // Generate an intermediate node representing the leak point.
3624 ExplodedNode *N = Builder.MakeNode(state, Pred);
3625
3626 if (N) {
3627 for (SmallVectorImpl<SymbolRef>::iterator
3628 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3629
David Blaikie4e4d0842012-03-11 07:00:24 +00003630 const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
Anna Zaks6a93bd52011-10-25 19:57:11 +00003631 bool GCEnabled = Ctx.isObjCGCEnabled();
Jordy Rose17a38e22011-09-02 05:55:19 +00003632 CFRefBug *BT = Pred ? getLeakWithinFunctionBug(LOpts, GCEnabled)
3633 : getLeakAtReturnBug(LOpts, GCEnabled);
Jordy Rose38f17d62011-08-23 19:01:07 +00003634 assert(BT && "BugType not initialized.");
Jordy Rose20589562011-08-24 22:39:09 +00003635
Jordy Rose17a38e22011-09-02 05:55:19 +00003636 CFRefLeakReport *report = new CFRefLeakReport(*BT, LOpts, GCEnabled,
Anna Zaks6a93bd52011-10-25 19:57:11 +00003637 SummaryLog, N, *I, Ctx);
3638 Ctx.EmitReport(report);
Jordy Rose38f17d62011-08-23 19:01:07 +00003639 }
3640 }
3641
3642 return N;
3643}
3644
Anna Zaksaf498a22011-10-25 19:56:48 +00003645void RetainCountChecker::checkEndPath(CheckerContext &Ctx) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +00003646 ProgramStateRef state = Ctx.getState();
Anna Zaksaf498a22011-10-25 19:56:48 +00003647 GenericNodeBuilderRefCount Bd(Ctx);
Jordy Rose38f17d62011-08-23 19:01:07 +00003648 RefBindings B = state->get<RefBindings>();
Anna Zaksaf498a22011-10-25 19:56:48 +00003649 ExplodedNode *Pred = Ctx.getPredecessor();
Jordy Rose38f17d62011-08-23 19:01:07 +00003650
3651 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Anna Zaks6a93bd52011-10-25 19:57:11 +00003652 llvm::tie(Pred, state) = handleAutoreleaseCounts(state, Bd, Pred, Ctx,
Jordy Rose8d228632011-08-23 20:07:14 +00003653 I->first, I->second);
3654 if (!state)
Jordy Rose38f17d62011-08-23 19:01:07 +00003655 return;
3656 }
3657
Ted Kremenek0cf3d472012-02-07 00:24:33 +00003658 // If the current LocationContext has a parent, don't check for leaks.
3659 // We will do that later.
3660 // FIXME: we should instead check for imblances of the retain/releases,
3661 // and suggest annotations.
3662 if (Ctx.getLocationContext()->getParent())
3663 return;
3664
Jordy Rose38f17d62011-08-23 19:01:07 +00003665 B = state->get<RefBindings>();
3666 SmallVector<SymbolRef, 10> Leaked;
3667
3668 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I)
Jordy Rose8d228632011-08-23 20:07:14 +00003669 state = handleSymbolDeath(state, I->first, I->second, Leaked);
Jordy Rose38f17d62011-08-23 19:01:07 +00003670
Anna Zaks6a93bd52011-10-25 19:57:11 +00003671 processLeaks(state, Leaked, Bd, Ctx, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003672}
3673
3674const ProgramPointTag *
Jordy Rose910c4052011-09-02 06:44:22 +00003675RetainCountChecker::getDeadSymbolTag(SymbolRef sym) const {
Jordy Rose38f17d62011-08-23 19:01:07 +00003676 const SimpleProgramPointTag *&tag = DeadSymbolTags[sym];
3677 if (!tag) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003678 SmallString<64> buf;
Jordy Rose38f17d62011-08-23 19:01:07 +00003679 llvm::raw_svector_ostream out(buf);
Anna Zaksf62ceec2011-12-05 18:58:11 +00003680 out << "RetainCountChecker : Dead Symbol : ";
3681 sym->dumpToStream(out);
Jordy Rose38f17d62011-08-23 19:01:07 +00003682 tag = new SimpleProgramPointTag(out.str());
3683 }
3684 return tag;
3685}
3686
Jordy Rose910c4052011-09-02 06:44:22 +00003687void RetainCountChecker::checkDeadSymbols(SymbolReaper &SymReaper,
3688 CheckerContext &C) const {
Jordy Rose38f17d62011-08-23 19:01:07 +00003689 ExplodedNode *Pred = C.getPredecessor();
3690
Ted Kremenek8bef8232012-01-26 21:29:00 +00003691 ProgramStateRef state = C.getState();
Jordy Rose38f17d62011-08-23 19:01:07 +00003692 RefBindings B = state->get<RefBindings>();
3693
3694 // Update counts from autorelease pools
3695 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3696 E = SymReaper.dead_end(); I != E; ++I) {
3697 SymbolRef Sym = *I;
3698 if (const RefVal *T = B.lookup(Sym)){
3699 // Use the symbol as the tag.
3700 // FIXME: This might not be as unique as we would like.
Anna Zaks4eff8232011-10-05 23:44:11 +00003701 GenericNodeBuilderRefCount Bd(C, getDeadSymbolTag(Sym));
Anna Zaks6a93bd52011-10-25 19:57:11 +00003702 llvm::tie(Pred, state) = handleAutoreleaseCounts(state, Bd, Pred, C,
Jordy Rose8d228632011-08-23 20:07:14 +00003703 Sym, *T);
3704 if (!state)
Jordy Rose38f17d62011-08-23 19:01:07 +00003705 return;
3706 }
3707 }
3708
3709 B = state->get<RefBindings>();
3710 SmallVector<SymbolRef, 10> Leaked;
3711
3712 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3713 E = SymReaper.dead_end(); I != E; ++I) {
3714 if (const RefVal *T = B.lookup(*I))
3715 state = handleSymbolDeath(state, *I, *T, Leaked);
3716 }
3717
3718 {
Anna Zaks4eff8232011-10-05 23:44:11 +00003719 GenericNodeBuilderRefCount Bd(C, this);
Anna Zaks6a93bd52011-10-25 19:57:11 +00003720 Pred = processLeaks(state, Leaked, Bd, C, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003721 }
3722
3723 // Did we cache out?
3724 if (!Pred)
3725 return;
3726
3727 // Now generate a new node that nukes the old bindings.
3728 RefBindings::Factory &F = state->get_context<RefBindings>();
3729
3730 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3731 E = SymReaper.dead_end(); I != E; ++I)
3732 B = F.remove(B, *I);
3733
3734 state = state->set<RefBindings>(B);
Anna Zaks0bd6b112011-10-26 21:06:34 +00003735 C.addTransition(state, Pred);
Jordy Rose38f17d62011-08-23 19:01:07 +00003736}
3737
Ted Kremenekd593eb92009-11-25 22:17:44 +00003738//===----------------------------------------------------------------------===//
Jordy Rosedbd658e2011-08-28 19:11:56 +00003739// Debug printing of refcount bindings and autorelease pools.
3740//===----------------------------------------------------------------------===//
3741
3742static void PrintPool(raw_ostream &Out, SymbolRef Sym,
Ted Kremenek8bef8232012-01-26 21:29:00 +00003743 ProgramStateRef State) {
Jordy Rosedbd658e2011-08-28 19:11:56 +00003744 Out << ' ';
3745 if (Sym)
Anna Zaksf62ceec2011-12-05 18:58:11 +00003746 Sym->dumpToStream(Out);
Jordy Rosedbd658e2011-08-28 19:11:56 +00003747 else
3748 Out << "<pool>";
3749 Out << ":{";
3750
3751 // Get the contents of the pool.
3752 if (const ARCounts *Cnts = State->get<AutoreleasePoolContents>(Sym))
3753 for (ARCounts::iterator I = Cnts->begin(), E = Cnts->end(); I != E; ++I)
3754 Out << '(' << I.getKey() << ',' << I.getData() << ')';
3755
3756 Out << '}';
3757}
3758
Ted Kremenek8bef8232012-01-26 21:29:00 +00003759static bool UsesAutorelease(ProgramStateRef state) {
Jordy Rosedbd658e2011-08-28 19:11:56 +00003760 // A state uses autorelease if it allocated an autorelease pool or if it has
3761 // objects in the caller's autorelease pool.
3762 return !state->get<AutoreleaseStack>().isEmpty() ||
3763 state->get<AutoreleasePoolContents>(SymbolRef());
3764}
3765
Ted Kremenek8bef8232012-01-26 21:29:00 +00003766void RetainCountChecker::printState(raw_ostream &Out, ProgramStateRef State,
Jordy Rose910c4052011-09-02 06:44:22 +00003767 const char *NL, const char *Sep) const {
Jordy Rosedbd658e2011-08-28 19:11:56 +00003768
3769 RefBindings B = State->get<RefBindings>();
3770
3771 if (!B.isEmpty())
3772 Out << Sep << NL;
3773
3774 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
3775 Out << I->first << " : ";
3776 I->second.print(Out);
3777 Out << NL;
3778 }
3779
3780 // Print the autorelease stack.
3781 if (UsesAutorelease(State)) {
3782 Out << Sep << NL << "AR pool stack:";
3783 ARStack Stack = State->get<AutoreleaseStack>();
3784
3785 PrintPool(Out, SymbolRef(), State); // Print the caller's pool.
3786 for (ARStack::iterator I = Stack.begin(), E = Stack.end(); I != E; ++I)
3787 PrintPool(Out, *I, State);
3788
3789 Out << NL;
3790 }
3791}
3792
3793//===----------------------------------------------------------------------===//
Jordy Rose910c4052011-09-02 06:44:22 +00003794// Checker registration.
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00003795//===----------------------------------------------------------------------===//
3796
Jordy Rose17a38e22011-09-02 05:55:19 +00003797void ento::registerRetainCountChecker(CheckerManager &Mgr) {
Jordy Rose910c4052011-09-02 06:44:22 +00003798 Mgr.registerChecker<RetainCountChecker>();
Jordy Rose17a38e22011-09-02 05:55:19 +00003799}
3800