blob: 58f581aff83ce7a581df25efb980ec5e4f8c2e36 [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"
Daniel Dunbar64789f82008-08-11 05:35:13 +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 Kremenek7d421f32008-04-09 23:49:11 +0000162//===----------------------------------------------------------------------===//
Ted Kremenek272aa852008-06-25 21:21:56 +0000163// Selector creation functions.
Ted Kremenekd9ccf682008-04-17 18:12:53 +0000164//===----------------------------------------------------------------------===//
165
Ted Kremenek1bd6ddb2008-05-01 18:31:44 +0000166static inline Selector GetNullarySelector(const char* name, ASTContext& Ctx) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +0000167 IdentifierInfo* II = &Ctx.Idents.get(name);
168 return Ctx.Selectors.getSelector(0, &II);
169}
170
Ted Kremenek0e344d42008-05-06 00:30:21 +0000171static inline Selector GetUnarySelector(const char* name, ASTContext& Ctx) {
172 IdentifierInfo* II = &Ctx.Idents.get(name);
173 return Ctx.Selectors.getSelector(1, &II);
174}
175
Ted Kremenek272aa852008-06-25 21:21:56 +0000176//===----------------------------------------------------------------------===//
177// Type querying functions.
178//===----------------------------------------------------------------------===//
179
Ted Kremenek17144e82009-01-12 21:45:02 +0000180static bool hasPrefix(const char* s, const char* prefix) {
181 if (!prefix)
182 return true;
Ted Kremenek62820d82008-05-07 20:06:41 +0000183
Ted Kremenek17144e82009-01-12 21:45:02 +0000184 char c = *s;
185 char cP = *prefix;
Ted Kremenek62820d82008-05-07 20:06:41 +0000186
Ted Kremenek17144e82009-01-12 21:45:02 +0000187 while (c != '\0' && cP != '\0') {
188 if (c != cP) break;
189 c = *(++s);
190 cP = *(++prefix);
191 }
Ted Kremenek62820d82008-05-07 20:06:41 +0000192
Ted Kremenek17144e82009-01-12 21:45:02 +0000193 return cP == '\0';
Ted Kremenek62820d82008-05-07 20:06:41 +0000194}
195
Ted Kremenek17144e82009-01-12 21:45:02 +0000196static bool hasSuffix(const char* s, const char* suffix) {
197 const char* loc = strstr(s, suffix);
198 return loc && strcmp(suffix, loc) == 0;
199}
200
201static bool isRefType(QualType RetTy, const char* prefix,
202 ASTContext* Ctx = 0, const char* name = 0) {
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000203
Ted Kremenek17144e82009-01-12 21:45:02 +0000204 if (TypedefType* TD = dyn_cast<TypedefType>(RetTy.getTypePtr())) {
205 const char* TDName = TD->getDecl()->getIdentifier()->getName();
206 return hasPrefix(TDName, prefix) && hasSuffix(TDName, "Ref");
207 }
208
209 if (!Ctx || !name)
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000210 return false;
Ted Kremenek17144e82009-01-12 21:45:02 +0000211
212 // Is the type void*?
213 const PointerType* PT = RetTy->getAsPointerType();
214 if (!(PT->getPointeeType().getUnqualifiedType() == Ctx->VoidTy))
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000215 return false;
Ted Kremenek17144e82009-01-12 21:45:02 +0000216
217 // Does the name start with the prefix?
218 return hasPrefix(name, prefix);
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000219}
220
Ted Kremenekd9ccf682008-04-17 18:12:53 +0000221//===----------------------------------------------------------------------===//
Ted Kremenek272aa852008-06-25 21:21:56 +0000222// Primitives used for constructing summaries for function/method calls.
Ted Kremenek7d421f32008-04-09 23:49:11 +0000223//===----------------------------------------------------------------------===//
224
Ted Kremenek272aa852008-06-25 21:21:56 +0000225/// ArgEffect is used to summarize a function/method call's effect on a
226/// particular argument.
Ted Kremenek6537a642009-03-17 19:42:23 +0000227enum ArgEffect { Autorelease, Dealloc, DecRef, DecRefMsg, DoNothing,
228 DoNothingByRef, IncRefMsg, IncRef, MakeCollectable, MayEscape,
229 NewAutoreleasePool, SelfOwn, StopTracking };
Ted Kremenek272aa852008-06-25 21:21:56 +0000230
Ted Kremeneka7338b42008-03-11 06:39:11 +0000231namespace llvm {
Ted Kremeneka56ae162009-05-03 05:20:50 +0000232template <> struct FoldingSetTrait<ArgEffect> {
233static inline void Profile(const ArgEffect X, FoldingSetNodeID& ID) {
234 ID.AddInteger((unsigned) X);
235}
Ted Kremenek272aa852008-06-25 21:21:56 +0000236};
Ted Kremeneka7338b42008-03-11 06:39:11 +0000237} // end llvm namespace
238
Ted Kremeneka56ae162009-05-03 05:20:50 +0000239/// ArgEffects summarizes the effects of a function/method call on all of
240/// its arguments.
241typedef llvm::ImmutableMap<unsigned,ArgEffect> ArgEffects;
242
Ted Kremeneka7338b42008-03-11 06:39:11 +0000243namespace {
Ted Kremenek272aa852008-06-25 21:21:56 +0000244
245/// RetEffect is used to summarize a function/method call's behavior with
246/// respect to its return value.
247class VISIBILITY_HIDDEN RetEffect {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000248public:
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000249 enum Kind { NoRet, Alias, OwnedSymbol, OwnedAllocatedSymbol,
Ted Kremenek382fb4e2009-04-27 19:14:45 +0000250 NotOwnedSymbol, GCNotOwnedSymbol, ReceiverAlias };
Ted Kremenek68621b92009-01-28 05:56:51 +0000251
252 enum ObjKind { CF, ObjC, AnyObj };
253
Ted Kremeneka7338b42008-03-11 06:39:11 +0000254private:
Ted Kremenek68621b92009-01-28 05:56:51 +0000255 Kind K;
256 ObjKind O;
257 unsigned index;
258
259 RetEffect(Kind k, unsigned idx = 0) : K(k), O(AnyObj), index(idx) {}
260 RetEffect(Kind k, ObjKind o) : K(k), O(o), index(0) {}
Ted Kremenek827f93b2008-03-06 00:08:09 +0000261
Ted Kremeneka7338b42008-03-11 06:39:11 +0000262public:
Ted Kremenek68621b92009-01-28 05:56:51 +0000263 Kind getKind() const { return K; }
264
265 ObjKind getObjKind() const { return O; }
Ted Kremenek272aa852008-06-25 21:21:56 +0000266
267 unsigned getIndex() const {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000268 assert(getKind() == Alias);
Ted Kremenek68621b92009-01-28 05:56:51 +0000269 return index;
Ted Kremeneka7338b42008-03-11 06:39:11 +0000270 }
Ted Kremenek827f93b2008-03-06 00:08:09 +0000271
Ted Kremenek314b1952009-04-29 23:03:22 +0000272 bool isOwned() const {
273 return K == OwnedSymbol || K == OwnedAllocatedSymbol;
274 }
275
Ted Kremenek272aa852008-06-25 21:21:56 +0000276 static RetEffect MakeAlias(unsigned Idx) {
277 return RetEffect(Alias, Idx);
278 }
279 static RetEffect MakeReceiverAlias() {
280 return RetEffect(ReceiverAlias);
281 }
Ted Kremenek68621b92009-01-28 05:56:51 +0000282 static RetEffect MakeOwned(ObjKind o, bool isAllocated = false) {
283 return RetEffect(isAllocated ? OwnedAllocatedSymbol : OwnedSymbol, o);
Ted Kremenek272aa852008-06-25 21:21:56 +0000284 }
Ted Kremenek68621b92009-01-28 05:56:51 +0000285 static RetEffect MakeNotOwned(ObjKind o) {
286 return RetEffect(NotOwnedSymbol, o);
Ted Kremenek382fb4e2009-04-27 19:14:45 +0000287 }
288 static RetEffect MakeGCNotOwned() {
289 return RetEffect(GCNotOwnedSymbol, ObjC);
290 }
291
Ted Kremenek272aa852008-06-25 21:21:56 +0000292 static RetEffect MakeNoRet() {
293 return RetEffect(NoRet);
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000294 }
Ted Kremenek827f93b2008-03-06 00:08:09 +0000295
Ted Kremenek272aa852008-06-25 21:21:56 +0000296 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek68621b92009-01-28 05:56:51 +0000297 ID.AddInteger((unsigned)K);
298 ID.AddInteger((unsigned)O);
299 ID.AddInteger(index);
Ted Kremenek272aa852008-06-25 21:21:56 +0000300 }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000301};
Ted Kremeneka7338b42008-03-11 06:39:11 +0000302
Ted Kremenek272aa852008-06-25 21:21:56 +0000303
304class VISIBILITY_HIDDEN RetainSummary : public llvm::FoldingSetNode {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000305 /// Args - an ordered vector of (index, ArgEffect) pairs, where index
306 /// specifies the argument (starting from 0). This can be sparsely
307 /// populated; arguments with no entry in Args use 'DefaultArgEffect'.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000308 ArgEffects Args;
Ted Kremenekbcaff792008-05-06 15:44:25 +0000309
310 /// DefaultArgEffect - The default ArgEffect to apply to arguments that
311 /// do not have an entry in Args.
312 ArgEffect DefaultArgEffect;
313
Ted Kremenek272aa852008-06-25 21:21:56 +0000314 /// Receiver - If this summary applies to an Objective-C message expression,
315 /// this is the effect applied to the state of the receiver.
Ted Kremenek266d8b62008-05-06 02:26:56 +0000316 ArgEffect Receiver;
Ted Kremenek272aa852008-06-25 21:21:56 +0000317
318 /// Ret - The effect on the return value. Used to indicate if the
319 /// function/method call returns a new tracked symbol, returns an
320 /// alias of one of the arguments in the call, and so on.
Ted Kremeneka7338b42008-03-11 06:39:11 +0000321 RetEffect Ret;
Ted Kremenek272aa852008-06-25 21:21:56 +0000322
Ted Kremenekf2717b02008-07-18 17:24:20 +0000323 /// EndPath - Indicates that execution of this method/function should
324 /// terminate the simulation of a path.
325 bool EndPath;
326
Ted Kremeneka7338b42008-03-11 06:39:11 +0000327public:
Ted Kremeneka56ae162009-05-03 05:20:50 +0000328 RetainSummary(ArgEffects A, RetEffect R, ArgEffect defaultEff,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000329 ArgEffect ReceiverEff, bool endpath = false)
330 : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R),
331 EndPath(endpath) {}
Ted Kremeneka7338b42008-03-11 06:39:11 +0000332
Ted Kremenek272aa852008-06-25 21:21:56 +0000333 /// getArg - Return the argument effect on the argument specified by
334 /// idx (starting from 0).
Ted Kremenek0d721572008-03-11 17:48:22 +0000335 ArgEffect getArg(unsigned idx) const {
Ted Kremeneka56ae162009-05-03 05:20:50 +0000336 if (const ArgEffect *AE = Args.lookup(idx))
337 return *AE;
Ted Kremenekae855d42008-04-24 17:22:33 +0000338
Ted Kremenekbcaff792008-05-06 15:44:25 +0000339 return DefaultArgEffect;
Ted Kremenek0d721572008-03-11 17:48:22 +0000340 }
341
Ted Kremenek272aa852008-06-25 21:21:56 +0000342 /// getRetEffect - Returns the effect on the return value of the call.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000343 RetEffect getRetEffect() const { return Ret; }
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000344
Ted Kremenekf2717b02008-07-18 17:24:20 +0000345 /// isEndPath - Returns true if executing the given method/function should
346 /// terminate the path.
347 bool isEndPath() const { return EndPath; }
348
Ted Kremenek272aa852008-06-25 21:21:56 +0000349 /// getReceiverEffect - Returns the effect on the receiver of the call.
350 /// This is only meaningful if the summary applies to an ObjCMessageExpr*.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000351 ArgEffect getReceiverEffect() const { return Receiver; }
Ted Kremenek266d8b62008-05-06 02:26:56 +0000352
Ted Kremeneka56ae162009-05-03 05:20:50 +0000353 typedef ArgEffects::iterator ExprIterator;
Ted Kremeneka7338b42008-03-11 06:39:11 +0000354
Ted Kremeneka56ae162009-05-03 05:20:50 +0000355 ExprIterator begin_args() const { return Args.begin(); }
356 ExprIterator end_args() const { return Args.end(); }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000357
Ted Kremeneka56ae162009-05-03 05:20:50 +0000358 static void Profile(llvm::FoldingSetNodeID& ID, ArgEffects A,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000359 RetEffect RetEff, ArgEffect DefaultEff,
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000360 ArgEffect ReceiverEff, bool EndPath) {
Ted Kremeneka56ae162009-05-03 05:20:50 +0000361 ID.Add(A);
Ted Kremenek266d8b62008-05-06 02:26:56 +0000362 ID.Add(RetEff);
Ted Kremenekbcaff792008-05-06 15:44:25 +0000363 ID.AddInteger((unsigned) DefaultEff);
Ted Kremenek266d8b62008-05-06 02:26:56 +0000364 ID.AddInteger((unsigned) ReceiverEff);
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000365 ID.AddInteger((unsigned) EndPath);
Ted Kremeneka7338b42008-03-11 06:39:11 +0000366 }
367
368 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000369 Profile(ID, Args, Ret, DefaultArgEffect, Receiver, EndPath);
Ted Kremeneka7338b42008-03-11 06:39:11 +0000370 }
371};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000372} // end anonymous namespace
Ted Kremeneka7338b42008-03-11 06:39:11 +0000373
Ted Kremenek272aa852008-06-25 21:21:56 +0000374//===----------------------------------------------------------------------===//
375// Data structures for constructing summaries.
376//===----------------------------------------------------------------------===//
Ted Kremenek9f0fc792008-06-24 03:49:48 +0000377
Ted Kremenek272aa852008-06-25 21:21:56 +0000378namespace {
379class VISIBILITY_HIDDEN ObjCSummaryKey {
380 IdentifierInfo* II;
381 Selector S;
382public:
383 ObjCSummaryKey(IdentifierInfo* ii, Selector s)
384 : II(ii), S(s) {}
385
Ted Kremenek314b1952009-04-29 23:03:22 +0000386 ObjCSummaryKey(const ObjCInterfaceDecl* d, Selector s)
Ted Kremenek272aa852008-06-25 21:21:56 +0000387 : II(d ? d->getIdentifier() : 0), S(s) {}
388
389 ObjCSummaryKey(Selector s)
390 : II(0), S(s) {}
391
392 IdentifierInfo* getIdentifier() const { return II; }
393 Selector getSelector() const { return S; }
394};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000395}
396
397namespace llvm {
Ted Kremenek272aa852008-06-25 21:21:56 +0000398template <> struct DenseMapInfo<ObjCSummaryKey> {
399 static inline ObjCSummaryKey getEmptyKey() {
400 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
401 DenseMapInfo<Selector>::getEmptyKey());
402 }
Ted Kremenek84f010c2008-06-23 23:30:29 +0000403
Ted Kremenek272aa852008-06-25 21:21:56 +0000404 static inline ObjCSummaryKey getTombstoneKey() {
405 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
406 DenseMapInfo<Selector>::getTombstoneKey());
407 }
408
409 static unsigned getHashValue(const ObjCSummaryKey &V) {
410 return (DenseMapInfo<IdentifierInfo*>::getHashValue(V.getIdentifier())
411 & 0x88888888)
412 | (DenseMapInfo<Selector>::getHashValue(V.getSelector())
413 & 0x55555555);
414 }
415
416 static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
417 return DenseMapInfo<IdentifierInfo*>::isEqual(LHS.getIdentifier(),
418 RHS.getIdentifier()) &&
419 DenseMapInfo<Selector>::isEqual(LHS.getSelector(),
420 RHS.getSelector());
421 }
422
423 static bool isPod() {
424 return DenseMapInfo<ObjCInterfaceDecl*>::isPod() &&
425 DenseMapInfo<Selector>::isPod();
426 }
427};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000428} // end llvm namespace
Ted Kremeneka7338b42008-03-11 06:39:11 +0000429
Ted Kremenek84f010c2008-06-23 23:30:29 +0000430namespace {
Ted Kremenek272aa852008-06-25 21:21:56 +0000431class VISIBILITY_HIDDEN ObjCSummaryCache {
432 typedef llvm::DenseMap<ObjCSummaryKey, RetainSummary*> MapTy;
433 MapTy M;
434public:
435 ObjCSummaryCache() {}
436
437 typedef MapTy::iterator iterator;
438
Ted Kremenek314b1952009-04-29 23:03:22 +0000439 iterator find(const ObjCInterfaceDecl* D, IdentifierInfo *ClsName,
440 Selector S) {
Ted Kremeneka821b792009-04-29 05:04:30 +0000441 // Lookup the method using the decl for the class @interface. If we
442 // have no decl, lookup using the class name.
443 return D ? find(D, S) : find(ClsName, S);
444 }
445
Ted Kremenek314b1952009-04-29 23:03:22 +0000446 iterator find(const ObjCInterfaceDecl* D, Selector S) {
Ted Kremenek272aa852008-06-25 21:21:56 +0000447 // Do a lookup with the (D,S) pair. If we find a match return
448 // the iterator.
449 ObjCSummaryKey K(D, S);
450 MapTy::iterator I = M.find(K);
451
452 if (I != M.end() || !D)
453 return I;
454
455 // Walk the super chain. If we find a hit with a parent, we'll end
456 // up returning that summary. We actually allow that key (null,S), as
457 // we cache summaries for the null ObjCInterfaceDecl* to allow us to
458 // generate initial summaries without having to worry about NSObject
459 // being declared.
460 // FIXME: We may change this at some point.
461 for (ObjCInterfaceDecl* C=D->getSuperClass() ;; C=C->getSuperClass()) {
462 if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
463 break;
464
465 if (!C)
466 return I;
467 }
468
469 // Cache the summary with original key to make the next lookup faster
470 // and return the iterator.
471 M[K] = I->second;
472 return I;
473 }
474
Ted Kremenek9449ca92008-08-12 20:41:56 +0000475
Ted Kremenek272aa852008-06-25 21:21:56 +0000476 iterator find(Expr* Receiver, Selector S) {
477 return find(getReceiverDecl(Receiver), S);
478 }
479
480 iterator find(IdentifierInfo* II, Selector S) {
481 // FIXME: Class method lookup. Right now we dont' have a good way
482 // of going between IdentifierInfo* and the class hierarchy.
483 iterator I = M.find(ObjCSummaryKey(II, S));
484 return I == M.end() ? M.find(ObjCSummaryKey(S)) : I;
485 }
486
487 ObjCInterfaceDecl* getReceiverDecl(Expr* E) {
488
489 const PointerType* PT = E->getType()->getAsPointerType();
490 if (!PT) return 0;
491
492 ObjCInterfaceType* OI = dyn_cast<ObjCInterfaceType>(PT->getPointeeType());
493 if (!OI) return 0;
494
495 return OI ? OI->getDecl() : 0;
496 }
497
498 iterator end() { return M.end(); }
499
500 RetainSummary*& operator[](ObjCMessageExpr* ME) {
501
502 Selector S = ME->getSelector();
503
504 if (Expr* Receiver = ME->getReceiver()) {
505 ObjCInterfaceDecl* OD = getReceiverDecl(Receiver);
506 return OD ? M[ObjCSummaryKey(OD->getIdentifier(), S)] : M[S];
507 }
508
509 return M[ObjCSummaryKey(ME->getClassName(), S)];
510 }
511
512 RetainSummary*& operator[](ObjCSummaryKey K) {
513 return M[K];
514 }
515
516 RetainSummary*& operator[](Selector S) {
517 return M[ ObjCSummaryKey(S) ];
518 }
519};
520} // end anonymous namespace
521
522//===----------------------------------------------------------------------===//
523// Data structures for managing collections of summaries.
524//===----------------------------------------------------------------------===//
525
526namespace {
527class VISIBILITY_HIDDEN RetainSummaryManager {
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000528
529 //==-----------------------------------------------------------------==//
530 // Typedefs.
531 //==-----------------------------------------------------------------==//
Ted Kremeneka7338b42008-03-11 06:39:11 +0000532
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000533 typedef llvm::FoldingSet<RetainSummary>
534 SummarySetTy;
535
536 typedef llvm::DenseMap<FunctionDecl*, RetainSummary*>
537 FuncSummariesTy;
538
Ted Kremenek84f010c2008-06-23 23:30:29 +0000539 typedef ObjCSummaryCache ObjCMethodSummariesTy;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000540
541 //==-----------------------------------------------------------------==//
542 // Data.
543 //==-----------------------------------------------------------------==//
544
Ted Kremenek272aa852008-06-25 21:21:56 +0000545 /// Ctx - The ASTContext object for the analyzed ASTs.
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000546 ASTContext& Ctx;
Ted Kremeneke44927e2008-07-01 17:21:27 +0000547
Ted Kremenekede40b72008-07-09 18:11:16 +0000548 /// CFDictionaryCreateII - An IdentifierInfo* representing the indentifier
549 /// "CFDictionaryCreate".
550 IdentifierInfo* CFDictionaryCreateII;
551
Ted Kremenek272aa852008-06-25 21:21:56 +0000552 /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000553 const bool GCEnabled;
554
Ted Kremenek272aa852008-06-25 21:21:56 +0000555 /// SummarySet - A FoldingSet of uniqued summaries.
Ted Kremeneka4c74292008-04-10 22:58:08 +0000556 SummarySetTy SummarySet;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000557
Ted Kremenek272aa852008-06-25 21:21:56 +0000558 /// FuncSummaries - A map from FunctionDecls to summaries.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000559 FuncSummariesTy FuncSummaries;
560
Ted Kremenek272aa852008-06-25 21:21:56 +0000561 /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
562 /// to summaries.
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000563 ObjCMethodSummariesTy ObjCClassMethodSummaries;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000564
Ted Kremenek272aa852008-06-25 21:21:56 +0000565 /// ObjCMethodSummaries - A map from selectors to summaries.
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000566 ObjCMethodSummariesTy ObjCMethodSummaries;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000567
Ted Kremenek272aa852008-06-25 21:21:56 +0000568 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
569 /// and all other data used by the checker.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000570 llvm::BumpPtrAllocator BPAlloc;
571
Ted Kremeneka56ae162009-05-03 05:20:50 +0000572 /// AF - A factory for ArgEffects objects.
573 ArgEffects::Factory AF;
574
Ted Kremenek272aa852008-06-25 21:21:56 +0000575 /// ScratchArgs - A holding buffer for construct ArgEffects.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000576 ArgEffects ScratchArgs;
577
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000578 RetainSummary* StopSummary;
579
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000580 //==-----------------------------------------------------------------==//
581 // Methods.
582 //==-----------------------------------------------------------------==//
583
Ted Kremenek272aa852008-06-25 21:21:56 +0000584 /// getArgEffects - Returns a persistent ArgEffects object based on the
585 /// data in ScratchArgs.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000586 ArgEffects getArgEffects();
Ted Kremeneka7338b42008-03-11 06:39:11 +0000587
Ted Kremenek562c1302008-05-05 16:51:50 +0000588 enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000589
590public:
Ted Kremenek064ef322009-02-23 16:51:39 +0000591 RetainSummary* getUnarySummary(const FunctionType* FT, UnaryFuncKind func);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000592
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000593 RetainSummary* getCFSummaryCreateRule(FunctionDecl* FD);
594 RetainSummary* getCFSummaryGetRule(FunctionDecl* FD);
Ted Kremenek17144e82009-01-12 21:45:02 +0000595 RetainSummary* getCFCreateGetRuleSummary(FunctionDecl* FD, const char* FName);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000596
Ted Kremeneka56ae162009-05-03 05:20:50 +0000597 RetainSummary* getPersistentSummary(ArgEffects AE, RetEffect RetEff,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000598 ArgEffect ReceiverEff = DoNothing,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000599 ArgEffect DefaultEff = MayEscape,
600 bool isEndPath = false);
Ted Kremenek45d0b502008-10-29 04:07:07 +0000601
Ted Kremenek266d8b62008-05-06 02:26:56 +0000602 RetainSummary* getPersistentSummary(RetEffect RE,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000603 ArgEffect ReceiverEff = DoNothing,
Ted Kremeneka3f30dd2008-05-22 17:31:13 +0000604 ArgEffect DefaultEff = MayEscape) {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000605 return getPersistentSummary(getArgEffects(), RE, ReceiverEff, DefaultEff);
Ted Kremenek0e344d42008-05-06 00:30:21 +0000606 }
Ted Kremenek42ea0322008-05-05 23:55:01 +0000607
Ted Kremeneka821b792009-04-29 05:04:30 +0000608 RetainSummary *getPersistentStopSummary() {
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000609 if (StopSummary)
610 return StopSummary;
611
612 StopSummary = getPersistentSummary(RetEffect::MakeNoRet(),
613 StopTracking, StopTracking);
Ted Kremenek45d0b502008-10-29 04:07:07 +0000614
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000615 return StopSummary;
Ted Kremenekbcaff792008-05-06 15:44:25 +0000616 }
Ted Kremenek926abf22008-05-06 04:20:12 +0000617
Ted Kremeneka821b792009-04-29 05:04:30 +0000618 RetainSummary *getInitMethodSummary(QualType RetTy);
Ted Kremenek42ea0322008-05-05 23:55:01 +0000619
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000620 void InitializeClassMethodSummaries();
621 void InitializeMethodSummaries();
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000622
Ted Kremenek9b42e062009-05-03 04:42:10 +0000623 bool isTrackedObjCObjectType(QualType T);
Ted Kremeneka9cdbc32009-05-03 06:08:32 +0000624 bool isTrackedCFObjectType(QualType T);
Ted Kremenek35920ed2009-01-07 00:39:56 +0000625
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000626private:
627
Ted Kremenekf2717b02008-07-18 17:24:20 +0000628 void addClsMethSummary(IdentifierInfo* ClsII, Selector S,
629 RetainSummary* Summ) {
630 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
631 }
632
Ted Kremenek272aa852008-06-25 21:21:56 +0000633 void addNSObjectClsMethSummary(Selector S, RetainSummary *Summ) {
634 ObjCClassMethodSummaries[S] = Summ;
635 }
636
637 void addNSObjectMethSummary(Selector S, RetainSummary *Summ) {
638 ObjCMethodSummaries[S] = Summ;
639 }
Ted Kremenekfbf2dc52009-03-04 23:30:42 +0000640
641 void addClassMethSummary(const char* Cls, const char* nullaryName,
642 RetainSummary *Summ) {
643 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
644 Selector S = GetNullarySelector(nullaryName, Ctx);
645 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
646 }
Ted Kremenek272aa852008-06-25 21:21:56 +0000647
Ted Kremenek1b4b6562009-02-25 02:54:57 +0000648 void addInstMethSummary(const char* Cls, const char* nullaryName,
649 RetainSummary *Summ) {
650 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
651 Selector S = GetNullarySelector(nullaryName, Ctx);
652 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
653 }
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000654
655 Selector generateSelector(va_list argp) {
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000656 llvm::SmallVector<IdentifierInfo*, 10> II;
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000657
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000658 while (const char* s = va_arg(argp, const char*))
659 II.push_back(&Ctx.Idents.get(s));
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000660
661 return Ctx.Selectors.getSelector(II.size(), &II[0]);
662 }
663
664 void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy& Summaries,
665 RetainSummary* Summ, va_list argp) {
666 Selector S = generateSelector(argp);
667 Summaries[ObjCSummaryKey(ClsII, S)] = Summ;
Ted Kremenekf2717b02008-07-18 17:24:20 +0000668 }
Ted Kremenek45642a42008-08-12 18:48:50 +0000669
670 void addInstMethSummary(const char* Cls, RetainSummary* Summ, ...) {
671 va_list argp;
672 va_start(argp, Summ);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000673 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Ted Kremenek45642a42008-08-12 18:48:50 +0000674 va_end(argp);
675 }
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000676
677 void addClsMethSummary(const char* Cls, RetainSummary* Summ, ...) {
678 va_list argp;
679 va_start(argp, Summ);
680 addMethodSummary(&Ctx.Idents.get(Cls),ObjCClassMethodSummaries, Summ, argp);
681 va_end(argp);
682 }
683
684 void addClsMethSummary(IdentifierInfo *II, RetainSummary* Summ, ...) {
685 va_list argp;
686 va_start(argp, Summ);
687 addMethodSummary(II, ObjCClassMethodSummaries, Summ, argp);
688 va_end(argp);
689 }
690
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000691 void addPanicSummary(const char* Cls, ...) {
Ted Kremeneka56ae162009-05-03 05:20:50 +0000692 RetainSummary* Summ = getPersistentSummary(AF.GetEmptyMap(),
693 RetEffect::MakeNoRet(),
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000694 DoNothing, DoNothing, true);
695 va_list argp;
696 va_start (argp, Cls);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000697 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000698 va_end(argp);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000699 }
Ted Kremenekf2717b02008-07-18 17:24:20 +0000700
Ted Kremeneka7338b42008-03-11 06:39:11 +0000701public:
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000702
703 RetainSummaryManager(ASTContext& ctx, bool gcenabled)
Ted Kremeneke44927e2008-07-01 17:21:27 +0000704 : Ctx(ctx),
Ted Kremenekede40b72008-07-09 18:11:16 +0000705 CFDictionaryCreateII(&ctx.Idents.get("CFDictionaryCreate")),
Ted Kremeneka56ae162009-05-03 05:20:50 +0000706 GCEnabled(gcenabled), AF(BPAlloc), ScratchArgs(AF.GetEmptyMap()),
707 StopSummary(0) {
Ted Kremenek272aa852008-06-25 21:21:56 +0000708
709 InitializeClassMethodSummaries();
710 InitializeMethodSummaries();
711 }
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000712
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000713 ~RetainSummaryManager();
Ted Kremeneka7338b42008-03-11 06:39:11 +0000714
Ted Kremenekd13c1872008-06-24 03:56:45 +0000715 RetainSummary* getSummary(FunctionDecl* FD);
Ted Kremeneka821b792009-04-29 05:04:30 +0000716
Ted Kremenek314b1952009-04-29 23:03:22 +0000717 RetainSummary* getInstanceMethodSummary(ObjCMessageExpr* ME,
718 const ObjCInterfaceDecl* ID) {
Ted Kremenek04e00302009-04-29 17:09:14 +0000719 return getInstanceMethodSummary(ME->getSelector(), ME->getClassName(),
Ted Kremeneka821b792009-04-29 05:04:30 +0000720 ID, ME->getMethodDecl(), ME->getType());
721 }
722
Ted Kremenek04e00302009-04-29 17:09:14 +0000723 RetainSummary* getInstanceMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +0000724 const ObjCInterfaceDecl* ID,
725 const ObjCMethodDecl *MD,
726 QualType RetTy);
Ted Kremenek578498a2009-04-29 00:42:39 +0000727
728 RetainSummary *getClassMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +0000729 const ObjCInterfaceDecl *ID,
730 const ObjCMethodDecl *MD,
731 QualType RetTy);
Ted Kremenek578498a2009-04-29 00:42:39 +0000732
733 RetainSummary *getClassMethodSummary(ObjCMessageExpr *ME) {
734 return getClassMethodSummary(ME->getSelector(), ME->getClassName(),
735 ME->getClassInfo().first,
736 ME->getMethodDecl(), ME->getType());
737 }
Ted Kremenek91b89a42009-04-29 17:17:48 +0000738
739 /// getMethodSummary - This version of getMethodSummary is used to query
740 /// the summary for the current method being analyzed.
Ted Kremenek314b1952009-04-29 23:03:22 +0000741 RetainSummary *getMethodSummary(const ObjCMethodDecl *MD) {
742 // FIXME: Eventually this should be unneeded.
Ted Kremenek314b1952009-04-29 23:03:22 +0000743 const ObjCInterfaceDecl *ID = MD->getClassInterface();
Ted Kremenek1447cc92009-04-30 05:41:14 +0000744 Selector S = MD->getSelector();
Ted Kremenek91b89a42009-04-29 17:17:48 +0000745 IdentifierInfo *ClsName = ID->getIdentifier();
746 QualType ResultTy = MD->getResultType();
747
Ted Kremenek81eb4642009-04-30 05:47:23 +0000748 // Resolve the method decl last.
749 if (const ObjCMethodDecl *InterfaceMD =
750 ResolveToInterfaceMethodDecl(MD, Ctx))
751 MD = InterfaceMD;
Ted Kremenek1447cc92009-04-30 05:41:14 +0000752
Ted Kremenek91b89a42009-04-29 17:17:48 +0000753 if (MD->isInstanceMethod())
754 return getInstanceMethodSummary(S, ClsName, ID, MD, ResultTy);
755 else
756 return getClassMethodSummary(S, ClsName, ID, MD, ResultTy);
757 }
Ted Kremenek578498a2009-04-29 00:42:39 +0000758
Ted Kremenek314b1952009-04-29 23:03:22 +0000759 RetainSummary* getCommonMethodSummary(const ObjCMethodDecl* MD,
760 Selector S, QualType RetTy);
761
762 RetainSummary* getMethodSummaryFromAnnotations(const ObjCMethodDecl *MD);
Ted Kremenek926abf22008-05-06 04:20:12 +0000763
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000764 bool isGCEnabled() const { return GCEnabled; }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000765};
766
767} // end anonymous namespace
768
769//===----------------------------------------------------------------------===//
770// Implementation of checker data structures.
771//===----------------------------------------------------------------------===//
772
Ted Kremeneka56ae162009-05-03 05:20:50 +0000773RetainSummaryManager::~RetainSummaryManager() {}
Ted Kremeneka7338b42008-03-11 06:39:11 +0000774
Ted Kremeneka56ae162009-05-03 05:20:50 +0000775ArgEffects RetainSummaryManager::getArgEffects() {
776 ArgEffects AE = ScratchArgs;
777 ScratchArgs = AF.GetEmptyMap();
778 return AE;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000779}
780
Ted Kremenek266d8b62008-05-06 02:26:56 +0000781RetainSummary*
Ted Kremeneka56ae162009-05-03 05:20:50 +0000782RetainSummaryManager::getPersistentSummary(ArgEffects AE, RetEffect RetEff,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000783 ArgEffect ReceiverEff,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000784 ArgEffect DefaultEff,
785 bool isEndPath) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000786
Ted Kremenekae855d42008-04-24 17:22:33 +0000787 // Generate a profile for the summary.
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000788 llvm::FoldingSetNodeID profile;
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000789 RetainSummary::Profile(profile, AE, RetEff, DefaultEff, ReceiverEff,
790 isEndPath);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000791
Ted Kremenekae855d42008-04-24 17:22:33 +0000792 // Look up the uniqued summary, or create one if it doesn't exist.
793 void* InsertPos;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000794 RetainSummary* Summ = SummarySet.FindNodeOrInsertPos(profile, InsertPos);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000795
796 if (Summ)
797 return Summ;
798
Ted Kremenekae855d42008-04-24 17:22:33 +0000799 // Create the summary and return it.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000800 Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
Ted Kremenekf2717b02008-07-18 17:24:20 +0000801 new (Summ) RetainSummary(AE, RetEff, DefaultEff, ReceiverEff, isEndPath);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000802 SummarySet.InsertNode(Summ, InsertPos);
803
804 return Summ;
805}
806
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000807//===----------------------------------------------------------------------===//
Ted Kremenek35920ed2009-01-07 00:39:56 +0000808// Predicates.
809//===----------------------------------------------------------------------===//
810
Ted Kremenek9b42e062009-05-03 04:42:10 +0000811bool RetainSummaryManager::isTrackedObjCObjectType(QualType Ty) {
Ted Kremenek0d813552009-04-23 22:11:07 +0000812 if (!Ctx.isObjCObjectPointerType(Ty))
Ted Kremenek35920ed2009-01-07 00:39:56 +0000813 return false;
814
Ted Kremenek0d813552009-04-23 22:11:07 +0000815 // We assume that id<..>, id, and "Class" all represent tracked objects.
816 const PointerType *PT = Ty->getAsPointerType();
817 if (PT == 0)
818 return true;
819
820 const ObjCInterfaceType *OT = PT->getPointeeType()->getAsObjCInterfaceType();
Ted Kremenek35920ed2009-01-07 00:39:56 +0000821
822 // We assume that id<..>, id, and "Class" all represent tracked objects.
823 if (!OT)
824 return true;
Ted Kremenek0d813552009-04-23 22:11:07 +0000825
826 // Does the interface subclass NSObject?
Ted Kremenek35920ed2009-01-07 00:39:56 +0000827 // FIXME: We can memoize here if this gets too expensive.
828 IdentifierInfo* NSObjectII = &Ctx.Idents.get("NSObject");
829 ObjCInterfaceDecl* ID = OT->getDecl();
830
831 for ( ; ID ; ID = ID->getSuperClass())
832 if (ID->getIdentifier() == NSObjectII)
833 return true;
834
835 return false;
836}
837
Ted Kremeneka9cdbc32009-05-03 06:08:32 +0000838bool RetainSummaryManager::isTrackedCFObjectType(QualType T) {
839 return isRefType(T, "CF") || // Core Foundation.
840 isRefType(T, "CG") || // Core Graphics.
841 isRefType(T, "DADisk") || // Disk Arbitration API.
842 isRefType(T, "DADissenter") ||
843 isRefType(T, "DASessionRef");
844}
845
Ted Kremenek35920ed2009-01-07 00:39:56 +0000846//===----------------------------------------------------------------------===//
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000847// Summary creation for functions (largely uses of Core Foundation).
848//===----------------------------------------------------------------------===//
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000849
Ted Kremenek17144e82009-01-12 21:45:02 +0000850static bool isRetain(FunctionDecl* FD, const char* FName) {
851 const char* loc = strstr(FName, "Retain");
852 return loc && loc[sizeof("Retain")-1] == '\0';
853}
854
855static bool isRelease(FunctionDecl* FD, const char* FName) {
856 const char* loc = strstr(FName, "Release");
857 return loc && loc[sizeof("Release")-1] == '\0';
858}
859
Ted Kremenekd13c1872008-06-24 03:56:45 +0000860RetainSummary* RetainSummaryManager::getSummary(FunctionDecl* FD) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000861
862 SourceLocation Loc = FD->getLocation();
863
864 if (!Loc.isFileID())
865 return NULL;
Ted Kremenek827f93b2008-03-06 00:08:09 +0000866
Ted Kremenekae855d42008-04-24 17:22:33 +0000867 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000868 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremenekae855d42008-04-24 17:22:33 +0000869
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000870 if (I != FuncSummaries.end())
Ted Kremenekae855d42008-04-24 17:22:33 +0000871 return I->second;
872
873 // No summary. Generate one.
Ted Kremenek17144e82009-01-12 21:45:02 +0000874 RetainSummary *S = 0;
Ted Kremenek562c1302008-05-05 16:51:50 +0000875
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000876 do {
Ted Kremenek17144e82009-01-12 21:45:02 +0000877 // We generate "stop" summaries for implicitly defined functions.
878 if (FD->isImplicit()) {
879 S = getPersistentStopSummary();
880 break;
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000881 }
Ted Kremenekeafcc2f2008-11-04 00:36:12 +0000882
Ted Kremenek064ef322009-02-23 16:51:39 +0000883 // [PR 3337] Use 'getAsFunctionType' to strip away any typedefs on the
Ted Kremenekc239b9c2009-01-16 18:40:33 +0000884 // function's type.
Ted Kremenek064ef322009-02-23 16:51:39 +0000885 const FunctionType* FT = FD->getType()->getAsFunctionType();
Ted Kremenek17144e82009-01-12 21:45:02 +0000886 const char* FName = FD->getIdentifier()->getName();
887
Ted Kremenek38c6f022009-03-05 22:11:14 +0000888 // Strip away preceding '_'. Doing this here will effect all the checks
889 // down below.
890 while (*FName == '_') ++FName;
891
Ted Kremenek17144e82009-01-12 21:45:02 +0000892 // Inspect the result type.
893 QualType RetTy = FT->getResultType();
894
895 // FIXME: This should all be refactored into a chain of "summary lookup"
896 // filters.
897 if (strcmp(FName, "IOServiceGetMatchingServices") == 0) {
898 // FIXES: <rdar://problem/6326900>
899 // This should be addressed using a API table. This strcmp is also
900 // a little gross, but there is no need to super optimize here.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000901 assert (ScratchArgs.isEmpty());
902 ScratchArgs = AF.Add(ScratchArgs, 1, DecRef);
Ted Kremenek17144e82009-01-12 21:45:02 +0000903 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
904 break;
Ted Kremenekcfc50c72008-10-22 20:54:52 +0000905 }
Ted Kremenek7b88c892009-03-17 22:43:44 +0000906
907 // Enable this code once the semantics of NSDeallocateObject are resolved
908 // for GC. <rdar://problem/6619988>
909#if 0
910 // Handle: NSDeallocateObject(id anObject);
911 // This method does allow 'nil' (although we don't check it now).
912 if (strcmp(FName, "NSDeallocateObject") == 0) {
913 return RetTy == Ctx.VoidTy
914 ? getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, Dealloc)
915 : getPersistentStopSummary();
916 }
917#endif
Ted Kremenek17144e82009-01-12 21:45:02 +0000918
919 // Handle: id NSMakeCollectable(CFTypeRef)
920 if (strcmp(FName, "NSMakeCollectable") == 0) {
921 S = (RetTy == Ctx.getObjCIdType())
922 ? getUnarySummary(FT, cfmakecollectable)
923 : getPersistentStopSummary();
924
925 break;
926 }
927
928 if (RetTy->isPointerType()) {
929 // For CoreFoundation ('CF') types.
930 if (isRefType(RetTy, "CF", &Ctx, FName)) {
931 if (isRetain(FD, FName))
932 S = getUnarySummary(FT, cfretain);
933 else if (strstr(FName, "MakeCollectable"))
934 S = getUnarySummary(FT, cfmakecollectable);
935 else
936 S = getCFCreateGetRuleSummary(FD, FName);
937
938 break;
939 }
940
941 // For CoreGraphics ('CG') types.
942 if (isRefType(RetTy, "CG", &Ctx, FName)) {
943 if (isRetain(FD, FName))
944 S = getUnarySummary(FT, cfretain);
945 else
946 S = getCFCreateGetRuleSummary(FD, FName);
947
948 break;
949 }
950
951 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
952 if (isRefType(RetTy, "DADisk") ||
953 isRefType(RetTy, "DADissenter") ||
954 isRefType(RetTy, "DASessionRef")) {
955 S = getCFCreateGetRuleSummary(FD, FName);
956 break;
957 }
958
959 break;
960 }
961
962 // Check for release functions, the only kind of functions that we care
963 // about that don't return a pointer type.
964 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
Ted Kremenek38c6f022009-03-05 22:11:14 +0000965 // Test for 'CGCF'.
966 if (FName[1] == 'G' && FName[2] == 'C' && FName[3] == 'F')
967 FName += 4;
968 else
969 FName += 2;
970
971 if (isRelease(FD, FName))
Ted Kremenek17144e82009-01-12 21:45:02 +0000972 S = getUnarySummary(FT, cfrelease);
973 else {
Ted Kremeneka56ae162009-05-03 05:20:50 +0000974 assert (ScratchArgs.isEmpty());
Ted Kremenek7b293682009-01-29 22:45:13 +0000975 // Remaining CoreFoundation and CoreGraphics functions.
976 // We use to assume that they all strictly followed the ownership idiom
977 // and that ownership cannot be transferred. While this is technically
978 // correct, many methods allow a tracked object to escape. For example:
979 //
980 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
981 // CFDictionaryAddValue(y, key, x);
982 // CFRelease(x);
983 // ... it is okay to use 'x' since 'y' has a reference to it
984 //
985 // We handle this and similar cases with the follow heuristic. If the
986 // function name contains "InsertValue", "SetValue" or "AddValue" then
987 // we assume that arguments may "escape."
988 //
989 ArgEffect E = (CStrInCStrNoCase(FName, "InsertValue") ||
990 CStrInCStrNoCase(FName, "AddValue") ||
Ted Kremenekcf071252009-02-05 22:34:53 +0000991 CStrInCStrNoCase(FName, "SetValue") ||
992 CStrInCStrNoCase(FName, "AppendValue"))
Ted Kremenek7b293682009-01-29 22:45:13 +0000993 ? MayEscape : DoNothing;
994
995 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek17144e82009-01-12 21:45:02 +0000996 }
997 }
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000998 }
999 while (0);
Ted Kremenekae855d42008-04-24 17:22:33 +00001000
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001001 FuncSummaries[FD] = S;
Ted Kremenek562c1302008-05-05 16:51:50 +00001002 return S;
Ted Kremenek827f93b2008-03-06 00:08:09 +00001003}
1004
Ted Kremenek4c5378c2008-07-15 16:50:12 +00001005RetainSummary*
1006RetainSummaryManager::getCFCreateGetRuleSummary(FunctionDecl* FD,
1007 const char* FName) {
1008
Ted Kremenek562c1302008-05-05 16:51:50 +00001009 if (strstr(FName, "Create") || strstr(FName, "Copy"))
1010 return getCFSummaryCreateRule(FD);
Ted Kremenek4c5378c2008-07-15 16:50:12 +00001011
Ted Kremenek562c1302008-05-05 16:51:50 +00001012 if (strstr(FName, "Get"))
1013 return getCFSummaryGetRule(FD);
1014
1015 return 0;
1016}
1017
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001018RetainSummary*
Ted Kremenek064ef322009-02-23 16:51:39 +00001019RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1020 UnaryFuncKind func) {
1021
Ted Kremenek17144e82009-01-12 21:45:02 +00001022 // Sanity check that this is *really* a unary function. This can
1023 // happen if people do weird things.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001024 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
Ted Kremenek17144e82009-01-12 21:45:02 +00001025 if (!FTP || FTP->getNumArgs() != 1)
1026 return getPersistentStopSummary();
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001027
Ted Kremeneka56ae162009-05-03 05:20:50 +00001028 assert (ScratchArgs.isEmpty());
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001029
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001030 switch (func) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001031 case cfretain: {
1032 ScratchArgs = AF.Add(ScratchArgs, 0, IncRef);
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001033 return getPersistentSummary(RetEffect::MakeAlias(0),
1034 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001035 }
1036
1037 case cfrelease: {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001038 ScratchArgs = AF.Add(ScratchArgs, 0, DecRef);
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001039 return getPersistentSummary(RetEffect::MakeNoRet(),
1040 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001041 }
1042
1043 case cfmakecollectable: {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001044 ScratchArgs = AF.Add(ScratchArgs, 0, MakeCollectable);
Ted Kremenek2126bef2009-02-18 21:57:45 +00001045 return getPersistentSummary(RetEffect::MakeAlias(0),DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001046 }
1047
1048 default:
Ted Kremenek562c1302008-05-05 16:51:50 +00001049 assert (false && "Not a supported unary function.");
Ted Kremenek9449ca92008-08-12 20:41:56 +00001050 return 0;
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00001051 }
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001052}
1053
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001054RetainSummary* RetainSummaryManager::getCFSummaryCreateRule(FunctionDecl* FD) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001055 assert (ScratchArgs.isEmpty());
Ted Kremenekede40b72008-07-09 18:11:16 +00001056
1057 if (FD->getIdentifier() == CFDictionaryCreateII) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001058 ScratchArgs = AF.Add(ScratchArgs, 1, DoNothingByRef);
1059 ScratchArgs = AF.Add(ScratchArgs, 2, DoNothingByRef);
Ted Kremenekede40b72008-07-09 18:11:16 +00001060 }
1061
Ted Kremenek68621b92009-01-28 05:56:51 +00001062 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001063}
1064
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001065RetainSummary* RetainSummaryManager::getCFSummaryGetRule(FunctionDecl* FD) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001066 assert (ScratchArgs.isEmpty());
Ted Kremenek68621b92009-01-28 05:56:51 +00001067 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1068 DoNothing, DoNothing);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001069}
1070
Ted Kremeneka7338b42008-03-11 06:39:11 +00001071//===----------------------------------------------------------------------===//
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001072// Summary creation for Selectors.
1073//===----------------------------------------------------------------------===//
1074
Ted Kremenekbcaff792008-05-06 15:44:25 +00001075RetainSummary*
Ted Kremeneka821b792009-04-29 05:04:30 +00001076RetainSummaryManager::getInitMethodSummary(QualType RetTy) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001077 assert(ScratchArgs.isEmpty());
Ted Kremenek42ea0322008-05-05 23:55:01 +00001078
Ted Kremenek802cfc72009-02-20 00:05:35 +00001079 // 'init' methods only return an alias if the return type is a location type.
Ted Kremeneka821b792009-04-29 05:04:30 +00001080 return getPersistentSummary(Loc::IsLocType(RetTy)
1081 ? RetEffect::MakeReceiverAlias()
1082 : RetEffect::MakeNoRet());
Ted Kremenek42ea0322008-05-05 23:55:01 +00001083}
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001084
Ted Kremenek923fc392009-04-24 23:32:32 +00001085RetainSummary*
Ted Kremenek314b1952009-04-29 23:03:22 +00001086RetainSummaryManager::getMethodSummaryFromAnnotations(const ObjCMethodDecl *MD){
Ted Kremenek923fc392009-04-24 23:32:32 +00001087 if (!MD)
1088 return 0;
1089
Ted Kremeneka56ae162009-05-03 05:20:50 +00001090 assert(ScratchArgs.isEmpty());
Ted Kremenek923fc392009-04-24 23:32:32 +00001091
1092 // Determine if there is a special return effect for this method.
Ted Kremeneke404c0d2009-04-30 20:00:31 +00001093 bool hasEffect = false;
Ted Kremenek923fc392009-04-24 23:32:32 +00001094 RetEffect RE = RetEffect::MakeNoRet();
1095
Ted Kremenek9b42e062009-05-03 04:42:10 +00001096 if (isTrackedObjCObjectType(MD->getResultType())) {
Ted Kremenek923fc392009-04-24 23:32:32 +00001097 if (MD->getAttr<ObjCOwnershipReturnsAttr>()) {
Ted Kremenek382fb4e2009-04-27 19:14:45 +00001098 RE = isGCEnabled() ? RetEffect::MakeGCNotOwned()
1099 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremeneke404c0d2009-04-30 20:00:31 +00001100 hasEffect = true;
Ted Kremenek923fc392009-04-24 23:32:32 +00001101 }
1102 else {
1103 // Default to 'not owned'.
1104 RE = RetEffect::MakeNotOwned(RetEffect::ObjC);
1105 }
1106 }
1107
Ted Kremenekb30a2f32009-04-25 01:21:50 +00001108 // Determine if there are any arguments with a specific ArgEffect.
Ted Kremenekb30a2f32009-04-25 01:21:50 +00001109 unsigned i = 0;
1110 for (ObjCMethodDecl::param_iterator I = MD->param_begin(),
1111 E = MD->param_end(); I != E; ++I, ++i) {
1112 if ((*I)->getAttr<ObjCOwnershipRetainAttr>()) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001113 ScratchArgs = AF.Add(ScratchArgs, i, IncRefMsg);
Ted Kremeneke404c0d2009-04-30 20:00:31 +00001114 hasEffect = true;
Ted Kremenekb30a2f32009-04-25 01:21:50 +00001115 }
Ted Kremenek15830ed2009-04-27 18:27:22 +00001116 else if ((*I)->getAttr<ObjCOwnershipCFRetainAttr>()) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001117 ScratchArgs = AF.Add(ScratchArgs, i, IncRef);
Ted Kremeneke404c0d2009-04-30 20:00:31 +00001118 hasEffect = true;
Ted Kremenek203169f2009-04-27 19:36:56 +00001119 }
1120 else if ((*I)->getAttr<ObjCOwnershipReleaseAttr>()) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001121 ScratchArgs = AF.Add(ScratchArgs, i, DecRefMsg);
Ted Kremeneke404c0d2009-04-30 20:00:31 +00001122 hasEffect = true;
Ted Kremenek203169f2009-04-27 19:36:56 +00001123 }
1124 else if ((*I)->getAttr<ObjCOwnershipCFReleaseAttr>()) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001125 ScratchArgs = AF.Add(ScratchArgs, i, DecRef);
Ted Kremeneke404c0d2009-04-30 20:00:31 +00001126 hasEffect = true;
Ted Kremenek203169f2009-04-27 19:36:56 +00001127 }
Ted Kremenekff8648d2009-04-28 22:32:26 +00001128 else if ((*I)->getAttr<ObjCOwnershipMakeCollectableAttr>()) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001129 ScratchArgs = AF.Add(ScratchArgs, i, MakeCollectable);
Ted Kremeneke404c0d2009-04-30 20:00:31 +00001130 hasEffect = true;
Ted Kremenekff8648d2009-04-28 22:32:26 +00001131 }
Ted Kremenek15830ed2009-04-27 18:27:22 +00001132 }
Ted Kremenekb30a2f32009-04-25 01:21:50 +00001133
Ted Kremeneke404c0d2009-04-30 20:00:31 +00001134 // Determine any effects on the receiver.
1135 ArgEffect ReceiverEff = DoNothing;
1136 if (MD->getAttr<ObjCOwnershipRetainAttr>()) {
1137 ReceiverEff = IncRefMsg;
1138 hasEffect = true;
1139 }
1140 else if (MD->getAttr<ObjCOwnershipReleaseAttr>()) {
1141 ReceiverEff = DecRefMsg;
1142 hasEffect = true;
1143 }
1144
1145 if (!hasEffect)
Ted Kremenek923fc392009-04-24 23:32:32 +00001146 return 0;
1147
Ted Kremeneke404c0d2009-04-30 20:00:31 +00001148 return getPersistentSummary(RE, ReceiverEff);
Ted Kremenek923fc392009-04-24 23:32:32 +00001149}
Ted Kremenek272aa852008-06-25 21:21:56 +00001150
Ted Kremenekbcaff792008-05-06 15:44:25 +00001151RetainSummary*
Ted Kremenek314b1952009-04-29 23:03:22 +00001152RetainSummaryManager::getCommonMethodSummary(const ObjCMethodDecl* MD,
1153 Selector S, QualType RetTy) {
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001154
Ted Kremenek578498a2009-04-29 00:42:39 +00001155 if (MD) {
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001156 // Scan the method decl for 'void*' arguments. These should be treated
1157 // as 'StopTracking' because they are often used with delegates.
1158 // Delegates are a frequent form of false positives with the retain
1159 // count checker.
1160 unsigned i = 0;
1161 for (ObjCMethodDecl::param_iterator I = MD->param_begin(),
1162 E = MD->param_end(); I != E; ++I, ++i)
1163 if (ParmVarDecl *PD = *I) {
1164 QualType Ty = Ctx.getCanonicalType(PD->getType());
1165 if (Ty.getUnqualifiedType() == Ctx.VoidPtrTy)
Ted Kremeneka56ae162009-05-03 05:20:50 +00001166 ScratchArgs = AF.Add(ScratchArgs, i, StopTracking);
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001167 }
1168 }
1169
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001170 // Any special effect for the receiver?
1171 ArgEffect ReceiverEff = DoNothing;
1172
1173 // If one of the arguments in the selector has the keyword 'delegate' we
1174 // should stop tracking the reference count for the receiver. This is
1175 // because the reference count is quite possibly handled by a delegate
1176 // method.
1177 if (S.isKeywordSelector()) {
1178 const std::string &str = S.getAsString();
1179 assert(!str.empty());
1180 if (CStrInCStrNoCase(&str[0], "delegate:")) ReceiverEff = StopTracking;
1181 }
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001182
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001183
Ted Kremenek174a0772009-04-23 23:08:22 +00001184 // Look for methods that return an owned object.
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001185 if (isTrackedObjCObjectType(RetTy)) {
1186 // EXPERIMENTAL: Assume the Cocoa conventions for all objects returned
1187 // by instance methods.
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001188
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001189 RetEffect E =
1190 followsFundamentalRule(S.getIdentifierInfoForSlot(0)->getName())
1191 ? (isGCEnabled() ? RetEffect::MakeGCNotOwned()
1192 : RetEffect::MakeOwned(RetEffect::ObjC, true))
1193 : RetEffect::MakeNotOwned(RetEffect::ObjC);
1194
1195 return getPersistentSummary(E, ReceiverEff, MayEscape);
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001196 }
Ted Kremenek174a0772009-04-23 23:08:22 +00001197
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001198 // Look for methods that return an owned core foundation object.
1199 if (isTrackedCFObjectType(RetTy)) {
1200 RetEffect E =
1201 followsFundamentalRule(S.getIdentifierInfoForSlot(0)->getName())
1202 ? RetEffect::MakeOwned(RetEffect::CF, true)
1203 : RetEffect::MakeNotOwned(RetEffect::CF);
1204
1205 return getPersistentSummary(E, ReceiverEff, MayEscape);
1206 }
Ted Kremenek174a0772009-04-23 23:08:22 +00001207
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001208 if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing)
1209 return 0;
Ted Kremenek174a0772009-04-23 23:08:22 +00001210
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001211 return getPersistentSummary(RetEffect::MakeNoRet(), ReceiverEff,
1212 MayEscape);
Ted Kremenek174a0772009-04-23 23:08:22 +00001213}
1214
1215RetainSummary*
Ted Kremenek04e00302009-04-29 17:09:14 +00001216RetainSummaryManager::getInstanceMethodSummary(Selector S,
1217 IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +00001218 const ObjCInterfaceDecl* ID,
1219 const ObjCMethodDecl *MD,
Ted Kremenek04e00302009-04-29 17:09:14 +00001220 QualType RetTy) {
Ted Kremenekbcaff792008-05-06 15:44:25 +00001221
Ted Kremeneka821b792009-04-29 05:04:30 +00001222 // Look up a summary in our summary cache.
1223 ObjCMethodSummariesTy::iterator I = ObjCMethodSummaries.find(ID, ClsName, S);
Ted Kremenek42ea0322008-05-05 23:55:01 +00001224
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001225 if (I != ObjCMethodSummaries.end())
Ted Kremenek42ea0322008-05-05 23:55:01 +00001226 return I->second;
Ted Kremenek42ea0322008-05-05 23:55:01 +00001227
Ted Kremeneka56ae162009-05-03 05:20:50 +00001228 assert(ScratchArgs.isEmpty());
Ted Kremenek923fc392009-04-24 23:32:32 +00001229
1230 // Annotations take precedence over all other ways to derive
1231 // summaries.
Ted Kremeneka821b792009-04-29 05:04:30 +00001232 RetainSummary *Summ = getMethodSummaryFromAnnotations(MD);
Ted Kremenek1d3d9562008-05-06 06:09:09 +00001233
Ted Kremenek923fc392009-04-24 23:32:32 +00001234 if (!Summ) {
1235 // "initXXX": pass-through for receiver.
1236 if (deriveNamingConvention(S.getIdentifierInfoForSlot(0)->getName())
1237 == InitRule)
Ted Kremeneka821b792009-04-29 05:04:30 +00001238 Summ = getInitMethodSummary(RetTy);
1239 else
1240 Summ = getCommonMethodSummary(MD, S, RetTy);
Ted Kremenek923fc392009-04-24 23:32:32 +00001241 }
1242
Ted Kremeneka821b792009-04-29 05:04:30 +00001243 ObjCMethodSummaries[ObjCSummaryKey(ClsName, S)] = Summ;
Ted Kremeneke4158502009-04-23 19:11:35 +00001244 return Summ;
Ted Kremenek42ea0322008-05-05 23:55:01 +00001245}
1246
Ted Kremeneka7722b72008-05-06 21:26:51 +00001247RetainSummary*
Ted Kremenek578498a2009-04-29 00:42:39 +00001248RetainSummaryManager::getClassMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +00001249 const ObjCInterfaceDecl *ID,
1250 const ObjCMethodDecl *MD,
1251 QualType RetTy) {
Ted Kremenekccbe79a2009-04-24 17:50:11 +00001252
Ted Kremenek578498a2009-04-29 00:42:39 +00001253 assert(ClsName && "Class name must be specified.");
Ted Kremeneka821b792009-04-29 05:04:30 +00001254 ObjCMethodSummariesTy::iterator I =
1255 ObjCClassMethodSummaries.find(ID, ClsName, S);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001256
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001257 if (I != ObjCClassMethodSummaries.end())
Ted Kremeneka7722b72008-05-06 21:26:51 +00001258 return I->second;
1259
Ted Kremenek923fc392009-04-24 23:32:32 +00001260 // Annotations take precedence over all other ways to derive
1261 // summaries.
Ted Kremenek578498a2009-04-29 00:42:39 +00001262 RetainSummary *Summ = getMethodSummaryFromAnnotations(MD);
Ted Kremenek923fc392009-04-24 23:32:32 +00001263
1264 if (!Summ)
Ted Kremenek578498a2009-04-29 00:42:39 +00001265 Summ = getCommonMethodSummary(MD, S, RetTy);
Ted Kremenek923fc392009-04-24 23:32:32 +00001266
Ted Kremenek578498a2009-04-29 00:42:39 +00001267 ObjCClassMethodSummaries[ObjCSummaryKey(ClsName, S)] = Summ;
Ted Kremeneke4158502009-04-23 19:11:35 +00001268 return Summ;
Ted Kremeneka7722b72008-05-06 21:26:51 +00001269}
1270
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001271void RetainSummaryManager::InitializeClassMethodSummaries() {
Ted Kremenek0e344d42008-05-06 00:30:21 +00001272
Ted Kremeneka56ae162009-05-03 05:20:50 +00001273 assert (ScratchArgs.isEmpty());
Ted Kremenek0e344d42008-05-06 00:30:21 +00001274
Ted Kremenek382fb4e2009-04-27 19:14:45 +00001275 RetEffect E = isGCEnabled() ? RetEffect::MakeGCNotOwned()
Ted Kremenek68621b92009-01-28 05:56:51 +00001276 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001277
Ted Kremenek0e344d42008-05-06 00:30:21 +00001278 RetainSummary* Summ = getPersistentSummary(E);
1279
Ted Kremenek272aa852008-06-25 21:21:56 +00001280 // Create the summaries for "alloc", "new", and "allocWithZone:" for
1281 // NSObject and its derivatives.
1282 addNSObjectClsMethSummary(GetNullarySelector("alloc", Ctx), Summ);
1283 addNSObjectClsMethSummary(GetNullarySelector("new", Ctx), Summ);
1284 addNSObjectClsMethSummary(GetUnarySelector("allocWithZone", Ctx), Summ);
Ted Kremenekf2717b02008-07-18 17:24:20 +00001285
1286 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001287 addClsMethSummary(&Ctx.Idents.get("NSAssertionHandler"),
Ted Kremenek68621b92009-01-28 05:56:51 +00001288 GetNullarySelector("currentHandler", Ctx),
1289 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001290
1291 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremeneka56ae162009-05-03 05:20:50 +00001292 ScratchArgs = AF.Add(ScratchArgs, 0, Autorelease);
Ted Kremenek9b112d22009-01-28 21:44:40 +00001293 addClsMethSummary(&Ctx.Idents.get("NSAutoreleasePool"),
1294 GetUnarySelector("addObject", Ctx),
1295 getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenekf21cb242009-02-23 02:31:16 +00001296 DoNothing, Autorelease));
Ted Kremenekccbe79a2009-04-24 17:50:11 +00001297
1298 // Create the summaries for [NSObject performSelector...]. We treat
1299 // these as 'stop tracking' for the arguments because they are often
1300 // used for delegates that can release the object. When we have better
1301 // inter-procedural analysis we can potentially do something better. This
1302 // workaround is to remove false positives.
1303 Summ = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, StopTracking);
1304 IdentifierInfo *NSObjectII = &Ctx.Idents.get("NSObject");
1305 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1306 "afterDelay", NULL);
1307 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1308 "afterDelay", "inModes", NULL);
1309 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1310 "withObject", "waitUntilDone", NULL);
1311 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1312 "withObject", "waitUntilDone", "modes", NULL);
1313 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1314 "withObject", "waitUntilDone", NULL);
1315 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1316 "withObject", "waitUntilDone", "modes", NULL);
1317 addClsMethSummary(NSObjectII, Summ, "performSelectorInBackground",
1318 "withObject", NULL);
Ted Kremenek0e344d42008-05-06 00:30:21 +00001319}
1320
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001321void RetainSummaryManager::InitializeMethodSummaries() {
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001322
Ted Kremeneka56ae162009-05-03 05:20:50 +00001323 assert (ScratchArgs.isEmpty());
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001324
Ted Kremeneka7722b72008-05-06 21:26:51 +00001325 // Create the "init" selector. It just acts as a pass-through for the
1326 // receiver.
Ted Kremenek56c70aa2009-02-23 16:54:00 +00001327 RetainSummary* InitSumm =
1328 getPersistentSummary(RetEffect::MakeReceiverAlias());
Ted Kremeneke44927e2008-07-01 17:21:27 +00001329 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001330
1331 // The next methods are allocators.
Ted Kremenek382fb4e2009-04-27 19:14:45 +00001332 RetEffect E = isGCEnabled() ? RetEffect::MakeGCNotOwned()
Ted Kremenek68621b92009-01-28 05:56:51 +00001333 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001334
Ted Kremeneke44927e2008-07-01 17:21:27 +00001335 RetainSummary* Summ = getPersistentSummary(E);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001336
1337 // Create the "copy" selector.
Ted Kremenek9449ca92008-08-12 20:41:56 +00001338 addNSObjectMethSummary(GetNullarySelector("copy", Ctx), Summ);
1339
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001340 // Create the "mutableCopy" selector.
Ted Kremenek272aa852008-06-25 21:21:56 +00001341 addNSObjectMethSummary(GetNullarySelector("mutableCopy", Ctx), Summ);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001342
Ted Kremenek266d8b62008-05-06 02:26:56 +00001343 // Create the "retain" selector.
1344 E = RetEffect::MakeReceiverAlias();
Ted Kremenek58dd95b2009-02-18 18:54:33 +00001345 Summ = getPersistentSummary(E, IncRefMsg);
Ted Kremenek272aa852008-06-25 21:21:56 +00001346 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001347
1348 // Create the "release" selector.
Ted Kremenek58dd95b2009-02-18 18:54:33 +00001349 Summ = getPersistentSummary(E, DecRefMsg);
Ted Kremenek272aa852008-06-25 21:21:56 +00001350 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Ted Kremenekc00b32b2008-05-07 21:17:39 +00001351
1352 // Create the "drain" selector.
1353 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek272aa852008-06-25 21:21:56 +00001354 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
Ted Kremenek6537a642009-03-17 19:42:23 +00001355
1356 // Create the -dealloc summary.
1357 Summ = getPersistentSummary(RetEffect::MakeNoRet(), Dealloc);
1358 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001359
1360 // Create the "autorelease" selector.
Ted Kremenek9b112d22009-01-28 21:44:40 +00001361 Summ = getPersistentSummary(E, Autorelease);
Ted Kremenek272aa852008-06-25 21:21:56 +00001362 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001363
Ted Kremenekaac82832009-02-23 17:45:03 +00001364 // Specially handle NSAutoreleasePool.
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001365 addInstMethSummary("NSAutoreleasePool", "init",
Ted Kremenekaac82832009-02-23 17:45:03 +00001366 getPersistentSummary(RetEffect::MakeReceiverAlias(),
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001367 NewAutoreleasePool));
Ted Kremenekaac82832009-02-23 17:45:03 +00001368
Ted Kremenek45642a42008-08-12 18:48:50 +00001369 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremenek7e3a3272009-02-23 02:51:29 +00001370 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1371 // self-own themselves. However, they only do this once they are displayed.
1372 // Thus, we need to track an NSWindow's display status.
1373 // This is tracked in <rdar://problem/6062711>.
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001374 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
Ted Kremeneke5a036a2009-04-03 19:02:51 +00001375 RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet());
1376
1377 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1378
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001379
1380#if 0
Ted Kremeneke44927e2008-07-01 17:21:27 +00001381 RetainSummary *NSWindowSumm =
Ted Kremenek7e3a3272009-02-23 02:51:29 +00001382 getPersistentSummary(RetEffect::MakeReceiverAlias(), StopTracking);
Ted Kremenek45642a42008-08-12 18:48:50 +00001383
1384 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1385 "styleMask", "backing", "defer", NULL);
1386
1387 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1388 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001389#endif
Ted Kremenek45642a42008-08-12 18:48:50 +00001390
1391 // For NSPanel (which subclasses NSWindow), allocated objects are not
1392 // self-owned.
Ted Kremeneke5a036a2009-04-03 19:02:51 +00001393 // FIXME: For now we don't track NSPanels. object for the same reason
1394 // as for NSWindow objects.
1395 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
1396
Ted Kremenek45642a42008-08-12 18:48:50 +00001397 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1398 "styleMask", "backing", "defer", NULL);
1399
1400 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1401 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek272aa852008-06-25 21:21:56 +00001402
Ted Kremenekf2717b02008-07-18 17:24:20 +00001403 // Create NSAssertionHandler summaries.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001404 addPanicSummary("NSAssertionHandler", "handleFailureInFunction", "file",
1405 "lineNumber", "description", NULL);
Ted Kremenekf2717b02008-07-18 17:24:20 +00001406
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001407 addPanicSummary("NSAssertionHandler", "handleFailureInMethod", "object",
1408 "file", "lineNumber", "description", NULL);
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001409}
1410
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001411//===----------------------------------------------------------------------===//
Ted Kremenek7aef4842008-04-16 20:40:59 +00001412// Reference-counting logic (typestate + counts).
Ted Kremeneka7338b42008-03-11 06:39:11 +00001413//===----------------------------------------------------------------------===//
1414
Ted Kremeneka7338b42008-03-11 06:39:11 +00001415namespace {
1416
Ted Kremenek7d421f32008-04-09 23:49:11 +00001417class VISIBILITY_HIDDEN RefVal {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001418public:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001419 enum Kind {
1420 Owned = 0, // Owning reference.
1421 NotOwned, // Reference is not owned by still valid (not freed).
1422 Released, // Object has been released.
1423 ReturnedOwned, // Returned object passes ownership to caller.
1424 ReturnedNotOwned, // Return object does not pass ownership to caller.
Ted Kremenek6537a642009-03-17 19:42:23 +00001425 ERROR_START,
1426 ErrorDeallocNotOwned, // -dealloc called on non-owned object.
1427 ErrorDeallocGC, // Calling -dealloc with GC enabled.
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001428 ErrorUseAfterRelease, // Object used after released.
1429 ErrorReleaseNotOwned, // Release of an object that was not owned.
Ted Kremenek6537a642009-03-17 19:42:23 +00001430 ERROR_LEAK_START,
Ted Kremenek311f3d42008-10-22 23:56:21 +00001431 ErrorLeak, // A memory leak due to excessive reference counts.
1432 ErrorLeakReturned // A memory leak due to the returning method not having
1433 // the correct naming conventions.
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001434 };
Ted Kremenek68621b92009-01-28 05:56:51 +00001435
1436private:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001437 Kind kind;
Ted Kremenek68621b92009-01-28 05:56:51 +00001438 RetEffect::ObjKind okind;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001439 unsigned Cnt;
Ted Kremenek272aa852008-06-25 21:21:56 +00001440 QualType T;
1441
Ted Kremenek68621b92009-01-28 05:56:51 +00001442 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, QualType t)
1443 : kind(k), okind(o), Cnt(cnt), T(t) {}
Ted Kremenek0d721572008-03-11 17:48:22 +00001444
Ted Kremenek68621b92009-01-28 05:56:51 +00001445 RefVal(Kind k, unsigned cnt = 0)
1446 : kind(k), okind(RetEffect::AnyObj), Cnt(cnt) {}
1447
1448public:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001449 Kind getKind() const { return kind; }
Ted Kremenek68621b92009-01-28 05:56:51 +00001450
1451 RetEffect::ObjKind getObjKind() const { return okind; }
Ted Kremenek0d721572008-03-11 17:48:22 +00001452
Ted Kremenek6537a642009-03-17 19:42:23 +00001453 unsigned getCount() const { return Cnt; }
1454 void clearCounts() { Cnt = 0; }
1455
Ted Kremenek272aa852008-06-25 21:21:56 +00001456 QualType getType() const { return T; }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001457
1458 // Useful predicates.
Ted Kremenek0d721572008-03-11 17:48:22 +00001459
Ted Kremenek6537a642009-03-17 19:42:23 +00001460 static bool isError(Kind k) { return k >= ERROR_START; }
Ted Kremenek1daa16c2008-03-11 18:14:09 +00001461
Ted Kremenek6537a642009-03-17 19:42:23 +00001462 static bool isLeak(Kind k) { return k >= ERROR_LEAK_START; }
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001463
Ted Kremenekffefc352008-04-11 22:25:11 +00001464 bool isOwned() const {
1465 return getKind() == Owned;
1466 }
1467
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001468 bool isNotOwned() const {
1469 return getKind() == NotOwned;
1470 }
1471
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001472 bool isReturnedOwned() const {
1473 return getKind() == ReturnedOwned;
1474 }
1475
1476 bool isReturnedNotOwned() const {
1477 return getKind() == ReturnedNotOwned;
1478 }
1479
1480 bool isNonLeakError() const {
1481 Kind k = getKind();
1482 return isError(k) && !isLeak(k);
1483 }
1484
Ted Kremenek68621b92009-01-28 05:56:51 +00001485 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
1486 unsigned Count = 1) {
1487 return RefVal(Owned, o, Count, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001488 }
1489
Ted Kremenek68621b92009-01-28 05:56:51 +00001490 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
1491 unsigned Count = 0) {
1492 return RefVal(NotOwned, o, Count, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001493 }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001494
1495 static RefVal makeReturnedOwned(unsigned Count) {
1496 return RefVal(ReturnedOwned, Count);
1497 }
1498
1499 static RefVal makeReturnedNotOwned() {
1500 return RefVal(ReturnedNotOwned);
1501 }
1502
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001503 // Comparison, profiling, and pretty-printing.
Ted Kremenek0d721572008-03-11 17:48:22 +00001504
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001505 bool operator==(const RefVal& X) const {
Ted Kremenek272aa852008-06-25 21:21:56 +00001506 return kind == X.kind && Cnt == X.Cnt && T == X.T;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001507 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001508
Ted Kremenek272aa852008-06-25 21:21:56 +00001509 RefVal operator-(size_t i) const {
Ted Kremenek68621b92009-01-28 05:56:51 +00001510 return RefVal(getKind(), getObjKind(), getCount() - i, getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001511 }
1512
1513 RefVal operator+(size_t i) const {
Ted Kremenek68621b92009-01-28 05:56:51 +00001514 return RefVal(getKind(), getObjKind(), getCount() + i, getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001515 }
1516
1517 RefVal operator^(Kind k) const {
Ted Kremenek68621b92009-01-28 05:56:51 +00001518 return RefVal(k, getObjKind(), getCount(), getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001519 }
Ted Kremenek6537a642009-03-17 19:42:23 +00001520
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001521 void Profile(llvm::FoldingSetNodeID& ID) const {
1522 ID.AddInteger((unsigned) kind);
1523 ID.AddInteger(Cnt);
Ted Kremenek272aa852008-06-25 21:21:56 +00001524 ID.Add(T);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001525 }
1526
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001527 void print(std::ostream& Out) const;
Ted Kremenek0d721572008-03-11 17:48:22 +00001528};
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001529
1530void RefVal::print(std::ostream& Out) const {
Ted Kremenek272aa852008-06-25 21:21:56 +00001531 if (!T.isNull())
1532 Out << "Tracked Type:" << T.getAsString() << '\n';
1533
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001534 switch (getKind()) {
1535 default: assert(false);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001536 case Owned: {
1537 Out << "Owned";
1538 unsigned cnt = getCount();
1539 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001540 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001541 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001542
Ted Kremenekc4f81022008-04-10 23:09:18 +00001543 case NotOwned: {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001544 Out << "NotOwned";
Ted Kremenekc4f81022008-04-10 23:09:18 +00001545 unsigned cnt = getCount();
1546 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001547 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001548 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001549
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001550 case ReturnedOwned: {
1551 Out << "ReturnedOwned";
1552 unsigned cnt = getCount();
1553 if (cnt) Out << " (+ " << cnt << ")";
1554 break;
1555 }
1556
1557 case ReturnedNotOwned: {
1558 Out << "ReturnedNotOwned";
1559 unsigned cnt = getCount();
1560 if (cnt) Out << " (+ " << cnt << ")";
1561 break;
1562 }
1563
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001564 case Released:
1565 Out << "Released";
1566 break;
Ted Kremenek6537a642009-03-17 19:42:23 +00001567
1568 case ErrorDeallocGC:
1569 Out << "-dealloc (GC)";
1570 break;
1571
1572 case ErrorDeallocNotOwned:
1573 Out << "-dealloc (not-owned)";
1574 break;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001575
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001576 case ErrorLeak:
1577 Out << "Leaked";
1578 break;
1579
Ted Kremenek311f3d42008-10-22 23:56:21 +00001580 case ErrorLeakReturned:
1581 Out << "Leaked (Bad naming)";
1582 break;
1583
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001584 case ErrorUseAfterRelease:
1585 Out << "Use-After-Release [ERROR]";
1586 break;
1587
1588 case ErrorReleaseNotOwned:
1589 Out << "Release of Not-Owned [ERROR]";
1590 break;
1591 }
1592}
Ted Kremenek0d721572008-03-11 17:48:22 +00001593
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001594} // end anonymous namespace
1595
1596//===----------------------------------------------------------------------===//
1597// RefBindings - State used to track object reference counts.
1598//===----------------------------------------------------------------------===//
1599
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001600typedef llvm::ImmutableMap<SymbolRef, RefVal> RefBindings;
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001601static int RefBIndex = 0;
Ted Kremenek876d8df2009-02-19 23:47:02 +00001602static std::pair<const void*, const void*> LeakProgramPointTag(&RefBIndex, 0);
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001603
1604namespace clang {
Ted Kremenek91781202008-08-17 03:20:02 +00001605 template<>
1606 struct GRStateTrait<RefBindings> : public GRStatePartialTrait<RefBindings> {
1607 static inline void* GDMIndex() { return &RefBIndex; }
1608 };
1609}
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001610
1611//===----------------------------------------------------------------------===//
Ted Kremenekb6578942009-02-24 19:15:11 +00001612// AutoreleaseBindings - State used to track objects in autorelease pools.
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001613//===----------------------------------------------------------------------===//
1614
Ted Kremenekb6578942009-02-24 19:15:11 +00001615typedef llvm::ImmutableMap<SymbolRef, unsigned> ARCounts;
1616typedef llvm::ImmutableMap<SymbolRef, ARCounts> ARPoolContents;
1617typedef llvm::ImmutableList<SymbolRef> ARStack;
Ted Kremenekaac82832009-02-23 17:45:03 +00001618
Ted Kremenekb6578942009-02-24 19:15:11 +00001619static int AutoRCIndex = 0;
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001620static int AutoRBIndex = 0;
1621
Ted Kremenekb6578942009-02-24 19:15:11 +00001622namespace { class VISIBILITY_HIDDEN AutoreleasePoolContents {}; }
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001623namespace { class VISIBILITY_HIDDEN AutoreleaseStack {}; }
Ted Kremenekb6578942009-02-24 19:15:11 +00001624
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001625namespace clang {
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001626template<> struct GRStateTrait<AutoreleaseStack>
Ted Kremenekb6578942009-02-24 19:15:11 +00001627 : public GRStatePartialTrait<ARStack> {
1628 static inline void* GDMIndex() { return &AutoRBIndex; }
1629};
1630
1631template<> struct GRStateTrait<AutoreleasePoolContents>
1632 : public GRStatePartialTrait<ARPoolContents> {
1633 static inline void* GDMIndex() { return &AutoRCIndex; }
1634};
1635} // end clang namespace
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001636
Ted Kremenek681fb352009-03-20 17:34:15 +00001637static SymbolRef GetCurrentAutoreleasePool(const GRState* state) {
1638 ARStack stack = state->get<AutoreleaseStack>();
1639 return stack.isEmpty() ? SymbolRef() : stack.getHead();
1640}
1641
1642static GRStateRef SendAutorelease(GRStateRef state, ARCounts::Factory &F,
1643 SymbolRef sym) {
1644
1645 SymbolRef pool = GetCurrentAutoreleasePool(state);
1646 const ARCounts *cnts = state.get<AutoreleasePoolContents>(pool);
1647 ARCounts newCnts(0);
1648
1649 if (cnts) {
1650 const unsigned *cnt = (*cnts).lookup(sym);
1651 newCnts = F.Add(*cnts, sym, cnt ? *cnt + 1 : 1);
1652 }
1653 else
1654 newCnts = F.Add(F.GetEmptyMap(), sym, 1);
1655
1656 return state.set<AutoreleasePoolContents>(pool, newCnts);
1657}
1658
Ted Kremenek7aef4842008-04-16 20:40:59 +00001659//===----------------------------------------------------------------------===//
1660// Transfer functions.
1661//===----------------------------------------------------------------------===//
1662
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001663namespace {
1664
Ted Kremenek7d421f32008-04-09 23:49:11 +00001665class VISIBILITY_HIDDEN CFRefCount : public GRSimpleVals {
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001666public:
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001667 class BindingsPrinter : public GRState::Printer {
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001668 public:
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001669 virtual void Print(std::ostream& Out, const GRState* state,
1670 const char* nl, const char* sep);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001671 };
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001672
1673private:
Ted Kremenekc26c4692009-02-18 03:48:14 +00001674 typedef llvm::DenseMap<const GRExprEngine::NodeTy*, const RetainSummary*>
1675 SummaryLogTy;
1676
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001677 RetainSummaryManager Summaries;
Ted Kremenekc26c4692009-02-18 03:48:14 +00001678 SummaryLogTy SummaryLog;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001679 const LangOptions& LOpts;
Ted Kremenekb6578942009-02-24 19:15:11 +00001680 ARCounts::Factory ARCountFactory;
Ted Kremenek91781202008-08-17 03:20:02 +00001681
Ted Kremenek708af042009-02-05 06:50:21 +00001682 BugType *useAfterRelease, *releaseNotOwned;
Ted Kremenek6537a642009-03-17 19:42:23 +00001683 BugType *deallocGC, *deallocNotOwned;
Ted Kremenek708af042009-02-05 06:50:21 +00001684 BugType *leakWithinFunction, *leakAtReturn;
1685 BugReporter *BR;
Ted Kremeneka7338b42008-03-11 06:39:11 +00001686
Ted Kremenekb6578942009-02-24 19:15:11 +00001687 GRStateRef Update(GRStateRef state, SymbolRef sym, RefVal V, ArgEffect E,
1688 RefVal::Kind& hasErr);
1689
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001690 void ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
1691 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001692 Expr* NodeExpr, Expr* ErrorExpr,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001693 ExplodedNode<GRState>* Pred,
1694 const GRState* St,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001695 RefVal::Kind hasErr, SymbolRef Sym);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001696
Ted Kremenek0106e202008-10-24 20:32:50 +00001697 std::pair<GRStateRef, bool>
1698 HandleSymbolDeath(GRStateManager& VMgr, const GRState* St,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001699 const Decl* CD, SymbolRef sid, RefVal V, bool& hasLeak);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001700
Ted Kremenekb6578942009-02-24 19:15:11 +00001701public:
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00001702 CFRefCount(ASTContext& Ctx, bool gcenabled, const LangOptions& lopts)
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001703 : Summaries(Ctx, gcenabled),
Ted Kremenek6537a642009-03-17 19:42:23 +00001704 LOpts(lopts), useAfterRelease(0), releaseNotOwned(0),
1705 deallocGC(0), deallocNotOwned(0),
Ted Kremenek708af042009-02-05 06:50:21 +00001706 leakWithinFunction(0), leakAtReturn(0), BR(0) {}
Ted Kremenek1feab292008-04-16 04:28:53 +00001707
Ted Kremenek708af042009-02-05 06:50:21 +00001708 virtual ~CFRefCount() {}
Ted Kremenek7d421f32008-04-09 23:49:11 +00001709
Ted Kremenekbf6babf2009-02-04 23:49:09 +00001710 void RegisterChecks(BugReporter &BR);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001711
Ted Kremenekb0f2b9e2008-08-16 00:49:49 +00001712 virtual void RegisterPrinters(std::vector<GRState::Printer*>& Printers) {
1713 Printers.push_back(new BindingsPrinter());
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001714 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00001715
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001716 bool isGCEnabled() const { return Summaries.isGCEnabled(); }
Ted Kremenekfe30beb2008-04-30 23:47:44 +00001717 const LangOptions& getLangOptions() const { return LOpts; }
1718
Ted Kremenekc26c4692009-02-18 03:48:14 +00001719 const RetainSummary *getSummaryOfNode(const ExplodedNode<GRState> *N) const {
1720 SummaryLogTy::const_iterator I = SummaryLog.find(N);
1721 return I == SummaryLog.end() ? 0 : I->second;
1722 }
1723
Ted Kremeneka7338b42008-03-11 06:39:11 +00001724 // Calls.
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001725
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001726 void EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001727 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001728 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001729 Expr* Ex,
1730 Expr* Receiver,
1731 RetainSummary* Summ,
Ted Kremenek2719e982008-06-17 02:43:46 +00001732 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001733 ExplodedNode<GRState>* Pred);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001734
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001735 virtual void EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekce0767f2008-03-12 21:06:49 +00001736 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001737 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001738 CallExpr* CE, SVal L,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001739 ExplodedNode<GRState>* Pred);
Ted Kremenek10fe66d2008-04-09 01:10:13 +00001740
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001741
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001742 virtual void EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001743 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001744 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001745 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001746 ExplodedNode<GRState>* Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001747
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001748 bool EvalObjCMessageExprAux(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001749 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001750 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001751 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001752 ExplodedNode<GRState>* Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001753
Ted Kremeneka42be302009-02-14 01:43:44 +00001754 // Stores.
1755 virtual void EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val);
1756
Ted Kremenekffefc352008-04-11 22:25:11 +00001757 // End-of-path.
1758
1759 virtual void EvalEndPath(GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001760 GREndPathNodeBuilder<GRState>& Builder);
Ted Kremenekffefc352008-04-11 22:25:11 +00001761
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001762 virtual void EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek541db372008-04-24 23:57:27 +00001763 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001764 GRStmtNodeBuilder<GRState>& Builder,
1765 ExplodedNode<GRState>* Pred,
Ted Kremenek5c0729b2009-01-21 22:26:05 +00001766 Stmt* S, const GRState* state,
1767 SymbolReaper& SymReaper);
1768
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001769 // Return statements.
1770
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001771 virtual void EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001772 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001773 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001774 ReturnStmt* S,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001775 ExplodedNode<GRState>* Pred);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001776
1777 // Assumptions.
1778
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001779 virtual const GRState* EvalAssume(GRStateManager& VMgr,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001780 const GRState* St, SVal Cond,
Ted Kremenekf22f8682008-07-10 22:03:41 +00001781 bool Assumption, bool& isFeasible);
Ted Kremeneka7338b42008-03-11 06:39:11 +00001782};
1783
1784} // end anonymous namespace
1785
Ted Kremenek681fb352009-03-20 17:34:15 +00001786static void PrintPool(std::ostream &Out, SymbolRef Sym, const GRState *state) {
1787 Out << ' ';
Ted Kremenek74556a12009-03-26 03:35:11 +00001788 if (Sym)
1789 Out << Sym->getSymbolID();
Ted Kremenek681fb352009-03-20 17:34:15 +00001790 else
1791 Out << "<pool>";
1792 Out << ":{";
1793
1794 // Get the contents of the pool.
1795 if (const ARCounts *cnts = state->get<AutoreleasePoolContents>(Sym))
1796 for (ARCounts::iterator J=cnts->begin(), EJ=cnts->end(); J != EJ; ++J)
1797 Out << '(' << J.getKey() << ',' << J.getData() << ')';
1798
1799 Out << '}';
1800}
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001801
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001802void CFRefCount::BindingsPrinter::Print(std::ostream& Out, const GRState* state,
1803 const char* nl, const char* sep) {
Ted Kremenek681fb352009-03-20 17:34:15 +00001804
1805
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001806
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001807 RefBindings B = state->get<RefBindings>();
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001808
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001809 if (!B.isEmpty())
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001810 Out << sep << nl;
1811
1812 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
1813 Out << (*I).first << " : ";
1814 (*I).second.print(Out);
1815 Out << nl;
1816 }
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001817
1818 // Print the autorelease stack.
Ted Kremenek681fb352009-03-20 17:34:15 +00001819 Out << sep << nl << "AR pool stack:";
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001820 ARStack stack = state->get<AutoreleaseStack>();
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001821
Ted Kremenek681fb352009-03-20 17:34:15 +00001822 PrintPool(Out, SymbolRef(), state); // Print the caller's pool.
1823 for (ARStack::iterator I=stack.begin(), E=stack.end(); I!=E; ++I)
1824 PrintPool(Out, *I, state);
1825
1826 Out << nl;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001827}
1828
Ted Kremenek47a72422009-04-29 18:50:19 +00001829//===----------------------------------------------------------------------===//
1830// Error reporting.
1831//===----------------------------------------------------------------------===//
1832
1833namespace {
1834
1835 //===-------------===//
1836 // Bug Descriptions. //
1837 //===-------------===//
1838
1839 class VISIBILITY_HIDDEN CFRefBug : public BugType {
1840 protected:
1841 CFRefCount& TF;
1842
1843 CFRefBug(CFRefCount* tf, const char* name)
1844 : BugType(name, "Memory (Core Foundation/Objective-C)"), TF(*tf) {}
1845 public:
1846
1847 CFRefCount& getTF() { return TF; }
1848 const CFRefCount& getTF() const { return TF; }
1849
1850 // FIXME: Eventually remove.
1851 virtual const char* getDescription() const = 0;
1852
1853 virtual bool isLeak() const { return false; }
1854 };
1855
1856 class VISIBILITY_HIDDEN UseAfterRelease : public CFRefBug {
1857 public:
1858 UseAfterRelease(CFRefCount* tf)
1859 : CFRefBug(tf, "Use-after-release") {}
1860
1861 const char* getDescription() const {
1862 return "Reference-counted object is used after it is released";
1863 }
1864 };
1865
1866 class VISIBILITY_HIDDEN BadRelease : public CFRefBug {
1867 public:
1868 BadRelease(CFRefCount* tf) : CFRefBug(tf, "Bad release") {}
1869
1870 const char* getDescription() const {
1871 return "Incorrect decrement of the reference count of an "
1872 "object is not owned at this point by the caller";
1873 }
1874 };
1875
1876 class VISIBILITY_HIDDEN DeallocGC : public CFRefBug {
1877 public:
1878 DeallocGC(CFRefCount *tf) : CFRefBug(tf,
1879 "-dealloc called while using GC") {}
1880
1881 const char *getDescription() const {
1882 return "-dealloc called while using GC";
1883 }
1884 };
1885
1886 class VISIBILITY_HIDDEN DeallocNotOwned : public CFRefBug {
1887 public:
1888 DeallocNotOwned(CFRefCount *tf) : CFRefBug(tf,
1889 "-dealloc sent to non-exclusively owned object") {}
1890
1891 const char *getDescription() const {
1892 return "-dealloc sent to object that may be referenced elsewhere";
1893 }
1894 };
1895
1896 class VISIBILITY_HIDDEN Leak : public CFRefBug {
1897 const bool isReturn;
1898 protected:
1899 Leak(CFRefCount* tf, const char* name, bool isRet)
1900 : CFRefBug(tf, name), isReturn(isRet) {}
1901 public:
1902
1903 const char* getDescription() const { return ""; }
1904
1905 bool isLeak() const { return true; }
1906 };
1907
1908 class VISIBILITY_HIDDEN LeakAtReturn : public Leak {
1909 public:
1910 LeakAtReturn(CFRefCount* tf, const char* name)
1911 : Leak(tf, name, true) {}
1912 };
1913
1914 class VISIBILITY_HIDDEN LeakWithinFunction : public Leak {
1915 public:
1916 LeakWithinFunction(CFRefCount* tf, const char* name)
1917 : Leak(tf, name, false) {}
1918 };
1919
1920 //===---------===//
1921 // Bug Reports. //
1922 //===---------===//
1923
1924 class VISIBILITY_HIDDEN CFRefReport : public RangedBugReport {
1925 protected:
1926 SymbolRef Sym;
1927 const CFRefCount &TF;
1928 public:
1929 CFRefReport(CFRefBug& D, const CFRefCount &tf,
1930 ExplodedNode<GRState> *n, SymbolRef sym)
1931 : RangedBugReport(D, D.getDescription(), n), Sym(sym), TF(tf) {}
1932
1933 virtual ~CFRefReport() {}
1934
1935 CFRefBug& getBugType() {
1936 return (CFRefBug&) RangedBugReport::getBugType();
1937 }
1938 const CFRefBug& getBugType() const {
1939 return (const CFRefBug&) RangedBugReport::getBugType();
1940 }
1941
1942 virtual void getRanges(BugReporter& BR, const SourceRange*& beg,
1943 const SourceRange*& end) {
1944
1945 if (!getBugType().isLeak())
1946 RangedBugReport::getRanges(BR, beg, end);
1947 else
1948 beg = end = 0;
1949 }
1950
1951 SymbolRef getSymbol() const { return Sym; }
1952
1953 PathDiagnosticPiece* getEndPath(BugReporter& BR,
1954 const ExplodedNode<GRState>* N);
1955
1956 std::pair<const char**,const char**> getExtraDescriptiveText();
1957
1958 PathDiagnosticPiece* VisitNode(const ExplodedNode<GRState>* N,
1959 const ExplodedNode<GRState>* PrevN,
1960 const ExplodedGraph<GRState>& G,
1961 BugReporter& BR,
1962 NodeResolver& NR);
1963 };
1964
1965 class VISIBILITY_HIDDEN CFRefLeakReport : public CFRefReport {
1966 SourceLocation AllocSite;
1967 const MemRegion* AllocBinding;
1968 public:
1969 CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
1970 ExplodedNode<GRState> *n, SymbolRef sym,
1971 GRExprEngine& Eng);
1972
1973 PathDiagnosticPiece* getEndPath(BugReporter& BR,
1974 const ExplodedNode<GRState>* N);
1975
1976 SourceLocation getLocation() const { return AllocSite; }
1977 };
1978} // end anonymous namespace
1979
1980void CFRefCount::RegisterChecks(BugReporter& BR) {
1981 useAfterRelease = new UseAfterRelease(this);
1982 BR.Register(useAfterRelease);
1983
1984 releaseNotOwned = new BadRelease(this);
1985 BR.Register(releaseNotOwned);
1986
1987 deallocGC = new DeallocGC(this);
1988 BR.Register(deallocGC);
1989
1990 deallocNotOwned = new DeallocNotOwned(this);
1991 BR.Register(deallocNotOwned);
1992
1993 // First register "return" leaks.
1994 const char* name = 0;
1995
1996 if (isGCEnabled())
1997 name = "Leak of returned object when using garbage collection";
1998 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
1999 name = "Leak of returned object when not using garbage collection (GC) in "
2000 "dual GC/non-GC code";
2001 else {
2002 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2003 name = "Leak of returned object";
2004 }
2005
2006 leakAtReturn = new LeakAtReturn(this, name);
2007 BR.Register(leakAtReturn);
2008
2009 // Second, register leaks within a function/method.
2010 if (isGCEnabled())
2011 name = "Leak of object when using garbage collection";
2012 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2013 name = "Leak of object when not using garbage collection (GC) in "
2014 "dual GC/non-GC code";
2015 else {
2016 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2017 name = "Leak";
2018 }
2019
2020 leakWithinFunction = new LeakWithinFunction(this, name);
2021 BR.Register(leakWithinFunction);
2022
2023 // Save the reference to the BugReporter.
2024 this->BR = &BR;
2025}
2026
2027static const char* Msgs[] = {
2028 // GC only
2029 "Code is compiled to only use garbage collection",
2030 // No GC.
2031 "Code is compiled to use reference counts",
2032 // Hybrid, with GC.
2033 "Code is compiled to use either garbage collection (GC) or reference counts"
2034 " (non-GC). The bug occurs with GC enabled",
2035 // Hybrid, without GC
2036 "Code is compiled to use either garbage collection (GC) or reference counts"
2037 " (non-GC). The bug occurs in non-GC mode"
2038};
2039
2040std::pair<const char**,const char**> CFRefReport::getExtraDescriptiveText() {
2041 CFRefCount& TF = static_cast<CFRefBug&>(getBugType()).getTF();
2042
2043 switch (TF.getLangOptions().getGCMode()) {
2044 default:
2045 assert(false);
2046
2047 case LangOptions::GCOnly:
2048 assert (TF.isGCEnabled());
2049 return std::make_pair(&Msgs[0], &Msgs[0]+1);
2050
2051 case LangOptions::NonGC:
2052 assert (!TF.isGCEnabled());
2053 return std::make_pair(&Msgs[1], &Msgs[1]+1);
2054
2055 case LangOptions::HybridGC:
2056 if (TF.isGCEnabled())
2057 return std::make_pair(&Msgs[2], &Msgs[2]+1);
2058 else
2059 return std::make_pair(&Msgs[3], &Msgs[3]+1);
2060 }
2061}
2062
2063static inline bool contains(const llvm::SmallVectorImpl<ArgEffect>& V,
2064 ArgEffect X) {
2065 for (llvm::SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
2066 I!=E; ++I)
2067 if (*I == X) return true;
2068
2069 return false;
2070}
2071
2072PathDiagnosticPiece* CFRefReport::VisitNode(const ExplodedNode<GRState>* N,
2073 const ExplodedNode<GRState>* PrevN,
2074 const ExplodedGraph<GRState>& G,
2075 BugReporter& BR,
2076 NodeResolver& NR) {
2077
2078 // Check if the type state has changed.
2079 GRStateManager &StMgr = cast<GRBugReporter>(BR).getStateManager();
2080 GRStateRef PrevSt(PrevN->getState(), StMgr);
2081 GRStateRef CurrSt(N->getState(), StMgr);
2082
2083 const RefVal* CurrT = CurrSt.get<RefBindings>(Sym);
2084 if (!CurrT) return NULL;
2085
2086 const RefVal& CurrV = *CurrT;
2087 const RefVal* PrevT = PrevSt.get<RefBindings>(Sym);
2088
2089 // Create a string buffer to constain all the useful things we want
2090 // to tell the user.
2091 std::string sbuf;
2092 llvm::raw_string_ostream os(sbuf);
2093
2094 // This is the allocation site since the previous node had no bindings
2095 // for this symbol.
2096 if (!PrevT) {
2097 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2098
2099 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2100 // Get the name of the callee (if it is available).
2101 SVal X = CurrSt.GetSValAsScalarOrLoc(CE->getCallee());
2102 if (const FunctionDecl* FD = X.getAsFunctionDecl())
2103 os << "Call to function '" << FD->getNameAsString() <<'\'';
2104 else
2105 os << "function call";
2106 }
2107 else {
2108 assert (isa<ObjCMessageExpr>(S));
2109 os << "Method";
2110 }
2111
2112 if (CurrV.getObjKind() == RetEffect::CF) {
2113 os << " returns a Core Foundation object with a ";
2114 }
2115 else {
2116 assert (CurrV.getObjKind() == RetEffect::ObjC);
2117 os << " returns an Objective-C object with a ";
2118 }
2119
2120 if (CurrV.isOwned()) {
2121 os << "+1 retain count (owning reference).";
2122
2123 if (static_cast<CFRefBug&>(getBugType()).getTF().isGCEnabled()) {
2124 assert(CurrV.getObjKind() == RetEffect::CF);
2125 os << " "
2126 "Core Foundation objects are not automatically garbage collected.";
2127 }
2128 }
2129 else {
2130 assert (CurrV.isNotOwned());
2131 os << "+0 retain count (non-owning reference).";
2132 }
2133
2134 PathDiagnosticLocation Pos(S, BR.getContext().getSourceManager());
2135 return new PathDiagnosticEventPiece(Pos, os.str());
2136 }
2137
2138 // Gather up the effects that were performed on the object at this
2139 // program point
2140 llvm::SmallVector<ArgEffect, 2> AEffects;
2141
2142 if (const RetainSummary *Summ = TF.getSummaryOfNode(NR.getOriginalNode(N))) {
2143 // We only have summaries attached to nodes after evaluating CallExpr and
2144 // ObjCMessageExprs.
2145 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2146
2147 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2148 // Iterate through the parameter expressions and see if the symbol
2149 // was ever passed as an argument.
2150 unsigned i = 0;
2151
2152 for (CallExpr::arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
2153 AI!=AE; ++AI, ++i) {
2154
2155 // Retrieve the value of the argument. Is it the symbol
2156 // we are interested in?
2157 if (CurrSt.GetSValAsScalarOrLoc(*AI).getAsLocSymbol() != Sym)
2158 continue;
2159
2160 // We have an argument. Get the effect!
2161 AEffects.push_back(Summ->getArg(i));
2162 }
2163 }
2164 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
2165 if (Expr *receiver = ME->getReceiver())
2166 if (CurrSt.GetSValAsScalarOrLoc(receiver).getAsLocSymbol() == Sym) {
2167 // The symbol we are tracking is the receiver.
2168 AEffects.push_back(Summ->getReceiverEffect());
2169 }
2170 }
2171 }
2172
2173 do {
2174 // Get the previous type state.
2175 RefVal PrevV = *PrevT;
2176
2177 // Specially handle -dealloc.
2178 if (!TF.isGCEnabled() && contains(AEffects, Dealloc)) {
2179 // Determine if the object's reference count was pushed to zero.
2180 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2181 // We may not have transitioned to 'release' if we hit an error.
2182 // This case is handled elsewhere.
2183 if (CurrV.getKind() == RefVal::Released) {
2184 assert(CurrV.getCount() == 0);
2185 os << "Object released by directly sending the '-dealloc' message";
2186 break;
2187 }
2188 }
2189
2190 // Specially handle CFMakeCollectable and friends.
2191 if (contains(AEffects, MakeCollectable)) {
2192 // Get the name of the function.
2193 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2194 SVal X = CurrSt.GetSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee());
2195 const FunctionDecl* FD = X.getAsFunctionDecl();
2196 const std::string& FName = FD->getNameAsString();
2197
2198 if (TF.isGCEnabled()) {
2199 // Determine if the object's reference count was pushed to zero.
2200 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2201
2202 os << "In GC mode a call to '" << FName
2203 << "' decrements an object's retain count and registers the "
2204 "object with the garbage collector. ";
2205
2206 if (CurrV.getKind() == RefVal::Released) {
2207 assert(CurrV.getCount() == 0);
2208 os << "Since it now has a 0 retain count the object can be "
2209 "automatically collected by the garbage collector.";
2210 }
2211 else
2212 os << "An object must have a 0 retain count to be garbage collected. "
2213 "After this call its retain count is +" << CurrV.getCount()
2214 << '.';
2215 }
2216 else
2217 os << "When GC is not enabled a call to '" << FName
2218 << "' has no effect on its argument.";
2219
2220 // Nothing more to say.
2221 break;
2222 }
2223
2224 // Determine if the typestate has changed.
2225 if (!(PrevV == CurrV))
2226 switch (CurrV.getKind()) {
2227 case RefVal::Owned:
2228 case RefVal::NotOwned:
2229
2230 if (PrevV.getCount() == CurrV.getCount())
2231 return 0;
2232
2233 if (PrevV.getCount() > CurrV.getCount())
2234 os << "Reference count decremented.";
2235 else
2236 os << "Reference count incremented.";
2237
2238 if (unsigned Count = CurrV.getCount())
2239 os << " The object now has a +" << Count << " retain count.";
2240
2241 if (PrevV.getKind() == RefVal::Released) {
2242 assert(TF.isGCEnabled() && CurrV.getCount() > 0);
2243 os << " The object is not eligible for garbage collection until the "
2244 "retain count reaches 0 again.";
2245 }
2246
2247 break;
2248
2249 case RefVal::Released:
2250 os << "Object released.";
2251 break;
2252
2253 case RefVal::ReturnedOwned:
2254 os << "Object returned to caller as an owning reference (single retain "
2255 "count transferred to caller).";
2256 break;
2257
2258 case RefVal::ReturnedNotOwned:
2259 os << "Object returned to caller with a +0 (non-owning) retain count.";
2260 break;
2261
2262 default:
2263 return NULL;
2264 }
2265
2266 // Emit any remaining diagnostics for the argument effects (if any).
2267 for (llvm::SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
2268 E=AEffects.end(); I != E; ++I) {
2269
2270 // A bunch of things have alternate behavior under GC.
2271 if (TF.isGCEnabled())
2272 switch (*I) {
2273 default: break;
2274 case Autorelease:
2275 os << "In GC mode an 'autorelease' has no effect.";
2276 continue;
2277 case IncRefMsg:
2278 os << "In GC mode the 'retain' message has no effect.";
2279 continue;
2280 case DecRefMsg:
2281 os << "In GC mode the 'release' message has no effect.";
2282 continue;
2283 }
2284 }
2285 } while(0);
2286
2287 if (os.str().empty())
2288 return 0; // We have nothing to say!
2289
2290 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2291 PathDiagnosticLocation Pos(S, BR.getContext().getSourceManager());
2292 PathDiagnosticPiece* P = new PathDiagnosticEventPiece(Pos, os.str());
2293
2294 // Add the range by scanning the children of the statement for any bindings
2295 // to Sym.
2296 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I)
2297 if (Expr* Exp = dyn_cast_or_null<Expr>(*I))
2298 if (CurrSt.GetSValAsScalarOrLoc(Exp).getAsLocSymbol() == Sym) {
2299 P->addRange(Exp->getSourceRange());
2300 break;
2301 }
2302
2303 return P;
2304}
2305
2306namespace {
2307 class VISIBILITY_HIDDEN FindUniqueBinding :
2308 public StoreManager::BindingsHandler {
2309 SymbolRef Sym;
2310 const MemRegion* Binding;
2311 bool First;
2312
2313 public:
2314 FindUniqueBinding(SymbolRef sym) : Sym(sym), Binding(0), First(true) {}
2315
2316 bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
2317 SVal val) {
2318
2319 SymbolRef SymV = val.getAsSymbol();
2320 if (!SymV || SymV != Sym)
2321 return true;
2322
2323 if (Binding) {
2324 First = false;
2325 return false;
2326 }
2327 else
2328 Binding = R;
2329
2330 return true;
2331 }
2332
2333 operator bool() { return First && Binding; }
2334 const MemRegion* getRegion() { return Binding; }
2335 };
2336}
2337
2338static std::pair<const ExplodedNode<GRState>*,const MemRegion*>
2339GetAllocationSite(GRStateManager& StateMgr, const ExplodedNode<GRState>* N,
2340 SymbolRef Sym) {
2341
2342 // Find both first node that referred to the tracked symbol and the
2343 // memory location that value was store to.
2344 const ExplodedNode<GRState>* Last = N;
2345 const MemRegion* FirstBinding = 0;
2346
2347 while (N) {
2348 const GRState* St = N->getState();
2349 RefBindings B = St->get<RefBindings>();
2350
2351 if (!B.lookup(Sym))
2352 break;
2353
2354 FindUniqueBinding FB(Sym);
2355 StateMgr.iterBindings(St, FB);
2356 if (FB) FirstBinding = FB.getRegion();
2357
2358 Last = N;
2359 N = N->pred_empty() ? NULL : *(N->pred_begin());
2360 }
2361
2362 return std::make_pair(Last, FirstBinding);
2363}
2364
2365PathDiagnosticPiece*
2366CFRefReport::getEndPath(BugReporter& br, const ExplodedNode<GRState>* EndN) {
2367 // Tell the BugReporter to report cases when the tracked symbol is
2368 // assigned to different variables, etc.
2369 GRBugReporter& BR = cast<GRBugReporter>(br);
2370 cast<GRBugReporter>(BR).addNotableSymbol(Sym);
2371 return RangedBugReport::getEndPath(BR, EndN);
2372}
2373
2374PathDiagnosticPiece*
2375CFRefLeakReport::getEndPath(BugReporter& br, const ExplodedNode<GRState>* EndN){
2376
2377 GRBugReporter& BR = cast<GRBugReporter>(br);
2378 // Tell the BugReporter to report cases when the tracked symbol is
2379 // assigned to different variables, etc.
2380 cast<GRBugReporter>(BR).addNotableSymbol(Sym);
2381
2382 // We are reporting a leak. Walk up the graph to get to the first node where
2383 // the symbol appeared, and also get the first VarDecl that tracked object
2384 // is stored to.
2385 const ExplodedNode<GRState>* AllocNode = 0;
2386 const MemRegion* FirstBinding = 0;
2387
2388 llvm::tie(AllocNode, FirstBinding) =
2389 GetAllocationSite(BR.getStateManager(), EndN, Sym);
2390
2391 // Get the allocate site.
2392 assert(AllocNode);
2393 Stmt* FirstStmt = cast<PostStmt>(AllocNode->getLocation()).getStmt();
2394
2395 SourceManager& SMgr = BR.getContext().getSourceManager();
2396 unsigned AllocLine =SMgr.getInstantiationLineNumber(FirstStmt->getLocStart());
2397
2398 // Compute an actual location for the leak. Sometimes a leak doesn't
2399 // occur at an actual statement (e.g., transition between blocks; end
2400 // of function) so we need to walk the graph and compute a real location.
2401 const ExplodedNode<GRState>* LeakN = EndN;
2402 PathDiagnosticLocation L;
2403
2404 while (LeakN) {
2405 ProgramPoint P = LeakN->getLocation();
2406
2407 if (const PostStmt *PS = dyn_cast<PostStmt>(&P)) {
2408 L = PathDiagnosticLocation(PS->getStmt()->getLocStart(), SMgr);
2409 break;
2410 }
2411 else if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
2412 if (const Stmt* Term = BE->getSrc()->getTerminator()) {
2413 L = PathDiagnosticLocation(Term->getLocStart(), SMgr);
2414 break;
2415 }
2416 }
2417
2418 LeakN = LeakN->succ_empty() ? 0 : *(LeakN->succ_begin());
2419 }
2420
2421 if (!L.isValid()) {
Ted Kremenek0a6913d2009-04-29 21:31:59 +00002422 const Decl &D = BR.getStateManager().getCodeDecl();
2423 L = PathDiagnosticLocation(D.getBodyRBrace(BR.getContext()), SMgr);
Ted Kremenek47a72422009-04-29 18:50:19 +00002424 }
2425
2426 std::string sbuf;
2427 llvm::raw_string_ostream os(sbuf);
2428
2429 os << "Object allocated on line " << AllocLine;
2430
2431 if (FirstBinding)
2432 os << " and stored into '" << FirstBinding->getString() << '\'';
2433
2434 // Get the retain count.
2435 const RefVal* RV = EndN->getState()->get<RefBindings>(Sym);
2436
2437 if (RV->getKind() == RefVal::ErrorLeakReturned) {
2438 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
2439 // ojbects. Only "copy", "alloc", "retain" and "new" transfer ownership
2440 // to the caller for NS objects.
2441 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(BR.getGraph().getCodeDecl());
2442 os << " is returned from a method whose name ('"
Ted Kremenek314b1952009-04-29 23:03:22 +00002443 << MD.getSelector().getAsString()
Ted Kremenek47a72422009-04-29 18:50:19 +00002444 << "') does not contain 'copy' or otherwise starts with"
2445 " 'new' or 'alloc'. This violates the naming convention rules given"
Ted Kremenek2a410c92009-04-29 22:25:52 +00002446 " in the Memory Management Guide for Cocoa (object leaked)";
Ted Kremenek47a72422009-04-29 18:50:19 +00002447 }
2448 else
2449 os << " is no longer referenced after this point and has a retain count of"
Ted Kremenek2a410c92009-04-29 22:25:52 +00002450 " +" << RV->getCount() << " (object leaked)";
Ted Kremenek47a72422009-04-29 18:50:19 +00002451
2452 return new PathDiagnosticEventPiece(L, os.str());
2453}
2454
2455
2456CFRefLeakReport::CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2457 ExplodedNode<GRState> *n,
2458 SymbolRef sym, GRExprEngine& Eng)
2459: CFRefReport(D, tf, n, sym)
2460{
2461
2462 // Most bug reports are cached at the location where they occured.
2463 // With leaks, we want to unique them by the location where they were
2464 // allocated, and only report a single path. To do this, we need to find
2465 // the allocation site of a piece of tracked memory, which we do via a
2466 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2467 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2468 // that all ancestor nodes that represent the allocation site have the
2469 // same SourceLocation.
2470 const ExplodedNode<GRState>* AllocNode = 0;
2471
2472 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding.
2473 GetAllocationSite(Eng.getStateManager(), getEndNode(), getSymbol());
2474
2475 // Get the SourceLocation for the allocation site.
2476 ProgramPoint P = AllocNode->getLocation();
2477 AllocSite = cast<PostStmt>(P).getStmt()->getLocStart();
2478
2479 // Fill in the description of the bug.
2480 Description.clear();
2481 llvm::raw_string_ostream os(Description);
2482 SourceManager& SMgr = Eng.getContext().getSourceManager();
2483 unsigned AllocLine = SMgr.getInstantiationLineNumber(AllocSite);
Ted Kremenek2e9d0302009-05-02 19:05:19 +00002484 os << "Potential leak ";
2485 if (tf.isGCEnabled()) {
2486 os << "(when using garbage collection) ";
2487 }
2488 os << "of an object allocated on line " << AllocLine;
Ted Kremenek47a72422009-04-29 18:50:19 +00002489
2490 // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2491 if (AllocBinding)
2492 os << " and stored into '" << AllocBinding->getString() << '\'';
2493}
2494
2495//===----------------------------------------------------------------------===//
2496// Main checker logic.
2497//===----------------------------------------------------------------------===//
2498
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002499static inline ArgEffect GetArgE(RetainSummary* Summ, unsigned idx) {
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00002500 return Summ ? Summ->getArg(idx) : MayEscape;
Ted Kremenek455dd862008-04-11 20:23:24 +00002501}
2502
Ted Kremenek266d8b62008-05-06 02:26:56 +00002503static inline RetEffect GetRetEffect(RetainSummary* Summ) {
2504 return Summ ? Summ->getRetEffect() : RetEffect::MakeNoRet();
Ted Kremenek455dd862008-04-11 20:23:24 +00002505}
2506
Ted Kremenek227c5372008-05-06 02:41:27 +00002507static inline ArgEffect GetReceiverE(RetainSummary* Summ) {
2508 return Summ ? Summ->getReceiverEffect() : DoNothing;
2509}
2510
Ted Kremenekf2717b02008-07-18 17:24:20 +00002511static inline bool IsEndPath(RetainSummary* Summ) {
2512 return Summ ? Summ->isEndPath() : false;
2513}
2514
Ted Kremenek1feab292008-04-16 04:28:53 +00002515
Ted Kremenek272aa852008-06-25 21:21:56 +00002516/// GetReturnType - Used to get the return type of a message expression or
2517/// function call with the intention of affixing that type to a tracked symbol.
2518/// While the the return type can be queried directly from RetEx, when
2519/// invoking class methods we augment to the return type to be that of
2520/// a pointer to the class (as opposed it just being id).
2521static QualType GetReturnType(Expr* RetE, ASTContext& Ctx) {
2522
2523 QualType RetTy = RetE->getType();
2524
2525 // FIXME: We aren't handling id<...>.
Chris Lattnerb724ab22008-07-26 22:36:27 +00002526 const PointerType* PT = RetTy->getAsPointerType();
Ted Kremenek272aa852008-06-25 21:21:56 +00002527 if (!PT)
2528 return RetTy;
2529
2530 // If RetEx is not a message expression just return its type.
2531 // If RetEx is a message expression, return its types if it is something
2532 /// more specific than id.
2533
2534 ObjCMessageExpr* ME = dyn_cast<ObjCMessageExpr>(RetE);
2535
Steve Naroff17c03822009-02-12 17:52:19 +00002536 if (!ME || !Ctx.isObjCIdStructType(PT->getPointeeType()))
Ted Kremenek272aa852008-06-25 21:21:56 +00002537 return RetTy;
2538
2539 ObjCInterfaceDecl* D = ME->getClassInfo().first;
2540
2541 // At this point we know the return type of the message expression is id.
2542 // If we have an ObjCInterceDecl, we know this is a call to a class method
2543 // whose type we can resolve. In such cases, promote the return type to
2544 // Class*.
2545 return !D ? RetTy : Ctx.getPointerType(Ctx.getObjCInterfaceType(D));
2546}
2547
2548
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002549void CFRefCount::EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002550 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002551 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002552 Expr* Ex,
2553 Expr* Receiver,
2554 RetainSummary* Summ,
Zhongxing Xucac107a2009-04-20 05:24:46 +00002555 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002556 ExplodedNode<GRState>* Pred) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002557
Ted Kremeneka7338b42008-03-11 06:39:11 +00002558 // Get the state.
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002559 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenek0106e202008-10-24 20:32:50 +00002560 ASTContext& Ctx = Eng.getStateManager().getContext();
Ted Kremenek227c5372008-05-06 02:41:27 +00002561
2562 // Evaluate the effect of the arguments.
Ted Kremenek1feab292008-04-16 04:28:53 +00002563 RefVal::Kind hasErr = (RefVal::Kind) 0;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002564 unsigned idx = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002565 Expr* ErrorExpr = NULL;
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002566 SymbolRef ErrorSym = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002567
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002568 for (ExprIterator I = arg_beg; I != arg_end; ++I, ++idx) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002569 SVal V = state.GetSValAsScalarOrLoc(*I);
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002570 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002571
Ted Kremenek74556a12009-03-26 03:35:11 +00002572 if (Sym)
Ted Kremenekb6578942009-02-24 19:15:11 +00002573 if (RefBindings::data_type* T = state.get<RefBindings>(Sym)) {
2574 state = Update(state, Sym, *T, GetArgE(Summ, idx), hasErr);
2575 if (hasErr) {
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002576 ErrorExpr = *I;
Ted Kremenek6064a362008-07-07 16:21:19 +00002577 ErrorSym = Sym;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002578 break;
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002579 }
2580 continue;
Ted Kremenekb6578942009-02-24 19:15:11 +00002581 }
Ted Kremenekede40b72008-07-09 18:11:16 +00002582
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002583 if (isa<Loc>(V)) {
2584 if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(&V)) {
Ted Kremenekede40b72008-07-09 18:11:16 +00002585 if (GetArgE(Summ, idx) == DoNothingByRef)
2586 continue;
2587
2588 // Invalidate the value of the variable passed by reference.
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002589
2590 // FIXME: Either this logic should also be replicated in GRSimpleVals
2591 // or should be pulled into a separate "constraint engine."
Ted Kremenekede40b72008-07-09 18:11:16 +00002592
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002593 // FIXME: We can have collisions on the conjured symbol if the
2594 // expression *I also creates conjured symbols. We probably want
2595 // to identify conjured symbols by an expression pair: the enclosing
2596 // expression (the context) and the expression itself. This should
Ted Kremenekede40b72008-07-09 18:11:16 +00002597 // disambiguate conjured symbols.
Ted Kremenekb15eba42008-10-04 05:50:14 +00002598
Ted Kremenek38a4b4b2008-10-17 20:28:54 +00002599 const TypedRegion* R = dyn_cast<TypedRegion>(MR->getRegion());
Zhongxing Xub9d47a42009-04-29 02:30:09 +00002600
Ted Kremenek53b24182009-03-04 22:56:43 +00002601 if (R) {
Ted Kremenek618c6cd2008-12-18 23:34:57 +00002602 // Is the invalidated variable something that we were tracking?
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002603 SymbolRef Sym = state.GetSValAsScalarOrLoc(R).getAsLocSymbol();
Ted Kremenek618c6cd2008-12-18 23:34:57 +00002604
Ted Kremenek53b24182009-03-04 22:56:43 +00002605 // Remove any existing reference-count binding.
Ted Kremenek74556a12009-03-26 03:35:11 +00002606 if (Sym) state = state.remove<RefBindings>(Sym);
Ted Kremenekb15eba42008-10-04 05:50:14 +00002607
Ted Kremenek53b24182009-03-04 22:56:43 +00002608 if (R->isBoundable(Ctx)) {
2609 // Set the value of the variable to be a conjured symbol.
2610 unsigned Count = Builder.getCurrentBlockCount();
2611 QualType T = R->getRValueType(Ctx);
2612
Zhongxing Xu079dc352009-04-09 06:03:54 +00002613 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())){
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002614 ValueManager &ValMgr = Eng.getValueManager();
2615 SVal V = ValMgr.getConjuredSymbolVal(*I, T, Count);
Zhongxing Xu079dc352009-04-09 06:03:54 +00002616 state = state.BindLoc(Loc::MakeVal(R), V);
Ted Kremenek53b24182009-03-04 22:56:43 +00002617 }
2618 else if (const RecordType *RT = T->getAsStructureType()) {
2619 // Handle structs in a not so awesome way. Here we just
2620 // eagerly bind new symbols to the fields. In reality we
2621 // should have the store manager handle this. The idea is just
2622 // to prototype some basic functionality here. All of this logic
2623 // should one day soon just go away.
2624 const RecordDecl *RD = RT->getDecl()->getDefinition(Ctx);
2625
2626 // No record definition. There is nothing we can do.
2627 if (!RD)
2628 continue;
2629
2630 MemRegionManager &MRMgr = state.getManager().getRegionManager();
2631
2632 // Iterate through the fields and construct new symbols.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002633 for (RecordDecl::field_iterator FI=RD->field_begin(Ctx),
2634 FE=RD->field_end(Ctx); FI!=FE; ++FI) {
Ted Kremenek53b24182009-03-04 22:56:43 +00002635
2636 // For now just handle scalar fields.
2637 FieldDecl *FD = *FI;
2638 QualType FT = FD->getType();
2639
2640 if (Loc::IsLocType(FT) ||
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002641 (FT->isIntegerType() && FT->isScalarType())) {
Ted Kremenek53b24182009-03-04 22:56:43 +00002642 const FieldRegion* FR = MRMgr.getFieldRegion(FD, R);
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002643 ValueManager &ValMgr = Eng.getValueManager();
2644 SVal V = ValMgr.getConjuredSymbolVal(*I, FT, Count);
Zhongxing Xuc458e322009-04-09 06:32:20 +00002645 state = state.BindLoc(Loc::MakeVal(FR), V);
Ted Kremenek53b24182009-03-04 22:56:43 +00002646 }
2647 }
2648 }
2649 else {
2650 // Just blast away other values.
2651 state = state.BindLoc(*MR, UnknownVal());
2652 }
Ted Kremenek8f90e712008-10-17 22:23:12 +00002653 }
Ted Kremenekb15eba42008-10-04 05:50:14 +00002654 }
2655 else
Ted Kremenek09102db2008-11-12 19:22:09 +00002656 state = state.BindLoc(*MR, UnknownVal());
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002657 }
2658 else {
2659 // Nuke all other arguments passed by reference.
Zhongxing Xu097fc982008-10-17 05:57:07 +00002660 state = state.Unbind(cast<Loc>(V));
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002661 }
Ted Kremeneke4924202008-04-11 20:51:02 +00002662 }
Zhongxing Xu097fc982008-10-17 05:57:07 +00002663 else if (isa<nonloc::LocAsInteger>(V))
2664 state = state.Unbind(cast<nonloc::LocAsInteger>(V).getLoc());
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002665 }
Ted Kremenek1feab292008-04-16 04:28:53 +00002666
Ted Kremenek272aa852008-06-25 21:21:56 +00002667 // Evaluate the effect on the message receiver.
Ted Kremenek227c5372008-05-06 02:41:27 +00002668 if (!ErrorExpr && Receiver) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002669 SymbolRef Sym = state.GetSValAsScalarOrLoc(Receiver).getAsLocSymbol();
Ted Kremenek74556a12009-03-26 03:35:11 +00002670 if (Sym) {
Ted Kremenekb6578942009-02-24 19:15:11 +00002671 if (const RefVal* T = state.get<RefBindings>(Sym)) {
2672 state = Update(state, Sym, *T, GetReceiverE(Summ), hasErr);
2673 if (hasErr) {
Ted Kremenek227c5372008-05-06 02:41:27 +00002674 ErrorExpr = Receiver;
Ted Kremenek6064a362008-07-07 16:21:19 +00002675 ErrorSym = Sym;
Ted Kremenek227c5372008-05-06 02:41:27 +00002676 }
Ted Kremenekb6578942009-02-24 19:15:11 +00002677 }
Ted Kremenek227c5372008-05-06 02:41:27 +00002678 }
2679 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002680
Ted Kremenek272aa852008-06-25 21:21:56 +00002681 // Process any errors.
Ted Kremenek1feab292008-04-16 04:28:53 +00002682 if (hasErr) {
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002683 ProcessNonLeakError(Dst, Builder, Ex, ErrorExpr, Pred, state,
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002684 hasErr, ErrorSym);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002685 return;
Ted Kremenek0d721572008-03-11 17:48:22 +00002686 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002687
Ted Kremenekf2717b02008-07-18 17:24:20 +00002688 // Consult the summary for the return value.
Ted Kremenek266d8b62008-05-06 02:26:56 +00002689 RetEffect RE = GetRetEffect(Summ);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002690
2691 switch (RE.getKind()) {
2692 default:
2693 assert (false && "Unhandled RetEffect."); break;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002694
Ted Kremenek8f90e712008-10-17 22:23:12 +00002695 case RetEffect::NoRet: {
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002696
Ted Kremenek455dd862008-04-11 20:23:24 +00002697 // Make up a symbol for the return value (not reference counted).
Ted Kremeneke4924202008-04-11 20:51:02 +00002698 // FIXME: This is basically copy-and-paste from GRSimpleVals. We
2699 // should compose behavior, not copy it.
Ted Kremenek455dd862008-04-11 20:23:24 +00002700
Ted Kremenek8f90e712008-10-17 22:23:12 +00002701 // FIXME: We eventually should handle structs and other compound types
2702 // that are returned by value.
2703
2704 QualType T = Ex->getType();
2705
Ted Kremenek79413a52008-11-13 06:10:40 +00002706 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())) {
Ted Kremenek455dd862008-04-11 20:23:24 +00002707 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002708 ValueManager &ValMgr = Eng.getValueManager();
2709 SVal X = ValMgr.getConjuredSymbolVal(Ex, T, Count);
Ted Kremenek09102db2008-11-12 19:22:09 +00002710 state = state.BindExpr(Ex, X, false);
Ted Kremenek455dd862008-04-11 20:23:24 +00002711 }
2712
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002713 break;
Ted Kremenek8f90e712008-10-17 22:23:12 +00002714 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002715
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002716 case RetEffect::Alias: {
Ted Kremenek272aa852008-06-25 21:21:56 +00002717 unsigned idx = RE.getIndex();
Ted Kremenek2719e982008-06-17 02:43:46 +00002718 assert (arg_end >= arg_beg);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002719 assert (idx < (unsigned) (arg_end - arg_beg));
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002720 SVal V = state.GetSValAsScalarOrLoc(*(arg_beg+idx));
Ted Kremenek09102db2008-11-12 19:22:09 +00002721 state = state.BindExpr(Ex, V, false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002722 break;
2723 }
2724
Ted Kremenek227c5372008-05-06 02:41:27 +00002725 case RetEffect::ReceiverAlias: {
2726 assert (Receiver);
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002727 SVal V = state.GetSValAsScalarOrLoc(Receiver);
Ted Kremenek09102db2008-11-12 19:22:09 +00002728 state = state.BindExpr(Ex, V, false);
Ted Kremenek227c5372008-05-06 02:41:27 +00002729 break;
2730 }
2731
Ted Kremenek6a1cc252008-06-23 18:02:52 +00002732 case RetEffect::OwnedAllocatedSymbol:
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002733 case RetEffect::OwnedSymbol: {
2734 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke9e726e2009-04-09 16:13:17 +00002735 ValueManager &ValMgr = Eng.getValueManager();
2736 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
2737 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
2738 state = state.set<RefBindings>(Sym, RefVal::makeOwned(RE.getObjKind(),
2739 RetT));
2740 state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenek45c52a12009-03-09 22:46:49 +00002741
2742 // FIXME: Add a flag to the checker where allocations are assumed to
2743 // *not fail.
2744#if 0
Ted Kremeneke62fd052009-01-28 22:27:59 +00002745 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) {
2746 bool isFeasible;
2747 state = state.Assume(loc::SymbolVal(Sym), true, isFeasible);
2748 assert(isFeasible && "Cannot assume fresh symbol is non-null.");
2749 }
Ted Kremenek45c52a12009-03-09 22:46:49 +00002750#endif
Ted Kremenek6a1cc252008-06-23 18:02:52 +00002751
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002752 break;
2753 }
Ted Kremenek382fb4e2009-04-27 19:14:45 +00002754
2755 case RetEffect::GCNotOwnedSymbol:
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002756 case RetEffect::NotOwnedSymbol: {
2757 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke9e726e2009-04-09 16:13:17 +00002758 ValueManager &ValMgr = Eng.getValueManager();
2759 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
2760 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
2761 state = state.set<RefBindings>(Sym, RefVal::makeNotOwned(RE.getObjKind(),
2762 RetT));
2763 state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002764 break;
2765 }
2766 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002767
Ted Kremenek0dd65012009-02-18 02:00:25 +00002768 // Generate a sink node if we are at the end of a path.
2769 GRExprEngine::NodeTy *NewNode =
2770 IsEndPath(Summ) ? Builder.MakeSinkNode(Dst, Ex, Pred, state)
2771 : Builder.MakeNode(Dst, Ex, Pred, state);
2772
2773 // Annotate the edge with summary we used.
2774 // FIXME: This assumes that we always use the same summary when generating
2775 // this node.
2776 if (NewNode) SummaryLog[NewNode] = Summ;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002777}
2778
2779
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002780void CFRefCount::EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002781 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002782 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu097fc982008-10-17 05:57:07 +00002783 CallExpr* CE, SVal L,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002784 ExplodedNode<GRState>* Pred) {
Zhongxing Xucac107a2009-04-20 05:24:46 +00002785 const FunctionDecl* FD = L.getAsFunctionDecl();
2786 RetainSummary* Summ = !FD ? 0
2787 : Summaries.getSummary(const_cast<FunctionDecl*>(FD));
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002788
2789 EvalSummary(Dst, Eng, Builder, CE, 0, Summ,
2790 CE->arg_begin(), CE->arg_end(), Pred);
Ted Kremenek827f93b2008-03-06 00:08:09 +00002791}
Ted Kremeneka7338b42008-03-11 06:39:11 +00002792
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002793void CFRefCount::EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002794 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002795 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002796 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002797 ExplodedNode<GRState>* Pred) {
Ted Kremenek926abf22008-05-06 04:20:12 +00002798 RetainSummary* Summ;
Ted Kremenek33661802008-05-01 21:31:50 +00002799
Ted Kremenek272aa852008-06-25 21:21:56 +00002800 if (Expr* Receiver = ME->getReceiver()) {
2801 // We need the type-information of the tracked receiver object
2802 // Retrieve it from the state.
2803 ObjCInterfaceDecl* ID = 0;
2804
2805 // FIXME: Wouldn't it be great if this code could be reduced? It's just
2806 // a chain of lookups.
Ted Kremeneka821b792009-04-29 05:04:30 +00002807 // FIXME: Is this really working as expected? There are cases where
2808 // we just use the 'ID' from the message expression.
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002809 const GRState* St = Builder.GetState(Pred);
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002810 SVal V = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
Ted Kremenek272aa852008-06-25 21:21:56 +00002811
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002812 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenek74556a12009-03-26 03:35:11 +00002813 if (Sym) {
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002814 if (const RefVal* T = St->get<RefBindings>(Sym)) {
Ted Kremenek6064a362008-07-07 16:21:19 +00002815 QualType Ty = T->getType();
Ted Kremenek272aa852008-06-25 21:21:56 +00002816
2817 if (const PointerType* PT = Ty->getAsPointerType()) {
2818 QualType PointeeTy = PT->getPointeeType();
2819
2820 if (ObjCInterfaceType* IT = dyn_cast<ObjCInterfaceType>(PointeeTy))
2821 ID = IT->getDecl();
2822 }
2823 }
2824 }
2825
Ted Kremenek04e00302009-04-29 17:09:14 +00002826 // FIXME: The receiver could be a reference to a class, meaning that
2827 // we should use the class method.
2828 Summ = Summaries.getInstanceMethodSummary(ME, ID);
Ted Kremenek0106e202008-10-24 20:32:50 +00002829
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002830 // Special-case: are we sending a mesage to "self"?
2831 // This is a hack. When we have full-IP this should be removed.
2832 if (!Summ) {
2833 ObjCMethodDecl* MD =
2834 dyn_cast<ObjCMethodDecl>(&Eng.getGraph().getCodeDecl());
2835
2836 if (MD) {
2837 if (Expr* Receiver = ME->getReceiver()) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002838 SVal X = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002839 if (loc::MemRegionVal* L = dyn_cast<loc::MemRegionVal>(&X))
Ted Kremenek0106e202008-10-24 20:32:50 +00002840 if (L->getRegion() == Eng.getStateManager().getSelfRegion(St)) {
2841 // Create a summmary where all of the arguments "StopTracking".
2842 Summ = Summaries.getPersistentSummary(RetEffect::MakeNoRet(),
2843 DoNothing,
2844 StopTracking);
2845 }
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002846 }
2847 }
2848 }
Ted Kremenek272aa852008-06-25 21:21:56 +00002849 }
Ted Kremenek1feab292008-04-16 04:28:53 +00002850 else
Ted Kremenekb17fa952009-04-23 21:25:57 +00002851 Summ = Summaries.getClassMethodSummary(ME);
Ted Kremenek1feab292008-04-16 04:28:53 +00002852
Ted Kremenekccbe79a2009-04-24 17:50:11 +00002853
Ted Kremenek926abf22008-05-06 04:20:12 +00002854 EvalSummary(Dst, Eng, Builder, ME, ME->getReceiver(), Summ,
2855 ME->arg_begin(), ME->arg_end(), Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002856}
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002857
2858namespace {
2859class VISIBILITY_HIDDEN StopTrackingCallback : public SymbolVisitor {
2860 GRStateRef state;
2861public:
2862 StopTrackingCallback(GRStateRef st) : state(st) {}
2863 GRStateRef getState() { return state; }
2864
2865 bool VisitSymbol(SymbolRef sym) {
2866 state = state.remove<RefBindings>(sym);
2867 return true;
2868 }
Ted Kremenek926abf22008-05-06 04:20:12 +00002869
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002870 const GRState* getState() const { return state.getState(); }
2871};
2872} // end anonymous namespace
2873
2874
Ted Kremeneka42be302009-02-14 01:43:44 +00002875void CFRefCount::EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val) {
Ted Kremeneka42be302009-02-14 01:43:44 +00002876 // Are we storing to something that causes the value to "escape"?
Ted Kremenek7aef4842008-04-16 20:40:59 +00002877 bool escapes = false;
2878
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002879 // A value escapes in three possible cases (this may change):
2880 //
2881 // (1) we are binding to something that is not a memory region.
2882 // (2) we are binding to a memregion that does not have stack storage
2883 // (3) we are binding to a memregion with stack storage that the store
Ted Kremeneka42be302009-02-14 01:43:44 +00002884 // does not understand.
Ted Kremeneka42be302009-02-14 01:43:44 +00002885 GRStateRef state = B.getState();
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002886
Ted Kremeneka42be302009-02-14 01:43:44 +00002887 if (!isa<loc::MemRegionVal>(location))
Ted Kremenek7aef4842008-04-16 20:40:59 +00002888 escapes = true;
Ted Kremenekb15eba42008-10-04 05:50:14 +00002889 else {
Ted Kremeneka42be302009-02-14 01:43:44 +00002890 const MemRegion* R = cast<loc::MemRegionVal>(location).getRegion();
2891 escapes = !B.getStateManager().hasStackStorage(R);
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002892
2893 if (!escapes) {
2894 // To test (3), generate a new state with the binding removed. If it is
2895 // the same state, then it escapes (since the store cannot represent
2896 // the binding).
Ted Kremeneka42be302009-02-14 01:43:44 +00002897 escapes = (state == (state.BindLoc(cast<Loc>(location), UnknownVal())));
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002898 }
Ted Kremenekb15eba42008-10-04 05:50:14 +00002899 }
Ted Kremeneka42be302009-02-14 01:43:44 +00002900
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002901 // If our store can represent the binding and we aren't storing to something
2902 // that doesn't have local storage then just return and have the simulation
2903 // state continue as is.
2904 if (!escapes)
2905 return;
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002906
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002907 // Otherwise, find all symbols referenced by 'val' that we are tracking
2908 // and stop tracking them.
2909 B.MakeNode(state.scanReachableSymbols<StopTrackingCallback>(val).getState());
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002910}
2911
Ted Kremenek0106e202008-10-24 20:32:50 +00002912std::pair<GRStateRef,bool>
2913CFRefCount::HandleSymbolDeath(GRStateManager& VMgr,
2914 const GRState* St, const Decl* CD,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002915 SymbolRef sid,
Ted Kremenek0106e202008-10-24 20:32:50 +00002916 RefVal V, bool& hasLeak) {
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002917
Ted Kremenek47a72422009-04-29 18:50:19 +00002918 // Any remaining leaks?
Ted Kremenek311f3d42008-10-22 23:56:21 +00002919 hasLeak = V.isOwned() ||
2920 ((V.isNotOwned() || V.isReturnedOwned()) && V.getCount() > 0);
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002921
Ted Kremenek47a72422009-04-29 18:50:19 +00002922 GRStateRef state(St, VMgr);
2923
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002924 if (!hasLeak)
Ted Kremenek0106e202008-10-24 20:32:50 +00002925 return std::make_pair(state.remove<RefBindings>(sid), false);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002926
Ted Kremenek0106e202008-10-24 20:32:50 +00002927 return std::make_pair(state.set<RefBindings>(sid, V ^ RefVal::ErrorLeak),
2928 false);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002929}
2930
Ted Kremenek541db372008-04-24 23:57:27 +00002931
Ted Kremenekffefc352008-04-11 22:25:11 +00002932
Ted Kremenek541db372008-04-24 23:57:27 +00002933// Dead symbols.
2934
Ted Kremenek708af042009-02-05 06:50:21 +00002935
Ted Kremenek541db372008-04-24 23:57:27 +00002936
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002937 // Return statements.
2938
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002939void CFRefCount::EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002940 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002941 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002942 ReturnStmt* S,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002943 ExplodedNode<GRState>* Pred) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002944
2945 Expr* RetE = S->getRetValue();
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002946 if (!RetE)
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002947 return;
2948
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002949 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002950 SymbolRef Sym = state.GetSValAsScalarOrLoc(RetE).getAsLocSymbol();
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002951
Ted Kremenek74556a12009-03-26 03:35:11 +00002952 if (!Sym)
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002953 return;
2954
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002955 // Get the reference count binding (if any).
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002956 const RefVal* T = state.get<RefBindings>(Sym);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002957
2958 if (!T)
2959 return;
2960
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002961 // Change the reference count.
Ted Kremenek6064a362008-07-07 16:21:19 +00002962 RefVal X = *T;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002963
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002964 switch (X.getKind()) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002965 case RefVal::Owned: {
2966 unsigned cnt = X.getCount();
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00002967 assert (cnt > 0);
2968 X = RefVal::makeReturnedOwned(cnt - 1);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002969 break;
2970 }
2971
2972 case RefVal::NotOwned: {
2973 unsigned cnt = X.getCount();
2974 X = cnt ? RefVal::makeReturnedOwned(cnt - 1)
2975 : RefVal::makeReturnedNotOwned();
2976 break;
2977 }
2978
2979 default:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002980 return;
2981 }
2982
2983 // Update the binding.
Ted Kremenek91781202008-08-17 03:20:02 +00002984 state = state.set<RefBindings>(Sym, X);
Ted Kremenek47a72422009-04-29 18:50:19 +00002985 Pred = Builder.MakeNode(Dst, S, Pred, state);
2986
Ted Kremeneka208d0c2009-04-30 05:51:50 +00002987 // Did we cache out?
2988 if (!Pred)
2989 return;
2990
Ted Kremenek47a72422009-04-29 18:50:19 +00002991 // Any leaks or other errors?
2992 if (X.isReturnedOwned() && X.getCount() == 0) {
2993 const Decl *CD = &Eng.getStateManager().getCodeDecl();
2994
Ted Kremenek314b1952009-04-29 23:03:22 +00002995 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
2996 RetainSummary *Summ = Summaries.getMethodSummary(MD);
2997 if (!GetRetEffect(Summ).isOwned()) {
Ted Kremenek47a72422009-04-29 18:50:19 +00002998 static int ReturnOwnLeakTag = 0;
2999 state = state.set<RefBindings>(Sym, X ^ RefVal::ErrorLeakReturned);
Ted Kremenek47a72422009-04-29 18:50:19 +00003000 // Generate an error node.
Ted Kremeneka208d0c2009-04-30 05:51:50 +00003001 if (ExplodedNode<GRState> *N =
3002 Builder.generateNode(PostStmt(S, &ReturnOwnLeakTag), state, Pred)) {
3003 CFRefLeakReport *report =
3004 new CFRefLeakReport(*static_cast<CFRefBug*>(leakAtReturn), *this,
3005 N, Sym, Eng);
3006 BR->EmitReport(report);
3007 }
Ted Kremenek47a72422009-04-29 18:50:19 +00003008 }
3009 }
3010 }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003011}
3012
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003013// Assumptions.
3014
Ted Kremenekabd89ac2008-08-13 04:27:00 +00003015const GRState* CFRefCount::EvalAssume(GRStateManager& VMgr,
3016 const GRState* St,
Zhongxing Xu097fc982008-10-17 05:57:07 +00003017 SVal Cond, bool Assumption,
Ted Kremenekf22f8682008-07-10 22:03:41 +00003018 bool& isFeasible) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003019
3020 // FIXME: We may add to the interface of EvalAssume the list of symbols
3021 // whose assumptions have changed. For now we just iterate through the
3022 // bindings and check if any of the tracked symbols are NULL. This isn't
3023 // too bad since the number of symbols we will track in practice are
3024 // probably small and EvalAssume is only called at branches and a few
3025 // other places.
Ted Kremenek4ae925c2008-08-14 21:16:54 +00003026 RefBindings B = St->get<RefBindings>();
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003027
3028 if (B.isEmpty())
3029 return St;
3030
3031 bool changed = false;
Ted Kremenek91781202008-08-17 03:20:02 +00003032
3033 GRStateRef state(St, VMgr);
3034 RefBindings::Factory& RefBFactory = state.get_context<RefBindings>();
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003035
3036 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003037 // Check if the symbol is null (or equal to any constant).
3038 // If this is the case, stop tracking the symbol.
Zhongxing Xuc6b27d02008-08-29 14:52:36 +00003039 if (VMgr.getSymVal(St, I.getKey())) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003040 changed = true;
3041 B = RefBFactory.Remove(B, I.getKey());
3042 }
3043 }
3044
Ted Kremenek91781202008-08-17 03:20:02 +00003045 if (changed)
3046 state = state.set<RefBindings>(B);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003047
Ted Kremenek4ae925c2008-08-14 21:16:54 +00003048 return state;
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003049}
Ted Kremeneka7338b42008-03-11 06:39:11 +00003050
Ted Kremenekb6578942009-02-24 19:15:11 +00003051GRStateRef CFRefCount::Update(GRStateRef state, SymbolRef sym,
3052 RefVal V, ArgEffect E,
3053 RefVal::Kind& hasErr) {
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003054
3055 // In GC mode [... release] and [... retain] do nothing.
3056 switch (E) {
3057 default: break;
3058 case IncRefMsg: E = isGCEnabled() ? DoNothing : IncRef; break;
3059 case DecRefMsg: E = isGCEnabled() ? DoNothing : DecRef; break;
Ted Kremenek2126bef2009-02-18 21:57:45 +00003060 case MakeCollectable: E = isGCEnabled() ? DecRef : DoNothing; break;
Ted Kremenekaac82832009-02-23 17:45:03 +00003061 case NewAutoreleasePool: E = isGCEnabled() ? DoNothing :
3062 NewAutoreleasePool; break;
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003063 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00003064
Ted Kremenek6537a642009-03-17 19:42:23 +00003065 // Handle all use-after-releases.
3066 if (!isGCEnabled() && V.getKind() == RefVal::Released) {
3067 V = V ^ RefVal::ErrorUseAfterRelease;
3068 hasErr = V.getKind();
3069 return state.set<RefBindings>(sym, V);
3070 }
3071
Ted Kremenek0d721572008-03-11 17:48:22 +00003072 switch (E) {
3073 default:
3074 assert (false && "Unhandled CFRef transition.");
Ted Kremenek6537a642009-03-17 19:42:23 +00003075
3076 case Dealloc:
3077 // Any use of -dealloc in GC is *bad*.
3078 if (isGCEnabled()) {
3079 V = V ^ RefVal::ErrorDeallocGC;
3080 hasErr = V.getKind();
3081 break;
3082 }
3083
3084 switch (V.getKind()) {
3085 default:
3086 assert(false && "Invalid case.");
3087 case RefVal::Owned:
3088 // The object immediately transitions to the released state.
3089 V = V ^ RefVal::Released;
3090 V.clearCounts();
3091 return state.set<RefBindings>(sym, V);
3092 case RefVal::NotOwned:
3093 V = V ^ RefVal::ErrorDeallocNotOwned;
3094 hasErr = V.getKind();
3095 break;
3096 }
3097 break;
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003098
Ted Kremenekb7826ab2009-02-25 23:11:49 +00003099 case NewAutoreleasePool:
3100 assert(!isGCEnabled());
3101 return state.add<AutoreleaseStack>(sym);
3102
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003103 case MayEscape:
3104 if (V.getKind() == RefVal::Owned) {
Ted Kremenek272aa852008-06-25 21:21:56 +00003105 V = V ^ RefVal::NotOwned;
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003106 break;
3107 }
Ted Kremenek6537a642009-03-17 19:42:23 +00003108
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003109 // Fall-through.
Ted Kremenek1b4b6562009-02-25 02:54:57 +00003110
Ted Kremenekede40b72008-07-09 18:11:16 +00003111 case DoNothingByRef:
Ted Kremenek0d721572008-03-11 17:48:22 +00003112 case DoNothing:
Ted Kremenekb6578942009-02-24 19:15:11 +00003113 return state;
Ted Kremeneke5a4bb02008-06-30 16:57:41 +00003114
Ted Kremenek9b112d22009-01-28 21:44:40 +00003115 case Autorelease:
Ted Kremenek6537a642009-03-17 19:42:23 +00003116 if (isGCEnabled())
3117 return state;
Ted Kremenek681fb352009-03-20 17:34:15 +00003118
3119 // Update the autorelease counts.
3120 state = SendAutorelease(state, ARCountFactory, sym);
Ted Kremenek6537a642009-03-17 19:42:23 +00003121
3122 // Fall-through.
3123
Ted Kremenek227c5372008-05-06 02:41:27 +00003124 case StopTracking:
Ted Kremenekb6578942009-02-24 19:15:11 +00003125 return state.remove<RefBindings>(sym);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003126
Ted Kremenek0d721572008-03-11 17:48:22 +00003127 case IncRef:
3128 switch (V.getKind()) {
3129 default:
3130 assert(false);
3131
3132 case RefVal::Owned:
Ted Kremenek0d721572008-03-11 17:48:22 +00003133 case RefVal::NotOwned:
Ted Kremenek272aa852008-06-25 21:21:56 +00003134 V = V + 1;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003135 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003136 case RefVal::Released:
Ted Kremenek6537a642009-03-17 19:42:23 +00003137 // Non-GC cases are handled above.
3138 assert(isGCEnabled());
3139 V = (V ^ RefVal::Owned) + 1;
Ted Kremenek0d721572008-03-11 17:48:22 +00003140 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003141 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00003142 break;
3143
Ted Kremenek272aa852008-06-25 21:21:56 +00003144 case SelfOwn:
3145 V = V ^ RefVal::NotOwned;
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003146 // Fall-through.
Ted Kremenek0d721572008-03-11 17:48:22 +00003147 case DecRef:
3148 switch (V.getKind()) {
3149 default:
Ted Kremenek6537a642009-03-17 19:42:23 +00003150 // case 'RefVal::Released' handled above.
Ted Kremenek0d721572008-03-11 17:48:22 +00003151 assert (false);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003152
Ted Kremenek272aa852008-06-25 21:21:56 +00003153 case RefVal::Owned:
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00003154 assert(V.getCount() > 0);
3155 if (V.getCount() == 1) V = V ^ RefVal::Released;
3156 V = V - 1;
Ted Kremenek0d721572008-03-11 17:48:22 +00003157 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003158
Ted Kremenek272aa852008-06-25 21:21:56 +00003159 case RefVal::NotOwned:
3160 if (V.getCount() > 0)
3161 V = V - 1;
Ted Kremenekc4f81022008-04-10 23:09:18 +00003162 else {
Ted Kremenek272aa852008-06-25 21:21:56 +00003163 V = V ^ RefVal::ErrorReleaseNotOwned;
Ted Kremenek1feab292008-04-16 04:28:53 +00003164 hasErr = V.getKind();
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003165 }
Ted Kremenek0d721572008-03-11 17:48:22 +00003166 break;
Ted Kremenek6537a642009-03-17 19:42:23 +00003167
Ted Kremenek0d721572008-03-11 17:48:22 +00003168 case RefVal::Released:
Ted Kremenek6537a642009-03-17 19:42:23 +00003169 // Non-GC cases are handled above.
3170 assert(isGCEnabled());
Ted Kremenek272aa852008-06-25 21:21:56 +00003171 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek1feab292008-04-16 04:28:53 +00003172 hasErr = V.getKind();
Ted Kremenek6537a642009-03-17 19:42:23 +00003173 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003174 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00003175 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003176 }
Ted Kremenekb6578942009-02-24 19:15:11 +00003177 return state.set<RefBindings>(sym, V);
Ted Kremeneka7338b42008-03-11 06:39:11 +00003178}
3179
Ted Kremenek10fe66d2008-04-09 01:10:13 +00003180//===----------------------------------------------------------------------===//
Ted Kremenek708af042009-02-05 06:50:21 +00003181// Handle dead symbols and end-of-path.
3182//===----------------------------------------------------------------------===//
3183
3184void CFRefCount::EvalEndPath(GRExprEngine& Eng,
3185 GREndPathNodeBuilder<GRState>& Builder) {
3186
3187 const GRState* St = Builder.getState();
3188 RefBindings B = St->get<RefBindings>();
3189
3190 llvm::SmallVector<std::pair<SymbolRef, bool>, 10> Leaked;
3191 const Decl* CodeDecl = &Eng.getGraph().getCodeDecl();
3192
3193 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
3194 bool hasLeak = false;
3195
3196 std::pair<GRStateRef, bool> X =
Ted Kremenek9577c1e2009-03-03 22:06:47 +00003197 HandleSymbolDeath(Eng.getStateManager(), St, CodeDecl,
3198 (*I).first, (*I).second, hasLeak);
Ted Kremenek708af042009-02-05 06:50:21 +00003199
3200 St = X.first;
3201 if (hasLeak) Leaked.push_back(std::make_pair((*I).first, X.second));
3202 }
3203
3204 if (Leaked.empty())
3205 return;
3206
3207 ExplodedNode<GRState>* N = Builder.MakeNode(St);
3208
3209 if (!N)
3210 return;
3211
3212 for (llvm::SmallVector<std::pair<SymbolRef,bool>, 10>::iterator
3213 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3214
3215 CFRefBug *BT = static_cast<CFRefBug*>(I->second ? leakAtReturn
3216 : leakWithinFunction);
3217 assert(BT && "BugType not initialized.");
Ted Kremenekc034f712009-04-07 05:07:44 +00003218 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N, I->first, Eng);
Ted Kremenek708af042009-02-05 06:50:21 +00003219 BR->EmitReport(report);
3220 }
3221}
3222
3223void CFRefCount::EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
3224 GRExprEngine& Eng,
3225 GRStmtNodeBuilder<GRState>& Builder,
3226 ExplodedNode<GRState>* Pred,
3227 Stmt* S,
3228 const GRState* St,
3229 SymbolReaper& SymReaper) {
3230
Ted Kremenek876d8df2009-02-19 23:47:02 +00003231 // FIXME: a lot of copy-and-paste from EvalEndPath. Refactor.
Ted Kremenek708af042009-02-05 06:50:21 +00003232 RefBindings B = St->get<RefBindings>();
3233 llvm::SmallVector<std::pair<SymbolRef,bool>, 10> Leaked;
3234
3235 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3236 E = SymReaper.dead_end(); I != E; ++I) {
3237
3238 const RefVal* T = B.lookup(*I);
3239 if (!T) continue;
3240
3241 bool hasLeak = false;
3242
3243 std::pair<GRStateRef, bool> X
Ted Kremenek876d8df2009-02-19 23:47:02 +00003244 = HandleSymbolDeath(Eng.getStateManager(), St, 0, *I, *T, hasLeak);
Ted Kremenek708af042009-02-05 06:50:21 +00003245
3246 St = X.first;
3247
3248 if (hasLeak)
3249 Leaked.push_back(std::make_pair(*I,X.second));
3250 }
3251
Ted Kremenek876d8df2009-02-19 23:47:02 +00003252 if (!Leaked.empty()) {
3253 // Create a new intermediate node representing the leak point. We
3254 // use a special program point that represents this checker-specific
3255 // transition. We use the address of RefBIndex as a unique tag for this
3256 // checker. We will create another node (if we don't cache out) that
3257 // removes the retain-count bindings from the state.
3258 // NOTE: We use 'generateNode' so that it does interplay with the
3259 // auto-transition logic.
3260 ExplodedNode<GRState>* N =
3261 Builder.generateNode(PostStmtCustom(S, &LeakProgramPointTag), St, Pred);
Ted Kremenek708af042009-02-05 06:50:21 +00003262
Ted Kremenek876d8df2009-02-19 23:47:02 +00003263 if (!N)
3264 return;
3265
3266 // Generate the bug reports.
3267 for (llvm::SmallVectorImpl<std::pair<SymbolRef,bool> >::iterator
3268 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3269
3270 CFRefBug *BT = static_cast<CFRefBug*>(I->second ? leakAtReturn
3271 : leakWithinFunction);
3272 assert(BT && "BugType not initialized.");
Ted Kremenek56c70aa2009-02-23 16:54:00 +00003273 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N,
3274 I->first, Eng);
Ted Kremenek876d8df2009-02-19 23:47:02 +00003275 BR->EmitReport(report);
3276 }
Ted Kremenek708af042009-02-05 06:50:21 +00003277
Ted Kremenek876d8df2009-02-19 23:47:02 +00003278 Pred = N;
Ted Kremenek708af042009-02-05 06:50:21 +00003279 }
Ted Kremenek876d8df2009-02-19 23:47:02 +00003280
3281 // Now generate a new node that nukes the old bindings.
3282 GRStateRef state(St, Eng.getStateManager());
3283 RefBindings::Factory& F = state.get_context<RefBindings>();
3284
3285 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3286 E = SymReaper.dead_end(); I!=E; ++I)
3287 B = F.Remove(B, *I);
3288
3289 state = state.set<RefBindings>(B);
3290 Builder.MakeNode(Dst, S, Pred, state);
Ted Kremenek708af042009-02-05 06:50:21 +00003291}
3292
3293void CFRefCount::ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
3294 GRStmtNodeBuilder<GRState>& Builder,
3295 Expr* NodeExpr, Expr* ErrorExpr,
3296 ExplodedNode<GRState>* Pred,
3297 const GRState* St,
3298 RefVal::Kind hasErr, SymbolRef Sym) {
3299 Builder.BuildSinks = true;
3300 GRExprEngine::NodeTy* N = Builder.MakeNode(Dst, NodeExpr, Pred, St);
3301
3302 if (!N) return;
3303
3304 CFRefBug *BT = 0;
3305
Ted Kremenek6537a642009-03-17 19:42:23 +00003306 switch (hasErr) {
3307 default:
3308 assert(false && "Unhandled error.");
3309 return;
3310 case RefVal::ErrorUseAfterRelease:
3311 BT = static_cast<CFRefBug*>(useAfterRelease);
3312 break;
3313 case RefVal::ErrorReleaseNotOwned:
3314 BT = static_cast<CFRefBug*>(releaseNotOwned);
3315 break;
3316 case RefVal::ErrorDeallocGC:
3317 BT = static_cast<CFRefBug*>(deallocGC);
3318 break;
3319 case RefVal::ErrorDeallocNotOwned:
3320 BT = static_cast<CFRefBug*>(deallocNotOwned);
3321 break;
Ted Kremenek708af042009-02-05 06:50:21 +00003322 }
3323
Ted Kremenekc26c4692009-02-18 03:48:14 +00003324 CFRefReport *report = new CFRefReport(*BT, *this, N, Sym);
Ted Kremenek708af042009-02-05 06:50:21 +00003325 report->addRange(ErrorExpr->getSourceRange());
3326 BR->EmitReport(report);
3327}
3328
3329//===----------------------------------------------------------------------===//
Ted Kremenekb1983ba2008-04-10 22:16:52 +00003330// Transfer function creation for external clients.
Ted Kremeneka7338b42008-03-11 06:39:11 +00003331//===----------------------------------------------------------------------===//
3332
Ted Kremenekfe30beb2008-04-30 23:47:44 +00003333GRTransferFuncs* clang::MakeCFRefCountTF(ASTContext& Ctx, bool GCEnabled,
3334 const LangOptions& lopts) {
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00003335 return new CFRefCount(Ctx, GCEnabled, lopts);
Ted Kremeneka4c74292008-04-10 22:58:08 +00003336}