blob: 4961ef47fcfb68737d2a57e5694a886afa6b0461 [file] [log] [blame]
Chris Lattnerbe1a7a02008-03-15 23:59:48 +00001// CFRefCount.cpp - Transfer functions for tracking simple values -*- C++ -*--//
Ted Kremenek827f93b2008-03-06 00:08:09 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Gabor Greif2224fcb2008-03-06 10:40:09 +000010// This file defines the methods for CFRefCount, which implements
Ted Kremenek827f93b2008-03-06 00:08:09 +000011// a reference count checker for Core Foundation (Mac OS X).
12//
13//===----------------------------------------------------------------------===//
14
Ted Kremeneka7338b42008-03-11 06:39:11 +000015#include "GRSimpleVals.h"
Ted Kremenekfe30beb2008-04-30 23:47:44 +000016#include "clang/Basic/LangOptions.h"
Ted Kremenekfe4d2312008-05-01 23:13:35 +000017#include "clang/Basic/SourceManager.h"
Ted Kremeneka42be302009-02-14 01:43:44 +000018#include "clang/Analysis/PathSensitive/GRExprEngineBuilders.h"
Ted Kremenek91781202008-08-17 03:20:02 +000019#include "clang/Analysis/PathSensitive/GRStateTrait.h"
Ted Kremenekdd0126b2008-03-31 18:26:32 +000020#include "clang/Analysis/PathDiagnostic.h"
Ted Kremenek827f93b2008-03-06 00:08:09 +000021#include "clang/Analysis/LocalCheckers.h"
Ted Kremenek10fe66d2008-04-09 01:10:13 +000022#include "clang/Analysis/PathDiagnostic.h"
23#include "clang/Analysis/PathSensitive/BugReporter.h"
Ted Kremenek2ddb4b22009-02-14 03:16:10 +000024#include "clang/Analysis/PathSensitive/SymbolManager.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000025#include "clang/AST/DeclObjC.h"
Ted Kremeneka7338b42008-03-11 06:39:11 +000026#include "llvm/ADT/DenseMap.h"
27#include "llvm/ADT/FoldingSet.h"
28#include "llvm/ADT/ImmutableMap.h"
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +000029#include "llvm/ADT/ImmutableList.h"
Ted Kremenek2ac4ba62008-05-07 18:36:45 +000030#include "llvm/ADT/StringExtras.h"
Ted Kremenek10fe66d2008-04-09 01:10:13 +000031#include "llvm/Support/Compiler.h"
Ted Kremenekd7e26782008-05-16 18:33:44 +000032#include "llvm/ADT/STLExtras.h"
Ted Kremenek3b11f7a2008-03-11 19:44:10 +000033#include <ostream>
Ted Kremenek9449ca92008-08-12 20:41:56 +000034#include <stdarg.h>
Ted Kremenek827f93b2008-03-06 00:08:09 +000035
36using namespace clang;
Ted Kremenekb6f09542008-10-24 21:18:08 +000037
38//===----------------------------------------------------------------------===//
39// Utility functions.
40//===----------------------------------------------------------------------===//
41
Ted Kremenekb6f09542008-10-24 21:18:08 +000042// The "fundamental rule" for naming conventions of methods:
43// (url broken into two lines)
44// http://developer.apple.com/documentation/Cocoa/Conceptual/
45// MemoryMgmt/Tasks/MemoryManagementRules.html
46//
47// "You take ownership of an object if you create it using a method whose name
48// begins with “alloc” or “new” or contains “copy” (for example, alloc,
49// newObject, or mutableCopy), or if you send it a retain message. You are
50// responsible for relinquishing ownership of objects you own using release
51// or autorelease. Any other time you receive an object, you must
52// not release it."
53//
Ted Kremenek4395b452009-02-21 05:13:43 +000054
55using llvm::CStrInCStrNoCase;
Ted Kremenekfd42ffc2009-02-21 18:26:02 +000056using llvm::StringsEqualNoCase;
Ted Kremenek4395b452009-02-21 05:13:43 +000057
58enum NamingConvention { NoConvention, CreateRule, InitRule };
59
60static inline bool isWordEnd(char ch, char prev, char next) {
61 return ch == '\0'
62 || (islower(prev) && isupper(ch)) // xxxC
63 || (isupper(prev) && isupper(ch) && islower(next)) // XXCreate
64 || !isalpha(ch);
65}
66
67static inline const char* parseWord(const char* s) {
68 char ch = *s, prev = '\0';
69 assert(ch != '\0');
70 char next = *(s+1);
71 while (!isWordEnd(ch, prev, next)) {
72 prev = ch;
73 ch = next;
74 next = *((++s)+1);
75 }
76 return s;
77}
78
79static NamingConvention deriveNamingConvention(const char* s) {
80 // A method/function name may contain a prefix. We don't know it is there,
81 // however, until we encounter the first '_'.
82 bool InPossiblePrefix = true;
83 bool AtBeginning = true;
84 NamingConvention C = NoConvention;
85
86 while (*s != '\0') {
87 // Skip '_'.
88 if (*s == '_') {
89 if (InPossiblePrefix) {
90 InPossiblePrefix = false;
91 AtBeginning = true;
92 // Discard whatever 'convention' we
93 // had already derived since it occurs
94 // in the prefix.
95 C = NoConvention;
96 }
97 ++s;
98 continue;
99 }
100
101 // Skip numbers, ':', etc.
102 if (!isalpha(*s)) {
103 ++s;
104 continue;
105 }
106
107 const char *wordEnd = parseWord(s);
108 assert(wordEnd > s);
109 unsigned len = wordEnd - s;
110
111 switch (len) {
112 default:
113 break;
114 case 3:
115 // Methods starting with 'new' follow the create rule.
Ted Kremenekfd42ffc2009-02-21 18:26:02 +0000116 if (AtBeginning && StringsEqualNoCase("new", s, len))
Ted Kremenek4395b452009-02-21 05:13:43 +0000117 C = CreateRule;
118 break;
119 case 4:
120 // Methods starting with 'alloc' or contain 'copy' follow the
121 // create rule
Ted Kremenek91b79532009-03-13 20:27:06 +0000122 if (C == NoConvention && StringsEqualNoCase("copy", s, len))
Ted Kremenek4395b452009-02-21 05:13:43 +0000123 C = CreateRule;
124 else // Methods starting with 'init' follow the init rule.
Ted Kremenekfd42ffc2009-02-21 18:26:02 +0000125 if (AtBeginning && StringsEqualNoCase("init", s, len))
Ted Kremenek91b79532009-03-13 20:27:06 +0000126 C = InitRule;
127 break;
128 case 5:
129 if (AtBeginning && StringsEqualNoCase("alloc", s, len))
130 C = CreateRule;
Ted Kremenek4395b452009-02-21 05:13:43 +0000131 break;
132 }
133
134 // If we aren't in the prefix and have a derived convention then just
135 // return it now.
136 if (!InPossiblePrefix && C != NoConvention)
137 return C;
138
139 AtBeginning = false;
140 s = wordEnd;
141 }
142
143 // We will get here if there wasn't more than one word
144 // after the prefix.
145 return C;
146}
147
Ted Kremenekb6f09542008-10-24 21:18:08 +0000148static bool followsFundamentalRule(const char* s) {
Ted Kremenek4395b452009-02-21 05:13:43 +0000149 return deriveNamingConvention(s) == CreateRule;
Ted Kremenekcdd3bb22008-11-05 16:54:44 +0000150}
151
152static bool followsReturnRule(const char* s) {
Ted Kremenek4395b452009-02-21 05:13:43 +0000153 NamingConvention C = deriveNamingConvention(s);
154 return C == CreateRule || C == InitRule;
Ted Kremenekcdd3bb22008-11-05 16:54:44 +0000155}
Ted Kremenekb6f09542008-10-24 21:18:08 +0000156
Ted Kremenek7d421f32008-04-09 23:49:11 +0000157//===----------------------------------------------------------------------===//
Ted Kremenek272aa852008-06-25 21:21:56 +0000158// Selector creation functions.
Ted Kremenekd9ccf682008-04-17 18:12:53 +0000159//===----------------------------------------------------------------------===//
160
Ted Kremenek1bd6ddb2008-05-01 18:31:44 +0000161static inline Selector GetNullarySelector(const char* name, ASTContext& Ctx) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +0000162 IdentifierInfo* II = &Ctx.Idents.get(name);
163 return Ctx.Selectors.getSelector(0, &II);
164}
165
Ted Kremenek0e344d42008-05-06 00:30:21 +0000166static inline Selector GetUnarySelector(const char* name, ASTContext& Ctx) {
167 IdentifierInfo* II = &Ctx.Idents.get(name);
168 return Ctx.Selectors.getSelector(1, &II);
169}
170
Ted Kremenek272aa852008-06-25 21:21:56 +0000171//===----------------------------------------------------------------------===//
172// Type querying functions.
173//===----------------------------------------------------------------------===//
174
Ted Kremenek17144e82009-01-12 21:45:02 +0000175static bool hasPrefix(const char* s, const char* prefix) {
176 if (!prefix)
177 return true;
Ted Kremenek62820d82008-05-07 20:06:41 +0000178
Ted Kremenek17144e82009-01-12 21:45:02 +0000179 char c = *s;
180 char cP = *prefix;
Ted Kremenek62820d82008-05-07 20:06:41 +0000181
Ted Kremenek17144e82009-01-12 21:45:02 +0000182 while (c != '\0' && cP != '\0') {
183 if (c != cP) break;
184 c = *(++s);
185 cP = *(++prefix);
186 }
Ted Kremenek62820d82008-05-07 20:06:41 +0000187
Ted Kremenek17144e82009-01-12 21:45:02 +0000188 return cP == '\0';
Ted Kremenek62820d82008-05-07 20:06:41 +0000189}
190
Ted Kremenek17144e82009-01-12 21:45:02 +0000191static bool hasSuffix(const char* s, const char* suffix) {
192 const char* loc = strstr(s, suffix);
193 return loc && strcmp(suffix, loc) == 0;
194}
195
196static bool isRefType(QualType RetTy, const char* prefix,
197 ASTContext* Ctx = 0, const char* name = 0) {
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000198
Ted Kremenek17144e82009-01-12 21:45:02 +0000199 if (TypedefType* TD = dyn_cast<TypedefType>(RetTy.getTypePtr())) {
200 const char* TDName = TD->getDecl()->getIdentifier()->getName();
201 return hasPrefix(TDName, prefix) && hasSuffix(TDName, "Ref");
202 }
203
204 if (!Ctx || !name)
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000205 return false;
Ted Kremenek17144e82009-01-12 21:45:02 +0000206
207 // Is the type void*?
208 const PointerType* PT = RetTy->getAsPointerType();
209 if (!(PT->getPointeeType().getUnqualifiedType() == Ctx->VoidTy))
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000210 return false;
Ted Kremenek17144e82009-01-12 21:45:02 +0000211
212 // Does the name start with the prefix?
213 return hasPrefix(name, prefix);
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000214}
215
Ted Kremenekd9ccf682008-04-17 18:12:53 +0000216//===----------------------------------------------------------------------===//
Ted Kremenek272aa852008-06-25 21:21:56 +0000217// Primitives used for constructing summaries for function/method calls.
Ted Kremenek7d421f32008-04-09 23:49:11 +0000218//===----------------------------------------------------------------------===//
219
Ted Kremenek272aa852008-06-25 21:21:56 +0000220namespace {
221/// ArgEffect is used to summarize a function/method call's effect on a
222/// particular argument.
Ted Kremenek6537a642009-03-17 19:42:23 +0000223enum ArgEffect { Autorelease, Dealloc, DecRef, DecRefMsg, DoNothing,
224 DoNothingByRef, IncRefMsg, IncRef, MakeCollectable, MayEscape,
225 NewAutoreleasePool, SelfOwn, StopTracking };
Ted Kremenek272aa852008-06-25 21:21:56 +0000226
227/// ArgEffects summarizes the effects of a function/method call on all of
228/// its arguments.
229typedef std::vector<std::pair<unsigned,ArgEffect> > ArgEffects;
Ted Kremeneka7338b42008-03-11 06:39:11 +0000230}
Ted Kremenek827f93b2008-03-06 00:08:09 +0000231
Ted Kremeneka7338b42008-03-11 06:39:11 +0000232namespace llvm {
Ted Kremenek272aa852008-06-25 21:21:56 +0000233template <> struct FoldingSetTrait<ArgEffects> {
234 static void Profile(const ArgEffects& X, FoldingSetNodeID& ID) {
235 for (ArgEffects::const_iterator I = X.begin(), E = X.end(); I!= E; ++I) {
236 ID.AddInteger(I->first);
237 ID.AddInteger((unsigned) I->second);
238 }
239 }
240};
Ted Kremeneka7338b42008-03-11 06:39:11 +0000241} // end llvm namespace
242
243namespace {
Ted Kremenek272aa852008-06-25 21:21:56 +0000244
245/// RetEffect is used to summarize a function/method call's behavior with
246/// respect to its return value.
247class VISIBILITY_HIDDEN RetEffect {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000248public:
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000249 enum Kind { NoRet, Alias, OwnedSymbol, OwnedAllocatedSymbol,
250 NotOwnedSymbol, ReceiverAlias };
Ted Kremenek68621b92009-01-28 05:56:51 +0000251
252 enum ObjKind { CF, ObjC, AnyObj };
253
Ted Kremeneka7338b42008-03-11 06:39:11 +0000254private:
Ted Kremenek68621b92009-01-28 05:56:51 +0000255 Kind K;
256 ObjKind O;
257 unsigned index;
258
259 RetEffect(Kind k, unsigned idx = 0) : K(k), O(AnyObj), index(idx) {}
260 RetEffect(Kind k, ObjKind o) : K(k), O(o), index(0) {}
Ted Kremenek827f93b2008-03-06 00:08:09 +0000261
Ted Kremeneka7338b42008-03-11 06:39:11 +0000262public:
Ted Kremenek68621b92009-01-28 05:56:51 +0000263 Kind getKind() const { return K; }
264
265 ObjKind getObjKind() const { return O; }
Ted Kremenek272aa852008-06-25 21:21:56 +0000266
267 unsigned getIndex() const {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000268 assert(getKind() == Alias);
Ted Kremenek68621b92009-01-28 05:56:51 +0000269 return index;
Ted Kremeneka7338b42008-03-11 06:39:11 +0000270 }
Ted Kremenek827f93b2008-03-06 00:08:09 +0000271
Ted Kremenek272aa852008-06-25 21:21:56 +0000272 static RetEffect MakeAlias(unsigned Idx) {
273 return RetEffect(Alias, Idx);
274 }
275 static RetEffect MakeReceiverAlias() {
276 return RetEffect(ReceiverAlias);
277 }
Ted Kremenek68621b92009-01-28 05:56:51 +0000278 static RetEffect MakeOwned(ObjKind o, bool isAllocated = false) {
279 return RetEffect(isAllocated ? OwnedAllocatedSymbol : OwnedSymbol, o);
Ted Kremenek272aa852008-06-25 21:21:56 +0000280 }
Ted Kremenek68621b92009-01-28 05:56:51 +0000281 static RetEffect MakeNotOwned(ObjKind o) {
282 return RetEffect(NotOwnedSymbol, o);
Ted Kremenek272aa852008-06-25 21:21:56 +0000283 }
284 static RetEffect MakeNoRet() {
285 return RetEffect(NoRet);
Ted Kremenek6a1cc252008-06-23 18:02:52 +0000286 }
Ted Kremenek827f93b2008-03-06 00:08:09 +0000287
Ted Kremenek272aa852008-06-25 21:21:56 +0000288 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek68621b92009-01-28 05:56:51 +0000289 ID.AddInteger((unsigned)K);
290 ID.AddInteger((unsigned)O);
291 ID.AddInteger(index);
Ted Kremenek272aa852008-06-25 21:21:56 +0000292 }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000293};
Ted Kremeneka7338b42008-03-11 06:39:11 +0000294
Ted Kremenek272aa852008-06-25 21:21:56 +0000295
296class VISIBILITY_HIDDEN RetainSummary : public llvm::FoldingSetNode {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000297 /// Args - an ordered vector of (index, ArgEffect) pairs, where index
298 /// specifies the argument (starting from 0). This can be sparsely
299 /// populated; arguments with no entry in Args use 'DefaultArgEffect'.
Ted Kremeneka7338b42008-03-11 06:39:11 +0000300 ArgEffects* Args;
Ted Kremenekbcaff792008-05-06 15:44:25 +0000301
302 /// DefaultArgEffect - The default ArgEffect to apply to arguments that
303 /// do not have an entry in Args.
304 ArgEffect DefaultArgEffect;
305
Ted Kremenek272aa852008-06-25 21:21:56 +0000306 /// Receiver - If this summary applies to an Objective-C message expression,
307 /// this is the effect applied to the state of the receiver.
Ted Kremenek266d8b62008-05-06 02:26:56 +0000308 ArgEffect Receiver;
Ted Kremenek272aa852008-06-25 21:21:56 +0000309
310 /// Ret - The effect on the return value. Used to indicate if the
311 /// function/method call returns a new tracked symbol, returns an
312 /// alias of one of the arguments in the call, and so on.
Ted Kremeneka7338b42008-03-11 06:39:11 +0000313 RetEffect Ret;
Ted Kremenek272aa852008-06-25 21:21:56 +0000314
Ted Kremenekf2717b02008-07-18 17:24:20 +0000315 /// EndPath - Indicates that execution of this method/function should
316 /// terminate the simulation of a path.
317 bool EndPath;
318
Ted Kremeneka7338b42008-03-11 06:39:11 +0000319public:
320
Ted Kremenekbcaff792008-05-06 15:44:25 +0000321 RetainSummary(ArgEffects* A, RetEffect R, ArgEffect defaultEff,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000322 ArgEffect ReceiverEff, bool endpath = false)
323 : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R),
324 EndPath(endpath) {}
Ted Kremeneka7338b42008-03-11 06:39:11 +0000325
Ted Kremenek272aa852008-06-25 21:21:56 +0000326 /// getArg - Return the argument effect on the argument specified by
327 /// idx (starting from 0).
Ted Kremenek0d721572008-03-11 17:48:22 +0000328 ArgEffect getArg(unsigned idx) const {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000329
Ted Kremenekae855d42008-04-24 17:22:33 +0000330 if (!Args)
Ted Kremenekbcaff792008-05-06 15:44:25 +0000331 return DefaultArgEffect;
Ted Kremenekae855d42008-04-24 17:22:33 +0000332
333 // If Args is present, it is likely to contain only 1 element.
334 // Just do a linear search. Do it from the back because functions with
335 // large numbers of arguments will be tail heavy with respect to which
Ted Kremenek272aa852008-06-25 21:21:56 +0000336 // argument they actually modify with respect to the reference count.
Ted Kremenekae855d42008-04-24 17:22:33 +0000337 for (ArgEffects::reverse_iterator I=Args->rbegin(), E=Args->rend();
338 I!=E; ++I) {
339
340 if (idx > I->first)
Ted Kremenekbcaff792008-05-06 15:44:25 +0000341 return DefaultArgEffect;
Ted Kremenekae855d42008-04-24 17:22:33 +0000342
343 if (idx == I->first)
344 return I->second;
345 }
346
Ted Kremenekbcaff792008-05-06 15:44:25 +0000347 return DefaultArgEffect;
Ted Kremenek0d721572008-03-11 17:48:22 +0000348 }
349
Ted Kremenek272aa852008-06-25 21:21:56 +0000350 /// getRetEffect - Returns the effect on the return value of the call.
Ted Kremenek266d8b62008-05-06 02:26:56 +0000351 RetEffect getRetEffect() const {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000352 return Ret;
353 }
354
Ted Kremenekf2717b02008-07-18 17:24:20 +0000355 /// isEndPath - Returns true if executing the given method/function should
356 /// terminate the path.
357 bool isEndPath() const { return EndPath; }
358
Ted Kremenek272aa852008-06-25 21:21:56 +0000359 /// getReceiverEffect - Returns the effect on the receiver of the call.
360 /// This is only meaningful if the summary applies to an ObjCMessageExpr*.
Ted Kremenek266d8b62008-05-06 02:26:56 +0000361 ArgEffect getReceiverEffect() const {
362 return Receiver;
363 }
364
Ted Kremenek2719e982008-06-17 02:43:46 +0000365 typedef ArgEffects::const_iterator ExprIterator;
Ted Kremeneka7338b42008-03-11 06:39:11 +0000366
Ted Kremenek2719e982008-06-17 02:43:46 +0000367 ExprIterator begin_args() const { return Args->begin(); }
368 ExprIterator end_args() const { return Args->end(); }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000369
Ted Kremenek266d8b62008-05-06 02:26:56 +0000370 static void Profile(llvm::FoldingSetNodeID& ID, ArgEffects* A,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000371 RetEffect RetEff, ArgEffect DefaultEff,
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000372 ArgEffect ReceiverEff, bool EndPath) {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000373 ID.AddPointer(A);
Ted Kremenek266d8b62008-05-06 02:26:56 +0000374 ID.Add(RetEff);
Ted Kremenekbcaff792008-05-06 15:44:25 +0000375 ID.AddInteger((unsigned) DefaultEff);
Ted Kremenek266d8b62008-05-06 02:26:56 +0000376 ID.AddInteger((unsigned) ReceiverEff);
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000377 ID.AddInteger((unsigned) EndPath);
Ted Kremeneka7338b42008-03-11 06:39:11 +0000378 }
379
380 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000381 Profile(ID, Args, Ret, DefaultArgEffect, Receiver, EndPath);
Ted Kremeneka7338b42008-03-11 06:39:11 +0000382 }
383};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000384} // end anonymous namespace
Ted Kremeneka7338b42008-03-11 06:39:11 +0000385
Ted Kremenek272aa852008-06-25 21:21:56 +0000386//===----------------------------------------------------------------------===//
387// Data structures for constructing summaries.
388//===----------------------------------------------------------------------===//
Ted Kremenek9f0fc792008-06-24 03:49:48 +0000389
Ted Kremenek272aa852008-06-25 21:21:56 +0000390namespace {
391class VISIBILITY_HIDDEN ObjCSummaryKey {
392 IdentifierInfo* II;
393 Selector S;
394public:
395 ObjCSummaryKey(IdentifierInfo* ii, Selector s)
396 : II(ii), S(s) {}
397
398 ObjCSummaryKey(ObjCInterfaceDecl* d, Selector s)
399 : II(d ? d->getIdentifier() : 0), S(s) {}
400
401 ObjCSummaryKey(Selector s)
402 : II(0), S(s) {}
403
404 IdentifierInfo* getIdentifier() const { return II; }
405 Selector getSelector() const { return S; }
406};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000407}
408
409namespace llvm {
Ted Kremenek272aa852008-06-25 21:21:56 +0000410template <> struct DenseMapInfo<ObjCSummaryKey> {
411 static inline ObjCSummaryKey getEmptyKey() {
412 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
413 DenseMapInfo<Selector>::getEmptyKey());
414 }
Ted Kremenek84f010c2008-06-23 23:30:29 +0000415
Ted Kremenek272aa852008-06-25 21:21:56 +0000416 static inline ObjCSummaryKey getTombstoneKey() {
417 return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
418 DenseMapInfo<Selector>::getTombstoneKey());
419 }
420
421 static unsigned getHashValue(const ObjCSummaryKey &V) {
422 return (DenseMapInfo<IdentifierInfo*>::getHashValue(V.getIdentifier())
423 & 0x88888888)
424 | (DenseMapInfo<Selector>::getHashValue(V.getSelector())
425 & 0x55555555);
426 }
427
428 static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
429 return DenseMapInfo<IdentifierInfo*>::isEqual(LHS.getIdentifier(),
430 RHS.getIdentifier()) &&
431 DenseMapInfo<Selector>::isEqual(LHS.getSelector(),
432 RHS.getSelector());
433 }
434
435 static bool isPod() {
436 return DenseMapInfo<ObjCInterfaceDecl*>::isPod() &&
437 DenseMapInfo<Selector>::isPod();
438 }
439};
Ted Kremenek84f010c2008-06-23 23:30:29 +0000440} // end llvm namespace
Ted Kremeneka7338b42008-03-11 06:39:11 +0000441
Ted Kremenek84f010c2008-06-23 23:30:29 +0000442namespace {
Ted Kremenek272aa852008-06-25 21:21:56 +0000443class VISIBILITY_HIDDEN ObjCSummaryCache {
444 typedef llvm::DenseMap<ObjCSummaryKey, RetainSummary*> MapTy;
445 MapTy M;
446public:
447 ObjCSummaryCache() {}
448
449 typedef MapTy::iterator iterator;
450
451 iterator find(ObjCInterfaceDecl* D, Selector S) {
452
453 // Do a lookup with the (D,S) pair. If we find a match return
454 // the iterator.
455 ObjCSummaryKey K(D, S);
456 MapTy::iterator I = M.find(K);
457
458 if (I != M.end() || !D)
459 return I;
460
461 // Walk the super chain. If we find a hit with a parent, we'll end
462 // up returning that summary. We actually allow that key (null,S), as
463 // we cache summaries for the null ObjCInterfaceDecl* to allow us to
464 // generate initial summaries without having to worry about NSObject
465 // being declared.
466 // FIXME: We may change this at some point.
467 for (ObjCInterfaceDecl* C=D->getSuperClass() ;; C=C->getSuperClass()) {
468 if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
469 break;
470
471 if (!C)
472 return I;
473 }
474
475 // Cache the summary with original key to make the next lookup faster
476 // and return the iterator.
477 M[K] = I->second;
478 return I;
479 }
480
Ted Kremenek9449ca92008-08-12 20:41:56 +0000481
Ted Kremenek272aa852008-06-25 21:21:56 +0000482 iterator find(Expr* Receiver, Selector S) {
483 return find(getReceiverDecl(Receiver), S);
484 }
485
486 iterator find(IdentifierInfo* II, Selector S) {
487 // FIXME: Class method lookup. Right now we dont' have a good way
488 // of going between IdentifierInfo* and the class hierarchy.
489 iterator I = M.find(ObjCSummaryKey(II, S));
490 return I == M.end() ? M.find(ObjCSummaryKey(S)) : I;
491 }
492
493 ObjCInterfaceDecl* getReceiverDecl(Expr* E) {
494
495 const PointerType* PT = E->getType()->getAsPointerType();
496 if (!PT) return 0;
497
498 ObjCInterfaceType* OI = dyn_cast<ObjCInterfaceType>(PT->getPointeeType());
499 if (!OI) return 0;
500
501 return OI ? OI->getDecl() : 0;
502 }
503
504 iterator end() { return M.end(); }
505
506 RetainSummary*& operator[](ObjCMessageExpr* ME) {
507
508 Selector S = ME->getSelector();
509
510 if (Expr* Receiver = ME->getReceiver()) {
511 ObjCInterfaceDecl* OD = getReceiverDecl(Receiver);
512 return OD ? M[ObjCSummaryKey(OD->getIdentifier(), S)] : M[S];
513 }
514
515 return M[ObjCSummaryKey(ME->getClassName(), S)];
516 }
517
518 RetainSummary*& operator[](ObjCSummaryKey K) {
519 return M[K];
520 }
521
522 RetainSummary*& operator[](Selector S) {
523 return M[ ObjCSummaryKey(S) ];
524 }
525};
526} // end anonymous namespace
527
528//===----------------------------------------------------------------------===//
529// Data structures for managing collections of summaries.
530//===----------------------------------------------------------------------===//
531
532namespace {
533class VISIBILITY_HIDDEN RetainSummaryManager {
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000534
535 //==-----------------------------------------------------------------==//
536 // Typedefs.
537 //==-----------------------------------------------------------------==//
Ted Kremeneka7338b42008-03-11 06:39:11 +0000538
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000539 typedef llvm::FoldingSet<llvm::FoldingSetNodeWrapper<ArgEffects> >
540 ArgEffectsSetTy;
541
542 typedef llvm::FoldingSet<RetainSummary>
543 SummarySetTy;
544
545 typedef llvm::DenseMap<FunctionDecl*, RetainSummary*>
546 FuncSummariesTy;
547
Ted Kremenek84f010c2008-06-23 23:30:29 +0000548 typedef ObjCSummaryCache ObjCMethodSummariesTy;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000549
550 //==-----------------------------------------------------------------==//
551 // Data.
552 //==-----------------------------------------------------------------==//
553
Ted Kremenek272aa852008-06-25 21:21:56 +0000554 /// Ctx - The ASTContext object for the analyzed ASTs.
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000555 ASTContext& Ctx;
Ted Kremeneke44927e2008-07-01 17:21:27 +0000556
Ted Kremenekede40b72008-07-09 18:11:16 +0000557 /// CFDictionaryCreateII - An IdentifierInfo* representing the indentifier
558 /// "CFDictionaryCreate".
559 IdentifierInfo* CFDictionaryCreateII;
560
Ted Kremenek272aa852008-06-25 21:21:56 +0000561 /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000562 const bool GCEnabled;
563
Ted Kremenek272aa852008-06-25 21:21:56 +0000564 /// SummarySet - A FoldingSet of uniqued summaries.
Ted Kremeneka4c74292008-04-10 22:58:08 +0000565 SummarySetTy SummarySet;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000566
Ted Kremenek272aa852008-06-25 21:21:56 +0000567 /// FuncSummaries - A map from FunctionDecls to summaries.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000568 FuncSummariesTy FuncSummaries;
569
Ted Kremenek272aa852008-06-25 21:21:56 +0000570 /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
571 /// to summaries.
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000572 ObjCMethodSummariesTy ObjCClassMethodSummaries;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000573
Ted Kremenek272aa852008-06-25 21:21:56 +0000574 /// ObjCMethodSummaries - A map from selectors to summaries.
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000575 ObjCMethodSummariesTy ObjCMethodSummaries;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000576
Ted Kremenek272aa852008-06-25 21:21:56 +0000577 /// ArgEffectsSet - A FoldingSet of uniqued ArgEffects.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000578 ArgEffectsSetTy ArgEffectsSet;
579
Ted Kremenek272aa852008-06-25 21:21:56 +0000580 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
581 /// and all other data used by the checker.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000582 llvm::BumpPtrAllocator BPAlloc;
583
Ted Kremenek272aa852008-06-25 21:21:56 +0000584 /// ScratchArgs - A holding buffer for construct ArgEffects.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000585 ArgEffects ScratchArgs;
586
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000587 RetainSummary* StopSummary;
588
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000589 //==-----------------------------------------------------------------==//
590 // Methods.
591 //==-----------------------------------------------------------------==//
592
Ted Kremenek272aa852008-06-25 21:21:56 +0000593 /// getArgEffects - Returns a persistent ArgEffects object based on the
594 /// data in ScratchArgs.
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000595 ArgEffects* getArgEffects();
Ted Kremeneka7338b42008-03-11 06:39:11 +0000596
Ted Kremenek562c1302008-05-05 16:51:50 +0000597 enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000598
599public:
Ted Kremenek064ef322009-02-23 16:51:39 +0000600 RetainSummary* getUnarySummary(const FunctionType* FT, UnaryFuncKind func);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000601
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000602 RetainSummary* getCFSummaryCreateRule(FunctionDecl* FD);
603 RetainSummary* getCFSummaryGetRule(FunctionDecl* FD);
Ted Kremenek17144e82009-01-12 21:45:02 +0000604 RetainSummary* getCFCreateGetRuleSummary(FunctionDecl* FD, const char* FName);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000605
Ted Kremenek266d8b62008-05-06 02:26:56 +0000606 RetainSummary* getPersistentSummary(ArgEffects* AE, RetEffect RetEff,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000607 ArgEffect ReceiverEff = DoNothing,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000608 ArgEffect DefaultEff = MayEscape,
609 bool isEndPath = false);
Ted Kremenek45d0b502008-10-29 04:07:07 +0000610
Ted Kremenek266d8b62008-05-06 02:26:56 +0000611 RetainSummary* getPersistentSummary(RetEffect RE,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000612 ArgEffect ReceiverEff = DoNothing,
Ted Kremeneka3f30dd2008-05-22 17:31:13 +0000613 ArgEffect DefaultEff = MayEscape) {
Ted Kremenekbcaff792008-05-06 15:44:25 +0000614 return getPersistentSummary(getArgEffects(), RE, ReceiverEff, DefaultEff);
Ted Kremenek0e344d42008-05-06 00:30:21 +0000615 }
Ted Kremenek42ea0322008-05-05 23:55:01 +0000616
Ted Kremenekbcaff792008-05-06 15:44:25 +0000617 RetainSummary* getPersistentStopSummary() {
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000618 if (StopSummary)
619 return StopSummary;
620
621 StopSummary = getPersistentSummary(RetEffect::MakeNoRet(),
622 StopTracking, StopTracking);
Ted Kremenek45d0b502008-10-29 04:07:07 +0000623
Ted Kremenekb3a44e72008-05-06 18:11:36 +0000624 return StopSummary;
Ted Kremenekbcaff792008-05-06 15:44:25 +0000625 }
Ted Kremenek926abf22008-05-06 04:20:12 +0000626
Ted Kremenek272aa852008-06-25 21:21:56 +0000627 RetainSummary* getInitMethodSummary(ObjCMessageExpr* ME);
Ted Kremenek42ea0322008-05-05 23:55:01 +0000628
Ted Kremenek97c1e0c2008-06-23 22:21:20 +0000629 void InitializeClassMethodSummaries();
630 void InitializeMethodSummaries();
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000631
Ted Kremenek35920ed2009-01-07 00:39:56 +0000632 bool isTrackedObjectType(QualType T);
633
Ted Kremenek63d09ae2008-10-23 01:56:15 +0000634private:
635
Ted Kremenekf2717b02008-07-18 17:24:20 +0000636 void addClsMethSummary(IdentifierInfo* ClsII, Selector S,
637 RetainSummary* Summ) {
638 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
639 }
640
Ted Kremenek272aa852008-06-25 21:21:56 +0000641 void addNSObjectClsMethSummary(Selector S, RetainSummary *Summ) {
642 ObjCClassMethodSummaries[S] = Summ;
643 }
644
645 void addNSObjectMethSummary(Selector S, RetainSummary *Summ) {
646 ObjCMethodSummaries[S] = Summ;
647 }
Ted Kremenekfbf2dc52009-03-04 23:30:42 +0000648
649 void addClassMethSummary(const char* Cls, const char* nullaryName,
650 RetainSummary *Summ) {
651 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
652 Selector S = GetNullarySelector(nullaryName, Ctx);
653 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
654 }
Ted Kremenek272aa852008-06-25 21:21:56 +0000655
Ted Kremenek1b4b6562009-02-25 02:54:57 +0000656 void addInstMethSummary(const char* Cls, const char* nullaryName,
657 RetainSummary *Summ) {
658 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
659 Selector S = GetNullarySelector(nullaryName, Ctx);
660 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
661 }
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000662
663 Selector generateSelector(va_list argp) {
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000664 llvm::SmallVector<IdentifierInfo*, 10> II;
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000665
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000666 while (const char* s = va_arg(argp, const char*))
667 II.push_back(&Ctx.Idents.get(s));
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000668
669 return Ctx.Selectors.getSelector(II.size(), &II[0]);
670 }
671
672 void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy& Summaries,
673 RetainSummary* Summ, va_list argp) {
674 Selector S = generateSelector(argp);
675 Summaries[ObjCSummaryKey(ClsII, S)] = Summ;
Ted Kremenekf2717b02008-07-18 17:24:20 +0000676 }
Ted Kremenek45642a42008-08-12 18:48:50 +0000677
678 void addInstMethSummary(const char* Cls, RetainSummary* Summ, ...) {
679 va_list argp;
680 va_start(argp, Summ);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000681 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Ted Kremenek45642a42008-08-12 18:48:50 +0000682 va_end(argp);
683 }
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000684
685 void addClsMethSummary(const char* Cls, RetainSummary* Summ, ...) {
686 va_list argp;
687 va_start(argp, Summ);
688 addMethodSummary(&Ctx.Idents.get(Cls),ObjCClassMethodSummaries, Summ, argp);
689 va_end(argp);
690 }
691
692 void addClsMethSummary(IdentifierInfo *II, RetainSummary* Summ, ...) {
693 va_list argp;
694 va_start(argp, Summ);
695 addMethodSummary(II, ObjCClassMethodSummaries, Summ, argp);
696 va_end(argp);
697 }
698
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000699 void addPanicSummary(const char* Cls, ...) {
700 RetainSummary* Summ = getPersistentSummary(0, RetEffect::MakeNoRet(),
701 DoNothing, DoNothing, true);
702 va_list argp;
703 va_start (argp, Cls);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000704 addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +0000705 va_end(argp);
Ted Kremenekccbe79a2009-04-24 17:50:11 +0000706 }
Ted Kremenekf2717b02008-07-18 17:24:20 +0000707
Ted Kremeneka7338b42008-03-11 06:39:11 +0000708public:
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000709
710 RetainSummaryManager(ASTContext& ctx, bool gcenabled)
Ted Kremeneke44927e2008-07-01 17:21:27 +0000711 : Ctx(ctx),
Ted Kremenekede40b72008-07-09 18:11:16 +0000712 CFDictionaryCreateII(&ctx.Idents.get("CFDictionaryCreate")),
Ted Kremenek272aa852008-06-25 21:21:56 +0000713 GCEnabled(gcenabled), StopSummary(0) {
714
715 InitializeClassMethodSummaries();
716 InitializeMethodSummaries();
717 }
Ted Kremenek9b0c09c2008-04-29 05:33:51 +0000718
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000719 ~RetainSummaryManager();
Ted Kremeneka7338b42008-03-11 06:39:11 +0000720
Ted Kremenekd13c1872008-06-24 03:56:45 +0000721 RetainSummary* getSummary(FunctionDecl* FD);
Ted Kremenek272aa852008-06-25 21:21:56 +0000722 RetainSummary* getMethodSummary(ObjCMessageExpr* ME, ObjCInterfaceDecl* ID);
Ted Kremenekb17fa952009-04-23 21:25:57 +0000723 RetainSummary* getClassMethodSummary(ObjCMessageExpr *ME);
Ted Kremenekaca0b452009-04-24 18:19:07 +0000724 RetainSummary* getCommonMethodSummary(ObjCMessageExpr *ME, Selector S);
Ted Kremenek926abf22008-05-06 04:20:12 +0000725
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000726 bool isGCEnabled() const { return GCEnabled; }
Ted Kremeneka7338b42008-03-11 06:39:11 +0000727};
728
729} // end anonymous namespace
730
731//===----------------------------------------------------------------------===//
732// Implementation of checker data structures.
733//===----------------------------------------------------------------------===//
734
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000735RetainSummaryManager::~RetainSummaryManager() {
Ted Kremeneka7338b42008-03-11 06:39:11 +0000736
737 // FIXME: The ArgEffects could eventually be allocated from BPAlloc,
738 // mitigating the need to do explicit cleanup of the
739 // Argument-Effect summaries.
740
Ted Kremenek42ea0322008-05-05 23:55:01 +0000741 for (ArgEffectsSetTy::iterator I = ArgEffectsSet.begin(),
742 E = ArgEffectsSet.end(); I!=E; ++I)
Ted Kremeneka7338b42008-03-11 06:39:11 +0000743 I->getValue().~ArgEffects();
Ted Kremenek827f93b2008-03-06 00:08:09 +0000744}
Ted Kremeneka7338b42008-03-11 06:39:11 +0000745
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000746ArgEffects* RetainSummaryManager::getArgEffects() {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000747
Ted Kremenekae855d42008-04-24 17:22:33 +0000748 if (ScratchArgs.empty())
749 return NULL;
750
751 // Compute a profile for a non-empty ScratchArgs.
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000752 llvm::FoldingSetNodeID profile;
753 profile.Add(ScratchArgs);
754 void* InsertPos;
755
Ted Kremenekae855d42008-04-24 17:22:33 +0000756 // Look up the uniqued copy, or create a new one.
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000757 llvm::FoldingSetNodeWrapper<ArgEffects>* E =
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000758 ArgEffectsSet.FindNodeOrInsertPos(profile, InsertPos);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000759
Ted Kremenekae855d42008-04-24 17:22:33 +0000760 if (E) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000761 ScratchArgs.clear();
762 return &E->getValue();
763 }
764
765 E = (llvm::FoldingSetNodeWrapper<ArgEffects>*)
Ted Kremenek272aa852008-06-25 21:21:56 +0000766 BPAlloc.Allocate<llvm::FoldingSetNodeWrapper<ArgEffects> >();
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000767
768 new (E) llvm::FoldingSetNodeWrapper<ArgEffects>(ScratchArgs);
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000769 ArgEffectsSet.InsertNode(E, InsertPos);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000770
771 ScratchArgs.clear();
772 return &E->getValue();
773}
774
Ted Kremenek266d8b62008-05-06 02:26:56 +0000775RetainSummary*
776RetainSummaryManager::getPersistentSummary(ArgEffects* AE, RetEffect RetEff,
Ted Kremenekbcaff792008-05-06 15:44:25 +0000777 ArgEffect ReceiverEff,
Ted Kremenekf2717b02008-07-18 17:24:20 +0000778 ArgEffect DefaultEff,
779 bool isEndPath) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000780
Ted Kremenekae855d42008-04-24 17:22:33 +0000781 // Generate a profile for the summary.
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000782 llvm::FoldingSetNodeID profile;
Ted Kremenek6fbecac2008-07-18 17:39:56 +0000783 RetainSummary::Profile(profile, AE, RetEff, DefaultEff, ReceiverEff,
784 isEndPath);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000785
Ted Kremenekae855d42008-04-24 17:22:33 +0000786 // Look up the uniqued summary, or create one if it doesn't exist.
787 void* InsertPos;
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000788 RetainSummary* Summ = SummarySet.FindNodeOrInsertPos(profile, InsertPos);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000789
790 if (Summ)
791 return Summ;
792
Ted Kremenekae855d42008-04-24 17:22:33 +0000793 // Create the summary and return it.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000794 Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
Ted Kremenekf2717b02008-07-18 17:24:20 +0000795 new (Summ) RetainSummary(AE, RetEff, DefaultEff, ReceiverEff, isEndPath);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000796 SummarySet.InsertNode(Summ, InsertPos);
797
798 return Summ;
799}
800
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000801//===----------------------------------------------------------------------===//
Ted Kremenek35920ed2009-01-07 00:39:56 +0000802// Predicates.
803//===----------------------------------------------------------------------===//
804
Ted Kremenek0d813552009-04-23 22:11:07 +0000805bool RetainSummaryManager::isTrackedObjectType(QualType Ty) {
806 if (!Ctx.isObjCObjectPointerType(Ty))
Ted Kremenek35920ed2009-01-07 00:39:56 +0000807 return false;
808
Ted Kremenek0d813552009-04-23 22:11:07 +0000809 // We assume that id<..>, id, and "Class" all represent tracked objects.
810 const PointerType *PT = Ty->getAsPointerType();
811 if (PT == 0)
812 return true;
813
814 const ObjCInterfaceType *OT = PT->getPointeeType()->getAsObjCInterfaceType();
Ted Kremenek35920ed2009-01-07 00:39:56 +0000815
816 // We assume that id<..>, id, and "Class" all represent tracked objects.
817 if (!OT)
818 return true;
Ted Kremenek0d813552009-04-23 22:11:07 +0000819
820 // Does the interface subclass NSObject?
Ted Kremenek35920ed2009-01-07 00:39:56 +0000821 // FIXME: We can memoize here if this gets too expensive.
822 IdentifierInfo* NSObjectII = &Ctx.Idents.get("NSObject");
823 ObjCInterfaceDecl* ID = OT->getDecl();
824
825 for ( ; ID ; ID = ID->getSuperClass())
826 if (ID->getIdentifier() == NSObjectII)
827 return true;
828
829 return false;
830}
831
832//===----------------------------------------------------------------------===//
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000833// Summary creation for functions (largely uses of Core Foundation).
834//===----------------------------------------------------------------------===//
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000835
Ted Kremenek17144e82009-01-12 21:45:02 +0000836static bool isRetain(FunctionDecl* FD, const char* FName) {
837 const char* loc = strstr(FName, "Retain");
838 return loc && loc[sizeof("Retain")-1] == '\0';
839}
840
841static bool isRelease(FunctionDecl* FD, const char* FName) {
842 const char* loc = strstr(FName, "Release");
843 return loc && loc[sizeof("Release")-1] == '\0';
844}
845
Ted Kremenekd13c1872008-06-24 03:56:45 +0000846RetainSummary* RetainSummaryManager::getSummary(FunctionDecl* FD) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +0000847
848 SourceLocation Loc = FD->getLocation();
849
850 if (!Loc.isFileID())
851 return NULL;
Ted Kremenek827f93b2008-03-06 00:08:09 +0000852
Ted Kremenekae855d42008-04-24 17:22:33 +0000853 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000854 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremenekae855d42008-04-24 17:22:33 +0000855
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000856 if (I != FuncSummaries.end())
Ted Kremenekae855d42008-04-24 17:22:33 +0000857 return I->second;
858
859 // No summary. Generate one.
Ted Kremenek17144e82009-01-12 21:45:02 +0000860 RetainSummary *S = 0;
Ted Kremenek562c1302008-05-05 16:51:50 +0000861
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000862 do {
Ted Kremenek17144e82009-01-12 21:45:02 +0000863 // We generate "stop" summaries for implicitly defined functions.
864 if (FD->isImplicit()) {
865 S = getPersistentStopSummary();
866 break;
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000867 }
Ted Kremenekeafcc2f2008-11-04 00:36:12 +0000868
Ted Kremenek064ef322009-02-23 16:51:39 +0000869 // [PR 3337] Use 'getAsFunctionType' to strip away any typedefs on the
Ted Kremenekc239b9c2009-01-16 18:40:33 +0000870 // function's type.
Ted Kremenek064ef322009-02-23 16:51:39 +0000871 const FunctionType* FT = FD->getType()->getAsFunctionType();
Ted Kremenek17144e82009-01-12 21:45:02 +0000872 const char* FName = FD->getIdentifier()->getName();
873
Ted Kremenek38c6f022009-03-05 22:11:14 +0000874 // Strip away preceding '_'. Doing this here will effect all the checks
875 // down below.
876 while (*FName == '_') ++FName;
877
Ted Kremenek17144e82009-01-12 21:45:02 +0000878 // Inspect the result type.
879 QualType RetTy = FT->getResultType();
880
881 // FIXME: This should all be refactored into a chain of "summary lookup"
882 // filters.
883 if (strcmp(FName, "IOServiceGetMatchingServices") == 0) {
884 // FIXES: <rdar://problem/6326900>
885 // This should be addressed using a API table. This strcmp is also
886 // a little gross, but there is no need to super optimize here.
887 assert (ScratchArgs.empty());
888 ScratchArgs.push_back(std::make_pair(1, DecRef));
889 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
890 break;
Ted Kremenekcfc50c72008-10-22 20:54:52 +0000891 }
Ted Kremenek7b88c892009-03-17 22:43:44 +0000892
893 // Enable this code once the semantics of NSDeallocateObject are resolved
894 // for GC. <rdar://problem/6619988>
895#if 0
896 // Handle: NSDeallocateObject(id anObject);
897 // This method does allow 'nil' (although we don't check it now).
898 if (strcmp(FName, "NSDeallocateObject") == 0) {
899 return RetTy == Ctx.VoidTy
900 ? getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, Dealloc)
901 : getPersistentStopSummary();
902 }
903#endif
Ted Kremenek17144e82009-01-12 21:45:02 +0000904
905 // Handle: id NSMakeCollectable(CFTypeRef)
906 if (strcmp(FName, "NSMakeCollectable") == 0) {
907 S = (RetTy == Ctx.getObjCIdType())
908 ? getUnarySummary(FT, cfmakecollectable)
909 : getPersistentStopSummary();
910
911 break;
912 }
913
914 if (RetTy->isPointerType()) {
915 // For CoreFoundation ('CF') types.
916 if (isRefType(RetTy, "CF", &Ctx, FName)) {
917 if (isRetain(FD, FName))
918 S = getUnarySummary(FT, cfretain);
919 else if (strstr(FName, "MakeCollectable"))
920 S = getUnarySummary(FT, cfmakecollectable);
921 else
922 S = getCFCreateGetRuleSummary(FD, FName);
923
924 break;
925 }
926
927 // For CoreGraphics ('CG') types.
928 if (isRefType(RetTy, "CG", &Ctx, FName)) {
929 if (isRetain(FD, FName))
930 S = getUnarySummary(FT, cfretain);
931 else
932 S = getCFCreateGetRuleSummary(FD, FName);
933
934 break;
935 }
936
937 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
938 if (isRefType(RetTy, "DADisk") ||
939 isRefType(RetTy, "DADissenter") ||
940 isRefType(RetTy, "DASessionRef")) {
941 S = getCFCreateGetRuleSummary(FD, FName);
942 break;
943 }
944
945 break;
946 }
947
948 // Check for release functions, the only kind of functions that we care
949 // about that don't return a pointer type.
950 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
Ted Kremenek38c6f022009-03-05 22:11:14 +0000951 // Test for 'CGCF'.
952 if (FName[1] == 'G' && FName[2] == 'C' && FName[3] == 'F')
953 FName += 4;
954 else
955 FName += 2;
956
957 if (isRelease(FD, FName))
Ted Kremenek17144e82009-01-12 21:45:02 +0000958 S = getUnarySummary(FT, cfrelease);
959 else {
Ted Kremenek7b293682009-01-29 22:45:13 +0000960 assert (ScratchArgs.empty());
961 // Remaining CoreFoundation and CoreGraphics functions.
962 // We use to assume that they all strictly followed the ownership idiom
963 // and that ownership cannot be transferred. While this is technically
964 // correct, many methods allow a tracked object to escape. For example:
965 //
966 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
967 // CFDictionaryAddValue(y, key, x);
968 // CFRelease(x);
969 // ... it is okay to use 'x' since 'y' has a reference to it
970 //
971 // We handle this and similar cases with the follow heuristic. If the
972 // function name contains "InsertValue", "SetValue" or "AddValue" then
973 // we assume that arguments may "escape."
974 //
975 ArgEffect E = (CStrInCStrNoCase(FName, "InsertValue") ||
976 CStrInCStrNoCase(FName, "AddValue") ||
Ted Kremenekcf071252009-02-05 22:34:53 +0000977 CStrInCStrNoCase(FName, "SetValue") ||
978 CStrInCStrNoCase(FName, "AppendValue"))
Ted Kremenek7b293682009-01-29 22:45:13 +0000979 ? MayEscape : DoNothing;
980
981 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek17144e82009-01-12 21:45:02 +0000982 }
983 }
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000984 }
985 while (0);
Ted Kremenekae855d42008-04-24 17:22:33 +0000986
Ted Kremeneka8c3c432008-05-05 22:11:16 +0000987 FuncSummaries[FD] = S;
Ted Kremenek562c1302008-05-05 16:51:50 +0000988 return S;
Ted Kremenek827f93b2008-03-06 00:08:09 +0000989}
990
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000991RetainSummary*
992RetainSummaryManager::getCFCreateGetRuleSummary(FunctionDecl* FD,
993 const char* FName) {
994
Ted Kremenek562c1302008-05-05 16:51:50 +0000995 if (strstr(FName, "Create") || strstr(FName, "Copy"))
996 return getCFSummaryCreateRule(FD);
Ted Kremenek4c5378c2008-07-15 16:50:12 +0000997
Ted Kremenek562c1302008-05-05 16:51:50 +0000998 if (strstr(FName, "Get"))
999 return getCFSummaryGetRule(FD);
1000
1001 return 0;
1002}
1003
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001004RetainSummary*
Ted Kremenek064ef322009-02-23 16:51:39 +00001005RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1006 UnaryFuncKind func) {
1007
Ted Kremenek17144e82009-01-12 21:45:02 +00001008 // Sanity check that this is *really* a unary function. This can
1009 // happen if people do weird things.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001010 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
Ted Kremenek17144e82009-01-12 21:45:02 +00001011 if (!FTP || FTP->getNumArgs() != 1)
1012 return getPersistentStopSummary();
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001013
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001014 assert (ScratchArgs.empty());
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001015
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001016 switch (func) {
Ted Kremenek17144e82009-01-12 21:45:02 +00001017 case cfretain: {
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001018 ScratchArgs.push_back(std::make_pair(0, IncRef));
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001019 return getPersistentSummary(RetEffect::MakeAlias(0),
1020 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001021 }
1022
1023 case cfrelease: {
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001024 ScratchArgs.push_back(std::make_pair(0, DecRef));
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001025 return getPersistentSummary(RetEffect::MakeNoRet(),
1026 DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001027 }
1028
1029 case cfmakecollectable: {
Ted Kremenek2126bef2009-02-18 21:57:45 +00001030 ScratchArgs.push_back(std::make_pair(0, MakeCollectable));
1031 return getPersistentSummary(RetEffect::MakeAlias(0),DoNothing, DoNothing);
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001032 }
1033
1034 default:
Ted Kremenek562c1302008-05-05 16:51:50 +00001035 assert (false && "Not a supported unary function.");
Ted Kremenek9449ca92008-08-12 20:41:56 +00001036 return 0;
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00001037 }
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001038}
1039
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001040RetainSummary* RetainSummaryManager::getCFSummaryCreateRule(FunctionDecl* FD) {
Ted Kremenekae855d42008-04-24 17:22:33 +00001041 assert (ScratchArgs.empty());
Ted Kremenekede40b72008-07-09 18:11:16 +00001042
1043 if (FD->getIdentifier() == CFDictionaryCreateII) {
1044 ScratchArgs.push_back(std::make_pair(1, DoNothingByRef));
1045 ScratchArgs.push_back(std::make_pair(2, DoNothingByRef));
1046 }
1047
Ted Kremenek68621b92009-01-28 05:56:51 +00001048 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001049}
1050
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001051RetainSummary* RetainSummaryManager::getCFSummaryGetRule(FunctionDecl* FD) {
Ted Kremenekae855d42008-04-24 17:22:33 +00001052 assert (ScratchArgs.empty());
Ted Kremenek68621b92009-01-28 05:56:51 +00001053 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1054 DoNothing, DoNothing);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001055}
1056
Ted Kremeneka7338b42008-03-11 06:39:11 +00001057//===----------------------------------------------------------------------===//
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001058// Summary creation for Selectors.
1059//===----------------------------------------------------------------------===//
1060
Ted Kremenekbcaff792008-05-06 15:44:25 +00001061RetainSummary*
Ted Kremenek272aa852008-06-25 21:21:56 +00001062RetainSummaryManager::getInitMethodSummary(ObjCMessageExpr* ME) {
Ted Kremenek42ea0322008-05-05 23:55:01 +00001063 assert(ScratchArgs.empty());
1064
Ted Kremenek802cfc72009-02-20 00:05:35 +00001065 // 'init' methods only return an alias if the return type is a location type.
1066 QualType T = ME->getType();
Ted Kremenek42ea0322008-05-05 23:55:01 +00001067 RetainSummary* Summ =
Ted Kremenek802cfc72009-02-20 00:05:35 +00001068 getPersistentSummary(Loc::IsLocType(T) ? RetEffect::MakeReceiverAlias()
1069 : RetEffect::MakeNoRet());
Ted Kremenek42ea0322008-05-05 23:55:01 +00001070
Ted Kremenek272aa852008-06-25 21:21:56 +00001071 ObjCMethodSummaries[ME] = Summ;
Ted Kremenek42ea0322008-05-05 23:55:01 +00001072 return Summ;
1073}
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001074
Ted Kremenek272aa852008-06-25 21:21:56 +00001075
Ted Kremenekbcaff792008-05-06 15:44:25 +00001076RetainSummary*
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001077RetainSummaryManager::getCommonMethodSummary(ObjCMessageExpr* ME, Selector S) {
1078
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001079 if (ObjCMethodDecl *MD = ME->getMethodDecl()) {
1080 // Scan the method decl for 'void*' arguments. These should be treated
1081 // as 'StopTracking' because they are often used with delegates.
1082 // Delegates are a frequent form of false positives with the retain
1083 // count checker.
1084 unsigned i = 0;
1085 for (ObjCMethodDecl::param_iterator I = MD->param_begin(),
1086 E = MD->param_end(); I != E; ++I, ++i)
1087 if (ParmVarDecl *PD = *I) {
1088 QualType Ty = Ctx.getCanonicalType(PD->getType());
1089 if (Ty.getUnqualifiedType() == Ctx.VoidPtrTy)
1090 ScratchArgs.push_back(std::make_pair(i, StopTracking));
1091 }
1092 }
1093
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001094 // Any special effect for the receiver?
1095 ArgEffect ReceiverEff = DoNothing;
1096
1097 // If one of the arguments in the selector has the keyword 'delegate' we
1098 // should stop tracking the reference count for the receiver. This is
1099 // because the reference count is quite possibly handled by a delegate
1100 // method.
1101 if (S.isKeywordSelector()) {
1102 const std::string &str = S.getAsString();
1103 assert(!str.empty());
1104 if (CStrInCStrNoCase(&str[0], "delegate:")) ReceiverEff = StopTracking;
1105 }
1106
Ted Kremenek174a0772009-04-23 23:08:22 +00001107 // Look for methods that return an owned object.
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001108 if (!isTrackedObjectType(ME->getType())) {
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001109 if (ScratchArgs.empty() && ReceiverEff == DoNothing)
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001110 return 0;
1111
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001112 return getPersistentSummary(RetEffect::MakeNoRet(), ReceiverEff,
1113 MayEscape);
Ted Kremenek3fc3e112009-04-24 18:00:17 +00001114 }
Ted Kremenek174a0772009-04-23 23:08:22 +00001115
1116 // EXPERIMENTAL: Assume the Cocoa conventions for all objects returned
1117 // by instance methods.
1118
1119 RetEffect E =
Ted Kremenekaca0b452009-04-24 18:19:07 +00001120 followsFundamentalRule(S.getIdentifierInfoForSlot(0)->getName())
Ted Kremenek174a0772009-04-23 23:08:22 +00001121 ? (isGCEnabled() ? RetEffect::MakeNotOwned(RetEffect::ObjC)
1122 : RetEffect::MakeOwned(RetEffect::ObjC, true))
1123 : RetEffect::MakeNotOwned(RetEffect::ObjC);
1124
Ted Kremenekf936b3f2009-04-24 21:56:17 +00001125 return getPersistentSummary(E, ReceiverEff, MayEscape);
Ted Kremenek174a0772009-04-23 23:08:22 +00001126}
1127
1128RetainSummary*
Ted Kremenek272aa852008-06-25 21:21:56 +00001129RetainSummaryManager::getMethodSummary(ObjCMessageExpr* ME,
1130 ObjCInterfaceDecl* ID) {
Ted Kremenekbcaff792008-05-06 15:44:25 +00001131
1132 Selector S = ME->getSelector();
Ted Kremenek42ea0322008-05-05 23:55:01 +00001133
Ted Kremenek272aa852008-06-25 21:21:56 +00001134 // Look up a summary in our summary cache.
1135 ObjCMethodSummariesTy::iterator I = ObjCMethodSummaries.find(ID, S);
Ted Kremenek42ea0322008-05-05 23:55:01 +00001136
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001137 if (I != ObjCMethodSummaries.end())
Ted Kremenek42ea0322008-05-05 23:55:01 +00001138 return I->second;
Ted Kremenek42ea0322008-05-05 23:55:01 +00001139
Ted Kremenek35920ed2009-01-07 00:39:56 +00001140 // "initXXX": pass-through for receiver.
Ted Kremenek174a0772009-04-23 23:08:22 +00001141 assert(ScratchArgs.empty());
Ted Kremenek1d3d9562008-05-06 06:09:09 +00001142
Ted Kremenekaca0b452009-04-24 18:19:07 +00001143 if (deriveNamingConvention(S.getIdentifierInfoForSlot(0)->getName())
1144 == InitRule)
Ted Kremenek35920ed2009-01-07 00:39:56 +00001145 return getInitMethodSummary(ME);
Ted Kremenekbcaff792008-05-06 15:44:25 +00001146
Ted Kremenekaca0b452009-04-24 18:19:07 +00001147 RetainSummary *Summ = getCommonMethodSummary(ME, S);
Ted Kremeneke4158502009-04-23 19:11:35 +00001148 ObjCMethodSummaries[ME] = Summ;
1149 return Summ;
Ted Kremenek42ea0322008-05-05 23:55:01 +00001150}
1151
Ted Kremeneka7722b72008-05-06 21:26:51 +00001152RetainSummary*
Ted Kremenekccbe79a2009-04-24 17:50:11 +00001153RetainSummaryManager::getClassMethodSummary(ObjCMessageExpr *ME) {
1154
Ted Kremenekb17fa952009-04-23 21:25:57 +00001155 Selector S = ME->getSelector();
Ted Kremenekccbe79a2009-04-24 17:50:11 +00001156 ObjCMethodSummariesTy::iterator I;
Ted Kremenek272aa852008-06-25 21:21:56 +00001157
Ted Kremenekccbe79a2009-04-24 17:50:11 +00001158 if (ObjCInterfaceDecl *ID = ME->getClassInfo().first) {
1159 // Lookup the method using the decl for the class @interface.
1160 I = ObjCClassMethodSummaries.find(ID, S);
1161 }
1162 else {
1163 // Fallback to using the class name.
1164 IdentifierInfo *ClsName = ME->getClassName();
1165
1166 // Look up a summary in our cache of Selectors -> Summaries.
1167 I = ObjCClassMethodSummaries.find(ClsName, S);
1168 }
Ted Kremeneka7722b72008-05-06 21:26:51 +00001169
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001170 if (I != ObjCClassMethodSummaries.end())
Ted Kremeneka7722b72008-05-06 21:26:51 +00001171 return I->second;
1172
Ted Kremenekaca0b452009-04-24 18:19:07 +00001173 RetainSummary* Summ = getCommonMethodSummary(ME, S);
Ted Kremenekccbe79a2009-04-24 17:50:11 +00001174 ObjCClassMethodSummaries[ObjCSummaryKey(ME->getClassName(), S)] = Summ;
Ted Kremeneke4158502009-04-23 19:11:35 +00001175 return Summ;
Ted Kremeneka7722b72008-05-06 21:26:51 +00001176}
1177
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001178void RetainSummaryManager::InitializeClassMethodSummaries() {
Ted Kremenek0e344d42008-05-06 00:30:21 +00001179
1180 assert (ScratchArgs.empty());
1181
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001182 RetEffect E = isGCEnabled() ? RetEffect::MakeNoRet()
Ted Kremenek68621b92009-01-28 05:56:51 +00001183 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001184
Ted Kremenek0e344d42008-05-06 00:30:21 +00001185 RetainSummary* Summ = getPersistentSummary(E);
1186
Ted Kremenek272aa852008-06-25 21:21:56 +00001187 // Create the summaries for "alloc", "new", and "allocWithZone:" for
1188 // NSObject and its derivatives.
1189 addNSObjectClsMethSummary(GetNullarySelector("alloc", Ctx), Summ);
1190 addNSObjectClsMethSummary(GetNullarySelector("new", Ctx), Summ);
1191 addNSObjectClsMethSummary(GetUnarySelector("allocWithZone", Ctx), Summ);
Ted Kremenekf2717b02008-07-18 17:24:20 +00001192
1193 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001194 addClsMethSummary(&Ctx.Idents.get("NSAssertionHandler"),
Ted Kremenek68621b92009-01-28 05:56:51 +00001195 GetNullarySelector("currentHandler", Ctx),
1196 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001197
1198 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremenek9b112d22009-01-28 21:44:40 +00001199 ScratchArgs.push_back(std::make_pair(0, Autorelease));
1200 addClsMethSummary(&Ctx.Idents.get("NSAutoreleasePool"),
1201 GetUnarySelector("addObject", Ctx),
1202 getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenekf21cb242009-02-23 02:31:16 +00001203 DoNothing, Autorelease));
Ted Kremenekccbe79a2009-04-24 17:50:11 +00001204
1205 // Create the summaries for [NSObject performSelector...]. We treat
1206 // these as 'stop tracking' for the arguments because they are often
1207 // used for delegates that can release the object. When we have better
1208 // inter-procedural analysis we can potentially do something better. This
1209 // workaround is to remove false positives.
1210 Summ = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, StopTracking);
1211 IdentifierInfo *NSObjectII = &Ctx.Idents.get("NSObject");
1212 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1213 "afterDelay", NULL);
1214 addClsMethSummary(NSObjectII, Summ, "performSelector", "withObject",
1215 "afterDelay", "inModes", NULL);
1216 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1217 "withObject", "waitUntilDone", NULL);
1218 addClsMethSummary(NSObjectII, Summ, "performSelectorOnMainThread",
1219 "withObject", "waitUntilDone", "modes", NULL);
1220 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1221 "withObject", "waitUntilDone", NULL);
1222 addClsMethSummary(NSObjectII, Summ, "performSelector", "onThread",
1223 "withObject", "waitUntilDone", "modes", NULL);
1224 addClsMethSummary(NSObjectII, Summ, "performSelectorInBackground",
1225 "withObject", NULL);
Ted Kremenek0e344d42008-05-06 00:30:21 +00001226}
1227
Ted Kremenek97c1e0c2008-06-23 22:21:20 +00001228void RetainSummaryManager::InitializeMethodSummaries() {
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001229
1230 assert (ScratchArgs.empty());
1231
Ted Kremeneka7722b72008-05-06 21:26:51 +00001232 // Create the "init" selector. It just acts as a pass-through for the
1233 // receiver.
Ted Kremenek56c70aa2009-02-23 16:54:00 +00001234 RetainSummary* InitSumm =
1235 getPersistentSummary(RetEffect::MakeReceiverAlias());
Ted Kremeneke44927e2008-07-01 17:21:27 +00001236 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001237
1238 // The next methods are allocators.
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001239 RetEffect E = isGCEnabled() ? RetEffect::MakeNoRet()
Ted Kremenek68621b92009-01-28 05:56:51 +00001240 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001241
Ted Kremeneke44927e2008-07-01 17:21:27 +00001242 RetainSummary* Summ = getPersistentSummary(E);
Ted Kremeneka7722b72008-05-06 21:26:51 +00001243
1244 // Create the "copy" selector.
Ted Kremenek9449ca92008-08-12 20:41:56 +00001245 addNSObjectMethSummary(GetNullarySelector("copy", Ctx), Summ);
1246
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001247 // Create the "mutableCopy" selector.
Ted Kremenek272aa852008-06-25 21:21:56 +00001248 addNSObjectMethSummary(GetNullarySelector("mutableCopy", Ctx), Summ);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001249
Ted Kremenek266d8b62008-05-06 02:26:56 +00001250 // Create the "retain" selector.
1251 E = RetEffect::MakeReceiverAlias();
Ted Kremenek58dd95b2009-02-18 18:54:33 +00001252 Summ = getPersistentSummary(E, IncRefMsg);
Ted Kremenek272aa852008-06-25 21:21:56 +00001253 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001254
1255 // Create the "release" selector.
Ted Kremenek58dd95b2009-02-18 18:54:33 +00001256 Summ = getPersistentSummary(E, DecRefMsg);
Ted Kremenek272aa852008-06-25 21:21:56 +00001257 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Ted Kremenekc00b32b2008-05-07 21:17:39 +00001258
1259 // Create the "drain" selector.
1260 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek272aa852008-06-25 21:21:56 +00001261 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
Ted Kremenek6537a642009-03-17 19:42:23 +00001262
1263 // Create the -dealloc summary.
1264 Summ = getPersistentSummary(RetEffect::MakeNoRet(), Dealloc);
1265 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
Ted Kremenek266d8b62008-05-06 02:26:56 +00001266
1267 // Create the "autorelease" selector.
Ted Kremenek9b112d22009-01-28 21:44:40 +00001268 Summ = getPersistentSummary(E, Autorelease);
Ted Kremenek272aa852008-06-25 21:21:56 +00001269 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Ted Kremenek9449ca92008-08-12 20:41:56 +00001270
Ted Kremenekaac82832009-02-23 17:45:03 +00001271 // Specially handle NSAutoreleasePool.
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001272 addInstMethSummary("NSAutoreleasePool", "init",
Ted Kremenekaac82832009-02-23 17:45:03 +00001273 getPersistentSummary(RetEffect::MakeReceiverAlias(),
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001274 NewAutoreleasePool));
Ted Kremenekaac82832009-02-23 17:45:03 +00001275
Ted Kremenek45642a42008-08-12 18:48:50 +00001276 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremenek7e3a3272009-02-23 02:51:29 +00001277 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1278 // self-own themselves. However, they only do this once they are displayed.
1279 // Thus, we need to track an NSWindow's display status.
1280 // This is tracked in <rdar://problem/6062711>.
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001281 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
Ted Kremeneke5a036a2009-04-03 19:02:51 +00001282 RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet());
1283
1284 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1285
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001286
1287#if 0
Ted Kremeneke44927e2008-07-01 17:21:27 +00001288 RetainSummary *NSWindowSumm =
Ted Kremenek7e3a3272009-02-23 02:51:29 +00001289 getPersistentSummary(RetEffect::MakeReceiverAlias(), StopTracking);
Ted Kremenek45642a42008-08-12 18:48:50 +00001290
1291 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1292 "styleMask", "backing", "defer", NULL);
1293
1294 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1295 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenekfbf2dc52009-03-04 23:30:42 +00001296#endif
Ted Kremenek45642a42008-08-12 18:48:50 +00001297
1298 // For NSPanel (which subclasses NSWindow), allocated objects are not
1299 // self-owned.
Ted Kremeneke5a036a2009-04-03 19:02:51 +00001300 // FIXME: For now we don't track NSPanels. object for the same reason
1301 // as for NSWindow objects.
1302 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
1303
Ted Kremenek45642a42008-08-12 18:48:50 +00001304 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1305 "styleMask", "backing", "defer", NULL);
1306
1307 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1308 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek272aa852008-06-25 21:21:56 +00001309
Ted Kremenekf2717b02008-07-18 17:24:20 +00001310 // Create NSAssertionHandler summaries.
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001311 addPanicSummary("NSAssertionHandler", "handleFailureInFunction", "file",
1312 "lineNumber", "description", NULL);
Ted Kremenekf2717b02008-07-18 17:24:20 +00001313
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00001314 addPanicSummary("NSAssertionHandler", "handleFailureInMethod", "object",
1315 "file", "lineNumber", "description", NULL);
Ted Kremenek83b2cde2008-05-06 00:38:54 +00001316}
1317
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001318//===----------------------------------------------------------------------===//
Ted Kremenek7aef4842008-04-16 20:40:59 +00001319// Reference-counting logic (typestate + counts).
Ted Kremeneka7338b42008-03-11 06:39:11 +00001320//===----------------------------------------------------------------------===//
1321
Ted Kremeneka7338b42008-03-11 06:39:11 +00001322namespace {
1323
Ted Kremenek7d421f32008-04-09 23:49:11 +00001324class VISIBILITY_HIDDEN RefVal {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001325public:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001326 enum Kind {
1327 Owned = 0, // Owning reference.
1328 NotOwned, // Reference is not owned by still valid (not freed).
1329 Released, // Object has been released.
1330 ReturnedOwned, // Returned object passes ownership to caller.
1331 ReturnedNotOwned, // Return object does not pass ownership to caller.
Ted Kremenek6537a642009-03-17 19:42:23 +00001332 ERROR_START,
1333 ErrorDeallocNotOwned, // -dealloc called on non-owned object.
1334 ErrorDeallocGC, // Calling -dealloc with GC enabled.
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001335 ErrorUseAfterRelease, // Object used after released.
1336 ErrorReleaseNotOwned, // Release of an object that was not owned.
Ted Kremenek6537a642009-03-17 19:42:23 +00001337 ERROR_LEAK_START,
Ted Kremenek311f3d42008-10-22 23:56:21 +00001338 ErrorLeak, // A memory leak due to excessive reference counts.
1339 ErrorLeakReturned // A memory leak due to the returning method not having
1340 // the correct naming conventions.
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001341 };
Ted Kremenek68621b92009-01-28 05:56:51 +00001342
1343private:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001344 Kind kind;
Ted Kremenek68621b92009-01-28 05:56:51 +00001345 RetEffect::ObjKind okind;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001346 unsigned Cnt;
Ted Kremenek272aa852008-06-25 21:21:56 +00001347 QualType T;
1348
Ted Kremenek68621b92009-01-28 05:56:51 +00001349 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, QualType t)
1350 : kind(k), okind(o), Cnt(cnt), T(t) {}
Ted Kremenek0d721572008-03-11 17:48:22 +00001351
Ted Kremenek68621b92009-01-28 05:56:51 +00001352 RefVal(Kind k, unsigned cnt = 0)
1353 : kind(k), okind(RetEffect::AnyObj), Cnt(cnt) {}
1354
1355public:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001356 Kind getKind() const { return kind; }
Ted Kremenek68621b92009-01-28 05:56:51 +00001357
1358 RetEffect::ObjKind getObjKind() const { return okind; }
Ted Kremenek0d721572008-03-11 17:48:22 +00001359
Ted Kremenek6537a642009-03-17 19:42:23 +00001360 unsigned getCount() const { return Cnt; }
1361 void clearCounts() { Cnt = 0; }
1362
Ted Kremenek272aa852008-06-25 21:21:56 +00001363 QualType getType() const { return T; }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001364
1365 // Useful predicates.
Ted Kremenek0d721572008-03-11 17:48:22 +00001366
Ted Kremenek6537a642009-03-17 19:42:23 +00001367 static bool isError(Kind k) { return k >= ERROR_START; }
Ted Kremenek1daa16c2008-03-11 18:14:09 +00001368
Ted Kremenek6537a642009-03-17 19:42:23 +00001369 static bool isLeak(Kind k) { return k >= ERROR_LEAK_START; }
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001370
Ted Kremenekffefc352008-04-11 22:25:11 +00001371 bool isOwned() const {
1372 return getKind() == Owned;
1373 }
1374
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001375 bool isNotOwned() const {
1376 return getKind() == NotOwned;
1377 }
1378
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001379 bool isReturnedOwned() const {
1380 return getKind() == ReturnedOwned;
1381 }
1382
1383 bool isReturnedNotOwned() const {
1384 return getKind() == ReturnedNotOwned;
1385 }
1386
1387 bool isNonLeakError() const {
1388 Kind k = getKind();
1389 return isError(k) && !isLeak(k);
1390 }
1391
Ted Kremenek68621b92009-01-28 05:56:51 +00001392 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
1393 unsigned Count = 1) {
1394 return RefVal(Owned, o, Count, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001395 }
1396
Ted Kremenek68621b92009-01-28 05:56:51 +00001397 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
1398 unsigned Count = 0) {
1399 return RefVal(NotOwned, o, Count, t);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001400 }
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001401
1402 static RefVal makeReturnedOwned(unsigned Count) {
1403 return RefVal(ReturnedOwned, Count);
1404 }
1405
1406 static RefVal makeReturnedNotOwned() {
1407 return RefVal(ReturnedNotOwned);
1408 }
1409
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001410 // Comparison, profiling, and pretty-printing.
Ted Kremenek0d721572008-03-11 17:48:22 +00001411
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001412 bool operator==(const RefVal& X) const {
Ted Kremenek272aa852008-06-25 21:21:56 +00001413 return kind == X.kind && Cnt == X.Cnt && T == X.T;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001414 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001415
Ted Kremenek272aa852008-06-25 21:21:56 +00001416 RefVal operator-(size_t i) const {
Ted Kremenek68621b92009-01-28 05:56:51 +00001417 return RefVal(getKind(), getObjKind(), getCount() - i, getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001418 }
1419
1420 RefVal operator+(size_t i) const {
Ted Kremenek68621b92009-01-28 05:56:51 +00001421 return RefVal(getKind(), getObjKind(), getCount() + i, getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001422 }
1423
1424 RefVal operator^(Kind k) const {
Ted Kremenek68621b92009-01-28 05:56:51 +00001425 return RefVal(k, getObjKind(), getCount(), getType());
Ted Kremenek272aa852008-06-25 21:21:56 +00001426 }
Ted Kremenek6537a642009-03-17 19:42:23 +00001427
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001428 void Profile(llvm::FoldingSetNodeID& ID) const {
1429 ID.AddInteger((unsigned) kind);
1430 ID.AddInteger(Cnt);
Ted Kremenek272aa852008-06-25 21:21:56 +00001431 ID.Add(T);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001432 }
1433
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001434 void print(std::ostream& Out) const;
Ted Kremenek0d721572008-03-11 17:48:22 +00001435};
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001436
1437void RefVal::print(std::ostream& Out) const {
Ted Kremenek272aa852008-06-25 21:21:56 +00001438 if (!T.isNull())
1439 Out << "Tracked Type:" << T.getAsString() << '\n';
1440
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001441 switch (getKind()) {
1442 default: assert(false);
Ted Kremenekc4f81022008-04-10 23:09:18 +00001443 case Owned: {
1444 Out << "Owned";
1445 unsigned cnt = getCount();
1446 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001447 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001448 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001449
Ted Kremenekc4f81022008-04-10 23:09:18 +00001450 case NotOwned: {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001451 Out << "NotOwned";
Ted Kremenekc4f81022008-04-10 23:09:18 +00001452 unsigned cnt = getCount();
1453 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001454 break;
Ted Kremenekc4f81022008-04-10 23:09:18 +00001455 }
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001456
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001457 case ReturnedOwned: {
1458 Out << "ReturnedOwned";
1459 unsigned cnt = getCount();
1460 if (cnt) Out << " (+ " << cnt << ")";
1461 break;
1462 }
1463
1464 case ReturnedNotOwned: {
1465 Out << "ReturnedNotOwned";
1466 unsigned cnt = getCount();
1467 if (cnt) Out << " (+ " << cnt << ")";
1468 break;
1469 }
1470
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001471 case Released:
1472 Out << "Released";
1473 break;
Ted Kremenek6537a642009-03-17 19:42:23 +00001474
1475 case ErrorDeallocGC:
1476 Out << "-dealloc (GC)";
1477 break;
1478
1479 case ErrorDeallocNotOwned:
1480 Out << "-dealloc (not-owned)";
1481 break;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001482
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001483 case ErrorLeak:
1484 Out << "Leaked";
1485 break;
1486
Ted Kremenek311f3d42008-10-22 23:56:21 +00001487 case ErrorLeakReturned:
1488 Out << "Leaked (Bad naming)";
1489 break;
1490
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001491 case ErrorUseAfterRelease:
1492 Out << "Use-After-Release [ERROR]";
1493 break;
1494
1495 case ErrorReleaseNotOwned:
1496 Out << "Release of Not-Owned [ERROR]";
1497 break;
1498 }
1499}
Ted Kremenek0d721572008-03-11 17:48:22 +00001500
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001501} // end anonymous namespace
1502
1503//===----------------------------------------------------------------------===//
1504// RefBindings - State used to track object reference counts.
1505//===----------------------------------------------------------------------===//
1506
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001507typedef llvm::ImmutableMap<SymbolRef, RefVal> RefBindings;
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001508static int RefBIndex = 0;
Ted Kremenek876d8df2009-02-19 23:47:02 +00001509static std::pair<const void*, const void*> LeakProgramPointTag(&RefBIndex, 0);
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001510
1511namespace clang {
Ted Kremenek91781202008-08-17 03:20:02 +00001512 template<>
1513 struct GRStateTrait<RefBindings> : public GRStatePartialTrait<RefBindings> {
1514 static inline void* GDMIndex() { return &RefBIndex; }
1515 };
1516}
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001517
1518//===----------------------------------------------------------------------===//
Ted Kremenekb6578942009-02-24 19:15:11 +00001519// AutoreleaseBindings - State used to track objects in autorelease pools.
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001520//===----------------------------------------------------------------------===//
1521
Ted Kremenekb6578942009-02-24 19:15:11 +00001522typedef llvm::ImmutableMap<SymbolRef, unsigned> ARCounts;
1523typedef llvm::ImmutableMap<SymbolRef, ARCounts> ARPoolContents;
1524typedef llvm::ImmutableList<SymbolRef> ARStack;
Ted Kremenekaac82832009-02-23 17:45:03 +00001525
Ted Kremenekb6578942009-02-24 19:15:11 +00001526static int AutoRCIndex = 0;
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001527static int AutoRBIndex = 0;
1528
Ted Kremenekb6578942009-02-24 19:15:11 +00001529namespace { class VISIBILITY_HIDDEN AutoreleasePoolContents {}; }
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001530namespace { class VISIBILITY_HIDDEN AutoreleaseStack {}; }
Ted Kremenekb6578942009-02-24 19:15:11 +00001531
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001532namespace clang {
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001533template<> struct GRStateTrait<AutoreleaseStack>
Ted Kremenekb6578942009-02-24 19:15:11 +00001534 : public GRStatePartialTrait<ARStack> {
1535 static inline void* GDMIndex() { return &AutoRBIndex; }
1536};
1537
1538template<> struct GRStateTrait<AutoreleasePoolContents>
1539 : public GRStatePartialTrait<ARPoolContents> {
1540 static inline void* GDMIndex() { return &AutoRCIndex; }
1541};
1542} // end clang namespace
Ted Kremenekc8c8d2c2008-10-21 15:53:15 +00001543
Ted Kremenek681fb352009-03-20 17:34:15 +00001544static SymbolRef GetCurrentAutoreleasePool(const GRState* state) {
1545 ARStack stack = state->get<AutoreleaseStack>();
1546 return stack.isEmpty() ? SymbolRef() : stack.getHead();
1547}
1548
1549static GRStateRef SendAutorelease(GRStateRef state, ARCounts::Factory &F,
1550 SymbolRef sym) {
1551
1552 SymbolRef pool = GetCurrentAutoreleasePool(state);
1553 const ARCounts *cnts = state.get<AutoreleasePoolContents>(pool);
1554 ARCounts newCnts(0);
1555
1556 if (cnts) {
1557 const unsigned *cnt = (*cnts).lookup(sym);
1558 newCnts = F.Add(*cnts, sym, cnt ? *cnt + 1 : 1);
1559 }
1560 else
1561 newCnts = F.Add(F.GetEmptyMap(), sym, 1);
1562
1563 return state.set<AutoreleasePoolContents>(pool, newCnts);
1564}
1565
Ted Kremenek7aef4842008-04-16 20:40:59 +00001566//===----------------------------------------------------------------------===//
1567// Transfer functions.
1568//===----------------------------------------------------------------------===//
1569
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001570namespace {
1571
Ted Kremenek7d421f32008-04-09 23:49:11 +00001572class VISIBILITY_HIDDEN CFRefCount : public GRSimpleVals {
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001573public:
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001574 class BindingsPrinter : public GRState::Printer {
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001575 public:
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001576 virtual void Print(std::ostream& Out, const GRState* state,
1577 const char* nl, const char* sep);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001578 };
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001579
1580private:
Ted Kremenekc26c4692009-02-18 03:48:14 +00001581 typedef llvm::DenseMap<const GRExprEngine::NodeTy*, const RetainSummary*>
1582 SummaryLogTy;
1583
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001584 RetainSummaryManager Summaries;
Ted Kremenekc26c4692009-02-18 03:48:14 +00001585 SummaryLogTy SummaryLog;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001586 const LangOptions& LOpts;
Ted Kremenekb6578942009-02-24 19:15:11 +00001587 ARCounts::Factory ARCountFactory;
Ted Kremenek91781202008-08-17 03:20:02 +00001588
Ted Kremenek708af042009-02-05 06:50:21 +00001589 BugType *useAfterRelease, *releaseNotOwned;
Ted Kremenek6537a642009-03-17 19:42:23 +00001590 BugType *deallocGC, *deallocNotOwned;
Ted Kremenek708af042009-02-05 06:50:21 +00001591 BugType *leakWithinFunction, *leakAtReturn;
1592 BugReporter *BR;
Ted Kremeneka7338b42008-03-11 06:39:11 +00001593
Ted Kremenekb6578942009-02-24 19:15:11 +00001594 GRStateRef Update(GRStateRef state, SymbolRef sym, RefVal V, ArgEffect E,
1595 RefVal::Kind& hasErr);
1596
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001597 void ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
1598 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001599 Expr* NodeExpr, Expr* ErrorExpr,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001600 ExplodedNode<GRState>* Pred,
1601 const GRState* St,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001602 RefVal::Kind hasErr, SymbolRef Sym);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001603
Ted Kremenek0106e202008-10-24 20:32:50 +00001604 std::pair<GRStateRef, bool>
1605 HandleSymbolDeath(GRStateManager& VMgr, const GRState* St,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001606 const Decl* CD, SymbolRef sid, RefVal V, bool& hasLeak);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00001607
Ted Kremenekb6578942009-02-24 19:15:11 +00001608public:
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00001609 CFRefCount(ASTContext& Ctx, bool gcenabled, const LangOptions& lopts)
Ted Kremenek9b0c09c2008-04-29 05:33:51 +00001610 : Summaries(Ctx, gcenabled),
Ted Kremenek6537a642009-03-17 19:42:23 +00001611 LOpts(lopts), useAfterRelease(0), releaseNotOwned(0),
1612 deallocGC(0), deallocNotOwned(0),
Ted Kremenek708af042009-02-05 06:50:21 +00001613 leakWithinFunction(0), leakAtReturn(0), BR(0) {}
Ted Kremenek1feab292008-04-16 04:28:53 +00001614
Ted Kremenek708af042009-02-05 06:50:21 +00001615 virtual ~CFRefCount() {}
Ted Kremenek7d421f32008-04-09 23:49:11 +00001616
Ted Kremenekbf6babf2009-02-04 23:49:09 +00001617 void RegisterChecks(BugReporter &BR);
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001618
Ted Kremenekb0f2b9e2008-08-16 00:49:49 +00001619 virtual void RegisterPrinters(std::vector<GRState::Printer*>& Printers) {
1620 Printers.push_back(new BindingsPrinter());
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001621 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00001622
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001623 bool isGCEnabled() const { return Summaries.isGCEnabled(); }
Ted Kremenekfe30beb2008-04-30 23:47:44 +00001624 const LangOptions& getLangOptions() const { return LOpts; }
1625
Ted Kremenekc26c4692009-02-18 03:48:14 +00001626 const RetainSummary *getSummaryOfNode(const ExplodedNode<GRState> *N) const {
1627 SummaryLogTy::const_iterator I = SummaryLog.find(N);
1628 return I == SummaryLog.end() ? 0 : I->second;
1629 }
1630
Ted Kremeneka7338b42008-03-11 06:39:11 +00001631 // Calls.
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001632
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001633 void EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001634 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001635 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001636 Expr* Ex,
1637 Expr* Receiver,
1638 RetainSummary* Summ,
Ted Kremenek2719e982008-06-17 02:43:46 +00001639 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001640 ExplodedNode<GRState>* Pred);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001641
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001642 virtual void EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekce0767f2008-03-12 21:06:49 +00001643 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001644 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001645 CallExpr* CE, SVal L,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001646 ExplodedNode<GRState>* Pred);
Ted Kremenek10fe66d2008-04-09 01:10:13 +00001647
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001648
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001649 virtual void EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001650 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001651 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001652 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001653 ExplodedNode<GRState>* Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001654
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001655 bool EvalObjCMessageExprAux(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001656 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001657 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001658 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001659 ExplodedNode<GRState>* Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00001660
Ted Kremeneka42be302009-02-14 01:43:44 +00001661 // Stores.
1662 virtual void EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val);
1663
Ted Kremenekffefc352008-04-11 22:25:11 +00001664 // End-of-path.
1665
1666 virtual void EvalEndPath(GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001667 GREndPathNodeBuilder<GRState>& Builder);
Ted Kremenekffefc352008-04-11 22:25:11 +00001668
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001669 virtual void EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek541db372008-04-24 23:57:27 +00001670 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001671 GRStmtNodeBuilder<GRState>& Builder,
1672 ExplodedNode<GRState>* Pred,
Ted Kremenek5c0729b2009-01-21 22:26:05 +00001673 Stmt* S, const GRState* state,
1674 SymbolReaper& SymReaper);
1675
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001676 // Return statements.
1677
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001678 virtual void EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001679 GRExprEngine& Engine,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001680 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00001681 ReturnStmt* S,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001682 ExplodedNode<GRState>* Pred);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00001683
1684 // Assumptions.
1685
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001686 virtual const GRState* EvalAssume(GRStateManager& VMgr,
Zhongxing Xu097fc982008-10-17 05:57:07 +00001687 const GRState* St, SVal Cond,
Ted Kremenekf22f8682008-07-10 22:03:41 +00001688 bool Assumption, bool& isFeasible);
Ted Kremeneka7338b42008-03-11 06:39:11 +00001689};
1690
1691} // end anonymous namespace
1692
Ted Kremenek681fb352009-03-20 17:34:15 +00001693static void PrintPool(std::ostream &Out, SymbolRef Sym, const GRState *state) {
1694 Out << ' ';
Ted Kremenek74556a12009-03-26 03:35:11 +00001695 if (Sym)
1696 Out << Sym->getSymbolID();
Ted Kremenek681fb352009-03-20 17:34:15 +00001697 else
1698 Out << "<pool>";
1699 Out << ":{";
1700
1701 // Get the contents of the pool.
1702 if (const ARCounts *cnts = state->get<AutoreleasePoolContents>(Sym))
1703 for (ARCounts::iterator J=cnts->begin(), EJ=cnts->end(); J != EJ; ++J)
1704 Out << '(' << J.getKey() << ',' << J.getData() << ')';
1705
1706 Out << '}';
1707}
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001708
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001709void CFRefCount::BindingsPrinter::Print(std::ostream& Out, const GRState* state,
1710 const char* nl, const char* sep) {
Ted Kremenek681fb352009-03-20 17:34:15 +00001711
1712
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001713
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001714 RefBindings B = state->get<RefBindings>();
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001715
Ted Kremenekbccfbcc2008-08-13 21:24:49 +00001716 if (!B.isEmpty())
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001717 Out << sep << nl;
1718
1719 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
1720 Out << (*I).first << " : ";
1721 (*I).second.print(Out);
1722 Out << nl;
1723 }
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001724
1725 // Print the autorelease stack.
Ted Kremenek681fb352009-03-20 17:34:15 +00001726 Out << sep << nl << "AR pool stack:";
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001727 ARStack stack = state->get<AutoreleaseStack>();
Ted Kremenek1b4b6562009-02-25 02:54:57 +00001728
Ted Kremenek681fb352009-03-20 17:34:15 +00001729 PrintPool(Out, SymbolRef(), state); // Print the caller's pool.
1730 for (ARStack::iterator I=stack.begin(), E=stack.end(); I!=E; ++I)
1731 PrintPool(Out, *I, state);
1732
1733 Out << nl;
Ted Kremenek3b11f7a2008-03-11 19:44:10 +00001734}
1735
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001736static inline ArgEffect GetArgE(RetainSummary* Summ, unsigned idx) {
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00001737 return Summ ? Summ->getArg(idx) : MayEscape;
Ted Kremenek455dd862008-04-11 20:23:24 +00001738}
1739
Ted Kremenek266d8b62008-05-06 02:26:56 +00001740static inline RetEffect GetRetEffect(RetainSummary* Summ) {
1741 return Summ ? Summ->getRetEffect() : RetEffect::MakeNoRet();
Ted Kremenek455dd862008-04-11 20:23:24 +00001742}
1743
Ted Kremenek227c5372008-05-06 02:41:27 +00001744static inline ArgEffect GetReceiverE(RetainSummary* Summ) {
1745 return Summ ? Summ->getReceiverEffect() : DoNothing;
1746}
1747
Ted Kremenekf2717b02008-07-18 17:24:20 +00001748static inline bool IsEndPath(RetainSummary* Summ) {
1749 return Summ ? Summ->isEndPath() : false;
1750}
1751
Ted Kremenek1feab292008-04-16 04:28:53 +00001752
Ted Kremenek272aa852008-06-25 21:21:56 +00001753/// GetReturnType - Used to get the return type of a message expression or
1754/// function call with the intention of affixing that type to a tracked symbol.
1755/// While the the return type can be queried directly from RetEx, when
1756/// invoking class methods we augment to the return type to be that of
1757/// a pointer to the class (as opposed it just being id).
1758static QualType GetReturnType(Expr* RetE, ASTContext& Ctx) {
1759
1760 QualType RetTy = RetE->getType();
1761
1762 // FIXME: We aren't handling id<...>.
Chris Lattnerb724ab22008-07-26 22:36:27 +00001763 const PointerType* PT = RetTy->getAsPointerType();
Ted Kremenek272aa852008-06-25 21:21:56 +00001764 if (!PT)
1765 return RetTy;
1766
1767 // If RetEx is not a message expression just return its type.
1768 // If RetEx is a message expression, return its types if it is something
1769 /// more specific than id.
1770
1771 ObjCMessageExpr* ME = dyn_cast<ObjCMessageExpr>(RetE);
1772
Steve Naroff17c03822009-02-12 17:52:19 +00001773 if (!ME || !Ctx.isObjCIdStructType(PT->getPointeeType()))
Ted Kremenek272aa852008-06-25 21:21:56 +00001774 return RetTy;
1775
1776 ObjCInterfaceDecl* D = ME->getClassInfo().first;
1777
1778 // At this point we know the return type of the message expression is id.
1779 // If we have an ObjCInterceDecl, we know this is a call to a class method
1780 // whose type we can resolve. In such cases, promote the return type to
1781 // Class*.
1782 return !D ? RetTy : Ctx.getPointerType(Ctx.getObjCInterfaceType(D));
1783}
1784
1785
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001786void CFRefCount::EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001787 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001788 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001789 Expr* Ex,
1790 Expr* Receiver,
1791 RetainSummary* Summ,
Zhongxing Xucac107a2009-04-20 05:24:46 +00001792 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00001793 ExplodedNode<GRState>* Pred) {
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001794
Ted Kremeneka7338b42008-03-11 06:39:11 +00001795 // Get the state.
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001796 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenek0106e202008-10-24 20:32:50 +00001797 ASTContext& Ctx = Eng.getStateManager().getContext();
Ted Kremenek227c5372008-05-06 02:41:27 +00001798
1799 // Evaluate the effect of the arguments.
Ted Kremenek1feab292008-04-16 04:28:53 +00001800 RefVal::Kind hasErr = (RefVal::Kind) 0;
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001801 unsigned idx = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00001802 Expr* ErrorExpr = NULL;
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00001803 SymbolRef ErrorSym = 0;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00001804
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001805 for (ExprIterator I = arg_beg; I != arg_end; ++I, ++idx) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00001806 SVal V = state.GetSValAsScalarOrLoc(*I);
Ted Kremenek9577c1e2009-03-03 22:06:47 +00001807 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00001808
Ted Kremenek74556a12009-03-26 03:35:11 +00001809 if (Sym)
Ted Kremenekb6578942009-02-24 19:15:11 +00001810 if (RefBindings::data_type* T = state.get<RefBindings>(Sym)) {
1811 state = Update(state, Sym, *T, GetArgE(Summ, idx), hasErr);
1812 if (hasErr) {
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00001813 ErrorExpr = *I;
Ted Kremenek6064a362008-07-07 16:21:19 +00001814 ErrorSym = Sym;
Ted Kremenek99b0ecb2008-04-11 18:40:51 +00001815 break;
Ted Kremenek9577c1e2009-03-03 22:06:47 +00001816 }
1817 continue;
Ted Kremenekb6578942009-02-24 19:15:11 +00001818 }
Ted Kremenekede40b72008-07-09 18:11:16 +00001819
Ted Kremenek9577c1e2009-03-03 22:06:47 +00001820 if (isa<Loc>(V)) {
1821 if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(&V)) {
Ted Kremenekede40b72008-07-09 18:11:16 +00001822 if (GetArgE(Summ, idx) == DoNothingByRef)
1823 continue;
1824
1825 // Invalidate the value of the variable passed by reference.
Ted Kremenek852e3ca2008-07-03 23:26:32 +00001826
1827 // FIXME: Either this logic should also be replicated in GRSimpleVals
1828 // or should be pulled into a separate "constraint engine."
Ted Kremenekede40b72008-07-09 18:11:16 +00001829
Ted Kremenek852e3ca2008-07-03 23:26:32 +00001830 // FIXME: We can have collisions on the conjured symbol if the
1831 // expression *I also creates conjured symbols. We probably want
1832 // to identify conjured symbols by an expression pair: the enclosing
1833 // expression (the context) and the expression itself. This should
Ted Kremenekede40b72008-07-09 18:11:16 +00001834 // disambiguate conjured symbols.
Ted Kremenekb15eba42008-10-04 05:50:14 +00001835
Ted Kremenek38a4b4b2008-10-17 20:28:54 +00001836 const TypedRegion* R = dyn_cast<TypedRegion>(MR->getRegion());
Ted Kremenek58a26bf2008-12-17 19:42:34 +00001837
Ted Kremenek6a9b5352009-03-01 05:44:08 +00001838 // Blast through TypedViewRegions to get the original region type.
Ted Kremenek58a26bf2008-12-17 19:42:34 +00001839 while (R) {
Ted Kremenek6a9b5352009-03-01 05:44:08 +00001840 const TypedViewRegion* ATR = dyn_cast<TypedViewRegion>(R);
Ted Kremenek58a26bf2008-12-17 19:42:34 +00001841 if (!ATR) break;
1842 R = dyn_cast<TypedRegion>(ATR->getSuperRegion());
1843 }
1844
Ted Kremenek53b24182009-03-04 22:56:43 +00001845 if (R) {
Ted Kremenek618c6cd2008-12-18 23:34:57 +00001846 // Is the invalidated variable something that we were tracking?
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00001847 SymbolRef Sym = state.GetSValAsScalarOrLoc(R).getAsLocSymbol();
Ted Kremenek618c6cd2008-12-18 23:34:57 +00001848
Ted Kremenek53b24182009-03-04 22:56:43 +00001849 // Remove any existing reference-count binding.
Ted Kremenek74556a12009-03-26 03:35:11 +00001850 if (Sym) state = state.remove<RefBindings>(Sym);
Ted Kremenekb15eba42008-10-04 05:50:14 +00001851
Ted Kremenek53b24182009-03-04 22:56:43 +00001852 if (R->isBoundable(Ctx)) {
1853 // Set the value of the variable to be a conjured symbol.
1854 unsigned Count = Builder.getCurrentBlockCount();
1855 QualType T = R->getRValueType(Ctx);
1856
Zhongxing Xu079dc352009-04-09 06:03:54 +00001857 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())){
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00001858 ValueManager &ValMgr = Eng.getValueManager();
1859 SVal V = ValMgr.getConjuredSymbolVal(*I, T, Count);
Zhongxing Xu079dc352009-04-09 06:03:54 +00001860 state = state.BindLoc(Loc::MakeVal(R), V);
Ted Kremenek53b24182009-03-04 22:56:43 +00001861 }
1862 else if (const RecordType *RT = T->getAsStructureType()) {
1863 // Handle structs in a not so awesome way. Here we just
1864 // eagerly bind new symbols to the fields. In reality we
1865 // should have the store manager handle this. The idea is just
1866 // to prototype some basic functionality here. All of this logic
1867 // should one day soon just go away.
1868 const RecordDecl *RD = RT->getDecl()->getDefinition(Ctx);
1869
1870 // No record definition. There is nothing we can do.
1871 if (!RD)
1872 continue;
1873
1874 MemRegionManager &MRMgr = state.getManager().getRegionManager();
1875
1876 // Iterate through the fields and construct new symbols.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001877 for (RecordDecl::field_iterator FI=RD->field_begin(Ctx),
1878 FE=RD->field_end(Ctx); FI!=FE; ++FI) {
Ted Kremenek53b24182009-03-04 22:56:43 +00001879
1880 // For now just handle scalar fields.
1881 FieldDecl *FD = *FI;
1882 QualType FT = FD->getType();
1883
1884 if (Loc::IsLocType(FT) ||
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00001885 (FT->isIntegerType() && FT->isScalarType())) {
Ted Kremenek53b24182009-03-04 22:56:43 +00001886 const FieldRegion* FR = MRMgr.getFieldRegion(FD, R);
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00001887 ValueManager &ValMgr = Eng.getValueManager();
1888 SVal V = ValMgr.getConjuredSymbolVal(*I, FT, Count);
Zhongxing Xuc458e322009-04-09 06:32:20 +00001889 state = state.BindLoc(Loc::MakeVal(FR), V);
Ted Kremenek53b24182009-03-04 22:56:43 +00001890 }
1891 }
1892 }
1893 else {
1894 // Just blast away other values.
1895 state = state.BindLoc(*MR, UnknownVal());
1896 }
Ted Kremenek8f90e712008-10-17 22:23:12 +00001897 }
Ted Kremenekb15eba42008-10-04 05:50:14 +00001898 }
1899 else
Ted Kremenek09102db2008-11-12 19:22:09 +00001900 state = state.BindLoc(*MR, UnknownVal());
Ted Kremenek852e3ca2008-07-03 23:26:32 +00001901 }
1902 else {
1903 // Nuke all other arguments passed by reference.
Zhongxing Xu097fc982008-10-17 05:57:07 +00001904 state = state.Unbind(cast<Loc>(V));
Ted Kremenek852e3ca2008-07-03 23:26:32 +00001905 }
Ted Kremeneke4924202008-04-11 20:51:02 +00001906 }
Zhongxing Xu097fc982008-10-17 05:57:07 +00001907 else if (isa<nonloc::LocAsInteger>(V))
1908 state = state.Unbind(cast<nonloc::LocAsInteger>(V).getLoc());
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001909 }
Ted Kremenek1feab292008-04-16 04:28:53 +00001910
Ted Kremenek272aa852008-06-25 21:21:56 +00001911 // Evaluate the effect on the message receiver.
Ted Kremenek227c5372008-05-06 02:41:27 +00001912 if (!ErrorExpr && Receiver) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00001913 SymbolRef Sym = state.GetSValAsScalarOrLoc(Receiver).getAsLocSymbol();
Ted Kremenek74556a12009-03-26 03:35:11 +00001914 if (Sym) {
Ted Kremenekb6578942009-02-24 19:15:11 +00001915 if (const RefVal* T = state.get<RefBindings>(Sym)) {
1916 state = Update(state, Sym, *T, GetReceiverE(Summ), hasErr);
1917 if (hasErr) {
Ted Kremenek227c5372008-05-06 02:41:27 +00001918 ErrorExpr = Receiver;
Ted Kremenek6064a362008-07-07 16:21:19 +00001919 ErrorSym = Sym;
Ted Kremenek227c5372008-05-06 02:41:27 +00001920 }
Ted Kremenekb6578942009-02-24 19:15:11 +00001921 }
Ted Kremenek227c5372008-05-06 02:41:27 +00001922 }
1923 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001924
Ted Kremenek272aa852008-06-25 21:21:56 +00001925 // Process any errors.
Ted Kremenek1feab292008-04-16 04:28:53 +00001926 if (hasErr) {
Ted Kremenek4ae925c2008-08-14 21:16:54 +00001927 ProcessNonLeakError(Dst, Builder, Ex, ErrorExpr, Pred, state,
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00001928 hasErr, ErrorSym);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001929 return;
Ted Kremenek0d721572008-03-11 17:48:22 +00001930 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001931
Ted Kremenekf2717b02008-07-18 17:24:20 +00001932 // Consult the summary for the return value.
Ted Kremenek266d8b62008-05-06 02:26:56 +00001933 RetEffect RE = GetRetEffect(Summ);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001934
1935 switch (RE.getKind()) {
1936 default:
1937 assert (false && "Unhandled RetEffect."); break;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001938
Ted Kremenek8f90e712008-10-17 22:23:12 +00001939 case RetEffect::NoRet: {
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001940
Ted Kremenek455dd862008-04-11 20:23:24 +00001941 // Make up a symbol for the return value (not reference counted).
Ted Kremeneke4924202008-04-11 20:51:02 +00001942 // FIXME: This is basically copy-and-paste from GRSimpleVals. We
1943 // should compose behavior, not copy it.
Ted Kremenek455dd862008-04-11 20:23:24 +00001944
Ted Kremenek8f90e712008-10-17 22:23:12 +00001945 // FIXME: We eventually should handle structs and other compound types
1946 // that are returned by value.
1947
1948 QualType T = Ex->getType();
1949
Ted Kremenek79413a52008-11-13 06:10:40 +00001950 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())) {
Ted Kremenek455dd862008-04-11 20:23:24 +00001951 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke4cb3c82009-04-09 22:22:44 +00001952 ValueManager &ValMgr = Eng.getValueManager();
1953 SVal X = ValMgr.getConjuredSymbolVal(Ex, T, Count);
Ted Kremenek09102db2008-11-12 19:22:09 +00001954 state = state.BindExpr(Ex, X, false);
Ted Kremenek455dd862008-04-11 20:23:24 +00001955 }
1956
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00001957 break;
Ted Kremenek8f90e712008-10-17 22:23:12 +00001958 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00001959
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001960 case RetEffect::Alias: {
Ted Kremenek272aa852008-06-25 21:21:56 +00001961 unsigned idx = RE.getIndex();
Ted Kremenek2719e982008-06-17 02:43:46 +00001962 assert (arg_end >= arg_beg);
Ted Kremeneka8c3c432008-05-05 22:11:16 +00001963 assert (idx < (unsigned) (arg_end - arg_beg));
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00001964 SVal V = state.GetSValAsScalarOrLoc(*(arg_beg+idx));
Ted Kremenek09102db2008-11-12 19:22:09 +00001965 state = state.BindExpr(Ex, V, false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001966 break;
1967 }
1968
Ted Kremenek227c5372008-05-06 02:41:27 +00001969 case RetEffect::ReceiverAlias: {
1970 assert (Receiver);
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00001971 SVal V = state.GetSValAsScalarOrLoc(Receiver);
Ted Kremenek09102db2008-11-12 19:22:09 +00001972 state = state.BindExpr(Ex, V, false);
Ted Kremenek227c5372008-05-06 02:41:27 +00001973 break;
1974 }
1975
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001976 case RetEffect::OwnedAllocatedSymbol:
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001977 case RetEffect::OwnedSymbol: {
1978 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke9e726e2009-04-09 16:13:17 +00001979 ValueManager &ValMgr = Eng.getValueManager();
1980 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
1981 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
1982 state = state.set<RefBindings>(Sym, RefVal::makeOwned(RE.getObjKind(),
1983 RetT));
1984 state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenek45c52a12009-03-09 22:46:49 +00001985
1986 // FIXME: Add a flag to the checker where allocations are assumed to
1987 // *not fail.
1988#if 0
Ted Kremeneke62fd052009-01-28 22:27:59 +00001989 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) {
1990 bool isFeasible;
1991 state = state.Assume(loc::SymbolVal(Sym), true, isFeasible);
1992 assert(isFeasible && "Cannot assume fresh symbol is non-null.");
1993 }
Ted Kremenek45c52a12009-03-09 22:46:49 +00001994#endif
Ted Kremenek6a1cc252008-06-23 18:02:52 +00001995
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00001996 break;
1997 }
1998
1999 case RetEffect::NotOwnedSymbol: {
2000 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremeneke9e726e2009-04-09 16:13:17 +00002001 ValueManager &ValMgr = Eng.getValueManager();
2002 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
2003 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
2004 state = state.set<RefBindings>(Sym, RefVal::makeNotOwned(RE.getObjKind(),
2005 RetT));
2006 state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenekce3ed1e2008-03-12 01:21:45 +00002007 break;
2008 }
2009 }
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002010
Ted Kremenek0dd65012009-02-18 02:00:25 +00002011 // Generate a sink node if we are at the end of a path.
2012 GRExprEngine::NodeTy *NewNode =
2013 IsEndPath(Summ) ? Builder.MakeSinkNode(Dst, Ex, Pred, state)
2014 : Builder.MakeNode(Dst, Ex, Pred, state);
2015
2016 // Annotate the edge with summary we used.
2017 // FIXME: This assumes that we always use the same summary when generating
2018 // this node.
2019 if (NewNode) SummaryLog[NewNode] = Summ;
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002020}
2021
2022
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002023void CFRefCount::EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002024 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002025 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu097fc982008-10-17 05:57:07 +00002026 CallExpr* CE, SVal L,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002027 ExplodedNode<GRState>* Pred) {
Zhongxing Xucac107a2009-04-20 05:24:46 +00002028 const FunctionDecl* FD = L.getAsFunctionDecl();
2029 RetainSummary* Summ = !FD ? 0
2030 : Summaries.getSummary(const_cast<FunctionDecl*>(FD));
Ted Kremeneka8c3c432008-05-05 22:11:16 +00002031
2032 EvalSummary(Dst, Eng, Builder, CE, 0, Summ,
2033 CE->arg_begin(), CE->arg_end(), Pred);
Ted Kremenek827f93b2008-03-06 00:08:09 +00002034}
Ted Kremeneka7338b42008-03-11 06:39:11 +00002035
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002036void CFRefCount::EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002037 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002038 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002039 ObjCMessageExpr* ME,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002040 ExplodedNode<GRState>* Pred) {
Ted Kremenek926abf22008-05-06 04:20:12 +00002041 RetainSummary* Summ;
Ted Kremenek33661802008-05-01 21:31:50 +00002042
Ted Kremenek272aa852008-06-25 21:21:56 +00002043 if (Expr* Receiver = ME->getReceiver()) {
2044 // We need the type-information of the tracked receiver object
2045 // Retrieve it from the state.
2046 ObjCInterfaceDecl* ID = 0;
2047
2048 // FIXME: Wouldn't it be great if this code could be reduced? It's just
2049 // a chain of lookups.
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002050 const GRState* St = Builder.GetState(Pred);
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002051 SVal V = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
Ted Kremenek272aa852008-06-25 21:21:56 +00002052
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002053 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenek74556a12009-03-26 03:35:11 +00002054 if (Sym) {
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002055 if (const RefVal* T = St->get<RefBindings>(Sym)) {
Ted Kremenek6064a362008-07-07 16:21:19 +00002056 QualType Ty = T->getType();
Ted Kremenek272aa852008-06-25 21:21:56 +00002057
2058 if (const PointerType* PT = Ty->getAsPointerType()) {
2059 QualType PointeeTy = PT->getPointeeType();
2060
2061 if (ObjCInterfaceType* IT = dyn_cast<ObjCInterfaceType>(PointeeTy))
2062 ID = IT->getDecl();
2063 }
2064 }
2065 }
2066
2067 Summ = Summaries.getMethodSummary(ME, ID);
Ted Kremenek0106e202008-10-24 20:32:50 +00002068
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002069 // Special-case: are we sending a mesage to "self"?
2070 // This is a hack. When we have full-IP this should be removed.
2071 if (!Summ) {
2072 ObjCMethodDecl* MD =
2073 dyn_cast<ObjCMethodDecl>(&Eng.getGraph().getCodeDecl());
2074
2075 if (MD) {
2076 if (Expr* Receiver = ME->getReceiver()) {
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002077 SVal X = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002078 if (loc::MemRegionVal* L = dyn_cast<loc::MemRegionVal>(&X))
Ted Kremenek0106e202008-10-24 20:32:50 +00002079 if (L->getRegion() == Eng.getStateManager().getSelfRegion(St)) {
2080 // Create a summmary where all of the arguments "StopTracking".
2081 Summ = Summaries.getPersistentSummary(RetEffect::MakeNoRet(),
2082 DoNothing,
2083 StopTracking);
2084 }
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002085 }
2086 }
2087 }
Ted Kremenek272aa852008-06-25 21:21:56 +00002088 }
Ted Kremenek1feab292008-04-16 04:28:53 +00002089 else
Ted Kremenekb17fa952009-04-23 21:25:57 +00002090 Summ = Summaries.getClassMethodSummary(ME);
Ted Kremenek1feab292008-04-16 04:28:53 +00002091
Ted Kremenekccbe79a2009-04-24 17:50:11 +00002092
Ted Kremenek926abf22008-05-06 04:20:12 +00002093 EvalSummary(Dst, Eng, Builder, ME, ME->getReceiver(), Summ,
2094 ME->arg_begin(), ME->arg_end(), Pred);
Ted Kremenek4b4738b2008-04-15 23:44:31 +00002095}
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002096
2097namespace {
2098class VISIBILITY_HIDDEN StopTrackingCallback : public SymbolVisitor {
2099 GRStateRef state;
2100public:
2101 StopTrackingCallback(GRStateRef st) : state(st) {}
2102 GRStateRef getState() { return state; }
2103
2104 bool VisitSymbol(SymbolRef sym) {
2105 state = state.remove<RefBindings>(sym);
2106 return true;
2107 }
Ted Kremenek926abf22008-05-06 04:20:12 +00002108
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002109 const GRState* getState() const { return state.getState(); }
2110};
2111} // end anonymous namespace
2112
2113
Ted Kremeneka42be302009-02-14 01:43:44 +00002114void CFRefCount::EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val) {
Ted Kremeneka42be302009-02-14 01:43:44 +00002115 // Are we storing to something that causes the value to "escape"?
Ted Kremenek7aef4842008-04-16 20:40:59 +00002116 bool escapes = false;
2117
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002118 // A value escapes in three possible cases (this may change):
2119 //
2120 // (1) we are binding to something that is not a memory region.
2121 // (2) we are binding to a memregion that does not have stack storage
2122 // (3) we are binding to a memregion with stack storage that the store
Ted Kremeneka42be302009-02-14 01:43:44 +00002123 // does not understand.
Ted Kremeneka42be302009-02-14 01:43:44 +00002124 GRStateRef state = B.getState();
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002125
Ted Kremeneka42be302009-02-14 01:43:44 +00002126 if (!isa<loc::MemRegionVal>(location))
Ted Kremenek7aef4842008-04-16 20:40:59 +00002127 escapes = true;
Ted Kremenekb15eba42008-10-04 05:50:14 +00002128 else {
Ted Kremeneka42be302009-02-14 01:43:44 +00002129 const MemRegion* R = cast<loc::MemRegionVal>(location).getRegion();
2130 escapes = !B.getStateManager().hasStackStorage(R);
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002131
2132 if (!escapes) {
2133 // To test (3), generate a new state with the binding removed. If it is
2134 // the same state, then it escapes (since the store cannot represent
2135 // the binding).
Ted Kremeneka42be302009-02-14 01:43:44 +00002136 escapes = (state == (state.BindLoc(cast<Loc>(location), UnknownVal())));
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002137 }
Ted Kremenekb15eba42008-10-04 05:50:14 +00002138 }
Ted Kremeneka42be302009-02-14 01:43:44 +00002139
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002140 // If our store can represent the binding and we aren't storing to something
2141 // that doesn't have local storage then just return and have the simulation
2142 // state continue as is.
2143 if (!escapes)
2144 return;
Ted Kremenek28d7eef2008-10-18 03:49:51 +00002145
Ted Kremenek2ddb4b22009-02-14 03:16:10 +00002146 // Otherwise, find all symbols referenced by 'val' that we are tracking
2147 // and stop tracking them.
2148 B.MakeNode(state.scanReachableSymbols<StopTrackingCallback>(val).getState());
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002149}
2150
Ted Kremenek0106e202008-10-24 20:32:50 +00002151std::pair<GRStateRef,bool>
2152CFRefCount::HandleSymbolDeath(GRStateManager& VMgr,
2153 const GRState* St, const Decl* CD,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002154 SymbolRef sid,
Ted Kremenek0106e202008-10-24 20:32:50 +00002155 RefVal V, bool& hasLeak) {
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002156
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002157 GRStateRef state(St, VMgr);
Sanjiv Guptafa451432008-10-31 09:52:39 +00002158 assert ((!V.isReturnedOwned() || CD) &&
Ted Kremenek311f3d42008-10-22 23:56:21 +00002159 "CodeDecl must be available for reporting ReturnOwned errors.");
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002160
Ted Kremenek311f3d42008-10-22 23:56:21 +00002161 if (V.isReturnedOwned() && V.getCount() == 0)
2162 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
Chris Lattner3a8f2942008-11-24 03:33:13 +00002163 std::string s = MD->getSelector().getAsString();
Ted Kremenekcdd3bb22008-11-05 16:54:44 +00002164 if (!followsReturnRule(s.c_str())) {
Ted Kremenek311f3d42008-10-22 23:56:21 +00002165 hasLeak = true;
Ted Kremenek0106e202008-10-24 20:32:50 +00002166 state = state.set<RefBindings>(sid, V ^ RefVal::ErrorLeakReturned);
2167 return std::make_pair(state, true);
Ted Kremenek311f3d42008-10-22 23:56:21 +00002168 }
2169 }
Ted Kremenek63d09ae2008-10-23 01:56:15 +00002170
Ted Kremenek311f3d42008-10-22 23:56:21 +00002171 // All other cases.
2172
2173 hasLeak = V.isOwned() ||
2174 ((V.isNotOwned() || V.isReturnedOwned()) && V.getCount() > 0);
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002175
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002176 if (!hasLeak)
Ted Kremenek0106e202008-10-24 20:32:50 +00002177 return std::make_pair(state.remove<RefBindings>(sid), false);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002178
Ted Kremenek0106e202008-10-24 20:32:50 +00002179 return std::make_pair(state.set<RefBindings>(sid, V ^ RefVal::ErrorLeak),
2180 false);
Ted Kremenek3f3c9c82008-04-16 22:32:20 +00002181}
2182
Ted Kremenek541db372008-04-24 23:57:27 +00002183
Ted Kremenekffefc352008-04-11 22:25:11 +00002184
Ted Kremenek541db372008-04-24 23:57:27 +00002185// Dead symbols.
2186
Ted Kremenek708af042009-02-05 06:50:21 +00002187
Ted Kremenek541db372008-04-24 23:57:27 +00002188
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002189 // Return statements.
2190
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002191void CFRefCount::EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002192 GRExprEngine& Eng,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002193 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002194 ReturnStmt* S,
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002195 ExplodedNode<GRState>* Pred) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002196
2197 Expr* RetE = S->getRetValue();
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002198 if (!RetE)
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002199 return;
2200
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002201 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002202 SymbolRef Sym = state.GetSValAsScalarOrLoc(RetE).getAsLocSymbol();
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002203
Ted Kremenek74556a12009-03-26 03:35:11 +00002204 if (!Sym)
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002205 return;
2206
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002207 // Get the reference count binding (if any).
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002208 const RefVal* T = state.get<RefBindings>(Sym);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002209
2210 if (!T)
2211 return;
2212
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002213 // Change the reference count.
Ted Kremenek6064a362008-07-07 16:21:19 +00002214 RefVal X = *T;
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002215
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002216 switch (X.getKind()) {
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002217 case RefVal::Owned: {
2218 unsigned cnt = X.getCount();
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00002219 assert (cnt > 0);
2220 X = RefVal::makeReturnedOwned(cnt - 1);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002221 break;
2222 }
2223
2224 case RefVal::NotOwned: {
2225 unsigned cnt = X.getCount();
2226 X = cnt ? RefVal::makeReturnedOwned(cnt - 1)
2227 : RefVal::makeReturnedNotOwned();
2228 break;
2229 }
2230
2231 default:
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002232 return;
2233 }
2234
2235 // Update the binding.
Ted Kremenek91781202008-08-17 03:20:02 +00002236 state = state.set<RefBindings>(Sym, X);
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002237 Builder.MakeNode(Dst, S, Pred, state);
Ted Kremenekd9ccf682008-04-17 18:12:53 +00002238}
2239
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002240// Assumptions.
2241
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002242const GRState* CFRefCount::EvalAssume(GRStateManager& VMgr,
2243 const GRState* St,
Zhongxing Xu097fc982008-10-17 05:57:07 +00002244 SVal Cond, bool Assumption,
Ted Kremenekf22f8682008-07-10 22:03:41 +00002245 bool& isFeasible) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002246
2247 // FIXME: We may add to the interface of EvalAssume the list of symbols
2248 // whose assumptions have changed. For now we just iterate through the
2249 // bindings and check if any of the tracked symbols are NULL. This isn't
2250 // too bad since the number of symbols we will track in practice are
2251 // probably small and EvalAssume is only called at branches and a few
2252 // other places.
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002253 RefBindings B = St->get<RefBindings>();
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002254
2255 if (B.isEmpty())
2256 return St;
2257
2258 bool changed = false;
Ted Kremenek91781202008-08-17 03:20:02 +00002259
2260 GRStateRef state(St, VMgr);
2261 RefBindings::Factory& RefBFactory = state.get_context<RefBindings>();
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002262
2263 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002264 // Check if the symbol is null (or equal to any constant).
2265 // If this is the case, stop tracking the symbol.
Zhongxing Xuc6b27d02008-08-29 14:52:36 +00002266 if (VMgr.getSymVal(St, I.getKey())) {
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002267 changed = true;
2268 B = RefBFactory.Remove(B, I.getKey());
2269 }
2270 }
2271
Ted Kremenek91781202008-08-17 03:20:02 +00002272 if (changed)
2273 state = state.set<RefBindings>(B);
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002274
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002275 return state;
Ted Kremenekeef8f1e2008-04-18 19:23:43 +00002276}
Ted Kremeneka7338b42008-03-11 06:39:11 +00002277
Ted Kremenekb6578942009-02-24 19:15:11 +00002278GRStateRef CFRefCount::Update(GRStateRef state, SymbolRef sym,
2279 RefVal V, ArgEffect E,
2280 RefVal::Kind& hasErr) {
Ted Kremenek58dd95b2009-02-18 18:54:33 +00002281
2282 // In GC mode [... release] and [... retain] do nothing.
2283 switch (E) {
2284 default: break;
2285 case IncRefMsg: E = isGCEnabled() ? DoNothing : IncRef; break;
2286 case DecRefMsg: E = isGCEnabled() ? DoNothing : DecRef; break;
Ted Kremenek2126bef2009-02-18 21:57:45 +00002287 case MakeCollectable: E = isGCEnabled() ? DecRef : DoNothing; break;
Ted Kremenekaac82832009-02-23 17:45:03 +00002288 case NewAutoreleasePool: E = isGCEnabled() ? DoNothing :
2289 NewAutoreleasePool; break;
Ted Kremenek58dd95b2009-02-18 18:54:33 +00002290 }
Ted Kremeneka7338b42008-03-11 06:39:11 +00002291
Ted Kremenek6537a642009-03-17 19:42:23 +00002292 // Handle all use-after-releases.
2293 if (!isGCEnabled() && V.getKind() == RefVal::Released) {
2294 V = V ^ RefVal::ErrorUseAfterRelease;
2295 hasErr = V.getKind();
2296 return state.set<RefBindings>(sym, V);
2297 }
2298
Ted Kremenek0d721572008-03-11 17:48:22 +00002299 switch (E) {
2300 default:
2301 assert (false && "Unhandled CFRef transition.");
Ted Kremenek6537a642009-03-17 19:42:23 +00002302
2303 case Dealloc:
2304 // Any use of -dealloc in GC is *bad*.
2305 if (isGCEnabled()) {
2306 V = V ^ RefVal::ErrorDeallocGC;
2307 hasErr = V.getKind();
2308 break;
2309 }
2310
2311 switch (V.getKind()) {
2312 default:
2313 assert(false && "Invalid case.");
2314 case RefVal::Owned:
2315 // The object immediately transitions to the released state.
2316 V = V ^ RefVal::Released;
2317 V.clearCounts();
2318 return state.set<RefBindings>(sym, V);
2319 case RefVal::NotOwned:
2320 V = V ^ RefVal::ErrorDeallocNotOwned;
2321 hasErr = V.getKind();
2322 break;
2323 }
2324 break;
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00002325
Ted Kremenekb7826ab2009-02-25 23:11:49 +00002326 case NewAutoreleasePool:
2327 assert(!isGCEnabled());
2328 return state.add<AutoreleaseStack>(sym);
2329
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00002330 case MayEscape:
2331 if (V.getKind() == RefVal::Owned) {
Ted Kremenek272aa852008-06-25 21:21:56 +00002332 V = V ^ RefVal::NotOwned;
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00002333 break;
2334 }
Ted Kremenek6537a642009-03-17 19:42:23 +00002335
Ted Kremeneka3f30dd2008-05-22 17:31:13 +00002336 // Fall-through.
Ted Kremenek1b4b6562009-02-25 02:54:57 +00002337
Ted Kremenekede40b72008-07-09 18:11:16 +00002338 case DoNothingByRef:
Ted Kremenek0d721572008-03-11 17:48:22 +00002339 case DoNothing:
Ted Kremenekb6578942009-02-24 19:15:11 +00002340 return state;
Ted Kremeneke5a4bb02008-06-30 16:57:41 +00002341
Ted Kremenek9b112d22009-01-28 21:44:40 +00002342 case Autorelease:
Ted Kremenek6537a642009-03-17 19:42:23 +00002343 if (isGCEnabled())
2344 return state;
Ted Kremenek681fb352009-03-20 17:34:15 +00002345
2346 // Update the autorelease counts.
2347 state = SendAutorelease(state, ARCountFactory, sym);
Ted Kremenek6537a642009-03-17 19:42:23 +00002348
2349 // Fall-through.
2350
Ted Kremenek227c5372008-05-06 02:41:27 +00002351 case StopTracking:
Ted Kremenekb6578942009-02-24 19:15:11 +00002352 return state.remove<RefBindings>(sym);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002353
Ted Kremenek0d721572008-03-11 17:48:22 +00002354 case IncRef:
2355 switch (V.getKind()) {
2356 default:
2357 assert(false);
2358
2359 case RefVal::Owned:
Ted Kremenek0d721572008-03-11 17:48:22 +00002360 case RefVal::NotOwned:
Ted Kremenek272aa852008-06-25 21:21:56 +00002361 V = V + 1;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002362 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00002363 case RefVal::Released:
Ted Kremenek6537a642009-03-17 19:42:23 +00002364 // Non-GC cases are handled above.
2365 assert(isGCEnabled());
2366 V = (V ^ RefVal::Owned) + 1;
Ted Kremenek0d721572008-03-11 17:48:22 +00002367 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002368 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002369 break;
2370
Ted Kremenek272aa852008-06-25 21:21:56 +00002371 case SelfOwn:
2372 V = V ^ RefVal::NotOwned;
Ted Kremenek58dd95b2009-02-18 18:54:33 +00002373 // Fall-through.
Ted Kremenek0d721572008-03-11 17:48:22 +00002374 case DecRef:
2375 switch (V.getKind()) {
2376 default:
Ted Kremenek6537a642009-03-17 19:42:23 +00002377 // case 'RefVal::Released' handled above.
Ted Kremenek0d721572008-03-11 17:48:22 +00002378 assert (false);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002379
Ted Kremenek272aa852008-06-25 21:21:56 +00002380 case RefVal::Owned:
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00002381 assert(V.getCount() > 0);
2382 if (V.getCount() == 1) V = V ^ RefVal::Released;
2383 V = V - 1;
Ted Kremenek0d721572008-03-11 17:48:22 +00002384 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00002385
Ted Kremenek272aa852008-06-25 21:21:56 +00002386 case RefVal::NotOwned:
2387 if (V.getCount() > 0)
2388 V = V - 1;
Ted Kremenekc4f81022008-04-10 23:09:18 +00002389 else {
Ted Kremenek272aa852008-06-25 21:21:56 +00002390 V = V ^ RefVal::ErrorReleaseNotOwned;
Ted Kremenek1feab292008-04-16 04:28:53 +00002391 hasErr = V.getKind();
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002392 }
Ted Kremenek0d721572008-03-11 17:48:22 +00002393 break;
Ted Kremenek6537a642009-03-17 19:42:23 +00002394
Ted Kremenek0d721572008-03-11 17:48:22 +00002395 case RefVal::Released:
Ted Kremenek6537a642009-03-17 19:42:23 +00002396 // Non-GC cases are handled above.
2397 assert(isGCEnabled());
Ted Kremenek272aa852008-06-25 21:21:56 +00002398 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek1feab292008-04-16 04:28:53 +00002399 hasErr = V.getKind();
Ted Kremenek6537a642009-03-17 19:42:23 +00002400 break;
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002401 }
Ted Kremenekab2fa2a2008-04-10 23:44:06 +00002402 break;
Ted Kremenek0d721572008-03-11 17:48:22 +00002403 }
Ted Kremenekb6578942009-02-24 19:15:11 +00002404 return state.set<RefBindings>(sym, V);
Ted Kremeneka7338b42008-03-11 06:39:11 +00002405}
2406
Ted Kremenek10fe66d2008-04-09 01:10:13 +00002407//===----------------------------------------------------------------------===//
Ted Kremenek7d421f32008-04-09 23:49:11 +00002408// Error reporting.
Ted Kremenek10fe66d2008-04-09 01:10:13 +00002409//===----------------------------------------------------------------------===//
2410
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002411namespace {
2412
2413 //===-------------===//
2414 // Bug Descriptions. //
2415 //===-------------===//
2416
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002417 class VISIBILITY_HIDDEN CFRefBug : public BugType {
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002418 protected:
2419 CFRefCount& TF;
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002420
2421 CFRefBug(CFRefCount* tf, const char* name)
2422 : BugType(name, "Memory (Core Foundation/Objective-C)"), TF(*tf) {}
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002423 public:
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002424
Ted Kremenek5c3407a2008-05-01 22:50:36 +00002425 CFRefCount& getTF() { return TF; }
Ted Kremenek0ff3f202008-05-05 23:16:31 +00002426 const CFRefCount& getTF() const { return TF; }
2427
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002428 // FIXME: Eventually remove.
2429 virtual const char* getDescription() const = 0;
2430
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002431 virtual bool isLeak() const { return false; }
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002432 };
2433
2434 class VISIBILITY_HIDDEN UseAfterRelease : public CFRefBug {
2435 public:
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002436 UseAfterRelease(CFRefCount* tf)
Ted Kremenek5b1ab102009-04-03 21:10:31 +00002437 : CFRefBug(tf, "Use-after-release") {}
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002438
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002439 const char* getDescription() const {
Ted Kremenekef9d0a82009-02-26 21:04:07 +00002440 return "Reference-counted object is used after it is released";
Ted Kremenek708af042009-02-05 06:50:21 +00002441 }
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002442 };
2443
2444 class VISIBILITY_HIDDEN BadRelease : public CFRefBug {
2445 public:
Ted Kremenekcce60492009-04-24 17:51:19 +00002446 BadRelease(CFRefCount* tf) : CFRefBug(tf, "Bad release") {}
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002447
2448 const char* getDescription() const {
Ted Kremeneke4158502009-04-23 19:11:35 +00002449 return "Incorrect decrement of the reference count of an "
2450 "object is not owned at this point by the caller";
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002451 }
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002452 };
2453
Ted Kremenek6537a642009-03-17 19:42:23 +00002454 class VISIBILITY_HIDDEN DeallocGC : public CFRefBug {
2455 public:
2456 DeallocGC(CFRefCount *tf) : CFRefBug(tf,
2457 "-dealloc called while using GC") {}
2458
2459 const char *getDescription() const {
2460 return "-dealloc called while using GC";
2461 }
2462 };
2463
2464 class VISIBILITY_HIDDEN DeallocNotOwned : public CFRefBug {
2465 public:
2466 DeallocNotOwned(CFRefCount *tf) : CFRefBug(tf,
2467 "-dealloc sent to non-exclusively owned object") {}
2468
2469 const char *getDescription() const {
2470 return "-dealloc sent to object that may be referenced elsewhere";
2471 }
2472 };
2473
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002474 class VISIBILITY_HIDDEN Leak : public CFRefBug {
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002475 const bool isReturn;
2476 protected:
2477 Leak(CFRefCount* tf, const char* name, bool isRet)
2478 : CFRefBug(tf, name), isReturn(isRet) {}
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002479 public:
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002480
Ted Kremenek44274e62009-02-07 22:38:00 +00002481 const char* getDescription() const { return ""; }
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002482
Ted Kremenek538a3ba2009-02-05 00:38:00 +00002483 bool isLeak() const { return true; }
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002484 };
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002485
2486 class VISIBILITY_HIDDEN LeakAtReturn : public Leak {
2487 public:
2488 LeakAtReturn(CFRefCount* tf, const char* name)
2489 : Leak(tf, name, true) {}
2490 };
2491
2492 class VISIBILITY_HIDDEN LeakWithinFunction : public Leak {
2493 public:
2494 LeakWithinFunction(CFRefCount* tf, const char* name)
2495 : Leak(tf, name, false) {}
2496 };
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002497
2498 //===---------===//
2499 // Bug Reports. //
2500 //===---------===//
2501
2502 class VISIBILITY_HIDDEN CFRefReport : public RangedBugReport {
Ted Kremenek8ff05042009-02-07 22:04:05 +00002503 protected:
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002504 SymbolRef Sym;
Ted Kremenekc26c4692009-02-18 03:48:14 +00002505 const CFRefCount &TF;
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002506 public:
Ted Kremenekc26c4692009-02-18 03:48:14 +00002507 CFRefReport(CFRefBug& D, const CFRefCount &tf,
2508 ExplodedNode<GRState> *n, SymbolRef sym)
2509 : RangedBugReport(D, D.getDescription(), n), Sym(sym), TF(tf) {}
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002510
2511 virtual ~CFRefReport() {}
2512
Ted Kremenek5c3407a2008-05-01 22:50:36 +00002513 CFRefBug& getBugType() {
2514 return (CFRefBug&) RangedBugReport::getBugType();
2515 }
2516 const CFRefBug& getBugType() const {
2517 return (const CFRefBug&) RangedBugReport::getBugType();
2518 }
2519
2520 virtual void getRanges(BugReporter& BR, const SourceRange*& beg,
2521 const SourceRange*& end) {
2522
Ted Kremenek198cae02008-05-02 20:53:50 +00002523 if (!getBugType().isLeak())
Ted Kremenek5c3407a2008-05-01 22:50:36 +00002524 RangedBugReport::getRanges(BR, beg, end);
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002525 else
2526 beg = end = 0;
Ted Kremenek5c3407a2008-05-01 22:50:36 +00002527 }
2528
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002529 SymbolRef getSymbol() const { return Sym; }
Ted Kremenekd7e26782008-05-16 18:33:44 +00002530
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002531 PathDiagnosticPiece* getEndPath(BugReporter& BR,
2532 const ExplodedNode<GRState>* N);
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002533
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002534 std::pair<const char**,const char**> getExtraDescriptiveText();
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002535
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002536 PathDiagnosticPiece* VisitNode(const ExplodedNode<GRState>* N,
2537 const ExplodedNode<GRState>* PrevN,
2538 const ExplodedGraph<GRState>& G,
Ted Kremenekc26c4692009-02-18 03:48:14 +00002539 BugReporter& BR,
2540 NodeResolver& NR);
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002541 };
2542
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002543 class VISIBILITY_HIDDEN CFRefLeakReport : public CFRefReport {
Ted Kremenek86617f42009-02-07 22:19:59 +00002544 SourceLocation AllocSite;
2545 const MemRegion* AllocBinding;
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002546 public:
Ted Kremenekc26c4692009-02-18 03:48:14 +00002547 CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2548 ExplodedNode<GRState> *n, SymbolRef sym,
Ted Kremenek44274e62009-02-07 22:38:00 +00002549 GRExprEngine& Eng);
Ted Kremenek8ff05042009-02-07 22:04:05 +00002550
2551 PathDiagnosticPiece* getEndPath(BugReporter& BR,
2552 const ExplodedNode<GRState>* N);
2553
Ted Kremenek86617f42009-02-07 22:19:59 +00002554 SourceLocation getLocation() const { return AllocSite; }
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002555 };
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002556} // end anonymous namespace
2557
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002558void CFRefCount::RegisterChecks(BugReporter& BR) {
Ted Kremenek708af042009-02-05 06:50:21 +00002559 useAfterRelease = new UseAfterRelease(this);
2560 BR.Register(useAfterRelease);
2561
2562 releaseNotOwned = new BadRelease(this);
2563 BR.Register(releaseNotOwned);
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002564
Ted Kremenek6537a642009-03-17 19:42:23 +00002565 deallocGC = new DeallocGC(this);
2566 BR.Register(deallocGC);
2567
2568 deallocNotOwned = new DeallocNotOwned(this);
2569 BR.Register(deallocNotOwned);
2570
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002571 // First register "return" leaks.
2572 const char* name = 0;
2573
2574 if (isGCEnabled())
Ted Kremenekfbf08ff2009-04-02 02:40:45 +00002575 name = "Leak of returned object when using garbage collection";
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002576 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
Ted Kremenekfbf08ff2009-04-02 02:40:45 +00002577 name = "Leak of returned object when not using garbage collection (GC) in "
2578 "dual GC/non-GC code";
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002579 else {
2580 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
Ted Kremenekfbf08ff2009-04-02 02:40:45 +00002581 name = "Leak of returned object";
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002582 }
2583
Ted Kremenek708af042009-02-05 06:50:21 +00002584 leakAtReturn = new LeakAtReturn(this, name);
2585 BR.Register(leakAtReturn);
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002586
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002587 // Second, register leaks within a function/method.
2588 if (isGCEnabled())
Ted Kremenekfbf08ff2009-04-02 02:40:45 +00002589 name = "Leak of object when using garbage collection";
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002590 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
Ted Kremenekfbf08ff2009-04-02 02:40:45 +00002591 name = "Leak of object when not using garbage collection (GC) in "
2592 "dual GC/non-GC code";
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002593 else {
2594 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
Ted Kremenekfbf08ff2009-04-02 02:40:45 +00002595 name = "Leak";
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002596 }
2597
Ted Kremenek708af042009-02-05 06:50:21 +00002598 leakWithinFunction = new LeakWithinFunction(this, name);
2599 BR.Register(leakWithinFunction);
2600
2601 // Save the reference to the BugReporter.
2602 this->BR = &BR;
Ted Kremenekbf6babf2009-02-04 23:49:09 +00002603}
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002604
2605static const char* Msgs[] = {
Ted Kremenekef9d0a82009-02-26 21:04:07 +00002606 // GC only
2607 "Code is compiled to only use garbage collection",
2608 // No GC.
Ted Kremeneka9203882009-03-05 00:12:45 +00002609 "Code is compiled to use reference counts",
Ted Kremenekef9d0a82009-02-26 21:04:07 +00002610 // Hybrid, with GC.
2611 "Code is compiled to use either garbage collection (GC) or reference counts"
2612 " (non-GC). The bug occurs with GC enabled",
2613 // Hybrid, without GC
2614 "Code is compiled to use either garbage collection (GC) or reference counts"
2615 " (non-GC). The bug occurs in non-GC mode"
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002616};
2617
2618std::pair<const char**,const char**> CFRefReport::getExtraDescriptiveText() {
2619 CFRefCount& TF = static_cast<CFRefBug&>(getBugType()).getTF();
2620
2621 switch (TF.getLangOptions().getGCMode()) {
2622 default:
2623 assert(false);
Ted Kremenekcb4709402008-05-01 04:02:04 +00002624
2625 case LangOptions::GCOnly:
2626 assert (TF.isGCEnabled());
Ted Kremenek3d6ddbb2008-08-12 18:30:56 +00002627 return std::make_pair(&Msgs[0], &Msgs[0]+1);
2628
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002629 case LangOptions::NonGC:
2630 assert (!TF.isGCEnabled());
Ted Kremenekfe30beb2008-04-30 23:47:44 +00002631 return std::make_pair(&Msgs[1], &Msgs[1]+1);
2632
2633 case LangOptions::HybridGC:
2634 if (TF.isGCEnabled())
2635 return std::make_pair(&Msgs[2], &Msgs[2]+1);
2636 else
2637 return std::make_pair(&Msgs[3], &Msgs[3]+1);
2638 }
2639}
2640
Ted Kremenek2126bef2009-02-18 21:57:45 +00002641static inline bool contains(const llvm::SmallVectorImpl<ArgEffect>& V,
2642 ArgEffect X) {
2643 for (llvm::SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
2644 I!=E; ++I)
2645 if (*I == X) return true;
2646
2647 return false;
2648}
2649
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002650PathDiagnosticPiece* CFRefReport::VisitNode(const ExplodedNode<GRState>* N,
2651 const ExplodedNode<GRState>* PrevN,
2652 const ExplodedGraph<GRState>& G,
Ted Kremenekc26c4692009-02-18 03:48:14 +00002653 BugReporter& BR,
2654 NodeResolver& NR) {
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002655
Ted Kremenek71745d92009-01-28 05:29:13 +00002656 // Check if the type state has changed.
2657 GRStateManager &StMgr = cast<GRBugReporter>(BR).getStateManager();
2658 GRStateRef PrevSt(PrevN->getState(), StMgr);
2659 GRStateRef CurrSt(N->getState(), StMgr);
Ted Kremenek335a3022009-01-28 05:06:46 +00002660
Ted Kremenek71745d92009-01-28 05:29:13 +00002661 const RefVal* CurrT = CurrSt.get<RefBindings>(Sym);
2662 if (!CurrT) return NULL;
2663
2664 const RefVal& CurrV = *CurrT;
2665 const RefVal* PrevT = PrevSt.get<RefBindings>(Sym);
Ted Kremenek9363fd92008-05-05 17:53:17 +00002666
Ted Kremenek2126bef2009-02-18 21:57:45 +00002667 // Create a string buffer to constain all the useful things we want
2668 // to tell the user.
2669 std::string sbuf;
2670 llvm::raw_string_ostream os(sbuf);
2671
Ted Kremenekc26c4692009-02-18 03:48:14 +00002672 // This is the allocation site since the previous node had no bindings
2673 // for this symbol.
Ted Kremeneka8503952008-04-18 04:55:01 +00002674 if (!PrevT) {
Ted Kremenek9363fd92008-05-05 17:53:17 +00002675 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2676
Ted Kremenek2e2b1332009-01-28 05:15:02 +00002677 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2678 // Get the name of the callee (if it is available).
Zhongxing Xucac107a2009-04-20 05:24:46 +00002679 SVal X = CurrSt.GetSValAsScalarOrLoc(CE->getCallee());
2680 if (const FunctionDecl* FD = X.getAsFunctionDecl())
2681 os << "Call to function '" << FD->getNameAsString() <<'\'';
Ted Kremenek2e2b1332009-01-28 05:15:02 +00002682 else
Ted Kremenekb4bf8cf2009-01-28 06:01:42 +00002683 os << "function call";
Ted Kremenek2e2b1332009-01-28 05:15:02 +00002684 }
2685 else {
2686 assert (isa<ObjCMessageExpr>(S));
Ted Kremenekb4bf8cf2009-01-28 06:01:42 +00002687 os << "Method";
Ted Kremenek9363fd92008-05-05 17:53:17 +00002688 }
Ted Kremenek2e2b1332009-01-28 05:15:02 +00002689
Ted Kremenek18878b12009-01-28 06:06:36 +00002690 if (CurrV.getObjKind() == RetEffect::CF) {
2691 os << " returns a Core Foundation object with a ";
2692 }
2693 else {
2694 assert (CurrV.getObjKind() == RetEffect::ObjC);
2695 os << " returns an Objective-C object with a ";
2696 }
Ted Kremenekb4bf8cf2009-01-28 06:01:42 +00002697
Ted Kremenekabe30922009-01-28 06:25:48 +00002698 if (CurrV.isOwned()) {
2699 os << "+1 retain count (owning reference).";
2700
2701 if (static_cast<CFRefBug&>(getBugType()).getTF().isGCEnabled()) {
2702 assert(CurrV.getObjKind() == RetEffect::CF);
2703 os << " "
2704 "Core Foundation objects are not automatically garbage collected.";
2705 }
2706 }
Ted Kremeneka8503952008-04-18 04:55:01 +00002707 else {
2708 assert (CurrV.isNotOwned());
Ted Kremenek2e2b1332009-01-28 05:15:02 +00002709 os << "+0 retain count (non-owning reference).";
Ted Kremeneka8503952008-04-18 04:55:01 +00002710 }
Ted Kremenek9363fd92008-05-05 17:53:17 +00002711
Ted Kremenek2fba6152009-04-01 06:13:56 +00002712 PathDiagnosticLocation Pos(S, BR.getContext().getSourceManager());
2713 return new PathDiagnosticEventPiece(Pos, os.str());
Ted Kremeneka8503952008-04-18 04:55:01 +00002714 }
Ted Kremeneka8503952008-04-18 04:55:01 +00002715
Ted Kremenek2126bef2009-02-18 21:57:45 +00002716 // Gather up the effects that were performed on the object at this
2717 // program point
2718 llvm::SmallVector<ArgEffect, 2> AEffects;
2719
Ted Kremenekc26c4692009-02-18 03:48:14 +00002720 if (const RetainSummary *Summ = TF.getSummaryOfNode(NR.getOriginalNode(N))) {
2721 // We only have summaries attached to nodes after evaluating CallExpr and
2722 // ObjCMessageExprs.
2723 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2724
Ted Kremenekc26c4692009-02-18 03:48:14 +00002725 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2726 // Iterate through the parameter expressions and see if the symbol
2727 // was ever passed as an argument.
2728 unsigned i = 0;
2729
2730 for (CallExpr::arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
2731 AI!=AE; ++AI, ++i) {
Ted Kremenek2126bef2009-02-18 21:57:45 +00002732
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002733 // Retrieve the value of the argument. Is it the symbol
2734 // we are interested in?
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002735 if (CurrSt.GetSValAsScalarOrLoc(*AI).getAsLocSymbol() != Sym)
Ted Kremenekc26c4692009-02-18 03:48:14 +00002736 continue;
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002737
Ted Kremenekc26c4692009-02-18 03:48:14 +00002738 // We have an argument. Get the effect!
2739 AEffects.push_back(Summ->getArg(i));
Ted Kremenek752b5842008-04-18 05:32:44 +00002740 }
Ted Kremenekc26c4692009-02-18 03:48:14 +00002741 }
2742 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002743 if (Expr *receiver = ME->getReceiver())
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002744 if (CurrSt.GetSValAsScalarOrLoc(receiver).getAsLocSymbol() == Sym) {
Ted Kremenek2126bef2009-02-18 21:57:45 +00002745 // The symbol we are tracking is the receiver.
2746 AEffects.push_back(Summ->getReceiverEffect());
2747 }
Ted Kremenekc26c4692009-02-18 03:48:14 +00002748 }
Ted Kremeneka8503952008-04-18 04:55:01 +00002749 }
Ted Kremenekc26c4692009-02-18 03:48:14 +00002750
Ted Kremenek2126bef2009-02-18 21:57:45 +00002751 do {
2752 // Get the previous type state.
2753 RefVal PrevV = *PrevT;
Ted Kremenek6537a642009-03-17 19:42:23 +00002754
2755 // Specially handle -dealloc.
2756 if (!TF.isGCEnabled() && contains(AEffects, Dealloc)) {
2757 // Determine if the object's reference count was pushed to zero.
2758 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2759 // We may not have transitioned to 'release' if we hit an error.
2760 // This case is handled elsewhere.
2761 if (CurrV.getKind() == RefVal::Released) {
2762 assert(CurrV.getCount() == 0);
2763 os << "Object released by directly sending the '-dealloc' message";
2764 break;
2765 }
2766 }
Ted Kremenek2126bef2009-02-18 21:57:45 +00002767
2768 // Specially handle CFMakeCollectable and friends.
2769 if (contains(AEffects, MakeCollectable)) {
2770 // Get the name of the function.
2771 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
Zhongxing Xucac107a2009-04-20 05:24:46 +00002772 SVal X = CurrSt.GetSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee());
2773 const FunctionDecl* FD = X.getAsFunctionDecl();
2774 const std::string& FName = FD->getNameAsString();
Ted Kremenek2126bef2009-02-18 21:57:45 +00002775
2776 if (TF.isGCEnabled()) {
2777 // Determine if the object's reference count was pushed to zero.
2778 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2779
2780 os << "In GC mode a call to '" << FName
2781 << "' decrements an object's retain count and registers the "
2782 "object with the garbage collector. ";
2783
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00002784 if (CurrV.getKind() == RefVal::Released) {
2785 assert(CurrV.getCount() == 0);
2786 os << "Since it now has a 0 retain count the object can be "
Ted Kremenek2126bef2009-02-18 21:57:45 +00002787 "automatically collected by the garbage collector.";
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00002788 }
Ted Kremenek2126bef2009-02-18 21:57:45 +00002789 else
2790 os << "An object must have a 0 retain count to be garbage collected. "
2791 "After this call its retain count is +" << CurrV.getCount()
2792 << '.';
2793 }
2794 else
2795 os << "When GC is not enabled a call to '" << FName
2796 << "' has no effect on its argument.";
2797
2798 // Nothing more to say.
2799 break;
2800 }
2801
2802 // Determine if the typestate has changed.
2803 if (!(PrevV == CurrV))
2804 switch (CurrV.getKind()) {
Ted Kremenekc26c4692009-02-18 03:48:14 +00002805 case RefVal::Owned:
2806 case RefVal::NotOwned:
2807
2808 if (PrevV.getCount() == CurrV.getCount())
2809 return 0;
2810
2811 if (PrevV.getCount() > CurrV.getCount())
2812 os << "Reference count decremented.";
2813 else
2814 os << "Reference count incremented.";
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00002815
Ted Kremenekef9d0a82009-02-26 21:04:07 +00002816 if (unsigned Count = CurrV.getCount())
2817 os << " The object now has a +" << Count << " retain count.";
Ted Kremenekb7d9c9e2009-02-18 22:57:22 +00002818
2819 if (PrevV.getKind() == RefVal::Released) {
2820 assert(TF.isGCEnabled() && CurrV.getCount() > 0);
2821 os << " The object is not eligible for garbage collection until the "
2822 "retain count reaches 0 again.";
2823 }
2824
Ted Kremenekc26c4692009-02-18 03:48:14 +00002825 break;
2826
2827 case RefVal::Released:
2828 os << "Object released.";
2829 break;
2830
2831 case RefVal::ReturnedOwned:
2832 os << "Object returned to caller as an owning reference (single retain "
2833 "count transferred to caller).";
2834 break;
2835
2836 case RefVal::ReturnedNotOwned:
2837 os << "Object returned to caller with a +0 (non-owning) retain count.";
2838 break;
2839
2840 default:
2841 return NULL;
Ted Kremenek2126bef2009-02-18 21:57:45 +00002842 }
2843
2844 // Emit any remaining diagnostics for the argument effects (if any).
2845 for (llvm::SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
2846 E=AEffects.end(); I != E; ++I) {
2847
2848 // A bunch of things have alternate behavior under GC.
2849 if (TF.isGCEnabled())
2850 switch (*I) {
2851 default: break;
2852 case Autorelease:
2853 os << "In GC mode an 'autorelease' has no effect.";
2854 continue;
2855 case IncRefMsg:
2856 os << "In GC mode the 'retain' message has no effect.";
2857 continue;
2858 case DecRefMsg:
2859 os << "In GC mode the 'release' message has no effect.";
2860 continue;
2861 }
Ted Kremenekc26c4692009-02-18 03:48:14 +00002862 }
Ted Kremenek2126bef2009-02-18 21:57:45 +00002863 } while(0);
Ted Kremenekc26c4692009-02-18 03:48:14 +00002864
2865 if (os.str().empty())
2866 return 0; // We have nothing to say!
Ted Kremeneka8503952008-04-18 04:55:01 +00002867
2868 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
Ted Kremenek2fba6152009-04-01 06:13:56 +00002869 PathDiagnosticLocation Pos(S, BR.getContext().getSourceManager());
Ted Kremenek23563642009-03-06 23:58:11 +00002870 PathDiagnosticPiece* P = new PathDiagnosticEventPiece(Pos, os.str());
Ted Kremeneka8503952008-04-18 04:55:01 +00002871
2872 // Add the range by scanning the children of the statement for any bindings
2873 // to Sym.
Ted Kremeneka8503952008-04-18 04:55:01 +00002874 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I)
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002875 if (Expr* Exp = dyn_cast_or_null<Expr>(*I))
Ted Kremenekb6ac0e52009-03-04 00:13:50 +00002876 if (CurrSt.GetSValAsScalarOrLoc(Exp).getAsLocSymbol() == Sym) {
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002877 P->addRange(Exp->getSourceRange());
2878 break;
2879 }
Ted Kremeneka8503952008-04-18 04:55:01 +00002880
2881 return P;
Ted Kremenek2be7ddb2008-04-18 03:39:05 +00002882}
2883
Ted Kremenekb15eba42008-10-04 05:50:14 +00002884namespace {
2885class VISIBILITY_HIDDEN FindUniqueBinding :
2886 public StoreManager::BindingsHandler {
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002887 SymbolRef Sym;
Ted Kremenekb6b0bb82009-03-05 16:31:07 +00002888 const MemRegion* Binding;
Ted Kremenekb15eba42008-10-04 05:50:14 +00002889 bool First;
2890
2891 public:
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002892 FindUniqueBinding(SymbolRef sym) : Sym(sym), Binding(0), First(true) {}
Ted Kremenekb15eba42008-10-04 05:50:14 +00002893
Ted Kremenekb6b0bb82009-03-05 16:31:07 +00002894 bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
2895 SVal val) {
Ted Kremenek74556a12009-03-26 03:35:11 +00002896
2897 SymbolRef SymV = val.getAsSymbol();
2898 if (!SymV || SymV != Sym)
Ted Kremenekb15eba42008-10-04 05:50:14 +00002899 return true;
Ted Kremenek9577c1e2009-03-03 22:06:47 +00002900
Ted Kremenekb15eba42008-10-04 05:50:14 +00002901 if (Binding) {
2902 First = false;
2903 return false;
2904 }
2905 else
2906 Binding = R;
2907
2908 return true;
2909 }
2910
2911 operator bool() { return First && Binding; }
Ted Kremenekb6b0bb82009-03-05 16:31:07 +00002912 const MemRegion* getRegion() { return Binding; }
Ted Kremenekb15eba42008-10-04 05:50:14 +00002913};
2914}
2915
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002916static std::pair<const ExplodedNode<GRState>*,const MemRegion*>
Ted Kremenek86617f42009-02-07 22:19:59 +00002917GetAllocationSite(GRStateManager& StateMgr, const ExplodedNode<GRState>* N,
Ted Kremenekb9cd9a72008-12-05 02:27:51 +00002918 SymbolRef Sym) {
Ted Kremenekd7e26782008-05-16 18:33:44 +00002919
Ted Kremenekbe9b6f72008-08-29 00:47:32 +00002920 // Find both first node that referred to the tracked symbol and the
2921 // memory location that value was store to.
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002922 const ExplodedNode<GRState>* Last = N;
2923 const MemRegion* FirstBinding = 0;
Ted Kremenekd7e26782008-05-16 18:33:44 +00002924
2925 while (N) {
Ted Kremenekabd89ac2008-08-13 04:27:00 +00002926 const GRState* St = N->getState();
Ted Kremenek4ae925c2008-08-14 21:16:54 +00002927 RefBindings B = St->get<RefBindings>();
Ted Kremenekd7e26782008-05-16 18:33:44 +00002928
Ted Kremenek6064a362008-07-07 16:21:19 +00002929 if (!B.lookup(Sym))
Ted Kremenekd7e26782008-05-16 18:33:44 +00002930 break;
Ted Kremenekbe9b6f72008-08-29 00:47:32 +00002931
Ted Kremenek86617f42009-02-07 22:19:59 +00002932 FindUniqueBinding FB(Sym);
2933 StateMgr.iterBindings(St, FB);
2934 if (FB) FirstBinding = FB.getRegion();
Ted Kremenekd7e26782008-05-16 18:33:44 +00002935
Ted Kremenekd7e26782008-05-16 18:33:44 +00002936 Last = N;
2937 N = N->pred_empty() ? NULL : *(N->pred_begin());
2938 }
2939
Ted Kremenekbe9b6f72008-08-29 00:47:32 +00002940 return std::make_pair(Last, FirstBinding);
Ted Kremenekd7e26782008-05-16 18:33:44 +00002941}
Ted Kremenek4c479322008-05-06 23:07:13 +00002942
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002943PathDiagnosticPiece*
2944CFRefReport::getEndPath(BugReporter& br, const ExplodedNode<GRState>* EndN) {
Ted Kremenek86953652008-05-22 23:45:19 +00002945 // Tell the BugReporter to report cases when the tracked symbol is
2946 // assigned to different variables, etc.
Ted Kremenek6537a642009-03-17 19:42:23 +00002947 GRBugReporter& BR = cast<GRBugReporter>(br);
Ted Kremenekba1c7ed2008-07-02 21:24:01 +00002948 cast<GRBugReporter>(BR).addNotableSymbol(Sym);
Ted Kremenek8ff05042009-02-07 22:04:05 +00002949 return RangedBugReport::getEndPath(BR, EndN);
2950}
2951
2952PathDiagnosticPiece*
2953CFRefLeakReport::getEndPath(BugReporter& br, const ExplodedNode<GRState>* EndN){
2954
2955 GRBugReporter& BR = cast<GRBugReporter>(br);
2956 // Tell the BugReporter to report cases when the tracked symbol is
2957 // assigned to different variables, etc.
2958 cast<GRBugReporter>(BR).addNotableSymbol(Sym);
2959
2960 // We are reporting a leak. Walk up the graph to get to the first node where
2961 // the symbol appeared, and also get the first VarDecl that tracked object
Ted Kremenekd7e26782008-05-16 18:33:44 +00002962 // is stored to.
Ted Kremenek3f6c6802009-01-24 00:55:43 +00002963 const ExplodedNode<GRState>* AllocNode = 0;
2964 const MemRegion* FirstBinding = 0;
Ted Kremenekbe9b6f72008-08-29 00:47:32 +00002965
2966 llvm::tie(AllocNode, FirstBinding) =
Ted Kremenek86617f42009-02-07 22:19:59 +00002967 GetAllocationSite(BR.getStateManager(), EndN, Sym);
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002968
Ted Kremenekd7e26782008-05-16 18:33:44 +00002969 // Get the allocate site.
Ted Kremenekd31ceaf2009-04-07 00:12:43 +00002970 assert(AllocNode);
Ted Kremenekd7e26782008-05-16 18:33:44 +00002971 Stmt* FirstStmt = cast<PostStmt>(AllocNode->getLocation()).getStmt();
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002972
Ted Kremenekea794e92008-05-05 18:50:19 +00002973 SourceManager& SMgr = BR.getContext().getSourceManager();
Chris Lattner18c8dc02009-01-16 07:36:28 +00002974 unsigned AllocLine =SMgr.getInstantiationLineNumber(FirstStmt->getLocStart());
Ted Kremenekfe4d2312008-05-01 23:13:35 +00002975
Ted Kremenek505dc672009-04-07 04:54:20 +00002976 // Compute an actual location for the leak. Sometimes a leak doesn't
2977 // occur at an actual statement (e.g., transition between blocks; end
2978 // of function) so we need to walk the graph and compute a real location.
Ted Kremenekd31ceaf2009-04-07 00:12:43 +00002979 const ExplodedNode<GRState>* LeakN = EndN;
2980 PathDiagnosticLocation L;
2981
2982 while (LeakN) {
2983 ProgramPoint P = LeakN->getLocation();
2984
2985 if (const PostStmt *PS = dyn_cast<PostStmt>(&P)) {
2986 L = PathDiagnosticLocation(PS->getStmt()->getLocStart(), SMgr);
2987 break;
2988 }
2989 else if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
2990 if (const Stmt* Term = BE->getSrc()->getTerminator()) {
2991 L = PathDiagnosticLocation(Term->getLocStart(), SMgr);
2992 break;
2993 }
2994 }
2995
Ted Kremenekd31ceaf2009-04-07 00:12:43 +00002996 LeakN = LeakN->succ_empty() ? 0 : *(LeakN->succ_begin());
2997 }
2998
2999 if (!L.isValid()) {
Douglas Gregore3241e92009-04-18 00:02:19 +00003000 CompoundStmt *CS
3001 = BR.getStateManager().getCodeDecl().getBody(BR.getContext());
Ted Kremenekd31ceaf2009-04-07 00:12:43 +00003002 L = PathDiagnosticLocation(CS->getRBracLoc(), SMgr);
3003 }
3004
Ted Kremenek59f9fe12009-02-07 21:59:45 +00003005 std::string sbuf;
3006 llvm::raw_string_ostream os(sbuf);
Ted Kremenek198cae02008-05-02 20:53:50 +00003007
Ted Kremenekea794e92008-05-05 18:50:19 +00003008 os << "Object allocated on line " << AllocLine;
Ted Kremenek198cae02008-05-02 20:53:50 +00003009
Ted Kremenekbe9b6f72008-08-29 00:47:32 +00003010 if (FirstBinding)
Ted Kremenekb15eba42008-10-04 05:50:14 +00003011 os << " and stored into '" << FirstBinding->getString() << '\'';
3012
Ted Kremenek311f3d42008-10-22 23:56:21 +00003013 // Get the retain count.
3014 const RefVal* RV = EndN->getState()->get<RefBindings>(Sym);
3015
3016 if (RV->getKind() == RefVal::ErrorLeakReturned) {
Ted Kremenekf9544fe2008-12-02 01:26:07 +00003017 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
3018 // ojbects. Only "copy", "alloc", "retain" and "new" transfer ownership
3019 // to the caller for NS objects.
Ted Kremenek311f3d42008-10-22 23:56:21 +00003020 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(BR.getGraph().getCodeDecl());
3021 os << " is returned from a method whose name ('"
Chris Lattner3a8f2942008-11-24 03:33:13 +00003022 << MD.getSelector().getAsString()
Ted Kremenek35920ed2009-01-07 00:39:56 +00003023 << "') does not contain 'copy' or otherwise starts with"
Ted Kremeneka05446c2008-10-24 21:22:44 +00003024 " 'new' or 'alloc'. This violates the naming convention rules given"
Ted Kremenek311f3d42008-10-22 23:56:21 +00003025 " in the Memory Management Guide for Cocoa (object leaked).";
3026 }
3027 else
Ted Kremeneka05446c2008-10-24 21:22:44 +00003028 os << " is no longer referenced after this point and has a retain count of"
3029 " +"
Ted Kremenek311f3d42008-10-22 23:56:21 +00003030 << RV->getCount() << " (object leaked).";
Ted Kremenekfe4d2312008-05-01 23:13:35 +00003031
Ted Kremenek23563642009-03-06 23:58:11 +00003032 return new PathDiagnosticEventPiece(L, os.str());
Ted Kremenekfe4d2312008-05-01 23:13:35 +00003033}
3034
Ted Kremenek7f3f41a2008-04-17 23:43:50 +00003035
Ted Kremenekc26c4692009-02-18 03:48:14 +00003036CFRefLeakReport::CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
3037 ExplodedNode<GRState> *n,
Ted Kremenek44274e62009-02-07 22:38:00 +00003038 SymbolRef sym, GRExprEngine& Eng)
Ted Kremenekc26c4692009-02-18 03:48:14 +00003039 : CFRefReport(D, tf, n, sym)
Ted Kremenek86617f42009-02-07 22:19:59 +00003040{
3041
Ted Kremenekd7e26782008-05-16 18:33:44 +00003042 // Most bug reports are cached at the location where they occured.
3043 // With leaks, we want to unique them by the location where they were
Ted Kremenek86617f42009-02-07 22:19:59 +00003044 // allocated, and only report a single path. To do this, we need to find
3045 // the allocation site of a piece of tracked memory, which we do via a
3046 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
3047 // Note that this is *not* the trimmed graph; we are guaranteed, however,
3048 // that all ancestor nodes that represent the allocation site have the
3049 // same SourceLocation.
3050 const ExplodedNode<GRState>* AllocNode = 0;
3051
3052 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding.
Ted Kremenek44274e62009-02-07 22:38:00 +00003053 GetAllocationSite(Eng.getStateManager(), getEndNode(), getSymbol());
Ted Kremenek86617f42009-02-07 22:19:59 +00003054
Ted Kremenek86617f42009-02-07 22:19:59 +00003055 // Get the SourceLocation for the allocation site.
Ted Kremenek44274e62009-02-07 22:38:00 +00003056 ProgramPoint P = AllocNode->getLocation();
Ted Kremenek86617f42009-02-07 22:19:59 +00003057 AllocSite = cast<PostStmt>(P).getStmt()->getLocStart();
Ted Kremenek44274e62009-02-07 22:38:00 +00003058
3059 // Fill in the description of the bug.
3060 Description.clear();
3061 llvm::raw_string_ostream os(Description);
3062 SourceManager& SMgr = Eng.getContext().getSourceManager();
3063 unsigned AllocLine = SMgr.getInstantiationLineNumber(AllocSite);
Ted Kremenek91f51ce2009-02-07 22:54:59 +00003064 os << "Potential leak of object allocated on line " << AllocLine;
3065
3066 // FIXME: AllocBinding doesn't get populated for RegionStore yet.
3067 if (AllocBinding)
Ted Kremenek5ee01662009-04-02 03:42:38 +00003068 os << " and stored into '" << AllocBinding->getString() << '\'';
Ted Kremenekd7e26782008-05-16 18:33:44 +00003069}
3070
Ted Kremeneka7338b42008-03-11 06:39:11 +00003071//===----------------------------------------------------------------------===//
Ted Kremenek708af042009-02-05 06:50:21 +00003072// Handle dead symbols and end-of-path.
3073//===----------------------------------------------------------------------===//
3074
3075void CFRefCount::EvalEndPath(GRExprEngine& Eng,
3076 GREndPathNodeBuilder<GRState>& Builder) {
3077
3078 const GRState* St = Builder.getState();
3079 RefBindings B = St->get<RefBindings>();
3080
3081 llvm::SmallVector<std::pair<SymbolRef, bool>, 10> Leaked;
3082 const Decl* CodeDecl = &Eng.getGraph().getCodeDecl();
3083
3084 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
3085 bool hasLeak = false;
3086
3087 std::pair<GRStateRef, bool> X =
Ted Kremenek9577c1e2009-03-03 22:06:47 +00003088 HandleSymbolDeath(Eng.getStateManager(), St, CodeDecl,
3089 (*I).first, (*I).second, hasLeak);
Ted Kremenek708af042009-02-05 06:50:21 +00003090
3091 St = X.first;
3092 if (hasLeak) Leaked.push_back(std::make_pair((*I).first, X.second));
3093 }
3094
3095 if (Leaked.empty())
3096 return;
3097
3098 ExplodedNode<GRState>* N = Builder.MakeNode(St);
3099
3100 if (!N)
3101 return;
3102
3103 for (llvm::SmallVector<std::pair<SymbolRef,bool>, 10>::iterator
3104 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3105
3106 CFRefBug *BT = static_cast<CFRefBug*>(I->second ? leakAtReturn
3107 : leakWithinFunction);
3108 assert(BT && "BugType not initialized.");
Ted Kremenekc034f712009-04-07 05:07:44 +00003109 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N, I->first, Eng);
Ted Kremenek708af042009-02-05 06:50:21 +00003110 BR->EmitReport(report);
3111 }
3112}
3113
3114void CFRefCount::EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
3115 GRExprEngine& Eng,
3116 GRStmtNodeBuilder<GRState>& Builder,
3117 ExplodedNode<GRState>* Pred,
3118 Stmt* S,
3119 const GRState* St,
3120 SymbolReaper& SymReaper) {
3121
Ted Kremenek876d8df2009-02-19 23:47:02 +00003122 // FIXME: a lot of copy-and-paste from EvalEndPath. Refactor.
Ted Kremenek708af042009-02-05 06:50:21 +00003123 RefBindings B = St->get<RefBindings>();
3124 llvm::SmallVector<std::pair<SymbolRef,bool>, 10> Leaked;
3125
3126 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3127 E = SymReaper.dead_end(); I != E; ++I) {
3128
3129 const RefVal* T = B.lookup(*I);
3130 if (!T) continue;
3131
3132 bool hasLeak = false;
3133
3134 std::pair<GRStateRef, bool> X
Ted Kremenek876d8df2009-02-19 23:47:02 +00003135 = HandleSymbolDeath(Eng.getStateManager(), St, 0, *I, *T, hasLeak);
Ted Kremenek708af042009-02-05 06:50:21 +00003136
3137 St = X.first;
3138
3139 if (hasLeak)
3140 Leaked.push_back(std::make_pair(*I,X.second));
3141 }
3142
Ted Kremenek876d8df2009-02-19 23:47:02 +00003143 if (!Leaked.empty()) {
3144 // Create a new intermediate node representing the leak point. We
3145 // use a special program point that represents this checker-specific
3146 // transition. We use the address of RefBIndex as a unique tag for this
3147 // checker. We will create another node (if we don't cache out) that
3148 // removes the retain-count bindings from the state.
3149 // NOTE: We use 'generateNode' so that it does interplay with the
3150 // auto-transition logic.
3151 ExplodedNode<GRState>* N =
3152 Builder.generateNode(PostStmtCustom(S, &LeakProgramPointTag), St, Pred);
Ted Kremenek708af042009-02-05 06:50:21 +00003153
Ted Kremenek876d8df2009-02-19 23:47:02 +00003154 if (!N)
3155 return;
3156
3157 // Generate the bug reports.
3158 for (llvm::SmallVectorImpl<std::pair<SymbolRef,bool> >::iterator
3159 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3160
3161 CFRefBug *BT = static_cast<CFRefBug*>(I->second ? leakAtReturn
3162 : leakWithinFunction);
3163 assert(BT && "BugType not initialized.");
Ted Kremenek56c70aa2009-02-23 16:54:00 +00003164 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N,
3165 I->first, Eng);
Ted Kremenek876d8df2009-02-19 23:47:02 +00003166 BR->EmitReport(report);
3167 }
Ted Kremenek708af042009-02-05 06:50:21 +00003168
Ted Kremenek876d8df2009-02-19 23:47:02 +00003169 Pred = N;
Ted Kremenek708af042009-02-05 06:50:21 +00003170 }
Ted Kremenek876d8df2009-02-19 23:47:02 +00003171
3172 // Now generate a new node that nukes the old bindings.
3173 GRStateRef state(St, Eng.getStateManager());
3174 RefBindings::Factory& F = state.get_context<RefBindings>();
3175
3176 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3177 E = SymReaper.dead_end(); I!=E; ++I)
3178 B = F.Remove(B, *I);
3179
3180 state = state.set<RefBindings>(B);
3181 Builder.MakeNode(Dst, S, Pred, state);
Ted Kremenek708af042009-02-05 06:50:21 +00003182}
3183
3184void CFRefCount::ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
3185 GRStmtNodeBuilder<GRState>& Builder,
3186 Expr* NodeExpr, Expr* ErrorExpr,
3187 ExplodedNode<GRState>* Pred,
3188 const GRState* St,
3189 RefVal::Kind hasErr, SymbolRef Sym) {
3190 Builder.BuildSinks = true;
3191 GRExprEngine::NodeTy* N = Builder.MakeNode(Dst, NodeExpr, Pred, St);
3192
3193 if (!N) return;
3194
3195 CFRefBug *BT = 0;
3196
Ted Kremenek6537a642009-03-17 19:42:23 +00003197 switch (hasErr) {
3198 default:
3199 assert(false && "Unhandled error.");
3200 return;
3201 case RefVal::ErrorUseAfterRelease:
3202 BT = static_cast<CFRefBug*>(useAfterRelease);
3203 break;
3204 case RefVal::ErrorReleaseNotOwned:
3205 BT = static_cast<CFRefBug*>(releaseNotOwned);
3206 break;
3207 case RefVal::ErrorDeallocGC:
3208 BT = static_cast<CFRefBug*>(deallocGC);
3209 break;
3210 case RefVal::ErrorDeallocNotOwned:
3211 BT = static_cast<CFRefBug*>(deallocNotOwned);
3212 break;
Ted Kremenek708af042009-02-05 06:50:21 +00003213 }
3214
Ted Kremenekc26c4692009-02-18 03:48:14 +00003215 CFRefReport *report = new CFRefReport(*BT, *this, N, Sym);
Ted Kremenek708af042009-02-05 06:50:21 +00003216 report->addRange(ErrorExpr->getSourceRange());
3217 BR->EmitReport(report);
3218}
3219
3220//===----------------------------------------------------------------------===//
Ted Kremenekb1983ba2008-04-10 22:16:52 +00003221// Transfer function creation for external clients.
Ted Kremeneka7338b42008-03-11 06:39:11 +00003222//===----------------------------------------------------------------------===//
3223
Ted Kremenekfe30beb2008-04-30 23:47:44 +00003224GRTransferFuncs* clang::MakeCFRefCountTF(ASTContext& Ctx, bool GCEnabled,
3225 const LangOptions& lopts) {
Ted Kremenek9f20c7c2008-07-22 16:21:24 +00003226 return new CFRefCount(Ctx, GCEnabled, lopts);
Ted Kremeneka4c74292008-04-10 22:58:08 +00003227}