blob: a9ef5cf3fcfda01f0cd1dc0e22d8bd9ff516178c [file] [log] [blame]
Chris Lattnerbda0b622008-03-15 23:59:48 +00001// CFRefCount.cpp - Transfer functions for tracking simple values -*- C++ -*--//
Ted Kremenek2fff37e2008-03-06 00:08:09 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Gabor Greif843e9342008-03-06 10:40:09 +000010// This file defines the methods for CFRefCount, which implements
Ted Kremenek2fff37e2008-03-06 00:08:09 +000011// a reference count checker for Core Foundation (Mac OS X).
12//
13//===----------------------------------------------------------------------===//
14
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000015#include "GRSimpleVals.h"
Ted Kremenek072192b2008-04-30 23:47:44 +000016#include "clang/Basic/LangOptions.h"
Ted Kremenekc9fa2f72008-05-01 23:13:35 +000017#include "clang/Basic/SourceManager.h"
Ted Kremenek41573eb2009-02-14 01:43:44 +000018#include "clang/Analysis/PathSensitive/GRExprEngineBuilders.h"
Ted Kremenekb9d17f92008-08-17 03:20:02 +000019#include "clang/Analysis/PathSensitive/GRStateTrait.h"
Ted Kremenek4dc41cc2008-03-31 18:26:32 +000020#include "clang/Analysis/PathDiagnostic.h"
Ted Kremenek2fff37e2008-03-06 00:08:09 +000021#include "clang/Analysis/LocalCheckers.h"
Ted Kremenekfa34b332008-04-09 01:10:13 +000022#include "clang/Analysis/PathDiagnostic.h"
23#include "clang/Analysis/PathSensitive/BugReporter.h"
Ted Kremenek5216ad72009-02-14 03:16:10 +000024#include "clang/Analysis/PathSensitive/SymbolManager.h"
Ted Kremenek8966bc12009-05-06 21:39:49 +000025#include "clang/AST/DeclObjC.h"
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000026#include "llvm/ADT/DenseMap.h"
27#include "llvm/ADT/FoldingSet.h"
28#include "llvm/ADT/ImmutableMap.h"
Ted Kremenek6d348932008-10-21 15:53:15 +000029#include "llvm/ADT/ImmutableList.h"
Ted Kremenek900a2d72008-05-07 18:36:45 +000030#include "llvm/ADT/StringExtras.h"
Ted Kremenekfa34b332008-04-09 01:10:13 +000031#include "llvm/Support/Compiler.h"
Ted Kremenek6ed9afc2008-05-16 18:33:44 +000032#include "llvm/ADT/STLExtras.h"
Ted Kremenekf3948042008-03-11 19:44:10 +000033#include <ostream>
Ted Kremenek98530452008-08-12 20:41:56 +000034#include <stdarg.h>
Ted Kremenek2fff37e2008-03-06 00:08:09 +000035
36using namespace clang;
Ted Kremenek5c74d502008-10-24 21:18:08 +000037
38//===----------------------------------------------------------------------===//
39// Utility functions.
40//===----------------------------------------------------------------------===//
41
Ted Kremenek5c74d502008-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 Kremenekb80976c2009-02-21 05:13:43 +000054
55using llvm::CStrInCStrNoCase;
Ted Kremenek39868cd2009-02-21 18:26:02 +000056using llvm::StringsEqualNoCase;
Ted Kremenekb80976c2009-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 Kremenek39868cd2009-02-21 18:26:02 +0000116 if (AtBeginning && StringsEqualNoCase("new", s, len))
Ted Kremenekb80976c2009-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 Kremenek8be2a672009-03-13 20:27:06 +0000122 if (C == NoConvention && StringsEqualNoCase("copy", s, len))
Ted Kremenekb80976c2009-02-21 05:13:43 +0000123 C = CreateRule;
124 else // Methods starting with 'init' follow the init rule.
Ted Kremenek39868cd2009-02-21 18:26:02 +0000125 if (AtBeginning && StringsEqualNoCase("init", s, len))
Ted Kremenek8be2a672009-03-13 20:27:06 +0000126 C = InitRule;
127 break;
128 case 5:
129 if (AtBeginning && StringsEqualNoCase("alloc", s, len))
130 C = CreateRule;
Ted Kremenekb80976c2009-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 Kremenek5c74d502008-10-24 21:18:08 +0000148static bool followsFundamentalRule(const char* s) {
Ted Kremenekb80976c2009-02-21 05:13:43 +0000149 return deriveNamingConvention(s) == CreateRule;
Ted Kremenek4c79e552008-11-05 16:54:44 +0000150}
151
Ted Kremeneka8833552009-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 Kremenek4c79e552008-11-05 16:54:44 +0000160}
Ted Kremenek5c74d502008-10-24 21:18:08 +0000161
Ted Kremenek9d9d3a62009-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 Kremenek6b62ec92009-05-09 01:50:57 +0000178 return SNB->generateNode(PostStmt(S, tag), state, Pred);
Ted Kremenek9d9d3a62009-05-08 23:09:42 +0000179
180 assert(ENB);
Ted Kremenek80c24182009-05-09 00:44:07 +0000181 return ENB->generateNode(state, Pred);
Ted Kremenek9d9d3a62009-05-08 23:09:42 +0000182 }
183};
184} // end anonymous namespace
185
Ted Kremenek05cbe1a2008-04-09 23:49:11 +0000186//===----------------------------------------------------------------------===//
Ted Kremenek553cf182008-06-25 21:21:56 +0000187// Selector creation functions.
Ted Kremenek4fd88972008-04-17 18:12:53 +0000188//===----------------------------------------------------------------------===//
189
Ted Kremenekb83e02e2008-05-01 18:31:44 +0000190static inline Selector GetNullarySelector(const char* name, ASTContext& Ctx) {
Ted Kremenek4fd88972008-04-17 18:12:53 +0000191 IdentifierInfo* II = &Ctx.Idents.get(name);
192 return Ctx.Selectors.getSelector(0, &II);
193}
194
Ted Kremenek9c32d082008-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 Kremenek553cf182008-06-25 21:21:56 +0000200//===----------------------------------------------------------------------===//
201// Type querying functions.
202//===----------------------------------------------------------------------===//
203
Ted Kremenek12619382009-01-12 21:45:02 +0000204static bool hasPrefix(const char* s, const char* prefix) {
205 if (!prefix)
206 return true;
Ted Kremenek0fcbf8e2008-05-07 20:06:41 +0000207
Ted Kremenek12619382009-01-12 21:45:02 +0000208 char c = *s;
209 char cP = *prefix;
Ted Kremenek0fcbf8e2008-05-07 20:06:41 +0000210
Ted Kremenek12619382009-01-12 21:45:02 +0000211 while (c != '\0' && cP != '\0') {
212 if (c != cP) break;
213 c = *(++s);
214 cP = *(++prefix);
215 }
Ted Kremenek0fcbf8e2008-05-07 20:06:41 +0000216
Ted Kremenek12619382009-01-12 21:45:02 +0000217 return cP == '\0';
Ted Kremenek0fcbf8e2008-05-07 20:06:41 +0000218}
219
Ted Kremenek12619382009-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 Kremenek37d785b2008-07-15 16:50:12 +0000227
Ted Kremenek12619382009-01-12 21:45:02 +0000228 if (TypedefType* TD = dyn_cast<TypedefType>(RetTy.getTypePtr())) {
229 const char* TDName = TD->getDecl()->getIdentifier()->getName();
230 return hasPrefix(TDName, prefix) && hasSuffix(TDName, "Ref");
231 }
232
233 if (!Ctx || !name)
Ted Kremenek37d785b2008-07-15 16:50:12 +0000234 return false;
Ted Kremenek12619382009-01-12 21:45:02 +0000235
236 // Is the type void*?
237 const PointerType* PT = RetTy->getAsPointerType();
238 if (!(PT->getPointeeType().getUnqualifiedType() == Ctx->VoidTy))
Ted Kremenek37d785b2008-07-15 16:50:12 +0000239 return false;
Ted Kremenek12619382009-01-12 21:45:02 +0000240
241 // Does the name start with the prefix?
242 return hasPrefix(name, prefix);
Ted Kremenek37d785b2008-07-15 16:50:12 +0000243}
244
Ted Kremenek4fd88972008-04-17 18:12:53 +0000245//===----------------------------------------------------------------------===//
Ted Kremenek553cf182008-06-25 21:21:56 +0000246// Primitives used for constructing summaries for function/method calls.
Ted Kremenek05cbe1a2008-04-09 23:49:11 +0000247//===----------------------------------------------------------------------===//
248
Ted Kremenek553cf182008-06-25 21:21:56 +0000249/// ArgEffect is used to summarize a function/method call's effect on a
250/// particular argument.
Ted Kremenekf95e9fc2009-03-17 19:42:23 +0000251enum ArgEffect { Autorelease, Dealloc, DecRef, DecRefMsg, DoNothing,
252 DoNothingByRef, IncRefMsg, IncRef, MakeCollectable, MayEscape,
253 NewAutoreleasePool, SelfOwn, StopTracking };
Ted Kremenek553cf182008-06-25 21:21:56 +0000254
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000255namespace llvm {
Ted Kremenekb77449c2009-05-03 05:20:50 +0000256template <> struct FoldingSetTrait<ArgEffect> {
257static inline void Profile(const ArgEffect X, FoldingSetNodeID& ID) {
258 ID.AddInteger((unsigned) X);
259}
Ted Kremenek553cf182008-06-25 21:21:56 +0000260};
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000261} // end llvm namespace
262
Ted Kremenekb77449c2009-05-03 05:20:50 +0000263/// ArgEffects summarizes the effects of a function/method call on all of
264/// its arguments.
265typedef llvm::ImmutableMap<unsigned,ArgEffect> ArgEffects;
266
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000267namespace {
Ted Kremenek553cf182008-06-25 21:21:56 +0000268
269/// RetEffect is used to summarize a function/method call's behavior with
270/// respect to its return value.
271class VISIBILITY_HIDDEN RetEffect {
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000272public:
Ted Kremeneka7344702008-06-23 18:02:52 +0000273 enum Kind { NoRet, Alias, OwnedSymbol, OwnedAllocatedSymbol,
Ted Kremeneke798e7c2009-04-27 19:14:45 +0000274 NotOwnedSymbol, GCNotOwnedSymbol, ReceiverAlias };
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000275
276 enum ObjKind { CF, ObjC, AnyObj };
277
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000278private:
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000279 Kind K;
280 ObjKind O;
281 unsigned index;
282
283 RetEffect(Kind k, unsigned idx = 0) : K(k), O(AnyObj), index(idx) {}
284 RetEffect(Kind k, ObjKind o) : K(k), O(o), index(0) {}
Ted Kremenek2fff37e2008-03-06 00:08:09 +0000285
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000286public:
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000287 Kind getKind() const { return K; }
288
289 ObjKind getObjKind() const { return O; }
Ted Kremenek553cf182008-06-25 21:21:56 +0000290
291 unsigned getIndex() const {
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000292 assert(getKind() == Alias);
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000293 return index;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000294 }
Ted Kremenek2fff37e2008-03-06 00:08:09 +0000295
Ted Kremeneka8833552009-04-29 23:03:22 +0000296 bool isOwned() const {
297 return K == OwnedSymbol || K == OwnedAllocatedSymbol;
298 }
299
Ted Kremenek553cf182008-06-25 21:21:56 +0000300 static RetEffect MakeAlias(unsigned Idx) {
301 return RetEffect(Alias, Idx);
302 }
303 static RetEffect MakeReceiverAlias() {
304 return RetEffect(ReceiverAlias);
305 }
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000306 static RetEffect MakeOwned(ObjKind o, bool isAllocated = false) {
307 return RetEffect(isAllocated ? OwnedAllocatedSymbol : OwnedSymbol, o);
Ted Kremenek553cf182008-06-25 21:21:56 +0000308 }
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000309 static RetEffect MakeNotOwned(ObjKind o) {
310 return RetEffect(NotOwnedSymbol, o);
Ted Kremeneke798e7c2009-04-27 19:14:45 +0000311 }
312 static RetEffect MakeGCNotOwned() {
313 return RetEffect(GCNotOwnedSymbol, ObjC);
314 }
315
Ted Kremenek553cf182008-06-25 21:21:56 +0000316 static RetEffect MakeNoRet() {
317 return RetEffect(NoRet);
Ted Kremeneka7344702008-06-23 18:02:52 +0000318 }
Ted Kremenek2fff37e2008-03-06 00:08:09 +0000319
Ted Kremenek553cf182008-06-25 21:21:56 +0000320 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000321 ID.AddInteger((unsigned)K);
322 ID.AddInteger((unsigned)O);
323 ID.AddInteger(index);
Ted Kremenek553cf182008-06-25 21:21:56 +0000324 }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000325};
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000326
Ted Kremenek553cf182008-06-25 21:21:56 +0000327
Ted Kremenek885c27b2009-05-04 05:31:22 +0000328class VISIBILITY_HIDDEN RetainSummary {
Ted Kremenek1bffd742008-05-06 15:44:25 +0000329 /// Args - an ordered vector of (index, ArgEffect) pairs, where index
330 /// specifies the argument (starting from 0). This can be sparsely
331 /// populated; arguments with no entry in Args use 'DefaultArgEffect'.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000332 ArgEffects Args;
Ted Kremenek1bffd742008-05-06 15:44:25 +0000333
334 /// DefaultArgEffect - The default ArgEffect to apply to arguments that
335 /// do not have an entry in Args.
336 ArgEffect DefaultArgEffect;
337
Ted Kremenek553cf182008-06-25 21:21:56 +0000338 /// Receiver - If this summary applies to an Objective-C message expression,
339 /// this is the effect applied to the state of the receiver.
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000340 ArgEffect Receiver;
Ted Kremenek553cf182008-06-25 21:21:56 +0000341
342 /// Ret - The effect on the return value. Used to indicate if the
343 /// function/method call returns a new tracked symbol, returns an
344 /// alias of one of the arguments in the call, and so on.
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000345 RetEffect Ret;
Ted Kremenek553cf182008-06-25 21:21:56 +0000346
Ted Kremenek70a733e2008-07-18 17:24:20 +0000347 /// EndPath - Indicates that execution of this method/function should
348 /// terminate the simulation of a path.
349 bool EndPath;
350
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000351public:
Ted Kremenekb77449c2009-05-03 05:20:50 +0000352 RetainSummary(ArgEffects A, RetEffect R, ArgEffect defaultEff,
Ted Kremenek70a733e2008-07-18 17:24:20 +0000353 ArgEffect ReceiverEff, bool endpath = false)
354 : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R),
355 EndPath(endpath) {}
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000356
Ted Kremenek553cf182008-06-25 21:21:56 +0000357 /// getArg - Return the argument effect on the argument specified by
358 /// idx (starting from 0).
Ted Kremenek1ac08d62008-03-11 17:48:22 +0000359 ArgEffect getArg(unsigned idx) const {
Ted Kremenekb77449c2009-05-03 05:20:50 +0000360 if (const ArgEffect *AE = Args.lookup(idx))
361 return *AE;
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000362
Ted Kremenek1bffd742008-05-06 15:44:25 +0000363 return DefaultArgEffect;
Ted Kremenek1ac08d62008-03-11 17:48:22 +0000364 }
365
Ted Kremenek885c27b2009-05-04 05:31:22 +0000366 /// setDefaultArgEffect - Set the default argument effect.
367 void setDefaultArgEffect(ArgEffect E) {
368 DefaultArgEffect = E;
369 }
370
371 /// setArg - Set the argument effect on the argument specified by idx.
372 void setArgEffect(ArgEffects::Factory& AF, unsigned idx, ArgEffect E) {
373 Args = AF.Add(Args, idx, E);
374 }
375
Ted Kremenek553cf182008-06-25 21:21:56 +0000376 /// getRetEffect - Returns the effect on the return value of the call.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000377 RetEffect getRetEffect() const { return Ret; }
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000378
Ted Kremenek885c27b2009-05-04 05:31:22 +0000379 /// setRetEffect - Set the effect of the return value of the call.
380 void setRetEffect(RetEffect E) { Ret = E; }
381
Ted Kremenek70a733e2008-07-18 17:24:20 +0000382 /// isEndPath - Returns true if executing the given method/function should
383 /// terminate the path.
384 bool isEndPath() const { return EndPath; }
385
Ted Kremenek553cf182008-06-25 21:21:56 +0000386 /// getReceiverEffect - Returns the effect on the receiver of the call.
387 /// This is only meaningful if the summary applies to an ObjCMessageExpr*.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000388 ArgEffect getReceiverEffect() const { return Receiver; }
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000389
Ted Kremenek885c27b2009-05-04 05:31:22 +0000390 /// setReceiverEffect - Set the effect on the receiver of the call.
391 void setReceiverEffect(ArgEffect E) { Receiver = E; }
392
Ted Kremenekb77449c2009-05-03 05:20:50 +0000393 typedef ArgEffects::iterator ExprIterator;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000394
Ted Kremenekb77449c2009-05-03 05:20:50 +0000395 ExprIterator begin_args() const { return Args.begin(); }
396 ExprIterator end_args() const { return Args.end(); }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000397
Ted Kremenekb77449c2009-05-03 05:20:50 +0000398 static void Profile(llvm::FoldingSetNodeID& ID, ArgEffects A,
Ted Kremenek1bffd742008-05-06 15:44:25 +0000399 RetEffect RetEff, ArgEffect DefaultEff,
Ted Kremenek2d1086c2008-07-18 17:39:56 +0000400 ArgEffect ReceiverEff, bool EndPath) {
Ted Kremenekb77449c2009-05-03 05:20:50 +0000401 ID.Add(A);
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000402 ID.Add(RetEff);
Ted Kremenek1bffd742008-05-06 15:44:25 +0000403 ID.AddInteger((unsigned) DefaultEff);
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000404 ID.AddInteger((unsigned) ReceiverEff);
Ted Kremenek2d1086c2008-07-18 17:39:56 +0000405 ID.AddInteger((unsigned) EndPath);
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000406 }
407
408 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek2d1086c2008-07-18 17:39:56 +0000409 Profile(ID, Args, Ret, DefaultArgEffect, Receiver, EndPath);
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000410 }
411};
Ted Kremenek4f22a782008-06-23 23:30:29 +0000412} // end anonymous namespace
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000413
Ted Kremenek553cf182008-06-25 21:21:56 +0000414//===----------------------------------------------------------------------===//
415// Data structures for constructing summaries.
416//===----------------------------------------------------------------------===//
Ted Kremenek53301ba2008-06-24 03:49:48 +0000417
Ted Kremenek553cf182008-06-25 21:21:56 +0000418namespace {
419class VISIBILITY_HIDDEN ObjCSummaryKey {
420 IdentifierInfo* II;
421 Selector S;
422public:
423 ObjCSummaryKey(IdentifierInfo* ii, Selector s)
424 : II(ii), S(s) {}
425
Ted Kremeneka8833552009-04-29 23:03:22 +0000426 ObjCSummaryKey(const ObjCInterfaceDecl* d, Selector s)
Ted Kremenek553cf182008-06-25 21:21:56 +0000427 : II(d ? d->getIdentifier() : 0), S(s) {}
428
429 ObjCSummaryKey(Selector s)
430 : II(0), S(s) {}
431
432 IdentifierInfo* getIdentifier() const { return II; }
433 Selector getSelector() const { return S; }
434};
Ted Kremenek4f22a782008-06-23 23:30:29 +0000435}
436
437namespace llvm {
Ted Kremenek553cf182008-06-25 21:21:56 +0000438template <> struct DenseMapInfo<ObjCSummaryKey> {
439 static inline ObjCSummaryKey getEmptyKey() {
440 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
441 DenseMapInfo<Selector>::getEmptyKey());
442 }
Ted Kremenek4f22a782008-06-23 23:30:29 +0000443
Ted Kremenek553cf182008-06-25 21:21:56 +0000444 static inline ObjCSummaryKey getTombstoneKey() {
445 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
446 DenseMapInfo<Selector>::getTombstoneKey());
447 }
448
449 static unsigned getHashValue(const ObjCSummaryKey &V) {
450 return (DenseMapInfo<IdentifierInfo*>::getHashValue(V.getIdentifier())
451 & 0x88888888)
452 | (DenseMapInfo<Selector>::getHashValue(V.getSelector())
453 & 0x55555555);
454 }
455
456 static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
457 return DenseMapInfo<IdentifierInfo*>::isEqual(LHS.getIdentifier(),
458 RHS.getIdentifier()) &&
459 DenseMapInfo<Selector>::isEqual(LHS.getSelector(),
460 RHS.getSelector());
461 }
462
463 static bool isPod() {
464 return DenseMapInfo<ObjCInterfaceDecl*>::isPod() &&
465 DenseMapInfo<Selector>::isPod();
466 }
467};
Ted Kremenek4f22a782008-06-23 23:30:29 +0000468} // end llvm namespace
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000469
Ted Kremenek4f22a782008-06-23 23:30:29 +0000470namespace {
Ted Kremenek553cf182008-06-25 21:21:56 +0000471class VISIBILITY_HIDDEN ObjCSummaryCache {
472 typedef llvm::DenseMap<ObjCSummaryKey, RetainSummary*> MapTy;
473 MapTy M;
474public:
475 ObjCSummaryCache() {}
476
477 typedef MapTy::iterator iterator;
478
Ted Kremeneka8833552009-04-29 23:03:22 +0000479 iterator find(const ObjCInterfaceDecl* D, IdentifierInfo *ClsName,
480 Selector S) {
Ted Kremenek8711c032009-04-29 05:04:30 +0000481 // Lookup the method using the decl for the class @interface. If we
482 // have no decl, lookup using the class name.
483 return D ? find(D, S) : find(ClsName, S);
484 }
485
Ted Kremeneka8833552009-04-29 23:03:22 +0000486 iterator find(const ObjCInterfaceDecl* D, Selector S) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000487 // Do a lookup with the (D,S) pair. If we find a match return
488 // the iterator.
489 ObjCSummaryKey K(D, S);
490 MapTy::iterator I = M.find(K);
491
492 if (I != M.end() || !D)
493 return I;
494
495 // Walk the super chain. If we find a hit with a parent, we'll end
496 // up returning that summary. We actually allow that key (null,S), as
497 // we cache summaries for the null ObjCInterfaceDecl* to allow us to
498 // generate initial summaries without having to worry about NSObject
499 // being declared.
500 // FIXME: We may change this at some point.
501 for (ObjCInterfaceDecl* C=D->getSuperClass() ;; C=C->getSuperClass()) {
502 if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
503 break;
504
505 if (!C)
506 return I;
507 }
508
509 // Cache the summary with original key to make the next lookup faster
510 // and return the iterator.
511 M[K] = I->second;
512 return I;
513 }
514
Ted Kremenek98530452008-08-12 20:41:56 +0000515
Ted Kremenek553cf182008-06-25 21:21:56 +0000516 iterator find(Expr* Receiver, Selector S) {
517 return find(getReceiverDecl(Receiver), S);
518 }
519
520 iterator find(IdentifierInfo* II, Selector S) {
521 // FIXME: Class method lookup. Right now we dont' have a good way
522 // of going between IdentifierInfo* and the class hierarchy.
523 iterator I = M.find(ObjCSummaryKey(II, S));
524 return I == M.end() ? M.find(ObjCSummaryKey(S)) : I;
525 }
526
527 ObjCInterfaceDecl* getReceiverDecl(Expr* E) {
528
529 const PointerType* PT = E->getType()->getAsPointerType();
530 if (!PT) return 0;
531
532 ObjCInterfaceType* OI = dyn_cast<ObjCInterfaceType>(PT->getPointeeType());
533 if (!OI) return 0;
534
535 return OI ? OI->getDecl() : 0;
536 }
537
538 iterator end() { return M.end(); }
539
540 RetainSummary*& operator[](ObjCMessageExpr* ME) {
541
542 Selector S = ME->getSelector();
543
544 if (Expr* Receiver = ME->getReceiver()) {
545 ObjCInterfaceDecl* OD = getReceiverDecl(Receiver);
546 return OD ? M[ObjCSummaryKey(OD->getIdentifier(), S)] : M[S];
547 }
548
549 return M[ObjCSummaryKey(ME->getClassName(), S)];
550 }
551
552 RetainSummary*& operator[](ObjCSummaryKey K) {
553 return M[K];
554 }
555
556 RetainSummary*& operator[](Selector S) {
557 return M[ ObjCSummaryKey(S) ];
558 }
559};
560} // end anonymous namespace
561
562//===----------------------------------------------------------------------===//
563// Data structures for managing collections of summaries.
564//===----------------------------------------------------------------------===//
565
566namespace {
567class VISIBILITY_HIDDEN RetainSummaryManager {
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000568
569 //==-----------------------------------------------------------------==//
570 // Typedefs.
571 //==-----------------------------------------------------------------==//
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000572
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000573 typedef llvm::DenseMap<FunctionDecl*, RetainSummary*>
574 FuncSummariesTy;
575
Ted Kremenek4f22a782008-06-23 23:30:29 +0000576 typedef ObjCSummaryCache ObjCMethodSummariesTy;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000577
578 //==-----------------------------------------------------------------==//
579 // Data.
580 //==-----------------------------------------------------------------==//
581
Ted Kremenek553cf182008-06-25 21:21:56 +0000582 /// Ctx - The ASTContext object for the analyzed ASTs.
Ted Kremenek377e2302008-04-29 05:33:51 +0000583 ASTContext& Ctx;
Ted Kremenek179064e2008-07-01 17:21:27 +0000584
Ted Kremenek070a8252008-07-09 18:11:16 +0000585 /// CFDictionaryCreateII - An IdentifierInfo* representing the indentifier
586 /// "CFDictionaryCreate".
587 IdentifierInfo* CFDictionaryCreateII;
588
Ted Kremenek553cf182008-06-25 21:21:56 +0000589 /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
Ted Kremenek377e2302008-04-29 05:33:51 +0000590 const bool GCEnabled;
Ted Kremenek22fe2482009-05-04 04:30:18 +0000591
Ted Kremenek553cf182008-06-25 21:21:56 +0000592 /// FuncSummaries - A map from FunctionDecls to summaries.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000593 FuncSummariesTy FuncSummaries;
594
Ted Kremenek553cf182008-06-25 21:21:56 +0000595 /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
596 /// to summaries.
Ted Kremenek1f180c32008-06-23 22:21:20 +0000597 ObjCMethodSummariesTy ObjCClassMethodSummaries;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000598
Ted Kremenek553cf182008-06-25 21:21:56 +0000599 /// ObjCMethodSummaries - A map from selectors to summaries.
Ted Kremenek1f180c32008-06-23 22:21:20 +0000600 ObjCMethodSummariesTy ObjCMethodSummaries;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000601
Ted Kremenek553cf182008-06-25 21:21:56 +0000602 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
603 /// and all other data used by the checker.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000604 llvm::BumpPtrAllocator BPAlloc;
605
Ted Kremenekb77449c2009-05-03 05:20:50 +0000606 /// AF - A factory for ArgEffects objects.
607 ArgEffects::Factory AF;
608
Ted Kremenek553cf182008-06-25 21:21:56 +0000609 /// ScratchArgs - A holding buffer for construct ArgEffects.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000610 ArgEffects ScratchArgs;
611
Ted Kremenekec315332009-05-07 23:40:42 +0000612 /// ObjCAllocRetE - Default return effect for methods returning Objective-C
613 /// objects.
614 RetEffect ObjCAllocRetE;
615
Ted Kremenek7faca822009-05-04 04:57:00 +0000616 RetainSummary DefaultSummary;
Ted Kremenek432af592008-05-06 18:11:36 +0000617 RetainSummary* StopSummary;
618
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000619 //==-----------------------------------------------------------------==//
620 // Methods.
621 //==-----------------------------------------------------------------==//
622
Ted Kremenek553cf182008-06-25 21:21:56 +0000623 /// getArgEffects - Returns a persistent ArgEffects object based on the
624 /// data in ScratchArgs.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000625 ArgEffects getArgEffects();
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000626
Ted Kremenek86ad3bc2008-05-05 16:51:50 +0000627 enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
Ted Kremenek896cd9d2008-10-23 01:56:15 +0000628
629public:
Ted Kremenek885c27b2009-05-04 05:31:22 +0000630 RetainSummary *getDefaultSummary() {
631 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
632 return new (Summ) RetainSummary(DefaultSummary);
633 }
Ted Kremenek7faca822009-05-04 04:57:00 +0000634
Ted Kremenek6ad315a2009-02-23 16:51:39 +0000635 RetainSummary* getUnarySummary(const FunctionType* FT, UnaryFuncKind func);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000636
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000637 RetainSummary* getCFSummaryCreateRule(FunctionDecl* FD);
638 RetainSummary* getCFSummaryGetRule(FunctionDecl* FD);
Ted Kremenek12619382009-01-12 21:45:02 +0000639 RetainSummary* getCFCreateGetRuleSummary(FunctionDecl* FD, const char* FName);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000640
Ted Kremenekb77449c2009-05-03 05:20:50 +0000641 RetainSummary* getPersistentSummary(ArgEffects AE, RetEffect RetEff,
Ted Kremenek1bffd742008-05-06 15:44:25 +0000642 ArgEffect ReceiverEff = DoNothing,
Ted Kremenek70a733e2008-07-18 17:24:20 +0000643 ArgEffect DefaultEff = MayEscape,
644 bool isEndPath = false);
Ted Kremenek706522f2008-10-29 04:07:07 +0000645
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000646 RetainSummary* getPersistentSummary(RetEffect RE,
Ted Kremenek1bffd742008-05-06 15:44:25 +0000647 ArgEffect ReceiverEff = DoNothing,
Ted Kremenek3eabf1c2008-05-22 17:31:13 +0000648 ArgEffect DefaultEff = MayEscape) {
Ted Kremenek1bffd742008-05-06 15:44:25 +0000649 return getPersistentSummary(getArgEffects(), RE, ReceiverEff, DefaultEff);
Ted Kremenek9c32d082008-05-06 00:30:21 +0000650 }
Ted Kremenek46e49ee2008-05-05 23:55:01 +0000651
Ted Kremenek8711c032009-04-29 05:04:30 +0000652 RetainSummary *getPersistentStopSummary() {
Ted Kremenek432af592008-05-06 18:11:36 +0000653 if (StopSummary)
654 return StopSummary;
655
656 StopSummary = getPersistentSummary(RetEffect::MakeNoRet(),
657 StopTracking, StopTracking);
Ted Kremenek706522f2008-10-29 04:07:07 +0000658
Ted Kremenek432af592008-05-06 18:11:36 +0000659 return StopSummary;
Ted Kremenek1bffd742008-05-06 15:44:25 +0000660 }
Ted Kremenekb3095252008-05-06 04:20:12 +0000661
Ted Kremenek8711c032009-04-29 05:04:30 +0000662 RetainSummary *getInitMethodSummary(QualType RetTy);
Ted Kremenek46e49ee2008-05-05 23:55:01 +0000663
Ted Kremenek1f180c32008-06-23 22:21:20 +0000664 void InitializeClassMethodSummaries();
665 void InitializeMethodSummaries();
Ted Kremenek896cd9d2008-10-23 01:56:15 +0000666
Ted Kremenekeff4b3c2009-05-03 04:42:10 +0000667 bool isTrackedObjCObjectType(QualType T);
Ted Kremenek92511432009-05-03 06:08:32 +0000668 bool isTrackedCFObjectType(QualType T);
Ted Kremenek234a4c22009-01-07 00:39:56 +0000669
Ted Kremenek896cd9d2008-10-23 01:56:15 +0000670private:
671
Ted Kremenek70a733e2008-07-18 17:24:20 +0000672 void addClsMethSummary(IdentifierInfo* ClsII, Selector S,
673 RetainSummary* Summ) {
674 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
675 }
676
Ted Kremenek553cf182008-06-25 21:21:56 +0000677 void addNSObjectClsMethSummary(Selector S, RetainSummary *Summ) {
678 ObjCClassMethodSummaries[S] = Summ;
679 }
680
681 void addNSObjectMethSummary(Selector S, RetainSummary *Summ) {
682 ObjCMethodSummaries[S] = Summ;
683 }
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +0000684
685 void addClassMethSummary(const char* Cls, const char* nullaryName,
686 RetainSummary *Summ) {
687 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
688 Selector S = GetNullarySelector(nullaryName, Ctx);
689 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
690 }
Ted Kremenek553cf182008-06-25 21:21:56 +0000691
Ted Kremenek6c4becb2009-02-25 02:54:57 +0000692 void addInstMethSummary(const char* Cls, const char* nullaryName,
693 RetainSummary *Summ) {
694 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
695 Selector S = GetNullarySelector(nullaryName, Ctx);
696 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
697 }
Ted Kremenekde4d5332009-04-24 17:50:11 +0000698
699 Selector generateSelector(va_list argp) {
Ted Kremenek9e476de2008-08-12 18:30:56 +0000700 llvm::SmallVector<IdentifierInfo*, 10> II;
Ted Kremenekde4d5332009-04-24 17:50:11 +0000701
Ted Kremenek9e476de2008-08-12 18:30:56 +0000702 while (const char* s = va_arg(argp, const char*))
703 II.push_back(&Ctx.Idents.get(s));
Ted Kremenekde4d5332009-04-24 17:50:11 +0000704
705 return Ctx.Selectors.getSelector(II.size(), &II[0]);
706 }
707
708 void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy& Summaries,
709 RetainSummary* Summ, va_list argp) {
710 Selector S = generateSelector(argp);
711 Summaries[ObjCSummaryKey(ClsII, S)] = Summ;
Ted Kremenek70a733e2008-07-18 17:24:20 +0000712 }
Ted Kremenekaf9dc272008-08-12 18:48:50 +0000713
714 void addInstMethSummary(const char* Cls, RetainSummary* Summ, ...) {
715 va_list argp;
716 va_start(argp, Summ);
Ted Kremenekde4d5332009-04-24 17:50:11 +0000717 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Ted Kremenekaf9dc272008-08-12 18:48:50 +0000718 va_end(argp);
719 }
Ted Kremenekde4d5332009-04-24 17:50:11 +0000720
721 void addClsMethSummary(const char* Cls, RetainSummary* Summ, ...) {
722 va_list argp;
723 va_start(argp, Summ);
724 addMethodSummary(&Ctx.Idents.get(Cls),ObjCClassMethodSummaries, Summ, argp);
725 va_end(argp);
726 }
727
728 void addClsMethSummary(IdentifierInfo *II, RetainSummary* Summ, ...) {
729 va_list argp;
730 va_start(argp, Summ);
731 addMethodSummary(II, ObjCClassMethodSummaries, Summ, argp);
732 va_end(argp);
733 }
734
Ted Kremenek9e476de2008-08-12 18:30:56 +0000735 void addPanicSummary(const char* Cls, ...) {
Ted Kremenekb77449c2009-05-03 05:20:50 +0000736 RetainSummary* Summ = getPersistentSummary(AF.GetEmptyMap(),
737 RetEffect::MakeNoRet(),
Ted Kremenek9e476de2008-08-12 18:30:56 +0000738 DoNothing, DoNothing, true);
739 va_list argp;
740 va_start (argp, Cls);
Ted Kremenekde4d5332009-04-24 17:50:11 +0000741 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Ted Kremenek9e476de2008-08-12 18:30:56 +0000742 va_end(argp);
Ted Kremenekde4d5332009-04-24 17:50:11 +0000743 }
Ted Kremenek70a733e2008-07-18 17:24:20 +0000744
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000745public:
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000746
747 RetainSummaryManager(ASTContext& ctx, bool gcenabled)
Ted Kremenek179064e2008-07-01 17:21:27 +0000748 : Ctx(ctx),
Ted Kremenek070a8252008-07-09 18:11:16 +0000749 CFDictionaryCreateII(&ctx.Idents.get("CFDictionaryCreate")),
Ted Kremenekb77449c2009-05-03 05:20:50 +0000750 GCEnabled(gcenabled), AF(BPAlloc), ScratchArgs(AF.GetEmptyMap()),
Ted Kremenekec315332009-05-07 23:40:42 +0000751 ObjCAllocRetE(gcenabled ? RetEffect::MakeGCNotOwned()
752 : RetEffect::MakeOwned(RetEffect::ObjC, true)),
Ted Kremenek7faca822009-05-04 04:57:00 +0000753 DefaultSummary(AF.GetEmptyMap() /* per-argument effects (none) */,
754 RetEffect::MakeNoRet() /* return effect */,
755 DoNothing /* receiver effect */,
756 MayEscape /* default argument effect */),
Ted Kremenekb77449c2009-05-03 05:20:50 +0000757 StopSummary(0) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000758
759 InitializeClassMethodSummaries();
760 InitializeMethodSummaries();
761 }
Ted Kremenek377e2302008-04-29 05:33:51 +0000762
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000763 ~RetainSummaryManager();
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000764
Ted Kremenekab592272008-06-24 03:56:45 +0000765 RetainSummary* getSummary(FunctionDecl* FD);
Ted Kremenek8711c032009-04-29 05:04:30 +0000766
Ted Kremeneka8833552009-04-29 23:03:22 +0000767 RetainSummary* getInstanceMethodSummary(ObjCMessageExpr* ME,
768 const ObjCInterfaceDecl* ID) {
Ted Kremenekce8a41d2009-04-29 17:09:14 +0000769 return getInstanceMethodSummary(ME->getSelector(), ME->getClassName(),
Ted Kremenek8711c032009-04-29 05:04:30 +0000770 ID, ME->getMethodDecl(), ME->getType());
771 }
772
Ted Kremenekce8a41d2009-04-29 17:09:14 +0000773 RetainSummary* getInstanceMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremeneka8833552009-04-29 23:03:22 +0000774 const ObjCInterfaceDecl* ID,
775 const ObjCMethodDecl *MD,
776 QualType RetTy);
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +0000777
778 RetainSummary *getClassMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremeneka8833552009-04-29 23:03:22 +0000779 const ObjCInterfaceDecl *ID,
780 const ObjCMethodDecl *MD,
781 QualType RetTy);
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +0000782
783 RetainSummary *getClassMethodSummary(ObjCMessageExpr *ME) {
784 return getClassMethodSummary(ME->getSelector(), ME->getClassName(),
785 ME->getClassInfo().first,
786 ME->getMethodDecl(), ME->getType());
787 }
Ted Kremenek552333c2009-04-29 17:17:48 +0000788
789 /// getMethodSummary - This version of getMethodSummary is used to query
790 /// the summary for the current method being analyzed.
Ted Kremeneka8833552009-04-29 23:03:22 +0000791 RetainSummary *getMethodSummary(const ObjCMethodDecl *MD) {
792 // FIXME: Eventually this should be unneeded.
Ted Kremeneka8833552009-04-29 23:03:22 +0000793 const ObjCInterfaceDecl *ID = MD->getClassInterface();
Ted Kremenek70a65762009-04-30 05:41:14 +0000794 Selector S = MD->getSelector();
Ted Kremenek552333c2009-04-29 17:17:48 +0000795 IdentifierInfo *ClsName = ID->getIdentifier();
796 QualType ResultTy = MD->getResultType();
797
Ted Kremenek76a50e32009-04-30 05:47:23 +0000798 // Resolve the method decl last.
799 if (const ObjCMethodDecl *InterfaceMD =
800 ResolveToInterfaceMethodDecl(MD, Ctx))
801 MD = InterfaceMD;
Ted Kremenek70a65762009-04-30 05:41:14 +0000802
Ted Kremenek552333c2009-04-29 17:17:48 +0000803 if (MD->isInstanceMethod())
804 return getInstanceMethodSummary(S, ClsName, ID, MD, ResultTy);
805 else
806 return getClassMethodSummary(S, ClsName, ID, MD, ResultTy);
807 }
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +0000808
Ted Kremeneka8833552009-04-29 23:03:22 +0000809 RetainSummary* getCommonMethodSummary(const ObjCMethodDecl* MD,
810 Selector S, QualType RetTy);
811
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000812 bool isGCEnabled() const { return GCEnabled; }
Ted Kremenek885c27b2009-05-04 05:31:22 +0000813
814 RetainSummary *copySummary(RetainSummary *OldSumm) {
815 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
816 new (Summ) RetainSummary(*OldSumm);
817 return Summ;
818 }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000819};
820
821} // end anonymous namespace
822
823//===----------------------------------------------------------------------===//
824// Implementation of checker data structures.
825//===----------------------------------------------------------------------===//
826
Ted Kremenekb77449c2009-05-03 05:20:50 +0000827RetainSummaryManager::~RetainSummaryManager() {}
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000828
Ted Kremenekb77449c2009-05-03 05:20:50 +0000829ArgEffects RetainSummaryManager::getArgEffects() {
830 ArgEffects AE = ScratchArgs;
831 ScratchArgs = AF.GetEmptyMap();
832 return AE;
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000833}
834
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000835RetainSummary*
Ted Kremenekb77449c2009-05-03 05:20:50 +0000836RetainSummaryManager::getPersistentSummary(ArgEffects AE, RetEffect RetEff,
Ted Kremenek1bffd742008-05-06 15:44:25 +0000837 ArgEffect ReceiverEff,
Ted Kremenek70a733e2008-07-18 17:24:20 +0000838 ArgEffect DefaultEff,
Ted Kremenek22fe2482009-05-04 04:30:18 +0000839 bool isEndPath) {
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000840 // Create the summary and return it.
Ted Kremenek22fe2482009-05-04 04:30:18 +0000841 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
Ted Kremenek70a733e2008-07-18 17:24:20 +0000842 new (Summ) RetainSummary(AE, RetEff, DefaultEff, ReceiverEff, isEndPath);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000843 return Summ;
844}
845
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000846//===----------------------------------------------------------------------===//
Ted Kremenek234a4c22009-01-07 00:39:56 +0000847// Predicates.
848//===----------------------------------------------------------------------===//
849
Ted Kremenekeff4b3c2009-05-03 04:42:10 +0000850bool RetainSummaryManager::isTrackedObjCObjectType(QualType Ty) {
Ted Kremenek97d095f2009-04-23 22:11:07 +0000851 if (!Ctx.isObjCObjectPointerType(Ty))
Ted Kremenek234a4c22009-01-07 00:39:56 +0000852 return false;
853
Ted Kremenek97d095f2009-04-23 22:11:07 +0000854 // We assume that id<..>, id, and "Class" all represent tracked objects.
855 const PointerType *PT = Ty->getAsPointerType();
856 if (PT == 0)
857 return true;
858
859 const ObjCInterfaceType *OT = PT->getPointeeType()->getAsObjCInterfaceType();
Ted Kremenek234a4c22009-01-07 00:39:56 +0000860
861 // We assume that id<..>, id, and "Class" all represent tracked objects.
862 if (!OT)
863 return true;
Ted Kremenek97d095f2009-04-23 22:11:07 +0000864
865 // Does the interface subclass NSObject?
Ted Kremenek234a4c22009-01-07 00:39:56 +0000866 // FIXME: We can memoize here if this gets too expensive.
867 IdentifierInfo* NSObjectII = &Ctx.Idents.get("NSObject");
868 ObjCInterfaceDecl* ID = OT->getDecl();
869
870 for ( ; ID ; ID = ID->getSuperClass())
871 if (ID->getIdentifier() == NSObjectII)
872 return true;
873
874 return false;
875}
876
Ted Kremenek92511432009-05-03 06:08:32 +0000877bool RetainSummaryManager::isTrackedCFObjectType(QualType T) {
878 return isRefType(T, "CF") || // Core Foundation.
879 isRefType(T, "CG") || // Core Graphics.
880 isRefType(T, "DADisk") || // Disk Arbitration API.
881 isRefType(T, "DADissenter") ||
882 isRefType(T, "DASessionRef");
883}
884
Ted Kremenek234a4c22009-01-07 00:39:56 +0000885//===----------------------------------------------------------------------===//
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000886// Summary creation for functions (largely uses of Core Foundation).
887//===----------------------------------------------------------------------===//
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000888
Ted Kremenek12619382009-01-12 21:45:02 +0000889static bool isRetain(FunctionDecl* FD, const char* FName) {
890 const char* loc = strstr(FName, "Retain");
891 return loc && loc[sizeof("Retain")-1] == '\0';
892}
893
894static bool isRelease(FunctionDecl* FD, const char* FName) {
895 const char* loc = strstr(FName, "Release");
896 return loc && loc[sizeof("Release")-1] == '\0';
897}
898
Ted Kremenekab592272008-06-24 03:56:45 +0000899RetainSummary* RetainSummaryManager::getSummary(FunctionDecl* FD) {
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000900 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000901 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000902 if (I != FuncSummaries.end())
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000903 return I->second;
904
Ted Kremeneke401a0c2009-05-04 15:34:07 +0000905 // No summary? Generate one.
Ted Kremenek12619382009-01-12 21:45:02 +0000906 RetainSummary *S = 0;
Ted Kremenek86ad3bc2008-05-05 16:51:50 +0000907
Ted Kremenek37d785b2008-07-15 16:50:12 +0000908 do {
Ted Kremenek12619382009-01-12 21:45:02 +0000909 // We generate "stop" summaries for implicitly defined functions.
910 if (FD->isImplicit()) {
911 S = getPersistentStopSummary();
912 break;
Ted Kremenek37d785b2008-07-15 16:50:12 +0000913 }
Ted Kremenek6ca31912008-11-04 00:36:12 +0000914
Ted Kremenek6ad315a2009-02-23 16:51:39 +0000915 // [PR 3337] Use 'getAsFunctionType' to strip away any typedefs on the
Ted Kremenek99890652009-01-16 18:40:33 +0000916 // function's type.
Ted Kremenek6ad315a2009-02-23 16:51:39 +0000917 const FunctionType* FT = FD->getType()->getAsFunctionType();
Ted Kremenek12619382009-01-12 21:45:02 +0000918 const char* FName = FD->getIdentifier()->getName();
919
Ted Kremenekbf0a4dd2009-03-05 22:11:14 +0000920 // Strip away preceding '_'. Doing this here will effect all the checks
921 // down below.
922 while (*FName == '_') ++FName;
923
Ted Kremenek12619382009-01-12 21:45:02 +0000924 // Inspect the result type.
925 QualType RetTy = FT->getResultType();
926
927 // FIXME: This should all be refactored into a chain of "summary lookup"
928 // filters.
929 if (strcmp(FName, "IOServiceGetMatchingServices") == 0) {
930 // FIXES: <rdar://problem/6326900>
931 // This should be addressed using a API table. This strcmp is also
932 // a little gross, but there is no need to super optimize here.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000933 assert (ScratchArgs.isEmpty());
934 ScratchArgs = AF.Add(ScratchArgs, 1, DecRef);
Ted Kremenek12619382009-01-12 21:45:02 +0000935 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
936 break;
Ted Kremenek64e859a2008-10-22 20:54:52 +0000937 }
Ted Kremenek61991902009-03-17 22:43:44 +0000938
939 // Enable this code once the semantics of NSDeallocateObject are resolved
940 // for GC. <rdar://problem/6619988>
941#if 0
942 // Handle: NSDeallocateObject(id anObject);
943 // This method does allow 'nil' (although we don't check it now).
944 if (strcmp(FName, "NSDeallocateObject") == 0) {
945 return RetTy == Ctx.VoidTy
946 ? getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, Dealloc)
947 : getPersistentStopSummary();
948 }
949#endif
Ted Kremenek12619382009-01-12 21:45:02 +0000950
951 // Handle: id NSMakeCollectable(CFTypeRef)
952 if (strcmp(FName, "NSMakeCollectable") == 0) {
953 S = (RetTy == Ctx.getObjCIdType())
954 ? getUnarySummary(FT, cfmakecollectable)
955 : getPersistentStopSummary();
956
957 break;
958 }
959
960 if (RetTy->isPointerType()) {
961 // For CoreFoundation ('CF') types.
962 if (isRefType(RetTy, "CF", &Ctx, FName)) {
963 if (isRetain(FD, FName))
964 S = getUnarySummary(FT, cfretain);
965 else if (strstr(FName, "MakeCollectable"))
966 S = getUnarySummary(FT, cfmakecollectable);
967 else
968 S = getCFCreateGetRuleSummary(FD, FName);
969
970 break;
971 }
972
973 // For CoreGraphics ('CG') types.
974 if (isRefType(RetTy, "CG", &Ctx, FName)) {
975 if (isRetain(FD, FName))
976 S = getUnarySummary(FT, cfretain);
977 else
978 S = getCFCreateGetRuleSummary(FD, FName);
979
980 break;
981 }
982
983 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
984 if (isRefType(RetTy, "DADisk") ||
985 isRefType(RetTy, "DADissenter") ||
986 isRefType(RetTy, "DASessionRef")) {
987 S = getCFCreateGetRuleSummary(FD, FName);
988 break;
989 }
990
991 break;
992 }
993
994 // Check for release functions, the only kind of functions that we care
995 // about that don't return a pointer type.
996 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
Ted Kremenekbf0a4dd2009-03-05 22:11:14 +0000997 // Test for 'CGCF'.
998 if (FName[1] == 'G' && FName[2] == 'C' && FName[3] == 'F')
999 FName += 4;
1000 else
1001 FName += 2;
1002
1003 if (isRelease(FD, FName))
Ted Kremenek12619382009-01-12 21:45:02 +00001004 S = getUnarySummary(FT, cfrelease);
1005 else {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001006 assert (ScratchArgs.isEmpty());
Ted Kremenek68189282009-01-29 22:45:13 +00001007 // Remaining CoreFoundation and CoreGraphics functions.
1008 // We use to assume that they all strictly followed the ownership idiom
1009 // and that ownership cannot be transferred. While this is technically
1010 // correct, many methods allow a tracked object to escape. For example:
1011 //
1012 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
1013 // CFDictionaryAddValue(y, key, x);
1014 // CFRelease(x);
1015 // ... it is okay to use 'x' since 'y' has a reference to it
1016 //
1017 // We handle this and similar cases with the follow heuristic. If the
1018 // function name contains "InsertValue", "SetValue" or "AddValue" then
1019 // we assume that arguments may "escape."
1020 //
1021 ArgEffect E = (CStrInCStrNoCase(FName, "InsertValue") ||
1022 CStrInCStrNoCase(FName, "AddValue") ||
Ted Kremeneka92206e2009-02-05 22:34:53 +00001023 CStrInCStrNoCase(FName, "SetValue") ||
1024 CStrInCStrNoCase(FName, "AppendValue"))
Ted Kremenek68189282009-01-29 22:45:13 +00001025 ? MayEscape : DoNothing;
1026
1027 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek12619382009-01-12 21:45:02 +00001028 }
1029 }
Ted Kremenek37d785b2008-07-15 16:50:12 +00001030 }
1031 while (0);
Ted Kremenek885c27b2009-05-04 05:31:22 +00001032
1033 if (!S)
1034 S = getDefaultSummary();
Ted Kremenek891d5cc2008-04-24 17:22:33 +00001035
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001036 FuncSummaries[FD] = S;
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001037 return S;
Ted Kremenek2fff37e2008-03-06 00:08:09 +00001038}
1039
Ted Kremenek37d785b2008-07-15 16:50:12 +00001040RetainSummary*
1041RetainSummaryManager::getCFCreateGetRuleSummary(FunctionDecl* FD,
1042 const char* FName) {
1043
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001044 if (strstr(FName, "Create") || strstr(FName, "Copy"))
1045 return getCFSummaryCreateRule(FD);
Ted Kremenek37d785b2008-07-15 16:50:12 +00001046
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001047 if (strstr(FName, "Get"))
1048 return getCFSummaryGetRule(FD);
1049
Ted Kremenek7faca822009-05-04 04:57:00 +00001050 return getDefaultSummary();
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001051}
1052
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001053RetainSummary*
Ted Kremenek6ad315a2009-02-23 16:51:39 +00001054RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1055 UnaryFuncKind func) {
1056
Ted Kremenek12619382009-01-12 21:45:02 +00001057 // Sanity check that this is *really* a unary function. This can
1058 // happen if people do weird things.
Douglas Gregor72564e72009-02-26 23:50:07 +00001059 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
Ted Kremenek12619382009-01-12 21:45:02 +00001060 if (!FTP || FTP->getNumArgs() != 1)
1061 return getPersistentStopSummary();
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001062
Ted Kremenekb77449c2009-05-03 05:20:50 +00001063 assert (ScratchArgs.isEmpty());
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001064
Ted Kremenek377e2302008-04-29 05:33:51 +00001065 switch (func) {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001066 case cfretain: {
1067 ScratchArgs = AF.Add(ScratchArgs, 0, IncRef);
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00001068 return getPersistentSummary(RetEffect::MakeAlias(0),
1069 DoNothing, DoNothing);
Ted Kremenek377e2302008-04-29 05:33:51 +00001070 }
1071
1072 case cfrelease: {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001073 ScratchArgs = AF.Add(ScratchArgs, 0, DecRef);
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00001074 return getPersistentSummary(RetEffect::MakeNoRet(),
1075 DoNothing, DoNothing);
Ted Kremenek377e2302008-04-29 05:33:51 +00001076 }
1077
1078 case cfmakecollectable: {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001079 ScratchArgs = AF.Add(ScratchArgs, 0, MakeCollectable);
Ted Kremenek27019002009-02-18 21:57:45 +00001080 return getPersistentSummary(RetEffect::MakeAlias(0),DoNothing, DoNothing);
Ted Kremenek377e2302008-04-29 05:33:51 +00001081 }
1082
1083 default:
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001084 assert (false && "Not a supported unary function.");
Ted Kremenek7faca822009-05-04 04:57:00 +00001085 return getDefaultSummary();
Ted Kremenek940b1d82008-04-10 23:44:06 +00001086 }
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001087}
1088
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001089RetainSummary* RetainSummaryManager::getCFSummaryCreateRule(FunctionDecl* FD) {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001090 assert (ScratchArgs.isEmpty());
Ted Kremenek070a8252008-07-09 18:11:16 +00001091
1092 if (FD->getIdentifier() == CFDictionaryCreateII) {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001093 ScratchArgs = AF.Add(ScratchArgs, 1, DoNothingByRef);
1094 ScratchArgs = AF.Add(ScratchArgs, 2, DoNothingByRef);
Ted Kremenek070a8252008-07-09 18:11:16 +00001095 }
1096
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001097 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001098}
1099
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001100RetainSummary* RetainSummaryManager::getCFSummaryGetRule(FunctionDecl* FD) {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001101 assert (ScratchArgs.isEmpty());
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001102 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1103 DoNothing, DoNothing);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001104}
1105
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001106//===----------------------------------------------------------------------===//
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001107// Summary creation for Selectors.
1108//===----------------------------------------------------------------------===//
1109
Ted Kremenek1bffd742008-05-06 15:44:25 +00001110RetainSummary*
Ted Kremenek8711c032009-04-29 05:04:30 +00001111RetainSummaryManager::getInitMethodSummary(QualType RetTy) {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001112 assert(ScratchArgs.isEmpty());
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001113
Ted Kremenekc3cf7b22009-02-20 00:05:35 +00001114 // 'init' methods only return an alias if the return type is a location type.
Ted Kremenek8711c032009-04-29 05:04:30 +00001115 return getPersistentSummary(Loc::IsLocType(RetTy)
1116 ? RetEffect::MakeReceiverAlias()
Ted Kremenek69aa0802009-05-05 18:44:20 +00001117 : RetEffect::MakeNoRet());
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001118}
Ted Kremenek69aa0802009-05-05 18:44:20 +00001119
Ted Kremenek1bffd742008-05-06 15:44:25 +00001120RetainSummary*
Ted Kremeneka8833552009-04-29 23:03:22 +00001121RetainSummaryManager::getCommonMethodSummary(const ObjCMethodDecl* MD,
1122 Selector S, QualType RetTy) {
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001123
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +00001124 if (MD) {
Ted Kremenek376d1e72009-04-24 18:00:17 +00001125 // Scan the method decl for 'void*' arguments. These should be treated
1126 // as 'StopTracking' because they are often used with delegates.
1127 // Delegates are a frequent form of false positives with the retain
1128 // count checker.
1129 unsigned i = 0;
1130 for (ObjCMethodDecl::param_iterator I = MD->param_begin(),
1131 E = MD->param_end(); I != E; ++I, ++i)
1132 if (ParmVarDecl *PD = *I) {
1133 QualType Ty = Ctx.getCanonicalType(PD->getType());
1134 if (Ty.getUnqualifiedType() == Ctx.VoidPtrTy)
Ted Kremenekb77449c2009-05-03 05:20:50 +00001135 ScratchArgs = AF.Add(ScratchArgs, i, StopTracking);
Ted Kremenek376d1e72009-04-24 18:00:17 +00001136 }
1137 }
1138
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001139 // Any special effect for the receiver?
1140 ArgEffect ReceiverEff = DoNothing;
1141
1142 // If one of the arguments in the selector has the keyword 'delegate' we
1143 // should stop tracking the reference count for the receiver. This is
1144 // because the reference count is quite possibly handled by a delegate
1145 // method.
1146 if (S.isKeywordSelector()) {
1147 const std::string &str = S.getAsString();
1148 assert(!str.empty());
1149 if (CStrInCStrNoCase(&str[0], "delegate:")) ReceiverEff = StopTracking;
1150 }
1151
Ted Kremenek250b1fa2009-04-23 23:08:22 +00001152 // Look for methods that return an owned object.
Ted Kremenek92511432009-05-03 06:08:32 +00001153 if (isTrackedObjCObjectType(RetTy)) {
1154 // EXPERIMENTAL: Assume the Cocoa conventions for all objects returned
1155 // by instance methods.
Ted Kremenek92511432009-05-03 06:08:32 +00001156 RetEffect E =
1157 followsFundamentalRule(S.getIdentifierInfoForSlot(0)->getName())
Ted Kremenekec315332009-05-07 23:40:42 +00001158 ? ObjCAllocRetE : RetEffect::MakeNotOwned(RetEffect::ObjC);
Ted Kremenek92511432009-05-03 06:08:32 +00001159
1160 return getPersistentSummary(E, ReceiverEff, MayEscape);
Ted Kremenek376d1e72009-04-24 18:00:17 +00001161 }
Ted Kremenek250b1fa2009-04-23 23:08:22 +00001162
Ted Kremenek92511432009-05-03 06:08:32 +00001163 // Look for methods that return an owned core foundation object.
1164 if (isTrackedCFObjectType(RetTy)) {
1165 RetEffect E =
1166 followsFundamentalRule(S.getIdentifierInfoForSlot(0)->getName())
1167 ? RetEffect::MakeOwned(RetEffect::CF, true)
1168 : RetEffect::MakeNotOwned(RetEffect::CF);
1169
1170 return getPersistentSummary(E, ReceiverEff, MayEscape);
1171 }
Ted Kremenek250b1fa2009-04-23 23:08:22 +00001172
Ted Kremenek92511432009-05-03 06:08:32 +00001173 if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing)
Ted Kremenek7faca822009-05-04 04:57:00 +00001174 return getDefaultSummary();
Ted Kremenek250b1fa2009-04-23 23:08:22 +00001175
Ted Kremenek885c27b2009-05-04 05:31:22 +00001176 return getPersistentSummary(RetEffect::MakeNoRet(), ReceiverEff, MayEscape);
Ted Kremenek250b1fa2009-04-23 23:08:22 +00001177}
1178
1179RetainSummary*
Ted Kremenekce8a41d2009-04-29 17:09:14 +00001180RetainSummaryManager::getInstanceMethodSummary(Selector S,
1181 IdentifierInfo *ClsName,
Ted Kremeneka8833552009-04-29 23:03:22 +00001182 const ObjCInterfaceDecl* ID,
1183 const ObjCMethodDecl *MD,
Ted Kremenekce8a41d2009-04-29 17:09:14 +00001184 QualType RetTy) {
Ted Kremenek1bffd742008-05-06 15:44:25 +00001185
Ted Kremenek8711c032009-04-29 05:04:30 +00001186 // Look up a summary in our summary cache.
1187 ObjCMethodSummariesTy::iterator I = ObjCMethodSummaries.find(ID, ClsName, S);
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001188
Ted Kremenek1f180c32008-06-23 22:21:20 +00001189 if (I != ObjCMethodSummaries.end())
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001190 return I->second;
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001191
Ted Kremenekb77449c2009-05-03 05:20:50 +00001192 assert(ScratchArgs.isEmpty());
Ted Kremenek885c27b2009-05-04 05:31:22 +00001193 RetainSummary *Summ = 0;
Ted Kremenekaee9e572008-05-06 06:09:09 +00001194
Ted Kremenek885c27b2009-05-04 05:31:22 +00001195 // "initXXX": pass-through for receiver.
1196 if (deriveNamingConvention(S.getIdentifierInfoForSlot(0)->getName())
1197 == InitRule)
1198 Summ = getInitMethodSummary(RetTy);
1199 else
1200 Summ = getCommonMethodSummary(MD, S, RetTy);
1201
Ted Kremenek885c27b2009-05-04 05:31:22 +00001202 // Memoize the summary.
Ted Kremenek8711c032009-04-29 05:04:30 +00001203 ObjCMethodSummaries[ObjCSummaryKey(ClsName, S)] = Summ;
Ted Kremeneke87450e2009-04-23 19:11:35 +00001204 return Summ;
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001205}
1206
Ted Kremenekc8395602008-05-06 21:26:51 +00001207RetainSummary*
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +00001208RetainSummaryManager::getClassMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremeneka8833552009-04-29 23:03:22 +00001209 const ObjCInterfaceDecl *ID,
1210 const ObjCMethodDecl *MD,
1211 QualType RetTy) {
Ted Kremenekde4d5332009-04-24 17:50:11 +00001212
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +00001213 assert(ClsName && "Class name must be specified.");
Ted Kremenek8711c032009-04-29 05:04:30 +00001214 ObjCMethodSummariesTy::iterator I =
1215 ObjCClassMethodSummaries.find(ID, ClsName, S);
Ted Kremenekc8395602008-05-06 21:26:51 +00001216
Ted Kremenek1f180c32008-06-23 22:21:20 +00001217 if (I != ObjCClassMethodSummaries.end())
Ted Kremenekc8395602008-05-06 21:26:51 +00001218 return I->second;
Ted Kremenek885c27b2009-05-04 05:31:22 +00001219
1220 RetainSummary *Summ = getCommonMethodSummary(MD, S, RetTy);
1221
Ted Kremenek885c27b2009-05-04 05:31:22 +00001222 // Memoize the summary.
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +00001223 ObjCClassMethodSummaries[ObjCSummaryKey(ClsName, S)] = Summ;
Ted Kremeneke87450e2009-04-23 19:11:35 +00001224 return Summ;
Ted Kremenekc8395602008-05-06 21:26:51 +00001225}
1226
Ted Kremenekec315332009-05-07 23:40:42 +00001227void RetainSummaryManager::InitializeClassMethodSummaries() {
1228 assert(ScratchArgs.isEmpty());
1229 RetainSummary* Summ = getPersistentSummary(ObjCAllocRetE);
Ted Kremenek9c32d082008-05-06 00:30:21 +00001230
Ted Kremenek553cf182008-06-25 21:21:56 +00001231 // Create the summaries for "alloc", "new", and "allocWithZone:" for
1232 // NSObject and its derivatives.
1233 addNSObjectClsMethSummary(GetNullarySelector("alloc", Ctx), Summ);
1234 addNSObjectClsMethSummary(GetNullarySelector("new", Ctx), Summ);
1235 addNSObjectClsMethSummary(GetUnarySelector("allocWithZone", Ctx), Summ);
Ted Kremenek70a733e2008-07-18 17:24:20 +00001236
1237 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek9e476de2008-08-12 18:30:56 +00001238 addClsMethSummary(&Ctx.Idents.get("NSAssertionHandler"),
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001239 GetNullarySelector("currentHandler", Ctx),
1240 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Ted Kremenek6d348932008-10-21 15:53:15 +00001241
1242 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremenekb77449c2009-05-03 05:20:50 +00001243 ScratchArgs = AF.Add(ScratchArgs, 0, Autorelease);
Ted Kremenekabf43972009-01-28 21:44:40 +00001244 addClsMethSummary(&Ctx.Idents.get("NSAutoreleasePool"),
1245 GetUnarySelector("addObject", Ctx),
1246 getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenek022a3c42009-02-23 02:31:16 +00001247 DoNothing, Autorelease));
Ted Kremenekde4d5332009-04-24 17:50:11 +00001248
1249 // Create the summaries for [NSObject performSelector...]. We treat
1250 // these as 'stop tracking' for the arguments because they are often
1251 // used for delegates that can release the object. When we have better
1252 // inter-procedural analysis we can potentially do something better. This
1253 // workaround is to remove false positives.
1254 Summ = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, StopTracking);
1255 IdentifierInfo *NSObjectII = &Ctx.Idents.get("NSObject");
1256 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1257 "afterDelay", NULL);
1258 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1259 "afterDelay", "inModes", NULL);
1260 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1261 "withObject", "waitUntilDone", NULL);
1262 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1263 "withObject", "waitUntilDone", "modes", NULL);
1264 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1265 "withObject", "waitUntilDone", NULL);
1266 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1267 "withObject", "waitUntilDone", "modes", NULL);
1268 addClsMethSummary(NSObjectII, Summ, "performSelectorInBackground",
1269 "withObject", NULL);
Ted Kremenek9c32d082008-05-06 00:30:21 +00001270}
1271
Ted Kremenek1f180c32008-06-23 22:21:20 +00001272void RetainSummaryManager::InitializeMethodSummaries() {
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001273
Ted Kremenekb77449c2009-05-03 05:20:50 +00001274 assert (ScratchArgs.isEmpty());
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001275
Ted Kremenekc8395602008-05-06 21:26:51 +00001276 // Create the "init" selector. It just acts as a pass-through for the
1277 // receiver.
Ted Kremenek46347352009-02-23 16:54:00 +00001278 RetainSummary* InitSumm =
1279 getPersistentSummary(RetEffect::MakeReceiverAlias());
Ted Kremenek179064e2008-07-01 17:21:27 +00001280 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
Ted Kremenekc8395602008-05-06 21:26:51 +00001281
1282 // The next methods are allocators.
Ted Kremenekec315332009-05-07 23:40:42 +00001283 RetainSummary* Summ = getPersistentSummary(ObjCAllocRetE);
Ted Kremenekc8395602008-05-06 21:26:51 +00001284
1285 // Create the "copy" selector.
Ted Kremenek98530452008-08-12 20:41:56 +00001286 addNSObjectMethSummary(GetNullarySelector("copy", Ctx), Summ);
1287
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001288 // Create the "mutableCopy" selector.
Ted Kremenek553cf182008-06-25 21:21:56 +00001289 addNSObjectMethSummary(GetNullarySelector("mutableCopy", Ctx), Summ);
Ted Kremenek98530452008-08-12 20:41:56 +00001290
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001291 // Create the "retain" selector.
Ted Kremenekec315332009-05-07 23:40:42 +00001292 RetEffect E = RetEffect::MakeReceiverAlias();
Ted Kremenek1c512f52009-02-18 18:54:33 +00001293 Summ = getPersistentSummary(E, IncRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001294 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001295
1296 // Create the "release" selector.
Ted Kremenek1c512f52009-02-18 18:54:33 +00001297 Summ = getPersistentSummary(E, DecRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001298 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Ted Kremenek299e8152008-05-07 21:17:39 +00001299
1300 // Create the "drain" selector.
1301 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek553cf182008-06-25 21:21:56 +00001302 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001303
1304 // Create the -dealloc summary.
1305 Summ = getPersistentSummary(RetEffect::MakeNoRet(), Dealloc);
1306 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001307
1308 // Create the "autorelease" selector.
Ted Kremenekabf43972009-01-28 21:44:40 +00001309 Summ = getPersistentSummary(E, Autorelease);
Ted Kremenek553cf182008-06-25 21:21:56 +00001310 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Ted Kremenek98530452008-08-12 20:41:56 +00001311
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00001312 // Specially handle NSAutoreleasePool.
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001313 addInstMethSummary("NSAutoreleasePool", "init",
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00001314 getPersistentSummary(RetEffect::MakeReceiverAlias(),
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001315 NewAutoreleasePool));
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00001316
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001317 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremenek89e202d2009-02-23 02:51:29 +00001318 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1319 // self-own themselves. However, they only do this once they are displayed.
1320 // Thus, we need to track an NSWindow's display status.
1321 // This is tracked in <rdar://problem/6062711>.
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +00001322 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
Ted Kremenek99d02692009-04-03 19:02:51 +00001323 RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet());
1324
1325 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1326
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +00001327
1328#if 0
Ted Kremenek179064e2008-07-01 17:21:27 +00001329 RetainSummary *NSWindowSumm =
Ted Kremenek89e202d2009-02-23 02:51:29 +00001330 getPersistentSummary(RetEffect::MakeReceiverAlias(), StopTracking);
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001331
1332 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1333 "styleMask", "backing", "defer", NULL);
1334
1335 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1336 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +00001337#endif
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001338
1339 // For NSPanel (which subclasses NSWindow), allocated objects are not
1340 // self-owned.
Ted Kremenek99d02692009-04-03 19:02:51 +00001341 // FIXME: For now we don't track NSPanels. object for the same reason
1342 // as for NSWindow objects.
1343 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
1344
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001345 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1346 "styleMask", "backing", "defer", NULL);
1347
1348 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1349 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek553cf182008-06-25 21:21:56 +00001350
Ted Kremenek70a733e2008-07-18 17:24:20 +00001351 // Create NSAssertionHandler summaries.
Ted Kremenek9e476de2008-08-12 18:30:56 +00001352 addPanicSummary("NSAssertionHandler", "handleFailureInFunction", "file",
1353 "lineNumber", "description", NULL);
Ted Kremenek70a733e2008-07-18 17:24:20 +00001354
Ted Kremenek9e476de2008-08-12 18:30:56 +00001355 addPanicSummary("NSAssertionHandler", "handleFailureInMethod", "object",
1356 "file", "lineNumber", "description", NULL);
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001357}
1358
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001359//===----------------------------------------------------------------------===//
Ted Kremenek13922612008-04-16 20:40:59 +00001360// Reference-counting logic (typestate + counts).
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001361//===----------------------------------------------------------------------===//
1362
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001363namespace {
1364
Ted Kremenek05cbe1a2008-04-09 23:49:11 +00001365class VISIBILITY_HIDDEN RefVal {
Ted Kremenek4fd88972008-04-17 18:12:53 +00001366public:
Ted Kremenek4fd88972008-04-17 18:12:53 +00001367 enum Kind {
1368 Owned = 0, // Owning reference.
1369 NotOwned, // Reference is not owned by still valid (not freed).
1370 Released, // Object has been released.
1371 ReturnedOwned, // Returned object passes ownership to caller.
1372 ReturnedNotOwned, // Return object does not pass ownership to caller.
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001373 ERROR_START,
1374 ErrorDeallocNotOwned, // -dealloc called on non-owned object.
1375 ErrorDeallocGC, // Calling -dealloc with GC enabled.
Ted Kremenek4fd88972008-04-17 18:12:53 +00001376 ErrorUseAfterRelease, // Object used after released.
1377 ErrorReleaseNotOwned, // Release of an object that was not owned.
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001378 ERROR_LEAK_START,
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00001379 ErrorLeak, // A memory leak due to excessive reference counts.
Ted Kremenek369de562009-05-09 00:10:05 +00001380 ErrorLeakReturned, // A memory leak due to the returning method not having
1381 // the correct naming conventions.
1382 ErrorOverAutorelease
Ted Kremenek4fd88972008-04-17 18:12:53 +00001383 };
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001384
1385private:
Ted Kremenek4fd88972008-04-17 18:12:53 +00001386 Kind kind;
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001387 RetEffect::ObjKind okind;
Ted Kremenek4fd88972008-04-17 18:12:53 +00001388 unsigned Cnt;
Ted Kremenekf21332e2009-05-08 20:01:42 +00001389 unsigned ACnt;
Ted Kremenek553cf182008-06-25 21:21:56 +00001390 QualType T;
1391
Ted Kremenekf21332e2009-05-08 20:01:42 +00001392 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, unsigned acnt, QualType t)
1393 : kind(k), okind(o), Cnt(cnt), ACnt(acnt), T(t) {}
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001394
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001395 RefVal(Kind k, unsigned cnt = 0)
Ted Kremenekf21332e2009-05-08 20:01:42 +00001396 : kind(k), okind(RetEffect::AnyObj), Cnt(cnt), ACnt(0) {}
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001397
1398public:
Ted Kremenek4fd88972008-04-17 18:12:53 +00001399 Kind getKind() const { return kind; }
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001400
1401 RetEffect::ObjKind getObjKind() const { return okind; }
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001402
Ted Kremenekf21332e2009-05-08 20:01:42 +00001403 unsigned getCount() const { return Cnt; }
1404 unsigned getAutoreleaseCount() const { return ACnt; }
1405 unsigned getCombinedCounts() const { return Cnt + ACnt; }
1406 void clearCounts() { Cnt = 0; ACnt = 0; }
Ted Kremenek369de562009-05-09 00:10:05 +00001407 void setCount(unsigned i) { Cnt = i; }
1408 void setAutoreleaseCount(unsigned i) { ACnt = i; }
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001409
Ted Kremenek553cf182008-06-25 21:21:56 +00001410 QualType getType() const { return T; }
Ted Kremenek4fd88972008-04-17 18:12:53 +00001411
1412 // Useful predicates.
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001413
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001414 static bool isError(Kind k) { return k >= ERROR_START; }
Ted Kremenek73c750b2008-03-11 18:14:09 +00001415
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001416 static bool isLeak(Kind k) { return k >= ERROR_LEAK_START; }
Ted Kremenekdb863712008-04-16 22:32:20 +00001417
Ted Kremeneke7bd9c22008-04-11 22:25:11 +00001418 bool isOwned() const {
1419 return getKind() == Owned;
1420 }
1421
Ted Kremenekdb863712008-04-16 22:32:20 +00001422 bool isNotOwned() const {
1423 return getKind() == NotOwned;
1424 }
1425
Ted Kremenek4fd88972008-04-17 18:12:53 +00001426 bool isReturnedOwned() const {
1427 return getKind() == ReturnedOwned;
1428 }
1429
1430 bool isReturnedNotOwned() const {
1431 return getKind() == ReturnedNotOwned;
1432 }
1433
1434 bool isNonLeakError() const {
1435 Kind k = getKind();
1436 return isError(k) && !isLeak(k);
1437 }
1438
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001439 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
1440 unsigned Count = 1) {
Ted Kremenekf21332e2009-05-08 20:01:42 +00001441 return RefVal(Owned, o, Count, 0, t);
Ted Kremenek61b9f872008-04-10 23:09:18 +00001442 }
1443
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001444 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
1445 unsigned Count = 0) {
Ted Kremenekf21332e2009-05-08 20:01:42 +00001446 return RefVal(NotOwned, o, Count, 0, t);
Ted Kremenek61b9f872008-04-10 23:09:18 +00001447 }
Ted Kremenek4fd88972008-04-17 18:12:53 +00001448
1449 static RefVal makeReturnedOwned(unsigned Count) {
1450 return RefVal(ReturnedOwned, Count);
1451 }
1452
1453 static RefVal makeReturnedNotOwned() {
1454 return RefVal(ReturnedNotOwned);
1455 }
1456
Ted Kremenek4fd88972008-04-17 18:12:53 +00001457 // Comparison, profiling, and pretty-printing.
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001458
Ted Kremenek4fd88972008-04-17 18:12:53 +00001459 bool operator==(const RefVal& X) const {
Ted Kremenek553cf182008-06-25 21:21:56 +00001460 return kind == X.kind && Cnt == X.Cnt && T == X.T;
Ted Kremenek4fd88972008-04-17 18:12:53 +00001461 }
Ted Kremenekf3948042008-03-11 19:44:10 +00001462
Ted Kremenek553cf182008-06-25 21:21:56 +00001463 RefVal operator-(size_t i) const {
Ted Kremenekf21332e2009-05-08 20:01:42 +00001464 return RefVal(getKind(), getObjKind(), getCount() - i,
1465 getAutoreleaseCount(), getType());
Ted Kremenek553cf182008-06-25 21:21:56 +00001466 }
1467
1468 RefVal operator+(size_t i) const {
Ted Kremenekf21332e2009-05-08 20:01:42 +00001469 return RefVal(getKind(), getObjKind(), getCount() + i,
1470 getAutoreleaseCount(), getType());
Ted Kremenek553cf182008-06-25 21:21:56 +00001471 }
1472
1473 RefVal operator^(Kind k) const {
Ted Kremenekf21332e2009-05-08 20:01:42 +00001474 return RefVal(k, getObjKind(), getCount(), getAutoreleaseCount(),
1475 getType());
1476 }
1477
1478 RefVal autorelease() const {
1479 return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount()+1,
1480 getType());
Ted Kremenek553cf182008-06-25 21:21:56 +00001481 }
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001482
Ted Kremenek4fd88972008-04-17 18:12:53 +00001483 void Profile(llvm::FoldingSetNodeID& ID) const {
1484 ID.AddInteger((unsigned) kind);
1485 ID.AddInteger(Cnt);
Ted Kremenekf21332e2009-05-08 20:01:42 +00001486 ID.AddInteger(ACnt);
Ted Kremenek553cf182008-06-25 21:21:56 +00001487 ID.Add(T);
Ted Kremenek4fd88972008-04-17 18:12:53 +00001488 }
1489
Ted Kremenekf3948042008-03-11 19:44:10 +00001490 void print(std::ostream& Out) const;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001491};
Ted Kremenekf3948042008-03-11 19:44:10 +00001492
1493void RefVal::print(std::ostream& Out) const {
Ted Kremenek553cf182008-06-25 21:21:56 +00001494 if (!T.isNull())
1495 Out << "Tracked Type:" << T.getAsString() << '\n';
1496
Ted Kremenekf3948042008-03-11 19:44:10 +00001497 switch (getKind()) {
1498 default: assert(false);
Ted Kremenek61b9f872008-04-10 23:09:18 +00001499 case Owned: {
1500 Out << "Owned";
1501 unsigned cnt = getCount();
1502 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenekf3948042008-03-11 19:44:10 +00001503 break;
Ted Kremenek61b9f872008-04-10 23:09:18 +00001504 }
Ted Kremenekf3948042008-03-11 19:44:10 +00001505
Ted Kremenek61b9f872008-04-10 23:09:18 +00001506 case NotOwned: {
Ted Kremenek4fd88972008-04-17 18:12:53 +00001507 Out << "NotOwned";
Ted Kremenek61b9f872008-04-10 23:09:18 +00001508 unsigned cnt = getCount();
1509 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenekf3948042008-03-11 19:44:10 +00001510 break;
Ted Kremenek61b9f872008-04-10 23:09:18 +00001511 }
Ted Kremenekf3948042008-03-11 19:44:10 +00001512
Ted Kremenek4fd88972008-04-17 18:12:53 +00001513 case ReturnedOwned: {
1514 Out << "ReturnedOwned";
1515 unsigned cnt = getCount();
1516 if (cnt) Out << " (+ " << cnt << ")";
1517 break;
1518 }
1519
1520 case ReturnedNotOwned: {
1521 Out << "ReturnedNotOwned";
1522 unsigned cnt = getCount();
1523 if (cnt) Out << " (+ " << cnt << ")";
1524 break;
1525 }
1526
Ted Kremenekf3948042008-03-11 19:44:10 +00001527 case Released:
1528 Out << "Released";
1529 break;
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001530
1531 case ErrorDeallocGC:
1532 Out << "-dealloc (GC)";
1533 break;
1534
1535 case ErrorDeallocNotOwned:
1536 Out << "-dealloc (not-owned)";
1537 break;
Ted Kremenekf3948042008-03-11 19:44:10 +00001538
Ted Kremenekdb863712008-04-16 22:32:20 +00001539 case ErrorLeak:
1540 Out << "Leaked";
1541 break;
1542
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00001543 case ErrorLeakReturned:
1544 Out << "Leaked (Bad naming)";
1545 break;
1546
Ted Kremenekf3948042008-03-11 19:44:10 +00001547 case ErrorUseAfterRelease:
1548 Out << "Use-After-Release [ERROR]";
1549 break;
1550
1551 case ErrorReleaseNotOwned:
1552 Out << "Release of Not-Owned [ERROR]";
1553 break;
Ted Kremenek80c24182009-05-09 00:44:07 +00001554
1555 case RefVal::ErrorOverAutorelease:
1556 Out << "Over autoreleased";
1557 break;
Ted Kremenekf3948042008-03-11 19:44:10 +00001558 }
Ted Kremenekf21332e2009-05-08 20:01:42 +00001559
1560 if (ACnt) {
1561 Out << " [ARC +" << ACnt << ']';
1562 }
Ted Kremenekf3948042008-03-11 19:44:10 +00001563}
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001564
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001565} // end anonymous namespace
1566
1567//===----------------------------------------------------------------------===//
1568// RefBindings - State used to track object reference counts.
1569//===----------------------------------------------------------------------===//
1570
Ted Kremenek2dabd432008-12-05 02:27:51 +00001571typedef llvm::ImmutableMap<SymbolRef, RefVal> RefBindings;
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001572static int RefBIndex = 0;
1573
1574namespace clang {
Ted Kremenekb9d17f92008-08-17 03:20:02 +00001575 template<>
1576 struct GRStateTrait<RefBindings> : public GRStatePartialTrait<RefBindings> {
1577 static inline void* GDMIndex() { return &RefBIndex; }
1578 };
1579}
Ted Kremenek6d348932008-10-21 15:53:15 +00001580
1581//===----------------------------------------------------------------------===//
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001582// AutoreleaseBindings - State used to track objects in autorelease pools.
Ted Kremenek6d348932008-10-21 15:53:15 +00001583//===----------------------------------------------------------------------===//
1584
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001585typedef llvm::ImmutableMap<SymbolRef, unsigned> ARCounts;
1586typedef llvm::ImmutableMap<SymbolRef, ARCounts> ARPoolContents;
1587typedef llvm::ImmutableList<SymbolRef> ARStack;
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00001588
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001589static int AutoRCIndex = 0;
Ted Kremenek6d348932008-10-21 15:53:15 +00001590static int AutoRBIndex = 0;
1591
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001592namespace { class VISIBILITY_HIDDEN AutoreleasePoolContents {}; }
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001593namespace { class VISIBILITY_HIDDEN AutoreleaseStack {}; }
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001594
Ted Kremenek6d348932008-10-21 15:53:15 +00001595namespace clang {
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001596template<> struct GRStateTrait<AutoreleaseStack>
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001597 : public GRStatePartialTrait<ARStack> {
1598 static inline void* GDMIndex() { return &AutoRBIndex; }
1599};
1600
1601template<> struct GRStateTrait<AutoreleasePoolContents>
1602 : public GRStatePartialTrait<ARPoolContents> {
1603 static inline void* GDMIndex() { return &AutoRCIndex; }
1604};
1605} // end clang namespace
Ted Kremenek6d348932008-10-21 15:53:15 +00001606
Ted Kremenek7037ab82009-03-20 17:34:15 +00001607static SymbolRef GetCurrentAutoreleasePool(const GRState* state) {
1608 ARStack stack = state->get<AutoreleaseStack>();
1609 return stack.isEmpty() ? SymbolRef() : stack.getHead();
1610}
1611
1612static GRStateRef SendAutorelease(GRStateRef state, ARCounts::Factory &F,
1613 SymbolRef sym) {
1614
1615 SymbolRef pool = GetCurrentAutoreleasePool(state);
1616 const ARCounts *cnts = state.get<AutoreleasePoolContents>(pool);
1617 ARCounts newCnts(0);
1618
1619 if (cnts) {
1620 const unsigned *cnt = (*cnts).lookup(sym);
1621 newCnts = F.Add(*cnts, sym, cnt ? *cnt + 1 : 1);
1622 }
1623 else
1624 newCnts = F.Add(F.GetEmptyMap(), sym, 1);
1625
1626 return state.set<AutoreleasePoolContents>(pool, newCnts);
1627}
1628
Ted Kremenek13922612008-04-16 20:40:59 +00001629//===----------------------------------------------------------------------===//
1630// Transfer functions.
1631//===----------------------------------------------------------------------===//
1632
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001633namespace {
1634
Ted Kremenek05cbe1a2008-04-09 23:49:11 +00001635class VISIBILITY_HIDDEN CFRefCount : public GRSimpleVals {
Ted Kremenek8dd56462008-04-18 03:39:05 +00001636public:
Ted Kremenekae6814e2008-08-13 21:24:49 +00001637 class BindingsPrinter : public GRState::Printer {
Ted Kremenekf3948042008-03-11 19:44:10 +00001638 public:
Ted Kremenekae6814e2008-08-13 21:24:49 +00001639 virtual void Print(std::ostream& Out, const GRState* state,
1640 const char* nl, const char* sep);
Ted Kremenekf3948042008-03-11 19:44:10 +00001641 };
Ted Kremenek8dd56462008-04-18 03:39:05 +00001642
1643private:
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001644 typedef llvm::DenseMap<const GRExprEngine::NodeTy*, const RetainSummary*>
1645 SummaryLogTy;
1646
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001647 RetainSummaryManager Summaries;
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001648 SummaryLogTy SummaryLog;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001649 const LangOptions& LOpts;
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001650 ARCounts::Factory ARCountFactory;
Ted Kremenekb9d17f92008-08-17 03:20:02 +00001651
Ted Kremenekcf701772009-02-05 06:50:21 +00001652 BugType *useAfterRelease, *releaseNotOwned;
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001653 BugType *deallocGC, *deallocNotOwned;
Ted Kremenekcf701772009-02-05 06:50:21 +00001654 BugType *leakWithinFunction, *leakAtReturn;
Ted Kremenek369de562009-05-09 00:10:05 +00001655 BugType *overAutorelease;
Ted Kremenekcf701772009-02-05 06:50:21 +00001656 BugReporter *BR;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001657
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001658 GRStateRef Update(GRStateRef state, SymbolRef sym, RefVal V, ArgEffect E,
1659 RefVal::Kind& hasErr);
1660
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001661 void ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
1662 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekdb863712008-04-16 22:32:20 +00001663 Expr* NodeExpr, Expr* ErrorExpr,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001664 ExplodedNode<GRState>* Pred,
1665 const GRState* St,
Ted Kremenek2dabd432008-12-05 02:27:51 +00001666 RefVal::Kind hasErr, SymbolRef Sym);
Ted Kremenekdb863712008-04-16 22:32:20 +00001667
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00001668 GRStateRef HandleSymbolDeath(GRStateRef state, SymbolRef sid, RefVal V,
1669 llvm::SmallVectorImpl<SymbolRef> &Leaked);
1670
1671 ExplodedNode<GRState>* ProcessLeaks(GRStateRef state,
1672 llvm::SmallVectorImpl<SymbolRef> &Leaked,
1673 GenericNodeBuilder &Builder,
1674 GRExprEngine &Eng,
1675 ExplodedNode<GRState> *Pred = 0);
Ted Kremenekdb863712008-04-16 22:32:20 +00001676
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001677public:
Ted Kremenek78d46242008-07-22 16:21:24 +00001678 CFRefCount(ASTContext& Ctx, bool gcenabled, const LangOptions& lopts)
Ted Kremenek377e2302008-04-29 05:33:51 +00001679 : Summaries(Ctx, gcenabled),
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001680 LOpts(lopts), useAfterRelease(0), releaseNotOwned(0),
1681 deallocGC(0), deallocNotOwned(0),
Ted Kremenek369de562009-05-09 00:10:05 +00001682 leakWithinFunction(0), leakAtReturn(0), overAutorelease(0), BR(0) {}
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001683
Ted Kremenekcf701772009-02-05 06:50:21 +00001684 virtual ~CFRefCount() {}
Ted Kremenek05cbe1a2008-04-09 23:49:11 +00001685
Ted Kremenekcf118d42009-02-04 23:49:09 +00001686 void RegisterChecks(BugReporter &BR);
Ted Kremenekf3948042008-03-11 19:44:10 +00001687
Ted Kremenek1c72ef02008-08-16 00:49:49 +00001688 virtual void RegisterPrinters(std::vector<GRState::Printer*>& Printers) {
1689 Printers.push_back(new BindingsPrinter());
Ted Kremenekf3948042008-03-11 19:44:10 +00001690 }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001691
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001692 bool isGCEnabled() const { return Summaries.isGCEnabled(); }
Ted Kremenek072192b2008-04-30 23:47:44 +00001693 const LangOptions& getLangOptions() const { return LOpts; }
1694
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001695 const RetainSummary *getSummaryOfNode(const ExplodedNode<GRState> *N) const {
1696 SummaryLogTy::const_iterator I = SummaryLog.find(N);
1697 return I == SummaryLog.end() ? 0 : I->second;
1698 }
1699
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001700 // Calls.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001701
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001702 void EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001703 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001704 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001705 Expr* Ex,
1706 Expr* Receiver,
Ted Kremenek7faca822009-05-04 04:57:00 +00001707 const RetainSummary& Summ,
Ted Kremenek55499762008-06-17 02:43:46 +00001708 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001709 ExplodedNode<GRState>* Pred);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001710
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001711 virtual void EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek199e1a02008-03-12 21:06:49 +00001712 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001713 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001714 CallExpr* CE, SVal L,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001715 ExplodedNode<GRState>* Pred);
Ted Kremenekfa34b332008-04-09 01:10:13 +00001716
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001717
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001718 virtual void EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek85348202008-04-15 23:44:31 +00001719 GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001720 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek85348202008-04-15 23:44:31 +00001721 ObjCMessageExpr* ME,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001722 ExplodedNode<GRState>* Pred);
Ted Kremenek85348202008-04-15 23:44:31 +00001723
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001724 bool EvalObjCMessageExprAux(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek85348202008-04-15 23:44:31 +00001725 GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001726 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek85348202008-04-15 23:44:31 +00001727 ObjCMessageExpr* ME,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001728 ExplodedNode<GRState>* Pred);
Ted Kremenek85348202008-04-15 23:44:31 +00001729
Ted Kremenek41573eb2009-02-14 01:43:44 +00001730 // Stores.
1731 virtual void EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val);
1732
Ted Kremeneke7bd9c22008-04-11 22:25:11 +00001733 // End-of-path.
1734
1735 virtual void EvalEndPath(GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001736 GREndPathNodeBuilder<GRState>& Builder);
Ted Kremeneke7bd9c22008-04-11 22:25:11 +00001737
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001738 virtual void EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek652adc62008-04-24 23:57:27 +00001739 GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001740 GRStmtNodeBuilder<GRState>& Builder,
1741 ExplodedNode<GRState>* Pred,
Ted Kremenek241677a2009-01-21 22:26:05 +00001742 Stmt* S, const GRState* state,
1743 SymbolReaper& SymReaper);
Ted Kremenekf04dced2009-05-08 23:32:51 +00001744
1745 std::pair<ExplodedNode<GRState>*, GRStateRef>
1746 HandleAutoreleaseCounts(GRStateRef state, GenericNodeBuilder Bd,
Ted Kremenek369de562009-05-09 00:10:05 +00001747 ExplodedNode<GRState>* Pred, GRExprEngine &Eng,
1748 SymbolRef Sym, RefVal V, bool &stop);
Ted Kremenek4fd88972008-04-17 18:12:53 +00001749 // Return statements.
1750
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001751 virtual void EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4fd88972008-04-17 18:12:53 +00001752 GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001753 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4fd88972008-04-17 18:12:53 +00001754 ReturnStmt* S,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001755 ExplodedNode<GRState>* Pred);
Ted Kremenekcb612922008-04-18 19:23:43 +00001756
1757 // Assumptions.
1758
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001759 virtual const GRState* EvalAssume(GRStateManager& VMgr,
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001760 const GRState* St, SVal Cond,
Ted Kremenek4323a572008-07-10 22:03:41 +00001761 bool Assumption, bool& isFeasible);
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001762};
1763
1764} // end anonymous namespace
1765
Ted Kremenek7037ab82009-03-20 17:34:15 +00001766static void PrintPool(std::ostream &Out, SymbolRef Sym, const GRState *state) {
1767 Out << ' ';
Ted Kremeneke0e4ebf2009-03-26 03:35:11 +00001768 if (Sym)
1769 Out << Sym->getSymbolID();
Ted Kremenek7037ab82009-03-20 17:34:15 +00001770 else
1771 Out << "<pool>";
1772 Out << ":{";
1773
1774 // Get the contents of the pool.
1775 if (const ARCounts *cnts = state->get<AutoreleasePoolContents>(Sym))
1776 for (ARCounts::iterator J=cnts->begin(), EJ=cnts->end(); J != EJ; ++J)
1777 Out << '(' << J.getKey() << ',' << J.getData() << ')';
1778
1779 Out << '}';
1780}
Ted Kremenek8dd56462008-04-18 03:39:05 +00001781
Ted Kremenekae6814e2008-08-13 21:24:49 +00001782void CFRefCount::BindingsPrinter::Print(std::ostream& Out, const GRState* state,
1783 const char* nl, const char* sep) {
Ted Kremenek7037ab82009-03-20 17:34:15 +00001784
1785
Ted Kremenekae6814e2008-08-13 21:24:49 +00001786
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001787 RefBindings B = state->get<RefBindings>();
Ted Kremenekf3948042008-03-11 19:44:10 +00001788
Ted Kremenekae6814e2008-08-13 21:24:49 +00001789 if (!B.isEmpty())
Ted Kremenekf3948042008-03-11 19:44:10 +00001790 Out << sep << nl;
1791
1792 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
1793 Out << (*I).first << " : ";
1794 (*I).second.print(Out);
1795 Out << nl;
1796 }
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001797
1798 // Print the autorelease stack.
Ted Kremenek7037ab82009-03-20 17:34:15 +00001799 Out << sep << nl << "AR pool stack:";
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001800 ARStack stack = state->get<AutoreleaseStack>();
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001801
Ted Kremenek7037ab82009-03-20 17:34:15 +00001802 PrintPool(Out, SymbolRef(), state); // Print the caller's pool.
1803 for (ARStack::iterator I=stack.begin(), E=stack.end(); I!=E; ++I)
1804 PrintPool(Out, *I, state);
1805
1806 Out << nl;
Ted Kremenekf3948042008-03-11 19:44:10 +00001807}
1808
Ted Kremenekc887d132009-04-29 18:50:19 +00001809//===----------------------------------------------------------------------===//
1810// Error reporting.
1811//===----------------------------------------------------------------------===//
1812
1813namespace {
1814
1815 //===-------------===//
1816 // Bug Descriptions. //
1817 //===-------------===//
1818
1819 class VISIBILITY_HIDDEN CFRefBug : public BugType {
1820 protected:
1821 CFRefCount& TF;
1822
1823 CFRefBug(CFRefCount* tf, const char* name)
1824 : BugType(name, "Memory (Core Foundation/Objective-C)"), TF(*tf) {}
1825 public:
1826
1827 CFRefCount& getTF() { return TF; }
1828 const CFRefCount& getTF() const { return TF; }
1829
1830 // FIXME: Eventually remove.
1831 virtual const char* getDescription() const = 0;
1832
1833 virtual bool isLeak() const { return false; }
1834 };
1835
1836 class VISIBILITY_HIDDEN UseAfterRelease : public CFRefBug {
1837 public:
1838 UseAfterRelease(CFRefCount* tf)
1839 : CFRefBug(tf, "Use-after-release") {}
1840
1841 const char* getDescription() const {
1842 return "Reference-counted object is used after it is released";
1843 }
1844 };
1845
1846 class VISIBILITY_HIDDEN BadRelease : public CFRefBug {
1847 public:
1848 BadRelease(CFRefCount* tf) : CFRefBug(tf, "Bad release") {}
1849
1850 const char* getDescription() const {
1851 return "Incorrect decrement of the reference count of an "
1852 "object is not owned at this point by the caller";
1853 }
1854 };
1855
1856 class VISIBILITY_HIDDEN DeallocGC : public CFRefBug {
1857 public:
Ted Kremenek369de562009-05-09 00:10:05 +00001858 DeallocGC(CFRefCount *tf)
1859 : CFRefBug(tf, "-dealloc called while using garbage collection") {}
Ted Kremenekc887d132009-04-29 18:50:19 +00001860
1861 const char *getDescription() const {
Ted Kremenek369de562009-05-09 00:10:05 +00001862 return "-dealloc called while using garbage collection";
Ted Kremenekc887d132009-04-29 18:50:19 +00001863 }
1864 };
1865
1866 class VISIBILITY_HIDDEN DeallocNotOwned : public CFRefBug {
1867 public:
Ted Kremenek369de562009-05-09 00:10:05 +00001868 DeallocNotOwned(CFRefCount *tf)
1869 : CFRefBug(tf, "-dealloc sent to non-exclusively owned object") {}
Ted Kremenekc887d132009-04-29 18:50:19 +00001870
1871 const char *getDescription() const {
1872 return "-dealloc sent to object that may be referenced elsewhere";
1873 }
1874 };
1875
Ted Kremenek369de562009-05-09 00:10:05 +00001876 class VISIBILITY_HIDDEN OverAutorelease : public CFRefBug {
1877 public:
1878 OverAutorelease(CFRefCount *tf) :
1879 CFRefBug(tf, "Object sent -autorelease too many times") {}
1880
1881 const char *getDescription() const {
1882 return "Object will be sent more -release messages from its containing "
1883 "autorelease pools than it has retain counts";
1884 }
1885 };
1886
Ted Kremenekc887d132009-04-29 18:50:19 +00001887 class VISIBILITY_HIDDEN Leak : public CFRefBug {
1888 const bool isReturn;
1889 protected:
1890 Leak(CFRefCount* tf, const char* name, bool isRet)
1891 : CFRefBug(tf, name), isReturn(isRet) {}
1892 public:
1893
1894 const char* getDescription() const { return ""; }
1895
1896 bool isLeak() const { return true; }
1897 };
1898
1899 class VISIBILITY_HIDDEN LeakAtReturn : public Leak {
1900 public:
1901 LeakAtReturn(CFRefCount* tf, const char* name)
1902 : Leak(tf, name, true) {}
1903 };
1904
1905 class VISIBILITY_HIDDEN LeakWithinFunction : public Leak {
1906 public:
1907 LeakWithinFunction(CFRefCount* tf, const char* name)
1908 : Leak(tf, name, false) {}
1909 };
1910
1911 //===---------===//
1912 // Bug Reports. //
1913 //===---------===//
1914
1915 class VISIBILITY_HIDDEN CFRefReport : public RangedBugReport {
1916 protected:
1917 SymbolRef Sym;
1918 const CFRefCount &TF;
1919 public:
1920 CFRefReport(CFRefBug& D, const CFRefCount &tf,
1921 ExplodedNode<GRState> *n, SymbolRef sym)
1922 : RangedBugReport(D, D.getDescription(), n), Sym(sym), TF(tf) {}
1923
1924 virtual ~CFRefReport() {}
1925
1926 CFRefBug& getBugType() {
1927 return (CFRefBug&) RangedBugReport::getBugType();
1928 }
1929 const CFRefBug& getBugType() const {
1930 return (const CFRefBug&) RangedBugReport::getBugType();
1931 }
1932
1933 virtual void getRanges(BugReporter& BR, const SourceRange*& beg,
1934 const SourceRange*& end) {
1935
1936 if (!getBugType().isLeak())
1937 RangedBugReport::getRanges(BR, beg, end);
1938 else
1939 beg = end = 0;
1940 }
1941
1942 SymbolRef getSymbol() const { return Sym; }
1943
Ted Kremenek8966bc12009-05-06 21:39:49 +00001944 PathDiagnosticPiece* getEndPath(BugReporterContext& BRC,
Ted Kremenekc887d132009-04-29 18:50:19 +00001945 const ExplodedNode<GRState>* N);
1946
1947 std::pair<const char**,const char**> getExtraDescriptiveText();
1948
1949 PathDiagnosticPiece* VisitNode(const ExplodedNode<GRState>* N,
1950 const ExplodedNode<GRState>* PrevN,
Ted Kremenek8966bc12009-05-06 21:39:49 +00001951 BugReporterContext& BRC);
Ted Kremenekc887d132009-04-29 18:50:19 +00001952 };
1953
1954 class VISIBILITY_HIDDEN CFRefLeakReport : public CFRefReport {
1955 SourceLocation AllocSite;
1956 const MemRegion* AllocBinding;
1957 public:
1958 CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
1959 ExplodedNode<GRState> *n, SymbolRef sym,
1960 GRExprEngine& Eng);
1961
Ted Kremenek8966bc12009-05-06 21:39:49 +00001962 PathDiagnosticPiece* getEndPath(BugReporterContext& BRC,
Ted Kremenekc887d132009-04-29 18:50:19 +00001963 const ExplodedNode<GRState>* N);
1964
1965 SourceLocation getLocation() const { return AllocSite; }
1966 };
1967} // end anonymous namespace
1968
1969void CFRefCount::RegisterChecks(BugReporter& BR) {
1970 useAfterRelease = new UseAfterRelease(this);
1971 BR.Register(useAfterRelease);
1972
1973 releaseNotOwned = new BadRelease(this);
1974 BR.Register(releaseNotOwned);
1975
1976 deallocGC = new DeallocGC(this);
1977 BR.Register(deallocGC);
1978
1979 deallocNotOwned = new DeallocNotOwned(this);
1980 BR.Register(deallocNotOwned);
1981
Ted Kremenek369de562009-05-09 00:10:05 +00001982 overAutorelease = new OverAutorelease(this);
1983 BR.Register(overAutorelease);
1984
Ted Kremenekc887d132009-04-29 18:50:19 +00001985 // First register "return" leaks.
1986 const char* name = 0;
1987
1988 if (isGCEnabled())
1989 name = "Leak of returned object when using garbage collection";
1990 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
1991 name = "Leak of returned object when not using garbage collection (GC) in "
1992 "dual GC/non-GC code";
1993 else {
1994 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
1995 name = "Leak of returned object";
1996 }
1997
1998 leakAtReturn = new LeakAtReturn(this, name);
1999 BR.Register(leakAtReturn);
2000
2001 // Second, register leaks within a function/method.
2002 if (isGCEnabled())
2003 name = "Leak of object when using garbage collection";
2004 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2005 name = "Leak of object when not using garbage collection (GC) in "
2006 "dual GC/non-GC code";
2007 else {
2008 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2009 name = "Leak";
2010 }
2011
2012 leakWithinFunction = new LeakWithinFunction(this, name);
2013 BR.Register(leakWithinFunction);
2014
2015 // Save the reference to the BugReporter.
2016 this->BR = &BR;
2017}
2018
2019static const char* Msgs[] = {
2020 // GC only
2021 "Code is compiled to only use garbage collection",
2022 // No GC.
2023 "Code is compiled to use reference counts",
2024 // Hybrid, with GC.
2025 "Code is compiled to use either garbage collection (GC) or reference counts"
2026 " (non-GC). The bug occurs with GC enabled",
2027 // Hybrid, without GC
2028 "Code is compiled to use either garbage collection (GC) or reference counts"
2029 " (non-GC). The bug occurs in non-GC mode"
2030};
2031
2032std::pair<const char**,const char**> CFRefReport::getExtraDescriptiveText() {
2033 CFRefCount& TF = static_cast<CFRefBug&>(getBugType()).getTF();
2034
2035 switch (TF.getLangOptions().getGCMode()) {
2036 default:
2037 assert(false);
2038
2039 case LangOptions::GCOnly:
2040 assert (TF.isGCEnabled());
2041 return std::make_pair(&Msgs[0], &Msgs[0]+1);
2042
2043 case LangOptions::NonGC:
2044 assert (!TF.isGCEnabled());
2045 return std::make_pair(&Msgs[1], &Msgs[1]+1);
2046
2047 case LangOptions::HybridGC:
2048 if (TF.isGCEnabled())
2049 return std::make_pair(&Msgs[2], &Msgs[2]+1);
2050 else
2051 return std::make_pair(&Msgs[3], &Msgs[3]+1);
2052 }
2053}
2054
2055static inline bool contains(const llvm::SmallVectorImpl<ArgEffect>& V,
2056 ArgEffect X) {
2057 for (llvm::SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
2058 I!=E; ++I)
2059 if (*I == X) return true;
2060
2061 return false;
2062}
2063
2064PathDiagnosticPiece* CFRefReport::VisitNode(const ExplodedNode<GRState>* N,
2065 const ExplodedNode<GRState>* PrevN,
Ted Kremenek8966bc12009-05-06 21:39:49 +00002066 BugReporterContext& BRC) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002067
Ted Kremenek8966bc12009-05-06 21:39:49 +00002068 // Check if the type state has changed.
2069 GRStateManager &StMgr = BRC.getStateManager();
Ted Kremenekc887d132009-04-29 18:50:19 +00002070 GRStateRef PrevSt(PrevN->getState(), StMgr);
2071 GRStateRef CurrSt(N->getState(), StMgr);
2072
2073 const RefVal* CurrT = CurrSt.get<RefBindings>(Sym);
2074 if (!CurrT) return NULL;
2075
2076 const RefVal& CurrV = *CurrT;
2077 const RefVal* PrevT = PrevSt.get<RefBindings>(Sym);
2078
2079 // Create a string buffer to constain all the useful things we want
2080 // to tell the user.
2081 std::string sbuf;
2082 llvm::raw_string_ostream os(sbuf);
2083
2084 // This is the allocation site since the previous node had no bindings
2085 // for this symbol.
2086 if (!PrevT) {
2087 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2088
2089 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2090 // Get the name of the callee (if it is available).
2091 SVal X = CurrSt.GetSValAsScalarOrLoc(CE->getCallee());
2092 if (const FunctionDecl* FD = X.getAsFunctionDecl())
2093 os << "Call to function '" << FD->getNameAsString() <<'\'';
2094 else
2095 os << "function call";
2096 }
2097 else {
2098 assert (isa<ObjCMessageExpr>(S));
2099 os << "Method";
2100 }
2101
2102 if (CurrV.getObjKind() == RetEffect::CF) {
2103 os << " returns a Core Foundation object with a ";
2104 }
2105 else {
2106 assert (CurrV.getObjKind() == RetEffect::ObjC);
2107 os << " returns an Objective-C object with a ";
2108 }
2109
2110 if (CurrV.isOwned()) {
2111 os << "+1 retain count (owning reference).";
2112
2113 if (static_cast<CFRefBug&>(getBugType()).getTF().isGCEnabled()) {
2114 assert(CurrV.getObjKind() == RetEffect::CF);
2115 os << " "
2116 "Core Foundation objects are not automatically garbage collected.";
2117 }
2118 }
2119 else {
2120 assert (CurrV.isNotOwned());
2121 os << "+0 retain count (non-owning reference).";
2122 }
2123
Ted Kremenek8966bc12009-05-06 21:39:49 +00002124 PathDiagnosticLocation Pos(S, BRC.getSourceManager());
Ted Kremenekc887d132009-04-29 18:50:19 +00002125 return new PathDiagnosticEventPiece(Pos, os.str());
2126 }
2127
2128 // Gather up the effects that were performed on the object at this
2129 // program point
2130 llvm::SmallVector<ArgEffect, 2> AEffects;
2131
Ted Kremenek8966bc12009-05-06 21:39:49 +00002132 if (const RetainSummary *Summ =
2133 TF.getSummaryOfNode(BRC.getNodeResolver().getOriginalNode(N))) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002134 // We only have summaries attached to nodes after evaluating CallExpr and
2135 // ObjCMessageExprs.
2136 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2137
2138 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2139 // Iterate through the parameter expressions and see if the symbol
2140 // was ever passed as an argument.
2141 unsigned i = 0;
2142
2143 for (CallExpr::arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
2144 AI!=AE; ++AI, ++i) {
2145
2146 // Retrieve the value of the argument. Is it the symbol
2147 // we are interested in?
2148 if (CurrSt.GetSValAsScalarOrLoc(*AI).getAsLocSymbol() != Sym)
2149 continue;
2150
2151 // We have an argument. Get the effect!
2152 AEffects.push_back(Summ->getArg(i));
2153 }
2154 }
2155 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
2156 if (Expr *receiver = ME->getReceiver())
2157 if (CurrSt.GetSValAsScalarOrLoc(receiver).getAsLocSymbol() == Sym) {
2158 // The symbol we are tracking is the receiver.
2159 AEffects.push_back(Summ->getReceiverEffect());
2160 }
2161 }
2162 }
2163
2164 do {
2165 // Get the previous type state.
2166 RefVal PrevV = *PrevT;
2167
2168 // Specially handle -dealloc.
2169 if (!TF.isGCEnabled() && contains(AEffects, Dealloc)) {
2170 // Determine if the object's reference count was pushed to zero.
2171 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2172 // We may not have transitioned to 'release' if we hit an error.
2173 // This case is handled elsewhere.
2174 if (CurrV.getKind() == RefVal::Released) {
Ted Kremenekf21332e2009-05-08 20:01:42 +00002175 assert(CurrV.getCombinedCounts() == 0);
Ted Kremenekc887d132009-04-29 18:50:19 +00002176 os << "Object released by directly sending the '-dealloc' message";
2177 break;
2178 }
2179 }
2180
2181 // Specially handle CFMakeCollectable and friends.
2182 if (contains(AEffects, MakeCollectable)) {
2183 // Get the name of the function.
2184 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2185 SVal X = CurrSt.GetSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee());
2186 const FunctionDecl* FD = X.getAsFunctionDecl();
2187 const std::string& FName = FD->getNameAsString();
2188
2189 if (TF.isGCEnabled()) {
2190 // Determine if the object's reference count was pushed to zero.
2191 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2192
2193 os << "In GC mode a call to '" << FName
2194 << "' decrements an object's retain count and registers the "
2195 "object with the garbage collector. ";
2196
2197 if (CurrV.getKind() == RefVal::Released) {
2198 assert(CurrV.getCount() == 0);
2199 os << "Since it now has a 0 retain count the object can be "
2200 "automatically collected by the garbage collector.";
2201 }
2202 else
2203 os << "An object must have a 0 retain count to be garbage collected. "
2204 "After this call its retain count is +" << CurrV.getCount()
2205 << '.';
2206 }
2207 else
2208 os << "When GC is not enabled a call to '" << FName
2209 << "' has no effect on its argument.";
2210
2211 // Nothing more to say.
2212 break;
2213 }
2214
2215 // Determine if the typestate has changed.
2216 if (!(PrevV == CurrV))
2217 switch (CurrV.getKind()) {
2218 case RefVal::Owned:
2219 case RefVal::NotOwned:
2220
Ted Kremenekf21332e2009-05-08 20:01:42 +00002221 if (PrevV.getCount() == CurrV.getCount()) {
2222 // Did an autorelease message get sent?
2223 if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
2224 return 0;
2225
2226 assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount());
2227 os << "Object added to autorelease pool.";
2228 break;
2229 }
Ted Kremenekc887d132009-04-29 18:50:19 +00002230
2231 if (PrevV.getCount() > CurrV.getCount())
2232 os << "Reference count decremented.";
2233 else
2234 os << "Reference count incremented.";
2235
2236 if (unsigned Count = CurrV.getCount())
2237 os << " The object now has a +" << Count << " retain count.";
2238
2239 if (PrevV.getKind() == RefVal::Released) {
2240 assert(TF.isGCEnabled() && CurrV.getCount() > 0);
2241 os << " The object is not eligible for garbage collection until the "
2242 "retain count reaches 0 again.";
2243 }
2244
2245 break;
2246
2247 case RefVal::Released:
2248 os << "Object released.";
2249 break;
2250
2251 case RefVal::ReturnedOwned:
2252 os << "Object returned to caller as an owning reference (single retain "
2253 "count transferred to caller).";
2254 break;
2255
2256 case RefVal::ReturnedNotOwned:
2257 os << "Object returned to caller with a +0 (non-owning) retain count.";
2258 break;
2259
2260 default:
2261 return NULL;
2262 }
2263
2264 // Emit any remaining diagnostics for the argument effects (if any).
2265 for (llvm::SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
2266 E=AEffects.end(); I != E; ++I) {
2267
2268 // A bunch of things have alternate behavior under GC.
2269 if (TF.isGCEnabled())
2270 switch (*I) {
2271 default: break;
2272 case Autorelease:
2273 os << "In GC mode an 'autorelease' has no effect.";
2274 continue;
2275 case IncRefMsg:
2276 os << "In GC mode the 'retain' message has no effect.";
2277 continue;
2278 case DecRefMsg:
2279 os << "In GC mode the 'release' message has no effect.";
2280 continue;
2281 }
2282 }
2283 } while(0);
2284
2285 if (os.str().empty())
2286 return 0; // We have nothing to say!
2287
2288 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
Ted Kremenek8966bc12009-05-06 21:39:49 +00002289 PathDiagnosticLocation Pos(S, BRC.getSourceManager());
Ted Kremenekc887d132009-04-29 18:50:19 +00002290 PathDiagnosticPiece* P = new PathDiagnosticEventPiece(Pos, os.str());
2291
2292 // Add the range by scanning the children of the statement for any bindings
2293 // to Sym.
2294 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I)
2295 if (Expr* Exp = dyn_cast_or_null<Expr>(*I))
2296 if (CurrSt.GetSValAsScalarOrLoc(Exp).getAsLocSymbol() == Sym) {
2297 P->addRange(Exp->getSourceRange());
2298 break;
2299 }
2300
2301 return P;
2302}
2303
2304namespace {
2305 class VISIBILITY_HIDDEN FindUniqueBinding :
2306 public StoreManager::BindingsHandler {
2307 SymbolRef Sym;
2308 const MemRegion* Binding;
2309 bool First;
2310
2311 public:
2312 FindUniqueBinding(SymbolRef sym) : Sym(sym), Binding(0), First(true) {}
2313
2314 bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
2315 SVal val) {
2316
2317 SymbolRef SymV = val.getAsSymbol();
2318 if (!SymV || SymV != Sym)
2319 return true;
2320
2321 if (Binding) {
2322 First = false;
2323 return false;
2324 }
2325 else
2326 Binding = R;
2327
2328 return true;
2329 }
2330
2331 operator bool() { return First && Binding; }
2332 const MemRegion* getRegion() { return Binding; }
2333 };
2334}
2335
2336static std::pair<const ExplodedNode<GRState>*,const MemRegion*>
2337GetAllocationSite(GRStateManager& StateMgr, const ExplodedNode<GRState>* N,
2338 SymbolRef Sym) {
2339
2340 // Find both first node that referred to the tracked symbol and the
2341 // memory location that value was store to.
2342 const ExplodedNode<GRState>* Last = N;
2343 const MemRegion* FirstBinding = 0;
2344
2345 while (N) {
2346 const GRState* St = N->getState();
2347 RefBindings B = St->get<RefBindings>();
2348
2349 if (!B.lookup(Sym))
2350 break;
2351
2352 FindUniqueBinding FB(Sym);
2353 StateMgr.iterBindings(St, FB);
2354 if (FB) FirstBinding = FB.getRegion();
2355
2356 Last = N;
2357 N = N->pred_empty() ? NULL : *(N->pred_begin());
2358 }
2359
2360 return std::make_pair(Last, FirstBinding);
2361}
2362
2363PathDiagnosticPiece*
Ted Kremenek8966bc12009-05-06 21:39:49 +00002364CFRefReport::getEndPath(BugReporterContext& BRC,
2365 const ExplodedNode<GRState>* EndN) {
2366 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenekc887d132009-04-29 18:50:19 +00002367 // assigned to different variables, etc.
Ted Kremenek8966bc12009-05-06 21:39:49 +00002368 BRC.addNotableSymbol(Sym);
2369 return RangedBugReport::getEndPath(BRC, EndN);
Ted Kremenekc887d132009-04-29 18:50:19 +00002370}
2371
2372PathDiagnosticPiece*
Ted Kremenek8966bc12009-05-06 21:39:49 +00002373CFRefLeakReport::getEndPath(BugReporterContext& BRC,
2374 const ExplodedNode<GRState>* EndN){
Ted Kremenekc887d132009-04-29 18:50:19 +00002375
Ted Kremenek8966bc12009-05-06 21:39:49 +00002376 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenekc887d132009-04-29 18:50:19 +00002377 // assigned to different variables, etc.
Ted Kremenek8966bc12009-05-06 21:39:49 +00002378 BRC.addNotableSymbol(Sym);
Ted Kremenekc887d132009-04-29 18:50:19 +00002379
2380 // We are reporting a leak. Walk up the graph to get to the first node where
2381 // the symbol appeared, and also get the first VarDecl that tracked object
2382 // is stored to.
2383 const ExplodedNode<GRState>* AllocNode = 0;
2384 const MemRegion* FirstBinding = 0;
2385
2386 llvm::tie(AllocNode, FirstBinding) =
Ted Kremenekf04dced2009-05-08 23:32:51 +00002387 GetAllocationSite(BRC.getStateManager(), EndN, Sym);
Ted Kremenekc887d132009-04-29 18:50:19 +00002388
2389 // Get the allocate site.
2390 assert(AllocNode);
2391 Stmt* FirstStmt = cast<PostStmt>(AllocNode->getLocation()).getStmt();
2392
Ted Kremenek8966bc12009-05-06 21:39:49 +00002393 SourceManager& SMgr = BRC.getSourceManager();
Ted Kremenekc887d132009-04-29 18:50:19 +00002394 unsigned AllocLine =SMgr.getInstantiationLineNumber(FirstStmt->getLocStart());
2395
2396 // Compute an actual location for the leak. Sometimes a leak doesn't
2397 // occur at an actual statement (e.g., transition between blocks; end
2398 // of function) so we need to walk the graph and compute a real location.
2399 const ExplodedNode<GRState>* LeakN = EndN;
2400 PathDiagnosticLocation L;
2401
2402 while (LeakN) {
2403 ProgramPoint P = LeakN->getLocation();
2404
2405 if (const PostStmt *PS = dyn_cast<PostStmt>(&P)) {
2406 L = PathDiagnosticLocation(PS->getStmt()->getLocStart(), SMgr);
2407 break;
2408 }
2409 else if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
2410 if (const Stmt* Term = BE->getSrc()->getTerminator()) {
2411 L = PathDiagnosticLocation(Term->getLocStart(), SMgr);
2412 break;
2413 }
2414 }
2415
2416 LeakN = LeakN->succ_empty() ? 0 : *(LeakN->succ_begin());
2417 }
2418
2419 if (!L.isValid()) {
Ted Kremenek8966bc12009-05-06 21:39:49 +00002420 const Decl &D = BRC.getCodeDecl();
2421 L = PathDiagnosticLocation(D.getBodyRBrace(BRC.getASTContext()), SMgr);
Ted Kremenekc887d132009-04-29 18:50:19 +00002422 }
2423
2424 std::string sbuf;
2425 llvm::raw_string_ostream os(sbuf);
2426
2427 os << "Object allocated on line " << AllocLine;
2428
2429 if (FirstBinding)
2430 os << " and stored into '" << FirstBinding->getString() << '\'';
2431
2432 // Get the retain count.
2433 const RefVal* RV = EndN->getState()->get<RefBindings>(Sym);
2434
2435 if (RV->getKind() == RefVal::ErrorLeakReturned) {
2436 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
2437 // ojbects. Only "copy", "alloc", "retain" and "new" transfer ownership
2438 // to the caller for NS objects.
Ted Kremenek8966bc12009-05-06 21:39:49 +00002439 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(BRC.getCodeDecl());
Ted Kremenekc887d132009-04-29 18:50:19 +00002440 os << " is returned from a method whose name ('"
Ted Kremeneka8833552009-04-29 23:03:22 +00002441 << MD.getSelector().getAsString()
Ted Kremenekc887d132009-04-29 18:50:19 +00002442 << "') does not contain 'copy' or otherwise starts with"
2443 " 'new' or 'alloc'. This violates the naming convention rules given"
Ted Kremenek8987a022009-04-29 22:25:52 +00002444 " in the Memory Management Guide for Cocoa (object leaked)";
Ted Kremenekc887d132009-04-29 18:50:19 +00002445 }
2446 else
2447 os << " is no longer referenced after this point and has a retain count of"
Ted Kremenek8987a022009-04-29 22:25:52 +00002448 " +" << RV->getCount() << " (object leaked)";
Ted Kremenekc887d132009-04-29 18:50:19 +00002449
2450 return new PathDiagnosticEventPiece(L, os.str());
2451}
2452
2453
2454CFRefLeakReport::CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2455 ExplodedNode<GRState> *n,
2456 SymbolRef sym, GRExprEngine& Eng)
2457: CFRefReport(D, tf, n, sym)
2458{
2459
2460 // Most bug reports are cached at the location where they occured.
2461 // With leaks, we want to unique them by the location where they were
2462 // allocated, and only report a single path. To do this, we need to find
2463 // the allocation site of a piece of tracked memory, which we do via a
2464 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2465 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2466 // that all ancestor nodes that represent the allocation site have the
2467 // same SourceLocation.
2468 const ExplodedNode<GRState>* AllocNode = 0;
2469
2470 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding.
Ted Kremenekf04dced2009-05-08 23:32:51 +00002471 GetAllocationSite(Eng.getStateManager(), getEndNode(), getSymbol());
Ted Kremenekc887d132009-04-29 18:50:19 +00002472
2473 // Get the SourceLocation for the allocation site.
2474 ProgramPoint P = AllocNode->getLocation();
2475 AllocSite = cast<PostStmt>(P).getStmt()->getLocStart();
2476
2477 // Fill in the description of the bug.
2478 Description.clear();
2479 llvm::raw_string_ostream os(Description);
2480 SourceManager& SMgr = Eng.getContext().getSourceManager();
2481 unsigned AllocLine = SMgr.getInstantiationLineNumber(AllocSite);
Ted Kremenekdd924e22009-05-02 19:05:19 +00002482 os << "Potential leak ";
2483 if (tf.isGCEnabled()) {
2484 os << "(when using garbage collection) ";
2485 }
2486 os << "of an object allocated on line " << AllocLine;
Ted Kremenekc887d132009-04-29 18:50:19 +00002487
2488 // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2489 if (AllocBinding)
2490 os << " and stored into '" << AllocBinding->getString() << '\'';
2491}
2492
2493//===----------------------------------------------------------------------===//
2494// Main checker logic.
2495//===----------------------------------------------------------------------===//
2496
Ted Kremenek553cf182008-06-25 21:21:56 +00002497/// GetReturnType - Used to get the return type of a message expression or
2498/// function call with the intention of affixing that type to a tracked symbol.
2499/// While the the return type can be queried directly from RetEx, when
2500/// invoking class methods we augment to the return type to be that of
2501/// a pointer to the class (as opposed it just being id).
2502static QualType GetReturnType(Expr* RetE, ASTContext& Ctx) {
2503
2504 QualType RetTy = RetE->getType();
2505
2506 // FIXME: We aren't handling id<...>.
Chris Lattner8b51fd72008-07-26 22:36:27 +00002507 const PointerType* PT = RetTy->getAsPointerType();
Ted Kremenek553cf182008-06-25 21:21:56 +00002508 if (!PT)
2509 return RetTy;
2510
2511 // If RetEx is not a message expression just return its type.
2512 // If RetEx is a message expression, return its types if it is something
2513 /// more specific than id.
2514
2515 ObjCMessageExpr* ME = dyn_cast<ObjCMessageExpr>(RetE);
2516
Steve Naroff389bf462009-02-12 17:52:19 +00002517 if (!ME || !Ctx.isObjCIdStructType(PT->getPointeeType()))
Ted Kremenek553cf182008-06-25 21:21:56 +00002518 return RetTy;
2519
2520 ObjCInterfaceDecl* D = ME->getClassInfo().first;
2521
2522 // At this point we know the return type of the message expression is id.
2523 // If we have an ObjCInterceDecl, we know this is a call to a class method
2524 // whose type we can resolve. In such cases, promote the return type to
2525 // Class*.
2526 return !D ? RetTy : Ctx.getPointerType(Ctx.getObjCInterfaceType(D));
2527}
2528
2529
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002530void CFRefCount::EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002531 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002532 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002533 Expr* Ex,
2534 Expr* Receiver,
Ted Kremenek7faca822009-05-04 04:57:00 +00002535 const RetainSummary& Summ,
Zhongxing Xu369f4472009-04-20 05:24:46 +00002536 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002537 ExplodedNode<GRState>* Pred) {
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002538
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00002539 // Get the state.
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002540 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenekf9790ae2008-10-24 20:32:50 +00002541 ASTContext& Ctx = Eng.getStateManager().getContext();
Ted Kremenek14993892008-05-06 02:41:27 +00002542
2543 // Evaluate the effect of the arguments.
Ted Kremenek9ed18e62008-04-16 04:28:53 +00002544 RefVal::Kind hasErr = (RefVal::Kind) 0;
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002545 unsigned idx = 0;
Ted Kremenekbcf50ad2008-04-11 18:40:51 +00002546 Expr* ErrorExpr = NULL;
Ted Kremenek2dabd432008-12-05 02:27:51 +00002547 SymbolRef ErrorSym = 0;
Ted Kremenekbcf50ad2008-04-11 18:40:51 +00002548
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002549 for (ExprIterator I = arg_beg; I != arg_end; ++I, ++idx) {
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00002550 SVal V = state.GetSValAsScalarOrLoc(*I);
Ted Kremenek94c96982009-03-03 22:06:47 +00002551 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00002552
Ted Kremeneke0e4ebf2009-03-26 03:35:11 +00002553 if (Sym)
Ted Kremenek4d3957d2009-02-24 19:15:11 +00002554 if (RefBindings::data_type* T = state.get<RefBindings>(Sym)) {
Ted Kremenek7faca822009-05-04 04:57:00 +00002555 state = Update(state, Sym, *T, Summ.getArg(idx), hasErr);
Ted Kremenek4d3957d2009-02-24 19:15:11 +00002556 if (hasErr) {
Ted Kremenekbcf50ad2008-04-11 18:40:51 +00002557 ErrorExpr = *I;
Ted Kremeneke8fdc832008-07-07 16:21:19 +00002558 ErrorSym = Sym;
Ted Kremenekbcf50ad2008-04-11 18:40:51 +00002559 break;
Ted Kremenek94c96982009-03-03 22:06:47 +00002560 }
2561 continue;
Ted Kremenek4d3957d2009-02-24 19:15:11 +00002562 }
Ted Kremenek070a8252008-07-09 18:11:16 +00002563
Ted Kremenek94c96982009-03-03 22:06:47 +00002564 if (isa<Loc>(V)) {
2565 if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(&V)) {
Ted Kremenek7faca822009-05-04 04:57:00 +00002566 if (Summ.getArg(idx) == DoNothingByRef)
Ted Kremenek070a8252008-07-09 18:11:16 +00002567 continue;
2568
2569 // Invalidate the value of the variable passed by reference.
Ted Kremenek8c5633e2008-07-03 23:26:32 +00002570
2571 // FIXME: Either this logic should also be replicated in GRSimpleVals
2572 // or should be pulled into a separate "constraint engine."
Ted Kremenek070a8252008-07-09 18:11:16 +00002573
Ted Kremenek8c5633e2008-07-03 23:26:32 +00002574 // FIXME: We can have collisions on the conjured symbol if the
2575 // expression *I also creates conjured symbols. We probably want
2576 // to identify conjured symbols by an expression pair: the enclosing
2577 // expression (the context) and the expression itself. This should
Ted Kremenek070a8252008-07-09 18:11:16 +00002578 // disambiguate conjured symbols.
Ted Kremenek9e240492008-10-04 05:50:14 +00002579
Ted Kremenek993f1c72008-10-17 20:28:54 +00002580 const TypedRegion* R = dyn_cast<TypedRegion>(MR->getRegion());
Zhongxing Xuf82af1e2009-04-29 02:30:09 +00002581
Ted Kremenek42530512009-05-06 18:19:24 +00002582 if (R) {
2583 // Are we dealing with an ElementRegion? If the element type is
2584 // a basic integer type (e.g., char, int) and the underying region
2585 // is also typed then strip off the ElementRegion.
2586 // FIXME: We really need to think about this for the general case
2587 // as sometimes we are reasoning about arrays and other times
2588 // about (char*), etc., is just a form of passing raw bytes.
2589 // e.g., void *p = alloca(); foo((char*)p);
2590 if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
2591 // Checking for 'integral type' is probably too promiscuous, but
2592 // we'll leave it in for now until we have a systematic way of
2593 // handling all of these cases. Eventually we need to come up
2594 // with an interface to StoreManager so that this logic can be
2595 // approriately delegated to the respective StoreManagers while
2596 // still allowing us to do checker-specific logic (e.g.,
2597 // invalidating reference counts), probably via callbacks.
2598 if (ER->getElementType()->isIntegralType())
2599 if (const TypedRegion *superReg =
2600 dyn_cast<TypedRegion>(ER->getSuperRegion()))
2601 R = superReg;
2602 // FIXME: What about layers of ElementRegions?
2603 }
2604
Ted Kremenek40e86d92008-12-18 23:34:57 +00002605 // Is the invalidated variable something that we were tracking?
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00002606 SymbolRef Sym = state.GetSValAsScalarOrLoc(R).getAsLocSymbol();
Ted Kremenek40e86d92008-12-18 23:34:57 +00002607
Ted Kremenekd104a092009-03-04 22:56:43 +00002608 // Remove any existing reference-count binding.
Ted Kremeneke0e4ebf2009-03-26 03:35:11 +00002609 if (Sym) state = state.remove<RefBindings>(Sym);
Ted Kremenek9e240492008-10-04 05:50:14 +00002610
Ted Kremenekd104a092009-03-04 22:56:43 +00002611 if (R->isBoundable(Ctx)) {
2612 // Set the value of the variable to be a conjured symbol.
2613 unsigned Count = Builder.getCurrentBlockCount();
Zhongxing Xuff697822009-05-09 00:50:33 +00002614 QualType T = R->getObjectType(Ctx);
Ted Kremenekd104a092009-03-04 22:56:43 +00002615
Zhongxing Xu51ae7902009-04-09 06:03:54 +00002616 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())){
Ted Kremenek8d7f5482009-04-09 22:22:44 +00002617 ValueManager &ValMgr = Eng.getValueManager();
2618 SVal V = ValMgr.getConjuredSymbolVal(*I, T, Count);
Zhongxing Xu51ae7902009-04-09 06:03:54 +00002619 state = state.BindLoc(Loc::MakeVal(R), V);
Ted Kremenekd104a092009-03-04 22:56:43 +00002620 }
2621 else if (const RecordType *RT = T->getAsStructureType()) {
2622 // Handle structs in a not so awesome way. Here we just
2623 // eagerly bind new symbols to the fields. In reality we
2624 // should have the store manager handle this. The idea is just
2625 // to prototype some basic functionality here. All of this logic
2626 // should one day soon just go away.
2627 const RecordDecl *RD = RT->getDecl()->getDefinition(Ctx);
2628
2629 // No record definition. There is nothing we can do.
2630 if (!RD)
2631 continue;
2632
2633 MemRegionManager &MRMgr = state.getManager().getRegionManager();
2634
2635 // Iterate through the fields and construct new symbols.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002636 for (RecordDecl::field_iterator FI=RD->field_begin(Ctx),
2637 FE=RD->field_end(Ctx); FI!=FE; ++FI) {
Ted Kremenekd104a092009-03-04 22:56:43 +00002638
2639 // For now just handle scalar fields.
2640 FieldDecl *FD = *FI;
2641 QualType FT = FD->getType();
2642
2643 if (Loc::IsLocType(FT) ||
Ted Kremenek8d7f5482009-04-09 22:22:44 +00002644 (FT->isIntegerType() && FT->isScalarType())) {
Ted Kremenekd104a092009-03-04 22:56:43 +00002645 const FieldRegion* FR = MRMgr.getFieldRegion(FD, R);
Ted Kremenek8d7f5482009-04-09 22:22:44 +00002646 ValueManager &ValMgr = Eng.getValueManager();
2647 SVal V = ValMgr.getConjuredSymbolVal(*I, FT, Count);
Zhongxing Xu6782f752009-04-09 06:32:20 +00002648 state = state.BindLoc(Loc::MakeVal(FR), V);
Ted Kremenekd104a092009-03-04 22:56:43 +00002649 }
2650 }
2651 }
2652 else {
2653 // Just blast away other values.
2654 state = state.BindLoc(*MR, UnknownVal());
2655 }
Ted Kremenekfd301942008-10-17 22:23:12 +00002656 }
Ted Kremenek9e240492008-10-04 05:50:14 +00002657 }
2658 else
Ted Kremeneka441b7e2008-11-12 19:22:09 +00002659 state = state.BindLoc(*MR, UnknownVal());
Ted Kremenek8c5633e2008-07-03 23:26:32 +00002660 }
2661 else {
2662 // Nuke all other arguments passed by reference.
Zhongxing Xu1c96b242008-10-17 05:57:07 +00002663 state = state.Unbind(cast<Loc>(V));
Ted Kremenek8c5633e2008-07-03 23:26:32 +00002664 }
Ted Kremenekb8873552008-04-11 20:51:02 +00002665 }
Zhongxing Xu1c96b242008-10-17 05:57:07 +00002666 else if (isa<nonloc::LocAsInteger>(V))
2667 state = state.Unbind(cast<nonloc::LocAsInteger>(V).getLoc());
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002668 }
Ted Kremenek9ed18e62008-04-16 04:28:53 +00002669
Ted Kremenek553cf182008-06-25 21:21:56 +00002670 // Evaluate the effect on the message receiver.
Ted Kremenek14993892008-05-06 02:41:27 +00002671 if (!ErrorExpr && Receiver) {
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00002672 SymbolRef Sym = state.GetSValAsScalarOrLoc(Receiver).getAsLocSymbol();
Ted Kremeneke0e4ebf2009-03-26 03:35:11 +00002673 if (Sym) {
Ted Kremenek4d3957d2009-02-24 19:15:11 +00002674 if (const RefVal* T = state.get<RefBindings>(Sym)) {
Ted Kremenek7faca822009-05-04 04:57:00 +00002675 state = Update(state, Sym, *T, Summ.getReceiverEffect(), hasErr);
Ted Kremenek4d3957d2009-02-24 19:15:11 +00002676 if (hasErr) {
Ted Kremenek14993892008-05-06 02:41:27 +00002677 ErrorExpr = Receiver;
Ted Kremeneke8fdc832008-07-07 16:21:19 +00002678 ErrorSym = Sym;
Ted Kremenek14993892008-05-06 02:41:27 +00002679 }
Ted Kremenek4d3957d2009-02-24 19:15:11 +00002680 }
Ted Kremenek14993892008-05-06 02:41:27 +00002681 }
2682 }
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002683
Ted Kremenek553cf182008-06-25 21:21:56 +00002684 // Process any errors.
Ted Kremenek9ed18e62008-04-16 04:28:53 +00002685 if (hasErr) {
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002686 ProcessNonLeakError(Dst, Builder, Ex, ErrorExpr, Pred, state,
Ted Kremenek8dd56462008-04-18 03:39:05 +00002687 hasErr, ErrorSym);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002688 return;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002689 }
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002690
Ted Kremenek70a733e2008-07-18 17:24:20 +00002691 // Consult the summary for the return value.
Ted Kremenek7faca822009-05-04 04:57:00 +00002692 RetEffect RE = Summ.getRetEffect();
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002693
2694 switch (RE.getKind()) {
2695 default:
2696 assert (false && "Unhandled RetEffect."); break;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002697
Ted Kremenekfd301942008-10-17 22:23:12 +00002698 case RetEffect::NoRet: {
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002699
Ted Kremenekf9561e52008-04-11 20:23:24 +00002700 // Make up a symbol for the return value (not reference counted).
Ted Kremenekb8873552008-04-11 20:51:02 +00002701 // FIXME: This is basically copy-and-paste from GRSimpleVals. We
2702 // should compose behavior, not copy it.
Ted Kremenekf9561e52008-04-11 20:23:24 +00002703
Ted Kremenekfd301942008-10-17 22:23:12 +00002704 // FIXME: We eventually should handle structs and other compound types
2705 // that are returned by value.
2706
2707 QualType T = Ex->getType();
2708
Ted Kremenek062e2f92008-11-13 06:10:40 +00002709 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())) {
Ted Kremenekf9561e52008-04-11 20:23:24 +00002710 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenek8d7f5482009-04-09 22:22:44 +00002711 ValueManager &ValMgr = Eng.getValueManager();
2712 SVal X = ValMgr.getConjuredSymbolVal(Ex, T, Count);
Ted Kremeneka441b7e2008-11-12 19:22:09 +00002713 state = state.BindExpr(Ex, X, false);
Ted Kremenekf9561e52008-04-11 20:23:24 +00002714 }
2715
Ted Kremenek940b1d82008-04-10 23:44:06 +00002716 break;
Ted Kremenekfd301942008-10-17 22:23:12 +00002717 }
Ted Kremenek940b1d82008-04-10 23:44:06 +00002718
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002719 case RetEffect::Alias: {
Ted Kremenek553cf182008-06-25 21:21:56 +00002720 unsigned idx = RE.getIndex();
Ted Kremenek55499762008-06-17 02:43:46 +00002721 assert (arg_end >= arg_beg);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002722 assert (idx < (unsigned) (arg_end - arg_beg));
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00002723 SVal V = state.GetSValAsScalarOrLoc(*(arg_beg+idx));
Ted Kremeneka441b7e2008-11-12 19:22:09 +00002724 state = state.BindExpr(Ex, V, false);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002725 break;
2726 }
2727
Ted Kremenek14993892008-05-06 02:41:27 +00002728 case RetEffect::ReceiverAlias: {
2729 assert (Receiver);
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00002730 SVal V = state.GetSValAsScalarOrLoc(Receiver);
Ted Kremeneka441b7e2008-11-12 19:22:09 +00002731 state = state.BindExpr(Ex, V, false);
Ted Kremenek14993892008-05-06 02:41:27 +00002732 break;
2733 }
2734
Ted Kremeneka7344702008-06-23 18:02:52 +00002735 case RetEffect::OwnedAllocatedSymbol:
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002736 case RetEffect::OwnedSymbol: {
2737 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenek044b6f02009-04-09 16:13:17 +00002738 ValueManager &ValMgr = Eng.getValueManager();
2739 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
2740 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
2741 state = state.set<RefBindings>(Sym, RefVal::makeOwned(RE.getObjKind(),
2742 RetT));
2743 state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenek25d01ba2009-03-09 22:46:49 +00002744
2745 // FIXME: Add a flag to the checker where allocations are assumed to
2746 // *not fail.
2747#if 0
Ted Kremenekb2bf7cd2009-01-28 22:27:59 +00002748 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) {
2749 bool isFeasible;
2750 state = state.Assume(loc::SymbolVal(Sym), true, isFeasible);
2751 assert(isFeasible && "Cannot assume fresh symbol is non-null.");
2752 }
Ted Kremenek25d01ba2009-03-09 22:46:49 +00002753#endif
Ted Kremeneka7344702008-06-23 18:02:52 +00002754
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002755 break;
2756 }
Ted Kremeneke798e7c2009-04-27 19:14:45 +00002757
2758 case RetEffect::GCNotOwnedSymbol:
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002759 case RetEffect::NotOwnedSymbol: {
2760 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenek044b6f02009-04-09 16:13:17 +00002761 ValueManager &ValMgr = Eng.getValueManager();
2762 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
2763 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
2764 state = state.set<RefBindings>(Sym, RefVal::makeNotOwned(RE.getObjKind(),
2765 RetT));
2766 state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002767 break;
2768 }
2769 }
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002770
Ted Kremenekf5b34b12009-02-18 02:00:25 +00002771 // Generate a sink node if we are at the end of a path.
2772 GRExprEngine::NodeTy *NewNode =
Ted Kremenek7faca822009-05-04 04:57:00 +00002773 Summ.isEndPath() ? Builder.MakeSinkNode(Dst, Ex, Pred, state)
2774 : Builder.MakeNode(Dst, Ex, Pred, state);
Ted Kremenekf5b34b12009-02-18 02:00:25 +00002775
2776 // Annotate the edge with summary we used.
Ted Kremenek7faca822009-05-04 04:57:00 +00002777 if (NewNode) SummaryLog[NewNode] = &Summ;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002778}
2779
2780
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002781void CFRefCount::EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002782 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002783 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu1c96b242008-10-17 05:57:07 +00002784 CallExpr* CE, SVal L,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002785 ExplodedNode<GRState>* Pred) {
Zhongxing Xu369f4472009-04-20 05:24:46 +00002786 const FunctionDecl* FD = L.getAsFunctionDecl();
Ted Kremenek7faca822009-05-04 04:57:00 +00002787 RetainSummary* Summ = !FD ? Summaries.getDefaultSummary()
Zhongxing Xu369f4472009-04-20 05:24:46 +00002788 : Summaries.getSummary(const_cast<FunctionDecl*>(FD));
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002789
Ted Kremenek7faca822009-05-04 04:57:00 +00002790 assert(Summ);
2791 EvalSummary(Dst, Eng, Builder, CE, 0, *Summ,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002792 CE->arg_begin(), CE->arg_end(), Pred);
Ted Kremenek2fff37e2008-03-06 00:08:09 +00002793}
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00002794
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002795void CFRefCount::EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek85348202008-04-15 23:44:31 +00002796 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002797 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek85348202008-04-15 23:44:31 +00002798 ObjCMessageExpr* ME,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002799 ExplodedNode<GRState>* Pred) {
Ted Kremenek7faca822009-05-04 04:57:00 +00002800 RetainSummary* Summ = 0;
Ted Kremenek9040c652008-05-01 21:31:50 +00002801
Ted Kremenek553cf182008-06-25 21:21:56 +00002802 if (Expr* Receiver = ME->getReceiver()) {
2803 // We need the type-information of the tracked receiver object
2804 // Retrieve it from the state.
2805 ObjCInterfaceDecl* ID = 0;
2806
2807 // FIXME: Wouldn't it be great if this code could be reduced? It's just
2808 // a chain of lookups.
Ted Kremenek8711c032009-04-29 05:04:30 +00002809 // FIXME: Is this really working as expected? There are cases where
2810 // we just use the 'ID' from the message expression.
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002811 const GRState* St = Builder.GetState(Pred);
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00002812 SVal V = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
Ted Kremenek553cf182008-06-25 21:21:56 +00002813
Ted Kremenek94c96982009-03-03 22:06:47 +00002814 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremeneke0e4ebf2009-03-26 03:35:11 +00002815 if (Sym) {
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002816 if (const RefVal* T = St->get<RefBindings>(Sym)) {
Ted Kremeneke8fdc832008-07-07 16:21:19 +00002817 QualType Ty = T->getType();
Ted Kremenek553cf182008-06-25 21:21:56 +00002818
2819 if (const PointerType* PT = Ty->getAsPointerType()) {
2820 QualType PointeeTy = PT->getPointeeType();
2821
2822 if (ObjCInterfaceType* IT = dyn_cast<ObjCInterfaceType>(PointeeTy))
2823 ID = IT->getDecl();
2824 }
2825 }
2826 }
2827
Ted Kremenekce8a41d2009-04-29 17:09:14 +00002828 // FIXME: The receiver could be a reference to a class, meaning that
2829 // we should use the class method.
2830 Summ = Summaries.getInstanceMethodSummary(ME, ID);
Ted Kremenekf9790ae2008-10-24 20:32:50 +00002831
Ted Kremenek896cd9d2008-10-23 01:56:15 +00002832 // Special-case: are we sending a mesage to "self"?
2833 // This is a hack. When we have full-IP this should be removed.
Ted Kremenek885c27b2009-05-04 05:31:22 +00002834 if (isa<ObjCMethodDecl>(&Eng.getGraph().getCodeDecl())) {
2835 if (Expr* Receiver = ME->getReceiver()) {
2836 SVal X = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
2837 if (loc::MemRegionVal* L = dyn_cast<loc::MemRegionVal>(&X))
2838 if (L->getRegion() == Eng.getStateManager().getSelfRegion(St)) {
2839 // Update the summary to make the default argument effect
2840 // 'StopTracking'.
2841 Summ = Summaries.copySummary(Summ);
2842 Summ->setDefaultArgEffect(StopTracking);
2843 }
Ted Kremenek896cd9d2008-10-23 01:56:15 +00002844 }
2845 }
Ted Kremenek553cf182008-06-25 21:21:56 +00002846 }
Ted Kremenek9ed18e62008-04-16 04:28:53 +00002847 else
Ted Kremenekf9df1362009-04-23 21:25:57 +00002848 Summ = Summaries.getClassMethodSummary(ME);
Ted Kremenek9ed18e62008-04-16 04:28:53 +00002849
Ted Kremenek7faca822009-05-04 04:57:00 +00002850 if (!Summ)
2851 Summ = Summaries.getDefaultSummary();
Ted Kremenekde4d5332009-04-24 17:50:11 +00002852
Ted Kremenek7faca822009-05-04 04:57:00 +00002853 EvalSummary(Dst, Eng, Builder, ME, ME->getReceiver(), *Summ,
Ted Kremenekb3095252008-05-06 04:20:12 +00002854 ME->arg_begin(), ME->arg_end(), Pred);
Ted Kremenek85348202008-04-15 23:44:31 +00002855}
Ted Kremenek5216ad72009-02-14 03:16:10 +00002856
2857namespace {
2858class VISIBILITY_HIDDEN StopTrackingCallback : public SymbolVisitor {
2859 GRStateRef state;
2860public:
2861 StopTrackingCallback(GRStateRef st) : state(st) {}
2862 GRStateRef getState() { return state; }
2863
2864 bool VisitSymbol(SymbolRef sym) {
2865 state = state.remove<RefBindings>(sym);
2866 return true;
2867 }
Ted Kremenekb3095252008-05-06 04:20:12 +00002868
Ted Kremenek5216ad72009-02-14 03:16:10 +00002869 const GRState* getState() const { return state.getState(); }
2870};
2871} // end anonymous namespace
2872
2873
Ted Kremenek41573eb2009-02-14 01:43:44 +00002874void CFRefCount::EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val) {
Ted Kremenek41573eb2009-02-14 01:43:44 +00002875 // Are we storing to something that causes the value to "escape"?
Ted Kremenek13922612008-04-16 20:40:59 +00002876 bool escapes = false;
2877
Ted Kremeneka496d162008-10-18 03:49:51 +00002878 // A value escapes in three possible cases (this may change):
2879 //
2880 // (1) we are binding to something that is not a memory region.
2881 // (2) we are binding to a memregion that does not have stack storage
2882 // (3) we are binding to a memregion with stack storage that the store
Ted Kremenek41573eb2009-02-14 01:43:44 +00002883 // does not understand.
Ted Kremenek41573eb2009-02-14 01:43:44 +00002884 GRStateRef state = B.getState();
Ted Kremeneka496d162008-10-18 03:49:51 +00002885
Ted Kremenek41573eb2009-02-14 01:43:44 +00002886 if (!isa<loc::MemRegionVal>(location))
Ted Kremenek13922612008-04-16 20:40:59 +00002887 escapes = true;
Ted Kremenek9e240492008-10-04 05:50:14 +00002888 else {
Ted Kremenek41573eb2009-02-14 01:43:44 +00002889 const MemRegion* R = cast<loc::MemRegionVal>(location).getRegion();
2890 escapes = !B.getStateManager().hasStackStorage(R);
Ted Kremeneka496d162008-10-18 03:49:51 +00002891
2892 if (!escapes) {
2893 // To test (3), generate a new state with the binding removed. If it is
2894 // the same state, then it escapes (since the store cannot represent
2895 // the binding).
Ted Kremenek41573eb2009-02-14 01:43:44 +00002896 escapes = (state == (state.BindLoc(cast<Loc>(location), UnknownVal())));
Ted Kremeneka496d162008-10-18 03:49:51 +00002897 }
Ted Kremenek9e240492008-10-04 05:50:14 +00002898 }
Ted Kremenek41573eb2009-02-14 01:43:44 +00002899
Ted Kremenek5216ad72009-02-14 03:16:10 +00002900 // If our store can represent the binding and we aren't storing to something
2901 // that doesn't have local storage then just return and have the simulation
2902 // state continue as is.
2903 if (!escapes)
2904 return;
Ted Kremeneka496d162008-10-18 03:49:51 +00002905
Ted Kremenek5216ad72009-02-14 03:16:10 +00002906 // Otherwise, find all symbols referenced by 'val' that we are tracking
2907 // and stop tracking them.
2908 B.MakeNode(state.scanReachableSymbols<StopTrackingCallback>(val).getState());
Ted Kremenekdb863712008-04-16 22:32:20 +00002909}
2910
Ted Kremenek652adc62008-04-24 23:57:27 +00002911
Ted Kremenek4fd88972008-04-17 18:12:53 +00002912 // Return statements.
2913
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002914void CFRefCount::EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4fd88972008-04-17 18:12:53 +00002915 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002916 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4fd88972008-04-17 18:12:53 +00002917 ReturnStmt* S,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002918 ExplodedNode<GRState>* Pred) {
Ted Kremenek4fd88972008-04-17 18:12:53 +00002919
2920 Expr* RetE = S->getRetValue();
Ted Kremenek94c96982009-03-03 22:06:47 +00002921 if (!RetE)
Ted Kremenek4fd88972008-04-17 18:12:53 +00002922 return;
2923
Ted Kremenek94c96982009-03-03 22:06:47 +00002924 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00002925 SymbolRef Sym = state.GetSValAsScalarOrLoc(RetE).getAsLocSymbol();
Ted Kremenek94c96982009-03-03 22:06:47 +00002926
Ted Kremeneke0e4ebf2009-03-26 03:35:11 +00002927 if (!Sym)
Ted Kremenek94c96982009-03-03 22:06:47 +00002928 return;
Ted Kremenekf04dced2009-05-08 23:32:51 +00002929
Ted Kremenek4fd88972008-04-17 18:12:53 +00002930 // Get the reference count binding (if any).
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002931 const RefVal* T = state.get<RefBindings>(Sym);
Ted Kremenek4fd88972008-04-17 18:12:53 +00002932
2933 if (!T)
2934 return;
2935
Ted Kremenekf04dced2009-05-08 23:32:51 +00002936 // Update the autorelease counts.
2937 static unsigned autoreleasetag = 0;
2938 GenericNodeBuilder Bd(Builder, S, &autoreleasetag);
Ted Kremenek369de562009-05-09 00:10:05 +00002939 bool stop = false;
2940 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state , Bd, Pred, Eng, Sym,
2941 *T, stop);
2942
2943 if (stop)
2944 return;
Ted Kremenekf04dced2009-05-08 23:32:51 +00002945
2946 // Get the updated binding.
2947 T = state.get<RefBindings>(Sym);
2948 assert(T);
2949
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002950 // Change the reference count.
Ted Kremeneke8fdc832008-07-07 16:21:19 +00002951 RefVal X = *T;
Ted Kremenek4fd88972008-04-17 18:12:53 +00002952
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002953 switch (X.getKind()) {
Ted Kremenek4fd88972008-04-17 18:12:53 +00002954 case RefVal::Owned: {
2955 unsigned cnt = X.getCount();
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00002956 assert (cnt > 0);
2957 X = RefVal::makeReturnedOwned(cnt - 1);
Ted Kremenek4fd88972008-04-17 18:12:53 +00002958 break;
2959 }
2960
2961 case RefVal::NotOwned: {
2962 unsigned cnt = X.getCount();
2963 X = cnt ? RefVal::makeReturnedOwned(cnt - 1)
2964 : RefVal::makeReturnedNotOwned();
2965 break;
2966 }
2967
2968 default:
Ted Kremenek4fd88972008-04-17 18:12:53 +00002969 return;
2970 }
2971
2972 // Update the binding.
Ted Kremenekb9d17f92008-08-17 03:20:02 +00002973 state = state.set<RefBindings>(Sym, X);
Ted Kremenekc887d132009-04-29 18:50:19 +00002974 Pred = Builder.MakeNode(Dst, S, Pred, state);
2975
Ted Kremenek9f246b62009-04-30 05:51:50 +00002976 // Did we cache out?
2977 if (!Pred)
2978 return;
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00002979
Ted Kremenekc887d132009-04-29 18:50:19 +00002980 // Any leaks or other errors?
2981 if (X.isReturnedOwned() && X.getCount() == 0) {
2982 const Decl *CD = &Eng.getStateManager().getCodeDecl();
2983
Ted Kremeneka8833552009-04-29 23:03:22 +00002984 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
Ted Kremenek7faca822009-05-04 04:57:00 +00002985 const RetainSummary &Summ = *Summaries.getMethodSummary(MD);
2986 if (!Summ.getRetEffect().isOwned()) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002987 static int ReturnOwnLeakTag = 0;
2988 state = state.set<RefBindings>(Sym, X ^ RefVal::ErrorLeakReturned);
Ted Kremenekc887d132009-04-29 18:50:19 +00002989 // Generate an error node.
Ted Kremenek9f246b62009-04-30 05:51:50 +00002990 if (ExplodedNode<GRState> *N =
2991 Builder.generateNode(PostStmt(S, &ReturnOwnLeakTag), state, Pred)) {
2992 CFRefLeakReport *report =
2993 new CFRefLeakReport(*static_cast<CFRefBug*>(leakAtReturn), *this,
2994 N, Sym, Eng);
2995 BR->EmitReport(report);
2996 }
Ted Kremenekc887d132009-04-29 18:50:19 +00002997 }
2998 }
2999 }
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003000
3001
Ted Kremenek4fd88972008-04-17 18:12:53 +00003002}
3003
Ted Kremenekcb612922008-04-18 19:23:43 +00003004// Assumptions.
3005
Ted Kremenek4adc81e2008-08-13 04:27:00 +00003006const GRState* CFRefCount::EvalAssume(GRStateManager& VMgr,
3007 const GRState* St,
Zhongxing Xu1c96b242008-10-17 05:57:07 +00003008 SVal Cond, bool Assumption,
Ted Kremenek4323a572008-07-10 22:03:41 +00003009 bool& isFeasible) {
Ted Kremenekcb612922008-04-18 19:23:43 +00003010
3011 // FIXME: We may add to the interface of EvalAssume the list of symbols
3012 // whose assumptions have changed. For now we just iterate through the
3013 // bindings and check if any of the tracked symbols are NULL. This isn't
3014 // too bad since the number of symbols we will track in practice are
3015 // probably small and EvalAssume is only called at branches and a few
3016 // other places.
Ted Kremenek72cd17f2008-08-14 21:16:54 +00003017 RefBindings B = St->get<RefBindings>();
Ted Kremenekcb612922008-04-18 19:23:43 +00003018
3019 if (B.isEmpty())
3020 return St;
3021
3022 bool changed = false;
Ted Kremenekb9d17f92008-08-17 03:20:02 +00003023
3024 GRStateRef state(St, VMgr);
3025 RefBindings::Factory& RefBFactory = state.get_context<RefBindings>();
Ted Kremenekcb612922008-04-18 19:23:43 +00003026
3027 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
Ted Kremenekcb612922008-04-18 19:23:43 +00003028 // Check if the symbol is null (or equal to any constant).
3029 // If this is the case, stop tracking the symbol.
Zhongxing Xu39cfed32008-08-29 14:52:36 +00003030 if (VMgr.getSymVal(St, I.getKey())) {
Ted Kremenekcb612922008-04-18 19:23:43 +00003031 changed = true;
3032 B = RefBFactory.Remove(B, I.getKey());
3033 }
3034 }
3035
Ted Kremenekb9d17f92008-08-17 03:20:02 +00003036 if (changed)
3037 state = state.set<RefBindings>(B);
Ted Kremenekcb612922008-04-18 19:23:43 +00003038
Ted Kremenek72cd17f2008-08-14 21:16:54 +00003039 return state;
Ted Kremenekcb612922008-04-18 19:23:43 +00003040}
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00003041
Ted Kremenek4d3957d2009-02-24 19:15:11 +00003042GRStateRef CFRefCount::Update(GRStateRef state, SymbolRef sym,
3043 RefVal V, ArgEffect E,
3044 RefVal::Kind& hasErr) {
Ted Kremenek1c512f52009-02-18 18:54:33 +00003045
3046 // In GC mode [... release] and [... retain] do nothing.
3047 switch (E) {
3048 default: break;
3049 case IncRefMsg: E = isGCEnabled() ? DoNothing : IncRef; break;
3050 case DecRefMsg: E = isGCEnabled() ? DoNothing : DecRef; break;
Ted Kremenek27019002009-02-18 21:57:45 +00003051 case MakeCollectable: E = isGCEnabled() ? DecRef : DoNothing; break;
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00003052 case NewAutoreleasePool: E = isGCEnabled() ? DoNothing :
3053 NewAutoreleasePool; break;
Ted Kremenek1c512f52009-02-18 18:54:33 +00003054 }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00003055
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003056 // Handle all use-after-releases.
3057 if (!isGCEnabled() && V.getKind() == RefVal::Released) {
3058 V = V ^ RefVal::ErrorUseAfterRelease;
3059 hasErr = V.getKind();
3060 return state.set<RefBindings>(sym, V);
3061 }
3062
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003063 switch (E) {
3064 default:
3065 assert (false && "Unhandled CFRef transition.");
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003066
3067 case Dealloc:
3068 // Any use of -dealloc in GC is *bad*.
3069 if (isGCEnabled()) {
3070 V = V ^ RefVal::ErrorDeallocGC;
3071 hasErr = V.getKind();
3072 break;
3073 }
3074
3075 switch (V.getKind()) {
3076 default:
3077 assert(false && "Invalid case.");
3078 case RefVal::Owned:
3079 // The object immediately transitions to the released state.
3080 V = V ^ RefVal::Released;
3081 V.clearCounts();
3082 return state.set<RefBindings>(sym, V);
3083 case RefVal::NotOwned:
3084 V = V ^ RefVal::ErrorDeallocNotOwned;
3085 hasErr = V.getKind();
3086 break;
3087 }
3088 break;
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00003089
Ted Kremenek35790732009-02-25 23:11:49 +00003090 case NewAutoreleasePool:
3091 assert(!isGCEnabled());
3092 return state.add<AutoreleaseStack>(sym);
3093
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00003094 case MayEscape:
3095 if (V.getKind() == RefVal::Owned) {
Ted Kremenek553cf182008-06-25 21:21:56 +00003096 V = V ^ RefVal::NotOwned;
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00003097 break;
3098 }
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003099
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00003100 // Fall-through.
Ted Kremenek6c4becb2009-02-25 02:54:57 +00003101
Ted Kremenek070a8252008-07-09 18:11:16 +00003102 case DoNothingByRef:
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003103 case DoNothing:
Ted Kremenek4d3957d2009-02-24 19:15:11 +00003104 return state;
Ted Kremeneke19f4492008-06-30 16:57:41 +00003105
Ted Kremenekabf43972009-01-28 21:44:40 +00003106 case Autorelease:
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003107 if (isGCEnabled())
3108 return state;
Ted Kremenek7037ab82009-03-20 17:34:15 +00003109
3110 // Update the autorelease counts.
3111 state = SendAutorelease(state, ARCountFactory, sym);
Ted Kremenekf21332e2009-05-08 20:01:42 +00003112 V = V.autorelease();
Ted Kremenek6b62ec92009-05-09 01:50:57 +00003113 break;
Ted Kremenek369de562009-05-09 00:10:05 +00003114
Ted Kremenek14993892008-05-06 02:41:27 +00003115 case StopTracking:
Ted Kremenek4d3957d2009-02-24 19:15:11 +00003116 return state.remove<RefBindings>(sym);
Ted Kremenek9e476de2008-08-12 18:30:56 +00003117
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003118 case IncRef:
3119 switch (V.getKind()) {
3120 default:
3121 assert(false);
3122
3123 case RefVal::Owned:
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003124 case RefVal::NotOwned:
Ted Kremenek553cf182008-06-25 21:21:56 +00003125 V = V + 1;
Ted Kremenek9e476de2008-08-12 18:30:56 +00003126 break;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003127 case RefVal::Released:
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003128 // Non-GC cases are handled above.
3129 assert(isGCEnabled());
3130 V = (V ^ RefVal::Owned) + 1;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003131 break;
Ted Kremenek9e476de2008-08-12 18:30:56 +00003132 }
Ted Kremenek940b1d82008-04-10 23:44:06 +00003133 break;
3134
Ted Kremenek553cf182008-06-25 21:21:56 +00003135 case SelfOwn:
3136 V = V ^ RefVal::NotOwned;
Ted Kremenek1c512f52009-02-18 18:54:33 +00003137 // Fall-through.
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003138 case DecRef:
3139 switch (V.getKind()) {
3140 default:
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003141 // case 'RefVal::Released' handled above.
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003142 assert (false);
Ted Kremenek9e476de2008-08-12 18:30:56 +00003143
Ted Kremenek553cf182008-06-25 21:21:56 +00003144 case RefVal::Owned:
Ted Kremenekbb8c5aa2009-02-18 22:57:22 +00003145 assert(V.getCount() > 0);
3146 if (V.getCount() == 1) V = V ^ RefVal::Released;
3147 V = V - 1;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003148 break;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003149
Ted Kremenek553cf182008-06-25 21:21:56 +00003150 case RefVal::NotOwned:
3151 if (V.getCount() > 0)
3152 V = V - 1;
Ted Kremenek61b9f872008-04-10 23:09:18 +00003153 else {
Ted Kremenek553cf182008-06-25 21:21:56 +00003154 V = V ^ RefVal::ErrorReleaseNotOwned;
Ted Kremenek9ed18e62008-04-16 04:28:53 +00003155 hasErr = V.getKind();
Ted Kremenek9e476de2008-08-12 18:30:56 +00003156 }
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003157 break;
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003158
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003159 case RefVal::Released:
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003160 // Non-GC cases are handled above.
3161 assert(isGCEnabled());
Ted Kremenek553cf182008-06-25 21:21:56 +00003162 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek9ed18e62008-04-16 04:28:53 +00003163 hasErr = V.getKind();
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003164 break;
Ted Kremenek9e476de2008-08-12 18:30:56 +00003165 }
Ted Kremenek940b1d82008-04-10 23:44:06 +00003166 break;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003167 }
Ted Kremenek4d3957d2009-02-24 19:15:11 +00003168 return state.set<RefBindings>(sym, V);
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00003169}
3170
Ted Kremenekfa34b332008-04-09 01:10:13 +00003171//===----------------------------------------------------------------------===//
Ted Kremenekcf701772009-02-05 06:50:21 +00003172// Handle dead symbols and end-of-path.
3173//===----------------------------------------------------------------------===//
3174
Ted Kremenekf04dced2009-05-08 23:32:51 +00003175std::pair<ExplodedNode<GRState>*, GRStateRef>
3176CFRefCount::HandleAutoreleaseCounts(GRStateRef state, GenericNodeBuilder Bd,
3177 ExplodedNode<GRState>* Pred,
Ted Kremenek369de562009-05-09 00:10:05 +00003178 GRExprEngine &Eng,
3179 SymbolRef Sym, RefVal V, bool &stop) {
Ted Kremenekf04dced2009-05-08 23:32:51 +00003180
Ted Kremenek369de562009-05-09 00:10:05 +00003181 unsigned ACnt = V.getAutoreleaseCount();
3182 stop = false;
3183
3184 // No autorelease counts? Nothing to be done.
3185 if (!ACnt)
3186 return std::make_pair(Pred, state);
3187
3188 assert(!isGCEnabled() && "Autorelease counts in GC mode?");
3189 unsigned Cnt = V.getCount();
3190
3191 if (ACnt <= Cnt) {
Ted Kremenek80c24182009-05-09 00:44:07 +00003192 if (ACnt == Cnt) {
3193 V.clearCounts();
3194 V = V ^ RefVal::NotOwned;
3195 }
3196 else {
3197 V.setCount(Cnt - ACnt);
3198 V.setAutoreleaseCount(0);
3199 }
Ted Kremenek369de562009-05-09 00:10:05 +00003200 state = state.set<RefBindings>(Sym, V);
3201 ExplodedNode<GRState> *N = Bd.MakeNode(state, Pred);
3202 stop = (N == 0);
3203 return std::make_pair(N, state);
3204 }
3205
3206 // Woah! More autorelease counts then retain counts left.
3207 // Emit hard error.
3208 stop = true;
3209 V = V ^ RefVal::ErrorOverAutorelease;
3210 state = state.set<RefBindings>(Sym, V);
3211
3212 if (ExplodedNode<GRState> *N = Bd.MakeNode(state, Pred)) {
Ted Kremenek80c24182009-05-09 00:44:07 +00003213 N->markAsSink();
Ted Kremenek369de562009-05-09 00:10:05 +00003214 CFRefReport *report =
3215 new CFRefReport(*static_cast<CFRefBug*>(overAutorelease),
3216 *this, N, Sym);
3217 BR->EmitReport(report);
3218 }
3219
3220 return std::make_pair((ExplodedNode<GRState>*)0, state);
Ted Kremenekf04dced2009-05-08 23:32:51 +00003221}
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003222
3223GRStateRef
3224CFRefCount::HandleSymbolDeath(GRStateRef state, SymbolRef sid, RefVal V,
3225 llvm::SmallVectorImpl<SymbolRef> &Leaked) {
3226
3227 bool hasLeak = V.isOwned() ||
3228 ((V.isNotOwned() || V.isReturnedOwned()) && V.getCount() > 0);
3229
3230 if (!hasLeak)
3231 return state.remove<RefBindings>(sid);
3232
3233 Leaked.push_back(sid);
3234 return state.set<RefBindings>(sid, V ^ RefVal::ErrorLeak);
3235}
3236
3237ExplodedNode<GRState>*
3238CFRefCount::ProcessLeaks(GRStateRef state,
3239 llvm::SmallVectorImpl<SymbolRef> &Leaked,
3240 GenericNodeBuilder &Builder,
3241 GRExprEngine& Eng,
3242 ExplodedNode<GRState> *Pred) {
3243
3244 if (Leaked.empty())
3245 return Pred;
3246
Ted Kremenekf04dced2009-05-08 23:32:51 +00003247 // Generate an intermediate node representing the leak point.
Ted Kremenek6b62ec92009-05-09 01:50:57 +00003248 ExplodedNode<GRState> *N = Builder.MakeNode(state, Pred);
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003249
3250 if (N) {
3251 for (llvm::SmallVectorImpl<SymbolRef>::iterator
3252 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3253
3254 CFRefBug *BT = static_cast<CFRefBug*>(Pred ? leakWithinFunction
3255 : leakAtReturn);
3256 assert(BT && "BugType not initialized.");
3257 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N, *I, Eng);
3258 BR->EmitReport(report);
3259 }
3260 }
3261
3262 return N;
3263}
3264
Ted Kremenekcf701772009-02-05 06:50:21 +00003265void CFRefCount::EvalEndPath(GRExprEngine& Eng,
3266 GREndPathNodeBuilder<GRState>& Builder) {
3267
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003268 GRStateRef state(Builder.getState(), Eng.getStateManager());
Ted Kremenekf04dced2009-05-08 23:32:51 +00003269 GenericNodeBuilder Bd(Builder);
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003270 RefBindings B = state.get<RefBindings>();
Ted Kremenekf04dced2009-05-08 23:32:51 +00003271 ExplodedNode<GRState> *Pred = 0;
3272
3273 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Ted Kremenek369de562009-05-09 00:10:05 +00003274 bool stop = false;
3275 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state, Bd, Pred, Eng,
3276 (*I).first,
3277 (*I).second, stop);
3278
3279 if (stop)
3280 return;
Ted Kremenekf04dced2009-05-08 23:32:51 +00003281 }
3282
3283 B = state.get<RefBindings>();
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003284 llvm::SmallVector<SymbolRef, 10> Leaked;
Ted Kremenekcf701772009-02-05 06:50:21 +00003285
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003286 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I)
3287 state = HandleSymbolDeath(state, (*I).first, (*I).second, Leaked);
3288
Ted Kremenekf04dced2009-05-08 23:32:51 +00003289 ProcessLeaks(state, Leaked, Bd, Eng, Pred);
Ted Kremenekcf701772009-02-05 06:50:21 +00003290}
3291
3292void CFRefCount::EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
3293 GRExprEngine& Eng,
3294 GRStmtNodeBuilder<GRState>& Builder,
3295 ExplodedNode<GRState>* Pred,
3296 Stmt* S,
3297 const GRState* St,
3298 SymbolReaper& SymReaper) {
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003299
3300 GRStateRef state(St, Eng.getStateManager());
Ted Kremenekf04dced2009-05-08 23:32:51 +00003301 RefBindings B = state.get<RefBindings>();
3302
3303 // Update counts from autorelease pools
3304 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3305 E = SymReaper.dead_end(); I != E; ++I) {
3306 SymbolRef Sym = *I;
3307 if (const RefVal* T = B.lookup(Sym)){
3308 // Use the symbol as the tag.
3309 // FIXME: This might not be as unique as we would like.
3310 GenericNodeBuilder Bd(Builder, S, Sym);
Ted Kremenek369de562009-05-09 00:10:05 +00003311 bool stop = false;
3312 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state, Bd, Pred, Eng,
3313 Sym, *T, stop);
3314 if (stop)
3315 return;
Ted Kremenekf04dced2009-05-08 23:32:51 +00003316 }
3317 }
3318
3319 B = state.get<RefBindings>();
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003320 llvm::SmallVector<SymbolRef, 10> Leaked;
Ted Kremenekcf701772009-02-05 06:50:21 +00003321
3322 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003323 E = SymReaper.dead_end(); I != E; ++I) {
3324 if (const RefVal* T = B.lookup(*I))
3325 state = HandleSymbolDeath(state, *I, *T, Leaked);
3326 }
Ted Kremenekcf701772009-02-05 06:50:21 +00003327
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003328 static unsigned LeakPPTag = 0;
Ted Kremenekf04dced2009-05-08 23:32:51 +00003329 {
3330 GenericNodeBuilder Bd(Builder, S, &LeakPPTag);
3331 Pred = ProcessLeaks(state, Leaked, Bd, Eng, Pred);
3332 }
Ted Kremenekcf701772009-02-05 06:50:21 +00003333
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003334 // Did we cache out?
3335 if (!Pred)
3336 return;
Ted Kremenek33b6f632009-02-19 23:47:02 +00003337
3338 // Now generate a new node that nukes the old bindings.
Ted Kremenek33b6f632009-02-19 23:47:02 +00003339 RefBindings::Factory& F = state.get_context<RefBindings>();
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003340
Ted Kremenek33b6f632009-02-19 23:47:02 +00003341 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003342 E = SymReaper.dead_end(); I!=E; ++I) B = F.Remove(B, *I);
3343
Ted Kremenek33b6f632009-02-19 23:47:02 +00003344 state = state.set<RefBindings>(B);
3345 Builder.MakeNode(Dst, S, Pred, state);
Ted Kremenekcf701772009-02-05 06:50:21 +00003346}
3347
3348void CFRefCount::ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
3349 GRStmtNodeBuilder<GRState>& Builder,
3350 Expr* NodeExpr, Expr* ErrorExpr,
3351 ExplodedNode<GRState>* Pred,
3352 const GRState* St,
3353 RefVal::Kind hasErr, SymbolRef Sym) {
3354 Builder.BuildSinks = true;
3355 GRExprEngine::NodeTy* N = Builder.MakeNode(Dst, NodeExpr, Pred, St);
3356
Ted Kremenek6b62ec92009-05-09 01:50:57 +00003357 if (!N)
3358 return;
Ted Kremenekcf701772009-02-05 06:50:21 +00003359
3360 CFRefBug *BT = 0;
3361
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003362 switch (hasErr) {
3363 default:
3364 assert(false && "Unhandled error.");
3365 return;
3366 case RefVal::ErrorUseAfterRelease:
3367 BT = static_cast<CFRefBug*>(useAfterRelease);
3368 break;
3369 case RefVal::ErrorReleaseNotOwned:
3370 BT = static_cast<CFRefBug*>(releaseNotOwned);
3371 break;
3372 case RefVal::ErrorDeallocGC:
3373 BT = static_cast<CFRefBug*>(deallocGC);
3374 break;
3375 case RefVal::ErrorDeallocNotOwned:
3376 BT = static_cast<CFRefBug*>(deallocNotOwned);
3377 break;
Ted Kremenekcf701772009-02-05 06:50:21 +00003378 }
3379
Ted Kremenekfe9e5432009-02-18 03:48:14 +00003380 CFRefReport *report = new CFRefReport(*BT, *this, N, Sym);
Ted Kremenekcf701772009-02-05 06:50:21 +00003381 report->addRange(ErrorExpr->getSourceRange());
3382 BR->EmitReport(report);
3383}
3384
3385//===----------------------------------------------------------------------===//
Ted Kremenekd71ed262008-04-10 22:16:52 +00003386// Transfer function creation for external clients.
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00003387//===----------------------------------------------------------------------===//
3388
Ted Kremenek072192b2008-04-30 23:47:44 +00003389GRTransferFuncs* clang::MakeCFRefCountTF(ASTContext& Ctx, bool GCEnabled,
3390 const LangOptions& lopts) {
Ted Kremenek78d46242008-07-22 16:21:24 +00003391 return new CFRefCount(Ctx, GCEnabled, lopts);
Ted Kremenek3ea0b6a2008-04-10 22:58:08 +00003392}