blob: e45b3b37f8a916e042947dc6a64de908597eaf10 [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);
182 return ENB->MakeNode(state, Pred);
183 }
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;
1555 }
Ted Kremenek4d99d342009-05-08 20:01:42 +00001556
1557 if (ACnt) {
1558 Out << " [ARC +" << ACnt << ']';
1559 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001560}
Ted Kremenek0d721572008-03-11 17:48:22 +00001561
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001562} // end anonymous namespace
1563
1564//===----------------------------------------------------------------------===//
1565// RefBindings - State used to track object reference counts.
1566//===----------------------------------------------------------------------===//
1567
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001568typedef llvm::ImmutableMap<SymbolRef, RefVal> RefBindings;
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001569static int RefBIndex = 0;
1570
1571namespace clang {
Ted Kremenek91781202008-08-17 03:20:02 +00001572 template<>
1573 struct GRStateTrait<RefBindings> : public GRStatePartialTrait<RefBindings> {
1574 static inline void* GDMIndex() { return &RefBIndex; }
1575 };
1576}
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001577
1578//===----------------------------------------------------------------------===//
Ted Kremenekb6578942009-02-24 19:15:11 +00001579// AutoreleaseBindings - State used to track objects in autorelease pools.
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001580//===----------------------------------------------------------------------===//
1581
Ted Kremenekb6578942009-02-24 19:15:11 +00001582typedef llvm::ImmutableMap<SymbolRef, unsigned> ARCounts;
1583typedef llvm::ImmutableMap<SymbolRef, ARCounts> ARPoolContents;
1584typedef llvm::ImmutableList<SymbolRef> ARStack;
Ted Kremenekaac82832009-02-23 17:45:03 +00001585
Ted Kremenekb6578942009-02-24 19:15:11 +00001586static int AutoRCIndex = 0;
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001587static int AutoRBIndex = 0;
1588
Ted Kremenekb6578942009-02-24 19:15:11 +00001589namespace { class VISIBILITY_HIDDEN AutoreleasePoolContents {}; }
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001590namespace { class VISIBILITY_HIDDEN AutoreleaseStack {}; }
Ted Kremenekb6578942009-02-24 19:15:11 +00001591
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001592namespace clang {
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001593template<> struct GRStateTrait<AutoreleaseStack>
Ted Kremenekb6578942009-02-24 19:15:11 +00001594 : public GRStatePartialTrait<ARStack> {
1595 static inline void* GDMIndex() { return &AutoRBIndex; }
1596};
1597
1598template<> struct GRStateTrait<AutoreleasePoolContents>
1599 : public GRStatePartialTrait<ARPoolContents> {
1600 static inline void* GDMIndex() { return &AutoRCIndex; }
1601};
1602} // end clang namespace
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001603
Ted Kremenek681fb352009-03-20 17:34:15 +00001604static SymbolRef GetCurrentAutoreleasePool(const GRState* state) {
1605 ARStack stack = state->get<AutoreleaseStack>();
1606 return stack.isEmpty() ? SymbolRef() : stack.getHead();
1607}
1608
1609static GRStateRef SendAutorelease(GRStateRef state, ARCounts::Factory &F,
1610 SymbolRef sym) {
1611
1612 SymbolRef pool = GetCurrentAutoreleasePool(state);
1613 const ARCounts *cnts = state.get<AutoreleasePoolContents>(pool);
1614 ARCounts newCnts(0);
1615
1616 if (cnts) {
1617 const unsigned *cnt = (*cnts).lookup(sym);
1618 newCnts = F.Add(*cnts, sym, cnt ? *cnt + 1 : 1);
1619 }
1620 else
1621 newCnts = F.Add(F.GetEmptyMap(), sym, 1);
1622
1623 return state.set<AutoreleasePoolContents>(pool, newCnts);
1624}
1625
Ted Kremenek7aef4842008-04-16 20:40:59 +00001626//===----------------------------------------------------------------------===//
1627// Transfer functions.
1628//===----------------------------------------------------------------------===//
1629
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001630namespace {
1631
Ted Kremenek7d421f32008-04-09 23:49:11 +00001632class VISIBILITY_HIDDEN CFRefCount : public GRSimpleVals {
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001633public:
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001634 class BindingsPrinter : public GRState::Printer {
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001635 public:
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001636 virtual void Print(std::ostream& Out, const GRState* state,
1637 const char* nl, const char* sep);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001638 };
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001639
1640private:
Ted Kremenekc26c4692009-02-18 03:48:14 +00001641 typedef llvm::DenseMap<const GRExprEngine::NodeTy*, const RetainSummary*>
1642 SummaryLogTy;
1643
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001644 RetainSummaryManager Summaries;
Ted Kremenekc26c4692009-02-18 03:48:14 +00001645 SummaryLogTy SummaryLog;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001646 const LangOptions& LOpts;
Ted Kremenekb6578942009-02-24 19:15:11 +00001647 ARCounts::Factory ARCountFactory;
Ted Kremenek91781202008-08-17 03:20:02 +00001648
Ted Kremenek708af042009-02-05 06:50:21 +00001649 BugType *useAfterRelease, *releaseNotOwned;
Ted Kremenek6537a642009-03-17 19:42:23 +00001650 BugType *deallocGC, *deallocNotOwned;
Ted Kremenek708af042009-02-05 06:50:21 +00001651 BugType *leakWithinFunction, *leakAtReturn;
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001652 BugType *overAutorelease;
Ted Kremenek708af042009-02-05 06:50:21 +00001653 BugReporter *BR;
Ted Kremeneka7338b42008-03-11 06:39:11 +00001654
Ted Kremenekb6578942009-02-24 19:15:11 +00001655 GRStateRef Update(GRStateRef state, SymbolRef sym, RefVal V, ArgEffect E,
1656 RefVal::Kind& hasErr);
1657
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001658 void ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
1659 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001660 Expr* NodeExpr, Expr* ErrorExpr,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001661 ExplodedNode<GRState>* Pred,
1662 const GRState* St,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001663 RefVal::Kind hasErr, SymbolRef Sym);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001664
Ted Kremenek41a4bc62009-05-08 23:09:42 +00001665 GRStateRef HandleSymbolDeath(GRStateRef state, SymbolRef sid, RefVal V,
1666 llvm::SmallVectorImpl<SymbolRef> &Leaked);
1667
1668 ExplodedNode<GRState>* ProcessLeaks(GRStateRef state,
1669 llvm::SmallVectorImpl<SymbolRef> &Leaked,
1670 GenericNodeBuilder &Builder,
1671 GRExprEngine &Eng,
1672 ExplodedNode<GRState> *Pred = 0);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001673
Ted Kremenekb6578942009-02-24 19:15:11 +00001674public:
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00001675 CFRefCount(ASTContext& Ctx, bool gcenabled, const LangOptions& lopts)
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001676 : Summaries(Ctx, gcenabled),
Ted Kremenek6537a642009-03-17 19:42:23 +00001677 LOpts(lopts), useAfterRelease(0), releaseNotOwned(0),
1678 deallocGC(0), deallocNotOwned(0),
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001679 leakWithinFunction(0), leakAtReturn(0), overAutorelease(0), BR(0) {}
Ted Kremenek1feab292008-04-16 04:28:53 +00001680
Ted Kremenek708af042009-02-05 06:50:21 +00001681 virtual ~CFRefCount() {}
Ted Kremenek7d421f32008-04-09 23:49:11 +00001682
Ted Kremenekbf6babf2009-02-04 23:49:09 +00001683 void RegisterChecks(BugReporter &BR);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001684
Ted Kremenekb0f2b9e2008-08-16 00:49:49 +00001685 virtual void RegisterPrinters(std::vector<GRState::Printer*>& Printers) {
1686 Printers.push_back(new BindingsPrinter());
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001687 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00001688
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001689 bool isGCEnabled() const { return Summaries.isGCEnabled(); }
Ted Kremenekfe30beb2008-04-30 23:47:44 +00001690 const LangOptions& getLangOptions() const { return LOpts; }
1691
Ted Kremenekc26c4692009-02-18 03:48:14 +00001692 const RetainSummary *getSummaryOfNode(const ExplodedNode<GRState> *N) const {
1693 SummaryLogTy::const_iterator I = SummaryLog.find(N);
1694 return I == SummaryLog.end() ? 0 : I->second;
1695 }
1696
Ted Kremeneka7338b42008-03-11 06:39:11 +00001697 // Calls.
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001698
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001699 void EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001700 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001701 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001702 Expr* Ex,
1703 Expr* Receiver,
Ted Kremenek286e9852009-05-04 04:57:00 +00001704 const RetainSummary& Summ,
Ted Kremenek2719e982008-06-17 02:43:46 +00001705 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001706 ExplodedNode<GRState>* Pred);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001707
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001708 virtual void EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekce0767f2008-03-12 21:06:49 +00001709 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001710 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001711 CallExpr* CE, SVal L,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001712 ExplodedNode<GRState>* Pred);
Ted Kremenek10fe66d2008-04-09 01:10:13 +00001713
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001714
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001715 virtual void EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001716 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001717 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001718 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001719 ExplodedNode<GRState>* Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001720
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001721 bool EvalObjCMessageExprAux(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001722 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001723 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001724 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001725 ExplodedNode<GRState>* Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001726
Ted Kremeneka42be302009-02-14 01:43:44 +00001727 // Stores.
1728 virtual void EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val);
1729
Ted Kremenekffefc352008-04-11 22:25:11 +00001730 // End-of-path.
1731
1732 virtual void EvalEndPath(GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001733 GREndPathNodeBuilder<GRState>& Builder);
Ted Kremenekffefc352008-04-11 22:25:11 +00001734
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001735 virtual void EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek541db372008-04-24 23:57:27 +00001736 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001737 GRStmtNodeBuilder<GRState>& Builder,
1738 ExplodedNode<GRState>* Pred,
Ted Kremenek5c0729b2009-01-21 22:26:05 +00001739 Stmt* S, const GRState* state,
1740 SymbolReaper& SymReaper);
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00001741
1742 std::pair<ExplodedNode<GRState>*, GRStateRef>
1743 HandleAutoreleaseCounts(GRStateRef state, GenericNodeBuilder Bd,
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001744 ExplodedNode<GRState>* Pred, GRExprEngine &Eng,
1745 SymbolRef Sym, RefVal V, bool &stop);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001746 // Return statements.
1747
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001748 virtual void EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001749 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001750 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001751 ReturnStmt* S,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001752 ExplodedNode<GRState>* Pred);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001753
1754 // Assumptions.
1755
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001756 virtual const GRState* EvalAssume(GRStateManager& VMgr,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001757 const GRState* St, SVal Cond,
Ted Kremenekf22f8682008-07-10 22:03:41 +00001758 bool Assumption, bool& isFeasible);
Ted Kremeneka7338b42008-03-11 06:39:11 +00001759};
1760
1761} // end anonymous namespace
1762
Ted Kremenek681fb352009-03-20 17:34:15 +00001763static void PrintPool(std::ostream &Out, SymbolRef Sym, const GRState *state) {
1764 Out << ' ';
Ted Kremenek74556a12009-03-26 03:35:11 +00001765 if (Sym)
1766 Out << Sym->getSymbolID();
Ted Kremenek681fb352009-03-20 17:34:15 +00001767 else
1768 Out << "<pool>";
1769 Out << ":{";
1770
1771 // Get the contents of the pool.
1772 if (const ARCounts *cnts = state->get<AutoreleasePoolContents>(Sym))
1773 for (ARCounts::iterator J=cnts->begin(), EJ=cnts->end(); J != EJ; ++J)
1774 Out << '(' << J.getKey() << ',' << J.getData() << ')';
1775
1776 Out << '}';
1777}
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001778
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001779void CFRefCount::BindingsPrinter::Print(std::ostream& Out, const GRState* state,
1780 const char* nl, const char* sep) {
Ted Kremenek681fb352009-03-20 17:34:15 +00001781
1782
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001783
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001784 RefBindings B = state->get<RefBindings>();
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001785
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001786 if (!B.isEmpty())
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001787 Out << sep << nl;
1788
1789 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
1790 Out << (*I).first << " : ";
1791 (*I).second.print(Out);
1792 Out << nl;
1793 }
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001794
1795 // Print the autorelease stack.
Ted Kremenek681fb352009-03-20 17:34:15 +00001796 Out << sep << nl << "AR pool stack:";
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001797 ARStack stack = state->get<AutoreleaseStack>();
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001798
Ted Kremenek681fb352009-03-20 17:34:15 +00001799 PrintPool(Out, SymbolRef(), state); // Print the caller's pool.
1800 for (ARStack::iterator I=stack.begin(), E=stack.end(); I!=E; ++I)
1801 PrintPool(Out, *I, state);
1802
1803 Out << nl;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001804}
1805
Ted Kremenek47a72422009-04-29 18:50:19 +00001806//===----------------------------------------------------------------------===//
1807// Error reporting.
1808//===----------------------------------------------------------------------===//
1809
1810namespace {
1811
1812 //===-------------===//
1813 // Bug Descriptions. //
1814 //===-------------===//
1815
1816 class VISIBILITY_HIDDEN CFRefBug : public BugType {
1817 protected:
1818 CFRefCount& TF;
1819
1820 CFRefBug(CFRefCount* tf, const char* name)
1821 : BugType(name, "Memory (Core Foundation/Objective-C)"), TF(*tf) {}
1822 public:
1823
1824 CFRefCount& getTF() { return TF; }
1825 const CFRefCount& getTF() const { return TF; }
1826
1827 // FIXME: Eventually remove.
1828 virtual const char* getDescription() const = 0;
1829
1830 virtual bool isLeak() const { return false; }
1831 };
1832
1833 class VISIBILITY_HIDDEN UseAfterRelease : public CFRefBug {
1834 public:
1835 UseAfterRelease(CFRefCount* tf)
1836 : CFRefBug(tf, "Use-after-release") {}
1837
1838 const char* getDescription() const {
1839 return "Reference-counted object is used after it is released";
1840 }
1841 };
1842
1843 class VISIBILITY_HIDDEN BadRelease : public CFRefBug {
1844 public:
1845 BadRelease(CFRefCount* tf) : CFRefBug(tf, "Bad release") {}
1846
1847 const char* getDescription() const {
1848 return "Incorrect decrement of the reference count of an "
1849 "object is not owned at this point by the caller";
1850 }
1851 };
1852
1853 class VISIBILITY_HIDDEN DeallocGC : public CFRefBug {
1854 public:
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001855 DeallocGC(CFRefCount *tf)
1856 : CFRefBug(tf, "-dealloc called while using garbage collection") {}
Ted Kremenek47a72422009-04-29 18:50:19 +00001857
1858 const char *getDescription() const {
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001859 return "-dealloc called while using garbage collection";
Ted Kremenek47a72422009-04-29 18:50:19 +00001860 }
1861 };
1862
1863 class VISIBILITY_HIDDEN DeallocNotOwned : public CFRefBug {
1864 public:
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001865 DeallocNotOwned(CFRefCount *tf)
1866 : CFRefBug(tf, "-dealloc sent to non-exclusively owned object") {}
Ted Kremenek47a72422009-04-29 18:50:19 +00001867
1868 const char *getDescription() const {
1869 return "-dealloc sent to object that may be referenced elsewhere";
1870 }
1871 };
1872
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001873 class VISIBILITY_HIDDEN OverAutorelease : public CFRefBug {
1874 public:
1875 OverAutorelease(CFRefCount *tf) :
1876 CFRefBug(tf, "Object sent -autorelease too many times") {}
1877
1878 const char *getDescription() const {
1879 return "Object will be sent more -release messages from its containing "
1880 "autorelease pools than it has retain counts";
1881 }
1882 };
1883
Ted Kremenek47a72422009-04-29 18:50:19 +00001884 class VISIBILITY_HIDDEN Leak : public CFRefBug {
1885 const bool isReturn;
1886 protected:
1887 Leak(CFRefCount* tf, const char* name, bool isRet)
1888 : CFRefBug(tf, name), isReturn(isRet) {}
1889 public:
1890
1891 const char* getDescription() const { return ""; }
1892
1893 bool isLeak() const { return true; }
1894 };
1895
1896 class VISIBILITY_HIDDEN LeakAtReturn : public Leak {
1897 public:
1898 LeakAtReturn(CFRefCount* tf, const char* name)
1899 : Leak(tf, name, true) {}
1900 };
1901
1902 class VISIBILITY_HIDDEN LeakWithinFunction : public Leak {
1903 public:
1904 LeakWithinFunction(CFRefCount* tf, const char* name)
1905 : Leak(tf, name, false) {}
1906 };
1907
1908 //===---------===//
1909 // Bug Reports. //
1910 //===---------===//
1911
1912 class VISIBILITY_HIDDEN CFRefReport : public RangedBugReport {
1913 protected:
1914 SymbolRef Sym;
1915 const CFRefCount &TF;
1916 public:
1917 CFRefReport(CFRefBug& D, const CFRefCount &tf,
1918 ExplodedNode<GRState> *n, SymbolRef sym)
1919 : RangedBugReport(D, D.getDescription(), n), Sym(sym), TF(tf) {}
1920
1921 virtual ~CFRefReport() {}
1922
1923 CFRefBug& getBugType() {
1924 return (CFRefBug&) RangedBugReport::getBugType();
1925 }
1926 const CFRefBug& getBugType() const {
1927 return (const CFRefBug&) RangedBugReport::getBugType();
1928 }
1929
1930 virtual void getRanges(BugReporter& BR, const SourceRange*& beg,
1931 const SourceRange*& end) {
1932
1933 if (!getBugType().isLeak())
1934 RangedBugReport::getRanges(BR, beg, end);
1935 else
1936 beg = end = 0;
1937 }
1938
1939 SymbolRef getSymbol() const { return Sym; }
1940
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00001941 PathDiagnosticPiece* getEndPath(BugReporterContext& BRC,
Ted Kremenek47a72422009-04-29 18:50:19 +00001942 const ExplodedNode<GRState>* N);
1943
1944 std::pair<const char**,const char**> getExtraDescriptiveText();
1945
1946 PathDiagnosticPiece* VisitNode(const ExplodedNode<GRState>* N,
1947 const ExplodedNode<GRState>* PrevN,
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00001948 BugReporterContext& BRC);
Ted Kremenek47a72422009-04-29 18:50:19 +00001949 };
1950
1951 class VISIBILITY_HIDDEN CFRefLeakReport : public CFRefReport {
1952 SourceLocation AllocSite;
1953 const MemRegion* AllocBinding;
1954 public:
1955 CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
1956 ExplodedNode<GRState> *n, SymbolRef sym,
1957 GRExprEngine& Eng);
1958
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00001959 PathDiagnosticPiece* getEndPath(BugReporterContext& BRC,
Ted Kremenek47a72422009-04-29 18:50:19 +00001960 const ExplodedNode<GRState>* N);
1961
1962 SourceLocation getLocation() const { return AllocSite; }
1963 };
1964} // end anonymous namespace
1965
1966void CFRefCount::RegisterChecks(BugReporter& BR) {
1967 useAfterRelease = new UseAfterRelease(this);
1968 BR.Register(useAfterRelease);
1969
1970 releaseNotOwned = new BadRelease(this);
1971 BR.Register(releaseNotOwned);
1972
1973 deallocGC = new DeallocGC(this);
1974 BR.Register(deallocGC);
1975
1976 deallocNotOwned = new DeallocNotOwned(this);
1977 BR.Register(deallocNotOwned);
1978
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001979 overAutorelease = new OverAutorelease(this);
1980 BR.Register(overAutorelease);
1981
Ted Kremenek47a72422009-04-29 18:50:19 +00001982 // First register "return" leaks.
1983 const char* name = 0;
1984
1985 if (isGCEnabled())
1986 name = "Leak of returned object when using garbage collection";
1987 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
1988 name = "Leak of returned object when not using garbage collection (GC) in "
1989 "dual GC/non-GC code";
1990 else {
1991 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
1992 name = "Leak of returned object";
1993 }
1994
1995 leakAtReturn = new LeakAtReturn(this, name);
1996 BR.Register(leakAtReturn);
1997
1998 // Second, register leaks within a function/method.
1999 if (isGCEnabled())
2000 name = "Leak of object when using garbage collection";
2001 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2002 name = "Leak of object when not using garbage collection (GC) in "
2003 "dual GC/non-GC code";
2004 else {
2005 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2006 name = "Leak";
2007 }
2008
2009 leakWithinFunction = new LeakWithinFunction(this, name);
2010 BR.Register(leakWithinFunction);
2011
2012 // Save the reference to the BugReporter.
2013 this->BR = &BR;
2014}
2015
2016static const char* Msgs[] = {
2017 // GC only
2018 "Code is compiled to only use garbage collection",
2019 // No GC.
2020 "Code is compiled to use reference counts",
2021 // Hybrid, with GC.
2022 "Code is compiled to use either garbage collection (GC) or reference counts"
2023 " (non-GC). The bug occurs with GC enabled",
2024 // Hybrid, without GC
2025 "Code is compiled to use either garbage collection (GC) or reference counts"
2026 " (non-GC). The bug occurs in non-GC mode"
2027};
2028
2029std::pair<const char**,const char**> CFRefReport::getExtraDescriptiveText() {
2030 CFRefCount& TF = static_cast<CFRefBug&>(getBugType()).getTF();
2031
2032 switch (TF.getLangOptions().getGCMode()) {
2033 default:
2034 assert(false);
2035
2036 case LangOptions::GCOnly:
2037 assert (TF.isGCEnabled());
2038 return std::make_pair(&Msgs[0], &Msgs[0]+1);
2039
2040 case LangOptions::NonGC:
2041 assert (!TF.isGCEnabled());
2042 return std::make_pair(&Msgs[1], &Msgs[1]+1);
2043
2044 case LangOptions::HybridGC:
2045 if (TF.isGCEnabled())
2046 return std::make_pair(&Msgs[2], &Msgs[2]+1);
2047 else
2048 return std::make_pair(&Msgs[3], &Msgs[3]+1);
2049 }
2050}
2051
2052static inline bool contains(const llvm::SmallVectorImpl<ArgEffect>& V,
2053 ArgEffect X) {
2054 for (llvm::SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
2055 I!=E; ++I)
2056 if (*I == X) return true;
2057
2058 return false;
2059}
2060
2061PathDiagnosticPiece* CFRefReport::VisitNode(const ExplodedNode<GRState>* N,
2062 const ExplodedNode<GRState>* PrevN,
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002063 BugReporterContext& BRC) {
Ted Kremenek47a72422009-04-29 18:50:19 +00002064
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002065 // Check if the type state has changed.
2066 GRStateManager &StMgr = BRC.getStateManager();
Ted Kremenek47a72422009-04-29 18:50:19 +00002067 GRStateRef PrevSt(PrevN->getState(), StMgr);
2068 GRStateRef CurrSt(N->getState(), StMgr);
2069
2070 const RefVal* CurrT = CurrSt.get<RefBindings>(Sym);
2071 if (!CurrT) return NULL;
2072
2073 const RefVal& CurrV = *CurrT;
2074 const RefVal* PrevT = PrevSt.get<RefBindings>(Sym);
2075
2076 // Create a string buffer to constain all the useful things we want
2077 // to tell the user.
2078 std::string sbuf;
2079 llvm::raw_string_ostream os(sbuf);
2080
2081 // This is the allocation site since the previous node had no bindings
2082 // for this symbol.
2083 if (!PrevT) {
2084 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2085
2086 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2087 // Get the name of the callee (if it is available).
2088 SVal X = CurrSt.GetSValAsScalarOrLoc(CE->getCallee());
2089 if (const FunctionDecl* FD = X.getAsFunctionDecl())
2090 os << "Call to function '" << FD->getNameAsString() <<'\'';
2091 else
2092 os << "function call";
2093 }
2094 else {
2095 assert (isa<ObjCMessageExpr>(S));
2096 os << "Method";
2097 }
2098
2099 if (CurrV.getObjKind() == RetEffect::CF) {
2100 os << " returns a Core Foundation object with a ";
2101 }
2102 else {
2103 assert (CurrV.getObjKind() == RetEffect::ObjC);
2104 os << " returns an Objective-C object with a ";
2105 }
2106
2107 if (CurrV.isOwned()) {
2108 os << "+1 retain count (owning reference).";
2109
2110 if (static_cast<CFRefBug&>(getBugType()).getTF().isGCEnabled()) {
2111 assert(CurrV.getObjKind() == RetEffect::CF);
2112 os << " "
2113 "Core Foundation objects are not automatically garbage collected.";
2114 }
2115 }
2116 else {
2117 assert (CurrV.isNotOwned());
2118 os << "+0 retain count (non-owning reference).";
2119 }
2120
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002121 PathDiagnosticLocation Pos(S, BRC.getSourceManager());
Ted Kremenek47a72422009-04-29 18:50:19 +00002122 return new PathDiagnosticEventPiece(Pos, os.str());
2123 }
2124
2125 // Gather up the effects that were performed on the object at this
2126 // program point
2127 llvm::SmallVector<ArgEffect, 2> AEffects;
2128
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002129 if (const RetainSummary *Summ =
2130 TF.getSummaryOfNode(BRC.getNodeResolver().getOriginalNode(N))) {
Ted Kremenek47a72422009-04-29 18:50:19 +00002131 // We only have summaries attached to nodes after evaluating CallExpr and
2132 // ObjCMessageExprs.
2133 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2134
2135 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2136 // Iterate through the parameter expressions and see if the symbol
2137 // was ever passed as an argument.
2138 unsigned i = 0;
2139
2140 for (CallExpr::arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
2141 AI!=AE; ++AI, ++i) {
2142
2143 // Retrieve the value of the argument. Is it the symbol
2144 // we are interested in?
2145 if (CurrSt.GetSValAsScalarOrLoc(*AI).getAsLocSymbol() != Sym)
2146 continue;
2147
2148 // We have an argument. Get the effect!
2149 AEffects.push_back(Summ->getArg(i));
2150 }
2151 }
2152 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
2153 if (Expr *receiver = ME->getReceiver())
2154 if (CurrSt.GetSValAsScalarOrLoc(receiver).getAsLocSymbol() == Sym) {
2155 // The symbol we are tracking is the receiver.
2156 AEffects.push_back(Summ->getReceiverEffect());
2157 }
2158 }
2159 }
2160
2161 do {
2162 // Get the previous type state.
2163 RefVal PrevV = *PrevT;
2164
2165 // Specially handle -dealloc.
2166 if (!TF.isGCEnabled() && contains(AEffects, Dealloc)) {
2167 // Determine if the object's reference count was pushed to zero.
2168 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2169 // We may not have transitioned to 'release' if we hit an error.
2170 // This case is handled elsewhere.
2171 if (CurrV.getKind() == RefVal::Released) {
Ted Kremenek4d99d342009-05-08 20:01:42 +00002172 assert(CurrV.getCombinedCounts() == 0);
Ted Kremenek47a72422009-04-29 18:50:19 +00002173 os << "Object released by directly sending the '-dealloc' message";
2174 break;
2175 }
2176 }
2177
2178 // Specially handle CFMakeCollectable and friends.
2179 if (contains(AEffects, MakeCollectable)) {
2180 // Get the name of the function.
2181 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2182 SVal X = CurrSt.GetSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee());
2183 const FunctionDecl* FD = X.getAsFunctionDecl();
2184 const std::string& FName = FD->getNameAsString();
2185
2186 if (TF.isGCEnabled()) {
2187 // Determine if the object's reference count was pushed to zero.
2188 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2189
2190 os << "In GC mode a call to '" << FName
2191 << "' decrements an object's retain count and registers the "
2192 "object with the garbage collector. ";
2193
2194 if (CurrV.getKind() == RefVal::Released) {
2195 assert(CurrV.getCount() == 0);
2196 os << "Since it now has a 0 retain count the object can be "
2197 "automatically collected by the garbage collector.";
2198 }
2199 else
2200 os << "An object must have a 0 retain count to be garbage collected. "
2201 "After this call its retain count is +" << CurrV.getCount()
2202 << '.';
2203 }
2204 else
2205 os << "When GC is not enabled a call to '" << FName
2206 << "' has no effect on its argument.";
2207
2208 // Nothing more to say.
2209 break;
2210 }
2211
2212 // Determine if the typestate has changed.
2213 if (!(PrevV == CurrV))
2214 switch (CurrV.getKind()) {
2215 case RefVal::Owned:
2216 case RefVal::NotOwned:
2217
Ted Kremenek4d99d342009-05-08 20:01:42 +00002218 if (PrevV.getCount() == CurrV.getCount()) {
2219 // Did an autorelease message get sent?
2220 if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
2221 return 0;
2222
2223 assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount());
2224 os << "Object added to autorelease pool.";
2225 break;
2226 }
Ted Kremenek47a72422009-04-29 18:50:19 +00002227
2228 if (PrevV.getCount() > CurrV.getCount())
2229 os << "Reference count decremented.";
2230 else
2231 os << "Reference count incremented.";
2232
2233 if (unsigned Count = CurrV.getCount())
2234 os << " The object now has a +" << Count << " retain count.";
2235
2236 if (PrevV.getKind() == RefVal::Released) {
2237 assert(TF.isGCEnabled() && CurrV.getCount() > 0);
2238 os << " The object is not eligible for garbage collection until the "
2239 "retain count reaches 0 again.";
2240 }
2241
2242 break;
2243
2244 case RefVal::Released:
2245 os << "Object released.";
2246 break;
2247
2248 case RefVal::ReturnedOwned:
2249 os << "Object returned to caller as an owning reference (single retain "
2250 "count transferred to caller).";
2251 break;
2252
2253 case RefVal::ReturnedNotOwned:
2254 os << "Object returned to caller with a +0 (non-owning) retain count.";
2255 break;
2256
2257 default:
2258 return NULL;
2259 }
2260
2261 // Emit any remaining diagnostics for the argument effects (if any).
2262 for (llvm::SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
2263 E=AEffects.end(); I != E; ++I) {
2264
2265 // A bunch of things have alternate behavior under GC.
2266 if (TF.isGCEnabled())
2267 switch (*I) {
2268 default: break;
2269 case Autorelease:
2270 os << "In GC mode an 'autorelease' has no effect.";
2271 continue;
2272 case IncRefMsg:
2273 os << "In GC mode the 'retain' message has no effect.";
2274 continue;
2275 case DecRefMsg:
2276 os << "In GC mode the 'release' message has no effect.";
2277 continue;
2278 }
2279 }
2280 } while(0);
2281
2282 if (os.str().empty())
2283 return 0; // We have nothing to say!
2284
2285 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002286 PathDiagnosticLocation Pos(S, BRC.getSourceManager());
Ted Kremenek47a72422009-04-29 18:50:19 +00002287 PathDiagnosticPiece* P = new PathDiagnosticEventPiece(Pos, os.str());
2288
2289 // Add the range by scanning the children of the statement for any bindings
2290 // to Sym.
2291 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I)
2292 if (Expr* Exp = dyn_cast_or_null<Expr>(*I))
2293 if (CurrSt.GetSValAsScalarOrLoc(Exp).getAsLocSymbol() == Sym) {
2294 P->addRange(Exp->getSourceRange());
2295 break;
2296 }
2297
2298 return P;
2299}
2300
2301namespace {
2302 class VISIBILITY_HIDDEN FindUniqueBinding :
2303 public StoreManager::BindingsHandler {
2304 SymbolRef Sym;
2305 const MemRegion* Binding;
2306 bool First;
2307
2308 public:
2309 FindUniqueBinding(SymbolRef sym) : Sym(sym), Binding(0), First(true) {}
2310
2311 bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
2312 SVal val) {
2313
2314 SymbolRef SymV = val.getAsSymbol();
2315 if (!SymV || SymV != Sym)
2316 return true;
2317
2318 if (Binding) {
2319 First = false;
2320 return false;
2321 }
2322 else
2323 Binding = R;
2324
2325 return true;
2326 }
2327
2328 operator bool() { return First && Binding; }
2329 const MemRegion* getRegion() { return Binding; }
2330 };
2331}
2332
2333static std::pair<const ExplodedNode<GRState>*,const MemRegion*>
2334GetAllocationSite(GRStateManager& StateMgr, const ExplodedNode<GRState>* N,
2335 SymbolRef Sym) {
2336
2337 // Find both first node that referred to the tracked symbol and the
2338 // memory location that value was store to.
2339 const ExplodedNode<GRState>* Last = N;
2340 const MemRegion* FirstBinding = 0;
2341
2342 while (N) {
2343 const GRState* St = N->getState();
2344 RefBindings B = St->get<RefBindings>();
2345
2346 if (!B.lookup(Sym))
2347 break;
2348
2349 FindUniqueBinding FB(Sym);
2350 StateMgr.iterBindings(St, FB);
2351 if (FB) FirstBinding = FB.getRegion();
2352
2353 Last = N;
2354 N = N->pred_empty() ? NULL : *(N->pred_begin());
2355 }
2356
2357 return std::make_pair(Last, FirstBinding);
2358}
2359
2360PathDiagnosticPiece*
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002361CFRefReport::getEndPath(BugReporterContext& BRC,
2362 const ExplodedNode<GRState>* EndN) {
2363 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenek47a72422009-04-29 18:50:19 +00002364 // assigned to different variables, etc.
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002365 BRC.addNotableSymbol(Sym);
2366 return RangedBugReport::getEndPath(BRC, EndN);
Ted Kremenek47a72422009-04-29 18:50:19 +00002367}
2368
2369PathDiagnosticPiece*
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002370CFRefLeakReport::getEndPath(BugReporterContext& BRC,
2371 const ExplodedNode<GRState>* EndN){
Ted Kremenek47a72422009-04-29 18:50:19 +00002372
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002373 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenek47a72422009-04-29 18:50:19 +00002374 // assigned to different variables, etc.
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002375 BRC.addNotableSymbol(Sym);
Ted Kremenek47a72422009-04-29 18:50:19 +00002376
2377 // We are reporting a leak. Walk up the graph to get to the first node where
2378 // the symbol appeared, and also get the first VarDecl that tracked object
2379 // is stored to.
2380 const ExplodedNode<GRState>* AllocNode = 0;
2381 const MemRegion* FirstBinding = 0;
2382
2383 llvm::tie(AllocNode, FirstBinding) =
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00002384 GetAllocationSite(BRC.getStateManager(), EndN, Sym);
Ted Kremenek47a72422009-04-29 18:50:19 +00002385
2386 // Get the allocate site.
2387 assert(AllocNode);
2388 Stmt* FirstStmt = cast<PostStmt>(AllocNode->getLocation()).getStmt();
2389
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002390 SourceManager& SMgr = BRC.getSourceManager();
Ted Kremenek47a72422009-04-29 18:50:19 +00002391 unsigned AllocLine =SMgr.getInstantiationLineNumber(FirstStmt->getLocStart());
2392
2393 // Compute an actual location for the leak. Sometimes a leak doesn't
2394 // occur at an actual statement (e.g., transition between blocks; end
2395 // of function) so we need to walk the graph and compute a real location.
2396 const ExplodedNode<GRState>* LeakN = EndN;
2397 PathDiagnosticLocation L;
2398
2399 while (LeakN) {
2400 ProgramPoint P = LeakN->getLocation();
2401
2402 if (const PostStmt *PS = dyn_cast<PostStmt>(&P)) {
2403 L = PathDiagnosticLocation(PS->getStmt()->getLocStart(), SMgr);
2404 break;
2405 }
2406 else if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
2407 if (const Stmt* Term = BE->getSrc()->getTerminator()) {
2408 L = PathDiagnosticLocation(Term->getLocStart(), SMgr);
2409 break;
2410 }
2411 }
2412
2413 LeakN = LeakN->succ_empty() ? 0 : *(LeakN->succ_begin());
2414 }
2415
2416 if (!L.isValid()) {
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002417 const Decl &D = BRC.getCodeDecl();
2418 L = PathDiagnosticLocation(D.getBodyRBrace(BRC.getASTContext()), SMgr);
Ted Kremenek47a72422009-04-29 18:50:19 +00002419 }
2420
2421 std::string sbuf;
2422 llvm::raw_string_ostream os(sbuf);
2423
2424 os << "Object allocated on line " << AllocLine;
2425
2426 if (FirstBinding)
2427 os << " and stored into '" << FirstBinding->getString() << '\'';
2428
2429 // Get the retain count.
2430 const RefVal* RV = EndN->getState()->get<RefBindings>(Sym);
2431
2432 if (RV->getKind() == RefVal::ErrorLeakReturned) {
2433 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
2434 // ojbects. Only "copy", "alloc", "retain" and "new" transfer ownership
2435 // to the caller for NS objects.
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002436 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(BRC.getCodeDecl());
Ted Kremenek47a72422009-04-29 18:50:19 +00002437 os << " is returned from a method whose name ('"
Ted Kremenek314b1952009-04-29 23:03:22 +00002438 << MD.getSelector().getAsString()
Ted Kremenek47a72422009-04-29 18:50:19 +00002439 << "') does not contain 'copy' or otherwise starts with"
2440 " 'new' or 'alloc'. This violates the naming convention rules given"
Ted Kremenek2a410c92009-04-29 22:25:52 +00002441 " in the Memory Management Guide for Cocoa (object leaked)";
Ted Kremenek47a72422009-04-29 18:50:19 +00002442 }
2443 else
2444 os << " is no longer referenced after this point and has a retain count of"
Ted Kremenek2a410c92009-04-29 22:25:52 +00002445 " +" << RV->getCount() << " (object leaked)";
Ted Kremenek47a72422009-04-29 18:50:19 +00002446
2447 return new PathDiagnosticEventPiece(L, os.str());
2448}
2449
2450
2451CFRefLeakReport::CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2452 ExplodedNode<GRState> *n,
2453 SymbolRef sym, GRExprEngine& Eng)
2454: CFRefReport(D, tf, n, sym)
2455{
2456
2457 // Most bug reports are cached at the location where they occured.
2458 // With leaks, we want to unique them by the location where they were
2459 // allocated, and only report a single path. To do this, we need to find
2460 // the allocation site of a piece of tracked memory, which we do via a
2461 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2462 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2463 // that all ancestor nodes that represent the allocation site have the
2464 // same SourceLocation.
2465 const ExplodedNode<GRState>* AllocNode = 0;
2466
2467 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding.
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00002468 GetAllocationSite(Eng.getStateManager(), getEndNode(), getSymbol());
Ted Kremenek47a72422009-04-29 18:50:19 +00002469
2470 // Get the SourceLocation for the allocation site.
2471 ProgramPoint P = AllocNode->getLocation();
2472 AllocSite = cast<PostStmt>(P).getStmt()->getLocStart();
2473
2474 // Fill in the description of the bug.
2475 Description.clear();
2476 llvm::raw_string_ostream os(Description);
2477 SourceManager& SMgr = Eng.getContext().getSourceManager();
2478 unsigned AllocLine = SMgr.getInstantiationLineNumber(AllocSite);
Ted Kremenek2e9d0302009-05-02 19:05:19 +00002479 os << "Potential leak ";
2480 if (tf.isGCEnabled()) {
2481 os << "(when using garbage collection) ";
2482 }
2483 os << "of an object allocated on line " << AllocLine;
Ted Kremenek47a72422009-04-29 18:50:19 +00002484
2485 // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2486 if (AllocBinding)
2487 os << " and stored into '" << AllocBinding->getString() << '\'';
2488}
2489
2490//===----------------------------------------------------------------------===//
2491// Main checker logic.
2492//===----------------------------------------------------------------------===//
2493
Ted Kremenek272aa852008-06-25 21:21:56 +00002494/// GetReturnType - Used to get the return type of a message expression or
2495/// function call with the intention of affixing that type to a tracked symbol.
2496/// While the the return type can be queried directly from RetEx, when
2497/// invoking class methods we augment to the return type to be that of
2498/// a pointer to the class (as opposed it just being id).
2499static QualType GetReturnType(Expr* RetE, ASTContext& Ctx) {
2500
2501 QualType RetTy = RetE->getType();
2502
2503 // FIXME: We aren't handling id<...>.
Chris Lattnerb724ab22008-07-26 22:36:27 +00002504 const PointerType* PT = RetTy->getAsPointerType();
Ted Kremenek272aa852008-06-25 21:21:56 +00002505 if (!PT)
2506 return RetTy;
2507
2508 // If RetEx is not a message expression just return its type.
2509 // If RetEx is a message expression, return its types if it is something
2510 /// more specific than id.
2511
2512 ObjCMessageExpr* ME = dyn_cast<ObjCMessageExpr>(RetE);
2513
Steve Naroff17c03822009-02-12 17:52:19 +00002514 if (!ME || !Ctx.isObjCIdStructType(PT->getPointeeType()))
Ted Kremenek272aa852008-06-25 21:21:56 +00002515 return RetTy;
2516
2517 ObjCInterfaceDecl* D = ME->getClassInfo().first;
2518
2519 // At this point we know the return type of the message expression is id.
2520 // If we have an ObjCInterceDecl, we know this is a call to a class method
2521 // whose type we can resolve. In such cases, promote the return type to
2522 // Class*.
2523 return !D ? RetTy : Ctx.getPointerType(Ctx.getObjCInterfaceType(D));
2524}
2525
2526
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002527void CFRefCount::EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002528 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002529 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002530 Expr* Ex,
2531 Expr* Receiver,
Ted Kremenek286e9852009-05-04 04:57:00 +00002532 const RetainSummary& Summ,
Zhongxing Xucac107a2009-04-20 05:24:46 +00002533 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002534 ExplodedNode<GRState>* Pred) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002535
Ted Kremeneka7338b42008-03-11 06:39:11 +00002536 // Get the state.
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002537 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenek0106e202008-10-24 20:32:50 +00002538 ASTContext& Ctx = Eng.getStateManager().getContext();
Ted Kremenek227c5372008-05-06 02:41:27 +00002539
2540 // Evaluate the effect of the arguments.
Ted Kremenek1feab292008-04-16 04:28:53 +00002541 RefVal::Kind hasErr = (RefVal::Kind) 0;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002542 unsigned idx = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002543 Expr* ErrorExpr = NULL;
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002544 SymbolRef ErrorSym = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002545
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002546 for (ExprIterator I = arg_beg; I != arg_end; ++I, ++idx) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002547 SVal V = state.GetSValAsScalarOrLoc(*I);
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002548 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002549
Ted Kremenek74556a12009-03-26 03:35:11 +00002550 if (Sym)
Ted Kremenekb6578942009-02-24 19:15:11 +00002551 if (RefBindings::data_type* T = state.get<RefBindings>(Sym)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002552 state = Update(state, Sym, *T, Summ.getArg(idx), hasErr);
Ted Kremenekb6578942009-02-24 19:15:11 +00002553 if (hasErr) {
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002554 ErrorExpr = *I;
Ted Kremenek6064a362008-07-07 16:21:19 +00002555 ErrorSym = Sym;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002556 break;
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002557 }
2558 continue;
Ted Kremenekb6578942009-02-24 19:15:11 +00002559 }
Ted Kremenekede40b72008-07-09 18:11:16 +00002560
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002561 if (isa<Loc>(V)) {
2562 if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(&V)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002563 if (Summ.getArg(idx) == DoNothingByRef)
Ted Kremenekede40b72008-07-09 18:11:16 +00002564 continue;
2565
2566 // Invalidate the value of the variable passed by reference.
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002567
2568 // FIXME: Either this logic should also be replicated in GRSimpleVals
2569 // or should be pulled into a separate "constraint engine."
Ted Kremenekede40b72008-07-09 18:11:16 +00002570
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002571 // FIXME: We can have collisions on the conjured symbol if the
2572 // expression *I also creates conjured symbols. We probably want
2573 // to identify conjured symbols by an expression pair: the enclosing
2574 // expression (the context) and the expression itself. This should
Ted Kremenekede40b72008-07-09 18:11:16 +00002575 // disambiguate conjured symbols.
Ted Kremenekb15eba42008-10-04 05:50:14 +00002576
Ted Kremenek38a4b4b2008-10-17 20:28:54 +00002577 const TypedRegion* R = dyn_cast<TypedRegion>(MR->getRegion());
Zhongxing Xub9d47a42009-04-29 02:30:09 +00002578
Ted Kremenek73ec7732009-05-06 18:19:24 +00002579 if (R) {
2580 // Are we dealing with an ElementRegion? If the element type is
2581 // a basic integer type (e.g., char, int) and the underying region
2582 // is also typed then strip off the ElementRegion.
2583 // FIXME: We really need to think about this for the general case
2584 // as sometimes we are reasoning about arrays and other times
2585 // about (char*), etc., is just a form of passing raw bytes.
2586 // e.g., void *p = alloca(); foo((char*)p);
2587 if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
2588 // Checking for 'integral type' is probably too promiscuous, but
2589 // we'll leave it in for now until we have a systematic way of
2590 // handling all of these cases. Eventually we need to come up
2591 // with an interface to StoreManager so that this logic can be
2592 // approriately delegated to the respective StoreManagers while
2593 // still allowing us to do checker-specific logic (e.g.,
2594 // invalidating reference counts), probably via callbacks.
2595 if (ER->getElementType()->isIntegralType())
2596 if (const TypedRegion *superReg =
2597 dyn_cast<TypedRegion>(ER->getSuperRegion()))
2598 R = superReg;
2599 // FIXME: What about layers of ElementRegions?
2600 }
2601
Ted Kremenek618c6cd2008-12-18 23:34:57 +00002602 // Is the invalidated variable something that we were tracking?
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002603 SymbolRef Sym = state.GetSValAsScalarOrLoc(R).getAsLocSymbol();
Ted Kremenek618c6cd2008-12-18 23:34:57 +00002604
Ted Kremenek53b24182009-03-04 22:56:43 +00002605 // Remove any existing reference-count binding.
Ted Kremenek74556a12009-03-26 03:35:11 +00002606 if (Sym) state = state.remove<RefBindings>(Sym);
Ted Kremenekb15eba42008-10-04 05:50:14 +00002607
Ted Kremenek53b24182009-03-04 22:56:43 +00002608 if (R->isBoundable(Ctx)) {
2609 // Set the value of the variable to be a conjured symbol.
2610 unsigned Count = Builder.getCurrentBlockCount();
2611 QualType T = R->getRValueType(Ctx);
2612
Zhongxing Xu079dc352009-04-09 06:03:54 +00002613 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())){
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002614 ValueManager &ValMgr = Eng.getValueManager();
2615 SVal V = ValMgr.getConjuredSymbolVal(*I, T, Count);
Zhongxing Xu079dc352009-04-09 06:03:54 +00002616 state = state.BindLoc(Loc::MakeVal(R), V);
Ted Kremenek53b24182009-03-04 22:56:43 +00002617 }
2618 else if (const RecordType *RT = T->getAsStructureType()) {
2619 // Handle structs in a not so awesome way. Here we just
2620 // eagerly bind new symbols to the fields. In reality we
2621 // should have the store manager handle this. The idea is just
2622 // to prototype some basic functionality here. All of this logic
2623 // should one day soon just go away.
2624 const RecordDecl *RD = RT->getDecl()->getDefinition(Ctx);
2625
2626 // No record definition. There is nothing we can do.
2627 if (!RD)
2628 continue;
2629
2630 MemRegionManager &MRMgr = state.getManager().getRegionManager();
2631
2632 // Iterate through the fields and construct new symbols.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002633 for (RecordDecl::field_iterator FI=RD->field_begin(Ctx),
2634 FE=RD->field_end(Ctx); FI!=FE; ++FI) {
Ted Kremenek53b24182009-03-04 22:56:43 +00002635
2636 // For now just handle scalar fields.
2637 FieldDecl *FD = *FI;
2638 QualType FT = FD->getType();
2639
2640 if (Loc::IsLocType(FT) ||
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002641 (FT->isIntegerType() && FT->isScalarType())) {
Ted Kremenek53b24182009-03-04 22:56:43 +00002642 const FieldRegion* FR = MRMgr.getFieldRegion(FD, R);
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002643 ValueManager &ValMgr = Eng.getValueManager();
2644 SVal V = ValMgr.getConjuredSymbolVal(*I, FT, Count);
Zhongxing Xuc458e322009-04-09 06:32:20 +00002645 state = state.BindLoc(Loc::MakeVal(FR), V);
Ted Kremenek53b24182009-03-04 22:56:43 +00002646 }
2647 }
2648 }
2649 else {
2650 // Just blast away other values.
2651 state = state.BindLoc(*MR, UnknownVal());
2652 }
Ted Kremenek8f90e712008-10-17 22:23:12 +00002653 }
Ted Kremenekb15eba42008-10-04 05:50:14 +00002654 }
2655 else
Ted Kremenek09102db2008-11-12 19:22:09 +00002656 state = state.BindLoc(*MR, UnknownVal());
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002657 }
2658 else {
2659 // Nuke all other arguments passed by reference.
Zhongxing Xu097fc982008-10-17 05:57:07 +00002660 state = state.Unbind(cast<Loc>(V));
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002661 }
Ted Kremeneke4924202008-04-11 20:51:02 +00002662 }
Zhongxing Xu097fc982008-10-17 05:57:07 +00002663 else if (isa<nonloc::LocAsInteger>(V))
2664 state = state.Unbind(cast<nonloc::LocAsInteger>(V).getLoc());
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002665 }
Ted Kremenek1feab292008-04-16 04:28:53 +00002666
Ted Kremenek272aa852008-06-25 21:21:56 +00002667 // Evaluate the effect on the message receiver.
Ted Kremenek227c5372008-05-06 02:41:27 +00002668 if (!ErrorExpr && Receiver) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002669 SymbolRef Sym = state.GetSValAsScalarOrLoc(Receiver).getAsLocSymbol();
Ted Kremenek74556a12009-03-26 03:35:11 +00002670 if (Sym) {
Ted Kremenekb6578942009-02-24 19:15:11 +00002671 if (const RefVal* T = state.get<RefBindings>(Sym)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002672 state = Update(state, Sym, *T, Summ.getReceiverEffect(), hasErr);
Ted Kremenekb6578942009-02-24 19:15:11 +00002673 if (hasErr) {
Ted Kremenek227c5372008-05-06 02:41:27 +00002674 ErrorExpr = Receiver;
Ted Kremenek6064a362008-07-07 16:21:19 +00002675 ErrorSym = Sym;
Ted Kremenek227c5372008-05-06 02:41:27 +00002676 }
Ted Kremenekb6578942009-02-24 19:15:11 +00002677 }
Ted Kremenek227c5372008-05-06 02:41:27 +00002678 }
2679 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002680
Ted Kremenek272aa852008-06-25 21:21:56 +00002681 // Process any errors.
Ted Kremenek1feab292008-04-16 04:28:53 +00002682 if (hasErr) {
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002683 ProcessNonLeakError(Dst, Builder, Ex, ErrorExpr, Pred, state,
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002684 hasErr, ErrorSym);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002685 return;
Ted Kremenek0d721572008-03-11 17:48:22 +00002686 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002687
Ted Kremenekf2717b02008-07-18 17:24:20 +00002688 // Consult the summary for the return value.
Ted Kremenek286e9852009-05-04 04:57:00 +00002689 RetEffect RE = Summ.getRetEffect();
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002690
2691 switch (RE.getKind()) {
2692 default:
2693 assert (false && "Unhandled RetEffect."); break;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002694
Ted Kremenek8f90e712008-10-17 22:23:12 +00002695 case RetEffect::NoRet: {
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002696
Ted Kremenek455dd862008-04-11 20:23:24 +00002697 // Make up a symbol for the return value (not reference counted).
Ted Kremeneke4924202008-04-11 20:51:02 +00002698 // FIXME: This is basically copy-and-paste from GRSimpleVals. We
2699 // should compose behavior, not copy it.
Ted Kremenek455dd862008-04-11 20:23:24 +00002700
Ted Kremenek8f90e712008-10-17 22:23:12 +00002701 // FIXME: We eventually should handle structs and other compound types
2702 // that are returned by value.
2703
2704 QualType T = Ex->getType();
2705
Ted Kremenek79413a52008-11-13 06:10:40 +00002706 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())) {
Ted Kremenek455dd862008-04-11 20:23:24 +00002707 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002708 ValueManager &ValMgr = Eng.getValueManager();
2709 SVal X = ValMgr.getConjuredSymbolVal(Ex, T, Count);
Ted Kremenek09102db2008-11-12 19:22:09 +00002710 state = state.BindExpr(Ex, X, false);
Ted Kremenek455dd862008-04-11 20:23:24 +00002711 }
2712
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002713 break;
Ted Kremenek8f90e712008-10-17 22:23:12 +00002714 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002715
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002716 case RetEffect::Alias: {
Ted Kremenek272aa852008-06-25 21:21:56 +00002717 unsigned idx = RE.getIndex();
Ted Kremenek2719e982008-06-17 02:43:46 +00002718 assert (arg_end >= arg_beg);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002719 assert (idx < (unsigned) (arg_end - arg_beg));
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002720 SVal V = state.GetSValAsScalarOrLoc(*(arg_beg+idx));
Ted Kremenek09102db2008-11-12 19:22:09 +00002721 state = state.BindExpr(Ex, V, false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002722 break;
2723 }
2724
Ted Kremenek227c5372008-05-06 02:41:27 +00002725 case RetEffect::ReceiverAlias: {
2726 assert (Receiver);
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002727 SVal V = state.GetSValAsScalarOrLoc(Receiver);
Ted Kremenek09102db2008-11-12 19:22:09 +00002728 state = state.BindExpr(Ex, V, false);
Ted Kremenek227c5372008-05-06 02:41:27 +00002729 break;
2730 }
2731
Ted Kremenek6a1cc252008-06-23 18:02:52 +00002732 case RetEffect::OwnedAllocatedSymbol:
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002733 case RetEffect::OwnedSymbol: {
2734 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke9e726e2009-04-09 16:13:17 +00002735 ValueManager &ValMgr = Eng.getValueManager();
2736 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
2737 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
2738 state = state.set<RefBindings>(Sym, RefVal::makeOwned(RE.getObjKind(),
2739 RetT));
2740 state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenek45c52a12009-03-09 22:46:49 +00002741
2742 // FIXME: Add a flag to the checker where allocations are assumed to
2743 // *not fail.
2744#if 0
Ted Kremeneke62fd052009-01-28 22:27:59 +00002745 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) {
2746 bool isFeasible;
2747 state = state.Assume(loc::SymbolVal(Sym), true, isFeasible);
2748 assert(isFeasible && "Cannot assume fresh symbol is non-null.");
2749 }
Ted Kremenek45c52a12009-03-09 22:46:49 +00002750#endif
Ted Kremenek6a1cc252008-06-23 18:02:52 +00002751
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002752 break;
2753 }
Ted Kremenek382fb4e2009-04-27 19:14:45 +00002754
2755 case RetEffect::GCNotOwnedSymbol:
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002756 case RetEffect::NotOwnedSymbol: {
2757 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke9e726e2009-04-09 16:13:17 +00002758 ValueManager &ValMgr = Eng.getValueManager();
2759 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
2760 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
2761 state = state.set<RefBindings>(Sym, RefVal::makeNotOwned(RE.getObjKind(),
2762 RetT));
2763 state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002764 break;
2765 }
2766 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002767
Ted Kremenek0dd65012009-02-18 02:00:25 +00002768 // Generate a sink node if we are at the end of a path.
2769 GRExprEngine::NodeTy *NewNode =
Ted Kremenek286e9852009-05-04 04:57:00 +00002770 Summ.isEndPath() ? Builder.MakeSinkNode(Dst, Ex, Pred, state)
2771 : Builder.MakeNode(Dst, Ex, Pred, state);
Ted Kremenek0dd65012009-02-18 02:00:25 +00002772
2773 // Annotate the edge with summary we used.
Ted Kremenek286e9852009-05-04 04:57:00 +00002774 if (NewNode) SummaryLog[NewNode] = &Summ;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002775}
2776
2777
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002778void CFRefCount::EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002779 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002780 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu097fc982008-10-17 05:57:07 +00002781 CallExpr* CE, SVal L,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002782 ExplodedNode<GRState>* Pred) {
Zhongxing Xucac107a2009-04-20 05:24:46 +00002783 const FunctionDecl* FD = L.getAsFunctionDecl();
Ted Kremenek286e9852009-05-04 04:57:00 +00002784 RetainSummary* Summ = !FD ? Summaries.getDefaultSummary()
Zhongxing Xucac107a2009-04-20 05:24:46 +00002785 : Summaries.getSummary(const_cast<FunctionDecl*>(FD));
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002786
Ted Kremenek286e9852009-05-04 04:57:00 +00002787 assert(Summ);
2788 EvalSummary(Dst, Eng, Builder, CE, 0, *Summ,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002789 CE->arg_begin(), CE->arg_end(), Pred);
Ted Kremenek827f93b2008-03-06 00:08:09 +00002790}
Ted Kremeneka7338b42008-03-11 06:39:11 +00002791
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002792void CFRefCount::EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002793 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002794 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002795 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002796 ExplodedNode<GRState>* Pred) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002797 RetainSummary* Summ = 0;
Ted Kremenek33661802008-05-01 21:31:50 +00002798
Ted Kremenek272aa852008-06-25 21:21:56 +00002799 if (Expr* Receiver = ME->getReceiver()) {
2800 // We need the type-information of the tracked receiver object
2801 // Retrieve it from the state.
2802 ObjCInterfaceDecl* ID = 0;
2803
2804 // FIXME: Wouldn't it be great if this code could be reduced? It's just
2805 // a chain of lookups.
Ted Kremeneka821b792009-04-29 05:04:30 +00002806 // FIXME: Is this really working as expected? There are cases where
2807 // we just use the 'ID' from the message expression.
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002808 const GRState* St = Builder.GetState(Pred);
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002809 SVal V = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
Ted Kremenek272aa852008-06-25 21:21:56 +00002810
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002811 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenek74556a12009-03-26 03:35:11 +00002812 if (Sym) {
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002813 if (const RefVal* T = St->get<RefBindings>(Sym)) {
Ted Kremenek6064a362008-07-07 16:21:19 +00002814 QualType Ty = T->getType();
Ted Kremenek272aa852008-06-25 21:21:56 +00002815
2816 if (const PointerType* PT = Ty->getAsPointerType()) {
2817 QualType PointeeTy = PT->getPointeeType();
2818
2819 if (ObjCInterfaceType* IT = dyn_cast<ObjCInterfaceType>(PointeeTy))
2820 ID = IT->getDecl();
2821 }
2822 }
2823 }
2824
Ted Kremenek04e00302009-04-29 17:09:14 +00002825 // FIXME: The receiver could be a reference to a class, meaning that
2826 // we should use the class method.
2827 Summ = Summaries.getInstanceMethodSummary(ME, ID);
Ted Kremenek0106e202008-10-24 20:32:50 +00002828
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002829 // Special-case: are we sending a mesage to "self"?
2830 // This is a hack. When we have full-IP this should be removed.
Ted Kremenek2f226732009-05-04 05:31:22 +00002831 if (isa<ObjCMethodDecl>(&Eng.getGraph().getCodeDecl())) {
2832 if (Expr* Receiver = ME->getReceiver()) {
2833 SVal X = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
2834 if (loc::MemRegionVal* L = dyn_cast<loc::MemRegionVal>(&X))
2835 if (L->getRegion() == Eng.getStateManager().getSelfRegion(St)) {
2836 // Update the summary to make the default argument effect
2837 // 'StopTracking'.
2838 Summ = Summaries.copySummary(Summ);
2839 Summ->setDefaultArgEffect(StopTracking);
2840 }
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002841 }
2842 }
Ted Kremenek272aa852008-06-25 21:21:56 +00002843 }
Ted Kremenek1feab292008-04-16 04:28:53 +00002844 else
Ted Kremenekb17fa952009-04-23 21:25:57 +00002845 Summ = Summaries.getClassMethodSummary(ME);
Ted Kremenek1feab292008-04-16 04:28:53 +00002846
Ted Kremenek286e9852009-05-04 04:57:00 +00002847 if (!Summ)
2848 Summ = Summaries.getDefaultSummary();
Ted Kremenekccbe79a2009-04-24 17:50:11 +00002849
Ted Kremenek286e9852009-05-04 04:57:00 +00002850 EvalSummary(Dst, Eng, Builder, ME, ME->getReceiver(), *Summ,
Ted Kremenek926abf22008-05-06 04:20:12 +00002851 ME->arg_begin(), ME->arg_end(), Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002852}
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002853
2854namespace {
2855class VISIBILITY_HIDDEN StopTrackingCallback : public SymbolVisitor {
2856 GRStateRef state;
2857public:
2858 StopTrackingCallback(GRStateRef st) : state(st) {}
2859 GRStateRef getState() { return state; }
2860
2861 bool VisitSymbol(SymbolRef sym) {
2862 state = state.remove<RefBindings>(sym);
2863 return true;
2864 }
Ted Kremenek926abf22008-05-06 04:20:12 +00002865
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002866 const GRState* getState() const { return state.getState(); }
2867};
2868} // end anonymous namespace
2869
2870
Ted Kremeneka42be302009-02-14 01:43:44 +00002871void CFRefCount::EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val) {
Ted Kremeneka42be302009-02-14 01:43:44 +00002872 // Are we storing to something that causes the value to "escape"?
Ted Kremenek7aef4842008-04-16 20:40:59 +00002873 bool escapes = false;
2874
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002875 // A value escapes in three possible cases (this may change):
2876 //
2877 // (1) we are binding to something that is not a memory region.
2878 // (2) we are binding to a memregion that does not have stack storage
2879 // (3) we are binding to a memregion with stack storage that the store
Ted Kremeneka42be302009-02-14 01:43:44 +00002880 // does not understand.
Ted Kremeneka42be302009-02-14 01:43:44 +00002881 GRStateRef state = B.getState();
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002882
Ted Kremeneka42be302009-02-14 01:43:44 +00002883 if (!isa<loc::MemRegionVal>(location))
Ted Kremenek7aef4842008-04-16 20:40:59 +00002884 escapes = true;
Ted Kremenekb15eba42008-10-04 05:50:14 +00002885 else {
Ted Kremeneka42be302009-02-14 01:43:44 +00002886 const MemRegion* R = cast<loc::MemRegionVal>(location).getRegion();
2887 escapes = !B.getStateManager().hasStackStorage(R);
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002888
2889 if (!escapes) {
2890 // To test (3), generate a new state with the binding removed. If it is
2891 // the same state, then it escapes (since the store cannot represent
2892 // the binding).
Ted Kremeneka42be302009-02-14 01:43:44 +00002893 escapes = (state == (state.BindLoc(cast<Loc>(location), UnknownVal())));
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002894 }
Ted Kremenekb15eba42008-10-04 05:50:14 +00002895 }
Ted Kremeneka42be302009-02-14 01:43:44 +00002896
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002897 // If our store can represent the binding and we aren't storing to something
2898 // that doesn't have local storage then just return and have the simulation
2899 // state continue as is.
2900 if (!escapes)
2901 return;
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002902
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002903 // Otherwise, find all symbols referenced by 'val' that we are tracking
2904 // and stop tracking them.
2905 B.MakeNode(state.scanReachableSymbols<StopTrackingCallback>(val).getState());
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002906}
2907
Ted Kremenek541db372008-04-24 23:57:27 +00002908
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002909 // Return statements.
2910
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002911void CFRefCount::EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002912 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002913 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002914 ReturnStmt* S,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002915 ExplodedNode<GRState>* Pred) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002916
2917 Expr* RetE = S->getRetValue();
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002918 if (!RetE)
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002919 return;
2920
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002921 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002922 SymbolRef Sym = state.GetSValAsScalarOrLoc(RetE).getAsLocSymbol();
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002923
Ted Kremenek74556a12009-03-26 03:35:11 +00002924 if (!Sym)
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002925 return;
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00002926
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002927 // Get the reference count binding (if any).
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002928 const RefVal* T = state.get<RefBindings>(Sym);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002929
2930 if (!T)
2931 return;
2932
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00002933 // Update the autorelease counts.
2934 static unsigned autoreleasetag = 0;
2935 GenericNodeBuilder Bd(Builder, S, &autoreleasetag);
Ted Kremenek412ca1e2009-05-09 00:10:05 +00002936 bool stop = false;
2937 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state , Bd, Pred, Eng, Sym,
2938 *T, stop);
2939
2940 if (stop)
2941 return;
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00002942
2943 // Get the updated binding.
2944 T = state.get<RefBindings>(Sym);
2945 assert(T);
2946
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002947 // Change the reference count.
Ted Kremenek6064a362008-07-07 16:21:19 +00002948 RefVal X = *T;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002949
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002950 switch (X.getKind()) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002951 case RefVal::Owned: {
2952 unsigned cnt = X.getCount();
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00002953 assert (cnt > 0);
2954 X = RefVal::makeReturnedOwned(cnt - 1);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002955 break;
2956 }
2957
2958 case RefVal::NotOwned: {
2959 unsigned cnt = X.getCount();
2960 X = cnt ? RefVal::makeReturnedOwned(cnt - 1)
2961 : RefVal::makeReturnedNotOwned();
2962 break;
2963 }
2964
2965 default:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002966 return;
2967 }
2968
2969 // Update the binding.
Ted Kremenek91781202008-08-17 03:20:02 +00002970 state = state.set<RefBindings>(Sym, X);
Ted Kremenek47a72422009-04-29 18:50:19 +00002971 Pred = Builder.MakeNode(Dst, S, Pred, state);
2972
Ted Kremeneka208d0c2009-04-30 05:51:50 +00002973 // Did we cache out?
2974 if (!Pred)
2975 return;
Ted Kremenek41a4bc62009-05-08 23:09:42 +00002976
Ted Kremenek47a72422009-04-29 18:50:19 +00002977 // Any leaks or other errors?
2978 if (X.isReturnedOwned() && X.getCount() == 0) {
2979 const Decl *CD = &Eng.getStateManager().getCodeDecl();
2980
Ted Kremenek314b1952009-04-29 23:03:22 +00002981 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002982 const RetainSummary &Summ = *Summaries.getMethodSummary(MD);
2983 if (!Summ.getRetEffect().isOwned()) {
Ted Kremenek47a72422009-04-29 18:50:19 +00002984 static int ReturnOwnLeakTag = 0;
2985 state = state.set<RefBindings>(Sym, X ^ RefVal::ErrorLeakReturned);
Ted Kremenek47a72422009-04-29 18:50:19 +00002986 // Generate an error node.
Ted Kremeneka208d0c2009-04-30 05:51:50 +00002987 if (ExplodedNode<GRState> *N =
2988 Builder.generateNode(PostStmt(S, &ReturnOwnLeakTag), state, Pred)) {
2989 CFRefLeakReport *report =
2990 new CFRefLeakReport(*static_cast<CFRefBug*>(leakAtReturn), *this,
2991 N, Sym, Eng);
2992 BR->EmitReport(report);
2993 }
Ted Kremenek47a72422009-04-29 18:50:19 +00002994 }
2995 }
2996 }
Ted Kremenek41a4bc62009-05-08 23:09:42 +00002997
2998
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002999}
3000
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003001// Assumptions.
3002
Ted Kremenekabd89ac2008-08-13 04:27:00 +00003003const GRState* CFRefCount::EvalAssume(GRStateManager& VMgr,
3004 const GRState* St,
Zhongxing Xu097fc982008-10-17 05:57:07 +00003005 SVal Cond, bool Assumption,
Ted Kremenekf22f8682008-07-10 22:03:41 +00003006 bool& isFeasible) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003007
3008 // FIXME: We may add to the interface of EvalAssume the list of symbols
3009 // whose assumptions have changed. For now we just iterate through the
3010 // bindings and check if any of the tracked symbols are NULL. This isn't
3011 // too bad since the number of symbols we will track in practice are
3012 // probably small and EvalAssume is only called at branches and a few
3013 // other places.
Ted Kremenek4ae925c2008-08-14 21:16:54 +00003014 RefBindings B = St->get<RefBindings>();
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003015
3016 if (B.isEmpty())
3017 return St;
3018
3019 bool changed = false;
Ted Kremenek91781202008-08-17 03:20:02 +00003020
3021 GRStateRef state(St, VMgr);
3022 RefBindings::Factory& RefBFactory = state.get_context<RefBindings>();
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003023
3024 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003025 // Check if the symbol is null (or equal to any constant).
3026 // If this is the case, stop tracking the symbol.
Zhongxing Xuc6b27d02008-08-29 14:52:36 +00003027 if (VMgr.getSymVal(St, I.getKey())) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003028 changed = true;
3029 B = RefBFactory.Remove(B, I.getKey());
3030 }
3031 }
3032
Ted Kremenek91781202008-08-17 03:20:02 +00003033 if (changed)
3034 state = state.set<RefBindings>(B);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003035
Ted Kremenek4ae925c2008-08-14 21:16:54 +00003036 return state;
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003037}
Ted Kremeneka7338b42008-03-11 06:39:11 +00003038
Ted Kremenekb6578942009-02-24 19:15:11 +00003039GRStateRef CFRefCount::Update(GRStateRef state, SymbolRef sym,
3040 RefVal V, ArgEffect E,
3041 RefVal::Kind& hasErr) {
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003042
3043 // In GC mode [... release] and [... retain] do nothing.
3044 switch (E) {
3045 default: break;
3046 case IncRefMsg: E = isGCEnabled() ? DoNothing : IncRef; break;
3047 case DecRefMsg: E = isGCEnabled() ? DoNothing : DecRef; break;
Ted Kremenek2126bef2009-02-18 21:57:45 +00003048 case MakeCollectable: E = isGCEnabled() ? DecRef : DoNothing; break;
Ted Kremenekaac82832009-02-23 17:45:03 +00003049 case NewAutoreleasePool: E = isGCEnabled() ? DoNothing :
3050 NewAutoreleasePool; break;
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003051 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00003052
Ted Kremenek6537a642009-03-17 19:42:23 +00003053 // Handle all use-after-releases.
3054 if (!isGCEnabled() && V.getKind() == RefVal::Released) {
3055 V = V ^ RefVal::ErrorUseAfterRelease;
3056 hasErr = V.getKind();
3057 return state.set<RefBindings>(sym, V);
3058 }
3059
Ted Kremenek0d721572008-03-11 17:48:22 +00003060 switch (E) {
3061 default:
3062 assert (false && "Unhandled CFRef transition.");
Ted Kremenek6537a642009-03-17 19:42:23 +00003063
3064 case Dealloc:
3065 // Any use of -dealloc in GC is *bad*.
3066 if (isGCEnabled()) {
3067 V = V ^ RefVal::ErrorDeallocGC;
3068 hasErr = V.getKind();
3069 break;
3070 }
3071
3072 switch (V.getKind()) {
3073 default:
3074 assert(false && "Invalid case.");
3075 case RefVal::Owned:
3076 // The object immediately transitions to the released state.
3077 V = V ^ RefVal::Released;
3078 V.clearCounts();
3079 return state.set<RefBindings>(sym, V);
3080 case RefVal::NotOwned:
3081 V = V ^ RefVal::ErrorDeallocNotOwned;
3082 hasErr = V.getKind();
3083 break;
3084 }
3085 break;
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003086
Ted Kremenekb7826ab2009-02-25 23:11:49 +00003087 case NewAutoreleasePool:
3088 assert(!isGCEnabled());
3089 return state.add<AutoreleaseStack>(sym);
3090
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003091 case MayEscape:
3092 if (V.getKind() == RefVal::Owned) {
Ted Kremenek272aa852008-06-25 21:21:56 +00003093 V = V ^ RefVal::NotOwned;
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003094 break;
3095 }
Ted Kremenek6537a642009-03-17 19:42:23 +00003096
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003097 // Fall-through.
Ted Kremenek1b4b6562009-02-25 02:54:57 +00003098
Ted Kremenekede40b72008-07-09 18:11:16 +00003099 case DoNothingByRef:
Ted Kremenek0d721572008-03-11 17:48:22 +00003100 case DoNothing:
Ted Kremenekb6578942009-02-24 19:15:11 +00003101 return state;
Ted Kremeneke5a4bb02008-06-30 16:57:41 +00003102
Ted Kremenek9b112d22009-01-28 21:44:40 +00003103 case Autorelease:
Ted Kremenek6537a642009-03-17 19:42:23 +00003104 if (isGCEnabled())
3105 return state;
Ted Kremenek681fb352009-03-20 17:34:15 +00003106
3107 // Update the autorelease counts.
3108 state = SendAutorelease(state, ARCountFactory, sym);
Ted Kremenek4d99d342009-05-08 20:01:42 +00003109 V = V.autorelease();
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003110
Ted Kremenek227c5372008-05-06 02:41:27 +00003111 case StopTracking:
Ted Kremenekb6578942009-02-24 19:15:11 +00003112 return state.remove<RefBindings>(sym);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003113
Ted Kremenek0d721572008-03-11 17:48:22 +00003114 case IncRef:
3115 switch (V.getKind()) {
3116 default:
3117 assert(false);
3118
3119 case RefVal::Owned:
Ted Kremenek0d721572008-03-11 17:48:22 +00003120 case RefVal::NotOwned:
Ted Kremenek272aa852008-06-25 21:21:56 +00003121 V = V + 1;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003122 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003123 case RefVal::Released:
Ted Kremenek6537a642009-03-17 19:42:23 +00003124 // Non-GC cases are handled above.
3125 assert(isGCEnabled());
3126 V = (V ^ RefVal::Owned) + 1;
Ted Kremenek0d721572008-03-11 17:48:22 +00003127 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003128 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00003129 break;
3130
Ted Kremenek272aa852008-06-25 21:21:56 +00003131 case SelfOwn:
3132 V = V ^ RefVal::NotOwned;
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003133 // Fall-through.
Ted Kremenek0d721572008-03-11 17:48:22 +00003134 case DecRef:
3135 switch (V.getKind()) {
3136 default:
Ted Kremenek6537a642009-03-17 19:42:23 +00003137 // case 'RefVal::Released' handled above.
Ted Kremenek0d721572008-03-11 17:48:22 +00003138 assert (false);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003139
Ted Kremenek272aa852008-06-25 21:21:56 +00003140 case RefVal::Owned:
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00003141 assert(V.getCount() > 0);
3142 if (V.getCount() == 1) V = V ^ RefVal::Released;
3143 V = V - 1;
Ted Kremenek0d721572008-03-11 17:48:22 +00003144 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003145
Ted Kremenek272aa852008-06-25 21:21:56 +00003146 case RefVal::NotOwned:
3147 if (V.getCount() > 0)
3148 V = V - 1;
Ted Kremenekc4f81022008-04-10 23:09:18 +00003149 else {
Ted Kremenek272aa852008-06-25 21:21:56 +00003150 V = V ^ RefVal::ErrorReleaseNotOwned;
Ted Kremenek1feab292008-04-16 04:28:53 +00003151 hasErr = V.getKind();
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003152 }
Ted Kremenek0d721572008-03-11 17:48:22 +00003153 break;
Ted Kremenek6537a642009-03-17 19:42:23 +00003154
Ted Kremenek0d721572008-03-11 17:48:22 +00003155 case RefVal::Released:
Ted Kremenek6537a642009-03-17 19:42:23 +00003156 // Non-GC cases are handled above.
3157 assert(isGCEnabled());
Ted Kremenek272aa852008-06-25 21:21:56 +00003158 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek1feab292008-04-16 04:28:53 +00003159 hasErr = V.getKind();
Ted Kremenek6537a642009-03-17 19:42:23 +00003160 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003161 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00003162 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003163 }
Ted Kremenekb6578942009-02-24 19:15:11 +00003164 return state.set<RefBindings>(sym, V);
Ted Kremeneka7338b42008-03-11 06:39:11 +00003165}
3166
Ted Kremenek10fe66d2008-04-09 01:10:13 +00003167//===----------------------------------------------------------------------===//
Ted Kremenek708af042009-02-05 06:50:21 +00003168// Handle dead symbols and end-of-path.
3169//===----------------------------------------------------------------------===//
3170
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003171std::pair<ExplodedNode<GRState>*, GRStateRef>
3172CFRefCount::HandleAutoreleaseCounts(GRStateRef state, GenericNodeBuilder Bd,
3173 ExplodedNode<GRState>* Pred,
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003174 GRExprEngine &Eng,
3175 SymbolRef Sym, RefVal V, bool &stop) {
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003176
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003177 unsigned ACnt = V.getAutoreleaseCount();
3178 stop = false;
3179
3180 // No autorelease counts? Nothing to be done.
3181 if (!ACnt)
3182 return std::make_pair(Pred, state);
3183
3184 assert(!isGCEnabled() && "Autorelease counts in GC mode?");
3185 unsigned Cnt = V.getCount();
3186
3187 if (ACnt <= Cnt) {
3188 V.setCount(Cnt - ACnt);
3189 V.setAutoreleaseCount(0);
3190 state = state.set<RefBindings>(Sym, V);
3191 ExplodedNode<GRState> *N = Bd.MakeNode(state, Pred);
3192 stop = (N == 0);
3193 return std::make_pair(N, state);
3194 }
3195
3196 // Woah! More autorelease counts then retain counts left.
3197 // Emit hard error.
3198 stop = true;
3199 V = V ^ RefVal::ErrorOverAutorelease;
3200 state = state.set<RefBindings>(Sym, V);
3201
3202 if (ExplodedNode<GRState> *N = Bd.MakeNode(state, Pred)) {
3203 CFRefReport *report =
3204 new CFRefReport(*static_cast<CFRefBug*>(overAutorelease),
3205 *this, N, Sym);
3206 BR->EmitReport(report);
3207 }
3208
3209 return std::make_pair((ExplodedNode<GRState>*)0, state);
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003210}
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003211
3212GRStateRef
3213CFRefCount::HandleSymbolDeath(GRStateRef state, SymbolRef sid, RefVal V,
3214 llvm::SmallVectorImpl<SymbolRef> &Leaked) {
3215
3216 bool hasLeak = V.isOwned() ||
3217 ((V.isNotOwned() || V.isReturnedOwned()) && V.getCount() > 0);
3218
3219 if (!hasLeak)
3220 return state.remove<RefBindings>(sid);
3221
3222 Leaked.push_back(sid);
3223 return state.set<RefBindings>(sid, V ^ RefVal::ErrorLeak);
3224}
3225
3226ExplodedNode<GRState>*
3227CFRefCount::ProcessLeaks(GRStateRef state,
3228 llvm::SmallVectorImpl<SymbolRef> &Leaked,
3229 GenericNodeBuilder &Builder,
3230 GRExprEngine& Eng,
3231 ExplodedNode<GRState> *Pred) {
3232
3233 if (Leaked.empty())
3234 return Pred;
3235
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003236 // Generate an intermediate node representing the leak point.
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003237 ExplodedNode<GRState> *N = Builder.MakeNode(state, Pred);
3238
3239 if (N) {
3240 for (llvm::SmallVectorImpl<SymbolRef>::iterator
3241 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3242
3243 CFRefBug *BT = static_cast<CFRefBug*>(Pred ? leakWithinFunction
3244 : leakAtReturn);
3245 assert(BT && "BugType not initialized.");
3246 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N, *I, Eng);
3247 BR->EmitReport(report);
3248 }
3249 }
3250
3251 return N;
3252}
3253
Ted Kremenek708af042009-02-05 06:50:21 +00003254void CFRefCount::EvalEndPath(GRExprEngine& Eng,
3255 GREndPathNodeBuilder<GRState>& Builder) {
3256
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003257 GRStateRef state(Builder.getState(), Eng.getStateManager());
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003258 GenericNodeBuilder Bd(Builder);
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003259 RefBindings B = state.get<RefBindings>();
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003260 ExplodedNode<GRState> *Pred = 0;
3261
3262 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003263 bool stop = false;
3264 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state, Bd, Pred, Eng,
3265 (*I).first,
3266 (*I).second, stop);
3267
3268 if (stop)
3269 return;
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003270 }
3271
3272 B = state.get<RefBindings>();
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003273 llvm::SmallVector<SymbolRef, 10> Leaked;
Ted Kremenek708af042009-02-05 06:50:21 +00003274
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003275 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I)
3276 state = HandleSymbolDeath(state, (*I).first, (*I).second, Leaked);
3277
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003278 ProcessLeaks(state, Leaked, Bd, Eng, Pred);
Ted Kremenek708af042009-02-05 06:50:21 +00003279}
3280
3281void CFRefCount::EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
3282 GRExprEngine& Eng,
3283 GRStmtNodeBuilder<GRState>& Builder,
3284 ExplodedNode<GRState>* Pred,
3285 Stmt* S,
3286 const GRState* St,
3287 SymbolReaper& SymReaper) {
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003288
3289 GRStateRef state(St, Eng.getStateManager());
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003290 RefBindings B = state.get<RefBindings>();
3291
3292 // Update counts from autorelease pools
3293 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3294 E = SymReaper.dead_end(); I != E; ++I) {
3295 SymbolRef Sym = *I;
3296 if (const RefVal* T = B.lookup(Sym)){
3297 // Use the symbol as the tag.
3298 // FIXME: This might not be as unique as we would like.
3299 GenericNodeBuilder Bd(Builder, S, Sym);
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003300 bool stop = false;
3301 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state, Bd, Pred, Eng,
3302 Sym, *T, stop);
3303 if (stop)
3304 return;
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003305 }
3306 }
3307
3308 B = state.get<RefBindings>();
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003309 llvm::SmallVector<SymbolRef, 10> Leaked;
Ted Kremenek708af042009-02-05 06:50:21 +00003310
3311 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003312 E = SymReaper.dead_end(); I != E; ++I) {
3313 if (const RefVal* T = B.lookup(*I))
3314 state = HandleSymbolDeath(state, *I, *T, Leaked);
3315 }
Ted Kremenek708af042009-02-05 06:50:21 +00003316
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003317 static unsigned LeakPPTag = 0;
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003318 {
3319 GenericNodeBuilder Bd(Builder, S, &LeakPPTag);
3320 Pred = ProcessLeaks(state, Leaked, Bd, Eng, Pred);
3321 }
Ted Kremenek708af042009-02-05 06:50:21 +00003322
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003323 // Did we cache out?
3324 if (!Pred)
3325 return;
Ted Kremenek876d8df2009-02-19 23:47:02 +00003326
3327 // Now generate a new node that nukes the old bindings.
Ted Kremenek876d8df2009-02-19 23:47:02 +00003328 RefBindings::Factory& F = state.get_context<RefBindings>();
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003329
Ted Kremenek876d8df2009-02-19 23:47:02 +00003330 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003331 E = SymReaper.dead_end(); I!=E; ++I) B = F.Remove(B, *I);
3332
Ted Kremenek876d8df2009-02-19 23:47:02 +00003333 state = state.set<RefBindings>(B);
3334 Builder.MakeNode(Dst, S, Pred, state);
Ted Kremenek708af042009-02-05 06:50:21 +00003335}
3336
3337void CFRefCount::ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
3338 GRStmtNodeBuilder<GRState>& Builder,
3339 Expr* NodeExpr, Expr* ErrorExpr,
3340 ExplodedNode<GRState>* Pred,
3341 const GRState* St,
3342 RefVal::Kind hasErr, SymbolRef Sym) {
3343 Builder.BuildSinks = true;
3344 GRExprEngine::NodeTy* N = Builder.MakeNode(Dst, NodeExpr, Pred, St);
3345
3346 if (!N) return;
3347
3348 CFRefBug *BT = 0;
3349
Ted Kremenek6537a642009-03-17 19:42:23 +00003350 switch (hasErr) {
3351 default:
3352 assert(false && "Unhandled error.");
3353 return;
3354 case RefVal::ErrorUseAfterRelease:
3355 BT = static_cast<CFRefBug*>(useAfterRelease);
3356 break;
3357 case RefVal::ErrorReleaseNotOwned:
3358 BT = static_cast<CFRefBug*>(releaseNotOwned);
3359 break;
3360 case RefVal::ErrorDeallocGC:
3361 BT = static_cast<CFRefBug*>(deallocGC);
3362 break;
3363 case RefVal::ErrorDeallocNotOwned:
3364 BT = static_cast<CFRefBug*>(deallocNotOwned);
3365 break;
Ted Kremenek708af042009-02-05 06:50:21 +00003366 }
3367
Ted Kremenekc26c4692009-02-18 03:48:14 +00003368 CFRefReport *report = new CFRefReport(*BT, *this, N, Sym);
Ted Kremenek708af042009-02-05 06:50:21 +00003369 report->addRange(ErrorExpr->getSourceRange());
3370 BR->EmitReport(report);
3371}
3372
3373//===----------------------------------------------------------------------===//
Ted Kremenekb1983ba2008-04-10 22:16:52 +00003374// Transfer function creation for external clients.
Ted Kremeneka7338b42008-03-11 06:39:11 +00003375//===----------------------------------------------------------------------===//
3376
Ted Kremenekfe30beb2008-04-30 23:47:44 +00003377GRTransferFuncs* clang::MakeCFRefCountTF(ASTContext& Ctx, bool GCEnabled,
3378 const LangOptions& lopts) {
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00003379 return new CFRefCount(Ctx, GCEnabled, lopts);
Ted Kremeneka4c74292008-04-10 22:58:08 +00003380}