blob: b9c9bb5923dd254967c62d00abd966dc31504612 [file] [log] [blame]
Chris Lattnerbe1a7a02008-03-15 23:59:48 +00001// CFRefCount.cpp - Transfer functions for tracking simple values -*- C++ -*--//
Ted Kremenek827f93b2008-03-06 00:08:09 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Gabor Greif2224fcb2008-03-06 10:40:09 +000010// This file defines the methods for CFRefCount, which implements
Ted Kremenek827f93b2008-03-06 00:08:09 +000011// a reference count checker for Core Foundation (Mac OS X).
12//
13//===----------------------------------------------------------------------===//
14
Ted Kremeneka7338b42008-03-11 06:39:11 +000015#include "GRSimpleVals.h"
Ted Kremenekfe30beb2008-04-30 23:47:44 +000016#include "clang/Basic/LangOptions.h"
Ted Kremenekfe4d2312008-05-01 23:13:35 +000017#include "clang/Basic/SourceManager.h"
Ted Kremeneka42be302009-02-14 01:43:44 +000018#include "clang/Analysis/PathSensitive/GRExprEngineBuilders.h"
Ted Kremenek91781202008-08-17 03:20:02 +000019#include "clang/Analysis/PathSensitive/GRStateTrait.h"
Ted Kremenekdd0126b2008-03-31 18:26:32 +000020#include "clang/Analysis/PathDiagnostic.h"
Ted Kremenek827f93b2008-03-06 00:08:09 +000021#include "clang/Analysis/LocalCheckers.h"
Ted Kremenek10fe66d2008-04-09 01:10:13 +000022#include "clang/Analysis/PathDiagnostic.h"
23#include "clang/Analysis/PathSensitive/BugReporter.h"
Ted Kremenek2ddb4b22009-02-14 03:16:10 +000024#include "clang/Analysis/PathSensitive/SymbolManager.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000025#include "clang/AST/DeclObjC.h"
Ted Kremeneka7338b42008-03-11 06:39:11 +000026#include "llvm/ADT/DenseMap.h"
27#include "llvm/ADT/FoldingSet.h"
28#include "llvm/ADT/ImmutableMap.h"
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +000029#include "llvm/ADT/ImmutableList.h"
Ted Kremenek2ac4ba62008-05-07 18:36:45 +000030#include "llvm/ADT/StringExtras.h"
Ted Kremenek10fe66d2008-04-09 01:10:13 +000031#include "llvm/Support/Compiler.h"
Ted Kremenekd7e26782008-05-16 18:33:44 +000032#include "llvm/ADT/STLExtras.h"
Ted Kremenek3b11f7a2008-03-11 19:44:10 +000033#include <ostream>
Ted Kremenek9449ca92008-08-12 20:41:56 +000034#include <stdarg.h>
Ted Kremenek827f93b2008-03-06 00:08:09 +000035
36using namespace clang;
Ted Kremenekb6f09542008-10-24 21:18:08 +000037
38//===----------------------------------------------------------------------===//
39// Utility functions.
40//===----------------------------------------------------------------------===//
41
Ted Kremenekb6f09542008-10-24 21:18:08 +000042// The "fundamental rule" for naming conventions of methods:
43// (url broken into two lines)
44// http://developer.apple.com/documentation/Cocoa/Conceptual/
45// MemoryMgmt/Tasks/MemoryManagementRules.html
46//
47// "You take ownership of an object if you create it using a method whose name
48// begins with “alloc” or “new” or contains “copy” (for example, alloc,
49// newObject, or mutableCopy), or if you send it a retain message. You are
50// responsible for relinquishing ownership of objects you own using release
51// or autorelease. Any other time you receive an object, you must
52// not release it."
53//
Ted Kremenek4395b452009-02-21 05:13:43 +000054
55using llvm::CStrInCStrNoCase;
Ted Kremenekfd42ffc2009-02-21 18:26:02 +000056using llvm::StringsEqualNoCase;
Ted Kremenek4395b452009-02-21 05:13:43 +000057
58enum NamingConvention { NoConvention, CreateRule, InitRule };
59
60static inline bool isWordEnd(char ch, char prev, char next) {
61 return ch == '\0'
62 || (islower(prev) && isupper(ch)) // xxxC
63 || (isupper(prev) && isupper(ch) && islower(next)) // XXCreate
64 || !isalpha(ch);
65}
66
67static inline const char* parseWord(const char* s) {
68 char ch = *s, prev = '\0';
69 assert(ch != '\0');
70 char next = *(s+1);
71 while (!isWordEnd(ch, prev, next)) {
72 prev = ch;
73 ch = next;
74 next = *((++s)+1);
75 }
76 return s;
77}
78
79static NamingConvention deriveNamingConvention(const char* s) {
80 // A method/function name may contain a prefix. We don't know it is there,
81 // however, until we encounter the first '_'.
82 bool InPossiblePrefix = true;
83 bool AtBeginning = true;
84 NamingConvention C = NoConvention;
85
86 while (*s != '\0') {
87 // Skip '_'.
88 if (*s == '_') {
89 if (InPossiblePrefix) {
90 InPossiblePrefix = false;
91 AtBeginning = true;
92 // Discard whatever 'convention' we
93 // had already derived since it occurs
94 // in the prefix.
95 C = NoConvention;
96 }
97 ++s;
98 continue;
99 }
100
101 // Skip numbers, ':', etc.
102 if (!isalpha(*s)) {
103 ++s;
104 continue;
105 }
106
107 const char *wordEnd = parseWord(s);
108 assert(wordEnd > s);
109 unsigned len = wordEnd - s;
110
111 switch (len) {
112 default:
113 break;
114 case 3:
115 // Methods starting with 'new' follow the create rule.
Ted Kremenekfd42ffc2009-02-21 18:26:02 +0000116 if (AtBeginning && StringsEqualNoCase("new", s, len))
Ted Kremenek4395b452009-02-21 05:13:43 +0000117 C = CreateRule;
118 break;
119 case 4:
120 // Methods starting with 'alloc' or contain 'copy' follow the
121 // create rule
Ted Kremenek91b79532009-03-13 20:27:06 +0000122 if (C == NoConvention && StringsEqualNoCase("copy", s, len))
Ted Kremenek4395b452009-02-21 05:13:43 +0000123 C = CreateRule;
124 else // Methods starting with 'init' follow the init rule.
Ted Kremenekfd42ffc2009-02-21 18:26:02 +0000125 if (AtBeginning && StringsEqualNoCase("init", s, len))
Ted Kremenek91b79532009-03-13 20:27:06 +0000126 C = InitRule;
127 break;
128 case 5:
129 if (AtBeginning && StringsEqualNoCase("alloc", s, len))
130 C = CreateRule;
Ted Kremenek4395b452009-02-21 05:13:43 +0000131 break;
132 }
133
134 // If we aren't in the prefix and have a derived convention then just
135 // return it now.
136 if (!InPossiblePrefix && C != NoConvention)
137 return C;
138
139 AtBeginning = false;
140 s = wordEnd;
141 }
142
143 // We will get here if there wasn't more than one word
144 // after the prefix.
145 return C;
146}
147
Ted Kremenekb6f09542008-10-24 21:18:08 +0000148static bool followsFundamentalRule(const char* s) {
Ted Kremenek4395b452009-02-21 05:13:43 +0000149 return deriveNamingConvention(s) == CreateRule;
Ted Kremenekcdd3bb22008-11-05 16:54:44 +0000150}
151
Ted Kremenek314b1952009-04-29 23:03:22 +0000152static const ObjCMethodDecl*
153ResolveToInterfaceMethodDecl(const ObjCMethodDecl *MD, ASTContext &Context) {
154 ObjCInterfaceDecl *ID =
155 const_cast<ObjCInterfaceDecl*>(MD->getClassInterface());
156
157 return MD->isInstanceMethod()
158 ? ID->lookupInstanceMethod(Context, MD->getSelector())
159 : ID->lookupClassMethod(Context, MD->getSelector());
Ted Kremenekcdd3bb22008-11-05 16:54:44 +0000160}
Ted Kremenekb6f09542008-10-24 21:18:08 +0000161
Ted Kremenek7d421f32008-04-09 23:49:11 +0000162//===----------------------------------------------------------------------===//
Ted Kremenek272aa852008-06-25 21:21:56 +0000163// Selector creation functions.
Ted Kremenekd9ccf682008-04-17 18:12:53 +0000164//===----------------------------------------------------------------------===//
165
Ted Kremenek1bd6ddb2008-05-01 18:31:44 +0000166static inline Selector GetNullarySelector(const char* name, ASTContext& Ctx) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +0000167 IdentifierInfo* II = &Ctx.Idents.get(name);
168 return Ctx.Selectors.getSelector(0, &II);
169}
170
Ted Kremenek0e344d42008-05-06 00:30:21 +0000171static inline Selector GetUnarySelector(const char* name, ASTContext& Ctx) {
172 IdentifierInfo* II = &Ctx.Idents.get(name);
173 return Ctx.Selectors.getSelector(1, &II);
174}
175
Ted Kremenek272aa852008-06-25 21:21:56 +0000176//===----------------------------------------------------------------------===//
177// Type querying functions.
178//===----------------------------------------------------------------------===//
179
Ted Kremenek17144e82009-01-12 21:45:02 +0000180static bool hasPrefix(const char* s, const char* prefix) {
181 if (!prefix)
182 return true;
Ted Kremenek62820d82008-05-07 20:06:41 +0000183
Ted Kremenek17144e82009-01-12 21:45:02 +0000184 char c = *s;
185 char cP = *prefix;
Ted Kremenek62820d82008-05-07 20:06:41 +0000186
Ted Kremenek17144e82009-01-12 21:45:02 +0000187 while (c != '\0' && cP != '\0') {
188 if (c != cP) break;
189 c = *(++s);
190 cP = *(++prefix);
191 }
Ted Kremenek62820d82008-05-07 20:06:41 +0000192
Ted Kremenek17144e82009-01-12 21:45:02 +0000193 return cP == '\0';
Ted Kremenek62820d82008-05-07 20:06:41 +0000194}
195
Ted Kremenek17144e82009-01-12 21:45:02 +0000196static bool hasSuffix(const char* s, const char* suffix) {
197 const char* loc = strstr(s, suffix);
198 return loc && strcmp(suffix, loc) == 0;
199}
200
201static bool isRefType(QualType RetTy, const char* prefix,
202 ASTContext* Ctx = 0, const char* name = 0) {
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000203
Ted Kremenek17144e82009-01-12 21:45:02 +0000204 if (TypedefType* TD = dyn_cast<TypedefType>(RetTy.getTypePtr())) {
205 const char* TDName = TD->getDecl()->getIdentifier()->getName();
206 return hasPrefix(TDName, prefix) && hasSuffix(TDName, "Ref");
207 }
208
209 if (!Ctx || !name)
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000210 return false;
Ted Kremenek17144e82009-01-12 21:45:02 +0000211
212 // Is the type void*?
213 const PointerType* PT = RetTy->getAsPointerType();
214 if (!(PT->getPointeeType().getUnqualifiedType() == Ctx->VoidTy))
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000215 return false;
Ted Kremenek17144e82009-01-12 21:45:02 +0000216
217 // Does the name start with the prefix?
218 return hasPrefix(name, prefix);
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000219}
220
Ted Kremenekd9ccf682008-04-17 18:12:53 +0000221//===----------------------------------------------------------------------===//
Ted Kremenek272aa852008-06-25 21:21:56 +0000222// Primitives used for constructing summaries for function/method calls.
Ted Kremenek7d421f32008-04-09 23:49:11 +0000223//===----------------------------------------------------------------------===//
224
Ted Kremenek272aa852008-06-25 21:21:56 +0000225/// ArgEffect is used to summarize a function/method call's effect on a
226/// particular argument.
Ted Kremenek6537a642009-03-17 19:42:23 +0000227enum ArgEffect { Autorelease, Dealloc, DecRef, DecRefMsg, DoNothing,
228 DoNothingByRef, IncRefMsg, IncRef, MakeCollectable, MayEscape,
229 NewAutoreleasePool, SelfOwn, StopTracking };
Ted Kremenek272aa852008-06-25 21:21:56 +0000230
Ted Kremeneka7338b42008-03-11 06:39:11 +0000231namespace llvm {
Ted Kremeneka56ae162009-05-03 05:20:50 +0000232template <> struct FoldingSetTrait<ArgEffect> {
233static inline void Profile(const ArgEffect X, FoldingSetNodeID& ID) {
234 ID.AddInteger((unsigned) X);
235}
Ted Kremenek272aa852008-06-25 21:21:56 +0000236};
Ted Kremeneka7338b42008-03-11 06:39:11 +0000237} // end llvm namespace
238
Ted Kremeneka56ae162009-05-03 05:20:50 +0000239/// ArgEffects summarizes the effects of a function/method call on all of
240/// its arguments.
241typedef llvm::ImmutableMap<unsigned,ArgEffect> ArgEffects;
242
Ted Kremeneka7338b42008-03-11 06:39:11 +0000243namespace {
Ted Kremenek272aa852008-06-25 21:21:56 +0000244
245/// RetEffect is used to summarize a function/method call's behavior with
246/// respect to its return value.
247class VISIBILITY_HIDDEN RetEffect {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000248public:
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000249 enum Kind { NoRet, Alias, OwnedSymbol, OwnedAllocatedSymbol,
Ted Kremenek382fb4e2009-04-27 19:14:45 +0000250 NotOwnedSymbol, GCNotOwnedSymbol, ReceiverAlias };
Ted Kremenek68621b92009-01-28 05:56:51 +0000251
252 enum ObjKind { CF, ObjC, AnyObj };
253
Ted Kremeneka7338b42008-03-11 06:39:11 +0000254private:
Ted Kremenek68621b92009-01-28 05:56:51 +0000255 Kind K;
256 ObjKind O;
257 unsigned index;
258
259 RetEffect(Kind k, unsigned idx = 0) : K(k), O(AnyObj), index(idx) {}
260 RetEffect(Kind k, ObjKind o) : K(k), O(o), index(0) {}
Ted Kremenek827f93b2008-03-06 00:08:09 +0000261
Ted Kremeneka7338b42008-03-11 06:39:11 +0000262public:
Ted Kremenek68621b92009-01-28 05:56:51 +0000263 Kind getKind() const { return K; }
264
265 ObjKind getObjKind() const { return O; }
Ted Kremenek272aa852008-06-25 21:21:56 +0000266
267 unsigned getIndex() const {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000268 assert(getKind() == Alias);
Ted Kremenek68621b92009-01-28 05:56:51 +0000269 return index;
Ted Kremeneka7338b42008-03-11 06:39:11 +0000270 }
Ted Kremenek827f93b2008-03-06 00:08:09 +0000271
Ted Kremenek314b1952009-04-29 23:03:22 +0000272 bool isOwned() const {
273 return K == OwnedSymbol || K == OwnedAllocatedSymbol;
274 }
275
Ted Kremenek272aa852008-06-25 21:21:56 +0000276 static RetEffect MakeAlias(unsigned Idx) {
277 return RetEffect(Alias, Idx);
278 }
279 static RetEffect MakeReceiverAlias() {
280 return RetEffect(ReceiverAlias);
281 }
Ted Kremenek68621b92009-01-28 05:56:51 +0000282 static RetEffect MakeOwned(ObjKind o, bool isAllocated = false) {
283 return RetEffect(isAllocated ? OwnedAllocatedSymbol : OwnedSymbol, o);
Ted Kremenek272aa852008-06-25 21:21:56 +0000284 }
Ted Kremenek68621b92009-01-28 05:56:51 +0000285 static RetEffect MakeNotOwned(ObjKind o) {
286 return RetEffect(NotOwnedSymbol, o);
Ted Kremenek382fb4e2009-04-27 19:14:45 +0000287 }
288 static RetEffect MakeGCNotOwned() {
289 return RetEffect(GCNotOwnedSymbol, ObjC);
290 }
291
Ted Kremenek272aa852008-06-25 21:21:56 +0000292 static RetEffect MakeNoRet() {
293 return RetEffect(NoRet);
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000294 }
Ted Kremenek827f93b2008-03-06 00:08:09 +0000295
Ted Kremenek272aa852008-06-25 21:21:56 +0000296 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek68621b92009-01-28 05:56:51 +0000297 ID.AddInteger((unsigned)K);
298 ID.AddInteger((unsigned)O);
299 ID.AddInteger(index);
Ted Kremenek272aa852008-06-25 21:21:56 +0000300 }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000301};
Ted Kremeneka7338b42008-03-11 06:39:11 +0000302
Ted Kremenek272aa852008-06-25 21:21:56 +0000303
304class VISIBILITY_HIDDEN RetainSummary : public llvm::FoldingSetNode {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000305 /// Args - an ordered vector of (index, ArgEffect) pairs, where index
306 /// specifies the argument (starting from 0). This can be sparsely
307 /// populated; arguments with no entry in Args use 'DefaultArgEffect'.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000308 ArgEffects Args;
Ted Kremenekbcaff792008-05-06 15:44:25 +0000309
310 /// DefaultArgEffect - The default ArgEffect to apply to arguments that
311 /// do not have an entry in Args.
312 ArgEffect DefaultArgEffect;
313
Ted Kremenek272aa852008-06-25 21:21:56 +0000314 /// Receiver - If this summary applies to an Objective-C message expression,
315 /// this is the effect applied to the state of the receiver.
Ted Kremenek266d8b62008-05-06 02:26:56 +0000316 ArgEffect Receiver;
Ted Kremenek272aa852008-06-25 21:21:56 +0000317
318 /// Ret - The effect on the return value. Used to indicate if the
319 /// function/method call returns a new tracked symbol, returns an
320 /// alias of one of the arguments in the call, and so on.
Ted Kremeneka7338b42008-03-11 06:39:11 +0000321 RetEffect Ret;
Ted Kremenek272aa852008-06-25 21:21:56 +0000322
Ted Kremenekf2717b02008-07-18 17:24:20 +0000323 /// EndPath - Indicates that execution of this method/function should
324 /// terminate the simulation of a path.
325 bool EndPath;
326
Ted Kremeneka7338b42008-03-11 06:39:11 +0000327public:
Ted Kremeneka56ae162009-05-03 05:20:50 +0000328 RetainSummary(ArgEffects A, RetEffect R, ArgEffect defaultEff,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000329 ArgEffect ReceiverEff, bool endpath = false)
330 : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R),
331 EndPath(endpath) {}
Ted Kremeneka7338b42008-03-11 06:39:11 +0000332
Ted Kremenek272aa852008-06-25 21:21:56 +0000333 /// getArg - Return the argument effect on the argument specified by
334 /// idx (starting from 0).
Ted Kremenek0d721572008-03-11 17:48:22 +0000335 ArgEffect getArg(unsigned idx) const {
Ted Kremeneka56ae162009-05-03 05:20:50 +0000336 if (const ArgEffect *AE = Args.lookup(idx))
337 return *AE;
Ted Kremenekae855d42008-04-24 17:22:33 +0000338
Ted Kremenekbcaff792008-05-06 15:44:25 +0000339 return DefaultArgEffect;
Ted Kremenek0d721572008-03-11 17:48:22 +0000340 }
341
Ted Kremenek272aa852008-06-25 21:21:56 +0000342 /// getRetEffect - Returns the effect on the return value of the call.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000343 RetEffect getRetEffect() const { return Ret; }
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000344
Ted Kremenekf2717b02008-07-18 17:24:20 +0000345 /// isEndPath - Returns true if executing the given method/function should
346 /// terminate the path.
347 bool isEndPath() const { return EndPath; }
348
Ted Kremenek272aa852008-06-25 21:21:56 +0000349 /// getReceiverEffect - Returns the effect on the receiver of the call.
350 /// This is only meaningful if the summary applies to an ObjCMessageExpr*.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000351 ArgEffect getReceiverEffect() const { return Receiver; }
Ted Kremenek266d8b62008-05-06 02:26:56 +0000352
Ted Kremeneka56ae162009-05-03 05:20:50 +0000353 typedef ArgEffects::iterator ExprIterator;
Ted Kremeneka7338b42008-03-11 06:39:11 +0000354
Ted Kremeneka56ae162009-05-03 05:20:50 +0000355 ExprIterator begin_args() const { return Args.begin(); }
356 ExprIterator end_args() const { return Args.end(); }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000357
Ted Kremeneka56ae162009-05-03 05:20:50 +0000358 static void Profile(llvm::FoldingSetNodeID& ID, ArgEffects A,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000359 RetEffect RetEff, ArgEffect DefaultEff,
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000360 ArgEffect ReceiverEff, bool EndPath) {
Ted Kremeneka56ae162009-05-03 05:20:50 +0000361 ID.Add(A);
Ted Kremenek266d8b62008-05-06 02:26:56 +0000362 ID.Add(RetEff);
Ted Kremenekbcaff792008-05-06 15:44:25 +0000363 ID.AddInteger((unsigned) DefaultEff);
Ted Kremenek266d8b62008-05-06 02:26:56 +0000364 ID.AddInteger((unsigned) ReceiverEff);
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000365 ID.AddInteger((unsigned) EndPath);
Ted Kremeneka7338b42008-03-11 06:39:11 +0000366 }
367
368 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000369 Profile(ID, Args, Ret, DefaultArgEffect, Receiver, EndPath);
Ted Kremeneka7338b42008-03-11 06:39:11 +0000370 }
371};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000372} // end anonymous namespace
Ted Kremeneka7338b42008-03-11 06:39:11 +0000373
Ted Kremenek272aa852008-06-25 21:21:56 +0000374//===----------------------------------------------------------------------===//
375// Data structures for constructing summaries.
376//===----------------------------------------------------------------------===//
Ted Kremenek9f0fc792008-06-24 03:49:48 +0000377
Ted Kremenek272aa852008-06-25 21:21:56 +0000378namespace {
379class VISIBILITY_HIDDEN ObjCSummaryKey {
380 IdentifierInfo* II;
381 Selector S;
382public:
383 ObjCSummaryKey(IdentifierInfo* ii, Selector s)
384 : II(ii), S(s) {}
385
Ted Kremenek314b1952009-04-29 23:03:22 +0000386 ObjCSummaryKey(const ObjCInterfaceDecl* d, Selector s)
Ted Kremenek272aa852008-06-25 21:21:56 +0000387 : II(d ? d->getIdentifier() : 0), S(s) {}
388
389 ObjCSummaryKey(Selector s)
390 : II(0), S(s) {}
391
392 IdentifierInfo* getIdentifier() const { return II; }
393 Selector getSelector() const { return S; }
394};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000395}
396
397namespace llvm {
Ted Kremenek272aa852008-06-25 21:21:56 +0000398template <> struct DenseMapInfo<ObjCSummaryKey> {
399 static inline ObjCSummaryKey getEmptyKey() {
400 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
401 DenseMapInfo<Selector>::getEmptyKey());
402 }
Ted Kremenek84f010c2008-06-23 23:30:29 +0000403
Ted Kremenek272aa852008-06-25 21:21:56 +0000404 static inline ObjCSummaryKey getTombstoneKey() {
405 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
406 DenseMapInfo<Selector>::getTombstoneKey());
407 }
408
409 static unsigned getHashValue(const ObjCSummaryKey &V) {
410 return (DenseMapInfo<IdentifierInfo*>::getHashValue(V.getIdentifier())
411 & 0x88888888)
412 | (DenseMapInfo<Selector>::getHashValue(V.getSelector())
413 & 0x55555555);
414 }
415
416 static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
417 return DenseMapInfo<IdentifierInfo*>::isEqual(LHS.getIdentifier(),
418 RHS.getIdentifier()) &&
419 DenseMapInfo<Selector>::isEqual(LHS.getSelector(),
420 RHS.getSelector());
421 }
422
423 static bool isPod() {
424 return DenseMapInfo<ObjCInterfaceDecl*>::isPod() &&
425 DenseMapInfo<Selector>::isPod();
426 }
427};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000428} // end llvm namespace
Ted Kremeneka7338b42008-03-11 06:39:11 +0000429
Ted Kremenek84f010c2008-06-23 23:30:29 +0000430namespace {
Ted Kremenek272aa852008-06-25 21:21:56 +0000431class VISIBILITY_HIDDEN ObjCSummaryCache {
432 typedef llvm::DenseMap<ObjCSummaryKey, RetainSummary*> MapTy;
433 MapTy M;
434public:
435 ObjCSummaryCache() {}
436
437 typedef MapTy::iterator iterator;
438
Ted Kremenek314b1952009-04-29 23:03:22 +0000439 iterator find(const ObjCInterfaceDecl* D, IdentifierInfo *ClsName,
440 Selector S) {
Ted Kremeneka821b792009-04-29 05:04:30 +0000441 // Lookup the method using the decl for the class @interface. If we
442 // have no decl, lookup using the class name.
443 return D ? find(D, S) : find(ClsName, S);
444 }
445
Ted Kremenek314b1952009-04-29 23:03:22 +0000446 iterator find(const ObjCInterfaceDecl* D, Selector S) {
Ted Kremenek272aa852008-06-25 21:21:56 +0000447 // Do a lookup with the (D,S) pair. If we find a match return
448 // the iterator.
449 ObjCSummaryKey K(D, S);
450 MapTy::iterator I = M.find(K);
451
452 if (I != M.end() || !D)
453 return I;
454
455 // Walk the super chain. If we find a hit with a parent, we'll end
456 // up returning that summary. We actually allow that key (null,S), as
457 // we cache summaries for the null ObjCInterfaceDecl* to allow us to
458 // generate initial summaries without having to worry about NSObject
459 // being declared.
460 // FIXME: We may change this at some point.
461 for (ObjCInterfaceDecl* C=D->getSuperClass() ;; C=C->getSuperClass()) {
462 if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
463 break;
464
465 if (!C)
466 return I;
467 }
468
469 // Cache the summary with original key to make the next lookup faster
470 // and return the iterator.
471 M[K] = I->second;
472 return I;
473 }
474
Ted Kremenek9449ca92008-08-12 20:41:56 +0000475
Ted Kremenek272aa852008-06-25 21:21:56 +0000476 iterator find(Expr* Receiver, Selector S) {
477 return find(getReceiverDecl(Receiver), S);
478 }
479
480 iterator find(IdentifierInfo* II, Selector S) {
481 // FIXME: Class method lookup. Right now we dont' have a good way
482 // of going between IdentifierInfo* and the class hierarchy.
483 iterator I = M.find(ObjCSummaryKey(II, S));
484 return I == M.end() ? M.find(ObjCSummaryKey(S)) : I;
485 }
486
487 ObjCInterfaceDecl* getReceiverDecl(Expr* E) {
488
489 const PointerType* PT = E->getType()->getAsPointerType();
490 if (!PT) return 0;
491
492 ObjCInterfaceType* OI = dyn_cast<ObjCInterfaceType>(PT->getPointeeType());
493 if (!OI) return 0;
494
495 return OI ? OI->getDecl() : 0;
496 }
497
498 iterator end() { return M.end(); }
499
500 RetainSummary*& operator[](ObjCMessageExpr* ME) {
501
502 Selector S = ME->getSelector();
503
504 if (Expr* Receiver = ME->getReceiver()) {
505 ObjCInterfaceDecl* OD = getReceiverDecl(Receiver);
506 return OD ? M[ObjCSummaryKey(OD->getIdentifier(), S)] : M[S];
507 }
508
509 return M[ObjCSummaryKey(ME->getClassName(), S)];
510 }
511
512 RetainSummary*& operator[](ObjCSummaryKey K) {
513 return M[K];
514 }
515
516 RetainSummary*& operator[](Selector S) {
517 return M[ ObjCSummaryKey(S) ];
518 }
519};
520} // end anonymous namespace
521
522//===----------------------------------------------------------------------===//
523// Data structures for managing collections of summaries.
524//===----------------------------------------------------------------------===//
525
526namespace {
527class VISIBILITY_HIDDEN RetainSummaryManager {
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000528
529 //==-----------------------------------------------------------------==//
530 // Typedefs.
531 //==-----------------------------------------------------------------==//
Ted Kremeneka7338b42008-03-11 06:39:11 +0000532
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000533 typedef llvm::FoldingSet<RetainSummary>
534 SummarySetTy;
535
536 typedef llvm::DenseMap<FunctionDecl*, RetainSummary*>
537 FuncSummariesTy;
538
Ted Kremenek84f010c2008-06-23 23:30:29 +0000539 typedef ObjCSummaryCache ObjCMethodSummariesTy;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000540
541 //==-----------------------------------------------------------------==//
542 // Data.
543 //==-----------------------------------------------------------------==//
544
Ted Kremenek272aa852008-06-25 21:21:56 +0000545 /// Ctx - The ASTContext object for the analyzed ASTs.
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000546 ASTContext& Ctx;
Ted Kremeneke44927e2008-07-01 17:21:27 +0000547
Ted Kremenekede40b72008-07-09 18:11:16 +0000548 /// CFDictionaryCreateII - An IdentifierInfo* representing the indentifier
549 /// "CFDictionaryCreate".
550 IdentifierInfo* CFDictionaryCreateII;
551
Ted Kremenek272aa852008-06-25 21:21:56 +0000552 /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000553 const bool GCEnabled;
554
Ted Kremenek272aa852008-06-25 21:21:56 +0000555 /// SummarySet - A FoldingSet of uniqued summaries.
Ted Kremeneka4c74292008-04-10 22:58:08 +0000556 SummarySetTy SummarySet;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000557
Ted Kremenek272aa852008-06-25 21:21:56 +0000558 /// FuncSummaries - A map from FunctionDecls to summaries.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000559 FuncSummariesTy FuncSummaries;
560
Ted Kremenek272aa852008-06-25 21:21:56 +0000561 /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
562 /// to summaries.
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000563 ObjCMethodSummariesTy ObjCClassMethodSummaries;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000564
Ted Kremenek272aa852008-06-25 21:21:56 +0000565 /// ObjCMethodSummaries - A map from selectors to summaries.
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000566 ObjCMethodSummariesTy ObjCMethodSummaries;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000567
Ted Kremenek272aa852008-06-25 21:21:56 +0000568 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
569 /// and all other data used by the checker.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000570 llvm::BumpPtrAllocator BPAlloc;
571
Ted Kremeneka56ae162009-05-03 05:20:50 +0000572 /// AF - A factory for ArgEffects objects.
573 ArgEffects::Factory AF;
574
Ted Kremenek272aa852008-06-25 21:21:56 +0000575 /// ScratchArgs - A holding buffer for construct ArgEffects.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000576 ArgEffects ScratchArgs;
577
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000578 RetainSummary* StopSummary;
579
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000580 //==-----------------------------------------------------------------==//
581 // Methods.
582 //==-----------------------------------------------------------------==//
583
Ted Kremenek272aa852008-06-25 21:21:56 +0000584 /// getArgEffects - Returns a persistent ArgEffects object based on the
585 /// data in ScratchArgs.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000586 ArgEffects getArgEffects();
Ted Kremeneka7338b42008-03-11 06:39:11 +0000587
Ted Kremenek562c1302008-05-05 16:51:50 +0000588 enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000589
590public:
Ted Kremenek064ef322009-02-23 16:51:39 +0000591 RetainSummary* getUnarySummary(const FunctionType* FT, UnaryFuncKind func);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000592
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000593 RetainSummary* getCFSummaryCreateRule(FunctionDecl* FD);
594 RetainSummary* getCFSummaryGetRule(FunctionDecl* FD);
Ted Kremenek17144e82009-01-12 21:45:02 +0000595 RetainSummary* getCFCreateGetRuleSummary(FunctionDecl* FD, const char* FName);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000596
Ted Kremeneka56ae162009-05-03 05:20:50 +0000597 RetainSummary* getPersistentSummary(ArgEffects AE, RetEffect RetEff,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000598 ArgEffect ReceiverEff = DoNothing,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000599 ArgEffect DefaultEff = MayEscape,
600 bool isEndPath = false);
Ted Kremenek45d0b502008-10-29 04:07:07 +0000601
Ted Kremenek266d8b62008-05-06 02:26:56 +0000602 RetainSummary* getPersistentSummary(RetEffect RE,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000603 ArgEffect ReceiverEff = DoNothing,
Ted Kremeneka3f30dd2008-05-22 17:31:13 +0000604 ArgEffect DefaultEff = MayEscape) {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000605 return getPersistentSummary(getArgEffects(), RE, ReceiverEff, DefaultEff);
Ted Kremenek0e344d42008-05-06 00:30:21 +0000606 }
Ted Kremenek42ea0322008-05-05 23:55:01 +0000607
Ted Kremeneka821b792009-04-29 05:04:30 +0000608 RetainSummary *getPersistentStopSummary() {
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000609 if (StopSummary)
610 return StopSummary;
611
612 StopSummary = getPersistentSummary(RetEffect::MakeNoRet(),
613 StopTracking, StopTracking);
Ted Kremenek45d0b502008-10-29 04:07:07 +0000614
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000615 return StopSummary;
Ted Kremenekbcaff792008-05-06 15:44:25 +0000616 }
Ted Kremenek926abf22008-05-06 04:20:12 +0000617
Ted Kremeneka821b792009-04-29 05:04:30 +0000618 RetainSummary *getInitMethodSummary(QualType RetTy);
Ted Kremenek42ea0322008-05-05 23:55:01 +0000619
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000620 void InitializeClassMethodSummaries();
621 void InitializeMethodSummaries();
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000622
Ted Kremenek9b42e062009-05-03 04:42:10 +0000623 bool isTrackedObjCObjectType(QualType T);
Ted Kremenek35920ed2009-01-07 00:39:56 +0000624
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000625private:
626
Ted Kremenekf2717b02008-07-18 17:24:20 +0000627 void addClsMethSummary(IdentifierInfo* ClsII, Selector S,
628 RetainSummary* Summ) {
629 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
630 }
631
Ted Kremenek272aa852008-06-25 21:21:56 +0000632 void addNSObjectClsMethSummary(Selector S, RetainSummary *Summ) {
633 ObjCClassMethodSummaries[S] = Summ;
634 }
635
636 void addNSObjectMethSummary(Selector S, RetainSummary *Summ) {
637 ObjCMethodSummaries[S] = Summ;
638 }
Ted Kremenekfbf2dc52009-03-04 23:30:42 +0000639
640 void addClassMethSummary(const char* Cls, const char* nullaryName,
641 RetainSummary *Summ) {
642 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
643 Selector S = GetNullarySelector(nullaryName, Ctx);
644 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
645 }
Ted Kremenek272aa852008-06-25 21:21:56 +0000646
Ted Kremenek1b4b6562009-02-25 02:54:57 +0000647 void addInstMethSummary(const char* Cls, const char* nullaryName,
648 RetainSummary *Summ) {
649 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
650 Selector S = GetNullarySelector(nullaryName, Ctx);
651 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
652 }
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000653
654 Selector generateSelector(va_list argp) {
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000655 llvm::SmallVector<IdentifierInfo*, 10> II;
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000656
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000657 while (const char* s = va_arg(argp, const char*))
658 II.push_back(&Ctx.Idents.get(s));
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000659
660 return Ctx.Selectors.getSelector(II.size(), &II[0]);
661 }
662
663 void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy& Summaries,
664 RetainSummary* Summ, va_list argp) {
665 Selector S = generateSelector(argp);
666 Summaries[ObjCSummaryKey(ClsII, S)] = Summ;
Ted Kremenekf2717b02008-07-18 17:24:20 +0000667 }
Ted Kremenek45642a42008-08-12 18:48:50 +0000668
669 void addInstMethSummary(const char* Cls, RetainSummary* Summ, ...) {
670 va_list argp;
671 va_start(argp, Summ);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000672 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Ted Kremenek45642a42008-08-12 18:48:50 +0000673 va_end(argp);
674 }
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000675
676 void addClsMethSummary(const char* Cls, RetainSummary* Summ, ...) {
677 va_list argp;
678 va_start(argp, Summ);
679 addMethodSummary(&Ctx.Idents.get(Cls),ObjCClassMethodSummaries, Summ, argp);
680 va_end(argp);
681 }
682
683 void addClsMethSummary(IdentifierInfo *II, RetainSummary* Summ, ...) {
684 va_list argp;
685 va_start(argp, Summ);
686 addMethodSummary(II, ObjCClassMethodSummaries, Summ, argp);
687 va_end(argp);
688 }
689
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000690 void addPanicSummary(const char* Cls, ...) {
Ted Kremeneka56ae162009-05-03 05:20:50 +0000691 RetainSummary* Summ = getPersistentSummary(AF.GetEmptyMap(),
692 RetEffect::MakeNoRet(),
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000693 DoNothing, DoNothing, true);
694 va_list argp;
695 va_start (argp, Cls);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000696 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000697 va_end(argp);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000698 }
Ted Kremenekf2717b02008-07-18 17:24:20 +0000699
Ted Kremeneka7338b42008-03-11 06:39:11 +0000700public:
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000701
702 RetainSummaryManager(ASTContext& ctx, bool gcenabled)
Ted Kremeneke44927e2008-07-01 17:21:27 +0000703 : Ctx(ctx),
Ted Kremenekede40b72008-07-09 18:11:16 +0000704 CFDictionaryCreateII(&ctx.Idents.get("CFDictionaryCreate")),
Ted Kremeneka56ae162009-05-03 05:20:50 +0000705 GCEnabled(gcenabled), AF(BPAlloc), ScratchArgs(AF.GetEmptyMap()),
706 StopSummary(0) {
Ted Kremenek272aa852008-06-25 21:21:56 +0000707
708 InitializeClassMethodSummaries();
709 InitializeMethodSummaries();
710 }
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000711
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000712 ~RetainSummaryManager();
Ted Kremeneka7338b42008-03-11 06:39:11 +0000713
Ted Kremenekd13c1872008-06-24 03:56:45 +0000714 RetainSummary* getSummary(FunctionDecl* FD);
Ted Kremeneka821b792009-04-29 05:04:30 +0000715
Ted Kremenek314b1952009-04-29 23:03:22 +0000716 RetainSummary* getInstanceMethodSummary(ObjCMessageExpr* ME,
717 const ObjCInterfaceDecl* ID) {
Ted Kremenek04e00302009-04-29 17:09:14 +0000718 return getInstanceMethodSummary(ME->getSelector(), ME->getClassName(),
Ted Kremeneka821b792009-04-29 05:04:30 +0000719 ID, ME->getMethodDecl(), ME->getType());
720 }
721
Ted Kremenek04e00302009-04-29 17:09:14 +0000722 RetainSummary* getInstanceMethodSummary(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(Selector S, IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +0000728 const ObjCInterfaceDecl *ID,
729 const ObjCMethodDecl *MD,
730 QualType RetTy);
Ted Kremenek578498a2009-04-29 00:42:39 +0000731
732 RetainSummary *getClassMethodSummary(ObjCMessageExpr *ME) {
733 return getClassMethodSummary(ME->getSelector(), ME->getClassName(),
734 ME->getClassInfo().first,
735 ME->getMethodDecl(), ME->getType());
736 }
Ted Kremenek91b89a42009-04-29 17:17:48 +0000737
738 /// getMethodSummary - This version of getMethodSummary is used to query
739 /// the summary for the current method being analyzed.
Ted Kremenek314b1952009-04-29 23:03:22 +0000740 RetainSummary *getMethodSummary(const ObjCMethodDecl *MD) {
741 // FIXME: Eventually this should be unneeded.
Ted Kremenek314b1952009-04-29 23:03:22 +0000742 const ObjCInterfaceDecl *ID = MD->getClassInterface();
Ted Kremenek1447cc92009-04-30 05:41:14 +0000743 Selector S = MD->getSelector();
Ted Kremenek91b89a42009-04-29 17:17:48 +0000744 IdentifierInfo *ClsName = ID->getIdentifier();
745 QualType ResultTy = MD->getResultType();
746
Ted Kremenek81eb4642009-04-30 05:47:23 +0000747 // Resolve the method decl last.
748 if (const ObjCMethodDecl *InterfaceMD =
749 ResolveToInterfaceMethodDecl(MD, Ctx))
750 MD = InterfaceMD;
Ted Kremenek1447cc92009-04-30 05:41:14 +0000751
Ted Kremenek91b89a42009-04-29 17:17:48 +0000752 if (MD->isInstanceMethod())
753 return getInstanceMethodSummary(S, ClsName, ID, MD, ResultTy);
754 else
755 return getClassMethodSummary(S, ClsName, ID, MD, ResultTy);
756 }
Ted Kremenek578498a2009-04-29 00:42:39 +0000757
Ted Kremenek314b1952009-04-29 23:03:22 +0000758 RetainSummary* getCommonMethodSummary(const ObjCMethodDecl* MD,
759 Selector S, QualType RetTy);
760
761 RetainSummary* getMethodSummaryFromAnnotations(const ObjCMethodDecl *MD);
Ted Kremenek926abf22008-05-06 04:20:12 +0000762
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000763 bool isGCEnabled() const { return GCEnabled; }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000764};
765
766} // end anonymous namespace
767
768//===----------------------------------------------------------------------===//
769// Implementation of checker data structures.
770//===----------------------------------------------------------------------===//
771
Ted Kremeneka56ae162009-05-03 05:20:50 +0000772RetainSummaryManager::~RetainSummaryManager() {}
Ted Kremeneka7338b42008-03-11 06:39:11 +0000773
Ted Kremeneka56ae162009-05-03 05:20:50 +0000774ArgEffects RetainSummaryManager::getArgEffects() {
775 ArgEffects AE = ScratchArgs;
776 ScratchArgs = AF.GetEmptyMap();
777 return AE;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000778}
779
Ted Kremenek266d8b62008-05-06 02:26:56 +0000780RetainSummary*
Ted Kremeneka56ae162009-05-03 05:20:50 +0000781RetainSummaryManager::getPersistentSummary(ArgEffects AE, RetEffect RetEff,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000782 ArgEffect ReceiverEff,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000783 ArgEffect DefaultEff,
784 bool isEndPath) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000785
Ted Kremenekae855d42008-04-24 17:22:33 +0000786 // Generate a profile for the summary.
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000787 llvm::FoldingSetNodeID profile;
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000788 RetainSummary::Profile(profile, AE, RetEff, DefaultEff, ReceiverEff,
789 isEndPath);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000790
Ted Kremenekae855d42008-04-24 17:22:33 +0000791 // Look up the uniqued summary, or create one if it doesn't exist.
792 void* InsertPos;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000793 RetainSummary* Summ = SummarySet.FindNodeOrInsertPos(profile, InsertPos);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000794
795 if (Summ)
796 return Summ;
797
Ted Kremenekae855d42008-04-24 17:22:33 +0000798 // Create the summary and return it.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000799 Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
Ted Kremenekf2717b02008-07-18 17:24:20 +0000800 new (Summ) RetainSummary(AE, RetEff, DefaultEff, ReceiverEff, isEndPath);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000801 SummarySet.InsertNode(Summ, InsertPos);
802
803 return Summ;
804}
805
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000806//===----------------------------------------------------------------------===//
Ted Kremenek35920ed2009-01-07 00:39:56 +0000807// Predicates.
808//===----------------------------------------------------------------------===//
809
Ted Kremenek9b42e062009-05-03 04:42:10 +0000810bool RetainSummaryManager::isTrackedObjCObjectType(QualType Ty) {
Ted Kremenek0d813552009-04-23 22:11:07 +0000811 if (!Ctx.isObjCObjectPointerType(Ty))
Ted Kremenek35920ed2009-01-07 00:39:56 +0000812 return false;
813
Ted Kremenek0d813552009-04-23 22:11:07 +0000814 // We assume that id<..>, id, and "Class" all represent tracked objects.
815 const PointerType *PT = Ty->getAsPointerType();
816 if (PT == 0)
817 return true;
818
819 const ObjCInterfaceType *OT = PT->getPointeeType()->getAsObjCInterfaceType();
Ted Kremenek35920ed2009-01-07 00:39:56 +0000820
821 // We assume that id<..>, id, and "Class" all represent tracked objects.
822 if (!OT)
823 return true;
Ted Kremenek0d813552009-04-23 22:11:07 +0000824
825 // Does the interface subclass NSObject?
Ted Kremenek35920ed2009-01-07 00:39:56 +0000826 // FIXME: We can memoize here if this gets too expensive.
827 IdentifierInfo* NSObjectII = &Ctx.Idents.get("NSObject");
828 ObjCInterfaceDecl* ID = OT->getDecl();
829
830 for ( ; ID ; ID = ID->getSuperClass())
831 if (ID->getIdentifier() == NSObjectII)
832 return true;
833
834 return false;
835}
836
837//===----------------------------------------------------------------------===//
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000838// Summary creation for functions (largely uses of Core Foundation).
839//===----------------------------------------------------------------------===//
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000840
Ted Kremenek17144e82009-01-12 21:45:02 +0000841static bool isRetain(FunctionDecl* FD, const char* FName) {
842 const char* loc = strstr(FName, "Retain");
843 return loc && loc[sizeof("Retain")-1] == '\0';
844}
845
846static bool isRelease(FunctionDecl* FD, const char* FName) {
847 const char* loc = strstr(FName, "Release");
848 return loc && loc[sizeof("Release")-1] == '\0';
849}
850
Ted Kremenekd13c1872008-06-24 03:56:45 +0000851RetainSummary* RetainSummaryManager::getSummary(FunctionDecl* FD) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000852
853 SourceLocation Loc = FD->getLocation();
854
855 if (!Loc.isFileID())
856 return NULL;
Ted Kremenek827f93b2008-03-06 00:08:09 +0000857
Ted Kremenekae855d42008-04-24 17:22:33 +0000858 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000859 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremenekae855d42008-04-24 17:22:33 +0000860
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000861 if (I != FuncSummaries.end())
Ted Kremenekae855d42008-04-24 17:22:33 +0000862 return I->second;
863
864 // No summary. Generate one.
Ted Kremenek17144e82009-01-12 21:45:02 +0000865 RetainSummary *S = 0;
Ted Kremenek562c1302008-05-05 16:51:50 +0000866
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000867 do {
Ted Kremenek17144e82009-01-12 21:45:02 +0000868 // We generate "stop" summaries for implicitly defined functions.
869 if (FD->isImplicit()) {
870 S = getPersistentStopSummary();
871 break;
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000872 }
Ted Kremenekeafcc2f2008-11-04 00:36:12 +0000873
Ted Kremenek064ef322009-02-23 16:51:39 +0000874 // [PR 3337] Use 'getAsFunctionType' to strip away any typedefs on the
Ted Kremenekc239b9c2009-01-16 18:40:33 +0000875 // function's type.
Ted Kremenek064ef322009-02-23 16:51:39 +0000876 const FunctionType* FT = FD->getType()->getAsFunctionType();
Ted Kremenek17144e82009-01-12 21:45:02 +0000877 const char* FName = FD->getIdentifier()->getName();
878
Ted Kremenek38c6f022009-03-05 22:11:14 +0000879 // Strip away preceding '_'. Doing this here will effect all the checks
880 // down below.
881 while (*FName == '_') ++FName;
882
Ted Kremenek17144e82009-01-12 21:45:02 +0000883 // Inspect the result type.
884 QualType RetTy = FT->getResultType();
885
886 // FIXME: This should all be refactored into a chain of "summary lookup"
887 // filters.
888 if (strcmp(FName, "IOServiceGetMatchingServices") == 0) {
889 // FIXES: <rdar://problem/6326900>
890 // This should be addressed using a API table. This strcmp is also
891 // a little gross, but there is no need to super optimize here.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000892 assert (ScratchArgs.isEmpty());
893 ScratchArgs = AF.Add(ScratchArgs, 1, DecRef);
Ted Kremenek17144e82009-01-12 21:45:02 +0000894 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
895 break;
Ted Kremenekcfc50c72008-10-22 20:54:52 +0000896 }
Ted Kremenek7b88c892009-03-17 22:43:44 +0000897
898 // Enable this code once the semantics of NSDeallocateObject are resolved
899 // for GC. <rdar://problem/6619988>
900#if 0
901 // Handle: NSDeallocateObject(id anObject);
902 // This method does allow 'nil' (although we don't check it now).
903 if (strcmp(FName, "NSDeallocateObject") == 0) {
904 return RetTy == Ctx.VoidTy
905 ? getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, Dealloc)
906 : getPersistentStopSummary();
907 }
908#endif
Ted Kremenek17144e82009-01-12 21:45:02 +0000909
910 // Handle: id NSMakeCollectable(CFTypeRef)
911 if (strcmp(FName, "NSMakeCollectable") == 0) {
912 S = (RetTy == Ctx.getObjCIdType())
913 ? getUnarySummary(FT, cfmakecollectable)
914 : getPersistentStopSummary();
915
916 break;
917 }
918
919 if (RetTy->isPointerType()) {
920 // For CoreFoundation ('CF') types.
921 if (isRefType(RetTy, "CF", &Ctx, FName)) {
922 if (isRetain(FD, FName))
923 S = getUnarySummary(FT, cfretain);
924 else if (strstr(FName, "MakeCollectable"))
925 S = getUnarySummary(FT, cfmakecollectable);
926 else
927 S = getCFCreateGetRuleSummary(FD, FName);
928
929 break;
930 }
931
932 // For CoreGraphics ('CG') types.
933 if (isRefType(RetTy, "CG", &Ctx, FName)) {
934 if (isRetain(FD, FName))
935 S = getUnarySummary(FT, cfretain);
936 else
937 S = getCFCreateGetRuleSummary(FD, FName);
938
939 break;
940 }
941
942 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
943 if (isRefType(RetTy, "DADisk") ||
944 isRefType(RetTy, "DADissenter") ||
945 isRefType(RetTy, "DASessionRef")) {
946 S = getCFCreateGetRuleSummary(FD, FName);
947 break;
948 }
949
950 break;
951 }
952
953 // Check for release functions, the only kind of functions that we care
954 // about that don't return a pointer type.
955 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
Ted Kremenek38c6f022009-03-05 22:11:14 +0000956 // Test for 'CGCF'.
957 if (FName[1] == 'G' && FName[2] == 'C' && FName[3] == 'F')
958 FName += 4;
959 else
960 FName += 2;
961
962 if (isRelease(FD, FName))
Ted Kremenek17144e82009-01-12 21:45:02 +0000963 S = getUnarySummary(FT, cfrelease);
964 else {
Ted Kremeneka56ae162009-05-03 05:20:50 +0000965 assert (ScratchArgs.isEmpty());
Ted Kremenek7b293682009-01-29 22:45:13 +0000966 // Remaining CoreFoundation and CoreGraphics functions.
967 // We use to assume that they all strictly followed the ownership idiom
968 // and that ownership cannot be transferred. While this is technically
969 // correct, many methods allow a tracked object to escape. For example:
970 //
971 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
972 // CFDictionaryAddValue(y, key, x);
973 // CFRelease(x);
974 // ... it is okay to use 'x' since 'y' has a reference to it
975 //
976 // We handle this and similar cases with the follow heuristic. If the
977 // function name contains "InsertValue", "SetValue" or "AddValue" then
978 // we assume that arguments may "escape."
979 //
980 ArgEffect E = (CStrInCStrNoCase(FName, "InsertValue") ||
981 CStrInCStrNoCase(FName, "AddValue") ||
Ted Kremenekcf071252009-02-05 22:34:53 +0000982 CStrInCStrNoCase(FName, "SetValue") ||
983 CStrInCStrNoCase(FName, "AppendValue"))
Ted Kremenek7b293682009-01-29 22:45:13 +0000984 ? MayEscape : DoNothing;
985
986 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek17144e82009-01-12 21:45:02 +0000987 }
988 }
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000989 }
990 while (0);
Ted Kremenekae855d42008-04-24 17:22:33 +0000991
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000992 FuncSummaries[FD] = S;
Ted Kremenek562c1302008-05-05 16:51:50 +0000993 return S;
Ted Kremenek827f93b2008-03-06 00:08:09 +0000994}
995
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000996RetainSummary*
997RetainSummaryManager::getCFCreateGetRuleSummary(FunctionDecl* FD,
998 const char* FName) {
999
Ted Kremenek562c1302008-05-05 16:51:50 +00001000 if (strstr(FName, "Create") || strstr(FName, "Copy"))
1001 return getCFSummaryCreateRule(FD);
Ted Kremenek4c5378c2008-07-15 16:50:12 +00001002
Ted Kremenek562c1302008-05-05 16:51:50 +00001003 if (strstr(FName, "Get"))
1004 return getCFSummaryGetRule(FD);
1005
1006 return 0;
1007}
1008
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001009RetainSummary*
Ted Kremenek064ef322009-02-23 16:51:39 +00001010RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1011 UnaryFuncKind func) {
1012
Ted Kremenek17144e82009-01-12 21:45:02 +00001013 // Sanity check that this is *really* a unary function. This can
1014 // happen if people do weird things.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001015 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
Ted Kremenek17144e82009-01-12 21:45:02 +00001016 if (!FTP || FTP->getNumArgs() != 1)
1017 return getPersistentStopSummary();
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001018
Ted Kremeneka56ae162009-05-03 05:20:50 +00001019 assert (ScratchArgs.isEmpty());
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001020
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001021 switch (func) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001022 case cfretain: {
1023 ScratchArgs = AF.Add(ScratchArgs, 0, IncRef);
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001024 return getPersistentSummary(RetEffect::MakeAlias(0),
1025 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001026 }
1027
1028 case cfrelease: {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001029 ScratchArgs = AF.Add(ScratchArgs, 0, DecRef);
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001030 return getPersistentSummary(RetEffect::MakeNoRet(),
1031 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001032 }
1033
1034 case cfmakecollectable: {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001035 ScratchArgs = AF.Add(ScratchArgs, 0, MakeCollectable);
Ted Kremenek2126bef2009-02-18 21:57:45 +00001036 return getPersistentSummary(RetEffect::MakeAlias(0),DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001037 }
1038
1039 default:
Ted Kremenek562c1302008-05-05 16:51:50 +00001040 assert (false && "Not a supported unary function.");
Ted Kremenek9449ca92008-08-12 20:41:56 +00001041 return 0;
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00001042 }
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001043}
1044
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001045RetainSummary* RetainSummaryManager::getCFSummaryCreateRule(FunctionDecl* FD) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001046 assert (ScratchArgs.isEmpty());
Ted Kremenekede40b72008-07-09 18:11:16 +00001047
1048 if (FD->getIdentifier() == CFDictionaryCreateII) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001049 ScratchArgs = AF.Add(ScratchArgs, 1, DoNothingByRef);
1050 ScratchArgs = AF.Add(ScratchArgs, 2, DoNothingByRef);
Ted Kremenekede40b72008-07-09 18:11:16 +00001051 }
1052
Ted Kremenek68621b92009-01-28 05:56:51 +00001053 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001054}
1055
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001056RetainSummary* RetainSummaryManager::getCFSummaryGetRule(FunctionDecl* FD) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001057 assert (ScratchArgs.isEmpty());
Ted Kremenek68621b92009-01-28 05:56:51 +00001058 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1059 DoNothing, DoNothing);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001060}
1061
Ted Kremeneka7338b42008-03-11 06:39:11 +00001062//===----------------------------------------------------------------------===//
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001063// Summary creation for Selectors.
1064//===----------------------------------------------------------------------===//
1065
Ted Kremenekbcaff792008-05-06 15:44:25 +00001066RetainSummary*
Ted Kremeneka821b792009-04-29 05:04:30 +00001067RetainSummaryManager::getInitMethodSummary(QualType RetTy) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001068 assert(ScratchArgs.isEmpty());
Ted Kremenek42ea0322008-05-05 23:55:01 +00001069
Ted Kremenek802cfc72009-02-20 00:05:35 +00001070 // 'init' methods only return an alias if the return type is a location type.
Ted Kremeneka821b792009-04-29 05:04:30 +00001071 return getPersistentSummary(Loc::IsLocType(RetTy)
1072 ? RetEffect::MakeReceiverAlias()
1073 : RetEffect::MakeNoRet());
Ted Kremenek42ea0322008-05-05 23:55:01 +00001074}
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001075
Ted Kremenek923fc392009-04-24 23:32:32 +00001076RetainSummary*
Ted Kremenek314b1952009-04-29 23:03:22 +00001077RetainSummaryManager::getMethodSummaryFromAnnotations(const ObjCMethodDecl *MD){
Ted Kremenek923fc392009-04-24 23:32:32 +00001078 if (!MD)
1079 return 0;
1080
Ted Kremeneka56ae162009-05-03 05:20:50 +00001081 assert(ScratchArgs.isEmpty());
Ted Kremenek923fc392009-04-24 23:32:32 +00001082
1083 // Determine if there is a special return effect for this method.
Ted Kremeneke404c0d2009-04-30 20:00:31 +00001084 bool hasEffect = false;
Ted Kremenek923fc392009-04-24 23:32:32 +00001085 RetEffect RE = RetEffect::MakeNoRet();
1086
Ted Kremenek9b42e062009-05-03 04:42:10 +00001087 if (isTrackedObjCObjectType(MD->getResultType())) {
Ted Kremenek923fc392009-04-24 23:32:32 +00001088 if (MD->getAttr<ObjCOwnershipReturnsAttr>()) {
Ted Kremenek382fb4e2009-04-27 19:14:45 +00001089 RE = isGCEnabled() ? RetEffect::MakeGCNotOwned()
1090 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremeneke404c0d2009-04-30 20:00:31 +00001091 hasEffect = true;
Ted Kremenek923fc392009-04-24 23:32:32 +00001092 }
1093 else {
1094 // Default to 'not owned'.
1095 RE = RetEffect::MakeNotOwned(RetEffect::ObjC);
1096 }
1097 }
1098
Ted Kremenekb30a2f32009-04-25 01:21:50 +00001099 // Determine if there are any arguments with a specific ArgEffect.
Ted Kremenekb30a2f32009-04-25 01:21:50 +00001100 unsigned i = 0;
1101 for (ObjCMethodDecl::param_iterator I = MD->param_begin(),
1102 E = MD->param_end(); I != E; ++I, ++i) {
1103 if ((*I)->getAttr<ObjCOwnershipRetainAttr>()) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001104 ScratchArgs = AF.Add(ScratchArgs, i, IncRefMsg);
Ted Kremeneke404c0d2009-04-30 20:00:31 +00001105 hasEffect = true;
Ted Kremenekb30a2f32009-04-25 01:21:50 +00001106 }
Ted Kremenek15830ed2009-04-27 18:27:22 +00001107 else if ((*I)->getAttr<ObjCOwnershipCFRetainAttr>()) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001108 ScratchArgs = AF.Add(ScratchArgs, i, IncRef);
Ted Kremeneke404c0d2009-04-30 20:00:31 +00001109 hasEffect = true;
Ted Kremenek203169f2009-04-27 19:36:56 +00001110 }
1111 else if ((*I)->getAttr<ObjCOwnershipReleaseAttr>()) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001112 ScratchArgs = AF.Add(ScratchArgs, i, DecRefMsg);
Ted Kremeneke404c0d2009-04-30 20:00:31 +00001113 hasEffect = true;
Ted Kremenek203169f2009-04-27 19:36:56 +00001114 }
1115 else if ((*I)->getAttr<ObjCOwnershipCFReleaseAttr>()) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001116 ScratchArgs = AF.Add(ScratchArgs, i, DecRef);
Ted Kremeneke404c0d2009-04-30 20:00:31 +00001117 hasEffect = true;
Ted Kremenek203169f2009-04-27 19:36:56 +00001118 }
Ted Kremenekff8648d2009-04-28 22:32:26 +00001119 else if ((*I)->getAttr<ObjCOwnershipMakeCollectableAttr>()) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001120 ScratchArgs = AF.Add(ScratchArgs, i, MakeCollectable);
Ted Kremeneke404c0d2009-04-30 20:00:31 +00001121 hasEffect = true;
Ted Kremenekff8648d2009-04-28 22:32:26 +00001122 }
Ted Kremenek15830ed2009-04-27 18:27:22 +00001123 }
Ted Kremenekb30a2f32009-04-25 01:21:50 +00001124
Ted Kremeneke404c0d2009-04-30 20:00:31 +00001125 // Determine any effects on the receiver.
1126 ArgEffect ReceiverEff = DoNothing;
1127 if (MD->getAttr<ObjCOwnershipRetainAttr>()) {
1128 ReceiverEff = IncRefMsg;
1129 hasEffect = true;
1130 }
1131 else if (MD->getAttr<ObjCOwnershipReleaseAttr>()) {
1132 ReceiverEff = DecRefMsg;
1133 hasEffect = true;
1134 }
1135
1136 if (!hasEffect)
Ted Kremenek923fc392009-04-24 23:32:32 +00001137 return 0;
1138
Ted Kremeneke404c0d2009-04-30 20:00:31 +00001139 return getPersistentSummary(RE, ReceiverEff);
Ted Kremenek923fc392009-04-24 23:32:32 +00001140}
Ted Kremenek272aa852008-06-25 21:21:56 +00001141
Ted Kremenekbcaff792008-05-06 15:44:25 +00001142RetainSummary*
Ted Kremenek314b1952009-04-29 23:03:22 +00001143RetainSummaryManager::getCommonMethodSummary(const ObjCMethodDecl* MD,
1144 Selector S, QualType RetTy) {
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001145
Ted Kremenek578498a2009-04-29 00:42:39 +00001146 if (MD) {
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001147 // Scan the method decl for 'void*' arguments. These should be treated
1148 // as 'StopTracking' because they are often used with delegates.
1149 // Delegates are a frequent form of false positives with the retain
1150 // count checker.
1151 unsigned i = 0;
1152 for (ObjCMethodDecl::param_iterator I = MD->param_begin(),
1153 E = MD->param_end(); I != E; ++I, ++i)
1154 if (ParmVarDecl *PD = *I) {
1155 QualType Ty = Ctx.getCanonicalType(PD->getType());
1156 if (Ty.getUnqualifiedType() == Ctx.VoidPtrTy)
Ted Kremeneka56ae162009-05-03 05:20:50 +00001157 ScratchArgs = AF.Add(ScratchArgs, i, StopTracking);
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001158 }
1159 }
1160
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001161 // Any special effect for the receiver?
1162 ArgEffect ReceiverEff = DoNothing;
1163
1164 // If one of the arguments in the selector has the keyword 'delegate' we
1165 // should stop tracking the reference count for the receiver. This is
1166 // because the reference count is quite possibly handled by a delegate
1167 // method.
1168 if (S.isKeywordSelector()) {
1169 const std::string &str = S.getAsString();
1170 assert(!str.empty());
1171 if (CStrInCStrNoCase(&str[0], "delegate:")) ReceiverEff = StopTracking;
1172 }
1173
Ted Kremenek174a0772009-04-23 23:08:22 +00001174 // Look for methods that return an owned object.
Ted Kremenek9b42e062009-05-03 04:42:10 +00001175 if (!isTrackedObjCObjectType(RetTy)) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001176 if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing)
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001177 return 0;
1178
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001179 return getPersistentSummary(RetEffect::MakeNoRet(), ReceiverEff,
1180 MayEscape);
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001181 }
Ted Kremenek174a0772009-04-23 23:08:22 +00001182
1183 // EXPERIMENTAL: Assume the Cocoa conventions for all objects returned
1184 // by instance methods.
1185
1186 RetEffect E =
Ted Kremenekaca0b452009-04-24 18:19:07 +00001187 followsFundamentalRule(S.getIdentifierInfoForSlot(0)->getName())
Ted Kremenek382fb4e2009-04-27 19:14:45 +00001188 ? (isGCEnabled() ? RetEffect::MakeGCNotOwned()
Ted Kremenek174a0772009-04-23 23:08:22 +00001189 : RetEffect::MakeOwned(RetEffect::ObjC, true))
1190 : RetEffect::MakeNotOwned(RetEffect::ObjC);
1191
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001192 return getPersistentSummary(E, ReceiverEff, MayEscape);
Ted Kremenek174a0772009-04-23 23:08:22 +00001193}
1194
1195RetainSummary*
Ted Kremenek04e00302009-04-29 17:09:14 +00001196RetainSummaryManager::getInstanceMethodSummary(Selector S,
1197 IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +00001198 const ObjCInterfaceDecl* ID,
1199 const ObjCMethodDecl *MD,
Ted Kremenek04e00302009-04-29 17:09:14 +00001200 QualType RetTy) {
Ted Kremenekbcaff792008-05-06 15:44:25 +00001201
Ted Kremeneka821b792009-04-29 05:04:30 +00001202 // Look up a summary in our summary cache.
1203 ObjCMethodSummariesTy::iterator I = ObjCMethodSummaries.find(ID, ClsName, S);
Ted Kremenek42ea0322008-05-05 23:55:01 +00001204
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001205 if (I != ObjCMethodSummaries.end())
Ted Kremenek42ea0322008-05-05 23:55:01 +00001206 return I->second;
Ted Kremenek42ea0322008-05-05 23:55:01 +00001207
Ted Kremeneka56ae162009-05-03 05:20:50 +00001208 assert(ScratchArgs.isEmpty());
Ted Kremenek923fc392009-04-24 23:32:32 +00001209
1210 // Annotations take precedence over all other ways to derive
1211 // summaries.
Ted Kremeneka821b792009-04-29 05:04:30 +00001212 RetainSummary *Summ = getMethodSummaryFromAnnotations(MD);
Ted Kremenek1d3d9562008-05-06 06:09:09 +00001213
Ted Kremenek923fc392009-04-24 23:32:32 +00001214 if (!Summ) {
1215 // "initXXX": pass-through for receiver.
1216 if (deriveNamingConvention(S.getIdentifierInfoForSlot(0)->getName())
1217 == InitRule)
Ted Kremeneka821b792009-04-29 05:04:30 +00001218 Summ = getInitMethodSummary(RetTy);
1219 else
1220 Summ = getCommonMethodSummary(MD, S, RetTy);
Ted Kremenek923fc392009-04-24 23:32:32 +00001221 }
1222
Ted Kremeneka821b792009-04-29 05:04:30 +00001223 ObjCMethodSummaries[ObjCSummaryKey(ClsName, S)] = Summ;
Ted Kremeneke4158502009-04-23 19:11:35 +00001224 return Summ;
Ted Kremenek42ea0322008-05-05 23:55:01 +00001225}
1226
Ted Kremeneka7722b72008-05-06 21:26:51 +00001227RetainSummary*
Ted Kremenek578498a2009-04-29 00:42:39 +00001228RetainSummaryManager::getClassMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +00001229 const ObjCInterfaceDecl *ID,
1230 const ObjCMethodDecl *MD,
1231 QualType RetTy) {
Ted Kremenekccbe79a2009-04-24 17:50:11 +00001232
Ted Kremenek578498a2009-04-29 00:42:39 +00001233 assert(ClsName && "Class name must be specified.");
Ted Kremeneka821b792009-04-29 05:04:30 +00001234 ObjCMethodSummariesTy::iterator I =
1235 ObjCClassMethodSummaries.find(ID, ClsName, S);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001236
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001237 if (I != ObjCClassMethodSummaries.end())
Ted Kremeneka7722b72008-05-06 21:26:51 +00001238 return I->second;
1239
Ted Kremenek923fc392009-04-24 23:32:32 +00001240 // Annotations take precedence over all other ways to derive
1241 // summaries.
Ted Kremenek578498a2009-04-29 00:42:39 +00001242 RetainSummary *Summ = getMethodSummaryFromAnnotations(MD);
Ted Kremenek923fc392009-04-24 23:32:32 +00001243
1244 if (!Summ)
Ted Kremenek578498a2009-04-29 00:42:39 +00001245 Summ = getCommonMethodSummary(MD, S, RetTy);
Ted Kremenek923fc392009-04-24 23:32:32 +00001246
Ted Kremenek578498a2009-04-29 00:42:39 +00001247 ObjCClassMethodSummaries[ObjCSummaryKey(ClsName, S)] = Summ;
Ted Kremeneke4158502009-04-23 19:11:35 +00001248 return Summ;
Ted Kremeneka7722b72008-05-06 21:26:51 +00001249}
1250
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001251void RetainSummaryManager::InitializeClassMethodSummaries() {
Ted Kremenek0e344d42008-05-06 00:30:21 +00001252
Ted Kremeneka56ae162009-05-03 05:20:50 +00001253 assert (ScratchArgs.isEmpty());
Ted Kremenek0e344d42008-05-06 00:30:21 +00001254
Ted Kremenek382fb4e2009-04-27 19:14:45 +00001255 RetEffect E = isGCEnabled() ? RetEffect::MakeGCNotOwned()
Ted Kremenek68621b92009-01-28 05:56:51 +00001256 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001257
Ted Kremenek0e344d42008-05-06 00:30:21 +00001258 RetainSummary* Summ = getPersistentSummary(E);
1259
Ted Kremenek272aa852008-06-25 21:21:56 +00001260 // Create the summaries for "alloc", "new", and "allocWithZone:" for
1261 // NSObject and its derivatives.
1262 addNSObjectClsMethSummary(GetNullarySelector("alloc", Ctx), Summ);
1263 addNSObjectClsMethSummary(GetNullarySelector("new", Ctx), Summ);
1264 addNSObjectClsMethSummary(GetUnarySelector("allocWithZone", Ctx), Summ);
Ted Kremenekf2717b02008-07-18 17:24:20 +00001265
1266 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001267 addClsMethSummary(&Ctx.Idents.get("NSAssertionHandler"),
Ted Kremenek68621b92009-01-28 05:56:51 +00001268 GetNullarySelector("currentHandler", Ctx),
1269 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001270
1271 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremeneka56ae162009-05-03 05:20:50 +00001272 ScratchArgs = AF.Add(ScratchArgs, 0, Autorelease);
Ted Kremenek9b112d22009-01-28 21:44:40 +00001273 addClsMethSummary(&Ctx.Idents.get("NSAutoreleasePool"),
1274 GetUnarySelector("addObject", Ctx),
1275 getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenekf21cb242009-02-23 02:31:16 +00001276 DoNothing, Autorelease));
Ted Kremenekccbe79a2009-04-24 17:50:11 +00001277
1278 // Create the summaries for [NSObject performSelector...]. We treat
1279 // these as 'stop tracking' for the arguments because they are often
1280 // used for delegates that can release the object. When we have better
1281 // inter-procedural analysis we can potentially do something better. This
1282 // workaround is to remove false positives.
1283 Summ = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, StopTracking);
1284 IdentifierInfo *NSObjectII = &Ctx.Idents.get("NSObject");
1285 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1286 "afterDelay", NULL);
1287 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1288 "afterDelay", "inModes", NULL);
1289 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1290 "withObject", "waitUntilDone", NULL);
1291 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1292 "withObject", "waitUntilDone", "modes", NULL);
1293 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1294 "withObject", "waitUntilDone", NULL);
1295 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1296 "withObject", "waitUntilDone", "modes", NULL);
1297 addClsMethSummary(NSObjectII, Summ, "performSelectorInBackground",
1298 "withObject", NULL);
Ted Kremenek0e344d42008-05-06 00:30:21 +00001299}
1300
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001301void RetainSummaryManager::InitializeMethodSummaries() {
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001302
Ted Kremeneka56ae162009-05-03 05:20:50 +00001303 assert (ScratchArgs.isEmpty());
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001304
Ted Kremeneka7722b72008-05-06 21:26:51 +00001305 // Create the "init" selector. It just acts as a pass-through for the
1306 // receiver.
Ted Kremenek56c70aa2009-02-23 16:54:00 +00001307 RetainSummary* InitSumm =
1308 getPersistentSummary(RetEffect::MakeReceiverAlias());
Ted Kremeneke44927e2008-07-01 17:21:27 +00001309 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001310
1311 // The next methods are allocators.
Ted Kremenek382fb4e2009-04-27 19:14:45 +00001312 RetEffect E = isGCEnabled() ? RetEffect::MakeGCNotOwned()
Ted Kremenek68621b92009-01-28 05:56:51 +00001313 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001314
Ted Kremeneke44927e2008-07-01 17:21:27 +00001315 RetainSummary* Summ = getPersistentSummary(E);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001316
1317 // Create the "copy" selector.
Ted Kremenek9449ca92008-08-12 20:41:56 +00001318 addNSObjectMethSummary(GetNullarySelector("copy", Ctx), Summ);
1319
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001320 // Create the "mutableCopy" selector.
Ted Kremenek272aa852008-06-25 21:21:56 +00001321 addNSObjectMethSummary(GetNullarySelector("mutableCopy", Ctx), Summ);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001322
Ted Kremenek266d8b62008-05-06 02:26:56 +00001323 // Create the "retain" selector.
1324 E = RetEffect::MakeReceiverAlias();
Ted Kremenek58dd95b2009-02-18 18:54:33 +00001325 Summ = getPersistentSummary(E, IncRefMsg);
Ted Kremenek272aa852008-06-25 21:21:56 +00001326 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001327
1328 // Create the "release" selector.
Ted Kremenek58dd95b2009-02-18 18:54:33 +00001329 Summ = getPersistentSummary(E, DecRefMsg);
Ted Kremenek272aa852008-06-25 21:21:56 +00001330 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Ted Kremenekc00b32b2008-05-07 21:17:39 +00001331
1332 // Create the "drain" selector.
1333 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek272aa852008-06-25 21:21:56 +00001334 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
Ted Kremenek6537a642009-03-17 19:42:23 +00001335
1336 // Create the -dealloc summary.
1337 Summ = getPersistentSummary(RetEffect::MakeNoRet(), Dealloc);
1338 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001339
1340 // Create the "autorelease" selector.
Ted Kremenek9b112d22009-01-28 21:44:40 +00001341 Summ = getPersistentSummary(E, Autorelease);
Ted Kremenek272aa852008-06-25 21:21:56 +00001342 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001343
Ted Kremenekaac82832009-02-23 17:45:03 +00001344 // Specially handle NSAutoreleasePool.
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001345 addInstMethSummary("NSAutoreleasePool", "init",
Ted Kremenekaac82832009-02-23 17:45:03 +00001346 getPersistentSummary(RetEffect::MakeReceiverAlias(),
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001347 NewAutoreleasePool));
Ted Kremenekaac82832009-02-23 17:45:03 +00001348
Ted Kremenek45642a42008-08-12 18:48:50 +00001349 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremenek7e3a3272009-02-23 02:51:29 +00001350 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1351 // self-own themselves. However, they only do this once they are displayed.
1352 // Thus, we need to track an NSWindow's display status.
1353 // This is tracked in <rdar://problem/6062711>.
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001354 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
Ted Kremeneke5a036a2009-04-03 19:02:51 +00001355 RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet());
1356
1357 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1358
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001359
1360#if 0
Ted Kremeneke44927e2008-07-01 17:21:27 +00001361 RetainSummary *NSWindowSumm =
Ted Kremenek7e3a3272009-02-23 02:51:29 +00001362 getPersistentSummary(RetEffect::MakeReceiverAlias(), StopTracking);
Ted Kremenek45642a42008-08-12 18:48:50 +00001363
1364 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1365 "styleMask", "backing", "defer", NULL);
1366
1367 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1368 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001369#endif
Ted Kremenek45642a42008-08-12 18:48:50 +00001370
1371 // For NSPanel (which subclasses NSWindow), allocated objects are not
1372 // self-owned.
Ted Kremeneke5a036a2009-04-03 19:02:51 +00001373 // FIXME: For now we don't track NSPanels. object for the same reason
1374 // as for NSWindow objects.
1375 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
1376
Ted Kremenek45642a42008-08-12 18:48:50 +00001377 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1378 "styleMask", "backing", "defer", NULL);
1379
1380 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1381 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek272aa852008-06-25 21:21:56 +00001382
Ted Kremenekf2717b02008-07-18 17:24:20 +00001383 // Create NSAssertionHandler summaries.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001384 addPanicSummary("NSAssertionHandler", "handleFailureInFunction", "file",
1385 "lineNumber", "description", NULL);
Ted Kremenekf2717b02008-07-18 17:24:20 +00001386
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001387 addPanicSummary("NSAssertionHandler", "handleFailureInMethod", "object",
1388 "file", "lineNumber", "description", NULL);
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001389}
1390
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001391//===----------------------------------------------------------------------===//
Ted Kremenek7aef4842008-04-16 20:40:59 +00001392// Reference-counting logic (typestate + counts).
Ted Kremeneka7338b42008-03-11 06:39:11 +00001393//===----------------------------------------------------------------------===//
1394
Ted Kremeneka7338b42008-03-11 06:39:11 +00001395namespace {
1396
Ted Kremenek7d421f32008-04-09 23:49:11 +00001397class VISIBILITY_HIDDEN RefVal {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001398public:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001399 enum Kind {
1400 Owned = 0, // Owning reference.
1401 NotOwned, // Reference is not owned by still valid (not freed).
1402 Released, // Object has been released.
1403 ReturnedOwned, // Returned object passes ownership to caller.
1404 ReturnedNotOwned, // Return object does not pass ownership to caller.
Ted Kremenek6537a642009-03-17 19:42:23 +00001405 ERROR_START,
1406 ErrorDeallocNotOwned, // -dealloc called on non-owned object.
1407 ErrorDeallocGC, // Calling -dealloc with GC enabled.
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001408 ErrorUseAfterRelease, // Object used after released.
1409 ErrorReleaseNotOwned, // Release of an object that was not owned.
Ted Kremenek6537a642009-03-17 19:42:23 +00001410 ERROR_LEAK_START,
Ted Kremenek311f3d42008-10-22 23:56:21 +00001411 ErrorLeak, // A memory leak due to excessive reference counts.
1412 ErrorLeakReturned // A memory leak due to the returning method not having
1413 // the correct naming conventions.
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001414 };
Ted Kremenek68621b92009-01-28 05:56:51 +00001415
1416private:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001417 Kind kind;
Ted Kremenek68621b92009-01-28 05:56:51 +00001418 RetEffect::ObjKind okind;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001419 unsigned Cnt;
Ted Kremenek272aa852008-06-25 21:21:56 +00001420 QualType T;
1421
Ted Kremenek68621b92009-01-28 05:56:51 +00001422 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, QualType t)
1423 : kind(k), okind(o), Cnt(cnt), T(t) {}
Ted Kremenek0d721572008-03-11 17:48:22 +00001424
Ted Kremenek68621b92009-01-28 05:56:51 +00001425 RefVal(Kind k, unsigned cnt = 0)
1426 : kind(k), okind(RetEffect::AnyObj), Cnt(cnt) {}
1427
1428public:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001429 Kind getKind() const { return kind; }
Ted Kremenek68621b92009-01-28 05:56:51 +00001430
1431 RetEffect::ObjKind getObjKind() const { return okind; }
Ted Kremenek0d721572008-03-11 17:48:22 +00001432
Ted Kremenek6537a642009-03-17 19:42:23 +00001433 unsigned getCount() const { return Cnt; }
1434 void clearCounts() { Cnt = 0; }
1435
Ted Kremenek272aa852008-06-25 21:21:56 +00001436 QualType getType() const { return T; }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001437
1438 // Useful predicates.
Ted Kremenek0d721572008-03-11 17:48:22 +00001439
Ted Kremenek6537a642009-03-17 19:42:23 +00001440 static bool isError(Kind k) { return k >= ERROR_START; }
Ted Kremenek1daa16c2008-03-11 18:14:09 +00001441
Ted Kremenek6537a642009-03-17 19:42:23 +00001442 static bool isLeak(Kind k) { return k >= ERROR_LEAK_START; }
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001443
Ted Kremenekffefc352008-04-11 22:25:11 +00001444 bool isOwned() const {
1445 return getKind() == Owned;
1446 }
1447
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001448 bool isNotOwned() const {
1449 return getKind() == NotOwned;
1450 }
1451
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001452 bool isReturnedOwned() const {
1453 return getKind() == ReturnedOwned;
1454 }
1455
1456 bool isReturnedNotOwned() const {
1457 return getKind() == ReturnedNotOwned;
1458 }
1459
1460 bool isNonLeakError() const {
1461 Kind k = getKind();
1462 return isError(k) && !isLeak(k);
1463 }
1464
Ted Kremenek68621b92009-01-28 05:56:51 +00001465 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
1466 unsigned Count = 1) {
1467 return RefVal(Owned, o, Count, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001468 }
1469
Ted Kremenek68621b92009-01-28 05:56:51 +00001470 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
1471 unsigned Count = 0) {
1472 return RefVal(NotOwned, o, Count, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001473 }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001474
1475 static RefVal makeReturnedOwned(unsigned Count) {
1476 return RefVal(ReturnedOwned, Count);
1477 }
1478
1479 static RefVal makeReturnedNotOwned() {
1480 return RefVal(ReturnedNotOwned);
1481 }
1482
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001483 // Comparison, profiling, and pretty-printing.
Ted Kremenek0d721572008-03-11 17:48:22 +00001484
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001485 bool operator==(const RefVal& X) const {
Ted Kremenek272aa852008-06-25 21:21:56 +00001486 return kind == X.kind && Cnt == X.Cnt && T == X.T;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001487 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001488
Ted Kremenek272aa852008-06-25 21:21:56 +00001489 RefVal operator-(size_t i) const {
Ted Kremenek68621b92009-01-28 05:56:51 +00001490 return RefVal(getKind(), getObjKind(), getCount() - i, getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001491 }
1492
1493 RefVal operator+(size_t i) const {
Ted Kremenek68621b92009-01-28 05:56:51 +00001494 return RefVal(getKind(), getObjKind(), getCount() + i, getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001495 }
1496
1497 RefVal operator^(Kind k) const {
Ted Kremenek68621b92009-01-28 05:56:51 +00001498 return RefVal(k, getObjKind(), getCount(), getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001499 }
Ted Kremenek6537a642009-03-17 19:42:23 +00001500
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001501 void Profile(llvm::FoldingSetNodeID& ID) const {
1502 ID.AddInteger((unsigned) kind);
1503 ID.AddInteger(Cnt);
Ted Kremenek272aa852008-06-25 21:21:56 +00001504 ID.Add(T);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001505 }
1506
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001507 void print(std::ostream& Out) const;
Ted Kremenek0d721572008-03-11 17:48:22 +00001508};
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001509
1510void RefVal::print(std::ostream& Out) const {
Ted Kremenek272aa852008-06-25 21:21:56 +00001511 if (!T.isNull())
1512 Out << "Tracked Type:" << T.getAsString() << '\n';
1513
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001514 switch (getKind()) {
1515 default: assert(false);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001516 case Owned: {
1517 Out << "Owned";
1518 unsigned cnt = getCount();
1519 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001520 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001521 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001522
Ted Kremenekc4f81022008-04-10 23:09:18 +00001523 case NotOwned: {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001524 Out << "NotOwned";
Ted Kremenekc4f81022008-04-10 23:09:18 +00001525 unsigned cnt = getCount();
1526 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001527 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001528 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001529
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001530 case ReturnedOwned: {
1531 Out << "ReturnedOwned";
1532 unsigned cnt = getCount();
1533 if (cnt) Out << " (+ " << cnt << ")";
1534 break;
1535 }
1536
1537 case ReturnedNotOwned: {
1538 Out << "ReturnedNotOwned";
1539 unsigned cnt = getCount();
1540 if (cnt) Out << " (+ " << cnt << ")";
1541 break;
1542 }
1543
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001544 case Released:
1545 Out << "Released";
1546 break;
Ted Kremenek6537a642009-03-17 19:42:23 +00001547
1548 case ErrorDeallocGC:
1549 Out << "-dealloc (GC)";
1550 break;
1551
1552 case ErrorDeallocNotOwned:
1553 Out << "-dealloc (not-owned)";
1554 break;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001555
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001556 case ErrorLeak:
1557 Out << "Leaked";
1558 break;
1559
Ted Kremenek311f3d42008-10-22 23:56:21 +00001560 case ErrorLeakReturned:
1561 Out << "Leaked (Bad naming)";
1562 break;
1563
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001564 case ErrorUseAfterRelease:
1565 Out << "Use-After-Release [ERROR]";
1566 break;
1567
1568 case ErrorReleaseNotOwned:
1569 Out << "Release of Not-Owned [ERROR]";
1570 break;
1571 }
1572}
Ted Kremenek0d721572008-03-11 17:48:22 +00001573
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001574} // end anonymous namespace
1575
1576//===----------------------------------------------------------------------===//
1577// RefBindings - State used to track object reference counts.
1578//===----------------------------------------------------------------------===//
1579
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001580typedef llvm::ImmutableMap<SymbolRef, RefVal> RefBindings;
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001581static int RefBIndex = 0;
Ted Kremenek876d8df2009-02-19 23:47:02 +00001582static std::pair<const void*, const void*> LeakProgramPointTag(&RefBIndex, 0);
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001583
1584namespace clang {
Ted Kremenek91781202008-08-17 03:20:02 +00001585 template<>
1586 struct GRStateTrait<RefBindings> : public GRStatePartialTrait<RefBindings> {
1587 static inline void* GDMIndex() { return &RefBIndex; }
1588 };
1589}
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001590
1591//===----------------------------------------------------------------------===//
Ted Kremenekb6578942009-02-24 19:15:11 +00001592// AutoreleaseBindings - State used to track objects in autorelease pools.
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001593//===----------------------------------------------------------------------===//
1594
Ted Kremenekb6578942009-02-24 19:15:11 +00001595typedef llvm::ImmutableMap<SymbolRef, unsigned> ARCounts;
1596typedef llvm::ImmutableMap<SymbolRef, ARCounts> ARPoolContents;
1597typedef llvm::ImmutableList<SymbolRef> ARStack;
Ted Kremenekaac82832009-02-23 17:45:03 +00001598
Ted Kremenekb6578942009-02-24 19:15:11 +00001599static int AutoRCIndex = 0;
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001600static int AutoRBIndex = 0;
1601
Ted Kremenekb6578942009-02-24 19:15:11 +00001602namespace { class VISIBILITY_HIDDEN AutoreleasePoolContents {}; }
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001603namespace { class VISIBILITY_HIDDEN AutoreleaseStack {}; }
Ted Kremenekb6578942009-02-24 19:15:11 +00001604
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001605namespace clang {
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001606template<> struct GRStateTrait<AutoreleaseStack>
Ted Kremenekb6578942009-02-24 19:15:11 +00001607 : public GRStatePartialTrait<ARStack> {
1608 static inline void* GDMIndex() { return &AutoRBIndex; }
1609};
1610
1611template<> struct GRStateTrait<AutoreleasePoolContents>
1612 : public GRStatePartialTrait<ARPoolContents> {
1613 static inline void* GDMIndex() { return &AutoRCIndex; }
1614};
1615} // end clang namespace
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001616
Ted Kremenek681fb352009-03-20 17:34:15 +00001617static SymbolRef GetCurrentAutoreleasePool(const GRState* state) {
1618 ARStack stack = state->get<AutoreleaseStack>();
1619 return stack.isEmpty() ? SymbolRef() : stack.getHead();
1620}
1621
1622static GRStateRef SendAutorelease(GRStateRef state, ARCounts::Factory &F,
1623 SymbolRef sym) {
1624
1625 SymbolRef pool = GetCurrentAutoreleasePool(state);
1626 const ARCounts *cnts = state.get<AutoreleasePoolContents>(pool);
1627 ARCounts newCnts(0);
1628
1629 if (cnts) {
1630 const unsigned *cnt = (*cnts).lookup(sym);
1631 newCnts = F.Add(*cnts, sym, cnt ? *cnt + 1 : 1);
1632 }
1633 else
1634 newCnts = F.Add(F.GetEmptyMap(), sym, 1);
1635
1636 return state.set<AutoreleasePoolContents>(pool, newCnts);
1637}
1638
Ted Kremenek7aef4842008-04-16 20:40:59 +00001639//===----------------------------------------------------------------------===//
1640// Transfer functions.
1641//===----------------------------------------------------------------------===//
1642
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001643namespace {
1644
Ted Kremenek7d421f32008-04-09 23:49:11 +00001645class VISIBILITY_HIDDEN CFRefCount : public GRSimpleVals {
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001646public:
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001647 class BindingsPrinter : public GRState::Printer {
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001648 public:
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001649 virtual void Print(std::ostream& Out, const GRState* state,
1650 const char* nl, const char* sep);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001651 };
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001652
1653private:
Ted Kremenekc26c4692009-02-18 03:48:14 +00001654 typedef llvm::DenseMap<const GRExprEngine::NodeTy*, const RetainSummary*>
1655 SummaryLogTy;
1656
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001657 RetainSummaryManager Summaries;
Ted Kremenekc26c4692009-02-18 03:48:14 +00001658 SummaryLogTy SummaryLog;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001659 const LangOptions& LOpts;
Ted Kremenekb6578942009-02-24 19:15:11 +00001660 ARCounts::Factory ARCountFactory;
Ted Kremenek91781202008-08-17 03:20:02 +00001661
Ted Kremenek708af042009-02-05 06:50:21 +00001662 BugType *useAfterRelease, *releaseNotOwned;
Ted Kremenek6537a642009-03-17 19:42:23 +00001663 BugType *deallocGC, *deallocNotOwned;
Ted Kremenek708af042009-02-05 06:50:21 +00001664 BugType *leakWithinFunction, *leakAtReturn;
1665 BugReporter *BR;
Ted Kremeneka7338b42008-03-11 06:39:11 +00001666
Ted Kremenekb6578942009-02-24 19:15:11 +00001667 GRStateRef Update(GRStateRef state, SymbolRef sym, RefVal V, ArgEffect E,
1668 RefVal::Kind& hasErr);
1669
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001670 void ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
1671 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001672 Expr* NodeExpr, Expr* ErrorExpr,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001673 ExplodedNode<GRState>* Pred,
1674 const GRState* St,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001675 RefVal::Kind hasErr, SymbolRef Sym);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001676
Ted Kremenek0106e202008-10-24 20:32:50 +00001677 std::pair<GRStateRef, bool>
1678 HandleSymbolDeath(GRStateManager& VMgr, const GRState* St,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001679 const Decl* CD, SymbolRef sid, RefVal V, bool& hasLeak);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001680
Ted Kremenekb6578942009-02-24 19:15:11 +00001681public:
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00001682 CFRefCount(ASTContext& Ctx, bool gcenabled, const LangOptions& lopts)
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001683 : Summaries(Ctx, gcenabled),
Ted Kremenek6537a642009-03-17 19:42:23 +00001684 LOpts(lopts), useAfterRelease(0), releaseNotOwned(0),
1685 deallocGC(0), deallocNotOwned(0),
Ted Kremenek708af042009-02-05 06:50:21 +00001686 leakWithinFunction(0), leakAtReturn(0), BR(0) {}
Ted Kremenek1feab292008-04-16 04:28:53 +00001687
Ted Kremenek708af042009-02-05 06:50:21 +00001688 virtual ~CFRefCount() {}
Ted Kremenek7d421f32008-04-09 23:49:11 +00001689
Ted Kremenekbf6babf2009-02-04 23:49:09 +00001690 void RegisterChecks(BugReporter &BR);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001691
Ted Kremenekb0f2b9e2008-08-16 00:49:49 +00001692 virtual void RegisterPrinters(std::vector<GRState::Printer*>& Printers) {
1693 Printers.push_back(new BindingsPrinter());
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001694 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00001695
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001696 bool isGCEnabled() const { return Summaries.isGCEnabled(); }
Ted Kremenekfe30beb2008-04-30 23:47:44 +00001697 const LangOptions& getLangOptions() const { return LOpts; }
1698
Ted Kremenekc26c4692009-02-18 03:48:14 +00001699 const RetainSummary *getSummaryOfNode(const ExplodedNode<GRState> *N) const {
1700 SummaryLogTy::const_iterator I = SummaryLog.find(N);
1701 return I == SummaryLog.end() ? 0 : I->second;
1702 }
1703
Ted Kremeneka7338b42008-03-11 06:39:11 +00001704 // Calls.
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001705
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001706 void EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001707 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001708 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001709 Expr* Ex,
1710 Expr* Receiver,
1711 RetainSummary* Summ,
Ted Kremenek2719e982008-06-17 02:43:46 +00001712 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001713 ExplodedNode<GRState>* Pred);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001714
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001715 virtual void EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekce0767f2008-03-12 21:06:49 +00001716 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001717 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001718 CallExpr* CE, SVal L,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001719 ExplodedNode<GRState>* Pred);
Ted Kremenek10fe66d2008-04-09 01:10:13 +00001720
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001721
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001722 virtual void EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001723 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001724 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001725 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001726 ExplodedNode<GRState>* Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001727
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001728 bool EvalObjCMessageExprAux(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001729 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001730 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001731 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001732 ExplodedNode<GRState>* Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001733
Ted Kremeneka42be302009-02-14 01:43:44 +00001734 // Stores.
1735 virtual void EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val);
1736
Ted Kremenekffefc352008-04-11 22:25:11 +00001737 // End-of-path.
1738
1739 virtual void EvalEndPath(GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001740 GREndPathNodeBuilder<GRState>& Builder);
Ted Kremenekffefc352008-04-11 22:25:11 +00001741
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001742 virtual void EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek541db372008-04-24 23:57:27 +00001743 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001744 GRStmtNodeBuilder<GRState>& Builder,
1745 ExplodedNode<GRState>* Pred,
Ted Kremenek5c0729b2009-01-21 22:26:05 +00001746 Stmt* S, const GRState* state,
1747 SymbolReaper& SymReaper);
1748
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001749 // Return statements.
1750
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001751 virtual void EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001752 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001753 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001754 ReturnStmt* S,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001755 ExplodedNode<GRState>* Pred);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001756
1757 // Assumptions.
1758
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001759 virtual const GRState* EvalAssume(GRStateManager& VMgr,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001760 const GRState* St, SVal Cond,
Ted Kremenekf22f8682008-07-10 22:03:41 +00001761 bool Assumption, bool& isFeasible);
Ted Kremeneka7338b42008-03-11 06:39:11 +00001762};
1763
1764} // end anonymous namespace
1765
Ted Kremenek681fb352009-03-20 17:34:15 +00001766static void PrintPool(std::ostream &Out, SymbolRef Sym, const GRState *state) {
1767 Out << ' ';
Ted Kremenek74556a12009-03-26 03:35:11 +00001768 if (Sym)
1769 Out << Sym->getSymbolID();
Ted Kremenek681fb352009-03-20 17:34:15 +00001770 else
1771 Out << "<pool>";
1772 Out << ":{";
1773
1774 // Get the contents of the pool.
1775 if (const ARCounts *cnts = state->get<AutoreleasePoolContents>(Sym))
1776 for (ARCounts::iterator J=cnts->begin(), EJ=cnts->end(); J != EJ; ++J)
1777 Out << '(' << J.getKey() << ',' << J.getData() << ')';
1778
1779 Out << '}';
1780}
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001781
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001782void CFRefCount::BindingsPrinter::Print(std::ostream& Out, const GRState* state,
1783 const char* nl, const char* sep) {
Ted Kremenek681fb352009-03-20 17:34:15 +00001784
1785
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001786
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001787 RefBindings B = state->get<RefBindings>();
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001788
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001789 if (!B.isEmpty())
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001790 Out << sep << nl;
1791
1792 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
1793 Out << (*I).first << " : ";
1794 (*I).second.print(Out);
1795 Out << nl;
1796 }
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001797
1798 // Print the autorelease stack.
Ted Kremenek681fb352009-03-20 17:34:15 +00001799 Out << sep << nl << "AR pool stack:";
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001800 ARStack stack = state->get<AutoreleaseStack>();
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001801
Ted Kremenek681fb352009-03-20 17:34:15 +00001802 PrintPool(Out, SymbolRef(), state); // Print the caller's pool.
1803 for (ARStack::iterator I=stack.begin(), E=stack.end(); I!=E; ++I)
1804 PrintPool(Out, *I, state);
1805
1806 Out << nl;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001807}
1808
Ted Kremenek47a72422009-04-29 18:50:19 +00001809//===----------------------------------------------------------------------===//
1810// Error reporting.
1811//===----------------------------------------------------------------------===//
1812
1813namespace {
1814
1815 //===-------------===//
1816 // Bug Descriptions. //
1817 //===-------------===//
1818
1819 class VISIBILITY_HIDDEN CFRefBug : public BugType {
1820 protected:
1821 CFRefCount& TF;
1822
1823 CFRefBug(CFRefCount* tf, const char* name)
1824 : BugType(name, "Memory (Core Foundation/Objective-C)"), TF(*tf) {}
1825 public:
1826
1827 CFRefCount& getTF() { return TF; }
1828 const CFRefCount& getTF() const { return TF; }
1829
1830 // FIXME: Eventually remove.
1831 virtual const char* getDescription() const = 0;
1832
1833 virtual bool isLeak() const { return false; }
1834 };
1835
1836 class VISIBILITY_HIDDEN UseAfterRelease : public CFRefBug {
1837 public:
1838 UseAfterRelease(CFRefCount* tf)
1839 : CFRefBug(tf, "Use-after-release") {}
1840
1841 const char* getDescription() const {
1842 return "Reference-counted object is used after it is released";
1843 }
1844 };
1845
1846 class VISIBILITY_HIDDEN BadRelease : public CFRefBug {
1847 public:
1848 BadRelease(CFRefCount* tf) : CFRefBug(tf, "Bad release") {}
1849
1850 const char* getDescription() const {
1851 return "Incorrect decrement of the reference count of an "
1852 "object is not owned at this point by the caller";
1853 }
1854 };
1855
1856 class VISIBILITY_HIDDEN DeallocGC : public CFRefBug {
1857 public:
1858 DeallocGC(CFRefCount *tf) : CFRefBug(tf,
1859 "-dealloc called while using GC") {}
1860
1861 const char *getDescription() const {
1862 return "-dealloc called while using GC";
1863 }
1864 };
1865
1866 class VISIBILITY_HIDDEN DeallocNotOwned : public CFRefBug {
1867 public:
1868 DeallocNotOwned(CFRefCount *tf) : CFRefBug(tf,
1869 "-dealloc sent to non-exclusively owned object") {}
1870
1871 const char *getDescription() const {
1872 return "-dealloc sent to object that may be referenced elsewhere";
1873 }
1874 };
1875
1876 class VISIBILITY_HIDDEN Leak : public CFRefBug {
1877 const bool isReturn;
1878 protected:
1879 Leak(CFRefCount* tf, const char* name, bool isRet)
1880 : CFRefBug(tf, name), isReturn(isRet) {}
1881 public:
1882
1883 const char* getDescription() const { return ""; }
1884
1885 bool isLeak() const { return true; }
1886 };
1887
1888 class VISIBILITY_HIDDEN LeakAtReturn : public Leak {
1889 public:
1890 LeakAtReturn(CFRefCount* tf, const char* name)
1891 : Leak(tf, name, true) {}
1892 };
1893
1894 class VISIBILITY_HIDDEN LeakWithinFunction : public Leak {
1895 public:
1896 LeakWithinFunction(CFRefCount* tf, const char* name)
1897 : Leak(tf, name, false) {}
1898 };
1899
1900 //===---------===//
1901 // Bug Reports. //
1902 //===---------===//
1903
1904 class VISIBILITY_HIDDEN CFRefReport : public RangedBugReport {
1905 protected:
1906 SymbolRef Sym;
1907 const CFRefCount &TF;
1908 public:
1909 CFRefReport(CFRefBug& D, const CFRefCount &tf,
1910 ExplodedNode<GRState> *n, SymbolRef sym)
1911 : RangedBugReport(D, D.getDescription(), n), Sym(sym), TF(tf) {}
1912
1913 virtual ~CFRefReport() {}
1914
1915 CFRefBug& getBugType() {
1916 return (CFRefBug&) RangedBugReport::getBugType();
1917 }
1918 const CFRefBug& getBugType() const {
1919 return (const CFRefBug&) RangedBugReport::getBugType();
1920 }
1921
1922 virtual void getRanges(BugReporter& BR, const SourceRange*& beg,
1923 const SourceRange*& end) {
1924
1925 if (!getBugType().isLeak())
1926 RangedBugReport::getRanges(BR, beg, end);
1927 else
1928 beg = end = 0;
1929 }
1930
1931 SymbolRef getSymbol() const { return Sym; }
1932
1933 PathDiagnosticPiece* getEndPath(BugReporter& BR,
1934 const ExplodedNode<GRState>* N);
1935
1936 std::pair<const char**,const char**> getExtraDescriptiveText();
1937
1938 PathDiagnosticPiece* VisitNode(const ExplodedNode<GRState>* N,
1939 const ExplodedNode<GRState>* PrevN,
1940 const ExplodedGraph<GRState>& G,
1941 BugReporter& BR,
1942 NodeResolver& NR);
1943 };
1944
1945 class VISIBILITY_HIDDEN CFRefLeakReport : public CFRefReport {
1946 SourceLocation AllocSite;
1947 const MemRegion* AllocBinding;
1948 public:
1949 CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
1950 ExplodedNode<GRState> *n, SymbolRef sym,
1951 GRExprEngine& Eng);
1952
1953 PathDiagnosticPiece* getEndPath(BugReporter& BR,
1954 const ExplodedNode<GRState>* N);
1955
1956 SourceLocation getLocation() const { return AllocSite; }
1957 };
1958} // end anonymous namespace
1959
1960void CFRefCount::RegisterChecks(BugReporter& BR) {
1961 useAfterRelease = new UseAfterRelease(this);
1962 BR.Register(useAfterRelease);
1963
1964 releaseNotOwned = new BadRelease(this);
1965 BR.Register(releaseNotOwned);
1966
1967 deallocGC = new DeallocGC(this);
1968 BR.Register(deallocGC);
1969
1970 deallocNotOwned = new DeallocNotOwned(this);
1971 BR.Register(deallocNotOwned);
1972
1973 // First register "return" leaks.
1974 const char* name = 0;
1975
1976 if (isGCEnabled())
1977 name = "Leak of returned object when using garbage collection";
1978 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
1979 name = "Leak of returned object when not using garbage collection (GC) in "
1980 "dual GC/non-GC code";
1981 else {
1982 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
1983 name = "Leak of returned object";
1984 }
1985
1986 leakAtReturn = new LeakAtReturn(this, name);
1987 BR.Register(leakAtReturn);
1988
1989 // Second, register leaks within a function/method.
1990 if (isGCEnabled())
1991 name = "Leak of object when using garbage collection";
1992 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
1993 name = "Leak of object when not using garbage collection (GC) in "
1994 "dual GC/non-GC code";
1995 else {
1996 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
1997 name = "Leak";
1998 }
1999
2000 leakWithinFunction = new LeakWithinFunction(this, name);
2001 BR.Register(leakWithinFunction);
2002
2003 // Save the reference to the BugReporter.
2004 this->BR = &BR;
2005}
2006
2007static const char* Msgs[] = {
2008 // GC only
2009 "Code is compiled to only use garbage collection",
2010 // No GC.
2011 "Code is compiled to use reference counts",
2012 // Hybrid, with GC.
2013 "Code is compiled to use either garbage collection (GC) or reference counts"
2014 " (non-GC). The bug occurs with GC enabled",
2015 // Hybrid, without GC
2016 "Code is compiled to use either garbage collection (GC) or reference counts"
2017 " (non-GC). The bug occurs in non-GC mode"
2018};
2019
2020std::pair<const char**,const char**> CFRefReport::getExtraDescriptiveText() {
2021 CFRefCount& TF = static_cast<CFRefBug&>(getBugType()).getTF();
2022
2023 switch (TF.getLangOptions().getGCMode()) {
2024 default:
2025 assert(false);
2026
2027 case LangOptions::GCOnly:
2028 assert (TF.isGCEnabled());
2029 return std::make_pair(&Msgs[0], &Msgs[0]+1);
2030
2031 case LangOptions::NonGC:
2032 assert (!TF.isGCEnabled());
2033 return std::make_pair(&Msgs[1], &Msgs[1]+1);
2034
2035 case LangOptions::HybridGC:
2036 if (TF.isGCEnabled())
2037 return std::make_pair(&Msgs[2], &Msgs[2]+1);
2038 else
2039 return std::make_pair(&Msgs[3], &Msgs[3]+1);
2040 }
2041}
2042
2043static inline bool contains(const llvm::SmallVectorImpl<ArgEffect>& V,
2044 ArgEffect X) {
2045 for (llvm::SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
2046 I!=E; ++I)
2047 if (*I == X) return true;
2048
2049 return false;
2050}
2051
2052PathDiagnosticPiece* CFRefReport::VisitNode(const ExplodedNode<GRState>* N,
2053 const ExplodedNode<GRState>* PrevN,
2054 const ExplodedGraph<GRState>& G,
2055 BugReporter& BR,
2056 NodeResolver& NR) {
2057
2058 // Check if the type state has changed.
2059 GRStateManager &StMgr = cast<GRBugReporter>(BR).getStateManager();
2060 GRStateRef PrevSt(PrevN->getState(), StMgr);
2061 GRStateRef CurrSt(N->getState(), StMgr);
2062
2063 const RefVal* CurrT = CurrSt.get<RefBindings>(Sym);
2064 if (!CurrT) return NULL;
2065
2066 const RefVal& CurrV = *CurrT;
2067 const RefVal* PrevT = PrevSt.get<RefBindings>(Sym);
2068
2069 // Create a string buffer to constain all the useful things we want
2070 // to tell the user.
2071 std::string sbuf;
2072 llvm::raw_string_ostream os(sbuf);
2073
2074 // This is the allocation site since the previous node had no bindings
2075 // for this symbol.
2076 if (!PrevT) {
2077 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2078
2079 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2080 // Get the name of the callee (if it is available).
2081 SVal X = CurrSt.GetSValAsScalarOrLoc(CE->getCallee());
2082 if (const FunctionDecl* FD = X.getAsFunctionDecl())
2083 os << "Call to function '" << FD->getNameAsString() <<'\'';
2084 else
2085 os << "function call";
2086 }
2087 else {
2088 assert (isa<ObjCMessageExpr>(S));
2089 os << "Method";
2090 }
2091
2092 if (CurrV.getObjKind() == RetEffect::CF) {
2093 os << " returns a Core Foundation object with a ";
2094 }
2095 else {
2096 assert (CurrV.getObjKind() == RetEffect::ObjC);
2097 os << " returns an Objective-C object with a ";
2098 }
2099
2100 if (CurrV.isOwned()) {
2101 os << "+1 retain count (owning reference).";
2102
2103 if (static_cast<CFRefBug&>(getBugType()).getTF().isGCEnabled()) {
2104 assert(CurrV.getObjKind() == RetEffect::CF);
2105 os << " "
2106 "Core Foundation objects are not automatically garbage collected.";
2107 }
2108 }
2109 else {
2110 assert (CurrV.isNotOwned());
2111 os << "+0 retain count (non-owning reference).";
2112 }
2113
2114 PathDiagnosticLocation Pos(S, BR.getContext().getSourceManager());
2115 return new PathDiagnosticEventPiece(Pos, os.str());
2116 }
2117
2118 // Gather up the effects that were performed on the object at this
2119 // program point
2120 llvm::SmallVector<ArgEffect, 2> AEffects;
2121
2122 if (const RetainSummary *Summ = TF.getSummaryOfNode(NR.getOriginalNode(N))) {
2123 // We only have summaries attached to nodes after evaluating CallExpr and
2124 // ObjCMessageExprs.
2125 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2126
2127 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2128 // Iterate through the parameter expressions and see if the symbol
2129 // was ever passed as an argument.
2130 unsigned i = 0;
2131
2132 for (CallExpr::arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
2133 AI!=AE; ++AI, ++i) {
2134
2135 // Retrieve the value of the argument. Is it the symbol
2136 // we are interested in?
2137 if (CurrSt.GetSValAsScalarOrLoc(*AI).getAsLocSymbol() != Sym)
2138 continue;
2139
2140 // We have an argument. Get the effect!
2141 AEffects.push_back(Summ->getArg(i));
2142 }
2143 }
2144 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
2145 if (Expr *receiver = ME->getReceiver())
2146 if (CurrSt.GetSValAsScalarOrLoc(receiver).getAsLocSymbol() == Sym) {
2147 // The symbol we are tracking is the receiver.
2148 AEffects.push_back(Summ->getReceiverEffect());
2149 }
2150 }
2151 }
2152
2153 do {
2154 // Get the previous type state.
2155 RefVal PrevV = *PrevT;
2156
2157 // Specially handle -dealloc.
2158 if (!TF.isGCEnabled() && contains(AEffects, Dealloc)) {
2159 // Determine if the object's reference count was pushed to zero.
2160 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2161 // We may not have transitioned to 'release' if we hit an error.
2162 // This case is handled elsewhere.
2163 if (CurrV.getKind() == RefVal::Released) {
2164 assert(CurrV.getCount() == 0);
2165 os << "Object released by directly sending the '-dealloc' message";
2166 break;
2167 }
2168 }
2169
2170 // Specially handle CFMakeCollectable and friends.
2171 if (contains(AEffects, MakeCollectable)) {
2172 // Get the name of the function.
2173 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2174 SVal X = CurrSt.GetSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee());
2175 const FunctionDecl* FD = X.getAsFunctionDecl();
2176 const std::string& FName = FD->getNameAsString();
2177
2178 if (TF.isGCEnabled()) {
2179 // Determine if the object's reference count was pushed to zero.
2180 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2181
2182 os << "In GC mode a call to '" << FName
2183 << "' decrements an object's retain count and registers the "
2184 "object with the garbage collector. ";
2185
2186 if (CurrV.getKind() == RefVal::Released) {
2187 assert(CurrV.getCount() == 0);
2188 os << "Since it now has a 0 retain count the object can be "
2189 "automatically collected by the garbage collector.";
2190 }
2191 else
2192 os << "An object must have a 0 retain count to be garbage collected. "
2193 "After this call its retain count is +" << CurrV.getCount()
2194 << '.';
2195 }
2196 else
2197 os << "When GC is not enabled a call to '" << FName
2198 << "' has no effect on its argument.";
2199
2200 // Nothing more to say.
2201 break;
2202 }
2203
2204 // Determine if the typestate has changed.
2205 if (!(PrevV == CurrV))
2206 switch (CurrV.getKind()) {
2207 case RefVal::Owned:
2208 case RefVal::NotOwned:
2209
2210 if (PrevV.getCount() == CurrV.getCount())
2211 return 0;
2212
2213 if (PrevV.getCount() > CurrV.getCount())
2214 os << "Reference count decremented.";
2215 else
2216 os << "Reference count incremented.";
2217
2218 if (unsigned Count = CurrV.getCount())
2219 os << " The object now has a +" << Count << " retain count.";
2220
2221 if (PrevV.getKind() == RefVal::Released) {
2222 assert(TF.isGCEnabled() && CurrV.getCount() > 0);
2223 os << " The object is not eligible for garbage collection until the "
2224 "retain count reaches 0 again.";
2225 }
2226
2227 break;
2228
2229 case RefVal::Released:
2230 os << "Object released.";
2231 break;
2232
2233 case RefVal::ReturnedOwned:
2234 os << "Object returned to caller as an owning reference (single retain "
2235 "count transferred to caller).";
2236 break;
2237
2238 case RefVal::ReturnedNotOwned:
2239 os << "Object returned to caller with a +0 (non-owning) retain count.";
2240 break;
2241
2242 default:
2243 return NULL;
2244 }
2245
2246 // Emit any remaining diagnostics for the argument effects (if any).
2247 for (llvm::SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
2248 E=AEffects.end(); I != E; ++I) {
2249
2250 // A bunch of things have alternate behavior under GC.
2251 if (TF.isGCEnabled())
2252 switch (*I) {
2253 default: break;
2254 case Autorelease:
2255 os << "In GC mode an 'autorelease' has no effect.";
2256 continue;
2257 case IncRefMsg:
2258 os << "In GC mode the 'retain' message has no effect.";
2259 continue;
2260 case DecRefMsg:
2261 os << "In GC mode the 'release' message has no effect.";
2262 continue;
2263 }
2264 }
2265 } while(0);
2266
2267 if (os.str().empty())
2268 return 0; // We have nothing to say!
2269
2270 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2271 PathDiagnosticLocation Pos(S, BR.getContext().getSourceManager());
2272 PathDiagnosticPiece* P = new PathDiagnosticEventPiece(Pos, os.str());
2273
2274 // Add the range by scanning the children of the statement for any bindings
2275 // to Sym.
2276 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I)
2277 if (Expr* Exp = dyn_cast_or_null<Expr>(*I))
2278 if (CurrSt.GetSValAsScalarOrLoc(Exp).getAsLocSymbol() == Sym) {
2279 P->addRange(Exp->getSourceRange());
2280 break;
2281 }
2282
2283 return P;
2284}
2285
2286namespace {
2287 class VISIBILITY_HIDDEN FindUniqueBinding :
2288 public StoreManager::BindingsHandler {
2289 SymbolRef Sym;
2290 const MemRegion* Binding;
2291 bool First;
2292
2293 public:
2294 FindUniqueBinding(SymbolRef sym) : Sym(sym), Binding(0), First(true) {}
2295
2296 bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
2297 SVal val) {
2298
2299 SymbolRef SymV = val.getAsSymbol();
2300 if (!SymV || SymV != Sym)
2301 return true;
2302
2303 if (Binding) {
2304 First = false;
2305 return false;
2306 }
2307 else
2308 Binding = R;
2309
2310 return true;
2311 }
2312
2313 operator bool() { return First && Binding; }
2314 const MemRegion* getRegion() { return Binding; }
2315 };
2316}
2317
2318static std::pair<const ExplodedNode<GRState>*,const MemRegion*>
2319GetAllocationSite(GRStateManager& StateMgr, const ExplodedNode<GRState>* N,
2320 SymbolRef Sym) {
2321
2322 // Find both first node that referred to the tracked symbol and the
2323 // memory location that value was store to.
2324 const ExplodedNode<GRState>* Last = N;
2325 const MemRegion* FirstBinding = 0;
2326
2327 while (N) {
2328 const GRState* St = N->getState();
2329 RefBindings B = St->get<RefBindings>();
2330
2331 if (!B.lookup(Sym))
2332 break;
2333
2334 FindUniqueBinding FB(Sym);
2335 StateMgr.iterBindings(St, FB);
2336 if (FB) FirstBinding = FB.getRegion();
2337
2338 Last = N;
2339 N = N->pred_empty() ? NULL : *(N->pred_begin());
2340 }
2341
2342 return std::make_pair(Last, FirstBinding);
2343}
2344
2345PathDiagnosticPiece*
2346CFRefReport::getEndPath(BugReporter& br, const ExplodedNode<GRState>* EndN) {
2347 // Tell the BugReporter to report cases when the tracked symbol is
2348 // assigned to different variables, etc.
2349 GRBugReporter& BR = cast<GRBugReporter>(br);
2350 cast<GRBugReporter>(BR).addNotableSymbol(Sym);
2351 return RangedBugReport::getEndPath(BR, EndN);
2352}
2353
2354PathDiagnosticPiece*
2355CFRefLeakReport::getEndPath(BugReporter& br, const ExplodedNode<GRState>* EndN){
2356
2357 GRBugReporter& BR = cast<GRBugReporter>(br);
2358 // Tell the BugReporter to report cases when the tracked symbol is
2359 // assigned to different variables, etc.
2360 cast<GRBugReporter>(BR).addNotableSymbol(Sym);
2361
2362 // We are reporting a leak. Walk up the graph to get to the first node where
2363 // the symbol appeared, and also get the first VarDecl that tracked object
2364 // is stored to.
2365 const ExplodedNode<GRState>* AllocNode = 0;
2366 const MemRegion* FirstBinding = 0;
2367
2368 llvm::tie(AllocNode, FirstBinding) =
2369 GetAllocationSite(BR.getStateManager(), EndN, Sym);
2370
2371 // Get the allocate site.
2372 assert(AllocNode);
2373 Stmt* FirstStmt = cast<PostStmt>(AllocNode->getLocation()).getStmt();
2374
2375 SourceManager& SMgr = BR.getContext().getSourceManager();
2376 unsigned AllocLine =SMgr.getInstantiationLineNumber(FirstStmt->getLocStart());
2377
2378 // Compute an actual location for the leak. Sometimes a leak doesn't
2379 // occur at an actual statement (e.g., transition between blocks; end
2380 // of function) so we need to walk the graph and compute a real location.
2381 const ExplodedNode<GRState>* LeakN = EndN;
2382 PathDiagnosticLocation L;
2383
2384 while (LeakN) {
2385 ProgramPoint P = LeakN->getLocation();
2386
2387 if (const PostStmt *PS = dyn_cast<PostStmt>(&P)) {
2388 L = PathDiagnosticLocation(PS->getStmt()->getLocStart(), SMgr);
2389 break;
2390 }
2391 else if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
2392 if (const Stmt* Term = BE->getSrc()->getTerminator()) {
2393 L = PathDiagnosticLocation(Term->getLocStart(), SMgr);
2394 break;
2395 }
2396 }
2397
2398 LeakN = LeakN->succ_empty() ? 0 : *(LeakN->succ_begin());
2399 }
2400
2401 if (!L.isValid()) {
Ted Kremenek0a6913d2009-04-29 21:31:59 +00002402 const Decl &D = BR.getStateManager().getCodeDecl();
2403 L = PathDiagnosticLocation(D.getBodyRBrace(BR.getContext()), SMgr);
Ted Kremenek47a72422009-04-29 18:50:19 +00002404 }
2405
2406 std::string sbuf;
2407 llvm::raw_string_ostream os(sbuf);
2408
2409 os << "Object allocated on line " << AllocLine;
2410
2411 if (FirstBinding)
2412 os << " and stored into '" << FirstBinding->getString() << '\'';
2413
2414 // Get the retain count.
2415 const RefVal* RV = EndN->getState()->get<RefBindings>(Sym);
2416
2417 if (RV->getKind() == RefVal::ErrorLeakReturned) {
2418 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
2419 // ojbects. Only "copy", "alloc", "retain" and "new" transfer ownership
2420 // to the caller for NS objects.
2421 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(BR.getGraph().getCodeDecl());
2422 os << " is returned from a method whose name ('"
Ted Kremenek314b1952009-04-29 23:03:22 +00002423 << MD.getSelector().getAsString()
Ted Kremenek47a72422009-04-29 18:50:19 +00002424 << "') does not contain 'copy' or otherwise starts with"
2425 " 'new' or 'alloc'. This violates the naming convention rules given"
Ted Kremenek2a410c92009-04-29 22:25:52 +00002426 " in the Memory Management Guide for Cocoa (object leaked)";
Ted Kremenek47a72422009-04-29 18:50:19 +00002427 }
2428 else
2429 os << " is no longer referenced after this point and has a retain count of"
Ted Kremenek2a410c92009-04-29 22:25:52 +00002430 " +" << RV->getCount() << " (object leaked)";
Ted Kremenek47a72422009-04-29 18:50:19 +00002431
2432 return new PathDiagnosticEventPiece(L, os.str());
2433}
2434
2435
2436CFRefLeakReport::CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2437 ExplodedNode<GRState> *n,
2438 SymbolRef sym, GRExprEngine& Eng)
2439: CFRefReport(D, tf, n, sym)
2440{
2441
2442 // Most bug reports are cached at the location where they occured.
2443 // With leaks, we want to unique them by the location where they were
2444 // allocated, and only report a single path. To do this, we need to find
2445 // the allocation site of a piece of tracked memory, which we do via a
2446 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2447 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2448 // that all ancestor nodes that represent the allocation site have the
2449 // same SourceLocation.
2450 const ExplodedNode<GRState>* AllocNode = 0;
2451
2452 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding.
2453 GetAllocationSite(Eng.getStateManager(), getEndNode(), getSymbol());
2454
2455 // Get the SourceLocation for the allocation site.
2456 ProgramPoint P = AllocNode->getLocation();
2457 AllocSite = cast<PostStmt>(P).getStmt()->getLocStart();
2458
2459 // Fill in the description of the bug.
2460 Description.clear();
2461 llvm::raw_string_ostream os(Description);
2462 SourceManager& SMgr = Eng.getContext().getSourceManager();
2463 unsigned AllocLine = SMgr.getInstantiationLineNumber(AllocSite);
Ted Kremenek2e9d0302009-05-02 19:05:19 +00002464 os << "Potential leak ";
2465 if (tf.isGCEnabled()) {
2466 os << "(when using garbage collection) ";
2467 }
2468 os << "of an object allocated on line " << AllocLine;
Ted Kremenek47a72422009-04-29 18:50:19 +00002469
2470 // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2471 if (AllocBinding)
2472 os << " and stored into '" << AllocBinding->getString() << '\'';
2473}
2474
2475//===----------------------------------------------------------------------===//
2476// Main checker logic.
2477//===----------------------------------------------------------------------===//
2478
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002479static inline ArgEffect GetArgE(RetainSummary* Summ, unsigned idx) {
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00002480 return Summ ? Summ->getArg(idx) : MayEscape;
Ted Kremenek455dd862008-04-11 20:23:24 +00002481}
2482
Ted Kremenek266d8b62008-05-06 02:26:56 +00002483static inline RetEffect GetRetEffect(RetainSummary* Summ) {
2484 return Summ ? Summ->getRetEffect() : RetEffect::MakeNoRet();
Ted Kremenek455dd862008-04-11 20:23:24 +00002485}
2486
Ted Kremenek227c5372008-05-06 02:41:27 +00002487static inline ArgEffect GetReceiverE(RetainSummary* Summ) {
2488 return Summ ? Summ->getReceiverEffect() : DoNothing;
2489}
2490
Ted Kremenekf2717b02008-07-18 17:24:20 +00002491static inline bool IsEndPath(RetainSummary* Summ) {
2492 return Summ ? Summ->isEndPath() : false;
2493}
2494
Ted Kremenek1feab292008-04-16 04:28:53 +00002495
Ted Kremenek272aa852008-06-25 21:21:56 +00002496/// GetReturnType - Used to get the return type of a message expression or
2497/// function call with the intention of affixing that type to a tracked symbol.
2498/// While the the return type can be queried directly from RetEx, when
2499/// invoking class methods we augment to the return type to be that of
2500/// a pointer to the class (as opposed it just being id).
2501static QualType GetReturnType(Expr* RetE, ASTContext& Ctx) {
2502
2503 QualType RetTy = RetE->getType();
2504
2505 // FIXME: We aren't handling id<...>.
Chris Lattnerb724ab22008-07-26 22:36:27 +00002506 const PointerType* PT = RetTy->getAsPointerType();
Ted Kremenek272aa852008-06-25 21:21:56 +00002507 if (!PT)
2508 return RetTy;
2509
2510 // If RetEx is not a message expression just return its type.
2511 // If RetEx is a message expression, return its types if it is something
2512 /// more specific than id.
2513
2514 ObjCMessageExpr* ME = dyn_cast<ObjCMessageExpr>(RetE);
2515
Steve Naroff17c03822009-02-12 17:52:19 +00002516 if (!ME || !Ctx.isObjCIdStructType(PT->getPointeeType()))
Ted Kremenek272aa852008-06-25 21:21:56 +00002517 return RetTy;
2518
2519 ObjCInterfaceDecl* D = ME->getClassInfo().first;
2520
2521 // At this point we know the return type of the message expression is id.
2522 // If we have an ObjCInterceDecl, we know this is a call to a class method
2523 // whose type we can resolve. In such cases, promote the return type to
2524 // Class*.
2525 return !D ? RetTy : Ctx.getPointerType(Ctx.getObjCInterfaceType(D));
2526}
2527
2528
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002529void CFRefCount::EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002530 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002531 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002532 Expr* Ex,
2533 Expr* Receiver,
2534 RetainSummary* Summ,
Zhongxing Xucac107a2009-04-20 05:24:46 +00002535 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002536 ExplodedNode<GRState>* Pred) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002537
Ted Kremeneka7338b42008-03-11 06:39:11 +00002538 // Get the state.
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002539 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenek0106e202008-10-24 20:32:50 +00002540 ASTContext& Ctx = Eng.getStateManager().getContext();
Ted Kremenek227c5372008-05-06 02:41:27 +00002541
2542 // Evaluate the effect of the arguments.
Ted Kremenek1feab292008-04-16 04:28:53 +00002543 RefVal::Kind hasErr = (RefVal::Kind) 0;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002544 unsigned idx = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002545 Expr* ErrorExpr = NULL;
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002546 SymbolRef ErrorSym = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002547
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002548 for (ExprIterator I = arg_beg; I != arg_end; ++I, ++idx) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002549 SVal V = state.GetSValAsScalarOrLoc(*I);
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002550 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002551
Ted Kremenek74556a12009-03-26 03:35:11 +00002552 if (Sym)
Ted Kremenekb6578942009-02-24 19:15:11 +00002553 if (RefBindings::data_type* T = state.get<RefBindings>(Sym)) {
2554 state = Update(state, Sym, *T, GetArgE(Summ, idx), hasErr);
2555 if (hasErr) {
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002556 ErrorExpr = *I;
Ted Kremenek6064a362008-07-07 16:21:19 +00002557 ErrorSym = Sym;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002558 break;
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002559 }
2560 continue;
Ted Kremenekb6578942009-02-24 19:15:11 +00002561 }
Ted Kremenekede40b72008-07-09 18:11:16 +00002562
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002563 if (isa<Loc>(V)) {
2564 if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(&V)) {
Ted Kremenekede40b72008-07-09 18:11:16 +00002565 if (GetArgE(Summ, idx) == DoNothingByRef)
2566 continue;
2567
2568 // Invalidate the value of the variable passed by reference.
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002569
2570 // FIXME: Either this logic should also be replicated in GRSimpleVals
2571 // or should be pulled into a separate "constraint engine."
Ted Kremenekede40b72008-07-09 18:11:16 +00002572
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002573 // FIXME: We can have collisions on the conjured symbol if the
2574 // expression *I also creates conjured symbols. We probably want
2575 // to identify conjured symbols by an expression pair: the enclosing
2576 // expression (the context) and the expression itself. This should
Ted Kremenekede40b72008-07-09 18:11:16 +00002577 // disambiguate conjured symbols.
Ted Kremenekb15eba42008-10-04 05:50:14 +00002578
Ted Kremenek38a4b4b2008-10-17 20:28:54 +00002579 const TypedRegion* R = dyn_cast<TypedRegion>(MR->getRegion());
Zhongxing Xub9d47a42009-04-29 02:30:09 +00002580
Ted Kremenek53b24182009-03-04 22:56:43 +00002581 if (R) {
Ted Kremenek618c6cd2008-12-18 23:34:57 +00002582 // Is the invalidated variable something that we were tracking?
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002583 SymbolRef Sym = state.GetSValAsScalarOrLoc(R).getAsLocSymbol();
Ted Kremenek618c6cd2008-12-18 23:34:57 +00002584
Ted Kremenek53b24182009-03-04 22:56:43 +00002585 // Remove any existing reference-count binding.
Ted Kremenek74556a12009-03-26 03:35:11 +00002586 if (Sym) state = state.remove<RefBindings>(Sym);
Ted Kremenekb15eba42008-10-04 05:50:14 +00002587
Ted Kremenek53b24182009-03-04 22:56:43 +00002588 if (R->isBoundable(Ctx)) {
2589 // Set the value of the variable to be a conjured symbol.
2590 unsigned Count = Builder.getCurrentBlockCount();
2591 QualType T = R->getRValueType(Ctx);
2592
Zhongxing Xu079dc352009-04-09 06:03:54 +00002593 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())){
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002594 ValueManager &ValMgr = Eng.getValueManager();
2595 SVal V = ValMgr.getConjuredSymbolVal(*I, T, Count);
Zhongxing Xu079dc352009-04-09 06:03:54 +00002596 state = state.BindLoc(Loc::MakeVal(R), V);
Ted Kremenek53b24182009-03-04 22:56:43 +00002597 }
2598 else if (const RecordType *RT = T->getAsStructureType()) {
2599 // Handle structs in a not so awesome way. Here we just
2600 // eagerly bind new symbols to the fields. In reality we
2601 // should have the store manager handle this. The idea is just
2602 // to prototype some basic functionality here. All of this logic
2603 // should one day soon just go away.
2604 const RecordDecl *RD = RT->getDecl()->getDefinition(Ctx);
2605
2606 // No record definition. There is nothing we can do.
2607 if (!RD)
2608 continue;
2609
2610 MemRegionManager &MRMgr = state.getManager().getRegionManager();
2611
2612 // Iterate through the fields and construct new symbols.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002613 for (RecordDecl::field_iterator FI=RD->field_begin(Ctx),
2614 FE=RD->field_end(Ctx); FI!=FE; ++FI) {
Ted Kremenek53b24182009-03-04 22:56:43 +00002615
2616 // For now just handle scalar fields.
2617 FieldDecl *FD = *FI;
2618 QualType FT = FD->getType();
2619
2620 if (Loc::IsLocType(FT) ||
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002621 (FT->isIntegerType() && FT->isScalarType())) {
Ted Kremenek53b24182009-03-04 22:56:43 +00002622 const FieldRegion* FR = MRMgr.getFieldRegion(FD, R);
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002623 ValueManager &ValMgr = Eng.getValueManager();
2624 SVal V = ValMgr.getConjuredSymbolVal(*I, FT, Count);
Zhongxing Xuc458e322009-04-09 06:32:20 +00002625 state = state.BindLoc(Loc::MakeVal(FR), V);
Ted Kremenek53b24182009-03-04 22:56:43 +00002626 }
2627 }
2628 }
2629 else {
2630 // Just blast away other values.
2631 state = state.BindLoc(*MR, UnknownVal());
2632 }
Ted Kremenek8f90e712008-10-17 22:23:12 +00002633 }
Ted Kremenekb15eba42008-10-04 05:50:14 +00002634 }
2635 else
Ted Kremenek09102db2008-11-12 19:22:09 +00002636 state = state.BindLoc(*MR, UnknownVal());
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002637 }
2638 else {
2639 // Nuke all other arguments passed by reference.
Zhongxing Xu097fc982008-10-17 05:57:07 +00002640 state = state.Unbind(cast<Loc>(V));
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002641 }
Ted Kremeneke4924202008-04-11 20:51:02 +00002642 }
Zhongxing Xu097fc982008-10-17 05:57:07 +00002643 else if (isa<nonloc::LocAsInteger>(V))
2644 state = state.Unbind(cast<nonloc::LocAsInteger>(V).getLoc());
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002645 }
Ted Kremenek1feab292008-04-16 04:28:53 +00002646
Ted Kremenek272aa852008-06-25 21:21:56 +00002647 // Evaluate the effect on the message receiver.
Ted Kremenek227c5372008-05-06 02:41:27 +00002648 if (!ErrorExpr && Receiver) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002649 SymbolRef Sym = state.GetSValAsScalarOrLoc(Receiver).getAsLocSymbol();
Ted Kremenek74556a12009-03-26 03:35:11 +00002650 if (Sym) {
Ted Kremenekb6578942009-02-24 19:15:11 +00002651 if (const RefVal* T = state.get<RefBindings>(Sym)) {
2652 state = Update(state, Sym, *T, GetReceiverE(Summ), hasErr);
2653 if (hasErr) {
Ted Kremenek227c5372008-05-06 02:41:27 +00002654 ErrorExpr = Receiver;
Ted Kremenek6064a362008-07-07 16:21:19 +00002655 ErrorSym = Sym;
Ted Kremenek227c5372008-05-06 02:41:27 +00002656 }
Ted Kremenekb6578942009-02-24 19:15:11 +00002657 }
Ted Kremenek227c5372008-05-06 02:41:27 +00002658 }
2659 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002660
Ted Kremenek272aa852008-06-25 21:21:56 +00002661 // Process any errors.
Ted Kremenek1feab292008-04-16 04:28:53 +00002662 if (hasErr) {
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002663 ProcessNonLeakError(Dst, Builder, Ex, ErrorExpr, Pred, state,
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002664 hasErr, ErrorSym);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002665 return;
Ted Kremenek0d721572008-03-11 17:48:22 +00002666 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002667
Ted Kremenekf2717b02008-07-18 17:24:20 +00002668 // Consult the summary for the return value.
Ted Kremenek266d8b62008-05-06 02:26:56 +00002669 RetEffect RE = GetRetEffect(Summ);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002670
2671 switch (RE.getKind()) {
2672 default:
2673 assert (false && "Unhandled RetEffect."); break;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002674
Ted Kremenek8f90e712008-10-17 22:23:12 +00002675 case RetEffect::NoRet: {
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002676
Ted Kremenek455dd862008-04-11 20:23:24 +00002677 // Make up a symbol for the return value (not reference counted).
Ted Kremeneke4924202008-04-11 20:51:02 +00002678 // FIXME: This is basically copy-and-paste from GRSimpleVals. We
2679 // should compose behavior, not copy it.
Ted Kremenek455dd862008-04-11 20:23:24 +00002680
Ted Kremenek8f90e712008-10-17 22:23:12 +00002681 // FIXME: We eventually should handle structs and other compound types
2682 // that are returned by value.
2683
2684 QualType T = Ex->getType();
2685
Ted Kremenek79413a52008-11-13 06:10:40 +00002686 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())) {
Ted Kremenek455dd862008-04-11 20:23:24 +00002687 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002688 ValueManager &ValMgr = Eng.getValueManager();
2689 SVal X = ValMgr.getConjuredSymbolVal(Ex, T, Count);
Ted Kremenek09102db2008-11-12 19:22:09 +00002690 state = state.BindExpr(Ex, X, false);
Ted Kremenek455dd862008-04-11 20:23:24 +00002691 }
2692
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002693 break;
Ted Kremenek8f90e712008-10-17 22:23:12 +00002694 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002695
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002696 case RetEffect::Alias: {
Ted Kremenek272aa852008-06-25 21:21:56 +00002697 unsigned idx = RE.getIndex();
Ted Kremenek2719e982008-06-17 02:43:46 +00002698 assert (arg_end >= arg_beg);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002699 assert (idx < (unsigned) (arg_end - arg_beg));
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002700 SVal V = state.GetSValAsScalarOrLoc(*(arg_beg+idx));
Ted Kremenek09102db2008-11-12 19:22:09 +00002701 state = state.BindExpr(Ex, V, false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002702 break;
2703 }
2704
Ted Kremenek227c5372008-05-06 02:41:27 +00002705 case RetEffect::ReceiverAlias: {
2706 assert (Receiver);
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002707 SVal V = state.GetSValAsScalarOrLoc(Receiver);
Ted Kremenek09102db2008-11-12 19:22:09 +00002708 state = state.BindExpr(Ex, V, false);
Ted Kremenek227c5372008-05-06 02:41:27 +00002709 break;
2710 }
2711
Ted Kremenek6a1cc252008-06-23 18:02:52 +00002712 case RetEffect::OwnedAllocatedSymbol:
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002713 case RetEffect::OwnedSymbol: {
2714 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke9e726e2009-04-09 16:13:17 +00002715 ValueManager &ValMgr = Eng.getValueManager();
2716 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
2717 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
2718 state = state.set<RefBindings>(Sym, RefVal::makeOwned(RE.getObjKind(),
2719 RetT));
2720 state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenek45c52a12009-03-09 22:46:49 +00002721
2722 // FIXME: Add a flag to the checker where allocations are assumed to
2723 // *not fail.
2724#if 0
Ted Kremeneke62fd052009-01-28 22:27:59 +00002725 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) {
2726 bool isFeasible;
2727 state = state.Assume(loc::SymbolVal(Sym), true, isFeasible);
2728 assert(isFeasible && "Cannot assume fresh symbol is non-null.");
2729 }
Ted Kremenek45c52a12009-03-09 22:46:49 +00002730#endif
Ted Kremenek6a1cc252008-06-23 18:02:52 +00002731
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002732 break;
2733 }
Ted Kremenek382fb4e2009-04-27 19:14:45 +00002734
2735 case RetEffect::GCNotOwnedSymbol:
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002736 case RetEffect::NotOwnedSymbol: {
2737 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke9e726e2009-04-09 16:13:17 +00002738 ValueManager &ValMgr = Eng.getValueManager();
2739 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
2740 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
2741 state = state.set<RefBindings>(Sym, RefVal::makeNotOwned(RE.getObjKind(),
2742 RetT));
2743 state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002744 break;
2745 }
2746 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002747
Ted Kremenek0dd65012009-02-18 02:00:25 +00002748 // Generate a sink node if we are at the end of a path.
2749 GRExprEngine::NodeTy *NewNode =
2750 IsEndPath(Summ) ? Builder.MakeSinkNode(Dst, Ex, Pred, state)
2751 : Builder.MakeNode(Dst, Ex, Pred, state);
2752
2753 // Annotate the edge with summary we used.
2754 // FIXME: This assumes that we always use the same summary when generating
2755 // this node.
2756 if (NewNode) SummaryLog[NewNode] = Summ;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002757}
2758
2759
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002760void CFRefCount::EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002761 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002762 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu097fc982008-10-17 05:57:07 +00002763 CallExpr* CE, SVal L,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002764 ExplodedNode<GRState>* Pred) {
Zhongxing Xucac107a2009-04-20 05:24:46 +00002765 const FunctionDecl* FD = L.getAsFunctionDecl();
2766 RetainSummary* Summ = !FD ? 0
2767 : Summaries.getSummary(const_cast<FunctionDecl*>(FD));
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002768
2769 EvalSummary(Dst, Eng, Builder, CE, 0, Summ,
2770 CE->arg_begin(), CE->arg_end(), Pred);
Ted Kremenek827f93b2008-03-06 00:08:09 +00002771}
Ted Kremeneka7338b42008-03-11 06:39:11 +00002772
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002773void CFRefCount::EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002774 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002775 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002776 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002777 ExplodedNode<GRState>* Pred) {
Ted Kremenek926abf22008-05-06 04:20:12 +00002778 RetainSummary* Summ;
Ted Kremenek33661802008-05-01 21:31:50 +00002779
Ted Kremenek272aa852008-06-25 21:21:56 +00002780 if (Expr* Receiver = ME->getReceiver()) {
2781 // We need the type-information of the tracked receiver object
2782 // Retrieve it from the state.
2783 ObjCInterfaceDecl* ID = 0;
2784
2785 // FIXME: Wouldn't it be great if this code could be reduced? It's just
2786 // a chain of lookups.
Ted Kremeneka821b792009-04-29 05:04:30 +00002787 // FIXME: Is this really working as expected? There are cases where
2788 // we just use the 'ID' from the message expression.
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002789 const GRState* St = Builder.GetState(Pred);
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002790 SVal V = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
Ted Kremenek272aa852008-06-25 21:21:56 +00002791
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002792 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenek74556a12009-03-26 03:35:11 +00002793 if (Sym) {
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002794 if (const RefVal* T = St->get<RefBindings>(Sym)) {
Ted Kremenek6064a362008-07-07 16:21:19 +00002795 QualType Ty = T->getType();
Ted Kremenek272aa852008-06-25 21:21:56 +00002796
2797 if (const PointerType* PT = Ty->getAsPointerType()) {
2798 QualType PointeeTy = PT->getPointeeType();
2799
2800 if (ObjCInterfaceType* IT = dyn_cast<ObjCInterfaceType>(PointeeTy))
2801 ID = IT->getDecl();
2802 }
2803 }
2804 }
2805
Ted Kremenek04e00302009-04-29 17:09:14 +00002806 // FIXME: The receiver could be a reference to a class, meaning that
2807 // we should use the class method.
2808 Summ = Summaries.getInstanceMethodSummary(ME, ID);
Ted Kremenek0106e202008-10-24 20:32:50 +00002809
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002810 // Special-case: are we sending a mesage to "self"?
2811 // This is a hack. When we have full-IP this should be removed.
2812 if (!Summ) {
2813 ObjCMethodDecl* MD =
2814 dyn_cast<ObjCMethodDecl>(&Eng.getGraph().getCodeDecl());
2815
2816 if (MD) {
2817 if (Expr* Receiver = ME->getReceiver()) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002818 SVal X = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002819 if (loc::MemRegionVal* L = dyn_cast<loc::MemRegionVal>(&X))
Ted Kremenek0106e202008-10-24 20:32:50 +00002820 if (L->getRegion() == Eng.getStateManager().getSelfRegion(St)) {
2821 // Create a summmary where all of the arguments "StopTracking".
2822 Summ = Summaries.getPersistentSummary(RetEffect::MakeNoRet(),
2823 DoNothing,
2824 StopTracking);
2825 }
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002826 }
2827 }
2828 }
Ted Kremenek272aa852008-06-25 21:21:56 +00002829 }
Ted Kremenek1feab292008-04-16 04:28:53 +00002830 else
Ted Kremenekb17fa952009-04-23 21:25:57 +00002831 Summ = Summaries.getClassMethodSummary(ME);
Ted Kremenek1feab292008-04-16 04:28:53 +00002832
Ted Kremenekccbe79a2009-04-24 17:50:11 +00002833
Ted Kremenek926abf22008-05-06 04:20:12 +00002834 EvalSummary(Dst, Eng, Builder, ME, ME->getReceiver(), Summ,
2835 ME->arg_begin(), ME->arg_end(), Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002836}
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002837
2838namespace {
2839class VISIBILITY_HIDDEN StopTrackingCallback : public SymbolVisitor {
2840 GRStateRef state;
2841public:
2842 StopTrackingCallback(GRStateRef st) : state(st) {}
2843 GRStateRef getState() { return state; }
2844
2845 bool VisitSymbol(SymbolRef sym) {
2846 state = state.remove<RefBindings>(sym);
2847 return true;
2848 }
Ted Kremenek926abf22008-05-06 04:20:12 +00002849
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002850 const GRState* getState() const { return state.getState(); }
2851};
2852} // end anonymous namespace
2853
2854
Ted Kremeneka42be302009-02-14 01:43:44 +00002855void CFRefCount::EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val) {
Ted Kremeneka42be302009-02-14 01:43:44 +00002856 // Are we storing to something that causes the value to "escape"?
Ted Kremenek7aef4842008-04-16 20:40:59 +00002857 bool escapes = false;
2858
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002859 // A value escapes in three possible cases (this may change):
2860 //
2861 // (1) we are binding to something that is not a memory region.
2862 // (2) we are binding to a memregion that does not have stack storage
2863 // (3) we are binding to a memregion with stack storage that the store
Ted Kremeneka42be302009-02-14 01:43:44 +00002864 // does not understand.
Ted Kremeneka42be302009-02-14 01:43:44 +00002865 GRStateRef state = B.getState();
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002866
Ted Kremeneka42be302009-02-14 01:43:44 +00002867 if (!isa<loc::MemRegionVal>(location))
Ted Kremenek7aef4842008-04-16 20:40:59 +00002868 escapes = true;
Ted Kremenekb15eba42008-10-04 05:50:14 +00002869 else {
Ted Kremeneka42be302009-02-14 01:43:44 +00002870 const MemRegion* R = cast<loc::MemRegionVal>(location).getRegion();
2871 escapes = !B.getStateManager().hasStackStorage(R);
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002872
2873 if (!escapes) {
2874 // To test (3), generate a new state with the binding removed. If it is
2875 // the same state, then it escapes (since the store cannot represent
2876 // the binding).
Ted Kremeneka42be302009-02-14 01:43:44 +00002877 escapes = (state == (state.BindLoc(cast<Loc>(location), UnknownVal())));
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002878 }
Ted Kremenekb15eba42008-10-04 05:50:14 +00002879 }
Ted Kremeneka42be302009-02-14 01:43:44 +00002880
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002881 // If our store can represent the binding and we aren't storing to something
2882 // that doesn't have local storage then just return and have the simulation
2883 // state continue as is.
2884 if (!escapes)
2885 return;
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002886
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002887 // Otherwise, find all symbols referenced by 'val' that we are tracking
2888 // and stop tracking them.
2889 B.MakeNode(state.scanReachableSymbols<StopTrackingCallback>(val).getState());
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002890}
2891
Ted Kremenek0106e202008-10-24 20:32:50 +00002892std::pair<GRStateRef,bool>
2893CFRefCount::HandleSymbolDeath(GRStateManager& VMgr,
2894 const GRState* St, const Decl* CD,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002895 SymbolRef sid,
Ted Kremenek0106e202008-10-24 20:32:50 +00002896 RefVal V, bool& hasLeak) {
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002897
Ted Kremenek47a72422009-04-29 18:50:19 +00002898 // Any remaining leaks?
Ted Kremenek311f3d42008-10-22 23:56:21 +00002899 hasLeak = V.isOwned() ||
2900 ((V.isNotOwned() || V.isReturnedOwned()) && V.getCount() > 0);
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002901
Ted Kremenek47a72422009-04-29 18:50:19 +00002902 GRStateRef state(St, VMgr);
2903
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002904 if (!hasLeak)
Ted Kremenek0106e202008-10-24 20:32:50 +00002905 return std::make_pair(state.remove<RefBindings>(sid), false);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002906
Ted Kremenek0106e202008-10-24 20:32:50 +00002907 return std::make_pair(state.set<RefBindings>(sid, V ^ RefVal::ErrorLeak),
2908 false);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002909}
2910
Ted Kremenek541db372008-04-24 23:57:27 +00002911
Ted Kremenekffefc352008-04-11 22:25:11 +00002912
Ted Kremenek541db372008-04-24 23:57:27 +00002913// Dead symbols.
2914
Ted Kremenek708af042009-02-05 06:50:21 +00002915
Ted Kremenek541db372008-04-24 23:57:27 +00002916
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002917 // Return statements.
2918
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002919void CFRefCount::EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002920 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002921 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002922 ReturnStmt* S,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002923 ExplodedNode<GRState>* Pred) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002924
2925 Expr* RetE = S->getRetValue();
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002926 if (!RetE)
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002927 return;
2928
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002929 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002930 SymbolRef Sym = state.GetSValAsScalarOrLoc(RetE).getAsLocSymbol();
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002931
Ted Kremenek74556a12009-03-26 03:35:11 +00002932 if (!Sym)
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002933 return;
2934
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002935 // Get the reference count binding (if any).
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002936 const RefVal* T = state.get<RefBindings>(Sym);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002937
2938 if (!T)
2939 return;
2940
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002941 // Change the reference count.
Ted Kremenek6064a362008-07-07 16:21:19 +00002942 RefVal X = *T;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002943
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002944 switch (X.getKind()) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002945 case RefVal::Owned: {
2946 unsigned cnt = X.getCount();
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00002947 assert (cnt > 0);
2948 X = RefVal::makeReturnedOwned(cnt - 1);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002949 break;
2950 }
2951
2952 case RefVal::NotOwned: {
2953 unsigned cnt = X.getCount();
2954 X = cnt ? RefVal::makeReturnedOwned(cnt - 1)
2955 : RefVal::makeReturnedNotOwned();
2956 break;
2957 }
2958
2959 default:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002960 return;
2961 }
2962
2963 // Update the binding.
Ted Kremenek91781202008-08-17 03:20:02 +00002964 state = state.set<RefBindings>(Sym, X);
Ted Kremenek47a72422009-04-29 18:50:19 +00002965 Pred = Builder.MakeNode(Dst, S, Pred, state);
2966
Ted Kremeneka208d0c2009-04-30 05:51:50 +00002967 // Did we cache out?
2968 if (!Pred)
2969 return;
2970
Ted Kremenek47a72422009-04-29 18:50:19 +00002971 // Any leaks or other errors?
2972 if (X.isReturnedOwned() && X.getCount() == 0) {
2973 const Decl *CD = &Eng.getStateManager().getCodeDecl();
2974
Ted Kremenek314b1952009-04-29 23:03:22 +00002975 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
2976 RetainSummary *Summ = Summaries.getMethodSummary(MD);
2977 if (!GetRetEffect(Summ).isOwned()) {
Ted Kremenek47a72422009-04-29 18:50:19 +00002978 static int ReturnOwnLeakTag = 0;
2979 state = state.set<RefBindings>(Sym, X ^ RefVal::ErrorLeakReturned);
Ted Kremenek47a72422009-04-29 18:50:19 +00002980 // Generate an error node.
Ted Kremeneka208d0c2009-04-30 05:51:50 +00002981 if (ExplodedNode<GRState> *N =
2982 Builder.generateNode(PostStmt(S, &ReturnOwnLeakTag), state, Pred)) {
2983 CFRefLeakReport *report =
2984 new CFRefLeakReport(*static_cast<CFRefBug*>(leakAtReturn), *this,
2985 N, Sym, Eng);
2986 BR->EmitReport(report);
2987 }
Ted Kremenek47a72422009-04-29 18:50:19 +00002988 }
2989 }
2990 }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002991}
2992
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002993// Assumptions.
2994
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002995const GRState* CFRefCount::EvalAssume(GRStateManager& VMgr,
2996 const GRState* St,
Zhongxing Xu097fc982008-10-17 05:57:07 +00002997 SVal Cond, bool Assumption,
Ted Kremenekf22f8682008-07-10 22:03:41 +00002998 bool& isFeasible) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002999
3000 // FIXME: We may add to the interface of EvalAssume the list of symbols
3001 // whose assumptions have changed. For now we just iterate through the
3002 // bindings and check if any of the tracked symbols are NULL. This isn't
3003 // too bad since the number of symbols we will track in practice are
3004 // probably small and EvalAssume is only called at branches and a few
3005 // other places.
Ted Kremenek4ae925c2008-08-14 21:16:54 +00003006 RefBindings B = St->get<RefBindings>();
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003007
3008 if (B.isEmpty())
3009 return St;
3010
3011 bool changed = false;
Ted Kremenek91781202008-08-17 03:20:02 +00003012
3013 GRStateRef state(St, VMgr);
3014 RefBindings::Factory& RefBFactory = state.get_context<RefBindings>();
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003015
3016 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003017 // Check if the symbol is null (or equal to any constant).
3018 // If this is the case, stop tracking the symbol.
Zhongxing Xuc6b27d02008-08-29 14:52:36 +00003019 if (VMgr.getSymVal(St, I.getKey())) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003020 changed = true;
3021 B = RefBFactory.Remove(B, I.getKey());
3022 }
3023 }
3024
Ted Kremenek91781202008-08-17 03:20:02 +00003025 if (changed)
3026 state = state.set<RefBindings>(B);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003027
Ted Kremenek4ae925c2008-08-14 21:16:54 +00003028 return state;
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003029}
Ted Kremeneka7338b42008-03-11 06:39:11 +00003030
Ted Kremenekb6578942009-02-24 19:15:11 +00003031GRStateRef CFRefCount::Update(GRStateRef state, SymbolRef sym,
3032 RefVal V, ArgEffect E,
3033 RefVal::Kind& hasErr) {
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003034
3035 // In GC mode [... release] and [... retain] do nothing.
3036 switch (E) {
3037 default: break;
3038 case IncRefMsg: E = isGCEnabled() ? DoNothing : IncRef; break;
3039 case DecRefMsg: E = isGCEnabled() ? DoNothing : DecRef; break;
Ted Kremenek2126bef2009-02-18 21:57:45 +00003040 case MakeCollectable: E = isGCEnabled() ? DecRef : DoNothing; break;
Ted Kremenekaac82832009-02-23 17:45:03 +00003041 case NewAutoreleasePool: E = isGCEnabled() ? DoNothing :
3042 NewAutoreleasePool; break;
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003043 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00003044
Ted Kremenek6537a642009-03-17 19:42:23 +00003045 // Handle all use-after-releases.
3046 if (!isGCEnabled() && V.getKind() == RefVal::Released) {
3047 V = V ^ RefVal::ErrorUseAfterRelease;
3048 hasErr = V.getKind();
3049 return state.set<RefBindings>(sym, V);
3050 }
3051
Ted Kremenek0d721572008-03-11 17:48:22 +00003052 switch (E) {
3053 default:
3054 assert (false && "Unhandled CFRef transition.");
Ted Kremenek6537a642009-03-17 19:42:23 +00003055
3056 case Dealloc:
3057 // Any use of -dealloc in GC is *bad*.
3058 if (isGCEnabled()) {
3059 V = V ^ RefVal::ErrorDeallocGC;
3060 hasErr = V.getKind();
3061 break;
3062 }
3063
3064 switch (V.getKind()) {
3065 default:
3066 assert(false && "Invalid case.");
3067 case RefVal::Owned:
3068 // The object immediately transitions to the released state.
3069 V = V ^ RefVal::Released;
3070 V.clearCounts();
3071 return state.set<RefBindings>(sym, V);
3072 case RefVal::NotOwned:
3073 V = V ^ RefVal::ErrorDeallocNotOwned;
3074 hasErr = V.getKind();
3075 break;
3076 }
3077 break;
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003078
Ted Kremenekb7826ab2009-02-25 23:11:49 +00003079 case NewAutoreleasePool:
3080 assert(!isGCEnabled());
3081 return state.add<AutoreleaseStack>(sym);
3082
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003083 case MayEscape:
3084 if (V.getKind() == RefVal::Owned) {
Ted Kremenek272aa852008-06-25 21:21:56 +00003085 V = V ^ RefVal::NotOwned;
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003086 break;
3087 }
Ted Kremenek6537a642009-03-17 19:42:23 +00003088
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003089 // Fall-through.
Ted Kremenek1b4b6562009-02-25 02:54:57 +00003090
Ted Kremenekede40b72008-07-09 18:11:16 +00003091 case DoNothingByRef:
Ted Kremenek0d721572008-03-11 17:48:22 +00003092 case DoNothing:
Ted Kremenekb6578942009-02-24 19:15:11 +00003093 return state;
Ted Kremeneke5a4bb02008-06-30 16:57:41 +00003094
Ted Kremenek9b112d22009-01-28 21:44:40 +00003095 case Autorelease:
Ted Kremenek6537a642009-03-17 19:42:23 +00003096 if (isGCEnabled())
3097 return state;
Ted Kremenek681fb352009-03-20 17:34:15 +00003098
3099 // Update the autorelease counts.
3100 state = SendAutorelease(state, ARCountFactory, sym);
Ted Kremenek6537a642009-03-17 19:42:23 +00003101
3102 // Fall-through.
3103
Ted Kremenek227c5372008-05-06 02:41:27 +00003104 case StopTracking:
Ted Kremenekb6578942009-02-24 19:15:11 +00003105 return state.remove<RefBindings>(sym);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003106
Ted Kremenek0d721572008-03-11 17:48:22 +00003107 case IncRef:
3108 switch (V.getKind()) {
3109 default:
3110 assert(false);
3111
3112 case RefVal::Owned:
Ted Kremenek0d721572008-03-11 17:48:22 +00003113 case RefVal::NotOwned:
Ted Kremenek272aa852008-06-25 21:21:56 +00003114 V = V + 1;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003115 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003116 case RefVal::Released:
Ted Kremenek6537a642009-03-17 19:42:23 +00003117 // Non-GC cases are handled above.
3118 assert(isGCEnabled());
3119 V = (V ^ RefVal::Owned) + 1;
Ted Kremenek0d721572008-03-11 17:48:22 +00003120 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003121 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00003122 break;
3123
Ted Kremenek272aa852008-06-25 21:21:56 +00003124 case SelfOwn:
3125 V = V ^ RefVal::NotOwned;
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003126 // Fall-through.
Ted Kremenek0d721572008-03-11 17:48:22 +00003127 case DecRef:
3128 switch (V.getKind()) {
3129 default:
Ted Kremenek6537a642009-03-17 19:42:23 +00003130 // case 'RefVal::Released' handled above.
Ted Kremenek0d721572008-03-11 17:48:22 +00003131 assert (false);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003132
Ted Kremenek272aa852008-06-25 21:21:56 +00003133 case RefVal::Owned:
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00003134 assert(V.getCount() > 0);
3135 if (V.getCount() == 1) V = V ^ RefVal::Released;
3136 V = V - 1;
Ted Kremenek0d721572008-03-11 17:48:22 +00003137 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003138
Ted Kremenek272aa852008-06-25 21:21:56 +00003139 case RefVal::NotOwned:
3140 if (V.getCount() > 0)
3141 V = V - 1;
Ted Kremenekc4f81022008-04-10 23:09:18 +00003142 else {
Ted Kremenek272aa852008-06-25 21:21:56 +00003143 V = V ^ RefVal::ErrorReleaseNotOwned;
Ted Kremenek1feab292008-04-16 04:28:53 +00003144 hasErr = V.getKind();
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003145 }
Ted Kremenek0d721572008-03-11 17:48:22 +00003146 break;
Ted Kremenek6537a642009-03-17 19:42:23 +00003147
Ted Kremenek0d721572008-03-11 17:48:22 +00003148 case RefVal::Released:
Ted Kremenek6537a642009-03-17 19:42:23 +00003149 // Non-GC cases are handled above.
3150 assert(isGCEnabled());
Ted Kremenek272aa852008-06-25 21:21:56 +00003151 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek1feab292008-04-16 04:28:53 +00003152 hasErr = V.getKind();
Ted Kremenek6537a642009-03-17 19:42:23 +00003153 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003154 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00003155 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003156 }
Ted Kremenekb6578942009-02-24 19:15:11 +00003157 return state.set<RefBindings>(sym, V);
Ted Kremeneka7338b42008-03-11 06:39:11 +00003158}
3159
Ted Kremenek10fe66d2008-04-09 01:10:13 +00003160//===----------------------------------------------------------------------===//
Ted Kremenek708af042009-02-05 06:50:21 +00003161// Handle dead symbols and end-of-path.
3162//===----------------------------------------------------------------------===//
3163
3164void CFRefCount::EvalEndPath(GRExprEngine& Eng,
3165 GREndPathNodeBuilder<GRState>& Builder) {
3166
3167 const GRState* St = Builder.getState();
3168 RefBindings B = St->get<RefBindings>();
3169
3170 llvm::SmallVector<std::pair<SymbolRef, bool>, 10> Leaked;
3171 const Decl* CodeDecl = &Eng.getGraph().getCodeDecl();
3172
3173 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
3174 bool hasLeak = false;
3175
3176 std::pair<GRStateRef, bool> X =
Ted Kremenek9577c1e2009-03-03 22:06:47 +00003177 HandleSymbolDeath(Eng.getStateManager(), St, CodeDecl,
3178 (*I).first, (*I).second, hasLeak);
Ted Kremenek708af042009-02-05 06:50:21 +00003179
3180 St = X.first;
3181 if (hasLeak) Leaked.push_back(std::make_pair((*I).first, X.second));
3182 }
3183
3184 if (Leaked.empty())
3185 return;
3186
3187 ExplodedNode<GRState>* N = Builder.MakeNode(St);
3188
3189 if (!N)
3190 return;
3191
3192 for (llvm::SmallVector<std::pair<SymbolRef,bool>, 10>::iterator
3193 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3194
3195 CFRefBug *BT = static_cast<CFRefBug*>(I->second ? leakAtReturn
3196 : leakWithinFunction);
3197 assert(BT && "BugType not initialized.");
Ted Kremenekc034f712009-04-07 05:07:44 +00003198 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N, I->first, Eng);
Ted Kremenek708af042009-02-05 06:50:21 +00003199 BR->EmitReport(report);
3200 }
3201}
3202
3203void CFRefCount::EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
3204 GRExprEngine& Eng,
3205 GRStmtNodeBuilder<GRState>& Builder,
3206 ExplodedNode<GRState>* Pred,
3207 Stmt* S,
3208 const GRState* St,
3209 SymbolReaper& SymReaper) {
3210
Ted Kremenek876d8df2009-02-19 23:47:02 +00003211 // FIXME: a lot of copy-and-paste from EvalEndPath. Refactor.
Ted Kremenek708af042009-02-05 06:50:21 +00003212 RefBindings B = St->get<RefBindings>();
3213 llvm::SmallVector<std::pair<SymbolRef,bool>, 10> Leaked;
3214
3215 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3216 E = SymReaper.dead_end(); I != E; ++I) {
3217
3218 const RefVal* T = B.lookup(*I);
3219 if (!T) continue;
3220
3221 bool hasLeak = false;
3222
3223 std::pair<GRStateRef, bool> X
Ted Kremenek876d8df2009-02-19 23:47:02 +00003224 = HandleSymbolDeath(Eng.getStateManager(), St, 0, *I, *T, hasLeak);
Ted Kremenek708af042009-02-05 06:50:21 +00003225
3226 St = X.first;
3227
3228 if (hasLeak)
3229 Leaked.push_back(std::make_pair(*I,X.second));
3230 }
3231
Ted Kremenek876d8df2009-02-19 23:47:02 +00003232 if (!Leaked.empty()) {
3233 // Create a new intermediate node representing the leak point. We
3234 // use a special program point that represents this checker-specific
3235 // transition. We use the address of RefBIndex as a unique tag for this
3236 // checker. We will create another node (if we don't cache out) that
3237 // removes the retain-count bindings from the state.
3238 // NOTE: We use 'generateNode' so that it does interplay with the
3239 // auto-transition logic.
3240 ExplodedNode<GRState>* N =
3241 Builder.generateNode(PostStmtCustom(S, &LeakProgramPointTag), St, Pred);
Ted Kremenek708af042009-02-05 06:50:21 +00003242
Ted Kremenek876d8df2009-02-19 23:47:02 +00003243 if (!N)
3244 return;
3245
3246 // Generate the bug reports.
3247 for (llvm::SmallVectorImpl<std::pair<SymbolRef,bool> >::iterator
3248 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3249
3250 CFRefBug *BT = static_cast<CFRefBug*>(I->second ? leakAtReturn
3251 : leakWithinFunction);
3252 assert(BT && "BugType not initialized.");
Ted Kremenek56c70aa2009-02-23 16:54:00 +00003253 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N,
3254 I->first, Eng);
Ted Kremenek876d8df2009-02-19 23:47:02 +00003255 BR->EmitReport(report);
3256 }
Ted Kremenek708af042009-02-05 06:50:21 +00003257
Ted Kremenek876d8df2009-02-19 23:47:02 +00003258 Pred = N;
Ted Kremenek708af042009-02-05 06:50:21 +00003259 }
Ted Kremenek876d8df2009-02-19 23:47:02 +00003260
3261 // Now generate a new node that nukes the old bindings.
3262 GRStateRef state(St, Eng.getStateManager());
3263 RefBindings::Factory& F = state.get_context<RefBindings>();
3264
3265 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3266 E = SymReaper.dead_end(); I!=E; ++I)
3267 B = F.Remove(B, *I);
3268
3269 state = state.set<RefBindings>(B);
3270 Builder.MakeNode(Dst, S, Pred, state);
Ted Kremenek708af042009-02-05 06:50:21 +00003271}
3272
3273void CFRefCount::ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
3274 GRStmtNodeBuilder<GRState>& Builder,
3275 Expr* NodeExpr, Expr* ErrorExpr,
3276 ExplodedNode<GRState>* Pred,
3277 const GRState* St,
3278 RefVal::Kind hasErr, SymbolRef Sym) {
3279 Builder.BuildSinks = true;
3280 GRExprEngine::NodeTy* N = Builder.MakeNode(Dst, NodeExpr, Pred, St);
3281
3282 if (!N) return;
3283
3284 CFRefBug *BT = 0;
3285
Ted Kremenek6537a642009-03-17 19:42:23 +00003286 switch (hasErr) {
3287 default:
3288 assert(false && "Unhandled error.");
3289 return;
3290 case RefVal::ErrorUseAfterRelease:
3291 BT = static_cast<CFRefBug*>(useAfterRelease);
3292 break;
3293 case RefVal::ErrorReleaseNotOwned:
3294 BT = static_cast<CFRefBug*>(releaseNotOwned);
3295 break;
3296 case RefVal::ErrorDeallocGC:
3297 BT = static_cast<CFRefBug*>(deallocGC);
3298 break;
3299 case RefVal::ErrorDeallocNotOwned:
3300 BT = static_cast<CFRefBug*>(deallocNotOwned);
3301 break;
Ted Kremenek708af042009-02-05 06:50:21 +00003302 }
3303
Ted Kremenekc26c4692009-02-18 03:48:14 +00003304 CFRefReport *report = new CFRefReport(*BT, *this, N, Sym);
Ted Kremenek708af042009-02-05 06:50:21 +00003305 report->addRange(ErrorExpr->getSourceRange());
3306 BR->EmitReport(report);
3307}
3308
3309//===----------------------------------------------------------------------===//
Ted Kremenekb1983ba2008-04-10 22:16:52 +00003310// Transfer function creation for external clients.
Ted Kremeneka7338b42008-03-11 06:39:11 +00003311//===----------------------------------------------------------------------===//
3312
Ted Kremenekfe30beb2008-04-30 23:47:44 +00003313GRTransferFuncs* clang::MakeCFRefCountTF(ASTContext& Ctx, bool GCEnabled,
3314 const LangOptions& lopts) {
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00003315 return new CFRefCount(Ctx, GCEnabled, lopts);
Ted Kremeneka4c74292008-04-10 22:58:08 +00003316}