blob: ebc4dcc6ff5df9cfb9699ecbcedeff4e6f31939f [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 }
Ted Kremeneke8720ce2009-05-10 06:25:57 +0000299
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.
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001432 ErrorGCLeakReturned,
1433 ErrorOverAutorelease,
1434 ErrorReturnedNotOwned
Ted Kremenek4fd88972008-04-17 18:12:53 +00001435 };
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001436
1437private:
Ted Kremenek4fd88972008-04-17 18:12:53 +00001438 Kind kind;
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001439 RetEffect::ObjKind okind;
Ted Kremenek4fd88972008-04-17 18:12:53 +00001440 unsigned Cnt;
Ted Kremenekf21332e2009-05-08 20:01:42 +00001441 unsigned ACnt;
Ted Kremenek553cf182008-06-25 21:21:56 +00001442 QualType T;
1443
Ted Kremenekf21332e2009-05-08 20:01:42 +00001444 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, unsigned acnt, QualType t)
1445 : kind(k), okind(o), Cnt(cnt), ACnt(acnt), T(t) {}
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001446
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001447 RefVal(Kind k, unsigned cnt = 0)
Ted Kremenekf21332e2009-05-08 20:01:42 +00001448 : kind(k), okind(RetEffect::AnyObj), Cnt(cnt), ACnt(0) {}
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001449
1450public:
Ted Kremenek4fd88972008-04-17 18:12:53 +00001451 Kind getKind() const { return kind; }
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001452
1453 RetEffect::ObjKind getObjKind() const { return okind; }
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001454
Ted Kremenekf21332e2009-05-08 20:01:42 +00001455 unsigned getCount() const { return Cnt; }
1456 unsigned getAutoreleaseCount() const { return ACnt; }
1457 unsigned getCombinedCounts() const { return Cnt + ACnt; }
1458 void clearCounts() { Cnt = 0; ACnt = 0; }
Ted Kremenek369de562009-05-09 00:10:05 +00001459 void setCount(unsigned i) { Cnt = i; }
1460 void setAutoreleaseCount(unsigned i) { ACnt = i; }
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001461
Ted Kremenek553cf182008-06-25 21:21:56 +00001462 QualType getType() const { return T; }
Ted Kremenek4fd88972008-04-17 18:12:53 +00001463
1464 // Useful predicates.
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001465
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001466 static bool isError(Kind k) { return k >= ERROR_START; }
Ted Kremenek73c750b2008-03-11 18:14:09 +00001467
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001468 static bool isLeak(Kind k) { return k >= ERROR_LEAK_START; }
Ted Kremenekdb863712008-04-16 22:32:20 +00001469
Ted Kremeneke7bd9c22008-04-11 22:25:11 +00001470 bool isOwned() const {
1471 return getKind() == Owned;
1472 }
1473
Ted Kremenekdb863712008-04-16 22:32:20 +00001474 bool isNotOwned() const {
1475 return getKind() == NotOwned;
1476 }
1477
Ted Kremenek4fd88972008-04-17 18:12:53 +00001478 bool isReturnedOwned() const {
1479 return getKind() == ReturnedOwned;
1480 }
1481
1482 bool isReturnedNotOwned() const {
1483 return getKind() == ReturnedNotOwned;
1484 }
1485
1486 bool isNonLeakError() const {
1487 Kind k = getKind();
1488 return isError(k) && !isLeak(k);
1489 }
1490
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001491 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
1492 unsigned Count = 1) {
Ted Kremenekf21332e2009-05-08 20:01:42 +00001493 return RefVal(Owned, o, Count, 0, t);
Ted Kremenek61b9f872008-04-10 23:09:18 +00001494 }
1495
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001496 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
1497 unsigned Count = 0) {
Ted Kremenekf21332e2009-05-08 20:01:42 +00001498 return RefVal(NotOwned, o, Count, 0, t);
Ted Kremenek61b9f872008-04-10 23:09:18 +00001499 }
Ted Kremenek4fd88972008-04-17 18:12:53 +00001500
Ted Kremenek4fd88972008-04-17 18:12:53 +00001501 // Comparison, profiling, and pretty-printing.
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001502
Ted Kremenek4fd88972008-04-17 18:12:53 +00001503 bool operator==(const RefVal& X) const {
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001504 return kind == X.kind && Cnt == X.Cnt && T == X.T && ACnt == X.ACnt;
Ted Kremenek4fd88972008-04-17 18:12:53 +00001505 }
Ted Kremenekf3948042008-03-11 19:44:10 +00001506
Ted Kremenek553cf182008-06-25 21:21:56 +00001507 RefVal operator-(size_t i) const {
Ted Kremenekf21332e2009-05-08 20:01:42 +00001508 return RefVal(getKind(), getObjKind(), getCount() - i,
1509 getAutoreleaseCount(), getType());
Ted Kremenek553cf182008-06-25 21:21:56 +00001510 }
1511
1512 RefVal operator+(size_t i) const {
Ted Kremenekf21332e2009-05-08 20:01:42 +00001513 return RefVal(getKind(), getObjKind(), getCount() + i,
1514 getAutoreleaseCount(), getType());
Ted Kremenek553cf182008-06-25 21:21:56 +00001515 }
1516
1517 RefVal operator^(Kind k) const {
Ted Kremenekf21332e2009-05-08 20:01:42 +00001518 return RefVal(k, getObjKind(), getCount(), getAutoreleaseCount(),
1519 getType());
1520 }
1521
1522 RefVal autorelease() const {
1523 return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount()+1,
1524 getType());
Ted Kremenek553cf182008-06-25 21:21:56 +00001525 }
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001526
Ted Kremenek4fd88972008-04-17 18:12:53 +00001527 void Profile(llvm::FoldingSetNodeID& ID) const {
1528 ID.AddInteger((unsigned) kind);
1529 ID.AddInteger(Cnt);
Ted Kremenekf21332e2009-05-08 20:01:42 +00001530 ID.AddInteger(ACnt);
Ted Kremenek553cf182008-06-25 21:21:56 +00001531 ID.Add(T);
Ted Kremenek4fd88972008-04-17 18:12:53 +00001532 }
1533
Ted Kremenekf3948042008-03-11 19:44:10 +00001534 void print(std::ostream& Out) const;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001535};
Ted Kremenekf3948042008-03-11 19:44:10 +00001536
1537void RefVal::print(std::ostream& Out) const {
Ted Kremenek553cf182008-06-25 21:21:56 +00001538 if (!T.isNull())
1539 Out << "Tracked Type:" << T.getAsString() << '\n';
1540
Ted Kremenekf3948042008-03-11 19:44:10 +00001541 switch (getKind()) {
1542 default: assert(false);
Ted Kremenek61b9f872008-04-10 23:09:18 +00001543 case Owned: {
1544 Out << "Owned";
1545 unsigned cnt = getCount();
1546 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenekf3948042008-03-11 19:44:10 +00001547 break;
Ted Kremenek61b9f872008-04-10 23:09:18 +00001548 }
Ted Kremenekf3948042008-03-11 19:44:10 +00001549
Ted Kremenek61b9f872008-04-10 23:09:18 +00001550 case NotOwned: {
Ted Kremenek4fd88972008-04-17 18:12:53 +00001551 Out << "NotOwned";
Ted Kremenek61b9f872008-04-10 23:09:18 +00001552 unsigned cnt = getCount();
1553 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenekf3948042008-03-11 19:44:10 +00001554 break;
Ted Kremenek61b9f872008-04-10 23:09:18 +00001555 }
Ted Kremenekf3948042008-03-11 19:44:10 +00001556
Ted Kremenek4fd88972008-04-17 18:12:53 +00001557 case ReturnedOwned: {
1558 Out << "ReturnedOwned";
1559 unsigned cnt = getCount();
1560 if (cnt) Out << " (+ " << cnt << ")";
1561 break;
1562 }
1563
1564 case ReturnedNotOwned: {
1565 Out << "ReturnedNotOwned";
1566 unsigned cnt = getCount();
1567 if (cnt) Out << " (+ " << cnt << ")";
1568 break;
1569 }
1570
Ted Kremenekf3948042008-03-11 19:44:10 +00001571 case Released:
1572 Out << "Released";
1573 break;
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001574
1575 case ErrorDeallocGC:
1576 Out << "-dealloc (GC)";
1577 break;
1578
1579 case ErrorDeallocNotOwned:
1580 Out << "-dealloc (not-owned)";
1581 break;
Ted Kremenekf3948042008-03-11 19:44:10 +00001582
Ted Kremenekdb863712008-04-16 22:32:20 +00001583 case ErrorLeak:
1584 Out << "Leaked";
1585 break;
1586
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00001587 case ErrorLeakReturned:
1588 Out << "Leaked (Bad naming)";
1589 break;
1590
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001591 case ErrorGCLeakReturned:
1592 Out << "Leaked (GC-ed at return)";
1593 break;
1594
Ted Kremenekf3948042008-03-11 19:44:10 +00001595 case ErrorUseAfterRelease:
1596 Out << "Use-After-Release [ERROR]";
1597 break;
1598
1599 case ErrorReleaseNotOwned:
1600 Out << "Release of Not-Owned [ERROR]";
1601 break;
Ted Kremenek80c24182009-05-09 00:44:07 +00001602
1603 case RefVal::ErrorOverAutorelease:
1604 Out << "Over autoreleased";
1605 break;
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001606
1607 case RefVal::ErrorReturnedNotOwned:
1608 Out << "Non-owned object returned instead of owned";
1609 break;
Ted Kremenekf3948042008-03-11 19:44:10 +00001610 }
Ted Kremenekf21332e2009-05-08 20:01:42 +00001611
1612 if (ACnt) {
1613 Out << " [ARC +" << ACnt << ']';
1614 }
Ted Kremenekf3948042008-03-11 19:44:10 +00001615}
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001616
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001617} // end anonymous namespace
1618
1619//===----------------------------------------------------------------------===//
1620// RefBindings - State used to track object reference counts.
1621//===----------------------------------------------------------------------===//
1622
Ted Kremenek2dabd432008-12-05 02:27:51 +00001623typedef llvm::ImmutableMap<SymbolRef, RefVal> RefBindings;
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001624static int RefBIndex = 0;
1625
1626namespace clang {
Ted Kremenekb9d17f92008-08-17 03:20:02 +00001627 template<>
1628 struct GRStateTrait<RefBindings> : public GRStatePartialTrait<RefBindings> {
1629 static inline void* GDMIndex() { return &RefBIndex; }
1630 };
1631}
Ted Kremenek6d348932008-10-21 15:53:15 +00001632
1633//===----------------------------------------------------------------------===//
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001634// AutoreleaseBindings - State used to track objects in autorelease pools.
Ted Kremenek6d348932008-10-21 15:53:15 +00001635//===----------------------------------------------------------------------===//
1636
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001637typedef llvm::ImmutableMap<SymbolRef, unsigned> ARCounts;
1638typedef llvm::ImmutableMap<SymbolRef, ARCounts> ARPoolContents;
1639typedef llvm::ImmutableList<SymbolRef> ARStack;
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00001640
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001641static int AutoRCIndex = 0;
Ted Kremenek6d348932008-10-21 15:53:15 +00001642static int AutoRBIndex = 0;
1643
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001644namespace { class VISIBILITY_HIDDEN AutoreleasePoolContents {}; }
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001645namespace { class VISIBILITY_HIDDEN AutoreleaseStack {}; }
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001646
Ted Kremenek6d348932008-10-21 15:53:15 +00001647namespace clang {
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001648template<> struct GRStateTrait<AutoreleaseStack>
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001649 : public GRStatePartialTrait<ARStack> {
1650 static inline void* GDMIndex() { return &AutoRBIndex; }
1651};
1652
1653template<> struct GRStateTrait<AutoreleasePoolContents>
1654 : public GRStatePartialTrait<ARPoolContents> {
1655 static inline void* GDMIndex() { return &AutoRCIndex; }
1656};
1657} // end clang namespace
Ted Kremenek6d348932008-10-21 15:53:15 +00001658
Ted Kremenek7037ab82009-03-20 17:34:15 +00001659static SymbolRef GetCurrentAutoreleasePool(const GRState* state) {
1660 ARStack stack = state->get<AutoreleaseStack>();
1661 return stack.isEmpty() ? SymbolRef() : stack.getHead();
1662}
1663
1664static GRStateRef SendAutorelease(GRStateRef state, ARCounts::Factory &F,
1665 SymbolRef sym) {
1666
1667 SymbolRef pool = GetCurrentAutoreleasePool(state);
1668 const ARCounts *cnts = state.get<AutoreleasePoolContents>(pool);
1669 ARCounts newCnts(0);
1670
1671 if (cnts) {
1672 const unsigned *cnt = (*cnts).lookup(sym);
1673 newCnts = F.Add(*cnts, sym, cnt ? *cnt + 1 : 1);
1674 }
1675 else
1676 newCnts = F.Add(F.GetEmptyMap(), sym, 1);
1677
1678 return state.set<AutoreleasePoolContents>(pool, newCnts);
1679}
1680
Ted Kremenek13922612008-04-16 20:40:59 +00001681//===----------------------------------------------------------------------===//
1682// Transfer functions.
1683//===----------------------------------------------------------------------===//
1684
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001685namespace {
1686
Ted Kremenek05cbe1a2008-04-09 23:49:11 +00001687class VISIBILITY_HIDDEN CFRefCount : public GRSimpleVals {
Ted Kremenek8dd56462008-04-18 03:39:05 +00001688public:
Ted Kremenekae6814e2008-08-13 21:24:49 +00001689 class BindingsPrinter : public GRState::Printer {
Ted Kremenekf3948042008-03-11 19:44:10 +00001690 public:
Ted Kremenekae6814e2008-08-13 21:24:49 +00001691 virtual void Print(std::ostream& Out, const GRState* state,
1692 const char* nl, const char* sep);
Ted Kremenekf3948042008-03-11 19:44:10 +00001693 };
Ted Kremenek8dd56462008-04-18 03:39:05 +00001694
1695private:
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001696 typedef llvm::DenseMap<const GRExprEngine::NodeTy*, const RetainSummary*>
1697 SummaryLogTy;
1698
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001699 RetainSummaryManager Summaries;
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001700 SummaryLogTy SummaryLog;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001701 const LangOptions& LOpts;
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001702 ARCounts::Factory ARCountFactory;
Ted Kremenekb9d17f92008-08-17 03:20:02 +00001703
Ted Kremenekcf701772009-02-05 06:50:21 +00001704 BugType *useAfterRelease, *releaseNotOwned;
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001705 BugType *deallocGC, *deallocNotOwned;
Ted Kremenekcf701772009-02-05 06:50:21 +00001706 BugType *leakWithinFunction, *leakAtReturn;
Ted Kremenek369de562009-05-09 00:10:05 +00001707 BugType *overAutorelease;
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001708 BugType *returnNotOwnedForOwned;
Ted Kremenekcf701772009-02-05 06:50:21 +00001709 BugReporter *BR;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001710
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001711 GRStateRef Update(GRStateRef state, SymbolRef sym, RefVal V, ArgEffect E,
1712 RefVal::Kind& hasErr);
1713
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001714 void ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
1715 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekdb863712008-04-16 22:32:20 +00001716 Expr* NodeExpr, Expr* ErrorExpr,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001717 ExplodedNode<GRState>* Pred,
1718 const GRState* St,
Ted Kremenek2dabd432008-12-05 02:27:51 +00001719 RefVal::Kind hasErr, SymbolRef Sym);
Ted Kremenekdb863712008-04-16 22:32:20 +00001720
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00001721 GRStateRef HandleSymbolDeath(GRStateRef state, SymbolRef sid, RefVal V,
1722 llvm::SmallVectorImpl<SymbolRef> &Leaked);
1723
1724 ExplodedNode<GRState>* ProcessLeaks(GRStateRef state,
1725 llvm::SmallVectorImpl<SymbolRef> &Leaked,
1726 GenericNodeBuilder &Builder,
1727 GRExprEngine &Eng,
1728 ExplodedNode<GRState> *Pred = 0);
Ted Kremenekdb863712008-04-16 22:32:20 +00001729
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001730public:
Ted Kremenek78d46242008-07-22 16:21:24 +00001731 CFRefCount(ASTContext& Ctx, bool gcenabled, const LangOptions& lopts)
Ted Kremenek377e2302008-04-29 05:33:51 +00001732 : Summaries(Ctx, gcenabled),
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001733 LOpts(lopts), useAfterRelease(0), releaseNotOwned(0),
1734 deallocGC(0), deallocNotOwned(0),
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001735 leakWithinFunction(0), leakAtReturn(0), overAutorelease(0),
1736 returnNotOwnedForOwned(0), BR(0) {}
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001737
Ted Kremenekcf701772009-02-05 06:50:21 +00001738 virtual ~CFRefCount() {}
Ted Kremenek05cbe1a2008-04-09 23:49:11 +00001739
Ted Kremenekcf118d42009-02-04 23:49:09 +00001740 void RegisterChecks(BugReporter &BR);
Ted Kremenekf3948042008-03-11 19:44:10 +00001741
Ted Kremenek1c72ef02008-08-16 00:49:49 +00001742 virtual void RegisterPrinters(std::vector<GRState::Printer*>& Printers) {
1743 Printers.push_back(new BindingsPrinter());
Ted Kremenekf3948042008-03-11 19:44:10 +00001744 }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001745
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001746 bool isGCEnabled() const { return Summaries.isGCEnabled(); }
Ted Kremenek072192b2008-04-30 23:47:44 +00001747 const LangOptions& getLangOptions() const { return LOpts; }
1748
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001749 const RetainSummary *getSummaryOfNode(const ExplodedNode<GRState> *N) const {
1750 SummaryLogTy::const_iterator I = SummaryLog.find(N);
1751 return I == SummaryLog.end() ? 0 : I->second;
1752 }
1753
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001754 // Calls.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001755
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001756 void EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001757 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001758 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001759 Expr* Ex,
1760 Expr* Receiver,
Ted Kremenek7faca822009-05-04 04:57:00 +00001761 const RetainSummary& Summ,
Ted Kremenek55499762008-06-17 02:43:46 +00001762 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001763 ExplodedNode<GRState>* Pred);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001764
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001765 virtual void EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek199e1a02008-03-12 21:06:49 +00001766 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001767 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001768 CallExpr* CE, SVal L,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001769 ExplodedNode<GRState>* Pred);
Ted Kremenekfa34b332008-04-09 01:10:13 +00001770
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001771
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001772 virtual void EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek85348202008-04-15 23:44:31 +00001773 GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001774 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek85348202008-04-15 23:44:31 +00001775 ObjCMessageExpr* ME,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001776 ExplodedNode<GRState>* Pred);
Ted Kremenek85348202008-04-15 23:44:31 +00001777
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001778 bool EvalObjCMessageExprAux(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek85348202008-04-15 23:44:31 +00001779 GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001780 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek85348202008-04-15 23:44:31 +00001781 ObjCMessageExpr* ME,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001782 ExplodedNode<GRState>* Pred);
Ted Kremenek85348202008-04-15 23:44:31 +00001783
Ted Kremenek41573eb2009-02-14 01:43:44 +00001784 // Stores.
1785 virtual void EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val);
1786
Ted Kremeneke7bd9c22008-04-11 22:25:11 +00001787 // End-of-path.
1788
1789 virtual void EvalEndPath(GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001790 GREndPathNodeBuilder<GRState>& Builder);
Ted Kremeneke7bd9c22008-04-11 22:25:11 +00001791
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001792 virtual void EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek652adc62008-04-24 23:57:27 +00001793 GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001794 GRStmtNodeBuilder<GRState>& Builder,
1795 ExplodedNode<GRState>* Pred,
Ted Kremenek241677a2009-01-21 22:26:05 +00001796 Stmt* S, const GRState* state,
1797 SymbolReaper& SymReaper);
Ted Kremenekf04dced2009-05-08 23:32:51 +00001798
1799 std::pair<ExplodedNode<GRState>*, GRStateRef>
1800 HandleAutoreleaseCounts(GRStateRef state, GenericNodeBuilder Bd,
Ted Kremenek369de562009-05-09 00:10:05 +00001801 ExplodedNode<GRState>* Pred, GRExprEngine &Eng,
1802 SymbolRef Sym, RefVal V, bool &stop);
Ted Kremenek4fd88972008-04-17 18:12:53 +00001803 // Return statements.
1804
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001805 virtual void EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4fd88972008-04-17 18:12:53 +00001806 GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001807 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4fd88972008-04-17 18:12:53 +00001808 ReturnStmt* S,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001809 ExplodedNode<GRState>* Pred);
Ted Kremenekcb612922008-04-18 19:23:43 +00001810
1811 // Assumptions.
1812
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001813 virtual const GRState* EvalAssume(GRStateManager& VMgr,
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001814 const GRState* St, SVal Cond,
Ted Kremenek4323a572008-07-10 22:03:41 +00001815 bool Assumption, bool& isFeasible);
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001816};
1817
1818} // end anonymous namespace
1819
Ted Kremenek7037ab82009-03-20 17:34:15 +00001820static void PrintPool(std::ostream &Out, SymbolRef Sym, const GRState *state) {
1821 Out << ' ';
Ted Kremeneke0e4ebf2009-03-26 03:35:11 +00001822 if (Sym)
1823 Out << Sym->getSymbolID();
Ted Kremenek7037ab82009-03-20 17:34:15 +00001824 else
1825 Out << "<pool>";
1826 Out << ":{";
1827
1828 // Get the contents of the pool.
1829 if (const ARCounts *cnts = state->get<AutoreleasePoolContents>(Sym))
1830 for (ARCounts::iterator J=cnts->begin(), EJ=cnts->end(); J != EJ; ++J)
1831 Out << '(' << J.getKey() << ',' << J.getData() << ')';
1832
1833 Out << '}';
1834}
Ted Kremenek8dd56462008-04-18 03:39:05 +00001835
Ted Kremenekae6814e2008-08-13 21:24:49 +00001836void CFRefCount::BindingsPrinter::Print(std::ostream& Out, const GRState* state,
1837 const char* nl, const char* sep) {
Ted Kremenek7037ab82009-03-20 17:34:15 +00001838
1839
Ted Kremenekae6814e2008-08-13 21:24:49 +00001840
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001841 RefBindings B = state->get<RefBindings>();
Ted Kremenekf3948042008-03-11 19:44:10 +00001842
Ted Kremenekae6814e2008-08-13 21:24:49 +00001843 if (!B.isEmpty())
Ted Kremenekf3948042008-03-11 19:44:10 +00001844 Out << sep << nl;
1845
1846 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
1847 Out << (*I).first << " : ";
1848 (*I).second.print(Out);
1849 Out << nl;
1850 }
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001851
1852 // Print the autorelease stack.
Ted Kremenek7037ab82009-03-20 17:34:15 +00001853 Out << sep << nl << "AR pool stack:";
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001854 ARStack stack = state->get<AutoreleaseStack>();
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001855
Ted Kremenek7037ab82009-03-20 17:34:15 +00001856 PrintPool(Out, SymbolRef(), state); // Print the caller's pool.
1857 for (ARStack::iterator I=stack.begin(), E=stack.end(); I!=E; ++I)
1858 PrintPool(Out, *I, state);
1859
1860 Out << nl;
Ted Kremenekf3948042008-03-11 19:44:10 +00001861}
1862
Ted Kremenekc887d132009-04-29 18:50:19 +00001863//===----------------------------------------------------------------------===//
1864// Error reporting.
1865//===----------------------------------------------------------------------===//
1866
1867namespace {
1868
1869 //===-------------===//
1870 // Bug Descriptions. //
1871 //===-------------===//
1872
1873 class VISIBILITY_HIDDEN CFRefBug : public BugType {
1874 protected:
1875 CFRefCount& TF;
1876
1877 CFRefBug(CFRefCount* tf, const char* name)
1878 : BugType(name, "Memory (Core Foundation/Objective-C)"), TF(*tf) {}
1879 public:
1880
1881 CFRefCount& getTF() { return TF; }
1882 const CFRefCount& getTF() const { return TF; }
1883
1884 // FIXME: Eventually remove.
1885 virtual const char* getDescription() const = 0;
1886
1887 virtual bool isLeak() const { return false; }
1888 };
1889
1890 class VISIBILITY_HIDDEN UseAfterRelease : public CFRefBug {
1891 public:
1892 UseAfterRelease(CFRefCount* tf)
1893 : CFRefBug(tf, "Use-after-release") {}
1894
1895 const char* getDescription() const {
1896 return "Reference-counted object is used after it is released";
1897 }
1898 };
1899
1900 class VISIBILITY_HIDDEN BadRelease : public CFRefBug {
1901 public:
1902 BadRelease(CFRefCount* tf) : CFRefBug(tf, "Bad release") {}
1903
1904 const char* getDescription() const {
1905 return "Incorrect decrement of the reference count of an "
1906 "object is not owned at this point by the caller";
1907 }
1908 };
1909
1910 class VISIBILITY_HIDDEN DeallocGC : public CFRefBug {
1911 public:
Ted Kremenek369de562009-05-09 00:10:05 +00001912 DeallocGC(CFRefCount *tf)
1913 : CFRefBug(tf, "-dealloc called while using garbage collection") {}
Ted Kremenekc887d132009-04-29 18:50:19 +00001914
1915 const char *getDescription() const {
Ted Kremenek369de562009-05-09 00:10:05 +00001916 return "-dealloc called while using garbage collection";
Ted Kremenekc887d132009-04-29 18:50:19 +00001917 }
1918 };
1919
1920 class VISIBILITY_HIDDEN DeallocNotOwned : public CFRefBug {
1921 public:
Ted Kremenek369de562009-05-09 00:10:05 +00001922 DeallocNotOwned(CFRefCount *tf)
1923 : CFRefBug(tf, "-dealloc sent to non-exclusively owned object") {}
Ted Kremenekc887d132009-04-29 18:50:19 +00001924
1925 const char *getDescription() const {
1926 return "-dealloc sent to object that may be referenced elsewhere";
1927 }
1928 };
1929
Ted Kremenek369de562009-05-09 00:10:05 +00001930 class VISIBILITY_HIDDEN OverAutorelease : public CFRefBug {
1931 public:
1932 OverAutorelease(CFRefCount *tf) :
1933 CFRefBug(tf, "Object sent -autorelease too many times") {}
1934
1935 const char *getDescription() const {
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001936 return "Object sent -autorelease too many times";
Ted Kremenek369de562009-05-09 00:10:05 +00001937 }
1938 };
1939
Ted Kremeneke8720ce2009-05-10 06:25:57 +00001940 class VISIBILITY_HIDDEN ReturnedNotOwnedForOwned : public CFRefBug {
1941 public:
1942 ReturnedNotOwnedForOwned(CFRefCount *tf) :
1943 CFRefBug(tf, "Method should return an owned object") {}
1944
1945 const char *getDescription() const {
1946 return "Object with +0 retain counts returned to caller where a +1 "
1947 "(owning) retain count is expected";
1948 }
1949 };
1950
Ted Kremenekc887d132009-04-29 18:50:19 +00001951 class VISIBILITY_HIDDEN Leak : public CFRefBug {
1952 const bool isReturn;
1953 protected:
1954 Leak(CFRefCount* tf, const char* name, bool isRet)
1955 : CFRefBug(tf, name), isReturn(isRet) {}
1956 public:
1957
1958 const char* getDescription() const { return ""; }
1959
1960 bool isLeak() const { return true; }
1961 };
1962
1963 class VISIBILITY_HIDDEN LeakAtReturn : public Leak {
1964 public:
1965 LeakAtReturn(CFRefCount* tf, const char* name)
1966 : Leak(tf, name, true) {}
1967 };
1968
1969 class VISIBILITY_HIDDEN LeakWithinFunction : public Leak {
1970 public:
1971 LeakWithinFunction(CFRefCount* tf, const char* name)
1972 : Leak(tf, name, false) {}
1973 };
1974
1975 //===---------===//
1976 // Bug Reports. //
1977 //===---------===//
1978
1979 class VISIBILITY_HIDDEN CFRefReport : public RangedBugReport {
1980 protected:
1981 SymbolRef Sym;
1982 const CFRefCount &TF;
1983 public:
1984 CFRefReport(CFRefBug& D, const CFRefCount &tf,
1985 ExplodedNode<GRState> *n, SymbolRef sym)
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001986 : RangedBugReport(D, D.getDescription(), n), Sym(sym), TF(tf) {}
1987
1988 CFRefReport(CFRefBug& D, const CFRefCount &tf,
1989 ExplodedNode<GRState> *n, SymbolRef sym, const char* endText)
1990 : RangedBugReport(D, D.getDescription(), endText, n), Sym(sym), TF(tf) {}
Ted Kremenekc887d132009-04-29 18:50:19 +00001991
1992 virtual ~CFRefReport() {}
1993
1994 CFRefBug& getBugType() {
1995 return (CFRefBug&) RangedBugReport::getBugType();
1996 }
1997 const CFRefBug& getBugType() const {
1998 return (const CFRefBug&) RangedBugReport::getBugType();
1999 }
2000
2001 virtual void getRanges(BugReporter& BR, const SourceRange*& beg,
2002 const SourceRange*& end) {
2003
2004 if (!getBugType().isLeak())
2005 RangedBugReport::getRanges(BR, beg, end);
2006 else
2007 beg = end = 0;
2008 }
2009
2010 SymbolRef getSymbol() const { return Sym; }
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 std::pair<const char**,const char**> getExtraDescriptiveText();
2016
2017 PathDiagnosticPiece* VisitNode(const ExplodedNode<GRState>* N,
2018 const ExplodedNode<GRState>* PrevN,
Ted Kremenek8966bc12009-05-06 21:39:49 +00002019 BugReporterContext& BRC);
Ted Kremenekc887d132009-04-29 18:50:19 +00002020 };
Ted Kremenekeaedfea2009-05-10 05:11:21 +00002021
Ted Kremenekc887d132009-04-29 18:50:19 +00002022 class VISIBILITY_HIDDEN CFRefLeakReport : public CFRefReport {
2023 SourceLocation AllocSite;
2024 const MemRegion* AllocBinding;
2025 public:
2026 CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2027 ExplodedNode<GRState> *n, SymbolRef sym,
2028 GRExprEngine& Eng);
2029
Ted Kremenek8966bc12009-05-06 21:39:49 +00002030 PathDiagnosticPiece* getEndPath(BugReporterContext& BRC,
Ted Kremenekc887d132009-04-29 18:50:19 +00002031 const ExplodedNode<GRState>* N);
2032
2033 SourceLocation getLocation() const { return AllocSite; }
2034 };
2035} // end anonymous namespace
2036
2037void CFRefCount::RegisterChecks(BugReporter& BR) {
2038 useAfterRelease = new UseAfterRelease(this);
2039 BR.Register(useAfterRelease);
2040
2041 releaseNotOwned = new BadRelease(this);
2042 BR.Register(releaseNotOwned);
2043
2044 deallocGC = new DeallocGC(this);
2045 BR.Register(deallocGC);
2046
2047 deallocNotOwned = new DeallocNotOwned(this);
2048 BR.Register(deallocNotOwned);
2049
Ted Kremenek369de562009-05-09 00:10:05 +00002050 overAutorelease = new OverAutorelease(this);
2051 BR.Register(overAutorelease);
2052
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002053 returnNotOwnedForOwned = new ReturnedNotOwnedForOwned(this);
2054 BR.Register(returnNotOwnedForOwned);
2055
Ted Kremenekc887d132009-04-29 18:50:19 +00002056 // First register "return" leaks.
2057 const char* name = 0;
2058
2059 if (isGCEnabled())
2060 name = "Leak of returned object when using garbage collection";
2061 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2062 name = "Leak of returned object when not using garbage collection (GC) in "
2063 "dual GC/non-GC code";
2064 else {
2065 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2066 name = "Leak of returned object";
2067 }
2068
2069 leakAtReturn = new LeakAtReturn(this, name);
2070 BR.Register(leakAtReturn);
2071
2072 // Second, register leaks within a function/method.
2073 if (isGCEnabled())
2074 name = "Leak of object when using garbage collection";
2075 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2076 name = "Leak of object when not using garbage collection (GC) in "
2077 "dual GC/non-GC code";
2078 else {
2079 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2080 name = "Leak";
2081 }
2082
2083 leakWithinFunction = new LeakWithinFunction(this, name);
2084 BR.Register(leakWithinFunction);
2085
2086 // Save the reference to the BugReporter.
2087 this->BR = &BR;
2088}
2089
2090static const char* Msgs[] = {
2091 // GC only
2092 "Code is compiled to only use garbage collection",
2093 // No GC.
2094 "Code is compiled to use reference counts",
2095 // Hybrid, with GC.
2096 "Code is compiled to use either garbage collection (GC) or reference counts"
2097 " (non-GC). The bug occurs with GC enabled",
2098 // Hybrid, without GC
2099 "Code is compiled to use either garbage collection (GC) or reference counts"
2100 " (non-GC). The bug occurs in non-GC mode"
2101};
2102
2103std::pair<const char**,const char**> CFRefReport::getExtraDescriptiveText() {
2104 CFRefCount& TF = static_cast<CFRefBug&>(getBugType()).getTF();
2105
2106 switch (TF.getLangOptions().getGCMode()) {
2107 default:
2108 assert(false);
2109
2110 case LangOptions::GCOnly:
2111 assert (TF.isGCEnabled());
2112 return std::make_pair(&Msgs[0], &Msgs[0]+1);
2113
2114 case LangOptions::NonGC:
2115 assert (!TF.isGCEnabled());
2116 return std::make_pair(&Msgs[1], &Msgs[1]+1);
2117
2118 case LangOptions::HybridGC:
2119 if (TF.isGCEnabled())
2120 return std::make_pair(&Msgs[2], &Msgs[2]+1);
2121 else
2122 return std::make_pair(&Msgs[3], &Msgs[3]+1);
2123 }
2124}
2125
2126static inline bool contains(const llvm::SmallVectorImpl<ArgEffect>& V,
2127 ArgEffect X) {
2128 for (llvm::SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
2129 I!=E; ++I)
2130 if (*I == X) return true;
2131
2132 return false;
2133}
2134
2135PathDiagnosticPiece* CFRefReport::VisitNode(const ExplodedNode<GRState>* N,
2136 const ExplodedNode<GRState>* PrevN,
Ted Kremenek8966bc12009-05-06 21:39:49 +00002137 BugReporterContext& BRC) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002138
Ted Kremenek8966bc12009-05-06 21:39:49 +00002139 // Check if the type state has changed.
2140 GRStateManager &StMgr = BRC.getStateManager();
Ted Kremenekc887d132009-04-29 18:50:19 +00002141 GRStateRef PrevSt(PrevN->getState(), StMgr);
2142 GRStateRef CurrSt(N->getState(), StMgr);
2143
2144 const RefVal* CurrT = CurrSt.get<RefBindings>(Sym);
2145 if (!CurrT) return NULL;
2146
2147 const RefVal& CurrV = *CurrT;
2148 const RefVal* PrevT = PrevSt.get<RefBindings>(Sym);
2149
2150 // Create a string buffer to constain all the useful things we want
2151 // to tell the user.
2152 std::string sbuf;
2153 llvm::raw_string_ostream os(sbuf);
2154
2155 // This is the allocation site since the previous node had no bindings
2156 // for this symbol.
2157 if (!PrevT) {
2158 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2159
2160 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2161 // Get the name of the callee (if it is available).
2162 SVal X = CurrSt.GetSValAsScalarOrLoc(CE->getCallee());
2163 if (const FunctionDecl* FD = X.getAsFunctionDecl())
2164 os << "Call to function '" << FD->getNameAsString() <<'\'';
2165 else
2166 os << "function call";
2167 }
2168 else {
2169 assert (isa<ObjCMessageExpr>(S));
2170 os << "Method";
2171 }
2172
2173 if (CurrV.getObjKind() == RetEffect::CF) {
2174 os << " returns a Core Foundation object with a ";
2175 }
2176 else {
2177 assert (CurrV.getObjKind() == RetEffect::ObjC);
2178 os << " returns an Objective-C object with a ";
2179 }
2180
2181 if (CurrV.isOwned()) {
2182 os << "+1 retain count (owning reference).";
2183
2184 if (static_cast<CFRefBug&>(getBugType()).getTF().isGCEnabled()) {
2185 assert(CurrV.getObjKind() == RetEffect::CF);
2186 os << " "
2187 "Core Foundation objects are not automatically garbage collected.";
2188 }
2189 }
2190 else {
2191 assert (CurrV.isNotOwned());
2192 os << "+0 retain count (non-owning reference).";
2193 }
2194
Ted Kremenek8966bc12009-05-06 21:39:49 +00002195 PathDiagnosticLocation Pos(S, BRC.getSourceManager());
Ted Kremenekc887d132009-04-29 18:50:19 +00002196 return new PathDiagnosticEventPiece(Pos, os.str());
2197 }
2198
2199 // Gather up the effects that were performed on the object at this
2200 // program point
2201 llvm::SmallVector<ArgEffect, 2> AEffects;
2202
Ted Kremenek8966bc12009-05-06 21:39:49 +00002203 if (const RetainSummary *Summ =
2204 TF.getSummaryOfNode(BRC.getNodeResolver().getOriginalNode(N))) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002205 // We only have summaries attached to nodes after evaluating CallExpr and
2206 // ObjCMessageExprs.
2207 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2208
2209 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2210 // Iterate through the parameter expressions and see if the symbol
2211 // was ever passed as an argument.
2212 unsigned i = 0;
2213
2214 for (CallExpr::arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
2215 AI!=AE; ++AI, ++i) {
2216
2217 // Retrieve the value of the argument. Is it the symbol
2218 // we are interested in?
2219 if (CurrSt.GetSValAsScalarOrLoc(*AI).getAsLocSymbol() != Sym)
2220 continue;
2221
2222 // We have an argument. Get the effect!
2223 AEffects.push_back(Summ->getArg(i));
2224 }
2225 }
2226 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
2227 if (Expr *receiver = ME->getReceiver())
2228 if (CurrSt.GetSValAsScalarOrLoc(receiver).getAsLocSymbol() == Sym) {
2229 // The symbol we are tracking is the receiver.
2230 AEffects.push_back(Summ->getReceiverEffect());
2231 }
2232 }
2233 }
2234
2235 do {
2236 // Get the previous type state.
2237 RefVal PrevV = *PrevT;
2238
2239 // Specially handle -dealloc.
2240 if (!TF.isGCEnabled() && contains(AEffects, Dealloc)) {
2241 // Determine if the object's reference count was pushed to zero.
2242 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2243 // We may not have transitioned to 'release' if we hit an error.
2244 // This case is handled elsewhere.
2245 if (CurrV.getKind() == RefVal::Released) {
Ted Kremenekf21332e2009-05-08 20:01:42 +00002246 assert(CurrV.getCombinedCounts() == 0);
Ted Kremenekc887d132009-04-29 18:50:19 +00002247 os << "Object released by directly sending the '-dealloc' message";
2248 break;
2249 }
2250 }
2251
2252 // Specially handle CFMakeCollectable and friends.
2253 if (contains(AEffects, MakeCollectable)) {
2254 // Get the name of the function.
2255 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2256 SVal X = CurrSt.GetSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee());
2257 const FunctionDecl* FD = X.getAsFunctionDecl();
2258 const std::string& FName = FD->getNameAsString();
2259
2260 if (TF.isGCEnabled()) {
2261 // Determine if the object's reference count was pushed to zero.
2262 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2263
2264 os << "In GC mode a call to '" << FName
2265 << "' decrements an object's retain count and registers the "
2266 "object with the garbage collector. ";
2267
2268 if (CurrV.getKind() == RefVal::Released) {
2269 assert(CurrV.getCount() == 0);
2270 os << "Since it now has a 0 retain count the object can be "
2271 "automatically collected by the garbage collector.";
2272 }
2273 else
2274 os << "An object must have a 0 retain count to be garbage collected. "
2275 "After this call its retain count is +" << CurrV.getCount()
2276 << '.';
2277 }
2278 else
2279 os << "When GC is not enabled a call to '" << FName
2280 << "' has no effect on its argument.";
2281
2282 // Nothing more to say.
2283 break;
2284 }
2285
2286 // Determine if the typestate has changed.
2287 if (!(PrevV == CurrV))
2288 switch (CurrV.getKind()) {
2289 case RefVal::Owned:
2290 case RefVal::NotOwned:
2291
Ted Kremenekf21332e2009-05-08 20:01:42 +00002292 if (PrevV.getCount() == CurrV.getCount()) {
2293 // Did an autorelease message get sent?
2294 if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
2295 return 0;
2296
2297 assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount());
Ted Kremenekeaedfea2009-05-10 05:11:21 +00002298 os << "Object sent -autorelease message";
Ted Kremenekf21332e2009-05-08 20:01:42 +00002299 break;
2300 }
Ted Kremenekc887d132009-04-29 18:50:19 +00002301
2302 if (PrevV.getCount() > CurrV.getCount())
2303 os << "Reference count decremented.";
2304 else
2305 os << "Reference count incremented.";
2306
2307 if (unsigned Count = CurrV.getCount())
2308 os << " The object now has a +" << Count << " retain count.";
2309
2310 if (PrevV.getKind() == RefVal::Released) {
2311 assert(TF.isGCEnabled() && CurrV.getCount() > 0);
2312 os << " The object is not eligible for garbage collection until the "
2313 "retain count reaches 0 again.";
2314 }
2315
2316 break;
2317
2318 case RefVal::Released:
2319 os << "Object released.";
2320 break;
2321
2322 case RefVal::ReturnedOwned:
2323 os << "Object returned to caller as an owning reference (single retain "
2324 "count transferred to caller).";
2325 break;
2326
2327 case RefVal::ReturnedNotOwned:
2328 os << "Object returned to caller with a +0 (non-owning) retain count.";
2329 break;
2330
2331 default:
2332 return NULL;
2333 }
2334
2335 // Emit any remaining diagnostics for the argument effects (if any).
2336 for (llvm::SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
2337 E=AEffects.end(); I != E; ++I) {
2338
2339 // A bunch of things have alternate behavior under GC.
2340 if (TF.isGCEnabled())
2341 switch (*I) {
2342 default: break;
2343 case Autorelease:
2344 os << "In GC mode an 'autorelease' has no effect.";
2345 continue;
2346 case IncRefMsg:
2347 os << "In GC mode the 'retain' message has no effect.";
2348 continue;
2349 case DecRefMsg:
2350 os << "In GC mode the 'release' message has no effect.";
2351 continue;
2352 }
2353 }
2354 } while(0);
2355
2356 if (os.str().empty())
2357 return 0; // We have nothing to say!
2358
2359 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
Ted Kremenek8966bc12009-05-06 21:39:49 +00002360 PathDiagnosticLocation Pos(S, BRC.getSourceManager());
Ted Kremenekc887d132009-04-29 18:50:19 +00002361 PathDiagnosticPiece* P = new PathDiagnosticEventPiece(Pos, os.str());
2362
2363 // Add the range by scanning the children of the statement for any bindings
2364 // to Sym.
2365 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I)
2366 if (Expr* Exp = dyn_cast_or_null<Expr>(*I))
2367 if (CurrSt.GetSValAsScalarOrLoc(Exp).getAsLocSymbol() == Sym) {
2368 P->addRange(Exp->getSourceRange());
2369 break;
2370 }
2371
2372 return P;
2373}
2374
2375namespace {
2376 class VISIBILITY_HIDDEN FindUniqueBinding :
2377 public StoreManager::BindingsHandler {
2378 SymbolRef Sym;
2379 const MemRegion* Binding;
2380 bool First;
2381
2382 public:
2383 FindUniqueBinding(SymbolRef sym) : Sym(sym), Binding(0), First(true) {}
2384
2385 bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
2386 SVal val) {
2387
2388 SymbolRef SymV = val.getAsSymbol();
2389 if (!SymV || SymV != Sym)
2390 return true;
2391
2392 if (Binding) {
2393 First = false;
2394 return false;
2395 }
2396 else
2397 Binding = R;
2398
2399 return true;
2400 }
2401
2402 operator bool() { return First && Binding; }
2403 const MemRegion* getRegion() { return Binding; }
2404 };
2405}
2406
2407static std::pair<const ExplodedNode<GRState>*,const MemRegion*>
2408GetAllocationSite(GRStateManager& StateMgr, const ExplodedNode<GRState>* N,
2409 SymbolRef Sym) {
2410
2411 // Find both first node that referred to the tracked symbol and the
2412 // memory location that value was store to.
2413 const ExplodedNode<GRState>* Last = N;
2414 const MemRegion* FirstBinding = 0;
2415
2416 while (N) {
2417 const GRState* St = N->getState();
2418 RefBindings B = St->get<RefBindings>();
2419
2420 if (!B.lookup(Sym))
2421 break;
2422
2423 FindUniqueBinding FB(Sym);
2424 StateMgr.iterBindings(St, FB);
2425 if (FB) FirstBinding = FB.getRegion();
2426
2427 Last = N;
2428 N = N->pred_empty() ? NULL : *(N->pred_begin());
2429 }
2430
2431 return std::make_pair(Last, FirstBinding);
2432}
2433
2434PathDiagnosticPiece*
Ted Kremenek8966bc12009-05-06 21:39:49 +00002435CFRefReport::getEndPath(BugReporterContext& BRC,
2436 const ExplodedNode<GRState>* EndN) {
2437 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenekc887d132009-04-29 18:50:19 +00002438 // assigned to different variables, etc.
Ted Kremenek8966bc12009-05-06 21:39:49 +00002439 BRC.addNotableSymbol(Sym);
2440 return RangedBugReport::getEndPath(BRC, EndN);
Ted Kremenekc887d132009-04-29 18:50:19 +00002441}
2442
2443PathDiagnosticPiece*
Ted Kremenek8966bc12009-05-06 21:39:49 +00002444CFRefLeakReport::getEndPath(BugReporterContext& BRC,
2445 const ExplodedNode<GRState>* EndN){
Ted Kremenekc887d132009-04-29 18:50:19 +00002446
Ted Kremenek8966bc12009-05-06 21:39:49 +00002447 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenekc887d132009-04-29 18:50:19 +00002448 // assigned to different variables, etc.
Ted Kremenek8966bc12009-05-06 21:39:49 +00002449 BRC.addNotableSymbol(Sym);
Ted Kremenekc887d132009-04-29 18:50:19 +00002450
2451 // We are reporting a leak. Walk up the graph to get to the first node where
2452 // the symbol appeared, and also get the first VarDecl that tracked object
2453 // is stored to.
2454 const ExplodedNode<GRState>* AllocNode = 0;
2455 const MemRegion* FirstBinding = 0;
2456
2457 llvm::tie(AllocNode, FirstBinding) =
Ted Kremenekf04dced2009-05-08 23:32:51 +00002458 GetAllocationSite(BRC.getStateManager(), EndN, Sym);
Ted Kremenekc887d132009-04-29 18:50:19 +00002459
2460 // Get the allocate site.
2461 assert(AllocNode);
2462 Stmt* FirstStmt = cast<PostStmt>(AllocNode->getLocation()).getStmt();
2463
Ted Kremenek8966bc12009-05-06 21:39:49 +00002464 SourceManager& SMgr = BRC.getSourceManager();
Ted Kremenekc887d132009-04-29 18:50:19 +00002465 unsigned AllocLine =SMgr.getInstantiationLineNumber(FirstStmt->getLocStart());
2466
2467 // Compute an actual location for the leak. Sometimes a leak doesn't
2468 // occur at an actual statement (e.g., transition between blocks; end
2469 // of function) so we need to walk the graph and compute a real location.
2470 const ExplodedNode<GRState>* LeakN = EndN;
2471 PathDiagnosticLocation L;
2472
2473 while (LeakN) {
2474 ProgramPoint P = LeakN->getLocation();
2475
2476 if (const PostStmt *PS = dyn_cast<PostStmt>(&P)) {
2477 L = PathDiagnosticLocation(PS->getStmt()->getLocStart(), SMgr);
2478 break;
2479 }
2480 else if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
2481 if (const Stmt* Term = BE->getSrc()->getTerminator()) {
2482 L = PathDiagnosticLocation(Term->getLocStart(), SMgr);
2483 break;
2484 }
2485 }
2486
2487 LeakN = LeakN->succ_empty() ? 0 : *(LeakN->succ_begin());
2488 }
2489
2490 if (!L.isValid()) {
Ted Kremenek8966bc12009-05-06 21:39:49 +00002491 const Decl &D = BRC.getCodeDecl();
2492 L = PathDiagnosticLocation(D.getBodyRBrace(BRC.getASTContext()), SMgr);
Ted Kremenekc887d132009-04-29 18:50:19 +00002493 }
2494
2495 std::string sbuf;
2496 llvm::raw_string_ostream os(sbuf);
2497
2498 os << "Object allocated on line " << AllocLine;
2499
2500 if (FirstBinding)
2501 os << " and stored into '" << FirstBinding->getString() << '\'';
2502
2503 // Get the retain count.
2504 const RefVal* RV = EndN->getState()->get<RefBindings>(Sym);
2505
2506 if (RV->getKind() == RefVal::ErrorLeakReturned) {
2507 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
2508 // ojbects. Only "copy", "alloc", "retain" and "new" transfer ownership
2509 // to the caller for NS objects.
Ted Kremenek8966bc12009-05-06 21:39:49 +00002510 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(BRC.getCodeDecl());
Ted Kremenekc887d132009-04-29 18:50:19 +00002511 os << " is returned from a method whose name ('"
Ted Kremeneka8833552009-04-29 23:03:22 +00002512 << MD.getSelector().getAsString()
Ted Kremenekc887d132009-04-29 18:50:19 +00002513 << "') does not contain 'copy' or otherwise starts with"
2514 " 'new' or 'alloc'. This violates the naming convention rules given"
Ted Kremenek8987a022009-04-29 22:25:52 +00002515 " in the Memory Management Guide for Cocoa (object leaked)";
Ted Kremenekc887d132009-04-29 18:50:19 +00002516 }
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002517 else if (RV->getKind() == RefVal::ErrorGCLeakReturned) {
2518 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(BRC.getCodeDecl());
2519 os << " and returned from method '" << MD.getSelector().getAsString()
Ted Kremenek82f2be52009-05-10 16:52:15 +00002520 << "' is potentially leaked when using garbage collection. Callers "
2521 "of this method do not expect a returned object with a +1 retain "
2522 "count since they expect the object to be managed by the garbage "
2523 "collector";
Ted Kremeneke8720ce2009-05-10 06:25:57 +00002524 }
Ted Kremenekc887d132009-04-29 18:50:19 +00002525 else
2526 os << " is no longer referenced after this point and has a retain count of"
Ted Kremenek8987a022009-04-29 22:25:52 +00002527 " +" << RV->getCount() << " (object leaked)";
Ted Kremenekc887d132009-04-29 18:50:19 +00002528
2529 return new PathDiagnosticEventPiece(L, os.str());
2530}
2531
Ted Kremenekc887d132009-04-29 18:50:19 +00002532CFRefLeakReport::CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2533 ExplodedNode<GRState> *n,
2534 SymbolRef sym, GRExprEngine& Eng)
2535: CFRefReport(D, tf, n, sym)
2536{
2537
2538 // Most bug reports are cached at the location where they occured.
2539 // With leaks, we want to unique them by the location where they were
2540 // allocated, and only report a single path. To do this, we need to find
2541 // the allocation site of a piece of tracked memory, which we do via a
2542 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2543 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2544 // that all ancestor nodes that represent the allocation site have the
2545 // same SourceLocation.
2546 const ExplodedNode<GRState>* AllocNode = 0;
2547
2548 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding.
Ted Kremenekf04dced2009-05-08 23:32:51 +00002549 GetAllocationSite(Eng.getStateManager(), getEndNode(), getSymbol());
Ted Kremenekc887d132009-04-29 18:50:19 +00002550
2551 // Get the SourceLocation for the allocation site.
2552 ProgramPoint P = AllocNode->getLocation();
2553 AllocSite = cast<PostStmt>(P).getStmt()->getLocStart();
2554
2555 // Fill in the description of the bug.
2556 Description.clear();
2557 llvm::raw_string_ostream os(Description);
2558 SourceManager& SMgr = Eng.getContext().getSourceManager();
2559 unsigned AllocLine = SMgr.getInstantiationLineNumber(AllocSite);
Ted Kremenekdd924e22009-05-02 19:05:19 +00002560 os << "Potential leak ";
2561 if (tf.isGCEnabled()) {
2562 os << "(when using garbage collection) ";
2563 }
2564 os << "of an object allocated on line " << AllocLine;
Ted Kremenekc887d132009-04-29 18:50:19 +00002565
2566 // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2567 if (AllocBinding)
2568 os << " and stored into '" << AllocBinding->getString() << '\'';
2569}
2570
2571//===----------------------------------------------------------------------===//
2572// Main checker logic.
2573//===----------------------------------------------------------------------===//
2574
Ted Kremenek553cf182008-06-25 21:21:56 +00002575/// GetReturnType - Used to get the return type of a message expression or
2576/// function call with the intention of affixing that type to a tracked symbol.
2577/// While the the return type can be queried directly from RetEx, when
2578/// invoking class methods we augment to the return type to be that of
2579/// a pointer to the class (as opposed it just being id).
2580static QualType GetReturnType(Expr* RetE, ASTContext& Ctx) {
2581
2582 QualType RetTy = RetE->getType();
2583
2584 // FIXME: We aren't handling id<...>.
Chris Lattner8b51fd72008-07-26 22:36:27 +00002585 const PointerType* PT = RetTy->getAsPointerType();
Ted Kremenek553cf182008-06-25 21:21:56 +00002586 if (!PT)
2587 return RetTy;
2588
2589 // If RetEx is not a message expression just return its type.
2590 // If RetEx is a message expression, return its types if it is something
2591 /// more specific than id.
2592
2593 ObjCMessageExpr* ME = dyn_cast<ObjCMessageExpr>(RetE);
2594
Steve Naroff389bf462009-02-12 17:52:19 +00002595 if (!ME || !Ctx.isObjCIdStructType(PT->getPointeeType()))
Ted Kremenek553cf182008-06-25 21:21:56 +00002596 return RetTy;
2597
2598 ObjCInterfaceDecl* D = ME->getClassInfo().first;
2599
2600 // At this point we know the return type of the message expression is id.
2601 // If we have an ObjCInterceDecl, we know this is a call to a class method
2602 // whose type we can resolve. In such cases, promote the return type to
2603 // Class*.
2604 return !D ? RetTy : Ctx.getPointerType(Ctx.getObjCInterfaceType(D));
2605}
2606
2607
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002608void CFRefCount::EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002609 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002610 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002611 Expr* Ex,
2612 Expr* Receiver,
Ted Kremenek7faca822009-05-04 04:57:00 +00002613 const RetainSummary& Summ,
Zhongxing Xu369f4472009-04-20 05:24:46 +00002614 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002615 ExplodedNode<GRState>* Pred) {
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002616
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00002617 // Get the state.
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002618 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenekf9790ae2008-10-24 20:32:50 +00002619 ASTContext& Ctx = Eng.getStateManager().getContext();
Ted Kremenek14993892008-05-06 02:41:27 +00002620
2621 // Evaluate the effect of the arguments.
Ted Kremenek9ed18e62008-04-16 04:28:53 +00002622 RefVal::Kind hasErr = (RefVal::Kind) 0;
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002623 unsigned idx = 0;
Ted Kremenekbcf50ad2008-04-11 18:40:51 +00002624 Expr* ErrorExpr = NULL;
Ted Kremenek2dabd432008-12-05 02:27:51 +00002625 SymbolRef ErrorSym = 0;
Ted Kremenekbcf50ad2008-04-11 18:40:51 +00002626
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002627 for (ExprIterator I = arg_beg; I != arg_end; ++I, ++idx) {
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00002628 SVal V = state.GetSValAsScalarOrLoc(*I);
Ted Kremenek94c96982009-03-03 22:06:47 +00002629 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00002630
Ted Kremeneke0e4ebf2009-03-26 03:35:11 +00002631 if (Sym)
Ted Kremenek4d3957d2009-02-24 19:15:11 +00002632 if (RefBindings::data_type* T = state.get<RefBindings>(Sym)) {
Ted Kremenek7faca822009-05-04 04:57:00 +00002633 state = Update(state, Sym, *T, Summ.getArg(idx), hasErr);
Ted Kremenek4d3957d2009-02-24 19:15:11 +00002634 if (hasErr) {
Ted Kremenekbcf50ad2008-04-11 18:40:51 +00002635 ErrorExpr = *I;
Ted Kremeneke8fdc832008-07-07 16:21:19 +00002636 ErrorSym = Sym;
Ted Kremenekbcf50ad2008-04-11 18:40:51 +00002637 break;
Ted Kremenek94c96982009-03-03 22:06:47 +00002638 }
2639 continue;
Ted Kremenek4d3957d2009-02-24 19:15:11 +00002640 }
Ted Kremenek070a8252008-07-09 18:11:16 +00002641
Ted Kremenek94c96982009-03-03 22:06:47 +00002642 if (isa<Loc>(V)) {
2643 if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(&V)) {
Ted Kremenek7faca822009-05-04 04:57:00 +00002644 if (Summ.getArg(idx) == DoNothingByRef)
Ted Kremenek070a8252008-07-09 18:11:16 +00002645 continue;
2646
2647 // Invalidate the value of the variable passed by reference.
Ted Kremenek8c5633e2008-07-03 23:26:32 +00002648
2649 // FIXME: Either this logic should also be replicated in GRSimpleVals
2650 // or should be pulled into a separate "constraint engine."
Ted Kremenek070a8252008-07-09 18:11:16 +00002651
Ted Kremenek8c5633e2008-07-03 23:26:32 +00002652 // FIXME: We can have collisions on the conjured symbol if the
2653 // expression *I also creates conjured symbols. We probably want
2654 // to identify conjured symbols by an expression pair: the enclosing
2655 // expression (the context) and the expression itself. This should
Ted Kremenek070a8252008-07-09 18:11:16 +00002656 // disambiguate conjured symbols.
Ted Kremenek9e240492008-10-04 05:50:14 +00002657
Ted Kremenek993f1c72008-10-17 20:28:54 +00002658 const TypedRegion* R = dyn_cast<TypedRegion>(MR->getRegion());
Zhongxing Xuf82af1e2009-04-29 02:30:09 +00002659
Ted Kremenek42530512009-05-06 18:19:24 +00002660 if (R) {
2661 // Are we dealing with an ElementRegion? If the element type is
2662 // a basic integer type (e.g., char, int) and the underying region
Zhongxing Xu2e7c6782009-05-11 14:28:14 +00002663 // is a variable region then strip off the ElementRegion.
Ted Kremenek42530512009-05-06 18:19:24 +00002664 // FIXME: We really need to think about this for the general case
2665 // as sometimes we are reasoning about arrays and other times
2666 // about (char*), etc., is just a form of passing raw bytes.
2667 // e.g., void *p = alloca(); foo((char*)p);
2668 if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
2669 // Checking for 'integral type' is probably too promiscuous, but
2670 // we'll leave it in for now until we have a systematic way of
2671 // handling all of these cases. Eventually we need to come up
2672 // with an interface to StoreManager so that this logic can be
2673 // approriately delegated to the respective StoreManagers while
2674 // still allowing us to do checker-specific logic (e.g.,
2675 // invalidating reference counts), probably via callbacks.
2676 if (ER->getElementType()->isIntegralType())
Zhongxing Xu2e7c6782009-05-11 14:28:14 +00002677 if (const VarRegion *superReg =
2678 dyn_cast<VarRegion>(ER->getSuperRegion()))
Ted Kremenek42530512009-05-06 18:19:24 +00002679 R = superReg;
2680 // FIXME: What about layers of ElementRegions?
2681 }
2682
Ted Kremenek40e86d92008-12-18 23:34:57 +00002683 // Is the invalidated variable something that we were tracking?
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00002684 SymbolRef Sym = state.GetSValAsScalarOrLoc(R).getAsLocSymbol();
Ted Kremenek40e86d92008-12-18 23:34:57 +00002685
Ted Kremenekd104a092009-03-04 22:56:43 +00002686 // Remove any existing reference-count binding.
Ted Kremeneke0e4ebf2009-03-26 03:35:11 +00002687 if (Sym) state = state.remove<RefBindings>(Sym);
Ted Kremenek9e240492008-10-04 05:50:14 +00002688
Ted Kremenekd104a092009-03-04 22:56:43 +00002689 if (R->isBoundable(Ctx)) {
2690 // Set the value of the variable to be a conjured symbol.
2691 unsigned Count = Builder.getCurrentBlockCount();
Zhongxing Xua82d8aa2009-05-09 03:57:34 +00002692 QualType T = R->getValueType(Ctx);
Ted Kremenekd104a092009-03-04 22:56:43 +00002693
Zhongxing Xu51ae7902009-04-09 06:03:54 +00002694 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())){
Ted Kremenek8d7f5482009-04-09 22:22:44 +00002695 ValueManager &ValMgr = Eng.getValueManager();
2696 SVal V = ValMgr.getConjuredSymbolVal(*I, T, Count);
Zhongxing Xu51ae7902009-04-09 06:03:54 +00002697 state = state.BindLoc(Loc::MakeVal(R), V);
Ted Kremenekd104a092009-03-04 22:56:43 +00002698 }
2699 else if (const RecordType *RT = T->getAsStructureType()) {
2700 // Handle structs in a not so awesome way. Here we just
2701 // eagerly bind new symbols to the fields. In reality we
2702 // should have the store manager handle this. The idea is just
2703 // to prototype some basic functionality here. All of this logic
2704 // should one day soon just go away.
2705 const RecordDecl *RD = RT->getDecl()->getDefinition(Ctx);
2706
2707 // No record definition. There is nothing we can do.
2708 if (!RD)
2709 continue;
2710
2711 MemRegionManager &MRMgr = state.getManager().getRegionManager();
2712
2713 // Iterate through the fields and construct new symbols.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002714 for (RecordDecl::field_iterator FI=RD->field_begin(Ctx),
2715 FE=RD->field_end(Ctx); FI!=FE; ++FI) {
Ted Kremenekd104a092009-03-04 22:56:43 +00002716
2717 // For now just handle scalar fields.
2718 FieldDecl *FD = *FI;
2719 QualType FT = FD->getType();
2720
2721 if (Loc::IsLocType(FT) ||
Ted Kremenek8d7f5482009-04-09 22:22:44 +00002722 (FT->isIntegerType() && FT->isScalarType())) {
Ted Kremenekd104a092009-03-04 22:56:43 +00002723 const FieldRegion* FR = MRMgr.getFieldRegion(FD, R);
Ted Kremenek8d7f5482009-04-09 22:22:44 +00002724 ValueManager &ValMgr = Eng.getValueManager();
2725 SVal V = ValMgr.getConjuredSymbolVal(*I, FT, Count);
Zhongxing Xu6782f752009-04-09 06:32:20 +00002726 state = state.BindLoc(Loc::MakeVal(FR), V);
Ted Kremenekd104a092009-03-04 22:56:43 +00002727 }
2728 }
2729 }
2730 else {
2731 // Just blast away other values.
2732 state = state.BindLoc(*MR, UnknownVal());
2733 }
Ted Kremenekfd301942008-10-17 22:23:12 +00002734 }
Ted Kremenek9e240492008-10-04 05:50:14 +00002735 }
2736 else
Ted Kremeneka441b7e2008-11-12 19:22:09 +00002737 state = state.BindLoc(*MR, UnknownVal());
Ted Kremenek8c5633e2008-07-03 23:26:32 +00002738 }
2739 else {
2740 // Nuke all other arguments passed by reference.
Zhongxing Xu1c96b242008-10-17 05:57:07 +00002741 state = state.Unbind(cast<Loc>(V));
Ted Kremenek8c5633e2008-07-03 23:26:32 +00002742 }
Ted Kremenekb8873552008-04-11 20:51:02 +00002743 }
Zhongxing Xu1c96b242008-10-17 05:57:07 +00002744 else if (isa<nonloc::LocAsInteger>(V))
2745 state = state.Unbind(cast<nonloc::LocAsInteger>(V).getLoc());
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002746 }
Ted Kremenek9ed18e62008-04-16 04:28:53 +00002747
Ted Kremenek553cf182008-06-25 21:21:56 +00002748 // Evaluate the effect on the message receiver.
Ted Kremenek14993892008-05-06 02:41:27 +00002749 if (!ErrorExpr && Receiver) {
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00002750 SymbolRef Sym = state.GetSValAsScalarOrLoc(Receiver).getAsLocSymbol();
Ted Kremeneke0e4ebf2009-03-26 03:35:11 +00002751 if (Sym) {
Ted Kremenek4d3957d2009-02-24 19:15:11 +00002752 if (const RefVal* T = state.get<RefBindings>(Sym)) {
Ted Kremenek7faca822009-05-04 04:57:00 +00002753 state = Update(state, Sym, *T, Summ.getReceiverEffect(), hasErr);
Ted Kremenek4d3957d2009-02-24 19:15:11 +00002754 if (hasErr) {
Ted Kremenek14993892008-05-06 02:41:27 +00002755 ErrorExpr = Receiver;
Ted Kremeneke8fdc832008-07-07 16:21:19 +00002756 ErrorSym = Sym;
Ted Kremenek14993892008-05-06 02:41:27 +00002757 }
Ted Kremenek4d3957d2009-02-24 19:15:11 +00002758 }
Ted Kremenek14993892008-05-06 02:41:27 +00002759 }
2760 }
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002761
Ted Kremenek553cf182008-06-25 21:21:56 +00002762 // Process any errors.
Ted Kremenek9ed18e62008-04-16 04:28:53 +00002763 if (hasErr) {
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002764 ProcessNonLeakError(Dst, Builder, Ex, ErrorExpr, Pred, state,
Ted Kremenek8dd56462008-04-18 03:39:05 +00002765 hasErr, ErrorSym);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002766 return;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002767 }
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002768
Ted Kremenek70a733e2008-07-18 17:24:20 +00002769 // Consult the summary for the return value.
Ted Kremenek7faca822009-05-04 04:57:00 +00002770 RetEffect RE = Summ.getRetEffect();
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002771
2772 switch (RE.getKind()) {
2773 default:
2774 assert (false && "Unhandled RetEffect."); break;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002775
Ted Kremenekfd301942008-10-17 22:23:12 +00002776 case RetEffect::NoRet: {
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002777
Ted Kremenekf9561e52008-04-11 20:23:24 +00002778 // Make up a symbol for the return value (not reference counted).
Ted Kremenekb8873552008-04-11 20:51:02 +00002779 // FIXME: This is basically copy-and-paste from GRSimpleVals. We
2780 // should compose behavior, not copy it.
Ted Kremenekf9561e52008-04-11 20:23:24 +00002781
Ted Kremenekfd301942008-10-17 22:23:12 +00002782 // FIXME: We eventually should handle structs and other compound types
2783 // that are returned by value.
2784
2785 QualType T = Ex->getType();
2786
Ted Kremenek062e2f92008-11-13 06:10:40 +00002787 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())) {
Ted Kremenekf9561e52008-04-11 20:23:24 +00002788 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenek8d7f5482009-04-09 22:22:44 +00002789 ValueManager &ValMgr = Eng.getValueManager();
2790 SVal X = ValMgr.getConjuredSymbolVal(Ex, T, Count);
Ted Kremeneka441b7e2008-11-12 19:22:09 +00002791 state = state.BindExpr(Ex, X, false);
Ted Kremenekf9561e52008-04-11 20:23:24 +00002792 }
2793
Ted Kremenek940b1d82008-04-10 23:44:06 +00002794 break;
Ted Kremenekfd301942008-10-17 22:23:12 +00002795 }
Ted Kremenek940b1d82008-04-10 23:44:06 +00002796
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002797 case RetEffect::Alias: {
Ted Kremenek553cf182008-06-25 21:21:56 +00002798 unsigned idx = RE.getIndex();
Ted Kremenek55499762008-06-17 02:43:46 +00002799 assert (arg_end >= arg_beg);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002800 assert (idx < (unsigned) (arg_end - arg_beg));
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00002801 SVal V = state.GetSValAsScalarOrLoc(*(arg_beg+idx));
Ted Kremeneka441b7e2008-11-12 19:22:09 +00002802 state = state.BindExpr(Ex, V, false);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002803 break;
2804 }
2805
Ted Kremenek14993892008-05-06 02:41:27 +00002806 case RetEffect::ReceiverAlias: {
2807 assert (Receiver);
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00002808 SVal V = state.GetSValAsScalarOrLoc(Receiver);
Ted Kremeneka441b7e2008-11-12 19:22:09 +00002809 state = state.BindExpr(Ex, V, false);
Ted Kremenek14993892008-05-06 02:41:27 +00002810 break;
2811 }
2812
Ted Kremeneka7344702008-06-23 18:02:52 +00002813 case RetEffect::OwnedAllocatedSymbol:
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002814 case RetEffect::OwnedSymbol: {
2815 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenek044b6f02009-04-09 16:13:17 +00002816 ValueManager &ValMgr = Eng.getValueManager();
2817 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
2818 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
2819 state = state.set<RefBindings>(Sym, RefVal::makeOwned(RE.getObjKind(),
2820 RetT));
2821 state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenek25d01ba2009-03-09 22:46:49 +00002822
2823 // FIXME: Add a flag to the checker where allocations are assumed to
2824 // *not fail.
2825#if 0
Ted Kremenekb2bf7cd2009-01-28 22:27:59 +00002826 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) {
2827 bool isFeasible;
2828 state = state.Assume(loc::SymbolVal(Sym), true, isFeasible);
2829 assert(isFeasible && "Cannot assume fresh symbol is non-null.");
2830 }
Ted Kremenek25d01ba2009-03-09 22:46:49 +00002831#endif
Ted Kremeneka7344702008-06-23 18:02:52 +00002832
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002833 break;
2834 }
Ted Kremeneke798e7c2009-04-27 19:14:45 +00002835
2836 case RetEffect::GCNotOwnedSymbol:
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002837 case RetEffect::NotOwnedSymbol: {
2838 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenek044b6f02009-04-09 16:13:17 +00002839 ValueManager &ValMgr = Eng.getValueManager();
2840 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
2841 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
2842 state = state.set<RefBindings>(Sym, RefVal::makeNotOwned(RE.getObjKind(),
2843 RetT));
2844 state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002845 break;
2846 }
2847 }
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002848
Ted Kremenekf5b34b12009-02-18 02:00:25 +00002849 // Generate a sink node if we are at the end of a path.
2850 GRExprEngine::NodeTy *NewNode =
Ted Kremenek7faca822009-05-04 04:57:00 +00002851 Summ.isEndPath() ? Builder.MakeSinkNode(Dst, Ex, Pred, state)
2852 : Builder.MakeNode(Dst, Ex, Pred, state);
Ted Kremenekf5b34b12009-02-18 02:00:25 +00002853
2854 // Annotate the edge with summary we used.
Ted Kremenek7faca822009-05-04 04:57:00 +00002855 if (NewNode) SummaryLog[NewNode] = &Summ;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002856}
2857
2858
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002859void CFRefCount::EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002860 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002861 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu1c96b242008-10-17 05:57:07 +00002862 CallExpr* CE, SVal L,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002863 ExplodedNode<GRState>* Pred) {
Zhongxing Xu369f4472009-04-20 05:24:46 +00002864 const FunctionDecl* FD = L.getAsFunctionDecl();
Ted Kremenek7faca822009-05-04 04:57:00 +00002865 RetainSummary* Summ = !FD ? Summaries.getDefaultSummary()
Zhongxing Xu369f4472009-04-20 05:24:46 +00002866 : Summaries.getSummary(const_cast<FunctionDecl*>(FD));
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002867
Ted Kremenek7faca822009-05-04 04:57:00 +00002868 assert(Summ);
2869 EvalSummary(Dst, Eng, Builder, CE, 0, *Summ,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002870 CE->arg_begin(), CE->arg_end(), Pred);
Ted Kremenek2fff37e2008-03-06 00:08:09 +00002871}
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00002872
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002873void CFRefCount::EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek85348202008-04-15 23:44:31 +00002874 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002875 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek85348202008-04-15 23:44:31 +00002876 ObjCMessageExpr* ME,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002877 ExplodedNode<GRState>* Pred) {
Ted Kremenek7faca822009-05-04 04:57:00 +00002878 RetainSummary* Summ = 0;
Ted Kremenek9040c652008-05-01 21:31:50 +00002879
Ted Kremenek553cf182008-06-25 21:21:56 +00002880 if (Expr* Receiver = ME->getReceiver()) {
2881 // We need the type-information of the tracked receiver object
2882 // Retrieve it from the state.
2883 ObjCInterfaceDecl* ID = 0;
2884
2885 // FIXME: Wouldn't it be great if this code could be reduced? It's just
2886 // a chain of lookups.
Ted Kremenek8711c032009-04-29 05:04:30 +00002887 // FIXME: Is this really working as expected? There are cases where
2888 // we just use the 'ID' from the message expression.
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002889 const GRState* St = Builder.GetState(Pred);
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00002890 SVal V = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
Ted Kremenek553cf182008-06-25 21:21:56 +00002891
Ted Kremenek94c96982009-03-03 22:06:47 +00002892 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremeneke0e4ebf2009-03-26 03:35:11 +00002893 if (Sym) {
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002894 if (const RefVal* T = St->get<RefBindings>(Sym)) {
Ted Kremeneke8fdc832008-07-07 16:21:19 +00002895 QualType Ty = T->getType();
Ted Kremenek553cf182008-06-25 21:21:56 +00002896
2897 if (const PointerType* PT = Ty->getAsPointerType()) {
2898 QualType PointeeTy = PT->getPointeeType();
2899
2900 if (ObjCInterfaceType* IT = dyn_cast<ObjCInterfaceType>(PointeeTy))
2901 ID = IT->getDecl();
2902 }
2903 }
2904 }
2905
Ted Kremenekce8a41d2009-04-29 17:09:14 +00002906 // FIXME: The receiver could be a reference to a class, meaning that
2907 // we should use the class method.
2908 Summ = Summaries.getInstanceMethodSummary(ME, ID);
Ted Kremenekf9790ae2008-10-24 20:32:50 +00002909
Ted Kremenek896cd9d2008-10-23 01:56:15 +00002910 // Special-case: are we sending a mesage to "self"?
2911 // This is a hack. When we have full-IP this should be removed.
Ted Kremenek885c27b2009-05-04 05:31:22 +00002912 if (isa<ObjCMethodDecl>(&Eng.getGraph().getCodeDecl())) {
2913 if (Expr* Receiver = ME->getReceiver()) {
2914 SVal X = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
2915 if (loc::MemRegionVal* L = dyn_cast<loc::MemRegionVal>(&X))
2916 if (L->getRegion() == Eng.getStateManager().getSelfRegion(St)) {
2917 // Update the summary to make the default argument effect
2918 // 'StopTracking'.
2919 Summ = Summaries.copySummary(Summ);
2920 Summ->setDefaultArgEffect(StopTracking);
2921 }
Ted Kremenek896cd9d2008-10-23 01:56:15 +00002922 }
2923 }
Ted Kremenek553cf182008-06-25 21:21:56 +00002924 }
Ted Kremenek9ed18e62008-04-16 04:28:53 +00002925 else
Ted Kremenekf9df1362009-04-23 21:25:57 +00002926 Summ = Summaries.getClassMethodSummary(ME);
Ted Kremenek9ed18e62008-04-16 04:28:53 +00002927
Ted Kremenek7faca822009-05-04 04:57:00 +00002928 if (!Summ)
2929 Summ = Summaries.getDefaultSummary();
Ted Kremenekde4d5332009-04-24 17:50:11 +00002930
Ted Kremenek7faca822009-05-04 04:57:00 +00002931 EvalSummary(Dst, Eng, Builder, ME, ME->getReceiver(), *Summ,
Ted Kremenekb3095252008-05-06 04:20:12 +00002932 ME->arg_begin(), ME->arg_end(), Pred);
Ted Kremenek85348202008-04-15 23:44:31 +00002933}
Ted Kremenek5216ad72009-02-14 03:16:10 +00002934
2935namespace {
2936class VISIBILITY_HIDDEN StopTrackingCallback : public SymbolVisitor {
2937 GRStateRef state;
2938public:
2939 StopTrackingCallback(GRStateRef st) : state(st) {}
2940 GRStateRef getState() { return state; }
2941
2942 bool VisitSymbol(SymbolRef sym) {
2943 state = state.remove<RefBindings>(sym);
2944 return true;
2945 }
Ted Kremenekb3095252008-05-06 04:20:12 +00002946
Ted Kremenek5216ad72009-02-14 03:16:10 +00002947 const GRState* getState() const { return state.getState(); }
2948};
2949} // end anonymous namespace
2950
2951
Ted Kremenek41573eb2009-02-14 01:43:44 +00002952void CFRefCount::EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val) {
Ted Kremenek41573eb2009-02-14 01:43:44 +00002953 // Are we storing to something that causes the value to "escape"?
Ted Kremenek13922612008-04-16 20:40:59 +00002954 bool escapes = false;
2955
Ted Kremeneka496d162008-10-18 03:49:51 +00002956 // A value escapes in three possible cases (this may change):
2957 //
2958 // (1) we are binding to something that is not a memory region.
2959 // (2) we are binding to a memregion that does not have stack storage
2960 // (3) we are binding to a memregion with stack storage that the store
Ted Kremenek41573eb2009-02-14 01:43:44 +00002961 // does not understand.
Ted Kremenek41573eb2009-02-14 01:43:44 +00002962 GRStateRef state = B.getState();
Ted Kremeneka496d162008-10-18 03:49:51 +00002963
Ted Kremenek41573eb2009-02-14 01:43:44 +00002964 if (!isa<loc::MemRegionVal>(location))
Ted Kremenek13922612008-04-16 20:40:59 +00002965 escapes = true;
Ted Kremenek9e240492008-10-04 05:50:14 +00002966 else {
Ted Kremenek41573eb2009-02-14 01:43:44 +00002967 const MemRegion* R = cast<loc::MemRegionVal>(location).getRegion();
2968 escapes = !B.getStateManager().hasStackStorage(R);
Ted Kremeneka496d162008-10-18 03:49:51 +00002969
2970 if (!escapes) {
2971 // To test (3), generate a new state with the binding removed. If it is
2972 // the same state, then it escapes (since the store cannot represent
2973 // the binding).
Ted Kremenek41573eb2009-02-14 01:43:44 +00002974 escapes = (state == (state.BindLoc(cast<Loc>(location), UnknownVal())));
Ted Kremeneka496d162008-10-18 03:49:51 +00002975 }
Ted Kremenek9e240492008-10-04 05:50:14 +00002976 }
Ted Kremenek41573eb2009-02-14 01:43:44 +00002977
Ted Kremenek5216ad72009-02-14 03:16:10 +00002978 // If our store can represent the binding and we aren't storing to something
2979 // that doesn't have local storage then just return and have the simulation
2980 // state continue as is.
2981 if (!escapes)
2982 return;
Ted Kremeneka496d162008-10-18 03:49:51 +00002983
Ted Kremenek5216ad72009-02-14 03:16:10 +00002984 // Otherwise, find all symbols referenced by 'val' that we are tracking
2985 // and stop tracking them.
2986 B.MakeNode(state.scanReachableSymbols<StopTrackingCallback>(val).getState());
Ted Kremenekdb863712008-04-16 22:32:20 +00002987}
2988
Ted Kremenek652adc62008-04-24 23:57:27 +00002989
Ted Kremenek4fd88972008-04-17 18:12:53 +00002990 // Return statements.
2991
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002992void CFRefCount::EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4fd88972008-04-17 18:12:53 +00002993 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002994 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4fd88972008-04-17 18:12:53 +00002995 ReturnStmt* S,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002996 ExplodedNode<GRState>* Pred) {
Ted Kremenek4fd88972008-04-17 18:12:53 +00002997
2998 Expr* RetE = S->getRetValue();
Ted Kremenek94c96982009-03-03 22:06:47 +00002999 if (!RetE)
Ted Kremenek4fd88972008-04-17 18:12:53 +00003000 return;
3001
Ted Kremenek94c96982009-03-03 22:06:47 +00003002 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00003003 SymbolRef Sym = state.GetSValAsScalarOrLoc(RetE).getAsLocSymbol();
Ted Kremenek94c96982009-03-03 22:06:47 +00003004
Ted Kremeneke0e4ebf2009-03-26 03:35:11 +00003005 if (!Sym)
Ted Kremenek94c96982009-03-03 22:06:47 +00003006 return;
Ted Kremenekf04dced2009-05-08 23:32:51 +00003007
Ted Kremenek4fd88972008-04-17 18:12:53 +00003008 // Get the reference count binding (if any).
Ted Kremenek72cd17f2008-08-14 21:16:54 +00003009 const RefVal* T = state.get<RefBindings>(Sym);
Ted Kremenek4fd88972008-04-17 18:12:53 +00003010
3011 if (!T)
3012 return;
3013
Ted Kremenek72cd17f2008-08-14 21:16:54 +00003014 // Change the reference count.
Ted Kremeneke8fdc832008-07-07 16:21:19 +00003015 RefVal X = *T;
Ted Kremenek4fd88972008-04-17 18:12:53 +00003016
Ted Kremenek72cd17f2008-08-14 21:16:54 +00003017 switch (X.getKind()) {
Ted Kremenek4fd88972008-04-17 18:12:53 +00003018 case RefVal::Owned: {
3019 unsigned cnt = X.getCount();
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00003020 assert (cnt > 0);
Ted Kremenekeaedfea2009-05-10 05:11:21 +00003021 X.setCount(cnt - 1);
3022 X = X ^ RefVal::ReturnedOwned;
Ted Kremenek4fd88972008-04-17 18:12:53 +00003023 break;
3024 }
3025
3026 case RefVal::NotOwned: {
3027 unsigned cnt = X.getCount();
Ted Kremenekeaedfea2009-05-10 05:11:21 +00003028 if (cnt) {
3029 X.setCount(cnt - 1);
3030 X = X ^ RefVal::ReturnedOwned;
3031 }
3032 else {
3033 X = X ^ RefVal::ReturnedNotOwned;
3034 }
Ted Kremenek4fd88972008-04-17 18:12:53 +00003035 break;
3036 }
3037
3038 default:
Ted Kremenek4fd88972008-04-17 18:12:53 +00003039 return;
3040 }
3041
3042 // Update the binding.
Ted Kremenekb9d17f92008-08-17 03:20:02 +00003043 state = state.set<RefBindings>(Sym, X);
Ted Kremenekc887d132009-04-29 18:50:19 +00003044 Pred = Builder.MakeNode(Dst, S, Pred, state);
3045
Ted Kremenek9f246b62009-04-30 05:51:50 +00003046 // Did we cache out?
3047 if (!Pred)
3048 return;
Ted Kremenekeaedfea2009-05-10 05:11:21 +00003049
3050 // Update the autorelease counts.
3051 static unsigned autoreleasetag = 0;
3052 GenericNodeBuilder Bd(Builder, S, &autoreleasetag);
3053 bool stop = false;
3054 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state , Bd, Pred, Eng, Sym,
3055 X, stop);
3056
3057 // Did we cache out?
3058 if (!Pred || stop)
3059 return;
3060
3061 // Get the updated binding.
3062 T = state.get<RefBindings>(Sym);
3063 assert(T);
3064 X = *T;
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003065
Ted Kremenekc887d132009-04-29 18:50:19 +00003066 // Any leaks or other errors?
3067 if (X.isReturnedOwned() && X.getCount() == 0) {
Ted Kremeneke8720ce2009-05-10 06:25:57 +00003068 const Decl *CD = &Eng.getStateManager().getCodeDecl();
Ted Kremeneka8833552009-04-29 23:03:22 +00003069 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
Ted Kremenek7faca822009-05-04 04:57:00 +00003070 const RetainSummary &Summ = *Summaries.getMethodSummary(MD);
Ted Kremeneke8720ce2009-05-10 06:25:57 +00003071 RetEffect RE = Summ.getRetEffect();
3072 bool hasError = false;
3073
3074 if (isGCEnabled() && RE.getObjKind() == RetEffect::ObjC) {
3075 // Things are more complicated with garbage collection. If the
3076 // returned object is suppose to be an Objective-C object, we have
Ted Kremenek82f2be52009-05-10 16:52:15 +00003077 // a leak (as the caller expects a GC'ed object) because no
3078 // method should return ownership unless it returns a CF object.
Ted Kremeneke8720ce2009-05-10 06:25:57 +00003079 X = X ^ RefVal::ErrorGCLeakReturned;
3080
3081 // Keep this false until this is properly tested.
Ted Kremenek82f2be52009-05-10 16:52:15 +00003082 hasError = true;
Ted Kremeneke8720ce2009-05-10 06:25:57 +00003083 }
3084 else if (!RE.isOwned()) {
3085 // Either we are using GC and the returned object is a CF type
3086 // or we aren't using GC. In either case, we expect that the
3087 // enclosing method is expected to return ownership.
3088 hasError = true;
3089 X = X ^ RefVal::ErrorLeakReturned;
3090 }
3091
3092 if (hasError) {
Ted Kremenekc887d132009-04-29 18:50:19 +00003093 // Generate an error node.
Ted Kremeneke8720ce2009-05-10 06:25:57 +00003094 static int ReturnOwnLeakTag = 0;
3095 state = state.set<RefBindings>(Sym, X);
3096 ExplodedNode<GRState> *N =
3097 Builder.generateNode(PostStmt(S, &ReturnOwnLeakTag), state, Pred);
3098 if (N) {
3099 CFRefReport *report =
Ted Kremenek9f246b62009-04-30 05:51:50 +00003100 new CFRefLeakReport(*static_cast<CFRefBug*>(leakAtReturn), *this,
3101 N, Sym, Eng);
3102 BR->EmitReport(report);
3103 }
Ted Kremenekc887d132009-04-29 18:50:19 +00003104 }
Ted Kremeneke8720ce2009-05-10 06:25:57 +00003105 }
3106 }
3107 else if (X.isReturnedNotOwned()) {
3108 const Decl *CD = &Eng.getStateManager().getCodeDecl();
3109 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
3110 const RetainSummary &Summ = *Summaries.getMethodSummary(MD);
3111 if (Summ.getRetEffect().isOwned()) {
3112 // Trying to return a not owned object to a caller expecting an
3113 // owned object.
3114
3115 static int ReturnNotOwnedForOwnedTag = 0;
3116 state = state.set<RefBindings>(Sym, X ^ RefVal::ErrorReturnedNotOwned);
3117 if (ExplodedNode<GRState> *N =
3118 Builder.generateNode(PostStmt(S, &ReturnNotOwnedForOwnedTag),
3119 state, Pred)) {
3120 CFRefReport *report =
3121 new CFRefReport(*static_cast<CFRefBug*>(returnNotOwnedForOwned),
3122 *this, N, Sym);
3123 BR->EmitReport(report);
3124 }
3125 }
Ted Kremenekc887d132009-04-29 18:50:19 +00003126 }
3127 }
Ted Kremenek4fd88972008-04-17 18:12:53 +00003128}
3129
Ted Kremenekcb612922008-04-18 19:23:43 +00003130// Assumptions.
3131
Ted Kremenek4adc81e2008-08-13 04:27:00 +00003132const GRState* CFRefCount::EvalAssume(GRStateManager& VMgr,
3133 const GRState* St,
Zhongxing Xu1c96b242008-10-17 05:57:07 +00003134 SVal Cond, bool Assumption,
Ted Kremenek4323a572008-07-10 22:03:41 +00003135 bool& isFeasible) {
Ted Kremenekcb612922008-04-18 19:23:43 +00003136
3137 // FIXME: We may add to the interface of EvalAssume the list of symbols
3138 // whose assumptions have changed. For now we just iterate through the
3139 // bindings and check if any of the tracked symbols are NULL. This isn't
3140 // too bad since the number of symbols we will track in practice are
3141 // probably small and EvalAssume is only called at branches and a few
3142 // other places.
Ted Kremenek72cd17f2008-08-14 21:16:54 +00003143 RefBindings B = St->get<RefBindings>();
Ted Kremenekcb612922008-04-18 19:23:43 +00003144
3145 if (B.isEmpty())
3146 return St;
3147
3148 bool changed = false;
Ted Kremenekb9d17f92008-08-17 03:20:02 +00003149
3150 GRStateRef state(St, VMgr);
3151 RefBindings::Factory& RefBFactory = state.get_context<RefBindings>();
Ted Kremenekcb612922008-04-18 19:23:43 +00003152
3153 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
Ted Kremenekcb612922008-04-18 19:23:43 +00003154 // Check if the symbol is null (or equal to any constant).
3155 // If this is the case, stop tracking the symbol.
Zhongxing Xu39cfed32008-08-29 14:52:36 +00003156 if (VMgr.getSymVal(St, I.getKey())) {
Ted Kremenekcb612922008-04-18 19:23:43 +00003157 changed = true;
3158 B = RefBFactory.Remove(B, I.getKey());
3159 }
3160 }
3161
Ted Kremenekb9d17f92008-08-17 03:20:02 +00003162 if (changed)
3163 state = state.set<RefBindings>(B);
Ted Kremenekcb612922008-04-18 19:23:43 +00003164
Ted Kremenek72cd17f2008-08-14 21:16:54 +00003165 return state;
Ted Kremenekcb612922008-04-18 19:23:43 +00003166}
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00003167
Ted Kremenek4d3957d2009-02-24 19:15:11 +00003168GRStateRef CFRefCount::Update(GRStateRef state, SymbolRef sym,
3169 RefVal V, ArgEffect E,
3170 RefVal::Kind& hasErr) {
Ted Kremenek1c512f52009-02-18 18:54:33 +00003171
3172 // In GC mode [... release] and [... retain] do nothing.
3173 switch (E) {
3174 default: break;
3175 case IncRefMsg: E = isGCEnabled() ? DoNothing : IncRef; break;
3176 case DecRefMsg: E = isGCEnabled() ? DoNothing : DecRef; break;
Ted Kremenek27019002009-02-18 21:57:45 +00003177 case MakeCollectable: E = isGCEnabled() ? DecRef : DoNothing; break;
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00003178 case NewAutoreleasePool: E = isGCEnabled() ? DoNothing :
3179 NewAutoreleasePool; break;
Ted Kremenek1c512f52009-02-18 18:54:33 +00003180 }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00003181
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003182 // Handle all use-after-releases.
3183 if (!isGCEnabled() && V.getKind() == RefVal::Released) {
3184 V = V ^ RefVal::ErrorUseAfterRelease;
3185 hasErr = V.getKind();
3186 return state.set<RefBindings>(sym, V);
3187 }
3188
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003189 switch (E) {
3190 default:
3191 assert (false && "Unhandled CFRef transition.");
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003192
3193 case Dealloc:
3194 // Any use of -dealloc in GC is *bad*.
3195 if (isGCEnabled()) {
3196 V = V ^ RefVal::ErrorDeallocGC;
3197 hasErr = V.getKind();
3198 break;
3199 }
3200
3201 switch (V.getKind()) {
3202 default:
3203 assert(false && "Invalid case.");
3204 case RefVal::Owned:
3205 // The object immediately transitions to the released state.
3206 V = V ^ RefVal::Released;
3207 V.clearCounts();
3208 return state.set<RefBindings>(sym, V);
3209 case RefVal::NotOwned:
3210 V = V ^ RefVal::ErrorDeallocNotOwned;
3211 hasErr = V.getKind();
3212 break;
3213 }
3214 break;
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00003215
Ted Kremenek35790732009-02-25 23:11:49 +00003216 case NewAutoreleasePool:
3217 assert(!isGCEnabled());
3218 return state.add<AutoreleaseStack>(sym);
3219
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00003220 case MayEscape:
3221 if (V.getKind() == RefVal::Owned) {
Ted Kremenek553cf182008-06-25 21:21:56 +00003222 V = V ^ RefVal::NotOwned;
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00003223 break;
3224 }
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003225
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00003226 // Fall-through.
Ted Kremenek6c4becb2009-02-25 02:54:57 +00003227
Ted Kremenek070a8252008-07-09 18:11:16 +00003228 case DoNothingByRef:
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003229 case DoNothing:
Ted Kremenek4d3957d2009-02-24 19:15:11 +00003230 return state;
Ted Kremeneke19f4492008-06-30 16:57:41 +00003231
Ted Kremenekabf43972009-01-28 21:44:40 +00003232 case Autorelease:
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003233 if (isGCEnabled())
3234 return state;
Ted Kremenek7037ab82009-03-20 17:34:15 +00003235
3236 // Update the autorelease counts.
3237 state = SendAutorelease(state, ARCountFactory, sym);
Ted Kremenekf21332e2009-05-08 20:01:42 +00003238 V = V.autorelease();
Ted Kremenek6b62ec92009-05-09 01:50:57 +00003239 break;
Ted Kremenek369de562009-05-09 00:10:05 +00003240
Ted Kremenek14993892008-05-06 02:41:27 +00003241 case StopTracking:
Ted Kremenek4d3957d2009-02-24 19:15:11 +00003242 return state.remove<RefBindings>(sym);
Ted Kremenek9e476de2008-08-12 18:30:56 +00003243
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003244 case IncRef:
3245 switch (V.getKind()) {
3246 default:
3247 assert(false);
3248
3249 case RefVal::Owned:
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003250 case RefVal::NotOwned:
Ted Kremenek553cf182008-06-25 21:21:56 +00003251 V = V + 1;
Ted Kremenek9e476de2008-08-12 18:30:56 +00003252 break;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003253 case RefVal::Released:
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003254 // Non-GC cases are handled above.
3255 assert(isGCEnabled());
3256 V = (V ^ RefVal::Owned) + 1;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003257 break;
Ted Kremenek9e476de2008-08-12 18:30:56 +00003258 }
Ted Kremenek940b1d82008-04-10 23:44:06 +00003259 break;
3260
Ted Kremenek553cf182008-06-25 21:21:56 +00003261 case SelfOwn:
3262 V = V ^ RefVal::NotOwned;
Ted Kremenek1c512f52009-02-18 18:54:33 +00003263 // Fall-through.
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003264 case DecRef:
3265 switch (V.getKind()) {
3266 default:
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003267 // case 'RefVal::Released' handled above.
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003268 assert (false);
Ted Kremenek9e476de2008-08-12 18:30:56 +00003269
Ted Kremenek553cf182008-06-25 21:21:56 +00003270 case RefVal::Owned:
Ted Kremenekbb8c5aa2009-02-18 22:57:22 +00003271 assert(V.getCount() > 0);
3272 if (V.getCount() == 1) V = V ^ RefVal::Released;
3273 V = V - 1;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003274 break;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003275
Ted Kremenek553cf182008-06-25 21:21:56 +00003276 case RefVal::NotOwned:
3277 if (V.getCount() > 0)
3278 V = V - 1;
Ted Kremenek61b9f872008-04-10 23:09:18 +00003279 else {
Ted Kremenek553cf182008-06-25 21:21:56 +00003280 V = V ^ RefVal::ErrorReleaseNotOwned;
Ted Kremenek9ed18e62008-04-16 04:28:53 +00003281 hasErr = V.getKind();
Ted Kremenek9e476de2008-08-12 18:30:56 +00003282 }
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003283 break;
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003284
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003285 case RefVal::Released:
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003286 // Non-GC cases are handled above.
3287 assert(isGCEnabled());
Ted Kremenek553cf182008-06-25 21:21:56 +00003288 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek9ed18e62008-04-16 04:28:53 +00003289 hasErr = V.getKind();
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003290 break;
Ted Kremenek9e476de2008-08-12 18:30:56 +00003291 }
Ted Kremenek940b1d82008-04-10 23:44:06 +00003292 break;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003293 }
Ted Kremenek4d3957d2009-02-24 19:15:11 +00003294 return state.set<RefBindings>(sym, V);
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00003295}
3296
Ted Kremenekfa34b332008-04-09 01:10:13 +00003297//===----------------------------------------------------------------------===//
Ted Kremenekcf701772009-02-05 06:50:21 +00003298// Handle dead symbols and end-of-path.
3299//===----------------------------------------------------------------------===//
3300
Ted Kremenekf04dced2009-05-08 23:32:51 +00003301std::pair<ExplodedNode<GRState>*, GRStateRef>
3302CFRefCount::HandleAutoreleaseCounts(GRStateRef state, GenericNodeBuilder Bd,
3303 ExplodedNode<GRState>* Pred,
Ted Kremenek369de562009-05-09 00:10:05 +00003304 GRExprEngine &Eng,
3305 SymbolRef Sym, RefVal V, bool &stop) {
Ted Kremenekf04dced2009-05-08 23:32:51 +00003306
Ted Kremenek369de562009-05-09 00:10:05 +00003307 unsigned ACnt = V.getAutoreleaseCount();
3308 stop = false;
3309
3310 // No autorelease counts? Nothing to be done.
3311 if (!ACnt)
3312 return std::make_pair(Pred, state);
3313
3314 assert(!isGCEnabled() && "Autorelease counts in GC mode?");
3315 unsigned Cnt = V.getCount();
3316
Ted Kremenek95d3b902009-05-11 15:26:06 +00003317 // FIXME: Handle sending 'autorelease' to already released object.
3318
3319 if (V.getKind() == RefVal::ReturnedOwned)
3320 ++Cnt;
3321
Ted Kremenek369de562009-05-09 00:10:05 +00003322 if (ACnt <= Cnt) {
Ted Kremenek80c24182009-05-09 00:44:07 +00003323 if (ACnt == Cnt) {
3324 V.clearCounts();
Ted Kremenek95d3b902009-05-11 15:26:06 +00003325 if (V.getKind() == RefVal::ReturnedOwned)
3326 V = V ^ RefVal::ReturnedNotOwned;
3327 else
3328 V = V ^ RefVal::NotOwned;
Ted Kremenek80c24182009-05-09 00:44:07 +00003329 }
Ted Kremenek95d3b902009-05-11 15:26:06 +00003330 else {
Ted Kremenek80c24182009-05-09 00:44:07 +00003331 V.setCount(Cnt - ACnt);
3332 V.setAutoreleaseCount(0);
3333 }
Ted Kremenek369de562009-05-09 00:10:05 +00003334 state = state.set<RefBindings>(Sym, V);
3335 ExplodedNode<GRState> *N = Bd.MakeNode(state, Pred);
3336 stop = (N == 0);
3337 return std::make_pair(N, state);
3338 }
3339
3340 // Woah! More autorelease counts then retain counts left.
3341 // Emit hard error.
3342 stop = true;
3343 V = V ^ RefVal::ErrorOverAutorelease;
3344 state = state.set<RefBindings>(Sym, V);
3345
3346 if (ExplodedNode<GRState> *N = Bd.MakeNode(state, Pred)) {
Ted Kremenek80c24182009-05-09 00:44:07 +00003347 N->markAsSink();
Ted Kremenekeaedfea2009-05-10 05:11:21 +00003348
3349 std::string sbuf;
3350 llvm::raw_string_ostream os(sbuf);
3351 os << "Object over-autoreleased: object was sent -autorelease " ;
3352 if (V.getAutoreleaseCount() > 1)
3353 os << V.getAutoreleaseCount() << " times";
3354 os << " but the object has ";
3355 if (V.getCount() == 0)
3356 os << "zero (locally visible)";
3357 else
3358 os << "+" << V.getCount();
3359 os << " retain counts";
3360
Ted Kremenek369de562009-05-09 00:10:05 +00003361 CFRefReport *report =
3362 new CFRefReport(*static_cast<CFRefBug*>(overAutorelease),
Ted Kremenekeaedfea2009-05-10 05:11:21 +00003363 *this, N, Sym, os.str().c_str());
Ted Kremenek369de562009-05-09 00:10:05 +00003364 BR->EmitReport(report);
3365 }
3366
3367 return std::make_pair((ExplodedNode<GRState>*)0, state);
Ted Kremenekf04dced2009-05-08 23:32:51 +00003368}
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003369
3370GRStateRef
3371CFRefCount::HandleSymbolDeath(GRStateRef state, SymbolRef sid, RefVal V,
3372 llvm::SmallVectorImpl<SymbolRef> &Leaked) {
3373
3374 bool hasLeak = V.isOwned() ||
3375 ((V.isNotOwned() || V.isReturnedOwned()) && V.getCount() > 0);
3376
3377 if (!hasLeak)
3378 return state.remove<RefBindings>(sid);
3379
3380 Leaked.push_back(sid);
3381 return state.set<RefBindings>(sid, V ^ RefVal::ErrorLeak);
3382}
3383
3384ExplodedNode<GRState>*
3385CFRefCount::ProcessLeaks(GRStateRef state,
3386 llvm::SmallVectorImpl<SymbolRef> &Leaked,
3387 GenericNodeBuilder &Builder,
3388 GRExprEngine& Eng,
3389 ExplodedNode<GRState> *Pred) {
3390
3391 if (Leaked.empty())
3392 return Pred;
3393
Ted Kremenekf04dced2009-05-08 23:32:51 +00003394 // Generate an intermediate node representing the leak point.
Ted Kremenek6b62ec92009-05-09 01:50:57 +00003395 ExplodedNode<GRState> *N = Builder.MakeNode(state, Pred);
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003396
3397 if (N) {
3398 for (llvm::SmallVectorImpl<SymbolRef>::iterator
3399 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3400
3401 CFRefBug *BT = static_cast<CFRefBug*>(Pred ? leakWithinFunction
3402 : leakAtReturn);
3403 assert(BT && "BugType not initialized.");
3404 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N, *I, Eng);
3405 BR->EmitReport(report);
3406 }
3407 }
3408
3409 return N;
3410}
3411
Ted Kremenekcf701772009-02-05 06:50:21 +00003412void CFRefCount::EvalEndPath(GRExprEngine& Eng,
3413 GREndPathNodeBuilder<GRState>& Builder) {
3414
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003415 GRStateRef state(Builder.getState(), Eng.getStateManager());
Ted Kremenekf04dced2009-05-08 23:32:51 +00003416 GenericNodeBuilder Bd(Builder);
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003417 RefBindings B = state.get<RefBindings>();
Ted Kremenekf04dced2009-05-08 23:32:51 +00003418 ExplodedNode<GRState> *Pred = 0;
3419
3420 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Ted Kremenek369de562009-05-09 00:10:05 +00003421 bool stop = false;
3422 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state, Bd, Pred, Eng,
3423 (*I).first,
3424 (*I).second, stop);
3425
3426 if (stop)
3427 return;
Ted Kremenekf04dced2009-05-08 23:32:51 +00003428 }
3429
3430 B = state.get<RefBindings>();
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003431 llvm::SmallVector<SymbolRef, 10> Leaked;
Ted Kremenekcf701772009-02-05 06:50:21 +00003432
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003433 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I)
3434 state = HandleSymbolDeath(state, (*I).first, (*I).second, Leaked);
3435
Ted Kremenekf04dced2009-05-08 23:32:51 +00003436 ProcessLeaks(state, Leaked, Bd, Eng, Pred);
Ted Kremenekcf701772009-02-05 06:50:21 +00003437}
3438
3439void CFRefCount::EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
3440 GRExprEngine& Eng,
3441 GRStmtNodeBuilder<GRState>& Builder,
3442 ExplodedNode<GRState>* Pred,
3443 Stmt* S,
3444 const GRState* St,
3445 SymbolReaper& SymReaper) {
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003446
3447 GRStateRef state(St, Eng.getStateManager());
Ted Kremenekf04dced2009-05-08 23:32:51 +00003448 RefBindings B = state.get<RefBindings>();
3449
3450 // Update counts from autorelease pools
3451 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3452 E = SymReaper.dead_end(); I != E; ++I) {
3453 SymbolRef Sym = *I;
3454 if (const RefVal* T = B.lookup(Sym)){
3455 // Use the symbol as the tag.
3456 // FIXME: This might not be as unique as we would like.
3457 GenericNodeBuilder Bd(Builder, S, Sym);
Ted Kremenek369de562009-05-09 00:10:05 +00003458 bool stop = false;
3459 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state, Bd, Pred, Eng,
3460 Sym, *T, stop);
3461 if (stop)
3462 return;
Ted Kremenekf04dced2009-05-08 23:32:51 +00003463 }
3464 }
3465
3466 B = state.get<RefBindings>();
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003467 llvm::SmallVector<SymbolRef, 10> Leaked;
Ted Kremenekcf701772009-02-05 06:50:21 +00003468
3469 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003470 E = SymReaper.dead_end(); I != E; ++I) {
3471 if (const RefVal* T = B.lookup(*I))
3472 state = HandleSymbolDeath(state, *I, *T, Leaked);
3473 }
Ted Kremenekcf701772009-02-05 06:50:21 +00003474
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003475 static unsigned LeakPPTag = 0;
Ted Kremenekf04dced2009-05-08 23:32:51 +00003476 {
3477 GenericNodeBuilder Bd(Builder, S, &LeakPPTag);
3478 Pred = ProcessLeaks(state, Leaked, Bd, Eng, Pred);
3479 }
Ted Kremenekcf701772009-02-05 06:50:21 +00003480
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003481 // Did we cache out?
3482 if (!Pred)
3483 return;
Ted Kremenek33b6f632009-02-19 23:47:02 +00003484
3485 // Now generate a new node that nukes the old bindings.
Ted Kremenek33b6f632009-02-19 23:47:02 +00003486 RefBindings::Factory& F = state.get_context<RefBindings>();
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003487
Ted Kremenek33b6f632009-02-19 23:47:02 +00003488 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003489 E = SymReaper.dead_end(); I!=E; ++I) B = F.Remove(B, *I);
3490
Ted Kremenek33b6f632009-02-19 23:47:02 +00003491 state = state.set<RefBindings>(B);
3492 Builder.MakeNode(Dst, S, Pred, state);
Ted Kremenekcf701772009-02-05 06:50:21 +00003493}
3494
3495void CFRefCount::ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
3496 GRStmtNodeBuilder<GRState>& Builder,
3497 Expr* NodeExpr, Expr* ErrorExpr,
3498 ExplodedNode<GRState>* Pred,
3499 const GRState* St,
3500 RefVal::Kind hasErr, SymbolRef Sym) {
3501 Builder.BuildSinks = true;
3502 GRExprEngine::NodeTy* N = Builder.MakeNode(Dst, NodeExpr, Pred, St);
3503
Ted Kremenek6b62ec92009-05-09 01:50:57 +00003504 if (!N)
3505 return;
Ted Kremenekcf701772009-02-05 06:50:21 +00003506
3507 CFRefBug *BT = 0;
3508
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003509 switch (hasErr) {
3510 default:
3511 assert(false && "Unhandled error.");
3512 return;
3513 case RefVal::ErrorUseAfterRelease:
3514 BT = static_cast<CFRefBug*>(useAfterRelease);
3515 break;
3516 case RefVal::ErrorReleaseNotOwned:
3517 BT = static_cast<CFRefBug*>(releaseNotOwned);
3518 break;
3519 case RefVal::ErrorDeallocGC:
3520 BT = static_cast<CFRefBug*>(deallocGC);
3521 break;
3522 case RefVal::ErrorDeallocNotOwned:
3523 BT = static_cast<CFRefBug*>(deallocNotOwned);
3524 break;
Ted Kremenekcf701772009-02-05 06:50:21 +00003525 }
3526
Ted Kremenekfe9e5432009-02-18 03:48:14 +00003527 CFRefReport *report = new CFRefReport(*BT, *this, N, Sym);
Ted Kremenekcf701772009-02-05 06:50:21 +00003528 report->addRange(ErrorExpr->getSourceRange());
3529 BR->EmitReport(report);
3530}
3531
3532//===----------------------------------------------------------------------===//
Ted Kremenekd71ed262008-04-10 22:16:52 +00003533// Transfer function creation for external clients.
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00003534//===----------------------------------------------------------------------===//
3535
Ted Kremenek072192b2008-04-30 23:47:44 +00003536GRTransferFuncs* clang::MakeCFRefCountTF(ASTContext& Ctx, bool GCEnabled,
3537 const LangOptions& lopts) {
Ted Kremenek78d46242008-07-22 16:21:24 +00003538 return new CFRefCount(Ctx, GCEnabled, lopts);
Ted Kremenek3ea0b6a2008-04-10 22:58:08 +00003539}