blob: f0eb55d5fb57bec19f72e45a6c7ea29ee4fdd1a9 [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)
178 return SNB->generateNode(PostStmt(S, tag), state,
179 Pred);
180
181 assert(ENB);
182 return ENB->MakeNode(state, Pred);
183 }
184};
185} // end anonymous namespace
186
Ted Kremenek05cbe1a2008-04-09 23:49:11 +0000187//===----------------------------------------------------------------------===//
Ted Kremenek553cf182008-06-25 21:21:56 +0000188// Selector creation functions.
Ted Kremenek4fd88972008-04-17 18:12:53 +0000189//===----------------------------------------------------------------------===//
190
Ted Kremenekb83e02e2008-05-01 18:31:44 +0000191static inline Selector GetNullarySelector(const char* name, ASTContext& Ctx) {
Ted Kremenek4fd88972008-04-17 18:12:53 +0000192 IdentifierInfo* II = &Ctx.Idents.get(name);
193 return Ctx.Selectors.getSelector(0, &II);
194}
195
Ted Kremenek9c32d082008-05-06 00:30:21 +0000196static inline Selector GetUnarySelector(const char* name, ASTContext& Ctx) {
197 IdentifierInfo* II = &Ctx.Idents.get(name);
198 return Ctx.Selectors.getSelector(1, &II);
199}
200
Ted Kremenek553cf182008-06-25 21:21:56 +0000201//===----------------------------------------------------------------------===//
202// Type querying functions.
203//===----------------------------------------------------------------------===//
204
Ted Kremenek12619382009-01-12 21:45:02 +0000205static bool hasPrefix(const char* s, const char* prefix) {
206 if (!prefix)
207 return true;
Ted Kremenek0fcbf8e2008-05-07 20:06:41 +0000208
Ted Kremenek12619382009-01-12 21:45:02 +0000209 char c = *s;
210 char cP = *prefix;
Ted Kremenek0fcbf8e2008-05-07 20:06:41 +0000211
Ted Kremenek12619382009-01-12 21:45:02 +0000212 while (c != '\0' && cP != '\0') {
213 if (c != cP) break;
214 c = *(++s);
215 cP = *(++prefix);
216 }
Ted Kremenek0fcbf8e2008-05-07 20:06:41 +0000217
Ted Kremenek12619382009-01-12 21:45:02 +0000218 return cP == '\0';
Ted Kremenek0fcbf8e2008-05-07 20:06:41 +0000219}
220
Ted Kremenek12619382009-01-12 21:45:02 +0000221static bool hasSuffix(const char* s, const char* suffix) {
222 const char* loc = strstr(s, suffix);
223 return loc && strcmp(suffix, loc) == 0;
224}
225
226static bool isRefType(QualType RetTy, const char* prefix,
227 ASTContext* Ctx = 0, const char* name = 0) {
Ted Kremenek37d785b2008-07-15 16:50:12 +0000228
Ted Kremenek12619382009-01-12 21:45:02 +0000229 if (TypedefType* TD = dyn_cast<TypedefType>(RetTy.getTypePtr())) {
230 const char* TDName = TD->getDecl()->getIdentifier()->getName();
231 return hasPrefix(TDName, prefix) && hasSuffix(TDName, "Ref");
232 }
233
234 if (!Ctx || !name)
Ted Kremenek37d785b2008-07-15 16:50:12 +0000235 return false;
Ted Kremenek12619382009-01-12 21:45:02 +0000236
237 // Is the type void*?
238 const PointerType* PT = RetTy->getAsPointerType();
239 if (!(PT->getPointeeType().getUnqualifiedType() == Ctx->VoidTy))
Ted Kremenek37d785b2008-07-15 16:50:12 +0000240 return false;
Ted Kremenek12619382009-01-12 21:45:02 +0000241
242 // Does the name start with the prefix?
243 return hasPrefix(name, prefix);
Ted Kremenek37d785b2008-07-15 16:50:12 +0000244}
245
Ted Kremenek4fd88972008-04-17 18:12:53 +0000246//===----------------------------------------------------------------------===//
Ted Kremenek553cf182008-06-25 21:21:56 +0000247// Primitives used for constructing summaries for function/method calls.
Ted Kremenek05cbe1a2008-04-09 23:49:11 +0000248//===----------------------------------------------------------------------===//
249
Ted Kremenek553cf182008-06-25 21:21:56 +0000250/// ArgEffect is used to summarize a function/method call's effect on a
251/// particular argument.
Ted Kremenekf95e9fc2009-03-17 19:42:23 +0000252enum ArgEffect { Autorelease, Dealloc, DecRef, DecRefMsg, DoNothing,
253 DoNothingByRef, IncRefMsg, IncRef, MakeCollectable, MayEscape,
254 NewAutoreleasePool, SelfOwn, StopTracking };
Ted Kremenek553cf182008-06-25 21:21:56 +0000255
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000256namespace llvm {
Ted Kremenekb77449c2009-05-03 05:20:50 +0000257template <> struct FoldingSetTrait<ArgEffect> {
258static inline void Profile(const ArgEffect X, FoldingSetNodeID& ID) {
259 ID.AddInteger((unsigned) X);
260}
Ted Kremenek553cf182008-06-25 21:21:56 +0000261};
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000262} // end llvm namespace
263
Ted Kremenekb77449c2009-05-03 05:20:50 +0000264/// ArgEffects summarizes the effects of a function/method call on all of
265/// its arguments.
266typedef llvm::ImmutableMap<unsigned,ArgEffect> ArgEffects;
267
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000268namespace {
Ted Kremenek553cf182008-06-25 21:21:56 +0000269
270/// RetEffect is used to summarize a function/method call's behavior with
271/// respect to its return value.
272class VISIBILITY_HIDDEN RetEffect {
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000273public:
Ted Kremeneka7344702008-06-23 18:02:52 +0000274 enum Kind { NoRet, Alias, OwnedSymbol, OwnedAllocatedSymbol,
Ted Kremeneke798e7c2009-04-27 19:14:45 +0000275 NotOwnedSymbol, GCNotOwnedSymbol, ReceiverAlias };
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000276
277 enum ObjKind { CF, ObjC, AnyObj };
278
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000279private:
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000280 Kind K;
281 ObjKind O;
282 unsigned index;
283
284 RetEffect(Kind k, unsigned idx = 0) : K(k), O(AnyObj), index(idx) {}
285 RetEffect(Kind k, ObjKind o) : K(k), O(o), index(0) {}
Ted Kremenek2fff37e2008-03-06 00:08:09 +0000286
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000287public:
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000288 Kind getKind() const { return K; }
289
290 ObjKind getObjKind() const { return O; }
Ted Kremenek553cf182008-06-25 21:21:56 +0000291
292 unsigned getIndex() const {
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000293 assert(getKind() == Alias);
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000294 return index;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000295 }
Ted Kremenek2fff37e2008-03-06 00:08:09 +0000296
Ted Kremeneka8833552009-04-29 23:03:22 +0000297 bool isOwned() const {
298 return K == OwnedSymbol || K == OwnedAllocatedSymbol;
299 }
300
Ted Kremenek553cf182008-06-25 21:21:56 +0000301 static RetEffect MakeAlias(unsigned Idx) {
302 return RetEffect(Alias, Idx);
303 }
304 static RetEffect MakeReceiverAlias() {
305 return RetEffect(ReceiverAlias);
306 }
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000307 static RetEffect MakeOwned(ObjKind o, bool isAllocated = false) {
308 return RetEffect(isAllocated ? OwnedAllocatedSymbol : OwnedSymbol, o);
Ted Kremenek553cf182008-06-25 21:21:56 +0000309 }
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000310 static RetEffect MakeNotOwned(ObjKind o) {
311 return RetEffect(NotOwnedSymbol, o);
Ted Kremeneke798e7c2009-04-27 19:14:45 +0000312 }
313 static RetEffect MakeGCNotOwned() {
314 return RetEffect(GCNotOwnedSymbol, ObjC);
315 }
316
Ted Kremenek553cf182008-06-25 21:21:56 +0000317 static RetEffect MakeNoRet() {
318 return RetEffect(NoRet);
Ted Kremeneka7344702008-06-23 18:02:52 +0000319 }
Ted Kremenek2fff37e2008-03-06 00:08:09 +0000320
Ted Kremenek553cf182008-06-25 21:21:56 +0000321 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000322 ID.AddInteger((unsigned)K);
323 ID.AddInteger((unsigned)O);
324 ID.AddInteger(index);
Ted Kremenek553cf182008-06-25 21:21:56 +0000325 }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000326};
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000327
Ted Kremenek553cf182008-06-25 21:21:56 +0000328
Ted Kremenek885c27b2009-05-04 05:31:22 +0000329class VISIBILITY_HIDDEN RetainSummary {
Ted Kremenek1bffd742008-05-06 15:44:25 +0000330 /// Args - an ordered vector of (index, ArgEffect) pairs, where index
331 /// specifies the argument (starting from 0). This can be sparsely
332 /// populated; arguments with no entry in Args use 'DefaultArgEffect'.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000333 ArgEffects Args;
Ted Kremenek1bffd742008-05-06 15:44:25 +0000334
335 /// DefaultArgEffect - The default ArgEffect to apply to arguments that
336 /// do not have an entry in Args.
337 ArgEffect DefaultArgEffect;
338
Ted Kremenek553cf182008-06-25 21:21:56 +0000339 /// Receiver - If this summary applies to an Objective-C message expression,
340 /// this is the effect applied to the state of the receiver.
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000341 ArgEffect Receiver;
Ted Kremenek553cf182008-06-25 21:21:56 +0000342
343 /// Ret - The effect on the return value. Used to indicate if the
344 /// function/method call returns a new tracked symbol, returns an
345 /// alias of one of the arguments in the call, and so on.
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000346 RetEffect Ret;
Ted Kremenek553cf182008-06-25 21:21:56 +0000347
Ted Kremenek70a733e2008-07-18 17:24:20 +0000348 /// EndPath - Indicates that execution of this method/function should
349 /// terminate the simulation of a path.
350 bool EndPath;
351
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000352public:
Ted Kremenekb77449c2009-05-03 05:20:50 +0000353 RetainSummary(ArgEffects A, RetEffect R, ArgEffect defaultEff,
Ted Kremenek70a733e2008-07-18 17:24:20 +0000354 ArgEffect ReceiverEff, bool endpath = false)
355 : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R),
356 EndPath(endpath) {}
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000357
Ted Kremenek553cf182008-06-25 21:21:56 +0000358 /// getArg - Return the argument effect on the argument specified by
359 /// idx (starting from 0).
Ted Kremenek1ac08d62008-03-11 17:48:22 +0000360 ArgEffect getArg(unsigned idx) const {
Ted Kremenekb77449c2009-05-03 05:20:50 +0000361 if (const ArgEffect *AE = Args.lookup(idx))
362 return *AE;
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000363
Ted Kremenek1bffd742008-05-06 15:44:25 +0000364 return DefaultArgEffect;
Ted Kremenek1ac08d62008-03-11 17:48:22 +0000365 }
366
Ted Kremenek885c27b2009-05-04 05:31:22 +0000367 /// setDefaultArgEffect - Set the default argument effect.
368 void setDefaultArgEffect(ArgEffect E) {
369 DefaultArgEffect = E;
370 }
371
372 /// setArg - Set the argument effect on the argument specified by idx.
373 void setArgEffect(ArgEffects::Factory& AF, unsigned idx, ArgEffect E) {
374 Args = AF.Add(Args, idx, E);
375 }
376
Ted Kremenek553cf182008-06-25 21:21:56 +0000377 /// getRetEffect - Returns the effect on the return value of the call.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000378 RetEffect getRetEffect() const { return Ret; }
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000379
Ted Kremenek885c27b2009-05-04 05:31:22 +0000380 /// setRetEffect - Set the effect of the return value of the call.
381 void setRetEffect(RetEffect E) { Ret = E; }
382
Ted Kremenek70a733e2008-07-18 17:24:20 +0000383 /// isEndPath - Returns true if executing the given method/function should
384 /// terminate the path.
385 bool isEndPath() const { return EndPath; }
386
Ted Kremenek553cf182008-06-25 21:21:56 +0000387 /// getReceiverEffect - Returns the effect on the receiver of the call.
388 /// This is only meaningful if the summary applies to an ObjCMessageExpr*.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000389 ArgEffect getReceiverEffect() const { return Receiver; }
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000390
Ted Kremenek885c27b2009-05-04 05:31:22 +0000391 /// setReceiverEffect - Set the effect on the receiver of the call.
392 void setReceiverEffect(ArgEffect E) { Receiver = E; }
393
Ted Kremenekb77449c2009-05-03 05:20:50 +0000394 typedef ArgEffects::iterator ExprIterator;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000395
Ted Kremenekb77449c2009-05-03 05:20:50 +0000396 ExprIterator begin_args() const { return Args.begin(); }
397 ExprIterator end_args() const { return Args.end(); }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000398
Ted Kremenekb77449c2009-05-03 05:20:50 +0000399 static void Profile(llvm::FoldingSetNodeID& ID, ArgEffects A,
Ted Kremenek1bffd742008-05-06 15:44:25 +0000400 RetEffect RetEff, ArgEffect DefaultEff,
Ted Kremenek2d1086c2008-07-18 17:39:56 +0000401 ArgEffect ReceiverEff, bool EndPath) {
Ted Kremenekb77449c2009-05-03 05:20:50 +0000402 ID.Add(A);
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000403 ID.Add(RetEff);
Ted Kremenek1bffd742008-05-06 15:44:25 +0000404 ID.AddInteger((unsigned) DefaultEff);
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000405 ID.AddInteger((unsigned) ReceiverEff);
Ted Kremenek2d1086c2008-07-18 17:39:56 +0000406 ID.AddInteger((unsigned) EndPath);
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000407 }
408
409 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek2d1086c2008-07-18 17:39:56 +0000410 Profile(ID, Args, Ret, DefaultArgEffect, Receiver, EndPath);
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000411 }
412};
Ted Kremenek4f22a782008-06-23 23:30:29 +0000413} // end anonymous namespace
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000414
Ted Kremenek553cf182008-06-25 21:21:56 +0000415//===----------------------------------------------------------------------===//
416// Data structures for constructing summaries.
417//===----------------------------------------------------------------------===//
Ted Kremenek53301ba2008-06-24 03:49:48 +0000418
Ted Kremenek553cf182008-06-25 21:21:56 +0000419namespace {
420class VISIBILITY_HIDDEN ObjCSummaryKey {
421 IdentifierInfo* II;
422 Selector S;
423public:
424 ObjCSummaryKey(IdentifierInfo* ii, Selector s)
425 : II(ii), S(s) {}
426
Ted Kremeneka8833552009-04-29 23:03:22 +0000427 ObjCSummaryKey(const ObjCInterfaceDecl* d, Selector s)
Ted Kremenek553cf182008-06-25 21:21:56 +0000428 : II(d ? d->getIdentifier() : 0), S(s) {}
429
430 ObjCSummaryKey(Selector s)
431 : II(0), S(s) {}
432
433 IdentifierInfo* getIdentifier() const { return II; }
434 Selector getSelector() const { return S; }
435};
Ted Kremenek4f22a782008-06-23 23:30:29 +0000436}
437
438namespace llvm {
Ted Kremenek553cf182008-06-25 21:21:56 +0000439template <> struct DenseMapInfo<ObjCSummaryKey> {
440 static inline ObjCSummaryKey getEmptyKey() {
441 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
442 DenseMapInfo<Selector>::getEmptyKey());
443 }
Ted Kremenek4f22a782008-06-23 23:30:29 +0000444
Ted Kremenek553cf182008-06-25 21:21:56 +0000445 static inline ObjCSummaryKey getTombstoneKey() {
446 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
447 DenseMapInfo<Selector>::getTombstoneKey());
448 }
449
450 static unsigned getHashValue(const ObjCSummaryKey &V) {
451 return (DenseMapInfo<IdentifierInfo*>::getHashValue(V.getIdentifier())
452 & 0x88888888)
453 | (DenseMapInfo<Selector>::getHashValue(V.getSelector())
454 & 0x55555555);
455 }
456
457 static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
458 return DenseMapInfo<IdentifierInfo*>::isEqual(LHS.getIdentifier(),
459 RHS.getIdentifier()) &&
460 DenseMapInfo<Selector>::isEqual(LHS.getSelector(),
461 RHS.getSelector());
462 }
463
464 static bool isPod() {
465 return DenseMapInfo<ObjCInterfaceDecl*>::isPod() &&
466 DenseMapInfo<Selector>::isPod();
467 }
468};
Ted Kremenek4f22a782008-06-23 23:30:29 +0000469} // end llvm namespace
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000470
Ted Kremenek4f22a782008-06-23 23:30:29 +0000471namespace {
Ted Kremenek553cf182008-06-25 21:21:56 +0000472class VISIBILITY_HIDDEN ObjCSummaryCache {
473 typedef llvm::DenseMap<ObjCSummaryKey, RetainSummary*> MapTy;
474 MapTy M;
475public:
476 ObjCSummaryCache() {}
477
478 typedef MapTy::iterator iterator;
479
Ted Kremeneka8833552009-04-29 23:03:22 +0000480 iterator find(const ObjCInterfaceDecl* D, IdentifierInfo *ClsName,
481 Selector S) {
Ted Kremenek8711c032009-04-29 05:04:30 +0000482 // Lookup the method using the decl for the class @interface. If we
483 // have no decl, lookup using the class name.
484 return D ? find(D, S) : find(ClsName, S);
485 }
486
Ted Kremeneka8833552009-04-29 23:03:22 +0000487 iterator find(const ObjCInterfaceDecl* D, Selector S) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000488 // Do a lookup with the (D,S) pair. If we find a match return
489 // the iterator.
490 ObjCSummaryKey K(D, S);
491 MapTy::iterator I = M.find(K);
492
493 if (I != M.end() || !D)
494 return I;
495
496 // Walk the super chain. If we find a hit with a parent, we'll end
497 // up returning that summary. We actually allow that key (null,S), as
498 // we cache summaries for the null ObjCInterfaceDecl* to allow us to
499 // generate initial summaries without having to worry about NSObject
500 // being declared.
501 // FIXME: We may change this at some point.
502 for (ObjCInterfaceDecl* C=D->getSuperClass() ;; C=C->getSuperClass()) {
503 if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
504 break;
505
506 if (!C)
507 return I;
508 }
509
510 // Cache the summary with original key to make the next lookup faster
511 // and return the iterator.
512 M[K] = I->second;
513 return I;
514 }
515
Ted Kremenek98530452008-08-12 20:41:56 +0000516
Ted Kremenek553cf182008-06-25 21:21:56 +0000517 iterator find(Expr* Receiver, Selector S) {
518 return find(getReceiverDecl(Receiver), S);
519 }
520
521 iterator find(IdentifierInfo* II, Selector S) {
522 // FIXME: Class method lookup. Right now we dont' have a good way
523 // of going between IdentifierInfo* and the class hierarchy.
524 iterator I = M.find(ObjCSummaryKey(II, S));
525 return I == M.end() ? M.find(ObjCSummaryKey(S)) : I;
526 }
527
528 ObjCInterfaceDecl* getReceiverDecl(Expr* E) {
529
530 const PointerType* PT = E->getType()->getAsPointerType();
531 if (!PT) return 0;
532
533 ObjCInterfaceType* OI = dyn_cast<ObjCInterfaceType>(PT->getPointeeType());
534 if (!OI) return 0;
535
536 return OI ? OI->getDecl() : 0;
537 }
538
539 iterator end() { return M.end(); }
540
541 RetainSummary*& operator[](ObjCMessageExpr* ME) {
542
543 Selector S = ME->getSelector();
544
545 if (Expr* Receiver = ME->getReceiver()) {
546 ObjCInterfaceDecl* OD = getReceiverDecl(Receiver);
547 return OD ? M[ObjCSummaryKey(OD->getIdentifier(), S)] : M[S];
548 }
549
550 return M[ObjCSummaryKey(ME->getClassName(), S)];
551 }
552
553 RetainSummary*& operator[](ObjCSummaryKey K) {
554 return M[K];
555 }
556
557 RetainSummary*& operator[](Selector S) {
558 return M[ ObjCSummaryKey(S) ];
559 }
560};
561} // end anonymous namespace
562
563//===----------------------------------------------------------------------===//
564// Data structures for managing collections of summaries.
565//===----------------------------------------------------------------------===//
566
567namespace {
568class VISIBILITY_HIDDEN RetainSummaryManager {
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000569
570 //==-----------------------------------------------------------------==//
571 // Typedefs.
572 //==-----------------------------------------------------------------==//
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000573
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000574 typedef llvm::DenseMap<FunctionDecl*, RetainSummary*>
575 FuncSummariesTy;
576
Ted Kremenek4f22a782008-06-23 23:30:29 +0000577 typedef ObjCSummaryCache ObjCMethodSummariesTy;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000578
579 //==-----------------------------------------------------------------==//
580 // Data.
581 //==-----------------------------------------------------------------==//
582
Ted Kremenek553cf182008-06-25 21:21:56 +0000583 /// Ctx - The ASTContext object for the analyzed ASTs.
Ted Kremenek377e2302008-04-29 05:33:51 +0000584 ASTContext& Ctx;
Ted Kremenek179064e2008-07-01 17:21:27 +0000585
Ted Kremenek070a8252008-07-09 18:11:16 +0000586 /// CFDictionaryCreateII - An IdentifierInfo* representing the indentifier
587 /// "CFDictionaryCreate".
588 IdentifierInfo* CFDictionaryCreateII;
589
Ted Kremenek553cf182008-06-25 21:21:56 +0000590 /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
Ted Kremenek377e2302008-04-29 05:33:51 +0000591 const bool GCEnabled;
Ted Kremenek22fe2482009-05-04 04:30:18 +0000592
Ted Kremenek553cf182008-06-25 21:21:56 +0000593 /// FuncSummaries - A map from FunctionDecls to summaries.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000594 FuncSummariesTy FuncSummaries;
595
Ted Kremenek553cf182008-06-25 21:21:56 +0000596 /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
597 /// to summaries.
Ted Kremenek1f180c32008-06-23 22:21:20 +0000598 ObjCMethodSummariesTy ObjCClassMethodSummaries;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000599
Ted Kremenek553cf182008-06-25 21:21:56 +0000600 /// ObjCMethodSummaries - A map from selectors to summaries.
Ted Kremenek1f180c32008-06-23 22:21:20 +0000601 ObjCMethodSummariesTy ObjCMethodSummaries;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000602
Ted Kremenek553cf182008-06-25 21:21:56 +0000603 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
604 /// and all other data used by the checker.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000605 llvm::BumpPtrAllocator BPAlloc;
606
Ted Kremenekb77449c2009-05-03 05:20:50 +0000607 /// AF - A factory for ArgEffects objects.
608 ArgEffects::Factory AF;
609
Ted Kremenek553cf182008-06-25 21:21:56 +0000610 /// ScratchArgs - A holding buffer for construct ArgEffects.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000611 ArgEffects ScratchArgs;
612
Ted Kremenekec315332009-05-07 23:40:42 +0000613 /// ObjCAllocRetE - Default return effect for methods returning Objective-C
614 /// objects.
615 RetEffect ObjCAllocRetE;
616
Ted Kremenek7faca822009-05-04 04:57:00 +0000617 RetainSummary DefaultSummary;
Ted Kremenek432af592008-05-06 18:11:36 +0000618 RetainSummary* StopSummary;
619
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000620 //==-----------------------------------------------------------------==//
621 // Methods.
622 //==-----------------------------------------------------------------==//
623
Ted Kremenek553cf182008-06-25 21:21:56 +0000624 /// getArgEffects - Returns a persistent ArgEffects object based on the
625 /// data in ScratchArgs.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000626 ArgEffects getArgEffects();
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000627
Ted Kremenek86ad3bc2008-05-05 16:51:50 +0000628 enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
Ted Kremenek896cd9d2008-10-23 01:56:15 +0000629
630public:
Ted Kremenek885c27b2009-05-04 05:31:22 +0000631 RetainSummary *getDefaultSummary() {
632 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
633 return new (Summ) RetainSummary(DefaultSummary);
634 }
Ted Kremenek7faca822009-05-04 04:57:00 +0000635
Ted Kremenek6ad315a2009-02-23 16:51:39 +0000636 RetainSummary* getUnarySummary(const FunctionType* FT, UnaryFuncKind func);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000637
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000638 RetainSummary* getCFSummaryCreateRule(FunctionDecl* FD);
639 RetainSummary* getCFSummaryGetRule(FunctionDecl* FD);
Ted Kremenek12619382009-01-12 21:45:02 +0000640 RetainSummary* getCFCreateGetRuleSummary(FunctionDecl* FD, const char* FName);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000641
Ted Kremenekb77449c2009-05-03 05:20:50 +0000642 RetainSummary* getPersistentSummary(ArgEffects AE, RetEffect RetEff,
Ted Kremenek1bffd742008-05-06 15:44:25 +0000643 ArgEffect ReceiverEff = DoNothing,
Ted Kremenek70a733e2008-07-18 17:24:20 +0000644 ArgEffect DefaultEff = MayEscape,
645 bool isEndPath = false);
Ted Kremenek706522f2008-10-29 04:07:07 +0000646
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000647 RetainSummary* getPersistentSummary(RetEffect RE,
Ted Kremenek1bffd742008-05-06 15:44:25 +0000648 ArgEffect ReceiverEff = DoNothing,
Ted Kremenek3eabf1c2008-05-22 17:31:13 +0000649 ArgEffect DefaultEff = MayEscape) {
Ted Kremenek1bffd742008-05-06 15:44:25 +0000650 return getPersistentSummary(getArgEffects(), RE, ReceiverEff, DefaultEff);
Ted Kremenek9c32d082008-05-06 00:30:21 +0000651 }
Ted Kremenek46e49ee2008-05-05 23:55:01 +0000652
Ted Kremenek8711c032009-04-29 05:04:30 +0000653 RetainSummary *getPersistentStopSummary() {
Ted Kremenek432af592008-05-06 18:11:36 +0000654 if (StopSummary)
655 return StopSummary;
656
657 StopSummary = getPersistentSummary(RetEffect::MakeNoRet(),
658 StopTracking, StopTracking);
Ted Kremenek706522f2008-10-29 04:07:07 +0000659
Ted Kremenek432af592008-05-06 18:11:36 +0000660 return StopSummary;
Ted Kremenek1bffd742008-05-06 15:44:25 +0000661 }
Ted Kremenekb3095252008-05-06 04:20:12 +0000662
Ted Kremenek8711c032009-04-29 05:04:30 +0000663 RetainSummary *getInitMethodSummary(QualType RetTy);
Ted Kremenek46e49ee2008-05-05 23:55:01 +0000664
Ted Kremenek1f180c32008-06-23 22:21:20 +0000665 void InitializeClassMethodSummaries();
666 void InitializeMethodSummaries();
Ted Kremenek896cd9d2008-10-23 01:56:15 +0000667
Ted Kremenekeff4b3c2009-05-03 04:42:10 +0000668 bool isTrackedObjCObjectType(QualType T);
Ted Kremenek92511432009-05-03 06:08:32 +0000669 bool isTrackedCFObjectType(QualType T);
Ted Kremenek234a4c22009-01-07 00:39:56 +0000670
Ted Kremenek896cd9d2008-10-23 01:56:15 +0000671private:
672
Ted Kremenek70a733e2008-07-18 17:24:20 +0000673 void addClsMethSummary(IdentifierInfo* ClsII, Selector S,
674 RetainSummary* Summ) {
675 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
676 }
677
Ted Kremenek553cf182008-06-25 21:21:56 +0000678 void addNSObjectClsMethSummary(Selector S, RetainSummary *Summ) {
679 ObjCClassMethodSummaries[S] = Summ;
680 }
681
682 void addNSObjectMethSummary(Selector S, RetainSummary *Summ) {
683 ObjCMethodSummaries[S] = Summ;
684 }
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +0000685
686 void addClassMethSummary(const char* Cls, const char* nullaryName,
687 RetainSummary *Summ) {
688 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
689 Selector S = GetNullarySelector(nullaryName, Ctx);
690 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
691 }
Ted Kremenek553cf182008-06-25 21:21:56 +0000692
Ted Kremenek6c4becb2009-02-25 02:54:57 +0000693 void addInstMethSummary(const char* Cls, const char* nullaryName,
694 RetainSummary *Summ) {
695 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
696 Selector S = GetNullarySelector(nullaryName, Ctx);
697 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
698 }
Ted Kremenekde4d5332009-04-24 17:50:11 +0000699
700 Selector generateSelector(va_list argp) {
Ted Kremenek9e476de2008-08-12 18:30:56 +0000701 llvm::SmallVector<IdentifierInfo*, 10> II;
Ted Kremenekde4d5332009-04-24 17:50:11 +0000702
Ted Kremenek9e476de2008-08-12 18:30:56 +0000703 while (const char* s = va_arg(argp, const char*))
704 II.push_back(&Ctx.Idents.get(s));
Ted Kremenekde4d5332009-04-24 17:50:11 +0000705
706 return Ctx.Selectors.getSelector(II.size(), &II[0]);
707 }
708
709 void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy& Summaries,
710 RetainSummary* Summ, va_list argp) {
711 Selector S = generateSelector(argp);
712 Summaries[ObjCSummaryKey(ClsII, S)] = Summ;
Ted Kremenek70a733e2008-07-18 17:24:20 +0000713 }
Ted Kremenekaf9dc272008-08-12 18:48:50 +0000714
715 void addInstMethSummary(const char* Cls, RetainSummary* Summ, ...) {
716 va_list argp;
717 va_start(argp, Summ);
Ted Kremenekde4d5332009-04-24 17:50:11 +0000718 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Ted Kremenekaf9dc272008-08-12 18:48:50 +0000719 va_end(argp);
720 }
Ted Kremenekde4d5332009-04-24 17:50:11 +0000721
722 void addClsMethSummary(const char* Cls, RetainSummary* Summ, ...) {
723 va_list argp;
724 va_start(argp, Summ);
725 addMethodSummary(&Ctx.Idents.get(Cls),ObjCClassMethodSummaries, Summ, argp);
726 va_end(argp);
727 }
728
729 void addClsMethSummary(IdentifierInfo *II, RetainSummary* Summ, ...) {
730 va_list argp;
731 va_start(argp, Summ);
732 addMethodSummary(II, ObjCClassMethodSummaries, Summ, argp);
733 va_end(argp);
734 }
735
Ted Kremenek9e476de2008-08-12 18:30:56 +0000736 void addPanicSummary(const char* Cls, ...) {
Ted Kremenekb77449c2009-05-03 05:20:50 +0000737 RetainSummary* Summ = getPersistentSummary(AF.GetEmptyMap(),
738 RetEffect::MakeNoRet(),
Ted Kremenek9e476de2008-08-12 18:30:56 +0000739 DoNothing, DoNothing, true);
740 va_list argp;
741 va_start (argp, Cls);
Ted Kremenekde4d5332009-04-24 17:50:11 +0000742 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Ted Kremenek9e476de2008-08-12 18:30:56 +0000743 va_end(argp);
Ted Kremenekde4d5332009-04-24 17:50:11 +0000744 }
Ted Kremenek70a733e2008-07-18 17:24:20 +0000745
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000746public:
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000747
748 RetainSummaryManager(ASTContext& ctx, bool gcenabled)
Ted Kremenek179064e2008-07-01 17:21:27 +0000749 : Ctx(ctx),
Ted Kremenek070a8252008-07-09 18:11:16 +0000750 CFDictionaryCreateII(&ctx.Idents.get("CFDictionaryCreate")),
Ted Kremenekb77449c2009-05-03 05:20:50 +0000751 GCEnabled(gcenabled), AF(BPAlloc), ScratchArgs(AF.GetEmptyMap()),
Ted Kremenekec315332009-05-07 23:40:42 +0000752 ObjCAllocRetE(gcenabled ? RetEffect::MakeGCNotOwned()
753 : RetEffect::MakeOwned(RetEffect::ObjC, true)),
Ted Kremenek7faca822009-05-04 04:57:00 +0000754 DefaultSummary(AF.GetEmptyMap() /* per-argument effects (none) */,
755 RetEffect::MakeNoRet() /* return effect */,
756 DoNothing /* receiver effect */,
757 MayEscape /* default argument effect */),
Ted Kremenekb77449c2009-05-03 05:20:50 +0000758 StopSummary(0) {
Ted Kremenek553cf182008-06-25 21:21:56 +0000759
760 InitializeClassMethodSummaries();
761 InitializeMethodSummaries();
762 }
Ted Kremenek377e2302008-04-29 05:33:51 +0000763
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000764 ~RetainSummaryManager();
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000765
Ted Kremenekab592272008-06-24 03:56:45 +0000766 RetainSummary* getSummary(FunctionDecl* FD);
Ted Kremenek8711c032009-04-29 05:04:30 +0000767
Ted Kremeneka8833552009-04-29 23:03:22 +0000768 RetainSummary* getInstanceMethodSummary(ObjCMessageExpr* ME,
769 const ObjCInterfaceDecl* ID) {
Ted Kremenekce8a41d2009-04-29 17:09:14 +0000770 return getInstanceMethodSummary(ME->getSelector(), ME->getClassName(),
Ted Kremenek8711c032009-04-29 05:04:30 +0000771 ID, ME->getMethodDecl(), ME->getType());
772 }
773
Ted Kremenekce8a41d2009-04-29 17:09:14 +0000774 RetainSummary* getInstanceMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremeneka8833552009-04-29 23:03:22 +0000775 const ObjCInterfaceDecl* ID,
776 const ObjCMethodDecl *MD,
777 QualType RetTy);
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +0000778
779 RetainSummary *getClassMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremeneka8833552009-04-29 23:03:22 +0000780 const ObjCInterfaceDecl *ID,
781 const ObjCMethodDecl *MD,
782 QualType RetTy);
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +0000783
784 RetainSummary *getClassMethodSummary(ObjCMessageExpr *ME) {
785 return getClassMethodSummary(ME->getSelector(), ME->getClassName(),
786 ME->getClassInfo().first,
787 ME->getMethodDecl(), ME->getType());
788 }
Ted Kremenek552333c2009-04-29 17:17:48 +0000789
790 /// getMethodSummary - This version of getMethodSummary is used to query
791 /// the summary for the current method being analyzed.
Ted Kremeneka8833552009-04-29 23:03:22 +0000792 RetainSummary *getMethodSummary(const ObjCMethodDecl *MD) {
793 // FIXME: Eventually this should be unneeded.
Ted Kremeneka8833552009-04-29 23:03:22 +0000794 const ObjCInterfaceDecl *ID = MD->getClassInterface();
Ted Kremenek70a65762009-04-30 05:41:14 +0000795 Selector S = MD->getSelector();
Ted Kremenek552333c2009-04-29 17:17:48 +0000796 IdentifierInfo *ClsName = ID->getIdentifier();
797 QualType ResultTy = MD->getResultType();
798
Ted Kremenek76a50e32009-04-30 05:47:23 +0000799 // Resolve the method decl last.
800 if (const ObjCMethodDecl *InterfaceMD =
801 ResolveToInterfaceMethodDecl(MD, Ctx))
802 MD = InterfaceMD;
Ted Kremenek70a65762009-04-30 05:41:14 +0000803
Ted Kremenek552333c2009-04-29 17:17:48 +0000804 if (MD->isInstanceMethod())
805 return getInstanceMethodSummary(S, ClsName, ID, MD, ResultTy);
806 else
807 return getClassMethodSummary(S, ClsName, ID, MD, ResultTy);
808 }
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +0000809
Ted Kremeneka8833552009-04-29 23:03:22 +0000810 RetainSummary* getCommonMethodSummary(const ObjCMethodDecl* MD,
811 Selector S, QualType RetTy);
812
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000813 bool isGCEnabled() const { return GCEnabled; }
Ted Kremenek885c27b2009-05-04 05:31:22 +0000814
815 RetainSummary *copySummary(RetainSummary *OldSumm) {
816 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
817 new (Summ) RetainSummary(*OldSumm);
818 return Summ;
819 }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000820};
821
822} // end anonymous namespace
823
824//===----------------------------------------------------------------------===//
825// Implementation of checker data structures.
826//===----------------------------------------------------------------------===//
827
Ted Kremenekb77449c2009-05-03 05:20:50 +0000828RetainSummaryManager::~RetainSummaryManager() {}
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000829
Ted Kremenekb77449c2009-05-03 05:20:50 +0000830ArgEffects RetainSummaryManager::getArgEffects() {
831 ArgEffects AE = ScratchArgs;
832 ScratchArgs = AF.GetEmptyMap();
833 return AE;
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000834}
835
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000836RetainSummary*
Ted Kremenekb77449c2009-05-03 05:20:50 +0000837RetainSummaryManager::getPersistentSummary(ArgEffects AE, RetEffect RetEff,
Ted Kremenek1bffd742008-05-06 15:44:25 +0000838 ArgEffect ReceiverEff,
Ted Kremenek70a733e2008-07-18 17:24:20 +0000839 ArgEffect DefaultEff,
Ted Kremenek22fe2482009-05-04 04:30:18 +0000840 bool isEndPath) {
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000841 // Create the summary and return it.
Ted Kremenek22fe2482009-05-04 04:30:18 +0000842 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
Ted Kremenek70a733e2008-07-18 17:24:20 +0000843 new (Summ) RetainSummary(AE, RetEff, DefaultEff, ReceiverEff, isEndPath);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000844 return Summ;
845}
846
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000847//===----------------------------------------------------------------------===//
Ted Kremenek234a4c22009-01-07 00:39:56 +0000848// Predicates.
849//===----------------------------------------------------------------------===//
850
Ted Kremenekeff4b3c2009-05-03 04:42:10 +0000851bool RetainSummaryManager::isTrackedObjCObjectType(QualType Ty) {
Ted Kremenek97d095f2009-04-23 22:11:07 +0000852 if (!Ctx.isObjCObjectPointerType(Ty))
Ted Kremenek234a4c22009-01-07 00:39:56 +0000853 return false;
854
Ted Kremenek97d095f2009-04-23 22:11:07 +0000855 // We assume that id<..>, id, and "Class" all represent tracked objects.
856 const PointerType *PT = Ty->getAsPointerType();
857 if (PT == 0)
858 return true;
859
860 const ObjCInterfaceType *OT = PT->getPointeeType()->getAsObjCInterfaceType();
Ted Kremenek234a4c22009-01-07 00:39:56 +0000861
862 // We assume that id<..>, id, and "Class" all represent tracked objects.
863 if (!OT)
864 return true;
Ted Kremenek97d095f2009-04-23 22:11:07 +0000865
866 // Does the interface subclass NSObject?
Ted Kremenek234a4c22009-01-07 00:39:56 +0000867 // FIXME: We can memoize here if this gets too expensive.
868 IdentifierInfo* NSObjectII = &Ctx.Idents.get("NSObject");
869 ObjCInterfaceDecl* ID = OT->getDecl();
870
871 for ( ; ID ; ID = ID->getSuperClass())
872 if (ID->getIdentifier() == NSObjectII)
873 return true;
874
875 return false;
876}
877
Ted Kremenek92511432009-05-03 06:08:32 +0000878bool RetainSummaryManager::isTrackedCFObjectType(QualType T) {
879 return isRefType(T, "CF") || // Core Foundation.
880 isRefType(T, "CG") || // Core Graphics.
881 isRefType(T, "DADisk") || // Disk Arbitration API.
882 isRefType(T, "DADissenter") ||
883 isRefType(T, "DASessionRef");
884}
885
Ted Kremenek234a4c22009-01-07 00:39:56 +0000886//===----------------------------------------------------------------------===//
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000887// Summary creation for functions (largely uses of Core Foundation).
888//===----------------------------------------------------------------------===//
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000889
Ted Kremenek12619382009-01-12 21:45:02 +0000890static bool isRetain(FunctionDecl* FD, const char* FName) {
891 const char* loc = strstr(FName, "Retain");
892 return loc && loc[sizeof("Retain")-1] == '\0';
893}
894
895static bool isRelease(FunctionDecl* FD, const char* FName) {
896 const char* loc = strstr(FName, "Release");
897 return loc && loc[sizeof("Release")-1] == '\0';
898}
899
Ted Kremenekab592272008-06-24 03:56:45 +0000900RetainSummary* RetainSummaryManager::getSummary(FunctionDecl* FD) {
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000901 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000902 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000903 if (I != FuncSummaries.end())
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000904 return I->second;
905
Ted Kremeneke401a0c2009-05-04 15:34:07 +0000906 // No summary? Generate one.
Ted Kremenek12619382009-01-12 21:45:02 +0000907 RetainSummary *S = 0;
Ted Kremenek86ad3bc2008-05-05 16:51:50 +0000908
Ted Kremenek37d785b2008-07-15 16:50:12 +0000909 do {
Ted Kremenek12619382009-01-12 21:45:02 +0000910 // We generate "stop" summaries for implicitly defined functions.
911 if (FD->isImplicit()) {
912 S = getPersistentStopSummary();
913 break;
Ted Kremenek37d785b2008-07-15 16:50:12 +0000914 }
Ted Kremenek6ca31912008-11-04 00:36:12 +0000915
Ted Kremenek6ad315a2009-02-23 16:51:39 +0000916 // [PR 3337] Use 'getAsFunctionType' to strip away any typedefs on the
Ted Kremenek99890652009-01-16 18:40:33 +0000917 // function's type.
Ted Kremenek6ad315a2009-02-23 16:51:39 +0000918 const FunctionType* FT = FD->getType()->getAsFunctionType();
Ted Kremenek12619382009-01-12 21:45:02 +0000919 const char* FName = FD->getIdentifier()->getName();
920
Ted Kremenekbf0a4dd2009-03-05 22:11:14 +0000921 // Strip away preceding '_'. Doing this here will effect all the checks
922 // down below.
923 while (*FName == '_') ++FName;
924
Ted Kremenek12619382009-01-12 21:45:02 +0000925 // Inspect the result type.
926 QualType RetTy = FT->getResultType();
927
928 // FIXME: This should all be refactored into a chain of "summary lookup"
929 // filters.
930 if (strcmp(FName, "IOServiceGetMatchingServices") == 0) {
931 // FIXES: <rdar://problem/6326900>
932 // This should be addressed using a API table. This strcmp is also
933 // a little gross, but there is no need to super optimize here.
Ted Kremenekb77449c2009-05-03 05:20:50 +0000934 assert (ScratchArgs.isEmpty());
935 ScratchArgs = AF.Add(ScratchArgs, 1, DecRef);
Ted Kremenek12619382009-01-12 21:45:02 +0000936 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
937 break;
Ted Kremenek64e859a2008-10-22 20:54:52 +0000938 }
Ted Kremenek61991902009-03-17 22:43:44 +0000939
940 // Enable this code once the semantics of NSDeallocateObject are resolved
941 // for GC. <rdar://problem/6619988>
942#if 0
943 // Handle: NSDeallocateObject(id anObject);
944 // This method does allow 'nil' (although we don't check it now).
945 if (strcmp(FName, "NSDeallocateObject") == 0) {
946 return RetTy == Ctx.VoidTy
947 ? getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, Dealloc)
948 : getPersistentStopSummary();
949 }
950#endif
Ted Kremenek12619382009-01-12 21:45:02 +0000951
952 // Handle: id NSMakeCollectable(CFTypeRef)
953 if (strcmp(FName, "NSMakeCollectable") == 0) {
954 S = (RetTy == Ctx.getObjCIdType())
955 ? getUnarySummary(FT, cfmakecollectable)
956 : getPersistentStopSummary();
957
958 break;
959 }
960
961 if (RetTy->isPointerType()) {
962 // For CoreFoundation ('CF') types.
963 if (isRefType(RetTy, "CF", &Ctx, FName)) {
964 if (isRetain(FD, FName))
965 S = getUnarySummary(FT, cfretain);
966 else if (strstr(FName, "MakeCollectable"))
967 S = getUnarySummary(FT, cfmakecollectable);
968 else
969 S = getCFCreateGetRuleSummary(FD, FName);
970
971 break;
972 }
973
974 // For CoreGraphics ('CG') types.
975 if (isRefType(RetTy, "CG", &Ctx, FName)) {
976 if (isRetain(FD, FName))
977 S = getUnarySummary(FT, cfretain);
978 else
979 S = getCFCreateGetRuleSummary(FD, FName);
980
981 break;
982 }
983
984 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
985 if (isRefType(RetTy, "DADisk") ||
986 isRefType(RetTy, "DADissenter") ||
987 isRefType(RetTy, "DASessionRef")) {
988 S = getCFCreateGetRuleSummary(FD, FName);
989 break;
990 }
991
992 break;
993 }
994
995 // Check for release functions, the only kind of functions that we care
996 // about that don't return a pointer type.
997 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
Ted Kremenekbf0a4dd2009-03-05 22:11:14 +0000998 // Test for 'CGCF'.
999 if (FName[1] == 'G' && FName[2] == 'C' && FName[3] == 'F')
1000 FName += 4;
1001 else
1002 FName += 2;
1003
1004 if (isRelease(FD, FName))
Ted Kremenek12619382009-01-12 21:45:02 +00001005 S = getUnarySummary(FT, cfrelease);
1006 else {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001007 assert (ScratchArgs.isEmpty());
Ted Kremenek68189282009-01-29 22:45:13 +00001008 // Remaining CoreFoundation and CoreGraphics functions.
1009 // We use to assume that they all strictly followed the ownership idiom
1010 // and that ownership cannot be transferred. While this is technically
1011 // correct, many methods allow a tracked object to escape. For example:
1012 //
1013 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
1014 // CFDictionaryAddValue(y, key, x);
1015 // CFRelease(x);
1016 // ... it is okay to use 'x' since 'y' has a reference to it
1017 //
1018 // We handle this and similar cases with the follow heuristic. If the
1019 // function name contains "InsertValue", "SetValue" or "AddValue" then
1020 // we assume that arguments may "escape."
1021 //
1022 ArgEffect E = (CStrInCStrNoCase(FName, "InsertValue") ||
1023 CStrInCStrNoCase(FName, "AddValue") ||
Ted Kremeneka92206e2009-02-05 22:34:53 +00001024 CStrInCStrNoCase(FName, "SetValue") ||
1025 CStrInCStrNoCase(FName, "AppendValue"))
Ted Kremenek68189282009-01-29 22:45:13 +00001026 ? MayEscape : DoNothing;
1027
1028 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek12619382009-01-12 21:45:02 +00001029 }
1030 }
Ted Kremenek37d785b2008-07-15 16:50:12 +00001031 }
1032 while (0);
Ted Kremenek885c27b2009-05-04 05:31:22 +00001033
1034 if (!S)
1035 S = getDefaultSummary();
Ted Kremenek891d5cc2008-04-24 17:22:33 +00001036
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001037 FuncSummaries[FD] = S;
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001038 return S;
Ted Kremenek2fff37e2008-03-06 00:08:09 +00001039}
1040
Ted Kremenek37d785b2008-07-15 16:50:12 +00001041RetainSummary*
1042RetainSummaryManager::getCFCreateGetRuleSummary(FunctionDecl* FD,
1043 const char* FName) {
1044
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001045 if (strstr(FName, "Create") || strstr(FName, "Copy"))
1046 return getCFSummaryCreateRule(FD);
Ted Kremenek37d785b2008-07-15 16:50:12 +00001047
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001048 if (strstr(FName, "Get"))
1049 return getCFSummaryGetRule(FD);
1050
Ted Kremenek7faca822009-05-04 04:57:00 +00001051 return getDefaultSummary();
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001052}
1053
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001054RetainSummary*
Ted Kremenek6ad315a2009-02-23 16:51:39 +00001055RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1056 UnaryFuncKind func) {
1057
Ted Kremenek12619382009-01-12 21:45:02 +00001058 // Sanity check that this is *really* a unary function. This can
1059 // happen if people do weird things.
Douglas Gregor72564e72009-02-26 23:50:07 +00001060 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
Ted Kremenek12619382009-01-12 21:45:02 +00001061 if (!FTP || FTP->getNumArgs() != 1)
1062 return getPersistentStopSummary();
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001063
Ted Kremenekb77449c2009-05-03 05:20:50 +00001064 assert (ScratchArgs.isEmpty());
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001065
Ted Kremenek377e2302008-04-29 05:33:51 +00001066 switch (func) {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001067 case cfretain: {
1068 ScratchArgs = AF.Add(ScratchArgs, 0, IncRef);
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00001069 return getPersistentSummary(RetEffect::MakeAlias(0),
1070 DoNothing, DoNothing);
Ted Kremenek377e2302008-04-29 05:33:51 +00001071 }
1072
1073 case cfrelease: {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001074 ScratchArgs = AF.Add(ScratchArgs, 0, DecRef);
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00001075 return getPersistentSummary(RetEffect::MakeNoRet(),
1076 DoNothing, DoNothing);
Ted Kremenek377e2302008-04-29 05:33:51 +00001077 }
1078
1079 case cfmakecollectable: {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001080 ScratchArgs = AF.Add(ScratchArgs, 0, MakeCollectable);
Ted Kremenek27019002009-02-18 21:57:45 +00001081 return getPersistentSummary(RetEffect::MakeAlias(0),DoNothing, DoNothing);
Ted Kremenek377e2302008-04-29 05:33:51 +00001082 }
1083
1084 default:
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001085 assert (false && "Not a supported unary function.");
Ted Kremenek7faca822009-05-04 04:57:00 +00001086 return getDefaultSummary();
Ted Kremenek940b1d82008-04-10 23:44:06 +00001087 }
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001088}
1089
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001090RetainSummary* RetainSummaryManager::getCFSummaryCreateRule(FunctionDecl* FD) {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001091 assert (ScratchArgs.isEmpty());
Ted Kremenek070a8252008-07-09 18:11:16 +00001092
1093 if (FD->getIdentifier() == CFDictionaryCreateII) {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001094 ScratchArgs = AF.Add(ScratchArgs, 1, DoNothingByRef);
1095 ScratchArgs = AF.Add(ScratchArgs, 2, DoNothingByRef);
Ted Kremenek070a8252008-07-09 18:11:16 +00001096 }
1097
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001098 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001099}
1100
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001101RetainSummary* RetainSummaryManager::getCFSummaryGetRule(FunctionDecl* FD) {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001102 assert (ScratchArgs.isEmpty());
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001103 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1104 DoNothing, DoNothing);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001105}
1106
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001107//===----------------------------------------------------------------------===//
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001108// Summary creation for Selectors.
1109//===----------------------------------------------------------------------===//
1110
Ted Kremenek1bffd742008-05-06 15:44:25 +00001111RetainSummary*
Ted Kremenek8711c032009-04-29 05:04:30 +00001112RetainSummaryManager::getInitMethodSummary(QualType RetTy) {
Ted Kremenekb77449c2009-05-03 05:20:50 +00001113 assert(ScratchArgs.isEmpty());
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001114
Ted Kremenekc3cf7b22009-02-20 00:05:35 +00001115 // 'init' methods only return an alias if the return type is a location type.
Ted Kremenek8711c032009-04-29 05:04:30 +00001116 return getPersistentSummary(Loc::IsLocType(RetTy)
1117 ? RetEffect::MakeReceiverAlias()
Ted Kremenek69aa0802009-05-05 18:44:20 +00001118 : RetEffect::MakeNoRet());
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001119}
Ted Kremenek69aa0802009-05-05 18:44:20 +00001120
Ted Kremenek1bffd742008-05-06 15:44:25 +00001121RetainSummary*
Ted Kremeneka8833552009-04-29 23:03:22 +00001122RetainSummaryManager::getCommonMethodSummary(const ObjCMethodDecl* MD,
1123 Selector S, QualType RetTy) {
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001124
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +00001125 if (MD) {
Ted Kremenek376d1e72009-04-24 18:00:17 +00001126 // Scan the method decl for 'void*' arguments. These should be treated
1127 // as 'StopTracking' because they are often used with delegates.
1128 // Delegates are a frequent form of false positives with the retain
1129 // count checker.
1130 unsigned i = 0;
1131 for (ObjCMethodDecl::param_iterator I = MD->param_begin(),
1132 E = MD->param_end(); I != E; ++I, ++i)
1133 if (ParmVarDecl *PD = *I) {
1134 QualType Ty = Ctx.getCanonicalType(PD->getType());
1135 if (Ty.getUnqualifiedType() == Ctx.VoidPtrTy)
Ted Kremenekb77449c2009-05-03 05:20:50 +00001136 ScratchArgs = AF.Add(ScratchArgs, i, StopTracking);
Ted Kremenek376d1e72009-04-24 18:00:17 +00001137 }
1138 }
1139
Ted Kremenek8ee885b2009-04-24 21:56:17 +00001140 // Any special effect for the receiver?
1141 ArgEffect ReceiverEff = DoNothing;
1142
1143 // If one of the arguments in the selector has the keyword 'delegate' we
1144 // should stop tracking the reference count for the receiver. This is
1145 // because the reference count is quite possibly handled by a delegate
1146 // method.
1147 if (S.isKeywordSelector()) {
1148 const std::string &str = S.getAsString();
1149 assert(!str.empty());
1150 if (CStrInCStrNoCase(&str[0], "delegate:")) ReceiverEff = StopTracking;
1151 }
1152
Ted Kremenek250b1fa2009-04-23 23:08:22 +00001153 // Look for methods that return an owned object.
Ted Kremenek92511432009-05-03 06:08:32 +00001154 if (isTrackedObjCObjectType(RetTy)) {
1155 // EXPERIMENTAL: Assume the Cocoa conventions for all objects returned
1156 // by instance methods.
Ted Kremenek92511432009-05-03 06:08:32 +00001157 RetEffect E =
1158 followsFundamentalRule(S.getIdentifierInfoForSlot(0)->getName())
Ted Kremenekec315332009-05-07 23:40:42 +00001159 ? ObjCAllocRetE : RetEffect::MakeNotOwned(RetEffect::ObjC);
Ted Kremenek92511432009-05-03 06:08:32 +00001160
1161 return getPersistentSummary(E, ReceiverEff, MayEscape);
Ted Kremenek376d1e72009-04-24 18:00:17 +00001162 }
Ted Kremenek250b1fa2009-04-23 23:08:22 +00001163
Ted Kremenek92511432009-05-03 06:08:32 +00001164 // Look for methods that return an owned core foundation object.
1165 if (isTrackedCFObjectType(RetTy)) {
1166 RetEffect E =
1167 followsFundamentalRule(S.getIdentifierInfoForSlot(0)->getName())
1168 ? RetEffect::MakeOwned(RetEffect::CF, true)
1169 : RetEffect::MakeNotOwned(RetEffect::CF);
1170
1171 return getPersistentSummary(E, ReceiverEff, MayEscape);
1172 }
Ted Kremenek250b1fa2009-04-23 23:08:22 +00001173
Ted Kremenek92511432009-05-03 06:08:32 +00001174 if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing)
Ted Kremenek7faca822009-05-04 04:57:00 +00001175 return getDefaultSummary();
Ted Kremenek250b1fa2009-04-23 23:08:22 +00001176
Ted Kremenek885c27b2009-05-04 05:31:22 +00001177 return getPersistentSummary(RetEffect::MakeNoRet(), ReceiverEff, MayEscape);
Ted Kremenek250b1fa2009-04-23 23:08:22 +00001178}
1179
1180RetainSummary*
Ted Kremenekce8a41d2009-04-29 17:09:14 +00001181RetainSummaryManager::getInstanceMethodSummary(Selector S,
1182 IdentifierInfo *ClsName,
Ted Kremeneka8833552009-04-29 23:03:22 +00001183 const ObjCInterfaceDecl* ID,
1184 const ObjCMethodDecl *MD,
Ted Kremenekce8a41d2009-04-29 17:09:14 +00001185 QualType RetTy) {
Ted Kremenek1bffd742008-05-06 15:44:25 +00001186
Ted Kremenek8711c032009-04-29 05:04:30 +00001187 // Look up a summary in our summary cache.
1188 ObjCMethodSummariesTy::iterator I = ObjCMethodSummaries.find(ID, ClsName, S);
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001189
Ted Kremenek1f180c32008-06-23 22:21:20 +00001190 if (I != ObjCMethodSummaries.end())
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001191 return I->second;
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001192
Ted Kremenekb77449c2009-05-03 05:20:50 +00001193 assert(ScratchArgs.isEmpty());
Ted Kremenek885c27b2009-05-04 05:31:22 +00001194 RetainSummary *Summ = 0;
Ted Kremenekaee9e572008-05-06 06:09:09 +00001195
Ted Kremenek885c27b2009-05-04 05:31:22 +00001196 // "initXXX": pass-through for receiver.
1197 if (deriveNamingConvention(S.getIdentifierInfoForSlot(0)->getName())
1198 == InitRule)
1199 Summ = getInitMethodSummary(RetTy);
1200 else
1201 Summ = getCommonMethodSummary(MD, S, RetTy);
1202
Ted Kremenek885c27b2009-05-04 05:31:22 +00001203 // Memoize the summary.
Ted Kremenek8711c032009-04-29 05:04:30 +00001204 ObjCMethodSummaries[ObjCSummaryKey(ClsName, S)] = Summ;
Ted Kremeneke87450e2009-04-23 19:11:35 +00001205 return Summ;
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001206}
1207
Ted Kremenekc8395602008-05-06 21:26:51 +00001208RetainSummary*
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +00001209RetainSummaryManager::getClassMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremeneka8833552009-04-29 23:03:22 +00001210 const ObjCInterfaceDecl *ID,
1211 const ObjCMethodDecl *MD,
1212 QualType RetTy) {
Ted Kremenekde4d5332009-04-24 17:50:11 +00001213
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +00001214 assert(ClsName && "Class name must be specified.");
Ted Kremenek8711c032009-04-29 05:04:30 +00001215 ObjCMethodSummariesTy::iterator I =
1216 ObjCClassMethodSummaries.find(ID, ClsName, S);
Ted Kremenekc8395602008-05-06 21:26:51 +00001217
Ted Kremenek1f180c32008-06-23 22:21:20 +00001218 if (I != ObjCClassMethodSummaries.end())
Ted Kremenekc8395602008-05-06 21:26:51 +00001219 return I->second;
Ted Kremenek885c27b2009-05-04 05:31:22 +00001220
1221 RetainSummary *Summ = getCommonMethodSummary(MD, S, RetTy);
1222
Ted Kremenek885c27b2009-05-04 05:31:22 +00001223 // Memoize the summary.
Ted Kremenekfcd7c6f2009-04-29 00:42:39 +00001224 ObjCClassMethodSummaries[ObjCSummaryKey(ClsName, S)] = Summ;
Ted Kremeneke87450e2009-04-23 19:11:35 +00001225 return Summ;
Ted Kremenekc8395602008-05-06 21:26:51 +00001226}
1227
Ted Kremenekec315332009-05-07 23:40:42 +00001228void RetainSummaryManager::InitializeClassMethodSummaries() {
1229 assert(ScratchArgs.isEmpty());
1230 RetainSummary* Summ = getPersistentSummary(ObjCAllocRetE);
Ted Kremenek9c32d082008-05-06 00:30:21 +00001231
Ted Kremenek553cf182008-06-25 21:21:56 +00001232 // Create the summaries for "alloc", "new", and "allocWithZone:" for
1233 // NSObject and its derivatives.
1234 addNSObjectClsMethSummary(GetNullarySelector("alloc", Ctx), Summ);
1235 addNSObjectClsMethSummary(GetNullarySelector("new", Ctx), Summ);
1236 addNSObjectClsMethSummary(GetUnarySelector("allocWithZone", Ctx), Summ);
Ted Kremenek70a733e2008-07-18 17:24:20 +00001237
1238 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek9e476de2008-08-12 18:30:56 +00001239 addClsMethSummary(&Ctx.Idents.get("NSAssertionHandler"),
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001240 GetNullarySelector("currentHandler", Ctx),
1241 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Ted Kremenek6d348932008-10-21 15:53:15 +00001242
1243 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremenekb77449c2009-05-03 05:20:50 +00001244 ScratchArgs = AF.Add(ScratchArgs, 0, Autorelease);
Ted Kremenekabf43972009-01-28 21:44:40 +00001245 addClsMethSummary(&Ctx.Idents.get("NSAutoreleasePool"),
1246 GetUnarySelector("addObject", Ctx),
1247 getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenek022a3c42009-02-23 02:31:16 +00001248 DoNothing, Autorelease));
Ted Kremenekde4d5332009-04-24 17:50:11 +00001249
1250 // Create the summaries for [NSObject performSelector...]. We treat
1251 // these as 'stop tracking' for the arguments because they are often
1252 // used for delegates that can release the object. When we have better
1253 // inter-procedural analysis we can potentially do something better. This
1254 // workaround is to remove false positives.
1255 Summ = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, StopTracking);
1256 IdentifierInfo *NSObjectII = &Ctx.Idents.get("NSObject");
1257 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1258 "afterDelay", NULL);
1259 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1260 "afterDelay", "inModes", NULL);
1261 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1262 "withObject", "waitUntilDone", NULL);
1263 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1264 "withObject", "waitUntilDone", "modes", NULL);
1265 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1266 "withObject", "waitUntilDone", NULL);
1267 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1268 "withObject", "waitUntilDone", "modes", NULL);
1269 addClsMethSummary(NSObjectII, Summ, "performSelectorInBackground",
1270 "withObject", NULL);
Ted Kremenek9c32d082008-05-06 00:30:21 +00001271}
1272
Ted Kremenek1f180c32008-06-23 22:21:20 +00001273void RetainSummaryManager::InitializeMethodSummaries() {
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001274
Ted Kremenekb77449c2009-05-03 05:20:50 +00001275 assert (ScratchArgs.isEmpty());
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001276
Ted Kremenekc8395602008-05-06 21:26:51 +00001277 // Create the "init" selector. It just acts as a pass-through for the
1278 // receiver.
Ted Kremenek46347352009-02-23 16:54:00 +00001279 RetainSummary* InitSumm =
1280 getPersistentSummary(RetEffect::MakeReceiverAlias());
Ted Kremenek179064e2008-07-01 17:21:27 +00001281 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
Ted Kremenekc8395602008-05-06 21:26:51 +00001282
1283 // The next methods are allocators.
Ted Kremenekec315332009-05-07 23:40:42 +00001284 RetainSummary* Summ = getPersistentSummary(ObjCAllocRetE);
Ted Kremenekc8395602008-05-06 21:26:51 +00001285
1286 // Create the "copy" selector.
Ted Kremenek98530452008-08-12 20:41:56 +00001287 addNSObjectMethSummary(GetNullarySelector("copy", Ctx), Summ);
1288
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001289 // Create the "mutableCopy" selector.
Ted Kremenek553cf182008-06-25 21:21:56 +00001290 addNSObjectMethSummary(GetNullarySelector("mutableCopy", Ctx), Summ);
Ted Kremenek98530452008-08-12 20:41:56 +00001291
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001292 // Create the "retain" selector.
Ted Kremenekec315332009-05-07 23:40:42 +00001293 RetEffect E = RetEffect::MakeReceiverAlias();
Ted Kremenek1c512f52009-02-18 18:54:33 +00001294 Summ = getPersistentSummary(E, IncRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001295 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001296
1297 // Create the "release" selector.
Ted Kremenek1c512f52009-02-18 18:54:33 +00001298 Summ = getPersistentSummary(E, DecRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001299 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Ted Kremenek299e8152008-05-07 21:17:39 +00001300
1301 // Create the "drain" selector.
1302 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek553cf182008-06-25 21:21:56 +00001303 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001304
1305 // Create the -dealloc summary.
1306 Summ = getPersistentSummary(RetEffect::MakeNoRet(), Dealloc);
1307 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001308
1309 // Create the "autorelease" selector.
Ted Kremenekabf43972009-01-28 21:44:40 +00001310 Summ = getPersistentSummary(E, Autorelease);
Ted Kremenek553cf182008-06-25 21:21:56 +00001311 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Ted Kremenek98530452008-08-12 20:41:56 +00001312
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00001313 // Specially handle NSAutoreleasePool.
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001314 addInstMethSummary("NSAutoreleasePool", "init",
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00001315 getPersistentSummary(RetEffect::MakeReceiverAlias(),
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001316 NewAutoreleasePool));
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00001317
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001318 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremenek89e202d2009-02-23 02:51:29 +00001319 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1320 // self-own themselves. However, they only do this once they are displayed.
1321 // Thus, we need to track an NSWindow's display status.
1322 // This is tracked in <rdar://problem/6062711>.
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +00001323 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
Ted Kremenek99d02692009-04-03 19:02:51 +00001324 RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet());
1325
1326 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1327
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +00001328
1329#if 0
Ted Kremenek179064e2008-07-01 17:21:27 +00001330 RetainSummary *NSWindowSumm =
Ted Kremenek89e202d2009-02-23 02:51:29 +00001331 getPersistentSummary(RetEffect::MakeReceiverAlias(), StopTracking);
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001332
1333 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1334 "styleMask", "backing", "defer", NULL);
1335
1336 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1337 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +00001338#endif
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001339
1340 // For NSPanel (which subclasses NSWindow), allocated objects are not
1341 // self-owned.
Ted Kremenek99d02692009-04-03 19:02:51 +00001342 // FIXME: For now we don't track NSPanels. object for the same reason
1343 // as for NSWindow objects.
1344 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
1345
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001346 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1347 "styleMask", "backing", "defer", NULL);
1348
1349 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1350 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek553cf182008-06-25 21:21:56 +00001351
Ted Kremenek70a733e2008-07-18 17:24:20 +00001352 // Create NSAssertionHandler summaries.
Ted Kremenek9e476de2008-08-12 18:30:56 +00001353 addPanicSummary("NSAssertionHandler", "handleFailureInFunction", "file",
1354 "lineNumber", "description", NULL);
Ted Kremenek70a733e2008-07-18 17:24:20 +00001355
Ted Kremenek9e476de2008-08-12 18:30:56 +00001356 addPanicSummary("NSAssertionHandler", "handleFailureInMethod", "object",
1357 "file", "lineNumber", "description", NULL);
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001358}
1359
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001360//===----------------------------------------------------------------------===//
Ted Kremenek13922612008-04-16 20:40:59 +00001361// Reference-counting logic (typestate + counts).
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001362//===----------------------------------------------------------------------===//
1363
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001364namespace {
1365
Ted Kremenek05cbe1a2008-04-09 23:49:11 +00001366class VISIBILITY_HIDDEN RefVal {
Ted Kremenek4fd88972008-04-17 18:12:53 +00001367public:
Ted Kremenek4fd88972008-04-17 18:12:53 +00001368 enum Kind {
1369 Owned = 0, // Owning reference.
1370 NotOwned, // Reference is not owned by still valid (not freed).
1371 Released, // Object has been released.
1372 ReturnedOwned, // Returned object passes ownership to caller.
1373 ReturnedNotOwned, // Return object does not pass ownership to caller.
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001374 ERROR_START,
1375 ErrorDeallocNotOwned, // -dealloc called on non-owned object.
1376 ErrorDeallocGC, // Calling -dealloc with GC enabled.
Ted Kremenek4fd88972008-04-17 18:12:53 +00001377 ErrorUseAfterRelease, // Object used after released.
1378 ErrorReleaseNotOwned, // Release of an object that was not owned.
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001379 ERROR_LEAK_START,
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00001380 ErrorLeak, // A memory leak due to excessive reference counts.
1381 ErrorLeakReturned // A memory leak due to the returning method not having
1382 // the correct naming conventions.
Ted Kremenek4fd88972008-04-17 18:12:53 +00001383 };
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001384
1385private:
Ted Kremenek4fd88972008-04-17 18:12:53 +00001386 Kind kind;
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001387 RetEffect::ObjKind okind;
Ted Kremenek4fd88972008-04-17 18:12:53 +00001388 unsigned Cnt;
Ted Kremenekf21332e2009-05-08 20:01:42 +00001389 unsigned ACnt;
Ted Kremenek553cf182008-06-25 21:21:56 +00001390 QualType T;
1391
Ted Kremenekf21332e2009-05-08 20:01:42 +00001392 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, unsigned acnt, QualType t)
1393 : kind(k), okind(o), Cnt(cnt), ACnt(acnt), T(t) {}
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001394
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001395 RefVal(Kind k, unsigned cnt = 0)
Ted Kremenekf21332e2009-05-08 20:01:42 +00001396 : kind(k), okind(RetEffect::AnyObj), Cnt(cnt), ACnt(0) {}
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001397
1398public:
Ted Kremenek4fd88972008-04-17 18:12:53 +00001399 Kind getKind() const { return kind; }
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001400
1401 RetEffect::ObjKind getObjKind() const { return okind; }
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001402
Ted Kremenekf21332e2009-05-08 20:01:42 +00001403 unsigned getCount() const { return Cnt; }
1404 unsigned getAutoreleaseCount() const { return ACnt; }
1405 unsigned getCombinedCounts() const { return Cnt + ACnt; }
1406 void clearCounts() { Cnt = 0; ACnt = 0; }
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001407
Ted Kremenek553cf182008-06-25 21:21:56 +00001408 QualType getType() const { return T; }
Ted Kremenek4fd88972008-04-17 18:12:53 +00001409
1410 // Useful predicates.
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001411
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001412 static bool isError(Kind k) { return k >= ERROR_START; }
Ted Kremenek73c750b2008-03-11 18:14:09 +00001413
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001414 static bool isLeak(Kind k) { return k >= ERROR_LEAK_START; }
Ted Kremenekdb863712008-04-16 22:32:20 +00001415
Ted Kremeneke7bd9c22008-04-11 22:25:11 +00001416 bool isOwned() const {
1417 return getKind() == Owned;
1418 }
1419
Ted Kremenekdb863712008-04-16 22:32:20 +00001420 bool isNotOwned() const {
1421 return getKind() == NotOwned;
1422 }
1423
Ted Kremenek4fd88972008-04-17 18:12:53 +00001424 bool isReturnedOwned() const {
1425 return getKind() == ReturnedOwned;
1426 }
1427
1428 bool isReturnedNotOwned() const {
1429 return getKind() == ReturnedNotOwned;
1430 }
1431
1432 bool isNonLeakError() const {
1433 Kind k = getKind();
1434 return isError(k) && !isLeak(k);
1435 }
1436
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001437 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
1438 unsigned Count = 1) {
Ted Kremenekf21332e2009-05-08 20:01:42 +00001439 return RefVal(Owned, o, Count, 0, t);
Ted Kremenek61b9f872008-04-10 23:09:18 +00001440 }
1441
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001442 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
1443 unsigned Count = 0) {
Ted Kremenekf21332e2009-05-08 20:01:42 +00001444 return RefVal(NotOwned, o, Count, 0, t);
Ted Kremenek61b9f872008-04-10 23:09:18 +00001445 }
Ted Kremenek4fd88972008-04-17 18:12:53 +00001446
1447 static RefVal makeReturnedOwned(unsigned Count) {
1448 return RefVal(ReturnedOwned, Count);
1449 }
1450
1451 static RefVal makeReturnedNotOwned() {
1452 return RefVal(ReturnedNotOwned);
1453 }
1454
Ted Kremenek4fd88972008-04-17 18:12:53 +00001455 // Comparison, profiling, and pretty-printing.
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001456
Ted Kremenek4fd88972008-04-17 18:12:53 +00001457 bool operator==(const RefVal& X) const {
Ted Kremenek553cf182008-06-25 21:21:56 +00001458 return kind == X.kind && Cnt == X.Cnt && T == X.T;
Ted Kremenek4fd88972008-04-17 18:12:53 +00001459 }
Ted Kremenekf3948042008-03-11 19:44:10 +00001460
Ted Kremenek553cf182008-06-25 21:21:56 +00001461 RefVal operator-(size_t i) const {
Ted Kremenekf21332e2009-05-08 20:01:42 +00001462 return RefVal(getKind(), getObjKind(), getCount() - i,
1463 getAutoreleaseCount(), getType());
Ted Kremenek553cf182008-06-25 21:21:56 +00001464 }
1465
1466 RefVal operator+(size_t i) const {
Ted Kremenekf21332e2009-05-08 20:01:42 +00001467 return RefVal(getKind(), getObjKind(), getCount() + i,
1468 getAutoreleaseCount(), getType());
Ted Kremenek553cf182008-06-25 21:21:56 +00001469 }
1470
1471 RefVal operator^(Kind k) const {
Ted Kremenekf21332e2009-05-08 20:01:42 +00001472 return RefVal(k, getObjKind(), getCount(), getAutoreleaseCount(),
1473 getType());
1474 }
1475
1476 RefVal autorelease() const {
1477 return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount()+1,
1478 getType());
Ted Kremenek553cf182008-06-25 21:21:56 +00001479 }
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001480
Ted Kremenek4fd88972008-04-17 18:12:53 +00001481 void Profile(llvm::FoldingSetNodeID& ID) const {
1482 ID.AddInteger((unsigned) kind);
1483 ID.AddInteger(Cnt);
Ted Kremenekf21332e2009-05-08 20:01:42 +00001484 ID.AddInteger(ACnt);
Ted Kremenek553cf182008-06-25 21:21:56 +00001485 ID.Add(T);
Ted Kremenek4fd88972008-04-17 18:12:53 +00001486 }
1487
Ted Kremenekf3948042008-03-11 19:44:10 +00001488 void print(std::ostream& Out) const;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001489};
Ted Kremenekf3948042008-03-11 19:44:10 +00001490
1491void RefVal::print(std::ostream& Out) const {
Ted Kremenek553cf182008-06-25 21:21:56 +00001492 if (!T.isNull())
1493 Out << "Tracked Type:" << T.getAsString() << '\n';
1494
Ted Kremenekf3948042008-03-11 19:44:10 +00001495 switch (getKind()) {
1496 default: assert(false);
Ted Kremenek61b9f872008-04-10 23:09:18 +00001497 case Owned: {
1498 Out << "Owned";
1499 unsigned cnt = getCount();
1500 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenekf3948042008-03-11 19:44:10 +00001501 break;
Ted Kremenek61b9f872008-04-10 23:09:18 +00001502 }
Ted Kremenekf3948042008-03-11 19:44:10 +00001503
Ted Kremenek61b9f872008-04-10 23:09:18 +00001504 case NotOwned: {
Ted Kremenek4fd88972008-04-17 18:12:53 +00001505 Out << "NotOwned";
Ted Kremenek61b9f872008-04-10 23:09:18 +00001506 unsigned cnt = getCount();
1507 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenekf3948042008-03-11 19:44:10 +00001508 break;
Ted Kremenek61b9f872008-04-10 23:09:18 +00001509 }
Ted Kremenekf3948042008-03-11 19:44:10 +00001510
Ted Kremenek4fd88972008-04-17 18:12:53 +00001511 case ReturnedOwned: {
1512 Out << "ReturnedOwned";
1513 unsigned cnt = getCount();
1514 if (cnt) Out << " (+ " << cnt << ")";
1515 break;
1516 }
1517
1518 case ReturnedNotOwned: {
1519 Out << "ReturnedNotOwned";
1520 unsigned cnt = getCount();
1521 if (cnt) Out << " (+ " << cnt << ")";
1522 break;
1523 }
1524
Ted Kremenekf3948042008-03-11 19:44:10 +00001525 case Released:
1526 Out << "Released";
1527 break;
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001528
1529 case ErrorDeallocGC:
1530 Out << "-dealloc (GC)";
1531 break;
1532
1533 case ErrorDeallocNotOwned:
1534 Out << "-dealloc (not-owned)";
1535 break;
Ted Kremenekf3948042008-03-11 19:44:10 +00001536
Ted Kremenekdb863712008-04-16 22:32:20 +00001537 case ErrorLeak:
1538 Out << "Leaked";
1539 break;
1540
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00001541 case ErrorLeakReturned:
1542 Out << "Leaked (Bad naming)";
1543 break;
1544
Ted Kremenekf3948042008-03-11 19:44:10 +00001545 case ErrorUseAfterRelease:
1546 Out << "Use-After-Release [ERROR]";
1547 break;
1548
1549 case ErrorReleaseNotOwned:
1550 Out << "Release of Not-Owned [ERROR]";
1551 break;
1552 }
Ted Kremenekf21332e2009-05-08 20:01:42 +00001553
1554 if (ACnt) {
1555 Out << " [ARC +" << ACnt << ']';
1556 }
Ted Kremenekf3948042008-03-11 19:44:10 +00001557}
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001558
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001559} // end anonymous namespace
1560
1561//===----------------------------------------------------------------------===//
1562// RefBindings - State used to track object reference counts.
1563//===----------------------------------------------------------------------===//
1564
Ted Kremenek2dabd432008-12-05 02:27:51 +00001565typedef llvm::ImmutableMap<SymbolRef, RefVal> RefBindings;
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001566static int RefBIndex = 0;
1567
1568namespace clang {
Ted Kremenekb9d17f92008-08-17 03:20:02 +00001569 template<>
1570 struct GRStateTrait<RefBindings> : public GRStatePartialTrait<RefBindings> {
1571 static inline void* GDMIndex() { return &RefBIndex; }
1572 };
1573}
Ted Kremenek6d348932008-10-21 15:53:15 +00001574
1575//===----------------------------------------------------------------------===//
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001576// AutoreleaseBindings - State used to track objects in autorelease pools.
Ted Kremenek6d348932008-10-21 15:53:15 +00001577//===----------------------------------------------------------------------===//
1578
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001579typedef llvm::ImmutableMap<SymbolRef, unsigned> ARCounts;
1580typedef llvm::ImmutableMap<SymbolRef, ARCounts> ARPoolContents;
1581typedef llvm::ImmutableList<SymbolRef> ARStack;
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00001582
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001583static int AutoRCIndex = 0;
Ted Kremenek6d348932008-10-21 15:53:15 +00001584static int AutoRBIndex = 0;
1585
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001586namespace { class VISIBILITY_HIDDEN AutoreleasePoolContents {}; }
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001587namespace { class VISIBILITY_HIDDEN AutoreleaseStack {}; }
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001588
Ted Kremenek6d348932008-10-21 15:53:15 +00001589namespace clang {
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001590template<> struct GRStateTrait<AutoreleaseStack>
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001591 : public GRStatePartialTrait<ARStack> {
1592 static inline void* GDMIndex() { return &AutoRBIndex; }
1593};
1594
1595template<> struct GRStateTrait<AutoreleasePoolContents>
1596 : public GRStatePartialTrait<ARPoolContents> {
1597 static inline void* GDMIndex() { return &AutoRCIndex; }
1598};
1599} // end clang namespace
Ted Kremenek6d348932008-10-21 15:53:15 +00001600
Ted Kremenek7037ab82009-03-20 17:34:15 +00001601static SymbolRef GetCurrentAutoreleasePool(const GRState* state) {
1602 ARStack stack = state->get<AutoreleaseStack>();
1603 return stack.isEmpty() ? SymbolRef() : stack.getHead();
1604}
1605
1606static GRStateRef SendAutorelease(GRStateRef state, ARCounts::Factory &F,
1607 SymbolRef sym) {
1608
1609 SymbolRef pool = GetCurrentAutoreleasePool(state);
1610 const ARCounts *cnts = state.get<AutoreleasePoolContents>(pool);
1611 ARCounts newCnts(0);
1612
1613 if (cnts) {
1614 const unsigned *cnt = (*cnts).lookup(sym);
1615 newCnts = F.Add(*cnts, sym, cnt ? *cnt + 1 : 1);
1616 }
1617 else
1618 newCnts = F.Add(F.GetEmptyMap(), sym, 1);
1619
1620 return state.set<AutoreleasePoolContents>(pool, newCnts);
1621}
1622
Ted Kremenek13922612008-04-16 20:40:59 +00001623//===----------------------------------------------------------------------===//
1624// Transfer functions.
1625//===----------------------------------------------------------------------===//
1626
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001627namespace {
1628
Ted Kremenek05cbe1a2008-04-09 23:49:11 +00001629class VISIBILITY_HIDDEN CFRefCount : public GRSimpleVals {
Ted Kremenek8dd56462008-04-18 03:39:05 +00001630public:
Ted Kremenekae6814e2008-08-13 21:24:49 +00001631 class BindingsPrinter : public GRState::Printer {
Ted Kremenekf3948042008-03-11 19:44:10 +00001632 public:
Ted Kremenekae6814e2008-08-13 21:24:49 +00001633 virtual void Print(std::ostream& Out, const GRState* state,
1634 const char* nl, const char* sep);
Ted Kremenekf3948042008-03-11 19:44:10 +00001635 };
Ted Kremenek8dd56462008-04-18 03:39:05 +00001636
1637private:
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001638 typedef llvm::DenseMap<const GRExprEngine::NodeTy*, const RetainSummary*>
1639 SummaryLogTy;
1640
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001641 RetainSummaryManager Summaries;
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001642 SummaryLogTy SummaryLog;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001643 const LangOptions& LOpts;
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001644 ARCounts::Factory ARCountFactory;
Ted Kremenekb9d17f92008-08-17 03:20:02 +00001645
Ted Kremenekcf701772009-02-05 06:50:21 +00001646 BugType *useAfterRelease, *releaseNotOwned;
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001647 BugType *deallocGC, *deallocNotOwned;
Ted Kremenekcf701772009-02-05 06:50:21 +00001648 BugType *leakWithinFunction, *leakAtReturn;
1649 BugReporter *BR;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001650
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001651 GRStateRef Update(GRStateRef state, SymbolRef sym, RefVal V, ArgEffect E,
1652 RefVal::Kind& hasErr);
1653
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001654 void ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
1655 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekdb863712008-04-16 22:32:20 +00001656 Expr* NodeExpr, Expr* ErrorExpr,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001657 ExplodedNode<GRState>* Pred,
1658 const GRState* St,
Ted Kremenek2dabd432008-12-05 02:27:51 +00001659 RefVal::Kind hasErr, SymbolRef Sym);
Ted Kremenekdb863712008-04-16 22:32:20 +00001660
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00001661 GRStateRef HandleSymbolDeath(GRStateRef state, SymbolRef sid, RefVal V,
1662 llvm::SmallVectorImpl<SymbolRef> &Leaked);
1663
1664 ExplodedNode<GRState>* ProcessLeaks(GRStateRef state,
1665 llvm::SmallVectorImpl<SymbolRef> &Leaked,
1666 GenericNodeBuilder &Builder,
1667 GRExprEngine &Eng,
1668 ExplodedNode<GRState> *Pred = 0);
Ted Kremenekdb863712008-04-16 22:32:20 +00001669
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001670public:
Ted Kremenek78d46242008-07-22 16:21:24 +00001671 CFRefCount(ASTContext& Ctx, bool gcenabled, const LangOptions& lopts)
Ted Kremenek377e2302008-04-29 05:33:51 +00001672 : Summaries(Ctx, gcenabled),
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001673 LOpts(lopts), useAfterRelease(0), releaseNotOwned(0),
1674 deallocGC(0), deallocNotOwned(0),
Ted Kremenekcf701772009-02-05 06:50:21 +00001675 leakWithinFunction(0), leakAtReturn(0), BR(0) {}
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001676
Ted Kremenekcf701772009-02-05 06:50:21 +00001677 virtual ~CFRefCount() {}
Ted Kremenek05cbe1a2008-04-09 23:49:11 +00001678
Ted Kremenekcf118d42009-02-04 23:49:09 +00001679 void RegisterChecks(BugReporter &BR);
Ted Kremenekf3948042008-03-11 19:44:10 +00001680
Ted Kremenek1c72ef02008-08-16 00:49:49 +00001681 virtual void RegisterPrinters(std::vector<GRState::Printer*>& Printers) {
1682 Printers.push_back(new BindingsPrinter());
Ted Kremenekf3948042008-03-11 19:44:10 +00001683 }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001684
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001685 bool isGCEnabled() const { return Summaries.isGCEnabled(); }
Ted Kremenek072192b2008-04-30 23:47:44 +00001686 const LangOptions& getLangOptions() const { return LOpts; }
1687
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001688 const RetainSummary *getSummaryOfNode(const ExplodedNode<GRState> *N) const {
1689 SummaryLogTy::const_iterator I = SummaryLog.find(N);
1690 return I == SummaryLog.end() ? 0 : I->second;
1691 }
1692
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001693 // Calls.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001694
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001695 void EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001696 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001697 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001698 Expr* Ex,
1699 Expr* Receiver,
Ted Kremenek7faca822009-05-04 04:57:00 +00001700 const RetainSummary& Summ,
Ted Kremenek55499762008-06-17 02:43:46 +00001701 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001702 ExplodedNode<GRState>* Pred);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001703
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001704 virtual void EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek199e1a02008-03-12 21:06:49 +00001705 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001706 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001707 CallExpr* CE, SVal L,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001708 ExplodedNode<GRState>* Pred);
Ted Kremenekfa34b332008-04-09 01:10:13 +00001709
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001710
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001711 virtual void EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek85348202008-04-15 23:44:31 +00001712 GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001713 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek85348202008-04-15 23:44:31 +00001714 ObjCMessageExpr* ME,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001715 ExplodedNode<GRState>* Pred);
Ted Kremenek85348202008-04-15 23:44:31 +00001716
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001717 bool EvalObjCMessageExprAux(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek85348202008-04-15 23:44:31 +00001718 GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001719 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek85348202008-04-15 23:44:31 +00001720 ObjCMessageExpr* ME,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001721 ExplodedNode<GRState>* Pred);
Ted Kremenek85348202008-04-15 23:44:31 +00001722
Ted Kremenek41573eb2009-02-14 01:43:44 +00001723 // Stores.
1724 virtual void EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val);
1725
Ted Kremeneke7bd9c22008-04-11 22:25:11 +00001726 // End-of-path.
1727
1728 virtual void EvalEndPath(GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001729 GREndPathNodeBuilder<GRState>& Builder);
Ted Kremeneke7bd9c22008-04-11 22:25:11 +00001730
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001731 virtual void EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek652adc62008-04-24 23:57:27 +00001732 GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001733 GRStmtNodeBuilder<GRState>& Builder,
1734 ExplodedNode<GRState>* Pred,
Ted Kremenek241677a2009-01-21 22:26:05 +00001735 Stmt* S, const GRState* state,
1736 SymbolReaper& SymReaper);
Ted Kremenekf04dced2009-05-08 23:32:51 +00001737
1738 std::pair<ExplodedNode<GRState>*, GRStateRef>
1739 HandleAutoreleaseCounts(GRStateRef state, GenericNodeBuilder Bd,
1740 ExplodedNode<GRState>* Pred,
1741 SymbolRef Sym, RefVal V);
Ted Kremenek4fd88972008-04-17 18:12:53 +00001742 // Return statements.
1743
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001744 virtual void EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4fd88972008-04-17 18:12:53 +00001745 GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001746 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4fd88972008-04-17 18:12:53 +00001747 ReturnStmt* S,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001748 ExplodedNode<GRState>* Pred);
Ted Kremenekcb612922008-04-18 19:23:43 +00001749
1750 // Assumptions.
1751
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001752 virtual const GRState* EvalAssume(GRStateManager& VMgr,
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001753 const GRState* St, SVal Cond,
Ted Kremenek4323a572008-07-10 22:03:41 +00001754 bool Assumption, bool& isFeasible);
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001755};
1756
1757} // end anonymous namespace
1758
Ted Kremenek7037ab82009-03-20 17:34:15 +00001759static void PrintPool(std::ostream &Out, SymbolRef Sym, const GRState *state) {
1760 Out << ' ';
Ted Kremeneke0e4ebf2009-03-26 03:35:11 +00001761 if (Sym)
1762 Out << Sym->getSymbolID();
Ted Kremenek7037ab82009-03-20 17:34:15 +00001763 else
1764 Out << "<pool>";
1765 Out << ":{";
1766
1767 // Get the contents of the pool.
1768 if (const ARCounts *cnts = state->get<AutoreleasePoolContents>(Sym))
1769 for (ARCounts::iterator J=cnts->begin(), EJ=cnts->end(); J != EJ; ++J)
1770 Out << '(' << J.getKey() << ',' << J.getData() << ')';
1771
1772 Out << '}';
1773}
Ted Kremenek8dd56462008-04-18 03:39:05 +00001774
Ted Kremenekae6814e2008-08-13 21:24:49 +00001775void CFRefCount::BindingsPrinter::Print(std::ostream& Out, const GRState* state,
1776 const char* nl, const char* sep) {
Ted Kremenek7037ab82009-03-20 17:34:15 +00001777
1778
Ted Kremenekae6814e2008-08-13 21:24:49 +00001779
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001780 RefBindings B = state->get<RefBindings>();
Ted Kremenekf3948042008-03-11 19:44:10 +00001781
Ted Kremenekae6814e2008-08-13 21:24:49 +00001782 if (!B.isEmpty())
Ted Kremenekf3948042008-03-11 19:44:10 +00001783 Out << sep << nl;
1784
1785 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
1786 Out << (*I).first << " : ";
1787 (*I).second.print(Out);
1788 Out << nl;
1789 }
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001790
1791 // Print the autorelease stack.
Ted Kremenek7037ab82009-03-20 17:34:15 +00001792 Out << sep << nl << "AR pool stack:";
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001793 ARStack stack = state->get<AutoreleaseStack>();
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001794
Ted Kremenek7037ab82009-03-20 17:34:15 +00001795 PrintPool(Out, SymbolRef(), state); // Print the caller's pool.
1796 for (ARStack::iterator I=stack.begin(), E=stack.end(); I!=E; ++I)
1797 PrintPool(Out, *I, state);
1798
1799 Out << nl;
Ted Kremenekf3948042008-03-11 19:44:10 +00001800}
1801
Ted Kremenekc887d132009-04-29 18:50:19 +00001802//===----------------------------------------------------------------------===//
1803// Error reporting.
1804//===----------------------------------------------------------------------===//
1805
1806namespace {
1807
1808 //===-------------===//
1809 // Bug Descriptions. //
1810 //===-------------===//
1811
1812 class VISIBILITY_HIDDEN CFRefBug : public BugType {
1813 protected:
1814 CFRefCount& TF;
1815
1816 CFRefBug(CFRefCount* tf, const char* name)
1817 : BugType(name, "Memory (Core Foundation/Objective-C)"), TF(*tf) {}
1818 public:
1819
1820 CFRefCount& getTF() { return TF; }
1821 const CFRefCount& getTF() const { return TF; }
1822
1823 // FIXME: Eventually remove.
1824 virtual const char* getDescription() const = 0;
1825
1826 virtual bool isLeak() const { return false; }
1827 };
1828
1829 class VISIBILITY_HIDDEN UseAfterRelease : public CFRefBug {
1830 public:
1831 UseAfterRelease(CFRefCount* tf)
1832 : CFRefBug(tf, "Use-after-release") {}
1833
1834 const char* getDescription() const {
1835 return "Reference-counted object is used after it is released";
1836 }
1837 };
1838
1839 class VISIBILITY_HIDDEN BadRelease : public CFRefBug {
1840 public:
1841 BadRelease(CFRefCount* tf) : CFRefBug(tf, "Bad release") {}
1842
1843 const char* getDescription() const {
1844 return "Incorrect decrement of the reference count of an "
1845 "object is not owned at this point by the caller";
1846 }
1847 };
1848
1849 class VISIBILITY_HIDDEN DeallocGC : public CFRefBug {
1850 public:
1851 DeallocGC(CFRefCount *tf) : CFRefBug(tf,
1852 "-dealloc called while using GC") {}
1853
1854 const char *getDescription() const {
1855 return "-dealloc called while using GC";
1856 }
1857 };
1858
1859 class VISIBILITY_HIDDEN DeallocNotOwned : public CFRefBug {
1860 public:
1861 DeallocNotOwned(CFRefCount *tf) : CFRefBug(tf,
1862 "-dealloc sent to non-exclusively owned object") {}
1863
1864 const char *getDescription() const {
1865 return "-dealloc sent to object that may be referenced elsewhere";
1866 }
1867 };
1868
1869 class VISIBILITY_HIDDEN Leak : public CFRefBug {
1870 const bool isReturn;
1871 protected:
1872 Leak(CFRefCount* tf, const char* name, bool isRet)
1873 : CFRefBug(tf, name), isReturn(isRet) {}
1874 public:
1875
1876 const char* getDescription() const { return ""; }
1877
1878 bool isLeak() const { return true; }
1879 };
1880
1881 class VISIBILITY_HIDDEN LeakAtReturn : public Leak {
1882 public:
1883 LeakAtReturn(CFRefCount* tf, const char* name)
1884 : Leak(tf, name, true) {}
1885 };
1886
1887 class VISIBILITY_HIDDEN LeakWithinFunction : public Leak {
1888 public:
1889 LeakWithinFunction(CFRefCount* tf, const char* name)
1890 : Leak(tf, name, false) {}
1891 };
1892
1893 //===---------===//
1894 // Bug Reports. //
1895 //===---------===//
1896
1897 class VISIBILITY_HIDDEN CFRefReport : public RangedBugReport {
1898 protected:
1899 SymbolRef Sym;
1900 const CFRefCount &TF;
1901 public:
1902 CFRefReport(CFRefBug& D, const CFRefCount &tf,
1903 ExplodedNode<GRState> *n, SymbolRef sym)
1904 : RangedBugReport(D, D.getDescription(), n), Sym(sym), TF(tf) {}
1905
1906 virtual ~CFRefReport() {}
1907
1908 CFRefBug& getBugType() {
1909 return (CFRefBug&) RangedBugReport::getBugType();
1910 }
1911 const CFRefBug& getBugType() const {
1912 return (const CFRefBug&) RangedBugReport::getBugType();
1913 }
1914
1915 virtual void getRanges(BugReporter& BR, const SourceRange*& beg,
1916 const SourceRange*& end) {
1917
1918 if (!getBugType().isLeak())
1919 RangedBugReport::getRanges(BR, beg, end);
1920 else
1921 beg = end = 0;
1922 }
1923
1924 SymbolRef getSymbol() const { return Sym; }
1925
Ted Kremenek8966bc12009-05-06 21:39:49 +00001926 PathDiagnosticPiece* getEndPath(BugReporterContext& BRC,
Ted Kremenekc887d132009-04-29 18:50:19 +00001927 const ExplodedNode<GRState>* N);
1928
1929 std::pair<const char**,const char**> getExtraDescriptiveText();
1930
1931 PathDiagnosticPiece* VisitNode(const ExplodedNode<GRState>* N,
1932 const ExplodedNode<GRState>* PrevN,
Ted Kremenek8966bc12009-05-06 21:39:49 +00001933 BugReporterContext& BRC);
Ted Kremenekc887d132009-04-29 18:50:19 +00001934 };
1935
1936 class VISIBILITY_HIDDEN CFRefLeakReport : public CFRefReport {
1937 SourceLocation AllocSite;
1938 const MemRegion* AllocBinding;
1939 public:
1940 CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
1941 ExplodedNode<GRState> *n, SymbolRef sym,
1942 GRExprEngine& Eng);
1943
Ted Kremenek8966bc12009-05-06 21:39:49 +00001944 PathDiagnosticPiece* getEndPath(BugReporterContext& BRC,
Ted Kremenekc887d132009-04-29 18:50:19 +00001945 const ExplodedNode<GRState>* N);
1946
1947 SourceLocation getLocation() const { return AllocSite; }
1948 };
1949} // end anonymous namespace
1950
1951void CFRefCount::RegisterChecks(BugReporter& BR) {
1952 useAfterRelease = new UseAfterRelease(this);
1953 BR.Register(useAfterRelease);
1954
1955 releaseNotOwned = new BadRelease(this);
1956 BR.Register(releaseNotOwned);
1957
1958 deallocGC = new DeallocGC(this);
1959 BR.Register(deallocGC);
1960
1961 deallocNotOwned = new DeallocNotOwned(this);
1962 BR.Register(deallocNotOwned);
1963
1964 // First register "return" leaks.
1965 const char* name = 0;
1966
1967 if (isGCEnabled())
1968 name = "Leak of returned object when using garbage collection";
1969 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
1970 name = "Leak of returned object when not using garbage collection (GC) in "
1971 "dual GC/non-GC code";
1972 else {
1973 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
1974 name = "Leak of returned object";
1975 }
1976
1977 leakAtReturn = new LeakAtReturn(this, name);
1978 BR.Register(leakAtReturn);
1979
1980 // Second, register leaks within a function/method.
1981 if (isGCEnabled())
1982 name = "Leak of object when using garbage collection";
1983 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
1984 name = "Leak of object when not using garbage collection (GC) in "
1985 "dual GC/non-GC code";
1986 else {
1987 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
1988 name = "Leak";
1989 }
1990
1991 leakWithinFunction = new LeakWithinFunction(this, name);
1992 BR.Register(leakWithinFunction);
1993
1994 // Save the reference to the BugReporter.
1995 this->BR = &BR;
1996}
1997
1998static const char* Msgs[] = {
1999 // GC only
2000 "Code is compiled to only use garbage collection",
2001 // No GC.
2002 "Code is compiled to use reference counts",
2003 // Hybrid, with GC.
2004 "Code is compiled to use either garbage collection (GC) or reference counts"
2005 " (non-GC). The bug occurs with GC enabled",
2006 // Hybrid, without GC
2007 "Code is compiled to use either garbage collection (GC) or reference counts"
2008 " (non-GC). The bug occurs in non-GC mode"
2009};
2010
2011std::pair<const char**,const char**> CFRefReport::getExtraDescriptiveText() {
2012 CFRefCount& TF = static_cast<CFRefBug&>(getBugType()).getTF();
2013
2014 switch (TF.getLangOptions().getGCMode()) {
2015 default:
2016 assert(false);
2017
2018 case LangOptions::GCOnly:
2019 assert (TF.isGCEnabled());
2020 return std::make_pair(&Msgs[0], &Msgs[0]+1);
2021
2022 case LangOptions::NonGC:
2023 assert (!TF.isGCEnabled());
2024 return std::make_pair(&Msgs[1], &Msgs[1]+1);
2025
2026 case LangOptions::HybridGC:
2027 if (TF.isGCEnabled())
2028 return std::make_pair(&Msgs[2], &Msgs[2]+1);
2029 else
2030 return std::make_pair(&Msgs[3], &Msgs[3]+1);
2031 }
2032}
2033
2034static inline bool contains(const llvm::SmallVectorImpl<ArgEffect>& V,
2035 ArgEffect X) {
2036 for (llvm::SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
2037 I!=E; ++I)
2038 if (*I == X) return true;
2039
2040 return false;
2041}
2042
2043PathDiagnosticPiece* CFRefReport::VisitNode(const ExplodedNode<GRState>* N,
2044 const ExplodedNode<GRState>* PrevN,
Ted Kremenek8966bc12009-05-06 21:39:49 +00002045 BugReporterContext& BRC) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002046
Ted Kremenek8966bc12009-05-06 21:39:49 +00002047 // Check if the type state has changed.
2048 GRStateManager &StMgr = BRC.getStateManager();
Ted Kremenekc887d132009-04-29 18:50:19 +00002049 GRStateRef PrevSt(PrevN->getState(), StMgr);
2050 GRStateRef CurrSt(N->getState(), StMgr);
2051
2052 const RefVal* CurrT = CurrSt.get<RefBindings>(Sym);
2053 if (!CurrT) return NULL;
2054
2055 const RefVal& CurrV = *CurrT;
2056 const RefVal* PrevT = PrevSt.get<RefBindings>(Sym);
2057
2058 // Create a string buffer to constain all the useful things we want
2059 // to tell the user.
2060 std::string sbuf;
2061 llvm::raw_string_ostream os(sbuf);
2062
2063 // This is the allocation site since the previous node had no bindings
2064 // for this symbol.
2065 if (!PrevT) {
2066 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2067
2068 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2069 // Get the name of the callee (if it is available).
2070 SVal X = CurrSt.GetSValAsScalarOrLoc(CE->getCallee());
2071 if (const FunctionDecl* FD = X.getAsFunctionDecl())
2072 os << "Call to function '" << FD->getNameAsString() <<'\'';
2073 else
2074 os << "function call";
2075 }
2076 else {
2077 assert (isa<ObjCMessageExpr>(S));
2078 os << "Method";
2079 }
2080
2081 if (CurrV.getObjKind() == RetEffect::CF) {
2082 os << " returns a Core Foundation object with a ";
2083 }
2084 else {
2085 assert (CurrV.getObjKind() == RetEffect::ObjC);
2086 os << " returns an Objective-C object with a ";
2087 }
2088
2089 if (CurrV.isOwned()) {
2090 os << "+1 retain count (owning reference).";
2091
2092 if (static_cast<CFRefBug&>(getBugType()).getTF().isGCEnabled()) {
2093 assert(CurrV.getObjKind() == RetEffect::CF);
2094 os << " "
2095 "Core Foundation objects are not automatically garbage collected.";
2096 }
2097 }
2098 else {
2099 assert (CurrV.isNotOwned());
2100 os << "+0 retain count (non-owning reference).";
2101 }
2102
Ted Kremenek8966bc12009-05-06 21:39:49 +00002103 PathDiagnosticLocation Pos(S, BRC.getSourceManager());
Ted Kremenekc887d132009-04-29 18:50:19 +00002104 return new PathDiagnosticEventPiece(Pos, os.str());
2105 }
2106
2107 // Gather up the effects that were performed on the object at this
2108 // program point
2109 llvm::SmallVector<ArgEffect, 2> AEffects;
2110
Ted Kremenek8966bc12009-05-06 21:39:49 +00002111 if (const RetainSummary *Summ =
2112 TF.getSummaryOfNode(BRC.getNodeResolver().getOriginalNode(N))) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002113 // We only have summaries attached to nodes after evaluating CallExpr and
2114 // ObjCMessageExprs.
2115 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2116
2117 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2118 // Iterate through the parameter expressions and see if the symbol
2119 // was ever passed as an argument.
2120 unsigned i = 0;
2121
2122 for (CallExpr::arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
2123 AI!=AE; ++AI, ++i) {
2124
2125 // Retrieve the value of the argument. Is it the symbol
2126 // we are interested in?
2127 if (CurrSt.GetSValAsScalarOrLoc(*AI).getAsLocSymbol() != Sym)
2128 continue;
2129
2130 // We have an argument. Get the effect!
2131 AEffects.push_back(Summ->getArg(i));
2132 }
2133 }
2134 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
2135 if (Expr *receiver = ME->getReceiver())
2136 if (CurrSt.GetSValAsScalarOrLoc(receiver).getAsLocSymbol() == Sym) {
2137 // The symbol we are tracking is the receiver.
2138 AEffects.push_back(Summ->getReceiverEffect());
2139 }
2140 }
2141 }
2142
2143 do {
2144 // Get the previous type state.
2145 RefVal PrevV = *PrevT;
2146
2147 // Specially handle -dealloc.
2148 if (!TF.isGCEnabled() && contains(AEffects, Dealloc)) {
2149 // Determine if the object's reference count was pushed to zero.
2150 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2151 // We may not have transitioned to 'release' if we hit an error.
2152 // This case is handled elsewhere.
2153 if (CurrV.getKind() == RefVal::Released) {
Ted Kremenekf21332e2009-05-08 20:01:42 +00002154 assert(CurrV.getCombinedCounts() == 0);
Ted Kremenekc887d132009-04-29 18:50:19 +00002155 os << "Object released by directly sending the '-dealloc' message";
2156 break;
2157 }
2158 }
2159
2160 // Specially handle CFMakeCollectable and friends.
2161 if (contains(AEffects, MakeCollectable)) {
2162 // Get the name of the function.
2163 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2164 SVal X = CurrSt.GetSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee());
2165 const FunctionDecl* FD = X.getAsFunctionDecl();
2166 const std::string& FName = FD->getNameAsString();
2167
2168 if (TF.isGCEnabled()) {
2169 // Determine if the object's reference count was pushed to zero.
2170 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2171
2172 os << "In GC mode a call to '" << FName
2173 << "' decrements an object's retain count and registers the "
2174 "object with the garbage collector. ";
2175
2176 if (CurrV.getKind() == RefVal::Released) {
2177 assert(CurrV.getCount() == 0);
2178 os << "Since it now has a 0 retain count the object can be "
2179 "automatically collected by the garbage collector.";
2180 }
2181 else
2182 os << "An object must have a 0 retain count to be garbage collected. "
2183 "After this call its retain count is +" << CurrV.getCount()
2184 << '.';
2185 }
2186 else
2187 os << "When GC is not enabled a call to '" << FName
2188 << "' has no effect on its argument.";
2189
2190 // Nothing more to say.
2191 break;
2192 }
2193
2194 // Determine if the typestate has changed.
2195 if (!(PrevV == CurrV))
2196 switch (CurrV.getKind()) {
2197 case RefVal::Owned:
2198 case RefVal::NotOwned:
2199
Ted Kremenekf21332e2009-05-08 20:01:42 +00002200 if (PrevV.getCount() == CurrV.getCount()) {
2201 // Did an autorelease message get sent?
2202 if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
2203 return 0;
2204
2205 assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount());
2206 os << "Object added to autorelease pool.";
2207 break;
2208 }
Ted Kremenekc887d132009-04-29 18:50:19 +00002209
2210 if (PrevV.getCount() > CurrV.getCount())
2211 os << "Reference count decremented.";
2212 else
2213 os << "Reference count incremented.";
2214
2215 if (unsigned Count = CurrV.getCount())
2216 os << " The object now has a +" << Count << " retain count.";
2217
2218 if (PrevV.getKind() == RefVal::Released) {
2219 assert(TF.isGCEnabled() && CurrV.getCount() > 0);
2220 os << " The object is not eligible for garbage collection until the "
2221 "retain count reaches 0 again.";
2222 }
2223
2224 break;
2225
2226 case RefVal::Released:
2227 os << "Object released.";
2228 break;
2229
2230 case RefVal::ReturnedOwned:
2231 os << "Object returned to caller as an owning reference (single retain "
2232 "count transferred to caller).";
2233 break;
2234
2235 case RefVal::ReturnedNotOwned:
2236 os << "Object returned to caller with a +0 (non-owning) retain count.";
2237 break;
2238
2239 default:
2240 return NULL;
2241 }
2242
2243 // Emit any remaining diagnostics for the argument effects (if any).
2244 for (llvm::SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
2245 E=AEffects.end(); I != E; ++I) {
2246
2247 // A bunch of things have alternate behavior under GC.
2248 if (TF.isGCEnabled())
2249 switch (*I) {
2250 default: break;
2251 case Autorelease:
2252 os << "In GC mode an 'autorelease' has no effect.";
2253 continue;
2254 case IncRefMsg:
2255 os << "In GC mode the 'retain' message has no effect.";
2256 continue;
2257 case DecRefMsg:
2258 os << "In GC mode the 'release' message has no effect.";
2259 continue;
2260 }
2261 }
2262 } while(0);
2263
2264 if (os.str().empty())
2265 return 0; // We have nothing to say!
2266
2267 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
Ted Kremenek8966bc12009-05-06 21:39:49 +00002268 PathDiagnosticLocation Pos(S, BRC.getSourceManager());
Ted Kremenekc887d132009-04-29 18:50:19 +00002269 PathDiagnosticPiece* P = new PathDiagnosticEventPiece(Pos, os.str());
2270
2271 // Add the range by scanning the children of the statement for any bindings
2272 // to Sym.
2273 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I)
2274 if (Expr* Exp = dyn_cast_or_null<Expr>(*I))
2275 if (CurrSt.GetSValAsScalarOrLoc(Exp).getAsLocSymbol() == Sym) {
2276 P->addRange(Exp->getSourceRange());
2277 break;
2278 }
2279
2280 return P;
2281}
2282
2283namespace {
2284 class VISIBILITY_HIDDEN FindUniqueBinding :
2285 public StoreManager::BindingsHandler {
2286 SymbolRef Sym;
2287 const MemRegion* Binding;
2288 bool First;
2289
2290 public:
2291 FindUniqueBinding(SymbolRef sym) : Sym(sym), Binding(0), First(true) {}
2292
2293 bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
2294 SVal val) {
2295
2296 SymbolRef SymV = val.getAsSymbol();
2297 if (!SymV || SymV != Sym)
2298 return true;
2299
2300 if (Binding) {
2301 First = false;
2302 return false;
2303 }
2304 else
2305 Binding = R;
2306
2307 return true;
2308 }
2309
2310 operator bool() { return First && Binding; }
2311 const MemRegion* getRegion() { return Binding; }
2312 };
2313}
2314
2315static std::pair<const ExplodedNode<GRState>*,const MemRegion*>
2316GetAllocationSite(GRStateManager& StateMgr, const ExplodedNode<GRState>* N,
2317 SymbolRef Sym) {
2318
2319 // Find both first node that referred to the tracked symbol and the
2320 // memory location that value was store to.
2321 const ExplodedNode<GRState>* Last = N;
2322 const MemRegion* FirstBinding = 0;
2323
2324 while (N) {
2325 const GRState* St = N->getState();
2326 RefBindings B = St->get<RefBindings>();
2327
2328 if (!B.lookup(Sym))
2329 break;
2330
2331 FindUniqueBinding FB(Sym);
2332 StateMgr.iterBindings(St, FB);
2333 if (FB) FirstBinding = FB.getRegion();
2334
2335 Last = N;
2336 N = N->pred_empty() ? NULL : *(N->pred_begin());
2337 }
2338
2339 return std::make_pair(Last, FirstBinding);
2340}
2341
2342PathDiagnosticPiece*
Ted Kremenek8966bc12009-05-06 21:39:49 +00002343CFRefReport::getEndPath(BugReporterContext& BRC,
2344 const ExplodedNode<GRState>* EndN) {
2345 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenekc887d132009-04-29 18:50:19 +00002346 // assigned to different variables, etc.
Ted Kremenek8966bc12009-05-06 21:39:49 +00002347 BRC.addNotableSymbol(Sym);
2348 return RangedBugReport::getEndPath(BRC, EndN);
Ted Kremenekc887d132009-04-29 18:50:19 +00002349}
2350
2351PathDiagnosticPiece*
Ted Kremenek8966bc12009-05-06 21:39:49 +00002352CFRefLeakReport::getEndPath(BugReporterContext& BRC,
2353 const ExplodedNode<GRState>* EndN){
Ted Kremenekc887d132009-04-29 18:50:19 +00002354
Ted Kremenek8966bc12009-05-06 21:39:49 +00002355 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenekc887d132009-04-29 18:50:19 +00002356 // assigned to different variables, etc.
Ted Kremenek8966bc12009-05-06 21:39:49 +00002357 BRC.addNotableSymbol(Sym);
Ted Kremenekc887d132009-04-29 18:50:19 +00002358
2359 // We are reporting a leak. Walk up the graph to get to the first node where
2360 // the symbol appeared, and also get the first VarDecl that tracked object
2361 // is stored to.
2362 const ExplodedNode<GRState>* AllocNode = 0;
2363 const MemRegion* FirstBinding = 0;
2364
2365 llvm::tie(AllocNode, FirstBinding) =
Ted Kremenekf04dced2009-05-08 23:32:51 +00002366 GetAllocationSite(BRC.getStateManager(), EndN, Sym);
Ted Kremenekc887d132009-04-29 18:50:19 +00002367
2368 // Get the allocate site.
2369 assert(AllocNode);
2370 Stmt* FirstStmt = cast<PostStmt>(AllocNode->getLocation()).getStmt();
2371
Ted Kremenek8966bc12009-05-06 21:39:49 +00002372 SourceManager& SMgr = BRC.getSourceManager();
Ted Kremenekc887d132009-04-29 18:50:19 +00002373 unsigned AllocLine =SMgr.getInstantiationLineNumber(FirstStmt->getLocStart());
2374
2375 // Compute an actual location for the leak. Sometimes a leak doesn't
2376 // occur at an actual statement (e.g., transition between blocks; end
2377 // of function) so we need to walk the graph and compute a real location.
2378 const ExplodedNode<GRState>* LeakN = EndN;
2379 PathDiagnosticLocation L;
2380
2381 while (LeakN) {
2382 ProgramPoint P = LeakN->getLocation();
2383
2384 if (const PostStmt *PS = dyn_cast<PostStmt>(&P)) {
2385 L = PathDiagnosticLocation(PS->getStmt()->getLocStart(), SMgr);
2386 break;
2387 }
2388 else if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
2389 if (const Stmt* Term = BE->getSrc()->getTerminator()) {
2390 L = PathDiagnosticLocation(Term->getLocStart(), SMgr);
2391 break;
2392 }
2393 }
2394
2395 LeakN = LeakN->succ_empty() ? 0 : *(LeakN->succ_begin());
2396 }
2397
2398 if (!L.isValid()) {
Ted Kremenek8966bc12009-05-06 21:39:49 +00002399 const Decl &D = BRC.getCodeDecl();
2400 L = PathDiagnosticLocation(D.getBodyRBrace(BRC.getASTContext()), SMgr);
Ted Kremenekc887d132009-04-29 18:50:19 +00002401 }
2402
2403 std::string sbuf;
2404 llvm::raw_string_ostream os(sbuf);
2405
2406 os << "Object allocated on line " << AllocLine;
2407
2408 if (FirstBinding)
2409 os << " and stored into '" << FirstBinding->getString() << '\'';
2410
2411 // Get the retain count.
2412 const RefVal* RV = EndN->getState()->get<RefBindings>(Sym);
2413
2414 if (RV->getKind() == RefVal::ErrorLeakReturned) {
2415 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
2416 // ojbects. Only "copy", "alloc", "retain" and "new" transfer ownership
2417 // to the caller for NS objects.
Ted Kremenek8966bc12009-05-06 21:39:49 +00002418 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(BRC.getCodeDecl());
Ted Kremenekc887d132009-04-29 18:50:19 +00002419 os << " is returned from a method whose name ('"
Ted Kremeneka8833552009-04-29 23:03:22 +00002420 << MD.getSelector().getAsString()
Ted Kremenekc887d132009-04-29 18:50:19 +00002421 << "') does not contain 'copy' or otherwise starts with"
2422 " 'new' or 'alloc'. This violates the naming convention rules given"
Ted Kremenek8987a022009-04-29 22:25:52 +00002423 " in the Memory Management Guide for Cocoa (object leaked)";
Ted Kremenekc887d132009-04-29 18:50:19 +00002424 }
2425 else
2426 os << " is no longer referenced after this point and has a retain count of"
Ted Kremenek8987a022009-04-29 22:25:52 +00002427 " +" << RV->getCount() << " (object leaked)";
Ted Kremenekc887d132009-04-29 18:50:19 +00002428
2429 return new PathDiagnosticEventPiece(L, os.str());
2430}
2431
2432
2433CFRefLeakReport::CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2434 ExplodedNode<GRState> *n,
2435 SymbolRef sym, GRExprEngine& Eng)
2436: CFRefReport(D, tf, n, sym)
2437{
2438
2439 // Most bug reports are cached at the location where they occured.
2440 // With leaks, we want to unique them by the location where they were
2441 // allocated, and only report a single path. To do this, we need to find
2442 // the allocation site of a piece of tracked memory, which we do via a
2443 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2444 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2445 // that all ancestor nodes that represent the allocation site have the
2446 // same SourceLocation.
2447 const ExplodedNode<GRState>* AllocNode = 0;
2448
2449 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding.
Ted Kremenekf04dced2009-05-08 23:32:51 +00002450 GetAllocationSite(Eng.getStateManager(), getEndNode(), getSymbol());
Ted Kremenekc887d132009-04-29 18:50:19 +00002451
2452 // Get the SourceLocation for the allocation site.
2453 ProgramPoint P = AllocNode->getLocation();
2454 AllocSite = cast<PostStmt>(P).getStmt()->getLocStart();
2455
2456 // Fill in the description of the bug.
2457 Description.clear();
2458 llvm::raw_string_ostream os(Description);
2459 SourceManager& SMgr = Eng.getContext().getSourceManager();
2460 unsigned AllocLine = SMgr.getInstantiationLineNumber(AllocSite);
Ted Kremenekdd924e22009-05-02 19:05:19 +00002461 os << "Potential leak ";
2462 if (tf.isGCEnabled()) {
2463 os << "(when using garbage collection) ";
2464 }
2465 os << "of an object allocated on line " << AllocLine;
Ted Kremenekc887d132009-04-29 18:50:19 +00002466
2467 // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2468 if (AllocBinding)
2469 os << " and stored into '" << AllocBinding->getString() << '\'';
2470}
2471
2472//===----------------------------------------------------------------------===//
2473// Main checker logic.
2474//===----------------------------------------------------------------------===//
2475
Ted Kremenek553cf182008-06-25 21:21:56 +00002476/// GetReturnType - Used to get the return type of a message expression or
2477/// function call with the intention of affixing that type to a tracked symbol.
2478/// While the the return type can be queried directly from RetEx, when
2479/// invoking class methods we augment to the return type to be that of
2480/// a pointer to the class (as opposed it just being id).
2481static QualType GetReturnType(Expr* RetE, ASTContext& Ctx) {
2482
2483 QualType RetTy = RetE->getType();
2484
2485 // FIXME: We aren't handling id<...>.
Chris Lattner8b51fd72008-07-26 22:36:27 +00002486 const PointerType* PT = RetTy->getAsPointerType();
Ted Kremenek553cf182008-06-25 21:21:56 +00002487 if (!PT)
2488 return RetTy;
2489
2490 // If RetEx is not a message expression just return its type.
2491 // If RetEx is a message expression, return its types if it is something
2492 /// more specific than id.
2493
2494 ObjCMessageExpr* ME = dyn_cast<ObjCMessageExpr>(RetE);
2495
Steve Naroff389bf462009-02-12 17:52:19 +00002496 if (!ME || !Ctx.isObjCIdStructType(PT->getPointeeType()))
Ted Kremenek553cf182008-06-25 21:21:56 +00002497 return RetTy;
2498
2499 ObjCInterfaceDecl* D = ME->getClassInfo().first;
2500
2501 // At this point we know the return type of the message expression is id.
2502 // If we have an ObjCInterceDecl, we know this is a call to a class method
2503 // whose type we can resolve. In such cases, promote the return type to
2504 // Class*.
2505 return !D ? RetTy : Ctx.getPointerType(Ctx.getObjCInterfaceType(D));
2506}
2507
2508
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002509void CFRefCount::EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002510 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002511 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002512 Expr* Ex,
2513 Expr* Receiver,
Ted Kremenek7faca822009-05-04 04:57:00 +00002514 const RetainSummary& Summ,
Zhongxing Xu369f4472009-04-20 05:24:46 +00002515 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002516 ExplodedNode<GRState>* Pred) {
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002517
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00002518 // Get the state.
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002519 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenekf9790ae2008-10-24 20:32:50 +00002520 ASTContext& Ctx = Eng.getStateManager().getContext();
Ted Kremenek14993892008-05-06 02:41:27 +00002521
2522 // Evaluate the effect of the arguments.
Ted Kremenek9ed18e62008-04-16 04:28:53 +00002523 RefVal::Kind hasErr = (RefVal::Kind) 0;
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002524 unsigned idx = 0;
Ted Kremenekbcf50ad2008-04-11 18:40:51 +00002525 Expr* ErrorExpr = NULL;
Ted Kremenek2dabd432008-12-05 02:27:51 +00002526 SymbolRef ErrorSym = 0;
Ted Kremenekbcf50ad2008-04-11 18:40:51 +00002527
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002528 for (ExprIterator I = arg_beg; I != arg_end; ++I, ++idx) {
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00002529 SVal V = state.GetSValAsScalarOrLoc(*I);
Ted Kremenek94c96982009-03-03 22:06:47 +00002530 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00002531
Ted Kremeneke0e4ebf2009-03-26 03:35:11 +00002532 if (Sym)
Ted Kremenek4d3957d2009-02-24 19:15:11 +00002533 if (RefBindings::data_type* T = state.get<RefBindings>(Sym)) {
Ted Kremenek7faca822009-05-04 04:57:00 +00002534 state = Update(state, Sym, *T, Summ.getArg(idx), hasErr);
Ted Kremenek4d3957d2009-02-24 19:15:11 +00002535 if (hasErr) {
Ted Kremenekbcf50ad2008-04-11 18:40:51 +00002536 ErrorExpr = *I;
Ted Kremeneke8fdc832008-07-07 16:21:19 +00002537 ErrorSym = Sym;
Ted Kremenekbcf50ad2008-04-11 18:40:51 +00002538 break;
Ted Kremenek94c96982009-03-03 22:06:47 +00002539 }
2540 continue;
Ted Kremenek4d3957d2009-02-24 19:15:11 +00002541 }
Ted Kremenek070a8252008-07-09 18:11:16 +00002542
Ted Kremenek94c96982009-03-03 22:06:47 +00002543 if (isa<Loc>(V)) {
2544 if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(&V)) {
Ted Kremenek7faca822009-05-04 04:57:00 +00002545 if (Summ.getArg(idx) == DoNothingByRef)
Ted Kremenek070a8252008-07-09 18:11:16 +00002546 continue;
2547
2548 // Invalidate the value of the variable passed by reference.
Ted Kremenek8c5633e2008-07-03 23:26:32 +00002549
2550 // FIXME: Either this logic should also be replicated in GRSimpleVals
2551 // or should be pulled into a separate "constraint engine."
Ted Kremenek070a8252008-07-09 18:11:16 +00002552
Ted Kremenek8c5633e2008-07-03 23:26:32 +00002553 // FIXME: We can have collisions on the conjured symbol if the
2554 // expression *I also creates conjured symbols. We probably want
2555 // to identify conjured symbols by an expression pair: the enclosing
2556 // expression (the context) and the expression itself. This should
Ted Kremenek070a8252008-07-09 18:11:16 +00002557 // disambiguate conjured symbols.
Ted Kremenek9e240492008-10-04 05:50:14 +00002558
Ted Kremenek993f1c72008-10-17 20:28:54 +00002559 const TypedRegion* R = dyn_cast<TypedRegion>(MR->getRegion());
Zhongxing Xuf82af1e2009-04-29 02:30:09 +00002560
Ted Kremenek42530512009-05-06 18:19:24 +00002561 if (R) {
2562 // Are we dealing with an ElementRegion? If the element type is
2563 // a basic integer type (e.g., char, int) and the underying region
2564 // is also typed then strip off the ElementRegion.
2565 // FIXME: We really need to think about this for the general case
2566 // as sometimes we are reasoning about arrays and other times
2567 // about (char*), etc., is just a form of passing raw bytes.
2568 // e.g., void *p = alloca(); foo((char*)p);
2569 if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
2570 // Checking for 'integral type' is probably too promiscuous, but
2571 // we'll leave it in for now until we have a systematic way of
2572 // handling all of these cases. Eventually we need to come up
2573 // with an interface to StoreManager so that this logic can be
2574 // approriately delegated to the respective StoreManagers while
2575 // still allowing us to do checker-specific logic (e.g.,
2576 // invalidating reference counts), probably via callbacks.
2577 if (ER->getElementType()->isIntegralType())
2578 if (const TypedRegion *superReg =
2579 dyn_cast<TypedRegion>(ER->getSuperRegion()))
2580 R = superReg;
2581 // FIXME: What about layers of ElementRegions?
2582 }
2583
Ted Kremenek40e86d92008-12-18 23:34:57 +00002584 // Is the invalidated variable something that we were tracking?
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00002585 SymbolRef Sym = state.GetSValAsScalarOrLoc(R).getAsLocSymbol();
Ted Kremenek40e86d92008-12-18 23:34:57 +00002586
Ted Kremenekd104a092009-03-04 22:56:43 +00002587 // Remove any existing reference-count binding.
Ted Kremeneke0e4ebf2009-03-26 03:35:11 +00002588 if (Sym) state = state.remove<RefBindings>(Sym);
Ted Kremenek9e240492008-10-04 05:50:14 +00002589
Ted Kremenekd104a092009-03-04 22:56:43 +00002590 if (R->isBoundable(Ctx)) {
2591 // Set the value of the variable to be a conjured symbol.
2592 unsigned Count = Builder.getCurrentBlockCount();
2593 QualType T = R->getRValueType(Ctx);
2594
Zhongxing Xu51ae7902009-04-09 06:03:54 +00002595 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())){
Ted Kremenek8d7f5482009-04-09 22:22:44 +00002596 ValueManager &ValMgr = Eng.getValueManager();
2597 SVal V = ValMgr.getConjuredSymbolVal(*I, T, Count);
Zhongxing Xu51ae7902009-04-09 06:03:54 +00002598 state = state.BindLoc(Loc::MakeVal(R), V);
Ted Kremenekd104a092009-03-04 22:56:43 +00002599 }
2600 else if (const RecordType *RT = T->getAsStructureType()) {
2601 // Handle structs in a not so awesome way. Here we just
2602 // eagerly bind new symbols to the fields. In reality we
2603 // should have the store manager handle this. The idea is just
2604 // to prototype some basic functionality here. All of this logic
2605 // should one day soon just go away.
2606 const RecordDecl *RD = RT->getDecl()->getDefinition(Ctx);
2607
2608 // No record definition. There is nothing we can do.
2609 if (!RD)
2610 continue;
2611
2612 MemRegionManager &MRMgr = state.getManager().getRegionManager();
2613
2614 // Iterate through the fields and construct new symbols.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002615 for (RecordDecl::field_iterator FI=RD->field_begin(Ctx),
2616 FE=RD->field_end(Ctx); FI!=FE; ++FI) {
Ted Kremenekd104a092009-03-04 22:56:43 +00002617
2618 // For now just handle scalar fields.
2619 FieldDecl *FD = *FI;
2620 QualType FT = FD->getType();
2621
2622 if (Loc::IsLocType(FT) ||
Ted Kremenek8d7f5482009-04-09 22:22:44 +00002623 (FT->isIntegerType() && FT->isScalarType())) {
Ted Kremenekd104a092009-03-04 22:56:43 +00002624 const FieldRegion* FR = MRMgr.getFieldRegion(FD, R);
Ted Kremenek8d7f5482009-04-09 22:22:44 +00002625 ValueManager &ValMgr = Eng.getValueManager();
2626 SVal V = ValMgr.getConjuredSymbolVal(*I, FT, Count);
Zhongxing Xu6782f752009-04-09 06:32:20 +00002627 state = state.BindLoc(Loc::MakeVal(FR), V);
Ted Kremenekd104a092009-03-04 22:56:43 +00002628 }
2629 }
2630 }
2631 else {
2632 // Just blast away other values.
2633 state = state.BindLoc(*MR, UnknownVal());
2634 }
Ted Kremenekfd301942008-10-17 22:23:12 +00002635 }
Ted Kremenek9e240492008-10-04 05:50:14 +00002636 }
2637 else
Ted Kremeneka441b7e2008-11-12 19:22:09 +00002638 state = state.BindLoc(*MR, UnknownVal());
Ted Kremenek8c5633e2008-07-03 23:26:32 +00002639 }
2640 else {
2641 // Nuke all other arguments passed by reference.
Zhongxing Xu1c96b242008-10-17 05:57:07 +00002642 state = state.Unbind(cast<Loc>(V));
Ted Kremenek8c5633e2008-07-03 23:26:32 +00002643 }
Ted Kremenekb8873552008-04-11 20:51:02 +00002644 }
Zhongxing Xu1c96b242008-10-17 05:57:07 +00002645 else if (isa<nonloc::LocAsInteger>(V))
2646 state = state.Unbind(cast<nonloc::LocAsInteger>(V).getLoc());
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002647 }
Ted Kremenek9ed18e62008-04-16 04:28:53 +00002648
Ted Kremenek553cf182008-06-25 21:21:56 +00002649 // Evaluate the effect on the message receiver.
Ted Kremenek14993892008-05-06 02:41:27 +00002650 if (!ErrorExpr && Receiver) {
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00002651 SymbolRef Sym = state.GetSValAsScalarOrLoc(Receiver).getAsLocSymbol();
Ted Kremeneke0e4ebf2009-03-26 03:35:11 +00002652 if (Sym) {
Ted Kremenek4d3957d2009-02-24 19:15:11 +00002653 if (const RefVal* T = state.get<RefBindings>(Sym)) {
Ted Kremenek7faca822009-05-04 04:57:00 +00002654 state = Update(state, Sym, *T, Summ.getReceiverEffect(), hasErr);
Ted Kremenek4d3957d2009-02-24 19:15:11 +00002655 if (hasErr) {
Ted Kremenek14993892008-05-06 02:41:27 +00002656 ErrorExpr = Receiver;
Ted Kremeneke8fdc832008-07-07 16:21:19 +00002657 ErrorSym = Sym;
Ted Kremenek14993892008-05-06 02:41:27 +00002658 }
Ted Kremenek4d3957d2009-02-24 19:15:11 +00002659 }
Ted Kremenek14993892008-05-06 02:41:27 +00002660 }
2661 }
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002662
Ted Kremenek553cf182008-06-25 21:21:56 +00002663 // Process any errors.
Ted Kremenek9ed18e62008-04-16 04:28:53 +00002664 if (hasErr) {
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002665 ProcessNonLeakError(Dst, Builder, Ex, ErrorExpr, Pred, state,
Ted Kremenek8dd56462008-04-18 03:39:05 +00002666 hasErr, ErrorSym);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002667 return;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002668 }
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002669
Ted Kremenek70a733e2008-07-18 17:24:20 +00002670 // Consult the summary for the return value.
Ted Kremenek7faca822009-05-04 04:57:00 +00002671 RetEffect RE = Summ.getRetEffect();
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002672
2673 switch (RE.getKind()) {
2674 default:
2675 assert (false && "Unhandled RetEffect."); break;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002676
Ted Kremenekfd301942008-10-17 22:23:12 +00002677 case RetEffect::NoRet: {
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002678
Ted Kremenekf9561e52008-04-11 20:23:24 +00002679 // Make up a symbol for the return value (not reference counted).
Ted Kremenekb8873552008-04-11 20:51:02 +00002680 // FIXME: This is basically copy-and-paste from GRSimpleVals. We
2681 // should compose behavior, not copy it.
Ted Kremenekf9561e52008-04-11 20:23:24 +00002682
Ted Kremenekfd301942008-10-17 22:23:12 +00002683 // FIXME: We eventually should handle structs and other compound types
2684 // that are returned by value.
2685
2686 QualType T = Ex->getType();
2687
Ted Kremenek062e2f92008-11-13 06:10:40 +00002688 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())) {
Ted Kremenekf9561e52008-04-11 20:23:24 +00002689 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenek8d7f5482009-04-09 22:22:44 +00002690 ValueManager &ValMgr = Eng.getValueManager();
2691 SVal X = ValMgr.getConjuredSymbolVal(Ex, T, Count);
Ted Kremeneka441b7e2008-11-12 19:22:09 +00002692 state = state.BindExpr(Ex, X, false);
Ted Kremenekf9561e52008-04-11 20:23:24 +00002693 }
2694
Ted Kremenek940b1d82008-04-10 23:44:06 +00002695 break;
Ted Kremenekfd301942008-10-17 22:23:12 +00002696 }
Ted Kremenek940b1d82008-04-10 23:44:06 +00002697
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002698 case RetEffect::Alias: {
Ted Kremenek553cf182008-06-25 21:21:56 +00002699 unsigned idx = RE.getIndex();
Ted Kremenek55499762008-06-17 02:43:46 +00002700 assert (arg_end >= arg_beg);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002701 assert (idx < (unsigned) (arg_end - arg_beg));
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00002702 SVal V = state.GetSValAsScalarOrLoc(*(arg_beg+idx));
Ted Kremeneka441b7e2008-11-12 19:22:09 +00002703 state = state.BindExpr(Ex, V, false);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002704 break;
2705 }
2706
Ted Kremenek14993892008-05-06 02:41:27 +00002707 case RetEffect::ReceiverAlias: {
2708 assert (Receiver);
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00002709 SVal V = state.GetSValAsScalarOrLoc(Receiver);
Ted Kremeneka441b7e2008-11-12 19:22:09 +00002710 state = state.BindExpr(Ex, V, false);
Ted Kremenek14993892008-05-06 02:41:27 +00002711 break;
2712 }
2713
Ted Kremeneka7344702008-06-23 18:02:52 +00002714 case RetEffect::OwnedAllocatedSymbol:
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002715 case RetEffect::OwnedSymbol: {
2716 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenek044b6f02009-04-09 16:13:17 +00002717 ValueManager &ValMgr = Eng.getValueManager();
2718 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
2719 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
2720 state = state.set<RefBindings>(Sym, RefVal::makeOwned(RE.getObjKind(),
2721 RetT));
2722 state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenek25d01ba2009-03-09 22:46:49 +00002723
2724 // FIXME: Add a flag to the checker where allocations are assumed to
2725 // *not fail.
2726#if 0
Ted Kremenekb2bf7cd2009-01-28 22:27:59 +00002727 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) {
2728 bool isFeasible;
2729 state = state.Assume(loc::SymbolVal(Sym), true, isFeasible);
2730 assert(isFeasible && "Cannot assume fresh symbol is non-null.");
2731 }
Ted Kremenek25d01ba2009-03-09 22:46:49 +00002732#endif
Ted Kremeneka7344702008-06-23 18:02:52 +00002733
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002734 break;
2735 }
Ted Kremeneke798e7c2009-04-27 19:14:45 +00002736
2737 case RetEffect::GCNotOwnedSymbol:
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002738 case RetEffect::NotOwnedSymbol: {
2739 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenek044b6f02009-04-09 16:13:17 +00002740 ValueManager &ValMgr = Eng.getValueManager();
2741 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
2742 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
2743 state = state.set<RefBindings>(Sym, RefVal::makeNotOwned(RE.getObjKind(),
2744 RetT));
2745 state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002746 break;
2747 }
2748 }
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002749
Ted Kremenekf5b34b12009-02-18 02:00:25 +00002750 // Generate a sink node if we are at the end of a path.
2751 GRExprEngine::NodeTy *NewNode =
Ted Kremenek7faca822009-05-04 04:57:00 +00002752 Summ.isEndPath() ? Builder.MakeSinkNode(Dst, Ex, Pred, state)
2753 : Builder.MakeNode(Dst, Ex, Pred, state);
Ted Kremenekf5b34b12009-02-18 02:00:25 +00002754
2755 // Annotate the edge with summary we used.
Ted Kremenek7faca822009-05-04 04:57:00 +00002756 if (NewNode) SummaryLog[NewNode] = &Summ;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002757}
2758
2759
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002760void CFRefCount::EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002761 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002762 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu1c96b242008-10-17 05:57:07 +00002763 CallExpr* CE, SVal L,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002764 ExplodedNode<GRState>* Pred) {
Zhongxing Xu369f4472009-04-20 05:24:46 +00002765 const FunctionDecl* FD = L.getAsFunctionDecl();
Ted Kremenek7faca822009-05-04 04:57:00 +00002766 RetainSummary* Summ = !FD ? Summaries.getDefaultSummary()
Zhongxing Xu369f4472009-04-20 05:24:46 +00002767 : Summaries.getSummary(const_cast<FunctionDecl*>(FD));
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002768
Ted Kremenek7faca822009-05-04 04:57:00 +00002769 assert(Summ);
2770 EvalSummary(Dst, Eng, Builder, CE, 0, *Summ,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002771 CE->arg_begin(), CE->arg_end(), Pred);
Ted Kremenek2fff37e2008-03-06 00:08:09 +00002772}
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00002773
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002774void CFRefCount::EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek85348202008-04-15 23:44:31 +00002775 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002776 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek85348202008-04-15 23:44:31 +00002777 ObjCMessageExpr* ME,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002778 ExplodedNode<GRState>* Pred) {
Ted Kremenek7faca822009-05-04 04:57:00 +00002779 RetainSummary* Summ = 0;
Ted Kremenek9040c652008-05-01 21:31:50 +00002780
Ted Kremenek553cf182008-06-25 21:21:56 +00002781 if (Expr* Receiver = ME->getReceiver()) {
2782 // We need the type-information of the tracked receiver object
2783 // Retrieve it from the state.
2784 ObjCInterfaceDecl* ID = 0;
2785
2786 // FIXME: Wouldn't it be great if this code could be reduced? It's just
2787 // a chain of lookups.
Ted Kremenek8711c032009-04-29 05:04:30 +00002788 // FIXME: Is this really working as expected? There are cases where
2789 // we just use the 'ID' from the message expression.
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002790 const GRState* St = Builder.GetState(Pred);
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00002791 SVal V = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
Ted Kremenek553cf182008-06-25 21:21:56 +00002792
Ted Kremenek94c96982009-03-03 22:06:47 +00002793 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremeneke0e4ebf2009-03-26 03:35:11 +00002794 if (Sym) {
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002795 if (const RefVal* T = St->get<RefBindings>(Sym)) {
Ted Kremeneke8fdc832008-07-07 16:21:19 +00002796 QualType Ty = T->getType();
Ted Kremenek553cf182008-06-25 21:21:56 +00002797
2798 if (const PointerType* PT = Ty->getAsPointerType()) {
2799 QualType PointeeTy = PT->getPointeeType();
2800
2801 if (ObjCInterfaceType* IT = dyn_cast<ObjCInterfaceType>(PointeeTy))
2802 ID = IT->getDecl();
2803 }
2804 }
2805 }
2806
Ted Kremenekce8a41d2009-04-29 17:09:14 +00002807 // FIXME: The receiver could be a reference to a class, meaning that
2808 // we should use the class method.
2809 Summ = Summaries.getInstanceMethodSummary(ME, ID);
Ted Kremenekf9790ae2008-10-24 20:32:50 +00002810
Ted Kremenek896cd9d2008-10-23 01:56:15 +00002811 // Special-case: are we sending a mesage to "self"?
2812 // This is a hack. When we have full-IP this should be removed.
Ted Kremenek885c27b2009-05-04 05:31:22 +00002813 if (isa<ObjCMethodDecl>(&Eng.getGraph().getCodeDecl())) {
2814 if (Expr* Receiver = ME->getReceiver()) {
2815 SVal X = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
2816 if (loc::MemRegionVal* L = dyn_cast<loc::MemRegionVal>(&X))
2817 if (L->getRegion() == Eng.getStateManager().getSelfRegion(St)) {
2818 // Update the summary to make the default argument effect
2819 // 'StopTracking'.
2820 Summ = Summaries.copySummary(Summ);
2821 Summ->setDefaultArgEffect(StopTracking);
2822 }
Ted Kremenek896cd9d2008-10-23 01:56:15 +00002823 }
2824 }
Ted Kremenek553cf182008-06-25 21:21:56 +00002825 }
Ted Kremenek9ed18e62008-04-16 04:28:53 +00002826 else
Ted Kremenekf9df1362009-04-23 21:25:57 +00002827 Summ = Summaries.getClassMethodSummary(ME);
Ted Kremenek9ed18e62008-04-16 04:28:53 +00002828
Ted Kremenek7faca822009-05-04 04:57:00 +00002829 if (!Summ)
2830 Summ = Summaries.getDefaultSummary();
Ted Kremenekde4d5332009-04-24 17:50:11 +00002831
Ted Kremenek7faca822009-05-04 04:57:00 +00002832 EvalSummary(Dst, Eng, Builder, ME, ME->getReceiver(), *Summ,
Ted Kremenekb3095252008-05-06 04:20:12 +00002833 ME->arg_begin(), ME->arg_end(), Pred);
Ted Kremenek85348202008-04-15 23:44:31 +00002834}
Ted Kremenek5216ad72009-02-14 03:16:10 +00002835
2836namespace {
2837class VISIBILITY_HIDDEN StopTrackingCallback : public SymbolVisitor {
2838 GRStateRef state;
2839public:
2840 StopTrackingCallback(GRStateRef st) : state(st) {}
2841 GRStateRef getState() { return state; }
2842
2843 bool VisitSymbol(SymbolRef sym) {
2844 state = state.remove<RefBindings>(sym);
2845 return true;
2846 }
Ted Kremenekb3095252008-05-06 04:20:12 +00002847
Ted Kremenek5216ad72009-02-14 03:16:10 +00002848 const GRState* getState() const { return state.getState(); }
2849};
2850} // end anonymous namespace
2851
2852
Ted Kremenek41573eb2009-02-14 01:43:44 +00002853void CFRefCount::EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val) {
Ted Kremenek41573eb2009-02-14 01:43:44 +00002854 // Are we storing to something that causes the value to "escape"?
Ted Kremenek13922612008-04-16 20:40:59 +00002855 bool escapes = false;
2856
Ted Kremeneka496d162008-10-18 03:49:51 +00002857 // A value escapes in three possible cases (this may change):
2858 //
2859 // (1) we are binding to something that is not a memory region.
2860 // (2) we are binding to a memregion that does not have stack storage
2861 // (3) we are binding to a memregion with stack storage that the store
Ted Kremenek41573eb2009-02-14 01:43:44 +00002862 // does not understand.
Ted Kremenek41573eb2009-02-14 01:43:44 +00002863 GRStateRef state = B.getState();
Ted Kremeneka496d162008-10-18 03:49:51 +00002864
Ted Kremenek41573eb2009-02-14 01:43:44 +00002865 if (!isa<loc::MemRegionVal>(location))
Ted Kremenek13922612008-04-16 20:40:59 +00002866 escapes = true;
Ted Kremenek9e240492008-10-04 05:50:14 +00002867 else {
Ted Kremenek41573eb2009-02-14 01:43:44 +00002868 const MemRegion* R = cast<loc::MemRegionVal>(location).getRegion();
2869 escapes = !B.getStateManager().hasStackStorage(R);
Ted Kremeneka496d162008-10-18 03:49:51 +00002870
2871 if (!escapes) {
2872 // To test (3), generate a new state with the binding removed. If it is
2873 // the same state, then it escapes (since the store cannot represent
2874 // the binding).
Ted Kremenek41573eb2009-02-14 01:43:44 +00002875 escapes = (state == (state.BindLoc(cast<Loc>(location), UnknownVal())));
Ted Kremeneka496d162008-10-18 03:49:51 +00002876 }
Ted Kremenek9e240492008-10-04 05:50:14 +00002877 }
Ted Kremenek41573eb2009-02-14 01:43:44 +00002878
Ted Kremenek5216ad72009-02-14 03:16:10 +00002879 // If our store can represent the binding and we aren't storing to something
2880 // that doesn't have local storage then just return and have the simulation
2881 // state continue as is.
2882 if (!escapes)
2883 return;
Ted Kremeneka496d162008-10-18 03:49:51 +00002884
Ted Kremenek5216ad72009-02-14 03:16:10 +00002885 // Otherwise, find all symbols referenced by 'val' that we are tracking
2886 // and stop tracking them.
2887 B.MakeNode(state.scanReachableSymbols<StopTrackingCallback>(val).getState());
Ted Kremenekdb863712008-04-16 22:32:20 +00002888}
2889
Ted Kremenek652adc62008-04-24 23:57:27 +00002890
Ted Kremenek4fd88972008-04-17 18:12:53 +00002891 // Return statements.
2892
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002893void CFRefCount::EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4fd88972008-04-17 18:12:53 +00002894 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002895 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4fd88972008-04-17 18:12:53 +00002896 ReturnStmt* S,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002897 ExplodedNode<GRState>* Pred) {
Ted Kremenek4fd88972008-04-17 18:12:53 +00002898
2899 Expr* RetE = S->getRetValue();
Ted Kremenek94c96982009-03-03 22:06:47 +00002900 if (!RetE)
Ted Kremenek4fd88972008-04-17 18:12:53 +00002901 return;
2902
Ted Kremenek94c96982009-03-03 22:06:47 +00002903 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00002904 SymbolRef Sym = state.GetSValAsScalarOrLoc(RetE).getAsLocSymbol();
Ted Kremenek94c96982009-03-03 22:06:47 +00002905
Ted Kremeneke0e4ebf2009-03-26 03:35:11 +00002906 if (!Sym)
Ted Kremenek94c96982009-03-03 22:06:47 +00002907 return;
Ted Kremenekf04dced2009-05-08 23:32:51 +00002908
Ted Kremenek4fd88972008-04-17 18:12:53 +00002909 // Get the reference count binding (if any).
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002910 const RefVal* T = state.get<RefBindings>(Sym);
Ted Kremenek4fd88972008-04-17 18:12:53 +00002911
2912 if (!T)
2913 return;
2914
Ted Kremenekf04dced2009-05-08 23:32:51 +00002915 // Update the autorelease counts.
2916 static unsigned autoreleasetag = 0;
2917 GenericNodeBuilder Bd(Builder, S, &autoreleasetag);
2918 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state , Bd, Pred, Sym, *T);
2919
2920 // Get the updated binding.
2921 T = state.get<RefBindings>(Sym);
2922 assert(T);
2923
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002924 // Change the reference count.
Ted Kremeneke8fdc832008-07-07 16:21:19 +00002925 RefVal X = *T;
Ted Kremenek4fd88972008-04-17 18:12:53 +00002926
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002927 switch (X.getKind()) {
Ted Kremenek4fd88972008-04-17 18:12:53 +00002928 case RefVal::Owned: {
2929 unsigned cnt = X.getCount();
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00002930 assert (cnt > 0);
2931 X = RefVal::makeReturnedOwned(cnt - 1);
Ted Kremenek4fd88972008-04-17 18:12:53 +00002932 break;
2933 }
2934
2935 case RefVal::NotOwned: {
2936 unsigned cnt = X.getCount();
2937 X = cnt ? RefVal::makeReturnedOwned(cnt - 1)
2938 : RefVal::makeReturnedNotOwned();
2939 break;
2940 }
2941
2942 default:
Ted Kremenek4fd88972008-04-17 18:12:53 +00002943 return;
2944 }
2945
2946 // Update the binding.
Ted Kremenekb9d17f92008-08-17 03:20:02 +00002947 state = state.set<RefBindings>(Sym, X);
Ted Kremenekc887d132009-04-29 18:50:19 +00002948 Pred = Builder.MakeNode(Dst, S, Pred, state);
2949
Ted Kremenek9f246b62009-04-30 05:51:50 +00002950 // Did we cache out?
2951 if (!Pred)
2952 return;
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00002953
Ted Kremenekc887d132009-04-29 18:50:19 +00002954 // Any leaks or other errors?
2955 if (X.isReturnedOwned() && X.getCount() == 0) {
2956 const Decl *CD = &Eng.getStateManager().getCodeDecl();
2957
Ted Kremeneka8833552009-04-29 23:03:22 +00002958 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
Ted Kremenek7faca822009-05-04 04:57:00 +00002959 const RetainSummary &Summ = *Summaries.getMethodSummary(MD);
2960 if (!Summ.getRetEffect().isOwned()) {
Ted Kremenekc887d132009-04-29 18:50:19 +00002961 static int ReturnOwnLeakTag = 0;
2962 state = state.set<RefBindings>(Sym, X ^ RefVal::ErrorLeakReturned);
Ted Kremenekc887d132009-04-29 18:50:19 +00002963 // Generate an error node.
Ted Kremenek9f246b62009-04-30 05:51:50 +00002964 if (ExplodedNode<GRState> *N =
2965 Builder.generateNode(PostStmt(S, &ReturnOwnLeakTag), state, Pred)) {
2966 CFRefLeakReport *report =
2967 new CFRefLeakReport(*static_cast<CFRefBug*>(leakAtReturn), *this,
2968 N, Sym, Eng);
2969 BR->EmitReport(report);
2970 }
Ted Kremenekc887d132009-04-29 18:50:19 +00002971 }
2972 }
2973 }
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00002974
2975
Ted Kremenek4fd88972008-04-17 18:12:53 +00002976}
2977
Ted Kremenekcb612922008-04-18 19:23:43 +00002978// Assumptions.
2979
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002980const GRState* CFRefCount::EvalAssume(GRStateManager& VMgr,
2981 const GRState* St,
Zhongxing Xu1c96b242008-10-17 05:57:07 +00002982 SVal Cond, bool Assumption,
Ted Kremenek4323a572008-07-10 22:03:41 +00002983 bool& isFeasible) {
Ted Kremenekcb612922008-04-18 19:23:43 +00002984
2985 // FIXME: We may add to the interface of EvalAssume the list of symbols
2986 // whose assumptions have changed. For now we just iterate through the
2987 // bindings and check if any of the tracked symbols are NULL. This isn't
2988 // too bad since the number of symbols we will track in practice are
2989 // probably small and EvalAssume is only called at branches and a few
2990 // other places.
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002991 RefBindings B = St->get<RefBindings>();
Ted Kremenekcb612922008-04-18 19:23:43 +00002992
2993 if (B.isEmpty())
2994 return St;
2995
2996 bool changed = false;
Ted Kremenekb9d17f92008-08-17 03:20:02 +00002997
2998 GRStateRef state(St, VMgr);
2999 RefBindings::Factory& RefBFactory = state.get_context<RefBindings>();
Ted Kremenekcb612922008-04-18 19:23:43 +00003000
3001 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
Ted Kremenekcb612922008-04-18 19:23:43 +00003002 // Check if the symbol is null (or equal to any constant).
3003 // If this is the case, stop tracking the symbol.
Zhongxing Xu39cfed32008-08-29 14:52:36 +00003004 if (VMgr.getSymVal(St, I.getKey())) {
Ted Kremenekcb612922008-04-18 19:23:43 +00003005 changed = true;
3006 B = RefBFactory.Remove(B, I.getKey());
3007 }
3008 }
3009
Ted Kremenekb9d17f92008-08-17 03:20:02 +00003010 if (changed)
3011 state = state.set<RefBindings>(B);
Ted Kremenekcb612922008-04-18 19:23:43 +00003012
Ted Kremenek72cd17f2008-08-14 21:16:54 +00003013 return state;
Ted Kremenekcb612922008-04-18 19:23:43 +00003014}
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00003015
Ted Kremenek4d3957d2009-02-24 19:15:11 +00003016GRStateRef CFRefCount::Update(GRStateRef state, SymbolRef sym,
3017 RefVal V, ArgEffect E,
3018 RefVal::Kind& hasErr) {
Ted Kremenek1c512f52009-02-18 18:54:33 +00003019
3020 // In GC mode [... release] and [... retain] do nothing.
3021 switch (E) {
3022 default: break;
3023 case IncRefMsg: E = isGCEnabled() ? DoNothing : IncRef; break;
3024 case DecRefMsg: E = isGCEnabled() ? DoNothing : DecRef; break;
Ted Kremenek27019002009-02-18 21:57:45 +00003025 case MakeCollectable: E = isGCEnabled() ? DecRef : DoNothing; break;
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00003026 case NewAutoreleasePool: E = isGCEnabled() ? DoNothing :
3027 NewAutoreleasePool; break;
Ted Kremenek1c512f52009-02-18 18:54:33 +00003028 }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00003029
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003030 // Handle all use-after-releases.
3031 if (!isGCEnabled() && V.getKind() == RefVal::Released) {
3032 V = V ^ RefVal::ErrorUseAfterRelease;
3033 hasErr = V.getKind();
3034 return state.set<RefBindings>(sym, V);
3035 }
3036
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003037 switch (E) {
3038 default:
3039 assert (false && "Unhandled CFRef transition.");
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003040
3041 case Dealloc:
3042 // Any use of -dealloc in GC is *bad*.
3043 if (isGCEnabled()) {
3044 V = V ^ RefVal::ErrorDeallocGC;
3045 hasErr = V.getKind();
3046 break;
3047 }
3048
3049 switch (V.getKind()) {
3050 default:
3051 assert(false && "Invalid case.");
3052 case RefVal::Owned:
3053 // The object immediately transitions to the released state.
3054 V = V ^ RefVal::Released;
3055 V.clearCounts();
3056 return state.set<RefBindings>(sym, V);
3057 case RefVal::NotOwned:
3058 V = V ^ RefVal::ErrorDeallocNotOwned;
3059 hasErr = V.getKind();
3060 break;
3061 }
3062 break;
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00003063
Ted Kremenek35790732009-02-25 23:11:49 +00003064 case NewAutoreleasePool:
3065 assert(!isGCEnabled());
3066 return state.add<AutoreleaseStack>(sym);
3067
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00003068 case MayEscape:
3069 if (V.getKind() == RefVal::Owned) {
Ted Kremenek553cf182008-06-25 21:21:56 +00003070 V = V ^ RefVal::NotOwned;
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00003071 break;
3072 }
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003073
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00003074 // Fall-through.
Ted Kremenek6c4becb2009-02-25 02:54:57 +00003075
Ted Kremenek070a8252008-07-09 18:11:16 +00003076 case DoNothingByRef:
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003077 case DoNothing:
Ted Kremenek4d3957d2009-02-24 19:15:11 +00003078 return state;
Ted Kremeneke19f4492008-06-30 16:57:41 +00003079
Ted Kremenekabf43972009-01-28 21:44:40 +00003080 case Autorelease:
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003081 if (isGCEnabled())
3082 return state;
Ted Kremenek7037ab82009-03-20 17:34:15 +00003083
3084 // Update the autorelease counts.
3085 state = SendAutorelease(state, ARCountFactory, sym);
Ted Kremenekf21332e2009-05-08 20:01:42 +00003086 V = V.autorelease();
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003087
Ted Kremenek14993892008-05-06 02:41:27 +00003088 case StopTracking:
Ted Kremenek4d3957d2009-02-24 19:15:11 +00003089 return state.remove<RefBindings>(sym);
Ted Kremenek9e476de2008-08-12 18:30:56 +00003090
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003091 case IncRef:
3092 switch (V.getKind()) {
3093 default:
3094 assert(false);
3095
3096 case RefVal::Owned:
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003097 case RefVal::NotOwned:
Ted Kremenek553cf182008-06-25 21:21:56 +00003098 V = V + 1;
Ted Kremenek9e476de2008-08-12 18:30:56 +00003099 break;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003100 case RefVal::Released:
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003101 // Non-GC cases are handled above.
3102 assert(isGCEnabled());
3103 V = (V ^ RefVal::Owned) + 1;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003104 break;
Ted Kremenek9e476de2008-08-12 18:30:56 +00003105 }
Ted Kremenek940b1d82008-04-10 23:44:06 +00003106 break;
3107
Ted Kremenek553cf182008-06-25 21:21:56 +00003108 case SelfOwn:
3109 V = V ^ RefVal::NotOwned;
Ted Kremenek1c512f52009-02-18 18:54:33 +00003110 // Fall-through.
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003111 case DecRef:
3112 switch (V.getKind()) {
3113 default:
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003114 // case 'RefVal::Released' handled above.
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003115 assert (false);
Ted Kremenek9e476de2008-08-12 18:30:56 +00003116
Ted Kremenek553cf182008-06-25 21:21:56 +00003117 case RefVal::Owned:
Ted Kremenekbb8c5aa2009-02-18 22:57:22 +00003118 assert(V.getCount() > 0);
3119 if (V.getCount() == 1) V = V ^ RefVal::Released;
3120 V = V - 1;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003121 break;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003122
Ted Kremenek553cf182008-06-25 21:21:56 +00003123 case RefVal::NotOwned:
3124 if (V.getCount() > 0)
3125 V = V - 1;
Ted Kremenek61b9f872008-04-10 23:09:18 +00003126 else {
Ted Kremenek553cf182008-06-25 21:21:56 +00003127 V = V ^ RefVal::ErrorReleaseNotOwned;
Ted Kremenek9ed18e62008-04-16 04:28:53 +00003128 hasErr = V.getKind();
Ted Kremenek9e476de2008-08-12 18:30:56 +00003129 }
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003130 break;
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003131
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003132 case RefVal::Released:
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003133 // Non-GC cases are handled above.
3134 assert(isGCEnabled());
Ted Kremenek553cf182008-06-25 21:21:56 +00003135 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek9ed18e62008-04-16 04:28:53 +00003136 hasErr = V.getKind();
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003137 break;
Ted Kremenek9e476de2008-08-12 18:30:56 +00003138 }
Ted Kremenek940b1d82008-04-10 23:44:06 +00003139 break;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00003140 }
Ted Kremenek4d3957d2009-02-24 19:15:11 +00003141 return state.set<RefBindings>(sym, V);
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00003142}
3143
Ted Kremenekfa34b332008-04-09 01:10:13 +00003144//===----------------------------------------------------------------------===//
Ted Kremenekcf701772009-02-05 06:50:21 +00003145// Handle dead symbols and end-of-path.
3146//===----------------------------------------------------------------------===//
3147
Ted Kremenekf04dced2009-05-08 23:32:51 +00003148std::pair<ExplodedNode<GRState>*, GRStateRef>
3149CFRefCount::HandleAutoreleaseCounts(GRStateRef state, GenericNodeBuilder Bd,
3150 ExplodedNode<GRState>* Pred,
3151 SymbolRef Sym, RefVal V) {
3152
3153 return std::make_pair(Pred, state);
3154}
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003155
3156GRStateRef
3157CFRefCount::HandleSymbolDeath(GRStateRef state, SymbolRef sid, RefVal V,
3158 llvm::SmallVectorImpl<SymbolRef> &Leaked) {
3159
3160 bool hasLeak = V.isOwned() ||
3161 ((V.isNotOwned() || V.isReturnedOwned()) && V.getCount() > 0);
3162
3163 if (!hasLeak)
3164 return state.remove<RefBindings>(sid);
3165
3166 Leaked.push_back(sid);
3167 return state.set<RefBindings>(sid, V ^ RefVal::ErrorLeak);
3168}
3169
3170ExplodedNode<GRState>*
3171CFRefCount::ProcessLeaks(GRStateRef state,
3172 llvm::SmallVectorImpl<SymbolRef> &Leaked,
3173 GenericNodeBuilder &Builder,
3174 GRExprEngine& Eng,
3175 ExplodedNode<GRState> *Pred) {
3176
3177 if (Leaked.empty())
3178 return Pred;
3179
Ted Kremenekf04dced2009-05-08 23:32:51 +00003180 // Generate an intermediate node representing the leak point.
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003181 ExplodedNode<GRState> *N = Builder.MakeNode(state, Pred);
3182
3183 if (N) {
3184 for (llvm::SmallVectorImpl<SymbolRef>::iterator
3185 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3186
3187 CFRefBug *BT = static_cast<CFRefBug*>(Pred ? leakWithinFunction
3188 : leakAtReturn);
3189 assert(BT && "BugType not initialized.");
3190 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N, *I, Eng);
3191 BR->EmitReport(report);
3192 }
3193 }
3194
3195 return N;
3196}
3197
Ted Kremenekcf701772009-02-05 06:50:21 +00003198void CFRefCount::EvalEndPath(GRExprEngine& Eng,
3199 GREndPathNodeBuilder<GRState>& Builder) {
3200
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003201 GRStateRef state(Builder.getState(), Eng.getStateManager());
Ted Kremenekf04dced2009-05-08 23:32:51 +00003202 GenericNodeBuilder Bd(Builder);
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003203 RefBindings B = state.get<RefBindings>();
Ted Kremenekf04dced2009-05-08 23:32:51 +00003204 ExplodedNode<GRState> *Pred = 0;
3205
3206 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
3207 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state, Bd, Pred,
3208 (*I).first,
3209 (*I).second);
3210 }
3211
3212 B = state.get<RefBindings>();
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003213 llvm::SmallVector<SymbolRef, 10> Leaked;
Ted Kremenekcf701772009-02-05 06:50:21 +00003214
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003215 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I)
3216 state = HandleSymbolDeath(state, (*I).first, (*I).second, Leaked);
3217
Ted Kremenekf04dced2009-05-08 23:32:51 +00003218 ProcessLeaks(state, Leaked, Bd, Eng, Pred);
Ted Kremenekcf701772009-02-05 06:50:21 +00003219}
3220
3221void CFRefCount::EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
3222 GRExprEngine& Eng,
3223 GRStmtNodeBuilder<GRState>& Builder,
3224 ExplodedNode<GRState>* Pred,
3225 Stmt* S,
3226 const GRState* St,
3227 SymbolReaper& SymReaper) {
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003228
3229 GRStateRef state(St, Eng.getStateManager());
Ted Kremenekf04dced2009-05-08 23:32:51 +00003230 RefBindings B = state.get<RefBindings>();
3231
3232 // Update counts from autorelease pools
3233 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3234 E = SymReaper.dead_end(); I != E; ++I) {
3235 SymbolRef Sym = *I;
3236 if (const RefVal* T = B.lookup(Sym)){
3237 // Use the symbol as the tag.
3238 // FIXME: This might not be as unique as we would like.
3239 GenericNodeBuilder Bd(Builder, S, Sym);
3240 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state, Bd, Pred, Sym,
3241 *T);
3242 }
3243 }
3244
3245 B = state.get<RefBindings>();
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003246 llvm::SmallVector<SymbolRef, 10> Leaked;
Ted Kremenekcf701772009-02-05 06:50:21 +00003247
3248 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003249 E = SymReaper.dead_end(); I != E; ++I) {
3250 if (const RefVal* T = B.lookup(*I))
3251 state = HandleSymbolDeath(state, *I, *T, Leaked);
3252 }
Ted Kremenekcf701772009-02-05 06:50:21 +00003253
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003254 static unsigned LeakPPTag = 0;
Ted Kremenekf04dced2009-05-08 23:32:51 +00003255 {
3256 GenericNodeBuilder Bd(Builder, S, &LeakPPTag);
3257 Pred = ProcessLeaks(state, Leaked, Bd, Eng, Pred);
3258 }
Ted Kremenekcf701772009-02-05 06:50:21 +00003259
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003260 // Did we cache out?
3261 if (!Pred)
3262 return;
Ted Kremenek33b6f632009-02-19 23:47:02 +00003263
3264 // Now generate a new node that nukes the old bindings.
Ted Kremenek33b6f632009-02-19 23:47:02 +00003265 RefBindings::Factory& F = state.get_context<RefBindings>();
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003266
Ted Kremenek33b6f632009-02-19 23:47:02 +00003267 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
Ted Kremenek9d9d3a62009-05-08 23:09:42 +00003268 E = SymReaper.dead_end(); I!=E; ++I) B = F.Remove(B, *I);
3269
Ted Kremenek33b6f632009-02-19 23:47:02 +00003270 state = state.set<RefBindings>(B);
3271 Builder.MakeNode(Dst, S, Pred, state);
Ted Kremenekcf701772009-02-05 06:50:21 +00003272}
3273
3274void CFRefCount::ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
3275 GRStmtNodeBuilder<GRState>& Builder,
3276 Expr* NodeExpr, Expr* ErrorExpr,
3277 ExplodedNode<GRState>* Pred,
3278 const GRState* St,
3279 RefVal::Kind hasErr, SymbolRef Sym) {
3280 Builder.BuildSinks = true;
3281 GRExprEngine::NodeTy* N = Builder.MakeNode(Dst, NodeExpr, Pred, St);
3282
3283 if (!N) return;
3284
3285 CFRefBug *BT = 0;
3286
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003287 switch (hasErr) {
3288 default:
3289 assert(false && "Unhandled error.");
3290 return;
3291 case RefVal::ErrorUseAfterRelease:
3292 BT = static_cast<CFRefBug*>(useAfterRelease);
3293 break;
3294 case RefVal::ErrorReleaseNotOwned:
3295 BT = static_cast<CFRefBug*>(releaseNotOwned);
3296 break;
3297 case RefVal::ErrorDeallocGC:
3298 BT = static_cast<CFRefBug*>(deallocGC);
3299 break;
3300 case RefVal::ErrorDeallocNotOwned:
3301 BT = static_cast<CFRefBug*>(deallocNotOwned);
3302 break;
Ted Kremenekcf701772009-02-05 06:50:21 +00003303 }
3304
Ted Kremenekfe9e5432009-02-18 03:48:14 +00003305 CFRefReport *report = new CFRefReport(*BT, *this, N, Sym);
Ted Kremenekcf701772009-02-05 06:50:21 +00003306 report->addRange(ErrorExpr->getSourceRange());
3307 BR->EmitReport(report);
3308}
3309
3310//===----------------------------------------------------------------------===//
Ted Kremenekd71ed262008-04-10 22:16:52 +00003311// Transfer function creation for external clients.
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00003312//===----------------------------------------------------------------------===//
3313
Ted Kremenek072192b2008-04-30 23:47:44 +00003314GRTransferFuncs* clang::MakeCFRefCountTF(ASTContext& Ctx, bool GCEnabled,
3315 const LangOptions& lopts) {
Ted Kremenek78d46242008-07-22 16:21:24 +00003316 return new CFRefCount(Ctx, GCEnabled, lopts);
Ted Kremenek3ea0b6a2008-04-10 22:58:08 +00003317}