blob: 81017211a6008881bb2563edc4b4f9624d393552 [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,
Ted Kremenek382fb4e2009-04-27 19:14:45 +0000250 NotOwnedSymbol, GCNotOwnedSymbol, ReceiverAlias };
Ted Kremenek68621b92009-01-28 05:56:51 +0000251
252 enum ObjKind { CF, ObjC, AnyObj };
253
Ted Kremeneka7338b42008-03-11 06:39:11 +0000254private:
Ted Kremenek68621b92009-01-28 05:56:51 +0000255 Kind K;
256 ObjKind O;
257 unsigned index;
258
259 RetEffect(Kind k, unsigned idx = 0) : K(k), O(AnyObj), index(idx) {}
260 RetEffect(Kind k, ObjKind o) : K(k), O(o), index(0) {}
Ted Kremenek827f93b2008-03-06 00:08:09 +0000261
Ted Kremeneka7338b42008-03-11 06:39:11 +0000262public:
Ted Kremenek68621b92009-01-28 05:56:51 +0000263 Kind getKind() const { return K; }
264
265 ObjKind getObjKind() const { return O; }
Ted Kremenek272aa852008-06-25 21:21:56 +0000266
267 unsigned getIndex() const {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000268 assert(getKind() == Alias);
Ted Kremenek68621b92009-01-28 05:56:51 +0000269 return index;
Ted Kremeneka7338b42008-03-11 06:39:11 +0000270 }
Ted Kremenek827f93b2008-03-06 00:08:09 +0000271
Ted 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 Kremenek382fb4e2009-04-27 19:14:45 +0000283 }
284 static RetEffect MakeGCNotOwned() {
285 return RetEffect(GCNotOwnedSymbol, ObjC);
286 }
287
Ted Kremenek272aa852008-06-25 21:21:56 +0000288 static RetEffect MakeNoRet() {
289 return RetEffect(NoRet);
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000290 }
Ted Kremenek827f93b2008-03-06 00:08:09 +0000291
Ted Kremenek272aa852008-06-25 21:21:56 +0000292 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek68621b92009-01-28 05:56:51 +0000293 ID.AddInteger((unsigned)K);
294 ID.AddInteger((unsigned)O);
295 ID.AddInteger(index);
Ted Kremenek272aa852008-06-25 21:21:56 +0000296 }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000297};
Ted Kremeneka7338b42008-03-11 06:39:11 +0000298
Ted Kremenek272aa852008-06-25 21:21:56 +0000299
300class VISIBILITY_HIDDEN RetainSummary : public llvm::FoldingSetNode {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000301 /// Args - an ordered vector of (index, ArgEffect) pairs, where index
302 /// specifies the argument (starting from 0). This can be sparsely
303 /// populated; arguments with no entry in Args use 'DefaultArgEffect'.
Ted Kremeneka7338b42008-03-11 06:39:11 +0000304 ArgEffects* Args;
Ted Kremenekbcaff792008-05-06 15:44:25 +0000305
306 /// DefaultArgEffect - The default ArgEffect to apply to arguments that
307 /// do not have an entry in Args.
308 ArgEffect DefaultArgEffect;
309
Ted Kremenek272aa852008-06-25 21:21:56 +0000310 /// Receiver - If this summary applies to an Objective-C message expression,
311 /// this is the effect applied to the state of the receiver.
Ted Kremenek266d8b62008-05-06 02:26:56 +0000312 ArgEffect Receiver;
Ted Kremenek272aa852008-06-25 21:21:56 +0000313
314 /// Ret - The effect on the return value. Used to indicate if the
315 /// function/method call returns a new tracked symbol, returns an
316 /// alias of one of the arguments in the call, and so on.
Ted Kremeneka7338b42008-03-11 06:39:11 +0000317 RetEffect Ret;
Ted Kremenek272aa852008-06-25 21:21:56 +0000318
Ted Kremenekf2717b02008-07-18 17:24:20 +0000319 /// EndPath - Indicates that execution of this method/function should
320 /// terminate the simulation of a path.
321 bool EndPath;
322
Ted Kremeneka7338b42008-03-11 06:39:11 +0000323public:
324
Ted Kremenekbcaff792008-05-06 15:44:25 +0000325 RetainSummary(ArgEffects* A, RetEffect R, ArgEffect defaultEff,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000326 ArgEffect ReceiverEff, bool endpath = false)
327 : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R),
328 EndPath(endpath) {}
Ted Kremeneka7338b42008-03-11 06:39:11 +0000329
Ted Kremenek272aa852008-06-25 21:21:56 +0000330 /// getArg - Return the argument effect on the argument specified by
331 /// idx (starting from 0).
Ted Kremenek0d721572008-03-11 17:48:22 +0000332 ArgEffect getArg(unsigned idx) const {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000333
Ted Kremenekae855d42008-04-24 17:22:33 +0000334 if (!Args)
Ted Kremenekbcaff792008-05-06 15:44:25 +0000335 return DefaultArgEffect;
Ted Kremenekae855d42008-04-24 17:22:33 +0000336
337 // If Args is present, it is likely to contain only 1 element.
338 // Just do a linear search. Do it from the back because functions with
339 // large numbers of arguments will be tail heavy with respect to which
Ted Kremenek272aa852008-06-25 21:21:56 +0000340 // argument they actually modify with respect to the reference count.
Ted Kremenekae855d42008-04-24 17:22:33 +0000341 for (ArgEffects::reverse_iterator I=Args->rbegin(), E=Args->rend();
342 I!=E; ++I) {
343
344 if (idx > I->first)
Ted Kremenekbcaff792008-05-06 15:44:25 +0000345 return DefaultArgEffect;
Ted Kremenekae855d42008-04-24 17:22:33 +0000346
347 if (idx == I->first)
348 return I->second;
349 }
350
Ted Kremenekbcaff792008-05-06 15:44:25 +0000351 return DefaultArgEffect;
Ted Kremenek0d721572008-03-11 17:48:22 +0000352 }
353
Ted Kremenek272aa852008-06-25 21:21:56 +0000354 /// getRetEffect - Returns the effect on the return value of the call.
Ted Kremenek266d8b62008-05-06 02:26:56 +0000355 RetEffect getRetEffect() const {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000356 return Ret;
357 }
358
Ted Kremenekf2717b02008-07-18 17:24:20 +0000359 /// isEndPath - Returns true if executing the given method/function should
360 /// terminate the path.
361 bool isEndPath() const { return EndPath; }
362
Ted Kremenek272aa852008-06-25 21:21:56 +0000363 /// getReceiverEffect - Returns the effect on the receiver of the call.
364 /// This is only meaningful if the summary applies to an ObjCMessageExpr*.
Ted Kremenek266d8b62008-05-06 02:26:56 +0000365 ArgEffect getReceiverEffect() const {
366 return Receiver;
367 }
368
Ted Kremenek2719e982008-06-17 02:43:46 +0000369 typedef ArgEffects::const_iterator ExprIterator;
Ted Kremeneka7338b42008-03-11 06:39:11 +0000370
Ted Kremenek2719e982008-06-17 02:43:46 +0000371 ExprIterator begin_args() const { return Args->begin(); }
372 ExprIterator end_args() const { return Args->end(); }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000373
Ted Kremenek266d8b62008-05-06 02:26:56 +0000374 static void Profile(llvm::FoldingSetNodeID& ID, ArgEffects* A,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000375 RetEffect RetEff, ArgEffect DefaultEff,
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000376 ArgEffect ReceiverEff, bool EndPath) {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000377 ID.AddPointer(A);
Ted Kremenek266d8b62008-05-06 02:26:56 +0000378 ID.Add(RetEff);
Ted Kremenekbcaff792008-05-06 15:44:25 +0000379 ID.AddInteger((unsigned) DefaultEff);
Ted Kremenek266d8b62008-05-06 02:26:56 +0000380 ID.AddInteger((unsigned) ReceiverEff);
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000381 ID.AddInteger((unsigned) EndPath);
Ted Kremeneka7338b42008-03-11 06:39:11 +0000382 }
383
384 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000385 Profile(ID, Args, Ret, DefaultArgEffect, Receiver, EndPath);
Ted Kremeneka7338b42008-03-11 06:39:11 +0000386 }
387};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000388} // end anonymous namespace
Ted Kremeneka7338b42008-03-11 06:39:11 +0000389
Ted Kremenek272aa852008-06-25 21:21:56 +0000390//===----------------------------------------------------------------------===//
391// Data structures for constructing summaries.
392//===----------------------------------------------------------------------===//
Ted Kremenek9f0fc792008-06-24 03:49:48 +0000393
Ted Kremenek272aa852008-06-25 21:21:56 +0000394namespace {
395class VISIBILITY_HIDDEN ObjCSummaryKey {
396 IdentifierInfo* II;
397 Selector S;
398public:
399 ObjCSummaryKey(IdentifierInfo* ii, Selector s)
400 : II(ii), S(s) {}
401
402 ObjCSummaryKey(ObjCInterfaceDecl* d, Selector s)
403 : II(d ? d->getIdentifier() : 0), S(s) {}
404
405 ObjCSummaryKey(Selector s)
406 : II(0), S(s) {}
407
408 IdentifierInfo* getIdentifier() const { return II; }
409 Selector getSelector() const { return S; }
410};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000411}
412
413namespace llvm {
Ted Kremenek272aa852008-06-25 21:21:56 +0000414template <> struct DenseMapInfo<ObjCSummaryKey> {
415 static inline ObjCSummaryKey getEmptyKey() {
416 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
417 DenseMapInfo<Selector>::getEmptyKey());
418 }
Ted Kremenek84f010c2008-06-23 23:30:29 +0000419
Ted Kremenek272aa852008-06-25 21:21:56 +0000420 static inline ObjCSummaryKey getTombstoneKey() {
421 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
422 DenseMapInfo<Selector>::getTombstoneKey());
423 }
424
425 static unsigned getHashValue(const ObjCSummaryKey &V) {
426 return (DenseMapInfo<IdentifierInfo*>::getHashValue(V.getIdentifier())
427 & 0x88888888)
428 | (DenseMapInfo<Selector>::getHashValue(V.getSelector())
429 & 0x55555555);
430 }
431
432 static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
433 return DenseMapInfo<IdentifierInfo*>::isEqual(LHS.getIdentifier(),
434 RHS.getIdentifier()) &&
435 DenseMapInfo<Selector>::isEqual(LHS.getSelector(),
436 RHS.getSelector());
437 }
438
439 static bool isPod() {
440 return DenseMapInfo<ObjCInterfaceDecl*>::isPod() &&
441 DenseMapInfo<Selector>::isPod();
442 }
443};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000444} // end llvm namespace
Ted Kremeneka7338b42008-03-11 06:39:11 +0000445
Ted Kremenek84f010c2008-06-23 23:30:29 +0000446namespace {
Ted Kremenek272aa852008-06-25 21:21:56 +0000447class VISIBILITY_HIDDEN ObjCSummaryCache {
448 typedef llvm::DenseMap<ObjCSummaryKey, RetainSummary*> MapTy;
449 MapTy M;
450public:
451 ObjCSummaryCache() {}
452
453 typedef MapTy::iterator iterator;
454
Ted Kremeneka821b792009-04-29 05:04:30 +0000455 iterator find(ObjCInterfaceDecl* D, IdentifierInfo *ClsName, Selector S) {
456 // Lookup the method using the decl for the class @interface. If we
457 // have no decl, lookup using the class name.
458 return D ? find(D, S) : find(ClsName, S);
459 }
460
Ted Kremenek272aa852008-06-25 21:21:56 +0000461 iterator find(ObjCInterfaceDecl* D, Selector S) {
462
463 // Do a lookup with the (D,S) pair. If we find a match return
464 // the iterator.
465 ObjCSummaryKey K(D, S);
466 MapTy::iterator I = M.find(K);
467
468 if (I != M.end() || !D)
469 return I;
470
471 // Walk the super chain. If we find a hit with a parent, we'll end
472 // up returning that summary. We actually allow that key (null,S), as
473 // we cache summaries for the null ObjCInterfaceDecl* to allow us to
474 // generate initial summaries without having to worry about NSObject
475 // being declared.
476 // FIXME: We may change this at some point.
477 for (ObjCInterfaceDecl* C=D->getSuperClass() ;; C=C->getSuperClass()) {
478 if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
479 break;
480
481 if (!C)
482 return I;
483 }
484
485 // Cache the summary with original key to make the next lookup faster
486 // and return the iterator.
487 M[K] = I->second;
488 return I;
489 }
490
Ted Kremenek9449ca92008-08-12 20:41:56 +0000491
Ted Kremenek272aa852008-06-25 21:21:56 +0000492 iterator find(Expr* Receiver, Selector S) {
493 return find(getReceiverDecl(Receiver), S);
494 }
495
496 iterator find(IdentifierInfo* II, Selector S) {
497 // FIXME: Class method lookup. Right now we dont' have a good way
498 // of going between IdentifierInfo* and the class hierarchy.
499 iterator I = M.find(ObjCSummaryKey(II, S));
500 return I == M.end() ? M.find(ObjCSummaryKey(S)) : I;
501 }
502
503 ObjCInterfaceDecl* getReceiverDecl(Expr* E) {
504
505 const PointerType* PT = E->getType()->getAsPointerType();
506 if (!PT) return 0;
507
508 ObjCInterfaceType* OI = dyn_cast<ObjCInterfaceType>(PT->getPointeeType());
509 if (!OI) return 0;
510
511 return OI ? OI->getDecl() : 0;
512 }
513
514 iterator end() { return M.end(); }
515
516 RetainSummary*& operator[](ObjCMessageExpr* ME) {
517
518 Selector S = ME->getSelector();
519
520 if (Expr* Receiver = ME->getReceiver()) {
521 ObjCInterfaceDecl* OD = getReceiverDecl(Receiver);
522 return OD ? M[ObjCSummaryKey(OD->getIdentifier(), S)] : M[S];
523 }
524
525 return M[ObjCSummaryKey(ME->getClassName(), S)];
526 }
527
528 RetainSummary*& operator[](ObjCSummaryKey K) {
529 return M[K];
530 }
531
532 RetainSummary*& operator[](Selector S) {
533 return M[ ObjCSummaryKey(S) ];
534 }
535};
536} // end anonymous namespace
537
538//===----------------------------------------------------------------------===//
539// Data structures for managing collections of summaries.
540//===----------------------------------------------------------------------===//
541
542namespace {
543class VISIBILITY_HIDDEN RetainSummaryManager {
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000544
545 //==-----------------------------------------------------------------==//
546 // Typedefs.
547 //==-----------------------------------------------------------------==//
Ted Kremeneka7338b42008-03-11 06:39:11 +0000548
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000549 typedef llvm::FoldingSet<llvm::FoldingSetNodeWrapper<ArgEffects> >
550 ArgEffectsSetTy;
551
552 typedef llvm::FoldingSet<RetainSummary>
553 SummarySetTy;
554
555 typedef llvm::DenseMap<FunctionDecl*, RetainSummary*>
556 FuncSummariesTy;
557
Ted Kremenek84f010c2008-06-23 23:30:29 +0000558 typedef ObjCSummaryCache ObjCMethodSummariesTy;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000559
560 //==-----------------------------------------------------------------==//
561 // Data.
562 //==-----------------------------------------------------------------==//
563
Ted Kremenek272aa852008-06-25 21:21:56 +0000564 /// Ctx - The ASTContext object for the analyzed ASTs.
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000565 ASTContext& Ctx;
Ted Kremeneke44927e2008-07-01 17:21:27 +0000566
Ted Kremenekede40b72008-07-09 18:11:16 +0000567 /// CFDictionaryCreateII - An IdentifierInfo* representing the indentifier
568 /// "CFDictionaryCreate".
569 IdentifierInfo* CFDictionaryCreateII;
570
Ted Kremenek272aa852008-06-25 21:21:56 +0000571 /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000572 const bool GCEnabled;
573
Ted Kremenek272aa852008-06-25 21:21:56 +0000574 /// SummarySet - A FoldingSet of uniqued summaries.
Ted Kremeneka4c74292008-04-10 22:58:08 +0000575 SummarySetTy SummarySet;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000576
Ted Kremenek272aa852008-06-25 21:21:56 +0000577 /// FuncSummaries - A map from FunctionDecls to summaries.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000578 FuncSummariesTy FuncSummaries;
579
Ted Kremenek272aa852008-06-25 21:21:56 +0000580 /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
581 /// to summaries.
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000582 ObjCMethodSummariesTy ObjCClassMethodSummaries;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000583
Ted Kremenek272aa852008-06-25 21:21:56 +0000584 /// ObjCMethodSummaries - A map from selectors to summaries.
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000585 ObjCMethodSummariesTy ObjCMethodSummaries;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000586
Ted Kremenek272aa852008-06-25 21:21:56 +0000587 /// ArgEffectsSet - A FoldingSet of uniqued ArgEffects.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000588 ArgEffectsSetTy ArgEffectsSet;
589
Ted Kremenek272aa852008-06-25 21:21:56 +0000590 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
591 /// and all other data used by the checker.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000592 llvm::BumpPtrAllocator BPAlloc;
593
Ted Kremenek272aa852008-06-25 21:21:56 +0000594 /// ScratchArgs - A holding buffer for construct ArgEffects.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000595 ArgEffects ScratchArgs;
596
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000597 RetainSummary* StopSummary;
598
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000599 //==-----------------------------------------------------------------==//
600 // Methods.
601 //==-----------------------------------------------------------------==//
602
Ted Kremenek272aa852008-06-25 21:21:56 +0000603 /// getArgEffects - Returns a persistent ArgEffects object based on the
604 /// data in ScratchArgs.
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000605 ArgEffects* getArgEffects();
Ted Kremeneka7338b42008-03-11 06:39:11 +0000606
Ted Kremenek562c1302008-05-05 16:51:50 +0000607 enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000608
609public:
Ted Kremenek064ef322009-02-23 16:51:39 +0000610 RetainSummary* getUnarySummary(const FunctionType* FT, UnaryFuncKind func);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000611
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000612 RetainSummary* getCFSummaryCreateRule(FunctionDecl* FD);
613 RetainSummary* getCFSummaryGetRule(FunctionDecl* FD);
Ted Kremenek17144e82009-01-12 21:45:02 +0000614 RetainSummary* getCFCreateGetRuleSummary(FunctionDecl* FD, const char* FName);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000615
Ted Kremenek266d8b62008-05-06 02:26:56 +0000616 RetainSummary* getPersistentSummary(ArgEffects* AE, RetEffect RetEff,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000617 ArgEffect ReceiverEff = DoNothing,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000618 ArgEffect DefaultEff = MayEscape,
619 bool isEndPath = false);
Ted Kremenek45d0b502008-10-29 04:07:07 +0000620
Ted Kremenek266d8b62008-05-06 02:26:56 +0000621 RetainSummary* getPersistentSummary(RetEffect RE,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000622 ArgEffect ReceiverEff = DoNothing,
Ted Kremeneka3f30dd2008-05-22 17:31:13 +0000623 ArgEffect DefaultEff = MayEscape) {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000624 return getPersistentSummary(getArgEffects(), RE, ReceiverEff, DefaultEff);
Ted Kremenek0e344d42008-05-06 00:30:21 +0000625 }
Ted Kremenek42ea0322008-05-05 23:55:01 +0000626
Ted Kremeneka821b792009-04-29 05:04:30 +0000627 RetainSummary *getPersistentStopSummary() {
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000628 if (StopSummary)
629 return StopSummary;
630
631 StopSummary = getPersistentSummary(RetEffect::MakeNoRet(),
632 StopTracking, StopTracking);
Ted Kremenek45d0b502008-10-29 04:07:07 +0000633
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000634 return StopSummary;
Ted Kremenekbcaff792008-05-06 15:44:25 +0000635 }
Ted Kremenek926abf22008-05-06 04:20:12 +0000636
Ted Kremeneka821b792009-04-29 05:04:30 +0000637 RetainSummary *getInitMethodSummary(QualType RetTy);
Ted Kremenek42ea0322008-05-05 23:55:01 +0000638
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000639 void InitializeClassMethodSummaries();
640 void InitializeMethodSummaries();
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000641
Ted Kremenek35920ed2009-01-07 00:39:56 +0000642 bool isTrackedObjectType(QualType T);
643
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000644private:
645
Ted Kremenekf2717b02008-07-18 17:24:20 +0000646 void addClsMethSummary(IdentifierInfo* ClsII, Selector S,
647 RetainSummary* Summ) {
648 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
649 }
650
Ted Kremenek272aa852008-06-25 21:21:56 +0000651 void addNSObjectClsMethSummary(Selector S, RetainSummary *Summ) {
652 ObjCClassMethodSummaries[S] = Summ;
653 }
654
655 void addNSObjectMethSummary(Selector S, RetainSummary *Summ) {
656 ObjCMethodSummaries[S] = Summ;
657 }
Ted Kremenekfbf2dc52009-03-04 23:30:42 +0000658
659 void addClassMethSummary(const char* Cls, const char* nullaryName,
660 RetainSummary *Summ) {
661 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
662 Selector S = GetNullarySelector(nullaryName, Ctx);
663 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
664 }
Ted Kremenek272aa852008-06-25 21:21:56 +0000665
Ted Kremenek1b4b6562009-02-25 02:54:57 +0000666 void addInstMethSummary(const char* Cls, const char* nullaryName,
667 RetainSummary *Summ) {
668 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
669 Selector S = GetNullarySelector(nullaryName, Ctx);
670 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
671 }
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000672
673 Selector generateSelector(va_list argp) {
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000674 llvm::SmallVector<IdentifierInfo*, 10> II;
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000675
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000676 while (const char* s = va_arg(argp, const char*))
677 II.push_back(&Ctx.Idents.get(s));
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000678
679 return Ctx.Selectors.getSelector(II.size(), &II[0]);
680 }
681
682 void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy& Summaries,
683 RetainSummary* Summ, va_list argp) {
684 Selector S = generateSelector(argp);
685 Summaries[ObjCSummaryKey(ClsII, S)] = Summ;
Ted Kremenekf2717b02008-07-18 17:24:20 +0000686 }
Ted Kremenek45642a42008-08-12 18:48:50 +0000687
688 void addInstMethSummary(const char* Cls, RetainSummary* Summ, ...) {
689 va_list argp;
690 va_start(argp, Summ);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000691 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Ted Kremenek45642a42008-08-12 18:48:50 +0000692 va_end(argp);
693 }
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000694
695 void addClsMethSummary(const char* Cls, RetainSummary* Summ, ...) {
696 va_list argp;
697 va_start(argp, Summ);
698 addMethodSummary(&Ctx.Idents.get(Cls),ObjCClassMethodSummaries, Summ, argp);
699 va_end(argp);
700 }
701
702 void addClsMethSummary(IdentifierInfo *II, RetainSummary* Summ, ...) {
703 va_list argp;
704 va_start(argp, Summ);
705 addMethodSummary(II, ObjCClassMethodSummaries, Summ, argp);
706 va_end(argp);
707 }
708
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000709 void addPanicSummary(const char* Cls, ...) {
710 RetainSummary* Summ = getPersistentSummary(0, RetEffect::MakeNoRet(),
711 DoNothing, DoNothing, true);
712 va_list argp;
713 va_start (argp, Cls);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000714 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000715 va_end(argp);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000716 }
Ted Kremenekf2717b02008-07-18 17:24:20 +0000717
Ted Kremeneka7338b42008-03-11 06:39:11 +0000718public:
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000719
720 RetainSummaryManager(ASTContext& ctx, bool gcenabled)
Ted Kremeneke44927e2008-07-01 17:21:27 +0000721 : Ctx(ctx),
Ted Kremenekede40b72008-07-09 18:11:16 +0000722 CFDictionaryCreateII(&ctx.Idents.get("CFDictionaryCreate")),
Ted Kremenek272aa852008-06-25 21:21:56 +0000723 GCEnabled(gcenabled), StopSummary(0) {
724
725 InitializeClassMethodSummaries();
726 InitializeMethodSummaries();
727 }
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000728
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000729 ~RetainSummaryManager();
Ted Kremeneka7338b42008-03-11 06:39:11 +0000730
Ted Kremenekd13c1872008-06-24 03:56:45 +0000731 RetainSummary* getSummary(FunctionDecl* FD);
Ted Kremeneka821b792009-04-29 05:04:30 +0000732
Ted Kremenek04e00302009-04-29 17:09:14 +0000733 RetainSummary* getInstanceMethodSummary(ObjCMessageExpr* ME, ObjCInterfaceDecl* ID) {
734 return getInstanceMethodSummary(ME->getSelector(), ME->getClassName(),
Ted Kremeneka821b792009-04-29 05:04:30 +0000735 ID, ME->getMethodDecl(), ME->getType());
736 }
737
Ted Kremenek04e00302009-04-29 17:09:14 +0000738 RetainSummary* getInstanceMethodSummary(Selector S, IdentifierInfo *ClsName,
Ted Kremeneka821b792009-04-29 05:04:30 +0000739 ObjCInterfaceDecl* ID,
740 ObjCMethodDecl *MD, QualType RetTy);
Ted Kremenek578498a2009-04-29 00:42:39 +0000741
742 RetainSummary *getClassMethodSummary(Selector S, IdentifierInfo *ClsName,
743 ObjCInterfaceDecl *ID,
744 ObjCMethodDecl *MD, QualType RetTy);
745
746 RetainSummary *getClassMethodSummary(ObjCMessageExpr *ME) {
747 return getClassMethodSummary(ME->getSelector(), ME->getClassName(),
748 ME->getClassInfo().first,
749 ME->getMethodDecl(), ME->getType());
750 }
Ted Kremenek91b89a42009-04-29 17:17:48 +0000751
752 /// getMethodSummary - This version of getMethodSummary is used to query
753 /// the summary for the current method being analyzed.
754 RetainSummary *getMethodSummary(ObjCMethodDecl *MD) {
755 Selector S = MD->getSelector();
756 ObjCInterfaceDecl *ID = MD->getClassInterface();
757 IdentifierInfo *ClsName = ID->getIdentifier();
758 QualType ResultTy = MD->getResultType();
759
760 if (MD->isInstanceMethod())
761 return getInstanceMethodSummary(S, ClsName, ID, MD, ResultTy);
762 else
763 return getClassMethodSummary(S, ClsName, ID, MD, ResultTy);
764 }
Ted Kremenek578498a2009-04-29 00:42:39 +0000765
766 RetainSummary* getCommonMethodSummary(ObjCMethodDecl* MD, Selector S,
767 QualType RetTy);
Ted Kremenek923fc392009-04-24 23:32:32 +0000768 RetainSummary* getMethodSummaryFromAnnotations(ObjCMethodDecl *MD);
Ted Kremenek926abf22008-05-06 04:20:12 +0000769
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000770 bool isGCEnabled() const { return GCEnabled; }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000771};
772
773} // end anonymous namespace
774
775//===----------------------------------------------------------------------===//
776// Implementation of checker data structures.
777//===----------------------------------------------------------------------===//
778
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000779RetainSummaryManager::~RetainSummaryManager() {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000780
781 // FIXME: The ArgEffects could eventually be allocated from BPAlloc,
782 // mitigating the need to do explicit cleanup of the
783 // Argument-Effect summaries.
784
Ted Kremenek42ea0322008-05-05 23:55:01 +0000785 for (ArgEffectsSetTy::iterator I = ArgEffectsSet.begin(),
786 E = ArgEffectsSet.end(); I!=E; ++I)
Ted Kremeneka7338b42008-03-11 06:39:11 +0000787 I->getValue().~ArgEffects();
Ted Kremenek827f93b2008-03-06 00:08:09 +0000788}
Ted Kremeneka7338b42008-03-11 06:39:11 +0000789
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000790ArgEffects* RetainSummaryManager::getArgEffects() {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000791
Ted Kremenekae855d42008-04-24 17:22:33 +0000792 if (ScratchArgs.empty())
793 return NULL;
794
795 // Compute a profile for a non-empty ScratchArgs.
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000796 llvm::FoldingSetNodeID profile;
797 profile.Add(ScratchArgs);
798 void* InsertPos;
799
Ted Kremenekae855d42008-04-24 17:22:33 +0000800 // Look up the uniqued copy, or create a new one.
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000801 llvm::FoldingSetNodeWrapper<ArgEffects>* E =
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000802 ArgEffectsSet.FindNodeOrInsertPos(profile, InsertPos);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000803
Ted Kremenekae855d42008-04-24 17:22:33 +0000804 if (E) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000805 ScratchArgs.clear();
806 return &E->getValue();
807 }
808
809 E = (llvm::FoldingSetNodeWrapper<ArgEffects>*)
Ted Kremenek272aa852008-06-25 21:21:56 +0000810 BPAlloc.Allocate<llvm::FoldingSetNodeWrapper<ArgEffects> >();
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000811
812 new (E) llvm::FoldingSetNodeWrapper<ArgEffects>(ScratchArgs);
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000813 ArgEffectsSet.InsertNode(E, InsertPos);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000814
815 ScratchArgs.clear();
816 return &E->getValue();
817}
818
Ted Kremenek266d8b62008-05-06 02:26:56 +0000819RetainSummary*
820RetainSummaryManager::getPersistentSummary(ArgEffects* AE, RetEffect RetEff,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000821 ArgEffect ReceiverEff,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000822 ArgEffect DefaultEff,
823 bool isEndPath) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000824
Ted Kremenekae855d42008-04-24 17:22:33 +0000825 // Generate a profile for the summary.
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000826 llvm::FoldingSetNodeID profile;
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000827 RetainSummary::Profile(profile, AE, RetEff, DefaultEff, ReceiverEff,
828 isEndPath);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000829
Ted Kremenekae855d42008-04-24 17:22:33 +0000830 // Look up the uniqued summary, or create one if it doesn't exist.
831 void* InsertPos;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000832 RetainSummary* Summ = SummarySet.FindNodeOrInsertPos(profile, InsertPos);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000833
834 if (Summ)
835 return Summ;
836
Ted Kremenekae855d42008-04-24 17:22:33 +0000837 // Create the summary and return it.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000838 Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
Ted Kremenekf2717b02008-07-18 17:24:20 +0000839 new (Summ) RetainSummary(AE, RetEff, DefaultEff, ReceiverEff, isEndPath);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000840 SummarySet.InsertNode(Summ, InsertPos);
841
842 return Summ;
843}
844
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000845//===----------------------------------------------------------------------===//
Ted Kremenek35920ed2009-01-07 00:39:56 +0000846// Predicates.
847//===----------------------------------------------------------------------===//
848
Ted Kremenek0d813552009-04-23 22:11:07 +0000849bool RetainSummaryManager::isTrackedObjectType(QualType Ty) {
850 if (!Ctx.isObjCObjectPointerType(Ty))
Ted Kremenek35920ed2009-01-07 00:39:56 +0000851 return false;
852
Ted Kremenek0d813552009-04-23 22:11:07 +0000853 // We assume that id<..>, id, and "Class" all represent tracked objects.
854 const PointerType *PT = Ty->getAsPointerType();
855 if (PT == 0)
856 return true;
857
858 const ObjCInterfaceType *OT = PT->getPointeeType()->getAsObjCInterfaceType();
Ted Kremenek35920ed2009-01-07 00:39:56 +0000859
860 // We assume that id<..>, id, and "Class" all represent tracked objects.
861 if (!OT)
862 return true;
Ted Kremenek0d813552009-04-23 22:11:07 +0000863
864 // Does the interface subclass NSObject?
Ted Kremenek35920ed2009-01-07 00:39:56 +0000865 // FIXME: We can memoize here if this gets too expensive.
866 IdentifierInfo* NSObjectII = &Ctx.Idents.get("NSObject");
867 ObjCInterfaceDecl* ID = OT->getDecl();
868
869 for ( ; ID ; ID = ID->getSuperClass())
870 if (ID->getIdentifier() == NSObjectII)
871 return true;
872
873 return false;
874}
875
876//===----------------------------------------------------------------------===//
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000877// Summary creation for functions (largely uses of Core Foundation).
878//===----------------------------------------------------------------------===//
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000879
Ted Kremenek17144e82009-01-12 21:45:02 +0000880static bool isRetain(FunctionDecl* FD, const char* FName) {
881 const char* loc = strstr(FName, "Retain");
882 return loc && loc[sizeof("Retain")-1] == '\0';
883}
884
885static bool isRelease(FunctionDecl* FD, const char* FName) {
886 const char* loc = strstr(FName, "Release");
887 return loc && loc[sizeof("Release")-1] == '\0';
888}
889
Ted Kremenekd13c1872008-06-24 03:56:45 +0000890RetainSummary* RetainSummaryManager::getSummary(FunctionDecl* FD) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000891
892 SourceLocation Loc = FD->getLocation();
893
894 if (!Loc.isFileID())
895 return NULL;
Ted Kremenek827f93b2008-03-06 00:08:09 +0000896
Ted Kremenekae855d42008-04-24 17:22:33 +0000897 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000898 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremenekae855d42008-04-24 17:22:33 +0000899
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000900 if (I != FuncSummaries.end())
Ted Kremenekae855d42008-04-24 17:22:33 +0000901 return I->second;
902
903 // No summary. Generate one.
Ted Kremenek17144e82009-01-12 21:45:02 +0000904 RetainSummary *S = 0;
Ted Kremenek562c1302008-05-05 16:51:50 +0000905
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000906 do {
Ted Kremenek17144e82009-01-12 21:45:02 +0000907 // We generate "stop" summaries for implicitly defined functions.
908 if (FD->isImplicit()) {
909 S = getPersistentStopSummary();
910 break;
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000911 }
Ted Kremenekeafcc2f2008-11-04 00:36:12 +0000912
Ted Kremenek064ef322009-02-23 16:51:39 +0000913 // [PR 3337] Use 'getAsFunctionType' to strip away any typedefs on the
Ted Kremenekc239b9c2009-01-16 18:40:33 +0000914 // function's type.
Ted Kremenek064ef322009-02-23 16:51:39 +0000915 const FunctionType* FT = FD->getType()->getAsFunctionType();
Ted Kremenek17144e82009-01-12 21:45:02 +0000916 const char* FName = FD->getIdentifier()->getName();
917
Ted Kremenek38c6f022009-03-05 22:11:14 +0000918 // Strip away preceding '_'. Doing this here will effect all the checks
919 // down below.
920 while (*FName == '_') ++FName;
921
Ted Kremenek17144e82009-01-12 21:45:02 +0000922 // Inspect the result type.
923 QualType RetTy = FT->getResultType();
924
925 // FIXME: This should all be refactored into a chain of "summary lookup"
926 // filters.
927 if (strcmp(FName, "IOServiceGetMatchingServices") == 0) {
928 // FIXES: <rdar://problem/6326900>
929 // This should be addressed using a API table. This strcmp is also
930 // a little gross, but there is no need to super optimize here.
931 assert (ScratchArgs.empty());
932 ScratchArgs.push_back(std::make_pair(1, DecRef));
933 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
934 break;
Ted Kremenekcfc50c72008-10-22 20:54:52 +0000935 }
Ted Kremenek7b88c892009-03-17 22:43:44 +0000936
937 // Enable this code once the semantics of NSDeallocateObject are resolved
938 // for GC. <rdar://problem/6619988>
939#if 0
940 // Handle: NSDeallocateObject(id anObject);
941 // This method does allow 'nil' (although we don't check it now).
942 if (strcmp(FName, "NSDeallocateObject") == 0) {
943 return RetTy == Ctx.VoidTy
944 ? getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, Dealloc)
945 : getPersistentStopSummary();
946 }
947#endif
Ted Kremenek17144e82009-01-12 21:45:02 +0000948
949 // Handle: id NSMakeCollectable(CFTypeRef)
950 if (strcmp(FName, "NSMakeCollectable") == 0) {
951 S = (RetTy == Ctx.getObjCIdType())
952 ? getUnarySummary(FT, cfmakecollectable)
953 : getPersistentStopSummary();
954
955 break;
956 }
957
958 if (RetTy->isPointerType()) {
959 // For CoreFoundation ('CF') types.
960 if (isRefType(RetTy, "CF", &Ctx, FName)) {
961 if (isRetain(FD, FName))
962 S = getUnarySummary(FT, cfretain);
963 else if (strstr(FName, "MakeCollectable"))
964 S = getUnarySummary(FT, cfmakecollectable);
965 else
966 S = getCFCreateGetRuleSummary(FD, FName);
967
968 break;
969 }
970
971 // For CoreGraphics ('CG') types.
972 if (isRefType(RetTy, "CG", &Ctx, FName)) {
973 if (isRetain(FD, FName))
974 S = getUnarySummary(FT, cfretain);
975 else
976 S = getCFCreateGetRuleSummary(FD, FName);
977
978 break;
979 }
980
981 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
982 if (isRefType(RetTy, "DADisk") ||
983 isRefType(RetTy, "DADissenter") ||
984 isRefType(RetTy, "DASessionRef")) {
985 S = getCFCreateGetRuleSummary(FD, FName);
986 break;
987 }
988
989 break;
990 }
991
992 // Check for release functions, the only kind of functions that we care
993 // about that don't return a pointer type.
994 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
Ted Kremenek38c6f022009-03-05 22:11:14 +0000995 // Test for 'CGCF'.
996 if (FName[1] == 'G' && FName[2] == 'C' && FName[3] == 'F')
997 FName += 4;
998 else
999 FName += 2;
1000
1001 if (isRelease(FD, FName))
Ted Kremenek17144e82009-01-12 21:45:02 +00001002 S = getUnarySummary(FT, cfrelease);
1003 else {
Ted Kremenek7b293682009-01-29 22:45:13 +00001004 assert (ScratchArgs.empty());
1005 // Remaining CoreFoundation and CoreGraphics functions.
1006 // We use to assume that they all strictly followed the ownership idiom
1007 // and that ownership cannot be transferred. While this is technically
1008 // correct, many methods allow a tracked object to escape. For example:
1009 //
1010 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
1011 // CFDictionaryAddValue(y, key, x);
1012 // CFRelease(x);
1013 // ... it is okay to use 'x' since 'y' has a reference to it
1014 //
1015 // We handle this and similar cases with the follow heuristic. If the
1016 // function name contains "InsertValue", "SetValue" or "AddValue" then
1017 // we assume that arguments may "escape."
1018 //
1019 ArgEffect E = (CStrInCStrNoCase(FName, "InsertValue") ||
1020 CStrInCStrNoCase(FName, "AddValue") ||
Ted Kremenekcf071252009-02-05 22:34:53 +00001021 CStrInCStrNoCase(FName, "SetValue") ||
1022 CStrInCStrNoCase(FName, "AppendValue"))
Ted Kremenek7b293682009-01-29 22:45:13 +00001023 ? MayEscape : DoNothing;
1024
1025 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek17144e82009-01-12 21:45:02 +00001026 }
1027 }
Ted Kremenek4c5378c2008-07-15 16:50:12 +00001028 }
1029 while (0);
Ted Kremenekae855d42008-04-24 17:22:33 +00001030
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001031 FuncSummaries[FD] = S;
Ted Kremenek562c1302008-05-05 16:51:50 +00001032 return S;
Ted Kremenek827f93b2008-03-06 00:08:09 +00001033}
1034
Ted Kremenek4c5378c2008-07-15 16:50:12 +00001035RetainSummary*
1036RetainSummaryManager::getCFCreateGetRuleSummary(FunctionDecl* FD,
1037 const char* FName) {
1038
Ted Kremenek562c1302008-05-05 16:51:50 +00001039 if (strstr(FName, "Create") || strstr(FName, "Copy"))
1040 return getCFSummaryCreateRule(FD);
Ted Kremenek4c5378c2008-07-15 16:50:12 +00001041
Ted Kremenek562c1302008-05-05 16:51:50 +00001042 if (strstr(FName, "Get"))
1043 return getCFSummaryGetRule(FD);
1044
1045 return 0;
1046}
1047
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001048RetainSummary*
Ted Kremenek064ef322009-02-23 16:51:39 +00001049RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1050 UnaryFuncKind func) {
1051
Ted Kremenek17144e82009-01-12 21:45:02 +00001052 // Sanity check that this is *really* a unary function. This can
1053 // happen if people do weird things.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001054 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
Ted Kremenek17144e82009-01-12 21:45:02 +00001055 if (!FTP || FTP->getNumArgs() != 1)
1056 return getPersistentStopSummary();
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001057
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001058 assert (ScratchArgs.empty());
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001059
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001060 switch (func) {
Ted Kremenek17144e82009-01-12 21:45:02 +00001061 case cfretain: {
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001062 ScratchArgs.push_back(std::make_pair(0, IncRef));
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001063 return getPersistentSummary(RetEffect::MakeAlias(0),
1064 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001065 }
1066
1067 case cfrelease: {
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001068 ScratchArgs.push_back(std::make_pair(0, DecRef));
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001069 return getPersistentSummary(RetEffect::MakeNoRet(),
1070 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001071 }
1072
1073 case cfmakecollectable: {
Ted Kremenek2126bef2009-02-18 21:57:45 +00001074 ScratchArgs.push_back(std::make_pair(0, MakeCollectable));
1075 return getPersistentSummary(RetEffect::MakeAlias(0),DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001076 }
1077
1078 default:
Ted Kremenek562c1302008-05-05 16:51:50 +00001079 assert (false && "Not a supported unary function.");
Ted Kremenek9449ca92008-08-12 20:41:56 +00001080 return 0;
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00001081 }
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001082}
1083
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001084RetainSummary* RetainSummaryManager::getCFSummaryCreateRule(FunctionDecl* FD) {
Ted Kremenekae855d42008-04-24 17:22:33 +00001085 assert (ScratchArgs.empty());
Ted Kremenekede40b72008-07-09 18:11:16 +00001086
1087 if (FD->getIdentifier() == CFDictionaryCreateII) {
1088 ScratchArgs.push_back(std::make_pair(1, DoNothingByRef));
1089 ScratchArgs.push_back(std::make_pair(2, DoNothingByRef));
1090 }
1091
Ted Kremenek68621b92009-01-28 05:56:51 +00001092 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001093}
1094
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001095RetainSummary* RetainSummaryManager::getCFSummaryGetRule(FunctionDecl* FD) {
Ted Kremenekae855d42008-04-24 17:22:33 +00001096 assert (ScratchArgs.empty());
Ted Kremenek68621b92009-01-28 05:56:51 +00001097 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1098 DoNothing, DoNothing);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001099}
1100
Ted Kremeneka7338b42008-03-11 06:39:11 +00001101//===----------------------------------------------------------------------===//
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001102// Summary creation for Selectors.
1103//===----------------------------------------------------------------------===//
1104
Ted Kremenekbcaff792008-05-06 15:44:25 +00001105RetainSummary*
Ted Kremeneka821b792009-04-29 05:04:30 +00001106RetainSummaryManager::getInitMethodSummary(QualType RetTy) {
Ted Kremenek42ea0322008-05-05 23:55:01 +00001107 assert(ScratchArgs.empty());
1108
Ted Kremenek802cfc72009-02-20 00:05:35 +00001109 // 'init' methods only return an alias if the return type is a location type.
Ted Kremeneka821b792009-04-29 05:04:30 +00001110 return getPersistentSummary(Loc::IsLocType(RetTy)
1111 ? RetEffect::MakeReceiverAlias()
1112 : RetEffect::MakeNoRet());
Ted Kremenek42ea0322008-05-05 23:55:01 +00001113}
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001114
Ted Kremenek923fc392009-04-24 23:32:32 +00001115RetainSummary*
1116RetainSummaryManager::getMethodSummaryFromAnnotations(ObjCMethodDecl *MD) {
1117 if (!MD)
1118 return 0;
1119
1120 assert(ScratchArgs.empty());
1121
1122 // Determine if there is a special return effect for this method.
1123 bool hasRetEffect = false;
1124 RetEffect RE = RetEffect::MakeNoRet();
1125
1126 if (isTrackedObjectType(MD->getResultType())) {
1127 if (MD->getAttr<ObjCOwnershipReturnsAttr>()) {
Ted Kremenek382fb4e2009-04-27 19:14:45 +00001128 RE = isGCEnabled() ? RetEffect::MakeGCNotOwned()
1129 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremenek923fc392009-04-24 23:32:32 +00001130 hasRetEffect = true;
1131 }
1132 else {
1133 // Default to 'not owned'.
1134 RE = RetEffect::MakeNotOwned(RetEffect::ObjC);
1135 }
1136 }
1137
Ted Kremenekb30a2f32009-04-25 01:21:50 +00001138 // Determine if there are any arguments with a specific ArgEffect.
1139 bool hasArgEffect = false;
1140 unsigned i = 0;
1141 for (ObjCMethodDecl::param_iterator I = MD->param_begin(),
1142 E = MD->param_end(); I != E; ++I, ++i) {
1143 if ((*I)->getAttr<ObjCOwnershipRetainAttr>()) {
1144 ScratchArgs.push_back(std::make_pair(i, IncRefMsg));
1145 hasArgEffect = true;
1146 }
Ted Kremenek15830ed2009-04-27 18:27:22 +00001147 else if ((*I)->getAttr<ObjCOwnershipCFRetainAttr>()) {
1148 ScratchArgs.push_back(std::make_pair(i, IncRef));
1149 hasArgEffect = true;
Ted Kremenek203169f2009-04-27 19:36:56 +00001150 }
1151 else if ((*I)->getAttr<ObjCOwnershipReleaseAttr>()) {
1152 ScratchArgs.push_back(std::make_pair(i, DecRefMsg));
1153 hasArgEffect = true;
1154 }
1155 else if ((*I)->getAttr<ObjCOwnershipCFReleaseAttr>()) {
1156 ScratchArgs.push_back(std::make_pair(i, DecRef));
1157 hasArgEffect = true;
1158 }
Ted Kremenekff8648d2009-04-28 22:32:26 +00001159 else if ((*I)->getAttr<ObjCOwnershipMakeCollectableAttr>()) {
1160 ScratchArgs.push_back(std::make_pair(i, MakeCollectable));
1161 hasArgEffect = true;
1162 }
Ted Kremenek15830ed2009-04-27 18:27:22 +00001163 }
Ted Kremenekb30a2f32009-04-25 01:21:50 +00001164
1165 if (!hasRetEffect && !hasArgEffect)
Ted Kremenek923fc392009-04-24 23:32:32 +00001166 return 0;
1167
1168 return getPersistentSummary(RE);
1169}
Ted Kremenek272aa852008-06-25 21:21:56 +00001170
Ted Kremenekbcaff792008-05-06 15:44:25 +00001171RetainSummary*
Ted Kremenek578498a2009-04-29 00:42:39 +00001172RetainSummaryManager::getCommonMethodSummary(ObjCMethodDecl* MD, Selector S,
1173 QualType RetTy) {
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001174
Ted Kremenek578498a2009-04-29 00:42:39 +00001175 if (MD) {
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001176 // Scan the method decl for 'void*' arguments. These should be treated
1177 // as 'StopTracking' because they are often used with delegates.
1178 // Delegates are a frequent form of false positives with the retain
1179 // count checker.
1180 unsigned i = 0;
1181 for (ObjCMethodDecl::param_iterator I = MD->param_begin(),
1182 E = MD->param_end(); I != E; ++I, ++i)
1183 if (ParmVarDecl *PD = *I) {
1184 QualType Ty = Ctx.getCanonicalType(PD->getType());
1185 if (Ty.getUnqualifiedType() == Ctx.VoidPtrTy)
1186 ScratchArgs.push_back(std::make_pair(i, StopTracking));
1187 }
1188 }
1189
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001190 // Any special effect for the receiver?
1191 ArgEffect ReceiverEff = DoNothing;
1192
1193 // If one of the arguments in the selector has the keyword 'delegate' we
1194 // should stop tracking the reference count for the receiver. This is
1195 // because the reference count is quite possibly handled by a delegate
1196 // method.
1197 if (S.isKeywordSelector()) {
1198 const std::string &str = S.getAsString();
1199 assert(!str.empty());
1200 if (CStrInCStrNoCase(&str[0], "delegate:")) ReceiverEff = StopTracking;
1201 }
1202
Ted Kremenek174a0772009-04-23 23:08:22 +00001203 // Look for methods that return an owned object.
Ted Kremenek578498a2009-04-29 00:42:39 +00001204 if (!isTrackedObjectType(RetTy)) {
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001205 if (ScratchArgs.empty() && ReceiverEff == DoNothing)
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001206 return 0;
1207
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001208 return getPersistentSummary(RetEffect::MakeNoRet(), ReceiverEff,
1209 MayEscape);
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001210 }
Ted Kremenek174a0772009-04-23 23:08:22 +00001211
1212 // EXPERIMENTAL: Assume the Cocoa conventions for all objects returned
1213 // by instance methods.
1214
1215 RetEffect E =
Ted Kremenekaca0b452009-04-24 18:19:07 +00001216 followsFundamentalRule(S.getIdentifierInfoForSlot(0)->getName())
Ted Kremenek382fb4e2009-04-27 19:14:45 +00001217 ? (isGCEnabled() ? RetEffect::MakeGCNotOwned()
Ted Kremenek174a0772009-04-23 23:08:22 +00001218 : RetEffect::MakeOwned(RetEffect::ObjC, true))
1219 : RetEffect::MakeNotOwned(RetEffect::ObjC);
1220
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001221 return getPersistentSummary(E, ReceiverEff, MayEscape);
Ted Kremenek174a0772009-04-23 23:08:22 +00001222}
1223
1224RetainSummary*
Ted Kremenek04e00302009-04-29 17:09:14 +00001225RetainSummaryManager::getInstanceMethodSummary(Selector S,
1226 IdentifierInfo *ClsName,
1227 ObjCInterfaceDecl* ID,
1228 ObjCMethodDecl *MD,
1229 QualType RetTy) {
Ted Kremenekbcaff792008-05-06 15:44:25 +00001230
Ted Kremeneka821b792009-04-29 05:04:30 +00001231 // Look up a summary in our summary cache.
1232 ObjCMethodSummariesTy::iterator I = ObjCMethodSummaries.find(ID, ClsName, S);
Ted Kremenek42ea0322008-05-05 23:55:01 +00001233
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001234 if (I != ObjCMethodSummaries.end())
Ted Kremenek42ea0322008-05-05 23:55:01 +00001235 return I->second;
Ted Kremenek42ea0322008-05-05 23:55:01 +00001236
Ted Kremenek174a0772009-04-23 23:08:22 +00001237 assert(ScratchArgs.empty());
Ted Kremenek923fc392009-04-24 23:32:32 +00001238
1239 // Annotations take precedence over all other ways to derive
1240 // summaries.
Ted Kremeneka821b792009-04-29 05:04:30 +00001241 RetainSummary *Summ = getMethodSummaryFromAnnotations(MD);
Ted Kremenek1d3d9562008-05-06 06:09:09 +00001242
Ted Kremenek923fc392009-04-24 23:32:32 +00001243 if (!Summ) {
1244 // "initXXX": pass-through for receiver.
1245 if (deriveNamingConvention(S.getIdentifierInfoForSlot(0)->getName())
1246 == InitRule)
Ted Kremeneka821b792009-04-29 05:04:30 +00001247 Summ = getInitMethodSummary(RetTy);
1248 else
1249 Summ = getCommonMethodSummary(MD, S, RetTy);
Ted Kremenek923fc392009-04-24 23:32:32 +00001250 }
1251
Ted Kremeneka821b792009-04-29 05:04:30 +00001252 ObjCMethodSummaries[ObjCSummaryKey(ClsName, S)] = Summ;
Ted Kremeneke4158502009-04-23 19:11:35 +00001253 return Summ;
Ted Kremenek42ea0322008-05-05 23:55:01 +00001254}
1255
Ted Kremeneka7722b72008-05-06 21:26:51 +00001256RetainSummary*
Ted Kremenek578498a2009-04-29 00:42:39 +00001257RetainSummaryManager::getClassMethodSummary(Selector S, IdentifierInfo *ClsName,
1258 ObjCInterfaceDecl *ID,
1259 ObjCMethodDecl *MD, QualType RetTy){
Ted Kremenekccbe79a2009-04-24 17:50:11 +00001260
Ted Kremenek578498a2009-04-29 00:42:39 +00001261 assert(ClsName && "Class name must be specified.");
Ted Kremeneka821b792009-04-29 05:04:30 +00001262 ObjCMethodSummariesTy::iterator I =
1263 ObjCClassMethodSummaries.find(ID, ClsName, S);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001264
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001265 if (I != ObjCClassMethodSummaries.end())
Ted Kremeneka7722b72008-05-06 21:26:51 +00001266 return I->second;
1267
Ted Kremenek923fc392009-04-24 23:32:32 +00001268 // Annotations take precedence over all other ways to derive
1269 // summaries.
Ted Kremenek578498a2009-04-29 00:42:39 +00001270 RetainSummary *Summ = getMethodSummaryFromAnnotations(MD);
Ted Kremenek923fc392009-04-24 23:32:32 +00001271
1272 if (!Summ)
Ted Kremenek578498a2009-04-29 00:42:39 +00001273 Summ = getCommonMethodSummary(MD, S, RetTy);
Ted Kremenek923fc392009-04-24 23:32:32 +00001274
Ted Kremenek578498a2009-04-29 00:42:39 +00001275 ObjCClassMethodSummaries[ObjCSummaryKey(ClsName, S)] = Summ;
Ted Kremeneke4158502009-04-23 19:11:35 +00001276 return Summ;
Ted Kremeneka7722b72008-05-06 21:26:51 +00001277}
1278
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001279void RetainSummaryManager::InitializeClassMethodSummaries() {
Ted Kremenek0e344d42008-05-06 00:30:21 +00001280
1281 assert (ScratchArgs.empty());
1282
Ted Kremenek382fb4e2009-04-27 19:14:45 +00001283 RetEffect E = isGCEnabled() ? RetEffect::MakeGCNotOwned()
Ted Kremenek68621b92009-01-28 05:56:51 +00001284 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001285
Ted Kremenek0e344d42008-05-06 00:30:21 +00001286 RetainSummary* Summ = getPersistentSummary(E);
1287
Ted Kremenek272aa852008-06-25 21:21:56 +00001288 // Create the summaries for "alloc", "new", and "allocWithZone:" for
1289 // NSObject and its derivatives.
1290 addNSObjectClsMethSummary(GetNullarySelector("alloc", Ctx), Summ);
1291 addNSObjectClsMethSummary(GetNullarySelector("new", Ctx), Summ);
1292 addNSObjectClsMethSummary(GetUnarySelector("allocWithZone", Ctx), Summ);
Ted Kremenekf2717b02008-07-18 17:24:20 +00001293
1294 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001295 addClsMethSummary(&Ctx.Idents.get("NSAssertionHandler"),
Ted Kremenek68621b92009-01-28 05:56:51 +00001296 GetNullarySelector("currentHandler", Ctx),
1297 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001298
1299 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremenek9b112d22009-01-28 21:44:40 +00001300 ScratchArgs.push_back(std::make_pair(0, Autorelease));
1301 addClsMethSummary(&Ctx.Idents.get("NSAutoreleasePool"),
1302 GetUnarySelector("addObject", Ctx),
1303 getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenekf21cb242009-02-23 02:31:16 +00001304 DoNothing, Autorelease));
Ted Kremenekccbe79a2009-04-24 17:50:11 +00001305
1306 // Create the summaries for [NSObject performSelector...]. We treat
1307 // these as 'stop tracking' for the arguments because they are often
1308 // used for delegates that can release the object. When we have better
1309 // inter-procedural analysis we can potentially do something better. This
1310 // workaround is to remove false positives.
1311 Summ = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, StopTracking);
1312 IdentifierInfo *NSObjectII = &Ctx.Idents.get("NSObject");
1313 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1314 "afterDelay", NULL);
1315 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1316 "afterDelay", "inModes", NULL);
1317 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1318 "withObject", "waitUntilDone", NULL);
1319 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1320 "withObject", "waitUntilDone", "modes", NULL);
1321 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1322 "withObject", "waitUntilDone", NULL);
1323 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1324 "withObject", "waitUntilDone", "modes", NULL);
1325 addClsMethSummary(NSObjectII, Summ, "performSelectorInBackground",
1326 "withObject", NULL);
Ted Kremenek0e344d42008-05-06 00:30:21 +00001327}
1328
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001329void RetainSummaryManager::InitializeMethodSummaries() {
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001330
1331 assert (ScratchArgs.empty());
1332
Ted Kremeneka7722b72008-05-06 21:26:51 +00001333 // Create the "init" selector. It just acts as a pass-through for the
1334 // receiver.
Ted Kremenek56c70aa2009-02-23 16:54:00 +00001335 RetainSummary* InitSumm =
1336 getPersistentSummary(RetEffect::MakeReceiverAlias());
Ted Kremeneke44927e2008-07-01 17:21:27 +00001337 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001338
1339 // The next methods are allocators.
Ted Kremenek382fb4e2009-04-27 19:14:45 +00001340 RetEffect E = isGCEnabled() ? RetEffect::MakeGCNotOwned()
Ted Kremenek68621b92009-01-28 05:56:51 +00001341 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001342
Ted Kremeneke44927e2008-07-01 17:21:27 +00001343 RetainSummary* Summ = getPersistentSummary(E);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001344
1345 // Create the "copy" selector.
Ted Kremenek9449ca92008-08-12 20:41:56 +00001346 addNSObjectMethSummary(GetNullarySelector("copy", Ctx), Summ);
1347
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001348 // Create the "mutableCopy" selector.
Ted Kremenek272aa852008-06-25 21:21:56 +00001349 addNSObjectMethSummary(GetNullarySelector("mutableCopy", Ctx), Summ);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001350
Ted Kremenek266d8b62008-05-06 02:26:56 +00001351 // Create the "retain" selector.
1352 E = RetEffect::MakeReceiverAlias();
Ted Kremenek58dd95b2009-02-18 18:54:33 +00001353 Summ = getPersistentSummary(E, IncRefMsg);
Ted Kremenek272aa852008-06-25 21:21:56 +00001354 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001355
1356 // Create the "release" selector.
Ted Kremenek58dd95b2009-02-18 18:54:33 +00001357 Summ = getPersistentSummary(E, DecRefMsg);
Ted Kremenek272aa852008-06-25 21:21:56 +00001358 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Ted Kremenekc00b32b2008-05-07 21:17:39 +00001359
1360 // Create the "drain" selector.
1361 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek272aa852008-06-25 21:21:56 +00001362 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
Ted Kremenek6537a642009-03-17 19:42:23 +00001363
1364 // Create the -dealloc summary.
1365 Summ = getPersistentSummary(RetEffect::MakeNoRet(), Dealloc);
1366 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001367
1368 // Create the "autorelease" selector.
Ted Kremenek9b112d22009-01-28 21:44:40 +00001369 Summ = getPersistentSummary(E, Autorelease);
Ted Kremenek272aa852008-06-25 21:21:56 +00001370 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001371
Ted Kremenekaac82832009-02-23 17:45:03 +00001372 // Specially handle NSAutoreleasePool.
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001373 addInstMethSummary("NSAutoreleasePool", "init",
Ted Kremenekaac82832009-02-23 17:45:03 +00001374 getPersistentSummary(RetEffect::MakeReceiverAlias(),
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001375 NewAutoreleasePool));
Ted Kremenekaac82832009-02-23 17:45:03 +00001376
Ted Kremenek45642a42008-08-12 18:48:50 +00001377 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremenek7e3a3272009-02-23 02:51:29 +00001378 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1379 // self-own themselves. However, they only do this once they are displayed.
1380 // Thus, we need to track an NSWindow's display status.
1381 // This is tracked in <rdar://problem/6062711>.
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001382 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
Ted Kremeneke5a036a2009-04-03 19:02:51 +00001383 RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet());
1384
1385 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1386
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001387
1388#if 0
Ted Kremeneke44927e2008-07-01 17:21:27 +00001389 RetainSummary *NSWindowSumm =
Ted Kremenek7e3a3272009-02-23 02:51:29 +00001390 getPersistentSummary(RetEffect::MakeReceiverAlias(), StopTracking);
Ted Kremenek45642a42008-08-12 18:48:50 +00001391
1392 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1393 "styleMask", "backing", "defer", NULL);
1394
1395 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1396 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001397#endif
Ted Kremenek45642a42008-08-12 18:48:50 +00001398
1399 // For NSPanel (which subclasses NSWindow), allocated objects are not
1400 // self-owned.
Ted Kremeneke5a036a2009-04-03 19:02:51 +00001401 // FIXME: For now we don't track NSPanels. object for the same reason
1402 // as for NSWindow objects.
1403 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
1404
Ted Kremenek45642a42008-08-12 18:48:50 +00001405 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1406 "styleMask", "backing", "defer", NULL);
1407
1408 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1409 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek272aa852008-06-25 21:21:56 +00001410
Ted Kremenekf2717b02008-07-18 17:24:20 +00001411 // Create NSAssertionHandler summaries.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001412 addPanicSummary("NSAssertionHandler", "handleFailureInFunction", "file",
1413 "lineNumber", "description", NULL);
Ted Kremenekf2717b02008-07-18 17:24:20 +00001414
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001415 addPanicSummary("NSAssertionHandler", "handleFailureInMethod", "object",
1416 "file", "lineNumber", "description", NULL);
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001417}
1418
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001419//===----------------------------------------------------------------------===//
Ted Kremenek7aef4842008-04-16 20:40:59 +00001420// Reference-counting logic (typestate + counts).
Ted Kremeneka7338b42008-03-11 06:39:11 +00001421//===----------------------------------------------------------------------===//
1422
Ted Kremeneka7338b42008-03-11 06:39:11 +00001423namespace {
1424
Ted Kremenek7d421f32008-04-09 23:49:11 +00001425class VISIBILITY_HIDDEN RefVal {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001426public:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001427 enum Kind {
1428 Owned = 0, // Owning reference.
1429 NotOwned, // Reference is not owned by still valid (not freed).
1430 Released, // Object has been released.
1431 ReturnedOwned, // Returned object passes ownership to caller.
1432 ReturnedNotOwned, // Return object does not pass ownership to caller.
Ted Kremenek6537a642009-03-17 19:42:23 +00001433 ERROR_START,
1434 ErrorDeallocNotOwned, // -dealloc called on non-owned object.
1435 ErrorDeallocGC, // Calling -dealloc with GC enabled.
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001436 ErrorUseAfterRelease, // Object used after released.
1437 ErrorReleaseNotOwned, // Release of an object that was not owned.
Ted Kremenek6537a642009-03-17 19:42:23 +00001438 ERROR_LEAK_START,
Ted Kremenek311f3d42008-10-22 23:56:21 +00001439 ErrorLeak, // A memory leak due to excessive reference counts.
1440 ErrorLeakReturned // A memory leak due to the returning method not having
1441 // the correct naming conventions.
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001442 };
Ted Kremenek68621b92009-01-28 05:56:51 +00001443
1444private:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001445 Kind kind;
Ted Kremenek68621b92009-01-28 05:56:51 +00001446 RetEffect::ObjKind okind;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001447 unsigned Cnt;
Ted Kremenek272aa852008-06-25 21:21:56 +00001448 QualType T;
1449
Ted Kremenek68621b92009-01-28 05:56:51 +00001450 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, QualType t)
1451 : kind(k), okind(o), Cnt(cnt), T(t) {}
Ted Kremenek0d721572008-03-11 17:48:22 +00001452
Ted Kremenek68621b92009-01-28 05:56:51 +00001453 RefVal(Kind k, unsigned cnt = 0)
1454 : kind(k), okind(RetEffect::AnyObj), Cnt(cnt) {}
1455
1456public:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001457 Kind getKind() const { return kind; }
Ted Kremenek68621b92009-01-28 05:56:51 +00001458
1459 RetEffect::ObjKind getObjKind() const { return okind; }
Ted Kremenek0d721572008-03-11 17:48:22 +00001460
Ted Kremenek6537a642009-03-17 19:42:23 +00001461 unsigned getCount() const { return Cnt; }
1462 void clearCounts() { Cnt = 0; }
1463
Ted Kremenek272aa852008-06-25 21:21:56 +00001464 QualType getType() const { return T; }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001465
1466 // Useful predicates.
Ted Kremenek0d721572008-03-11 17:48:22 +00001467
Ted Kremenek6537a642009-03-17 19:42:23 +00001468 static bool isError(Kind k) { return k >= ERROR_START; }
Ted Kremenek1daa16c2008-03-11 18:14:09 +00001469
Ted Kremenek6537a642009-03-17 19:42:23 +00001470 static bool isLeak(Kind k) { return k >= ERROR_LEAK_START; }
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001471
Ted Kremenekffefc352008-04-11 22:25:11 +00001472 bool isOwned() const {
1473 return getKind() == Owned;
1474 }
1475
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001476 bool isNotOwned() const {
1477 return getKind() == NotOwned;
1478 }
1479
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001480 bool isReturnedOwned() const {
1481 return getKind() == ReturnedOwned;
1482 }
1483
1484 bool isReturnedNotOwned() const {
1485 return getKind() == ReturnedNotOwned;
1486 }
1487
1488 bool isNonLeakError() const {
1489 Kind k = getKind();
1490 return isError(k) && !isLeak(k);
1491 }
1492
Ted Kremenek68621b92009-01-28 05:56:51 +00001493 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
1494 unsigned Count = 1) {
1495 return RefVal(Owned, o, Count, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001496 }
1497
Ted Kremenek68621b92009-01-28 05:56:51 +00001498 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
1499 unsigned Count = 0) {
1500 return RefVal(NotOwned, o, Count, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001501 }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001502
1503 static RefVal makeReturnedOwned(unsigned Count) {
1504 return RefVal(ReturnedOwned, Count);
1505 }
1506
1507 static RefVal makeReturnedNotOwned() {
1508 return RefVal(ReturnedNotOwned);
1509 }
1510
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001511 // Comparison, profiling, and pretty-printing.
Ted Kremenek0d721572008-03-11 17:48:22 +00001512
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001513 bool operator==(const RefVal& X) const {
Ted Kremenek272aa852008-06-25 21:21:56 +00001514 return kind == X.kind && Cnt == X.Cnt && T == X.T;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001515 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001516
Ted Kremenek272aa852008-06-25 21:21:56 +00001517 RefVal operator-(size_t i) const {
Ted Kremenek68621b92009-01-28 05:56:51 +00001518 return RefVal(getKind(), getObjKind(), getCount() - i, getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001519 }
1520
1521 RefVal operator+(size_t i) const {
Ted Kremenek68621b92009-01-28 05:56:51 +00001522 return RefVal(getKind(), getObjKind(), getCount() + i, getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001523 }
1524
1525 RefVal operator^(Kind k) const {
Ted Kremenek68621b92009-01-28 05:56:51 +00001526 return RefVal(k, getObjKind(), getCount(), getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001527 }
Ted Kremenek6537a642009-03-17 19:42:23 +00001528
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001529 void Profile(llvm::FoldingSetNodeID& ID) const {
1530 ID.AddInteger((unsigned) kind);
1531 ID.AddInteger(Cnt);
Ted Kremenek272aa852008-06-25 21:21:56 +00001532 ID.Add(T);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001533 }
1534
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001535 void print(std::ostream& Out) const;
Ted Kremenek0d721572008-03-11 17:48:22 +00001536};
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001537
1538void RefVal::print(std::ostream& Out) const {
Ted Kremenek272aa852008-06-25 21:21:56 +00001539 if (!T.isNull())
1540 Out << "Tracked Type:" << T.getAsString() << '\n';
1541
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001542 switch (getKind()) {
1543 default: assert(false);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001544 case Owned: {
1545 Out << "Owned";
1546 unsigned cnt = getCount();
1547 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001548 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001549 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001550
Ted Kremenekc4f81022008-04-10 23:09:18 +00001551 case NotOwned: {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001552 Out << "NotOwned";
Ted Kremenekc4f81022008-04-10 23:09:18 +00001553 unsigned cnt = getCount();
1554 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001555 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001556 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001557
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001558 case ReturnedOwned: {
1559 Out << "ReturnedOwned";
1560 unsigned cnt = getCount();
1561 if (cnt) Out << " (+ " << cnt << ")";
1562 break;
1563 }
1564
1565 case ReturnedNotOwned: {
1566 Out << "ReturnedNotOwned";
1567 unsigned cnt = getCount();
1568 if (cnt) Out << " (+ " << cnt << ")";
1569 break;
1570 }
1571
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001572 case Released:
1573 Out << "Released";
1574 break;
Ted Kremenek6537a642009-03-17 19:42:23 +00001575
1576 case ErrorDeallocGC:
1577 Out << "-dealloc (GC)";
1578 break;
1579
1580 case ErrorDeallocNotOwned:
1581 Out << "-dealloc (not-owned)";
1582 break;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001583
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001584 case ErrorLeak:
1585 Out << "Leaked";
1586 break;
1587
Ted Kremenek311f3d42008-10-22 23:56:21 +00001588 case ErrorLeakReturned:
1589 Out << "Leaked (Bad naming)";
1590 break;
1591
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001592 case ErrorUseAfterRelease:
1593 Out << "Use-After-Release [ERROR]";
1594 break;
1595
1596 case ErrorReleaseNotOwned:
1597 Out << "Release of Not-Owned [ERROR]";
1598 break;
1599 }
1600}
Ted Kremenek0d721572008-03-11 17:48:22 +00001601
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001602} // end anonymous namespace
1603
1604//===----------------------------------------------------------------------===//
1605// RefBindings - State used to track object reference counts.
1606//===----------------------------------------------------------------------===//
1607
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001608typedef llvm::ImmutableMap<SymbolRef, RefVal> RefBindings;
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001609static int RefBIndex = 0;
Ted Kremenek876d8df2009-02-19 23:47:02 +00001610static std::pair<const void*, const void*> LeakProgramPointTag(&RefBIndex, 0);
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001611
1612namespace clang {
Ted Kremenek91781202008-08-17 03:20:02 +00001613 template<>
1614 struct GRStateTrait<RefBindings> : public GRStatePartialTrait<RefBindings> {
1615 static inline void* GDMIndex() { return &RefBIndex; }
1616 };
1617}
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001618
1619//===----------------------------------------------------------------------===//
Ted Kremenekb6578942009-02-24 19:15:11 +00001620// AutoreleaseBindings - State used to track objects in autorelease pools.
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001621//===----------------------------------------------------------------------===//
1622
Ted Kremenekb6578942009-02-24 19:15:11 +00001623typedef llvm::ImmutableMap<SymbolRef, unsigned> ARCounts;
1624typedef llvm::ImmutableMap<SymbolRef, ARCounts> ARPoolContents;
1625typedef llvm::ImmutableList<SymbolRef> ARStack;
Ted Kremenekaac82832009-02-23 17:45:03 +00001626
Ted Kremenekb6578942009-02-24 19:15:11 +00001627static int AutoRCIndex = 0;
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001628static int AutoRBIndex = 0;
1629
Ted Kremenekb6578942009-02-24 19:15:11 +00001630namespace { class VISIBILITY_HIDDEN AutoreleasePoolContents {}; }
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001631namespace { class VISIBILITY_HIDDEN AutoreleaseStack {}; }
Ted Kremenekb6578942009-02-24 19:15:11 +00001632
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001633namespace clang {
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001634template<> struct GRStateTrait<AutoreleaseStack>
Ted Kremenekb6578942009-02-24 19:15:11 +00001635 : public GRStatePartialTrait<ARStack> {
1636 static inline void* GDMIndex() { return &AutoRBIndex; }
1637};
1638
1639template<> struct GRStateTrait<AutoreleasePoolContents>
1640 : public GRStatePartialTrait<ARPoolContents> {
1641 static inline void* GDMIndex() { return &AutoRCIndex; }
1642};
1643} // end clang namespace
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001644
Ted Kremenek681fb352009-03-20 17:34:15 +00001645static SymbolRef GetCurrentAutoreleasePool(const GRState* state) {
1646 ARStack stack = state->get<AutoreleaseStack>();
1647 return stack.isEmpty() ? SymbolRef() : stack.getHead();
1648}
1649
1650static GRStateRef SendAutorelease(GRStateRef state, ARCounts::Factory &F,
1651 SymbolRef sym) {
1652
1653 SymbolRef pool = GetCurrentAutoreleasePool(state);
1654 const ARCounts *cnts = state.get<AutoreleasePoolContents>(pool);
1655 ARCounts newCnts(0);
1656
1657 if (cnts) {
1658 const unsigned *cnt = (*cnts).lookup(sym);
1659 newCnts = F.Add(*cnts, sym, cnt ? *cnt + 1 : 1);
1660 }
1661 else
1662 newCnts = F.Add(F.GetEmptyMap(), sym, 1);
1663
1664 return state.set<AutoreleasePoolContents>(pool, newCnts);
1665}
1666
Ted Kremenek7aef4842008-04-16 20:40:59 +00001667//===----------------------------------------------------------------------===//
1668// Transfer functions.
1669//===----------------------------------------------------------------------===//
1670
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001671namespace {
1672
Ted Kremenek7d421f32008-04-09 23:49:11 +00001673class VISIBILITY_HIDDEN CFRefCount : public GRSimpleVals {
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001674public:
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001675 class BindingsPrinter : public GRState::Printer {
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001676 public:
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001677 virtual void Print(std::ostream& Out, const GRState* state,
1678 const char* nl, const char* sep);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001679 };
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001680
1681private:
Ted Kremenekc26c4692009-02-18 03:48:14 +00001682 typedef llvm::DenseMap<const GRExprEngine::NodeTy*, const RetainSummary*>
1683 SummaryLogTy;
1684
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001685 RetainSummaryManager Summaries;
Ted Kremenekc26c4692009-02-18 03:48:14 +00001686 SummaryLogTy SummaryLog;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001687 const LangOptions& LOpts;
Ted Kremenekb6578942009-02-24 19:15:11 +00001688 ARCounts::Factory ARCountFactory;
Ted Kremenek91781202008-08-17 03:20:02 +00001689
Ted Kremenek708af042009-02-05 06:50:21 +00001690 BugType *useAfterRelease, *releaseNotOwned;
Ted Kremenek6537a642009-03-17 19:42:23 +00001691 BugType *deallocGC, *deallocNotOwned;
Ted Kremenek708af042009-02-05 06:50:21 +00001692 BugType *leakWithinFunction, *leakAtReturn;
1693 BugReporter *BR;
Ted Kremeneka7338b42008-03-11 06:39:11 +00001694
Ted Kremenekb6578942009-02-24 19:15:11 +00001695 GRStateRef Update(GRStateRef state, SymbolRef sym, RefVal V, ArgEffect E,
1696 RefVal::Kind& hasErr);
1697
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001698 void ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
1699 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001700 Expr* NodeExpr, Expr* ErrorExpr,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001701 ExplodedNode<GRState>* Pred,
1702 const GRState* St,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001703 RefVal::Kind hasErr, SymbolRef Sym);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001704
Ted Kremenek0106e202008-10-24 20:32:50 +00001705 std::pair<GRStateRef, bool>
1706 HandleSymbolDeath(GRStateManager& VMgr, const GRState* St,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001707 const Decl* CD, SymbolRef sid, RefVal V, bool& hasLeak);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001708
Ted Kremenekb6578942009-02-24 19:15:11 +00001709public:
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00001710 CFRefCount(ASTContext& Ctx, bool gcenabled, const LangOptions& lopts)
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001711 : Summaries(Ctx, gcenabled),
Ted Kremenek6537a642009-03-17 19:42:23 +00001712 LOpts(lopts), useAfterRelease(0), releaseNotOwned(0),
1713 deallocGC(0), deallocNotOwned(0),
Ted Kremenek708af042009-02-05 06:50:21 +00001714 leakWithinFunction(0), leakAtReturn(0), BR(0) {}
Ted Kremenek1feab292008-04-16 04:28:53 +00001715
Ted Kremenek708af042009-02-05 06:50:21 +00001716 virtual ~CFRefCount() {}
Ted Kremenek7d421f32008-04-09 23:49:11 +00001717
Ted Kremenekbf6babf2009-02-04 23:49:09 +00001718 void RegisterChecks(BugReporter &BR);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001719
Ted Kremenekb0f2b9e2008-08-16 00:49:49 +00001720 virtual void RegisterPrinters(std::vector<GRState::Printer*>& Printers) {
1721 Printers.push_back(new BindingsPrinter());
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001722 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00001723
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001724 bool isGCEnabled() const { return Summaries.isGCEnabled(); }
Ted Kremenekfe30beb2008-04-30 23:47:44 +00001725 const LangOptions& getLangOptions() const { return LOpts; }
1726
Ted Kremenekc26c4692009-02-18 03:48:14 +00001727 const RetainSummary *getSummaryOfNode(const ExplodedNode<GRState> *N) const {
1728 SummaryLogTy::const_iterator I = SummaryLog.find(N);
1729 return I == SummaryLog.end() ? 0 : I->second;
1730 }
1731
Ted Kremeneka7338b42008-03-11 06:39:11 +00001732 // Calls.
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001733
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001734 void EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001735 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001736 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001737 Expr* Ex,
1738 Expr* Receiver,
1739 RetainSummary* Summ,
Ted Kremenek2719e982008-06-17 02:43:46 +00001740 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001741 ExplodedNode<GRState>* Pred);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001742
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001743 virtual void EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekce0767f2008-03-12 21:06:49 +00001744 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001745 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001746 CallExpr* CE, SVal L,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001747 ExplodedNode<GRState>* Pred);
Ted Kremenek10fe66d2008-04-09 01:10:13 +00001748
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001749
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001750 virtual void EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001751 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001752 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001753 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001754 ExplodedNode<GRState>* Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001755
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001756 bool EvalObjCMessageExprAux(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001757 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001758 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001759 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001760 ExplodedNode<GRState>* Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001761
Ted Kremeneka42be302009-02-14 01:43:44 +00001762 // Stores.
1763 virtual void EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val);
1764
Ted Kremenekffefc352008-04-11 22:25:11 +00001765 // End-of-path.
1766
1767 virtual void EvalEndPath(GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001768 GREndPathNodeBuilder<GRState>& Builder);
Ted Kremenekffefc352008-04-11 22:25:11 +00001769
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001770 virtual void EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek541db372008-04-24 23:57:27 +00001771 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001772 GRStmtNodeBuilder<GRState>& Builder,
1773 ExplodedNode<GRState>* Pred,
Ted Kremenek5c0729b2009-01-21 22:26:05 +00001774 Stmt* S, const GRState* state,
1775 SymbolReaper& SymReaper);
1776
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001777 // Return statements.
1778
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001779 virtual void EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001780 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001781 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001782 ReturnStmt* S,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001783 ExplodedNode<GRState>* Pred);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001784
1785 // Assumptions.
1786
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001787 virtual const GRState* EvalAssume(GRStateManager& VMgr,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001788 const GRState* St, SVal Cond,
Ted Kremenekf22f8682008-07-10 22:03:41 +00001789 bool Assumption, bool& isFeasible);
Ted Kremeneka7338b42008-03-11 06:39:11 +00001790};
1791
1792} // end anonymous namespace
1793
Ted Kremenek681fb352009-03-20 17:34:15 +00001794static void PrintPool(std::ostream &Out, SymbolRef Sym, const GRState *state) {
1795 Out << ' ';
Ted Kremenek74556a12009-03-26 03:35:11 +00001796 if (Sym)
1797 Out << Sym->getSymbolID();
Ted Kremenek681fb352009-03-20 17:34:15 +00001798 else
1799 Out << "<pool>";
1800 Out << ":{";
1801
1802 // Get the contents of the pool.
1803 if (const ARCounts *cnts = state->get<AutoreleasePoolContents>(Sym))
1804 for (ARCounts::iterator J=cnts->begin(), EJ=cnts->end(); J != EJ; ++J)
1805 Out << '(' << J.getKey() << ',' << J.getData() << ')';
1806
1807 Out << '}';
1808}
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001809
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001810void CFRefCount::BindingsPrinter::Print(std::ostream& Out, const GRState* state,
1811 const char* nl, const char* sep) {
Ted Kremenek681fb352009-03-20 17:34:15 +00001812
1813
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001814
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001815 RefBindings B = state->get<RefBindings>();
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001816
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001817 if (!B.isEmpty())
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001818 Out << sep << nl;
1819
1820 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
1821 Out << (*I).first << " : ";
1822 (*I).second.print(Out);
1823 Out << nl;
1824 }
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001825
1826 // Print the autorelease stack.
Ted Kremenek681fb352009-03-20 17:34:15 +00001827 Out << sep << nl << "AR pool stack:";
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001828 ARStack stack = state->get<AutoreleaseStack>();
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001829
Ted Kremenek681fb352009-03-20 17:34:15 +00001830 PrintPool(Out, SymbolRef(), state); // Print the caller's pool.
1831 for (ARStack::iterator I=stack.begin(), E=stack.end(); I!=E; ++I)
1832 PrintPool(Out, *I, state);
1833
1834 Out << nl;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001835}
1836
Ted Kremenek47a72422009-04-29 18:50:19 +00001837//===----------------------------------------------------------------------===//
1838// Error reporting.
1839//===----------------------------------------------------------------------===//
1840
1841namespace {
1842
1843 //===-------------===//
1844 // Bug Descriptions. //
1845 //===-------------===//
1846
1847 class VISIBILITY_HIDDEN CFRefBug : public BugType {
1848 protected:
1849 CFRefCount& TF;
1850
1851 CFRefBug(CFRefCount* tf, const char* name)
1852 : BugType(name, "Memory (Core Foundation/Objective-C)"), TF(*tf) {}
1853 public:
1854
1855 CFRefCount& getTF() { return TF; }
1856 const CFRefCount& getTF() const { return TF; }
1857
1858 // FIXME: Eventually remove.
1859 virtual const char* getDescription() const = 0;
1860
1861 virtual bool isLeak() const { return false; }
1862 };
1863
1864 class VISIBILITY_HIDDEN UseAfterRelease : public CFRefBug {
1865 public:
1866 UseAfterRelease(CFRefCount* tf)
1867 : CFRefBug(tf, "Use-after-release") {}
1868
1869 const char* getDescription() const {
1870 return "Reference-counted object is used after it is released";
1871 }
1872 };
1873
1874 class VISIBILITY_HIDDEN BadRelease : public CFRefBug {
1875 public:
1876 BadRelease(CFRefCount* tf) : CFRefBug(tf, "Bad release") {}
1877
1878 const char* getDescription() const {
1879 return "Incorrect decrement of the reference count of an "
1880 "object is not owned at this point by the caller";
1881 }
1882 };
1883
1884 class VISIBILITY_HIDDEN DeallocGC : public CFRefBug {
1885 public:
1886 DeallocGC(CFRefCount *tf) : CFRefBug(tf,
1887 "-dealloc called while using GC") {}
1888
1889 const char *getDescription() const {
1890 return "-dealloc called while using GC";
1891 }
1892 };
1893
1894 class VISIBILITY_HIDDEN DeallocNotOwned : public CFRefBug {
1895 public:
1896 DeallocNotOwned(CFRefCount *tf) : CFRefBug(tf,
1897 "-dealloc sent to non-exclusively owned object") {}
1898
1899 const char *getDescription() const {
1900 return "-dealloc sent to object that may be referenced elsewhere";
1901 }
1902 };
1903
1904 class VISIBILITY_HIDDEN Leak : public CFRefBug {
1905 const bool isReturn;
1906 protected:
1907 Leak(CFRefCount* tf, const char* name, bool isRet)
1908 : CFRefBug(tf, name), isReturn(isRet) {}
1909 public:
1910
1911 const char* getDescription() const { return ""; }
1912
1913 bool isLeak() const { return true; }
1914 };
1915
1916 class VISIBILITY_HIDDEN LeakAtReturn : public Leak {
1917 public:
1918 LeakAtReturn(CFRefCount* tf, const char* name)
1919 : Leak(tf, name, true) {}
1920 };
1921
1922 class VISIBILITY_HIDDEN LeakWithinFunction : public Leak {
1923 public:
1924 LeakWithinFunction(CFRefCount* tf, const char* name)
1925 : Leak(tf, name, false) {}
1926 };
1927
1928 //===---------===//
1929 // Bug Reports. //
1930 //===---------===//
1931
1932 class VISIBILITY_HIDDEN CFRefReport : public RangedBugReport {
1933 protected:
1934 SymbolRef Sym;
1935 const CFRefCount &TF;
1936 public:
1937 CFRefReport(CFRefBug& D, const CFRefCount &tf,
1938 ExplodedNode<GRState> *n, SymbolRef sym)
1939 : RangedBugReport(D, D.getDescription(), n), Sym(sym), TF(tf) {}
1940
1941 virtual ~CFRefReport() {}
1942
1943 CFRefBug& getBugType() {
1944 return (CFRefBug&) RangedBugReport::getBugType();
1945 }
1946 const CFRefBug& getBugType() const {
1947 return (const CFRefBug&) RangedBugReport::getBugType();
1948 }
1949
1950 virtual void getRanges(BugReporter& BR, const SourceRange*& beg,
1951 const SourceRange*& end) {
1952
1953 if (!getBugType().isLeak())
1954 RangedBugReport::getRanges(BR, beg, end);
1955 else
1956 beg = end = 0;
1957 }
1958
1959 SymbolRef getSymbol() const { return Sym; }
1960
1961 PathDiagnosticPiece* getEndPath(BugReporter& BR,
1962 const ExplodedNode<GRState>* N);
1963
1964 std::pair<const char**,const char**> getExtraDescriptiveText();
1965
1966 PathDiagnosticPiece* VisitNode(const ExplodedNode<GRState>* N,
1967 const ExplodedNode<GRState>* PrevN,
1968 const ExplodedGraph<GRState>& G,
1969 BugReporter& BR,
1970 NodeResolver& NR);
1971 };
1972
1973 class VISIBILITY_HIDDEN CFRefLeakReport : public CFRefReport {
1974 SourceLocation AllocSite;
1975 const MemRegion* AllocBinding;
1976 public:
1977 CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
1978 ExplodedNode<GRState> *n, SymbolRef sym,
1979 GRExprEngine& Eng);
1980
1981 PathDiagnosticPiece* getEndPath(BugReporter& BR,
1982 const ExplodedNode<GRState>* N);
1983
1984 SourceLocation getLocation() const { return AllocSite; }
1985 };
1986} // end anonymous namespace
1987
1988void CFRefCount::RegisterChecks(BugReporter& BR) {
1989 useAfterRelease = new UseAfterRelease(this);
1990 BR.Register(useAfterRelease);
1991
1992 releaseNotOwned = new BadRelease(this);
1993 BR.Register(releaseNotOwned);
1994
1995 deallocGC = new DeallocGC(this);
1996 BR.Register(deallocGC);
1997
1998 deallocNotOwned = new DeallocNotOwned(this);
1999 BR.Register(deallocNotOwned);
2000
2001 // First register "return" leaks.
2002 const char* name = 0;
2003
2004 if (isGCEnabled())
2005 name = "Leak of returned object when using garbage collection";
2006 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2007 name = "Leak of returned object when not using garbage collection (GC) in "
2008 "dual GC/non-GC code";
2009 else {
2010 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2011 name = "Leak of returned object";
2012 }
2013
2014 leakAtReturn = new LeakAtReturn(this, name);
2015 BR.Register(leakAtReturn);
2016
2017 // Second, register leaks within a function/method.
2018 if (isGCEnabled())
2019 name = "Leak of object when using garbage collection";
2020 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2021 name = "Leak of object when not using garbage collection (GC) in "
2022 "dual GC/non-GC code";
2023 else {
2024 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2025 name = "Leak";
2026 }
2027
2028 leakWithinFunction = new LeakWithinFunction(this, name);
2029 BR.Register(leakWithinFunction);
2030
2031 // Save the reference to the BugReporter.
2032 this->BR = &BR;
2033}
2034
2035static const char* Msgs[] = {
2036 // GC only
2037 "Code is compiled to only use garbage collection",
2038 // No GC.
2039 "Code is compiled to use reference counts",
2040 // Hybrid, with GC.
2041 "Code is compiled to use either garbage collection (GC) or reference counts"
2042 " (non-GC). The bug occurs with GC enabled",
2043 // Hybrid, without GC
2044 "Code is compiled to use either garbage collection (GC) or reference counts"
2045 " (non-GC). The bug occurs in non-GC mode"
2046};
2047
2048std::pair<const char**,const char**> CFRefReport::getExtraDescriptiveText() {
2049 CFRefCount& TF = static_cast<CFRefBug&>(getBugType()).getTF();
2050
2051 switch (TF.getLangOptions().getGCMode()) {
2052 default:
2053 assert(false);
2054
2055 case LangOptions::GCOnly:
2056 assert (TF.isGCEnabled());
2057 return std::make_pair(&Msgs[0], &Msgs[0]+1);
2058
2059 case LangOptions::NonGC:
2060 assert (!TF.isGCEnabled());
2061 return std::make_pair(&Msgs[1], &Msgs[1]+1);
2062
2063 case LangOptions::HybridGC:
2064 if (TF.isGCEnabled())
2065 return std::make_pair(&Msgs[2], &Msgs[2]+1);
2066 else
2067 return std::make_pair(&Msgs[3], &Msgs[3]+1);
2068 }
2069}
2070
2071static inline bool contains(const llvm::SmallVectorImpl<ArgEffect>& V,
2072 ArgEffect X) {
2073 for (llvm::SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
2074 I!=E; ++I)
2075 if (*I == X) return true;
2076
2077 return false;
2078}
2079
2080PathDiagnosticPiece* CFRefReport::VisitNode(const ExplodedNode<GRState>* N,
2081 const ExplodedNode<GRState>* PrevN,
2082 const ExplodedGraph<GRState>& G,
2083 BugReporter& BR,
2084 NodeResolver& NR) {
2085
2086 // Check if the type state has changed.
2087 GRStateManager &StMgr = cast<GRBugReporter>(BR).getStateManager();
2088 GRStateRef PrevSt(PrevN->getState(), StMgr);
2089 GRStateRef CurrSt(N->getState(), StMgr);
2090
2091 const RefVal* CurrT = CurrSt.get<RefBindings>(Sym);
2092 if (!CurrT) return NULL;
2093
2094 const RefVal& CurrV = *CurrT;
2095 const RefVal* PrevT = PrevSt.get<RefBindings>(Sym);
2096
2097 // Create a string buffer to constain all the useful things we want
2098 // to tell the user.
2099 std::string sbuf;
2100 llvm::raw_string_ostream os(sbuf);
2101
2102 // This is the allocation site since the previous node had no bindings
2103 // for this symbol.
2104 if (!PrevT) {
2105 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2106
2107 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2108 // Get the name of the callee (if it is available).
2109 SVal X = CurrSt.GetSValAsScalarOrLoc(CE->getCallee());
2110 if (const FunctionDecl* FD = X.getAsFunctionDecl())
2111 os << "Call to function '" << FD->getNameAsString() <<'\'';
2112 else
2113 os << "function call";
2114 }
2115 else {
2116 assert (isa<ObjCMessageExpr>(S));
2117 os << "Method";
2118 }
2119
2120 if (CurrV.getObjKind() == RetEffect::CF) {
2121 os << " returns a Core Foundation object with a ";
2122 }
2123 else {
2124 assert (CurrV.getObjKind() == RetEffect::ObjC);
2125 os << " returns an Objective-C object with a ";
2126 }
2127
2128 if (CurrV.isOwned()) {
2129 os << "+1 retain count (owning reference).";
2130
2131 if (static_cast<CFRefBug&>(getBugType()).getTF().isGCEnabled()) {
2132 assert(CurrV.getObjKind() == RetEffect::CF);
2133 os << " "
2134 "Core Foundation objects are not automatically garbage collected.";
2135 }
2136 }
2137 else {
2138 assert (CurrV.isNotOwned());
2139 os << "+0 retain count (non-owning reference).";
2140 }
2141
2142 PathDiagnosticLocation Pos(S, BR.getContext().getSourceManager());
2143 return new PathDiagnosticEventPiece(Pos, os.str());
2144 }
2145
2146 // Gather up the effects that were performed on the object at this
2147 // program point
2148 llvm::SmallVector<ArgEffect, 2> AEffects;
2149
2150 if (const RetainSummary *Summ = TF.getSummaryOfNode(NR.getOriginalNode(N))) {
2151 // We only have summaries attached to nodes after evaluating CallExpr and
2152 // ObjCMessageExprs.
2153 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2154
2155 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2156 // Iterate through the parameter expressions and see if the symbol
2157 // was ever passed as an argument.
2158 unsigned i = 0;
2159
2160 for (CallExpr::arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
2161 AI!=AE; ++AI, ++i) {
2162
2163 // Retrieve the value of the argument. Is it the symbol
2164 // we are interested in?
2165 if (CurrSt.GetSValAsScalarOrLoc(*AI).getAsLocSymbol() != Sym)
2166 continue;
2167
2168 // We have an argument. Get the effect!
2169 AEffects.push_back(Summ->getArg(i));
2170 }
2171 }
2172 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
2173 if (Expr *receiver = ME->getReceiver())
2174 if (CurrSt.GetSValAsScalarOrLoc(receiver).getAsLocSymbol() == Sym) {
2175 // The symbol we are tracking is the receiver.
2176 AEffects.push_back(Summ->getReceiverEffect());
2177 }
2178 }
2179 }
2180
2181 do {
2182 // Get the previous type state.
2183 RefVal PrevV = *PrevT;
2184
2185 // Specially handle -dealloc.
2186 if (!TF.isGCEnabled() && contains(AEffects, Dealloc)) {
2187 // Determine if the object's reference count was pushed to zero.
2188 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2189 // We may not have transitioned to 'release' if we hit an error.
2190 // This case is handled elsewhere.
2191 if (CurrV.getKind() == RefVal::Released) {
2192 assert(CurrV.getCount() == 0);
2193 os << "Object released by directly sending the '-dealloc' message";
2194 break;
2195 }
2196 }
2197
2198 // Specially handle CFMakeCollectable and friends.
2199 if (contains(AEffects, MakeCollectable)) {
2200 // Get the name of the function.
2201 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2202 SVal X = CurrSt.GetSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee());
2203 const FunctionDecl* FD = X.getAsFunctionDecl();
2204 const std::string& FName = FD->getNameAsString();
2205
2206 if (TF.isGCEnabled()) {
2207 // Determine if the object's reference count was pushed to zero.
2208 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2209
2210 os << "In GC mode a call to '" << FName
2211 << "' decrements an object's retain count and registers the "
2212 "object with the garbage collector. ";
2213
2214 if (CurrV.getKind() == RefVal::Released) {
2215 assert(CurrV.getCount() == 0);
2216 os << "Since it now has a 0 retain count the object can be "
2217 "automatically collected by the garbage collector.";
2218 }
2219 else
2220 os << "An object must have a 0 retain count to be garbage collected. "
2221 "After this call its retain count is +" << CurrV.getCount()
2222 << '.';
2223 }
2224 else
2225 os << "When GC is not enabled a call to '" << FName
2226 << "' has no effect on its argument.";
2227
2228 // Nothing more to say.
2229 break;
2230 }
2231
2232 // Determine if the typestate has changed.
2233 if (!(PrevV == CurrV))
2234 switch (CurrV.getKind()) {
2235 case RefVal::Owned:
2236 case RefVal::NotOwned:
2237
2238 if (PrevV.getCount() == CurrV.getCount())
2239 return 0;
2240
2241 if (PrevV.getCount() > CurrV.getCount())
2242 os << "Reference count decremented.";
2243 else
2244 os << "Reference count incremented.";
2245
2246 if (unsigned Count = CurrV.getCount())
2247 os << " The object now has a +" << Count << " retain count.";
2248
2249 if (PrevV.getKind() == RefVal::Released) {
2250 assert(TF.isGCEnabled() && CurrV.getCount() > 0);
2251 os << " The object is not eligible for garbage collection until the "
2252 "retain count reaches 0 again.";
2253 }
2254
2255 break;
2256
2257 case RefVal::Released:
2258 os << "Object released.";
2259 break;
2260
2261 case RefVal::ReturnedOwned:
2262 os << "Object returned to caller as an owning reference (single retain "
2263 "count transferred to caller).";
2264 break;
2265
2266 case RefVal::ReturnedNotOwned:
2267 os << "Object returned to caller with a +0 (non-owning) retain count.";
2268 break;
2269
2270 default:
2271 return NULL;
2272 }
2273
2274 // Emit any remaining diagnostics for the argument effects (if any).
2275 for (llvm::SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
2276 E=AEffects.end(); I != E; ++I) {
2277
2278 // A bunch of things have alternate behavior under GC.
2279 if (TF.isGCEnabled())
2280 switch (*I) {
2281 default: break;
2282 case Autorelease:
2283 os << "In GC mode an 'autorelease' has no effect.";
2284 continue;
2285 case IncRefMsg:
2286 os << "In GC mode the 'retain' message has no effect.";
2287 continue;
2288 case DecRefMsg:
2289 os << "In GC mode the 'release' message has no effect.";
2290 continue;
2291 }
2292 }
2293 } while(0);
2294
2295 if (os.str().empty())
2296 return 0; // We have nothing to say!
2297
2298 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2299 PathDiagnosticLocation Pos(S, BR.getContext().getSourceManager());
2300 PathDiagnosticPiece* P = new PathDiagnosticEventPiece(Pos, os.str());
2301
2302 // Add the range by scanning the children of the statement for any bindings
2303 // to Sym.
2304 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I)
2305 if (Expr* Exp = dyn_cast_or_null<Expr>(*I))
2306 if (CurrSt.GetSValAsScalarOrLoc(Exp).getAsLocSymbol() == Sym) {
2307 P->addRange(Exp->getSourceRange());
2308 break;
2309 }
2310
2311 return P;
2312}
2313
2314namespace {
2315 class VISIBILITY_HIDDEN FindUniqueBinding :
2316 public StoreManager::BindingsHandler {
2317 SymbolRef Sym;
2318 const MemRegion* Binding;
2319 bool First;
2320
2321 public:
2322 FindUniqueBinding(SymbolRef sym) : Sym(sym), Binding(0), First(true) {}
2323
2324 bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
2325 SVal val) {
2326
2327 SymbolRef SymV = val.getAsSymbol();
2328 if (!SymV || SymV != Sym)
2329 return true;
2330
2331 if (Binding) {
2332 First = false;
2333 return false;
2334 }
2335 else
2336 Binding = R;
2337
2338 return true;
2339 }
2340
2341 operator bool() { return First && Binding; }
2342 const MemRegion* getRegion() { return Binding; }
2343 };
2344}
2345
2346static std::pair<const ExplodedNode<GRState>*,const MemRegion*>
2347GetAllocationSite(GRStateManager& StateMgr, const ExplodedNode<GRState>* N,
2348 SymbolRef Sym) {
2349
2350 // Find both first node that referred to the tracked symbol and the
2351 // memory location that value was store to.
2352 const ExplodedNode<GRState>* Last = N;
2353 const MemRegion* FirstBinding = 0;
2354
2355 while (N) {
2356 const GRState* St = N->getState();
2357 RefBindings B = St->get<RefBindings>();
2358
2359 if (!B.lookup(Sym))
2360 break;
2361
2362 FindUniqueBinding FB(Sym);
2363 StateMgr.iterBindings(St, FB);
2364 if (FB) FirstBinding = FB.getRegion();
2365
2366 Last = N;
2367 N = N->pred_empty() ? NULL : *(N->pred_begin());
2368 }
2369
2370 return std::make_pair(Last, FirstBinding);
2371}
2372
2373PathDiagnosticPiece*
2374CFRefReport::getEndPath(BugReporter& br, const ExplodedNode<GRState>* EndN) {
2375 // Tell the BugReporter to report cases when the tracked symbol is
2376 // assigned to different variables, etc.
2377 GRBugReporter& BR = cast<GRBugReporter>(br);
2378 cast<GRBugReporter>(BR).addNotableSymbol(Sym);
2379 return RangedBugReport::getEndPath(BR, EndN);
2380}
2381
2382PathDiagnosticPiece*
2383CFRefLeakReport::getEndPath(BugReporter& br, const ExplodedNode<GRState>* EndN){
2384
2385 GRBugReporter& BR = cast<GRBugReporter>(br);
2386 // Tell the BugReporter to report cases when the tracked symbol is
2387 // assigned to different variables, etc.
2388 cast<GRBugReporter>(BR).addNotableSymbol(Sym);
2389
2390 // We are reporting a leak. Walk up the graph to get to the first node where
2391 // the symbol appeared, and also get the first VarDecl that tracked object
2392 // is stored to.
2393 const ExplodedNode<GRState>* AllocNode = 0;
2394 const MemRegion* FirstBinding = 0;
2395
2396 llvm::tie(AllocNode, FirstBinding) =
2397 GetAllocationSite(BR.getStateManager(), EndN, Sym);
2398
2399 // Get the allocate site.
2400 assert(AllocNode);
2401 Stmt* FirstStmt = cast<PostStmt>(AllocNode->getLocation()).getStmt();
2402
2403 SourceManager& SMgr = BR.getContext().getSourceManager();
2404 unsigned AllocLine =SMgr.getInstantiationLineNumber(FirstStmt->getLocStart());
2405
2406 // Compute an actual location for the leak. Sometimes a leak doesn't
2407 // occur at an actual statement (e.g., transition between blocks; end
2408 // of function) so we need to walk the graph and compute a real location.
2409 const ExplodedNode<GRState>* LeakN = EndN;
2410 PathDiagnosticLocation L;
2411
2412 while (LeakN) {
2413 ProgramPoint P = LeakN->getLocation();
2414
2415 if (const PostStmt *PS = dyn_cast<PostStmt>(&P)) {
2416 L = PathDiagnosticLocation(PS->getStmt()->getLocStart(), SMgr);
2417 break;
2418 }
2419 else if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
2420 if (const Stmt* Term = BE->getSrc()->getTerminator()) {
2421 L = PathDiagnosticLocation(Term->getLocStart(), SMgr);
2422 break;
2423 }
2424 }
2425
2426 LeakN = LeakN->succ_empty() ? 0 : *(LeakN->succ_begin());
2427 }
2428
2429 if (!L.isValid()) {
Ted Kremenek0a6913d2009-04-29 21:31:59 +00002430 const Decl &D = BR.getStateManager().getCodeDecl();
2431 L = PathDiagnosticLocation(D.getBodyRBrace(BR.getContext()), SMgr);
Ted Kremenek47a72422009-04-29 18:50:19 +00002432 }
2433
2434 std::string sbuf;
2435 llvm::raw_string_ostream os(sbuf);
2436
2437 os << "Object allocated on line " << AllocLine;
2438
2439 if (FirstBinding)
2440 os << " and stored into '" << FirstBinding->getString() << '\'';
2441
2442 // Get the retain count.
2443 const RefVal* RV = EndN->getState()->get<RefBindings>(Sym);
2444
2445 if (RV->getKind() == RefVal::ErrorLeakReturned) {
2446 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
2447 // ojbects. Only "copy", "alloc", "retain" and "new" transfer ownership
2448 // to the caller for NS objects.
2449 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(BR.getGraph().getCodeDecl());
2450 os << " is returned from a method whose name ('"
2451 << MD.getSelector().getAsString()
2452 << "') does not contain 'copy' or otherwise starts with"
2453 " 'new' or 'alloc'. This violates the naming convention rules given"
Ted Kremenek2a410c92009-04-29 22:25:52 +00002454 " in the Memory Management Guide for Cocoa (object leaked)";
Ted Kremenek47a72422009-04-29 18:50:19 +00002455 }
2456 else
2457 os << " is no longer referenced after this point and has a retain count of"
Ted Kremenek2a410c92009-04-29 22:25:52 +00002458 " +" << RV->getCount() << " (object leaked)";
Ted Kremenek47a72422009-04-29 18:50:19 +00002459
2460 return new PathDiagnosticEventPiece(L, os.str());
2461}
2462
2463
2464CFRefLeakReport::CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2465 ExplodedNode<GRState> *n,
2466 SymbolRef sym, GRExprEngine& Eng)
2467: CFRefReport(D, tf, n, sym)
2468{
2469
2470 // Most bug reports are cached at the location where they occured.
2471 // With leaks, we want to unique them by the location where they were
2472 // allocated, and only report a single path. To do this, we need to find
2473 // the allocation site of a piece of tracked memory, which we do via a
2474 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2475 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2476 // that all ancestor nodes that represent the allocation site have the
2477 // same SourceLocation.
2478 const ExplodedNode<GRState>* AllocNode = 0;
2479
2480 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding.
2481 GetAllocationSite(Eng.getStateManager(), getEndNode(), getSymbol());
2482
2483 // Get the SourceLocation for the allocation site.
2484 ProgramPoint P = AllocNode->getLocation();
2485 AllocSite = cast<PostStmt>(P).getStmt()->getLocStart();
2486
2487 // Fill in the description of the bug.
2488 Description.clear();
2489 llvm::raw_string_ostream os(Description);
2490 SourceManager& SMgr = Eng.getContext().getSourceManager();
2491 unsigned AllocLine = SMgr.getInstantiationLineNumber(AllocSite);
2492 os << "Potential leak of object allocated on line " << AllocLine;
2493
2494 // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2495 if (AllocBinding)
2496 os << " and stored into '" << AllocBinding->getString() << '\'';
2497}
2498
2499//===----------------------------------------------------------------------===//
2500// Main checker logic.
2501//===----------------------------------------------------------------------===//
2502
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002503static inline ArgEffect GetArgE(RetainSummary* Summ, unsigned idx) {
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00002504 return Summ ? Summ->getArg(idx) : MayEscape;
Ted Kremenek455dd862008-04-11 20:23:24 +00002505}
2506
Ted Kremenek266d8b62008-05-06 02:26:56 +00002507static inline RetEffect GetRetEffect(RetainSummary* Summ) {
2508 return Summ ? Summ->getRetEffect() : RetEffect::MakeNoRet();
Ted Kremenek455dd862008-04-11 20:23:24 +00002509}
2510
Ted Kremenek227c5372008-05-06 02:41:27 +00002511static inline ArgEffect GetReceiverE(RetainSummary* Summ) {
2512 return Summ ? Summ->getReceiverEffect() : DoNothing;
2513}
2514
Ted Kremenekf2717b02008-07-18 17:24:20 +00002515static inline bool IsEndPath(RetainSummary* Summ) {
2516 return Summ ? Summ->isEndPath() : false;
2517}
2518
Ted Kremenek1feab292008-04-16 04:28:53 +00002519
Ted Kremenek272aa852008-06-25 21:21:56 +00002520/// GetReturnType - Used to get the return type of a message expression or
2521/// function call with the intention of affixing that type to a tracked symbol.
2522/// While the the return type can be queried directly from RetEx, when
2523/// invoking class methods we augment to the return type to be that of
2524/// a pointer to the class (as opposed it just being id).
2525static QualType GetReturnType(Expr* RetE, ASTContext& Ctx) {
2526
2527 QualType RetTy = RetE->getType();
2528
2529 // FIXME: We aren't handling id<...>.
Chris Lattnerb724ab22008-07-26 22:36:27 +00002530 const PointerType* PT = RetTy->getAsPointerType();
Ted Kremenek272aa852008-06-25 21:21:56 +00002531 if (!PT)
2532 return RetTy;
2533
2534 // If RetEx is not a message expression just return its type.
2535 // If RetEx is a message expression, return its types if it is something
2536 /// more specific than id.
2537
2538 ObjCMessageExpr* ME = dyn_cast<ObjCMessageExpr>(RetE);
2539
Steve Naroff17c03822009-02-12 17:52:19 +00002540 if (!ME || !Ctx.isObjCIdStructType(PT->getPointeeType()))
Ted Kremenek272aa852008-06-25 21:21:56 +00002541 return RetTy;
2542
2543 ObjCInterfaceDecl* D = ME->getClassInfo().first;
2544
2545 // At this point we know the return type of the message expression is id.
2546 // If we have an ObjCInterceDecl, we know this is a call to a class method
2547 // whose type we can resolve. In such cases, promote the return type to
2548 // Class*.
2549 return !D ? RetTy : Ctx.getPointerType(Ctx.getObjCInterfaceType(D));
2550}
2551
2552
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002553void CFRefCount::EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002554 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002555 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002556 Expr* Ex,
2557 Expr* Receiver,
2558 RetainSummary* Summ,
Zhongxing Xucac107a2009-04-20 05:24:46 +00002559 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002560 ExplodedNode<GRState>* Pred) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002561
Ted Kremeneka7338b42008-03-11 06:39:11 +00002562 // Get the state.
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002563 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenek0106e202008-10-24 20:32:50 +00002564 ASTContext& Ctx = Eng.getStateManager().getContext();
Ted Kremenek227c5372008-05-06 02:41:27 +00002565
2566 // Evaluate the effect of the arguments.
Ted Kremenek1feab292008-04-16 04:28:53 +00002567 RefVal::Kind hasErr = (RefVal::Kind) 0;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002568 unsigned idx = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002569 Expr* ErrorExpr = NULL;
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002570 SymbolRef ErrorSym = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002571
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002572 for (ExprIterator I = arg_beg; I != arg_end; ++I, ++idx) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002573 SVal V = state.GetSValAsScalarOrLoc(*I);
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002574 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002575
Ted Kremenek74556a12009-03-26 03:35:11 +00002576 if (Sym)
Ted Kremenekb6578942009-02-24 19:15:11 +00002577 if (RefBindings::data_type* T = state.get<RefBindings>(Sym)) {
2578 state = Update(state, Sym, *T, GetArgE(Summ, idx), hasErr);
2579 if (hasErr) {
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002580 ErrorExpr = *I;
Ted Kremenek6064a362008-07-07 16:21:19 +00002581 ErrorSym = Sym;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00002582 break;
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002583 }
2584 continue;
Ted Kremenekb6578942009-02-24 19:15:11 +00002585 }
Ted Kremenekede40b72008-07-09 18:11:16 +00002586
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002587 if (isa<Loc>(V)) {
2588 if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(&V)) {
Ted Kremenekede40b72008-07-09 18:11:16 +00002589 if (GetArgE(Summ, idx) == DoNothingByRef)
2590 continue;
2591
2592 // Invalidate the value of the variable passed by reference.
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002593
2594 // FIXME: Either this logic should also be replicated in GRSimpleVals
2595 // or should be pulled into a separate "constraint engine."
Ted Kremenekede40b72008-07-09 18:11:16 +00002596
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002597 // FIXME: We can have collisions on the conjured symbol if the
2598 // expression *I also creates conjured symbols. We probably want
2599 // to identify conjured symbols by an expression pair: the enclosing
2600 // expression (the context) and the expression itself. This should
Ted Kremenekede40b72008-07-09 18:11:16 +00002601 // disambiguate conjured symbols.
Ted Kremenekb15eba42008-10-04 05:50:14 +00002602
Ted Kremenek38a4b4b2008-10-17 20:28:54 +00002603 const TypedRegion* R = dyn_cast<TypedRegion>(MR->getRegion());
Zhongxing Xub9d47a42009-04-29 02:30:09 +00002604
Ted Kremenek53b24182009-03-04 22:56:43 +00002605 if (R) {
Ted Kremenek618c6cd2008-12-18 23:34:57 +00002606 // Is the invalidated variable something that we were tracking?
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002607 SymbolRef Sym = state.GetSValAsScalarOrLoc(R).getAsLocSymbol();
Ted Kremenek618c6cd2008-12-18 23:34:57 +00002608
Ted Kremenek53b24182009-03-04 22:56:43 +00002609 // Remove any existing reference-count binding.
Ted Kremenek74556a12009-03-26 03:35:11 +00002610 if (Sym) state = state.remove<RefBindings>(Sym);
Ted Kremenekb15eba42008-10-04 05:50:14 +00002611
Ted Kremenek53b24182009-03-04 22:56:43 +00002612 if (R->isBoundable(Ctx)) {
2613 // Set the value of the variable to be a conjured symbol.
2614 unsigned Count = Builder.getCurrentBlockCount();
2615 QualType T = R->getRValueType(Ctx);
2616
Zhongxing Xu079dc352009-04-09 06:03:54 +00002617 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())){
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002618 ValueManager &ValMgr = Eng.getValueManager();
2619 SVal V = ValMgr.getConjuredSymbolVal(*I, T, Count);
Zhongxing Xu079dc352009-04-09 06:03:54 +00002620 state = state.BindLoc(Loc::MakeVal(R), V);
Ted Kremenek53b24182009-03-04 22:56:43 +00002621 }
2622 else if (const RecordType *RT = T->getAsStructureType()) {
2623 // Handle structs in a not so awesome way. Here we just
2624 // eagerly bind new symbols to the fields. In reality we
2625 // should have the store manager handle this. The idea is just
2626 // to prototype some basic functionality here. All of this logic
2627 // should one day soon just go away.
2628 const RecordDecl *RD = RT->getDecl()->getDefinition(Ctx);
2629
2630 // No record definition. There is nothing we can do.
2631 if (!RD)
2632 continue;
2633
2634 MemRegionManager &MRMgr = state.getManager().getRegionManager();
2635
2636 // Iterate through the fields and construct new symbols.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002637 for (RecordDecl::field_iterator FI=RD->field_begin(Ctx),
2638 FE=RD->field_end(Ctx); FI!=FE; ++FI) {
Ted Kremenek53b24182009-03-04 22:56:43 +00002639
2640 // For now just handle scalar fields.
2641 FieldDecl *FD = *FI;
2642 QualType FT = FD->getType();
2643
2644 if (Loc::IsLocType(FT) ||
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002645 (FT->isIntegerType() && FT->isScalarType())) {
Ted Kremenek53b24182009-03-04 22:56:43 +00002646 const FieldRegion* FR = MRMgr.getFieldRegion(FD, R);
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002647 ValueManager &ValMgr = Eng.getValueManager();
2648 SVal V = ValMgr.getConjuredSymbolVal(*I, FT, Count);
Zhongxing Xuc458e322009-04-09 06:32:20 +00002649 state = state.BindLoc(Loc::MakeVal(FR), V);
Ted Kremenek53b24182009-03-04 22:56:43 +00002650 }
2651 }
2652 }
2653 else {
2654 // Just blast away other values.
2655 state = state.BindLoc(*MR, UnknownVal());
2656 }
Ted Kremenek8f90e712008-10-17 22:23:12 +00002657 }
Ted Kremenekb15eba42008-10-04 05:50:14 +00002658 }
2659 else
Ted Kremenek09102db2008-11-12 19:22:09 +00002660 state = state.BindLoc(*MR, UnknownVal());
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002661 }
2662 else {
2663 // Nuke all other arguments passed by reference.
Zhongxing Xu097fc982008-10-17 05:57:07 +00002664 state = state.Unbind(cast<Loc>(V));
Ted Kremenek852e3ca2008-07-03 23:26:32 +00002665 }
Ted Kremeneke4924202008-04-11 20:51:02 +00002666 }
Zhongxing Xu097fc982008-10-17 05:57:07 +00002667 else if (isa<nonloc::LocAsInteger>(V))
2668 state = state.Unbind(cast<nonloc::LocAsInteger>(V).getLoc());
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002669 }
Ted Kremenek1feab292008-04-16 04:28:53 +00002670
Ted Kremenek272aa852008-06-25 21:21:56 +00002671 // Evaluate the effect on the message receiver.
Ted Kremenek227c5372008-05-06 02:41:27 +00002672 if (!ErrorExpr && Receiver) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002673 SymbolRef Sym = state.GetSValAsScalarOrLoc(Receiver).getAsLocSymbol();
Ted Kremenek74556a12009-03-26 03:35:11 +00002674 if (Sym) {
Ted Kremenekb6578942009-02-24 19:15:11 +00002675 if (const RefVal* T = state.get<RefBindings>(Sym)) {
2676 state = Update(state, Sym, *T, GetReceiverE(Summ), hasErr);
2677 if (hasErr) {
Ted Kremenek227c5372008-05-06 02:41:27 +00002678 ErrorExpr = Receiver;
Ted Kremenek6064a362008-07-07 16:21:19 +00002679 ErrorSym = Sym;
Ted Kremenek227c5372008-05-06 02:41:27 +00002680 }
Ted Kremenekb6578942009-02-24 19:15:11 +00002681 }
Ted Kremenek227c5372008-05-06 02:41:27 +00002682 }
2683 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002684
Ted Kremenek272aa852008-06-25 21:21:56 +00002685 // Process any errors.
Ted Kremenek1feab292008-04-16 04:28:53 +00002686 if (hasErr) {
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002687 ProcessNonLeakError(Dst, Builder, Ex, ErrorExpr, Pred, state,
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002688 hasErr, ErrorSym);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002689 return;
Ted Kremenek0d721572008-03-11 17:48:22 +00002690 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002691
Ted Kremenekf2717b02008-07-18 17:24:20 +00002692 // Consult the summary for the return value.
Ted Kremenek266d8b62008-05-06 02:26:56 +00002693 RetEffect RE = GetRetEffect(Summ);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002694
2695 switch (RE.getKind()) {
2696 default:
2697 assert (false && "Unhandled RetEffect."); break;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002698
Ted Kremenek8f90e712008-10-17 22:23:12 +00002699 case RetEffect::NoRet: {
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002700
Ted Kremenek455dd862008-04-11 20:23:24 +00002701 // Make up a symbol for the return value (not reference counted).
Ted Kremeneke4924202008-04-11 20:51:02 +00002702 // FIXME: This is basically copy-and-paste from GRSimpleVals. We
2703 // should compose behavior, not copy it.
Ted Kremenek455dd862008-04-11 20:23:24 +00002704
Ted Kremenek8f90e712008-10-17 22:23:12 +00002705 // FIXME: We eventually should handle structs and other compound types
2706 // that are returned by value.
2707
2708 QualType T = Ex->getType();
2709
Ted Kremenek79413a52008-11-13 06:10:40 +00002710 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())) {
Ted Kremenek455dd862008-04-11 20:23:24 +00002711 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00002712 ValueManager &ValMgr = Eng.getValueManager();
2713 SVal X = ValMgr.getConjuredSymbolVal(Ex, T, Count);
Ted Kremenek09102db2008-11-12 19:22:09 +00002714 state = state.BindExpr(Ex, X, false);
Ted Kremenek455dd862008-04-11 20:23:24 +00002715 }
2716
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002717 break;
Ted Kremenek8f90e712008-10-17 22:23:12 +00002718 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002719
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002720 case RetEffect::Alias: {
Ted Kremenek272aa852008-06-25 21:21:56 +00002721 unsigned idx = RE.getIndex();
Ted Kremenek2719e982008-06-17 02:43:46 +00002722 assert (arg_end >= arg_beg);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002723 assert (idx < (unsigned) (arg_end - arg_beg));
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002724 SVal V = state.GetSValAsScalarOrLoc(*(arg_beg+idx));
Ted Kremenek09102db2008-11-12 19:22:09 +00002725 state = state.BindExpr(Ex, V, false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002726 break;
2727 }
2728
Ted Kremenek227c5372008-05-06 02:41:27 +00002729 case RetEffect::ReceiverAlias: {
2730 assert (Receiver);
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002731 SVal V = state.GetSValAsScalarOrLoc(Receiver);
Ted Kremenek09102db2008-11-12 19:22:09 +00002732 state = state.BindExpr(Ex, V, false);
Ted Kremenek227c5372008-05-06 02:41:27 +00002733 break;
2734 }
2735
Ted Kremenek6a1cc252008-06-23 18:02:52 +00002736 case RetEffect::OwnedAllocatedSymbol:
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002737 case RetEffect::OwnedSymbol: {
2738 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke9e726e2009-04-09 16:13:17 +00002739 ValueManager &ValMgr = Eng.getValueManager();
2740 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
2741 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
2742 state = state.set<RefBindings>(Sym, RefVal::makeOwned(RE.getObjKind(),
2743 RetT));
2744 state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenek45c52a12009-03-09 22:46:49 +00002745
2746 // FIXME: Add a flag to the checker where allocations are assumed to
2747 // *not fail.
2748#if 0
Ted Kremeneke62fd052009-01-28 22:27:59 +00002749 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) {
2750 bool isFeasible;
2751 state = state.Assume(loc::SymbolVal(Sym), true, isFeasible);
2752 assert(isFeasible && "Cannot assume fresh symbol is non-null.");
2753 }
Ted Kremenek45c52a12009-03-09 22:46:49 +00002754#endif
Ted Kremenek6a1cc252008-06-23 18:02:52 +00002755
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002756 break;
2757 }
Ted Kremenek382fb4e2009-04-27 19:14:45 +00002758
2759 case RetEffect::GCNotOwnedSymbol:
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002760 case RetEffect::NotOwnedSymbol: {
2761 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke9e726e2009-04-09 16:13:17 +00002762 ValueManager &ValMgr = Eng.getValueManager();
2763 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
2764 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
2765 state = state.set<RefBindings>(Sym, RefVal::makeNotOwned(RE.getObjKind(),
2766 RetT));
2767 state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002768 break;
2769 }
2770 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002771
Ted Kremenek0dd65012009-02-18 02:00:25 +00002772 // Generate a sink node if we are at the end of a path.
2773 GRExprEngine::NodeTy *NewNode =
2774 IsEndPath(Summ) ? Builder.MakeSinkNode(Dst, Ex, Pred, state)
2775 : Builder.MakeNode(Dst, Ex, Pred, state);
2776
2777 // Annotate the edge with summary we used.
2778 // FIXME: This assumes that we always use the same summary when generating
2779 // this node.
2780 if (NewNode) SummaryLog[NewNode] = Summ;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002781}
2782
2783
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002784void CFRefCount::EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002785 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002786 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu097fc982008-10-17 05:57:07 +00002787 CallExpr* CE, SVal L,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002788 ExplodedNode<GRState>* Pred) {
Zhongxing Xucac107a2009-04-20 05:24:46 +00002789 const FunctionDecl* FD = L.getAsFunctionDecl();
2790 RetainSummary* Summ = !FD ? 0
2791 : Summaries.getSummary(const_cast<FunctionDecl*>(FD));
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002792
2793 EvalSummary(Dst, Eng, Builder, CE, 0, Summ,
2794 CE->arg_begin(), CE->arg_end(), Pred);
Ted Kremenek827f93b2008-03-06 00:08:09 +00002795}
Ted Kremeneka7338b42008-03-11 06:39:11 +00002796
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002797void CFRefCount::EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002798 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002799 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002800 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002801 ExplodedNode<GRState>* Pred) {
Ted Kremenek926abf22008-05-06 04:20:12 +00002802 RetainSummary* Summ;
Ted Kremenek33661802008-05-01 21:31:50 +00002803
Ted Kremenek272aa852008-06-25 21:21:56 +00002804 if (Expr* Receiver = ME->getReceiver()) {
2805 // We need the type-information of the tracked receiver object
2806 // Retrieve it from the state.
2807 ObjCInterfaceDecl* ID = 0;
2808
2809 // FIXME: Wouldn't it be great if this code could be reduced? It's just
2810 // a chain of lookups.
Ted Kremeneka821b792009-04-29 05:04:30 +00002811 // FIXME: Is this really working as expected? There are cases where
2812 // we just use the 'ID' from the message expression.
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002813 const GRState* St = Builder.GetState(Pred);
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002814 SVal V = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
Ted Kremenek272aa852008-06-25 21:21:56 +00002815
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002816 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenek74556a12009-03-26 03:35:11 +00002817 if (Sym) {
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002818 if (const RefVal* T = St->get<RefBindings>(Sym)) {
Ted Kremenek6064a362008-07-07 16:21:19 +00002819 QualType Ty = T->getType();
Ted Kremenek272aa852008-06-25 21:21:56 +00002820
2821 if (const PointerType* PT = Ty->getAsPointerType()) {
2822 QualType PointeeTy = PT->getPointeeType();
2823
2824 if (ObjCInterfaceType* IT = dyn_cast<ObjCInterfaceType>(PointeeTy))
2825 ID = IT->getDecl();
2826 }
2827 }
2828 }
2829
Ted Kremenek04e00302009-04-29 17:09:14 +00002830 // FIXME: The receiver could be a reference to a class, meaning that
2831 // we should use the class method.
2832 Summ = Summaries.getInstanceMethodSummary(ME, ID);
Ted Kremenek0106e202008-10-24 20:32:50 +00002833
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002834 // Special-case: are we sending a mesage to "self"?
2835 // This is a hack. When we have full-IP this should be removed.
2836 if (!Summ) {
2837 ObjCMethodDecl* MD =
2838 dyn_cast<ObjCMethodDecl>(&Eng.getGraph().getCodeDecl());
2839
2840 if (MD) {
2841 if (Expr* Receiver = ME->getReceiver()) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002842 SVal X = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002843 if (loc::MemRegionVal* L = dyn_cast<loc::MemRegionVal>(&X))
Ted Kremenek0106e202008-10-24 20:32:50 +00002844 if (L->getRegion() == Eng.getStateManager().getSelfRegion(St)) {
2845 // Create a summmary where all of the arguments "StopTracking".
2846 Summ = Summaries.getPersistentSummary(RetEffect::MakeNoRet(),
2847 DoNothing,
2848 StopTracking);
2849 }
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002850 }
2851 }
2852 }
Ted Kremenek272aa852008-06-25 21:21:56 +00002853 }
Ted Kremenek1feab292008-04-16 04:28:53 +00002854 else
Ted Kremenekb17fa952009-04-23 21:25:57 +00002855 Summ = Summaries.getClassMethodSummary(ME);
Ted Kremenek1feab292008-04-16 04:28:53 +00002856
Ted Kremenekccbe79a2009-04-24 17:50:11 +00002857
Ted Kremenek926abf22008-05-06 04:20:12 +00002858 EvalSummary(Dst, Eng, Builder, ME, ME->getReceiver(), Summ,
2859 ME->arg_begin(), ME->arg_end(), Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002860}
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002861
2862namespace {
2863class VISIBILITY_HIDDEN StopTrackingCallback : public SymbolVisitor {
2864 GRStateRef state;
2865public:
2866 StopTrackingCallback(GRStateRef st) : state(st) {}
2867 GRStateRef getState() { return state; }
2868
2869 bool VisitSymbol(SymbolRef sym) {
2870 state = state.remove<RefBindings>(sym);
2871 return true;
2872 }
Ted Kremenek926abf22008-05-06 04:20:12 +00002873
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002874 const GRState* getState() const { return state.getState(); }
2875};
2876} // end anonymous namespace
2877
2878
Ted Kremeneka42be302009-02-14 01:43:44 +00002879void CFRefCount::EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val) {
Ted Kremeneka42be302009-02-14 01:43:44 +00002880 // Are we storing to something that causes the value to "escape"?
Ted Kremenek7aef4842008-04-16 20:40:59 +00002881 bool escapes = false;
2882
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002883 // A value escapes in three possible cases (this may change):
2884 //
2885 // (1) we are binding to something that is not a memory region.
2886 // (2) we are binding to a memregion that does not have stack storage
2887 // (3) we are binding to a memregion with stack storage that the store
Ted Kremeneka42be302009-02-14 01:43:44 +00002888 // does not understand.
Ted Kremeneka42be302009-02-14 01:43:44 +00002889 GRStateRef state = B.getState();
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002890
Ted Kremeneka42be302009-02-14 01:43:44 +00002891 if (!isa<loc::MemRegionVal>(location))
Ted Kremenek7aef4842008-04-16 20:40:59 +00002892 escapes = true;
Ted Kremenekb15eba42008-10-04 05:50:14 +00002893 else {
Ted Kremeneka42be302009-02-14 01:43:44 +00002894 const MemRegion* R = cast<loc::MemRegionVal>(location).getRegion();
2895 escapes = !B.getStateManager().hasStackStorage(R);
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002896
2897 if (!escapes) {
2898 // To test (3), generate a new state with the binding removed. If it is
2899 // the same state, then it escapes (since the store cannot represent
2900 // the binding).
Ted Kremeneka42be302009-02-14 01:43:44 +00002901 escapes = (state == (state.BindLoc(cast<Loc>(location), UnknownVal())));
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002902 }
Ted Kremenekb15eba42008-10-04 05:50:14 +00002903 }
Ted Kremeneka42be302009-02-14 01:43:44 +00002904
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002905 // If our store can represent the binding and we aren't storing to something
2906 // that doesn't have local storage then just return and have the simulation
2907 // state continue as is.
2908 if (!escapes)
2909 return;
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002910
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002911 // Otherwise, find all symbols referenced by 'val' that we are tracking
2912 // and stop tracking them.
2913 B.MakeNode(state.scanReachableSymbols<StopTrackingCallback>(val).getState());
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002914}
2915
Ted Kremenek0106e202008-10-24 20:32:50 +00002916std::pair<GRStateRef,bool>
2917CFRefCount::HandleSymbolDeath(GRStateManager& VMgr,
2918 const GRState* St, const Decl* CD,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002919 SymbolRef sid,
Ted Kremenek0106e202008-10-24 20:32:50 +00002920 RefVal V, bool& hasLeak) {
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002921
Ted Kremenek47a72422009-04-29 18:50:19 +00002922 // Any remaining leaks?
Ted Kremenek311f3d42008-10-22 23:56:21 +00002923 hasLeak = V.isOwned() ||
2924 ((V.isNotOwned() || V.isReturnedOwned()) && V.getCount() > 0);
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002925
Ted Kremenek47a72422009-04-29 18:50:19 +00002926 GRStateRef state(St, VMgr);
2927
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002928 if (!hasLeak)
Ted Kremenek0106e202008-10-24 20:32:50 +00002929 return std::make_pair(state.remove<RefBindings>(sid), false);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002930
Ted Kremenek0106e202008-10-24 20:32:50 +00002931 return std::make_pair(state.set<RefBindings>(sid, V ^ RefVal::ErrorLeak),
2932 false);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002933}
2934
Ted Kremenek541db372008-04-24 23:57:27 +00002935
Ted Kremenekffefc352008-04-11 22:25:11 +00002936
Ted Kremenek541db372008-04-24 23:57:27 +00002937// Dead symbols.
2938
Ted Kremenek708af042009-02-05 06:50:21 +00002939
Ted Kremenek541db372008-04-24 23:57:27 +00002940
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002941 // Return statements.
2942
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002943void CFRefCount::EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002944 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002945 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002946 ReturnStmt* S,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002947 ExplodedNode<GRState>* Pred) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002948
2949 Expr* RetE = S->getRetValue();
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002950 if (!RetE)
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002951 return;
2952
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002953 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002954 SymbolRef Sym = state.GetSValAsScalarOrLoc(RetE).getAsLocSymbol();
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002955
Ted Kremenek74556a12009-03-26 03:35:11 +00002956 if (!Sym)
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002957 return;
2958
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002959 // Get the reference count binding (if any).
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002960 const RefVal* T = state.get<RefBindings>(Sym);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002961
2962 if (!T)
2963 return;
2964
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002965 // Change the reference count.
Ted Kremenek6064a362008-07-07 16:21:19 +00002966 RefVal X = *T;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002967
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002968 switch (X.getKind()) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002969 case RefVal::Owned: {
2970 unsigned cnt = X.getCount();
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00002971 assert (cnt > 0);
2972 X = RefVal::makeReturnedOwned(cnt - 1);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002973 break;
2974 }
2975
2976 case RefVal::NotOwned: {
2977 unsigned cnt = X.getCount();
2978 X = cnt ? RefVal::makeReturnedOwned(cnt - 1)
2979 : RefVal::makeReturnedNotOwned();
2980 break;
2981 }
2982
2983 default:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002984 return;
2985 }
2986
2987 // Update the binding.
Ted Kremenek91781202008-08-17 03:20:02 +00002988 state = state.set<RefBindings>(Sym, X);
Ted Kremenek47a72422009-04-29 18:50:19 +00002989 Pred = Builder.MakeNode(Dst, S, Pred, state);
2990
2991 // Any leaks or other errors?
2992 if (X.isReturnedOwned() && X.getCount() == 0) {
2993 const Decl *CD = &Eng.getStateManager().getCodeDecl();
2994
2995 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
2996 std::string s = MD->getSelector().getAsString();
2997 // FIXME: Use method summary.
2998 if (!followsReturnRule(s.c_str())) {
2999 static int ReturnOwnLeakTag = 0;
3000 state = state.set<RefBindings>(Sym, X ^ RefVal::ErrorLeakReturned);
3001
3002 // Generate an error node.
3003 ExplodedNode<GRState> *N =
3004 Builder.generateNode(PostStmt(S, &ReturnOwnLeakTag), state, Pred);
3005
3006 CFRefLeakReport *report =
3007 new CFRefLeakReport(*static_cast<CFRefBug*>(leakAtReturn), *this,
3008 N, Sym, Eng);
3009 BR->EmitReport(report);
3010 }
3011 }
3012 }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00003013}
3014
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003015// Assumptions.
3016
Ted Kremenekabd89ac2008-08-13 04:27:00 +00003017const GRState* CFRefCount::EvalAssume(GRStateManager& VMgr,
3018 const GRState* St,
Zhongxing Xu097fc982008-10-17 05:57:07 +00003019 SVal Cond, bool Assumption,
Ted Kremenekf22f8682008-07-10 22:03:41 +00003020 bool& isFeasible) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003021
3022 // FIXME: We may add to the interface of EvalAssume the list of symbols
3023 // whose assumptions have changed. For now we just iterate through the
3024 // bindings and check if any of the tracked symbols are NULL. This isn't
3025 // too bad since the number of symbols we will track in practice are
3026 // probably small and EvalAssume is only called at branches and a few
3027 // other places.
Ted Kremenek4ae925c2008-08-14 21:16:54 +00003028 RefBindings B = St->get<RefBindings>();
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003029
3030 if (B.isEmpty())
3031 return St;
3032
3033 bool changed = false;
Ted Kremenek91781202008-08-17 03:20:02 +00003034
3035 GRStateRef state(St, VMgr);
3036 RefBindings::Factory& RefBFactory = state.get_context<RefBindings>();
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003037
3038 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003039 // Check if the symbol is null (or equal to any constant).
3040 // If this is the case, stop tracking the symbol.
Zhongxing Xuc6b27d02008-08-29 14:52:36 +00003041 if (VMgr.getSymVal(St, I.getKey())) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003042 changed = true;
3043 B = RefBFactory.Remove(B, I.getKey());
3044 }
3045 }
3046
Ted Kremenek91781202008-08-17 03:20:02 +00003047 if (changed)
3048 state = state.set<RefBindings>(B);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003049
Ted Kremenek4ae925c2008-08-14 21:16:54 +00003050 return state;
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00003051}
Ted Kremeneka7338b42008-03-11 06:39:11 +00003052
Ted Kremenekb6578942009-02-24 19:15:11 +00003053GRStateRef CFRefCount::Update(GRStateRef state, SymbolRef sym,
3054 RefVal V, ArgEffect E,
3055 RefVal::Kind& hasErr) {
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003056
3057 // In GC mode [... release] and [... retain] do nothing.
3058 switch (E) {
3059 default: break;
3060 case IncRefMsg: E = isGCEnabled() ? DoNothing : IncRef; break;
3061 case DecRefMsg: E = isGCEnabled() ? DoNothing : DecRef; break;
Ted Kremenek2126bef2009-02-18 21:57:45 +00003062 case MakeCollectable: E = isGCEnabled() ? DecRef : DoNothing; break;
Ted Kremenekaac82832009-02-23 17:45:03 +00003063 case NewAutoreleasePool: E = isGCEnabled() ? DoNothing :
3064 NewAutoreleasePool; break;
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003065 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00003066
Ted Kremenek6537a642009-03-17 19:42:23 +00003067 // Handle all use-after-releases.
3068 if (!isGCEnabled() && V.getKind() == RefVal::Released) {
3069 V = V ^ RefVal::ErrorUseAfterRelease;
3070 hasErr = V.getKind();
3071 return state.set<RefBindings>(sym, V);
3072 }
3073
Ted Kremenek0d721572008-03-11 17:48:22 +00003074 switch (E) {
3075 default:
3076 assert (false && "Unhandled CFRef transition.");
Ted Kremenek6537a642009-03-17 19:42:23 +00003077
3078 case Dealloc:
3079 // Any use of -dealloc in GC is *bad*.
3080 if (isGCEnabled()) {
3081 V = V ^ RefVal::ErrorDeallocGC;
3082 hasErr = V.getKind();
3083 break;
3084 }
3085
3086 switch (V.getKind()) {
3087 default:
3088 assert(false && "Invalid case.");
3089 case RefVal::Owned:
3090 // The object immediately transitions to the released state.
3091 V = V ^ RefVal::Released;
3092 V.clearCounts();
3093 return state.set<RefBindings>(sym, V);
3094 case RefVal::NotOwned:
3095 V = V ^ RefVal::ErrorDeallocNotOwned;
3096 hasErr = V.getKind();
3097 break;
3098 }
3099 break;
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003100
Ted Kremenekb7826ab2009-02-25 23:11:49 +00003101 case NewAutoreleasePool:
3102 assert(!isGCEnabled());
3103 return state.add<AutoreleaseStack>(sym);
3104
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003105 case MayEscape:
3106 if (V.getKind() == RefVal::Owned) {
Ted Kremenek272aa852008-06-25 21:21:56 +00003107 V = V ^ RefVal::NotOwned;
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003108 break;
3109 }
Ted Kremenek6537a642009-03-17 19:42:23 +00003110
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00003111 // Fall-through.
Ted Kremenek1b4b6562009-02-25 02:54:57 +00003112
Ted Kremenekede40b72008-07-09 18:11:16 +00003113 case DoNothingByRef:
Ted Kremenek0d721572008-03-11 17:48:22 +00003114 case DoNothing:
Ted Kremenekb6578942009-02-24 19:15:11 +00003115 return state;
Ted Kremeneke5a4bb02008-06-30 16:57:41 +00003116
Ted Kremenek9b112d22009-01-28 21:44:40 +00003117 case Autorelease:
Ted Kremenek6537a642009-03-17 19:42:23 +00003118 if (isGCEnabled())
3119 return state;
Ted Kremenek681fb352009-03-20 17:34:15 +00003120
3121 // Update the autorelease counts.
3122 state = SendAutorelease(state, ARCountFactory, sym);
Ted Kremenek6537a642009-03-17 19:42:23 +00003123
3124 // Fall-through.
3125
Ted Kremenek227c5372008-05-06 02:41:27 +00003126 case StopTracking:
Ted Kremenekb6578942009-02-24 19:15:11 +00003127 return state.remove<RefBindings>(sym);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003128
Ted Kremenek0d721572008-03-11 17:48:22 +00003129 case IncRef:
3130 switch (V.getKind()) {
3131 default:
3132 assert(false);
3133
3134 case RefVal::Owned:
Ted Kremenek0d721572008-03-11 17:48:22 +00003135 case RefVal::NotOwned:
Ted Kremenek272aa852008-06-25 21:21:56 +00003136 V = V + 1;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003137 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003138 case RefVal::Released:
Ted Kremenek6537a642009-03-17 19:42:23 +00003139 // Non-GC cases are handled above.
3140 assert(isGCEnabled());
3141 V = (V ^ RefVal::Owned) + 1;
Ted Kremenek0d721572008-03-11 17:48:22 +00003142 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003143 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00003144 break;
3145
Ted Kremenek272aa852008-06-25 21:21:56 +00003146 case SelfOwn:
3147 V = V ^ RefVal::NotOwned;
Ted Kremenek58dd95b2009-02-18 18:54:33 +00003148 // Fall-through.
Ted Kremenek0d721572008-03-11 17:48:22 +00003149 case DecRef:
3150 switch (V.getKind()) {
3151 default:
Ted Kremenek6537a642009-03-17 19:42:23 +00003152 // case 'RefVal::Released' handled above.
Ted Kremenek0d721572008-03-11 17:48:22 +00003153 assert (false);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003154
Ted Kremenek272aa852008-06-25 21:21:56 +00003155 case RefVal::Owned:
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00003156 assert(V.getCount() > 0);
3157 if (V.getCount() == 1) V = V ^ RefVal::Released;
3158 V = V - 1;
Ted Kremenek0d721572008-03-11 17:48:22 +00003159 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003160
Ted Kremenek272aa852008-06-25 21:21:56 +00003161 case RefVal::NotOwned:
3162 if (V.getCount() > 0)
3163 V = V - 1;
Ted Kremenekc4f81022008-04-10 23:09:18 +00003164 else {
Ted Kremenek272aa852008-06-25 21:21:56 +00003165 V = V ^ RefVal::ErrorReleaseNotOwned;
Ted Kremenek1feab292008-04-16 04:28:53 +00003166 hasErr = V.getKind();
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003167 }
Ted Kremenek0d721572008-03-11 17:48:22 +00003168 break;
Ted Kremenek6537a642009-03-17 19:42:23 +00003169
Ted Kremenek0d721572008-03-11 17:48:22 +00003170 case RefVal::Released:
Ted Kremenek6537a642009-03-17 19:42:23 +00003171 // Non-GC cases are handled above.
3172 assert(isGCEnabled());
Ted Kremenek272aa852008-06-25 21:21:56 +00003173 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek1feab292008-04-16 04:28:53 +00003174 hasErr = V.getKind();
Ted Kremenek6537a642009-03-17 19:42:23 +00003175 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00003176 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00003177 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00003178 }
Ted Kremenekb6578942009-02-24 19:15:11 +00003179 return state.set<RefBindings>(sym, V);
Ted Kremeneka7338b42008-03-11 06:39:11 +00003180}
3181
Ted Kremenek10fe66d2008-04-09 01:10:13 +00003182//===----------------------------------------------------------------------===//
Ted Kremenek708af042009-02-05 06:50:21 +00003183// Handle dead symbols and end-of-path.
3184//===----------------------------------------------------------------------===//
3185
3186void CFRefCount::EvalEndPath(GRExprEngine& Eng,
3187 GREndPathNodeBuilder<GRState>& Builder) {
3188
3189 const GRState* St = Builder.getState();
3190 RefBindings B = St->get<RefBindings>();
3191
3192 llvm::SmallVector<std::pair<SymbolRef, bool>, 10> Leaked;
3193 const Decl* CodeDecl = &Eng.getGraph().getCodeDecl();
3194
3195 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
3196 bool hasLeak = false;
3197
3198 std::pair<GRStateRef, bool> X =
Ted Kremenek9577c1e2009-03-03 22:06:47 +00003199 HandleSymbolDeath(Eng.getStateManager(), St, CodeDecl,
3200 (*I).first, (*I).second, hasLeak);
Ted Kremenek708af042009-02-05 06:50:21 +00003201
3202 St = X.first;
3203 if (hasLeak) Leaked.push_back(std::make_pair((*I).first, X.second));
3204 }
3205
3206 if (Leaked.empty())
3207 return;
3208
3209 ExplodedNode<GRState>* N = Builder.MakeNode(St);
3210
3211 if (!N)
3212 return;
3213
3214 for (llvm::SmallVector<std::pair<SymbolRef,bool>, 10>::iterator
3215 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3216
3217 CFRefBug *BT = static_cast<CFRefBug*>(I->second ? leakAtReturn
3218 : leakWithinFunction);
3219 assert(BT && "BugType not initialized.");
Ted Kremenekc034f712009-04-07 05:07:44 +00003220 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N, I->first, Eng);
Ted Kremenek708af042009-02-05 06:50:21 +00003221 BR->EmitReport(report);
3222 }
3223}
3224
3225void CFRefCount::EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
3226 GRExprEngine& Eng,
3227 GRStmtNodeBuilder<GRState>& Builder,
3228 ExplodedNode<GRState>* Pred,
3229 Stmt* S,
3230 const GRState* St,
3231 SymbolReaper& SymReaper) {
3232
Ted Kremenek876d8df2009-02-19 23:47:02 +00003233 // FIXME: a lot of copy-and-paste from EvalEndPath. Refactor.
Ted Kremenek708af042009-02-05 06:50:21 +00003234 RefBindings B = St->get<RefBindings>();
3235 llvm::SmallVector<std::pair<SymbolRef,bool>, 10> Leaked;
3236
3237 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3238 E = SymReaper.dead_end(); I != E; ++I) {
3239
3240 const RefVal* T = B.lookup(*I);
3241 if (!T) continue;
3242
3243 bool hasLeak = false;
3244
3245 std::pair<GRStateRef, bool> X
Ted Kremenek876d8df2009-02-19 23:47:02 +00003246 = HandleSymbolDeath(Eng.getStateManager(), St, 0, *I, *T, hasLeak);
Ted Kremenek708af042009-02-05 06:50:21 +00003247
3248 St = X.first;
3249
3250 if (hasLeak)
3251 Leaked.push_back(std::make_pair(*I,X.second));
3252 }
3253
Ted Kremenek876d8df2009-02-19 23:47:02 +00003254 if (!Leaked.empty()) {
3255 // Create a new intermediate node representing the leak point. We
3256 // use a special program point that represents this checker-specific
3257 // transition. We use the address of RefBIndex as a unique tag for this
3258 // checker. We will create another node (if we don't cache out) that
3259 // removes the retain-count bindings from the state.
3260 // NOTE: We use 'generateNode' so that it does interplay with the
3261 // auto-transition logic.
3262 ExplodedNode<GRState>* N =
3263 Builder.generateNode(PostStmtCustom(S, &LeakProgramPointTag), St, Pred);
Ted Kremenek708af042009-02-05 06:50:21 +00003264
Ted Kremenek876d8df2009-02-19 23:47:02 +00003265 if (!N)
3266 return;
3267
3268 // Generate the bug reports.
3269 for (llvm::SmallVectorImpl<std::pair<SymbolRef,bool> >::iterator
3270 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3271
3272 CFRefBug *BT = static_cast<CFRefBug*>(I->second ? leakAtReturn
3273 : leakWithinFunction);
3274 assert(BT && "BugType not initialized.");
Ted Kremenek56c70aa2009-02-23 16:54:00 +00003275 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N,
3276 I->first, Eng);
Ted Kremenek876d8df2009-02-19 23:47:02 +00003277 BR->EmitReport(report);
3278 }
Ted Kremenek708af042009-02-05 06:50:21 +00003279
Ted Kremenek876d8df2009-02-19 23:47:02 +00003280 Pred = N;
Ted Kremenek708af042009-02-05 06:50:21 +00003281 }
Ted Kremenek876d8df2009-02-19 23:47:02 +00003282
3283 // Now generate a new node that nukes the old bindings.
3284 GRStateRef state(St, Eng.getStateManager());
3285 RefBindings::Factory& F = state.get_context<RefBindings>();
3286
3287 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3288 E = SymReaper.dead_end(); I!=E; ++I)
3289 B = F.Remove(B, *I);
3290
3291 state = state.set<RefBindings>(B);
3292 Builder.MakeNode(Dst, S, Pred, state);
Ted Kremenek708af042009-02-05 06:50:21 +00003293}
3294
3295void CFRefCount::ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
3296 GRStmtNodeBuilder<GRState>& Builder,
3297 Expr* NodeExpr, Expr* ErrorExpr,
3298 ExplodedNode<GRState>* Pred,
3299 const GRState* St,
3300 RefVal::Kind hasErr, SymbolRef Sym) {
3301 Builder.BuildSinks = true;
3302 GRExprEngine::NodeTy* N = Builder.MakeNode(Dst, NodeExpr, Pred, St);
3303
3304 if (!N) return;
3305
3306 CFRefBug *BT = 0;
3307
Ted Kremenek6537a642009-03-17 19:42:23 +00003308 switch (hasErr) {
3309 default:
3310 assert(false && "Unhandled error.");
3311 return;
3312 case RefVal::ErrorUseAfterRelease:
3313 BT = static_cast<CFRefBug*>(useAfterRelease);
3314 break;
3315 case RefVal::ErrorReleaseNotOwned:
3316 BT = static_cast<CFRefBug*>(releaseNotOwned);
3317 break;
3318 case RefVal::ErrorDeallocGC:
3319 BT = static_cast<CFRefBug*>(deallocGC);
3320 break;
3321 case RefVal::ErrorDeallocNotOwned:
3322 BT = static_cast<CFRefBug*>(deallocNotOwned);
3323 break;
Ted Kremenek708af042009-02-05 06:50:21 +00003324 }
3325
Ted Kremenekc26c4692009-02-18 03:48:14 +00003326 CFRefReport *report = new CFRefReport(*BT, *this, N, Sym);
Ted Kremenek708af042009-02-05 06:50:21 +00003327 report->addRange(ErrorExpr->getSourceRange());
3328 BR->EmitReport(report);
3329}
3330
3331//===----------------------------------------------------------------------===//
Ted Kremenekb1983ba2008-04-10 22:16:52 +00003332// Transfer function creation for external clients.
Ted Kremeneka7338b42008-03-11 06:39:11 +00003333//===----------------------------------------------------------------------===//
3334
Ted Kremenekfe30beb2008-04-30 23:47:44 +00003335GRTransferFuncs* clang::MakeCFRefCountTF(ASTContext& Ctx, bool GCEnabled,
3336 const LangOptions& lopts) {
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00003337 return new CFRefCount(Ctx, GCEnabled, lopts);
Ted Kremeneka4c74292008-04-10 22:58:08 +00003338}