blob: 80ea6e9f5abbf9d91ba5d62bc9d5792878205f81 [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)
Ted Kremenek3e3328d2009-05-09 01:50:57 +0000178 return SNB->generateNode(PostStmt(S, tag), state, Pred);
Ted Kremenek41a4bc62009-05-08 23:09:42 +0000179
180 assert(ENB);
Ted Kremenek3f15aba2009-05-09 00:44:07 +0000181 return ENB->generateNode(state, Pred);
Ted Kremenek41a4bc62009-05-08 23:09:42 +0000182 }
183};
184} // end anonymous namespace
185
Ted Kremenek7d421f32008-04-09 23:49:11 +0000186//===----------------------------------------------------------------------===//
Ted Kremenek272aa852008-06-25 21:21:56 +0000187// Selector creation functions.
Ted Kremenekd9ccf682008-04-17 18:12:53 +0000188//===----------------------------------------------------------------------===//
189
Ted Kremenek1bd6ddb2008-05-01 18:31:44 +0000190static inline Selector GetNullarySelector(const char* name, ASTContext& Ctx) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +0000191 IdentifierInfo* II = &Ctx.Idents.get(name);
192 return Ctx.Selectors.getSelector(0, &II);
193}
194
Ted Kremenek0e344d42008-05-06 00:30:21 +0000195static inline Selector GetUnarySelector(const char* name, ASTContext& Ctx) {
196 IdentifierInfo* II = &Ctx.Idents.get(name);
197 return Ctx.Selectors.getSelector(1, &II);
198}
199
Ted Kremenek272aa852008-06-25 21:21:56 +0000200//===----------------------------------------------------------------------===//
201// Type querying functions.
202//===----------------------------------------------------------------------===//
203
Ted Kremenek17144e82009-01-12 21:45:02 +0000204static bool hasPrefix(const char* s, const char* prefix) {
205 if (!prefix)
206 return true;
Ted Kremenek62820d82008-05-07 20:06:41 +0000207
Ted Kremenek17144e82009-01-12 21:45:02 +0000208 char c = *s;
209 char cP = *prefix;
Ted Kremenek62820d82008-05-07 20:06:41 +0000210
Ted Kremenek17144e82009-01-12 21:45:02 +0000211 while (c != '\0' && cP != '\0') {
212 if (c != cP) break;
213 c = *(++s);
214 cP = *(++prefix);
215 }
Ted Kremenek62820d82008-05-07 20:06:41 +0000216
Ted Kremenek17144e82009-01-12 21:45:02 +0000217 return cP == '\0';
Ted Kremenek62820d82008-05-07 20:06:41 +0000218}
219
Ted Kremenek17144e82009-01-12 21:45:02 +0000220static bool hasSuffix(const char* s, const char* suffix) {
221 const char* loc = strstr(s, suffix);
222 return loc && strcmp(suffix, loc) == 0;
223}
224
225static bool isRefType(QualType RetTy, const char* prefix,
226 ASTContext* Ctx = 0, const char* name = 0) {
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000227
Ted Kremenek17144e82009-01-12 21:45:02 +0000228 if (TypedefType* TD = dyn_cast<TypedefType>(RetTy.getTypePtr())) {
229 const char* TDName = TD->getDecl()->getIdentifier()->getName();
230 return hasPrefix(TDName, prefix) && hasSuffix(TDName, "Ref");
231 }
232
233 if (!Ctx || !name)
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000234 return false;
Ted Kremenek17144e82009-01-12 21:45:02 +0000235
236 // Is the type void*?
237 const PointerType* PT = RetTy->getAsPointerType();
238 if (!(PT->getPointeeType().getUnqualifiedType() == Ctx->VoidTy))
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000239 return false;
Ted Kremenek17144e82009-01-12 21:45:02 +0000240
241 // Does the name start with the prefix?
242 return hasPrefix(name, prefix);
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000243}
244
Ted Kremenekd9ccf682008-04-17 18:12:53 +0000245//===----------------------------------------------------------------------===//
Ted Kremenek272aa852008-06-25 21:21:56 +0000246// Primitives used for constructing summaries for function/method calls.
Ted Kremenek7d421f32008-04-09 23:49:11 +0000247//===----------------------------------------------------------------------===//
248
Ted Kremenek272aa852008-06-25 21:21:56 +0000249/// ArgEffect is used to summarize a function/method call's effect on a
250/// particular argument.
Ted Kremenek6537a642009-03-17 19:42:23 +0000251enum ArgEffect { Autorelease, Dealloc, DecRef, DecRefMsg, DoNothing,
252 DoNothingByRef, IncRefMsg, IncRef, MakeCollectable, MayEscape,
253 NewAutoreleasePool, SelfOwn, StopTracking };
Ted Kremenek272aa852008-06-25 21:21:56 +0000254
Ted Kremeneka7338b42008-03-11 06:39:11 +0000255namespace llvm {
Ted Kremeneka56ae162009-05-03 05:20:50 +0000256template <> struct FoldingSetTrait<ArgEffect> {
257static inline void Profile(const ArgEffect X, FoldingSetNodeID& ID) {
258 ID.AddInteger((unsigned) X);
259}
Ted Kremenek272aa852008-06-25 21:21:56 +0000260};
Ted Kremeneka7338b42008-03-11 06:39:11 +0000261} // end llvm namespace
262
Ted Kremeneka56ae162009-05-03 05:20:50 +0000263/// ArgEffects summarizes the effects of a function/method call on all of
264/// its arguments.
265typedef llvm::ImmutableMap<unsigned,ArgEffect> ArgEffects;
266
Ted Kremeneka7338b42008-03-11 06:39:11 +0000267namespace {
Ted Kremenek272aa852008-06-25 21:21:56 +0000268
269/// RetEffect is used to summarize a function/method call's behavior with
270/// respect to its return value.
271class VISIBILITY_HIDDEN RetEffect {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000272public:
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000273 enum Kind { NoRet, Alias, OwnedSymbol, OwnedAllocatedSymbol,
Ted Kremenek382fb4e2009-04-27 19:14:45 +0000274 NotOwnedSymbol, GCNotOwnedSymbol, ReceiverAlias };
Ted Kremenek68621b92009-01-28 05:56:51 +0000275
276 enum ObjKind { CF, ObjC, AnyObj };
277
Ted Kremeneka7338b42008-03-11 06:39:11 +0000278private:
Ted Kremenek68621b92009-01-28 05:56:51 +0000279 Kind K;
280 ObjKind O;
281 unsigned index;
282
283 RetEffect(Kind k, unsigned idx = 0) : K(k), O(AnyObj), index(idx) {}
284 RetEffect(Kind k, ObjKind o) : K(k), O(o), index(0) {}
Ted Kremenek827f93b2008-03-06 00:08:09 +0000285
Ted Kremeneka7338b42008-03-11 06:39:11 +0000286public:
Ted Kremenek68621b92009-01-28 05:56:51 +0000287 Kind getKind() const { return K; }
288
289 ObjKind getObjKind() const { return O; }
Ted Kremenek272aa852008-06-25 21:21:56 +0000290
291 unsigned getIndex() const {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000292 assert(getKind() == Alias);
Ted Kremenek68621b92009-01-28 05:56:51 +0000293 return index;
Ted Kremeneka7338b42008-03-11 06:39:11 +0000294 }
Ted Kremenek827f93b2008-03-06 00:08:09 +0000295
Ted Kremenek314b1952009-04-29 23:03:22 +0000296 bool isOwned() const {
297 return K == OwnedSymbol || K == OwnedAllocatedSymbol;
298 }
299
Ted Kremenek272aa852008-06-25 21:21:56 +0000300 static RetEffect MakeAlias(unsigned Idx) {
301 return RetEffect(Alias, Idx);
302 }
303 static RetEffect MakeReceiverAlias() {
304 return RetEffect(ReceiverAlias);
305 }
Ted Kremenek68621b92009-01-28 05:56:51 +0000306 static RetEffect MakeOwned(ObjKind o, bool isAllocated = false) {
307 return RetEffect(isAllocated ? OwnedAllocatedSymbol : OwnedSymbol, o);
Ted Kremenek272aa852008-06-25 21:21:56 +0000308 }
Ted Kremenek68621b92009-01-28 05:56:51 +0000309 static RetEffect MakeNotOwned(ObjKind o) {
310 return RetEffect(NotOwnedSymbol, o);
Ted Kremenek382fb4e2009-04-27 19:14:45 +0000311 }
312 static RetEffect MakeGCNotOwned() {
313 return RetEffect(GCNotOwnedSymbol, ObjC);
314 }
315
Ted Kremenek272aa852008-06-25 21:21:56 +0000316 static RetEffect MakeNoRet() {
317 return RetEffect(NoRet);
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000318 }
Ted Kremenek827f93b2008-03-06 00:08:09 +0000319
Ted Kremenek272aa852008-06-25 21:21:56 +0000320 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek68621b92009-01-28 05:56:51 +0000321 ID.AddInteger((unsigned)K);
322 ID.AddInteger((unsigned)O);
323 ID.AddInteger(index);
Ted Kremenek272aa852008-06-25 21:21:56 +0000324 }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000325};
Ted Kremeneka7338b42008-03-11 06:39:11 +0000326
Ted Kremenek272aa852008-06-25 21:21:56 +0000327
Ted Kremenek2f226732009-05-04 05:31:22 +0000328class VISIBILITY_HIDDEN RetainSummary {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000329 /// Args - an ordered vector of (index, ArgEffect) pairs, where index
330 /// specifies the argument (starting from 0). This can be sparsely
331 /// populated; arguments with no entry in Args use 'DefaultArgEffect'.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000332 ArgEffects Args;
Ted Kremenekbcaff792008-05-06 15:44:25 +0000333
334 /// DefaultArgEffect - The default ArgEffect to apply to arguments that
335 /// do not have an entry in Args.
336 ArgEffect DefaultArgEffect;
337
Ted Kremenek272aa852008-06-25 21:21:56 +0000338 /// Receiver - If this summary applies to an Objective-C message expression,
339 /// this is the effect applied to the state of the receiver.
Ted Kremenek266d8b62008-05-06 02:26:56 +0000340 ArgEffect Receiver;
Ted Kremenek272aa852008-06-25 21:21:56 +0000341
342 /// Ret - The effect on the return value. Used to indicate if the
343 /// function/method call returns a new tracked symbol, returns an
344 /// alias of one of the arguments in the call, and so on.
Ted Kremeneka7338b42008-03-11 06:39:11 +0000345 RetEffect Ret;
Ted Kremenek272aa852008-06-25 21:21:56 +0000346
Ted Kremenekf2717b02008-07-18 17:24:20 +0000347 /// EndPath - Indicates that execution of this method/function should
348 /// terminate the simulation of a path.
349 bool EndPath;
350
Ted Kremeneka7338b42008-03-11 06:39:11 +0000351public:
Ted Kremeneka56ae162009-05-03 05:20:50 +0000352 RetainSummary(ArgEffects A, RetEffect R, ArgEffect defaultEff,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000353 ArgEffect ReceiverEff, bool endpath = false)
354 : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R),
355 EndPath(endpath) {}
Ted Kremeneka7338b42008-03-11 06:39:11 +0000356
Ted Kremenek272aa852008-06-25 21:21:56 +0000357 /// getArg - Return the argument effect on the argument specified by
358 /// idx (starting from 0).
Ted Kremenek0d721572008-03-11 17:48:22 +0000359 ArgEffect getArg(unsigned idx) const {
Ted Kremeneka56ae162009-05-03 05:20:50 +0000360 if (const ArgEffect *AE = Args.lookup(idx))
361 return *AE;
Ted Kremenekae855d42008-04-24 17:22:33 +0000362
Ted Kremenekbcaff792008-05-06 15:44:25 +0000363 return DefaultArgEffect;
Ted Kremenek0d721572008-03-11 17:48:22 +0000364 }
365
Ted Kremenek2f226732009-05-04 05:31:22 +0000366 /// setDefaultArgEffect - Set the default argument effect.
367 void setDefaultArgEffect(ArgEffect E) {
368 DefaultArgEffect = E;
369 }
370
371 /// setArg - Set the argument effect on the argument specified by idx.
372 void setArgEffect(ArgEffects::Factory& AF, unsigned idx, ArgEffect E) {
373 Args = AF.Add(Args, idx, E);
374 }
375
Ted Kremenek272aa852008-06-25 21:21:56 +0000376 /// getRetEffect - Returns the effect on the return value of the call.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000377 RetEffect getRetEffect() const { return Ret; }
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000378
Ted Kremenek2f226732009-05-04 05:31:22 +0000379 /// setRetEffect - Set the effect of the return value of the call.
380 void setRetEffect(RetEffect E) { Ret = E; }
381
Ted Kremenekf2717b02008-07-18 17:24:20 +0000382 /// isEndPath - Returns true if executing the given method/function should
383 /// terminate the path.
384 bool isEndPath() const { return EndPath; }
385
Ted Kremenek272aa852008-06-25 21:21:56 +0000386 /// getReceiverEffect - Returns the effect on the receiver of the call.
387 /// This is only meaningful if the summary applies to an ObjCMessageExpr*.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000388 ArgEffect getReceiverEffect() const { return Receiver; }
Ted Kremenek266d8b62008-05-06 02:26:56 +0000389
Ted Kremenek2f226732009-05-04 05:31:22 +0000390 /// setReceiverEffect - Set the effect on the receiver of the call.
391 void setReceiverEffect(ArgEffect E) { Receiver = E; }
392
Ted Kremeneka56ae162009-05-03 05:20:50 +0000393 typedef ArgEffects::iterator ExprIterator;
Ted Kremeneka7338b42008-03-11 06:39:11 +0000394
Ted Kremeneka56ae162009-05-03 05:20:50 +0000395 ExprIterator begin_args() const { return Args.begin(); }
396 ExprIterator end_args() const { return Args.end(); }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000397
Ted Kremeneka56ae162009-05-03 05:20:50 +0000398 static void Profile(llvm::FoldingSetNodeID& ID, ArgEffects A,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000399 RetEffect RetEff, ArgEffect DefaultEff,
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000400 ArgEffect ReceiverEff, bool EndPath) {
Ted Kremeneka56ae162009-05-03 05:20:50 +0000401 ID.Add(A);
Ted Kremenek266d8b62008-05-06 02:26:56 +0000402 ID.Add(RetEff);
Ted Kremenekbcaff792008-05-06 15:44:25 +0000403 ID.AddInteger((unsigned) DefaultEff);
Ted Kremenek266d8b62008-05-06 02:26:56 +0000404 ID.AddInteger((unsigned) ReceiverEff);
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000405 ID.AddInteger((unsigned) EndPath);
Ted Kremeneka7338b42008-03-11 06:39:11 +0000406 }
407
408 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000409 Profile(ID, Args, Ret, DefaultArgEffect, Receiver, EndPath);
Ted Kremeneka7338b42008-03-11 06:39:11 +0000410 }
411};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000412} // end anonymous namespace
Ted Kremeneka7338b42008-03-11 06:39:11 +0000413
Ted Kremenek272aa852008-06-25 21:21:56 +0000414//===----------------------------------------------------------------------===//
415// Data structures for constructing summaries.
416//===----------------------------------------------------------------------===//
Ted Kremenek9f0fc792008-06-24 03:49:48 +0000417
Ted Kremenek272aa852008-06-25 21:21:56 +0000418namespace {
419class VISIBILITY_HIDDEN ObjCSummaryKey {
420 IdentifierInfo* II;
421 Selector S;
422public:
423 ObjCSummaryKey(IdentifierInfo* ii, Selector s)
424 : II(ii), S(s) {}
425
Ted Kremenek314b1952009-04-29 23:03:22 +0000426 ObjCSummaryKey(const ObjCInterfaceDecl* d, Selector s)
Ted Kremenek272aa852008-06-25 21:21:56 +0000427 : II(d ? d->getIdentifier() : 0), S(s) {}
428
429 ObjCSummaryKey(Selector s)
430 : II(0), S(s) {}
431
432 IdentifierInfo* getIdentifier() const { return II; }
433 Selector getSelector() const { return S; }
434};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000435}
436
437namespace llvm {
Ted Kremenek272aa852008-06-25 21:21:56 +0000438template <> struct DenseMapInfo<ObjCSummaryKey> {
439 static inline ObjCSummaryKey getEmptyKey() {
440 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
441 DenseMapInfo<Selector>::getEmptyKey());
442 }
Ted Kremenek84f010c2008-06-23 23:30:29 +0000443
Ted Kremenek272aa852008-06-25 21:21:56 +0000444 static inline ObjCSummaryKey getTombstoneKey() {
445 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
446 DenseMapInfo<Selector>::getTombstoneKey());
447 }
448
449 static unsigned getHashValue(const ObjCSummaryKey &V) {
450 return (DenseMapInfo<IdentifierInfo*>::getHashValue(V.getIdentifier())
451 & 0x88888888)
452 | (DenseMapInfo<Selector>::getHashValue(V.getSelector())
453 & 0x55555555);
454 }
455
456 static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
457 return DenseMapInfo<IdentifierInfo*>::isEqual(LHS.getIdentifier(),
458 RHS.getIdentifier()) &&
459 DenseMapInfo<Selector>::isEqual(LHS.getSelector(),
460 RHS.getSelector());
461 }
462
463 static bool isPod() {
464 return DenseMapInfo<ObjCInterfaceDecl*>::isPod() &&
465 DenseMapInfo<Selector>::isPod();
466 }
467};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000468} // end llvm namespace
Ted Kremeneka7338b42008-03-11 06:39:11 +0000469
Ted Kremenek84f010c2008-06-23 23:30:29 +0000470namespace {
Ted Kremenek272aa852008-06-25 21:21:56 +0000471class VISIBILITY_HIDDEN ObjCSummaryCache {
472 typedef llvm::DenseMap<ObjCSummaryKey, RetainSummary*> MapTy;
473 MapTy M;
474public:
475 ObjCSummaryCache() {}
476
477 typedef MapTy::iterator iterator;
478
Ted Kremenek314b1952009-04-29 23:03:22 +0000479 iterator find(const ObjCInterfaceDecl* D, IdentifierInfo *ClsName,
480 Selector S) {
Ted Kremeneka821b792009-04-29 05:04:30 +0000481 // Lookup the method using the decl for the class @interface. If we
482 // have no decl, lookup using the class name.
483 return D ? find(D, S) : find(ClsName, S);
484 }
485
Ted Kremenek314b1952009-04-29 23:03:22 +0000486 iterator find(const ObjCInterfaceDecl* D, Selector S) {
Ted Kremenek272aa852008-06-25 21:21:56 +0000487 // Do a lookup with the (D,S) pair. If we find a match return
488 // the iterator.
489 ObjCSummaryKey K(D, S);
490 MapTy::iterator I = M.find(K);
491
492 if (I != M.end() || !D)
493 return I;
494
495 // Walk the super chain. If we find a hit with a parent, we'll end
496 // up returning that summary. We actually allow that key (null,S), as
497 // we cache summaries for the null ObjCInterfaceDecl* to allow us to
498 // generate initial summaries without having to worry about NSObject
499 // being declared.
500 // FIXME: We may change this at some point.
501 for (ObjCInterfaceDecl* C=D->getSuperClass() ;; C=C->getSuperClass()) {
502 if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
503 break;
504
505 if (!C)
506 return I;
507 }
508
509 // Cache the summary with original key to make the next lookup faster
510 // and return the iterator.
511 M[K] = I->second;
512 return I;
513 }
514
Ted Kremenek9449ca92008-08-12 20:41:56 +0000515
Ted Kremenek272aa852008-06-25 21:21:56 +0000516 iterator find(Expr* Receiver, Selector S) {
517 return find(getReceiverDecl(Receiver), S);
518 }
519
520 iterator find(IdentifierInfo* II, Selector S) {
521 // FIXME: Class method lookup. Right now we dont' have a good way
522 // of going between IdentifierInfo* and the class hierarchy.
523 iterator I = M.find(ObjCSummaryKey(II, S));
524 return I == M.end() ? M.find(ObjCSummaryKey(S)) : I;
525 }
526
527 ObjCInterfaceDecl* getReceiverDecl(Expr* E) {
528
529 const PointerType* PT = E->getType()->getAsPointerType();
530 if (!PT) return 0;
531
532 ObjCInterfaceType* OI = dyn_cast<ObjCInterfaceType>(PT->getPointeeType());
533 if (!OI) return 0;
534
535 return OI ? OI->getDecl() : 0;
536 }
537
538 iterator end() { return M.end(); }
539
540 RetainSummary*& operator[](ObjCMessageExpr* ME) {
541
542 Selector S = ME->getSelector();
543
544 if (Expr* Receiver = ME->getReceiver()) {
545 ObjCInterfaceDecl* OD = getReceiverDecl(Receiver);
546 return OD ? M[ObjCSummaryKey(OD->getIdentifier(), S)] : M[S];
547 }
548
549 return M[ObjCSummaryKey(ME->getClassName(), S)];
550 }
551
552 RetainSummary*& operator[](ObjCSummaryKey K) {
553 return M[K];
554 }
555
556 RetainSummary*& operator[](Selector S) {
557 return M[ ObjCSummaryKey(S) ];
558 }
559};
560} // end anonymous namespace
561
562//===----------------------------------------------------------------------===//
563// Data structures for managing collections of summaries.
564//===----------------------------------------------------------------------===//
565
566namespace {
567class VISIBILITY_HIDDEN RetainSummaryManager {
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000568
569 //==-----------------------------------------------------------------==//
570 // Typedefs.
571 //==-----------------------------------------------------------------==//
Ted Kremeneka7338b42008-03-11 06:39:11 +0000572
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000573 typedef llvm::DenseMap<FunctionDecl*, RetainSummary*>
574 FuncSummariesTy;
575
Ted Kremenek84f010c2008-06-23 23:30:29 +0000576 typedef ObjCSummaryCache ObjCMethodSummariesTy;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000577
578 //==-----------------------------------------------------------------==//
579 // Data.
580 //==-----------------------------------------------------------------==//
581
Ted Kremenek272aa852008-06-25 21:21:56 +0000582 /// Ctx - The ASTContext object for the analyzed ASTs.
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000583 ASTContext& Ctx;
Ted Kremeneke44927e2008-07-01 17:21:27 +0000584
Ted Kremenekede40b72008-07-09 18:11:16 +0000585 /// CFDictionaryCreateII - An IdentifierInfo* representing the indentifier
586 /// "CFDictionaryCreate".
587 IdentifierInfo* CFDictionaryCreateII;
588
Ted Kremenek272aa852008-06-25 21:21:56 +0000589 /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000590 const bool GCEnabled;
Ted Kremenekee649082009-05-04 04:30:18 +0000591
Ted Kremenek272aa852008-06-25 21:21:56 +0000592 /// FuncSummaries - A map from FunctionDecls to summaries.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000593 FuncSummariesTy FuncSummaries;
594
Ted Kremenek272aa852008-06-25 21:21:56 +0000595 /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
596 /// to summaries.
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000597 ObjCMethodSummariesTy ObjCClassMethodSummaries;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000598
Ted Kremenek272aa852008-06-25 21:21:56 +0000599 /// ObjCMethodSummaries - A map from selectors to summaries.
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000600 ObjCMethodSummariesTy ObjCMethodSummaries;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000601
Ted Kremenek272aa852008-06-25 21:21:56 +0000602 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
603 /// and all other data used by the checker.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000604 llvm::BumpPtrAllocator BPAlloc;
605
Ted Kremeneka56ae162009-05-03 05:20:50 +0000606 /// AF - A factory for ArgEffects objects.
607 ArgEffects::Factory AF;
608
Ted Kremenek272aa852008-06-25 21:21:56 +0000609 /// ScratchArgs - A holding buffer for construct ArgEffects.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000610 ArgEffects ScratchArgs;
611
Ted Kremenek5535e5e2009-05-07 23:40:42 +0000612 /// ObjCAllocRetE - Default return effect for methods returning Objective-C
613 /// objects.
614 RetEffect ObjCAllocRetE;
615
Ted Kremenek286e9852009-05-04 04:57:00 +0000616 RetainSummary DefaultSummary;
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000617 RetainSummary* StopSummary;
618
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000619 //==-----------------------------------------------------------------==//
620 // Methods.
621 //==-----------------------------------------------------------------==//
622
Ted Kremenek272aa852008-06-25 21:21:56 +0000623 /// getArgEffects - Returns a persistent ArgEffects object based on the
624 /// data in ScratchArgs.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000625 ArgEffects getArgEffects();
Ted Kremeneka7338b42008-03-11 06:39:11 +0000626
Ted Kremenek562c1302008-05-05 16:51:50 +0000627 enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000628
629public:
Ted Kremenek2f226732009-05-04 05:31:22 +0000630 RetainSummary *getDefaultSummary() {
631 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
632 return new (Summ) RetainSummary(DefaultSummary);
633 }
Ted Kremenek286e9852009-05-04 04:57:00 +0000634
Ted Kremenek064ef322009-02-23 16:51:39 +0000635 RetainSummary* getUnarySummary(const FunctionType* FT, UnaryFuncKind func);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000636
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000637 RetainSummary* getCFSummaryCreateRule(FunctionDecl* FD);
638 RetainSummary* getCFSummaryGetRule(FunctionDecl* FD);
Ted Kremenek17144e82009-01-12 21:45:02 +0000639 RetainSummary* getCFCreateGetRuleSummary(FunctionDecl* FD, const char* FName);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000640
Ted Kremeneka56ae162009-05-03 05:20:50 +0000641 RetainSummary* getPersistentSummary(ArgEffects AE, RetEffect RetEff,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000642 ArgEffect ReceiverEff = DoNothing,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000643 ArgEffect DefaultEff = MayEscape,
644 bool isEndPath = false);
Ted Kremenek45d0b502008-10-29 04:07:07 +0000645
Ted Kremenek266d8b62008-05-06 02:26:56 +0000646 RetainSummary* getPersistentSummary(RetEffect RE,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000647 ArgEffect ReceiverEff = DoNothing,
Ted Kremeneka3f30dd2008-05-22 17:31:13 +0000648 ArgEffect DefaultEff = MayEscape) {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000649 return getPersistentSummary(getArgEffects(), RE, ReceiverEff, DefaultEff);
Ted Kremenek0e344d42008-05-06 00:30:21 +0000650 }
Ted Kremenek42ea0322008-05-05 23:55:01 +0000651
Ted Kremeneka821b792009-04-29 05:04:30 +0000652 RetainSummary *getPersistentStopSummary() {
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000653 if (StopSummary)
654 return StopSummary;
655
656 StopSummary = getPersistentSummary(RetEffect::MakeNoRet(),
657 StopTracking, StopTracking);
Ted Kremenek45d0b502008-10-29 04:07:07 +0000658
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000659 return StopSummary;
Ted Kremenekbcaff792008-05-06 15:44:25 +0000660 }
Ted Kremenek926abf22008-05-06 04:20:12 +0000661
Ted Kremeneka821b792009-04-29 05:04:30 +0000662 RetainSummary *getInitMethodSummary(QualType RetTy);
Ted Kremenek42ea0322008-05-05 23:55:01 +0000663
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000664 void InitializeClassMethodSummaries();
665 void InitializeMethodSummaries();
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000666
Ted Kremenek9b42e062009-05-03 04:42:10 +0000667 bool isTrackedObjCObjectType(QualType T);
Ted Kremeneka9cdbc32009-05-03 06:08:32 +0000668 bool isTrackedCFObjectType(QualType T);
Ted Kremenek35920ed2009-01-07 00:39:56 +0000669
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000670private:
671
Ted Kremenekf2717b02008-07-18 17:24:20 +0000672 void addClsMethSummary(IdentifierInfo* ClsII, Selector S,
673 RetainSummary* Summ) {
674 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
675 }
676
Ted Kremenek272aa852008-06-25 21:21:56 +0000677 void addNSObjectClsMethSummary(Selector S, RetainSummary *Summ) {
678 ObjCClassMethodSummaries[S] = Summ;
679 }
680
681 void addNSObjectMethSummary(Selector S, RetainSummary *Summ) {
682 ObjCMethodSummaries[S] = Summ;
683 }
Ted Kremenekfbf2dc52009-03-04 23:30:42 +0000684
685 void addClassMethSummary(const char* Cls, const char* nullaryName,
686 RetainSummary *Summ) {
687 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
688 Selector S = GetNullarySelector(nullaryName, Ctx);
689 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
690 }
Ted Kremenek272aa852008-06-25 21:21:56 +0000691
Ted Kremenek1b4b6562009-02-25 02:54:57 +0000692 void addInstMethSummary(const char* Cls, const char* nullaryName,
693 RetainSummary *Summ) {
694 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
695 Selector S = GetNullarySelector(nullaryName, Ctx);
696 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
697 }
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000698
699 Selector generateSelector(va_list argp) {
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000700 llvm::SmallVector<IdentifierInfo*, 10> II;
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000701
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000702 while (const char* s = va_arg(argp, const char*))
703 II.push_back(&Ctx.Idents.get(s));
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000704
705 return Ctx.Selectors.getSelector(II.size(), &II[0]);
706 }
707
708 void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy& Summaries,
709 RetainSummary* Summ, va_list argp) {
710 Selector S = generateSelector(argp);
711 Summaries[ObjCSummaryKey(ClsII, S)] = Summ;
Ted Kremenekf2717b02008-07-18 17:24:20 +0000712 }
Ted Kremenek45642a42008-08-12 18:48:50 +0000713
714 void addInstMethSummary(const char* Cls, RetainSummary* Summ, ...) {
715 va_list argp;
716 va_start(argp, Summ);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000717 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Ted Kremenek45642a42008-08-12 18:48:50 +0000718 va_end(argp);
719 }
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000720
721 void addClsMethSummary(const char* Cls, RetainSummary* Summ, ...) {
722 va_list argp;
723 va_start(argp, Summ);
724 addMethodSummary(&Ctx.Idents.get(Cls),ObjCClassMethodSummaries, Summ, argp);
725 va_end(argp);
726 }
727
728 void addClsMethSummary(IdentifierInfo *II, RetainSummary* Summ, ...) {
729 va_list argp;
730 va_start(argp, Summ);
731 addMethodSummary(II, ObjCClassMethodSummaries, Summ, argp);
732 va_end(argp);
733 }
734
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000735 void addPanicSummary(const char* Cls, ...) {
Ted Kremeneka56ae162009-05-03 05:20:50 +0000736 RetainSummary* Summ = getPersistentSummary(AF.GetEmptyMap(),
737 RetEffect::MakeNoRet(),
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000738 DoNothing, DoNothing, true);
739 va_list argp;
740 va_start (argp, Cls);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000741 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000742 va_end(argp);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000743 }
Ted Kremenekf2717b02008-07-18 17:24:20 +0000744
Ted Kremeneka7338b42008-03-11 06:39:11 +0000745public:
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000746
747 RetainSummaryManager(ASTContext& ctx, bool gcenabled)
Ted Kremeneke44927e2008-07-01 17:21:27 +0000748 : Ctx(ctx),
Ted Kremenekede40b72008-07-09 18:11:16 +0000749 CFDictionaryCreateII(&ctx.Idents.get("CFDictionaryCreate")),
Ted Kremeneka56ae162009-05-03 05:20:50 +0000750 GCEnabled(gcenabled), AF(BPAlloc), ScratchArgs(AF.GetEmptyMap()),
Ted Kremenek5535e5e2009-05-07 23:40:42 +0000751 ObjCAllocRetE(gcenabled ? RetEffect::MakeGCNotOwned()
752 : RetEffect::MakeOwned(RetEffect::ObjC, true)),
Ted Kremenek286e9852009-05-04 04:57:00 +0000753 DefaultSummary(AF.GetEmptyMap() /* per-argument effects (none) */,
754 RetEffect::MakeNoRet() /* return effect */,
755 DoNothing /* receiver effect */,
756 MayEscape /* default argument effect */),
Ted Kremeneka56ae162009-05-03 05:20:50 +0000757 StopSummary(0) {
Ted Kremenek272aa852008-06-25 21:21:56 +0000758
759 InitializeClassMethodSummaries();
760 InitializeMethodSummaries();
761 }
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000762
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000763 ~RetainSummaryManager();
Ted Kremeneka7338b42008-03-11 06:39:11 +0000764
Ted Kremenekd13c1872008-06-24 03:56:45 +0000765 RetainSummary* getSummary(FunctionDecl* FD);
Ted Kremeneka821b792009-04-29 05:04:30 +0000766
Ted Kremenek314b1952009-04-29 23:03:22 +0000767 RetainSummary* getInstanceMethodSummary(ObjCMessageExpr* ME,
768 const ObjCInterfaceDecl* ID) {
Ted Kremenek04e00302009-04-29 17:09:14 +0000769 return getInstanceMethodSummary(ME->getSelector(), ME->getClassName(),
Ted Kremeneka821b792009-04-29 05:04:30 +0000770 ID, ME->getMethodDecl(), ME->getType());
771 }
772
Ted Kremenek04e00302009-04-29 17:09:14 +0000773 RetainSummary* getInstanceMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +0000774 const ObjCInterfaceDecl* ID,
775 const ObjCMethodDecl *MD,
776 QualType RetTy);
Ted Kremenek578498a2009-04-29 00:42:39 +0000777
778 RetainSummary *getClassMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +0000779 const ObjCInterfaceDecl *ID,
780 const ObjCMethodDecl *MD,
781 QualType RetTy);
Ted Kremenek578498a2009-04-29 00:42:39 +0000782
783 RetainSummary *getClassMethodSummary(ObjCMessageExpr *ME) {
784 return getClassMethodSummary(ME->getSelector(), ME->getClassName(),
785 ME->getClassInfo().first,
786 ME->getMethodDecl(), ME->getType());
787 }
Ted Kremenek91b89a42009-04-29 17:17:48 +0000788
789 /// getMethodSummary - This version of getMethodSummary is used to query
790 /// the summary for the current method being analyzed.
Ted Kremenek314b1952009-04-29 23:03:22 +0000791 RetainSummary *getMethodSummary(const ObjCMethodDecl *MD) {
792 // FIXME: Eventually this should be unneeded.
Ted Kremenek314b1952009-04-29 23:03:22 +0000793 const ObjCInterfaceDecl *ID = MD->getClassInterface();
Ted Kremenek1447cc92009-04-30 05:41:14 +0000794 Selector S = MD->getSelector();
Ted Kremenek91b89a42009-04-29 17:17:48 +0000795 IdentifierInfo *ClsName = ID->getIdentifier();
796 QualType ResultTy = MD->getResultType();
797
Ted Kremenek81eb4642009-04-30 05:47:23 +0000798 // Resolve the method decl last.
799 if (const ObjCMethodDecl *InterfaceMD =
800 ResolveToInterfaceMethodDecl(MD, Ctx))
801 MD = InterfaceMD;
Ted Kremenek1447cc92009-04-30 05:41:14 +0000802
Ted Kremenek91b89a42009-04-29 17:17:48 +0000803 if (MD->isInstanceMethod())
804 return getInstanceMethodSummary(S, ClsName, ID, MD, ResultTy);
805 else
806 return getClassMethodSummary(S, ClsName, ID, MD, ResultTy);
807 }
Ted Kremenek578498a2009-04-29 00:42:39 +0000808
Ted Kremenek314b1952009-04-29 23:03:22 +0000809 RetainSummary* getCommonMethodSummary(const ObjCMethodDecl* MD,
810 Selector S, QualType RetTy);
811
Ted Kremeneka4c8afc2009-05-09 02:58:13 +0000812 void updateSummaryFromAnnotations(RetainSummary &Summ,
813 const ObjCMethodDecl *MD);
814
815 void updateSummaryFromAnnotations(RetainSummary &Summ,
816 const FunctionDecl *FD);
817
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000818 bool isGCEnabled() const { return GCEnabled; }
Ted Kremenek2f226732009-05-04 05:31:22 +0000819
820 RetainSummary *copySummary(RetainSummary *OldSumm) {
821 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
822 new (Summ) RetainSummary(*OldSumm);
823 return Summ;
824 }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000825};
826
827} // end anonymous namespace
828
829//===----------------------------------------------------------------------===//
830// Implementation of checker data structures.
831//===----------------------------------------------------------------------===//
832
Ted Kremeneka56ae162009-05-03 05:20:50 +0000833RetainSummaryManager::~RetainSummaryManager() {}
Ted Kremeneka7338b42008-03-11 06:39:11 +0000834
Ted Kremeneka56ae162009-05-03 05:20:50 +0000835ArgEffects RetainSummaryManager::getArgEffects() {
836 ArgEffects AE = ScratchArgs;
837 ScratchArgs = AF.GetEmptyMap();
838 return AE;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000839}
840
Ted Kremenek266d8b62008-05-06 02:26:56 +0000841RetainSummary*
Ted Kremeneka56ae162009-05-03 05:20:50 +0000842RetainSummaryManager::getPersistentSummary(ArgEffects AE, RetEffect RetEff,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000843 ArgEffect ReceiverEff,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000844 ArgEffect DefaultEff,
Ted Kremenekee649082009-05-04 04:30:18 +0000845 bool isEndPath) {
Ted Kremenekae855d42008-04-24 17:22:33 +0000846 // Create the summary and return it.
Ted Kremenekee649082009-05-04 04:30:18 +0000847 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
Ted Kremenekf2717b02008-07-18 17:24:20 +0000848 new (Summ) RetainSummary(AE, RetEff, DefaultEff, ReceiverEff, isEndPath);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000849 return Summ;
850}
851
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000852//===----------------------------------------------------------------------===//
Ted Kremenek35920ed2009-01-07 00:39:56 +0000853// Predicates.
854//===----------------------------------------------------------------------===//
855
Ted Kremenek9b42e062009-05-03 04:42:10 +0000856bool RetainSummaryManager::isTrackedObjCObjectType(QualType Ty) {
Ted Kremenek0d813552009-04-23 22:11:07 +0000857 if (!Ctx.isObjCObjectPointerType(Ty))
Ted Kremenek35920ed2009-01-07 00:39:56 +0000858 return false;
859
Ted Kremenek0d813552009-04-23 22:11:07 +0000860 // We assume that id<..>, id, and "Class" all represent tracked objects.
861 const PointerType *PT = Ty->getAsPointerType();
862 if (PT == 0)
863 return true;
864
865 const ObjCInterfaceType *OT = PT->getPointeeType()->getAsObjCInterfaceType();
Ted Kremenek35920ed2009-01-07 00:39:56 +0000866
867 // We assume that id<..>, id, and "Class" all represent tracked objects.
868 if (!OT)
869 return true;
Ted Kremenek0d813552009-04-23 22:11:07 +0000870
871 // Does the interface subclass NSObject?
Ted Kremenek35920ed2009-01-07 00:39:56 +0000872 // FIXME: We can memoize here if this gets too expensive.
873 IdentifierInfo* NSObjectII = &Ctx.Idents.get("NSObject");
874 ObjCInterfaceDecl* ID = OT->getDecl();
875
876 for ( ; ID ; ID = ID->getSuperClass())
877 if (ID->getIdentifier() == NSObjectII)
878 return true;
879
880 return false;
881}
882
Ted Kremeneka9cdbc32009-05-03 06:08:32 +0000883bool RetainSummaryManager::isTrackedCFObjectType(QualType T) {
884 return isRefType(T, "CF") || // Core Foundation.
885 isRefType(T, "CG") || // Core Graphics.
886 isRefType(T, "DADisk") || // Disk Arbitration API.
887 isRefType(T, "DADissenter") ||
888 isRefType(T, "DASessionRef");
889}
890
Ted Kremenek35920ed2009-01-07 00:39:56 +0000891//===----------------------------------------------------------------------===//
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000892// Summary creation for functions (largely uses of Core Foundation).
893//===----------------------------------------------------------------------===//
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000894
Ted Kremenek17144e82009-01-12 21:45:02 +0000895static bool isRetain(FunctionDecl* FD, const char* FName) {
896 const char* loc = strstr(FName, "Retain");
897 return loc && loc[sizeof("Retain")-1] == '\0';
898}
899
900static bool isRelease(FunctionDecl* FD, const char* FName) {
901 const char* loc = strstr(FName, "Release");
902 return loc && loc[sizeof("Release")-1] == '\0';
903}
904
Ted Kremenekd13c1872008-06-24 03:56:45 +0000905RetainSummary* RetainSummaryManager::getSummary(FunctionDecl* FD) {
Ted Kremenekae855d42008-04-24 17:22:33 +0000906 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000907 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000908 if (I != FuncSummaries.end())
Ted Kremenekae855d42008-04-24 17:22:33 +0000909 return I->second;
910
Ted Kremenek64cddf12009-05-04 15:34:07 +0000911 // No summary? Generate one.
Ted Kremenek17144e82009-01-12 21:45:02 +0000912 RetainSummary *S = 0;
Ted Kremenek562c1302008-05-05 16:51:50 +0000913
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000914 do {
Ted Kremenek17144e82009-01-12 21:45:02 +0000915 // We generate "stop" summaries for implicitly defined functions.
916 if (FD->isImplicit()) {
917 S = getPersistentStopSummary();
918 break;
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000919 }
Ted Kremenekeafcc2f2008-11-04 00:36:12 +0000920
Ted Kremenek064ef322009-02-23 16:51:39 +0000921 // [PR 3337] Use 'getAsFunctionType' to strip away any typedefs on the
Ted Kremenekc239b9c2009-01-16 18:40:33 +0000922 // function's type.
Ted Kremenek064ef322009-02-23 16:51:39 +0000923 const FunctionType* FT = FD->getType()->getAsFunctionType();
Ted Kremenek17144e82009-01-12 21:45:02 +0000924 const char* FName = FD->getIdentifier()->getName();
925
Ted Kremenek38c6f022009-03-05 22:11:14 +0000926 // Strip away preceding '_'. Doing this here will effect all the checks
927 // down below.
928 while (*FName == '_') ++FName;
929
Ted Kremenek17144e82009-01-12 21:45:02 +0000930 // Inspect the result type.
931 QualType RetTy = FT->getResultType();
932
933 // FIXME: This should all be refactored into a chain of "summary lookup"
934 // filters.
935 if (strcmp(FName, "IOServiceGetMatchingServices") == 0) {
936 // FIXES: <rdar://problem/6326900>
937 // This should be addressed using a API table. This strcmp is also
938 // a little gross, but there is no need to super optimize here.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000939 assert (ScratchArgs.isEmpty());
940 ScratchArgs = AF.Add(ScratchArgs, 1, DecRef);
Ted Kremenek17144e82009-01-12 21:45:02 +0000941 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
942 break;
Ted Kremenekcfc50c72008-10-22 20:54:52 +0000943 }
Ted Kremenek7b88c892009-03-17 22:43:44 +0000944
945 // Enable this code once the semantics of NSDeallocateObject are resolved
946 // for GC. <rdar://problem/6619988>
947#if 0
948 // Handle: NSDeallocateObject(id anObject);
949 // This method does allow 'nil' (although we don't check it now).
950 if (strcmp(FName, "NSDeallocateObject") == 0) {
951 return RetTy == Ctx.VoidTy
952 ? getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, Dealloc)
953 : getPersistentStopSummary();
954 }
955#endif
Ted Kremenek17144e82009-01-12 21:45:02 +0000956
957 // Handle: id NSMakeCollectable(CFTypeRef)
958 if (strcmp(FName, "NSMakeCollectable") == 0) {
959 S = (RetTy == Ctx.getObjCIdType())
960 ? getUnarySummary(FT, cfmakecollectable)
961 : getPersistentStopSummary();
962
963 break;
964 }
965
966 if (RetTy->isPointerType()) {
967 // For CoreFoundation ('CF') types.
968 if (isRefType(RetTy, "CF", &Ctx, FName)) {
969 if (isRetain(FD, FName))
970 S = getUnarySummary(FT, cfretain);
971 else if (strstr(FName, "MakeCollectable"))
972 S = getUnarySummary(FT, cfmakecollectable);
973 else
974 S = getCFCreateGetRuleSummary(FD, FName);
975
976 break;
977 }
978
979 // For CoreGraphics ('CG') types.
980 if (isRefType(RetTy, "CG", &Ctx, FName)) {
981 if (isRetain(FD, FName))
982 S = getUnarySummary(FT, cfretain);
983 else
984 S = getCFCreateGetRuleSummary(FD, FName);
985
986 break;
987 }
988
989 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
990 if (isRefType(RetTy, "DADisk") ||
991 isRefType(RetTy, "DADissenter") ||
992 isRefType(RetTy, "DASessionRef")) {
993 S = getCFCreateGetRuleSummary(FD, FName);
994 break;
995 }
996
997 break;
998 }
999
1000 // Check for release functions, the only kind of functions that we care
1001 // about that don't return a pointer type.
1002 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
Ted Kremenek38c6f022009-03-05 22:11:14 +00001003 // Test for 'CGCF'.
1004 if (FName[1] == 'G' && FName[2] == 'C' && FName[3] == 'F')
1005 FName += 4;
1006 else
1007 FName += 2;
1008
1009 if (isRelease(FD, FName))
Ted Kremenek17144e82009-01-12 21:45:02 +00001010 S = getUnarySummary(FT, cfrelease);
1011 else {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001012 assert (ScratchArgs.isEmpty());
Ted Kremenek7b293682009-01-29 22:45:13 +00001013 // Remaining CoreFoundation and CoreGraphics functions.
1014 // We use to assume that they all strictly followed the ownership idiom
1015 // and that ownership cannot be transferred. While this is technically
1016 // correct, many methods allow a tracked object to escape. For example:
1017 //
1018 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
1019 // CFDictionaryAddValue(y, key, x);
1020 // CFRelease(x);
1021 // ... it is okay to use 'x' since 'y' has a reference to it
1022 //
1023 // We handle this and similar cases with the follow heuristic. If the
1024 // function name contains "InsertValue", "SetValue" or "AddValue" then
1025 // we assume that arguments may "escape."
1026 //
1027 ArgEffect E = (CStrInCStrNoCase(FName, "InsertValue") ||
1028 CStrInCStrNoCase(FName, "AddValue") ||
Ted Kremenekcf071252009-02-05 22:34:53 +00001029 CStrInCStrNoCase(FName, "SetValue") ||
1030 CStrInCStrNoCase(FName, "AppendValue"))
Ted Kremenek7b293682009-01-29 22:45:13 +00001031 ? MayEscape : DoNothing;
1032
1033 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek17144e82009-01-12 21:45:02 +00001034 }
1035 }
Ted Kremenek4c5378c2008-07-15 16:50:12 +00001036 }
1037 while (0);
Ted Kremenek2f226732009-05-04 05:31:22 +00001038
1039 if (!S)
1040 S = getDefaultSummary();
Ted Kremenekae855d42008-04-24 17:22:33 +00001041
Ted Kremeneka4c8afc2009-05-09 02:58:13 +00001042 // Annotations override defaults.
1043 assert(S);
1044 updateSummaryFromAnnotations(*S, FD);
1045
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001046 FuncSummaries[FD] = S;
Ted Kremenek562c1302008-05-05 16:51:50 +00001047 return S;
Ted Kremenek827f93b2008-03-06 00:08:09 +00001048}
1049
Ted Kremenek4c5378c2008-07-15 16:50:12 +00001050RetainSummary*
1051RetainSummaryManager::getCFCreateGetRuleSummary(FunctionDecl* FD,
1052 const char* FName) {
1053
Ted Kremenek562c1302008-05-05 16:51:50 +00001054 if (strstr(FName, "Create") || strstr(FName, "Copy"))
1055 return getCFSummaryCreateRule(FD);
Ted Kremenek4c5378c2008-07-15 16:50:12 +00001056
Ted Kremenek562c1302008-05-05 16:51:50 +00001057 if (strstr(FName, "Get"))
1058 return getCFSummaryGetRule(FD);
1059
Ted Kremenek286e9852009-05-04 04:57:00 +00001060 return getDefaultSummary();
Ted Kremenek562c1302008-05-05 16:51:50 +00001061}
1062
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001063RetainSummary*
Ted Kremenek064ef322009-02-23 16:51:39 +00001064RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1065 UnaryFuncKind func) {
1066
Ted Kremenek17144e82009-01-12 21:45:02 +00001067 // Sanity check that this is *really* a unary function. This can
1068 // happen if people do weird things.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001069 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
Ted Kremenek17144e82009-01-12 21:45:02 +00001070 if (!FTP || FTP->getNumArgs() != 1)
1071 return getPersistentStopSummary();
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001072
Ted Kremeneka56ae162009-05-03 05:20:50 +00001073 assert (ScratchArgs.isEmpty());
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001074
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001075 switch (func) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001076 case cfretain: {
1077 ScratchArgs = AF.Add(ScratchArgs, 0, IncRef);
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001078 return getPersistentSummary(RetEffect::MakeAlias(0),
1079 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001080 }
1081
1082 case cfrelease: {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001083 ScratchArgs = AF.Add(ScratchArgs, 0, DecRef);
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001084 return getPersistentSummary(RetEffect::MakeNoRet(),
1085 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001086 }
1087
1088 case cfmakecollectable: {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001089 ScratchArgs = AF.Add(ScratchArgs, 0, MakeCollectable);
Ted Kremenek2126bef2009-02-18 21:57:45 +00001090 return getPersistentSummary(RetEffect::MakeAlias(0),DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001091 }
1092
1093 default:
Ted Kremenek562c1302008-05-05 16:51:50 +00001094 assert (false && "Not a supported unary function.");
Ted Kremenek286e9852009-05-04 04:57:00 +00001095 return getDefaultSummary();
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00001096 }
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001097}
1098
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001099RetainSummary* RetainSummaryManager::getCFSummaryCreateRule(FunctionDecl* FD) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001100 assert (ScratchArgs.isEmpty());
Ted Kremenekede40b72008-07-09 18:11:16 +00001101
1102 if (FD->getIdentifier() == CFDictionaryCreateII) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001103 ScratchArgs = AF.Add(ScratchArgs, 1, DoNothingByRef);
1104 ScratchArgs = AF.Add(ScratchArgs, 2, DoNothingByRef);
Ted Kremenekede40b72008-07-09 18:11:16 +00001105 }
1106
Ted Kremenek68621b92009-01-28 05:56:51 +00001107 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001108}
1109
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001110RetainSummary* RetainSummaryManager::getCFSummaryGetRule(FunctionDecl* FD) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001111 assert (ScratchArgs.isEmpty());
Ted Kremenek68621b92009-01-28 05:56:51 +00001112 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1113 DoNothing, DoNothing);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001114}
1115
Ted Kremeneka7338b42008-03-11 06:39:11 +00001116//===----------------------------------------------------------------------===//
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001117// Summary creation for Selectors.
1118//===----------------------------------------------------------------------===//
1119
Ted Kremenekbcaff792008-05-06 15:44:25 +00001120RetainSummary*
Ted Kremeneka821b792009-04-29 05:04:30 +00001121RetainSummaryManager::getInitMethodSummary(QualType RetTy) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001122 assert(ScratchArgs.isEmpty());
Ted Kremenek42ea0322008-05-05 23:55:01 +00001123
Ted Kremenek802cfc72009-02-20 00:05:35 +00001124 // 'init' methods only return an alias if the return type is a location type.
Ted Kremeneka821b792009-04-29 05:04:30 +00001125 return getPersistentSummary(Loc::IsLocType(RetTy)
1126 ? RetEffect::MakeReceiverAlias()
Ted Kremenek03d242e2009-05-05 18:44:20 +00001127 : RetEffect::MakeNoRet());
Ted Kremenek42ea0322008-05-05 23:55:01 +00001128}
Ted Kremeneka4c8afc2009-05-09 02:58:13 +00001129
1130void
1131RetainSummaryManager::updateSummaryFromAnnotations(RetainSummary &Summ,
1132 const FunctionDecl *FD) {
1133 if (!FD)
1134 return;
1135
1136 // Determine if there is a special return effect for this method.
1137 if (isTrackedObjCObjectType(FD->getResultType())) {
1138 if (FD->getAttr<NSReturnsRetainedAttr>()) {
1139 Summ.setRetEffect(ObjCAllocRetE);
1140 }
1141 else if (FD->getAttr<CFReturnsRetainedAttr>()) {
1142 Summ.setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
1143 }
1144 }
1145}
1146
1147void
1148RetainSummaryManager::updateSummaryFromAnnotations(RetainSummary &Summ,
1149 const ObjCMethodDecl *MD) {
1150 if (!MD)
1151 return;
1152
1153 // Determine if there is a special return effect for this method.
1154 if (isTrackedObjCObjectType(MD->getResultType())) {
1155 if (MD->getAttr<NSReturnsRetainedAttr>()) {
1156 Summ.setRetEffect(ObjCAllocRetE);
1157 }
1158 else if (MD->getAttr<CFReturnsRetainedAttr>()) {
1159 Summ.setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
1160 }
1161 }
1162}
1163
Ted Kremenekbcaff792008-05-06 15:44:25 +00001164RetainSummary*
Ted Kremenek314b1952009-04-29 23:03:22 +00001165RetainSummaryManager::getCommonMethodSummary(const ObjCMethodDecl* MD,
1166 Selector S, QualType RetTy) {
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001167
Ted Kremenek578498a2009-04-29 00:42:39 +00001168 if (MD) {
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001169 // Scan the method decl for 'void*' arguments. These should be treated
1170 // as 'StopTracking' because they are often used with delegates.
1171 // Delegates are a frequent form of false positives with the retain
1172 // count checker.
1173 unsigned i = 0;
1174 for (ObjCMethodDecl::param_iterator I = MD->param_begin(),
1175 E = MD->param_end(); I != E; ++I, ++i)
1176 if (ParmVarDecl *PD = *I) {
1177 QualType Ty = Ctx.getCanonicalType(PD->getType());
1178 if (Ty.getUnqualifiedType() == Ctx.VoidPtrTy)
Ted Kremeneka56ae162009-05-03 05:20:50 +00001179 ScratchArgs = AF.Add(ScratchArgs, i, StopTracking);
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001180 }
1181 }
1182
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001183 // Any special effect for the receiver?
1184 ArgEffect ReceiverEff = DoNothing;
1185
1186 // If one of the arguments in the selector has the keyword 'delegate' we
1187 // should stop tracking the reference count for the receiver. This is
1188 // because the reference count is quite possibly handled by a delegate
1189 // method.
1190 if (S.isKeywordSelector()) {
1191 const std::string &str = S.getAsString();
1192 assert(!str.empty());
1193 if (CStrInCStrNoCase(&str[0], "delegate:")) ReceiverEff = StopTracking;
1194 }
1195
Ted Kremenek174a0772009-04-23 23:08:22 +00001196 // Look for methods that return an owned object.
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001197 if (isTrackedObjCObjectType(RetTy)) {
1198 // EXPERIMENTAL: Assume the Cocoa conventions for all objects returned
1199 // by instance methods.
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001200 RetEffect E =
1201 followsFundamentalRule(S.getIdentifierInfoForSlot(0)->getName())
Ted Kremenek5535e5e2009-05-07 23:40:42 +00001202 ? ObjCAllocRetE : RetEffect::MakeNotOwned(RetEffect::ObjC);
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001203
1204 return getPersistentSummary(E, ReceiverEff, MayEscape);
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001205 }
Ted Kremenek174a0772009-04-23 23:08:22 +00001206
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001207 // Look for methods that return an owned core foundation object.
1208 if (isTrackedCFObjectType(RetTy)) {
1209 RetEffect E =
1210 followsFundamentalRule(S.getIdentifierInfoForSlot(0)->getName())
1211 ? RetEffect::MakeOwned(RetEffect::CF, true)
1212 : RetEffect::MakeNotOwned(RetEffect::CF);
1213
1214 return getPersistentSummary(E, ReceiverEff, MayEscape);
1215 }
Ted Kremenek174a0772009-04-23 23:08:22 +00001216
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001217 if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing)
Ted Kremenek286e9852009-05-04 04:57:00 +00001218 return getDefaultSummary();
Ted Kremenek174a0772009-04-23 23:08:22 +00001219
Ted Kremenek2f226732009-05-04 05:31:22 +00001220 return getPersistentSummary(RetEffect::MakeNoRet(), ReceiverEff, MayEscape);
Ted Kremenek174a0772009-04-23 23:08:22 +00001221}
1222
1223RetainSummary*
Ted Kremenek04e00302009-04-29 17:09:14 +00001224RetainSummaryManager::getInstanceMethodSummary(Selector S,
1225 IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +00001226 const ObjCInterfaceDecl* ID,
1227 const ObjCMethodDecl *MD,
Ted Kremenek04e00302009-04-29 17:09:14 +00001228 QualType RetTy) {
Ted Kremenekbcaff792008-05-06 15:44:25 +00001229
Ted Kremeneka821b792009-04-29 05:04:30 +00001230 // Look up a summary in our summary cache.
1231 ObjCMethodSummariesTy::iterator I = ObjCMethodSummaries.find(ID, ClsName, S);
Ted Kremenek42ea0322008-05-05 23:55:01 +00001232
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001233 if (I != ObjCMethodSummaries.end())
Ted Kremenek42ea0322008-05-05 23:55:01 +00001234 return I->second;
Ted Kremenek42ea0322008-05-05 23:55:01 +00001235
Ted Kremeneka56ae162009-05-03 05:20:50 +00001236 assert(ScratchArgs.isEmpty());
Ted Kremenek2f226732009-05-04 05:31:22 +00001237 RetainSummary *Summ = 0;
Ted Kremenek1d3d9562008-05-06 06:09:09 +00001238
Ted Kremenek2f226732009-05-04 05:31:22 +00001239 // "initXXX": pass-through for receiver.
1240 if (deriveNamingConvention(S.getIdentifierInfoForSlot(0)->getName())
1241 == InitRule)
1242 Summ = getInitMethodSummary(RetTy);
1243 else
1244 Summ = getCommonMethodSummary(MD, S, RetTy);
1245
Ted Kremeneka4c8afc2009-05-09 02:58:13 +00001246 // Annotations override defaults.
1247 updateSummaryFromAnnotations(*Summ, MD);
1248
Ted Kremenek2f226732009-05-04 05:31:22 +00001249 // Memoize the summary.
Ted Kremeneka821b792009-04-29 05:04:30 +00001250 ObjCMethodSummaries[ObjCSummaryKey(ClsName, S)] = Summ;
Ted Kremeneke4158502009-04-23 19:11:35 +00001251 return Summ;
Ted Kremenek42ea0322008-05-05 23:55:01 +00001252}
1253
Ted Kremeneka7722b72008-05-06 21:26:51 +00001254RetainSummary*
Ted Kremenek578498a2009-04-29 00:42:39 +00001255RetainSummaryManager::getClassMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +00001256 const ObjCInterfaceDecl *ID,
1257 const ObjCMethodDecl *MD,
1258 QualType RetTy) {
Ted Kremenekccbe79a2009-04-24 17:50:11 +00001259
Ted Kremenek578498a2009-04-29 00:42:39 +00001260 assert(ClsName && "Class name must be specified.");
Ted Kremeneka821b792009-04-29 05:04:30 +00001261 ObjCMethodSummariesTy::iterator I =
1262 ObjCClassMethodSummaries.find(ID, ClsName, S);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001263
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001264 if (I != ObjCClassMethodSummaries.end())
Ted Kremeneka7722b72008-05-06 21:26:51 +00001265 return I->second;
Ted Kremenek2f226732009-05-04 05:31:22 +00001266
1267 RetainSummary *Summ = getCommonMethodSummary(MD, S, RetTy);
Ted Kremeneka4c8afc2009-05-09 02:58:13 +00001268
1269 // Annotations override defaults.
1270 updateSummaryFromAnnotations(*Summ, MD);
Ted Kremenek2f226732009-05-04 05:31:22 +00001271
Ted Kremenek2f226732009-05-04 05:31:22 +00001272 // Memoize the summary.
Ted Kremenek578498a2009-04-29 00:42:39 +00001273 ObjCClassMethodSummaries[ObjCSummaryKey(ClsName, S)] = Summ;
Ted Kremeneke4158502009-04-23 19:11:35 +00001274 return Summ;
Ted Kremeneka7722b72008-05-06 21:26:51 +00001275}
1276
Ted Kremenek5535e5e2009-05-07 23:40:42 +00001277void RetainSummaryManager::InitializeClassMethodSummaries() {
1278 assert(ScratchArgs.isEmpty());
1279 RetainSummary* Summ = getPersistentSummary(ObjCAllocRetE);
Ted Kremenek0e344d42008-05-06 00:30:21 +00001280
Ted Kremenek272aa852008-06-25 21:21:56 +00001281 // Create the summaries for "alloc", "new", and "allocWithZone:" for
1282 // NSObject and its derivatives.
1283 addNSObjectClsMethSummary(GetNullarySelector("alloc", Ctx), Summ);
1284 addNSObjectClsMethSummary(GetNullarySelector("new", Ctx), Summ);
1285 addNSObjectClsMethSummary(GetUnarySelector("allocWithZone", Ctx), Summ);
Ted Kremenekf2717b02008-07-18 17:24:20 +00001286
1287 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001288 addClsMethSummary(&Ctx.Idents.get("NSAssertionHandler"),
Ted Kremenek68621b92009-01-28 05:56:51 +00001289 GetNullarySelector("currentHandler", Ctx),
1290 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001291
1292 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremeneka56ae162009-05-03 05:20:50 +00001293 ScratchArgs = AF.Add(ScratchArgs, 0, Autorelease);
Ted Kremenek9b112d22009-01-28 21:44:40 +00001294 addClsMethSummary(&Ctx.Idents.get("NSAutoreleasePool"),
1295 GetUnarySelector("addObject", Ctx),
1296 getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenekf21cb242009-02-23 02:31:16 +00001297 DoNothing, Autorelease));
Ted Kremenekccbe79a2009-04-24 17:50:11 +00001298
1299 // Create the summaries for [NSObject performSelector...]. We treat
1300 // these as 'stop tracking' for the arguments because they are often
1301 // used for delegates that can release the object. When we have better
1302 // inter-procedural analysis we can potentially do something better. This
1303 // workaround is to remove false positives.
1304 Summ = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, StopTracking);
1305 IdentifierInfo *NSObjectII = &Ctx.Idents.get("NSObject");
1306 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1307 "afterDelay", NULL);
1308 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1309 "afterDelay", "inModes", NULL);
1310 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1311 "withObject", "waitUntilDone", NULL);
1312 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1313 "withObject", "waitUntilDone", "modes", NULL);
1314 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1315 "withObject", "waitUntilDone", NULL);
1316 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1317 "withObject", "waitUntilDone", "modes", NULL);
1318 addClsMethSummary(NSObjectII, Summ, "performSelectorInBackground",
1319 "withObject", NULL);
Ted Kremenek0e344d42008-05-06 00:30:21 +00001320}
1321
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001322void RetainSummaryManager::InitializeMethodSummaries() {
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001323
Ted Kremeneka56ae162009-05-03 05:20:50 +00001324 assert (ScratchArgs.isEmpty());
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001325
Ted Kremeneka7722b72008-05-06 21:26:51 +00001326 // Create the "init" selector. It just acts as a pass-through for the
1327 // receiver.
Ted Kremenek56c70aa2009-02-23 16:54:00 +00001328 RetainSummary* InitSumm =
1329 getPersistentSummary(RetEffect::MakeReceiverAlias());
Ted Kremeneke44927e2008-07-01 17:21:27 +00001330 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001331
1332 // The next methods are allocators.
Ted Kremenek5535e5e2009-05-07 23:40:42 +00001333 RetainSummary* Summ = getPersistentSummary(ObjCAllocRetE);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001334
1335 // Create the "copy" selector.
Ted Kremenek9449ca92008-08-12 20:41:56 +00001336 addNSObjectMethSummary(GetNullarySelector("copy", Ctx), Summ);
1337
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001338 // Create the "mutableCopy" selector.
Ted Kremenek272aa852008-06-25 21:21:56 +00001339 addNSObjectMethSummary(GetNullarySelector("mutableCopy", Ctx), Summ);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001340
Ted Kremenek266d8b62008-05-06 02:26:56 +00001341 // Create the "retain" selector.
Ted Kremenek5535e5e2009-05-07 23:40:42 +00001342 RetEffect E = RetEffect::MakeReceiverAlias();
Ted Kremenek58dd95b2009-02-18 18:54:33 +00001343 Summ = getPersistentSummary(E, IncRefMsg);
Ted Kremenek272aa852008-06-25 21:21:56 +00001344 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001345
1346 // Create the "release" selector.
Ted Kremenek58dd95b2009-02-18 18:54:33 +00001347 Summ = getPersistentSummary(E, DecRefMsg);
Ted Kremenek272aa852008-06-25 21:21:56 +00001348 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Ted Kremenekc00b32b2008-05-07 21:17:39 +00001349
1350 // Create the "drain" selector.
1351 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek272aa852008-06-25 21:21:56 +00001352 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
Ted Kremenek6537a642009-03-17 19:42:23 +00001353
1354 // Create the -dealloc summary.
1355 Summ = getPersistentSummary(RetEffect::MakeNoRet(), Dealloc);
1356 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001357
1358 // Create the "autorelease" selector.
Ted Kremenek9b112d22009-01-28 21:44:40 +00001359 Summ = getPersistentSummary(E, Autorelease);
Ted Kremenek272aa852008-06-25 21:21:56 +00001360 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001361
Ted Kremenekaac82832009-02-23 17:45:03 +00001362 // Specially handle NSAutoreleasePool.
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001363 addInstMethSummary("NSAutoreleasePool", "init",
Ted Kremenekaac82832009-02-23 17:45:03 +00001364 getPersistentSummary(RetEffect::MakeReceiverAlias(),
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001365 NewAutoreleasePool));
Ted Kremenekaac82832009-02-23 17:45:03 +00001366
Ted Kremenek45642a42008-08-12 18:48:50 +00001367 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremenek7e3a3272009-02-23 02:51:29 +00001368 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1369 // self-own themselves. However, they only do this once they are displayed.
1370 // Thus, we need to track an NSWindow's display status.
1371 // This is tracked in <rdar://problem/6062711>.
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001372 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
Ted Kremeneke5a036a2009-04-03 19:02:51 +00001373 RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet());
1374
1375 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1376
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001377
1378#if 0
Ted Kremeneke44927e2008-07-01 17:21:27 +00001379 RetainSummary *NSWindowSumm =
Ted Kremenek7e3a3272009-02-23 02:51:29 +00001380 getPersistentSummary(RetEffect::MakeReceiverAlias(), StopTracking);
Ted Kremenek45642a42008-08-12 18:48:50 +00001381
1382 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1383 "styleMask", "backing", "defer", NULL);
1384
1385 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1386 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001387#endif
Ted Kremenek45642a42008-08-12 18:48:50 +00001388
1389 // For NSPanel (which subclasses NSWindow), allocated objects are not
1390 // self-owned.
Ted Kremeneke5a036a2009-04-03 19:02:51 +00001391 // FIXME: For now we don't track NSPanels. object for the same reason
1392 // as for NSWindow objects.
1393 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
1394
Ted Kremenek45642a42008-08-12 18:48:50 +00001395 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1396 "styleMask", "backing", "defer", NULL);
1397
1398 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1399 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek272aa852008-06-25 21:21:56 +00001400
Ted Kremenekf2717b02008-07-18 17:24:20 +00001401 // Create NSAssertionHandler summaries.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001402 addPanicSummary("NSAssertionHandler", "handleFailureInFunction", "file",
1403 "lineNumber", "description", NULL);
Ted Kremenekf2717b02008-07-18 17:24:20 +00001404
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001405 addPanicSummary("NSAssertionHandler", "handleFailureInMethod", "object",
1406 "file", "lineNumber", "description", NULL);
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001407}
1408
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001409//===----------------------------------------------------------------------===//
Ted Kremenek7aef4842008-04-16 20:40:59 +00001410// Reference-counting logic (typestate + counts).
Ted Kremeneka7338b42008-03-11 06:39:11 +00001411//===----------------------------------------------------------------------===//
1412
Ted Kremeneka7338b42008-03-11 06:39:11 +00001413namespace {
1414
Ted Kremenek7d421f32008-04-09 23:49:11 +00001415class VISIBILITY_HIDDEN RefVal {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001416public:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001417 enum Kind {
1418 Owned = 0, // Owning reference.
1419 NotOwned, // Reference is not owned by still valid (not freed).
1420 Released, // Object has been released.
1421 ReturnedOwned, // Returned object passes ownership to caller.
1422 ReturnedNotOwned, // Return object does not pass ownership to caller.
Ted Kremenek6537a642009-03-17 19:42:23 +00001423 ERROR_START,
1424 ErrorDeallocNotOwned, // -dealloc called on non-owned object.
1425 ErrorDeallocGC, // Calling -dealloc with GC enabled.
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001426 ErrorUseAfterRelease, // Object used after released.
1427 ErrorReleaseNotOwned, // Release of an object that was not owned.
Ted Kremenek6537a642009-03-17 19:42:23 +00001428 ERROR_LEAK_START,
Ted Kremenek311f3d42008-10-22 23:56:21 +00001429 ErrorLeak, // A memory leak due to excessive reference counts.
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001430 ErrorLeakReturned, // A memory leak due to the returning method not having
1431 // the correct naming conventions.
1432 ErrorOverAutorelease
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001433 };
Ted Kremenek68621b92009-01-28 05:56:51 +00001434
1435private:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001436 Kind kind;
Ted Kremenek68621b92009-01-28 05:56:51 +00001437 RetEffect::ObjKind okind;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001438 unsigned Cnt;
Ted Kremenek4d99d342009-05-08 20:01:42 +00001439 unsigned ACnt;
Ted Kremenek272aa852008-06-25 21:21:56 +00001440 QualType T;
1441
Ted Kremenek4d99d342009-05-08 20:01:42 +00001442 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, unsigned acnt, QualType t)
1443 : kind(k), okind(o), Cnt(cnt), ACnt(acnt), T(t) {}
Ted Kremenek0d721572008-03-11 17:48:22 +00001444
Ted Kremenek68621b92009-01-28 05:56:51 +00001445 RefVal(Kind k, unsigned cnt = 0)
Ted Kremenek4d99d342009-05-08 20:01:42 +00001446 : kind(k), okind(RetEffect::AnyObj), Cnt(cnt), ACnt(0) {}
Ted Kremenek68621b92009-01-28 05:56:51 +00001447
1448public:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001449 Kind getKind() const { return kind; }
Ted Kremenek68621b92009-01-28 05:56:51 +00001450
1451 RetEffect::ObjKind getObjKind() const { return okind; }
Ted Kremenek0d721572008-03-11 17:48:22 +00001452
Ted Kremenek4d99d342009-05-08 20:01:42 +00001453 unsigned getCount() const { return Cnt; }
1454 unsigned getAutoreleaseCount() const { return ACnt; }
1455 unsigned getCombinedCounts() const { return Cnt + ACnt; }
1456 void clearCounts() { Cnt = 0; ACnt = 0; }
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001457 void setCount(unsigned i) { Cnt = i; }
1458 void setAutoreleaseCount(unsigned i) { ACnt = i; }
Ted Kremenek6537a642009-03-17 19:42:23 +00001459
Ted Kremenek272aa852008-06-25 21:21:56 +00001460 QualType getType() const { return T; }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001461
1462 // Useful predicates.
Ted Kremenek0d721572008-03-11 17:48:22 +00001463
Ted Kremenek6537a642009-03-17 19:42:23 +00001464 static bool isError(Kind k) { return k >= ERROR_START; }
Ted Kremenek1daa16c2008-03-11 18:14:09 +00001465
Ted Kremenek6537a642009-03-17 19:42:23 +00001466 static bool isLeak(Kind k) { return k >= ERROR_LEAK_START; }
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001467
Ted Kremenekffefc352008-04-11 22:25:11 +00001468 bool isOwned() const {
1469 return getKind() == Owned;
1470 }
1471
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001472 bool isNotOwned() const {
1473 return getKind() == NotOwned;
1474 }
1475
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001476 bool isReturnedOwned() const {
1477 return getKind() == ReturnedOwned;
1478 }
1479
1480 bool isReturnedNotOwned() const {
1481 return getKind() == ReturnedNotOwned;
1482 }
1483
1484 bool isNonLeakError() const {
1485 Kind k = getKind();
1486 return isError(k) && !isLeak(k);
1487 }
1488
Ted Kremenek68621b92009-01-28 05:56:51 +00001489 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
1490 unsigned Count = 1) {
Ted Kremenek4d99d342009-05-08 20:01:42 +00001491 return RefVal(Owned, o, Count, 0, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001492 }
1493
Ted Kremenek68621b92009-01-28 05:56:51 +00001494 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
1495 unsigned Count = 0) {
Ted Kremenek4d99d342009-05-08 20:01:42 +00001496 return RefVal(NotOwned, o, Count, 0, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001497 }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001498
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001499 // Comparison, profiling, and pretty-printing.
Ted Kremenek0d721572008-03-11 17:48:22 +00001500
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001501 bool operator==(const RefVal& X) const {
Ted Kremenekbd271be2009-05-10 05:11:21 +00001502 return kind == X.kind && Cnt == X.Cnt && T == X.T && ACnt == X.ACnt;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001503 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001504
Ted Kremenek272aa852008-06-25 21:21:56 +00001505 RefVal operator-(size_t i) const {
Ted Kremenek4d99d342009-05-08 20:01:42 +00001506 return RefVal(getKind(), getObjKind(), getCount() - i,
1507 getAutoreleaseCount(), getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001508 }
1509
1510 RefVal operator+(size_t i) const {
Ted Kremenek4d99d342009-05-08 20:01:42 +00001511 return RefVal(getKind(), getObjKind(), getCount() + i,
1512 getAutoreleaseCount(), getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001513 }
1514
1515 RefVal operator^(Kind k) const {
Ted Kremenek4d99d342009-05-08 20:01:42 +00001516 return RefVal(k, getObjKind(), getCount(), getAutoreleaseCount(),
1517 getType());
1518 }
1519
1520 RefVal autorelease() const {
1521 return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount()+1,
1522 getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001523 }
Ted Kremenek6537a642009-03-17 19:42:23 +00001524
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001525 void Profile(llvm::FoldingSetNodeID& ID) const {
1526 ID.AddInteger((unsigned) kind);
1527 ID.AddInteger(Cnt);
Ted Kremenek4d99d342009-05-08 20:01:42 +00001528 ID.AddInteger(ACnt);
Ted Kremenek272aa852008-06-25 21:21:56 +00001529 ID.Add(T);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001530 }
1531
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001532 void print(std::ostream& Out) const;
Ted Kremenek0d721572008-03-11 17:48:22 +00001533};
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001534
1535void RefVal::print(std::ostream& Out) const {
Ted Kremenek272aa852008-06-25 21:21:56 +00001536 if (!T.isNull())
1537 Out << "Tracked Type:" << T.getAsString() << '\n';
1538
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001539 switch (getKind()) {
1540 default: assert(false);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001541 case Owned: {
1542 Out << "Owned";
1543 unsigned cnt = getCount();
1544 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001545 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001546 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001547
Ted Kremenekc4f81022008-04-10 23:09:18 +00001548 case NotOwned: {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001549 Out << "NotOwned";
Ted Kremenekc4f81022008-04-10 23:09:18 +00001550 unsigned cnt = getCount();
1551 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001552 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001553 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001554
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001555 case ReturnedOwned: {
1556 Out << "ReturnedOwned";
1557 unsigned cnt = getCount();
1558 if (cnt) Out << " (+ " << cnt << ")";
1559 break;
1560 }
1561
1562 case ReturnedNotOwned: {
1563 Out << "ReturnedNotOwned";
1564 unsigned cnt = getCount();
1565 if (cnt) Out << " (+ " << cnt << ")";
1566 break;
1567 }
1568
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001569 case Released:
1570 Out << "Released";
1571 break;
Ted Kremenek6537a642009-03-17 19:42:23 +00001572
1573 case ErrorDeallocGC:
1574 Out << "-dealloc (GC)";
1575 break;
1576
1577 case ErrorDeallocNotOwned:
1578 Out << "-dealloc (not-owned)";
1579 break;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001580
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001581 case ErrorLeak:
1582 Out << "Leaked";
1583 break;
1584
Ted Kremenek311f3d42008-10-22 23:56:21 +00001585 case ErrorLeakReturned:
1586 Out << "Leaked (Bad naming)";
1587 break;
1588
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001589 case ErrorUseAfterRelease:
1590 Out << "Use-After-Release [ERROR]";
1591 break;
1592
1593 case ErrorReleaseNotOwned:
1594 Out << "Release of Not-Owned [ERROR]";
1595 break;
Ted Kremenek3f15aba2009-05-09 00:44:07 +00001596
1597 case RefVal::ErrorOverAutorelease:
1598 Out << "Over autoreleased";
1599 break;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001600 }
Ted Kremenek4d99d342009-05-08 20:01:42 +00001601
1602 if (ACnt) {
1603 Out << " [ARC +" << ACnt << ']';
1604 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001605}
Ted Kremenek0d721572008-03-11 17:48:22 +00001606
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001607} // end anonymous namespace
1608
1609//===----------------------------------------------------------------------===//
1610// RefBindings - State used to track object reference counts.
1611//===----------------------------------------------------------------------===//
1612
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001613typedef llvm::ImmutableMap<SymbolRef, RefVal> RefBindings;
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001614static int RefBIndex = 0;
1615
1616namespace clang {
Ted Kremenek91781202008-08-17 03:20:02 +00001617 template<>
1618 struct GRStateTrait<RefBindings> : public GRStatePartialTrait<RefBindings> {
1619 static inline void* GDMIndex() { return &RefBIndex; }
1620 };
1621}
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001622
1623//===----------------------------------------------------------------------===//
Ted Kremenekb6578942009-02-24 19:15:11 +00001624// AutoreleaseBindings - State used to track objects in autorelease pools.
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001625//===----------------------------------------------------------------------===//
1626
Ted Kremenekb6578942009-02-24 19:15:11 +00001627typedef llvm::ImmutableMap<SymbolRef, unsigned> ARCounts;
1628typedef llvm::ImmutableMap<SymbolRef, ARCounts> ARPoolContents;
1629typedef llvm::ImmutableList<SymbolRef> ARStack;
Ted Kremenekaac82832009-02-23 17:45:03 +00001630
Ted Kremenekb6578942009-02-24 19:15:11 +00001631static int AutoRCIndex = 0;
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001632static int AutoRBIndex = 0;
1633
Ted Kremenekb6578942009-02-24 19:15:11 +00001634namespace { class VISIBILITY_HIDDEN AutoreleasePoolContents {}; }
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001635namespace { class VISIBILITY_HIDDEN AutoreleaseStack {}; }
Ted Kremenekb6578942009-02-24 19:15:11 +00001636
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001637namespace clang {
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001638template<> struct GRStateTrait<AutoreleaseStack>
Ted Kremenekb6578942009-02-24 19:15:11 +00001639 : public GRStatePartialTrait<ARStack> {
1640 static inline void* GDMIndex() { return &AutoRBIndex; }
1641};
1642
1643template<> struct GRStateTrait<AutoreleasePoolContents>
1644 : public GRStatePartialTrait<ARPoolContents> {
1645 static inline void* GDMIndex() { return &AutoRCIndex; }
1646};
1647} // end clang namespace
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001648
Ted Kremenek681fb352009-03-20 17:34:15 +00001649static SymbolRef GetCurrentAutoreleasePool(const GRState* state) {
1650 ARStack stack = state->get<AutoreleaseStack>();
1651 return stack.isEmpty() ? SymbolRef() : stack.getHead();
1652}
1653
1654static GRStateRef SendAutorelease(GRStateRef state, ARCounts::Factory &F,
1655 SymbolRef sym) {
1656
1657 SymbolRef pool = GetCurrentAutoreleasePool(state);
1658 const ARCounts *cnts = state.get<AutoreleasePoolContents>(pool);
1659 ARCounts newCnts(0);
1660
1661 if (cnts) {
1662 const unsigned *cnt = (*cnts).lookup(sym);
1663 newCnts = F.Add(*cnts, sym, cnt ? *cnt + 1 : 1);
1664 }
1665 else
1666 newCnts = F.Add(F.GetEmptyMap(), sym, 1);
1667
1668 return state.set<AutoreleasePoolContents>(pool, newCnts);
1669}
1670
Ted Kremenek7aef4842008-04-16 20:40:59 +00001671//===----------------------------------------------------------------------===//
1672// Transfer functions.
1673//===----------------------------------------------------------------------===//
1674
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001675namespace {
1676
Ted Kremenek7d421f32008-04-09 23:49:11 +00001677class VISIBILITY_HIDDEN CFRefCount : public GRSimpleVals {
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001678public:
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001679 class BindingsPrinter : public GRState::Printer {
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001680 public:
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001681 virtual void Print(std::ostream& Out, const GRState* state,
1682 const char* nl, const char* sep);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001683 };
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001684
1685private:
Ted Kremenekc26c4692009-02-18 03:48:14 +00001686 typedef llvm::DenseMap<const GRExprEngine::NodeTy*, const RetainSummary*>
1687 SummaryLogTy;
1688
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001689 RetainSummaryManager Summaries;
Ted Kremenekc26c4692009-02-18 03:48:14 +00001690 SummaryLogTy SummaryLog;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001691 const LangOptions& LOpts;
Ted Kremenekb6578942009-02-24 19:15:11 +00001692 ARCounts::Factory ARCountFactory;
Ted Kremenek91781202008-08-17 03:20:02 +00001693
Ted Kremenek708af042009-02-05 06:50:21 +00001694 BugType *useAfterRelease, *releaseNotOwned;
Ted Kremenek6537a642009-03-17 19:42:23 +00001695 BugType *deallocGC, *deallocNotOwned;
Ted Kremenek708af042009-02-05 06:50:21 +00001696 BugType *leakWithinFunction, *leakAtReturn;
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001697 BugType *overAutorelease;
Ted Kremenek708af042009-02-05 06:50:21 +00001698 BugReporter *BR;
Ted Kremeneka7338b42008-03-11 06:39:11 +00001699
Ted Kremenekb6578942009-02-24 19:15:11 +00001700 GRStateRef Update(GRStateRef state, SymbolRef sym, RefVal V, ArgEffect E,
1701 RefVal::Kind& hasErr);
1702
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001703 void ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
1704 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001705 Expr* NodeExpr, Expr* ErrorExpr,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001706 ExplodedNode<GRState>* Pred,
1707 const GRState* St,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001708 RefVal::Kind hasErr, SymbolRef Sym);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001709
Ted Kremenek41a4bc62009-05-08 23:09:42 +00001710 GRStateRef HandleSymbolDeath(GRStateRef state, SymbolRef sid, RefVal V,
1711 llvm::SmallVectorImpl<SymbolRef> &Leaked);
1712
1713 ExplodedNode<GRState>* ProcessLeaks(GRStateRef state,
1714 llvm::SmallVectorImpl<SymbolRef> &Leaked,
1715 GenericNodeBuilder &Builder,
1716 GRExprEngine &Eng,
1717 ExplodedNode<GRState> *Pred = 0);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001718
Ted Kremenekb6578942009-02-24 19:15:11 +00001719public:
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00001720 CFRefCount(ASTContext& Ctx, bool gcenabled, const LangOptions& lopts)
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001721 : Summaries(Ctx, gcenabled),
Ted Kremenek6537a642009-03-17 19:42:23 +00001722 LOpts(lopts), useAfterRelease(0), releaseNotOwned(0),
1723 deallocGC(0), deallocNotOwned(0),
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001724 leakWithinFunction(0), leakAtReturn(0), overAutorelease(0), BR(0) {}
Ted Kremenek1feab292008-04-16 04:28:53 +00001725
Ted Kremenek708af042009-02-05 06:50:21 +00001726 virtual ~CFRefCount() {}
Ted Kremenek7d421f32008-04-09 23:49:11 +00001727
Ted Kremenekbf6babf2009-02-04 23:49:09 +00001728 void RegisterChecks(BugReporter &BR);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001729
Ted Kremenekb0f2b9e2008-08-16 00:49:49 +00001730 virtual void RegisterPrinters(std::vector<GRState::Printer*>& Printers) {
1731 Printers.push_back(new BindingsPrinter());
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001732 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00001733
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001734 bool isGCEnabled() const { return Summaries.isGCEnabled(); }
Ted Kremenekfe30beb2008-04-30 23:47:44 +00001735 const LangOptions& getLangOptions() const { return LOpts; }
1736
Ted Kremenekc26c4692009-02-18 03:48:14 +00001737 const RetainSummary *getSummaryOfNode(const ExplodedNode<GRState> *N) const {
1738 SummaryLogTy::const_iterator I = SummaryLog.find(N);
1739 return I == SummaryLog.end() ? 0 : I->second;
1740 }
1741
Ted Kremeneka7338b42008-03-11 06:39:11 +00001742 // Calls.
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001743
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001744 void EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001745 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001746 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001747 Expr* Ex,
1748 Expr* Receiver,
Ted Kremenek286e9852009-05-04 04:57:00 +00001749 const RetainSummary& Summ,
Ted Kremenek2719e982008-06-17 02:43:46 +00001750 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001751 ExplodedNode<GRState>* Pred);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001752
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001753 virtual void EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekce0767f2008-03-12 21:06:49 +00001754 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001755 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001756 CallExpr* CE, SVal L,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001757 ExplodedNode<GRState>* Pred);
Ted Kremenek10fe66d2008-04-09 01:10:13 +00001758
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001759
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001760 virtual void EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001761 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001762 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001763 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001764 ExplodedNode<GRState>* Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001765
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001766 bool EvalObjCMessageExprAux(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001767 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001768 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001769 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001770 ExplodedNode<GRState>* Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001771
Ted Kremeneka42be302009-02-14 01:43:44 +00001772 // Stores.
1773 virtual void EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val);
1774
Ted Kremenekffefc352008-04-11 22:25:11 +00001775 // End-of-path.
1776
1777 virtual void EvalEndPath(GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001778 GREndPathNodeBuilder<GRState>& Builder);
Ted Kremenekffefc352008-04-11 22:25:11 +00001779
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001780 virtual void EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek541db372008-04-24 23:57:27 +00001781 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001782 GRStmtNodeBuilder<GRState>& Builder,
1783 ExplodedNode<GRState>* Pred,
Ted Kremenek5c0729b2009-01-21 22:26:05 +00001784 Stmt* S, const GRState* state,
1785 SymbolReaper& SymReaper);
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00001786
1787 std::pair<ExplodedNode<GRState>*, GRStateRef>
1788 HandleAutoreleaseCounts(GRStateRef state, GenericNodeBuilder Bd,
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001789 ExplodedNode<GRState>* Pred, GRExprEngine &Eng,
1790 SymbolRef Sym, RefVal V, bool &stop);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001791 // Return statements.
1792
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001793 virtual void EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001794 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001795 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001796 ReturnStmt* S,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001797 ExplodedNode<GRState>* Pred);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001798
1799 // Assumptions.
1800
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001801 virtual const GRState* EvalAssume(GRStateManager& VMgr,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001802 const GRState* St, SVal Cond,
Ted Kremenekf22f8682008-07-10 22:03:41 +00001803 bool Assumption, bool& isFeasible);
Ted Kremeneka7338b42008-03-11 06:39:11 +00001804};
1805
1806} // end anonymous namespace
1807
Ted Kremenek681fb352009-03-20 17:34:15 +00001808static void PrintPool(std::ostream &Out, SymbolRef Sym, const GRState *state) {
1809 Out << ' ';
Ted Kremenek74556a12009-03-26 03:35:11 +00001810 if (Sym)
1811 Out << Sym->getSymbolID();
Ted Kremenek681fb352009-03-20 17:34:15 +00001812 else
1813 Out << "<pool>";
1814 Out << ":{";
1815
1816 // Get the contents of the pool.
1817 if (const ARCounts *cnts = state->get<AutoreleasePoolContents>(Sym))
1818 for (ARCounts::iterator J=cnts->begin(), EJ=cnts->end(); J != EJ; ++J)
1819 Out << '(' << J.getKey() << ',' << J.getData() << ')';
1820
1821 Out << '}';
1822}
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001823
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001824void CFRefCount::BindingsPrinter::Print(std::ostream& Out, const GRState* state,
1825 const char* nl, const char* sep) {
Ted Kremenek681fb352009-03-20 17:34:15 +00001826
1827
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001828
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001829 RefBindings B = state->get<RefBindings>();
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001830
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001831 if (!B.isEmpty())
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001832 Out << sep << nl;
1833
1834 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
1835 Out << (*I).first << " : ";
1836 (*I).second.print(Out);
1837 Out << nl;
1838 }
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001839
1840 // Print the autorelease stack.
Ted Kremenek681fb352009-03-20 17:34:15 +00001841 Out << sep << nl << "AR pool stack:";
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001842 ARStack stack = state->get<AutoreleaseStack>();
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001843
Ted Kremenek681fb352009-03-20 17:34:15 +00001844 PrintPool(Out, SymbolRef(), state); // Print the caller's pool.
1845 for (ARStack::iterator I=stack.begin(), E=stack.end(); I!=E; ++I)
1846 PrintPool(Out, *I, state);
1847
1848 Out << nl;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001849}
1850
Ted Kremenek47a72422009-04-29 18:50:19 +00001851//===----------------------------------------------------------------------===//
1852// Error reporting.
1853//===----------------------------------------------------------------------===//
1854
1855namespace {
1856
1857 //===-------------===//
1858 // Bug Descriptions. //
1859 //===-------------===//
1860
1861 class VISIBILITY_HIDDEN CFRefBug : public BugType {
1862 protected:
1863 CFRefCount& TF;
1864
1865 CFRefBug(CFRefCount* tf, const char* name)
1866 : BugType(name, "Memory (Core Foundation/Objective-C)"), TF(*tf) {}
1867 public:
1868
1869 CFRefCount& getTF() { return TF; }
1870 const CFRefCount& getTF() const { return TF; }
1871
1872 // FIXME: Eventually remove.
1873 virtual const char* getDescription() const = 0;
1874
1875 virtual bool isLeak() const { return false; }
1876 };
1877
1878 class VISIBILITY_HIDDEN UseAfterRelease : public CFRefBug {
1879 public:
1880 UseAfterRelease(CFRefCount* tf)
1881 : CFRefBug(tf, "Use-after-release") {}
1882
1883 const char* getDescription() const {
1884 return "Reference-counted object is used after it is released";
1885 }
1886 };
1887
1888 class VISIBILITY_HIDDEN BadRelease : public CFRefBug {
1889 public:
1890 BadRelease(CFRefCount* tf) : CFRefBug(tf, "Bad release") {}
1891
1892 const char* getDescription() const {
1893 return "Incorrect decrement of the reference count of an "
1894 "object is not owned at this point by the caller";
1895 }
1896 };
1897
1898 class VISIBILITY_HIDDEN DeallocGC : public CFRefBug {
1899 public:
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001900 DeallocGC(CFRefCount *tf)
1901 : CFRefBug(tf, "-dealloc called while using garbage collection") {}
Ted Kremenek47a72422009-04-29 18:50:19 +00001902
1903 const char *getDescription() const {
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001904 return "-dealloc called while using garbage collection";
Ted Kremenek47a72422009-04-29 18:50:19 +00001905 }
1906 };
1907
1908 class VISIBILITY_HIDDEN DeallocNotOwned : public CFRefBug {
1909 public:
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001910 DeallocNotOwned(CFRefCount *tf)
1911 : CFRefBug(tf, "-dealloc sent to non-exclusively owned object") {}
Ted Kremenek47a72422009-04-29 18:50:19 +00001912
1913 const char *getDescription() const {
1914 return "-dealloc sent to object that may be referenced elsewhere";
1915 }
1916 };
1917
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001918 class VISIBILITY_HIDDEN OverAutorelease : public CFRefBug {
1919 public:
1920 OverAutorelease(CFRefCount *tf) :
1921 CFRefBug(tf, "Object sent -autorelease too many times") {}
1922
1923 const char *getDescription() const {
Ted Kremenekbd271be2009-05-10 05:11:21 +00001924 return "Object sent -autorelease too many times";
Ted Kremenek412ca1e2009-05-09 00:10:05 +00001925 }
1926 };
1927
Ted Kremenek47a72422009-04-29 18:50:19 +00001928 class VISIBILITY_HIDDEN Leak : public CFRefBug {
1929 const bool isReturn;
1930 protected:
1931 Leak(CFRefCount* tf, const char* name, bool isRet)
1932 : CFRefBug(tf, name), isReturn(isRet) {}
1933 public:
1934
1935 const char* getDescription() const { return ""; }
1936
1937 bool isLeak() const { return true; }
1938 };
1939
1940 class VISIBILITY_HIDDEN LeakAtReturn : public Leak {
1941 public:
1942 LeakAtReturn(CFRefCount* tf, const char* name)
1943 : Leak(tf, name, true) {}
1944 };
1945
1946 class VISIBILITY_HIDDEN LeakWithinFunction : public Leak {
1947 public:
1948 LeakWithinFunction(CFRefCount* tf, const char* name)
1949 : Leak(tf, name, false) {}
1950 };
1951
1952 //===---------===//
1953 // Bug Reports. //
1954 //===---------===//
1955
1956 class VISIBILITY_HIDDEN CFRefReport : public RangedBugReport {
1957 protected:
1958 SymbolRef Sym;
1959 const CFRefCount &TF;
1960 public:
1961 CFRefReport(CFRefBug& D, const CFRefCount &tf,
1962 ExplodedNode<GRState> *n, SymbolRef sym)
Ted Kremenekbd271be2009-05-10 05:11:21 +00001963 : RangedBugReport(D, D.getDescription(), n), Sym(sym), TF(tf) {}
1964
1965 CFRefReport(CFRefBug& D, const CFRefCount &tf,
1966 ExplodedNode<GRState> *n, SymbolRef sym, const char* endText)
1967 : RangedBugReport(D, D.getDescription(), endText, n), Sym(sym), TF(tf) {}
Ted Kremenek47a72422009-04-29 18:50:19 +00001968
1969 virtual ~CFRefReport() {}
1970
1971 CFRefBug& getBugType() {
1972 return (CFRefBug&) RangedBugReport::getBugType();
1973 }
1974 const CFRefBug& getBugType() const {
1975 return (const CFRefBug&) RangedBugReport::getBugType();
1976 }
1977
1978 virtual void getRanges(BugReporter& BR, const SourceRange*& beg,
1979 const SourceRange*& end) {
1980
1981 if (!getBugType().isLeak())
1982 RangedBugReport::getRanges(BR, beg, end);
1983 else
1984 beg = end = 0;
1985 }
1986
1987 SymbolRef getSymbol() const { return Sym; }
1988
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00001989 PathDiagnosticPiece* getEndPath(BugReporterContext& BRC,
Ted Kremenek47a72422009-04-29 18:50:19 +00001990 const ExplodedNode<GRState>* N);
1991
1992 std::pair<const char**,const char**> getExtraDescriptiveText();
1993
1994 PathDiagnosticPiece* VisitNode(const ExplodedNode<GRState>* N,
1995 const ExplodedNode<GRState>* PrevN,
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00001996 BugReporterContext& BRC);
Ted Kremenek47a72422009-04-29 18:50:19 +00001997 };
Ted Kremenekbd271be2009-05-10 05:11:21 +00001998
Ted Kremenek47a72422009-04-29 18:50:19 +00001999 class VISIBILITY_HIDDEN CFRefLeakReport : public CFRefReport {
2000 SourceLocation AllocSite;
2001 const MemRegion* AllocBinding;
2002 public:
2003 CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2004 ExplodedNode<GRState> *n, SymbolRef sym,
2005 GRExprEngine& Eng);
2006
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002007 PathDiagnosticPiece* getEndPath(BugReporterContext& BRC,
Ted Kremenek47a72422009-04-29 18:50:19 +00002008 const ExplodedNode<GRState>* N);
2009
2010 SourceLocation getLocation() const { return AllocSite; }
2011 };
2012} // end anonymous namespace
2013
2014void CFRefCount::RegisterChecks(BugReporter& BR) {
2015 useAfterRelease = new UseAfterRelease(this);
2016 BR.Register(useAfterRelease);
2017
2018 releaseNotOwned = new BadRelease(this);
2019 BR.Register(releaseNotOwned);
2020
2021 deallocGC = new DeallocGC(this);
2022 BR.Register(deallocGC);
2023
2024 deallocNotOwned = new DeallocNotOwned(this);
2025 BR.Register(deallocNotOwned);
2026
Ted Kremenek412ca1e2009-05-09 00:10:05 +00002027 overAutorelease = new OverAutorelease(this);
2028 BR.Register(overAutorelease);
2029
Ted Kremenek47a72422009-04-29 18:50:19 +00002030 // First register "return" leaks.
2031 const char* name = 0;
2032
2033 if (isGCEnabled())
2034 name = "Leak of returned object when using garbage collection";
2035 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2036 name = "Leak of returned object when not using garbage collection (GC) in "
2037 "dual GC/non-GC code";
2038 else {
2039 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2040 name = "Leak of returned object";
2041 }
2042
2043 leakAtReturn = new LeakAtReturn(this, name);
2044 BR.Register(leakAtReturn);
2045
2046 // Second, register leaks within a function/method.
2047 if (isGCEnabled())
2048 name = "Leak of object when using garbage collection";
2049 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2050 name = "Leak of object when not using garbage collection (GC) in "
2051 "dual GC/non-GC code";
2052 else {
2053 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2054 name = "Leak";
2055 }
2056
2057 leakWithinFunction = new LeakWithinFunction(this, name);
2058 BR.Register(leakWithinFunction);
2059
2060 // Save the reference to the BugReporter.
2061 this->BR = &BR;
2062}
2063
2064static const char* Msgs[] = {
2065 // GC only
2066 "Code is compiled to only use garbage collection",
2067 // No GC.
2068 "Code is compiled to use reference counts",
2069 // Hybrid, with GC.
2070 "Code is compiled to use either garbage collection (GC) or reference counts"
2071 " (non-GC). The bug occurs with GC enabled",
2072 // Hybrid, without GC
2073 "Code is compiled to use either garbage collection (GC) or reference counts"
2074 " (non-GC). The bug occurs in non-GC mode"
2075};
2076
2077std::pair<const char**,const char**> CFRefReport::getExtraDescriptiveText() {
2078 CFRefCount& TF = static_cast<CFRefBug&>(getBugType()).getTF();
2079
2080 switch (TF.getLangOptions().getGCMode()) {
2081 default:
2082 assert(false);
2083
2084 case LangOptions::GCOnly:
2085 assert (TF.isGCEnabled());
2086 return std::make_pair(&Msgs[0], &Msgs[0]+1);
2087
2088 case LangOptions::NonGC:
2089 assert (!TF.isGCEnabled());
2090 return std::make_pair(&Msgs[1], &Msgs[1]+1);
2091
2092 case LangOptions::HybridGC:
2093 if (TF.isGCEnabled())
2094 return std::make_pair(&Msgs[2], &Msgs[2]+1);
2095 else
2096 return std::make_pair(&Msgs[3], &Msgs[3]+1);
2097 }
2098}
2099
2100static inline bool contains(const llvm::SmallVectorImpl<ArgEffect>& V,
2101 ArgEffect X) {
2102 for (llvm::SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
2103 I!=E; ++I)
2104 if (*I == X) return true;
2105
2106 return false;
2107}
2108
2109PathDiagnosticPiece* CFRefReport::VisitNode(const ExplodedNode<GRState>* N,
2110 const ExplodedNode<GRState>* PrevN,
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002111 BugReporterContext& BRC) {
Ted Kremenek47a72422009-04-29 18:50:19 +00002112
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002113 // Check if the type state has changed.
2114 GRStateManager &StMgr = BRC.getStateManager();
Ted Kremenek47a72422009-04-29 18:50:19 +00002115 GRStateRef PrevSt(PrevN->getState(), StMgr);
2116 GRStateRef CurrSt(N->getState(), StMgr);
2117
2118 const RefVal* CurrT = CurrSt.get<RefBindings>(Sym);
2119 if (!CurrT) return NULL;
2120
2121 const RefVal& CurrV = *CurrT;
2122 const RefVal* PrevT = PrevSt.get<RefBindings>(Sym);
2123
2124 // Create a string buffer to constain all the useful things we want
2125 // to tell the user.
2126 std::string sbuf;
2127 llvm::raw_string_ostream os(sbuf);
2128
2129 // This is the allocation site since the previous node had no bindings
2130 // for this symbol.
2131 if (!PrevT) {
2132 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2133
2134 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2135 // Get the name of the callee (if it is available).
2136 SVal X = CurrSt.GetSValAsScalarOrLoc(CE->getCallee());
2137 if (const FunctionDecl* FD = X.getAsFunctionDecl())
2138 os << "Call to function '" << FD->getNameAsString() <<'\'';
2139 else
2140 os << "function call";
2141 }
2142 else {
2143 assert (isa<ObjCMessageExpr>(S));
2144 os << "Method";
2145 }
2146
2147 if (CurrV.getObjKind() == RetEffect::CF) {
2148 os << " returns a Core Foundation object with a ";
2149 }
2150 else {
2151 assert (CurrV.getObjKind() == RetEffect::ObjC);
2152 os << " returns an Objective-C object with a ";
2153 }
2154
2155 if (CurrV.isOwned()) {
2156 os << "+1 retain count (owning reference).";
2157
2158 if (static_cast<CFRefBug&>(getBugType()).getTF().isGCEnabled()) {
2159 assert(CurrV.getObjKind() == RetEffect::CF);
2160 os << " "
2161 "Core Foundation objects are not automatically garbage collected.";
2162 }
2163 }
2164 else {
2165 assert (CurrV.isNotOwned());
2166 os << "+0 retain count (non-owning reference).";
2167 }
2168
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002169 PathDiagnosticLocation Pos(S, BRC.getSourceManager());
Ted Kremenek47a72422009-04-29 18:50:19 +00002170 return new PathDiagnosticEventPiece(Pos, os.str());
2171 }
2172
2173 // Gather up the effects that were performed on the object at this
2174 // program point
2175 llvm::SmallVector<ArgEffect, 2> AEffects;
2176
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002177 if (const RetainSummary *Summ =
2178 TF.getSummaryOfNode(BRC.getNodeResolver().getOriginalNode(N))) {
Ted Kremenek47a72422009-04-29 18:50:19 +00002179 // We only have summaries attached to nodes after evaluating CallExpr and
2180 // ObjCMessageExprs.
2181 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2182
2183 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2184 // Iterate through the parameter expressions and see if the symbol
2185 // was ever passed as an argument.
2186 unsigned i = 0;
2187
2188 for (CallExpr::arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
2189 AI!=AE; ++AI, ++i) {
2190
2191 // Retrieve the value of the argument. Is it the symbol
2192 // we are interested in?
2193 if (CurrSt.GetSValAsScalarOrLoc(*AI).getAsLocSymbol() != Sym)
2194 continue;
2195
2196 // We have an argument. Get the effect!
2197 AEffects.push_back(Summ->getArg(i));
2198 }
2199 }
2200 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
2201 if (Expr *receiver = ME->getReceiver())
2202 if (CurrSt.GetSValAsScalarOrLoc(receiver).getAsLocSymbol() == Sym) {
2203 // The symbol we are tracking is the receiver.
2204 AEffects.push_back(Summ->getReceiverEffect());
2205 }
2206 }
2207 }
2208
2209 do {
2210 // Get the previous type state.
2211 RefVal PrevV = *PrevT;
2212
2213 // Specially handle -dealloc.
2214 if (!TF.isGCEnabled() && contains(AEffects, Dealloc)) {
2215 // Determine if the object's reference count was pushed to zero.
2216 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2217 // We may not have transitioned to 'release' if we hit an error.
2218 // This case is handled elsewhere.
2219 if (CurrV.getKind() == RefVal::Released) {
Ted Kremenek4d99d342009-05-08 20:01:42 +00002220 assert(CurrV.getCombinedCounts() == 0);
Ted Kremenek47a72422009-04-29 18:50:19 +00002221 os << "Object released by directly sending the '-dealloc' message";
2222 break;
2223 }
2224 }
2225
2226 // Specially handle CFMakeCollectable and friends.
2227 if (contains(AEffects, MakeCollectable)) {
2228 // Get the name of the function.
2229 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2230 SVal X = CurrSt.GetSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee());
2231 const FunctionDecl* FD = X.getAsFunctionDecl();
2232 const std::string& FName = FD->getNameAsString();
2233
2234 if (TF.isGCEnabled()) {
2235 // Determine if the object's reference count was pushed to zero.
2236 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2237
2238 os << "In GC mode a call to '" << FName
2239 << "' decrements an object's retain count and registers the "
2240 "object with the garbage collector. ";
2241
2242 if (CurrV.getKind() == RefVal::Released) {
2243 assert(CurrV.getCount() == 0);
2244 os << "Since it now has a 0 retain count the object can be "
2245 "automatically collected by the garbage collector.";
2246 }
2247 else
2248 os << "An object must have a 0 retain count to be garbage collected. "
2249 "After this call its retain count is +" << CurrV.getCount()
2250 << '.';
2251 }
2252 else
2253 os << "When GC is not enabled a call to '" << FName
2254 << "' has no effect on its argument.";
2255
2256 // Nothing more to say.
2257 break;
2258 }
2259
2260 // Determine if the typestate has changed.
2261 if (!(PrevV == CurrV))
2262 switch (CurrV.getKind()) {
2263 case RefVal::Owned:
2264 case RefVal::NotOwned:
2265
Ted Kremenek4d99d342009-05-08 20:01:42 +00002266 if (PrevV.getCount() == CurrV.getCount()) {
2267 // Did an autorelease message get sent?
2268 if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
2269 return 0;
2270
2271 assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount());
Ted Kremenekbd271be2009-05-10 05:11:21 +00002272 os << "Object sent -autorelease message";
Ted Kremenek4d99d342009-05-08 20:01:42 +00002273 break;
2274 }
Ted Kremenek47a72422009-04-29 18:50:19 +00002275
2276 if (PrevV.getCount() > CurrV.getCount())
2277 os << "Reference count decremented.";
2278 else
2279 os << "Reference count incremented.";
2280
2281 if (unsigned Count = CurrV.getCount())
2282 os << " The object now has a +" << Count << " retain count.";
2283
2284 if (PrevV.getKind() == RefVal::Released) {
2285 assert(TF.isGCEnabled() && CurrV.getCount() > 0);
2286 os << " The object is not eligible for garbage collection until the "
2287 "retain count reaches 0 again.";
2288 }
2289
2290 break;
2291
2292 case RefVal::Released:
2293 os << "Object released.";
2294 break;
2295
2296 case RefVal::ReturnedOwned:
2297 os << "Object returned to caller as an owning reference (single retain "
2298 "count transferred to caller).";
2299 break;
2300
2301 case RefVal::ReturnedNotOwned:
2302 os << "Object returned to caller with a +0 (non-owning) retain count.";
2303 break;
2304
2305 default:
2306 return NULL;
2307 }
2308
2309 // Emit any remaining diagnostics for the argument effects (if any).
2310 for (llvm::SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
2311 E=AEffects.end(); I != E; ++I) {
2312
2313 // A bunch of things have alternate behavior under GC.
2314 if (TF.isGCEnabled())
2315 switch (*I) {
2316 default: break;
2317 case Autorelease:
2318 os << "In GC mode an 'autorelease' has no effect.";
2319 continue;
2320 case IncRefMsg:
2321 os << "In GC mode the 'retain' message has no effect.";
2322 continue;
2323 case DecRefMsg:
2324 os << "In GC mode the 'release' message has no effect.";
2325 continue;
2326 }
2327 }
2328 } while(0);
2329
2330 if (os.str().empty())
2331 return 0; // We have nothing to say!
2332
2333 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002334 PathDiagnosticLocation Pos(S, BRC.getSourceManager());
Ted Kremenek47a72422009-04-29 18:50:19 +00002335 PathDiagnosticPiece* P = new PathDiagnosticEventPiece(Pos, os.str());
2336
2337 // Add the range by scanning the children of the statement for any bindings
2338 // to Sym.
2339 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I)
2340 if (Expr* Exp = dyn_cast_or_null<Expr>(*I))
2341 if (CurrSt.GetSValAsScalarOrLoc(Exp).getAsLocSymbol() == Sym) {
2342 P->addRange(Exp->getSourceRange());
2343 break;
2344 }
2345
2346 return P;
2347}
2348
2349namespace {
2350 class VISIBILITY_HIDDEN FindUniqueBinding :
2351 public StoreManager::BindingsHandler {
2352 SymbolRef Sym;
2353 const MemRegion* Binding;
2354 bool First;
2355
2356 public:
2357 FindUniqueBinding(SymbolRef sym) : Sym(sym), Binding(0), First(true) {}
2358
2359 bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
2360 SVal val) {
2361
2362 SymbolRef SymV = val.getAsSymbol();
2363 if (!SymV || SymV != Sym)
2364 return true;
2365
2366 if (Binding) {
2367 First = false;
2368 return false;
2369 }
2370 else
2371 Binding = R;
2372
2373 return true;
2374 }
2375
2376 operator bool() { return First && Binding; }
2377 const MemRegion* getRegion() { return Binding; }
2378 };
2379}
2380
2381static std::pair<const ExplodedNode<GRState>*,const MemRegion*>
2382GetAllocationSite(GRStateManager& StateMgr, const ExplodedNode<GRState>* N,
2383 SymbolRef Sym) {
2384
2385 // Find both first node that referred to the tracked symbol and the
2386 // memory location that value was store to.
2387 const ExplodedNode<GRState>* Last = N;
2388 const MemRegion* FirstBinding = 0;
2389
2390 while (N) {
2391 const GRState* St = N->getState();
2392 RefBindings B = St->get<RefBindings>();
2393
2394 if (!B.lookup(Sym))
2395 break;
2396
2397 FindUniqueBinding FB(Sym);
2398 StateMgr.iterBindings(St, FB);
2399 if (FB) FirstBinding = FB.getRegion();
2400
2401 Last = N;
2402 N = N->pred_empty() ? NULL : *(N->pred_begin());
2403 }
2404
2405 return std::make_pair(Last, FirstBinding);
2406}
2407
2408PathDiagnosticPiece*
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002409CFRefReport::getEndPath(BugReporterContext& BRC,
2410 const ExplodedNode<GRState>* EndN) {
2411 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenek47a72422009-04-29 18:50:19 +00002412 // assigned to different variables, etc.
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002413 BRC.addNotableSymbol(Sym);
2414 return RangedBugReport::getEndPath(BRC, EndN);
Ted Kremenek47a72422009-04-29 18:50:19 +00002415}
2416
2417PathDiagnosticPiece*
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002418CFRefLeakReport::getEndPath(BugReporterContext& BRC,
2419 const ExplodedNode<GRState>* EndN){
Ted Kremenek47a72422009-04-29 18:50:19 +00002420
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002421 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenek47a72422009-04-29 18:50:19 +00002422 // assigned to different variables, etc.
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002423 BRC.addNotableSymbol(Sym);
Ted Kremenek47a72422009-04-29 18:50:19 +00002424
2425 // We are reporting a leak. Walk up the graph to get to the first node where
2426 // the symbol appeared, and also get the first VarDecl that tracked object
2427 // is stored to.
2428 const ExplodedNode<GRState>* AllocNode = 0;
2429 const MemRegion* FirstBinding = 0;
2430
2431 llvm::tie(AllocNode, FirstBinding) =
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00002432 GetAllocationSite(BRC.getStateManager(), EndN, Sym);
Ted Kremenek47a72422009-04-29 18:50:19 +00002433
2434 // Get the allocate site.
2435 assert(AllocNode);
2436 Stmt* FirstStmt = cast<PostStmt>(AllocNode->getLocation()).getStmt();
2437
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002438 SourceManager& SMgr = BRC.getSourceManager();
Ted Kremenek47a72422009-04-29 18:50:19 +00002439 unsigned AllocLine =SMgr.getInstantiationLineNumber(FirstStmt->getLocStart());
2440
2441 // Compute an actual location for the leak. Sometimes a leak doesn't
2442 // occur at an actual statement (e.g., transition between blocks; end
2443 // of function) so we need to walk the graph and compute a real location.
2444 const ExplodedNode<GRState>* LeakN = EndN;
2445 PathDiagnosticLocation L;
2446
2447 while (LeakN) {
2448 ProgramPoint P = LeakN->getLocation();
2449
2450 if (const PostStmt *PS = dyn_cast<PostStmt>(&P)) {
2451 L = PathDiagnosticLocation(PS->getStmt()->getLocStart(), SMgr);
2452 break;
2453 }
2454 else if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
2455 if (const Stmt* Term = BE->getSrc()->getTerminator()) {
2456 L = PathDiagnosticLocation(Term->getLocStart(), SMgr);
2457 break;
2458 }
2459 }
2460
2461 LeakN = LeakN->succ_empty() ? 0 : *(LeakN->succ_begin());
2462 }
2463
2464 if (!L.isValid()) {
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002465 const Decl &D = BRC.getCodeDecl();
2466 L = PathDiagnosticLocation(D.getBodyRBrace(BRC.getASTContext()), SMgr);
Ted Kremenek47a72422009-04-29 18:50:19 +00002467 }
2468
2469 std::string sbuf;
2470 llvm::raw_string_ostream os(sbuf);
2471
2472 os << "Object allocated on line " << AllocLine;
2473
2474 if (FirstBinding)
2475 os << " and stored into '" << FirstBinding->getString() << '\'';
2476
2477 // Get the retain count.
2478 const RefVal* RV = EndN->getState()->get<RefBindings>(Sym);
2479
2480 if (RV->getKind() == RefVal::ErrorLeakReturned) {
2481 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
2482 // ojbects. Only "copy", "alloc", "retain" and "new" transfer ownership
2483 // to the caller for NS objects.
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002484 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(BRC.getCodeDecl());
Ted Kremenek47a72422009-04-29 18:50:19 +00002485 os << " is returned from a method whose name ('"
Ted Kremenek314b1952009-04-29 23:03:22 +00002486 << MD.getSelector().getAsString()
Ted Kremenek47a72422009-04-29 18:50:19 +00002487 << "') does not contain 'copy' or otherwise starts with"
2488 " 'new' or 'alloc'. This violates the naming convention rules given"
Ted Kremenek2a410c92009-04-29 22:25:52 +00002489 " in the Memory Management Guide for Cocoa (object leaked)";
Ted Kremenek47a72422009-04-29 18:50:19 +00002490 }
2491 else
2492 os << " is no longer referenced after this point and has a retain count of"
Ted Kremenek2a410c92009-04-29 22:25:52 +00002493 " +" << RV->getCount() << " (object leaked)";
Ted Kremenek47a72422009-04-29 18:50:19 +00002494
2495 return new PathDiagnosticEventPiece(L, os.str());
2496}
2497
Ted Kremenek47a72422009-04-29 18:50:19 +00002498CFRefLeakReport::CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2499 ExplodedNode<GRState> *n,
2500 SymbolRef sym, GRExprEngine& Eng)
2501: CFRefReport(D, tf, n, sym)
2502{
2503
2504 // Most bug reports are cached at the location where they occured.
2505 // With leaks, we want to unique them by the location where they were
2506 // allocated, and only report a single path. To do this, we need to find
2507 // the allocation site of a piece of tracked memory, which we do via a
2508 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2509 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2510 // that all ancestor nodes that represent the allocation site have the
2511 // same SourceLocation.
2512 const ExplodedNode<GRState>* AllocNode = 0;
2513
2514 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding.
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00002515 GetAllocationSite(Eng.getStateManager(), getEndNode(), getSymbol());
Ted Kremenek47a72422009-04-29 18:50:19 +00002516
2517 // Get the SourceLocation for the allocation site.
2518 ProgramPoint P = AllocNode->getLocation();
2519 AllocSite = cast<PostStmt>(P).getStmt()->getLocStart();
2520
2521 // Fill in the description of the bug.
2522 Description.clear();
2523 llvm::raw_string_ostream os(Description);
2524 SourceManager& SMgr = Eng.getContext().getSourceManager();
2525 unsigned AllocLine = SMgr.getInstantiationLineNumber(AllocSite);
Ted Kremenek2e9d0302009-05-02 19:05:19 +00002526 os << "Potential leak ";
2527 if (tf.isGCEnabled()) {
2528 os << "(when using garbage collection) ";
2529 }
2530 os << "of an object allocated on line " << AllocLine;
Ted Kremenek47a72422009-04-29 18:50:19 +00002531
2532 // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2533 if (AllocBinding)
2534 os << " and stored into '" << AllocBinding->getString() << '\'';
2535}
2536
2537//===----------------------------------------------------------------------===//
2538// Main checker logic.
2539//===----------------------------------------------------------------------===//
2540
Ted Kremenek272aa852008-06-25 21:21:56 +00002541/// GetReturnType - Used to get the return type of a message expression or
2542/// function call with the intention of affixing that type to a tracked symbol.
2543/// While the the return type can be queried directly from RetEx, when
2544/// invoking class methods we augment to the return type to be that of
2545/// a pointer to the class (as opposed it just being id).
2546static QualType GetReturnType(Expr* RetE, ASTContext& Ctx) {
2547
2548 QualType RetTy = RetE->getType();
2549
2550 // FIXME: We aren't handling id<...>.
Chris Lattnerb724ab22008-07-26 22:36:27 +00002551 const PointerType* PT = RetTy->getAsPointerType();
Ted Kremenek272aa852008-06-25 21:21:56 +00002552 if (!PT)
2553 return RetTy;
2554
2555 // If RetEx is not a message expression just return its type.
2556 // If RetEx is a message expression, return its types if it is something
2557 /// more specific than id.
2558
2559 ObjCMessageExpr* ME = dyn_cast<ObjCMessageExpr>(RetE);
2560
Steve Naroff17c03822009-02-12 17:52:19 +00002561 if (!ME || !Ctx.isObjCIdStructType(PT->getPointeeType()))
Ted Kremenek272aa852008-06-25 21:21:56 +00002562 return RetTy;
2563
2564 ObjCInterfaceDecl* D = ME->getClassInfo().first;
2565
2566 // At this point we know the return type of the message expression is id.
2567 // If we have an ObjCInterceDecl, we know this is a call to a class method
2568 // whose type we can resolve. In such cases, promote the return type to
2569 // Class*.
2570 return !D ? RetTy : Ctx.getPointerType(Ctx.getObjCInterfaceType(D));
2571}
2572
2573
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002574void CFRefCount::EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002575 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002576 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002577 Expr* Ex,
2578 Expr* Receiver,
Ted Kremenek286e9852009-05-04 04:57:00 +00002579 const RetainSummary& Summ,
Zhongxing Xucac107a2009-04-20 05:24:46 +00002580 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002581 ExplodedNode<GRState>* Pred) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002582
Ted Kremeneka7338b42008-03-11 06:39:11 +00002583 // Get the state.
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002584 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenek0106e202008-10-24 20:32:50 +00002585 ASTContext& Ctx = Eng.getStateManager().getContext();
Ted Kremenek227c5372008-05-06 02:41:27 +00002586
2587 // Evaluate the effect of the arguments.
Ted Kremenek1feab292008-04-16 04:28:53 +00002588 RefVal::Kind hasErr = (RefVal::Kind) 0;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002589 unsigned idx = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002590 Expr* ErrorExpr = NULL;
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002591 SymbolRef ErrorSym = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002592
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002593 for (ExprIterator I = arg_beg; I != arg_end; ++I, ++idx) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002594 SVal V = state.GetSValAsScalarOrLoc(*I);
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002595 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002596
Ted Kremenek74556a12009-03-26 03:35:11 +00002597 if (Sym)
Ted Kremenekb6578942009-02-24 19:15:11 +00002598 if (RefBindings::data_type* T = state.get<RefBindings>(Sym)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002599 state = Update(state, Sym, *T, Summ.getArg(idx), hasErr);
Ted Kremenekb6578942009-02-24 19:15:11 +00002600 if (hasErr) {
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002601 ErrorExpr = *I;
Ted Kremenek6064a362008-07-07 16:21:19 +00002602 ErrorSym = Sym;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002603 break;
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002604 }
2605 continue;
Ted Kremenekb6578942009-02-24 19:15:11 +00002606 }
Ted Kremenekede40b72008-07-09 18:11:16 +00002607
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002608 if (isa<Loc>(V)) {
2609 if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(&V)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002610 if (Summ.getArg(idx) == DoNothingByRef)
Ted Kremenekede40b72008-07-09 18:11:16 +00002611 continue;
2612
2613 // Invalidate the value of the variable passed by reference.
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002614
2615 // FIXME: Either this logic should also be replicated in GRSimpleVals
2616 // or should be pulled into a separate "constraint engine."
Ted Kremenekede40b72008-07-09 18:11:16 +00002617
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002618 // FIXME: We can have collisions on the conjured symbol if the
2619 // expression *I also creates conjured symbols. We probably want
2620 // to identify conjured symbols by an expression pair: the enclosing
2621 // expression (the context) and the expression itself. This should
Ted Kremenekede40b72008-07-09 18:11:16 +00002622 // disambiguate conjured symbols.
Ted Kremenekb15eba42008-10-04 05:50:14 +00002623
Ted Kremenek38a4b4b2008-10-17 20:28:54 +00002624 const TypedRegion* R = dyn_cast<TypedRegion>(MR->getRegion());
Zhongxing Xub9d47a42009-04-29 02:30:09 +00002625
Ted Kremenek73ec7732009-05-06 18:19:24 +00002626 if (R) {
2627 // Are we dealing with an ElementRegion? If the element type is
2628 // a basic integer type (e.g., char, int) and the underying region
2629 // is also typed then strip off the ElementRegion.
2630 // FIXME: We really need to think about this for the general case
2631 // as sometimes we are reasoning about arrays and other times
2632 // about (char*), etc., is just a form of passing raw bytes.
2633 // e.g., void *p = alloca(); foo((char*)p);
2634 if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
2635 // Checking for 'integral type' is probably too promiscuous, but
2636 // we'll leave it in for now until we have a systematic way of
2637 // handling all of these cases. Eventually we need to come up
2638 // with an interface to StoreManager so that this logic can be
2639 // approriately delegated to the respective StoreManagers while
2640 // still allowing us to do checker-specific logic (e.g.,
2641 // invalidating reference counts), probably via callbacks.
2642 if (ER->getElementType()->isIntegralType())
2643 if (const TypedRegion *superReg =
2644 dyn_cast<TypedRegion>(ER->getSuperRegion()))
2645 R = superReg;
2646 // FIXME: What about layers of ElementRegions?
2647 }
2648
Ted Kremenek618c6cd2008-12-18 23:34:57 +00002649 // Is the invalidated variable something that we were tracking?
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002650 SymbolRef Sym = state.GetSValAsScalarOrLoc(R).getAsLocSymbol();
Ted Kremenek618c6cd2008-12-18 23:34:57 +00002651
Ted Kremenek53b24182009-03-04 22:56:43 +00002652 // Remove any existing reference-count binding.
Ted Kremenek74556a12009-03-26 03:35:11 +00002653 if (Sym) state = state.remove<RefBindings>(Sym);
Ted Kremenekb15eba42008-10-04 05:50:14 +00002654
Ted Kremenek53b24182009-03-04 22:56:43 +00002655 if (R->isBoundable(Ctx)) {
2656 // Set the value of the variable to be a conjured symbol.
2657 unsigned Count = Builder.getCurrentBlockCount();
Zhongxing Xu20362702009-05-09 03:57:34 +00002658 QualType T = R->getValueType(Ctx);
Ted Kremenek53b24182009-03-04 22:56:43 +00002659
Zhongxing Xu079dc352009-04-09 06:03:54 +00002660 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())){
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002661 ValueManager &ValMgr = Eng.getValueManager();
2662 SVal V = ValMgr.getConjuredSymbolVal(*I, T, Count);
Zhongxing Xu079dc352009-04-09 06:03:54 +00002663 state = state.BindLoc(Loc::MakeVal(R), V);
Ted Kremenek53b24182009-03-04 22:56:43 +00002664 }
2665 else if (const RecordType *RT = T->getAsStructureType()) {
2666 // Handle structs in a not so awesome way. Here we just
2667 // eagerly bind new symbols to the fields. In reality we
2668 // should have the store manager handle this. The idea is just
2669 // to prototype some basic functionality here. All of this logic
2670 // should one day soon just go away.
2671 const RecordDecl *RD = RT->getDecl()->getDefinition(Ctx);
2672
2673 // No record definition. There is nothing we can do.
2674 if (!RD)
2675 continue;
2676
2677 MemRegionManager &MRMgr = state.getManager().getRegionManager();
2678
2679 // Iterate through the fields and construct new symbols.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002680 for (RecordDecl::field_iterator FI=RD->field_begin(Ctx),
2681 FE=RD->field_end(Ctx); FI!=FE; ++FI) {
Ted Kremenek53b24182009-03-04 22:56:43 +00002682
2683 // For now just handle scalar fields.
2684 FieldDecl *FD = *FI;
2685 QualType FT = FD->getType();
2686
2687 if (Loc::IsLocType(FT) ||
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002688 (FT->isIntegerType() && FT->isScalarType())) {
Ted Kremenek53b24182009-03-04 22:56:43 +00002689 const FieldRegion* FR = MRMgr.getFieldRegion(FD, R);
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002690 ValueManager &ValMgr = Eng.getValueManager();
2691 SVal V = ValMgr.getConjuredSymbolVal(*I, FT, Count);
Zhongxing Xuc458e322009-04-09 06:32:20 +00002692 state = state.BindLoc(Loc::MakeVal(FR), V);
Ted Kremenek53b24182009-03-04 22:56:43 +00002693 }
2694 }
2695 }
2696 else {
2697 // Just blast away other values.
2698 state = state.BindLoc(*MR, UnknownVal());
2699 }
Ted Kremenek8f90e712008-10-17 22:23:12 +00002700 }
Ted Kremenekb15eba42008-10-04 05:50:14 +00002701 }
2702 else
Ted Kremenek09102db2008-11-12 19:22:09 +00002703 state = state.BindLoc(*MR, UnknownVal());
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002704 }
2705 else {
2706 // Nuke all other arguments passed by reference.
Zhongxing Xu097fc982008-10-17 05:57:07 +00002707 state = state.Unbind(cast<Loc>(V));
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002708 }
Ted Kremeneke4924202008-04-11 20:51:02 +00002709 }
Zhongxing Xu097fc982008-10-17 05:57:07 +00002710 else if (isa<nonloc::LocAsInteger>(V))
2711 state = state.Unbind(cast<nonloc::LocAsInteger>(V).getLoc());
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002712 }
Ted Kremenek1feab292008-04-16 04:28:53 +00002713
Ted Kremenek272aa852008-06-25 21:21:56 +00002714 // Evaluate the effect on the message receiver.
Ted Kremenek227c5372008-05-06 02:41:27 +00002715 if (!ErrorExpr && Receiver) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002716 SymbolRef Sym = state.GetSValAsScalarOrLoc(Receiver).getAsLocSymbol();
Ted Kremenek74556a12009-03-26 03:35:11 +00002717 if (Sym) {
Ted Kremenekb6578942009-02-24 19:15:11 +00002718 if (const RefVal* T = state.get<RefBindings>(Sym)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002719 state = Update(state, Sym, *T, Summ.getReceiverEffect(), hasErr);
Ted Kremenekb6578942009-02-24 19:15:11 +00002720 if (hasErr) {
Ted Kremenek227c5372008-05-06 02:41:27 +00002721 ErrorExpr = Receiver;
Ted Kremenek6064a362008-07-07 16:21:19 +00002722 ErrorSym = Sym;
Ted Kremenek227c5372008-05-06 02:41:27 +00002723 }
Ted Kremenekb6578942009-02-24 19:15:11 +00002724 }
Ted Kremenek227c5372008-05-06 02:41:27 +00002725 }
2726 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002727
Ted Kremenek272aa852008-06-25 21:21:56 +00002728 // Process any errors.
Ted Kremenek1feab292008-04-16 04:28:53 +00002729 if (hasErr) {
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002730 ProcessNonLeakError(Dst, Builder, Ex, ErrorExpr, Pred, state,
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002731 hasErr, ErrorSym);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002732 return;
Ted Kremenek0d721572008-03-11 17:48:22 +00002733 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002734
Ted Kremenekf2717b02008-07-18 17:24:20 +00002735 // Consult the summary for the return value.
Ted Kremenek286e9852009-05-04 04:57:00 +00002736 RetEffect RE = Summ.getRetEffect();
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002737
2738 switch (RE.getKind()) {
2739 default:
2740 assert (false && "Unhandled RetEffect."); break;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002741
Ted Kremenek8f90e712008-10-17 22:23:12 +00002742 case RetEffect::NoRet: {
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002743
Ted Kremenek455dd862008-04-11 20:23:24 +00002744 // Make up a symbol for the return value (not reference counted).
Ted Kremeneke4924202008-04-11 20:51:02 +00002745 // FIXME: This is basically copy-and-paste from GRSimpleVals. We
2746 // should compose behavior, not copy it.
Ted Kremenek455dd862008-04-11 20:23:24 +00002747
Ted Kremenek8f90e712008-10-17 22:23:12 +00002748 // FIXME: We eventually should handle structs and other compound types
2749 // that are returned by value.
2750
2751 QualType T = Ex->getType();
2752
Ted Kremenek79413a52008-11-13 06:10:40 +00002753 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())) {
Ted Kremenek455dd862008-04-11 20:23:24 +00002754 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002755 ValueManager &ValMgr = Eng.getValueManager();
2756 SVal X = ValMgr.getConjuredSymbolVal(Ex, T, Count);
Ted Kremenek09102db2008-11-12 19:22:09 +00002757 state = state.BindExpr(Ex, X, false);
Ted Kremenek455dd862008-04-11 20:23:24 +00002758 }
2759
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002760 break;
Ted Kremenek8f90e712008-10-17 22:23:12 +00002761 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002762
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002763 case RetEffect::Alias: {
Ted Kremenek272aa852008-06-25 21:21:56 +00002764 unsigned idx = RE.getIndex();
Ted Kremenek2719e982008-06-17 02:43:46 +00002765 assert (arg_end >= arg_beg);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002766 assert (idx < (unsigned) (arg_end - arg_beg));
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002767 SVal V = state.GetSValAsScalarOrLoc(*(arg_beg+idx));
Ted Kremenek09102db2008-11-12 19:22:09 +00002768 state = state.BindExpr(Ex, V, false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002769 break;
2770 }
2771
Ted Kremenek227c5372008-05-06 02:41:27 +00002772 case RetEffect::ReceiverAlias: {
2773 assert (Receiver);
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002774 SVal V = state.GetSValAsScalarOrLoc(Receiver);
Ted Kremenek09102db2008-11-12 19:22:09 +00002775 state = state.BindExpr(Ex, V, false);
Ted Kremenek227c5372008-05-06 02:41:27 +00002776 break;
2777 }
2778
Ted Kremenek6a1cc252008-06-23 18:02:52 +00002779 case RetEffect::OwnedAllocatedSymbol:
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002780 case RetEffect::OwnedSymbol: {
2781 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke9e726e2009-04-09 16:13:17 +00002782 ValueManager &ValMgr = Eng.getValueManager();
2783 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
2784 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
2785 state = state.set<RefBindings>(Sym, RefVal::makeOwned(RE.getObjKind(),
2786 RetT));
2787 state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenek45c52a12009-03-09 22:46:49 +00002788
2789 // FIXME: Add a flag to the checker where allocations are assumed to
2790 // *not fail.
2791#if 0
Ted Kremeneke62fd052009-01-28 22:27:59 +00002792 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) {
2793 bool isFeasible;
2794 state = state.Assume(loc::SymbolVal(Sym), true, isFeasible);
2795 assert(isFeasible && "Cannot assume fresh symbol is non-null.");
2796 }
Ted Kremenek45c52a12009-03-09 22:46:49 +00002797#endif
Ted Kremenek6a1cc252008-06-23 18:02:52 +00002798
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002799 break;
2800 }
Ted Kremenek382fb4e2009-04-27 19:14:45 +00002801
2802 case RetEffect::GCNotOwnedSymbol:
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002803 case RetEffect::NotOwnedSymbol: {
2804 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke9e726e2009-04-09 16:13:17 +00002805 ValueManager &ValMgr = Eng.getValueManager();
2806 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
2807 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
2808 state = state.set<RefBindings>(Sym, RefVal::makeNotOwned(RE.getObjKind(),
2809 RetT));
2810 state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002811 break;
2812 }
2813 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002814
Ted Kremenek0dd65012009-02-18 02:00:25 +00002815 // Generate a sink node if we are at the end of a path.
2816 GRExprEngine::NodeTy *NewNode =
Ted Kremenek286e9852009-05-04 04:57:00 +00002817 Summ.isEndPath() ? Builder.MakeSinkNode(Dst, Ex, Pred, state)
2818 : Builder.MakeNode(Dst, Ex, Pred, state);
Ted Kremenek0dd65012009-02-18 02:00:25 +00002819
2820 // Annotate the edge with summary we used.
Ted Kremenek286e9852009-05-04 04:57:00 +00002821 if (NewNode) SummaryLog[NewNode] = &Summ;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002822}
2823
2824
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002825void CFRefCount::EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002826 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002827 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu097fc982008-10-17 05:57:07 +00002828 CallExpr* CE, SVal L,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002829 ExplodedNode<GRState>* Pred) {
Zhongxing Xucac107a2009-04-20 05:24:46 +00002830 const FunctionDecl* FD = L.getAsFunctionDecl();
Ted Kremenek286e9852009-05-04 04:57:00 +00002831 RetainSummary* Summ = !FD ? Summaries.getDefaultSummary()
Zhongxing Xucac107a2009-04-20 05:24:46 +00002832 : Summaries.getSummary(const_cast<FunctionDecl*>(FD));
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002833
Ted Kremenek286e9852009-05-04 04:57:00 +00002834 assert(Summ);
2835 EvalSummary(Dst, Eng, Builder, CE, 0, *Summ,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002836 CE->arg_begin(), CE->arg_end(), Pred);
Ted Kremenek827f93b2008-03-06 00:08:09 +00002837}
Ted Kremeneka7338b42008-03-11 06:39:11 +00002838
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002839void CFRefCount::EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002840 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002841 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002842 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002843 ExplodedNode<GRState>* Pred) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002844 RetainSummary* Summ = 0;
Ted Kremenek33661802008-05-01 21:31:50 +00002845
Ted Kremenek272aa852008-06-25 21:21:56 +00002846 if (Expr* Receiver = ME->getReceiver()) {
2847 // We need the type-information of the tracked receiver object
2848 // Retrieve it from the state.
2849 ObjCInterfaceDecl* ID = 0;
2850
2851 // FIXME: Wouldn't it be great if this code could be reduced? It's just
2852 // a chain of lookups.
Ted Kremeneka821b792009-04-29 05:04:30 +00002853 // FIXME: Is this really working as expected? There are cases where
2854 // we just use the 'ID' from the message expression.
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002855 const GRState* St = Builder.GetState(Pred);
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002856 SVal V = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
Ted Kremenek272aa852008-06-25 21:21:56 +00002857
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002858 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenek74556a12009-03-26 03:35:11 +00002859 if (Sym) {
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002860 if (const RefVal* T = St->get<RefBindings>(Sym)) {
Ted Kremenek6064a362008-07-07 16:21:19 +00002861 QualType Ty = T->getType();
Ted Kremenek272aa852008-06-25 21:21:56 +00002862
2863 if (const PointerType* PT = Ty->getAsPointerType()) {
2864 QualType PointeeTy = PT->getPointeeType();
2865
2866 if (ObjCInterfaceType* IT = dyn_cast<ObjCInterfaceType>(PointeeTy))
2867 ID = IT->getDecl();
2868 }
2869 }
2870 }
2871
Ted Kremenek04e00302009-04-29 17:09:14 +00002872 // FIXME: The receiver could be a reference to a class, meaning that
2873 // we should use the class method.
2874 Summ = Summaries.getInstanceMethodSummary(ME, ID);
Ted Kremenek0106e202008-10-24 20:32:50 +00002875
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002876 // Special-case: are we sending a mesage to "self"?
2877 // This is a hack. When we have full-IP this should be removed.
Ted Kremenek2f226732009-05-04 05:31:22 +00002878 if (isa<ObjCMethodDecl>(&Eng.getGraph().getCodeDecl())) {
2879 if (Expr* Receiver = ME->getReceiver()) {
2880 SVal X = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
2881 if (loc::MemRegionVal* L = dyn_cast<loc::MemRegionVal>(&X))
2882 if (L->getRegion() == Eng.getStateManager().getSelfRegion(St)) {
2883 // Update the summary to make the default argument effect
2884 // 'StopTracking'.
2885 Summ = Summaries.copySummary(Summ);
2886 Summ->setDefaultArgEffect(StopTracking);
2887 }
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002888 }
2889 }
Ted Kremenek272aa852008-06-25 21:21:56 +00002890 }
Ted Kremenek1feab292008-04-16 04:28:53 +00002891 else
Ted Kremenekb17fa952009-04-23 21:25:57 +00002892 Summ = Summaries.getClassMethodSummary(ME);
Ted Kremenek1feab292008-04-16 04:28:53 +00002893
Ted Kremenek286e9852009-05-04 04:57:00 +00002894 if (!Summ)
2895 Summ = Summaries.getDefaultSummary();
Ted Kremenekccbe79a2009-04-24 17:50:11 +00002896
Ted Kremenek286e9852009-05-04 04:57:00 +00002897 EvalSummary(Dst, Eng, Builder, ME, ME->getReceiver(), *Summ,
Ted Kremenek926abf22008-05-06 04:20:12 +00002898 ME->arg_begin(), ME->arg_end(), Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002899}
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002900
2901namespace {
2902class VISIBILITY_HIDDEN StopTrackingCallback : public SymbolVisitor {
2903 GRStateRef state;
2904public:
2905 StopTrackingCallback(GRStateRef st) : state(st) {}
2906 GRStateRef getState() { return state; }
2907
2908 bool VisitSymbol(SymbolRef sym) {
2909 state = state.remove<RefBindings>(sym);
2910 return true;
2911 }
Ted Kremenek926abf22008-05-06 04:20:12 +00002912
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002913 const GRState* getState() const { return state.getState(); }
2914};
2915} // end anonymous namespace
2916
2917
Ted Kremeneka42be302009-02-14 01:43:44 +00002918void CFRefCount::EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val) {
Ted Kremeneka42be302009-02-14 01:43:44 +00002919 // Are we storing to something that causes the value to "escape"?
Ted Kremenek7aef4842008-04-16 20:40:59 +00002920 bool escapes = false;
2921
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002922 // A value escapes in three possible cases (this may change):
2923 //
2924 // (1) we are binding to something that is not a memory region.
2925 // (2) we are binding to a memregion that does not have stack storage
2926 // (3) we are binding to a memregion with stack storage that the store
Ted Kremeneka42be302009-02-14 01:43:44 +00002927 // does not understand.
Ted Kremeneka42be302009-02-14 01:43:44 +00002928 GRStateRef state = B.getState();
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002929
Ted Kremeneka42be302009-02-14 01:43:44 +00002930 if (!isa<loc::MemRegionVal>(location))
Ted Kremenek7aef4842008-04-16 20:40:59 +00002931 escapes = true;
Ted Kremenekb15eba42008-10-04 05:50:14 +00002932 else {
Ted Kremeneka42be302009-02-14 01:43:44 +00002933 const MemRegion* R = cast<loc::MemRegionVal>(location).getRegion();
2934 escapes = !B.getStateManager().hasStackStorage(R);
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002935
2936 if (!escapes) {
2937 // To test (3), generate a new state with the binding removed. If it is
2938 // the same state, then it escapes (since the store cannot represent
2939 // the binding).
Ted Kremeneka42be302009-02-14 01:43:44 +00002940 escapes = (state == (state.BindLoc(cast<Loc>(location), UnknownVal())));
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002941 }
Ted Kremenekb15eba42008-10-04 05:50:14 +00002942 }
Ted Kremeneka42be302009-02-14 01:43:44 +00002943
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002944 // If our store can represent the binding and we aren't storing to something
2945 // that doesn't have local storage then just return and have the simulation
2946 // state continue as is.
2947 if (!escapes)
2948 return;
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002949
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002950 // Otherwise, find all symbols referenced by 'val' that we are tracking
2951 // and stop tracking them.
2952 B.MakeNode(state.scanReachableSymbols<StopTrackingCallback>(val).getState());
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002953}
2954
Ted Kremenek541db372008-04-24 23:57:27 +00002955
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002956 // Return statements.
2957
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002958void CFRefCount::EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002959 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002960 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002961 ReturnStmt* S,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002962 ExplodedNode<GRState>* Pred) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002963
2964 Expr* RetE = S->getRetValue();
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002965 if (!RetE)
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002966 return;
2967
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002968 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002969 SymbolRef Sym = state.GetSValAsScalarOrLoc(RetE).getAsLocSymbol();
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002970
Ted Kremenek74556a12009-03-26 03:35:11 +00002971 if (!Sym)
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002972 return;
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00002973
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002974 // Get the reference count binding (if any).
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002975 const RefVal* T = state.get<RefBindings>(Sym);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002976
2977 if (!T)
2978 return;
2979
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002980 // Change the reference count.
Ted Kremenek6064a362008-07-07 16:21:19 +00002981 RefVal X = *T;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002982
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002983 switch (X.getKind()) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002984 case RefVal::Owned: {
2985 unsigned cnt = X.getCount();
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00002986 assert (cnt > 0);
Ted Kremenekbd271be2009-05-10 05:11:21 +00002987 X.setCount(cnt - 1);
2988 X = X ^ RefVal::ReturnedOwned;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002989 break;
2990 }
2991
2992 case RefVal::NotOwned: {
2993 unsigned cnt = X.getCount();
Ted Kremenekbd271be2009-05-10 05:11:21 +00002994 if (cnt) {
2995 X.setCount(cnt - 1);
2996 X = X ^ RefVal::ReturnedOwned;
2997 }
2998 else {
2999 X = X ^ RefVal::ReturnedNotOwned;
3000 }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003001 break;
3002 }
3003
3004 default:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003005 return;
3006 }
3007
3008 // Update the binding.
Ted Kremenek91781202008-08-17 03:20:02 +00003009 state = state.set<RefBindings>(Sym, X);
Ted Kremenek47a72422009-04-29 18:50:19 +00003010 Pred = Builder.MakeNode(Dst, S, Pred, state);
3011
Ted Kremeneka208d0c2009-04-30 05:51:50 +00003012 // Did we cache out?
3013 if (!Pred)
3014 return;
Ted Kremenekbd271be2009-05-10 05:11:21 +00003015
3016 // Update the autorelease counts.
3017 static unsigned autoreleasetag = 0;
3018 GenericNodeBuilder Bd(Builder, S, &autoreleasetag);
3019 bool stop = false;
3020 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state , Bd, Pred, Eng, Sym,
3021 X, stop);
3022
3023 // Did we cache out?
3024 if (!Pred || stop)
3025 return;
3026
3027 // Get the updated binding.
3028 T = state.get<RefBindings>(Sym);
3029 assert(T);
3030 X = *T;
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003031
Ted Kremenek47a72422009-04-29 18:50:19 +00003032 // Any leaks or other errors?
3033 if (X.isReturnedOwned() && X.getCount() == 0) {
3034 const Decl *CD = &Eng.getStateManager().getCodeDecl();
3035
Ted Kremenek314b1952009-04-29 23:03:22 +00003036 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00003037 const RetainSummary &Summ = *Summaries.getMethodSummary(MD);
3038 if (!Summ.getRetEffect().isOwned()) {
Ted Kremenek47a72422009-04-29 18:50:19 +00003039 static int ReturnOwnLeakTag = 0;
3040 state = state.set<RefBindings>(Sym, X ^ RefVal::ErrorLeakReturned);
Ted Kremenek47a72422009-04-29 18:50:19 +00003041 // Generate an error node.
Ted Kremeneka208d0c2009-04-30 05:51:50 +00003042 if (ExplodedNode<GRState> *N =
3043 Builder.generateNode(PostStmt(S, &ReturnOwnLeakTag), state, Pred)) {
3044 CFRefLeakReport *report =
3045 new CFRefLeakReport(*static_cast<CFRefBug*>(leakAtReturn), *this,
3046 N, Sym, Eng);
3047 BR->EmitReport(report);
3048 }
Ted Kremenek47a72422009-04-29 18:50:19 +00003049 }
3050 }
3051 }
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003052
3053
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003054}
3055
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003056// Assumptions.
3057
Ted Kremenekabd89ac2008-08-13 04:27:00 +00003058const GRState* CFRefCount::EvalAssume(GRStateManager& VMgr,
3059 const GRState* St,
Zhongxing Xu097fc982008-10-17 05:57:07 +00003060 SVal Cond, bool Assumption,
Ted Kremenekf22f8682008-07-10 22:03:41 +00003061 bool& isFeasible) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003062
3063 // FIXME: We may add to the interface of EvalAssume the list of symbols
3064 // whose assumptions have changed. For now we just iterate through the
3065 // bindings and check if any of the tracked symbols are NULL. This isn't
3066 // too bad since the number of symbols we will track in practice are
3067 // probably small and EvalAssume is only called at branches and a few
3068 // other places.
Ted Kremenek4ae925c2008-08-14 21:16:54 +00003069 RefBindings B = St->get<RefBindings>();
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003070
3071 if (B.isEmpty())
3072 return St;
3073
3074 bool changed = false;
Ted Kremenek91781202008-08-17 03:20:02 +00003075
3076 GRStateRef state(St, VMgr);
3077 RefBindings::Factory& RefBFactory = state.get_context<RefBindings>();
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003078
3079 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003080 // Check if the symbol is null (or equal to any constant).
3081 // If this is the case, stop tracking the symbol.
Zhongxing Xuc6b27d02008-08-29 14:52:36 +00003082 if (VMgr.getSymVal(St, I.getKey())) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003083 changed = true;
3084 B = RefBFactory.Remove(B, I.getKey());
3085 }
3086 }
3087
Ted Kremenek91781202008-08-17 03:20:02 +00003088 if (changed)
3089 state = state.set<RefBindings>(B);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003090
Ted Kremenek4ae925c2008-08-14 21:16:54 +00003091 return state;
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003092}
Ted Kremeneka7338b42008-03-11 06:39:11 +00003093
Ted Kremenekb6578942009-02-24 19:15:11 +00003094GRStateRef CFRefCount::Update(GRStateRef state, SymbolRef sym,
3095 RefVal V, ArgEffect E,
3096 RefVal::Kind& hasErr) {
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003097
3098 // In GC mode [... release] and [... retain] do nothing.
3099 switch (E) {
3100 default: break;
3101 case IncRefMsg: E = isGCEnabled() ? DoNothing : IncRef; break;
3102 case DecRefMsg: E = isGCEnabled() ? DoNothing : DecRef; break;
Ted Kremenek2126bef2009-02-18 21:57:45 +00003103 case MakeCollectable: E = isGCEnabled() ? DecRef : DoNothing; break;
Ted Kremenekaac82832009-02-23 17:45:03 +00003104 case NewAutoreleasePool: E = isGCEnabled() ? DoNothing :
3105 NewAutoreleasePool; break;
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003106 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00003107
Ted Kremenek6537a642009-03-17 19:42:23 +00003108 // Handle all use-after-releases.
3109 if (!isGCEnabled() && V.getKind() == RefVal::Released) {
3110 V = V ^ RefVal::ErrorUseAfterRelease;
3111 hasErr = V.getKind();
3112 return state.set<RefBindings>(sym, V);
3113 }
3114
Ted Kremenek0d721572008-03-11 17:48:22 +00003115 switch (E) {
3116 default:
3117 assert (false && "Unhandled CFRef transition.");
Ted Kremenek6537a642009-03-17 19:42:23 +00003118
3119 case Dealloc:
3120 // Any use of -dealloc in GC is *bad*.
3121 if (isGCEnabled()) {
3122 V = V ^ RefVal::ErrorDeallocGC;
3123 hasErr = V.getKind();
3124 break;
3125 }
3126
3127 switch (V.getKind()) {
3128 default:
3129 assert(false && "Invalid case.");
3130 case RefVal::Owned:
3131 // The object immediately transitions to the released state.
3132 V = V ^ RefVal::Released;
3133 V.clearCounts();
3134 return state.set<RefBindings>(sym, V);
3135 case RefVal::NotOwned:
3136 V = V ^ RefVal::ErrorDeallocNotOwned;
3137 hasErr = V.getKind();
3138 break;
3139 }
3140 break;
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003141
Ted Kremenekb7826ab2009-02-25 23:11:49 +00003142 case NewAutoreleasePool:
3143 assert(!isGCEnabled());
3144 return state.add<AutoreleaseStack>(sym);
3145
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003146 case MayEscape:
3147 if (V.getKind() == RefVal::Owned) {
Ted Kremenek272aa852008-06-25 21:21:56 +00003148 V = V ^ RefVal::NotOwned;
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003149 break;
3150 }
Ted Kremenek6537a642009-03-17 19:42:23 +00003151
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003152 // Fall-through.
Ted Kremenek1b4b6562009-02-25 02:54:57 +00003153
Ted Kremenekede40b72008-07-09 18:11:16 +00003154 case DoNothingByRef:
Ted Kremenek0d721572008-03-11 17:48:22 +00003155 case DoNothing:
Ted Kremenekb6578942009-02-24 19:15:11 +00003156 return state;
Ted Kremeneke5a4bb02008-06-30 16:57:41 +00003157
Ted Kremenek9b112d22009-01-28 21:44:40 +00003158 case Autorelease:
Ted Kremenek6537a642009-03-17 19:42:23 +00003159 if (isGCEnabled())
3160 return state;
Ted Kremenek681fb352009-03-20 17:34:15 +00003161
3162 // Update the autorelease counts.
3163 state = SendAutorelease(state, ARCountFactory, sym);
Ted Kremenek4d99d342009-05-08 20:01:42 +00003164 V = V.autorelease();
Ted Kremenek3e3328d2009-05-09 01:50:57 +00003165 break;
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003166
Ted Kremenek227c5372008-05-06 02:41:27 +00003167 case StopTracking:
Ted Kremenekb6578942009-02-24 19:15:11 +00003168 return state.remove<RefBindings>(sym);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003169
Ted Kremenek0d721572008-03-11 17:48:22 +00003170 case IncRef:
3171 switch (V.getKind()) {
3172 default:
3173 assert(false);
3174
3175 case RefVal::Owned:
Ted Kremenek0d721572008-03-11 17:48:22 +00003176 case RefVal::NotOwned:
Ted Kremenek272aa852008-06-25 21:21:56 +00003177 V = V + 1;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003178 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003179 case RefVal::Released:
Ted Kremenek6537a642009-03-17 19:42:23 +00003180 // Non-GC cases are handled above.
3181 assert(isGCEnabled());
3182 V = (V ^ RefVal::Owned) + 1;
Ted Kremenek0d721572008-03-11 17:48:22 +00003183 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003184 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00003185 break;
3186
Ted Kremenek272aa852008-06-25 21:21:56 +00003187 case SelfOwn:
3188 V = V ^ RefVal::NotOwned;
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003189 // Fall-through.
Ted Kremenek0d721572008-03-11 17:48:22 +00003190 case DecRef:
3191 switch (V.getKind()) {
3192 default:
Ted Kremenek6537a642009-03-17 19:42:23 +00003193 // case 'RefVal::Released' handled above.
Ted Kremenek0d721572008-03-11 17:48:22 +00003194 assert (false);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003195
Ted Kremenek272aa852008-06-25 21:21:56 +00003196 case RefVal::Owned:
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00003197 assert(V.getCount() > 0);
3198 if (V.getCount() == 1) V = V ^ RefVal::Released;
3199 V = V - 1;
Ted Kremenek0d721572008-03-11 17:48:22 +00003200 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003201
Ted Kremenek272aa852008-06-25 21:21:56 +00003202 case RefVal::NotOwned:
3203 if (V.getCount() > 0)
3204 V = V - 1;
Ted Kremenekc4f81022008-04-10 23:09:18 +00003205 else {
Ted Kremenek272aa852008-06-25 21:21:56 +00003206 V = V ^ RefVal::ErrorReleaseNotOwned;
Ted Kremenek1feab292008-04-16 04:28:53 +00003207 hasErr = V.getKind();
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003208 }
Ted Kremenek0d721572008-03-11 17:48:22 +00003209 break;
Ted Kremenek6537a642009-03-17 19:42:23 +00003210
Ted Kremenek0d721572008-03-11 17:48:22 +00003211 case RefVal::Released:
Ted Kremenek6537a642009-03-17 19:42:23 +00003212 // Non-GC cases are handled above.
3213 assert(isGCEnabled());
Ted Kremenek272aa852008-06-25 21:21:56 +00003214 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek1feab292008-04-16 04:28:53 +00003215 hasErr = V.getKind();
Ted Kremenek6537a642009-03-17 19:42:23 +00003216 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003217 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00003218 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003219 }
Ted Kremenekb6578942009-02-24 19:15:11 +00003220 return state.set<RefBindings>(sym, V);
Ted Kremeneka7338b42008-03-11 06:39:11 +00003221}
3222
Ted Kremenek10fe66d2008-04-09 01:10:13 +00003223//===----------------------------------------------------------------------===//
Ted Kremenek708af042009-02-05 06:50:21 +00003224// Handle dead symbols and end-of-path.
3225//===----------------------------------------------------------------------===//
3226
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003227std::pair<ExplodedNode<GRState>*, GRStateRef>
3228CFRefCount::HandleAutoreleaseCounts(GRStateRef state, GenericNodeBuilder Bd,
3229 ExplodedNode<GRState>* Pred,
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003230 GRExprEngine &Eng,
3231 SymbolRef Sym, RefVal V, bool &stop) {
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003232
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003233 unsigned ACnt = V.getAutoreleaseCount();
3234 stop = false;
3235
3236 // No autorelease counts? Nothing to be done.
3237 if (!ACnt)
3238 return std::make_pair(Pred, state);
3239
3240 assert(!isGCEnabled() && "Autorelease counts in GC mode?");
3241 unsigned Cnt = V.getCount();
3242
3243 if (ACnt <= Cnt) {
Ted Kremenek3f15aba2009-05-09 00:44:07 +00003244 if (ACnt == Cnt) {
3245 V.clearCounts();
3246 V = V ^ RefVal::NotOwned;
3247 }
3248 else {
3249 V.setCount(Cnt - ACnt);
3250 V.setAutoreleaseCount(0);
3251 }
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003252 state = state.set<RefBindings>(Sym, V);
3253 ExplodedNode<GRState> *N = Bd.MakeNode(state, Pred);
3254 stop = (N == 0);
3255 return std::make_pair(N, state);
3256 }
3257
3258 // Woah! More autorelease counts then retain counts left.
3259 // Emit hard error.
3260 stop = true;
3261 V = V ^ RefVal::ErrorOverAutorelease;
3262 state = state.set<RefBindings>(Sym, V);
3263
3264 if (ExplodedNode<GRState> *N = Bd.MakeNode(state, Pred)) {
Ted Kremenek3f15aba2009-05-09 00:44:07 +00003265 N->markAsSink();
Ted Kremenekbd271be2009-05-10 05:11:21 +00003266
3267 std::string sbuf;
3268 llvm::raw_string_ostream os(sbuf);
3269 os << "Object over-autoreleased: object was sent -autorelease " ;
3270 if (V.getAutoreleaseCount() > 1)
3271 os << V.getAutoreleaseCount() << " times";
3272 os << " but the object has ";
3273 if (V.getCount() == 0)
3274 os << "zero (locally visible)";
3275 else
3276 os << "+" << V.getCount();
3277 os << " retain counts";
3278
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003279 CFRefReport *report =
3280 new CFRefReport(*static_cast<CFRefBug*>(overAutorelease),
Ted Kremenekbd271be2009-05-10 05:11:21 +00003281 *this, N, Sym, os.str().c_str());
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003282 BR->EmitReport(report);
3283 }
3284
3285 return std::make_pair((ExplodedNode<GRState>*)0, state);
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003286}
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003287
3288GRStateRef
3289CFRefCount::HandleSymbolDeath(GRStateRef state, SymbolRef sid, RefVal V,
3290 llvm::SmallVectorImpl<SymbolRef> &Leaked) {
3291
3292 bool hasLeak = V.isOwned() ||
3293 ((V.isNotOwned() || V.isReturnedOwned()) && V.getCount() > 0);
3294
3295 if (!hasLeak)
3296 return state.remove<RefBindings>(sid);
3297
3298 Leaked.push_back(sid);
3299 return state.set<RefBindings>(sid, V ^ RefVal::ErrorLeak);
3300}
3301
3302ExplodedNode<GRState>*
3303CFRefCount::ProcessLeaks(GRStateRef state,
3304 llvm::SmallVectorImpl<SymbolRef> &Leaked,
3305 GenericNodeBuilder &Builder,
3306 GRExprEngine& Eng,
3307 ExplodedNode<GRState> *Pred) {
3308
3309 if (Leaked.empty())
3310 return Pred;
3311
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003312 // Generate an intermediate node representing the leak point.
Ted Kremenek3e3328d2009-05-09 01:50:57 +00003313 ExplodedNode<GRState> *N = Builder.MakeNode(state, Pred);
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003314
3315 if (N) {
3316 for (llvm::SmallVectorImpl<SymbolRef>::iterator
3317 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3318
3319 CFRefBug *BT = static_cast<CFRefBug*>(Pred ? leakWithinFunction
3320 : leakAtReturn);
3321 assert(BT && "BugType not initialized.");
3322 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N, *I, Eng);
3323 BR->EmitReport(report);
3324 }
3325 }
3326
3327 return N;
3328}
3329
Ted Kremenek708af042009-02-05 06:50:21 +00003330void CFRefCount::EvalEndPath(GRExprEngine& Eng,
3331 GREndPathNodeBuilder<GRState>& Builder) {
3332
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003333 GRStateRef state(Builder.getState(), Eng.getStateManager());
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003334 GenericNodeBuilder Bd(Builder);
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003335 RefBindings B = state.get<RefBindings>();
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003336 ExplodedNode<GRState> *Pred = 0;
3337
3338 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003339 bool stop = false;
3340 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state, Bd, Pred, Eng,
3341 (*I).first,
3342 (*I).second, stop);
3343
3344 if (stop)
3345 return;
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003346 }
3347
3348 B = state.get<RefBindings>();
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003349 llvm::SmallVector<SymbolRef, 10> Leaked;
Ted Kremenek708af042009-02-05 06:50:21 +00003350
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003351 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I)
3352 state = HandleSymbolDeath(state, (*I).first, (*I).second, Leaked);
3353
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003354 ProcessLeaks(state, Leaked, Bd, Eng, Pred);
Ted Kremenek708af042009-02-05 06:50:21 +00003355}
3356
3357void CFRefCount::EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
3358 GRExprEngine& Eng,
3359 GRStmtNodeBuilder<GRState>& Builder,
3360 ExplodedNode<GRState>* Pred,
3361 Stmt* S,
3362 const GRState* St,
3363 SymbolReaper& SymReaper) {
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003364
3365 GRStateRef state(St, Eng.getStateManager());
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003366 RefBindings B = state.get<RefBindings>();
3367
3368 // Update counts from autorelease pools
3369 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3370 E = SymReaper.dead_end(); I != E; ++I) {
3371 SymbolRef Sym = *I;
3372 if (const RefVal* T = B.lookup(Sym)){
3373 // Use the symbol as the tag.
3374 // FIXME: This might not be as unique as we would like.
3375 GenericNodeBuilder Bd(Builder, S, Sym);
Ted Kremenek412ca1e2009-05-09 00:10:05 +00003376 bool stop = false;
3377 llvm::tie(Pred, state) = HandleAutoreleaseCounts(state, Bd, Pred, Eng,
3378 Sym, *T, stop);
3379 if (stop)
3380 return;
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003381 }
3382 }
3383
3384 B = state.get<RefBindings>();
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003385 llvm::SmallVector<SymbolRef, 10> Leaked;
Ted Kremenek708af042009-02-05 06:50:21 +00003386
3387 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003388 E = SymReaper.dead_end(); I != E; ++I) {
3389 if (const RefVal* T = B.lookup(*I))
3390 state = HandleSymbolDeath(state, *I, *T, Leaked);
3391 }
Ted Kremenek708af042009-02-05 06:50:21 +00003392
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003393 static unsigned LeakPPTag = 0;
Ted Kremenekbb5ff5a2009-05-08 23:32:51 +00003394 {
3395 GenericNodeBuilder Bd(Builder, S, &LeakPPTag);
3396 Pred = ProcessLeaks(state, Leaked, Bd, Eng, Pred);
3397 }
Ted Kremenek708af042009-02-05 06:50:21 +00003398
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003399 // Did we cache out?
3400 if (!Pred)
3401 return;
Ted Kremenek876d8df2009-02-19 23:47:02 +00003402
3403 // Now generate a new node that nukes the old bindings.
Ted Kremenek876d8df2009-02-19 23:47:02 +00003404 RefBindings::Factory& F = state.get_context<RefBindings>();
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003405
Ted Kremenek876d8df2009-02-19 23:47:02 +00003406 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003407 E = SymReaper.dead_end(); I!=E; ++I) B = F.Remove(B, *I);
3408
Ted Kremenek876d8df2009-02-19 23:47:02 +00003409 state = state.set<RefBindings>(B);
3410 Builder.MakeNode(Dst, S, Pred, state);
Ted Kremenek708af042009-02-05 06:50:21 +00003411}
3412
3413void CFRefCount::ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
3414 GRStmtNodeBuilder<GRState>& Builder,
3415 Expr* NodeExpr, Expr* ErrorExpr,
3416 ExplodedNode<GRState>* Pred,
3417 const GRState* St,
3418 RefVal::Kind hasErr, SymbolRef Sym) {
3419 Builder.BuildSinks = true;
3420 GRExprEngine::NodeTy* N = Builder.MakeNode(Dst, NodeExpr, Pred, St);
3421
Ted Kremenek3e3328d2009-05-09 01:50:57 +00003422 if (!N)
3423 return;
Ted Kremenek708af042009-02-05 06:50:21 +00003424
3425 CFRefBug *BT = 0;
3426
Ted Kremenek6537a642009-03-17 19:42:23 +00003427 switch (hasErr) {
3428 default:
3429 assert(false && "Unhandled error.");
3430 return;
3431 case RefVal::ErrorUseAfterRelease:
3432 BT = static_cast<CFRefBug*>(useAfterRelease);
3433 break;
3434 case RefVal::ErrorReleaseNotOwned:
3435 BT = static_cast<CFRefBug*>(releaseNotOwned);
3436 break;
3437 case RefVal::ErrorDeallocGC:
3438 BT = static_cast<CFRefBug*>(deallocGC);
3439 break;
3440 case RefVal::ErrorDeallocNotOwned:
3441 BT = static_cast<CFRefBug*>(deallocNotOwned);
3442 break;
Ted Kremenek708af042009-02-05 06:50:21 +00003443 }
3444
Ted Kremenekc26c4692009-02-18 03:48:14 +00003445 CFRefReport *report = new CFRefReport(*BT, *this, N, Sym);
Ted Kremenek708af042009-02-05 06:50:21 +00003446 report->addRange(ErrorExpr->getSourceRange());
3447 BR->EmitReport(report);
3448}
3449
3450//===----------------------------------------------------------------------===//
Ted Kremenekb1983ba2008-04-10 22:16:52 +00003451// Transfer function creation for external clients.
Ted Kremeneka7338b42008-03-11 06:39:11 +00003452//===----------------------------------------------------------------------===//
3453
Ted Kremenekfe30beb2008-04-30 23:47:44 +00003454GRTransferFuncs* clang::MakeCFRefCountTF(ASTContext& Ctx, bool GCEnabled,
3455 const LangOptions& lopts) {
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00003456 return new CFRefCount(Ctx, GCEnabled, lopts);
Ted Kremeneka4c74292008-04-10 22:58:08 +00003457}