blob: 3c3441156a2040bba6eb5eba5041b4efa2ee2f10 [file] [log] [blame]
Chris Lattnerbe1a7a02008-03-15 23:59:48 +00001// CFRefCount.cpp - Transfer functions for tracking simple values -*- C++ -*--//
Ted Kremenek827f93b2008-03-06 00:08:09 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Gabor Greif2224fcb2008-03-06 10:40:09 +000010// This file defines the methods for CFRefCount, which implements
Ted Kremenek827f93b2008-03-06 00:08:09 +000011// a reference count checker for Core Foundation (Mac OS X).
12//
13//===----------------------------------------------------------------------===//
14
Ted Kremeneka7338b42008-03-11 06:39:11 +000015#include "GRSimpleVals.h"
Ted Kremenekfe30beb2008-04-30 23:47:44 +000016#include "clang/Basic/LangOptions.h"
Ted Kremenekfe4d2312008-05-01 23:13:35 +000017#include "clang/Basic/SourceManager.h"
Ted Kremeneka42be302009-02-14 01:43:44 +000018#include "clang/Analysis/PathSensitive/GRExprEngineBuilders.h"
Ted Kremenek91781202008-08-17 03:20:02 +000019#include "clang/Analysis/PathSensitive/GRStateTrait.h"
Ted Kremenekdd0126b2008-03-31 18:26:32 +000020#include "clang/Analysis/PathDiagnostic.h"
Ted Kremenek827f93b2008-03-06 00:08:09 +000021#include "clang/Analysis/LocalCheckers.h"
Ted Kremenek10fe66d2008-04-09 01:10:13 +000022#include "clang/Analysis/PathDiagnostic.h"
23#include "clang/Analysis/PathSensitive/BugReporter.h"
Ted Kremenek2ddb4b22009-02-14 03:16:10 +000024#include "clang/Analysis/PathSensitive/SymbolManager.h"
Ted Kremenekc3bc6c82009-05-06 21:39:49 +000025#include "clang/AST/DeclObjC.h"
Ted Kremeneka7338b42008-03-11 06:39:11 +000026#include "llvm/ADT/DenseMap.h"
27#include "llvm/ADT/FoldingSet.h"
28#include "llvm/ADT/ImmutableMap.h"
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +000029#include "llvm/ADT/ImmutableList.h"
Ted Kremenek2ac4ba62008-05-07 18:36:45 +000030#include "llvm/ADT/StringExtras.h"
Ted Kremenek10fe66d2008-04-09 01:10:13 +000031#include "llvm/Support/Compiler.h"
Ted Kremenekd7e26782008-05-16 18:33:44 +000032#include "llvm/ADT/STLExtras.h"
Ted Kremenek3b11f7a2008-03-11 19:44:10 +000033#include <ostream>
Ted Kremenek9449ca92008-08-12 20:41:56 +000034#include <stdarg.h>
Ted Kremenek827f93b2008-03-06 00:08:09 +000035
36using namespace clang;
Ted Kremenekb6f09542008-10-24 21:18:08 +000037
38//===----------------------------------------------------------------------===//
39// Utility functions.
40//===----------------------------------------------------------------------===//
41
Ted Kremenekb6f09542008-10-24 21:18:08 +000042// The "fundamental rule" for naming conventions of methods:
43// (url broken into two lines)
44// http://developer.apple.com/documentation/Cocoa/Conceptual/
45// MemoryMgmt/Tasks/MemoryManagementRules.html
46//
47// "You take ownership of an object if you create it using a method whose name
48// begins with “alloc” or “new” or contains “copy” (for example, alloc,
49// newObject, or mutableCopy), or if you send it a retain message. You are
50// responsible for relinquishing ownership of objects you own using release
51// or autorelease. Any other time you receive an object, you must
52// not release it."
53//
Ted Kremenek4395b452009-02-21 05:13:43 +000054
55using llvm::CStrInCStrNoCase;
Ted Kremenekfd42ffc2009-02-21 18:26:02 +000056using llvm::StringsEqualNoCase;
Ted Kremenek4395b452009-02-21 05:13:43 +000057
58enum NamingConvention { NoConvention, CreateRule, InitRule };
59
60static inline bool isWordEnd(char ch, char prev, char next) {
61 return ch == '\0'
62 || (islower(prev) && isupper(ch)) // xxxC
63 || (isupper(prev) && isupper(ch) && islower(next)) // XXCreate
64 || !isalpha(ch);
65}
66
67static inline const char* parseWord(const char* s) {
68 char ch = *s, prev = '\0';
69 assert(ch != '\0');
70 char next = *(s+1);
71 while (!isWordEnd(ch, prev, next)) {
72 prev = ch;
73 ch = next;
74 next = *((++s)+1);
75 }
76 return s;
77}
78
79static NamingConvention deriveNamingConvention(const char* s) {
80 // A method/function name may contain a prefix. We don't know it is there,
81 // however, until we encounter the first '_'.
82 bool InPossiblePrefix = true;
83 bool AtBeginning = true;
84 NamingConvention C = NoConvention;
85
86 while (*s != '\0') {
87 // Skip '_'.
88 if (*s == '_') {
89 if (InPossiblePrefix) {
90 InPossiblePrefix = false;
91 AtBeginning = true;
92 // Discard whatever 'convention' we
93 // had already derived since it occurs
94 // in the prefix.
95 C = NoConvention;
96 }
97 ++s;
98 continue;
99 }
100
101 // Skip numbers, ':', etc.
102 if (!isalpha(*s)) {
103 ++s;
104 continue;
105 }
106
107 const char *wordEnd = parseWord(s);
108 assert(wordEnd > s);
109 unsigned len = wordEnd - s;
110
111 switch (len) {
112 default:
113 break;
114 case 3:
115 // Methods starting with 'new' follow the create rule.
Ted Kremenekfd42ffc2009-02-21 18:26:02 +0000116 if (AtBeginning && StringsEqualNoCase("new", s, len))
Ted Kremenek4395b452009-02-21 05:13:43 +0000117 C = CreateRule;
118 break;
119 case 4:
120 // Methods starting with 'alloc' or contain 'copy' follow the
121 // create rule
Ted Kremenek91b79532009-03-13 20:27:06 +0000122 if (C == NoConvention && StringsEqualNoCase("copy", s, len))
Ted Kremenek4395b452009-02-21 05:13:43 +0000123 C = CreateRule;
124 else // Methods starting with 'init' follow the init rule.
Ted Kremenekfd42ffc2009-02-21 18:26:02 +0000125 if (AtBeginning && StringsEqualNoCase("init", s, len))
Ted Kremenek91b79532009-03-13 20:27:06 +0000126 C = InitRule;
127 break;
128 case 5:
129 if (AtBeginning && StringsEqualNoCase("alloc", s, len))
130 C = CreateRule;
Ted Kremenek4395b452009-02-21 05:13:43 +0000131 break;
132 }
133
134 // If we aren't in the prefix and have a derived convention then just
135 // return it now.
136 if (!InPossiblePrefix && C != NoConvention)
137 return C;
138
139 AtBeginning = false;
140 s = wordEnd;
141 }
142
143 // We will get here if there wasn't more than one word
144 // after the prefix.
145 return C;
146}
147
Ted Kremenekb6f09542008-10-24 21:18:08 +0000148static bool followsFundamentalRule(const char* s) {
Ted Kremenek4395b452009-02-21 05:13:43 +0000149 return deriveNamingConvention(s) == CreateRule;
Ted Kremenekcdd3bb22008-11-05 16:54:44 +0000150}
151
Ted Kremenek314b1952009-04-29 23:03:22 +0000152static const ObjCMethodDecl*
153ResolveToInterfaceMethodDecl(const ObjCMethodDecl *MD, ASTContext &Context) {
154 ObjCInterfaceDecl *ID =
155 const_cast<ObjCInterfaceDecl*>(MD->getClassInterface());
156
157 return MD->isInstanceMethod()
158 ? ID->lookupInstanceMethod(Context, MD->getSelector())
159 : ID->lookupClassMethod(Context, MD->getSelector());
Ted Kremenekcdd3bb22008-11-05 16:54:44 +0000160}
Ted Kremenekb6f09542008-10-24 21:18:08 +0000161
Ted Kremenek41a4bc62009-05-08 23:09:42 +0000162namespace {
163class VISIBILITY_HIDDEN GenericNodeBuilder {
164 GRStmtNodeBuilder<GRState> *SNB;
165 Stmt *S;
166 const void *tag;
167 GREndPathNodeBuilder<GRState> *ENB;
168public:
169 GenericNodeBuilder(GRStmtNodeBuilder<GRState> &snb, Stmt *s,
170 const void *t)
171 : SNB(&snb), S(s), tag(t), ENB(0) {}
172 GenericNodeBuilder(GREndPathNodeBuilder<GRState> &enb)
173 : SNB(0), S(0), tag(0), ENB(&enb) {}
174
175 ExplodedNode<GRState> *MakeNode(const GRState *state,
176 ExplodedNode<GRState> *Pred) {
177 if (SNB)
178 return SNB->generateNode(PostStmt(S, tag), state,
179 Pred);
180
181 assert(ENB);
182 return ENB->MakeNode(state, Pred);
183 }
184};
185} // end anonymous namespace
186
Ted Kremenek7d421f32008-04-09 23:49:11 +0000187//===----------------------------------------------------------------------===//
Ted Kremenek272aa852008-06-25 21:21:56 +0000188// Selector creation functions.
Ted Kremenekd9ccf682008-04-17 18:12:53 +0000189//===----------------------------------------------------------------------===//
190
Ted Kremenek1bd6ddb2008-05-01 18:31:44 +0000191static inline Selector GetNullarySelector(const char* name, ASTContext& Ctx) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +0000192 IdentifierInfo* II = &Ctx.Idents.get(name);
193 return Ctx.Selectors.getSelector(0, &II);
194}
195
Ted Kremenek0e344d42008-05-06 00:30:21 +0000196static inline Selector GetUnarySelector(const char* name, ASTContext& Ctx) {
197 IdentifierInfo* II = &Ctx.Idents.get(name);
198 return Ctx.Selectors.getSelector(1, &II);
199}
200
Ted Kremenek272aa852008-06-25 21:21:56 +0000201//===----------------------------------------------------------------------===//
202// Type querying functions.
203//===----------------------------------------------------------------------===//
204
Ted Kremenek17144e82009-01-12 21:45:02 +0000205static bool hasPrefix(const char* s, const char* prefix) {
206 if (!prefix)
207 return true;
Ted Kremenek62820d82008-05-07 20:06:41 +0000208
Ted Kremenek17144e82009-01-12 21:45:02 +0000209 char c = *s;
210 char cP = *prefix;
Ted Kremenek62820d82008-05-07 20:06:41 +0000211
Ted Kremenek17144e82009-01-12 21:45:02 +0000212 while (c != '\0' && cP != '\0') {
213 if (c != cP) break;
214 c = *(++s);
215 cP = *(++prefix);
216 }
Ted Kremenek62820d82008-05-07 20:06:41 +0000217
Ted Kremenek17144e82009-01-12 21:45:02 +0000218 return cP == '\0';
Ted Kremenek62820d82008-05-07 20:06:41 +0000219}
220
Ted Kremenek17144e82009-01-12 21:45:02 +0000221static bool hasSuffix(const char* s, const char* suffix) {
222 const char* loc = strstr(s, suffix);
223 return loc && strcmp(suffix, loc) == 0;
224}
225
226static bool isRefType(QualType RetTy, const char* prefix,
227 ASTContext* Ctx = 0, const char* name = 0) {
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000228
Ted Kremenek17144e82009-01-12 21:45:02 +0000229 if (TypedefType* TD = dyn_cast<TypedefType>(RetTy.getTypePtr())) {
230 const char* TDName = TD->getDecl()->getIdentifier()->getName();
231 return hasPrefix(TDName, prefix) && hasSuffix(TDName, "Ref");
232 }
233
234 if (!Ctx || !name)
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000235 return false;
Ted Kremenek17144e82009-01-12 21:45:02 +0000236
237 // Is the type void*?
238 const PointerType* PT = RetTy->getAsPointerType();
239 if (!(PT->getPointeeType().getUnqualifiedType() == Ctx->VoidTy))
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000240 return false;
Ted Kremenek17144e82009-01-12 21:45:02 +0000241
242 // Does the name start with the prefix?
243 return hasPrefix(name, prefix);
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000244}
245
Ted Kremenekd9ccf682008-04-17 18:12:53 +0000246//===----------------------------------------------------------------------===//
Ted Kremenek272aa852008-06-25 21:21:56 +0000247// Primitives used for constructing summaries for function/method calls.
Ted Kremenek7d421f32008-04-09 23:49:11 +0000248//===----------------------------------------------------------------------===//
249
Ted Kremenek272aa852008-06-25 21:21:56 +0000250/// ArgEffect is used to summarize a function/method call's effect on a
251/// particular argument.
Ted Kremenek6537a642009-03-17 19:42:23 +0000252enum ArgEffect { Autorelease, Dealloc, DecRef, DecRefMsg, DoNothing,
253 DoNothingByRef, IncRefMsg, IncRef, MakeCollectable, MayEscape,
254 NewAutoreleasePool, SelfOwn, StopTracking };
Ted Kremenek272aa852008-06-25 21:21:56 +0000255
Ted Kremeneka7338b42008-03-11 06:39:11 +0000256namespace llvm {
Ted Kremeneka56ae162009-05-03 05:20:50 +0000257template <> struct FoldingSetTrait<ArgEffect> {
258static inline void Profile(const ArgEffect X, FoldingSetNodeID& ID) {
259 ID.AddInteger((unsigned) X);
260}
Ted Kremenek272aa852008-06-25 21:21:56 +0000261};
Ted Kremeneka7338b42008-03-11 06:39:11 +0000262} // end llvm namespace
263
Ted Kremeneka56ae162009-05-03 05:20:50 +0000264/// ArgEffects summarizes the effects of a function/method call on all of
265/// its arguments.
266typedef llvm::ImmutableMap<unsigned,ArgEffect> ArgEffects;
267
Ted Kremeneka7338b42008-03-11 06:39:11 +0000268namespace {
Ted Kremenek272aa852008-06-25 21:21:56 +0000269
270/// RetEffect is used to summarize a function/method call's behavior with
271/// respect to its return value.
272class VISIBILITY_HIDDEN RetEffect {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000273public:
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000274 enum Kind { NoRet, Alias, OwnedSymbol, OwnedAllocatedSymbol,
Ted Kremenek382fb4e2009-04-27 19:14:45 +0000275 NotOwnedSymbol, GCNotOwnedSymbol, ReceiverAlias };
Ted Kremenek68621b92009-01-28 05:56:51 +0000276
277 enum ObjKind { CF, ObjC, AnyObj };
278
Ted Kremeneka7338b42008-03-11 06:39:11 +0000279private:
Ted Kremenek68621b92009-01-28 05:56:51 +0000280 Kind K;
281 ObjKind O;
282 unsigned index;
283
284 RetEffect(Kind k, unsigned idx = 0) : K(k), O(AnyObj), index(idx) {}
285 RetEffect(Kind k, ObjKind o) : K(k), O(o), index(0) {}
Ted Kremenek827f93b2008-03-06 00:08:09 +0000286
Ted Kremeneka7338b42008-03-11 06:39:11 +0000287public:
Ted Kremenek68621b92009-01-28 05:56:51 +0000288 Kind getKind() const { return K; }
289
290 ObjKind getObjKind() const { return O; }
Ted Kremenek272aa852008-06-25 21:21:56 +0000291
292 unsigned getIndex() const {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000293 assert(getKind() == Alias);
Ted Kremenek68621b92009-01-28 05:56:51 +0000294 return index;
Ted Kremeneka7338b42008-03-11 06:39:11 +0000295 }
Ted Kremenek827f93b2008-03-06 00:08:09 +0000296
Ted Kremenek314b1952009-04-29 23:03:22 +0000297 bool isOwned() const {
298 return K == OwnedSymbol || K == OwnedAllocatedSymbol;
299 }
300
Ted Kremenek272aa852008-06-25 21:21:56 +0000301 static RetEffect MakeAlias(unsigned Idx) {
302 return RetEffect(Alias, Idx);
303 }
304 static RetEffect MakeReceiverAlias() {
305 return RetEffect(ReceiverAlias);
306 }
Ted Kremenek68621b92009-01-28 05:56:51 +0000307 static RetEffect MakeOwned(ObjKind o, bool isAllocated = false) {
308 return RetEffect(isAllocated ? OwnedAllocatedSymbol : OwnedSymbol, o);
Ted Kremenek272aa852008-06-25 21:21:56 +0000309 }
Ted Kremenek68621b92009-01-28 05:56:51 +0000310 static RetEffect MakeNotOwned(ObjKind o) {
311 return RetEffect(NotOwnedSymbol, o);
Ted Kremenek382fb4e2009-04-27 19:14:45 +0000312 }
313 static RetEffect MakeGCNotOwned() {
314 return RetEffect(GCNotOwnedSymbol, ObjC);
315 }
316
Ted Kremenek272aa852008-06-25 21:21:56 +0000317 static RetEffect MakeNoRet() {
318 return RetEffect(NoRet);
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000319 }
Ted Kremenek827f93b2008-03-06 00:08:09 +0000320
Ted Kremenek272aa852008-06-25 21:21:56 +0000321 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek68621b92009-01-28 05:56:51 +0000322 ID.AddInteger((unsigned)K);
323 ID.AddInteger((unsigned)O);
324 ID.AddInteger(index);
Ted Kremenek272aa852008-06-25 21:21:56 +0000325 }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000326};
Ted Kremeneka7338b42008-03-11 06:39:11 +0000327
Ted Kremenek272aa852008-06-25 21:21:56 +0000328
Ted Kremenek2f226732009-05-04 05:31:22 +0000329class VISIBILITY_HIDDEN RetainSummary {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000330 /// Args - an ordered vector of (index, ArgEffect) pairs, where index
331 /// specifies the argument (starting from 0). This can be sparsely
332 /// populated; arguments with no entry in Args use 'DefaultArgEffect'.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000333 ArgEffects Args;
Ted Kremenekbcaff792008-05-06 15:44:25 +0000334
335 /// DefaultArgEffect - The default ArgEffect to apply to arguments that
336 /// do not have an entry in Args.
337 ArgEffect DefaultArgEffect;
338
Ted Kremenek272aa852008-06-25 21:21:56 +0000339 /// Receiver - If this summary applies to an Objective-C message expression,
340 /// this is the effect applied to the state of the receiver.
Ted Kremenek266d8b62008-05-06 02:26:56 +0000341 ArgEffect Receiver;
Ted Kremenek272aa852008-06-25 21:21:56 +0000342
343 /// Ret - The effect on the return value. Used to indicate if the
344 /// function/method call returns a new tracked symbol, returns an
345 /// alias of one of the arguments in the call, and so on.
Ted Kremeneka7338b42008-03-11 06:39:11 +0000346 RetEffect Ret;
Ted Kremenek272aa852008-06-25 21:21:56 +0000347
Ted Kremenekf2717b02008-07-18 17:24:20 +0000348 /// EndPath - Indicates that execution of this method/function should
349 /// terminate the simulation of a path.
350 bool EndPath;
351
Ted Kremeneka7338b42008-03-11 06:39:11 +0000352public:
Ted Kremeneka56ae162009-05-03 05:20:50 +0000353 RetainSummary(ArgEffects A, RetEffect R, ArgEffect defaultEff,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000354 ArgEffect ReceiverEff, bool endpath = false)
355 : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R),
356 EndPath(endpath) {}
Ted Kremeneka7338b42008-03-11 06:39:11 +0000357
Ted Kremenek272aa852008-06-25 21:21:56 +0000358 /// getArg - Return the argument effect on the argument specified by
359 /// idx (starting from 0).
Ted Kremenek0d721572008-03-11 17:48:22 +0000360 ArgEffect getArg(unsigned idx) const {
Ted Kremeneka56ae162009-05-03 05:20:50 +0000361 if (const ArgEffect *AE = Args.lookup(idx))
362 return *AE;
Ted Kremenekae855d42008-04-24 17:22:33 +0000363
Ted Kremenekbcaff792008-05-06 15:44:25 +0000364 return DefaultArgEffect;
Ted Kremenek0d721572008-03-11 17:48:22 +0000365 }
366
Ted Kremenek2f226732009-05-04 05:31:22 +0000367 /// setDefaultArgEffect - Set the default argument effect.
368 void setDefaultArgEffect(ArgEffect E) {
369 DefaultArgEffect = E;
370 }
371
372 /// setArg - Set the argument effect on the argument specified by idx.
373 void setArgEffect(ArgEffects::Factory& AF, unsigned idx, ArgEffect E) {
374 Args = AF.Add(Args, idx, E);
375 }
376
Ted Kremenek272aa852008-06-25 21:21:56 +0000377 /// getRetEffect - Returns the effect on the return value of the call.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000378 RetEffect getRetEffect() const { return Ret; }
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000379
Ted Kremenek2f226732009-05-04 05:31:22 +0000380 /// setRetEffect - Set the effect of the return value of the call.
381 void setRetEffect(RetEffect E) { Ret = E; }
382
Ted Kremenekf2717b02008-07-18 17:24:20 +0000383 /// isEndPath - Returns true if executing the given method/function should
384 /// terminate the path.
385 bool isEndPath() const { return EndPath; }
386
Ted Kremenek272aa852008-06-25 21:21:56 +0000387 /// getReceiverEffect - Returns the effect on the receiver of the call.
388 /// This is only meaningful if the summary applies to an ObjCMessageExpr*.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000389 ArgEffect getReceiverEffect() const { return Receiver; }
Ted Kremenek266d8b62008-05-06 02:26:56 +0000390
Ted Kremenek2f226732009-05-04 05:31:22 +0000391 /// setReceiverEffect - Set the effect on the receiver of the call.
392 void setReceiverEffect(ArgEffect E) { Receiver = E; }
393
Ted Kremeneka56ae162009-05-03 05:20:50 +0000394 typedef ArgEffects::iterator ExprIterator;
Ted Kremeneka7338b42008-03-11 06:39:11 +0000395
Ted Kremeneka56ae162009-05-03 05:20:50 +0000396 ExprIterator begin_args() const { return Args.begin(); }
397 ExprIterator end_args() const { return Args.end(); }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000398
Ted Kremeneka56ae162009-05-03 05:20:50 +0000399 static void Profile(llvm::FoldingSetNodeID& ID, ArgEffects A,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000400 RetEffect RetEff, ArgEffect DefaultEff,
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000401 ArgEffect ReceiverEff, bool EndPath) {
Ted Kremeneka56ae162009-05-03 05:20:50 +0000402 ID.Add(A);
Ted Kremenek266d8b62008-05-06 02:26:56 +0000403 ID.Add(RetEff);
Ted Kremenekbcaff792008-05-06 15:44:25 +0000404 ID.AddInteger((unsigned) DefaultEff);
Ted Kremenek266d8b62008-05-06 02:26:56 +0000405 ID.AddInteger((unsigned) ReceiverEff);
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000406 ID.AddInteger((unsigned) EndPath);
Ted Kremeneka7338b42008-03-11 06:39:11 +0000407 }
408
409 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000410 Profile(ID, Args, Ret, DefaultArgEffect, Receiver, EndPath);
Ted Kremeneka7338b42008-03-11 06:39:11 +0000411 }
412};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000413} // end anonymous namespace
Ted Kremeneka7338b42008-03-11 06:39:11 +0000414
Ted Kremenek272aa852008-06-25 21:21:56 +0000415//===----------------------------------------------------------------------===//
416// Data structures for constructing summaries.
417//===----------------------------------------------------------------------===//
Ted Kremenek9f0fc792008-06-24 03:49:48 +0000418
Ted Kremenek272aa852008-06-25 21:21:56 +0000419namespace {
420class VISIBILITY_HIDDEN ObjCSummaryKey {
421 IdentifierInfo* II;
422 Selector S;
423public:
424 ObjCSummaryKey(IdentifierInfo* ii, Selector s)
425 : II(ii), S(s) {}
426
Ted Kremenek314b1952009-04-29 23:03:22 +0000427 ObjCSummaryKey(const ObjCInterfaceDecl* d, Selector s)
Ted Kremenek272aa852008-06-25 21:21:56 +0000428 : II(d ? d->getIdentifier() : 0), S(s) {}
429
430 ObjCSummaryKey(Selector s)
431 : II(0), S(s) {}
432
433 IdentifierInfo* getIdentifier() const { return II; }
434 Selector getSelector() const { return S; }
435};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000436}
437
438namespace llvm {
Ted Kremenek272aa852008-06-25 21:21:56 +0000439template <> struct DenseMapInfo<ObjCSummaryKey> {
440 static inline ObjCSummaryKey getEmptyKey() {
441 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
442 DenseMapInfo<Selector>::getEmptyKey());
443 }
Ted Kremenek84f010c2008-06-23 23:30:29 +0000444
Ted Kremenek272aa852008-06-25 21:21:56 +0000445 static inline ObjCSummaryKey getTombstoneKey() {
446 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
447 DenseMapInfo<Selector>::getTombstoneKey());
448 }
449
450 static unsigned getHashValue(const ObjCSummaryKey &V) {
451 return (DenseMapInfo<IdentifierInfo*>::getHashValue(V.getIdentifier())
452 & 0x88888888)
453 | (DenseMapInfo<Selector>::getHashValue(V.getSelector())
454 & 0x55555555);
455 }
456
457 static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
458 return DenseMapInfo<IdentifierInfo*>::isEqual(LHS.getIdentifier(),
459 RHS.getIdentifier()) &&
460 DenseMapInfo<Selector>::isEqual(LHS.getSelector(),
461 RHS.getSelector());
462 }
463
464 static bool isPod() {
465 return DenseMapInfo<ObjCInterfaceDecl*>::isPod() &&
466 DenseMapInfo<Selector>::isPod();
467 }
468};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000469} // end llvm namespace
Ted Kremeneka7338b42008-03-11 06:39:11 +0000470
Ted Kremenek84f010c2008-06-23 23:30:29 +0000471namespace {
Ted Kremenek272aa852008-06-25 21:21:56 +0000472class VISIBILITY_HIDDEN ObjCSummaryCache {
473 typedef llvm::DenseMap<ObjCSummaryKey, RetainSummary*> MapTy;
474 MapTy M;
475public:
476 ObjCSummaryCache() {}
477
478 typedef MapTy::iterator iterator;
479
Ted Kremenek314b1952009-04-29 23:03:22 +0000480 iterator find(const ObjCInterfaceDecl* D, IdentifierInfo *ClsName,
481 Selector S) {
Ted Kremeneka821b792009-04-29 05:04:30 +0000482 // Lookup the method using the decl for the class @interface. If we
483 // have no decl, lookup using the class name.
484 return D ? find(D, S) : find(ClsName, S);
485 }
486
Ted Kremenek314b1952009-04-29 23:03:22 +0000487 iterator find(const ObjCInterfaceDecl* D, Selector S) {
Ted Kremenek272aa852008-06-25 21:21:56 +0000488 // Do a lookup with the (D,S) pair. If we find a match return
489 // the iterator.
490 ObjCSummaryKey K(D, S);
491 MapTy::iterator I = M.find(K);
492
493 if (I != M.end() || !D)
494 return I;
495
496 // Walk the super chain. If we find a hit with a parent, we'll end
497 // up returning that summary. We actually allow that key (null,S), as
498 // we cache summaries for the null ObjCInterfaceDecl* to allow us to
499 // generate initial summaries without having to worry about NSObject
500 // being declared.
501 // FIXME: We may change this at some point.
502 for (ObjCInterfaceDecl* C=D->getSuperClass() ;; C=C->getSuperClass()) {
503 if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
504 break;
505
506 if (!C)
507 return I;
508 }
509
510 // Cache the summary with original key to make the next lookup faster
511 // and return the iterator.
512 M[K] = I->second;
513 return I;
514 }
515
Ted Kremenek9449ca92008-08-12 20:41:56 +0000516
Ted Kremenek272aa852008-06-25 21:21:56 +0000517 iterator find(Expr* Receiver, Selector S) {
518 return find(getReceiverDecl(Receiver), S);
519 }
520
521 iterator find(IdentifierInfo* II, Selector S) {
522 // FIXME: Class method lookup. Right now we dont' have a good way
523 // of going between IdentifierInfo* and the class hierarchy.
524 iterator I = M.find(ObjCSummaryKey(II, S));
525 return I == M.end() ? M.find(ObjCSummaryKey(S)) : I;
526 }
527
528 ObjCInterfaceDecl* getReceiverDecl(Expr* E) {
529
530 const PointerType* PT = E->getType()->getAsPointerType();
531 if (!PT) return 0;
532
533 ObjCInterfaceType* OI = dyn_cast<ObjCInterfaceType>(PT->getPointeeType());
534 if (!OI) return 0;
535
536 return OI ? OI->getDecl() : 0;
537 }
538
539 iterator end() { return M.end(); }
540
541 RetainSummary*& operator[](ObjCMessageExpr* ME) {
542
543 Selector S = ME->getSelector();
544
545 if (Expr* Receiver = ME->getReceiver()) {
546 ObjCInterfaceDecl* OD = getReceiverDecl(Receiver);
547 return OD ? M[ObjCSummaryKey(OD->getIdentifier(), S)] : M[S];
548 }
549
550 return M[ObjCSummaryKey(ME->getClassName(), S)];
551 }
552
553 RetainSummary*& operator[](ObjCSummaryKey K) {
554 return M[K];
555 }
556
557 RetainSummary*& operator[](Selector S) {
558 return M[ ObjCSummaryKey(S) ];
559 }
560};
561} // end anonymous namespace
562
563//===----------------------------------------------------------------------===//
564// Data structures for managing collections of summaries.
565//===----------------------------------------------------------------------===//
566
567namespace {
568class VISIBILITY_HIDDEN RetainSummaryManager {
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000569
570 //==-----------------------------------------------------------------==//
571 // Typedefs.
572 //==-----------------------------------------------------------------==//
Ted Kremeneka7338b42008-03-11 06:39:11 +0000573
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000574 typedef llvm::DenseMap<FunctionDecl*, RetainSummary*>
575 FuncSummariesTy;
576
Ted Kremenek84f010c2008-06-23 23:30:29 +0000577 typedef ObjCSummaryCache ObjCMethodSummariesTy;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000578
579 //==-----------------------------------------------------------------==//
580 // Data.
581 //==-----------------------------------------------------------------==//
582
Ted Kremenek272aa852008-06-25 21:21:56 +0000583 /// Ctx - The ASTContext object for the analyzed ASTs.
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000584 ASTContext& Ctx;
Ted Kremeneke44927e2008-07-01 17:21:27 +0000585
Ted Kremenekede40b72008-07-09 18:11:16 +0000586 /// CFDictionaryCreateII - An IdentifierInfo* representing the indentifier
587 /// "CFDictionaryCreate".
588 IdentifierInfo* CFDictionaryCreateII;
589
Ted Kremenek272aa852008-06-25 21:21:56 +0000590 /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000591 const bool GCEnabled;
Ted Kremenekee649082009-05-04 04:30:18 +0000592
Ted Kremenek272aa852008-06-25 21:21:56 +0000593 /// FuncSummaries - A map from FunctionDecls to summaries.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000594 FuncSummariesTy FuncSummaries;
595
Ted Kremenek272aa852008-06-25 21:21:56 +0000596 /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
597 /// to summaries.
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000598 ObjCMethodSummariesTy ObjCClassMethodSummaries;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000599
Ted Kremenek272aa852008-06-25 21:21:56 +0000600 /// ObjCMethodSummaries - A map from selectors to summaries.
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000601 ObjCMethodSummariesTy ObjCMethodSummaries;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000602
Ted Kremenek272aa852008-06-25 21:21:56 +0000603 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
604 /// and all other data used by the checker.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000605 llvm::BumpPtrAllocator BPAlloc;
606
Ted Kremeneka56ae162009-05-03 05:20:50 +0000607 /// AF - A factory for ArgEffects objects.
608 ArgEffects::Factory AF;
609
Ted Kremenek272aa852008-06-25 21:21:56 +0000610 /// ScratchArgs - A holding buffer for construct ArgEffects.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000611 ArgEffects ScratchArgs;
612
Ted Kremenek5535e5e2009-05-07 23:40:42 +0000613 /// ObjCAllocRetE - Default return effect for methods returning Objective-C
614 /// objects.
615 RetEffect ObjCAllocRetE;
616
Ted Kremenek286e9852009-05-04 04:57:00 +0000617 RetainSummary DefaultSummary;
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000618 RetainSummary* StopSummary;
619
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000620 //==-----------------------------------------------------------------==//
621 // Methods.
622 //==-----------------------------------------------------------------==//
623
Ted Kremenek272aa852008-06-25 21:21:56 +0000624 /// getArgEffects - Returns a persistent ArgEffects object based on the
625 /// data in ScratchArgs.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000626 ArgEffects getArgEffects();
Ted Kremeneka7338b42008-03-11 06:39:11 +0000627
Ted Kremenek562c1302008-05-05 16:51:50 +0000628 enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000629
630public:
Ted Kremenek2f226732009-05-04 05:31:22 +0000631 RetainSummary *getDefaultSummary() {
632 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
633 return new (Summ) RetainSummary(DefaultSummary);
634 }
Ted Kremenek286e9852009-05-04 04:57:00 +0000635
Ted Kremenek064ef322009-02-23 16:51:39 +0000636 RetainSummary* getUnarySummary(const FunctionType* FT, UnaryFuncKind func);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000637
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000638 RetainSummary* getCFSummaryCreateRule(FunctionDecl* FD);
639 RetainSummary* getCFSummaryGetRule(FunctionDecl* FD);
Ted Kremenek17144e82009-01-12 21:45:02 +0000640 RetainSummary* getCFCreateGetRuleSummary(FunctionDecl* FD, const char* FName);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000641
Ted Kremeneka56ae162009-05-03 05:20:50 +0000642 RetainSummary* getPersistentSummary(ArgEffects AE, RetEffect RetEff,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000643 ArgEffect ReceiverEff = DoNothing,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000644 ArgEffect DefaultEff = MayEscape,
645 bool isEndPath = false);
Ted Kremenek45d0b502008-10-29 04:07:07 +0000646
Ted Kremenek266d8b62008-05-06 02:26:56 +0000647 RetainSummary* getPersistentSummary(RetEffect RE,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000648 ArgEffect ReceiverEff = DoNothing,
Ted Kremeneka3f30dd2008-05-22 17:31:13 +0000649 ArgEffect DefaultEff = MayEscape) {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000650 return getPersistentSummary(getArgEffects(), RE, ReceiverEff, DefaultEff);
Ted Kremenek0e344d42008-05-06 00:30:21 +0000651 }
Ted Kremenek42ea0322008-05-05 23:55:01 +0000652
Ted Kremeneka821b792009-04-29 05:04:30 +0000653 RetainSummary *getPersistentStopSummary() {
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000654 if (StopSummary)
655 return StopSummary;
656
657 StopSummary = getPersistentSummary(RetEffect::MakeNoRet(),
658 StopTracking, StopTracking);
Ted Kremenek45d0b502008-10-29 04:07:07 +0000659
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000660 return StopSummary;
Ted Kremenekbcaff792008-05-06 15:44:25 +0000661 }
Ted Kremenek926abf22008-05-06 04:20:12 +0000662
Ted Kremeneka821b792009-04-29 05:04:30 +0000663 RetainSummary *getInitMethodSummary(QualType RetTy);
Ted Kremenek42ea0322008-05-05 23:55:01 +0000664
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000665 void InitializeClassMethodSummaries();
666 void InitializeMethodSummaries();
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000667
Ted Kremenek9b42e062009-05-03 04:42:10 +0000668 bool isTrackedObjCObjectType(QualType T);
Ted Kremeneka9cdbc32009-05-03 06:08:32 +0000669 bool isTrackedCFObjectType(QualType T);
Ted Kremenek35920ed2009-01-07 00:39:56 +0000670
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000671private:
672
Ted Kremenekf2717b02008-07-18 17:24:20 +0000673 void addClsMethSummary(IdentifierInfo* ClsII, Selector S,
674 RetainSummary* Summ) {
675 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
676 }
677
Ted Kremenek272aa852008-06-25 21:21:56 +0000678 void addNSObjectClsMethSummary(Selector S, RetainSummary *Summ) {
679 ObjCClassMethodSummaries[S] = Summ;
680 }
681
682 void addNSObjectMethSummary(Selector S, RetainSummary *Summ) {
683 ObjCMethodSummaries[S] = Summ;
684 }
Ted Kremenekfbf2dc52009-03-04 23:30:42 +0000685
686 void addClassMethSummary(const char* Cls, const char* nullaryName,
687 RetainSummary *Summ) {
688 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
689 Selector S = GetNullarySelector(nullaryName, Ctx);
690 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
691 }
Ted Kremenek272aa852008-06-25 21:21:56 +0000692
Ted Kremenek1b4b6562009-02-25 02:54:57 +0000693 void addInstMethSummary(const char* Cls, const char* nullaryName,
694 RetainSummary *Summ) {
695 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
696 Selector S = GetNullarySelector(nullaryName, Ctx);
697 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
698 }
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000699
700 Selector generateSelector(va_list argp) {
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000701 llvm::SmallVector<IdentifierInfo*, 10> II;
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000702
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000703 while (const char* s = va_arg(argp, const char*))
704 II.push_back(&Ctx.Idents.get(s));
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000705
706 return Ctx.Selectors.getSelector(II.size(), &II[0]);
707 }
708
709 void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy& Summaries,
710 RetainSummary* Summ, va_list argp) {
711 Selector S = generateSelector(argp);
712 Summaries[ObjCSummaryKey(ClsII, S)] = Summ;
Ted Kremenekf2717b02008-07-18 17:24:20 +0000713 }
Ted Kremenek45642a42008-08-12 18:48:50 +0000714
715 void addInstMethSummary(const char* Cls, RetainSummary* Summ, ...) {
716 va_list argp;
717 va_start(argp, Summ);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000718 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Ted Kremenek45642a42008-08-12 18:48:50 +0000719 va_end(argp);
720 }
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000721
722 void addClsMethSummary(const char* Cls, RetainSummary* Summ, ...) {
723 va_list argp;
724 va_start(argp, Summ);
725 addMethodSummary(&Ctx.Idents.get(Cls),ObjCClassMethodSummaries, Summ, argp);
726 va_end(argp);
727 }
728
729 void addClsMethSummary(IdentifierInfo *II, RetainSummary* Summ, ...) {
730 va_list argp;
731 va_start(argp, Summ);
732 addMethodSummary(II, ObjCClassMethodSummaries, Summ, argp);
733 va_end(argp);
734 }
735
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000736 void addPanicSummary(const char* Cls, ...) {
Ted Kremeneka56ae162009-05-03 05:20:50 +0000737 RetainSummary* Summ = getPersistentSummary(AF.GetEmptyMap(),
738 RetEffect::MakeNoRet(),
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000739 DoNothing, DoNothing, true);
740 va_list argp;
741 va_start (argp, Cls);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000742 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000743 va_end(argp);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000744 }
Ted Kremenekf2717b02008-07-18 17:24:20 +0000745
Ted Kremeneka7338b42008-03-11 06:39:11 +0000746public:
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000747
748 RetainSummaryManager(ASTContext& ctx, bool gcenabled)
Ted Kremeneke44927e2008-07-01 17:21:27 +0000749 : Ctx(ctx),
Ted Kremenekede40b72008-07-09 18:11:16 +0000750 CFDictionaryCreateII(&ctx.Idents.get("CFDictionaryCreate")),
Ted Kremeneka56ae162009-05-03 05:20:50 +0000751 GCEnabled(gcenabled), AF(BPAlloc), ScratchArgs(AF.GetEmptyMap()),
Ted Kremenek5535e5e2009-05-07 23:40:42 +0000752 ObjCAllocRetE(gcenabled ? RetEffect::MakeGCNotOwned()
753 : RetEffect::MakeOwned(RetEffect::ObjC, true)),
Ted Kremenek286e9852009-05-04 04:57:00 +0000754 DefaultSummary(AF.GetEmptyMap() /* per-argument effects (none) */,
755 RetEffect::MakeNoRet() /* return effect */,
756 DoNothing /* receiver effect */,
757 MayEscape /* default argument effect */),
Ted Kremeneka56ae162009-05-03 05:20:50 +0000758 StopSummary(0) {
Ted Kremenek272aa852008-06-25 21:21:56 +0000759
760 InitializeClassMethodSummaries();
761 InitializeMethodSummaries();
762 }
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000763
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000764 ~RetainSummaryManager();
Ted Kremeneka7338b42008-03-11 06:39:11 +0000765
Ted Kremenekd13c1872008-06-24 03:56:45 +0000766 RetainSummary* getSummary(FunctionDecl* FD);
Ted Kremeneka821b792009-04-29 05:04:30 +0000767
Ted Kremenek314b1952009-04-29 23:03:22 +0000768 RetainSummary* getInstanceMethodSummary(ObjCMessageExpr* ME,
769 const ObjCInterfaceDecl* ID) {
Ted Kremenek04e00302009-04-29 17:09:14 +0000770 return getInstanceMethodSummary(ME->getSelector(), ME->getClassName(),
Ted Kremeneka821b792009-04-29 05:04:30 +0000771 ID, ME->getMethodDecl(), ME->getType());
772 }
773
Ted Kremenek04e00302009-04-29 17:09:14 +0000774 RetainSummary* getInstanceMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +0000775 const ObjCInterfaceDecl* ID,
776 const ObjCMethodDecl *MD,
777 QualType RetTy);
Ted Kremenek578498a2009-04-29 00:42:39 +0000778
779 RetainSummary *getClassMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +0000780 const ObjCInterfaceDecl *ID,
781 const ObjCMethodDecl *MD,
782 QualType RetTy);
Ted Kremenek578498a2009-04-29 00:42:39 +0000783
784 RetainSummary *getClassMethodSummary(ObjCMessageExpr *ME) {
785 return getClassMethodSummary(ME->getSelector(), ME->getClassName(),
786 ME->getClassInfo().first,
787 ME->getMethodDecl(), ME->getType());
788 }
Ted Kremenek91b89a42009-04-29 17:17:48 +0000789
790 /// getMethodSummary - This version of getMethodSummary is used to query
791 /// the summary for the current method being analyzed.
Ted Kremenek314b1952009-04-29 23:03:22 +0000792 RetainSummary *getMethodSummary(const ObjCMethodDecl *MD) {
793 // FIXME: Eventually this should be unneeded.
Ted Kremenek314b1952009-04-29 23:03:22 +0000794 const ObjCInterfaceDecl *ID = MD->getClassInterface();
Ted Kremenek1447cc92009-04-30 05:41:14 +0000795 Selector S = MD->getSelector();
Ted Kremenek91b89a42009-04-29 17:17:48 +0000796 IdentifierInfo *ClsName = ID->getIdentifier();
797 QualType ResultTy = MD->getResultType();
798
Ted Kremenek81eb4642009-04-30 05:47:23 +0000799 // Resolve the method decl last.
800 if (const ObjCMethodDecl *InterfaceMD =
801 ResolveToInterfaceMethodDecl(MD, Ctx))
802 MD = InterfaceMD;
Ted Kremenek1447cc92009-04-30 05:41:14 +0000803
Ted Kremenek91b89a42009-04-29 17:17:48 +0000804 if (MD->isInstanceMethod())
805 return getInstanceMethodSummary(S, ClsName, ID, MD, ResultTy);
806 else
807 return getClassMethodSummary(S, ClsName, ID, MD, ResultTy);
808 }
Ted Kremenek578498a2009-04-29 00:42:39 +0000809
Ted Kremenek314b1952009-04-29 23:03:22 +0000810 RetainSummary* getCommonMethodSummary(const ObjCMethodDecl* MD,
811 Selector S, QualType RetTy);
812
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000813 bool isGCEnabled() const { return GCEnabled; }
Ted Kremenek2f226732009-05-04 05:31:22 +0000814
815 RetainSummary *copySummary(RetainSummary *OldSumm) {
816 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
817 new (Summ) RetainSummary(*OldSumm);
818 return Summ;
819 }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000820};
821
822} // end anonymous namespace
823
824//===----------------------------------------------------------------------===//
825// Implementation of checker data structures.
826//===----------------------------------------------------------------------===//
827
Ted Kremeneka56ae162009-05-03 05:20:50 +0000828RetainSummaryManager::~RetainSummaryManager() {}
Ted Kremeneka7338b42008-03-11 06:39:11 +0000829
Ted Kremeneka56ae162009-05-03 05:20:50 +0000830ArgEffects RetainSummaryManager::getArgEffects() {
831 ArgEffects AE = ScratchArgs;
832 ScratchArgs = AF.GetEmptyMap();
833 return AE;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000834}
835
Ted Kremenek266d8b62008-05-06 02:26:56 +0000836RetainSummary*
Ted Kremeneka56ae162009-05-03 05:20:50 +0000837RetainSummaryManager::getPersistentSummary(ArgEffects AE, RetEffect RetEff,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000838 ArgEffect ReceiverEff,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000839 ArgEffect DefaultEff,
Ted Kremenekee649082009-05-04 04:30:18 +0000840 bool isEndPath) {
Ted Kremenekae855d42008-04-24 17:22:33 +0000841 // Create the summary and return it.
Ted Kremenekee649082009-05-04 04:30:18 +0000842 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
Ted Kremenekf2717b02008-07-18 17:24:20 +0000843 new (Summ) RetainSummary(AE, RetEff, DefaultEff, ReceiverEff, isEndPath);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000844 return Summ;
845}
846
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000847//===----------------------------------------------------------------------===//
Ted Kremenek35920ed2009-01-07 00:39:56 +0000848// Predicates.
849//===----------------------------------------------------------------------===//
850
Ted Kremenek9b42e062009-05-03 04:42:10 +0000851bool RetainSummaryManager::isTrackedObjCObjectType(QualType Ty) {
Ted Kremenek0d813552009-04-23 22:11:07 +0000852 if (!Ctx.isObjCObjectPointerType(Ty))
Ted Kremenek35920ed2009-01-07 00:39:56 +0000853 return false;
854
Ted Kremenek0d813552009-04-23 22:11:07 +0000855 // We assume that id<..>, id, and "Class" all represent tracked objects.
856 const PointerType *PT = Ty->getAsPointerType();
857 if (PT == 0)
858 return true;
859
860 const ObjCInterfaceType *OT = PT->getPointeeType()->getAsObjCInterfaceType();
Ted Kremenek35920ed2009-01-07 00:39:56 +0000861
862 // We assume that id<..>, id, and "Class" all represent tracked objects.
863 if (!OT)
864 return true;
Ted Kremenek0d813552009-04-23 22:11:07 +0000865
866 // Does the interface subclass NSObject?
Ted Kremenek35920ed2009-01-07 00:39:56 +0000867 // FIXME: We can memoize here if this gets too expensive.
868 IdentifierInfo* NSObjectII = &Ctx.Idents.get("NSObject");
869 ObjCInterfaceDecl* ID = OT->getDecl();
870
871 for ( ; ID ; ID = ID->getSuperClass())
872 if (ID->getIdentifier() == NSObjectII)
873 return true;
874
875 return false;
876}
877
Ted Kremeneka9cdbc32009-05-03 06:08:32 +0000878bool RetainSummaryManager::isTrackedCFObjectType(QualType T) {
879 return isRefType(T, "CF") || // Core Foundation.
880 isRefType(T, "CG") || // Core Graphics.
881 isRefType(T, "DADisk") || // Disk Arbitration API.
882 isRefType(T, "DADissenter") ||
883 isRefType(T, "DASessionRef");
884}
885
Ted Kremenek35920ed2009-01-07 00:39:56 +0000886//===----------------------------------------------------------------------===//
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000887// Summary creation for functions (largely uses of Core Foundation).
888//===----------------------------------------------------------------------===//
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000889
Ted Kremenek17144e82009-01-12 21:45:02 +0000890static bool isRetain(FunctionDecl* FD, const char* FName) {
891 const char* loc = strstr(FName, "Retain");
892 return loc && loc[sizeof("Retain")-1] == '\0';
893}
894
895static bool isRelease(FunctionDecl* FD, const char* FName) {
896 const char* loc = strstr(FName, "Release");
897 return loc && loc[sizeof("Release")-1] == '\0';
898}
899
Ted Kremenekd13c1872008-06-24 03:56:45 +0000900RetainSummary* RetainSummaryManager::getSummary(FunctionDecl* FD) {
Ted Kremenekae855d42008-04-24 17:22:33 +0000901 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000902 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000903 if (I != FuncSummaries.end())
Ted Kremenekae855d42008-04-24 17:22:33 +0000904 return I->second;
905
Ted Kremenek64cddf12009-05-04 15:34:07 +0000906 // No summary? Generate one.
Ted Kremenek17144e82009-01-12 21:45:02 +0000907 RetainSummary *S = 0;
Ted Kremenek562c1302008-05-05 16:51:50 +0000908
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000909 do {
Ted Kremenek17144e82009-01-12 21:45:02 +0000910 // We generate "stop" summaries for implicitly defined functions.
911 if (FD->isImplicit()) {
912 S = getPersistentStopSummary();
913 break;
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000914 }
Ted Kremenekeafcc2f2008-11-04 00:36:12 +0000915
Ted Kremenek064ef322009-02-23 16:51:39 +0000916 // [PR 3337] Use 'getAsFunctionType' to strip away any typedefs on the
Ted Kremenekc239b9c2009-01-16 18:40:33 +0000917 // function's type.
Ted Kremenek064ef322009-02-23 16:51:39 +0000918 const FunctionType* FT = FD->getType()->getAsFunctionType();
Ted Kremenek17144e82009-01-12 21:45:02 +0000919 const char* FName = FD->getIdentifier()->getName();
920
Ted Kremenek38c6f022009-03-05 22:11:14 +0000921 // Strip away preceding '_'. Doing this here will effect all the checks
922 // down below.
923 while (*FName == '_') ++FName;
924
Ted Kremenek17144e82009-01-12 21:45:02 +0000925 // Inspect the result type.
926 QualType RetTy = FT->getResultType();
927
928 // FIXME: This should all be refactored into a chain of "summary lookup"
929 // filters.
930 if (strcmp(FName, "IOServiceGetMatchingServices") == 0) {
931 // FIXES: <rdar://problem/6326900>
932 // This should be addressed using a API table. This strcmp is also
933 // a little gross, but there is no need to super optimize here.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000934 assert (ScratchArgs.isEmpty());
935 ScratchArgs = AF.Add(ScratchArgs, 1, DecRef);
Ted Kremenek17144e82009-01-12 21:45:02 +0000936 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
937 break;
Ted Kremenekcfc50c72008-10-22 20:54:52 +0000938 }
Ted Kremenek7b88c892009-03-17 22:43:44 +0000939
940 // Enable this code once the semantics of NSDeallocateObject are resolved
941 // for GC. <rdar://problem/6619988>
942#if 0
943 // Handle: NSDeallocateObject(id anObject);
944 // This method does allow 'nil' (although we don't check it now).
945 if (strcmp(FName, "NSDeallocateObject") == 0) {
946 return RetTy == Ctx.VoidTy
947 ? getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, Dealloc)
948 : getPersistentStopSummary();
949 }
950#endif
Ted Kremenek17144e82009-01-12 21:45:02 +0000951
952 // Handle: id NSMakeCollectable(CFTypeRef)
953 if (strcmp(FName, "NSMakeCollectable") == 0) {
954 S = (RetTy == Ctx.getObjCIdType())
955 ? getUnarySummary(FT, cfmakecollectable)
956 : getPersistentStopSummary();
957
958 break;
959 }
960
961 if (RetTy->isPointerType()) {
962 // For CoreFoundation ('CF') types.
963 if (isRefType(RetTy, "CF", &Ctx, FName)) {
964 if (isRetain(FD, FName))
965 S = getUnarySummary(FT, cfretain);
966 else if (strstr(FName, "MakeCollectable"))
967 S = getUnarySummary(FT, cfmakecollectable);
968 else
969 S = getCFCreateGetRuleSummary(FD, FName);
970
971 break;
972 }
973
974 // For CoreGraphics ('CG') types.
975 if (isRefType(RetTy, "CG", &Ctx, FName)) {
976 if (isRetain(FD, FName))
977 S = getUnarySummary(FT, cfretain);
978 else
979 S = getCFCreateGetRuleSummary(FD, FName);
980
981 break;
982 }
983
984 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
985 if (isRefType(RetTy, "DADisk") ||
986 isRefType(RetTy, "DADissenter") ||
987 isRefType(RetTy, "DASessionRef")) {
988 S = getCFCreateGetRuleSummary(FD, FName);
989 break;
990 }
991
992 break;
993 }
994
995 // Check for release functions, the only kind of functions that we care
996 // about that don't return a pointer type.
997 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
Ted Kremenek38c6f022009-03-05 22:11:14 +0000998 // Test for 'CGCF'.
999 if (FName[1] == 'G' && FName[2] == 'C' && FName[3] == 'F')
1000 FName += 4;
1001 else
1002 FName += 2;
1003
1004 if (isRelease(FD, FName))
Ted Kremenek17144e82009-01-12 21:45:02 +00001005 S = getUnarySummary(FT, cfrelease);
1006 else {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001007 assert (ScratchArgs.isEmpty());
Ted Kremenek7b293682009-01-29 22:45:13 +00001008 // Remaining CoreFoundation and CoreGraphics functions.
1009 // We use to assume that they all strictly followed the ownership idiom
1010 // and that ownership cannot be transferred. While this is technically
1011 // correct, many methods allow a tracked object to escape. For example:
1012 //
1013 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
1014 // CFDictionaryAddValue(y, key, x);
1015 // CFRelease(x);
1016 // ... it is okay to use 'x' since 'y' has a reference to it
1017 //
1018 // We handle this and similar cases with the follow heuristic. If the
1019 // function name contains "InsertValue", "SetValue" or "AddValue" then
1020 // we assume that arguments may "escape."
1021 //
1022 ArgEffect E = (CStrInCStrNoCase(FName, "InsertValue") ||
1023 CStrInCStrNoCase(FName, "AddValue") ||
Ted Kremenekcf071252009-02-05 22:34:53 +00001024 CStrInCStrNoCase(FName, "SetValue") ||
1025 CStrInCStrNoCase(FName, "AppendValue"))
Ted Kremenek7b293682009-01-29 22:45:13 +00001026 ? MayEscape : DoNothing;
1027
1028 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek17144e82009-01-12 21:45:02 +00001029 }
1030 }
Ted Kremenek4c5378c2008-07-15 16:50:12 +00001031 }
1032 while (0);
Ted Kremenek2f226732009-05-04 05:31:22 +00001033
1034 if (!S)
1035 S = getDefaultSummary();
Ted Kremenekae855d42008-04-24 17:22:33 +00001036
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001037 FuncSummaries[FD] = S;
Ted Kremenek562c1302008-05-05 16:51:50 +00001038 return S;
Ted Kremenek827f93b2008-03-06 00:08:09 +00001039}
1040
Ted Kremenek4c5378c2008-07-15 16:50:12 +00001041RetainSummary*
1042RetainSummaryManager::getCFCreateGetRuleSummary(FunctionDecl* FD,
1043 const char* FName) {
1044
Ted Kremenek562c1302008-05-05 16:51:50 +00001045 if (strstr(FName, "Create") || strstr(FName, "Copy"))
1046 return getCFSummaryCreateRule(FD);
Ted Kremenek4c5378c2008-07-15 16:50:12 +00001047
Ted Kremenek562c1302008-05-05 16:51:50 +00001048 if (strstr(FName, "Get"))
1049 return getCFSummaryGetRule(FD);
1050
Ted Kremenek286e9852009-05-04 04:57:00 +00001051 return getDefaultSummary();
Ted Kremenek562c1302008-05-05 16:51:50 +00001052}
1053
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001054RetainSummary*
Ted Kremenek064ef322009-02-23 16:51:39 +00001055RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1056 UnaryFuncKind func) {
1057
Ted Kremenek17144e82009-01-12 21:45:02 +00001058 // Sanity check that this is *really* a unary function. This can
1059 // happen if people do weird things.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001060 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
Ted Kremenek17144e82009-01-12 21:45:02 +00001061 if (!FTP || FTP->getNumArgs() != 1)
1062 return getPersistentStopSummary();
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001063
Ted Kremeneka56ae162009-05-03 05:20:50 +00001064 assert (ScratchArgs.isEmpty());
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001065
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001066 switch (func) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001067 case cfretain: {
1068 ScratchArgs = AF.Add(ScratchArgs, 0, IncRef);
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001069 return getPersistentSummary(RetEffect::MakeAlias(0),
1070 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001071 }
1072
1073 case cfrelease: {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001074 ScratchArgs = AF.Add(ScratchArgs, 0, DecRef);
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001075 return getPersistentSummary(RetEffect::MakeNoRet(),
1076 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001077 }
1078
1079 case cfmakecollectable: {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001080 ScratchArgs = AF.Add(ScratchArgs, 0, MakeCollectable);
Ted Kremenek2126bef2009-02-18 21:57:45 +00001081 return getPersistentSummary(RetEffect::MakeAlias(0),DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001082 }
1083
1084 default:
Ted Kremenek562c1302008-05-05 16:51:50 +00001085 assert (false && "Not a supported unary function.");
Ted Kremenek286e9852009-05-04 04:57:00 +00001086 return getDefaultSummary();
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00001087 }
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001088}
1089
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001090RetainSummary* RetainSummaryManager::getCFSummaryCreateRule(FunctionDecl* FD) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001091 assert (ScratchArgs.isEmpty());
Ted Kremenekede40b72008-07-09 18:11:16 +00001092
1093 if (FD->getIdentifier() == CFDictionaryCreateII) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001094 ScratchArgs = AF.Add(ScratchArgs, 1, DoNothingByRef);
1095 ScratchArgs = AF.Add(ScratchArgs, 2, DoNothingByRef);
Ted Kremenekede40b72008-07-09 18:11:16 +00001096 }
1097
Ted Kremenek68621b92009-01-28 05:56:51 +00001098 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001099}
1100
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001101RetainSummary* RetainSummaryManager::getCFSummaryGetRule(FunctionDecl* FD) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001102 assert (ScratchArgs.isEmpty());
Ted Kremenek68621b92009-01-28 05:56:51 +00001103 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1104 DoNothing, DoNothing);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001105}
1106
Ted Kremeneka7338b42008-03-11 06:39:11 +00001107//===----------------------------------------------------------------------===//
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001108// Summary creation for Selectors.
1109//===----------------------------------------------------------------------===//
1110
Ted Kremenekbcaff792008-05-06 15:44:25 +00001111RetainSummary*
Ted Kremeneka821b792009-04-29 05:04:30 +00001112RetainSummaryManager::getInitMethodSummary(QualType RetTy) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001113 assert(ScratchArgs.isEmpty());
Ted Kremenek42ea0322008-05-05 23:55:01 +00001114
Ted Kremenek802cfc72009-02-20 00:05:35 +00001115 // 'init' methods only return an alias if the return type is a location type.
Ted Kremeneka821b792009-04-29 05:04:30 +00001116 return getPersistentSummary(Loc::IsLocType(RetTy)
1117 ? RetEffect::MakeReceiverAlias()
Ted Kremenek03d242e2009-05-05 18:44:20 +00001118 : RetEffect::MakeNoRet());
Ted Kremenek42ea0322008-05-05 23:55:01 +00001119}
Ted Kremenek03d242e2009-05-05 18:44:20 +00001120
Ted Kremenekbcaff792008-05-06 15:44:25 +00001121RetainSummary*
Ted Kremenek314b1952009-04-29 23:03:22 +00001122RetainSummaryManager::getCommonMethodSummary(const ObjCMethodDecl* MD,
1123 Selector S, QualType RetTy) {
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001124
Ted Kremenek578498a2009-04-29 00:42:39 +00001125 if (MD) {
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001126 // Scan the method decl for 'void*' arguments. These should be treated
1127 // as 'StopTracking' because they are often used with delegates.
1128 // Delegates are a frequent form of false positives with the retain
1129 // count checker.
1130 unsigned i = 0;
1131 for (ObjCMethodDecl::param_iterator I = MD->param_begin(),
1132 E = MD->param_end(); I != E; ++I, ++i)
1133 if (ParmVarDecl *PD = *I) {
1134 QualType Ty = Ctx.getCanonicalType(PD->getType());
1135 if (Ty.getUnqualifiedType() == Ctx.VoidPtrTy)
Ted Kremeneka56ae162009-05-03 05:20:50 +00001136 ScratchArgs = AF.Add(ScratchArgs, i, StopTracking);
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001137 }
1138 }
1139
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001140 // Any special effect for the receiver?
1141 ArgEffect ReceiverEff = DoNothing;
1142
1143 // If one of the arguments in the selector has the keyword 'delegate' we
1144 // should stop tracking the reference count for the receiver. This is
1145 // because the reference count is quite possibly handled by a delegate
1146 // method.
1147 if (S.isKeywordSelector()) {
1148 const std::string &str = S.getAsString();
1149 assert(!str.empty());
1150 if (CStrInCStrNoCase(&str[0], "delegate:")) ReceiverEff = StopTracking;
1151 }
1152
Ted Kremenek174a0772009-04-23 23:08:22 +00001153 // Look for methods that return an owned object.
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001154 if (isTrackedObjCObjectType(RetTy)) {
1155 // EXPERIMENTAL: Assume the Cocoa conventions for all objects returned
1156 // by instance methods.
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001157 RetEffect E =
1158 followsFundamentalRule(S.getIdentifierInfoForSlot(0)->getName())
Ted Kremenek5535e5e2009-05-07 23:40:42 +00001159 ? ObjCAllocRetE : RetEffect::MakeNotOwned(RetEffect::ObjC);
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001160
1161 return getPersistentSummary(E, ReceiverEff, MayEscape);
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001162 }
Ted Kremenek174a0772009-04-23 23:08:22 +00001163
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001164 // Look for methods that return an owned core foundation object.
1165 if (isTrackedCFObjectType(RetTy)) {
1166 RetEffect E =
1167 followsFundamentalRule(S.getIdentifierInfoForSlot(0)->getName())
1168 ? RetEffect::MakeOwned(RetEffect::CF, true)
1169 : RetEffect::MakeNotOwned(RetEffect::CF);
1170
1171 return getPersistentSummary(E, ReceiverEff, MayEscape);
1172 }
Ted Kremenek174a0772009-04-23 23:08:22 +00001173
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001174 if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing)
Ted Kremenek286e9852009-05-04 04:57:00 +00001175 return getDefaultSummary();
Ted Kremenek174a0772009-04-23 23:08:22 +00001176
Ted Kremenek2f226732009-05-04 05:31:22 +00001177 return getPersistentSummary(RetEffect::MakeNoRet(), ReceiverEff, MayEscape);
Ted Kremenek174a0772009-04-23 23:08:22 +00001178}
1179
1180RetainSummary*
Ted Kremenek04e00302009-04-29 17:09:14 +00001181RetainSummaryManager::getInstanceMethodSummary(Selector S,
1182 IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +00001183 const ObjCInterfaceDecl* ID,
1184 const ObjCMethodDecl *MD,
Ted Kremenek04e00302009-04-29 17:09:14 +00001185 QualType RetTy) {
Ted Kremenekbcaff792008-05-06 15:44:25 +00001186
Ted Kremeneka821b792009-04-29 05:04:30 +00001187 // Look up a summary in our summary cache.
1188 ObjCMethodSummariesTy::iterator I = ObjCMethodSummaries.find(ID, ClsName, S);
Ted Kremenek42ea0322008-05-05 23:55:01 +00001189
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001190 if (I != ObjCMethodSummaries.end())
Ted Kremenek42ea0322008-05-05 23:55:01 +00001191 return I->second;
Ted Kremenek42ea0322008-05-05 23:55:01 +00001192
Ted Kremeneka56ae162009-05-03 05:20:50 +00001193 assert(ScratchArgs.isEmpty());
Ted Kremenek2f226732009-05-04 05:31:22 +00001194 RetainSummary *Summ = 0;
Ted Kremenek1d3d9562008-05-06 06:09:09 +00001195
Ted Kremenek2f226732009-05-04 05:31:22 +00001196 // "initXXX": pass-through for receiver.
1197 if (deriveNamingConvention(S.getIdentifierInfoForSlot(0)->getName())
1198 == InitRule)
1199 Summ = getInitMethodSummary(RetTy);
1200 else
1201 Summ = getCommonMethodSummary(MD, S, RetTy);
1202
Ted Kremenek2f226732009-05-04 05:31:22 +00001203 // Memoize the summary.
Ted Kremeneka821b792009-04-29 05:04:30 +00001204 ObjCMethodSummaries[ObjCSummaryKey(ClsName, S)] = Summ;
Ted Kremeneke4158502009-04-23 19:11:35 +00001205 return Summ;
Ted Kremenek42ea0322008-05-05 23:55:01 +00001206}
1207
Ted Kremeneka7722b72008-05-06 21:26:51 +00001208RetainSummary*
Ted Kremenek578498a2009-04-29 00:42:39 +00001209RetainSummaryManager::getClassMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +00001210 const ObjCInterfaceDecl *ID,
1211 const ObjCMethodDecl *MD,
1212 QualType RetTy) {
Ted Kremenekccbe79a2009-04-24 17:50:11 +00001213
Ted Kremenek578498a2009-04-29 00:42:39 +00001214 assert(ClsName && "Class name must be specified.");
Ted Kremeneka821b792009-04-29 05:04:30 +00001215 ObjCMethodSummariesTy::iterator I =
1216 ObjCClassMethodSummaries.find(ID, ClsName, S);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001217
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001218 if (I != ObjCClassMethodSummaries.end())
Ted Kremeneka7722b72008-05-06 21:26:51 +00001219 return I->second;
Ted Kremenek2f226732009-05-04 05:31:22 +00001220
1221 RetainSummary *Summ = getCommonMethodSummary(MD, S, RetTy);
1222
Ted Kremenek2f226732009-05-04 05:31:22 +00001223 // Memoize the summary.
Ted Kremenek578498a2009-04-29 00:42:39 +00001224 ObjCClassMethodSummaries[ObjCSummaryKey(ClsName, S)] = Summ;
Ted Kremeneke4158502009-04-23 19:11:35 +00001225 return Summ;
Ted Kremeneka7722b72008-05-06 21:26:51 +00001226}
1227
Ted Kremenek5535e5e2009-05-07 23:40:42 +00001228void RetainSummaryManager::InitializeClassMethodSummaries() {
1229 assert(ScratchArgs.isEmpty());
1230 RetainSummary* Summ = getPersistentSummary(ObjCAllocRetE);
Ted Kremenek0e344d42008-05-06 00:30:21 +00001231
Ted Kremenek272aa852008-06-25 21:21:56 +00001232 // Create the summaries for "alloc", "new", and "allocWithZone:" for
1233 // NSObject and its derivatives.
1234 addNSObjectClsMethSummary(GetNullarySelector("alloc", Ctx), Summ);
1235 addNSObjectClsMethSummary(GetNullarySelector("new", Ctx), Summ);
1236 addNSObjectClsMethSummary(GetUnarySelector("allocWithZone", Ctx), Summ);
Ted Kremenekf2717b02008-07-18 17:24:20 +00001237
1238 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001239 addClsMethSummary(&Ctx.Idents.get("NSAssertionHandler"),
Ted Kremenek68621b92009-01-28 05:56:51 +00001240 GetNullarySelector("currentHandler", Ctx),
1241 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001242
1243 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremeneka56ae162009-05-03 05:20:50 +00001244 ScratchArgs = AF.Add(ScratchArgs, 0, Autorelease);
Ted Kremenek9b112d22009-01-28 21:44:40 +00001245 addClsMethSummary(&Ctx.Idents.get("NSAutoreleasePool"),
1246 GetUnarySelector("addObject", Ctx),
1247 getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenekf21cb242009-02-23 02:31:16 +00001248 DoNothing, Autorelease));
Ted Kremenekccbe79a2009-04-24 17:50:11 +00001249
1250 // Create the summaries for [NSObject performSelector...]. We treat
1251 // these as 'stop tracking' for the arguments because they are often
1252 // used for delegates that can release the object. When we have better
1253 // inter-procedural analysis we can potentially do something better. This
1254 // workaround is to remove false positives.
1255 Summ = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, StopTracking);
1256 IdentifierInfo *NSObjectII = &Ctx.Idents.get("NSObject");
1257 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1258 "afterDelay", NULL);
1259 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1260 "afterDelay", "inModes", NULL);
1261 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1262 "withObject", "waitUntilDone", NULL);
1263 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1264 "withObject", "waitUntilDone", "modes", NULL);
1265 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1266 "withObject", "waitUntilDone", NULL);
1267 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1268 "withObject", "waitUntilDone", "modes", NULL);
1269 addClsMethSummary(NSObjectII, Summ, "performSelectorInBackground",
1270 "withObject", NULL);
Ted Kremenek0e344d42008-05-06 00:30:21 +00001271}
1272
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001273void RetainSummaryManager::InitializeMethodSummaries() {
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001274
Ted Kremeneka56ae162009-05-03 05:20:50 +00001275 assert (ScratchArgs.isEmpty());
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001276
Ted Kremeneka7722b72008-05-06 21:26:51 +00001277 // Create the "init" selector. It just acts as a pass-through for the
1278 // receiver.
Ted Kremenek56c70aa2009-02-23 16:54:00 +00001279 RetainSummary* InitSumm =
1280 getPersistentSummary(RetEffect::MakeReceiverAlias());
Ted Kremeneke44927e2008-07-01 17:21:27 +00001281 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001282
1283 // The next methods are allocators.
Ted Kremenek5535e5e2009-05-07 23:40:42 +00001284 RetainSummary* Summ = getPersistentSummary(ObjCAllocRetE);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001285
1286 // Create the "copy" selector.
Ted Kremenek9449ca92008-08-12 20:41:56 +00001287 addNSObjectMethSummary(GetNullarySelector("copy", Ctx), Summ);
1288
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001289 // Create the "mutableCopy" selector.
Ted Kremenek272aa852008-06-25 21:21:56 +00001290 addNSObjectMethSummary(GetNullarySelector("mutableCopy", Ctx), Summ);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001291
Ted Kremenek266d8b62008-05-06 02:26:56 +00001292 // Create the "retain" selector.
Ted Kremenek5535e5e2009-05-07 23:40:42 +00001293 RetEffect E = RetEffect::MakeReceiverAlias();
Ted Kremenek58dd95b2009-02-18 18:54:33 +00001294 Summ = getPersistentSummary(E, IncRefMsg);
Ted Kremenek272aa852008-06-25 21:21:56 +00001295 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001296
1297 // Create the "release" selector.
Ted Kremenek58dd95b2009-02-18 18:54:33 +00001298 Summ = getPersistentSummary(E, DecRefMsg);
Ted Kremenek272aa852008-06-25 21:21:56 +00001299 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Ted Kremenekc00b32b2008-05-07 21:17:39 +00001300
1301 // Create the "drain" selector.
1302 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek272aa852008-06-25 21:21:56 +00001303 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
Ted Kremenek6537a642009-03-17 19:42:23 +00001304
1305 // Create the -dealloc summary.
1306 Summ = getPersistentSummary(RetEffect::MakeNoRet(), Dealloc);
1307 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001308
1309 // Create the "autorelease" selector.
Ted Kremenek9b112d22009-01-28 21:44:40 +00001310 Summ = getPersistentSummary(E, Autorelease);
Ted Kremenek272aa852008-06-25 21:21:56 +00001311 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001312
Ted Kremenekaac82832009-02-23 17:45:03 +00001313 // Specially handle NSAutoreleasePool.
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001314 addInstMethSummary("NSAutoreleasePool", "init",
Ted Kremenekaac82832009-02-23 17:45:03 +00001315 getPersistentSummary(RetEffect::MakeReceiverAlias(),
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001316 NewAutoreleasePool));
Ted Kremenekaac82832009-02-23 17:45:03 +00001317
Ted Kremenek45642a42008-08-12 18:48:50 +00001318 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremenek7e3a3272009-02-23 02:51:29 +00001319 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1320 // self-own themselves. However, they only do this once they are displayed.
1321 // Thus, we need to track an NSWindow's display status.
1322 // This is tracked in <rdar://problem/6062711>.
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001323 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
Ted Kremeneke5a036a2009-04-03 19:02:51 +00001324 RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet());
1325
1326 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1327
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001328
1329#if 0
Ted Kremeneke44927e2008-07-01 17:21:27 +00001330 RetainSummary *NSWindowSumm =
Ted Kremenek7e3a3272009-02-23 02:51:29 +00001331 getPersistentSummary(RetEffect::MakeReceiverAlias(), StopTracking);
Ted Kremenek45642a42008-08-12 18:48:50 +00001332
1333 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1334 "styleMask", "backing", "defer", NULL);
1335
1336 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1337 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001338#endif
Ted Kremenek45642a42008-08-12 18:48:50 +00001339
1340 // For NSPanel (which subclasses NSWindow), allocated objects are not
1341 // self-owned.
Ted Kremeneke5a036a2009-04-03 19:02:51 +00001342 // FIXME: For now we don't track NSPanels. object for the same reason
1343 // as for NSWindow objects.
1344 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
1345
Ted Kremenek45642a42008-08-12 18:48:50 +00001346 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1347 "styleMask", "backing", "defer", NULL);
1348
1349 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1350 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek272aa852008-06-25 21:21:56 +00001351
Ted Kremenekf2717b02008-07-18 17:24:20 +00001352 // Create NSAssertionHandler summaries.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001353 addPanicSummary("NSAssertionHandler", "handleFailureInFunction", "file",
1354 "lineNumber", "description", NULL);
Ted Kremenekf2717b02008-07-18 17:24:20 +00001355
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001356 addPanicSummary("NSAssertionHandler", "handleFailureInMethod", "object",
1357 "file", "lineNumber", "description", NULL);
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001358}
1359
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001360//===----------------------------------------------------------------------===//
Ted Kremenek7aef4842008-04-16 20:40:59 +00001361// Reference-counting logic (typestate + counts).
Ted Kremeneka7338b42008-03-11 06:39:11 +00001362//===----------------------------------------------------------------------===//
1363
Ted Kremeneka7338b42008-03-11 06:39:11 +00001364namespace {
1365
Ted Kremenek7d421f32008-04-09 23:49:11 +00001366class VISIBILITY_HIDDEN RefVal {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001367public:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001368 enum Kind {
1369 Owned = 0, // Owning reference.
1370 NotOwned, // Reference is not owned by still valid (not freed).
1371 Released, // Object has been released.
1372 ReturnedOwned, // Returned object passes ownership to caller.
1373 ReturnedNotOwned, // Return object does not pass ownership to caller.
Ted Kremenek6537a642009-03-17 19:42:23 +00001374 ERROR_START,
1375 ErrorDeallocNotOwned, // -dealloc called on non-owned object.
1376 ErrorDeallocGC, // Calling -dealloc with GC enabled.
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001377 ErrorUseAfterRelease, // Object used after released.
1378 ErrorReleaseNotOwned, // Release of an object that was not owned.
Ted Kremenek6537a642009-03-17 19:42:23 +00001379 ERROR_LEAK_START,
Ted Kremenek311f3d42008-10-22 23:56:21 +00001380 ErrorLeak, // A memory leak due to excessive reference counts.
1381 ErrorLeakReturned // A memory leak due to the returning method not having
1382 // the correct naming conventions.
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001383 };
Ted Kremenek68621b92009-01-28 05:56:51 +00001384
1385private:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001386 Kind kind;
Ted Kremenek68621b92009-01-28 05:56:51 +00001387 RetEffect::ObjKind okind;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001388 unsigned Cnt;
Ted Kremenek4d99d342009-05-08 20:01:42 +00001389 unsigned ACnt;
Ted Kremenek272aa852008-06-25 21:21:56 +00001390 QualType T;
1391
Ted Kremenek4d99d342009-05-08 20:01:42 +00001392 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, unsigned acnt, QualType t)
1393 : kind(k), okind(o), Cnt(cnt), ACnt(acnt), T(t) {}
Ted Kremenek0d721572008-03-11 17:48:22 +00001394
Ted Kremenek68621b92009-01-28 05:56:51 +00001395 RefVal(Kind k, unsigned cnt = 0)
Ted Kremenek4d99d342009-05-08 20:01:42 +00001396 : kind(k), okind(RetEffect::AnyObj), Cnt(cnt), ACnt(0) {}
Ted Kremenek68621b92009-01-28 05:56:51 +00001397
1398public:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001399 Kind getKind() const { return kind; }
Ted Kremenek68621b92009-01-28 05:56:51 +00001400
1401 RetEffect::ObjKind getObjKind() const { return okind; }
Ted Kremenek0d721572008-03-11 17:48:22 +00001402
Ted Kremenek4d99d342009-05-08 20:01:42 +00001403 unsigned getCount() const { return Cnt; }
1404 unsigned getAutoreleaseCount() const { return ACnt; }
1405 unsigned getCombinedCounts() const { return Cnt + ACnt; }
1406 void clearCounts() { Cnt = 0; ACnt = 0; }
Ted Kremenek6537a642009-03-17 19:42:23 +00001407
Ted Kremenek272aa852008-06-25 21:21:56 +00001408 QualType getType() const { return T; }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001409
1410 // Useful predicates.
Ted Kremenek0d721572008-03-11 17:48:22 +00001411
Ted Kremenek6537a642009-03-17 19:42:23 +00001412 static bool isError(Kind k) { return k >= ERROR_START; }
Ted Kremenek1daa16c2008-03-11 18:14:09 +00001413
Ted Kremenek6537a642009-03-17 19:42:23 +00001414 static bool isLeak(Kind k) { return k >= ERROR_LEAK_START; }
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001415
Ted Kremenekffefc352008-04-11 22:25:11 +00001416 bool isOwned() const {
1417 return getKind() == Owned;
1418 }
1419
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001420 bool isNotOwned() const {
1421 return getKind() == NotOwned;
1422 }
1423
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001424 bool isReturnedOwned() const {
1425 return getKind() == ReturnedOwned;
1426 }
1427
1428 bool isReturnedNotOwned() const {
1429 return getKind() == ReturnedNotOwned;
1430 }
1431
1432 bool isNonLeakError() const {
1433 Kind k = getKind();
1434 return isError(k) && !isLeak(k);
1435 }
1436
Ted Kremenek68621b92009-01-28 05:56:51 +00001437 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
1438 unsigned Count = 1) {
Ted Kremenek4d99d342009-05-08 20:01:42 +00001439 return RefVal(Owned, o, Count, 0, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001440 }
1441
Ted Kremenek68621b92009-01-28 05:56:51 +00001442 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
1443 unsigned Count = 0) {
Ted Kremenek4d99d342009-05-08 20:01:42 +00001444 return RefVal(NotOwned, o, Count, 0, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001445 }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001446
1447 static RefVal makeReturnedOwned(unsigned Count) {
1448 return RefVal(ReturnedOwned, Count);
1449 }
1450
1451 static RefVal makeReturnedNotOwned() {
1452 return RefVal(ReturnedNotOwned);
1453 }
1454
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001455 // Comparison, profiling, and pretty-printing.
Ted Kremenek0d721572008-03-11 17:48:22 +00001456
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001457 bool operator==(const RefVal& X) const {
Ted Kremenek272aa852008-06-25 21:21:56 +00001458 return kind == X.kind && Cnt == X.Cnt && T == X.T;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001459 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001460
Ted Kremenek272aa852008-06-25 21:21:56 +00001461 RefVal operator-(size_t i) const {
Ted Kremenek4d99d342009-05-08 20:01:42 +00001462 return RefVal(getKind(), getObjKind(), getCount() - i,
1463 getAutoreleaseCount(), getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001464 }
1465
1466 RefVal operator+(size_t i) const {
Ted Kremenek4d99d342009-05-08 20:01:42 +00001467 return RefVal(getKind(), getObjKind(), getCount() + i,
1468 getAutoreleaseCount(), getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001469 }
1470
1471 RefVal operator^(Kind k) const {
Ted Kremenek4d99d342009-05-08 20:01:42 +00001472 return RefVal(k, getObjKind(), getCount(), getAutoreleaseCount(),
1473 getType());
1474 }
1475
1476 RefVal autorelease() const {
1477 return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount()+1,
1478 getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001479 }
Ted Kremenek6537a642009-03-17 19:42:23 +00001480
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001481 void Profile(llvm::FoldingSetNodeID& ID) const {
1482 ID.AddInteger((unsigned) kind);
1483 ID.AddInteger(Cnt);
Ted Kremenek4d99d342009-05-08 20:01:42 +00001484 ID.AddInteger(ACnt);
Ted Kremenek272aa852008-06-25 21:21:56 +00001485 ID.Add(T);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001486 }
1487
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001488 void print(std::ostream& Out) const;
Ted Kremenek0d721572008-03-11 17:48:22 +00001489};
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001490
1491void RefVal::print(std::ostream& Out) const {
Ted Kremenek272aa852008-06-25 21:21:56 +00001492 if (!T.isNull())
1493 Out << "Tracked Type:" << T.getAsString() << '\n';
1494
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001495 switch (getKind()) {
1496 default: assert(false);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001497 case Owned: {
1498 Out << "Owned";
1499 unsigned cnt = getCount();
1500 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001501 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001502 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001503
Ted Kremenekc4f81022008-04-10 23:09:18 +00001504 case NotOwned: {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001505 Out << "NotOwned";
Ted Kremenekc4f81022008-04-10 23:09:18 +00001506 unsigned cnt = getCount();
1507 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001508 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001509 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001510
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001511 case ReturnedOwned: {
1512 Out << "ReturnedOwned";
1513 unsigned cnt = getCount();
1514 if (cnt) Out << " (+ " << cnt << ")";
1515 break;
1516 }
1517
1518 case ReturnedNotOwned: {
1519 Out << "ReturnedNotOwned";
1520 unsigned cnt = getCount();
1521 if (cnt) Out << " (+ " << cnt << ")";
1522 break;
1523 }
1524
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001525 case Released:
1526 Out << "Released";
1527 break;
Ted Kremenek6537a642009-03-17 19:42:23 +00001528
1529 case ErrorDeallocGC:
1530 Out << "-dealloc (GC)";
1531 break;
1532
1533 case ErrorDeallocNotOwned:
1534 Out << "-dealloc (not-owned)";
1535 break;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001536
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001537 case ErrorLeak:
1538 Out << "Leaked";
1539 break;
1540
Ted Kremenek311f3d42008-10-22 23:56:21 +00001541 case ErrorLeakReturned:
1542 Out << "Leaked (Bad naming)";
1543 break;
1544
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001545 case ErrorUseAfterRelease:
1546 Out << "Use-After-Release [ERROR]";
1547 break;
1548
1549 case ErrorReleaseNotOwned:
1550 Out << "Release of Not-Owned [ERROR]";
1551 break;
1552 }
Ted Kremenek4d99d342009-05-08 20:01:42 +00001553
1554 if (ACnt) {
1555 Out << " [ARC +" << ACnt << ']';
1556 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001557}
Ted Kremenek0d721572008-03-11 17:48:22 +00001558
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001559} // end anonymous namespace
1560
1561//===----------------------------------------------------------------------===//
1562// RefBindings - State used to track object reference counts.
1563//===----------------------------------------------------------------------===//
1564
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001565typedef llvm::ImmutableMap<SymbolRef, RefVal> RefBindings;
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001566static int RefBIndex = 0;
1567
1568namespace clang {
Ted Kremenek91781202008-08-17 03:20:02 +00001569 template<>
1570 struct GRStateTrait<RefBindings> : public GRStatePartialTrait<RefBindings> {
1571 static inline void* GDMIndex() { return &RefBIndex; }
1572 };
1573}
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001574
1575//===----------------------------------------------------------------------===//
Ted Kremenekb6578942009-02-24 19:15:11 +00001576// AutoreleaseBindings - State used to track objects in autorelease pools.
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001577//===----------------------------------------------------------------------===//
1578
Ted Kremenekb6578942009-02-24 19:15:11 +00001579typedef llvm::ImmutableMap<SymbolRef, unsigned> ARCounts;
1580typedef llvm::ImmutableMap<SymbolRef, ARCounts> ARPoolContents;
1581typedef llvm::ImmutableList<SymbolRef> ARStack;
Ted Kremenekaac82832009-02-23 17:45:03 +00001582
Ted Kremenekb6578942009-02-24 19:15:11 +00001583static int AutoRCIndex = 0;
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001584static int AutoRBIndex = 0;
1585
Ted Kremenekb6578942009-02-24 19:15:11 +00001586namespace { class VISIBILITY_HIDDEN AutoreleasePoolContents {}; }
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001587namespace { class VISIBILITY_HIDDEN AutoreleaseStack {}; }
Ted Kremenekb6578942009-02-24 19:15:11 +00001588
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001589namespace clang {
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001590template<> struct GRStateTrait<AutoreleaseStack>
Ted Kremenekb6578942009-02-24 19:15:11 +00001591 : public GRStatePartialTrait<ARStack> {
1592 static inline void* GDMIndex() { return &AutoRBIndex; }
1593};
1594
1595template<> struct GRStateTrait<AutoreleasePoolContents>
1596 : public GRStatePartialTrait<ARPoolContents> {
1597 static inline void* GDMIndex() { return &AutoRCIndex; }
1598};
1599} // end clang namespace
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001600
Ted Kremenek681fb352009-03-20 17:34:15 +00001601static SymbolRef GetCurrentAutoreleasePool(const GRState* state) {
1602 ARStack stack = state->get<AutoreleaseStack>();
1603 return stack.isEmpty() ? SymbolRef() : stack.getHead();
1604}
1605
1606static GRStateRef SendAutorelease(GRStateRef state, ARCounts::Factory &F,
1607 SymbolRef sym) {
1608
1609 SymbolRef pool = GetCurrentAutoreleasePool(state);
1610 const ARCounts *cnts = state.get<AutoreleasePoolContents>(pool);
1611 ARCounts newCnts(0);
1612
1613 if (cnts) {
1614 const unsigned *cnt = (*cnts).lookup(sym);
1615 newCnts = F.Add(*cnts, sym, cnt ? *cnt + 1 : 1);
1616 }
1617 else
1618 newCnts = F.Add(F.GetEmptyMap(), sym, 1);
1619
1620 return state.set<AutoreleasePoolContents>(pool, newCnts);
1621}
1622
Ted Kremenek7aef4842008-04-16 20:40:59 +00001623//===----------------------------------------------------------------------===//
1624// Transfer functions.
1625//===----------------------------------------------------------------------===//
1626
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001627namespace {
1628
Ted Kremenek7d421f32008-04-09 23:49:11 +00001629class VISIBILITY_HIDDEN CFRefCount : public GRSimpleVals {
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001630public:
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001631 class BindingsPrinter : public GRState::Printer {
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001632 public:
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001633 virtual void Print(std::ostream& Out, const GRState* state,
1634 const char* nl, const char* sep);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001635 };
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001636
1637private:
Ted Kremenekc26c4692009-02-18 03:48:14 +00001638 typedef llvm::DenseMap<const GRExprEngine::NodeTy*, const RetainSummary*>
1639 SummaryLogTy;
1640
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001641 RetainSummaryManager Summaries;
Ted Kremenekc26c4692009-02-18 03:48:14 +00001642 SummaryLogTy SummaryLog;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001643 const LangOptions& LOpts;
Ted Kremenekb6578942009-02-24 19:15:11 +00001644 ARCounts::Factory ARCountFactory;
Ted Kremenek91781202008-08-17 03:20:02 +00001645
Ted Kremenek708af042009-02-05 06:50:21 +00001646 BugType *useAfterRelease, *releaseNotOwned;
Ted Kremenek6537a642009-03-17 19:42:23 +00001647 BugType *deallocGC, *deallocNotOwned;
Ted Kremenek708af042009-02-05 06:50:21 +00001648 BugType *leakWithinFunction, *leakAtReturn;
1649 BugReporter *BR;
Ted Kremeneka7338b42008-03-11 06:39:11 +00001650
Ted Kremenekb6578942009-02-24 19:15:11 +00001651 GRStateRef Update(GRStateRef state, SymbolRef sym, RefVal V, ArgEffect E,
1652 RefVal::Kind& hasErr);
1653
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001654 void ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
1655 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001656 Expr* NodeExpr, Expr* ErrorExpr,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001657 ExplodedNode<GRState>* Pred,
1658 const GRState* St,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001659 RefVal::Kind hasErr, SymbolRef Sym);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001660
Ted Kremenek41a4bc62009-05-08 23:09:42 +00001661 GRStateRef HandleSymbolDeath(GRStateRef state, SymbolRef sid, RefVal V,
1662 llvm::SmallVectorImpl<SymbolRef> &Leaked);
1663
1664 ExplodedNode<GRState>* ProcessLeaks(GRStateRef state,
1665 llvm::SmallVectorImpl<SymbolRef> &Leaked,
1666 GenericNodeBuilder &Builder,
1667 GRExprEngine &Eng,
1668 ExplodedNode<GRState> *Pred = 0);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001669
Ted Kremenekb6578942009-02-24 19:15:11 +00001670public:
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00001671 CFRefCount(ASTContext& Ctx, bool gcenabled, const LangOptions& lopts)
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001672 : Summaries(Ctx, gcenabled),
Ted Kremenek6537a642009-03-17 19:42:23 +00001673 LOpts(lopts), useAfterRelease(0), releaseNotOwned(0),
1674 deallocGC(0), deallocNotOwned(0),
Ted Kremenek708af042009-02-05 06:50:21 +00001675 leakWithinFunction(0), leakAtReturn(0), BR(0) {}
Ted Kremenek1feab292008-04-16 04:28:53 +00001676
Ted Kremenek708af042009-02-05 06:50:21 +00001677 virtual ~CFRefCount() {}
Ted Kremenek7d421f32008-04-09 23:49:11 +00001678
Ted Kremenekbf6babf2009-02-04 23:49:09 +00001679 void RegisterChecks(BugReporter &BR);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001680
Ted Kremenekb0f2b9e2008-08-16 00:49:49 +00001681 virtual void RegisterPrinters(std::vector<GRState::Printer*>& Printers) {
1682 Printers.push_back(new BindingsPrinter());
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001683 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00001684
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001685 bool isGCEnabled() const { return Summaries.isGCEnabled(); }
Ted Kremenekfe30beb2008-04-30 23:47:44 +00001686 const LangOptions& getLangOptions() const { return LOpts; }
1687
Ted Kremenekc26c4692009-02-18 03:48:14 +00001688 const RetainSummary *getSummaryOfNode(const ExplodedNode<GRState> *N) const {
1689 SummaryLogTy::const_iterator I = SummaryLog.find(N);
1690 return I == SummaryLog.end() ? 0 : I->second;
1691 }
1692
Ted Kremeneka7338b42008-03-11 06:39:11 +00001693 // Calls.
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001694
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001695 void EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001696 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001697 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001698 Expr* Ex,
1699 Expr* Receiver,
Ted Kremenek286e9852009-05-04 04:57:00 +00001700 const RetainSummary& Summ,
Ted Kremenek2719e982008-06-17 02:43:46 +00001701 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001702 ExplodedNode<GRState>* Pred);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001703
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001704 virtual void EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekce0767f2008-03-12 21:06:49 +00001705 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001706 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001707 CallExpr* CE, SVal L,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001708 ExplodedNode<GRState>* Pred);
Ted Kremenek10fe66d2008-04-09 01:10:13 +00001709
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001710
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001711 virtual void EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001712 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001713 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001714 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001715 ExplodedNode<GRState>* Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001716
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001717 bool EvalObjCMessageExprAux(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001718 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001719 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001720 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001721 ExplodedNode<GRState>* Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001722
Ted Kremeneka42be302009-02-14 01:43:44 +00001723 // Stores.
1724 virtual void EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val);
1725
Ted Kremenekffefc352008-04-11 22:25:11 +00001726 // End-of-path.
1727
1728 virtual void EvalEndPath(GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001729 GREndPathNodeBuilder<GRState>& Builder);
Ted Kremenekffefc352008-04-11 22:25:11 +00001730
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001731 virtual void EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek541db372008-04-24 23:57:27 +00001732 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001733 GRStmtNodeBuilder<GRState>& Builder,
1734 ExplodedNode<GRState>* Pred,
Ted Kremenek5c0729b2009-01-21 22:26:05 +00001735 Stmt* S, const GRState* state,
1736 SymbolReaper& SymReaper);
1737
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001738 // Return statements.
1739
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001740 virtual void EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001741 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001742 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001743 ReturnStmt* S,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001744 ExplodedNode<GRState>* Pred);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001745
1746 // Assumptions.
1747
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001748 virtual const GRState* EvalAssume(GRStateManager& VMgr,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001749 const GRState* St, SVal Cond,
Ted Kremenekf22f8682008-07-10 22:03:41 +00001750 bool Assumption, bool& isFeasible);
Ted Kremeneka7338b42008-03-11 06:39:11 +00001751};
1752
1753} // end anonymous namespace
1754
Ted Kremenek681fb352009-03-20 17:34:15 +00001755static void PrintPool(std::ostream &Out, SymbolRef Sym, const GRState *state) {
1756 Out << ' ';
Ted Kremenek74556a12009-03-26 03:35:11 +00001757 if (Sym)
1758 Out << Sym->getSymbolID();
Ted Kremenek681fb352009-03-20 17:34:15 +00001759 else
1760 Out << "<pool>";
1761 Out << ":{";
1762
1763 // Get the contents of the pool.
1764 if (const ARCounts *cnts = state->get<AutoreleasePoolContents>(Sym))
1765 for (ARCounts::iterator J=cnts->begin(), EJ=cnts->end(); J != EJ; ++J)
1766 Out << '(' << J.getKey() << ',' << J.getData() << ')';
1767
1768 Out << '}';
1769}
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001770
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001771void CFRefCount::BindingsPrinter::Print(std::ostream& Out, const GRState* state,
1772 const char* nl, const char* sep) {
Ted Kremenek681fb352009-03-20 17:34:15 +00001773
1774
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001775
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001776 RefBindings B = state->get<RefBindings>();
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001777
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001778 if (!B.isEmpty())
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001779 Out << sep << nl;
1780
1781 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
1782 Out << (*I).first << " : ";
1783 (*I).second.print(Out);
1784 Out << nl;
1785 }
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001786
1787 // Print the autorelease stack.
Ted Kremenek681fb352009-03-20 17:34:15 +00001788 Out << sep << nl << "AR pool stack:";
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001789 ARStack stack = state->get<AutoreleaseStack>();
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001790
Ted Kremenek681fb352009-03-20 17:34:15 +00001791 PrintPool(Out, SymbolRef(), state); // Print the caller's pool.
1792 for (ARStack::iterator I=stack.begin(), E=stack.end(); I!=E; ++I)
1793 PrintPool(Out, *I, state);
1794
1795 Out << nl;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001796}
1797
Ted Kremenek47a72422009-04-29 18:50:19 +00001798//===----------------------------------------------------------------------===//
1799// Error reporting.
1800//===----------------------------------------------------------------------===//
1801
1802namespace {
1803
1804 //===-------------===//
1805 // Bug Descriptions. //
1806 //===-------------===//
1807
1808 class VISIBILITY_HIDDEN CFRefBug : public BugType {
1809 protected:
1810 CFRefCount& TF;
1811
1812 CFRefBug(CFRefCount* tf, const char* name)
1813 : BugType(name, "Memory (Core Foundation/Objective-C)"), TF(*tf) {}
1814 public:
1815
1816 CFRefCount& getTF() { return TF; }
1817 const CFRefCount& getTF() const { return TF; }
1818
1819 // FIXME: Eventually remove.
1820 virtual const char* getDescription() const = 0;
1821
1822 virtual bool isLeak() const { return false; }
1823 };
1824
1825 class VISIBILITY_HIDDEN UseAfterRelease : public CFRefBug {
1826 public:
1827 UseAfterRelease(CFRefCount* tf)
1828 : CFRefBug(tf, "Use-after-release") {}
1829
1830 const char* getDescription() const {
1831 return "Reference-counted object is used after it is released";
1832 }
1833 };
1834
1835 class VISIBILITY_HIDDEN BadRelease : public CFRefBug {
1836 public:
1837 BadRelease(CFRefCount* tf) : CFRefBug(tf, "Bad release") {}
1838
1839 const char* getDescription() const {
1840 return "Incorrect decrement of the reference count of an "
1841 "object is not owned at this point by the caller";
1842 }
1843 };
1844
1845 class VISIBILITY_HIDDEN DeallocGC : public CFRefBug {
1846 public:
1847 DeallocGC(CFRefCount *tf) : CFRefBug(tf,
1848 "-dealloc called while using GC") {}
1849
1850 const char *getDescription() const {
1851 return "-dealloc called while using GC";
1852 }
1853 };
1854
1855 class VISIBILITY_HIDDEN DeallocNotOwned : public CFRefBug {
1856 public:
1857 DeallocNotOwned(CFRefCount *tf) : CFRefBug(tf,
1858 "-dealloc sent to non-exclusively owned object") {}
1859
1860 const char *getDescription() const {
1861 return "-dealloc sent to object that may be referenced elsewhere";
1862 }
1863 };
1864
1865 class VISIBILITY_HIDDEN Leak : public CFRefBug {
1866 const bool isReturn;
1867 protected:
1868 Leak(CFRefCount* tf, const char* name, bool isRet)
1869 : CFRefBug(tf, name), isReturn(isRet) {}
1870 public:
1871
1872 const char* getDescription() const { return ""; }
1873
1874 bool isLeak() const { return true; }
1875 };
1876
1877 class VISIBILITY_HIDDEN LeakAtReturn : public Leak {
1878 public:
1879 LeakAtReturn(CFRefCount* tf, const char* name)
1880 : Leak(tf, name, true) {}
1881 };
1882
1883 class VISIBILITY_HIDDEN LeakWithinFunction : public Leak {
1884 public:
1885 LeakWithinFunction(CFRefCount* tf, const char* name)
1886 : Leak(tf, name, false) {}
1887 };
1888
1889 //===---------===//
1890 // Bug Reports. //
1891 //===---------===//
1892
1893 class VISIBILITY_HIDDEN CFRefReport : public RangedBugReport {
1894 protected:
1895 SymbolRef Sym;
1896 const CFRefCount &TF;
1897 public:
1898 CFRefReport(CFRefBug& D, const CFRefCount &tf,
1899 ExplodedNode<GRState> *n, SymbolRef sym)
1900 : RangedBugReport(D, D.getDescription(), n), Sym(sym), TF(tf) {}
1901
1902 virtual ~CFRefReport() {}
1903
1904 CFRefBug& getBugType() {
1905 return (CFRefBug&) RangedBugReport::getBugType();
1906 }
1907 const CFRefBug& getBugType() const {
1908 return (const CFRefBug&) RangedBugReport::getBugType();
1909 }
1910
1911 virtual void getRanges(BugReporter& BR, const SourceRange*& beg,
1912 const SourceRange*& end) {
1913
1914 if (!getBugType().isLeak())
1915 RangedBugReport::getRanges(BR, beg, end);
1916 else
1917 beg = end = 0;
1918 }
1919
1920 SymbolRef getSymbol() const { return Sym; }
1921
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00001922 PathDiagnosticPiece* getEndPath(BugReporterContext& BRC,
Ted Kremenek47a72422009-04-29 18:50:19 +00001923 const ExplodedNode<GRState>* N);
1924
1925 std::pair<const char**,const char**> getExtraDescriptiveText();
1926
1927 PathDiagnosticPiece* VisitNode(const ExplodedNode<GRState>* N,
1928 const ExplodedNode<GRState>* PrevN,
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00001929 BugReporterContext& BRC);
Ted Kremenek47a72422009-04-29 18:50:19 +00001930 };
1931
1932 class VISIBILITY_HIDDEN CFRefLeakReport : public CFRefReport {
1933 SourceLocation AllocSite;
1934 const MemRegion* AllocBinding;
1935 public:
1936 CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
1937 ExplodedNode<GRState> *n, SymbolRef sym,
1938 GRExprEngine& Eng);
1939
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00001940 PathDiagnosticPiece* getEndPath(BugReporterContext& BRC,
Ted Kremenek47a72422009-04-29 18:50:19 +00001941 const ExplodedNode<GRState>* N);
1942
1943 SourceLocation getLocation() const { return AllocSite; }
1944 };
1945} // end anonymous namespace
1946
1947void CFRefCount::RegisterChecks(BugReporter& BR) {
1948 useAfterRelease = new UseAfterRelease(this);
1949 BR.Register(useAfterRelease);
1950
1951 releaseNotOwned = new BadRelease(this);
1952 BR.Register(releaseNotOwned);
1953
1954 deallocGC = new DeallocGC(this);
1955 BR.Register(deallocGC);
1956
1957 deallocNotOwned = new DeallocNotOwned(this);
1958 BR.Register(deallocNotOwned);
1959
1960 // First register "return" leaks.
1961 const char* name = 0;
1962
1963 if (isGCEnabled())
1964 name = "Leak of returned object when using garbage collection";
1965 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
1966 name = "Leak of returned object when not using garbage collection (GC) in "
1967 "dual GC/non-GC code";
1968 else {
1969 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
1970 name = "Leak of returned object";
1971 }
1972
1973 leakAtReturn = new LeakAtReturn(this, name);
1974 BR.Register(leakAtReturn);
1975
1976 // Second, register leaks within a function/method.
1977 if (isGCEnabled())
1978 name = "Leak of object when using garbage collection";
1979 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
1980 name = "Leak of object when not using garbage collection (GC) in "
1981 "dual GC/non-GC code";
1982 else {
1983 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
1984 name = "Leak";
1985 }
1986
1987 leakWithinFunction = new LeakWithinFunction(this, name);
1988 BR.Register(leakWithinFunction);
1989
1990 // Save the reference to the BugReporter.
1991 this->BR = &BR;
1992}
1993
1994static const char* Msgs[] = {
1995 // GC only
1996 "Code is compiled to only use garbage collection",
1997 // No GC.
1998 "Code is compiled to use reference counts",
1999 // Hybrid, with GC.
2000 "Code is compiled to use either garbage collection (GC) or reference counts"
2001 " (non-GC). The bug occurs with GC enabled",
2002 // Hybrid, without GC
2003 "Code is compiled to use either garbage collection (GC) or reference counts"
2004 " (non-GC). The bug occurs in non-GC mode"
2005};
2006
2007std::pair<const char**,const char**> CFRefReport::getExtraDescriptiveText() {
2008 CFRefCount& TF = static_cast<CFRefBug&>(getBugType()).getTF();
2009
2010 switch (TF.getLangOptions().getGCMode()) {
2011 default:
2012 assert(false);
2013
2014 case LangOptions::GCOnly:
2015 assert (TF.isGCEnabled());
2016 return std::make_pair(&Msgs[0], &Msgs[0]+1);
2017
2018 case LangOptions::NonGC:
2019 assert (!TF.isGCEnabled());
2020 return std::make_pair(&Msgs[1], &Msgs[1]+1);
2021
2022 case LangOptions::HybridGC:
2023 if (TF.isGCEnabled())
2024 return std::make_pair(&Msgs[2], &Msgs[2]+1);
2025 else
2026 return std::make_pair(&Msgs[3], &Msgs[3]+1);
2027 }
2028}
2029
2030static inline bool contains(const llvm::SmallVectorImpl<ArgEffect>& V,
2031 ArgEffect X) {
2032 for (llvm::SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
2033 I!=E; ++I)
2034 if (*I == X) return true;
2035
2036 return false;
2037}
2038
2039PathDiagnosticPiece* CFRefReport::VisitNode(const ExplodedNode<GRState>* N,
2040 const ExplodedNode<GRState>* PrevN,
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002041 BugReporterContext& BRC) {
Ted Kremenek47a72422009-04-29 18:50:19 +00002042
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002043 // Check if the type state has changed.
2044 GRStateManager &StMgr = BRC.getStateManager();
Ted Kremenek47a72422009-04-29 18:50:19 +00002045 GRStateRef PrevSt(PrevN->getState(), StMgr);
2046 GRStateRef CurrSt(N->getState(), StMgr);
2047
2048 const RefVal* CurrT = CurrSt.get<RefBindings>(Sym);
2049 if (!CurrT) return NULL;
2050
2051 const RefVal& CurrV = *CurrT;
2052 const RefVal* PrevT = PrevSt.get<RefBindings>(Sym);
2053
2054 // Create a string buffer to constain all the useful things we want
2055 // to tell the user.
2056 std::string sbuf;
2057 llvm::raw_string_ostream os(sbuf);
2058
2059 // This is the allocation site since the previous node had no bindings
2060 // for this symbol.
2061 if (!PrevT) {
2062 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2063
2064 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2065 // Get the name of the callee (if it is available).
2066 SVal X = CurrSt.GetSValAsScalarOrLoc(CE->getCallee());
2067 if (const FunctionDecl* FD = X.getAsFunctionDecl())
2068 os << "Call to function '" << FD->getNameAsString() <<'\'';
2069 else
2070 os << "function call";
2071 }
2072 else {
2073 assert (isa<ObjCMessageExpr>(S));
2074 os << "Method";
2075 }
2076
2077 if (CurrV.getObjKind() == RetEffect::CF) {
2078 os << " returns a Core Foundation object with a ";
2079 }
2080 else {
2081 assert (CurrV.getObjKind() == RetEffect::ObjC);
2082 os << " returns an Objective-C object with a ";
2083 }
2084
2085 if (CurrV.isOwned()) {
2086 os << "+1 retain count (owning reference).";
2087
2088 if (static_cast<CFRefBug&>(getBugType()).getTF().isGCEnabled()) {
2089 assert(CurrV.getObjKind() == RetEffect::CF);
2090 os << " "
2091 "Core Foundation objects are not automatically garbage collected.";
2092 }
2093 }
2094 else {
2095 assert (CurrV.isNotOwned());
2096 os << "+0 retain count (non-owning reference).";
2097 }
2098
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002099 PathDiagnosticLocation Pos(S, BRC.getSourceManager());
Ted Kremenek47a72422009-04-29 18:50:19 +00002100 return new PathDiagnosticEventPiece(Pos, os.str());
2101 }
2102
2103 // Gather up the effects that were performed on the object at this
2104 // program point
2105 llvm::SmallVector<ArgEffect, 2> AEffects;
2106
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002107 if (const RetainSummary *Summ =
2108 TF.getSummaryOfNode(BRC.getNodeResolver().getOriginalNode(N))) {
Ted Kremenek47a72422009-04-29 18:50:19 +00002109 // We only have summaries attached to nodes after evaluating CallExpr and
2110 // ObjCMessageExprs.
2111 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2112
2113 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2114 // Iterate through the parameter expressions and see if the symbol
2115 // was ever passed as an argument.
2116 unsigned i = 0;
2117
2118 for (CallExpr::arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
2119 AI!=AE; ++AI, ++i) {
2120
2121 // Retrieve the value of the argument. Is it the symbol
2122 // we are interested in?
2123 if (CurrSt.GetSValAsScalarOrLoc(*AI).getAsLocSymbol() != Sym)
2124 continue;
2125
2126 // We have an argument. Get the effect!
2127 AEffects.push_back(Summ->getArg(i));
2128 }
2129 }
2130 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
2131 if (Expr *receiver = ME->getReceiver())
2132 if (CurrSt.GetSValAsScalarOrLoc(receiver).getAsLocSymbol() == Sym) {
2133 // The symbol we are tracking is the receiver.
2134 AEffects.push_back(Summ->getReceiverEffect());
2135 }
2136 }
2137 }
2138
2139 do {
2140 // Get the previous type state.
2141 RefVal PrevV = *PrevT;
2142
2143 // Specially handle -dealloc.
2144 if (!TF.isGCEnabled() && contains(AEffects, Dealloc)) {
2145 // Determine if the object's reference count was pushed to zero.
2146 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2147 // We may not have transitioned to 'release' if we hit an error.
2148 // This case is handled elsewhere.
2149 if (CurrV.getKind() == RefVal::Released) {
Ted Kremenek4d99d342009-05-08 20:01:42 +00002150 assert(CurrV.getCombinedCounts() == 0);
Ted Kremenek47a72422009-04-29 18:50:19 +00002151 os << "Object released by directly sending the '-dealloc' message";
2152 break;
2153 }
2154 }
2155
2156 // Specially handle CFMakeCollectable and friends.
2157 if (contains(AEffects, MakeCollectable)) {
2158 // Get the name of the function.
2159 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2160 SVal X = CurrSt.GetSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee());
2161 const FunctionDecl* FD = X.getAsFunctionDecl();
2162 const std::string& FName = FD->getNameAsString();
2163
2164 if (TF.isGCEnabled()) {
2165 // Determine if the object's reference count was pushed to zero.
2166 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2167
2168 os << "In GC mode a call to '" << FName
2169 << "' decrements an object's retain count and registers the "
2170 "object with the garbage collector. ";
2171
2172 if (CurrV.getKind() == RefVal::Released) {
2173 assert(CurrV.getCount() == 0);
2174 os << "Since it now has a 0 retain count the object can be "
2175 "automatically collected by the garbage collector.";
2176 }
2177 else
2178 os << "An object must have a 0 retain count to be garbage collected. "
2179 "After this call its retain count is +" << CurrV.getCount()
2180 << '.';
2181 }
2182 else
2183 os << "When GC is not enabled a call to '" << FName
2184 << "' has no effect on its argument.";
2185
2186 // Nothing more to say.
2187 break;
2188 }
2189
2190 // Determine if the typestate has changed.
2191 if (!(PrevV == CurrV))
2192 switch (CurrV.getKind()) {
2193 case RefVal::Owned:
2194 case RefVal::NotOwned:
2195
Ted Kremenek4d99d342009-05-08 20:01:42 +00002196 if (PrevV.getCount() == CurrV.getCount()) {
2197 // Did an autorelease message get sent?
2198 if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
2199 return 0;
2200
2201 assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount());
2202 os << "Object added to autorelease pool.";
2203 break;
2204 }
Ted Kremenek47a72422009-04-29 18:50:19 +00002205
2206 if (PrevV.getCount() > CurrV.getCount())
2207 os << "Reference count decremented.";
2208 else
2209 os << "Reference count incremented.";
2210
2211 if (unsigned Count = CurrV.getCount())
2212 os << " The object now has a +" << Count << " retain count.";
2213
2214 if (PrevV.getKind() == RefVal::Released) {
2215 assert(TF.isGCEnabled() && CurrV.getCount() > 0);
2216 os << " The object is not eligible for garbage collection until the "
2217 "retain count reaches 0 again.";
2218 }
2219
2220 break;
2221
2222 case RefVal::Released:
2223 os << "Object released.";
2224 break;
2225
2226 case RefVal::ReturnedOwned:
2227 os << "Object returned to caller as an owning reference (single retain "
2228 "count transferred to caller).";
2229 break;
2230
2231 case RefVal::ReturnedNotOwned:
2232 os << "Object returned to caller with a +0 (non-owning) retain count.";
2233 break;
2234
2235 default:
2236 return NULL;
2237 }
2238
2239 // Emit any remaining diagnostics for the argument effects (if any).
2240 for (llvm::SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
2241 E=AEffects.end(); I != E; ++I) {
2242
2243 // A bunch of things have alternate behavior under GC.
2244 if (TF.isGCEnabled())
2245 switch (*I) {
2246 default: break;
2247 case Autorelease:
2248 os << "In GC mode an 'autorelease' has no effect.";
2249 continue;
2250 case IncRefMsg:
2251 os << "In GC mode the 'retain' message has no effect.";
2252 continue;
2253 case DecRefMsg:
2254 os << "In GC mode the 'release' message has no effect.";
2255 continue;
2256 }
2257 }
2258 } while(0);
2259
2260 if (os.str().empty())
2261 return 0; // We have nothing to say!
2262
2263 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002264 PathDiagnosticLocation Pos(S, BRC.getSourceManager());
Ted Kremenek47a72422009-04-29 18:50:19 +00002265 PathDiagnosticPiece* P = new PathDiagnosticEventPiece(Pos, os.str());
2266
2267 // Add the range by scanning the children of the statement for any bindings
2268 // to Sym.
2269 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I)
2270 if (Expr* Exp = dyn_cast_or_null<Expr>(*I))
2271 if (CurrSt.GetSValAsScalarOrLoc(Exp).getAsLocSymbol() == Sym) {
2272 P->addRange(Exp->getSourceRange());
2273 break;
2274 }
2275
2276 return P;
2277}
2278
2279namespace {
2280 class VISIBILITY_HIDDEN FindUniqueBinding :
2281 public StoreManager::BindingsHandler {
2282 SymbolRef Sym;
2283 const MemRegion* Binding;
2284 bool First;
2285
2286 public:
2287 FindUniqueBinding(SymbolRef sym) : Sym(sym), Binding(0), First(true) {}
2288
2289 bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
2290 SVal val) {
2291
2292 SymbolRef SymV = val.getAsSymbol();
2293 if (!SymV || SymV != Sym)
2294 return true;
2295
2296 if (Binding) {
2297 First = false;
2298 return false;
2299 }
2300 else
2301 Binding = R;
2302
2303 return true;
2304 }
2305
2306 operator bool() { return First && Binding; }
2307 const MemRegion* getRegion() { return Binding; }
2308 };
2309}
2310
2311static std::pair<const ExplodedNode<GRState>*,const MemRegion*>
2312GetAllocationSite(GRStateManager& StateMgr, const ExplodedNode<GRState>* N,
2313 SymbolRef Sym) {
2314
2315 // Find both first node that referred to the tracked symbol and the
2316 // memory location that value was store to.
2317 const ExplodedNode<GRState>* Last = N;
2318 const MemRegion* FirstBinding = 0;
2319
2320 while (N) {
2321 const GRState* St = N->getState();
2322 RefBindings B = St->get<RefBindings>();
2323
2324 if (!B.lookup(Sym))
2325 break;
2326
2327 FindUniqueBinding FB(Sym);
2328 StateMgr.iterBindings(St, FB);
2329 if (FB) FirstBinding = FB.getRegion();
2330
2331 Last = N;
2332 N = N->pred_empty() ? NULL : *(N->pred_begin());
2333 }
2334
2335 return std::make_pair(Last, FirstBinding);
2336}
2337
2338PathDiagnosticPiece*
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002339CFRefReport::getEndPath(BugReporterContext& BRC,
2340 const ExplodedNode<GRState>* EndN) {
2341 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenek47a72422009-04-29 18:50:19 +00002342 // assigned to different variables, etc.
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002343 BRC.addNotableSymbol(Sym);
2344 return RangedBugReport::getEndPath(BRC, EndN);
Ted Kremenek47a72422009-04-29 18:50:19 +00002345}
2346
2347PathDiagnosticPiece*
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002348CFRefLeakReport::getEndPath(BugReporterContext& BRC,
2349 const ExplodedNode<GRState>* EndN){
Ted Kremenek47a72422009-04-29 18:50:19 +00002350
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002351 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenek47a72422009-04-29 18:50:19 +00002352 // assigned to different variables, etc.
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002353 BRC.addNotableSymbol(Sym);
Ted Kremenek47a72422009-04-29 18:50:19 +00002354
2355 // We are reporting a leak. Walk up the graph to get to the first node where
2356 // the symbol appeared, and also get the first VarDecl that tracked object
2357 // is stored to.
2358 const ExplodedNode<GRState>* AllocNode = 0;
2359 const MemRegion* FirstBinding = 0;
2360
2361 llvm::tie(AllocNode, FirstBinding) =
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002362 GetAllocationSite(BRC.getStateManager(), EndN, Sym);
Ted Kremenek47a72422009-04-29 18:50:19 +00002363
2364 // Get the allocate site.
2365 assert(AllocNode);
2366 Stmt* FirstStmt = cast<PostStmt>(AllocNode->getLocation()).getStmt();
2367
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002368 SourceManager& SMgr = BRC.getSourceManager();
Ted Kremenek47a72422009-04-29 18:50:19 +00002369 unsigned AllocLine =SMgr.getInstantiationLineNumber(FirstStmt->getLocStart());
2370
2371 // Compute an actual location for the leak. Sometimes a leak doesn't
2372 // occur at an actual statement (e.g., transition between blocks; end
2373 // of function) so we need to walk the graph and compute a real location.
2374 const ExplodedNode<GRState>* LeakN = EndN;
2375 PathDiagnosticLocation L;
2376
2377 while (LeakN) {
2378 ProgramPoint P = LeakN->getLocation();
2379
2380 if (const PostStmt *PS = dyn_cast<PostStmt>(&P)) {
2381 L = PathDiagnosticLocation(PS->getStmt()->getLocStart(), SMgr);
2382 break;
2383 }
2384 else if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
2385 if (const Stmt* Term = BE->getSrc()->getTerminator()) {
2386 L = PathDiagnosticLocation(Term->getLocStart(), SMgr);
2387 break;
2388 }
2389 }
2390
2391 LeakN = LeakN->succ_empty() ? 0 : *(LeakN->succ_begin());
2392 }
2393
2394 if (!L.isValid()) {
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002395 const Decl &D = BRC.getCodeDecl();
2396 L = PathDiagnosticLocation(D.getBodyRBrace(BRC.getASTContext()), SMgr);
Ted Kremenek47a72422009-04-29 18:50:19 +00002397 }
2398
2399 std::string sbuf;
2400 llvm::raw_string_ostream os(sbuf);
2401
2402 os << "Object allocated on line " << AllocLine;
2403
2404 if (FirstBinding)
2405 os << " and stored into '" << FirstBinding->getString() << '\'';
2406
2407 // Get the retain count.
2408 const RefVal* RV = EndN->getState()->get<RefBindings>(Sym);
2409
2410 if (RV->getKind() == RefVal::ErrorLeakReturned) {
2411 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
2412 // ojbects. Only "copy", "alloc", "retain" and "new" transfer ownership
2413 // to the caller for NS objects.
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002414 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(BRC.getCodeDecl());
Ted Kremenek47a72422009-04-29 18:50:19 +00002415 os << " is returned from a method whose name ('"
Ted Kremenek314b1952009-04-29 23:03:22 +00002416 << MD.getSelector().getAsString()
Ted Kremenek47a72422009-04-29 18:50:19 +00002417 << "') does not contain 'copy' or otherwise starts with"
2418 " 'new' or 'alloc'. This violates the naming convention rules given"
Ted Kremenek2a410c92009-04-29 22:25:52 +00002419 " in the Memory Management Guide for Cocoa (object leaked)";
Ted Kremenek47a72422009-04-29 18:50:19 +00002420 }
2421 else
2422 os << " is no longer referenced after this point and has a retain count of"
Ted Kremenek2a410c92009-04-29 22:25:52 +00002423 " +" << RV->getCount() << " (object leaked)";
Ted Kremenek47a72422009-04-29 18:50:19 +00002424
2425 return new PathDiagnosticEventPiece(L, os.str());
2426}
2427
2428
2429CFRefLeakReport::CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2430 ExplodedNode<GRState> *n,
2431 SymbolRef sym, GRExprEngine& Eng)
2432: CFRefReport(D, tf, n, sym)
2433{
2434
2435 // Most bug reports are cached at the location where they occured.
2436 // With leaks, we want to unique them by the location where they were
2437 // allocated, and only report a single path. To do this, we need to find
2438 // the allocation site of a piece of tracked memory, which we do via a
2439 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2440 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2441 // that all ancestor nodes that represent the allocation site have the
2442 // same SourceLocation.
2443 const ExplodedNode<GRState>* AllocNode = 0;
2444
2445 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding.
2446 GetAllocationSite(Eng.getStateManager(), getEndNode(), getSymbol());
2447
2448 // Get the SourceLocation for the allocation site.
2449 ProgramPoint P = AllocNode->getLocation();
2450 AllocSite = cast<PostStmt>(P).getStmt()->getLocStart();
2451
2452 // Fill in the description of the bug.
2453 Description.clear();
2454 llvm::raw_string_ostream os(Description);
2455 SourceManager& SMgr = Eng.getContext().getSourceManager();
2456 unsigned AllocLine = SMgr.getInstantiationLineNumber(AllocSite);
Ted Kremenek2e9d0302009-05-02 19:05:19 +00002457 os << "Potential leak ";
2458 if (tf.isGCEnabled()) {
2459 os << "(when using garbage collection) ";
2460 }
2461 os << "of an object allocated on line " << AllocLine;
Ted Kremenek47a72422009-04-29 18:50:19 +00002462
2463 // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2464 if (AllocBinding)
2465 os << " and stored into '" << AllocBinding->getString() << '\'';
2466}
2467
2468//===----------------------------------------------------------------------===//
2469// Main checker logic.
2470//===----------------------------------------------------------------------===//
2471
Ted Kremenek272aa852008-06-25 21:21:56 +00002472/// GetReturnType - Used to get the return type of a message expression or
2473/// function call with the intention of affixing that type to a tracked symbol.
2474/// While the the return type can be queried directly from RetEx, when
2475/// invoking class methods we augment to the return type to be that of
2476/// a pointer to the class (as opposed it just being id).
2477static QualType GetReturnType(Expr* RetE, ASTContext& Ctx) {
2478
2479 QualType RetTy = RetE->getType();
2480
2481 // FIXME: We aren't handling id<...>.
Chris Lattnerb724ab22008-07-26 22:36:27 +00002482 const PointerType* PT = RetTy->getAsPointerType();
Ted Kremenek272aa852008-06-25 21:21:56 +00002483 if (!PT)
2484 return RetTy;
2485
2486 // If RetEx is not a message expression just return its type.
2487 // If RetEx is a message expression, return its types if it is something
2488 /// more specific than id.
2489
2490 ObjCMessageExpr* ME = dyn_cast<ObjCMessageExpr>(RetE);
2491
Steve Naroff17c03822009-02-12 17:52:19 +00002492 if (!ME || !Ctx.isObjCIdStructType(PT->getPointeeType()))
Ted Kremenek272aa852008-06-25 21:21:56 +00002493 return RetTy;
2494
2495 ObjCInterfaceDecl* D = ME->getClassInfo().first;
2496
2497 // At this point we know the return type of the message expression is id.
2498 // If we have an ObjCInterceDecl, we know this is a call to a class method
2499 // whose type we can resolve. In such cases, promote the return type to
2500 // Class*.
2501 return !D ? RetTy : Ctx.getPointerType(Ctx.getObjCInterfaceType(D));
2502}
2503
2504
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002505void CFRefCount::EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002506 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002507 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002508 Expr* Ex,
2509 Expr* Receiver,
Ted Kremenek286e9852009-05-04 04:57:00 +00002510 const RetainSummary& Summ,
Zhongxing Xucac107a2009-04-20 05:24:46 +00002511 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002512 ExplodedNode<GRState>* Pred) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002513
Ted Kremeneka7338b42008-03-11 06:39:11 +00002514 // Get the state.
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002515 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenek0106e202008-10-24 20:32:50 +00002516 ASTContext& Ctx = Eng.getStateManager().getContext();
Ted Kremenek227c5372008-05-06 02:41:27 +00002517
2518 // Evaluate the effect of the arguments.
Ted Kremenek1feab292008-04-16 04:28:53 +00002519 RefVal::Kind hasErr = (RefVal::Kind) 0;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002520 unsigned idx = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002521 Expr* ErrorExpr = NULL;
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002522 SymbolRef ErrorSym = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002523
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002524 for (ExprIterator I = arg_beg; I != arg_end; ++I, ++idx) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002525 SVal V = state.GetSValAsScalarOrLoc(*I);
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002526 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002527
Ted Kremenek74556a12009-03-26 03:35:11 +00002528 if (Sym)
Ted Kremenekb6578942009-02-24 19:15:11 +00002529 if (RefBindings::data_type* T = state.get<RefBindings>(Sym)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002530 state = Update(state, Sym, *T, Summ.getArg(idx), hasErr);
Ted Kremenekb6578942009-02-24 19:15:11 +00002531 if (hasErr) {
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002532 ErrorExpr = *I;
Ted Kremenek6064a362008-07-07 16:21:19 +00002533 ErrorSym = Sym;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002534 break;
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002535 }
2536 continue;
Ted Kremenekb6578942009-02-24 19:15:11 +00002537 }
Ted Kremenekede40b72008-07-09 18:11:16 +00002538
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002539 if (isa<Loc>(V)) {
2540 if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(&V)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002541 if (Summ.getArg(idx) == DoNothingByRef)
Ted Kremenekede40b72008-07-09 18:11:16 +00002542 continue;
2543
2544 // Invalidate the value of the variable passed by reference.
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002545
2546 // FIXME: Either this logic should also be replicated in GRSimpleVals
2547 // or should be pulled into a separate "constraint engine."
Ted Kremenekede40b72008-07-09 18:11:16 +00002548
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002549 // FIXME: We can have collisions on the conjured symbol if the
2550 // expression *I also creates conjured symbols. We probably want
2551 // to identify conjured symbols by an expression pair: the enclosing
2552 // expression (the context) and the expression itself. This should
Ted Kremenekede40b72008-07-09 18:11:16 +00002553 // disambiguate conjured symbols.
Ted Kremenekb15eba42008-10-04 05:50:14 +00002554
Ted Kremenek38a4b4b2008-10-17 20:28:54 +00002555 const TypedRegion* R = dyn_cast<TypedRegion>(MR->getRegion());
Zhongxing Xub9d47a42009-04-29 02:30:09 +00002556
Ted Kremenek73ec7732009-05-06 18:19:24 +00002557 if (R) {
2558 // Are we dealing with an ElementRegion? If the element type is
2559 // a basic integer type (e.g., char, int) and the underying region
2560 // is also typed then strip off the ElementRegion.
2561 // FIXME: We really need to think about this for the general case
2562 // as sometimes we are reasoning about arrays and other times
2563 // about (char*), etc., is just a form of passing raw bytes.
2564 // e.g., void *p = alloca(); foo((char*)p);
2565 if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
2566 // Checking for 'integral type' is probably too promiscuous, but
2567 // we'll leave it in for now until we have a systematic way of
2568 // handling all of these cases. Eventually we need to come up
2569 // with an interface to StoreManager so that this logic can be
2570 // approriately delegated to the respective StoreManagers while
2571 // still allowing us to do checker-specific logic (e.g.,
2572 // invalidating reference counts), probably via callbacks.
2573 if (ER->getElementType()->isIntegralType())
2574 if (const TypedRegion *superReg =
2575 dyn_cast<TypedRegion>(ER->getSuperRegion()))
2576 R = superReg;
2577 // FIXME: What about layers of ElementRegions?
2578 }
2579
Ted Kremenek618c6cd2008-12-18 23:34:57 +00002580 // Is the invalidated variable something that we were tracking?
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002581 SymbolRef Sym = state.GetSValAsScalarOrLoc(R).getAsLocSymbol();
Ted Kremenek618c6cd2008-12-18 23:34:57 +00002582
Ted Kremenek53b24182009-03-04 22:56:43 +00002583 // Remove any existing reference-count binding.
Ted Kremenek74556a12009-03-26 03:35:11 +00002584 if (Sym) state = state.remove<RefBindings>(Sym);
Ted Kremenekb15eba42008-10-04 05:50:14 +00002585
Ted Kremenek53b24182009-03-04 22:56:43 +00002586 if (R->isBoundable(Ctx)) {
2587 // Set the value of the variable to be a conjured symbol.
2588 unsigned Count = Builder.getCurrentBlockCount();
2589 QualType T = R->getRValueType(Ctx);
2590
Zhongxing Xu079dc352009-04-09 06:03:54 +00002591 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())){
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002592 ValueManager &ValMgr = Eng.getValueManager();
2593 SVal V = ValMgr.getConjuredSymbolVal(*I, T, Count);
Zhongxing Xu079dc352009-04-09 06:03:54 +00002594 state = state.BindLoc(Loc::MakeVal(R), V);
Ted Kremenek53b24182009-03-04 22:56:43 +00002595 }
2596 else if (const RecordType *RT = T->getAsStructureType()) {
2597 // Handle structs in a not so awesome way. Here we just
2598 // eagerly bind new symbols to the fields. In reality we
2599 // should have the store manager handle this. The idea is just
2600 // to prototype some basic functionality here. All of this logic
2601 // should one day soon just go away.
2602 const RecordDecl *RD = RT->getDecl()->getDefinition(Ctx);
2603
2604 // No record definition. There is nothing we can do.
2605 if (!RD)
2606 continue;
2607
2608 MemRegionManager &MRMgr = state.getManager().getRegionManager();
2609
2610 // Iterate through the fields and construct new symbols.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002611 for (RecordDecl::field_iterator FI=RD->field_begin(Ctx),
2612 FE=RD->field_end(Ctx); FI!=FE; ++FI) {
Ted Kremenek53b24182009-03-04 22:56:43 +00002613
2614 // For now just handle scalar fields.
2615 FieldDecl *FD = *FI;
2616 QualType FT = FD->getType();
2617
2618 if (Loc::IsLocType(FT) ||
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002619 (FT->isIntegerType() && FT->isScalarType())) {
Ted Kremenek53b24182009-03-04 22:56:43 +00002620 const FieldRegion* FR = MRMgr.getFieldRegion(FD, R);
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002621 ValueManager &ValMgr = Eng.getValueManager();
2622 SVal V = ValMgr.getConjuredSymbolVal(*I, FT, Count);
Zhongxing Xuc458e322009-04-09 06:32:20 +00002623 state = state.BindLoc(Loc::MakeVal(FR), V);
Ted Kremenek53b24182009-03-04 22:56:43 +00002624 }
2625 }
2626 }
2627 else {
2628 // Just blast away other values.
2629 state = state.BindLoc(*MR, UnknownVal());
2630 }
Ted Kremenek8f90e712008-10-17 22:23:12 +00002631 }
Ted Kremenekb15eba42008-10-04 05:50:14 +00002632 }
2633 else
Ted Kremenek09102db2008-11-12 19:22:09 +00002634 state = state.BindLoc(*MR, UnknownVal());
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002635 }
2636 else {
2637 // Nuke all other arguments passed by reference.
Zhongxing Xu097fc982008-10-17 05:57:07 +00002638 state = state.Unbind(cast<Loc>(V));
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002639 }
Ted Kremeneke4924202008-04-11 20:51:02 +00002640 }
Zhongxing Xu097fc982008-10-17 05:57:07 +00002641 else if (isa<nonloc::LocAsInteger>(V))
2642 state = state.Unbind(cast<nonloc::LocAsInteger>(V).getLoc());
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002643 }
Ted Kremenek1feab292008-04-16 04:28:53 +00002644
Ted Kremenek272aa852008-06-25 21:21:56 +00002645 // Evaluate the effect on the message receiver.
Ted Kremenek227c5372008-05-06 02:41:27 +00002646 if (!ErrorExpr && Receiver) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002647 SymbolRef Sym = state.GetSValAsScalarOrLoc(Receiver).getAsLocSymbol();
Ted Kremenek74556a12009-03-26 03:35:11 +00002648 if (Sym) {
Ted Kremenekb6578942009-02-24 19:15:11 +00002649 if (const RefVal* T = state.get<RefBindings>(Sym)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002650 state = Update(state, Sym, *T, Summ.getReceiverEffect(), hasErr);
Ted Kremenekb6578942009-02-24 19:15:11 +00002651 if (hasErr) {
Ted Kremenek227c5372008-05-06 02:41:27 +00002652 ErrorExpr = Receiver;
Ted Kremenek6064a362008-07-07 16:21:19 +00002653 ErrorSym = Sym;
Ted Kremenek227c5372008-05-06 02:41:27 +00002654 }
Ted Kremenekb6578942009-02-24 19:15:11 +00002655 }
Ted Kremenek227c5372008-05-06 02:41:27 +00002656 }
2657 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002658
Ted Kremenek272aa852008-06-25 21:21:56 +00002659 // Process any errors.
Ted Kremenek1feab292008-04-16 04:28:53 +00002660 if (hasErr) {
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002661 ProcessNonLeakError(Dst, Builder, Ex, ErrorExpr, Pred, state,
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002662 hasErr, ErrorSym);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002663 return;
Ted Kremenek0d721572008-03-11 17:48:22 +00002664 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002665
Ted Kremenekf2717b02008-07-18 17:24:20 +00002666 // Consult the summary for the return value.
Ted Kremenek286e9852009-05-04 04:57:00 +00002667 RetEffect RE = Summ.getRetEffect();
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002668
2669 switch (RE.getKind()) {
2670 default:
2671 assert (false && "Unhandled RetEffect."); break;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002672
Ted Kremenek8f90e712008-10-17 22:23:12 +00002673 case RetEffect::NoRet: {
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002674
Ted Kremenek455dd862008-04-11 20:23:24 +00002675 // Make up a symbol for the return value (not reference counted).
Ted Kremeneke4924202008-04-11 20:51:02 +00002676 // FIXME: This is basically copy-and-paste from GRSimpleVals. We
2677 // should compose behavior, not copy it.
Ted Kremenek455dd862008-04-11 20:23:24 +00002678
Ted Kremenek8f90e712008-10-17 22:23:12 +00002679 // FIXME: We eventually should handle structs and other compound types
2680 // that are returned by value.
2681
2682 QualType T = Ex->getType();
2683
Ted Kremenek79413a52008-11-13 06:10:40 +00002684 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())) {
Ted Kremenek455dd862008-04-11 20:23:24 +00002685 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002686 ValueManager &ValMgr = Eng.getValueManager();
2687 SVal X = ValMgr.getConjuredSymbolVal(Ex, T, Count);
Ted Kremenek09102db2008-11-12 19:22:09 +00002688 state = state.BindExpr(Ex, X, false);
Ted Kremenek455dd862008-04-11 20:23:24 +00002689 }
2690
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002691 break;
Ted Kremenek8f90e712008-10-17 22:23:12 +00002692 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002693
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002694 case RetEffect::Alias: {
Ted Kremenek272aa852008-06-25 21:21:56 +00002695 unsigned idx = RE.getIndex();
Ted Kremenek2719e982008-06-17 02:43:46 +00002696 assert (arg_end >= arg_beg);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002697 assert (idx < (unsigned) (arg_end - arg_beg));
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002698 SVal V = state.GetSValAsScalarOrLoc(*(arg_beg+idx));
Ted Kremenek09102db2008-11-12 19:22:09 +00002699 state = state.BindExpr(Ex, V, false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002700 break;
2701 }
2702
Ted Kremenek227c5372008-05-06 02:41:27 +00002703 case RetEffect::ReceiverAlias: {
2704 assert (Receiver);
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002705 SVal V = state.GetSValAsScalarOrLoc(Receiver);
Ted Kremenek09102db2008-11-12 19:22:09 +00002706 state = state.BindExpr(Ex, V, false);
Ted Kremenek227c5372008-05-06 02:41:27 +00002707 break;
2708 }
2709
Ted Kremenek6a1cc252008-06-23 18:02:52 +00002710 case RetEffect::OwnedAllocatedSymbol:
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002711 case RetEffect::OwnedSymbol: {
2712 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke9e726e2009-04-09 16:13:17 +00002713 ValueManager &ValMgr = Eng.getValueManager();
2714 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
2715 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
2716 state = state.set<RefBindings>(Sym, RefVal::makeOwned(RE.getObjKind(),
2717 RetT));
2718 state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenek45c52a12009-03-09 22:46:49 +00002719
2720 // FIXME: Add a flag to the checker where allocations are assumed to
2721 // *not fail.
2722#if 0
Ted Kremeneke62fd052009-01-28 22:27:59 +00002723 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) {
2724 bool isFeasible;
2725 state = state.Assume(loc::SymbolVal(Sym), true, isFeasible);
2726 assert(isFeasible && "Cannot assume fresh symbol is non-null.");
2727 }
Ted Kremenek45c52a12009-03-09 22:46:49 +00002728#endif
Ted Kremenek6a1cc252008-06-23 18:02:52 +00002729
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002730 break;
2731 }
Ted Kremenek382fb4e2009-04-27 19:14:45 +00002732
2733 case RetEffect::GCNotOwnedSymbol:
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002734 case RetEffect::NotOwnedSymbol: {
2735 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke9e726e2009-04-09 16:13:17 +00002736 ValueManager &ValMgr = Eng.getValueManager();
2737 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
2738 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
2739 state = state.set<RefBindings>(Sym, RefVal::makeNotOwned(RE.getObjKind(),
2740 RetT));
2741 state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002742 break;
2743 }
2744 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002745
Ted Kremenek0dd65012009-02-18 02:00:25 +00002746 // Generate a sink node if we are at the end of a path.
2747 GRExprEngine::NodeTy *NewNode =
Ted Kremenek286e9852009-05-04 04:57:00 +00002748 Summ.isEndPath() ? Builder.MakeSinkNode(Dst, Ex, Pred, state)
2749 : Builder.MakeNode(Dst, Ex, Pred, state);
Ted Kremenek0dd65012009-02-18 02:00:25 +00002750
2751 // Annotate the edge with summary we used.
Ted Kremenek286e9852009-05-04 04:57:00 +00002752 if (NewNode) SummaryLog[NewNode] = &Summ;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002753}
2754
2755
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002756void CFRefCount::EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002757 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002758 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu097fc982008-10-17 05:57:07 +00002759 CallExpr* CE, SVal L,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002760 ExplodedNode<GRState>* Pred) {
Zhongxing Xucac107a2009-04-20 05:24:46 +00002761 const FunctionDecl* FD = L.getAsFunctionDecl();
Ted Kremenek286e9852009-05-04 04:57:00 +00002762 RetainSummary* Summ = !FD ? Summaries.getDefaultSummary()
Zhongxing Xucac107a2009-04-20 05:24:46 +00002763 : Summaries.getSummary(const_cast<FunctionDecl*>(FD));
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002764
Ted Kremenek286e9852009-05-04 04:57:00 +00002765 assert(Summ);
2766 EvalSummary(Dst, Eng, Builder, CE, 0, *Summ,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002767 CE->arg_begin(), CE->arg_end(), Pred);
Ted Kremenek827f93b2008-03-06 00:08:09 +00002768}
Ted Kremeneka7338b42008-03-11 06:39:11 +00002769
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002770void CFRefCount::EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002771 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002772 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002773 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002774 ExplodedNode<GRState>* Pred) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002775 RetainSummary* Summ = 0;
Ted Kremenek33661802008-05-01 21:31:50 +00002776
Ted Kremenek272aa852008-06-25 21:21:56 +00002777 if (Expr* Receiver = ME->getReceiver()) {
2778 // We need the type-information of the tracked receiver object
2779 // Retrieve it from the state.
2780 ObjCInterfaceDecl* ID = 0;
2781
2782 // FIXME: Wouldn't it be great if this code could be reduced? It's just
2783 // a chain of lookups.
Ted Kremeneka821b792009-04-29 05:04:30 +00002784 // FIXME: Is this really working as expected? There are cases where
2785 // we just use the 'ID' from the message expression.
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002786 const GRState* St = Builder.GetState(Pred);
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002787 SVal V = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
Ted Kremenek272aa852008-06-25 21:21:56 +00002788
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002789 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenek74556a12009-03-26 03:35:11 +00002790 if (Sym) {
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002791 if (const RefVal* T = St->get<RefBindings>(Sym)) {
Ted Kremenek6064a362008-07-07 16:21:19 +00002792 QualType Ty = T->getType();
Ted Kremenek272aa852008-06-25 21:21:56 +00002793
2794 if (const PointerType* PT = Ty->getAsPointerType()) {
2795 QualType PointeeTy = PT->getPointeeType();
2796
2797 if (ObjCInterfaceType* IT = dyn_cast<ObjCInterfaceType>(PointeeTy))
2798 ID = IT->getDecl();
2799 }
2800 }
2801 }
2802
Ted Kremenek04e00302009-04-29 17:09:14 +00002803 // FIXME: The receiver could be a reference to a class, meaning that
2804 // we should use the class method.
2805 Summ = Summaries.getInstanceMethodSummary(ME, ID);
Ted Kremenek0106e202008-10-24 20:32:50 +00002806
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002807 // Special-case: are we sending a mesage to "self"?
2808 // This is a hack. When we have full-IP this should be removed.
Ted Kremenek2f226732009-05-04 05:31:22 +00002809 if (isa<ObjCMethodDecl>(&Eng.getGraph().getCodeDecl())) {
2810 if (Expr* Receiver = ME->getReceiver()) {
2811 SVal X = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
2812 if (loc::MemRegionVal* L = dyn_cast<loc::MemRegionVal>(&X))
2813 if (L->getRegion() == Eng.getStateManager().getSelfRegion(St)) {
2814 // Update the summary to make the default argument effect
2815 // 'StopTracking'.
2816 Summ = Summaries.copySummary(Summ);
2817 Summ->setDefaultArgEffect(StopTracking);
2818 }
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002819 }
2820 }
Ted Kremenek272aa852008-06-25 21:21:56 +00002821 }
Ted Kremenek1feab292008-04-16 04:28:53 +00002822 else
Ted Kremenekb17fa952009-04-23 21:25:57 +00002823 Summ = Summaries.getClassMethodSummary(ME);
Ted Kremenek1feab292008-04-16 04:28:53 +00002824
Ted Kremenek286e9852009-05-04 04:57:00 +00002825 if (!Summ)
2826 Summ = Summaries.getDefaultSummary();
Ted Kremenekccbe79a2009-04-24 17:50:11 +00002827
Ted Kremenek286e9852009-05-04 04:57:00 +00002828 EvalSummary(Dst, Eng, Builder, ME, ME->getReceiver(), *Summ,
Ted Kremenek926abf22008-05-06 04:20:12 +00002829 ME->arg_begin(), ME->arg_end(), Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002830}
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002831
2832namespace {
2833class VISIBILITY_HIDDEN StopTrackingCallback : public SymbolVisitor {
2834 GRStateRef state;
2835public:
2836 StopTrackingCallback(GRStateRef st) : state(st) {}
2837 GRStateRef getState() { return state; }
2838
2839 bool VisitSymbol(SymbolRef sym) {
2840 state = state.remove<RefBindings>(sym);
2841 return true;
2842 }
Ted Kremenek926abf22008-05-06 04:20:12 +00002843
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002844 const GRState* getState() const { return state.getState(); }
2845};
2846} // end anonymous namespace
2847
2848
Ted Kremeneka42be302009-02-14 01:43:44 +00002849void CFRefCount::EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val) {
Ted Kremeneka42be302009-02-14 01:43:44 +00002850 // Are we storing to something that causes the value to "escape"?
Ted Kremenek7aef4842008-04-16 20:40:59 +00002851 bool escapes = false;
2852
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002853 // A value escapes in three possible cases (this may change):
2854 //
2855 // (1) we are binding to something that is not a memory region.
2856 // (2) we are binding to a memregion that does not have stack storage
2857 // (3) we are binding to a memregion with stack storage that the store
Ted Kremeneka42be302009-02-14 01:43:44 +00002858 // does not understand.
Ted Kremeneka42be302009-02-14 01:43:44 +00002859 GRStateRef state = B.getState();
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002860
Ted Kremeneka42be302009-02-14 01:43:44 +00002861 if (!isa<loc::MemRegionVal>(location))
Ted Kremenek7aef4842008-04-16 20:40:59 +00002862 escapes = true;
Ted Kremenekb15eba42008-10-04 05:50:14 +00002863 else {
Ted Kremeneka42be302009-02-14 01:43:44 +00002864 const MemRegion* R = cast<loc::MemRegionVal>(location).getRegion();
2865 escapes = !B.getStateManager().hasStackStorage(R);
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002866
2867 if (!escapes) {
2868 // To test (3), generate a new state with the binding removed. If it is
2869 // the same state, then it escapes (since the store cannot represent
2870 // the binding).
Ted Kremeneka42be302009-02-14 01:43:44 +00002871 escapes = (state == (state.BindLoc(cast<Loc>(location), UnknownVal())));
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002872 }
Ted Kremenekb15eba42008-10-04 05:50:14 +00002873 }
Ted Kremeneka42be302009-02-14 01:43:44 +00002874
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002875 // If our store can represent the binding and we aren't storing to something
2876 // that doesn't have local storage then just return and have the simulation
2877 // state continue as is.
2878 if (!escapes)
2879 return;
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002880
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002881 // Otherwise, find all symbols referenced by 'val' that we are tracking
2882 // and stop tracking them.
2883 B.MakeNode(state.scanReachableSymbols<StopTrackingCallback>(val).getState());
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002884}
2885
Ted Kremenek541db372008-04-24 23:57:27 +00002886
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002887 // Return statements.
2888
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002889void CFRefCount::EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002890 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002891 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002892 ReturnStmt* S,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002893 ExplodedNode<GRState>* Pred) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002894
2895 Expr* RetE = S->getRetValue();
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002896 if (!RetE)
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002897 return;
2898
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002899 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002900 SymbolRef Sym = state.GetSValAsScalarOrLoc(RetE).getAsLocSymbol();
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002901
Ted Kremenek74556a12009-03-26 03:35:11 +00002902 if (!Sym)
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002903 return;
2904
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002905 // Get the reference count binding (if any).
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002906 const RefVal* T = state.get<RefBindings>(Sym);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002907
2908 if (!T)
2909 return;
2910
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002911 // Change the reference count.
Ted Kremenek6064a362008-07-07 16:21:19 +00002912 RefVal X = *T;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002913
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002914 switch (X.getKind()) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002915 case RefVal::Owned: {
2916 unsigned cnt = X.getCount();
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00002917 assert (cnt > 0);
2918 X = RefVal::makeReturnedOwned(cnt - 1);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002919 break;
2920 }
2921
2922 case RefVal::NotOwned: {
2923 unsigned cnt = X.getCount();
2924 X = cnt ? RefVal::makeReturnedOwned(cnt - 1)
2925 : RefVal::makeReturnedNotOwned();
2926 break;
2927 }
2928
2929 default:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002930 return;
2931 }
2932
2933 // Update the binding.
Ted Kremenek91781202008-08-17 03:20:02 +00002934 state = state.set<RefBindings>(Sym, X);
Ted Kremenek47a72422009-04-29 18:50:19 +00002935 Pred = Builder.MakeNode(Dst, S, Pred, state);
2936
Ted Kremeneka208d0c2009-04-30 05:51:50 +00002937 // Did we cache out?
2938 if (!Pred)
2939 return;
Ted Kremenek41a4bc62009-05-08 23:09:42 +00002940
Ted Kremenek47a72422009-04-29 18:50:19 +00002941 // Any leaks or other errors?
2942 if (X.isReturnedOwned() && X.getCount() == 0) {
2943 const Decl *CD = &Eng.getStateManager().getCodeDecl();
2944
Ted Kremenek314b1952009-04-29 23:03:22 +00002945 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002946 const RetainSummary &Summ = *Summaries.getMethodSummary(MD);
2947 if (!Summ.getRetEffect().isOwned()) {
Ted Kremenek47a72422009-04-29 18:50:19 +00002948 static int ReturnOwnLeakTag = 0;
2949 state = state.set<RefBindings>(Sym, X ^ RefVal::ErrorLeakReturned);
Ted Kremenek47a72422009-04-29 18:50:19 +00002950 // Generate an error node.
Ted Kremeneka208d0c2009-04-30 05:51:50 +00002951 if (ExplodedNode<GRState> *N =
2952 Builder.generateNode(PostStmt(S, &ReturnOwnLeakTag), state, Pred)) {
2953 CFRefLeakReport *report =
2954 new CFRefLeakReport(*static_cast<CFRefBug*>(leakAtReturn), *this,
2955 N, Sym, Eng);
2956 BR->EmitReport(report);
2957 }
Ted Kremenek47a72422009-04-29 18:50:19 +00002958 }
2959 }
2960 }
Ted Kremenek41a4bc62009-05-08 23:09:42 +00002961
2962
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002963}
2964
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002965// Assumptions.
2966
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002967const GRState* CFRefCount::EvalAssume(GRStateManager& VMgr,
2968 const GRState* St,
Zhongxing Xu097fc982008-10-17 05:57:07 +00002969 SVal Cond, bool Assumption,
Ted Kremenekf22f8682008-07-10 22:03:41 +00002970 bool& isFeasible) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002971
2972 // FIXME: We may add to the interface of EvalAssume the list of symbols
2973 // whose assumptions have changed. For now we just iterate through the
2974 // bindings and check if any of the tracked symbols are NULL. This isn't
2975 // too bad since the number of symbols we will track in practice are
2976 // probably small and EvalAssume is only called at branches and a few
2977 // other places.
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002978 RefBindings B = St->get<RefBindings>();
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002979
2980 if (B.isEmpty())
2981 return St;
2982
2983 bool changed = false;
Ted Kremenek91781202008-08-17 03:20:02 +00002984
2985 GRStateRef state(St, VMgr);
2986 RefBindings::Factory& RefBFactory = state.get_context<RefBindings>();
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002987
2988 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002989 // Check if the symbol is null (or equal to any constant).
2990 // If this is the case, stop tracking the symbol.
Zhongxing Xuc6b27d02008-08-29 14:52:36 +00002991 if (VMgr.getSymVal(St, I.getKey())) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002992 changed = true;
2993 B = RefBFactory.Remove(B, I.getKey());
2994 }
2995 }
2996
Ted Kremenek91781202008-08-17 03:20:02 +00002997 if (changed)
2998 state = state.set<RefBindings>(B);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002999
Ted Kremenek4ae925c2008-08-14 21:16:54 +00003000 return state;
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003001}
Ted Kremeneka7338b42008-03-11 06:39:11 +00003002
Ted Kremenekb6578942009-02-24 19:15:11 +00003003GRStateRef CFRefCount::Update(GRStateRef state, SymbolRef sym,
3004 RefVal V, ArgEffect E,
3005 RefVal::Kind& hasErr) {
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003006
3007 // In GC mode [... release] and [... retain] do nothing.
3008 switch (E) {
3009 default: break;
3010 case IncRefMsg: E = isGCEnabled() ? DoNothing : IncRef; break;
3011 case DecRefMsg: E = isGCEnabled() ? DoNothing : DecRef; break;
Ted Kremenek2126bef2009-02-18 21:57:45 +00003012 case MakeCollectable: E = isGCEnabled() ? DecRef : DoNothing; break;
Ted Kremenekaac82832009-02-23 17:45:03 +00003013 case NewAutoreleasePool: E = isGCEnabled() ? DoNothing :
3014 NewAutoreleasePool; break;
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003015 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00003016
Ted Kremenek6537a642009-03-17 19:42:23 +00003017 // Handle all use-after-releases.
3018 if (!isGCEnabled() && V.getKind() == RefVal::Released) {
3019 V = V ^ RefVal::ErrorUseAfterRelease;
3020 hasErr = V.getKind();
3021 return state.set<RefBindings>(sym, V);
3022 }
3023
Ted Kremenek0d721572008-03-11 17:48:22 +00003024 switch (E) {
3025 default:
3026 assert (false && "Unhandled CFRef transition.");
Ted Kremenek6537a642009-03-17 19:42:23 +00003027
3028 case Dealloc:
3029 // Any use of -dealloc in GC is *bad*.
3030 if (isGCEnabled()) {
3031 V = V ^ RefVal::ErrorDeallocGC;
3032 hasErr = V.getKind();
3033 break;
3034 }
3035
3036 switch (V.getKind()) {
3037 default:
3038 assert(false && "Invalid case.");
3039 case RefVal::Owned:
3040 // The object immediately transitions to the released state.
3041 V = V ^ RefVal::Released;
3042 V.clearCounts();
3043 return state.set<RefBindings>(sym, V);
3044 case RefVal::NotOwned:
3045 V = V ^ RefVal::ErrorDeallocNotOwned;
3046 hasErr = V.getKind();
3047 break;
3048 }
3049 break;
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003050
Ted Kremenekb7826ab2009-02-25 23:11:49 +00003051 case NewAutoreleasePool:
3052 assert(!isGCEnabled());
3053 return state.add<AutoreleaseStack>(sym);
3054
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003055 case MayEscape:
3056 if (V.getKind() == RefVal::Owned) {
Ted Kremenek272aa852008-06-25 21:21:56 +00003057 V = V ^ RefVal::NotOwned;
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003058 break;
3059 }
Ted Kremenek6537a642009-03-17 19:42:23 +00003060
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003061 // Fall-through.
Ted Kremenek1b4b6562009-02-25 02:54:57 +00003062
Ted Kremenekede40b72008-07-09 18:11:16 +00003063 case DoNothingByRef:
Ted Kremenek0d721572008-03-11 17:48:22 +00003064 case DoNothing:
Ted Kremenekb6578942009-02-24 19:15:11 +00003065 return state;
Ted Kremeneke5a4bb02008-06-30 16:57:41 +00003066
Ted Kremenek9b112d22009-01-28 21:44:40 +00003067 case Autorelease:
Ted Kremenek6537a642009-03-17 19:42:23 +00003068 if (isGCEnabled())
3069 return state;
Ted Kremenek681fb352009-03-20 17:34:15 +00003070
3071 // Update the autorelease counts.
3072 state = SendAutorelease(state, ARCountFactory, sym);
Ted Kremenek4d99d342009-05-08 20:01:42 +00003073 V = V.autorelease();
Ted Kremenek6537a642009-03-17 19:42:23 +00003074
Ted Kremenek227c5372008-05-06 02:41:27 +00003075 case StopTracking:
Ted Kremenekb6578942009-02-24 19:15:11 +00003076 return state.remove<RefBindings>(sym);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003077
Ted Kremenek0d721572008-03-11 17:48:22 +00003078 case IncRef:
3079 switch (V.getKind()) {
3080 default:
3081 assert(false);
3082
3083 case RefVal::Owned:
Ted Kremenek0d721572008-03-11 17:48:22 +00003084 case RefVal::NotOwned:
Ted Kremenek272aa852008-06-25 21:21:56 +00003085 V = V + 1;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003086 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003087 case RefVal::Released:
Ted Kremenek6537a642009-03-17 19:42:23 +00003088 // Non-GC cases are handled above.
3089 assert(isGCEnabled());
3090 V = (V ^ RefVal::Owned) + 1;
Ted Kremenek0d721572008-03-11 17:48:22 +00003091 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003092 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00003093 break;
3094
Ted Kremenek272aa852008-06-25 21:21:56 +00003095 case SelfOwn:
3096 V = V ^ RefVal::NotOwned;
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003097 // Fall-through.
Ted Kremenek0d721572008-03-11 17:48:22 +00003098 case DecRef:
3099 switch (V.getKind()) {
3100 default:
Ted Kremenek6537a642009-03-17 19:42:23 +00003101 // case 'RefVal::Released' handled above.
Ted Kremenek0d721572008-03-11 17:48:22 +00003102 assert (false);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003103
Ted Kremenek272aa852008-06-25 21:21:56 +00003104 case RefVal::Owned:
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00003105 assert(V.getCount() > 0);
3106 if (V.getCount() == 1) V = V ^ RefVal::Released;
3107 V = V - 1;
Ted Kremenek0d721572008-03-11 17:48:22 +00003108 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003109
Ted Kremenek272aa852008-06-25 21:21:56 +00003110 case RefVal::NotOwned:
3111 if (V.getCount() > 0)
3112 V = V - 1;
Ted Kremenekc4f81022008-04-10 23:09:18 +00003113 else {
Ted Kremenek272aa852008-06-25 21:21:56 +00003114 V = V ^ RefVal::ErrorReleaseNotOwned;
Ted Kremenek1feab292008-04-16 04:28:53 +00003115 hasErr = V.getKind();
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003116 }
Ted Kremenek0d721572008-03-11 17:48:22 +00003117 break;
Ted Kremenek6537a642009-03-17 19:42:23 +00003118
Ted Kremenek0d721572008-03-11 17:48:22 +00003119 case RefVal::Released:
Ted Kremenek6537a642009-03-17 19:42:23 +00003120 // Non-GC cases are handled above.
3121 assert(isGCEnabled());
Ted Kremenek272aa852008-06-25 21:21:56 +00003122 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek1feab292008-04-16 04:28:53 +00003123 hasErr = V.getKind();
Ted Kremenek6537a642009-03-17 19:42:23 +00003124 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003125 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00003126 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003127 }
Ted Kremenekb6578942009-02-24 19:15:11 +00003128 return state.set<RefBindings>(sym, V);
Ted Kremeneka7338b42008-03-11 06:39:11 +00003129}
3130
Ted Kremenek10fe66d2008-04-09 01:10:13 +00003131//===----------------------------------------------------------------------===//
Ted Kremenek708af042009-02-05 06:50:21 +00003132// Handle dead symbols and end-of-path.
3133//===----------------------------------------------------------------------===//
3134
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003135
3136GRStateRef
3137CFRefCount::HandleSymbolDeath(GRStateRef state, SymbolRef sid, RefVal V,
3138 llvm::SmallVectorImpl<SymbolRef> &Leaked) {
3139
3140 bool hasLeak = V.isOwned() ||
3141 ((V.isNotOwned() || V.isReturnedOwned()) && V.getCount() > 0);
3142
3143 if (!hasLeak)
3144 return state.remove<RefBindings>(sid);
3145
3146 Leaked.push_back(sid);
3147 return state.set<RefBindings>(sid, V ^ RefVal::ErrorLeak);
3148}
3149
3150ExplodedNode<GRState>*
3151CFRefCount::ProcessLeaks(GRStateRef state,
3152 llvm::SmallVectorImpl<SymbolRef> &Leaked,
3153 GenericNodeBuilder &Builder,
3154 GRExprEngine& Eng,
3155 ExplodedNode<GRState> *Pred) {
3156
3157 if (Leaked.empty())
3158 return Pred;
3159
3160 ExplodedNode<GRState> *N = Builder.MakeNode(state, Pred);
3161
3162 if (N) {
3163 for (llvm::SmallVectorImpl<SymbolRef>::iterator
3164 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3165
3166 CFRefBug *BT = static_cast<CFRefBug*>(Pred ? leakWithinFunction
3167 : leakAtReturn);
3168 assert(BT && "BugType not initialized.");
3169 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N, *I, Eng);
3170 BR->EmitReport(report);
3171 }
3172 }
3173
3174 return N;
3175}
3176
Ted Kremenek708af042009-02-05 06:50:21 +00003177void CFRefCount::EvalEndPath(GRExprEngine& Eng,
3178 GREndPathNodeBuilder<GRState>& Builder) {
3179
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003180 GRStateRef state(Builder.getState(), Eng.getStateManager());
3181 RefBindings B = state.get<RefBindings>();
3182 llvm::SmallVector<SymbolRef, 10> Leaked;
Ted Kremenek708af042009-02-05 06:50:21 +00003183
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003184 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I)
3185 state = HandleSymbolDeath(state, (*I).first, (*I).second, Leaked);
3186
3187 GenericNodeBuilder Bd(Builder);
3188 ProcessLeaks(state, Leaked, Bd, Eng, NULL);
Ted Kremenek708af042009-02-05 06:50:21 +00003189}
3190
3191void CFRefCount::EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
3192 GRExprEngine& Eng,
3193 GRStmtNodeBuilder<GRState>& Builder,
3194 ExplodedNode<GRState>* Pred,
3195 Stmt* S,
3196 const GRState* St,
3197 SymbolReaper& SymReaper) {
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003198
3199 GRStateRef state(St, Eng.getStateManager());
Ted Kremenek708af042009-02-05 06:50:21 +00003200 RefBindings B = St->get<RefBindings>();
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003201 llvm::SmallVector<SymbolRef, 10> Leaked;
Ted Kremenek708af042009-02-05 06:50:21 +00003202
3203 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003204 E = SymReaper.dead_end(); I != E; ++I) {
3205 if (const RefVal* T = B.lookup(*I))
3206 state = HandleSymbolDeath(state, *I, *T, Leaked);
3207 }
Ted Kremenek708af042009-02-05 06:50:21 +00003208
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003209 static unsigned LeakPPTag = 0;
3210 GenericNodeBuilder Bd(Builder, S, &LeakPPTag);
3211 Pred = ProcessLeaks(state, Leaked, Bd, Eng, Pred);
Ted Kremenek708af042009-02-05 06:50:21 +00003212
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003213 // Did we cache out?
3214 if (!Pred)
3215 return;
Ted Kremenek876d8df2009-02-19 23:47:02 +00003216
3217 // Now generate a new node that nukes the old bindings.
Ted Kremenek876d8df2009-02-19 23:47:02 +00003218 RefBindings::Factory& F = state.get_context<RefBindings>();
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003219
Ted Kremenek876d8df2009-02-19 23:47:02 +00003220 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
Ted Kremenek41a4bc62009-05-08 23:09:42 +00003221 E = SymReaper.dead_end(); I!=E; ++I) B = F.Remove(B, *I);
3222
Ted Kremenek876d8df2009-02-19 23:47:02 +00003223 state = state.set<RefBindings>(B);
3224 Builder.MakeNode(Dst, S, Pred, state);
Ted Kremenek708af042009-02-05 06:50:21 +00003225}
3226
3227void CFRefCount::ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
3228 GRStmtNodeBuilder<GRState>& Builder,
3229 Expr* NodeExpr, Expr* ErrorExpr,
3230 ExplodedNode<GRState>* Pred,
3231 const GRState* St,
3232 RefVal::Kind hasErr, SymbolRef Sym) {
3233 Builder.BuildSinks = true;
3234 GRExprEngine::NodeTy* N = Builder.MakeNode(Dst, NodeExpr, Pred, St);
3235
3236 if (!N) return;
3237
3238 CFRefBug *BT = 0;
3239
Ted Kremenek6537a642009-03-17 19:42:23 +00003240 switch (hasErr) {
3241 default:
3242 assert(false && "Unhandled error.");
3243 return;
3244 case RefVal::ErrorUseAfterRelease:
3245 BT = static_cast<CFRefBug*>(useAfterRelease);
3246 break;
3247 case RefVal::ErrorReleaseNotOwned:
3248 BT = static_cast<CFRefBug*>(releaseNotOwned);
3249 break;
3250 case RefVal::ErrorDeallocGC:
3251 BT = static_cast<CFRefBug*>(deallocGC);
3252 break;
3253 case RefVal::ErrorDeallocNotOwned:
3254 BT = static_cast<CFRefBug*>(deallocNotOwned);
3255 break;
Ted Kremenek708af042009-02-05 06:50:21 +00003256 }
3257
Ted Kremenekc26c4692009-02-18 03:48:14 +00003258 CFRefReport *report = new CFRefReport(*BT, *this, N, Sym);
Ted Kremenek708af042009-02-05 06:50:21 +00003259 report->addRange(ErrorExpr->getSourceRange());
3260 BR->EmitReport(report);
3261}
3262
3263//===----------------------------------------------------------------------===//
Ted Kremenekb1983ba2008-04-10 22:16:52 +00003264// Transfer function creation for external clients.
Ted Kremeneka7338b42008-03-11 06:39:11 +00003265//===----------------------------------------------------------------------===//
3266
Ted Kremenekfe30beb2008-04-30 23:47:44 +00003267GRTransferFuncs* clang::MakeCFRefCountTF(ASTContext& Ctx, bool GCEnabled,
3268 const LangOptions& lopts) {
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00003269 return new CFRefCount(Ctx, GCEnabled, lopts);
Ted Kremeneka4c74292008-04-10 22:58:08 +00003270}