blob: 052a610db1b4682bbfce8a930b9fe7a61f74a681 [file] [log] [blame]
Chris Lattnerbda0b622008-03-15 23:59:48 +00001// CFRefCount.cpp - Transfer functions for tracking simple values -*- C++ -*--//
Ted Kremenek2fff37e2008-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 Greif843e9342008-03-06 10:40:09 +000010// This file defines the methods for CFRefCount, which implements
Ted Kremenek2fff37e2008-03-06 00:08:09 +000011// a reference count checker for Core Foundation (Mac OS X).
12//
13//===----------------------------------------------------------------------===//
14
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000015#include "GRSimpleVals.h"
Ted Kremenek072192b2008-04-30 23:47:44 +000016#include "clang/Basic/LangOptions.h"
Ted Kremenekc9fa2f72008-05-01 23:13:35 +000017#include "clang/Basic/SourceManager.h"
Ted Kremenek41573eb2009-02-14 01:43:44 +000018#include "clang/Analysis/PathSensitive/GRExprEngineBuilders.h"
Ted Kremenekb9d17f92008-08-17 03:20:02 +000019#include "clang/Analysis/PathSensitive/GRStateTrait.h"
Ted Kremenek4dc41cc2008-03-31 18:26:32 +000020#include "clang/Analysis/PathDiagnostic.h"
Ted Kremenek2fff37e2008-03-06 00:08:09 +000021#include "clang/Analysis/LocalCheckers.h"
Ted Kremenekfa34b332008-04-09 01:10:13 +000022#include "clang/Analysis/PathDiagnostic.h"
23#include "clang/Analysis/PathSensitive/BugReporter.h"
Ted Kremenek5216ad72009-02-14 03:16:10 +000024#include "clang/Analysis/PathSensitive/SymbolManager.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000025#include "clang/AST/DeclObjC.h"
Ted Kremenek6b3a0f72008-03-11 06:39:11 +000026#include "llvm/ADT/DenseMap.h"
27#include "llvm/ADT/FoldingSet.h"
28#include "llvm/ADT/ImmutableMap.h"
Ted Kremenek6d348932008-10-21 15:53:15 +000029#include "llvm/ADT/ImmutableList.h"
Ted Kremenek900a2d72008-05-07 18:36:45 +000030#include "llvm/ADT/StringExtras.h"
Ted Kremenekfa34b332008-04-09 01:10:13 +000031#include "llvm/Support/Compiler.h"
Ted Kremenek6ed9afc2008-05-16 18:33:44 +000032#include "llvm/ADT/STLExtras.h"
Ted Kremenekf3948042008-03-11 19:44:10 +000033#include <ostream>
Ted Kremenek98530452008-08-12 20:41:56 +000034#include <stdarg.h>
Ted Kremenek2fff37e2008-03-06 00:08:09 +000035
36using namespace clang;
Ted Kremenek5c74d502008-10-24 21:18:08 +000037
38//===----------------------------------------------------------------------===//
39// Utility functions.
40//===----------------------------------------------------------------------===//
41
Ted Kremenek5c74d502008-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 Kremenekb80976c2009-02-21 05:13:43 +000054
55using llvm::CStrInCStrNoCase;
Ted Kremenek39868cd2009-02-21 18:26:02 +000056using llvm::StringsEqualNoCase;
Ted Kremenekb80976c2009-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 Kremenek39868cd2009-02-21 18:26:02 +0000116 if (AtBeginning && StringsEqualNoCase("new", s, len))
Ted Kremenekb80976c2009-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 Kremenek8be2a672009-03-13 20:27:06 +0000122 if (C == NoConvention && StringsEqualNoCase("copy", s, len))
Ted Kremenekb80976c2009-02-21 05:13:43 +0000123 C = CreateRule;
124 else // Methods starting with 'init' follow the init rule.
Ted Kremenek39868cd2009-02-21 18:26:02 +0000125 if (AtBeginning && StringsEqualNoCase("init", s, len))
Ted Kremenek8be2a672009-03-13 20:27:06 +0000126 C = InitRule;
127 break;
128 case 5:
129 if (AtBeginning && StringsEqualNoCase("alloc", s, len))
130 C = CreateRule;
Ted Kremenekb80976c2009-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 Kremenek5c74d502008-10-24 21:18:08 +0000148static bool followsFundamentalRule(const char* s) {
Ted Kremenekb80976c2009-02-21 05:13:43 +0000149 return deriveNamingConvention(s) == CreateRule;
Ted Kremenek4c79e552008-11-05 16:54:44 +0000150}
151
152static bool followsReturnRule(const char* s) {
Ted Kremenekb80976c2009-02-21 05:13:43 +0000153 NamingConvention C = deriveNamingConvention(s);
154 return C == CreateRule || C == InitRule;
Ted Kremenek4c79e552008-11-05 16:54:44 +0000155}
Ted Kremenek5c74d502008-10-24 21:18:08 +0000156
Ted Kremenek05cbe1a2008-04-09 23:49:11 +0000157//===----------------------------------------------------------------------===//
Ted Kremenek553cf182008-06-25 21:21:56 +0000158// Selector creation functions.
Ted Kremenek4fd88972008-04-17 18:12:53 +0000159//===----------------------------------------------------------------------===//
160
Ted Kremenekb83e02e2008-05-01 18:31:44 +0000161static inline Selector GetNullarySelector(const char* name, ASTContext& Ctx) {
Ted Kremenek4fd88972008-04-17 18:12:53 +0000162 IdentifierInfo* II = &Ctx.Idents.get(name);
163 return Ctx.Selectors.getSelector(0, &II);
164}
165
Ted Kremenek9c32d082008-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 Kremenek553cf182008-06-25 21:21:56 +0000171//===----------------------------------------------------------------------===//
172// Type querying functions.
173//===----------------------------------------------------------------------===//
174
Ted Kremenek12619382009-01-12 21:45:02 +0000175static bool hasPrefix(const char* s, const char* prefix) {
176 if (!prefix)
177 return true;
Ted Kremenek0fcbf8e2008-05-07 20:06:41 +0000178
Ted Kremenek12619382009-01-12 21:45:02 +0000179 char c = *s;
180 char cP = *prefix;
Ted Kremenek0fcbf8e2008-05-07 20:06:41 +0000181
Ted Kremenek12619382009-01-12 21:45:02 +0000182 while (c != '\0' && cP != '\0') {
183 if (c != cP) break;
184 c = *(++s);
185 cP = *(++prefix);
186 }
Ted Kremenek0fcbf8e2008-05-07 20:06:41 +0000187
Ted Kremenek12619382009-01-12 21:45:02 +0000188 return cP == '\0';
Ted Kremenek0fcbf8e2008-05-07 20:06:41 +0000189}
190
Ted Kremenek12619382009-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 Kremenek37d785b2008-07-15 16:50:12 +0000198
Ted Kremenek12619382009-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 Kremenek37d785b2008-07-15 16:50:12 +0000205 return false;
Ted Kremenek12619382009-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 Kremenek37d785b2008-07-15 16:50:12 +0000210 return false;
Ted Kremenek12619382009-01-12 21:45:02 +0000211
212 // Does the name start with the prefix?
213 return hasPrefix(name, prefix);
Ted Kremenek37d785b2008-07-15 16:50:12 +0000214}
215
Ted Kremenek4fd88972008-04-17 18:12:53 +0000216//===----------------------------------------------------------------------===//
Ted Kremenek553cf182008-06-25 21:21:56 +0000217// Primitives used for constructing summaries for function/method calls.
Ted Kremenek05cbe1a2008-04-09 23:49:11 +0000218//===----------------------------------------------------------------------===//
219
Ted Kremenek553cf182008-06-25 21:21:56 +0000220namespace {
221/// ArgEffect is used to summarize a function/method call's effect on a
222/// particular argument.
Ted Kremenekf95e9fc2009-03-17 19:42:23 +0000223enum ArgEffect { Autorelease, Dealloc, DecRef, DecRefMsg, DoNothing,
224 DoNothingByRef, IncRefMsg, IncRef, MakeCollectable, MayEscape,
225 NewAutoreleasePool, SelfOwn, StopTracking };
Ted Kremenek553cf182008-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 Kremenek6b3a0f72008-03-11 06:39:11 +0000230}
Ted Kremenek2fff37e2008-03-06 00:08:09 +0000231
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000232namespace llvm {
Ted Kremenek553cf182008-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 Kremenek6b3a0f72008-03-11 06:39:11 +0000241} // end llvm namespace
242
243namespace {
Ted Kremenek553cf182008-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 Kremenek6b3a0f72008-03-11 06:39:11 +0000248public:
Ted Kremeneka7344702008-06-23 18:02:52 +0000249 enum Kind { NoRet, Alias, OwnedSymbol, OwnedAllocatedSymbol,
250 NotOwnedSymbol, ReceiverAlias };
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000251
252 enum ObjKind { CF, ObjC, AnyObj };
253
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000254private:
Ted Kremenek2d1652e2009-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 Kremenek2fff37e2008-03-06 00:08:09 +0000261
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000262public:
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000263 Kind getKind() const { return K; }
264
265 ObjKind getObjKind() const { return O; }
Ted Kremenek553cf182008-06-25 21:21:56 +0000266
267 unsigned getIndex() const {
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000268 assert(getKind() == Alias);
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000269 return index;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000270 }
Ted Kremenek2fff37e2008-03-06 00:08:09 +0000271
Ted Kremenek553cf182008-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 Kremenek2d1652e2009-01-28 05:56:51 +0000278 static RetEffect MakeOwned(ObjKind o, bool isAllocated = false) {
279 return RetEffect(isAllocated ? OwnedAllocatedSymbol : OwnedSymbol, o);
Ted Kremenek553cf182008-06-25 21:21:56 +0000280 }
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000281 static RetEffect MakeNotOwned(ObjKind o) {
282 return RetEffect(NotOwnedSymbol, o);
Ted Kremenek553cf182008-06-25 21:21:56 +0000283 }
284 static RetEffect MakeNoRet() {
285 return RetEffect(NoRet);
Ted Kremeneka7344702008-06-23 18:02:52 +0000286 }
Ted Kremenek2fff37e2008-03-06 00:08:09 +0000287
Ted Kremenek553cf182008-06-25 21:21:56 +0000288 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000289 ID.AddInteger((unsigned)K);
290 ID.AddInteger((unsigned)O);
291 ID.AddInteger(index);
Ted Kremenek553cf182008-06-25 21:21:56 +0000292 }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000293};
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000294
Ted Kremenek553cf182008-06-25 21:21:56 +0000295
296class VISIBILITY_HIDDEN RetainSummary : public llvm::FoldingSetNode {
Ted Kremenek1bffd742008-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 Kremenek6b3a0f72008-03-11 06:39:11 +0000300 ArgEffects* Args;
Ted Kremenek1bffd742008-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 Kremenek553cf182008-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 Kremenek3c0cea32008-05-06 02:26:56 +0000308 ArgEffect Receiver;
Ted Kremenek553cf182008-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 Kremenek6b3a0f72008-03-11 06:39:11 +0000313 RetEffect Ret;
Ted Kremenek553cf182008-06-25 21:21:56 +0000314
Ted Kremenek70a733e2008-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 Kremenek6b3a0f72008-03-11 06:39:11 +0000319public:
320
Ted Kremenek1bffd742008-05-06 15:44:25 +0000321 RetainSummary(ArgEffects* A, RetEffect R, ArgEffect defaultEff,
Ted Kremenek70a733e2008-07-18 17:24:20 +0000322 ArgEffect ReceiverEff, bool endpath = false)
323 : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R),
324 EndPath(endpath) {}
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000325
Ted Kremenek553cf182008-06-25 21:21:56 +0000326 /// getArg - Return the argument effect on the argument specified by
327 /// idx (starting from 0).
Ted Kremenek1ac08d62008-03-11 17:48:22 +0000328 ArgEffect getArg(unsigned idx) const {
Ted Kremenek1bffd742008-05-06 15:44:25 +0000329
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000330 if (!Args)
Ted Kremenek1bffd742008-05-06 15:44:25 +0000331 return DefaultArgEffect;
Ted Kremenek891d5cc2008-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 Kremenek553cf182008-06-25 21:21:56 +0000336 // argument they actually modify with respect to the reference count.
Ted Kremenek891d5cc2008-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 Kremenek1bffd742008-05-06 15:44:25 +0000341 return DefaultArgEffect;
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000342
343 if (idx == I->first)
344 return I->second;
345 }
346
Ted Kremenek1bffd742008-05-06 15:44:25 +0000347 return DefaultArgEffect;
Ted Kremenek1ac08d62008-03-11 17:48:22 +0000348 }
349
Ted Kremenek553cf182008-06-25 21:21:56 +0000350 /// getRetEffect - Returns the effect on the return value of the call.
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000351 RetEffect getRetEffect() const {
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000352 return Ret;
353 }
354
Ted Kremenek70a733e2008-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 Kremenek553cf182008-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 Kremenek3c0cea32008-05-06 02:26:56 +0000361 ArgEffect getReceiverEffect() const {
362 return Receiver;
363 }
364
Ted Kremenek55499762008-06-17 02:43:46 +0000365 typedef ArgEffects::const_iterator ExprIterator;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000366
Ted Kremenek55499762008-06-17 02:43:46 +0000367 ExprIterator begin_args() const { return Args->begin(); }
368 ExprIterator end_args() const { return Args->end(); }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000369
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000370 static void Profile(llvm::FoldingSetNodeID& ID, ArgEffects* A,
Ted Kremenek1bffd742008-05-06 15:44:25 +0000371 RetEffect RetEff, ArgEffect DefaultEff,
Ted Kremenek2d1086c2008-07-18 17:39:56 +0000372 ArgEffect ReceiverEff, bool EndPath) {
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000373 ID.AddPointer(A);
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000374 ID.Add(RetEff);
Ted Kremenek1bffd742008-05-06 15:44:25 +0000375 ID.AddInteger((unsigned) DefaultEff);
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000376 ID.AddInteger((unsigned) ReceiverEff);
Ted Kremenek2d1086c2008-07-18 17:39:56 +0000377 ID.AddInteger((unsigned) EndPath);
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000378 }
379
380 void Profile(llvm::FoldingSetNodeID& ID) const {
Ted Kremenek2d1086c2008-07-18 17:39:56 +0000381 Profile(ID, Args, Ret, DefaultArgEffect, Receiver, EndPath);
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000382 }
383};
Ted Kremenek4f22a782008-06-23 23:30:29 +0000384} // end anonymous namespace
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000385
Ted Kremenek553cf182008-06-25 21:21:56 +0000386//===----------------------------------------------------------------------===//
387// Data structures for constructing summaries.
388//===----------------------------------------------------------------------===//
Ted Kremenek53301ba2008-06-24 03:49:48 +0000389
Ted Kremenek553cf182008-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 Kremenek4f22a782008-06-23 23:30:29 +0000407}
408
409namespace llvm {
Ted Kremenek553cf182008-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 Kremenek4f22a782008-06-23 23:30:29 +0000415
Ted Kremenek553cf182008-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 Kremenek4f22a782008-06-23 23:30:29 +0000440} // end llvm namespace
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000441
Ted Kremenek4f22a782008-06-23 23:30:29 +0000442namespace {
Ted Kremenek553cf182008-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 Kremenek98530452008-08-12 20:41:56 +0000481
Ted Kremenek553cf182008-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 Kremenekd3dbcf42008-05-05 22:11:16 +0000534
535 //==-----------------------------------------------------------------==//
536 // Typedefs.
537 //==-----------------------------------------------------------------==//
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000538
Ted Kremenekd3dbcf42008-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 Kremenek4f22a782008-06-23 23:30:29 +0000548 typedef ObjCSummaryCache ObjCMethodSummariesTy;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000549
550 //==-----------------------------------------------------------------==//
551 // Data.
552 //==-----------------------------------------------------------------==//
553
Ted Kremenek553cf182008-06-25 21:21:56 +0000554 /// Ctx - The ASTContext object for the analyzed ASTs.
Ted Kremenek377e2302008-04-29 05:33:51 +0000555 ASTContext& Ctx;
Ted Kremenek179064e2008-07-01 17:21:27 +0000556
Ted Kremenek070a8252008-07-09 18:11:16 +0000557 /// CFDictionaryCreateII - An IdentifierInfo* representing the indentifier
558 /// "CFDictionaryCreate".
559 IdentifierInfo* CFDictionaryCreateII;
560
Ted Kremenek553cf182008-06-25 21:21:56 +0000561 /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
Ted Kremenek377e2302008-04-29 05:33:51 +0000562 const bool GCEnabled;
563
Ted Kremenek553cf182008-06-25 21:21:56 +0000564 /// SummarySet - A FoldingSet of uniqued summaries.
Ted Kremenek3ea0b6a2008-04-10 22:58:08 +0000565 SummarySetTy SummarySet;
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000566
Ted Kremenek553cf182008-06-25 21:21:56 +0000567 /// FuncSummaries - A map from FunctionDecls to summaries.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000568 FuncSummariesTy FuncSummaries;
569
Ted Kremenek553cf182008-06-25 21:21:56 +0000570 /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
571 /// to summaries.
Ted Kremenek1f180c32008-06-23 22:21:20 +0000572 ObjCMethodSummariesTy ObjCClassMethodSummaries;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000573
Ted Kremenek553cf182008-06-25 21:21:56 +0000574 /// ObjCMethodSummaries - A map from selectors to summaries.
Ted Kremenek1f180c32008-06-23 22:21:20 +0000575 ObjCMethodSummariesTy ObjCMethodSummaries;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000576
Ted Kremenek553cf182008-06-25 21:21:56 +0000577 /// ArgEffectsSet - A FoldingSet of uniqued ArgEffects.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000578 ArgEffectsSetTy ArgEffectsSet;
579
Ted Kremenek553cf182008-06-25 21:21:56 +0000580 /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
581 /// and all other data used by the checker.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000582 llvm::BumpPtrAllocator BPAlloc;
583
Ted Kremenek553cf182008-06-25 21:21:56 +0000584 /// ScratchArgs - A holding buffer for construct ArgEffects.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000585 ArgEffects ScratchArgs;
586
Ted Kremenek432af592008-05-06 18:11:36 +0000587 RetainSummary* StopSummary;
588
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000589 //==-----------------------------------------------------------------==//
590 // Methods.
591 //==-----------------------------------------------------------------==//
592
Ted Kremenek553cf182008-06-25 21:21:56 +0000593 /// getArgEffects - Returns a persistent ArgEffects object based on the
594 /// data in ScratchArgs.
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000595 ArgEffects* getArgEffects();
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000596
Ted Kremenek86ad3bc2008-05-05 16:51:50 +0000597 enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
Ted Kremenek896cd9d2008-10-23 01:56:15 +0000598
599public:
Ted Kremenek6ad315a2009-02-23 16:51:39 +0000600 RetainSummary* getUnarySummary(const FunctionType* FT, UnaryFuncKind func);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000601
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000602 RetainSummary* getCFSummaryCreateRule(FunctionDecl* FD);
603 RetainSummary* getCFSummaryGetRule(FunctionDecl* FD);
Ted Kremenek12619382009-01-12 21:45:02 +0000604 RetainSummary* getCFCreateGetRuleSummary(FunctionDecl* FD, const char* FName);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000605
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000606 RetainSummary* getPersistentSummary(ArgEffects* AE, RetEffect RetEff,
Ted Kremenek1bffd742008-05-06 15:44:25 +0000607 ArgEffect ReceiverEff = DoNothing,
Ted Kremenek70a733e2008-07-18 17:24:20 +0000608 ArgEffect DefaultEff = MayEscape,
609 bool isEndPath = false);
Ted Kremenek706522f2008-10-29 04:07:07 +0000610
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000611 RetainSummary* getPersistentSummary(RetEffect RE,
Ted Kremenek1bffd742008-05-06 15:44:25 +0000612 ArgEffect ReceiverEff = DoNothing,
Ted Kremenek3eabf1c2008-05-22 17:31:13 +0000613 ArgEffect DefaultEff = MayEscape) {
Ted Kremenek1bffd742008-05-06 15:44:25 +0000614 return getPersistentSummary(getArgEffects(), RE, ReceiverEff, DefaultEff);
Ted Kremenek9c32d082008-05-06 00:30:21 +0000615 }
Ted Kremenek46e49ee2008-05-05 23:55:01 +0000616
Ted Kremenek1bffd742008-05-06 15:44:25 +0000617 RetainSummary* getPersistentStopSummary() {
Ted Kremenek432af592008-05-06 18:11:36 +0000618 if (StopSummary)
619 return StopSummary;
620
621 StopSummary = getPersistentSummary(RetEffect::MakeNoRet(),
622 StopTracking, StopTracking);
Ted Kremenek706522f2008-10-29 04:07:07 +0000623
Ted Kremenek432af592008-05-06 18:11:36 +0000624 return StopSummary;
Ted Kremenek1bffd742008-05-06 15:44:25 +0000625 }
Ted Kremenekb3095252008-05-06 04:20:12 +0000626
Ted Kremenek553cf182008-06-25 21:21:56 +0000627 RetainSummary* getInitMethodSummary(ObjCMessageExpr* ME);
Ted Kremenek46e49ee2008-05-05 23:55:01 +0000628
Ted Kremenek1f180c32008-06-23 22:21:20 +0000629 void InitializeClassMethodSummaries();
630 void InitializeMethodSummaries();
Ted Kremenek896cd9d2008-10-23 01:56:15 +0000631
Ted Kremenek234a4c22009-01-07 00:39:56 +0000632 bool isTrackedObjectType(QualType T);
633
Ted Kremenek896cd9d2008-10-23 01:56:15 +0000634private:
635
Ted Kremenek70a733e2008-07-18 17:24:20 +0000636 void addClsMethSummary(IdentifierInfo* ClsII, Selector S,
637 RetainSummary* Summ) {
638 ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
639 }
640
Ted Kremenek553cf182008-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 Kremenek3aa7ecd2009-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 Kremenek553cf182008-06-25 21:21:56 +0000655
Ted Kremenek6c4becb2009-02-25 02:54:57 +0000656 void addInstMethSummary(const char* Cls, const char* nullaryName,
657 RetainSummary *Summ) {
658 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
659 Selector S = GetNullarySelector(nullaryName, Ctx);
660 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
661 }
662
Ted Kremenekaf9dc272008-08-12 18:48:50 +0000663 void addInstMethSummary(const char* Cls, RetainSummary* Summ, va_list argp) {
Ted Kremenek70a733e2008-07-18 17:24:20 +0000664
Ted Kremenek9e476de2008-08-12 18:30:56 +0000665 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
666 llvm::SmallVector<IdentifierInfo*, 10> II;
667
668 while (const char* s = va_arg(argp, const char*))
669 II.push_back(&Ctx.Idents.get(s));
670
671 Selector S = Ctx.Selectors.getSelector(II.size(), &II[0]);
Ted Kremenek70a733e2008-07-18 17:24:20 +0000672 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
673 }
Ted Kremenekaf9dc272008-08-12 18:48:50 +0000674
675 void addInstMethSummary(const char* Cls, RetainSummary* Summ, ...) {
676 va_list argp;
677 va_start(argp, Summ);
678 addInstMethSummary(Cls, Summ, argp);
679 va_end(argp);
680 }
Ted Kremenek9e476de2008-08-12 18:30:56 +0000681
682 void addPanicSummary(const char* Cls, ...) {
683 RetainSummary* Summ = getPersistentSummary(0, RetEffect::MakeNoRet(),
684 DoNothing, DoNothing, true);
685 va_list argp;
686 va_start (argp, Cls);
Ted Kremenekaf9dc272008-08-12 18:48:50 +0000687 addInstMethSummary(Cls, Summ, argp);
Ted Kremenek9e476de2008-08-12 18:30:56 +0000688 va_end(argp);
689 }
Ted Kremenek70a733e2008-07-18 17:24:20 +0000690
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000691public:
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000692
693 RetainSummaryManager(ASTContext& ctx, bool gcenabled)
Ted Kremenek179064e2008-07-01 17:21:27 +0000694 : Ctx(ctx),
Ted Kremenek070a8252008-07-09 18:11:16 +0000695 CFDictionaryCreateII(&ctx.Idents.get("CFDictionaryCreate")),
Ted Kremenek553cf182008-06-25 21:21:56 +0000696 GCEnabled(gcenabled), StopSummary(0) {
697
698 InitializeClassMethodSummaries();
699 InitializeMethodSummaries();
700 }
Ted Kremenek377e2302008-04-29 05:33:51 +0000701
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000702 ~RetainSummaryManager();
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000703
Ted Kremenekab592272008-06-24 03:56:45 +0000704 RetainSummary* getSummary(FunctionDecl* FD);
Ted Kremenek553cf182008-06-25 21:21:56 +0000705 RetainSummary* getMethodSummary(ObjCMessageExpr* ME, ObjCInterfaceDecl* ID);
Ted Kremenekf9df1362009-04-23 21:25:57 +0000706 RetainSummary* getClassMethodSummary(ObjCMessageExpr *ME);
Ted Kremenekb3095252008-05-06 04:20:12 +0000707
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000708 bool isGCEnabled() const { return GCEnabled; }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000709};
710
711} // end anonymous namespace
712
713//===----------------------------------------------------------------------===//
714// Implementation of checker data structures.
715//===----------------------------------------------------------------------===//
716
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000717RetainSummaryManager::~RetainSummaryManager() {
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000718
719 // FIXME: The ArgEffects could eventually be allocated from BPAlloc,
720 // mitigating the need to do explicit cleanup of the
721 // Argument-Effect summaries.
722
Ted Kremenek46e49ee2008-05-05 23:55:01 +0000723 for (ArgEffectsSetTy::iterator I = ArgEffectsSet.begin(),
724 E = ArgEffectsSet.end(); I!=E; ++I)
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000725 I->getValue().~ArgEffects();
Ted Kremenek2fff37e2008-03-06 00:08:09 +0000726}
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000727
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000728ArgEffects* RetainSummaryManager::getArgEffects() {
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000729
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000730 if (ScratchArgs.empty())
731 return NULL;
732
733 // Compute a profile for a non-empty ScratchArgs.
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000734 llvm::FoldingSetNodeID profile;
735 profile.Add(ScratchArgs);
736 void* InsertPos;
737
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000738 // Look up the uniqued copy, or create a new one.
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000739 llvm::FoldingSetNodeWrapper<ArgEffects>* E =
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000740 ArgEffectsSet.FindNodeOrInsertPos(profile, InsertPos);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000741
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000742 if (E) {
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000743 ScratchArgs.clear();
744 return &E->getValue();
745 }
746
747 E = (llvm::FoldingSetNodeWrapper<ArgEffects>*)
Ted Kremenek553cf182008-06-25 21:21:56 +0000748 BPAlloc.Allocate<llvm::FoldingSetNodeWrapper<ArgEffects> >();
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000749
750 new (E) llvm::FoldingSetNodeWrapper<ArgEffects>(ScratchArgs);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000751 ArgEffectsSet.InsertNode(E, InsertPos);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000752
753 ScratchArgs.clear();
754 return &E->getValue();
755}
756
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000757RetainSummary*
758RetainSummaryManager::getPersistentSummary(ArgEffects* AE, RetEffect RetEff,
Ted Kremenek1bffd742008-05-06 15:44:25 +0000759 ArgEffect ReceiverEff,
Ted Kremenek70a733e2008-07-18 17:24:20 +0000760 ArgEffect DefaultEff,
761 bool isEndPath) {
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000762
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000763 // Generate a profile for the summary.
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000764 llvm::FoldingSetNodeID profile;
Ted Kremenek2d1086c2008-07-18 17:39:56 +0000765 RetainSummary::Profile(profile, AE, RetEff, DefaultEff, ReceiverEff,
766 isEndPath);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000767
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000768 // Look up the uniqued summary, or create one if it doesn't exist.
769 void* InsertPos;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000770 RetainSummary* Summ = SummarySet.FindNodeOrInsertPos(profile, InsertPos);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000771
772 if (Summ)
773 return Summ;
774
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000775 // Create the summary and return it.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000776 Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
Ted Kremenek70a733e2008-07-18 17:24:20 +0000777 new (Summ) RetainSummary(AE, RetEff, DefaultEff, ReceiverEff, isEndPath);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000778 SummarySet.InsertNode(Summ, InsertPos);
779
780 return Summ;
781}
782
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000783//===----------------------------------------------------------------------===//
Ted Kremenek234a4c22009-01-07 00:39:56 +0000784// Predicates.
785//===----------------------------------------------------------------------===//
786
Ted Kremenek97d095f2009-04-23 22:11:07 +0000787bool RetainSummaryManager::isTrackedObjectType(QualType Ty) {
788 if (!Ctx.isObjCObjectPointerType(Ty))
Ted Kremenek234a4c22009-01-07 00:39:56 +0000789 return false;
790
Ted Kremenek97d095f2009-04-23 22:11:07 +0000791 // We assume that id<..>, id, and "Class" all represent tracked objects.
792 const PointerType *PT = Ty->getAsPointerType();
793 if (PT == 0)
794 return true;
795
796 const ObjCInterfaceType *OT = PT->getPointeeType()->getAsObjCInterfaceType();
Ted Kremenek234a4c22009-01-07 00:39:56 +0000797
798 // We assume that id<..>, id, and "Class" all represent tracked objects.
799 if (!OT)
800 return true;
Ted Kremenek97d095f2009-04-23 22:11:07 +0000801
802 // Does the interface subclass NSObject?
Ted Kremenek234a4c22009-01-07 00:39:56 +0000803 // FIXME: We can memoize here if this gets too expensive.
804 IdentifierInfo* NSObjectII = &Ctx.Idents.get("NSObject");
805 ObjCInterfaceDecl* ID = OT->getDecl();
806
807 for ( ; ID ; ID = ID->getSuperClass())
808 if (ID->getIdentifier() == NSObjectII)
809 return true;
810
811 return false;
812}
813
814//===----------------------------------------------------------------------===//
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000815// Summary creation for functions (largely uses of Core Foundation).
816//===----------------------------------------------------------------------===//
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000817
Ted Kremenek12619382009-01-12 21:45:02 +0000818static bool isRetain(FunctionDecl* FD, const char* FName) {
819 const char* loc = strstr(FName, "Retain");
820 return loc && loc[sizeof("Retain")-1] == '\0';
821}
822
823static bool isRelease(FunctionDecl* FD, const char* FName) {
824 const char* loc = strstr(FName, "Release");
825 return loc && loc[sizeof("Release")-1] == '\0';
826}
827
Ted Kremenekab592272008-06-24 03:56:45 +0000828RetainSummary* RetainSummaryManager::getSummary(FunctionDecl* FD) {
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000829
830 SourceLocation Loc = FD->getLocation();
831
832 if (!Loc.isFileID())
833 return NULL;
Ted Kremenek2fff37e2008-03-06 00:08:09 +0000834
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000835 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000836 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000837
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000838 if (I != FuncSummaries.end())
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000839 return I->second;
840
841 // No summary. Generate one.
Ted Kremenek12619382009-01-12 21:45:02 +0000842 RetainSummary *S = 0;
Ted Kremenek86ad3bc2008-05-05 16:51:50 +0000843
Ted Kremenek37d785b2008-07-15 16:50:12 +0000844 do {
Ted Kremenek12619382009-01-12 21:45:02 +0000845 // We generate "stop" summaries for implicitly defined functions.
846 if (FD->isImplicit()) {
847 S = getPersistentStopSummary();
848 break;
Ted Kremenek37d785b2008-07-15 16:50:12 +0000849 }
Ted Kremenek6ca31912008-11-04 00:36:12 +0000850
Ted Kremenek6ad315a2009-02-23 16:51:39 +0000851 // [PR 3337] Use 'getAsFunctionType' to strip away any typedefs on the
Ted Kremenek99890652009-01-16 18:40:33 +0000852 // function's type.
Ted Kremenek6ad315a2009-02-23 16:51:39 +0000853 const FunctionType* FT = FD->getType()->getAsFunctionType();
Ted Kremenek12619382009-01-12 21:45:02 +0000854 const char* FName = FD->getIdentifier()->getName();
855
Ted Kremenekbf0a4dd2009-03-05 22:11:14 +0000856 // Strip away preceding '_'. Doing this here will effect all the checks
857 // down below.
858 while (*FName == '_') ++FName;
859
Ted Kremenek12619382009-01-12 21:45:02 +0000860 // Inspect the result type.
861 QualType RetTy = FT->getResultType();
862
863 // FIXME: This should all be refactored into a chain of "summary lookup"
864 // filters.
865 if (strcmp(FName, "IOServiceGetMatchingServices") == 0) {
866 // FIXES: <rdar://problem/6326900>
867 // This should be addressed using a API table. This strcmp is also
868 // a little gross, but there is no need to super optimize here.
869 assert (ScratchArgs.empty());
870 ScratchArgs.push_back(std::make_pair(1, DecRef));
871 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
872 break;
Ted Kremenek64e859a2008-10-22 20:54:52 +0000873 }
Ted Kremenek61991902009-03-17 22:43:44 +0000874
875 // Enable this code once the semantics of NSDeallocateObject are resolved
876 // for GC. <rdar://problem/6619988>
877#if 0
878 // Handle: NSDeallocateObject(id anObject);
879 // This method does allow 'nil' (although we don't check it now).
880 if (strcmp(FName, "NSDeallocateObject") == 0) {
881 return RetTy == Ctx.VoidTy
882 ? getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, Dealloc)
883 : getPersistentStopSummary();
884 }
885#endif
Ted Kremenek12619382009-01-12 21:45:02 +0000886
887 // Handle: id NSMakeCollectable(CFTypeRef)
888 if (strcmp(FName, "NSMakeCollectable") == 0) {
889 S = (RetTy == Ctx.getObjCIdType())
890 ? getUnarySummary(FT, cfmakecollectable)
891 : getPersistentStopSummary();
892
893 break;
894 }
895
896 if (RetTy->isPointerType()) {
897 // For CoreFoundation ('CF') types.
898 if (isRefType(RetTy, "CF", &Ctx, FName)) {
899 if (isRetain(FD, FName))
900 S = getUnarySummary(FT, cfretain);
901 else if (strstr(FName, "MakeCollectable"))
902 S = getUnarySummary(FT, cfmakecollectable);
903 else
904 S = getCFCreateGetRuleSummary(FD, FName);
905
906 break;
907 }
908
909 // For CoreGraphics ('CG') types.
910 if (isRefType(RetTy, "CG", &Ctx, FName)) {
911 if (isRetain(FD, FName))
912 S = getUnarySummary(FT, cfretain);
913 else
914 S = getCFCreateGetRuleSummary(FD, FName);
915
916 break;
917 }
918
919 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
920 if (isRefType(RetTy, "DADisk") ||
921 isRefType(RetTy, "DADissenter") ||
922 isRefType(RetTy, "DASessionRef")) {
923 S = getCFCreateGetRuleSummary(FD, FName);
924 break;
925 }
926
927 break;
928 }
929
930 // Check for release functions, the only kind of functions that we care
931 // about that don't return a pointer type.
932 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
Ted Kremenekbf0a4dd2009-03-05 22:11:14 +0000933 // Test for 'CGCF'.
934 if (FName[1] == 'G' && FName[2] == 'C' && FName[3] == 'F')
935 FName += 4;
936 else
937 FName += 2;
938
939 if (isRelease(FD, FName))
Ted Kremenek12619382009-01-12 21:45:02 +0000940 S = getUnarySummary(FT, cfrelease);
941 else {
Ted Kremenek68189282009-01-29 22:45:13 +0000942 assert (ScratchArgs.empty());
943 // Remaining CoreFoundation and CoreGraphics functions.
944 // We use to assume that they all strictly followed the ownership idiom
945 // and that ownership cannot be transferred. While this is technically
946 // correct, many methods allow a tracked object to escape. For example:
947 //
948 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
949 // CFDictionaryAddValue(y, key, x);
950 // CFRelease(x);
951 // ... it is okay to use 'x' since 'y' has a reference to it
952 //
953 // We handle this and similar cases with the follow heuristic. If the
954 // function name contains "InsertValue", "SetValue" or "AddValue" then
955 // we assume that arguments may "escape."
956 //
957 ArgEffect E = (CStrInCStrNoCase(FName, "InsertValue") ||
958 CStrInCStrNoCase(FName, "AddValue") ||
Ted Kremeneka92206e2009-02-05 22:34:53 +0000959 CStrInCStrNoCase(FName, "SetValue") ||
960 CStrInCStrNoCase(FName, "AppendValue"))
Ted Kremenek68189282009-01-29 22:45:13 +0000961 ? MayEscape : DoNothing;
962
963 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek12619382009-01-12 21:45:02 +0000964 }
965 }
Ted Kremenek37d785b2008-07-15 16:50:12 +0000966 }
967 while (0);
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000968
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000969 FuncSummaries[FD] = S;
Ted Kremenek86ad3bc2008-05-05 16:51:50 +0000970 return S;
Ted Kremenek2fff37e2008-03-06 00:08:09 +0000971}
972
Ted Kremenek37d785b2008-07-15 16:50:12 +0000973RetainSummary*
974RetainSummaryManager::getCFCreateGetRuleSummary(FunctionDecl* FD,
975 const char* FName) {
976
Ted Kremenek86ad3bc2008-05-05 16:51:50 +0000977 if (strstr(FName, "Create") || strstr(FName, "Copy"))
978 return getCFSummaryCreateRule(FD);
Ted Kremenek37d785b2008-07-15 16:50:12 +0000979
Ted Kremenek86ad3bc2008-05-05 16:51:50 +0000980 if (strstr(FName, "Get"))
981 return getCFSummaryGetRule(FD);
982
983 return 0;
984}
985
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000986RetainSummary*
Ted Kremenek6ad315a2009-02-23 16:51:39 +0000987RetainSummaryManager::getUnarySummary(const FunctionType* FT,
988 UnaryFuncKind func) {
989
Ted Kremenek12619382009-01-12 21:45:02 +0000990 // Sanity check that this is *really* a unary function. This can
991 // happen if people do weird things.
Douglas Gregor72564e72009-02-26 23:50:07 +0000992 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
Ted Kremenek12619382009-01-12 21:45:02 +0000993 if (!FTP || FTP->getNumArgs() != 1)
994 return getPersistentStopSummary();
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000995
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000996 assert (ScratchArgs.empty());
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000997
Ted Kremenek377e2302008-04-29 05:33:51 +0000998 switch (func) {
Ted Kremenek12619382009-01-12 21:45:02 +0000999 case cfretain: {
Ted Kremenek377e2302008-04-29 05:33:51 +00001000 ScratchArgs.push_back(std::make_pair(0, IncRef));
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00001001 return getPersistentSummary(RetEffect::MakeAlias(0),
1002 DoNothing, DoNothing);
Ted Kremenek377e2302008-04-29 05:33:51 +00001003 }
1004
1005 case cfrelease: {
Ted Kremenek377e2302008-04-29 05:33:51 +00001006 ScratchArgs.push_back(std::make_pair(0, DecRef));
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00001007 return getPersistentSummary(RetEffect::MakeNoRet(),
1008 DoNothing, DoNothing);
Ted Kremenek377e2302008-04-29 05:33:51 +00001009 }
1010
1011 case cfmakecollectable: {
Ted Kremenek27019002009-02-18 21:57:45 +00001012 ScratchArgs.push_back(std::make_pair(0, MakeCollectable));
1013 return getPersistentSummary(RetEffect::MakeAlias(0),DoNothing, DoNothing);
Ted Kremenek377e2302008-04-29 05:33:51 +00001014 }
1015
1016 default:
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001017 assert (false && "Not a supported unary function.");
Ted Kremenek98530452008-08-12 20:41:56 +00001018 return 0;
Ted Kremenek940b1d82008-04-10 23:44:06 +00001019 }
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001020}
1021
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001022RetainSummary* RetainSummaryManager::getCFSummaryCreateRule(FunctionDecl* FD) {
Ted Kremenek891d5cc2008-04-24 17:22:33 +00001023 assert (ScratchArgs.empty());
Ted Kremenek070a8252008-07-09 18:11:16 +00001024
1025 if (FD->getIdentifier() == CFDictionaryCreateII) {
1026 ScratchArgs.push_back(std::make_pair(1, DoNothingByRef));
1027 ScratchArgs.push_back(std::make_pair(2, DoNothingByRef));
1028 }
1029
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001030 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001031}
1032
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001033RetainSummary* RetainSummaryManager::getCFSummaryGetRule(FunctionDecl* FD) {
Ted Kremenek891d5cc2008-04-24 17:22:33 +00001034 assert (ScratchArgs.empty());
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001035 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1036 DoNothing, DoNothing);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001037}
1038
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001039//===----------------------------------------------------------------------===//
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001040// Summary creation for Selectors.
1041//===----------------------------------------------------------------------===//
1042
Ted Kremenek1bffd742008-05-06 15:44:25 +00001043RetainSummary*
Ted Kremenek553cf182008-06-25 21:21:56 +00001044RetainSummaryManager::getInitMethodSummary(ObjCMessageExpr* ME) {
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001045 assert(ScratchArgs.empty());
1046
Ted Kremenekc3cf7b22009-02-20 00:05:35 +00001047 // 'init' methods only return an alias if the return type is a location type.
1048 QualType T = ME->getType();
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001049 RetainSummary* Summ =
Ted Kremenekc3cf7b22009-02-20 00:05:35 +00001050 getPersistentSummary(Loc::IsLocType(T) ? RetEffect::MakeReceiverAlias()
1051 : RetEffect::MakeNoRet());
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001052
Ted Kremenek553cf182008-06-25 21:21:56 +00001053 ObjCMethodSummaries[ME] = Summ;
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001054 return Summ;
1055}
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001056
Ted Kremenek553cf182008-06-25 21:21:56 +00001057
Ted Kremenek1bffd742008-05-06 15:44:25 +00001058RetainSummary*
Ted Kremenek553cf182008-06-25 21:21:56 +00001059RetainSummaryManager::getMethodSummary(ObjCMessageExpr* ME,
1060 ObjCInterfaceDecl* ID) {
Ted Kremenek1bffd742008-05-06 15:44:25 +00001061
1062 Selector S = ME->getSelector();
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001063
Ted Kremenek553cf182008-06-25 21:21:56 +00001064 // Look up a summary in our summary cache.
1065 ObjCMethodSummariesTy::iterator I = ObjCMethodSummaries.find(ID, S);
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001066
Ted Kremenek1f180c32008-06-23 22:21:20 +00001067 if (I != ObjCMethodSummaries.end())
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001068 return I->second;
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001069
Ted Kremenek234a4c22009-01-07 00:39:56 +00001070 // "initXXX": pass-through for receiver.
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001071 const char* s = S.getIdentifierInfoForSlot(0)->getName();
Ted Kremeneka4b695a2008-05-07 03:45:05 +00001072 assert (ScratchArgs.empty());
Ted Kremenekaee9e572008-05-06 06:09:09 +00001073
Ted Kremenekb80976c2009-02-21 05:13:43 +00001074 if (deriveNamingConvention(s) == InitRule)
Ted Kremenek234a4c22009-01-07 00:39:56 +00001075 return getInitMethodSummary(ME);
Ted Kremenek1bffd742008-05-06 15:44:25 +00001076
Ted Kremenek234a4c22009-01-07 00:39:56 +00001077 // Look for methods that return an owned object.
Ted Kremenekf9df1362009-04-23 21:25:57 +00001078 if (!isTrackedObjectType(ME->getType()))
Ted Kremenek84060db2008-05-07 04:25:59 +00001079 return 0;
Ted Kremeneka4b695a2008-05-07 03:45:05 +00001080
Ted Kremeneke87450e2009-04-23 19:11:35 +00001081 // EXPERIMENTAL: Assume the Cocoa conventions for all objects returned
1082 // by instance methods.
1083
1084 RetEffect E =
1085 followsFundamentalRule(s)
1086 ? (isGCEnabled() ? RetEffect::MakeNotOwned(RetEffect::ObjC)
1087 : RetEffect::MakeOwned(RetEffect::ObjC, true))
1088 : RetEffect::MakeNotOwned(RetEffect::ObjC);
Ted Kremenek1bffd742008-05-06 15:44:25 +00001089
Ted Kremeneke87450e2009-04-23 19:11:35 +00001090 RetainSummary* Summ = getPersistentSummary(E);
1091 ObjCMethodSummaries[ME] = Summ;
1092 return Summ;
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001093}
1094
Ted Kremenekc8395602008-05-06 21:26:51 +00001095RetainSummary*
Ted Kremenekf9df1362009-04-23 21:25:57 +00001096RetainSummaryManager::getClassMethodSummary(ObjCMessageExpr* ME) {
Ted Kremenekc8395602008-05-06 21:26:51 +00001097
Ted Kremenek553cf182008-06-25 21:21:56 +00001098 // FIXME: Eventually we should properly do class method summaries, but
1099 // it requires us being able to walk the type hierarchy. Unfortunately,
Ted Kremenek1f0186c2009-04-23 20:02:30 +00001100 // we cannot do this with just an IdentifierInfo* for the class name.
1101 IdentifierInfo* ClsName = ME->getClassName();
Ted Kremenekf9df1362009-04-23 21:25:57 +00001102 Selector S = ME->getSelector();
Ted Kremenek553cf182008-06-25 21:21:56 +00001103
Ted Kremenekc8395602008-05-06 21:26:51 +00001104 // Look up a summary in our cache of Selectors -> Summaries.
Ted Kremenek553cf182008-06-25 21:21:56 +00001105 ObjCMethodSummariesTy::iterator I = ObjCClassMethodSummaries.find(ClsName, S);
Ted Kremenekc8395602008-05-06 21:26:51 +00001106
Ted Kremenek1f180c32008-06-23 22:21:20 +00001107 if (I != ObjCClassMethodSummaries.end())
Ted Kremenekc8395602008-05-06 21:26:51 +00001108 return I->second;
1109
Ted Kremenek1f0186c2009-04-23 20:02:30 +00001110 // Look for methods that return an owned object.
Ted Kremenekf9df1362009-04-23 21:25:57 +00001111 if (!isTrackedObjectType(ME->getType()))
Ted Kremenek1f0186c2009-04-23 20:02:30 +00001112 return 0;
1113
Ted Kremeneke87450e2009-04-23 19:11:35 +00001114 // EXPERIMENTAL: Assume the Cocoa conventions for all objects returned
1115 // by class methods.
Ted Kremenek1f0186c2009-04-23 20:02:30 +00001116 // Look for methods that return an owned object.
Ted Kremenekf9df1362009-04-23 21:25:57 +00001117
Ted Kremeneke87450e2009-04-23 19:11:35 +00001118 const char* s = S.getIdentifierInfoForSlot(0)->getName();
1119 RetEffect E = followsFundamentalRule(s)
1120 ? (isGCEnabled() ? RetEffect::MakeNotOwned(RetEffect::ObjC)
1121 : RetEffect::MakeOwned(RetEffect::ObjC, true))
1122 : RetEffect::MakeNotOwned(RetEffect::ObjC);
1123
1124 RetainSummary* Summ = getPersistentSummary(E);
1125 ObjCClassMethodSummaries[ObjCSummaryKey(ClsName, S)] = Summ;
1126 return Summ;
Ted Kremenekc8395602008-05-06 21:26:51 +00001127}
1128
Ted Kremenek1f180c32008-06-23 22:21:20 +00001129void RetainSummaryManager::InitializeClassMethodSummaries() {
Ted Kremenek9c32d082008-05-06 00:30:21 +00001130
1131 assert (ScratchArgs.empty());
1132
Ted Kremeneka7344702008-06-23 18:02:52 +00001133 RetEffect E = isGCEnabled() ? RetEffect::MakeNoRet()
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001134 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremeneka7344702008-06-23 18:02:52 +00001135
Ted Kremenek9c32d082008-05-06 00:30:21 +00001136 RetainSummary* Summ = getPersistentSummary(E);
1137
Ted Kremenek553cf182008-06-25 21:21:56 +00001138 // Create the summaries for "alloc", "new", and "allocWithZone:" for
1139 // NSObject and its derivatives.
1140 addNSObjectClsMethSummary(GetNullarySelector("alloc", Ctx), Summ);
1141 addNSObjectClsMethSummary(GetNullarySelector("new", Ctx), Summ);
1142 addNSObjectClsMethSummary(GetUnarySelector("allocWithZone", Ctx), Summ);
Ted Kremenek70a733e2008-07-18 17:24:20 +00001143
1144 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek9e476de2008-08-12 18:30:56 +00001145 addClsMethSummary(&Ctx.Idents.get("NSAssertionHandler"),
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001146 GetNullarySelector("currentHandler", Ctx),
1147 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Ted Kremenek6d348932008-10-21 15:53:15 +00001148
1149 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremenekabf43972009-01-28 21:44:40 +00001150 ScratchArgs.push_back(std::make_pair(0, Autorelease));
1151 addClsMethSummary(&Ctx.Idents.get("NSAutoreleasePool"),
1152 GetUnarySelector("addObject", Ctx),
1153 getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenek022a3c42009-02-23 02:31:16 +00001154 DoNothing, Autorelease));
Ted Kremenek9c32d082008-05-06 00:30:21 +00001155}
1156
Ted Kremenek1f180c32008-06-23 22:21:20 +00001157void RetainSummaryManager::InitializeMethodSummaries() {
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001158
1159 assert (ScratchArgs.empty());
1160
Ted Kremenekc8395602008-05-06 21:26:51 +00001161 // Create the "init" selector. It just acts as a pass-through for the
1162 // receiver.
Ted Kremenek46347352009-02-23 16:54:00 +00001163 RetainSummary* InitSumm =
1164 getPersistentSummary(RetEffect::MakeReceiverAlias());
Ted Kremenek179064e2008-07-01 17:21:27 +00001165 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
Ted Kremenekc8395602008-05-06 21:26:51 +00001166
1167 // The next methods are allocators.
Ted Kremeneka7344702008-06-23 18:02:52 +00001168 RetEffect E = isGCEnabled() ? RetEffect::MakeNoRet()
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001169 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremeneka7344702008-06-23 18:02:52 +00001170
Ted Kremenek179064e2008-07-01 17:21:27 +00001171 RetainSummary* Summ = getPersistentSummary(E);
Ted Kremenekc8395602008-05-06 21:26:51 +00001172
1173 // Create the "copy" selector.
Ted Kremenek98530452008-08-12 20:41:56 +00001174 addNSObjectMethSummary(GetNullarySelector("copy", Ctx), Summ);
1175
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001176 // Create the "mutableCopy" selector.
Ted Kremenek553cf182008-06-25 21:21:56 +00001177 addNSObjectMethSummary(GetNullarySelector("mutableCopy", Ctx), Summ);
Ted Kremenek98530452008-08-12 20:41:56 +00001178
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001179 // Create the "retain" selector.
1180 E = RetEffect::MakeReceiverAlias();
Ted Kremenek1c512f52009-02-18 18:54:33 +00001181 Summ = getPersistentSummary(E, IncRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001182 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001183
1184 // Create the "release" selector.
Ted Kremenek1c512f52009-02-18 18:54:33 +00001185 Summ = getPersistentSummary(E, DecRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001186 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Ted Kremenek299e8152008-05-07 21:17:39 +00001187
1188 // Create the "drain" selector.
1189 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek553cf182008-06-25 21:21:56 +00001190 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001191
1192 // Create the -dealloc summary.
1193 Summ = getPersistentSummary(RetEffect::MakeNoRet(), Dealloc);
1194 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001195
1196 // Create the "autorelease" selector.
Ted Kremenekabf43972009-01-28 21:44:40 +00001197 Summ = getPersistentSummary(E, Autorelease);
Ted Kremenek553cf182008-06-25 21:21:56 +00001198 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Ted Kremenek98530452008-08-12 20:41:56 +00001199
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00001200 // Specially handle NSAutoreleasePool.
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001201 addInstMethSummary("NSAutoreleasePool", "init",
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00001202 getPersistentSummary(RetEffect::MakeReceiverAlias(),
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001203 NewAutoreleasePool));
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00001204
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001205 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremenek89e202d2009-02-23 02:51:29 +00001206 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1207 // self-own themselves. However, they only do this once they are displayed.
1208 // Thus, we need to track an NSWindow's display status.
1209 // This is tracked in <rdar://problem/6062711>.
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +00001210 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
Ted Kremenek99d02692009-04-03 19:02:51 +00001211 RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet());
1212
1213 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1214
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +00001215
1216#if 0
Ted Kremenek179064e2008-07-01 17:21:27 +00001217 RetainSummary *NSWindowSumm =
Ted Kremenek89e202d2009-02-23 02:51:29 +00001218 getPersistentSummary(RetEffect::MakeReceiverAlias(), StopTracking);
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001219
1220 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1221 "styleMask", "backing", "defer", NULL);
1222
1223 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1224 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +00001225#endif
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001226
1227 // For NSPanel (which subclasses NSWindow), allocated objects are not
1228 // self-owned.
Ted Kremenek99d02692009-04-03 19:02:51 +00001229 // FIXME: For now we don't track NSPanels. object for the same reason
1230 // as for NSWindow objects.
1231 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
1232
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001233 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1234 "styleMask", "backing", "defer", NULL);
1235
1236 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1237 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek553cf182008-06-25 21:21:56 +00001238
Ted Kremenek70a733e2008-07-18 17:24:20 +00001239 // Create NSAssertionHandler summaries.
Ted Kremenek9e476de2008-08-12 18:30:56 +00001240 addPanicSummary("NSAssertionHandler", "handleFailureInFunction", "file",
1241 "lineNumber", "description", NULL);
Ted Kremenek70a733e2008-07-18 17:24:20 +00001242
Ted Kremenek9e476de2008-08-12 18:30:56 +00001243 addPanicSummary("NSAssertionHandler", "handleFailureInMethod", "object",
1244 "file", "lineNumber", "description", NULL);
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001245}
1246
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001247//===----------------------------------------------------------------------===//
Ted Kremenek13922612008-04-16 20:40:59 +00001248// Reference-counting logic (typestate + counts).
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001249//===----------------------------------------------------------------------===//
1250
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001251namespace {
1252
Ted Kremenek05cbe1a2008-04-09 23:49:11 +00001253class VISIBILITY_HIDDEN RefVal {
Ted Kremenek4fd88972008-04-17 18:12:53 +00001254public:
Ted Kremenek4fd88972008-04-17 18:12:53 +00001255 enum Kind {
1256 Owned = 0, // Owning reference.
1257 NotOwned, // Reference is not owned by still valid (not freed).
1258 Released, // Object has been released.
1259 ReturnedOwned, // Returned object passes ownership to caller.
1260 ReturnedNotOwned, // Return object does not pass ownership to caller.
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001261 ERROR_START,
1262 ErrorDeallocNotOwned, // -dealloc called on non-owned object.
1263 ErrorDeallocGC, // Calling -dealloc with GC enabled.
Ted Kremenek4fd88972008-04-17 18:12:53 +00001264 ErrorUseAfterRelease, // Object used after released.
1265 ErrorReleaseNotOwned, // Release of an object that was not owned.
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001266 ERROR_LEAK_START,
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00001267 ErrorLeak, // A memory leak due to excessive reference counts.
1268 ErrorLeakReturned // A memory leak due to the returning method not having
1269 // the correct naming conventions.
Ted Kremenek4fd88972008-04-17 18:12:53 +00001270 };
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001271
1272private:
Ted Kremenek4fd88972008-04-17 18:12:53 +00001273 Kind kind;
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001274 RetEffect::ObjKind okind;
Ted Kremenek4fd88972008-04-17 18:12:53 +00001275 unsigned Cnt;
Ted Kremenek553cf182008-06-25 21:21:56 +00001276 QualType T;
1277
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001278 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, QualType t)
1279 : kind(k), okind(o), Cnt(cnt), T(t) {}
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001280
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001281 RefVal(Kind k, unsigned cnt = 0)
1282 : kind(k), okind(RetEffect::AnyObj), Cnt(cnt) {}
1283
1284public:
Ted Kremenek4fd88972008-04-17 18:12:53 +00001285 Kind getKind() const { return kind; }
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001286
1287 RetEffect::ObjKind getObjKind() const { return okind; }
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001288
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001289 unsigned getCount() const { return Cnt; }
1290 void clearCounts() { Cnt = 0; }
1291
Ted Kremenek553cf182008-06-25 21:21:56 +00001292 QualType getType() const { return T; }
Ted Kremenek4fd88972008-04-17 18:12:53 +00001293
1294 // Useful predicates.
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001295
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001296 static bool isError(Kind k) { return k >= ERROR_START; }
Ted Kremenek73c750b2008-03-11 18:14:09 +00001297
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001298 static bool isLeak(Kind k) { return k >= ERROR_LEAK_START; }
Ted Kremenekdb863712008-04-16 22:32:20 +00001299
Ted Kremeneke7bd9c22008-04-11 22:25:11 +00001300 bool isOwned() const {
1301 return getKind() == Owned;
1302 }
1303
Ted Kremenekdb863712008-04-16 22:32:20 +00001304 bool isNotOwned() const {
1305 return getKind() == NotOwned;
1306 }
1307
Ted Kremenek4fd88972008-04-17 18:12:53 +00001308 bool isReturnedOwned() const {
1309 return getKind() == ReturnedOwned;
1310 }
1311
1312 bool isReturnedNotOwned() const {
1313 return getKind() == ReturnedNotOwned;
1314 }
1315
1316 bool isNonLeakError() const {
1317 Kind k = getKind();
1318 return isError(k) && !isLeak(k);
1319 }
1320
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001321 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
1322 unsigned Count = 1) {
1323 return RefVal(Owned, o, Count, t);
Ted Kremenek61b9f872008-04-10 23:09:18 +00001324 }
1325
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001326 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
1327 unsigned Count = 0) {
1328 return RefVal(NotOwned, o, Count, t);
Ted Kremenek61b9f872008-04-10 23:09:18 +00001329 }
Ted Kremenek4fd88972008-04-17 18:12:53 +00001330
1331 static RefVal makeReturnedOwned(unsigned Count) {
1332 return RefVal(ReturnedOwned, Count);
1333 }
1334
1335 static RefVal makeReturnedNotOwned() {
1336 return RefVal(ReturnedNotOwned);
1337 }
1338
Ted Kremenek4fd88972008-04-17 18:12:53 +00001339 // Comparison, profiling, and pretty-printing.
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001340
Ted Kremenek4fd88972008-04-17 18:12:53 +00001341 bool operator==(const RefVal& X) const {
Ted Kremenek553cf182008-06-25 21:21:56 +00001342 return kind == X.kind && Cnt == X.Cnt && T == X.T;
Ted Kremenek4fd88972008-04-17 18:12:53 +00001343 }
Ted Kremenekf3948042008-03-11 19:44:10 +00001344
Ted Kremenek553cf182008-06-25 21:21:56 +00001345 RefVal operator-(size_t i) const {
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001346 return RefVal(getKind(), getObjKind(), getCount() - i, getType());
Ted Kremenek553cf182008-06-25 21:21:56 +00001347 }
1348
1349 RefVal operator+(size_t i) const {
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001350 return RefVal(getKind(), getObjKind(), getCount() + i, getType());
Ted Kremenek553cf182008-06-25 21:21:56 +00001351 }
1352
1353 RefVal operator^(Kind k) const {
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001354 return RefVal(k, getObjKind(), getCount(), getType());
Ted Kremenek553cf182008-06-25 21:21:56 +00001355 }
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001356
Ted Kremenek4fd88972008-04-17 18:12:53 +00001357 void Profile(llvm::FoldingSetNodeID& ID) const {
1358 ID.AddInteger((unsigned) kind);
1359 ID.AddInteger(Cnt);
Ted Kremenek553cf182008-06-25 21:21:56 +00001360 ID.Add(T);
Ted Kremenek4fd88972008-04-17 18:12:53 +00001361 }
1362
Ted Kremenekf3948042008-03-11 19:44:10 +00001363 void print(std::ostream& Out) const;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001364};
Ted Kremenekf3948042008-03-11 19:44:10 +00001365
1366void RefVal::print(std::ostream& Out) const {
Ted Kremenek553cf182008-06-25 21:21:56 +00001367 if (!T.isNull())
1368 Out << "Tracked Type:" << T.getAsString() << '\n';
1369
Ted Kremenekf3948042008-03-11 19:44:10 +00001370 switch (getKind()) {
1371 default: assert(false);
Ted Kremenek61b9f872008-04-10 23:09:18 +00001372 case Owned: {
1373 Out << "Owned";
1374 unsigned cnt = getCount();
1375 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenekf3948042008-03-11 19:44:10 +00001376 break;
Ted Kremenek61b9f872008-04-10 23:09:18 +00001377 }
Ted Kremenekf3948042008-03-11 19:44:10 +00001378
Ted Kremenek61b9f872008-04-10 23:09:18 +00001379 case NotOwned: {
Ted Kremenek4fd88972008-04-17 18:12:53 +00001380 Out << "NotOwned";
Ted Kremenek61b9f872008-04-10 23:09:18 +00001381 unsigned cnt = getCount();
1382 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenekf3948042008-03-11 19:44:10 +00001383 break;
Ted Kremenek61b9f872008-04-10 23:09:18 +00001384 }
Ted Kremenekf3948042008-03-11 19:44:10 +00001385
Ted Kremenek4fd88972008-04-17 18:12:53 +00001386 case ReturnedOwned: {
1387 Out << "ReturnedOwned";
1388 unsigned cnt = getCount();
1389 if (cnt) Out << " (+ " << cnt << ")";
1390 break;
1391 }
1392
1393 case ReturnedNotOwned: {
1394 Out << "ReturnedNotOwned";
1395 unsigned cnt = getCount();
1396 if (cnt) Out << " (+ " << cnt << ")";
1397 break;
1398 }
1399
Ted Kremenekf3948042008-03-11 19:44:10 +00001400 case Released:
1401 Out << "Released";
1402 break;
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001403
1404 case ErrorDeallocGC:
1405 Out << "-dealloc (GC)";
1406 break;
1407
1408 case ErrorDeallocNotOwned:
1409 Out << "-dealloc (not-owned)";
1410 break;
Ted Kremenekf3948042008-03-11 19:44:10 +00001411
Ted Kremenekdb863712008-04-16 22:32:20 +00001412 case ErrorLeak:
1413 Out << "Leaked";
1414 break;
1415
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00001416 case ErrorLeakReturned:
1417 Out << "Leaked (Bad naming)";
1418 break;
1419
Ted Kremenekf3948042008-03-11 19:44:10 +00001420 case ErrorUseAfterRelease:
1421 Out << "Use-After-Release [ERROR]";
1422 break;
1423
1424 case ErrorReleaseNotOwned:
1425 Out << "Release of Not-Owned [ERROR]";
1426 break;
1427 }
1428}
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001429
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001430} // end anonymous namespace
1431
1432//===----------------------------------------------------------------------===//
1433// RefBindings - State used to track object reference counts.
1434//===----------------------------------------------------------------------===//
1435
Ted Kremenek2dabd432008-12-05 02:27:51 +00001436typedef llvm::ImmutableMap<SymbolRef, RefVal> RefBindings;
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001437static int RefBIndex = 0;
Ted Kremenek33b6f632009-02-19 23:47:02 +00001438static std::pair<const void*, const void*> LeakProgramPointTag(&RefBIndex, 0);
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001439
1440namespace clang {
Ted Kremenekb9d17f92008-08-17 03:20:02 +00001441 template<>
1442 struct GRStateTrait<RefBindings> : public GRStatePartialTrait<RefBindings> {
1443 static inline void* GDMIndex() { return &RefBIndex; }
1444 };
1445}
Ted Kremenek6d348932008-10-21 15:53:15 +00001446
1447//===----------------------------------------------------------------------===//
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001448// AutoreleaseBindings - State used to track objects in autorelease pools.
Ted Kremenek6d348932008-10-21 15:53:15 +00001449//===----------------------------------------------------------------------===//
1450
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001451typedef llvm::ImmutableMap<SymbolRef, unsigned> ARCounts;
1452typedef llvm::ImmutableMap<SymbolRef, ARCounts> ARPoolContents;
1453typedef llvm::ImmutableList<SymbolRef> ARStack;
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00001454
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001455static int AutoRCIndex = 0;
Ted Kremenek6d348932008-10-21 15:53:15 +00001456static int AutoRBIndex = 0;
1457
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001458namespace { class VISIBILITY_HIDDEN AutoreleasePoolContents {}; }
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001459namespace { class VISIBILITY_HIDDEN AutoreleaseStack {}; }
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001460
Ted Kremenek6d348932008-10-21 15:53:15 +00001461namespace clang {
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001462template<> struct GRStateTrait<AutoreleaseStack>
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001463 : public GRStatePartialTrait<ARStack> {
1464 static inline void* GDMIndex() { return &AutoRBIndex; }
1465};
1466
1467template<> struct GRStateTrait<AutoreleasePoolContents>
1468 : public GRStatePartialTrait<ARPoolContents> {
1469 static inline void* GDMIndex() { return &AutoRCIndex; }
1470};
1471} // end clang namespace
Ted Kremenek6d348932008-10-21 15:53:15 +00001472
Ted Kremenek7037ab82009-03-20 17:34:15 +00001473static SymbolRef GetCurrentAutoreleasePool(const GRState* state) {
1474 ARStack stack = state->get<AutoreleaseStack>();
1475 return stack.isEmpty() ? SymbolRef() : stack.getHead();
1476}
1477
1478static GRStateRef SendAutorelease(GRStateRef state, ARCounts::Factory &F,
1479 SymbolRef sym) {
1480
1481 SymbolRef pool = GetCurrentAutoreleasePool(state);
1482 const ARCounts *cnts = state.get<AutoreleasePoolContents>(pool);
1483 ARCounts newCnts(0);
1484
1485 if (cnts) {
1486 const unsigned *cnt = (*cnts).lookup(sym);
1487 newCnts = F.Add(*cnts, sym, cnt ? *cnt + 1 : 1);
1488 }
1489 else
1490 newCnts = F.Add(F.GetEmptyMap(), sym, 1);
1491
1492 return state.set<AutoreleasePoolContents>(pool, newCnts);
1493}
1494
Ted Kremenek13922612008-04-16 20:40:59 +00001495//===----------------------------------------------------------------------===//
1496// Transfer functions.
1497//===----------------------------------------------------------------------===//
1498
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001499namespace {
1500
Ted Kremenek05cbe1a2008-04-09 23:49:11 +00001501class VISIBILITY_HIDDEN CFRefCount : public GRSimpleVals {
Ted Kremenek8dd56462008-04-18 03:39:05 +00001502public:
Ted Kremenekae6814e2008-08-13 21:24:49 +00001503 class BindingsPrinter : public GRState::Printer {
Ted Kremenekf3948042008-03-11 19:44:10 +00001504 public:
Ted Kremenekae6814e2008-08-13 21:24:49 +00001505 virtual void Print(std::ostream& Out, const GRState* state,
1506 const char* nl, const char* sep);
Ted Kremenekf3948042008-03-11 19:44:10 +00001507 };
Ted Kremenek8dd56462008-04-18 03:39:05 +00001508
1509private:
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001510 typedef llvm::DenseMap<const GRExprEngine::NodeTy*, const RetainSummary*>
1511 SummaryLogTy;
1512
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001513 RetainSummaryManager Summaries;
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001514 SummaryLogTy SummaryLog;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001515 const LangOptions& LOpts;
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001516 ARCounts::Factory ARCountFactory;
Ted Kremenekb9d17f92008-08-17 03:20:02 +00001517
Ted Kremenekcf701772009-02-05 06:50:21 +00001518 BugType *useAfterRelease, *releaseNotOwned;
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001519 BugType *deallocGC, *deallocNotOwned;
Ted Kremenekcf701772009-02-05 06:50:21 +00001520 BugType *leakWithinFunction, *leakAtReturn;
1521 BugReporter *BR;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001522
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001523 GRStateRef Update(GRStateRef state, SymbolRef sym, RefVal V, ArgEffect E,
1524 RefVal::Kind& hasErr);
1525
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001526 void ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
1527 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekdb863712008-04-16 22:32:20 +00001528 Expr* NodeExpr, Expr* ErrorExpr,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001529 ExplodedNode<GRState>* Pred,
1530 const GRState* St,
Ted Kremenek2dabd432008-12-05 02:27:51 +00001531 RefVal::Kind hasErr, SymbolRef Sym);
Ted Kremenekdb863712008-04-16 22:32:20 +00001532
Ted Kremenekf9790ae2008-10-24 20:32:50 +00001533 std::pair<GRStateRef, bool>
1534 HandleSymbolDeath(GRStateManager& VMgr, const GRState* St,
Ted Kremenek2dabd432008-12-05 02:27:51 +00001535 const Decl* CD, SymbolRef sid, RefVal V, bool& hasLeak);
Ted Kremenekdb863712008-04-16 22:32:20 +00001536
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001537public:
Ted Kremenek78d46242008-07-22 16:21:24 +00001538 CFRefCount(ASTContext& Ctx, bool gcenabled, const LangOptions& lopts)
Ted Kremenek377e2302008-04-29 05:33:51 +00001539 : Summaries(Ctx, gcenabled),
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001540 LOpts(lopts), useAfterRelease(0), releaseNotOwned(0),
1541 deallocGC(0), deallocNotOwned(0),
Ted Kremenekcf701772009-02-05 06:50:21 +00001542 leakWithinFunction(0), leakAtReturn(0), BR(0) {}
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001543
Ted Kremenekcf701772009-02-05 06:50:21 +00001544 virtual ~CFRefCount() {}
Ted Kremenek05cbe1a2008-04-09 23:49:11 +00001545
Ted Kremenekcf118d42009-02-04 23:49:09 +00001546 void RegisterChecks(BugReporter &BR);
Ted Kremenekf3948042008-03-11 19:44:10 +00001547
Ted Kremenek1c72ef02008-08-16 00:49:49 +00001548 virtual void RegisterPrinters(std::vector<GRState::Printer*>& Printers) {
1549 Printers.push_back(new BindingsPrinter());
Ted Kremenekf3948042008-03-11 19:44:10 +00001550 }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001551
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001552 bool isGCEnabled() const { return Summaries.isGCEnabled(); }
Ted Kremenek072192b2008-04-30 23:47:44 +00001553 const LangOptions& getLangOptions() const { return LOpts; }
1554
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001555 const RetainSummary *getSummaryOfNode(const ExplodedNode<GRState> *N) const {
1556 SummaryLogTy::const_iterator I = SummaryLog.find(N);
1557 return I == SummaryLog.end() ? 0 : I->second;
1558 }
1559
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001560 // Calls.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001561
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001562 void EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001563 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001564 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001565 Expr* Ex,
1566 Expr* Receiver,
1567 RetainSummary* Summ,
Ted Kremenek55499762008-06-17 02:43:46 +00001568 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001569 ExplodedNode<GRState>* Pred);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001570
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001571 virtual void EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek199e1a02008-03-12 21:06:49 +00001572 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001573 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001574 CallExpr* CE, SVal L,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001575 ExplodedNode<GRState>* Pred);
Ted Kremenekfa34b332008-04-09 01:10:13 +00001576
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001577
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001578 virtual void EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek85348202008-04-15 23:44:31 +00001579 GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001580 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek85348202008-04-15 23:44:31 +00001581 ObjCMessageExpr* ME,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001582 ExplodedNode<GRState>* Pred);
Ted Kremenek85348202008-04-15 23:44:31 +00001583
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001584 bool EvalObjCMessageExprAux(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek85348202008-04-15 23:44:31 +00001585 GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001586 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek85348202008-04-15 23:44:31 +00001587 ObjCMessageExpr* ME,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001588 ExplodedNode<GRState>* Pred);
Ted Kremenek85348202008-04-15 23:44:31 +00001589
Ted Kremenek41573eb2009-02-14 01:43:44 +00001590 // Stores.
1591 virtual void EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val);
1592
Ted Kremeneke7bd9c22008-04-11 22:25:11 +00001593 // End-of-path.
1594
1595 virtual void EvalEndPath(GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001596 GREndPathNodeBuilder<GRState>& Builder);
Ted Kremeneke7bd9c22008-04-11 22:25:11 +00001597
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001598 virtual void EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek652adc62008-04-24 23:57:27 +00001599 GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001600 GRStmtNodeBuilder<GRState>& Builder,
1601 ExplodedNode<GRState>* Pred,
Ted Kremenek241677a2009-01-21 22:26:05 +00001602 Stmt* S, const GRState* state,
1603 SymbolReaper& SymReaper);
1604
Ted Kremenek4fd88972008-04-17 18:12:53 +00001605 // Return statements.
1606
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001607 virtual void EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4fd88972008-04-17 18:12:53 +00001608 GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001609 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4fd88972008-04-17 18:12:53 +00001610 ReturnStmt* S,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001611 ExplodedNode<GRState>* Pred);
Ted Kremenekcb612922008-04-18 19:23:43 +00001612
1613 // Assumptions.
1614
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001615 virtual const GRState* EvalAssume(GRStateManager& VMgr,
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001616 const GRState* St, SVal Cond,
Ted Kremenek4323a572008-07-10 22:03:41 +00001617 bool Assumption, bool& isFeasible);
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001618};
1619
1620} // end anonymous namespace
1621
Ted Kremenek7037ab82009-03-20 17:34:15 +00001622static void PrintPool(std::ostream &Out, SymbolRef Sym, const GRState *state) {
1623 Out << ' ';
Ted Kremeneke0e4ebf2009-03-26 03:35:11 +00001624 if (Sym)
1625 Out << Sym->getSymbolID();
Ted Kremenek7037ab82009-03-20 17:34:15 +00001626 else
1627 Out << "<pool>";
1628 Out << ":{";
1629
1630 // Get the contents of the pool.
1631 if (const ARCounts *cnts = state->get<AutoreleasePoolContents>(Sym))
1632 for (ARCounts::iterator J=cnts->begin(), EJ=cnts->end(); J != EJ; ++J)
1633 Out << '(' << J.getKey() << ',' << J.getData() << ')';
1634
1635 Out << '}';
1636}
Ted Kremenek8dd56462008-04-18 03:39:05 +00001637
Ted Kremenekae6814e2008-08-13 21:24:49 +00001638void CFRefCount::BindingsPrinter::Print(std::ostream& Out, const GRState* state,
1639 const char* nl, const char* sep) {
Ted Kremenek7037ab82009-03-20 17:34:15 +00001640
1641
Ted Kremenekae6814e2008-08-13 21:24:49 +00001642
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001643 RefBindings B = state->get<RefBindings>();
Ted Kremenekf3948042008-03-11 19:44:10 +00001644
Ted Kremenekae6814e2008-08-13 21:24:49 +00001645 if (!B.isEmpty())
Ted Kremenekf3948042008-03-11 19:44:10 +00001646 Out << sep << nl;
1647
1648 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
1649 Out << (*I).first << " : ";
1650 (*I).second.print(Out);
1651 Out << nl;
1652 }
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001653
1654 // Print the autorelease stack.
Ted Kremenek7037ab82009-03-20 17:34:15 +00001655 Out << sep << nl << "AR pool stack:";
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001656 ARStack stack = state->get<AutoreleaseStack>();
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001657
Ted Kremenek7037ab82009-03-20 17:34:15 +00001658 PrintPool(Out, SymbolRef(), state); // Print the caller's pool.
1659 for (ARStack::iterator I=stack.begin(), E=stack.end(); I!=E; ++I)
1660 PrintPool(Out, *I, state);
1661
1662 Out << nl;
Ted Kremenekf3948042008-03-11 19:44:10 +00001663}
1664
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001665static inline ArgEffect GetArgE(RetainSummary* Summ, unsigned idx) {
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00001666 return Summ ? Summ->getArg(idx) : MayEscape;
Ted Kremenekf9561e52008-04-11 20:23:24 +00001667}
1668
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001669static inline RetEffect GetRetEffect(RetainSummary* Summ) {
1670 return Summ ? Summ->getRetEffect() : RetEffect::MakeNoRet();
Ted Kremenekf9561e52008-04-11 20:23:24 +00001671}
1672
Ted Kremenek14993892008-05-06 02:41:27 +00001673static inline ArgEffect GetReceiverE(RetainSummary* Summ) {
1674 return Summ ? Summ->getReceiverEffect() : DoNothing;
1675}
1676
Ted Kremenek70a733e2008-07-18 17:24:20 +00001677static inline bool IsEndPath(RetainSummary* Summ) {
1678 return Summ ? Summ->isEndPath() : false;
1679}
1680
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001681
Ted Kremenek553cf182008-06-25 21:21:56 +00001682/// GetReturnType - Used to get the return type of a message expression or
1683/// function call with the intention of affixing that type to a tracked symbol.
1684/// While the the return type can be queried directly from RetEx, when
1685/// invoking class methods we augment to the return type to be that of
1686/// a pointer to the class (as opposed it just being id).
1687static QualType GetReturnType(Expr* RetE, ASTContext& Ctx) {
1688
1689 QualType RetTy = RetE->getType();
1690
1691 // FIXME: We aren't handling id<...>.
Chris Lattner8b51fd72008-07-26 22:36:27 +00001692 const PointerType* PT = RetTy->getAsPointerType();
Ted Kremenek553cf182008-06-25 21:21:56 +00001693 if (!PT)
1694 return RetTy;
1695
1696 // If RetEx is not a message expression just return its type.
1697 // If RetEx is a message expression, return its types if it is something
1698 /// more specific than id.
1699
1700 ObjCMessageExpr* ME = dyn_cast<ObjCMessageExpr>(RetE);
1701
Steve Naroff389bf462009-02-12 17:52:19 +00001702 if (!ME || !Ctx.isObjCIdStructType(PT->getPointeeType()))
Ted Kremenek553cf182008-06-25 21:21:56 +00001703 return RetTy;
1704
1705 ObjCInterfaceDecl* D = ME->getClassInfo().first;
1706
1707 // At this point we know the return type of the message expression is id.
1708 // If we have an ObjCInterceDecl, we know this is a call to a class method
1709 // whose type we can resolve. In such cases, promote the return type to
1710 // Class*.
1711 return !D ? RetTy : Ctx.getPointerType(Ctx.getObjCInterfaceType(D));
1712}
1713
1714
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001715void CFRefCount::EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001716 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001717 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001718 Expr* Ex,
1719 Expr* Receiver,
1720 RetainSummary* Summ,
Zhongxing Xu369f4472009-04-20 05:24:46 +00001721 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001722 ExplodedNode<GRState>* Pred) {
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001723
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001724 // Get the state.
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001725 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenekf9790ae2008-10-24 20:32:50 +00001726 ASTContext& Ctx = Eng.getStateManager().getContext();
Ted Kremenek14993892008-05-06 02:41:27 +00001727
1728 // Evaluate the effect of the arguments.
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001729 RefVal::Kind hasErr = (RefVal::Kind) 0;
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001730 unsigned idx = 0;
Ted Kremenekbcf50ad2008-04-11 18:40:51 +00001731 Expr* ErrorExpr = NULL;
Ted Kremenek2dabd432008-12-05 02:27:51 +00001732 SymbolRef ErrorSym = 0;
Ted Kremenekbcf50ad2008-04-11 18:40:51 +00001733
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001734 for (ExprIterator I = arg_beg; I != arg_end; ++I, ++idx) {
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00001735 SVal V = state.GetSValAsScalarOrLoc(*I);
Ted Kremenek94c96982009-03-03 22:06:47 +00001736 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00001737
Ted Kremeneke0e4ebf2009-03-26 03:35:11 +00001738 if (Sym)
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001739 if (RefBindings::data_type* T = state.get<RefBindings>(Sym)) {
1740 state = Update(state, Sym, *T, GetArgE(Summ, idx), hasErr);
1741 if (hasErr) {
Ted Kremenekbcf50ad2008-04-11 18:40:51 +00001742 ErrorExpr = *I;
Ted Kremeneke8fdc832008-07-07 16:21:19 +00001743 ErrorSym = Sym;
Ted Kremenekbcf50ad2008-04-11 18:40:51 +00001744 break;
Ted Kremenek94c96982009-03-03 22:06:47 +00001745 }
1746 continue;
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001747 }
Ted Kremenek070a8252008-07-09 18:11:16 +00001748
Ted Kremenek94c96982009-03-03 22:06:47 +00001749 if (isa<Loc>(V)) {
1750 if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(&V)) {
Ted Kremenek070a8252008-07-09 18:11:16 +00001751 if (GetArgE(Summ, idx) == DoNothingByRef)
1752 continue;
1753
1754 // Invalidate the value of the variable passed by reference.
Ted Kremenek8c5633e2008-07-03 23:26:32 +00001755
1756 // FIXME: Either this logic should also be replicated in GRSimpleVals
1757 // or should be pulled into a separate "constraint engine."
Ted Kremenek070a8252008-07-09 18:11:16 +00001758
Ted Kremenek8c5633e2008-07-03 23:26:32 +00001759 // FIXME: We can have collisions on the conjured symbol if the
1760 // expression *I also creates conjured symbols. We probably want
1761 // to identify conjured symbols by an expression pair: the enclosing
1762 // expression (the context) and the expression itself. This should
Ted Kremenek070a8252008-07-09 18:11:16 +00001763 // disambiguate conjured symbols.
Ted Kremenek9e240492008-10-04 05:50:14 +00001764
Ted Kremenek993f1c72008-10-17 20:28:54 +00001765 const TypedRegion* R = dyn_cast<TypedRegion>(MR->getRegion());
Ted Kremenek90b32362008-12-17 19:42:34 +00001766
Ted Kremenek0312c0e2009-03-01 05:44:08 +00001767 // Blast through TypedViewRegions to get the original region type.
Ted Kremenek90b32362008-12-17 19:42:34 +00001768 while (R) {
Ted Kremenek0312c0e2009-03-01 05:44:08 +00001769 const TypedViewRegion* ATR = dyn_cast<TypedViewRegion>(R);
Ted Kremenek90b32362008-12-17 19:42:34 +00001770 if (!ATR) break;
1771 R = dyn_cast<TypedRegion>(ATR->getSuperRegion());
1772 }
1773
Ted Kremenekd104a092009-03-04 22:56:43 +00001774 if (R) {
Ted Kremenek40e86d92008-12-18 23:34:57 +00001775 // Is the invalidated variable something that we were tracking?
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00001776 SymbolRef Sym = state.GetSValAsScalarOrLoc(R).getAsLocSymbol();
Ted Kremenek40e86d92008-12-18 23:34:57 +00001777
Ted Kremenekd104a092009-03-04 22:56:43 +00001778 // Remove any existing reference-count binding.
Ted Kremeneke0e4ebf2009-03-26 03:35:11 +00001779 if (Sym) state = state.remove<RefBindings>(Sym);
Ted Kremenek9e240492008-10-04 05:50:14 +00001780
Ted Kremenekd104a092009-03-04 22:56:43 +00001781 if (R->isBoundable(Ctx)) {
1782 // Set the value of the variable to be a conjured symbol.
1783 unsigned Count = Builder.getCurrentBlockCount();
1784 QualType T = R->getRValueType(Ctx);
1785
Zhongxing Xu51ae7902009-04-09 06:03:54 +00001786 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())){
Ted Kremenek8d7f5482009-04-09 22:22:44 +00001787 ValueManager &ValMgr = Eng.getValueManager();
1788 SVal V = ValMgr.getConjuredSymbolVal(*I, T, Count);
Zhongxing Xu51ae7902009-04-09 06:03:54 +00001789 state = state.BindLoc(Loc::MakeVal(R), V);
Ted Kremenekd104a092009-03-04 22:56:43 +00001790 }
1791 else if (const RecordType *RT = T->getAsStructureType()) {
1792 // Handle structs in a not so awesome way. Here we just
1793 // eagerly bind new symbols to the fields. In reality we
1794 // should have the store manager handle this. The idea is just
1795 // to prototype some basic functionality here. All of this logic
1796 // should one day soon just go away.
1797 const RecordDecl *RD = RT->getDecl()->getDefinition(Ctx);
1798
1799 // No record definition. There is nothing we can do.
1800 if (!RD)
1801 continue;
1802
1803 MemRegionManager &MRMgr = state.getManager().getRegionManager();
1804
1805 // Iterate through the fields and construct new symbols.
Douglas Gregor6ab35242009-04-09 21:40:53 +00001806 for (RecordDecl::field_iterator FI=RD->field_begin(Ctx),
1807 FE=RD->field_end(Ctx); FI!=FE; ++FI) {
Ted Kremenekd104a092009-03-04 22:56:43 +00001808
1809 // For now just handle scalar fields.
1810 FieldDecl *FD = *FI;
1811 QualType FT = FD->getType();
1812
1813 if (Loc::IsLocType(FT) ||
Ted Kremenek8d7f5482009-04-09 22:22:44 +00001814 (FT->isIntegerType() && FT->isScalarType())) {
Ted Kremenekd104a092009-03-04 22:56:43 +00001815 const FieldRegion* FR = MRMgr.getFieldRegion(FD, R);
Ted Kremenek8d7f5482009-04-09 22:22:44 +00001816 ValueManager &ValMgr = Eng.getValueManager();
1817 SVal V = ValMgr.getConjuredSymbolVal(*I, FT, Count);
Zhongxing Xu6782f752009-04-09 06:32:20 +00001818 state = state.BindLoc(Loc::MakeVal(FR), V);
Ted Kremenekd104a092009-03-04 22:56:43 +00001819 }
1820 }
1821 }
1822 else {
1823 // Just blast away other values.
1824 state = state.BindLoc(*MR, UnknownVal());
1825 }
Ted Kremenekfd301942008-10-17 22:23:12 +00001826 }
Ted Kremenek9e240492008-10-04 05:50:14 +00001827 }
1828 else
Ted Kremeneka441b7e2008-11-12 19:22:09 +00001829 state = state.BindLoc(*MR, UnknownVal());
Ted Kremenek8c5633e2008-07-03 23:26:32 +00001830 }
1831 else {
1832 // Nuke all other arguments passed by reference.
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001833 state = state.Unbind(cast<Loc>(V));
Ted Kremenek8c5633e2008-07-03 23:26:32 +00001834 }
Ted Kremenekb8873552008-04-11 20:51:02 +00001835 }
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001836 else if (isa<nonloc::LocAsInteger>(V))
1837 state = state.Unbind(cast<nonloc::LocAsInteger>(V).getLoc());
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001838 }
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001839
Ted Kremenek553cf182008-06-25 21:21:56 +00001840 // Evaluate the effect on the message receiver.
Ted Kremenek14993892008-05-06 02:41:27 +00001841 if (!ErrorExpr && Receiver) {
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00001842 SymbolRef Sym = state.GetSValAsScalarOrLoc(Receiver).getAsLocSymbol();
Ted Kremeneke0e4ebf2009-03-26 03:35:11 +00001843 if (Sym) {
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001844 if (const RefVal* T = state.get<RefBindings>(Sym)) {
1845 state = Update(state, Sym, *T, GetReceiverE(Summ), hasErr);
1846 if (hasErr) {
Ted Kremenek14993892008-05-06 02:41:27 +00001847 ErrorExpr = Receiver;
Ted Kremeneke8fdc832008-07-07 16:21:19 +00001848 ErrorSym = Sym;
Ted Kremenek14993892008-05-06 02:41:27 +00001849 }
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001850 }
Ted Kremenek14993892008-05-06 02:41:27 +00001851 }
1852 }
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001853
Ted Kremenek553cf182008-06-25 21:21:56 +00001854 // Process any errors.
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001855 if (hasErr) {
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001856 ProcessNonLeakError(Dst, Builder, Ex, ErrorExpr, Pred, state,
Ted Kremenek8dd56462008-04-18 03:39:05 +00001857 hasErr, ErrorSym);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001858 return;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001859 }
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001860
Ted Kremenek70a733e2008-07-18 17:24:20 +00001861 // Consult the summary for the return value.
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001862 RetEffect RE = GetRetEffect(Summ);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001863
1864 switch (RE.getKind()) {
1865 default:
1866 assert (false && "Unhandled RetEffect."); break;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001867
Ted Kremenekfd301942008-10-17 22:23:12 +00001868 case RetEffect::NoRet: {
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001869
Ted Kremenekf9561e52008-04-11 20:23:24 +00001870 // Make up a symbol for the return value (not reference counted).
Ted Kremenekb8873552008-04-11 20:51:02 +00001871 // FIXME: This is basically copy-and-paste from GRSimpleVals. We
1872 // should compose behavior, not copy it.
Ted Kremenekf9561e52008-04-11 20:23:24 +00001873
Ted Kremenekfd301942008-10-17 22:23:12 +00001874 // FIXME: We eventually should handle structs and other compound types
1875 // that are returned by value.
1876
1877 QualType T = Ex->getType();
1878
Ted Kremenek062e2f92008-11-13 06:10:40 +00001879 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())) {
Ted Kremenekf9561e52008-04-11 20:23:24 +00001880 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenek8d7f5482009-04-09 22:22:44 +00001881 ValueManager &ValMgr = Eng.getValueManager();
1882 SVal X = ValMgr.getConjuredSymbolVal(Ex, T, Count);
Ted Kremeneka441b7e2008-11-12 19:22:09 +00001883 state = state.BindExpr(Ex, X, false);
Ted Kremenekf9561e52008-04-11 20:23:24 +00001884 }
1885
Ted Kremenek940b1d82008-04-10 23:44:06 +00001886 break;
Ted Kremenekfd301942008-10-17 22:23:12 +00001887 }
Ted Kremenek940b1d82008-04-10 23:44:06 +00001888
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001889 case RetEffect::Alias: {
Ted Kremenek553cf182008-06-25 21:21:56 +00001890 unsigned idx = RE.getIndex();
Ted Kremenek55499762008-06-17 02:43:46 +00001891 assert (arg_end >= arg_beg);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001892 assert (idx < (unsigned) (arg_end - arg_beg));
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00001893 SVal V = state.GetSValAsScalarOrLoc(*(arg_beg+idx));
Ted Kremeneka441b7e2008-11-12 19:22:09 +00001894 state = state.BindExpr(Ex, V, false);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001895 break;
1896 }
1897
Ted Kremenek14993892008-05-06 02:41:27 +00001898 case RetEffect::ReceiverAlias: {
1899 assert (Receiver);
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00001900 SVal V = state.GetSValAsScalarOrLoc(Receiver);
Ted Kremeneka441b7e2008-11-12 19:22:09 +00001901 state = state.BindExpr(Ex, V, false);
Ted Kremenek14993892008-05-06 02:41:27 +00001902 break;
1903 }
1904
Ted Kremeneka7344702008-06-23 18:02:52 +00001905 case RetEffect::OwnedAllocatedSymbol:
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001906 case RetEffect::OwnedSymbol: {
1907 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenek044b6f02009-04-09 16:13:17 +00001908 ValueManager &ValMgr = Eng.getValueManager();
1909 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
1910 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
1911 state = state.set<RefBindings>(Sym, RefVal::makeOwned(RE.getObjKind(),
1912 RetT));
1913 state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenek25d01ba2009-03-09 22:46:49 +00001914
1915 // FIXME: Add a flag to the checker where allocations are assumed to
1916 // *not fail.
1917#if 0
Ted Kremenekb2bf7cd2009-01-28 22:27:59 +00001918 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) {
1919 bool isFeasible;
1920 state = state.Assume(loc::SymbolVal(Sym), true, isFeasible);
1921 assert(isFeasible && "Cannot assume fresh symbol is non-null.");
1922 }
Ted Kremenek25d01ba2009-03-09 22:46:49 +00001923#endif
Ted Kremeneka7344702008-06-23 18:02:52 +00001924
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001925 break;
1926 }
1927
1928 case RetEffect::NotOwnedSymbol: {
1929 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenek044b6f02009-04-09 16:13:17 +00001930 ValueManager &ValMgr = Eng.getValueManager();
1931 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
1932 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
1933 state = state.set<RefBindings>(Sym, RefVal::makeNotOwned(RE.getObjKind(),
1934 RetT));
1935 state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001936 break;
1937 }
1938 }
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001939
Ted Kremenekf5b34b12009-02-18 02:00:25 +00001940 // Generate a sink node if we are at the end of a path.
1941 GRExprEngine::NodeTy *NewNode =
1942 IsEndPath(Summ) ? Builder.MakeSinkNode(Dst, Ex, Pred, state)
1943 : Builder.MakeNode(Dst, Ex, Pred, state);
1944
1945 // Annotate the edge with summary we used.
1946 // FIXME: This assumes that we always use the same summary when generating
1947 // this node.
1948 if (NewNode) SummaryLog[NewNode] = Summ;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001949}
1950
1951
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001952void CFRefCount::EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001953 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001954 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001955 CallExpr* CE, SVal L,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001956 ExplodedNode<GRState>* Pred) {
Zhongxing Xu369f4472009-04-20 05:24:46 +00001957 const FunctionDecl* FD = L.getAsFunctionDecl();
1958 RetainSummary* Summ = !FD ? 0
1959 : Summaries.getSummary(const_cast<FunctionDecl*>(FD));
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001960
1961 EvalSummary(Dst, Eng, Builder, CE, 0, Summ,
1962 CE->arg_begin(), CE->arg_end(), Pred);
Ted Kremenek2fff37e2008-03-06 00:08:09 +00001963}
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001964
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001965void CFRefCount::EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek85348202008-04-15 23:44:31 +00001966 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001967 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek85348202008-04-15 23:44:31 +00001968 ObjCMessageExpr* ME,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001969 ExplodedNode<GRState>* Pred) {
Ted Kremenekb3095252008-05-06 04:20:12 +00001970 RetainSummary* Summ;
Ted Kremenek9040c652008-05-01 21:31:50 +00001971
Ted Kremenek553cf182008-06-25 21:21:56 +00001972 if (Expr* Receiver = ME->getReceiver()) {
1973 // We need the type-information of the tracked receiver object
1974 // Retrieve it from the state.
1975 ObjCInterfaceDecl* ID = 0;
1976
1977 // FIXME: Wouldn't it be great if this code could be reduced? It's just
1978 // a chain of lookups.
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001979 const GRState* St = Builder.GetState(Pred);
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00001980 SVal V = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
Ted Kremenek553cf182008-06-25 21:21:56 +00001981
Ted Kremenek94c96982009-03-03 22:06:47 +00001982 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremeneke0e4ebf2009-03-26 03:35:11 +00001983 if (Sym) {
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001984 if (const RefVal* T = St->get<RefBindings>(Sym)) {
Ted Kremeneke8fdc832008-07-07 16:21:19 +00001985 QualType Ty = T->getType();
Ted Kremenek553cf182008-06-25 21:21:56 +00001986
1987 if (const PointerType* PT = Ty->getAsPointerType()) {
1988 QualType PointeeTy = PT->getPointeeType();
1989
1990 if (ObjCInterfaceType* IT = dyn_cast<ObjCInterfaceType>(PointeeTy))
1991 ID = IT->getDecl();
1992 }
1993 }
1994 }
1995
1996 Summ = Summaries.getMethodSummary(ME, ID);
Ted Kremenekf9790ae2008-10-24 20:32:50 +00001997
Ted Kremenek896cd9d2008-10-23 01:56:15 +00001998 // Special-case: are we sending a mesage to "self"?
1999 // This is a hack. When we have full-IP this should be removed.
2000 if (!Summ) {
2001 ObjCMethodDecl* MD =
2002 dyn_cast<ObjCMethodDecl>(&Eng.getGraph().getCodeDecl());
2003
2004 if (MD) {
2005 if (Expr* Receiver = ME->getReceiver()) {
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00002006 SVal X = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
Ted Kremenek896cd9d2008-10-23 01:56:15 +00002007 if (loc::MemRegionVal* L = dyn_cast<loc::MemRegionVal>(&X))
Ted Kremenekf9790ae2008-10-24 20:32:50 +00002008 if (L->getRegion() == Eng.getStateManager().getSelfRegion(St)) {
2009 // Create a summmary where all of the arguments "StopTracking".
2010 Summ = Summaries.getPersistentSummary(RetEffect::MakeNoRet(),
2011 DoNothing,
2012 StopTracking);
2013 }
Ted Kremenek896cd9d2008-10-23 01:56:15 +00002014 }
2015 }
2016 }
Ted Kremenek553cf182008-06-25 21:21:56 +00002017 }
Ted Kremenek9ed18e62008-04-16 04:28:53 +00002018 else
Ted Kremenekf9df1362009-04-23 21:25:57 +00002019 Summ = Summaries.getClassMethodSummary(ME);
Ted Kremenek9ed18e62008-04-16 04:28:53 +00002020
Ted Kremenekb3095252008-05-06 04:20:12 +00002021 EvalSummary(Dst, Eng, Builder, ME, ME->getReceiver(), Summ,
2022 ME->arg_begin(), ME->arg_end(), Pred);
Ted Kremenek85348202008-04-15 23:44:31 +00002023}
Ted Kremenek5216ad72009-02-14 03:16:10 +00002024
2025namespace {
2026class VISIBILITY_HIDDEN StopTrackingCallback : public SymbolVisitor {
2027 GRStateRef state;
2028public:
2029 StopTrackingCallback(GRStateRef st) : state(st) {}
2030 GRStateRef getState() { return state; }
2031
2032 bool VisitSymbol(SymbolRef sym) {
2033 state = state.remove<RefBindings>(sym);
2034 return true;
2035 }
Ted Kremenekb3095252008-05-06 04:20:12 +00002036
Ted Kremenek5216ad72009-02-14 03:16:10 +00002037 const GRState* getState() const { return state.getState(); }
2038};
2039} // end anonymous namespace
2040
2041
Ted Kremenek41573eb2009-02-14 01:43:44 +00002042void CFRefCount::EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val) {
Ted Kremenek41573eb2009-02-14 01:43:44 +00002043 // Are we storing to something that causes the value to "escape"?
Ted Kremenek13922612008-04-16 20:40:59 +00002044 bool escapes = false;
2045
Ted Kremeneka496d162008-10-18 03:49:51 +00002046 // A value escapes in three possible cases (this may change):
2047 //
2048 // (1) we are binding to something that is not a memory region.
2049 // (2) we are binding to a memregion that does not have stack storage
2050 // (3) we are binding to a memregion with stack storage that the store
Ted Kremenek41573eb2009-02-14 01:43:44 +00002051 // does not understand.
Ted Kremenek41573eb2009-02-14 01:43:44 +00002052 GRStateRef state = B.getState();
Ted Kremeneka496d162008-10-18 03:49:51 +00002053
Ted Kremenek41573eb2009-02-14 01:43:44 +00002054 if (!isa<loc::MemRegionVal>(location))
Ted Kremenek13922612008-04-16 20:40:59 +00002055 escapes = true;
Ted Kremenek9e240492008-10-04 05:50:14 +00002056 else {
Ted Kremenek41573eb2009-02-14 01:43:44 +00002057 const MemRegion* R = cast<loc::MemRegionVal>(location).getRegion();
2058 escapes = !B.getStateManager().hasStackStorage(R);
Ted Kremeneka496d162008-10-18 03:49:51 +00002059
2060 if (!escapes) {
2061 // To test (3), generate a new state with the binding removed. If it is
2062 // the same state, then it escapes (since the store cannot represent
2063 // the binding).
Ted Kremenek41573eb2009-02-14 01:43:44 +00002064 escapes = (state == (state.BindLoc(cast<Loc>(location), UnknownVal())));
Ted Kremeneka496d162008-10-18 03:49:51 +00002065 }
Ted Kremenek9e240492008-10-04 05:50:14 +00002066 }
Ted Kremenek41573eb2009-02-14 01:43:44 +00002067
Ted Kremenek5216ad72009-02-14 03:16:10 +00002068 // If our store can represent the binding and we aren't storing to something
2069 // that doesn't have local storage then just return and have the simulation
2070 // state continue as is.
2071 if (!escapes)
2072 return;
Ted Kremeneka496d162008-10-18 03:49:51 +00002073
Ted Kremenek5216ad72009-02-14 03:16:10 +00002074 // Otherwise, find all symbols referenced by 'val' that we are tracking
2075 // and stop tracking them.
2076 B.MakeNode(state.scanReachableSymbols<StopTrackingCallback>(val).getState());
Ted Kremenekdb863712008-04-16 22:32:20 +00002077}
2078
Ted Kremenekf9790ae2008-10-24 20:32:50 +00002079std::pair<GRStateRef,bool>
2080CFRefCount::HandleSymbolDeath(GRStateManager& VMgr,
2081 const GRState* St, const Decl* CD,
Ted Kremenek2dabd432008-12-05 02:27:51 +00002082 SymbolRef sid,
Ted Kremenekf9790ae2008-10-24 20:32:50 +00002083 RefVal V, bool& hasLeak) {
Ted Kremenekdb863712008-04-16 22:32:20 +00002084
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002085 GRStateRef state(St, VMgr);
Sanjiv Gupta31fc07d2008-10-31 09:52:39 +00002086 assert ((!V.isReturnedOwned() || CD) &&
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00002087 "CodeDecl must be available for reporting ReturnOwned errors.");
Ted Kremenek896cd9d2008-10-23 01:56:15 +00002088
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00002089 if (V.isReturnedOwned() && V.getCount() == 0)
2090 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
Chris Lattner077bf5e2008-11-24 03:33:13 +00002091 std::string s = MD->getSelector().getAsString();
Ted Kremenek4c79e552008-11-05 16:54:44 +00002092 if (!followsReturnRule(s.c_str())) {
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00002093 hasLeak = true;
Ted Kremenekf9790ae2008-10-24 20:32:50 +00002094 state = state.set<RefBindings>(sid, V ^ RefVal::ErrorLeakReturned);
2095 return std::make_pair(state, true);
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00002096 }
2097 }
Ted Kremenek896cd9d2008-10-23 01:56:15 +00002098
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00002099 // All other cases.
2100
2101 hasLeak = V.isOwned() ||
2102 ((V.isNotOwned() || V.isReturnedOwned()) && V.getCount() > 0);
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002103
Ted Kremenekdb863712008-04-16 22:32:20 +00002104 if (!hasLeak)
Ted Kremenekf9790ae2008-10-24 20:32:50 +00002105 return std::make_pair(state.remove<RefBindings>(sid), false);
Ted Kremenekdb863712008-04-16 22:32:20 +00002106
Ted Kremenekf9790ae2008-10-24 20:32:50 +00002107 return std::make_pair(state.set<RefBindings>(sid, V ^ RefVal::ErrorLeak),
2108 false);
Ted Kremenekdb863712008-04-16 22:32:20 +00002109}
2110
Ted Kremenek652adc62008-04-24 23:57:27 +00002111
Ted Kremeneke7bd9c22008-04-11 22:25:11 +00002112
Ted Kremenek652adc62008-04-24 23:57:27 +00002113// Dead symbols.
2114
Ted Kremenekcf701772009-02-05 06:50:21 +00002115
Ted Kremenek652adc62008-04-24 23:57:27 +00002116
Ted Kremenek4fd88972008-04-17 18:12:53 +00002117 // Return statements.
2118
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002119void CFRefCount::EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4fd88972008-04-17 18:12:53 +00002120 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002121 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4fd88972008-04-17 18:12:53 +00002122 ReturnStmt* S,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002123 ExplodedNode<GRState>* Pred) {
Ted Kremenek4fd88972008-04-17 18:12:53 +00002124
2125 Expr* RetE = S->getRetValue();
Ted Kremenek94c96982009-03-03 22:06:47 +00002126 if (!RetE)
Ted Kremenek4fd88972008-04-17 18:12:53 +00002127 return;
2128
Ted Kremenek94c96982009-03-03 22:06:47 +00002129 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00002130 SymbolRef Sym = state.GetSValAsScalarOrLoc(RetE).getAsLocSymbol();
Ted Kremenek94c96982009-03-03 22:06:47 +00002131
Ted Kremeneke0e4ebf2009-03-26 03:35:11 +00002132 if (!Sym)
Ted Kremenek94c96982009-03-03 22:06:47 +00002133 return;
2134
Ted Kremenek4fd88972008-04-17 18:12:53 +00002135 // Get the reference count binding (if any).
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002136 const RefVal* T = state.get<RefBindings>(Sym);
Ted Kremenek4fd88972008-04-17 18:12:53 +00002137
2138 if (!T)
2139 return;
2140
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002141 // Change the reference count.
Ted Kremeneke8fdc832008-07-07 16:21:19 +00002142 RefVal X = *T;
Ted Kremenek4fd88972008-04-17 18:12:53 +00002143
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002144 switch (X.getKind()) {
Ted Kremenek4fd88972008-04-17 18:12:53 +00002145 case RefVal::Owned: {
2146 unsigned cnt = X.getCount();
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00002147 assert (cnt > 0);
2148 X = RefVal::makeReturnedOwned(cnt - 1);
Ted Kremenek4fd88972008-04-17 18:12:53 +00002149 break;
2150 }
2151
2152 case RefVal::NotOwned: {
2153 unsigned cnt = X.getCount();
2154 X = cnt ? RefVal::makeReturnedOwned(cnt - 1)
2155 : RefVal::makeReturnedNotOwned();
2156 break;
2157 }
2158
2159 default:
Ted Kremenek4fd88972008-04-17 18:12:53 +00002160 return;
2161 }
2162
2163 // Update the binding.
Ted Kremenekb9d17f92008-08-17 03:20:02 +00002164 state = state.set<RefBindings>(Sym, X);
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002165 Builder.MakeNode(Dst, S, Pred, state);
Ted Kremenek4fd88972008-04-17 18:12:53 +00002166}
2167
Ted Kremenekcb612922008-04-18 19:23:43 +00002168// Assumptions.
2169
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002170const GRState* CFRefCount::EvalAssume(GRStateManager& VMgr,
2171 const GRState* St,
Zhongxing Xu1c96b242008-10-17 05:57:07 +00002172 SVal Cond, bool Assumption,
Ted Kremenek4323a572008-07-10 22:03:41 +00002173 bool& isFeasible) {
Ted Kremenekcb612922008-04-18 19:23:43 +00002174
2175 // FIXME: We may add to the interface of EvalAssume the list of symbols
2176 // whose assumptions have changed. For now we just iterate through the
2177 // bindings and check if any of the tracked symbols are NULL. This isn't
2178 // too bad since the number of symbols we will track in practice are
2179 // probably small and EvalAssume is only called at branches and a few
2180 // other places.
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002181 RefBindings B = St->get<RefBindings>();
Ted Kremenekcb612922008-04-18 19:23:43 +00002182
2183 if (B.isEmpty())
2184 return St;
2185
2186 bool changed = false;
Ted Kremenekb9d17f92008-08-17 03:20:02 +00002187
2188 GRStateRef state(St, VMgr);
2189 RefBindings::Factory& RefBFactory = state.get_context<RefBindings>();
Ted Kremenekcb612922008-04-18 19:23:43 +00002190
2191 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
Ted Kremenekcb612922008-04-18 19:23:43 +00002192 // Check if the symbol is null (or equal to any constant).
2193 // If this is the case, stop tracking the symbol.
Zhongxing Xu39cfed32008-08-29 14:52:36 +00002194 if (VMgr.getSymVal(St, I.getKey())) {
Ted Kremenekcb612922008-04-18 19:23:43 +00002195 changed = true;
2196 B = RefBFactory.Remove(B, I.getKey());
2197 }
2198 }
2199
Ted Kremenekb9d17f92008-08-17 03:20:02 +00002200 if (changed)
2201 state = state.set<RefBindings>(B);
Ted Kremenekcb612922008-04-18 19:23:43 +00002202
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002203 return state;
Ted Kremenekcb612922008-04-18 19:23:43 +00002204}
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00002205
Ted Kremenek4d3957d2009-02-24 19:15:11 +00002206GRStateRef CFRefCount::Update(GRStateRef state, SymbolRef sym,
2207 RefVal V, ArgEffect E,
2208 RefVal::Kind& hasErr) {
Ted Kremenek1c512f52009-02-18 18:54:33 +00002209
2210 // In GC mode [... release] and [... retain] do nothing.
2211 switch (E) {
2212 default: break;
2213 case IncRefMsg: E = isGCEnabled() ? DoNothing : IncRef; break;
2214 case DecRefMsg: E = isGCEnabled() ? DoNothing : DecRef; break;
Ted Kremenek27019002009-02-18 21:57:45 +00002215 case MakeCollectable: E = isGCEnabled() ? DecRef : DoNothing; break;
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00002216 case NewAutoreleasePool: E = isGCEnabled() ? DoNothing :
2217 NewAutoreleasePool; break;
Ted Kremenek1c512f52009-02-18 18:54:33 +00002218 }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00002219
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00002220 // Handle all use-after-releases.
2221 if (!isGCEnabled() && V.getKind() == RefVal::Released) {
2222 V = V ^ RefVal::ErrorUseAfterRelease;
2223 hasErr = V.getKind();
2224 return state.set<RefBindings>(sym, V);
2225 }
2226
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002227 switch (E) {
2228 default:
2229 assert (false && "Unhandled CFRef transition.");
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00002230
2231 case Dealloc:
2232 // Any use of -dealloc in GC is *bad*.
2233 if (isGCEnabled()) {
2234 V = V ^ RefVal::ErrorDeallocGC;
2235 hasErr = V.getKind();
2236 break;
2237 }
2238
2239 switch (V.getKind()) {
2240 default:
2241 assert(false && "Invalid case.");
2242 case RefVal::Owned:
2243 // The object immediately transitions to the released state.
2244 V = V ^ RefVal::Released;
2245 V.clearCounts();
2246 return state.set<RefBindings>(sym, V);
2247 case RefVal::NotOwned:
2248 V = V ^ RefVal::ErrorDeallocNotOwned;
2249 hasErr = V.getKind();
2250 break;
2251 }
2252 break;
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00002253
Ted Kremenek35790732009-02-25 23:11:49 +00002254 case NewAutoreleasePool:
2255 assert(!isGCEnabled());
2256 return state.add<AutoreleaseStack>(sym);
2257
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00002258 case MayEscape:
2259 if (V.getKind() == RefVal::Owned) {
Ted Kremenek553cf182008-06-25 21:21:56 +00002260 V = V ^ RefVal::NotOwned;
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00002261 break;
2262 }
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00002263
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00002264 // Fall-through.
Ted Kremenek6c4becb2009-02-25 02:54:57 +00002265
Ted Kremenek070a8252008-07-09 18:11:16 +00002266 case DoNothingByRef:
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002267 case DoNothing:
Ted Kremenek4d3957d2009-02-24 19:15:11 +00002268 return state;
Ted Kremeneke19f4492008-06-30 16:57:41 +00002269
Ted Kremenekabf43972009-01-28 21:44:40 +00002270 case Autorelease:
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00002271 if (isGCEnabled())
2272 return state;
Ted Kremenek7037ab82009-03-20 17:34:15 +00002273
2274 // Update the autorelease counts.
2275 state = SendAutorelease(state, ARCountFactory, sym);
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00002276
2277 // Fall-through.
2278
Ted Kremenek14993892008-05-06 02:41:27 +00002279 case StopTracking:
Ted Kremenek4d3957d2009-02-24 19:15:11 +00002280 return state.remove<RefBindings>(sym);
Ted Kremenek9e476de2008-08-12 18:30:56 +00002281
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002282 case IncRef:
2283 switch (V.getKind()) {
2284 default:
2285 assert(false);
2286
2287 case RefVal::Owned:
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002288 case RefVal::NotOwned:
Ted Kremenek553cf182008-06-25 21:21:56 +00002289 V = V + 1;
Ted Kremenek9e476de2008-08-12 18:30:56 +00002290 break;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002291 case RefVal::Released:
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00002292 // Non-GC cases are handled above.
2293 assert(isGCEnabled());
2294 V = (V ^ RefVal::Owned) + 1;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002295 break;
Ted Kremenek9e476de2008-08-12 18:30:56 +00002296 }
Ted Kremenek940b1d82008-04-10 23:44:06 +00002297 break;
2298
Ted Kremenek553cf182008-06-25 21:21:56 +00002299 case SelfOwn:
2300 V = V ^ RefVal::NotOwned;
Ted Kremenek1c512f52009-02-18 18:54:33 +00002301 // Fall-through.
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002302 case DecRef:
2303 switch (V.getKind()) {
2304 default:
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00002305 // case 'RefVal::Released' handled above.
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002306 assert (false);
Ted Kremenek9e476de2008-08-12 18:30:56 +00002307
Ted Kremenek553cf182008-06-25 21:21:56 +00002308 case RefVal::Owned:
Ted Kremenekbb8c5aa2009-02-18 22:57:22 +00002309 assert(V.getCount() > 0);
2310 if (V.getCount() == 1) V = V ^ RefVal::Released;
2311 V = V - 1;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002312 break;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002313
Ted Kremenek553cf182008-06-25 21:21:56 +00002314 case RefVal::NotOwned:
2315 if (V.getCount() > 0)
2316 V = V - 1;
Ted Kremenek61b9f872008-04-10 23:09:18 +00002317 else {
Ted Kremenek553cf182008-06-25 21:21:56 +00002318 V = V ^ RefVal::ErrorReleaseNotOwned;
Ted Kremenek9ed18e62008-04-16 04:28:53 +00002319 hasErr = V.getKind();
Ted Kremenek9e476de2008-08-12 18:30:56 +00002320 }
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002321 break;
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00002322
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002323 case RefVal::Released:
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00002324 // Non-GC cases are handled above.
2325 assert(isGCEnabled());
Ted Kremenek553cf182008-06-25 21:21:56 +00002326 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek9ed18e62008-04-16 04:28:53 +00002327 hasErr = V.getKind();
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00002328 break;
Ted Kremenek9e476de2008-08-12 18:30:56 +00002329 }
Ted Kremenek940b1d82008-04-10 23:44:06 +00002330 break;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002331 }
Ted Kremenek4d3957d2009-02-24 19:15:11 +00002332 return state.set<RefBindings>(sym, V);
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00002333}
2334
Ted Kremenekfa34b332008-04-09 01:10:13 +00002335//===----------------------------------------------------------------------===//
Ted Kremenek05cbe1a2008-04-09 23:49:11 +00002336// Error reporting.
Ted Kremenekfa34b332008-04-09 01:10:13 +00002337//===----------------------------------------------------------------------===//
2338
Ted Kremenek8dd56462008-04-18 03:39:05 +00002339namespace {
2340
2341 //===-------------===//
2342 // Bug Descriptions. //
2343 //===-------------===//
2344
Ted Kremenekcf118d42009-02-04 23:49:09 +00002345 class VISIBILITY_HIDDEN CFRefBug : public BugType {
Ted Kremenek8dd56462008-04-18 03:39:05 +00002346 protected:
2347 CFRefCount& TF;
Ted Kremenekcf118d42009-02-04 23:49:09 +00002348
2349 CFRefBug(CFRefCount* tf, const char* name)
2350 : BugType(name, "Memory (Core Foundation/Objective-C)"), TF(*tf) {}
Ted Kremenek8dd56462008-04-18 03:39:05 +00002351 public:
Ted Kremenek072192b2008-04-30 23:47:44 +00002352
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00002353 CFRefCount& getTF() { return TF; }
Ted Kremenek789deac2008-05-05 23:16:31 +00002354 const CFRefCount& getTF() const { return TF; }
2355
Ted Kremenekcf118d42009-02-04 23:49:09 +00002356 // FIXME: Eventually remove.
2357 virtual const char* getDescription() const = 0;
2358
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00002359 virtual bool isLeak() const { return false; }
Ted Kremenek8dd56462008-04-18 03:39:05 +00002360 };
2361
2362 class VISIBILITY_HIDDEN UseAfterRelease : public CFRefBug {
2363 public:
Ted Kremenekcf118d42009-02-04 23:49:09 +00002364 UseAfterRelease(CFRefCount* tf)
Ted Kremenek9dab0ed2009-04-03 21:10:31 +00002365 : CFRefBug(tf, "Use-after-release") {}
Ted Kremenek8dd56462008-04-18 03:39:05 +00002366
Ted Kremenekcf118d42009-02-04 23:49:09 +00002367 const char* getDescription() const {
Ted Kremeneke1981162009-02-26 21:04:07 +00002368 return "Reference-counted object is used after it is released";
Ted Kremenekcf701772009-02-05 06:50:21 +00002369 }
Ted Kremenek8dd56462008-04-18 03:39:05 +00002370 };
2371
2372 class VISIBILITY_HIDDEN BadRelease : public CFRefBug {
2373 public:
Ted Kremenekcf118d42009-02-04 23:49:09 +00002374 BadRelease(CFRefCount* tf) : CFRefBug(tf, "bad release") {}
2375
2376 const char* getDescription() const {
Ted Kremeneke87450e2009-04-23 19:11:35 +00002377 return "Incorrect decrement of the reference count of an "
2378 "object is not owned at this point by the caller";
Ted Kremenek8dd56462008-04-18 03:39:05 +00002379 }
Ted Kremenek8dd56462008-04-18 03:39:05 +00002380 };
2381
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00002382 class VISIBILITY_HIDDEN DeallocGC : public CFRefBug {
2383 public:
2384 DeallocGC(CFRefCount *tf) : CFRefBug(tf,
2385 "-dealloc called while using GC") {}
2386
2387 const char *getDescription() const {
2388 return "-dealloc called while using GC";
2389 }
2390 };
2391
2392 class VISIBILITY_HIDDEN DeallocNotOwned : public CFRefBug {
2393 public:
2394 DeallocNotOwned(CFRefCount *tf) : CFRefBug(tf,
2395 "-dealloc sent to non-exclusively owned object") {}
2396
2397 const char *getDescription() const {
2398 return "-dealloc sent to object that may be referenced elsewhere";
2399 }
2400 };
2401
Ted Kremenek8dd56462008-04-18 03:39:05 +00002402 class VISIBILITY_HIDDEN Leak : public CFRefBug {
Ted Kremenekcf118d42009-02-04 23:49:09 +00002403 const bool isReturn;
2404 protected:
2405 Leak(CFRefCount* tf, const char* name, bool isRet)
2406 : CFRefBug(tf, name), isReturn(isRet) {}
Ted Kremenek8dd56462008-04-18 03:39:05 +00002407 public:
Ted Kremenek8dd56462008-04-18 03:39:05 +00002408
Ted Kremenekd3057212009-02-07 22:38:00 +00002409 const char* getDescription() const { return ""; }
Ted Kremenek3148eb42009-01-24 00:55:43 +00002410
Ted Kremeneke45e57f2009-02-05 00:38:00 +00002411 bool isLeak() const { return true; }
Ted Kremenek8dd56462008-04-18 03:39:05 +00002412 };
Ted Kremenekcf118d42009-02-04 23:49:09 +00002413
2414 class VISIBILITY_HIDDEN LeakAtReturn : public Leak {
2415 public:
2416 LeakAtReturn(CFRefCount* tf, const char* name)
2417 : Leak(tf, name, true) {}
2418 };
2419
2420 class VISIBILITY_HIDDEN LeakWithinFunction : public Leak {
2421 public:
2422 LeakWithinFunction(CFRefCount* tf, const char* name)
2423 : Leak(tf, name, false) {}
2424 };
Ted Kremenek8dd56462008-04-18 03:39:05 +00002425
2426 //===---------===//
2427 // Bug Reports. //
2428 //===---------===//
2429
2430 class VISIBILITY_HIDDEN CFRefReport : public RangedBugReport {
Ted Kremenek66d97062009-02-07 22:04:05 +00002431 protected:
Ted Kremenek2dabd432008-12-05 02:27:51 +00002432 SymbolRef Sym;
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002433 const CFRefCount &TF;
Ted Kremenek8dd56462008-04-18 03:39:05 +00002434 public:
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002435 CFRefReport(CFRefBug& D, const CFRefCount &tf,
2436 ExplodedNode<GRState> *n, SymbolRef sym)
2437 : RangedBugReport(D, D.getDescription(), n), Sym(sym), TF(tf) {}
Ted Kremenek8dd56462008-04-18 03:39:05 +00002438
2439 virtual ~CFRefReport() {}
2440
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00002441 CFRefBug& getBugType() {
2442 return (CFRefBug&) RangedBugReport::getBugType();
2443 }
2444 const CFRefBug& getBugType() const {
2445 return (const CFRefBug&) RangedBugReport::getBugType();
2446 }
2447
2448 virtual void getRanges(BugReporter& BR, const SourceRange*& beg,
2449 const SourceRange*& end) {
2450
Ted Kremeneke92c1b22008-05-02 20:53:50 +00002451 if (!getBugType().isLeak())
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00002452 RangedBugReport::getRanges(BR, beg, end);
Ted Kremenek9e476de2008-08-12 18:30:56 +00002453 else
2454 beg = end = 0;
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00002455 }
2456
Ted Kremenek2dabd432008-12-05 02:27:51 +00002457 SymbolRef getSymbol() const { return Sym; }
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002458
Ted Kremenek3148eb42009-01-24 00:55:43 +00002459 PathDiagnosticPiece* getEndPath(BugReporter& BR,
2460 const ExplodedNode<GRState>* N);
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00002461
Ted Kremenek3148eb42009-01-24 00:55:43 +00002462 std::pair<const char**,const char**> getExtraDescriptiveText();
Ted Kremenek8dd56462008-04-18 03:39:05 +00002463
Ted Kremenek3148eb42009-01-24 00:55:43 +00002464 PathDiagnosticPiece* VisitNode(const ExplodedNode<GRState>* N,
2465 const ExplodedNode<GRState>* PrevN,
2466 const ExplodedGraph<GRState>& G,
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002467 BugReporter& BR,
2468 NodeResolver& NR);
Ted Kremenek8dd56462008-04-18 03:39:05 +00002469 };
2470
Ted Kremenekcf118d42009-02-04 23:49:09 +00002471 class VISIBILITY_HIDDEN CFRefLeakReport : public CFRefReport {
Ted Kremeneke469fa02009-02-07 22:19:59 +00002472 SourceLocation AllocSite;
2473 const MemRegion* AllocBinding;
Ted Kremenekcf118d42009-02-04 23:49:09 +00002474 public:
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002475 CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2476 ExplodedNode<GRState> *n, SymbolRef sym,
Ted Kremenekd3057212009-02-07 22:38:00 +00002477 GRExprEngine& Eng);
Ted Kremenek66d97062009-02-07 22:04:05 +00002478
2479 PathDiagnosticPiece* getEndPath(BugReporter& BR,
2480 const ExplodedNode<GRState>* N);
2481
Ted Kremeneke469fa02009-02-07 22:19:59 +00002482 SourceLocation getLocation() const { return AllocSite; }
Ted Kremenekcf118d42009-02-04 23:49:09 +00002483 };
Ted Kremenek8dd56462008-04-18 03:39:05 +00002484} // end anonymous namespace
2485
Ted Kremenekcf118d42009-02-04 23:49:09 +00002486void CFRefCount::RegisterChecks(BugReporter& BR) {
Ted Kremenekcf701772009-02-05 06:50:21 +00002487 useAfterRelease = new UseAfterRelease(this);
2488 BR.Register(useAfterRelease);
2489
2490 releaseNotOwned = new BadRelease(this);
2491 BR.Register(releaseNotOwned);
Ted Kremenekcf118d42009-02-04 23:49:09 +00002492
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00002493 deallocGC = new DeallocGC(this);
2494 BR.Register(deallocGC);
2495
2496 deallocNotOwned = new DeallocNotOwned(this);
2497 BR.Register(deallocNotOwned);
2498
Ted Kremenekcf118d42009-02-04 23:49:09 +00002499 // First register "return" leaks.
2500 const char* name = 0;
2501
2502 if (isGCEnabled())
Ted Kremenek41884092009-04-02 02:40:45 +00002503 name = "Leak of returned object when using garbage collection";
Ted Kremenekcf118d42009-02-04 23:49:09 +00002504 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
Ted Kremenek41884092009-04-02 02:40:45 +00002505 name = "Leak of returned object when not using garbage collection (GC) in "
2506 "dual GC/non-GC code";
Ted Kremenekcf118d42009-02-04 23:49:09 +00002507 else {
2508 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
Ted Kremenek41884092009-04-02 02:40:45 +00002509 name = "Leak of returned object";
Ted Kremenekcf118d42009-02-04 23:49:09 +00002510 }
2511
Ted Kremenekcf701772009-02-05 06:50:21 +00002512 leakAtReturn = new LeakAtReturn(this, name);
2513 BR.Register(leakAtReturn);
Ted Kremenek8dd56462008-04-18 03:39:05 +00002514
Ted Kremenekcf118d42009-02-04 23:49:09 +00002515 // Second, register leaks within a function/method.
2516 if (isGCEnabled())
Ted Kremenek41884092009-04-02 02:40:45 +00002517 name = "Leak of object when using garbage collection";
Ted Kremenekcf118d42009-02-04 23:49:09 +00002518 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
Ted Kremenek41884092009-04-02 02:40:45 +00002519 name = "Leak of object when not using garbage collection (GC) in "
2520 "dual GC/non-GC code";
Ted Kremenekcf118d42009-02-04 23:49:09 +00002521 else {
2522 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
Ted Kremenek41884092009-04-02 02:40:45 +00002523 name = "Leak";
Ted Kremenekcf118d42009-02-04 23:49:09 +00002524 }
2525
Ted Kremenekcf701772009-02-05 06:50:21 +00002526 leakWithinFunction = new LeakWithinFunction(this, name);
2527 BR.Register(leakWithinFunction);
2528
2529 // Save the reference to the BugReporter.
2530 this->BR = &BR;
Ted Kremenekcf118d42009-02-04 23:49:09 +00002531}
Ted Kremenek072192b2008-04-30 23:47:44 +00002532
2533static const char* Msgs[] = {
Ted Kremeneke1981162009-02-26 21:04:07 +00002534 // GC only
2535 "Code is compiled to only use garbage collection",
2536 // No GC.
Ted Kremenek452c31e2009-03-05 00:12:45 +00002537 "Code is compiled to use reference counts",
Ted Kremeneke1981162009-02-26 21:04:07 +00002538 // Hybrid, with GC.
2539 "Code is compiled to use either garbage collection (GC) or reference counts"
2540 " (non-GC). The bug occurs with GC enabled",
2541 // Hybrid, without GC
2542 "Code is compiled to use either garbage collection (GC) or reference counts"
2543 " (non-GC). The bug occurs in non-GC mode"
Ted Kremenek072192b2008-04-30 23:47:44 +00002544};
2545
2546std::pair<const char**,const char**> CFRefReport::getExtraDescriptiveText() {
2547 CFRefCount& TF = static_cast<CFRefBug&>(getBugType()).getTF();
2548
2549 switch (TF.getLangOptions().getGCMode()) {
2550 default:
2551 assert(false);
Ted Kremenek31593ac2008-05-01 04:02:04 +00002552
2553 case LangOptions::GCOnly:
2554 assert (TF.isGCEnabled());
Ted Kremenek9e476de2008-08-12 18:30:56 +00002555 return std::make_pair(&Msgs[0], &Msgs[0]+1);
2556
Ted Kremenek072192b2008-04-30 23:47:44 +00002557 case LangOptions::NonGC:
2558 assert (!TF.isGCEnabled());
Ted Kremenek072192b2008-04-30 23:47:44 +00002559 return std::make_pair(&Msgs[1], &Msgs[1]+1);
2560
2561 case LangOptions::HybridGC:
2562 if (TF.isGCEnabled())
2563 return std::make_pair(&Msgs[2], &Msgs[2]+1);
2564 else
2565 return std::make_pair(&Msgs[3], &Msgs[3]+1);
2566 }
2567}
2568
Ted Kremenek27019002009-02-18 21:57:45 +00002569static inline bool contains(const llvm::SmallVectorImpl<ArgEffect>& V,
2570 ArgEffect X) {
2571 for (llvm::SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
2572 I!=E; ++I)
2573 if (*I == X) return true;
2574
2575 return false;
2576}
2577
Ted Kremenek3148eb42009-01-24 00:55:43 +00002578PathDiagnosticPiece* CFRefReport::VisitNode(const ExplodedNode<GRState>* N,
2579 const ExplodedNode<GRState>* PrevN,
2580 const ExplodedGraph<GRState>& G,
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002581 BugReporter& BR,
2582 NodeResolver& NR) {
Ted Kremenek8dd56462008-04-18 03:39:05 +00002583
Ted Kremenek611a15a2009-01-28 05:29:13 +00002584 // Check if the type state has changed.
2585 GRStateManager &StMgr = cast<GRBugReporter>(BR).getStateManager();
2586 GRStateRef PrevSt(PrevN->getState(), StMgr);
2587 GRStateRef CurrSt(N->getState(), StMgr);
Ted Kremenek20982802009-01-28 05:06:46 +00002588
Ted Kremenek611a15a2009-01-28 05:29:13 +00002589 const RefVal* CurrT = CurrSt.get<RefBindings>(Sym);
2590 if (!CurrT) return NULL;
2591
2592 const RefVal& CurrV = *CurrT;
2593 const RefVal* PrevT = PrevSt.get<RefBindings>(Sym);
Ted Kremenekce48e002008-05-05 17:53:17 +00002594
Ted Kremenek27019002009-02-18 21:57:45 +00002595 // Create a string buffer to constain all the useful things we want
2596 // to tell the user.
2597 std::string sbuf;
2598 llvm::raw_string_ostream os(sbuf);
2599
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002600 // This is the allocation site since the previous node had no bindings
2601 // for this symbol.
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002602 if (!PrevT) {
Ted Kremenekce48e002008-05-05 17:53:17 +00002603 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2604
Ted Kremenek5c1cd522009-01-28 05:15:02 +00002605 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2606 // Get the name of the callee (if it is available).
Zhongxing Xu369f4472009-04-20 05:24:46 +00002607 SVal X = CurrSt.GetSValAsScalarOrLoc(CE->getCallee());
2608 if (const FunctionDecl* FD = X.getAsFunctionDecl())
2609 os << "Call to function '" << FD->getNameAsString() <<'\'';
Ted Kremenek5c1cd522009-01-28 05:15:02 +00002610 else
Ted Kremeneka102c0c2009-01-28 06:01:42 +00002611 os << "function call";
Ted Kremenek5c1cd522009-01-28 05:15:02 +00002612 }
2613 else {
2614 assert (isa<ObjCMessageExpr>(S));
Ted Kremeneka102c0c2009-01-28 06:01:42 +00002615 os << "Method";
Ted Kremenekce48e002008-05-05 17:53:17 +00002616 }
Ted Kremenek5c1cd522009-01-28 05:15:02 +00002617
Ted Kremenek961b61d2009-01-28 06:06:36 +00002618 if (CurrV.getObjKind() == RetEffect::CF) {
2619 os << " returns a Core Foundation object with a ";
2620 }
2621 else {
2622 assert (CurrV.getObjKind() == RetEffect::ObjC);
2623 os << " returns an Objective-C object with a ";
2624 }
Ted Kremeneka102c0c2009-01-28 06:01:42 +00002625
Ted Kremenek23b8eaa2009-01-28 06:25:48 +00002626 if (CurrV.isOwned()) {
2627 os << "+1 retain count (owning reference).";
2628
2629 if (static_cast<CFRefBug&>(getBugType()).getTF().isGCEnabled()) {
2630 assert(CurrV.getObjKind() == RetEffect::CF);
2631 os << " "
2632 "Core Foundation objects are not automatically garbage collected.";
2633 }
2634 }
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002635 else {
2636 assert (CurrV.isNotOwned());
Ted Kremenek5c1cd522009-01-28 05:15:02 +00002637 os << "+0 retain count (non-owning reference).";
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002638 }
Ted Kremenekce48e002008-05-05 17:53:17 +00002639
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00002640 PathDiagnosticLocation Pos(S, BR.getContext().getSourceManager());
2641 return new PathDiagnosticEventPiece(Pos, os.str());
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002642 }
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002643
Ted Kremenek27019002009-02-18 21:57:45 +00002644 // Gather up the effects that were performed on the object at this
2645 // program point
2646 llvm::SmallVector<ArgEffect, 2> AEffects;
2647
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002648 if (const RetainSummary *Summ = TF.getSummaryOfNode(NR.getOriginalNode(N))) {
2649 // We only have summaries attached to nodes after evaluating CallExpr and
2650 // ObjCMessageExprs.
2651 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2652
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002653 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2654 // Iterate through the parameter expressions and see if the symbol
2655 // was ever passed as an argument.
2656 unsigned i = 0;
2657
2658 for (CallExpr::arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
2659 AI!=AE; ++AI, ++i) {
Ted Kremenek27019002009-02-18 21:57:45 +00002660
Ted Kremenek94c96982009-03-03 22:06:47 +00002661 // Retrieve the value of the argument. Is it the symbol
2662 // we are interested in?
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00002663 if (CurrSt.GetSValAsScalarOrLoc(*AI).getAsLocSymbol() != Sym)
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002664 continue;
Ted Kremenek94c96982009-03-03 22:06:47 +00002665
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002666 // We have an argument. Get the effect!
2667 AEffects.push_back(Summ->getArg(i));
Ted Kremenek79c140b2008-04-18 05:32:44 +00002668 }
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002669 }
2670 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
Ted Kremenek94c96982009-03-03 22:06:47 +00002671 if (Expr *receiver = ME->getReceiver())
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00002672 if (CurrSt.GetSValAsScalarOrLoc(receiver).getAsLocSymbol() == Sym) {
Ted Kremenek27019002009-02-18 21:57:45 +00002673 // The symbol we are tracking is the receiver.
2674 AEffects.push_back(Summ->getReceiverEffect());
2675 }
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002676 }
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002677 }
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002678
Ted Kremenek27019002009-02-18 21:57:45 +00002679 do {
2680 // Get the previous type state.
2681 RefVal PrevV = *PrevT;
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00002682
2683 // Specially handle -dealloc.
2684 if (!TF.isGCEnabled() && contains(AEffects, Dealloc)) {
2685 // Determine if the object's reference count was pushed to zero.
2686 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2687 // We may not have transitioned to 'release' if we hit an error.
2688 // This case is handled elsewhere.
2689 if (CurrV.getKind() == RefVal::Released) {
2690 assert(CurrV.getCount() == 0);
2691 os << "Object released by directly sending the '-dealloc' message";
2692 break;
2693 }
2694 }
Ted Kremenek27019002009-02-18 21:57:45 +00002695
2696 // Specially handle CFMakeCollectable and friends.
2697 if (contains(AEffects, MakeCollectable)) {
2698 // Get the name of the function.
2699 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
Zhongxing Xu369f4472009-04-20 05:24:46 +00002700 SVal X = CurrSt.GetSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee());
2701 const FunctionDecl* FD = X.getAsFunctionDecl();
2702 const std::string& FName = FD->getNameAsString();
Ted Kremenek27019002009-02-18 21:57:45 +00002703
2704 if (TF.isGCEnabled()) {
2705 // Determine if the object's reference count was pushed to zero.
2706 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2707
2708 os << "In GC mode a call to '" << FName
2709 << "' decrements an object's retain count and registers the "
2710 "object with the garbage collector. ";
2711
Ted Kremenekbb8c5aa2009-02-18 22:57:22 +00002712 if (CurrV.getKind() == RefVal::Released) {
2713 assert(CurrV.getCount() == 0);
2714 os << "Since it now has a 0 retain count the object can be "
Ted Kremenek27019002009-02-18 21:57:45 +00002715 "automatically collected by the garbage collector.";
Ted Kremenekbb8c5aa2009-02-18 22:57:22 +00002716 }
Ted Kremenek27019002009-02-18 21:57:45 +00002717 else
2718 os << "An object must have a 0 retain count to be garbage collected. "
2719 "After this call its retain count is +" << CurrV.getCount()
2720 << '.';
2721 }
2722 else
2723 os << "When GC is not enabled a call to '" << FName
2724 << "' has no effect on its argument.";
2725
2726 // Nothing more to say.
2727 break;
2728 }
2729
2730 // Determine if the typestate has changed.
2731 if (!(PrevV == CurrV))
2732 switch (CurrV.getKind()) {
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002733 case RefVal::Owned:
2734 case RefVal::NotOwned:
2735
2736 if (PrevV.getCount() == CurrV.getCount())
2737 return 0;
2738
2739 if (PrevV.getCount() > CurrV.getCount())
2740 os << "Reference count decremented.";
2741 else
2742 os << "Reference count incremented.";
Ted Kremenekbb8c5aa2009-02-18 22:57:22 +00002743
Ted Kremeneke1981162009-02-26 21:04:07 +00002744 if (unsigned Count = CurrV.getCount())
2745 os << " The object now has a +" << Count << " retain count.";
Ted Kremenekbb8c5aa2009-02-18 22:57:22 +00002746
2747 if (PrevV.getKind() == RefVal::Released) {
2748 assert(TF.isGCEnabled() && CurrV.getCount() > 0);
2749 os << " The object is not eligible for garbage collection until the "
2750 "retain count reaches 0 again.";
2751 }
2752
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002753 break;
2754
2755 case RefVal::Released:
2756 os << "Object released.";
2757 break;
2758
2759 case RefVal::ReturnedOwned:
2760 os << "Object returned to caller as an owning reference (single retain "
2761 "count transferred to caller).";
2762 break;
2763
2764 case RefVal::ReturnedNotOwned:
2765 os << "Object returned to caller with a +0 (non-owning) retain count.";
2766 break;
2767
2768 default:
2769 return NULL;
Ted Kremenek27019002009-02-18 21:57:45 +00002770 }
2771
2772 // Emit any remaining diagnostics for the argument effects (if any).
2773 for (llvm::SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
2774 E=AEffects.end(); I != E; ++I) {
2775
2776 // A bunch of things have alternate behavior under GC.
2777 if (TF.isGCEnabled())
2778 switch (*I) {
2779 default: break;
2780 case Autorelease:
2781 os << "In GC mode an 'autorelease' has no effect.";
2782 continue;
2783 case IncRefMsg:
2784 os << "In GC mode the 'retain' message has no effect.";
2785 continue;
2786 case DecRefMsg:
2787 os << "In GC mode the 'release' message has no effect.";
2788 continue;
2789 }
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002790 }
Ted Kremenek27019002009-02-18 21:57:45 +00002791 } while(0);
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002792
2793 if (os.str().empty())
2794 return 0; // We have nothing to say!
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002795
2796 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00002797 PathDiagnosticLocation Pos(S, BR.getContext().getSourceManager());
Ted Kremenek1fbfd5b2009-03-06 23:58:11 +00002798 PathDiagnosticPiece* P = new PathDiagnosticEventPiece(Pos, os.str());
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002799
2800 // Add the range by scanning the children of the statement for any bindings
2801 // to Sym.
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002802 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I)
Ted Kremenek94c96982009-03-03 22:06:47 +00002803 if (Expr* Exp = dyn_cast_or_null<Expr>(*I))
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00002804 if (CurrSt.GetSValAsScalarOrLoc(Exp).getAsLocSymbol() == Sym) {
Ted Kremenek94c96982009-03-03 22:06:47 +00002805 P->addRange(Exp->getSourceRange());
2806 break;
2807 }
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002808
2809 return P;
Ted Kremenek8dd56462008-04-18 03:39:05 +00002810}
2811
Ted Kremenek9e240492008-10-04 05:50:14 +00002812namespace {
2813class VISIBILITY_HIDDEN FindUniqueBinding :
2814 public StoreManager::BindingsHandler {
Ted Kremenek2dabd432008-12-05 02:27:51 +00002815 SymbolRef Sym;
Ted Kremenekbe912242009-03-05 16:31:07 +00002816 const MemRegion* Binding;
Ted Kremenek9e240492008-10-04 05:50:14 +00002817 bool First;
2818
2819 public:
Ted Kremenek2dabd432008-12-05 02:27:51 +00002820 FindUniqueBinding(SymbolRef sym) : Sym(sym), Binding(0), First(true) {}
Ted Kremenek9e240492008-10-04 05:50:14 +00002821
Ted Kremenekbe912242009-03-05 16:31:07 +00002822 bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
2823 SVal val) {
Ted Kremeneke0e4ebf2009-03-26 03:35:11 +00002824
2825 SymbolRef SymV = val.getAsSymbol();
2826 if (!SymV || SymV != Sym)
Ted Kremenek9e240492008-10-04 05:50:14 +00002827 return true;
Ted Kremenek94c96982009-03-03 22:06:47 +00002828
Ted Kremenek9e240492008-10-04 05:50:14 +00002829 if (Binding) {
2830 First = false;
2831 return false;
2832 }
2833 else
2834 Binding = R;
2835
2836 return true;
2837 }
2838
2839 operator bool() { return First && Binding; }
Ted Kremenekbe912242009-03-05 16:31:07 +00002840 const MemRegion* getRegion() { return Binding; }
Ted Kremenek9e240492008-10-04 05:50:14 +00002841};
2842}
2843
Ted Kremenek3148eb42009-01-24 00:55:43 +00002844static std::pair<const ExplodedNode<GRState>*,const MemRegion*>
Ted Kremeneke469fa02009-02-07 22:19:59 +00002845GetAllocationSite(GRStateManager& StateMgr, const ExplodedNode<GRState>* N,
Ted Kremenek2dabd432008-12-05 02:27:51 +00002846 SymbolRef Sym) {
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002847
Ted Kremenek2bc39c62008-08-29 00:47:32 +00002848 // Find both first node that referred to the tracked symbol and the
2849 // memory location that value was store to.
Ted Kremenek3148eb42009-01-24 00:55:43 +00002850 const ExplodedNode<GRState>* Last = N;
2851 const MemRegion* FirstBinding = 0;
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002852
2853 while (N) {
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002854 const GRState* St = N->getState();
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002855 RefBindings B = St->get<RefBindings>();
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002856
Ted Kremeneke8fdc832008-07-07 16:21:19 +00002857 if (!B.lookup(Sym))
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002858 break;
Ted Kremenek2bc39c62008-08-29 00:47:32 +00002859
Ted Kremeneke469fa02009-02-07 22:19:59 +00002860 FindUniqueBinding FB(Sym);
2861 StateMgr.iterBindings(St, FB);
2862 if (FB) FirstBinding = FB.getRegion();
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002863
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002864 Last = N;
2865 N = N->pred_empty() ? NULL : *(N->pred_begin());
2866 }
2867
Ted Kremenek2bc39c62008-08-29 00:47:32 +00002868 return std::make_pair(Last, FirstBinding);
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002869}
Ted Kremeneka22cc2f2008-05-06 23:07:13 +00002870
Ted Kremenek3148eb42009-01-24 00:55:43 +00002871PathDiagnosticPiece*
2872CFRefReport::getEndPath(BugReporter& br, const ExplodedNode<GRState>* EndN) {
Ted Kremenek1aa44c72008-05-22 23:45:19 +00002873 // Tell the BugReporter to report cases when the tracked symbol is
2874 // assigned to different variables, etc.
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00002875 GRBugReporter& BR = cast<GRBugReporter>(br);
Ted Kremenekc0959972008-07-02 21:24:01 +00002876 cast<GRBugReporter>(BR).addNotableSymbol(Sym);
Ted Kremenek66d97062009-02-07 22:04:05 +00002877 return RangedBugReport::getEndPath(BR, EndN);
2878}
2879
2880PathDiagnosticPiece*
2881CFRefLeakReport::getEndPath(BugReporter& br, const ExplodedNode<GRState>* EndN){
2882
2883 GRBugReporter& BR = cast<GRBugReporter>(br);
2884 // Tell the BugReporter to report cases when the tracked symbol is
2885 // assigned to different variables, etc.
2886 cast<GRBugReporter>(BR).addNotableSymbol(Sym);
2887
2888 // We are reporting a leak. Walk up the graph to get to the first node where
2889 // the symbol appeared, and also get the first VarDecl that tracked object
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002890 // is stored to.
Ted Kremenek3148eb42009-01-24 00:55:43 +00002891 const ExplodedNode<GRState>* AllocNode = 0;
2892 const MemRegion* FirstBinding = 0;
Ted Kremenek2bc39c62008-08-29 00:47:32 +00002893
2894 llvm::tie(AllocNode, FirstBinding) =
Ted Kremeneke469fa02009-02-07 22:19:59 +00002895 GetAllocationSite(BR.getStateManager(), EndN, Sym);
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00002896
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002897 // Get the allocate site.
Ted Kremenek933c4222009-04-07 00:12:43 +00002898 assert(AllocNode);
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002899 Stmt* FirstStmt = cast<PostStmt>(AllocNode->getLocation()).getStmt();
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00002900
Ted Kremeneke28565b2008-05-05 18:50:19 +00002901 SourceManager& SMgr = BR.getContext().getSourceManager();
Chris Lattnerf7cf85b2009-01-16 07:36:28 +00002902 unsigned AllocLine =SMgr.getInstantiationLineNumber(FirstStmt->getLocStart());
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00002903
Ted Kremenek0b3c9a92009-04-07 04:54:20 +00002904 // Compute an actual location for the leak. Sometimes a leak doesn't
2905 // occur at an actual statement (e.g., transition between blocks; end
2906 // of function) so we need to walk the graph and compute a real location.
Ted Kremenek933c4222009-04-07 00:12:43 +00002907 const ExplodedNode<GRState>* LeakN = EndN;
2908 PathDiagnosticLocation L;
2909
2910 while (LeakN) {
2911 ProgramPoint P = LeakN->getLocation();
2912
2913 if (const PostStmt *PS = dyn_cast<PostStmt>(&P)) {
2914 L = PathDiagnosticLocation(PS->getStmt()->getLocStart(), SMgr);
2915 break;
2916 }
2917 else if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
2918 if (const Stmt* Term = BE->getSrc()->getTerminator()) {
2919 L = PathDiagnosticLocation(Term->getLocStart(), SMgr);
2920 break;
2921 }
2922 }
2923
Ted Kremenek933c4222009-04-07 00:12:43 +00002924 LeakN = LeakN->succ_empty() ? 0 : *(LeakN->succ_begin());
2925 }
2926
2927 if (!L.isValid()) {
Douglas Gregor72971342009-04-18 00:02:19 +00002928 CompoundStmt *CS
2929 = BR.getStateManager().getCodeDecl().getBody(BR.getContext());
Ted Kremenek933c4222009-04-07 00:12:43 +00002930 L = PathDiagnosticLocation(CS->getRBracLoc(), SMgr);
2931 }
2932
Ted Kremenekc9e3d862009-02-07 21:59:45 +00002933 std::string sbuf;
2934 llvm::raw_string_ostream os(sbuf);
Ted Kremeneke92c1b22008-05-02 20:53:50 +00002935
Ted Kremeneke28565b2008-05-05 18:50:19 +00002936 os << "Object allocated on line " << AllocLine;
Ted Kremeneke92c1b22008-05-02 20:53:50 +00002937
Ted Kremenek2bc39c62008-08-29 00:47:32 +00002938 if (FirstBinding)
Ted Kremenek9e240492008-10-04 05:50:14 +00002939 os << " and stored into '" << FirstBinding->getString() << '\'';
2940
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00002941 // Get the retain count.
2942 const RefVal* RV = EndN->getState()->get<RefBindings>(Sym);
2943
2944 if (RV->getKind() == RefVal::ErrorLeakReturned) {
Ted Kremenek04f9d462008-12-02 01:26:07 +00002945 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
2946 // ojbects. Only "copy", "alloc", "retain" and "new" transfer ownership
2947 // to the caller for NS objects.
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00002948 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(BR.getGraph().getCodeDecl());
2949 os << " is returned from a method whose name ('"
Chris Lattner077bf5e2008-11-24 03:33:13 +00002950 << MD.getSelector().getAsString()
Ted Kremenek234a4c22009-01-07 00:39:56 +00002951 << "') does not contain 'copy' or otherwise starts with"
Ted Kremenek9d1d5702008-10-24 21:22:44 +00002952 " 'new' or 'alloc'. This violates the naming convention rules given"
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00002953 " in the Memory Management Guide for Cocoa (object leaked).";
2954 }
2955 else
Ted Kremenek9d1d5702008-10-24 21:22:44 +00002956 os << " is no longer referenced after this point and has a retain count of"
2957 " +"
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00002958 << RV->getCount() << " (object leaked).";
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00002959
Ted Kremenek1fbfd5b2009-03-06 23:58:11 +00002960 return new PathDiagnosticEventPiece(L, os.str());
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00002961}
2962
Ted Kremenek989d5192008-04-17 23:43:50 +00002963
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002964CFRefLeakReport::CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2965 ExplodedNode<GRState> *n,
Ted Kremenekd3057212009-02-07 22:38:00 +00002966 SymbolRef sym, GRExprEngine& Eng)
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002967 : CFRefReport(D, tf, n, sym)
Ted Kremeneke469fa02009-02-07 22:19:59 +00002968{
2969
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002970 // Most bug reports are cached at the location where they occured.
2971 // With leaks, we want to unique them by the location where they were
Ted Kremeneke469fa02009-02-07 22:19:59 +00002972 // allocated, and only report a single path. To do this, we need to find
2973 // the allocation site of a piece of tracked memory, which we do via a
2974 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2975 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2976 // that all ancestor nodes that represent the allocation site have the
2977 // same SourceLocation.
2978 const ExplodedNode<GRState>* AllocNode = 0;
2979
2980 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding.
Ted Kremenekd3057212009-02-07 22:38:00 +00002981 GetAllocationSite(Eng.getStateManager(), getEndNode(), getSymbol());
Ted Kremeneke469fa02009-02-07 22:19:59 +00002982
Ted Kremeneke469fa02009-02-07 22:19:59 +00002983 // Get the SourceLocation for the allocation site.
Ted Kremenekd3057212009-02-07 22:38:00 +00002984 ProgramPoint P = AllocNode->getLocation();
Ted Kremeneke469fa02009-02-07 22:19:59 +00002985 AllocSite = cast<PostStmt>(P).getStmt()->getLocStart();
Ted Kremenekd3057212009-02-07 22:38:00 +00002986
2987 // Fill in the description of the bug.
2988 Description.clear();
2989 llvm::raw_string_ostream os(Description);
2990 SourceManager& SMgr = Eng.getContext().getSourceManager();
2991 unsigned AllocLine = SMgr.getInstantiationLineNumber(AllocSite);
Ted Kremenekc5c60002009-02-07 22:54:59 +00002992 os << "Potential leak of object allocated on line " << AllocLine;
2993
2994 // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2995 if (AllocBinding)
Ted Kremenekc2dcd892009-04-02 03:42:38 +00002996 os << " and stored into '" << AllocBinding->getString() << '\'';
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002997}
2998
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00002999//===----------------------------------------------------------------------===//
Ted Kremenekcf701772009-02-05 06:50:21 +00003000// Handle dead symbols and end-of-path.
3001//===----------------------------------------------------------------------===//
3002
3003void CFRefCount::EvalEndPath(GRExprEngine& Eng,
3004 GREndPathNodeBuilder<GRState>& Builder) {
3005
3006 const GRState* St = Builder.getState();
3007 RefBindings B = St->get<RefBindings>();
3008
3009 llvm::SmallVector<std::pair<SymbolRef, bool>, 10> Leaked;
3010 const Decl* CodeDecl = &Eng.getGraph().getCodeDecl();
3011
3012 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
3013 bool hasLeak = false;
3014
3015 std::pair<GRStateRef, bool> X =
Ted Kremenek94c96982009-03-03 22:06:47 +00003016 HandleSymbolDeath(Eng.getStateManager(), St, CodeDecl,
3017 (*I).first, (*I).second, hasLeak);
Ted Kremenekcf701772009-02-05 06:50:21 +00003018
3019 St = X.first;
3020 if (hasLeak) Leaked.push_back(std::make_pair((*I).first, X.second));
3021 }
3022
3023 if (Leaked.empty())
3024 return;
3025
3026 ExplodedNode<GRState>* N = Builder.MakeNode(St);
3027
3028 if (!N)
3029 return;
3030
3031 for (llvm::SmallVector<std::pair<SymbolRef,bool>, 10>::iterator
3032 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3033
3034 CFRefBug *BT = static_cast<CFRefBug*>(I->second ? leakAtReturn
3035 : leakWithinFunction);
3036 assert(BT && "BugType not initialized.");
Ted Kremeneka5770b92009-04-07 05:07:44 +00003037 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N, I->first, Eng);
Ted Kremenekcf701772009-02-05 06:50:21 +00003038 BR->EmitReport(report);
3039 }
3040}
3041
3042void CFRefCount::EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
3043 GRExprEngine& Eng,
3044 GRStmtNodeBuilder<GRState>& Builder,
3045 ExplodedNode<GRState>* Pred,
3046 Stmt* S,
3047 const GRState* St,
3048 SymbolReaper& SymReaper) {
3049
Ted Kremenek33b6f632009-02-19 23:47:02 +00003050 // FIXME: a lot of copy-and-paste from EvalEndPath. Refactor.
Ted Kremenekcf701772009-02-05 06:50:21 +00003051 RefBindings B = St->get<RefBindings>();
3052 llvm::SmallVector<std::pair<SymbolRef,bool>, 10> Leaked;
3053
3054 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3055 E = SymReaper.dead_end(); I != E; ++I) {
3056
3057 const RefVal* T = B.lookup(*I);
3058 if (!T) continue;
3059
3060 bool hasLeak = false;
3061
3062 std::pair<GRStateRef, bool> X
Ted Kremenek33b6f632009-02-19 23:47:02 +00003063 = HandleSymbolDeath(Eng.getStateManager(), St, 0, *I, *T, hasLeak);
Ted Kremenekcf701772009-02-05 06:50:21 +00003064
3065 St = X.first;
3066
3067 if (hasLeak)
3068 Leaked.push_back(std::make_pair(*I,X.second));
3069 }
3070
Ted Kremenek33b6f632009-02-19 23:47:02 +00003071 if (!Leaked.empty()) {
3072 // Create a new intermediate node representing the leak point. We
3073 // use a special program point that represents this checker-specific
3074 // transition. We use the address of RefBIndex as a unique tag for this
3075 // checker. We will create another node (if we don't cache out) that
3076 // removes the retain-count bindings from the state.
3077 // NOTE: We use 'generateNode' so that it does interplay with the
3078 // auto-transition logic.
3079 ExplodedNode<GRState>* N =
3080 Builder.generateNode(PostStmtCustom(S, &LeakProgramPointTag), St, Pred);
Ted Kremenekcf701772009-02-05 06:50:21 +00003081
Ted Kremenek33b6f632009-02-19 23:47:02 +00003082 if (!N)
3083 return;
3084
3085 // Generate the bug reports.
3086 for (llvm::SmallVectorImpl<std::pair<SymbolRef,bool> >::iterator
3087 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3088
3089 CFRefBug *BT = static_cast<CFRefBug*>(I->second ? leakAtReturn
3090 : leakWithinFunction);
3091 assert(BT && "BugType not initialized.");
Ted Kremenek46347352009-02-23 16:54:00 +00003092 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N,
3093 I->first, Eng);
Ted Kremenek33b6f632009-02-19 23:47:02 +00003094 BR->EmitReport(report);
3095 }
Ted Kremenekcf701772009-02-05 06:50:21 +00003096
Ted Kremenek33b6f632009-02-19 23:47:02 +00003097 Pred = N;
Ted Kremenekcf701772009-02-05 06:50:21 +00003098 }
Ted Kremenek33b6f632009-02-19 23:47:02 +00003099
3100 // Now generate a new node that nukes the old bindings.
3101 GRStateRef state(St, Eng.getStateManager());
3102 RefBindings::Factory& F = state.get_context<RefBindings>();
3103
3104 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3105 E = SymReaper.dead_end(); I!=E; ++I)
3106 B = F.Remove(B, *I);
3107
3108 state = state.set<RefBindings>(B);
3109 Builder.MakeNode(Dst, S, Pred, state);
Ted Kremenekcf701772009-02-05 06:50:21 +00003110}
3111
3112void CFRefCount::ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
3113 GRStmtNodeBuilder<GRState>& Builder,
3114 Expr* NodeExpr, Expr* ErrorExpr,
3115 ExplodedNode<GRState>* Pred,
3116 const GRState* St,
3117 RefVal::Kind hasErr, SymbolRef Sym) {
3118 Builder.BuildSinks = true;
3119 GRExprEngine::NodeTy* N = Builder.MakeNode(Dst, NodeExpr, Pred, St);
3120
3121 if (!N) return;
3122
3123 CFRefBug *BT = 0;
3124
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003125 switch (hasErr) {
3126 default:
3127 assert(false && "Unhandled error.");
3128 return;
3129 case RefVal::ErrorUseAfterRelease:
3130 BT = static_cast<CFRefBug*>(useAfterRelease);
3131 break;
3132 case RefVal::ErrorReleaseNotOwned:
3133 BT = static_cast<CFRefBug*>(releaseNotOwned);
3134 break;
3135 case RefVal::ErrorDeallocGC:
3136 BT = static_cast<CFRefBug*>(deallocGC);
3137 break;
3138 case RefVal::ErrorDeallocNotOwned:
3139 BT = static_cast<CFRefBug*>(deallocNotOwned);
3140 break;
Ted Kremenekcf701772009-02-05 06:50:21 +00003141 }
3142
Ted Kremenekfe9e5432009-02-18 03:48:14 +00003143 CFRefReport *report = new CFRefReport(*BT, *this, N, Sym);
Ted Kremenekcf701772009-02-05 06:50:21 +00003144 report->addRange(ErrorExpr->getSourceRange());
3145 BR->EmitReport(report);
3146}
3147
3148//===----------------------------------------------------------------------===//
Ted Kremenekd71ed262008-04-10 22:16:52 +00003149// Transfer function creation for external clients.
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00003150//===----------------------------------------------------------------------===//
3151
Ted Kremenek072192b2008-04-30 23:47:44 +00003152GRTransferFuncs* clang::MakeCFRefCountTF(ASTContext& Ctx, bool GCEnabled,
3153 const LangOptions& lopts) {
Ted Kremenek78d46242008-07-22 16:21:24 +00003154 return new CFRefCount(Ctx, GCEnabled, lopts);
Ted Kremenek3ea0b6a2008-04-10 22:58:08 +00003155}