blob: 267fc0be1a204cfd38c8a006ad50275ca680edc5 [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 Kremenek1f180c32008-06-23 22:21:20 +0000706 RetainSummary* getClassMethodSummary(IdentifierInfo* ClsName, Selector S);
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
787bool RetainSummaryManager::isTrackedObjectType(QualType T) {
788 if (!Ctx.isObjCObjectPointerType(T))
789 return false;
790
791 // Does it subclass NSObject?
792 ObjCInterfaceType* OT = dyn_cast<ObjCInterfaceType>(T.getTypePtr());
793
794 // We assume that id<..>, id, and "Class" all represent tracked objects.
795 if (!OT)
796 return true;
797
798 // Does the object type subclass NSObject?
799 // FIXME: We can memoize here if this gets too expensive.
800 IdentifierInfo* NSObjectII = &Ctx.Idents.get("NSObject");
801 ObjCInterfaceDecl* ID = OT->getDecl();
802
803 for ( ; ID ; ID = ID->getSuperClass())
804 if (ID->getIdentifier() == NSObjectII)
805 return true;
806
807 return false;
808}
809
810//===----------------------------------------------------------------------===//
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000811// Summary creation for functions (largely uses of Core Foundation).
812//===----------------------------------------------------------------------===//
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000813
Ted Kremenek12619382009-01-12 21:45:02 +0000814static bool isRetain(FunctionDecl* FD, const char* FName) {
815 const char* loc = strstr(FName, "Retain");
816 return loc && loc[sizeof("Retain")-1] == '\0';
817}
818
819static bool isRelease(FunctionDecl* FD, const char* FName) {
820 const char* loc = strstr(FName, "Release");
821 return loc && loc[sizeof("Release")-1] == '\0';
822}
823
Ted Kremenekab592272008-06-24 03:56:45 +0000824RetainSummary* RetainSummaryManager::getSummary(FunctionDecl* FD) {
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000825
826 SourceLocation Loc = FD->getLocation();
827
828 if (!Loc.isFileID())
829 return NULL;
Ted Kremenek2fff37e2008-03-06 00:08:09 +0000830
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000831 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000832 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000833
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000834 if (I != FuncSummaries.end())
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000835 return I->second;
836
837 // No summary. Generate one.
Ted Kremenek12619382009-01-12 21:45:02 +0000838 RetainSummary *S = 0;
Ted Kremenek86ad3bc2008-05-05 16:51:50 +0000839
Ted Kremenek37d785b2008-07-15 16:50:12 +0000840 do {
Ted Kremenek12619382009-01-12 21:45:02 +0000841 // We generate "stop" summaries for implicitly defined functions.
842 if (FD->isImplicit()) {
843 S = getPersistentStopSummary();
844 break;
Ted Kremenek37d785b2008-07-15 16:50:12 +0000845 }
Ted Kremenek6ca31912008-11-04 00:36:12 +0000846
Ted Kremenek6ad315a2009-02-23 16:51:39 +0000847 // [PR 3337] Use 'getAsFunctionType' to strip away any typedefs on the
Ted Kremenek99890652009-01-16 18:40:33 +0000848 // function's type.
Ted Kremenek6ad315a2009-02-23 16:51:39 +0000849 const FunctionType* FT = FD->getType()->getAsFunctionType();
Ted Kremenek12619382009-01-12 21:45:02 +0000850 const char* FName = FD->getIdentifier()->getName();
851
Ted Kremenekbf0a4dd2009-03-05 22:11:14 +0000852 // Strip away preceding '_'. Doing this here will effect all the checks
853 // down below.
854 while (*FName == '_') ++FName;
855
Ted Kremenek12619382009-01-12 21:45:02 +0000856 // Inspect the result type.
857 QualType RetTy = FT->getResultType();
858
859 // FIXME: This should all be refactored into a chain of "summary lookup"
860 // filters.
861 if (strcmp(FName, "IOServiceGetMatchingServices") == 0) {
862 // FIXES: <rdar://problem/6326900>
863 // This should be addressed using a API table. This strcmp is also
864 // a little gross, but there is no need to super optimize here.
865 assert (ScratchArgs.empty());
866 ScratchArgs.push_back(std::make_pair(1, DecRef));
867 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
868 break;
Ted Kremenek64e859a2008-10-22 20:54:52 +0000869 }
Ted Kremenek61991902009-03-17 22:43:44 +0000870
871 // Enable this code once the semantics of NSDeallocateObject are resolved
872 // for GC. <rdar://problem/6619988>
873#if 0
874 // Handle: NSDeallocateObject(id anObject);
875 // This method does allow 'nil' (although we don't check it now).
876 if (strcmp(FName, "NSDeallocateObject") == 0) {
877 return RetTy == Ctx.VoidTy
878 ? getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, Dealloc)
879 : getPersistentStopSummary();
880 }
881#endif
Ted Kremenek12619382009-01-12 21:45:02 +0000882
883 // Handle: id NSMakeCollectable(CFTypeRef)
884 if (strcmp(FName, "NSMakeCollectable") == 0) {
885 S = (RetTy == Ctx.getObjCIdType())
886 ? getUnarySummary(FT, cfmakecollectable)
887 : getPersistentStopSummary();
888
889 break;
890 }
891
892 if (RetTy->isPointerType()) {
893 // For CoreFoundation ('CF') types.
894 if (isRefType(RetTy, "CF", &Ctx, FName)) {
895 if (isRetain(FD, FName))
896 S = getUnarySummary(FT, cfretain);
897 else if (strstr(FName, "MakeCollectable"))
898 S = getUnarySummary(FT, cfmakecollectable);
899 else
900 S = getCFCreateGetRuleSummary(FD, FName);
901
902 break;
903 }
904
905 // For CoreGraphics ('CG') types.
906 if (isRefType(RetTy, "CG", &Ctx, FName)) {
907 if (isRetain(FD, FName))
908 S = getUnarySummary(FT, cfretain);
909 else
910 S = getCFCreateGetRuleSummary(FD, FName);
911
912 break;
913 }
914
915 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
916 if (isRefType(RetTy, "DADisk") ||
917 isRefType(RetTy, "DADissenter") ||
918 isRefType(RetTy, "DASessionRef")) {
919 S = getCFCreateGetRuleSummary(FD, FName);
920 break;
921 }
922
923 break;
924 }
925
926 // Check for release functions, the only kind of functions that we care
927 // about that don't return a pointer type.
928 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
Ted Kremenekbf0a4dd2009-03-05 22:11:14 +0000929 // Test for 'CGCF'.
930 if (FName[1] == 'G' && FName[2] == 'C' && FName[3] == 'F')
931 FName += 4;
932 else
933 FName += 2;
934
935 if (isRelease(FD, FName))
Ted Kremenek12619382009-01-12 21:45:02 +0000936 S = getUnarySummary(FT, cfrelease);
937 else {
Ted Kremenek68189282009-01-29 22:45:13 +0000938 assert (ScratchArgs.empty());
939 // Remaining CoreFoundation and CoreGraphics functions.
940 // We use to assume that they all strictly followed the ownership idiom
941 // and that ownership cannot be transferred. While this is technically
942 // correct, many methods allow a tracked object to escape. For example:
943 //
944 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
945 // CFDictionaryAddValue(y, key, x);
946 // CFRelease(x);
947 // ... it is okay to use 'x' since 'y' has a reference to it
948 //
949 // We handle this and similar cases with the follow heuristic. If the
950 // function name contains "InsertValue", "SetValue" or "AddValue" then
951 // we assume that arguments may "escape."
952 //
953 ArgEffect E = (CStrInCStrNoCase(FName, "InsertValue") ||
954 CStrInCStrNoCase(FName, "AddValue") ||
Ted Kremeneka92206e2009-02-05 22:34:53 +0000955 CStrInCStrNoCase(FName, "SetValue") ||
956 CStrInCStrNoCase(FName, "AppendValue"))
Ted Kremenek68189282009-01-29 22:45:13 +0000957 ? MayEscape : DoNothing;
958
959 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek12619382009-01-12 21:45:02 +0000960 }
961 }
Ted Kremenek37d785b2008-07-15 16:50:12 +0000962 }
963 while (0);
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000964
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000965 FuncSummaries[FD] = S;
Ted Kremenek86ad3bc2008-05-05 16:51:50 +0000966 return S;
Ted Kremenek2fff37e2008-03-06 00:08:09 +0000967}
968
Ted Kremenek37d785b2008-07-15 16:50:12 +0000969RetainSummary*
970RetainSummaryManager::getCFCreateGetRuleSummary(FunctionDecl* FD,
971 const char* FName) {
972
Ted Kremenek86ad3bc2008-05-05 16:51:50 +0000973 if (strstr(FName, "Create") || strstr(FName, "Copy"))
974 return getCFSummaryCreateRule(FD);
Ted Kremenek37d785b2008-07-15 16:50:12 +0000975
Ted Kremenek86ad3bc2008-05-05 16:51:50 +0000976 if (strstr(FName, "Get"))
977 return getCFSummaryGetRule(FD);
978
979 return 0;
980}
981
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000982RetainSummary*
Ted Kremenek6ad315a2009-02-23 16:51:39 +0000983RetainSummaryManager::getUnarySummary(const FunctionType* FT,
984 UnaryFuncKind func) {
985
Ted Kremenek12619382009-01-12 21:45:02 +0000986 // Sanity check that this is *really* a unary function. This can
987 // happen if people do weird things.
Douglas Gregor72564e72009-02-26 23:50:07 +0000988 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
Ted Kremenek12619382009-01-12 21:45:02 +0000989 if (!FTP || FTP->getNumArgs() != 1)
990 return getPersistentStopSummary();
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000991
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000992 assert (ScratchArgs.empty());
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000993
Ted Kremenek377e2302008-04-29 05:33:51 +0000994 switch (func) {
Ted Kremenek12619382009-01-12 21:45:02 +0000995 case cfretain: {
Ted Kremenek377e2302008-04-29 05:33:51 +0000996 ScratchArgs.push_back(std::make_pair(0, IncRef));
Ted Kremenek3eabf1c2008-05-22 17:31:13 +0000997 return getPersistentSummary(RetEffect::MakeAlias(0),
998 DoNothing, DoNothing);
Ted Kremenek377e2302008-04-29 05:33:51 +0000999 }
1000
1001 case cfrelease: {
Ted Kremenek377e2302008-04-29 05:33:51 +00001002 ScratchArgs.push_back(std::make_pair(0, DecRef));
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00001003 return getPersistentSummary(RetEffect::MakeNoRet(),
1004 DoNothing, DoNothing);
Ted Kremenek377e2302008-04-29 05:33:51 +00001005 }
1006
1007 case cfmakecollectable: {
Ted Kremenek27019002009-02-18 21:57:45 +00001008 ScratchArgs.push_back(std::make_pair(0, MakeCollectable));
1009 return getPersistentSummary(RetEffect::MakeAlias(0),DoNothing, DoNothing);
Ted Kremenek377e2302008-04-29 05:33:51 +00001010 }
1011
1012 default:
Ted Kremenek86ad3bc2008-05-05 16:51:50 +00001013 assert (false && "Not a supported unary function.");
Ted Kremenek98530452008-08-12 20:41:56 +00001014 return 0;
Ted Kremenek940b1d82008-04-10 23:44:06 +00001015 }
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001016}
1017
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001018RetainSummary* RetainSummaryManager::getCFSummaryCreateRule(FunctionDecl* FD) {
Ted Kremenek891d5cc2008-04-24 17:22:33 +00001019 assert (ScratchArgs.empty());
Ted Kremenek070a8252008-07-09 18:11:16 +00001020
1021 if (FD->getIdentifier() == CFDictionaryCreateII) {
1022 ScratchArgs.push_back(std::make_pair(1, DoNothingByRef));
1023 ScratchArgs.push_back(std::make_pair(2, DoNothingByRef));
1024 }
1025
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001026 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001027}
1028
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001029RetainSummary* RetainSummaryManager::getCFSummaryGetRule(FunctionDecl* FD) {
Ted Kremenek891d5cc2008-04-24 17:22:33 +00001030 assert (ScratchArgs.empty());
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001031 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1032 DoNothing, DoNothing);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001033}
1034
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001035//===----------------------------------------------------------------------===//
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001036// Summary creation for Selectors.
1037//===----------------------------------------------------------------------===//
1038
Ted Kremenek1bffd742008-05-06 15:44:25 +00001039RetainSummary*
Ted Kremenek553cf182008-06-25 21:21:56 +00001040RetainSummaryManager::getInitMethodSummary(ObjCMessageExpr* ME) {
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001041 assert(ScratchArgs.empty());
1042
Ted Kremenekc3cf7b22009-02-20 00:05:35 +00001043 // 'init' methods only return an alias if the return type is a location type.
1044 QualType T = ME->getType();
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001045 RetainSummary* Summ =
Ted Kremenekc3cf7b22009-02-20 00:05:35 +00001046 getPersistentSummary(Loc::IsLocType(T) ? RetEffect::MakeReceiverAlias()
1047 : RetEffect::MakeNoRet());
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001048
Ted Kremenek553cf182008-06-25 21:21:56 +00001049 ObjCMethodSummaries[ME] = Summ;
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001050 return Summ;
1051}
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001052
Ted Kremenek553cf182008-06-25 21:21:56 +00001053
Ted Kremenek1bffd742008-05-06 15:44:25 +00001054RetainSummary*
Ted Kremenek553cf182008-06-25 21:21:56 +00001055RetainSummaryManager::getMethodSummary(ObjCMessageExpr* ME,
1056 ObjCInterfaceDecl* ID) {
Ted Kremenek1bffd742008-05-06 15:44:25 +00001057
1058 Selector S = ME->getSelector();
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001059
Ted Kremenek553cf182008-06-25 21:21:56 +00001060 // Look up a summary in our summary cache.
1061 ObjCMethodSummariesTy::iterator I = ObjCMethodSummaries.find(ID, S);
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001062
Ted Kremenek1f180c32008-06-23 22:21:20 +00001063 if (I != ObjCMethodSummaries.end())
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001064 return I->second;
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001065
Ted Kremenek234a4c22009-01-07 00:39:56 +00001066 // "initXXX": pass-through for receiver.
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001067 const char* s = S.getIdentifierInfoForSlot(0)->getName();
Ted Kremeneka4b695a2008-05-07 03:45:05 +00001068 assert (ScratchArgs.empty());
Ted Kremenekaee9e572008-05-06 06:09:09 +00001069
Ted Kremenekb80976c2009-02-21 05:13:43 +00001070 if (deriveNamingConvention(s) == InitRule)
Ted Kremenek234a4c22009-01-07 00:39:56 +00001071 return getInitMethodSummary(ME);
Ted Kremenek1bffd742008-05-06 15:44:25 +00001072
Ted Kremenek234a4c22009-01-07 00:39:56 +00001073 // Look for methods that return an owned object.
1074 if (!isTrackedObjectType(Ctx.getCanonicalType(ME->getType())))
Ted Kremenek84060db2008-05-07 04:25:59 +00001075 return 0;
Ted Kremeneka4b695a2008-05-07 03:45:05 +00001076
Ted Kremenek234a4c22009-01-07 00:39:56 +00001077 if (followsFundamentalRule(s)) {
1078 RetEffect E = isGCEnabled() ? RetEffect::MakeNoRet()
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001079 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremeneka4b695a2008-05-07 03:45:05 +00001080 RetainSummary* Summ = getPersistentSummary(E);
Ted Kremenek553cf182008-06-25 21:21:56 +00001081 ObjCMethodSummaries[ME] = Summ;
Ted Kremenek1bffd742008-05-06 15:44:25 +00001082 return Summ;
1083 }
Ted Kremenek1bffd742008-05-06 15:44:25 +00001084
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001085 return 0;
1086}
1087
Ted Kremenekc8395602008-05-06 21:26:51 +00001088RetainSummary*
Ted Kremenek1f180c32008-06-23 22:21:20 +00001089RetainSummaryManager::getClassMethodSummary(IdentifierInfo* ClsName,
1090 Selector S) {
Ted Kremenekc8395602008-05-06 21:26:51 +00001091
Ted Kremenek553cf182008-06-25 21:21:56 +00001092 // FIXME: Eventually we should properly do class method summaries, but
1093 // it requires us being able to walk the type hierarchy. Unfortunately,
1094 // we cannot do this with just an IdentifierInfo* for the class name.
1095
Ted Kremenekc8395602008-05-06 21:26:51 +00001096 // Look up a summary in our cache of Selectors -> Summaries.
Ted Kremenek553cf182008-06-25 21:21:56 +00001097 ObjCMethodSummariesTy::iterator I = ObjCClassMethodSummaries.find(ClsName, S);
Ted Kremenekc8395602008-05-06 21:26:51 +00001098
Ted Kremenek1f180c32008-06-23 22:21:20 +00001099 if (I != ObjCClassMethodSummaries.end())
Ted Kremenekc8395602008-05-06 21:26:51 +00001100 return I->second;
1101
Ted Kremeneka22cc2f2008-05-06 23:07:13 +00001102 return 0;
Ted Kremenekc8395602008-05-06 21:26:51 +00001103}
1104
Ted Kremenek1f180c32008-06-23 22:21:20 +00001105void RetainSummaryManager::InitializeClassMethodSummaries() {
Ted Kremenek9c32d082008-05-06 00:30:21 +00001106
1107 assert (ScratchArgs.empty());
1108
Ted Kremeneka7344702008-06-23 18:02:52 +00001109 RetEffect E = isGCEnabled() ? RetEffect::MakeNoRet()
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001110 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremeneka7344702008-06-23 18:02:52 +00001111
Ted Kremenek9c32d082008-05-06 00:30:21 +00001112 RetainSummary* Summ = getPersistentSummary(E);
1113
Ted Kremenek553cf182008-06-25 21:21:56 +00001114 // Create the summaries for "alloc", "new", and "allocWithZone:" for
1115 // NSObject and its derivatives.
1116 addNSObjectClsMethSummary(GetNullarySelector("alloc", Ctx), Summ);
1117 addNSObjectClsMethSummary(GetNullarySelector("new", Ctx), Summ);
1118 addNSObjectClsMethSummary(GetUnarySelector("allocWithZone", Ctx), Summ);
Ted Kremenek70a733e2008-07-18 17:24:20 +00001119
1120 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek9e476de2008-08-12 18:30:56 +00001121 addClsMethSummary(&Ctx.Idents.get("NSAssertionHandler"),
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001122 GetNullarySelector("currentHandler", Ctx),
1123 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Ted Kremenek6d348932008-10-21 15:53:15 +00001124
1125 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremenekabf43972009-01-28 21:44:40 +00001126 ScratchArgs.push_back(std::make_pair(0, Autorelease));
1127 addClsMethSummary(&Ctx.Idents.get("NSAutoreleasePool"),
1128 GetUnarySelector("addObject", Ctx),
1129 getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenek022a3c42009-02-23 02:31:16 +00001130 DoNothing, Autorelease));
Ted Kremenek9c32d082008-05-06 00:30:21 +00001131}
1132
Ted Kremenek1f180c32008-06-23 22:21:20 +00001133void RetainSummaryManager::InitializeMethodSummaries() {
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001134
1135 assert (ScratchArgs.empty());
1136
Ted Kremenekc8395602008-05-06 21:26:51 +00001137 // Create the "init" selector. It just acts as a pass-through for the
1138 // receiver.
Ted Kremenek46347352009-02-23 16:54:00 +00001139 RetainSummary* InitSumm =
1140 getPersistentSummary(RetEffect::MakeReceiverAlias());
Ted Kremenek179064e2008-07-01 17:21:27 +00001141 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
Ted Kremenekc8395602008-05-06 21:26:51 +00001142
1143 // The next methods are allocators.
Ted Kremeneka7344702008-06-23 18:02:52 +00001144 RetEffect E = isGCEnabled() ? RetEffect::MakeNoRet()
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001145 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremeneka7344702008-06-23 18:02:52 +00001146
Ted Kremenek179064e2008-07-01 17:21:27 +00001147 RetainSummary* Summ = getPersistentSummary(E);
Ted Kremenekc8395602008-05-06 21:26:51 +00001148
1149 // Create the "copy" selector.
Ted Kremenek98530452008-08-12 20:41:56 +00001150 addNSObjectMethSummary(GetNullarySelector("copy", Ctx), Summ);
1151
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001152 // Create the "mutableCopy" selector.
Ted Kremenek553cf182008-06-25 21:21:56 +00001153 addNSObjectMethSummary(GetNullarySelector("mutableCopy", Ctx), Summ);
Ted Kremenek98530452008-08-12 20:41:56 +00001154
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001155 // Create the "retain" selector.
1156 E = RetEffect::MakeReceiverAlias();
Ted Kremenek1c512f52009-02-18 18:54:33 +00001157 Summ = getPersistentSummary(E, IncRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001158 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001159
1160 // Create the "release" selector.
Ted Kremenek1c512f52009-02-18 18:54:33 +00001161 Summ = getPersistentSummary(E, DecRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001162 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Ted Kremenek299e8152008-05-07 21:17:39 +00001163
1164 // Create the "drain" selector.
1165 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek553cf182008-06-25 21:21:56 +00001166 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001167
1168 // Create the -dealloc summary.
1169 Summ = getPersistentSummary(RetEffect::MakeNoRet(), Dealloc);
1170 addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001171
1172 // Create the "autorelease" selector.
Ted Kremenekabf43972009-01-28 21:44:40 +00001173 Summ = getPersistentSummary(E, Autorelease);
Ted Kremenek553cf182008-06-25 21:21:56 +00001174 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Ted Kremenek98530452008-08-12 20:41:56 +00001175
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00001176 // Specially handle NSAutoreleasePool.
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001177 addInstMethSummary("NSAutoreleasePool", "init",
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00001178 getPersistentSummary(RetEffect::MakeReceiverAlias(),
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001179 NewAutoreleasePool));
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00001180
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001181 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremenek89e202d2009-02-23 02:51:29 +00001182 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1183 // self-own themselves. However, they only do this once they are displayed.
1184 // Thus, we need to track an NSWindow's display status.
1185 // This is tracked in <rdar://problem/6062711>.
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +00001186 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
Ted Kremenek99d02692009-04-03 19:02:51 +00001187 RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet());
1188
1189 addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1190
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +00001191
1192#if 0
Ted Kremenek179064e2008-07-01 17:21:27 +00001193 RetainSummary *NSWindowSumm =
Ted Kremenek89e202d2009-02-23 02:51:29 +00001194 getPersistentSummary(RetEffect::MakeReceiverAlias(), StopTracking);
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001195
1196 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1197 "styleMask", "backing", "defer", NULL);
1198
1199 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1200 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +00001201#endif
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001202
1203 // For NSPanel (which subclasses NSWindow), allocated objects are not
1204 // self-owned.
Ted Kremenek99d02692009-04-03 19:02:51 +00001205 // FIXME: For now we don't track NSPanels. object for the same reason
1206 // as for NSWindow objects.
1207 addClassMethSummary("NSPanel", "alloc", NoTrackYet);
1208
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001209 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1210 "styleMask", "backing", "defer", NULL);
1211
1212 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1213 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek553cf182008-06-25 21:21:56 +00001214
Ted Kremenek70a733e2008-07-18 17:24:20 +00001215 // Create NSAssertionHandler summaries.
Ted Kremenek9e476de2008-08-12 18:30:56 +00001216 addPanicSummary("NSAssertionHandler", "handleFailureInFunction", "file",
1217 "lineNumber", "description", NULL);
Ted Kremenek70a733e2008-07-18 17:24:20 +00001218
Ted Kremenek9e476de2008-08-12 18:30:56 +00001219 addPanicSummary("NSAssertionHandler", "handleFailureInMethod", "object",
1220 "file", "lineNumber", "description", NULL);
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001221}
1222
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001223//===----------------------------------------------------------------------===//
Ted Kremenek13922612008-04-16 20:40:59 +00001224// Reference-counting logic (typestate + counts).
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001225//===----------------------------------------------------------------------===//
1226
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001227namespace {
1228
Ted Kremenek05cbe1a2008-04-09 23:49:11 +00001229class VISIBILITY_HIDDEN RefVal {
Ted Kremenek4fd88972008-04-17 18:12:53 +00001230public:
Ted Kremenek4fd88972008-04-17 18:12:53 +00001231 enum Kind {
1232 Owned = 0, // Owning reference.
1233 NotOwned, // Reference is not owned by still valid (not freed).
1234 Released, // Object has been released.
1235 ReturnedOwned, // Returned object passes ownership to caller.
1236 ReturnedNotOwned, // Return object does not pass ownership to caller.
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001237 ERROR_START,
1238 ErrorDeallocNotOwned, // -dealloc called on non-owned object.
1239 ErrorDeallocGC, // Calling -dealloc with GC enabled.
Ted Kremenek4fd88972008-04-17 18:12:53 +00001240 ErrorUseAfterRelease, // Object used after released.
1241 ErrorReleaseNotOwned, // Release of an object that was not owned.
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001242 ERROR_LEAK_START,
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00001243 ErrorLeak, // A memory leak due to excessive reference counts.
1244 ErrorLeakReturned // A memory leak due to the returning method not having
1245 // the correct naming conventions.
Ted Kremenek4fd88972008-04-17 18:12:53 +00001246 };
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001247
1248private:
Ted Kremenek4fd88972008-04-17 18:12:53 +00001249 Kind kind;
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001250 RetEffect::ObjKind okind;
Ted Kremenek4fd88972008-04-17 18:12:53 +00001251 unsigned Cnt;
Ted Kremenek553cf182008-06-25 21:21:56 +00001252 QualType T;
1253
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001254 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, QualType t)
1255 : kind(k), okind(o), Cnt(cnt), T(t) {}
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001256
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001257 RefVal(Kind k, unsigned cnt = 0)
1258 : kind(k), okind(RetEffect::AnyObj), Cnt(cnt) {}
1259
1260public:
Ted Kremenek4fd88972008-04-17 18:12:53 +00001261 Kind getKind() const { return kind; }
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001262
1263 RetEffect::ObjKind getObjKind() const { return okind; }
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001264
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001265 unsigned getCount() const { return Cnt; }
1266 void clearCounts() { Cnt = 0; }
1267
Ted Kremenek553cf182008-06-25 21:21:56 +00001268 QualType getType() const { return T; }
Ted Kremenek4fd88972008-04-17 18:12:53 +00001269
1270 // Useful predicates.
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001271
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001272 static bool isError(Kind k) { return k >= ERROR_START; }
Ted Kremenek73c750b2008-03-11 18:14:09 +00001273
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001274 static bool isLeak(Kind k) { return k >= ERROR_LEAK_START; }
Ted Kremenekdb863712008-04-16 22:32:20 +00001275
Ted Kremeneke7bd9c22008-04-11 22:25:11 +00001276 bool isOwned() const {
1277 return getKind() == Owned;
1278 }
1279
Ted Kremenekdb863712008-04-16 22:32:20 +00001280 bool isNotOwned() const {
1281 return getKind() == NotOwned;
1282 }
1283
Ted Kremenek4fd88972008-04-17 18:12:53 +00001284 bool isReturnedOwned() const {
1285 return getKind() == ReturnedOwned;
1286 }
1287
1288 bool isReturnedNotOwned() const {
1289 return getKind() == ReturnedNotOwned;
1290 }
1291
1292 bool isNonLeakError() const {
1293 Kind k = getKind();
1294 return isError(k) && !isLeak(k);
1295 }
1296
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001297 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
1298 unsigned Count = 1) {
1299 return RefVal(Owned, o, Count, t);
Ted Kremenek61b9f872008-04-10 23:09:18 +00001300 }
1301
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001302 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
1303 unsigned Count = 0) {
1304 return RefVal(NotOwned, o, Count, t);
Ted Kremenek61b9f872008-04-10 23:09:18 +00001305 }
Ted Kremenek4fd88972008-04-17 18:12:53 +00001306
1307 static RefVal makeReturnedOwned(unsigned Count) {
1308 return RefVal(ReturnedOwned, Count);
1309 }
1310
1311 static RefVal makeReturnedNotOwned() {
1312 return RefVal(ReturnedNotOwned);
1313 }
1314
Ted Kremenek4fd88972008-04-17 18:12:53 +00001315 // Comparison, profiling, and pretty-printing.
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001316
Ted Kremenek4fd88972008-04-17 18:12:53 +00001317 bool operator==(const RefVal& X) const {
Ted Kremenek553cf182008-06-25 21:21:56 +00001318 return kind == X.kind && Cnt == X.Cnt && T == X.T;
Ted Kremenek4fd88972008-04-17 18:12:53 +00001319 }
Ted Kremenekf3948042008-03-11 19:44:10 +00001320
Ted Kremenek553cf182008-06-25 21:21:56 +00001321 RefVal operator-(size_t i) const {
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001322 return RefVal(getKind(), getObjKind(), getCount() - i, getType());
Ted Kremenek553cf182008-06-25 21:21:56 +00001323 }
1324
1325 RefVal operator+(size_t i) const {
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001326 return RefVal(getKind(), getObjKind(), getCount() + i, getType());
Ted Kremenek553cf182008-06-25 21:21:56 +00001327 }
1328
1329 RefVal operator^(Kind k) const {
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001330 return RefVal(k, getObjKind(), getCount(), getType());
Ted Kremenek553cf182008-06-25 21:21:56 +00001331 }
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001332
Ted Kremenek4fd88972008-04-17 18:12:53 +00001333 void Profile(llvm::FoldingSetNodeID& ID) const {
1334 ID.AddInteger((unsigned) kind);
1335 ID.AddInteger(Cnt);
Ted Kremenek553cf182008-06-25 21:21:56 +00001336 ID.Add(T);
Ted Kremenek4fd88972008-04-17 18:12:53 +00001337 }
1338
Ted Kremenekf3948042008-03-11 19:44:10 +00001339 void print(std::ostream& Out) const;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001340};
Ted Kremenekf3948042008-03-11 19:44:10 +00001341
1342void RefVal::print(std::ostream& Out) const {
Ted Kremenek553cf182008-06-25 21:21:56 +00001343 if (!T.isNull())
1344 Out << "Tracked Type:" << T.getAsString() << '\n';
1345
Ted Kremenekf3948042008-03-11 19:44:10 +00001346 switch (getKind()) {
1347 default: assert(false);
Ted Kremenek61b9f872008-04-10 23:09:18 +00001348 case Owned: {
1349 Out << "Owned";
1350 unsigned cnt = getCount();
1351 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenekf3948042008-03-11 19:44:10 +00001352 break;
Ted Kremenek61b9f872008-04-10 23:09:18 +00001353 }
Ted Kremenekf3948042008-03-11 19:44:10 +00001354
Ted Kremenek61b9f872008-04-10 23:09:18 +00001355 case NotOwned: {
Ted Kremenek4fd88972008-04-17 18:12:53 +00001356 Out << "NotOwned";
Ted Kremenek61b9f872008-04-10 23:09:18 +00001357 unsigned cnt = getCount();
1358 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenekf3948042008-03-11 19:44:10 +00001359 break;
Ted Kremenek61b9f872008-04-10 23:09:18 +00001360 }
Ted Kremenekf3948042008-03-11 19:44:10 +00001361
Ted Kremenek4fd88972008-04-17 18:12:53 +00001362 case ReturnedOwned: {
1363 Out << "ReturnedOwned";
1364 unsigned cnt = getCount();
1365 if (cnt) Out << " (+ " << cnt << ")";
1366 break;
1367 }
1368
1369 case ReturnedNotOwned: {
1370 Out << "ReturnedNotOwned";
1371 unsigned cnt = getCount();
1372 if (cnt) Out << " (+ " << cnt << ")";
1373 break;
1374 }
1375
Ted Kremenekf3948042008-03-11 19:44:10 +00001376 case Released:
1377 Out << "Released";
1378 break;
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001379
1380 case ErrorDeallocGC:
1381 Out << "-dealloc (GC)";
1382 break;
1383
1384 case ErrorDeallocNotOwned:
1385 Out << "-dealloc (not-owned)";
1386 break;
Ted Kremenekf3948042008-03-11 19:44:10 +00001387
Ted Kremenekdb863712008-04-16 22:32:20 +00001388 case ErrorLeak:
1389 Out << "Leaked";
1390 break;
1391
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00001392 case ErrorLeakReturned:
1393 Out << "Leaked (Bad naming)";
1394 break;
1395
Ted Kremenekf3948042008-03-11 19:44:10 +00001396 case ErrorUseAfterRelease:
1397 Out << "Use-After-Release [ERROR]";
1398 break;
1399
1400 case ErrorReleaseNotOwned:
1401 Out << "Release of Not-Owned [ERROR]";
1402 break;
1403 }
1404}
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001405
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001406} // end anonymous namespace
1407
1408//===----------------------------------------------------------------------===//
1409// RefBindings - State used to track object reference counts.
1410//===----------------------------------------------------------------------===//
1411
Ted Kremenek2dabd432008-12-05 02:27:51 +00001412typedef llvm::ImmutableMap<SymbolRef, RefVal> RefBindings;
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001413static int RefBIndex = 0;
Ted Kremenek33b6f632009-02-19 23:47:02 +00001414static std::pair<const void*, const void*> LeakProgramPointTag(&RefBIndex, 0);
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001415
1416namespace clang {
Ted Kremenekb9d17f92008-08-17 03:20:02 +00001417 template<>
1418 struct GRStateTrait<RefBindings> : public GRStatePartialTrait<RefBindings> {
1419 static inline void* GDMIndex() { return &RefBIndex; }
1420 };
1421}
Ted Kremenek6d348932008-10-21 15:53:15 +00001422
1423//===----------------------------------------------------------------------===//
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001424// AutoreleaseBindings - State used to track objects in autorelease pools.
Ted Kremenek6d348932008-10-21 15:53:15 +00001425//===----------------------------------------------------------------------===//
1426
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001427typedef llvm::ImmutableMap<SymbolRef, unsigned> ARCounts;
1428typedef llvm::ImmutableMap<SymbolRef, ARCounts> ARPoolContents;
1429typedef llvm::ImmutableList<SymbolRef> ARStack;
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00001430
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001431static int AutoRCIndex = 0;
Ted Kremenek6d348932008-10-21 15:53:15 +00001432static int AutoRBIndex = 0;
1433
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001434namespace { class VISIBILITY_HIDDEN AutoreleasePoolContents {}; }
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001435namespace { class VISIBILITY_HIDDEN AutoreleaseStack {}; }
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001436
Ted Kremenek6d348932008-10-21 15:53:15 +00001437namespace clang {
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001438template<> struct GRStateTrait<AutoreleaseStack>
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001439 : public GRStatePartialTrait<ARStack> {
1440 static inline void* GDMIndex() { return &AutoRBIndex; }
1441};
1442
1443template<> struct GRStateTrait<AutoreleasePoolContents>
1444 : public GRStatePartialTrait<ARPoolContents> {
1445 static inline void* GDMIndex() { return &AutoRCIndex; }
1446};
1447} // end clang namespace
Ted Kremenek6d348932008-10-21 15:53:15 +00001448
Ted Kremenek7037ab82009-03-20 17:34:15 +00001449static SymbolRef GetCurrentAutoreleasePool(const GRState* state) {
1450 ARStack stack = state->get<AutoreleaseStack>();
1451 return stack.isEmpty() ? SymbolRef() : stack.getHead();
1452}
1453
1454static GRStateRef SendAutorelease(GRStateRef state, ARCounts::Factory &F,
1455 SymbolRef sym) {
1456
1457 SymbolRef pool = GetCurrentAutoreleasePool(state);
1458 const ARCounts *cnts = state.get<AutoreleasePoolContents>(pool);
1459 ARCounts newCnts(0);
1460
1461 if (cnts) {
1462 const unsigned *cnt = (*cnts).lookup(sym);
1463 newCnts = F.Add(*cnts, sym, cnt ? *cnt + 1 : 1);
1464 }
1465 else
1466 newCnts = F.Add(F.GetEmptyMap(), sym, 1);
1467
1468 return state.set<AutoreleasePoolContents>(pool, newCnts);
1469}
1470
Ted Kremenek13922612008-04-16 20:40:59 +00001471//===----------------------------------------------------------------------===//
1472// Transfer functions.
1473//===----------------------------------------------------------------------===//
1474
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001475namespace {
1476
Ted Kremenek05cbe1a2008-04-09 23:49:11 +00001477class VISIBILITY_HIDDEN CFRefCount : public GRSimpleVals {
Ted Kremenek8dd56462008-04-18 03:39:05 +00001478public:
Ted Kremenekae6814e2008-08-13 21:24:49 +00001479 class BindingsPrinter : public GRState::Printer {
Ted Kremenekf3948042008-03-11 19:44:10 +00001480 public:
Ted Kremenekae6814e2008-08-13 21:24:49 +00001481 virtual void Print(std::ostream& Out, const GRState* state,
1482 const char* nl, const char* sep);
Ted Kremenekf3948042008-03-11 19:44:10 +00001483 };
Ted Kremenek8dd56462008-04-18 03:39:05 +00001484
1485private:
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001486 typedef llvm::DenseMap<const GRExprEngine::NodeTy*, const RetainSummary*>
1487 SummaryLogTy;
1488
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001489 RetainSummaryManager Summaries;
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001490 SummaryLogTy SummaryLog;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001491 const LangOptions& LOpts;
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001492 ARCounts::Factory ARCountFactory;
Ted Kremenekb9d17f92008-08-17 03:20:02 +00001493
Ted Kremenekcf701772009-02-05 06:50:21 +00001494 BugType *useAfterRelease, *releaseNotOwned;
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001495 BugType *deallocGC, *deallocNotOwned;
Ted Kremenekcf701772009-02-05 06:50:21 +00001496 BugType *leakWithinFunction, *leakAtReturn;
1497 BugReporter *BR;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001498
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001499 GRStateRef Update(GRStateRef state, SymbolRef sym, RefVal V, ArgEffect E,
1500 RefVal::Kind& hasErr);
1501
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001502 void ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
1503 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekdb863712008-04-16 22:32:20 +00001504 Expr* NodeExpr, Expr* ErrorExpr,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001505 ExplodedNode<GRState>* Pred,
1506 const GRState* St,
Ted Kremenek2dabd432008-12-05 02:27:51 +00001507 RefVal::Kind hasErr, SymbolRef Sym);
Ted Kremenekdb863712008-04-16 22:32:20 +00001508
Ted Kremenekf9790ae2008-10-24 20:32:50 +00001509 std::pair<GRStateRef, bool>
1510 HandleSymbolDeath(GRStateManager& VMgr, const GRState* St,
Ted Kremenek2dabd432008-12-05 02:27:51 +00001511 const Decl* CD, SymbolRef sid, RefVal V, bool& hasLeak);
Ted Kremenekdb863712008-04-16 22:32:20 +00001512
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001513public:
Ted Kremenek78d46242008-07-22 16:21:24 +00001514 CFRefCount(ASTContext& Ctx, bool gcenabled, const LangOptions& lopts)
Ted Kremenek377e2302008-04-29 05:33:51 +00001515 : Summaries(Ctx, gcenabled),
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00001516 LOpts(lopts), useAfterRelease(0), releaseNotOwned(0),
1517 deallocGC(0), deallocNotOwned(0),
Ted Kremenekcf701772009-02-05 06:50:21 +00001518 leakWithinFunction(0), leakAtReturn(0), BR(0) {}
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001519
Ted Kremenekcf701772009-02-05 06:50:21 +00001520 virtual ~CFRefCount() {}
Ted Kremenek05cbe1a2008-04-09 23:49:11 +00001521
Ted Kremenekcf118d42009-02-04 23:49:09 +00001522 void RegisterChecks(BugReporter &BR);
Ted Kremenekf3948042008-03-11 19:44:10 +00001523
Ted Kremenek1c72ef02008-08-16 00:49:49 +00001524 virtual void RegisterPrinters(std::vector<GRState::Printer*>& Printers) {
1525 Printers.push_back(new BindingsPrinter());
Ted Kremenekf3948042008-03-11 19:44:10 +00001526 }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001527
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001528 bool isGCEnabled() const { return Summaries.isGCEnabled(); }
Ted Kremenek072192b2008-04-30 23:47:44 +00001529 const LangOptions& getLangOptions() const { return LOpts; }
1530
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001531 const RetainSummary *getSummaryOfNode(const ExplodedNode<GRState> *N) const {
1532 SummaryLogTy::const_iterator I = SummaryLog.find(N);
1533 return I == SummaryLog.end() ? 0 : I->second;
1534 }
1535
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001536 // Calls.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001537
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001538 void EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001539 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001540 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001541 Expr* Ex,
1542 Expr* Receiver,
1543 RetainSummary* Summ,
Ted Kremenek55499762008-06-17 02:43:46 +00001544 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001545 ExplodedNode<GRState>* Pred);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001546
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001547 virtual void EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek199e1a02008-03-12 21:06:49 +00001548 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001549 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001550 CallExpr* CE, SVal L,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001551 ExplodedNode<GRState>* Pred);
Ted Kremenekfa34b332008-04-09 01:10:13 +00001552
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001553
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001554 virtual void EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek85348202008-04-15 23:44:31 +00001555 GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001556 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek85348202008-04-15 23:44:31 +00001557 ObjCMessageExpr* ME,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001558 ExplodedNode<GRState>* Pred);
Ted Kremenek85348202008-04-15 23:44:31 +00001559
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001560 bool EvalObjCMessageExprAux(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek85348202008-04-15 23:44:31 +00001561 GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001562 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek85348202008-04-15 23:44:31 +00001563 ObjCMessageExpr* ME,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001564 ExplodedNode<GRState>* Pred);
Ted Kremenek85348202008-04-15 23:44:31 +00001565
Ted Kremenek41573eb2009-02-14 01:43:44 +00001566 // Stores.
1567 virtual void EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val);
1568
Ted Kremeneke7bd9c22008-04-11 22:25:11 +00001569 // End-of-path.
1570
1571 virtual void EvalEndPath(GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001572 GREndPathNodeBuilder<GRState>& Builder);
Ted Kremeneke7bd9c22008-04-11 22:25:11 +00001573
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001574 virtual void EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek652adc62008-04-24 23:57:27 +00001575 GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001576 GRStmtNodeBuilder<GRState>& Builder,
1577 ExplodedNode<GRState>* Pred,
Ted Kremenek241677a2009-01-21 22:26:05 +00001578 Stmt* S, const GRState* state,
1579 SymbolReaper& SymReaper);
1580
Ted Kremenek4fd88972008-04-17 18:12:53 +00001581 // Return statements.
1582
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001583 virtual void EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4fd88972008-04-17 18:12:53 +00001584 GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001585 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4fd88972008-04-17 18:12:53 +00001586 ReturnStmt* S,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001587 ExplodedNode<GRState>* Pred);
Ted Kremenekcb612922008-04-18 19:23:43 +00001588
1589 // Assumptions.
1590
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001591 virtual const GRState* EvalAssume(GRStateManager& VMgr,
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001592 const GRState* St, SVal Cond,
Ted Kremenek4323a572008-07-10 22:03:41 +00001593 bool Assumption, bool& isFeasible);
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001594};
1595
1596} // end anonymous namespace
1597
Ted Kremenek7037ab82009-03-20 17:34:15 +00001598static void PrintPool(std::ostream &Out, SymbolRef Sym, const GRState *state) {
1599 Out << ' ';
Ted Kremeneke0e4ebf2009-03-26 03:35:11 +00001600 if (Sym)
1601 Out << Sym->getSymbolID();
Ted Kremenek7037ab82009-03-20 17:34:15 +00001602 else
1603 Out << "<pool>";
1604 Out << ":{";
1605
1606 // Get the contents of the pool.
1607 if (const ARCounts *cnts = state->get<AutoreleasePoolContents>(Sym))
1608 for (ARCounts::iterator J=cnts->begin(), EJ=cnts->end(); J != EJ; ++J)
1609 Out << '(' << J.getKey() << ',' << J.getData() << ')';
1610
1611 Out << '}';
1612}
Ted Kremenek8dd56462008-04-18 03:39:05 +00001613
Ted Kremenekae6814e2008-08-13 21:24:49 +00001614void CFRefCount::BindingsPrinter::Print(std::ostream& Out, const GRState* state,
1615 const char* nl, const char* sep) {
Ted Kremenek7037ab82009-03-20 17:34:15 +00001616
1617
Ted Kremenekae6814e2008-08-13 21:24:49 +00001618
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001619 RefBindings B = state->get<RefBindings>();
Ted Kremenekf3948042008-03-11 19:44:10 +00001620
Ted Kremenekae6814e2008-08-13 21:24:49 +00001621 if (!B.isEmpty())
Ted Kremenekf3948042008-03-11 19:44:10 +00001622 Out << sep << nl;
1623
1624 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
1625 Out << (*I).first << " : ";
1626 (*I).second.print(Out);
1627 Out << nl;
1628 }
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001629
1630 // Print the autorelease stack.
Ted Kremenek7037ab82009-03-20 17:34:15 +00001631 Out << sep << nl << "AR pool stack:";
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001632 ARStack stack = state->get<AutoreleaseStack>();
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001633
Ted Kremenek7037ab82009-03-20 17:34:15 +00001634 PrintPool(Out, SymbolRef(), state); // Print the caller's pool.
1635 for (ARStack::iterator I=stack.begin(), E=stack.end(); I!=E; ++I)
1636 PrintPool(Out, *I, state);
1637
1638 Out << nl;
Ted Kremenekf3948042008-03-11 19:44:10 +00001639}
1640
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001641static inline ArgEffect GetArgE(RetainSummary* Summ, unsigned idx) {
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00001642 return Summ ? Summ->getArg(idx) : MayEscape;
Ted Kremenekf9561e52008-04-11 20:23:24 +00001643}
1644
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001645static inline RetEffect GetRetEffect(RetainSummary* Summ) {
1646 return Summ ? Summ->getRetEffect() : RetEffect::MakeNoRet();
Ted Kremenekf9561e52008-04-11 20:23:24 +00001647}
1648
Ted Kremenek14993892008-05-06 02:41:27 +00001649static inline ArgEffect GetReceiverE(RetainSummary* Summ) {
1650 return Summ ? Summ->getReceiverEffect() : DoNothing;
1651}
1652
Ted Kremenek70a733e2008-07-18 17:24:20 +00001653static inline bool IsEndPath(RetainSummary* Summ) {
1654 return Summ ? Summ->isEndPath() : false;
1655}
1656
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001657
Ted Kremenek553cf182008-06-25 21:21:56 +00001658/// GetReturnType - Used to get the return type of a message expression or
1659/// function call with the intention of affixing that type to a tracked symbol.
1660/// While the the return type can be queried directly from RetEx, when
1661/// invoking class methods we augment to the return type to be that of
1662/// a pointer to the class (as opposed it just being id).
1663static QualType GetReturnType(Expr* RetE, ASTContext& Ctx) {
1664
1665 QualType RetTy = RetE->getType();
1666
1667 // FIXME: We aren't handling id<...>.
Chris Lattner8b51fd72008-07-26 22:36:27 +00001668 const PointerType* PT = RetTy->getAsPointerType();
Ted Kremenek553cf182008-06-25 21:21:56 +00001669 if (!PT)
1670 return RetTy;
1671
1672 // If RetEx is not a message expression just return its type.
1673 // If RetEx is a message expression, return its types if it is something
1674 /// more specific than id.
1675
1676 ObjCMessageExpr* ME = dyn_cast<ObjCMessageExpr>(RetE);
1677
Steve Naroff389bf462009-02-12 17:52:19 +00001678 if (!ME || !Ctx.isObjCIdStructType(PT->getPointeeType()))
Ted Kremenek553cf182008-06-25 21:21:56 +00001679 return RetTy;
1680
1681 ObjCInterfaceDecl* D = ME->getClassInfo().first;
1682
1683 // At this point we know the return type of the message expression is id.
1684 // If we have an ObjCInterceDecl, we know this is a call to a class method
1685 // whose type we can resolve. In such cases, promote the return type to
1686 // Class*.
1687 return !D ? RetTy : Ctx.getPointerType(Ctx.getObjCInterfaceType(D));
1688}
1689
1690
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001691void CFRefCount::EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001692 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001693 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001694 Expr* Ex,
1695 Expr* Receiver,
1696 RetainSummary* Summ,
Ted Kremenek55499762008-06-17 02:43:46 +00001697 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001698 ExplodedNode<GRState>* Pred) {
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001699
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001700 // Get the state.
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001701 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenekf9790ae2008-10-24 20:32:50 +00001702 ASTContext& Ctx = Eng.getStateManager().getContext();
Ted Kremenek14993892008-05-06 02:41:27 +00001703
1704 // Evaluate the effect of the arguments.
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001705 RefVal::Kind hasErr = (RefVal::Kind) 0;
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001706 unsigned idx = 0;
Ted Kremenekbcf50ad2008-04-11 18:40:51 +00001707 Expr* ErrorExpr = NULL;
Ted Kremenek2dabd432008-12-05 02:27:51 +00001708 SymbolRef ErrorSym = 0;
Ted Kremenekbcf50ad2008-04-11 18:40:51 +00001709
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001710 for (ExprIterator I = arg_beg; I != arg_end; ++I, ++idx) {
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00001711 SVal V = state.GetSValAsScalarOrLoc(*I);
Ted Kremenek94c96982009-03-03 22:06:47 +00001712 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00001713
Ted Kremeneke0e4ebf2009-03-26 03:35:11 +00001714 if (Sym)
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001715 if (RefBindings::data_type* T = state.get<RefBindings>(Sym)) {
1716 state = Update(state, Sym, *T, GetArgE(Summ, idx), hasErr);
1717 if (hasErr) {
Ted Kremenekbcf50ad2008-04-11 18:40:51 +00001718 ErrorExpr = *I;
Ted Kremeneke8fdc832008-07-07 16:21:19 +00001719 ErrorSym = Sym;
Ted Kremenekbcf50ad2008-04-11 18:40:51 +00001720 break;
Ted Kremenek94c96982009-03-03 22:06:47 +00001721 }
1722 continue;
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001723 }
Ted Kremenek070a8252008-07-09 18:11:16 +00001724
Ted Kremenek94c96982009-03-03 22:06:47 +00001725 if (isa<Loc>(V)) {
1726 if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(&V)) {
Ted Kremenek070a8252008-07-09 18:11:16 +00001727 if (GetArgE(Summ, idx) == DoNothingByRef)
1728 continue;
1729
1730 // Invalidate the value of the variable passed by reference.
Ted Kremenek8c5633e2008-07-03 23:26:32 +00001731
1732 // FIXME: Either this logic should also be replicated in GRSimpleVals
1733 // or should be pulled into a separate "constraint engine."
Ted Kremenek070a8252008-07-09 18:11:16 +00001734
Ted Kremenek8c5633e2008-07-03 23:26:32 +00001735 // FIXME: We can have collisions on the conjured symbol if the
1736 // expression *I also creates conjured symbols. We probably want
1737 // to identify conjured symbols by an expression pair: the enclosing
1738 // expression (the context) and the expression itself. This should
Ted Kremenek070a8252008-07-09 18:11:16 +00001739 // disambiguate conjured symbols.
Ted Kremenek9e240492008-10-04 05:50:14 +00001740
Ted Kremenek993f1c72008-10-17 20:28:54 +00001741 const TypedRegion* R = dyn_cast<TypedRegion>(MR->getRegion());
Ted Kremenek90b32362008-12-17 19:42:34 +00001742
Ted Kremenek0312c0e2009-03-01 05:44:08 +00001743 // Blast through TypedViewRegions to get the original region type.
Ted Kremenek90b32362008-12-17 19:42:34 +00001744 while (R) {
Ted Kremenek0312c0e2009-03-01 05:44:08 +00001745 const TypedViewRegion* ATR = dyn_cast<TypedViewRegion>(R);
Ted Kremenek90b32362008-12-17 19:42:34 +00001746 if (!ATR) break;
1747 R = dyn_cast<TypedRegion>(ATR->getSuperRegion());
1748 }
1749
Ted Kremenekd104a092009-03-04 22:56:43 +00001750 if (R) {
Ted Kremenek40e86d92008-12-18 23:34:57 +00001751 // Is the invalidated variable something that we were tracking?
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00001752 SymbolRef Sym = state.GetSValAsScalarOrLoc(R).getAsLocSymbol();
Ted Kremenek40e86d92008-12-18 23:34:57 +00001753
Ted Kremenekd104a092009-03-04 22:56:43 +00001754 // Remove any existing reference-count binding.
Ted Kremeneke0e4ebf2009-03-26 03:35:11 +00001755 if (Sym) state = state.remove<RefBindings>(Sym);
Ted Kremenek9e240492008-10-04 05:50:14 +00001756
Ted Kremenekd104a092009-03-04 22:56:43 +00001757 if (R->isBoundable(Ctx)) {
1758 // Set the value of the variable to be a conjured symbol.
1759 unsigned Count = Builder.getCurrentBlockCount();
1760 QualType T = R->getRValueType(Ctx);
1761
Zhongxing Xu51ae7902009-04-09 06:03:54 +00001762 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())){
Zhongxing Xu9e82acb2009-04-09 06:18:05 +00001763 SVal V = SVal::GetConjuredSymbolVal(Eng.getSymbolManager(),
Zhongxing Xufe1635b2009-04-09 06:30:17 +00001764 Eng.getStoreManager().getRegionManager(), *I, T, Count);
Zhongxing Xu51ae7902009-04-09 06:03:54 +00001765 state = state.BindLoc(Loc::MakeVal(R), V);
Ted Kremenekd104a092009-03-04 22:56:43 +00001766 }
1767 else if (const RecordType *RT = T->getAsStructureType()) {
1768 // Handle structs in a not so awesome way. Here we just
1769 // eagerly bind new symbols to the fields. In reality we
1770 // should have the store manager handle this. The idea is just
1771 // to prototype some basic functionality here. All of this logic
1772 // should one day soon just go away.
1773 const RecordDecl *RD = RT->getDecl()->getDefinition(Ctx);
1774
1775 // No record definition. There is nothing we can do.
1776 if (!RD)
1777 continue;
1778
1779 MemRegionManager &MRMgr = state.getManager().getRegionManager();
1780
1781 // Iterate through the fields and construct new symbols.
1782 for (RecordDecl::field_iterator FI=RD->field_begin(),
1783 FE=RD->field_end(); FI!=FE; ++FI) {
1784
1785 // For now just handle scalar fields.
1786 FieldDecl *FD = *FI;
1787 QualType FT = FD->getType();
1788
1789 if (Loc::IsLocType(FT) ||
1790 (FT->isIntegerType() && FT->isScalarType())) {
1791
Ted Kremenekd104a092009-03-04 22:56:43 +00001792 const FieldRegion* FR = MRMgr.getFieldRegion(FD, R);
Zhongxing Xu6782f752009-04-09 06:32:20 +00001793
1794 SVal V = SVal::GetConjuredSymbolVal(Eng.getSymbolManager(),
1795 Eng.getStoreManager().getRegionManager(), *I, FT, Count);
1796
1797 state = state.BindLoc(Loc::MakeVal(FR), V);
Ted Kremenekd104a092009-03-04 22:56:43 +00001798 }
1799 }
1800 }
1801 else {
1802 // Just blast away other values.
1803 state = state.BindLoc(*MR, UnknownVal());
1804 }
Ted Kremenekfd301942008-10-17 22:23:12 +00001805 }
Ted Kremenek9e240492008-10-04 05:50:14 +00001806 }
1807 else
Ted Kremeneka441b7e2008-11-12 19:22:09 +00001808 state = state.BindLoc(*MR, UnknownVal());
Ted Kremenek8c5633e2008-07-03 23:26:32 +00001809 }
1810 else {
1811 // Nuke all other arguments passed by reference.
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001812 state = state.Unbind(cast<Loc>(V));
Ted Kremenek8c5633e2008-07-03 23:26:32 +00001813 }
Ted Kremenekb8873552008-04-11 20:51:02 +00001814 }
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001815 else if (isa<nonloc::LocAsInteger>(V))
1816 state = state.Unbind(cast<nonloc::LocAsInteger>(V).getLoc());
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001817 }
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001818
Ted Kremenek553cf182008-06-25 21:21:56 +00001819 // Evaluate the effect on the message receiver.
Ted Kremenek14993892008-05-06 02:41:27 +00001820 if (!ErrorExpr && Receiver) {
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00001821 SymbolRef Sym = state.GetSValAsScalarOrLoc(Receiver).getAsLocSymbol();
Ted Kremeneke0e4ebf2009-03-26 03:35:11 +00001822 if (Sym) {
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001823 if (const RefVal* T = state.get<RefBindings>(Sym)) {
1824 state = Update(state, Sym, *T, GetReceiverE(Summ), hasErr);
1825 if (hasErr) {
Ted Kremenek14993892008-05-06 02:41:27 +00001826 ErrorExpr = Receiver;
Ted Kremeneke8fdc832008-07-07 16:21:19 +00001827 ErrorSym = Sym;
Ted Kremenek14993892008-05-06 02:41:27 +00001828 }
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001829 }
Ted Kremenek14993892008-05-06 02:41:27 +00001830 }
1831 }
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001832
Ted Kremenek553cf182008-06-25 21:21:56 +00001833 // Process any errors.
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001834 if (hasErr) {
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001835 ProcessNonLeakError(Dst, Builder, Ex, ErrorExpr, Pred, state,
Ted Kremenek8dd56462008-04-18 03:39:05 +00001836 hasErr, ErrorSym);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001837 return;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001838 }
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001839
Ted Kremenek70a733e2008-07-18 17:24:20 +00001840 // Consult the summary for the return value.
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001841 RetEffect RE = GetRetEffect(Summ);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001842
1843 switch (RE.getKind()) {
1844 default:
1845 assert (false && "Unhandled RetEffect."); break;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001846
Ted Kremenekfd301942008-10-17 22:23:12 +00001847 case RetEffect::NoRet: {
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001848
Ted Kremenekf9561e52008-04-11 20:23:24 +00001849 // Make up a symbol for the return value (not reference counted).
Ted Kremenekb8873552008-04-11 20:51:02 +00001850 // FIXME: This is basically copy-and-paste from GRSimpleVals. We
1851 // should compose behavior, not copy it.
Ted Kremenekf9561e52008-04-11 20:23:24 +00001852
Ted Kremenekfd301942008-10-17 22:23:12 +00001853 // FIXME: We eventually should handle structs and other compound types
1854 // that are returned by value.
1855
1856 QualType T = Ex->getType();
1857
Ted Kremenek062e2f92008-11-13 06:10:40 +00001858 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())) {
Ted Kremenekf9561e52008-04-11 20:23:24 +00001859 unsigned Count = Builder.getCurrentBlockCount();
Zhongxing Xubd41db92009-04-09 06:35:30 +00001860 SVal X = SVal::GetConjuredSymbolVal(Eng.getSymbolManager(),
1861 Eng.getStoreManager().getRegionManager(), Ex, T, Count);
Ted Kremeneka441b7e2008-11-12 19:22:09 +00001862 state = state.BindExpr(Ex, X, false);
Ted Kremenekf9561e52008-04-11 20:23:24 +00001863 }
1864
Ted Kremenek940b1d82008-04-10 23:44:06 +00001865 break;
Ted Kremenekfd301942008-10-17 22:23:12 +00001866 }
Ted Kremenek940b1d82008-04-10 23:44:06 +00001867
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001868 case RetEffect::Alias: {
Ted Kremenek553cf182008-06-25 21:21:56 +00001869 unsigned idx = RE.getIndex();
Ted Kremenek55499762008-06-17 02:43:46 +00001870 assert (arg_end >= arg_beg);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001871 assert (idx < (unsigned) (arg_end - arg_beg));
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00001872 SVal V = state.GetSValAsScalarOrLoc(*(arg_beg+idx));
Ted Kremeneka441b7e2008-11-12 19:22:09 +00001873 state = state.BindExpr(Ex, V, false);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001874 break;
1875 }
1876
Ted Kremenek14993892008-05-06 02:41:27 +00001877 case RetEffect::ReceiverAlias: {
1878 assert (Receiver);
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00001879 SVal V = state.GetSValAsScalarOrLoc(Receiver);
Ted Kremeneka441b7e2008-11-12 19:22:09 +00001880 state = state.BindExpr(Ex, V, false);
Ted Kremenek14993892008-05-06 02:41:27 +00001881 break;
1882 }
1883
Ted Kremeneka7344702008-06-23 18:02:52 +00001884 case RetEffect::OwnedAllocatedSymbol:
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001885 case RetEffect::OwnedSymbol: {
1886 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenek044b6f02009-04-09 16:13:17 +00001887 ValueManager &ValMgr = Eng.getValueManager();
1888 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
1889 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
1890 state = state.set<RefBindings>(Sym, RefVal::makeOwned(RE.getObjKind(),
1891 RetT));
1892 state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenek25d01ba2009-03-09 22:46:49 +00001893
1894 // FIXME: Add a flag to the checker where allocations are assumed to
1895 // *not fail.
1896#if 0
Ted Kremenekb2bf7cd2009-01-28 22:27:59 +00001897 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) {
1898 bool isFeasible;
1899 state = state.Assume(loc::SymbolVal(Sym), true, isFeasible);
1900 assert(isFeasible && "Cannot assume fresh symbol is non-null.");
1901 }
Ted Kremenek25d01ba2009-03-09 22:46:49 +00001902#endif
Ted Kremeneka7344702008-06-23 18:02:52 +00001903
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001904 break;
1905 }
1906
1907 case RetEffect::NotOwnedSymbol: {
1908 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenek044b6f02009-04-09 16:13:17 +00001909 ValueManager &ValMgr = Eng.getValueManager();
1910 SymbolRef Sym = ValMgr.getConjuredSymbol(Ex, Count);
1911 QualType RetT = GetReturnType(Ex, ValMgr.getContext());
1912 state = state.set<RefBindings>(Sym, RefVal::makeNotOwned(RE.getObjKind(),
1913 RetT));
1914 state = state.BindExpr(Ex, ValMgr.makeRegionVal(Sym), false);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001915 break;
1916 }
1917 }
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001918
Ted Kremenekf5b34b12009-02-18 02:00:25 +00001919 // Generate a sink node if we are at the end of a path.
1920 GRExprEngine::NodeTy *NewNode =
1921 IsEndPath(Summ) ? Builder.MakeSinkNode(Dst, Ex, Pred, state)
1922 : Builder.MakeNode(Dst, Ex, Pred, state);
1923
1924 // Annotate the edge with summary we used.
1925 // FIXME: This assumes that we always use the same summary when generating
1926 // this node.
1927 if (NewNode) SummaryLog[NewNode] = Summ;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001928}
1929
1930
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001931void CFRefCount::EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001932 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001933 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001934 CallExpr* CE, SVal L,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001935 ExplodedNode<GRState>* Pred) {
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001936
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001937 RetainSummary* Summ = !isa<loc::FuncVal>(L) ? 0
1938 : Summaries.getSummary(cast<loc::FuncVal>(L).getDecl());
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001939
1940 EvalSummary(Dst, Eng, Builder, CE, 0, Summ,
1941 CE->arg_begin(), CE->arg_end(), Pred);
Ted Kremenek2fff37e2008-03-06 00:08:09 +00001942}
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001943
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001944void CFRefCount::EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek85348202008-04-15 23:44:31 +00001945 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001946 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek85348202008-04-15 23:44:31 +00001947 ObjCMessageExpr* ME,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001948 ExplodedNode<GRState>* Pred) {
Ted Kremenekb3095252008-05-06 04:20:12 +00001949 RetainSummary* Summ;
Ted Kremenek9040c652008-05-01 21:31:50 +00001950
Ted Kremenek553cf182008-06-25 21:21:56 +00001951 if (Expr* Receiver = ME->getReceiver()) {
1952 // We need the type-information of the tracked receiver object
1953 // Retrieve it from the state.
1954 ObjCInterfaceDecl* ID = 0;
1955
1956 // FIXME: Wouldn't it be great if this code could be reduced? It's just
1957 // a chain of lookups.
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001958 const GRState* St = Builder.GetState(Pred);
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00001959 SVal V = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
Ted Kremenek553cf182008-06-25 21:21:56 +00001960
Ted Kremenek94c96982009-03-03 22:06:47 +00001961 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremeneke0e4ebf2009-03-26 03:35:11 +00001962 if (Sym) {
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001963 if (const RefVal* T = St->get<RefBindings>(Sym)) {
Ted Kremeneke8fdc832008-07-07 16:21:19 +00001964 QualType Ty = T->getType();
Ted Kremenek553cf182008-06-25 21:21:56 +00001965
1966 if (const PointerType* PT = Ty->getAsPointerType()) {
1967 QualType PointeeTy = PT->getPointeeType();
1968
1969 if (ObjCInterfaceType* IT = dyn_cast<ObjCInterfaceType>(PointeeTy))
1970 ID = IT->getDecl();
1971 }
1972 }
1973 }
1974
1975 Summ = Summaries.getMethodSummary(ME, ID);
Ted Kremenekf9790ae2008-10-24 20:32:50 +00001976
Ted Kremenek896cd9d2008-10-23 01:56:15 +00001977 // Special-case: are we sending a mesage to "self"?
1978 // This is a hack. When we have full-IP this should be removed.
1979 if (!Summ) {
1980 ObjCMethodDecl* MD =
1981 dyn_cast<ObjCMethodDecl>(&Eng.getGraph().getCodeDecl());
1982
1983 if (MD) {
1984 if (Expr* Receiver = ME->getReceiver()) {
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00001985 SVal X = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
Ted Kremenek896cd9d2008-10-23 01:56:15 +00001986 if (loc::MemRegionVal* L = dyn_cast<loc::MemRegionVal>(&X))
Ted Kremenekf9790ae2008-10-24 20:32:50 +00001987 if (L->getRegion() == Eng.getStateManager().getSelfRegion(St)) {
1988 // Create a summmary where all of the arguments "StopTracking".
1989 Summ = Summaries.getPersistentSummary(RetEffect::MakeNoRet(),
1990 DoNothing,
1991 StopTracking);
1992 }
Ted Kremenek896cd9d2008-10-23 01:56:15 +00001993 }
1994 }
1995 }
Ted Kremenek553cf182008-06-25 21:21:56 +00001996 }
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001997 else
Ted Kremenek1f180c32008-06-23 22:21:20 +00001998 Summ = Summaries.getClassMethodSummary(ME->getClassName(),
1999 ME->getSelector());
Ted Kremenek9ed18e62008-04-16 04:28:53 +00002000
Ted Kremenekb3095252008-05-06 04:20:12 +00002001 EvalSummary(Dst, Eng, Builder, ME, ME->getReceiver(), Summ,
2002 ME->arg_begin(), ME->arg_end(), Pred);
Ted Kremenek85348202008-04-15 23:44:31 +00002003}
Ted Kremenek5216ad72009-02-14 03:16:10 +00002004
2005namespace {
2006class VISIBILITY_HIDDEN StopTrackingCallback : public SymbolVisitor {
2007 GRStateRef state;
2008public:
2009 StopTrackingCallback(GRStateRef st) : state(st) {}
2010 GRStateRef getState() { return state; }
2011
2012 bool VisitSymbol(SymbolRef sym) {
2013 state = state.remove<RefBindings>(sym);
2014 return true;
2015 }
Ted Kremenekb3095252008-05-06 04:20:12 +00002016
Ted Kremenek5216ad72009-02-14 03:16:10 +00002017 const GRState* getState() const { return state.getState(); }
2018};
2019} // end anonymous namespace
2020
2021
Ted Kremenek41573eb2009-02-14 01:43:44 +00002022void CFRefCount::EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val) {
Ted Kremenek41573eb2009-02-14 01:43:44 +00002023 // Are we storing to something that causes the value to "escape"?
Ted Kremenek13922612008-04-16 20:40:59 +00002024 bool escapes = false;
2025
Ted Kremeneka496d162008-10-18 03:49:51 +00002026 // A value escapes in three possible cases (this may change):
2027 //
2028 // (1) we are binding to something that is not a memory region.
2029 // (2) we are binding to a memregion that does not have stack storage
2030 // (3) we are binding to a memregion with stack storage that the store
Ted Kremenek41573eb2009-02-14 01:43:44 +00002031 // does not understand.
Ted Kremenek41573eb2009-02-14 01:43:44 +00002032 GRStateRef state = B.getState();
Ted Kremeneka496d162008-10-18 03:49:51 +00002033
Ted Kremenek41573eb2009-02-14 01:43:44 +00002034 if (!isa<loc::MemRegionVal>(location))
Ted Kremenek13922612008-04-16 20:40:59 +00002035 escapes = true;
Ted Kremenek9e240492008-10-04 05:50:14 +00002036 else {
Ted Kremenek41573eb2009-02-14 01:43:44 +00002037 const MemRegion* R = cast<loc::MemRegionVal>(location).getRegion();
2038 escapes = !B.getStateManager().hasStackStorage(R);
Ted Kremeneka496d162008-10-18 03:49:51 +00002039
2040 if (!escapes) {
2041 // To test (3), generate a new state with the binding removed. If it is
2042 // the same state, then it escapes (since the store cannot represent
2043 // the binding).
Ted Kremenek41573eb2009-02-14 01:43:44 +00002044 escapes = (state == (state.BindLoc(cast<Loc>(location), UnknownVal())));
Ted Kremeneka496d162008-10-18 03:49:51 +00002045 }
Ted Kremenek9e240492008-10-04 05:50:14 +00002046 }
Ted Kremenek41573eb2009-02-14 01:43:44 +00002047
Ted Kremenek5216ad72009-02-14 03:16:10 +00002048 // If our store can represent the binding and we aren't storing to something
2049 // that doesn't have local storage then just return and have the simulation
2050 // state continue as is.
2051 if (!escapes)
2052 return;
Ted Kremeneka496d162008-10-18 03:49:51 +00002053
Ted Kremenek5216ad72009-02-14 03:16:10 +00002054 // Otherwise, find all symbols referenced by 'val' that we are tracking
2055 // and stop tracking them.
2056 B.MakeNode(state.scanReachableSymbols<StopTrackingCallback>(val).getState());
Ted Kremenekdb863712008-04-16 22:32:20 +00002057}
2058
Ted Kremenekf9790ae2008-10-24 20:32:50 +00002059std::pair<GRStateRef,bool>
2060CFRefCount::HandleSymbolDeath(GRStateManager& VMgr,
2061 const GRState* St, const Decl* CD,
Ted Kremenek2dabd432008-12-05 02:27:51 +00002062 SymbolRef sid,
Ted Kremenekf9790ae2008-10-24 20:32:50 +00002063 RefVal V, bool& hasLeak) {
Ted Kremenekdb863712008-04-16 22:32:20 +00002064
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002065 GRStateRef state(St, VMgr);
Sanjiv Gupta31fc07d2008-10-31 09:52:39 +00002066 assert ((!V.isReturnedOwned() || CD) &&
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00002067 "CodeDecl must be available for reporting ReturnOwned errors.");
Ted Kremenek896cd9d2008-10-23 01:56:15 +00002068
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00002069 if (V.isReturnedOwned() && V.getCount() == 0)
2070 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
Chris Lattner077bf5e2008-11-24 03:33:13 +00002071 std::string s = MD->getSelector().getAsString();
Ted Kremenek4c79e552008-11-05 16:54:44 +00002072 if (!followsReturnRule(s.c_str())) {
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00002073 hasLeak = true;
Ted Kremenekf9790ae2008-10-24 20:32:50 +00002074 state = state.set<RefBindings>(sid, V ^ RefVal::ErrorLeakReturned);
2075 return std::make_pair(state, true);
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00002076 }
2077 }
Ted Kremenek896cd9d2008-10-23 01:56:15 +00002078
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00002079 // All other cases.
2080
2081 hasLeak = V.isOwned() ||
2082 ((V.isNotOwned() || V.isReturnedOwned()) && V.getCount() > 0);
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002083
Ted Kremenekdb863712008-04-16 22:32:20 +00002084 if (!hasLeak)
Ted Kremenekf9790ae2008-10-24 20:32:50 +00002085 return std::make_pair(state.remove<RefBindings>(sid), false);
Ted Kremenekdb863712008-04-16 22:32:20 +00002086
Ted Kremenekf9790ae2008-10-24 20:32:50 +00002087 return std::make_pair(state.set<RefBindings>(sid, V ^ RefVal::ErrorLeak),
2088 false);
Ted Kremenekdb863712008-04-16 22:32:20 +00002089}
2090
Ted Kremenek652adc62008-04-24 23:57:27 +00002091
Ted Kremeneke7bd9c22008-04-11 22:25:11 +00002092
Ted Kremenek652adc62008-04-24 23:57:27 +00002093// Dead symbols.
2094
Ted Kremenekcf701772009-02-05 06:50:21 +00002095
Ted Kremenek652adc62008-04-24 23:57:27 +00002096
Ted Kremenek4fd88972008-04-17 18:12:53 +00002097 // Return statements.
2098
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002099void CFRefCount::EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4fd88972008-04-17 18:12:53 +00002100 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002101 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4fd88972008-04-17 18:12:53 +00002102 ReturnStmt* S,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002103 ExplodedNode<GRState>* Pred) {
Ted Kremenek4fd88972008-04-17 18:12:53 +00002104
2105 Expr* RetE = S->getRetValue();
Ted Kremenek94c96982009-03-03 22:06:47 +00002106 if (!RetE)
Ted Kremenek4fd88972008-04-17 18:12:53 +00002107 return;
2108
Ted Kremenek94c96982009-03-03 22:06:47 +00002109 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00002110 SymbolRef Sym = state.GetSValAsScalarOrLoc(RetE).getAsLocSymbol();
Ted Kremenek94c96982009-03-03 22:06:47 +00002111
Ted Kremeneke0e4ebf2009-03-26 03:35:11 +00002112 if (!Sym)
Ted Kremenek94c96982009-03-03 22:06:47 +00002113 return;
2114
Ted Kremenek4fd88972008-04-17 18:12:53 +00002115 // Get the reference count binding (if any).
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002116 const RefVal* T = state.get<RefBindings>(Sym);
Ted Kremenek4fd88972008-04-17 18:12:53 +00002117
2118 if (!T)
2119 return;
2120
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002121 // Change the reference count.
Ted Kremeneke8fdc832008-07-07 16:21:19 +00002122 RefVal X = *T;
Ted Kremenek4fd88972008-04-17 18:12:53 +00002123
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002124 switch (X.getKind()) {
Ted Kremenek4fd88972008-04-17 18:12:53 +00002125 case RefVal::Owned: {
2126 unsigned cnt = X.getCount();
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00002127 assert (cnt > 0);
2128 X = RefVal::makeReturnedOwned(cnt - 1);
Ted Kremenek4fd88972008-04-17 18:12:53 +00002129 break;
2130 }
2131
2132 case RefVal::NotOwned: {
2133 unsigned cnt = X.getCount();
2134 X = cnt ? RefVal::makeReturnedOwned(cnt - 1)
2135 : RefVal::makeReturnedNotOwned();
2136 break;
2137 }
2138
2139 default:
Ted Kremenek4fd88972008-04-17 18:12:53 +00002140 return;
2141 }
2142
2143 // Update the binding.
Ted Kremenekb9d17f92008-08-17 03:20:02 +00002144 state = state.set<RefBindings>(Sym, X);
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002145 Builder.MakeNode(Dst, S, Pred, state);
Ted Kremenek4fd88972008-04-17 18:12:53 +00002146}
2147
Ted Kremenekcb612922008-04-18 19:23:43 +00002148// Assumptions.
2149
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002150const GRState* CFRefCount::EvalAssume(GRStateManager& VMgr,
2151 const GRState* St,
Zhongxing Xu1c96b242008-10-17 05:57:07 +00002152 SVal Cond, bool Assumption,
Ted Kremenek4323a572008-07-10 22:03:41 +00002153 bool& isFeasible) {
Ted Kremenekcb612922008-04-18 19:23:43 +00002154
2155 // FIXME: We may add to the interface of EvalAssume the list of symbols
2156 // whose assumptions have changed. For now we just iterate through the
2157 // bindings and check if any of the tracked symbols are NULL. This isn't
2158 // too bad since the number of symbols we will track in practice are
2159 // probably small and EvalAssume is only called at branches and a few
2160 // other places.
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002161 RefBindings B = St->get<RefBindings>();
Ted Kremenekcb612922008-04-18 19:23:43 +00002162
2163 if (B.isEmpty())
2164 return St;
2165
2166 bool changed = false;
Ted Kremenekb9d17f92008-08-17 03:20:02 +00002167
2168 GRStateRef state(St, VMgr);
2169 RefBindings::Factory& RefBFactory = state.get_context<RefBindings>();
Ted Kremenekcb612922008-04-18 19:23:43 +00002170
2171 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
Ted Kremenekcb612922008-04-18 19:23:43 +00002172 // Check if the symbol is null (or equal to any constant).
2173 // If this is the case, stop tracking the symbol.
Zhongxing Xu39cfed32008-08-29 14:52:36 +00002174 if (VMgr.getSymVal(St, I.getKey())) {
Ted Kremenekcb612922008-04-18 19:23:43 +00002175 changed = true;
2176 B = RefBFactory.Remove(B, I.getKey());
2177 }
2178 }
2179
Ted Kremenekb9d17f92008-08-17 03:20:02 +00002180 if (changed)
2181 state = state.set<RefBindings>(B);
Ted Kremenekcb612922008-04-18 19:23:43 +00002182
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002183 return state;
Ted Kremenekcb612922008-04-18 19:23:43 +00002184}
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00002185
Ted Kremenek4d3957d2009-02-24 19:15:11 +00002186GRStateRef CFRefCount::Update(GRStateRef state, SymbolRef sym,
2187 RefVal V, ArgEffect E,
2188 RefVal::Kind& hasErr) {
Ted Kremenek1c512f52009-02-18 18:54:33 +00002189
2190 // In GC mode [... release] and [... retain] do nothing.
2191 switch (E) {
2192 default: break;
2193 case IncRefMsg: E = isGCEnabled() ? DoNothing : IncRef; break;
2194 case DecRefMsg: E = isGCEnabled() ? DoNothing : DecRef; break;
Ted Kremenek27019002009-02-18 21:57:45 +00002195 case MakeCollectable: E = isGCEnabled() ? DecRef : DoNothing; break;
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00002196 case NewAutoreleasePool: E = isGCEnabled() ? DoNothing :
2197 NewAutoreleasePool; break;
Ted Kremenek1c512f52009-02-18 18:54:33 +00002198 }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00002199
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00002200 // Handle all use-after-releases.
2201 if (!isGCEnabled() && V.getKind() == RefVal::Released) {
2202 V = V ^ RefVal::ErrorUseAfterRelease;
2203 hasErr = V.getKind();
2204 return state.set<RefBindings>(sym, V);
2205 }
2206
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002207 switch (E) {
2208 default:
2209 assert (false && "Unhandled CFRef transition.");
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00002210
2211 case Dealloc:
2212 // Any use of -dealloc in GC is *bad*.
2213 if (isGCEnabled()) {
2214 V = V ^ RefVal::ErrorDeallocGC;
2215 hasErr = V.getKind();
2216 break;
2217 }
2218
2219 switch (V.getKind()) {
2220 default:
2221 assert(false && "Invalid case.");
2222 case RefVal::Owned:
2223 // The object immediately transitions to the released state.
2224 V = V ^ RefVal::Released;
2225 V.clearCounts();
2226 return state.set<RefBindings>(sym, V);
2227 case RefVal::NotOwned:
2228 V = V ^ RefVal::ErrorDeallocNotOwned;
2229 hasErr = V.getKind();
2230 break;
2231 }
2232 break;
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00002233
Ted Kremenek35790732009-02-25 23:11:49 +00002234 case NewAutoreleasePool:
2235 assert(!isGCEnabled());
2236 return state.add<AutoreleaseStack>(sym);
2237
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00002238 case MayEscape:
2239 if (V.getKind() == RefVal::Owned) {
Ted Kremenek553cf182008-06-25 21:21:56 +00002240 V = V ^ RefVal::NotOwned;
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00002241 break;
2242 }
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00002243
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00002244 // Fall-through.
Ted Kremenek6c4becb2009-02-25 02:54:57 +00002245
Ted Kremenek070a8252008-07-09 18:11:16 +00002246 case DoNothingByRef:
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002247 case DoNothing:
Ted Kremenek4d3957d2009-02-24 19:15:11 +00002248 return state;
Ted Kremeneke19f4492008-06-30 16:57:41 +00002249
Ted Kremenekabf43972009-01-28 21:44:40 +00002250 case Autorelease:
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00002251 if (isGCEnabled())
2252 return state;
Ted Kremenek7037ab82009-03-20 17:34:15 +00002253
2254 // Update the autorelease counts.
2255 state = SendAutorelease(state, ARCountFactory, sym);
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00002256
2257 // Fall-through.
2258
Ted Kremenek14993892008-05-06 02:41:27 +00002259 case StopTracking:
Ted Kremenek4d3957d2009-02-24 19:15:11 +00002260 return state.remove<RefBindings>(sym);
Ted Kremenek9e476de2008-08-12 18:30:56 +00002261
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002262 case IncRef:
2263 switch (V.getKind()) {
2264 default:
2265 assert(false);
2266
2267 case RefVal::Owned:
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002268 case RefVal::NotOwned:
Ted Kremenek553cf182008-06-25 21:21:56 +00002269 V = V + 1;
Ted Kremenek9e476de2008-08-12 18:30:56 +00002270 break;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002271 case RefVal::Released:
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00002272 // Non-GC cases are handled above.
2273 assert(isGCEnabled());
2274 V = (V ^ RefVal::Owned) + 1;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002275 break;
Ted Kremenek9e476de2008-08-12 18:30:56 +00002276 }
Ted Kremenek940b1d82008-04-10 23:44:06 +00002277 break;
2278
Ted Kremenek553cf182008-06-25 21:21:56 +00002279 case SelfOwn:
2280 V = V ^ RefVal::NotOwned;
Ted Kremenek1c512f52009-02-18 18:54:33 +00002281 // Fall-through.
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002282 case DecRef:
2283 switch (V.getKind()) {
2284 default:
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00002285 // case 'RefVal::Released' handled above.
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002286 assert (false);
Ted Kremenek9e476de2008-08-12 18:30:56 +00002287
Ted Kremenek553cf182008-06-25 21:21:56 +00002288 case RefVal::Owned:
Ted Kremenekbb8c5aa2009-02-18 22:57:22 +00002289 assert(V.getCount() > 0);
2290 if (V.getCount() == 1) V = V ^ RefVal::Released;
2291 V = V - 1;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002292 break;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002293
Ted Kremenek553cf182008-06-25 21:21:56 +00002294 case RefVal::NotOwned:
2295 if (V.getCount() > 0)
2296 V = V - 1;
Ted Kremenek61b9f872008-04-10 23:09:18 +00002297 else {
Ted Kremenek553cf182008-06-25 21:21:56 +00002298 V = V ^ RefVal::ErrorReleaseNotOwned;
Ted Kremenek9ed18e62008-04-16 04:28:53 +00002299 hasErr = V.getKind();
Ted Kremenek9e476de2008-08-12 18:30:56 +00002300 }
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002301 break;
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00002302
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002303 case RefVal::Released:
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00002304 // Non-GC cases are handled above.
2305 assert(isGCEnabled());
Ted Kremenek553cf182008-06-25 21:21:56 +00002306 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek9ed18e62008-04-16 04:28:53 +00002307 hasErr = V.getKind();
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00002308 break;
Ted Kremenek9e476de2008-08-12 18:30:56 +00002309 }
Ted Kremenek940b1d82008-04-10 23:44:06 +00002310 break;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002311 }
Ted Kremenek4d3957d2009-02-24 19:15:11 +00002312 return state.set<RefBindings>(sym, V);
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00002313}
2314
Ted Kremenekfa34b332008-04-09 01:10:13 +00002315//===----------------------------------------------------------------------===//
Ted Kremenek05cbe1a2008-04-09 23:49:11 +00002316// Error reporting.
Ted Kremenekfa34b332008-04-09 01:10:13 +00002317//===----------------------------------------------------------------------===//
2318
Ted Kremenek8dd56462008-04-18 03:39:05 +00002319namespace {
2320
2321 //===-------------===//
2322 // Bug Descriptions. //
2323 //===-------------===//
2324
Ted Kremenekcf118d42009-02-04 23:49:09 +00002325 class VISIBILITY_HIDDEN CFRefBug : public BugType {
Ted Kremenek8dd56462008-04-18 03:39:05 +00002326 protected:
2327 CFRefCount& TF;
Ted Kremenekcf118d42009-02-04 23:49:09 +00002328
2329 CFRefBug(CFRefCount* tf, const char* name)
2330 : BugType(name, "Memory (Core Foundation/Objective-C)"), TF(*tf) {}
Ted Kremenek8dd56462008-04-18 03:39:05 +00002331 public:
Ted Kremenek072192b2008-04-30 23:47:44 +00002332
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00002333 CFRefCount& getTF() { return TF; }
Ted Kremenek789deac2008-05-05 23:16:31 +00002334 const CFRefCount& getTF() const { return TF; }
2335
Ted Kremenekcf118d42009-02-04 23:49:09 +00002336 // FIXME: Eventually remove.
2337 virtual const char* getDescription() const = 0;
2338
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00002339 virtual bool isLeak() const { return false; }
Ted Kremenek8dd56462008-04-18 03:39:05 +00002340 };
2341
2342 class VISIBILITY_HIDDEN UseAfterRelease : public CFRefBug {
2343 public:
Ted Kremenekcf118d42009-02-04 23:49:09 +00002344 UseAfterRelease(CFRefCount* tf)
Ted Kremenek9dab0ed2009-04-03 21:10:31 +00002345 : CFRefBug(tf, "Use-after-release") {}
Ted Kremenek8dd56462008-04-18 03:39:05 +00002346
Ted Kremenekcf118d42009-02-04 23:49:09 +00002347 const char* getDescription() const {
Ted Kremeneke1981162009-02-26 21:04:07 +00002348 return "Reference-counted object is used after it is released";
Ted Kremenekcf701772009-02-05 06:50:21 +00002349 }
Ted Kremenek8dd56462008-04-18 03:39:05 +00002350 };
2351
2352 class VISIBILITY_HIDDEN BadRelease : public CFRefBug {
2353 public:
Ted Kremenekcf118d42009-02-04 23:49:09 +00002354 BadRelease(CFRefCount* tf) : CFRefBug(tf, "bad release") {}
2355
2356 const char* getDescription() const {
Ted Kremenek8dd56462008-04-18 03:39:05 +00002357 return "Incorrect decrement of the reference count of a "
Ted Kremeneke1981162009-02-26 21:04:07 +00002358 "Core Foundation object ("
2359 "the object is not owned at this point by the caller)";
Ted Kremenek8dd56462008-04-18 03:39:05 +00002360 }
Ted Kremenek8dd56462008-04-18 03:39:05 +00002361 };
2362
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00002363 class VISIBILITY_HIDDEN DeallocGC : public CFRefBug {
2364 public:
2365 DeallocGC(CFRefCount *tf) : CFRefBug(tf,
2366 "-dealloc called while using GC") {}
2367
2368 const char *getDescription() const {
2369 return "-dealloc called while using GC";
2370 }
2371 };
2372
2373 class VISIBILITY_HIDDEN DeallocNotOwned : public CFRefBug {
2374 public:
2375 DeallocNotOwned(CFRefCount *tf) : CFRefBug(tf,
2376 "-dealloc sent to non-exclusively owned object") {}
2377
2378 const char *getDescription() const {
2379 return "-dealloc sent to object that may be referenced elsewhere";
2380 }
2381 };
2382
Ted Kremenek8dd56462008-04-18 03:39:05 +00002383 class VISIBILITY_HIDDEN Leak : public CFRefBug {
Ted Kremenekcf118d42009-02-04 23:49:09 +00002384 const bool isReturn;
2385 protected:
2386 Leak(CFRefCount* tf, const char* name, bool isRet)
2387 : CFRefBug(tf, name), isReturn(isRet) {}
Ted Kremenek8dd56462008-04-18 03:39:05 +00002388 public:
Ted Kremenek8dd56462008-04-18 03:39:05 +00002389
Ted Kremenekd3057212009-02-07 22:38:00 +00002390 const char* getDescription() const { return ""; }
Ted Kremenek3148eb42009-01-24 00:55:43 +00002391
Ted Kremeneke45e57f2009-02-05 00:38:00 +00002392 bool isLeak() const { return true; }
Ted Kremenek8dd56462008-04-18 03:39:05 +00002393 };
Ted Kremenekcf118d42009-02-04 23:49:09 +00002394
2395 class VISIBILITY_HIDDEN LeakAtReturn : public Leak {
2396 public:
2397 LeakAtReturn(CFRefCount* tf, const char* name)
2398 : Leak(tf, name, true) {}
2399 };
2400
2401 class VISIBILITY_HIDDEN LeakWithinFunction : public Leak {
2402 public:
2403 LeakWithinFunction(CFRefCount* tf, const char* name)
2404 : Leak(tf, name, false) {}
2405 };
Ted Kremenek8dd56462008-04-18 03:39:05 +00002406
2407 //===---------===//
2408 // Bug Reports. //
2409 //===---------===//
2410
2411 class VISIBILITY_HIDDEN CFRefReport : public RangedBugReport {
Ted Kremenek66d97062009-02-07 22:04:05 +00002412 protected:
Ted Kremenek2dabd432008-12-05 02:27:51 +00002413 SymbolRef Sym;
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002414 const CFRefCount &TF;
Ted Kremenek8dd56462008-04-18 03:39:05 +00002415 public:
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002416 CFRefReport(CFRefBug& D, const CFRefCount &tf,
2417 ExplodedNode<GRState> *n, SymbolRef sym)
2418 : RangedBugReport(D, D.getDescription(), n), Sym(sym), TF(tf) {}
Ted Kremenek8dd56462008-04-18 03:39:05 +00002419
2420 virtual ~CFRefReport() {}
2421
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00002422 CFRefBug& getBugType() {
2423 return (CFRefBug&) RangedBugReport::getBugType();
2424 }
2425 const CFRefBug& getBugType() const {
2426 return (const CFRefBug&) RangedBugReport::getBugType();
2427 }
2428
2429 virtual void getRanges(BugReporter& BR, const SourceRange*& beg,
2430 const SourceRange*& end) {
2431
Ted Kremeneke92c1b22008-05-02 20:53:50 +00002432 if (!getBugType().isLeak())
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00002433 RangedBugReport::getRanges(BR, beg, end);
Ted Kremenek9e476de2008-08-12 18:30:56 +00002434 else
2435 beg = end = 0;
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00002436 }
2437
Ted Kremenek2dabd432008-12-05 02:27:51 +00002438 SymbolRef getSymbol() const { return Sym; }
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002439
Ted Kremenek3148eb42009-01-24 00:55:43 +00002440 PathDiagnosticPiece* getEndPath(BugReporter& BR,
2441 const ExplodedNode<GRState>* N);
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00002442
Ted Kremenek3148eb42009-01-24 00:55:43 +00002443 std::pair<const char**,const char**> getExtraDescriptiveText();
Ted Kremenek8dd56462008-04-18 03:39:05 +00002444
Ted Kremenek3148eb42009-01-24 00:55:43 +00002445 PathDiagnosticPiece* VisitNode(const ExplodedNode<GRState>* N,
2446 const ExplodedNode<GRState>* PrevN,
2447 const ExplodedGraph<GRState>& G,
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002448 BugReporter& BR,
2449 NodeResolver& NR);
Ted Kremenek8dd56462008-04-18 03:39:05 +00002450 };
2451
Ted Kremenekcf118d42009-02-04 23:49:09 +00002452 class VISIBILITY_HIDDEN CFRefLeakReport : public CFRefReport {
Ted Kremeneke469fa02009-02-07 22:19:59 +00002453 SourceLocation AllocSite;
2454 const MemRegion* AllocBinding;
Ted Kremenekcf118d42009-02-04 23:49:09 +00002455 public:
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002456 CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2457 ExplodedNode<GRState> *n, SymbolRef sym,
Ted Kremenekd3057212009-02-07 22:38:00 +00002458 GRExprEngine& Eng);
Ted Kremenek66d97062009-02-07 22:04:05 +00002459
2460 PathDiagnosticPiece* getEndPath(BugReporter& BR,
2461 const ExplodedNode<GRState>* N);
2462
Ted Kremeneke469fa02009-02-07 22:19:59 +00002463 SourceLocation getLocation() const { return AllocSite; }
Ted Kremenekcf118d42009-02-04 23:49:09 +00002464 };
Ted Kremenek8dd56462008-04-18 03:39:05 +00002465} // end anonymous namespace
2466
Ted Kremenekcf118d42009-02-04 23:49:09 +00002467void CFRefCount::RegisterChecks(BugReporter& BR) {
Ted Kremenekcf701772009-02-05 06:50:21 +00002468 useAfterRelease = new UseAfterRelease(this);
2469 BR.Register(useAfterRelease);
2470
2471 releaseNotOwned = new BadRelease(this);
2472 BR.Register(releaseNotOwned);
Ted Kremenekcf118d42009-02-04 23:49:09 +00002473
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00002474 deallocGC = new DeallocGC(this);
2475 BR.Register(deallocGC);
2476
2477 deallocNotOwned = new DeallocNotOwned(this);
2478 BR.Register(deallocNotOwned);
2479
Ted Kremenekcf118d42009-02-04 23:49:09 +00002480 // First register "return" leaks.
2481 const char* name = 0;
2482
2483 if (isGCEnabled())
Ted Kremenek41884092009-04-02 02:40:45 +00002484 name = "Leak of returned object when using garbage collection";
Ted Kremenekcf118d42009-02-04 23:49:09 +00002485 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
Ted Kremenek41884092009-04-02 02:40:45 +00002486 name = "Leak of returned object when not using garbage collection (GC) in "
2487 "dual GC/non-GC code";
Ted Kremenekcf118d42009-02-04 23:49:09 +00002488 else {
2489 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
Ted Kremenek41884092009-04-02 02:40:45 +00002490 name = "Leak of returned object";
Ted Kremenekcf118d42009-02-04 23:49:09 +00002491 }
2492
Ted Kremenekcf701772009-02-05 06:50:21 +00002493 leakAtReturn = new LeakAtReturn(this, name);
2494 BR.Register(leakAtReturn);
Ted Kremenek8dd56462008-04-18 03:39:05 +00002495
Ted Kremenekcf118d42009-02-04 23:49:09 +00002496 // Second, register leaks within a function/method.
2497 if (isGCEnabled())
Ted Kremenek41884092009-04-02 02:40:45 +00002498 name = "Leak of object when using garbage collection";
Ted Kremenekcf118d42009-02-04 23:49:09 +00002499 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
Ted Kremenek41884092009-04-02 02:40:45 +00002500 name = "Leak of object when not using garbage collection (GC) in "
2501 "dual GC/non-GC code";
Ted Kremenekcf118d42009-02-04 23:49:09 +00002502 else {
2503 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
Ted Kremenek41884092009-04-02 02:40:45 +00002504 name = "Leak";
Ted Kremenekcf118d42009-02-04 23:49:09 +00002505 }
2506
Ted Kremenekcf701772009-02-05 06:50:21 +00002507 leakWithinFunction = new LeakWithinFunction(this, name);
2508 BR.Register(leakWithinFunction);
2509
2510 // Save the reference to the BugReporter.
2511 this->BR = &BR;
Ted Kremenekcf118d42009-02-04 23:49:09 +00002512}
Ted Kremenek072192b2008-04-30 23:47:44 +00002513
2514static const char* Msgs[] = {
Ted Kremeneke1981162009-02-26 21:04:07 +00002515 // GC only
2516 "Code is compiled to only use garbage collection",
2517 // No GC.
Ted Kremenek452c31e2009-03-05 00:12:45 +00002518 "Code is compiled to use reference counts",
Ted Kremeneke1981162009-02-26 21:04:07 +00002519 // Hybrid, with GC.
2520 "Code is compiled to use either garbage collection (GC) or reference counts"
2521 " (non-GC). The bug occurs with GC enabled",
2522 // Hybrid, without GC
2523 "Code is compiled to use either garbage collection (GC) or reference counts"
2524 " (non-GC). The bug occurs in non-GC mode"
Ted Kremenek072192b2008-04-30 23:47:44 +00002525};
2526
2527std::pair<const char**,const char**> CFRefReport::getExtraDescriptiveText() {
2528 CFRefCount& TF = static_cast<CFRefBug&>(getBugType()).getTF();
2529
2530 switch (TF.getLangOptions().getGCMode()) {
2531 default:
2532 assert(false);
Ted Kremenek31593ac2008-05-01 04:02:04 +00002533
2534 case LangOptions::GCOnly:
2535 assert (TF.isGCEnabled());
Ted Kremenek9e476de2008-08-12 18:30:56 +00002536 return std::make_pair(&Msgs[0], &Msgs[0]+1);
2537
Ted Kremenek072192b2008-04-30 23:47:44 +00002538 case LangOptions::NonGC:
2539 assert (!TF.isGCEnabled());
Ted Kremenek072192b2008-04-30 23:47:44 +00002540 return std::make_pair(&Msgs[1], &Msgs[1]+1);
2541
2542 case LangOptions::HybridGC:
2543 if (TF.isGCEnabled())
2544 return std::make_pair(&Msgs[2], &Msgs[2]+1);
2545 else
2546 return std::make_pair(&Msgs[3], &Msgs[3]+1);
2547 }
2548}
2549
Ted Kremenek27019002009-02-18 21:57:45 +00002550static inline bool contains(const llvm::SmallVectorImpl<ArgEffect>& V,
2551 ArgEffect X) {
2552 for (llvm::SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
2553 I!=E; ++I)
2554 if (*I == X) return true;
2555
2556 return false;
2557}
2558
Ted Kremenek3148eb42009-01-24 00:55:43 +00002559PathDiagnosticPiece* CFRefReport::VisitNode(const ExplodedNode<GRState>* N,
2560 const ExplodedNode<GRState>* PrevN,
2561 const ExplodedGraph<GRState>& G,
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002562 BugReporter& BR,
2563 NodeResolver& NR) {
Ted Kremenek8dd56462008-04-18 03:39:05 +00002564
Ted Kremenek611a15a2009-01-28 05:29:13 +00002565 // Check if the type state has changed.
2566 GRStateManager &StMgr = cast<GRBugReporter>(BR).getStateManager();
2567 GRStateRef PrevSt(PrevN->getState(), StMgr);
2568 GRStateRef CurrSt(N->getState(), StMgr);
Ted Kremenek20982802009-01-28 05:06:46 +00002569
Ted Kremenek611a15a2009-01-28 05:29:13 +00002570 const RefVal* CurrT = CurrSt.get<RefBindings>(Sym);
2571 if (!CurrT) return NULL;
2572
2573 const RefVal& CurrV = *CurrT;
2574 const RefVal* PrevT = PrevSt.get<RefBindings>(Sym);
Ted Kremenekce48e002008-05-05 17:53:17 +00002575
Ted Kremenek27019002009-02-18 21:57:45 +00002576 // Create a string buffer to constain all the useful things we want
2577 // to tell the user.
2578 std::string sbuf;
2579 llvm::raw_string_ostream os(sbuf);
2580
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002581 // This is the allocation site since the previous node had no bindings
2582 // for this symbol.
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002583 if (!PrevT) {
Ted Kremenekce48e002008-05-05 17:53:17 +00002584 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2585
Ted Kremenek5c1cd522009-01-28 05:15:02 +00002586 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2587 // Get the name of the callee (if it is available).
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00002588 SVal X = CurrSt.GetSValAsScalarOrLoc(CE->getCallee());
Ted Kremenek5c1cd522009-01-28 05:15:02 +00002589 if (loc::FuncVal* FV = dyn_cast<loc::FuncVal>(&X))
2590 os << "Call to function '" << FV->getDecl()->getNameAsString() <<'\'';
2591 else
Ted Kremeneka102c0c2009-01-28 06:01:42 +00002592 os << "function call";
Ted Kremenek5c1cd522009-01-28 05:15:02 +00002593 }
2594 else {
2595 assert (isa<ObjCMessageExpr>(S));
Ted Kremeneka102c0c2009-01-28 06:01:42 +00002596 os << "Method";
Ted Kremenekce48e002008-05-05 17:53:17 +00002597 }
Ted Kremenek5c1cd522009-01-28 05:15:02 +00002598
Ted Kremenek961b61d2009-01-28 06:06:36 +00002599 if (CurrV.getObjKind() == RetEffect::CF) {
2600 os << " returns a Core Foundation object with a ";
2601 }
2602 else {
2603 assert (CurrV.getObjKind() == RetEffect::ObjC);
2604 os << " returns an Objective-C object with a ";
2605 }
Ted Kremeneka102c0c2009-01-28 06:01:42 +00002606
Ted Kremenek23b8eaa2009-01-28 06:25:48 +00002607 if (CurrV.isOwned()) {
2608 os << "+1 retain count (owning reference).";
2609
2610 if (static_cast<CFRefBug&>(getBugType()).getTF().isGCEnabled()) {
2611 assert(CurrV.getObjKind() == RetEffect::CF);
2612 os << " "
2613 "Core Foundation objects are not automatically garbage collected.";
2614 }
2615 }
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002616 else {
2617 assert (CurrV.isNotOwned());
Ted Kremenek5c1cd522009-01-28 05:15:02 +00002618 os << "+0 retain count (non-owning reference).";
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002619 }
Ted Kremenekce48e002008-05-05 17:53:17 +00002620
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00002621 PathDiagnosticLocation Pos(S, BR.getContext().getSourceManager());
2622 return new PathDiagnosticEventPiece(Pos, os.str());
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002623 }
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002624
Ted Kremenek27019002009-02-18 21:57:45 +00002625 // Gather up the effects that were performed on the object at this
2626 // program point
2627 llvm::SmallVector<ArgEffect, 2> AEffects;
2628
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002629 if (const RetainSummary *Summ = TF.getSummaryOfNode(NR.getOriginalNode(N))) {
2630 // We only have summaries attached to nodes after evaluating CallExpr and
2631 // ObjCMessageExprs.
2632 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2633
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002634 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2635 // Iterate through the parameter expressions and see if the symbol
2636 // was ever passed as an argument.
2637 unsigned i = 0;
2638
2639 for (CallExpr::arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
2640 AI!=AE; ++AI, ++i) {
Ted Kremenek27019002009-02-18 21:57:45 +00002641
Ted Kremenek94c96982009-03-03 22:06:47 +00002642 // Retrieve the value of the argument. Is it the symbol
2643 // we are interested in?
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00002644 if (CurrSt.GetSValAsScalarOrLoc(*AI).getAsLocSymbol() != Sym)
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002645 continue;
Ted Kremenek94c96982009-03-03 22:06:47 +00002646
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002647 // We have an argument. Get the effect!
2648 AEffects.push_back(Summ->getArg(i));
Ted Kremenek79c140b2008-04-18 05:32:44 +00002649 }
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002650 }
2651 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
Ted Kremenek94c96982009-03-03 22:06:47 +00002652 if (Expr *receiver = ME->getReceiver())
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00002653 if (CurrSt.GetSValAsScalarOrLoc(receiver).getAsLocSymbol() == Sym) {
Ted Kremenek27019002009-02-18 21:57:45 +00002654 // The symbol we are tracking is the receiver.
2655 AEffects.push_back(Summ->getReceiverEffect());
2656 }
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002657 }
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002658 }
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002659
Ted Kremenek27019002009-02-18 21:57:45 +00002660 do {
2661 // Get the previous type state.
2662 RefVal PrevV = *PrevT;
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00002663
2664 // Specially handle -dealloc.
2665 if (!TF.isGCEnabled() && contains(AEffects, Dealloc)) {
2666 // Determine if the object's reference count was pushed to zero.
2667 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2668 // We may not have transitioned to 'release' if we hit an error.
2669 // This case is handled elsewhere.
2670 if (CurrV.getKind() == RefVal::Released) {
2671 assert(CurrV.getCount() == 0);
2672 os << "Object released by directly sending the '-dealloc' message";
2673 break;
2674 }
2675 }
Ted Kremenek27019002009-02-18 21:57:45 +00002676
2677 // Specially handle CFMakeCollectable and friends.
2678 if (contains(AEffects, MakeCollectable)) {
2679 // Get the name of the function.
2680 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2681 loc::FuncVal FV =
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00002682 cast<loc::FuncVal>(CurrSt.GetSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee()));
Ted Kremenek27019002009-02-18 21:57:45 +00002683 const std::string& FName = FV.getDecl()->getNameAsString();
2684
2685 if (TF.isGCEnabled()) {
2686 // Determine if the object's reference count was pushed to zero.
2687 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2688
2689 os << "In GC mode a call to '" << FName
2690 << "' decrements an object's retain count and registers the "
2691 "object with the garbage collector. ";
2692
Ted Kremenekbb8c5aa2009-02-18 22:57:22 +00002693 if (CurrV.getKind() == RefVal::Released) {
2694 assert(CurrV.getCount() == 0);
2695 os << "Since it now has a 0 retain count the object can be "
Ted Kremenek27019002009-02-18 21:57:45 +00002696 "automatically collected by the garbage collector.";
Ted Kremenekbb8c5aa2009-02-18 22:57:22 +00002697 }
Ted Kremenek27019002009-02-18 21:57:45 +00002698 else
2699 os << "An object must have a 0 retain count to be garbage collected. "
2700 "After this call its retain count is +" << CurrV.getCount()
2701 << '.';
2702 }
2703 else
2704 os << "When GC is not enabled a call to '" << FName
2705 << "' has no effect on its argument.";
2706
2707 // Nothing more to say.
2708 break;
2709 }
2710
2711 // Determine if the typestate has changed.
2712 if (!(PrevV == CurrV))
2713 switch (CurrV.getKind()) {
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002714 case RefVal::Owned:
2715 case RefVal::NotOwned:
2716
2717 if (PrevV.getCount() == CurrV.getCount())
2718 return 0;
2719
2720 if (PrevV.getCount() > CurrV.getCount())
2721 os << "Reference count decremented.";
2722 else
2723 os << "Reference count incremented.";
Ted Kremenekbb8c5aa2009-02-18 22:57:22 +00002724
Ted Kremeneke1981162009-02-26 21:04:07 +00002725 if (unsigned Count = CurrV.getCount())
2726 os << " The object now has a +" << Count << " retain count.";
Ted Kremenekbb8c5aa2009-02-18 22:57:22 +00002727
2728 if (PrevV.getKind() == RefVal::Released) {
2729 assert(TF.isGCEnabled() && CurrV.getCount() > 0);
2730 os << " The object is not eligible for garbage collection until the "
2731 "retain count reaches 0 again.";
2732 }
2733
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002734 break;
2735
2736 case RefVal::Released:
2737 os << "Object released.";
2738 break;
2739
2740 case RefVal::ReturnedOwned:
2741 os << "Object returned to caller as an owning reference (single retain "
2742 "count transferred to caller).";
2743 break;
2744
2745 case RefVal::ReturnedNotOwned:
2746 os << "Object returned to caller with a +0 (non-owning) retain count.";
2747 break;
2748
2749 default:
2750 return NULL;
Ted Kremenek27019002009-02-18 21:57:45 +00002751 }
2752
2753 // Emit any remaining diagnostics for the argument effects (if any).
2754 for (llvm::SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
2755 E=AEffects.end(); I != E; ++I) {
2756
2757 // A bunch of things have alternate behavior under GC.
2758 if (TF.isGCEnabled())
2759 switch (*I) {
2760 default: break;
2761 case Autorelease:
2762 os << "In GC mode an 'autorelease' has no effect.";
2763 continue;
2764 case IncRefMsg:
2765 os << "In GC mode the 'retain' message has no effect.";
2766 continue;
2767 case DecRefMsg:
2768 os << "In GC mode the 'release' message has no effect.";
2769 continue;
2770 }
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002771 }
Ted Kremenek27019002009-02-18 21:57:45 +00002772 } while(0);
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002773
2774 if (os.str().empty())
2775 return 0; // We have nothing to say!
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002776
2777 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00002778 PathDiagnosticLocation Pos(S, BR.getContext().getSourceManager());
Ted Kremenek1fbfd5b2009-03-06 23:58:11 +00002779 PathDiagnosticPiece* P = new PathDiagnosticEventPiece(Pos, os.str());
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002780
2781 // Add the range by scanning the children of the statement for any bindings
2782 // to Sym.
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002783 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I)
Ted Kremenek94c96982009-03-03 22:06:47 +00002784 if (Expr* Exp = dyn_cast_or_null<Expr>(*I))
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00002785 if (CurrSt.GetSValAsScalarOrLoc(Exp).getAsLocSymbol() == Sym) {
Ted Kremenek94c96982009-03-03 22:06:47 +00002786 P->addRange(Exp->getSourceRange());
2787 break;
2788 }
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002789
2790 return P;
Ted Kremenek8dd56462008-04-18 03:39:05 +00002791}
2792
Ted Kremenek9e240492008-10-04 05:50:14 +00002793namespace {
2794class VISIBILITY_HIDDEN FindUniqueBinding :
2795 public StoreManager::BindingsHandler {
Ted Kremenek2dabd432008-12-05 02:27:51 +00002796 SymbolRef Sym;
Ted Kremenekbe912242009-03-05 16:31:07 +00002797 const MemRegion* Binding;
Ted Kremenek9e240492008-10-04 05:50:14 +00002798 bool First;
2799
2800 public:
Ted Kremenek2dabd432008-12-05 02:27:51 +00002801 FindUniqueBinding(SymbolRef sym) : Sym(sym), Binding(0), First(true) {}
Ted Kremenek9e240492008-10-04 05:50:14 +00002802
Ted Kremenekbe912242009-03-05 16:31:07 +00002803 bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
2804 SVal val) {
Ted Kremeneke0e4ebf2009-03-26 03:35:11 +00002805
2806 SymbolRef SymV = val.getAsSymbol();
2807 if (!SymV || SymV != Sym)
Ted Kremenek9e240492008-10-04 05:50:14 +00002808 return true;
Ted Kremenek94c96982009-03-03 22:06:47 +00002809
Ted Kremenek9e240492008-10-04 05:50:14 +00002810 if (Binding) {
2811 First = false;
2812 return false;
2813 }
2814 else
2815 Binding = R;
2816
2817 return true;
2818 }
2819
2820 operator bool() { return First && Binding; }
Ted Kremenekbe912242009-03-05 16:31:07 +00002821 const MemRegion* getRegion() { return Binding; }
Ted Kremenek9e240492008-10-04 05:50:14 +00002822};
2823}
2824
Ted Kremenek3148eb42009-01-24 00:55:43 +00002825static std::pair<const ExplodedNode<GRState>*,const MemRegion*>
Ted Kremeneke469fa02009-02-07 22:19:59 +00002826GetAllocationSite(GRStateManager& StateMgr, const ExplodedNode<GRState>* N,
Ted Kremenek2dabd432008-12-05 02:27:51 +00002827 SymbolRef Sym) {
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002828
Ted Kremenek2bc39c62008-08-29 00:47:32 +00002829 // Find both first node that referred to the tracked symbol and the
2830 // memory location that value was store to.
Ted Kremenek3148eb42009-01-24 00:55:43 +00002831 const ExplodedNode<GRState>* Last = N;
2832 const MemRegion* FirstBinding = 0;
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002833
2834 while (N) {
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002835 const GRState* St = N->getState();
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002836 RefBindings B = St->get<RefBindings>();
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002837
Ted Kremeneke8fdc832008-07-07 16:21:19 +00002838 if (!B.lookup(Sym))
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002839 break;
Ted Kremenek2bc39c62008-08-29 00:47:32 +00002840
Ted Kremeneke469fa02009-02-07 22:19:59 +00002841 FindUniqueBinding FB(Sym);
2842 StateMgr.iterBindings(St, FB);
2843 if (FB) FirstBinding = FB.getRegion();
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002844
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002845 Last = N;
2846 N = N->pred_empty() ? NULL : *(N->pred_begin());
2847 }
2848
Ted Kremenek2bc39c62008-08-29 00:47:32 +00002849 return std::make_pair(Last, FirstBinding);
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002850}
Ted Kremeneka22cc2f2008-05-06 23:07:13 +00002851
Ted Kremenek3148eb42009-01-24 00:55:43 +00002852PathDiagnosticPiece*
2853CFRefReport::getEndPath(BugReporter& br, const ExplodedNode<GRState>* EndN) {
Ted Kremenek1aa44c72008-05-22 23:45:19 +00002854 // Tell the BugReporter to report cases when the tracked symbol is
2855 // assigned to different variables, etc.
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00002856 GRBugReporter& BR = cast<GRBugReporter>(br);
Ted Kremenekc0959972008-07-02 21:24:01 +00002857 cast<GRBugReporter>(BR).addNotableSymbol(Sym);
Ted Kremenek66d97062009-02-07 22:04:05 +00002858 return RangedBugReport::getEndPath(BR, EndN);
2859}
2860
2861PathDiagnosticPiece*
2862CFRefLeakReport::getEndPath(BugReporter& br, const ExplodedNode<GRState>* EndN){
2863
2864 GRBugReporter& BR = cast<GRBugReporter>(br);
2865 // Tell the BugReporter to report cases when the tracked symbol is
2866 // assigned to different variables, etc.
2867 cast<GRBugReporter>(BR).addNotableSymbol(Sym);
2868
2869 // We are reporting a leak. Walk up the graph to get to the first node where
2870 // the symbol appeared, and also get the first VarDecl that tracked object
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002871 // is stored to.
Ted Kremenek3148eb42009-01-24 00:55:43 +00002872 const ExplodedNode<GRState>* AllocNode = 0;
2873 const MemRegion* FirstBinding = 0;
Ted Kremenek2bc39c62008-08-29 00:47:32 +00002874
2875 llvm::tie(AllocNode, FirstBinding) =
Ted Kremeneke469fa02009-02-07 22:19:59 +00002876 GetAllocationSite(BR.getStateManager(), EndN, Sym);
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00002877
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002878 // Get the allocate site.
Ted Kremenek933c4222009-04-07 00:12:43 +00002879 assert(AllocNode);
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002880 Stmt* FirstStmt = cast<PostStmt>(AllocNode->getLocation()).getStmt();
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00002881
Ted Kremeneke28565b2008-05-05 18:50:19 +00002882 SourceManager& SMgr = BR.getContext().getSourceManager();
Chris Lattnerf7cf85b2009-01-16 07:36:28 +00002883 unsigned AllocLine =SMgr.getInstantiationLineNumber(FirstStmt->getLocStart());
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00002884
Ted Kremenek0b3c9a92009-04-07 04:54:20 +00002885 // Compute an actual location for the leak. Sometimes a leak doesn't
2886 // occur at an actual statement (e.g., transition between blocks; end
2887 // of function) so we need to walk the graph and compute a real location.
Ted Kremenek933c4222009-04-07 00:12:43 +00002888 const ExplodedNode<GRState>* LeakN = EndN;
2889 PathDiagnosticLocation L;
2890
2891 while (LeakN) {
2892 ProgramPoint P = LeakN->getLocation();
2893
2894 if (const PostStmt *PS = dyn_cast<PostStmt>(&P)) {
2895 L = PathDiagnosticLocation(PS->getStmt()->getLocStart(), SMgr);
2896 break;
2897 }
2898 else if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
2899 if (const Stmt* Term = BE->getSrc()->getTerminator()) {
2900 L = PathDiagnosticLocation(Term->getLocStart(), SMgr);
2901 break;
2902 }
2903 }
2904
Ted Kremenek933c4222009-04-07 00:12:43 +00002905 LeakN = LeakN->succ_empty() ? 0 : *(LeakN->succ_begin());
2906 }
2907
2908 if (!L.isValid()) {
2909 CompoundStmt *CS = BR.getStateManager().getCodeDecl().getBody();
2910 L = PathDiagnosticLocation(CS->getRBracLoc(), SMgr);
2911 }
2912
Ted Kremenekc9e3d862009-02-07 21:59:45 +00002913 std::string sbuf;
2914 llvm::raw_string_ostream os(sbuf);
Ted Kremeneke92c1b22008-05-02 20:53:50 +00002915
Ted Kremeneke28565b2008-05-05 18:50:19 +00002916 os << "Object allocated on line " << AllocLine;
Ted Kremeneke92c1b22008-05-02 20:53:50 +00002917
Ted Kremenek2bc39c62008-08-29 00:47:32 +00002918 if (FirstBinding)
Ted Kremenek9e240492008-10-04 05:50:14 +00002919 os << " and stored into '" << FirstBinding->getString() << '\'';
2920
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00002921 // Get the retain count.
2922 const RefVal* RV = EndN->getState()->get<RefBindings>(Sym);
2923
2924 if (RV->getKind() == RefVal::ErrorLeakReturned) {
Ted Kremenek04f9d462008-12-02 01:26:07 +00002925 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
2926 // ojbects. Only "copy", "alloc", "retain" and "new" transfer ownership
2927 // to the caller for NS objects.
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00002928 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(BR.getGraph().getCodeDecl());
2929 os << " is returned from a method whose name ('"
Chris Lattner077bf5e2008-11-24 03:33:13 +00002930 << MD.getSelector().getAsString()
Ted Kremenek234a4c22009-01-07 00:39:56 +00002931 << "') does not contain 'copy' or otherwise starts with"
Ted Kremenek9d1d5702008-10-24 21:22:44 +00002932 " 'new' or 'alloc'. This violates the naming convention rules given"
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00002933 " in the Memory Management Guide for Cocoa (object leaked).";
2934 }
2935 else
Ted Kremenek9d1d5702008-10-24 21:22:44 +00002936 os << " is no longer referenced after this point and has a retain count of"
2937 " +"
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00002938 << RV->getCount() << " (object leaked).";
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00002939
Ted Kremenek1fbfd5b2009-03-06 23:58:11 +00002940 return new PathDiagnosticEventPiece(L, os.str());
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00002941}
2942
Ted Kremenek989d5192008-04-17 23:43:50 +00002943
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002944CFRefLeakReport::CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2945 ExplodedNode<GRState> *n,
Ted Kremenekd3057212009-02-07 22:38:00 +00002946 SymbolRef sym, GRExprEngine& Eng)
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002947 : CFRefReport(D, tf, n, sym)
Ted Kremeneke469fa02009-02-07 22:19:59 +00002948{
2949
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002950 // Most bug reports are cached at the location where they occured.
2951 // With leaks, we want to unique them by the location where they were
Ted Kremeneke469fa02009-02-07 22:19:59 +00002952 // allocated, and only report a single path. To do this, we need to find
2953 // the allocation site of a piece of tracked memory, which we do via a
2954 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2955 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2956 // that all ancestor nodes that represent the allocation site have the
2957 // same SourceLocation.
2958 const ExplodedNode<GRState>* AllocNode = 0;
2959
2960 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding.
Ted Kremenekd3057212009-02-07 22:38:00 +00002961 GetAllocationSite(Eng.getStateManager(), getEndNode(), getSymbol());
Ted Kremeneke469fa02009-02-07 22:19:59 +00002962
Ted Kremeneke469fa02009-02-07 22:19:59 +00002963 // Get the SourceLocation for the allocation site.
Ted Kremenekd3057212009-02-07 22:38:00 +00002964 ProgramPoint P = AllocNode->getLocation();
Ted Kremeneke469fa02009-02-07 22:19:59 +00002965 AllocSite = cast<PostStmt>(P).getStmt()->getLocStart();
Ted Kremenekd3057212009-02-07 22:38:00 +00002966
2967 // Fill in the description of the bug.
2968 Description.clear();
2969 llvm::raw_string_ostream os(Description);
2970 SourceManager& SMgr = Eng.getContext().getSourceManager();
2971 unsigned AllocLine = SMgr.getInstantiationLineNumber(AllocSite);
Ted Kremenekc5c60002009-02-07 22:54:59 +00002972 os << "Potential leak of object allocated on line " << AllocLine;
2973
2974 // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2975 if (AllocBinding)
Ted Kremenekc2dcd892009-04-02 03:42:38 +00002976 os << " and stored into '" << AllocBinding->getString() << '\'';
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002977}
2978
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00002979//===----------------------------------------------------------------------===//
Ted Kremenekcf701772009-02-05 06:50:21 +00002980// Handle dead symbols and end-of-path.
2981//===----------------------------------------------------------------------===//
2982
2983void CFRefCount::EvalEndPath(GRExprEngine& Eng,
2984 GREndPathNodeBuilder<GRState>& Builder) {
2985
2986 const GRState* St = Builder.getState();
2987 RefBindings B = St->get<RefBindings>();
2988
2989 llvm::SmallVector<std::pair<SymbolRef, bool>, 10> Leaked;
2990 const Decl* CodeDecl = &Eng.getGraph().getCodeDecl();
2991
2992 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
2993 bool hasLeak = false;
2994
2995 std::pair<GRStateRef, bool> X =
Ted Kremenek94c96982009-03-03 22:06:47 +00002996 HandleSymbolDeath(Eng.getStateManager(), St, CodeDecl,
2997 (*I).first, (*I).second, hasLeak);
Ted Kremenekcf701772009-02-05 06:50:21 +00002998
2999 St = X.first;
3000 if (hasLeak) Leaked.push_back(std::make_pair((*I).first, X.second));
3001 }
3002
3003 if (Leaked.empty())
3004 return;
3005
3006 ExplodedNode<GRState>* N = Builder.MakeNode(St);
3007
3008 if (!N)
3009 return;
3010
3011 for (llvm::SmallVector<std::pair<SymbolRef,bool>, 10>::iterator
3012 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3013
3014 CFRefBug *BT = static_cast<CFRefBug*>(I->second ? leakAtReturn
3015 : leakWithinFunction);
3016 assert(BT && "BugType not initialized.");
Ted Kremeneka5770b92009-04-07 05:07:44 +00003017 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N, I->first, Eng);
Ted Kremenekcf701772009-02-05 06:50:21 +00003018 BR->EmitReport(report);
3019 }
3020}
3021
3022void CFRefCount::EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
3023 GRExprEngine& Eng,
3024 GRStmtNodeBuilder<GRState>& Builder,
3025 ExplodedNode<GRState>* Pred,
3026 Stmt* S,
3027 const GRState* St,
3028 SymbolReaper& SymReaper) {
3029
Ted Kremenek33b6f632009-02-19 23:47:02 +00003030 // FIXME: a lot of copy-and-paste from EvalEndPath. Refactor.
Ted Kremenekcf701772009-02-05 06:50:21 +00003031 RefBindings B = St->get<RefBindings>();
3032 llvm::SmallVector<std::pair<SymbolRef,bool>, 10> Leaked;
3033
3034 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3035 E = SymReaper.dead_end(); I != E; ++I) {
3036
3037 const RefVal* T = B.lookup(*I);
3038 if (!T) continue;
3039
3040 bool hasLeak = false;
3041
3042 std::pair<GRStateRef, bool> X
Ted Kremenek33b6f632009-02-19 23:47:02 +00003043 = HandleSymbolDeath(Eng.getStateManager(), St, 0, *I, *T, hasLeak);
Ted Kremenekcf701772009-02-05 06:50:21 +00003044
3045 St = X.first;
3046
3047 if (hasLeak)
3048 Leaked.push_back(std::make_pair(*I,X.second));
3049 }
3050
Ted Kremenek33b6f632009-02-19 23:47:02 +00003051 if (!Leaked.empty()) {
3052 // Create a new intermediate node representing the leak point. We
3053 // use a special program point that represents this checker-specific
3054 // transition. We use the address of RefBIndex as a unique tag for this
3055 // checker. We will create another node (if we don't cache out) that
3056 // removes the retain-count bindings from the state.
3057 // NOTE: We use 'generateNode' so that it does interplay with the
3058 // auto-transition logic.
3059 ExplodedNode<GRState>* N =
3060 Builder.generateNode(PostStmtCustom(S, &LeakProgramPointTag), St, Pred);
Ted Kremenekcf701772009-02-05 06:50:21 +00003061
Ted Kremenek33b6f632009-02-19 23:47:02 +00003062 if (!N)
3063 return;
3064
3065 // Generate the bug reports.
3066 for (llvm::SmallVectorImpl<std::pair<SymbolRef,bool> >::iterator
3067 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3068
3069 CFRefBug *BT = static_cast<CFRefBug*>(I->second ? leakAtReturn
3070 : leakWithinFunction);
3071 assert(BT && "BugType not initialized.");
Ted Kremenek46347352009-02-23 16:54:00 +00003072 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N,
3073 I->first, Eng);
Ted Kremenek33b6f632009-02-19 23:47:02 +00003074 BR->EmitReport(report);
3075 }
Ted Kremenekcf701772009-02-05 06:50:21 +00003076
Ted Kremenek33b6f632009-02-19 23:47:02 +00003077 Pred = N;
Ted Kremenekcf701772009-02-05 06:50:21 +00003078 }
Ted Kremenek33b6f632009-02-19 23:47:02 +00003079
3080 // Now generate a new node that nukes the old bindings.
3081 GRStateRef state(St, Eng.getStateManager());
3082 RefBindings::Factory& F = state.get_context<RefBindings>();
3083
3084 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3085 E = SymReaper.dead_end(); I!=E; ++I)
3086 B = F.Remove(B, *I);
3087
3088 state = state.set<RefBindings>(B);
3089 Builder.MakeNode(Dst, S, Pred, state);
Ted Kremenekcf701772009-02-05 06:50:21 +00003090}
3091
3092void CFRefCount::ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
3093 GRStmtNodeBuilder<GRState>& Builder,
3094 Expr* NodeExpr, Expr* ErrorExpr,
3095 ExplodedNode<GRState>* Pred,
3096 const GRState* St,
3097 RefVal::Kind hasErr, SymbolRef Sym) {
3098 Builder.BuildSinks = true;
3099 GRExprEngine::NodeTy* N = Builder.MakeNode(Dst, NodeExpr, Pred, St);
3100
3101 if (!N) return;
3102
3103 CFRefBug *BT = 0;
3104
Ted Kremenekf95e9fc2009-03-17 19:42:23 +00003105 switch (hasErr) {
3106 default:
3107 assert(false && "Unhandled error.");
3108 return;
3109 case RefVal::ErrorUseAfterRelease:
3110 BT = static_cast<CFRefBug*>(useAfterRelease);
3111 break;
3112 case RefVal::ErrorReleaseNotOwned:
3113 BT = static_cast<CFRefBug*>(releaseNotOwned);
3114 break;
3115 case RefVal::ErrorDeallocGC:
3116 BT = static_cast<CFRefBug*>(deallocGC);
3117 break;
3118 case RefVal::ErrorDeallocNotOwned:
3119 BT = static_cast<CFRefBug*>(deallocNotOwned);
3120 break;
Ted Kremenekcf701772009-02-05 06:50:21 +00003121 }
3122
Ted Kremenekfe9e5432009-02-18 03:48:14 +00003123 CFRefReport *report = new CFRefReport(*BT, *this, N, Sym);
Ted Kremenekcf701772009-02-05 06:50:21 +00003124 report->addRange(ErrorExpr->getSourceRange());
3125 BR->EmitReport(report);
3126}
3127
3128//===----------------------------------------------------------------------===//
Ted Kremenekd71ed262008-04-10 22:16:52 +00003129// Transfer function creation for external clients.
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00003130//===----------------------------------------------------------------------===//
3131
Ted Kremenek072192b2008-04-30 23:47:44 +00003132GRTransferFuncs* clang::MakeCFRefCountTF(ASTContext& Ctx, bool GCEnabled,
3133 const LangOptions& lopts) {
Ted Kremenek78d46242008-07-22 16:21:24 +00003134 return new CFRefCount(Ctx, GCEnabled, lopts);
Ted Kremenek3ea0b6a2008-04-10 22:58:08 +00003135}