blob: 90b15a40b441423ec5fe4857d85807a13f5a868d [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"
Ted Kremenekc3bc6c82009-05-06 21:39:49 +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 Kremenek5535e5e2009-05-07 23:40:42 +0000588 /// ObjCAllocRetE - Default return effect for methods returning Objective-C
589 /// objects.
590 RetEffect ObjCAllocRetE;
591
Ted Kremenek286e9852009-05-04 04:57:00 +0000592 RetainSummary DefaultSummary;
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000593 RetainSummary* StopSummary;
594
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000595 //==-----------------------------------------------------------------==//
596 // Methods.
597 //==-----------------------------------------------------------------==//
598
Ted Kremenek272aa852008-06-25 21:21:56 +0000599 /// getArgEffects - Returns a persistent ArgEffects object based on the
600 /// data in ScratchArgs.
Ted Kremeneka56ae162009-05-03 05:20:50 +0000601 ArgEffects getArgEffects();
Ted Kremeneka7338b42008-03-11 06:39:11 +0000602
Ted Kremenek562c1302008-05-05 16:51:50 +0000603 enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000604
605public:
Ted Kremenek2f226732009-05-04 05:31:22 +0000606 RetainSummary *getDefaultSummary() {
607 RetainSummary *Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
608 return new (Summ) RetainSummary(DefaultSummary);
609 }
Ted Kremenek286e9852009-05-04 04:57:00 +0000610
Ted Kremenek064ef322009-02-23 16:51:39 +0000611 RetainSummary* getUnarySummary(const FunctionType* FT, UnaryFuncKind func);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000612
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000613 RetainSummary* getCFSummaryCreateRule(FunctionDecl* FD);
614 RetainSummary* getCFSummaryGetRule(FunctionDecl* FD);
Ted Kremenek17144e82009-01-12 21:45:02 +0000615 RetainSummary* getCFCreateGetRuleSummary(FunctionDecl* FD, const char* FName);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000616
Ted Kremeneka56ae162009-05-03 05:20:50 +0000617 RetainSummary* getPersistentSummary(ArgEffects AE, RetEffect RetEff,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000618 ArgEffect ReceiverEff = DoNothing,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000619 ArgEffect DefaultEff = MayEscape,
620 bool isEndPath = false);
Ted Kremenek45d0b502008-10-29 04:07:07 +0000621
Ted Kremenek266d8b62008-05-06 02:26:56 +0000622 RetainSummary* getPersistentSummary(RetEffect RE,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000623 ArgEffect ReceiverEff = DoNothing,
Ted Kremeneka3f30dd2008-05-22 17:31:13 +0000624 ArgEffect DefaultEff = MayEscape) {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000625 return getPersistentSummary(getArgEffects(), RE, ReceiverEff, DefaultEff);
Ted Kremenek0e344d42008-05-06 00:30:21 +0000626 }
Ted Kremenek42ea0322008-05-05 23:55:01 +0000627
Ted Kremeneka821b792009-04-29 05:04:30 +0000628 RetainSummary *getPersistentStopSummary() {
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000629 if (StopSummary)
630 return StopSummary;
631
632 StopSummary = getPersistentSummary(RetEffect::MakeNoRet(),
633 StopTracking, StopTracking);
Ted Kremenek45d0b502008-10-29 04:07:07 +0000634
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000635 return StopSummary;
Ted Kremenekbcaff792008-05-06 15:44:25 +0000636 }
Ted Kremenek926abf22008-05-06 04:20:12 +0000637
Ted Kremeneka821b792009-04-29 05:04:30 +0000638 RetainSummary *getInitMethodSummary(QualType RetTy);
Ted Kremenek42ea0322008-05-05 23:55:01 +0000639
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000640 void InitializeClassMethodSummaries();
641 void InitializeMethodSummaries();
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000642
Ted Kremenek9b42e062009-05-03 04:42:10 +0000643 bool isTrackedObjCObjectType(QualType T);
Ted Kremeneka9cdbc32009-05-03 06:08:32 +0000644 bool isTrackedCFObjectType(QualType T);
Ted Kremenek35920ed2009-01-07 00:39:56 +0000645
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000646private:
647
Ted Kremenekf2717b02008-07-18 17:24:20 +0000648 void addClsMethSummary(IdentifierInfo* ClsII, Selector S,
649 RetainSummary* Summ) {
650 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
651 }
652
Ted Kremenek272aa852008-06-25 21:21:56 +0000653 void addNSObjectClsMethSummary(Selector S, RetainSummary *Summ) {
654 ObjCClassMethodSummaries[S] = Summ;
655 }
656
657 void addNSObjectMethSummary(Selector S, RetainSummary *Summ) {
658 ObjCMethodSummaries[S] = Summ;
659 }
Ted Kremenekfbf2dc52009-03-04 23:30:42 +0000660
661 void addClassMethSummary(const char* Cls, const char* nullaryName,
662 RetainSummary *Summ) {
663 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
664 Selector S = GetNullarySelector(nullaryName, Ctx);
665 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
666 }
Ted Kremenek272aa852008-06-25 21:21:56 +0000667
Ted Kremenek1b4b6562009-02-25 02:54:57 +0000668 void addInstMethSummary(const char* Cls, const char* nullaryName,
669 RetainSummary *Summ) {
670 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
671 Selector S = GetNullarySelector(nullaryName, Ctx);
672 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
673 }
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000674
675 Selector generateSelector(va_list argp) {
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000676 llvm::SmallVector<IdentifierInfo*, 10> II;
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000677
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000678 while (const char* s = va_arg(argp, const char*))
679 II.push_back(&Ctx.Idents.get(s));
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000680
681 return Ctx.Selectors.getSelector(II.size(), &II[0]);
682 }
683
684 void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy& Summaries,
685 RetainSummary* Summ, va_list argp) {
686 Selector S = generateSelector(argp);
687 Summaries[ObjCSummaryKey(ClsII, S)] = Summ;
Ted Kremenekf2717b02008-07-18 17:24:20 +0000688 }
Ted Kremenek45642a42008-08-12 18:48:50 +0000689
690 void addInstMethSummary(const char* Cls, RetainSummary* Summ, ...) {
691 va_list argp;
692 va_start(argp, Summ);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000693 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Ted Kremenek45642a42008-08-12 18:48:50 +0000694 va_end(argp);
695 }
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000696
697 void addClsMethSummary(const char* Cls, RetainSummary* Summ, ...) {
698 va_list argp;
699 va_start(argp, Summ);
700 addMethodSummary(&Ctx.Idents.get(Cls),ObjCClassMethodSummaries, Summ, argp);
701 va_end(argp);
702 }
703
704 void addClsMethSummary(IdentifierInfo *II, RetainSummary* Summ, ...) {
705 va_list argp;
706 va_start(argp, Summ);
707 addMethodSummary(II, ObjCClassMethodSummaries, Summ, argp);
708 va_end(argp);
709 }
710
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000711 void addPanicSummary(const char* Cls, ...) {
Ted Kremeneka56ae162009-05-03 05:20:50 +0000712 RetainSummary* Summ = getPersistentSummary(AF.GetEmptyMap(),
713 RetEffect::MakeNoRet(),
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000714 DoNothing, DoNothing, true);
715 va_list argp;
716 va_start (argp, Cls);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000717 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000718 va_end(argp);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000719 }
Ted Kremenekf2717b02008-07-18 17:24:20 +0000720
Ted Kremeneka7338b42008-03-11 06:39:11 +0000721public:
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000722
723 RetainSummaryManager(ASTContext& ctx, bool gcenabled)
Ted Kremeneke44927e2008-07-01 17:21:27 +0000724 : Ctx(ctx),
Ted Kremenekede40b72008-07-09 18:11:16 +0000725 CFDictionaryCreateII(&ctx.Idents.get("CFDictionaryCreate")),
Ted Kremeneka56ae162009-05-03 05:20:50 +0000726 GCEnabled(gcenabled), AF(BPAlloc), ScratchArgs(AF.GetEmptyMap()),
Ted Kremenek5535e5e2009-05-07 23:40:42 +0000727 ObjCAllocRetE(gcenabled ? RetEffect::MakeGCNotOwned()
728 : RetEffect::MakeOwned(RetEffect::ObjC, true)),
Ted Kremenek286e9852009-05-04 04:57:00 +0000729 DefaultSummary(AF.GetEmptyMap() /* per-argument effects (none) */,
730 RetEffect::MakeNoRet() /* return effect */,
731 DoNothing /* receiver effect */,
732 MayEscape /* default argument effect */),
Ted Kremeneka56ae162009-05-03 05:20:50 +0000733 StopSummary(0) {
Ted Kremenek272aa852008-06-25 21:21:56 +0000734
735 InitializeClassMethodSummaries();
736 InitializeMethodSummaries();
737 }
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000738
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000739 ~RetainSummaryManager();
Ted Kremeneka7338b42008-03-11 06:39:11 +0000740
Ted Kremenekd13c1872008-06-24 03:56:45 +0000741 RetainSummary* getSummary(FunctionDecl* FD);
Ted Kremeneka821b792009-04-29 05:04:30 +0000742
Ted Kremenek314b1952009-04-29 23:03:22 +0000743 RetainSummary* getInstanceMethodSummary(ObjCMessageExpr* ME,
744 const ObjCInterfaceDecl* ID) {
Ted Kremenek04e00302009-04-29 17:09:14 +0000745 return getInstanceMethodSummary(ME->getSelector(), ME->getClassName(),
Ted Kremeneka821b792009-04-29 05:04:30 +0000746 ID, ME->getMethodDecl(), ME->getType());
747 }
748
Ted Kremenek04e00302009-04-29 17:09:14 +0000749 RetainSummary* getInstanceMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +0000750 const ObjCInterfaceDecl* ID,
751 const ObjCMethodDecl *MD,
752 QualType RetTy);
Ted Kremenek578498a2009-04-29 00:42:39 +0000753
754 RetainSummary *getClassMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +0000755 const ObjCInterfaceDecl *ID,
756 const ObjCMethodDecl *MD,
757 QualType RetTy);
Ted Kremenek578498a2009-04-29 00:42:39 +0000758
759 RetainSummary *getClassMethodSummary(ObjCMessageExpr *ME) {
760 return getClassMethodSummary(ME->getSelector(), ME->getClassName(),
761 ME->getClassInfo().first,
762 ME->getMethodDecl(), ME->getType());
763 }
Ted Kremenek91b89a42009-04-29 17:17:48 +0000764
765 /// getMethodSummary - This version of getMethodSummary is used to query
766 /// the summary for the current method being analyzed.
Ted Kremenek314b1952009-04-29 23:03:22 +0000767 RetainSummary *getMethodSummary(const ObjCMethodDecl *MD) {
768 // FIXME: Eventually this should be unneeded.
Ted Kremenek314b1952009-04-29 23:03:22 +0000769 const ObjCInterfaceDecl *ID = MD->getClassInterface();
Ted Kremenek1447cc92009-04-30 05:41:14 +0000770 Selector S = MD->getSelector();
Ted Kremenek91b89a42009-04-29 17:17:48 +0000771 IdentifierInfo *ClsName = ID->getIdentifier();
772 QualType ResultTy = MD->getResultType();
773
Ted Kremenek81eb4642009-04-30 05:47:23 +0000774 // Resolve the method decl last.
775 if (const ObjCMethodDecl *InterfaceMD =
776 ResolveToInterfaceMethodDecl(MD, Ctx))
777 MD = InterfaceMD;
Ted Kremenek1447cc92009-04-30 05:41:14 +0000778
Ted Kremenek91b89a42009-04-29 17:17:48 +0000779 if (MD->isInstanceMethod())
780 return getInstanceMethodSummary(S, ClsName, ID, MD, ResultTy);
781 else
782 return getClassMethodSummary(S, ClsName, ID, MD, ResultTy);
783 }
Ted Kremenek578498a2009-04-29 00:42:39 +0000784
Ted Kremenek314b1952009-04-29 23:03:22 +0000785 RetainSummary* getCommonMethodSummary(const ObjCMethodDecl* MD,
786 Selector S, QualType RetTy);
787
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()
Ted Kremenek03d242e2009-05-05 18:44:20 +00001093 : RetEffect::MakeNoRet());
Ted Kremenek42ea0322008-05-05 23:55:01 +00001094}
Ted Kremenek03d242e2009-05-05 18:44:20 +00001095
Ted Kremenekbcaff792008-05-06 15:44:25 +00001096RetainSummary*
Ted Kremenek314b1952009-04-29 23:03:22 +00001097RetainSummaryManager::getCommonMethodSummary(const ObjCMethodDecl* MD,
1098 Selector S, QualType RetTy) {
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001099
Ted Kremenek578498a2009-04-29 00:42:39 +00001100 if (MD) {
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001101 // Scan the method decl for 'void*' arguments. These should be treated
1102 // as 'StopTracking' because they are often used with delegates.
1103 // Delegates are a frequent form of false positives with the retain
1104 // count checker.
1105 unsigned i = 0;
1106 for (ObjCMethodDecl::param_iterator I = MD->param_begin(),
1107 E = MD->param_end(); I != E; ++I, ++i)
1108 if (ParmVarDecl *PD = *I) {
1109 QualType Ty = Ctx.getCanonicalType(PD->getType());
1110 if (Ty.getUnqualifiedType() == Ctx.VoidPtrTy)
Ted Kremeneka56ae162009-05-03 05:20:50 +00001111 ScratchArgs = AF.Add(ScratchArgs, i, StopTracking);
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001112 }
1113 }
1114
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001115 // Any special effect for the receiver?
1116 ArgEffect ReceiverEff = DoNothing;
1117
1118 // If one of the arguments in the selector has the keyword 'delegate' we
1119 // should stop tracking the reference count for the receiver. This is
1120 // because the reference count is quite possibly handled by a delegate
1121 // method.
1122 if (S.isKeywordSelector()) {
1123 const std::string &str = S.getAsString();
1124 assert(!str.empty());
1125 if (CStrInCStrNoCase(&str[0], "delegate:")) ReceiverEff = StopTracking;
1126 }
1127
Ted Kremenek174a0772009-04-23 23:08:22 +00001128 // Look for methods that return an owned object.
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001129 if (isTrackedObjCObjectType(RetTy)) {
1130 // EXPERIMENTAL: Assume the Cocoa conventions for all objects returned
1131 // by instance methods.
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001132 RetEffect E =
1133 followsFundamentalRule(S.getIdentifierInfoForSlot(0)->getName())
Ted Kremenek5535e5e2009-05-07 23:40:42 +00001134 ? ObjCAllocRetE : RetEffect::MakeNotOwned(RetEffect::ObjC);
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001135
1136 return getPersistentSummary(E, ReceiverEff, MayEscape);
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001137 }
Ted Kremenek174a0772009-04-23 23:08:22 +00001138
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001139 // Look for methods that return an owned core foundation object.
1140 if (isTrackedCFObjectType(RetTy)) {
1141 RetEffect E =
1142 followsFundamentalRule(S.getIdentifierInfoForSlot(0)->getName())
1143 ? RetEffect::MakeOwned(RetEffect::CF, true)
1144 : RetEffect::MakeNotOwned(RetEffect::CF);
1145
1146 return getPersistentSummary(E, ReceiverEff, MayEscape);
1147 }
Ted Kremenek174a0772009-04-23 23:08:22 +00001148
Ted Kremeneka9cdbc32009-05-03 06:08:32 +00001149 if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing)
Ted Kremenek286e9852009-05-04 04:57:00 +00001150 return getDefaultSummary();
Ted Kremenek174a0772009-04-23 23:08:22 +00001151
Ted Kremenek2f226732009-05-04 05:31:22 +00001152 return getPersistentSummary(RetEffect::MakeNoRet(), ReceiverEff, MayEscape);
Ted Kremenek174a0772009-04-23 23:08:22 +00001153}
1154
1155RetainSummary*
Ted Kremenek04e00302009-04-29 17:09:14 +00001156RetainSummaryManager::getInstanceMethodSummary(Selector S,
1157 IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +00001158 const ObjCInterfaceDecl* ID,
1159 const ObjCMethodDecl *MD,
Ted Kremenek04e00302009-04-29 17:09:14 +00001160 QualType RetTy) {
Ted Kremenekbcaff792008-05-06 15:44:25 +00001161
Ted Kremeneka821b792009-04-29 05:04:30 +00001162 // Look up a summary in our summary cache.
1163 ObjCMethodSummariesTy::iterator I = ObjCMethodSummaries.find(ID, ClsName, S);
Ted Kremenek42ea0322008-05-05 23:55:01 +00001164
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001165 if (I != ObjCMethodSummaries.end())
Ted Kremenek42ea0322008-05-05 23:55:01 +00001166 return I->second;
Ted Kremenek42ea0322008-05-05 23:55:01 +00001167
Ted Kremeneka56ae162009-05-03 05:20:50 +00001168 assert(ScratchArgs.isEmpty());
Ted Kremenek2f226732009-05-04 05:31:22 +00001169 RetainSummary *Summ = 0;
Ted Kremenek1d3d9562008-05-06 06:09:09 +00001170
Ted Kremenek2f226732009-05-04 05:31:22 +00001171 // "initXXX": pass-through for receiver.
1172 if (deriveNamingConvention(S.getIdentifierInfoForSlot(0)->getName())
1173 == InitRule)
1174 Summ = getInitMethodSummary(RetTy);
1175 else
1176 Summ = getCommonMethodSummary(MD, S, RetTy);
1177
Ted Kremenek2f226732009-05-04 05:31:22 +00001178 // Memoize the summary.
Ted Kremeneka821b792009-04-29 05:04:30 +00001179 ObjCMethodSummaries[ObjCSummaryKey(ClsName, S)] = Summ;
Ted Kremeneke4158502009-04-23 19:11:35 +00001180 return Summ;
Ted Kremenek42ea0322008-05-05 23:55:01 +00001181}
1182
Ted Kremeneka7722b72008-05-06 21:26:51 +00001183RetainSummary*
Ted Kremenek578498a2009-04-29 00:42:39 +00001184RetainSummaryManager::getClassMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremenek314b1952009-04-29 23:03:22 +00001185 const ObjCInterfaceDecl *ID,
1186 const ObjCMethodDecl *MD,
1187 QualType RetTy) {
Ted Kremenekccbe79a2009-04-24 17:50:11 +00001188
Ted Kremenek578498a2009-04-29 00:42:39 +00001189 assert(ClsName && "Class name must be specified.");
Ted Kremeneka821b792009-04-29 05:04:30 +00001190 ObjCMethodSummariesTy::iterator I =
1191 ObjCClassMethodSummaries.find(ID, ClsName, S);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001192
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001193 if (I != ObjCClassMethodSummaries.end())
Ted Kremeneka7722b72008-05-06 21:26:51 +00001194 return I->second;
Ted Kremenek2f226732009-05-04 05:31:22 +00001195
1196 RetainSummary *Summ = getCommonMethodSummary(MD, S, RetTy);
1197
Ted Kremenek2f226732009-05-04 05:31:22 +00001198 // Memoize the summary.
Ted Kremenek578498a2009-04-29 00:42:39 +00001199 ObjCClassMethodSummaries[ObjCSummaryKey(ClsName, S)] = Summ;
Ted Kremeneke4158502009-04-23 19:11:35 +00001200 return Summ;
Ted Kremeneka7722b72008-05-06 21:26:51 +00001201}
1202
Ted Kremenek5535e5e2009-05-07 23:40:42 +00001203void RetainSummaryManager::InitializeClassMethodSummaries() {
1204 assert(ScratchArgs.isEmpty());
1205 RetainSummary* Summ = getPersistentSummary(ObjCAllocRetE);
Ted Kremenek0e344d42008-05-06 00:30:21 +00001206
Ted Kremenek272aa852008-06-25 21:21:56 +00001207 // Create the summaries for "alloc", "new", and "allocWithZone:" for
1208 // NSObject and its derivatives.
1209 addNSObjectClsMethSummary(GetNullarySelector("alloc", Ctx), Summ);
1210 addNSObjectClsMethSummary(GetNullarySelector("new", Ctx), Summ);
1211 addNSObjectClsMethSummary(GetUnarySelector("allocWithZone", Ctx), Summ);
Ted Kremenekf2717b02008-07-18 17:24:20 +00001212
1213 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001214 addClsMethSummary(&Ctx.Idents.get("NSAssertionHandler"),
Ted Kremenek68621b92009-01-28 05:56:51 +00001215 GetNullarySelector("currentHandler", Ctx),
1216 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001217
1218 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremeneka56ae162009-05-03 05:20:50 +00001219 ScratchArgs = AF.Add(ScratchArgs, 0, Autorelease);
Ted Kremenek9b112d22009-01-28 21:44:40 +00001220 addClsMethSummary(&Ctx.Idents.get("NSAutoreleasePool"),
1221 GetUnarySelector("addObject", Ctx),
1222 getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenekf21cb242009-02-23 02:31:16 +00001223 DoNothing, Autorelease));
Ted Kremenekccbe79a2009-04-24 17:50:11 +00001224
1225 // Create the summaries for [NSObject performSelector...]. We treat
1226 // these as 'stop tracking' for the arguments because they are often
1227 // used for delegates that can release the object. When we have better
1228 // inter-procedural analysis we can potentially do something better. This
1229 // workaround is to remove false positives.
1230 Summ = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, StopTracking);
1231 IdentifierInfo *NSObjectII = &Ctx.Idents.get("NSObject");
1232 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1233 "afterDelay", NULL);
1234 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1235 "afterDelay", "inModes", NULL);
1236 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1237 "withObject", "waitUntilDone", NULL);
1238 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1239 "withObject", "waitUntilDone", "modes", NULL);
1240 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1241 "withObject", "waitUntilDone", NULL);
1242 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1243 "withObject", "waitUntilDone", "modes", NULL);
1244 addClsMethSummary(NSObjectII, Summ, "performSelectorInBackground",
1245 "withObject", NULL);
Ted Kremenek0e344d42008-05-06 00:30:21 +00001246}
1247
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001248void RetainSummaryManager::InitializeMethodSummaries() {
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001249
Ted Kremeneka56ae162009-05-03 05:20:50 +00001250 assert (ScratchArgs.isEmpty());
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001251
Ted Kremeneka7722b72008-05-06 21:26:51 +00001252 // Create the "init" selector. It just acts as a pass-through for the
1253 // receiver.
Ted Kremenek56c70aa2009-02-23 16:54:00 +00001254 RetainSummary* InitSumm =
1255 getPersistentSummary(RetEffect::MakeReceiverAlias());
Ted Kremeneke44927e2008-07-01 17:21:27 +00001256 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001257
1258 // The next methods are allocators.
Ted Kremenek5535e5e2009-05-07 23:40:42 +00001259 RetainSummary* Summ = getPersistentSummary(ObjCAllocRetE);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001260
1261 // Create the "copy" selector.
Ted Kremenek9449ca92008-08-12 20:41:56 +00001262 addNSObjectMethSummary(GetNullarySelector("copy", Ctx), Summ);
1263
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001264 // Create the "mutableCopy" selector.
Ted Kremenek272aa852008-06-25 21:21:56 +00001265 addNSObjectMethSummary(GetNullarySelector("mutableCopy", Ctx), Summ);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001266
Ted Kremenek266d8b62008-05-06 02:26:56 +00001267 // Create the "retain" selector.
Ted Kremenek5535e5e2009-05-07 23:40:42 +00001268 RetEffect E = RetEffect::MakeReceiverAlias();
Ted Kremenek58dd95b2009-02-18 18:54:33 +00001269 Summ = getPersistentSummary(E, IncRefMsg);
Ted Kremenek272aa852008-06-25 21:21:56 +00001270 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001271
1272 // Create the "release" selector.
Ted Kremenek58dd95b2009-02-18 18:54:33 +00001273 Summ = getPersistentSummary(E, DecRefMsg);
Ted Kremenek272aa852008-06-25 21:21:56 +00001274 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Ted Kremenekc00b32b2008-05-07 21:17:39 +00001275
1276 // Create the "drain" selector.
1277 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek272aa852008-06-25 21:21:56 +00001278 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
Ted Kremenek6537a642009-03-17 19:42:23 +00001279
1280 // Create the -dealloc summary.
1281 Summ = getPersistentSummary(RetEffect::MakeNoRet(), Dealloc);
1282 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001283
1284 // Create the "autorelease" selector.
Ted Kremenek9b112d22009-01-28 21:44:40 +00001285 Summ = getPersistentSummary(E, Autorelease);
Ted Kremenek272aa852008-06-25 21:21:56 +00001286 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001287
Ted Kremenekaac82832009-02-23 17:45:03 +00001288 // Specially handle NSAutoreleasePool.
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001289 addInstMethSummary("NSAutoreleasePool", "init",
Ted Kremenekaac82832009-02-23 17:45:03 +00001290 getPersistentSummary(RetEffect::MakeReceiverAlias(),
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001291 NewAutoreleasePool));
Ted Kremenekaac82832009-02-23 17:45:03 +00001292
Ted Kremenek45642a42008-08-12 18:48:50 +00001293 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremenek7e3a3272009-02-23 02:51:29 +00001294 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1295 // self-own themselves. However, they only do this once they are displayed.
1296 // Thus, we need to track an NSWindow's display status.
1297 // This is tracked in <rdar://problem/6062711>.
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001298 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
Ted Kremeneke5a036a2009-04-03 19:02:51 +00001299 RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet());
1300
1301 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1302
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001303
1304#if 0
Ted Kremeneke44927e2008-07-01 17:21:27 +00001305 RetainSummary *NSWindowSumm =
Ted Kremenek7e3a3272009-02-23 02:51:29 +00001306 getPersistentSummary(RetEffect::MakeReceiverAlias(), StopTracking);
Ted Kremenek45642a42008-08-12 18:48:50 +00001307
1308 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1309 "styleMask", "backing", "defer", NULL);
1310
1311 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1312 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001313#endif
Ted Kremenek45642a42008-08-12 18:48:50 +00001314
1315 // For NSPanel (which subclasses NSWindow), allocated objects are not
1316 // self-owned.
Ted Kremeneke5a036a2009-04-03 19:02:51 +00001317 // FIXME: For now we don't track NSPanels. object for the same reason
1318 // as for NSWindow objects.
1319 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
1320
Ted Kremenek45642a42008-08-12 18:48:50 +00001321 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1322 "styleMask", "backing", "defer", NULL);
1323
1324 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1325 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek272aa852008-06-25 21:21:56 +00001326
Ted Kremenekf2717b02008-07-18 17:24:20 +00001327 // Create NSAssertionHandler summaries.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001328 addPanicSummary("NSAssertionHandler", "handleFailureInFunction", "file",
1329 "lineNumber", "description", NULL);
Ted Kremenekf2717b02008-07-18 17:24:20 +00001330
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001331 addPanicSummary("NSAssertionHandler", "handleFailureInMethod", "object",
1332 "file", "lineNumber", "description", NULL);
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001333}
1334
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001335//===----------------------------------------------------------------------===//
Ted Kremenek7aef4842008-04-16 20:40:59 +00001336// Reference-counting logic (typestate + counts).
Ted Kremeneka7338b42008-03-11 06:39:11 +00001337//===----------------------------------------------------------------------===//
1338
Ted Kremeneka7338b42008-03-11 06:39:11 +00001339namespace {
1340
Ted Kremenek7d421f32008-04-09 23:49:11 +00001341class VISIBILITY_HIDDEN RefVal {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001342public:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001343 enum Kind {
1344 Owned = 0, // Owning reference.
1345 NotOwned, // Reference is not owned by still valid (not freed).
1346 Released, // Object has been released.
1347 ReturnedOwned, // Returned object passes ownership to caller.
1348 ReturnedNotOwned, // Return object does not pass ownership to caller.
Ted Kremenek6537a642009-03-17 19:42:23 +00001349 ERROR_START,
1350 ErrorDeallocNotOwned, // -dealloc called on non-owned object.
1351 ErrorDeallocGC, // Calling -dealloc with GC enabled.
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001352 ErrorUseAfterRelease, // Object used after released.
1353 ErrorReleaseNotOwned, // Release of an object that was not owned.
Ted Kremenek6537a642009-03-17 19:42:23 +00001354 ERROR_LEAK_START,
Ted Kremenek311f3d42008-10-22 23:56:21 +00001355 ErrorLeak, // A memory leak due to excessive reference counts.
1356 ErrorLeakReturned // A memory leak due to the returning method not having
1357 // the correct naming conventions.
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001358 };
Ted Kremenek68621b92009-01-28 05:56:51 +00001359
1360private:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001361 Kind kind;
Ted Kremenek68621b92009-01-28 05:56:51 +00001362 RetEffect::ObjKind okind;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001363 unsigned Cnt;
Ted Kremenek272aa852008-06-25 21:21:56 +00001364 QualType T;
1365
Ted Kremenek68621b92009-01-28 05:56:51 +00001366 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, QualType t)
1367 : kind(k), okind(o), Cnt(cnt), T(t) {}
Ted Kremenek0d721572008-03-11 17:48:22 +00001368
Ted Kremenek68621b92009-01-28 05:56:51 +00001369 RefVal(Kind k, unsigned cnt = 0)
1370 : kind(k), okind(RetEffect::AnyObj), Cnt(cnt) {}
1371
1372public:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001373 Kind getKind() const { return kind; }
Ted Kremenek68621b92009-01-28 05:56:51 +00001374
1375 RetEffect::ObjKind getObjKind() const { return okind; }
Ted Kremenek0d721572008-03-11 17:48:22 +00001376
Ted Kremenek6537a642009-03-17 19:42:23 +00001377 unsigned getCount() const { return Cnt; }
1378 void clearCounts() { Cnt = 0; }
1379
Ted Kremenek272aa852008-06-25 21:21:56 +00001380 QualType getType() const { return T; }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001381
1382 // Useful predicates.
Ted Kremenek0d721572008-03-11 17:48:22 +00001383
Ted Kremenek6537a642009-03-17 19:42:23 +00001384 static bool isError(Kind k) { return k >= ERROR_START; }
Ted Kremenek1daa16c2008-03-11 18:14:09 +00001385
Ted Kremenek6537a642009-03-17 19:42:23 +00001386 static bool isLeak(Kind k) { return k >= ERROR_LEAK_START; }
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001387
Ted Kremenekffefc352008-04-11 22:25:11 +00001388 bool isOwned() const {
1389 return getKind() == Owned;
1390 }
1391
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001392 bool isNotOwned() const {
1393 return getKind() == NotOwned;
1394 }
1395
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001396 bool isReturnedOwned() const {
1397 return getKind() == ReturnedOwned;
1398 }
1399
1400 bool isReturnedNotOwned() const {
1401 return getKind() == ReturnedNotOwned;
1402 }
1403
1404 bool isNonLeakError() const {
1405 Kind k = getKind();
1406 return isError(k) && !isLeak(k);
1407 }
1408
Ted Kremenek68621b92009-01-28 05:56:51 +00001409 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
1410 unsigned Count = 1) {
1411 return RefVal(Owned, o, Count, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001412 }
1413
Ted Kremenek68621b92009-01-28 05:56:51 +00001414 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
1415 unsigned Count = 0) {
1416 return RefVal(NotOwned, o, Count, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001417 }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001418
1419 static RefVal makeReturnedOwned(unsigned Count) {
1420 return RefVal(ReturnedOwned, Count);
1421 }
1422
1423 static RefVal makeReturnedNotOwned() {
1424 return RefVal(ReturnedNotOwned);
1425 }
1426
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001427 // Comparison, profiling, and pretty-printing.
Ted Kremenek0d721572008-03-11 17:48:22 +00001428
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001429 bool operator==(const RefVal& X) const {
Ted Kremenek272aa852008-06-25 21:21:56 +00001430 return kind == X.kind && Cnt == X.Cnt && T == X.T;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001431 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001432
Ted Kremenek272aa852008-06-25 21:21:56 +00001433 RefVal operator-(size_t i) const {
Ted Kremenek68621b92009-01-28 05:56:51 +00001434 return RefVal(getKind(), getObjKind(), getCount() - i, getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001435 }
1436
1437 RefVal operator+(size_t i) const {
Ted Kremenek68621b92009-01-28 05:56:51 +00001438 return RefVal(getKind(), getObjKind(), getCount() + i, getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001439 }
1440
1441 RefVal operator^(Kind k) const {
Ted Kremenek68621b92009-01-28 05:56:51 +00001442 return RefVal(k, getObjKind(), getCount(), getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001443 }
Ted Kremenek6537a642009-03-17 19:42:23 +00001444
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001445 void Profile(llvm::FoldingSetNodeID& ID) const {
1446 ID.AddInteger((unsigned) kind);
1447 ID.AddInteger(Cnt);
Ted Kremenek272aa852008-06-25 21:21:56 +00001448 ID.Add(T);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001449 }
1450
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001451 void print(std::ostream& Out) const;
Ted Kremenek0d721572008-03-11 17:48:22 +00001452};
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001453
1454void RefVal::print(std::ostream& Out) const {
Ted Kremenek272aa852008-06-25 21:21:56 +00001455 if (!T.isNull())
1456 Out << "Tracked Type:" << T.getAsString() << '\n';
1457
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001458 switch (getKind()) {
1459 default: assert(false);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001460 case Owned: {
1461 Out << "Owned";
1462 unsigned cnt = getCount();
1463 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001464 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001465 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001466
Ted Kremenekc4f81022008-04-10 23:09:18 +00001467 case NotOwned: {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001468 Out << "NotOwned";
Ted Kremenekc4f81022008-04-10 23:09:18 +00001469 unsigned cnt = getCount();
1470 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001471 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001472 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001473
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001474 case ReturnedOwned: {
1475 Out << "ReturnedOwned";
1476 unsigned cnt = getCount();
1477 if (cnt) Out << " (+ " << cnt << ")";
1478 break;
1479 }
1480
1481 case ReturnedNotOwned: {
1482 Out << "ReturnedNotOwned";
1483 unsigned cnt = getCount();
1484 if (cnt) Out << " (+ " << cnt << ")";
1485 break;
1486 }
1487
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001488 case Released:
1489 Out << "Released";
1490 break;
Ted Kremenek6537a642009-03-17 19:42:23 +00001491
1492 case ErrorDeallocGC:
1493 Out << "-dealloc (GC)";
1494 break;
1495
1496 case ErrorDeallocNotOwned:
1497 Out << "-dealloc (not-owned)";
1498 break;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001499
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001500 case ErrorLeak:
1501 Out << "Leaked";
1502 break;
1503
Ted Kremenek311f3d42008-10-22 23:56:21 +00001504 case ErrorLeakReturned:
1505 Out << "Leaked (Bad naming)";
1506 break;
1507
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001508 case ErrorUseAfterRelease:
1509 Out << "Use-After-Release [ERROR]";
1510 break;
1511
1512 case ErrorReleaseNotOwned:
1513 Out << "Release of Not-Owned [ERROR]";
1514 break;
1515 }
1516}
Ted Kremenek0d721572008-03-11 17:48:22 +00001517
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001518} // end anonymous namespace
1519
1520//===----------------------------------------------------------------------===//
1521// RefBindings - State used to track object reference counts.
1522//===----------------------------------------------------------------------===//
1523
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001524typedef llvm::ImmutableMap<SymbolRef, RefVal> RefBindings;
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001525static int RefBIndex = 0;
Ted Kremenek876d8df2009-02-19 23:47:02 +00001526static std::pair<const void*, const void*> LeakProgramPointTag(&RefBIndex, 0);
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001527
1528namespace clang {
Ted Kremenek91781202008-08-17 03:20:02 +00001529 template<>
1530 struct GRStateTrait<RefBindings> : public GRStatePartialTrait<RefBindings> {
1531 static inline void* GDMIndex() { return &RefBIndex; }
1532 };
1533}
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001534
1535//===----------------------------------------------------------------------===//
Ted Kremenekb6578942009-02-24 19:15:11 +00001536// AutoreleaseBindings - State used to track objects in autorelease pools.
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001537//===----------------------------------------------------------------------===//
1538
Ted Kremenekb6578942009-02-24 19:15:11 +00001539typedef llvm::ImmutableMap<SymbolRef, unsigned> ARCounts;
1540typedef llvm::ImmutableMap<SymbolRef, ARCounts> ARPoolContents;
1541typedef llvm::ImmutableList<SymbolRef> ARStack;
Ted Kremenekaac82832009-02-23 17:45:03 +00001542
Ted Kremenekb6578942009-02-24 19:15:11 +00001543static int AutoRCIndex = 0;
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001544static int AutoRBIndex = 0;
1545
Ted Kremenekb6578942009-02-24 19:15:11 +00001546namespace { class VISIBILITY_HIDDEN AutoreleasePoolContents {}; }
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001547namespace { class VISIBILITY_HIDDEN AutoreleaseStack {}; }
Ted Kremenekb6578942009-02-24 19:15:11 +00001548
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001549namespace clang {
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001550template<> struct GRStateTrait<AutoreleaseStack>
Ted Kremenekb6578942009-02-24 19:15:11 +00001551 : public GRStatePartialTrait<ARStack> {
1552 static inline void* GDMIndex() { return &AutoRBIndex; }
1553};
1554
1555template<> struct GRStateTrait<AutoreleasePoolContents>
1556 : public GRStatePartialTrait<ARPoolContents> {
1557 static inline void* GDMIndex() { return &AutoRCIndex; }
1558};
1559} // end clang namespace
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001560
Ted Kremenek681fb352009-03-20 17:34:15 +00001561static SymbolRef GetCurrentAutoreleasePool(const GRState* state) {
1562 ARStack stack = state->get<AutoreleaseStack>();
1563 return stack.isEmpty() ? SymbolRef() : stack.getHead();
1564}
1565
1566static GRStateRef SendAutorelease(GRStateRef state, ARCounts::Factory &F,
1567 SymbolRef sym) {
1568
1569 SymbolRef pool = GetCurrentAutoreleasePool(state);
1570 const ARCounts *cnts = state.get<AutoreleasePoolContents>(pool);
1571 ARCounts newCnts(0);
1572
1573 if (cnts) {
1574 const unsigned *cnt = (*cnts).lookup(sym);
1575 newCnts = F.Add(*cnts, sym, cnt ? *cnt + 1 : 1);
1576 }
1577 else
1578 newCnts = F.Add(F.GetEmptyMap(), sym, 1);
1579
1580 return state.set<AutoreleasePoolContents>(pool, newCnts);
1581}
1582
Ted Kremenek7aef4842008-04-16 20:40:59 +00001583//===----------------------------------------------------------------------===//
1584// Transfer functions.
1585//===----------------------------------------------------------------------===//
1586
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001587namespace {
1588
Ted Kremenek7d421f32008-04-09 23:49:11 +00001589class VISIBILITY_HIDDEN CFRefCount : public GRSimpleVals {
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001590public:
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001591 class BindingsPrinter : public GRState::Printer {
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001592 public:
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001593 virtual void Print(std::ostream& Out, const GRState* state,
1594 const char* nl, const char* sep);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001595 };
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001596
1597private:
Ted Kremenekc26c4692009-02-18 03:48:14 +00001598 typedef llvm::DenseMap<const GRExprEngine::NodeTy*, const RetainSummary*>
1599 SummaryLogTy;
1600
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001601 RetainSummaryManager Summaries;
Ted Kremenekc26c4692009-02-18 03:48:14 +00001602 SummaryLogTy SummaryLog;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001603 const LangOptions& LOpts;
Ted Kremenekb6578942009-02-24 19:15:11 +00001604 ARCounts::Factory ARCountFactory;
Ted Kremenek91781202008-08-17 03:20:02 +00001605
Ted Kremenek708af042009-02-05 06:50:21 +00001606 BugType *useAfterRelease, *releaseNotOwned;
Ted Kremenek6537a642009-03-17 19:42:23 +00001607 BugType *deallocGC, *deallocNotOwned;
Ted Kremenek708af042009-02-05 06:50:21 +00001608 BugType *leakWithinFunction, *leakAtReturn;
1609 BugReporter *BR;
Ted Kremeneka7338b42008-03-11 06:39:11 +00001610
Ted Kremenekb6578942009-02-24 19:15:11 +00001611 GRStateRef Update(GRStateRef state, SymbolRef sym, RefVal V, ArgEffect E,
1612 RefVal::Kind& hasErr);
1613
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001614 void ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
1615 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001616 Expr* NodeExpr, Expr* ErrorExpr,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001617 ExplodedNode<GRState>* Pred,
1618 const GRState* St,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001619 RefVal::Kind hasErr, SymbolRef Sym);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001620
Ted Kremenek0106e202008-10-24 20:32:50 +00001621 std::pair<GRStateRef, bool>
1622 HandleSymbolDeath(GRStateManager& VMgr, const GRState* St,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001623 const Decl* CD, SymbolRef sid, RefVal V, bool& hasLeak);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001624
Ted Kremenekb6578942009-02-24 19:15:11 +00001625public:
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00001626 CFRefCount(ASTContext& Ctx, bool gcenabled, const LangOptions& lopts)
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001627 : Summaries(Ctx, gcenabled),
Ted Kremenek6537a642009-03-17 19:42:23 +00001628 LOpts(lopts), useAfterRelease(0), releaseNotOwned(0),
1629 deallocGC(0), deallocNotOwned(0),
Ted Kremenek708af042009-02-05 06:50:21 +00001630 leakWithinFunction(0), leakAtReturn(0), BR(0) {}
Ted Kremenek1feab292008-04-16 04:28:53 +00001631
Ted Kremenek708af042009-02-05 06:50:21 +00001632 virtual ~CFRefCount() {}
Ted Kremenek7d421f32008-04-09 23:49:11 +00001633
Ted Kremenekbf6babf2009-02-04 23:49:09 +00001634 void RegisterChecks(BugReporter &BR);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001635
Ted Kremenekb0f2b9e2008-08-16 00:49:49 +00001636 virtual void RegisterPrinters(std::vector<GRState::Printer*>& Printers) {
1637 Printers.push_back(new BindingsPrinter());
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001638 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00001639
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001640 bool isGCEnabled() const { return Summaries.isGCEnabled(); }
Ted Kremenekfe30beb2008-04-30 23:47:44 +00001641 const LangOptions& getLangOptions() const { return LOpts; }
1642
Ted Kremenekc26c4692009-02-18 03:48:14 +00001643 const RetainSummary *getSummaryOfNode(const ExplodedNode<GRState> *N) const {
1644 SummaryLogTy::const_iterator I = SummaryLog.find(N);
1645 return I == SummaryLog.end() ? 0 : I->second;
1646 }
1647
Ted Kremeneka7338b42008-03-11 06:39:11 +00001648 // Calls.
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001649
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001650 void EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001651 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001652 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001653 Expr* Ex,
1654 Expr* Receiver,
Ted Kremenek286e9852009-05-04 04:57:00 +00001655 const RetainSummary& Summ,
Ted Kremenek2719e982008-06-17 02:43:46 +00001656 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001657 ExplodedNode<GRState>* Pred);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001658
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001659 virtual void EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekce0767f2008-03-12 21:06:49 +00001660 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001661 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001662 CallExpr* CE, SVal L,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001663 ExplodedNode<GRState>* Pred);
Ted Kremenek10fe66d2008-04-09 01:10:13 +00001664
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001665
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001666 virtual void EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001667 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001668 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001669 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001670 ExplodedNode<GRState>* Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001671
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001672 bool EvalObjCMessageExprAux(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001673 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001674 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001675 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001676 ExplodedNode<GRState>* Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001677
Ted Kremeneka42be302009-02-14 01:43:44 +00001678 // Stores.
1679 virtual void EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val);
1680
Ted Kremenekffefc352008-04-11 22:25:11 +00001681 // End-of-path.
1682
1683 virtual void EvalEndPath(GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001684 GREndPathNodeBuilder<GRState>& Builder);
Ted Kremenekffefc352008-04-11 22:25:11 +00001685
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001686 virtual void EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek541db372008-04-24 23:57:27 +00001687 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001688 GRStmtNodeBuilder<GRState>& Builder,
1689 ExplodedNode<GRState>* Pred,
Ted Kremenek5c0729b2009-01-21 22:26:05 +00001690 Stmt* S, const GRState* state,
1691 SymbolReaper& SymReaper);
1692
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001693 // Return statements.
1694
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001695 virtual void EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001696 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001697 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001698 ReturnStmt* S,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001699 ExplodedNode<GRState>* Pred);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001700
1701 // Assumptions.
1702
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001703 virtual const GRState* EvalAssume(GRStateManager& VMgr,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001704 const GRState* St, SVal Cond,
Ted Kremenekf22f8682008-07-10 22:03:41 +00001705 bool Assumption, bool& isFeasible);
Ted Kremeneka7338b42008-03-11 06:39:11 +00001706};
1707
1708} // end anonymous namespace
1709
Ted Kremenek681fb352009-03-20 17:34:15 +00001710static void PrintPool(std::ostream &Out, SymbolRef Sym, const GRState *state) {
1711 Out << ' ';
Ted Kremenek74556a12009-03-26 03:35:11 +00001712 if (Sym)
1713 Out << Sym->getSymbolID();
Ted Kremenek681fb352009-03-20 17:34:15 +00001714 else
1715 Out << "<pool>";
1716 Out << ":{";
1717
1718 // Get the contents of the pool.
1719 if (const ARCounts *cnts = state->get<AutoreleasePoolContents>(Sym))
1720 for (ARCounts::iterator J=cnts->begin(), EJ=cnts->end(); J != EJ; ++J)
1721 Out << '(' << J.getKey() << ',' << J.getData() << ')';
1722
1723 Out << '}';
1724}
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001725
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001726void CFRefCount::BindingsPrinter::Print(std::ostream& Out, const GRState* state,
1727 const char* nl, const char* sep) {
Ted Kremenek681fb352009-03-20 17:34:15 +00001728
1729
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001730
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001731 RefBindings B = state->get<RefBindings>();
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001732
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001733 if (!B.isEmpty())
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001734 Out << sep << nl;
1735
1736 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
1737 Out << (*I).first << " : ";
1738 (*I).second.print(Out);
1739 Out << nl;
1740 }
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001741
1742 // Print the autorelease stack.
Ted Kremenek681fb352009-03-20 17:34:15 +00001743 Out << sep << nl << "AR pool stack:";
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001744 ARStack stack = state->get<AutoreleaseStack>();
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001745
Ted Kremenek681fb352009-03-20 17:34:15 +00001746 PrintPool(Out, SymbolRef(), state); // Print the caller's pool.
1747 for (ARStack::iterator I=stack.begin(), E=stack.end(); I!=E; ++I)
1748 PrintPool(Out, *I, state);
1749
1750 Out << nl;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001751}
1752
Ted Kremenek47a72422009-04-29 18:50:19 +00001753//===----------------------------------------------------------------------===//
1754// Error reporting.
1755//===----------------------------------------------------------------------===//
1756
1757namespace {
1758
1759 //===-------------===//
1760 // Bug Descriptions. //
1761 //===-------------===//
1762
1763 class VISIBILITY_HIDDEN CFRefBug : public BugType {
1764 protected:
1765 CFRefCount& TF;
1766
1767 CFRefBug(CFRefCount* tf, const char* name)
1768 : BugType(name, "Memory (Core Foundation/Objective-C)"), TF(*tf) {}
1769 public:
1770
1771 CFRefCount& getTF() { return TF; }
1772 const CFRefCount& getTF() const { return TF; }
1773
1774 // FIXME: Eventually remove.
1775 virtual const char* getDescription() const = 0;
1776
1777 virtual bool isLeak() const { return false; }
1778 };
1779
1780 class VISIBILITY_HIDDEN UseAfterRelease : public CFRefBug {
1781 public:
1782 UseAfterRelease(CFRefCount* tf)
1783 : CFRefBug(tf, "Use-after-release") {}
1784
1785 const char* getDescription() const {
1786 return "Reference-counted object is used after it is released";
1787 }
1788 };
1789
1790 class VISIBILITY_HIDDEN BadRelease : public CFRefBug {
1791 public:
1792 BadRelease(CFRefCount* tf) : CFRefBug(tf, "Bad release") {}
1793
1794 const char* getDescription() const {
1795 return "Incorrect decrement of the reference count of an "
1796 "object is not owned at this point by the caller";
1797 }
1798 };
1799
1800 class VISIBILITY_HIDDEN DeallocGC : public CFRefBug {
1801 public:
1802 DeallocGC(CFRefCount *tf) : CFRefBug(tf,
1803 "-dealloc called while using GC") {}
1804
1805 const char *getDescription() const {
1806 return "-dealloc called while using GC";
1807 }
1808 };
1809
1810 class VISIBILITY_HIDDEN DeallocNotOwned : public CFRefBug {
1811 public:
1812 DeallocNotOwned(CFRefCount *tf) : CFRefBug(tf,
1813 "-dealloc sent to non-exclusively owned object") {}
1814
1815 const char *getDescription() const {
1816 return "-dealloc sent to object that may be referenced elsewhere";
1817 }
1818 };
1819
1820 class VISIBILITY_HIDDEN Leak : public CFRefBug {
1821 const bool isReturn;
1822 protected:
1823 Leak(CFRefCount* tf, const char* name, bool isRet)
1824 : CFRefBug(tf, name), isReturn(isRet) {}
1825 public:
1826
1827 const char* getDescription() const { return ""; }
1828
1829 bool isLeak() const { return true; }
1830 };
1831
1832 class VISIBILITY_HIDDEN LeakAtReturn : public Leak {
1833 public:
1834 LeakAtReturn(CFRefCount* tf, const char* name)
1835 : Leak(tf, name, true) {}
1836 };
1837
1838 class VISIBILITY_HIDDEN LeakWithinFunction : public Leak {
1839 public:
1840 LeakWithinFunction(CFRefCount* tf, const char* name)
1841 : Leak(tf, name, false) {}
1842 };
1843
1844 //===---------===//
1845 // Bug Reports. //
1846 //===---------===//
1847
1848 class VISIBILITY_HIDDEN CFRefReport : public RangedBugReport {
1849 protected:
1850 SymbolRef Sym;
1851 const CFRefCount &TF;
1852 public:
1853 CFRefReport(CFRefBug& D, const CFRefCount &tf,
1854 ExplodedNode<GRState> *n, SymbolRef sym)
1855 : RangedBugReport(D, D.getDescription(), n), Sym(sym), TF(tf) {}
1856
1857 virtual ~CFRefReport() {}
1858
1859 CFRefBug& getBugType() {
1860 return (CFRefBug&) RangedBugReport::getBugType();
1861 }
1862 const CFRefBug& getBugType() const {
1863 return (const CFRefBug&) RangedBugReport::getBugType();
1864 }
1865
1866 virtual void getRanges(BugReporter& BR, const SourceRange*& beg,
1867 const SourceRange*& end) {
1868
1869 if (!getBugType().isLeak())
1870 RangedBugReport::getRanges(BR, beg, end);
1871 else
1872 beg = end = 0;
1873 }
1874
1875 SymbolRef getSymbol() const { return Sym; }
1876
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00001877 PathDiagnosticPiece* getEndPath(BugReporterContext& BRC,
Ted Kremenek47a72422009-04-29 18:50:19 +00001878 const ExplodedNode<GRState>* N);
1879
1880 std::pair<const char**,const char**> getExtraDescriptiveText();
1881
1882 PathDiagnosticPiece* VisitNode(const ExplodedNode<GRState>* N,
1883 const ExplodedNode<GRState>* PrevN,
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00001884 BugReporterContext& BRC);
Ted Kremenek47a72422009-04-29 18:50:19 +00001885 };
1886
1887 class VISIBILITY_HIDDEN CFRefLeakReport : public CFRefReport {
1888 SourceLocation AllocSite;
1889 const MemRegion* AllocBinding;
1890 public:
1891 CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
1892 ExplodedNode<GRState> *n, SymbolRef sym,
1893 GRExprEngine& Eng);
1894
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00001895 PathDiagnosticPiece* getEndPath(BugReporterContext& BRC,
Ted Kremenek47a72422009-04-29 18:50:19 +00001896 const ExplodedNode<GRState>* N);
1897
1898 SourceLocation getLocation() const { return AllocSite; }
1899 };
1900} // end anonymous namespace
1901
1902void CFRefCount::RegisterChecks(BugReporter& BR) {
1903 useAfterRelease = new UseAfterRelease(this);
1904 BR.Register(useAfterRelease);
1905
1906 releaseNotOwned = new BadRelease(this);
1907 BR.Register(releaseNotOwned);
1908
1909 deallocGC = new DeallocGC(this);
1910 BR.Register(deallocGC);
1911
1912 deallocNotOwned = new DeallocNotOwned(this);
1913 BR.Register(deallocNotOwned);
1914
1915 // First register "return" leaks.
1916 const char* name = 0;
1917
1918 if (isGCEnabled())
1919 name = "Leak of returned object when using garbage collection";
1920 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
1921 name = "Leak of returned object when not using garbage collection (GC) in "
1922 "dual GC/non-GC code";
1923 else {
1924 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
1925 name = "Leak of returned object";
1926 }
1927
1928 leakAtReturn = new LeakAtReturn(this, name);
1929 BR.Register(leakAtReturn);
1930
1931 // Second, register leaks within a function/method.
1932 if (isGCEnabled())
1933 name = "Leak of object when using garbage collection";
1934 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
1935 name = "Leak of object when not using garbage collection (GC) in "
1936 "dual GC/non-GC code";
1937 else {
1938 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
1939 name = "Leak";
1940 }
1941
1942 leakWithinFunction = new LeakWithinFunction(this, name);
1943 BR.Register(leakWithinFunction);
1944
1945 // Save the reference to the BugReporter.
1946 this->BR = &BR;
1947}
1948
1949static const char* Msgs[] = {
1950 // GC only
1951 "Code is compiled to only use garbage collection",
1952 // No GC.
1953 "Code is compiled to use reference counts",
1954 // Hybrid, with GC.
1955 "Code is compiled to use either garbage collection (GC) or reference counts"
1956 " (non-GC). The bug occurs with GC enabled",
1957 // Hybrid, without GC
1958 "Code is compiled to use either garbage collection (GC) or reference counts"
1959 " (non-GC). The bug occurs in non-GC mode"
1960};
1961
1962std::pair<const char**,const char**> CFRefReport::getExtraDescriptiveText() {
1963 CFRefCount& TF = static_cast<CFRefBug&>(getBugType()).getTF();
1964
1965 switch (TF.getLangOptions().getGCMode()) {
1966 default:
1967 assert(false);
1968
1969 case LangOptions::GCOnly:
1970 assert (TF.isGCEnabled());
1971 return std::make_pair(&Msgs[0], &Msgs[0]+1);
1972
1973 case LangOptions::NonGC:
1974 assert (!TF.isGCEnabled());
1975 return std::make_pair(&Msgs[1], &Msgs[1]+1);
1976
1977 case LangOptions::HybridGC:
1978 if (TF.isGCEnabled())
1979 return std::make_pair(&Msgs[2], &Msgs[2]+1);
1980 else
1981 return std::make_pair(&Msgs[3], &Msgs[3]+1);
1982 }
1983}
1984
1985static inline bool contains(const llvm::SmallVectorImpl<ArgEffect>& V,
1986 ArgEffect X) {
1987 for (llvm::SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
1988 I!=E; ++I)
1989 if (*I == X) return true;
1990
1991 return false;
1992}
1993
1994PathDiagnosticPiece* CFRefReport::VisitNode(const ExplodedNode<GRState>* N,
1995 const ExplodedNode<GRState>* PrevN,
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00001996 BugReporterContext& BRC) {
Ted Kremenek47a72422009-04-29 18:50:19 +00001997
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00001998 // Check if the type state has changed.
1999 GRStateManager &StMgr = BRC.getStateManager();
Ted Kremenek47a72422009-04-29 18:50:19 +00002000 GRStateRef PrevSt(PrevN->getState(), StMgr);
2001 GRStateRef CurrSt(N->getState(), StMgr);
2002
2003 const RefVal* CurrT = CurrSt.get<RefBindings>(Sym);
2004 if (!CurrT) return NULL;
2005
2006 const RefVal& CurrV = *CurrT;
2007 const RefVal* PrevT = PrevSt.get<RefBindings>(Sym);
2008
2009 // Create a string buffer to constain all the useful things we want
2010 // to tell the user.
2011 std::string sbuf;
2012 llvm::raw_string_ostream os(sbuf);
2013
2014 // This is the allocation site since the previous node had no bindings
2015 // for this symbol.
2016 if (!PrevT) {
2017 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2018
2019 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2020 // Get the name of the callee (if it is available).
2021 SVal X = CurrSt.GetSValAsScalarOrLoc(CE->getCallee());
2022 if (const FunctionDecl* FD = X.getAsFunctionDecl())
2023 os << "Call to function '" << FD->getNameAsString() <<'\'';
2024 else
2025 os << "function call";
2026 }
2027 else {
2028 assert (isa<ObjCMessageExpr>(S));
2029 os << "Method";
2030 }
2031
2032 if (CurrV.getObjKind() == RetEffect::CF) {
2033 os << " returns a Core Foundation object with a ";
2034 }
2035 else {
2036 assert (CurrV.getObjKind() == RetEffect::ObjC);
2037 os << " returns an Objective-C object with a ";
2038 }
2039
2040 if (CurrV.isOwned()) {
2041 os << "+1 retain count (owning reference).";
2042
2043 if (static_cast<CFRefBug&>(getBugType()).getTF().isGCEnabled()) {
2044 assert(CurrV.getObjKind() == RetEffect::CF);
2045 os << " "
2046 "Core Foundation objects are not automatically garbage collected.";
2047 }
2048 }
2049 else {
2050 assert (CurrV.isNotOwned());
2051 os << "+0 retain count (non-owning reference).";
2052 }
2053
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002054 PathDiagnosticLocation Pos(S, BRC.getSourceManager());
Ted Kremenek47a72422009-04-29 18:50:19 +00002055 return new PathDiagnosticEventPiece(Pos, os.str());
2056 }
2057
2058 // Gather up the effects that were performed on the object at this
2059 // program point
2060 llvm::SmallVector<ArgEffect, 2> AEffects;
2061
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002062 if (const RetainSummary *Summ =
2063 TF.getSummaryOfNode(BRC.getNodeResolver().getOriginalNode(N))) {
Ted Kremenek47a72422009-04-29 18:50:19 +00002064 // We only have summaries attached to nodes after evaluating CallExpr and
2065 // ObjCMessageExprs.
2066 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2067
2068 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2069 // Iterate through the parameter expressions and see if the symbol
2070 // was ever passed as an argument.
2071 unsigned i = 0;
2072
2073 for (CallExpr::arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
2074 AI!=AE; ++AI, ++i) {
2075
2076 // Retrieve the value of the argument. Is it the symbol
2077 // we are interested in?
2078 if (CurrSt.GetSValAsScalarOrLoc(*AI).getAsLocSymbol() != Sym)
2079 continue;
2080
2081 // We have an argument. Get the effect!
2082 AEffects.push_back(Summ->getArg(i));
2083 }
2084 }
2085 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
2086 if (Expr *receiver = ME->getReceiver())
2087 if (CurrSt.GetSValAsScalarOrLoc(receiver).getAsLocSymbol() == Sym) {
2088 // The symbol we are tracking is the receiver.
2089 AEffects.push_back(Summ->getReceiverEffect());
2090 }
2091 }
2092 }
2093
2094 do {
2095 // Get the previous type state.
2096 RefVal PrevV = *PrevT;
2097
2098 // Specially handle -dealloc.
2099 if (!TF.isGCEnabled() && contains(AEffects, Dealloc)) {
2100 // Determine if the object's reference count was pushed to zero.
2101 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2102 // We may not have transitioned to 'release' if we hit an error.
2103 // This case is handled elsewhere.
2104 if (CurrV.getKind() == RefVal::Released) {
2105 assert(CurrV.getCount() == 0);
2106 os << "Object released by directly sending the '-dealloc' message";
2107 break;
2108 }
2109 }
2110
2111 // Specially handle CFMakeCollectable and friends.
2112 if (contains(AEffects, MakeCollectable)) {
2113 // Get the name of the function.
2114 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2115 SVal X = CurrSt.GetSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee());
2116 const FunctionDecl* FD = X.getAsFunctionDecl();
2117 const std::string& FName = FD->getNameAsString();
2118
2119 if (TF.isGCEnabled()) {
2120 // Determine if the object's reference count was pushed to zero.
2121 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2122
2123 os << "In GC mode a call to '" << FName
2124 << "' decrements an object's retain count and registers the "
2125 "object with the garbage collector. ";
2126
2127 if (CurrV.getKind() == RefVal::Released) {
2128 assert(CurrV.getCount() == 0);
2129 os << "Since it now has a 0 retain count the object can be "
2130 "automatically collected by the garbage collector.";
2131 }
2132 else
2133 os << "An object must have a 0 retain count to be garbage collected. "
2134 "After this call its retain count is +" << CurrV.getCount()
2135 << '.';
2136 }
2137 else
2138 os << "When GC is not enabled a call to '" << FName
2139 << "' has no effect on its argument.";
2140
2141 // Nothing more to say.
2142 break;
2143 }
2144
2145 // Determine if the typestate has changed.
2146 if (!(PrevV == CurrV))
2147 switch (CurrV.getKind()) {
2148 case RefVal::Owned:
2149 case RefVal::NotOwned:
2150
2151 if (PrevV.getCount() == CurrV.getCount())
2152 return 0;
2153
2154 if (PrevV.getCount() > CurrV.getCount())
2155 os << "Reference count decremented.";
2156 else
2157 os << "Reference count incremented.";
2158
2159 if (unsigned Count = CurrV.getCount())
2160 os << " The object now has a +" << Count << " retain count.";
2161
2162 if (PrevV.getKind() == RefVal::Released) {
2163 assert(TF.isGCEnabled() && CurrV.getCount() > 0);
2164 os << " The object is not eligible for garbage collection until the "
2165 "retain count reaches 0 again.";
2166 }
2167
2168 break;
2169
2170 case RefVal::Released:
2171 os << "Object released.";
2172 break;
2173
2174 case RefVal::ReturnedOwned:
2175 os << "Object returned to caller as an owning reference (single retain "
2176 "count transferred to caller).";
2177 break;
2178
2179 case RefVal::ReturnedNotOwned:
2180 os << "Object returned to caller with a +0 (non-owning) retain count.";
2181 break;
2182
2183 default:
2184 return NULL;
2185 }
2186
2187 // Emit any remaining diagnostics for the argument effects (if any).
2188 for (llvm::SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
2189 E=AEffects.end(); I != E; ++I) {
2190
2191 // A bunch of things have alternate behavior under GC.
2192 if (TF.isGCEnabled())
2193 switch (*I) {
2194 default: break;
2195 case Autorelease:
2196 os << "In GC mode an 'autorelease' has no effect.";
2197 continue;
2198 case IncRefMsg:
2199 os << "In GC mode the 'retain' message has no effect.";
2200 continue;
2201 case DecRefMsg:
2202 os << "In GC mode the 'release' message has no effect.";
2203 continue;
2204 }
2205 }
2206 } while(0);
2207
2208 if (os.str().empty())
2209 return 0; // We have nothing to say!
2210
2211 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002212 PathDiagnosticLocation Pos(S, BRC.getSourceManager());
Ted Kremenek47a72422009-04-29 18:50:19 +00002213 PathDiagnosticPiece* P = new PathDiagnosticEventPiece(Pos, os.str());
2214
2215 // Add the range by scanning the children of the statement for any bindings
2216 // to Sym.
2217 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I)
2218 if (Expr* Exp = dyn_cast_or_null<Expr>(*I))
2219 if (CurrSt.GetSValAsScalarOrLoc(Exp).getAsLocSymbol() == Sym) {
2220 P->addRange(Exp->getSourceRange());
2221 break;
2222 }
2223
2224 return P;
2225}
2226
2227namespace {
2228 class VISIBILITY_HIDDEN FindUniqueBinding :
2229 public StoreManager::BindingsHandler {
2230 SymbolRef Sym;
2231 const MemRegion* Binding;
2232 bool First;
2233
2234 public:
2235 FindUniqueBinding(SymbolRef sym) : Sym(sym), Binding(0), First(true) {}
2236
2237 bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
2238 SVal val) {
2239
2240 SymbolRef SymV = val.getAsSymbol();
2241 if (!SymV || SymV != Sym)
2242 return true;
2243
2244 if (Binding) {
2245 First = false;
2246 return false;
2247 }
2248 else
2249 Binding = R;
2250
2251 return true;
2252 }
2253
2254 operator bool() { return First && Binding; }
2255 const MemRegion* getRegion() { return Binding; }
2256 };
2257}
2258
2259static std::pair<const ExplodedNode<GRState>*,const MemRegion*>
2260GetAllocationSite(GRStateManager& StateMgr, const ExplodedNode<GRState>* N,
2261 SymbolRef Sym) {
2262
2263 // Find both first node that referred to the tracked symbol and the
2264 // memory location that value was store to.
2265 const ExplodedNode<GRState>* Last = N;
2266 const MemRegion* FirstBinding = 0;
2267
2268 while (N) {
2269 const GRState* St = N->getState();
2270 RefBindings B = St->get<RefBindings>();
2271
2272 if (!B.lookup(Sym))
2273 break;
2274
2275 FindUniqueBinding FB(Sym);
2276 StateMgr.iterBindings(St, FB);
2277 if (FB) FirstBinding = FB.getRegion();
2278
2279 Last = N;
2280 N = N->pred_empty() ? NULL : *(N->pred_begin());
2281 }
2282
2283 return std::make_pair(Last, FirstBinding);
2284}
2285
2286PathDiagnosticPiece*
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002287CFRefReport::getEndPath(BugReporterContext& BRC,
2288 const ExplodedNode<GRState>* EndN) {
2289 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenek47a72422009-04-29 18:50:19 +00002290 // assigned to different variables, etc.
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002291 BRC.addNotableSymbol(Sym);
2292 return RangedBugReport::getEndPath(BRC, EndN);
Ted Kremenek47a72422009-04-29 18:50:19 +00002293}
2294
2295PathDiagnosticPiece*
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002296CFRefLeakReport::getEndPath(BugReporterContext& BRC,
2297 const ExplodedNode<GRState>* EndN){
Ted Kremenek47a72422009-04-29 18:50:19 +00002298
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002299 // Tell the BugReporterContext to report cases when the tracked symbol is
Ted Kremenek47a72422009-04-29 18:50:19 +00002300 // assigned to different variables, etc.
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002301 BRC.addNotableSymbol(Sym);
Ted Kremenek47a72422009-04-29 18:50:19 +00002302
2303 // We are reporting a leak. Walk up the graph to get to the first node where
2304 // the symbol appeared, and also get the first VarDecl that tracked object
2305 // is stored to.
2306 const ExplodedNode<GRState>* AllocNode = 0;
2307 const MemRegion* FirstBinding = 0;
2308
2309 llvm::tie(AllocNode, FirstBinding) =
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002310 GetAllocationSite(BRC.getStateManager(), EndN, Sym);
Ted Kremenek47a72422009-04-29 18:50:19 +00002311
2312 // Get the allocate site.
2313 assert(AllocNode);
2314 Stmt* FirstStmt = cast<PostStmt>(AllocNode->getLocation()).getStmt();
2315
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002316 SourceManager& SMgr = BRC.getSourceManager();
Ted Kremenek47a72422009-04-29 18:50:19 +00002317 unsigned AllocLine =SMgr.getInstantiationLineNumber(FirstStmt->getLocStart());
2318
2319 // Compute an actual location for the leak. Sometimes a leak doesn't
2320 // occur at an actual statement (e.g., transition between blocks; end
2321 // of function) so we need to walk the graph and compute a real location.
2322 const ExplodedNode<GRState>* LeakN = EndN;
2323 PathDiagnosticLocation L;
2324
2325 while (LeakN) {
2326 ProgramPoint P = LeakN->getLocation();
2327
2328 if (const PostStmt *PS = dyn_cast<PostStmt>(&P)) {
2329 L = PathDiagnosticLocation(PS->getStmt()->getLocStart(), SMgr);
2330 break;
2331 }
2332 else if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
2333 if (const Stmt* Term = BE->getSrc()->getTerminator()) {
2334 L = PathDiagnosticLocation(Term->getLocStart(), SMgr);
2335 break;
2336 }
2337 }
2338
2339 LeakN = LeakN->succ_empty() ? 0 : *(LeakN->succ_begin());
2340 }
2341
2342 if (!L.isValid()) {
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002343 const Decl &D = BRC.getCodeDecl();
2344 L = PathDiagnosticLocation(D.getBodyRBrace(BRC.getASTContext()), SMgr);
Ted Kremenek47a72422009-04-29 18:50:19 +00002345 }
2346
2347 std::string sbuf;
2348 llvm::raw_string_ostream os(sbuf);
2349
2350 os << "Object allocated on line " << AllocLine;
2351
2352 if (FirstBinding)
2353 os << " and stored into '" << FirstBinding->getString() << '\'';
2354
2355 // Get the retain count.
2356 const RefVal* RV = EndN->getState()->get<RefBindings>(Sym);
2357
2358 if (RV->getKind() == RefVal::ErrorLeakReturned) {
2359 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
2360 // ojbects. Only "copy", "alloc", "retain" and "new" transfer ownership
2361 // to the caller for NS objects.
Ted Kremenekc3bc6c82009-05-06 21:39:49 +00002362 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(BRC.getCodeDecl());
Ted Kremenek47a72422009-04-29 18:50:19 +00002363 os << " is returned from a method whose name ('"
Ted Kremenek314b1952009-04-29 23:03:22 +00002364 << MD.getSelector().getAsString()
Ted Kremenek47a72422009-04-29 18:50:19 +00002365 << "') does not contain 'copy' or otherwise starts with"
2366 " 'new' or 'alloc'. This violates the naming convention rules given"
Ted Kremenek2a410c92009-04-29 22:25:52 +00002367 " in the Memory Management Guide for Cocoa (object leaked)";
Ted Kremenek47a72422009-04-29 18:50:19 +00002368 }
2369 else
2370 os << " is no longer referenced after this point and has a retain count of"
Ted Kremenek2a410c92009-04-29 22:25:52 +00002371 " +" << RV->getCount() << " (object leaked)";
Ted Kremenek47a72422009-04-29 18:50:19 +00002372
2373 return new PathDiagnosticEventPiece(L, os.str());
2374}
2375
2376
2377CFRefLeakReport::CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2378 ExplodedNode<GRState> *n,
2379 SymbolRef sym, GRExprEngine& Eng)
2380: CFRefReport(D, tf, n, sym)
2381{
2382
2383 // Most bug reports are cached at the location where they occured.
2384 // With leaks, we want to unique them by the location where they were
2385 // allocated, and only report a single path. To do this, we need to find
2386 // the allocation site of a piece of tracked memory, which we do via a
2387 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2388 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2389 // that all ancestor nodes that represent the allocation site have the
2390 // same SourceLocation.
2391 const ExplodedNode<GRState>* AllocNode = 0;
2392
2393 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding.
2394 GetAllocationSite(Eng.getStateManager(), getEndNode(), getSymbol());
2395
2396 // Get the SourceLocation for the allocation site.
2397 ProgramPoint P = AllocNode->getLocation();
2398 AllocSite = cast<PostStmt>(P).getStmt()->getLocStart();
2399
2400 // Fill in the description of the bug.
2401 Description.clear();
2402 llvm::raw_string_ostream os(Description);
2403 SourceManager& SMgr = Eng.getContext().getSourceManager();
2404 unsigned AllocLine = SMgr.getInstantiationLineNumber(AllocSite);
Ted Kremenek2e9d0302009-05-02 19:05:19 +00002405 os << "Potential leak ";
2406 if (tf.isGCEnabled()) {
2407 os << "(when using garbage collection) ";
2408 }
2409 os << "of an object allocated on line " << AllocLine;
Ted Kremenek47a72422009-04-29 18:50:19 +00002410
2411 // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2412 if (AllocBinding)
2413 os << " and stored into '" << AllocBinding->getString() << '\'';
2414}
2415
2416//===----------------------------------------------------------------------===//
2417// Main checker logic.
2418//===----------------------------------------------------------------------===//
2419
Ted Kremenek272aa852008-06-25 21:21:56 +00002420/// GetReturnType - Used to get the return type of a message expression or
2421/// function call with the intention of affixing that type to a tracked symbol.
2422/// While the the return type can be queried directly from RetEx, when
2423/// invoking class methods we augment to the return type to be that of
2424/// a pointer to the class (as opposed it just being id).
2425static QualType GetReturnType(Expr* RetE, ASTContext& Ctx) {
2426
2427 QualType RetTy = RetE->getType();
2428
2429 // FIXME: We aren't handling id<...>.
Chris Lattnerb724ab22008-07-26 22:36:27 +00002430 const PointerType* PT = RetTy->getAsPointerType();
Ted Kremenek272aa852008-06-25 21:21:56 +00002431 if (!PT)
2432 return RetTy;
2433
2434 // If RetEx is not a message expression just return its type.
2435 // If RetEx is a message expression, return its types if it is something
2436 /// more specific than id.
2437
2438 ObjCMessageExpr* ME = dyn_cast<ObjCMessageExpr>(RetE);
2439
Steve Naroff17c03822009-02-12 17:52:19 +00002440 if (!ME || !Ctx.isObjCIdStructType(PT->getPointeeType()))
Ted Kremenek272aa852008-06-25 21:21:56 +00002441 return RetTy;
2442
2443 ObjCInterfaceDecl* D = ME->getClassInfo().first;
2444
2445 // At this point we know the return type of the message expression is id.
2446 // If we have an ObjCInterceDecl, we know this is a call to a class method
2447 // whose type we can resolve. In such cases, promote the return type to
2448 // Class*.
2449 return !D ? RetTy : Ctx.getPointerType(Ctx.getObjCInterfaceType(D));
2450}
2451
2452
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002453void CFRefCount::EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002454 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002455 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002456 Expr* Ex,
2457 Expr* Receiver,
Ted Kremenek286e9852009-05-04 04:57:00 +00002458 const RetainSummary& Summ,
Zhongxing Xucac107a2009-04-20 05:24:46 +00002459 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002460 ExplodedNode<GRState>* Pred) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002461
Ted Kremeneka7338b42008-03-11 06:39:11 +00002462 // Get the state.
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002463 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenek0106e202008-10-24 20:32:50 +00002464 ASTContext& Ctx = Eng.getStateManager().getContext();
Ted Kremenek227c5372008-05-06 02:41:27 +00002465
2466 // Evaluate the effect of the arguments.
Ted Kremenek1feab292008-04-16 04:28:53 +00002467 RefVal::Kind hasErr = (RefVal::Kind) 0;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002468 unsigned idx = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002469 Expr* ErrorExpr = NULL;
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002470 SymbolRef ErrorSym = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002471
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002472 for (ExprIterator I = arg_beg; I != arg_end; ++I, ++idx) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002473 SVal V = state.GetSValAsScalarOrLoc(*I);
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002474 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002475
Ted Kremenek74556a12009-03-26 03:35:11 +00002476 if (Sym)
Ted Kremenekb6578942009-02-24 19:15:11 +00002477 if (RefBindings::data_type* T = state.get<RefBindings>(Sym)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002478 state = Update(state, Sym, *T, Summ.getArg(idx), hasErr);
Ted Kremenekb6578942009-02-24 19:15:11 +00002479 if (hasErr) {
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002480 ErrorExpr = *I;
Ted Kremenek6064a362008-07-07 16:21:19 +00002481 ErrorSym = Sym;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002482 break;
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002483 }
2484 continue;
Ted Kremenekb6578942009-02-24 19:15:11 +00002485 }
Ted Kremenekede40b72008-07-09 18:11:16 +00002486
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002487 if (isa<Loc>(V)) {
2488 if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(&V)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002489 if (Summ.getArg(idx) == DoNothingByRef)
Ted Kremenekede40b72008-07-09 18:11:16 +00002490 continue;
2491
2492 // Invalidate the value of the variable passed by reference.
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002493
2494 // FIXME: Either this logic should also be replicated in GRSimpleVals
2495 // or should be pulled into a separate "constraint engine."
Ted Kremenekede40b72008-07-09 18:11:16 +00002496
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002497 // FIXME: We can have collisions on the conjured symbol if the
2498 // expression *I also creates conjured symbols. We probably want
2499 // to identify conjured symbols by an expression pair: the enclosing
2500 // expression (the context) and the expression itself. This should
Ted Kremenekede40b72008-07-09 18:11:16 +00002501 // disambiguate conjured symbols.
Ted Kremenekb15eba42008-10-04 05:50:14 +00002502
Ted Kremenek38a4b4b2008-10-17 20:28:54 +00002503 const TypedRegion* R = dyn_cast<TypedRegion>(MR->getRegion());
Zhongxing Xub9d47a42009-04-29 02:30:09 +00002504
Ted Kremenek73ec7732009-05-06 18:19:24 +00002505 if (R) {
2506 // Are we dealing with an ElementRegion? If the element type is
2507 // a basic integer type (e.g., char, int) and the underying region
2508 // is also typed then strip off the ElementRegion.
2509 // FIXME: We really need to think about this for the general case
2510 // as sometimes we are reasoning about arrays and other times
2511 // about (char*), etc., is just a form of passing raw bytes.
2512 // e.g., void *p = alloca(); foo((char*)p);
2513 if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
2514 // Checking for 'integral type' is probably too promiscuous, but
2515 // we'll leave it in for now until we have a systematic way of
2516 // handling all of these cases. Eventually we need to come up
2517 // with an interface to StoreManager so that this logic can be
2518 // approriately delegated to the respective StoreManagers while
2519 // still allowing us to do checker-specific logic (e.g.,
2520 // invalidating reference counts), probably via callbacks.
2521 if (ER->getElementType()->isIntegralType())
2522 if (const TypedRegion *superReg =
2523 dyn_cast<TypedRegion>(ER->getSuperRegion()))
2524 R = superReg;
2525 // FIXME: What about layers of ElementRegions?
2526 }
2527
Ted Kremenek618c6cd2008-12-18 23:34:57 +00002528 // Is the invalidated variable something that we were tracking?
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002529 SymbolRef Sym = state.GetSValAsScalarOrLoc(R).getAsLocSymbol();
Ted Kremenek618c6cd2008-12-18 23:34:57 +00002530
Ted Kremenek53b24182009-03-04 22:56:43 +00002531 // Remove any existing reference-count binding.
Ted Kremenek74556a12009-03-26 03:35:11 +00002532 if (Sym) state = state.remove<RefBindings>(Sym);
Ted Kremenekb15eba42008-10-04 05:50:14 +00002533
Ted Kremenek53b24182009-03-04 22:56:43 +00002534 if (R->isBoundable(Ctx)) {
2535 // Set the value of the variable to be a conjured symbol.
2536 unsigned Count = Builder.getCurrentBlockCount();
2537 QualType T = R->getRValueType(Ctx);
2538
Zhongxing Xu079dc352009-04-09 06:03:54 +00002539 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())){
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002540 ValueManager &ValMgr = Eng.getValueManager();
2541 SVal V = ValMgr.getConjuredSymbolVal(*I, T, Count);
Zhongxing Xu079dc352009-04-09 06:03:54 +00002542 state = state.BindLoc(Loc::MakeVal(R), V);
Ted Kremenek53b24182009-03-04 22:56:43 +00002543 }
2544 else if (const RecordType *RT = T->getAsStructureType()) {
2545 // Handle structs in a not so awesome way. Here we just
2546 // eagerly bind new symbols to the fields. In reality we
2547 // should have the store manager handle this. The idea is just
2548 // to prototype some basic functionality here. All of this logic
2549 // should one day soon just go away.
2550 const RecordDecl *RD = RT->getDecl()->getDefinition(Ctx);
2551
2552 // No record definition. There is nothing we can do.
2553 if (!RD)
2554 continue;
2555
2556 MemRegionManager &MRMgr = state.getManager().getRegionManager();
2557
2558 // Iterate through the fields and construct new symbols.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002559 for (RecordDecl::field_iterator FI=RD->field_begin(Ctx),
2560 FE=RD->field_end(Ctx); FI!=FE; ++FI) {
Ted Kremenek53b24182009-03-04 22:56:43 +00002561
2562 // For now just handle scalar fields.
2563 FieldDecl *FD = *FI;
2564 QualType FT = FD->getType();
2565
2566 if (Loc::IsLocType(FT) ||
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002567 (FT->isIntegerType() && FT->isScalarType())) {
Ted Kremenek53b24182009-03-04 22:56:43 +00002568 const FieldRegion* FR = MRMgr.getFieldRegion(FD, R);
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002569 ValueManager &ValMgr = Eng.getValueManager();
2570 SVal V = ValMgr.getConjuredSymbolVal(*I, FT, Count);
Zhongxing Xuc458e322009-04-09 06:32:20 +00002571 state = state.BindLoc(Loc::MakeVal(FR), V);
Ted Kremenek53b24182009-03-04 22:56:43 +00002572 }
2573 }
2574 }
2575 else {
2576 // Just blast away other values.
2577 state = state.BindLoc(*MR, UnknownVal());
2578 }
Ted Kremenek8f90e712008-10-17 22:23:12 +00002579 }
Ted Kremenekb15eba42008-10-04 05:50:14 +00002580 }
2581 else
Ted Kremenek09102db2008-11-12 19:22:09 +00002582 state = state.BindLoc(*MR, UnknownVal());
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002583 }
2584 else {
2585 // Nuke all other arguments passed by reference.
Zhongxing Xu097fc982008-10-17 05:57:07 +00002586 state = state.Unbind(cast<Loc>(V));
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002587 }
Ted Kremeneke4924202008-04-11 20:51:02 +00002588 }
Zhongxing Xu097fc982008-10-17 05:57:07 +00002589 else if (isa<nonloc::LocAsInteger>(V))
2590 state = state.Unbind(cast<nonloc::LocAsInteger>(V).getLoc());
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002591 }
Ted Kremenek1feab292008-04-16 04:28:53 +00002592
Ted Kremenek272aa852008-06-25 21:21:56 +00002593 // Evaluate the effect on the message receiver.
Ted Kremenek227c5372008-05-06 02:41:27 +00002594 if (!ErrorExpr && Receiver) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002595 SymbolRef Sym = state.GetSValAsScalarOrLoc(Receiver).getAsLocSymbol();
Ted Kremenek74556a12009-03-26 03:35:11 +00002596 if (Sym) {
Ted Kremenekb6578942009-02-24 19:15:11 +00002597 if (const RefVal* T = state.get<RefBindings>(Sym)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002598 state = Update(state, Sym, *T, Summ.getReceiverEffect(), hasErr);
Ted Kremenekb6578942009-02-24 19:15:11 +00002599 if (hasErr) {
Ted Kremenek227c5372008-05-06 02:41:27 +00002600 ErrorExpr = Receiver;
Ted Kremenek6064a362008-07-07 16:21:19 +00002601 ErrorSym = Sym;
Ted Kremenek227c5372008-05-06 02:41:27 +00002602 }
Ted Kremenekb6578942009-02-24 19:15:11 +00002603 }
Ted Kremenek227c5372008-05-06 02:41:27 +00002604 }
2605 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002606
Ted Kremenek272aa852008-06-25 21:21:56 +00002607 // Process any errors.
Ted Kremenek1feab292008-04-16 04:28:53 +00002608 if (hasErr) {
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002609 ProcessNonLeakError(Dst, Builder, Ex, ErrorExpr, Pred, state,
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002610 hasErr, ErrorSym);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002611 return;
Ted Kremenek0d721572008-03-11 17:48:22 +00002612 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002613
Ted Kremenekf2717b02008-07-18 17:24:20 +00002614 // Consult the summary for the return value.
Ted Kremenek286e9852009-05-04 04:57:00 +00002615 RetEffect RE = Summ.getRetEffect();
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002616
2617 switch (RE.getKind()) {
2618 default:
2619 assert (false && "Unhandled RetEffect."); break;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002620
Ted Kremenek8f90e712008-10-17 22:23:12 +00002621 case RetEffect::NoRet: {
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002622
Ted Kremenek455dd862008-04-11 20:23:24 +00002623 // Make up a symbol for the return value (not reference counted).
Ted Kremeneke4924202008-04-11 20:51:02 +00002624 // FIXME: This is basically copy-and-paste from GRSimpleVals. We
2625 // should compose behavior, not copy it.
Ted Kremenek455dd862008-04-11 20:23:24 +00002626
Ted Kremenek8f90e712008-10-17 22:23:12 +00002627 // FIXME: We eventually should handle structs and other compound types
2628 // that are returned by value.
2629
2630 QualType T = Ex->getType();
2631
Ted Kremenek79413a52008-11-13 06:10:40 +00002632 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())) {
Ted Kremenek455dd862008-04-11 20:23:24 +00002633 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002634 ValueManager &ValMgr = Eng.getValueManager();
2635 SVal X = ValMgr.getConjuredSymbolVal(Ex, T, Count);
Ted Kremenek09102db2008-11-12 19:22:09 +00002636 state = state.BindExpr(Ex, X, false);
Ted Kremenek455dd862008-04-11 20:23:24 +00002637 }
2638
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002639 break;
Ted Kremenek8f90e712008-10-17 22:23:12 +00002640 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002641
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002642 case RetEffect::Alias: {
Ted Kremenek272aa852008-06-25 21:21:56 +00002643 unsigned idx = RE.getIndex();
Ted Kremenek2719e982008-06-17 02:43:46 +00002644 assert (arg_end >= arg_beg);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002645 assert (idx < (unsigned) (arg_end - arg_beg));
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002646 SVal V = state.GetSValAsScalarOrLoc(*(arg_beg+idx));
Ted Kremenek09102db2008-11-12 19:22:09 +00002647 state = state.BindExpr(Ex, V, false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002648 break;
2649 }
2650
Ted Kremenek227c5372008-05-06 02:41:27 +00002651 case RetEffect::ReceiverAlias: {
2652 assert (Receiver);
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002653 SVal V = state.GetSValAsScalarOrLoc(Receiver);
Ted Kremenek09102db2008-11-12 19:22:09 +00002654 state = state.BindExpr(Ex, V, false);
Ted Kremenek227c5372008-05-06 02:41:27 +00002655 break;
2656 }
2657
Ted Kremenek6a1cc252008-06-23 18:02:52 +00002658 case RetEffect::OwnedAllocatedSymbol:
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002659 case RetEffect::OwnedSymbol: {
2660 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke9e726e2009-04-09 16:13:17 +00002661 ValueManager &ValMgr = Eng.getValueManager();
2662 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
2663 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
2664 state = state.set<RefBindings>(Sym, RefVal::makeOwned(RE.getObjKind(),
2665 RetT));
2666 state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenek45c52a12009-03-09 22:46:49 +00002667
2668 // FIXME: Add a flag to the checker where allocations are assumed to
2669 // *not fail.
2670#if 0
Ted Kremeneke62fd052009-01-28 22:27:59 +00002671 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) {
2672 bool isFeasible;
2673 state = state.Assume(loc::SymbolVal(Sym), true, isFeasible);
2674 assert(isFeasible && "Cannot assume fresh symbol is non-null.");
2675 }
Ted Kremenek45c52a12009-03-09 22:46:49 +00002676#endif
Ted Kremenek6a1cc252008-06-23 18:02:52 +00002677
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002678 break;
2679 }
Ted Kremenek382fb4e2009-04-27 19:14:45 +00002680
2681 case RetEffect::GCNotOwnedSymbol:
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002682 case RetEffect::NotOwnedSymbol: {
2683 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke9e726e2009-04-09 16:13:17 +00002684 ValueManager &ValMgr = Eng.getValueManager();
2685 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
2686 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
2687 state = state.set<RefBindings>(Sym, RefVal::makeNotOwned(RE.getObjKind(),
2688 RetT));
2689 state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002690 break;
2691 }
2692 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002693
Ted Kremenek0dd65012009-02-18 02:00:25 +00002694 // Generate a sink node if we are at the end of a path.
2695 GRExprEngine::NodeTy *NewNode =
Ted Kremenek286e9852009-05-04 04:57:00 +00002696 Summ.isEndPath() ? Builder.MakeSinkNode(Dst, Ex, Pred, state)
2697 : Builder.MakeNode(Dst, Ex, Pred, state);
Ted Kremenek0dd65012009-02-18 02:00:25 +00002698
2699 // Annotate the edge with summary we used.
Ted Kremenek286e9852009-05-04 04:57:00 +00002700 if (NewNode) SummaryLog[NewNode] = &Summ;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002701}
2702
2703
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002704void CFRefCount::EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002705 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002706 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu097fc982008-10-17 05:57:07 +00002707 CallExpr* CE, SVal L,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002708 ExplodedNode<GRState>* Pred) {
Zhongxing Xucac107a2009-04-20 05:24:46 +00002709 const FunctionDecl* FD = L.getAsFunctionDecl();
Ted Kremenek286e9852009-05-04 04:57:00 +00002710 RetainSummary* Summ = !FD ? Summaries.getDefaultSummary()
Zhongxing Xucac107a2009-04-20 05:24:46 +00002711 : Summaries.getSummary(const_cast<FunctionDecl*>(FD));
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002712
Ted Kremenek286e9852009-05-04 04:57:00 +00002713 assert(Summ);
2714 EvalSummary(Dst, Eng, Builder, CE, 0, *Summ,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002715 CE->arg_begin(), CE->arg_end(), Pred);
Ted Kremenek827f93b2008-03-06 00:08:09 +00002716}
Ted Kremeneka7338b42008-03-11 06:39:11 +00002717
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002718void CFRefCount::EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002719 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002720 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002721 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002722 ExplodedNode<GRState>* Pred) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002723 RetainSummary* Summ = 0;
Ted Kremenek33661802008-05-01 21:31:50 +00002724
Ted Kremenek272aa852008-06-25 21:21:56 +00002725 if (Expr* Receiver = ME->getReceiver()) {
2726 // We need the type-information of the tracked receiver object
2727 // Retrieve it from the state.
2728 ObjCInterfaceDecl* ID = 0;
2729
2730 // FIXME: Wouldn't it be great if this code could be reduced? It's just
2731 // a chain of lookups.
Ted Kremeneka821b792009-04-29 05:04:30 +00002732 // FIXME: Is this really working as expected? There are cases where
2733 // we just use the 'ID' from the message expression.
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002734 const GRState* St = Builder.GetState(Pred);
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002735 SVal V = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
Ted Kremenek272aa852008-06-25 21:21:56 +00002736
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002737 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenek74556a12009-03-26 03:35:11 +00002738 if (Sym) {
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002739 if (const RefVal* T = St->get<RefBindings>(Sym)) {
Ted Kremenek6064a362008-07-07 16:21:19 +00002740 QualType Ty = T->getType();
Ted Kremenek272aa852008-06-25 21:21:56 +00002741
2742 if (const PointerType* PT = Ty->getAsPointerType()) {
2743 QualType PointeeTy = PT->getPointeeType();
2744
2745 if (ObjCInterfaceType* IT = dyn_cast<ObjCInterfaceType>(PointeeTy))
2746 ID = IT->getDecl();
2747 }
2748 }
2749 }
2750
Ted Kremenek04e00302009-04-29 17:09:14 +00002751 // FIXME: The receiver could be a reference to a class, meaning that
2752 // we should use the class method.
2753 Summ = Summaries.getInstanceMethodSummary(ME, ID);
Ted Kremenek0106e202008-10-24 20:32:50 +00002754
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002755 // Special-case: are we sending a mesage to "self"?
2756 // This is a hack. When we have full-IP this should be removed.
Ted Kremenek2f226732009-05-04 05:31:22 +00002757 if (isa<ObjCMethodDecl>(&Eng.getGraph().getCodeDecl())) {
2758 if (Expr* Receiver = ME->getReceiver()) {
2759 SVal X = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
2760 if (loc::MemRegionVal* L = dyn_cast<loc::MemRegionVal>(&X))
2761 if (L->getRegion() == Eng.getStateManager().getSelfRegion(St)) {
2762 // Update the summary to make the default argument effect
2763 // 'StopTracking'.
2764 Summ = Summaries.copySummary(Summ);
2765 Summ->setDefaultArgEffect(StopTracking);
2766 }
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002767 }
2768 }
Ted Kremenek272aa852008-06-25 21:21:56 +00002769 }
Ted Kremenek1feab292008-04-16 04:28:53 +00002770 else
Ted Kremenekb17fa952009-04-23 21:25:57 +00002771 Summ = Summaries.getClassMethodSummary(ME);
Ted Kremenek1feab292008-04-16 04:28:53 +00002772
Ted Kremenek286e9852009-05-04 04:57:00 +00002773 if (!Summ)
2774 Summ = Summaries.getDefaultSummary();
Ted Kremenekccbe79a2009-04-24 17:50:11 +00002775
Ted Kremenek286e9852009-05-04 04:57:00 +00002776 EvalSummary(Dst, Eng, Builder, ME, ME->getReceiver(), *Summ,
Ted Kremenek926abf22008-05-06 04:20:12 +00002777 ME->arg_begin(), ME->arg_end(), Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002778}
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002779
2780namespace {
2781class VISIBILITY_HIDDEN StopTrackingCallback : public SymbolVisitor {
2782 GRStateRef state;
2783public:
2784 StopTrackingCallback(GRStateRef st) : state(st) {}
2785 GRStateRef getState() { return state; }
2786
2787 bool VisitSymbol(SymbolRef sym) {
2788 state = state.remove<RefBindings>(sym);
2789 return true;
2790 }
Ted Kremenek926abf22008-05-06 04:20:12 +00002791
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002792 const GRState* getState() const { return state.getState(); }
2793};
2794} // end anonymous namespace
2795
2796
Ted Kremeneka42be302009-02-14 01:43:44 +00002797void CFRefCount::EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val) {
Ted Kremeneka42be302009-02-14 01:43:44 +00002798 // Are we storing to something that causes the value to "escape"?
Ted Kremenek7aef4842008-04-16 20:40:59 +00002799 bool escapes = false;
2800
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002801 // A value escapes in three possible cases (this may change):
2802 //
2803 // (1) we are binding to something that is not a memory region.
2804 // (2) we are binding to a memregion that does not have stack storage
2805 // (3) we are binding to a memregion with stack storage that the store
Ted Kremeneka42be302009-02-14 01:43:44 +00002806 // does not understand.
Ted Kremeneka42be302009-02-14 01:43:44 +00002807 GRStateRef state = B.getState();
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002808
Ted Kremeneka42be302009-02-14 01:43:44 +00002809 if (!isa<loc::MemRegionVal>(location))
Ted Kremenek7aef4842008-04-16 20:40:59 +00002810 escapes = true;
Ted Kremenekb15eba42008-10-04 05:50:14 +00002811 else {
Ted Kremeneka42be302009-02-14 01:43:44 +00002812 const MemRegion* R = cast<loc::MemRegionVal>(location).getRegion();
2813 escapes = !B.getStateManager().hasStackStorage(R);
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002814
2815 if (!escapes) {
2816 // To test (3), generate a new state with the binding removed. If it is
2817 // the same state, then it escapes (since the store cannot represent
2818 // the binding).
Ted Kremeneka42be302009-02-14 01:43:44 +00002819 escapes = (state == (state.BindLoc(cast<Loc>(location), UnknownVal())));
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002820 }
Ted Kremenekb15eba42008-10-04 05:50:14 +00002821 }
Ted Kremeneka42be302009-02-14 01:43:44 +00002822
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002823 // If our store can represent the binding and we aren't storing to something
2824 // that doesn't have local storage then just return and have the simulation
2825 // state continue as is.
2826 if (!escapes)
2827 return;
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002828
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002829 // Otherwise, find all symbols referenced by 'val' that we are tracking
2830 // and stop tracking them.
2831 B.MakeNode(state.scanReachableSymbols<StopTrackingCallback>(val).getState());
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002832}
2833
Ted Kremenek0106e202008-10-24 20:32:50 +00002834std::pair<GRStateRef,bool>
2835CFRefCount::HandleSymbolDeath(GRStateManager& VMgr,
2836 const GRState* St, const Decl* CD,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002837 SymbolRef sid,
Ted Kremenek0106e202008-10-24 20:32:50 +00002838 RefVal V, bool& hasLeak) {
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002839
Ted Kremenek47a72422009-04-29 18:50:19 +00002840 // Any remaining leaks?
Ted Kremenek311f3d42008-10-22 23:56:21 +00002841 hasLeak = V.isOwned() ||
2842 ((V.isNotOwned() || V.isReturnedOwned()) && V.getCount() > 0);
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002843
Ted Kremenek47a72422009-04-29 18:50:19 +00002844 GRStateRef state(St, VMgr);
2845
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002846 if (!hasLeak)
Ted Kremenek0106e202008-10-24 20:32:50 +00002847 return std::make_pair(state.remove<RefBindings>(sid), false);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002848
Ted Kremenek0106e202008-10-24 20:32:50 +00002849 return std::make_pair(state.set<RefBindings>(sid, V ^ RefVal::ErrorLeak),
2850 false);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002851}
2852
Ted Kremenek541db372008-04-24 23:57:27 +00002853
Ted Kremenekffefc352008-04-11 22:25:11 +00002854
Ted Kremenek541db372008-04-24 23:57:27 +00002855// Dead symbols.
2856
Ted Kremenek708af042009-02-05 06:50:21 +00002857
Ted Kremenek541db372008-04-24 23:57:27 +00002858
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002859 // Return statements.
2860
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002861void CFRefCount::EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002862 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002863 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002864 ReturnStmt* S,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002865 ExplodedNode<GRState>* Pred) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002866
2867 Expr* RetE = S->getRetValue();
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002868 if (!RetE)
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002869 return;
2870
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002871 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002872 SymbolRef Sym = state.GetSValAsScalarOrLoc(RetE).getAsLocSymbol();
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002873
Ted Kremenek74556a12009-03-26 03:35:11 +00002874 if (!Sym)
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002875 return;
2876
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002877 // Get the reference count binding (if any).
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002878 const RefVal* T = state.get<RefBindings>(Sym);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002879
2880 if (!T)
2881 return;
2882
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002883 // Change the reference count.
Ted Kremenek6064a362008-07-07 16:21:19 +00002884 RefVal X = *T;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002885
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002886 switch (X.getKind()) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002887 case RefVal::Owned: {
2888 unsigned cnt = X.getCount();
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00002889 assert (cnt > 0);
2890 X = RefVal::makeReturnedOwned(cnt - 1);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002891 break;
2892 }
2893
2894 case RefVal::NotOwned: {
2895 unsigned cnt = X.getCount();
2896 X = cnt ? RefVal::makeReturnedOwned(cnt - 1)
2897 : RefVal::makeReturnedNotOwned();
2898 break;
2899 }
2900
2901 default:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002902 return;
2903 }
2904
2905 // Update the binding.
Ted Kremenek91781202008-08-17 03:20:02 +00002906 state = state.set<RefBindings>(Sym, X);
Ted Kremenek47a72422009-04-29 18:50:19 +00002907 Pred = Builder.MakeNode(Dst, S, Pred, state);
2908
Ted Kremeneka208d0c2009-04-30 05:51:50 +00002909 // Did we cache out?
2910 if (!Pred)
2911 return;
2912
Ted Kremenek47a72422009-04-29 18:50:19 +00002913 // Any leaks or other errors?
2914 if (X.isReturnedOwned() && X.getCount() == 0) {
2915 const Decl *CD = &Eng.getStateManager().getCodeDecl();
2916
Ted Kremenek314b1952009-04-29 23:03:22 +00002917 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
Ted Kremenek286e9852009-05-04 04:57:00 +00002918 const RetainSummary &Summ = *Summaries.getMethodSummary(MD);
2919 if (!Summ.getRetEffect().isOwned()) {
Ted Kremenek47a72422009-04-29 18:50:19 +00002920 static int ReturnOwnLeakTag = 0;
2921 state = state.set<RefBindings>(Sym, X ^ RefVal::ErrorLeakReturned);
Ted Kremenek47a72422009-04-29 18:50:19 +00002922 // Generate an error node.
Ted Kremeneka208d0c2009-04-30 05:51:50 +00002923 if (ExplodedNode<GRState> *N =
2924 Builder.generateNode(PostStmt(S, &ReturnOwnLeakTag), state, Pred)) {
2925 CFRefLeakReport *report =
2926 new CFRefLeakReport(*static_cast<CFRefBug*>(leakAtReturn), *this,
2927 N, Sym, Eng);
2928 BR->EmitReport(report);
2929 }
Ted Kremenek47a72422009-04-29 18:50:19 +00002930 }
2931 }
2932 }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002933}
2934
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002935// Assumptions.
2936
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002937const GRState* CFRefCount::EvalAssume(GRStateManager& VMgr,
2938 const GRState* St,
Zhongxing Xu097fc982008-10-17 05:57:07 +00002939 SVal Cond, bool Assumption,
Ted Kremenekf22f8682008-07-10 22:03:41 +00002940 bool& isFeasible) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002941
2942 // FIXME: We may add to the interface of EvalAssume the list of symbols
2943 // whose assumptions have changed. For now we just iterate through the
2944 // bindings and check if any of the tracked symbols are NULL. This isn't
2945 // too bad since the number of symbols we will track in practice are
2946 // probably small and EvalAssume is only called at branches and a few
2947 // other places.
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002948 RefBindings B = St->get<RefBindings>();
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002949
2950 if (B.isEmpty())
2951 return St;
2952
2953 bool changed = false;
Ted Kremenek91781202008-08-17 03:20:02 +00002954
2955 GRStateRef state(St, VMgr);
2956 RefBindings::Factory& RefBFactory = state.get_context<RefBindings>();
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002957
2958 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002959 // Check if the symbol is null (or equal to any constant).
2960 // If this is the case, stop tracking the symbol.
Zhongxing Xuc6b27d02008-08-29 14:52:36 +00002961 if (VMgr.getSymVal(St, I.getKey())) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002962 changed = true;
2963 B = RefBFactory.Remove(B, I.getKey());
2964 }
2965 }
2966
Ted Kremenek91781202008-08-17 03:20:02 +00002967 if (changed)
2968 state = state.set<RefBindings>(B);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002969
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002970 return state;
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002971}
Ted Kremeneka7338b42008-03-11 06:39:11 +00002972
Ted Kremenekb6578942009-02-24 19:15:11 +00002973GRStateRef CFRefCount::Update(GRStateRef state, SymbolRef sym,
2974 RefVal V, ArgEffect E,
2975 RefVal::Kind& hasErr) {
Ted Kremenek58dd95b2009-02-18 18:54:33 +00002976
2977 // In GC mode [... release] and [... retain] do nothing.
2978 switch (E) {
2979 default: break;
2980 case IncRefMsg: E = isGCEnabled() ? DoNothing : IncRef; break;
2981 case DecRefMsg: E = isGCEnabled() ? DoNothing : DecRef; break;
Ted Kremenek2126bef2009-02-18 21:57:45 +00002982 case MakeCollectable: E = isGCEnabled() ? DecRef : DoNothing; break;
Ted Kremenekaac82832009-02-23 17:45:03 +00002983 case NewAutoreleasePool: E = isGCEnabled() ? DoNothing :
2984 NewAutoreleasePool; break;
Ted Kremenek58dd95b2009-02-18 18:54:33 +00002985 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00002986
Ted Kremenek6537a642009-03-17 19:42:23 +00002987 // Handle all use-after-releases.
2988 if (!isGCEnabled() && V.getKind() == RefVal::Released) {
2989 V = V ^ RefVal::ErrorUseAfterRelease;
2990 hasErr = V.getKind();
2991 return state.set<RefBindings>(sym, V);
2992 }
2993
Ted Kremenek0d721572008-03-11 17:48:22 +00002994 switch (E) {
2995 default:
2996 assert (false && "Unhandled CFRef transition.");
Ted Kremenek6537a642009-03-17 19:42:23 +00002997
2998 case Dealloc:
2999 // Any use of -dealloc in GC is *bad*.
3000 if (isGCEnabled()) {
3001 V = V ^ RefVal::ErrorDeallocGC;
3002 hasErr = V.getKind();
3003 break;
3004 }
3005
3006 switch (V.getKind()) {
3007 default:
3008 assert(false && "Invalid case.");
3009 case RefVal::Owned:
3010 // The object immediately transitions to the released state.
3011 V = V ^ RefVal::Released;
3012 V.clearCounts();
3013 return state.set<RefBindings>(sym, V);
3014 case RefVal::NotOwned:
3015 V = V ^ RefVal::ErrorDeallocNotOwned;
3016 hasErr = V.getKind();
3017 break;
3018 }
3019 break;
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003020
Ted Kremenekb7826ab2009-02-25 23:11:49 +00003021 case NewAutoreleasePool:
3022 assert(!isGCEnabled());
3023 return state.add<AutoreleaseStack>(sym);
3024
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003025 case MayEscape:
3026 if (V.getKind() == RefVal::Owned) {
Ted Kremenek272aa852008-06-25 21:21:56 +00003027 V = V ^ RefVal::NotOwned;
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003028 break;
3029 }
Ted Kremenek6537a642009-03-17 19:42:23 +00003030
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003031 // Fall-through.
Ted Kremenek1b4b6562009-02-25 02:54:57 +00003032
Ted Kremenekede40b72008-07-09 18:11:16 +00003033 case DoNothingByRef:
Ted Kremenek0d721572008-03-11 17:48:22 +00003034 case DoNothing:
Ted Kremenekb6578942009-02-24 19:15:11 +00003035 return state;
Ted Kremeneke5a4bb02008-06-30 16:57:41 +00003036
Ted Kremenek9b112d22009-01-28 21:44:40 +00003037 case Autorelease:
Ted Kremenek6537a642009-03-17 19:42:23 +00003038 if (isGCEnabled())
3039 return state;
Ted Kremenek681fb352009-03-20 17:34:15 +00003040
3041 // Update the autorelease counts.
3042 state = SendAutorelease(state, ARCountFactory, sym);
Ted Kremenek6537a642009-03-17 19:42:23 +00003043
3044 // Fall-through.
3045
Ted Kremenek227c5372008-05-06 02:41:27 +00003046 case StopTracking:
Ted Kremenekb6578942009-02-24 19:15:11 +00003047 return state.remove<RefBindings>(sym);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003048
Ted Kremenek0d721572008-03-11 17:48:22 +00003049 case IncRef:
3050 switch (V.getKind()) {
3051 default:
3052 assert(false);
3053
3054 case RefVal::Owned:
Ted Kremenek0d721572008-03-11 17:48:22 +00003055 case RefVal::NotOwned:
Ted Kremenek272aa852008-06-25 21:21:56 +00003056 V = V + 1;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003057 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003058 case RefVal::Released:
Ted Kremenek6537a642009-03-17 19:42:23 +00003059 // Non-GC cases are handled above.
3060 assert(isGCEnabled());
3061 V = (V ^ RefVal::Owned) + 1;
Ted Kremenek0d721572008-03-11 17:48:22 +00003062 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003063 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00003064 break;
3065
Ted Kremenek272aa852008-06-25 21:21:56 +00003066 case SelfOwn:
3067 V = V ^ RefVal::NotOwned;
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003068 // Fall-through.
Ted Kremenek0d721572008-03-11 17:48:22 +00003069 case DecRef:
3070 switch (V.getKind()) {
3071 default:
Ted Kremenek6537a642009-03-17 19:42:23 +00003072 // case 'RefVal::Released' handled above.
Ted Kremenek0d721572008-03-11 17:48:22 +00003073 assert (false);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003074
Ted Kremenek272aa852008-06-25 21:21:56 +00003075 case RefVal::Owned:
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00003076 assert(V.getCount() > 0);
3077 if (V.getCount() == 1) V = V ^ RefVal::Released;
3078 V = V - 1;
Ted Kremenek0d721572008-03-11 17:48:22 +00003079 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003080
Ted Kremenek272aa852008-06-25 21:21:56 +00003081 case RefVal::NotOwned:
3082 if (V.getCount() > 0)
3083 V = V - 1;
Ted Kremenekc4f81022008-04-10 23:09:18 +00003084 else {
Ted Kremenek272aa852008-06-25 21:21:56 +00003085 V = V ^ RefVal::ErrorReleaseNotOwned;
Ted Kremenek1feab292008-04-16 04:28:53 +00003086 hasErr = V.getKind();
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003087 }
Ted Kremenek0d721572008-03-11 17:48:22 +00003088 break;
Ted Kremenek6537a642009-03-17 19:42:23 +00003089
Ted Kremenek0d721572008-03-11 17:48:22 +00003090 case RefVal::Released:
Ted Kremenek6537a642009-03-17 19:42:23 +00003091 // Non-GC cases are handled above.
3092 assert(isGCEnabled());
Ted Kremenek272aa852008-06-25 21:21:56 +00003093 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek1feab292008-04-16 04:28:53 +00003094 hasErr = V.getKind();
Ted Kremenek6537a642009-03-17 19:42:23 +00003095 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003096 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00003097 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003098 }
Ted Kremenekb6578942009-02-24 19:15:11 +00003099 return state.set<RefBindings>(sym, V);
Ted Kremeneka7338b42008-03-11 06:39:11 +00003100}
3101
Ted Kremenek10fe66d2008-04-09 01:10:13 +00003102//===----------------------------------------------------------------------===//
Ted Kremenek708af042009-02-05 06:50:21 +00003103// Handle dead symbols and end-of-path.
3104//===----------------------------------------------------------------------===//
3105
3106void CFRefCount::EvalEndPath(GRExprEngine& Eng,
3107 GREndPathNodeBuilder<GRState>& Builder) {
3108
3109 const GRState* St = Builder.getState();
3110 RefBindings B = St->get<RefBindings>();
3111
3112 llvm::SmallVector<std::pair<SymbolRef, bool>, 10> Leaked;
3113 const Decl* CodeDecl = &Eng.getGraph().getCodeDecl();
3114
3115 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
3116 bool hasLeak = false;
3117
3118 std::pair<GRStateRef, bool> X =
Ted Kremenek9577c1e2009-03-03 22:06:47 +00003119 HandleSymbolDeath(Eng.getStateManager(), St, CodeDecl,
3120 (*I).first, (*I).second, hasLeak);
Ted Kremenek708af042009-02-05 06:50:21 +00003121
3122 St = X.first;
3123 if (hasLeak) Leaked.push_back(std::make_pair((*I).first, X.second));
3124 }
3125
3126 if (Leaked.empty())
3127 return;
3128
3129 ExplodedNode<GRState>* N = Builder.MakeNode(St);
3130
3131 if (!N)
3132 return;
3133
3134 for (llvm::SmallVector<std::pair<SymbolRef,bool>, 10>::iterator
3135 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3136
3137 CFRefBug *BT = static_cast<CFRefBug*>(I->second ? leakAtReturn
3138 : leakWithinFunction);
3139 assert(BT && "BugType not initialized.");
Ted Kremenekc034f712009-04-07 05:07:44 +00003140 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N, I->first, Eng);
Ted Kremenek708af042009-02-05 06:50:21 +00003141 BR->EmitReport(report);
3142 }
3143}
3144
3145void CFRefCount::EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
3146 GRExprEngine& Eng,
3147 GRStmtNodeBuilder<GRState>& Builder,
3148 ExplodedNode<GRState>* Pred,
3149 Stmt* S,
3150 const GRState* St,
3151 SymbolReaper& SymReaper) {
3152
Ted Kremenek876d8df2009-02-19 23:47:02 +00003153 // FIXME: a lot of copy-and-paste from EvalEndPath. Refactor.
Ted Kremenek708af042009-02-05 06:50:21 +00003154 RefBindings B = St->get<RefBindings>();
3155 llvm::SmallVector<std::pair<SymbolRef,bool>, 10> Leaked;
3156
3157 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3158 E = SymReaper.dead_end(); I != E; ++I) {
3159
3160 const RefVal* T = B.lookup(*I);
3161 if (!T) continue;
3162
3163 bool hasLeak = false;
3164
3165 std::pair<GRStateRef, bool> X
Ted Kremenek876d8df2009-02-19 23:47:02 +00003166 = HandleSymbolDeath(Eng.getStateManager(), St, 0, *I, *T, hasLeak);
Ted Kremenek708af042009-02-05 06:50:21 +00003167
3168 St = X.first;
3169
3170 if (hasLeak)
3171 Leaked.push_back(std::make_pair(*I,X.second));
3172 }
3173
Ted Kremenek876d8df2009-02-19 23:47:02 +00003174 if (!Leaked.empty()) {
3175 // Create a new intermediate node representing the leak point. We
3176 // use a special program point that represents this checker-specific
3177 // transition. We use the address of RefBIndex as a unique tag for this
3178 // checker. We will create another node (if we don't cache out) that
3179 // removes the retain-count bindings from the state.
3180 // NOTE: We use 'generateNode' so that it does interplay with the
3181 // auto-transition logic.
3182 ExplodedNode<GRState>* N =
3183 Builder.generateNode(PostStmtCustom(S, &LeakProgramPointTag), St, Pred);
Ted Kremenek708af042009-02-05 06:50:21 +00003184
Ted Kremenek876d8df2009-02-19 23:47:02 +00003185 if (!N)
3186 return;
3187
3188 // Generate the bug reports.
3189 for (llvm::SmallVectorImpl<std::pair<SymbolRef,bool> >::iterator
3190 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3191
3192 CFRefBug *BT = static_cast<CFRefBug*>(I->second ? leakAtReturn
3193 : leakWithinFunction);
3194 assert(BT && "BugType not initialized.");
Ted Kremenek56c70aa2009-02-23 16:54:00 +00003195 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N,
3196 I->first, Eng);
Ted Kremenek876d8df2009-02-19 23:47:02 +00003197 BR->EmitReport(report);
3198 }
Ted Kremenek708af042009-02-05 06:50:21 +00003199
Ted Kremenek876d8df2009-02-19 23:47:02 +00003200 Pred = N;
Ted Kremenek708af042009-02-05 06:50:21 +00003201 }
Ted Kremenek876d8df2009-02-19 23:47:02 +00003202
3203 // Now generate a new node that nukes the old bindings.
3204 GRStateRef state(St, Eng.getStateManager());
3205 RefBindings::Factory& F = state.get_context<RefBindings>();
3206
3207 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3208 E = SymReaper.dead_end(); I!=E; ++I)
3209 B = F.Remove(B, *I);
3210
3211 state = state.set<RefBindings>(B);
3212 Builder.MakeNode(Dst, S, Pred, state);
Ted Kremenek708af042009-02-05 06:50:21 +00003213}
3214
3215void CFRefCount::ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
3216 GRStmtNodeBuilder<GRState>& Builder,
3217 Expr* NodeExpr, Expr* ErrorExpr,
3218 ExplodedNode<GRState>* Pred,
3219 const GRState* St,
3220 RefVal::Kind hasErr, SymbolRef Sym) {
3221 Builder.BuildSinks = true;
3222 GRExprEngine::NodeTy* N = Builder.MakeNode(Dst, NodeExpr, Pred, St);
3223
3224 if (!N) return;
3225
3226 CFRefBug *BT = 0;
3227
Ted Kremenek6537a642009-03-17 19:42:23 +00003228 switch (hasErr) {
3229 default:
3230 assert(false && "Unhandled error.");
3231 return;
3232 case RefVal::ErrorUseAfterRelease:
3233 BT = static_cast<CFRefBug*>(useAfterRelease);
3234 break;
3235 case RefVal::ErrorReleaseNotOwned:
3236 BT = static_cast<CFRefBug*>(releaseNotOwned);
3237 break;
3238 case RefVal::ErrorDeallocGC:
3239 BT = static_cast<CFRefBug*>(deallocGC);
3240 break;
3241 case RefVal::ErrorDeallocNotOwned:
3242 BT = static_cast<CFRefBug*>(deallocNotOwned);
3243 break;
Ted Kremenek708af042009-02-05 06:50:21 +00003244 }
3245
Ted Kremenekc26c4692009-02-18 03:48:14 +00003246 CFRefReport *report = new CFRefReport(*BT, *this, N, Sym);
Ted Kremenek708af042009-02-05 06:50:21 +00003247 report->addRange(ErrorExpr->getSourceRange());
3248 BR->EmitReport(report);
3249}
3250
3251//===----------------------------------------------------------------------===//
Ted Kremenekb1983ba2008-04-10 22:16:52 +00003252// Transfer function creation for external clients.
Ted Kremeneka7338b42008-03-11 06:39:11 +00003253//===----------------------------------------------------------------------===//
3254
Ted Kremenekfe30beb2008-04-30 23:47:44 +00003255GRTransferFuncs* clang::MakeCFRefCountTF(ASTContext& Ctx, bool GCEnabled,
3256 const LangOptions& lopts) {
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00003257 return new CFRefCount(Ctx, GCEnabled, lopts);
Ted Kremeneka4c74292008-04-10 22:58:08 +00003258}