blob: 6f9cbbba3130018f1cd68cc58f291c28d635dd71 [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::DenseMap<FunctionDecl*, RetainSummary*>
534 FuncSummariesTy;
535
Ted Kremenek84f010c2008-06-23 23:30:29 +0000536 typedef ObjCSummaryCache ObjCMethodSummariesTy;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000537
538 //==-----------------------------------------------------------------==//
539 // Data.
540 //==-----------------------------------------------------------------==//
541
Ted Kremenek272aa852008-06-25 21:21:56 +0000542 /// Ctx - The ASTContext object for the analyzed ASTs.
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000543 ASTContext& Ctx;
Ted Kremeneke44927e2008-07-01 17:21:27 +0000544
Ted Kremenekede40b72008-07-09 18:11:16 +0000545 /// CFDictionaryCreateII - An IdentifierInfo* representing the indentifier
546 /// "CFDictionaryCreate".
547 IdentifierInfo* CFDictionaryCreateII;
548
Ted Kremenek272aa852008-06-25 21:21:56 +0000549 /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000550 const bool GCEnabled;
Ted Kremenekee649082009-05-04 04:30:18 +0000551
Ted Kremenek272aa852008-06-25 21:21:56 +0000552 /// FuncSummaries - A map from FunctionDecls to summaries.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000553 FuncSummariesTy FuncSummaries;
554
Ted Kremenek272aa852008-06-25 21:21:56 +0000555 /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
556 /// to summaries.
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000557 ObjCMethodSummariesTy ObjCClassMethodSummaries;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000558
Ted Kremenek272aa852008-06-25 21:21:56 +0000559 /// ObjCMethodSummaries - A map from selectors to summaries.
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000560 ObjCMethodSummariesTy ObjCMethodSummaries;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000561
Ted Kremenek272aa852008-06-25 21:21:56 +0000562 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
563 /// and all other data used by the checker.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000564 llvm::BumpPtrAllocator BPAlloc;
565
Ted Kremeneka56ae162009-05-03 05:20:50 +0000566 /// AF - A factory for ArgEffects objects.
567 ArgEffects::Factory AF;
568
Ted Kremenek272aa852008-06-25 21:21:56 +0000569 /// ScratchArgs - A holding buffer for construct ArgEffects.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000570 ArgEffects ScratchArgs;
571
Ted Kremenek286e9852009-05-04 04:57:00 +0000572 RetainSummary DefaultSummary;
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000573 RetainSummary* StopSummary;
574
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000575 //==-----------------------------------------------------------------==//
576 // Methods.
577 //==-----------------------------------------------------------------==//
578
Ted Kremenek272aa852008-06-25 21:21:56 +0000579 /// getArgEffects - Returns a persistent ArgEffects object based on the
580 /// data in ScratchArgs.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000581 ArgEffects getArgEffects();
Ted Kremeneka7338b42008-03-11 06:39:11 +0000582
Ted Kremenek562c1302008-05-05 16:51:50 +0000583 enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000584
585public:
Ted Kremenek286e9852009-05-04 04:57:00 +0000586 RetainSummary *getDefaultSummary() { return &DefaultSummary; }
587
Ted Kremenek064ef322009-02-23 16:51:39 +0000588 RetainSummary* getUnarySummary(const FunctionType* FT, UnaryFuncKind func);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000589
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000590 RetainSummary* getCFSummaryCreateRule(FunctionDecl* FD);
591 RetainSummary* getCFSummaryGetRule(FunctionDecl* FD);
Ted Kremenek17144e82009-01-12 21:45:02 +0000592 RetainSummary* getCFCreateGetRuleSummary(FunctionDecl* FD, const char* FName);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000593
Ted Kremeneka56ae162009-05-03 05:20:50 +0000594 RetainSummary* getPersistentSummary(ArgEffects AE, RetEffect RetEff,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000595 ArgEffect ReceiverEff = DoNothing,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000596 ArgEffect DefaultEff = MayEscape,
597 bool isEndPath = false);
Ted Kremenek45d0b502008-10-29 04:07:07 +0000598
Ted Kremenek266d8b62008-05-06 02:26:56 +0000599 RetainSummary* getPersistentSummary(RetEffect RE,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000600 ArgEffect ReceiverEff = DoNothing,
Ted Kremeneka3f30dd2008-05-22 17:31:13 +0000601 ArgEffect DefaultEff = MayEscape) {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000602 return getPersistentSummary(getArgEffects(), RE, ReceiverEff, DefaultEff);
Ted Kremenek0e344d42008-05-06 00:30:21 +0000603 }
Ted Kremenek42ea0322008-05-05 23:55:01 +0000604
Ted Kremeneka821b792009-04-29 05:04:30 +0000605 RetainSummary *getPersistentStopSummary() {
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000606 if (StopSummary)
607 return StopSummary;
608
609 StopSummary = getPersistentSummary(RetEffect::MakeNoRet(),
610 StopTracking, StopTracking);
Ted Kremenek45d0b502008-10-29 04:07:07 +0000611
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000612 return StopSummary;
Ted Kremenekbcaff792008-05-06 15:44:25 +0000613 }
Ted Kremenek926abf22008-05-06 04:20:12 +0000614
Ted Kremeneka821b792009-04-29 05:04:30 +0000615 RetainSummary *getInitMethodSummary(QualType RetTy);
Ted Kremenek42ea0322008-05-05 23:55:01 +0000616
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000617 void InitializeClassMethodSummaries();
618 void InitializeMethodSummaries();
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000619
Ted Kremenek9b42e062009-05-03 04:42:10 +0000620 bool isTrackedObjCObjectType(QualType T);
Ted Kremeneka9cdbc32009-05-03 06:08:32 +0000621 bool isTrackedCFObjectType(QualType T);
Ted Kremenek35920ed2009-01-07 00:39:56 +0000622
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000623private:
624
Ted Kremenekf2717b02008-07-18 17:24:20 +0000625 void addClsMethSummary(IdentifierInfo* ClsII, Selector S,
626 RetainSummary* Summ) {
627 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
628 }
629
Ted Kremenek272aa852008-06-25 21:21:56 +0000630 void addNSObjectClsMethSummary(Selector S, RetainSummary *Summ) {
631 ObjCClassMethodSummaries[S] = Summ;
632 }
633
634 void addNSObjectMethSummary(Selector S, RetainSummary *Summ) {
635 ObjCMethodSummaries[S] = Summ;
636 }
Ted Kremenekfbf2dc52009-03-04 23:30:42 +0000637
638 void addClassMethSummary(const char* Cls, const char* nullaryName,
639 RetainSummary *Summ) {
640 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
641 Selector S = GetNullarySelector(nullaryName, Ctx);
642 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
643 }
Ted Kremenek272aa852008-06-25 21:21:56 +0000644
Ted Kremenek1b4b6562009-02-25 02:54:57 +0000645 void addInstMethSummary(const char* Cls, const char* nullaryName,
646 RetainSummary *Summ) {
647 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
648 Selector S = GetNullarySelector(nullaryName, Ctx);
649 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
650 }
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000651
652 Selector generateSelector(va_list argp) {
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000653 llvm::SmallVector<IdentifierInfo*, 10> II;
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000654
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000655 while (const char* s = va_arg(argp, const char*))
656 II.push_back(&Ctx.Idents.get(s));
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000657
658 return Ctx.Selectors.getSelector(II.size(), &II[0]);
659 }
660
661 void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy& Summaries,
662 RetainSummary* Summ, va_list argp) {
663 Selector S = generateSelector(argp);
664 Summaries[ObjCSummaryKey(ClsII, S)] = Summ;
Ted Kremenekf2717b02008-07-18 17:24:20 +0000665 }
Ted Kremenek45642a42008-08-12 18:48:50 +0000666
667 void addInstMethSummary(const char* Cls, RetainSummary* Summ, ...) {
668 va_list argp;
669 va_start(argp, Summ);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000670 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Ted Kremenek45642a42008-08-12 18:48:50 +0000671 va_end(argp);
672 }
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000673
674 void addClsMethSummary(const char* Cls, RetainSummary* Summ, ...) {
675 va_list argp;
676 va_start(argp, Summ);
677 addMethodSummary(&Ctx.Idents.get(Cls),ObjCClassMethodSummaries, Summ, argp);
678 va_end(argp);
679 }
680
681 void addClsMethSummary(IdentifierInfo *II, RetainSummary* Summ, ...) {
682 va_list argp;
683 va_start(argp, Summ);
684 addMethodSummary(II, ObjCClassMethodSummaries, Summ, argp);
685 va_end(argp);
686 }
687
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000688 void addPanicSummary(const char* Cls, ...) {
Ted Kremeneka56ae162009-05-03 05:20:50 +0000689 RetainSummary* Summ = getPersistentSummary(AF.GetEmptyMap(),
690 RetEffect::MakeNoRet(),
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000691 DoNothing, DoNothing, true);
692 va_list argp;
693 va_start (argp, Cls);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000694 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000695 va_end(argp);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000696 }
Ted Kremenekf2717b02008-07-18 17:24:20 +0000697
Ted Kremeneka7338b42008-03-11 06:39:11 +0000698public:
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000699
700 RetainSummaryManager(ASTContext& ctx, bool gcenabled)
Ted Kremeneke44927e2008-07-01 17:21:27 +0000701 : Ctx(ctx),
Ted Kremenekede40b72008-07-09 18:11:16 +0000702 CFDictionaryCreateII(&ctx.Idents.get("CFDictionaryCreate")),
Ted Kremeneka56ae162009-05-03 05:20:50 +0000703 GCEnabled(gcenabled), AF(BPAlloc), ScratchArgs(AF.GetEmptyMap()),
Ted Kremenek286e9852009-05-04 04:57:00 +0000704 DefaultSummary(AF.GetEmptyMap() /* per-argument effects (none) */,
705 RetEffect::MakeNoRet() /* return effect */,
706 DoNothing /* receiver effect */,
707 MayEscape /* default argument effect */),
Ted Kremeneka56ae162009-05-03 05:20:50 +0000708 StopSummary(0) {
Ted Kremenek272aa852008-06-25 21:21:56 +0000709
710 InitializeClassMethodSummaries();
711 InitializeMethodSummaries();
712 }
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000713
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000714 ~RetainSummaryManager();
Ted Kremeneka7338b42008-03-11 06:39:11 +0000715
Ted Kremenekd13c1872008-06-24 03:56:45 +0000716 RetainSummary* getSummary(FunctionDecl* FD);
Ted Kremeneka821b792009-04-29 05:04:30 +0000717
Ted Kremenek314b1952009-04-29 23:03:22 +0000718 RetainSummary* getInstanceMethodSummary(ObjCMessageExpr* ME,
719 const ObjCInterfaceDecl* ID) {
Ted Kremenek04e00302009-04-29 17:09:14 +0000720 return getInstanceMethodSummary(ME->getSelector(), ME->getClassName(),
Ted Kremeneka821b792009-04-29 05:04:30 +0000721 ID, ME->getMethodDecl(), ME->getType());
722 }
723
Ted Kremenek04e00302009-04-29 17:09:14 +0000724 RetainSummary* getInstanceMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +0000725 const ObjCInterfaceDecl* ID,
726 const ObjCMethodDecl *MD,
727 QualType RetTy);
Ted Kremenek578498a2009-04-29 00:42:39 +0000728
729 RetainSummary *getClassMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +0000730 const ObjCInterfaceDecl *ID,
731 const ObjCMethodDecl *MD,
732 QualType RetTy);
Ted Kremenek578498a2009-04-29 00:42:39 +0000733
734 RetainSummary *getClassMethodSummary(ObjCMessageExpr *ME) {
735 return getClassMethodSummary(ME->getSelector(), ME->getClassName(),
736 ME->getClassInfo().first,
737 ME->getMethodDecl(), ME->getType());
738 }
Ted Kremenek91b89a42009-04-29 17:17:48 +0000739
740 /// getMethodSummary - This version of getMethodSummary is used to query
741 /// the summary for the current method being analyzed.
Ted Kremenek314b1952009-04-29 23:03:22 +0000742 RetainSummary *getMethodSummary(const ObjCMethodDecl *MD) {
743 // FIXME: Eventually this should be unneeded.
Ted Kremenek314b1952009-04-29 23:03:22 +0000744 const ObjCInterfaceDecl *ID = MD->getClassInterface();
Ted Kremenek1447cc92009-04-30 05:41:14 +0000745 Selector S = MD->getSelector();
Ted Kremenek91b89a42009-04-29 17:17:48 +0000746 IdentifierInfo *ClsName = ID->getIdentifier();
747 QualType ResultTy = MD->getResultType();
748
Ted Kremenek81eb4642009-04-30 05:47:23 +0000749 // Resolve the method decl last.
750 if (const ObjCMethodDecl *InterfaceMD =
751 ResolveToInterfaceMethodDecl(MD, Ctx))
752 MD = InterfaceMD;
Ted Kremenek1447cc92009-04-30 05:41:14 +0000753
Ted Kremenek91b89a42009-04-29 17:17:48 +0000754 if (MD->isInstanceMethod())
755 return getInstanceMethodSummary(S, ClsName, ID, MD, ResultTy);
756 else
757 return getClassMethodSummary(S, ClsName, ID, MD, ResultTy);
758 }
Ted Kremenek578498a2009-04-29 00:42:39 +0000759
Ted Kremenek314b1952009-04-29 23:03:22 +0000760 RetainSummary* getCommonMethodSummary(const ObjCMethodDecl* MD,
761 Selector S, QualType RetTy);
762
763 RetainSummary* getMethodSummaryFromAnnotations(const ObjCMethodDecl *MD);
Ted Kremenek926abf22008-05-06 04:20:12 +0000764
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000765 bool isGCEnabled() const { return GCEnabled; }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000766};
767
768} // end anonymous namespace
769
770//===----------------------------------------------------------------------===//
771// Implementation of checker data structures.
772//===----------------------------------------------------------------------===//
773
Ted Kremeneka56ae162009-05-03 05:20:50 +0000774RetainSummaryManager::~RetainSummaryManager() {}
Ted Kremeneka7338b42008-03-11 06:39:11 +0000775
Ted Kremeneka56ae162009-05-03 05:20:50 +0000776ArgEffects RetainSummaryManager::getArgEffects() {
777 ArgEffects AE = ScratchArgs;
778 ScratchArgs = AF.GetEmptyMap();
779 return AE;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000780}
781
Ted Kremenek266d8b62008-05-06 02:26:56 +0000782RetainSummary*
Ted Kremeneka56ae162009-05-03 05:20:50 +0000783RetainSummaryManager::getPersistentSummary(ArgEffects AE, RetEffect RetEff,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000784 ArgEffect ReceiverEff,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000785 ArgEffect DefaultEff,
Ted Kremenekee649082009-05-04 04:30:18 +0000786 bool isEndPath) {
Ted Kremenekae855d42008-04-24 17:22:33 +0000787 // Create the summary and return it.
Ted Kremenekee649082009-05-04 04:30:18 +0000788 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
Ted Kremenekf2717b02008-07-18 17:24:20 +0000789 new (Summ) RetainSummary(AE, RetEff, DefaultEff, ReceiverEff, isEndPath);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000790 return Summ;
791}
792
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000793//===----------------------------------------------------------------------===//
Ted Kremenek35920ed2009-01-07 00:39:56 +0000794// Predicates.
795//===----------------------------------------------------------------------===//
796
Ted Kremenek9b42e062009-05-03 04:42:10 +0000797bool RetainSummaryManager::isTrackedObjCObjectType(QualType Ty) {
Ted Kremenek0d813552009-04-23 22:11:07 +0000798 if (!Ctx.isObjCObjectPointerType(Ty))
Ted Kremenek35920ed2009-01-07 00:39:56 +0000799 return false;
800
Ted Kremenek0d813552009-04-23 22:11:07 +0000801 // We assume that id<..>, id, and "Class" all represent tracked objects.
802 const PointerType *PT = Ty->getAsPointerType();
803 if (PT == 0)
804 return true;
805
806 const ObjCInterfaceType *OT = PT->getPointeeType()->getAsObjCInterfaceType();
Ted Kremenek35920ed2009-01-07 00:39:56 +0000807
808 // We assume that id<..>, id, and "Class" all represent tracked objects.
809 if (!OT)
810 return true;
Ted Kremenek0d813552009-04-23 22:11:07 +0000811
812 // Does the interface subclass NSObject?
Ted Kremenek35920ed2009-01-07 00:39:56 +0000813 // FIXME: We can memoize here if this gets too expensive.
814 IdentifierInfo* NSObjectII = &Ctx.Idents.get("NSObject");
815 ObjCInterfaceDecl* ID = OT->getDecl();
816
817 for ( ; ID ; ID = ID->getSuperClass())
818 if (ID->getIdentifier() == NSObjectII)
819 return true;
820
821 return false;
822}
823
Ted Kremeneka9cdbc32009-05-03 06:08:32 +0000824bool RetainSummaryManager::isTrackedCFObjectType(QualType T) {
825 return isRefType(T, "CF") || // Core Foundation.
826 isRefType(T, "CG") || // Core Graphics.
827 isRefType(T, "DADisk") || // Disk Arbitration API.
828 isRefType(T, "DADissenter") ||
829 isRefType(T, "DASessionRef");
830}
831
Ted Kremenek35920ed2009-01-07 00:39:56 +0000832//===----------------------------------------------------------------------===//
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000833// Summary creation for functions (largely uses of Core Foundation).
834//===----------------------------------------------------------------------===//
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000835
Ted Kremenek17144e82009-01-12 21:45:02 +0000836static bool isRetain(FunctionDecl* FD, const char* FName) {
837 const char* loc = strstr(FName, "Retain");
838 return loc && loc[sizeof("Retain")-1] == '\0';
839}
840
841static bool isRelease(FunctionDecl* FD, const char* FName) {
842 const char* loc = strstr(FName, "Release");
843 return loc && loc[sizeof("Release")-1] == '\0';
844}
845
Ted Kremenekd13c1872008-06-24 03:56:45 +0000846RetainSummary* RetainSummaryManager::getSummary(FunctionDecl* FD) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000847
848 SourceLocation Loc = FD->getLocation();
849
850 if (!Loc.isFileID())
851 return NULL;
Ted Kremenek827f93b2008-03-06 00:08:09 +0000852
Ted Kremenekae855d42008-04-24 17:22:33 +0000853 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000854 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremenekae855d42008-04-24 17:22:33 +0000855
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000856 if (I != FuncSummaries.end())
Ted Kremenekae855d42008-04-24 17:22:33 +0000857 return I->second;
858
859 // No summary. Generate one.
Ted Kremenek17144e82009-01-12 21:45:02 +0000860 RetainSummary *S = 0;
Ted Kremenek562c1302008-05-05 16:51:50 +0000861
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000862 do {
Ted Kremenek17144e82009-01-12 21:45:02 +0000863 // We generate "stop" summaries for implicitly defined functions.
864 if (FD->isImplicit()) {
865 S = getPersistentStopSummary();
866 break;
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000867 }
Ted Kremenekeafcc2f2008-11-04 00:36:12 +0000868
Ted Kremenek064ef322009-02-23 16:51:39 +0000869 // [PR 3337] Use 'getAsFunctionType' to strip away any typedefs on the
Ted Kremenekc239b9c2009-01-16 18:40:33 +0000870 // function's type.
Ted Kremenek064ef322009-02-23 16:51:39 +0000871 const FunctionType* FT = FD->getType()->getAsFunctionType();
Ted Kremenek17144e82009-01-12 21:45:02 +0000872 const char* FName = FD->getIdentifier()->getName();
873
Ted Kremenek38c6f022009-03-05 22:11:14 +0000874 // Strip away preceding '_'. Doing this here will effect all the checks
875 // down below.
876 while (*FName == '_') ++FName;
877
Ted Kremenek17144e82009-01-12 21:45:02 +0000878 // Inspect the result type.
879 QualType RetTy = FT->getResultType();
880
881 // FIXME: This should all be refactored into a chain of "summary lookup"
882 // filters.
883 if (strcmp(FName, "IOServiceGetMatchingServices") == 0) {
884 // FIXES: <rdar://problem/6326900>
885 // This should be addressed using a API table. This strcmp is also
886 // a little gross, but there is no need to super optimize here.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000887 assert (ScratchArgs.isEmpty());
888 ScratchArgs = AF.Add(ScratchArgs, 1, DecRef);
Ted Kremenek17144e82009-01-12 21:45:02 +0000889 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
890 break;
Ted Kremenekcfc50c72008-10-22 20:54:52 +0000891 }
Ted Kremenek7b88c892009-03-17 22:43:44 +0000892
893 // Enable this code once the semantics of NSDeallocateObject are resolved
894 // for GC. <rdar://problem/6619988>
895#if 0
896 // Handle: NSDeallocateObject(id anObject);
897 // This method does allow 'nil' (although we don't check it now).
898 if (strcmp(FName, "NSDeallocateObject") == 0) {
899 return RetTy == Ctx.VoidTy
900 ? getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, Dealloc)
901 : getPersistentStopSummary();
902 }
903#endif
Ted Kremenek17144e82009-01-12 21:45:02 +0000904
905 // Handle: id NSMakeCollectable(CFTypeRef)
906 if (strcmp(FName, "NSMakeCollectable") == 0) {
907 S = (RetTy == Ctx.getObjCIdType())
908 ? getUnarySummary(FT, cfmakecollectable)
909 : getPersistentStopSummary();
910
911 break;
912 }
913
914 if (RetTy->isPointerType()) {
915 // For CoreFoundation ('CF') types.
916 if (isRefType(RetTy, "CF", &Ctx, FName)) {
917 if (isRetain(FD, FName))
918 S = getUnarySummary(FT, cfretain);
919 else if (strstr(FName, "MakeCollectable"))
920 S = getUnarySummary(FT, cfmakecollectable);
921 else
922 S = getCFCreateGetRuleSummary(FD, FName);
923
924 break;
925 }
926
927 // For CoreGraphics ('CG') types.
928 if (isRefType(RetTy, "CG", &Ctx, FName)) {
929 if (isRetain(FD, FName))
930 S = getUnarySummary(FT, cfretain);
931 else
932 S = getCFCreateGetRuleSummary(FD, FName);
933
934 break;
935 }
936
937 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
938 if (isRefType(RetTy, "DADisk") ||
939 isRefType(RetTy, "DADissenter") ||
940 isRefType(RetTy, "DASessionRef")) {
941 S = getCFCreateGetRuleSummary(FD, FName);
942 break;
943 }
944
945 break;
946 }
947
948 // Check for release functions, the only kind of functions that we care
949 // about that don't return a pointer type.
950 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
Ted Kremenek38c6f022009-03-05 22:11:14 +0000951 // Test for 'CGCF'.
952 if (FName[1] == 'G' && FName[2] == 'C' && FName[3] == 'F')
953 FName += 4;
954 else
955 FName += 2;
956
957 if (isRelease(FD, FName))
Ted Kremenek17144e82009-01-12 21:45:02 +0000958 S = getUnarySummary(FT, cfrelease);
959 else {
Ted Kremeneka56ae162009-05-03 05:20:50 +0000960 assert (ScratchArgs.isEmpty());
Ted Kremenek7b293682009-01-29 22:45:13 +0000961 // Remaining CoreFoundation and CoreGraphics functions.
962 // We use to assume that they all strictly followed the ownership idiom
963 // and that ownership cannot be transferred. While this is technically
964 // correct, many methods allow a tracked object to escape. For example:
965 //
966 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
967 // CFDictionaryAddValue(y, key, x);
968 // CFRelease(x);
969 // ... it is okay to use 'x' since 'y' has a reference to it
970 //
971 // We handle this and similar cases with the follow heuristic. If the
972 // function name contains "InsertValue", "SetValue" or "AddValue" then
973 // we assume that arguments may "escape."
974 //
975 ArgEffect E = (CStrInCStrNoCase(FName, "InsertValue") ||
976 CStrInCStrNoCase(FName, "AddValue") ||
Ted Kremenekcf071252009-02-05 22:34:53 +0000977 CStrInCStrNoCase(FName, "SetValue") ||
978 CStrInCStrNoCase(FName, "AppendValue"))
Ted Kremenek7b293682009-01-29 22:45:13 +0000979 ? MayEscape : DoNothing;
980
981 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek17144e82009-01-12 21:45:02 +0000982 }
983 }
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000984 }
985 while (0);
Ted Kremenekae855d42008-04-24 17:22:33 +0000986
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000987 FuncSummaries[FD] = S;
Ted Kremenek562c1302008-05-05 16:51:50 +0000988 return S;
Ted Kremenek827f93b2008-03-06 00:08:09 +0000989}
990
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000991RetainSummary*
992RetainSummaryManager::getCFCreateGetRuleSummary(FunctionDecl* FD,
993 const char* FName) {
994
Ted Kremenek562c1302008-05-05 16:51:50 +0000995 if (strstr(FName, "Create") || strstr(FName, "Copy"))
996 return getCFSummaryCreateRule(FD);
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000997
Ted Kremenek562c1302008-05-05 16:51:50 +0000998 if (strstr(FName, "Get"))
999 return getCFSummaryGetRule(FD);
1000
Ted Kremenek286e9852009-05-04 04:57:00 +00001001 return getDefaultSummary();
Ted Kremenek562c1302008-05-05 16:51:50 +00001002}
1003
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001004RetainSummary*
Ted Kremenek064ef322009-02-23 16:51:39 +00001005RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1006 UnaryFuncKind func) {
1007
Ted Kremenek17144e82009-01-12 21:45:02 +00001008 // Sanity check that this is *really* a unary function. This can
1009 // happen if people do weird things.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001010 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
Ted Kremenek17144e82009-01-12 21:45:02 +00001011 if (!FTP || FTP->getNumArgs() != 1)
1012 return getPersistentStopSummary();
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001013
Ted Kremeneka56ae162009-05-03 05:20:50 +00001014 assert (ScratchArgs.isEmpty());
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001015
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001016 switch (func) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001017 case cfretain: {
1018 ScratchArgs = AF.Add(ScratchArgs, 0, IncRef);
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001019 return getPersistentSummary(RetEffect::MakeAlias(0),
1020 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001021 }
1022
1023 case cfrelease: {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001024 ScratchArgs = AF.Add(ScratchArgs, 0, DecRef);
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001025 return getPersistentSummary(RetEffect::MakeNoRet(),
1026 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001027 }
1028
1029 case cfmakecollectable: {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001030 ScratchArgs = AF.Add(ScratchArgs, 0, MakeCollectable);
Ted Kremenek2126bef2009-02-18 21:57:45 +00001031 return getPersistentSummary(RetEffect::MakeAlias(0),DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001032 }
1033
1034 default:
Ted Kremenek562c1302008-05-05 16:51:50 +00001035 assert (false && "Not a supported unary function.");
Ted Kremenek286e9852009-05-04 04:57:00 +00001036 return getDefaultSummary();
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00001037 }
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001038}
1039
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001040RetainSummary* RetainSummaryManager::getCFSummaryCreateRule(FunctionDecl* FD) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001041 assert (ScratchArgs.isEmpty());
Ted Kremenekede40b72008-07-09 18:11:16 +00001042
1043 if (FD->getIdentifier() == CFDictionaryCreateII) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001044 ScratchArgs = AF.Add(ScratchArgs, 1, DoNothingByRef);
1045 ScratchArgs = AF.Add(ScratchArgs, 2, DoNothingByRef);
Ted Kremenekede40b72008-07-09 18:11:16 +00001046 }
1047
Ted Kremenek68621b92009-01-28 05:56:51 +00001048 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001049}
1050
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001051RetainSummary* RetainSummaryManager::getCFSummaryGetRule(FunctionDecl* FD) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001052 assert (ScratchArgs.isEmpty());
Ted Kremenek68621b92009-01-28 05:56:51 +00001053 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1054 DoNothing, DoNothing);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001055}
1056
Ted Kremeneka7338b42008-03-11 06:39:11 +00001057//===----------------------------------------------------------------------===//
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001058// Summary creation for Selectors.
1059//===----------------------------------------------------------------------===//
1060
Ted Kremenekbcaff792008-05-06 15:44:25 +00001061RetainSummary*
Ted Kremeneka821b792009-04-29 05:04:30 +00001062RetainSummaryManager::getInitMethodSummary(QualType RetTy) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001063 assert(ScratchArgs.isEmpty());
Ted Kremenek42ea0322008-05-05 23:55:01 +00001064
Ted Kremenek802cfc72009-02-20 00:05:35 +00001065 // 'init' methods only return an alias if the return type is a location type.
Ted Kremeneka821b792009-04-29 05:04:30 +00001066 return getPersistentSummary(Loc::IsLocType(RetTy)
1067 ? RetEffect::MakeReceiverAlias()
1068 : RetEffect::MakeNoRet());
Ted Kremenek42ea0322008-05-05 23:55:01 +00001069}
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001070
Ted Kremenek923fc392009-04-24 23:32:32 +00001071RetainSummary*
Ted Kremenek314b1952009-04-29 23:03:22 +00001072RetainSummaryManager::getMethodSummaryFromAnnotations(const ObjCMethodDecl *MD){
Ted Kremenek923fc392009-04-24 23:32:32 +00001073 if (!MD)
Ted Kremenek286e9852009-05-04 04:57:00 +00001074 return getDefaultSummary();
Ted Kremenek923fc392009-04-24 23:32:32 +00001075
Ted Kremeneka56ae162009-05-03 05:20:50 +00001076 assert(ScratchArgs.isEmpty());
Ted Kremenek923fc392009-04-24 23:32:32 +00001077
1078 // Determine if there is a special return effect for this method.
Ted Kremeneke404c0d2009-04-30 20:00:31 +00001079 bool hasEffect = false;
Ted Kremenek923fc392009-04-24 23:32:32 +00001080 RetEffect RE = RetEffect::MakeNoRet();
1081
Ted Kremenek9b42e062009-05-03 04:42:10 +00001082 if (isTrackedObjCObjectType(MD->getResultType())) {
Ted Kremenek923fc392009-04-24 23:32:32 +00001083 if (MD->getAttr<ObjCOwnershipReturnsAttr>()) {
Ted Kremenek382fb4e2009-04-27 19:14:45 +00001084 RE = isGCEnabled() ? RetEffect::MakeGCNotOwned()
1085 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremeneke404c0d2009-04-30 20:00:31 +00001086 hasEffect = true;
Ted Kremenek923fc392009-04-24 23:32:32 +00001087 }
1088 else {
1089 // Default to 'not owned'.
1090 RE = RetEffect::MakeNotOwned(RetEffect::ObjC);
1091 }
1092 }
1093
Ted Kremenekb30a2f32009-04-25 01:21:50 +00001094 // Determine if there are any arguments with a specific ArgEffect.
Ted Kremenekb30a2f32009-04-25 01:21:50 +00001095 unsigned i = 0;
1096 for (ObjCMethodDecl::param_iterator I = MD->param_begin(),
1097 E = MD->param_end(); I != E; ++I, ++i) {
1098 if ((*I)->getAttr<ObjCOwnershipRetainAttr>()) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001099 ScratchArgs = AF.Add(ScratchArgs, i, IncRefMsg);
Ted Kremeneke404c0d2009-04-30 20:00:31 +00001100 hasEffect = true;
Ted Kremenekb30a2f32009-04-25 01:21:50 +00001101 }
Ted Kremenek15830ed2009-04-27 18:27:22 +00001102 else if ((*I)->getAttr<ObjCOwnershipCFRetainAttr>()) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001103 ScratchArgs = AF.Add(ScratchArgs, i, IncRef);
Ted Kremeneke404c0d2009-04-30 20:00:31 +00001104 hasEffect = true;
Ted Kremenek203169f2009-04-27 19:36:56 +00001105 }
1106 else if ((*I)->getAttr<ObjCOwnershipReleaseAttr>()) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001107 ScratchArgs = AF.Add(ScratchArgs, i, DecRefMsg);
Ted Kremeneke404c0d2009-04-30 20:00:31 +00001108 hasEffect = true;
Ted Kremenek203169f2009-04-27 19:36:56 +00001109 }
1110 else if ((*I)->getAttr<ObjCOwnershipCFReleaseAttr>()) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001111 ScratchArgs = AF.Add(ScratchArgs, i, DecRef);
Ted Kremeneke404c0d2009-04-30 20:00:31 +00001112 hasEffect = true;
Ted Kremenek203169f2009-04-27 19:36:56 +00001113 }
Ted Kremenekff8648d2009-04-28 22:32:26 +00001114 else if ((*I)->getAttr<ObjCOwnershipMakeCollectableAttr>()) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001115 ScratchArgs = AF.Add(ScratchArgs, i, MakeCollectable);
Ted Kremeneke404c0d2009-04-30 20:00:31 +00001116 hasEffect = true;
Ted Kremenekff8648d2009-04-28 22:32:26 +00001117 }
Ted Kremenek15830ed2009-04-27 18:27:22 +00001118 }
Ted Kremenekb30a2f32009-04-25 01:21:50 +00001119
Ted Kremeneke404c0d2009-04-30 20:00:31 +00001120 // Determine any effects on the receiver.
1121 ArgEffect ReceiverEff = DoNothing;
1122 if (MD->getAttr<ObjCOwnershipRetainAttr>()) {
1123 ReceiverEff = IncRefMsg;
1124 hasEffect = true;
1125 }
1126 else if (MD->getAttr<ObjCOwnershipReleaseAttr>()) {
1127 ReceiverEff = DecRefMsg;
1128 hasEffect = true;
1129 }
1130
1131 if (!hasEffect)
Ted Kremenek286e9852009-05-04 04:57:00 +00001132 return getDefaultSummary();
Ted Kremenek923fc392009-04-24 23:32:32 +00001133
Ted Kremeneke404c0d2009-04-30 20:00:31 +00001134 return getPersistentSummary(RE, ReceiverEff);
Ted Kremenek923fc392009-04-24 23:32:32 +00001135}
Ted Kremenek272aa852008-06-25 21:21:56 +00001136
Ted Kremenekbcaff792008-05-06 15:44:25 +00001137RetainSummary*
Ted Kremenek314b1952009-04-29 23:03:22 +00001138RetainSummaryManager::getCommonMethodSummary(const ObjCMethodDecl* MD,
1139 Selector S, QualType RetTy) {
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001140
Ted Kremenek578498a2009-04-29 00:42:39 +00001141 if (MD) {
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001142 // Scan the method decl for 'void*' arguments. These should be treated
1143 // as 'StopTracking' because they are often used with delegates.
1144 // Delegates are a frequent form of false positives with the retain
1145 // count checker.
1146 unsigned i = 0;
1147 for (ObjCMethodDecl::param_iterator I = MD->param_begin(),
1148 E = MD->param_end(); I != E; ++I, ++i)
1149 if (ParmVarDecl *PD = *I) {
1150 QualType Ty = Ctx.getCanonicalType(PD->getType());
1151 if (Ty.getUnqualifiedType() == Ctx.VoidPtrTy)
Ted Kremeneka56ae162009-05-03 05:20:50 +00001152 ScratchArgs = AF.Add(ScratchArgs, i, StopTracking);
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001153 }
1154 }
1155
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001156 // Any special effect for the receiver?
1157 ArgEffect ReceiverEff = DoNothing;
1158
1159 // If one of the arguments in the selector has the keyword 'delegate' we
1160 // should stop tracking the reference count for the receiver. This is
1161 // because the reference count is quite possibly handled by a delegate
1162 // method.
1163 if (S.isKeywordSelector()) {
1164 const std::string &str = S.getAsString();
1165 assert(!str.empty());
1166 if (CStrInCStrNoCase(&str[0], "delegate:")) ReceiverEff = StopTracking;
1167 }
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001168
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001169
Ted Kremenek174a0772009-04-23 23:08:22 +00001170 // Look for methods that return an owned object.
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001171 if (isTrackedObjCObjectType(RetTy)) {
1172 // EXPERIMENTAL: Assume the Cocoa conventions for all objects returned
1173 // by instance methods.
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001174
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001175 RetEffect E =
1176 followsFundamentalRule(S.getIdentifierInfoForSlot(0)->getName())
1177 ? (isGCEnabled() ? RetEffect::MakeGCNotOwned()
1178 : RetEffect::MakeOwned(RetEffect::ObjC, true))
1179 : RetEffect::MakeNotOwned(RetEffect::ObjC);
1180
1181 return getPersistentSummary(E, ReceiverEff, MayEscape);
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001182 }
Ted Kremenek174a0772009-04-23 23:08:22 +00001183
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001184 // Look for methods that return an owned core foundation object.
1185 if (isTrackedCFObjectType(RetTy)) {
1186 RetEffect E =
1187 followsFundamentalRule(S.getIdentifierInfoForSlot(0)->getName())
1188 ? RetEffect::MakeOwned(RetEffect::CF, true)
1189 : RetEffect::MakeNotOwned(RetEffect::CF);
1190
1191 return getPersistentSummary(E, ReceiverEff, MayEscape);
1192 }
Ted Kremenek174a0772009-04-23 23:08:22 +00001193
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001194 if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing)
Ted Kremenek286e9852009-05-04 04:57:00 +00001195 return getDefaultSummary();
Ted Kremenek174a0772009-04-23 23:08:22 +00001196
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001197 return getPersistentSummary(RetEffect::MakeNoRet(), ReceiverEff,
1198 MayEscape);
Ted Kremenek174a0772009-04-23 23:08:22 +00001199}
1200
1201RetainSummary*
Ted Kremenek04e00302009-04-29 17:09:14 +00001202RetainSummaryManager::getInstanceMethodSummary(Selector S,
1203 IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +00001204 const ObjCInterfaceDecl* ID,
1205 const ObjCMethodDecl *MD,
Ted Kremenek04e00302009-04-29 17:09:14 +00001206 QualType RetTy) {
Ted Kremenekbcaff792008-05-06 15:44:25 +00001207
Ted Kremeneka821b792009-04-29 05:04:30 +00001208 // Look up a summary in our summary cache.
1209 ObjCMethodSummariesTy::iterator I = ObjCMethodSummaries.find(ID, ClsName, S);
Ted Kremenek42ea0322008-05-05 23:55:01 +00001210
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001211 if (I != ObjCMethodSummaries.end())
Ted Kremenek42ea0322008-05-05 23:55:01 +00001212 return I->second;
Ted Kremenek42ea0322008-05-05 23:55:01 +00001213
Ted Kremeneka56ae162009-05-03 05:20:50 +00001214 assert(ScratchArgs.isEmpty());
Ted Kremenek923fc392009-04-24 23:32:32 +00001215
1216 // Annotations take precedence over all other ways to derive
1217 // summaries.
Ted Kremeneka821b792009-04-29 05:04:30 +00001218 RetainSummary *Summ = getMethodSummaryFromAnnotations(MD);
Ted Kremenek1d3d9562008-05-06 06:09:09 +00001219
Ted Kremenek923fc392009-04-24 23:32:32 +00001220 if (!Summ) {
1221 // "initXXX": pass-through for receiver.
1222 if (deriveNamingConvention(S.getIdentifierInfoForSlot(0)->getName())
1223 == InitRule)
Ted Kremeneka821b792009-04-29 05:04:30 +00001224 Summ = getInitMethodSummary(RetTy);
1225 else
1226 Summ = getCommonMethodSummary(MD, S, RetTy);
Ted Kremenek923fc392009-04-24 23:32:32 +00001227 }
1228
Ted Kremeneka821b792009-04-29 05:04:30 +00001229 ObjCMethodSummaries[ObjCSummaryKey(ClsName, S)] = Summ;
Ted Kremeneke4158502009-04-23 19:11:35 +00001230 return Summ;
Ted Kremenek42ea0322008-05-05 23:55:01 +00001231}
1232
Ted Kremeneka7722b72008-05-06 21:26:51 +00001233RetainSummary*
Ted Kremenek578498a2009-04-29 00:42:39 +00001234RetainSummaryManager::getClassMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +00001235 const ObjCInterfaceDecl *ID,
1236 const ObjCMethodDecl *MD,
1237 QualType RetTy) {
Ted Kremenekccbe79a2009-04-24 17:50:11 +00001238
Ted Kremenek578498a2009-04-29 00:42:39 +00001239 assert(ClsName && "Class name must be specified.");
Ted Kremeneka821b792009-04-29 05:04:30 +00001240 ObjCMethodSummariesTy::iterator I =
1241 ObjCClassMethodSummaries.find(ID, ClsName, S);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001242
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001243 if (I != ObjCClassMethodSummaries.end())
Ted Kremeneka7722b72008-05-06 21:26:51 +00001244 return I->second;
1245
Ted Kremenek923fc392009-04-24 23:32:32 +00001246 // Annotations take precedence over all other ways to derive
1247 // summaries.
Ted Kremenek578498a2009-04-29 00:42:39 +00001248 RetainSummary *Summ = getMethodSummaryFromAnnotations(MD);
Ted Kremenek923fc392009-04-24 23:32:32 +00001249
1250 if (!Summ)
Ted Kremenek578498a2009-04-29 00:42:39 +00001251 Summ = getCommonMethodSummary(MD, S, RetTy);
Ted Kremenek923fc392009-04-24 23:32:32 +00001252
Ted Kremenek578498a2009-04-29 00:42:39 +00001253 ObjCClassMethodSummaries[ObjCSummaryKey(ClsName, S)] = Summ;
Ted Kremeneke4158502009-04-23 19:11:35 +00001254 return Summ;
Ted Kremeneka7722b72008-05-06 21:26:51 +00001255}
1256
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001257void RetainSummaryManager::InitializeClassMethodSummaries() {
Ted Kremenek0e344d42008-05-06 00:30:21 +00001258
Ted Kremeneka56ae162009-05-03 05:20:50 +00001259 assert (ScratchArgs.isEmpty());
Ted Kremenek0e344d42008-05-06 00:30:21 +00001260
Ted Kremenek382fb4e2009-04-27 19:14:45 +00001261 RetEffect E = isGCEnabled() ? RetEffect::MakeGCNotOwned()
Ted Kremenek68621b92009-01-28 05:56:51 +00001262 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001263
Ted Kremenek0e344d42008-05-06 00:30:21 +00001264 RetainSummary* Summ = getPersistentSummary(E);
1265
Ted Kremenek272aa852008-06-25 21:21:56 +00001266 // Create the summaries for "alloc", "new", and "allocWithZone:" for
1267 // NSObject and its derivatives.
1268 addNSObjectClsMethSummary(GetNullarySelector("alloc", Ctx), Summ);
1269 addNSObjectClsMethSummary(GetNullarySelector("new", Ctx), Summ);
1270 addNSObjectClsMethSummary(GetUnarySelector("allocWithZone", Ctx), Summ);
Ted Kremenekf2717b02008-07-18 17:24:20 +00001271
1272 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001273 addClsMethSummary(&Ctx.Idents.get("NSAssertionHandler"),
Ted Kremenek68621b92009-01-28 05:56:51 +00001274 GetNullarySelector("currentHandler", Ctx),
1275 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001276
1277 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremeneka56ae162009-05-03 05:20:50 +00001278 ScratchArgs = AF.Add(ScratchArgs, 0, Autorelease);
Ted Kremenek9b112d22009-01-28 21:44:40 +00001279 addClsMethSummary(&Ctx.Idents.get("NSAutoreleasePool"),
1280 GetUnarySelector("addObject", Ctx),
1281 getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenekf21cb242009-02-23 02:31:16 +00001282 DoNothing, Autorelease));
Ted Kremenekccbe79a2009-04-24 17:50:11 +00001283
1284 // Create the summaries for [NSObject performSelector...]. We treat
1285 // these as 'stop tracking' for the arguments because they are often
1286 // used for delegates that can release the object. When we have better
1287 // inter-procedural analysis we can potentially do something better. This
1288 // workaround is to remove false positives.
1289 Summ = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, StopTracking);
1290 IdentifierInfo *NSObjectII = &Ctx.Idents.get("NSObject");
1291 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1292 "afterDelay", NULL);
1293 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1294 "afterDelay", "inModes", NULL);
1295 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1296 "withObject", "waitUntilDone", NULL);
1297 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1298 "withObject", "waitUntilDone", "modes", NULL);
1299 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1300 "withObject", "waitUntilDone", NULL);
1301 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1302 "withObject", "waitUntilDone", "modes", NULL);
1303 addClsMethSummary(NSObjectII, Summ, "performSelectorInBackground",
1304 "withObject", NULL);
Ted Kremenek0e344d42008-05-06 00:30:21 +00001305}
1306
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001307void RetainSummaryManager::InitializeMethodSummaries() {
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001308
Ted Kremeneka56ae162009-05-03 05:20:50 +00001309 assert (ScratchArgs.isEmpty());
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001310
Ted Kremeneka7722b72008-05-06 21:26:51 +00001311 // Create the "init" selector. It just acts as a pass-through for the
1312 // receiver.
Ted Kremenek56c70aa2009-02-23 16:54:00 +00001313 RetainSummary* InitSumm =
1314 getPersistentSummary(RetEffect::MakeReceiverAlias());
Ted Kremeneke44927e2008-07-01 17:21:27 +00001315 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001316
1317 // The next methods are allocators.
Ted Kremenek382fb4e2009-04-27 19:14:45 +00001318 RetEffect E = isGCEnabled() ? RetEffect::MakeGCNotOwned()
Ted Kremenek68621b92009-01-28 05:56:51 +00001319 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001320
Ted Kremeneke44927e2008-07-01 17:21:27 +00001321 RetainSummary* Summ = getPersistentSummary(E);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001322
1323 // Create the "copy" selector.
Ted Kremenek9449ca92008-08-12 20:41:56 +00001324 addNSObjectMethSummary(GetNullarySelector("copy", Ctx), Summ);
1325
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001326 // Create the "mutableCopy" selector.
Ted Kremenek272aa852008-06-25 21:21:56 +00001327 addNSObjectMethSummary(GetNullarySelector("mutableCopy", Ctx), Summ);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001328
Ted Kremenek266d8b62008-05-06 02:26:56 +00001329 // Create the "retain" selector.
1330 E = RetEffect::MakeReceiverAlias();
Ted Kremenek58dd95b2009-02-18 18:54:33 +00001331 Summ = getPersistentSummary(E, IncRefMsg);
Ted Kremenek272aa852008-06-25 21:21:56 +00001332 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001333
1334 // Create the "release" selector.
Ted Kremenek58dd95b2009-02-18 18:54:33 +00001335 Summ = getPersistentSummary(E, DecRefMsg);
Ted Kremenek272aa852008-06-25 21:21:56 +00001336 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Ted Kremenekc00b32b2008-05-07 21:17:39 +00001337
1338 // Create the "drain" selector.
1339 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek272aa852008-06-25 21:21:56 +00001340 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
Ted Kremenek6537a642009-03-17 19:42:23 +00001341
1342 // Create the -dealloc summary.
1343 Summ = getPersistentSummary(RetEffect::MakeNoRet(), Dealloc);
1344 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001345
1346 // Create the "autorelease" selector.
Ted Kremenek9b112d22009-01-28 21:44:40 +00001347 Summ = getPersistentSummary(E, Autorelease);
Ted Kremenek272aa852008-06-25 21:21:56 +00001348 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001349
Ted Kremenekaac82832009-02-23 17:45:03 +00001350 // Specially handle NSAutoreleasePool.
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001351 addInstMethSummary("NSAutoreleasePool", "init",
Ted Kremenekaac82832009-02-23 17:45:03 +00001352 getPersistentSummary(RetEffect::MakeReceiverAlias(),
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001353 NewAutoreleasePool));
Ted Kremenekaac82832009-02-23 17:45:03 +00001354
Ted Kremenek45642a42008-08-12 18:48:50 +00001355 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremenek7e3a3272009-02-23 02:51:29 +00001356 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1357 // self-own themselves. However, they only do this once they are displayed.
1358 // Thus, we need to track an NSWindow's display status.
1359 // This is tracked in <rdar://problem/6062711>.
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001360 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
Ted Kremeneke5a036a2009-04-03 19:02:51 +00001361 RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet());
1362
1363 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1364
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001365
1366#if 0
Ted Kremeneke44927e2008-07-01 17:21:27 +00001367 RetainSummary *NSWindowSumm =
Ted Kremenek7e3a3272009-02-23 02:51:29 +00001368 getPersistentSummary(RetEffect::MakeReceiverAlias(), StopTracking);
Ted Kremenek45642a42008-08-12 18:48:50 +00001369
1370 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1371 "styleMask", "backing", "defer", NULL);
1372
1373 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1374 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001375#endif
Ted Kremenek45642a42008-08-12 18:48:50 +00001376
1377 // For NSPanel (which subclasses NSWindow), allocated objects are not
1378 // self-owned.
Ted Kremeneke5a036a2009-04-03 19:02:51 +00001379 // FIXME: For now we don't track NSPanels. object for the same reason
1380 // as for NSWindow objects.
1381 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
1382
Ted Kremenek45642a42008-08-12 18:48:50 +00001383 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1384 "styleMask", "backing", "defer", NULL);
1385
1386 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1387 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek272aa852008-06-25 21:21:56 +00001388
Ted Kremenekf2717b02008-07-18 17:24:20 +00001389 // Create NSAssertionHandler summaries.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001390 addPanicSummary("NSAssertionHandler", "handleFailureInFunction", "file",
1391 "lineNumber", "description", NULL);
Ted Kremenekf2717b02008-07-18 17:24:20 +00001392
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001393 addPanicSummary("NSAssertionHandler", "handleFailureInMethod", "object",
1394 "file", "lineNumber", "description", NULL);
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001395}
1396
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001397//===----------------------------------------------------------------------===//
Ted Kremenek7aef4842008-04-16 20:40:59 +00001398// Reference-counting logic (typestate + counts).
Ted Kremeneka7338b42008-03-11 06:39:11 +00001399//===----------------------------------------------------------------------===//
1400
Ted Kremeneka7338b42008-03-11 06:39:11 +00001401namespace {
1402
Ted Kremenek7d421f32008-04-09 23:49:11 +00001403class VISIBILITY_HIDDEN RefVal {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001404public:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001405 enum Kind {
1406 Owned = 0, // Owning reference.
1407 NotOwned, // Reference is not owned by still valid (not freed).
1408 Released, // Object has been released.
1409 ReturnedOwned, // Returned object passes ownership to caller.
1410 ReturnedNotOwned, // Return object does not pass ownership to caller.
Ted Kremenek6537a642009-03-17 19:42:23 +00001411 ERROR_START,
1412 ErrorDeallocNotOwned, // -dealloc called on non-owned object.
1413 ErrorDeallocGC, // Calling -dealloc with GC enabled.
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001414 ErrorUseAfterRelease, // Object used after released.
1415 ErrorReleaseNotOwned, // Release of an object that was not owned.
Ted Kremenek6537a642009-03-17 19:42:23 +00001416 ERROR_LEAK_START,
Ted Kremenek311f3d42008-10-22 23:56:21 +00001417 ErrorLeak, // A memory leak due to excessive reference counts.
1418 ErrorLeakReturned // A memory leak due to the returning method not having
1419 // the correct naming conventions.
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001420 };
Ted Kremenek68621b92009-01-28 05:56:51 +00001421
1422private:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001423 Kind kind;
Ted Kremenek68621b92009-01-28 05:56:51 +00001424 RetEffect::ObjKind okind;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001425 unsigned Cnt;
Ted Kremenek272aa852008-06-25 21:21:56 +00001426 QualType T;
1427
Ted Kremenek68621b92009-01-28 05:56:51 +00001428 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, QualType t)
1429 : kind(k), okind(o), Cnt(cnt), T(t) {}
Ted Kremenek0d721572008-03-11 17:48:22 +00001430
Ted Kremenek68621b92009-01-28 05:56:51 +00001431 RefVal(Kind k, unsigned cnt = 0)
1432 : kind(k), okind(RetEffect::AnyObj), Cnt(cnt) {}
1433
1434public:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001435 Kind getKind() const { return kind; }
Ted Kremenek68621b92009-01-28 05:56:51 +00001436
1437 RetEffect::ObjKind getObjKind() const { return okind; }
Ted Kremenek0d721572008-03-11 17:48:22 +00001438
Ted Kremenek6537a642009-03-17 19:42:23 +00001439 unsigned getCount() const { return Cnt; }
1440 void clearCounts() { Cnt = 0; }
1441
Ted Kremenek272aa852008-06-25 21:21:56 +00001442 QualType getType() const { return T; }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001443
1444 // Useful predicates.
Ted Kremenek0d721572008-03-11 17:48:22 +00001445
Ted Kremenek6537a642009-03-17 19:42:23 +00001446 static bool isError(Kind k) { return k >= ERROR_START; }
Ted Kremenek1daa16c2008-03-11 18:14:09 +00001447
Ted Kremenek6537a642009-03-17 19:42:23 +00001448 static bool isLeak(Kind k) { return k >= ERROR_LEAK_START; }
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001449
Ted Kremenekffefc352008-04-11 22:25:11 +00001450 bool isOwned() const {
1451 return getKind() == Owned;
1452 }
1453
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001454 bool isNotOwned() const {
1455 return getKind() == NotOwned;
1456 }
1457
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001458 bool isReturnedOwned() const {
1459 return getKind() == ReturnedOwned;
1460 }
1461
1462 bool isReturnedNotOwned() const {
1463 return getKind() == ReturnedNotOwned;
1464 }
1465
1466 bool isNonLeakError() const {
1467 Kind k = getKind();
1468 return isError(k) && !isLeak(k);
1469 }
1470
Ted Kremenek68621b92009-01-28 05:56:51 +00001471 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
1472 unsigned Count = 1) {
1473 return RefVal(Owned, o, Count, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001474 }
1475
Ted Kremenek68621b92009-01-28 05:56:51 +00001476 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
1477 unsigned Count = 0) {
1478 return RefVal(NotOwned, o, Count, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001479 }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001480
1481 static RefVal makeReturnedOwned(unsigned Count) {
1482 return RefVal(ReturnedOwned, Count);
1483 }
1484
1485 static RefVal makeReturnedNotOwned() {
1486 return RefVal(ReturnedNotOwned);
1487 }
1488
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001489 // Comparison, profiling, and pretty-printing.
Ted Kremenek0d721572008-03-11 17:48:22 +00001490
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001491 bool operator==(const RefVal& X) const {
Ted Kremenek272aa852008-06-25 21:21:56 +00001492 return kind == X.kind && Cnt == X.Cnt && T == X.T;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001493 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001494
Ted Kremenek272aa852008-06-25 21:21:56 +00001495 RefVal operator-(size_t i) const {
Ted Kremenek68621b92009-01-28 05:56:51 +00001496 return RefVal(getKind(), getObjKind(), getCount() - i, getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001497 }
1498
1499 RefVal operator+(size_t i) const {
Ted Kremenek68621b92009-01-28 05:56:51 +00001500 return RefVal(getKind(), getObjKind(), getCount() + i, getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001501 }
1502
1503 RefVal operator^(Kind k) const {
Ted Kremenek68621b92009-01-28 05:56:51 +00001504 return RefVal(k, getObjKind(), getCount(), getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001505 }
Ted Kremenek6537a642009-03-17 19:42:23 +00001506
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001507 void Profile(llvm::FoldingSetNodeID& ID) const {
1508 ID.AddInteger((unsigned) kind);
1509 ID.AddInteger(Cnt);
Ted Kremenek272aa852008-06-25 21:21:56 +00001510 ID.Add(T);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001511 }
1512
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001513 void print(std::ostream& Out) const;
Ted Kremenek0d721572008-03-11 17:48:22 +00001514};
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001515
1516void RefVal::print(std::ostream& Out) const {
Ted Kremenek272aa852008-06-25 21:21:56 +00001517 if (!T.isNull())
1518 Out << "Tracked Type:" << T.getAsString() << '\n';
1519
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001520 switch (getKind()) {
1521 default: assert(false);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001522 case Owned: {
1523 Out << "Owned";
1524 unsigned cnt = getCount();
1525 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001526 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001527 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001528
Ted Kremenekc4f81022008-04-10 23:09:18 +00001529 case NotOwned: {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001530 Out << "NotOwned";
Ted Kremenekc4f81022008-04-10 23:09:18 +00001531 unsigned cnt = getCount();
1532 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001533 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001534 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001535
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001536 case ReturnedOwned: {
1537 Out << "ReturnedOwned";
1538 unsigned cnt = getCount();
1539 if (cnt) Out << " (+ " << cnt << ")";
1540 break;
1541 }
1542
1543 case ReturnedNotOwned: {
1544 Out << "ReturnedNotOwned";
1545 unsigned cnt = getCount();
1546 if (cnt) Out << " (+ " << cnt << ")";
1547 break;
1548 }
1549
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001550 case Released:
1551 Out << "Released";
1552 break;
Ted Kremenek6537a642009-03-17 19:42:23 +00001553
1554 case ErrorDeallocGC:
1555 Out << "-dealloc (GC)";
1556 break;
1557
1558 case ErrorDeallocNotOwned:
1559 Out << "-dealloc (not-owned)";
1560 break;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001561
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001562 case ErrorLeak:
1563 Out << "Leaked";
1564 break;
1565
Ted Kremenek311f3d42008-10-22 23:56:21 +00001566 case ErrorLeakReturned:
1567 Out << "Leaked (Bad naming)";
1568 break;
1569
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001570 case ErrorUseAfterRelease:
1571 Out << "Use-After-Release [ERROR]";
1572 break;
1573
1574 case ErrorReleaseNotOwned:
1575 Out << "Release of Not-Owned [ERROR]";
1576 break;
1577 }
1578}
Ted Kremenek0d721572008-03-11 17:48:22 +00001579
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001580} // end anonymous namespace
1581
1582//===----------------------------------------------------------------------===//
1583// RefBindings - State used to track object reference counts.
1584//===----------------------------------------------------------------------===//
1585
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001586typedef llvm::ImmutableMap<SymbolRef, RefVal> RefBindings;
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001587static int RefBIndex = 0;
Ted Kremenek876d8df2009-02-19 23:47:02 +00001588static std::pair<const void*, const void*> LeakProgramPointTag(&RefBIndex, 0);
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001589
1590namespace clang {
Ted Kremenek91781202008-08-17 03:20:02 +00001591 template<>
1592 struct GRStateTrait<RefBindings> : public GRStatePartialTrait<RefBindings> {
1593 static inline void* GDMIndex() { return &RefBIndex; }
1594 };
1595}
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001596
1597//===----------------------------------------------------------------------===//
Ted Kremenekb6578942009-02-24 19:15:11 +00001598// AutoreleaseBindings - State used to track objects in autorelease pools.
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001599//===----------------------------------------------------------------------===//
1600
Ted Kremenekb6578942009-02-24 19:15:11 +00001601typedef llvm::ImmutableMap<SymbolRef, unsigned> ARCounts;
1602typedef llvm::ImmutableMap<SymbolRef, ARCounts> ARPoolContents;
1603typedef llvm::ImmutableList<SymbolRef> ARStack;
Ted Kremenekaac82832009-02-23 17:45:03 +00001604
Ted Kremenekb6578942009-02-24 19:15:11 +00001605static int AutoRCIndex = 0;
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001606static int AutoRBIndex = 0;
1607
Ted Kremenekb6578942009-02-24 19:15:11 +00001608namespace { class VISIBILITY_HIDDEN AutoreleasePoolContents {}; }
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001609namespace { class VISIBILITY_HIDDEN AutoreleaseStack {}; }
Ted Kremenekb6578942009-02-24 19:15:11 +00001610
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001611namespace clang {
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001612template<> struct GRStateTrait<AutoreleaseStack>
Ted Kremenekb6578942009-02-24 19:15:11 +00001613 : public GRStatePartialTrait<ARStack> {
1614 static inline void* GDMIndex() { return &AutoRBIndex; }
1615};
1616
1617template<> struct GRStateTrait<AutoreleasePoolContents>
1618 : public GRStatePartialTrait<ARPoolContents> {
1619 static inline void* GDMIndex() { return &AutoRCIndex; }
1620};
1621} // end clang namespace
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001622
Ted Kremenek681fb352009-03-20 17:34:15 +00001623static SymbolRef GetCurrentAutoreleasePool(const GRState* state) {
1624 ARStack stack = state->get<AutoreleaseStack>();
1625 return stack.isEmpty() ? SymbolRef() : stack.getHead();
1626}
1627
1628static GRStateRef SendAutorelease(GRStateRef state, ARCounts::Factory &F,
1629 SymbolRef sym) {
1630
1631 SymbolRef pool = GetCurrentAutoreleasePool(state);
1632 const ARCounts *cnts = state.get<AutoreleasePoolContents>(pool);
1633 ARCounts newCnts(0);
1634
1635 if (cnts) {
1636 const unsigned *cnt = (*cnts).lookup(sym);
1637 newCnts = F.Add(*cnts, sym, cnt ? *cnt + 1 : 1);
1638 }
1639 else
1640 newCnts = F.Add(F.GetEmptyMap(), sym, 1);
1641
1642 return state.set<AutoreleasePoolContents>(pool, newCnts);
1643}
1644
Ted Kremenek7aef4842008-04-16 20:40:59 +00001645//===----------------------------------------------------------------------===//
1646// Transfer functions.
1647//===----------------------------------------------------------------------===//
1648
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001649namespace {
1650
Ted Kremenek7d421f32008-04-09 23:49:11 +00001651class VISIBILITY_HIDDEN CFRefCount : public GRSimpleVals {
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001652public:
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001653 class BindingsPrinter : public GRState::Printer {
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001654 public:
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001655 virtual void Print(std::ostream& Out, const GRState* state,
1656 const char* nl, const char* sep);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001657 };
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001658
1659private:
Ted Kremenekc26c4692009-02-18 03:48:14 +00001660 typedef llvm::DenseMap<const GRExprEngine::NodeTy*, const RetainSummary*>
1661 SummaryLogTy;
1662
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001663 RetainSummaryManager Summaries;
Ted Kremenekc26c4692009-02-18 03:48:14 +00001664 SummaryLogTy SummaryLog;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001665 const LangOptions& LOpts;
Ted Kremenekb6578942009-02-24 19:15:11 +00001666 ARCounts::Factory ARCountFactory;
Ted Kremenek91781202008-08-17 03:20:02 +00001667
Ted Kremenek708af042009-02-05 06:50:21 +00001668 BugType *useAfterRelease, *releaseNotOwned;
Ted Kremenek6537a642009-03-17 19:42:23 +00001669 BugType *deallocGC, *deallocNotOwned;
Ted Kremenek708af042009-02-05 06:50:21 +00001670 BugType *leakWithinFunction, *leakAtReturn;
1671 BugReporter *BR;
Ted Kremeneka7338b42008-03-11 06:39:11 +00001672
Ted Kremenekb6578942009-02-24 19:15:11 +00001673 GRStateRef Update(GRStateRef state, SymbolRef sym, RefVal V, ArgEffect E,
1674 RefVal::Kind& hasErr);
1675
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001676 void ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
1677 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001678 Expr* NodeExpr, Expr* ErrorExpr,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001679 ExplodedNode<GRState>* Pred,
1680 const GRState* St,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001681 RefVal::Kind hasErr, SymbolRef Sym);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001682
Ted Kremenek0106e202008-10-24 20:32:50 +00001683 std::pair<GRStateRef, bool>
1684 HandleSymbolDeath(GRStateManager& VMgr, const GRState* St,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001685 const Decl* CD, SymbolRef sid, RefVal V, bool& hasLeak);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001686
Ted Kremenekb6578942009-02-24 19:15:11 +00001687public:
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00001688 CFRefCount(ASTContext& Ctx, bool gcenabled, const LangOptions& lopts)
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001689 : Summaries(Ctx, gcenabled),
Ted Kremenek6537a642009-03-17 19:42:23 +00001690 LOpts(lopts), useAfterRelease(0), releaseNotOwned(0),
1691 deallocGC(0), deallocNotOwned(0),
Ted Kremenek708af042009-02-05 06:50:21 +00001692 leakWithinFunction(0), leakAtReturn(0), BR(0) {}
Ted Kremenek1feab292008-04-16 04:28:53 +00001693
Ted Kremenek708af042009-02-05 06:50:21 +00001694 virtual ~CFRefCount() {}
Ted Kremenek7d421f32008-04-09 23:49:11 +00001695
Ted Kremenekbf6babf2009-02-04 23:49:09 +00001696 void RegisterChecks(BugReporter &BR);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001697
Ted Kremenekb0f2b9e2008-08-16 00:49:49 +00001698 virtual void RegisterPrinters(std::vector<GRState::Printer*>& Printers) {
1699 Printers.push_back(new BindingsPrinter());
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001700 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00001701
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001702 bool isGCEnabled() const { return Summaries.isGCEnabled(); }
Ted Kremenekfe30beb2008-04-30 23:47:44 +00001703 const LangOptions& getLangOptions() const { return LOpts; }
1704
Ted Kremenekc26c4692009-02-18 03:48:14 +00001705 const RetainSummary *getSummaryOfNode(const ExplodedNode<GRState> *N) const {
1706 SummaryLogTy::const_iterator I = SummaryLog.find(N);
1707 return I == SummaryLog.end() ? 0 : I->second;
1708 }
1709
Ted Kremeneka7338b42008-03-11 06:39:11 +00001710 // Calls.
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001711
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001712 void EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001713 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001714 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001715 Expr* Ex,
1716 Expr* Receiver,
Ted Kremenek286e9852009-05-04 04:57:00 +00001717 const RetainSummary& Summ,
Ted Kremenek2719e982008-06-17 02:43:46 +00001718 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001719 ExplodedNode<GRState>* Pred);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001720
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001721 virtual void EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekce0767f2008-03-12 21:06:49 +00001722 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001723 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001724 CallExpr* CE, SVal L,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001725 ExplodedNode<GRState>* Pred);
Ted Kremenek10fe66d2008-04-09 01:10:13 +00001726
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001727
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001728 virtual void EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001729 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001730 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001731 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001732 ExplodedNode<GRState>* Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001733
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001734 bool EvalObjCMessageExprAux(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001735 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001736 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001737 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001738 ExplodedNode<GRState>* Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001739
Ted Kremeneka42be302009-02-14 01:43:44 +00001740 // Stores.
1741 virtual void EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val);
1742
Ted Kremenekffefc352008-04-11 22:25:11 +00001743 // End-of-path.
1744
1745 virtual void EvalEndPath(GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001746 GREndPathNodeBuilder<GRState>& Builder);
Ted Kremenekffefc352008-04-11 22:25:11 +00001747
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001748 virtual void EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek541db372008-04-24 23:57:27 +00001749 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001750 GRStmtNodeBuilder<GRState>& Builder,
1751 ExplodedNode<GRState>* Pred,
Ted Kremenek5c0729b2009-01-21 22:26:05 +00001752 Stmt* S, const GRState* state,
1753 SymbolReaper& SymReaper);
1754
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001755 // Return statements.
1756
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001757 virtual void EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001758 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001759 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001760 ReturnStmt* S,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001761 ExplodedNode<GRState>* Pred);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001762
1763 // Assumptions.
1764
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001765 virtual const GRState* EvalAssume(GRStateManager& VMgr,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001766 const GRState* St, SVal Cond,
Ted Kremenekf22f8682008-07-10 22:03:41 +00001767 bool Assumption, bool& isFeasible);
Ted Kremeneka7338b42008-03-11 06:39:11 +00001768};
1769
1770} // end anonymous namespace
1771
Ted Kremenek681fb352009-03-20 17:34:15 +00001772static void PrintPool(std::ostream &Out, SymbolRef Sym, const GRState *state) {
1773 Out << ' ';
Ted Kremenek74556a12009-03-26 03:35:11 +00001774 if (Sym)
1775 Out << Sym->getSymbolID();
Ted Kremenek681fb352009-03-20 17:34:15 +00001776 else
1777 Out << "<pool>";
1778 Out << ":{";
1779
1780 // Get the contents of the pool.
1781 if (const ARCounts *cnts = state->get<AutoreleasePoolContents>(Sym))
1782 for (ARCounts::iterator J=cnts->begin(), EJ=cnts->end(); J != EJ; ++J)
1783 Out << '(' << J.getKey() << ',' << J.getData() << ')';
1784
1785 Out << '}';
1786}
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001787
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001788void CFRefCount::BindingsPrinter::Print(std::ostream& Out, const GRState* state,
1789 const char* nl, const char* sep) {
Ted Kremenek681fb352009-03-20 17:34:15 +00001790
1791
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001792
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001793 RefBindings B = state->get<RefBindings>();
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001794
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001795 if (!B.isEmpty())
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001796 Out << sep << nl;
1797
1798 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
1799 Out << (*I).first << " : ";
1800 (*I).second.print(Out);
1801 Out << nl;
1802 }
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001803
1804 // Print the autorelease stack.
Ted Kremenek681fb352009-03-20 17:34:15 +00001805 Out << sep << nl << "AR pool stack:";
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001806 ARStack stack = state->get<AutoreleaseStack>();
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001807
Ted Kremenek681fb352009-03-20 17:34:15 +00001808 PrintPool(Out, SymbolRef(), state); // Print the caller's pool.
1809 for (ARStack::iterator I=stack.begin(), E=stack.end(); I!=E; ++I)
1810 PrintPool(Out, *I, state);
1811
1812 Out << nl;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001813}
1814
Ted Kremenek47a72422009-04-29 18:50:19 +00001815//===----------------------------------------------------------------------===//
1816// Error reporting.
1817//===----------------------------------------------------------------------===//
1818
1819namespace {
1820
1821 //===-------------===//
1822 // Bug Descriptions. //
1823 //===-------------===//
1824
1825 class VISIBILITY_HIDDEN CFRefBug : public BugType {
1826 protected:
1827 CFRefCount& TF;
1828
1829 CFRefBug(CFRefCount* tf, const char* name)
1830 : BugType(name, "Memory (Core Foundation/Objective-C)"), TF(*tf) {}
1831 public:
1832
1833 CFRefCount& getTF() { return TF; }
1834 const CFRefCount& getTF() const { return TF; }
1835
1836 // FIXME: Eventually remove.
1837 virtual const char* getDescription() const = 0;
1838
1839 virtual bool isLeak() const { return false; }
1840 };
1841
1842 class VISIBILITY_HIDDEN UseAfterRelease : public CFRefBug {
1843 public:
1844 UseAfterRelease(CFRefCount* tf)
1845 : CFRefBug(tf, "Use-after-release") {}
1846
1847 const char* getDescription() const {
1848 return "Reference-counted object is used after it is released";
1849 }
1850 };
1851
1852 class VISIBILITY_HIDDEN BadRelease : public CFRefBug {
1853 public:
1854 BadRelease(CFRefCount* tf) : CFRefBug(tf, "Bad release") {}
1855
1856 const char* getDescription() const {
1857 return "Incorrect decrement of the reference count of an "
1858 "object is not owned at this point by the caller";
1859 }
1860 };
1861
1862 class VISIBILITY_HIDDEN DeallocGC : public CFRefBug {
1863 public:
1864 DeallocGC(CFRefCount *tf) : CFRefBug(tf,
1865 "-dealloc called while using GC") {}
1866
1867 const char *getDescription() const {
1868 return "-dealloc called while using GC";
1869 }
1870 };
1871
1872 class VISIBILITY_HIDDEN DeallocNotOwned : public CFRefBug {
1873 public:
1874 DeallocNotOwned(CFRefCount *tf) : CFRefBug(tf,
1875 "-dealloc sent to non-exclusively owned object") {}
1876
1877 const char *getDescription() const {
1878 return "-dealloc sent to object that may be referenced elsewhere";
1879 }
1880 };
1881
1882 class VISIBILITY_HIDDEN Leak : public CFRefBug {
1883 const bool isReturn;
1884 protected:
1885 Leak(CFRefCount* tf, const char* name, bool isRet)
1886 : CFRefBug(tf, name), isReturn(isRet) {}
1887 public:
1888
1889 const char* getDescription() const { return ""; }
1890
1891 bool isLeak() const { return true; }
1892 };
1893
1894 class VISIBILITY_HIDDEN LeakAtReturn : public Leak {
1895 public:
1896 LeakAtReturn(CFRefCount* tf, const char* name)
1897 : Leak(tf, name, true) {}
1898 };
1899
1900 class VISIBILITY_HIDDEN LeakWithinFunction : public Leak {
1901 public:
1902 LeakWithinFunction(CFRefCount* tf, const char* name)
1903 : Leak(tf, name, false) {}
1904 };
1905
1906 //===---------===//
1907 // Bug Reports. //
1908 //===---------===//
1909
1910 class VISIBILITY_HIDDEN CFRefReport : public RangedBugReport {
1911 protected:
1912 SymbolRef Sym;
1913 const CFRefCount &TF;
1914 public:
1915 CFRefReport(CFRefBug& D, const CFRefCount &tf,
1916 ExplodedNode<GRState> *n, SymbolRef sym)
1917 : RangedBugReport(D, D.getDescription(), n), Sym(sym), TF(tf) {}
1918
1919 virtual ~CFRefReport() {}
1920
1921 CFRefBug& getBugType() {
1922 return (CFRefBug&) RangedBugReport::getBugType();
1923 }
1924 const CFRefBug& getBugType() const {
1925 return (const CFRefBug&) RangedBugReport::getBugType();
1926 }
1927
1928 virtual void getRanges(BugReporter& BR, const SourceRange*& beg,
1929 const SourceRange*& end) {
1930
1931 if (!getBugType().isLeak())
1932 RangedBugReport::getRanges(BR, beg, end);
1933 else
1934 beg = end = 0;
1935 }
1936
1937 SymbolRef getSymbol() const { return Sym; }
1938
1939 PathDiagnosticPiece* getEndPath(BugReporter& BR,
1940 const ExplodedNode<GRState>* N);
1941
1942 std::pair<const char**,const char**> getExtraDescriptiveText();
1943
1944 PathDiagnosticPiece* VisitNode(const ExplodedNode<GRState>* N,
1945 const ExplodedNode<GRState>* PrevN,
1946 const ExplodedGraph<GRState>& G,
1947 BugReporter& BR,
1948 NodeResolver& NR);
1949 };
1950
1951 class VISIBILITY_HIDDEN CFRefLeakReport : public CFRefReport {
1952 SourceLocation AllocSite;
1953 const MemRegion* AllocBinding;
1954 public:
1955 CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
1956 ExplodedNode<GRState> *n, SymbolRef sym,
1957 GRExprEngine& Eng);
1958
1959 PathDiagnosticPiece* getEndPath(BugReporter& BR,
1960 const ExplodedNode<GRState>* N);
1961
1962 SourceLocation getLocation() const { return AllocSite; }
1963 };
1964} // end anonymous namespace
1965
1966void CFRefCount::RegisterChecks(BugReporter& BR) {
1967 useAfterRelease = new UseAfterRelease(this);
1968 BR.Register(useAfterRelease);
1969
1970 releaseNotOwned = new BadRelease(this);
1971 BR.Register(releaseNotOwned);
1972
1973 deallocGC = new DeallocGC(this);
1974 BR.Register(deallocGC);
1975
1976 deallocNotOwned = new DeallocNotOwned(this);
1977 BR.Register(deallocNotOwned);
1978
1979 // First register "return" leaks.
1980 const char* name = 0;
1981
1982 if (isGCEnabled())
1983 name = "Leak of returned object when using garbage collection";
1984 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
1985 name = "Leak of returned object when not using garbage collection (GC) in "
1986 "dual GC/non-GC code";
1987 else {
1988 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
1989 name = "Leak of returned object";
1990 }
1991
1992 leakAtReturn = new LeakAtReturn(this, name);
1993 BR.Register(leakAtReturn);
1994
1995 // Second, register leaks within a function/method.
1996 if (isGCEnabled())
1997 name = "Leak of object when using garbage collection";
1998 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
1999 name = "Leak of 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";
2004 }
2005
2006 leakWithinFunction = new LeakWithinFunction(this, name);
2007 BR.Register(leakWithinFunction);
2008
2009 // Save the reference to the BugReporter.
2010 this->BR = &BR;
2011}
2012
2013static const char* Msgs[] = {
2014 // GC only
2015 "Code is compiled to only use garbage collection",
2016 // No GC.
2017 "Code is compiled to use reference counts",
2018 // Hybrid, with GC.
2019 "Code is compiled to use either garbage collection (GC) or reference counts"
2020 " (non-GC). The bug occurs with GC enabled",
2021 // Hybrid, without GC
2022 "Code is compiled to use either garbage collection (GC) or reference counts"
2023 " (non-GC). The bug occurs in non-GC mode"
2024};
2025
2026std::pair<const char**,const char**> CFRefReport::getExtraDescriptiveText() {
2027 CFRefCount& TF = static_cast<CFRefBug&>(getBugType()).getTF();
2028
2029 switch (TF.getLangOptions().getGCMode()) {
2030 default:
2031 assert(false);
2032
2033 case LangOptions::GCOnly:
2034 assert (TF.isGCEnabled());
2035 return std::make_pair(&Msgs[0], &Msgs[0]+1);
2036
2037 case LangOptions::NonGC:
2038 assert (!TF.isGCEnabled());
2039 return std::make_pair(&Msgs[1], &Msgs[1]+1);
2040
2041 case LangOptions::HybridGC:
2042 if (TF.isGCEnabled())
2043 return std::make_pair(&Msgs[2], &Msgs[2]+1);
2044 else
2045 return std::make_pair(&Msgs[3], &Msgs[3]+1);
2046 }
2047}
2048
2049static inline bool contains(const llvm::SmallVectorImpl<ArgEffect>& V,
2050 ArgEffect X) {
2051 for (llvm::SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
2052 I!=E; ++I)
2053 if (*I == X) return true;
2054
2055 return false;
2056}
2057
2058PathDiagnosticPiece* CFRefReport::VisitNode(const ExplodedNode<GRState>* N,
2059 const ExplodedNode<GRState>* PrevN,
2060 const ExplodedGraph<GRState>& G,
2061 BugReporter& BR,
2062 NodeResolver& NR) {
2063
2064 // Check if the type state has changed.
2065 GRStateManager &StMgr = cast<GRBugReporter>(BR).getStateManager();
2066 GRStateRef PrevSt(PrevN->getState(), StMgr);
2067 GRStateRef CurrSt(N->getState(), StMgr);
2068
2069 const RefVal* CurrT = CurrSt.get<RefBindings>(Sym);
2070 if (!CurrT) return NULL;
2071
2072 const RefVal& CurrV = *CurrT;
2073 const RefVal* PrevT = PrevSt.get<RefBindings>(Sym);
2074
2075 // Create a string buffer to constain all the useful things we want
2076 // to tell the user.
2077 std::string sbuf;
2078 llvm::raw_string_ostream os(sbuf);
2079
2080 // This is the allocation site since the previous node had no bindings
2081 // for this symbol.
2082 if (!PrevT) {
2083 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2084
2085 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2086 // Get the name of the callee (if it is available).
2087 SVal X = CurrSt.GetSValAsScalarOrLoc(CE->getCallee());
2088 if (const FunctionDecl* FD = X.getAsFunctionDecl())
2089 os << "Call to function '" << FD->getNameAsString() <<'\'';
2090 else
2091 os << "function call";
2092 }
2093 else {
2094 assert (isa<ObjCMessageExpr>(S));
2095 os << "Method";
2096 }
2097
2098 if (CurrV.getObjKind() == RetEffect::CF) {
2099 os << " returns a Core Foundation object with a ";
2100 }
2101 else {
2102 assert (CurrV.getObjKind() == RetEffect::ObjC);
2103 os << " returns an Objective-C object with a ";
2104 }
2105
2106 if (CurrV.isOwned()) {
2107 os << "+1 retain count (owning reference).";
2108
2109 if (static_cast<CFRefBug&>(getBugType()).getTF().isGCEnabled()) {
2110 assert(CurrV.getObjKind() == RetEffect::CF);
2111 os << " "
2112 "Core Foundation objects are not automatically garbage collected.";
2113 }
2114 }
2115 else {
2116 assert (CurrV.isNotOwned());
2117 os << "+0 retain count (non-owning reference).";
2118 }
2119
2120 PathDiagnosticLocation Pos(S, BR.getContext().getSourceManager());
2121 return new PathDiagnosticEventPiece(Pos, os.str());
2122 }
2123
2124 // Gather up the effects that were performed on the object at this
2125 // program point
2126 llvm::SmallVector<ArgEffect, 2> AEffects;
2127
2128 if (const RetainSummary *Summ = TF.getSummaryOfNode(NR.getOriginalNode(N))) {
2129 // We only have summaries attached to nodes after evaluating CallExpr and
2130 // ObjCMessageExprs.
2131 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2132
2133 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2134 // Iterate through the parameter expressions and see if the symbol
2135 // was ever passed as an argument.
2136 unsigned i = 0;
2137
2138 for (CallExpr::arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
2139 AI!=AE; ++AI, ++i) {
2140
2141 // Retrieve the value of the argument. Is it the symbol
2142 // we are interested in?
2143 if (CurrSt.GetSValAsScalarOrLoc(*AI).getAsLocSymbol() != Sym)
2144 continue;
2145
2146 // We have an argument. Get the effect!
2147 AEffects.push_back(Summ->getArg(i));
2148 }
2149 }
2150 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
2151 if (Expr *receiver = ME->getReceiver())
2152 if (CurrSt.GetSValAsScalarOrLoc(receiver).getAsLocSymbol() == Sym) {
2153 // The symbol we are tracking is the receiver.
2154 AEffects.push_back(Summ->getReceiverEffect());
2155 }
2156 }
2157 }
2158
2159 do {
2160 // Get the previous type state.
2161 RefVal PrevV = *PrevT;
2162
2163 // Specially handle -dealloc.
2164 if (!TF.isGCEnabled() && contains(AEffects, Dealloc)) {
2165 // Determine if the object's reference count was pushed to zero.
2166 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2167 // We may not have transitioned to 'release' if we hit an error.
2168 // This case is handled elsewhere.
2169 if (CurrV.getKind() == RefVal::Released) {
2170 assert(CurrV.getCount() == 0);
2171 os << "Object released by directly sending the '-dealloc' message";
2172 break;
2173 }
2174 }
2175
2176 // Specially handle CFMakeCollectable and friends.
2177 if (contains(AEffects, MakeCollectable)) {
2178 // Get the name of the function.
2179 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2180 SVal X = CurrSt.GetSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee());
2181 const FunctionDecl* FD = X.getAsFunctionDecl();
2182 const std::string& FName = FD->getNameAsString();
2183
2184 if (TF.isGCEnabled()) {
2185 // Determine if the object's reference count was pushed to zero.
2186 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2187
2188 os << "In GC mode a call to '" << FName
2189 << "' decrements an object's retain count and registers the "
2190 "object with the garbage collector. ";
2191
2192 if (CurrV.getKind() == RefVal::Released) {
2193 assert(CurrV.getCount() == 0);
2194 os << "Since it now has a 0 retain count the object can be "
2195 "automatically collected by the garbage collector.";
2196 }
2197 else
2198 os << "An object must have a 0 retain count to be garbage collected. "
2199 "After this call its retain count is +" << CurrV.getCount()
2200 << '.';
2201 }
2202 else
2203 os << "When GC is not enabled a call to '" << FName
2204 << "' has no effect on its argument.";
2205
2206 // Nothing more to say.
2207 break;
2208 }
2209
2210 // Determine if the typestate has changed.
2211 if (!(PrevV == CurrV))
2212 switch (CurrV.getKind()) {
2213 case RefVal::Owned:
2214 case RefVal::NotOwned:
2215
2216 if (PrevV.getCount() == CurrV.getCount())
2217 return 0;
2218
2219 if (PrevV.getCount() > CurrV.getCount())
2220 os << "Reference count decremented.";
2221 else
2222 os << "Reference count incremented.";
2223
2224 if (unsigned Count = CurrV.getCount())
2225 os << " The object now has a +" << Count << " retain count.";
2226
2227 if (PrevV.getKind() == RefVal::Released) {
2228 assert(TF.isGCEnabled() && CurrV.getCount() > 0);
2229 os << " The object is not eligible for garbage collection until the "
2230 "retain count reaches 0 again.";
2231 }
2232
2233 break;
2234
2235 case RefVal::Released:
2236 os << "Object released.";
2237 break;
2238
2239 case RefVal::ReturnedOwned:
2240 os << "Object returned to caller as an owning reference (single retain "
2241 "count transferred to caller).";
2242 break;
2243
2244 case RefVal::ReturnedNotOwned:
2245 os << "Object returned to caller with a +0 (non-owning) retain count.";
2246 break;
2247
2248 default:
2249 return NULL;
2250 }
2251
2252 // Emit any remaining diagnostics for the argument effects (if any).
2253 for (llvm::SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
2254 E=AEffects.end(); I != E; ++I) {
2255
2256 // A bunch of things have alternate behavior under GC.
2257 if (TF.isGCEnabled())
2258 switch (*I) {
2259 default: break;
2260 case Autorelease:
2261 os << "In GC mode an 'autorelease' has no effect.";
2262 continue;
2263 case IncRefMsg:
2264 os << "In GC mode the 'retain' message has no effect.";
2265 continue;
2266 case DecRefMsg:
2267 os << "In GC mode the 'release' message has no effect.";
2268 continue;
2269 }
2270 }
2271 } while(0);
2272
2273 if (os.str().empty())
2274 return 0; // We have nothing to say!
2275
2276 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2277 PathDiagnosticLocation Pos(S, BR.getContext().getSourceManager());
2278 PathDiagnosticPiece* P = new PathDiagnosticEventPiece(Pos, os.str());
2279
2280 // Add the range by scanning the children of the statement for any bindings
2281 // to Sym.
2282 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I)
2283 if (Expr* Exp = dyn_cast_or_null<Expr>(*I))
2284 if (CurrSt.GetSValAsScalarOrLoc(Exp).getAsLocSymbol() == Sym) {
2285 P->addRange(Exp->getSourceRange());
2286 break;
2287 }
2288
2289 return P;
2290}
2291
2292namespace {
2293 class VISIBILITY_HIDDEN FindUniqueBinding :
2294 public StoreManager::BindingsHandler {
2295 SymbolRef Sym;
2296 const MemRegion* Binding;
2297 bool First;
2298
2299 public:
2300 FindUniqueBinding(SymbolRef sym) : Sym(sym), Binding(0), First(true) {}
2301
2302 bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
2303 SVal val) {
2304
2305 SymbolRef SymV = val.getAsSymbol();
2306 if (!SymV || SymV != Sym)
2307 return true;
2308
2309 if (Binding) {
2310 First = false;
2311 return false;
2312 }
2313 else
2314 Binding = R;
2315
2316 return true;
2317 }
2318
2319 operator bool() { return First && Binding; }
2320 const MemRegion* getRegion() { return Binding; }
2321 };
2322}
2323
2324static std::pair<const ExplodedNode<GRState>*,const MemRegion*>
2325GetAllocationSite(GRStateManager& StateMgr, const ExplodedNode<GRState>* N,
2326 SymbolRef Sym) {
2327
2328 // Find both first node that referred to the tracked symbol and the
2329 // memory location that value was store to.
2330 const ExplodedNode<GRState>* Last = N;
2331 const MemRegion* FirstBinding = 0;
2332
2333 while (N) {
2334 const GRState* St = N->getState();
2335 RefBindings B = St->get<RefBindings>();
2336
2337 if (!B.lookup(Sym))
2338 break;
2339
2340 FindUniqueBinding FB(Sym);
2341 StateMgr.iterBindings(St, FB);
2342 if (FB) FirstBinding = FB.getRegion();
2343
2344 Last = N;
2345 N = N->pred_empty() ? NULL : *(N->pred_begin());
2346 }
2347
2348 return std::make_pair(Last, FirstBinding);
2349}
2350
2351PathDiagnosticPiece*
2352CFRefReport::getEndPath(BugReporter& br, const ExplodedNode<GRState>* EndN) {
2353 // Tell the BugReporter to report cases when the tracked symbol is
2354 // assigned to different variables, etc.
2355 GRBugReporter& BR = cast<GRBugReporter>(br);
2356 cast<GRBugReporter>(BR).addNotableSymbol(Sym);
2357 return RangedBugReport::getEndPath(BR, EndN);
2358}
2359
2360PathDiagnosticPiece*
2361CFRefLeakReport::getEndPath(BugReporter& br, const ExplodedNode<GRState>* EndN){
2362
2363 GRBugReporter& BR = cast<GRBugReporter>(br);
2364 // Tell the BugReporter to report cases when the tracked symbol is
2365 // assigned to different variables, etc.
2366 cast<GRBugReporter>(BR).addNotableSymbol(Sym);
2367
2368 // We are reporting a leak. Walk up the graph to get to the first node where
2369 // the symbol appeared, and also get the first VarDecl that tracked object
2370 // is stored to.
2371 const ExplodedNode<GRState>* AllocNode = 0;
2372 const MemRegion* FirstBinding = 0;
2373
2374 llvm::tie(AllocNode, FirstBinding) =
2375 GetAllocationSite(BR.getStateManager(), EndN, Sym);
2376
2377 // Get the allocate site.
2378 assert(AllocNode);
2379 Stmt* FirstStmt = cast<PostStmt>(AllocNode->getLocation()).getStmt();
2380
2381 SourceManager& SMgr = BR.getContext().getSourceManager();
2382 unsigned AllocLine =SMgr.getInstantiationLineNumber(FirstStmt->getLocStart());
2383
2384 // Compute an actual location for the leak. Sometimes a leak doesn't
2385 // occur at an actual statement (e.g., transition between blocks; end
2386 // of function) so we need to walk the graph and compute a real location.
2387 const ExplodedNode<GRState>* LeakN = EndN;
2388 PathDiagnosticLocation L;
2389
2390 while (LeakN) {
2391 ProgramPoint P = LeakN->getLocation();
2392
2393 if (const PostStmt *PS = dyn_cast<PostStmt>(&P)) {
2394 L = PathDiagnosticLocation(PS->getStmt()->getLocStart(), SMgr);
2395 break;
2396 }
2397 else if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
2398 if (const Stmt* Term = BE->getSrc()->getTerminator()) {
2399 L = PathDiagnosticLocation(Term->getLocStart(), SMgr);
2400 break;
2401 }
2402 }
2403
2404 LeakN = LeakN->succ_empty() ? 0 : *(LeakN->succ_begin());
2405 }
2406
2407 if (!L.isValid()) {
Ted Kremenek0a6913d2009-04-29 21:31:59 +00002408 const Decl &D = BR.getStateManager().getCodeDecl();
2409 L = PathDiagnosticLocation(D.getBodyRBrace(BR.getContext()), SMgr);
Ted Kremenek47a72422009-04-29 18:50:19 +00002410 }
2411
2412 std::string sbuf;
2413 llvm::raw_string_ostream os(sbuf);
2414
2415 os << "Object allocated on line " << AllocLine;
2416
2417 if (FirstBinding)
2418 os << " and stored into '" << FirstBinding->getString() << '\'';
2419
2420 // Get the retain count.
2421 const RefVal* RV = EndN->getState()->get<RefBindings>(Sym);
2422
2423 if (RV->getKind() == RefVal::ErrorLeakReturned) {
2424 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
2425 // ojbects. Only "copy", "alloc", "retain" and "new" transfer ownership
2426 // to the caller for NS objects.
2427 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(BR.getGraph().getCodeDecl());
2428 os << " is returned from a method whose name ('"
Ted Kremenek314b1952009-04-29 23:03:22 +00002429 << MD.getSelector().getAsString()
Ted Kremenek47a72422009-04-29 18:50:19 +00002430 << "') does not contain 'copy' or otherwise starts with"
2431 " 'new' or 'alloc'. This violates the naming convention rules given"
Ted Kremenek2a410c92009-04-29 22:25:52 +00002432 " in the Memory Management Guide for Cocoa (object leaked)";
Ted Kremenek47a72422009-04-29 18:50:19 +00002433 }
2434 else
2435 os << " is no longer referenced after this point and has a retain count of"
Ted Kremenek2a410c92009-04-29 22:25:52 +00002436 " +" << RV->getCount() << " (object leaked)";
Ted Kremenek47a72422009-04-29 18:50:19 +00002437
2438 return new PathDiagnosticEventPiece(L, os.str());
2439}
2440
2441
2442CFRefLeakReport::CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2443 ExplodedNode<GRState> *n,
2444 SymbolRef sym, GRExprEngine& Eng)
2445: CFRefReport(D, tf, n, sym)
2446{
2447
2448 // Most bug reports are cached at the location where they occured.
2449 // With leaks, we want to unique them by the location where they were
2450 // allocated, and only report a single path. To do this, we need to find
2451 // the allocation site of a piece of tracked memory, which we do via a
2452 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2453 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2454 // that all ancestor nodes that represent the allocation site have the
2455 // same SourceLocation.
2456 const ExplodedNode<GRState>* AllocNode = 0;
2457
2458 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding.
2459 GetAllocationSite(Eng.getStateManager(), getEndNode(), getSymbol());
2460
2461 // Get the SourceLocation for the allocation site.
2462 ProgramPoint P = AllocNode->getLocation();
2463 AllocSite = cast<PostStmt>(P).getStmt()->getLocStart();
2464
2465 // Fill in the description of the bug.
2466 Description.clear();
2467 llvm::raw_string_ostream os(Description);
2468 SourceManager& SMgr = Eng.getContext().getSourceManager();
2469 unsigned AllocLine = SMgr.getInstantiationLineNumber(AllocSite);
Ted Kremenek2e9d0302009-05-02 19:05:19 +00002470 os << "Potential leak ";
2471 if (tf.isGCEnabled()) {
2472 os << "(when using garbage collection) ";
2473 }
2474 os << "of an object allocated on line " << AllocLine;
Ted Kremenek47a72422009-04-29 18:50:19 +00002475
2476 // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2477 if (AllocBinding)
2478 os << " and stored into '" << AllocBinding->getString() << '\'';
2479}
2480
2481//===----------------------------------------------------------------------===//
2482// Main checker logic.
2483//===----------------------------------------------------------------------===//
2484
Ted Kremenek272aa852008-06-25 21:21:56 +00002485/// GetReturnType - Used to get the return type of a message expression or
2486/// function call with the intention of affixing that type to a tracked symbol.
2487/// While the the return type can be queried directly from RetEx, when
2488/// invoking class methods we augment to the return type to be that of
2489/// a pointer to the class (as opposed it just being id).
2490static QualType GetReturnType(Expr* RetE, ASTContext& Ctx) {
2491
2492 QualType RetTy = RetE->getType();
2493
2494 // FIXME: We aren't handling id<...>.
Chris Lattnerb724ab22008-07-26 22:36:27 +00002495 const PointerType* PT = RetTy->getAsPointerType();
Ted Kremenek272aa852008-06-25 21:21:56 +00002496 if (!PT)
2497 return RetTy;
2498
2499 // If RetEx is not a message expression just return its type.
2500 // If RetEx is a message expression, return its types if it is something
2501 /// more specific than id.
2502
2503 ObjCMessageExpr* ME = dyn_cast<ObjCMessageExpr>(RetE);
2504
Steve Naroff17c03822009-02-12 17:52:19 +00002505 if (!ME || !Ctx.isObjCIdStructType(PT->getPointeeType()))
Ted Kremenek272aa852008-06-25 21:21:56 +00002506 return RetTy;
2507
2508 ObjCInterfaceDecl* D = ME->getClassInfo().first;
2509
2510 // At this point we know the return type of the message expression is id.
2511 // If we have an ObjCInterceDecl, we know this is a call to a class method
2512 // whose type we can resolve. In such cases, promote the return type to
2513 // Class*.
2514 return !D ? RetTy : Ctx.getPointerType(Ctx.getObjCInterfaceType(D));
2515}
2516
2517
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002518void CFRefCount::EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002519 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002520 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002521 Expr* Ex,
2522 Expr* Receiver,
Ted Kremenek286e9852009-05-04 04:57:00 +00002523 const RetainSummary& Summ,
Zhongxing Xucac107a2009-04-20 05:24:46 +00002524 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002525 ExplodedNode<GRState>* Pred) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002526
Ted Kremeneka7338b42008-03-11 06:39:11 +00002527 // Get the state.
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002528 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenek0106e202008-10-24 20:32:50 +00002529 ASTContext& Ctx = Eng.getStateManager().getContext();
Ted Kremenek227c5372008-05-06 02:41:27 +00002530
2531 // Evaluate the effect of the arguments.
Ted Kremenek1feab292008-04-16 04:28:53 +00002532 RefVal::Kind hasErr = (RefVal::Kind) 0;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002533 unsigned idx = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002534 Expr* ErrorExpr = NULL;
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002535 SymbolRef ErrorSym = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002536
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002537 for (ExprIterator I = arg_beg; I != arg_end; ++I, ++idx) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002538 SVal V = state.GetSValAsScalarOrLoc(*I);
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002539 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002540
Ted Kremenek74556a12009-03-26 03:35:11 +00002541 if (Sym)
Ted Kremenekb6578942009-02-24 19:15:11 +00002542 if (RefBindings::data_type* T = state.get<RefBindings>(Sym)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002543 state = Update(state, Sym, *T, Summ.getArg(idx), hasErr);
Ted Kremenekb6578942009-02-24 19:15:11 +00002544 if (hasErr) {
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002545 ErrorExpr = *I;
Ted Kremenek6064a362008-07-07 16:21:19 +00002546 ErrorSym = Sym;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002547 break;
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002548 }
2549 continue;
Ted Kremenekb6578942009-02-24 19:15:11 +00002550 }
Ted Kremenekede40b72008-07-09 18:11:16 +00002551
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002552 if (isa<Loc>(V)) {
2553 if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(&V)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002554 if (Summ.getArg(idx) == DoNothingByRef)
Ted Kremenekede40b72008-07-09 18:11:16 +00002555 continue;
2556
2557 // Invalidate the value of the variable passed by reference.
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002558
2559 // FIXME: Either this logic should also be replicated in GRSimpleVals
2560 // or should be pulled into a separate "constraint engine."
Ted Kremenekede40b72008-07-09 18:11:16 +00002561
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002562 // FIXME: We can have collisions on the conjured symbol if the
2563 // expression *I also creates conjured symbols. We probably want
2564 // to identify conjured symbols by an expression pair: the enclosing
2565 // expression (the context) and the expression itself. This should
Ted Kremenekede40b72008-07-09 18:11:16 +00002566 // disambiguate conjured symbols.
Ted Kremenekb15eba42008-10-04 05:50:14 +00002567
Ted Kremenek38a4b4b2008-10-17 20:28:54 +00002568 const TypedRegion* R = dyn_cast<TypedRegion>(MR->getRegion());
Zhongxing Xub9d47a42009-04-29 02:30:09 +00002569
Ted Kremenek53b24182009-03-04 22:56:43 +00002570 if (R) {
Ted Kremenek618c6cd2008-12-18 23:34:57 +00002571 // Is the invalidated variable something that we were tracking?
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002572 SymbolRef Sym = state.GetSValAsScalarOrLoc(R).getAsLocSymbol();
Ted Kremenek618c6cd2008-12-18 23:34:57 +00002573
Ted Kremenek53b24182009-03-04 22:56:43 +00002574 // Remove any existing reference-count binding.
Ted Kremenek74556a12009-03-26 03:35:11 +00002575 if (Sym) state = state.remove<RefBindings>(Sym);
Ted Kremenekb15eba42008-10-04 05:50:14 +00002576
Ted Kremenek53b24182009-03-04 22:56:43 +00002577 if (R->isBoundable(Ctx)) {
2578 // Set the value of the variable to be a conjured symbol.
2579 unsigned Count = Builder.getCurrentBlockCount();
2580 QualType T = R->getRValueType(Ctx);
2581
Zhongxing Xu079dc352009-04-09 06:03:54 +00002582 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())){
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002583 ValueManager &ValMgr = Eng.getValueManager();
2584 SVal V = ValMgr.getConjuredSymbolVal(*I, T, Count);
Zhongxing Xu079dc352009-04-09 06:03:54 +00002585 state = state.BindLoc(Loc::MakeVal(R), V);
Ted Kremenek53b24182009-03-04 22:56:43 +00002586 }
2587 else if (const RecordType *RT = T->getAsStructureType()) {
2588 // Handle structs in a not so awesome way. Here we just
2589 // eagerly bind new symbols to the fields. In reality we
2590 // should have the store manager handle this. The idea is just
2591 // to prototype some basic functionality here. All of this logic
2592 // should one day soon just go away.
2593 const RecordDecl *RD = RT->getDecl()->getDefinition(Ctx);
2594
2595 // No record definition. There is nothing we can do.
2596 if (!RD)
2597 continue;
2598
2599 MemRegionManager &MRMgr = state.getManager().getRegionManager();
2600
2601 // Iterate through the fields and construct new symbols.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002602 for (RecordDecl::field_iterator FI=RD->field_begin(Ctx),
2603 FE=RD->field_end(Ctx); FI!=FE; ++FI) {
Ted Kremenek53b24182009-03-04 22:56:43 +00002604
2605 // For now just handle scalar fields.
2606 FieldDecl *FD = *FI;
2607 QualType FT = FD->getType();
2608
2609 if (Loc::IsLocType(FT) ||
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002610 (FT->isIntegerType() && FT->isScalarType())) {
Ted Kremenek53b24182009-03-04 22:56:43 +00002611 const FieldRegion* FR = MRMgr.getFieldRegion(FD, R);
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002612 ValueManager &ValMgr = Eng.getValueManager();
2613 SVal V = ValMgr.getConjuredSymbolVal(*I, FT, Count);
Zhongxing Xuc458e322009-04-09 06:32:20 +00002614 state = state.BindLoc(Loc::MakeVal(FR), V);
Ted Kremenek53b24182009-03-04 22:56:43 +00002615 }
2616 }
2617 }
2618 else {
2619 // Just blast away other values.
2620 state = state.BindLoc(*MR, UnknownVal());
2621 }
Ted Kremenek8f90e712008-10-17 22:23:12 +00002622 }
Ted Kremenekb15eba42008-10-04 05:50:14 +00002623 }
2624 else
Ted Kremenek09102db2008-11-12 19:22:09 +00002625 state = state.BindLoc(*MR, UnknownVal());
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002626 }
2627 else {
2628 // Nuke all other arguments passed by reference.
Zhongxing Xu097fc982008-10-17 05:57:07 +00002629 state = state.Unbind(cast<Loc>(V));
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002630 }
Ted Kremeneke4924202008-04-11 20:51:02 +00002631 }
Zhongxing Xu097fc982008-10-17 05:57:07 +00002632 else if (isa<nonloc::LocAsInteger>(V))
2633 state = state.Unbind(cast<nonloc::LocAsInteger>(V).getLoc());
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002634 }
Ted Kremenek1feab292008-04-16 04:28:53 +00002635
Ted Kremenek272aa852008-06-25 21:21:56 +00002636 // Evaluate the effect on the message receiver.
Ted Kremenek227c5372008-05-06 02:41:27 +00002637 if (!ErrorExpr && Receiver) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002638 SymbolRef Sym = state.GetSValAsScalarOrLoc(Receiver).getAsLocSymbol();
Ted Kremenek74556a12009-03-26 03:35:11 +00002639 if (Sym) {
Ted Kremenekb6578942009-02-24 19:15:11 +00002640 if (const RefVal* T = state.get<RefBindings>(Sym)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002641 state = Update(state, Sym, *T, Summ.getReceiverEffect(), hasErr);
Ted Kremenekb6578942009-02-24 19:15:11 +00002642 if (hasErr) {
Ted Kremenek227c5372008-05-06 02:41:27 +00002643 ErrorExpr = Receiver;
Ted Kremenek6064a362008-07-07 16:21:19 +00002644 ErrorSym = Sym;
Ted Kremenek227c5372008-05-06 02:41:27 +00002645 }
Ted Kremenekb6578942009-02-24 19:15:11 +00002646 }
Ted Kremenek227c5372008-05-06 02:41:27 +00002647 }
2648 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002649
Ted Kremenek272aa852008-06-25 21:21:56 +00002650 // Process any errors.
Ted Kremenek1feab292008-04-16 04:28:53 +00002651 if (hasErr) {
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002652 ProcessNonLeakError(Dst, Builder, Ex, ErrorExpr, Pred, state,
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002653 hasErr, ErrorSym);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002654 return;
Ted Kremenek0d721572008-03-11 17:48:22 +00002655 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002656
Ted Kremenekf2717b02008-07-18 17:24:20 +00002657 // Consult the summary for the return value.
Ted Kremenek286e9852009-05-04 04:57:00 +00002658 RetEffect RE = Summ.getRetEffect();
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002659
2660 switch (RE.getKind()) {
2661 default:
2662 assert (false && "Unhandled RetEffect."); break;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002663
Ted Kremenek8f90e712008-10-17 22:23:12 +00002664 case RetEffect::NoRet: {
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002665
Ted Kremenek455dd862008-04-11 20:23:24 +00002666 // Make up a symbol for the return value (not reference counted).
Ted Kremeneke4924202008-04-11 20:51:02 +00002667 // FIXME: This is basically copy-and-paste from GRSimpleVals. We
2668 // should compose behavior, not copy it.
Ted Kremenek455dd862008-04-11 20:23:24 +00002669
Ted Kremenek8f90e712008-10-17 22:23:12 +00002670 // FIXME: We eventually should handle structs and other compound types
2671 // that are returned by value.
2672
2673 QualType T = Ex->getType();
2674
Ted Kremenek79413a52008-11-13 06:10:40 +00002675 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())) {
Ted Kremenek455dd862008-04-11 20:23:24 +00002676 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002677 ValueManager &ValMgr = Eng.getValueManager();
2678 SVal X = ValMgr.getConjuredSymbolVal(Ex, T, Count);
Ted Kremenek09102db2008-11-12 19:22:09 +00002679 state = state.BindExpr(Ex, X, false);
Ted Kremenek455dd862008-04-11 20:23:24 +00002680 }
2681
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002682 break;
Ted Kremenek8f90e712008-10-17 22:23:12 +00002683 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002684
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002685 case RetEffect::Alias: {
Ted Kremenek272aa852008-06-25 21:21:56 +00002686 unsigned idx = RE.getIndex();
Ted Kremenek2719e982008-06-17 02:43:46 +00002687 assert (arg_end >= arg_beg);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002688 assert (idx < (unsigned) (arg_end - arg_beg));
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002689 SVal V = state.GetSValAsScalarOrLoc(*(arg_beg+idx));
Ted Kremenek09102db2008-11-12 19:22:09 +00002690 state = state.BindExpr(Ex, V, false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002691 break;
2692 }
2693
Ted Kremenek227c5372008-05-06 02:41:27 +00002694 case RetEffect::ReceiverAlias: {
2695 assert (Receiver);
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002696 SVal V = state.GetSValAsScalarOrLoc(Receiver);
Ted Kremenek09102db2008-11-12 19:22:09 +00002697 state = state.BindExpr(Ex, V, false);
Ted Kremenek227c5372008-05-06 02:41:27 +00002698 break;
2699 }
2700
Ted Kremenek6a1cc252008-06-23 18:02:52 +00002701 case RetEffect::OwnedAllocatedSymbol:
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002702 case RetEffect::OwnedSymbol: {
2703 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke9e726e2009-04-09 16:13:17 +00002704 ValueManager &ValMgr = Eng.getValueManager();
2705 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
2706 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
2707 state = state.set<RefBindings>(Sym, RefVal::makeOwned(RE.getObjKind(),
2708 RetT));
2709 state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenek45c52a12009-03-09 22:46:49 +00002710
2711 // FIXME: Add a flag to the checker where allocations are assumed to
2712 // *not fail.
2713#if 0
Ted Kremeneke62fd052009-01-28 22:27:59 +00002714 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) {
2715 bool isFeasible;
2716 state = state.Assume(loc::SymbolVal(Sym), true, isFeasible);
2717 assert(isFeasible && "Cannot assume fresh symbol is non-null.");
2718 }
Ted Kremenek45c52a12009-03-09 22:46:49 +00002719#endif
Ted Kremenek6a1cc252008-06-23 18:02:52 +00002720
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002721 break;
2722 }
Ted Kremenek382fb4e2009-04-27 19:14:45 +00002723
2724 case RetEffect::GCNotOwnedSymbol:
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002725 case RetEffect::NotOwnedSymbol: {
2726 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke9e726e2009-04-09 16:13:17 +00002727 ValueManager &ValMgr = Eng.getValueManager();
2728 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
2729 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
2730 state = state.set<RefBindings>(Sym, RefVal::makeNotOwned(RE.getObjKind(),
2731 RetT));
2732 state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002733 break;
2734 }
2735 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002736
Ted Kremenek0dd65012009-02-18 02:00:25 +00002737 // Generate a sink node if we are at the end of a path.
2738 GRExprEngine::NodeTy *NewNode =
Ted Kremenek286e9852009-05-04 04:57:00 +00002739 Summ.isEndPath() ? Builder.MakeSinkNode(Dst, Ex, Pred, state)
2740 : Builder.MakeNode(Dst, Ex, Pred, state);
Ted Kremenek0dd65012009-02-18 02:00:25 +00002741
2742 // Annotate the edge with summary we used.
Ted Kremenek286e9852009-05-04 04:57:00 +00002743 if (NewNode) SummaryLog[NewNode] = &Summ;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002744}
2745
2746
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002747void CFRefCount::EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002748 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002749 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu097fc982008-10-17 05:57:07 +00002750 CallExpr* CE, SVal L,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002751 ExplodedNode<GRState>* Pred) {
Zhongxing Xucac107a2009-04-20 05:24:46 +00002752 const FunctionDecl* FD = L.getAsFunctionDecl();
Ted Kremenek286e9852009-05-04 04:57:00 +00002753 RetainSummary* Summ = !FD ? Summaries.getDefaultSummary()
Zhongxing Xucac107a2009-04-20 05:24:46 +00002754 : Summaries.getSummary(const_cast<FunctionDecl*>(FD));
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002755
Ted Kremenek286e9852009-05-04 04:57:00 +00002756 assert(Summ);
2757 EvalSummary(Dst, Eng, Builder, CE, 0, *Summ,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002758 CE->arg_begin(), CE->arg_end(), Pred);
Ted Kremenek827f93b2008-03-06 00:08:09 +00002759}
Ted Kremeneka7338b42008-03-11 06:39:11 +00002760
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002761void CFRefCount::EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002762 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002763 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002764 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002765 ExplodedNode<GRState>* Pred) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002766 RetainSummary* Summ = 0;
Ted Kremenek33661802008-05-01 21:31:50 +00002767
Ted Kremenek272aa852008-06-25 21:21:56 +00002768 if (Expr* Receiver = ME->getReceiver()) {
2769 // We need the type-information of the tracked receiver object
2770 // Retrieve it from the state.
2771 ObjCInterfaceDecl* ID = 0;
2772
2773 // FIXME: Wouldn't it be great if this code could be reduced? It's just
2774 // a chain of lookups.
Ted Kremeneka821b792009-04-29 05:04:30 +00002775 // FIXME: Is this really working as expected? There are cases where
2776 // we just use the 'ID' from the message expression.
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002777 const GRState* St = Builder.GetState(Pred);
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002778 SVal V = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
Ted Kremenek272aa852008-06-25 21:21:56 +00002779
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002780 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenek74556a12009-03-26 03:35:11 +00002781 if (Sym) {
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002782 if (const RefVal* T = St->get<RefBindings>(Sym)) {
Ted Kremenek6064a362008-07-07 16:21:19 +00002783 QualType Ty = T->getType();
Ted Kremenek272aa852008-06-25 21:21:56 +00002784
2785 if (const PointerType* PT = Ty->getAsPointerType()) {
2786 QualType PointeeTy = PT->getPointeeType();
2787
2788 if (ObjCInterfaceType* IT = dyn_cast<ObjCInterfaceType>(PointeeTy))
2789 ID = IT->getDecl();
2790 }
2791 }
2792 }
2793
Ted Kremenek04e00302009-04-29 17:09:14 +00002794 // FIXME: The receiver could be a reference to a class, meaning that
2795 // we should use the class method.
2796 Summ = Summaries.getInstanceMethodSummary(ME, ID);
Ted Kremenek0106e202008-10-24 20:32:50 +00002797
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002798 // Special-case: are we sending a mesage to "self"?
2799 // This is a hack. When we have full-IP this should be removed.
2800 if (!Summ) {
2801 ObjCMethodDecl* MD =
2802 dyn_cast<ObjCMethodDecl>(&Eng.getGraph().getCodeDecl());
2803
2804 if (MD) {
2805 if (Expr* Receiver = ME->getReceiver()) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002806 SVal X = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002807 if (loc::MemRegionVal* L = dyn_cast<loc::MemRegionVal>(&X))
Ted Kremenek0106e202008-10-24 20:32:50 +00002808 if (L->getRegion() == Eng.getStateManager().getSelfRegion(St)) {
2809 // Create a summmary where all of the arguments "StopTracking".
2810 Summ = Summaries.getPersistentSummary(RetEffect::MakeNoRet(),
2811 DoNothing,
2812 StopTracking);
2813 }
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002814 }
2815 }
2816 }
Ted Kremenek272aa852008-06-25 21:21:56 +00002817 }
Ted Kremenek1feab292008-04-16 04:28:53 +00002818 else
Ted Kremenekb17fa952009-04-23 21:25:57 +00002819 Summ = Summaries.getClassMethodSummary(ME);
Ted Kremenek1feab292008-04-16 04:28:53 +00002820
Ted Kremenek286e9852009-05-04 04:57:00 +00002821 if (!Summ)
2822 Summ = Summaries.getDefaultSummary();
Ted Kremenekccbe79a2009-04-24 17:50:11 +00002823
Ted Kremenek286e9852009-05-04 04:57:00 +00002824 EvalSummary(Dst, Eng, Builder, ME, ME->getReceiver(), *Summ,
Ted Kremenek926abf22008-05-06 04:20:12 +00002825 ME->arg_begin(), ME->arg_end(), Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002826}
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002827
2828namespace {
2829class VISIBILITY_HIDDEN StopTrackingCallback : public SymbolVisitor {
2830 GRStateRef state;
2831public:
2832 StopTrackingCallback(GRStateRef st) : state(st) {}
2833 GRStateRef getState() { return state; }
2834
2835 bool VisitSymbol(SymbolRef sym) {
2836 state = state.remove<RefBindings>(sym);
2837 return true;
2838 }
Ted Kremenek926abf22008-05-06 04:20:12 +00002839
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002840 const GRState* getState() const { return state.getState(); }
2841};
2842} // end anonymous namespace
2843
2844
Ted Kremeneka42be302009-02-14 01:43:44 +00002845void CFRefCount::EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val) {
Ted Kremeneka42be302009-02-14 01:43:44 +00002846 // Are we storing to something that causes the value to "escape"?
Ted Kremenek7aef4842008-04-16 20:40:59 +00002847 bool escapes = false;
2848
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002849 // A value escapes in three possible cases (this may change):
2850 //
2851 // (1) we are binding to something that is not a memory region.
2852 // (2) we are binding to a memregion that does not have stack storage
2853 // (3) we are binding to a memregion with stack storage that the store
Ted Kremeneka42be302009-02-14 01:43:44 +00002854 // does not understand.
Ted Kremeneka42be302009-02-14 01:43:44 +00002855 GRStateRef state = B.getState();
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002856
Ted Kremeneka42be302009-02-14 01:43:44 +00002857 if (!isa<loc::MemRegionVal>(location))
Ted Kremenek7aef4842008-04-16 20:40:59 +00002858 escapes = true;
Ted Kremenekb15eba42008-10-04 05:50:14 +00002859 else {
Ted Kremeneka42be302009-02-14 01:43:44 +00002860 const MemRegion* R = cast<loc::MemRegionVal>(location).getRegion();
2861 escapes = !B.getStateManager().hasStackStorage(R);
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002862
2863 if (!escapes) {
2864 // To test (3), generate a new state with the binding removed. If it is
2865 // the same state, then it escapes (since the store cannot represent
2866 // the binding).
Ted Kremeneka42be302009-02-14 01:43:44 +00002867 escapes = (state == (state.BindLoc(cast<Loc>(location), UnknownVal())));
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002868 }
Ted Kremenekb15eba42008-10-04 05:50:14 +00002869 }
Ted Kremeneka42be302009-02-14 01:43:44 +00002870
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002871 // If our store can represent the binding and we aren't storing to something
2872 // that doesn't have local storage then just return and have the simulation
2873 // state continue as is.
2874 if (!escapes)
2875 return;
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002876
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002877 // Otherwise, find all symbols referenced by 'val' that we are tracking
2878 // and stop tracking them.
2879 B.MakeNode(state.scanReachableSymbols<StopTrackingCallback>(val).getState());
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002880}
2881
Ted Kremenek0106e202008-10-24 20:32:50 +00002882std::pair<GRStateRef,bool>
2883CFRefCount::HandleSymbolDeath(GRStateManager& VMgr,
2884 const GRState* St, const Decl* CD,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002885 SymbolRef sid,
Ted Kremenek0106e202008-10-24 20:32:50 +00002886 RefVal V, bool& hasLeak) {
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002887
Ted Kremenek47a72422009-04-29 18:50:19 +00002888 // Any remaining leaks?
Ted Kremenek311f3d42008-10-22 23:56:21 +00002889 hasLeak = V.isOwned() ||
2890 ((V.isNotOwned() || V.isReturnedOwned()) && V.getCount() > 0);
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002891
Ted Kremenek47a72422009-04-29 18:50:19 +00002892 GRStateRef state(St, VMgr);
2893
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002894 if (!hasLeak)
Ted Kremenek0106e202008-10-24 20:32:50 +00002895 return std::make_pair(state.remove<RefBindings>(sid), false);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002896
Ted Kremenek0106e202008-10-24 20:32:50 +00002897 return std::make_pair(state.set<RefBindings>(sid, V ^ RefVal::ErrorLeak),
2898 false);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002899}
2900
Ted Kremenek541db372008-04-24 23:57:27 +00002901
Ted Kremenekffefc352008-04-11 22:25:11 +00002902
Ted Kremenek541db372008-04-24 23:57:27 +00002903// Dead symbols.
2904
Ted Kremenek708af042009-02-05 06:50:21 +00002905
Ted Kremenek541db372008-04-24 23:57:27 +00002906
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002907 // Return statements.
2908
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002909void CFRefCount::EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002910 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002911 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002912 ReturnStmt* S,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002913 ExplodedNode<GRState>* Pred) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002914
2915 Expr* RetE = S->getRetValue();
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002916 if (!RetE)
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002917 return;
2918
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002919 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002920 SymbolRef Sym = state.GetSValAsScalarOrLoc(RetE).getAsLocSymbol();
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002921
Ted Kremenek74556a12009-03-26 03:35:11 +00002922 if (!Sym)
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002923 return;
2924
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002925 // Get the reference count binding (if any).
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002926 const RefVal* T = state.get<RefBindings>(Sym);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002927
2928 if (!T)
2929 return;
2930
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002931 // Change the reference count.
Ted Kremenek6064a362008-07-07 16:21:19 +00002932 RefVal X = *T;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002933
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002934 switch (X.getKind()) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002935 case RefVal::Owned: {
2936 unsigned cnt = X.getCount();
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00002937 assert (cnt > 0);
2938 X = RefVal::makeReturnedOwned(cnt - 1);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002939 break;
2940 }
2941
2942 case RefVal::NotOwned: {
2943 unsigned cnt = X.getCount();
2944 X = cnt ? RefVal::makeReturnedOwned(cnt - 1)
2945 : RefVal::makeReturnedNotOwned();
2946 break;
2947 }
2948
2949 default:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002950 return;
2951 }
2952
2953 // Update the binding.
Ted Kremenek91781202008-08-17 03:20:02 +00002954 state = state.set<RefBindings>(Sym, X);
Ted Kremenek47a72422009-04-29 18:50:19 +00002955 Pred = Builder.MakeNode(Dst, S, Pred, state);
2956
Ted Kremeneka208d0c2009-04-30 05:51:50 +00002957 // Did we cache out?
2958 if (!Pred)
2959 return;
2960
Ted Kremenek47a72422009-04-29 18:50:19 +00002961 // Any leaks or other errors?
2962 if (X.isReturnedOwned() && X.getCount() == 0) {
2963 const Decl *CD = &Eng.getStateManager().getCodeDecl();
2964
Ted Kremenek314b1952009-04-29 23:03:22 +00002965 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002966 const RetainSummary &Summ = *Summaries.getMethodSummary(MD);
2967 if (!Summ.getRetEffect().isOwned()) {
Ted Kremenek47a72422009-04-29 18:50:19 +00002968 static int ReturnOwnLeakTag = 0;
2969 state = state.set<RefBindings>(Sym, X ^ RefVal::ErrorLeakReturned);
Ted Kremenek47a72422009-04-29 18:50:19 +00002970 // Generate an error node.
Ted Kremeneka208d0c2009-04-30 05:51:50 +00002971 if (ExplodedNode<GRState> *N =
2972 Builder.generateNode(PostStmt(S, &ReturnOwnLeakTag), state, Pred)) {
2973 CFRefLeakReport *report =
2974 new CFRefLeakReport(*static_cast<CFRefBug*>(leakAtReturn), *this,
2975 N, Sym, Eng);
2976 BR->EmitReport(report);
2977 }
Ted Kremenek47a72422009-04-29 18:50:19 +00002978 }
2979 }
2980 }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002981}
2982
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002983// Assumptions.
2984
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002985const GRState* CFRefCount::EvalAssume(GRStateManager& VMgr,
2986 const GRState* St,
Zhongxing Xu097fc982008-10-17 05:57:07 +00002987 SVal Cond, bool Assumption,
Ted Kremenekf22f8682008-07-10 22:03:41 +00002988 bool& isFeasible) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002989
2990 // FIXME: We may add to the interface of EvalAssume the list of symbols
2991 // whose assumptions have changed. For now we just iterate through the
2992 // bindings and check if any of the tracked symbols are NULL. This isn't
2993 // too bad since the number of symbols we will track in practice are
2994 // probably small and EvalAssume is only called at branches and a few
2995 // other places.
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002996 RefBindings B = St->get<RefBindings>();
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002997
2998 if (B.isEmpty())
2999 return St;
3000
3001 bool changed = false;
Ted Kremenek91781202008-08-17 03:20:02 +00003002
3003 GRStateRef state(St, VMgr);
3004 RefBindings::Factory& RefBFactory = state.get_context<RefBindings>();
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003005
3006 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003007 // Check if the symbol is null (or equal to any constant).
3008 // If this is the case, stop tracking the symbol.
Zhongxing Xuc6b27d02008-08-29 14:52:36 +00003009 if (VMgr.getSymVal(St, I.getKey())) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003010 changed = true;
3011 B = RefBFactory.Remove(B, I.getKey());
3012 }
3013 }
3014
Ted Kremenek91781202008-08-17 03:20:02 +00003015 if (changed)
3016 state = state.set<RefBindings>(B);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003017
Ted Kremenek4ae925c2008-08-14 21:16:54 +00003018 return state;
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003019}
Ted Kremeneka7338b42008-03-11 06:39:11 +00003020
Ted Kremenekb6578942009-02-24 19:15:11 +00003021GRStateRef CFRefCount::Update(GRStateRef state, SymbolRef sym,
3022 RefVal V, ArgEffect E,
3023 RefVal::Kind& hasErr) {
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003024
3025 // In GC mode [... release] and [... retain] do nothing.
3026 switch (E) {
3027 default: break;
3028 case IncRefMsg: E = isGCEnabled() ? DoNothing : IncRef; break;
3029 case DecRefMsg: E = isGCEnabled() ? DoNothing : DecRef; break;
Ted Kremenek2126bef2009-02-18 21:57:45 +00003030 case MakeCollectable: E = isGCEnabled() ? DecRef : DoNothing; break;
Ted Kremenekaac82832009-02-23 17:45:03 +00003031 case NewAutoreleasePool: E = isGCEnabled() ? DoNothing :
3032 NewAutoreleasePool; break;
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003033 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00003034
Ted Kremenek6537a642009-03-17 19:42:23 +00003035 // Handle all use-after-releases.
3036 if (!isGCEnabled() && V.getKind() == RefVal::Released) {
3037 V = V ^ RefVal::ErrorUseAfterRelease;
3038 hasErr = V.getKind();
3039 return state.set<RefBindings>(sym, V);
3040 }
3041
Ted Kremenek0d721572008-03-11 17:48:22 +00003042 switch (E) {
3043 default:
3044 assert (false && "Unhandled CFRef transition.");
Ted Kremenek6537a642009-03-17 19:42:23 +00003045
3046 case Dealloc:
3047 // Any use of -dealloc in GC is *bad*.
3048 if (isGCEnabled()) {
3049 V = V ^ RefVal::ErrorDeallocGC;
3050 hasErr = V.getKind();
3051 break;
3052 }
3053
3054 switch (V.getKind()) {
3055 default:
3056 assert(false && "Invalid case.");
3057 case RefVal::Owned:
3058 // The object immediately transitions to the released state.
3059 V = V ^ RefVal::Released;
3060 V.clearCounts();
3061 return state.set<RefBindings>(sym, V);
3062 case RefVal::NotOwned:
3063 V = V ^ RefVal::ErrorDeallocNotOwned;
3064 hasErr = V.getKind();
3065 break;
3066 }
3067 break;
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003068
Ted Kremenekb7826ab2009-02-25 23:11:49 +00003069 case NewAutoreleasePool:
3070 assert(!isGCEnabled());
3071 return state.add<AutoreleaseStack>(sym);
3072
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003073 case MayEscape:
3074 if (V.getKind() == RefVal::Owned) {
Ted Kremenek272aa852008-06-25 21:21:56 +00003075 V = V ^ RefVal::NotOwned;
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003076 break;
3077 }
Ted Kremenek6537a642009-03-17 19:42:23 +00003078
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003079 // Fall-through.
Ted Kremenek1b4b6562009-02-25 02:54:57 +00003080
Ted Kremenekede40b72008-07-09 18:11:16 +00003081 case DoNothingByRef:
Ted Kremenek0d721572008-03-11 17:48:22 +00003082 case DoNothing:
Ted Kremenekb6578942009-02-24 19:15:11 +00003083 return state;
Ted Kremeneke5a4bb02008-06-30 16:57:41 +00003084
Ted Kremenek9b112d22009-01-28 21:44:40 +00003085 case Autorelease:
Ted Kremenek6537a642009-03-17 19:42:23 +00003086 if (isGCEnabled())
3087 return state;
Ted Kremenek681fb352009-03-20 17:34:15 +00003088
3089 // Update the autorelease counts.
3090 state = SendAutorelease(state, ARCountFactory, sym);
Ted Kremenek6537a642009-03-17 19:42:23 +00003091
3092 // Fall-through.
3093
Ted Kremenek227c5372008-05-06 02:41:27 +00003094 case StopTracking:
Ted Kremenekb6578942009-02-24 19:15:11 +00003095 return state.remove<RefBindings>(sym);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003096
Ted Kremenek0d721572008-03-11 17:48:22 +00003097 case IncRef:
3098 switch (V.getKind()) {
3099 default:
3100 assert(false);
3101
3102 case RefVal::Owned:
Ted Kremenek0d721572008-03-11 17:48:22 +00003103 case RefVal::NotOwned:
Ted Kremenek272aa852008-06-25 21:21:56 +00003104 V = V + 1;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003105 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003106 case RefVal::Released:
Ted Kremenek6537a642009-03-17 19:42:23 +00003107 // Non-GC cases are handled above.
3108 assert(isGCEnabled());
3109 V = (V ^ RefVal::Owned) + 1;
Ted Kremenek0d721572008-03-11 17:48:22 +00003110 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003111 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00003112 break;
3113
Ted Kremenek272aa852008-06-25 21:21:56 +00003114 case SelfOwn:
3115 V = V ^ RefVal::NotOwned;
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003116 // Fall-through.
Ted Kremenek0d721572008-03-11 17:48:22 +00003117 case DecRef:
3118 switch (V.getKind()) {
3119 default:
Ted Kremenek6537a642009-03-17 19:42:23 +00003120 // case 'RefVal::Released' handled above.
Ted Kremenek0d721572008-03-11 17:48:22 +00003121 assert (false);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003122
Ted Kremenek272aa852008-06-25 21:21:56 +00003123 case RefVal::Owned:
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00003124 assert(V.getCount() > 0);
3125 if (V.getCount() == 1) V = V ^ RefVal::Released;
3126 V = V - 1;
Ted Kremenek0d721572008-03-11 17:48:22 +00003127 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003128
Ted Kremenek272aa852008-06-25 21:21:56 +00003129 case RefVal::NotOwned:
3130 if (V.getCount() > 0)
3131 V = V - 1;
Ted Kremenekc4f81022008-04-10 23:09:18 +00003132 else {
Ted Kremenek272aa852008-06-25 21:21:56 +00003133 V = V ^ RefVal::ErrorReleaseNotOwned;
Ted Kremenek1feab292008-04-16 04:28:53 +00003134 hasErr = V.getKind();
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003135 }
Ted Kremenek0d721572008-03-11 17:48:22 +00003136 break;
Ted Kremenek6537a642009-03-17 19:42:23 +00003137
Ted Kremenek0d721572008-03-11 17:48:22 +00003138 case RefVal::Released:
Ted Kremenek6537a642009-03-17 19:42:23 +00003139 // Non-GC cases are handled above.
3140 assert(isGCEnabled());
Ted Kremenek272aa852008-06-25 21:21:56 +00003141 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek1feab292008-04-16 04:28:53 +00003142 hasErr = V.getKind();
Ted Kremenek6537a642009-03-17 19:42:23 +00003143 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003144 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00003145 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003146 }
Ted Kremenekb6578942009-02-24 19:15:11 +00003147 return state.set<RefBindings>(sym, V);
Ted Kremeneka7338b42008-03-11 06:39:11 +00003148}
3149
Ted Kremenek10fe66d2008-04-09 01:10:13 +00003150//===----------------------------------------------------------------------===//
Ted Kremenek708af042009-02-05 06:50:21 +00003151// Handle dead symbols and end-of-path.
3152//===----------------------------------------------------------------------===//
3153
3154void CFRefCount::EvalEndPath(GRExprEngine& Eng,
3155 GREndPathNodeBuilder<GRState>& Builder) {
3156
3157 const GRState* St = Builder.getState();
3158 RefBindings B = St->get<RefBindings>();
3159
3160 llvm::SmallVector<std::pair<SymbolRef, bool>, 10> Leaked;
3161 const Decl* CodeDecl = &Eng.getGraph().getCodeDecl();
3162
3163 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
3164 bool hasLeak = false;
3165
3166 std::pair<GRStateRef, bool> X =
Ted Kremenek9577c1e2009-03-03 22:06:47 +00003167 HandleSymbolDeath(Eng.getStateManager(), St, CodeDecl,
3168 (*I).first, (*I).second, hasLeak);
Ted Kremenek708af042009-02-05 06:50:21 +00003169
3170 St = X.first;
3171 if (hasLeak) Leaked.push_back(std::make_pair((*I).first, X.second));
3172 }
3173
3174 if (Leaked.empty())
3175 return;
3176
3177 ExplodedNode<GRState>* N = Builder.MakeNode(St);
3178
3179 if (!N)
3180 return;
3181
3182 for (llvm::SmallVector<std::pair<SymbolRef,bool>, 10>::iterator
3183 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3184
3185 CFRefBug *BT = static_cast<CFRefBug*>(I->second ? leakAtReturn
3186 : leakWithinFunction);
3187 assert(BT && "BugType not initialized.");
Ted Kremenekc034f712009-04-07 05:07:44 +00003188 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N, I->first, Eng);
Ted Kremenek708af042009-02-05 06:50:21 +00003189 BR->EmitReport(report);
3190 }
3191}
3192
3193void CFRefCount::EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
3194 GRExprEngine& Eng,
3195 GRStmtNodeBuilder<GRState>& Builder,
3196 ExplodedNode<GRState>* Pred,
3197 Stmt* S,
3198 const GRState* St,
3199 SymbolReaper& SymReaper) {
3200
Ted Kremenek876d8df2009-02-19 23:47:02 +00003201 // FIXME: a lot of copy-and-paste from EvalEndPath. Refactor.
Ted Kremenek708af042009-02-05 06:50:21 +00003202 RefBindings B = St->get<RefBindings>();
3203 llvm::SmallVector<std::pair<SymbolRef,bool>, 10> Leaked;
3204
3205 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3206 E = SymReaper.dead_end(); I != E; ++I) {
3207
3208 const RefVal* T = B.lookup(*I);
3209 if (!T) continue;
3210
3211 bool hasLeak = false;
3212
3213 std::pair<GRStateRef, bool> X
Ted Kremenek876d8df2009-02-19 23:47:02 +00003214 = HandleSymbolDeath(Eng.getStateManager(), St, 0, *I, *T, hasLeak);
Ted Kremenek708af042009-02-05 06:50:21 +00003215
3216 St = X.first;
3217
3218 if (hasLeak)
3219 Leaked.push_back(std::make_pair(*I,X.second));
3220 }
3221
Ted Kremenek876d8df2009-02-19 23:47:02 +00003222 if (!Leaked.empty()) {
3223 // Create a new intermediate node representing the leak point. We
3224 // use a special program point that represents this checker-specific
3225 // transition. We use the address of RefBIndex as a unique tag for this
3226 // checker. We will create another node (if we don't cache out) that
3227 // removes the retain-count bindings from the state.
3228 // NOTE: We use 'generateNode' so that it does interplay with the
3229 // auto-transition logic.
3230 ExplodedNode<GRState>* N =
3231 Builder.generateNode(PostStmtCustom(S, &LeakProgramPointTag), St, Pred);
Ted Kremenek708af042009-02-05 06:50:21 +00003232
Ted Kremenek876d8df2009-02-19 23:47:02 +00003233 if (!N)
3234 return;
3235
3236 // Generate the bug reports.
3237 for (llvm::SmallVectorImpl<std::pair<SymbolRef,bool> >::iterator
3238 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3239
3240 CFRefBug *BT = static_cast<CFRefBug*>(I->second ? leakAtReturn
3241 : leakWithinFunction);
3242 assert(BT && "BugType not initialized.");
Ted Kremenek56c70aa2009-02-23 16:54:00 +00003243 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N,
3244 I->first, Eng);
Ted Kremenek876d8df2009-02-19 23:47:02 +00003245 BR->EmitReport(report);
3246 }
Ted Kremenek708af042009-02-05 06:50:21 +00003247
Ted Kremenek876d8df2009-02-19 23:47:02 +00003248 Pred = N;
Ted Kremenek708af042009-02-05 06:50:21 +00003249 }
Ted Kremenek876d8df2009-02-19 23:47:02 +00003250
3251 // Now generate a new node that nukes the old bindings.
3252 GRStateRef state(St, Eng.getStateManager());
3253 RefBindings::Factory& F = state.get_context<RefBindings>();
3254
3255 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3256 E = SymReaper.dead_end(); I!=E; ++I)
3257 B = F.Remove(B, *I);
3258
3259 state = state.set<RefBindings>(B);
3260 Builder.MakeNode(Dst, S, Pred, state);
Ted Kremenek708af042009-02-05 06:50:21 +00003261}
3262
3263void CFRefCount::ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
3264 GRStmtNodeBuilder<GRState>& Builder,
3265 Expr* NodeExpr, Expr* ErrorExpr,
3266 ExplodedNode<GRState>* Pred,
3267 const GRState* St,
3268 RefVal::Kind hasErr, SymbolRef Sym) {
3269 Builder.BuildSinks = true;
3270 GRExprEngine::NodeTy* N = Builder.MakeNode(Dst, NodeExpr, Pred, St);
3271
3272 if (!N) return;
3273
3274 CFRefBug *BT = 0;
3275
Ted Kremenek6537a642009-03-17 19:42:23 +00003276 switch (hasErr) {
3277 default:
3278 assert(false && "Unhandled error.");
3279 return;
3280 case RefVal::ErrorUseAfterRelease:
3281 BT = static_cast<CFRefBug*>(useAfterRelease);
3282 break;
3283 case RefVal::ErrorReleaseNotOwned:
3284 BT = static_cast<CFRefBug*>(releaseNotOwned);
3285 break;
3286 case RefVal::ErrorDeallocGC:
3287 BT = static_cast<CFRefBug*>(deallocGC);
3288 break;
3289 case RefVal::ErrorDeallocNotOwned:
3290 BT = static_cast<CFRefBug*>(deallocNotOwned);
3291 break;
Ted Kremenek708af042009-02-05 06:50:21 +00003292 }
3293
Ted Kremenekc26c4692009-02-18 03:48:14 +00003294 CFRefReport *report = new CFRefReport(*BT, *this, N, Sym);
Ted Kremenek708af042009-02-05 06:50:21 +00003295 report->addRange(ErrorExpr->getSourceRange());
3296 BR->EmitReport(report);
3297}
3298
3299//===----------------------------------------------------------------------===//
Ted Kremenekb1983ba2008-04-10 22:16:52 +00003300// Transfer function creation for external clients.
Ted Kremeneka7338b42008-03-11 06:39:11 +00003301//===----------------------------------------------------------------------===//
3302
Ted Kremenekfe30beb2008-04-30 23:47:44 +00003303GRTransferFuncs* clang::MakeCFRefCountTF(ASTContext& Ctx, bool GCEnabled,
3304 const LangOptions& lopts) {
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00003305 return new CFRefCount(Ctx, GCEnabled, lopts);
Ted Kremeneka4c74292008-04-10 22:58:08 +00003306}