blob: 59d484525031a053a1bee6d2623878c1c1f1f1e6 [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
Ted Kremenek2f226732009-05-04 05:31:22 +0000304class VISIBILITY_HIDDEN RetainSummary {
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 Kremenek2f226732009-05-04 05:31:22 +0000342 /// setDefaultArgEffect - Set the default argument effect.
343 void setDefaultArgEffect(ArgEffect E) {
344 DefaultArgEffect = E;
345 }
346
347 /// setArg - Set the argument effect on the argument specified by idx.
348 void setArgEffect(ArgEffects::Factory& AF, unsigned idx, ArgEffect E) {
349 Args = AF.Add(Args, idx, E);
350 }
351
Ted Kremenek272aa852008-06-25 21:21:56 +0000352 /// getRetEffect - Returns the effect on the return value of the call.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000353 RetEffect getRetEffect() const { return Ret; }
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000354
Ted Kremenek2f226732009-05-04 05:31:22 +0000355 /// setRetEffect - Set the effect of the return value of the call.
356 void setRetEffect(RetEffect E) { Ret = E; }
357
Ted Kremenekf2717b02008-07-18 17:24:20 +0000358 /// isEndPath - Returns true if executing the given method/function should
359 /// terminate the path.
360 bool isEndPath() const { return EndPath; }
361
Ted Kremenek272aa852008-06-25 21:21:56 +0000362 /// getReceiverEffect - Returns the effect on the receiver of the call.
363 /// This is only meaningful if the summary applies to an ObjCMessageExpr*.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000364 ArgEffect getReceiverEffect() const { return Receiver; }
Ted Kremenek266d8b62008-05-06 02:26:56 +0000365
Ted Kremenek2f226732009-05-04 05:31:22 +0000366 /// setReceiverEffect - Set the effect on the receiver of the call.
367 void setReceiverEffect(ArgEffect E) { Receiver = E; }
368
Ted Kremeneka56ae162009-05-03 05:20:50 +0000369 typedef ArgEffects::iterator ExprIterator;
Ted Kremeneka7338b42008-03-11 06:39:11 +0000370
Ted Kremeneka56ae162009-05-03 05:20:50 +0000371 ExprIterator begin_args() const { return Args.begin(); }
372 ExprIterator end_args() const { return Args.end(); }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000373
Ted Kremeneka56ae162009-05-03 05:20:50 +0000374 static void Profile(llvm::FoldingSetNodeID& ID, ArgEffects A,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000375 RetEffect RetEff, ArgEffect DefaultEff,
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000376 ArgEffect ReceiverEff, bool EndPath) {
Ted Kremeneka56ae162009-05-03 05:20:50 +0000377 ID.Add(A);
Ted Kremenek266d8b62008-05-06 02:26:56 +0000378 ID.Add(RetEff);
Ted Kremenekbcaff792008-05-06 15:44:25 +0000379 ID.AddInteger((unsigned) DefaultEff);
Ted Kremenek266d8b62008-05-06 02:26:56 +0000380 ID.AddInteger((unsigned) ReceiverEff);
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000381 ID.AddInteger((unsigned) EndPath);
Ted Kremeneka7338b42008-03-11 06:39:11 +0000382 }
383
384 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000385 Profile(ID, Args, Ret, DefaultArgEffect, Receiver, EndPath);
Ted Kremeneka7338b42008-03-11 06:39:11 +0000386 }
387};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000388} // end anonymous namespace
Ted Kremeneka7338b42008-03-11 06:39:11 +0000389
Ted Kremenek272aa852008-06-25 21:21:56 +0000390//===----------------------------------------------------------------------===//
391// Data structures for constructing summaries.
392//===----------------------------------------------------------------------===//
Ted Kremenek9f0fc792008-06-24 03:49:48 +0000393
Ted Kremenek272aa852008-06-25 21:21:56 +0000394namespace {
395class VISIBILITY_HIDDEN ObjCSummaryKey {
396 IdentifierInfo* II;
397 Selector S;
398public:
399 ObjCSummaryKey(IdentifierInfo* ii, Selector s)
400 : II(ii), S(s) {}
401
Ted Kremenek314b1952009-04-29 23:03:22 +0000402 ObjCSummaryKey(const ObjCInterfaceDecl* d, Selector s)
Ted Kremenek272aa852008-06-25 21:21:56 +0000403 : II(d ? d->getIdentifier() : 0), S(s) {}
404
405 ObjCSummaryKey(Selector s)
406 : II(0), S(s) {}
407
408 IdentifierInfo* getIdentifier() const { return II; }
409 Selector getSelector() const { return S; }
410};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000411}
412
413namespace llvm {
Ted Kremenek272aa852008-06-25 21:21:56 +0000414template <> struct DenseMapInfo<ObjCSummaryKey> {
415 static inline ObjCSummaryKey getEmptyKey() {
416 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
417 DenseMapInfo<Selector>::getEmptyKey());
418 }
Ted Kremenek84f010c2008-06-23 23:30:29 +0000419
Ted Kremenek272aa852008-06-25 21:21:56 +0000420 static inline ObjCSummaryKey getTombstoneKey() {
421 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
422 DenseMapInfo<Selector>::getTombstoneKey());
423 }
424
425 static unsigned getHashValue(const ObjCSummaryKey &V) {
426 return (DenseMapInfo<IdentifierInfo*>::getHashValue(V.getIdentifier())
427 & 0x88888888)
428 | (DenseMapInfo<Selector>::getHashValue(V.getSelector())
429 & 0x55555555);
430 }
431
432 static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
433 return DenseMapInfo<IdentifierInfo*>::isEqual(LHS.getIdentifier(),
434 RHS.getIdentifier()) &&
435 DenseMapInfo<Selector>::isEqual(LHS.getSelector(),
436 RHS.getSelector());
437 }
438
439 static bool isPod() {
440 return DenseMapInfo<ObjCInterfaceDecl*>::isPod() &&
441 DenseMapInfo<Selector>::isPod();
442 }
443};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000444} // end llvm namespace
Ted Kremeneka7338b42008-03-11 06:39:11 +0000445
Ted Kremenek84f010c2008-06-23 23:30:29 +0000446namespace {
Ted Kremenek272aa852008-06-25 21:21:56 +0000447class VISIBILITY_HIDDEN ObjCSummaryCache {
448 typedef llvm::DenseMap<ObjCSummaryKey, RetainSummary*> MapTy;
449 MapTy M;
450public:
451 ObjCSummaryCache() {}
452
453 typedef MapTy::iterator iterator;
454
Ted Kremenek314b1952009-04-29 23:03:22 +0000455 iterator find(const ObjCInterfaceDecl* D, IdentifierInfo *ClsName,
456 Selector S) {
Ted Kremeneka821b792009-04-29 05:04:30 +0000457 // Lookup the method using the decl for the class @interface. If we
458 // have no decl, lookup using the class name.
459 return D ? find(D, S) : find(ClsName, S);
460 }
461
Ted Kremenek314b1952009-04-29 23:03:22 +0000462 iterator find(const ObjCInterfaceDecl* D, Selector S) {
Ted Kremenek272aa852008-06-25 21:21:56 +0000463 // Do a lookup with the (D,S) pair. If we find a match return
464 // the iterator.
465 ObjCSummaryKey K(D, S);
466 MapTy::iterator I = M.find(K);
467
468 if (I != M.end() || !D)
469 return I;
470
471 // Walk the super chain. If we find a hit with a parent, we'll end
472 // up returning that summary. We actually allow that key (null,S), as
473 // we cache summaries for the null ObjCInterfaceDecl* to allow us to
474 // generate initial summaries without having to worry about NSObject
475 // being declared.
476 // FIXME: We may change this at some point.
477 for (ObjCInterfaceDecl* C=D->getSuperClass() ;; C=C->getSuperClass()) {
478 if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
479 break;
480
481 if (!C)
482 return I;
483 }
484
485 // Cache the summary with original key to make the next lookup faster
486 // and return the iterator.
487 M[K] = I->second;
488 return I;
489 }
490
Ted Kremenek9449ca92008-08-12 20:41:56 +0000491
Ted Kremenek272aa852008-06-25 21:21:56 +0000492 iterator find(Expr* Receiver, Selector S) {
493 return find(getReceiverDecl(Receiver), S);
494 }
495
496 iterator find(IdentifierInfo* II, Selector S) {
497 // FIXME: Class method lookup. Right now we dont' have a good way
498 // of going between IdentifierInfo* and the class hierarchy.
499 iterator I = M.find(ObjCSummaryKey(II, S));
500 return I == M.end() ? M.find(ObjCSummaryKey(S)) : I;
501 }
502
503 ObjCInterfaceDecl* getReceiverDecl(Expr* E) {
504
505 const PointerType* PT = E->getType()->getAsPointerType();
506 if (!PT) return 0;
507
508 ObjCInterfaceType* OI = dyn_cast<ObjCInterfaceType>(PT->getPointeeType());
509 if (!OI) return 0;
510
511 return OI ? OI->getDecl() : 0;
512 }
513
514 iterator end() { return M.end(); }
515
516 RetainSummary*& operator[](ObjCMessageExpr* ME) {
517
518 Selector S = ME->getSelector();
519
520 if (Expr* Receiver = ME->getReceiver()) {
521 ObjCInterfaceDecl* OD = getReceiverDecl(Receiver);
522 return OD ? M[ObjCSummaryKey(OD->getIdentifier(), S)] : M[S];
523 }
524
525 return M[ObjCSummaryKey(ME->getClassName(), S)];
526 }
527
528 RetainSummary*& operator[](ObjCSummaryKey K) {
529 return M[K];
530 }
531
532 RetainSummary*& operator[](Selector S) {
533 return M[ ObjCSummaryKey(S) ];
534 }
535};
536} // end anonymous namespace
537
538//===----------------------------------------------------------------------===//
539// Data structures for managing collections of summaries.
540//===----------------------------------------------------------------------===//
541
542namespace {
543class VISIBILITY_HIDDEN RetainSummaryManager {
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000544
545 //==-----------------------------------------------------------------==//
546 // Typedefs.
547 //==-----------------------------------------------------------------==//
Ted Kremeneka7338b42008-03-11 06:39:11 +0000548
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000549 typedef llvm::DenseMap<FunctionDecl*, RetainSummary*>
550 FuncSummariesTy;
551
Ted Kremenek84f010c2008-06-23 23:30:29 +0000552 typedef ObjCSummaryCache ObjCMethodSummariesTy;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000553
554 //==-----------------------------------------------------------------==//
555 // Data.
556 //==-----------------------------------------------------------------==//
557
Ted Kremenek272aa852008-06-25 21:21:56 +0000558 /// Ctx - The ASTContext object for the analyzed ASTs.
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000559 ASTContext& Ctx;
Ted Kremeneke44927e2008-07-01 17:21:27 +0000560
Ted Kremenekede40b72008-07-09 18:11:16 +0000561 /// CFDictionaryCreateII - An IdentifierInfo* representing the indentifier
562 /// "CFDictionaryCreate".
563 IdentifierInfo* CFDictionaryCreateII;
564
Ted Kremenek272aa852008-06-25 21:21:56 +0000565 /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000566 const bool GCEnabled;
Ted Kremenekee649082009-05-04 04:30:18 +0000567
Ted Kremenek272aa852008-06-25 21:21:56 +0000568 /// FuncSummaries - A map from FunctionDecls to summaries.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000569 FuncSummariesTy FuncSummaries;
570
Ted Kremenek272aa852008-06-25 21:21:56 +0000571 /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
572 /// to summaries.
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000573 ObjCMethodSummariesTy ObjCClassMethodSummaries;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000574
Ted Kremenek272aa852008-06-25 21:21:56 +0000575 /// ObjCMethodSummaries - A map from selectors to summaries.
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000576 ObjCMethodSummariesTy ObjCMethodSummaries;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000577
Ted Kremenek272aa852008-06-25 21:21:56 +0000578 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
579 /// and all other data used by the checker.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000580 llvm::BumpPtrAllocator BPAlloc;
581
Ted Kremeneka56ae162009-05-03 05:20:50 +0000582 /// AF - A factory for ArgEffects objects.
583 ArgEffects::Factory AF;
584
Ted Kremenek272aa852008-06-25 21:21:56 +0000585 /// ScratchArgs - A holding buffer for construct ArgEffects.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000586 ArgEffects ScratchArgs;
587
Ted Kremenek286e9852009-05-04 04:57:00 +0000588 RetainSummary DefaultSummary;
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000589 RetainSummary* StopSummary;
590
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000591 //==-----------------------------------------------------------------==//
592 // Methods.
593 //==-----------------------------------------------------------------==//
594
Ted Kremenek272aa852008-06-25 21:21:56 +0000595 /// getArgEffects - Returns a persistent ArgEffects object based on the
596 /// data in ScratchArgs.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000597 ArgEffects getArgEffects();
Ted Kremeneka7338b42008-03-11 06:39:11 +0000598
Ted Kremenek562c1302008-05-05 16:51:50 +0000599 enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000600
601public:
Ted Kremenek2f226732009-05-04 05:31:22 +0000602 RetainSummary *getDefaultSummary() {
603 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
604 return new (Summ) RetainSummary(DefaultSummary);
605 }
Ted Kremenek286e9852009-05-04 04:57:00 +0000606
Ted Kremenek064ef322009-02-23 16:51:39 +0000607 RetainSummary* getUnarySummary(const FunctionType* FT, UnaryFuncKind func);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000608
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000609 RetainSummary* getCFSummaryCreateRule(FunctionDecl* FD);
610 RetainSummary* getCFSummaryGetRule(FunctionDecl* FD);
Ted Kremenek17144e82009-01-12 21:45:02 +0000611 RetainSummary* getCFCreateGetRuleSummary(FunctionDecl* FD, const char* FName);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000612
Ted Kremeneka56ae162009-05-03 05:20:50 +0000613 RetainSummary* getPersistentSummary(ArgEffects AE, RetEffect RetEff,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000614 ArgEffect ReceiverEff = DoNothing,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000615 ArgEffect DefaultEff = MayEscape,
616 bool isEndPath = false);
Ted Kremenek45d0b502008-10-29 04:07:07 +0000617
Ted Kremenek266d8b62008-05-06 02:26:56 +0000618 RetainSummary* getPersistentSummary(RetEffect RE,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000619 ArgEffect ReceiverEff = DoNothing,
Ted Kremeneka3f30dd2008-05-22 17:31:13 +0000620 ArgEffect DefaultEff = MayEscape) {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000621 return getPersistentSummary(getArgEffects(), RE, ReceiverEff, DefaultEff);
Ted Kremenek0e344d42008-05-06 00:30:21 +0000622 }
Ted Kremenek42ea0322008-05-05 23:55:01 +0000623
Ted Kremeneka821b792009-04-29 05:04:30 +0000624 RetainSummary *getPersistentStopSummary() {
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000625 if (StopSummary)
626 return StopSummary;
627
628 StopSummary = getPersistentSummary(RetEffect::MakeNoRet(),
629 StopTracking, StopTracking);
Ted Kremenek45d0b502008-10-29 04:07:07 +0000630
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000631 return StopSummary;
Ted Kremenekbcaff792008-05-06 15:44:25 +0000632 }
Ted Kremenek926abf22008-05-06 04:20:12 +0000633
Ted Kremeneka821b792009-04-29 05:04:30 +0000634 RetainSummary *getInitMethodSummary(QualType RetTy);
Ted Kremenek42ea0322008-05-05 23:55:01 +0000635
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000636 void InitializeClassMethodSummaries();
637 void InitializeMethodSummaries();
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000638
Ted Kremenek9b42e062009-05-03 04:42:10 +0000639 bool isTrackedObjCObjectType(QualType T);
Ted Kremeneka9cdbc32009-05-03 06:08:32 +0000640 bool isTrackedCFObjectType(QualType T);
Ted Kremenek35920ed2009-01-07 00:39:56 +0000641
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000642private:
643
Ted Kremenekf2717b02008-07-18 17:24:20 +0000644 void addClsMethSummary(IdentifierInfo* ClsII, Selector S,
645 RetainSummary* Summ) {
646 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
647 }
648
Ted Kremenek272aa852008-06-25 21:21:56 +0000649 void addNSObjectClsMethSummary(Selector S, RetainSummary *Summ) {
650 ObjCClassMethodSummaries[S] = Summ;
651 }
652
653 void addNSObjectMethSummary(Selector S, RetainSummary *Summ) {
654 ObjCMethodSummaries[S] = Summ;
655 }
Ted Kremenekfbf2dc52009-03-04 23:30:42 +0000656
657 void addClassMethSummary(const char* Cls, const char* nullaryName,
658 RetainSummary *Summ) {
659 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
660 Selector S = GetNullarySelector(nullaryName, Ctx);
661 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
662 }
Ted Kremenek272aa852008-06-25 21:21:56 +0000663
Ted Kremenek1b4b6562009-02-25 02:54:57 +0000664 void addInstMethSummary(const char* Cls, const char* nullaryName,
665 RetainSummary *Summ) {
666 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
667 Selector S = GetNullarySelector(nullaryName, Ctx);
668 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
669 }
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000670
671 Selector generateSelector(va_list argp) {
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000672 llvm::SmallVector<IdentifierInfo*, 10> II;
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000673
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000674 while (const char* s = va_arg(argp, const char*))
675 II.push_back(&Ctx.Idents.get(s));
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000676
677 return Ctx.Selectors.getSelector(II.size(), &II[0]);
678 }
679
680 void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy& Summaries,
681 RetainSummary* Summ, va_list argp) {
682 Selector S = generateSelector(argp);
683 Summaries[ObjCSummaryKey(ClsII, S)] = Summ;
Ted Kremenekf2717b02008-07-18 17:24:20 +0000684 }
Ted Kremenek45642a42008-08-12 18:48:50 +0000685
686 void addInstMethSummary(const char* Cls, RetainSummary* Summ, ...) {
687 va_list argp;
688 va_start(argp, Summ);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000689 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Ted Kremenek45642a42008-08-12 18:48:50 +0000690 va_end(argp);
691 }
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000692
693 void addClsMethSummary(const char* Cls, RetainSummary* Summ, ...) {
694 va_list argp;
695 va_start(argp, Summ);
696 addMethodSummary(&Ctx.Idents.get(Cls),ObjCClassMethodSummaries, Summ, argp);
697 va_end(argp);
698 }
699
700 void addClsMethSummary(IdentifierInfo *II, RetainSummary* Summ, ...) {
701 va_list argp;
702 va_start(argp, Summ);
703 addMethodSummary(II, ObjCClassMethodSummaries, Summ, argp);
704 va_end(argp);
705 }
706
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000707 void addPanicSummary(const char* Cls, ...) {
Ted Kremeneka56ae162009-05-03 05:20:50 +0000708 RetainSummary* Summ = getPersistentSummary(AF.GetEmptyMap(),
709 RetEffect::MakeNoRet(),
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000710 DoNothing, DoNothing, true);
711 va_list argp;
712 va_start (argp, Cls);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000713 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000714 va_end(argp);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000715 }
Ted Kremenekf2717b02008-07-18 17:24:20 +0000716
Ted Kremeneka7338b42008-03-11 06:39:11 +0000717public:
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000718
719 RetainSummaryManager(ASTContext& ctx, bool gcenabled)
Ted Kremeneke44927e2008-07-01 17:21:27 +0000720 : Ctx(ctx),
Ted Kremenekede40b72008-07-09 18:11:16 +0000721 CFDictionaryCreateII(&ctx.Idents.get("CFDictionaryCreate")),
Ted Kremeneka56ae162009-05-03 05:20:50 +0000722 GCEnabled(gcenabled), AF(BPAlloc), ScratchArgs(AF.GetEmptyMap()),
Ted Kremenek286e9852009-05-04 04:57:00 +0000723 DefaultSummary(AF.GetEmptyMap() /* per-argument effects (none) */,
724 RetEffect::MakeNoRet() /* return effect */,
725 DoNothing /* receiver effect */,
726 MayEscape /* default argument effect */),
Ted Kremeneka56ae162009-05-03 05:20:50 +0000727 StopSummary(0) {
Ted Kremenek272aa852008-06-25 21:21:56 +0000728
729 InitializeClassMethodSummaries();
730 InitializeMethodSummaries();
731 }
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000732
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000733 ~RetainSummaryManager();
Ted Kremeneka7338b42008-03-11 06:39:11 +0000734
Ted Kremenekd13c1872008-06-24 03:56:45 +0000735 RetainSummary* getSummary(FunctionDecl* FD);
Ted Kremeneka821b792009-04-29 05:04:30 +0000736
Ted Kremenek314b1952009-04-29 23:03:22 +0000737 RetainSummary* getInstanceMethodSummary(ObjCMessageExpr* ME,
738 const ObjCInterfaceDecl* ID) {
Ted Kremenek04e00302009-04-29 17:09:14 +0000739 return getInstanceMethodSummary(ME->getSelector(), ME->getClassName(),
Ted Kremeneka821b792009-04-29 05:04:30 +0000740 ID, ME->getMethodDecl(), ME->getType());
741 }
742
Ted Kremenek04e00302009-04-29 17:09:14 +0000743 RetainSummary* getInstanceMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +0000744 const ObjCInterfaceDecl* ID,
745 const ObjCMethodDecl *MD,
746 QualType RetTy);
Ted Kremenek578498a2009-04-29 00:42:39 +0000747
748 RetainSummary *getClassMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +0000749 const ObjCInterfaceDecl *ID,
750 const ObjCMethodDecl *MD,
751 QualType RetTy);
Ted Kremenek578498a2009-04-29 00:42:39 +0000752
753 RetainSummary *getClassMethodSummary(ObjCMessageExpr *ME) {
754 return getClassMethodSummary(ME->getSelector(), ME->getClassName(),
755 ME->getClassInfo().first,
756 ME->getMethodDecl(), ME->getType());
757 }
Ted Kremenek91b89a42009-04-29 17:17:48 +0000758
759 /// getMethodSummary - This version of getMethodSummary is used to query
760 /// the summary for the current method being analyzed.
Ted Kremenek314b1952009-04-29 23:03:22 +0000761 RetainSummary *getMethodSummary(const ObjCMethodDecl *MD) {
762 // FIXME: Eventually this should be unneeded.
Ted Kremenek314b1952009-04-29 23:03:22 +0000763 const ObjCInterfaceDecl *ID = MD->getClassInterface();
Ted Kremenek1447cc92009-04-30 05:41:14 +0000764 Selector S = MD->getSelector();
Ted Kremenek91b89a42009-04-29 17:17:48 +0000765 IdentifierInfo *ClsName = ID->getIdentifier();
766 QualType ResultTy = MD->getResultType();
767
Ted Kremenek81eb4642009-04-30 05:47:23 +0000768 // Resolve the method decl last.
769 if (const ObjCMethodDecl *InterfaceMD =
770 ResolveToInterfaceMethodDecl(MD, Ctx))
771 MD = InterfaceMD;
Ted Kremenek1447cc92009-04-30 05:41:14 +0000772
Ted Kremenek91b89a42009-04-29 17:17:48 +0000773 if (MD->isInstanceMethod())
774 return getInstanceMethodSummary(S, ClsName, ID, MD, ResultTy);
775 else
776 return getClassMethodSummary(S, ClsName, ID, MD, ResultTy);
777 }
Ted Kremenek578498a2009-04-29 00:42:39 +0000778
Ted Kremenek314b1952009-04-29 23:03:22 +0000779 RetainSummary* getCommonMethodSummary(const ObjCMethodDecl* MD,
780 Selector S, QualType RetTy);
781
Ted Kremenekb88734c2009-05-04 15:40:58 +0000782 void updateSummaryArgEffFromAnnotations(RetainSummary &Summ, unsigned i,
783 const ParmVarDecl *PD);
784
Ted Kremenek2f226732009-05-04 05:31:22 +0000785 void updateSummaryFromAnnotations(RetainSummary &Summ,
786 const ObjCMethodDecl *MD);
Ted Kremenek926abf22008-05-06 04:20:12 +0000787
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000788 bool isGCEnabled() const { return GCEnabled; }
Ted Kremenek2f226732009-05-04 05:31:22 +0000789
790 RetainSummary *copySummary(RetainSummary *OldSumm) {
791 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
792 new (Summ) RetainSummary(*OldSumm);
793 return Summ;
794 }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000795};
796
797} // end anonymous namespace
798
799//===----------------------------------------------------------------------===//
800// Implementation of checker data structures.
801//===----------------------------------------------------------------------===//
802
Ted Kremeneka56ae162009-05-03 05:20:50 +0000803RetainSummaryManager::~RetainSummaryManager() {}
Ted Kremeneka7338b42008-03-11 06:39:11 +0000804
Ted Kremeneka56ae162009-05-03 05:20:50 +0000805ArgEffects RetainSummaryManager::getArgEffects() {
806 ArgEffects AE = ScratchArgs;
807 ScratchArgs = AF.GetEmptyMap();
808 return AE;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000809}
810
Ted Kremenek266d8b62008-05-06 02:26:56 +0000811RetainSummary*
Ted Kremeneka56ae162009-05-03 05:20:50 +0000812RetainSummaryManager::getPersistentSummary(ArgEffects AE, RetEffect RetEff,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000813 ArgEffect ReceiverEff,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000814 ArgEffect DefaultEff,
Ted Kremenekee649082009-05-04 04:30:18 +0000815 bool isEndPath) {
Ted Kremenekae855d42008-04-24 17:22:33 +0000816 // Create the summary and return it.
Ted Kremenekee649082009-05-04 04:30:18 +0000817 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
Ted Kremenekf2717b02008-07-18 17:24:20 +0000818 new (Summ) RetainSummary(AE, RetEff, DefaultEff, ReceiverEff, isEndPath);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000819 return Summ;
820}
821
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000822//===----------------------------------------------------------------------===//
Ted Kremenek35920ed2009-01-07 00:39:56 +0000823// Predicates.
824//===----------------------------------------------------------------------===//
825
Ted Kremenek9b42e062009-05-03 04:42:10 +0000826bool RetainSummaryManager::isTrackedObjCObjectType(QualType Ty) {
Ted Kremenek0d813552009-04-23 22:11:07 +0000827 if (!Ctx.isObjCObjectPointerType(Ty))
Ted Kremenek35920ed2009-01-07 00:39:56 +0000828 return false;
829
Ted Kremenek0d813552009-04-23 22:11:07 +0000830 // We assume that id<..>, id, and "Class" all represent tracked objects.
831 const PointerType *PT = Ty->getAsPointerType();
832 if (PT == 0)
833 return true;
834
835 const ObjCInterfaceType *OT = PT->getPointeeType()->getAsObjCInterfaceType();
Ted Kremenek35920ed2009-01-07 00:39:56 +0000836
837 // We assume that id<..>, id, and "Class" all represent tracked objects.
838 if (!OT)
839 return true;
Ted Kremenek0d813552009-04-23 22:11:07 +0000840
841 // Does the interface subclass NSObject?
Ted Kremenek35920ed2009-01-07 00:39:56 +0000842 // FIXME: We can memoize here if this gets too expensive.
843 IdentifierInfo* NSObjectII = &Ctx.Idents.get("NSObject");
844 ObjCInterfaceDecl* ID = OT->getDecl();
845
846 for ( ; ID ; ID = ID->getSuperClass())
847 if (ID->getIdentifier() == NSObjectII)
848 return true;
849
850 return false;
851}
852
Ted Kremeneka9cdbc32009-05-03 06:08:32 +0000853bool RetainSummaryManager::isTrackedCFObjectType(QualType T) {
854 return isRefType(T, "CF") || // Core Foundation.
855 isRefType(T, "CG") || // Core Graphics.
856 isRefType(T, "DADisk") || // Disk Arbitration API.
857 isRefType(T, "DADissenter") ||
858 isRefType(T, "DASessionRef");
859}
860
Ted Kremenek35920ed2009-01-07 00:39:56 +0000861//===----------------------------------------------------------------------===//
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000862// Summary creation for functions (largely uses of Core Foundation).
863//===----------------------------------------------------------------------===//
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000864
Ted Kremenek17144e82009-01-12 21:45:02 +0000865static bool isRetain(FunctionDecl* FD, const char* FName) {
866 const char* loc = strstr(FName, "Retain");
867 return loc && loc[sizeof("Retain")-1] == '\0';
868}
869
870static bool isRelease(FunctionDecl* FD, const char* FName) {
871 const char* loc = strstr(FName, "Release");
872 return loc && loc[sizeof("Release")-1] == '\0';
873}
874
Ted Kremenekd13c1872008-06-24 03:56:45 +0000875RetainSummary* RetainSummaryManager::getSummary(FunctionDecl* FD) {
Ted Kremenekae855d42008-04-24 17:22:33 +0000876 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000877 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000878 if (I != FuncSummaries.end())
Ted Kremenekae855d42008-04-24 17:22:33 +0000879 return I->second;
880
Ted Kremenek64cddf12009-05-04 15:34:07 +0000881 // No summary? Generate one.
Ted Kremenek17144e82009-01-12 21:45:02 +0000882 RetainSummary *S = 0;
Ted Kremenek562c1302008-05-05 16:51:50 +0000883
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000884 do {
Ted Kremenek17144e82009-01-12 21:45:02 +0000885 // We generate "stop" summaries for implicitly defined functions.
886 if (FD->isImplicit()) {
887 S = getPersistentStopSummary();
888 break;
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000889 }
Ted Kremenekeafcc2f2008-11-04 00:36:12 +0000890
Ted Kremenek064ef322009-02-23 16:51:39 +0000891 // [PR 3337] Use 'getAsFunctionType' to strip away any typedefs on the
Ted Kremenekc239b9c2009-01-16 18:40:33 +0000892 // function's type.
Ted Kremenek064ef322009-02-23 16:51:39 +0000893 const FunctionType* FT = FD->getType()->getAsFunctionType();
Ted Kremenek17144e82009-01-12 21:45:02 +0000894 const char* FName = FD->getIdentifier()->getName();
895
Ted Kremenek38c6f022009-03-05 22:11:14 +0000896 // Strip away preceding '_'. Doing this here will effect all the checks
897 // down below.
898 while (*FName == '_') ++FName;
899
Ted Kremenek17144e82009-01-12 21:45:02 +0000900 // Inspect the result type.
901 QualType RetTy = FT->getResultType();
902
903 // FIXME: This should all be refactored into a chain of "summary lookup"
904 // filters.
905 if (strcmp(FName, "IOServiceGetMatchingServices") == 0) {
906 // FIXES: <rdar://problem/6326900>
907 // This should be addressed using a API table. This strcmp is also
908 // a little gross, but there is no need to super optimize here.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000909 assert (ScratchArgs.isEmpty());
910 ScratchArgs = AF.Add(ScratchArgs, 1, DecRef);
Ted Kremenek17144e82009-01-12 21:45:02 +0000911 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
912 break;
Ted Kremenekcfc50c72008-10-22 20:54:52 +0000913 }
Ted Kremenek7b88c892009-03-17 22:43:44 +0000914
915 // Enable this code once the semantics of NSDeallocateObject are resolved
916 // for GC. <rdar://problem/6619988>
917#if 0
918 // Handle: NSDeallocateObject(id anObject);
919 // This method does allow 'nil' (although we don't check it now).
920 if (strcmp(FName, "NSDeallocateObject") == 0) {
921 return RetTy == Ctx.VoidTy
922 ? getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, Dealloc)
923 : getPersistentStopSummary();
924 }
925#endif
Ted Kremenek17144e82009-01-12 21:45:02 +0000926
927 // Handle: id NSMakeCollectable(CFTypeRef)
928 if (strcmp(FName, "NSMakeCollectable") == 0) {
929 S = (RetTy == Ctx.getObjCIdType())
930 ? getUnarySummary(FT, cfmakecollectable)
931 : getPersistentStopSummary();
932
933 break;
934 }
935
936 if (RetTy->isPointerType()) {
937 // For CoreFoundation ('CF') types.
938 if (isRefType(RetTy, "CF", &Ctx, FName)) {
939 if (isRetain(FD, FName))
940 S = getUnarySummary(FT, cfretain);
941 else if (strstr(FName, "MakeCollectable"))
942 S = getUnarySummary(FT, cfmakecollectable);
943 else
944 S = getCFCreateGetRuleSummary(FD, FName);
945
946 break;
947 }
948
949 // For CoreGraphics ('CG') types.
950 if (isRefType(RetTy, "CG", &Ctx, FName)) {
951 if (isRetain(FD, FName))
952 S = getUnarySummary(FT, cfretain);
953 else
954 S = getCFCreateGetRuleSummary(FD, FName);
955
956 break;
957 }
958
959 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
960 if (isRefType(RetTy, "DADisk") ||
961 isRefType(RetTy, "DADissenter") ||
962 isRefType(RetTy, "DASessionRef")) {
963 S = getCFCreateGetRuleSummary(FD, FName);
964 break;
965 }
966
967 break;
968 }
969
970 // Check for release functions, the only kind of functions that we care
971 // about that don't return a pointer type.
972 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
Ted Kremenek38c6f022009-03-05 22:11:14 +0000973 // Test for 'CGCF'.
974 if (FName[1] == 'G' && FName[2] == 'C' && FName[3] == 'F')
975 FName += 4;
976 else
977 FName += 2;
978
979 if (isRelease(FD, FName))
Ted Kremenek17144e82009-01-12 21:45:02 +0000980 S = getUnarySummary(FT, cfrelease);
981 else {
Ted Kremeneka56ae162009-05-03 05:20:50 +0000982 assert (ScratchArgs.isEmpty());
Ted Kremenek7b293682009-01-29 22:45:13 +0000983 // Remaining CoreFoundation and CoreGraphics functions.
984 // We use to assume that they all strictly followed the ownership idiom
985 // and that ownership cannot be transferred. While this is technically
986 // correct, many methods allow a tracked object to escape. For example:
987 //
988 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
989 // CFDictionaryAddValue(y, key, x);
990 // CFRelease(x);
991 // ... it is okay to use 'x' since 'y' has a reference to it
992 //
993 // We handle this and similar cases with the follow heuristic. If the
994 // function name contains "InsertValue", "SetValue" or "AddValue" then
995 // we assume that arguments may "escape."
996 //
997 ArgEffect E = (CStrInCStrNoCase(FName, "InsertValue") ||
998 CStrInCStrNoCase(FName, "AddValue") ||
Ted Kremenekcf071252009-02-05 22:34:53 +0000999 CStrInCStrNoCase(FName, "SetValue") ||
1000 CStrInCStrNoCase(FName, "AppendValue"))
Ted Kremenek7b293682009-01-29 22:45:13 +00001001 ? MayEscape : DoNothing;
1002
1003 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek17144e82009-01-12 21:45:02 +00001004 }
1005 }
Ted Kremenek4c5378c2008-07-15 16:50:12 +00001006 }
1007 while (0);
Ted Kremenek2f226732009-05-04 05:31:22 +00001008
1009 if (!S)
1010 S = getDefaultSummary();
Ted Kremenekae855d42008-04-24 17:22:33 +00001011
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001012 FuncSummaries[FD] = S;
Ted Kremenek562c1302008-05-05 16:51:50 +00001013 return S;
Ted Kremenek827f93b2008-03-06 00:08:09 +00001014}
1015
Ted Kremenek4c5378c2008-07-15 16:50:12 +00001016RetainSummary*
1017RetainSummaryManager::getCFCreateGetRuleSummary(FunctionDecl* FD,
1018 const char* FName) {
1019
Ted Kremenek562c1302008-05-05 16:51:50 +00001020 if (strstr(FName, "Create") || strstr(FName, "Copy"))
1021 return getCFSummaryCreateRule(FD);
Ted Kremenek4c5378c2008-07-15 16:50:12 +00001022
Ted Kremenek562c1302008-05-05 16:51:50 +00001023 if (strstr(FName, "Get"))
1024 return getCFSummaryGetRule(FD);
1025
Ted Kremenek286e9852009-05-04 04:57:00 +00001026 return getDefaultSummary();
Ted Kremenek562c1302008-05-05 16:51:50 +00001027}
1028
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001029RetainSummary*
Ted Kremenek064ef322009-02-23 16:51:39 +00001030RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1031 UnaryFuncKind func) {
1032
Ted Kremenek17144e82009-01-12 21:45:02 +00001033 // Sanity check that this is *really* a unary function. This can
1034 // happen if people do weird things.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001035 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
Ted Kremenek17144e82009-01-12 21:45:02 +00001036 if (!FTP || FTP->getNumArgs() != 1)
1037 return getPersistentStopSummary();
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001038
Ted Kremeneka56ae162009-05-03 05:20:50 +00001039 assert (ScratchArgs.isEmpty());
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001040
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001041 switch (func) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001042 case cfretain: {
1043 ScratchArgs = AF.Add(ScratchArgs, 0, IncRef);
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001044 return getPersistentSummary(RetEffect::MakeAlias(0),
1045 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001046 }
1047
1048 case cfrelease: {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001049 ScratchArgs = AF.Add(ScratchArgs, 0, DecRef);
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001050 return getPersistentSummary(RetEffect::MakeNoRet(),
1051 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001052 }
1053
1054 case cfmakecollectable: {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001055 ScratchArgs = AF.Add(ScratchArgs, 0, MakeCollectable);
Ted Kremenek2126bef2009-02-18 21:57:45 +00001056 return getPersistentSummary(RetEffect::MakeAlias(0),DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001057 }
1058
1059 default:
Ted Kremenek562c1302008-05-05 16:51:50 +00001060 assert (false && "Not a supported unary function.");
Ted Kremenek286e9852009-05-04 04:57:00 +00001061 return getDefaultSummary();
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00001062 }
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001063}
1064
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001065RetainSummary* RetainSummaryManager::getCFSummaryCreateRule(FunctionDecl* FD) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001066 assert (ScratchArgs.isEmpty());
Ted Kremenekede40b72008-07-09 18:11:16 +00001067
1068 if (FD->getIdentifier() == CFDictionaryCreateII) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001069 ScratchArgs = AF.Add(ScratchArgs, 1, DoNothingByRef);
1070 ScratchArgs = AF.Add(ScratchArgs, 2, DoNothingByRef);
Ted Kremenekede40b72008-07-09 18:11:16 +00001071 }
1072
Ted Kremenek68621b92009-01-28 05:56:51 +00001073 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001074}
1075
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001076RetainSummary* RetainSummaryManager::getCFSummaryGetRule(FunctionDecl* FD) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001077 assert (ScratchArgs.isEmpty());
Ted Kremenek68621b92009-01-28 05:56:51 +00001078 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1079 DoNothing, DoNothing);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001080}
1081
Ted Kremeneka7338b42008-03-11 06:39:11 +00001082//===----------------------------------------------------------------------===//
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001083// Summary creation for Selectors.
1084//===----------------------------------------------------------------------===//
1085
Ted Kremenekbcaff792008-05-06 15:44:25 +00001086RetainSummary*
Ted Kremeneka821b792009-04-29 05:04:30 +00001087RetainSummaryManager::getInitMethodSummary(QualType RetTy) {
Ted Kremeneka56ae162009-05-03 05:20:50 +00001088 assert(ScratchArgs.isEmpty());
Ted Kremenek42ea0322008-05-05 23:55:01 +00001089
Ted Kremenek802cfc72009-02-20 00:05:35 +00001090 // 'init' methods only return an alias if the return type is a location type.
Ted Kremeneka821b792009-04-29 05:04:30 +00001091 return getPersistentSummary(Loc::IsLocType(RetTy)
1092 ? RetEffect::MakeReceiverAlias()
1093 : RetEffect::MakeNoRet());
Ted Kremenek42ea0322008-05-05 23:55:01 +00001094}
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001095
Ted Kremenek2f226732009-05-04 05:31:22 +00001096
1097void
Ted Kremenekb88734c2009-05-04 15:40:58 +00001098RetainSummaryManager::updateSummaryArgEffFromAnnotations(RetainSummary &Summ,
1099 unsigned i,
1100 const ParmVarDecl *PD){
1101 if (PD->getAttr<ObjCOwnershipRetainAttr>())
1102 Summ.setArgEffect(AF, i, IncRefMsg);
1103 else if (PD->getAttr<ObjCOwnershipCFRetainAttr>())
1104 Summ.setArgEffect(AF, i, IncRef);
1105 else if (PD->getAttr<ObjCOwnershipReleaseAttr>())
1106 Summ.setArgEffect(AF, i, DecRefMsg);
1107 else if (PD->getAttr<ObjCOwnershipCFReleaseAttr>())
1108 Summ.setArgEffect(AF, i, DecRef);
1109 else if (PD->getAttr<ObjCOwnershipMakeCollectableAttr>())
1110 Summ.setArgEffect(AF, i, MakeCollectable);
1111}
1112
1113void
Ted Kremenek2f226732009-05-04 05:31:22 +00001114RetainSummaryManager::updateSummaryFromAnnotations(RetainSummary &Summ,
1115 const ObjCMethodDecl *MD) {
Ted Kremenek923fc392009-04-24 23:32:32 +00001116 if (!MD)
Ted Kremenek2f226732009-05-04 05:31:22 +00001117 return;
Ted Kremenek923fc392009-04-24 23:32:32 +00001118
1119 // Determine if there is a special return effect for this method.
Ted Kremenek9b42e062009-05-03 04:42:10 +00001120 if (isTrackedObjCObjectType(MD->getResultType())) {
Ted Kremenek923fc392009-04-24 23:32:32 +00001121 if (MD->getAttr<ObjCOwnershipReturnsAttr>()) {
Ted Kremenek2f226732009-05-04 05:31:22 +00001122 Summ.setRetEffect(isGCEnabled()
1123 ? RetEffect::MakeGCNotOwned()
1124 : RetEffect::MakeOwned(RetEffect::ObjC, true));
Ted Kremenek923fc392009-04-24 23:32:32 +00001125 }
1126 }
1127
Ted Kremenekb30a2f32009-04-25 01:21:50 +00001128 // Determine if there are any arguments with a specific ArgEffect.
Ted Kremenekb30a2f32009-04-25 01:21:50 +00001129 unsigned i = 0;
1130 for (ObjCMethodDecl::param_iterator I = MD->param_begin(),
Ted Kremenekb88734c2009-05-04 15:40:58 +00001131 E = MD->param_end(); I != E; ++I, ++i)
1132 updateSummaryArgEffFromAnnotations(Summ, i, *I);
Ted Kremenekb30a2f32009-04-25 01:21:50 +00001133
Ted Kremeneke404c0d2009-04-30 20:00:31 +00001134 // Determine any effects on the receiver.
Ted Kremenek2f226732009-05-04 05:31:22 +00001135 if (MD->getAttr<ObjCOwnershipRetainAttr>())
1136 Summ.setReceiverEffect(IncRefMsg);
1137 else if (MD->getAttr<ObjCOwnershipReleaseAttr>())
1138 Summ.setReceiverEffect(DecRefMsg);
Ted Kremenek923fc392009-04-24 23:32:32 +00001139}
Ted Kremenek272aa852008-06-25 21:21:56 +00001140
Ted Kremenekbcaff792008-05-06 15:44:25 +00001141RetainSummary*
Ted Kremenek314b1952009-04-29 23:03:22 +00001142RetainSummaryManager::getCommonMethodSummary(const ObjCMethodDecl* MD,
1143 Selector S, QualType RetTy) {
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001144
Ted Kremenek578498a2009-04-29 00:42:39 +00001145 if (MD) {
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001146 // Scan the method decl for 'void*' arguments. These should be treated
1147 // as 'StopTracking' because they are often used with delegates.
1148 // Delegates are a frequent form of false positives with the retain
1149 // count checker.
1150 unsigned i = 0;
1151 for (ObjCMethodDecl::param_iterator I = MD->param_begin(),
1152 E = MD->param_end(); I != E; ++I, ++i)
1153 if (ParmVarDecl *PD = *I) {
1154 QualType Ty = Ctx.getCanonicalType(PD->getType());
1155 if (Ty.getUnqualifiedType() == Ctx.VoidPtrTy)
Ted Kremeneka56ae162009-05-03 05:20:50 +00001156 ScratchArgs = AF.Add(ScratchArgs, i, StopTracking);
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001157 }
1158 }
1159
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001160 // Any special effect for the receiver?
1161 ArgEffect ReceiverEff = DoNothing;
1162
1163 // If one of the arguments in the selector has the keyword 'delegate' we
1164 // should stop tracking the reference count for the receiver. This is
1165 // because the reference count is quite possibly handled by a delegate
1166 // method.
1167 if (S.isKeywordSelector()) {
1168 const std::string &str = S.getAsString();
1169 assert(!str.empty());
1170 if (CStrInCStrNoCase(&str[0], "delegate:")) ReceiverEff = StopTracking;
1171 }
1172
Ted Kremenek174a0772009-04-23 23:08:22 +00001173 // Look for methods that return an owned object.
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001174 if (isTrackedObjCObjectType(RetTy)) {
1175 // EXPERIMENTAL: Assume the Cocoa conventions for all objects returned
1176 // by instance methods.
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001177 RetEffect E =
1178 followsFundamentalRule(S.getIdentifierInfoForSlot(0)->getName())
1179 ? (isGCEnabled() ? RetEffect::MakeGCNotOwned()
1180 : RetEffect::MakeOwned(RetEffect::ObjC, true))
1181 : RetEffect::MakeNotOwned(RetEffect::ObjC);
1182
1183 return getPersistentSummary(E, ReceiverEff, MayEscape);
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001184 }
Ted Kremenek174a0772009-04-23 23:08:22 +00001185
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001186 // Look for methods that return an owned core foundation object.
1187 if (isTrackedCFObjectType(RetTy)) {
1188 RetEffect E =
1189 followsFundamentalRule(S.getIdentifierInfoForSlot(0)->getName())
1190 ? RetEffect::MakeOwned(RetEffect::CF, true)
1191 : RetEffect::MakeNotOwned(RetEffect::CF);
1192
1193 return getPersistentSummary(E, ReceiverEff, MayEscape);
1194 }
Ted Kremenek174a0772009-04-23 23:08:22 +00001195
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001196 if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing)
Ted Kremenek286e9852009-05-04 04:57:00 +00001197 return getDefaultSummary();
Ted Kremenek174a0772009-04-23 23:08:22 +00001198
Ted Kremenek2f226732009-05-04 05:31:22 +00001199 return getPersistentSummary(RetEffect::MakeNoRet(), ReceiverEff, MayEscape);
Ted Kremenek174a0772009-04-23 23:08:22 +00001200}
1201
1202RetainSummary*
Ted Kremenek04e00302009-04-29 17:09:14 +00001203RetainSummaryManager::getInstanceMethodSummary(Selector S,
1204 IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +00001205 const ObjCInterfaceDecl* ID,
1206 const ObjCMethodDecl *MD,
Ted Kremenek04e00302009-04-29 17:09:14 +00001207 QualType RetTy) {
Ted Kremenekbcaff792008-05-06 15:44:25 +00001208
Ted Kremeneka821b792009-04-29 05:04:30 +00001209 // Look up a summary in our summary cache.
1210 ObjCMethodSummariesTy::iterator I = ObjCMethodSummaries.find(ID, ClsName, S);
Ted Kremenek42ea0322008-05-05 23:55:01 +00001211
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001212 if (I != ObjCMethodSummaries.end())
Ted Kremenek42ea0322008-05-05 23:55:01 +00001213 return I->second;
Ted Kremenek42ea0322008-05-05 23:55:01 +00001214
Ted Kremeneka56ae162009-05-03 05:20:50 +00001215 assert(ScratchArgs.isEmpty());
Ted Kremenek2f226732009-05-04 05:31:22 +00001216 RetainSummary *Summ = 0;
Ted Kremenek1d3d9562008-05-06 06:09:09 +00001217
Ted Kremenek2f226732009-05-04 05:31:22 +00001218 // "initXXX": pass-through for receiver.
1219 if (deriveNamingConvention(S.getIdentifierInfoForSlot(0)->getName())
1220 == InitRule)
1221 Summ = getInitMethodSummary(RetTy);
1222 else
1223 Summ = getCommonMethodSummary(MD, S, RetTy);
1224
1225 // Annotations override defaults.
1226 updateSummaryFromAnnotations(*Summ, MD);
Ted Kremenek923fc392009-04-24 23:32:32 +00001227
Ted Kremenek2f226732009-05-04 05:31:22 +00001228 // Memoize the summary.
Ted Kremeneka821b792009-04-29 05:04:30 +00001229 ObjCMethodSummaries[ObjCSummaryKey(ClsName, S)] = Summ;
Ted Kremeneke4158502009-04-23 19:11:35 +00001230 return Summ;
Ted Kremenek42ea0322008-05-05 23:55:01 +00001231}
1232
Ted Kremeneka7722b72008-05-06 21:26:51 +00001233RetainSummary*
Ted Kremenek578498a2009-04-29 00:42:39 +00001234RetainSummaryManager::getClassMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +00001235 const ObjCInterfaceDecl *ID,
1236 const ObjCMethodDecl *MD,
1237 QualType RetTy) {
Ted Kremenekccbe79a2009-04-24 17:50:11 +00001238
Ted Kremenek578498a2009-04-29 00:42:39 +00001239 assert(ClsName && "Class name must be specified.");
Ted Kremeneka821b792009-04-29 05:04:30 +00001240 ObjCMethodSummariesTy::iterator I =
1241 ObjCClassMethodSummaries.find(ID, ClsName, S);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001242
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001243 if (I != ObjCClassMethodSummaries.end())
Ted Kremeneka7722b72008-05-06 21:26:51 +00001244 return I->second;
Ted Kremenek2f226732009-05-04 05:31:22 +00001245
1246 RetainSummary *Summ = getCommonMethodSummary(MD, S, RetTy);
1247
1248 // Annotations override defaults.
1249 updateSummaryFromAnnotations(*Summ, MD);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001250
Ted Kremenek2f226732009-05-04 05:31:22 +00001251 // Memoize the summary.
Ted Kremenek578498a2009-04-29 00:42:39 +00001252 ObjCClassMethodSummaries[ObjCSummaryKey(ClsName, S)] = Summ;
Ted Kremeneke4158502009-04-23 19:11:35 +00001253 return Summ;
Ted Kremeneka7722b72008-05-06 21:26:51 +00001254}
1255
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001256void RetainSummaryManager::InitializeClassMethodSummaries() {
Ted Kremenek0e344d42008-05-06 00:30:21 +00001257
Ted Kremeneka56ae162009-05-03 05:20:50 +00001258 assert (ScratchArgs.isEmpty());
Ted Kremenek0e344d42008-05-06 00:30:21 +00001259
Ted Kremenek382fb4e2009-04-27 19:14:45 +00001260 RetEffect E = isGCEnabled() ? RetEffect::MakeGCNotOwned()
Ted Kremenek68621b92009-01-28 05:56:51 +00001261 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001262
Ted Kremenek0e344d42008-05-06 00:30:21 +00001263 RetainSummary* Summ = getPersistentSummary(E);
1264
Ted Kremenek272aa852008-06-25 21:21:56 +00001265 // Create the summaries for "alloc", "new", and "allocWithZone:" for
1266 // NSObject and its derivatives.
1267 addNSObjectClsMethSummary(GetNullarySelector("alloc", Ctx), Summ);
1268 addNSObjectClsMethSummary(GetNullarySelector("new", Ctx), Summ);
1269 addNSObjectClsMethSummary(GetUnarySelector("allocWithZone", Ctx), Summ);
Ted Kremenekf2717b02008-07-18 17:24:20 +00001270
1271 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001272 addClsMethSummary(&Ctx.Idents.get("NSAssertionHandler"),
Ted Kremenek68621b92009-01-28 05:56:51 +00001273 GetNullarySelector("currentHandler", Ctx),
1274 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001275
1276 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremeneka56ae162009-05-03 05:20:50 +00001277 ScratchArgs = AF.Add(ScratchArgs, 0, Autorelease);
Ted Kremenek9b112d22009-01-28 21:44:40 +00001278 addClsMethSummary(&Ctx.Idents.get("NSAutoreleasePool"),
1279 GetUnarySelector("addObject", Ctx),
1280 getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenekf21cb242009-02-23 02:31:16 +00001281 DoNothing, Autorelease));
Ted Kremenekccbe79a2009-04-24 17:50:11 +00001282
1283 // Create the summaries for [NSObject performSelector...]. We treat
1284 // these as 'stop tracking' for the arguments because they are often
1285 // used for delegates that can release the object. When we have better
1286 // inter-procedural analysis we can potentially do something better. This
1287 // workaround is to remove false positives.
1288 Summ = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, StopTracking);
1289 IdentifierInfo *NSObjectII = &Ctx.Idents.get("NSObject");
1290 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1291 "afterDelay", NULL);
1292 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1293 "afterDelay", "inModes", NULL);
1294 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1295 "withObject", "waitUntilDone", NULL);
1296 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1297 "withObject", "waitUntilDone", "modes", NULL);
1298 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1299 "withObject", "waitUntilDone", NULL);
1300 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1301 "withObject", "waitUntilDone", "modes", NULL);
1302 addClsMethSummary(NSObjectII, Summ, "performSelectorInBackground",
1303 "withObject", NULL);
Ted Kremenek0e344d42008-05-06 00:30:21 +00001304}
1305
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001306void RetainSummaryManager::InitializeMethodSummaries() {
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001307
Ted Kremeneka56ae162009-05-03 05:20:50 +00001308 assert (ScratchArgs.isEmpty());
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001309
Ted Kremeneka7722b72008-05-06 21:26:51 +00001310 // Create the "init" selector. It just acts as a pass-through for the
1311 // receiver.
Ted Kremenek56c70aa2009-02-23 16:54:00 +00001312 RetainSummary* InitSumm =
1313 getPersistentSummary(RetEffect::MakeReceiverAlias());
Ted Kremeneke44927e2008-07-01 17:21:27 +00001314 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001315
1316 // The next methods are allocators.
Ted Kremenek382fb4e2009-04-27 19:14:45 +00001317 RetEffect E = isGCEnabled() ? RetEffect::MakeGCNotOwned()
Ted Kremenek68621b92009-01-28 05:56:51 +00001318 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001319
Ted Kremeneke44927e2008-07-01 17:21:27 +00001320 RetainSummary* Summ = getPersistentSummary(E);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001321
1322 // Create the "copy" selector.
Ted Kremenek9449ca92008-08-12 20:41:56 +00001323 addNSObjectMethSummary(GetNullarySelector("copy", Ctx), Summ);
1324
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001325 // Create the "mutableCopy" selector.
Ted Kremenek272aa852008-06-25 21:21:56 +00001326 addNSObjectMethSummary(GetNullarySelector("mutableCopy", Ctx), Summ);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001327
Ted Kremenek266d8b62008-05-06 02:26:56 +00001328 // Create the "retain" selector.
1329 E = RetEffect::MakeReceiverAlias();
Ted Kremenek58dd95b2009-02-18 18:54:33 +00001330 Summ = getPersistentSummary(E, IncRefMsg);
Ted Kremenek272aa852008-06-25 21:21:56 +00001331 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001332
1333 // Create the "release" selector.
Ted Kremenek58dd95b2009-02-18 18:54:33 +00001334 Summ = getPersistentSummary(E, DecRefMsg);
Ted Kremenek272aa852008-06-25 21:21:56 +00001335 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Ted Kremenekc00b32b2008-05-07 21:17:39 +00001336
1337 // Create the "drain" selector.
1338 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek272aa852008-06-25 21:21:56 +00001339 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
Ted Kremenek6537a642009-03-17 19:42:23 +00001340
1341 // Create the -dealloc summary.
1342 Summ = getPersistentSummary(RetEffect::MakeNoRet(), Dealloc);
1343 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001344
1345 // Create the "autorelease" selector.
Ted Kremenek9b112d22009-01-28 21:44:40 +00001346 Summ = getPersistentSummary(E, Autorelease);
Ted Kremenek272aa852008-06-25 21:21:56 +00001347 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001348
Ted Kremenekaac82832009-02-23 17:45:03 +00001349 // Specially handle NSAutoreleasePool.
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001350 addInstMethSummary("NSAutoreleasePool", "init",
Ted Kremenekaac82832009-02-23 17:45:03 +00001351 getPersistentSummary(RetEffect::MakeReceiverAlias(),
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001352 NewAutoreleasePool));
Ted Kremenekaac82832009-02-23 17:45:03 +00001353
Ted Kremenek45642a42008-08-12 18:48:50 +00001354 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremenek7e3a3272009-02-23 02:51:29 +00001355 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1356 // self-own themselves. However, they only do this once they are displayed.
1357 // Thus, we need to track an NSWindow's display status.
1358 // This is tracked in <rdar://problem/6062711>.
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001359 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
Ted Kremeneke5a036a2009-04-03 19:02:51 +00001360 RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet());
1361
1362 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1363
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001364
1365#if 0
Ted Kremeneke44927e2008-07-01 17:21:27 +00001366 RetainSummary *NSWindowSumm =
Ted Kremenek7e3a3272009-02-23 02:51:29 +00001367 getPersistentSummary(RetEffect::MakeReceiverAlias(), StopTracking);
Ted Kremenek45642a42008-08-12 18:48:50 +00001368
1369 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1370 "styleMask", "backing", "defer", NULL);
1371
1372 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1373 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001374#endif
Ted Kremenek45642a42008-08-12 18:48:50 +00001375
1376 // For NSPanel (which subclasses NSWindow), allocated objects are not
1377 // self-owned.
Ted Kremeneke5a036a2009-04-03 19:02:51 +00001378 // FIXME: For now we don't track NSPanels. object for the same reason
1379 // as for NSWindow objects.
1380 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
1381
Ted Kremenek45642a42008-08-12 18:48:50 +00001382 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1383 "styleMask", "backing", "defer", NULL);
1384
1385 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1386 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek272aa852008-06-25 21:21:56 +00001387
Ted Kremenekf2717b02008-07-18 17:24:20 +00001388 // Create NSAssertionHandler summaries.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001389 addPanicSummary("NSAssertionHandler", "handleFailureInFunction", "file",
1390 "lineNumber", "description", NULL);
Ted Kremenekf2717b02008-07-18 17:24:20 +00001391
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001392 addPanicSummary("NSAssertionHandler", "handleFailureInMethod", "object",
1393 "file", "lineNumber", "description", NULL);
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001394}
1395
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001396//===----------------------------------------------------------------------===//
Ted Kremenek7aef4842008-04-16 20:40:59 +00001397// Reference-counting logic (typestate + counts).
Ted Kremeneka7338b42008-03-11 06:39:11 +00001398//===----------------------------------------------------------------------===//
1399
Ted Kremeneka7338b42008-03-11 06:39:11 +00001400namespace {
1401
Ted Kremenek7d421f32008-04-09 23:49:11 +00001402class VISIBILITY_HIDDEN RefVal {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001403public:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001404 enum Kind {
1405 Owned = 0, // Owning reference.
1406 NotOwned, // Reference is not owned by still valid (not freed).
1407 Released, // Object has been released.
1408 ReturnedOwned, // Returned object passes ownership to caller.
1409 ReturnedNotOwned, // Return object does not pass ownership to caller.
Ted Kremenek6537a642009-03-17 19:42:23 +00001410 ERROR_START,
1411 ErrorDeallocNotOwned, // -dealloc called on non-owned object.
1412 ErrorDeallocGC, // Calling -dealloc with GC enabled.
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001413 ErrorUseAfterRelease, // Object used after released.
1414 ErrorReleaseNotOwned, // Release of an object that was not owned.
Ted Kremenek6537a642009-03-17 19:42:23 +00001415 ERROR_LEAK_START,
Ted Kremenek311f3d42008-10-22 23:56:21 +00001416 ErrorLeak, // A memory leak due to excessive reference counts.
1417 ErrorLeakReturned // A memory leak due to the returning method not having
1418 // the correct naming conventions.
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001419 };
Ted Kremenek68621b92009-01-28 05:56:51 +00001420
1421private:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001422 Kind kind;
Ted Kremenek68621b92009-01-28 05:56:51 +00001423 RetEffect::ObjKind okind;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001424 unsigned Cnt;
Ted Kremenek272aa852008-06-25 21:21:56 +00001425 QualType T;
1426
Ted Kremenek68621b92009-01-28 05:56:51 +00001427 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, QualType t)
1428 : kind(k), okind(o), Cnt(cnt), T(t) {}
Ted Kremenek0d721572008-03-11 17:48:22 +00001429
Ted Kremenek68621b92009-01-28 05:56:51 +00001430 RefVal(Kind k, unsigned cnt = 0)
1431 : kind(k), okind(RetEffect::AnyObj), Cnt(cnt) {}
1432
1433public:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001434 Kind getKind() const { return kind; }
Ted Kremenek68621b92009-01-28 05:56:51 +00001435
1436 RetEffect::ObjKind getObjKind() const { return okind; }
Ted Kremenek0d721572008-03-11 17:48:22 +00001437
Ted Kremenek6537a642009-03-17 19:42:23 +00001438 unsigned getCount() const { return Cnt; }
1439 void clearCounts() { Cnt = 0; }
1440
Ted Kremenek272aa852008-06-25 21:21:56 +00001441 QualType getType() const { return T; }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001442
1443 // Useful predicates.
Ted Kremenek0d721572008-03-11 17:48:22 +00001444
Ted Kremenek6537a642009-03-17 19:42:23 +00001445 static bool isError(Kind k) { return k >= ERROR_START; }
Ted Kremenek1daa16c2008-03-11 18:14:09 +00001446
Ted Kremenek6537a642009-03-17 19:42:23 +00001447 static bool isLeak(Kind k) { return k >= ERROR_LEAK_START; }
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001448
Ted Kremenekffefc352008-04-11 22:25:11 +00001449 bool isOwned() const {
1450 return getKind() == Owned;
1451 }
1452
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001453 bool isNotOwned() const {
1454 return getKind() == NotOwned;
1455 }
1456
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001457 bool isReturnedOwned() const {
1458 return getKind() == ReturnedOwned;
1459 }
1460
1461 bool isReturnedNotOwned() const {
1462 return getKind() == ReturnedNotOwned;
1463 }
1464
1465 bool isNonLeakError() const {
1466 Kind k = getKind();
1467 return isError(k) && !isLeak(k);
1468 }
1469
Ted Kremenek68621b92009-01-28 05:56:51 +00001470 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
1471 unsigned Count = 1) {
1472 return RefVal(Owned, o, Count, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001473 }
1474
Ted Kremenek68621b92009-01-28 05:56:51 +00001475 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
1476 unsigned Count = 0) {
1477 return RefVal(NotOwned, o, Count, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001478 }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001479
1480 static RefVal makeReturnedOwned(unsigned Count) {
1481 return RefVal(ReturnedOwned, Count);
1482 }
1483
1484 static RefVal makeReturnedNotOwned() {
1485 return RefVal(ReturnedNotOwned);
1486 }
1487
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001488 // Comparison, profiling, and pretty-printing.
Ted Kremenek0d721572008-03-11 17:48:22 +00001489
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001490 bool operator==(const RefVal& X) const {
Ted Kremenek272aa852008-06-25 21:21:56 +00001491 return kind == X.kind && Cnt == X.Cnt && T == X.T;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001492 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001493
Ted Kremenek272aa852008-06-25 21:21:56 +00001494 RefVal operator-(size_t i) const {
Ted Kremenek68621b92009-01-28 05:56:51 +00001495 return RefVal(getKind(), getObjKind(), getCount() - i, getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001496 }
1497
1498 RefVal operator+(size_t i) const {
Ted Kremenek68621b92009-01-28 05:56:51 +00001499 return RefVal(getKind(), getObjKind(), getCount() + i, getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001500 }
1501
1502 RefVal operator^(Kind k) const {
Ted Kremenek68621b92009-01-28 05:56:51 +00001503 return RefVal(k, getObjKind(), getCount(), getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001504 }
Ted Kremenek6537a642009-03-17 19:42:23 +00001505
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001506 void Profile(llvm::FoldingSetNodeID& ID) const {
1507 ID.AddInteger((unsigned) kind);
1508 ID.AddInteger(Cnt);
Ted Kremenek272aa852008-06-25 21:21:56 +00001509 ID.Add(T);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001510 }
1511
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001512 void print(std::ostream& Out) const;
Ted Kremenek0d721572008-03-11 17:48:22 +00001513};
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001514
1515void RefVal::print(std::ostream& Out) const {
Ted Kremenek272aa852008-06-25 21:21:56 +00001516 if (!T.isNull())
1517 Out << "Tracked Type:" << T.getAsString() << '\n';
1518
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001519 switch (getKind()) {
1520 default: assert(false);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001521 case Owned: {
1522 Out << "Owned";
1523 unsigned cnt = getCount();
1524 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001525 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001526 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001527
Ted Kremenekc4f81022008-04-10 23:09:18 +00001528 case NotOwned: {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001529 Out << "NotOwned";
Ted Kremenekc4f81022008-04-10 23:09:18 +00001530 unsigned cnt = getCount();
1531 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001532 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001533 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001534
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001535 case ReturnedOwned: {
1536 Out << "ReturnedOwned";
1537 unsigned cnt = getCount();
1538 if (cnt) Out << " (+ " << cnt << ")";
1539 break;
1540 }
1541
1542 case ReturnedNotOwned: {
1543 Out << "ReturnedNotOwned";
1544 unsigned cnt = getCount();
1545 if (cnt) Out << " (+ " << cnt << ")";
1546 break;
1547 }
1548
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001549 case Released:
1550 Out << "Released";
1551 break;
Ted Kremenek6537a642009-03-17 19:42:23 +00001552
1553 case ErrorDeallocGC:
1554 Out << "-dealloc (GC)";
1555 break;
1556
1557 case ErrorDeallocNotOwned:
1558 Out << "-dealloc (not-owned)";
1559 break;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001560
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001561 case ErrorLeak:
1562 Out << "Leaked";
1563 break;
1564
Ted Kremenek311f3d42008-10-22 23:56:21 +00001565 case ErrorLeakReturned:
1566 Out << "Leaked (Bad naming)";
1567 break;
1568
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001569 case ErrorUseAfterRelease:
1570 Out << "Use-After-Release [ERROR]";
1571 break;
1572
1573 case ErrorReleaseNotOwned:
1574 Out << "Release of Not-Owned [ERROR]";
1575 break;
1576 }
1577}
Ted Kremenek0d721572008-03-11 17:48:22 +00001578
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001579} // end anonymous namespace
1580
1581//===----------------------------------------------------------------------===//
1582// RefBindings - State used to track object reference counts.
1583//===----------------------------------------------------------------------===//
1584
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001585typedef llvm::ImmutableMap<SymbolRef, RefVal> RefBindings;
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001586static int RefBIndex = 0;
Ted Kremenek876d8df2009-02-19 23:47:02 +00001587static std::pair<const void*, const void*> LeakProgramPointTag(&RefBIndex, 0);
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001588
1589namespace clang {
Ted Kremenek91781202008-08-17 03:20:02 +00001590 template<>
1591 struct GRStateTrait<RefBindings> : public GRStatePartialTrait<RefBindings> {
1592 static inline void* GDMIndex() { return &RefBIndex; }
1593 };
1594}
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001595
1596//===----------------------------------------------------------------------===//
Ted Kremenekb6578942009-02-24 19:15:11 +00001597// AutoreleaseBindings - State used to track objects in autorelease pools.
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001598//===----------------------------------------------------------------------===//
1599
Ted Kremenekb6578942009-02-24 19:15:11 +00001600typedef llvm::ImmutableMap<SymbolRef, unsigned> ARCounts;
1601typedef llvm::ImmutableMap<SymbolRef, ARCounts> ARPoolContents;
1602typedef llvm::ImmutableList<SymbolRef> ARStack;
Ted Kremenekaac82832009-02-23 17:45:03 +00001603
Ted Kremenekb6578942009-02-24 19:15:11 +00001604static int AutoRCIndex = 0;
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001605static int AutoRBIndex = 0;
1606
Ted Kremenekb6578942009-02-24 19:15:11 +00001607namespace { class VISIBILITY_HIDDEN AutoreleasePoolContents {}; }
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001608namespace { class VISIBILITY_HIDDEN AutoreleaseStack {}; }
Ted Kremenekb6578942009-02-24 19:15:11 +00001609
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001610namespace clang {
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001611template<> struct GRStateTrait<AutoreleaseStack>
Ted Kremenekb6578942009-02-24 19:15:11 +00001612 : public GRStatePartialTrait<ARStack> {
1613 static inline void* GDMIndex() { return &AutoRBIndex; }
1614};
1615
1616template<> struct GRStateTrait<AutoreleasePoolContents>
1617 : public GRStatePartialTrait<ARPoolContents> {
1618 static inline void* GDMIndex() { return &AutoRCIndex; }
1619};
1620} // end clang namespace
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001621
Ted Kremenek681fb352009-03-20 17:34:15 +00001622static SymbolRef GetCurrentAutoreleasePool(const GRState* state) {
1623 ARStack stack = state->get<AutoreleaseStack>();
1624 return stack.isEmpty() ? SymbolRef() : stack.getHead();
1625}
1626
1627static GRStateRef SendAutorelease(GRStateRef state, ARCounts::Factory &F,
1628 SymbolRef sym) {
1629
1630 SymbolRef pool = GetCurrentAutoreleasePool(state);
1631 const ARCounts *cnts = state.get<AutoreleasePoolContents>(pool);
1632 ARCounts newCnts(0);
1633
1634 if (cnts) {
1635 const unsigned *cnt = (*cnts).lookup(sym);
1636 newCnts = F.Add(*cnts, sym, cnt ? *cnt + 1 : 1);
1637 }
1638 else
1639 newCnts = F.Add(F.GetEmptyMap(), sym, 1);
1640
1641 return state.set<AutoreleasePoolContents>(pool, newCnts);
1642}
1643
Ted Kremenek7aef4842008-04-16 20:40:59 +00001644//===----------------------------------------------------------------------===//
1645// Transfer functions.
1646//===----------------------------------------------------------------------===//
1647
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001648namespace {
1649
Ted Kremenek7d421f32008-04-09 23:49:11 +00001650class VISIBILITY_HIDDEN CFRefCount : public GRSimpleVals {
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001651public:
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001652 class BindingsPrinter : public GRState::Printer {
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001653 public:
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001654 virtual void Print(std::ostream& Out, const GRState* state,
1655 const char* nl, const char* sep);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001656 };
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001657
1658private:
Ted Kremenekc26c4692009-02-18 03:48:14 +00001659 typedef llvm::DenseMap<const GRExprEngine::NodeTy*, const RetainSummary*>
1660 SummaryLogTy;
1661
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001662 RetainSummaryManager Summaries;
Ted Kremenekc26c4692009-02-18 03:48:14 +00001663 SummaryLogTy SummaryLog;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001664 const LangOptions& LOpts;
Ted Kremenekb6578942009-02-24 19:15:11 +00001665 ARCounts::Factory ARCountFactory;
Ted Kremenek91781202008-08-17 03:20:02 +00001666
Ted Kremenek708af042009-02-05 06:50:21 +00001667 BugType *useAfterRelease, *releaseNotOwned;
Ted Kremenek6537a642009-03-17 19:42:23 +00001668 BugType *deallocGC, *deallocNotOwned;
Ted Kremenek708af042009-02-05 06:50:21 +00001669 BugType *leakWithinFunction, *leakAtReturn;
1670 BugReporter *BR;
Ted Kremeneka7338b42008-03-11 06:39:11 +00001671
Ted Kremenekb6578942009-02-24 19:15:11 +00001672 GRStateRef Update(GRStateRef state, SymbolRef sym, RefVal V, ArgEffect E,
1673 RefVal::Kind& hasErr);
1674
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001675 void ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
1676 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001677 Expr* NodeExpr, Expr* ErrorExpr,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001678 ExplodedNode<GRState>* Pred,
1679 const GRState* St,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001680 RefVal::Kind hasErr, SymbolRef Sym);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001681
Ted Kremenek0106e202008-10-24 20:32:50 +00001682 std::pair<GRStateRef, bool>
1683 HandleSymbolDeath(GRStateManager& VMgr, const GRState* St,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001684 const Decl* CD, SymbolRef sid, RefVal V, bool& hasLeak);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001685
Ted Kremenekb6578942009-02-24 19:15:11 +00001686public:
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00001687 CFRefCount(ASTContext& Ctx, bool gcenabled, const LangOptions& lopts)
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001688 : Summaries(Ctx, gcenabled),
Ted Kremenek6537a642009-03-17 19:42:23 +00001689 LOpts(lopts), useAfterRelease(0), releaseNotOwned(0),
1690 deallocGC(0), deallocNotOwned(0),
Ted Kremenek708af042009-02-05 06:50:21 +00001691 leakWithinFunction(0), leakAtReturn(0), BR(0) {}
Ted Kremenek1feab292008-04-16 04:28:53 +00001692
Ted Kremenek708af042009-02-05 06:50:21 +00001693 virtual ~CFRefCount() {}
Ted Kremenek7d421f32008-04-09 23:49:11 +00001694
Ted Kremenekbf6babf2009-02-04 23:49:09 +00001695 void RegisterChecks(BugReporter &BR);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001696
Ted Kremenekb0f2b9e2008-08-16 00:49:49 +00001697 virtual void RegisterPrinters(std::vector<GRState::Printer*>& Printers) {
1698 Printers.push_back(new BindingsPrinter());
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001699 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00001700
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001701 bool isGCEnabled() const { return Summaries.isGCEnabled(); }
Ted Kremenekfe30beb2008-04-30 23:47:44 +00001702 const LangOptions& getLangOptions() const { return LOpts; }
1703
Ted Kremenekc26c4692009-02-18 03:48:14 +00001704 const RetainSummary *getSummaryOfNode(const ExplodedNode<GRState> *N) const {
1705 SummaryLogTy::const_iterator I = SummaryLog.find(N);
1706 return I == SummaryLog.end() ? 0 : I->second;
1707 }
1708
Ted Kremeneka7338b42008-03-11 06:39:11 +00001709 // Calls.
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001710
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001711 void EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001712 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001713 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001714 Expr* Ex,
1715 Expr* Receiver,
Ted Kremenek286e9852009-05-04 04:57:00 +00001716 const RetainSummary& Summ,
Ted Kremenek2719e982008-06-17 02:43:46 +00001717 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001718 ExplodedNode<GRState>* Pred);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001719
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001720 virtual void EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekce0767f2008-03-12 21:06:49 +00001721 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001722 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001723 CallExpr* CE, SVal L,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001724 ExplodedNode<GRState>* Pred);
Ted Kremenek10fe66d2008-04-09 01:10:13 +00001725
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001726
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001727 virtual void EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001728 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001729 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001730 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001731 ExplodedNode<GRState>* Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001732
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001733 bool EvalObjCMessageExprAux(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001734 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001735 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001736 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001737 ExplodedNode<GRState>* Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001738
Ted Kremeneka42be302009-02-14 01:43:44 +00001739 // Stores.
1740 virtual void EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val);
1741
Ted Kremenekffefc352008-04-11 22:25:11 +00001742 // End-of-path.
1743
1744 virtual void EvalEndPath(GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001745 GREndPathNodeBuilder<GRState>& Builder);
Ted Kremenekffefc352008-04-11 22:25:11 +00001746
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001747 virtual void EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek541db372008-04-24 23:57:27 +00001748 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001749 GRStmtNodeBuilder<GRState>& Builder,
1750 ExplodedNode<GRState>* Pred,
Ted Kremenek5c0729b2009-01-21 22:26:05 +00001751 Stmt* S, const GRState* state,
1752 SymbolReaper& SymReaper);
1753
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001754 // Return statements.
1755
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001756 virtual void EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001757 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001758 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001759 ReturnStmt* S,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001760 ExplodedNode<GRState>* Pred);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001761
1762 // Assumptions.
1763
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001764 virtual const GRState* EvalAssume(GRStateManager& VMgr,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001765 const GRState* St, SVal Cond,
Ted Kremenekf22f8682008-07-10 22:03:41 +00001766 bool Assumption, bool& isFeasible);
Ted Kremeneka7338b42008-03-11 06:39:11 +00001767};
1768
1769} // end anonymous namespace
1770
Ted Kremenek681fb352009-03-20 17:34:15 +00001771static void PrintPool(std::ostream &Out, SymbolRef Sym, const GRState *state) {
1772 Out << ' ';
Ted Kremenek74556a12009-03-26 03:35:11 +00001773 if (Sym)
1774 Out << Sym->getSymbolID();
Ted Kremenek681fb352009-03-20 17:34:15 +00001775 else
1776 Out << "<pool>";
1777 Out << ":{";
1778
1779 // Get the contents of the pool.
1780 if (const ARCounts *cnts = state->get<AutoreleasePoolContents>(Sym))
1781 for (ARCounts::iterator J=cnts->begin(), EJ=cnts->end(); J != EJ; ++J)
1782 Out << '(' << J.getKey() << ',' << J.getData() << ')';
1783
1784 Out << '}';
1785}
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001786
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001787void CFRefCount::BindingsPrinter::Print(std::ostream& Out, const GRState* state,
1788 const char* nl, const char* sep) {
Ted Kremenek681fb352009-03-20 17:34:15 +00001789
1790
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001791
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001792 RefBindings B = state->get<RefBindings>();
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001793
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001794 if (!B.isEmpty())
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001795 Out << sep << nl;
1796
1797 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
1798 Out << (*I).first << " : ";
1799 (*I).second.print(Out);
1800 Out << nl;
1801 }
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001802
1803 // Print the autorelease stack.
Ted Kremenek681fb352009-03-20 17:34:15 +00001804 Out << sep << nl << "AR pool stack:";
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001805 ARStack stack = state->get<AutoreleaseStack>();
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001806
Ted Kremenek681fb352009-03-20 17:34:15 +00001807 PrintPool(Out, SymbolRef(), state); // Print the caller's pool.
1808 for (ARStack::iterator I=stack.begin(), E=stack.end(); I!=E; ++I)
1809 PrintPool(Out, *I, state);
1810
1811 Out << nl;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001812}
1813
Ted Kremenek47a72422009-04-29 18:50:19 +00001814//===----------------------------------------------------------------------===//
1815// Error reporting.
1816//===----------------------------------------------------------------------===//
1817
1818namespace {
1819
1820 //===-------------===//
1821 // Bug Descriptions. //
1822 //===-------------===//
1823
1824 class VISIBILITY_HIDDEN CFRefBug : public BugType {
1825 protected:
1826 CFRefCount& TF;
1827
1828 CFRefBug(CFRefCount* tf, const char* name)
1829 : BugType(name, "Memory (Core Foundation/Objective-C)"), TF(*tf) {}
1830 public:
1831
1832 CFRefCount& getTF() { return TF; }
1833 const CFRefCount& getTF() const { return TF; }
1834
1835 // FIXME: Eventually remove.
1836 virtual const char* getDescription() const = 0;
1837
1838 virtual bool isLeak() const { return false; }
1839 };
1840
1841 class VISIBILITY_HIDDEN UseAfterRelease : public CFRefBug {
1842 public:
1843 UseAfterRelease(CFRefCount* tf)
1844 : CFRefBug(tf, "Use-after-release") {}
1845
1846 const char* getDescription() const {
1847 return "Reference-counted object is used after it is released";
1848 }
1849 };
1850
1851 class VISIBILITY_HIDDEN BadRelease : public CFRefBug {
1852 public:
1853 BadRelease(CFRefCount* tf) : CFRefBug(tf, "Bad release") {}
1854
1855 const char* getDescription() const {
1856 return "Incorrect decrement of the reference count of an "
1857 "object is not owned at this point by the caller";
1858 }
1859 };
1860
1861 class VISIBILITY_HIDDEN DeallocGC : public CFRefBug {
1862 public:
1863 DeallocGC(CFRefCount *tf) : CFRefBug(tf,
1864 "-dealloc called while using GC") {}
1865
1866 const char *getDescription() const {
1867 return "-dealloc called while using GC";
1868 }
1869 };
1870
1871 class VISIBILITY_HIDDEN DeallocNotOwned : public CFRefBug {
1872 public:
1873 DeallocNotOwned(CFRefCount *tf) : CFRefBug(tf,
1874 "-dealloc sent to non-exclusively owned object") {}
1875
1876 const char *getDescription() const {
1877 return "-dealloc sent to object that may be referenced elsewhere";
1878 }
1879 };
1880
1881 class VISIBILITY_HIDDEN Leak : public CFRefBug {
1882 const bool isReturn;
1883 protected:
1884 Leak(CFRefCount* tf, const char* name, bool isRet)
1885 : CFRefBug(tf, name), isReturn(isRet) {}
1886 public:
1887
1888 const char* getDescription() const { return ""; }
1889
1890 bool isLeak() const { return true; }
1891 };
1892
1893 class VISIBILITY_HIDDEN LeakAtReturn : public Leak {
1894 public:
1895 LeakAtReturn(CFRefCount* tf, const char* name)
1896 : Leak(tf, name, true) {}
1897 };
1898
1899 class VISIBILITY_HIDDEN LeakWithinFunction : public Leak {
1900 public:
1901 LeakWithinFunction(CFRefCount* tf, const char* name)
1902 : Leak(tf, name, false) {}
1903 };
1904
1905 //===---------===//
1906 // Bug Reports. //
1907 //===---------===//
1908
1909 class VISIBILITY_HIDDEN CFRefReport : public RangedBugReport {
1910 protected:
1911 SymbolRef Sym;
1912 const CFRefCount &TF;
1913 public:
1914 CFRefReport(CFRefBug& D, const CFRefCount &tf,
1915 ExplodedNode<GRState> *n, SymbolRef sym)
1916 : RangedBugReport(D, D.getDescription(), n), Sym(sym), TF(tf) {}
1917
1918 virtual ~CFRefReport() {}
1919
1920 CFRefBug& getBugType() {
1921 return (CFRefBug&) RangedBugReport::getBugType();
1922 }
1923 const CFRefBug& getBugType() const {
1924 return (const CFRefBug&) RangedBugReport::getBugType();
1925 }
1926
1927 virtual void getRanges(BugReporter& BR, const SourceRange*& beg,
1928 const SourceRange*& end) {
1929
1930 if (!getBugType().isLeak())
1931 RangedBugReport::getRanges(BR, beg, end);
1932 else
1933 beg = end = 0;
1934 }
1935
1936 SymbolRef getSymbol() const { return Sym; }
1937
1938 PathDiagnosticPiece* getEndPath(BugReporter& BR,
1939 const ExplodedNode<GRState>* N);
1940
1941 std::pair<const char**,const char**> getExtraDescriptiveText();
1942
1943 PathDiagnosticPiece* VisitNode(const ExplodedNode<GRState>* N,
1944 const ExplodedNode<GRState>* PrevN,
1945 const ExplodedGraph<GRState>& G,
1946 BugReporter& BR,
1947 NodeResolver& NR);
1948 };
1949
1950 class VISIBILITY_HIDDEN CFRefLeakReport : public CFRefReport {
1951 SourceLocation AllocSite;
1952 const MemRegion* AllocBinding;
1953 public:
1954 CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
1955 ExplodedNode<GRState> *n, SymbolRef sym,
1956 GRExprEngine& Eng);
1957
1958 PathDiagnosticPiece* getEndPath(BugReporter& BR,
1959 const ExplodedNode<GRState>* N);
1960
1961 SourceLocation getLocation() const { return AllocSite; }
1962 };
1963} // end anonymous namespace
1964
1965void CFRefCount::RegisterChecks(BugReporter& BR) {
1966 useAfterRelease = new UseAfterRelease(this);
1967 BR.Register(useAfterRelease);
1968
1969 releaseNotOwned = new BadRelease(this);
1970 BR.Register(releaseNotOwned);
1971
1972 deallocGC = new DeallocGC(this);
1973 BR.Register(deallocGC);
1974
1975 deallocNotOwned = new DeallocNotOwned(this);
1976 BR.Register(deallocNotOwned);
1977
1978 // First register "return" leaks.
1979 const char* name = 0;
1980
1981 if (isGCEnabled())
1982 name = "Leak of returned object when using garbage collection";
1983 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
1984 name = "Leak of returned object when not using garbage collection (GC) in "
1985 "dual GC/non-GC code";
1986 else {
1987 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
1988 name = "Leak of returned object";
1989 }
1990
1991 leakAtReturn = new LeakAtReturn(this, name);
1992 BR.Register(leakAtReturn);
1993
1994 // Second, register leaks within a function/method.
1995 if (isGCEnabled())
1996 name = "Leak of object when using garbage collection";
1997 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
1998 name = "Leak of object when not using garbage collection (GC) in "
1999 "dual GC/non-GC code";
2000 else {
2001 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2002 name = "Leak";
2003 }
2004
2005 leakWithinFunction = new LeakWithinFunction(this, name);
2006 BR.Register(leakWithinFunction);
2007
2008 // Save the reference to the BugReporter.
2009 this->BR = &BR;
2010}
2011
2012static const char* Msgs[] = {
2013 // GC only
2014 "Code is compiled to only use garbage collection",
2015 // No GC.
2016 "Code is compiled to use reference counts",
2017 // Hybrid, with GC.
2018 "Code is compiled to use either garbage collection (GC) or reference counts"
2019 " (non-GC). The bug occurs with GC enabled",
2020 // Hybrid, without GC
2021 "Code is compiled to use either garbage collection (GC) or reference counts"
2022 " (non-GC). The bug occurs in non-GC mode"
2023};
2024
2025std::pair<const char**,const char**> CFRefReport::getExtraDescriptiveText() {
2026 CFRefCount& TF = static_cast<CFRefBug&>(getBugType()).getTF();
2027
2028 switch (TF.getLangOptions().getGCMode()) {
2029 default:
2030 assert(false);
2031
2032 case LangOptions::GCOnly:
2033 assert (TF.isGCEnabled());
2034 return std::make_pair(&Msgs[0], &Msgs[0]+1);
2035
2036 case LangOptions::NonGC:
2037 assert (!TF.isGCEnabled());
2038 return std::make_pair(&Msgs[1], &Msgs[1]+1);
2039
2040 case LangOptions::HybridGC:
2041 if (TF.isGCEnabled())
2042 return std::make_pair(&Msgs[2], &Msgs[2]+1);
2043 else
2044 return std::make_pair(&Msgs[3], &Msgs[3]+1);
2045 }
2046}
2047
2048static inline bool contains(const llvm::SmallVectorImpl<ArgEffect>& V,
2049 ArgEffect X) {
2050 for (llvm::SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
2051 I!=E; ++I)
2052 if (*I == X) return true;
2053
2054 return false;
2055}
2056
2057PathDiagnosticPiece* CFRefReport::VisitNode(const ExplodedNode<GRState>* N,
2058 const ExplodedNode<GRState>* PrevN,
2059 const ExplodedGraph<GRState>& G,
2060 BugReporter& BR,
2061 NodeResolver& NR) {
2062
2063 // Check if the type state has changed.
2064 GRStateManager &StMgr = cast<GRBugReporter>(BR).getStateManager();
2065 GRStateRef PrevSt(PrevN->getState(), StMgr);
2066 GRStateRef CurrSt(N->getState(), StMgr);
2067
2068 const RefVal* CurrT = CurrSt.get<RefBindings>(Sym);
2069 if (!CurrT) return NULL;
2070
2071 const RefVal& CurrV = *CurrT;
2072 const RefVal* PrevT = PrevSt.get<RefBindings>(Sym);
2073
2074 // Create a string buffer to constain all the useful things we want
2075 // to tell the user.
2076 std::string sbuf;
2077 llvm::raw_string_ostream os(sbuf);
2078
2079 // This is the allocation site since the previous node had no bindings
2080 // for this symbol.
2081 if (!PrevT) {
2082 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2083
2084 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2085 // Get the name of the callee (if it is available).
2086 SVal X = CurrSt.GetSValAsScalarOrLoc(CE->getCallee());
2087 if (const FunctionDecl* FD = X.getAsFunctionDecl())
2088 os << "Call to function '" << FD->getNameAsString() <<'\'';
2089 else
2090 os << "function call";
2091 }
2092 else {
2093 assert (isa<ObjCMessageExpr>(S));
2094 os << "Method";
2095 }
2096
2097 if (CurrV.getObjKind() == RetEffect::CF) {
2098 os << " returns a Core Foundation object with a ";
2099 }
2100 else {
2101 assert (CurrV.getObjKind() == RetEffect::ObjC);
2102 os << " returns an Objective-C object with a ";
2103 }
2104
2105 if (CurrV.isOwned()) {
2106 os << "+1 retain count (owning reference).";
2107
2108 if (static_cast<CFRefBug&>(getBugType()).getTF().isGCEnabled()) {
2109 assert(CurrV.getObjKind() == RetEffect::CF);
2110 os << " "
2111 "Core Foundation objects are not automatically garbage collected.";
2112 }
2113 }
2114 else {
2115 assert (CurrV.isNotOwned());
2116 os << "+0 retain count (non-owning reference).";
2117 }
2118
2119 PathDiagnosticLocation Pos(S, BR.getContext().getSourceManager());
2120 return new PathDiagnosticEventPiece(Pos, os.str());
2121 }
2122
2123 // Gather up the effects that were performed on the object at this
2124 // program point
2125 llvm::SmallVector<ArgEffect, 2> AEffects;
2126
2127 if (const RetainSummary *Summ = TF.getSummaryOfNode(NR.getOriginalNode(N))) {
2128 // We only have summaries attached to nodes after evaluating CallExpr and
2129 // ObjCMessageExprs.
2130 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2131
2132 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2133 // Iterate through the parameter expressions and see if the symbol
2134 // was ever passed as an argument.
2135 unsigned i = 0;
2136
2137 for (CallExpr::arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
2138 AI!=AE; ++AI, ++i) {
2139
2140 // Retrieve the value of the argument. Is it the symbol
2141 // we are interested in?
2142 if (CurrSt.GetSValAsScalarOrLoc(*AI).getAsLocSymbol() != Sym)
2143 continue;
2144
2145 // We have an argument. Get the effect!
2146 AEffects.push_back(Summ->getArg(i));
2147 }
2148 }
2149 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
2150 if (Expr *receiver = ME->getReceiver())
2151 if (CurrSt.GetSValAsScalarOrLoc(receiver).getAsLocSymbol() == Sym) {
2152 // The symbol we are tracking is the receiver.
2153 AEffects.push_back(Summ->getReceiverEffect());
2154 }
2155 }
2156 }
2157
2158 do {
2159 // Get the previous type state.
2160 RefVal PrevV = *PrevT;
2161
2162 // Specially handle -dealloc.
2163 if (!TF.isGCEnabled() && contains(AEffects, Dealloc)) {
2164 // Determine if the object's reference count was pushed to zero.
2165 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2166 // We may not have transitioned to 'release' if we hit an error.
2167 // This case is handled elsewhere.
2168 if (CurrV.getKind() == RefVal::Released) {
2169 assert(CurrV.getCount() == 0);
2170 os << "Object released by directly sending the '-dealloc' message";
2171 break;
2172 }
2173 }
2174
2175 // Specially handle CFMakeCollectable and friends.
2176 if (contains(AEffects, MakeCollectable)) {
2177 // Get the name of the function.
2178 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2179 SVal X = CurrSt.GetSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee());
2180 const FunctionDecl* FD = X.getAsFunctionDecl();
2181 const std::string& FName = FD->getNameAsString();
2182
2183 if (TF.isGCEnabled()) {
2184 // Determine if the object's reference count was pushed to zero.
2185 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2186
2187 os << "In GC mode a call to '" << FName
2188 << "' decrements an object's retain count and registers the "
2189 "object with the garbage collector. ";
2190
2191 if (CurrV.getKind() == RefVal::Released) {
2192 assert(CurrV.getCount() == 0);
2193 os << "Since it now has a 0 retain count the object can be "
2194 "automatically collected by the garbage collector.";
2195 }
2196 else
2197 os << "An object must have a 0 retain count to be garbage collected. "
2198 "After this call its retain count is +" << CurrV.getCount()
2199 << '.';
2200 }
2201 else
2202 os << "When GC is not enabled a call to '" << FName
2203 << "' has no effect on its argument.";
2204
2205 // Nothing more to say.
2206 break;
2207 }
2208
2209 // Determine if the typestate has changed.
2210 if (!(PrevV == CurrV))
2211 switch (CurrV.getKind()) {
2212 case RefVal::Owned:
2213 case RefVal::NotOwned:
2214
2215 if (PrevV.getCount() == CurrV.getCount())
2216 return 0;
2217
2218 if (PrevV.getCount() > CurrV.getCount())
2219 os << "Reference count decremented.";
2220 else
2221 os << "Reference count incremented.";
2222
2223 if (unsigned Count = CurrV.getCount())
2224 os << " The object now has a +" << Count << " retain count.";
2225
2226 if (PrevV.getKind() == RefVal::Released) {
2227 assert(TF.isGCEnabled() && CurrV.getCount() > 0);
2228 os << " The object is not eligible for garbage collection until the "
2229 "retain count reaches 0 again.";
2230 }
2231
2232 break;
2233
2234 case RefVal::Released:
2235 os << "Object released.";
2236 break;
2237
2238 case RefVal::ReturnedOwned:
2239 os << "Object returned to caller as an owning reference (single retain "
2240 "count transferred to caller).";
2241 break;
2242
2243 case RefVal::ReturnedNotOwned:
2244 os << "Object returned to caller with a +0 (non-owning) retain count.";
2245 break;
2246
2247 default:
2248 return NULL;
2249 }
2250
2251 // Emit any remaining diagnostics for the argument effects (if any).
2252 for (llvm::SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
2253 E=AEffects.end(); I != E; ++I) {
2254
2255 // A bunch of things have alternate behavior under GC.
2256 if (TF.isGCEnabled())
2257 switch (*I) {
2258 default: break;
2259 case Autorelease:
2260 os << "In GC mode an 'autorelease' has no effect.";
2261 continue;
2262 case IncRefMsg:
2263 os << "In GC mode the 'retain' message has no effect.";
2264 continue;
2265 case DecRefMsg:
2266 os << "In GC mode the 'release' message has no effect.";
2267 continue;
2268 }
2269 }
2270 } while(0);
2271
2272 if (os.str().empty())
2273 return 0; // We have nothing to say!
2274
2275 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2276 PathDiagnosticLocation Pos(S, BR.getContext().getSourceManager());
2277 PathDiagnosticPiece* P = new PathDiagnosticEventPiece(Pos, os.str());
2278
2279 // Add the range by scanning the children of the statement for any bindings
2280 // to Sym.
2281 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I)
2282 if (Expr* Exp = dyn_cast_or_null<Expr>(*I))
2283 if (CurrSt.GetSValAsScalarOrLoc(Exp).getAsLocSymbol() == Sym) {
2284 P->addRange(Exp->getSourceRange());
2285 break;
2286 }
2287
2288 return P;
2289}
2290
2291namespace {
2292 class VISIBILITY_HIDDEN FindUniqueBinding :
2293 public StoreManager::BindingsHandler {
2294 SymbolRef Sym;
2295 const MemRegion* Binding;
2296 bool First;
2297
2298 public:
2299 FindUniqueBinding(SymbolRef sym) : Sym(sym), Binding(0), First(true) {}
2300
2301 bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
2302 SVal val) {
2303
2304 SymbolRef SymV = val.getAsSymbol();
2305 if (!SymV || SymV != Sym)
2306 return true;
2307
2308 if (Binding) {
2309 First = false;
2310 return false;
2311 }
2312 else
2313 Binding = R;
2314
2315 return true;
2316 }
2317
2318 operator bool() { return First && Binding; }
2319 const MemRegion* getRegion() { return Binding; }
2320 };
2321}
2322
2323static std::pair<const ExplodedNode<GRState>*,const MemRegion*>
2324GetAllocationSite(GRStateManager& StateMgr, const ExplodedNode<GRState>* N,
2325 SymbolRef Sym) {
2326
2327 // Find both first node that referred to the tracked symbol and the
2328 // memory location that value was store to.
2329 const ExplodedNode<GRState>* Last = N;
2330 const MemRegion* FirstBinding = 0;
2331
2332 while (N) {
2333 const GRState* St = N->getState();
2334 RefBindings B = St->get<RefBindings>();
2335
2336 if (!B.lookup(Sym))
2337 break;
2338
2339 FindUniqueBinding FB(Sym);
2340 StateMgr.iterBindings(St, FB);
2341 if (FB) FirstBinding = FB.getRegion();
2342
2343 Last = N;
2344 N = N->pred_empty() ? NULL : *(N->pred_begin());
2345 }
2346
2347 return std::make_pair(Last, FirstBinding);
2348}
2349
2350PathDiagnosticPiece*
2351CFRefReport::getEndPath(BugReporter& br, const ExplodedNode<GRState>* EndN) {
2352 // Tell the BugReporter to report cases when the tracked symbol is
2353 // assigned to different variables, etc.
2354 GRBugReporter& BR = cast<GRBugReporter>(br);
2355 cast<GRBugReporter>(BR).addNotableSymbol(Sym);
2356 return RangedBugReport::getEndPath(BR, EndN);
2357}
2358
2359PathDiagnosticPiece*
2360CFRefLeakReport::getEndPath(BugReporter& br, const ExplodedNode<GRState>* EndN){
2361
2362 GRBugReporter& BR = cast<GRBugReporter>(br);
2363 // Tell the BugReporter to report cases when the tracked symbol is
2364 // assigned to different variables, etc.
2365 cast<GRBugReporter>(BR).addNotableSymbol(Sym);
2366
2367 // We are reporting a leak. Walk up the graph to get to the first node where
2368 // the symbol appeared, and also get the first VarDecl that tracked object
2369 // is stored to.
2370 const ExplodedNode<GRState>* AllocNode = 0;
2371 const MemRegion* FirstBinding = 0;
2372
2373 llvm::tie(AllocNode, FirstBinding) =
2374 GetAllocationSite(BR.getStateManager(), EndN, Sym);
2375
2376 // Get the allocate site.
2377 assert(AllocNode);
2378 Stmt* FirstStmt = cast<PostStmt>(AllocNode->getLocation()).getStmt();
2379
2380 SourceManager& SMgr = BR.getContext().getSourceManager();
2381 unsigned AllocLine =SMgr.getInstantiationLineNumber(FirstStmt->getLocStart());
2382
2383 // Compute an actual location for the leak. Sometimes a leak doesn't
2384 // occur at an actual statement (e.g., transition between blocks; end
2385 // of function) so we need to walk the graph and compute a real location.
2386 const ExplodedNode<GRState>* LeakN = EndN;
2387 PathDiagnosticLocation L;
2388
2389 while (LeakN) {
2390 ProgramPoint P = LeakN->getLocation();
2391
2392 if (const PostStmt *PS = dyn_cast<PostStmt>(&P)) {
2393 L = PathDiagnosticLocation(PS->getStmt()->getLocStart(), SMgr);
2394 break;
2395 }
2396 else if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
2397 if (const Stmt* Term = BE->getSrc()->getTerminator()) {
2398 L = PathDiagnosticLocation(Term->getLocStart(), SMgr);
2399 break;
2400 }
2401 }
2402
2403 LeakN = LeakN->succ_empty() ? 0 : *(LeakN->succ_begin());
2404 }
2405
2406 if (!L.isValid()) {
Ted Kremenek0a6913d2009-04-29 21:31:59 +00002407 const Decl &D = BR.getStateManager().getCodeDecl();
2408 L = PathDiagnosticLocation(D.getBodyRBrace(BR.getContext()), SMgr);
Ted Kremenek47a72422009-04-29 18:50:19 +00002409 }
2410
2411 std::string sbuf;
2412 llvm::raw_string_ostream os(sbuf);
2413
2414 os << "Object allocated on line " << AllocLine;
2415
2416 if (FirstBinding)
2417 os << " and stored into '" << FirstBinding->getString() << '\'';
2418
2419 // Get the retain count.
2420 const RefVal* RV = EndN->getState()->get<RefBindings>(Sym);
2421
2422 if (RV->getKind() == RefVal::ErrorLeakReturned) {
2423 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
2424 // ojbects. Only "copy", "alloc", "retain" and "new" transfer ownership
2425 // to the caller for NS objects.
2426 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(BR.getGraph().getCodeDecl());
2427 os << " is returned from a method whose name ('"
Ted Kremenek314b1952009-04-29 23:03:22 +00002428 << MD.getSelector().getAsString()
Ted Kremenek47a72422009-04-29 18:50:19 +00002429 << "') does not contain 'copy' or otherwise starts with"
2430 " 'new' or 'alloc'. This violates the naming convention rules given"
Ted Kremenek2a410c92009-04-29 22:25:52 +00002431 " in the Memory Management Guide for Cocoa (object leaked)";
Ted Kremenek47a72422009-04-29 18:50:19 +00002432 }
2433 else
2434 os << " is no longer referenced after this point and has a retain count of"
Ted Kremenek2a410c92009-04-29 22:25:52 +00002435 " +" << RV->getCount() << " (object leaked)";
Ted Kremenek47a72422009-04-29 18:50:19 +00002436
2437 return new PathDiagnosticEventPiece(L, os.str());
2438}
2439
2440
2441CFRefLeakReport::CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2442 ExplodedNode<GRState> *n,
2443 SymbolRef sym, GRExprEngine& Eng)
2444: CFRefReport(D, tf, n, sym)
2445{
2446
2447 // Most bug reports are cached at the location where they occured.
2448 // With leaks, we want to unique them by the location where they were
2449 // allocated, and only report a single path. To do this, we need to find
2450 // the allocation site of a piece of tracked memory, which we do via a
2451 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2452 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2453 // that all ancestor nodes that represent the allocation site have the
2454 // same SourceLocation.
2455 const ExplodedNode<GRState>* AllocNode = 0;
2456
2457 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding.
2458 GetAllocationSite(Eng.getStateManager(), getEndNode(), getSymbol());
2459
2460 // Get the SourceLocation for the allocation site.
2461 ProgramPoint P = AllocNode->getLocation();
2462 AllocSite = cast<PostStmt>(P).getStmt()->getLocStart();
2463
2464 // Fill in the description of the bug.
2465 Description.clear();
2466 llvm::raw_string_ostream os(Description);
2467 SourceManager& SMgr = Eng.getContext().getSourceManager();
2468 unsigned AllocLine = SMgr.getInstantiationLineNumber(AllocSite);
Ted Kremenek2e9d0302009-05-02 19:05:19 +00002469 os << "Potential leak ";
2470 if (tf.isGCEnabled()) {
2471 os << "(when using garbage collection) ";
2472 }
2473 os << "of an object allocated on line " << AllocLine;
Ted Kremenek47a72422009-04-29 18:50:19 +00002474
2475 // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2476 if (AllocBinding)
2477 os << " and stored into '" << AllocBinding->getString() << '\'';
2478}
2479
2480//===----------------------------------------------------------------------===//
2481// Main checker logic.
2482//===----------------------------------------------------------------------===//
2483
Ted Kremenek272aa852008-06-25 21:21:56 +00002484/// GetReturnType - Used to get the return type of a message expression or
2485/// function call with the intention of affixing that type to a tracked symbol.
2486/// While the the return type can be queried directly from RetEx, when
2487/// invoking class methods we augment to the return type to be that of
2488/// a pointer to the class (as opposed it just being id).
2489static QualType GetReturnType(Expr* RetE, ASTContext& Ctx) {
2490
2491 QualType RetTy = RetE->getType();
2492
2493 // FIXME: We aren't handling id<...>.
Chris Lattnerb724ab22008-07-26 22:36:27 +00002494 const PointerType* PT = RetTy->getAsPointerType();
Ted Kremenek272aa852008-06-25 21:21:56 +00002495 if (!PT)
2496 return RetTy;
2497
2498 // If RetEx is not a message expression just return its type.
2499 // If RetEx is a message expression, return its types if it is something
2500 /// more specific than id.
2501
2502 ObjCMessageExpr* ME = dyn_cast<ObjCMessageExpr>(RetE);
2503
Steve Naroff17c03822009-02-12 17:52:19 +00002504 if (!ME || !Ctx.isObjCIdStructType(PT->getPointeeType()))
Ted Kremenek272aa852008-06-25 21:21:56 +00002505 return RetTy;
2506
2507 ObjCInterfaceDecl* D = ME->getClassInfo().first;
2508
2509 // At this point we know the return type of the message expression is id.
2510 // If we have an ObjCInterceDecl, we know this is a call to a class method
2511 // whose type we can resolve. In such cases, promote the return type to
2512 // Class*.
2513 return !D ? RetTy : Ctx.getPointerType(Ctx.getObjCInterfaceType(D));
2514}
2515
2516
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002517void CFRefCount::EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002518 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002519 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002520 Expr* Ex,
2521 Expr* Receiver,
Ted Kremenek286e9852009-05-04 04:57:00 +00002522 const RetainSummary& Summ,
Zhongxing Xucac107a2009-04-20 05:24:46 +00002523 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002524 ExplodedNode<GRState>* Pred) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002525
Ted Kremeneka7338b42008-03-11 06:39:11 +00002526 // Get the state.
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002527 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenek0106e202008-10-24 20:32:50 +00002528 ASTContext& Ctx = Eng.getStateManager().getContext();
Ted Kremenek227c5372008-05-06 02:41:27 +00002529
2530 // Evaluate the effect of the arguments.
Ted Kremenek1feab292008-04-16 04:28:53 +00002531 RefVal::Kind hasErr = (RefVal::Kind) 0;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002532 unsigned idx = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002533 Expr* ErrorExpr = NULL;
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002534 SymbolRef ErrorSym = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002535
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002536 for (ExprIterator I = arg_beg; I != arg_end; ++I, ++idx) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002537 SVal V = state.GetSValAsScalarOrLoc(*I);
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002538 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002539
Ted Kremenek74556a12009-03-26 03:35:11 +00002540 if (Sym)
Ted Kremenekb6578942009-02-24 19:15:11 +00002541 if (RefBindings::data_type* T = state.get<RefBindings>(Sym)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002542 state = Update(state, Sym, *T, Summ.getArg(idx), hasErr);
Ted Kremenekb6578942009-02-24 19:15:11 +00002543 if (hasErr) {
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002544 ErrorExpr = *I;
Ted Kremenek6064a362008-07-07 16:21:19 +00002545 ErrorSym = Sym;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002546 break;
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002547 }
2548 continue;
Ted Kremenekb6578942009-02-24 19:15:11 +00002549 }
Ted Kremenekede40b72008-07-09 18:11:16 +00002550
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002551 if (isa<Loc>(V)) {
2552 if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(&V)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002553 if (Summ.getArg(idx) == DoNothingByRef)
Ted Kremenekede40b72008-07-09 18:11:16 +00002554 continue;
2555
2556 // Invalidate the value of the variable passed by reference.
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002557
2558 // FIXME: Either this logic should also be replicated in GRSimpleVals
2559 // or should be pulled into a separate "constraint engine."
Ted Kremenekede40b72008-07-09 18:11:16 +00002560
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002561 // FIXME: We can have collisions on the conjured symbol if the
2562 // expression *I also creates conjured symbols. We probably want
2563 // to identify conjured symbols by an expression pair: the enclosing
2564 // expression (the context) and the expression itself. This should
Ted Kremenekede40b72008-07-09 18:11:16 +00002565 // disambiguate conjured symbols.
Ted Kremenekb15eba42008-10-04 05:50:14 +00002566
Ted Kremenek38a4b4b2008-10-17 20:28:54 +00002567 const TypedRegion* R = dyn_cast<TypedRegion>(MR->getRegion());
Zhongxing Xub9d47a42009-04-29 02:30:09 +00002568
Ted Kremenek53b24182009-03-04 22:56:43 +00002569 if (R) {
Ted Kremenek618c6cd2008-12-18 23:34:57 +00002570 // Is the invalidated variable something that we were tracking?
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002571 SymbolRef Sym = state.GetSValAsScalarOrLoc(R).getAsLocSymbol();
Ted Kremenek618c6cd2008-12-18 23:34:57 +00002572
Ted Kremenek53b24182009-03-04 22:56:43 +00002573 // Remove any existing reference-count binding.
Ted Kremenek74556a12009-03-26 03:35:11 +00002574 if (Sym) state = state.remove<RefBindings>(Sym);
Ted Kremenekb15eba42008-10-04 05:50:14 +00002575
Ted Kremenek53b24182009-03-04 22:56:43 +00002576 if (R->isBoundable(Ctx)) {
2577 // Set the value of the variable to be a conjured symbol.
2578 unsigned Count = Builder.getCurrentBlockCount();
2579 QualType T = R->getRValueType(Ctx);
2580
Zhongxing Xu079dc352009-04-09 06:03:54 +00002581 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())){
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002582 ValueManager &ValMgr = Eng.getValueManager();
2583 SVal V = ValMgr.getConjuredSymbolVal(*I, T, Count);
Zhongxing Xu079dc352009-04-09 06:03:54 +00002584 state = state.BindLoc(Loc::MakeVal(R), V);
Ted Kremenek53b24182009-03-04 22:56:43 +00002585 }
2586 else if (const RecordType *RT = T->getAsStructureType()) {
2587 // Handle structs in a not so awesome way. Here we just
2588 // eagerly bind new symbols to the fields. In reality we
2589 // should have the store manager handle this. The idea is just
2590 // to prototype some basic functionality here. All of this logic
2591 // should one day soon just go away.
2592 const RecordDecl *RD = RT->getDecl()->getDefinition(Ctx);
2593
2594 // No record definition. There is nothing we can do.
2595 if (!RD)
2596 continue;
2597
2598 MemRegionManager &MRMgr = state.getManager().getRegionManager();
2599
2600 // Iterate through the fields and construct new symbols.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002601 for (RecordDecl::field_iterator FI=RD->field_begin(Ctx),
2602 FE=RD->field_end(Ctx); FI!=FE; ++FI) {
Ted Kremenek53b24182009-03-04 22:56:43 +00002603
2604 // For now just handle scalar fields.
2605 FieldDecl *FD = *FI;
2606 QualType FT = FD->getType();
2607
2608 if (Loc::IsLocType(FT) ||
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002609 (FT->isIntegerType() && FT->isScalarType())) {
Ted Kremenek53b24182009-03-04 22:56:43 +00002610 const FieldRegion* FR = MRMgr.getFieldRegion(FD, R);
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002611 ValueManager &ValMgr = Eng.getValueManager();
2612 SVal V = ValMgr.getConjuredSymbolVal(*I, FT, Count);
Zhongxing Xuc458e322009-04-09 06:32:20 +00002613 state = state.BindLoc(Loc::MakeVal(FR), V);
Ted Kremenek53b24182009-03-04 22:56:43 +00002614 }
2615 }
2616 }
2617 else {
2618 // Just blast away other values.
2619 state = state.BindLoc(*MR, UnknownVal());
2620 }
Ted Kremenek8f90e712008-10-17 22:23:12 +00002621 }
Ted Kremenekb15eba42008-10-04 05:50:14 +00002622 }
2623 else
Ted Kremenek09102db2008-11-12 19:22:09 +00002624 state = state.BindLoc(*MR, UnknownVal());
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002625 }
2626 else {
2627 // Nuke all other arguments passed by reference.
Zhongxing Xu097fc982008-10-17 05:57:07 +00002628 state = state.Unbind(cast<Loc>(V));
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002629 }
Ted Kremeneke4924202008-04-11 20:51:02 +00002630 }
Zhongxing Xu097fc982008-10-17 05:57:07 +00002631 else if (isa<nonloc::LocAsInteger>(V))
2632 state = state.Unbind(cast<nonloc::LocAsInteger>(V).getLoc());
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002633 }
Ted Kremenek1feab292008-04-16 04:28:53 +00002634
Ted Kremenek272aa852008-06-25 21:21:56 +00002635 // Evaluate the effect on the message receiver.
Ted Kremenek227c5372008-05-06 02:41:27 +00002636 if (!ErrorExpr && Receiver) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002637 SymbolRef Sym = state.GetSValAsScalarOrLoc(Receiver).getAsLocSymbol();
Ted Kremenek74556a12009-03-26 03:35:11 +00002638 if (Sym) {
Ted Kremenekb6578942009-02-24 19:15:11 +00002639 if (const RefVal* T = state.get<RefBindings>(Sym)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002640 state = Update(state, Sym, *T, Summ.getReceiverEffect(), hasErr);
Ted Kremenekb6578942009-02-24 19:15:11 +00002641 if (hasErr) {
Ted Kremenek227c5372008-05-06 02:41:27 +00002642 ErrorExpr = Receiver;
Ted Kremenek6064a362008-07-07 16:21:19 +00002643 ErrorSym = Sym;
Ted Kremenek227c5372008-05-06 02:41:27 +00002644 }
Ted Kremenekb6578942009-02-24 19:15:11 +00002645 }
Ted Kremenek227c5372008-05-06 02:41:27 +00002646 }
2647 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002648
Ted Kremenek272aa852008-06-25 21:21:56 +00002649 // Process any errors.
Ted Kremenek1feab292008-04-16 04:28:53 +00002650 if (hasErr) {
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002651 ProcessNonLeakError(Dst, Builder, Ex, ErrorExpr, Pred, state,
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002652 hasErr, ErrorSym);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002653 return;
Ted Kremenek0d721572008-03-11 17:48:22 +00002654 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002655
Ted Kremenekf2717b02008-07-18 17:24:20 +00002656 // Consult the summary for the return value.
Ted Kremenek286e9852009-05-04 04:57:00 +00002657 RetEffect RE = Summ.getRetEffect();
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002658
2659 switch (RE.getKind()) {
2660 default:
2661 assert (false && "Unhandled RetEffect."); break;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002662
Ted Kremenek8f90e712008-10-17 22:23:12 +00002663 case RetEffect::NoRet: {
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002664
Ted Kremenek455dd862008-04-11 20:23:24 +00002665 // Make up a symbol for the return value (not reference counted).
Ted Kremeneke4924202008-04-11 20:51:02 +00002666 // FIXME: This is basically copy-and-paste from GRSimpleVals. We
2667 // should compose behavior, not copy it.
Ted Kremenek455dd862008-04-11 20:23:24 +00002668
Ted Kremenek8f90e712008-10-17 22:23:12 +00002669 // FIXME: We eventually should handle structs and other compound types
2670 // that are returned by value.
2671
2672 QualType T = Ex->getType();
2673
Ted Kremenek79413a52008-11-13 06:10:40 +00002674 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())) {
Ted Kremenek455dd862008-04-11 20:23:24 +00002675 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002676 ValueManager &ValMgr = Eng.getValueManager();
2677 SVal X = ValMgr.getConjuredSymbolVal(Ex, T, Count);
Ted Kremenek09102db2008-11-12 19:22:09 +00002678 state = state.BindExpr(Ex, X, false);
Ted Kremenek455dd862008-04-11 20:23:24 +00002679 }
2680
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002681 break;
Ted Kremenek8f90e712008-10-17 22:23:12 +00002682 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002683
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002684 case RetEffect::Alias: {
Ted Kremenek272aa852008-06-25 21:21:56 +00002685 unsigned idx = RE.getIndex();
Ted Kremenek2719e982008-06-17 02:43:46 +00002686 assert (arg_end >= arg_beg);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002687 assert (idx < (unsigned) (arg_end - arg_beg));
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002688 SVal V = state.GetSValAsScalarOrLoc(*(arg_beg+idx));
Ted Kremenek09102db2008-11-12 19:22:09 +00002689 state = state.BindExpr(Ex, V, false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002690 break;
2691 }
2692
Ted Kremenek227c5372008-05-06 02:41:27 +00002693 case RetEffect::ReceiverAlias: {
2694 assert (Receiver);
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002695 SVal V = state.GetSValAsScalarOrLoc(Receiver);
Ted Kremenek09102db2008-11-12 19:22:09 +00002696 state = state.BindExpr(Ex, V, false);
Ted Kremenek227c5372008-05-06 02:41:27 +00002697 break;
2698 }
2699
Ted Kremenek6a1cc252008-06-23 18:02:52 +00002700 case RetEffect::OwnedAllocatedSymbol:
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002701 case RetEffect::OwnedSymbol: {
2702 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke9e726e2009-04-09 16:13:17 +00002703 ValueManager &ValMgr = Eng.getValueManager();
2704 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
2705 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
2706 state = state.set<RefBindings>(Sym, RefVal::makeOwned(RE.getObjKind(),
2707 RetT));
2708 state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenek45c52a12009-03-09 22:46:49 +00002709
2710 // FIXME: Add a flag to the checker where allocations are assumed to
2711 // *not fail.
2712#if 0
Ted Kremeneke62fd052009-01-28 22:27:59 +00002713 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) {
2714 bool isFeasible;
2715 state = state.Assume(loc::SymbolVal(Sym), true, isFeasible);
2716 assert(isFeasible && "Cannot assume fresh symbol is non-null.");
2717 }
Ted Kremenek45c52a12009-03-09 22:46:49 +00002718#endif
Ted Kremenek6a1cc252008-06-23 18:02:52 +00002719
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002720 break;
2721 }
Ted Kremenek382fb4e2009-04-27 19:14:45 +00002722
2723 case RetEffect::GCNotOwnedSymbol:
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002724 case RetEffect::NotOwnedSymbol: {
2725 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke9e726e2009-04-09 16:13:17 +00002726 ValueManager &ValMgr = Eng.getValueManager();
2727 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
2728 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
2729 state = state.set<RefBindings>(Sym, RefVal::makeNotOwned(RE.getObjKind(),
2730 RetT));
2731 state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002732 break;
2733 }
2734 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002735
Ted Kremenek0dd65012009-02-18 02:00:25 +00002736 // Generate a sink node if we are at the end of a path.
2737 GRExprEngine::NodeTy *NewNode =
Ted Kremenek286e9852009-05-04 04:57:00 +00002738 Summ.isEndPath() ? Builder.MakeSinkNode(Dst, Ex, Pred, state)
2739 : Builder.MakeNode(Dst, Ex, Pred, state);
Ted Kremenek0dd65012009-02-18 02:00:25 +00002740
2741 // Annotate the edge with summary we used.
Ted Kremenek286e9852009-05-04 04:57:00 +00002742 if (NewNode) SummaryLog[NewNode] = &Summ;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002743}
2744
2745
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002746void CFRefCount::EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002747 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002748 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu097fc982008-10-17 05:57:07 +00002749 CallExpr* CE, SVal L,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002750 ExplodedNode<GRState>* Pred) {
Zhongxing Xucac107a2009-04-20 05:24:46 +00002751 const FunctionDecl* FD = L.getAsFunctionDecl();
Ted Kremenek286e9852009-05-04 04:57:00 +00002752 RetainSummary* Summ = !FD ? Summaries.getDefaultSummary()
Zhongxing Xucac107a2009-04-20 05:24:46 +00002753 : Summaries.getSummary(const_cast<FunctionDecl*>(FD));
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002754
Ted Kremenek286e9852009-05-04 04:57:00 +00002755 assert(Summ);
2756 EvalSummary(Dst, Eng, Builder, CE, 0, *Summ,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002757 CE->arg_begin(), CE->arg_end(), Pred);
Ted Kremenek827f93b2008-03-06 00:08:09 +00002758}
Ted Kremeneka7338b42008-03-11 06:39:11 +00002759
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002760void CFRefCount::EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002761 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002762 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002763 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002764 ExplodedNode<GRState>* Pred) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002765 RetainSummary* Summ = 0;
Ted Kremenek33661802008-05-01 21:31:50 +00002766
Ted Kremenek272aa852008-06-25 21:21:56 +00002767 if (Expr* Receiver = ME->getReceiver()) {
2768 // We need the type-information of the tracked receiver object
2769 // Retrieve it from the state.
2770 ObjCInterfaceDecl* ID = 0;
2771
2772 // FIXME: Wouldn't it be great if this code could be reduced? It's just
2773 // a chain of lookups.
Ted Kremeneka821b792009-04-29 05:04:30 +00002774 // FIXME: Is this really working as expected? There are cases where
2775 // we just use the 'ID' from the message expression.
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002776 const GRState* St = Builder.GetState(Pred);
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002777 SVal V = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
Ted Kremenek272aa852008-06-25 21:21:56 +00002778
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002779 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenek74556a12009-03-26 03:35:11 +00002780 if (Sym) {
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002781 if (const RefVal* T = St->get<RefBindings>(Sym)) {
Ted Kremenek6064a362008-07-07 16:21:19 +00002782 QualType Ty = T->getType();
Ted Kremenek272aa852008-06-25 21:21:56 +00002783
2784 if (const PointerType* PT = Ty->getAsPointerType()) {
2785 QualType PointeeTy = PT->getPointeeType();
2786
2787 if (ObjCInterfaceType* IT = dyn_cast<ObjCInterfaceType>(PointeeTy))
2788 ID = IT->getDecl();
2789 }
2790 }
2791 }
2792
Ted Kremenek04e00302009-04-29 17:09:14 +00002793 // FIXME: The receiver could be a reference to a class, meaning that
2794 // we should use the class method.
2795 Summ = Summaries.getInstanceMethodSummary(ME, ID);
Ted Kremenek0106e202008-10-24 20:32:50 +00002796
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002797 // Special-case: are we sending a mesage to "self"?
2798 // This is a hack. When we have full-IP this should be removed.
Ted Kremenek2f226732009-05-04 05:31:22 +00002799 if (isa<ObjCMethodDecl>(&Eng.getGraph().getCodeDecl())) {
2800 if (Expr* Receiver = ME->getReceiver()) {
2801 SVal X = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
2802 if (loc::MemRegionVal* L = dyn_cast<loc::MemRegionVal>(&X))
2803 if (L->getRegion() == Eng.getStateManager().getSelfRegion(St)) {
2804 // Update the summary to make the default argument effect
2805 // 'StopTracking'.
2806 Summ = Summaries.copySummary(Summ);
2807 Summ->setDefaultArgEffect(StopTracking);
2808 }
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002809 }
2810 }
Ted Kremenek272aa852008-06-25 21:21:56 +00002811 }
Ted Kremenek1feab292008-04-16 04:28:53 +00002812 else
Ted Kremenekb17fa952009-04-23 21:25:57 +00002813 Summ = Summaries.getClassMethodSummary(ME);
Ted Kremenek1feab292008-04-16 04:28:53 +00002814
Ted Kremenek286e9852009-05-04 04:57:00 +00002815 if (!Summ)
2816 Summ = Summaries.getDefaultSummary();
Ted Kremenekccbe79a2009-04-24 17:50:11 +00002817
Ted Kremenek286e9852009-05-04 04:57:00 +00002818 EvalSummary(Dst, Eng, Builder, ME, ME->getReceiver(), *Summ,
Ted Kremenek926abf22008-05-06 04:20:12 +00002819 ME->arg_begin(), ME->arg_end(), Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002820}
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002821
2822namespace {
2823class VISIBILITY_HIDDEN StopTrackingCallback : public SymbolVisitor {
2824 GRStateRef state;
2825public:
2826 StopTrackingCallback(GRStateRef st) : state(st) {}
2827 GRStateRef getState() { return state; }
2828
2829 bool VisitSymbol(SymbolRef sym) {
2830 state = state.remove<RefBindings>(sym);
2831 return true;
2832 }
Ted Kremenek926abf22008-05-06 04:20:12 +00002833
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002834 const GRState* getState() const { return state.getState(); }
2835};
2836} // end anonymous namespace
2837
2838
Ted Kremeneka42be302009-02-14 01:43:44 +00002839void CFRefCount::EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val) {
Ted Kremeneka42be302009-02-14 01:43:44 +00002840 // Are we storing to something that causes the value to "escape"?
Ted Kremenek7aef4842008-04-16 20:40:59 +00002841 bool escapes = false;
2842
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002843 // A value escapes in three possible cases (this may change):
2844 //
2845 // (1) we are binding to something that is not a memory region.
2846 // (2) we are binding to a memregion that does not have stack storage
2847 // (3) we are binding to a memregion with stack storage that the store
Ted Kremeneka42be302009-02-14 01:43:44 +00002848 // does not understand.
Ted Kremeneka42be302009-02-14 01:43:44 +00002849 GRStateRef state = B.getState();
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002850
Ted Kremeneka42be302009-02-14 01:43:44 +00002851 if (!isa<loc::MemRegionVal>(location))
Ted Kremenek7aef4842008-04-16 20:40:59 +00002852 escapes = true;
Ted Kremenekb15eba42008-10-04 05:50:14 +00002853 else {
Ted Kremeneka42be302009-02-14 01:43:44 +00002854 const MemRegion* R = cast<loc::MemRegionVal>(location).getRegion();
2855 escapes = !B.getStateManager().hasStackStorage(R);
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002856
2857 if (!escapes) {
2858 // To test (3), generate a new state with the binding removed. If it is
2859 // the same state, then it escapes (since the store cannot represent
2860 // the binding).
Ted Kremeneka42be302009-02-14 01:43:44 +00002861 escapes = (state == (state.BindLoc(cast<Loc>(location), UnknownVal())));
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002862 }
Ted Kremenekb15eba42008-10-04 05:50:14 +00002863 }
Ted Kremeneka42be302009-02-14 01:43:44 +00002864
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002865 // If our store can represent the binding and we aren't storing to something
2866 // that doesn't have local storage then just return and have the simulation
2867 // state continue as is.
2868 if (!escapes)
2869 return;
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002870
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002871 // Otherwise, find all symbols referenced by 'val' that we are tracking
2872 // and stop tracking them.
2873 B.MakeNode(state.scanReachableSymbols<StopTrackingCallback>(val).getState());
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002874}
2875
Ted Kremenek0106e202008-10-24 20:32:50 +00002876std::pair<GRStateRef,bool>
2877CFRefCount::HandleSymbolDeath(GRStateManager& VMgr,
2878 const GRState* St, const Decl* CD,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002879 SymbolRef sid,
Ted Kremenek0106e202008-10-24 20:32:50 +00002880 RefVal V, bool& hasLeak) {
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002881
Ted Kremenek47a72422009-04-29 18:50:19 +00002882 // Any remaining leaks?
Ted Kremenek311f3d42008-10-22 23:56:21 +00002883 hasLeak = V.isOwned() ||
2884 ((V.isNotOwned() || V.isReturnedOwned()) && V.getCount() > 0);
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002885
Ted Kremenek47a72422009-04-29 18:50:19 +00002886 GRStateRef state(St, VMgr);
2887
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002888 if (!hasLeak)
Ted Kremenek0106e202008-10-24 20:32:50 +00002889 return std::make_pair(state.remove<RefBindings>(sid), false);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002890
Ted Kremenek0106e202008-10-24 20:32:50 +00002891 return std::make_pair(state.set<RefBindings>(sid, V ^ RefVal::ErrorLeak),
2892 false);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002893}
2894
Ted Kremenek541db372008-04-24 23:57:27 +00002895
Ted Kremenekffefc352008-04-11 22:25:11 +00002896
Ted Kremenek541db372008-04-24 23:57:27 +00002897// Dead symbols.
2898
Ted Kremenek708af042009-02-05 06:50:21 +00002899
Ted Kremenek541db372008-04-24 23:57:27 +00002900
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002901 // Return statements.
2902
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002903void CFRefCount::EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002904 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002905 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002906 ReturnStmt* S,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002907 ExplodedNode<GRState>* Pred) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002908
2909 Expr* RetE = S->getRetValue();
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002910 if (!RetE)
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002911 return;
2912
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002913 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002914 SymbolRef Sym = state.GetSValAsScalarOrLoc(RetE).getAsLocSymbol();
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002915
Ted Kremenek74556a12009-03-26 03:35:11 +00002916 if (!Sym)
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002917 return;
2918
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002919 // Get the reference count binding (if any).
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002920 const RefVal* T = state.get<RefBindings>(Sym);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002921
2922 if (!T)
2923 return;
2924
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002925 // Change the reference count.
Ted Kremenek6064a362008-07-07 16:21:19 +00002926 RefVal X = *T;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002927
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002928 switch (X.getKind()) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002929 case RefVal::Owned: {
2930 unsigned cnt = X.getCount();
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00002931 assert (cnt > 0);
2932 X = RefVal::makeReturnedOwned(cnt - 1);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002933 break;
2934 }
2935
2936 case RefVal::NotOwned: {
2937 unsigned cnt = X.getCount();
2938 X = cnt ? RefVal::makeReturnedOwned(cnt - 1)
2939 : RefVal::makeReturnedNotOwned();
2940 break;
2941 }
2942
2943 default:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002944 return;
2945 }
2946
2947 // Update the binding.
Ted Kremenek91781202008-08-17 03:20:02 +00002948 state = state.set<RefBindings>(Sym, X);
Ted Kremenek47a72422009-04-29 18:50:19 +00002949 Pred = Builder.MakeNode(Dst, S, Pred, state);
2950
Ted Kremeneka208d0c2009-04-30 05:51:50 +00002951 // Did we cache out?
2952 if (!Pred)
2953 return;
2954
Ted Kremenek47a72422009-04-29 18:50:19 +00002955 // Any leaks or other errors?
2956 if (X.isReturnedOwned() && X.getCount() == 0) {
2957 const Decl *CD = &Eng.getStateManager().getCodeDecl();
2958
Ted Kremenek314b1952009-04-29 23:03:22 +00002959 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002960 const RetainSummary &Summ = *Summaries.getMethodSummary(MD);
2961 if (!Summ.getRetEffect().isOwned()) {
Ted Kremenek47a72422009-04-29 18:50:19 +00002962 static int ReturnOwnLeakTag = 0;
2963 state = state.set<RefBindings>(Sym, X ^ RefVal::ErrorLeakReturned);
Ted Kremenek47a72422009-04-29 18:50:19 +00002964 // Generate an error node.
Ted Kremeneka208d0c2009-04-30 05:51:50 +00002965 if (ExplodedNode<GRState> *N =
2966 Builder.generateNode(PostStmt(S, &ReturnOwnLeakTag), state, Pred)) {
2967 CFRefLeakReport *report =
2968 new CFRefLeakReport(*static_cast<CFRefBug*>(leakAtReturn), *this,
2969 N, Sym, Eng);
2970 BR->EmitReport(report);
2971 }
Ted Kremenek47a72422009-04-29 18:50:19 +00002972 }
2973 }
2974 }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002975}
2976
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002977// Assumptions.
2978
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002979const GRState* CFRefCount::EvalAssume(GRStateManager& VMgr,
2980 const GRState* St,
Zhongxing Xu097fc982008-10-17 05:57:07 +00002981 SVal Cond, bool Assumption,
Ted Kremenekf22f8682008-07-10 22:03:41 +00002982 bool& isFeasible) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002983
2984 // FIXME: We may add to the interface of EvalAssume the list of symbols
2985 // whose assumptions have changed. For now we just iterate through the
2986 // bindings and check if any of the tracked symbols are NULL. This isn't
2987 // too bad since the number of symbols we will track in practice are
2988 // probably small and EvalAssume is only called at branches and a few
2989 // other places.
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002990 RefBindings B = St->get<RefBindings>();
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002991
2992 if (B.isEmpty())
2993 return St;
2994
2995 bool changed = false;
Ted Kremenek91781202008-08-17 03:20:02 +00002996
2997 GRStateRef state(St, VMgr);
2998 RefBindings::Factory& RefBFactory = state.get_context<RefBindings>();
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002999
3000 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003001 // Check if the symbol is null (or equal to any constant).
3002 // If this is the case, stop tracking the symbol.
Zhongxing Xuc6b27d02008-08-29 14:52:36 +00003003 if (VMgr.getSymVal(St, I.getKey())) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003004 changed = true;
3005 B = RefBFactory.Remove(B, I.getKey());
3006 }
3007 }
3008
Ted Kremenek91781202008-08-17 03:20:02 +00003009 if (changed)
3010 state = state.set<RefBindings>(B);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003011
Ted Kremenek4ae925c2008-08-14 21:16:54 +00003012 return state;
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003013}
Ted Kremeneka7338b42008-03-11 06:39:11 +00003014
Ted Kremenekb6578942009-02-24 19:15:11 +00003015GRStateRef CFRefCount::Update(GRStateRef state, SymbolRef sym,
3016 RefVal V, ArgEffect E,
3017 RefVal::Kind& hasErr) {
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003018
3019 // In GC mode [... release] and [... retain] do nothing.
3020 switch (E) {
3021 default: break;
3022 case IncRefMsg: E = isGCEnabled() ? DoNothing : IncRef; break;
3023 case DecRefMsg: E = isGCEnabled() ? DoNothing : DecRef; break;
Ted Kremenek2126bef2009-02-18 21:57:45 +00003024 case MakeCollectable: E = isGCEnabled() ? DecRef : DoNothing; break;
Ted Kremenekaac82832009-02-23 17:45:03 +00003025 case NewAutoreleasePool: E = isGCEnabled() ? DoNothing :
3026 NewAutoreleasePool; break;
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003027 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00003028
Ted Kremenek6537a642009-03-17 19:42:23 +00003029 // Handle all use-after-releases.
3030 if (!isGCEnabled() && V.getKind() == RefVal::Released) {
3031 V = V ^ RefVal::ErrorUseAfterRelease;
3032 hasErr = V.getKind();
3033 return state.set<RefBindings>(sym, V);
3034 }
3035
Ted Kremenek0d721572008-03-11 17:48:22 +00003036 switch (E) {
3037 default:
3038 assert (false && "Unhandled CFRef transition.");
Ted Kremenek6537a642009-03-17 19:42:23 +00003039
3040 case Dealloc:
3041 // Any use of -dealloc in GC is *bad*.
3042 if (isGCEnabled()) {
3043 V = V ^ RefVal::ErrorDeallocGC;
3044 hasErr = V.getKind();
3045 break;
3046 }
3047
3048 switch (V.getKind()) {
3049 default:
3050 assert(false && "Invalid case.");
3051 case RefVal::Owned:
3052 // The object immediately transitions to the released state.
3053 V = V ^ RefVal::Released;
3054 V.clearCounts();
3055 return state.set<RefBindings>(sym, V);
3056 case RefVal::NotOwned:
3057 V = V ^ RefVal::ErrorDeallocNotOwned;
3058 hasErr = V.getKind();
3059 break;
3060 }
3061 break;
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003062
Ted Kremenekb7826ab2009-02-25 23:11:49 +00003063 case NewAutoreleasePool:
3064 assert(!isGCEnabled());
3065 return state.add<AutoreleaseStack>(sym);
3066
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003067 case MayEscape:
3068 if (V.getKind() == RefVal::Owned) {
Ted Kremenek272aa852008-06-25 21:21:56 +00003069 V = V ^ RefVal::NotOwned;
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003070 break;
3071 }
Ted Kremenek6537a642009-03-17 19:42:23 +00003072
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003073 // Fall-through.
Ted Kremenek1b4b6562009-02-25 02:54:57 +00003074
Ted Kremenekede40b72008-07-09 18:11:16 +00003075 case DoNothingByRef:
Ted Kremenek0d721572008-03-11 17:48:22 +00003076 case DoNothing:
Ted Kremenekb6578942009-02-24 19:15:11 +00003077 return state;
Ted Kremeneke5a4bb02008-06-30 16:57:41 +00003078
Ted Kremenek9b112d22009-01-28 21:44:40 +00003079 case Autorelease:
Ted Kremenek6537a642009-03-17 19:42:23 +00003080 if (isGCEnabled())
3081 return state;
Ted Kremenek681fb352009-03-20 17:34:15 +00003082
3083 // Update the autorelease counts.
3084 state = SendAutorelease(state, ARCountFactory, sym);
Ted Kremenek6537a642009-03-17 19:42:23 +00003085
3086 // Fall-through.
3087
Ted Kremenek227c5372008-05-06 02:41:27 +00003088 case StopTracking:
Ted Kremenekb6578942009-02-24 19:15:11 +00003089 return state.remove<RefBindings>(sym);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003090
Ted Kremenek0d721572008-03-11 17:48:22 +00003091 case IncRef:
3092 switch (V.getKind()) {
3093 default:
3094 assert(false);
3095
3096 case RefVal::Owned:
Ted Kremenek0d721572008-03-11 17:48:22 +00003097 case RefVal::NotOwned:
Ted Kremenek272aa852008-06-25 21:21:56 +00003098 V = V + 1;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003099 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003100 case RefVal::Released:
Ted Kremenek6537a642009-03-17 19:42:23 +00003101 // Non-GC cases are handled above.
3102 assert(isGCEnabled());
3103 V = (V ^ RefVal::Owned) + 1;
Ted Kremenek0d721572008-03-11 17:48:22 +00003104 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003105 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00003106 break;
3107
Ted Kremenek272aa852008-06-25 21:21:56 +00003108 case SelfOwn:
3109 V = V ^ RefVal::NotOwned;
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003110 // Fall-through.
Ted Kremenek0d721572008-03-11 17:48:22 +00003111 case DecRef:
3112 switch (V.getKind()) {
3113 default:
Ted Kremenek6537a642009-03-17 19:42:23 +00003114 // case 'RefVal::Released' handled above.
Ted Kremenek0d721572008-03-11 17:48:22 +00003115 assert (false);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003116
Ted Kremenek272aa852008-06-25 21:21:56 +00003117 case RefVal::Owned:
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00003118 assert(V.getCount() > 0);
3119 if (V.getCount() == 1) V = V ^ RefVal::Released;
3120 V = V - 1;
Ted Kremenek0d721572008-03-11 17:48:22 +00003121 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003122
Ted Kremenek272aa852008-06-25 21:21:56 +00003123 case RefVal::NotOwned:
3124 if (V.getCount() > 0)
3125 V = V - 1;
Ted Kremenekc4f81022008-04-10 23:09:18 +00003126 else {
Ted Kremenek272aa852008-06-25 21:21:56 +00003127 V = V ^ RefVal::ErrorReleaseNotOwned;
Ted Kremenek1feab292008-04-16 04:28:53 +00003128 hasErr = V.getKind();
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003129 }
Ted Kremenek0d721572008-03-11 17:48:22 +00003130 break;
Ted Kremenek6537a642009-03-17 19:42:23 +00003131
Ted Kremenek0d721572008-03-11 17:48:22 +00003132 case RefVal::Released:
Ted Kremenek6537a642009-03-17 19:42:23 +00003133 // Non-GC cases are handled above.
3134 assert(isGCEnabled());
Ted Kremenek272aa852008-06-25 21:21:56 +00003135 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek1feab292008-04-16 04:28:53 +00003136 hasErr = V.getKind();
Ted Kremenek6537a642009-03-17 19:42:23 +00003137 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003138 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00003139 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003140 }
Ted Kremenekb6578942009-02-24 19:15:11 +00003141 return state.set<RefBindings>(sym, V);
Ted Kremeneka7338b42008-03-11 06:39:11 +00003142}
3143
Ted Kremenek10fe66d2008-04-09 01:10:13 +00003144//===----------------------------------------------------------------------===//
Ted Kremenek708af042009-02-05 06:50:21 +00003145// Handle dead symbols and end-of-path.
3146//===----------------------------------------------------------------------===//
3147
3148void CFRefCount::EvalEndPath(GRExprEngine& Eng,
3149 GREndPathNodeBuilder<GRState>& Builder) {
3150
3151 const GRState* St = Builder.getState();
3152 RefBindings B = St->get<RefBindings>();
3153
3154 llvm::SmallVector<std::pair<SymbolRef, bool>, 10> Leaked;
3155 const Decl* CodeDecl = &Eng.getGraph().getCodeDecl();
3156
3157 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
3158 bool hasLeak = false;
3159
3160 std::pair<GRStateRef, bool> X =
Ted Kremenek9577c1e2009-03-03 22:06:47 +00003161 HandleSymbolDeath(Eng.getStateManager(), St, CodeDecl,
3162 (*I).first, (*I).second, hasLeak);
Ted Kremenek708af042009-02-05 06:50:21 +00003163
3164 St = X.first;
3165 if (hasLeak) Leaked.push_back(std::make_pair((*I).first, X.second));
3166 }
3167
3168 if (Leaked.empty())
3169 return;
3170
3171 ExplodedNode<GRState>* N = Builder.MakeNode(St);
3172
3173 if (!N)
3174 return;
3175
3176 for (llvm::SmallVector<std::pair<SymbolRef,bool>, 10>::iterator
3177 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3178
3179 CFRefBug *BT = static_cast<CFRefBug*>(I->second ? leakAtReturn
3180 : leakWithinFunction);
3181 assert(BT && "BugType not initialized.");
Ted Kremenekc034f712009-04-07 05:07:44 +00003182 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N, I->first, Eng);
Ted Kremenek708af042009-02-05 06:50:21 +00003183 BR->EmitReport(report);
3184 }
3185}
3186
3187void CFRefCount::EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
3188 GRExprEngine& Eng,
3189 GRStmtNodeBuilder<GRState>& Builder,
3190 ExplodedNode<GRState>* Pred,
3191 Stmt* S,
3192 const GRState* St,
3193 SymbolReaper& SymReaper) {
3194
Ted Kremenek876d8df2009-02-19 23:47:02 +00003195 // FIXME: a lot of copy-and-paste from EvalEndPath. Refactor.
Ted Kremenek708af042009-02-05 06:50:21 +00003196 RefBindings B = St->get<RefBindings>();
3197 llvm::SmallVector<std::pair<SymbolRef,bool>, 10> Leaked;
3198
3199 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3200 E = SymReaper.dead_end(); I != E; ++I) {
3201
3202 const RefVal* T = B.lookup(*I);
3203 if (!T) continue;
3204
3205 bool hasLeak = false;
3206
3207 std::pair<GRStateRef, bool> X
Ted Kremenek876d8df2009-02-19 23:47:02 +00003208 = HandleSymbolDeath(Eng.getStateManager(), St, 0, *I, *T, hasLeak);
Ted Kremenek708af042009-02-05 06:50:21 +00003209
3210 St = X.first;
3211
3212 if (hasLeak)
3213 Leaked.push_back(std::make_pair(*I,X.second));
3214 }
3215
Ted Kremenek876d8df2009-02-19 23:47:02 +00003216 if (!Leaked.empty()) {
3217 // Create a new intermediate node representing the leak point. We
3218 // use a special program point that represents this checker-specific
3219 // transition. We use the address of RefBIndex as a unique tag for this
3220 // checker. We will create another node (if we don't cache out) that
3221 // removes the retain-count bindings from the state.
3222 // NOTE: We use 'generateNode' so that it does interplay with the
3223 // auto-transition logic.
3224 ExplodedNode<GRState>* N =
3225 Builder.generateNode(PostStmtCustom(S, &LeakProgramPointTag), St, Pred);
Ted Kremenek708af042009-02-05 06:50:21 +00003226
Ted Kremenek876d8df2009-02-19 23:47:02 +00003227 if (!N)
3228 return;
3229
3230 // Generate the bug reports.
3231 for (llvm::SmallVectorImpl<std::pair<SymbolRef,bool> >::iterator
3232 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3233
3234 CFRefBug *BT = static_cast<CFRefBug*>(I->second ? leakAtReturn
3235 : leakWithinFunction);
3236 assert(BT && "BugType not initialized.");
Ted Kremenek56c70aa2009-02-23 16:54:00 +00003237 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N,
3238 I->first, Eng);
Ted Kremenek876d8df2009-02-19 23:47:02 +00003239 BR->EmitReport(report);
3240 }
Ted Kremenek708af042009-02-05 06:50:21 +00003241
Ted Kremenek876d8df2009-02-19 23:47:02 +00003242 Pred = N;
Ted Kremenek708af042009-02-05 06:50:21 +00003243 }
Ted Kremenek876d8df2009-02-19 23:47:02 +00003244
3245 // Now generate a new node that nukes the old bindings.
3246 GRStateRef state(St, Eng.getStateManager());
3247 RefBindings::Factory& F = state.get_context<RefBindings>();
3248
3249 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3250 E = SymReaper.dead_end(); I!=E; ++I)
3251 B = F.Remove(B, *I);
3252
3253 state = state.set<RefBindings>(B);
3254 Builder.MakeNode(Dst, S, Pred, state);
Ted Kremenek708af042009-02-05 06:50:21 +00003255}
3256
3257void CFRefCount::ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
3258 GRStmtNodeBuilder<GRState>& Builder,
3259 Expr* NodeExpr, Expr* ErrorExpr,
3260 ExplodedNode<GRState>* Pred,
3261 const GRState* St,
3262 RefVal::Kind hasErr, SymbolRef Sym) {
3263 Builder.BuildSinks = true;
3264 GRExprEngine::NodeTy* N = Builder.MakeNode(Dst, NodeExpr, Pred, St);
3265
3266 if (!N) return;
3267
3268 CFRefBug *BT = 0;
3269
Ted Kremenek6537a642009-03-17 19:42:23 +00003270 switch (hasErr) {
3271 default:
3272 assert(false && "Unhandled error.");
3273 return;
3274 case RefVal::ErrorUseAfterRelease:
3275 BT = static_cast<CFRefBug*>(useAfterRelease);
3276 break;
3277 case RefVal::ErrorReleaseNotOwned:
3278 BT = static_cast<CFRefBug*>(releaseNotOwned);
3279 break;
3280 case RefVal::ErrorDeallocGC:
3281 BT = static_cast<CFRefBug*>(deallocGC);
3282 break;
3283 case RefVal::ErrorDeallocNotOwned:
3284 BT = static_cast<CFRefBug*>(deallocNotOwned);
3285 break;
Ted Kremenek708af042009-02-05 06:50:21 +00003286 }
3287
Ted Kremenekc26c4692009-02-18 03:48:14 +00003288 CFRefReport *report = new CFRefReport(*BT, *this, N, Sym);
Ted Kremenek708af042009-02-05 06:50:21 +00003289 report->addRange(ErrorExpr->getSourceRange());
3290 BR->EmitReport(report);
3291}
3292
3293//===----------------------------------------------------------------------===//
Ted Kremenekb1983ba2008-04-10 22:16:52 +00003294// Transfer function creation for external clients.
Ted Kremeneka7338b42008-03-11 06:39:11 +00003295//===----------------------------------------------------------------------===//
3296
Ted Kremenekfe30beb2008-04-30 23:47:44 +00003297GRTransferFuncs* clang::MakeCFRefCountTF(ASTContext& Ctx, bool GCEnabled,
3298 const LangOptions& lopts) {
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00003299 return new CFRefCount(Ctx, GCEnabled, lopts);
Ted Kremeneka4c74292008-04-10 22:58:08 +00003300}