blob: 0e4d660f35af9ff54f4ab027e0f1ff4443dfca5e [file] [log] [blame]
Chris Lattnerbe1a7a02008-03-15 23:59:48 +00001// CFRefCount.cpp - Transfer functions for tracking simple values -*- C++ -*--//
Ted Kremenek827f93b2008-03-06 00:08:09 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Gabor Greif2224fcb2008-03-06 10:40:09 +000010// This file defines the methods for CFRefCount, which implements
Ted Kremenek827f93b2008-03-06 00:08:09 +000011// a reference count checker for Core Foundation (Mac OS X).
12//
13//===----------------------------------------------------------------------===//
14
Ted Kremeneka7338b42008-03-11 06:39:11 +000015#include "GRSimpleVals.h"
Ted Kremenekfe30beb2008-04-30 23:47:44 +000016#include "clang/Basic/LangOptions.h"
Ted Kremenekfe4d2312008-05-01 23:13:35 +000017#include "clang/Basic/SourceManager.h"
Ted Kremeneka42be302009-02-14 01:43:44 +000018#include "clang/Analysis/PathSensitive/GRExprEngineBuilders.h"
Ted Kremenek91781202008-08-17 03:20:02 +000019#include "clang/Analysis/PathSensitive/GRStateTrait.h"
Ted Kremenekdd0126b2008-03-31 18:26:32 +000020#include "clang/Analysis/PathDiagnostic.h"
Ted Kremenek827f93b2008-03-06 00:08:09 +000021#include "clang/Analysis/LocalCheckers.h"
Ted Kremenek10fe66d2008-04-09 01:10:13 +000022#include "clang/Analysis/PathDiagnostic.h"
23#include "clang/Analysis/PathSensitive/BugReporter.h"
Ted Kremenek2ddb4b22009-02-14 03:16:10 +000024#include "clang/Analysis/PathSensitive/SymbolManager.h"
Ted Kremenekc3bc6c82009-05-06 21:39:49 +000025#include "clang/AST/DeclObjC.h"
Ted Kremeneka7338b42008-03-11 06:39:11 +000026#include "llvm/ADT/DenseMap.h"
27#include "llvm/ADT/FoldingSet.h"
28#include "llvm/ADT/ImmutableMap.h"
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +000029#include "llvm/ADT/ImmutableList.h"
Ted Kremenek2ac4ba62008-05-07 18:36:45 +000030#include "llvm/ADT/StringExtras.h"
Ted Kremenek10fe66d2008-04-09 01:10:13 +000031#include "llvm/Support/Compiler.h"
Ted Kremenekd7e26782008-05-16 18:33:44 +000032#include "llvm/ADT/STLExtras.h"
Ted Kremenek3b11f7a2008-03-11 19:44:10 +000033#include <ostream>
Ted Kremenek9449ca92008-08-12 20:41:56 +000034#include <stdarg.h>
Ted Kremenek827f93b2008-03-06 00:08:09 +000035
36using namespace clang;
Ted Kremenekb6f09542008-10-24 21:18:08 +000037
38//===----------------------------------------------------------------------===//
39// Utility functions.
40//===----------------------------------------------------------------------===//
41
Ted Kremenekb6f09542008-10-24 21:18:08 +000042// The "fundamental rule" for naming conventions of methods:
43// (url broken into two lines)
44// http://developer.apple.com/documentation/Cocoa/Conceptual/
45// MemoryMgmt/Tasks/MemoryManagementRules.html
46//
47// "You take ownership of an object if you create it using a method whose name
48// begins with “alloc” or “new” or contains “copy” (for example, alloc,
49// newObject, or mutableCopy), or if you send it a retain message. You are
50// responsible for relinquishing ownership of objects you own using release
51// or autorelease. Any other time you receive an object, you must
52// not release it."
53//
Ted Kremenek4395b452009-02-21 05:13:43 +000054
55using llvm::CStrInCStrNoCase;
Ted Kremenekfd42ffc2009-02-21 18:26:02 +000056using llvm::StringsEqualNoCase;
Ted Kremenek4395b452009-02-21 05:13:43 +000057
58enum NamingConvention { NoConvention, CreateRule, InitRule };
59
60static inline bool isWordEnd(char ch, char prev, char next) {
61 return ch == '\0'
62 || (islower(prev) && isupper(ch)) // xxxC
63 || (isupper(prev) && isupper(ch) && islower(next)) // XXCreate
64 || !isalpha(ch);
65}
66
67static inline const char* parseWord(const char* s) {
68 char ch = *s, prev = '\0';
69 assert(ch != '\0');
70 char next = *(s+1);
71 while (!isWordEnd(ch, prev, next)) {
72 prev = ch;
73 ch = next;
74 next = *((++s)+1);
75 }
76 return s;
77}
78
79static NamingConvention deriveNamingConvention(const char* s) {
80 // A method/function name may contain a prefix. We don't know it is there,
81 // however, until we encounter the first '_'.
82 bool InPossiblePrefix = true;
83 bool AtBeginning = true;
84 NamingConvention C = NoConvention;
85
86 while (*s != '\0') {
87 // Skip '_'.
88 if (*s == '_') {
89 if (InPossiblePrefix) {
90 InPossiblePrefix = false;
91 AtBeginning = true;
92 // Discard whatever 'convention' we
93 // had already derived since it occurs
94 // in the prefix.
95 C = NoConvention;
96 }
97 ++s;
98 continue;
99 }
100
101 // Skip numbers, ':', etc.
102 if (!isalpha(*s)) {
103 ++s;
104 continue;
105 }
106
107 const char *wordEnd = parseWord(s);
108 assert(wordEnd > s);
109 unsigned len = wordEnd - s;
110
111 switch (len) {
112 default:
113 break;
114 case 3:
115 // Methods starting with 'new' follow the create rule.
Ted Kremenekfd42ffc2009-02-21 18:26:02 +0000116 if (AtBeginning && StringsEqualNoCase("new", s, len))
Ted Kremenek4395b452009-02-21 05:13:43 +0000117 C = CreateRule;
118 break;
119 case 4:
120 // Methods starting with 'alloc' or contain 'copy' follow the
121 // create rule
Ted Kremenek91b79532009-03-13 20:27:06 +0000122 if (C == NoConvention && StringsEqualNoCase("copy", s, len))
Ted Kremenek4395b452009-02-21 05:13:43 +0000123 C = CreateRule;
124 else // Methods starting with 'init' follow the init rule.
Ted Kremenekfd42ffc2009-02-21 18:26:02 +0000125 if (AtBeginning && StringsEqualNoCase("init", s, len))
Ted Kremenek91b79532009-03-13 20:27:06 +0000126 C = InitRule;
127 break;
128 case 5:
129 if (AtBeginning && StringsEqualNoCase("alloc", s, len))
130 C = CreateRule;
Ted Kremenek4395b452009-02-21 05:13:43 +0000131 break;
132 }
133
134 // If we aren't in the prefix and have a derived convention then just
135 // return it now.
136 if (!InPossiblePrefix && C != NoConvention)
137 return C;
138
139 AtBeginning = false;
140 s = wordEnd;
141 }
142
143 // We will get here if there wasn't more than one word
144 // after the prefix.
145 return C;
146}
147
Ted Kremenekb6f09542008-10-24 21:18:08 +0000148static bool followsFundamentalRule(const char* s) {
Ted Kremenek4395b452009-02-21 05:13:43 +0000149 return deriveNamingConvention(s) == CreateRule;
Ted Kremenekcdd3bb22008-11-05 16:54:44 +0000150}
151
Ted Kremenek314b1952009-04-29 23:03:22 +0000152static const ObjCMethodDecl*
153ResolveToInterfaceMethodDecl(const ObjCMethodDecl *MD, ASTContext &Context) {
154 ObjCInterfaceDecl *ID =
155 const_cast<ObjCInterfaceDecl*>(MD->getClassInterface());
156
157 return MD->isInstanceMethod()
158 ? ID->lookupInstanceMethod(Context, MD->getSelector())
159 : ID->lookupClassMethod(Context, MD->getSelector());
Ted Kremenekcdd3bb22008-11-05 16:54:44 +0000160}
Ted Kremenekb6f09542008-10-24 21:18:08 +0000161
Ted Kremenek41a4bc62009-05-08 23:09:42 +0000162namespace {
163class VISIBILITY_HIDDEN GenericNodeBuilder {
164 GRStmtNodeBuilder<GRState> *SNB;
165 Stmt *S;
166 const void *tag;
167 GREndPathNodeBuilder<GRState> *ENB;
168public:
169 GenericNodeBuilder(GRStmtNodeBuilder<GRState> &snb, Stmt *s,
170 const void *t)
171 : SNB(&snb), S(s), tag(t), ENB(0) {}
172 GenericNodeBuilder(GREndPathNodeBuilder<GRState> &enb)
173 : SNB(0), S(0), tag(0), ENB(&enb) {}
174
175 ExplodedNode<GRState> *MakeNode(const GRState *state,
176 ExplodedNode<GRState> *Pred) {
177 if (SNB)
178 return SNB->generateNode(PostStmt(S, tag), state,
179 Pred);
180
181 assert(ENB);
Ted Kremenek3f15aba2009-05-09 00:44:07 +0000182 return ENB->generateNode(state, Pred);
Ted Kremenek41a4bc62009-05-08 23:09:42 +0000183 }
184};
185} // end anonymous namespace
186
Ted Kremenek7d421f32008-04-09 23:49:11 +0000187//===----------------------------------------------------------------------===//
Ted Kremenek272aa852008-06-25 21:21:56 +0000188// Selector creation functions.
Ted Kremenekd9ccf682008-04-17 18:12:53 +0000189//===----------------------------------------------------------------------===//
190
Ted Kremenek1bd6ddb2008-05-01 18:31:44 +0000191static inline Selector GetNullarySelector(const char* name, ASTContext& Ctx) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +0000192 IdentifierInfo* II = &Ctx.Idents.get(name);
193 return Ctx.Selectors.getSelector(0, &II);
194}
195
Ted Kremenek0e344d42008-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 Kremenek272aa852008-06-25 21:21:56 +0000201//===----------------------------------------------------------------------===//
202// Type querying functions.
203//===----------------------------------------------------------------------===//
204
Ted Kremenek17144e82009-01-12 21:45:02 +0000205static bool hasPrefix(const char* s, const char* prefix) {
206 if (!prefix)
207 return true;
Ted Kremenek62820d82008-05-07 20:06:41 +0000208
Ted Kremenek17144e82009-01-12 21:45:02 +0000209 char c = *s;
210 char cP = *prefix;
Ted Kremenek62820d82008-05-07 20:06:41 +0000211
Ted Kremenek17144e82009-01-12 21:45:02 +0000212 while (c != '\0' && cP != '\0') {
213 if (c != cP) break;
214 c = *(++s);
215 cP = *(++prefix);
216 }
Ted Kremenek62820d82008-05-07 20:06:41 +0000217
Ted Kremenek17144e82009-01-12 21:45:02 +0000218 return cP == '\0';
Ted Kremenek62820d82008-05-07 20:06:41 +0000219}
220
Ted Kremenek17144e82009-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 Kremenek4c5378c2008-07-15 16:50:12 +0000228
Ted Kremenek17144e82009-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 Kremenek4c5378c2008-07-15 16:50:12 +0000235 return false;
Ted Kremenek17144e82009-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 Kremenek4c5378c2008-07-15 16:50:12 +0000240 return false;
Ted Kremenek17144e82009-01-12 21:45:02 +0000241
242 // Does the name start with the prefix?
243 return hasPrefix(name, prefix);
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000244}
245
Ted Kremenekd9ccf682008-04-17 18:12:53 +0000246//===----------------------------------------------------------------------===//
Ted Kremenek272aa852008-06-25 21:21:56 +0000247// Primitives used for constructing summaries for function/method calls.
Ted Kremenek7d421f32008-04-09 23:49:11 +0000248//===----------------------------------------------------------------------===//
249
Ted Kremenek272aa852008-06-25 21:21:56 +0000250/// ArgEffect is used to summarize a function/method call's effect on a
251/// particular argument.
Ted Kremenek6537a642009-03-17 19:42:23 +0000252enum ArgEffect { Autorelease, Dealloc, DecRef, DecRefMsg, DoNothing,
253 DoNothingByRef, IncRefMsg, IncRef, MakeCollectable, MayEscape,
254 NewAutoreleasePool, SelfOwn, StopTracking };
Ted Kremenek272aa852008-06-25 21:21:56 +0000255
Ted Kremeneka7338b42008-03-11 06:39:11 +0000256namespace llvm {
Ted Kremeneka56ae162009-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 Kremenek272aa852008-06-25 21:21:56 +0000261};
Ted Kremeneka7338b42008-03-11 06:39:11 +0000262} // end llvm namespace
263
Ted Kremeneka56ae162009-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 Kremeneka7338b42008-03-11 06:39:11 +0000268namespace {
Ted Kremenek272aa852008-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 Kremeneka7338b42008-03-11 06:39:11 +0000273public:
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000274 enum Kind { NoRet, Alias, OwnedSymbol, OwnedAllocatedSymbol,
Ted Kremenek382fb4e2009-04-27 19:14:45 +0000275 NotOwnedSymbol, GCNotOwnedSymbol, ReceiverAlias };
Ted Kremenek68621b92009-01-28 05:56:51 +0000276
277 enum ObjKind { CF, ObjC, AnyObj };
278
Ted Kremeneka7338b42008-03-11 06:39:11 +0000279private:
Ted Kremenek68621b92009-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 Kremenek827f93b2008-03-06 00:08:09 +0000286
Ted Kremeneka7338b42008-03-11 06:39:11 +0000287public:
Ted Kremenek68621b92009-01-28 05:56:51 +0000288 Kind getKind() const { return K; }
289
290 ObjKind getObjKind() const { return O; }
Ted Kremenek272aa852008-06-25 21:21:56 +0000291
292 unsigned getIndex() const {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000293 assert(getKind() == Alias);
Ted Kremenek68621b92009-01-28 05:56:51 +0000294 return index;
Ted Kremeneka7338b42008-03-11 06:39:11 +0000295 }
Ted Kremenek827f93b2008-03-06 00:08:09 +0000296
Ted Kremenek314b1952009-04-29 23:03:22 +0000297 bool isOwned() const {
298 return K == OwnedSymbol || K == OwnedAllocatedSymbol;
299 }
300
Ted Kremenek272aa852008-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 Kremenek68621b92009-01-28 05:56:51 +0000307 static RetEffect MakeOwned(ObjKind o, bool isAllocated = false) {
308 return RetEffect(isAllocated ? OwnedAllocatedSymbol : OwnedSymbol, o);
Ted Kremenek272aa852008-06-25 21:21:56 +0000309 }
Ted Kremenek68621b92009-01-28 05:56:51 +0000310 static RetEffect MakeNotOwned(ObjKind o) {
311 return RetEffect(NotOwnedSymbol, o);
Ted Kremenek382fb4e2009-04-27 19:14:45 +0000312 }
313 static RetEffect MakeGCNotOwned() {
314 return RetEffect(GCNotOwnedSymbol, ObjC);
315 }
316
Ted Kremenek272aa852008-06-25 21:21:56 +0000317 static RetEffect MakeNoRet() {
318 return RetEffect(NoRet);
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000319 }
Ted Kremenek827f93b2008-03-06 00:08:09 +0000320
Ted Kremenek272aa852008-06-25 21:21:56 +0000321 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek68621b92009-01-28 05:56:51 +0000322 ID.AddInteger((unsigned)K);
323 ID.AddInteger((unsigned)O);
324 ID.AddInteger(index);
Ted Kremenek272aa852008-06-25 21:21:56 +0000325 }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000326};
Ted Kremeneka7338b42008-03-11 06:39:11 +0000327
Ted Kremenek272aa852008-06-25 21:21:56 +0000328
Ted Kremenek2f226732009-05-04 05:31:22 +0000329class VISIBILITY_HIDDEN RetainSummary {
Ted Kremenekbcaff792008-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 Kremeneka56ae162009-05-03 05:20:50 +0000333 ArgEffects Args;
Ted Kremenekbcaff792008-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 Kremenek272aa852008-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 Kremenek266d8b62008-05-06 02:26:56 +0000341 ArgEffect Receiver;
Ted Kremenek272aa852008-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 Kremeneka7338b42008-03-11 06:39:11 +0000346 RetEffect Ret;
Ted Kremenek272aa852008-06-25 21:21:56 +0000347
Ted Kremenekf2717b02008-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 Kremeneka7338b42008-03-11 06:39:11 +0000352public:
Ted Kremeneka56ae162009-05-03 05:20:50 +0000353 RetainSummary(ArgEffects A, RetEffect R, ArgEffect defaultEff,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000354 ArgEffect ReceiverEff, bool endpath = false)
355 : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R),
356 EndPath(endpath) {}
Ted Kremeneka7338b42008-03-11 06:39:11 +0000357
Ted Kremenek272aa852008-06-25 21:21:56 +0000358 /// getArg - Return the argument effect on the argument specified by
359 /// idx (starting from 0).
Ted Kremenek0d721572008-03-11 17:48:22 +0000360 ArgEffect getArg(unsigned idx) const {
Ted Kremeneka56ae162009-05-03 05:20:50 +0000361 if (const ArgEffect *AE = Args.lookup(idx))
362 return *AE;
Ted Kremenekae855d42008-04-24 17:22:33 +0000363
Ted Kremenekbcaff792008-05-06 15:44:25 +0000364 return DefaultArgEffect;
Ted Kremenek0d721572008-03-11 17:48:22 +0000365 }
366
Ted Kremenek2f226732009-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 Kremenek272aa852008-06-25 21:21:56 +0000377 /// getRetEffect - Returns the effect on the return value of the call.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000378 RetEffect getRetEffect() const { return Ret; }
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000379
Ted Kremenek2f226732009-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 Kremenekf2717b02008-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 Kremenek272aa852008-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 Kremeneka56ae162009-05-03 05:20:50 +0000389 ArgEffect getReceiverEffect() const { return Receiver; }
Ted Kremenek266d8b62008-05-06 02:26:56 +0000390
Ted Kremenek2f226732009-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 Kremeneka56ae162009-05-03 05:20:50 +0000394 typedef ArgEffects::iterator ExprIterator;
Ted Kremeneka7338b42008-03-11 06:39:11 +0000395
Ted Kremeneka56ae162009-05-03 05:20:50 +0000396 ExprIterator begin_args() const { return Args.begin(); }
397 ExprIterator end_args() const { return Args.end(); }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000398
Ted Kremeneka56ae162009-05-03 05:20:50 +0000399 static void Profile(llvm::FoldingSetNodeID& ID, ArgEffects A,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000400 RetEffect RetEff, ArgEffect DefaultEff,
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000401 ArgEffect ReceiverEff, bool EndPath) {
Ted Kremeneka56ae162009-05-03 05:20:50 +0000402 ID.Add(A);
Ted Kremenek266d8b62008-05-06 02:26:56 +0000403 ID.Add(RetEff);
Ted Kremenekbcaff792008-05-06 15:44:25 +0000404 ID.AddInteger((unsigned) DefaultEff);
Ted Kremenek266d8b62008-05-06 02:26:56 +0000405 ID.AddInteger((unsigned) ReceiverEff);
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000406 ID.AddInteger((unsigned) EndPath);
Ted Kremeneka7338b42008-03-11 06:39:11 +0000407 }
408
409 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000410 Profile(ID, Args, Ret, DefaultArgEffect, Receiver, EndPath);
Ted Kremeneka7338b42008-03-11 06:39:11 +0000411 }
412};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000413} // end anonymous namespace
Ted Kremeneka7338b42008-03-11 06:39:11 +0000414
Ted Kremenek272aa852008-06-25 21:21:56 +0000415//===----------------------------------------------------------------------===//
416// Data structures for constructing summaries.
417//===----------------------------------------------------------------------===//
Ted Kremenek9f0fc792008-06-24 03:49:48 +0000418
Ted Kremenek272aa852008-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 Kremenek314b1952009-04-29 23:03:22 +0000427 ObjCSummaryKey(const ObjCInterfaceDecl* d, Selector s)
Ted Kremenek272aa852008-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 Kremenek84f010c2008-06-23 23:30:29 +0000436}
437
438namespace llvm {
Ted Kremenek272aa852008-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 Kremenek84f010c2008-06-23 23:30:29 +0000444
Ted Kremenek272aa852008-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 Kremenek84f010c2008-06-23 23:30:29 +0000469} // end llvm namespace
Ted Kremeneka7338b42008-03-11 06:39:11 +0000470
Ted Kremenek84f010c2008-06-23 23:30:29 +0000471namespace {
Ted Kremenek272aa852008-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 Kremenek314b1952009-04-29 23:03:22 +0000480 iterator find(const ObjCInterfaceDecl* D, IdentifierInfo *ClsName,
481 Selector S) {
Ted Kremeneka821b792009-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 Kremenek314b1952009-04-29 23:03:22 +0000487 iterator find(const ObjCInterfaceDecl* D, Selector S) {
Ted Kremenek272aa852008-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 Kremenek9449ca92008-08-12 20:41:56 +0000516
Ted Kremenek272aa852008-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 Kremeneka8c3c432008-05-05 22:11:16 +0000569
570 //==-----------------------------------------------------------------==//
571 // Typedefs.
572 //==-----------------------------------------------------------------==//
Ted Kremeneka7338b42008-03-11 06:39:11 +0000573
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000574 typedef llvm::DenseMap<FunctionDecl*, RetainSummary*>
575 FuncSummariesTy;
576
Ted Kremenek84f010c2008-06-23 23:30:29 +0000577 typedef ObjCSummaryCache ObjCMethodSummariesTy;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000578
579 //==-----------------------------------------------------------------==//
580 // Data.
581 //==-----------------------------------------------------------------==//
582
Ted Kremenek272aa852008-06-25 21:21:56 +0000583 /// Ctx - The ASTContext object for the analyzed ASTs.
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000584 ASTContext& Ctx;
Ted Kremeneke44927e2008-07-01 17:21:27 +0000585
Ted Kremenekede40b72008-07-09 18:11:16 +0000586 /// CFDictionaryCreateII - An IdentifierInfo* representing the indentifier
587 /// "CFDictionaryCreate".
588 IdentifierInfo* CFDictionaryCreateII;
589
Ted Kremenek272aa852008-06-25 21:21:56 +0000590 /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000591 const bool GCEnabled;
Ted Kremenekee649082009-05-04 04:30:18 +0000592
Ted Kremenek272aa852008-06-25 21:21:56 +0000593 /// FuncSummaries - A map from FunctionDecls to summaries.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000594 FuncSummariesTy FuncSummaries;
595
Ted Kremenek272aa852008-06-25 21:21:56 +0000596 /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
597 /// to summaries.
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000598 ObjCMethodSummariesTy ObjCClassMethodSummaries;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000599
Ted Kremenek272aa852008-06-25 21:21:56 +0000600 /// ObjCMethodSummaries - A map from selectors to summaries.
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000601 ObjCMethodSummariesTy ObjCMethodSummaries;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000602
Ted Kremenek272aa852008-06-25 21:21:56 +0000603 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
604 /// and all other data used by the checker.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000605 llvm::BumpPtrAllocator BPAlloc;
606
Ted Kremeneka56ae162009-05-03 05:20:50 +0000607 /// AF - A factory for ArgEffects objects.
608 ArgEffects::Factory AF;
609
Ted Kremenek272aa852008-06-25 21:21:56 +0000610 /// ScratchArgs - A holding buffer for construct ArgEffects.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000611 ArgEffects ScratchArgs;
612
Ted Kremenek5535e5e2009-05-07 23:40:42 +0000613 /// ObjCAllocRetE - Default return effect for methods returning Objective-C
614 /// objects.
615 RetEffect ObjCAllocRetE;
616
Ted Kremenek286e9852009-05-04 04:57:00 +0000617 RetainSummary DefaultSummary;
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000618 RetainSummary* StopSummary;
619
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000620 //==-----------------------------------------------------------------==//
621 // Methods.
622 //==-----------------------------------------------------------------==//
623
Ted Kremenek272aa852008-06-25 21:21:56 +0000624 /// getArgEffects - Returns a persistent ArgEffects object based on the
625 /// data in ScratchArgs.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000626 ArgEffects getArgEffects();
Ted Kremeneka7338b42008-03-11 06:39:11 +0000627
Ted Kremenek562c1302008-05-05 16:51:50 +0000628 enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000629
630public:
Ted Kremenek2f226732009-05-04 05:31:22 +0000631 RetainSummary *getDefaultSummary() {
632 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
633 return new (Summ) RetainSummary(DefaultSummary);
634 }
Ted Kremenek286e9852009-05-04 04:57:00 +0000635
Ted Kremenek064ef322009-02-23 16:51:39 +0000636 RetainSummary* getUnarySummary(const FunctionType* FT, UnaryFuncKind func);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000637
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000638 RetainSummary* getCFSummaryCreateRule(FunctionDecl* FD);
639 RetainSummary* getCFSummaryGetRule(FunctionDecl* FD);
Ted Kremenek17144e82009-01-12 21:45:02 +0000640 RetainSummary* getCFCreateGetRuleSummary(FunctionDecl* FD, const char* FName);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000641
Ted Kremeneka56ae162009-05-03 05:20:50 +0000642 RetainSummary* getPersistentSummary(ArgEffects AE, RetEffect RetEff,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000643 ArgEffect ReceiverEff = DoNothing,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000644 ArgEffect DefaultEff = MayEscape,
645 bool isEndPath = false);
Ted Kremenek45d0b502008-10-29 04:07:07 +0000646
Ted Kremenek266d8b62008-05-06 02:26:56 +0000647 RetainSummary* getPersistentSummary(RetEffect RE,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000648 ArgEffect ReceiverEff = DoNothing,
Ted Kremeneka3f30dd2008-05-22 17:31:13 +0000649 ArgEffect DefaultEff = MayEscape) {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000650 return getPersistentSummary(getArgEffects(), RE, ReceiverEff, DefaultEff);
Ted Kremenek0e344d42008-05-06 00:30:21 +0000651 }
Ted Kremenek42ea0322008-05-05 23:55:01 +0000652
Ted Kremeneka821b792009-04-29 05:04:30 +0000653 RetainSummary *getPersistentStopSummary() {
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000654 if (StopSummary)
655 return StopSummary;
656
657 StopSummary = getPersistentSummary(RetEffect::MakeNoRet(),
658 StopTracking, StopTracking);
Ted Kremenek45d0b502008-10-29 04:07:07 +0000659
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000660 return StopSummary;
Ted Kremenekbcaff792008-05-06 15:44:25 +0000661 }
Ted Kremenek926abf22008-05-06 04:20:12 +0000662
Ted Kremeneka821b792009-04-29 05:04:30 +0000663 RetainSummary *getInitMethodSummary(QualType RetTy);
Ted Kremenek42ea0322008-05-05 23:55:01 +0000664
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000665 void InitializeClassMethodSummaries();
666 void InitializeMethodSummaries();
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000667
Ted Kremenek9b42e062009-05-03 04:42:10 +0000668 bool isTrackedObjCObjectType(QualType T);
Ted Kremeneka9cdbc32009-05-03 06:08:32 +0000669 bool isTrackedCFObjectType(QualType T);
Ted Kremenek35920ed2009-01-07 00:39:56 +0000670
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000671private:
672
Ted Kremenekf2717b02008-07-18 17:24:20 +0000673 void addClsMethSummary(IdentifierInfo* ClsII, Selector S,
674 RetainSummary* Summ) {
675 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
676 }
677
Ted Kremenek272aa852008-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 Kremenekfbf2dc52009-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 Kremenek272aa852008-06-25 21:21:56 +0000692
Ted Kremenek1b4b6562009-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 Kremenekccbe79a2009-04-24 17:50:11 +0000699
700 Selector generateSelector(va_list argp) {
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000701 llvm::SmallVector<IdentifierInfo*, 10> II;
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000702
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000703 while (const char* s = va_arg(argp, const char*))
704 II.push_back(&Ctx.Idents.get(s));
Ted Kremenekccbe79a2009-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 Kremenekf2717b02008-07-18 17:24:20 +0000713 }
Ted Kremenek45642a42008-08-12 18:48:50 +0000714
715 void addInstMethSummary(const char* Cls, RetainSummary* Summ, ...) {
716 va_list argp;
717 va_start(argp, Summ);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000718 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Ted Kremenek45642a42008-08-12 18:48:50 +0000719 va_end(argp);
720 }
Ted Kremenekccbe79a2009-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 Kremenek3d6ddbb2008-08-12 18:30:56 +0000736 void addPanicSummary(const char* Cls, ...) {
Ted Kremeneka56ae162009-05-03 05:20:50 +0000737 RetainSummary* Summ = getPersistentSummary(AF.GetEmptyMap(),
738 RetEffect::MakeNoRet(),
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000739 DoNothing, DoNothing, true);
740 va_list argp;
741 va_start (argp, Cls);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000742 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000743 va_end(argp);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000744 }
Ted Kremenekf2717b02008-07-18 17:24:20 +0000745
Ted Kremeneka7338b42008-03-11 06:39:11 +0000746public:
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000747
748 RetainSummaryManager(ASTContext& ctx, bool gcenabled)
Ted Kremeneke44927e2008-07-01 17:21:27 +0000749 : Ctx(ctx),
Ted Kremenekede40b72008-07-09 18:11:16 +0000750 CFDictionaryCreateII(&ctx.Idents.get("CFDictionaryCreate")),
Ted Kremeneka56ae162009-05-03 05:20:50 +0000751 GCEnabled(gcenabled), AF(BPAlloc), ScratchArgs(AF.GetEmptyMap()),
Ted Kremenek5535e5e2009-05-07 23:40:42 +0000752 ObjCAllocRetE(gcenabled ? RetEffect::MakeGCNotOwned()
753 : RetEffect::MakeOwned(RetEffect::ObjC, true)),
Ted Kremenek286e9852009-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 Kremeneka56ae162009-05-03 05:20:50 +0000758 StopSummary(0) {
Ted Kremenek272aa852008-06-25 21:21:56 +0000759
760 InitializeClassMethodSummaries();
761 InitializeMethodSummaries();
762 }
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000763
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000764 ~RetainSummaryManager();
Ted Kremeneka7338b42008-03-11 06:39:11 +0000765
Ted Kremenekd13c1872008-06-24 03:56:45 +0000766 RetainSummary* getSummary(FunctionDecl* FD);
Ted Kremeneka821b792009-04-29 05:04:30 +0000767
Ted Kremenek314b1952009-04-29 23:03:22 +0000768 RetainSummary* getInstanceMethodSummary(ObjCMessageExpr* ME,
769 const ObjCInterfaceDecl* ID) {
Ted Kremenek04e00302009-04-29 17:09:14 +0000770 return getInstanceMethodSummary(ME->getSelector(), ME->getClassName(),
Ted Kremeneka821b792009-04-29 05:04:30 +0000771 ID, ME->getMethodDecl(), ME->getType());
772 }
773
Ted Kremenek04e00302009-04-29 17:09:14 +0000774 RetainSummary* getInstanceMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +0000775 const ObjCInterfaceDecl* ID,
776 const ObjCMethodDecl *MD,
777 QualType RetTy);
Ted Kremenek578498a2009-04-29 00:42:39 +0000778
779 RetainSummary *getClassMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +0000780 const ObjCInterfaceDecl *ID,
781 const ObjCMethodDecl *MD,
782 QualType RetTy);
Ted Kremenek578498a2009-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 Kremenek91b89a42009-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 Kremenek314b1952009-04-29 23:03:22 +0000792 RetainSummary *getMethodSummary(const ObjCMethodDecl *MD) {
793 // FIXME: Eventually this should be unneeded.
Ted Kremenek314b1952009-04-29 23:03:22 +0000794 const ObjCInterfaceDecl *ID = MD->getClassInterface();
Ted Kremenek1447cc92009-04-30 05:41:14 +0000795 Selector S = MD->getSelector();
Ted Kremenek91b89a42009-04-29 17:17:48 +0000796 IdentifierInfo *ClsName = ID->getIdentifier();
797 QualType ResultTy = MD->getResultType();
798
Ted Kremenek81eb4642009-04-30 05:47:23 +0000799 // Resolve the method decl last.
800 if (const ObjCMethodDecl *InterfaceMD =
801 ResolveToInterfaceMethodDecl(MD, Ctx))
802 MD = InterfaceMD;
Ted Kremenek1447cc92009-04-30 05:41:14 +0000803
Ted Kremenek91b89a42009-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 Kremenek578498a2009-04-29 00:42:39 +0000809
Ted Kremenek314b1952009-04-29 23:03:22 +0000810 RetainSummary* getCommonMethodSummary(const ObjCMethodDecl* MD,
811 Selector S, QualType RetTy);
812
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000813 bool isGCEnabled() const { return GCEnabled; }
Ted Kremenek2f226732009-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 Kremeneka7338b42008-03-11 06:39:11 +0000820};
821
822} // end anonymous namespace
823
824//===----------------------------------------------------------------------===//
825// Implementation of checker data structures.
826//===----------------------------------------------------------------------===//
827
Ted Kremeneka56ae162009-05-03 05:20:50 +0000828RetainSummaryManager::~RetainSummaryManager() {}
Ted Kremeneka7338b42008-03-11 06:39:11 +0000829
Ted Kremeneka56ae162009-05-03 05:20:50 +0000830ArgEffects RetainSummaryManager::getArgEffects() {
831 ArgEffects AE = ScratchArgs;
832 ScratchArgs = AF.GetEmptyMap();
833 return AE;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000834}
835
Ted Kremenek266d8b62008-05-06 02:26:56 +0000836RetainSummary*
Ted Kremeneka56ae162009-05-03 05:20:50 +0000837RetainSummaryManager::getPersistentSummary(ArgEffects AE, RetEffect RetEff,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000838 ArgEffect ReceiverEff,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000839 ArgEffect DefaultEff,
Ted Kremenekee649082009-05-04 04:30:18 +0000840 bool isEndPath) {
Ted Kremenekae855d42008-04-24 17:22:33 +0000841 // Create the summary and return it.
Ted Kremenekee649082009-05-04 04:30:18 +0000842 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
Ted Kremenekf2717b02008-07-18 17:24:20 +0000843 new (Summ) RetainSummary(AE, RetEff, DefaultEff, ReceiverEff, isEndPath);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000844 return Summ;
845}
846
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000847//===----------------------------------------------------------------------===//
Ted Kremenek35920ed2009-01-07 00:39:56 +0000848// Predicates.
849//===----------------------------------------------------------------------===//
850
Ted Kremenek9b42e062009-05-03 04:42:10 +0000851bool RetainSummaryManager::isTrackedObjCObjectType(QualType Ty) {
Ted Kremenek0d813552009-04-23 22:11:07 +0000852 if (!Ctx.isObjCObjectPointerType(Ty))
Ted Kremenek35920ed2009-01-07 00:39:56 +0000853 return false;
854
Ted Kremenek0d813552009-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 Kremenek35920ed2009-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 Kremenek0d813552009-04-23 22:11:07 +0000865
866 // Does the interface subclass NSObject?
Ted Kremenek35920ed2009-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 Kremeneka9cdbc32009-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 Kremenek35920ed2009-01-07 00:39:56 +0000886//===----------------------------------------------------------------------===//
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000887// Summary creation for functions (largely uses of Core Foundation).
888//===----------------------------------------------------------------------===//
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000889
Ted Kremenek17144e82009-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 Kremenekd13c1872008-06-24 03:56:45 +0000900RetainSummary* RetainSummaryManager::getSummary(FunctionDecl* FD) {
Ted Kremenekae855d42008-04-24 17:22:33 +0000901 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000902 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000903 if (I != FuncSummaries.end())
Ted Kremenekae855d42008-04-24 17:22:33 +0000904 return I->second;
905
Ted Kremenek64cddf12009-05-04 15:34:07 +0000906 // No summary? Generate one.
Ted Kremenek17144e82009-01-12 21:45:02 +0000907 RetainSummary *S = 0;
Ted Kremenek562c1302008-05-05 16:51:50 +0000908
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000909 do {
Ted Kremenek17144e82009-01-12 21:45:02 +0000910 // We generate "stop" summaries for implicitly defined functions.
911 if (FD->isImplicit()) {
912 S = getPersistentStopSummary();
913 break;
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000914 }
Ted Kremenekeafcc2f2008-11-04 00:36:12 +0000915
Ted Kremenek064ef322009-02-23 16:51:39 +0000916 // [PR 3337] Use 'getAsFunctionType' to strip away any typedefs on the
Ted Kremenekc239b9c2009-01-16 18:40:33 +0000917 // function's type.
Ted Kremenek064ef322009-02-23 16:51:39 +0000918 const FunctionType* FT = FD->getType()->getAsFunctionType();
Ted Kremenek17144e82009-01-12 21:45:02 +0000919 const char* FName = FD->getIdentifier()->getName();
920
Ted Kremenek38c6f022009-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 Kremenek17144e82009-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 Kremeneka56ae162009-05-03 05:20:50 +0000934 assert (ScratchArgs.isEmpty());
935 ScratchArgs = AF.Add(ScratchArgs, 1, DecRef);
Ted Kremenek17144e82009-01-12 21:45:02 +0000936 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
937 break;
Ted Kremenekcfc50c72008-10-22 20:54:52 +0000938 }
Ted Kremenek7b88c892009-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 Kremenek17144e82009-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 Kremenek38c6f022009-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 Kremenek17144e82009-01-12 21:45:02 +00001005 S = getUnarySummary(FT, cfrelease);
1006 else {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001007 assert (ScratchArgs.isEmpty());
Ted Kremenek7b293682009-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 Kremenekcf071252009-02-05 22:34:53 +00001024 CStrInCStrNoCase(FName, "SetValue") ||
1025 CStrInCStrNoCase(FName, "AppendValue"))
Ted Kremenek7b293682009-01-29 22:45:13 +00001026 ? MayEscape : DoNothing;
1027
1028 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek17144e82009-01-12 21:45:02 +00001029 }
1030 }
Ted Kremenek4c5378c2008-07-15 16:50:12 +00001031 }
1032 while (0);
Ted Kremenek2f226732009-05-04 05:31:22 +00001033
1034 if (!S)
1035 S = getDefaultSummary();
Ted Kremenekae855d42008-04-24 17:22:33 +00001036
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001037 FuncSummaries[FD] = S;
Ted Kremenek562c1302008-05-05 16:51:50 +00001038 return S;
Ted Kremenek827f93b2008-03-06 00:08:09 +00001039}
1040
Ted Kremenek4c5378c2008-07-15 16:50:12 +00001041RetainSummary*
1042RetainSummaryManager::getCFCreateGetRuleSummary(FunctionDecl* FD,
1043 const char* FName) {
1044
Ted Kremenek562c1302008-05-05 16:51:50 +00001045 if (strstr(FName, "Create") || strstr(FName, "Copy"))
1046 return getCFSummaryCreateRule(FD);
Ted Kremenek4c5378c2008-07-15 16:50:12 +00001047
Ted Kremenek562c1302008-05-05 16:51:50 +00001048 if (strstr(FName, "Get"))
1049 return getCFSummaryGetRule(FD);
1050
Ted Kremenek286e9852009-05-04 04:57:00 +00001051 return getDefaultSummary();
Ted Kremenek562c1302008-05-05 16:51:50 +00001052}
1053
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001054RetainSummary*
Ted Kremenek064ef322009-02-23 16:51:39 +00001055RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1056 UnaryFuncKind func) {
1057
Ted Kremenek17144e82009-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 Gregor4fa58902009-02-26 23:50:07 +00001060 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
Ted Kremenek17144e82009-01-12 21:45:02 +00001061 if (!FTP || FTP->getNumArgs() != 1)
1062 return getPersistentStopSummary();
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001063
Ted Kremeneka56ae162009-05-03 05:20:50 +00001064 assert (ScratchArgs.isEmpty());
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001065
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001066 switch (func) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001067 case cfretain: {
1068 ScratchArgs = AF.Add(ScratchArgs, 0, IncRef);
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001069 return getPersistentSummary(RetEffect::MakeAlias(0),
1070 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001071 }
1072
1073 case cfrelease: {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001074 ScratchArgs = AF.Add(ScratchArgs, 0, DecRef);
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001075 return getPersistentSummary(RetEffect::MakeNoRet(),
1076 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001077 }
1078
1079 case cfmakecollectable: {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001080 ScratchArgs = AF.Add(ScratchArgs, 0, MakeCollectable);
Ted Kremenek2126bef2009-02-18 21:57:45 +00001081 return getPersistentSummary(RetEffect::MakeAlias(0),DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001082 }
1083
1084 default:
Ted Kremenek562c1302008-05-05 16:51:50 +00001085 assert (false && "Not a supported unary function.");
Ted Kremenek286e9852009-05-04 04:57:00 +00001086 return getDefaultSummary();
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00001087 }
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001088}
1089
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001090RetainSummary* RetainSummaryManager::getCFSummaryCreateRule(FunctionDecl* FD) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001091 assert (ScratchArgs.isEmpty());
Ted Kremenekede40b72008-07-09 18:11:16 +00001092
1093 if (FD->getIdentifier() == CFDictionaryCreateII) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001094 ScratchArgs = AF.Add(ScratchArgs, 1, DoNothingByRef);
1095 ScratchArgs = AF.Add(ScratchArgs, 2, DoNothingByRef);
Ted Kremenekede40b72008-07-09 18:11:16 +00001096 }
1097
Ted Kremenek68621b92009-01-28 05:56:51 +00001098 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001099}
1100
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001101RetainSummary* RetainSummaryManager::getCFSummaryGetRule(FunctionDecl* FD) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001102 assert (ScratchArgs.isEmpty());
Ted Kremenek68621b92009-01-28 05:56:51 +00001103 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1104 DoNothing, DoNothing);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001105}
1106
Ted Kremeneka7338b42008-03-11 06:39:11 +00001107//===----------------------------------------------------------------------===//
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001108// Summary creation for Selectors.
1109//===----------------------------------------------------------------------===//
1110
Ted Kremenekbcaff792008-05-06 15:44:25 +00001111RetainSummary*
Ted Kremeneka821b792009-04-29 05:04:30 +00001112RetainSummaryManager::getInitMethodSummary(QualType RetTy) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001113 assert(ScratchArgs.isEmpty());
Ted Kremenek42ea0322008-05-05 23:55:01 +00001114
Ted Kremenek802cfc72009-02-20 00:05:35 +00001115 // 'init' methods only return an alias if the return type is a location type.
Ted Kremeneka821b792009-04-29 05:04:30 +00001116 return getPersistentSummary(Loc::IsLocType(RetTy)
1117 ? RetEffect::MakeReceiverAlias()
Ted Kremenek03d242e2009-05-05 18:44:20 +00001118 : RetEffect::MakeNoRet());
Ted Kremenek42ea0322008-05-05 23:55:01 +00001119}
Ted Kremenek03d242e2009-05-05 18:44:20 +00001120
Ted Kremenekbcaff792008-05-06 15:44:25 +00001121RetainSummary*
Ted Kremenek314b1952009-04-29 23:03:22 +00001122RetainSummaryManager::getCommonMethodSummary(const ObjCMethodDecl* MD,
1123 Selector S, QualType RetTy) {
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001124
Ted Kremenek578498a2009-04-29 00:42:39 +00001125 if (MD) {
Ted Kremenek3fc3e112009-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 Kremeneka56ae162009-05-03 05:20:50 +00001136 ScratchArgs = AF.Add(ScratchArgs, i, StopTracking);
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001137 }
1138 }
1139
Ted Kremenekf936b3f2009-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 Kremenek174a0772009-04-23 23:08:22 +00001153 // Look for methods that return an owned object.
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001154 if (isTrackedObjCObjectType(RetTy)) {
1155 // EXPERIMENTAL: Assume the Cocoa conventions for all objects returned
1156 // by instance methods.
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001157 RetEffect E =
1158 followsFundamentalRule(S.getIdentifierInfoForSlot(0)->getName())
Ted Kremenek5535e5e2009-05-07 23:40:42 +00001159 ? ObjCAllocRetE : RetEffect::MakeNotOwned(RetEffect::ObjC);
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001160
1161 return getPersistentSummary(E, ReceiverEff, MayEscape);
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001162 }
Ted Kremenek174a0772009-04-23 23:08:22 +00001163
Ted Kremeneka9cdbc32009-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 Kremenek174a0772009-04-23 23:08:22 +00001173
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001174 if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing)
Ted Kremenek286e9852009-05-04 04:57:00 +00001175 return getDefaultSummary();
Ted Kremenek174a0772009-04-23 23:08:22 +00001176
Ted Kremenek2f226732009-05-04 05:31:22 +00001177 return getPersistentSummary(RetEffect::MakeNoRet(), ReceiverEff, MayEscape);
Ted Kremenek174a0772009-04-23 23:08:22 +00001178}
1179
1180RetainSummary*
Ted Kremenek04e00302009-04-29 17:09:14 +00001181RetainSummaryManager::getInstanceMethodSummary(Selector S,
1182 IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +00001183 const ObjCInterfaceDecl* ID,
1184 const ObjCMethodDecl *MD,
Ted Kremenek04e00302009-04-29 17:09:14 +00001185 QualType RetTy) {
Ted Kremenekbcaff792008-05-06 15:44:25 +00001186
Ted Kremeneka821b792009-04-29 05:04:30 +00001187 // Look up a summary in our summary cache.
1188 ObjCMethodSummariesTy::iterator I = ObjCMethodSummaries.find(ID, ClsName, S);
Ted Kremenek42ea0322008-05-05 23:55:01 +00001189
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001190 if (I != ObjCMethodSummaries.end())
Ted Kremenek42ea0322008-05-05 23:55:01 +00001191 return I->second;
Ted Kremenek42ea0322008-05-05 23:55:01 +00001192
Ted Kremeneka56ae162009-05-03 05:20:50 +00001193 assert(ScratchArgs.isEmpty());
Ted Kremenek2f226732009-05-04 05:31:22 +00001194 RetainSummary *Summ = 0;
Ted Kremenek1d3d9562008-05-06 06:09:09 +00001195
Ted Kremenek2f226732009-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 Kremenek2f226732009-05-04 05:31:22 +00001203 // Memoize the summary.
Ted Kremeneka821b792009-04-29 05:04:30 +00001204 ObjCMethodSummaries[ObjCSummaryKey(ClsName, S)] = Summ;
Ted Kremeneke4158502009-04-23 19:11:35 +00001205 return Summ;
Ted Kremenek42ea0322008-05-05 23:55:01 +00001206}
1207
Ted Kremeneka7722b72008-05-06 21:26:51 +00001208RetainSummary*
Ted Kremenek578498a2009-04-29 00:42:39 +00001209RetainSummaryManager::getClassMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +00001210 const ObjCInterfaceDecl *ID,
1211 const ObjCMethodDecl *MD,
1212 QualType RetTy) {
Ted Kremenekccbe79a2009-04-24 17:50:11 +00001213
Ted Kremenek578498a2009-04-29 00:42:39 +00001214 assert(ClsName && "Class name must be specified.");
Ted Kremeneka821b792009-04-29 05:04:30 +00001215 ObjCMethodSummariesTy::iterator I =
1216 ObjCClassMethodSummaries.find(ID, ClsName, S);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001217
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001218 if (I != ObjCClassMethodSummaries.end())
Ted Kremeneka7722b72008-05-06 21:26:51 +00001219 return I->second;
Ted Kremenek2f226732009-05-04 05:31:22 +00001220
1221 RetainSummary *Summ = getCommonMethodSummary(MD, S, RetTy);
1222
Ted Kremenek2f226732009-05-04 05:31:22 +00001223 // Memoize the summary.
Ted Kremenek578498a2009-04-29 00:42:39 +00001224 ObjCClassMethodSummaries[ObjCSummaryKey(ClsName, S)] = Summ;
Ted Kremeneke4158502009-04-23 19:11:35 +00001225 return Summ;
Ted Kremeneka7722b72008-05-06 21:26:51 +00001226}
1227
Ted Kremenek5535e5e2009-05-07 23:40:42 +00001228void RetainSummaryManager::InitializeClassMethodSummaries() {
1229 assert(ScratchArgs.isEmpty());
1230 RetainSummary* Summ = getPersistentSummary(ObjCAllocRetE);
Ted Kremenek0e344d42008-05-06 00:30:21 +00001231
Ted Kremenek272aa852008-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 Kremenekf2717b02008-07-18 17:24:20 +00001237
1238 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001239 addClsMethSummary(&Ctx.Idents.get("NSAssertionHandler"),
Ted Kremenek68621b92009-01-28 05:56:51 +00001240 GetNullarySelector("currentHandler", Ctx),
1241 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001242
1243 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremeneka56ae162009-05-03 05:20:50 +00001244 ScratchArgs = AF.Add(ScratchArgs, 0, Autorelease);
Ted Kremenek9b112d22009-01-28 21:44:40 +00001245 addClsMethSummary(&Ctx.Idents.get("NSAutoreleasePool"),
1246 GetUnarySelector("addObject", Ctx),
1247 getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenekf21cb242009-02-23 02:31:16 +00001248 DoNothing, Autorelease));
Ted Kremenekccbe79a2009-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 Kremenek0e344d42008-05-06 00:30:21 +00001271}
1272
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001273void RetainSummaryManager::InitializeMethodSummaries() {
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001274
Ted Kremeneka56ae162009-05-03 05:20:50 +00001275 assert (ScratchArgs.isEmpty());
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001276
Ted Kremeneka7722b72008-05-06 21:26:51 +00001277 // Create the "init" selector. It just acts as a pass-through for the
1278 // receiver.
Ted Kremenek56c70aa2009-02-23 16:54:00 +00001279 RetainSummary* InitSumm =
1280 getPersistentSummary(RetEffect::MakeReceiverAlias());
Ted Kremeneke44927e2008-07-01 17:21:27 +00001281 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001282
1283 // The next methods are allocators.
Ted Kremenek5535e5e2009-05-07 23:40:42 +00001284 RetainSummary* Summ = getPersistentSummary(ObjCAllocRetE);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001285
1286 // Create the "copy" selector.
Ted Kremenek9449ca92008-08-12 20:41:56 +00001287 addNSObjectMethSummary(GetNullarySelector("copy", Ctx), Summ);
1288
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001289 // Create the "mutableCopy" selector.
Ted Kremenek272aa852008-06-25 21:21:56 +00001290 addNSObjectMethSummary(GetNullarySelector("mutableCopy", Ctx), Summ);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001291
Ted Kremenek266d8b62008-05-06 02:26:56 +00001292 // Create the "retain" selector.
Ted Kremenek5535e5e2009-05-07 23:40:42 +00001293 RetEffect E = RetEffect::MakeReceiverAlias();
Ted Kremenek58dd95b2009-02-18 18:54:33 +00001294 Summ = getPersistentSummary(E, IncRefMsg);
Ted Kremenek272aa852008-06-25 21:21:56 +00001295 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001296
1297 // Create the "release" selector.
Ted Kremenek58dd95b2009-02-18 18:54:33 +00001298 Summ = getPersistentSummary(E, DecRefMsg);
Ted Kremenek272aa852008-06-25 21:21:56 +00001299 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Ted Kremenekc00b32b2008-05-07 21:17:39 +00001300
1301 // Create the "drain" selector.
1302 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek272aa852008-06-25 21:21:56 +00001303 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
Ted Kremenek6537a642009-03-17 19:42:23 +00001304
1305 // Create the -dealloc summary.
1306 Summ = getPersistentSummary(RetEffect::MakeNoRet(), Dealloc);
1307 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001308
1309 // Create the "autorelease" selector.
Ted Kremenek9b112d22009-01-28 21:44:40 +00001310 Summ = getPersistentSummary(E, Autorelease);
Ted Kremenek272aa852008-06-25 21:21:56 +00001311 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001312
Ted Kremenekaac82832009-02-23 17:45:03 +00001313 // Specially handle NSAutoreleasePool.
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001314 addInstMethSummary("NSAutoreleasePool", "init",
Ted Kremenekaac82832009-02-23 17:45:03 +00001315 getPersistentSummary(RetEffect::MakeReceiverAlias(),
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001316 NewAutoreleasePool));
Ted Kremenekaac82832009-02-23 17:45:03 +00001317
Ted Kremenek45642a42008-08-12 18:48:50 +00001318 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremenek7e3a3272009-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 Kremenekfbf2dc52009-03-04 23:30:42 +00001323 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
Ted Kremeneke5a036a2009-04-03 19:02:51 +00001324 RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet());
1325
1326 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1327
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001328
1329#if 0
Ted Kremeneke44927e2008-07-01 17:21:27 +00001330 RetainSummary *NSWindowSumm =
Ted Kremenek7e3a3272009-02-23 02:51:29 +00001331 getPersistentSummary(RetEffect::MakeReceiverAlias(), StopTracking);
Ted Kremenek45642a42008-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 Kremenekfbf2dc52009-03-04 23:30:42 +00001338#endif
Ted Kremenek45642a42008-08-12 18:48:50 +00001339
1340 // For NSPanel (which subclasses NSWindow), allocated objects are not
1341 // self-owned.
Ted Kremeneke5a036a2009-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 Kremenek45642a42008-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 Kremenek272aa852008-06-25 21:21:56 +00001351
Ted Kremenekf2717b02008-07-18 17:24:20 +00001352 // Create NSAssertionHandler summaries.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001353 addPanicSummary("NSAssertionHandler", "handleFailureInFunction", "file",
1354 "lineNumber", "description", NULL);
Ted Kremenekf2717b02008-07-18 17:24:20 +00001355
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001356 addPanicSummary("NSAssertionHandler", "handleFailureInMethod", "object",
1357 "file", "lineNumber", "description", NULL);
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001358}
1359
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001360//===----------------------------------------------------------------------===//
Ted Kremenek7aef4842008-04-16 20:40:59 +00001361// Reference-counting logic (typestate + counts).
Ted Kremeneka7338b42008-03-11 06:39:11 +00001362//===----------------------------------------------------------------------===//
1363
Ted Kremeneka7338b42008-03-11 06:39:11 +00001364namespace {
1365
Ted Kremenek7d421f32008-04-09 23:49:11 +00001366class VISIBILITY_HIDDEN RefVal {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001367public:
Ted Kremenekd9ccf682008-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 Kremenek6537a642009-03-17 19:42:23 +00001374 ERROR_START,
1375 ErrorDeallocNotOwned, // -dealloc called on non-owned object.
1376 ErrorDeallocGC, // Calling -dealloc with GC enabled.
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001377 ErrorUseAfterRelease, // Object used after released.
1378 ErrorReleaseNotOwned, // Release of an object that was not owned.
Ted Kremenek6537a642009-03-17 19:42:23 +00001379 ERROR_LEAK_START,
Ted Kremenek311f3d42008-10-22 23:56:21 +00001380 ErrorLeak, // A memory leak due to excessive reference counts.
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001381 ErrorLeakReturned, // A memory leak due to the returning method not having
1382 // the correct naming conventions.
1383 ErrorOverAutorelease
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001384 };
Ted Kremenek68621b92009-01-28 05:56:51 +00001385
1386private:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001387 Kind kind;
Ted Kremenek68621b92009-01-28 05:56:51 +00001388 RetEffect::ObjKind okind;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001389 unsigned Cnt;
Ted Kremenek4d99d342009-05-08 20:01:42 +00001390 unsigned ACnt;
Ted Kremenek272aa852008-06-25 21:21:56 +00001391 QualType T;
1392
Ted Kremenek4d99d342009-05-08 20:01:42 +00001393 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, unsigned acnt, QualType t)
1394 : kind(k), okind(o), Cnt(cnt), ACnt(acnt), T(t) {}
Ted Kremenek0d721572008-03-11 17:48:22 +00001395
Ted Kremenek68621b92009-01-28 05:56:51 +00001396 RefVal(Kind k, unsigned cnt = 0)
Ted Kremenek4d99d342009-05-08 20:01:42 +00001397 : kind(k), okind(RetEffect::AnyObj), Cnt(cnt), ACnt(0) {}
Ted Kremenek68621b92009-01-28 05:56:51 +00001398
1399public:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001400 Kind getKind() const { return kind; }
Ted Kremenek68621b92009-01-28 05:56:51 +00001401
1402 RetEffect::ObjKind getObjKind() const { return okind; }
Ted Kremenek0d721572008-03-11 17:48:22 +00001403
Ted Kremenek4d99d342009-05-08 20:01:42 +00001404 unsigned getCount() const { return Cnt; }
1405 unsigned getAutoreleaseCount() const { return ACnt; }
1406 unsigned getCombinedCounts() const { return Cnt + ACnt; }
1407 void clearCounts() { Cnt = 0; ACnt = 0; }
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001408 void setCount(unsigned i) { Cnt = i; }
1409 void setAutoreleaseCount(unsigned i) { ACnt = i; }
Ted Kremenek6537a642009-03-17 19:42:23 +00001410
Ted Kremenek272aa852008-06-25 21:21:56 +00001411 QualType getType() const { return T; }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001412
1413 // Useful predicates.
Ted Kremenek0d721572008-03-11 17:48:22 +00001414
Ted Kremenek6537a642009-03-17 19:42:23 +00001415 static bool isError(Kind k) { return k >= ERROR_START; }
Ted Kremenek1daa16c2008-03-11 18:14:09 +00001416
Ted Kremenek6537a642009-03-17 19:42:23 +00001417 static bool isLeak(Kind k) { return k >= ERROR_LEAK_START; }
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001418
Ted Kremenekffefc352008-04-11 22:25:11 +00001419 bool isOwned() const {
1420 return getKind() == Owned;
1421 }
1422
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001423 bool isNotOwned() const {
1424 return getKind() == NotOwned;
1425 }
1426
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001427 bool isReturnedOwned() const {
1428 return getKind() == ReturnedOwned;
1429 }
1430
1431 bool isReturnedNotOwned() const {
1432 return getKind() == ReturnedNotOwned;
1433 }
1434
1435 bool isNonLeakError() const {
1436 Kind k = getKind();
1437 return isError(k) && !isLeak(k);
1438 }
1439
Ted Kremenek68621b92009-01-28 05:56:51 +00001440 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
1441 unsigned Count = 1) {
Ted Kremenek4d99d342009-05-08 20:01:42 +00001442 return RefVal(Owned, o, Count, 0, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001443 }
1444
Ted Kremenek68621b92009-01-28 05:56:51 +00001445 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
1446 unsigned Count = 0) {
Ted Kremenek4d99d342009-05-08 20:01:42 +00001447 return RefVal(NotOwned, o, Count, 0, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001448 }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001449
1450 static RefVal makeReturnedOwned(unsigned Count) {
1451 return RefVal(ReturnedOwned, Count);
1452 }
1453
1454 static RefVal makeReturnedNotOwned() {
1455 return RefVal(ReturnedNotOwned);
1456 }
1457
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001458 // Comparison, profiling, and pretty-printing.
Ted Kremenek0d721572008-03-11 17:48:22 +00001459
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001460 bool operator==(const RefVal& X) const {
Ted Kremenek272aa852008-06-25 21:21:56 +00001461 return kind == X.kind && Cnt == X.Cnt && T == X.T;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001462 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001463
Ted Kremenek272aa852008-06-25 21:21:56 +00001464 RefVal operator-(size_t i) const {
Ted Kremenek4d99d342009-05-08 20:01:42 +00001465 return RefVal(getKind(), getObjKind(), getCount() - i,
1466 getAutoreleaseCount(), getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001467 }
1468
1469 RefVal operator+(size_t i) const {
Ted Kremenek4d99d342009-05-08 20:01:42 +00001470 return RefVal(getKind(), getObjKind(), getCount() + i,
1471 getAutoreleaseCount(), getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001472 }
1473
1474 RefVal operator^(Kind k) const {
Ted Kremenek4d99d342009-05-08 20:01:42 +00001475 return RefVal(k, getObjKind(), getCount(), getAutoreleaseCount(),
1476 getType());
1477 }
1478
1479 RefVal autorelease() const {
1480 return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount()+1,
1481 getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001482 }
Ted Kremenek6537a642009-03-17 19:42:23 +00001483
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001484 void Profile(llvm::FoldingSetNodeID& ID) const {
1485 ID.AddInteger((unsigned) kind);
1486 ID.AddInteger(Cnt);
Ted Kremenek4d99d342009-05-08 20:01:42 +00001487 ID.AddInteger(ACnt);
Ted Kremenek272aa852008-06-25 21:21:56 +00001488 ID.Add(T);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001489 }
1490
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001491 void print(std::ostream& Out) const;
Ted Kremenek0d721572008-03-11 17:48:22 +00001492};
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001493
1494void RefVal::print(std::ostream& Out) const {
Ted Kremenek272aa852008-06-25 21:21:56 +00001495 if (!T.isNull())
1496 Out << "Tracked Type:" << T.getAsString() << '\n';
1497
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001498 switch (getKind()) {
1499 default: assert(false);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001500 case Owned: {
1501 Out << "Owned";
1502 unsigned cnt = getCount();
1503 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001504 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001505 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001506
Ted Kremenekc4f81022008-04-10 23:09:18 +00001507 case NotOwned: {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001508 Out << "NotOwned";
Ted Kremenekc4f81022008-04-10 23:09:18 +00001509 unsigned cnt = getCount();
1510 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001511 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001512 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001513
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001514 case ReturnedOwned: {
1515 Out << "ReturnedOwned";
1516 unsigned cnt = getCount();
1517 if (cnt) Out << " (+ " << cnt << ")";
1518 break;
1519 }
1520
1521 case ReturnedNotOwned: {
1522 Out << "ReturnedNotOwned";
1523 unsigned cnt = getCount();
1524 if (cnt) Out << " (+ " << cnt << ")";
1525 break;
1526 }
1527
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001528 case Released:
1529 Out << "Released";
1530 break;
Ted Kremenek6537a642009-03-17 19:42:23 +00001531
1532 case ErrorDeallocGC:
1533 Out << "-dealloc (GC)";
1534 break;
1535
1536 case ErrorDeallocNotOwned:
1537 Out << "-dealloc (not-owned)";
1538 break;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001539
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001540 case ErrorLeak:
1541 Out << "Leaked";
1542 break;
1543
Ted Kremenek311f3d42008-10-22 23:56:21 +00001544 case ErrorLeakReturned:
1545 Out << "Leaked (Bad naming)";
1546 break;
1547
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001548 case ErrorUseAfterRelease:
1549 Out << "Use-After-Release [ERROR]";
1550 break;
1551
1552 case ErrorReleaseNotOwned:
1553 Out << "Release of Not-Owned [ERROR]";
1554 break;
Ted Kremenek3f15aba2009-05-09 00:44:07 +00001555
1556 case RefVal::ErrorOverAutorelease:
1557 Out << "Over autoreleased";
1558 break;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001559 }
Ted Kremenek4d99d342009-05-08 20:01:42 +00001560
1561 if (ACnt) {
1562 Out << " [ARC +" << ACnt << ']';
1563 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001564}
Ted Kremenek0d721572008-03-11 17:48:22 +00001565
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001566} // end anonymous namespace
1567
1568//===----------------------------------------------------------------------===//
1569// RefBindings - State used to track object reference counts.
1570//===----------------------------------------------------------------------===//
1571
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001572typedef llvm::ImmutableMap<SymbolRef, RefVal> RefBindings;
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001573static int RefBIndex = 0;
1574
1575namespace clang {
Ted Kremenek91781202008-08-17 03:20:02 +00001576 template<>
1577 struct GRStateTrait<RefBindings> : public GRStatePartialTrait<RefBindings> {
1578 static inline void* GDMIndex() { return &RefBIndex; }
1579 };
1580}
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001581
1582//===----------------------------------------------------------------------===//
Ted Kremenekb6578942009-02-24 19:15:11 +00001583// AutoreleaseBindings - State used to track objects in autorelease pools.
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001584//===----------------------------------------------------------------------===//
1585
Ted Kremenekb6578942009-02-24 19:15:11 +00001586typedef llvm::ImmutableMap<SymbolRef, unsigned> ARCounts;
1587typedef llvm::ImmutableMap<SymbolRef, ARCounts> ARPoolContents;
1588typedef llvm::ImmutableList<SymbolRef> ARStack;
Ted Kremenekaac82832009-02-23 17:45:03 +00001589
Ted Kremenekb6578942009-02-24 19:15:11 +00001590static int AutoRCIndex = 0;
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001591static int AutoRBIndex = 0;
1592
Ted Kremenekb6578942009-02-24 19:15:11 +00001593namespace { class VISIBILITY_HIDDEN AutoreleasePoolContents {}; }
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001594namespace { class VISIBILITY_HIDDEN AutoreleaseStack {}; }
Ted Kremenekb6578942009-02-24 19:15:11 +00001595
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001596namespace clang {
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001597template<> struct GRStateTrait<AutoreleaseStack>
Ted Kremenekb6578942009-02-24 19:15:11 +00001598 : public GRStatePartialTrait<ARStack> {
1599 static inline void* GDMIndex() { return &AutoRBIndex; }
1600};
1601
1602template<> struct GRStateTrait<AutoreleasePoolContents>
1603 : public GRStatePartialTrait<ARPoolContents> {
1604 static inline void* GDMIndex() { return &AutoRCIndex; }
1605};
1606} // end clang namespace
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001607
Ted Kremenek681fb352009-03-20 17:34:15 +00001608static SymbolRef GetCurrentAutoreleasePool(const GRState* state) {
1609 ARStack stack = state->get<AutoreleaseStack>();
1610 return stack.isEmpty() ? SymbolRef() : stack.getHead();
1611}
1612
1613static GRStateRef SendAutorelease(GRStateRef state, ARCounts::Factory &F,
1614 SymbolRef sym) {
1615
1616 SymbolRef pool = GetCurrentAutoreleasePool(state);
1617 const ARCounts *cnts = state.get<AutoreleasePoolContents>(pool);
1618 ARCounts newCnts(0);
1619
1620 if (cnts) {
1621 const unsigned *cnt = (*cnts).lookup(sym);
1622 newCnts = F.Add(*cnts, sym, cnt ? *cnt + 1 : 1);
1623 }
1624 else
1625 newCnts = F.Add(F.GetEmptyMap(), sym, 1);
1626
1627 return state.set<AutoreleasePoolContents>(pool, newCnts);
1628}
1629
Ted Kremenek7aef4842008-04-16 20:40:59 +00001630//===----------------------------------------------------------------------===//
1631// Transfer functions.
1632//===----------------------------------------------------------------------===//
1633
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001634namespace {
1635
Ted Kremenek7d421f32008-04-09 23:49:11 +00001636class VISIBILITY_HIDDEN CFRefCount : public GRSimpleVals {
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001637public:
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001638 class BindingsPrinter : public GRState::Printer {
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001639 public:
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001640 virtual void Print(std::ostream& Out, const GRState* state,
1641 const char* nl, const char* sep);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001642 };
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001643
1644private:
Ted Kremenekc26c4692009-02-18 03:48:14 +00001645 typedef llvm::DenseMap<const GRExprEngine::NodeTy*, const RetainSummary*>
1646 SummaryLogTy;
1647
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001648 RetainSummaryManager Summaries;
Ted Kremenekc26c4692009-02-18 03:48:14 +00001649 SummaryLogTy SummaryLog;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001650 const LangOptions& LOpts;
Ted Kremenekb6578942009-02-24 19:15:11 +00001651 ARCounts::Factory ARCountFactory;
Ted Kremenek91781202008-08-17 03:20:02 +00001652
Ted Kremenek708af042009-02-05 06:50:21 +00001653 BugType *useAfterRelease, *releaseNotOwned;
Ted Kremenek6537a642009-03-17 19:42:23 +00001654 BugType *deallocGC, *deallocNotOwned;
Ted Kremenek708af042009-02-05 06:50:21 +00001655 BugType *leakWithinFunction, *leakAtReturn;
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001656 BugType *overAutorelease;
Ted Kremenek708af042009-02-05 06:50:21 +00001657 BugReporter *BR;
Ted Kremeneka7338b42008-03-11 06:39:11 +00001658
Ted Kremenekb6578942009-02-24 19:15:11 +00001659 GRStateRef Update(GRStateRef state, SymbolRef sym, RefVal V, ArgEffect E,
1660 RefVal::Kind& hasErr);
1661
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001662 void ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
1663 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001664 Expr* NodeExpr, Expr* ErrorExpr,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001665 ExplodedNode<GRState>* Pred,
1666 const GRState* St,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001667 RefVal::Kind hasErr, SymbolRef Sym);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001668
Ted Kremenek41a4bc62009-05-08 23:09:42 +00001669 GRStateRef HandleSymbolDeath(GRStateRef state, SymbolRef sid, RefVal V,
1670 llvm::SmallVectorImpl<SymbolRef> &Leaked);
1671
1672 ExplodedNode<GRState>* ProcessLeaks(GRStateRef state,
1673 llvm::SmallVectorImpl<SymbolRef> &Leaked,
1674 GenericNodeBuilder &Builder,
1675 GRExprEngine &Eng,
1676 ExplodedNode<GRState> *Pred = 0);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001677
Ted Kremenekb6578942009-02-24 19:15:11 +00001678public:
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00001679 CFRefCount(ASTContext& Ctx, bool gcenabled, const LangOptions& lopts)
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001680 : Summaries(Ctx, gcenabled),
Ted Kremenek6537a642009-03-17 19:42:23 +00001681 LOpts(lopts), useAfterRelease(0), releaseNotOwned(0),
1682 deallocGC(0), deallocNotOwned(0),
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001683 leakWithinFunction(0), leakAtReturn(0), overAutorelease(0), BR(0) {}
Ted Kremenek1feab292008-04-16 04:28:53 +00001684
Ted Kremenek708af042009-02-05 06:50:21 +00001685 virtual ~CFRefCount() {}
Ted Kremenek7d421f32008-04-09 23:49:11 +00001686
Ted Kremenekbf6babf2009-02-04 23:49:09 +00001687 void RegisterChecks(BugReporter &BR);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001688
Ted Kremenekb0f2b9e2008-08-16 00:49:49 +00001689 virtual void RegisterPrinters(std::vector<GRState::Printer*>& Printers) {
1690 Printers.push_back(new BindingsPrinter());
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001691 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00001692
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001693 bool isGCEnabled() const { return Summaries.isGCEnabled(); }
Ted Kremenekfe30beb2008-04-30 23:47:44 +00001694 const LangOptions& getLangOptions() const { return LOpts; }
1695
Ted Kremenekc26c4692009-02-18 03:48:14 +00001696 const RetainSummary *getSummaryOfNode(const ExplodedNode<GRState> *N) const {
1697 SummaryLogTy::const_iterator I = SummaryLog.find(N);
1698 return I == SummaryLog.end() ? 0 : I->second;
1699 }
1700
Ted Kremeneka7338b42008-03-11 06:39:11 +00001701 // Calls.
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001702
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001703 void EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001704 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001705 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001706 Expr* Ex,
1707 Expr* Receiver,
Ted Kremenek286e9852009-05-04 04:57:00 +00001708 const RetainSummary& Summ,
Ted Kremenek2719e982008-06-17 02:43:46 +00001709 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001710 ExplodedNode<GRState>* Pred);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001711
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001712 virtual void EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekce0767f2008-03-12 21:06:49 +00001713 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001714 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001715 CallExpr* CE, SVal L,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001716 ExplodedNode<GRState>* Pred);
Ted Kremenek10fe66d2008-04-09 01:10:13 +00001717
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001718
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001719 virtual void EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001720 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001721 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001722 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001723 ExplodedNode<GRState>* Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001724
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001725 bool EvalObjCMessageExprAux(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001726 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001727 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001728 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001729 ExplodedNode<GRState>* Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001730
Ted Kremeneka42be302009-02-14 01:43:44 +00001731 // Stores.
1732 virtual void EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val);
1733
Ted Kremenekffefc352008-04-11 22:25:11 +00001734 // End-of-path.
1735
1736 virtual void EvalEndPath(GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001737 GREndPathNodeBuilder<GRState>& Builder);
Ted Kremenekffefc352008-04-11 22:25:11 +00001738
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001739 virtual void EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek541db372008-04-24 23:57:27 +00001740 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001741 GRStmtNodeBuilder<GRState>& Builder,
1742 ExplodedNode<GRState>* Pred,
Ted Kremenek5c0729b2009-01-21 22:26:05 +00001743 Stmt* S, const GRState* state,
1744 SymbolReaper& SymReaper);
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00001745
1746 std::pair<ExplodedNode<GRState>*, GRStateRef>
1747 HandleAutoreleaseCounts(GRStateRef state, GenericNodeBuilder Bd,
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001748 ExplodedNode<GRState>* Pred, GRExprEngine &Eng,
1749 SymbolRef Sym, RefVal V, bool &stop);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001750 // Return statements.
1751
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001752 virtual void EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001753 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001754 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001755 ReturnStmt* S,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001756 ExplodedNode<GRState>* Pred);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001757
1758 // Assumptions.
1759
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001760 virtual const GRState* EvalAssume(GRStateManager& VMgr,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001761 const GRState* St, SVal Cond,
Ted Kremenekf22f8682008-07-10 22:03:41 +00001762 bool Assumption, bool& isFeasible);
Ted Kremeneka7338b42008-03-11 06:39:11 +00001763};
1764
1765} // end anonymous namespace
1766
Ted Kremenek681fb352009-03-20 17:34:15 +00001767static void PrintPool(std::ostream &Out, SymbolRef Sym, const GRState *state) {
1768 Out << ' ';
Ted Kremenek74556a12009-03-26 03:35:11 +00001769 if (Sym)
1770 Out << Sym->getSymbolID();
Ted Kremenek681fb352009-03-20 17:34:15 +00001771 else
1772 Out << "<pool>";
1773 Out << ":{";
1774
1775 // Get the contents of the pool.
1776 if (const ARCounts *cnts = state->get<AutoreleasePoolContents>(Sym))
1777 for (ARCounts::iterator J=cnts->begin(), EJ=cnts->end(); J != EJ; ++J)
1778 Out << '(' << J.getKey() << ',' << J.getData() << ')';
1779
1780 Out << '}';
1781}
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001782
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001783void CFRefCount::BindingsPrinter::Print(std::ostream& Out, const GRState* state,
1784 const char* nl, const char* sep) {
Ted Kremenek681fb352009-03-20 17:34:15 +00001785
1786
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001787
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001788 RefBindings B = state->get<RefBindings>();
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001789
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001790 if (!B.isEmpty())
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001791 Out << sep << nl;
1792
1793 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
1794 Out << (*I).first << " : ";
1795 (*I).second.print(Out);
1796 Out << nl;
1797 }
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001798
1799 // Print the autorelease stack.
Ted Kremenek681fb352009-03-20 17:34:15 +00001800 Out << sep << nl << "AR pool stack:";
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001801 ARStack stack = state->get<AutoreleaseStack>();
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001802
Ted Kremenek681fb352009-03-20 17:34:15 +00001803 PrintPool(Out, SymbolRef(), state); // Print the caller's pool.
1804 for (ARStack::iterator I=stack.begin(), E=stack.end(); I!=E; ++I)
1805 PrintPool(Out, *I, state);
1806
1807 Out << nl;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001808}
1809
Ted Kremenek47a72422009-04-29 18:50:19 +00001810//===----------------------------------------------------------------------===//
1811// Error reporting.
1812//===----------------------------------------------------------------------===//
1813
1814namespace {
1815
1816 //===-------------===//
1817 // Bug Descriptions. //
1818 //===-------------===//
1819
1820 class VISIBILITY_HIDDEN CFRefBug : public BugType {
1821 protected:
1822 CFRefCount& TF;
1823
1824 CFRefBug(CFRefCount* tf, const char* name)
1825 : BugType(name, "Memory (Core Foundation/Objective-C)"), TF(*tf) {}
1826 public:
1827
1828 CFRefCount& getTF() { return TF; }
1829 const CFRefCount& getTF() const { return TF; }
1830
1831 // FIXME: Eventually remove.
1832 virtual const char* getDescription() const = 0;
1833
1834 virtual bool isLeak() const { return false; }
1835 };
1836
1837 class VISIBILITY_HIDDEN UseAfterRelease : public CFRefBug {
1838 public:
1839 UseAfterRelease(CFRefCount* tf)
1840 : CFRefBug(tf, "Use-after-release") {}
1841
1842 const char* getDescription() const {
1843 return "Reference-counted object is used after it is released";
1844 }
1845 };
1846
1847 class VISIBILITY_HIDDEN BadRelease : public CFRefBug {
1848 public:
1849 BadRelease(CFRefCount* tf) : CFRefBug(tf, "Bad release") {}
1850
1851 const char* getDescription() const {
1852 return "Incorrect decrement of the reference count of an "
1853 "object is not owned at this point by the caller";
1854 }
1855 };
1856
1857 class VISIBILITY_HIDDEN DeallocGC : public CFRefBug {
1858 public:
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001859 DeallocGC(CFRefCount *tf)
1860 : CFRefBug(tf, "-dealloc called while using garbage collection") {}
Ted Kremenek47a72422009-04-29 18:50:19 +00001861
1862 const char *getDescription() const {
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001863 return "-dealloc called while using garbage collection";
Ted Kremenek47a72422009-04-29 18:50:19 +00001864 }
1865 };
1866
1867 class VISIBILITY_HIDDEN DeallocNotOwned : public CFRefBug {
1868 public:
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001869 DeallocNotOwned(CFRefCount *tf)
1870 : CFRefBug(tf, "-dealloc sent to non-exclusively owned object") {}
Ted Kremenek47a72422009-04-29 18:50:19 +00001871
1872 const char *getDescription() const {
1873 return "-dealloc sent to object that may be referenced elsewhere";
1874 }
1875 };
1876
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001877 class VISIBILITY_HIDDEN OverAutorelease : public CFRefBug {
1878 public:
1879 OverAutorelease(CFRefCount *tf) :
1880 CFRefBug(tf, "Object sent -autorelease too many times") {}
1881
1882 const char *getDescription() const {
1883 return "Object will be sent more -release messages from its containing "
1884 "autorelease pools than it has retain counts";
1885 }
1886 };
1887
Ted Kremenek47a72422009-04-29 18:50:19 +00001888 class VISIBILITY_HIDDEN Leak : public CFRefBug {
1889 const bool isReturn;
1890 protected:
1891 Leak(CFRefCount* tf, const char* name, bool isRet)
1892 : CFRefBug(tf, name), isReturn(isRet) {}
1893 public:
1894
1895 const char* getDescription() const { return ""; }
1896
1897 bool isLeak() const { return true; }
1898 };
1899
1900 class VISIBILITY_HIDDEN LeakAtReturn : public Leak {
1901 public:
1902 LeakAtReturn(CFRefCount* tf, const char* name)
1903 : Leak(tf, name, true) {}
1904 };
1905
1906 class VISIBILITY_HIDDEN LeakWithinFunction : public Leak {
1907 public:
1908 LeakWithinFunction(CFRefCount* tf, const char* name)
1909 : Leak(tf, name, false) {}
1910 };
1911
1912 //===---------===//
1913 // Bug Reports. //
1914 //===---------===//
1915
1916 class VISIBILITY_HIDDEN CFRefReport : public RangedBugReport {
1917 protected:
1918 SymbolRef Sym;
1919 const CFRefCount &TF;
1920 public:
1921 CFRefReport(CFRefBug& D, const CFRefCount &tf,
1922 ExplodedNode<GRState> *n, SymbolRef sym)
1923 : RangedBugReport(D, D.getDescription(), n), Sym(sym), TF(tf) {}
1924
1925 virtual ~CFRefReport() {}
1926
1927 CFRefBug& getBugType() {
1928 return (CFRefBug&) RangedBugReport::getBugType();
1929 }
1930 const CFRefBug& getBugType() const {
1931 return (const CFRefBug&) RangedBugReport::getBugType();
1932 }
1933
1934 virtual void getRanges(BugReporter& BR, const SourceRange*& beg,
1935 const SourceRange*& end) {
1936
1937 if (!getBugType().isLeak())
1938 RangedBugReport::getRanges(BR, beg, end);
1939 else
1940 beg = end = 0;
1941 }
1942
1943 SymbolRef getSymbol() const { return Sym; }
1944
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00001945 PathDiagnosticPiece* getEndPath(BugReporterContext& BRC,
Ted Kremenek47a72422009-04-29 18:50:19 +00001946 const ExplodedNode<GRState>* N);
1947
1948 std::pair<const char**,const char**> getExtraDescriptiveText();
1949
1950 PathDiagnosticPiece* VisitNode(const ExplodedNode<GRState>* N,
1951 const ExplodedNode<GRState>* PrevN,
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00001952 BugReporterContext& BRC);
Ted Kremenek47a72422009-04-29 18:50:19 +00001953 };
1954
1955 class VISIBILITY_HIDDEN CFRefLeakReport : public CFRefReport {
1956 SourceLocation AllocSite;
1957 const MemRegion* AllocBinding;
1958 public:
1959 CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
1960 ExplodedNode<GRState> *n, SymbolRef sym,
1961 GRExprEngine& Eng);
1962
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00001963 PathDiagnosticPiece* getEndPath(BugReporterContext& BRC,
Ted Kremenek47a72422009-04-29 18:50:19 +00001964 const ExplodedNode<GRState>* N);
1965
1966 SourceLocation getLocation() const { return AllocSite; }
1967 };
1968} // end anonymous namespace
1969
1970void CFRefCount::RegisterChecks(BugReporter& BR) {
1971 useAfterRelease = new UseAfterRelease(this);
1972 BR.Register(useAfterRelease);
1973
1974 releaseNotOwned = new BadRelease(this);
1975 BR.Register(releaseNotOwned);
1976
1977 deallocGC = new DeallocGC(this);
1978 BR.Register(deallocGC);
1979
1980 deallocNotOwned = new DeallocNotOwned(this);
1981 BR.Register(deallocNotOwned);
1982
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001983 overAutorelease = new OverAutorelease(this);
1984 BR.Register(overAutorelease);
1985
Ted Kremenek47a72422009-04-29 18:50:19 +00001986 // First register "return" leaks.
1987 const char* name = 0;
1988
1989 if (isGCEnabled())
1990 name = "Leak of returned object when using garbage collection";
1991 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
1992 name = "Leak of returned object when not using garbage collection (GC) in "
1993 "dual GC/non-GC code";
1994 else {
1995 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
1996 name = "Leak of returned object";
1997 }
1998
1999 leakAtReturn = new LeakAtReturn(this, name);
2000 BR.Register(leakAtReturn);
2001
2002 // Second, register leaks within a function/method.
2003 if (isGCEnabled())
2004 name = "Leak of object when using garbage collection";
2005 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2006 name = "Leak of object when not using garbage collection (GC) in "
2007 "dual GC/non-GC code";
2008 else {
2009 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2010 name = "Leak";
2011 }
2012
2013 leakWithinFunction = new LeakWithinFunction(this, name);
2014 BR.Register(leakWithinFunction);
2015
2016 // Save the reference to the BugReporter.
2017 this->BR = &BR;
2018}
2019
2020static const char* Msgs[] = {
2021 // GC only
2022 "Code is compiled to only use garbage collection",
2023 // No GC.
2024 "Code is compiled to use reference counts",
2025 // Hybrid, with GC.
2026 "Code is compiled to use either garbage collection (GC) or reference counts"
2027 " (non-GC). The bug occurs with GC enabled",
2028 // Hybrid, without GC
2029 "Code is compiled to use either garbage collection (GC) or reference counts"
2030 " (non-GC). The bug occurs in non-GC mode"
2031};
2032
2033std::pair<const char**,const char**> CFRefReport::getExtraDescriptiveText() {
2034 CFRefCount& TF = static_cast<CFRefBug&>(getBugType()).getTF();
2035
2036 switch (TF.getLangOptions().getGCMode()) {
2037 default:
2038 assert(false);
2039
2040 case LangOptions::GCOnly:
2041 assert (TF.isGCEnabled());
2042 return std::make_pair(&Msgs[0], &Msgs[0]+1);
2043
2044 case LangOptions::NonGC:
2045 assert (!TF.isGCEnabled());
2046 return std::make_pair(&Msgs[1], &Msgs[1]+1);
2047
2048 case LangOptions::HybridGC:
2049 if (TF.isGCEnabled())
2050 return std::make_pair(&Msgs[2], &Msgs[2]+1);
2051 else
2052 return std::make_pair(&Msgs[3], &Msgs[3]+1);
2053 }
2054}
2055
2056static inline bool contains(const llvm::SmallVectorImpl<ArgEffect>& V,
2057 ArgEffect X) {
2058 for (llvm::SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
2059 I!=E; ++I)
2060 if (*I == X) return true;
2061
2062 return false;
2063}
2064
2065PathDiagnosticPiece* CFRefReport::VisitNode(const ExplodedNode<GRState>* N,
2066 const ExplodedNode<GRState>* PrevN,
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002067 BugReporterContext& BRC) {
Ted Kremenek47a72422009-04-29 18:50:19 +00002068
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002069 // Check if the type state has changed.
2070 GRStateManager &StMgr = BRC.getStateManager();
Ted Kremenek47a72422009-04-29 18:50:19 +00002071 GRStateRef PrevSt(PrevN->getState(), StMgr);
2072 GRStateRef CurrSt(N->getState(), StMgr);
2073
2074 const RefVal* CurrT = CurrSt.get<RefBindings>(Sym);
2075 if (!CurrT) return NULL;
2076
2077 const RefVal& CurrV = *CurrT;
2078 const RefVal* PrevT = PrevSt.get<RefBindings>(Sym);
2079
2080 // Create a string buffer to constain all the useful things we want
2081 // to tell the user.
2082 std::string sbuf;
2083 llvm::raw_string_ostream os(sbuf);
2084
2085 // This is the allocation site since the previous node had no bindings
2086 // for this symbol.
2087 if (!PrevT) {
2088 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2089
2090 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2091 // Get the name of the callee (if it is available).
2092 SVal X = CurrSt.GetSValAsScalarOrLoc(CE->getCallee());
2093 if (const FunctionDecl* FD = X.getAsFunctionDecl())
2094 os << "Call to function '" << FD->getNameAsString() <<'\'';
2095 else
2096 os << "function call";
2097 }
2098 else {
2099 assert (isa<ObjCMessageExpr>(S));
2100 os << "Method";
2101 }
2102
2103 if (CurrV.getObjKind() == RetEffect::CF) {
2104 os << " returns a Core Foundation object with a ";
2105 }
2106 else {
2107 assert (CurrV.getObjKind() == RetEffect::ObjC);
2108 os << " returns an Objective-C object with a ";
2109 }
2110
2111 if (CurrV.isOwned()) {
2112 os << "+1 retain count (owning reference).";
2113
2114 if (static_cast<CFRefBug&>(getBugType()).getTF().isGCEnabled()) {
2115 assert(CurrV.getObjKind() == RetEffect::CF);
2116 os << " "
2117 "Core Foundation objects are not automatically garbage collected.";
2118 }
2119 }
2120 else {
2121 assert (CurrV.isNotOwned());
2122 os << "+0 retain count (non-owning reference).";
2123 }
2124
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002125 PathDiagnosticLocation Pos(S, BRC.getSourceManager());
Ted Kremenek47a72422009-04-29 18:50:19 +00002126 return new PathDiagnosticEventPiece(Pos, os.str());
2127 }
2128
2129 // Gather up the effects that were performed on the object at this
2130 // program point
2131 llvm::SmallVector<ArgEffect, 2> AEffects;
2132
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002133 if (const RetainSummary *Summ =
2134 TF.getSummaryOfNode(BRC.getNodeResolver().getOriginalNode(N))) {
Ted Kremenek47a72422009-04-29 18:50:19 +00002135 // We only have summaries attached to nodes after evaluating CallExpr and
2136 // ObjCMessageExprs.
2137 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2138
2139 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2140 // Iterate through the parameter expressions and see if the symbol
2141 // was ever passed as an argument.
2142 unsigned i = 0;
2143
2144 for (CallExpr::arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
2145 AI!=AE; ++AI, ++i) {
2146
2147 // Retrieve the value of the argument. Is it the symbol
2148 // we are interested in?
2149 if (CurrSt.GetSValAsScalarOrLoc(*AI).getAsLocSymbol() != Sym)
2150 continue;
2151
2152 // We have an argument. Get the effect!
2153 AEffects.push_back(Summ->getArg(i));
2154 }
2155 }
2156 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
2157 if (Expr *receiver = ME->getReceiver())
2158 if (CurrSt.GetSValAsScalarOrLoc(receiver).getAsLocSymbol() == Sym) {
2159 // The symbol we are tracking is the receiver.
2160 AEffects.push_back(Summ->getReceiverEffect());
2161 }
2162 }
2163 }
2164
2165 do {
2166 // Get the previous type state.
2167 RefVal PrevV = *PrevT;
2168
2169 // Specially handle -dealloc.
2170 if (!TF.isGCEnabled() && contains(AEffects, Dealloc)) {
2171 // Determine if the object's reference count was pushed to zero.
2172 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2173 // We may not have transitioned to 'release' if we hit an error.
2174 // This case is handled elsewhere.
2175 if (CurrV.getKind() == RefVal::Released) {
Ted Kremenek4d99d342009-05-08 20:01:42 +00002176 assert(CurrV.getCombinedCounts() == 0);
Ted Kremenek47a72422009-04-29 18:50:19 +00002177 os << "Object released by directly sending the '-dealloc' message";
2178 break;
2179 }
2180 }
2181
2182 // Specially handle CFMakeCollectable and friends.
2183 if (contains(AEffects, MakeCollectable)) {
2184 // Get the name of the function.
2185 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2186 SVal X = CurrSt.GetSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee());
2187 const FunctionDecl* FD = X.getAsFunctionDecl();
2188 const std::string& FName = FD->getNameAsString();
2189
2190 if (TF.isGCEnabled()) {
2191 // Determine if the object's reference count was pushed to zero.
2192 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2193
2194 os << "In GC mode a call to '" << FName
2195 << "' decrements an object's retain count and registers the "
2196 "object with the garbage collector. ";
2197
2198 if (CurrV.getKind() == RefVal::Released) {
2199 assert(CurrV.getCount() == 0);
2200 os << "Since it now has a 0 retain count the object can be "
2201 "automatically collected by the garbage collector.";
2202 }
2203 else
2204 os << "An object must have a 0 retain count to be garbage collected. "
2205 "After this call its retain count is +" << CurrV.getCount()
2206 << '.';
2207 }
2208 else
2209 os << "When GC is not enabled a call to '" << FName
2210 << "' has no effect on its argument.";
2211
2212 // Nothing more to say.
2213 break;
2214 }
2215
2216 // Determine if the typestate has changed.
2217 if (!(PrevV == CurrV))
2218 switch (CurrV.getKind()) {
2219 case RefVal::Owned:
2220 case RefVal::NotOwned:
2221
Ted Kremenek4d99d342009-05-08 20:01:42 +00002222 if (PrevV.getCount() == CurrV.getCount()) {
2223 // Did an autorelease message get sent?
2224 if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
2225 return 0;
2226
2227 assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount());
2228 os << "Object added to autorelease pool.";
2229 break;
2230 }
Ted Kremenek47a72422009-04-29 18:50:19 +00002231
2232 if (PrevV.getCount() > CurrV.getCount())
2233 os << "Reference count decremented.";
2234 else
2235 os << "Reference count incremented.";
2236
2237 if (unsigned Count = CurrV.getCount())
2238 os << " The object now has a +" << Count << " retain count.";
2239
2240 if (PrevV.getKind() == RefVal::Released) {
2241 assert(TF.isGCEnabled() && CurrV.getCount() > 0);
2242 os << " The object is not eligible for garbage collection until the "
2243 "retain count reaches 0 again.";
2244 }
2245
2246 break;
2247
2248 case RefVal::Released:
2249 os << "Object released.";
2250 break;
2251
2252 case RefVal::ReturnedOwned:
2253 os << "Object returned to caller as an owning reference (single retain "
2254 "count transferred to caller).";
2255 break;
2256
2257 case RefVal::ReturnedNotOwned:
2258 os << "Object returned to caller with a +0 (non-owning) retain count.";
2259 break;
2260
2261 default:
2262 return NULL;
2263 }
2264
2265 // Emit any remaining diagnostics for the argument effects (if any).
2266 for (llvm::SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
2267 E=AEffects.end(); I != E; ++I) {
2268
2269 // A bunch of things have alternate behavior under GC.
2270 if (TF.isGCEnabled())
2271 switch (*I) {
2272 default: break;
2273 case Autorelease:
2274 os << "In GC mode an 'autorelease' has no effect.";
2275 continue;
2276 case IncRefMsg:
2277 os << "In GC mode the 'retain' message has no effect.";
2278 continue;
2279 case DecRefMsg:
2280 os << "In GC mode the 'release' message has no effect.";
2281 continue;
2282 }
2283 }
2284 } while(0);
2285
2286 if (os.str().empty())
2287 return 0; // We have nothing to say!
2288
2289 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002290 PathDiagnosticLocation Pos(S, BRC.getSourceManager());
Ted Kremenek47a72422009-04-29 18:50:19 +00002291 PathDiagnosticPiece* P = new PathDiagnosticEventPiece(Pos, os.str());
2292
2293 // Add the range by scanning the children of the statement for any bindings
2294 // to Sym.
2295 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I)
2296 if (Expr* Exp = dyn_cast_or_null<Expr>(*I))
2297 if (CurrSt.GetSValAsScalarOrLoc(Exp).getAsLocSymbol() == Sym) {
2298 P->addRange(Exp->getSourceRange());
2299 break;
2300 }
2301
2302 return P;
2303}
2304
2305namespace {
2306 class VISIBILITY_HIDDEN FindUniqueBinding :
2307 public StoreManager::BindingsHandler {
2308 SymbolRef Sym;
2309 const MemRegion* Binding;
2310 bool First;
2311
2312 public:
2313 FindUniqueBinding(SymbolRef sym) : Sym(sym), Binding(0), First(true) {}
2314
2315 bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
2316 SVal val) {
2317
2318 SymbolRef SymV = val.getAsSymbol();
2319 if (!SymV || SymV != Sym)
2320 return true;
2321
2322 if (Binding) {
2323 First = false;
2324 return false;
2325 }
2326 else
2327 Binding = R;
2328
2329 return true;
2330 }
2331
2332 operator bool() { return First && Binding; }
2333 const MemRegion* getRegion() { return Binding; }
2334 };
2335}
2336
2337static std::pair<const ExplodedNode<GRState>*,const MemRegion*>
2338GetAllocationSite(GRStateManager& StateMgr, const ExplodedNode<GRState>* N,
2339 SymbolRef Sym) {
2340
2341 // Find both first node that referred to the tracked symbol and the
2342 // memory location that value was store to.
2343 const ExplodedNode<GRState>* Last = N;
2344 const MemRegion* FirstBinding = 0;
2345
2346 while (N) {
2347 const GRState* St = N->getState();
2348 RefBindings B = St->get<RefBindings>();
2349
2350 if (!B.lookup(Sym))
2351 break;
2352
2353 FindUniqueBinding FB(Sym);
2354 StateMgr.iterBindings(St, FB);
2355 if (FB) FirstBinding = FB.getRegion();
2356
2357 Last = N;
2358 N = N->pred_empty() ? NULL : *(N->pred_begin());
2359 }
2360
2361 return std::make_pair(Last, FirstBinding);
2362}
2363
2364PathDiagnosticPiece*
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002365CFRefReport::getEndPath(BugReporterContext& BRC,
2366 const ExplodedNode<GRState>* EndN) {
2367 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenek47a72422009-04-29 18:50:19 +00002368 // assigned to different variables, etc.
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002369 BRC.addNotableSymbol(Sym);
2370 return RangedBugReport::getEndPath(BRC, EndN);
Ted Kremenek47a72422009-04-29 18:50:19 +00002371}
2372
2373PathDiagnosticPiece*
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002374CFRefLeakReport::getEndPath(BugReporterContext& BRC,
2375 const ExplodedNode<GRState>* EndN){
Ted Kremenek47a72422009-04-29 18:50:19 +00002376
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002377 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenek47a72422009-04-29 18:50:19 +00002378 // assigned to different variables, etc.
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002379 BRC.addNotableSymbol(Sym);
Ted Kremenek47a72422009-04-29 18:50:19 +00002380
2381 // We are reporting a leak. Walk up the graph to get to the first node where
2382 // the symbol appeared, and also get the first VarDecl that tracked object
2383 // is stored to.
2384 const ExplodedNode<GRState>* AllocNode = 0;
2385 const MemRegion* FirstBinding = 0;
2386
2387 llvm::tie(AllocNode, FirstBinding) =
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00002388 GetAllocationSite(BRC.getStateManager(), EndN, Sym);
Ted Kremenek47a72422009-04-29 18:50:19 +00002389
2390 // Get the allocate site.
2391 assert(AllocNode);
2392 Stmt* FirstStmt = cast<PostStmt>(AllocNode->getLocation()).getStmt();
2393
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002394 SourceManager& SMgr = BRC.getSourceManager();
Ted Kremenek47a72422009-04-29 18:50:19 +00002395 unsigned AllocLine =SMgr.getInstantiationLineNumber(FirstStmt->getLocStart());
2396
2397 // Compute an actual location for the leak. Sometimes a leak doesn't
2398 // occur at an actual statement (e.g., transition between blocks; end
2399 // of function) so we need to walk the graph and compute a real location.
2400 const ExplodedNode<GRState>* LeakN = EndN;
2401 PathDiagnosticLocation L;
2402
2403 while (LeakN) {
2404 ProgramPoint P = LeakN->getLocation();
2405
2406 if (const PostStmt *PS = dyn_cast<PostStmt>(&P)) {
2407 L = PathDiagnosticLocation(PS->getStmt()->getLocStart(), SMgr);
2408 break;
2409 }
2410 else if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
2411 if (const Stmt* Term = BE->getSrc()->getTerminator()) {
2412 L = PathDiagnosticLocation(Term->getLocStart(), SMgr);
2413 break;
2414 }
2415 }
2416
2417 LeakN = LeakN->succ_empty() ? 0 : *(LeakN->succ_begin());
2418 }
2419
2420 if (!L.isValid()) {
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002421 const Decl &D = BRC.getCodeDecl();
2422 L = PathDiagnosticLocation(D.getBodyRBrace(BRC.getASTContext()), SMgr);
Ted Kremenek47a72422009-04-29 18:50:19 +00002423 }
2424
2425 std::string sbuf;
2426 llvm::raw_string_ostream os(sbuf);
2427
2428 os << "Object allocated on line " << AllocLine;
2429
2430 if (FirstBinding)
2431 os << " and stored into '" << FirstBinding->getString() << '\'';
2432
2433 // Get the retain count.
2434 const RefVal* RV = EndN->getState()->get<RefBindings>(Sym);
2435
2436 if (RV->getKind() == RefVal::ErrorLeakReturned) {
2437 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
2438 // ojbects. Only "copy", "alloc", "retain" and "new" transfer ownership
2439 // to the caller for NS objects.
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002440 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(BRC.getCodeDecl());
Ted Kremenek47a72422009-04-29 18:50:19 +00002441 os << " is returned from a method whose name ('"
Ted Kremenek314b1952009-04-29 23:03:22 +00002442 << MD.getSelector().getAsString()
Ted Kremenek47a72422009-04-29 18:50:19 +00002443 << "') does not contain 'copy' or otherwise starts with"
2444 " 'new' or 'alloc'. This violates the naming convention rules given"
Ted Kremenek2a410c92009-04-29 22:25:52 +00002445 " in the Memory Management Guide for Cocoa (object leaked)";
Ted Kremenek47a72422009-04-29 18:50:19 +00002446 }
2447 else
2448 os << " is no longer referenced after this point and has a retain count of"
Ted Kremenek2a410c92009-04-29 22:25:52 +00002449 " +" << RV->getCount() << " (object leaked)";
Ted Kremenek47a72422009-04-29 18:50:19 +00002450
2451 return new PathDiagnosticEventPiece(L, os.str());
2452}
2453
2454
2455CFRefLeakReport::CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2456 ExplodedNode<GRState> *n,
2457 SymbolRef sym, GRExprEngine& Eng)
2458: CFRefReport(D, tf, n, sym)
2459{
2460
2461 // Most bug reports are cached at the location where they occured.
2462 // With leaks, we want to unique them by the location where they were
2463 // allocated, and only report a single path. To do this, we need to find
2464 // the allocation site of a piece of tracked memory, which we do via a
2465 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2466 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2467 // that all ancestor nodes that represent the allocation site have the
2468 // same SourceLocation.
2469 const ExplodedNode<GRState>* AllocNode = 0;
2470
2471 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding.
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00002472 GetAllocationSite(Eng.getStateManager(), getEndNode(), getSymbol());
Ted Kremenek47a72422009-04-29 18:50:19 +00002473
2474 // Get the SourceLocation for the allocation site.
2475 ProgramPoint P = AllocNode->getLocation();
2476 AllocSite = cast<PostStmt>(P).getStmt()->getLocStart();
2477
2478 // Fill in the description of the bug.
2479 Description.clear();
2480 llvm::raw_string_ostream os(Description);
2481 SourceManager& SMgr = Eng.getContext().getSourceManager();
2482 unsigned AllocLine = SMgr.getInstantiationLineNumber(AllocSite);
Ted Kremenek2e9d0302009-05-02 19:05:19 +00002483 os << "Potential leak ";
2484 if (tf.isGCEnabled()) {
2485 os << "(when using garbage collection) ";
2486 }
2487 os << "of an object allocated on line " << AllocLine;
Ted Kremenek47a72422009-04-29 18:50:19 +00002488
2489 // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2490 if (AllocBinding)
2491 os << " and stored into '" << AllocBinding->getString() << '\'';
2492}
2493
2494//===----------------------------------------------------------------------===//
2495// Main checker logic.
2496//===----------------------------------------------------------------------===//
2497
Ted Kremenek272aa852008-06-25 21:21:56 +00002498/// GetReturnType - Used to get the return type of a message expression or
2499/// function call with the intention of affixing that type to a tracked symbol.
2500/// While the the return type can be queried directly from RetEx, when
2501/// invoking class methods we augment to the return type to be that of
2502/// a pointer to the class (as opposed it just being id).
2503static QualType GetReturnType(Expr* RetE, ASTContext& Ctx) {
2504
2505 QualType RetTy = RetE->getType();
2506
2507 // FIXME: We aren't handling id<...>.
Chris Lattnerb724ab22008-07-26 22:36:27 +00002508 const PointerType* PT = RetTy->getAsPointerType();
Ted Kremenek272aa852008-06-25 21:21:56 +00002509 if (!PT)
2510 return RetTy;
2511
2512 // If RetEx is not a message expression just return its type.
2513 // If RetEx is a message expression, return its types if it is something
2514 /// more specific than id.
2515
2516 ObjCMessageExpr* ME = dyn_cast<ObjCMessageExpr>(RetE);
2517
Steve Naroff17c03822009-02-12 17:52:19 +00002518 if (!ME || !Ctx.isObjCIdStructType(PT->getPointeeType()))
Ted Kremenek272aa852008-06-25 21:21:56 +00002519 return RetTy;
2520
2521 ObjCInterfaceDecl* D = ME->getClassInfo().first;
2522
2523 // At this point we know the return type of the message expression is id.
2524 // If we have an ObjCInterceDecl, we know this is a call to a class method
2525 // whose type we can resolve. In such cases, promote the return type to
2526 // Class*.
2527 return !D ? RetTy : Ctx.getPointerType(Ctx.getObjCInterfaceType(D));
2528}
2529
2530
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002531void CFRefCount::EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002532 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002533 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002534 Expr* Ex,
2535 Expr* Receiver,
Ted Kremenek286e9852009-05-04 04:57:00 +00002536 const RetainSummary& Summ,
Zhongxing Xucac107a2009-04-20 05:24:46 +00002537 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002538 ExplodedNode<GRState>* Pred) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002539
Ted Kremeneka7338b42008-03-11 06:39:11 +00002540 // Get the state.
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002541 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenek0106e202008-10-24 20:32:50 +00002542 ASTContext& Ctx = Eng.getStateManager().getContext();
Ted Kremenek227c5372008-05-06 02:41:27 +00002543
2544 // Evaluate the effect of the arguments.
Ted Kremenek1feab292008-04-16 04:28:53 +00002545 RefVal::Kind hasErr = (RefVal::Kind) 0;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002546 unsigned idx = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002547 Expr* ErrorExpr = NULL;
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002548 SymbolRef ErrorSym = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002549
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002550 for (ExprIterator I = arg_beg; I != arg_end; ++I, ++idx) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002551 SVal V = state.GetSValAsScalarOrLoc(*I);
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002552 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002553
Ted Kremenek74556a12009-03-26 03:35:11 +00002554 if (Sym)
Ted Kremenekb6578942009-02-24 19:15:11 +00002555 if (RefBindings::data_type* T = state.get<RefBindings>(Sym)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002556 state = Update(state, Sym, *T, Summ.getArg(idx), hasErr);
Ted Kremenekb6578942009-02-24 19:15:11 +00002557 if (hasErr) {
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002558 ErrorExpr = *I;
Ted Kremenek6064a362008-07-07 16:21:19 +00002559 ErrorSym = Sym;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002560 break;
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002561 }
2562 continue;
Ted Kremenekb6578942009-02-24 19:15:11 +00002563 }
Ted Kremenekede40b72008-07-09 18:11:16 +00002564
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002565 if (isa<Loc>(V)) {
2566 if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(&V)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002567 if (Summ.getArg(idx) == DoNothingByRef)
Ted Kremenekede40b72008-07-09 18:11:16 +00002568 continue;
2569
2570 // Invalidate the value of the variable passed by reference.
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002571
2572 // FIXME: Either this logic should also be replicated in GRSimpleVals
2573 // or should be pulled into a separate "constraint engine."
Ted Kremenekede40b72008-07-09 18:11:16 +00002574
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002575 // FIXME: We can have collisions on the conjured symbol if the
2576 // expression *I also creates conjured symbols. We probably want
2577 // to identify conjured symbols by an expression pair: the enclosing
2578 // expression (the context) and the expression itself. This should
Ted Kremenekede40b72008-07-09 18:11:16 +00002579 // disambiguate conjured symbols.
Ted Kremenekb15eba42008-10-04 05:50:14 +00002580
Ted Kremenek38a4b4b2008-10-17 20:28:54 +00002581 const TypedRegion* R = dyn_cast<TypedRegion>(MR->getRegion());
Zhongxing Xub9d47a42009-04-29 02:30:09 +00002582
Ted Kremenek73ec7732009-05-06 18:19:24 +00002583 if (R) {
2584 // Are we dealing with an ElementRegion? If the element type is
2585 // a basic integer type (e.g., char, int) and the underying region
2586 // is also typed then strip off the ElementRegion.
2587 // FIXME: We really need to think about this for the general case
2588 // as sometimes we are reasoning about arrays and other times
2589 // about (char*), etc., is just a form of passing raw bytes.
2590 // e.g., void *p = alloca(); foo((char*)p);
2591 if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
2592 // Checking for 'integral type' is probably too promiscuous, but
2593 // we'll leave it in for now until we have a systematic way of
2594 // handling all of these cases. Eventually we need to come up
2595 // with an interface to StoreManager so that this logic can be
2596 // approriately delegated to the respective StoreManagers while
2597 // still allowing us to do checker-specific logic (e.g.,
2598 // invalidating reference counts), probably via callbacks.
2599 if (ER->getElementType()->isIntegralType())
2600 if (const TypedRegion *superReg =
2601 dyn_cast<TypedRegion>(ER->getSuperRegion()))
2602 R = superReg;
2603 // FIXME: What about layers of ElementRegions?
2604 }
2605
Ted Kremenek618c6cd2008-12-18 23:34:57 +00002606 // Is the invalidated variable something that we were tracking?
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002607 SymbolRef Sym = state.GetSValAsScalarOrLoc(R).getAsLocSymbol();
Ted Kremenek618c6cd2008-12-18 23:34:57 +00002608
Ted Kremenek53b24182009-03-04 22:56:43 +00002609 // Remove any existing reference-count binding.
Ted Kremenek74556a12009-03-26 03:35:11 +00002610 if (Sym) state = state.remove<RefBindings>(Sym);
Ted Kremenekb15eba42008-10-04 05:50:14 +00002611
Ted Kremenek53b24182009-03-04 22:56:43 +00002612 if (R->isBoundable(Ctx)) {
2613 // Set the value of the variable to be a conjured symbol.
2614 unsigned Count = Builder.getCurrentBlockCount();
Zhongxing Xub02c8522009-05-09 00:50:33 +00002615 QualType T = R->getObjectType(Ctx);
Ted Kremenek53b24182009-03-04 22:56:43 +00002616
Zhongxing Xu079dc352009-04-09 06:03:54 +00002617 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())){
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002618 ValueManager &ValMgr = Eng.getValueManager();
2619 SVal V = ValMgr.getConjuredSymbolVal(*I, T, Count);
Zhongxing Xu079dc352009-04-09 06:03:54 +00002620 state = state.BindLoc(Loc::MakeVal(R), V);
Ted Kremenek53b24182009-03-04 22:56:43 +00002621 }
2622 else if (const RecordType *RT = T->getAsStructureType()) {
2623 // Handle structs in a not so awesome way. Here we just
2624 // eagerly bind new symbols to the fields. In reality we
2625 // should have the store manager handle this. The idea is just
2626 // to prototype some basic functionality here. All of this logic
2627 // should one day soon just go away.
2628 const RecordDecl *RD = RT->getDecl()->getDefinition(Ctx);
2629
2630 // No record definition. There is nothing we can do.
2631 if (!RD)
2632 continue;
2633
2634 MemRegionManager &MRMgr = state.getManager().getRegionManager();
2635
2636 // Iterate through the fields and construct new symbols.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002637 for (RecordDecl::field_iterator FI=RD->field_begin(Ctx),
2638 FE=RD->field_end(Ctx); FI!=FE; ++FI) {
Ted Kremenek53b24182009-03-04 22:56:43 +00002639
2640 // For now just handle scalar fields.
2641 FieldDecl *FD = *FI;
2642 QualType FT = FD->getType();
2643
2644 if (Loc::IsLocType(FT) ||
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002645 (FT->isIntegerType() && FT->isScalarType())) {
Ted Kremenek53b24182009-03-04 22:56:43 +00002646 const FieldRegion* FR = MRMgr.getFieldRegion(FD, R);
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002647 ValueManager &ValMgr = Eng.getValueManager();
2648 SVal V = ValMgr.getConjuredSymbolVal(*I, FT, Count);
Zhongxing Xuc458e322009-04-09 06:32:20 +00002649 state = state.BindLoc(Loc::MakeVal(FR), V);
Ted Kremenek53b24182009-03-04 22:56:43 +00002650 }
2651 }
2652 }
2653 else {
2654 // Just blast away other values.
2655 state = state.BindLoc(*MR, UnknownVal());
2656 }
Ted Kremenek8f90e712008-10-17 22:23:12 +00002657 }
Ted Kremenekb15eba42008-10-04 05:50:14 +00002658 }
2659 else
Ted Kremenek09102db2008-11-12 19:22:09 +00002660 state = state.BindLoc(*MR, UnknownVal());
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002661 }
2662 else {
2663 // Nuke all other arguments passed by reference.
Zhongxing Xu097fc982008-10-17 05:57:07 +00002664 state = state.Unbind(cast<Loc>(V));
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002665 }
Ted Kremeneke4924202008-04-11 20:51:02 +00002666 }
Zhongxing Xu097fc982008-10-17 05:57:07 +00002667 else if (isa<nonloc::LocAsInteger>(V))
2668 state = state.Unbind(cast<nonloc::LocAsInteger>(V).getLoc());
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002669 }
Ted Kremenek1feab292008-04-16 04:28:53 +00002670
Ted Kremenek272aa852008-06-25 21:21:56 +00002671 // Evaluate the effect on the message receiver.
Ted Kremenek227c5372008-05-06 02:41:27 +00002672 if (!ErrorExpr && Receiver) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002673 SymbolRef Sym = state.GetSValAsScalarOrLoc(Receiver).getAsLocSymbol();
Ted Kremenek74556a12009-03-26 03:35:11 +00002674 if (Sym) {
Ted Kremenekb6578942009-02-24 19:15:11 +00002675 if (const RefVal* T = state.get<RefBindings>(Sym)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002676 state = Update(state, Sym, *T, Summ.getReceiverEffect(), hasErr);
Ted Kremenekb6578942009-02-24 19:15:11 +00002677 if (hasErr) {
Ted Kremenek227c5372008-05-06 02:41:27 +00002678 ErrorExpr = Receiver;
Ted Kremenek6064a362008-07-07 16:21:19 +00002679 ErrorSym = Sym;
Ted Kremenek227c5372008-05-06 02:41:27 +00002680 }
Ted Kremenekb6578942009-02-24 19:15:11 +00002681 }
Ted Kremenek227c5372008-05-06 02:41:27 +00002682 }
2683 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002684
Ted Kremenek272aa852008-06-25 21:21:56 +00002685 // Process any errors.
Ted Kremenek1feab292008-04-16 04:28:53 +00002686 if (hasErr) {
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002687 ProcessNonLeakError(Dst, Builder, Ex, ErrorExpr, Pred, state,
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002688 hasErr, ErrorSym);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002689 return;
Ted Kremenek0d721572008-03-11 17:48:22 +00002690 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002691
Ted Kremenekf2717b02008-07-18 17:24:20 +00002692 // Consult the summary for the return value.
Ted Kremenek286e9852009-05-04 04:57:00 +00002693 RetEffect RE = Summ.getRetEffect();
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002694
2695 switch (RE.getKind()) {
2696 default:
2697 assert (false && "Unhandled RetEffect."); break;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002698
Ted Kremenek8f90e712008-10-17 22:23:12 +00002699 case RetEffect::NoRet: {
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002700
Ted Kremenek455dd862008-04-11 20:23:24 +00002701 // Make up a symbol for the return value (not reference counted).
Ted Kremeneke4924202008-04-11 20:51:02 +00002702 // FIXME: This is basically copy-and-paste from GRSimpleVals. We
2703 // should compose behavior, not copy it.
Ted Kremenek455dd862008-04-11 20:23:24 +00002704
Ted Kremenek8f90e712008-10-17 22:23:12 +00002705 // FIXME: We eventually should handle structs and other compound types
2706 // that are returned by value.
2707
2708 QualType T = Ex->getType();
2709
Ted Kremenek79413a52008-11-13 06:10:40 +00002710 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())) {
Ted Kremenek455dd862008-04-11 20:23:24 +00002711 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002712 ValueManager &ValMgr = Eng.getValueManager();
2713 SVal X = ValMgr.getConjuredSymbolVal(Ex, T, Count);
Ted Kremenek09102db2008-11-12 19:22:09 +00002714 state = state.BindExpr(Ex, X, false);
Ted Kremenek455dd862008-04-11 20:23:24 +00002715 }
2716
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002717 break;
Ted Kremenek8f90e712008-10-17 22:23:12 +00002718 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002719
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002720 case RetEffect::Alias: {
Ted Kremenek272aa852008-06-25 21:21:56 +00002721 unsigned idx = RE.getIndex();
Ted Kremenek2719e982008-06-17 02:43:46 +00002722 assert (arg_end >= arg_beg);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002723 assert (idx < (unsigned) (arg_end - arg_beg));
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002724 SVal V = state.GetSValAsScalarOrLoc(*(arg_beg+idx));
Ted Kremenek09102db2008-11-12 19:22:09 +00002725 state = state.BindExpr(Ex, V, false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002726 break;
2727 }
2728
Ted Kremenek227c5372008-05-06 02:41:27 +00002729 case RetEffect::ReceiverAlias: {
2730 assert (Receiver);
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002731 SVal V = state.GetSValAsScalarOrLoc(Receiver);
Ted Kremenek09102db2008-11-12 19:22:09 +00002732 state = state.BindExpr(Ex, V, false);
Ted Kremenek227c5372008-05-06 02:41:27 +00002733 break;
2734 }
2735
Ted Kremenek6a1cc252008-06-23 18:02:52 +00002736 case RetEffect::OwnedAllocatedSymbol:
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002737 case RetEffect::OwnedSymbol: {
2738 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke9e726e2009-04-09 16:13:17 +00002739 ValueManager &ValMgr = Eng.getValueManager();
2740 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
2741 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
2742 state = state.set<RefBindings>(Sym, RefVal::makeOwned(RE.getObjKind(),
2743 RetT));
2744 state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenek45c52a12009-03-09 22:46:49 +00002745
2746 // FIXME: Add a flag to the checker where allocations are assumed to
2747 // *not fail.
2748#if 0
Ted Kremeneke62fd052009-01-28 22:27:59 +00002749 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) {
2750 bool isFeasible;
2751 state = state.Assume(loc::SymbolVal(Sym), true, isFeasible);
2752 assert(isFeasible && "Cannot assume fresh symbol is non-null.");
2753 }
Ted Kremenek45c52a12009-03-09 22:46:49 +00002754#endif
Ted Kremenek6a1cc252008-06-23 18:02:52 +00002755
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002756 break;
2757 }
Ted Kremenek382fb4e2009-04-27 19:14:45 +00002758
2759 case RetEffect::GCNotOwnedSymbol:
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002760 case RetEffect::NotOwnedSymbol: {
2761 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke9e726e2009-04-09 16:13:17 +00002762 ValueManager &ValMgr = Eng.getValueManager();
2763 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
2764 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
2765 state = state.set<RefBindings>(Sym, RefVal::makeNotOwned(RE.getObjKind(),
2766 RetT));
2767 state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002768 break;
2769 }
2770 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002771
Ted Kremenek0dd65012009-02-18 02:00:25 +00002772 // Generate a sink node if we are at the end of a path.
2773 GRExprEngine::NodeTy *NewNode =
Ted Kremenek286e9852009-05-04 04:57:00 +00002774 Summ.isEndPath() ? Builder.MakeSinkNode(Dst, Ex, Pred, state)
2775 : Builder.MakeNode(Dst, Ex, Pred, state);
Ted Kremenek0dd65012009-02-18 02:00:25 +00002776
2777 // Annotate the edge with summary we used.
Ted Kremenek286e9852009-05-04 04:57:00 +00002778 if (NewNode) SummaryLog[NewNode] = &Summ;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002779}
2780
2781
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002782void CFRefCount::EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002783 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002784 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu097fc982008-10-17 05:57:07 +00002785 CallExpr* CE, SVal L,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002786 ExplodedNode<GRState>* Pred) {
Zhongxing Xucac107a2009-04-20 05:24:46 +00002787 const FunctionDecl* FD = L.getAsFunctionDecl();
Ted Kremenek286e9852009-05-04 04:57:00 +00002788 RetainSummary* Summ = !FD ? Summaries.getDefaultSummary()
Zhongxing Xucac107a2009-04-20 05:24:46 +00002789 : Summaries.getSummary(const_cast<FunctionDecl*>(FD));
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002790
Ted Kremenek286e9852009-05-04 04:57:00 +00002791 assert(Summ);
2792 EvalSummary(Dst, Eng, Builder, CE, 0, *Summ,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002793 CE->arg_begin(), CE->arg_end(), Pred);
Ted Kremenek827f93b2008-03-06 00:08:09 +00002794}
Ted Kremeneka7338b42008-03-11 06:39:11 +00002795
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002796void CFRefCount::EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002797 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002798 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002799 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002800 ExplodedNode<GRState>* Pred) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002801 RetainSummary* Summ = 0;
Ted Kremenek33661802008-05-01 21:31:50 +00002802
Ted Kremenek272aa852008-06-25 21:21:56 +00002803 if (Expr* Receiver = ME->getReceiver()) {
2804 // We need the type-information of the tracked receiver object
2805 // Retrieve it from the state.
2806 ObjCInterfaceDecl* ID = 0;
2807
2808 // FIXME: Wouldn't it be great if this code could be reduced? It's just
2809 // a chain of lookups.
Ted Kremeneka821b792009-04-29 05:04:30 +00002810 // FIXME: Is this really working as expected? There are cases where
2811 // we just use the 'ID' from the message expression.
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002812 const GRState* St = Builder.GetState(Pred);
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002813 SVal V = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
Ted Kremenek272aa852008-06-25 21:21:56 +00002814
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002815 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenek74556a12009-03-26 03:35:11 +00002816 if (Sym) {
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002817 if (const RefVal* T = St->get<RefBindings>(Sym)) {
Ted Kremenek6064a362008-07-07 16:21:19 +00002818 QualType Ty = T->getType();
Ted Kremenek272aa852008-06-25 21:21:56 +00002819
2820 if (const PointerType* PT = Ty->getAsPointerType()) {
2821 QualType PointeeTy = PT->getPointeeType();
2822
2823 if (ObjCInterfaceType* IT = dyn_cast<ObjCInterfaceType>(PointeeTy))
2824 ID = IT->getDecl();
2825 }
2826 }
2827 }
2828
Ted Kremenek04e00302009-04-29 17:09:14 +00002829 // FIXME: The receiver could be a reference to a class, meaning that
2830 // we should use the class method.
2831 Summ = Summaries.getInstanceMethodSummary(ME, ID);
Ted Kremenek0106e202008-10-24 20:32:50 +00002832
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002833 // Special-case: are we sending a mesage to "self"?
2834 // This is a hack. When we have full-IP this should be removed.
Ted Kremenek2f226732009-05-04 05:31:22 +00002835 if (isa<ObjCMethodDecl>(&Eng.getGraph().getCodeDecl())) {
2836 if (Expr* Receiver = ME->getReceiver()) {
2837 SVal X = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
2838 if (loc::MemRegionVal* L = dyn_cast<loc::MemRegionVal>(&X))
2839 if (L->getRegion() == Eng.getStateManager().getSelfRegion(St)) {
2840 // Update the summary to make the default argument effect
2841 // 'StopTracking'.
2842 Summ = Summaries.copySummary(Summ);
2843 Summ->setDefaultArgEffect(StopTracking);
2844 }
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002845 }
2846 }
Ted Kremenek272aa852008-06-25 21:21:56 +00002847 }
Ted Kremenek1feab292008-04-16 04:28:53 +00002848 else
Ted Kremenekb17fa952009-04-23 21:25:57 +00002849 Summ = Summaries.getClassMethodSummary(ME);
Ted Kremenek1feab292008-04-16 04:28:53 +00002850
Ted Kremenek286e9852009-05-04 04:57:00 +00002851 if (!Summ)
2852 Summ = Summaries.getDefaultSummary();
Ted Kremenekccbe79a2009-04-24 17:50:11 +00002853
Ted Kremenek286e9852009-05-04 04:57:00 +00002854 EvalSummary(Dst, Eng, Builder, ME, ME->getReceiver(), *Summ,
Ted Kremenek926abf22008-05-06 04:20:12 +00002855 ME->arg_begin(), ME->arg_end(), Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002856}
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002857
2858namespace {
2859class VISIBILITY_HIDDEN StopTrackingCallback : public SymbolVisitor {
2860 GRStateRef state;
2861public:
2862 StopTrackingCallback(GRStateRef st) : state(st) {}
2863 GRStateRef getState() { return state; }
2864
2865 bool VisitSymbol(SymbolRef sym) {
2866 state = state.remove<RefBindings>(sym);
2867 return true;
2868 }
Ted Kremenek926abf22008-05-06 04:20:12 +00002869
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002870 const GRState* getState() const { return state.getState(); }
2871};
2872} // end anonymous namespace
2873
2874
Ted Kremeneka42be302009-02-14 01:43:44 +00002875void CFRefCount::EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val) {
Ted Kremeneka42be302009-02-14 01:43:44 +00002876 // Are we storing to something that causes the value to "escape"?
Ted Kremenek7aef4842008-04-16 20:40:59 +00002877 bool escapes = false;
2878
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002879 // A value escapes in three possible cases (this may change):
2880 //
2881 // (1) we are binding to something that is not a memory region.
2882 // (2) we are binding to a memregion that does not have stack storage
2883 // (3) we are binding to a memregion with stack storage that the store
Ted Kremeneka42be302009-02-14 01:43:44 +00002884 // does not understand.
Ted Kremeneka42be302009-02-14 01:43:44 +00002885 GRStateRef state = B.getState();
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002886
Ted Kremeneka42be302009-02-14 01:43:44 +00002887 if (!isa<loc::MemRegionVal>(location))
Ted Kremenek7aef4842008-04-16 20:40:59 +00002888 escapes = true;
Ted Kremenekb15eba42008-10-04 05:50:14 +00002889 else {
Ted Kremeneka42be302009-02-14 01:43:44 +00002890 const MemRegion* R = cast<loc::MemRegionVal>(location).getRegion();
2891 escapes = !B.getStateManager().hasStackStorage(R);
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002892
2893 if (!escapes) {
2894 // To test (3), generate a new state with the binding removed. If it is
2895 // the same state, then it escapes (since the store cannot represent
2896 // the binding).
Ted Kremeneka42be302009-02-14 01:43:44 +00002897 escapes = (state == (state.BindLoc(cast<Loc>(location), UnknownVal())));
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002898 }
Ted Kremenekb15eba42008-10-04 05:50:14 +00002899 }
Ted Kremeneka42be302009-02-14 01:43:44 +00002900
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002901 // If our store can represent the binding and we aren't storing to something
2902 // that doesn't have local storage then just return and have the simulation
2903 // state continue as is.
2904 if (!escapes)
2905 return;
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002906
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002907 // Otherwise, find all symbols referenced by 'val' that we are tracking
2908 // and stop tracking them.
2909 B.MakeNode(state.scanReachableSymbols<StopTrackingCallback>(val).getState());
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002910}
2911
Ted Kremenek541db372008-04-24 23:57:27 +00002912
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002913 // Return statements.
2914
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002915void CFRefCount::EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002916 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002917 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002918 ReturnStmt* S,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002919 ExplodedNode<GRState>* Pred) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002920
2921 Expr* RetE = S->getRetValue();
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002922 if (!RetE)
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002923 return;
2924
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002925 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002926 SymbolRef Sym = state.GetSValAsScalarOrLoc(RetE).getAsLocSymbol();
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002927
Ted Kremenek74556a12009-03-26 03:35:11 +00002928 if (!Sym)
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002929 return;
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00002930
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002931 // Get the reference count binding (if any).
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002932 const RefVal* T = state.get<RefBindings>(Sym);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002933
2934 if (!T)
2935 return;
2936
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00002937 // Update the autorelease counts.
2938 static unsigned autoreleasetag = 0;
2939 GenericNodeBuilder Bd(Builder, S, &autoreleasetag);
Ted Kremenek412ca1e2009-05-09 00:10:05 +00002940 bool stop = false;
2941 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state , Bd, Pred, Eng, Sym,
2942 *T, stop);
2943
2944 if (stop)
2945 return;
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00002946
2947 // Get the updated binding.
2948 T = state.get<RefBindings>(Sym);
2949 assert(T);
2950
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002951 // Change the reference count.
Ted Kremenek6064a362008-07-07 16:21:19 +00002952 RefVal X = *T;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002953
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002954 switch (X.getKind()) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002955 case RefVal::Owned: {
2956 unsigned cnt = X.getCount();
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00002957 assert (cnt > 0);
2958 X = RefVal::makeReturnedOwned(cnt - 1);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002959 break;
2960 }
2961
2962 case RefVal::NotOwned: {
2963 unsigned cnt = X.getCount();
2964 X = cnt ? RefVal::makeReturnedOwned(cnt - 1)
2965 : RefVal::makeReturnedNotOwned();
2966 break;
2967 }
2968
2969 default:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002970 return;
2971 }
2972
2973 // Update the binding.
Ted Kremenek91781202008-08-17 03:20:02 +00002974 state = state.set<RefBindings>(Sym, X);
Ted Kremenek47a72422009-04-29 18:50:19 +00002975 Pred = Builder.MakeNode(Dst, S, Pred, state);
2976
Ted Kremeneka208d0c2009-04-30 05:51:50 +00002977 // Did we cache out?
2978 if (!Pred)
2979 return;
Ted Kremenek41a4bc62009-05-08 23:09:42 +00002980
Ted Kremenek47a72422009-04-29 18:50:19 +00002981 // Any leaks or other errors?
2982 if (X.isReturnedOwned() && X.getCount() == 0) {
2983 const Decl *CD = &Eng.getStateManager().getCodeDecl();
2984
Ted Kremenek314b1952009-04-29 23:03:22 +00002985 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002986 const RetainSummary &Summ = *Summaries.getMethodSummary(MD);
2987 if (!Summ.getRetEffect().isOwned()) {
Ted Kremenek47a72422009-04-29 18:50:19 +00002988 static int ReturnOwnLeakTag = 0;
2989 state = state.set<RefBindings>(Sym, X ^ RefVal::ErrorLeakReturned);
Ted Kremenek47a72422009-04-29 18:50:19 +00002990 // Generate an error node.
Ted Kremeneka208d0c2009-04-30 05:51:50 +00002991 if (ExplodedNode<GRState> *N =
2992 Builder.generateNode(PostStmt(S, &ReturnOwnLeakTag), state, Pred)) {
2993 CFRefLeakReport *report =
2994 new CFRefLeakReport(*static_cast<CFRefBug*>(leakAtReturn), *this,
2995 N, Sym, Eng);
2996 BR->EmitReport(report);
2997 }
Ted Kremenek47a72422009-04-29 18:50:19 +00002998 }
2999 }
3000 }
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003001
3002
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003003}
3004
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003005// Assumptions.
3006
Ted Kremenekabd89ac2008-08-13 04:27:00 +00003007const GRState* CFRefCount::EvalAssume(GRStateManager& VMgr,
3008 const GRState* St,
Zhongxing Xu097fc982008-10-17 05:57:07 +00003009 SVal Cond, bool Assumption,
Ted Kremenekf22f8682008-07-10 22:03:41 +00003010 bool& isFeasible) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003011
3012 // FIXME: We may add to the interface of EvalAssume the list of symbols
3013 // whose assumptions have changed. For now we just iterate through the
3014 // bindings and check if any of the tracked symbols are NULL. This isn't
3015 // too bad since the number of symbols we will track in practice are
3016 // probably small and EvalAssume is only called at branches and a few
3017 // other places.
Ted Kremenek4ae925c2008-08-14 21:16:54 +00003018 RefBindings B = St->get<RefBindings>();
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003019
3020 if (B.isEmpty())
3021 return St;
3022
3023 bool changed = false;
Ted Kremenek91781202008-08-17 03:20:02 +00003024
3025 GRStateRef state(St, VMgr);
3026 RefBindings::Factory& RefBFactory = state.get_context<RefBindings>();
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003027
3028 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003029 // Check if the symbol is null (or equal to any constant).
3030 // If this is the case, stop tracking the symbol.
Zhongxing Xuc6b27d02008-08-29 14:52:36 +00003031 if (VMgr.getSymVal(St, I.getKey())) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003032 changed = true;
3033 B = RefBFactory.Remove(B, I.getKey());
3034 }
3035 }
3036
Ted Kremenek91781202008-08-17 03:20:02 +00003037 if (changed)
3038 state = state.set<RefBindings>(B);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003039
Ted Kremenek4ae925c2008-08-14 21:16:54 +00003040 return state;
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003041}
Ted Kremeneka7338b42008-03-11 06:39:11 +00003042
Ted Kremenekb6578942009-02-24 19:15:11 +00003043GRStateRef CFRefCount::Update(GRStateRef state, SymbolRef sym,
3044 RefVal V, ArgEffect E,
3045 RefVal::Kind& hasErr) {
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003046
3047 // In GC mode [... release] and [... retain] do nothing.
3048 switch (E) {
3049 default: break;
3050 case IncRefMsg: E = isGCEnabled() ? DoNothing : IncRef; break;
3051 case DecRefMsg: E = isGCEnabled() ? DoNothing : DecRef; break;
Ted Kremenek2126bef2009-02-18 21:57:45 +00003052 case MakeCollectable: E = isGCEnabled() ? DecRef : DoNothing; break;
Ted Kremenekaac82832009-02-23 17:45:03 +00003053 case NewAutoreleasePool: E = isGCEnabled() ? DoNothing :
3054 NewAutoreleasePool; break;
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003055 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00003056
Ted Kremenek6537a642009-03-17 19:42:23 +00003057 // Handle all use-after-releases.
3058 if (!isGCEnabled() && V.getKind() == RefVal::Released) {
3059 V = V ^ RefVal::ErrorUseAfterRelease;
3060 hasErr = V.getKind();
3061 return state.set<RefBindings>(sym, V);
3062 }
3063
Ted Kremenek0d721572008-03-11 17:48:22 +00003064 switch (E) {
3065 default:
3066 assert (false && "Unhandled CFRef transition.");
Ted Kremenek6537a642009-03-17 19:42:23 +00003067
3068 case Dealloc:
3069 // Any use of -dealloc in GC is *bad*.
3070 if (isGCEnabled()) {
3071 V = V ^ RefVal::ErrorDeallocGC;
3072 hasErr = V.getKind();
3073 break;
3074 }
3075
3076 switch (V.getKind()) {
3077 default:
3078 assert(false && "Invalid case.");
3079 case RefVal::Owned:
3080 // The object immediately transitions to the released state.
3081 V = V ^ RefVal::Released;
3082 V.clearCounts();
3083 return state.set<RefBindings>(sym, V);
3084 case RefVal::NotOwned:
3085 V = V ^ RefVal::ErrorDeallocNotOwned;
3086 hasErr = V.getKind();
3087 break;
3088 }
3089 break;
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003090
Ted Kremenekb7826ab2009-02-25 23:11:49 +00003091 case NewAutoreleasePool:
3092 assert(!isGCEnabled());
3093 return state.add<AutoreleaseStack>(sym);
3094
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003095 case MayEscape:
3096 if (V.getKind() == RefVal::Owned) {
Ted Kremenek272aa852008-06-25 21:21:56 +00003097 V = V ^ RefVal::NotOwned;
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003098 break;
3099 }
Ted Kremenek6537a642009-03-17 19:42:23 +00003100
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003101 // Fall-through.
Ted Kremenek1b4b6562009-02-25 02:54:57 +00003102
Ted Kremenekede40b72008-07-09 18:11:16 +00003103 case DoNothingByRef:
Ted Kremenek0d721572008-03-11 17:48:22 +00003104 case DoNothing:
Ted Kremenekb6578942009-02-24 19:15:11 +00003105 return state;
Ted Kremeneke5a4bb02008-06-30 16:57:41 +00003106
Ted Kremenek9b112d22009-01-28 21:44:40 +00003107 case Autorelease:
Ted Kremenek6537a642009-03-17 19:42:23 +00003108 if (isGCEnabled())
3109 return state;
Ted Kremenek681fb352009-03-20 17:34:15 +00003110
3111 // Update the autorelease counts.
3112 state = SendAutorelease(state, ARCountFactory, sym);
Ted Kremenek4d99d342009-05-08 20:01:42 +00003113 V = V.autorelease();
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003114
Ted Kremenek227c5372008-05-06 02:41:27 +00003115 case StopTracking:
Ted Kremenekb6578942009-02-24 19:15:11 +00003116 return state.remove<RefBindings>(sym);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003117
Ted Kremenek0d721572008-03-11 17:48:22 +00003118 case IncRef:
3119 switch (V.getKind()) {
3120 default:
3121 assert(false);
3122
3123 case RefVal::Owned:
Ted Kremenek0d721572008-03-11 17:48:22 +00003124 case RefVal::NotOwned:
Ted Kremenek272aa852008-06-25 21:21:56 +00003125 V = V + 1;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003126 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003127 case RefVal::Released:
Ted Kremenek6537a642009-03-17 19:42:23 +00003128 // Non-GC cases are handled above.
3129 assert(isGCEnabled());
3130 V = (V ^ RefVal::Owned) + 1;
Ted Kremenek0d721572008-03-11 17:48:22 +00003131 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003132 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00003133 break;
3134
Ted Kremenek272aa852008-06-25 21:21:56 +00003135 case SelfOwn:
3136 V = V ^ RefVal::NotOwned;
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003137 // Fall-through.
Ted Kremenek0d721572008-03-11 17:48:22 +00003138 case DecRef:
3139 switch (V.getKind()) {
3140 default:
Ted Kremenek6537a642009-03-17 19:42:23 +00003141 // case 'RefVal::Released' handled above.
Ted Kremenek0d721572008-03-11 17:48:22 +00003142 assert (false);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003143
Ted Kremenek272aa852008-06-25 21:21:56 +00003144 case RefVal::Owned:
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00003145 assert(V.getCount() > 0);
3146 if (V.getCount() == 1) V = V ^ RefVal::Released;
3147 V = V - 1;
Ted Kremenek0d721572008-03-11 17:48:22 +00003148 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003149
Ted Kremenek272aa852008-06-25 21:21:56 +00003150 case RefVal::NotOwned:
3151 if (V.getCount() > 0)
3152 V = V - 1;
Ted Kremenekc4f81022008-04-10 23:09:18 +00003153 else {
Ted Kremenek272aa852008-06-25 21:21:56 +00003154 V = V ^ RefVal::ErrorReleaseNotOwned;
Ted Kremenek1feab292008-04-16 04:28:53 +00003155 hasErr = V.getKind();
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003156 }
Ted Kremenek0d721572008-03-11 17:48:22 +00003157 break;
Ted Kremenek6537a642009-03-17 19:42:23 +00003158
Ted Kremenek0d721572008-03-11 17:48:22 +00003159 case RefVal::Released:
Ted Kremenek6537a642009-03-17 19:42:23 +00003160 // Non-GC cases are handled above.
3161 assert(isGCEnabled());
Ted Kremenek272aa852008-06-25 21:21:56 +00003162 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek1feab292008-04-16 04:28:53 +00003163 hasErr = V.getKind();
Ted Kremenek6537a642009-03-17 19:42:23 +00003164 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003165 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00003166 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003167 }
Ted Kremenekb6578942009-02-24 19:15:11 +00003168 return state.set<RefBindings>(sym, V);
Ted Kremeneka7338b42008-03-11 06:39:11 +00003169}
3170
Ted Kremenek10fe66d2008-04-09 01:10:13 +00003171//===----------------------------------------------------------------------===//
Ted Kremenek708af042009-02-05 06:50:21 +00003172// Handle dead symbols and end-of-path.
3173//===----------------------------------------------------------------------===//
3174
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003175std::pair<ExplodedNode<GRState>*, GRStateRef>
3176CFRefCount::HandleAutoreleaseCounts(GRStateRef state, GenericNodeBuilder Bd,
3177 ExplodedNode<GRState>* Pred,
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003178 GRExprEngine &Eng,
3179 SymbolRef Sym, RefVal V, bool &stop) {
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003180
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003181 unsigned ACnt = V.getAutoreleaseCount();
3182 stop = false;
3183
3184 // No autorelease counts? Nothing to be done.
3185 if (!ACnt)
3186 return std::make_pair(Pred, state);
3187
3188 assert(!isGCEnabled() && "Autorelease counts in GC mode?");
3189 unsigned Cnt = V.getCount();
3190
3191 if (ACnt <= Cnt) {
Ted Kremenek3f15aba2009-05-09 00:44:07 +00003192 if (ACnt == Cnt) {
3193 V.clearCounts();
3194 V = V ^ RefVal::NotOwned;
3195 }
3196 else {
3197 V.setCount(Cnt - ACnt);
3198 V.setAutoreleaseCount(0);
3199 }
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003200 state = state.set<RefBindings>(Sym, V);
3201 ExplodedNode<GRState> *N = Bd.MakeNode(state, Pred);
3202 stop = (N == 0);
3203 return std::make_pair(N, state);
3204 }
3205
3206 // Woah! More autorelease counts then retain counts left.
3207 // Emit hard error.
3208 stop = true;
3209 V = V ^ RefVal::ErrorOverAutorelease;
3210 state = state.set<RefBindings>(Sym, V);
3211
3212 if (ExplodedNode<GRState> *N = Bd.MakeNode(state, Pred)) {
Ted Kremenek3f15aba2009-05-09 00:44:07 +00003213 N->markAsSink();
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003214 CFRefReport *report =
3215 new CFRefReport(*static_cast<CFRefBug*>(overAutorelease),
3216 *this, N, Sym);
3217 BR->EmitReport(report);
3218 }
3219
3220 return std::make_pair((ExplodedNode<GRState>*)0, state);
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003221}
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003222
3223GRStateRef
3224CFRefCount::HandleSymbolDeath(GRStateRef state, SymbolRef sid, RefVal V,
3225 llvm::SmallVectorImpl<SymbolRef> &Leaked) {
3226
3227 bool hasLeak = V.isOwned() ||
3228 ((V.isNotOwned() || V.isReturnedOwned()) && V.getCount() > 0);
3229
3230 if (!hasLeak)
3231 return state.remove<RefBindings>(sid);
3232
3233 Leaked.push_back(sid);
3234 return state.set<RefBindings>(sid, V ^ RefVal::ErrorLeak);
3235}
3236
3237ExplodedNode<GRState>*
3238CFRefCount::ProcessLeaks(GRStateRef state,
3239 llvm::SmallVectorImpl<SymbolRef> &Leaked,
3240 GenericNodeBuilder &Builder,
3241 GRExprEngine& Eng,
3242 ExplodedNode<GRState> *Pred) {
3243
3244 if (Leaked.empty())
3245 return Pred;
3246
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003247 // Generate an intermediate node representing the leak point.
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003248 ExplodedNode<GRState> *N = Builder.MakeNode(state, Pred);
3249
3250 if (N) {
3251 for (llvm::SmallVectorImpl<SymbolRef>::iterator
3252 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3253
3254 CFRefBug *BT = static_cast<CFRefBug*>(Pred ? leakWithinFunction
3255 : leakAtReturn);
3256 assert(BT && "BugType not initialized.");
3257 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N, *I, Eng);
3258 BR->EmitReport(report);
3259 }
3260 }
3261
3262 return N;
3263}
3264
Ted Kremenek708af042009-02-05 06:50:21 +00003265void CFRefCount::EvalEndPath(GRExprEngine& Eng,
3266 GREndPathNodeBuilder<GRState>& Builder) {
3267
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003268 GRStateRef state(Builder.getState(), Eng.getStateManager());
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003269 GenericNodeBuilder Bd(Builder);
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003270 RefBindings B = state.get<RefBindings>();
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003271 ExplodedNode<GRState> *Pred = 0;
3272
3273 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003274 bool stop = false;
3275 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state, Bd, Pred, Eng,
3276 (*I).first,
3277 (*I).second, stop);
3278
3279 if (stop)
3280 return;
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003281 }
3282
3283 B = state.get<RefBindings>();
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003284 llvm::SmallVector<SymbolRef, 10> Leaked;
Ted Kremenek708af042009-02-05 06:50:21 +00003285
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003286 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I)
3287 state = HandleSymbolDeath(state, (*I).first, (*I).second, Leaked);
3288
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003289 ProcessLeaks(state, Leaked, Bd, Eng, Pred);
Ted Kremenek708af042009-02-05 06:50:21 +00003290}
3291
3292void CFRefCount::EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
3293 GRExprEngine& Eng,
3294 GRStmtNodeBuilder<GRState>& Builder,
3295 ExplodedNode<GRState>* Pred,
3296 Stmt* S,
3297 const GRState* St,
3298 SymbolReaper& SymReaper) {
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003299
3300 GRStateRef state(St, Eng.getStateManager());
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003301 RefBindings B = state.get<RefBindings>();
3302
3303 // Update counts from autorelease pools
3304 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3305 E = SymReaper.dead_end(); I != E; ++I) {
3306 SymbolRef Sym = *I;
3307 if (const RefVal* T = B.lookup(Sym)){
3308 // Use the symbol as the tag.
3309 // FIXME: This might not be as unique as we would like.
3310 GenericNodeBuilder Bd(Builder, S, Sym);
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003311 bool stop = false;
3312 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state, Bd, Pred, Eng,
3313 Sym, *T, stop);
3314 if (stop)
3315 return;
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003316 }
3317 }
3318
3319 B = state.get<RefBindings>();
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003320 llvm::SmallVector<SymbolRef, 10> Leaked;
Ted Kremenek708af042009-02-05 06:50:21 +00003321
3322 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003323 E = SymReaper.dead_end(); I != E; ++I) {
3324 if (const RefVal* T = B.lookup(*I))
3325 state = HandleSymbolDeath(state, *I, *T, Leaked);
3326 }
Ted Kremenek708af042009-02-05 06:50:21 +00003327
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003328 static unsigned LeakPPTag = 0;
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003329 {
3330 GenericNodeBuilder Bd(Builder, S, &LeakPPTag);
3331 Pred = ProcessLeaks(state, Leaked, Bd, Eng, Pred);
3332 }
Ted Kremenek708af042009-02-05 06:50:21 +00003333
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003334 // Did we cache out?
3335 if (!Pred)
3336 return;
Ted Kremenek876d8df2009-02-19 23:47:02 +00003337
3338 // Now generate a new node that nukes the old bindings.
Ted Kremenek876d8df2009-02-19 23:47:02 +00003339 RefBindings::Factory& F = state.get_context<RefBindings>();
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003340
Ted Kremenek876d8df2009-02-19 23:47:02 +00003341 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003342 E = SymReaper.dead_end(); I!=E; ++I) B = F.Remove(B, *I);
3343
Ted Kremenek876d8df2009-02-19 23:47:02 +00003344 state = state.set<RefBindings>(B);
3345 Builder.MakeNode(Dst, S, Pred, state);
Ted Kremenek708af042009-02-05 06:50:21 +00003346}
3347
3348void CFRefCount::ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
3349 GRStmtNodeBuilder<GRState>& Builder,
3350 Expr* NodeExpr, Expr* ErrorExpr,
3351 ExplodedNode<GRState>* Pred,
3352 const GRState* St,
3353 RefVal::Kind hasErr, SymbolRef Sym) {
3354 Builder.BuildSinks = true;
3355 GRExprEngine::NodeTy* N = Builder.MakeNode(Dst, NodeExpr, Pred, St);
3356
3357 if (!N) return;
3358
3359 CFRefBug *BT = 0;
3360
Ted Kremenek6537a642009-03-17 19:42:23 +00003361 switch (hasErr) {
3362 default:
3363 assert(false && "Unhandled error.");
3364 return;
3365 case RefVal::ErrorUseAfterRelease:
3366 BT = static_cast<CFRefBug*>(useAfterRelease);
3367 break;
3368 case RefVal::ErrorReleaseNotOwned:
3369 BT = static_cast<CFRefBug*>(releaseNotOwned);
3370 break;
3371 case RefVal::ErrorDeallocGC:
3372 BT = static_cast<CFRefBug*>(deallocGC);
3373 break;
3374 case RefVal::ErrorDeallocNotOwned:
3375 BT = static_cast<CFRefBug*>(deallocNotOwned);
3376 break;
Ted Kremenek708af042009-02-05 06:50:21 +00003377 }
3378
Ted Kremenekc26c4692009-02-18 03:48:14 +00003379 CFRefReport *report = new CFRefReport(*BT, *this, N, Sym);
Ted Kremenek708af042009-02-05 06:50:21 +00003380 report->addRange(ErrorExpr->getSourceRange());
3381 BR->EmitReport(report);
3382}
3383
3384//===----------------------------------------------------------------------===//
Ted Kremenekb1983ba2008-04-10 22:16:52 +00003385// Transfer function creation for external clients.
Ted Kremeneka7338b42008-03-11 06:39:11 +00003386//===----------------------------------------------------------------------===//
3387
Ted Kremenekfe30beb2008-04-30 23:47:44 +00003388GRTransferFuncs* clang::MakeCFRefCountTF(ASTContext& Ctx, bool GCEnabled,
3389 const LangOptions& lopts) {
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00003390 return new CFRefCount(Ctx, GCEnabled, lopts);
Ted Kremeneka4c74292008-04-10 22:58:08 +00003391}