blob: 8c3d9bf366f38b8230285bbcb84de7782f491e40 [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 Kremenek39868cd2009-02-21 18:26:02 +0000122 if ((AtBeginning && StringsEqualNoCase("alloc", s, len)) ||
Ted Kremenek61d2e4a2009-02-22 07:32:24 +0000123 (C == NoConvention && StringsEqualNoCase("copy", s, len)))
Ted Kremenekb80976c2009-02-21 05:13:43 +0000124 C = CreateRule;
125 else // Methods starting with 'init' follow the init rule.
Ted Kremenek39868cd2009-02-21 18:26:02 +0000126 if (AtBeginning && StringsEqualNoCase("init", s, len))
Ted Kremenekb80976c2009-02-21 05:13:43 +0000127 C = InitRule;
128 break;
129 }
130
131 // If we aren't in the prefix and have a derived convention then just
132 // return it now.
133 if (!InPossiblePrefix && C != NoConvention)
134 return C;
135
136 AtBeginning = false;
137 s = wordEnd;
138 }
139
140 // We will get here if there wasn't more than one word
141 // after the prefix.
142 return C;
143}
144
Ted Kremenek5c74d502008-10-24 21:18:08 +0000145static bool followsFundamentalRule(const char* s) {
Ted Kremenekb80976c2009-02-21 05:13:43 +0000146 return deriveNamingConvention(s) == CreateRule;
Ted Kremenek4c79e552008-11-05 16:54:44 +0000147}
148
149static bool followsReturnRule(const char* s) {
Ted Kremenekb80976c2009-02-21 05:13:43 +0000150 NamingConvention C = deriveNamingConvention(s);
151 return C == CreateRule || C == InitRule;
Ted Kremenek4c79e552008-11-05 16:54:44 +0000152}
Ted Kremenek5c74d502008-10-24 21:18:08 +0000153
Ted Kremenek05cbe1a2008-04-09 23:49:11 +0000154//===----------------------------------------------------------------------===//
Ted Kremenek553cf182008-06-25 21:21:56 +0000155// Selector creation functions.
Ted Kremenek4fd88972008-04-17 18:12:53 +0000156//===----------------------------------------------------------------------===//
157
Ted Kremenekb83e02e2008-05-01 18:31:44 +0000158static inline Selector GetNullarySelector(const char* name, ASTContext& Ctx) {
Ted Kremenek4fd88972008-04-17 18:12:53 +0000159 IdentifierInfo* II = &Ctx.Idents.get(name);
160 return Ctx.Selectors.getSelector(0, &II);
161}
162
Ted Kremenek9c32d082008-05-06 00:30:21 +0000163static inline Selector GetUnarySelector(const char* name, ASTContext& Ctx) {
164 IdentifierInfo* II = &Ctx.Idents.get(name);
165 return Ctx.Selectors.getSelector(1, &II);
166}
167
Ted Kremenek553cf182008-06-25 21:21:56 +0000168//===----------------------------------------------------------------------===//
169// Type querying functions.
170//===----------------------------------------------------------------------===//
171
Ted Kremenek12619382009-01-12 21:45:02 +0000172static bool hasPrefix(const char* s, const char* prefix) {
173 if (!prefix)
174 return true;
Ted Kremenek0fcbf8e2008-05-07 20:06:41 +0000175
Ted Kremenek12619382009-01-12 21:45:02 +0000176 char c = *s;
177 char cP = *prefix;
Ted Kremenek0fcbf8e2008-05-07 20:06:41 +0000178
Ted Kremenek12619382009-01-12 21:45:02 +0000179 while (c != '\0' && cP != '\0') {
180 if (c != cP) break;
181 c = *(++s);
182 cP = *(++prefix);
183 }
Ted Kremenek0fcbf8e2008-05-07 20:06:41 +0000184
Ted Kremenek12619382009-01-12 21:45:02 +0000185 return cP == '\0';
Ted Kremenek0fcbf8e2008-05-07 20:06:41 +0000186}
187
Ted Kremenek12619382009-01-12 21:45:02 +0000188static bool hasSuffix(const char* s, const char* suffix) {
189 const char* loc = strstr(s, suffix);
190 return loc && strcmp(suffix, loc) == 0;
191}
192
193static bool isRefType(QualType RetTy, const char* prefix,
194 ASTContext* Ctx = 0, const char* name = 0) {
Ted Kremenek37d785b2008-07-15 16:50:12 +0000195
Ted Kremenek12619382009-01-12 21:45:02 +0000196 if (TypedefType* TD = dyn_cast<TypedefType>(RetTy.getTypePtr())) {
197 const char* TDName = TD->getDecl()->getIdentifier()->getName();
198 return hasPrefix(TDName, prefix) && hasSuffix(TDName, "Ref");
199 }
200
201 if (!Ctx || !name)
Ted Kremenek37d785b2008-07-15 16:50:12 +0000202 return false;
Ted Kremenek12619382009-01-12 21:45:02 +0000203
204 // Is the type void*?
205 const PointerType* PT = RetTy->getAsPointerType();
206 if (!(PT->getPointeeType().getUnqualifiedType() == Ctx->VoidTy))
Ted Kremenek37d785b2008-07-15 16:50:12 +0000207 return false;
Ted Kremenek12619382009-01-12 21:45:02 +0000208
209 // Does the name start with the prefix?
210 return hasPrefix(name, prefix);
Ted Kremenek37d785b2008-07-15 16:50:12 +0000211}
212
Ted Kremenek4fd88972008-04-17 18:12:53 +0000213//===----------------------------------------------------------------------===//
Ted Kremenek553cf182008-06-25 21:21:56 +0000214// Primitives used for constructing summaries for function/method calls.
Ted Kremenek05cbe1a2008-04-09 23:49:11 +0000215//===----------------------------------------------------------------------===//
216
Ted Kremenek553cf182008-06-25 21:21:56 +0000217namespace {
218/// ArgEffect is used to summarize a function/method call's effect on a
219/// particular argument.
Ted Kremenek1c512f52009-02-18 18:54:33 +0000220enum ArgEffect { IncRefMsg, IncRef,
221 DecRefMsg, DecRef,
Ted Kremenek27019002009-02-18 21:57:45 +0000222 MakeCollectable,
Ted Kremenek1c512f52009-02-18 18:54:33 +0000223 DoNothing, DoNothingByRef,
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +0000224 StopTracking, MayEscape, SelfOwn, Autorelease,
225 NewAutoreleasePool };
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
852 // Inspect the result type.
853 QualType RetTy = FT->getResultType();
854
855 // FIXME: This should all be refactored into a chain of "summary lookup"
856 // filters.
857 if (strcmp(FName, "IOServiceGetMatchingServices") == 0) {
858 // FIXES: <rdar://problem/6326900>
859 // This should be addressed using a API table. This strcmp is also
860 // a little gross, but there is no need to super optimize here.
861 assert (ScratchArgs.empty());
862 ScratchArgs.push_back(std::make_pair(1, DecRef));
863 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
864 break;
Ted Kremenek64e859a2008-10-22 20:54:52 +0000865 }
Ted Kremenek12619382009-01-12 21:45:02 +0000866
867 // Handle: id NSMakeCollectable(CFTypeRef)
868 if (strcmp(FName, "NSMakeCollectable") == 0) {
869 S = (RetTy == Ctx.getObjCIdType())
870 ? getUnarySummary(FT, cfmakecollectable)
871 : getPersistentStopSummary();
872
873 break;
874 }
875
876 if (RetTy->isPointerType()) {
877 // For CoreFoundation ('CF') types.
878 if (isRefType(RetTy, "CF", &Ctx, FName)) {
879 if (isRetain(FD, FName))
880 S = getUnarySummary(FT, cfretain);
881 else if (strstr(FName, "MakeCollectable"))
882 S = getUnarySummary(FT, cfmakecollectable);
883 else
884 S = getCFCreateGetRuleSummary(FD, FName);
885
886 break;
887 }
888
889 // For CoreGraphics ('CG') types.
890 if (isRefType(RetTy, "CG", &Ctx, FName)) {
891 if (isRetain(FD, FName))
892 S = getUnarySummary(FT, cfretain);
893 else
894 S = getCFCreateGetRuleSummary(FD, FName);
895
896 break;
897 }
898
899 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
900 if (isRefType(RetTy, "DADisk") ||
901 isRefType(RetTy, "DADissenter") ||
902 isRefType(RetTy, "DASessionRef")) {
903 S = getCFCreateGetRuleSummary(FD, FName);
904 break;
905 }
906
907 break;
908 }
909
910 // Check for release functions, the only kind of functions that we care
911 // about that don't return a pointer type.
912 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
913 if (isRelease(FD, FName+2))
914 S = getUnarySummary(FT, cfrelease);
915 else {
Ted Kremenek68189282009-01-29 22:45:13 +0000916 assert (ScratchArgs.empty());
917 // Remaining CoreFoundation and CoreGraphics functions.
918 // We use to assume that they all strictly followed the ownership idiom
919 // and that ownership cannot be transferred. While this is technically
920 // correct, many methods allow a tracked object to escape. For example:
921 //
922 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
923 // CFDictionaryAddValue(y, key, x);
924 // CFRelease(x);
925 // ... it is okay to use 'x' since 'y' has a reference to it
926 //
927 // We handle this and similar cases with the follow heuristic. If the
928 // function name contains "InsertValue", "SetValue" or "AddValue" then
929 // we assume that arguments may "escape."
930 //
931 ArgEffect E = (CStrInCStrNoCase(FName, "InsertValue") ||
932 CStrInCStrNoCase(FName, "AddValue") ||
Ted Kremeneka92206e2009-02-05 22:34:53 +0000933 CStrInCStrNoCase(FName, "SetValue") ||
934 CStrInCStrNoCase(FName, "AppendValue"))
Ted Kremenek68189282009-01-29 22:45:13 +0000935 ? MayEscape : DoNothing;
936
937 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek12619382009-01-12 21:45:02 +0000938 }
939 }
Ted Kremenek37d785b2008-07-15 16:50:12 +0000940 }
941 while (0);
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000942
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000943 FuncSummaries[FD] = S;
Ted Kremenek86ad3bc2008-05-05 16:51:50 +0000944 return S;
Ted Kremenek2fff37e2008-03-06 00:08:09 +0000945}
946
Ted Kremenek37d785b2008-07-15 16:50:12 +0000947RetainSummary*
948RetainSummaryManager::getCFCreateGetRuleSummary(FunctionDecl* FD,
949 const char* FName) {
950
Ted Kremenek86ad3bc2008-05-05 16:51:50 +0000951 if (strstr(FName, "Create") || strstr(FName, "Copy"))
952 return getCFSummaryCreateRule(FD);
Ted Kremenek37d785b2008-07-15 16:50:12 +0000953
Ted Kremenek86ad3bc2008-05-05 16:51:50 +0000954 if (strstr(FName, "Get"))
955 return getCFSummaryGetRule(FD);
956
957 return 0;
958}
959
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000960RetainSummary*
Ted Kremenek6ad315a2009-02-23 16:51:39 +0000961RetainSummaryManager::getUnarySummary(const FunctionType* FT,
962 UnaryFuncKind func) {
963
Ted Kremenek12619382009-01-12 21:45:02 +0000964 // Sanity check that this is *really* a unary function. This can
965 // happen if people do weird things.
Douglas Gregor72564e72009-02-26 23:50:07 +0000966 const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
Ted Kremenek12619382009-01-12 21:45:02 +0000967 if (!FTP || FTP->getNumArgs() != 1)
968 return getPersistentStopSummary();
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000969
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000970 assert (ScratchArgs.empty());
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000971
Ted Kremenek377e2302008-04-29 05:33:51 +0000972 switch (func) {
Ted Kremenek12619382009-01-12 21:45:02 +0000973 case cfretain: {
Ted Kremenek377e2302008-04-29 05:33:51 +0000974 ScratchArgs.push_back(std::make_pair(0, IncRef));
Ted Kremenek3eabf1c2008-05-22 17:31:13 +0000975 return getPersistentSummary(RetEffect::MakeAlias(0),
976 DoNothing, DoNothing);
Ted Kremenek377e2302008-04-29 05:33:51 +0000977 }
978
979 case cfrelease: {
Ted Kremenek377e2302008-04-29 05:33:51 +0000980 ScratchArgs.push_back(std::make_pair(0, DecRef));
Ted Kremenek3eabf1c2008-05-22 17:31:13 +0000981 return getPersistentSummary(RetEffect::MakeNoRet(),
982 DoNothing, DoNothing);
Ted Kremenek377e2302008-04-29 05:33:51 +0000983 }
984
985 case cfmakecollectable: {
Ted Kremenek27019002009-02-18 21:57:45 +0000986 ScratchArgs.push_back(std::make_pair(0, MakeCollectable));
987 return getPersistentSummary(RetEffect::MakeAlias(0),DoNothing, DoNothing);
Ted Kremenek377e2302008-04-29 05:33:51 +0000988 }
989
990 default:
Ted Kremenek86ad3bc2008-05-05 16:51:50 +0000991 assert (false && "Not a supported unary function.");
Ted Kremenek98530452008-08-12 20:41:56 +0000992 return 0;
Ted Kremenek940b1d82008-04-10 23:44:06 +0000993 }
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000994}
995
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000996RetainSummary* RetainSummaryManager::getCFSummaryCreateRule(FunctionDecl* FD) {
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000997 assert (ScratchArgs.empty());
Ted Kremenek070a8252008-07-09 18:11:16 +0000998
999 if (FD->getIdentifier() == CFDictionaryCreateII) {
1000 ScratchArgs.push_back(std::make_pair(1, DoNothingByRef));
1001 ScratchArgs.push_back(std::make_pair(2, DoNothingByRef));
1002 }
1003
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001004 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001005}
1006
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001007RetainSummary* RetainSummaryManager::getCFSummaryGetRule(FunctionDecl* FD) {
Ted Kremenek891d5cc2008-04-24 17:22:33 +00001008 assert (ScratchArgs.empty());
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001009 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1010 DoNothing, DoNothing);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001011}
1012
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001013//===----------------------------------------------------------------------===//
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001014// Summary creation for Selectors.
1015//===----------------------------------------------------------------------===//
1016
Ted Kremenek1bffd742008-05-06 15:44:25 +00001017RetainSummary*
Ted Kremenek553cf182008-06-25 21:21:56 +00001018RetainSummaryManager::getInitMethodSummary(ObjCMessageExpr* ME) {
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001019 assert(ScratchArgs.empty());
1020
Ted Kremenekc3cf7b22009-02-20 00:05:35 +00001021 // 'init' methods only return an alias if the return type is a location type.
1022 QualType T = ME->getType();
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001023 RetainSummary* Summ =
Ted Kremenekc3cf7b22009-02-20 00:05:35 +00001024 getPersistentSummary(Loc::IsLocType(T) ? RetEffect::MakeReceiverAlias()
1025 : RetEffect::MakeNoRet());
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001026
Ted Kremenek553cf182008-06-25 21:21:56 +00001027 ObjCMethodSummaries[ME] = Summ;
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001028 return Summ;
1029}
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001030
Ted Kremenek553cf182008-06-25 21:21:56 +00001031
Ted Kremenek1bffd742008-05-06 15:44:25 +00001032RetainSummary*
Ted Kremenek553cf182008-06-25 21:21:56 +00001033RetainSummaryManager::getMethodSummary(ObjCMessageExpr* ME,
1034 ObjCInterfaceDecl* ID) {
Ted Kremenek1bffd742008-05-06 15:44:25 +00001035
1036 Selector S = ME->getSelector();
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001037
Ted Kremenek553cf182008-06-25 21:21:56 +00001038 // Look up a summary in our summary cache.
1039 ObjCMethodSummariesTy::iterator I = ObjCMethodSummaries.find(ID, S);
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001040
Ted Kremenek1f180c32008-06-23 22:21:20 +00001041 if (I != ObjCMethodSummaries.end())
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001042 return I->second;
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001043
Ted Kremenek234a4c22009-01-07 00:39:56 +00001044 // "initXXX": pass-through for receiver.
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001045 const char* s = S.getIdentifierInfoForSlot(0)->getName();
Ted Kremeneka4b695a2008-05-07 03:45:05 +00001046 assert (ScratchArgs.empty());
Ted Kremenekaee9e572008-05-06 06:09:09 +00001047
Ted Kremenekb80976c2009-02-21 05:13:43 +00001048 if (deriveNamingConvention(s) == InitRule)
Ted Kremenek234a4c22009-01-07 00:39:56 +00001049 return getInitMethodSummary(ME);
Ted Kremenek1bffd742008-05-06 15:44:25 +00001050
Ted Kremenek234a4c22009-01-07 00:39:56 +00001051 // Look for methods that return an owned object.
1052 if (!isTrackedObjectType(Ctx.getCanonicalType(ME->getType())))
Ted Kremenek84060db2008-05-07 04:25:59 +00001053 return 0;
Ted Kremeneka4b695a2008-05-07 03:45:05 +00001054
Ted Kremenek234a4c22009-01-07 00:39:56 +00001055 if (followsFundamentalRule(s)) {
1056 RetEffect E = isGCEnabled() ? RetEffect::MakeNoRet()
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001057 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremeneka4b695a2008-05-07 03:45:05 +00001058 RetainSummary* Summ = getPersistentSummary(E);
Ted Kremenek553cf182008-06-25 21:21:56 +00001059 ObjCMethodSummaries[ME] = Summ;
Ted Kremenek1bffd742008-05-06 15:44:25 +00001060 return Summ;
1061 }
Ted Kremenek1bffd742008-05-06 15:44:25 +00001062
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001063 return 0;
1064}
1065
Ted Kremenekc8395602008-05-06 21:26:51 +00001066RetainSummary*
Ted Kremenek1f180c32008-06-23 22:21:20 +00001067RetainSummaryManager::getClassMethodSummary(IdentifierInfo* ClsName,
1068 Selector S) {
Ted Kremenekc8395602008-05-06 21:26:51 +00001069
Ted Kremenek553cf182008-06-25 21:21:56 +00001070 // FIXME: Eventually we should properly do class method summaries, but
1071 // it requires us being able to walk the type hierarchy. Unfortunately,
1072 // we cannot do this with just an IdentifierInfo* for the class name.
1073
Ted Kremenekc8395602008-05-06 21:26:51 +00001074 // Look up a summary in our cache of Selectors -> Summaries.
Ted Kremenek553cf182008-06-25 21:21:56 +00001075 ObjCMethodSummariesTy::iterator I = ObjCClassMethodSummaries.find(ClsName, S);
Ted Kremenekc8395602008-05-06 21:26:51 +00001076
Ted Kremenek1f180c32008-06-23 22:21:20 +00001077 if (I != ObjCClassMethodSummaries.end())
Ted Kremenekc8395602008-05-06 21:26:51 +00001078 return I->second;
1079
Ted Kremeneka22cc2f2008-05-06 23:07:13 +00001080 return 0;
Ted Kremenekc8395602008-05-06 21:26:51 +00001081}
1082
Ted Kremenek1f180c32008-06-23 22:21:20 +00001083void RetainSummaryManager::InitializeClassMethodSummaries() {
Ted Kremenek9c32d082008-05-06 00:30:21 +00001084
1085 assert (ScratchArgs.empty());
1086
Ted Kremeneka7344702008-06-23 18:02:52 +00001087 RetEffect E = isGCEnabled() ? RetEffect::MakeNoRet()
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001088 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremeneka7344702008-06-23 18:02:52 +00001089
Ted Kremenek9c32d082008-05-06 00:30:21 +00001090 RetainSummary* Summ = getPersistentSummary(E);
1091
Ted Kremenek553cf182008-06-25 21:21:56 +00001092 // Create the summaries for "alloc", "new", and "allocWithZone:" for
1093 // NSObject and its derivatives.
1094 addNSObjectClsMethSummary(GetNullarySelector("alloc", Ctx), Summ);
1095 addNSObjectClsMethSummary(GetNullarySelector("new", Ctx), Summ);
1096 addNSObjectClsMethSummary(GetUnarySelector("allocWithZone", Ctx), Summ);
Ted Kremenek70a733e2008-07-18 17:24:20 +00001097
1098 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek9e476de2008-08-12 18:30:56 +00001099 addClsMethSummary(&Ctx.Idents.get("NSAssertionHandler"),
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001100 GetNullarySelector("currentHandler", Ctx),
1101 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Ted Kremenek6d348932008-10-21 15:53:15 +00001102
1103 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremenekabf43972009-01-28 21:44:40 +00001104 ScratchArgs.push_back(std::make_pair(0, Autorelease));
1105 addClsMethSummary(&Ctx.Idents.get("NSAutoreleasePool"),
1106 GetUnarySelector("addObject", Ctx),
1107 getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenek022a3c42009-02-23 02:31:16 +00001108 DoNothing, Autorelease));
Ted Kremenek9c32d082008-05-06 00:30:21 +00001109}
1110
Ted Kremenek1f180c32008-06-23 22:21:20 +00001111void RetainSummaryManager::InitializeMethodSummaries() {
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001112
1113 assert (ScratchArgs.empty());
1114
Ted Kremenekc8395602008-05-06 21:26:51 +00001115 // Create the "init" selector. It just acts as a pass-through for the
1116 // receiver.
Ted Kremenek46347352009-02-23 16:54:00 +00001117 RetainSummary* InitSumm =
1118 getPersistentSummary(RetEffect::MakeReceiverAlias());
Ted Kremenek179064e2008-07-01 17:21:27 +00001119 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
Ted Kremenekc8395602008-05-06 21:26:51 +00001120
1121 // The next methods are allocators.
Ted Kremeneka7344702008-06-23 18:02:52 +00001122 RetEffect E = isGCEnabled() ? RetEffect::MakeNoRet()
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001123 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremeneka7344702008-06-23 18:02:52 +00001124
Ted Kremenek179064e2008-07-01 17:21:27 +00001125 RetainSummary* Summ = getPersistentSummary(E);
Ted Kremenekc8395602008-05-06 21:26:51 +00001126
1127 // Create the "copy" selector.
Ted Kremenek98530452008-08-12 20:41:56 +00001128 addNSObjectMethSummary(GetNullarySelector("copy", Ctx), Summ);
1129
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001130 // Create the "mutableCopy" selector.
Ted Kremenek553cf182008-06-25 21:21:56 +00001131 addNSObjectMethSummary(GetNullarySelector("mutableCopy", Ctx), Summ);
Ted Kremenek98530452008-08-12 20:41:56 +00001132
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001133 // Create the "retain" selector.
1134 E = RetEffect::MakeReceiverAlias();
Ted Kremenek1c512f52009-02-18 18:54:33 +00001135 Summ = getPersistentSummary(E, IncRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001136 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001137
1138 // Create the "release" selector.
Ted Kremenek1c512f52009-02-18 18:54:33 +00001139 Summ = getPersistentSummary(E, DecRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001140 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Ted Kremenek299e8152008-05-07 21:17:39 +00001141
1142 // Create the "drain" selector.
1143 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek553cf182008-06-25 21:21:56 +00001144 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001145
1146 // Create the "autorelease" selector.
Ted Kremenekabf43972009-01-28 21:44:40 +00001147 Summ = getPersistentSummary(E, Autorelease);
Ted Kremenek553cf182008-06-25 21:21:56 +00001148 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Ted Kremenek98530452008-08-12 20:41:56 +00001149
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00001150 // Specially handle NSAutoreleasePool.
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001151 addInstMethSummary("NSAutoreleasePool", "init",
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00001152 getPersistentSummary(RetEffect::MakeReceiverAlias(),
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001153 NewAutoreleasePool));
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00001154
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001155 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremenek89e202d2009-02-23 02:51:29 +00001156 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1157 // self-own themselves. However, they only do this once they are displayed.
1158 // Thus, we need to track an NSWindow's display status.
1159 // This is tracked in <rdar://problem/6062711>.
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +00001160 // See also http://llvm.org/bugs/show_bug.cgi?id=3714.
1161 addClassMethSummary("NSWindow", "alloc",
1162 getPersistentSummary(RetEffect::MakeNoRet()));
1163
1164#if 0
Ted Kremenek179064e2008-07-01 17:21:27 +00001165 RetainSummary *NSWindowSumm =
Ted Kremenek89e202d2009-02-23 02:51:29 +00001166 getPersistentSummary(RetEffect::MakeReceiverAlias(), StopTracking);
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001167
1168 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1169 "styleMask", "backing", "defer", NULL);
1170
1171 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1172 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek3aa7ecd2009-03-04 23:30:42 +00001173#endif
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001174
1175 // For NSPanel (which subclasses NSWindow), allocated objects are not
1176 // self-owned.
1177 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1178 "styleMask", "backing", "defer", NULL);
1179
1180 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1181 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek553cf182008-06-25 21:21:56 +00001182
Ted Kremenek70a733e2008-07-18 17:24:20 +00001183 // Create NSAssertionHandler summaries.
Ted Kremenek9e476de2008-08-12 18:30:56 +00001184 addPanicSummary("NSAssertionHandler", "handleFailureInFunction", "file",
1185 "lineNumber", "description", NULL);
Ted Kremenek70a733e2008-07-18 17:24:20 +00001186
Ted Kremenek9e476de2008-08-12 18:30:56 +00001187 addPanicSummary("NSAssertionHandler", "handleFailureInMethod", "object",
1188 "file", "lineNumber", "description", NULL);
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001189}
1190
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001191//===----------------------------------------------------------------------===//
Ted Kremenek13922612008-04-16 20:40:59 +00001192// Reference-counting logic (typestate + counts).
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001193//===----------------------------------------------------------------------===//
1194
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001195namespace {
1196
Ted Kremenek05cbe1a2008-04-09 23:49:11 +00001197class VISIBILITY_HIDDEN RefVal {
Ted Kremenek4fd88972008-04-17 18:12:53 +00001198public:
Ted Kremenek4fd88972008-04-17 18:12:53 +00001199 enum Kind {
1200 Owned = 0, // Owning reference.
1201 NotOwned, // Reference is not owned by still valid (not freed).
1202 Released, // Object has been released.
1203 ReturnedOwned, // Returned object passes ownership to caller.
1204 ReturnedNotOwned, // Return object does not pass ownership to caller.
1205 ErrorUseAfterRelease, // Object used after released.
1206 ErrorReleaseNotOwned, // Release of an object that was not owned.
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00001207 ErrorLeak, // A memory leak due to excessive reference counts.
1208 ErrorLeakReturned // A memory leak due to the returning method not having
1209 // the correct naming conventions.
Ted Kremenek4fd88972008-04-17 18:12:53 +00001210 };
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001211
1212private:
Ted Kremenek4fd88972008-04-17 18:12:53 +00001213 Kind kind;
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001214 RetEffect::ObjKind okind;
Ted Kremenek4fd88972008-04-17 18:12:53 +00001215 unsigned Cnt;
Ted Kremenek553cf182008-06-25 21:21:56 +00001216 QualType T;
1217
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001218 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, QualType t)
1219 : kind(k), okind(o), Cnt(cnt), T(t) {}
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001220
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001221 RefVal(Kind k, unsigned cnt = 0)
1222 : kind(k), okind(RetEffect::AnyObj), Cnt(cnt) {}
1223
1224public:
Ted Kremenek4fd88972008-04-17 18:12:53 +00001225 Kind getKind() const { return kind; }
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001226
1227 RetEffect::ObjKind getObjKind() const { return okind; }
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001228
Ted Kremenek553cf182008-06-25 21:21:56 +00001229 unsigned getCount() const { return Cnt; }
1230 QualType getType() const { return T; }
Ted Kremenek4fd88972008-04-17 18:12:53 +00001231
1232 // Useful predicates.
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001233
Ted Kremenek73c750b2008-03-11 18:14:09 +00001234 static bool isError(Kind k) { return k >= ErrorUseAfterRelease; }
1235
Ted Kremenekf9790ae2008-10-24 20:32:50 +00001236 static bool isLeak(Kind k) { return k >= ErrorLeak; }
Ted Kremenekdb863712008-04-16 22:32:20 +00001237
Ted Kremeneke7bd9c22008-04-11 22:25:11 +00001238 bool isOwned() const {
1239 return getKind() == Owned;
1240 }
1241
Ted Kremenekdb863712008-04-16 22:32:20 +00001242 bool isNotOwned() const {
1243 return getKind() == NotOwned;
1244 }
1245
Ted Kremenek4fd88972008-04-17 18:12:53 +00001246 bool isReturnedOwned() const {
1247 return getKind() == ReturnedOwned;
1248 }
1249
1250 bool isReturnedNotOwned() const {
1251 return getKind() == ReturnedNotOwned;
1252 }
1253
1254 bool isNonLeakError() const {
1255 Kind k = getKind();
1256 return isError(k) && !isLeak(k);
1257 }
1258
1259 // State creation: normal state.
1260
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001261 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
1262 unsigned Count = 1) {
1263 return RefVal(Owned, o, Count, t);
Ted Kremenek61b9f872008-04-10 23:09:18 +00001264 }
1265
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001266 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
1267 unsigned Count = 0) {
1268 return RefVal(NotOwned, o, Count, t);
Ted Kremenek61b9f872008-04-10 23:09:18 +00001269 }
Ted Kremenek4fd88972008-04-17 18:12:53 +00001270
1271 static RefVal makeReturnedOwned(unsigned Count) {
1272 return RefVal(ReturnedOwned, Count);
1273 }
1274
1275 static RefVal makeReturnedNotOwned() {
1276 return RefVal(ReturnedNotOwned);
1277 }
1278
Ted Kremenek4fd88972008-04-17 18:12:53 +00001279 // Comparison, profiling, and pretty-printing.
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001280
Ted Kremenek4fd88972008-04-17 18:12:53 +00001281 bool operator==(const RefVal& X) const {
Ted Kremenek553cf182008-06-25 21:21:56 +00001282 return kind == X.kind && Cnt == X.Cnt && T == X.T;
Ted Kremenek4fd88972008-04-17 18:12:53 +00001283 }
Ted Kremenekf3948042008-03-11 19:44:10 +00001284
Ted Kremenek553cf182008-06-25 21:21:56 +00001285 RefVal operator-(size_t i) const {
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001286 return RefVal(getKind(), getObjKind(), getCount() - i, getType());
Ted Kremenek553cf182008-06-25 21:21:56 +00001287 }
1288
1289 RefVal operator+(size_t i) const {
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001290 return RefVal(getKind(), getObjKind(), getCount() + i, getType());
Ted Kremenek553cf182008-06-25 21:21:56 +00001291 }
1292
1293 RefVal operator^(Kind k) const {
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001294 return RefVal(k, getObjKind(), getCount(), getType());
Ted Kremenek553cf182008-06-25 21:21:56 +00001295 }
Ted Kremenek553cf182008-06-25 21:21:56 +00001296
Ted Kremenek4fd88972008-04-17 18:12:53 +00001297 void Profile(llvm::FoldingSetNodeID& ID) const {
1298 ID.AddInteger((unsigned) kind);
1299 ID.AddInteger(Cnt);
Ted Kremenek553cf182008-06-25 21:21:56 +00001300 ID.Add(T);
Ted Kremenek4fd88972008-04-17 18:12:53 +00001301 }
1302
Ted Kremenekf3948042008-03-11 19:44:10 +00001303 void print(std::ostream& Out) const;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001304};
Ted Kremenekf3948042008-03-11 19:44:10 +00001305
1306void RefVal::print(std::ostream& Out) const {
Ted Kremenek553cf182008-06-25 21:21:56 +00001307 if (!T.isNull())
1308 Out << "Tracked Type:" << T.getAsString() << '\n';
1309
Ted Kremenekf3948042008-03-11 19:44:10 +00001310 switch (getKind()) {
1311 default: assert(false);
Ted Kremenek61b9f872008-04-10 23:09:18 +00001312 case Owned: {
1313 Out << "Owned";
1314 unsigned cnt = getCount();
1315 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenekf3948042008-03-11 19:44:10 +00001316 break;
Ted Kremenek61b9f872008-04-10 23:09:18 +00001317 }
Ted Kremenekf3948042008-03-11 19:44:10 +00001318
Ted Kremenek61b9f872008-04-10 23:09:18 +00001319 case NotOwned: {
Ted Kremenek4fd88972008-04-17 18:12:53 +00001320 Out << "NotOwned";
Ted Kremenek61b9f872008-04-10 23:09:18 +00001321 unsigned cnt = getCount();
1322 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenekf3948042008-03-11 19:44:10 +00001323 break;
Ted Kremenek61b9f872008-04-10 23:09:18 +00001324 }
Ted Kremenekf3948042008-03-11 19:44:10 +00001325
Ted Kremenek4fd88972008-04-17 18:12:53 +00001326 case ReturnedOwned: {
1327 Out << "ReturnedOwned";
1328 unsigned cnt = getCount();
1329 if (cnt) Out << " (+ " << cnt << ")";
1330 break;
1331 }
1332
1333 case ReturnedNotOwned: {
1334 Out << "ReturnedNotOwned";
1335 unsigned cnt = getCount();
1336 if (cnt) Out << " (+ " << cnt << ")";
1337 break;
1338 }
1339
Ted Kremenekf3948042008-03-11 19:44:10 +00001340 case Released:
1341 Out << "Released";
1342 break;
1343
Ted Kremenekdb863712008-04-16 22:32:20 +00001344 case ErrorLeak:
1345 Out << "Leaked";
1346 break;
1347
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00001348 case ErrorLeakReturned:
1349 Out << "Leaked (Bad naming)";
1350 break;
1351
Ted Kremenekf3948042008-03-11 19:44:10 +00001352 case ErrorUseAfterRelease:
1353 Out << "Use-After-Release [ERROR]";
1354 break;
1355
1356 case ErrorReleaseNotOwned:
1357 Out << "Release of Not-Owned [ERROR]";
1358 break;
1359 }
1360}
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001361
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001362} // end anonymous namespace
1363
1364//===----------------------------------------------------------------------===//
1365// RefBindings - State used to track object reference counts.
1366//===----------------------------------------------------------------------===//
1367
Ted Kremenek2dabd432008-12-05 02:27:51 +00001368typedef llvm::ImmutableMap<SymbolRef, RefVal> RefBindings;
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001369static int RefBIndex = 0;
Ted Kremenek33b6f632009-02-19 23:47:02 +00001370static std::pair<const void*, const void*> LeakProgramPointTag(&RefBIndex, 0);
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001371
1372namespace clang {
Ted Kremenekb9d17f92008-08-17 03:20:02 +00001373 template<>
1374 struct GRStateTrait<RefBindings> : public GRStatePartialTrait<RefBindings> {
1375 static inline void* GDMIndex() { return &RefBIndex; }
1376 };
1377}
Ted Kremenek6d348932008-10-21 15:53:15 +00001378
1379//===----------------------------------------------------------------------===//
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001380// AutoreleaseBindings - State used to track objects in autorelease pools.
Ted Kremenek6d348932008-10-21 15:53:15 +00001381//===----------------------------------------------------------------------===//
1382
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001383typedef llvm::ImmutableMap<SymbolRef, unsigned> ARCounts;
1384typedef llvm::ImmutableMap<SymbolRef, ARCounts> ARPoolContents;
1385typedef llvm::ImmutableList<SymbolRef> ARStack;
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00001386
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001387static int AutoRCIndex = 0;
Ted Kremenek6d348932008-10-21 15:53:15 +00001388static int AutoRBIndex = 0;
1389
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001390namespace { class VISIBILITY_HIDDEN AutoreleasePoolContents {}; }
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001391namespace { class VISIBILITY_HIDDEN AutoreleaseStack {}; }
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001392
Ted Kremenek6d348932008-10-21 15:53:15 +00001393namespace clang {
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001394template<> struct GRStateTrait<AutoreleaseStack>
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001395 : public GRStatePartialTrait<ARStack> {
1396 static inline void* GDMIndex() { return &AutoRBIndex; }
1397};
1398
1399template<> struct GRStateTrait<AutoreleasePoolContents>
1400 : public GRStatePartialTrait<ARPoolContents> {
1401 static inline void* GDMIndex() { return &AutoRCIndex; }
1402};
1403} // end clang namespace
Ted Kremenek6d348932008-10-21 15:53:15 +00001404
Ted Kremenek13922612008-04-16 20:40:59 +00001405//===----------------------------------------------------------------------===//
1406// Transfer functions.
1407//===----------------------------------------------------------------------===//
1408
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001409namespace {
1410
Ted Kremenek05cbe1a2008-04-09 23:49:11 +00001411class VISIBILITY_HIDDEN CFRefCount : public GRSimpleVals {
Ted Kremenek8dd56462008-04-18 03:39:05 +00001412public:
Ted Kremenekae6814e2008-08-13 21:24:49 +00001413 class BindingsPrinter : public GRState::Printer {
Ted Kremenekf3948042008-03-11 19:44:10 +00001414 public:
Ted Kremenekae6814e2008-08-13 21:24:49 +00001415 virtual void Print(std::ostream& Out, const GRState* state,
1416 const char* nl, const char* sep);
Ted Kremenekf3948042008-03-11 19:44:10 +00001417 };
Ted Kremenek8dd56462008-04-18 03:39:05 +00001418
1419private:
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001420 typedef llvm::DenseMap<const GRExprEngine::NodeTy*, const RetainSummary*>
1421 SummaryLogTy;
1422
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001423 RetainSummaryManager Summaries;
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001424 SummaryLogTy SummaryLog;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001425 const LangOptions& LOpts;
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001426 ARCounts::Factory ARCountFactory;
Ted Kremenekb9d17f92008-08-17 03:20:02 +00001427
Ted Kremenekcf701772009-02-05 06:50:21 +00001428 BugType *useAfterRelease, *releaseNotOwned;
1429 BugType *leakWithinFunction, *leakAtReturn;
1430 BugReporter *BR;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001431
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001432 GRStateRef Update(GRStateRef state, SymbolRef sym, RefVal V, ArgEffect E,
1433 RefVal::Kind& hasErr);
1434
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001435 void ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
1436 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekdb863712008-04-16 22:32:20 +00001437 Expr* NodeExpr, Expr* ErrorExpr,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001438 ExplodedNode<GRState>* Pred,
1439 const GRState* St,
Ted Kremenek2dabd432008-12-05 02:27:51 +00001440 RefVal::Kind hasErr, SymbolRef Sym);
Ted Kremenekdb863712008-04-16 22:32:20 +00001441
Ted Kremenekf9790ae2008-10-24 20:32:50 +00001442 std::pair<GRStateRef, bool>
1443 HandleSymbolDeath(GRStateManager& VMgr, const GRState* St,
Ted Kremenek2dabd432008-12-05 02:27:51 +00001444 const Decl* CD, SymbolRef sid, RefVal V, bool& hasLeak);
Ted Kremenekdb863712008-04-16 22:32:20 +00001445
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001446public:
Ted Kremenek78d46242008-07-22 16:21:24 +00001447 CFRefCount(ASTContext& Ctx, bool gcenabled, const LangOptions& lopts)
Ted Kremenek377e2302008-04-29 05:33:51 +00001448 : Summaries(Ctx, gcenabled),
Ted Kremenekcf701772009-02-05 06:50:21 +00001449 LOpts(lopts), useAfterRelease(0), releaseNotOwned(0),
1450 leakWithinFunction(0), leakAtReturn(0), BR(0) {}
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001451
Ted Kremenekcf701772009-02-05 06:50:21 +00001452 virtual ~CFRefCount() {}
Ted Kremenek05cbe1a2008-04-09 23:49:11 +00001453
Ted Kremenekcf118d42009-02-04 23:49:09 +00001454 void RegisterChecks(BugReporter &BR);
Ted Kremenekf3948042008-03-11 19:44:10 +00001455
Ted Kremenek1c72ef02008-08-16 00:49:49 +00001456 virtual void RegisterPrinters(std::vector<GRState::Printer*>& Printers) {
1457 Printers.push_back(new BindingsPrinter());
Ted Kremenekf3948042008-03-11 19:44:10 +00001458 }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001459
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001460 bool isGCEnabled() const { return Summaries.isGCEnabled(); }
Ted Kremenek072192b2008-04-30 23:47:44 +00001461 const LangOptions& getLangOptions() const { return LOpts; }
1462
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001463 const RetainSummary *getSummaryOfNode(const ExplodedNode<GRState> *N) const {
1464 SummaryLogTy::const_iterator I = SummaryLog.find(N);
1465 return I == SummaryLog.end() ? 0 : I->second;
1466 }
1467
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001468 // Calls.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001469
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001470 void EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001471 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001472 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001473 Expr* Ex,
1474 Expr* Receiver,
1475 RetainSummary* Summ,
Ted Kremenek55499762008-06-17 02:43:46 +00001476 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001477 ExplodedNode<GRState>* Pred);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001478
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001479 virtual void EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek199e1a02008-03-12 21:06:49 +00001480 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001481 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001482 CallExpr* CE, SVal L,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001483 ExplodedNode<GRState>* Pred);
Ted Kremenekfa34b332008-04-09 01:10:13 +00001484
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001485
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001486 virtual void EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek85348202008-04-15 23:44:31 +00001487 GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001488 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek85348202008-04-15 23:44:31 +00001489 ObjCMessageExpr* ME,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001490 ExplodedNode<GRState>* Pred);
Ted Kremenek85348202008-04-15 23:44:31 +00001491
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001492 bool EvalObjCMessageExprAux(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek85348202008-04-15 23:44:31 +00001493 GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001494 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek85348202008-04-15 23:44:31 +00001495 ObjCMessageExpr* ME,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001496 ExplodedNode<GRState>* Pred);
Ted Kremenek85348202008-04-15 23:44:31 +00001497
Ted Kremenek41573eb2009-02-14 01:43:44 +00001498 // Stores.
1499 virtual void EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val);
1500
Ted Kremeneke7bd9c22008-04-11 22:25:11 +00001501 // End-of-path.
1502
1503 virtual void EvalEndPath(GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001504 GREndPathNodeBuilder<GRState>& Builder);
Ted Kremeneke7bd9c22008-04-11 22:25:11 +00001505
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001506 virtual void EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek652adc62008-04-24 23:57:27 +00001507 GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001508 GRStmtNodeBuilder<GRState>& Builder,
1509 ExplodedNode<GRState>* Pred,
Ted Kremenek241677a2009-01-21 22:26:05 +00001510 Stmt* S, const GRState* state,
1511 SymbolReaper& SymReaper);
1512
Ted Kremenek4fd88972008-04-17 18:12:53 +00001513 // Return statements.
1514
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001515 virtual void EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4fd88972008-04-17 18:12:53 +00001516 GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001517 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4fd88972008-04-17 18:12:53 +00001518 ReturnStmt* S,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001519 ExplodedNode<GRState>* Pred);
Ted Kremenekcb612922008-04-18 19:23:43 +00001520
1521 // Assumptions.
1522
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001523 virtual const GRState* EvalAssume(GRStateManager& VMgr,
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001524 const GRState* St, SVal Cond,
Ted Kremenek4323a572008-07-10 22:03:41 +00001525 bool Assumption, bool& isFeasible);
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001526};
1527
1528} // end anonymous namespace
1529
Ted Kremenek8dd56462008-04-18 03:39:05 +00001530
Ted Kremenekae6814e2008-08-13 21:24:49 +00001531void CFRefCount::BindingsPrinter::Print(std::ostream& Out, const GRState* state,
1532 const char* nl, const char* sep) {
1533
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001534 RefBindings B = state->get<RefBindings>();
Ted Kremenekf3948042008-03-11 19:44:10 +00001535
Ted Kremenekae6814e2008-08-13 21:24:49 +00001536 if (!B.isEmpty())
Ted Kremenekf3948042008-03-11 19:44:10 +00001537 Out << sep << nl;
1538
1539 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
1540 Out << (*I).first << " : ";
1541 (*I).second.print(Out);
1542 Out << nl;
1543 }
Ted Kremenek6c4becb2009-02-25 02:54:57 +00001544
1545 // Print the autorelease stack.
1546 ARStack stack = state->get<AutoreleaseStack>();
1547 if (!stack.isEmpty()) {
1548 Out << sep << nl << "AR pool stack:";
1549
1550 for (ARStack::iterator I=stack.begin(), E=stack.end(); I!=E; ++I)
1551 Out << ' ' << (*I);
1552
1553 Out << nl;
1554 }
Ted Kremenekf3948042008-03-11 19:44:10 +00001555}
1556
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001557static inline ArgEffect GetArgE(RetainSummary* Summ, unsigned idx) {
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00001558 return Summ ? Summ->getArg(idx) : MayEscape;
Ted Kremenekf9561e52008-04-11 20:23:24 +00001559}
1560
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001561static inline RetEffect GetRetEffect(RetainSummary* Summ) {
1562 return Summ ? Summ->getRetEffect() : RetEffect::MakeNoRet();
Ted Kremenekf9561e52008-04-11 20:23:24 +00001563}
1564
Ted Kremenek14993892008-05-06 02:41:27 +00001565static inline ArgEffect GetReceiverE(RetainSummary* Summ) {
1566 return Summ ? Summ->getReceiverEffect() : DoNothing;
1567}
1568
Ted Kremenek70a733e2008-07-18 17:24:20 +00001569static inline bool IsEndPath(RetainSummary* Summ) {
1570 return Summ ? Summ->isEndPath() : false;
1571}
1572
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001573
Ted Kremenek553cf182008-06-25 21:21:56 +00001574/// GetReturnType - Used to get the return type of a message expression or
1575/// function call with the intention of affixing that type to a tracked symbol.
1576/// While the the return type can be queried directly from RetEx, when
1577/// invoking class methods we augment to the return type to be that of
1578/// a pointer to the class (as opposed it just being id).
1579static QualType GetReturnType(Expr* RetE, ASTContext& Ctx) {
1580
1581 QualType RetTy = RetE->getType();
1582
1583 // FIXME: We aren't handling id<...>.
Chris Lattner8b51fd72008-07-26 22:36:27 +00001584 const PointerType* PT = RetTy->getAsPointerType();
Ted Kremenek553cf182008-06-25 21:21:56 +00001585 if (!PT)
1586 return RetTy;
1587
1588 // If RetEx is not a message expression just return its type.
1589 // If RetEx is a message expression, return its types if it is something
1590 /// more specific than id.
1591
1592 ObjCMessageExpr* ME = dyn_cast<ObjCMessageExpr>(RetE);
1593
Steve Naroff389bf462009-02-12 17:52:19 +00001594 if (!ME || !Ctx.isObjCIdStructType(PT->getPointeeType()))
Ted Kremenek553cf182008-06-25 21:21:56 +00001595 return RetTy;
1596
1597 ObjCInterfaceDecl* D = ME->getClassInfo().first;
1598
1599 // At this point we know the return type of the message expression is id.
1600 // If we have an ObjCInterceDecl, we know this is a call to a class method
1601 // whose type we can resolve. In such cases, promote the return type to
1602 // Class*.
1603 return !D ? RetTy : Ctx.getPointerType(Ctx.getObjCInterfaceType(D));
1604}
1605
1606
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001607void CFRefCount::EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001608 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001609 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001610 Expr* Ex,
1611 Expr* Receiver,
1612 RetainSummary* Summ,
Ted Kremenek55499762008-06-17 02:43:46 +00001613 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001614 ExplodedNode<GRState>* Pred) {
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001615
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001616 // Get the state.
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001617 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenekf9790ae2008-10-24 20:32:50 +00001618 ASTContext& Ctx = Eng.getStateManager().getContext();
Ted Kremenek14993892008-05-06 02:41:27 +00001619
1620 // Evaluate the effect of the arguments.
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001621 RefVal::Kind hasErr = (RefVal::Kind) 0;
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001622 unsigned idx = 0;
Ted Kremenekbcf50ad2008-04-11 18:40:51 +00001623 Expr* ErrorExpr = NULL;
Ted Kremenek2dabd432008-12-05 02:27:51 +00001624 SymbolRef ErrorSym = 0;
Ted Kremenekbcf50ad2008-04-11 18:40:51 +00001625
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001626 for (ExprIterator I = arg_beg; I != arg_end; ++I, ++idx) {
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00001627 SVal V = state.GetSValAsScalarOrLoc(*I);
Ted Kremenek94c96982009-03-03 22:06:47 +00001628 SymbolRef Sym = V.getAsLocSymbol();
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00001629
Ted Kremenek94c96982009-03-03 22:06:47 +00001630 if (Sym.isValid())
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001631 if (RefBindings::data_type* T = state.get<RefBindings>(Sym)) {
1632 state = Update(state, Sym, *T, GetArgE(Summ, idx), hasErr);
1633 if (hasErr) {
Ted Kremenekbcf50ad2008-04-11 18:40:51 +00001634 ErrorExpr = *I;
Ted Kremeneke8fdc832008-07-07 16:21:19 +00001635 ErrorSym = Sym;
Ted Kremenekbcf50ad2008-04-11 18:40:51 +00001636 break;
Ted Kremenek94c96982009-03-03 22:06:47 +00001637 }
1638 continue;
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001639 }
Ted Kremenek070a8252008-07-09 18:11:16 +00001640
Ted Kremenek94c96982009-03-03 22:06:47 +00001641 if (isa<Loc>(V)) {
1642 if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(&V)) {
Ted Kremenek070a8252008-07-09 18:11:16 +00001643 if (GetArgE(Summ, idx) == DoNothingByRef)
1644 continue;
1645
1646 // Invalidate the value of the variable passed by reference.
Ted Kremenek8c5633e2008-07-03 23:26:32 +00001647
1648 // FIXME: Either this logic should also be replicated in GRSimpleVals
1649 // or should be pulled into a separate "constraint engine."
Ted Kremenek070a8252008-07-09 18:11:16 +00001650
Ted Kremenek8c5633e2008-07-03 23:26:32 +00001651 // FIXME: We can have collisions on the conjured symbol if the
1652 // expression *I also creates conjured symbols. We probably want
1653 // to identify conjured symbols by an expression pair: the enclosing
1654 // expression (the context) and the expression itself. This should
Ted Kremenek070a8252008-07-09 18:11:16 +00001655 // disambiguate conjured symbols.
Ted Kremenek9e240492008-10-04 05:50:14 +00001656
Ted Kremenek993f1c72008-10-17 20:28:54 +00001657 const TypedRegion* R = dyn_cast<TypedRegion>(MR->getRegion());
Ted Kremenek90b32362008-12-17 19:42:34 +00001658
Ted Kremenek0312c0e2009-03-01 05:44:08 +00001659 // Blast through TypedViewRegions to get the original region type.
Ted Kremenek90b32362008-12-17 19:42:34 +00001660 while (R) {
Ted Kremenek0312c0e2009-03-01 05:44:08 +00001661 const TypedViewRegion* ATR = dyn_cast<TypedViewRegion>(R);
Ted Kremenek90b32362008-12-17 19:42:34 +00001662 if (!ATR) break;
1663 R = dyn_cast<TypedRegion>(ATR->getSuperRegion());
1664 }
1665
Ted Kremenekd104a092009-03-04 22:56:43 +00001666 if (R) {
Ted Kremenek40e86d92008-12-18 23:34:57 +00001667 // Is the invalidated variable something that we were tracking?
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00001668 SymbolRef Sym = state.GetSValAsScalarOrLoc(R).getAsLocSymbol();
Ted Kremenek40e86d92008-12-18 23:34:57 +00001669
Ted Kremenekd104a092009-03-04 22:56:43 +00001670 // Remove any existing reference-count binding.
1671 if (Sym.isValid()) state = state.remove<RefBindings>(Sym);
Ted Kremenek9e240492008-10-04 05:50:14 +00001672
Ted Kremenekd104a092009-03-04 22:56:43 +00001673 if (R->isBoundable(Ctx)) {
1674 // Set the value of the variable to be a conjured symbol.
1675 unsigned Count = Builder.getCurrentBlockCount();
1676 QualType T = R->getRValueType(Ctx);
1677
1678 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())) {
1679 SymbolRef NewSym =
1680 Eng.getSymbolManager().getConjuredSymbol(*I, T, Count);
1681
1682 state = state.BindLoc(Loc::MakeVal(R),
1683 Loc::IsLocType(T)
1684 ? cast<SVal>(loc::SymbolVal(NewSym))
1685 : cast<SVal>(nonloc::SymbolVal(NewSym)));
1686 }
1687 else if (const RecordType *RT = T->getAsStructureType()) {
1688 // Handle structs in a not so awesome way. Here we just
1689 // eagerly bind new symbols to the fields. In reality we
1690 // should have the store manager handle this. The idea is just
1691 // to prototype some basic functionality here. All of this logic
1692 // should one day soon just go away.
1693 const RecordDecl *RD = RT->getDecl()->getDefinition(Ctx);
1694
1695 // No record definition. There is nothing we can do.
1696 if (!RD)
1697 continue;
1698
1699 MemRegionManager &MRMgr = state.getManager().getRegionManager();
1700
1701 // Iterate through the fields and construct new symbols.
1702 for (RecordDecl::field_iterator FI=RD->field_begin(),
1703 FE=RD->field_end(); FI!=FE; ++FI) {
1704
1705 // For now just handle scalar fields.
1706 FieldDecl *FD = *FI;
1707 QualType FT = FD->getType();
1708
1709 if (Loc::IsLocType(FT) ||
1710 (FT->isIntegerType() && FT->isScalarType())) {
1711
1712 // Tag the symbol with the field decl so that we generate
1713 // a unique symbol.
1714 SymbolRef NewSym =
1715 Eng.getSymbolManager().getConjuredSymbol(*I, FT, Count, FD);
1716
1717 // Create a region.
1718 // FIXME: How do we handle 'typedefs' in TypeViewRegions?
1719 // e.g.:
1720 // typedef struct *s foo;
1721 //
1722 // ((foo) x)->f vs. x->f
1723 //
1724 // The cast will add a ViewTypeRegion. Probably RegionStore
1725 // needs to reason about typedefs explicitly when binding
1726 // fields and elements.
1727 //
1728 const FieldRegion* FR = MRMgr.getFieldRegion(FD, R);
1729
1730 state = state.BindLoc(Loc::MakeVal(FR),
1731 Loc::IsLocType(FT)
1732 ? cast<SVal>(loc::SymbolVal(NewSym))
1733 : cast<SVal>(nonloc::SymbolVal(NewSym)));
1734 }
1735 }
1736 }
1737 else {
1738 // Just blast away other values.
1739 state = state.BindLoc(*MR, UnknownVal());
1740 }
Ted Kremenekfd301942008-10-17 22:23:12 +00001741 }
Ted Kremenek9e240492008-10-04 05:50:14 +00001742 }
1743 else
Ted Kremeneka441b7e2008-11-12 19:22:09 +00001744 state = state.BindLoc(*MR, UnknownVal());
Ted Kremenek8c5633e2008-07-03 23:26:32 +00001745 }
1746 else {
1747 // Nuke all other arguments passed by reference.
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001748 state = state.Unbind(cast<Loc>(V));
Ted Kremenek8c5633e2008-07-03 23:26:32 +00001749 }
Ted Kremenekb8873552008-04-11 20:51:02 +00001750 }
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001751 else if (isa<nonloc::LocAsInteger>(V))
1752 state = state.Unbind(cast<nonloc::LocAsInteger>(V).getLoc());
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001753 }
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001754
Ted Kremenek553cf182008-06-25 21:21:56 +00001755 // Evaluate the effect on the message receiver.
Ted Kremenek14993892008-05-06 02:41:27 +00001756 if (!ErrorExpr && Receiver) {
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00001757 SymbolRef Sym = state.GetSValAsScalarOrLoc(Receiver).getAsLocSymbol();
Ted Kremenek94c96982009-03-03 22:06:47 +00001758 if (Sym.isValid()) {
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001759 if (const RefVal* T = state.get<RefBindings>(Sym)) {
1760 state = Update(state, Sym, *T, GetReceiverE(Summ), hasErr);
1761 if (hasErr) {
Ted Kremenek14993892008-05-06 02:41:27 +00001762 ErrorExpr = Receiver;
Ted Kremeneke8fdc832008-07-07 16:21:19 +00001763 ErrorSym = Sym;
Ted Kremenek14993892008-05-06 02:41:27 +00001764 }
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001765 }
Ted Kremenek14993892008-05-06 02:41:27 +00001766 }
1767 }
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001768
Ted Kremenek553cf182008-06-25 21:21:56 +00001769 // Process any errors.
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001770 if (hasErr) {
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001771 ProcessNonLeakError(Dst, Builder, Ex, ErrorExpr, Pred, state,
Ted Kremenek8dd56462008-04-18 03:39:05 +00001772 hasErr, ErrorSym);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001773 return;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001774 }
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001775
Ted Kremenek70a733e2008-07-18 17:24:20 +00001776 // Consult the summary for the return value.
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001777 RetEffect RE = GetRetEffect(Summ);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001778
1779 switch (RE.getKind()) {
1780 default:
1781 assert (false && "Unhandled RetEffect."); break;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001782
Ted Kremenekfd301942008-10-17 22:23:12 +00001783 case RetEffect::NoRet: {
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001784
Ted Kremenekf9561e52008-04-11 20:23:24 +00001785 // Make up a symbol for the return value (not reference counted).
Ted Kremenekb8873552008-04-11 20:51:02 +00001786 // FIXME: This is basically copy-and-paste from GRSimpleVals. We
1787 // should compose behavior, not copy it.
Ted Kremenekf9561e52008-04-11 20:23:24 +00001788
Ted Kremenekfd301942008-10-17 22:23:12 +00001789 // FIXME: We eventually should handle structs and other compound types
1790 // that are returned by value.
1791
1792 QualType T = Ex->getType();
1793
Ted Kremenek062e2f92008-11-13 06:10:40 +00001794 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())) {
Ted Kremenekf9561e52008-04-11 20:23:24 +00001795 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenek2dabd432008-12-05 02:27:51 +00001796 SymbolRef Sym = Eng.getSymbolManager().getConjuredSymbol(Ex, Count);
Ted Kremenekf9561e52008-04-11 20:23:24 +00001797
Ted Kremenekc3cf7b22009-02-20 00:05:35 +00001798 SVal X = Loc::IsLocType(T)
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001799 ? cast<SVal>(loc::SymbolVal(Sym))
1800 : cast<SVal>(nonloc::SymbolVal(Sym));
Ted Kremenekf9561e52008-04-11 20:23:24 +00001801
Ted Kremeneka441b7e2008-11-12 19:22:09 +00001802 state = state.BindExpr(Ex, X, false);
Ted Kremenekf9561e52008-04-11 20:23:24 +00001803 }
1804
Ted Kremenek940b1d82008-04-10 23:44:06 +00001805 break;
Ted Kremenekfd301942008-10-17 22:23:12 +00001806 }
Ted Kremenek940b1d82008-04-10 23:44:06 +00001807
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001808 case RetEffect::Alias: {
Ted Kremenek553cf182008-06-25 21:21:56 +00001809 unsigned idx = RE.getIndex();
Ted Kremenek55499762008-06-17 02:43:46 +00001810 assert (arg_end >= arg_beg);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001811 assert (idx < (unsigned) (arg_end - arg_beg));
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00001812 SVal V = state.GetSValAsScalarOrLoc(*(arg_beg+idx));
Ted Kremeneka441b7e2008-11-12 19:22:09 +00001813 state = state.BindExpr(Ex, V, false);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001814 break;
1815 }
1816
Ted Kremenek14993892008-05-06 02:41:27 +00001817 case RetEffect::ReceiverAlias: {
1818 assert (Receiver);
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00001819 SVal V = state.GetSValAsScalarOrLoc(Receiver);
Ted Kremeneka441b7e2008-11-12 19:22:09 +00001820 state = state.BindExpr(Ex, V, false);
Ted Kremenek14993892008-05-06 02:41:27 +00001821 break;
1822 }
1823
Ted Kremeneka7344702008-06-23 18:02:52 +00001824 case RetEffect::OwnedAllocatedSymbol:
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001825 case RetEffect::OwnedSymbol: {
1826 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenek2dabd432008-12-05 02:27:51 +00001827 SymbolRef Sym = Eng.getSymbolManager().getConjuredSymbol(Ex, Count);
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001828 QualType RetT = GetReturnType(Ex, Eng.getContext());
1829 state =
1830 state.set<RefBindings>(Sym, RefVal::makeOwned(RE.getObjKind(), RetT));
Ted Kremeneka441b7e2008-11-12 19:22:09 +00001831 state = state.BindExpr(Ex, loc::SymbolVal(Sym), false);
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001832
Ted Kremeneka7344702008-06-23 18:02:52 +00001833 // FIXME: Add a flag to the checker where allocations are allowed to fail.
Ted Kremenekb2bf7cd2009-01-28 22:27:59 +00001834 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) {
1835 bool isFeasible;
1836 state = state.Assume(loc::SymbolVal(Sym), true, isFeasible);
1837 assert(isFeasible && "Cannot assume fresh symbol is non-null.");
1838 }
Ted Kremeneka7344702008-06-23 18:02:52 +00001839
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001840 break;
1841 }
1842
1843 case RetEffect::NotOwnedSymbol: {
1844 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenek2dabd432008-12-05 02:27:51 +00001845 SymbolRef Sym = Eng.getSymbolManager().getConjuredSymbol(Ex, Count);
Ted Kremenek553cf182008-06-25 21:21:56 +00001846 QualType RetT = GetReturnType(Ex, Eng.getContext());
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001847
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001848 state =
1849 state.set<RefBindings>(Sym, RefVal::makeNotOwned(RE.getObjKind(),RetT));
Ted Kremeneka441b7e2008-11-12 19:22:09 +00001850 state = state.BindExpr(Ex, loc::SymbolVal(Sym), false);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001851 break;
1852 }
1853 }
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001854
Ted Kremenekf5b34b12009-02-18 02:00:25 +00001855 // Generate a sink node if we are at the end of a path.
1856 GRExprEngine::NodeTy *NewNode =
1857 IsEndPath(Summ) ? Builder.MakeSinkNode(Dst, Ex, Pred, state)
1858 : Builder.MakeNode(Dst, Ex, Pred, state);
1859
1860 // Annotate the edge with summary we used.
1861 // FIXME: This assumes that we always use the same summary when generating
1862 // this node.
1863 if (NewNode) SummaryLog[NewNode] = Summ;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001864}
1865
1866
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001867void CFRefCount::EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001868 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001869 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001870 CallExpr* CE, SVal L,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001871 ExplodedNode<GRState>* Pred) {
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001872
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001873 RetainSummary* Summ = !isa<loc::FuncVal>(L) ? 0
1874 : Summaries.getSummary(cast<loc::FuncVal>(L).getDecl());
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001875
1876 EvalSummary(Dst, Eng, Builder, CE, 0, Summ,
1877 CE->arg_begin(), CE->arg_end(), Pred);
Ted Kremenek2fff37e2008-03-06 00:08:09 +00001878}
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001879
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001880void CFRefCount::EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek85348202008-04-15 23:44:31 +00001881 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001882 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek85348202008-04-15 23:44:31 +00001883 ObjCMessageExpr* ME,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001884 ExplodedNode<GRState>* Pred) {
Ted Kremenekb3095252008-05-06 04:20:12 +00001885 RetainSummary* Summ;
Ted Kremenek9040c652008-05-01 21:31:50 +00001886
Ted Kremenek553cf182008-06-25 21:21:56 +00001887 if (Expr* Receiver = ME->getReceiver()) {
1888 // We need the type-information of the tracked receiver object
1889 // Retrieve it from the state.
1890 ObjCInterfaceDecl* ID = 0;
1891
1892 // FIXME: Wouldn't it be great if this code could be reduced? It's just
1893 // a chain of lookups.
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001894 const GRState* St = Builder.GetState(Pred);
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00001895 SVal V = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
Ted Kremenek553cf182008-06-25 21:21:56 +00001896
Ted Kremenek94c96982009-03-03 22:06:47 +00001897 SymbolRef Sym = V.getAsLocSymbol();
1898 if (Sym.isValid()) {
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001899 if (const RefVal* T = St->get<RefBindings>(Sym)) {
Ted Kremeneke8fdc832008-07-07 16:21:19 +00001900 QualType Ty = T->getType();
Ted Kremenek553cf182008-06-25 21:21:56 +00001901
1902 if (const PointerType* PT = Ty->getAsPointerType()) {
1903 QualType PointeeTy = PT->getPointeeType();
1904
1905 if (ObjCInterfaceType* IT = dyn_cast<ObjCInterfaceType>(PointeeTy))
1906 ID = IT->getDecl();
1907 }
1908 }
1909 }
1910
1911 Summ = Summaries.getMethodSummary(ME, ID);
Ted Kremenekf9790ae2008-10-24 20:32:50 +00001912
Ted Kremenek896cd9d2008-10-23 01:56:15 +00001913 // Special-case: are we sending a mesage to "self"?
1914 // This is a hack. When we have full-IP this should be removed.
1915 if (!Summ) {
1916 ObjCMethodDecl* MD =
1917 dyn_cast<ObjCMethodDecl>(&Eng.getGraph().getCodeDecl());
1918
1919 if (MD) {
1920 if (Expr* Receiver = ME->getReceiver()) {
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00001921 SVal X = Eng.getStateManager().GetSValAsScalarOrLoc(St, Receiver);
Ted Kremenek896cd9d2008-10-23 01:56:15 +00001922 if (loc::MemRegionVal* L = dyn_cast<loc::MemRegionVal>(&X))
Ted Kremenekf9790ae2008-10-24 20:32:50 +00001923 if (L->getRegion() == Eng.getStateManager().getSelfRegion(St)) {
1924 // Create a summmary where all of the arguments "StopTracking".
1925 Summ = Summaries.getPersistentSummary(RetEffect::MakeNoRet(),
1926 DoNothing,
1927 StopTracking);
1928 }
Ted Kremenek896cd9d2008-10-23 01:56:15 +00001929 }
1930 }
1931 }
Ted Kremenek553cf182008-06-25 21:21:56 +00001932 }
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001933 else
Ted Kremenek1f180c32008-06-23 22:21:20 +00001934 Summ = Summaries.getClassMethodSummary(ME->getClassName(),
1935 ME->getSelector());
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001936
Ted Kremenekb3095252008-05-06 04:20:12 +00001937 EvalSummary(Dst, Eng, Builder, ME, ME->getReceiver(), Summ,
1938 ME->arg_begin(), ME->arg_end(), Pred);
Ted Kremenek85348202008-04-15 23:44:31 +00001939}
Ted Kremenek5216ad72009-02-14 03:16:10 +00001940
1941namespace {
1942class VISIBILITY_HIDDEN StopTrackingCallback : public SymbolVisitor {
1943 GRStateRef state;
1944public:
1945 StopTrackingCallback(GRStateRef st) : state(st) {}
1946 GRStateRef getState() { return state; }
1947
1948 bool VisitSymbol(SymbolRef sym) {
1949 state = state.remove<RefBindings>(sym);
1950 return true;
1951 }
Ted Kremenekb3095252008-05-06 04:20:12 +00001952
Ted Kremenek5216ad72009-02-14 03:16:10 +00001953 const GRState* getState() const { return state.getState(); }
1954};
1955} // end anonymous namespace
1956
1957
Ted Kremenek41573eb2009-02-14 01:43:44 +00001958void CFRefCount::EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val) {
Ted Kremenek41573eb2009-02-14 01:43:44 +00001959 // Are we storing to something that causes the value to "escape"?
Ted Kremenek13922612008-04-16 20:40:59 +00001960 bool escapes = false;
1961
Ted Kremeneka496d162008-10-18 03:49:51 +00001962 // A value escapes in three possible cases (this may change):
1963 //
1964 // (1) we are binding to something that is not a memory region.
1965 // (2) we are binding to a memregion that does not have stack storage
1966 // (3) we are binding to a memregion with stack storage that the store
Ted Kremenek41573eb2009-02-14 01:43:44 +00001967 // does not understand.
Ted Kremenek41573eb2009-02-14 01:43:44 +00001968 GRStateRef state = B.getState();
Ted Kremeneka496d162008-10-18 03:49:51 +00001969
Ted Kremenek41573eb2009-02-14 01:43:44 +00001970 if (!isa<loc::MemRegionVal>(location))
Ted Kremenek13922612008-04-16 20:40:59 +00001971 escapes = true;
Ted Kremenek9e240492008-10-04 05:50:14 +00001972 else {
Ted Kremenek41573eb2009-02-14 01:43:44 +00001973 const MemRegion* R = cast<loc::MemRegionVal>(location).getRegion();
1974 escapes = !B.getStateManager().hasStackStorage(R);
Ted Kremeneka496d162008-10-18 03:49:51 +00001975
1976 if (!escapes) {
1977 // To test (3), generate a new state with the binding removed. If it is
1978 // the same state, then it escapes (since the store cannot represent
1979 // the binding).
Ted Kremenek41573eb2009-02-14 01:43:44 +00001980 escapes = (state == (state.BindLoc(cast<Loc>(location), UnknownVal())));
Ted Kremeneka496d162008-10-18 03:49:51 +00001981 }
Ted Kremenek9e240492008-10-04 05:50:14 +00001982 }
Ted Kremenek41573eb2009-02-14 01:43:44 +00001983
Ted Kremenek5216ad72009-02-14 03:16:10 +00001984 // If our store can represent the binding and we aren't storing to something
1985 // that doesn't have local storage then just return and have the simulation
1986 // state continue as is.
1987 if (!escapes)
1988 return;
Ted Kremeneka496d162008-10-18 03:49:51 +00001989
Ted Kremenek5216ad72009-02-14 03:16:10 +00001990 // Otherwise, find all symbols referenced by 'val' that we are tracking
1991 // and stop tracking them.
1992 B.MakeNode(state.scanReachableSymbols<StopTrackingCallback>(val).getState());
Ted Kremenekdb863712008-04-16 22:32:20 +00001993}
1994
Ted Kremenekf9790ae2008-10-24 20:32:50 +00001995std::pair<GRStateRef,bool>
1996CFRefCount::HandleSymbolDeath(GRStateManager& VMgr,
1997 const GRState* St, const Decl* CD,
Ted Kremenek2dabd432008-12-05 02:27:51 +00001998 SymbolRef sid,
Ted Kremenekf9790ae2008-10-24 20:32:50 +00001999 RefVal V, bool& hasLeak) {
Ted Kremenekdb863712008-04-16 22:32:20 +00002000
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002001 GRStateRef state(St, VMgr);
Sanjiv Gupta31fc07d2008-10-31 09:52:39 +00002002 assert ((!V.isReturnedOwned() || CD) &&
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00002003 "CodeDecl must be available for reporting ReturnOwned errors.");
Ted Kremenek896cd9d2008-10-23 01:56:15 +00002004
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00002005 if (V.isReturnedOwned() && V.getCount() == 0)
2006 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
Chris Lattner077bf5e2008-11-24 03:33:13 +00002007 std::string s = MD->getSelector().getAsString();
Ted Kremenek4c79e552008-11-05 16:54:44 +00002008 if (!followsReturnRule(s.c_str())) {
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00002009 hasLeak = true;
Ted Kremenekf9790ae2008-10-24 20:32:50 +00002010 state = state.set<RefBindings>(sid, V ^ RefVal::ErrorLeakReturned);
2011 return std::make_pair(state, true);
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00002012 }
2013 }
Ted Kremenek896cd9d2008-10-23 01:56:15 +00002014
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00002015 // All other cases.
2016
2017 hasLeak = V.isOwned() ||
2018 ((V.isNotOwned() || V.isReturnedOwned()) && V.getCount() > 0);
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002019
Ted Kremenekdb863712008-04-16 22:32:20 +00002020 if (!hasLeak)
Ted Kremenekf9790ae2008-10-24 20:32:50 +00002021 return std::make_pair(state.remove<RefBindings>(sid), false);
Ted Kremenekdb863712008-04-16 22:32:20 +00002022
Ted Kremenekf9790ae2008-10-24 20:32:50 +00002023 return std::make_pair(state.set<RefBindings>(sid, V ^ RefVal::ErrorLeak),
2024 false);
Ted Kremenekdb863712008-04-16 22:32:20 +00002025}
2026
Ted Kremenek652adc62008-04-24 23:57:27 +00002027
Ted Kremeneke7bd9c22008-04-11 22:25:11 +00002028
Ted Kremenek652adc62008-04-24 23:57:27 +00002029// Dead symbols.
2030
Ted Kremenekcf701772009-02-05 06:50:21 +00002031
Ted Kremenek652adc62008-04-24 23:57:27 +00002032
Ted Kremenek4fd88972008-04-17 18:12:53 +00002033 // Return statements.
2034
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002035void CFRefCount::EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4fd88972008-04-17 18:12:53 +00002036 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002037 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4fd88972008-04-17 18:12:53 +00002038 ReturnStmt* S,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002039 ExplodedNode<GRState>* Pred) {
Ted Kremenek4fd88972008-04-17 18:12:53 +00002040
2041 Expr* RetE = S->getRetValue();
Ted Kremenek94c96982009-03-03 22:06:47 +00002042 if (!RetE)
Ted Kremenek4fd88972008-04-17 18:12:53 +00002043 return;
2044
Ted Kremenek94c96982009-03-03 22:06:47 +00002045 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00002046 SymbolRef Sym = state.GetSValAsScalarOrLoc(RetE).getAsLocSymbol();
Ted Kremenek94c96982009-03-03 22:06:47 +00002047
2048 if (!Sym.isValid())
2049 return;
2050
Ted Kremenek4fd88972008-04-17 18:12:53 +00002051 // Get the reference count binding (if any).
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002052 const RefVal* T = state.get<RefBindings>(Sym);
Ted Kremenek4fd88972008-04-17 18:12:53 +00002053
2054 if (!T)
2055 return;
2056
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002057 // Change the reference count.
Ted Kremeneke8fdc832008-07-07 16:21:19 +00002058 RefVal X = *T;
Ted Kremenek4fd88972008-04-17 18:12:53 +00002059
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002060 switch (X.getKind()) {
Ted Kremenek4fd88972008-04-17 18:12:53 +00002061 case RefVal::Owned: {
2062 unsigned cnt = X.getCount();
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00002063 assert (cnt > 0);
2064 X = RefVal::makeReturnedOwned(cnt - 1);
Ted Kremenek4fd88972008-04-17 18:12:53 +00002065 break;
2066 }
2067
2068 case RefVal::NotOwned: {
2069 unsigned cnt = X.getCount();
2070 X = cnt ? RefVal::makeReturnedOwned(cnt - 1)
2071 : RefVal::makeReturnedNotOwned();
2072 break;
2073 }
2074
2075 default:
Ted Kremenek4fd88972008-04-17 18:12:53 +00002076 return;
2077 }
2078
2079 // Update the binding.
Ted Kremenekb9d17f92008-08-17 03:20:02 +00002080 state = state.set<RefBindings>(Sym, X);
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002081 Builder.MakeNode(Dst, S, Pred, state);
Ted Kremenek4fd88972008-04-17 18:12:53 +00002082}
2083
Ted Kremenekcb612922008-04-18 19:23:43 +00002084// Assumptions.
2085
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002086const GRState* CFRefCount::EvalAssume(GRStateManager& VMgr,
2087 const GRState* St,
Zhongxing Xu1c96b242008-10-17 05:57:07 +00002088 SVal Cond, bool Assumption,
Ted Kremenek4323a572008-07-10 22:03:41 +00002089 bool& isFeasible) {
Ted Kremenekcb612922008-04-18 19:23:43 +00002090
2091 // FIXME: We may add to the interface of EvalAssume the list of symbols
2092 // whose assumptions have changed. For now we just iterate through the
2093 // bindings and check if any of the tracked symbols are NULL. This isn't
2094 // too bad since the number of symbols we will track in practice are
2095 // probably small and EvalAssume is only called at branches and a few
2096 // other places.
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002097 RefBindings B = St->get<RefBindings>();
Ted Kremenekcb612922008-04-18 19:23:43 +00002098
2099 if (B.isEmpty())
2100 return St;
2101
2102 bool changed = false;
Ted Kremenekb9d17f92008-08-17 03:20:02 +00002103
2104 GRStateRef state(St, VMgr);
2105 RefBindings::Factory& RefBFactory = state.get_context<RefBindings>();
Ted Kremenekcb612922008-04-18 19:23:43 +00002106
2107 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
Ted Kremenekcb612922008-04-18 19:23:43 +00002108 // Check if the symbol is null (or equal to any constant).
2109 // If this is the case, stop tracking the symbol.
Zhongxing Xu39cfed32008-08-29 14:52:36 +00002110 if (VMgr.getSymVal(St, I.getKey())) {
Ted Kremenekcb612922008-04-18 19:23:43 +00002111 changed = true;
2112 B = RefBFactory.Remove(B, I.getKey());
2113 }
2114 }
2115
Ted Kremenekb9d17f92008-08-17 03:20:02 +00002116 if (changed)
2117 state = state.set<RefBindings>(B);
Ted Kremenekcb612922008-04-18 19:23:43 +00002118
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002119 return state;
Ted Kremenekcb612922008-04-18 19:23:43 +00002120}
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00002121
Ted Kremenek4d3957d2009-02-24 19:15:11 +00002122GRStateRef CFRefCount::Update(GRStateRef state, SymbolRef sym,
2123 RefVal V, ArgEffect E,
2124 RefVal::Kind& hasErr) {
Ted Kremenek1c512f52009-02-18 18:54:33 +00002125
2126 // In GC mode [... release] and [... retain] do nothing.
2127 switch (E) {
2128 default: break;
2129 case IncRefMsg: E = isGCEnabled() ? DoNothing : IncRef; break;
2130 case DecRefMsg: E = isGCEnabled() ? DoNothing : DecRef; break;
Ted Kremenek27019002009-02-18 21:57:45 +00002131 case MakeCollectable: E = isGCEnabled() ? DecRef : DoNothing; break;
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00002132 case NewAutoreleasePool: E = isGCEnabled() ? DoNothing :
2133 NewAutoreleasePool; break;
Ted Kremenek1c512f52009-02-18 18:54:33 +00002134 }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00002135
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002136 switch (E) {
2137 default:
2138 assert (false && "Unhandled CFRef transition.");
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00002139
Ted Kremenek35790732009-02-25 23:11:49 +00002140 case NewAutoreleasePool:
2141 assert(!isGCEnabled());
2142 return state.add<AutoreleaseStack>(sym);
2143
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00002144 case MayEscape:
2145 if (V.getKind() == RefVal::Owned) {
Ted Kremenek553cf182008-06-25 21:21:56 +00002146 V = V ^ RefVal::NotOwned;
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00002147 break;
2148 }
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00002149 // Fall-through.
Ted Kremenek6c4becb2009-02-25 02:54:57 +00002150
Ted Kremenek070a8252008-07-09 18:11:16 +00002151 case DoNothingByRef:
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002152 case DoNothing:
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002153 if (!isGCEnabled() && V.getKind() == RefVal::Released) {
Ted Kremenek553cf182008-06-25 21:21:56 +00002154 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek9ed18e62008-04-16 04:28:53 +00002155 hasErr = V.getKind();
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002156 break;
Ted Kremenek9e476de2008-08-12 18:30:56 +00002157 }
Ted Kremenek4d3957d2009-02-24 19:15:11 +00002158 return state;
Ted Kremeneke19f4492008-06-30 16:57:41 +00002159
Ted Kremenekabf43972009-01-28 21:44:40 +00002160 case Autorelease:
Ted Kremenek4d3957d2009-02-24 19:15:11 +00002161 if (isGCEnabled()) return state;
Ted Kremenekabf43972009-01-28 21:44:40 +00002162 // Fall-through.
Ted Kremenek14993892008-05-06 02:41:27 +00002163 case StopTracking:
Ted Kremenek4d3957d2009-02-24 19:15:11 +00002164 return state.remove<RefBindings>(sym);
Ted Kremenek9e476de2008-08-12 18:30:56 +00002165
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002166 case IncRef:
2167 switch (V.getKind()) {
2168 default:
2169 assert(false);
2170
2171 case RefVal::Owned:
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002172 case RefVal::NotOwned:
Ted Kremenek553cf182008-06-25 21:21:56 +00002173 V = V + 1;
Ted Kremenek9e476de2008-08-12 18:30:56 +00002174 break;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002175 case RefVal::Released:
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002176 if (isGCEnabled())
Ted Kremenekbb8c5aa2009-02-18 22:57:22 +00002177 V = (V ^ RefVal::Owned) + 1;
Ted Kremenek65c91652008-04-29 05:44:10 +00002178 else {
Ted Kremenek553cf182008-06-25 21:21:56 +00002179 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek65c91652008-04-29 05:44:10 +00002180 hasErr = V.getKind();
2181 }
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002182 break;
Ted Kremenek9e476de2008-08-12 18:30:56 +00002183 }
Ted Kremenek940b1d82008-04-10 23:44:06 +00002184 break;
2185
Ted Kremenek553cf182008-06-25 21:21:56 +00002186 case SelfOwn:
2187 V = V ^ RefVal::NotOwned;
Ted Kremenek1c512f52009-02-18 18:54:33 +00002188 // Fall-through.
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002189 case DecRef:
2190 switch (V.getKind()) {
2191 default:
2192 assert (false);
Ted Kremenek9e476de2008-08-12 18:30:56 +00002193
Ted Kremenek553cf182008-06-25 21:21:56 +00002194 case RefVal::Owned:
Ted Kremenekbb8c5aa2009-02-18 22:57:22 +00002195 assert(V.getCount() > 0);
2196 if (V.getCount() == 1) V = V ^ RefVal::Released;
2197 V = V - 1;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002198 break;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002199
Ted Kremenek553cf182008-06-25 21:21:56 +00002200 case RefVal::NotOwned:
2201 if (V.getCount() > 0)
2202 V = V - 1;
Ted Kremenek61b9f872008-04-10 23:09:18 +00002203 else {
Ted Kremenek553cf182008-06-25 21:21:56 +00002204 V = V ^ RefVal::ErrorReleaseNotOwned;
Ted Kremenek9ed18e62008-04-16 04:28:53 +00002205 hasErr = V.getKind();
Ted Kremenek9e476de2008-08-12 18:30:56 +00002206 }
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002207 break;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002208
2209 case RefVal::Released:
Ted Kremenek553cf182008-06-25 21:21:56 +00002210 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek9ed18e62008-04-16 04:28:53 +00002211 hasErr = V.getKind();
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002212 break;
Ted Kremenek9e476de2008-08-12 18:30:56 +00002213 }
Ted Kremenek940b1d82008-04-10 23:44:06 +00002214 break;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002215 }
Ted Kremenek4d3957d2009-02-24 19:15:11 +00002216 return state.set<RefBindings>(sym, V);
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00002217}
2218
Ted Kremenekfa34b332008-04-09 01:10:13 +00002219//===----------------------------------------------------------------------===//
Ted Kremenek05cbe1a2008-04-09 23:49:11 +00002220// Error reporting.
Ted Kremenekfa34b332008-04-09 01:10:13 +00002221//===----------------------------------------------------------------------===//
2222
Ted Kremenek8dd56462008-04-18 03:39:05 +00002223namespace {
2224
2225 //===-------------===//
2226 // Bug Descriptions. //
2227 //===-------------===//
2228
Ted Kremenekcf118d42009-02-04 23:49:09 +00002229 class VISIBILITY_HIDDEN CFRefBug : public BugType {
Ted Kremenek8dd56462008-04-18 03:39:05 +00002230 protected:
2231 CFRefCount& TF;
Ted Kremenekcf118d42009-02-04 23:49:09 +00002232
2233 CFRefBug(CFRefCount* tf, const char* name)
2234 : BugType(name, "Memory (Core Foundation/Objective-C)"), TF(*tf) {}
Ted Kremenek8dd56462008-04-18 03:39:05 +00002235 public:
Ted Kremenek072192b2008-04-30 23:47:44 +00002236
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00002237 CFRefCount& getTF() { return TF; }
Ted Kremenek789deac2008-05-05 23:16:31 +00002238 const CFRefCount& getTF() const { return TF; }
2239
Ted Kremenekcf118d42009-02-04 23:49:09 +00002240 // FIXME: Eventually remove.
2241 virtual const char* getDescription() const = 0;
2242
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00002243 virtual bool isLeak() const { return false; }
Ted Kremenek8dd56462008-04-18 03:39:05 +00002244 };
2245
2246 class VISIBILITY_HIDDEN UseAfterRelease : public CFRefBug {
2247 public:
Ted Kremenekcf118d42009-02-04 23:49:09 +00002248 UseAfterRelease(CFRefCount* tf)
2249 : CFRefBug(tf, "use-after-release") {}
Ted Kremenek8dd56462008-04-18 03:39:05 +00002250
Ted Kremenekcf118d42009-02-04 23:49:09 +00002251 const char* getDescription() const {
Ted Kremeneke1981162009-02-26 21:04:07 +00002252 return "Reference-counted object is used after it is released";
Ted Kremenekcf701772009-02-05 06:50:21 +00002253 }
Ted Kremenek8dd56462008-04-18 03:39:05 +00002254 };
2255
2256 class VISIBILITY_HIDDEN BadRelease : public CFRefBug {
2257 public:
Ted Kremenekcf118d42009-02-04 23:49:09 +00002258 BadRelease(CFRefCount* tf) : CFRefBug(tf, "bad release") {}
2259
2260 const char* getDescription() const {
Ted Kremenek8dd56462008-04-18 03:39:05 +00002261 return "Incorrect decrement of the reference count of a "
Ted Kremeneke1981162009-02-26 21:04:07 +00002262 "Core Foundation object ("
2263 "the object is not owned at this point by the caller)";
Ted Kremenek8dd56462008-04-18 03:39:05 +00002264 }
Ted Kremenek8dd56462008-04-18 03:39:05 +00002265 };
2266
2267 class VISIBILITY_HIDDEN Leak : public CFRefBug {
Ted Kremenekcf118d42009-02-04 23:49:09 +00002268 const bool isReturn;
2269 protected:
2270 Leak(CFRefCount* tf, const char* name, bool isRet)
2271 : CFRefBug(tf, name), isReturn(isRet) {}
Ted Kremenek8dd56462008-04-18 03:39:05 +00002272 public:
Ted Kremenek8dd56462008-04-18 03:39:05 +00002273
Ted Kremenekd3057212009-02-07 22:38:00 +00002274 const char* getDescription() const { return ""; }
Ted Kremenek3148eb42009-01-24 00:55:43 +00002275
Ted Kremeneke45e57f2009-02-05 00:38:00 +00002276 bool isLeak() const { return true; }
Ted Kremenek8dd56462008-04-18 03:39:05 +00002277 };
Ted Kremenekcf118d42009-02-04 23:49:09 +00002278
2279 class VISIBILITY_HIDDEN LeakAtReturn : public Leak {
2280 public:
2281 LeakAtReturn(CFRefCount* tf, const char* name)
2282 : Leak(tf, name, true) {}
2283 };
2284
2285 class VISIBILITY_HIDDEN LeakWithinFunction : public Leak {
2286 public:
2287 LeakWithinFunction(CFRefCount* tf, const char* name)
2288 : Leak(tf, name, false) {}
2289 };
Ted Kremenek8dd56462008-04-18 03:39:05 +00002290
2291 //===---------===//
2292 // Bug Reports. //
2293 //===---------===//
2294
2295 class VISIBILITY_HIDDEN CFRefReport : public RangedBugReport {
Ted Kremenek66d97062009-02-07 22:04:05 +00002296 protected:
Ted Kremenek2dabd432008-12-05 02:27:51 +00002297 SymbolRef Sym;
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002298 const CFRefCount &TF;
Ted Kremenek8dd56462008-04-18 03:39:05 +00002299 public:
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002300 CFRefReport(CFRefBug& D, const CFRefCount &tf,
2301 ExplodedNode<GRState> *n, SymbolRef sym)
2302 : RangedBugReport(D, D.getDescription(), n), Sym(sym), TF(tf) {}
Ted Kremenek8dd56462008-04-18 03:39:05 +00002303
2304 virtual ~CFRefReport() {}
2305
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00002306 CFRefBug& getBugType() {
2307 return (CFRefBug&) RangedBugReport::getBugType();
2308 }
2309 const CFRefBug& getBugType() const {
2310 return (const CFRefBug&) RangedBugReport::getBugType();
2311 }
2312
2313 virtual void getRanges(BugReporter& BR, const SourceRange*& beg,
2314 const SourceRange*& end) {
2315
Ted Kremeneke92c1b22008-05-02 20:53:50 +00002316 if (!getBugType().isLeak())
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00002317 RangedBugReport::getRanges(BR, beg, end);
Ted Kremenek9e476de2008-08-12 18:30:56 +00002318 else
2319 beg = end = 0;
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00002320 }
2321
Ted Kremenek2dabd432008-12-05 02:27:51 +00002322 SymbolRef getSymbol() const { return Sym; }
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002323
Ted Kremenek3148eb42009-01-24 00:55:43 +00002324 PathDiagnosticPiece* getEndPath(BugReporter& BR,
2325 const ExplodedNode<GRState>* N);
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00002326
Ted Kremenek3148eb42009-01-24 00:55:43 +00002327 std::pair<const char**,const char**> getExtraDescriptiveText();
Ted Kremenek8dd56462008-04-18 03:39:05 +00002328
Ted Kremenek3148eb42009-01-24 00:55:43 +00002329 PathDiagnosticPiece* VisitNode(const ExplodedNode<GRState>* N,
2330 const ExplodedNode<GRState>* PrevN,
2331 const ExplodedGraph<GRState>& G,
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002332 BugReporter& BR,
2333 NodeResolver& NR);
Ted Kremenek8dd56462008-04-18 03:39:05 +00002334 };
2335
Ted Kremenekcf118d42009-02-04 23:49:09 +00002336 class VISIBILITY_HIDDEN CFRefLeakReport : public CFRefReport {
Ted Kremeneke469fa02009-02-07 22:19:59 +00002337 SourceLocation AllocSite;
2338 const MemRegion* AllocBinding;
Ted Kremenekcf118d42009-02-04 23:49:09 +00002339 public:
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002340 CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2341 ExplodedNode<GRState> *n, SymbolRef sym,
Ted Kremenekd3057212009-02-07 22:38:00 +00002342 GRExprEngine& Eng);
Ted Kremenek66d97062009-02-07 22:04:05 +00002343
2344 PathDiagnosticPiece* getEndPath(BugReporter& BR,
2345 const ExplodedNode<GRState>* N);
2346
Ted Kremeneke469fa02009-02-07 22:19:59 +00002347 SourceLocation getLocation() const { return AllocSite; }
Ted Kremenekcf118d42009-02-04 23:49:09 +00002348 };
Ted Kremenek8dd56462008-04-18 03:39:05 +00002349} // end anonymous namespace
2350
Ted Kremenekcf118d42009-02-04 23:49:09 +00002351void CFRefCount::RegisterChecks(BugReporter& BR) {
Ted Kremenekcf701772009-02-05 06:50:21 +00002352 useAfterRelease = new UseAfterRelease(this);
2353 BR.Register(useAfterRelease);
2354
2355 releaseNotOwned = new BadRelease(this);
2356 BR.Register(releaseNotOwned);
Ted Kremenekcf118d42009-02-04 23:49:09 +00002357
2358 // First register "return" leaks.
2359 const char* name = 0;
2360
2361 if (isGCEnabled())
2362 name = "[naming convention] leak of returned object (GC)";
2363 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2364 name = "[naming convention] leak of returned object (hybrid MM, "
2365 "non-GC)";
2366 else {
2367 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2368 name = "[naming convention] leak of returned object";
2369 }
2370
Ted Kremenekcf701772009-02-05 06:50:21 +00002371 leakAtReturn = new LeakAtReturn(this, name);
2372 BR.Register(leakAtReturn);
Ted Kremenek8dd56462008-04-18 03:39:05 +00002373
Ted Kremenekcf118d42009-02-04 23:49:09 +00002374 // Second, register leaks within a function/method.
2375 if (isGCEnabled())
2376 name = "leak (GC)";
2377 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2378 name = "leak (hybrid MM, non-GC)";
2379 else {
2380 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2381 name = "leak";
2382 }
2383
Ted Kremenekcf701772009-02-05 06:50:21 +00002384 leakWithinFunction = new LeakWithinFunction(this, name);
2385 BR.Register(leakWithinFunction);
2386
2387 // Save the reference to the BugReporter.
2388 this->BR = &BR;
Ted Kremenekcf118d42009-02-04 23:49:09 +00002389}
Ted Kremenek072192b2008-04-30 23:47:44 +00002390
2391static const char* Msgs[] = {
Ted Kremeneke1981162009-02-26 21:04:07 +00002392 // GC only
2393 "Code is compiled to only use garbage collection",
2394 // No GC.
Ted Kremenek452c31e2009-03-05 00:12:45 +00002395 "Code is compiled to use reference counts",
Ted Kremeneke1981162009-02-26 21:04:07 +00002396 // Hybrid, with GC.
2397 "Code is compiled to use either garbage collection (GC) or reference counts"
2398 " (non-GC). The bug occurs with GC enabled",
2399 // Hybrid, without GC
2400 "Code is compiled to use either garbage collection (GC) or reference counts"
2401 " (non-GC). The bug occurs in non-GC mode"
Ted Kremenek072192b2008-04-30 23:47:44 +00002402};
2403
2404std::pair<const char**,const char**> CFRefReport::getExtraDescriptiveText() {
2405 CFRefCount& TF = static_cast<CFRefBug&>(getBugType()).getTF();
2406
2407 switch (TF.getLangOptions().getGCMode()) {
2408 default:
2409 assert(false);
Ted Kremenek31593ac2008-05-01 04:02:04 +00002410
2411 case LangOptions::GCOnly:
2412 assert (TF.isGCEnabled());
Ted Kremenek9e476de2008-08-12 18:30:56 +00002413 return std::make_pair(&Msgs[0], &Msgs[0]+1);
2414
Ted Kremenek072192b2008-04-30 23:47:44 +00002415 case LangOptions::NonGC:
2416 assert (!TF.isGCEnabled());
Ted Kremenek072192b2008-04-30 23:47:44 +00002417 return std::make_pair(&Msgs[1], &Msgs[1]+1);
2418
2419 case LangOptions::HybridGC:
2420 if (TF.isGCEnabled())
2421 return std::make_pair(&Msgs[2], &Msgs[2]+1);
2422 else
2423 return std::make_pair(&Msgs[3], &Msgs[3]+1);
2424 }
2425}
2426
Ted Kremenek27019002009-02-18 21:57:45 +00002427static inline bool contains(const llvm::SmallVectorImpl<ArgEffect>& V,
2428 ArgEffect X) {
2429 for (llvm::SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
2430 I!=E; ++I)
2431 if (*I == X) return true;
2432
2433 return false;
2434}
2435
Ted Kremenek3148eb42009-01-24 00:55:43 +00002436PathDiagnosticPiece* CFRefReport::VisitNode(const ExplodedNode<GRState>* N,
2437 const ExplodedNode<GRState>* PrevN,
2438 const ExplodedGraph<GRState>& G,
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002439 BugReporter& BR,
2440 NodeResolver& NR) {
Ted Kremenek8dd56462008-04-18 03:39:05 +00002441
Ted Kremenek611a15a2009-01-28 05:29:13 +00002442 // Check if the type state has changed.
2443 GRStateManager &StMgr = cast<GRBugReporter>(BR).getStateManager();
2444 GRStateRef PrevSt(PrevN->getState(), StMgr);
2445 GRStateRef CurrSt(N->getState(), StMgr);
Ted Kremenek20982802009-01-28 05:06:46 +00002446
Ted Kremenek611a15a2009-01-28 05:29:13 +00002447 const RefVal* CurrT = CurrSt.get<RefBindings>(Sym);
2448 if (!CurrT) return NULL;
2449
2450 const RefVal& CurrV = *CurrT;
2451 const RefVal* PrevT = PrevSt.get<RefBindings>(Sym);
Ted Kremenekce48e002008-05-05 17:53:17 +00002452
Ted Kremenek27019002009-02-18 21:57:45 +00002453 // Create a string buffer to constain all the useful things we want
2454 // to tell the user.
2455 std::string sbuf;
2456 llvm::raw_string_ostream os(sbuf);
2457
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002458 // This is the allocation site since the previous node had no bindings
2459 // for this symbol.
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002460 if (!PrevT) {
Ted Kremenekce48e002008-05-05 17:53:17 +00002461 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2462
Ted Kremenek5c1cd522009-01-28 05:15:02 +00002463 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2464 // Get the name of the callee (if it is available).
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00002465 SVal X = CurrSt.GetSValAsScalarOrLoc(CE->getCallee());
Ted Kremenek5c1cd522009-01-28 05:15:02 +00002466 if (loc::FuncVal* FV = dyn_cast<loc::FuncVal>(&X))
2467 os << "Call to function '" << FV->getDecl()->getNameAsString() <<'\'';
2468 else
Ted Kremeneka102c0c2009-01-28 06:01:42 +00002469 os << "function call";
Ted Kremenek5c1cd522009-01-28 05:15:02 +00002470 }
2471 else {
2472 assert (isa<ObjCMessageExpr>(S));
Ted Kremeneka102c0c2009-01-28 06:01:42 +00002473 os << "Method";
Ted Kremenekce48e002008-05-05 17:53:17 +00002474 }
Ted Kremenek5c1cd522009-01-28 05:15:02 +00002475
Ted Kremenek961b61d2009-01-28 06:06:36 +00002476 if (CurrV.getObjKind() == RetEffect::CF) {
2477 os << " returns a Core Foundation object with a ";
2478 }
2479 else {
2480 assert (CurrV.getObjKind() == RetEffect::ObjC);
2481 os << " returns an Objective-C object with a ";
2482 }
Ted Kremeneka102c0c2009-01-28 06:01:42 +00002483
Ted Kremenek23b8eaa2009-01-28 06:25:48 +00002484 if (CurrV.isOwned()) {
2485 os << "+1 retain count (owning reference).";
2486
2487 if (static_cast<CFRefBug&>(getBugType()).getTF().isGCEnabled()) {
2488 assert(CurrV.getObjKind() == RetEffect::CF);
2489 os << " "
2490 "Core Foundation objects are not automatically garbage collected.";
2491 }
2492 }
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002493 else {
2494 assert (CurrV.isNotOwned());
Ted Kremenek5c1cd522009-01-28 05:15:02 +00002495 os << "+0 retain count (non-owning reference).";
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002496 }
Ted Kremenekce48e002008-05-05 17:53:17 +00002497
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002498 FullSourceLoc Pos(S->getLocStart(), BR.getContext().getSourceManager());
Ted Kremeneka1f117e2009-01-28 04:47:13 +00002499 PathDiagnosticPiece* P = new PathDiagnosticPiece(Pos, os.str());
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002500
2501 if (Expr* Exp = dyn_cast<Expr>(S))
2502 P->addRange(Exp->getSourceRange());
2503
2504 return P;
2505 }
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002506
Ted Kremenek27019002009-02-18 21:57:45 +00002507 // Gather up the effects that were performed on the object at this
2508 // program point
2509 llvm::SmallVector<ArgEffect, 2> AEffects;
2510
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002511 if (const RetainSummary *Summ = TF.getSummaryOfNode(NR.getOriginalNode(N))) {
2512 // We only have summaries attached to nodes after evaluating CallExpr and
2513 // ObjCMessageExprs.
2514 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2515
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002516 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2517 // Iterate through the parameter expressions and see if the symbol
2518 // was ever passed as an argument.
2519 unsigned i = 0;
2520
2521 for (CallExpr::arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
2522 AI!=AE; ++AI, ++i) {
Ted Kremenek27019002009-02-18 21:57:45 +00002523
Ted Kremenek94c96982009-03-03 22:06:47 +00002524 // Retrieve the value of the argument. Is it the symbol
2525 // we are interested in?
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00002526 if (CurrSt.GetSValAsScalarOrLoc(*AI).getAsLocSymbol() != Sym)
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002527 continue;
Ted Kremenek94c96982009-03-03 22:06:47 +00002528
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002529 // We have an argument. Get the effect!
2530 AEffects.push_back(Summ->getArg(i));
Ted Kremenek79c140b2008-04-18 05:32:44 +00002531 }
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002532 }
2533 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
Ted Kremenek94c96982009-03-03 22:06:47 +00002534 if (Expr *receiver = ME->getReceiver())
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00002535 if (CurrSt.GetSValAsScalarOrLoc(receiver).getAsLocSymbol() == Sym) {
Ted Kremenek27019002009-02-18 21:57:45 +00002536 // The symbol we are tracking is the receiver.
2537 AEffects.push_back(Summ->getReceiverEffect());
2538 }
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002539 }
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002540 }
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002541
Ted Kremenek27019002009-02-18 21:57:45 +00002542 do {
2543 // Get the previous type state.
2544 RefVal PrevV = *PrevT;
2545
2546 // Specially handle CFMakeCollectable and friends.
2547 if (contains(AEffects, MakeCollectable)) {
2548 // Get the name of the function.
2549 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2550 loc::FuncVal FV =
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00002551 cast<loc::FuncVal>(CurrSt.GetSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee()));
Ted Kremenek27019002009-02-18 21:57:45 +00002552 const std::string& FName = FV.getDecl()->getNameAsString();
2553
2554 if (TF.isGCEnabled()) {
2555 // Determine if the object's reference count was pushed to zero.
2556 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2557
2558 os << "In GC mode a call to '" << FName
2559 << "' decrements an object's retain count and registers the "
2560 "object with the garbage collector. ";
2561
Ted Kremenekbb8c5aa2009-02-18 22:57:22 +00002562 if (CurrV.getKind() == RefVal::Released) {
2563 assert(CurrV.getCount() == 0);
2564 os << "Since it now has a 0 retain count the object can be "
Ted Kremenek27019002009-02-18 21:57:45 +00002565 "automatically collected by the garbage collector.";
Ted Kremenekbb8c5aa2009-02-18 22:57:22 +00002566 }
Ted Kremenek27019002009-02-18 21:57:45 +00002567 else
2568 os << "An object must have a 0 retain count to be garbage collected. "
2569 "After this call its retain count is +" << CurrV.getCount()
2570 << '.';
2571 }
2572 else
2573 os << "When GC is not enabled a call to '" << FName
2574 << "' has no effect on its argument.";
2575
2576 // Nothing more to say.
2577 break;
2578 }
2579
2580 // Determine if the typestate has changed.
2581 if (!(PrevV == CurrV))
2582 switch (CurrV.getKind()) {
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002583 case RefVal::Owned:
2584 case RefVal::NotOwned:
2585
2586 if (PrevV.getCount() == CurrV.getCount())
2587 return 0;
2588
2589 if (PrevV.getCount() > CurrV.getCount())
2590 os << "Reference count decremented.";
2591 else
2592 os << "Reference count incremented.";
Ted Kremenekbb8c5aa2009-02-18 22:57:22 +00002593
Ted Kremeneke1981162009-02-26 21:04:07 +00002594 if (unsigned Count = CurrV.getCount())
2595 os << " The object now has a +" << Count << " retain count.";
Ted Kremenekbb8c5aa2009-02-18 22:57:22 +00002596
2597 if (PrevV.getKind() == RefVal::Released) {
2598 assert(TF.isGCEnabled() && CurrV.getCount() > 0);
2599 os << " The object is not eligible for garbage collection until the "
2600 "retain count reaches 0 again.";
2601 }
2602
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002603 break;
2604
2605 case RefVal::Released:
2606 os << "Object released.";
2607 break;
2608
2609 case RefVal::ReturnedOwned:
2610 os << "Object returned to caller as an owning reference (single retain "
2611 "count transferred to caller).";
2612 break;
2613
2614 case RefVal::ReturnedNotOwned:
2615 os << "Object returned to caller with a +0 (non-owning) retain count.";
2616 break;
2617
2618 default:
2619 return NULL;
Ted Kremenek27019002009-02-18 21:57:45 +00002620 }
2621
2622 // Emit any remaining diagnostics for the argument effects (if any).
2623 for (llvm::SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
2624 E=AEffects.end(); I != E; ++I) {
2625
2626 // A bunch of things have alternate behavior under GC.
2627 if (TF.isGCEnabled())
2628 switch (*I) {
2629 default: break;
2630 case Autorelease:
2631 os << "In GC mode an 'autorelease' has no effect.";
2632 continue;
2633 case IncRefMsg:
2634 os << "In GC mode the 'retain' message has no effect.";
2635 continue;
2636 case DecRefMsg:
2637 os << "In GC mode the 'release' message has no effect.";
2638 continue;
2639 }
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002640 }
Ted Kremenek27019002009-02-18 21:57:45 +00002641 } while(0);
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002642
2643 if (os.str().empty())
2644 return 0; // We have nothing to say!
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002645
2646 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2647 FullSourceLoc Pos(S->getLocStart(), BR.getContext().getSourceManager());
Ted Kremeneka1f117e2009-01-28 04:47:13 +00002648 PathDiagnosticPiece* P = new PathDiagnosticPiece(Pos, os.str());
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002649
2650 // Add the range by scanning the children of the statement for any bindings
2651 // to Sym.
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002652 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I)
Ted Kremenek94c96982009-03-03 22:06:47 +00002653 if (Expr* Exp = dyn_cast_or_null<Expr>(*I))
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00002654 if (CurrSt.GetSValAsScalarOrLoc(Exp).getAsLocSymbol() == Sym) {
Ted Kremenek94c96982009-03-03 22:06:47 +00002655 P->addRange(Exp->getSourceRange());
2656 break;
2657 }
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002658
2659 return P;
Ted Kremenek8dd56462008-04-18 03:39:05 +00002660}
2661
Ted Kremenek9e240492008-10-04 05:50:14 +00002662namespace {
2663class VISIBILITY_HIDDEN FindUniqueBinding :
2664 public StoreManager::BindingsHandler {
Ted Kremenek2dabd432008-12-05 02:27:51 +00002665 SymbolRef Sym;
Ted Kremenekbe912242009-03-05 16:31:07 +00002666 const MemRegion* Binding;
Ted Kremenek9e240492008-10-04 05:50:14 +00002667 bool First;
2668
2669 public:
Ted Kremenek2dabd432008-12-05 02:27:51 +00002670 FindUniqueBinding(SymbolRef sym) : Sym(sym), Binding(0), First(true) {}
Ted Kremenek9e240492008-10-04 05:50:14 +00002671
Ted Kremenekbe912242009-03-05 16:31:07 +00002672 bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
2673 SVal val) {
Ted Kremenek94c96982009-03-03 22:06:47 +00002674 SymbolRef SymV = val.getAsSymbol();
2675
2676 if (!SymV.isValid() || SymV != Sym)
Ted Kremenek9e240492008-10-04 05:50:14 +00002677 return true;
Ted Kremenek94c96982009-03-03 22:06:47 +00002678
Ted Kremenek9e240492008-10-04 05:50:14 +00002679 if (Binding) {
2680 First = false;
2681 return false;
2682 }
2683 else
2684 Binding = R;
2685
2686 return true;
2687 }
2688
2689 operator bool() { return First && Binding; }
Ted Kremenekbe912242009-03-05 16:31:07 +00002690 const MemRegion* getRegion() { return Binding; }
Ted Kremenek9e240492008-10-04 05:50:14 +00002691};
2692}
2693
Ted Kremenek3148eb42009-01-24 00:55:43 +00002694static std::pair<const ExplodedNode<GRState>*,const MemRegion*>
Ted Kremeneke469fa02009-02-07 22:19:59 +00002695GetAllocationSite(GRStateManager& StateMgr, const ExplodedNode<GRState>* N,
Ted Kremenek2dabd432008-12-05 02:27:51 +00002696 SymbolRef Sym) {
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002697
Ted Kremenek2bc39c62008-08-29 00:47:32 +00002698 // Find both first node that referred to the tracked symbol and the
2699 // memory location that value was store to.
Ted Kremenek3148eb42009-01-24 00:55:43 +00002700 const ExplodedNode<GRState>* Last = N;
2701 const MemRegion* FirstBinding = 0;
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002702
2703 while (N) {
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002704 const GRState* St = N->getState();
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002705 RefBindings B = St->get<RefBindings>();
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002706
Ted Kremeneke8fdc832008-07-07 16:21:19 +00002707 if (!B.lookup(Sym))
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002708 break;
Ted Kremenek2bc39c62008-08-29 00:47:32 +00002709
Ted Kremeneke469fa02009-02-07 22:19:59 +00002710 FindUniqueBinding FB(Sym);
2711 StateMgr.iterBindings(St, FB);
2712 if (FB) FirstBinding = FB.getRegion();
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002713
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002714 Last = N;
2715 N = N->pred_empty() ? NULL : *(N->pred_begin());
2716 }
2717
Ted Kremenek2bc39c62008-08-29 00:47:32 +00002718 return std::make_pair(Last, FirstBinding);
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002719}
Ted Kremeneka22cc2f2008-05-06 23:07:13 +00002720
Ted Kremenek3148eb42009-01-24 00:55:43 +00002721PathDiagnosticPiece*
2722CFRefReport::getEndPath(BugReporter& br, const ExplodedNode<GRState>* EndN) {
Ted Kremenek1aa44c72008-05-22 23:45:19 +00002723
Ted Kremenek2bc39c62008-08-29 00:47:32 +00002724 GRBugReporter& BR = cast<GRBugReporter>(br);
Ted Kremenek1aa44c72008-05-22 23:45:19 +00002725 // Tell the BugReporter to report cases when the tracked symbol is
2726 // assigned to different variables, etc.
Ted Kremenekc0959972008-07-02 21:24:01 +00002727 cast<GRBugReporter>(BR).addNotableSymbol(Sym);
Ted Kremenek66d97062009-02-07 22:04:05 +00002728 return RangedBugReport::getEndPath(BR, EndN);
2729}
2730
2731PathDiagnosticPiece*
2732CFRefLeakReport::getEndPath(BugReporter& br, const ExplodedNode<GRState>* EndN){
2733
2734 GRBugReporter& BR = cast<GRBugReporter>(br);
2735 // Tell the BugReporter to report cases when the tracked symbol is
2736 // assigned to different variables, etc.
2737 cast<GRBugReporter>(BR).addNotableSymbol(Sym);
2738
2739 // We are reporting a leak. Walk up the graph to get to the first node where
2740 // the symbol appeared, and also get the first VarDecl that tracked object
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002741 // is stored to.
Ted Kremenek3148eb42009-01-24 00:55:43 +00002742 const ExplodedNode<GRState>* AllocNode = 0;
2743 const MemRegion* FirstBinding = 0;
Ted Kremenek2bc39c62008-08-29 00:47:32 +00002744
2745 llvm::tie(AllocNode, FirstBinding) =
Ted Kremeneke469fa02009-02-07 22:19:59 +00002746 GetAllocationSite(BR.getStateManager(), EndN, Sym);
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00002747
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002748 // Get the allocate site.
2749 assert (AllocNode);
2750 Stmt* FirstStmt = cast<PostStmt>(AllocNode->getLocation()).getStmt();
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00002751
Ted Kremeneke28565b2008-05-05 18:50:19 +00002752 SourceManager& SMgr = BR.getContext().getSourceManager();
Chris Lattnerf7cf85b2009-01-16 07:36:28 +00002753 unsigned AllocLine =SMgr.getInstantiationLineNumber(FirstStmt->getLocStart());
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00002754
Ted Kremenekd5597922009-02-18 23:28:26 +00002755 // Get the leak site. We want to find the last place where the symbol
2756 // was used in an expression.
2757 const ExplodedNode<GRState>* LeakN = EndN;
2758 Stmt *S = 0;
Ted Kremeneke28565b2008-05-05 18:50:19 +00002759
Ted Kremenekd5597922009-02-18 23:28:26 +00002760 while (LeakN) {
Ted Kremenek4094b342009-02-24 23:30:57 +00002761 bool atBranch = false;
Ted Kremenekd5597922009-02-18 23:28:26 +00002762 ProgramPoint P = LeakN->getLocation();
Ted Kremenekd5597922009-02-18 23:28:26 +00002763
2764 if (const PostStmt *PS = dyn_cast<PostStmt>(&P))
2765 S = PS->getStmt();
Ted Kremenek4094b342009-02-24 23:30:57 +00002766 else if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
2767 // FIXME: What we really want is to set LeakN to be the node
2768 // for the BlockEntrance for the branch we took and have BugReporter
2769 // do the right thing.
Ted Kremenekd5597922009-02-18 23:28:26 +00002770 S = BE->getSrc()->getTerminator();
Ted Kremenek6431a262009-02-24 23:34:17 +00002771 atBranch = (S != 0);
Ted Kremenek4094b342009-02-24 23:30:57 +00002772 }
Ted Kremenekd5597922009-02-18 23:28:26 +00002773
2774 if (S) {
2775 // Scan 'S' for uses of Sym.
2776 GRStateRef state(LeakN->getState(), BR.getStateManager());
2777 bool foundSymbol = false;
Ted Kremenekb1dbf152009-02-19 18:18:48 +00002778
2779 // First check if 'S' itself binds to the symbol.
Ted Kremenek94c96982009-03-03 22:06:47 +00002780 if (Expr *Ex = dyn_cast<Expr>(S))
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00002781 if (state.GetSValAsScalarOrLoc(Ex).getAsLocSymbol() == Sym)
Ted Kremenekb1dbf152009-02-19 18:18:48 +00002782 foundSymbol = true;
Ted Kremenekb1dbf152009-02-19 18:18:48 +00002783
2784 if (!foundSymbol)
2785 for (Stmt::child_iterator I=S->child_begin(), E=S->child_end();
2786 I!=E; ++I)
2787 if (Expr *Ex = dyn_cast_or_null<Expr>(*I)) {
Ted Kremenek3f4d5ab2009-03-04 00:13:50 +00002788 SVal X = state.GetSValAsScalarOrLoc(Ex);
Ted Kremenek94c96982009-03-03 22:06:47 +00002789 if (X.getAsLocSymbol() == Sym) {
Ted Kremenekb1dbf152009-02-19 18:18:48 +00002790 foundSymbol = true;
2791 break;
2792 }
Ted Kremenekd5597922009-02-18 23:28:26 +00002793 }
Ted Kremenekb1dbf152009-02-19 18:18:48 +00002794
Ted Kremenekd5597922009-02-18 23:28:26 +00002795 if (foundSymbol)
2796 break;
2797 }
2798
Ted Kremenek4094b342009-02-24 23:30:57 +00002799 // Don't traverse any higher than the branch.
2800 if (atBranch)
2801 break;
2802
Ted Kremenekd5597922009-02-18 23:28:26 +00002803 LeakN = LeakN->pred_empty() ? 0 : *(LeakN->pred_begin());
2804 }
2805
2806 assert(LeakN && S && "No leak site found.");
Ted Kremeneke28565b2008-05-05 18:50:19 +00002807
Ted Kremeneke28565b2008-05-05 18:50:19 +00002808 // Generate the diagnostic.
Ted Kremenek572b2782009-02-18 22:59:04 +00002809 FullSourceLoc L(S->getLocStart(), SMgr);
Ted Kremenekc9e3d862009-02-07 21:59:45 +00002810 std::string sbuf;
2811 llvm::raw_string_ostream os(sbuf);
Ted Kremeneke92c1b22008-05-02 20:53:50 +00002812
Ted Kremeneke28565b2008-05-05 18:50:19 +00002813 os << "Object allocated on line " << AllocLine;
Ted Kremeneke92c1b22008-05-02 20:53:50 +00002814
Ted Kremenek2bc39c62008-08-29 00:47:32 +00002815 if (FirstBinding)
Ted Kremenek9e240492008-10-04 05:50:14 +00002816 os << " and stored into '" << FirstBinding->getString() << '\'';
2817
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00002818 // Get the retain count.
2819 const RefVal* RV = EndN->getState()->get<RefBindings>(Sym);
2820
2821 if (RV->getKind() == RefVal::ErrorLeakReturned) {
Ted Kremenek04f9d462008-12-02 01:26:07 +00002822 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
2823 // ojbects. Only "copy", "alloc", "retain" and "new" transfer ownership
2824 // to the caller for NS objects.
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00002825 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(BR.getGraph().getCodeDecl());
2826 os << " is returned from a method whose name ('"
Chris Lattner077bf5e2008-11-24 03:33:13 +00002827 << MD.getSelector().getAsString()
Ted Kremenek234a4c22009-01-07 00:39:56 +00002828 << "') does not contain 'copy' or otherwise starts with"
Ted Kremenek9d1d5702008-10-24 21:22:44 +00002829 " 'new' or 'alloc'. This violates the naming convention rules given"
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00002830 " in the Memory Management Guide for Cocoa (object leaked).";
2831 }
2832 else
Ted Kremenek9d1d5702008-10-24 21:22:44 +00002833 os << " is no longer referenced after this point and has a retain count of"
2834 " +"
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00002835 << RV->getCount() << " (object leaked).";
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00002836
Ted Kremenek572b2782009-02-18 22:59:04 +00002837 return new PathDiagnosticPiece(L, os.str());
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00002838}
2839
Ted Kremenek989d5192008-04-17 23:43:50 +00002840
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002841CFRefLeakReport::CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2842 ExplodedNode<GRState> *n,
Ted Kremenekd3057212009-02-07 22:38:00 +00002843 SymbolRef sym, GRExprEngine& Eng)
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002844 : CFRefReport(D, tf, n, sym)
Ted Kremeneke469fa02009-02-07 22:19:59 +00002845{
2846
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002847 // Most bug reports are cached at the location where they occured.
2848 // With leaks, we want to unique them by the location where they were
Ted Kremeneke469fa02009-02-07 22:19:59 +00002849 // allocated, and only report a single path. To do this, we need to find
2850 // the allocation site of a piece of tracked memory, which we do via a
2851 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2852 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2853 // that all ancestor nodes that represent the allocation site have the
2854 // same SourceLocation.
2855 const ExplodedNode<GRState>* AllocNode = 0;
2856
2857 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding.
Ted Kremenekd3057212009-02-07 22:38:00 +00002858 GetAllocationSite(Eng.getStateManager(), getEndNode(), getSymbol());
Ted Kremeneke469fa02009-02-07 22:19:59 +00002859
Ted Kremeneke469fa02009-02-07 22:19:59 +00002860 // Get the SourceLocation for the allocation site.
Ted Kremenekd3057212009-02-07 22:38:00 +00002861 ProgramPoint P = AllocNode->getLocation();
Ted Kremeneke469fa02009-02-07 22:19:59 +00002862 AllocSite = cast<PostStmt>(P).getStmt()->getLocStart();
Ted Kremenekd3057212009-02-07 22:38:00 +00002863
2864 // Fill in the description of the bug.
2865 Description.clear();
2866 llvm::raw_string_ostream os(Description);
2867 SourceManager& SMgr = Eng.getContext().getSourceManager();
2868 unsigned AllocLine = SMgr.getInstantiationLineNumber(AllocSite);
Ted Kremenekc5c60002009-02-07 22:54:59 +00002869 os << "Potential leak of object allocated on line " << AllocLine;
2870
2871 // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2872 if (AllocBinding)
2873 os << " and store into '" << AllocBinding->getString() << '\'';
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002874}
2875
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00002876//===----------------------------------------------------------------------===//
Ted Kremenekcf701772009-02-05 06:50:21 +00002877// Handle dead symbols and end-of-path.
2878//===----------------------------------------------------------------------===//
2879
2880void CFRefCount::EvalEndPath(GRExprEngine& Eng,
2881 GREndPathNodeBuilder<GRState>& Builder) {
2882
2883 const GRState* St = Builder.getState();
2884 RefBindings B = St->get<RefBindings>();
2885
2886 llvm::SmallVector<std::pair<SymbolRef, bool>, 10> Leaked;
2887 const Decl* CodeDecl = &Eng.getGraph().getCodeDecl();
2888
2889 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
2890 bool hasLeak = false;
2891
2892 std::pair<GRStateRef, bool> X =
Ted Kremenek94c96982009-03-03 22:06:47 +00002893 HandleSymbolDeath(Eng.getStateManager(), St, CodeDecl,
2894 (*I).first, (*I).second, hasLeak);
Ted Kremenekcf701772009-02-05 06:50:21 +00002895
2896 St = X.first;
2897 if (hasLeak) Leaked.push_back(std::make_pair((*I).first, X.second));
2898 }
2899
2900 if (Leaked.empty())
2901 return;
2902
2903 ExplodedNode<GRState>* N = Builder.MakeNode(St);
2904
2905 if (!N)
2906 return;
2907
2908 for (llvm::SmallVector<std::pair<SymbolRef,bool>, 10>::iterator
2909 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
2910
2911 CFRefBug *BT = static_cast<CFRefBug*>(I->second ? leakAtReturn
2912 : leakWithinFunction);
2913 assert(BT && "BugType not initialized.");
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002914 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N, I->first, Eng);
Ted Kremenekcf701772009-02-05 06:50:21 +00002915 BR->EmitReport(report);
2916 }
2917}
2918
2919void CFRefCount::EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
2920 GRExprEngine& Eng,
2921 GRStmtNodeBuilder<GRState>& Builder,
2922 ExplodedNode<GRState>* Pred,
2923 Stmt* S,
2924 const GRState* St,
2925 SymbolReaper& SymReaper) {
2926
Ted Kremenek33b6f632009-02-19 23:47:02 +00002927 // FIXME: a lot of copy-and-paste from EvalEndPath. Refactor.
Ted Kremenekcf701772009-02-05 06:50:21 +00002928 RefBindings B = St->get<RefBindings>();
2929 llvm::SmallVector<std::pair<SymbolRef,bool>, 10> Leaked;
2930
2931 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
2932 E = SymReaper.dead_end(); I != E; ++I) {
2933
2934 const RefVal* T = B.lookup(*I);
2935 if (!T) continue;
2936
2937 bool hasLeak = false;
2938
2939 std::pair<GRStateRef, bool> X
Ted Kremenek33b6f632009-02-19 23:47:02 +00002940 = HandleSymbolDeath(Eng.getStateManager(), St, 0, *I, *T, hasLeak);
Ted Kremenekcf701772009-02-05 06:50:21 +00002941
2942 St = X.first;
2943
2944 if (hasLeak)
2945 Leaked.push_back(std::make_pair(*I,X.second));
2946 }
2947
Ted Kremenek33b6f632009-02-19 23:47:02 +00002948 if (!Leaked.empty()) {
2949 // Create a new intermediate node representing the leak point. We
2950 // use a special program point that represents this checker-specific
2951 // transition. We use the address of RefBIndex as a unique tag for this
2952 // checker. We will create another node (if we don't cache out) that
2953 // removes the retain-count bindings from the state.
2954 // NOTE: We use 'generateNode' so that it does interplay with the
2955 // auto-transition logic.
2956 ExplodedNode<GRState>* N =
2957 Builder.generateNode(PostStmtCustom(S, &LeakProgramPointTag), St, Pred);
Ted Kremenekcf701772009-02-05 06:50:21 +00002958
Ted Kremenek33b6f632009-02-19 23:47:02 +00002959 if (!N)
2960 return;
2961
2962 // Generate the bug reports.
2963 for (llvm::SmallVectorImpl<std::pair<SymbolRef,bool> >::iterator
2964 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
2965
2966 CFRefBug *BT = static_cast<CFRefBug*>(I->second ? leakAtReturn
2967 : leakWithinFunction);
2968 assert(BT && "BugType not initialized.");
Ted Kremenek46347352009-02-23 16:54:00 +00002969 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N,
2970 I->first, Eng);
Ted Kremenek33b6f632009-02-19 23:47:02 +00002971 BR->EmitReport(report);
2972 }
Ted Kremenekcf701772009-02-05 06:50:21 +00002973
Ted Kremenek33b6f632009-02-19 23:47:02 +00002974 Pred = N;
Ted Kremenekcf701772009-02-05 06:50:21 +00002975 }
Ted Kremenek33b6f632009-02-19 23:47:02 +00002976
2977 // Now generate a new node that nukes the old bindings.
2978 GRStateRef state(St, Eng.getStateManager());
2979 RefBindings::Factory& F = state.get_context<RefBindings>();
2980
2981 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
2982 E = SymReaper.dead_end(); I!=E; ++I)
2983 B = F.Remove(B, *I);
2984
2985 state = state.set<RefBindings>(B);
2986 Builder.MakeNode(Dst, S, Pred, state);
Ted Kremenekcf701772009-02-05 06:50:21 +00002987}
2988
2989void CFRefCount::ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
2990 GRStmtNodeBuilder<GRState>& Builder,
2991 Expr* NodeExpr, Expr* ErrorExpr,
2992 ExplodedNode<GRState>* Pred,
2993 const GRState* St,
2994 RefVal::Kind hasErr, SymbolRef Sym) {
2995 Builder.BuildSinks = true;
2996 GRExprEngine::NodeTy* N = Builder.MakeNode(Dst, NodeExpr, Pred, St);
2997
2998 if (!N) return;
2999
3000 CFRefBug *BT = 0;
3001
3002 if (hasErr == RefVal::ErrorUseAfterRelease)
3003 BT = static_cast<CFRefBug*>(useAfterRelease);
3004 else {
3005 assert(hasErr == RefVal::ErrorReleaseNotOwned);
3006 BT = static_cast<CFRefBug*>(releaseNotOwned);
3007 }
3008
Ted Kremenekfe9e5432009-02-18 03:48:14 +00003009 CFRefReport *report = new CFRefReport(*BT, *this, N, Sym);
Ted Kremenekcf701772009-02-05 06:50:21 +00003010 report->addRange(ErrorExpr->getSourceRange());
3011 BR->EmitReport(report);
3012}
3013
3014//===----------------------------------------------------------------------===//
Ted Kremenekd71ed262008-04-10 22:16:52 +00003015// Transfer function creation for external clients.
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00003016//===----------------------------------------------------------------------===//
3017
Ted Kremenek072192b2008-04-30 23:47:44 +00003018GRTransferFuncs* clang::MakeCFRefCountTF(ASTContext& Ctx, bool GCEnabled,
3019 const LangOptions& lopts) {
Ted Kremenek78d46242008-07-22 16:21:24 +00003020 return new CFRefCount(Ctx, GCEnabled, lopts);
Ted Kremenek3ea0b6a2008-04-10 22:58:08 +00003021}