blob: 505ec7d11d1b81d583a6f9759b36f90399e11de5 [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 Kremenekb3a44e72008-05-06 18:11:36 +0000572 RetainSummary* StopSummary;
573
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000574 //==-----------------------------------------------------------------==//
575 // Methods.
576 //==-----------------------------------------------------------------==//
577
Ted Kremenek272aa852008-06-25 21:21:56 +0000578 /// getArgEffects - Returns a persistent ArgEffects object based on the
579 /// data in ScratchArgs.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000580 ArgEffects getArgEffects();
Ted Kremeneka7338b42008-03-11 06:39:11 +0000581
Ted Kremenek562c1302008-05-05 16:51:50 +0000582 enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000583
584public:
Ted Kremenek064ef322009-02-23 16:51:39 +0000585 RetainSummary* getUnarySummary(const FunctionType* FT, UnaryFuncKind func);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000586
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000587 RetainSummary* getCFSummaryCreateRule(FunctionDecl* FD);
588 RetainSummary* getCFSummaryGetRule(FunctionDecl* FD);
Ted Kremenek17144e82009-01-12 21:45:02 +0000589 RetainSummary* getCFCreateGetRuleSummary(FunctionDecl* FD, const char* FName);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000590
Ted Kremeneka56ae162009-05-03 05:20:50 +0000591 RetainSummary* getPersistentSummary(ArgEffects AE, RetEffect RetEff,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000592 ArgEffect ReceiverEff = DoNothing,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000593 ArgEffect DefaultEff = MayEscape,
594 bool isEndPath = false);
Ted Kremenek45d0b502008-10-29 04:07:07 +0000595
Ted Kremenek266d8b62008-05-06 02:26:56 +0000596 RetainSummary* getPersistentSummary(RetEffect RE,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000597 ArgEffect ReceiverEff = DoNothing,
Ted Kremeneka3f30dd2008-05-22 17:31:13 +0000598 ArgEffect DefaultEff = MayEscape) {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000599 return getPersistentSummary(getArgEffects(), RE, ReceiverEff, DefaultEff);
Ted Kremenek0e344d42008-05-06 00:30:21 +0000600 }
Ted Kremenek42ea0322008-05-05 23:55:01 +0000601
Ted Kremeneka821b792009-04-29 05:04:30 +0000602 RetainSummary *getPersistentStopSummary() {
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000603 if (StopSummary)
604 return StopSummary;
605
606 StopSummary = getPersistentSummary(RetEffect::MakeNoRet(),
607 StopTracking, StopTracking);
Ted Kremenek45d0b502008-10-29 04:07:07 +0000608
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000609 return StopSummary;
Ted Kremenekbcaff792008-05-06 15:44:25 +0000610 }
Ted Kremenek926abf22008-05-06 04:20:12 +0000611
Ted Kremeneka821b792009-04-29 05:04:30 +0000612 RetainSummary *getInitMethodSummary(QualType RetTy);
Ted Kremenek42ea0322008-05-05 23:55:01 +0000613
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000614 void InitializeClassMethodSummaries();
615 void InitializeMethodSummaries();
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000616
Ted Kremenek9b42e062009-05-03 04:42:10 +0000617 bool isTrackedObjCObjectType(QualType T);
Ted Kremeneka9cdbc32009-05-03 06:08:32 +0000618 bool isTrackedCFObjectType(QualType T);
Ted Kremenek35920ed2009-01-07 00:39:56 +0000619
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000620private:
621
Ted Kremenekf2717b02008-07-18 17:24:20 +0000622 void addClsMethSummary(IdentifierInfo* ClsII, Selector S,
623 RetainSummary* Summ) {
624 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
625 }
626
Ted Kremenek272aa852008-06-25 21:21:56 +0000627 void addNSObjectClsMethSummary(Selector S, RetainSummary *Summ) {
628 ObjCClassMethodSummaries[S] = Summ;
629 }
630
631 void addNSObjectMethSummary(Selector S, RetainSummary *Summ) {
632 ObjCMethodSummaries[S] = Summ;
633 }
Ted Kremenekfbf2dc52009-03-04 23:30:42 +0000634
635 void addClassMethSummary(const char* Cls, const char* nullaryName,
636 RetainSummary *Summ) {
637 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
638 Selector S = GetNullarySelector(nullaryName, Ctx);
639 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
640 }
Ted Kremenek272aa852008-06-25 21:21:56 +0000641
Ted Kremenek1b4b6562009-02-25 02:54:57 +0000642 void addInstMethSummary(const char* Cls, const char* nullaryName,
643 RetainSummary *Summ) {
644 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
645 Selector S = GetNullarySelector(nullaryName, Ctx);
646 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
647 }
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000648
649 Selector generateSelector(va_list argp) {
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000650 llvm::SmallVector<IdentifierInfo*, 10> II;
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000651
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000652 while (const char* s = va_arg(argp, const char*))
653 II.push_back(&Ctx.Idents.get(s));
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000654
655 return Ctx.Selectors.getSelector(II.size(), &II[0]);
656 }
657
658 void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy& Summaries,
659 RetainSummary* Summ, va_list argp) {
660 Selector S = generateSelector(argp);
661 Summaries[ObjCSummaryKey(ClsII, S)] = Summ;
Ted Kremenekf2717b02008-07-18 17:24:20 +0000662 }
Ted Kremenek45642a42008-08-12 18:48:50 +0000663
664 void addInstMethSummary(const char* Cls, RetainSummary* Summ, ...) {
665 va_list argp;
666 va_start(argp, Summ);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000667 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Ted Kremenek45642a42008-08-12 18:48:50 +0000668 va_end(argp);
669 }
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000670
671 void addClsMethSummary(const char* Cls, RetainSummary* Summ, ...) {
672 va_list argp;
673 va_start(argp, Summ);
674 addMethodSummary(&Ctx.Idents.get(Cls),ObjCClassMethodSummaries, Summ, argp);
675 va_end(argp);
676 }
677
678 void addClsMethSummary(IdentifierInfo *II, RetainSummary* Summ, ...) {
679 va_list argp;
680 va_start(argp, Summ);
681 addMethodSummary(II, ObjCClassMethodSummaries, Summ, argp);
682 va_end(argp);
683 }
684
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000685 void addPanicSummary(const char* Cls, ...) {
Ted Kremeneka56ae162009-05-03 05:20:50 +0000686 RetainSummary* Summ = getPersistentSummary(AF.GetEmptyMap(),
687 RetEffect::MakeNoRet(),
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000688 DoNothing, DoNothing, true);
689 va_list argp;
690 va_start (argp, Cls);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000691 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000692 va_end(argp);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000693 }
Ted Kremenekf2717b02008-07-18 17:24:20 +0000694
Ted Kremeneka7338b42008-03-11 06:39:11 +0000695public:
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000696
697 RetainSummaryManager(ASTContext& ctx, bool gcenabled)
Ted Kremeneke44927e2008-07-01 17:21:27 +0000698 : Ctx(ctx),
Ted Kremenekede40b72008-07-09 18:11:16 +0000699 CFDictionaryCreateII(&ctx.Idents.get("CFDictionaryCreate")),
Ted Kremeneka56ae162009-05-03 05:20:50 +0000700 GCEnabled(gcenabled), AF(BPAlloc), ScratchArgs(AF.GetEmptyMap()),
701 StopSummary(0) {
Ted Kremenek272aa852008-06-25 21:21:56 +0000702
703 InitializeClassMethodSummaries();
704 InitializeMethodSummaries();
705 }
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000706
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000707 ~RetainSummaryManager();
Ted Kremeneka7338b42008-03-11 06:39:11 +0000708
Ted Kremenekd13c1872008-06-24 03:56:45 +0000709 RetainSummary* getSummary(FunctionDecl* FD);
Ted Kremeneka821b792009-04-29 05:04:30 +0000710
Ted Kremenek314b1952009-04-29 23:03:22 +0000711 RetainSummary* getInstanceMethodSummary(ObjCMessageExpr* ME,
712 const ObjCInterfaceDecl* ID) {
Ted Kremenek04e00302009-04-29 17:09:14 +0000713 return getInstanceMethodSummary(ME->getSelector(), ME->getClassName(),
Ted Kremeneka821b792009-04-29 05:04:30 +0000714 ID, ME->getMethodDecl(), ME->getType());
715 }
716
Ted Kremenek04e00302009-04-29 17:09:14 +0000717 RetainSummary* getInstanceMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +0000718 const ObjCInterfaceDecl* ID,
719 const ObjCMethodDecl *MD,
720 QualType RetTy);
Ted Kremenek578498a2009-04-29 00:42:39 +0000721
722 RetainSummary *getClassMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +0000723 const ObjCInterfaceDecl *ID,
724 const ObjCMethodDecl *MD,
725 QualType RetTy);
Ted Kremenek578498a2009-04-29 00:42:39 +0000726
727 RetainSummary *getClassMethodSummary(ObjCMessageExpr *ME) {
728 return getClassMethodSummary(ME->getSelector(), ME->getClassName(),
729 ME->getClassInfo().first,
730 ME->getMethodDecl(), ME->getType());
731 }
Ted Kremenek91b89a42009-04-29 17:17:48 +0000732
733 /// getMethodSummary - This version of getMethodSummary is used to query
734 /// the summary for the current method being analyzed.
Ted Kremenek314b1952009-04-29 23:03:22 +0000735 RetainSummary *getMethodSummary(const ObjCMethodDecl *MD) {
736 // FIXME: Eventually this should be unneeded.
Ted Kremenek314b1952009-04-29 23:03:22 +0000737 const ObjCInterfaceDecl *ID = MD->getClassInterface();
Ted Kremenek1447cc92009-04-30 05:41:14 +0000738 Selector S = MD->getSelector();
Ted Kremenek91b89a42009-04-29 17:17:48 +0000739 IdentifierInfo *ClsName = ID->getIdentifier();
740 QualType ResultTy = MD->getResultType();
741
Ted Kremenek81eb4642009-04-30 05:47:23 +0000742 // Resolve the method decl last.
743 if (const ObjCMethodDecl *InterfaceMD =
744 ResolveToInterfaceMethodDecl(MD, Ctx))
745 MD = InterfaceMD;
Ted Kremenek1447cc92009-04-30 05:41:14 +0000746
Ted Kremenek91b89a42009-04-29 17:17:48 +0000747 if (MD->isInstanceMethod())
748 return getInstanceMethodSummary(S, ClsName, ID, MD, ResultTy);
749 else
750 return getClassMethodSummary(S, ClsName, ID, MD, ResultTy);
751 }
Ted Kremenek578498a2009-04-29 00:42:39 +0000752
Ted Kremenek314b1952009-04-29 23:03:22 +0000753 RetainSummary* getCommonMethodSummary(const ObjCMethodDecl* MD,
754 Selector S, QualType RetTy);
755
756 RetainSummary* getMethodSummaryFromAnnotations(const ObjCMethodDecl *MD);
Ted Kremenek926abf22008-05-06 04:20:12 +0000757
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000758 bool isGCEnabled() const { return GCEnabled; }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000759};
760
761} // end anonymous namespace
762
763//===----------------------------------------------------------------------===//
764// Implementation of checker data structures.
765//===----------------------------------------------------------------------===//
766
Ted Kremeneka56ae162009-05-03 05:20:50 +0000767RetainSummaryManager::~RetainSummaryManager() {}
Ted Kremeneka7338b42008-03-11 06:39:11 +0000768
Ted Kremeneka56ae162009-05-03 05:20:50 +0000769ArgEffects RetainSummaryManager::getArgEffects() {
770 ArgEffects AE = ScratchArgs;
771 ScratchArgs = AF.GetEmptyMap();
772 return AE;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000773}
774
Ted Kremenek266d8b62008-05-06 02:26:56 +0000775RetainSummary*
Ted Kremeneka56ae162009-05-03 05:20:50 +0000776RetainSummaryManager::getPersistentSummary(ArgEffects AE, RetEffect RetEff,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000777 ArgEffect ReceiverEff,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000778 ArgEffect DefaultEff,
Ted Kremenekee649082009-05-04 04:30:18 +0000779 bool isEndPath) {
Ted Kremenekae855d42008-04-24 17:22:33 +0000780 // Create the summary and return it.
Ted Kremenekee649082009-05-04 04:30:18 +0000781 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
Ted Kremenekf2717b02008-07-18 17:24:20 +0000782 new (Summ) RetainSummary(AE, RetEff, DefaultEff, ReceiverEff, isEndPath);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000783 return Summ;
784}
785
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000786//===----------------------------------------------------------------------===//
Ted Kremenek35920ed2009-01-07 00:39:56 +0000787// Predicates.
788//===----------------------------------------------------------------------===//
789
Ted Kremenek9b42e062009-05-03 04:42:10 +0000790bool RetainSummaryManager::isTrackedObjCObjectType(QualType Ty) {
Ted Kremenek0d813552009-04-23 22:11:07 +0000791 if (!Ctx.isObjCObjectPointerType(Ty))
Ted Kremenek35920ed2009-01-07 00:39:56 +0000792 return false;
793
Ted Kremenek0d813552009-04-23 22:11:07 +0000794 // We assume that id<..>, id, and "Class" all represent tracked objects.
795 const PointerType *PT = Ty->getAsPointerType();
796 if (PT == 0)
797 return true;
798
799 const ObjCInterfaceType *OT = PT->getPointeeType()->getAsObjCInterfaceType();
Ted Kremenek35920ed2009-01-07 00:39:56 +0000800
801 // We assume that id<..>, id, and "Class" all represent tracked objects.
802 if (!OT)
803 return true;
Ted Kremenek0d813552009-04-23 22:11:07 +0000804
805 // Does the interface subclass NSObject?
Ted Kremenek35920ed2009-01-07 00:39:56 +0000806 // FIXME: We can memoize here if this gets too expensive.
807 IdentifierInfo* NSObjectII = &Ctx.Idents.get("NSObject");
808 ObjCInterfaceDecl* ID = OT->getDecl();
809
810 for ( ; ID ; ID = ID->getSuperClass())
811 if (ID->getIdentifier() == NSObjectII)
812 return true;
813
814 return false;
815}
816
Ted Kremeneka9cdbc32009-05-03 06:08:32 +0000817bool RetainSummaryManager::isTrackedCFObjectType(QualType T) {
818 return isRefType(T, "CF") || // Core Foundation.
819 isRefType(T, "CG") || // Core Graphics.
820 isRefType(T, "DADisk") || // Disk Arbitration API.
821 isRefType(T, "DADissenter") ||
822 isRefType(T, "DASessionRef");
823}
824
Ted Kremenek35920ed2009-01-07 00:39:56 +0000825//===----------------------------------------------------------------------===//
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000826// Summary creation for functions (largely uses of Core Foundation).
827//===----------------------------------------------------------------------===//
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000828
Ted Kremenek17144e82009-01-12 21:45:02 +0000829static bool isRetain(FunctionDecl* FD, const char* FName) {
830 const char* loc = strstr(FName, "Retain");
831 return loc && loc[sizeof("Retain")-1] == '\0';
832}
833
834static bool isRelease(FunctionDecl* FD, const char* FName) {
835 const char* loc = strstr(FName, "Release");
836 return loc && loc[sizeof("Release")-1] == '\0';
837}
838
Ted Kremenekd13c1872008-06-24 03:56:45 +0000839RetainSummary* RetainSummaryManager::getSummary(FunctionDecl* FD) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000840
841 SourceLocation Loc = FD->getLocation();
842
843 if (!Loc.isFileID())
844 return NULL;
Ted Kremenek827f93b2008-03-06 00:08:09 +0000845
Ted Kremenekae855d42008-04-24 17:22:33 +0000846 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000847 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremenekae855d42008-04-24 17:22:33 +0000848
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000849 if (I != FuncSummaries.end())
Ted Kremenekae855d42008-04-24 17:22:33 +0000850 return I->second;
851
852 // No summary. Generate one.
Ted Kremenek17144e82009-01-12 21:45:02 +0000853 RetainSummary *S = 0;
Ted Kremenek562c1302008-05-05 16:51:50 +0000854
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000855 do {
Ted Kremenek17144e82009-01-12 21:45:02 +0000856 // We generate "stop" summaries for implicitly defined functions.
857 if (FD->isImplicit()) {
858 S = getPersistentStopSummary();
859 break;
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000860 }
Ted Kremenekeafcc2f2008-11-04 00:36:12 +0000861
Ted Kremenek064ef322009-02-23 16:51:39 +0000862 // [PR 3337] Use 'getAsFunctionType' to strip away any typedefs on the
Ted Kremenekc239b9c2009-01-16 18:40:33 +0000863 // function's type.
Ted Kremenek064ef322009-02-23 16:51:39 +0000864 const FunctionType* FT = FD->getType()->getAsFunctionType();
Ted Kremenek17144e82009-01-12 21:45:02 +0000865 const char* FName = FD->getIdentifier()->getName();
866
Ted Kremenek38c6f022009-03-05 22:11:14 +0000867 // Strip away preceding '_'. Doing this here will effect all the checks
868 // down below.
869 while (*FName == '_') ++FName;
870
Ted Kremenek17144e82009-01-12 21:45:02 +0000871 // Inspect the result type.
872 QualType RetTy = FT->getResultType();
873
874 // FIXME: This should all be refactored into a chain of "summary lookup"
875 // filters.
876 if (strcmp(FName, "IOServiceGetMatchingServices") == 0) {
877 // FIXES: <rdar://problem/6326900>
878 // This should be addressed using a API table. This strcmp is also
879 // a little gross, but there is no need to super optimize here.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000880 assert (ScratchArgs.isEmpty());
881 ScratchArgs = AF.Add(ScratchArgs, 1, DecRef);
Ted Kremenek17144e82009-01-12 21:45:02 +0000882 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
883 break;
Ted Kremenekcfc50c72008-10-22 20:54:52 +0000884 }
Ted Kremenek7b88c892009-03-17 22:43:44 +0000885
886 // Enable this code once the semantics of NSDeallocateObject are resolved
887 // for GC. <rdar://problem/6619988>
888#if 0
889 // Handle: NSDeallocateObject(id anObject);
890 // This method does allow 'nil' (although we don't check it now).
891 if (strcmp(FName, "NSDeallocateObject") == 0) {
892 return RetTy == Ctx.VoidTy
893 ? getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, Dealloc)
894 : getPersistentStopSummary();
895 }
896#endif
Ted Kremenek17144e82009-01-12 21:45:02 +0000897
898 // Handle: id NSMakeCollectable(CFTypeRef)
899 if (strcmp(FName, "NSMakeCollectable") == 0) {
900 S = (RetTy == Ctx.getObjCIdType())
901 ? getUnarySummary(FT, cfmakecollectable)
902 : getPersistentStopSummary();
903
904 break;
905 }
906
907 if (RetTy->isPointerType()) {
908 // For CoreFoundation ('CF') types.
909 if (isRefType(RetTy, "CF", &Ctx, FName)) {
910 if (isRetain(FD, FName))
911 S = getUnarySummary(FT, cfretain);
912 else if (strstr(FName, "MakeCollectable"))
913 S = getUnarySummary(FT, cfmakecollectable);
914 else
915 S = getCFCreateGetRuleSummary(FD, FName);
916
917 break;
918 }
919
920 // For CoreGraphics ('CG') types.
921 if (isRefType(RetTy, "CG", &Ctx, FName)) {
922 if (isRetain(FD, FName))
923 S = getUnarySummary(FT, cfretain);
924 else
925 S = getCFCreateGetRuleSummary(FD, FName);
926
927 break;
928 }
929
930 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
931 if (isRefType(RetTy, "DADisk") ||
932 isRefType(RetTy, "DADissenter") ||
933 isRefType(RetTy, "DASessionRef")) {
934 S = getCFCreateGetRuleSummary(FD, FName);
935 break;
936 }
937
938 break;
939 }
940
941 // Check for release functions, the only kind of functions that we care
942 // about that don't return a pointer type.
943 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
Ted Kremenek38c6f022009-03-05 22:11:14 +0000944 // Test for 'CGCF'.
945 if (FName[1] == 'G' && FName[2] == 'C' && FName[3] == 'F')
946 FName += 4;
947 else
948 FName += 2;
949
950 if (isRelease(FD, FName))
Ted Kremenek17144e82009-01-12 21:45:02 +0000951 S = getUnarySummary(FT, cfrelease);
952 else {
Ted Kremeneka56ae162009-05-03 05:20:50 +0000953 assert (ScratchArgs.isEmpty());
Ted Kremenek7b293682009-01-29 22:45:13 +0000954 // Remaining CoreFoundation and CoreGraphics functions.
955 // We use to assume that they all strictly followed the ownership idiom
956 // and that ownership cannot be transferred. While this is technically
957 // correct, many methods allow a tracked object to escape. For example:
958 //
959 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
960 // CFDictionaryAddValue(y, key, x);
961 // CFRelease(x);
962 // ... it is okay to use 'x' since 'y' has a reference to it
963 //
964 // We handle this and similar cases with the follow heuristic. If the
965 // function name contains "InsertValue", "SetValue" or "AddValue" then
966 // we assume that arguments may "escape."
967 //
968 ArgEffect E = (CStrInCStrNoCase(FName, "InsertValue") ||
969 CStrInCStrNoCase(FName, "AddValue") ||
Ted Kremenekcf071252009-02-05 22:34:53 +0000970 CStrInCStrNoCase(FName, "SetValue") ||
971 CStrInCStrNoCase(FName, "AppendValue"))
Ted Kremenek7b293682009-01-29 22:45:13 +0000972 ? MayEscape : DoNothing;
973
974 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek17144e82009-01-12 21:45:02 +0000975 }
976 }
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000977 }
978 while (0);
Ted Kremenekae855d42008-04-24 17:22:33 +0000979
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000980 FuncSummaries[FD] = S;
Ted Kremenek562c1302008-05-05 16:51:50 +0000981 return S;
Ted Kremenek827f93b2008-03-06 00:08:09 +0000982}
983
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000984RetainSummary*
985RetainSummaryManager::getCFCreateGetRuleSummary(FunctionDecl* FD,
986 const char* FName) {
987
Ted Kremenek562c1302008-05-05 16:51:50 +0000988 if (strstr(FName, "Create") || strstr(FName, "Copy"))
989 return getCFSummaryCreateRule(FD);
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000990
Ted Kremenek562c1302008-05-05 16:51:50 +0000991 if (strstr(FName, "Get"))
992 return getCFSummaryGetRule(FD);
993
994 return 0;
995}
996
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000997RetainSummary*
Ted Kremenek064ef322009-02-23 16:51:39 +0000998RetainSummaryManager::getUnarySummary(const FunctionType* FT,
999 UnaryFuncKind func) {
1000
Ted Kremenek17144e82009-01-12 21:45:02 +00001001 // Sanity check that this is *really* a unary function. This can
1002 // happen if people do weird things.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001003 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
Ted Kremenek17144e82009-01-12 21:45:02 +00001004 if (!FTP || FTP->getNumArgs() != 1)
1005 return getPersistentStopSummary();
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001006
Ted Kremeneka56ae162009-05-03 05:20:50 +00001007 assert (ScratchArgs.isEmpty());
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001008
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001009 switch (func) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001010 case cfretain: {
1011 ScratchArgs = AF.Add(ScratchArgs, 0, IncRef);
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001012 return getPersistentSummary(RetEffect::MakeAlias(0),
1013 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001014 }
1015
1016 case cfrelease: {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001017 ScratchArgs = AF.Add(ScratchArgs, 0, DecRef);
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001018 return getPersistentSummary(RetEffect::MakeNoRet(),
1019 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001020 }
1021
1022 case cfmakecollectable: {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001023 ScratchArgs = AF.Add(ScratchArgs, 0, MakeCollectable);
Ted Kremenek2126bef2009-02-18 21:57:45 +00001024 return getPersistentSummary(RetEffect::MakeAlias(0),DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001025 }
1026
1027 default:
Ted Kremenek562c1302008-05-05 16:51:50 +00001028 assert (false && "Not a supported unary function.");
Ted Kremenek9449ca92008-08-12 20:41:56 +00001029 return 0;
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00001030 }
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001031}
1032
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001033RetainSummary* RetainSummaryManager::getCFSummaryCreateRule(FunctionDecl* FD) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001034 assert (ScratchArgs.isEmpty());
Ted Kremenekede40b72008-07-09 18:11:16 +00001035
1036 if (FD->getIdentifier() == CFDictionaryCreateII) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001037 ScratchArgs = AF.Add(ScratchArgs, 1, DoNothingByRef);
1038 ScratchArgs = AF.Add(ScratchArgs, 2, DoNothingByRef);
Ted Kremenekede40b72008-07-09 18:11:16 +00001039 }
1040
Ted Kremenek68621b92009-01-28 05:56:51 +00001041 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001042}
1043
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001044RetainSummary* RetainSummaryManager::getCFSummaryGetRule(FunctionDecl* FD) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001045 assert (ScratchArgs.isEmpty());
Ted Kremenek68621b92009-01-28 05:56:51 +00001046 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1047 DoNothing, DoNothing);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001048}
1049
Ted Kremeneka7338b42008-03-11 06:39:11 +00001050//===----------------------------------------------------------------------===//
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001051// Summary creation for Selectors.
1052//===----------------------------------------------------------------------===//
1053
Ted Kremenekbcaff792008-05-06 15:44:25 +00001054RetainSummary*
Ted Kremeneka821b792009-04-29 05:04:30 +00001055RetainSummaryManager::getInitMethodSummary(QualType RetTy) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001056 assert(ScratchArgs.isEmpty());
Ted Kremenek42ea0322008-05-05 23:55:01 +00001057
Ted Kremenek802cfc72009-02-20 00:05:35 +00001058 // 'init' methods only return an alias if the return type is a location type.
Ted Kremeneka821b792009-04-29 05:04:30 +00001059 return getPersistentSummary(Loc::IsLocType(RetTy)
1060 ? RetEffect::MakeReceiverAlias()
1061 : RetEffect::MakeNoRet());
Ted Kremenek42ea0322008-05-05 23:55:01 +00001062}
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001063
Ted Kremenek923fc392009-04-24 23:32:32 +00001064RetainSummary*
Ted Kremenek314b1952009-04-29 23:03:22 +00001065RetainSummaryManager::getMethodSummaryFromAnnotations(const ObjCMethodDecl *MD){
Ted Kremenek923fc392009-04-24 23:32:32 +00001066 if (!MD)
1067 return 0;
1068
Ted Kremeneka56ae162009-05-03 05:20:50 +00001069 assert(ScratchArgs.isEmpty());
Ted Kremenek923fc392009-04-24 23:32:32 +00001070
1071 // Determine if there is a special return effect for this method.
Ted Kremeneke404c0d2009-04-30 20:00:31 +00001072 bool hasEffect = false;
Ted Kremenek923fc392009-04-24 23:32:32 +00001073 RetEffect RE = RetEffect::MakeNoRet();
1074
Ted Kremenek9b42e062009-05-03 04:42:10 +00001075 if (isTrackedObjCObjectType(MD->getResultType())) {
Ted Kremenek923fc392009-04-24 23:32:32 +00001076 if (MD->getAttr<ObjCOwnershipReturnsAttr>()) {
Ted Kremenek382fb4e2009-04-27 19:14:45 +00001077 RE = isGCEnabled() ? RetEffect::MakeGCNotOwned()
1078 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremeneke404c0d2009-04-30 20:00:31 +00001079 hasEffect = true;
Ted Kremenek923fc392009-04-24 23:32:32 +00001080 }
1081 else {
1082 // Default to 'not owned'.
1083 RE = RetEffect::MakeNotOwned(RetEffect::ObjC);
1084 }
1085 }
1086
Ted Kremenekb30a2f32009-04-25 01:21:50 +00001087 // Determine if there are any arguments with a specific ArgEffect.
Ted Kremenekb30a2f32009-04-25 01:21:50 +00001088 unsigned i = 0;
1089 for (ObjCMethodDecl::param_iterator I = MD->param_begin(),
1090 E = MD->param_end(); I != E; ++I, ++i) {
1091 if ((*I)->getAttr<ObjCOwnershipRetainAttr>()) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001092 ScratchArgs = AF.Add(ScratchArgs, i, IncRefMsg);
Ted Kremeneke404c0d2009-04-30 20:00:31 +00001093 hasEffect = true;
Ted Kremenekb30a2f32009-04-25 01:21:50 +00001094 }
Ted Kremenek15830ed2009-04-27 18:27:22 +00001095 else if ((*I)->getAttr<ObjCOwnershipCFRetainAttr>()) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001096 ScratchArgs = AF.Add(ScratchArgs, i, IncRef);
Ted Kremeneke404c0d2009-04-30 20:00:31 +00001097 hasEffect = true;
Ted Kremenek203169f2009-04-27 19:36:56 +00001098 }
1099 else if ((*I)->getAttr<ObjCOwnershipReleaseAttr>()) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001100 ScratchArgs = AF.Add(ScratchArgs, i, DecRefMsg);
Ted Kremeneke404c0d2009-04-30 20:00:31 +00001101 hasEffect = true;
Ted Kremenek203169f2009-04-27 19:36:56 +00001102 }
1103 else if ((*I)->getAttr<ObjCOwnershipCFReleaseAttr>()) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001104 ScratchArgs = AF.Add(ScratchArgs, i, DecRef);
Ted Kremeneke404c0d2009-04-30 20:00:31 +00001105 hasEffect = true;
Ted Kremenek203169f2009-04-27 19:36:56 +00001106 }
Ted Kremenekff8648d2009-04-28 22:32:26 +00001107 else if ((*I)->getAttr<ObjCOwnershipMakeCollectableAttr>()) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001108 ScratchArgs = AF.Add(ScratchArgs, i, MakeCollectable);
Ted Kremeneke404c0d2009-04-30 20:00:31 +00001109 hasEffect = true;
Ted Kremenekff8648d2009-04-28 22:32:26 +00001110 }
Ted Kremenek15830ed2009-04-27 18:27:22 +00001111 }
Ted Kremenekb30a2f32009-04-25 01:21:50 +00001112
Ted Kremeneke404c0d2009-04-30 20:00:31 +00001113 // Determine any effects on the receiver.
1114 ArgEffect ReceiverEff = DoNothing;
1115 if (MD->getAttr<ObjCOwnershipRetainAttr>()) {
1116 ReceiverEff = IncRefMsg;
1117 hasEffect = true;
1118 }
1119 else if (MD->getAttr<ObjCOwnershipReleaseAttr>()) {
1120 ReceiverEff = DecRefMsg;
1121 hasEffect = true;
1122 }
1123
1124 if (!hasEffect)
Ted Kremenek923fc392009-04-24 23:32:32 +00001125 return 0;
1126
Ted Kremeneke404c0d2009-04-30 20:00:31 +00001127 return getPersistentSummary(RE, ReceiverEff);
Ted Kremenek923fc392009-04-24 23:32:32 +00001128}
Ted Kremenek272aa852008-06-25 21:21:56 +00001129
Ted Kremenekbcaff792008-05-06 15:44:25 +00001130RetainSummary*
Ted Kremenek314b1952009-04-29 23:03:22 +00001131RetainSummaryManager::getCommonMethodSummary(const ObjCMethodDecl* MD,
1132 Selector S, QualType RetTy) {
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001133
Ted Kremenek578498a2009-04-29 00:42:39 +00001134 if (MD) {
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001135 // Scan the method decl for 'void*' arguments. These should be treated
1136 // as 'StopTracking' because they are often used with delegates.
1137 // Delegates are a frequent form of false positives with the retain
1138 // count checker.
1139 unsigned i = 0;
1140 for (ObjCMethodDecl::param_iterator I = MD->param_begin(),
1141 E = MD->param_end(); I != E; ++I, ++i)
1142 if (ParmVarDecl *PD = *I) {
1143 QualType Ty = Ctx.getCanonicalType(PD->getType());
1144 if (Ty.getUnqualifiedType() == Ctx.VoidPtrTy)
Ted Kremeneka56ae162009-05-03 05:20:50 +00001145 ScratchArgs = AF.Add(ScratchArgs, i, StopTracking);
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001146 }
1147 }
1148
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001149 // Any special effect for the receiver?
1150 ArgEffect ReceiverEff = DoNothing;
1151
1152 // If one of the arguments in the selector has the keyword 'delegate' we
1153 // should stop tracking the reference count for the receiver. This is
1154 // because the reference count is quite possibly handled by a delegate
1155 // method.
1156 if (S.isKeywordSelector()) {
1157 const std::string &str = S.getAsString();
1158 assert(!str.empty());
1159 if (CStrInCStrNoCase(&str[0], "delegate:")) ReceiverEff = StopTracking;
1160 }
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001161
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001162
Ted Kremenek174a0772009-04-23 23:08:22 +00001163 // Look for methods that return an owned object.
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001164 if (isTrackedObjCObjectType(RetTy)) {
1165 // EXPERIMENTAL: Assume the Cocoa conventions for all objects returned
1166 // by instance methods.
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001167
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001168 RetEffect E =
1169 followsFundamentalRule(S.getIdentifierInfoForSlot(0)->getName())
1170 ? (isGCEnabled() ? RetEffect::MakeGCNotOwned()
1171 : RetEffect::MakeOwned(RetEffect::ObjC, true))
1172 : RetEffect::MakeNotOwned(RetEffect::ObjC);
1173
1174 return getPersistentSummary(E, ReceiverEff, MayEscape);
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001175 }
Ted Kremenek174a0772009-04-23 23:08:22 +00001176
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001177 // Look for methods that return an owned core foundation object.
1178 if (isTrackedCFObjectType(RetTy)) {
1179 RetEffect E =
1180 followsFundamentalRule(S.getIdentifierInfoForSlot(0)->getName())
1181 ? RetEffect::MakeOwned(RetEffect::CF, true)
1182 : RetEffect::MakeNotOwned(RetEffect::CF);
1183
1184 return getPersistentSummary(E, ReceiverEff, MayEscape);
1185 }
Ted Kremenek174a0772009-04-23 23:08:22 +00001186
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001187 if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing)
1188 return 0;
Ted Kremenek174a0772009-04-23 23:08:22 +00001189
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001190 return getPersistentSummary(RetEffect::MakeNoRet(), ReceiverEff,
1191 MayEscape);
Ted Kremenek174a0772009-04-23 23:08:22 +00001192}
1193
1194RetainSummary*
Ted Kremenek04e00302009-04-29 17:09:14 +00001195RetainSummaryManager::getInstanceMethodSummary(Selector S,
1196 IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +00001197 const ObjCInterfaceDecl* ID,
1198 const ObjCMethodDecl *MD,
Ted Kremenek04e00302009-04-29 17:09:14 +00001199 QualType RetTy) {
Ted Kremenekbcaff792008-05-06 15:44:25 +00001200
Ted Kremeneka821b792009-04-29 05:04:30 +00001201 // Look up a summary in our summary cache.
1202 ObjCMethodSummariesTy::iterator I = ObjCMethodSummaries.find(ID, ClsName, S);
Ted Kremenek42ea0322008-05-05 23:55:01 +00001203
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001204 if (I != ObjCMethodSummaries.end())
Ted Kremenek42ea0322008-05-05 23:55:01 +00001205 return I->second;
Ted Kremenek42ea0322008-05-05 23:55:01 +00001206
Ted Kremeneka56ae162009-05-03 05:20:50 +00001207 assert(ScratchArgs.isEmpty());
Ted Kremenek923fc392009-04-24 23:32:32 +00001208
1209 // Annotations take precedence over all other ways to derive
1210 // summaries.
Ted Kremeneka821b792009-04-29 05:04:30 +00001211 RetainSummary *Summ = getMethodSummaryFromAnnotations(MD);
Ted Kremenek1d3d9562008-05-06 06:09:09 +00001212
Ted Kremenek923fc392009-04-24 23:32:32 +00001213 if (!Summ) {
1214 // "initXXX": pass-through for receiver.
1215 if (deriveNamingConvention(S.getIdentifierInfoForSlot(0)->getName())
1216 == InitRule)
Ted Kremeneka821b792009-04-29 05:04:30 +00001217 Summ = getInitMethodSummary(RetTy);
1218 else
1219 Summ = getCommonMethodSummary(MD, S, RetTy);
Ted Kremenek923fc392009-04-24 23:32:32 +00001220 }
1221
Ted Kremeneka821b792009-04-29 05:04:30 +00001222 ObjCMethodSummaries[ObjCSummaryKey(ClsName, S)] = Summ;
Ted Kremeneke4158502009-04-23 19:11:35 +00001223 return Summ;
Ted Kremenek42ea0322008-05-05 23:55:01 +00001224}
1225
Ted Kremeneka7722b72008-05-06 21:26:51 +00001226RetainSummary*
Ted Kremenek578498a2009-04-29 00:42:39 +00001227RetainSummaryManager::getClassMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +00001228 const ObjCInterfaceDecl *ID,
1229 const ObjCMethodDecl *MD,
1230 QualType RetTy) {
Ted Kremenekccbe79a2009-04-24 17:50:11 +00001231
Ted Kremenek578498a2009-04-29 00:42:39 +00001232 assert(ClsName && "Class name must be specified.");
Ted Kremeneka821b792009-04-29 05:04:30 +00001233 ObjCMethodSummariesTy::iterator I =
1234 ObjCClassMethodSummaries.find(ID, ClsName, S);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001235
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001236 if (I != ObjCClassMethodSummaries.end())
Ted Kremeneka7722b72008-05-06 21:26:51 +00001237 return I->second;
1238
Ted Kremenek923fc392009-04-24 23:32:32 +00001239 // Annotations take precedence over all other ways to derive
1240 // summaries.
Ted Kremenek578498a2009-04-29 00:42:39 +00001241 RetainSummary *Summ = getMethodSummaryFromAnnotations(MD);
Ted Kremenek923fc392009-04-24 23:32:32 +00001242
1243 if (!Summ)
Ted Kremenek578498a2009-04-29 00:42:39 +00001244 Summ = getCommonMethodSummary(MD, S, RetTy);
Ted Kremenek923fc392009-04-24 23:32:32 +00001245
Ted Kremenek578498a2009-04-29 00:42:39 +00001246 ObjCClassMethodSummaries[ObjCSummaryKey(ClsName, S)] = Summ;
Ted Kremeneke4158502009-04-23 19:11:35 +00001247 return Summ;
Ted Kremeneka7722b72008-05-06 21:26:51 +00001248}
1249
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001250void RetainSummaryManager::InitializeClassMethodSummaries() {
Ted Kremenek0e344d42008-05-06 00:30:21 +00001251
Ted Kremeneka56ae162009-05-03 05:20:50 +00001252 assert (ScratchArgs.isEmpty());
Ted Kremenek0e344d42008-05-06 00:30:21 +00001253
Ted Kremenek382fb4e2009-04-27 19:14:45 +00001254 RetEffect E = isGCEnabled() ? RetEffect::MakeGCNotOwned()
Ted Kremenek68621b92009-01-28 05:56:51 +00001255 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001256
Ted Kremenek0e344d42008-05-06 00:30:21 +00001257 RetainSummary* Summ = getPersistentSummary(E);
1258
Ted Kremenek272aa852008-06-25 21:21:56 +00001259 // Create the summaries for "alloc", "new", and "allocWithZone:" for
1260 // NSObject and its derivatives.
1261 addNSObjectClsMethSummary(GetNullarySelector("alloc", Ctx), Summ);
1262 addNSObjectClsMethSummary(GetNullarySelector("new", Ctx), Summ);
1263 addNSObjectClsMethSummary(GetUnarySelector("allocWithZone", Ctx), Summ);
Ted Kremenekf2717b02008-07-18 17:24:20 +00001264
1265 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001266 addClsMethSummary(&Ctx.Idents.get("NSAssertionHandler"),
Ted Kremenek68621b92009-01-28 05:56:51 +00001267 GetNullarySelector("currentHandler", Ctx),
1268 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001269
1270 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremeneka56ae162009-05-03 05:20:50 +00001271 ScratchArgs = AF.Add(ScratchArgs, 0, Autorelease);
Ted Kremenek9b112d22009-01-28 21:44:40 +00001272 addClsMethSummary(&Ctx.Idents.get("NSAutoreleasePool"),
1273 GetUnarySelector("addObject", Ctx),
1274 getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenekf21cb242009-02-23 02:31:16 +00001275 DoNothing, Autorelease));
Ted Kremenekccbe79a2009-04-24 17:50:11 +00001276
1277 // Create the summaries for [NSObject performSelector...]. We treat
1278 // these as 'stop tracking' for the arguments because they are often
1279 // used for delegates that can release the object. When we have better
1280 // inter-procedural analysis we can potentially do something better. This
1281 // workaround is to remove false positives.
1282 Summ = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, StopTracking);
1283 IdentifierInfo *NSObjectII = &Ctx.Idents.get("NSObject");
1284 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1285 "afterDelay", NULL);
1286 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1287 "afterDelay", "inModes", NULL);
1288 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1289 "withObject", "waitUntilDone", NULL);
1290 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1291 "withObject", "waitUntilDone", "modes", NULL);
1292 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1293 "withObject", "waitUntilDone", NULL);
1294 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1295 "withObject", "waitUntilDone", "modes", NULL);
1296 addClsMethSummary(NSObjectII, Summ, "performSelectorInBackground",
1297 "withObject", NULL);
Ted Kremenek0e344d42008-05-06 00:30:21 +00001298}
1299
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001300void RetainSummaryManager::InitializeMethodSummaries() {
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001301
Ted Kremeneka56ae162009-05-03 05:20:50 +00001302 assert (ScratchArgs.isEmpty());
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001303
Ted Kremeneka7722b72008-05-06 21:26:51 +00001304 // Create the "init" selector. It just acts as a pass-through for the
1305 // receiver.
Ted Kremenek56c70aa2009-02-23 16:54:00 +00001306 RetainSummary* InitSumm =
1307 getPersistentSummary(RetEffect::MakeReceiverAlias());
Ted Kremeneke44927e2008-07-01 17:21:27 +00001308 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001309
1310 // The next methods are allocators.
Ted Kremenek382fb4e2009-04-27 19:14:45 +00001311 RetEffect E = isGCEnabled() ? RetEffect::MakeGCNotOwned()
Ted Kremenek68621b92009-01-28 05:56:51 +00001312 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001313
Ted Kremeneke44927e2008-07-01 17:21:27 +00001314 RetainSummary* Summ = getPersistentSummary(E);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001315
1316 // Create the "copy" selector.
Ted Kremenek9449ca92008-08-12 20:41:56 +00001317 addNSObjectMethSummary(GetNullarySelector("copy", Ctx), Summ);
1318
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001319 // Create the "mutableCopy" selector.
Ted Kremenek272aa852008-06-25 21:21:56 +00001320 addNSObjectMethSummary(GetNullarySelector("mutableCopy", Ctx), Summ);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001321
Ted Kremenek266d8b62008-05-06 02:26:56 +00001322 // Create the "retain" selector.
1323 E = RetEffect::MakeReceiverAlias();
Ted Kremenek58dd95b2009-02-18 18:54:33 +00001324 Summ = getPersistentSummary(E, IncRefMsg);
Ted Kremenek272aa852008-06-25 21:21:56 +00001325 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001326
1327 // Create the "release" selector.
Ted Kremenek58dd95b2009-02-18 18:54:33 +00001328 Summ = getPersistentSummary(E, DecRefMsg);
Ted Kremenek272aa852008-06-25 21:21:56 +00001329 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Ted Kremenekc00b32b2008-05-07 21:17:39 +00001330
1331 // Create the "drain" selector.
1332 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek272aa852008-06-25 21:21:56 +00001333 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
Ted Kremenek6537a642009-03-17 19:42:23 +00001334
1335 // Create the -dealloc summary.
1336 Summ = getPersistentSummary(RetEffect::MakeNoRet(), Dealloc);
1337 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001338
1339 // Create the "autorelease" selector.
Ted Kremenek9b112d22009-01-28 21:44:40 +00001340 Summ = getPersistentSummary(E, Autorelease);
Ted Kremenek272aa852008-06-25 21:21:56 +00001341 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001342
Ted Kremenekaac82832009-02-23 17:45:03 +00001343 // Specially handle NSAutoreleasePool.
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001344 addInstMethSummary("NSAutoreleasePool", "init",
Ted Kremenekaac82832009-02-23 17:45:03 +00001345 getPersistentSummary(RetEffect::MakeReceiverAlias(),
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001346 NewAutoreleasePool));
Ted Kremenekaac82832009-02-23 17:45:03 +00001347
Ted Kremenek45642a42008-08-12 18:48:50 +00001348 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremenek7e3a3272009-02-23 02:51:29 +00001349 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1350 // self-own themselves. However, they only do this once they are displayed.
1351 // Thus, we need to track an NSWindow's display status.
1352 // This is tracked in <rdar://problem/6062711>.
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001353 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
Ted Kremeneke5a036a2009-04-03 19:02:51 +00001354 RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet());
1355
1356 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1357
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001358
1359#if 0
Ted Kremeneke44927e2008-07-01 17:21:27 +00001360 RetainSummary *NSWindowSumm =
Ted Kremenek7e3a3272009-02-23 02:51:29 +00001361 getPersistentSummary(RetEffect::MakeReceiverAlias(), StopTracking);
Ted Kremenek45642a42008-08-12 18:48:50 +00001362
1363 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1364 "styleMask", "backing", "defer", NULL);
1365
1366 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1367 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001368#endif
Ted Kremenek45642a42008-08-12 18:48:50 +00001369
1370 // For NSPanel (which subclasses NSWindow), allocated objects are not
1371 // self-owned.
Ted Kremeneke5a036a2009-04-03 19:02:51 +00001372 // FIXME: For now we don't track NSPanels. object for the same reason
1373 // as for NSWindow objects.
1374 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
1375
Ted Kremenek45642a42008-08-12 18:48:50 +00001376 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1377 "styleMask", "backing", "defer", NULL);
1378
1379 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1380 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek272aa852008-06-25 21:21:56 +00001381
Ted Kremenekf2717b02008-07-18 17:24:20 +00001382 // Create NSAssertionHandler summaries.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001383 addPanicSummary("NSAssertionHandler", "handleFailureInFunction", "file",
1384 "lineNumber", "description", NULL);
Ted Kremenekf2717b02008-07-18 17:24:20 +00001385
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001386 addPanicSummary("NSAssertionHandler", "handleFailureInMethod", "object",
1387 "file", "lineNumber", "description", NULL);
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001388}
1389
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001390//===----------------------------------------------------------------------===//
Ted Kremenek7aef4842008-04-16 20:40:59 +00001391// Reference-counting logic (typestate + counts).
Ted Kremeneka7338b42008-03-11 06:39:11 +00001392//===----------------------------------------------------------------------===//
1393
Ted Kremeneka7338b42008-03-11 06:39:11 +00001394namespace {
1395
Ted Kremenek7d421f32008-04-09 23:49:11 +00001396class VISIBILITY_HIDDEN RefVal {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001397public:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001398 enum Kind {
1399 Owned = 0, // Owning reference.
1400 NotOwned, // Reference is not owned by still valid (not freed).
1401 Released, // Object has been released.
1402 ReturnedOwned, // Returned object passes ownership to caller.
1403 ReturnedNotOwned, // Return object does not pass ownership to caller.
Ted Kremenek6537a642009-03-17 19:42:23 +00001404 ERROR_START,
1405 ErrorDeallocNotOwned, // -dealloc called on non-owned object.
1406 ErrorDeallocGC, // Calling -dealloc with GC enabled.
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001407 ErrorUseAfterRelease, // Object used after released.
1408 ErrorReleaseNotOwned, // Release of an object that was not owned.
Ted Kremenek6537a642009-03-17 19:42:23 +00001409 ERROR_LEAK_START,
Ted Kremenek311f3d42008-10-22 23:56:21 +00001410 ErrorLeak, // A memory leak due to excessive reference counts.
1411 ErrorLeakReturned // A memory leak due to the returning method not having
1412 // the correct naming conventions.
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001413 };
Ted Kremenek68621b92009-01-28 05:56:51 +00001414
1415private:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001416 Kind kind;
Ted Kremenek68621b92009-01-28 05:56:51 +00001417 RetEffect::ObjKind okind;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001418 unsigned Cnt;
Ted Kremenek272aa852008-06-25 21:21:56 +00001419 QualType T;
1420
Ted Kremenek68621b92009-01-28 05:56:51 +00001421 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, QualType t)
1422 : kind(k), okind(o), Cnt(cnt), T(t) {}
Ted Kremenek0d721572008-03-11 17:48:22 +00001423
Ted Kremenek68621b92009-01-28 05:56:51 +00001424 RefVal(Kind k, unsigned cnt = 0)
1425 : kind(k), okind(RetEffect::AnyObj), Cnt(cnt) {}
1426
1427public:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001428 Kind getKind() const { return kind; }
Ted Kremenek68621b92009-01-28 05:56:51 +00001429
1430 RetEffect::ObjKind getObjKind() const { return okind; }
Ted Kremenek0d721572008-03-11 17:48:22 +00001431
Ted Kremenek6537a642009-03-17 19:42:23 +00001432 unsigned getCount() const { return Cnt; }
1433 void clearCounts() { Cnt = 0; }
1434
Ted Kremenek272aa852008-06-25 21:21:56 +00001435 QualType getType() const { return T; }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001436
1437 // Useful predicates.
Ted Kremenek0d721572008-03-11 17:48:22 +00001438
Ted Kremenek6537a642009-03-17 19:42:23 +00001439 static bool isError(Kind k) { return k >= ERROR_START; }
Ted Kremenek1daa16c2008-03-11 18:14:09 +00001440
Ted Kremenek6537a642009-03-17 19:42:23 +00001441 static bool isLeak(Kind k) { return k >= ERROR_LEAK_START; }
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001442
Ted Kremenekffefc352008-04-11 22:25:11 +00001443 bool isOwned() const {
1444 return getKind() == Owned;
1445 }
1446
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001447 bool isNotOwned() const {
1448 return getKind() == NotOwned;
1449 }
1450
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001451 bool isReturnedOwned() const {
1452 return getKind() == ReturnedOwned;
1453 }
1454
1455 bool isReturnedNotOwned() const {
1456 return getKind() == ReturnedNotOwned;
1457 }
1458
1459 bool isNonLeakError() const {
1460 Kind k = getKind();
1461 return isError(k) && !isLeak(k);
1462 }
1463
Ted Kremenek68621b92009-01-28 05:56:51 +00001464 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
1465 unsigned Count = 1) {
1466 return RefVal(Owned, o, Count, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001467 }
1468
Ted Kremenek68621b92009-01-28 05:56:51 +00001469 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
1470 unsigned Count = 0) {
1471 return RefVal(NotOwned, o, Count, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001472 }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001473
1474 static RefVal makeReturnedOwned(unsigned Count) {
1475 return RefVal(ReturnedOwned, Count);
1476 }
1477
1478 static RefVal makeReturnedNotOwned() {
1479 return RefVal(ReturnedNotOwned);
1480 }
1481
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001482 // Comparison, profiling, and pretty-printing.
Ted Kremenek0d721572008-03-11 17:48:22 +00001483
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001484 bool operator==(const RefVal& X) const {
Ted Kremenek272aa852008-06-25 21:21:56 +00001485 return kind == X.kind && Cnt == X.Cnt && T == X.T;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001486 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001487
Ted Kremenek272aa852008-06-25 21:21:56 +00001488 RefVal operator-(size_t i) const {
Ted Kremenek68621b92009-01-28 05:56:51 +00001489 return RefVal(getKind(), getObjKind(), getCount() - i, getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001490 }
1491
1492 RefVal operator+(size_t i) const {
Ted Kremenek68621b92009-01-28 05:56:51 +00001493 return RefVal(getKind(), getObjKind(), getCount() + i, getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001494 }
1495
1496 RefVal operator^(Kind k) const {
Ted Kremenek68621b92009-01-28 05:56:51 +00001497 return RefVal(k, getObjKind(), getCount(), getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001498 }
Ted Kremenek6537a642009-03-17 19:42:23 +00001499
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001500 void Profile(llvm::FoldingSetNodeID& ID) const {
1501 ID.AddInteger((unsigned) kind);
1502 ID.AddInteger(Cnt);
Ted Kremenek272aa852008-06-25 21:21:56 +00001503 ID.Add(T);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001504 }
1505
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001506 void print(std::ostream& Out) const;
Ted Kremenek0d721572008-03-11 17:48:22 +00001507};
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001508
1509void RefVal::print(std::ostream& Out) const {
Ted Kremenek272aa852008-06-25 21:21:56 +00001510 if (!T.isNull())
1511 Out << "Tracked Type:" << T.getAsString() << '\n';
1512
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001513 switch (getKind()) {
1514 default: assert(false);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001515 case Owned: {
1516 Out << "Owned";
1517 unsigned cnt = getCount();
1518 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001519 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001520 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001521
Ted Kremenekc4f81022008-04-10 23:09:18 +00001522 case NotOwned: {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001523 Out << "NotOwned";
Ted Kremenekc4f81022008-04-10 23:09:18 +00001524 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 Kremenekd9ccf682008-04-17 18:12:53 +00001529 case ReturnedOwned: {
1530 Out << "ReturnedOwned";
1531 unsigned cnt = getCount();
1532 if (cnt) Out << " (+ " << cnt << ")";
1533 break;
1534 }
1535
1536 case ReturnedNotOwned: {
1537 Out << "ReturnedNotOwned";
1538 unsigned cnt = getCount();
1539 if (cnt) Out << " (+ " << cnt << ")";
1540 break;
1541 }
1542
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001543 case Released:
1544 Out << "Released";
1545 break;
Ted Kremenek6537a642009-03-17 19:42:23 +00001546
1547 case ErrorDeallocGC:
1548 Out << "-dealloc (GC)";
1549 break;
1550
1551 case ErrorDeallocNotOwned:
1552 Out << "-dealloc (not-owned)";
1553 break;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001554
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001555 case ErrorLeak:
1556 Out << "Leaked";
1557 break;
1558
Ted Kremenek311f3d42008-10-22 23:56:21 +00001559 case ErrorLeakReturned:
1560 Out << "Leaked (Bad naming)";
1561 break;
1562
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001563 case ErrorUseAfterRelease:
1564 Out << "Use-After-Release [ERROR]";
1565 break;
1566
1567 case ErrorReleaseNotOwned:
1568 Out << "Release of Not-Owned [ERROR]";
1569 break;
1570 }
1571}
Ted Kremenek0d721572008-03-11 17:48:22 +00001572
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001573} // end anonymous namespace
1574
1575//===----------------------------------------------------------------------===//
1576// RefBindings - State used to track object reference counts.
1577//===----------------------------------------------------------------------===//
1578
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001579typedef llvm::ImmutableMap<SymbolRef, RefVal> RefBindings;
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001580static int RefBIndex = 0;
Ted Kremenek876d8df2009-02-19 23:47:02 +00001581static std::pair<const void*, const void*> LeakProgramPointTag(&RefBIndex, 0);
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001582
1583namespace clang {
Ted Kremenek91781202008-08-17 03:20:02 +00001584 template<>
1585 struct GRStateTrait<RefBindings> : public GRStatePartialTrait<RefBindings> {
1586 static inline void* GDMIndex() { return &RefBIndex; }
1587 };
1588}
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001589
1590//===----------------------------------------------------------------------===//
Ted Kremenekb6578942009-02-24 19:15:11 +00001591// AutoreleaseBindings - State used to track objects in autorelease pools.
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001592//===----------------------------------------------------------------------===//
1593
Ted Kremenekb6578942009-02-24 19:15:11 +00001594typedef llvm::ImmutableMap<SymbolRef, unsigned> ARCounts;
1595typedef llvm::ImmutableMap<SymbolRef, ARCounts> ARPoolContents;
1596typedef llvm::ImmutableList<SymbolRef> ARStack;
Ted Kremenekaac82832009-02-23 17:45:03 +00001597
Ted Kremenekb6578942009-02-24 19:15:11 +00001598static int AutoRCIndex = 0;
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001599static int AutoRBIndex = 0;
1600
Ted Kremenekb6578942009-02-24 19:15:11 +00001601namespace { class VISIBILITY_HIDDEN AutoreleasePoolContents {}; }
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001602namespace { class VISIBILITY_HIDDEN AutoreleaseStack {}; }
Ted Kremenekb6578942009-02-24 19:15:11 +00001603
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001604namespace clang {
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001605template<> struct GRStateTrait<AutoreleaseStack>
Ted Kremenekb6578942009-02-24 19:15:11 +00001606 : public GRStatePartialTrait<ARStack> {
1607 static inline void* GDMIndex() { return &AutoRBIndex; }
1608};
1609
1610template<> struct GRStateTrait<AutoreleasePoolContents>
1611 : public GRStatePartialTrait<ARPoolContents> {
1612 static inline void* GDMIndex() { return &AutoRCIndex; }
1613};
1614} // end clang namespace
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001615
Ted Kremenek681fb352009-03-20 17:34:15 +00001616static SymbolRef GetCurrentAutoreleasePool(const GRState* state) {
1617 ARStack stack = state->get<AutoreleaseStack>();
1618 return stack.isEmpty() ? SymbolRef() : stack.getHead();
1619}
1620
1621static GRStateRef SendAutorelease(GRStateRef state, ARCounts::Factory &F,
1622 SymbolRef sym) {
1623
1624 SymbolRef pool = GetCurrentAutoreleasePool(state);
1625 const ARCounts *cnts = state.get<AutoreleasePoolContents>(pool);
1626 ARCounts newCnts(0);
1627
1628 if (cnts) {
1629 const unsigned *cnt = (*cnts).lookup(sym);
1630 newCnts = F.Add(*cnts, sym, cnt ? *cnt + 1 : 1);
1631 }
1632 else
1633 newCnts = F.Add(F.GetEmptyMap(), sym, 1);
1634
1635 return state.set<AutoreleasePoolContents>(pool, newCnts);
1636}
1637
Ted Kremenek7aef4842008-04-16 20:40:59 +00001638//===----------------------------------------------------------------------===//
1639// Transfer functions.
1640//===----------------------------------------------------------------------===//
1641
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001642namespace {
1643
Ted Kremenek7d421f32008-04-09 23:49:11 +00001644class VISIBILITY_HIDDEN CFRefCount : public GRSimpleVals {
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001645public:
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001646 class BindingsPrinter : public GRState::Printer {
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001647 public:
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001648 virtual void Print(std::ostream& Out, const GRState* state,
1649 const char* nl, const char* sep);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001650 };
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001651
1652private:
Ted Kremenekc26c4692009-02-18 03:48:14 +00001653 typedef llvm::DenseMap<const GRExprEngine::NodeTy*, const RetainSummary*>
1654 SummaryLogTy;
1655
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001656 RetainSummaryManager Summaries;
Ted Kremenekc26c4692009-02-18 03:48:14 +00001657 SummaryLogTy SummaryLog;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001658 const LangOptions& LOpts;
Ted Kremenekb6578942009-02-24 19:15:11 +00001659 ARCounts::Factory ARCountFactory;
Ted Kremenek91781202008-08-17 03:20:02 +00001660
Ted Kremenek708af042009-02-05 06:50:21 +00001661 BugType *useAfterRelease, *releaseNotOwned;
Ted Kremenek6537a642009-03-17 19:42:23 +00001662 BugType *deallocGC, *deallocNotOwned;
Ted Kremenek708af042009-02-05 06:50:21 +00001663 BugType *leakWithinFunction, *leakAtReturn;
1664 BugReporter *BR;
Ted Kremeneka7338b42008-03-11 06:39:11 +00001665
Ted Kremenekb6578942009-02-24 19:15:11 +00001666 GRStateRef Update(GRStateRef state, SymbolRef sym, RefVal V, ArgEffect E,
1667 RefVal::Kind& hasErr);
1668
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001669 void ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
1670 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001671 Expr* NodeExpr, Expr* ErrorExpr,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001672 ExplodedNode<GRState>* Pred,
1673 const GRState* St,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001674 RefVal::Kind hasErr, SymbolRef Sym);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001675
Ted Kremenek0106e202008-10-24 20:32:50 +00001676 std::pair<GRStateRef, bool>
1677 HandleSymbolDeath(GRStateManager& VMgr, const GRState* St,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001678 const Decl* CD, SymbolRef sid, RefVal V, bool& hasLeak);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001679
Ted Kremenekb6578942009-02-24 19:15:11 +00001680public:
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00001681 CFRefCount(ASTContext& Ctx, bool gcenabled, const LangOptions& lopts)
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001682 : Summaries(Ctx, gcenabled),
Ted Kremenek6537a642009-03-17 19:42:23 +00001683 LOpts(lopts), useAfterRelease(0), releaseNotOwned(0),
1684 deallocGC(0), deallocNotOwned(0),
Ted Kremenek708af042009-02-05 06:50:21 +00001685 leakWithinFunction(0), leakAtReturn(0), BR(0) {}
Ted Kremenek1feab292008-04-16 04:28:53 +00001686
Ted Kremenek708af042009-02-05 06:50:21 +00001687 virtual ~CFRefCount() {}
Ted Kremenek7d421f32008-04-09 23:49:11 +00001688
Ted Kremenekbf6babf2009-02-04 23:49:09 +00001689 void RegisterChecks(BugReporter &BR);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001690
Ted Kremenekb0f2b9e2008-08-16 00:49:49 +00001691 virtual void RegisterPrinters(std::vector<GRState::Printer*>& Printers) {
1692 Printers.push_back(new BindingsPrinter());
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001693 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00001694
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001695 bool isGCEnabled() const { return Summaries.isGCEnabled(); }
Ted Kremenekfe30beb2008-04-30 23:47:44 +00001696 const LangOptions& getLangOptions() const { return LOpts; }
1697
Ted Kremenekc26c4692009-02-18 03:48:14 +00001698 const RetainSummary *getSummaryOfNode(const ExplodedNode<GRState> *N) const {
1699 SummaryLogTy::const_iterator I = SummaryLog.find(N);
1700 return I == SummaryLog.end() ? 0 : I->second;
1701 }
1702
Ted Kremeneka7338b42008-03-11 06:39:11 +00001703 // Calls.
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001704
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001705 void EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001706 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001707 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001708 Expr* Ex,
1709 Expr* Receiver,
1710 RetainSummary* Summ,
Ted Kremenek2719e982008-06-17 02:43:46 +00001711 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001712 ExplodedNode<GRState>* Pred);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001713
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001714 virtual void EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekce0767f2008-03-12 21:06:49 +00001715 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001716 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001717 CallExpr* CE, SVal L,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001718 ExplodedNode<GRState>* Pred);
Ted Kremenek10fe66d2008-04-09 01:10:13 +00001719
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001720
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001721 virtual void EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001722 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001723 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001724 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001725 ExplodedNode<GRState>* Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001726
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001727 bool EvalObjCMessageExprAux(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001728 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001729 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001730 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001731 ExplodedNode<GRState>* Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001732
Ted Kremeneka42be302009-02-14 01:43:44 +00001733 // Stores.
1734 virtual void EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val);
1735
Ted Kremenekffefc352008-04-11 22:25:11 +00001736 // End-of-path.
1737
1738 virtual void EvalEndPath(GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001739 GREndPathNodeBuilder<GRState>& Builder);
Ted Kremenekffefc352008-04-11 22:25:11 +00001740
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001741 virtual void EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek541db372008-04-24 23:57:27 +00001742 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001743 GRStmtNodeBuilder<GRState>& Builder,
1744 ExplodedNode<GRState>* Pred,
Ted Kremenek5c0729b2009-01-21 22:26:05 +00001745 Stmt* S, const GRState* state,
1746 SymbolReaper& SymReaper);
1747
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001748 // Return statements.
1749
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001750 virtual void EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001751 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001752 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001753 ReturnStmt* S,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001754 ExplodedNode<GRState>* Pred);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001755
1756 // Assumptions.
1757
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001758 virtual const GRState* EvalAssume(GRStateManager& VMgr,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001759 const GRState* St, SVal Cond,
Ted Kremenekf22f8682008-07-10 22:03:41 +00001760 bool Assumption, bool& isFeasible);
Ted Kremeneka7338b42008-03-11 06:39:11 +00001761};
1762
1763} // end anonymous namespace
1764
Ted Kremenek681fb352009-03-20 17:34:15 +00001765static void PrintPool(std::ostream &Out, SymbolRef Sym, const GRState *state) {
1766 Out << ' ';
Ted Kremenek74556a12009-03-26 03:35:11 +00001767 if (Sym)
1768 Out << Sym->getSymbolID();
Ted Kremenek681fb352009-03-20 17:34:15 +00001769 else
1770 Out << "<pool>";
1771 Out << ":{";
1772
1773 // Get the contents of the pool.
1774 if (const ARCounts *cnts = state->get<AutoreleasePoolContents>(Sym))
1775 for (ARCounts::iterator J=cnts->begin(), EJ=cnts->end(); J != EJ; ++J)
1776 Out << '(' << J.getKey() << ',' << J.getData() << ')';
1777
1778 Out << '}';
1779}
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001780
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001781void CFRefCount::BindingsPrinter::Print(std::ostream& Out, const GRState* state,
1782 const char* nl, const char* sep) {
Ted Kremenek681fb352009-03-20 17:34:15 +00001783
1784
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001785
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001786 RefBindings B = state->get<RefBindings>();
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001787
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001788 if (!B.isEmpty())
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001789 Out << sep << nl;
1790
1791 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
1792 Out << (*I).first << " : ";
1793 (*I).second.print(Out);
1794 Out << nl;
1795 }
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001796
1797 // Print the autorelease stack.
Ted Kremenek681fb352009-03-20 17:34:15 +00001798 Out << sep << nl << "AR pool stack:";
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001799 ARStack stack = state->get<AutoreleaseStack>();
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001800
Ted Kremenek681fb352009-03-20 17:34:15 +00001801 PrintPool(Out, SymbolRef(), state); // Print the caller's pool.
1802 for (ARStack::iterator I=stack.begin(), E=stack.end(); I!=E; ++I)
1803 PrintPool(Out, *I, state);
1804
1805 Out << nl;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001806}
1807
Ted Kremenek47a72422009-04-29 18:50:19 +00001808//===----------------------------------------------------------------------===//
1809// Error reporting.
1810//===----------------------------------------------------------------------===//
1811
1812namespace {
1813
1814 //===-------------===//
1815 // Bug Descriptions. //
1816 //===-------------===//
1817
1818 class VISIBILITY_HIDDEN CFRefBug : public BugType {
1819 protected:
1820 CFRefCount& TF;
1821
1822 CFRefBug(CFRefCount* tf, const char* name)
1823 : BugType(name, "Memory (Core Foundation/Objective-C)"), TF(*tf) {}
1824 public:
1825
1826 CFRefCount& getTF() { return TF; }
1827 const CFRefCount& getTF() const { return TF; }
1828
1829 // FIXME: Eventually remove.
1830 virtual const char* getDescription() const = 0;
1831
1832 virtual bool isLeak() const { return false; }
1833 };
1834
1835 class VISIBILITY_HIDDEN UseAfterRelease : public CFRefBug {
1836 public:
1837 UseAfterRelease(CFRefCount* tf)
1838 : CFRefBug(tf, "Use-after-release") {}
1839
1840 const char* getDescription() const {
1841 return "Reference-counted object is used after it is released";
1842 }
1843 };
1844
1845 class VISIBILITY_HIDDEN BadRelease : public CFRefBug {
1846 public:
1847 BadRelease(CFRefCount* tf) : CFRefBug(tf, "Bad release") {}
1848
1849 const char* getDescription() const {
1850 return "Incorrect decrement of the reference count of an "
1851 "object is not owned at this point by the caller";
1852 }
1853 };
1854
1855 class VISIBILITY_HIDDEN DeallocGC : public CFRefBug {
1856 public:
1857 DeallocGC(CFRefCount *tf) : CFRefBug(tf,
1858 "-dealloc called while using GC") {}
1859
1860 const char *getDescription() const {
1861 return "-dealloc called while using GC";
1862 }
1863 };
1864
1865 class VISIBILITY_HIDDEN DeallocNotOwned : public CFRefBug {
1866 public:
1867 DeallocNotOwned(CFRefCount *tf) : CFRefBug(tf,
1868 "-dealloc sent to non-exclusively owned object") {}
1869
1870 const char *getDescription() const {
1871 return "-dealloc sent to object that may be referenced elsewhere";
1872 }
1873 };
1874
1875 class VISIBILITY_HIDDEN Leak : public CFRefBug {
1876 const bool isReturn;
1877 protected:
1878 Leak(CFRefCount* tf, const char* name, bool isRet)
1879 : CFRefBug(tf, name), isReturn(isRet) {}
1880 public:
1881
1882 const char* getDescription() const { return ""; }
1883
1884 bool isLeak() const { return true; }
1885 };
1886
1887 class VISIBILITY_HIDDEN LeakAtReturn : public Leak {
1888 public:
1889 LeakAtReturn(CFRefCount* tf, const char* name)
1890 : Leak(tf, name, true) {}
1891 };
1892
1893 class VISIBILITY_HIDDEN LeakWithinFunction : public Leak {
1894 public:
1895 LeakWithinFunction(CFRefCount* tf, const char* name)
1896 : Leak(tf, name, false) {}
1897 };
1898
1899 //===---------===//
1900 // Bug Reports. //
1901 //===---------===//
1902
1903 class VISIBILITY_HIDDEN CFRefReport : public RangedBugReport {
1904 protected:
1905 SymbolRef Sym;
1906 const CFRefCount &TF;
1907 public:
1908 CFRefReport(CFRefBug& D, const CFRefCount &tf,
1909 ExplodedNode<GRState> *n, SymbolRef sym)
1910 : RangedBugReport(D, D.getDescription(), n), Sym(sym), TF(tf) {}
1911
1912 virtual ~CFRefReport() {}
1913
1914 CFRefBug& getBugType() {
1915 return (CFRefBug&) RangedBugReport::getBugType();
1916 }
1917 const CFRefBug& getBugType() const {
1918 return (const CFRefBug&) RangedBugReport::getBugType();
1919 }
1920
1921 virtual void getRanges(BugReporter& BR, const SourceRange*& beg,
1922 const SourceRange*& end) {
1923
1924 if (!getBugType().isLeak())
1925 RangedBugReport::getRanges(BR, beg, end);
1926 else
1927 beg = end = 0;
1928 }
1929
1930 SymbolRef getSymbol() const { return Sym; }
1931
1932 PathDiagnosticPiece* getEndPath(BugReporter& BR,
1933 const ExplodedNode<GRState>* N);
1934
1935 std::pair<const char**,const char**> getExtraDescriptiveText();
1936
1937 PathDiagnosticPiece* VisitNode(const ExplodedNode<GRState>* N,
1938 const ExplodedNode<GRState>* PrevN,
1939 const ExplodedGraph<GRState>& G,
1940 BugReporter& BR,
1941 NodeResolver& NR);
1942 };
1943
1944 class VISIBILITY_HIDDEN CFRefLeakReport : public CFRefReport {
1945 SourceLocation AllocSite;
1946 const MemRegion* AllocBinding;
1947 public:
1948 CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
1949 ExplodedNode<GRState> *n, SymbolRef sym,
1950 GRExprEngine& Eng);
1951
1952 PathDiagnosticPiece* getEndPath(BugReporter& BR,
1953 const ExplodedNode<GRState>* N);
1954
1955 SourceLocation getLocation() const { return AllocSite; }
1956 };
1957} // end anonymous namespace
1958
1959void CFRefCount::RegisterChecks(BugReporter& BR) {
1960 useAfterRelease = new UseAfterRelease(this);
1961 BR.Register(useAfterRelease);
1962
1963 releaseNotOwned = new BadRelease(this);
1964 BR.Register(releaseNotOwned);
1965
1966 deallocGC = new DeallocGC(this);
1967 BR.Register(deallocGC);
1968
1969 deallocNotOwned = new DeallocNotOwned(this);
1970 BR.Register(deallocNotOwned);
1971
1972 // First register "return" leaks.
1973 const char* name = 0;
1974
1975 if (isGCEnabled())
1976 name = "Leak of returned object when using garbage collection";
1977 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
1978 name = "Leak of returned object when not using garbage collection (GC) in "
1979 "dual GC/non-GC code";
1980 else {
1981 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
1982 name = "Leak of returned object";
1983 }
1984
1985 leakAtReturn = new LeakAtReturn(this, name);
1986 BR.Register(leakAtReturn);
1987
1988 // Second, register leaks within a function/method.
1989 if (isGCEnabled())
1990 name = "Leak of object when using garbage collection";
1991 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
1992 name = "Leak of object when not using garbage collection (GC) in "
1993 "dual GC/non-GC code";
1994 else {
1995 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
1996 name = "Leak";
1997 }
1998
1999 leakWithinFunction = new LeakWithinFunction(this, name);
2000 BR.Register(leakWithinFunction);
2001
2002 // Save the reference to the BugReporter.
2003 this->BR = &BR;
2004}
2005
2006static const char* Msgs[] = {
2007 // GC only
2008 "Code is compiled to only use garbage collection",
2009 // No GC.
2010 "Code is compiled to use reference counts",
2011 // Hybrid, with GC.
2012 "Code is compiled to use either garbage collection (GC) or reference counts"
2013 " (non-GC). The bug occurs with GC enabled",
2014 // Hybrid, without GC
2015 "Code is compiled to use either garbage collection (GC) or reference counts"
2016 " (non-GC). The bug occurs in non-GC mode"
2017};
2018
2019std::pair<const char**,const char**> CFRefReport::getExtraDescriptiveText() {
2020 CFRefCount& TF = static_cast<CFRefBug&>(getBugType()).getTF();
2021
2022 switch (TF.getLangOptions().getGCMode()) {
2023 default:
2024 assert(false);
2025
2026 case LangOptions::GCOnly:
2027 assert (TF.isGCEnabled());
2028 return std::make_pair(&Msgs[0], &Msgs[0]+1);
2029
2030 case LangOptions::NonGC:
2031 assert (!TF.isGCEnabled());
2032 return std::make_pair(&Msgs[1], &Msgs[1]+1);
2033
2034 case LangOptions::HybridGC:
2035 if (TF.isGCEnabled())
2036 return std::make_pair(&Msgs[2], &Msgs[2]+1);
2037 else
2038 return std::make_pair(&Msgs[3], &Msgs[3]+1);
2039 }
2040}
2041
2042static inline bool contains(const llvm::SmallVectorImpl<ArgEffect>& V,
2043 ArgEffect X) {
2044 for (llvm::SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
2045 I!=E; ++I)
2046 if (*I == X) return true;
2047
2048 return false;
2049}
2050
2051PathDiagnosticPiece* CFRefReport::VisitNode(const ExplodedNode<GRState>* N,
2052 const ExplodedNode<GRState>* PrevN,
2053 const ExplodedGraph<GRState>& G,
2054 BugReporter& BR,
2055 NodeResolver& NR) {
2056
2057 // Check if the type state has changed.
2058 GRStateManager &StMgr = cast<GRBugReporter>(BR).getStateManager();
2059 GRStateRef PrevSt(PrevN->getState(), StMgr);
2060 GRStateRef CurrSt(N->getState(), StMgr);
2061
2062 const RefVal* CurrT = CurrSt.get<RefBindings>(Sym);
2063 if (!CurrT) return NULL;
2064
2065 const RefVal& CurrV = *CurrT;
2066 const RefVal* PrevT = PrevSt.get<RefBindings>(Sym);
2067
2068 // Create a string buffer to constain all the useful things we want
2069 // to tell the user.
2070 std::string sbuf;
2071 llvm::raw_string_ostream os(sbuf);
2072
2073 // This is the allocation site since the previous node had no bindings
2074 // for this symbol.
2075 if (!PrevT) {
2076 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2077
2078 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2079 // Get the name of the callee (if it is available).
2080 SVal X = CurrSt.GetSValAsScalarOrLoc(CE->getCallee());
2081 if (const FunctionDecl* FD = X.getAsFunctionDecl())
2082 os << "Call to function '" << FD->getNameAsString() <<'\'';
2083 else
2084 os << "function call";
2085 }
2086 else {
2087 assert (isa<ObjCMessageExpr>(S));
2088 os << "Method";
2089 }
2090
2091 if (CurrV.getObjKind() == RetEffect::CF) {
2092 os << " returns a Core Foundation object with a ";
2093 }
2094 else {
2095 assert (CurrV.getObjKind() == RetEffect::ObjC);
2096 os << " returns an Objective-C object with a ";
2097 }
2098
2099 if (CurrV.isOwned()) {
2100 os << "+1 retain count (owning reference).";
2101
2102 if (static_cast<CFRefBug&>(getBugType()).getTF().isGCEnabled()) {
2103 assert(CurrV.getObjKind() == RetEffect::CF);
2104 os << " "
2105 "Core Foundation objects are not automatically garbage collected.";
2106 }
2107 }
2108 else {
2109 assert (CurrV.isNotOwned());
2110 os << "+0 retain count (non-owning reference).";
2111 }
2112
2113 PathDiagnosticLocation Pos(S, BR.getContext().getSourceManager());
2114 return new PathDiagnosticEventPiece(Pos, os.str());
2115 }
2116
2117 // Gather up the effects that were performed on the object at this
2118 // program point
2119 llvm::SmallVector<ArgEffect, 2> AEffects;
2120
2121 if (const RetainSummary *Summ = TF.getSummaryOfNode(NR.getOriginalNode(N))) {
2122 // We only have summaries attached to nodes after evaluating CallExpr and
2123 // ObjCMessageExprs.
2124 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2125
2126 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2127 // Iterate through the parameter expressions and see if the symbol
2128 // was ever passed as an argument.
2129 unsigned i = 0;
2130
2131 for (CallExpr::arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
2132 AI!=AE; ++AI, ++i) {
2133
2134 // Retrieve the value of the argument. Is it the symbol
2135 // we are interested in?
2136 if (CurrSt.GetSValAsScalarOrLoc(*AI).getAsLocSymbol() != Sym)
2137 continue;
2138
2139 // We have an argument. Get the effect!
2140 AEffects.push_back(Summ->getArg(i));
2141 }
2142 }
2143 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
2144 if (Expr *receiver = ME->getReceiver())
2145 if (CurrSt.GetSValAsScalarOrLoc(receiver).getAsLocSymbol() == Sym) {
2146 // The symbol we are tracking is the receiver.
2147 AEffects.push_back(Summ->getReceiverEffect());
2148 }
2149 }
2150 }
2151
2152 do {
2153 // Get the previous type state.
2154 RefVal PrevV = *PrevT;
2155
2156 // Specially handle -dealloc.
2157 if (!TF.isGCEnabled() && contains(AEffects, Dealloc)) {
2158 // Determine if the object's reference count was pushed to zero.
2159 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2160 // We may not have transitioned to 'release' if we hit an error.
2161 // This case is handled elsewhere.
2162 if (CurrV.getKind() == RefVal::Released) {
2163 assert(CurrV.getCount() == 0);
2164 os << "Object released by directly sending the '-dealloc' message";
2165 break;
2166 }
2167 }
2168
2169 // Specially handle CFMakeCollectable and friends.
2170 if (contains(AEffects, MakeCollectable)) {
2171 // Get the name of the function.
2172 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2173 SVal X = CurrSt.GetSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee());
2174 const FunctionDecl* FD = X.getAsFunctionDecl();
2175 const std::string& FName = FD->getNameAsString();
2176
2177 if (TF.isGCEnabled()) {
2178 // Determine if the object's reference count was pushed to zero.
2179 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2180
2181 os << "In GC mode a call to '" << FName
2182 << "' decrements an object's retain count and registers the "
2183 "object with the garbage collector. ";
2184
2185 if (CurrV.getKind() == RefVal::Released) {
2186 assert(CurrV.getCount() == 0);
2187 os << "Since it now has a 0 retain count the object can be "
2188 "automatically collected by the garbage collector.";
2189 }
2190 else
2191 os << "An object must have a 0 retain count to be garbage collected. "
2192 "After this call its retain count is +" << CurrV.getCount()
2193 << '.';
2194 }
2195 else
2196 os << "When GC is not enabled a call to '" << FName
2197 << "' has no effect on its argument.";
2198
2199 // Nothing more to say.
2200 break;
2201 }
2202
2203 // Determine if the typestate has changed.
2204 if (!(PrevV == CurrV))
2205 switch (CurrV.getKind()) {
2206 case RefVal::Owned:
2207 case RefVal::NotOwned:
2208
2209 if (PrevV.getCount() == CurrV.getCount())
2210 return 0;
2211
2212 if (PrevV.getCount() > CurrV.getCount())
2213 os << "Reference count decremented.";
2214 else
2215 os << "Reference count incremented.";
2216
2217 if (unsigned Count = CurrV.getCount())
2218 os << " The object now has a +" << Count << " retain count.";
2219
2220 if (PrevV.getKind() == RefVal::Released) {
2221 assert(TF.isGCEnabled() && CurrV.getCount() > 0);
2222 os << " The object is not eligible for garbage collection until the "
2223 "retain count reaches 0 again.";
2224 }
2225
2226 break;
2227
2228 case RefVal::Released:
2229 os << "Object released.";
2230 break;
2231
2232 case RefVal::ReturnedOwned:
2233 os << "Object returned to caller as an owning reference (single retain "
2234 "count transferred to caller).";
2235 break;
2236
2237 case RefVal::ReturnedNotOwned:
2238 os << "Object returned to caller with a +0 (non-owning) retain count.";
2239 break;
2240
2241 default:
2242 return NULL;
2243 }
2244
2245 // Emit any remaining diagnostics for the argument effects (if any).
2246 for (llvm::SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
2247 E=AEffects.end(); I != E; ++I) {
2248
2249 // A bunch of things have alternate behavior under GC.
2250 if (TF.isGCEnabled())
2251 switch (*I) {
2252 default: break;
2253 case Autorelease:
2254 os << "In GC mode an 'autorelease' has no effect.";
2255 continue;
2256 case IncRefMsg:
2257 os << "In GC mode the 'retain' message has no effect.";
2258 continue;
2259 case DecRefMsg:
2260 os << "In GC mode the 'release' message has no effect.";
2261 continue;
2262 }
2263 }
2264 } while(0);
2265
2266 if (os.str().empty())
2267 return 0; // We have nothing to say!
2268
2269 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2270 PathDiagnosticLocation Pos(S, BR.getContext().getSourceManager());
2271 PathDiagnosticPiece* P = new PathDiagnosticEventPiece(Pos, os.str());
2272
2273 // Add the range by scanning the children of the statement for any bindings
2274 // to Sym.
2275 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I)
2276 if (Expr* Exp = dyn_cast_or_null<Expr>(*I))
2277 if (CurrSt.GetSValAsScalarOrLoc(Exp).getAsLocSymbol() == Sym) {
2278 P->addRange(Exp->getSourceRange());
2279 break;
2280 }
2281
2282 return P;
2283}
2284
2285namespace {
2286 class VISIBILITY_HIDDEN FindUniqueBinding :
2287 public StoreManager::BindingsHandler {
2288 SymbolRef Sym;
2289 const MemRegion* Binding;
2290 bool First;
2291
2292 public:
2293 FindUniqueBinding(SymbolRef sym) : Sym(sym), Binding(0), First(true) {}
2294
2295 bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
2296 SVal val) {
2297
2298 SymbolRef SymV = val.getAsSymbol();
2299 if (!SymV || SymV != Sym)
2300 return true;
2301
2302 if (Binding) {
2303 First = false;
2304 return false;
2305 }
2306 else
2307 Binding = R;
2308
2309 return true;
2310 }
2311
2312 operator bool() { return First && Binding; }
2313 const MemRegion* getRegion() { return Binding; }
2314 };
2315}
2316
2317static std::pair<const ExplodedNode<GRState>*,const MemRegion*>
2318GetAllocationSite(GRStateManager& StateMgr, const ExplodedNode<GRState>* N,
2319 SymbolRef Sym) {
2320
2321 // Find both first node that referred to the tracked symbol and the
2322 // memory location that value was store to.
2323 const ExplodedNode<GRState>* Last = N;
2324 const MemRegion* FirstBinding = 0;
2325
2326 while (N) {
2327 const GRState* St = N->getState();
2328 RefBindings B = St->get<RefBindings>();
2329
2330 if (!B.lookup(Sym))
2331 break;
2332
2333 FindUniqueBinding FB(Sym);
2334 StateMgr.iterBindings(St, FB);
2335 if (FB) FirstBinding = FB.getRegion();
2336
2337 Last = N;
2338 N = N->pred_empty() ? NULL : *(N->pred_begin());
2339 }
2340
2341 return std::make_pair(Last, FirstBinding);
2342}
2343
2344PathDiagnosticPiece*
2345CFRefReport::getEndPath(BugReporter& br, const ExplodedNode<GRState>* EndN) {
2346 // Tell the BugReporter to report cases when the tracked symbol is
2347 // assigned to different variables, etc.
2348 GRBugReporter& BR = cast<GRBugReporter>(br);
2349 cast<GRBugReporter>(BR).addNotableSymbol(Sym);
2350 return RangedBugReport::getEndPath(BR, EndN);
2351}
2352
2353PathDiagnosticPiece*
2354CFRefLeakReport::getEndPath(BugReporter& br, const ExplodedNode<GRState>* EndN){
2355
2356 GRBugReporter& BR = cast<GRBugReporter>(br);
2357 // Tell the BugReporter to report cases when the tracked symbol is
2358 // assigned to different variables, etc.
2359 cast<GRBugReporter>(BR).addNotableSymbol(Sym);
2360
2361 // We are reporting a leak. Walk up the graph to get to the first node where
2362 // the symbol appeared, and also get the first VarDecl that tracked object
2363 // is stored to.
2364 const ExplodedNode<GRState>* AllocNode = 0;
2365 const MemRegion* FirstBinding = 0;
2366
2367 llvm::tie(AllocNode, FirstBinding) =
2368 GetAllocationSite(BR.getStateManager(), EndN, Sym);
2369
2370 // Get the allocate site.
2371 assert(AllocNode);
2372 Stmt* FirstStmt = cast<PostStmt>(AllocNode->getLocation()).getStmt();
2373
2374 SourceManager& SMgr = BR.getContext().getSourceManager();
2375 unsigned AllocLine =SMgr.getInstantiationLineNumber(FirstStmt->getLocStart());
2376
2377 // Compute an actual location for the leak. Sometimes a leak doesn't
2378 // occur at an actual statement (e.g., transition between blocks; end
2379 // of function) so we need to walk the graph and compute a real location.
2380 const ExplodedNode<GRState>* LeakN = EndN;
2381 PathDiagnosticLocation L;
2382
2383 while (LeakN) {
2384 ProgramPoint P = LeakN->getLocation();
2385
2386 if (const PostStmt *PS = dyn_cast<PostStmt>(&P)) {
2387 L = PathDiagnosticLocation(PS->getStmt()->getLocStart(), SMgr);
2388 break;
2389 }
2390 else if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
2391 if (const Stmt* Term = BE->getSrc()->getTerminator()) {
2392 L = PathDiagnosticLocation(Term->getLocStart(), SMgr);
2393 break;
2394 }
2395 }
2396
2397 LeakN = LeakN->succ_empty() ? 0 : *(LeakN->succ_begin());
2398 }
2399
2400 if (!L.isValid()) {
Ted Kremenek0a6913d2009-04-29 21:31:59 +00002401 const Decl &D = BR.getStateManager().getCodeDecl();
2402 L = PathDiagnosticLocation(D.getBodyRBrace(BR.getContext()), SMgr);
Ted Kremenek47a72422009-04-29 18:50:19 +00002403 }
2404
2405 std::string sbuf;
2406 llvm::raw_string_ostream os(sbuf);
2407
2408 os << "Object allocated on line " << AllocLine;
2409
2410 if (FirstBinding)
2411 os << " and stored into '" << FirstBinding->getString() << '\'';
2412
2413 // Get the retain count.
2414 const RefVal* RV = EndN->getState()->get<RefBindings>(Sym);
2415
2416 if (RV->getKind() == RefVal::ErrorLeakReturned) {
2417 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
2418 // ojbects. Only "copy", "alloc", "retain" and "new" transfer ownership
2419 // to the caller for NS objects.
2420 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(BR.getGraph().getCodeDecl());
2421 os << " is returned from a method whose name ('"
Ted Kremenek314b1952009-04-29 23:03:22 +00002422 << MD.getSelector().getAsString()
Ted Kremenek47a72422009-04-29 18:50:19 +00002423 << "') does not contain 'copy' or otherwise starts with"
2424 " 'new' or 'alloc'. This violates the naming convention rules given"
Ted Kremenek2a410c92009-04-29 22:25:52 +00002425 " in the Memory Management Guide for Cocoa (object leaked)";
Ted Kremenek47a72422009-04-29 18:50:19 +00002426 }
2427 else
2428 os << " is no longer referenced after this point and has a retain count of"
Ted Kremenek2a410c92009-04-29 22:25:52 +00002429 " +" << RV->getCount() << " (object leaked)";
Ted Kremenek47a72422009-04-29 18:50:19 +00002430
2431 return new PathDiagnosticEventPiece(L, os.str());
2432}
2433
2434
2435CFRefLeakReport::CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2436 ExplodedNode<GRState> *n,
2437 SymbolRef sym, GRExprEngine& Eng)
2438: CFRefReport(D, tf, n, sym)
2439{
2440
2441 // Most bug reports are cached at the location where they occured.
2442 // With leaks, we want to unique them by the location where they were
2443 // allocated, and only report a single path. To do this, we need to find
2444 // the allocation site of a piece of tracked memory, which we do via a
2445 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2446 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2447 // that all ancestor nodes that represent the allocation site have the
2448 // same SourceLocation.
2449 const ExplodedNode<GRState>* AllocNode = 0;
2450
2451 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding.
2452 GetAllocationSite(Eng.getStateManager(), getEndNode(), getSymbol());
2453
2454 // Get the SourceLocation for the allocation site.
2455 ProgramPoint P = AllocNode->getLocation();
2456 AllocSite = cast<PostStmt>(P).getStmt()->getLocStart();
2457
2458 // Fill in the description of the bug.
2459 Description.clear();
2460 llvm::raw_string_ostream os(Description);
2461 SourceManager& SMgr = Eng.getContext().getSourceManager();
2462 unsigned AllocLine = SMgr.getInstantiationLineNumber(AllocSite);
Ted Kremenek2e9d0302009-05-02 19:05:19 +00002463 os << "Potential leak ";
2464 if (tf.isGCEnabled()) {
2465 os << "(when using garbage collection) ";
2466 }
2467 os << "of an object allocated on line " << AllocLine;
Ted Kremenek47a72422009-04-29 18:50:19 +00002468
2469 // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2470 if (AllocBinding)
2471 os << " and stored into '" << AllocBinding->getString() << '\'';
2472}
2473
2474//===----------------------------------------------------------------------===//
2475// Main checker logic.
2476//===----------------------------------------------------------------------===//
2477
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002478static inline ArgEffect GetArgE(RetainSummary* Summ, unsigned idx) {
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00002479 return Summ ? Summ->getArg(idx) : MayEscape;
Ted Kremenek455dd862008-04-11 20:23:24 +00002480}
2481
Ted Kremenek266d8b62008-05-06 02:26:56 +00002482static inline RetEffect GetRetEffect(RetainSummary* Summ) {
2483 return Summ ? Summ->getRetEffect() : RetEffect::MakeNoRet();
Ted Kremenek455dd862008-04-11 20:23:24 +00002484}
2485
Ted Kremenek227c5372008-05-06 02:41:27 +00002486static inline ArgEffect GetReceiverE(RetainSummary* Summ) {
2487 return Summ ? Summ->getReceiverEffect() : DoNothing;
2488}
2489
Ted Kremenekf2717b02008-07-18 17:24:20 +00002490static inline bool IsEndPath(RetainSummary* Summ) {
2491 return Summ ? Summ->isEndPath() : false;
2492}
2493
Ted Kremenek1feab292008-04-16 04:28:53 +00002494
Ted Kremenek272aa852008-06-25 21:21:56 +00002495/// GetReturnType - Used to get the return type of a message expression or
2496/// function call with the intention of affixing that type to a tracked symbol.
2497/// While the the return type can be queried directly from RetEx, when
2498/// invoking class methods we augment to the return type to be that of
2499/// a pointer to the class (as opposed it just being id).
2500static QualType GetReturnType(Expr* RetE, ASTContext& Ctx) {
2501
2502 QualType RetTy = RetE->getType();
2503
2504 // FIXME: We aren't handling id<...>.
Chris Lattnerb724ab22008-07-26 22:36:27 +00002505 const PointerType* PT = RetTy->getAsPointerType();
Ted Kremenek272aa852008-06-25 21:21:56 +00002506 if (!PT)
2507 return RetTy;
2508
2509 // If RetEx is not a message expression just return its type.
2510 // If RetEx is a message expression, return its types if it is something
2511 /// more specific than id.
2512
2513 ObjCMessageExpr* ME = dyn_cast<ObjCMessageExpr>(RetE);
2514
Steve Naroff17c03822009-02-12 17:52:19 +00002515 if (!ME || !Ctx.isObjCIdStructType(PT->getPointeeType()))
Ted Kremenek272aa852008-06-25 21:21:56 +00002516 return RetTy;
2517
2518 ObjCInterfaceDecl* D = ME->getClassInfo().first;
2519
2520 // At this point we know the return type of the message expression is id.
2521 // If we have an ObjCInterceDecl, we know this is a call to a class method
2522 // whose type we can resolve. In such cases, promote the return type to
2523 // Class*.
2524 return !D ? RetTy : Ctx.getPointerType(Ctx.getObjCInterfaceType(D));
2525}
2526
2527
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002528void CFRefCount::EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002529 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002530 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002531 Expr* Ex,
2532 Expr* Receiver,
2533 RetainSummary* Summ,
Zhongxing Xucac107a2009-04-20 05:24:46 +00002534 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002535 ExplodedNode<GRState>* Pred) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002536
Ted Kremeneka7338b42008-03-11 06:39:11 +00002537 // Get the state.
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002538 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenek0106e202008-10-24 20:32:50 +00002539 ASTContext& Ctx = Eng.getStateManager().getContext();
Ted Kremenek227c5372008-05-06 02:41:27 +00002540
2541 // Evaluate the effect of the arguments.
Ted Kremenek1feab292008-04-16 04:28:53 +00002542 RefVal::Kind hasErr = (RefVal::Kind) 0;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002543 unsigned idx = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002544 Expr* ErrorExpr = NULL;
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002545 SymbolRef ErrorSym = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002546
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002547 for (ExprIterator I = arg_beg; I != arg_end; ++I, ++idx) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002548 SVal V = state.GetSValAsScalarOrLoc(*I);
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002549 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002550
Ted Kremenek74556a12009-03-26 03:35:11 +00002551 if (Sym)
Ted Kremenekb6578942009-02-24 19:15:11 +00002552 if (RefBindings::data_type* T = state.get<RefBindings>(Sym)) {
2553 state = Update(state, Sym, *T, GetArgE(Summ, idx), hasErr);
2554 if (hasErr) {
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002555 ErrorExpr = *I;
Ted Kremenek6064a362008-07-07 16:21:19 +00002556 ErrorSym = Sym;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002557 break;
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002558 }
2559 continue;
Ted Kremenekb6578942009-02-24 19:15:11 +00002560 }
Ted Kremenekede40b72008-07-09 18:11:16 +00002561
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002562 if (isa<Loc>(V)) {
2563 if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(&V)) {
Ted Kremenekede40b72008-07-09 18:11:16 +00002564 if (GetArgE(Summ, idx) == DoNothingByRef)
2565 continue;
2566
2567 // Invalidate the value of the variable passed by reference.
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002568
2569 // FIXME: Either this logic should also be replicated in GRSimpleVals
2570 // or should be pulled into a separate "constraint engine."
Ted Kremenekede40b72008-07-09 18:11:16 +00002571
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002572 // FIXME: We can have collisions on the conjured symbol if the
2573 // expression *I also creates conjured symbols. We probably want
2574 // to identify conjured symbols by an expression pair: the enclosing
2575 // expression (the context) and the expression itself. This should
Ted Kremenekede40b72008-07-09 18:11:16 +00002576 // disambiguate conjured symbols.
Ted Kremenekb15eba42008-10-04 05:50:14 +00002577
Ted Kremenek38a4b4b2008-10-17 20:28:54 +00002578 const TypedRegion* R = dyn_cast<TypedRegion>(MR->getRegion());
Zhongxing Xub9d47a42009-04-29 02:30:09 +00002579
Ted Kremenek53b24182009-03-04 22:56:43 +00002580 if (R) {
Ted Kremenek618c6cd2008-12-18 23:34:57 +00002581 // Is the invalidated variable something that we were tracking?
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002582 SymbolRef Sym = state.GetSValAsScalarOrLoc(R).getAsLocSymbol();
Ted Kremenek618c6cd2008-12-18 23:34:57 +00002583
Ted Kremenek53b24182009-03-04 22:56:43 +00002584 // Remove any existing reference-count binding.
Ted Kremenek74556a12009-03-26 03:35:11 +00002585 if (Sym) state = state.remove<RefBindings>(Sym);
Ted Kremenekb15eba42008-10-04 05:50:14 +00002586
Ted Kremenek53b24182009-03-04 22:56:43 +00002587 if (R->isBoundable(Ctx)) {
2588 // Set the value of the variable to be a conjured symbol.
2589 unsigned Count = Builder.getCurrentBlockCount();
2590 QualType T = R->getRValueType(Ctx);
2591
Zhongxing Xu079dc352009-04-09 06:03:54 +00002592 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())){
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002593 ValueManager &ValMgr = Eng.getValueManager();
2594 SVal V = ValMgr.getConjuredSymbolVal(*I, T, Count);
Zhongxing Xu079dc352009-04-09 06:03:54 +00002595 state = state.BindLoc(Loc::MakeVal(R), V);
Ted Kremenek53b24182009-03-04 22:56:43 +00002596 }
2597 else if (const RecordType *RT = T->getAsStructureType()) {
2598 // Handle structs in a not so awesome way. Here we just
2599 // eagerly bind new symbols to the fields. In reality we
2600 // should have the store manager handle this. The idea is just
2601 // to prototype some basic functionality here. All of this logic
2602 // should one day soon just go away.
2603 const RecordDecl *RD = RT->getDecl()->getDefinition(Ctx);
2604
2605 // No record definition. There is nothing we can do.
2606 if (!RD)
2607 continue;
2608
2609 MemRegionManager &MRMgr = state.getManager().getRegionManager();
2610
2611 // Iterate through the fields and construct new symbols.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002612 for (RecordDecl::field_iterator FI=RD->field_begin(Ctx),
2613 FE=RD->field_end(Ctx); FI!=FE; ++FI) {
Ted Kremenek53b24182009-03-04 22:56:43 +00002614
2615 // For now just handle scalar fields.
2616 FieldDecl *FD = *FI;
2617 QualType FT = FD->getType();
2618
2619 if (Loc::IsLocType(FT) ||
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002620 (FT->isIntegerType() && FT->isScalarType())) {
Ted Kremenek53b24182009-03-04 22:56:43 +00002621 const FieldRegion* FR = MRMgr.getFieldRegion(FD, R);
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002622 ValueManager &ValMgr = Eng.getValueManager();
2623 SVal V = ValMgr.getConjuredSymbolVal(*I, FT, Count);
Zhongxing Xuc458e322009-04-09 06:32:20 +00002624 state = state.BindLoc(Loc::MakeVal(FR), V);
Ted Kremenek53b24182009-03-04 22:56:43 +00002625 }
2626 }
2627 }
2628 else {
2629 // Just blast away other values.
2630 state = state.BindLoc(*MR, UnknownVal());
2631 }
Ted Kremenek8f90e712008-10-17 22:23:12 +00002632 }
Ted Kremenekb15eba42008-10-04 05:50:14 +00002633 }
2634 else
Ted Kremenek09102db2008-11-12 19:22:09 +00002635 state = state.BindLoc(*MR, UnknownVal());
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002636 }
2637 else {
2638 // Nuke all other arguments passed by reference.
Zhongxing Xu097fc982008-10-17 05:57:07 +00002639 state = state.Unbind(cast<Loc>(V));
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002640 }
Ted Kremeneke4924202008-04-11 20:51:02 +00002641 }
Zhongxing Xu097fc982008-10-17 05:57:07 +00002642 else if (isa<nonloc::LocAsInteger>(V))
2643 state = state.Unbind(cast<nonloc::LocAsInteger>(V).getLoc());
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002644 }
Ted Kremenek1feab292008-04-16 04:28:53 +00002645
Ted Kremenek272aa852008-06-25 21:21:56 +00002646 // Evaluate the effect on the message receiver.
Ted Kremenek227c5372008-05-06 02:41:27 +00002647 if (!ErrorExpr && Receiver) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002648 SymbolRef Sym = state.GetSValAsScalarOrLoc(Receiver).getAsLocSymbol();
Ted Kremenek74556a12009-03-26 03:35:11 +00002649 if (Sym) {
Ted Kremenekb6578942009-02-24 19:15:11 +00002650 if (const RefVal* T = state.get<RefBindings>(Sym)) {
2651 state = Update(state, Sym, *T, GetReceiverE(Summ), hasErr);
2652 if (hasErr) {
Ted Kremenek227c5372008-05-06 02:41:27 +00002653 ErrorExpr = Receiver;
Ted Kremenek6064a362008-07-07 16:21:19 +00002654 ErrorSym = Sym;
Ted Kremenek227c5372008-05-06 02:41:27 +00002655 }
Ted Kremenekb6578942009-02-24 19:15:11 +00002656 }
Ted Kremenek227c5372008-05-06 02:41:27 +00002657 }
2658 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002659
Ted Kremenek272aa852008-06-25 21:21:56 +00002660 // Process any errors.
Ted Kremenek1feab292008-04-16 04:28:53 +00002661 if (hasErr) {
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002662 ProcessNonLeakError(Dst, Builder, Ex, ErrorExpr, Pred, state,
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002663 hasErr, ErrorSym);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002664 return;
Ted Kremenek0d721572008-03-11 17:48:22 +00002665 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002666
Ted Kremenekf2717b02008-07-18 17:24:20 +00002667 // Consult the summary for the return value.
Ted Kremenek266d8b62008-05-06 02:26:56 +00002668 RetEffect RE = GetRetEffect(Summ);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002669
2670 switch (RE.getKind()) {
2671 default:
2672 assert (false && "Unhandled RetEffect."); break;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002673
Ted Kremenek8f90e712008-10-17 22:23:12 +00002674 case RetEffect::NoRet: {
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002675
Ted Kremenek455dd862008-04-11 20:23:24 +00002676 // Make up a symbol for the return value (not reference counted).
Ted Kremeneke4924202008-04-11 20:51:02 +00002677 // FIXME: This is basically copy-and-paste from GRSimpleVals. We
2678 // should compose behavior, not copy it.
Ted Kremenek455dd862008-04-11 20:23:24 +00002679
Ted Kremenek8f90e712008-10-17 22:23:12 +00002680 // FIXME: We eventually should handle structs and other compound types
2681 // that are returned by value.
2682
2683 QualType T = Ex->getType();
2684
Ted Kremenek79413a52008-11-13 06:10:40 +00002685 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())) {
Ted Kremenek455dd862008-04-11 20:23:24 +00002686 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002687 ValueManager &ValMgr = Eng.getValueManager();
2688 SVal X = ValMgr.getConjuredSymbolVal(Ex, T, Count);
Ted Kremenek09102db2008-11-12 19:22:09 +00002689 state = state.BindExpr(Ex, X, false);
Ted Kremenek455dd862008-04-11 20:23:24 +00002690 }
2691
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002692 break;
Ted Kremenek8f90e712008-10-17 22:23:12 +00002693 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002694
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002695 case RetEffect::Alias: {
Ted Kremenek272aa852008-06-25 21:21:56 +00002696 unsigned idx = RE.getIndex();
Ted Kremenek2719e982008-06-17 02:43:46 +00002697 assert (arg_end >= arg_beg);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002698 assert (idx < (unsigned) (arg_end - arg_beg));
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002699 SVal V = state.GetSValAsScalarOrLoc(*(arg_beg+idx));
Ted Kremenek09102db2008-11-12 19:22:09 +00002700 state = state.BindExpr(Ex, V, false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002701 break;
2702 }
2703
Ted Kremenek227c5372008-05-06 02:41:27 +00002704 case RetEffect::ReceiverAlias: {
2705 assert (Receiver);
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002706 SVal V = state.GetSValAsScalarOrLoc(Receiver);
Ted Kremenek09102db2008-11-12 19:22:09 +00002707 state = state.BindExpr(Ex, V, false);
Ted Kremenek227c5372008-05-06 02:41:27 +00002708 break;
2709 }
2710
Ted Kremenek6a1cc252008-06-23 18:02:52 +00002711 case RetEffect::OwnedAllocatedSymbol:
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002712 case RetEffect::OwnedSymbol: {
2713 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke9e726e2009-04-09 16:13:17 +00002714 ValueManager &ValMgr = Eng.getValueManager();
2715 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
2716 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
2717 state = state.set<RefBindings>(Sym, RefVal::makeOwned(RE.getObjKind(),
2718 RetT));
2719 state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenek45c52a12009-03-09 22:46:49 +00002720
2721 // FIXME: Add a flag to the checker where allocations are assumed to
2722 // *not fail.
2723#if 0
Ted Kremeneke62fd052009-01-28 22:27:59 +00002724 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) {
2725 bool isFeasible;
2726 state = state.Assume(loc::SymbolVal(Sym), true, isFeasible);
2727 assert(isFeasible && "Cannot assume fresh symbol is non-null.");
2728 }
Ted Kremenek45c52a12009-03-09 22:46:49 +00002729#endif
Ted Kremenek6a1cc252008-06-23 18:02:52 +00002730
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002731 break;
2732 }
Ted Kremenek382fb4e2009-04-27 19:14:45 +00002733
2734 case RetEffect::GCNotOwnedSymbol:
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002735 case RetEffect::NotOwnedSymbol: {
2736 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke9e726e2009-04-09 16:13:17 +00002737 ValueManager &ValMgr = Eng.getValueManager();
2738 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
2739 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
2740 state = state.set<RefBindings>(Sym, RefVal::makeNotOwned(RE.getObjKind(),
2741 RetT));
2742 state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002743 break;
2744 }
2745 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002746
Ted Kremenek0dd65012009-02-18 02:00:25 +00002747 // Generate a sink node if we are at the end of a path.
2748 GRExprEngine::NodeTy *NewNode =
2749 IsEndPath(Summ) ? Builder.MakeSinkNode(Dst, Ex, Pred, state)
2750 : Builder.MakeNode(Dst, Ex, Pred, state);
2751
2752 // Annotate the edge with summary we used.
2753 // FIXME: This assumes that we always use the same summary when generating
2754 // this node.
2755 if (NewNode) SummaryLog[NewNode] = Summ;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002756}
2757
2758
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002759void CFRefCount::EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002760 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002761 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu097fc982008-10-17 05:57:07 +00002762 CallExpr* CE, SVal L,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002763 ExplodedNode<GRState>* Pred) {
Zhongxing Xucac107a2009-04-20 05:24:46 +00002764 const FunctionDecl* FD = L.getAsFunctionDecl();
2765 RetainSummary* Summ = !FD ? 0
2766 : Summaries.getSummary(const_cast<FunctionDecl*>(FD));
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002767
2768 EvalSummary(Dst, Eng, Builder, CE, 0, Summ,
2769 CE->arg_begin(), CE->arg_end(), Pred);
Ted Kremenek827f93b2008-03-06 00:08:09 +00002770}
Ted Kremeneka7338b42008-03-11 06:39:11 +00002771
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002772void CFRefCount::EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002773 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002774 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002775 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002776 ExplodedNode<GRState>* Pred) {
Ted Kremenek926abf22008-05-06 04:20:12 +00002777 RetainSummary* Summ;
Ted Kremenek33661802008-05-01 21:31:50 +00002778
Ted Kremenek272aa852008-06-25 21:21:56 +00002779 if (Expr* Receiver = ME->getReceiver()) {
2780 // We need the type-information of the tracked receiver object
2781 // Retrieve it from the state.
2782 ObjCInterfaceDecl* ID = 0;
2783
2784 // FIXME: Wouldn't it be great if this code could be reduced? It's just
2785 // a chain of lookups.
Ted Kremeneka821b792009-04-29 05:04:30 +00002786 // FIXME: Is this really working as expected? There are cases where
2787 // we just use the 'ID' from the message expression.
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002788 const GRState* St = Builder.GetState(Pred);
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002789 SVal V = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
Ted Kremenek272aa852008-06-25 21:21:56 +00002790
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002791 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenek74556a12009-03-26 03:35:11 +00002792 if (Sym) {
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002793 if (const RefVal* T = St->get<RefBindings>(Sym)) {
Ted Kremenek6064a362008-07-07 16:21:19 +00002794 QualType Ty = T->getType();
Ted Kremenek272aa852008-06-25 21:21:56 +00002795
2796 if (const PointerType* PT = Ty->getAsPointerType()) {
2797 QualType PointeeTy = PT->getPointeeType();
2798
2799 if (ObjCInterfaceType* IT = dyn_cast<ObjCInterfaceType>(PointeeTy))
2800 ID = IT->getDecl();
2801 }
2802 }
2803 }
2804
Ted Kremenek04e00302009-04-29 17:09:14 +00002805 // FIXME: The receiver could be a reference to a class, meaning that
2806 // we should use the class method.
2807 Summ = Summaries.getInstanceMethodSummary(ME, ID);
Ted Kremenek0106e202008-10-24 20:32:50 +00002808
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002809 // Special-case: are we sending a mesage to "self"?
2810 // This is a hack. When we have full-IP this should be removed.
2811 if (!Summ) {
2812 ObjCMethodDecl* MD =
2813 dyn_cast<ObjCMethodDecl>(&Eng.getGraph().getCodeDecl());
2814
2815 if (MD) {
2816 if (Expr* Receiver = ME->getReceiver()) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002817 SVal X = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002818 if (loc::MemRegionVal* L = dyn_cast<loc::MemRegionVal>(&X))
Ted Kremenek0106e202008-10-24 20:32:50 +00002819 if (L->getRegion() == Eng.getStateManager().getSelfRegion(St)) {
2820 // Create a summmary where all of the arguments "StopTracking".
2821 Summ = Summaries.getPersistentSummary(RetEffect::MakeNoRet(),
2822 DoNothing,
2823 StopTracking);
2824 }
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002825 }
2826 }
2827 }
Ted Kremenek272aa852008-06-25 21:21:56 +00002828 }
Ted Kremenek1feab292008-04-16 04:28:53 +00002829 else
Ted Kremenekb17fa952009-04-23 21:25:57 +00002830 Summ = Summaries.getClassMethodSummary(ME);
Ted Kremenek1feab292008-04-16 04:28:53 +00002831
Ted Kremenekccbe79a2009-04-24 17:50:11 +00002832
Ted Kremenek926abf22008-05-06 04:20:12 +00002833 EvalSummary(Dst, Eng, Builder, ME, ME->getReceiver(), Summ,
2834 ME->arg_begin(), ME->arg_end(), Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002835}
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002836
2837namespace {
2838class VISIBILITY_HIDDEN StopTrackingCallback : public SymbolVisitor {
2839 GRStateRef state;
2840public:
2841 StopTrackingCallback(GRStateRef st) : state(st) {}
2842 GRStateRef getState() { return state; }
2843
2844 bool VisitSymbol(SymbolRef sym) {
2845 state = state.remove<RefBindings>(sym);
2846 return true;
2847 }
Ted Kremenek926abf22008-05-06 04:20:12 +00002848
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002849 const GRState* getState() const { return state.getState(); }
2850};
2851} // end anonymous namespace
2852
2853
Ted Kremeneka42be302009-02-14 01:43:44 +00002854void CFRefCount::EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val) {
Ted Kremeneka42be302009-02-14 01:43:44 +00002855 // Are we storing to something that causes the value to "escape"?
Ted Kremenek7aef4842008-04-16 20:40:59 +00002856 bool escapes = false;
2857
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002858 // A value escapes in three possible cases (this may change):
2859 //
2860 // (1) we are binding to something that is not a memory region.
2861 // (2) we are binding to a memregion that does not have stack storage
2862 // (3) we are binding to a memregion with stack storage that the store
Ted Kremeneka42be302009-02-14 01:43:44 +00002863 // does not understand.
Ted Kremeneka42be302009-02-14 01:43:44 +00002864 GRStateRef state = B.getState();
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002865
Ted Kremeneka42be302009-02-14 01:43:44 +00002866 if (!isa<loc::MemRegionVal>(location))
Ted Kremenek7aef4842008-04-16 20:40:59 +00002867 escapes = true;
Ted Kremenekb15eba42008-10-04 05:50:14 +00002868 else {
Ted Kremeneka42be302009-02-14 01:43:44 +00002869 const MemRegion* R = cast<loc::MemRegionVal>(location).getRegion();
2870 escapes = !B.getStateManager().hasStackStorage(R);
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002871
2872 if (!escapes) {
2873 // To test (3), generate a new state with the binding removed. If it is
2874 // the same state, then it escapes (since the store cannot represent
2875 // the binding).
Ted Kremeneka42be302009-02-14 01:43:44 +00002876 escapes = (state == (state.BindLoc(cast<Loc>(location), UnknownVal())));
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002877 }
Ted Kremenekb15eba42008-10-04 05:50:14 +00002878 }
Ted Kremeneka42be302009-02-14 01:43:44 +00002879
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002880 // If our store can represent the binding and we aren't storing to something
2881 // that doesn't have local storage then just return and have the simulation
2882 // state continue as is.
2883 if (!escapes)
2884 return;
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002885
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002886 // Otherwise, find all symbols referenced by 'val' that we are tracking
2887 // and stop tracking them.
2888 B.MakeNode(state.scanReachableSymbols<StopTrackingCallback>(val).getState());
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002889}
2890
Ted Kremenek0106e202008-10-24 20:32:50 +00002891std::pair<GRStateRef,bool>
2892CFRefCount::HandleSymbolDeath(GRStateManager& VMgr,
2893 const GRState* St, const Decl* CD,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002894 SymbolRef sid,
Ted Kremenek0106e202008-10-24 20:32:50 +00002895 RefVal V, bool& hasLeak) {
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002896
Ted Kremenek47a72422009-04-29 18:50:19 +00002897 // Any remaining leaks?
Ted Kremenek311f3d42008-10-22 23:56:21 +00002898 hasLeak = V.isOwned() ||
2899 ((V.isNotOwned() || V.isReturnedOwned()) && V.getCount() > 0);
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002900
Ted Kremenek47a72422009-04-29 18:50:19 +00002901 GRStateRef state(St, VMgr);
2902
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002903 if (!hasLeak)
Ted Kremenek0106e202008-10-24 20:32:50 +00002904 return std::make_pair(state.remove<RefBindings>(sid), false);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002905
Ted Kremenek0106e202008-10-24 20:32:50 +00002906 return std::make_pair(state.set<RefBindings>(sid, V ^ RefVal::ErrorLeak),
2907 false);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002908}
2909
Ted Kremenek541db372008-04-24 23:57:27 +00002910
Ted Kremenekffefc352008-04-11 22:25:11 +00002911
Ted Kremenek541db372008-04-24 23:57:27 +00002912// Dead symbols.
2913
Ted Kremenek708af042009-02-05 06:50:21 +00002914
Ted Kremenek541db372008-04-24 23:57:27 +00002915
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002916 // Return statements.
2917
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002918void CFRefCount::EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002919 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002920 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002921 ReturnStmt* S,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002922 ExplodedNode<GRState>* Pred) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002923
2924 Expr* RetE = S->getRetValue();
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002925 if (!RetE)
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002926 return;
2927
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002928 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002929 SymbolRef Sym = state.GetSValAsScalarOrLoc(RetE).getAsLocSymbol();
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002930
Ted Kremenek74556a12009-03-26 03:35:11 +00002931 if (!Sym)
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002932 return;
2933
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002934 // Get the reference count binding (if any).
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002935 const RefVal* T = state.get<RefBindings>(Sym);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002936
2937 if (!T)
2938 return;
2939
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002940 // Change the reference count.
Ted Kremenek6064a362008-07-07 16:21:19 +00002941 RefVal X = *T;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002942
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002943 switch (X.getKind()) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002944 case RefVal::Owned: {
2945 unsigned cnt = X.getCount();
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00002946 assert (cnt > 0);
2947 X = RefVal::makeReturnedOwned(cnt - 1);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002948 break;
2949 }
2950
2951 case RefVal::NotOwned: {
2952 unsigned cnt = X.getCount();
2953 X = cnt ? RefVal::makeReturnedOwned(cnt - 1)
2954 : RefVal::makeReturnedNotOwned();
2955 break;
2956 }
2957
2958 default:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002959 return;
2960 }
2961
2962 // Update the binding.
Ted Kremenek91781202008-08-17 03:20:02 +00002963 state = state.set<RefBindings>(Sym, X);
Ted Kremenek47a72422009-04-29 18:50:19 +00002964 Pred = Builder.MakeNode(Dst, S, Pred, state);
2965
Ted Kremeneka208d0c2009-04-30 05:51:50 +00002966 // Did we cache out?
2967 if (!Pred)
2968 return;
2969
Ted Kremenek47a72422009-04-29 18:50:19 +00002970 // Any leaks or other errors?
2971 if (X.isReturnedOwned() && X.getCount() == 0) {
2972 const Decl *CD = &Eng.getStateManager().getCodeDecl();
2973
Ted Kremenek314b1952009-04-29 23:03:22 +00002974 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
2975 RetainSummary *Summ = Summaries.getMethodSummary(MD);
2976 if (!GetRetEffect(Summ).isOwned()) {
Ted Kremenek47a72422009-04-29 18:50:19 +00002977 static int ReturnOwnLeakTag = 0;
2978 state = state.set<RefBindings>(Sym, X ^ RefVal::ErrorLeakReturned);
Ted Kremenek47a72422009-04-29 18:50:19 +00002979 // Generate an error node.
Ted Kremeneka208d0c2009-04-30 05:51:50 +00002980 if (ExplodedNode<GRState> *N =
2981 Builder.generateNode(PostStmt(S, &ReturnOwnLeakTag), state, Pred)) {
2982 CFRefLeakReport *report =
2983 new CFRefLeakReport(*static_cast<CFRefBug*>(leakAtReturn), *this,
2984 N, Sym, Eng);
2985 BR->EmitReport(report);
2986 }
Ted Kremenek47a72422009-04-29 18:50:19 +00002987 }
2988 }
2989 }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002990}
2991
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002992// Assumptions.
2993
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002994const GRState* CFRefCount::EvalAssume(GRStateManager& VMgr,
2995 const GRState* St,
Zhongxing Xu097fc982008-10-17 05:57:07 +00002996 SVal Cond, bool Assumption,
Ted Kremenekf22f8682008-07-10 22:03:41 +00002997 bool& isFeasible) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002998
2999 // FIXME: We may add to the interface of EvalAssume the list of symbols
3000 // whose assumptions have changed. For now we just iterate through the
3001 // bindings and check if any of the tracked symbols are NULL. This isn't
3002 // too bad since the number of symbols we will track in practice are
3003 // probably small and EvalAssume is only called at branches and a few
3004 // other places.
Ted Kremenek4ae925c2008-08-14 21:16:54 +00003005 RefBindings B = St->get<RefBindings>();
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003006
3007 if (B.isEmpty())
3008 return St;
3009
3010 bool changed = false;
Ted Kremenek91781202008-08-17 03:20:02 +00003011
3012 GRStateRef state(St, VMgr);
3013 RefBindings::Factory& RefBFactory = state.get_context<RefBindings>();
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003014
3015 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003016 // Check if the symbol is null (or equal to any constant).
3017 // If this is the case, stop tracking the symbol.
Zhongxing Xuc6b27d02008-08-29 14:52:36 +00003018 if (VMgr.getSymVal(St, I.getKey())) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003019 changed = true;
3020 B = RefBFactory.Remove(B, I.getKey());
3021 }
3022 }
3023
Ted Kremenek91781202008-08-17 03:20:02 +00003024 if (changed)
3025 state = state.set<RefBindings>(B);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003026
Ted Kremenek4ae925c2008-08-14 21:16:54 +00003027 return state;
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003028}
Ted Kremeneka7338b42008-03-11 06:39:11 +00003029
Ted Kremenekb6578942009-02-24 19:15:11 +00003030GRStateRef CFRefCount::Update(GRStateRef state, SymbolRef sym,
3031 RefVal V, ArgEffect E,
3032 RefVal::Kind& hasErr) {
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003033
3034 // In GC mode [... release] and [... retain] do nothing.
3035 switch (E) {
3036 default: break;
3037 case IncRefMsg: E = isGCEnabled() ? DoNothing : IncRef; break;
3038 case DecRefMsg: E = isGCEnabled() ? DoNothing : DecRef; break;
Ted Kremenek2126bef2009-02-18 21:57:45 +00003039 case MakeCollectable: E = isGCEnabled() ? DecRef : DoNothing; break;
Ted Kremenekaac82832009-02-23 17:45:03 +00003040 case NewAutoreleasePool: E = isGCEnabled() ? DoNothing :
3041 NewAutoreleasePool; break;
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003042 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00003043
Ted Kremenek6537a642009-03-17 19:42:23 +00003044 // Handle all use-after-releases.
3045 if (!isGCEnabled() && V.getKind() == RefVal::Released) {
3046 V = V ^ RefVal::ErrorUseAfterRelease;
3047 hasErr = V.getKind();
3048 return state.set<RefBindings>(sym, V);
3049 }
3050
Ted Kremenek0d721572008-03-11 17:48:22 +00003051 switch (E) {
3052 default:
3053 assert (false && "Unhandled CFRef transition.");
Ted Kremenek6537a642009-03-17 19:42:23 +00003054
3055 case Dealloc:
3056 // Any use of -dealloc in GC is *bad*.
3057 if (isGCEnabled()) {
3058 V = V ^ RefVal::ErrorDeallocGC;
3059 hasErr = V.getKind();
3060 break;
3061 }
3062
3063 switch (V.getKind()) {
3064 default:
3065 assert(false && "Invalid case.");
3066 case RefVal::Owned:
3067 // The object immediately transitions to the released state.
3068 V = V ^ RefVal::Released;
3069 V.clearCounts();
3070 return state.set<RefBindings>(sym, V);
3071 case RefVal::NotOwned:
3072 V = V ^ RefVal::ErrorDeallocNotOwned;
3073 hasErr = V.getKind();
3074 break;
3075 }
3076 break;
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003077
Ted Kremenekb7826ab2009-02-25 23:11:49 +00003078 case NewAutoreleasePool:
3079 assert(!isGCEnabled());
3080 return state.add<AutoreleaseStack>(sym);
3081
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003082 case MayEscape:
3083 if (V.getKind() == RefVal::Owned) {
Ted Kremenek272aa852008-06-25 21:21:56 +00003084 V = V ^ RefVal::NotOwned;
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003085 break;
3086 }
Ted Kremenek6537a642009-03-17 19:42:23 +00003087
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003088 // Fall-through.
Ted Kremenek1b4b6562009-02-25 02:54:57 +00003089
Ted Kremenekede40b72008-07-09 18:11:16 +00003090 case DoNothingByRef:
Ted Kremenek0d721572008-03-11 17:48:22 +00003091 case DoNothing:
Ted Kremenekb6578942009-02-24 19:15:11 +00003092 return state;
Ted Kremeneke5a4bb02008-06-30 16:57:41 +00003093
Ted Kremenek9b112d22009-01-28 21:44:40 +00003094 case Autorelease:
Ted Kremenek6537a642009-03-17 19:42:23 +00003095 if (isGCEnabled())
3096 return state;
Ted Kremenek681fb352009-03-20 17:34:15 +00003097
3098 // Update the autorelease counts.
3099 state = SendAutorelease(state, ARCountFactory, sym);
Ted Kremenek6537a642009-03-17 19:42:23 +00003100
3101 // Fall-through.
3102
Ted Kremenek227c5372008-05-06 02:41:27 +00003103 case StopTracking:
Ted Kremenekb6578942009-02-24 19:15:11 +00003104 return state.remove<RefBindings>(sym);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003105
Ted Kremenek0d721572008-03-11 17:48:22 +00003106 case IncRef:
3107 switch (V.getKind()) {
3108 default:
3109 assert(false);
3110
3111 case RefVal::Owned:
Ted Kremenek0d721572008-03-11 17:48:22 +00003112 case RefVal::NotOwned:
Ted Kremenek272aa852008-06-25 21:21:56 +00003113 V = V + 1;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003114 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003115 case RefVal::Released:
Ted Kremenek6537a642009-03-17 19:42:23 +00003116 // Non-GC cases are handled above.
3117 assert(isGCEnabled());
3118 V = (V ^ RefVal::Owned) + 1;
Ted Kremenek0d721572008-03-11 17:48:22 +00003119 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003120 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00003121 break;
3122
Ted Kremenek272aa852008-06-25 21:21:56 +00003123 case SelfOwn:
3124 V = V ^ RefVal::NotOwned;
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003125 // Fall-through.
Ted Kremenek0d721572008-03-11 17:48:22 +00003126 case DecRef:
3127 switch (V.getKind()) {
3128 default:
Ted Kremenek6537a642009-03-17 19:42:23 +00003129 // case 'RefVal::Released' handled above.
Ted Kremenek0d721572008-03-11 17:48:22 +00003130 assert (false);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003131
Ted Kremenek272aa852008-06-25 21:21:56 +00003132 case RefVal::Owned:
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00003133 assert(V.getCount() > 0);
3134 if (V.getCount() == 1) V = V ^ RefVal::Released;
3135 V = V - 1;
Ted Kremenek0d721572008-03-11 17:48:22 +00003136 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003137
Ted Kremenek272aa852008-06-25 21:21:56 +00003138 case RefVal::NotOwned:
3139 if (V.getCount() > 0)
3140 V = V - 1;
Ted Kremenekc4f81022008-04-10 23:09:18 +00003141 else {
Ted Kremenek272aa852008-06-25 21:21:56 +00003142 V = V ^ RefVal::ErrorReleaseNotOwned;
Ted Kremenek1feab292008-04-16 04:28:53 +00003143 hasErr = V.getKind();
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003144 }
Ted Kremenek0d721572008-03-11 17:48:22 +00003145 break;
Ted Kremenek6537a642009-03-17 19:42:23 +00003146
Ted Kremenek0d721572008-03-11 17:48:22 +00003147 case RefVal::Released:
Ted Kremenek6537a642009-03-17 19:42:23 +00003148 // Non-GC cases are handled above.
3149 assert(isGCEnabled());
Ted Kremenek272aa852008-06-25 21:21:56 +00003150 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek1feab292008-04-16 04:28:53 +00003151 hasErr = V.getKind();
Ted Kremenek6537a642009-03-17 19:42:23 +00003152 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003153 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00003154 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003155 }
Ted Kremenekb6578942009-02-24 19:15:11 +00003156 return state.set<RefBindings>(sym, V);
Ted Kremeneka7338b42008-03-11 06:39:11 +00003157}
3158
Ted Kremenek10fe66d2008-04-09 01:10:13 +00003159//===----------------------------------------------------------------------===//
Ted Kremenek708af042009-02-05 06:50:21 +00003160// Handle dead symbols and end-of-path.
3161//===----------------------------------------------------------------------===//
3162
3163void CFRefCount::EvalEndPath(GRExprEngine& Eng,
3164 GREndPathNodeBuilder<GRState>& Builder) {
3165
3166 const GRState* St = Builder.getState();
3167 RefBindings B = St->get<RefBindings>();
3168
3169 llvm::SmallVector<std::pair<SymbolRef, bool>, 10> Leaked;
3170 const Decl* CodeDecl = &Eng.getGraph().getCodeDecl();
3171
3172 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
3173 bool hasLeak = false;
3174
3175 std::pair<GRStateRef, bool> X =
Ted Kremenek9577c1e2009-03-03 22:06:47 +00003176 HandleSymbolDeath(Eng.getStateManager(), St, CodeDecl,
3177 (*I).first, (*I).second, hasLeak);
Ted Kremenek708af042009-02-05 06:50:21 +00003178
3179 St = X.first;
3180 if (hasLeak) Leaked.push_back(std::make_pair((*I).first, X.second));
3181 }
3182
3183 if (Leaked.empty())
3184 return;
3185
3186 ExplodedNode<GRState>* N = Builder.MakeNode(St);
3187
3188 if (!N)
3189 return;
3190
3191 for (llvm::SmallVector<std::pair<SymbolRef,bool>, 10>::iterator
3192 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3193
3194 CFRefBug *BT = static_cast<CFRefBug*>(I->second ? leakAtReturn
3195 : leakWithinFunction);
3196 assert(BT && "BugType not initialized.");
Ted Kremenekc034f712009-04-07 05:07:44 +00003197 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N, I->first, Eng);
Ted Kremenek708af042009-02-05 06:50:21 +00003198 BR->EmitReport(report);
3199 }
3200}
3201
3202void CFRefCount::EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
3203 GRExprEngine& Eng,
3204 GRStmtNodeBuilder<GRState>& Builder,
3205 ExplodedNode<GRState>* Pred,
3206 Stmt* S,
3207 const GRState* St,
3208 SymbolReaper& SymReaper) {
3209
Ted Kremenek876d8df2009-02-19 23:47:02 +00003210 // FIXME: a lot of copy-and-paste from EvalEndPath. Refactor.
Ted Kremenek708af042009-02-05 06:50:21 +00003211 RefBindings B = St->get<RefBindings>();
3212 llvm::SmallVector<std::pair<SymbolRef,bool>, 10> Leaked;
3213
3214 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3215 E = SymReaper.dead_end(); I != E; ++I) {
3216
3217 const RefVal* T = B.lookup(*I);
3218 if (!T) continue;
3219
3220 bool hasLeak = false;
3221
3222 std::pair<GRStateRef, bool> X
Ted Kremenek876d8df2009-02-19 23:47:02 +00003223 = HandleSymbolDeath(Eng.getStateManager(), St, 0, *I, *T, hasLeak);
Ted Kremenek708af042009-02-05 06:50:21 +00003224
3225 St = X.first;
3226
3227 if (hasLeak)
3228 Leaked.push_back(std::make_pair(*I,X.second));
3229 }
3230
Ted Kremenek876d8df2009-02-19 23:47:02 +00003231 if (!Leaked.empty()) {
3232 // Create a new intermediate node representing the leak point. We
3233 // use a special program point that represents this checker-specific
3234 // transition. We use the address of RefBIndex as a unique tag for this
3235 // checker. We will create another node (if we don't cache out) that
3236 // removes the retain-count bindings from the state.
3237 // NOTE: We use 'generateNode' so that it does interplay with the
3238 // auto-transition logic.
3239 ExplodedNode<GRState>* N =
3240 Builder.generateNode(PostStmtCustom(S, &LeakProgramPointTag), St, Pred);
Ted Kremenek708af042009-02-05 06:50:21 +00003241
Ted Kremenek876d8df2009-02-19 23:47:02 +00003242 if (!N)
3243 return;
3244
3245 // Generate the bug reports.
3246 for (llvm::SmallVectorImpl<std::pair<SymbolRef,bool> >::iterator
3247 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3248
3249 CFRefBug *BT = static_cast<CFRefBug*>(I->second ? leakAtReturn
3250 : leakWithinFunction);
3251 assert(BT && "BugType not initialized.");
Ted Kremenek56c70aa2009-02-23 16:54:00 +00003252 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N,
3253 I->first, Eng);
Ted Kremenek876d8df2009-02-19 23:47:02 +00003254 BR->EmitReport(report);
3255 }
Ted Kremenek708af042009-02-05 06:50:21 +00003256
Ted Kremenek876d8df2009-02-19 23:47:02 +00003257 Pred = N;
Ted Kremenek708af042009-02-05 06:50:21 +00003258 }
Ted Kremenek876d8df2009-02-19 23:47:02 +00003259
3260 // Now generate a new node that nukes the old bindings.
3261 GRStateRef state(St, Eng.getStateManager());
3262 RefBindings::Factory& F = state.get_context<RefBindings>();
3263
3264 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3265 E = SymReaper.dead_end(); I!=E; ++I)
3266 B = F.Remove(B, *I);
3267
3268 state = state.set<RefBindings>(B);
3269 Builder.MakeNode(Dst, S, Pred, state);
Ted Kremenek708af042009-02-05 06:50:21 +00003270}
3271
3272void CFRefCount::ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
3273 GRStmtNodeBuilder<GRState>& Builder,
3274 Expr* NodeExpr, Expr* ErrorExpr,
3275 ExplodedNode<GRState>* Pred,
3276 const GRState* St,
3277 RefVal::Kind hasErr, SymbolRef Sym) {
3278 Builder.BuildSinks = true;
3279 GRExprEngine::NodeTy* N = Builder.MakeNode(Dst, NodeExpr, Pred, St);
3280
3281 if (!N) return;
3282
3283 CFRefBug *BT = 0;
3284
Ted Kremenek6537a642009-03-17 19:42:23 +00003285 switch (hasErr) {
3286 default:
3287 assert(false && "Unhandled error.");
3288 return;
3289 case RefVal::ErrorUseAfterRelease:
3290 BT = static_cast<CFRefBug*>(useAfterRelease);
3291 break;
3292 case RefVal::ErrorReleaseNotOwned:
3293 BT = static_cast<CFRefBug*>(releaseNotOwned);
3294 break;
3295 case RefVal::ErrorDeallocGC:
3296 BT = static_cast<CFRefBug*>(deallocGC);
3297 break;
3298 case RefVal::ErrorDeallocNotOwned:
3299 BT = static_cast<CFRefBug*>(deallocNotOwned);
3300 break;
Ted Kremenek708af042009-02-05 06:50:21 +00003301 }
3302
Ted Kremenekc26c4692009-02-18 03:48:14 +00003303 CFRefReport *report = new CFRefReport(*BT, *this, N, Sym);
Ted Kremenek708af042009-02-05 06:50:21 +00003304 report->addRange(ErrorExpr->getSourceRange());
3305 BR->EmitReport(report);
3306}
3307
3308//===----------------------------------------------------------------------===//
Ted Kremenekb1983ba2008-04-10 22:16:52 +00003309// Transfer function creation for external clients.
Ted Kremeneka7338b42008-03-11 06:39:11 +00003310//===----------------------------------------------------------------------===//
3311
Ted Kremenekfe30beb2008-04-30 23:47:44 +00003312GRTransferFuncs* clang::MakeCFRefCountTF(ASTContext& Ctx, bool GCEnabled,
3313 const LangOptions& lopts) {
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00003314 return new CFRefCount(Ctx, GCEnabled, lopts);
Ted Kremeneka4c74292008-04-10 22:58:08 +00003315}