blob: 0f251b343d0b8edc43e6fd3bddfd30894f1cff5d [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 Kremenek4dd8fb42009-05-09 02:58:13 +0000812 void updateSummaryFromAnnotations(RetainSummary &Summ,
813 const ObjCMethodDecl *MD);
814
815 void updateSummaryFromAnnotations(RetainSummary &Summ,
816 const FunctionDecl *FD);
817
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000818 bool isGCEnabled() const { return GCEnabled; }
Ted Kremenek885c27b2009-05-04 05:31:22 +0000819
820 RetainSummary *copySummary(RetainSummary *OldSumm) {
821 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
822 new (Summ) RetainSummary(*OldSumm);
823 return Summ;
824 }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000825};
826
827} // end anonymous namespace
828
829//===----------------------------------------------------------------------===//
830// Implementation of checker data structures.
831//===----------------------------------------------------------------------===//
832
Ted Kremenekb77449c2009-05-03 05:20:50 +0000833RetainSummaryManager::~RetainSummaryManager() {}
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000834
Ted Kremenekb77449c2009-05-03 05:20:50 +0000835ArgEffects RetainSummaryManager::getArgEffects() {
836 ArgEffects AE = ScratchArgs;
837 ScratchArgs = AF.GetEmptyMap();
838 return AE;
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000839}
840
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000841RetainSummary*
Ted Kremenekb77449c2009-05-03 05:20:50 +0000842RetainSummaryManager::getPersistentSummary(ArgEffects AE, RetEffect RetEff,
Ted Kremenek1bffd742008-05-06 15:44:25 +0000843 ArgEffect ReceiverEff,
Ted Kremenek70a733e2008-07-18 17:24:20 +0000844 ArgEffect DefaultEff,
Ted Kremenek22fe2482009-05-04 04:30:18 +0000845 bool isEndPath) {
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000846 // Create the summary and return it.
Ted Kremenek22fe2482009-05-04 04:30:18 +0000847 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
Ted Kremenek70a733e2008-07-18 17:24:20 +0000848 new (Summ) RetainSummary(AE, RetEff, DefaultEff, ReceiverEff, isEndPath);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000849 return Summ;
850}
851
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000852//===----------------------------------------------------------------------===//
Ted Kremenek234a4c22009-01-07 00:39:56 +0000853// Predicates.
854//===----------------------------------------------------------------------===//
855
Ted Kremenekeff4b3c2009-05-03 04:42:10 +0000856bool RetainSummaryManager::isTrackedObjCObjectType(QualType Ty) {
Ted Kremenek97d095f2009-04-23 22:11:07 +0000857 if (!Ctx.isObjCObjectPointerType(Ty))
Ted Kremenek234a4c22009-01-07 00:39:56 +0000858 return false;
859
Ted Kremenek97d095f2009-04-23 22:11:07 +0000860 // We assume that id<..>, id, and "Class" all represent tracked objects.
861 const PointerType *PT = Ty->getAsPointerType();
862 if (PT == 0)
863 return true;
864
865 const ObjCInterfaceType *OT = PT->getPointeeType()->getAsObjCInterfaceType();
Ted Kremenek234a4c22009-01-07 00:39:56 +0000866
867 // We assume that id<..>, id, and "Class" all represent tracked objects.
868 if (!OT)
869 return true;
Ted Kremenek97d095f2009-04-23 22:11:07 +0000870
871 // Does the interface subclass NSObject?
Ted Kremenek234a4c22009-01-07 00:39:56 +0000872 // FIXME: We can memoize here if this gets too expensive.
873 IdentifierInfo* NSObjectII = &Ctx.Idents.get("NSObject");
874 ObjCInterfaceDecl* ID = OT->getDecl();
875
876 for ( ; ID ; ID = ID->getSuperClass())
877 if (ID->getIdentifier() == NSObjectII)
878 return true;
879
880 return false;
881}
882
Ted Kremenek92511432009-05-03 06:08:32 +0000883bool RetainSummaryManager::isTrackedCFObjectType(QualType T) {
884 return isRefType(T, "CF") || // Core Foundation.
885 isRefType(T, "CG") || // Core Graphics.
886 isRefType(T, "DADisk") || // Disk Arbitration API.
887 isRefType(T, "DADissenter") ||
888 isRefType(T, "DASessionRef");
889}
890
Ted Kremenek234a4c22009-01-07 00:39:56 +0000891//===----------------------------------------------------------------------===//
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000892// Summary creation for functions (largely uses of Core Foundation).
893//===----------------------------------------------------------------------===//
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000894
Ted Kremenek12619382009-01-12 21:45:02 +0000895static bool isRetain(FunctionDecl* FD, const char* FName) {
896 const char* loc = strstr(FName, "Retain");
897 return loc && loc[sizeof("Retain")-1] == '\0';
898}
899
900static bool isRelease(FunctionDecl* FD, const char* FName) {
901 const char* loc = strstr(FName, "Release");
902 return loc && loc[sizeof("Release")-1] == '\0';
903}
904
Ted Kremenekab592272008-06-24 03:56:45 +0000905RetainSummary* RetainSummaryManager::getSummary(FunctionDecl* FD) {
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000906 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000907 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000908 if (I != FuncSummaries.end())
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000909 return I->second;
910
Ted Kremeneke401a0c2009-05-04 15:34:07 +0000911 // No summary? Generate one.
Ted Kremenek12619382009-01-12 21:45:02 +0000912 RetainSummary *S = 0;
Ted Kremenek86ad3bc2008-05-05 16:51:50 +0000913
Ted Kremenek37d785b2008-07-15 16:50:12 +0000914 do {
Ted Kremenek12619382009-01-12 21:45:02 +0000915 // We generate "stop" summaries for implicitly defined functions.
916 if (FD->isImplicit()) {
917 S = getPersistentStopSummary();
918 break;
Ted Kremenek37d785b2008-07-15 16:50:12 +0000919 }
Ted Kremenek6ca31912008-11-04 00:36:12 +0000920
Ted Kremenek6ad315a2009-02-23 16:51:39 +0000921 // [PR 3337] Use 'getAsFunctionType' to strip away any typedefs on the
Ted Kremenek99890652009-01-16 18:40:33 +0000922 // function's type.
Ted Kremenek6ad315a2009-02-23 16:51:39 +0000923 const FunctionType* FT = FD->getType()->getAsFunctionType();
Ted Kremenek12619382009-01-12 21:45:02 +0000924 const char* FName = FD->getIdentifier()->getName();
925
Ted Kremenekbf0a4dd2009-03-05 22:11:14 +0000926 // Strip away preceding '_'. Doing this here will effect all the checks
927 // down below.
928 while (*FName == '_') ++FName;
929
Ted Kremenek12619382009-01-12 21:45:02 +0000930 // Inspect the result type.
931 QualType RetTy = FT->getResultType();
932
933 // FIXME: This should all be refactored into a chain of "summary lookup"
934 // filters.
935 if (strcmp(FName, "IOServiceGetMatchingServices") == 0) {
936 // FIXES: <rdar://problem/6326900>
937 // This should be addressed using a API table. This strcmp is also
938 // a little gross, but there is no need to super optimize here.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000939 assert (ScratchArgs.isEmpty());
940 ScratchArgs = AF.Add(ScratchArgs, 1, DecRef);
Ted Kremenek12619382009-01-12 21:45:02 +0000941 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
942 break;
Ted Kremenek64e859a2008-10-22 20:54:52 +0000943 }
Ted Kremenek61991902009-03-17 22:43:44 +0000944
945 // Enable this code once the semantics of NSDeallocateObject are resolved
946 // for GC. <rdar://problem/6619988>
947#if 0
948 // Handle: NSDeallocateObject(id anObject);
949 // This method does allow 'nil' (although we don't check it now).
950 if (strcmp(FName, "NSDeallocateObject") == 0) {
951 return RetTy == Ctx.VoidTy
952 ? getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, Dealloc)
953 : getPersistentStopSummary();
954 }
955#endif
Ted Kremenek12619382009-01-12 21:45:02 +0000956
957 // Handle: id NSMakeCollectable(CFTypeRef)
958 if (strcmp(FName, "NSMakeCollectable") == 0) {
959 S = (RetTy == Ctx.getObjCIdType())
960 ? getUnarySummary(FT, cfmakecollectable)
961 : getPersistentStopSummary();
962
963 break;
964 }
965
966 if (RetTy->isPointerType()) {
967 // For CoreFoundation ('CF') types.
968 if (isRefType(RetTy, "CF", &Ctx, FName)) {
969 if (isRetain(FD, FName))
970 S = getUnarySummary(FT, cfretain);
971 else if (strstr(FName, "MakeCollectable"))
972 S = getUnarySummary(FT, cfmakecollectable);
973 else
974 S = getCFCreateGetRuleSummary(FD, FName);
975
976 break;
977 }
978
979 // For CoreGraphics ('CG') types.
980 if (isRefType(RetTy, "CG", &Ctx, FName)) {
981 if (isRetain(FD, FName))
982 S = getUnarySummary(FT, cfretain);
983 else
984 S = getCFCreateGetRuleSummary(FD, FName);
985
986 break;
987 }
988
989 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
990 if (isRefType(RetTy, "DADisk") ||
991 isRefType(RetTy, "DADissenter") ||
992 isRefType(RetTy, "DASessionRef")) {
993 S = getCFCreateGetRuleSummary(FD, FName);
994 break;
995 }
996
997 break;
998 }
999
1000 // Check for release functions, the only kind of functions that we care
1001 // about that don't return a pointer type.
1002 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
Ted Kremenekbf0a4dd2009-03-05 22:11:14 +00001003 // Test for 'CGCF'.
1004 if (FName[1] == 'G' && FName[2] == 'C' && FName[3] == 'F')
1005 FName += 4;
1006 else
1007 FName += 2;
1008
1009 if (isRelease(FD, FName))
Ted Kremenek12619382009-01-12 21:45:02 +00001010 S = getUnarySummary(FT, cfrelease);
1011 else {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001012 assert (ScratchArgs.isEmpty());
Ted Kremenek68189282009-01-29 22:45:13 +00001013 // Remaining CoreFoundation and CoreGraphics functions.
1014 // We use to assume that they all strictly followed the ownership idiom
1015 // and that ownership cannot be transferred. While this is technically
1016 // correct, many methods allow a tracked object to escape. For example:
1017 //
1018 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
1019 // CFDictionaryAddValue(y, key, x);
1020 // CFRelease(x);
1021 // ... it is okay to use 'x' since 'y' has a reference to it
1022 //
1023 // We handle this and similar cases with the follow heuristic. If the
1024 // function name contains "InsertValue", "SetValue" or "AddValue" then
1025 // we assume that arguments may "escape."
1026 //
1027 ArgEffect E = (CStrInCStrNoCase(FName, "InsertValue") ||
1028 CStrInCStrNoCase(FName, "AddValue") ||
Ted Kremeneka92206e2009-02-05 22:34:53 +00001029 CStrInCStrNoCase(FName, "SetValue") ||
1030 CStrInCStrNoCase(FName, "AppendValue"))
Ted Kremenek68189282009-01-29 22:45:13 +00001031 ? MayEscape : DoNothing;
1032
1033 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek12619382009-01-12 21:45:02 +00001034 }
1035 }
Ted Kremenek37d785b2008-07-15 16:50:12 +00001036 }
1037 while (0);
Ted Kremenek885c27b2009-05-04 05:31:22 +00001038
1039 if (!S)
1040 S = getDefaultSummary();
Ted Kremenek891d5cc2008-04-24 17:22:33 +00001041
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001042 // Annotations override defaults.
1043 assert(S);
1044 updateSummaryFromAnnotations(*S, FD);
1045
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001046 FuncSummaries[FD] = S;
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001047 return S;
Ted Kremenek2fff37e2008-03-06 00:08:09 +00001048}
1049
Ted Kremenek37d785b2008-07-15 16:50:12 +00001050RetainSummary*
1051RetainSummaryManager::getCFCreateGetRuleSummary(FunctionDecl* FD,
1052 const char* FName) {
1053
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001054 if (strstr(FName, "Create") || strstr(FName, "Copy"))
1055 return getCFSummaryCreateRule(FD);
Ted Kremenek37d785b2008-07-15 16:50:12 +00001056
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001057 if (strstr(FName, "Get"))
1058 return getCFSummaryGetRule(FD);
1059
Ted Kremenek7faca822009-05-04 04:57:00 +00001060 return getDefaultSummary();
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001061}
1062
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001063RetainSummary*
Ted Kremenek6ad315a2009-02-23 16:51:39 +00001064RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1065 UnaryFuncKind func) {
1066
Ted Kremenek12619382009-01-12 21:45:02 +00001067 // Sanity check that this is *really* a unary function. This can
1068 // happen if people do weird things.
Douglas Gregor72564e72009-02-26 23:50:07 +00001069 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
Ted Kremenek12619382009-01-12 21:45:02 +00001070 if (!FTP || FTP->getNumArgs() != 1)
1071 return getPersistentStopSummary();
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001072
Ted Kremenekb77449c2009-05-03 05:20:50 +00001073 assert (ScratchArgs.isEmpty());
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001074
Ted Kremenek377e2302008-04-29 05:33:51 +00001075 switch (func) {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001076 case cfretain: {
1077 ScratchArgs = AF.Add(ScratchArgs, 0, IncRef);
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00001078 return getPersistentSummary(RetEffect::MakeAlias(0),
1079 DoNothing, DoNothing);
Ted Kremenek377e2302008-04-29 05:33:51 +00001080 }
1081
1082 case cfrelease: {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001083 ScratchArgs = AF.Add(ScratchArgs, 0, DecRef);
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00001084 return getPersistentSummary(RetEffect::MakeNoRet(),
1085 DoNothing, DoNothing);
Ted Kremenek377e2302008-04-29 05:33:51 +00001086 }
1087
1088 case cfmakecollectable: {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001089 ScratchArgs = AF.Add(ScratchArgs, 0, MakeCollectable);
Ted Kremenek27019002009-02-18 21:57:45 +00001090 return getPersistentSummary(RetEffect::MakeAlias(0),DoNothing, DoNothing);
Ted Kremenek377e2302008-04-29 05:33:51 +00001091 }
1092
1093 default:
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001094 assert (false && "Not a supported unary function.");
Ted Kremenek7faca822009-05-04 04:57:00 +00001095 return getDefaultSummary();
Ted Kremenek940b1d82008-04-10 23:44:06 +00001096 }
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001097}
1098
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001099RetainSummary* RetainSummaryManager::getCFSummaryCreateRule(FunctionDecl* FD) {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001100 assert (ScratchArgs.isEmpty());
Ted Kremenek070a8252008-07-09 18:11:16 +00001101
1102 if (FD->getIdentifier() == CFDictionaryCreateII) {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001103 ScratchArgs = AF.Add(ScratchArgs, 1, DoNothingByRef);
1104 ScratchArgs = AF.Add(ScratchArgs, 2, DoNothingByRef);
Ted Kremenek070a8252008-07-09 18:11:16 +00001105 }
1106
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001107 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001108}
1109
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001110RetainSummary* RetainSummaryManager::getCFSummaryGetRule(FunctionDecl* FD) {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001111 assert (ScratchArgs.isEmpty());
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001112 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1113 DoNothing, DoNothing);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001114}
1115
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001116//===----------------------------------------------------------------------===//
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001117// Summary creation for Selectors.
1118//===----------------------------------------------------------------------===//
1119
Ted Kremenek1bffd742008-05-06 15:44:25 +00001120RetainSummary*
Ted Kremenek8711c032009-04-29 05:04:30 +00001121RetainSummaryManager::getInitMethodSummary(QualType RetTy) {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001122 assert(ScratchArgs.isEmpty());
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001123
Ted Kremenekc3cf7b22009-02-20 00:05:35 +00001124 // 'init' methods only return an alias if the return type is a location type.
Ted Kremenek8711c032009-04-29 05:04:30 +00001125 return getPersistentSummary(Loc::IsLocType(RetTy)
1126 ? RetEffect::MakeReceiverAlias()
Ted Kremenek69aa0802009-05-05 18:44:20 +00001127 : RetEffect::MakeNoRet());
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001128}
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001129
1130void
1131RetainSummaryManager::updateSummaryFromAnnotations(RetainSummary &Summ,
1132 const FunctionDecl *FD) {
1133 if (!FD)
1134 return;
1135
1136 // Determine if there is a special return effect for this method.
1137 if (isTrackedObjCObjectType(FD->getResultType())) {
1138 if (FD->getAttr<NSReturnsRetainedAttr>()) {
1139 Summ.setRetEffect(ObjCAllocRetE);
1140 }
1141 else if (FD->getAttr<CFReturnsRetainedAttr>()) {
1142 Summ.setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
1143 }
1144 }
1145}
1146
1147void
1148RetainSummaryManager::updateSummaryFromAnnotations(RetainSummary &Summ,
1149 const ObjCMethodDecl *MD) {
1150 if (!MD)
1151 return;
1152
1153 // Determine if there is a special return effect for this method.
1154 if (isTrackedObjCObjectType(MD->getResultType())) {
1155 if (MD->getAttr<NSReturnsRetainedAttr>()) {
1156 Summ.setRetEffect(ObjCAllocRetE);
1157 }
1158 else if (MD->getAttr<CFReturnsRetainedAttr>()) {
1159 Summ.setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
1160 }
1161 }
1162}
1163
Ted Kremenek1bffd742008-05-06 15:44:25 +00001164RetainSummary*
Ted Kremeneka8833552009-04-29 23:03:22 +00001165RetainSummaryManager::getCommonMethodSummary(const ObjCMethodDecl* MD,
1166 Selector S, QualType RetTy) {
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001167
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +00001168 if (MD) {
Ted Kremenek376d1e72009-04-24 18:00:17 +00001169 // Scan the method decl for 'void*' arguments. These should be treated
1170 // as 'StopTracking' because they are often used with delegates.
1171 // Delegates are a frequent form of false positives with the retain
1172 // count checker.
1173 unsigned i = 0;
1174 for (ObjCMethodDecl::param_iterator I = MD->param_begin(),
1175 E = MD->param_end(); I != E; ++I, ++i)
1176 if (ParmVarDecl *PD = *I) {
1177 QualType Ty = Ctx.getCanonicalType(PD->getType());
1178 if (Ty.getUnqualifiedType() == Ctx.VoidPtrTy)
Ted Kremenekb77449c2009-05-03 05:20:50 +00001179 ScratchArgs = AF.Add(ScratchArgs, i, StopTracking);
Ted Kremenek376d1e72009-04-24 18:00:17 +00001180 }
1181 }
1182
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001183 // Any special effect for the receiver?
1184 ArgEffect ReceiverEff = DoNothing;
1185
1186 // If one of the arguments in the selector has the keyword 'delegate' we
1187 // should stop tracking the reference count for the receiver. This is
1188 // because the reference count is quite possibly handled by a delegate
1189 // method.
1190 if (S.isKeywordSelector()) {
1191 const std::string &str = S.getAsString();
1192 assert(!str.empty());
1193 if (CStrInCStrNoCase(&str[0], "delegate:")) ReceiverEff = StopTracking;
1194 }
1195
Ted Kremenek250b1fa2009-04-23 23:08:22 +00001196 // Look for methods that return an owned object.
Ted Kremenek92511432009-05-03 06:08:32 +00001197 if (isTrackedObjCObjectType(RetTy)) {
1198 // EXPERIMENTAL: Assume the Cocoa conventions for all objects returned
1199 // by instance methods.
Ted Kremenek92511432009-05-03 06:08:32 +00001200 RetEffect E =
1201 followsFundamentalRule(S.getIdentifierInfoForSlot(0)->getName())
Ted Kremenekec315332009-05-07 23:40:42 +00001202 ? ObjCAllocRetE : RetEffect::MakeNotOwned(RetEffect::ObjC);
Ted Kremenek92511432009-05-03 06:08:32 +00001203
1204 return getPersistentSummary(E, ReceiverEff, MayEscape);
Ted Kremenek376d1e72009-04-24 18:00:17 +00001205 }
Ted Kremenek250b1fa2009-04-23 23:08:22 +00001206
Ted Kremenek92511432009-05-03 06:08:32 +00001207 // Look for methods that return an owned core foundation object.
1208 if (isTrackedCFObjectType(RetTy)) {
1209 RetEffect E =
1210 followsFundamentalRule(S.getIdentifierInfoForSlot(0)->getName())
1211 ? RetEffect::MakeOwned(RetEffect::CF, true)
1212 : RetEffect::MakeNotOwned(RetEffect::CF);
1213
1214 return getPersistentSummary(E, ReceiverEff, MayEscape);
1215 }
Ted Kremenek250b1fa2009-04-23 23:08:22 +00001216
Ted Kremenek92511432009-05-03 06:08:32 +00001217 if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing)
Ted Kremenek7faca822009-05-04 04:57:00 +00001218 return getDefaultSummary();
Ted Kremenek250b1fa2009-04-23 23:08:22 +00001219
Ted Kremenek885c27b2009-05-04 05:31:22 +00001220 return getPersistentSummary(RetEffect::MakeNoRet(), ReceiverEff, MayEscape);
Ted Kremenek250b1fa2009-04-23 23:08:22 +00001221}
1222
1223RetainSummary*
Ted Kremenekce8a41d2009-04-29 17:09:14 +00001224RetainSummaryManager::getInstanceMethodSummary(Selector S,
1225 IdentifierInfo *ClsName,
Ted Kremeneka8833552009-04-29 23:03:22 +00001226 const ObjCInterfaceDecl* ID,
1227 const ObjCMethodDecl *MD,
Ted Kremenekce8a41d2009-04-29 17:09:14 +00001228 QualType RetTy) {
Ted Kremenek1bffd742008-05-06 15:44:25 +00001229
Ted Kremenek8711c032009-04-29 05:04:30 +00001230 // Look up a summary in our summary cache.
1231 ObjCMethodSummariesTy::iterator I = ObjCMethodSummaries.find(ID, ClsName, S);
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001232
Ted Kremenek1f180c32008-06-23 22:21:20 +00001233 if (I != ObjCMethodSummaries.end())
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001234 return I->second;
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001235
Ted Kremenekb77449c2009-05-03 05:20:50 +00001236 assert(ScratchArgs.isEmpty());
Ted Kremenek885c27b2009-05-04 05:31:22 +00001237 RetainSummary *Summ = 0;
Ted Kremenekaee9e572008-05-06 06:09:09 +00001238
Ted Kremenek885c27b2009-05-04 05:31:22 +00001239 // "initXXX": pass-through for receiver.
1240 if (deriveNamingConvention(S.getIdentifierInfoForSlot(0)->getName())
1241 == InitRule)
1242 Summ = getInitMethodSummary(RetTy);
1243 else
1244 Summ = getCommonMethodSummary(MD, S, RetTy);
1245
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001246 // Annotations override defaults.
1247 updateSummaryFromAnnotations(*Summ, MD);
1248
Ted Kremenek885c27b2009-05-04 05:31:22 +00001249 // Memoize the summary.
Ted Kremenek8711c032009-04-29 05:04:30 +00001250 ObjCMethodSummaries[ObjCSummaryKey(ClsName, S)] = Summ;
Ted Kremeneke87450e2009-04-23 19:11:35 +00001251 return Summ;
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001252}
1253
Ted Kremenekc8395602008-05-06 21:26:51 +00001254RetainSummary*
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +00001255RetainSummaryManager::getClassMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremeneka8833552009-04-29 23:03:22 +00001256 const ObjCInterfaceDecl *ID,
1257 const ObjCMethodDecl *MD,
1258 QualType RetTy) {
Ted Kremenekde4d5332009-04-24 17:50:11 +00001259
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +00001260 assert(ClsName && "Class name must be specified.");
Ted Kremenek8711c032009-04-29 05:04:30 +00001261 ObjCMethodSummariesTy::iterator I =
1262 ObjCClassMethodSummaries.find(ID, ClsName, S);
Ted Kremenekc8395602008-05-06 21:26:51 +00001263
Ted Kremenek1f180c32008-06-23 22:21:20 +00001264 if (I != ObjCClassMethodSummaries.end())
Ted Kremenekc8395602008-05-06 21:26:51 +00001265 return I->second;
Ted Kremenek885c27b2009-05-04 05:31:22 +00001266
1267 RetainSummary *Summ = getCommonMethodSummary(MD, S, RetTy);
Ted Kremenek4dd8fb42009-05-09 02:58:13 +00001268
1269 // Annotations override defaults.
1270 updateSummaryFromAnnotations(*Summ, MD);
Ted Kremenek885c27b2009-05-04 05:31:22 +00001271
Ted Kremenek885c27b2009-05-04 05:31:22 +00001272 // Memoize the summary.
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +00001273 ObjCClassMethodSummaries[ObjCSummaryKey(ClsName, S)] = Summ;
Ted Kremeneke87450e2009-04-23 19:11:35 +00001274 return Summ;
Ted Kremenekc8395602008-05-06 21:26:51 +00001275}
1276
Ted Kremenekec315332009-05-07 23:40:42 +00001277void RetainSummaryManager::InitializeClassMethodSummaries() {
1278 assert(ScratchArgs.isEmpty());
1279 RetainSummary* Summ = getPersistentSummary(ObjCAllocRetE);
Ted Kremenek9c32d082008-05-06 00:30:21 +00001280
Ted Kremenek553cf182008-06-25 21:21:56 +00001281 // Create the summaries for "alloc", "new", and "allocWithZone:" for
1282 // NSObject and its derivatives.
1283 addNSObjectClsMethSummary(GetNullarySelector("alloc", Ctx), Summ);
1284 addNSObjectClsMethSummary(GetNullarySelector("new", Ctx), Summ);
1285 addNSObjectClsMethSummary(GetUnarySelector("allocWithZone", Ctx), Summ);
Ted Kremenek70a733e2008-07-18 17:24:20 +00001286
1287 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek9e476de2008-08-12 18:30:56 +00001288 addClsMethSummary(&Ctx.Idents.get("NSAssertionHandler"),
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001289 GetNullarySelector("currentHandler", Ctx),
1290 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Ted Kremenek6d348932008-10-21 15:53:15 +00001291
1292 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremenekb77449c2009-05-03 05:20:50 +00001293 ScratchArgs = AF.Add(ScratchArgs, 0, Autorelease);
Ted Kremenekabf43972009-01-28 21:44:40 +00001294 addClsMethSummary(&Ctx.Idents.get("NSAutoreleasePool"),
1295 GetUnarySelector("addObject", Ctx),
1296 getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenek022a3c42009-02-23 02:31:16 +00001297 DoNothing, Autorelease));
Ted Kremenekde4d5332009-04-24 17:50:11 +00001298
1299 // Create the summaries for [NSObject performSelector...]. We treat
1300 // these as 'stop tracking' for the arguments because they are often
1301 // used for delegates that can release the object. When we have better
1302 // inter-procedural analysis we can potentially do something better. This
1303 // workaround is to remove false positives.
1304 Summ = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, StopTracking);
1305 IdentifierInfo *NSObjectII = &Ctx.Idents.get("NSObject");
1306 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1307 "afterDelay", NULL);
1308 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1309 "afterDelay", "inModes", NULL);
1310 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1311 "withObject", "waitUntilDone", NULL);
1312 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1313 "withObject", "waitUntilDone", "modes", NULL);
1314 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1315 "withObject", "waitUntilDone", NULL);
1316 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1317 "withObject", "waitUntilDone", "modes", NULL);
1318 addClsMethSummary(NSObjectII, Summ, "performSelectorInBackground",
1319 "withObject", NULL);
Ted Kremenek9c32d082008-05-06 00:30:21 +00001320}
1321
Ted Kremenek1f180c32008-06-23 22:21:20 +00001322void RetainSummaryManager::InitializeMethodSummaries() {
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001323
Ted Kremenekb77449c2009-05-03 05:20:50 +00001324 assert (ScratchArgs.isEmpty());
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001325
Ted Kremenekc8395602008-05-06 21:26:51 +00001326 // Create the "init" selector. It just acts as a pass-through for the
1327 // receiver.
Ted Kremenek46347352009-02-23 16:54:00 +00001328 RetainSummary* InitSumm =
1329 getPersistentSummary(RetEffect::MakeReceiverAlias());
Ted Kremenek179064e2008-07-01 17:21:27 +00001330 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
Ted Kremenekc8395602008-05-06 21:26:51 +00001331
1332 // The next methods are allocators.
Ted Kremenekec315332009-05-07 23:40:42 +00001333 RetainSummary* Summ = getPersistentSummary(ObjCAllocRetE);
Ted Kremenekc8395602008-05-06 21:26:51 +00001334
1335 // Create the "copy" selector.
Ted Kremenek98530452008-08-12 20:41:56 +00001336 addNSObjectMethSummary(GetNullarySelector("copy", Ctx), Summ);
1337
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001338 // Create the "mutableCopy" selector.
Ted Kremenek553cf182008-06-25 21:21:56 +00001339 addNSObjectMethSummary(GetNullarySelector("mutableCopy", Ctx), Summ);
Ted Kremenek98530452008-08-12 20:41:56 +00001340
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001341 // Create the "retain" selector.
Ted Kremenekec315332009-05-07 23:40:42 +00001342 RetEffect E = RetEffect::MakeReceiverAlias();
Ted Kremenek1c512f52009-02-18 18:54:33 +00001343 Summ = getPersistentSummary(E, IncRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001344 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001345
1346 // Create the "release" selector.
Ted Kremenek1c512f52009-02-18 18:54:33 +00001347 Summ = getPersistentSummary(E, DecRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001348 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Ted Kremenek299e8152008-05-07 21:17:39 +00001349
1350 // Create the "drain" selector.
1351 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek553cf182008-06-25 21:21:56 +00001352 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001353
1354 // Create the -dealloc summary.
1355 Summ = getPersistentSummary(RetEffect::MakeNoRet(), Dealloc);
1356 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001357
1358 // Create the "autorelease" selector.
Ted Kremenekabf43972009-01-28 21:44:40 +00001359 Summ = getPersistentSummary(E, Autorelease);
Ted Kremenek553cf182008-06-25 21:21:56 +00001360 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Ted Kremenek98530452008-08-12 20:41:56 +00001361
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00001362 // Specially handle NSAutoreleasePool.
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001363 addInstMethSummary("NSAutoreleasePool", "init",
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00001364 getPersistentSummary(RetEffect::MakeReceiverAlias(),
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001365 NewAutoreleasePool));
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00001366
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001367 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremenek89e202d2009-02-23 02:51:29 +00001368 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1369 // self-own themselves. However, they only do this once they are displayed.
1370 // Thus, we need to track an NSWindow's display status.
1371 // This is tracked in <rdar://problem/6062711>.
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +00001372 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
Ted Kremenek99d02692009-04-03 19:02:51 +00001373 RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet());
1374
1375 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1376
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +00001377
1378#if 0
Ted Kremenek179064e2008-07-01 17:21:27 +00001379 RetainSummary *NSWindowSumm =
Ted Kremenek89e202d2009-02-23 02:51:29 +00001380 getPersistentSummary(RetEffect::MakeReceiverAlias(), StopTracking);
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001381
1382 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1383 "styleMask", "backing", "defer", NULL);
1384
1385 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1386 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +00001387#endif
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001388
1389 // For NSPanel (which subclasses NSWindow), allocated objects are not
1390 // self-owned.
Ted Kremenek99d02692009-04-03 19:02:51 +00001391 // FIXME: For now we don't track NSPanels. object for the same reason
1392 // as for NSWindow objects.
1393 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
1394
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001395 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1396 "styleMask", "backing", "defer", NULL);
1397
1398 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1399 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek553cf182008-06-25 21:21:56 +00001400
Ted Kremenek70a733e2008-07-18 17:24:20 +00001401 // Create NSAssertionHandler summaries.
Ted Kremenek9e476de2008-08-12 18:30:56 +00001402 addPanicSummary("NSAssertionHandler", "handleFailureInFunction", "file",
1403 "lineNumber", "description", NULL);
Ted Kremenek70a733e2008-07-18 17:24:20 +00001404
Ted Kremenek9e476de2008-08-12 18:30:56 +00001405 addPanicSummary("NSAssertionHandler", "handleFailureInMethod", "object",
1406 "file", "lineNumber", "description", NULL);
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001407}
1408
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001409//===----------------------------------------------------------------------===//
Ted Kremenek13922612008-04-16 20:40:59 +00001410// Reference-counting logic (typestate + counts).
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001411//===----------------------------------------------------------------------===//
1412
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001413namespace {
1414
Ted Kremenek05cbe1a2008-04-09 23:49:11 +00001415class VISIBILITY_HIDDEN RefVal {
Ted Kremenek4fd88972008-04-17 18:12:53 +00001416public:
Ted Kremenek4fd88972008-04-17 18:12:53 +00001417 enum Kind {
1418 Owned = 0, // Owning reference.
1419 NotOwned, // Reference is not owned by still valid (not freed).
1420 Released, // Object has been released.
1421 ReturnedOwned, // Returned object passes ownership to caller.
1422 ReturnedNotOwned, // Return object does not pass ownership to caller.
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001423 ERROR_START,
1424 ErrorDeallocNotOwned, // -dealloc called on non-owned object.
1425 ErrorDeallocGC, // Calling -dealloc with GC enabled.
Ted Kremenek4fd88972008-04-17 18:12:53 +00001426 ErrorUseAfterRelease, // Object used after released.
1427 ErrorReleaseNotOwned, // Release of an object that was not owned.
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001428 ERROR_LEAK_START,
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00001429 ErrorLeak, // A memory leak due to excessive reference counts.
Ted Kremenek369de562009-05-09 00:10:05 +00001430 ErrorLeakReturned, // A memory leak due to the returning method not having
1431 // the correct naming conventions.
1432 ErrorOverAutorelease
Ted Kremenek4fd88972008-04-17 18:12:53 +00001433 };
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001434
1435private:
Ted Kremenek4fd88972008-04-17 18:12:53 +00001436 Kind kind;
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001437 RetEffect::ObjKind okind;
Ted Kremenek4fd88972008-04-17 18:12:53 +00001438 unsigned Cnt;
Ted Kremenekf21332e2009-05-08 20:01:42 +00001439 unsigned ACnt;
Ted Kremenek553cf182008-06-25 21:21:56 +00001440 QualType T;
1441
Ted Kremenekf21332e2009-05-08 20:01:42 +00001442 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, unsigned acnt, QualType t)
1443 : kind(k), okind(o), Cnt(cnt), ACnt(acnt), T(t) {}
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001444
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001445 RefVal(Kind k, unsigned cnt = 0)
Ted Kremenekf21332e2009-05-08 20:01:42 +00001446 : kind(k), okind(RetEffect::AnyObj), Cnt(cnt), ACnt(0) {}
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001447
1448public:
Ted Kremenek4fd88972008-04-17 18:12:53 +00001449 Kind getKind() const { return kind; }
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001450
1451 RetEffect::ObjKind getObjKind() const { return okind; }
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001452
Ted Kremenekf21332e2009-05-08 20:01:42 +00001453 unsigned getCount() const { return Cnt; }
1454 unsigned getAutoreleaseCount() const { return ACnt; }
1455 unsigned getCombinedCounts() const { return Cnt + ACnt; }
1456 void clearCounts() { Cnt = 0; ACnt = 0; }
Ted Kremenek369de562009-05-09 00:10:05 +00001457 void setCount(unsigned i) { Cnt = i; }
1458 void setAutoreleaseCount(unsigned i) { ACnt = i; }
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001459
Ted Kremenek553cf182008-06-25 21:21:56 +00001460 QualType getType() const { return T; }
Ted Kremenek4fd88972008-04-17 18:12:53 +00001461
1462 // Useful predicates.
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001463
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001464 static bool isError(Kind k) { return k >= ERROR_START; }
Ted Kremenek73c750b2008-03-11 18:14:09 +00001465
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001466 static bool isLeak(Kind k) { return k >= ERROR_LEAK_START; }
Ted Kremenekdb863712008-04-16 22:32:20 +00001467
Ted Kremeneke7bd9c22008-04-11 22:25:11 +00001468 bool isOwned() const {
1469 return getKind() == Owned;
1470 }
1471
Ted Kremenekdb863712008-04-16 22:32:20 +00001472 bool isNotOwned() const {
1473 return getKind() == NotOwned;
1474 }
1475
Ted Kremenek4fd88972008-04-17 18:12:53 +00001476 bool isReturnedOwned() const {
1477 return getKind() == ReturnedOwned;
1478 }
1479
1480 bool isReturnedNotOwned() const {
1481 return getKind() == ReturnedNotOwned;
1482 }
1483
1484 bool isNonLeakError() const {
1485 Kind k = getKind();
1486 return isError(k) && !isLeak(k);
1487 }
1488
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001489 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
1490 unsigned Count = 1) {
Ted Kremenekf21332e2009-05-08 20:01:42 +00001491 return RefVal(Owned, o, Count, 0, t);
Ted Kremenek61b9f872008-04-10 23:09:18 +00001492 }
1493
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001494 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
1495 unsigned Count = 0) {
Ted Kremenekf21332e2009-05-08 20:01:42 +00001496 return RefVal(NotOwned, o, Count, 0, t);
Ted Kremenek61b9f872008-04-10 23:09:18 +00001497 }
Ted Kremenek4fd88972008-04-17 18:12:53 +00001498
1499 static RefVal makeReturnedOwned(unsigned Count) {
1500 return RefVal(ReturnedOwned, Count);
1501 }
1502
1503 static RefVal makeReturnedNotOwned() {
1504 return RefVal(ReturnedNotOwned);
1505 }
1506
Ted Kremenek4fd88972008-04-17 18:12:53 +00001507 // Comparison, profiling, and pretty-printing.
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001508
Ted Kremenek4fd88972008-04-17 18:12:53 +00001509 bool operator==(const RefVal& X) const {
Ted Kremenek553cf182008-06-25 21:21:56 +00001510 return kind == X.kind && Cnt == X.Cnt && T == X.T;
Ted Kremenek4fd88972008-04-17 18:12:53 +00001511 }
Ted Kremenekf3948042008-03-11 19:44:10 +00001512
Ted Kremenek553cf182008-06-25 21:21:56 +00001513 RefVal operator-(size_t i) const {
Ted Kremenekf21332e2009-05-08 20:01:42 +00001514 return RefVal(getKind(), getObjKind(), getCount() - i,
1515 getAutoreleaseCount(), getType());
Ted Kremenek553cf182008-06-25 21:21:56 +00001516 }
1517
1518 RefVal operator+(size_t i) const {
Ted Kremenekf21332e2009-05-08 20:01:42 +00001519 return RefVal(getKind(), getObjKind(), getCount() + i,
1520 getAutoreleaseCount(), getType());
Ted Kremenek553cf182008-06-25 21:21:56 +00001521 }
1522
1523 RefVal operator^(Kind k) const {
Ted Kremenekf21332e2009-05-08 20:01:42 +00001524 return RefVal(k, getObjKind(), getCount(), getAutoreleaseCount(),
1525 getType());
1526 }
1527
1528 RefVal autorelease() const {
1529 return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount()+1,
1530 getType());
Ted Kremenek553cf182008-06-25 21:21:56 +00001531 }
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001532
Ted Kremenek4fd88972008-04-17 18:12:53 +00001533 void Profile(llvm::FoldingSetNodeID& ID) const {
1534 ID.AddInteger((unsigned) kind);
1535 ID.AddInteger(Cnt);
Ted Kremenekf21332e2009-05-08 20:01:42 +00001536 ID.AddInteger(ACnt);
Ted Kremenek553cf182008-06-25 21:21:56 +00001537 ID.Add(T);
Ted Kremenek4fd88972008-04-17 18:12:53 +00001538 }
1539
Ted Kremenekf3948042008-03-11 19:44:10 +00001540 void print(std::ostream& Out) const;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001541};
Ted Kremenekf3948042008-03-11 19:44:10 +00001542
1543void RefVal::print(std::ostream& Out) const {
Ted Kremenek553cf182008-06-25 21:21:56 +00001544 if (!T.isNull())
1545 Out << "Tracked Type:" << T.getAsString() << '\n';
1546
Ted Kremenekf3948042008-03-11 19:44:10 +00001547 switch (getKind()) {
1548 default: assert(false);
Ted Kremenek61b9f872008-04-10 23:09:18 +00001549 case Owned: {
1550 Out << "Owned";
1551 unsigned cnt = getCount();
1552 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenekf3948042008-03-11 19:44:10 +00001553 break;
Ted Kremenek61b9f872008-04-10 23:09:18 +00001554 }
Ted Kremenekf3948042008-03-11 19:44:10 +00001555
Ted Kremenek61b9f872008-04-10 23:09:18 +00001556 case NotOwned: {
Ted Kremenek4fd88972008-04-17 18:12:53 +00001557 Out << "NotOwned";
Ted Kremenek61b9f872008-04-10 23:09:18 +00001558 unsigned cnt = getCount();
1559 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenekf3948042008-03-11 19:44:10 +00001560 break;
Ted Kremenek61b9f872008-04-10 23:09:18 +00001561 }
Ted Kremenekf3948042008-03-11 19:44:10 +00001562
Ted Kremenek4fd88972008-04-17 18:12:53 +00001563 case ReturnedOwned: {
1564 Out << "ReturnedOwned";
1565 unsigned cnt = getCount();
1566 if (cnt) Out << " (+ " << cnt << ")";
1567 break;
1568 }
1569
1570 case ReturnedNotOwned: {
1571 Out << "ReturnedNotOwned";
1572 unsigned cnt = getCount();
1573 if (cnt) Out << " (+ " << cnt << ")";
1574 break;
1575 }
1576
Ted Kremenekf3948042008-03-11 19:44:10 +00001577 case Released:
1578 Out << "Released";
1579 break;
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001580
1581 case ErrorDeallocGC:
1582 Out << "-dealloc (GC)";
1583 break;
1584
1585 case ErrorDeallocNotOwned:
1586 Out << "-dealloc (not-owned)";
1587 break;
Ted Kremenekf3948042008-03-11 19:44:10 +00001588
Ted Kremenekdb863712008-04-16 22:32:20 +00001589 case ErrorLeak:
1590 Out << "Leaked";
1591 break;
1592
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00001593 case ErrorLeakReturned:
1594 Out << "Leaked (Bad naming)";
1595 break;
1596
Ted Kremenekf3948042008-03-11 19:44:10 +00001597 case ErrorUseAfterRelease:
1598 Out << "Use-After-Release [ERROR]";
1599 break;
1600
1601 case ErrorReleaseNotOwned:
1602 Out << "Release of Not-Owned [ERROR]";
1603 break;
Ted Kremenek80c24182009-05-09 00:44:07 +00001604
1605 case RefVal::ErrorOverAutorelease:
1606 Out << "Over autoreleased";
1607 break;
Ted Kremenekf3948042008-03-11 19:44:10 +00001608 }
Ted Kremenekf21332e2009-05-08 20:01:42 +00001609
1610 if (ACnt) {
1611 Out << " [ARC +" << ACnt << ']';
1612 }
Ted Kremenekf3948042008-03-11 19:44:10 +00001613}
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001614
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001615} // end anonymous namespace
1616
1617//===----------------------------------------------------------------------===//
1618// RefBindings - State used to track object reference counts.
1619//===----------------------------------------------------------------------===//
1620
Ted Kremenek2dabd432008-12-05 02:27:51 +00001621typedef llvm::ImmutableMap<SymbolRef, RefVal> RefBindings;
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001622static int RefBIndex = 0;
1623
1624namespace clang {
Ted Kremenekb9d17f92008-08-17 03:20:02 +00001625 template<>
1626 struct GRStateTrait<RefBindings> : public GRStatePartialTrait<RefBindings> {
1627 static inline void* GDMIndex() { return &RefBIndex; }
1628 };
1629}
Ted Kremenek6d348932008-10-21 15:53:15 +00001630
1631//===----------------------------------------------------------------------===//
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001632// AutoreleaseBindings - State used to track objects in autorelease pools.
Ted Kremenek6d348932008-10-21 15:53:15 +00001633//===----------------------------------------------------------------------===//
1634
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001635typedef llvm::ImmutableMap<SymbolRef, unsigned> ARCounts;
1636typedef llvm::ImmutableMap<SymbolRef, ARCounts> ARPoolContents;
1637typedef llvm::ImmutableList<SymbolRef> ARStack;
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00001638
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001639static int AutoRCIndex = 0;
Ted Kremenek6d348932008-10-21 15:53:15 +00001640static int AutoRBIndex = 0;
1641
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001642namespace { class VISIBILITY_HIDDEN AutoreleasePoolContents {}; }
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001643namespace { class VISIBILITY_HIDDEN AutoreleaseStack {}; }
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001644
Ted Kremenek6d348932008-10-21 15:53:15 +00001645namespace clang {
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001646template<> struct GRStateTrait<AutoreleaseStack>
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001647 : public GRStatePartialTrait<ARStack> {
1648 static inline void* GDMIndex() { return &AutoRBIndex; }
1649};
1650
1651template<> struct GRStateTrait<AutoreleasePoolContents>
1652 : public GRStatePartialTrait<ARPoolContents> {
1653 static inline void* GDMIndex() { return &AutoRCIndex; }
1654};
1655} // end clang namespace
Ted Kremenek6d348932008-10-21 15:53:15 +00001656
Ted Kremenek7037ab82009-03-20 17:34:15 +00001657static SymbolRef GetCurrentAutoreleasePool(const GRState* state) {
1658 ARStack stack = state->get<AutoreleaseStack>();
1659 return stack.isEmpty() ? SymbolRef() : stack.getHead();
1660}
1661
1662static GRStateRef SendAutorelease(GRStateRef state, ARCounts::Factory &F,
1663 SymbolRef sym) {
1664
1665 SymbolRef pool = GetCurrentAutoreleasePool(state);
1666 const ARCounts *cnts = state.get<AutoreleasePoolContents>(pool);
1667 ARCounts newCnts(0);
1668
1669 if (cnts) {
1670 const unsigned *cnt = (*cnts).lookup(sym);
1671 newCnts = F.Add(*cnts, sym, cnt ? *cnt + 1 : 1);
1672 }
1673 else
1674 newCnts = F.Add(F.GetEmptyMap(), sym, 1);
1675
1676 return state.set<AutoreleasePoolContents>(pool, newCnts);
1677}
1678
Ted Kremenek13922612008-04-16 20:40:59 +00001679//===----------------------------------------------------------------------===//
1680// Transfer functions.
1681//===----------------------------------------------------------------------===//
1682
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001683namespace {
1684
Ted Kremenek05cbe1a2008-04-09 23:49:11 +00001685class VISIBILITY_HIDDEN CFRefCount : public GRSimpleVals {
Ted Kremenek8dd56462008-04-18 03:39:05 +00001686public:
Ted Kremenekae6814e2008-08-13 21:24:49 +00001687 class BindingsPrinter : public GRState::Printer {
Ted Kremenekf3948042008-03-11 19:44:10 +00001688 public:
Ted Kremenekae6814e2008-08-13 21:24:49 +00001689 virtual void Print(std::ostream& Out, const GRState* state,
1690 const char* nl, const char* sep);
Ted Kremenekf3948042008-03-11 19:44:10 +00001691 };
Ted Kremenek8dd56462008-04-18 03:39:05 +00001692
1693private:
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001694 typedef llvm::DenseMap<const GRExprEngine::NodeTy*, const RetainSummary*>
1695 SummaryLogTy;
1696
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001697 RetainSummaryManager Summaries;
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001698 SummaryLogTy SummaryLog;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001699 const LangOptions& LOpts;
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001700 ARCounts::Factory ARCountFactory;
Ted Kremenekb9d17f92008-08-17 03:20:02 +00001701
Ted Kremenekcf701772009-02-05 06:50:21 +00001702 BugType *useAfterRelease, *releaseNotOwned;
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001703 BugType *deallocGC, *deallocNotOwned;
Ted Kremenekcf701772009-02-05 06:50:21 +00001704 BugType *leakWithinFunction, *leakAtReturn;
Ted Kremenek369de562009-05-09 00:10:05 +00001705 BugType *overAutorelease;
Ted Kremenekcf701772009-02-05 06:50:21 +00001706 BugReporter *BR;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001707
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001708 GRStateRef Update(GRStateRef state, SymbolRef sym, RefVal V, ArgEffect E,
1709 RefVal::Kind& hasErr);
1710
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001711 void ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
1712 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekdb863712008-04-16 22:32:20 +00001713 Expr* NodeExpr, Expr* ErrorExpr,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001714 ExplodedNode<GRState>* Pred,
1715 const GRState* St,
Ted Kremenek2dabd432008-12-05 02:27:51 +00001716 RefVal::Kind hasErr, SymbolRef Sym);
Ted Kremenekdb863712008-04-16 22:32:20 +00001717
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00001718 GRStateRef HandleSymbolDeath(GRStateRef state, SymbolRef sid, RefVal V,
1719 llvm::SmallVectorImpl<SymbolRef> &Leaked);
1720
1721 ExplodedNode<GRState>* ProcessLeaks(GRStateRef state,
1722 llvm::SmallVectorImpl<SymbolRef> &Leaked,
1723 GenericNodeBuilder &Builder,
1724 GRExprEngine &Eng,
1725 ExplodedNode<GRState> *Pred = 0);
Ted Kremenekdb863712008-04-16 22:32:20 +00001726
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001727public:
Ted Kremenek78d46242008-07-22 16:21:24 +00001728 CFRefCount(ASTContext& Ctx, bool gcenabled, const LangOptions& lopts)
Ted Kremenek377e2302008-04-29 05:33:51 +00001729 : Summaries(Ctx, gcenabled),
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001730 LOpts(lopts), useAfterRelease(0), releaseNotOwned(0),
1731 deallocGC(0), deallocNotOwned(0),
Ted Kremenek369de562009-05-09 00:10:05 +00001732 leakWithinFunction(0), leakAtReturn(0), overAutorelease(0), BR(0) {}
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001733
Ted Kremenekcf701772009-02-05 06:50:21 +00001734 virtual ~CFRefCount() {}
Ted Kremenek05cbe1a2008-04-09 23:49:11 +00001735
Ted Kremenekcf118d42009-02-04 23:49:09 +00001736 void RegisterChecks(BugReporter &BR);
Ted Kremenekf3948042008-03-11 19:44:10 +00001737
Ted Kremenek1c72ef02008-08-16 00:49:49 +00001738 virtual void RegisterPrinters(std::vector<GRState::Printer*>& Printers) {
1739 Printers.push_back(new BindingsPrinter());
Ted Kremenekf3948042008-03-11 19:44:10 +00001740 }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001741
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001742 bool isGCEnabled() const { return Summaries.isGCEnabled(); }
Ted Kremenek072192b2008-04-30 23:47:44 +00001743 const LangOptions& getLangOptions() const { return LOpts; }
1744
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001745 const RetainSummary *getSummaryOfNode(const ExplodedNode<GRState> *N) const {
1746 SummaryLogTy::const_iterator I = SummaryLog.find(N);
1747 return I == SummaryLog.end() ? 0 : I->second;
1748 }
1749
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001750 // Calls.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001751
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001752 void EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001753 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001754 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001755 Expr* Ex,
1756 Expr* Receiver,
Ted Kremenek7faca822009-05-04 04:57:00 +00001757 const RetainSummary& Summ,
Ted Kremenek55499762008-06-17 02:43:46 +00001758 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001759 ExplodedNode<GRState>* Pred);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001760
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001761 virtual void EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek199e1a02008-03-12 21:06:49 +00001762 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001763 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001764 CallExpr* CE, SVal L,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001765 ExplodedNode<GRState>* Pred);
Ted Kremenekfa34b332008-04-09 01:10:13 +00001766
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001767
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001768 virtual void EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek85348202008-04-15 23:44:31 +00001769 GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001770 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek85348202008-04-15 23:44:31 +00001771 ObjCMessageExpr* ME,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001772 ExplodedNode<GRState>* Pred);
Ted Kremenek85348202008-04-15 23:44:31 +00001773
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001774 bool EvalObjCMessageExprAux(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek85348202008-04-15 23:44:31 +00001775 GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001776 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek85348202008-04-15 23:44:31 +00001777 ObjCMessageExpr* ME,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001778 ExplodedNode<GRState>* Pred);
Ted Kremenek85348202008-04-15 23:44:31 +00001779
Ted Kremenek41573eb2009-02-14 01:43:44 +00001780 // Stores.
1781 virtual void EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val);
1782
Ted Kremeneke7bd9c22008-04-11 22:25:11 +00001783 // End-of-path.
1784
1785 virtual void EvalEndPath(GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001786 GREndPathNodeBuilder<GRState>& Builder);
Ted Kremeneke7bd9c22008-04-11 22:25:11 +00001787
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001788 virtual void EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek652adc62008-04-24 23:57:27 +00001789 GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001790 GRStmtNodeBuilder<GRState>& Builder,
1791 ExplodedNode<GRState>* Pred,
Ted Kremenek241677a2009-01-21 22:26:05 +00001792 Stmt* S, const GRState* state,
1793 SymbolReaper& SymReaper);
Ted Kremenekf04dced2009-05-08 23:32:51 +00001794
1795 std::pair<ExplodedNode<GRState>*, GRStateRef>
1796 HandleAutoreleaseCounts(GRStateRef state, GenericNodeBuilder Bd,
Ted Kremenek369de562009-05-09 00:10:05 +00001797 ExplodedNode<GRState>* Pred, GRExprEngine &Eng,
1798 SymbolRef Sym, RefVal V, bool &stop);
Ted Kremenek4fd88972008-04-17 18:12:53 +00001799 // Return statements.
1800
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001801 virtual void EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4fd88972008-04-17 18:12:53 +00001802 GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001803 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4fd88972008-04-17 18:12:53 +00001804 ReturnStmt* S,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001805 ExplodedNode<GRState>* Pred);
Ted Kremenekcb612922008-04-18 19:23:43 +00001806
1807 // Assumptions.
1808
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001809 virtual const GRState* EvalAssume(GRStateManager& VMgr,
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001810 const GRState* St, SVal Cond,
Ted Kremenek4323a572008-07-10 22:03:41 +00001811 bool Assumption, bool& isFeasible);
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001812};
1813
1814} // end anonymous namespace
1815
Ted Kremenek7037ab82009-03-20 17:34:15 +00001816static void PrintPool(std::ostream &Out, SymbolRef Sym, const GRState *state) {
1817 Out << ' ';
Ted Kremeneke0e4ebf2009-03-26 03:35:11 +00001818 if (Sym)
1819 Out << Sym->getSymbolID();
Ted Kremenek7037ab82009-03-20 17:34:15 +00001820 else
1821 Out << "<pool>";
1822 Out << ":{";
1823
1824 // Get the contents of the pool.
1825 if (const ARCounts *cnts = state->get<AutoreleasePoolContents>(Sym))
1826 for (ARCounts::iterator J=cnts->begin(), EJ=cnts->end(); J != EJ; ++J)
1827 Out << '(' << J.getKey() << ',' << J.getData() << ')';
1828
1829 Out << '}';
1830}
Ted Kremenek8dd56462008-04-18 03:39:05 +00001831
Ted Kremenekae6814e2008-08-13 21:24:49 +00001832void CFRefCount::BindingsPrinter::Print(std::ostream& Out, const GRState* state,
1833 const char* nl, const char* sep) {
Ted Kremenek7037ab82009-03-20 17:34:15 +00001834
1835
Ted Kremenekae6814e2008-08-13 21:24:49 +00001836
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001837 RefBindings B = state->get<RefBindings>();
Ted Kremenekf3948042008-03-11 19:44:10 +00001838
Ted Kremenekae6814e2008-08-13 21:24:49 +00001839 if (!B.isEmpty())
Ted Kremenekf3948042008-03-11 19:44:10 +00001840 Out << sep << nl;
1841
1842 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
1843 Out << (*I).first << " : ";
1844 (*I).second.print(Out);
1845 Out << nl;
1846 }
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001847
1848 // Print the autorelease stack.
Ted Kremenek7037ab82009-03-20 17:34:15 +00001849 Out << sep << nl << "AR pool stack:";
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001850 ARStack stack = state->get<AutoreleaseStack>();
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001851
Ted Kremenek7037ab82009-03-20 17:34:15 +00001852 PrintPool(Out, SymbolRef(), state); // Print the caller's pool.
1853 for (ARStack::iterator I=stack.begin(), E=stack.end(); I!=E; ++I)
1854 PrintPool(Out, *I, state);
1855
1856 Out << nl;
Ted Kremenekf3948042008-03-11 19:44:10 +00001857}
1858
Ted Kremenekc887d132009-04-29 18:50:19 +00001859//===----------------------------------------------------------------------===//
1860// Error reporting.
1861//===----------------------------------------------------------------------===//
1862
1863namespace {
1864
1865 //===-------------===//
1866 // Bug Descriptions. //
1867 //===-------------===//
1868
1869 class VISIBILITY_HIDDEN CFRefBug : public BugType {
1870 protected:
1871 CFRefCount& TF;
1872
1873 CFRefBug(CFRefCount* tf, const char* name)
1874 : BugType(name, "Memory (Core Foundation/Objective-C)"), TF(*tf) {}
1875 public:
1876
1877 CFRefCount& getTF() { return TF; }
1878 const CFRefCount& getTF() const { return TF; }
1879
1880 // FIXME: Eventually remove.
1881 virtual const char* getDescription() const = 0;
1882
1883 virtual bool isLeak() const { return false; }
1884 };
1885
1886 class VISIBILITY_HIDDEN UseAfterRelease : public CFRefBug {
1887 public:
1888 UseAfterRelease(CFRefCount* tf)
1889 : CFRefBug(tf, "Use-after-release") {}
1890
1891 const char* getDescription() const {
1892 return "Reference-counted object is used after it is released";
1893 }
1894 };
1895
1896 class VISIBILITY_HIDDEN BadRelease : public CFRefBug {
1897 public:
1898 BadRelease(CFRefCount* tf) : CFRefBug(tf, "Bad release") {}
1899
1900 const char* getDescription() const {
1901 return "Incorrect decrement of the reference count of an "
1902 "object is not owned at this point by the caller";
1903 }
1904 };
1905
1906 class VISIBILITY_HIDDEN DeallocGC : public CFRefBug {
1907 public:
Ted Kremenek369de562009-05-09 00:10:05 +00001908 DeallocGC(CFRefCount *tf)
1909 : CFRefBug(tf, "-dealloc called while using garbage collection") {}
Ted Kremenekc887d132009-04-29 18:50:19 +00001910
1911 const char *getDescription() const {
Ted Kremenek369de562009-05-09 00:10:05 +00001912 return "-dealloc called while using garbage collection";
Ted Kremenekc887d132009-04-29 18:50:19 +00001913 }
1914 };
1915
1916 class VISIBILITY_HIDDEN DeallocNotOwned : public CFRefBug {
1917 public:
Ted Kremenek369de562009-05-09 00:10:05 +00001918 DeallocNotOwned(CFRefCount *tf)
1919 : CFRefBug(tf, "-dealloc sent to non-exclusively owned object") {}
Ted Kremenekc887d132009-04-29 18:50:19 +00001920
1921 const char *getDescription() const {
1922 return "-dealloc sent to object that may be referenced elsewhere";
1923 }
1924 };
1925
Ted Kremenek369de562009-05-09 00:10:05 +00001926 class VISIBILITY_HIDDEN OverAutorelease : public CFRefBug {
1927 public:
1928 OverAutorelease(CFRefCount *tf) :
1929 CFRefBug(tf, "Object sent -autorelease too many times") {}
1930
1931 const char *getDescription() const {
1932 return "Object will be sent more -release messages from its containing "
1933 "autorelease pools than it has retain counts";
1934 }
1935 };
1936
Ted Kremenekc887d132009-04-29 18:50:19 +00001937 class VISIBILITY_HIDDEN Leak : public CFRefBug {
1938 const bool isReturn;
1939 protected:
1940 Leak(CFRefCount* tf, const char* name, bool isRet)
1941 : CFRefBug(tf, name), isReturn(isRet) {}
1942 public:
1943
1944 const char* getDescription() const { return ""; }
1945
1946 bool isLeak() const { return true; }
1947 };
1948
1949 class VISIBILITY_HIDDEN LeakAtReturn : public Leak {
1950 public:
1951 LeakAtReturn(CFRefCount* tf, const char* name)
1952 : Leak(tf, name, true) {}
1953 };
1954
1955 class VISIBILITY_HIDDEN LeakWithinFunction : public Leak {
1956 public:
1957 LeakWithinFunction(CFRefCount* tf, const char* name)
1958 : Leak(tf, name, false) {}
1959 };
1960
1961 //===---------===//
1962 // Bug Reports. //
1963 //===---------===//
1964
1965 class VISIBILITY_HIDDEN CFRefReport : public RangedBugReport {
1966 protected:
1967 SymbolRef Sym;
1968 const CFRefCount &TF;
1969 public:
1970 CFRefReport(CFRefBug& D, const CFRefCount &tf,
1971 ExplodedNode<GRState> *n, SymbolRef sym)
1972 : RangedBugReport(D, D.getDescription(), n), Sym(sym), TF(tf) {}
1973
1974 virtual ~CFRefReport() {}
1975
1976 CFRefBug& getBugType() {
1977 return (CFRefBug&) RangedBugReport::getBugType();
1978 }
1979 const CFRefBug& getBugType() const {
1980 return (const CFRefBug&) RangedBugReport::getBugType();
1981 }
1982
1983 virtual void getRanges(BugReporter& BR, const SourceRange*& beg,
1984 const SourceRange*& end) {
1985
1986 if (!getBugType().isLeak())
1987 RangedBugReport::getRanges(BR, beg, end);
1988 else
1989 beg = end = 0;
1990 }
1991
1992 SymbolRef getSymbol() const { return Sym; }
1993
Ted Kremenek8966bc12009-05-06 21:39:49 +00001994 PathDiagnosticPiece* getEndPath(BugReporterContext& BRC,
Ted Kremenekc887d132009-04-29 18:50:19 +00001995 const ExplodedNode<GRState>* N);
1996
1997 std::pair<const char**,const char**> getExtraDescriptiveText();
1998
1999 PathDiagnosticPiece* VisitNode(const ExplodedNode<GRState>* N,
2000 const ExplodedNode<GRState>* PrevN,
Ted Kremenek8966bc12009-05-06 21:39:49 +00002001 BugReporterContext& BRC);
Ted Kremenekc887d132009-04-29 18:50:19 +00002002 };
2003
2004 class VISIBILITY_HIDDEN CFRefLeakReport : public CFRefReport {
2005 SourceLocation AllocSite;
2006 const MemRegion* AllocBinding;
2007 public:
2008 CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2009 ExplodedNode<GRState> *n, SymbolRef sym,
2010 GRExprEngine& Eng);
2011
Ted Kremenek8966bc12009-05-06 21:39:49 +00002012 PathDiagnosticPiece* getEndPath(BugReporterContext& BRC,
Ted Kremenekc887d132009-04-29 18:50:19 +00002013 const ExplodedNode<GRState>* N);
2014
2015 SourceLocation getLocation() const { return AllocSite; }
2016 };
2017} // end anonymous namespace
2018
2019void CFRefCount::RegisterChecks(BugReporter& BR) {
2020 useAfterRelease = new UseAfterRelease(this);
2021 BR.Register(useAfterRelease);
2022
2023 releaseNotOwned = new BadRelease(this);
2024 BR.Register(releaseNotOwned);
2025
2026 deallocGC = new DeallocGC(this);
2027 BR.Register(deallocGC);
2028
2029 deallocNotOwned = new DeallocNotOwned(this);
2030 BR.Register(deallocNotOwned);
2031
Ted Kremenek369de562009-05-09 00:10:05 +00002032 overAutorelease = new OverAutorelease(this);
2033 BR.Register(overAutorelease);
2034
Ted Kremenekc887d132009-04-29 18:50:19 +00002035 // First register "return" leaks.
2036 const char* name = 0;
2037
2038 if (isGCEnabled())
2039 name = "Leak of returned object when using garbage collection";
2040 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2041 name = "Leak of returned object when not using garbage collection (GC) in "
2042 "dual GC/non-GC code";
2043 else {
2044 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2045 name = "Leak of returned object";
2046 }
2047
2048 leakAtReturn = new LeakAtReturn(this, name);
2049 BR.Register(leakAtReturn);
2050
2051 // Second, register leaks within a function/method.
2052 if (isGCEnabled())
2053 name = "Leak of object when using garbage collection";
2054 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2055 name = "Leak of object when not using garbage collection (GC) in "
2056 "dual GC/non-GC code";
2057 else {
2058 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2059 name = "Leak";
2060 }
2061
2062 leakWithinFunction = new LeakWithinFunction(this, name);
2063 BR.Register(leakWithinFunction);
2064
2065 // Save the reference to the BugReporter.
2066 this->BR = &BR;
2067}
2068
2069static const char* Msgs[] = {
2070 // GC only
2071 "Code is compiled to only use garbage collection",
2072 // No GC.
2073 "Code is compiled to use reference counts",
2074 // Hybrid, with GC.
2075 "Code is compiled to use either garbage collection (GC) or reference counts"
2076 " (non-GC). The bug occurs with GC enabled",
2077 // Hybrid, without GC
2078 "Code is compiled to use either garbage collection (GC) or reference counts"
2079 " (non-GC). The bug occurs in non-GC mode"
2080};
2081
2082std::pair<const char**,const char**> CFRefReport::getExtraDescriptiveText() {
2083 CFRefCount& TF = static_cast<CFRefBug&>(getBugType()).getTF();
2084
2085 switch (TF.getLangOptions().getGCMode()) {
2086 default:
2087 assert(false);
2088
2089 case LangOptions::GCOnly:
2090 assert (TF.isGCEnabled());
2091 return std::make_pair(&Msgs[0], &Msgs[0]+1);
2092
2093 case LangOptions::NonGC:
2094 assert (!TF.isGCEnabled());
2095 return std::make_pair(&Msgs[1], &Msgs[1]+1);
2096
2097 case LangOptions::HybridGC:
2098 if (TF.isGCEnabled())
2099 return std::make_pair(&Msgs[2], &Msgs[2]+1);
2100 else
2101 return std::make_pair(&Msgs[3], &Msgs[3]+1);
2102 }
2103}
2104
2105static inline bool contains(const llvm::SmallVectorImpl<ArgEffect>& V,
2106 ArgEffect X) {
2107 for (llvm::SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
2108 I!=E; ++I)
2109 if (*I == X) return true;
2110
2111 return false;
2112}
2113
2114PathDiagnosticPiece* CFRefReport::VisitNode(const ExplodedNode<GRState>* N,
2115 const ExplodedNode<GRState>* PrevN,
Ted Kremenek8966bc12009-05-06 21:39:49 +00002116 BugReporterContext& BRC) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002117
Ted Kremenek8966bc12009-05-06 21:39:49 +00002118 // Check if the type state has changed.
2119 GRStateManager &StMgr = BRC.getStateManager();
Ted Kremenekc887d132009-04-29 18:50:19 +00002120 GRStateRef PrevSt(PrevN->getState(), StMgr);
2121 GRStateRef CurrSt(N->getState(), StMgr);
2122
2123 const RefVal* CurrT = CurrSt.get<RefBindings>(Sym);
2124 if (!CurrT) return NULL;
2125
2126 const RefVal& CurrV = *CurrT;
2127 const RefVal* PrevT = PrevSt.get<RefBindings>(Sym);
2128
2129 // Create a string buffer to constain all the useful things we want
2130 // to tell the user.
2131 std::string sbuf;
2132 llvm::raw_string_ostream os(sbuf);
2133
2134 // This is the allocation site since the previous node had no bindings
2135 // for this symbol.
2136 if (!PrevT) {
2137 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2138
2139 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2140 // Get the name of the callee (if it is available).
2141 SVal X = CurrSt.GetSValAsScalarOrLoc(CE->getCallee());
2142 if (const FunctionDecl* FD = X.getAsFunctionDecl())
2143 os << "Call to function '" << FD->getNameAsString() <<'\'';
2144 else
2145 os << "function call";
2146 }
2147 else {
2148 assert (isa<ObjCMessageExpr>(S));
2149 os << "Method";
2150 }
2151
2152 if (CurrV.getObjKind() == RetEffect::CF) {
2153 os << " returns a Core Foundation object with a ";
2154 }
2155 else {
2156 assert (CurrV.getObjKind() == RetEffect::ObjC);
2157 os << " returns an Objective-C object with a ";
2158 }
2159
2160 if (CurrV.isOwned()) {
2161 os << "+1 retain count (owning reference).";
2162
2163 if (static_cast<CFRefBug&>(getBugType()).getTF().isGCEnabled()) {
2164 assert(CurrV.getObjKind() == RetEffect::CF);
2165 os << " "
2166 "Core Foundation objects are not automatically garbage collected.";
2167 }
2168 }
2169 else {
2170 assert (CurrV.isNotOwned());
2171 os << "+0 retain count (non-owning reference).";
2172 }
2173
Ted Kremenek8966bc12009-05-06 21:39:49 +00002174 PathDiagnosticLocation Pos(S, BRC.getSourceManager());
Ted Kremenekc887d132009-04-29 18:50:19 +00002175 return new PathDiagnosticEventPiece(Pos, os.str());
2176 }
2177
2178 // Gather up the effects that were performed on the object at this
2179 // program point
2180 llvm::SmallVector<ArgEffect, 2> AEffects;
2181
Ted Kremenek8966bc12009-05-06 21:39:49 +00002182 if (const RetainSummary *Summ =
2183 TF.getSummaryOfNode(BRC.getNodeResolver().getOriginalNode(N))) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002184 // We only have summaries attached to nodes after evaluating CallExpr and
2185 // ObjCMessageExprs.
2186 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2187
2188 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2189 // Iterate through the parameter expressions and see if the symbol
2190 // was ever passed as an argument.
2191 unsigned i = 0;
2192
2193 for (CallExpr::arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
2194 AI!=AE; ++AI, ++i) {
2195
2196 // Retrieve the value of the argument. Is it the symbol
2197 // we are interested in?
2198 if (CurrSt.GetSValAsScalarOrLoc(*AI).getAsLocSymbol() != Sym)
2199 continue;
2200
2201 // We have an argument. Get the effect!
2202 AEffects.push_back(Summ->getArg(i));
2203 }
2204 }
2205 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
2206 if (Expr *receiver = ME->getReceiver())
2207 if (CurrSt.GetSValAsScalarOrLoc(receiver).getAsLocSymbol() == Sym) {
2208 // The symbol we are tracking is the receiver.
2209 AEffects.push_back(Summ->getReceiverEffect());
2210 }
2211 }
2212 }
2213
2214 do {
2215 // Get the previous type state.
2216 RefVal PrevV = *PrevT;
2217
2218 // Specially handle -dealloc.
2219 if (!TF.isGCEnabled() && contains(AEffects, Dealloc)) {
2220 // Determine if the object's reference count was pushed to zero.
2221 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2222 // We may not have transitioned to 'release' if we hit an error.
2223 // This case is handled elsewhere.
2224 if (CurrV.getKind() == RefVal::Released) {
Ted Kremenekf21332e2009-05-08 20:01:42 +00002225 assert(CurrV.getCombinedCounts() == 0);
Ted Kremenekc887d132009-04-29 18:50:19 +00002226 os << "Object released by directly sending the '-dealloc' message";
2227 break;
2228 }
2229 }
2230
2231 // Specially handle CFMakeCollectable and friends.
2232 if (contains(AEffects, MakeCollectable)) {
2233 // Get the name of the function.
2234 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2235 SVal X = CurrSt.GetSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee());
2236 const FunctionDecl* FD = X.getAsFunctionDecl();
2237 const std::string& FName = FD->getNameAsString();
2238
2239 if (TF.isGCEnabled()) {
2240 // Determine if the object's reference count was pushed to zero.
2241 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2242
2243 os << "In GC mode a call to '" << FName
2244 << "' decrements an object's retain count and registers the "
2245 "object with the garbage collector. ";
2246
2247 if (CurrV.getKind() == RefVal::Released) {
2248 assert(CurrV.getCount() == 0);
2249 os << "Since it now has a 0 retain count the object can be "
2250 "automatically collected by the garbage collector.";
2251 }
2252 else
2253 os << "An object must have a 0 retain count to be garbage collected. "
2254 "After this call its retain count is +" << CurrV.getCount()
2255 << '.';
2256 }
2257 else
2258 os << "When GC is not enabled a call to '" << FName
2259 << "' has no effect on its argument.";
2260
2261 // Nothing more to say.
2262 break;
2263 }
2264
2265 // Determine if the typestate has changed.
2266 if (!(PrevV == CurrV))
2267 switch (CurrV.getKind()) {
2268 case RefVal::Owned:
2269 case RefVal::NotOwned:
2270
Ted Kremenekf21332e2009-05-08 20:01:42 +00002271 if (PrevV.getCount() == CurrV.getCount()) {
2272 // Did an autorelease message get sent?
2273 if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
2274 return 0;
2275
2276 assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount());
2277 os << "Object added to autorelease pool.";
2278 break;
2279 }
Ted Kremenekc887d132009-04-29 18:50:19 +00002280
2281 if (PrevV.getCount() > CurrV.getCount())
2282 os << "Reference count decremented.";
2283 else
2284 os << "Reference count incremented.";
2285
2286 if (unsigned Count = CurrV.getCount())
2287 os << " The object now has a +" << Count << " retain count.";
2288
2289 if (PrevV.getKind() == RefVal::Released) {
2290 assert(TF.isGCEnabled() && CurrV.getCount() > 0);
2291 os << " The object is not eligible for garbage collection until the "
2292 "retain count reaches 0 again.";
2293 }
2294
2295 break;
2296
2297 case RefVal::Released:
2298 os << "Object released.";
2299 break;
2300
2301 case RefVal::ReturnedOwned:
2302 os << "Object returned to caller as an owning reference (single retain "
2303 "count transferred to caller).";
2304 break;
2305
2306 case RefVal::ReturnedNotOwned:
2307 os << "Object returned to caller with a +0 (non-owning) retain count.";
2308 break;
2309
2310 default:
2311 return NULL;
2312 }
2313
2314 // Emit any remaining diagnostics for the argument effects (if any).
2315 for (llvm::SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
2316 E=AEffects.end(); I != E; ++I) {
2317
2318 // A bunch of things have alternate behavior under GC.
2319 if (TF.isGCEnabled())
2320 switch (*I) {
2321 default: break;
2322 case Autorelease:
2323 os << "In GC mode an 'autorelease' has no effect.";
2324 continue;
2325 case IncRefMsg:
2326 os << "In GC mode the 'retain' message has no effect.";
2327 continue;
2328 case DecRefMsg:
2329 os << "In GC mode the 'release' message has no effect.";
2330 continue;
2331 }
2332 }
2333 } while(0);
2334
2335 if (os.str().empty())
2336 return 0; // We have nothing to say!
2337
2338 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
Ted Kremenek8966bc12009-05-06 21:39:49 +00002339 PathDiagnosticLocation Pos(S, BRC.getSourceManager());
Ted Kremenekc887d132009-04-29 18:50:19 +00002340 PathDiagnosticPiece* P = new PathDiagnosticEventPiece(Pos, os.str());
2341
2342 // Add the range by scanning the children of the statement for any bindings
2343 // to Sym.
2344 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I)
2345 if (Expr* Exp = dyn_cast_or_null<Expr>(*I))
2346 if (CurrSt.GetSValAsScalarOrLoc(Exp).getAsLocSymbol() == Sym) {
2347 P->addRange(Exp->getSourceRange());
2348 break;
2349 }
2350
2351 return P;
2352}
2353
2354namespace {
2355 class VISIBILITY_HIDDEN FindUniqueBinding :
2356 public StoreManager::BindingsHandler {
2357 SymbolRef Sym;
2358 const MemRegion* Binding;
2359 bool First;
2360
2361 public:
2362 FindUniqueBinding(SymbolRef sym) : Sym(sym), Binding(0), First(true) {}
2363
2364 bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
2365 SVal val) {
2366
2367 SymbolRef SymV = val.getAsSymbol();
2368 if (!SymV || SymV != Sym)
2369 return true;
2370
2371 if (Binding) {
2372 First = false;
2373 return false;
2374 }
2375 else
2376 Binding = R;
2377
2378 return true;
2379 }
2380
2381 operator bool() { return First && Binding; }
2382 const MemRegion* getRegion() { return Binding; }
2383 };
2384}
2385
2386static std::pair<const ExplodedNode<GRState>*,const MemRegion*>
2387GetAllocationSite(GRStateManager& StateMgr, const ExplodedNode<GRState>* N,
2388 SymbolRef Sym) {
2389
2390 // Find both first node that referred to the tracked symbol and the
2391 // memory location that value was store to.
2392 const ExplodedNode<GRState>* Last = N;
2393 const MemRegion* FirstBinding = 0;
2394
2395 while (N) {
2396 const GRState* St = N->getState();
2397 RefBindings B = St->get<RefBindings>();
2398
2399 if (!B.lookup(Sym))
2400 break;
2401
2402 FindUniqueBinding FB(Sym);
2403 StateMgr.iterBindings(St, FB);
2404 if (FB) FirstBinding = FB.getRegion();
2405
2406 Last = N;
2407 N = N->pred_empty() ? NULL : *(N->pred_begin());
2408 }
2409
2410 return std::make_pair(Last, FirstBinding);
2411}
2412
2413PathDiagnosticPiece*
Ted Kremenek8966bc12009-05-06 21:39:49 +00002414CFRefReport::getEndPath(BugReporterContext& BRC,
2415 const ExplodedNode<GRState>* EndN) {
2416 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenekc887d132009-04-29 18:50:19 +00002417 // assigned to different variables, etc.
Ted Kremenek8966bc12009-05-06 21:39:49 +00002418 BRC.addNotableSymbol(Sym);
2419 return RangedBugReport::getEndPath(BRC, EndN);
Ted Kremenekc887d132009-04-29 18:50:19 +00002420}
2421
2422PathDiagnosticPiece*
Ted Kremenek8966bc12009-05-06 21:39:49 +00002423CFRefLeakReport::getEndPath(BugReporterContext& BRC,
2424 const ExplodedNode<GRState>* EndN){
Ted Kremenekc887d132009-04-29 18:50:19 +00002425
Ted Kremenek8966bc12009-05-06 21:39:49 +00002426 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenekc887d132009-04-29 18:50:19 +00002427 // assigned to different variables, etc.
Ted Kremenek8966bc12009-05-06 21:39:49 +00002428 BRC.addNotableSymbol(Sym);
Ted Kremenekc887d132009-04-29 18:50:19 +00002429
2430 // We are reporting a leak. Walk up the graph to get to the first node where
2431 // the symbol appeared, and also get the first VarDecl that tracked object
2432 // is stored to.
2433 const ExplodedNode<GRState>* AllocNode = 0;
2434 const MemRegion* FirstBinding = 0;
2435
2436 llvm::tie(AllocNode, FirstBinding) =
Ted Kremenekf04dced2009-05-08 23:32:51 +00002437 GetAllocationSite(BRC.getStateManager(), EndN, Sym);
Ted Kremenekc887d132009-04-29 18:50:19 +00002438
2439 // Get the allocate site.
2440 assert(AllocNode);
2441 Stmt* FirstStmt = cast<PostStmt>(AllocNode->getLocation()).getStmt();
2442
Ted Kremenek8966bc12009-05-06 21:39:49 +00002443 SourceManager& SMgr = BRC.getSourceManager();
Ted Kremenekc887d132009-04-29 18:50:19 +00002444 unsigned AllocLine =SMgr.getInstantiationLineNumber(FirstStmt->getLocStart());
2445
2446 // Compute an actual location for the leak. Sometimes a leak doesn't
2447 // occur at an actual statement (e.g., transition between blocks; end
2448 // of function) so we need to walk the graph and compute a real location.
2449 const ExplodedNode<GRState>* LeakN = EndN;
2450 PathDiagnosticLocation L;
2451
2452 while (LeakN) {
2453 ProgramPoint P = LeakN->getLocation();
2454
2455 if (const PostStmt *PS = dyn_cast<PostStmt>(&P)) {
2456 L = PathDiagnosticLocation(PS->getStmt()->getLocStart(), SMgr);
2457 break;
2458 }
2459 else if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
2460 if (const Stmt* Term = BE->getSrc()->getTerminator()) {
2461 L = PathDiagnosticLocation(Term->getLocStart(), SMgr);
2462 break;
2463 }
2464 }
2465
2466 LeakN = LeakN->succ_empty() ? 0 : *(LeakN->succ_begin());
2467 }
2468
2469 if (!L.isValid()) {
Ted Kremenek8966bc12009-05-06 21:39:49 +00002470 const Decl &D = BRC.getCodeDecl();
2471 L = PathDiagnosticLocation(D.getBodyRBrace(BRC.getASTContext()), SMgr);
Ted Kremenekc887d132009-04-29 18:50:19 +00002472 }
2473
2474 std::string sbuf;
2475 llvm::raw_string_ostream os(sbuf);
2476
2477 os << "Object allocated on line " << AllocLine;
2478
2479 if (FirstBinding)
2480 os << " and stored into '" << FirstBinding->getString() << '\'';
2481
2482 // Get the retain count.
2483 const RefVal* RV = EndN->getState()->get<RefBindings>(Sym);
2484
2485 if (RV->getKind() == RefVal::ErrorLeakReturned) {
2486 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
2487 // ojbects. Only "copy", "alloc", "retain" and "new" transfer ownership
2488 // to the caller for NS objects.
Ted Kremenek8966bc12009-05-06 21:39:49 +00002489 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(BRC.getCodeDecl());
Ted Kremenekc887d132009-04-29 18:50:19 +00002490 os << " is returned from a method whose name ('"
Ted Kremeneka8833552009-04-29 23:03:22 +00002491 << MD.getSelector().getAsString()
Ted Kremenekc887d132009-04-29 18:50:19 +00002492 << "') does not contain 'copy' or otherwise starts with"
2493 " 'new' or 'alloc'. This violates the naming convention rules given"
Ted Kremenek8987a022009-04-29 22:25:52 +00002494 " in the Memory Management Guide for Cocoa (object leaked)";
Ted Kremenekc887d132009-04-29 18:50:19 +00002495 }
2496 else
2497 os << " is no longer referenced after this point and has a retain count of"
Ted Kremenek8987a022009-04-29 22:25:52 +00002498 " +" << RV->getCount() << " (object leaked)";
Ted Kremenekc887d132009-04-29 18:50:19 +00002499
2500 return new PathDiagnosticEventPiece(L, os.str());
2501}
2502
2503
2504CFRefLeakReport::CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2505 ExplodedNode<GRState> *n,
2506 SymbolRef sym, GRExprEngine& Eng)
2507: CFRefReport(D, tf, n, sym)
2508{
2509
2510 // Most bug reports are cached at the location where they occured.
2511 // With leaks, we want to unique them by the location where they were
2512 // allocated, and only report a single path. To do this, we need to find
2513 // the allocation site of a piece of tracked memory, which we do via a
2514 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2515 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2516 // that all ancestor nodes that represent the allocation site have the
2517 // same SourceLocation.
2518 const ExplodedNode<GRState>* AllocNode = 0;
2519
2520 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding.
Ted Kremenekf04dced2009-05-08 23:32:51 +00002521 GetAllocationSite(Eng.getStateManager(), getEndNode(), getSymbol());
Ted Kremenekc887d132009-04-29 18:50:19 +00002522
2523 // Get the SourceLocation for the allocation site.
2524 ProgramPoint P = AllocNode->getLocation();
2525 AllocSite = cast<PostStmt>(P).getStmt()->getLocStart();
2526
2527 // Fill in the description of the bug.
2528 Description.clear();
2529 llvm::raw_string_ostream os(Description);
2530 SourceManager& SMgr = Eng.getContext().getSourceManager();
2531 unsigned AllocLine = SMgr.getInstantiationLineNumber(AllocSite);
Ted Kremenekdd924e22009-05-02 19:05:19 +00002532 os << "Potential leak ";
2533 if (tf.isGCEnabled()) {
2534 os << "(when using garbage collection) ";
2535 }
2536 os << "of an object allocated on line " << AllocLine;
Ted Kremenekc887d132009-04-29 18:50:19 +00002537
2538 // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2539 if (AllocBinding)
2540 os << " and stored into '" << AllocBinding->getString() << '\'';
2541}
2542
2543//===----------------------------------------------------------------------===//
2544// Main checker logic.
2545//===----------------------------------------------------------------------===//
2546
Ted Kremenek553cf182008-06-25 21:21:56 +00002547/// GetReturnType - Used to get the return type of a message expression or
2548/// function call with the intention of affixing that type to a tracked symbol.
2549/// While the the return type can be queried directly from RetEx, when
2550/// invoking class methods we augment to the return type to be that of
2551/// a pointer to the class (as opposed it just being id).
2552static QualType GetReturnType(Expr* RetE, ASTContext& Ctx) {
2553
2554 QualType RetTy = RetE->getType();
2555
2556 // FIXME: We aren't handling id<...>.
Chris Lattner8b51fd72008-07-26 22:36:27 +00002557 const PointerType* PT = RetTy->getAsPointerType();
Ted Kremenek553cf182008-06-25 21:21:56 +00002558 if (!PT)
2559 return RetTy;
2560
2561 // If RetEx is not a message expression just return its type.
2562 // If RetEx is a message expression, return its types if it is something
2563 /// more specific than id.
2564
2565 ObjCMessageExpr* ME = dyn_cast<ObjCMessageExpr>(RetE);
2566
Steve Naroff389bf462009-02-12 17:52:19 +00002567 if (!ME || !Ctx.isObjCIdStructType(PT->getPointeeType()))
Ted Kremenek553cf182008-06-25 21:21:56 +00002568 return RetTy;
2569
2570 ObjCInterfaceDecl* D = ME->getClassInfo().first;
2571
2572 // At this point we know the return type of the message expression is id.
2573 // If we have an ObjCInterceDecl, we know this is a call to a class method
2574 // whose type we can resolve. In such cases, promote the return type to
2575 // Class*.
2576 return !D ? RetTy : Ctx.getPointerType(Ctx.getObjCInterfaceType(D));
2577}
2578
2579
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002580void CFRefCount::EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002581 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002582 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002583 Expr* Ex,
2584 Expr* Receiver,
Ted Kremenek7faca822009-05-04 04:57:00 +00002585 const RetainSummary& Summ,
Zhongxing Xu369f4472009-04-20 05:24:46 +00002586 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002587 ExplodedNode<GRState>* Pred) {
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002588
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00002589 // Get the state.
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002590 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenekf9790ae2008-10-24 20:32:50 +00002591 ASTContext& Ctx = Eng.getStateManager().getContext();
Ted Kremenek14993892008-05-06 02:41:27 +00002592
2593 // Evaluate the effect of the arguments.
Ted Kremenek9ed18e62008-04-16 04:28:53 +00002594 RefVal::Kind hasErr = (RefVal::Kind) 0;
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002595 unsigned idx = 0;
Ted Kremenekbcf50ad2008-04-11 18:40:51 +00002596 Expr* ErrorExpr = NULL;
Ted Kremenek2dabd432008-12-05 02:27:51 +00002597 SymbolRef ErrorSym = 0;
Ted Kremenekbcf50ad2008-04-11 18:40:51 +00002598
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002599 for (ExprIterator I = arg_beg; I != arg_end; ++I, ++idx) {
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00002600 SVal V = state.GetSValAsScalarOrLoc(*I);
Ted Kremenek94c96982009-03-03 22:06:47 +00002601 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00002602
Ted Kremeneke0e4ebf2009-03-26 03:35:11 +00002603 if (Sym)
Ted Kremenek4d3957d2009-02-24 19:15:11 +00002604 if (RefBindings::data_type* T = state.get<RefBindings>(Sym)) {
Ted Kremenek7faca822009-05-04 04:57:00 +00002605 state = Update(state, Sym, *T, Summ.getArg(idx), hasErr);
Ted Kremenek4d3957d2009-02-24 19:15:11 +00002606 if (hasErr) {
Ted Kremenekbcf50ad2008-04-11 18:40:51 +00002607 ErrorExpr = *I;
Ted Kremeneke8fdc832008-07-07 16:21:19 +00002608 ErrorSym = Sym;
Ted Kremenekbcf50ad2008-04-11 18:40:51 +00002609 break;
Ted Kremenek94c96982009-03-03 22:06:47 +00002610 }
2611 continue;
Ted Kremenek4d3957d2009-02-24 19:15:11 +00002612 }
Ted Kremenek070a8252008-07-09 18:11:16 +00002613
Ted Kremenek94c96982009-03-03 22:06:47 +00002614 if (isa<Loc>(V)) {
2615 if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(&V)) {
Ted Kremenek7faca822009-05-04 04:57:00 +00002616 if (Summ.getArg(idx) == DoNothingByRef)
Ted Kremenek070a8252008-07-09 18:11:16 +00002617 continue;
2618
2619 // Invalidate the value of the variable passed by reference.
Ted Kremenek8c5633e2008-07-03 23:26:32 +00002620
2621 // FIXME: Either this logic should also be replicated in GRSimpleVals
2622 // or should be pulled into a separate "constraint engine."
Ted Kremenek070a8252008-07-09 18:11:16 +00002623
Ted Kremenek8c5633e2008-07-03 23:26:32 +00002624 // FIXME: We can have collisions on the conjured symbol if the
2625 // expression *I also creates conjured symbols. We probably want
2626 // to identify conjured symbols by an expression pair: the enclosing
2627 // expression (the context) and the expression itself. This should
Ted Kremenek070a8252008-07-09 18:11:16 +00002628 // disambiguate conjured symbols.
Ted Kremenek9e240492008-10-04 05:50:14 +00002629
Ted Kremenek993f1c72008-10-17 20:28:54 +00002630 const TypedRegion* R = dyn_cast<TypedRegion>(MR->getRegion());
Zhongxing Xuf82af1e2009-04-29 02:30:09 +00002631
Ted Kremenek42530512009-05-06 18:19:24 +00002632 if (R) {
2633 // Are we dealing with an ElementRegion? If the element type is
2634 // a basic integer type (e.g., char, int) and the underying region
2635 // is also typed then strip off the ElementRegion.
2636 // FIXME: We really need to think about this for the general case
2637 // as sometimes we are reasoning about arrays and other times
2638 // about (char*), etc., is just a form of passing raw bytes.
2639 // e.g., void *p = alloca(); foo((char*)p);
2640 if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
2641 // Checking for 'integral type' is probably too promiscuous, but
2642 // we'll leave it in for now until we have a systematic way of
2643 // handling all of these cases. Eventually we need to come up
2644 // with an interface to StoreManager so that this logic can be
2645 // approriately delegated to the respective StoreManagers while
2646 // still allowing us to do checker-specific logic (e.g.,
2647 // invalidating reference counts), probably via callbacks.
2648 if (ER->getElementType()->isIntegralType())
2649 if (const TypedRegion *superReg =
2650 dyn_cast<TypedRegion>(ER->getSuperRegion()))
2651 R = superReg;
2652 // FIXME: What about layers of ElementRegions?
2653 }
2654
Ted Kremenek40e86d92008-12-18 23:34:57 +00002655 // Is the invalidated variable something that we were tracking?
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00002656 SymbolRef Sym = state.GetSValAsScalarOrLoc(R).getAsLocSymbol();
Ted Kremenek40e86d92008-12-18 23:34:57 +00002657
Ted Kremenekd104a092009-03-04 22:56:43 +00002658 // Remove any existing reference-count binding.
Ted Kremeneke0e4ebf2009-03-26 03:35:11 +00002659 if (Sym) state = state.remove<RefBindings>(Sym);
Ted Kremenek9e240492008-10-04 05:50:14 +00002660
Ted Kremenekd104a092009-03-04 22:56:43 +00002661 if (R->isBoundable(Ctx)) {
2662 // Set the value of the variable to be a conjured symbol.
2663 unsigned Count = Builder.getCurrentBlockCount();
Zhongxing Xuff697822009-05-09 00:50:33 +00002664 QualType T = R->getObjectType(Ctx);
Ted Kremenekd104a092009-03-04 22:56:43 +00002665
Zhongxing Xu51ae7902009-04-09 06:03:54 +00002666 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())){
Ted Kremenek8d7f5482009-04-09 22:22:44 +00002667 ValueManager &ValMgr = Eng.getValueManager();
2668 SVal V = ValMgr.getConjuredSymbolVal(*I, T, Count);
Zhongxing Xu51ae7902009-04-09 06:03:54 +00002669 state = state.BindLoc(Loc::MakeVal(R), V);
Ted Kremenekd104a092009-03-04 22:56:43 +00002670 }
2671 else if (const RecordType *RT = T->getAsStructureType()) {
2672 // Handle structs in a not so awesome way. Here we just
2673 // eagerly bind new symbols to the fields. In reality we
2674 // should have the store manager handle this. The idea is just
2675 // to prototype some basic functionality here. All of this logic
2676 // should one day soon just go away.
2677 const RecordDecl *RD = RT->getDecl()->getDefinition(Ctx);
2678
2679 // No record definition. There is nothing we can do.
2680 if (!RD)
2681 continue;
2682
2683 MemRegionManager &MRMgr = state.getManager().getRegionManager();
2684
2685 // Iterate through the fields and construct new symbols.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002686 for (RecordDecl::field_iterator FI=RD->field_begin(Ctx),
2687 FE=RD->field_end(Ctx); FI!=FE; ++FI) {
Ted Kremenekd104a092009-03-04 22:56:43 +00002688
2689 // For now just handle scalar fields.
2690 FieldDecl *FD = *FI;
2691 QualType FT = FD->getType();
2692
2693 if (Loc::IsLocType(FT) ||
Ted Kremenek8d7f5482009-04-09 22:22:44 +00002694 (FT->isIntegerType() && FT->isScalarType())) {
Ted Kremenekd104a092009-03-04 22:56:43 +00002695 const FieldRegion* FR = MRMgr.getFieldRegion(FD, R);
Ted Kremenek8d7f5482009-04-09 22:22:44 +00002696 ValueManager &ValMgr = Eng.getValueManager();
2697 SVal V = ValMgr.getConjuredSymbolVal(*I, FT, Count);
Zhongxing Xu6782f752009-04-09 06:32:20 +00002698 state = state.BindLoc(Loc::MakeVal(FR), V);
Ted Kremenekd104a092009-03-04 22:56:43 +00002699 }
2700 }
2701 }
2702 else {
2703 // Just blast away other values.
2704 state = state.BindLoc(*MR, UnknownVal());
2705 }
Ted Kremenekfd301942008-10-17 22:23:12 +00002706 }
Ted Kremenek9e240492008-10-04 05:50:14 +00002707 }
2708 else
Ted Kremeneka441b7e2008-11-12 19:22:09 +00002709 state = state.BindLoc(*MR, UnknownVal());
Ted Kremenek8c5633e2008-07-03 23:26:32 +00002710 }
2711 else {
2712 // Nuke all other arguments passed by reference.
Zhongxing Xu1c96b242008-10-17 05:57:07 +00002713 state = state.Unbind(cast<Loc>(V));
Ted Kremenek8c5633e2008-07-03 23:26:32 +00002714 }
Ted Kremenekb8873552008-04-11 20:51:02 +00002715 }
Zhongxing Xu1c96b242008-10-17 05:57:07 +00002716 else if (isa<nonloc::LocAsInteger>(V))
2717 state = state.Unbind(cast<nonloc::LocAsInteger>(V).getLoc());
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002718 }
Ted Kremenek9ed18e62008-04-16 04:28:53 +00002719
Ted Kremenek553cf182008-06-25 21:21:56 +00002720 // Evaluate the effect on the message receiver.
Ted Kremenek14993892008-05-06 02:41:27 +00002721 if (!ErrorExpr && Receiver) {
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00002722 SymbolRef Sym = state.GetSValAsScalarOrLoc(Receiver).getAsLocSymbol();
Ted Kremeneke0e4ebf2009-03-26 03:35:11 +00002723 if (Sym) {
Ted Kremenek4d3957d2009-02-24 19:15:11 +00002724 if (const RefVal* T = state.get<RefBindings>(Sym)) {
Ted Kremenek7faca822009-05-04 04:57:00 +00002725 state = Update(state, Sym, *T, Summ.getReceiverEffect(), hasErr);
Ted Kremenek4d3957d2009-02-24 19:15:11 +00002726 if (hasErr) {
Ted Kremenek14993892008-05-06 02:41:27 +00002727 ErrorExpr = Receiver;
Ted Kremeneke8fdc832008-07-07 16:21:19 +00002728 ErrorSym = Sym;
Ted Kremenek14993892008-05-06 02:41:27 +00002729 }
Ted Kremenek4d3957d2009-02-24 19:15:11 +00002730 }
Ted Kremenek14993892008-05-06 02:41:27 +00002731 }
2732 }
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002733
Ted Kremenek553cf182008-06-25 21:21:56 +00002734 // Process any errors.
Ted Kremenek9ed18e62008-04-16 04:28:53 +00002735 if (hasErr) {
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002736 ProcessNonLeakError(Dst, Builder, Ex, ErrorExpr, Pred, state,
Ted Kremenek8dd56462008-04-18 03:39:05 +00002737 hasErr, ErrorSym);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002738 return;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002739 }
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002740
Ted Kremenek70a733e2008-07-18 17:24:20 +00002741 // Consult the summary for the return value.
Ted Kremenek7faca822009-05-04 04:57:00 +00002742 RetEffect RE = Summ.getRetEffect();
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002743
2744 switch (RE.getKind()) {
2745 default:
2746 assert (false && "Unhandled RetEffect."); break;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002747
Ted Kremenekfd301942008-10-17 22:23:12 +00002748 case RetEffect::NoRet: {
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002749
Ted Kremenekf9561e52008-04-11 20:23:24 +00002750 // Make up a symbol for the return value (not reference counted).
Ted Kremenekb8873552008-04-11 20:51:02 +00002751 // FIXME: This is basically copy-and-paste from GRSimpleVals. We
2752 // should compose behavior, not copy it.
Ted Kremenekf9561e52008-04-11 20:23:24 +00002753
Ted Kremenekfd301942008-10-17 22:23:12 +00002754 // FIXME: We eventually should handle structs and other compound types
2755 // that are returned by value.
2756
2757 QualType T = Ex->getType();
2758
Ted Kremenek062e2f92008-11-13 06:10:40 +00002759 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())) {
Ted Kremenekf9561e52008-04-11 20:23:24 +00002760 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenek8d7f5482009-04-09 22:22:44 +00002761 ValueManager &ValMgr = Eng.getValueManager();
2762 SVal X = ValMgr.getConjuredSymbolVal(Ex, T, Count);
Ted Kremeneka441b7e2008-11-12 19:22:09 +00002763 state = state.BindExpr(Ex, X, false);
Ted Kremenekf9561e52008-04-11 20:23:24 +00002764 }
2765
Ted Kremenek940b1d82008-04-10 23:44:06 +00002766 break;
Ted Kremenekfd301942008-10-17 22:23:12 +00002767 }
Ted Kremenek940b1d82008-04-10 23:44:06 +00002768
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002769 case RetEffect::Alias: {
Ted Kremenek553cf182008-06-25 21:21:56 +00002770 unsigned idx = RE.getIndex();
Ted Kremenek55499762008-06-17 02:43:46 +00002771 assert (arg_end >= arg_beg);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002772 assert (idx < (unsigned) (arg_end - arg_beg));
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00002773 SVal V = state.GetSValAsScalarOrLoc(*(arg_beg+idx));
Ted Kremeneka441b7e2008-11-12 19:22:09 +00002774 state = state.BindExpr(Ex, V, false);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002775 break;
2776 }
2777
Ted Kremenek14993892008-05-06 02:41:27 +00002778 case RetEffect::ReceiverAlias: {
2779 assert (Receiver);
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00002780 SVal V = state.GetSValAsScalarOrLoc(Receiver);
Ted Kremeneka441b7e2008-11-12 19:22:09 +00002781 state = state.BindExpr(Ex, V, false);
Ted Kremenek14993892008-05-06 02:41:27 +00002782 break;
2783 }
2784
Ted Kremeneka7344702008-06-23 18:02:52 +00002785 case RetEffect::OwnedAllocatedSymbol:
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002786 case RetEffect::OwnedSymbol: {
2787 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenek044b6f02009-04-09 16:13:17 +00002788 ValueManager &ValMgr = Eng.getValueManager();
2789 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
2790 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
2791 state = state.set<RefBindings>(Sym, RefVal::makeOwned(RE.getObjKind(),
2792 RetT));
2793 state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenek25d01ba2009-03-09 22:46:49 +00002794
2795 // FIXME: Add a flag to the checker where allocations are assumed to
2796 // *not fail.
2797#if 0
Ted Kremenekb2bf7cd2009-01-28 22:27:59 +00002798 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) {
2799 bool isFeasible;
2800 state = state.Assume(loc::SymbolVal(Sym), true, isFeasible);
2801 assert(isFeasible && "Cannot assume fresh symbol is non-null.");
2802 }
Ted Kremenek25d01ba2009-03-09 22:46:49 +00002803#endif
Ted Kremeneka7344702008-06-23 18:02:52 +00002804
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002805 break;
2806 }
Ted Kremeneke798e7c2009-04-27 19:14:45 +00002807
2808 case RetEffect::GCNotOwnedSymbol:
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002809 case RetEffect::NotOwnedSymbol: {
2810 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenek044b6f02009-04-09 16:13:17 +00002811 ValueManager &ValMgr = Eng.getValueManager();
2812 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
2813 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
2814 state = state.set<RefBindings>(Sym, RefVal::makeNotOwned(RE.getObjKind(),
2815 RetT));
2816 state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002817 break;
2818 }
2819 }
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002820
Ted Kremenekf5b34b12009-02-18 02:00:25 +00002821 // Generate a sink node if we are at the end of a path.
2822 GRExprEngine::NodeTy *NewNode =
Ted Kremenek7faca822009-05-04 04:57:00 +00002823 Summ.isEndPath() ? Builder.MakeSinkNode(Dst, Ex, Pred, state)
2824 : Builder.MakeNode(Dst, Ex, Pred, state);
Ted Kremenekf5b34b12009-02-18 02:00:25 +00002825
2826 // Annotate the edge with summary we used.
Ted Kremenek7faca822009-05-04 04:57:00 +00002827 if (NewNode) SummaryLog[NewNode] = &Summ;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002828}
2829
2830
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002831void CFRefCount::EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002832 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002833 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu1c96b242008-10-17 05:57:07 +00002834 CallExpr* CE, SVal L,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002835 ExplodedNode<GRState>* Pred) {
Zhongxing Xu369f4472009-04-20 05:24:46 +00002836 const FunctionDecl* FD = L.getAsFunctionDecl();
Ted Kremenek7faca822009-05-04 04:57:00 +00002837 RetainSummary* Summ = !FD ? Summaries.getDefaultSummary()
Zhongxing Xu369f4472009-04-20 05:24:46 +00002838 : Summaries.getSummary(const_cast<FunctionDecl*>(FD));
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002839
Ted Kremenek7faca822009-05-04 04:57:00 +00002840 assert(Summ);
2841 EvalSummary(Dst, Eng, Builder, CE, 0, *Summ,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002842 CE->arg_begin(), CE->arg_end(), Pred);
Ted Kremenek2fff37e2008-03-06 00:08:09 +00002843}
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00002844
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002845void CFRefCount::EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek85348202008-04-15 23:44:31 +00002846 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002847 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek85348202008-04-15 23:44:31 +00002848 ObjCMessageExpr* ME,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002849 ExplodedNode<GRState>* Pred) {
Ted Kremenek7faca822009-05-04 04:57:00 +00002850 RetainSummary* Summ = 0;
Ted Kremenek9040c652008-05-01 21:31:50 +00002851
Ted Kremenek553cf182008-06-25 21:21:56 +00002852 if (Expr* Receiver = ME->getReceiver()) {
2853 // We need the type-information of the tracked receiver object
2854 // Retrieve it from the state.
2855 ObjCInterfaceDecl* ID = 0;
2856
2857 // FIXME: Wouldn't it be great if this code could be reduced? It's just
2858 // a chain of lookups.
Ted Kremenek8711c032009-04-29 05:04:30 +00002859 // FIXME: Is this really working as expected? There are cases where
2860 // we just use the 'ID' from the message expression.
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002861 const GRState* St = Builder.GetState(Pred);
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00002862 SVal V = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
Ted Kremenek553cf182008-06-25 21:21:56 +00002863
Ted Kremenek94c96982009-03-03 22:06:47 +00002864 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremeneke0e4ebf2009-03-26 03:35:11 +00002865 if (Sym) {
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002866 if (const RefVal* T = St->get<RefBindings>(Sym)) {
Ted Kremeneke8fdc832008-07-07 16:21:19 +00002867 QualType Ty = T->getType();
Ted Kremenek553cf182008-06-25 21:21:56 +00002868
2869 if (const PointerType* PT = Ty->getAsPointerType()) {
2870 QualType PointeeTy = PT->getPointeeType();
2871
2872 if (ObjCInterfaceType* IT = dyn_cast<ObjCInterfaceType>(PointeeTy))
2873 ID = IT->getDecl();
2874 }
2875 }
2876 }
2877
Ted Kremenekce8a41d2009-04-29 17:09:14 +00002878 // FIXME: The receiver could be a reference to a class, meaning that
2879 // we should use the class method.
2880 Summ = Summaries.getInstanceMethodSummary(ME, ID);
Ted Kremenekf9790ae2008-10-24 20:32:50 +00002881
Ted Kremenek896cd9d2008-10-23 01:56:15 +00002882 // Special-case: are we sending a mesage to "self"?
2883 // This is a hack. When we have full-IP this should be removed.
Ted Kremenek885c27b2009-05-04 05:31:22 +00002884 if (isa<ObjCMethodDecl>(&Eng.getGraph().getCodeDecl())) {
2885 if (Expr* Receiver = ME->getReceiver()) {
2886 SVal X = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
2887 if (loc::MemRegionVal* L = dyn_cast<loc::MemRegionVal>(&X))
2888 if (L->getRegion() == Eng.getStateManager().getSelfRegion(St)) {
2889 // Update the summary to make the default argument effect
2890 // 'StopTracking'.
2891 Summ = Summaries.copySummary(Summ);
2892 Summ->setDefaultArgEffect(StopTracking);
2893 }
Ted Kremenek896cd9d2008-10-23 01:56:15 +00002894 }
2895 }
Ted Kremenek553cf182008-06-25 21:21:56 +00002896 }
Ted Kremenek9ed18e62008-04-16 04:28:53 +00002897 else
Ted Kremenekf9df1362009-04-23 21:25:57 +00002898 Summ = Summaries.getClassMethodSummary(ME);
Ted Kremenek9ed18e62008-04-16 04:28:53 +00002899
Ted Kremenek7faca822009-05-04 04:57:00 +00002900 if (!Summ)
2901 Summ = Summaries.getDefaultSummary();
Ted Kremenekde4d5332009-04-24 17:50:11 +00002902
Ted Kremenek7faca822009-05-04 04:57:00 +00002903 EvalSummary(Dst, Eng, Builder, ME, ME->getReceiver(), *Summ,
Ted Kremenekb3095252008-05-06 04:20:12 +00002904 ME->arg_begin(), ME->arg_end(), Pred);
Ted Kremenek85348202008-04-15 23:44:31 +00002905}
Ted Kremenek5216ad72009-02-14 03:16:10 +00002906
2907namespace {
2908class VISIBILITY_HIDDEN StopTrackingCallback : public SymbolVisitor {
2909 GRStateRef state;
2910public:
2911 StopTrackingCallback(GRStateRef st) : state(st) {}
2912 GRStateRef getState() { return state; }
2913
2914 bool VisitSymbol(SymbolRef sym) {
2915 state = state.remove<RefBindings>(sym);
2916 return true;
2917 }
Ted Kremenekb3095252008-05-06 04:20:12 +00002918
Ted Kremenek5216ad72009-02-14 03:16:10 +00002919 const GRState* getState() const { return state.getState(); }
2920};
2921} // end anonymous namespace
2922
2923
Ted Kremenek41573eb2009-02-14 01:43:44 +00002924void CFRefCount::EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val) {
Ted Kremenek41573eb2009-02-14 01:43:44 +00002925 // Are we storing to something that causes the value to "escape"?
Ted Kremenek13922612008-04-16 20:40:59 +00002926 bool escapes = false;
2927
Ted Kremeneka496d162008-10-18 03:49:51 +00002928 // A value escapes in three possible cases (this may change):
2929 //
2930 // (1) we are binding to something that is not a memory region.
2931 // (2) we are binding to a memregion that does not have stack storage
2932 // (3) we are binding to a memregion with stack storage that the store
Ted Kremenek41573eb2009-02-14 01:43:44 +00002933 // does not understand.
Ted Kremenek41573eb2009-02-14 01:43:44 +00002934 GRStateRef state = B.getState();
Ted Kremeneka496d162008-10-18 03:49:51 +00002935
Ted Kremenek41573eb2009-02-14 01:43:44 +00002936 if (!isa<loc::MemRegionVal>(location))
Ted Kremenek13922612008-04-16 20:40:59 +00002937 escapes = true;
Ted Kremenek9e240492008-10-04 05:50:14 +00002938 else {
Ted Kremenek41573eb2009-02-14 01:43:44 +00002939 const MemRegion* R = cast<loc::MemRegionVal>(location).getRegion();
2940 escapes = !B.getStateManager().hasStackStorage(R);
Ted Kremeneka496d162008-10-18 03:49:51 +00002941
2942 if (!escapes) {
2943 // To test (3), generate a new state with the binding removed. If it is
2944 // the same state, then it escapes (since the store cannot represent
2945 // the binding).
Ted Kremenek41573eb2009-02-14 01:43:44 +00002946 escapes = (state == (state.BindLoc(cast<Loc>(location), UnknownVal())));
Ted Kremeneka496d162008-10-18 03:49:51 +00002947 }
Ted Kremenek9e240492008-10-04 05:50:14 +00002948 }
Ted Kremenek41573eb2009-02-14 01:43:44 +00002949
Ted Kremenek5216ad72009-02-14 03:16:10 +00002950 // If our store can represent the binding and we aren't storing to something
2951 // that doesn't have local storage then just return and have the simulation
2952 // state continue as is.
2953 if (!escapes)
2954 return;
Ted Kremeneka496d162008-10-18 03:49:51 +00002955
Ted Kremenek5216ad72009-02-14 03:16:10 +00002956 // Otherwise, find all symbols referenced by 'val' that we are tracking
2957 // and stop tracking them.
2958 B.MakeNode(state.scanReachableSymbols<StopTrackingCallback>(val).getState());
Ted Kremenekdb863712008-04-16 22:32:20 +00002959}
2960
Ted Kremenek652adc62008-04-24 23:57:27 +00002961
Ted Kremenek4fd88972008-04-17 18:12:53 +00002962 // Return statements.
2963
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002964void CFRefCount::EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4fd88972008-04-17 18:12:53 +00002965 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002966 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4fd88972008-04-17 18:12:53 +00002967 ReturnStmt* S,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002968 ExplodedNode<GRState>* Pred) {
Ted Kremenek4fd88972008-04-17 18:12:53 +00002969
2970 Expr* RetE = S->getRetValue();
Ted Kremenek94c96982009-03-03 22:06:47 +00002971 if (!RetE)
Ted Kremenek4fd88972008-04-17 18:12:53 +00002972 return;
2973
Ted Kremenek94c96982009-03-03 22:06:47 +00002974 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00002975 SymbolRef Sym = state.GetSValAsScalarOrLoc(RetE).getAsLocSymbol();
Ted Kremenek94c96982009-03-03 22:06:47 +00002976
Ted Kremeneke0e4ebf2009-03-26 03:35:11 +00002977 if (!Sym)
Ted Kremenek94c96982009-03-03 22:06:47 +00002978 return;
Ted Kremenekf04dced2009-05-08 23:32:51 +00002979
Ted Kremenek4fd88972008-04-17 18:12:53 +00002980 // Get the reference count binding (if any).
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002981 const RefVal* T = state.get<RefBindings>(Sym);
Ted Kremenek4fd88972008-04-17 18:12:53 +00002982
2983 if (!T)
2984 return;
2985
Ted Kremenekf04dced2009-05-08 23:32:51 +00002986 // Update the autorelease counts.
2987 static unsigned autoreleasetag = 0;
2988 GenericNodeBuilder Bd(Builder, S, &autoreleasetag);
Ted Kremenek369de562009-05-09 00:10:05 +00002989 bool stop = false;
2990 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state , Bd, Pred, Eng, Sym,
2991 *T, stop);
2992
2993 if (stop)
2994 return;
Ted Kremenekf04dced2009-05-08 23:32:51 +00002995
2996 // Get the updated binding.
2997 T = state.get<RefBindings>(Sym);
2998 assert(T);
2999
Ted Kremenek72cd17f2008-08-14 21:16:54 +00003000 // Change the reference count.
Ted Kremeneke8fdc832008-07-07 16:21:19 +00003001 RefVal X = *T;
Ted Kremenek4fd88972008-04-17 18:12:53 +00003002
Ted Kremenek72cd17f2008-08-14 21:16:54 +00003003 switch (X.getKind()) {
Ted Kremenek4fd88972008-04-17 18:12:53 +00003004 case RefVal::Owned: {
3005 unsigned cnt = X.getCount();
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00003006 assert (cnt > 0);
3007 X = RefVal::makeReturnedOwned(cnt - 1);
Ted Kremenek4fd88972008-04-17 18:12:53 +00003008 break;
3009 }
3010
3011 case RefVal::NotOwned: {
3012 unsigned cnt = X.getCount();
3013 X = cnt ? RefVal::makeReturnedOwned(cnt - 1)
3014 : RefVal::makeReturnedNotOwned();
3015 break;
3016 }
3017
3018 default:
Ted Kremenek4fd88972008-04-17 18:12:53 +00003019 return;
3020 }
3021
3022 // Update the binding.
Ted Kremenekb9d17f92008-08-17 03:20:02 +00003023 state = state.set<RefBindings>(Sym, X);
Ted Kremenekc887d132009-04-29 18:50:19 +00003024 Pred = Builder.MakeNode(Dst, S, Pred, state);
3025
Ted Kremenek9f246b62009-04-30 05:51:50 +00003026 // Did we cache out?
3027 if (!Pred)
3028 return;
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003029
Ted Kremenekc887d132009-04-29 18:50:19 +00003030 // Any leaks or other errors?
3031 if (X.isReturnedOwned() && X.getCount() == 0) {
3032 const Decl *CD = &Eng.getStateManager().getCodeDecl();
3033
Ted Kremeneka8833552009-04-29 23:03:22 +00003034 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
Ted Kremenek7faca822009-05-04 04:57:00 +00003035 const RetainSummary &Summ = *Summaries.getMethodSummary(MD);
3036 if (!Summ.getRetEffect().isOwned()) {
Ted Kremenekc887d132009-04-29 18:50:19 +00003037 static int ReturnOwnLeakTag = 0;
3038 state = state.set<RefBindings>(Sym, X ^ RefVal::ErrorLeakReturned);
Ted Kremenekc887d132009-04-29 18:50:19 +00003039 // Generate an error node.
Ted Kremenek9f246b62009-04-30 05:51:50 +00003040 if (ExplodedNode<GRState> *N =
3041 Builder.generateNode(PostStmt(S, &ReturnOwnLeakTag), state, Pred)) {
3042 CFRefLeakReport *report =
3043 new CFRefLeakReport(*static_cast<CFRefBug*>(leakAtReturn), *this,
3044 N, Sym, Eng);
3045 BR->EmitReport(report);
3046 }
Ted Kremenekc887d132009-04-29 18:50:19 +00003047 }
3048 }
3049 }
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003050
3051
Ted Kremenek4fd88972008-04-17 18:12:53 +00003052}
3053
Ted Kremenekcb612922008-04-18 19:23:43 +00003054// Assumptions.
3055
Ted Kremenek4adc81e2008-08-13 04:27:00 +00003056const GRState* CFRefCount::EvalAssume(GRStateManager& VMgr,
3057 const GRState* St,
Zhongxing Xu1c96b242008-10-17 05:57:07 +00003058 SVal Cond, bool Assumption,
Ted Kremenek4323a572008-07-10 22:03:41 +00003059 bool& isFeasible) {
Ted Kremenekcb612922008-04-18 19:23:43 +00003060
3061 // FIXME: We may add to the interface of EvalAssume the list of symbols
3062 // whose assumptions have changed. For now we just iterate through the
3063 // bindings and check if any of the tracked symbols are NULL. This isn't
3064 // too bad since the number of symbols we will track in practice are
3065 // probably small and EvalAssume is only called at branches and a few
3066 // other places.
Ted Kremenek72cd17f2008-08-14 21:16:54 +00003067 RefBindings B = St->get<RefBindings>();
Ted Kremenekcb612922008-04-18 19:23:43 +00003068
3069 if (B.isEmpty())
3070 return St;
3071
3072 bool changed = false;
Ted Kremenekb9d17f92008-08-17 03:20:02 +00003073
3074 GRStateRef state(St, VMgr);
3075 RefBindings::Factory& RefBFactory = state.get_context<RefBindings>();
Ted Kremenekcb612922008-04-18 19:23:43 +00003076
3077 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
Ted Kremenekcb612922008-04-18 19:23:43 +00003078 // Check if the symbol is null (or equal to any constant).
3079 // If this is the case, stop tracking the symbol.
Zhongxing Xu39cfed32008-08-29 14:52:36 +00003080 if (VMgr.getSymVal(St, I.getKey())) {
Ted Kremenekcb612922008-04-18 19:23:43 +00003081 changed = true;
3082 B = RefBFactory.Remove(B, I.getKey());
3083 }
3084 }
3085
Ted Kremenekb9d17f92008-08-17 03:20:02 +00003086 if (changed)
3087 state = state.set<RefBindings>(B);
Ted Kremenekcb612922008-04-18 19:23:43 +00003088
Ted Kremenek72cd17f2008-08-14 21:16:54 +00003089 return state;
Ted Kremenekcb612922008-04-18 19:23:43 +00003090}
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00003091
Ted Kremenek4d3957d2009-02-24 19:15:11 +00003092GRStateRef CFRefCount::Update(GRStateRef state, SymbolRef sym,
3093 RefVal V, ArgEffect E,
3094 RefVal::Kind& hasErr) {
Ted Kremenek1c512f52009-02-18 18:54:33 +00003095
3096 // In GC mode [... release] and [... retain] do nothing.
3097 switch (E) {
3098 default: break;
3099 case IncRefMsg: E = isGCEnabled() ? DoNothing : IncRef; break;
3100 case DecRefMsg: E = isGCEnabled() ? DoNothing : DecRef; break;
Ted Kremenek27019002009-02-18 21:57:45 +00003101 case MakeCollectable: E = isGCEnabled() ? DecRef : DoNothing; break;
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00003102 case NewAutoreleasePool: E = isGCEnabled() ? DoNothing :
3103 NewAutoreleasePool; break;
Ted Kremenek1c512f52009-02-18 18:54:33 +00003104 }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00003105
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003106 // Handle all use-after-releases.
3107 if (!isGCEnabled() && V.getKind() == RefVal::Released) {
3108 V = V ^ RefVal::ErrorUseAfterRelease;
3109 hasErr = V.getKind();
3110 return state.set<RefBindings>(sym, V);
3111 }
3112
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003113 switch (E) {
3114 default:
3115 assert (false && "Unhandled CFRef transition.");
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003116
3117 case Dealloc:
3118 // Any use of -dealloc in GC is *bad*.
3119 if (isGCEnabled()) {
3120 V = V ^ RefVal::ErrorDeallocGC;
3121 hasErr = V.getKind();
3122 break;
3123 }
3124
3125 switch (V.getKind()) {
3126 default:
3127 assert(false && "Invalid case.");
3128 case RefVal::Owned:
3129 // The object immediately transitions to the released state.
3130 V = V ^ RefVal::Released;
3131 V.clearCounts();
3132 return state.set<RefBindings>(sym, V);
3133 case RefVal::NotOwned:
3134 V = V ^ RefVal::ErrorDeallocNotOwned;
3135 hasErr = V.getKind();
3136 break;
3137 }
3138 break;
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00003139
Ted Kremenek35790732009-02-25 23:11:49 +00003140 case NewAutoreleasePool:
3141 assert(!isGCEnabled());
3142 return state.add<AutoreleaseStack>(sym);
3143
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00003144 case MayEscape:
3145 if (V.getKind() == RefVal::Owned) {
Ted Kremenek553cf182008-06-25 21:21:56 +00003146 V = V ^ RefVal::NotOwned;
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00003147 break;
3148 }
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003149
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00003150 // Fall-through.
Ted Kremenek6c4becb2009-02-25 02:54:57 +00003151
Ted Kremenek070a8252008-07-09 18:11:16 +00003152 case DoNothingByRef:
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003153 case DoNothing:
Ted Kremenek4d3957d2009-02-24 19:15:11 +00003154 return state;
Ted Kremeneke19f4492008-06-30 16:57:41 +00003155
Ted Kremenekabf43972009-01-28 21:44:40 +00003156 case Autorelease:
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003157 if (isGCEnabled())
3158 return state;
Ted Kremenek7037ab82009-03-20 17:34:15 +00003159
3160 // Update the autorelease counts.
3161 state = SendAutorelease(state, ARCountFactory, sym);
Ted Kremenekf21332e2009-05-08 20:01:42 +00003162 V = V.autorelease();
Ted Kremenek6b62ec92009-05-09 01:50:57 +00003163 break;
Ted Kremenek369de562009-05-09 00:10:05 +00003164
Ted Kremenek14993892008-05-06 02:41:27 +00003165 case StopTracking:
Ted Kremenek4d3957d2009-02-24 19:15:11 +00003166 return state.remove<RefBindings>(sym);
Ted Kremenek9e476de2008-08-12 18:30:56 +00003167
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003168 case IncRef:
3169 switch (V.getKind()) {
3170 default:
3171 assert(false);
3172
3173 case RefVal::Owned:
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003174 case RefVal::NotOwned:
Ted Kremenek553cf182008-06-25 21:21:56 +00003175 V = V + 1;
Ted Kremenek9e476de2008-08-12 18:30:56 +00003176 break;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003177 case RefVal::Released:
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003178 // Non-GC cases are handled above.
3179 assert(isGCEnabled());
3180 V = (V ^ RefVal::Owned) + 1;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003181 break;
Ted Kremenek9e476de2008-08-12 18:30:56 +00003182 }
Ted Kremenek940b1d82008-04-10 23:44:06 +00003183 break;
3184
Ted Kremenek553cf182008-06-25 21:21:56 +00003185 case SelfOwn:
3186 V = V ^ RefVal::NotOwned;
Ted Kremenek1c512f52009-02-18 18:54:33 +00003187 // Fall-through.
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003188 case DecRef:
3189 switch (V.getKind()) {
3190 default:
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003191 // case 'RefVal::Released' handled above.
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003192 assert (false);
Ted Kremenek9e476de2008-08-12 18:30:56 +00003193
Ted Kremenek553cf182008-06-25 21:21:56 +00003194 case RefVal::Owned:
Ted Kremenekbb8c5aa2009-02-18 22:57:22 +00003195 assert(V.getCount() > 0);
3196 if (V.getCount() == 1) V = V ^ RefVal::Released;
3197 V = V - 1;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003198 break;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003199
Ted Kremenek553cf182008-06-25 21:21:56 +00003200 case RefVal::NotOwned:
3201 if (V.getCount() > 0)
3202 V = V - 1;
Ted Kremenek61b9f872008-04-10 23:09:18 +00003203 else {
Ted Kremenek553cf182008-06-25 21:21:56 +00003204 V = V ^ RefVal::ErrorReleaseNotOwned;
Ted Kremenek9ed18e62008-04-16 04:28:53 +00003205 hasErr = V.getKind();
Ted Kremenek9e476de2008-08-12 18:30:56 +00003206 }
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003207 break;
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003208
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003209 case RefVal::Released:
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003210 // Non-GC cases are handled above.
3211 assert(isGCEnabled());
Ted Kremenek553cf182008-06-25 21:21:56 +00003212 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek9ed18e62008-04-16 04:28:53 +00003213 hasErr = V.getKind();
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003214 break;
Ted Kremenek9e476de2008-08-12 18:30:56 +00003215 }
Ted Kremenek940b1d82008-04-10 23:44:06 +00003216 break;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003217 }
Ted Kremenek4d3957d2009-02-24 19:15:11 +00003218 return state.set<RefBindings>(sym, V);
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00003219}
3220
Ted Kremenekfa34b332008-04-09 01:10:13 +00003221//===----------------------------------------------------------------------===//
Ted Kremenekcf701772009-02-05 06:50:21 +00003222// Handle dead symbols and end-of-path.
3223//===----------------------------------------------------------------------===//
3224
Ted Kremenekf04dced2009-05-08 23:32:51 +00003225std::pair<ExplodedNode<GRState>*, GRStateRef>
3226CFRefCount::HandleAutoreleaseCounts(GRStateRef state, GenericNodeBuilder Bd,
3227 ExplodedNode<GRState>* Pred,
Ted Kremenek369de562009-05-09 00:10:05 +00003228 GRExprEngine &Eng,
3229 SymbolRef Sym, RefVal V, bool &stop) {
Ted Kremenekf04dced2009-05-08 23:32:51 +00003230
Ted Kremenek369de562009-05-09 00:10:05 +00003231 unsigned ACnt = V.getAutoreleaseCount();
3232 stop = false;
3233
3234 // No autorelease counts? Nothing to be done.
3235 if (!ACnt)
3236 return std::make_pair(Pred, state);
3237
3238 assert(!isGCEnabled() && "Autorelease counts in GC mode?");
3239 unsigned Cnt = V.getCount();
3240
3241 if (ACnt <= Cnt) {
Ted Kremenek80c24182009-05-09 00:44:07 +00003242 if (ACnt == Cnt) {
3243 V.clearCounts();
3244 V = V ^ RefVal::NotOwned;
3245 }
3246 else {
3247 V.setCount(Cnt - ACnt);
3248 V.setAutoreleaseCount(0);
3249 }
Ted Kremenek369de562009-05-09 00:10:05 +00003250 state = state.set<RefBindings>(Sym, V);
3251 ExplodedNode<GRState> *N = Bd.MakeNode(state, Pred);
3252 stop = (N == 0);
3253 return std::make_pair(N, state);
3254 }
3255
3256 // Woah! More autorelease counts then retain counts left.
3257 // Emit hard error.
3258 stop = true;
3259 V = V ^ RefVal::ErrorOverAutorelease;
3260 state = state.set<RefBindings>(Sym, V);
3261
3262 if (ExplodedNode<GRState> *N = Bd.MakeNode(state, Pred)) {
Ted Kremenek80c24182009-05-09 00:44:07 +00003263 N->markAsSink();
Ted Kremenek369de562009-05-09 00:10:05 +00003264 CFRefReport *report =
3265 new CFRefReport(*static_cast<CFRefBug*>(overAutorelease),
3266 *this, N, Sym);
3267 BR->EmitReport(report);
3268 }
3269
3270 return std::make_pair((ExplodedNode<GRState>*)0, state);
Ted Kremenekf04dced2009-05-08 23:32:51 +00003271}
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003272
3273GRStateRef
3274CFRefCount::HandleSymbolDeath(GRStateRef state, SymbolRef sid, RefVal V,
3275 llvm::SmallVectorImpl<SymbolRef> &Leaked) {
3276
3277 bool hasLeak = V.isOwned() ||
3278 ((V.isNotOwned() || V.isReturnedOwned()) && V.getCount() > 0);
3279
3280 if (!hasLeak)
3281 return state.remove<RefBindings>(sid);
3282
3283 Leaked.push_back(sid);
3284 return state.set<RefBindings>(sid, V ^ RefVal::ErrorLeak);
3285}
3286
3287ExplodedNode<GRState>*
3288CFRefCount::ProcessLeaks(GRStateRef state,
3289 llvm::SmallVectorImpl<SymbolRef> &Leaked,
3290 GenericNodeBuilder &Builder,
3291 GRExprEngine& Eng,
3292 ExplodedNode<GRState> *Pred) {
3293
3294 if (Leaked.empty())
3295 return Pred;
3296
Ted Kremenekf04dced2009-05-08 23:32:51 +00003297 // Generate an intermediate node representing the leak point.
Ted Kremenek6b62ec92009-05-09 01:50:57 +00003298 ExplodedNode<GRState> *N = Builder.MakeNode(state, Pred);
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003299
3300 if (N) {
3301 for (llvm::SmallVectorImpl<SymbolRef>::iterator
3302 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3303
3304 CFRefBug *BT = static_cast<CFRefBug*>(Pred ? leakWithinFunction
3305 : leakAtReturn);
3306 assert(BT && "BugType not initialized.");
3307 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N, *I, Eng);
3308 BR->EmitReport(report);
3309 }
3310 }
3311
3312 return N;
3313}
3314
Ted Kremenekcf701772009-02-05 06:50:21 +00003315void CFRefCount::EvalEndPath(GRExprEngine& Eng,
3316 GREndPathNodeBuilder<GRState>& Builder) {
3317
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003318 GRStateRef state(Builder.getState(), Eng.getStateManager());
Ted Kremenekf04dced2009-05-08 23:32:51 +00003319 GenericNodeBuilder Bd(Builder);
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003320 RefBindings B = state.get<RefBindings>();
Ted Kremenekf04dced2009-05-08 23:32:51 +00003321 ExplodedNode<GRState> *Pred = 0;
3322
3323 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Ted Kremenek369de562009-05-09 00:10:05 +00003324 bool stop = false;
3325 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state, Bd, Pred, Eng,
3326 (*I).first,
3327 (*I).second, stop);
3328
3329 if (stop)
3330 return;
Ted Kremenekf04dced2009-05-08 23:32:51 +00003331 }
3332
3333 B = state.get<RefBindings>();
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003334 llvm::SmallVector<SymbolRef, 10> Leaked;
Ted Kremenekcf701772009-02-05 06:50:21 +00003335
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003336 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I)
3337 state = HandleSymbolDeath(state, (*I).first, (*I).second, Leaked);
3338
Ted Kremenekf04dced2009-05-08 23:32:51 +00003339 ProcessLeaks(state, Leaked, Bd, Eng, Pred);
Ted Kremenekcf701772009-02-05 06:50:21 +00003340}
3341
3342void CFRefCount::EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
3343 GRExprEngine& Eng,
3344 GRStmtNodeBuilder<GRState>& Builder,
3345 ExplodedNode<GRState>* Pred,
3346 Stmt* S,
3347 const GRState* St,
3348 SymbolReaper& SymReaper) {
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003349
3350 GRStateRef state(St, Eng.getStateManager());
Ted Kremenekf04dced2009-05-08 23:32:51 +00003351 RefBindings B = state.get<RefBindings>();
3352
3353 // Update counts from autorelease pools
3354 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3355 E = SymReaper.dead_end(); I != E; ++I) {
3356 SymbolRef Sym = *I;
3357 if (const RefVal* T = B.lookup(Sym)){
3358 // Use the symbol as the tag.
3359 // FIXME: This might not be as unique as we would like.
3360 GenericNodeBuilder Bd(Builder, S, Sym);
Ted Kremenek369de562009-05-09 00:10:05 +00003361 bool stop = false;
3362 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state, Bd, Pred, Eng,
3363 Sym, *T, stop);
3364 if (stop)
3365 return;
Ted Kremenekf04dced2009-05-08 23:32:51 +00003366 }
3367 }
3368
3369 B = state.get<RefBindings>();
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003370 llvm::SmallVector<SymbolRef, 10> Leaked;
Ted Kremenekcf701772009-02-05 06:50:21 +00003371
3372 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003373 E = SymReaper.dead_end(); I != E; ++I) {
3374 if (const RefVal* T = B.lookup(*I))
3375 state = HandleSymbolDeath(state, *I, *T, Leaked);
3376 }
Ted Kremenekcf701772009-02-05 06:50:21 +00003377
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003378 static unsigned LeakPPTag = 0;
Ted Kremenekf04dced2009-05-08 23:32:51 +00003379 {
3380 GenericNodeBuilder Bd(Builder, S, &LeakPPTag);
3381 Pred = ProcessLeaks(state, Leaked, Bd, Eng, Pred);
3382 }
Ted Kremenekcf701772009-02-05 06:50:21 +00003383
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003384 // Did we cache out?
3385 if (!Pred)
3386 return;
Ted Kremenek33b6f632009-02-19 23:47:02 +00003387
3388 // Now generate a new node that nukes the old bindings.
Ted Kremenek33b6f632009-02-19 23:47:02 +00003389 RefBindings::Factory& F = state.get_context<RefBindings>();
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003390
Ted Kremenek33b6f632009-02-19 23:47:02 +00003391 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003392 E = SymReaper.dead_end(); I!=E; ++I) B = F.Remove(B, *I);
3393
Ted Kremenek33b6f632009-02-19 23:47:02 +00003394 state = state.set<RefBindings>(B);
3395 Builder.MakeNode(Dst, S, Pred, state);
Ted Kremenekcf701772009-02-05 06:50:21 +00003396}
3397
3398void CFRefCount::ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
3399 GRStmtNodeBuilder<GRState>& Builder,
3400 Expr* NodeExpr, Expr* ErrorExpr,
3401 ExplodedNode<GRState>* Pred,
3402 const GRState* St,
3403 RefVal::Kind hasErr, SymbolRef Sym) {
3404 Builder.BuildSinks = true;
3405 GRExprEngine::NodeTy* N = Builder.MakeNode(Dst, NodeExpr, Pred, St);
3406
Ted Kremenek6b62ec92009-05-09 01:50:57 +00003407 if (!N)
3408 return;
Ted Kremenekcf701772009-02-05 06:50:21 +00003409
3410 CFRefBug *BT = 0;
3411
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003412 switch (hasErr) {
3413 default:
3414 assert(false && "Unhandled error.");
3415 return;
3416 case RefVal::ErrorUseAfterRelease:
3417 BT = static_cast<CFRefBug*>(useAfterRelease);
3418 break;
3419 case RefVal::ErrorReleaseNotOwned:
3420 BT = static_cast<CFRefBug*>(releaseNotOwned);
3421 break;
3422 case RefVal::ErrorDeallocGC:
3423 BT = static_cast<CFRefBug*>(deallocGC);
3424 break;
3425 case RefVal::ErrorDeallocNotOwned:
3426 BT = static_cast<CFRefBug*>(deallocNotOwned);
3427 break;
Ted Kremenekcf701772009-02-05 06:50:21 +00003428 }
3429
Ted Kremenekfe9e5432009-02-18 03:48:14 +00003430 CFRefReport *report = new CFRefReport(*BT, *this, N, Sym);
Ted Kremenekcf701772009-02-05 06:50:21 +00003431 report->addRange(ErrorExpr->getSourceRange());
3432 BR->EmitReport(report);
3433}
3434
3435//===----------------------------------------------------------------------===//
Ted Kremenekd71ed262008-04-10 22:16:52 +00003436// Transfer function creation for external clients.
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00003437//===----------------------------------------------------------------------===//
3438
Ted Kremenek072192b2008-04-30 23:47:44 +00003439GRTransferFuncs* clang::MakeCFRefCountTF(ASTContext& Ctx, bool GCEnabled,
3440 const LangOptions& lopts) {
Ted Kremenek78d46242008-07-22 16:21:24 +00003441 return new CFRefCount(Ctx, GCEnabled, lopts);
Ted Kremenek3ea0b6a2008-04-10 22:58:08 +00003442}