blob: 7382e1a7ac8fadc1b7f4c350f39ece4587695b0f [file] [log] [blame]
Chris Lattnerbe1a7a02008-03-15 23:59:48 +00001// CFRefCount.cpp - Transfer functions for tracking simple values -*- C++ -*--//
Ted Kremenek827f93b2008-03-06 00:08:09 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Gabor Greif2224fcb2008-03-06 10:40:09 +000010// This file defines the methods for CFRefCount, which implements
Ted Kremenek827f93b2008-03-06 00:08:09 +000011// a reference count checker for Core Foundation (Mac OS X).
12//
13//===----------------------------------------------------------------------===//
14
Ted Kremeneka7338b42008-03-11 06:39:11 +000015#include "GRSimpleVals.h"
Ted Kremenekfe30beb2008-04-30 23:47:44 +000016#include "clang/Basic/LangOptions.h"
Ted Kremenekfe4d2312008-05-01 23:13:35 +000017#include "clang/Basic/SourceManager.h"
Ted Kremeneka42be302009-02-14 01:43:44 +000018#include "clang/Analysis/PathSensitive/GRExprEngineBuilders.h"
Ted Kremenek91781202008-08-17 03:20:02 +000019#include "clang/Analysis/PathSensitive/GRStateTrait.h"
Ted Kremenekdd0126b2008-03-31 18:26:32 +000020#include "clang/Analysis/PathDiagnostic.h"
Ted Kremenek827f93b2008-03-06 00:08:09 +000021#include "clang/Analysis/LocalCheckers.h"
Ted Kremenek10fe66d2008-04-09 01:10:13 +000022#include "clang/Analysis/PathDiagnostic.h"
23#include "clang/Analysis/PathSensitive/BugReporter.h"
Ted Kremenek2ddb4b22009-02-14 03:16:10 +000024#include "clang/Analysis/PathSensitive/SymbolManager.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000025#include "clang/AST/DeclObjC.h"
Ted Kremeneka7338b42008-03-11 06:39:11 +000026#include "llvm/ADT/DenseMap.h"
27#include "llvm/ADT/FoldingSet.h"
28#include "llvm/ADT/ImmutableMap.h"
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +000029#include "llvm/ADT/ImmutableList.h"
Ted Kremenek2ac4ba62008-05-07 18:36:45 +000030#include "llvm/ADT/StringExtras.h"
Ted Kremenek10fe66d2008-04-09 01:10:13 +000031#include "llvm/Support/Compiler.h"
Ted Kremenekd7e26782008-05-16 18:33:44 +000032#include "llvm/ADT/STLExtras.h"
Ted Kremenek3b11f7a2008-03-11 19:44:10 +000033#include <ostream>
Ted Kremenek9449ca92008-08-12 20:41:56 +000034#include <stdarg.h>
Ted Kremenek827f93b2008-03-06 00:08:09 +000035
36using namespace clang;
Ted Kremenekb6f09542008-10-24 21:18:08 +000037
38//===----------------------------------------------------------------------===//
39// Utility functions.
40//===----------------------------------------------------------------------===//
41
Ted Kremenekb6f09542008-10-24 21:18:08 +000042// The "fundamental rule" for naming conventions of methods:
43// (url broken into two lines)
44// http://developer.apple.com/documentation/Cocoa/Conceptual/
45// MemoryMgmt/Tasks/MemoryManagementRules.html
46//
47// "You take ownership of an object if you create it using a method whose name
48// begins with “alloc” or “new” or contains “copy” (for example, alloc,
49// newObject, or mutableCopy), or if you send it a retain message. You are
50// responsible for relinquishing ownership of objects you own using release
51// or autorelease. Any other time you receive an object, you must
52// not release it."
53//
Ted Kremenek4395b452009-02-21 05:13:43 +000054
55using llvm::CStrInCStrNoCase;
Ted Kremenekfd42ffc2009-02-21 18:26:02 +000056using llvm::StringsEqualNoCase;
Ted Kremenek4395b452009-02-21 05:13:43 +000057
58enum NamingConvention { NoConvention, CreateRule, InitRule };
59
60static inline bool isWordEnd(char ch, char prev, char next) {
61 return ch == '\0'
62 || (islower(prev) && isupper(ch)) // xxxC
63 || (isupper(prev) && isupper(ch) && islower(next)) // XXCreate
64 || !isalpha(ch);
65}
66
67static inline const char* parseWord(const char* s) {
68 char ch = *s, prev = '\0';
69 assert(ch != '\0');
70 char next = *(s+1);
71 while (!isWordEnd(ch, prev, next)) {
72 prev = ch;
73 ch = next;
74 next = *((++s)+1);
75 }
76 return s;
77}
78
79static NamingConvention deriveNamingConvention(const char* s) {
80 // A method/function name may contain a prefix. We don't know it is there,
81 // however, until we encounter the first '_'.
82 bool InPossiblePrefix = true;
83 bool AtBeginning = true;
84 NamingConvention C = NoConvention;
85
86 while (*s != '\0') {
87 // Skip '_'.
88 if (*s == '_') {
89 if (InPossiblePrefix) {
90 InPossiblePrefix = false;
91 AtBeginning = true;
92 // Discard whatever 'convention' we
93 // had already derived since it occurs
94 // in the prefix.
95 C = NoConvention;
96 }
97 ++s;
98 continue;
99 }
100
101 // Skip numbers, ':', etc.
102 if (!isalpha(*s)) {
103 ++s;
104 continue;
105 }
106
107 const char *wordEnd = parseWord(s);
108 assert(wordEnd > s);
109 unsigned len = wordEnd - s;
110
111 switch (len) {
112 default:
113 break;
114 case 3:
115 // Methods starting with 'new' follow the create rule.
Ted Kremenekfd42ffc2009-02-21 18:26:02 +0000116 if (AtBeginning && StringsEqualNoCase("new", s, len))
Ted Kremenek4395b452009-02-21 05:13:43 +0000117 C = CreateRule;
118 break;
119 case 4:
120 // Methods starting with 'alloc' or contain 'copy' follow the
121 // create rule
Ted Kremenek91b79532009-03-13 20:27:06 +0000122 if (C == NoConvention && StringsEqualNoCase("copy", s, len))
Ted Kremenek4395b452009-02-21 05:13:43 +0000123 C = CreateRule;
124 else // Methods starting with 'init' follow the init rule.
Ted Kremenekfd42ffc2009-02-21 18:26:02 +0000125 if (AtBeginning && StringsEqualNoCase("init", s, len))
Ted Kremenek91b79532009-03-13 20:27:06 +0000126 C = InitRule;
127 break;
128 case 5:
129 if (AtBeginning && StringsEqualNoCase("alloc", s, len))
130 C = CreateRule;
Ted Kremenek4395b452009-02-21 05:13:43 +0000131 break;
132 }
133
134 // If we aren't in the prefix and have a derived convention then just
135 // return it now.
136 if (!InPossiblePrefix && C != NoConvention)
137 return C;
138
139 AtBeginning = false;
140 s = wordEnd;
141 }
142
143 // We will get here if there wasn't more than one word
144 // after the prefix.
145 return C;
146}
147
Ted Kremenekb6f09542008-10-24 21:18:08 +0000148static bool followsFundamentalRule(const char* s) {
Ted Kremenek4395b452009-02-21 05:13:43 +0000149 return deriveNamingConvention(s) == CreateRule;
Ted Kremenekcdd3bb22008-11-05 16:54:44 +0000150}
151
152static bool followsReturnRule(const char* s) {
Ted Kremenek4395b452009-02-21 05:13:43 +0000153 NamingConvention C = deriveNamingConvention(s);
154 return C == CreateRule || C == InitRule;
Ted Kremenekcdd3bb22008-11-05 16:54:44 +0000155}
Ted Kremenekb6f09542008-10-24 21:18:08 +0000156
Ted Kremenek7d421f32008-04-09 23:49:11 +0000157//===----------------------------------------------------------------------===//
Ted Kremenek272aa852008-06-25 21:21:56 +0000158// Selector creation functions.
Ted Kremenekd9ccf682008-04-17 18:12:53 +0000159//===----------------------------------------------------------------------===//
160
Ted Kremenek1bd6ddb2008-05-01 18:31:44 +0000161static inline Selector GetNullarySelector(const char* name, ASTContext& Ctx) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +0000162 IdentifierInfo* II = &Ctx.Idents.get(name);
163 return Ctx.Selectors.getSelector(0, &II);
164}
165
Ted Kremenek0e344d42008-05-06 00:30:21 +0000166static inline Selector GetUnarySelector(const char* name, ASTContext& Ctx) {
167 IdentifierInfo* II = &Ctx.Idents.get(name);
168 return Ctx.Selectors.getSelector(1, &II);
169}
170
Ted Kremenek272aa852008-06-25 21:21:56 +0000171//===----------------------------------------------------------------------===//
172// Type querying functions.
173//===----------------------------------------------------------------------===//
174
Ted Kremenek17144e82009-01-12 21:45:02 +0000175static bool hasPrefix(const char* s, const char* prefix) {
176 if (!prefix)
177 return true;
Ted Kremenek62820d82008-05-07 20:06:41 +0000178
Ted Kremenek17144e82009-01-12 21:45:02 +0000179 char c = *s;
180 char cP = *prefix;
Ted Kremenek62820d82008-05-07 20:06:41 +0000181
Ted Kremenek17144e82009-01-12 21:45:02 +0000182 while (c != '\0' && cP != '\0') {
183 if (c != cP) break;
184 c = *(++s);
185 cP = *(++prefix);
186 }
Ted Kremenek62820d82008-05-07 20:06:41 +0000187
Ted Kremenek17144e82009-01-12 21:45:02 +0000188 return cP == '\0';
Ted Kremenek62820d82008-05-07 20:06:41 +0000189}
190
Ted Kremenek17144e82009-01-12 21:45:02 +0000191static bool hasSuffix(const char* s, const char* suffix) {
192 const char* loc = strstr(s, suffix);
193 return loc && strcmp(suffix, loc) == 0;
194}
195
196static bool isRefType(QualType RetTy, const char* prefix,
197 ASTContext* Ctx = 0, const char* name = 0) {
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000198
Ted Kremenek17144e82009-01-12 21:45:02 +0000199 if (TypedefType* TD = dyn_cast<TypedefType>(RetTy.getTypePtr())) {
200 const char* TDName = TD->getDecl()->getIdentifier()->getName();
201 return hasPrefix(TDName, prefix) && hasSuffix(TDName, "Ref");
202 }
203
204 if (!Ctx || !name)
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000205 return false;
Ted Kremenek17144e82009-01-12 21:45:02 +0000206
207 // Is the type void*?
208 const PointerType* PT = RetTy->getAsPointerType();
209 if (!(PT->getPointeeType().getUnqualifiedType() == Ctx->VoidTy))
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000210 return false;
Ted Kremenek17144e82009-01-12 21:45:02 +0000211
212 // Does the name start with the prefix?
213 return hasPrefix(name, prefix);
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000214}
215
Ted Kremenekd9ccf682008-04-17 18:12:53 +0000216//===----------------------------------------------------------------------===//
Ted Kremenek272aa852008-06-25 21:21:56 +0000217// Primitives used for constructing summaries for function/method calls.
Ted Kremenek7d421f32008-04-09 23:49:11 +0000218//===----------------------------------------------------------------------===//
219
Ted Kremenek272aa852008-06-25 21:21:56 +0000220namespace {
221/// ArgEffect is used to summarize a function/method call's effect on a
222/// particular argument.
Ted Kremenek6537a642009-03-17 19:42:23 +0000223enum ArgEffect { Autorelease, Dealloc, DecRef, DecRefMsg, DoNothing,
224 DoNothingByRef, IncRefMsg, IncRef, MakeCollectable, MayEscape,
225 NewAutoreleasePool, SelfOwn, StopTracking };
Ted Kremenek272aa852008-06-25 21:21:56 +0000226
227/// ArgEffects summarizes the effects of a function/method call on all of
228/// its arguments.
229typedef std::vector<std::pair<unsigned,ArgEffect> > ArgEffects;
Ted Kremeneka7338b42008-03-11 06:39:11 +0000230}
Ted Kremenek827f93b2008-03-06 00:08:09 +0000231
Ted Kremeneka7338b42008-03-11 06:39:11 +0000232namespace llvm {
Ted Kremenek272aa852008-06-25 21:21:56 +0000233template <> struct FoldingSetTrait<ArgEffects> {
234 static void Profile(const ArgEffects& X, FoldingSetNodeID& ID) {
235 for (ArgEffects::const_iterator I = X.begin(), E = X.end(); I!= E; ++I) {
236 ID.AddInteger(I->first);
237 ID.AddInteger((unsigned) I->second);
238 }
239 }
240};
Ted Kremeneka7338b42008-03-11 06:39:11 +0000241} // end llvm namespace
242
243namespace {
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,
250 NotOwnedSymbol, 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 Kremenek272aa852008-06-25 21:21:56 +0000272 static RetEffect MakeAlias(unsigned Idx) {
273 return RetEffect(Alias, Idx);
274 }
275 static RetEffect MakeReceiverAlias() {
276 return RetEffect(ReceiverAlias);
277 }
Ted Kremenek68621b92009-01-28 05:56:51 +0000278 static RetEffect MakeOwned(ObjKind o, bool isAllocated = false) {
279 return RetEffect(isAllocated ? OwnedAllocatedSymbol : OwnedSymbol, o);
Ted Kremenek272aa852008-06-25 21:21:56 +0000280 }
Ted Kremenek68621b92009-01-28 05:56:51 +0000281 static RetEffect MakeNotOwned(ObjKind o) {
282 return RetEffect(NotOwnedSymbol, o);
Ted Kremenek272aa852008-06-25 21:21:56 +0000283 }
284 static RetEffect MakeNoRet() {
285 return RetEffect(NoRet);
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000286 }
Ted Kremenek827f93b2008-03-06 00:08:09 +0000287
Ted Kremenek272aa852008-06-25 21:21:56 +0000288 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek68621b92009-01-28 05:56:51 +0000289 ID.AddInteger((unsigned)K);
290 ID.AddInteger((unsigned)O);
291 ID.AddInteger(index);
Ted Kremenek272aa852008-06-25 21:21:56 +0000292 }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000293};
Ted Kremeneka7338b42008-03-11 06:39:11 +0000294
Ted Kremenek272aa852008-06-25 21:21:56 +0000295
296class VISIBILITY_HIDDEN RetainSummary : public llvm::FoldingSetNode {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000297 /// Args - an ordered vector of (index, ArgEffect) pairs, where index
298 /// specifies the argument (starting from 0). This can be sparsely
299 /// populated; arguments with no entry in Args use 'DefaultArgEffect'.
Ted Kremeneka7338b42008-03-11 06:39:11 +0000300 ArgEffects* Args;
Ted Kremenekbcaff792008-05-06 15:44:25 +0000301
302 /// DefaultArgEffect - The default ArgEffect to apply to arguments that
303 /// do not have an entry in Args.
304 ArgEffect DefaultArgEffect;
305
Ted Kremenek272aa852008-06-25 21:21:56 +0000306 /// Receiver - If this summary applies to an Objective-C message expression,
307 /// this is the effect applied to the state of the receiver.
Ted Kremenek266d8b62008-05-06 02:26:56 +0000308 ArgEffect Receiver;
Ted Kremenek272aa852008-06-25 21:21:56 +0000309
310 /// Ret - The effect on the return value. Used to indicate if the
311 /// function/method call returns a new tracked symbol, returns an
312 /// alias of one of the arguments in the call, and so on.
Ted Kremeneka7338b42008-03-11 06:39:11 +0000313 RetEffect Ret;
Ted Kremenek272aa852008-06-25 21:21:56 +0000314
Ted Kremenekf2717b02008-07-18 17:24:20 +0000315 /// EndPath - Indicates that execution of this method/function should
316 /// terminate the simulation of a path.
317 bool EndPath;
318
Ted Kremeneka7338b42008-03-11 06:39:11 +0000319public:
320
Ted Kremenekbcaff792008-05-06 15:44:25 +0000321 RetainSummary(ArgEffects* A, RetEffect R, ArgEffect defaultEff,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000322 ArgEffect ReceiverEff, bool endpath = false)
323 : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R),
324 EndPath(endpath) {}
Ted Kremeneka7338b42008-03-11 06:39:11 +0000325
Ted Kremenek272aa852008-06-25 21:21:56 +0000326 /// getArg - Return the argument effect on the argument specified by
327 /// idx (starting from 0).
Ted Kremenek0d721572008-03-11 17:48:22 +0000328 ArgEffect getArg(unsigned idx) const {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000329
Ted Kremenekae855d42008-04-24 17:22:33 +0000330 if (!Args)
Ted Kremenekbcaff792008-05-06 15:44:25 +0000331 return DefaultArgEffect;
Ted Kremenekae855d42008-04-24 17:22:33 +0000332
333 // If Args is present, it is likely to contain only 1 element.
334 // Just do a linear search. Do it from the back because functions with
335 // large numbers of arguments will be tail heavy with respect to which
Ted Kremenek272aa852008-06-25 21:21:56 +0000336 // argument they actually modify with respect to the reference count.
Ted Kremenekae855d42008-04-24 17:22:33 +0000337 for (ArgEffects::reverse_iterator I=Args->rbegin(), E=Args->rend();
338 I!=E; ++I) {
339
340 if (idx > I->first)
Ted Kremenekbcaff792008-05-06 15:44:25 +0000341 return DefaultArgEffect;
Ted Kremenekae855d42008-04-24 17:22:33 +0000342
343 if (idx == I->first)
344 return I->second;
345 }
346
Ted Kremenekbcaff792008-05-06 15:44:25 +0000347 return DefaultArgEffect;
Ted Kremenek0d721572008-03-11 17:48:22 +0000348 }
349
Ted Kremenek272aa852008-06-25 21:21:56 +0000350 /// getRetEffect - Returns the effect on the return value of the call.
Ted Kremenek266d8b62008-05-06 02:26:56 +0000351 RetEffect getRetEffect() const {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000352 return Ret;
353 }
354
Ted Kremenekf2717b02008-07-18 17:24:20 +0000355 /// isEndPath - Returns true if executing the given method/function should
356 /// terminate the path.
357 bool isEndPath() const { return EndPath; }
358
Ted Kremenek272aa852008-06-25 21:21:56 +0000359 /// getReceiverEffect - Returns the effect on the receiver of the call.
360 /// This is only meaningful if the summary applies to an ObjCMessageExpr*.
Ted Kremenek266d8b62008-05-06 02:26:56 +0000361 ArgEffect getReceiverEffect() const {
362 return Receiver;
363 }
364
Ted Kremenek2719e982008-06-17 02:43:46 +0000365 typedef ArgEffects::const_iterator ExprIterator;
Ted Kremeneka7338b42008-03-11 06:39:11 +0000366
Ted Kremenek2719e982008-06-17 02:43:46 +0000367 ExprIterator begin_args() const { return Args->begin(); }
368 ExprIterator end_args() const { return Args->end(); }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000369
Ted Kremenek266d8b62008-05-06 02:26:56 +0000370 static void Profile(llvm::FoldingSetNodeID& ID, ArgEffects* A,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000371 RetEffect RetEff, ArgEffect DefaultEff,
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000372 ArgEffect ReceiverEff, bool EndPath) {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000373 ID.AddPointer(A);
Ted Kremenek266d8b62008-05-06 02:26:56 +0000374 ID.Add(RetEff);
Ted Kremenekbcaff792008-05-06 15:44:25 +0000375 ID.AddInteger((unsigned) DefaultEff);
Ted Kremenek266d8b62008-05-06 02:26:56 +0000376 ID.AddInteger((unsigned) ReceiverEff);
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000377 ID.AddInteger((unsigned) EndPath);
Ted Kremeneka7338b42008-03-11 06:39:11 +0000378 }
379
380 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000381 Profile(ID, Args, Ret, DefaultArgEffect, Receiver, EndPath);
Ted Kremeneka7338b42008-03-11 06:39:11 +0000382 }
383};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000384} // end anonymous namespace
Ted Kremeneka7338b42008-03-11 06:39:11 +0000385
Ted Kremenek272aa852008-06-25 21:21:56 +0000386//===----------------------------------------------------------------------===//
387// Data structures for constructing summaries.
388//===----------------------------------------------------------------------===//
Ted Kremenek9f0fc792008-06-24 03:49:48 +0000389
Ted Kremenek272aa852008-06-25 21:21:56 +0000390namespace {
391class VISIBILITY_HIDDEN ObjCSummaryKey {
392 IdentifierInfo* II;
393 Selector S;
394public:
395 ObjCSummaryKey(IdentifierInfo* ii, Selector s)
396 : II(ii), S(s) {}
397
398 ObjCSummaryKey(ObjCInterfaceDecl* d, Selector s)
399 : II(d ? d->getIdentifier() : 0), S(s) {}
400
401 ObjCSummaryKey(Selector s)
402 : II(0), S(s) {}
403
404 IdentifierInfo* getIdentifier() const { return II; }
405 Selector getSelector() const { return S; }
406};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000407}
408
409namespace llvm {
Ted Kremenek272aa852008-06-25 21:21:56 +0000410template <> struct DenseMapInfo<ObjCSummaryKey> {
411 static inline ObjCSummaryKey getEmptyKey() {
412 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
413 DenseMapInfo<Selector>::getEmptyKey());
414 }
Ted Kremenek84f010c2008-06-23 23:30:29 +0000415
Ted Kremenek272aa852008-06-25 21:21:56 +0000416 static inline ObjCSummaryKey getTombstoneKey() {
417 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
418 DenseMapInfo<Selector>::getTombstoneKey());
419 }
420
421 static unsigned getHashValue(const ObjCSummaryKey &V) {
422 return (DenseMapInfo<IdentifierInfo*>::getHashValue(V.getIdentifier())
423 & 0x88888888)
424 | (DenseMapInfo<Selector>::getHashValue(V.getSelector())
425 & 0x55555555);
426 }
427
428 static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
429 return DenseMapInfo<IdentifierInfo*>::isEqual(LHS.getIdentifier(),
430 RHS.getIdentifier()) &&
431 DenseMapInfo<Selector>::isEqual(LHS.getSelector(),
432 RHS.getSelector());
433 }
434
435 static bool isPod() {
436 return DenseMapInfo<ObjCInterfaceDecl*>::isPod() &&
437 DenseMapInfo<Selector>::isPod();
438 }
439};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000440} // end llvm namespace
Ted Kremeneka7338b42008-03-11 06:39:11 +0000441
Ted Kremenek84f010c2008-06-23 23:30:29 +0000442namespace {
Ted Kremenek272aa852008-06-25 21:21:56 +0000443class VISIBILITY_HIDDEN ObjCSummaryCache {
444 typedef llvm::DenseMap<ObjCSummaryKey, RetainSummary*> MapTy;
445 MapTy M;
446public:
447 ObjCSummaryCache() {}
448
449 typedef MapTy::iterator iterator;
450
451 iterator find(ObjCInterfaceDecl* D, Selector S) {
452
453 // Do a lookup with the (D,S) pair. If we find a match return
454 // the iterator.
455 ObjCSummaryKey K(D, S);
456 MapTy::iterator I = M.find(K);
457
458 if (I != M.end() || !D)
459 return I;
460
461 // Walk the super chain. If we find a hit with a parent, we'll end
462 // up returning that summary. We actually allow that key (null,S), as
463 // we cache summaries for the null ObjCInterfaceDecl* to allow us to
464 // generate initial summaries without having to worry about NSObject
465 // being declared.
466 // FIXME: We may change this at some point.
467 for (ObjCInterfaceDecl* C=D->getSuperClass() ;; C=C->getSuperClass()) {
468 if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
469 break;
470
471 if (!C)
472 return I;
473 }
474
475 // Cache the summary with original key to make the next lookup faster
476 // and return the iterator.
477 M[K] = I->second;
478 return I;
479 }
480
Ted Kremenek9449ca92008-08-12 20:41:56 +0000481
Ted Kremenek272aa852008-06-25 21:21:56 +0000482 iterator find(Expr* Receiver, Selector S) {
483 return find(getReceiverDecl(Receiver), S);
484 }
485
486 iterator find(IdentifierInfo* II, Selector S) {
487 // FIXME: Class method lookup. Right now we dont' have a good way
488 // of going between IdentifierInfo* and the class hierarchy.
489 iterator I = M.find(ObjCSummaryKey(II, S));
490 return I == M.end() ? M.find(ObjCSummaryKey(S)) : I;
491 }
492
493 ObjCInterfaceDecl* getReceiverDecl(Expr* E) {
494
495 const PointerType* PT = E->getType()->getAsPointerType();
496 if (!PT) return 0;
497
498 ObjCInterfaceType* OI = dyn_cast<ObjCInterfaceType>(PT->getPointeeType());
499 if (!OI) return 0;
500
501 return OI ? OI->getDecl() : 0;
502 }
503
504 iterator end() { return M.end(); }
505
506 RetainSummary*& operator[](ObjCMessageExpr* ME) {
507
508 Selector S = ME->getSelector();
509
510 if (Expr* Receiver = ME->getReceiver()) {
511 ObjCInterfaceDecl* OD = getReceiverDecl(Receiver);
512 return OD ? M[ObjCSummaryKey(OD->getIdentifier(), S)] : M[S];
513 }
514
515 return M[ObjCSummaryKey(ME->getClassName(), S)];
516 }
517
518 RetainSummary*& operator[](ObjCSummaryKey K) {
519 return M[K];
520 }
521
522 RetainSummary*& operator[](Selector S) {
523 return M[ ObjCSummaryKey(S) ];
524 }
525};
526} // end anonymous namespace
527
528//===----------------------------------------------------------------------===//
529// Data structures for managing collections of summaries.
530//===----------------------------------------------------------------------===//
531
532namespace {
533class VISIBILITY_HIDDEN RetainSummaryManager {
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000534
535 //==-----------------------------------------------------------------==//
536 // Typedefs.
537 //==-----------------------------------------------------------------==//
Ted Kremeneka7338b42008-03-11 06:39:11 +0000538
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000539 typedef llvm::FoldingSet<llvm::FoldingSetNodeWrapper<ArgEffects> >
540 ArgEffectsSetTy;
541
542 typedef llvm::FoldingSet<RetainSummary>
543 SummarySetTy;
544
545 typedef llvm::DenseMap<FunctionDecl*, RetainSummary*>
546 FuncSummariesTy;
547
Ted Kremenek84f010c2008-06-23 23:30:29 +0000548 typedef ObjCSummaryCache ObjCMethodSummariesTy;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000549
550 //==-----------------------------------------------------------------==//
551 // Data.
552 //==-----------------------------------------------------------------==//
553
Ted Kremenek272aa852008-06-25 21:21:56 +0000554 /// Ctx - The ASTContext object for the analyzed ASTs.
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000555 ASTContext& Ctx;
Ted Kremeneke44927e2008-07-01 17:21:27 +0000556
Ted Kremenekede40b72008-07-09 18:11:16 +0000557 /// CFDictionaryCreateII - An IdentifierInfo* representing the indentifier
558 /// "CFDictionaryCreate".
559 IdentifierInfo* CFDictionaryCreateII;
560
Ted Kremenek272aa852008-06-25 21:21:56 +0000561 /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000562 const bool GCEnabled;
563
Ted Kremenek272aa852008-06-25 21:21:56 +0000564 /// SummarySet - A FoldingSet of uniqued summaries.
Ted Kremeneka4c74292008-04-10 22:58:08 +0000565 SummarySetTy SummarySet;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000566
Ted Kremenek272aa852008-06-25 21:21:56 +0000567 /// FuncSummaries - A map from FunctionDecls to summaries.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000568 FuncSummariesTy FuncSummaries;
569
Ted Kremenek272aa852008-06-25 21:21:56 +0000570 /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
571 /// to summaries.
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000572 ObjCMethodSummariesTy ObjCClassMethodSummaries;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000573
Ted Kremenek272aa852008-06-25 21:21:56 +0000574 /// ObjCMethodSummaries - A map from selectors to summaries.
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000575 ObjCMethodSummariesTy ObjCMethodSummaries;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000576
Ted Kremenek272aa852008-06-25 21:21:56 +0000577 /// ArgEffectsSet - A FoldingSet of uniqued ArgEffects.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000578 ArgEffectsSetTy ArgEffectsSet;
579
Ted Kremenek272aa852008-06-25 21:21:56 +0000580 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
581 /// and all other data used by the checker.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000582 llvm::BumpPtrAllocator BPAlloc;
583
Ted Kremenek272aa852008-06-25 21:21:56 +0000584 /// ScratchArgs - A holding buffer for construct ArgEffects.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000585 ArgEffects ScratchArgs;
586
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000587 RetainSummary* StopSummary;
588
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000589 //==-----------------------------------------------------------------==//
590 // Methods.
591 //==-----------------------------------------------------------------==//
592
Ted Kremenek272aa852008-06-25 21:21:56 +0000593 /// getArgEffects - Returns a persistent ArgEffects object based on the
594 /// data in ScratchArgs.
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000595 ArgEffects* getArgEffects();
Ted Kremeneka7338b42008-03-11 06:39:11 +0000596
Ted Kremenek562c1302008-05-05 16:51:50 +0000597 enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000598
599public:
Ted Kremenek064ef322009-02-23 16:51:39 +0000600 RetainSummary* getUnarySummary(const FunctionType* FT, UnaryFuncKind func);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000601
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000602 RetainSummary* getCFSummaryCreateRule(FunctionDecl* FD);
603 RetainSummary* getCFSummaryGetRule(FunctionDecl* FD);
Ted Kremenek17144e82009-01-12 21:45:02 +0000604 RetainSummary* getCFCreateGetRuleSummary(FunctionDecl* FD, const char* FName);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000605
Ted Kremenek266d8b62008-05-06 02:26:56 +0000606 RetainSummary* getPersistentSummary(ArgEffects* AE, RetEffect RetEff,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000607 ArgEffect ReceiverEff = DoNothing,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000608 ArgEffect DefaultEff = MayEscape,
609 bool isEndPath = false);
Ted Kremenek45d0b502008-10-29 04:07:07 +0000610
Ted Kremenek266d8b62008-05-06 02:26:56 +0000611 RetainSummary* getPersistentSummary(RetEffect RE,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000612 ArgEffect ReceiverEff = DoNothing,
Ted Kremeneka3f30dd2008-05-22 17:31:13 +0000613 ArgEffect DefaultEff = MayEscape) {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000614 return getPersistentSummary(getArgEffects(), RE, ReceiverEff, DefaultEff);
Ted Kremenek0e344d42008-05-06 00:30:21 +0000615 }
Ted Kremenek42ea0322008-05-05 23:55:01 +0000616
Ted Kremenekbcaff792008-05-06 15:44:25 +0000617 RetainSummary* getPersistentStopSummary() {
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000618 if (StopSummary)
619 return StopSummary;
620
621 StopSummary = getPersistentSummary(RetEffect::MakeNoRet(),
622 StopTracking, StopTracking);
Ted Kremenek45d0b502008-10-29 04:07:07 +0000623
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000624 return StopSummary;
Ted Kremenekbcaff792008-05-06 15:44:25 +0000625 }
Ted Kremenek926abf22008-05-06 04:20:12 +0000626
Ted Kremenek272aa852008-06-25 21:21:56 +0000627 RetainSummary* getInitMethodSummary(ObjCMessageExpr* ME);
Ted Kremenek42ea0322008-05-05 23:55:01 +0000628
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000629 void InitializeClassMethodSummaries();
630 void InitializeMethodSummaries();
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000631
Ted Kremenek35920ed2009-01-07 00:39:56 +0000632 bool isTrackedObjectType(QualType T);
633
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000634private:
635
Ted Kremenekf2717b02008-07-18 17:24:20 +0000636 void addClsMethSummary(IdentifierInfo* ClsII, Selector S,
637 RetainSummary* Summ) {
638 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
639 }
640
Ted Kremenek272aa852008-06-25 21:21:56 +0000641 void addNSObjectClsMethSummary(Selector S, RetainSummary *Summ) {
642 ObjCClassMethodSummaries[S] = Summ;
643 }
644
645 void addNSObjectMethSummary(Selector S, RetainSummary *Summ) {
646 ObjCMethodSummaries[S] = Summ;
647 }
Ted Kremenekfbf2dc52009-03-04 23:30:42 +0000648
649 void addClassMethSummary(const char* Cls, const char* nullaryName,
650 RetainSummary *Summ) {
651 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
652 Selector S = GetNullarySelector(nullaryName, Ctx);
653 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
654 }
Ted Kremenek272aa852008-06-25 21:21:56 +0000655
Ted Kremenek1b4b6562009-02-25 02:54:57 +0000656 void addInstMethSummary(const char* Cls, const char* nullaryName,
657 RetainSummary *Summ) {
658 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
659 Selector S = GetNullarySelector(nullaryName, Ctx);
660 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
661 }
662
Ted Kremenek45642a42008-08-12 18:48:50 +0000663 void addInstMethSummary(const char* Cls, RetainSummary* Summ, va_list argp) {
Ted Kremenekf2717b02008-07-18 17:24:20 +0000664
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000665 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
666 llvm::SmallVector<IdentifierInfo*, 10> II;
667
668 while (const char* s = va_arg(argp, const char*))
669 II.push_back(&Ctx.Idents.get(s));
670
671 Selector S = Ctx.Selectors.getSelector(II.size(), &II[0]);
Ted Kremenekf2717b02008-07-18 17:24:20 +0000672 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
673 }
Ted Kremenek45642a42008-08-12 18:48:50 +0000674
675 void addInstMethSummary(const char* Cls, RetainSummary* Summ, ...) {
676 va_list argp;
677 va_start(argp, Summ);
678 addInstMethSummary(Cls, Summ, argp);
679 va_end(argp);
680 }
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000681
682 void addPanicSummary(const char* Cls, ...) {
683 RetainSummary* Summ = getPersistentSummary(0, RetEffect::MakeNoRet(),
684 DoNothing, DoNothing, true);
685 va_list argp;
686 va_start (argp, Cls);
Ted Kremenek45642a42008-08-12 18:48:50 +0000687 addInstMethSummary(Cls, Summ, argp);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000688 va_end(argp);
689 }
Ted Kremenekf2717b02008-07-18 17:24:20 +0000690
Ted Kremeneka7338b42008-03-11 06:39:11 +0000691public:
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000692
693 RetainSummaryManager(ASTContext& ctx, bool gcenabled)
Ted Kremeneke44927e2008-07-01 17:21:27 +0000694 : Ctx(ctx),
Ted Kremenekede40b72008-07-09 18:11:16 +0000695 CFDictionaryCreateII(&ctx.Idents.get("CFDictionaryCreate")),
Ted Kremenek272aa852008-06-25 21:21:56 +0000696 GCEnabled(gcenabled), StopSummary(0) {
697
698 InitializeClassMethodSummaries();
699 InitializeMethodSummaries();
700 }
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000701
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000702 ~RetainSummaryManager();
Ted Kremeneka7338b42008-03-11 06:39:11 +0000703
Ted Kremenekd13c1872008-06-24 03:56:45 +0000704 RetainSummary* getSummary(FunctionDecl* FD);
Ted Kremenek272aa852008-06-25 21:21:56 +0000705 RetainSummary* getMethodSummary(ObjCMessageExpr* ME, ObjCInterfaceDecl* ID);
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000706 RetainSummary* getClassMethodSummary(IdentifierInfo* ClsName, Selector S);
Ted Kremenek926abf22008-05-06 04:20:12 +0000707
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000708 bool isGCEnabled() const { return GCEnabled; }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000709};
710
711} // end anonymous namespace
712
713//===----------------------------------------------------------------------===//
714// Implementation of checker data structures.
715//===----------------------------------------------------------------------===//
716
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000717RetainSummaryManager::~RetainSummaryManager() {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000718
719 // FIXME: The ArgEffects could eventually be allocated from BPAlloc,
720 // mitigating the need to do explicit cleanup of the
721 // Argument-Effect summaries.
722
Ted Kremenek42ea0322008-05-05 23:55:01 +0000723 for (ArgEffectsSetTy::iterator I = ArgEffectsSet.begin(),
724 E = ArgEffectsSet.end(); I!=E; ++I)
Ted Kremeneka7338b42008-03-11 06:39:11 +0000725 I->getValue().~ArgEffects();
Ted Kremenek827f93b2008-03-06 00:08:09 +0000726}
Ted Kremeneka7338b42008-03-11 06:39:11 +0000727
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000728ArgEffects* RetainSummaryManager::getArgEffects() {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000729
Ted Kremenekae855d42008-04-24 17:22:33 +0000730 if (ScratchArgs.empty())
731 return NULL;
732
733 // Compute a profile for a non-empty ScratchArgs.
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000734 llvm::FoldingSetNodeID profile;
735 profile.Add(ScratchArgs);
736 void* InsertPos;
737
Ted Kremenekae855d42008-04-24 17:22:33 +0000738 // Look up the uniqued copy, or create a new one.
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000739 llvm::FoldingSetNodeWrapper<ArgEffects>* E =
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000740 ArgEffectsSet.FindNodeOrInsertPos(profile, InsertPos);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000741
Ted Kremenekae855d42008-04-24 17:22:33 +0000742 if (E) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000743 ScratchArgs.clear();
744 return &E->getValue();
745 }
746
747 E = (llvm::FoldingSetNodeWrapper<ArgEffects>*)
Ted Kremenek272aa852008-06-25 21:21:56 +0000748 BPAlloc.Allocate<llvm::FoldingSetNodeWrapper<ArgEffects> >();
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000749
750 new (E) llvm::FoldingSetNodeWrapper<ArgEffects>(ScratchArgs);
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000751 ArgEffectsSet.InsertNode(E, InsertPos);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000752
753 ScratchArgs.clear();
754 return &E->getValue();
755}
756
Ted Kremenek266d8b62008-05-06 02:26:56 +0000757RetainSummary*
758RetainSummaryManager::getPersistentSummary(ArgEffects* AE, RetEffect RetEff,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000759 ArgEffect ReceiverEff,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000760 ArgEffect DefaultEff,
761 bool isEndPath) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000762
Ted Kremenekae855d42008-04-24 17:22:33 +0000763 // Generate a profile for the summary.
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000764 llvm::FoldingSetNodeID profile;
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000765 RetainSummary::Profile(profile, AE, RetEff, DefaultEff, ReceiverEff,
766 isEndPath);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000767
Ted Kremenekae855d42008-04-24 17:22:33 +0000768 // Look up the uniqued summary, or create one if it doesn't exist.
769 void* InsertPos;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000770 RetainSummary* Summ = SummarySet.FindNodeOrInsertPos(profile, InsertPos);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000771
772 if (Summ)
773 return Summ;
774
Ted Kremenekae855d42008-04-24 17:22:33 +0000775 // Create the summary and return it.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000776 Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
Ted Kremenekf2717b02008-07-18 17:24:20 +0000777 new (Summ) RetainSummary(AE, RetEff, DefaultEff, ReceiverEff, isEndPath);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000778 SummarySet.InsertNode(Summ, InsertPos);
779
780 return Summ;
781}
782
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000783//===----------------------------------------------------------------------===//
Ted Kremenek35920ed2009-01-07 00:39:56 +0000784// Predicates.
785//===----------------------------------------------------------------------===//
786
787bool RetainSummaryManager::isTrackedObjectType(QualType T) {
788 if (!Ctx.isObjCObjectPointerType(T))
789 return false;
790
791 // Does it subclass NSObject?
792 ObjCInterfaceType* OT = dyn_cast<ObjCInterfaceType>(T.getTypePtr());
793
794 // We assume that id<..>, id, and "Class" all represent tracked objects.
795 if (!OT)
796 return true;
797
798 // Does the object type subclass NSObject?
799 // FIXME: We can memoize here if this gets too expensive.
800 IdentifierInfo* NSObjectII = &Ctx.Idents.get("NSObject");
801 ObjCInterfaceDecl* ID = OT->getDecl();
802
803 for ( ; ID ; ID = ID->getSuperClass())
804 if (ID->getIdentifier() == NSObjectII)
805 return true;
806
807 return false;
808}
809
810//===----------------------------------------------------------------------===//
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000811// Summary creation for functions (largely uses of Core Foundation).
812//===----------------------------------------------------------------------===//
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000813
Ted Kremenek17144e82009-01-12 21:45:02 +0000814static bool isRetain(FunctionDecl* FD, const char* FName) {
815 const char* loc = strstr(FName, "Retain");
816 return loc && loc[sizeof("Retain")-1] == '\0';
817}
818
819static bool isRelease(FunctionDecl* FD, const char* FName) {
820 const char* loc = strstr(FName, "Release");
821 return loc && loc[sizeof("Release")-1] == '\0';
822}
823
Ted Kremenekd13c1872008-06-24 03:56:45 +0000824RetainSummary* RetainSummaryManager::getSummary(FunctionDecl* FD) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000825
826 SourceLocation Loc = FD->getLocation();
827
828 if (!Loc.isFileID())
829 return NULL;
Ted Kremenek827f93b2008-03-06 00:08:09 +0000830
Ted Kremenekae855d42008-04-24 17:22:33 +0000831 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000832 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremenekae855d42008-04-24 17:22:33 +0000833
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000834 if (I != FuncSummaries.end())
Ted Kremenekae855d42008-04-24 17:22:33 +0000835 return I->second;
836
837 // No summary. Generate one.
Ted Kremenek17144e82009-01-12 21:45:02 +0000838 RetainSummary *S = 0;
Ted Kremenek562c1302008-05-05 16:51:50 +0000839
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000840 do {
Ted Kremenek17144e82009-01-12 21:45:02 +0000841 // We generate "stop" summaries for implicitly defined functions.
842 if (FD->isImplicit()) {
843 S = getPersistentStopSummary();
844 break;
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000845 }
Ted Kremenekeafcc2f2008-11-04 00:36:12 +0000846
Ted Kremenek064ef322009-02-23 16:51:39 +0000847 // [PR 3337] Use 'getAsFunctionType' to strip away any typedefs on the
Ted Kremenekc239b9c2009-01-16 18:40:33 +0000848 // function's type.
Ted Kremenek064ef322009-02-23 16:51:39 +0000849 const FunctionType* FT = FD->getType()->getAsFunctionType();
Ted Kremenek17144e82009-01-12 21:45:02 +0000850 const char* FName = FD->getIdentifier()->getName();
851
Ted Kremenek38c6f022009-03-05 22:11:14 +0000852 // Strip away preceding '_'. Doing this here will effect all the checks
853 // down below.
854 while (*FName == '_') ++FName;
855
Ted Kremenek17144e82009-01-12 21:45:02 +0000856 // Inspect the result type.
857 QualType RetTy = FT->getResultType();
858
859 // FIXME: This should all be refactored into a chain of "summary lookup"
860 // filters.
861 if (strcmp(FName, "IOServiceGetMatchingServices") == 0) {
862 // FIXES: <rdar://problem/6326900>
863 // This should be addressed using a API table. This strcmp is also
864 // a little gross, but there is no need to super optimize here.
865 assert (ScratchArgs.empty());
866 ScratchArgs.push_back(std::make_pair(1, DecRef));
867 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
868 break;
Ted Kremenekcfc50c72008-10-22 20:54:52 +0000869 }
Ted Kremenek17144e82009-01-12 21:45:02 +0000870
871 // Handle: id NSMakeCollectable(CFTypeRef)
872 if (strcmp(FName, "NSMakeCollectable") == 0) {
873 S = (RetTy == Ctx.getObjCIdType())
874 ? getUnarySummary(FT, cfmakecollectable)
875 : getPersistentStopSummary();
876
877 break;
878 }
879
880 if (RetTy->isPointerType()) {
881 // For CoreFoundation ('CF') types.
882 if (isRefType(RetTy, "CF", &Ctx, FName)) {
883 if (isRetain(FD, FName))
884 S = getUnarySummary(FT, cfretain);
885 else if (strstr(FName, "MakeCollectable"))
886 S = getUnarySummary(FT, cfmakecollectable);
887 else
888 S = getCFCreateGetRuleSummary(FD, FName);
889
890 break;
891 }
892
893 // For CoreGraphics ('CG') types.
894 if (isRefType(RetTy, "CG", &Ctx, FName)) {
895 if (isRetain(FD, FName))
896 S = getUnarySummary(FT, cfretain);
897 else
898 S = getCFCreateGetRuleSummary(FD, FName);
899
900 break;
901 }
902
903 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
904 if (isRefType(RetTy, "DADisk") ||
905 isRefType(RetTy, "DADissenter") ||
906 isRefType(RetTy, "DASessionRef")) {
907 S = getCFCreateGetRuleSummary(FD, FName);
908 break;
909 }
910
911 break;
912 }
913
914 // Check for release functions, the only kind of functions that we care
915 // about that don't return a pointer type.
916 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
Ted Kremenek38c6f022009-03-05 22:11:14 +0000917 // Test for 'CGCF'.
918 if (FName[1] == 'G' && FName[2] == 'C' && FName[3] == 'F')
919 FName += 4;
920 else
921 FName += 2;
922
923 if (isRelease(FD, FName))
Ted Kremenek17144e82009-01-12 21:45:02 +0000924 S = getUnarySummary(FT, cfrelease);
925 else {
Ted Kremenek7b293682009-01-29 22:45:13 +0000926 assert (ScratchArgs.empty());
927 // Remaining CoreFoundation and CoreGraphics functions.
928 // We use to assume that they all strictly followed the ownership idiom
929 // and that ownership cannot be transferred. While this is technically
930 // correct, many methods allow a tracked object to escape. For example:
931 //
932 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
933 // CFDictionaryAddValue(y, key, x);
934 // CFRelease(x);
935 // ... it is okay to use 'x' since 'y' has a reference to it
936 //
937 // We handle this and similar cases with the follow heuristic. If the
938 // function name contains "InsertValue", "SetValue" or "AddValue" then
939 // we assume that arguments may "escape."
940 //
941 ArgEffect E = (CStrInCStrNoCase(FName, "InsertValue") ||
942 CStrInCStrNoCase(FName, "AddValue") ||
Ted Kremenekcf071252009-02-05 22:34:53 +0000943 CStrInCStrNoCase(FName, "SetValue") ||
944 CStrInCStrNoCase(FName, "AppendValue"))
Ted Kremenek7b293682009-01-29 22:45:13 +0000945 ? MayEscape : DoNothing;
946
947 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek17144e82009-01-12 21:45:02 +0000948 }
949 }
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000950 }
951 while (0);
Ted Kremenekae855d42008-04-24 17:22:33 +0000952
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000953 FuncSummaries[FD] = S;
Ted Kremenek562c1302008-05-05 16:51:50 +0000954 return S;
Ted Kremenek827f93b2008-03-06 00:08:09 +0000955}
956
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000957RetainSummary*
958RetainSummaryManager::getCFCreateGetRuleSummary(FunctionDecl* FD,
959 const char* FName) {
960
Ted Kremenek562c1302008-05-05 16:51:50 +0000961 if (strstr(FName, "Create") || strstr(FName, "Copy"))
962 return getCFSummaryCreateRule(FD);
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000963
Ted Kremenek562c1302008-05-05 16:51:50 +0000964 if (strstr(FName, "Get"))
965 return getCFSummaryGetRule(FD);
966
967 return 0;
968}
969
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000970RetainSummary*
Ted Kremenek064ef322009-02-23 16:51:39 +0000971RetainSummaryManager::getUnarySummary(const FunctionType* FT,
972 UnaryFuncKind func) {
973
Ted Kremenek17144e82009-01-12 21:45:02 +0000974 // Sanity check that this is *really* a unary function. This can
975 // happen if people do weird things.
Douglas Gregor4fa58902009-02-26 23:50:07 +0000976 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
Ted Kremenek17144e82009-01-12 21:45:02 +0000977 if (!FTP || FTP->getNumArgs() != 1)
978 return getPersistentStopSummary();
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000979
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000980 assert (ScratchArgs.empty());
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000981
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000982 switch (func) {
Ted Kremenek17144e82009-01-12 21:45:02 +0000983 case cfretain: {
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000984 ScratchArgs.push_back(std::make_pair(0, IncRef));
Ted Kremeneka3f30dd2008-05-22 17:31:13 +0000985 return getPersistentSummary(RetEffect::MakeAlias(0),
986 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000987 }
988
989 case cfrelease: {
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000990 ScratchArgs.push_back(std::make_pair(0, DecRef));
Ted Kremeneka3f30dd2008-05-22 17:31:13 +0000991 return getPersistentSummary(RetEffect::MakeNoRet(),
992 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000993 }
994
995 case cfmakecollectable: {
Ted Kremenek2126bef2009-02-18 21:57:45 +0000996 ScratchArgs.push_back(std::make_pair(0, MakeCollectable));
997 return getPersistentSummary(RetEffect::MakeAlias(0),DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000998 }
999
1000 default:
Ted Kremenek562c1302008-05-05 16:51:50 +00001001 assert (false && "Not a supported unary function.");
Ted Kremenek9449ca92008-08-12 20:41:56 +00001002 return 0;
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00001003 }
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001004}
1005
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001006RetainSummary* RetainSummaryManager::getCFSummaryCreateRule(FunctionDecl* FD) {
Ted Kremenekae855d42008-04-24 17:22:33 +00001007 assert (ScratchArgs.empty());
Ted Kremenekede40b72008-07-09 18:11:16 +00001008
1009 if (FD->getIdentifier() == CFDictionaryCreateII) {
1010 ScratchArgs.push_back(std::make_pair(1, DoNothingByRef));
1011 ScratchArgs.push_back(std::make_pair(2, DoNothingByRef));
1012 }
1013
Ted Kremenek68621b92009-01-28 05:56:51 +00001014 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001015}
1016
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001017RetainSummary* RetainSummaryManager::getCFSummaryGetRule(FunctionDecl* FD) {
Ted Kremenekae855d42008-04-24 17:22:33 +00001018 assert (ScratchArgs.empty());
Ted Kremenek68621b92009-01-28 05:56:51 +00001019 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1020 DoNothing, DoNothing);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001021}
1022
Ted Kremeneka7338b42008-03-11 06:39:11 +00001023//===----------------------------------------------------------------------===//
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001024// Summary creation for Selectors.
1025//===----------------------------------------------------------------------===//
1026
Ted Kremenekbcaff792008-05-06 15:44:25 +00001027RetainSummary*
Ted Kremenek272aa852008-06-25 21:21:56 +00001028RetainSummaryManager::getInitMethodSummary(ObjCMessageExpr* ME) {
Ted Kremenek42ea0322008-05-05 23:55:01 +00001029 assert(ScratchArgs.empty());
1030
Ted Kremenek802cfc72009-02-20 00:05:35 +00001031 // 'init' methods only return an alias if the return type is a location type.
1032 QualType T = ME->getType();
Ted Kremenek42ea0322008-05-05 23:55:01 +00001033 RetainSummary* Summ =
Ted Kremenek802cfc72009-02-20 00:05:35 +00001034 getPersistentSummary(Loc::IsLocType(T) ? RetEffect::MakeReceiverAlias()
1035 : RetEffect::MakeNoRet());
Ted Kremenek42ea0322008-05-05 23:55:01 +00001036
Ted Kremenek272aa852008-06-25 21:21:56 +00001037 ObjCMethodSummaries[ME] = Summ;
Ted Kremenek42ea0322008-05-05 23:55:01 +00001038 return Summ;
1039}
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001040
Ted Kremenek272aa852008-06-25 21:21:56 +00001041
Ted Kremenekbcaff792008-05-06 15:44:25 +00001042RetainSummary*
Ted Kremenek272aa852008-06-25 21:21:56 +00001043RetainSummaryManager::getMethodSummary(ObjCMessageExpr* ME,
1044 ObjCInterfaceDecl* ID) {
Ted Kremenekbcaff792008-05-06 15:44:25 +00001045
1046 Selector S = ME->getSelector();
Ted Kremenek42ea0322008-05-05 23:55:01 +00001047
Ted Kremenek272aa852008-06-25 21:21:56 +00001048 // Look up a summary in our summary cache.
1049 ObjCMethodSummariesTy::iterator I = ObjCMethodSummaries.find(ID, S);
Ted Kremenek42ea0322008-05-05 23:55:01 +00001050
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001051 if (I != ObjCMethodSummaries.end())
Ted Kremenek42ea0322008-05-05 23:55:01 +00001052 return I->second;
Ted Kremenek42ea0322008-05-05 23:55:01 +00001053
Ted Kremenek35920ed2009-01-07 00:39:56 +00001054 // "initXXX": pass-through for receiver.
Ted Kremenek42ea0322008-05-05 23:55:01 +00001055 const char* s = S.getIdentifierInfoForSlot(0)->getName();
Ted Kremenek48b6d9e2008-05-07 03:45:05 +00001056 assert (ScratchArgs.empty());
Ted Kremenek1d3d9562008-05-06 06:09:09 +00001057
Ted Kremenek4395b452009-02-21 05:13:43 +00001058 if (deriveNamingConvention(s) == InitRule)
Ted Kremenek35920ed2009-01-07 00:39:56 +00001059 return getInitMethodSummary(ME);
Ted Kremenekbcaff792008-05-06 15:44:25 +00001060
Ted Kremenek35920ed2009-01-07 00:39:56 +00001061 // Look for methods that return an owned object.
1062 if (!isTrackedObjectType(Ctx.getCanonicalType(ME->getType())))
Ted Kremenek5496f6d2008-05-07 04:25:59 +00001063 return 0;
Ted Kremenek48b6d9e2008-05-07 03:45:05 +00001064
Ted Kremenek35920ed2009-01-07 00:39:56 +00001065 if (followsFundamentalRule(s)) {
1066 RetEffect E = isGCEnabled() ? RetEffect::MakeNoRet()
Ted Kremenek68621b92009-01-28 05:56:51 +00001067 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremenek48b6d9e2008-05-07 03:45:05 +00001068 RetainSummary* Summ = getPersistentSummary(E);
Ted Kremenek272aa852008-06-25 21:21:56 +00001069 ObjCMethodSummaries[ME] = Summ;
Ted Kremenekbcaff792008-05-06 15:44:25 +00001070 return Summ;
1071 }
Ted Kremenekbcaff792008-05-06 15:44:25 +00001072
Ted Kremenek42ea0322008-05-05 23:55:01 +00001073 return 0;
1074}
1075
Ted Kremeneka7722b72008-05-06 21:26:51 +00001076RetainSummary*
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001077RetainSummaryManager::getClassMethodSummary(IdentifierInfo* ClsName,
1078 Selector S) {
Ted Kremeneka7722b72008-05-06 21:26:51 +00001079
Ted Kremenek272aa852008-06-25 21:21:56 +00001080 // FIXME: Eventually we should properly do class method summaries, but
1081 // it requires us being able to walk the type hierarchy. Unfortunately,
1082 // we cannot do this with just an IdentifierInfo* for the class name.
1083
Ted Kremeneka7722b72008-05-06 21:26:51 +00001084 // Look up a summary in our cache of Selectors -> Summaries.
Ted Kremenek272aa852008-06-25 21:21:56 +00001085 ObjCMethodSummariesTy::iterator I = ObjCClassMethodSummaries.find(ClsName, S);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001086
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001087 if (I != ObjCClassMethodSummaries.end())
Ted Kremeneka7722b72008-05-06 21:26:51 +00001088 return I->second;
1089
Ted Kremenek4c479322008-05-06 23:07:13 +00001090 return 0;
Ted Kremeneka7722b72008-05-06 21:26:51 +00001091}
1092
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001093void RetainSummaryManager::InitializeClassMethodSummaries() {
Ted Kremenek0e344d42008-05-06 00:30:21 +00001094
1095 assert (ScratchArgs.empty());
1096
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001097 RetEffect E = isGCEnabled() ? RetEffect::MakeNoRet()
Ted Kremenek68621b92009-01-28 05:56:51 +00001098 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001099
Ted Kremenek0e344d42008-05-06 00:30:21 +00001100 RetainSummary* Summ = getPersistentSummary(E);
1101
Ted Kremenek272aa852008-06-25 21:21:56 +00001102 // Create the summaries for "alloc", "new", and "allocWithZone:" for
1103 // NSObject and its derivatives.
1104 addNSObjectClsMethSummary(GetNullarySelector("alloc", Ctx), Summ);
1105 addNSObjectClsMethSummary(GetNullarySelector("new", Ctx), Summ);
1106 addNSObjectClsMethSummary(GetUnarySelector("allocWithZone", Ctx), Summ);
Ted Kremenekf2717b02008-07-18 17:24:20 +00001107
1108 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001109 addClsMethSummary(&Ctx.Idents.get("NSAssertionHandler"),
Ted Kremenek68621b92009-01-28 05:56:51 +00001110 GetNullarySelector("currentHandler", Ctx),
1111 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001112
1113 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremenek9b112d22009-01-28 21:44:40 +00001114 ScratchArgs.push_back(std::make_pair(0, Autorelease));
1115 addClsMethSummary(&Ctx.Idents.get("NSAutoreleasePool"),
1116 GetUnarySelector("addObject", Ctx),
1117 getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenekf21cb242009-02-23 02:31:16 +00001118 DoNothing, Autorelease));
Ted Kremenek0e344d42008-05-06 00:30:21 +00001119}
1120
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001121void RetainSummaryManager::InitializeMethodSummaries() {
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001122
1123 assert (ScratchArgs.empty());
1124
Ted Kremeneka7722b72008-05-06 21:26:51 +00001125 // Create the "init" selector. It just acts as a pass-through for the
1126 // receiver.
Ted Kremenek56c70aa2009-02-23 16:54:00 +00001127 RetainSummary* InitSumm =
1128 getPersistentSummary(RetEffect::MakeReceiverAlias());
Ted Kremeneke44927e2008-07-01 17:21:27 +00001129 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001130
1131 // The next methods are allocators.
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001132 RetEffect E = isGCEnabled() ? RetEffect::MakeNoRet()
Ted Kremenek68621b92009-01-28 05:56:51 +00001133 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001134
Ted Kremeneke44927e2008-07-01 17:21:27 +00001135 RetainSummary* Summ = getPersistentSummary(E);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001136
1137 // Create the "copy" selector.
Ted Kremenek9449ca92008-08-12 20:41:56 +00001138 addNSObjectMethSummary(GetNullarySelector("copy", Ctx), Summ);
1139
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001140 // Create the "mutableCopy" selector.
Ted Kremenek272aa852008-06-25 21:21:56 +00001141 addNSObjectMethSummary(GetNullarySelector("mutableCopy", Ctx), Summ);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001142
Ted Kremenek266d8b62008-05-06 02:26:56 +00001143 // Create the "retain" selector.
1144 E = RetEffect::MakeReceiverAlias();
Ted Kremenek58dd95b2009-02-18 18:54:33 +00001145 Summ = getPersistentSummary(E, IncRefMsg);
Ted Kremenek272aa852008-06-25 21:21:56 +00001146 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001147
1148 // Create the "release" selector.
Ted Kremenek58dd95b2009-02-18 18:54:33 +00001149 Summ = getPersistentSummary(E, DecRefMsg);
Ted Kremenek272aa852008-06-25 21:21:56 +00001150 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Ted Kremenekc00b32b2008-05-07 21:17:39 +00001151
1152 // Create the "drain" selector.
1153 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek272aa852008-06-25 21:21:56 +00001154 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
Ted Kremenek6537a642009-03-17 19:42:23 +00001155
1156 // Create the -dealloc summary.
1157 Summ = getPersistentSummary(RetEffect::MakeNoRet(), Dealloc);
1158 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001159
1160 // Create the "autorelease" selector.
Ted Kremenek9b112d22009-01-28 21:44:40 +00001161 Summ = getPersistentSummary(E, Autorelease);
Ted Kremenek272aa852008-06-25 21:21:56 +00001162 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001163
Ted Kremenekaac82832009-02-23 17:45:03 +00001164 // Specially handle NSAutoreleasePool.
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001165 addInstMethSummary("NSAutoreleasePool", "init",
Ted Kremenekaac82832009-02-23 17:45:03 +00001166 getPersistentSummary(RetEffect::MakeReceiverAlias(),
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001167 NewAutoreleasePool));
Ted Kremenekaac82832009-02-23 17:45:03 +00001168
Ted Kremenek45642a42008-08-12 18:48:50 +00001169 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremenek7e3a3272009-02-23 02:51:29 +00001170 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1171 // self-own themselves. However, they only do this once they are displayed.
1172 // Thus, we need to track an NSWindow's display status.
1173 // This is tracked in <rdar://problem/6062711>.
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001174 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
1175 addClassMethSummary("NSWindow", "alloc",
1176 getPersistentSummary(RetEffect::MakeNoRet()));
1177
1178#if 0
Ted Kremeneke44927e2008-07-01 17:21:27 +00001179 RetainSummary *NSWindowSumm =
Ted Kremenek7e3a3272009-02-23 02:51:29 +00001180 getPersistentSummary(RetEffect::MakeReceiverAlias(), StopTracking);
Ted Kremenek45642a42008-08-12 18:48:50 +00001181
1182 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1183 "styleMask", "backing", "defer", NULL);
1184
1185 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1186 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001187#endif
Ted Kremenek45642a42008-08-12 18:48:50 +00001188
1189 // For NSPanel (which subclasses NSWindow), allocated objects are not
1190 // self-owned.
1191 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1192 "styleMask", "backing", "defer", NULL);
1193
1194 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1195 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek272aa852008-06-25 21:21:56 +00001196
Ted Kremenekf2717b02008-07-18 17:24:20 +00001197 // Create NSAssertionHandler summaries.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001198 addPanicSummary("NSAssertionHandler", "handleFailureInFunction", "file",
1199 "lineNumber", "description", NULL);
Ted Kremenekf2717b02008-07-18 17:24:20 +00001200
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001201 addPanicSummary("NSAssertionHandler", "handleFailureInMethod", "object",
1202 "file", "lineNumber", "description", NULL);
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001203}
1204
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001205//===----------------------------------------------------------------------===//
Ted Kremenek7aef4842008-04-16 20:40:59 +00001206// Reference-counting logic (typestate + counts).
Ted Kremeneka7338b42008-03-11 06:39:11 +00001207//===----------------------------------------------------------------------===//
1208
Ted Kremeneka7338b42008-03-11 06:39:11 +00001209namespace {
1210
Ted Kremenek7d421f32008-04-09 23:49:11 +00001211class VISIBILITY_HIDDEN RefVal {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001212public:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001213 enum Kind {
1214 Owned = 0, // Owning reference.
1215 NotOwned, // Reference is not owned by still valid (not freed).
1216 Released, // Object has been released.
1217 ReturnedOwned, // Returned object passes ownership to caller.
1218 ReturnedNotOwned, // Return object does not pass ownership to caller.
Ted Kremenek6537a642009-03-17 19:42:23 +00001219 ERROR_START,
1220 ErrorDeallocNotOwned, // -dealloc called on non-owned object.
1221 ErrorDeallocGC, // Calling -dealloc with GC enabled.
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001222 ErrorUseAfterRelease, // Object used after released.
1223 ErrorReleaseNotOwned, // Release of an object that was not owned.
Ted Kremenek6537a642009-03-17 19:42:23 +00001224 ERROR_LEAK_START,
Ted Kremenek311f3d42008-10-22 23:56:21 +00001225 ErrorLeak, // A memory leak due to excessive reference counts.
1226 ErrorLeakReturned // A memory leak due to the returning method not having
1227 // the correct naming conventions.
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001228 };
Ted Kremenek68621b92009-01-28 05:56:51 +00001229
1230private:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001231 Kind kind;
Ted Kremenek68621b92009-01-28 05:56:51 +00001232 RetEffect::ObjKind okind;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001233 unsigned Cnt;
Ted Kremenek272aa852008-06-25 21:21:56 +00001234 QualType T;
1235
Ted Kremenek68621b92009-01-28 05:56:51 +00001236 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, QualType t)
1237 : kind(k), okind(o), Cnt(cnt), T(t) {}
Ted Kremenek0d721572008-03-11 17:48:22 +00001238
Ted Kremenek68621b92009-01-28 05:56:51 +00001239 RefVal(Kind k, unsigned cnt = 0)
1240 : kind(k), okind(RetEffect::AnyObj), Cnt(cnt) {}
1241
1242public:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001243 Kind getKind() const { return kind; }
Ted Kremenek68621b92009-01-28 05:56:51 +00001244
1245 RetEffect::ObjKind getObjKind() const { return okind; }
Ted Kremenek0d721572008-03-11 17:48:22 +00001246
Ted Kremenek6537a642009-03-17 19:42:23 +00001247 unsigned getCount() const { return Cnt; }
1248 void clearCounts() { Cnt = 0; }
1249
Ted Kremenek272aa852008-06-25 21:21:56 +00001250 QualType getType() const { return T; }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001251
1252 // Useful predicates.
Ted Kremenek0d721572008-03-11 17:48:22 +00001253
Ted Kremenek6537a642009-03-17 19:42:23 +00001254 static bool isError(Kind k) { return k >= ERROR_START; }
Ted Kremenek1daa16c2008-03-11 18:14:09 +00001255
Ted Kremenek6537a642009-03-17 19:42:23 +00001256 static bool isLeak(Kind k) { return k >= ERROR_LEAK_START; }
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001257
Ted Kremenekffefc352008-04-11 22:25:11 +00001258 bool isOwned() const {
1259 return getKind() == Owned;
1260 }
1261
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001262 bool isNotOwned() const {
1263 return getKind() == NotOwned;
1264 }
1265
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001266 bool isReturnedOwned() const {
1267 return getKind() == ReturnedOwned;
1268 }
1269
1270 bool isReturnedNotOwned() const {
1271 return getKind() == ReturnedNotOwned;
1272 }
1273
1274 bool isNonLeakError() const {
1275 Kind k = getKind();
1276 return isError(k) && !isLeak(k);
1277 }
1278
Ted Kremenek68621b92009-01-28 05:56:51 +00001279 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
1280 unsigned Count = 1) {
1281 return RefVal(Owned, o, Count, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001282 }
1283
Ted Kremenek68621b92009-01-28 05:56:51 +00001284 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
1285 unsigned Count = 0) {
1286 return RefVal(NotOwned, o, Count, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001287 }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001288
1289 static RefVal makeReturnedOwned(unsigned Count) {
1290 return RefVal(ReturnedOwned, Count);
1291 }
1292
1293 static RefVal makeReturnedNotOwned() {
1294 return RefVal(ReturnedNotOwned);
1295 }
1296
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001297 // Comparison, profiling, and pretty-printing.
Ted Kremenek0d721572008-03-11 17:48:22 +00001298
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001299 bool operator==(const RefVal& X) const {
Ted Kremenek272aa852008-06-25 21:21:56 +00001300 return kind == X.kind && Cnt == X.Cnt && T == X.T;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001301 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001302
Ted Kremenek272aa852008-06-25 21:21:56 +00001303 RefVal operator-(size_t i) const {
Ted Kremenek68621b92009-01-28 05:56:51 +00001304 return RefVal(getKind(), getObjKind(), getCount() - i, getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001305 }
1306
1307 RefVal operator+(size_t i) const {
Ted Kremenek68621b92009-01-28 05:56:51 +00001308 return RefVal(getKind(), getObjKind(), getCount() + i, getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001309 }
1310
1311 RefVal operator^(Kind k) const {
Ted Kremenek68621b92009-01-28 05:56:51 +00001312 return RefVal(k, getObjKind(), getCount(), getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001313 }
Ted Kremenek6537a642009-03-17 19:42:23 +00001314
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001315 void Profile(llvm::FoldingSetNodeID& ID) const {
1316 ID.AddInteger((unsigned) kind);
1317 ID.AddInteger(Cnt);
Ted Kremenek272aa852008-06-25 21:21:56 +00001318 ID.Add(T);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001319 }
1320
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001321 void print(std::ostream& Out) const;
Ted Kremenek0d721572008-03-11 17:48:22 +00001322};
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001323
1324void RefVal::print(std::ostream& Out) const {
Ted Kremenek272aa852008-06-25 21:21:56 +00001325 if (!T.isNull())
1326 Out << "Tracked Type:" << T.getAsString() << '\n';
1327
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001328 switch (getKind()) {
1329 default: assert(false);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001330 case Owned: {
1331 Out << "Owned";
1332 unsigned cnt = getCount();
1333 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001334 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001335 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001336
Ted Kremenekc4f81022008-04-10 23:09:18 +00001337 case NotOwned: {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001338 Out << "NotOwned";
Ted Kremenekc4f81022008-04-10 23:09:18 +00001339 unsigned cnt = getCount();
1340 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001341 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001342 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001343
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001344 case ReturnedOwned: {
1345 Out << "ReturnedOwned";
1346 unsigned cnt = getCount();
1347 if (cnt) Out << " (+ " << cnt << ")";
1348 break;
1349 }
1350
1351 case ReturnedNotOwned: {
1352 Out << "ReturnedNotOwned";
1353 unsigned cnt = getCount();
1354 if (cnt) Out << " (+ " << cnt << ")";
1355 break;
1356 }
1357
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001358 case Released:
1359 Out << "Released";
1360 break;
Ted Kremenek6537a642009-03-17 19:42:23 +00001361
1362 case ErrorDeallocGC:
1363 Out << "-dealloc (GC)";
1364 break;
1365
1366 case ErrorDeallocNotOwned:
1367 Out << "-dealloc (not-owned)";
1368 break;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001369
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001370 case ErrorLeak:
1371 Out << "Leaked";
1372 break;
1373
Ted Kremenek311f3d42008-10-22 23:56:21 +00001374 case ErrorLeakReturned:
1375 Out << "Leaked (Bad naming)";
1376 break;
1377
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001378 case ErrorUseAfterRelease:
1379 Out << "Use-After-Release [ERROR]";
1380 break;
1381
1382 case ErrorReleaseNotOwned:
1383 Out << "Release of Not-Owned [ERROR]";
1384 break;
1385 }
1386}
Ted Kremenek0d721572008-03-11 17:48:22 +00001387
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001388} // end anonymous namespace
1389
1390//===----------------------------------------------------------------------===//
1391// RefBindings - State used to track object reference counts.
1392//===----------------------------------------------------------------------===//
1393
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001394typedef llvm::ImmutableMap<SymbolRef, RefVal> RefBindings;
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001395static int RefBIndex = 0;
Ted Kremenek876d8df2009-02-19 23:47:02 +00001396static std::pair<const void*, const void*> LeakProgramPointTag(&RefBIndex, 0);
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001397
1398namespace clang {
Ted Kremenek91781202008-08-17 03:20:02 +00001399 template<>
1400 struct GRStateTrait<RefBindings> : public GRStatePartialTrait<RefBindings> {
1401 static inline void* GDMIndex() { return &RefBIndex; }
1402 };
1403}
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001404
1405//===----------------------------------------------------------------------===//
Ted Kremenekb6578942009-02-24 19:15:11 +00001406// AutoreleaseBindings - State used to track objects in autorelease pools.
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001407//===----------------------------------------------------------------------===//
1408
Ted Kremenekb6578942009-02-24 19:15:11 +00001409typedef llvm::ImmutableMap<SymbolRef, unsigned> ARCounts;
1410typedef llvm::ImmutableMap<SymbolRef, ARCounts> ARPoolContents;
1411typedef llvm::ImmutableList<SymbolRef> ARStack;
Ted Kremenekaac82832009-02-23 17:45:03 +00001412
Ted Kremenekb6578942009-02-24 19:15:11 +00001413static int AutoRCIndex = 0;
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001414static int AutoRBIndex = 0;
1415
Ted Kremenekb6578942009-02-24 19:15:11 +00001416namespace { class VISIBILITY_HIDDEN AutoreleasePoolContents {}; }
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001417namespace { class VISIBILITY_HIDDEN AutoreleaseStack {}; }
Ted Kremenekb6578942009-02-24 19:15:11 +00001418
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001419namespace clang {
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001420template<> struct GRStateTrait<AutoreleaseStack>
Ted Kremenekb6578942009-02-24 19:15:11 +00001421 : public GRStatePartialTrait<ARStack> {
1422 static inline void* GDMIndex() { return &AutoRBIndex; }
1423};
1424
1425template<> struct GRStateTrait<AutoreleasePoolContents>
1426 : public GRStatePartialTrait<ARPoolContents> {
1427 static inline void* GDMIndex() { return &AutoRCIndex; }
1428};
1429} // end clang namespace
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001430
Ted Kremenek7aef4842008-04-16 20:40:59 +00001431//===----------------------------------------------------------------------===//
1432// Transfer functions.
1433//===----------------------------------------------------------------------===//
1434
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001435namespace {
1436
Ted Kremenek7d421f32008-04-09 23:49:11 +00001437class VISIBILITY_HIDDEN CFRefCount : public GRSimpleVals {
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001438public:
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001439 class BindingsPrinter : public GRState::Printer {
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001440 public:
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001441 virtual void Print(std::ostream& Out, const GRState* state,
1442 const char* nl, const char* sep);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001443 };
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001444
1445private:
Ted Kremenekc26c4692009-02-18 03:48:14 +00001446 typedef llvm::DenseMap<const GRExprEngine::NodeTy*, const RetainSummary*>
1447 SummaryLogTy;
1448
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001449 RetainSummaryManager Summaries;
Ted Kremenekc26c4692009-02-18 03:48:14 +00001450 SummaryLogTy SummaryLog;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001451 const LangOptions& LOpts;
Ted Kremenekb6578942009-02-24 19:15:11 +00001452 ARCounts::Factory ARCountFactory;
Ted Kremenek91781202008-08-17 03:20:02 +00001453
Ted Kremenek708af042009-02-05 06:50:21 +00001454 BugType *useAfterRelease, *releaseNotOwned;
Ted Kremenek6537a642009-03-17 19:42:23 +00001455 BugType *deallocGC, *deallocNotOwned;
Ted Kremenek708af042009-02-05 06:50:21 +00001456 BugType *leakWithinFunction, *leakAtReturn;
1457 BugReporter *BR;
Ted Kremeneka7338b42008-03-11 06:39:11 +00001458
Ted Kremenekb6578942009-02-24 19:15:11 +00001459 GRStateRef Update(GRStateRef state, SymbolRef sym, RefVal V, ArgEffect E,
1460 RefVal::Kind& hasErr);
1461
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001462 void ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
1463 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001464 Expr* NodeExpr, Expr* ErrorExpr,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001465 ExplodedNode<GRState>* Pred,
1466 const GRState* St,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001467 RefVal::Kind hasErr, SymbolRef Sym);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001468
Ted Kremenek0106e202008-10-24 20:32:50 +00001469 std::pair<GRStateRef, bool>
1470 HandleSymbolDeath(GRStateManager& VMgr, const GRState* St,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001471 const Decl* CD, SymbolRef sid, RefVal V, bool& hasLeak);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001472
Ted Kremenekb6578942009-02-24 19:15:11 +00001473public:
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00001474 CFRefCount(ASTContext& Ctx, bool gcenabled, const LangOptions& lopts)
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001475 : Summaries(Ctx, gcenabled),
Ted Kremenek6537a642009-03-17 19:42:23 +00001476 LOpts(lopts), useAfterRelease(0), releaseNotOwned(0),
1477 deallocGC(0), deallocNotOwned(0),
Ted Kremenek708af042009-02-05 06:50:21 +00001478 leakWithinFunction(0), leakAtReturn(0), BR(0) {}
Ted Kremenek1feab292008-04-16 04:28:53 +00001479
Ted Kremenek708af042009-02-05 06:50:21 +00001480 virtual ~CFRefCount() {}
Ted Kremenek7d421f32008-04-09 23:49:11 +00001481
Ted Kremenekbf6babf2009-02-04 23:49:09 +00001482 void RegisterChecks(BugReporter &BR);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001483
Ted Kremenekb0f2b9e2008-08-16 00:49:49 +00001484 virtual void RegisterPrinters(std::vector<GRState::Printer*>& Printers) {
1485 Printers.push_back(new BindingsPrinter());
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001486 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00001487
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001488 bool isGCEnabled() const { return Summaries.isGCEnabled(); }
Ted Kremenekfe30beb2008-04-30 23:47:44 +00001489 const LangOptions& getLangOptions() const { return LOpts; }
1490
Ted Kremenekc26c4692009-02-18 03:48:14 +00001491 const RetainSummary *getSummaryOfNode(const ExplodedNode<GRState> *N) const {
1492 SummaryLogTy::const_iterator I = SummaryLog.find(N);
1493 return I == SummaryLog.end() ? 0 : I->second;
1494 }
1495
Ted Kremeneka7338b42008-03-11 06:39:11 +00001496 // Calls.
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001497
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001498 void EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001499 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001500 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001501 Expr* Ex,
1502 Expr* Receiver,
1503 RetainSummary* Summ,
Ted Kremenek2719e982008-06-17 02:43:46 +00001504 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001505 ExplodedNode<GRState>* Pred);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001506
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001507 virtual void EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekce0767f2008-03-12 21:06:49 +00001508 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001509 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001510 CallExpr* CE, SVal L,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001511 ExplodedNode<GRState>* Pred);
Ted Kremenek10fe66d2008-04-09 01:10:13 +00001512
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001513
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001514 virtual void EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001515 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001516 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001517 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001518 ExplodedNode<GRState>* Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001519
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001520 bool EvalObjCMessageExprAux(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001521 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001522 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001523 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001524 ExplodedNode<GRState>* Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001525
Ted Kremeneka42be302009-02-14 01:43:44 +00001526 // Stores.
1527 virtual void EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val);
1528
Ted Kremenekffefc352008-04-11 22:25:11 +00001529 // End-of-path.
1530
1531 virtual void EvalEndPath(GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001532 GREndPathNodeBuilder<GRState>& Builder);
Ted Kremenekffefc352008-04-11 22:25:11 +00001533
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001534 virtual void EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek541db372008-04-24 23:57:27 +00001535 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001536 GRStmtNodeBuilder<GRState>& Builder,
1537 ExplodedNode<GRState>* Pred,
Ted Kremenek5c0729b2009-01-21 22:26:05 +00001538 Stmt* S, const GRState* state,
1539 SymbolReaper& SymReaper);
1540
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001541 // Return statements.
1542
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001543 virtual void EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001544 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001545 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001546 ReturnStmt* S,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001547 ExplodedNode<GRState>* Pred);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001548
1549 // Assumptions.
1550
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001551 virtual const GRState* EvalAssume(GRStateManager& VMgr,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001552 const GRState* St, SVal Cond,
Ted Kremenekf22f8682008-07-10 22:03:41 +00001553 bool Assumption, bool& isFeasible);
Ted Kremeneka7338b42008-03-11 06:39:11 +00001554};
1555
1556} // end anonymous namespace
1557
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001558
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001559void CFRefCount::BindingsPrinter::Print(std::ostream& Out, const GRState* state,
1560 const char* nl, const char* sep) {
1561
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001562 RefBindings B = state->get<RefBindings>();
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001563
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001564 if (!B.isEmpty())
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001565 Out << sep << nl;
1566
1567 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
1568 Out << (*I).first << " : ";
1569 (*I).second.print(Out);
1570 Out << nl;
1571 }
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001572
1573 // Print the autorelease stack.
1574 ARStack stack = state->get<AutoreleaseStack>();
1575 if (!stack.isEmpty()) {
1576 Out << sep << nl << "AR pool stack:";
1577
1578 for (ARStack::iterator I=stack.begin(), E=stack.end(); I!=E; ++I)
1579 Out << ' ' << (*I);
1580
1581 Out << nl;
1582 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001583}
1584
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001585static inline ArgEffect GetArgE(RetainSummary* Summ, unsigned idx) {
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001586 return Summ ? Summ->getArg(idx) : MayEscape;
Ted Kremenek455dd862008-04-11 20:23:24 +00001587}
1588
Ted Kremenek266d8b62008-05-06 02:26:56 +00001589static inline RetEffect GetRetEffect(RetainSummary* Summ) {
1590 return Summ ? Summ->getRetEffect() : RetEffect::MakeNoRet();
Ted Kremenek455dd862008-04-11 20:23:24 +00001591}
1592
Ted Kremenek227c5372008-05-06 02:41:27 +00001593static inline ArgEffect GetReceiverE(RetainSummary* Summ) {
1594 return Summ ? Summ->getReceiverEffect() : DoNothing;
1595}
1596
Ted Kremenekf2717b02008-07-18 17:24:20 +00001597static inline bool IsEndPath(RetainSummary* Summ) {
1598 return Summ ? Summ->isEndPath() : false;
1599}
1600
Ted Kremenek1feab292008-04-16 04:28:53 +00001601
Ted Kremenek272aa852008-06-25 21:21:56 +00001602/// GetReturnType - Used to get the return type of a message expression or
1603/// function call with the intention of affixing that type to a tracked symbol.
1604/// While the the return type can be queried directly from RetEx, when
1605/// invoking class methods we augment to the return type to be that of
1606/// a pointer to the class (as opposed it just being id).
1607static QualType GetReturnType(Expr* RetE, ASTContext& Ctx) {
1608
1609 QualType RetTy = RetE->getType();
1610
1611 // FIXME: We aren't handling id<...>.
Chris Lattnerb724ab22008-07-26 22:36:27 +00001612 const PointerType* PT = RetTy->getAsPointerType();
Ted Kremenek272aa852008-06-25 21:21:56 +00001613 if (!PT)
1614 return RetTy;
1615
1616 // If RetEx is not a message expression just return its type.
1617 // If RetEx is a message expression, return its types if it is something
1618 /// more specific than id.
1619
1620 ObjCMessageExpr* ME = dyn_cast<ObjCMessageExpr>(RetE);
1621
Steve Naroff17c03822009-02-12 17:52:19 +00001622 if (!ME || !Ctx.isObjCIdStructType(PT->getPointeeType()))
Ted Kremenek272aa852008-06-25 21:21:56 +00001623 return RetTy;
1624
1625 ObjCInterfaceDecl* D = ME->getClassInfo().first;
1626
1627 // At this point we know the return type of the message expression is id.
1628 // If we have an ObjCInterceDecl, we know this is a call to a class method
1629 // whose type we can resolve. In such cases, promote the return type to
1630 // Class*.
1631 return !D ? RetTy : Ctx.getPointerType(Ctx.getObjCInterfaceType(D));
1632}
1633
1634
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001635void CFRefCount::EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001636 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001637 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001638 Expr* Ex,
1639 Expr* Receiver,
1640 RetainSummary* Summ,
Ted Kremenek2719e982008-06-17 02:43:46 +00001641 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001642 ExplodedNode<GRState>* Pred) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001643
Ted Kremeneka7338b42008-03-11 06:39:11 +00001644 // Get the state.
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001645 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenek0106e202008-10-24 20:32:50 +00001646 ASTContext& Ctx = Eng.getStateManager().getContext();
Ted Kremenek227c5372008-05-06 02:41:27 +00001647
1648 // Evaluate the effect of the arguments.
Ted Kremenek1feab292008-04-16 04:28:53 +00001649 RefVal::Kind hasErr = (RefVal::Kind) 0;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001650 unsigned idx = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00001651 Expr* ErrorExpr = NULL;
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001652 SymbolRef ErrorSym = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00001653
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001654 for (ExprIterator I = arg_beg; I != arg_end; ++I, ++idx) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00001655 SVal V = state.GetSValAsScalarOrLoc(*I);
Ted Kremenek9577c1e2009-03-03 22:06:47 +00001656 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00001657
Ted Kremenek9577c1e2009-03-03 22:06:47 +00001658 if (Sym.isValid())
Ted Kremenekb6578942009-02-24 19:15:11 +00001659 if (RefBindings::data_type* T = state.get<RefBindings>(Sym)) {
1660 state = Update(state, Sym, *T, GetArgE(Summ, idx), hasErr);
1661 if (hasErr) {
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00001662 ErrorExpr = *I;
Ted Kremenek6064a362008-07-07 16:21:19 +00001663 ErrorSym = Sym;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00001664 break;
Ted Kremenek9577c1e2009-03-03 22:06:47 +00001665 }
1666 continue;
Ted Kremenekb6578942009-02-24 19:15:11 +00001667 }
Ted Kremenekede40b72008-07-09 18:11:16 +00001668
Ted Kremenek9577c1e2009-03-03 22:06:47 +00001669 if (isa<Loc>(V)) {
1670 if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(&V)) {
Ted Kremenekede40b72008-07-09 18:11:16 +00001671 if (GetArgE(Summ, idx) == DoNothingByRef)
1672 continue;
1673
1674 // Invalidate the value of the variable passed by reference.
Ted Kremenek852e3ca2008-07-03 23:26:32 +00001675
1676 // FIXME: Either this logic should also be replicated in GRSimpleVals
1677 // or should be pulled into a separate "constraint engine."
Ted Kremenekede40b72008-07-09 18:11:16 +00001678
Ted Kremenek852e3ca2008-07-03 23:26:32 +00001679 // FIXME: We can have collisions on the conjured symbol if the
1680 // expression *I also creates conjured symbols. We probably want
1681 // to identify conjured symbols by an expression pair: the enclosing
1682 // expression (the context) and the expression itself. This should
Ted Kremenekede40b72008-07-09 18:11:16 +00001683 // disambiguate conjured symbols.
Ted Kremenekb15eba42008-10-04 05:50:14 +00001684
Ted Kremenek38a4b4b2008-10-17 20:28:54 +00001685 const TypedRegion* R = dyn_cast<TypedRegion>(MR->getRegion());
Ted Kremenek58a26bf2008-12-17 19:42:34 +00001686
Ted Kremenek6a9b5352009-03-01 05:44:08 +00001687 // Blast through TypedViewRegions to get the original region type.
Ted Kremenek58a26bf2008-12-17 19:42:34 +00001688 while (R) {
Ted Kremenek6a9b5352009-03-01 05:44:08 +00001689 const TypedViewRegion* ATR = dyn_cast<TypedViewRegion>(R);
Ted Kremenek58a26bf2008-12-17 19:42:34 +00001690 if (!ATR) break;
1691 R = dyn_cast<TypedRegion>(ATR->getSuperRegion());
1692 }
1693
Ted Kremenek53b24182009-03-04 22:56:43 +00001694 if (R) {
Ted Kremenek618c6cd2008-12-18 23:34:57 +00001695 // Is the invalidated variable something that we were tracking?
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00001696 SymbolRef Sym = state.GetSValAsScalarOrLoc(R).getAsLocSymbol();
Ted Kremenek618c6cd2008-12-18 23:34:57 +00001697
Ted Kremenek53b24182009-03-04 22:56:43 +00001698 // Remove any existing reference-count binding.
1699 if (Sym.isValid()) state = state.remove<RefBindings>(Sym);
Ted Kremenekb15eba42008-10-04 05:50:14 +00001700
Ted Kremenek53b24182009-03-04 22:56:43 +00001701 if (R->isBoundable(Ctx)) {
1702 // Set the value of the variable to be a conjured symbol.
1703 unsigned Count = Builder.getCurrentBlockCount();
1704 QualType T = R->getRValueType(Ctx);
1705
1706 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())) {
1707 SymbolRef NewSym =
1708 Eng.getSymbolManager().getConjuredSymbol(*I, T, Count);
1709
1710 state = state.BindLoc(Loc::MakeVal(R),
1711 Loc::IsLocType(T)
1712 ? cast<SVal>(loc::SymbolVal(NewSym))
1713 : cast<SVal>(nonloc::SymbolVal(NewSym)));
1714 }
1715 else if (const RecordType *RT = T->getAsStructureType()) {
1716 // Handle structs in a not so awesome way. Here we just
1717 // eagerly bind new symbols to the fields. In reality we
1718 // should have the store manager handle this. The idea is just
1719 // to prototype some basic functionality here. All of this logic
1720 // should one day soon just go away.
1721 const RecordDecl *RD = RT->getDecl()->getDefinition(Ctx);
1722
1723 // No record definition. There is nothing we can do.
1724 if (!RD)
1725 continue;
1726
1727 MemRegionManager &MRMgr = state.getManager().getRegionManager();
1728
1729 // Iterate through the fields and construct new symbols.
1730 for (RecordDecl::field_iterator FI=RD->field_begin(),
1731 FE=RD->field_end(); FI!=FE; ++FI) {
1732
1733 // For now just handle scalar fields.
1734 FieldDecl *FD = *FI;
1735 QualType FT = FD->getType();
1736
1737 if (Loc::IsLocType(FT) ||
1738 (FT->isIntegerType() && FT->isScalarType())) {
1739
1740 // Tag the symbol with the field decl so that we generate
1741 // a unique symbol.
1742 SymbolRef NewSym =
1743 Eng.getSymbolManager().getConjuredSymbol(*I, FT, Count, FD);
1744
1745 // Create a region.
1746 // FIXME: How do we handle 'typedefs' in TypeViewRegions?
1747 // e.g.:
1748 // typedef struct *s foo;
1749 //
1750 // ((foo) x)->f vs. x->f
1751 //
1752 // The cast will add a ViewTypeRegion. Probably RegionStore
1753 // needs to reason about typedefs explicitly when binding
1754 // fields and elements.
1755 //
1756 const FieldRegion* FR = MRMgr.getFieldRegion(FD, R);
1757
1758 state = state.BindLoc(Loc::MakeVal(FR),
1759 Loc::IsLocType(FT)
1760 ? cast<SVal>(loc::SymbolVal(NewSym))
1761 : cast<SVal>(nonloc::SymbolVal(NewSym)));
1762 }
1763 }
1764 }
1765 else {
1766 // Just blast away other values.
1767 state = state.BindLoc(*MR, UnknownVal());
1768 }
Ted Kremenek8f90e712008-10-17 22:23:12 +00001769 }
Ted Kremenekb15eba42008-10-04 05:50:14 +00001770 }
1771 else
Ted Kremenek09102db2008-11-12 19:22:09 +00001772 state = state.BindLoc(*MR, UnknownVal());
Ted Kremenek852e3ca2008-07-03 23:26:32 +00001773 }
1774 else {
1775 // Nuke all other arguments passed by reference.
Zhongxing Xu097fc982008-10-17 05:57:07 +00001776 state = state.Unbind(cast<Loc>(V));
Ted Kremenek852e3ca2008-07-03 23:26:32 +00001777 }
Ted Kremeneke4924202008-04-11 20:51:02 +00001778 }
Zhongxing Xu097fc982008-10-17 05:57:07 +00001779 else if (isa<nonloc::LocAsInteger>(V))
1780 state = state.Unbind(cast<nonloc::LocAsInteger>(V).getLoc());
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001781 }
Ted Kremenek1feab292008-04-16 04:28:53 +00001782
Ted Kremenek272aa852008-06-25 21:21:56 +00001783 // Evaluate the effect on the message receiver.
Ted Kremenek227c5372008-05-06 02:41:27 +00001784 if (!ErrorExpr && Receiver) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00001785 SymbolRef Sym = state.GetSValAsScalarOrLoc(Receiver).getAsLocSymbol();
Ted Kremenek9577c1e2009-03-03 22:06:47 +00001786 if (Sym.isValid()) {
Ted Kremenekb6578942009-02-24 19:15:11 +00001787 if (const RefVal* T = state.get<RefBindings>(Sym)) {
1788 state = Update(state, Sym, *T, GetReceiverE(Summ), hasErr);
1789 if (hasErr) {
Ted Kremenek227c5372008-05-06 02:41:27 +00001790 ErrorExpr = Receiver;
Ted Kremenek6064a362008-07-07 16:21:19 +00001791 ErrorSym = Sym;
Ted Kremenek227c5372008-05-06 02:41:27 +00001792 }
Ted Kremenekb6578942009-02-24 19:15:11 +00001793 }
Ted Kremenek227c5372008-05-06 02:41:27 +00001794 }
1795 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001796
Ted Kremenek272aa852008-06-25 21:21:56 +00001797 // Process any errors.
Ted Kremenek1feab292008-04-16 04:28:53 +00001798 if (hasErr) {
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001799 ProcessNonLeakError(Dst, Builder, Ex, ErrorExpr, Pred, state,
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001800 hasErr, ErrorSym);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001801 return;
Ted Kremenek0d721572008-03-11 17:48:22 +00001802 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001803
Ted Kremenekf2717b02008-07-18 17:24:20 +00001804 // Consult the summary for the return value.
Ted Kremenek266d8b62008-05-06 02:26:56 +00001805 RetEffect RE = GetRetEffect(Summ);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001806
1807 switch (RE.getKind()) {
1808 default:
1809 assert (false && "Unhandled RetEffect."); break;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001810
Ted Kremenek8f90e712008-10-17 22:23:12 +00001811 case RetEffect::NoRet: {
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001812
Ted Kremenek455dd862008-04-11 20:23:24 +00001813 // Make up a symbol for the return value (not reference counted).
Ted Kremeneke4924202008-04-11 20:51:02 +00001814 // FIXME: This is basically copy-and-paste from GRSimpleVals. We
1815 // should compose behavior, not copy it.
Ted Kremenek455dd862008-04-11 20:23:24 +00001816
Ted Kremenek8f90e712008-10-17 22:23:12 +00001817 // FIXME: We eventually should handle structs and other compound types
1818 // that are returned by value.
1819
1820 QualType T = Ex->getType();
1821
Ted Kremenek79413a52008-11-13 06:10:40 +00001822 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())) {
Ted Kremenek455dd862008-04-11 20:23:24 +00001823 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001824 SymbolRef Sym = Eng.getSymbolManager().getConjuredSymbol(Ex, Count);
Ted Kremenek455dd862008-04-11 20:23:24 +00001825
Ted Kremenek802cfc72009-02-20 00:05:35 +00001826 SVal X = Loc::IsLocType(T)
Zhongxing Xu097fc982008-10-17 05:57:07 +00001827 ? cast<SVal>(loc::SymbolVal(Sym))
1828 : cast<SVal>(nonloc::SymbolVal(Sym));
Ted Kremenek455dd862008-04-11 20:23:24 +00001829
Ted Kremenek09102db2008-11-12 19:22:09 +00001830 state = state.BindExpr(Ex, X, false);
Ted Kremenek455dd862008-04-11 20:23:24 +00001831 }
1832
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00001833 break;
Ted Kremenek8f90e712008-10-17 22:23:12 +00001834 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00001835
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001836 case RetEffect::Alias: {
Ted Kremenek272aa852008-06-25 21:21:56 +00001837 unsigned idx = RE.getIndex();
Ted Kremenek2719e982008-06-17 02:43:46 +00001838 assert (arg_end >= arg_beg);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001839 assert (idx < (unsigned) (arg_end - arg_beg));
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00001840 SVal V = state.GetSValAsScalarOrLoc(*(arg_beg+idx));
Ted Kremenek09102db2008-11-12 19:22:09 +00001841 state = state.BindExpr(Ex, V, false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001842 break;
1843 }
1844
Ted Kremenek227c5372008-05-06 02:41:27 +00001845 case RetEffect::ReceiverAlias: {
1846 assert (Receiver);
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00001847 SVal V = state.GetSValAsScalarOrLoc(Receiver);
Ted Kremenek09102db2008-11-12 19:22:09 +00001848 state = state.BindExpr(Ex, V, false);
Ted Kremenek227c5372008-05-06 02:41:27 +00001849 break;
1850 }
1851
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001852 case RetEffect::OwnedAllocatedSymbol:
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001853 case RetEffect::OwnedSymbol: {
1854 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001855 SymbolRef Sym = Eng.getSymbolManager().getConjuredSymbol(Ex, Count);
Ted Kremenek68621b92009-01-28 05:56:51 +00001856 QualType RetT = GetReturnType(Ex, Eng.getContext());
1857 state =
1858 state.set<RefBindings>(Sym, RefVal::makeOwned(RE.getObjKind(), RetT));
Ted Kremenek09102db2008-11-12 19:22:09 +00001859 state = state.BindExpr(Ex, loc::SymbolVal(Sym), false);
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001860
Ted Kremenek45c52a12009-03-09 22:46:49 +00001861
1862 // FIXME: Add a flag to the checker where allocations are assumed to
1863 // *not fail.
1864#if 0
Ted Kremeneke62fd052009-01-28 22:27:59 +00001865 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) {
1866 bool isFeasible;
1867 state = state.Assume(loc::SymbolVal(Sym), true, isFeasible);
1868 assert(isFeasible && "Cannot assume fresh symbol is non-null.");
1869 }
Ted Kremenek45c52a12009-03-09 22:46:49 +00001870#endif
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001871
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001872 break;
1873 }
1874
1875 case RetEffect::NotOwnedSymbol: {
1876 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001877 SymbolRef Sym = Eng.getSymbolManager().getConjuredSymbol(Ex, Count);
Ted Kremenek272aa852008-06-25 21:21:56 +00001878 QualType RetT = GetReturnType(Ex, Eng.getContext());
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001879
Ted Kremenek68621b92009-01-28 05:56:51 +00001880 state =
1881 state.set<RefBindings>(Sym, RefVal::makeNotOwned(RE.getObjKind(),RetT));
Ted Kremenek09102db2008-11-12 19:22:09 +00001882 state = state.BindExpr(Ex, loc::SymbolVal(Sym), false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001883 break;
1884 }
1885 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001886
Ted Kremenek0dd65012009-02-18 02:00:25 +00001887 // Generate a sink node if we are at the end of a path.
1888 GRExprEngine::NodeTy *NewNode =
1889 IsEndPath(Summ) ? Builder.MakeSinkNode(Dst, Ex, Pred, state)
1890 : Builder.MakeNode(Dst, Ex, Pred, state);
1891
1892 // Annotate the edge with summary we used.
1893 // FIXME: This assumes that we always use the same summary when generating
1894 // this node.
1895 if (NewNode) SummaryLog[NewNode] = Summ;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001896}
1897
1898
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001899void CFRefCount::EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001900 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001901 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001902 CallExpr* CE, SVal L,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001903 ExplodedNode<GRState>* Pred) {
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001904
Zhongxing Xu097fc982008-10-17 05:57:07 +00001905 RetainSummary* Summ = !isa<loc::FuncVal>(L) ? 0
1906 : Summaries.getSummary(cast<loc::FuncVal>(L).getDecl());
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001907
1908 EvalSummary(Dst, Eng, Builder, CE, 0, Summ,
1909 CE->arg_begin(), CE->arg_end(), Pred);
Ted Kremenek827f93b2008-03-06 00:08:09 +00001910}
Ted Kremeneka7338b42008-03-11 06:39:11 +00001911
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001912void CFRefCount::EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001913 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001914 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001915 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001916 ExplodedNode<GRState>* Pred) {
Ted Kremenek926abf22008-05-06 04:20:12 +00001917 RetainSummary* Summ;
Ted Kremenek33661802008-05-01 21:31:50 +00001918
Ted Kremenek272aa852008-06-25 21:21:56 +00001919 if (Expr* Receiver = ME->getReceiver()) {
1920 // We need the type-information of the tracked receiver object
1921 // Retrieve it from the state.
1922 ObjCInterfaceDecl* ID = 0;
1923
1924 // FIXME: Wouldn't it be great if this code could be reduced? It's just
1925 // a chain of lookups.
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001926 const GRState* St = Builder.GetState(Pred);
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00001927 SVal V = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
Ted Kremenek272aa852008-06-25 21:21:56 +00001928
Ted Kremenek9577c1e2009-03-03 22:06:47 +00001929 SymbolRef Sym = V.getAsLocSymbol();
1930 if (Sym.isValid()) {
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001931 if (const RefVal* T = St->get<RefBindings>(Sym)) {
Ted Kremenek6064a362008-07-07 16:21:19 +00001932 QualType Ty = T->getType();
Ted Kremenek272aa852008-06-25 21:21:56 +00001933
1934 if (const PointerType* PT = Ty->getAsPointerType()) {
1935 QualType PointeeTy = PT->getPointeeType();
1936
1937 if (ObjCInterfaceType* IT = dyn_cast<ObjCInterfaceType>(PointeeTy))
1938 ID = IT->getDecl();
1939 }
1940 }
1941 }
1942
1943 Summ = Summaries.getMethodSummary(ME, ID);
Ted Kremenek0106e202008-10-24 20:32:50 +00001944
Ted Kremenek63d09ae2008-10-23 01:56:15 +00001945 // Special-case: are we sending a mesage to "self"?
1946 // This is a hack. When we have full-IP this should be removed.
1947 if (!Summ) {
1948 ObjCMethodDecl* MD =
1949 dyn_cast<ObjCMethodDecl>(&Eng.getGraph().getCodeDecl());
1950
1951 if (MD) {
1952 if (Expr* Receiver = ME->getReceiver()) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00001953 SVal X = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
Ted Kremenek63d09ae2008-10-23 01:56:15 +00001954 if (loc::MemRegionVal* L = dyn_cast<loc::MemRegionVal>(&X))
Ted Kremenek0106e202008-10-24 20:32:50 +00001955 if (L->getRegion() == Eng.getStateManager().getSelfRegion(St)) {
1956 // Create a summmary where all of the arguments "StopTracking".
1957 Summ = Summaries.getPersistentSummary(RetEffect::MakeNoRet(),
1958 DoNothing,
1959 StopTracking);
1960 }
Ted Kremenek63d09ae2008-10-23 01:56:15 +00001961 }
1962 }
1963 }
Ted Kremenek272aa852008-06-25 21:21:56 +00001964 }
Ted Kremenek1feab292008-04-16 04:28:53 +00001965 else
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001966 Summ = Summaries.getClassMethodSummary(ME->getClassName(),
1967 ME->getSelector());
Ted Kremenek1feab292008-04-16 04:28:53 +00001968
Ted Kremenek926abf22008-05-06 04:20:12 +00001969 EvalSummary(Dst, Eng, Builder, ME, ME->getReceiver(), Summ,
1970 ME->arg_begin(), ME->arg_end(), Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001971}
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00001972
1973namespace {
1974class VISIBILITY_HIDDEN StopTrackingCallback : public SymbolVisitor {
1975 GRStateRef state;
1976public:
1977 StopTrackingCallback(GRStateRef st) : state(st) {}
1978 GRStateRef getState() { return state; }
1979
1980 bool VisitSymbol(SymbolRef sym) {
1981 state = state.remove<RefBindings>(sym);
1982 return true;
1983 }
Ted Kremenek926abf22008-05-06 04:20:12 +00001984
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00001985 const GRState* getState() const { return state.getState(); }
1986};
1987} // end anonymous namespace
1988
1989
Ted Kremeneka42be302009-02-14 01:43:44 +00001990void CFRefCount::EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val) {
Ted Kremeneka42be302009-02-14 01:43:44 +00001991 // Are we storing to something that causes the value to "escape"?
Ted Kremenek7aef4842008-04-16 20:40:59 +00001992 bool escapes = false;
1993
Ted Kremenek28d7eef2008-10-18 03:49:51 +00001994 // A value escapes in three possible cases (this may change):
1995 //
1996 // (1) we are binding to something that is not a memory region.
1997 // (2) we are binding to a memregion that does not have stack storage
1998 // (3) we are binding to a memregion with stack storage that the store
Ted Kremeneka42be302009-02-14 01:43:44 +00001999 // does not understand.
Ted Kremeneka42be302009-02-14 01:43:44 +00002000 GRStateRef state = B.getState();
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002001
Ted Kremeneka42be302009-02-14 01:43:44 +00002002 if (!isa<loc::MemRegionVal>(location))
Ted Kremenek7aef4842008-04-16 20:40:59 +00002003 escapes = true;
Ted Kremenekb15eba42008-10-04 05:50:14 +00002004 else {
Ted Kremeneka42be302009-02-14 01:43:44 +00002005 const MemRegion* R = cast<loc::MemRegionVal>(location).getRegion();
2006 escapes = !B.getStateManager().hasStackStorage(R);
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002007
2008 if (!escapes) {
2009 // To test (3), generate a new state with the binding removed. If it is
2010 // the same state, then it escapes (since the store cannot represent
2011 // the binding).
Ted Kremeneka42be302009-02-14 01:43:44 +00002012 escapes = (state == (state.BindLoc(cast<Loc>(location), UnknownVal())));
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002013 }
Ted Kremenekb15eba42008-10-04 05:50:14 +00002014 }
Ted Kremeneka42be302009-02-14 01:43:44 +00002015
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002016 // If our store can represent the binding and we aren't storing to something
2017 // that doesn't have local storage then just return and have the simulation
2018 // state continue as is.
2019 if (!escapes)
2020 return;
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002021
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002022 // Otherwise, find all symbols referenced by 'val' that we are tracking
2023 // and stop tracking them.
2024 B.MakeNode(state.scanReachableSymbols<StopTrackingCallback>(val).getState());
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002025}
2026
Ted Kremenek0106e202008-10-24 20:32:50 +00002027std::pair<GRStateRef,bool>
2028CFRefCount::HandleSymbolDeath(GRStateManager& VMgr,
2029 const GRState* St, const Decl* CD,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002030 SymbolRef sid,
Ted Kremenek0106e202008-10-24 20:32:50 +00002031 RefVal V, bool& hasLeak) {
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002032
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002033 GRStateRef state(St, VMgr);
Sanjiv Guptafa451432008-10-31 09:52:39 +00002034 assert ((!V.isReturnedOwned() || CD) &&
Ted Kremenek311f3d42008-10-22 23:56:21 +00002035 "CodeDecl must be available for reporting ReturnOwned errors.");
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002036
Ted Kremenek311f3d42008-10-22 23:56:21 +00002037 if (V.isReturnedOwned() && V.getCount() == 0)
2038 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
Chris Lattner3a8f2942008-11-24 03:33:13 +00002039 std::string s = MD->getSelector().getAsString();
Ted Kremenekcdd3bb22008-11-05 16:54:44 +00002040 if (!followsReturnRule(s.c_str())) {
Ted Kremenek311f3d42008-10-22 23:56:21 +00002041 hasLeak = true;
Ted Kremenek0106e202008-10-24 20:32:50 +00002042 state = state.set<RefBindings>(sid, V ^ RefVal::ErrorLeakReturned);
2043 return std::make_pair(state, true);
Ted Kremenek311f3d42008-10-22 23:56:21 +00002044 }
2045 }
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002046
Ted Kremenek311f3d42008-10-22 23:56:21 +00002047 // All other cases.
2048
2049 hasLeak = V.isOwned() ||
2050 ((V.isNotOwned() || V.isReturnedOwned()) && V.getCount() > 0);
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002051
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002052 if (!hasLeak)
Ted Kremenek0106e202008-10-24 20:32:50 +00002053 return std::make_pair(state.remove<RefBindings>(sid), false);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002054
Ted Kremenek0106e202008-10-24 20:32:50 +00002055 return std::make_pair(state.set<RefBindings>(sid, V ^ RefVal::ErrorLeak),
2056 false);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002057}
2058
Ted Kremenek541db372008-04-24 23:57:27 +00002059
Ted Kremenekffefc352008-04-11 22:25:11 +00002060
Ted Kremenek541db372008-04-24 23:57:27 +00002061// Dead symbols.
2062
Ted Kremenek708af042009-02-05 06:50:21 +00002063
Ted Kremenek541db372008-04-24 23:57:27 +00002064
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002065 // Return statements.
2066
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002067void CFRefCount::EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002068 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002069 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002070 ReturnStmt* S,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002071 ExplodedNode<GRState>* Pred) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002072
2073 Expr* RetE = S->getRetValue();
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002074 if (!RetE)
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002075 return;
2076
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002077 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002078 SymbolRef Sym = state.GetSValAsScalarOrLoc(RetE).getAsLocSymbol();
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002079
2080 if (!Sym.isValid())
2081 return;
2082
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002083 // Get the reference count binding (if any).
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002084 const RefVal* T = state.get<RefBindings>(Sym);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002085
2086 if (!T)
2087 return;
2088
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002089 // Change the reference count.
Ted Kremenek6064a362008-07-07 16:21:19 +00002090 RefVal X = *T;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002091
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002092 switch (X.getKind()) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002093 case RefVal::Owned: {
2094 unsigned cnt = X.getCount();
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00002095 assert (cnt > 0);
2096 X = RefVal::makeReturnedOwned(cnt - 1);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002097 break;
2098 }
2099
2100 case RefVal::NotOwned: {
2101 unsigned cnt = X.getCount();
2102 X = cnt ? RefVal::makeReturnedOwned(cnt - 1)
2103 : RefVal::makeReturnedNotOwned();
2104 break;
2105 }
2106
2107 default:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002108 return;
2109 }
2110
2111 // Update the binding.
Ted Kremenek91781202008-08-17 03:20:02 +00002112 state = state.set<RefBindings>(Sym, X);
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002113 Builder.MakeNode(Dst, S, Pred, state);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002114}
2115
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002116// Assumptions.
2117
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002118const GRState* CFRefCount::EvalAssume(GRStateManager& VMgr,
2119 const GRState* St,
Zhongxing Xu097fc982008-10-17 05:57:07 +00002120 SVal Cond, bool Assumption,
Ted Kremenekf22f8682008-07-10 22:03:41 +00002121 bool& isFeasible) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002122
2123 // FIXME: We may add to the interface of EvalAssume the list of symbols
2124 // whose assumptions have changed. For now we just iterate through the
2125 // bindings and check if any of the tracked symbols are NULL. This isn't
2126 // too bad since the number of symbols we will track in practice are
2127 // probably small and EvalAssume is only called at branches and a few
2128 // other places.
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002129 RefBindings B = St->get<RefBindings>();
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002130
2131 if (B.isEmpty())
2132 return St;
2133
2134 bool changed = false;
Ted Kremenek91781202008-08-17 03:20:02 +00002135
2136 GRStateRef state(St, VMgr);
2137 RefBindings::Factory& RefBFactory = state.get_context<RefBindings>();
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002138
2139 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002140 // Check if the symbol is null (or equal to any constant).
2141 // If this is the case, stop tracking the symbol.
Zhongxing Xuc6b27d02008-08-29 14:52:36 +00002142 if (VMgr.getSymVal(St, I.getKey())) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002143 changed = true;
2144 B = RefBFactory.Remove(B, I.getKey());
2145 }
2146 }
2147
Ted Kremenek91781202008-08-17 03:20:02 +00002148 if (changed)
2149 state = state.set<RefBindings>(B);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002150
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002151 return state;
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002152}
Ted Kremeneka7338b42008-03-11 06:39:11 +00002153
Ted Kremenekb6578942009-02-24 19:15:11 +00002154GRStateRef CFRefCount::Update(GRStateRef state, SymbolRef sym,
2155 RefVal V, ArgEffect E,
2156 RefVal::Kind& hasErr) {
Ted Kremenek58dd95b2009-02-18 18:54:33 +00002157
2158 // In GC mode [... release] and [... retain] do nothing.
2159 switch (E) {
2160 default: break;
2161 case IncRefMsg: E = isGCEnabled() ? DoNothing : IncRef; break;
2162 case DecRefMsg: E = isGCEnabled() ? DoNothing : DecRef; break;
Ted Kremenek2126bef2009-02-18 21:57:45 +00002163 case MakeCollectable: E = isGCEnabled() ? DecRef : DoNothing; break;
Ted Kremenekaac82832009-02-23 17:45:03 +00002164 case NewAutoreleasePool: E = isGCEnabled() ? DoNothing :
2165 NewAutoreleasePool; break;
Ted Kremenek58dd95b2009-02-18 18:54:33 +00002166 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00002167
Ted Kremenek6537a642009-03-17 19:42:23 +00002168 // Handle all use-after-releases.
2169 if (!isGCEnabled() && V.getKind() == RefVal::Released) {
2170 V = V ^ RefVal::ErrorUseAfterRelease;
2171 hasErr = V.getKind();
2172 return state.set<RefBindings>(sym, V);
2173 }
2174
Ted Kremenek0d721572008-03-11 17:48:22 +00002175 switch (E) {
2176 default:
2177 assert (false && "Unhandled CFRef transition.");
Ted Kremenek6537a642009-03-17 19:42:23 +00002178
2179 case Dealloc:
2180 // Any use of -dealloc in GC is *bad*.
2181 if (isGCEnabled()) {
2182 V = V ^ RefVal::ErrorDeallocGC;
2183 hasErr = V.getKind();
2184 break;
2185 }
2186
2187 switch (V.getKind()) {
2188 default:
2189 assert(false && "Invalid case.");
2190 case RefVal::Owned:
2191 // The object immediately transitions to the released state.
2192 V = V ^ RefVal::Released;
2193 V.clearCounts();
2194 return state.set<RefBindings>(sym, V);
2195 case RefVal::NotOwned:
2196 V = V ^ RefVal::ErrorDeallocNotOwned;
2197 hasErr = V.getKind();
2198 break;
2199 }
2200 break;
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00002201
Ted Kremenekb7826ab2009-02-25 23:11:49 +00002202 case NewAutoreleasePool:
2203 assert(!isGCEnabled());
2204 return state.add<AutoreleaseStack>(sym);
2205
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00002206 case MayEscape:
2207 if (V.getKind() == RefVal::Owned) {
Ted Kremenek272aa852008-06-25 21:21:56 +00002208 V = V ^ RefVal::NotOwned;
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00002209 break;
2210 }
Ted Kremenek6537a642009-03-17 19:42:23 +00002211
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00002212 // Fall-through.
Ted Kremenek1b4b6562009-02-25 02:54:57 +00002213
Ted Kremenekede40b72008-07-09 18:11:16 +00002214 case DoNothingByRef:
Ted Kremenek0d721572008-03-11 17:48:22 +00002215 case DoNothing:
Ted Kremenekb6578942009-02-24 19:15:11 +00002216 return state;
Ted Kremeneke5a4bb02008-06-30 16:57:41 +00002217
Ted Kremenek9b112d22009-01-28 21:44:40 +00002218 case Autorelease:
Ted Kremenek6537a642009-03-17 19:42:23 +00002219 if (isGCEnabled())
2220 return state;
2221
2222 // Fall-through.
2223
Ted Kremenek227c5372008-05-06 02:41:27 +00002224 case StopTracking:
Ted Kremenekb6578942009-02-24 19:15:11 +00002225 return state.remove<RefBindings>(sym);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002226
Ted Kremenek0d721572008-03-11 17:48:22 +00002227 case IncRef:
2228 switch (V.getKind()) {
2229 default:
2230 assert(false);
2231
2232 case RefVal::Owned:
Ted Kremenek0d721572008-03-11 17:48:22 +00002233 case RefVal::NotOwned:
Ted Kremenek272aa852008-06-25 21:21:56 +00002234 V = V + 1;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002235 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00002236 case RefVal::Released:
Ted Kremenek6537a642009-03-17 19:42:23 +00002237 // Non-GC cases are handled above.
2238 assert(isGCEnabled());
2239 V = (V ^ RefVal::Owned) + 1;
Ted Kremenek0d721572008-03-11 17:48:22 +00002240 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002241 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002242 break;
2243
Ted Kremenek272aa852008-06-25 21:21:56 +00002244 case SelfOwn:
2245 V = V ^ RefVal::NotOwned;
Ted Kremenek58dd95b2009-02-18 18:54:33 +00002246 // Fall-through.
Ted Kremenek0d721572008-03-11 17:48:22 +00002247 case DecRef:
2248 switch (V.getKind()) {
2249 default:
Ted Kremenek6537a642009-03-17 19:42:23 +00002250 // case 'RefVal::Released' handled above.
Ted Kremenek0d721572008-03-11 17:48:22 +00002251 assert (false);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002252
Ted Kremenek272aa852008-06-25 21:21:56 +00002253 case RefVal::Owned:
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00002254 assert(V.getCount() > 0);
2255 if (V.getCount() == 1) V = V ^ RefVal::Released;
2256 V = V - 1;
Ted Kremenek0d721572008-03-11 17:48:22 +00002257 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00002258
Ted Kremenek272aa852008-06-25 21:21:56 +00002259 case RefVal::NotOwned:
2260 if (V.getCount() > 0)
2261 V = V - 1;
Ted Kremenekc4f81022008-04-10 23:09:18 +00002262 else {
Ted Kremenek272aa852008-06-25 21:21:56 +00002263 V = V ^ RefVal::ErrorReleaseNotOwned;
Ted Kremenek1feab292008-04-16 04:28:53 +00002264 hasErr = V.getKind();
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002265 }
Ted Kremenek0d721572008-03-11 17:48:22 +00002266 break;
Ted Kremenek6537a642009-03-17 19:42:23 +00002267
Ted Kremenek0d721572008-03-11 17:48:22 +00002268 case RefVal::Released:
Ted Kremenek6537a642009-03-17 19:42:23 +00002269 // Non-GC cases are handled above.
2270 assert(isGCEnabled());
Ted Kremenek272aa852008-06-25 21:21:56 +00002271 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek1feab292008-04-16 04:28:53 +00002272 hasErr = V.getKind();
Ted Kremenek6537a642009-03-17 19:42:23 +00002273 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002274 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002275 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00002276 }
Ted Kremenekb6578942009-02-24 19:15:11 +00002277 return state.set<RefBindings>(sym, V);
Ted Kremeneka7338b42008-03-11 06:39:11 +00002278}
2279
Ted Kremenek10fe66d2008-04-09 01:10:13 +00002280//===----------------------------------------------------------------------===//
Ted Kremenek7d421f32008-04-09 23:49:11 +00002281// Error reporting.
Ted Kremenek10fe66d2008-04-09 01:10:13 +00002282//===----------------------------------------------------------------------===//
2283
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002284namespace {
2285
2286 //===-------------===//
2287 // Bug Descriptions. //
2288 //===-------------===//
2289
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002290 class VISIBILITY_HIDDEN CFRefBug : public BugType {
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002291 protected:
2292 CFRefCount& TF;
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002293
2294 CFRefBug(CFRefCount* tf, const char* name)
2295 : BugType(name, "Memory (Core Foundation/Objective-C)"), TF(*tf) {}
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002296 public:
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002297
Ted Kremenek5c3407a2008-05-01 22:50:36 +00002298 CFRefCount& getTF() { return TF; }
Ted Kremenek0ff3f202008-05-05 23:16:31 +00002299 const CFRefCount& getTF() const { return TF; }
2300
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002301 // FIXME: Eventually remove.
2302 virtual const char* getDescription() const = 0;
2303
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002304 virtual bool isLeak() const { return false; }
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002305 };
2306
2307 class VISIBILITY_HIDDEN UseAfterRelease : public CFRefBug {
2308 public:
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002309 UseAfterRelease(CFRefCount* tf)
2310 : CFRefBug(tf, "use-after-release") {}
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002311
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002312 const char* getDescription() const {
Ted Kremenekef9d0a82009-02-26 21:04:07 +00002313 return "Reference-counted object is used after it is released";
Ted Kremenek708af042009-02-05 06:50:21 +00002314 }
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002315 };
2316
2317 class VISIBILITY_HIDDEN BadRelease : public CFRefBug {
2318 public:
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002319 BadRelease(CFRefCount* tf) : CFRefBug(tf, "bad release") {}
2320
2321 const char* getDescription() const {
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002322 return "Incorrect decrement of the reference count of a "
Ted Kremenekef9d0a82009-02-26 21:04:07 +00002323 "Core Foundation object ("
2324 "the object is not owned at this point by the caller)";
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002325 }
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002326 };
2327
Ted Kremenek6537a642009-03-17 19:42:23 +00002328 class VISIBILITY_HIDDEN DeallocGC : public CFRefBug {
2329 public:
2330 DeallocGC(CFRefCount *tf) : CFRefBug(tf,
2331 "-dealloc called while using GC") {}
2332
2333 const char *getDescription() const {
2334 return "-dealloc called while using GC";
2335 }
2336 };
2337
2338 class VISIBILITY_HIDDEN DeallocNotOwned : public CFRefBug {
2339 public:
2340 DeallocNotOwned(CFRefCount *tf) : CFRefBug(tf,
2341 "-dealloc sent to non-exclusively owned object") {}
2342
2343 const char *getDescription() const {
2344 return "-dealloc sent to object that may be referenced elsewhere";
2345 }
2346 };
2347
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002348 class VISIBILITY_HIDDEN Leak : public CFRefBug {
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002349 const bool isReturn;
2350 protected:
2351 Leak(CFRefCount* tf, const char* name, bool isRet)
2352 : CFRefBug(tf, name), isReturn(isRet) {}
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002353 public:
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002354
Ted Kremenek44274e62009-02-07 22:38:00 +00002355 const char* getDescription() const { return ""; }
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002356
Ted Kremenek538a3ba2009-02-05 00:38:00 +00002357 bool isLeak() const { return true; }
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002358 };
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002359
2360 class VISIBILITY_HIDDEN LeakAtReturn : public Leak {
2361 public:
2362 LeakAtReturn(CFRefCount* tf, const char* name)
2363 : Leak(tf, name, true) {}
2364 };
2365
2366 class VISIBILITY_HIDDEN LeakWithinFunction : public Leak {
2367 public:
2368 LeakWithinFunction(CFRefCount* tf, const char* name)
2369 : Leak(tf, name, false) {}
2370 };
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002371
2372 //===---------===//
2373 // Bug Reports. //
2374 //===---------===//
2375
2376 class VISIBILITY_HIDDEN CFRefReport : public RangedBugReport {
Ted Kremenek8ff05042009-02-07 22:04:05 +00002377 protected:
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002378 SymbolRef Sym;
Ted Kremenekc26c4692009-02-18 03:48:14 +00002379 const CFRefCount &TF;
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002380 public:
Ted Kremenekc26c4692009-02-18 03:48:14 +00002381 CFRefReport(CFRefBug& D, const CFRefCount &tf,
2382 ExplodedNode<GRState> *n, SymbolRef sym)
2383 : RangedBugReport(D, D.getDescription(), n), Sym(sym), TF(tf) {}
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002384
2385 virtual ~CFRefReport() {}
2386
Ted Kremenek5c3407a2008-05-01 22:50:36 +00002387 CFRefBug& getBugType() {
2388 return (CFRefBug&) RangedBugReport::getBugType();
2389 }
2390 const CFRefBug& getBugType() const {
2391 return (const CFRefBug&) RangedBugReport::getBugType();
2392 }
2393
2394 virtual void getRanges(BugReporter& BR, const SourceRange*& beg,
2395 const SourceRange*& end) {
2396
Ted Kremenek198cae02008-05-02 20:53:50 +00002397 if (!getBugType().isLeak())
Ted Kremenek5c3407a2008-05-01 22:50:36 +00002398 RangedBugReport::getRanges(BR, beg, end);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002399 else
2400 beg = end = 0;
Ted Kremenek5c3407a2008-05-01 22:50:36 +00002401 }
2402
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002403 SymbolRef getSymbol() const { return Sym; }
Ted Kremenekd7e26782008-05-16 18:33:44 +00002404
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002405 PathDiagnosticPiece* getEndPath(BugReporter& BR,
2406 const ExplodedNode<GRState>* N);
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002407
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002408 std::pair<const char**,const char**> getExtraDescriptiveText();
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002409
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002410 PathDiagnosticPiece* VisitNode(const ExplodedNode<GRState>* N,
2411 const ExplodedNode<GRState>* PrevN,
2412 const ExplodedGraph<GRState>& G,
Ted Kremenekc26c4692009-02-18 03:48:14 +00002413 BugReporter& BR,
2414 NodeResolver& NR);
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002415 };
2416
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002417 class VISIBILITY_HIDDEN CFRefLeakReport : public CFRefReport {
Ted Kremenek86617f42009-02-07 22:19:59 +00002418 SourceLocation AllocSite;
2419 const MemRegion* AllocBinding;
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002420 public:
Ted Kremenekc26c4692009-02-18 03:48:14 +00002421 CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2422 ExplodedNode<GRState> *n, SymbolRef sym,
Ted Kremenek44274e62009-02-07 22:38:00 +00002423 GRExprEngine& Eng);
Ted Kremenek8ff05042009-02-07 22:04:05 +00002424
2425 PathDiagnosticPiece* getEndPath(BugReporter& BR,
2426 const ExplodedNode<GRState>* N);
2427
Ted Kremenek86617f42009-02-07 22:19:59 +00002428 SourceLocation getLocation() const { return AllocSite; }
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002429 };
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002430} // end anonymous namespace
2431
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002432void CFRefCount::RegisterChecks(BugReporter& BR) {
Ted Kremenek708af042009-02-05 06:50:21 +00002433 useAfterRelease = new UseAfterRelease(this);
2434 BR.Register(useAfterRelease);
2435
2436 releaseNotOwned = new BadRelease(this);
2437 BR.Register(releaseNotOwned);
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002438
Ted Kremenek6537a642009-03-17 19:42:23 +00002439 deallocGC = new DeallocGC(this);
2440 BR.Register(deallocGC);
2441
2442 deallocNotOwned = new DeallocNotOwned(this);
2443 BR.Register(deallocNotOwned);
2444
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002445 // First register "return" leaks.
2446 const char* name = 0;
2447
2448 if (isGCEnabled())
Ted Kremenek50ee2142009-03-11 23:43:16 +00002449 name = "leak of returned object (GC)";
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002450 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2451 name = "[naming convention] leak of returned object (hybrid MM, "
2452 "non-GC)";
2453 else {
2454 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
Ted Kremenek50ee2142009-03-11 23:43:16 +00002455 name = "leak of returned object";
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002456 }
2457
Ted Kremenek708af042009-02-05 06:50:21 +00002458 leakAtReturn = new LeakAtReturn(this, name);
2459 BR.Register(leakAtReturn);
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002460
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002461 // Second, register leaks within a function/method.
2462 if (isGCEnabled())
2463 name = "leak (GC)";
2464 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2465 name = "leak (hybrid MM, non-GC)";
2466 else {
2467 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2468 name = "leak";
2469 }
2470
Ted Kremenek708af042009-02-05 06:50:21 +00002471 leakWithinFunction = new LeakWithinFunction(this, name);
2472 BR.Register(leakWithinFunction);
2473
2474 // Save the reference to the BugReporter.
2475 this->BR = &BR;
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002476}
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002477
2478static const char* Msgs[] = {
Ted Kremenekef9d0a82009-02-26 21:04:07 +00002479 // GC only
2480 "Code is compiled to only use garbage collection",
2481 // No GC.
Ted Kremeneka9203882009-03-05 00:12:45 +00002482 "Code is compiled to use reference counts",
Ted Kremenekef9d0a82009-02-26 21:04:07 +00002483 // Hybrid, with GC.
2484 "Code is compiled to use either garbage collection (GC) or reference counts"
2485 " (non-GC). The bug occurs with GC enabled",
2486 // Hybrid, without GC
2487 "Code is compiled to use either garbage collection (GC) or reference counts"
2488 " (non-GC). The bug occurs in non-GC mode"
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002489};
2490
2491std::pair<const char**,const char**> CFRefReport::getExtraDescriptiveText() {
2492 CFRefCount& TF = static_cast<CFRefBug&>(getBugType()).getTF();
2493
2494 switch (TF.getLangOptions().getGCMode()) {
2495 default:
2496 assert(false);
Ted Kremenekcb4709402008-05-01 04:02:04 +00002497
2498 case LangOptions::GCOnly:
2499 assert (TF.isGCEnabled());
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002500 return std::make_pair(&Msgs[0], &Msgs[0]+1);
2501
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002502 case LangOptions::NonGC:
2503 assert (!TF.isGCEnabled());
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002504 return std::make_pair(&Msgs[1], &Msgs[1]+1);
2505
2506 case LangOptions::HybridGC:
2507 if (TF.isGCEnabled())
2508 return std::make_pair(&Msgs[2], &Msgs[2]+1);
2509 else
2510 return std::make_pair(&Msgs[3], &Msgs[3]+1);
2511 }
2512}
2513
Ted Kremenek2126bef2009-02-18 21:57:45 +00002514static inline bool contains(const llvm::SmallVectorImpl<ArgEffect>& V,
2515 ArgEffect X) {
2516 for (llvm::SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
2517 I!=E; ++I)
2518 if (*I == X) return true;
2519
2520 return false;
2521}
2522
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002523PathDiagnosticPiece* CFRefReport::VisitNode(const ExplodedNode<GRState>* N,
2524 const ExplodedNode<GRState>* PrevN,
2525 const ExplodedGraph<GRState>& G,
Ted Kremenekc26c4692009-02-18 03:48:14 +00002526 BugReporter& BR,
2527 NodeResolver& NR) {
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002528
Ted Kremenek71745d92009-01-28 05:29:13 +00002529 // Check if the type state has changed.
2530 GRStateManager &StMgr = cast<GRBugReporter>(BR).getStateManager();
2531 GRStateRef PrevSt(PrevN->getState(), StMgr);
2532 GRStateRef CurrSt(N->getState(), StMgr);
Ted Kremenek335a3022009-01-28 05:06:46 +00002533
Ted Kremenek71745d92009-01-28 05:29:13 +00002534 const RefVal* CurrT = CurrSt.get<RefBindings>(Sym);
2535 if (!CurrT) return NULL;
2536
2537 const RefVal& CurrV = *CurrT;
2538 const RefVal* PrevT = PrevSt.get<RefBindings>(Sym);
Ted Kremenek9363fd92008-05-05 17:53:17 +00002539
Ted Kremenek2126bef2009-02-18 21:57:45 +00002540 // Create a string buffer to constain all the useful things we want
2541 // to tell the user.
2542 std::string sbuf;
2543 llvm::raw_string_ostream os(sbuf);
2544
Ted Kremenekc26c4692009-02-18 03:48:14 +00002545 // This is the allocation site since the previous node had no bindings
2546 // for this symbol.
Ted Kremeneka8503952008-04-18 04:55:01 +00002547 if (!PrevT) {
Ted Kremenek9363fd92008-05-05 17:53:17 +00002548 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2549
Ted Kremenek2e2b1332009-01-28 05:15:02 +00002550 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2551 // Get the name of the callee (if it is available).
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002552 SVal X = CurrSt.GetSValAsScalarOrLoc(CE->getCallee());
Ted Kremenek2e2b1332009-01-28 05:15:02 +00002553 if (loc::FuncVal* FV = dyn_cast<loc::FuncVal>(&X))
2554 os << "Call to function '" << FV->getDecl()->getNameAsString() <<'\'';
2555 else
Ted Kremenekb4bf8cf2009-01-28 06:01:42 +00002556 os << "function call";
Ted Kremenek2e2b1332009-01-28 05:15:02 +00002557 }
2558 else {
2559 assert (isa<ObjCMessageExpr>(S));
Ted Kremenekb4bf8cf2009-01-28 06:01:42 +00002560 os << "Method";
Ted Kremenek9363fd92008-05-05 17:53:17 +00002561 }
Ted Kremenek2e2b1332009-01-28 05:15:02 +00002562
Ted Kremenek18878b12009-01-28 06:06:36 +00002563 if (CurrV.getObjKind() == RetEffect::CF) {
2564 os << " returns a Core Foundation object with a ";
2565 }
2566 else {
2567 assert (CurrV.getObjKind() == RetEffect::ObjC);
2568 os << " returns an Objective-C object with a ";
2569 }
Ted Kremenekb4bf8cf2009-01-28 06:01:42 +00002570
Ted Kremenekabe30922009-01-28 06:25:48 +00002571 if (CurrV.isOwned()) {
2572 os << "+1 retain count (owning reference).";
2573
2574 if (static_cast<CFRefBug&>(getBugType()).getTF().isGCEnabled()) {
2575 assert(CurrV.getObjKind() == RetEffect::CF);
2576 os << " "
2577 "Core Foundation objects are not automatically garbage collected.";
2578 }
2579 }
Ted Kremeneka8503952008-04-18 04:55:01 +00002580 else {
2581 assert (CurrV.isNotOwned());
Ted Kremenek2e2b1332009-01-28 05:15:02 +00002582 os << "+0 retain count (non-owning reference).";
Ted Kremeneka8503952008-04-18 04:55:01 +00002583 }
Ted Kremenek9363fd92008-05-05 17:53:17 +00002584
Ted Kremeneka8503952008-04-18 04:55:01 +00002585 FullSourceLoc Pos(S->getLocStart(), BR.getContext().getSourceManager());
Ted Kremenek23563642009-03-06 23:58:11 +00002586 PathDiagnosticPiece* P = new PathDiagnosticEventPiece(Pos, os.str());
Ted Kremeneka8503952008-04-18 04:55:01 +00002587
2588 if (Expr* Exp = dyn_cast<Expr>(S))
2589 P->addRange(Exp->getSourceRange());
2590
2591 return P;
2592 }
Ted Kremeneka8503952008-04-18 04:55:01 +00002593
Ted Kremenek2126bef2009-02-18 21:57:45 +00002594 // Gather up the effects that were performed on the object at this
2595 // program point
2596 llvm::SmallVector<ArgEffect, 2> AEffects;
2597
Ted Kremenekc26c4692009-02-18 03:48:14 +00002598 if (const RetainSummary *Summ = TF.getSummaryOfNode(NR.getOriginalNode(N))) {
2599 // We only have summaries attached to nodes after evaluating CallExpr and
2600 // ObjCMessageExprs.
2601 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2602
Ted Kremenekc26c4692009-02-18 03:48:14 +00002603 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2604 // Iterate through the parameter expressions and see if the symbol
2605 // was ever passed as an argument.
2606 unsigned i = 0;
2607
2608 for (CallExpr::arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
2609 AI!=AE; ++AI, ++i) {
Ted Kremenek2126bef2009-02-18 21:57:45 +00002610
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002611 // Retrieve the value of the argument. Is it the symbol
2612 // we are interested in?
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002613 if (CurrSt.GetSValAsScalarOrLoc(*AI).getAsLocSymbol() != Sym)
Ted Kremenekc26c4692009-02-18 03:48:14 +00002614 continue;
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002615
Ted Kremenekc26c4692009-02-18 03:48:14 +00002616 // We have an argument. Get the effect!
2617 AEffects.push_back(Summ->getArg(i));
Ted Kremenek752b5842008-04-18 05:32:44 +00002618 }
Ted Kremenekc26c4692009-02-18 03:48:14 +00002619 }
2620 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002621 if (Expr *receiver = ME->getReceiver())
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002622 if (CurrSt.GetSValAsScalarOrLoc(receiver).getAsLocSymbol() == Sym) {
Ted Kremenek2126bef2009-02-18 21:57:45 +00002623 // The symbol we are tracking is the receiver.
2624 AEffects.push_back(Summ->getReceiverEffect());
2625 }
Ted Kremenekc26c4692009-02-18 03:48:14 +00002626 }
Ted Kremeneka8503952008-04-18 04:55:01 +00002627 }
Ted Kremenekc26c4692009-02-18 03:48:14 +00002628
Ted Kremenek2126bef2009-02-18 21:57:45 +00002629 do {
2630 // Get the previous type state.
2631 RefVal PrevV = *PrevT;
Ted Kremenek6537a642009-03-17 19:42:23 +00002632
2633 // Specially handle -dealloc.
2634 if (!TF.isGCEnabled() && contains(AEffects, Dealloc)) {
2635 // Determine if the object's reference count was pushed to zero.
2636 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2637 // We may not have transitioned to 'release' if we hit an error.
2638 // This case is handled elsewhere.
2639 if (CurrV.getKind() == RefVal::Released) {
2640 assert(CurrV.getCount() == 0);
2641 os << "Object released by directly sending the '-dealloc' message";
2642 break;
2643 }
2644 }
Ted Kremenek2126bef2009-02-18 21:57:45 +00002645
2646 // Specially handle CFMakeCollectable and friends.
2647 if (contains(AEffects, MakeCollectable)) {
2648 // Get the name of the function.
2649 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2650 loc::FuncVal FV =
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002651 cast<loc::FuncVal>(CurrSt.GetSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee()));
Ted Kremenek2126bef2009-02-18 21:57:45 +00002652 const std::string& FName = FV.getDecl()->getNameAsString();
2653
2654 if (TF.isGCEnabled()) {
2655 // Determine if the object's reference count was pushed to zero.
2656 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2657
2658 os << "In GC mode a call to '" << FName
2659 << "' decrements an object's retain count and registers the "
2660 "object with the garbage collector. ";
2661
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00002662 if (CurrV.getKind() == RefVal::Released) {
2663 assert(CurrV.getCount() == 0);
2664 os << "Since it now has a 0 retain count the object can be "
Ted Kremenek2126bef2009-02-18 21:57:45 +00002665 "automatically collected by the garbage collector.";
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00002666 }
Ted Kremenek2126bef2009-02-18 21:57:45 +00002667 else
2668 os << "An object must have a 0 retain count to be garbage collected. "
2669 "After this call its retain count is +" << CurrV.getCount()
2670 << '.';
2671 }
2672 else
2673 os << "When GC is not enabled a call to '" << FName
2674 << "' has no effect on its argument.";
2675
2676 // Nothing more to say.
2677 break;
2678 }
2679
2680 // Determine if the typestate has changed.
2681 if (!(PrevV == CurrV))
2682 switch (CurrV.getKind()) {
Ted Kremenekc26c4692009-02-18 03:48:14 +00002683 case RefVal::Owned:
2684 case RefVal::NotOwned:
2685
2686 if (PrevV.getCount() == CurrV.getCount())
2687 return 0;
2688
2689 if (PrevV.getCount() > CurrV.getCount())
2690 os << "Reference count decremented.";
2691 else
2692 os << "Reference count incremented.";
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00002693
Ted Kremenekef9d0a82009-02-26 21:04:07 +00002694 if (unsigned Count = CurrV.getCount())
2695 os << " The object now has a +" << Count << " retain count.";
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00002696
2697 if (PrevV.getKind() == RefVal::Released) {
2698 assert(TF.isGCEnabled() && CurrV.getCount() > 0);
2699 os << " The object is not eligible for garbage collection until the "
2700 "retain count reaches 0 again.";
2701 }
2702
Ted Kremenekc26c4692009-02-18 03:48:14 +00002703 break;
2704
2705 case RefVal::Released:
2706 os << "Object released.";
2707 break;
2708
2709 case RefVal::ReturnedOwned:
2710 os << "Object returned to caller as an owning reference (single retain "
2711 "count transferred to caller).";
2712 break;
2713
2714 case RefVal::ReturnedNotOwned:
2715 os << "Object returned to caller with a +0 (non-owning) retain count.";
2716 break;
2717
2718 default:
2719 return NULL;
Ted Kremenek2126bef2009-02-18 21:57:45 +00002720 }
2721
2722 // Emit any remaining diagnostics for the argument effects (if any).
2723 for (llvm::SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
2724 E=AEffects.end(); I != E; ++I) {
2725
2726 // A bunch of things have alternate behavior under GC.
2727 if (TF.isGCEnabled())
2728 switch (*I) {
2729 default: break;
2730 case Autorelease:
2731 os << "In GC mode an 'autorelease' has no effect.";
2732 continue;
2733 case IncRefMsg:
2734 os << "In GC mode the 'retain' message has no effect.";
2735 continue;
2736 case DecRefMsg:
2737 os << "In GC mode the 'release' message has no effect.";
2738 continue;
2739 }
Ted Kremenekc26c4692009-02-18 03:48:14 +00002740 }
Ted Kremenek2126bef2009-02-18 21:57:45 +00002741 } while(0);
Ted Kremenekc26c4692009-02-18 03:48:14 +00002742
2743 if (os.str().empty())
2744 return 0; // We have nothing to say!
Ted Kremeneka8503952008-04-18 04:55:01 +00002745
2746 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2747 FullSourceLoc Pos(S->getLocStart(), BR.getContext().getSourceManager());
Ted Kremenek23563642009-03-06 23:58:11 +00002748 PathDiagnosticPiece* P = new PathDiagnosticEventPiece(Pos, os.str());
Ted Kremeneka8503952008-04-18 04:55:01 +00002749
2750 // Add the range by scanning the children of the statement for any bindings
2751 // to Sym.
Ted Kremeneka8503952008-04-18 04:55:01 +00002752 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I)
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002753 if (Expr* Exp = dyn_cast_or_null<Expr>(*I))
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002754 if (CurrSt.GetSValAsScalarOrLoc(Exp).getAsLocSymbol() == Sym) {
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002755 P->addRange(Exp->getSourceRange());
2756 break;
2757 }
Ted Kremeneka8503952008-04-18 04:55:01 +00002758
2759 return P;
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002760}
2761
Ted Kremenekb15eba42008-10-04 05:50:14 +00002762namespace {
2763class VISIBILITY_HIDDEN FindUniqueBinding :
2764 public StoreManager::BindingsHandler {
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002765 SymbolRef Sym;
Ted Kremenekb6b0bb82009-03-05 16:31:07 +00002766 const MemRegion* Binding;
Ted Kremenekb15eba42008-10-04 05:50:14 +00002767 bool First;
2768
2769 public:
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002770 FindUniqueBinding(SymbolRef sym) : Sym(sym), Binding(0), First(true) {}
Ted Kremenekb15eba42008-10-04 05:50:14 +00002771
Ted Kremenekb6b0bb82009-03-05 16:31:07 +00002772 bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
2773 SVal val) {
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002774 SymbolRef SymV = val.getAsSymbol();
2775
2776 if (!SymV.isValid() || SymV != Sym)
Ted Kremenekb15eba42008-10-04 05:50:14 +00002777 return true;
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002778
Ted Kremenekb15eba42008-10-04 05:50:14 +00002779 if (Binding) {
2780 First = false;
2781 return false;
2782 }
2783 else
2784 Binding = R;
2785
2786 return true;
2787 }
2788
2789 operator bool() { return First && Binding; }
Ted Kremenekb6b0bb82009-03-05 16:31:07 +00002790 const MemRegion* getRegion() { return Binding; }
Ted Kremenekb15eba42008-10-04 05:50:14 +00002791};
2792}
2793
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002794static std::pair<const ExplodedNode<GRState>*,const MemRegion*>
Ted Kremenek86617f42009-02-07 22:19:59 +00002795GetAllocationSite(GRStateManager& StateMgr, const ExplodedNode<GRState>* N,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002796 SymbolRef Sym) {
Ted Kremenekd7e26782008-05-16 18:33:44 +00002797
Ted Kremenekbe9b6f72008-08-29 00:47:32 +00002798 // Find both first node that referred to the tracked symbol and the
2799 // memory location that value was store to.
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002800 const ExplodedNode<GRState>* Last = N;
2801 const MemRegion* FirstBinding = 0;
Ted Kremenekd7e26782008-05-16 18:33:44 +00002802
2803 while (N) {
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002804 const GRState* St = N->getState();
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002805 RefBindings B = St->get<RefBindings>();
Ted Kremenekd7e26782008-05-16 18:33:44 +00002806
Ted Kremenek6064a362008-07-07 16:21:19 +00002807 if (!B.lookup(Sym))
Ted Kremenekd7e26782008-05-16 18:33:44 +00002808 break;
Ted Kremenekbe9b6f72008-08-29 00:47:32 +00002809
Ted Kremenek86617f42009-02-07 22:19:59 +00002810 FindUniqueBinding FB(Sym);
2811 StateMgr.iterBindings(St, FB);
2812 if (FB) FirstBinding = FB.getRegion();
Ted Kremenekd7e26782008-05-16 18:33:44 +00002813
Ted Kremenekd7e26782008-05-16 18:33:44 +00002814 Last = N;
2815 N = N->pred_empty() ? NULL : *(N->pred_begin());
2816 }
2817
Ted Kremenekbe9b6f72008-08-29 00:47:32 +00002818 return std::make_pair(Last, FirstBinding);
Ted Kremenekd7e26782008-05-16 18:33:44 +00002819}
Ted Kremenek4c479322008-05-06 23:07:13 +00002820
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002821PathDiagnosticPiece*
2822CFRefReport::getEndPath(BugReporter& br, const ExplodedNode<GRState>* EndN) {
Ted Kremenek86953652008-05-22 23:45:19 +00002823 // Tell the BugReporter to report cases when the tracked symbol is
2824 // assigned to different variables, etc.
Ted Kremenek6537a642009-03-17 19:42:23 +00002825 GRBugReporter& BR = cast<GRBugReporter>(br);
Ted Kremenekba1c7ed2008-07-02 21:24:01 +00002826 cast<GRBugReporter>(BR).addNotableSymbol(Sym);
Ted Kremenek8ff05042009-02-07 22:04:05 +00002827 return RangedBugReport::getEndPath(BR, EndN);
2828}
2829
2830PathDiagnosticPiece*
2831CFRefLeakReport::getEndPath(BugReporter& br, const ExplodedNode<GRState>* EndN){
2832
2833 GRBugReporter& BR = cast<GRBugReporter>(br);
2834 // Tell the BugReporter to report cases when the tracked symbol is
2835 // assigned to different variables, etc.
2836 cast<GRBugReporter>(BR).addNotableSymbol(Sym);
2837
2838 // We are reporting a leak. Walk up the graph to get to the first node where
2839 // the symbol appeared, and also get the first VarDecl that tracked object
Ted Kremenekd7e26782008-05-16 18:33:44 +00002840 // is stored to.
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002841 const ExplodedNode<GRState>* AllocNode = 0;
2842 const MemRegion* FirstBinding = 0;
Ted Kremenekbe9b6f72008-08-29 00:47:32 +00002843
2844 llvm::tie(AllocNode, FirstBinding) =
Ted Kremenek86617f42009-02-07 22:19:59 +00002845 GetAllocationSite(BR.getStateManager(), EndN, Sym);
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002846
Ted Kremenekd7e26782008-05-16 18:33:44 +00002847 // Get the allocate site.
2848 assert (AllocNode);
2849 Stmt* FirstStmt = cast<PostStmt>(AllocNode->getLocation()).getStmt();
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002850
Ted Kremenekea794e92008-05-05 18:50:19 +00002851 SourceManager& SMgr = BR.getContext().getSourceManager();
Chris Lattner18c8dc02009-01-16 07:36:28 +00002852 unsigned AllocLine =SMgr.getInstantiationLineNumber(FirstStmt->getLocStart());
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002853
Ted Kremeneke0336742009-02-18 23:28:26 +00002854 // Get the leak site. We want to find the last place where the symbol
2855 // was used in an expression.
2856 const ExplodedNode<GRState>* LeakN = EndN;
2857 Stmt *S = 0;
Ted Kremenekea794e92008-05-05 18:50:19 +00002858
Ted Kremeneke0336742009-02-18 23:28:26 +00002859 while (LeakN) {
Ted Kremenek914fc7c2009-02-24 23:30:57 +00002860 bool atBranch = false;
Ted Kremeneke0336742009-02-18 23:28:26 +00002861 ProgramPoint P = LeakN->getLocation();
Ted Kremeneke0336742009-02-18 23:28:26 +00002862
2863 if (const PostStmt *PS = dyn_cast<PostStmt>(&P))
2864 S = PS->getStmt();
Ted Kremenek914fc7c2009-02-24 23:30:57 +00002865 else if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
2866 // FIXME: What we really want is to set LeakN to be the node
2867 // for the BlockEntrance for the branch we took and have BugReporter
2868 // do the right thing.
Ted Kremeneke0336742009-02-18 23:28:26 +00002869 S = BE->getSrc()->getTerminator();
Ted Kremeneka1e39992009-02-24 23:34:17 +00002870 atBranch = (S != 0);
Ted Kremenek914fc7c2009-02-24 23:30:57 +00002871 }
Ted Kremeneke0336742009-02-18 23:28:26 +00002872
2873 if (S) {
2874 // Scan 'S' for uses of Sym.
2875 GRStateRef state(LeakN->getState(), BR.getStateManager());
2876 bool foundSymbol = false;
Ted Kremenek83ec2f92009-02-19 18:18:48 +00002877
2878 // First check if 'S' itself binds to the symbol.
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002879 if (Expr *Ex = dyn_cast<Expr>(S))
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002880 if (state.GetSValAsScalarOrLoc(Ex).getAsLocSymbol() == Sym)
Ted Kremenek83ec2f92009-02-19 18:18:48 +00002881 foundSymbol = true;
Ted Kremenek83ec2f92009-02-19 18:18:48 +00002882
2883 if (!foundSymbol)
2884 for (Stmt::child_iterator I=S->child_begin(), E=S->child_end();
2885 I!=E; ++I)
2886 if (Expr *Ex = dyn_cast_or_null<Expr>(*I)) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002887 SVal X = state.GetSValAsScalarOrLoc(Ex);
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002888 if (X.getAsLocSymbol() == Sym) {
Ted Kremenek83ec2f92009-02-19 18:18:48 +00002889 foundSymbol = true;
2890 break;
2891 }
Ted Kremeneke0336742009-02-18 23:28:26 +00002892 }
Ted Kremenek83ec2f92009-02-19 18:18:48 +00002893
Ted Kremeneke0336742009-02-18 23:28:26 +00002894 if (foundSymbol)
2895 break;
2896 }
2897
Ted Kremenek914fc7c2009-02-24 23:30:57 +00002898 // Don't traverse any higher than the branch.
2899 if (atBranch)
2900 break;
2901
Ted Kremeneke0336742009-02-18 23:28:26 +00002902 LeakN = LeakN->pred_empty() ? 0 : *(LeakN->pred_begin());
2903 }
2904
2905 assert(LeakN && S && "No leak site found.");
Ted Kremenekea794e92008-05-05 18:50:19 +00002906
Ted Kremenekea794e92008-05-05 18:50:19 +00002907 // Generate the diagnostic.
Ted Kremenek323207b2009-02-18 22:59:04 +00002908 FullSourceLoc L(S->getLocStart(), SMgr);
Ted Kremenek59f9fe12009-02-07 21:59:45 +00002909 std::string sbuf;
2910 llvm::raw_string_ostream os(sbuf);
Ted Kremenek198cae02008-05-02 20:53:50 +00002911
Ted Kremenekea794e92008-05-05 18:50:19 +00002912 os << "Object allocated on line " << AllocLine;
Ted Kremenek198cae02008-05-02 20:53:50 +00002913
Ted Kremenekbe9b6f72008-08-29 00:47:32 +00002914 if (FirstBinding)
Ted Kremenekb15eba42008-10-04 05:50:14 +00002915 os << " and stored into '" << FirstBinding->getString() << '\'';
2916
Ted Kremenek311f3d42008-10-22 23:56:21 +00002917 // Get the retain count.
2918 const RefVal* RV = EndN->getState()->get<RefBindings>(Sym);
2919
2920 if (RV->getKind() == RefVal::ErrorLeakReturned) {
Ted Kremenekf9544fe2008-12-02 01:26:07 +00002921 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
2922 // ojbects. Only "copy", "alloc", "retain" and "new" transfer ownership
2923 // to the caller for NS objects.
Ted Kremenek311f3d42008-10-22 23:56:21 +00002924 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(BR.getGraph().getCodeDecl());
2925 os << " is returned from a method whose name ('"
Chris Lattner3a8f2942008-11-24 03:33:13 +00002926 << MD.getSelector().getAsString()
Ted Kremenek35920ed2009-01-07 00:39:56 +00002927 << "') does not contain 'copy' or otherwise starts with"
Ted Kremeneka05446c2008-10-24 21:22:44 +00002928 " 'new' or 'alloc'. This violates the naming convention rules given"
Ted Kremenek311f3d42008-10-22 23:56:21 +00002929 " in the Memory Management Guide for Cocoa (object leaked).";
2930 }
2931 else
Ted Kremeneka05446c2008-10-24 21:22:44 +00002932 os << " is no longer referenced after this point and has a retain count of"
2933 " +"
Ted Kremenek311f3d42008-10-22 23:56:21 +00002934 << RV->getCount() << " (object leaked).";
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002935
Ted Kremenek23563642009-03-06 23:58:11 +00002936 return new PathDiagnosticEventPiece(L, os.str());
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002937}
2938
Ted Kremenek7f3f41a2008-04-17 23:43:50 +00002939
Ted Kremenekc26c4692009-02-18 03:48:14 +00002940CFRefLeakReport::CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2941 ExplodedNode<GRState> *n,
Ted Kremenek44274e62009-02-07 22:38:00 +00002942 SymbolRef sym, GRExprEngine& Eng)
Ted Kremenekc26c4692009-02-18 03:48:14 +00002943 : CFRefReport(D, tf, n, sym)
Ted Kremenek86617f42009-02-07 22:19:59 +00002944{
2945
Ted Kremenekd7e26782008-05-16 18:33:44 +00002946 // Most bug reports are cached at the location where they occured.
2947 // With leaks, we want to unique them by the location where they were
Ted Kremenek86617f42009-02-07 22:19:59 +00002948 // allocated, and only report a single path. To do this, we need to find
2949 // the allocation site of a piece of tracked memory, which we do via a
2950 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2951 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2952 // that all ancestor nodes that represent the allocation site have the
2953 // same SourceLocation.
2954 const ExplodedNode<GRState>* AllocNode = 0;
2955
2956 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding.
Ted Kremenek44274e62009-02-07 22:38:00 +00002957 GetAllocationSite(Eng.getStateManager(), getEndNode(), getSymbol());
Ted Kremenek86617f42009-02-07 22:19:59 +00002958
Ted Kremenek86617f42009-02-07 22:19:59 +00002959 // Get the SourceLocation for the allocation site.
Ted Kremenek44274e62009-02-07 22:38:00 +00002960 ProgramPoint P = AllocNode->getLocation();
Ted Kremenek86617f42009-02-07 22:19:59 +00002961 AllocSite = cast<PostStmt>(P).getStmt()->getLocStart();
Ted Kremenek44274e62009-02-07 22:38:00 +00002962
2963 // Fill in the description of the bug.
2964 Description.clear();
2965 llvm::raw_string_ostream os(Description);
2966 SourceManager& SMgr = Eng.getContext().getSourceManager();
2967 unsigned AllocLine = SMgr.getInstantiationLineNumber(AllocSite);
Ted Kremenek91f51ce2009-02-07 22:54:59 +00002968 os << "Potential leak of object allocated on line " << AllocLine;
2969
2970 // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2971 if (AllocBinding)
2972 os << " and store into '" << AllocBinding->getString() << '\'';
Ted Kremenekd7e26782008-05-16 18:33:44 +00002973}
2974
Ted Kremeneka7338b42008-03-11 06:39:11 +00002975//===----------------------------------------------------------------------===//
Ted Kremenek708af042009-02-05 06:50:21 +00002976// Handle dead symbols and end-of-path.
2977//===----------------------------------------------------------------------===//
2978
2979void CFRefCount::EvalEndPath(GRExprEngine& Eng,
2980 GREndPathNodeBuilder<GRState>& Builder) {
2981
2982 const GRState* St = Builder.getState();
2983 RefBindings B = St->get<RefBindings>();
2984
2985 llvm::SmallVector<std::pair<SymbolRef, bool>, 10> Leaked;
2986 const Decl* CodeDecl = &Eng.getGraph().getCodeDecl();
2987
2988 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
2989 bool hasLeak = false;
2990
2991 std::pair<GRStateRef, bool> X =
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002992 HandleSymbolDeath(Eng.getStateManager(), St, CodeDecl,
2993 (*I).first, (*I).second, hasLeak);
Ted Kremenek708af042009-02-05 06:50:21 +00002994
2995 St = X.first;
2996 if (hasLeak) Leaked.push_back(std::make_pair((*I).first, X.second));
2997 }
2998
2999 if (Leaked.empty())
3000 return;
3001
3002 ExplodedNode<GRState>* N = Builder.MakeNode(St);
3003
3004 if (!N)
3005 return;
3006
3007 for (llvm::SmallVector<std::pair<SymbolRef,bool>, 10>::iterator
3008 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3009
3010 CFRefBug *BT = static_cast<CFRefBug*>(I->second ? leakAtReturn
3011 : leakWithinFunction);
3012 assert(BT && "BugType not initialized.");
Ted Kremenekc26c4692009-02-18 03:48:14 +00003013 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N, I->first, Eng);
Ted Kremenek708af042009-02-05 06:50:21 +00003014 BR->EmitReport(report);
3015 }
3016}
3017
3018void CFRefCount::EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
3019 GRExprEngine& Eng,
3020 GRStmtNodeBuilder<GRState>& Builder,
3021 ExplodedNode<GRState>* Pred,
3022 Stmt* S,
3023 const GRState* St,
3024 SymbolReaper& SymReaper) {
3025
Ted Kremenek876d8df2009-02-19 23:47:02 +00003026 // FIXME: a lot of copy-and-paste from EvalEndPath. Refactor.
Ted Kremenek708af042009-02-05 06:50:21 +00003027 RefBindings B = St->get<RefBindings>();
3028 llvm::SmallVector<std::pair<SymbolRef,bool>, 10> Leaked;
3029
3030 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3031 E = SymReaper.dead_end(); I != E; ++I) {
3032
3033 const RefVal* T = B.lookup(*I);
3034 if (!T) continue;
3035
3036 bool hasLeak = false;
3037
3038 std::pair<GRStateRef, bool> X
Ted Kremenek876d8df2009-02-19 23:47:02 +00003039 = HandleSymbolDeath(Eng.getStateManager(), St, 0, *I, *T, hasLeak);
Ted Kremenek708af042009-02-05 06:50:21 +00003040
3041 St = X.first;
3042
3043 if (hasLeak)
3044 Leaked.push_back(std::make_pair(*I,X.second));
3045 }
3046
Ted Kremenek876d8df2009-02-19 23:47:02 +00003047 if (!Leaked.empty()) {
3048 // Create a new intermediate node representing the leak point. We
3049 // use a special program point that represents this checker-specific
3050 // transition. We use the address of RefBIndex as a unique tag for this
3051 // checker. We will create another node (if we don't cache out) that
3052 // removes the retain-count bindings from the state.
3053 // NOTE: We use 'generateNode' so that it does interplay with the
3054 // auto-transition logic.
3055 ExplodedNode<GRState>* N =
3056 Builder.generateNode(PostStmtCustom(S, &LeakProgramPointTag), St, Pred);
Ted Kremenek708af042009-02-05 06:50:21 +00003057
Ted Kremenek876d8df2009-02-19 23:47:02 +00003058 if (!N)
3059 return;
3060
3061 // Generate the bug reports.
3062 for (llvm::SmallVectorImpl<std::pair<SymbolRef,bool> >::iterator
3063 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3064
3065 CFRefBug *BT = static_cast<CFRefBug*>(I->second ? leakAtReturn
3066 : leakWithinFunction);
3067 assert(BT && "BugType not initialized.");
Ted Kremenek56c70aa2009-02-23 16:54:00 +00003068 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N,
3069 I->first, Eng);
Ted Kremenek876d8df2009-02-19 23:47:02 +00003070 BR->EmitReport(report);
3071 }
Ted Kremenek708af042009-02-05 06:50:21 +00003072
Ted Kremenek876d8df2009-02-19 23:47:02 +00003073 Pred = N;
Ted Kremenek708af042009-02-05 06:50:21 +00003074 }
Ted Kremenek876d8df2009-02-19 23:47:02 +00003075
3076 // Now generate a new node that nukes the old bindings.
3077 GRStateRef state(St, Eng.getStateManager());
3078 RefBindings::Factory& F = state.get_context<RefBindings>();
3079
3080 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3081 E = SymReaper.dead_end(); I!=E; ++I)
3082 B = F.Remove(B, *I);
3083
3084 state = state.set<RefBindings>(B);
3085 Builder.MakeNode(Dst, S, Pred, state);
Ted Kremenek708af042009-02-05 06:50:21 +00003086}
3087
3088void CFRefCount::ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
3089 GRStmtNodeBuilder<GRState>& Builder,
3090 Expr* NodeExpr, Expr* ErrorExpr,
3091 ExplodedNode<GRState>* Pred,
3092 const GRState* St,
3093 RefVal::Kind hasErr, SymbolRef Sym) {
3094 Builder.BuildSinks = true;
3095 GRExprEngine::NodeTy* N = Builder.MakeNode(Dst, NodeExpr, Pred, St);
3096
3097 if (!N) return;
3098
3099 CFRefBug *BT = 0;
3100
Ted Kremenek6537a642009-03-17 19:42:23 +00003101 switch (hasErr) {
3102 default:
3103 assert(false && "Unhandled error.");
3104 return;
3105 case RefVal::ErrorUseAfterRelease:
3106 BT = static_cast<CFRefBug*>(useAfterRelease);
3107 break;
3108 case RefVal::ErrorReleaseNotOwned:
3109 BT = static_cast<CFRefBug*>(releaseNotOwned);
3110 break;
3111 case RefVal::ErrorDeallocGC:
3112 BT = static_cast<CFRefBug*>(deallocGC);
3113 break;
3114 case RefVal::ErrorDeallocNotOwned:
3115 BT = static_cast<CFRefBug*>(deallocNotOwned);
3116 break;
Ted Kremenek708af042009-02-05 06:50:21 +00003117 }
3118
Ted Kremenekc26c4692009-02-18 03:48:14 +00003119 CFRefReport *report = new CFRefReport(*BT, *this, N, Sym);
Ted Kremenek708af042009-02-05 06:50:21 +00003120 report->addRange(ErrorExpr->getSourceRange());
3121 BR->EmitReport(report);
3122}
3123
3124//===----------------------------------------------------------------------===//
Ted Kremenekb1983ba2008-04-10 22:16:52 +00003125// Transfer function creation for external clients.
Ted Kremeneka7338b42008-03-11 06:39:11 +00003126//===----------------------------------------------------------------------===//
3127
Ted Kremenekfe30beb2008-04-30 23:47:44 +00003128GRTransferFuncs* clang::MakeCFRefCountTF(ASTContext& Ctx, bool GCEnabled,
3129 const LangOptions& lopts) {
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00003130 return new CFRefCount(Ctx, GCEnabled, lopts);
Ted Kremeneka4c74292008-04-10 22:58:08 +00003131}