blob: dc9602a7b2805489257dda6591d194298ef6e19d [file] [log] [blame]
Chris Lattnerbe1a7a02008-03-15 23:59:48 +00001// CFRefCount.cpp - Transfer functions for tracking simple values -*- C++ -*--//
Ted Kremenek827f93b2008-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//
Gabor Greif2224fcb2008-03-06 10:40:09 +000010// This file defines the methods for CFRefCount, which implements
Ted Kremenek827f93b2008-03-06 00:08:09 +000011// a reference count checker for Core Foundation (Mac OS X).
12//
13//===----------------------------------------------------------------------===//
14
Ted Kremeneka7338b42008-03-11 06:39:11 +000015#include "GRSimpleVals.h"
Ted Kremenekfe30beb2008-04-30 23:47:44 +000016#include "clang/Basic/LangOptions.h"
Ted Kremenekfe4d2312008-05-01 23:13:35 +000017#include "clang/Basic/SourceManager.h"
Ted Kremeneka42be302009-02-14 01:43:44 +000018#include "clang/Analysis/PathSensitive/GRExprEngineBuilders.h"
Ted Kremenek91781202008-08-17 03:20:02 +000019#include "clang/Analysis/PathSensitive/GRStateTrait.h"
Ted Kremenekdd0126b2008-03-31 18:26:32 +000020#include "clang/Analysis/PathDiagnostic.h"
Ted Kremenek827f93b2008-03-06 00:08:09 +000021#include "clang/Analysis/LocalCheckers.h"
Ted Kremenek10fe66d2008-04-09 01:10:13 +000022#include "clang/Analysis/PathDiagnostic.h"
23#include "clang/Analysis/PathSensitive/BugReporter.h"
Ted Kremenek2ddb4b22009-02-14 03:16:10 +000024#include "clang/Analysis/PathSensitive/SymbolManager.h"
Ted Kremenekc3bc6c82009-05-06 21:39:49 +000025#include "clang/AST/DeclObjC.h"
Ted Kremeneka7338b42008-03-11 06:39:11 +000026#include "llvm/ADT/DenseMap.h"
27#include "llvm/ADT/FoldingSet.h"
28#include "llvm/ADT/ImmutableMap.h"
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +000029#include "llvm/ADT/ImmutableList.h"
Ted Kremenek2ac4ba62008-05-07 18:36:45 +000030#include "llvm/ADT/StringExtras.h"
Ted Kremenek10fe66d2008-04-09 01:10:13 +000031#include "llvm/Support/Compiler.h"
Ted Kremenekd7e26782008-05-16 18:33:44 +000032#include "llvm/ADT/STLExtras.h"
Ted Kremenek3b11f7a2008-03-11 19:44:10 +000033#include <ostream>
Ted Kremenek9449ca92008-08-12 20:41:56 +000034#include <stdarg.h>
Ted Kremenek827f93b2008-03-06 00:08:09 +000035
36using namespace clang;
Ted Kremenekb6f09542008-10-24 21:18:08 +000037
38//===----------------------------------------------------------------------===//
39// Utility functions.
40//===----------------------------------------------------------------------===//
41
Ted Kremenekb6f09542008-10-24 21:18:08 +000042// The "fundamental rule" for naming conventions of methods:
43// (url broken into two lines)
44// http://developer.apple.com/documentation/Cocoa/Conceptual/
45// MemoryMgmt/Tasks/MemoryManagementRules.html
46//
47// "You take ownership of an object if you create it using a method whose name
48// begins with “alloc” or “new” or contains “copy” (for example, alloc,
49// newObject, or mutableCopy), or if you send it a retain message. You are
50// responsible for relinquishing ownership of objects you own using release
51// or autorelease. Any other time you receive an object, you must
52// not release it."
53//
Ted Kremenek4395b452009-02-21 05:13:43 +000054
55using llvm::CStrInCStrNoCase;
Ted Kremenekfd42ffc2009-02-21 18:26:02 +000056using llvm::StringsEqualNoCase;
Ted Kremenek4395b452009-02-21 05:13:43 +000057
58enum NamingConvention { NoConvention, CreateRule, InitRule };
59
60static inline bool isWordEnd(char ch, char prev, char next) {
61 return ch == '\0'
62 || (islower(prev) && isupper(ch)) // xxxC
63 || (isupper(prev) && isupper(ch) && islower(next)) // XXCreate
64 || !isalpha(ch);
65}
66
67static inline const char* parseWord(const char* s) {
68 char ch = *s, prev = '\0';
69 assert(ch != '\0');
70 char next = *(s+1);
71 while (!isWordEnd(ch, prev, next)) {
72 prev = ch;
73 ch = next;
74 next = *((++s)+1);
75 }
76 return s;
77}
78
79static NamingConvention deriveNamingConvention(const char* s) {
80 // A method/function name may contain a prefix. We don't know it is there,
81 // however, until we encounter the first '_'.
82 bool InPossiblePrefix = true;
83 bool AtBeginning = true;
84 NamingConvention C = NoConvention;
85
86 while (*s != '\0') {
87 // Skip '_'.
88 if (*s == '_') {
89 if (InPossiblePrefix) {
90 InPossiblePrefix = false;
91 AtBeginning = true;
92 // Discard whatever 'convention' we
93 // had already derived since it occurs
94 // in the prefix.
95 C = NoConvention;
96 }
97 ++s;
98 continue;
99 }
100
101 // Skip numbers, ':', etc.
102 if (!isalpha(*s)) {
103 ++s;
104 continue;
105 }
106
107 const char *wordEnd = parseWord(s);
108 assert(wordEnd > s);
109 unsigned len = wordEnd - s;
110
111 switch (len) {
112 default:
113 break;
114 case 3:
115 // Methods starting with 'new' follow the create rule.
Ted Kremenekfd42ffc2009-02-21 18:26:02 +0000116 if (AtBeginning && StringsEqualNoCase("new", s, len))
Ted Kremenek4395b452009-02-21 05:13:43 +0000117 C = CreateRule;
118 break;
119 case 4:
120 // Methods starting with 'alloc' or contain 'copy' follow the
121 // create rule
Ted Kremenek91b79532009-03-13 20:27:06 +0000122 if (C == NoConvention && StringsEqualNoCase("copy", s, len))
Ted Kremenek4395b452009-02-21 05:13:43 +0000123 C = CreateRule;
124 else // Methods starting with 'init' follow the init rule.
Ted Kremenekfd42ffc2009-02-21 18:26:02 +0000125 if (AtBeginning && StringsEqualNoCase("init", s, len))
Ted Kremenek91b79532009-03-13 20:27:06 +0000126 C = InitRule;
127 break;
128 case 5:
129 if (AtBeginning && StringsEqualNoCase("alloc", s, len))
130 C = CreateRule;
Ted Kremenek4395b452009-02-21 05:13:43 +0000131 break;
132 }
133
134 // If we aren't in the prefix and have a derived convention then just
135 // return it now.
136 if (!InPossiblePrefix && C != NoConvention)
137 return C;
138
139 AtBeginning = false;
140 s = wordEnd;
141 }
142
143 // We will get here if there wasn't more than one word
144 // after the prefix.
145 return C;
146}
147
Ted Kremenekb6f09542008-10-24 21:18:08 +0000148static bool followsFundamentalRule(const char* s) {
Ted Kremenek4395b452009-02-21 05:13:43 +0000149 return deriveNamingConvention(s) == CreateRule;
Ted Kremenekcdd3bb22008-11-05 16:54:44 +0000150}
151
Ted Kremenek314b1952009-04-29 23:03:22 +0000152static const ObjCMethodDecl*
153ResolveToInterfaceMethodDecl(const ObjCMethodDecl *MD, ASTContext &Context) {
154 ObjCInterfaceDecl *ID =
155 const_cast<ObjCInterfaceDecl*>(MD->getClassInterface());
156
157 return MD->isInstanceMethod()
158 ? ID->lookupInstanceMethod(Context, MD->getSelector())
159 : ID->lookupClassMethod(Context, MD->getSelector());
Ted Kremenekcdd3bb22008-11-05 16:54:44 +0000160}
Ted Kremenekb6f09542008-10-24 21:18:08 +0000161
Ted Kremenek41a4bc62009-05-08 23:09:42 +0000162namespace {
163class VISIBILITY_HIDDEN GenericNodeBuilder {
164 GRStmtNodeBuilder<GRState> *SNB;
165 Stmt *S;
166 const void *tag;
167 GREndPathNodeBuilder<GRState> *ENB;
168public:
169 GenericNodeBuilder(GRStmtNodeBuilder<GRState> &snb, Stmt *s,
170 const void *t)
171 : SNB(&snb), S(s), tag(t), ENB(0) {}
172 GenericNodeBuilder(GREndPathNodeBuilder<GRState> &enb)
173 : SNB(0), S(0), tag(0), ENB(&enb) {}
174
175 ExplodedNode<GRState> *MakeNode(const GRState *state,
176 ExplodedNode<GRState> *Pred) {
177 if (SNB)
Ted Kremenek3e3328d2009-05-09 01:50:57 +0000178 return SNB->generateNode(PostStmt(S, tag), state, Pred);
Ted Kremenek41a4bc62009-05-08 23:09:42 +0000179
180 assert(ENB);
Ted Kremenek3f15aba2009-05-09 00:44:07 +0000181 return ENB->generateNode(state, Pred);
Ted Kremenek41a4bc62009-05-08 23:09:42 +0000182 }
183};
184} // end anonymous namespace
185
Ted Kremenek7d421f32008-04-09 23:49:11 +0000186//===----------------------------------------------------------------------===//
Ted Kremenek272aa852008-06-25 21:21:56 +0000187// Selector creation functions.
Ted Kremenekd9ccf682008-04-17 18:12:53 +0000188//===----------------------------------------------------------------------===//
189
Ted Kremenek1bd6ddb2008-05-01 18:31:44 +0000190static inline Selector GetNullarySelector(const char* name, ASTContext& Ctx) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +0000191 IdentifierInfo* II = &Ctx.Idents.get(name);
192 return Ctx.Selectors.getSelector(0, &II);
193}
194
Ted Kremenek0e344d42008-05-06 00:30:21 +0000195static inline Selector GetUnarySelector(const char* name, ASTContext& Ctx) {
196 IdentifierInfo* II = &Ctx.Idents.get(name);
197 return Ctx.Selectors.getSelector(1, &II);
198}
199
Ted Kremenek272aa852008-06-25 21:21:56 +0000200//===----------------------------------------------------------------------===//
201// Type querying functions.
202//===----------------------------------------------------------------------===//
203
Ted Kremenek17144e82009-01-12 21:45:02 +0000204static bool hasPrefix(const char* s, const char* prefix) {
205 if (!prefix)
206 return true;
Ted Kremenek62820d82008-05-07 20:06:41 +0000207
Ted Kremenek17144e82009-01-12 21:45:02 +0000208 char c = *s;
209 char cP = *prefix;
Ted Kremenek62820d82008-05-07 20:06:41 +0000210
Ted Kremenek17144e82009-01-12 21:45:02 +0000211 while (c != '\0' && cP != '\0') {
212 if (c != cP) break;
213 c = *(++s);
214 cP = *(++prefix);
215 }
Ted Kremenek62820d82008-05-07 20:06:41 +0000216
Ted Kremenek17144e82009-01-12 21:45:02 +0000217 return cP == '\0';
Ted Kremenek62820d82008-05-07 20:06:41 +0000218}
219
Ted Kremenek17144e82009-01-12 21:45:02 +0000220static bool hasSuffix(const char* s, const char* suffix) {
221 const char* loc = strstr(s, suffix);
222 return loc && strcmp(suffix, loc) == 0;
223}
224
225static bool isRefType(QualType RetTy, const char* prefix,
226 ASTContext* Ctx = 0, const char* name = 0) {
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000227
Ted Kremenek2f289b62009-05-12 04:53:03 +0000228 // Recursively walk the typedef stack, allowing typedefs of reference types.
229 while (1) {
230 if (TypedefType* TD = dyn_cast<TypedefType>(RetTy.getTypePtr())) {
231 const char* TDName = TD->getDecl()->getIdentifier()->getName();
232 if (hasPrefix(TDName, prefix) && hasSuffix(TDName, "Ref"))
233 return true;
234
235 RetTy = TD->getDecl()->getUnderlyingType();
236 continue;
237 }
238 break;
Ted Kremenek17144e82009-01-12 21:45:02 +0000239 }
240
241 if (!Ctx || !name)
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000242 return false;
Ted Kremenek17144e82009-01-12 21:45:02 +0000243
244 // Is the type void*?
245 const PointerType* PT = RetTy->getAsPointerType();
246 if (!(PT->getPointeeType().getUnqualifiedType() == Ctx->VoidTy))
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000247 return false;
Ted Kremenek17144e82009-01-12 21:45:02 +0000248
249 // Does the name start with the prefix?
250 return hasPrefix(name, prefix);
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000251}
252
Ted Kremenekd9ccf682008-04-17 18:12:53 +0000253//===----------------------------------------------------------------------===//
Ted Kremenek272aa852008-06-25 21:21:56 +0000254// Primitives used for constructing summaries for function/method calls.
Ted Kremenek7d421f32008-04-09 23:49:11 +0000255//===----------------------------------------------------------------------===//
256
Ted Kremenek272aa852008-06-25 21:21:56 +0000257/// ArgEffect is used to summarize a function/method call's effect on a
258/// particular argument.
Ted Kremenek6537a642009-03-17 19:42:23 +0000259enum ArgEffect { Autorelease, Dealloc, DecRef, DecRefMsg, DoNothing,
260 DoNothingByRef, IncRefMsg, IncRef, MakeCollectable, MayEscape,
261 NewAutoreleasePool, SelfOwn, StopTracking };
Ted Kremenek272aa852008-06-25 21:21:56 +0000262
Ted Kremeneka7338b42008-03-11 06:39:11 +0000263namespace llvm {
Ted Kremeneka56ae162009-05-03 05:20:50 +0000264template <> struct FoldingSetTrait<ArgEffect> {
265static inline void Profile(const ArgEffect X, FoldingSetNodeID& ID) {
266 ID.AddInteger((unsigned) X);
267}
Ted Kremenek272aa852008-06-25 21:21:56 +0000268};
Ted Kremeneka7338b42008-03-11 06:39:11 +0000269} // end llvm namespace
270
Ted Kremeneka56ae162009-05-03 05:20:50 +0000271/// ArgEffects summarizes the effects of a function/method call on all of
272/// its arguments.
273typedef llvm::ImmutableMap<unsigned,ArgEffect> ArgEffects;
274
Ted Kremeneka7338b42008-03-11 06:39:11 +0000275namespace {
Ted Kremenek272aa852008-06-25 21:21:56 +0000276
277/// RetEffect is used to summarize a function/method call's behavior with
278/// respect to its return value.
279class VISIBILITY_HIDDEN RetEffect {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000280public:
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000281 enum Kind { NoRet, Alias, OwnedSymbol, OwnedAllocatedSymbol,
Ted Kremenek382fb4e2009-04-27 19:14:45 +0000282 NotOwnedSymbol, GCNotOwnedSymbol, ReceiverAlias };
Ted Kremenek68621b92009-01-28 05:56:51 +0000283
284 enum ObjKind { CF, ObjC, AnyObj };
285
Ted Kremeneka7338b42008-03-11 06:39:11 +0000286private:
Ted Kremenek68621b92009-01-28 05:56:51 +0000287 Kind K;
288 ObjKind O;
289 unsigned index;
290
291 RetEffect(Kind k, unsigned idx = 0) : K(k), O(AnyObj), index(idx) {}
292 RetEffect(Kind k, ObjKind o) : K(k), O(o), index(0) {}
Ted Kremenek827f93b2008-03-06 00:08:09 +0000293
Ted Kremeneka7338b42008-03-11 06:39:11 +0000294public:
Ted Kremenek68621b92009-01-28 05:56:51 +0000295 Kind getKind() const { return K; }
296
297 ObjKind getObjKind() const { return O; }
Ted Kremenek272aa852008-06-25 21:21:56 +0000298
299 unsigned getIndex() const {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000300 assert(getKind() == Alias);
Ted Kremenek68621b92009-01-28 05:56:51 +0000301 return index;
Ted Kremeneka7338b42008-03-11 06:39:11 +0000302 }
Ted Kremenek827f93b2008-03-06 00:08:09 +0000303
Ted Kremenek314b1952009-04-29 23:03:22 +0000304 bool isOwned() const {
305 return K == OwnedSymbol || K == OwnedAllocatedSymbol;
306 }
Ted Kremenekde92f7c2009-05-10 06:25:57 +0000307
Ted Kremenek272aa852008-06-25 21:21:56 +0000308 static RetEffect MakeAlias(unsigned Idx) {
309 return RetEffect(Alias, Idx);
310 }
311 static RetEffect MakeReceiverAlias() {
312 return RetEffect(ReceiverAlias);
313 }
Ted Kremenek68621b92009-01-28 05:56:51 +0000314 static RetEffect MakeOwned(ObjKind o, bool isAllocated = false) {
315 return RetEffect(isAllocated ? OwnedAllocatedSymbol : OwnedSymbol, o);
Ted Kremenek272aa852008-06-25 21:21:56 +0000316 }
Ted Kremenek68621b92009-01-28 05:56:51 +0000317 static RetEffect MakeNotOwned(ObjKind o) {
318 return RetEffect(NotOwnedSymbol, o);
Ted Kremenek382fb4e2009-04-27 19:14:45 +0000319 }
320 static RetEffect MakeGCNotOwned() {
321 return RetEffect(GCNotOwnedSymbol, ObjC);
322 }
323
Ted Kremenek272aa852008-06-25 21:21:56 +0000324 static RetEffect MakeNoRet() {
325 return RetEffect(NoRet);
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000326 }
Ted Kremenek827f93b2008-03-06 00:08:09 +0000327
Ted Kremenek272aa852008-06-25 21:21:56 +0000328 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek68621b92009-01-28 05:56:51 +0000329 ID.AddInteger((unsigned)K);
330 ID.AddInteger((unsigned)O);
331 ID.AddInteger(index);
Ted Kremenek272aa852008-06-25 21:21:56 +0000332 }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000333};
Ted Kremeneka7338b42008-03-11 06:39:11 +0000334
Ted Kremenek272aa852008-06-25 21:21:56 +0000335
Ted Kremenek2f226732009-05-04 05:31:22 +0000336class VISIBILITY_HIDDEN RetainSummary {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000337 /// Args - an ordered vector of (index, ArgEffect) pairs, where index
338 /// specifies the argument (starting from 0). This can be sparsely
339 /// populated; arguments with no entry in Args use 'DefaultArgEffect'.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000340 ArgEffects Args;
Ted Kremenekbcaff792008-05-06 15:44:25 +0000341
342 /// DefaultArgEffect - The default ArgEffect to apply to arguments that
343 /// do not have an entry in Args.
344 ArgEffect DefaultArgEffect;
345
Ted Kremenek272aa852008-06-25 21:21:56 +0000346 /// Receiver - If this summary applies to an Objective-C message expression,
347 /// this is the effect applied to the state of the receiver.
Ted Kremenek266d8b62008-05-06 02:26:56 +0000348 ArgEffect Receiver;
Ted Kremenek272aa852008-06-25 21:21:56 +0000349
350 /// Ret - The effect on the return value. Used to indicate if the
351 /// function/method call returns a new tracked symbol, returns an
352 /// alias of one of the arguments in the call, and so on.
Ted Kremeneka7338b42008-03-11 06:39:11 +0000353 RetEffect Ret;
Ted Kremenek272aa852008-06-25 21:21:56 +0000354
Ted Kremenekf2717b02008-07-18 17:24:20 +0000355 /// EndPath - Indicates that execution of this method/function should
356 /// terminate the simulation of a path.
357 bool EndPath;
358
Ted Kremeneka7338b42008-03-11 06:39:11 +0000359public:
Ted Kremeneka56ae162009-05-03 05:20:50 +0000360 RetainSummary(ArgEffects A, RetEffect R, ArgEffect defaultEff,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000361 ArgEffect ReceiverEff, bool endpath = false)
362 : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R),
363 EndPath(endpath) {}
Ted Kremeneka7338b42008-03-11 06:39:11 +0000364
Ted Kremenek272aa852008-06-25 21:21:56 +0000365 /// getArg - Return the argument effect on the argument specified by
366 /// idx (starting from 0).
Ted Kremenek0d721572008-03-11 17:48:22 +0000367 ArgEffect getArg(unsigned idx) const {
Ted Kremeneka56ae162009-05-03 05:20:50 +0000368 if (const ArgEffect *AE = Args.lookup(idx))
369 return *AE;
Ted Kremenekae855d42008-04-24 17:22:33 +0000370
Ted Kremenekbcaff792008-05-06 15:44:25 +0000371 return DefaultArgEffect;
Ted Kremenek0d721572008-03-11 17:48:22 +0000372 }
373
Ted Kremenek2f226732009-05-04 05:31:22 +0000374 /// setDefaultArgEffect - Set the default argument effect.
375 void setDefaultArgEffect(ArgEffect E) {
376 DefaultArgEffect = E;
377 }
378
379 /// setArg - Set the argument effect on the argument specified by idx.
380 void setArgEffect(ArgEffects::Factory& AF, unsigned idx, ArgEffect E) {
381 Args = AF.Add(Args, idx, E);
382 }
383
Ted Kremenek272aa852008-06-25 21:21:56 +0000384 /// getRetEffect - Returns the effect on the return value of the call.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000385 RetEffect getRetEffect() const { return Ret; }
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000386
Ted Kremenek2f226732009-05-04 05:31:22 +0000387 /// setRetEffect - Set the effect of the return value of the call.
388 void setRetEffect(RetEffect E) { Ret = E; }
389
Ted Kremenekf2717b02008-07-18 17:24:20 +0000390 /// isEndPath - Returns true if executing the given method/function should
391 /// terminate the path.
392 bool isEndPath() const { return EndPath; }
393
Ted Kremenek272aa852008-06-25 21:21:56 +0000394 /// getReceiverEffect - Returns the effect on the receiver of the call.
395 /// This is only meaningful if the summary applies to an ObjCMessageExpr*.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000396 ArgEffect getReceiverEffect() const { return Receiver; }
Ted Kremenek266d8b62008-05-06 02:26:56 +0000397
Ted Kremenek2f226732009-05-04 05:31:22 +0000398 /// setReceiverEffect - Set the effect on the receiver of the call.
399 void setReceiverEffect(ArgEffect E) { Receiver = E; }
400
Ted Kremeneka56ae162009-05-03 05:20:50 +0000401 typedef ArgEffects::iterator ExprIterator;
Ted Kremeneka7338b42008-03-11 06:39:11 +0000402
Ted Kremeneka56ae162009-05-03 05:20:50 +0000403 ExprIterator begin_args() const { return Args.begin(); }
404 ExprIterator end_args() const { return Args.end(); }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000405
Ted Kremeneka56ae162009-05-03 05:20:50 +0000406 static void Profile(llvm::FoldingSetNodeID& ID, ArgEffects A,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000407 RetEffect RetEff, ArgEffect DefaultEff,
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000408 ArgEffect ReceiverEff, bool EndPath) {
Ted Kremeneka56ae162009-05-03 05:20:50 +0000409 ID.Add(A);
Ted Kremenek266d8b62008-05-06 02:26:56 +0000410 ID.Add(RetEff);
Ted Kremenekbcaff792008-05-06 15:44:25 +0000411 ID.AddInteger((unsigned) DefaultEff);
Ted Kremenek266d8b62008-05-06 02:26:56 +0000412 ID.AddInteger((unsigned) ReceiverEff);
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000413 ID.AddInteger((unsigned) EndPath);
Ted Kremeneka7338b42008-03-11 06:39:11 +0000414 }
415
416 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000417 Profile(ID, Args, Ret, DefaultArgEffect, Receiver, EndPath);
Ted Kremeneka7338b42008-03-11 06:39:11 +0000418 }
419};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000420} // end anonymous namespace
Ted Kremeneka7338b42008-03-11 06:39:11 +0000421
Ted Kremenek272aa852008-06-25 21:21:56 +0000422//===----------------------------------------------------------------------===//
423// Data structures for constructing summaries.
424//===----------------------------------------------------------------------===//
Ted Kremenek9f0fc792008-06-24 03:49:48 +0000425
Ted Kremenek272aa852008-06-25 21:21:56 +0000426namespace {
427class VISIBILITY_HIDDEN ObjCSummaryKey {
428 IdentifierInfo* II;
429 Selector S;
430public:
431 ObjCSummaryKey(IdentifierInfo* ii, Selector s)
432 : II(ii), S(s) {}
433
Ted Kremenek314b1952009-04-29 23:03:22 +0000434 ObjCSummaryKey(const ObjCInterfaceDecl* d, Selector s)
Ted Kremenek272aa852008-06-25 21:21:56 +0000435 : II(d ? d->getIdentifier() : 0), S(s) {}
436
437 ObjCSummaryKey(Selector s)
438 : II(0), S(s) {}
439
440 IdentifierInfo* getIdentifier() const { return II; }
441 Selector getSelector() const { return S; }
442};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000443}
444
445namespace llvm {
Ted Kremenek272aa852008-06-25 21:21:56 +0000446template <> struct DenseMapInfo<ObjCSummaryKey> {
447 static inline ObjCSummaryKey getEmptyKey() {
448 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
449 DenseMapInfo<Selector>::getEmptyKey());
450 }
Ted Kremenek84f010c2008-06-23 23:30:29 +0000451
Ted Kremenek272aa852008-06-25 21:21:56 +0000452 static inline ObjCSummaryKey getTombstoneKey() {
453 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
454 DenseMapInfo<Selector>::getTombstoneKey());
455 }
456
457 static unsigned getHashValue(const ObjCSummaryKey &V) {
458 return (DenseMapInfo<IdentifierInfo*>::getHashValue(V.getIdentifier())
459 & 0x88888888)
460 | (DenseMapInfo<Selector>::getHashValue(V.getSelector())
461 & 0x55555555);
462 }
463
464 static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
465 return DenseMapInfo<IdentifierInfo*>::isEqual(LHS.getIdentifier(),
466 RHS.getIdentifier()) &&
467 DenseMapInfo<Selector>::isEqual(LHS.getSelector(),
468 RHS.getSelector());
469 }
470
471 static bool isPod() {
472 return DenseMapInfo<ObjCInterfaceDecl*>::isPod() &&
473 DenseMapInfo<Selector>::isPod();
474 }
475};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000476} // end llvm namespace
Ted Kremeneka7338b42008-03-11 06:39:11 +0000477
Ted Kremenek84f010c2008-06-23 23:30:29 +0000478namespace {
Ted Kremenek272aa852008-06-25 21:21:56 +0000479class VISIBILITY_HIDDEN ObjCSummaryCache {
480 typedef llvm::DenseMap<ObjCSummaryKey, RetainSummary*> MapTy;
481 MapTy M;
482public:
483 ObjCSummaryCache() {}
484
485 typedef MapTy::iterator iterator;
486
Ted Kremenek314b1952009-04-29 23:03:22 +0000487 iterator find(const ObjCInterfaceDecl* D, IdentifierInfo *ClsName,
488 Selector S) {
Ted Kremeneka821b792009-04-29 05:04:30 +0000489 // Lookup the method using the decl for the class @interface. If we
490 // have no decl, lookup using the class name.
491 return D ? find(D, S) : find(ClsName, S);
492 }
493
Ted Kremenek314b1952009-04-29 23:03:22 +0000494 iterator find(const ObjCInterfaceDecl* D, Selector S) {
Ted Kremenek272aa852008-06-25 21:21:56 +0000495 // Do a lookup with the (D,S) pair. If we find a match return
496 // the iterator.
497 ObjCSummaryKey K(D, S);
498 MapTy::iterator I = M.find(K);
499
500 if (I != M.end() || !D)
501 return I;
502
503 // Walk the super chain. If we find a hit with a parent, we'll end
504 // up returning that summary. We actually allow that key (null,S), as
505 // we cache summaries for the null ObjCInterfaceDecl* to allow us to
506 // generate initial summaries without having to worry about NSObject
507 // being declared.
508 // FIXME: We may change this at some point.
509 for (ObjCInterfaceDecl* C=D->getSuperClass() ;; C=C->getSuperClass()) {
510 if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
511 break;
512
513 if (!C)
514 return I;
515 }
516
517 // Cache the summary with original key to make the next lookup faster
518 // and return the iterator.
519 M[K] = I->second;
520 return I;
521 }
522
Ted Kremenek9449ca92008-08-12 20:41:56 +0000523
Ted Kremenek272aa852008-06-25 21:21:56 +0000524 iterator find(Expr* Receiver, Selector S) {
525 return find(getReceiverDecl(Receiver), S);
526 }
527
528 iterator find(IdentifierInfo* II, Selector S) {
529 // FIXME: Class method lookup. Right now we dont' have a good way
530 // of going between IdentifierInfo* and the class hierarchy.
531 iterator I = M.find(ObjCSummaryKey(II, S));
532 return I == M.end() ? M.find(ObjCSummaryKey(S)) : I;
533 }
534
535 ObjCInterfaceDecl* getReceiverDecl(Expr* E) {
536
537 const PointerType* PT = E->getType()->getAsPointerType();
538 if (!PT) return 0;
539
540 ObjCInterfaceType* OI = dyn_cast<ObjCInterfaceType>(PT->getPointeeType());
541 if (!OI) return 0;
542
543 return OI ? OI->getDecl() : 0;
544 }
545
546 iterator end() { return M.end(); }
547
548 RetainSummary*& operator[](ObjCMessageExpr* ME) {
549
550 Selector S = ME->getSelector();
551
552 if (Expr* Receiver = ME->getReceiver()) {
553 ObjCInterfaceDecl* OD = getReceiverDecl(Receiver);
554 return OD ? M[ObjCSummaryKey(OD->getIdentifier(), S)] : M[S];
555 }
556
557 return M[ObjCSummaryKey(ME->getClassName(), S)];
558 }
559
560 RetainSummary*& operator[](ObjCSummaryKey K) {
561 return M[K];
562 }
563
564 RetainSummary*& operator[](Selector S) {
565 return M[ ObjCSummaryKey(S) ];
566 }
567};
568} // end anonymous namespace
569
570//===----------------------------------------------------------------------===//
571// Data structures for managing collections of summaries.
572//===----------------------------------------------------------------------===//
573
574namespace {
575class VISIBILITY_HIDDEN RetainSummaryManager {
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000576
577 //==-----------------------------------------------------------------==//
578 // Typedefs.
579 //==-----------------------------------------------------------------==//
Ted Kremeneka7338b42008-03-11 06:39:11 +0000580
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000581 typedef llvm::DenseMap<FunctionDecl*, RetainSummary*>
582 FuncSummariesTy;
583
Ted Kremenek84f010c2008-06-23 23:30:29 +0000584 typedef ObjCSummaryCache ObjCMethodSummariesTy;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000585
586 //==-----------------------------------------------------------------==//
587 // Data.
588 //==-----------------------------------------------------------------==//
589
Ted Kremenek272aa852008-06-25 21:21:56 +0000590 /// Ctx - The ASTContext object for the analyzed ASTs.
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000591 ASTContext& Ctx;
Ted Kremeneke44927e2008-07-01 17:21:27 +0000592
Ted Kremenekede40b72008-07-09 18:11:16 +0000593 /// CFDictionaryCreateII - An IdentifierInfo* representing the indentifier
594 /// "CFDictionaryCreate".
595 IdentifierInfo* CFDictionaryCreateII;
596
Ted Kremenek272aa852008-06-25 21:21:56 +0000597 /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000598 const bool GCEnabled;
Ted Kremenekee649082009-05-04 04:30:18 +0000599
Ted Kremenek272aa852008-06-25 21:21:56 +0000600 /// FuncSummaries - A map from FunctionDecls to summaries.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000601 FuncSummariesTy FuncSummaries;
602
Ted Kremenek272aa852008-06-25 21:21:56 +0000603 /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
604 /// to summaries.
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000605 ObjCMethodSummariesTy ObjCClassMethodSummaries;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000606
Ted Kremenek272aa852008-06-25 21:21:56 +0000607 /// ObjCMethodSummaries - A map from selectors to summaries.
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000608 ObjCMethodSummariesTy ObjCMethodSummaries;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000609
Ted Kremenek272aa852008-06-25 21:21:56 +0000610 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
611 /// and all other data used by the checker.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000612 llvm::BumpPtrAllocator BPAlloc;
613
Ted Kremeneka56ae162009-05-03 05:20:50 +0000614 /// AF - A factory for ArgEffects objects.
615 ArgEffects::Factory AF;
616
Ted Kremenek272aa852008-06-25 21:21:56 +0000617 /// ScratchArgs - A holding buffer for construct ArgEffects.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000618 ArgEffects ScratchArgs;
619
Ted Kremenek5535e5e2009-05-07 23:40:42 +0000620 /// ObjCAllocRetE - Default return effect for methods returning Objective-C
621 /// objects.
622 RetEffect ObjCAllocRetE;
623
Ted Kremenek286e9852009-05-04 04:57:00 +0000624 RetainSummary DefaultSummary;
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000625 RetainSummary* StopSummary;
626
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000627 //==-----------------------------------------------------------------==//
628 // Methods.
629 //==-----------------------------------------------------------------==//
630
Ted Kremenek272aa852008-06-25 21:21:56 +0000631 /// getArgEffects - Returns a persistent ArgEffects object based on the
632 /// data in ScratchArgs.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000633 ArgEffects getArgEffects();
Ted Kremeneka7338b42008-03-11 06:39:11 +0000634
Ted Kremenek562c1302008-05-05 16:51:50 +0000635 enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000636
637public:
Ted Kremenek2f226732009-05-04 05:31:22 +0000638 RetainSummary *getDefaultSummary() {
639 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
640 return new (Summ) RetainSummary(DefaultSummary);
641 }
Ted Kremenek286e9852009-05-04 04:57:00 +0000642
Ted Kremenek064ef322009-02-23 16:51:39 +0000643 RetainSummary* getUnarySummary(const FunctionType* FT, UnaryFuncKind func);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000644
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000645 RetainSummary* getCFSummaryCreateRule(FunctionDecl* FD);
646 RetainSummary* getCFSummaryGetRule(FunctionDecl* FD);
Ted Kremenek17144e82009-01-12 21:45:02 +0000647 RetainSummary* getCFCreateGetRuleSummary(FunctionDecl* FD, const char* FName);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000648
Ted Kremeneka56ae162009-05-03 05:20:50 +0000649 RetainSummary* getPersistentSummary(ArgEffects AE, RetEffect RetEff,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000650 ArgEffect ReceiverEff = DoNothing,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000651 ArgEffect DefaultEff = MayEscape,
652 bool isEndPath = false);
Ted Kremenek45d0b502008-10-29 04:07:07 +0000653
Ted Kremenek266d8b62008-05-06 02:26:56 +0000654 RetainSummary* getPersistentSummary(RetEffect RE,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000655 ArgEffect ReceiverEff = DoNothing,
Ted Kremeneka3f30dd2008-05-22 17:31:13 +0000656 ArgEffect DefaultEff = MayEscape) {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000657 return getPersistentSummary(getArgEffects(), RE, ReceiverEff, DefaultEff);
Ted Kremenek0e344d42008-05-06 00:30:21 +0000658 }
Ted Kremenek42ea0322008-05-05 23:55:01 +0000659
Ted Kremeneka821b792009-04-29 05:04:30 +0000660 RetainSummary *getPersistentStopSummary() {
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000661 if (StopSummary)
662 return StopSummary;
663
664 StopSummary = getPersistentSummary(RetEffect::MakeNoRet(),
665 StopTracking, StopTracking);
Ted Kremenek45d0b502008-10-29 04:07:07 +0000666
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000667 return StopSummary;
Ted Kremenekbcaff792008-05-06 15:44:25 +0000668 }
Ted Kremenek926abf22008-05-06 04:20:12 +0000669
Ted Kremeneka821b792009-04-29 05:04:30 +0000670 RetainSummary *getInitMethodSummary(QualType RetTy);
Ted Kremenek42ea0322008-05-05 23:55:01 +0000671
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000672 void InitializeClassMethodSummaries();
673 void InitializeMethodSummaries();
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000674
Ted Kremenek9b42e062009-05-03 04:42:10 +0000675 bool isTrackedObjCObjectType(QualType T);
Ted Kremeneka9cdbc32009-05-03 06:08:32 +0000676 bool isTrackedCFObjectType(QualType T);
Ted Kremenek35920ed2009-01-07 00:39:56 +0000677
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000678private:
679
Ted Kremenekf2717b02008-07-18 17:24:20 +0000680 void addClsMethSummary(IdentifierInfo* ClsII, Selector S,
681 RetainSummary* Summ) {
682 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
683 }
684
Ted Kremenek272aa852008-06-25 21:21:56 +0000685 void addNSObjectClsMethSummary(Selector S, RetainSummary *Summ) {
686 ObjCClassMethodSummaries[S] = Summ;
687 }
688
689 void addNSObjectMethSummary(Selector S, RetainSummary *Summ) {
690 ObjCMethodSummaries[S] = Summ;
691 }
Ted Kremenekfbf2dc52009-03-04 23:30:42 +0000692
693 void addClassMethSummary(const char* Cls, const char* nullaryName,
694 RetainSummary *Summ) {
695 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
696 Selector S = GetNullarySelector(nullaryName, Ctx);
697 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
698 }
Ted Kremenek272aa852008-06-25 21:21:56 +0000699
Ted Kremenek1b4b6562009-02-25 02:54:57 +0000700 void addInstMethSummary(const char* Cls, const char* nullaryName,
701 RetainSummary *Summ) {
702 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
703 Selector S = GetNullarySelector(nullaryName, Ctx);
704 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
705 }
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000706
707 Selector generateSelector(va_list argp) {
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000708 llvm::SmallVector<IdentifierInfo*, 10> II;
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000709
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000710 while (const char* s = va_arg(argp, const char*))
711 II.push_back(&Ctx.Idents.get(s));
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000712
713 return Ctx.Selectors.getSelector(II.size(), &II[0]);
714 }
715
716 void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy& Summaries,
717 RetainSummary* Summ, va_list argp) {
718 Selector S = generateSelector(argp);
719 Summaries[ObjCSummaryKey(ClsII, S)] = Summ;
Ted Kremenekf2717b02008-07-18 17:24:20 +0000720 }
Ted Kremenek45642a42008-08-12 18:48:50 +0000721
722 void addInstMethSummary(const char* Cls, RetainSummary* Summ, ...) {
723 va_list argp;
724 va_start(argp, Summ);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000725 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Ted Kremenek45642a42008-08-12 18:48:50 +0000726 va_end(argp);
727 }
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000728
729 void addClsMethSummary(const char* Cls, RetainSummary* Summ, ...) {
730 va_list argp;
731 va_start(argp, Summ);
732 addMethodSummary(&Ctx.Idents.get(Cls),ObjCClassMethodSummaries, Summ, argp);
733 va_end(argp);
734 }
735
736 void addClsMethSummary(IdentifierInfo *II, RetainSummary* Summ, ...) {
737 va_list argp;
738 va_start(argp, Summ);
739 addMethodSummary(II, ObjCClassMethodSummaries, Summ, argp);
740 va_end(argp);
741 }
742
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000743 void addPanicSummary(const char* Cls, ...) {
Ted Kremeneka56ae162009-05-03 05:20:50 +0000744 RetainSummary* Summ = getPersistentSummary(AF.GetEmptyMap(),
745 RetEffect::MakeNoRet(),
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000746 DoNothing, DoNothing, true);
747 va_list argp;
748 va_start (argp, Cls);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000749 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000750 va_end(argp);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000751 }
Ted Kremenekf2717b02008-07-18 17:24:20 +0000752
Ted Kremeneka7338b42008-03-11 06:39:11 +0000753public:
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000754
755 RetainSummaryManager(ASTContext& ctx, bool gcenabled)
Ted Kremeneke44927e2008-07-01 17:21:27 +0000756 : Ctx(ctx),
Ted Kremenekede40b72008-07-09 18:11:16 +0000757 CFDictionaryCreateII(&ctx.Idents.get("CFDictionaryCreate")),
Ted Kremeneka56ae162009-05-03 05:20:50 +0000758 GCEnabled(gcenabled), AF(BPAlloc), ScratchArgs(AF.GetEmptyMap()),
Ted Kremenek5535e5e2009-05-07 23:40:42 +0000759 ObjCAllocRetE(gcenabled ? RetEffect::MakeGCNotOwned()
760 : RetEffect::MakeOwned(RetEffect::ObjC, true)),
Ted Kremenek286e9852009-05-04 04:57:00 +0000761 DefaultSummary(AF.GetEmptyMap() /* per-argument effects (none) */,
762 RetEffect::MakeNoRet() /* return effect */,
Ted Kremeneka13b0862009-05-11 18:30:24 +0000763 MayEscape, /* default argument effect */
764 DoNothing /* receiver effect */),
Ted Kremeneka56ae162009-05-03 05:20:50 +0000765 StopSummary(0) {
Ted Kremenek272aa852008-06-25 21:21:56 +0000766
767 InitializeClassMethodSummaries();
768 InitializeMethodSummaries();
769 }
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000770
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000771 ~RetainSummaryManager();
Ted Kremeneka7338b42008-03-11 06:39:11 +0000772
Ted Kremenekd13c1872008-06-24 03:56:45 +0000773 RetainSummary* getSummary(FunctionDecl* FD);
Ted Kremeneka821b792009-04-29 05:04:30 +0000774
Ted Kremenek314b1952009-04-29 23:03:22 +0000775 RetainSummary* getInstanceMethodSummary(ObjCMessageExpr* ME,
776 const ObjCInterfaceDecl* ID) {
Ted Kremenek04e00302009-04-29 17:09:14 +0000777 return getInstanceMethodSummary(ME->getSelector(), ME->getClassName(),
Ted Kremeneka821b792009-04-29 05:04:30 +0000778 ID, ME->getMethodDecl(), ME->getType());
779 }
780
Ted Kremenek04e00302009-04-29 17:09:14 +0000781 RetainSummary* getInstanceMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +0000782 const ObjCInterfaceDecl* ID,
783 const ObjCMethodDecl *MD,
784 QualType RetTy);
Ted Kremenek578498a2009-04-29 00:42:39 +0000785
786 RetainSummary *getClassMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +0000787 const ObjCInterfaceDecl *ID,
788 const ObjCMethodDecl *MD,
789 QualType RetTy);
Ted Kremenek578498a2009-04-29 00:42:39 +0000790
791 RetainSummary *getClassMethodSummary(ObjCMessageExpr *ME) {
792 return getClassMethodSummary(ME->getSelector(), ME->getClassName(),
793 ME->getClassInfo().first,
794 ME->getMethodDecl(), ME->getType());
795 }
Ted Kremenek91b89a42009-04-29 17:17:48 +0000796
797 /// getMethodSummary - This version of getMethodSummary is used to query
798 /// the summary for the current method being analyzed.
Ted Kremenek314b1952009-04-29 23:03:22 +0000799 RetainSummary *getMethodSummary(const ObjCMethodDecl *MD) {
800 // FIXME: Eventually this should be unneeded.
Ted Kremenek314b1952009-04-29 23:03:22 +0000801 const ObjCInterfaceDecl *ID = MD->getClassInterface();
Ted Kremenek1447cc92009-04-30 05:41:14 +0000802 Selector S = MD->getSelector();
Ted Kremenek91b89a42009-04-29 17:17:48 +0000803 IdentifierInfo *ClsName = ID->getIdentifier();
804 QualType ResultTy = MD->getResultType();
805
Ted Kremenek81eb4642009-04-30 05:47:23 +0000806 // Resolve the method decl last.
807 if (const ObjCMethodDecl *InterfaceMD =
808 ResolveToInterfaceMethodDecl(MD, Ctx))
809 MD = InterfaceMD;
Ted Kremenek1447cc92009-04-30 05:41:14 +0000810
Ted Kremenek91b89a42009-04-29 17:17:48 +0000811 if (MD->isInstanceMethod())
812 return getInstanceMethodSummary(S, ClsName, ID, MD, ResultTy);
813 else
814 return getClassMethodSummary(S, ClsName, ID, MD, ResultTy);
815 }
Ted Kremenek578498a2009-04-29 00:42:39 +0000816
Ted Kremenek314b1952009-04-29 23:03:22 +0000817 RetainSummary* getCommonMethodSummary(const ObjCMethodDecl* MD,
818 Selector S, QualType RetTy);
819
Ted Kremeneka4c8afc2009-05-09 02:58:13 +0000820 void updateSummaryFromAnnotations(RetainSummary &Summ,
821 const ObjCMethodDecl *MD);
822
823 void updateSummaryFromAnnotations(RetainSummary &Summ,
824 const FunctionDecl *FD);
825
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000826 bool isGCEnabled() const { return GCEnabled; }
Ted Kremenek2f226732009-05-04 05:31:22 +0000827
828 RetainSummary *copySummary(RetainSummary *OldSumm) {
829 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
830 new (Summ) RetainSummary(*OldSumm);
831 return Summ;
832 }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000833};
834
835} // end anonymous namespace
836
837//===----------------------------------------------------------------------===//
838// Implementation of checker data structures.
839//===----------------------------------------------------------------------===//
840
Ted Kremeneka56ae162009-05-03 05:20:50 +0000841RetainSummaryManager::~RetainSummaryManager() {}
Ted Kremeneka7338b42008-03-11 06:39:11 +0000842
Ted Kremeneka56ae162009-05-03 05:20:50 +0000843ArgEffects RetainSummaryManager::getArgEffects() {
844 ArgEffects AE = ScratchArgs;
845 ScratchArgs = AF.GetEmptyMap();
846 return AE;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000847}
848
Ted Kremenek266d8b62008-05-06 02:26:56 +0000849RetainSummary*
Ted Kremeneka56ae162009-05-03 05:20:50 +0000850RetainSummaryManager::getPersistentSummary(ArgEffects AE, RetEffect RetEff,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000851 ArgEffect ReceiverEff,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000852 ArgEffect DefaultEff,
Ted Kremenekee649082009-05-04 04:30:18 +0000853 bool isEndPath) {
Ted Kremenekae855d42008-04-24 17:22:33 +0000854 // Create the summary and return it.
Ted Kremenekee649082009-05-04 04:30:18 +0000855 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
Ted Kremenekf2717b02008-07-18 17:24:20 +0000856 new (Summ) RetainSummary(AE, RetEff, DefaultEff, ReceiverEff, isEndPath);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000857 return Summ;
858}
859
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000860//===----------------------------------------------------------------------===//
Ted Kremenek35920ed2009-01-07 00:39:56 +0000861// Predicates.
862//===----------------------------------------------------------------------===//
863
Ted Kremenek9b42e062009-05-03 04:42:10 +0000864bool RetainSummaryManager::isTrackedObjCObjectType(QualType Ty) {
Ted Kremenek0d813552009-04-23 22:11:07 +0000865 if (!Ctx.isObjCObjectPointerType(Ty))
Ted Kremenek35920ed2009-01-07 00:39:56 +0000866 return false;
867
Ted Kremenek0d813552009-04-23 22:11:07 +0000868 // We assume that id<..>, id, and "Class" all represent tracked objects.
869 const PointerType *PT = Ty->getAsPointerType();
870 if (PT == 0)
871 return true;
872
873 const ObjCInterfaceType *OT = PT->getPointeeType()->getAsObjCInterfaceType();
Ted Kremenek35920ed2009-01-07 00:39:56 +0000874
875 // We assume that id<..>, id, and "Class" all represent tracked objects.
876 if (!OT)
877 return true;
Ted Kremenek0d813552009-04-23 22:11:07 +0000878
879 // Does the interface subclass NSObject?
Ted Kremenek35920ed2009-01-07 00:39:56 +0000880 // FIXME: We can memoize here if this gets too expensive.
881 IdentifierInfo* NSObjectII = &Ctx.Idents.get("NSObject");
882 ObjCInterfaceDecl* ID = OT->getDecl();
883
884 for ( ; ID ; ID = ID->getSuperClass())
885 if (ID->getIdentifier() == NSObjectII)
886 return true;
887
888 return false;
889}
890
Ted Kremeneka9cdbc32009-05-03 06:08:32 +0000891bool RetainSummaryManager::isTrackedCFObjectType(QualType T) {
892 return isRefType(T, "CF") || // Core Foundation.
893 isRefType(T, "CG") || // Core Graphics.
894 isRefType(T, "DADisk") || // Disk Arbitration API.
895 isRefType(T, "DADissenter") ||
896 isRefType(T, "DASessionRef");
897}
898
Ted Kremenek35920ed2009-01-07 00:39:56 +0000899//===----------------------------------------------------------------------===//
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000900// Summary creation for functions (largely uses of Core Foundation).
901//===----------------------------------------------------------------------===//
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000902
Ted Kremenek17144e82009-01-12 21:45:02 +0000903static bool isRetain(FunctionDecl* FD, const char* FName) {
904 const char* loc = strstr(FName, "Retain");
905 return loc && loc[sizeof("Retain")-1] == '\0';
906}
907
908static bool isRelease(FunctionDecl* FD, const char* FName) {
909 const char* loc = strstr(FName, "Release");
910 return loc && loc[sizeof("Release")-1] == '\0';
911}
912
Ted Kremenekd13c1872008-06-24 03:56:45 +0000913RetainSummary* RetainSummaryManager::getSummary(FunctionDecl* FD) {
Ted Kremenekae855d42008-04-24 17:22:33 +0000914 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000915 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000916 if (I != FuncSummaries.end())
Ted Kremenekae855d42008-04-24 17:22:33 +0000917 return I->second;
918
Ted Kremenek64cddf12009-05-04 15:34:07 +0000919 // No summary? Generate one.
Ted Kremenek17144e82009-01-12 21:45:02 +0000920 RetainSummary *S = 0;
Ted Kremenek562c1302008-05-05 16:51:50 +0000921
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000922 do {
Ted Kremenek17144e82009-01-12 21:45:02 +0000923 // We generate "stop" summaries for implicitly defined functions.
924 if (FD->isImplicit()) {
925 S = getPersistentStopSummary();
926 break;
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000927 }
Ted Kremenekeafcc2f2008-11-04 00:36:12 +0000928
Ted Kremenek064ef322009-02-23 16:51:39 +0000929 // [PR 3337] Use 'getAsFunctionType' to strip away any typedefs on the
Ted Kremenekc239b9c2009-01-16 18:40:33 +0000930 // function's type.
Ted Kremenek064ef322009-02-23 16:51:39 +0000931 const FunctionType* FT = FD->getType()->getAsFunctionType();
Ted Kremenek17144e82009-01-12 21:45:02 +0000932 const char* FName = FD->getIdentifier()->getName();
933
Ted Kremenek38c6f022009-03-05 22:11:14 +0000934 // Strip away preceding '_'. Doing this here will effect all the checks
935 // down below.
936 while (*FName == '_') ++FName;
937
Ted Kremenek17144e82009-01-12 21:45:02 +0000938 // Inspect the result type.
939 QualType RetTy = FT->getResultType();
940
941 // FIXME: This should all be refactored into a chain of "summary lookup"
942 // filters.
943 if (strcmp(FName, "IOServiceGetMatchingServices") == 0) {
944 // FIXES: <rdar://problem/6326900>
945 // This should be addressed using a API table. This strcmp is also
946 // a little gross, but there is no need to super optimize here.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000947 assert (ScratchArgs.isEmpty());
948 ScratchArgs = AF.Add(ScratchArgs, 1, DecRef);
Ted Kremenek17144e82009-01-12 21:45:02 +0000949 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
950 break;
Ted Kremenekcfc50c72008-10-22 20:54:52 +0000951 }
Ted Kremenek7b88c892009-03-17 22:43:44 +0000952
953 // Enable this code once the semantics of NSDeallocateObject are resolved
954 // for GC. <rdar://problem/6619988>
955#if 0
956 // Handle: NSDeallocateObject(id anObject);
957 // This method does allow 'nil' (although we don't check it now).
958 if (strcmp(FName, "NSDeallocateObject") == 0) {
959 return RetTy == Ctx.VoidTy
960 ? getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, Dealloc)
961 : getPersistentStopSummary();
962 }
963#endif
Ted Kremenek17144e82009-01-12 21:45:02 +0000964
965 // Handle: id NSMakeCollectable(CFTypeRef)
966 if (strcmp(FName, "NSMakeCollectable") == 0) {
967 S = (RetTy == Ctx.getObjCIdType())
968 ? getUnarySummary(FT, cfmakecollectable)
969 : getPersistentStopSummary();
970
971 break;
972 }
973
974 if (RetTy->isPointerType()) {
975 // For CoreFoundation ('CF') types.
976 if (isRefType(RetTy, "CF", &Ctx, FName)) {
977 if (isRetain(FD, FName))
978 S = getUnarySummary(FT, cfretain);
979 else if (strstr(FName, "MakeCollectable"))
980 S = getUnarySummary(FT, cfmakecollectable);
981 else
982 S = getCFCreateGetRuleSummary(FD, FName);
983
984 break;
985 }
986
987 // For CoreGraphics ('CG') types.
988 if (isRefType(RetTy, "CG", &Ctx, FName)) {
989 if (isRetain(FD, FName))
990 S = getUnarySummary(FT, cfretain);
991 else
992 S = getCFCreateGetRuleSummary(FD, FName);
993
994 break;
995 }
996
997 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
998 if (isRefType(RetTy, "DADisk") ||
999 isRefType(RetTy, "DADissenter") ||
1000 isRefType(RetTy, "DASessionRef")) {
1001 S = getCFCreateGetRuleSummary(FD, FName);
1002 break;
1003 }
1004
1005 break;
1006 }
1007
1008 // Check for release functions, the only kind of functions that we care
1009 // about that don't return a pointer type.
1010 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
Ted Kremenek38c6f022009-03-05 22:11:14 +00001011 // Test for 'CGCF'.
1012 if (FName[1] == 'G' && FName[2] == 'C' && FName[3] == 'F')
1013 FName += 4;
1014 else
1015 FName += 2;
1016
1017 if (isRelease(FD, FName))
Ted Kremenek17144e82009-01-12 21:45:02 +00001018 S = getUnarySummary(FT, cfrelease);
1019 else {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001020 assert (ScratchArgs.isEmpty());
Ted Kremenek7b293682009-01-29 22:45:13 +00001021 // Remaining CoreFoundation and CoreGraphics functions.
1022 // We use to assume that they all strictly followed the ownership idiom
1023 // and that ownership cannot be transferred. While this is technically
1024 // correct, many methods allow a tracked object to escape. For example:
1025 //
1026 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
1027 // CFDictionaryAddValue(y, key, x);
1028 // CFRelease(x);
1029 // ... it is okay to use 'x' since 'y' has a reference to it
1030 //
1031 // We handle this and similar cases with the follow heuristic. If the
1032 // function name contains "InsertValue", "SetValue" or "AddValue" then
1033 // we assume that arguments may "escape."
1034 //
1035 ArgEffect E = (CStrInCStrNoCase(FName, "InsertValue") ||
1036 CStrInCStrNoCase(FName, "AddValue") ||
Ted Kremenekcf071252009-02-05 22:34:53 +00001037 CStrInCStrNoCase(FName, "SetValue") ||
1038 CStrInCStrNoCase(FName, "AppendValue"))
Ted Kremenek7b293682009-01-29 22:45:13 +00001039 ? MayEscape : DoNothing;
1040
1041 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek17144e82009-01-12 21:45:02 +00001042 }
1043 }
Ted Kremenek4c5378c2008-07-15 16:50:12 +00001044 }
1045 while (0);
Ted Kremenek2f226732009-05-04 05:31:22 +00001046
1047 if (!S)
1048 S = getDefaultSummary();
Ted Kremenekae855d42008-04-24 17:22:33 +00001049
Ted Kremeneka4c8afc2009-05-09 02:58:13 +00001050 // Annotations override defaults.
1051 assert(S);
1052 updateSummaryFromAnnotations(*S, FD);
1053
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001054 FuncSummaries[FD] = S;
Ted Kremenek562c1302008-05-05 16:51:50 +00001055 return S;
Ted Kremenek827f93b2008-03-06 00:08:09 +00001056}
1057
Ted Kremenek4c5378c2008-07-15 16:50:12 +00001058RetainSummary*
1059RetainSummaryManager::getCFCreateGetRuleSummary(FunctionDecl* FD,
1060 const char* FName) {
1061
Ted Kremenek562c1302008-05-05 16:51:50 +00001062 if (strstr(FName, "Create") || strstr(FName, "Copy"))
1063 return getCFSummaryCreateRule(FD);
Ted Kremenek4c5378c2008-07-15 16:50:12 +00001064
Ted Kremenek562c1302008-05-05 16:51:50 +00001065 if (strstr(FName, "Get"))
1066 return getCFSummaryGetRule(FD);
1067
Ted Kremenek286e9852009-05-04 04:57:00 +00001068 return getDefaultSummary();
Ted Kremenek562c1302008-05-05 16:51:50 +00001069}
1070
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001071RetainSummary*
Ted Kremenek064ef322009-02-23 16:51:39 +00001072RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1073 UnaryFuncKind func) {
1074
Ted Kremenek17144e82009-01-12 21:45:02 +00001075 // Sanity check that this is *really* a unary function. This can
1076 // happen if people do weird things.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001077 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
Ted Kremenek17144e82009-01-12 21:45:02 +00001078 if (!FTP || FTP->getNumArgs() != 1)
1079 return getPersistentStopSummary();
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001080
Ted Kremeneka56ae162009-05-03 05:20:50 +00001081 assert (ScratchArgs.isEmpty());
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001082
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001083 switch (func) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001084 case cfretain: {
1085 ScratchArgs = AF.Add(ScratchArgs, 0, IncRef);
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001086 return getPersistentSummary(RetEffect::MakeAlias(0),
1087 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001088 }
1089
1090 case cfrelease: {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001091 ScratchArgs = AF.Add(ScratchArgs, 0, DecRef);
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001092 return getPersistentSummary(RetEffect::MakeNoRet(),
1093 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001094 }
1095
1096 case cfmakecollectable: {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001097 ScratchArgs = AF.Add(ScratchArgs, 0, MakeCollectable);
Ted Kremenek2126bef2009-02-18 21:57:45 +00001098 return getPersistentSummary(RetEffect::MakeAlias(0),DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001099 }
1100
1101 default:
Ted Kremenek562c1302008-05-05 16:51:50 +00001102 assert (false && "Not a supported unary function.");
Ted Kremenek286e9852009-05-04 04:57:00 +00001103 return getDefaultSummary();
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00001104 }
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001105}
1106
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001107RetainSummary* RetainSummaryManager::getCFSummaryCreateRule(FunctionDecl* FD) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001108 assert (ScratchArgs.isEmpty());
Ted Kremenekede40b72008-07-09 18:11:16 +00001109
1110 if (FD->getIdentifier() == CFDictionaryCreateII) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001111 ScratchArgs = AF.Add(ScratchArgs, 1, DoNothingByRef);
1112 ScratchArgs = AF.Add(ScratchArgs, 2, DoNothingByRef);
Ted Kremenekede40b72008-07-09 18:11:16 +00001113 }
1114
Ted Kremenek68621b92009-01-28 05:56:51 +00001115 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001116}
1117
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001118RetainSummary* RetainSummaryManager::getCFSummaryGetRule(FunctionDecl* FD) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001119 assert (ScratchArgs.isEmpty());
Ted Kremenek68621b92009-01-28 05:56:51 +00001120 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1121 DoNothing, DoNothing);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001122}
1123
Ted Kremeneka7338b42008-03-11 06:39:11 +00001124//===----------------------------------------------------------------------===//
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001125// Summary creation for Selectors.
1126//===----------------------------------------------------------------------===//
1127
Ted Kremenekbcaff792008-05-06 15:44:25 +00001128RetainSummary*
Ted Kremeneka821b792009-04-29 05:04:30 +00001129RetainSummaryManager::getInitMethodSummary(QualType RetTy) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001130 assert(ScratchArgs.isEmpty());
Ted Kremenek42ea0322008-05-05 23:55:01 +00001131
Ted Kremenek802cfc72009-02-20 00:05:35 +00001132 // 'init' methods only return an alias if the return type is a location type.
Ted Kremeneka821b792009-04-29 05:04:30 +00001133 return getPersistentSummary(Loc::IsLocType(RetTy)
1134 ? RetEffect::MakeReceiverAlias()
Ted Kremenek03d242e2009-05-05 18:44:20 +00001135 : RetEffect::MakeNoRet());
Ted Kremenek42ea0322008-05-05 23:55:01 +00001136}
Ted Kremeneka4c8afc2009-05-09 02:58:13 +00001137
1138void
1139RetainSummaryManager::updateSummaryFromAnnotations(RetainSummary &Summ,
1140 const FunctionDecl *FD) {
1141 if (!FD)
1142 return;
1143
1144 // Determine if there is a special return effect for this method.
1145 if (isTrackedObjCObjectType(FD->getResultType())) {
1146 if (FD->getAttr<NSReturnsRetainedAttr>()) {
1147 Summ.setRetEffect(ObjCAllocRetE);
1148 }
1149 else if (FD->getAttr<CFReturnsRetainedAttr>()) {
1150 Summ.setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
1151 }
1152 }
1153}
1154
1155void
1156RetainSummaryManager::updateSummaryFromAnnotations(RetainSummary &Summ,
1157 const ObjCMethodDecl *MD) {
1158 if (!MD)
1159 return;
1160
1161 // Determine if there is a special return effect for this method.
1162 if (isTrackedObjCObjectType(MD->getResultType())) {
1163 if (MD->getAttr<NSReturnsRetainedAttr>()) {
1164 Summ.setRetEffect(ObjCAllocRetE);
1165 }
1166 else if (MD->getAttr<CFReturnsRetainedAttr>()) {
1167 Summ.setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
1168 }
1169 }
1170}
1171
Ted Kremenekbcaff792008-05-06 15:44:25 +00001172RetainSummary*
Ted Kremenek314b1952009-04-29 23:03:22 +00001173RetainSummaryManager::getCommonMethodSummary(const ObjCMethodDecl* MD,
1174 Selector S, QualType RetTy) {
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001175
Ted Kremenek578498a2009-04-29 00:42:39 +00001176 if (MD) {
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001177 // Scan the method decl for 'void*' arguments. These should be treated
1178 // as 'StopTracking' because they are often used with delegates.
1179 // Delegates are a frequent form of false positives with the retain
1180 // count checker.
1181 unsigned i = 0;
1182 for (ObjCMethodDecl::param_iterator I = MD->param_begin(),
1183 E = MD->param_end(); I != E; ++I, ++i)
1184 if (ParmVarDecl *PD = *I) {
1185 QualType Ty = Ctx.getCanonicalType(PD->getType());
1186 if (Ty.getUnqualifiedType() == Ctx.VoidPtrTy)
Ted Kremeneka56ae162009-05-03 05:20:50 +00001187 ScratchArgs = AF.Add(ScratchArgs, i, StopTracking);
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001188 }
1189 }
1190
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001191 // Any special effect for the receiver?
1192 ArgEffect ReceiverEff = DoNothing;
1193
1194 // If one of the arguments in the selector has the keyword 'delegate' we
1195 // should stop tracking the reference count for the receiver. This is
1196 // because the reference count is quite possibly handled by a delegate
1197 // method.
1198 if (S.isKeywordSelector()) {
1199 const std::string &str = S.getAsString();
1200 assert(!str.empty());
1201 if (CStrInCStrNoCase(&str[0], "delegate:")) ReceiverEff = StopTracking;
1202 }
1203
Ted Kremenek174a0772009-04-23 23:08:22 +00001204 // Look for methods that return an owned object.
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001205 if (isTrackedObjCObjectType(RetTy)) {
1206 // EXPERIMENTAL: Assume the Cocoa conventions for all objects returned
1207 // by instance methods.
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001208 RetEffect E =
1209 followsFundamentalRule(S.getIdentifierInfoForSlot(0)->getName())
Ted Kremenek5535e5e2009-05-07 23:40:42 +00001210 ? ObjCAllocRetE : RetEffect::MakeNotOwned(RetEffect::ObjC);
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001211
1212 return getPersistentSummary(E, ReceiverEff, MayEscape);
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001213 }
Ted Kremenek174a0772009-04-23 23:08:22 +00001214
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001215 // Look for methods that return an owned core foundation object.
1216 if (isTrackedCFObjectType(RetTy)) {
1217 RetEffect E =
1218 followsFundamentalRule(S.getIdentifierInfoForSlot(0)->getName())
1219 ? RetEffect::MakeOwned(RetEffect::CF, true)
1220 : RetEffect::MakeNotOwned(RetEffect::CF);
1221
1222 return getPersistentSummary(E, ReceiverEff, MayEscape);
1223 }
Ted Kremenek174a0772009-04-23 23:08:22 +00001224
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001225 if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing)
Ted Kremenek286e9852009-05-04 04:57:00 +00001226 return getDefaultSummary();
Ted Kremenek174a0772009-04-23 23:08:22 +00001227
Ted Kremenek2f226732009-05-04 05:31:22 +00001228 return getPersistentSummary(RetEffect::MakeNoRet(), ReceiverEff, MayEscape);
Ted Kremenek174a0772009-04-23 23:08:22 +00001229}
1230
1231RetainSummary*
Ted Kremenek04e00302009-04-29 17:09:14 +00001232RetainSummaryManager::getInstanceMethodSummary(Selector S,
1233 IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +00001234 const ObjCInterfaceDecl* ID,
1235 const ObjCMethodDecl *MD,
Ted Kremenek04e00302009-04-29 17:09:14 +00001236 QualType RetTy) {
Ted Kremenekbcaff792008-05-06 15:44:25 +00001237
Ted Kremeneka821b792009-04-29 05:04:30 +00001238 // Look up a summary in our summary cache.
1239 ObjCMethodSummariesTy::iterator I = ObjCMethodSummaries.find(ID, ClsName, S);
Ted Kremenek42ea0322008-05-05 23:55:01 +00001240
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001241 if (I != ObjCMethodSummaries.end())
Ted Kremenek42ea0322008-05-05 23:55:01 +00001242 return I->second;
Ted Kremenek42ea0322008-05-05 23:55:01 +00001243
Ted Kremeneka56ae162009-05-03 05:20:50 +00001244 assert(ScratchArgs.isEmpty());
Ted Kremenek2f226732009-05-04 05:31:22 +00001245 RetainSummary *Summ = 0;
Ted Kremenek1d3d9562008-05-06 06:09:09 +00001246
Ted Kremenek2f226732009-05-04 05:31:22 +00001247 // "initXXX": pass-through for receiver.
1248 if (deriveNamingConvention(S.getIdentifierInfoForSlot(0)->getName())
1249 == InitRule)
1250 Summ = getInitMethodSummary(RetTy);
1251 else
1252 Summ = getCommonMethodSummary(MD, S, RetTy);
1253
Ted Kremeneka4c8afc2009-05-09 02:58:13 +00001254 // Annotations override defaults.
1255 updateSummaryFromAnnotations(*Summ, MD);
1256
Ted Kremenek2f226732009-05-04 05:31:22 +00001257 // Memoize the summary.
Ted Kremeneka821b792009-04-29 05:04:30 +00001258 ObjCMethodSummaries[ObjCSummaryKey(ClsName, S)] = Summ;
Ted Kremeneke4158502009-04-23 19:11:35 +00001259 return Summ;
Ted Kremenek42ea0322008-05-05 23:55:01 +00001260}
1261
Ted Kremeneka7722b72008-05-06 21:26:51 +00001262RetainSummary*
Ted Kremenek578498a2009-04-29 00:42:39 +00001263RetainSummaryManager::getClassMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +00001264 const ObjCInterfaceDecl *ID,
1265 const ObjCMethodDecl *MD,
1266 QualType RetTy) {
Ted Kremenekccbe79a2009-04-24 17:50:11 +00001267
Ted Kremenek578498a2009-04-29 00:42:39 +00001268 assert(ClsName && "Class name must be specified.");
Ted Kremeneka821b792009-04-29 05:04:30 +00001269 ObjCMethodSummariesTy::iterator I =
1270 ObjCClassMethodSummaries.find(ID, ClsName, S);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001271
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001272 if (I != ObjCClassMethodSummaries.end())
Ted Kremeneka7722b72008-05-06 21:26:51 +00001273 return I->second;
Ted Kremenek2f226732009-05-04 05:31:22 +00001274
1275 RetainSummary *Summ = getCommonMethodSummary(MD, S, RetTy);
Ted Kremeneka4c8afc2009-05-09 02:58:13 +00001276
1277 // Annotations override defaults.
1278 updateSummaryFromAnnotations(*Summ, MD);
Ted Kremenek2f226732009-05-04 05:31:22 +00001279
Ted Kremenek2f226732009-05-04 05:31:22 +00001280 // Memoize the summary.
Ted Kremenek578498a2009-04-29 00:42:39 +00001281 ObjCClassMethodSummaries[ObjCSummaryKey(ClsName, S)] = Summ;
Ted Kremeneke4158502009-04-23 19:11:35 +00001282 return Summ;
Ted Kremeneka7722b72008-05-06 21:26:51 +00001283}
1284
Ted Kremenek5535e5e2009-05-07 23:40:42 +00001285void RetainSummaryManager::InitializeClassMethodSummaries() {
1286 assert(ScratchArgs.isEmpty());
1287 RetainSummary* Summ = getPersistentSummary(ObjCAllocRetE);
Ted Kremenek0e344d42008-05-06 00:30:21 +00001288
Ted Kremenek272aa852008-06-25 21:21:56 +00001289 // Create the summaries for "alloc", "new", and "allocWithZone:" for
1290 // NSObject and its derivatives.
1291 addNSObjectClsMethSummary(GetNullarySelector("alloc", Ctx), Summ);
1292 addNSObjectClsMethSummary(GetNullarySelector("new", Ctx), Summ);
1293 addNSObjectClsMethSummary(GetUnarySelector("allocWithZone", Ctx), Summ);
Ted Kremenekf2717b02008-07-18 17:24:20 +00001294
1295 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001296 addClsMethSummary(&Ctx.Idents.get("NSAssertionHandler"),
Ted Kremenek68621b92009-01-28 05:56:51 +00001297 GetNullarySelector("currentHandler", Ctx),
1298 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001299
1300 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremeneka56ae162009-05-03 05:20:50 +00001301 ScratchArgs = AF.Add(ScratchArgs, 0, Autorelease);
Ted Kremenek9b112d22009-01-28 21:44:40 +00001302 addClsMethSummary(&Ctx.Idents.get("NSAutoreleasePool"),
1303 GetUnarySelector("addObject", Ctx),
1304 getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenekf21cb242009-02-23 02:31:16 +00001305 DoNothing, Autorelease));
Ted Kremenekccbe79a2009-04-24 17:50:11 +00001306
1307 // Create the summaries for [NSObject performSelector...]. We treat
1308 // these as 'stop tracking' for the arguments because they are often
1309 // used for delegates that can release the object. When we have better
1310 // inter-procedural analysis we can potentially do something better. This
1311 // workaround is to remove false positives.
1312 Summ = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, StopTracking);
1313 IdentifierInfo *NSObjectII = &Ctx.Idents.get("NSObject");
1314 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1315 "afterDelay", NULL);
1316 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1317 "afterDelay", "inModes", NULL);
1318 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1319 "withObject", "waitUntilDone", NULL);
1320 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1321 "withObject", "waitUntilDone", "modes", NULL);
1322 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1323 "withObject", "waitUntilDone", NULL);
1324 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1325 "withObject", "waitUntilDone", "modes", NULL);
1326 addClsMethSummary(NSObjectII, Summ, "performSelectorInBackground",
1327 "withObject", NULL);
Ted Kremenek0e344d42008-05-06 00:30:21 +00001328}
1329
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001330void RetainSummaryManager::InitializeMethodSummaries() {
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001331
Ted Kremeneka56ae162009-05-03 05:20:50 +00001332 assert (ScratchArgs.isEmpty());
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001333
Ted Kremeneka7722b72008-05-06 21:26:51 +00001334 // Create the "init" selector. It just acts as a pass-through for the
1335 // receiver.
Ted Kremenek56c70aa2009-02-23 16:54:00 +00001336 RetainSummary* InitSumm =
1337 getPersistentSummary(RetEffect::MakeReceiverAlias());
Ted Kremeneke44927e2008-07-01 17:21:27 +00001338 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001339
1340 // The next methods are allocators.
Ted Kremenek5535e5e2009-05-07 23:40:42 +00001341 RetainSummary* Summ = getPersistentSummary(ObjCAllocRetE);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001342
1343 // Create the "copy" selector.
Ted Kremenek9449ca92008-08-12 20:41:56 +00001344 addNSObjectMethSummary(GetNullarySelector("copy", Ctx), Summ);
1345
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001346 // Create the "mutableCopy" selector.
Ted Kremenek272aa852008-06-25 21:21:56 +00001347 addNSObjectMethSummary(GetNullarySelector("mutableCopy", Ctx), Summ);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001348
Ted Kremenek266d8b62008-05-06 02:26:56 +00001349 // Create the "retain" selector.
Ted Kremenek5535e5e2009-05-07 23:40:42 +00001350 RetEffect E = RetEffect::MakeReceiverAlias();
Ted Kremenek58dd95b2009-02-18 18:54:33 +00001351 Summ = getPersistentSummary(E, IncRefMsg);
Ted Kremenek272aa852008-06-25 21:21:56 +00001352 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001353
1354 // Create the "release" selector.
Ted Kremenek58dd95b2009-02-18 18:54:33 +00001355 Summ = getPersistentSummary(E, DecRefMsg);
Ted Kremenek272aa852008-06-25 21:21:56 +00001356 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Ted Kremenekc00b32b2008-05-07 21:17:39 +00001357
1358 // Create the "drain" selector.
1359 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek272aa852008-06-25 21:21:56 +00001360 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
Ted Kremenek6537a642009-03-17 19:42:23 +00001361
1362 // Create the -dealloc summary.
1363 Summ = getPersistentSummary(RetEffect::MakeNoRet(), Dealloc);
1364 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001365
1366 // Create the "autorelease" selector.
Ted Kremenek9b112d22009-01-28 21:44:40 +00001367 Summ = getPersistentSummary(E, Autorelease);
Ted Kremenek272aa852008-06-25 21:21:56 +00001368 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001369
Ted Kremenekaac82832009-02-23 17:45:03 +00001370 // Specially handle NSAutoreleasePool.
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001371 addInstMethSummary("NSAutoreleasePool", "init",
Ted Kremenekaac82832009-02-23 17:45:03 +00001372 getPersistentSummary(RetEffect::MakeReceiverAlias(),
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001373 NewAutoreleasePool));
Ted Kremenekaac82832009-02-23 17:45:03 +00001374
Ted Kremenek45642a42008-08-12 18:48:50 +00001375 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremenek7e3a3272009-02-23 02:51:29 +00001376 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1377 // self-own themselves. However, they only do this once they are displayed.
1378 // Thus, we need to track an NSWindow's display status.
1379 // This is tracked in <rdar://problem/6062711>.
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001380 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
Ted Kremeneke5a036a2009-04-03 19:02:51 +00001381 RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet());
1382
1383 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1384
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001385
1386#if 0
Ted Kremeneke44927e2008-07-01 17:21:27 +00001387 RetainSummary *NSWindowSumm =
Ted Kremenek7e3a3272009-02-23 02:51:29 +00001388 getPersistentSummary(RetEffect::MakeReceiverAlias(), StopTracking);
Ted Kremenek45642a42008-08-12 18:48:50 +00001389
1390 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1391 "styleMask", "backing", "defer", NULL);
1392
1393 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1394 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001395#endif
Ted Kremenek45642a42008-08-12 18:48:50 +00001396
1397 // For NSPanel (which subclasses NSWindow), allocated objects are not
1398 // self-owned.
Ted Kremeneke5a036a2009-04-03 19:02:51 +00001399 // FIXME: For now we don't track NSPanels. object for the same reason
1400 // as for NSWindow objects.
1401 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
1402
Ted Kremenek45642a42008-08-12 18:48:50 +00001403 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1404 "styleMask", "backing", "defer", NULL);
1405
1406 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1407 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek272aa852008-06-25 21:21:56 +00001408
Ted Kremenekf2717b02008-07-18 17:24:20 +00001409 // Create NSAssertionHandler summaries.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001410 addPanicSummary("NSAssertionHandler", "handleFailureInFunction", "file",
1411 "lineNumber", "description", NULL);
Ted Kremenekf2717b02008-07-18 17:24:20 +00001412
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001413 addPanicSummary("NSAssertionHandler", "handleFailureInMethod", "object",
1414 "file", "lineNumber", "description", NULL);
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001415}
1416
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001417//===----------------------------------------------------------------------===//
Ted Kremenek7aef4842008-04-16 20:40:59 +00001418// Reference-counting logic (typestate + counts).
Ted Kremeneka7338b42008-03-11 06:39:11 +00001419//===----------------------------------------------------------------------===//
1420
Ted Kremeneka7338b42008-03-11 06:39:11 +00001421namespace {
1422
Ted Kremenek7d421f32008-04-09 23:49:11 +00001423class VISIBILITY_HIDDEN RefVal {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001424public:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001425 enum Kind {
1426 Owned = 0, // Owning reference.
1427 NotOwned, // Reference is not owned by still valid (not freed).
1428 Released, // Object has been released.
1429 ReturnedOwned, // Returned object passes ownership to caller.
1430 ReturnedNotOwned, // Return object does not pass ownership to caller.
Ted Kremenek6537a642009-03-17 19:42:23 +00001431 ERROR_START,
1432 ErrorDeallocNotOwned, // -dealloc called on non-owned object.
1433 ErrorDeallocGC, // Calling -dealloc with GC enabled.
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001434 ErrorUseAfterRelease, // Object used after released.
1435 ErrorReleaseNotOwned, // Release of an object that was not owned.
Ted Kremenek6537a642009-03-17 19:42:23 +00001436 ERROR_LEAK_START,
Ted Kremenek311f3d42008-10-22 23:56:21 +00001437 ErrorLeak, // A memory leak due to excessive reference counts.
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001438 ErrorLeakReturned, // A memory leak due to the returning method not having
1439 // the correct naming conventions.
Ted Kremenekde92f7c2009-05-10 06:25:57 +00001440 ErrorGCLeakReturned,
1441 ErrorOverAutorelease,
1442 ErrorReturnedNotOwned
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001443 };
Ted Kremenek68621b92009-01-28 05:56:51 +00001444
1445private:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001446 Kind kind;
Ted Kremenek68621b92009-01-28 05:56:51 +00001447 RetEffect::ObjKind okind;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001448 unsigned Cnt;
Ted Kremenek4d99d342009-05-08 20:01:42 +00001449 unsigned ACnt;
Ted Kremenek272aa852008-06-25 21:21:56 +00001450 QualType T;
1451
Ted Kremenek4d99d342009-05-08 20:01:42 +00001452 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, unsigned acnt, QualType t)
1453 : kind(k), okind(o), Cnt(cnt), ACnt(acnt), T(t) {}
Ted Kremenek0d721572008-03-11 17:48:22 +00001454
Ted Kremenek68621b92009-01-28 05:56:51 +00001455 RefVal(Kind k, unsigned cnt = 0)
Ted Kremenek4d99d342009-05-08 20:01:42 +00001456 : kind(k), okind(RetEffect::AnyObj), Cnt(cnt), ACnt(0) {}
Ted Kremenek68621b92009-01-28 05:56:51 +00001457
1458public:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001459 Kind getKind() const { return kind; }
Ted Kremenek68621b92009-01-28 05:56:51 +00001460
1461 RetEffect::ObjKind getObjKind() const { return okind; }
Ted Kremenek0d721572008-03-11 17:48:22 +00001462
Ted Kremenek4d99d342009-05-08 20:01:42 +00001463 unsigned getCount() const { return Cnt; }
1464 unsigned getAutoreleaseCount() const { return ACnt; }
1465 unsigned getCombinedCounts() const { return Cnt + ACnt; }
1466 void clearCounts() { Cnt = 0; ACnt = 0; }
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001467 void setCount(unsigned i) { Cnt = i; }
1468 void setAutoreleaseCount(unsigned i) { ACnt = i; }
Ted Kremenek6537a642009-03-17 19:42:23 +00001469
Ted Kremenek272aa852008-06-25 21:21:56 +00001470 QualType getType() const { return T; }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001471
1472 // Useful predicates.
Ted Kremenek0d721572008-03-11 17:48:22 +00001473
Ted Kremenek6537a642009-03-17 19:42:23 +00001474 static bool isError(Kind k) { return k >= ERROR_START; }
Ted Kremenek1daa16c2008-03-11 18:14:09 +00001475
Ted Kremenek6537a642009-03-17 19:42:23 +00001476 static bool isLeak(Kind k) { return k >= ERROR_LEAK_START; }
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001477
Ted Kremenekffefc352008-04-11 22:25:11 +00001478 bool isOwned() const {
1479 return getKind() == Owned;
1480 }
1481
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001482 bool isNotOwned() const {
1483 return getKind() == NotOwned;
1484 }
1485
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001486 bool isReturnedOwned() const {
1487 return getKind() == ReturnedOwned;
1488 }
1489
1490 bool isReturnedNotOwned() const {
1491 return getKind() == ReturnedNotOwned;
1492 }
1493
1494 bool isNonLeakError() const {
1495 Kind k = getKind();
1496 return isError(k) && !isLeak(k);
1497 }
1498
Ted Kremenek68621b92009-01-28 05:56:51 +00001499 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
1500 unsigned Count = 1) {
Ted Kremenek4d99d342009-05-08 20:01:42 +00001501 return RefVal(Owned, o, Count, 0, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001502 }
1503
Ted Kremenek68621b92009-01-28 05:56:51 +00001504 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
1505 unsigned Count = 0) {
Ted Kremenek4d99d342009-05-08 20:01:42 +00001506 return RefVal(NotOwned, o, Count, 0, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001507 }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001508
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001509 // Comparison, profiling, and pretty-printing.
Ted Kremenek0d721572008-03-11 17:48:22 +00001510
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001511 bool operator==(const RefVal& X) const {
Ted Kremenekbd271be2009-05-10 05:11:21 +00001512 return kind == X.kind && Cnt == X.Cnt && T == X.T && ACnt == X.ACnt;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001513 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001514
Ted Kremenek272aa852008-06-25 21:21:56 +00001515 RefVal operator-(size_t i) const {
Ted Kremenek4d99d342009-05-08 20:01:42 +00001516 return RefVal(getKind(), getObjKind(), getCount() - i,
1517 getAutoreleaseCount(), getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001518 }
1519
1520 RefVal operator+(size_t i) const {
Ted Kremenek4d99d342009-05-08 20:01:42 +00001521 return RefVal(getKind(), getObjKind(), getCount() + i,
1522 getAutoreleaseCount(), getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001523 }
1524
1525 RefVal operator^(Kind k) const {
Ted Kremenek4d99d342009-05-08 20:01:42 +00001526 return RefVal(k, getObjKind(), getCount(), getAutoreleaseCount(),
1527 getType());
1528 }
1529
1530 RefVal autorelease() const {
1531 return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount()+1,
1532 getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001533 }
Ted Kremenek6537a642009-03-17 19:42:23 +00001534
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001535 void Profile(llvm::FoldingSetNodeID& ID) const {
1536 ID.AddInteger((unsigned) kind);
1537 ID.AddInteger(Cnt);
Ted Kremenek4d99d342009-05-08 20:01:42 +00001538 ID.AddInteger(ACnt);
Ted Kremenek272aa852008-06-25 21:21:56 +00001539 ID.Add(T);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001540 }
1541
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001542 void print(std::ostream& Out) const;
Ted Kremenek0d721572008-03-11 17:48:22 +00001543};
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001544
1545void RefVal::print(std::ostream& Out) const {
Ted Kremenek272aa852008-06-25 21:21:56 +00001546 if (!T.isNull())
1547 Out << "Tracked Type:" << T.getAsString() << '\n';
1548
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001549 switch (getKind()) {
1550 default: assert(false);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001551 case Owned: {
1552 Out << "Owned";
1553 unsigned cnt = getCount();
1554 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001555 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001556 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001557
Ted Kremenekc4f81022008-04-10 23:09:18 +00001558 case NotOwned: {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001559 Out << "NotOwned";
Ted Kremenekc4f81022008-04-10 23:09:18 +00001560 unsigned cnt = getCount();
1561 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001562 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001563 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001564
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001565 case ReturnedOwned: {
1566 Out << "ReturnedOwned";
1567 unsigned cnt = getCount();
1568 if (cnt) Out << " (+ " << cnt << ")";
1569 break;
1570 }
1571
1572 case ReturnedNotOwned: {
1573 Out << "ReturnedNotOwned";
1574 unsigned cnt = getCount();
1575 if (cnt) Out << " (+ " << cnt << ")";
1576 break;
1577 }
1578
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001579 case Released:
1580 Out << "Released";
1581 break;
Ted Kremenek6537a642009-03-17 19:42:23 +00001582
1583 case ErrorDeallocGC:
1584 Out << "-dealloc (GC)";
1585 break;
1586
1587 case ErrorDeallocNotOwned:
1588 Out << "-dealloc (not-owned)";
1589 break;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001590
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001591 case ErrorLeak:
1592 Out << "Leaked";
1593 break;
1594
Ted Kremenek311f3d42008-10-22 23:56:21 +00001595 case ErrorLeakReturned:
1596 Out << "Leaked (Bad naming)";
1597 break;
1598
Ted Kremenekde92f7c2009-05-10 06:25:57 +00001599 case ErrorGCLeakReturned:
1600 Out << "Leaked (GC-ed at return)";
1601 break;
1602
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001603 case ErrorUseAfterRelease:
1604 Out << "Use-After-Release [ERROR]";
1605 break;
1606
1607 case ErrorReleaseNotOwned:
1608 Out << "Release of Not-Owned [ERROR]";
1609 break;
Ted Kremenek3f15aba2009-05-09 00:44:07 +00001610
1611 case RefVal::ErrorOverAutorelease:
1612 Out << "Over autoreleased";
1613 break;
Ted Kremenekde92f7c2009-05-10 06:25:57 +00001614
1615 case RefVal::ErrorReturnedNotOwned:
1616 Out << "Non-owned object returned instead of owned";
1617 break;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001618 }
Ted Kremenek4d99d342009-05-08 20:01:42 +00001619
1620 if (ACnt) {
1621 Out << " [ARC +" << ACnt << ']';
1622 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001623}
Ted Kremenek0d721572008-03-11 17:48:22 +00001624
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001625} // end anonymous namespace
1626
1627//===----------------------------------------------------------------------===//
1628// RefBindings - State used to track object reference counts.
1629//===----------------------------------------------------------------------===//
1630
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001631typedef llvm::ImmutableMap<SymbolRef, RefVal> RefBindings;
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001632static int RefBIndex = 0;
1633
1634namespace clang {
Ted Kremenek91781202008-08-17 03:20:02 +00001635 template<>
1636 struct GRStateTrait<RefBindings> : public GRStatePartialTrait<RefBindings> {
1637 static inline void* GDMIndex() { return &RefBIndex; }
1638 };
1639}
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001640
1641//===----------------------------------------------------------------------===//
Ted Kremenekb6578942009-02-24 19:15:11 +00001642// AutoreleaseBindings - State used to track objects in autorelease pools.
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001643//===----------------------------------------------------------------------===//
1644
Ted Kremenekb6578942009-02-24 19:15:11 +00001645typedef llvm::ImmutableMap<SymbolRef, unsigned> ARCounts;
1646typedef llvm::ImmutableMap<SymbolRef, ARCounts> ARPoolContents;
1647typedef llvm::ImmutableList<SymbolRef> ARStack;
Ted Kremenekaac82832009-02-23 17:45:03 +00001648
Ted Kremenekb6578942009-02-24 19:15:11 +00001649static int AutoRCIndex = 0;
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001650static int AutoRBIndex = 0;
1651
Ted Kremenekb6578942009-02-24 19:15:11 +00001652namespace { class VISIBILITY_HIDDEN AutoreleasePoolContents {}; }
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001653namespace { class VISIBILITY_HIDDEN AutoreleaseStack {}; }
Ted Kremenekb6578942009-02-24 19:15:11 +00001654
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001655namespace clang {
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001656template<> struct GRStateTrait<AutoreleaseStack>
Ted Kremenekb6578942009-02-24 19:15:11 +00001657 : public GRStatePartialTrait<ARStack> {
1658 static inline void* GDMIndex() { return &AutoRBIndex; }
1659};
1660
1661template<> struct GRStateTrait<AutoreleasePoolContents>
1662 : public GRStatePartialTrait<ARPoolContents> {
1663 static inline void* GDMIndex() { return &AutoRCIndex; }
1664};
1665} // end clang namespace
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001666
Ted Kremenek681fb352009-03-20 17:34:15 +00001667static SymbolRef GetCurrentAutoreleasePool(const GRState* state) {
1668 ARStack stack = state->get<AutoreleaseStack>();
1669 return stack.isEmpty() ? SymbolRef() : stack.getHead();
1670}
1671
1672static GRStateRef SendAutorelease(GRStateRef state, ARCounts::Factory &F,
1673 SymbolRef sym) {
1674
1675 SymbolRef pool = GetCurrentAutoreleasePool(state);
1676 const ARCounts *cnts = state.get<AutoreleasePoolContents>(pool);
1677 ARCounts newCnts(0);
1678
1679 if (cnts) {
1680 const unsigned *cnt = (*cnts).lookup(sym);
1681 newCnts = F.Add(*cnts, sym, cnt ? *cnt + 1 : 1);
1682 }
1683 else
1684 newCnts = F.Add(F.GetEmptyMap(), sym, 1);
1685
1686 return state.set<AutoreleasePoolContents>(pool, newCnts);
1687}
1688
Ted Kremenek7aef4842008-04-16 20:40:59 +00001689//===----------------------------------------------------------------------===//
1690// Transfer functions.
1691//===----------------------------------------------------------------------===//
1692
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001693namespace {
1694
Ted Kremenek7d421f32008-04-09 23:49:11 +00001695class VISIBILITY_HIDDEN CFRefCount : public GRSimpleVals {
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001696public:
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001697 class BindingsPrinter : public GRState::Printer {
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001698 public:
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001699 virtual void Print(std::ostream& Out, const GRState* state,
1700 const char* nl, const char* sep);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001701 };
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001702
1703private:
Ted Kremenekc26c4692009-02-18 03:48:14 +00001704 typedef llvm::DenseMap<const GRExprEngine::NodeTy*, const RetainSummary*>
1705 SummaryLogTy;
1706
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001707 RetainSummaryManager Summaries;
Ted Kremenekc26c4692009-02-18 03:48:14 +00001708 SummaryLogTy SummaryLog;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001709 const LangOptions& LOpts;
Ted Kremenekb6578942009-02-24 19:15:11 +00001710 ARCounts::Factory ARCountFactory;
Ted Kremenek91781202008-08-17 03:20:02 +00001711
Ted Kremenek708af042009-02-05 06:50:21 +00001712 BugType *useAfterRelease, *releaseNotOwned;
Ted Kremenek6537a642009-03-17 19:42:23 +00001713 BugType *deallocGC, *deallocNotOwned;
Ted Kremenek708af042009-02-05 06:50:21 +00001714 BugType *leakWithinFunction, *leakAtReturn;
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001715 BugType *overAutorelease;
Ted Kremenekde92f7c2009-05-10 06:25:57 +00001716 BugType *returnNotOwnedForOwned;
Ted Kremenek708af042009-02-05 06:50:21 +00001717 BugReporter *BR;
Ted Kremeneka7338b42008-03-11 06:39:11 +00001718
Ted Kremenekb6578942009-02-24 19:15:11 +00001719 GRStateRef Update(GRStateRef state, SymbolRef sym, RefVal V, ArgEffect E,
1720 RefVal::Kind& hasErr);
1721
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001722 void ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
1723 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00001724 Expr* NodeExpr, Expr* ErrorExpr,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001725 ExplodedNode<GRState>* Pred,
1726 const GRState* St,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001727 RefVal::Kind hasErr, SymbolRef Sym);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001728
Ted Kremenek41a4bc62009-05-08 23:09:42 +00001729 GRStateRef HandleSymbolDeath(GRStateRef state, SymbolRef sid, RefVal V,
1730 llvm::SmallVectorImpl<SymbolRef> &Leaked);
1731
1732 ExplodedNode<GRState>* ProcessLeaks(GRStateRef state,
1733 llvm::SmallVectorImpl<SymbolRef> &Leaked,
1734 GenericNodeBuilder &Builder,
1735 GRExprEngine &Eng,
1736 ExplodedNode<GRState> *Pred = 0);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001737
Ted Kremenekb6578942009-02-24 19:15:11 +00001738public:
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00001739 CFRefCount(ASTContext& Ctx, bool gcenabled, const LangOptions& lopts)
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001740 : Summaries(Ctx, gcenabled),
Ted Kremenek6537a642009-03-17 19:42:23 +00001741 LOpts(lopts), useAfterRelease(0), releaseNotOwned(0),
1742 deallocGC(0), deallocNotOwned(0),
Ted Kremenekde92f7c2009-05-10 06:25:57 +00001743 leakWithinFunction(0), leakAtReturn(0), overAutorelease(0),
1744 returnNotOwnedForOwned(0), BR(0) {}
Ted Kremenek1feab292008-04-16 04:28:53 +00001745
Ted Kremenek708af042009-02-05 06:50:21 +00001746 virtual ~CFRefCount() {}
Ted Kremenek7d421f32008-04-09 23:49:11 +00001747
Ted Kremenekbf6babf2009-02-04 23:49:09 +00001748 void RegisterChecks(BugReporter &BR);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001749
Ted Kremenekb0f2b9e2008-08-16 00:49:49 +00001750 virtual void RegisterPrinters(std::vector<GRState::Printer*>& Printers) {
1751 Printers.push_back(new BindingsPrinter());
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001752 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00001753
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001754 bool isGCEnabled() const { return Summaries.isGCEnabled(); }
Ted Kremenekfe30beb2008-04-30 23:47:44 +00001755 const LangOptions& getLangOptions() const { return LOpts; }
1756
Ted Kremenekc26c4692009-02-18 03:48:14 +00001757 const RetainSummary *getSummaryOfNode(const ExplodedNode<GRState> *N) const {
1758 SummaryLogTy::const_iterator I = SummaryLog.find(N);
1759 return I == SummaryLog.end() ? 0 : I->second;
1760 }
1761
Ted Kremeneka7338b42008-03-11 06:39:11 +00001762 // Calls.
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001763
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001764 void EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001765 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001766 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001767 Expr* Ex,
1768 Expr* Receiver,
Ted Kremenek286e9852009-05-04 04:57:00 +00001769 const RetainSummary& Summ,
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00001770 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001771 ExplodedNode<GRState>* Pred);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001772
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001773 virtual void EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekce0767f2008-03-12 21:06:49 +00001774 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001775 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001776 CallExpr* CE, SVal L,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001777 ExplodedNode<GRState>* Pred);
Ted Kremenek10fe66d2008-04-09 01:10:13 +00001778
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001779
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001780 virtual void EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001781 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001782 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001783 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001784 ExplodedNode<GRState>* Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001785
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001786 bool EvalObjCMessageExprAux(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001787 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001788 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001789 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001790 ExplodedNode<GRState>* Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001791
Ted Kremeneka42be302009-02-14 01:43:44 +00001792 // Stores.
1793 virtual void EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val);
1794
Ted Kremenekffefc352008-04-11 22:25:11 +00001795 // End-of-path.
1796
1797 virtual void EvalEndPath(GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001798 GREndPathNodeBuilder<GRState>& Builder);
Ted Kremenekffefc352008-04-11 22:25:11 +00001799
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001800 virtual void EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek541db372008-04-24 23:57:27 +00001801 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001802 GRStmtNodeBuilder<GRState>& Builder,
1803 ExplodedNode<GRState>* Pred,
Ted Kremenek5c0729b2009-01-21 22:26:05 +00001804 Stmt* S, const GRState* state,
1805 SymbolReaper& SymReaper);
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00001806
1807 std::pair<ExplodedNode<GRState>*, GRStateRef>
1808 HandleAutoreleaseCounts(GRStateRef state, GenericNodeBuilder Bd,
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001809 ExplodedNode<GRState>* Pred, GRExprEngine &Eng,
1810 SymbolRef Sym, RefVal V, bool &stop);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001811 // Return statements.
1812
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001813 virtual void EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001814 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001815 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001816 ReturnStmt* S,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001817 ExplodedNode<GRState>* Pred);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001818
1819 // Assumptions.
1820
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001821 virtual const GRState* EvalAssume(GRStateManager& VMgr,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001822 const GRState* St, SVal Cond,
Ted Kremenekf22f8682008-07-10 22:03:41 +00001823 bool Assumption, bool& isFeasible);
Ted Kremeneka7338b42008-03-11 06:39:11 +00001824};
1825
1826} // end anonymous namespace
1827
Ted Kremenek681fb352009-03-20 17:34:15 +00001828static void PrintPool(std::ostream &Out, SymbolRef Sym, const GRState *state) {
1829 Out << ' ';
Ted Kremenek74556a12009-03-26 03:35:11 +00001830 if (Sym)
1831 Out << Sym->getSymbolID();
Ted Kremenek681fb352009-03-20 17:34:15 +00001832 else
1833 Out << "<pool>";
1834 Out << ":{";
1835
1836 // Get the contents of the pool.
1837 if (const ARCounts *cnts = state->get<AutoreleasePoolContents>(Sym))
1838 for (ARCounts::iterator J=cnts->begin(), EJ=cnts->end(); J != EJ; ++J)
1839 Out << '(' << J.getKey() << ',' << J.getData() << ')';
1840
1841 Out << '}';
1842}
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001843
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001844void CFRefCount::BindingsPrinter::Print(std::ostream& Out, const GRState* state,
1845 const char* nl, const char* sep) {
Ted Kremenek681fb352009-03-20 17:34:15 +00001846
1847
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001848
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001849 RefBindings B = state->get<RefBindings>();
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001850
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001851 if (!B.isEmpty())
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001852 Out << sep << nl;
1853
1854 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
1855 Out << (*I).first << " : ";
1856 (*I).second.print(Out);
1857 Out << nl;
1858 }
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001859
1860 // Print the autorelease stack.
Ted Kremenek681fb352009-03-20 17:34:15 +00001861 Out << sep << nl << "AR pool stack:";
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001862 ARStack stack = state->get<AutoreleaseStack>();
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001863
Ted Kremenek681fb352009-03-20 17:34:15 +00001864 PrintPool(Out, SymbolRef(), state); // Print the caller's pool.
1865 for (ARStack::iterator I=stack.begin(), E=stack.end(); I!=E; ++I)
1866 PrintPool(Out, *I, state);
1867
1868 Out << nl;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001869}
1870
Ted Kremenek47a72422009-04-29 18:50:19 +00001871//===----------------------------------------------------------------------===//
1872// Error reporting.
1873//===----------------------------------------------------------------------===//
1874
1875namespace {
1876
1877 //===-------------===//
1878 // Bug Descriptions. //
1879 //===-------------===//
1880
1881 class VISIBILITY_HIDDEN CFRefBug : public BugType {
1882 protected:
1883 CFRefCount& TF;
1884
1885 CFRefBug(CFRefCount* tf, const char* name)
1886 : BugType(name, "Memory (Core Foundation/Objective-C)"), TF(*tf) {}
1887 public:
1888
1889 CFRefCount& getTF() { return TF; }
1890 const CFRefCount& getTF() const { return TF; }
1891
1892 // FIXME: Eventually remove.
1893 virtual const char* getDescription() const = 0;
1894
1895 virtual bool isLeak() const { return false; }
1896 };
1897
1898 class VISIBILITY_HIDDEN UseAfterRelease : public CFRefBug {
1899 public:
1900 UseAfterRelease(CFRefCount* tf)
1901 : CFRefBug(tf, "Use-after-release") {}
1902
1903 const char* getDescription() const {
1904 return "Reference-counted object is used after it is released";
1905 }
1906 };
1907
1908 class VISIBILITY_HIDDEN BadRelease : public CFRefBug {
1909 public:
1910 BadRelease(CFRefCount* tf) : CFRefBug(tf, "Bad release") {}
1911
1912 const char* getDescription() const {
1913 return "Incorrect decrement of the reference count of an "
1914 "object is not owned at this point by the caller";
1915 }
1916 };
1917
1918 class VISIBILITY_HIDDEN DeallocGC : public CFRefBug {
1919 public:
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001920 DeallocGC(CFRefCount *tf)
1921 : CFRefBug(tf, "-dealloc called while using garbage collection") {}
Ted Kremenek47a72422009-04-29 18:50:19 +00001922
1923 const char *getDescription() const {
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001924 return "-dealloc called while using garbage collection";
Ted Kremenek47a72422009-04-29 18:50:19 +00001925 }
1926 };
1927
1928 class VISIBILITY_HIDDEN DeallocNotOwned : public CFRefBug {
1929 public:
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001930 DeallocNotOwned(CFRefCount *tf)
1931 : CFRefBug(tf, "-dealloc sent to non-exclusively owned object") {}
Ted Kremenek47a72422009-04-29 18:50:19 +00001932
1933 const char *getDescription() const {
1934 return "-dealloc sent to object that may be referenced elsewhere";
1935 }
1936 };
1937
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001938 class VISIBILITY_HIDDEN OverAutorelease : public CFRefBug {
1939 public:
1940 OverAutorelease(CFRefCount *tf) :
1941 CFRefBug(tf, "Object sent -autorelease too many times") {}
1942
1943 const char *getDescription() const {
Ted Kremenekbd271be2009-05-10 05:11:21 +00001944 return "Object sent -autorelease too many times";
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001945 }
1946 };
1947
Ted Kremenekde92f7c2009-05-10 06:25:57 +00001948 class VISIBILITY_HIDDEN ReturnedNotOwnedForOwned : public CFRefBug {
1949 public:
1950 ReturnedNotOwnedForOwned(CFRefCount *tf) :
1951 CFRefBug(tf, "Method should return an owned object") {}
1952
1953 const char *getDescription() const {
1954 return "Object with +0 retain counts returned to caller where a +1 "
1955 "(owning) retain count is expected";
1956 }
1957 };
1958
Ted Kremenek47a72422009-04-29 18:50:19 +00001959 class VISIBILITY_HIDDEN Leak : public CFRefBug {
1960 const bool isReturn;
1961 protected:
1962 Leak(CFRefCount* tf, const char* name, bool isRet)
1963 : CFRefBug(tf, name), isReturn(isRet) {}
1964 public:
1965
1966 const char* getDescription() const { return ""; }
1967
1968 bool isLeak() const { return true; }
1969 };
1970
1971 class VISIBILITY_HIDDEN LeakAtReturn : public Leak {
1972 public:
1973 LeakAtReturn(CFRefCount* tf, const char* name)
1974 : Leak(tf, name, true) {}
1975 };
1976
1977 class VISIBILITY_HIDDEN LeakWithinFunction : public Leak {
1978 public:
1979 LeakWithinFunction(CFRefCount* tf, const char* name)
1980 : Leak(tf, name, false) {}
1981 };
1982
1983 //===---------===//
1984 // Bug Reports. //
1985 //===---------===//
1986
1987 class VISIBILITY_HIDDEN CFRefReport : public RangedBugReport {
1988 protected:
1989 SymbolRef Sym;
1990 const CFRefCount &TF;
1991 public:
1992 CFRefReport(CFRefBug& D, const CFRefCount &tf,
1993 ExplodedNode<GRState> *n, SymbolRef sym)
Ted Kremenekbd271be2009-05-10 05:11:21 +00001994 : RangedBugReport(D, D.getDescription(), n), Sym(sym), TF(tf) {}
1995
1996 CFRefReport(CFRefBug& D, const CFRefCount &tf,
1997 ExplodedNode<GRState> *n, SymbolRef sym, const char* endText)
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00001998 : RangedBugReport(D, D.getDescription(), endText, n), Sym(sym), TF(tf) {}
Ted Kremenek47a72422009-04-29 18:50:19 +00001999
2000 virtual ~CFRefReport() {}
2001
2002 CFRefBug& getBugType() {
2003 return (CFRefBug&) RangedBugReport::getBugType();
2004 }
2005 const CFRefBug& getBugType() const {
2006 return (const CFRefBug&) RangedBugReport::getBugType();
2007 }
2008
2009 virtual void getRanges(BugReporter& BR, const SourceRange*& beg,
2010 const SourceRange*& end) {
2011
2012 if (!getBugType().isLeak())
2013 RangedBugReport::getRanges(BR, beg, end);
2014 else
2015 beg = end = 0;
2016 }
2017
2018 SymbolRef getSymbol() const { return Sym; }
2019
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002020 PathDiagnosticPiece* getEndPath(BugReporterContext& BRC,
Ted Kremenek47a72422009-04-29 18:50:19 +00002021 const ExplodedNode<GRState>* N);
2022
2023 std::pair<const char**,const char**> getExtraDescriptiveText();
2024
2025 PathDiagnosticPiece* VisitNode(const ExplodedNode<GRState>* N,
2026 const ExplodedNode<GRState>* PrevN,
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002027 BugReporterContext& BRC);
Ted Kremenek47a72422009-04-29 18:50:19 +00002028 };
Ted Kremenekbd271be2009-05-10 05:11:21 +00002029
Ted Kremenek47a72422009-04-29 18:50:19 +00002030 class VISIBILITY_HIDDEN CFRefLeakReport : public CFRefReport {
2031 SourceLocation AllocSite;
2032 const MemRegion* AllocBinding;
2033 public:
2034 CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2035 ExplodedNode<GRState> *n, SymbolRef sym,
2036 GRExprEngine& Eng);
2037
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002038 PathDiagnosticPiece* getEndPath(BugReporterContext& BRC,
Ted Kremenek47a72422009-04-29 18:50:19 +00002039 const ExplodedNode<GRState>* N);
2040
2041 SourceLocation getLocation() const { return AllocSite; }
2042 };
2043} // end anonymous namespace
2044
2045void CFRefCount::RegisterChecks(BugReporter& BR) {
2046 useAfterRelease = new UseAfterRelease(this);
2047 BR.Register(useAfterRelease);
2048
2049 releaseNotOwned = new BadRelease(this);
2050 BR.Register(releaseNotOwned);
2051
2052 deallocGC = new DeallocGC(this);
2053 BR.Register(deallocGC);
2054
2055 deallocNotOwned = new DeallocNotOwned(this);
2056 BR.Register(deallocNotOwned);
2057
Ted Kremenek412ca1e2009-05-09 00:10:05 +00002058 overAutorelease = new OverAutorelease(this);
2059 BR.Register(overAutorelease);
2060
Ted Kremenekde92f7c2009-05-10 06:25:57 +00002061 returnNotOwnedForOwned = new ReturnedNotOwnedForOwned(this);
2062 BR.Register(returnNotOwnedForOwned);
2063
Ted Kremenek47a72422009-04-29 18:50:19 +00002064 // First register "return" leaks.
2065 const char* name = 0;
2066
2067 if (isGCEnabled())
2068 name = "Leak of returned object when using garbage collection";
2069 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2070 name = "Leak of returned object when not using garbage collection (GC) in "
2071 "dual GC/non-GC code";
2072 else {
2073 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2074 name = "Leak of returned object";
2075 }
2076
2077 leakAtReturn = new LeakAtReturn(this, name);
2078 BR.Register(leakAtReturn);
2079
2080 // Second, register leaks within a function/method.
2081 if (isGCEnabled())
2082 name = "Leak of object when using garbage collection";
2083 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2084 name = "Leak of object when not using garbage collection (GC) in "
2085 "dual GC/non-GC code";
2086 else {
2087 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2088 name = "Leak";
2089 }
2090
2091 leakWithinFunction = new LeakWithinFunction(this, name);
2092 BR.Register(leakWithinFunction);
2093
2094 // Save the reference to the BugReporter.
2095 this->BR = &BR;
2096}
2097
2098static const char* Msgs[] = {
2099 // GC only
2100 "Code is compiled to only use garbage collection",
2101 // No GC.
2102 "Code is compiled to use reference counts",
2103 // Hybrid, with GC.
2104 "Code is compiled to use either garbage collection (GC) or reference counts"
2105 " (non-GC). The bug occurs with GC enabled",
2106 // Hybrid, without GC
2107 "Code is compiled to use either garbage collection (GC) or reference counts"
2108 " (non-GC). The bug occurs in non-GC mode"
2109};
2110
2111std::pair<const char**,const char**> CFRefReport::getExtraDescriptiveText() {
2112 CFRefCount& TF = static_cast<CFRefBug&>(getBugType()).getTF();
2113
2114 switch (TF.getLangOptions().getGCMode()) {
2115 default:
2116 assert(false);
2117
2118 case LangOptions::GCOnly:
2119 assert (TF.isGCEnabled());
2120 return std::make_pair(&Msgs[0], &Msgs[0]+1);
2121
2122 case LangOptions::NonGC:
2123 assert (!TF.isGCEnabled());
2124 return std::make_pair(&Msgs[1], &Msgs[1]+1);
2125
2126 case LangOptions::HybridGC:
2127 if (TF.isGCEnabled())
2128 return std::make_pair(&Msgs[2], &Msgs[2]+1);
2129 else
2130 return std::make_pair(&Msgs[3], &Msgs[3]+1);
2131 }
2132}
2133
2134static inline bool contains(const llvm::SmallVectorImpl<ArgEffect>& V,
2135 ArgEffect X) {
2136 for (llvm::SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
2137 I!=E; ++I)
2138 if (*I == X) return true;
2139
2140 return false;
2141}
2142
2143PathDiagnosticPiece* CFRefReport::VisitNode(const ExplodedNode<GRState>* N,
2144 const ExplodedNode<GRState>* PrevN,
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002145 BugReporterContext& BRC) {
Ted Kremenek47a72422009-04-29 18:50:19 +00002146
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002147 // Check if the type state has changed.
2148 GRStateManager &StMgr = BRC.getStateManager();
Ted Kremenek47a72422009-04-29 18:50:19 +00002149 GRStateRef PrevSt(PrevN->getState(), StMgr);
2150 GRStateRef CurrSt(N->getState(), StMgr);
2151
2152 const RefVal* CurrT = CurrSt.get<RefBindings>(Sym);
2153 if (!CurrT) return NULL;
2154
2155 const RefVal& CurrV = *CurrT;
2156 const RefVal* PrevT = PrevSt.get<RefBindings>(Sym);
2157
2158 // Create a string buffer to constain all the useful things we want
2159 // to tell the user.
2160 std::string sbuf;
2161 llvm::raw_string_ostream os(sbuf);
2162
2163 // This is the allocation site since the previous node had no bindings
2164 // for this symbol.
2165 if (!PrevT) {
2166 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2167
2168 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2169 // Get the name of the callee (if it is available).
2170 SVal X = CurrSt.GetSValAsScalarOrLoc(CE->getCallee());
2171 if (const FunctionDecl* FD = X.getAsFunctionDecl())
2172 os << "Call to function '" << FD->getNameAsString() <<'\'';
2173 else
2174 os << "function call";
2175 }
2176 else {
2177 assert (isa<ObjCMessageExpr>(S));
2178 os << "Method";
2179 }
2180
2181 if (CurrV.getObjKind() == RetEffect::CF) {
2182 os << " returns a Core Foundation object with a ";
2183 }
2184 else {
2185 assert (CurrV.getObjKind() == RetEffect::ObjC);
2186 os << " returns an Objective-C object with a ";
2187 }
2188
2189 if (CurrV.isOwned()) {
2190 os << "+1 retain count (owning reference).";
2191
2192 if (static_cast<CFRefBug&>(getBugType()).getTF().isGCEnabled()) {
2193 assert(CurrV.getObjKind() == RetEffect::CF);
2194 os << " "
2195 "Core Foundation objects are not automatically garbage collected.";
2196 }
2197 }
2198 else {
2199 assert (CurrV.isNotOwned());
2200 os << "+0 retain count (non-owning reference).";
2201 }
2202
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002203 PathDiagnosticLocation Pos(S, BRC.getSourceManager());
Ted Kremenek47a72422009-04-29 18:50:19 +00002204 return new PathDiagnosticEventPiece(Pos, os.str());
2205 }
2206
2207 // Gather up the effects that were performed on the object at this
2208 // program point
2209 llvm::SmallVector<ArgEffect, 2> AEffects;
2210
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002211 if (const RetainSummary *Summ =
2212 TF.getSummaryOfNode(BRC.getNodeResolver().getOriginalNode(N))) {
Ted Kremenek47a72422009-04-29 18:50:19 +00002213 // We only have summaries attached to nodes after evaluating CallExpr and
2214 // ObjCMessageExprs.
2215 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2216
2217 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2218 // Iterate through the parameter expressions and see if the symbol
2219 // was ever passed as an argument.
2220 unsigned i = 0;
2221
2222 for (CallExpr::arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
2223 AI!=AE; ++AI, ++i) {
2224
2225 // Retrieve the value of the argument. Is it the symbol
2226 // we are interested in?
2227 if (CurrSt.GetSValAsScalarOrLoc(*AI).getAsLocSymbol() != Sym)
2228 continue;
2229
2230 // We have an argument. Get the effect!
2231 AEffects.push_back(Summ->getArg(i));
2232 }
2233 }
2234 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
2235 if (Expr *receiver = ME->getReceiver())
2236 if (CurrSt.GetSValAsScalarOrLoc(receiver).getAsLocSymbol() == Sym) {
2237 // The symbol we are tracking is the receiver.
2238 AEffects.push_back(Summ->getReceiverEffect());
2239 }
2240 }
2241 }
2242
2243 do {
2244 // Get the previous type state.
2245 RefVal PrevV = *PrevT;
2246
2247 // Specially handle -dealloc.
2248 if (!TF.isGCEnabled() && contains(AEffects, Dealloc)) {
2249 // Determine if the object's reference count was pushed to zero.
2250 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2251 // We may not have transitioned to 'release' if we hit an error.
2252 // This case is handled elsewhere.
2253 if (CurrV.getKind() == RefVal::Released) {
Ted Kremenek4d99d342009-05-08 20:01:42 +00002254 assert(CurrV.getCombinedCounts() == 0);
Ted Kremenek47a72422009-04-29 18:50:19 +00002255 os << "Object released by directly sending the '-dealloc' message";
2256 break;
2257 }
2258 }
2259
2260 // Specially handle CFMakeCollectable and friends.
2261 if (contains(AEffects, MakeCollectable)) {
2262 // Get the name of the function.
2263 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2264 SVal X = CurrSt.GetSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee());
2265 const FunctionDecl* FD = X.getAsFunctionDecl();
2266 const std::string& FName = FD->getNameAsString();
2267
2268 if (TF.isGCEnabled()) {
2269 // Determine if the object's reference count was pushed to zero.
2270 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2271
2272 os << "In GC mode a call to '" << FName
2273 << "' decrements an object's retain count and registers the "
2274 "object with the garbage collector. ";
2275
2276 if (CurrV.getKind() == RefVal::Released) {
2277 assert(CurrV.getCount() == 0);
2278 os << "Since it now has a 0 retain count the object can be "
2279 "automatically collected by the garbage collector.";
2280 }
2281 else
2282 os << "An object must have a 0 retain count to be garbage collected. "
2283 "After this call its retain count is +" << CurrV.getCount()
2284 << '.';
2285 }
2286 else
2287 os << "When GC is not enabled a call to '" << FName
2288 << "' has no effect on its argument.";
2289
2290 // Nothing more to say.
2291 break;
2292 }
2293
2294 // Determine if the typestate has changed.
2295 if (!(PrevV == CurrV))
2296 switch (CurrV.getKind()) {
2297 case RefVal::Owned:
2298 case RefVal::NotOwned:
2299
Ted Kremenek4d99d342009-05-08 20:01:42 +00002300 if (PrevV.getCount() == CurrV.getCount()) {
2301 // Did an autorelease message get sent?
2302 if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
2303 return 0;
2304
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00002305 assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount());
Ted Kremenekbd271be2009-05-10 05:11:21 +00002306 os << "Object sent -autorelease message";
Ted Kremenek4d99d342009-05-08 20:01:42 +00002307 break;
2308 }
Ted Kremenek47a72422009-04-29 18:50:19 +00002309
2310 if (PrevV.getCount() > CurrV.getCount())
2311 os << "Reference count decremented.";
2312 else
2313 os << "Reference count incremented.";
2314
2315 if (unsigned Count = CurrV.getCount())
2316 os << " The object now has a +" << Count << " retain count.";
2317
2318 if (PrevV.getKind() == RefVal::Released) {
2319 assert(TF.isGCEnabled() && CurrV.getCount() > 0);
2320 os << " The object is not eligible for garbage collection until the "
2321 "retain count reaches 0 again.";
2322 }
2323
2324 break;
2325
2326 case RefVal::Released:
2327 os << "Object released.";
2328 break;
2329
2330 case RefVal::ReturnedOwned:
2331 os << "Object returned to caller as an owning reference (single retain "
2332 "count transferred to caller).";
2333 break;
2334
2335 case RefVal::ReturnedNotOwned:
2336 os << "Object returned to caller with a +0 (non-owning) retain count.";
2337 break;
2338
2339 default:
2340 return NULL;
2341 }
2342
2343 // Emit any remaining diagnostics for the argument effects (if any).
2344 for (llvm::SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
2345 E=AEffects.end(); I != E; ++I) {
2346
2347 // A bunch of things have alternate behavior under GC.
2348 if (TF.isGCEnabled())
2349 switch (*I) {
2350 default: break;
2351 case Autorelease:
2352 os << "In GC mode an 'autorelease' has no effect.";
2353 continue;
2354 case IncRefMsg:
2355 os << "In GC mode the 'retain' message has no effect.";
2356 continue;
2357 case DecRefMsg:
2358 os << "In GC mode the 'release' message has no effect.";
2359 continue;
2360 }
2361 }
2362 } while(0);
2363
2364 if (os.str().empty())
2365 return 0; // We have nothing to say!
2366
2367 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002368 PathDiagnosticLocation Pos(S, BRC.getSourceManager());
Ted Kremenek47a72422009-04-29 18:50:19 +00002369 PathDiagnosticPiece* P = new PathDiagnosticEventPiece(Pos, os.str());
2370
2371 // Add the range by scanning the children of the statement for any bindings
2372 // to Sym.
2373 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I)
2374 if (Expr* Exp = dyn_cast_or_null<Expr>(*I))
2375 if (CurrSt.GetSValAsScalarOrLoc(Exp).getAsLocSymbol() == Sym) {
2376 P->addRange(Exp->getSourceRange());
2377 break;
2378 }
2379
2380 return P;
2381}
2382
2383namespace {
2384 class VISIBILITY_HIDDEN FindUniqueBinding :
2385 public StoreManager::BindingsHandler {
2386 SymbolRef Sym;
2387 const MemRegion* Binding;
2388 bool First;
2389
2390 public:
2391 FindUniqueBinding(SymbolRef sym) : Sym(sym), Binding(0), First(true) {}
2392
2393 bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
2394 SVal val) {
2395
2396 SymbolRef SymV = val.getAsSymbol();
2397 if (!SymV || SymV != Sym)
2398 return true;
2399
2400 if (Binding) {
2401 First = false;
2402 return false;
2403 }
2404 else
2405 Binding = R;
2406
2407 return true;
2408 }
2409
2410 operator bool() { return First && Binding; }
2411 const MemRegion* getRegion() { return Binding; }
2412 };
2413}
2414
2415static std::pair<const ExplodedNode<GRState>*,const MemRegion*>
2416GetAllocationSite(GRStateManager& StateMgr, const ExplodedNode<GRState>* N,
2417 SymbolRef Sym) {
2418
2419 // Find both first node that referred to the tracked symbol and the
2420 // memory location that value was store to.
2421 const ExplodedNode<GRState>* Last = N;
2422 const MemRegion* FirstBinding = 0;
2423
2424 while (N) {
2425 const GRState* St = N->getState();
2426 RefBindings B = St->get<RefBindings>();
2427
2428 if (!B.lookup(Sym))
2429 break;
2430
2431 FindUniqueBinding FB(Sym);
2432 StateMgr.iterBindings(St, FB);
2433 if (FB) FirstBinding = FB.getRegion();
2434
2435 Last = N;
2436 N = N->pred_empty() ? NULL : *(N->pred_begin());
2437 }
2438
2439 return std::make_pair(Last, FirstBinding);
2440}
2441
2442PathDiagnosticPiece*
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002443CFRefReport::getEndPath(BugReporterContext& BRC,
2444 const ExplodedNode<GRState>* EndN) {
2445 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenek47a72422009-04-29 18:50:19 +00002446 // assigned to different variables, etc.
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002447 BRC.addNotableSymbol(Sym);
2448 return RangedBugReport::getEndPath(BRC, EndN);
Ted Kremenek47a72422009-04-29 18:50:19 +00002449}
2450
2451PathDiagnosticPiece*
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002452CFRefLeakReport::getEndPath(BugReporterContext& BRC,
2453 const ExplodedNode<GRState>* EndN){
Ted Kremenek47a72422009-04-29 18:50:19 +00002454
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002455 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenek47a72422009-04-29 18:50:19 +00002456 // assigned to different variables, etc.
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002457 BRC.addNotableSymbol(Sym);
Ted Kremenek47a72422009-04-29 18:50:19 +00002458
2459 // We are reporting a leak. Walk up the graph to get to the first node where
2460 // the symbol appeared, and also get the first VarDecl that tracked object
2461 // is stored to.
2462 const ExplodedNode<GRState>* AllocNode = 0;
2463 const MemRegion* FirstBinding = 0;
2464
2465 llvm::tie(AllocNode, FirstBinding) =
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00002466 GetAllocationSite(BRC.getStateManager(), EndN, Sym);
Ted Kremenek47a72422009-04-29 18:50:19 +00002467
2468 // Get the allocate site.
2469 assert(AllocNode);
2470 Stmt* FirstStmt = cast<PostStmt>(AllocNode->getLocation()).getStmt();
2471
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002472 SourceManager& SMgr = BRC.getSourceManager();
Ted Kremenek47a72422009-04-29 18:50:19 +00002473 unsigned AllocLine =SMgr.getInstantiationLineNumber(FirstStmt->getLocStart());
2474
2475 // Compute an actual location for the leak. Sometimes a leak doesn't
2476 // occur at an actual statement (e.g., transition between blocks; end
2477 // of function) so we need to walk the graph and compute a real location.
2478 const ExplodedNode<GRState>* LeakN = EndN;
2479 PathDiagnosticLocation L;
2480
2481 while (LeakN) {
2482 ProgramPoint P = LeakN->getLocation();
2483
2484 if (const PostStmt *PS = dyn_cast<PostStmt>(&P)) {
2485 L = PathDiagnosticLocation(PS->getStmt()->getLocStart(), SMgr);
2486 break;
2487 }
2488 else if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
2489 if (const Stmt* Term = BE->getSrc()->getTerminator()) {
2490 L = PathDiagnosticLocation(Term->getLocStart(), SMgr);
2491 break;
2492 }
2493 }
2494
2495 LeakN = LeakN->succ_empty() ? 0 : *(LeakN->succ_begin());
2496 }
2497
2498 if (!L.isValid()) {
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002499 const Decl &D = BRC.getCodeDecl();
2500 L = PathDiagnosticLocation(D.getBodyRBrace(BRC.getASTContext()), SMgr);
Ted Kremenek47a72422009-04-29 18:50:19 +00002501 }
2502
2503 std::string sbuf;
2504 llvm::raw_string_ostream os(sbuf);
2505
2506 os << "Object allocated on line " << AllocLine;
2507
2508 if (FirstBinding)
2509 os << " and stored into '" << FirstBinding->getString() << '\'';
2510
2511 // Get the retain count.
2512 const RefVal* RV = EndN->getState()->get<RefBindings>(Sym);
2513
2514 if (RV->getKind() == RefVal::ErrorLeakReturned) {
2515 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
2516 // ojbects. Only "copy", "alloc", "retain" and "new" transfer ownership
2517 // to the caller for NS objects.
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002518 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(BRC.getCodeDecl());
Ted Kremenek47a72422009-04-29 18:50:19 +00002519 os << " is returned from a method whose name ('"
Ted Kremenek314b1952009-04-29 23:03:22 +00002520 << MD.getSelector().getAsString()
Ted Kremenek47a72422009-04-29 18:50:19 +00002521 << "') does not contain 'copy' or otherwise starts with"
2522 " 'new' or 'alloc'. This violates the naming convention rules given"
Ted Kremenek2a410c92009-04-29 22:25:52 +00002523 " in the Memory Management Guide for Cocoa (object leaked)";
Ted Kremenek47a72422009-04-29 18:50:19 +00002524 }
Ted Kremenekde92f7c2009-05-10 06:25:57 +00002525 else if (RV->getKind() == RefVal::ErrorGCLeakReturned) {
2526 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(BRC.getCodeDecl());
2527 os << " and returned from method '" << MD.getSelector().getAsString()
Ted Kremenekeaea6582009-05-10 16:52:15 +00002528 << "' is potentially leaked when using garbage collection. Callers "
2529 "of this method do not expect a returned object with a +1 retain "
2530 "count since they expect the object to be managed by the garbage "
2531 "collector";
Ted Kremenekde92f7c2009-05-10 06:25:57 +00002532 }
Ted Kremenek47a72422009-04-29 18:50:19 +00002533 else
2534 os << " is no longer referenced after this point and has a retain count of"
Ted Kremenek2a410c92009-04-29 22:25:52 +00002535 " +" << RV->getCount() << " (object leaked)";
Ted Kremenek47a72422009-04-29 18:50:19 +00002536
2537 return new PathDiagnosticEventPiece(L, os.str());
2538}
2539
Ted Kremenek47a72422009-04-29 18:50:19 +00002540CFRefLeakReport::CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2541 ExplodedNode<GRState> *n,
2542 SymbolRef sym, GRExprEngine& Eng)
2543: CFRefReport(D, tf, n, sym)
2544{
2545
2546 // Most bug reports are cached at the location where they occured.
2547 // With leaks, we want to unique them by the location where they were
2548 // allocated, and only report a single path. To do this, we need to find
2549 // the allocation site of a piece of tracked memory, which we do via a
2550 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2551 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2552 // that all ancestor nodes that represent the allocation site have the
2553 // same SourceLocation.
2554 const ExplodedNode<GRState>* AllocNode = 0;
2555
2556 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding.
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00002557 GetAllocationSite(Eng.getStateManager(), getEndNode(), getSymbol());
Ted Kremenek47a72422009-04-29 18:50:19 +00002558
2559 // Get the SourceLocation for the allocation site.
2560 ProgramPoint P = AllocNode->getLocation();
2561 AllocSite = cast<PostStmt>(P).getStmt()->getLocStart();
2562
2563 // Fill in the description of the bug.
2564 Description.clear();
2565 llvm::raw_string_ostream os(Description);
2566 SourceManager& SMgr = Eng.getContext().getSourceManager();
2567 unsigned AllocLine = SMgr.getInstantiationLineNumber(AllocSite);
Ted Kremenek2e9d0302009-05-02 19:05:19 +00002568 os << "Potential leak ";
2569 if (tf.isGCEnabled()) {
2570 os << "(when using garbage collection) ";
2571 }
2572 os << "of an object allocated on line " << AllocLine;
Ted Kremenek47a72422009-04-29 18:50:19 +00002573
2574 // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2575 if (AllocBinding)
2576 os << " and stored into '" << AllocBinding->getString() << '\'';
2577}
2578
2579//===----------------------------------------------------------------------===//
2580// Main checker logic.
2581//===----------------------------------------------------------------------===//
2582
Ted Kremenek272aa852008-06-25 21:21:56 +00002583/// GetReturnType - Used to get the return type of a message expression or
2584/// function call with the intention of affixing that type to a tracked symbol.
2585/// While the the return type can be queried directly from RetEx, when
2586/// invoking class methods we augment to the return type to be that of
2587/// a pointer to the class (as opposed it just being id).
2588static QualType GetReturnType(Expr* RetE, ASTContext& Ctx) {
2589
2590 QualType RetTy = RetE->getType();
2591
2592 // FIXME: We aren't handling id<...>.
Chris Lattnerb724ab22008-07-26 22:36:27 +00002593 const PointerType* PT = RetTy->getAsPointerType();
Ted Kremenek272aa852008-06-25 21:21:56 +00002594 if (!PT)
2595 return RetTy;
2596
2597 // If RetEx is not a message expression just return its type.
2598 // If RetEx is a message expression, return its types if it is something
2599 /// more specific than id.
2600
2601 ObjCMessageExpr* ME = dyn_cast<ObjCMessageExpr>(RetE);
2602
Steve Naroff17c03822009-02-12 17:52:19 +00002603 if (!ME || !Ctx.isObjCIdStructType(PT->getPointeeType()))
Ted Kremenek272aa852008-06-25 21:21:56 +00002604 return RetTy;
2605
2606 ObjCInterfaceDecl* D = ME->getClassInfo().first;
2607
2608 // At this point we know the return type of the message expression is id.
2609 // If we have an ObjCInterceDecl, we know this is a call to a class method
2610 // whose type we can resolve. In such cases, promote the return type to
2611 // Class*.
2612 return !D ? RetTy : Ctx.getPointerType(Ctx.getObjCInterfaceType(D));
2613}
2614
2615
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002616void CFRefCount::EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002617 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002618 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002619 Expr* Ex,
2620 Expr* Receiver,
Ted Kremenek286e9852009-05-04 04:57:00 +00002621 const RetainSummary& Summ,
Zhongxing Xucac107a2009-04-20 05:24:46 +00002622 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002623 ExplodedNode<GRState>* Pred) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002624
Ted Kremeneka7338b42008-03-11 06:39:11 +00002625 // Get the state.
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00002626 GRStateManager& StateMgr = Eng.getStateManager();
2627 GRStateRef state(Builder.GetState(Pred), StateMgr);
2628 ASTContext& Ctx = StateMgr.getContext();
2629 ValueManager &ValMgr = Eng.getValueManager();
Ted Kremenek227c5372008-05-06 02:41:27 +00002630
2631 // Evaluate the effect of the arguments.
Ted Kremenek1feab292008-04-16 04:28:53 +00002632 RefVal::Kind hasErr = (RefVal::Kind) 0;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002633 unsigned idx = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002634 Expr* ErrorExpr = NULL;
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002635 SymbolRef ErrorSym = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002636
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002637 for (ExprIterator I = arg_beg; I != arg_end; ++I, ++idx) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002638 SVal V = state.GetSValAsScalarOrLoc(*I);
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002639 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002640
Ted Kremenek74556a12009-03-26 03:35:11 +00002641 if (Sym)
Ted Kremenekb6578942009-02-24 19:15:11 +00002642 if (RefBindings::data_type* T = state.get<RefBindings>(Sym)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002643 state = Update(state, Sym, *T, Summ.getArg(idx), hasErr);
Ted Kremenekb6578942009-02-24 19:15:11 +00002644 if (hasErr) {
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002645 ErrorExpr = *I;
Ted Kremenek6064a362008-07-07 16:21:19 +00002646 ErrorSym = Sym;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002647 break;
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002648 }
2649 continue;
Ted Kremenekb6578942009-02-24 19:15:11 +00002650 }
Ted Kremenekede40b72008-07-09 18:11:16 +00002651
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002652 if (isa<Loc>(V)) {
2653 if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(&V)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002654 if (Summ.getArg(idx) == DoNothingByRef)
Ted Kremenekede40b72008-07-09 18:11:16 +00002655 continue;
2656
2657 // Invalidate the value of the variable passed by reference.
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002658
2659 // FIXME: Either this logic should also be replicated in GRSimpleVals
2660 // or should be pulled into a separate "constraint engine."
Ted Kremenekede40b72008-07-09 18:11:16 +00002661
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002662 // FIXME: We can have collisions on the conjured symbol if the
2663 // expression *I also creates conjured symbols. We probably want
2664 // to identify conjured symbols by an expression pair: the enclosing
2665 // expression (the context) and the expression itself. This should
Ted Kremenekede40b72008-07-09 18:11:16 +00002666 // disambiguate conjured symbols.
Ted Kremenekb15eba42008-10-04 05:50:14 +00002667
Ted Kremenek38a4b4b2008-10-17 20:28:54 +00002668 const TypedRegion* R = dyn_cast<TypedRegion>(MR->getRegion());
Zhongxing Xub9d47a42009-04-29 02:30:09 +00002669
Ted Kremenek73ec7732009-05-06 18:19:24 +00002670 if (R) {
2671 // Are we dealing with an ElementRegion? If the element type is
2672 // a basic integer type (e.g., char, int) and the underying region
Zhongxing Xuea6851b2009-05-11 14:28:14 +00002673 // is a variable region then strip off the ElementRegion.
Ted Kremenek73ec7732009-05-06 18:19:24 +00002674 // FIXME: We really need to think about this for the general case
2675 // as sometimes we are reasoning about arrays and other times
2676 // about (char*), etc., is just a form of passing raw bytes.
2677 // e.g., void *p = alloca(); foo((char*)p);
2678 if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
2679 // Checking for 'integral type' is probably too promiscuous, but
2680 // we'll leave it in for now until we have a systematic way of
2681 // handling all of these cases. Eventually we need to come up
2682 // with an interface to StoreManager so that this logic can be
2683 // approriately delegated to the respective StoreManagers while
2684 // still allowing us to do checker-specific logic (e.g.,
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00002685 // invalidating reference counts), probably via callbacks.
Ted Kremenek1cba5772009-05-11 22:55:17 +00002686 if (ER->getElementType()->isIntegralType()) {
2687 const MemRegion *superReg = ER->getSuperRegion();
2688 if (isa<VarRegion>(superReg) || isa<FieldRegion>(superReg) ||
2689 isa<ObjCIvarRegion>(superReg))
2690 R = cast<TypedRegion>(superReg);
2691 }
2692
Ted Kremenek73ec7732009-05-06 18:19:24 +00002693 // FIXME: What about layers of ElementRegions?
2694 }
2695
Ted Kremenek618c6cd2008-12-18 23:34:57 +00002696 // Is the invalidated variable something that we were tracking?
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002697 SymbolRef Sym = state.GetSValAsScalarOrLoc(R).getAsLocSymbol();
Ted Kremenek618c6cd2008-12-18 23:34:57 +00002698
Ted Kremenek53b24182009-03-04 22:56:43 +00002699 // Remove any existing reference-count binding.
Ted Kremenek74556a12009-03-26 03:35:11 +00002700 if (Sym) state = state.remove<RefBindings>(Sym);
Ted Kremenekb15eba42008-10-04 05:50:14 +00002701
Ted Kremenek53b24182009-03-04 22:56:43 +00002702 if (R->isBoundable(Ctx)) {
2703 // Set the value of the variable to be a conjured symbol.
2704 unsigned Count = Builder.getCurrentBlockCount();
Zhongxing Xu20362702009-05-09 03:57:34 +00002705 QualType T = R->getValueType(Ctx);
Ted Kremenek53b24182009-03-04 22:56:43 +00002706
Zhongxing Xu079dc352009-04-09 06:03:54 +00002707 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())){
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002708 ValueManager &ValMgr = Eng.getValueManager();
2709 SVal V = ValMgr.getConjuredSymbolVal(*I, T, Count);
Zhongxing Xu079dc352009-04-09 06:03:54 +00002710 state = state.BindLoc(Loc::MakeVal(R), V);
Ted Kremenek53b24182009-03-04 22:56:43 +00002711 }
2712 else if (const RecordType *RT = T->getAsStructureType()) {
2713 // Handle structs in a not so awesome way. Here we just
2714 // eagerly bind new symbols to the fields. In reality we
2715 // should have the store manager handle this. The idea is just
2716 // to prototype some basic functionality here. All of this logic
2717 // should one day soon just go away.
2718 const RecordDecl *RD = RT->getDecl()->getDefinition(Ctx);
2719
2720 // No record definition. There is nothing we can do.
2721 if (!RD)
2722 continue;
2723
2724 MemRegionManager &MRMgr = state.getManager().getRegionManager();
2725
2726 // Iterate through the fields and construct new symbols.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002727 for (RecordDecl::field_iterator FI=RD->field_begin(Ctx),
2728 FE=RD->field_end(Ctx); FI!=FE; ++FI) {
Ted Kremenek53b24182009-03-04 22:56:43 +00002729
2730 // For now just handle scalar fields.
2731 FieldDecl *FD = *FI;
2732 QualType FT = FD->getType();
2733
2734 if (Loc::IsLocType(FT) ||
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00002735 (FT->isIntegerType() && FT->isScalarType())) {
Ted Kremenek53b24182009-03-04 22:56:43 +00002736 const FieldRegion* FR = MRMgr.getFieldRegion(FD, R);
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00002737
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002738 SVal V = ValMgr.getConjuredSymbolVal(*I, FT, Count);
Zhongxing Xuc458e322009-04-09 06:32:20 +00002739 state = state.BindLoc(Loc::MakeVal(FR), V);
Ted Kremenek53b24182009-03-04 22:56:43 +00002740 }
2741 }
Zhongxing Xu35edd9a2009-05-12 10:10:00 +00002742 } else if (const ArrayType *AT = Ctx.getAsArrayType(T)) {
2743 // Set the default value of the array to conjured symbol.
2744 StoreManager& StoreMgr = Eng.getStateManager().getStoreManager();
2745 SVal V = ValMgr.getConjuredSymbolVal(*I, AT->getElementType(),
2746 Count);
2747 state = GRStateRef(StoreMgr.setDefaultValue(state, R, V),
2748 StateMgr);
2749 } else {
Ted Kremenek53b24182009-03-04 22:56:43 +00002750 // Just blast away other values.
2751 state = state.BindLoc(*MR, UnknownVal());
2752 }
Ted Kremenek8f90e712008-10-17 22:23:12 +00002753 }
Ted Kremenekb15eba42008-10-04 05:50:14 +00002754 }
2755 else
Ted Kremenek09102db2008-11-12 19:22:09 +00002756 state = state.BindLoc(*MR, UnknownVal());
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002757 }
2758 else {
2759 // Nuke all other arguments passed by reference.
Zhongxing Xu097fc982008-10-17 05:57:07 +00002760 state = state.Unbind(cast<Loc>(V));
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002761 }
Ted Kremeneke4924202008-04-11 20:51:02 +00002762 }
Zhongxing Xu097fc982008-10-17 05:57:07 +00002763 else if (isa<nonloc::LocAsInteger>(V))
2764 state = state.Unbind(cast<nonloc::LocAsInteger>(V).getLoc());
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002765 }
Ted Kremenek1feab292008-04-16 04:28:53 +00002766
Ted Kremenek272aa852008-06-25 21:21:56 +00002767 // Evaluate the effect on the message receiver.
Ted Kremenek227c5372008-05-06 02:41:27 +00002768 if (!ErrorExpr && Receiver) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002769 SymbolRef Sym = state.GetSValAsScalarOrLoc(Receiver).getAsLocSymbol();
Ted Kremenek74556a12009-03-26 03:35:11 +00002770 if (Sym) {
Ted Kremenekb6578942009-02-24 19:15:11 +00002771 if (const RefVal* T = state.get<RefBindings>(Sym)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002772 state = Update(state, Sym, *T, Summ.getReceiverEffect(), hasErr);
Ted Kremenekb6578942009-02-24 19:15:11 +00002773 if (hasErr) {
Ted Kremenek227c5372008-05-06 02:41:27 +00002774 ErrorExpr = Receiver;
Ted Kremenek6064a362008-07-07 16:21:19 +00002775 ErrorSym = Sym;
Ted Kremenek227c5372008-05-06 02:41:27 +00002776 }
Ted Kremenekb6578942009-02-24 19:15:11 +00002777 }
Ted Kremenek227c5372008-05-06 02:41:27 +00002778 }
2779 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002780
Ted Kremenek272aa852008-06-25 21:21:56 +00002781 // Process any errors.
Ted Kremenek1feab292008-04-16 04:28:53 +00002782 if (hasErr) {
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002783 ProcessNonLeakError(Dst, Builder, Ex, ErrorExpr, Pred, state,
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002784 hasErr, ErrorSym);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002785 return;
Ted Kremenek0d721572008-03-11 17:48:22 +00002786 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002787
Ted Kremenekf2717b02008-07-18 17:24:20 +00002788 // Consult the summary for the return value.
Ted Kremenek286e9852009-05-04 04:57:00 +00002789 RetEffect RE = Summ.getRetEffect();
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002790
2791 switch (RE.getKind()) {
2792 default:
2793 assert (false && "Unhandled RetEffect."); break;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002794
Ted Kremenek8f90e712008-10-17 22:23:12 +00002795 case RetEffect::NoRet: {
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002796
Ted Kremenek455dd862008-04-11 20:23:24 +00002797 // Make up a symbol for the return value (not reference counted).
Ted Kremeneke4924202008-04-11 20:51:02 +00002798 // FIXME: This is basically copy-and-paste from GRSimpleVals. We
2799 // should compose behavior, not copy it.
Ted Kremenek455dd862008-04-11 20:23:24 +00002800
Ted Kremenek8f90e712008-10-17 22:23:12 +00002801 // FIXME: We eventually should handle structs and other compound types
2802 // that are returned by value.
2803
2804 QualType T = Ex->getType();
2805
Ted Kremenek79413a52008-11-13 06:10:40 +00002806 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())) {
Ted Kremenek455dd862008-04-11 20:23:24 +00002807 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002808 ValueManager &ValMgr = Eng.getValueManager();
2809 SVal X = ValMgr.getConjuredSymbolVal(Ex, T, Count);
Ted Kremenek09102db2008-11-12 19:22:09 +00002810 state = state.BindExpr(Ex, X, false);
Ted Kremenek455dd862008-04-11 20:23:24 +00002811 }
2812
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002813 break;
Ted Kremenek8f90e712008-10-17 22:23:12 +00002814 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002815
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002816 case RetEffect::Alias: {
Ted Kremenek272aa852008-06-25 21:21:56 +00002817 unsigned idx = RE.getIndex();
Ted Kremenek2719e982008-06-17 02:43:46 +00002818 assert (arg_end >= arg_beg);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002819 assert (idx < (unsigned) (arg_end - arg_beg));
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002820 SVal V = state.GetSValAsScalarOrLoc(*(arg_beg+idx));
Ted Kremenek09102db2008-11-12 19:22:09 +00002821 state = state.BindExpr(Ex, V, false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002822 break;
2823 }
2824
Ted Kremenek227c5372008-05-06 02:41:27 +00002825 case RetEffect::ReceiverAlias: {
2826 assert (Receiver);
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002827 SVal V = state.GetSValAsScalarOrLoc(Receiver);
Ted Kremenek09102db2008-11-12 19:22:09 +00002828 state = state.BindExpr(Ex, V, false);
Ted Kremenek227c5372008-05-06 02:41:27 +00002829 break;
2830 }
2831
Ted Kremenek6a1cc252008-06-23 18:02:52 +00002832 case RetEffect::OwnedAllocatedSymbol:
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002833 case RetEffect::OwnedSymbol: {
2834 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke9e726e2009-04-09 16:13:17 +00002835 ValueManager &ValMgr = Eng.getValueManager();
2836 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
2837 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
2838 state = state.set<RefBindings>(Sym, RefVal::makeOwned(RE.getObjKind(),
2839 RetT));
2840 state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenek45c52a12009-03-09 22:46:49 +00002841
2842 // FIXME: Add a flag to the checker where allocations are assumed to
2843 // *not fail.
2844#if 0
Ted Kremeneke62fd052009-01-28 22:27:59 +00002845 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) {
2846 bool isFeasible;
2847 state = state.Assume(loc::SymbolVal(Sym), true, isFeasible);
2848 assert(isFeasible && "Cannot assume fresh symbol is non-null.");
2849 }
Ted Kremenek45c52a12009-03-09 22:46:49 +00002850#endif
Ted Kremenek6a1cc252008-06-23 18:02:52 +00002851
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002852 break;
2853 }
Ted Kremenek382fb4e2009-04-27 19:14:45 +00002854
2855 case RetEffect::GCNotOwnedSymbol:
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002856 case RetEffect::NotOwnedSymbol: {
2857 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke9e726e2009-04-09 16:13:17 +00002858 ValueManager &ValMgr = Eng.getValueManager();
2859 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
2860 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
2861 state = state.set<RefBindings>(Sym, RefVal::makeNotOwned(RE.getObjKind(),
2862 RetT));
2863 state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002864 break;
2865 }
2866 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002867
Ted Kremenek0dd65012009-02-18 02:00:25 +00002868 // Generate a sink node if we are at the end of a path.
2869 GRExprEngine::NodeTy *NewNode =
Ted Kremenek286e9852009-05-04 04:57:00 +00002870 Summ.isEndPath() ? Builder.MakeSinkNode(Dst, Ex, Pred, state)
2871 : Builder.MakeNode(Dst, Ex, Pred, state);
Ted Kremenek0dd65012009-02-18 02:00:25 +00002872
2873 // Annotate the edge with summary we used.
Ted Kremenek286e9852009-05-04 04:57:00 +00002874 if (NewNode) SummaryLog[NewNode] = &Summ;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002875}
2876
2877
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002878void CFRefCount::EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002879 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002880 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu097fc982008-10-17 05:57:07 +00002881 CallExpr* CE, SVal L,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002882 ExplodedNode<GRState>* Pred) {
Zhongxing Xucac107a2009-04-20 05:24:46 +00002883 const FunctionDecl* FD = L.getAsFunctionDecl();
Ted Kremenek286e9852009-05-04 04:57:00 +00002884 RetainSummary* Summ = !FD ? Summaries.getDefaultSummary()
Zhongxing Xucac107a2009-04-20 05:24:46 +00002885 : Summaries.getSummary(const_cast<FunctionDecl*>(FD));
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002886
Ted Kremenek286e9852009-05-04 04:57:00 +00002887 assert(Summ);
2888 EvalSummary(Dst, Eng, Builder, CE, 0, *Summ,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002889 CE->arg_begin(), CE->arg_end(), Pred);
Ted Kremenek827f93b2008-03-06 00:08:09 +00002890}
Ted Kremeneka7338b42008-03-11 06:39:11 +00002891
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002892void CFRefCount::EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002893 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002894 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002895 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002896 ExplodedNode<GRState>* Pred) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002897 RetainSummary* Summ = 0;
Ted Kremenek33661802008-05-01 21:31:50 +00002898
Ted Kremenek272aa852008-06-25 21:21:56 +00002899 if (Expr* Receiver = ME->getReceiver()) {
2900 // We need the type-information of the tracked receiver object
2901 // Retrieve it from the state.
2902 ObjCInterfaceDecl* ID = 0;
2903
2904 // FIXME: Wouldn't it be great if this code could be reduced? It's just
2905 // a chain of lookups.
Ted Kremeneka821b792009-04-29 05:04:30 +00002906 // FIXME: Is this really working as expected? There are cases where
2907 // we just use the 'ID' from the message expression.
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002908 const GRState* St = Builder.GetState(Pred);
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002909 SVal V = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
Ted Kremenek272aa852008-06-25 21:21:56 +00002910
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002911 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenek74556a12009-03-26 03:35:11 +00002912 if (Sym) {
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002913 if (const RefVal* T = St->get<RefBindings>(Sym)) {
Ted Kremenek6064a362008-07-07 16:21:19 +00002914 QualType Ty = T->getType();
Ted Kremenek272aa852008-06-25 21:21:56 +00002915
2916 if (const PointerType* PT = Ty->getAsPointerType()) {
2917 QualType PointeeTy = PT->getPointeeType();
2918
2919 if (ObjCInterfaceType* IT = dyn_cast<ObjCInterfaceType>(PointeeTy))
2920 ID = IT->getDecl();
2921 }
2922 }
2923 }
2924
Ted Kremenek04e00302009-04-29 17:09:14 +00002925 // FIXME: The receiver could be a reference to a class, meaning that
2926 // we should use the class method.
2927 Summ = Summaries.getInstanceMethodSummary(ME, ID);
Ted Kremenek0106e202008-10-24 20:32:50 +00002928
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002929 // Special-case: are we sending a mesage to "self"?
2930 // This is a hack. When we have full-IP this should be removed.
Ted Kremenek2f226732009-05-04 05:31:22 +00002931 if (isa<ObjCMethodDecl>(&Eng.getGraph().getCodeDecl())) {
2932 if (Expr* Receiver = ME->getReceiver()) {
2933 SVal X = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
2934 if (loc::MemRegionVal* L = dyn_cast<loc::MemRegionVal>(&X))
2935 if (L->getRegion() == Eng.getStateManager().getSelfRegion(St)) {
2936 // Update the summary to make the default argument effect
2937 // 'StopTracking'.
2938 Summ = Summaries.copySummary(Summ);
2939 Summ->setDefaultArgEffect(StopTracking);
2940 }
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002941 }
2942 }
Ted Kremenek272aa852008-06-25 21:21:56 +00002943 }
Ted Kremenek1feab292008-04-16 04:28:53 +00002944 else
Ted Kremenekb17fa952009-04-23 21:25:57 +00002945 Summ = Summaries.getClassMethodSummary(ME);
Ted Kremenek1feab292008-04-16 04:28:53 +00002946
Ted Kremenek286e9852009-05-04 04:57:00 +00002947 if (!Summ)
2948 Summ = Summaries.getDefaultSummary();
Ted Kremenekccbe79a2009-04-24 17:50:11 +00002949
Ted Kremenek286e9852009-05-04 04:57:00 +00002950 EvalSummary(Dst, Eng, Builder, ME, ME->getReceiver(), *Summ,
Ted Kremenek926abf22008-05-06 04:20:12 +00002951 ME->arg_begin(), ME->arg_end(), Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002952}
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002953
2954namespace {
2955class VISIBILITY_HIDDEN StopTrackingCallback : public SymbolVisitor {
2956 GRStateRef state;
2957public:
2958 StopTrackingCallback(GRStateRef st) : state(st) {}
2959 GRStateRef getState() { return state; }
2960
2961 bool VisitSymbol(SymbolRef sym) {
2962 state = state.remove<RefBindings>(sym);
2963 return true;
2964 }
Ted Kremenek926abf22008-05-06 04:20:12 +00002965
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002966 const GRState* getState() const { return state.getState(); }
2967};
2968} // end anonymous namespace
2969
2970
Ted Kremeneka42be302009-02-14 01:43:44 +00002971void CFRefCount::EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val) {
Ted Kremeneka42be302009-02-14 01:43:44 +00002972 // Are we storing to something that causes the value to "escape"?
Ted Kremenek7aef4842008-04-16 20:40:59 +00002973 bool escapes = false;
2974
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002975 // A value escapes in three possible cases (this may change):
2976 //
2977 // (1) we are binding to something that is not a memory region.
2978 // (2) we are binding to a memregion that does not have stack storage
2979 // (3) we are binding to a memregion with stack storage that the store
Ted Kremeneka42be302009-02-14 01:43:44 +00002980 // does not understand.
Ted Kremeneka42be302009-02-14 01:43:44 +00002981 GRStateRef state = B.getState();
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002982
Ted Kremeneka42be302009-02-14 01:43:44 +00002983 if (!isa<loc::MemRegionVal>(location))
Ted Kremenek7aef4842008-04-16 20:40:59 +00002984 escapes = true;
Ted Kremenekb15eba42008-10-04 05:50:14 +00002985 else {
Ted Kremeneka42be302009-02-14 01:43:44 +00002986 const MemRegion* R = cast<loc::MemRegionVal>(location).getRegion();
2987 escapes = !B.getStateManager().hasStackStorage(R);
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002988
2989 if (!escapes) {
2990 // To test (3), generate a new state with the binding removed. If it is
2991 // the same state, then it escapes (since the store cannot represent
2992 // the binding).
Ted Kremeneka42be302009-02-14 01:43:44 +00002993 escapes = (state == (state.BindLoc(cast<Loc>(location), UnknownVal())));
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002994 }
Ted Kremenekb15eba42008-10-04 05:50:14 +00002995 }
Ted Kremeneka42be302009-02-14 01:43:44 +00002996
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002997 // If our store can represent the binding and we aren't storing to something
2998 // that doesn't have local storage then just return and have the simulation
2999 // state continue as is.
3000 if (!escapes)
3001 return;
Ted Kremenek28d7eef2008-10-18 03:49:51 +00003002
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00003003 // Otherwise, find all symbols referenced by 'val' that we are tracking
3004 // and stop tracking them.
3005 B.MakeNode(state.scanReachableSymbols<StopTrackingCallback>(val).getState());
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00003006}
3007
Ted Kremenek541db372008-04-24 23:57:27 +00003008
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003009 // Return statements.
3010
Ted Kremenekabd89ac2008-08-13 04:27:00 +00003011void CFRefCount::EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003012 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00003013 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003014 ReturnStmt* S,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00003015 ExplodedNode<GRState>* Pred) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003016
3017 Expr* RetE = S->getRetValue();
Ted Kremenek9577c1e2009-03-03 22:06:47 +00003018 if (!RetE)
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003019 return;
3020
Ted Kremenek9577c1e2009-03-03 22:06:47 +00003021 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00003022 SymbolRef Sym = state.GetSValAsScalarOrLoc(RetE).getAsLocSymbol();
Ted Kremenek9577c1e2009-03-03 22:06:47 +00003023
Ted Kremenek74556a12009-03-26 03:35:11 +00003024 if (!Sym)
Ted Kremenek9577c1e2009-03-03 22:06:47 +00003025 return;
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003026
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003027 // Get the reference count binding (if any).
Ted Kremenek4ae925c2008-08-14 21:16:54 +00003028 const RefVal* T = state.get<RefBindings>(Sym);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003029
3030 if (!T)
3031 return;
3032
Ted Kremenek4ae925c2008-08-14 21:16:54 +00003033 // Change the reference count.
Ted Kremenek6064a362008-07-07 16:21:19 +00003034 RefVal X = *T;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003035
Ted Kremenek4ae925c2008-08-14 21:16:54 +00003036 switch (X.getKind()) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003037 case RefVal::Owned: {
3038 unsigned cnt = X.getCount();
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003039 assert (cnt > 0);
Ted Kremenekbd271be2009-05-10 05:11:21 +00003040 X.setCount(cnt - 1);
3041 X = X ^ RefVal::ReturnedOwned;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003042 break;
3043 }
3044
3045 case RefVal::NotOwned: {
3046 unsigned cnt = X.getCount();
Ted Kremenekbd271be2009-05-10 05:11:21 +00003047 if (cnt) {
3048 X.setCount(cnt - 1);
3049 X = X ^ RefVal::ReturnedOwned;
3050 }
3051 else {
3052 X = X ^ RefVal::ReturnedNotOwned;
3053 }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003054 break;
3055 }
3056
3057 default:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003058 return;
3059 }
3060
3061 // Update the binding.
Ted Kremenek91781202008-08-17 03:20:02 +00003062 state = state.set<RefBindings>(Sym, X);
Ted Kremenek47a72422009-04-29 18:50:19 +00003063 Pred = Builder.MakeNode(Dst, S, Pred, state);
3064
Ted Kremeneka208d0c2009-04-30 05:51:50 +00003065 // Did we cache out?
3066 if (!Pred)
3067 return;
Ted Kremenekbd271be2009-05-10 05:11:21 +00003068
3069 // Update the autorelease counts.
3070 static unsigned autoreleasetag = 0;
3071 GenericNodeBuilder Bd(Builder, S, &autoreleasetag);
3072 bool stop = false;
3073 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state , Bd, Pred, Eng, Sym,
3074 X, stop);
3075
3076 // Did we cache out?
3077 if (!Pred || stop)
3078 return;
3079
3080 // Get the updated binding.
3081 T = state.get<RefBindings>(Sym);
3082 assert(T);
3083 X = *T;
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003084
Ted Kremenek47a72422009-04-29 18:50:19 +00003085 // Any leaks or other errors?
3086 if (X.isReturnedOwned() && X.getCount() == 0) {
Ted Kremenekde92f7c2009-05-10 06:25:57 +00003087 const Decl *CD = &Eng.getStateManager().getCodeDecl();
Ted Kremenek314b1952009-04-29 23:03:22 +00003088 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00003089 const RetainSummary &Summ = *Summaries.getMethodSummary(MD);
Ted Kremenekde92f7c2009-05-10 06:25:57 +00003090 RetEffect RE = Summ.getRetEffect();
3091 bool hasError = false;
3092
3093 if (isGCEnabled() && RE.getObjKind() == RetEffect::ObjC) {
3094 // Things are more complicated with garbage collection. If the
3095 // returned object is suppose to be an Objective-C object, we have
Ted Kremenekeaea6582009-05-10 16:52:15 +00003096 // a leak (as the caller expects a GC'ed object) because no
3097 // method should return ownership unless it returns a CF object.
Ted Kremenekde92f7c2009-05-10 06:25:57 +00003098 X = X ^ RefVal::ErrorGCLeakReturned;
3099
3100 // Keep this false until this is properly tested.
Ted Kremenekeaea6582009-05-10 16:52:15 +00003101 hasError = true;
Ted Kremenekde92f7c2009-05-10 06:25:57 +00003102 }
3103 else if (!RE.isOwned()) {
3104 // Either we are using GC and the returned object is a CF type
3105 // or we aren't using GC. In either case, we expect that the
3106 // enclosing method is expected to return ownership.
3107 hasError = true;
3108 X = X ^ RefVal::ErrorLeakReturned;
3109 }
3110
3111 if (hasError) {
Ted Kremenek47a72422009-04-29 18:50:19 +00003112 // Generate an error node.
Ted Kremenekde92f7c2009-05-10 06:25:57 +00003113 static int ReturnOwnLeakTag = 0;
3114 state = state.set<RefBindings>(Sym, X);
3115 ExplodedNode<GRState> *N =
3116 Builder.generateNode(PostStmt(S, &ReturnOwnLeakTag), state, Pred);
3117 if (N) {
3118 CFRefReport *report =
Ted Kremeneka208d0c2009-04-30 05:51:50 +00003119 new CFRefLeakReport(*static_cast<CFRefBug*>(leakAtReturn), *this,
3120 N, Sym, Eng);
3121 BR->EmitReport(report);
3122 }
Ted Kremenek47a72422009-04-29 18:50:19 +00003123 }
Ted Kremenekde92f7c2009-05-10 06:25:57 +00003124 }
3125 }
3126 else if (X.isReturnedNotOwned()) {
3127 const Decl *CD = &Eng.getStateManager().getCodeDecl();
3128 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
3129 const RetainSummary &Summ = *Summaries.getMethodSummary(MD);
3130 if (Summ.getRetEffect().isOwned()) {
3131 // Trying to return a not owned object to a caller expecting an
3132 // owned object.
3133
3134 static int ReturnNotOwnedForOwnedTag = 0;
3135 state = state.set<RefBindings>(Sym, X ^ RefVal::ErrorReturnedNotOwned);
3136 if (ExplodedNode<GRState> *N =
3137 Builder.generateNode(PostStmt(S, &ReturnNotOwnedForOwnedTag),
3138 state, Pred)) {
3139 CFRefReport *report =
3140 new CFRefReport(*static_cast<CFRefBug*>(returnNotOwnedForOwned),
3141 *this, N, Sym);
3142 BR->EmitReport(report);
3143 }
3144 }
Ted Kremenek47a72422009-04-29 18:50:19 +00003145 }
3146 }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003147}
3148
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003149// Assumptions.
3150
Ted Kremenekabd89ac2008-08-13 04:27:00 +00003151const GRState* CFRefCount::EvalAssume(GRStateManager& VMgr,
3152 const GRState* St,
Zhongxing Xu097fc982008-10-17 05:57:07 +00003153 SVal Cond, bool Assumption,
Ted Kremenekf22f8682008-07-10 22:03:41 +00003154 bool& isFeasible) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003155
3156 // FIXME: We may add to the interface of EvalAssume the list of symbols
3157 // whose assumptions have changed. For now we just iterate through the
3158 // bindings and check if any of the tracked symbols are NULL. This isn't
3159 // too bad since the number of symbols we will track in practice are
3160 // probably small and EvalAssume is only called at branches and a few
3161 // other places.
Ted Kremenek4ae925c2008-08-14 21:16:54 +00003162 RefBindings B = St->get<RefBindings>();
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003163
3164 if (B.isEmpty())
3165 return St;
3166
3167 bool changed = false;
Ted Kremenek91781202008-08-17 03:20:02 +00003168
3169 GRStateRef state(St, VMgr);
3170 RefBindings::Factory& RefBFactory = state.get_context<RefBindings>();
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003171
3172 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003173 // Check if the symbol is null (or equal to any constant).
3174 // If this is the case, stop tracking the symbol.
Zhongxing Xuc6b27d02008-08-29 14:52:36 +00003175 if (VMgr.getSymVal(St, I.getKey())) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003176 changed = true;
3177 B = RefBFactory.Remove(B, I.getKey());
3178 }
3179 }
3180
Ted Kremenek91781202008-08-17 03:20:02 +00003181 if (changed)
3182 state = state.set<RefBindings>(B);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003183
Ted Kremenek4ae925c2008-08-14 21:16:54 +00003184 return state;
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003185}
Ted Kremeneka7338b42008-03-11 06:39:11 +00003186
Ted Kremenekb6578942009-02-24 19:15:11 +00003187GRStateRef CFRefCount::Update(GRStateRef state, SymbolRef sym,
3188 RefVal V, ArgEffect E,
3189 RefVal::Kind& hasErr) {
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003190
3191 // In GC mode [... release] and [... retain] do nothing.
3192 switch (E) {
3193 default: break;
3194 case IncRefMsg: E = isGCEnabled() ? DoNothing : IncRef; break;
3195 case DecRefMsg: E = isGCEnabled() ? DoNothing : DecRef; break;
Ted Kremenek2126bef2009-02-18 21:57:45 +00003196 case MakeCollectable: E = isGCEnabled() ? DecRef : DoNothing; break;
Ted Kremenekaac82832009-02-23 17:45:03 +00003197 case NewAutoreleasePool: E = isGCEnabled() ? DoNothing :
3198 NewAutoreleasePool; break;
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003199 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00003200
Ted Kremenek6537a642009-03-17 19:42:23 +00003201 // Handle all use-after-releases.
3202 if (!isGCEnabled() && V.getKind() == RefVal::Released) {
3203 V = V ^ RefVal::ErrorUseAfterRelease;
3204 hasErr = V.getKind();
3205 return state.set<RefBindings>(sym, V);
3206 }
3207
Ted Kremenek0d721572008-03-11 17:48:22 +00003208 switch (E) {
3209 default:
3210 assert (false && "Unhandled CFRef transition.");
Ted Kremenek6537a642009-03-17 19:42:23 +00003211
3212 case Dealloc:
3213 // Any use of -dealloc in GC is *bad*.
3214 if (isGCEnabled()) {
3215 V = V ^ RefVal::ErrorDeallocGC;
3216 hasErr = V.getKind();
3217 break;
3218 }
3219
3220 switch (V.getKind()) {
3221 default:
3222 assert(false && "Invalid case.");
3223 case RefVal::Owned:
3224 // The object immediately transitions to the released state.
3225 V = V ^ RefVal::Released;
3226 V.clearCounts();
3227 return state.set<RefBindings>(sym, V);
3228 case RefVal::NotOwned:
3229 V = V ^ RefVal::ErrorDeallocNotOwned;
3230 hasErr = V.getKind();
3231 break;
3232 }
3233 break;
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003234
Ted Kremenekb7826ab2009-02-25 23:11:49 +00003235 case NewAutoreleasePool:
3236 assert(!isGCEnabled());
3237 return state.add<AutoreleaseStack>(sym);
3238
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003239 case MayEscape:
3240 if (V.getKind() == RefVal::Owned) {
Ted Kremenek272aa852008-06-25 21:21:56 +00003241 V = V ^ RefVal::NotOwned;
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003242 break;
3243 }
Ted Kremenek6537a642009-03-17 19:42:23 +00003244
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003245 // Fall-through.
Ted Kremenek1b4b6562009-02-25 02:54:57 +00003246
Ted Kremenekede40b72008-07-09 18:11:16 +00003247 case DoNothingByRef:
Ted Kremenek0d721572008-03-11 17:48:22 +00003248 case DoNothing:
Ted Kremenekb6578942009-02-24 19:15:11 +00003249 return state;
Ted Kremeneke5a4bb02008-06-30 16:57:41 +00003250
Ted Kremenek9b112d22009-01-28 21:44:40 +00003251 case Autorelease:
Ted Kremenek6537a642009-03-17 19:42:23 +00003252 if (isGCEnabled())
3253 return state;
Ted Kremenek681fb352009-03-20 17:34:15 +00003254
3255 // Update the autorelease counts.
3256 state = SendAutorelease(state, ARCountFactory, sym);
Ted Kremenek4d99d342009-05-08 20:01:42 +00003257 V = V.autorelease();
Ted Kremenek3e3328d2009-05-09 01:50:57 +00003258 break;
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003259
Ted Kremenek227c5372008-05-06 02:41:27 +00003260 case StopTracking:
Ted Kremenekb6578942009-02-24 19:15:11 +00003261 return state.remove<RefBindings>(sym);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003262
Ted Kremenek0d721572008-03-11 17:48:22 +00003263 case IncRef:
3264 switch (V.getKind()) {
3265 default:
3266 assert(false);
3267
3268 case RefVal::Owned:
Ted Kremenek0d721572008-03-11 17:48:22 +00003269 case RefVal::NotOwned:
Ted Kremenek272aa852008-06-25 21:21:56 +00003270 V = V + 1;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003271 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003272 case RefVal::Released:
Ted Kremenek6537a642009-03-17 19:42:23 +00003273 // Non-GC cases are handled above.
3274 assert(isGCEnabled());
3275 V = (V ^ RefVal::Owned) + 1;
Ted Kremenek0d721572008-03-11 17:48:22 +00003276 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003277 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00003278 break;
3279
Ted Kremenek272aa852008-06-25 21:21:56 +00003280 case SelfOwn:
3281 V = V ^ RefVal::NotOwned;
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003282 // Fall-through.
Ted Kremenek0d721572008-03-11 17:48:22 +00003283 case DecRef:
3284 switch (V.getKind()) {
3285 default:
Ted Kremenek6537a642009-03-17 19:42:23 +00003286 // case 'RefVal::Released' handled above.
Ted Kremenek0d721572008-03-11 17:48:22 +00003287 assert (false);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003288
Ted Kremenek272aa852008-06-25 21:21:56 +00003289 case RefVal::Owned:
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00003290 assert(V.getCount() > 0);
3291 if (V.getCount() == 1) V = V ^ RefVal::Released;
3292 V = V - 1;
Ted Kremenek0d721572008-03-11 17:48:22 +00003293 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003294
Ted Kremenek272aa852008-06-25 21:21:56 +00003295 case RefVal::NotOwned:
3296 if (V.getCount() > 0)
3297 V = V - 1;
Ted Kremenekc4f81022008-04-10 23:09:18 +00003298 else {
Ted Kremenek272aa852008-06-25 21:21:56 +00003299 V = V ^ RefVal::ErrorReleaseNotOwned;
Ted Kremenek1feab292008-04-16 04:28:53 +00003300 hasErr = V.getKind();
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003301 }
Ted Kremenek0d721572008-03-11 17:48:22 +00003302 break;
Ted Kremenek6537a642009-03-17 19:42:23 +00003303
Ted Kremenek0d721572008-03-11 17:48:22 +00003304 case RefVal::Released:
Ted Kremenek6537a642009-03-17 19:42:23 +00003305 // Non-GC cases are handled above.
3306 assert(isGCEnabled());
Ted Kremenek272aa852008-06-25 21:21:56 +00003307 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek1feab292008-04-16 04:28:53 +00003308 hasErr = V.getKind();
Ted Kremenek6537a642009-03-17 19:42:23 +00003309 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003310 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00003311 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003312 }
Ted Kremenekb6578942009-02-24 19:15:11 +00003313 return state.set<RefBindings>(sym, V);
Ted Kremeneka7338b42008-03-11 06:39:11 +00003314}
3315
Ted Kremenek10fe66d2008-04-09 01:10:13 +00003316//===----------------------------------------------------------------------===//
Ted Kremenek708af042009-02-05 06:50:21 +00003317// Handle dead symbols and end-of-path.
3318//===----------------------------------------------------------------------===//
3319
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003320std::pair<ExplodedNode<GRState>*, GRStateRef>
3321CFRefCount::HandleAutoreleaseCounts(GRStateRef state, GenericNodeBuilder Bd,
3322 ExplodedNode<GRState>* Pred,
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003323 GRExprEngine &Eng,
3324 SymbolRef Sym, RefVal V, bool &stop) {
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003325
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003326 unsigned ACnt = V.getAutoreleaseCount();
3327 stop = false;
3328
3329 // No autorelease counts? Nothing to be done.
3330 if (!ACnt)
3331 return std::make_pair(Pred, state);
3332
3333 assert(!isGCEnabled() && "Autorelease counts in GC mode?");
3334 unsigned Cnt = V.getCount();
3335
Ted Kremenek0603cf52009-05-11 15:26:06 +00003336 // FIXME: Handle sending 'autorelease' to already released object.
3337
3338 if (V.getKind() == RefVal::ReturnedOwned)
3339 ++Cnt;
3340
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003341 if (ACnt <= Cnt) {
Ted Kremenek3f15aba2009-05-09 00:44:07 +00003342 if (ACnt == Cnt) {
3343 V.clearCounts();
Ted Kremenek0603cf52009-05-11 15:26:06 +00003344 if (V.getKind() == RefVal::ReturnedOwned)
3345 V = V ^ RefVal::ReturnedNotOwned;
3346 else
3347 V = V ^ RefVal::NotOwned;
Ted Kremenek3f15aba2009-05-09 00:44:07 +00003348 }
Ted Kremenek0603cf52009-05-11 15:26:06 +00003349 else {
Ted Kremenek3f15aba2009-05-09 00:44:07 +00003350 V.setCount(Cnt - ACnt);
3351 V.setAutoreleaseCount(0);
3352 }
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003353 state = state.set<RefBindings>(Sym, V);
3354 ExplodedNode<GRState> *N = Bd.MakeNode(state, Pred);
3355 stop = (N == 0);
3356 return std::make_pair(N, state);
3357 }
3358
3359 // Woah! More autorelease counts then retain counts left.
3360 // Emit hard error.
3361 stop = true;
3362 V = V ^ RefVal::ErrorOverAutorelease;
3363 state = state.set<RefBindings>(Sym, V);
3364
3365 if (ExplodedNode<GRState> *N = Bd.MakeNode(state, Pred)) {
Ted Kremenek3f15aba2009-05-09 00:44:07 +00003366 N->markAsSink();
Ted Kremenekbd271be2009-05-10 05:11:21 +00003367
3368 std::string sbuf;
3369 llvm::raw_string_ostream os(sbuf);
3370 os << "Object over-autoreleased: object was sent -autorelease " ;
3371 if (V.getAutoreleaseCount() > 1)
3372 os << V.getAutoreleaseCount() << " times";
3373 os << " but the object has ";
3374 if (V.getCount() == 0)
3375 os << "zero (locally visible)";
3376 else
3377 os << "+" << V.getCount();
3378 os << " retain counts";
3379
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003380 CFRefReport *report =
3381 new CFRefReport(*static_cast<CFRefBug*>(overAutorelease),
Ted Kremenekbd271be2009-05-10 05:11:21 +00003382 *this, N, Sym, os.str().c_str());
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003383 BR->EmitReport(report);
3384 }
3385
3386 return std::make_pair((ExplodedNode<GRState>*)0, state);
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003387}
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003388
3389GRStateRef
3390CFRefCount::HandleSymbolDeath(GRStateRef state, SymbolRef sid, RefVal V,
3391 llvm::SmallVectorImpl<SymbolRef> &Leaked) {
3392
3393 bool hasLeak = V.isOwned() ||
3394 ((V.isNotOwned() || V.isReturnedOwned()) && V.getCount() > 0);
3395
3396 if (!hasLeak)
3397 return state.remove<RefBindings>(sid);
3398
3399 Leaked.push_back(sid);
3400 return state.set<RefBindings>(sid, V ^ RefVal::ErrorLeak);
3401}
3402
3403ExplodedNode<GRState>*
3404CFRefCount::ProcessLeaks(GRStateRef state,
3405 llvm::SmallVectorImpl<SymbolRef> &Leaked,
3406 GenericNodeBuilder &Builder,
3407 GRExprEngine& Eng,
3408 ExplodedNode<GRState> *Pred) {
3409
3410 if (Leaked.empty())
3411 return Pred;
3412
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003413 // Generate an intermediate node representing the leak point.
Ted Kremenek3e3328d2009-05-09 01:50:57 +00003414 ExplodedNode<GRState> *N = Builder.MakeNode(state, Pred);
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003415
3416 if (N) {
3417 for (llvm::SmallVectorImpl<SymbolRef>::iterator
3418 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3419
3420 CFRefBug *BT = static_cast<CFRefBug*>(Pred ? leakWithinFunction
3421 : leakAtReturn);
3422 assert(BT && "BugType not initialized.");
3423 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N, *I, Eng);
3424 BR->EmitReport(report);
3425 }
3426 }
3427
3428 return N;
3429}
3430
Ted Kremenek708af042009-02-05 06:50:21 +00003431void CFRefCount::EvalEndPath(GRExprEngine& Eng,
3432 GREndPathNodeBuilder<GRState>& Builder) {
3433
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003434 GRStateRef state(Builder.getState(), Eng.getStateManager());
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003435 GenericNodeBuilder Bd(Builder);
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003436 RefBindings B = state.get<RefBindings>();
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003437 ExplodedNode<GRState> *Pred = 0;
3438
3439 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003440 bool stop = false;
3441 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state, Bd, Pred, Eng,
3442 (*I).first,
3443 (*I).second, stop);
3444
3445 if (stop)
3446 return;
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003447 }
3448
3449 B = state.get<RefBindings>();
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003450 llvm::SmallVector<SymbolRef, 10> Leaked;
Ted Kremenek708af042009-02-05 06:50:21 +00003451
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003452 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I)
3453 state = HandleSymbolDeath(state, (*I).first, (*I).second, Leaked);
3454
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003455 ProcessLeaks(state, Leaked, Bd, Eng, Pred);
Ted Kremenek708af042009-02-05 06:50:21 +00003456}
3457
3458void CFRefCount::EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
3459 GRExprEngine& Eng,
3460 GRStmtNodeBuilder<GRState>& Builder,
3461 ExplodedNode<GRState>* Pred,
3462 Stmt* S,
3463 const GRState* St,
3464 SymbolReaper& SymReaper) {
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003465
3466 GRStateRef state(St, Eng.getStateManager());
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003467 RefBindings B = state.get<RefBindings>();
3468
3469 // Update counts from autorelease pools
3470 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3471 E = SymReaper.dead_end(); I != E; ++I) {
3472 SymbolRef Sym = *I;
3473 if (const RefVal* T = B.lookup(Sym)){
3474 // Use the symbol as the tag.
3475 // FIXME: This might not be as unique as we would like.
3476 GenericNodeBuilder Bd(Builder, S, Sym);
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003477 bool stop = false;
3478 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state, Bd, Pred, Eng,
3479 Sym, *T, stop);
3480 if (stop)
3481 return;
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003482 }
3483 }
3484
3485 B = state.get<RefBindings>();
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003486 llvm::SmallVector<SymbolRef, 10> Leaked;
Ted Kremenek708af042009-02-05 06:50:21 +00003487
3488 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003489 E = SymReaper.dead_end(); I != E; ++I) {
3490 if (const RefVal* T = B.lookup(*I))
3491 state = HandleSymbolDeath(state, *I, *T, Leaked);
3492 }
Ted Kremenek708af042009-02-05 06:50:21 +00003493
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003494 static unsigned LeakPPTag = 0;
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003495 {
3496 GenericNodeBuilder Bd(Builder, S, &LeakPPTag);
3497 Pred = ProcessLeaks(state, Leaked, Bd, Eng, Pred);
3498 }
Ted Kremenek708af042009-02-05 06:50:21 +00003499
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003500 // Did we cache out?
3501 if (!Pred)
3502 return;
Ted Kremenek876d8df2009-02-19 23:47:02 +00003503
3504 // Now generate a new node that nukes the old bindings.
Ted Kremenek876d8df2009-02-19 23:47:02 +00003505 RefBindings::Factory& F = state.get_context<RefBindings>();
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003506
Ted Kremenek876d8df2009-02-19 23:47:02 +00003507 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003508 E = SymReaper.dead_end(); I!=E; ++I) B = F.Remove(B, *I);
3509
Ted Kremenek876d8df2009-02-19 23:47:02 +00003510 state = state.set<RefBindings>(B);
3511 Builder.MakeNode(Dst, S, Pred, state);
Ted Kremenek708af042009-02-05 06:50:21 +00003512}
3513
3514void CFRefCount::ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
3515 GRStmtNodeBuilder<GRState>& Builder,
3516 Expr* NodeExpr, Expr* ErrorExpr,
3517 ExplodedNode<GRState>* Pred,
3518 const GRState* St,
3519 RefVal::Kind hasErr, SymbolRef Sym) {
3520 Builder.BuildSinks = true;
3521 GRExprEngine::NodeTy* N = Builder.MakeNode(Dst, NodeExpr, Pred, St);
3522
Ted Kremenek3e3328d2009-05-09 01:50:57 +00003523 if (!N)
3524 return;
Ted Kremenek708af042009-02-05 06:50:21 +00003525
3526 CFRefBug *BT = 0;
3527
Ted Kremenek6537a642009-03-17 19:42:23 +00003528 switch (hasErr) {
3529 default:
3530 assert(false && "Unhandled error.");
3531 return;
3532 case RefVal::ErrorUseAfterRelease:
3533 BT = static_cast<CFRefBug*>(useAfterRelease);
3534 break;
3535 case RefVal::ErrorReleaseNotOwned:
3536 BT = static_cast<CFRefBug*>(releaseNotOwned);
3537 break;
3538 case RefVal::ErrorDeallocGC:
3539 BT = static_cast<CFRefBug*>(deallocGC);
3540 break;
3541 case RefVal::ErrorDeallocNotOwned:
3542 BT = static_cast<CFRefBug*>(deallocNotOwned);
3543 break;
Ted Kremenek708af042009-02-05 06:50:21 +00003544 }
3545
Ted Kremenekc26c4692009-02-18 03:48:14 +00003546 CFRefReport *report = new CFRefReport(*BT, *this, N, Sym);
Ted Kremenek708af042009-02-05 06:50:21 +00003547 report->addRange(ErrorExpr->getSourceRange());
3548 BR->EmitReport(report);
3549}
3550
3551//===----------------------------------------------------------------------===//
Ted Kremenekb1983ba2008-04-10 22:16:52 +00003552// Transfer function creation for external clients.
Ted Kremeneka7338b42008-03-11 06:39:11 +00003553//===----------------------------------------------------------------------===//
3554
Ted Kremenekfe30beb2008-04-30 23:47:44 +00003555GRTransferFuncs* clang::MakeCFRefCountTF(ASTContext& Ctx, bool GCEnabled,
3556 const LangOptions& lopts) {
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00003557 return new CFRefCount(Ctx, GCEnabled, lopts);
Ted Kremeneka4c74292008-04-10 22:58:08 +00003558}