blob: faf783941841c841c5cddbd9380c5d6faf03cd3e [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 }
648
Ted Kremenekaf9dc272008-08-12 18:48:50 +0000649 void addInstMethSummary(const char* Cls, RetainSummary* Summ, va_list argp) {
Ted Kremenek70a733e2008-07-18 17:24:20 +0000650
Ted Kremenek9e476de2008-08-12 18:30:56 +0000651 IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
652 llvm::SmallVector<IdentifierInfo*, 10> II;
653
654 while (const char* s = va_arg(argp, const char*))
655 II.push_back(&Ctx.Idents.get(s));
656
657 Selector S = Ctx.Selectors.getSelector(II.size(), &II[0]);
Ted Kremenek70a733e2008-07-18 17:24:20 +0000658 ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)] = Summ;
659 }
Ted Kremenekaf9dc272008-08-12 18:48:50 +0000660
661 void addInstMethSummary(const char* Cls, RetainSummary* Summ, ...) {
662 va_list argp;
663 va_start(argp, Summ);
664 addInstMethSummary(Cls, Summ, argp);
665 va_end(argp);
666 }
Ted Kremenek9e476de2008-08-12 18:30:56 +0000667
668 void addPanicSummary(const char* Cls, ...) {
669 RetainSummary* Summ = getPersistentSummary(0, RetEffect::MakeNoRet(),
670 DoNothing, DoNothing, true);
671 va_list argp;
672 va_start (argp, Cls);
Ted Kremenekaf9dc272008-08-12 18:48:50 +0000673 addInstMethSummary(Cls, Summ, argp);
Ted Kremenek9e476de2008-08-12 18:30:56 +0000674 va_end(argp);
675 }
Ted Kremenek70a733e2008-07-18 17:24:20 +0000676
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000677public:
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000678
679 RetainSummaryManager(ASTContext& ctx, bool gcenabled)
Ted Kremenek179064e2008-07-01 17:21:27 +0000680 : Ctx(ctx),
Ted Kremenek070a8252008-07-09 18:11:16 +0000681 CFDictionaryCreateII(&ctx.Idents.get("CFDictionaryCreate")),
Ted Kremenek553cf182008-06-25 21:21:56 +0000682 GCEnabled(gcenabled), StopSummary(0) {
683
684 InitializeClassMethodSummaries();
685 InitializeMethodSummaries();
686 }
Ted Kremenek377e2302008-04-29 05:33:51 +0000687
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000688 ~RetainSummaryManager();
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000689
Ted Kremenekab592272008-06-24 03:56:45 +0000690 RetainSummary* getSummary(FunctionDecl* FD);
Ted Kremenek553cf182008-06-25 21:21:56 +0000691 RetainSummary* getMethodSummary(ObjCMessageExpr* ME, ObjCInterfaceDecl* ID);
Ted Kremenek1f180c32008-06-23 22:21:20 +0000692 RetainSummary* getClassMethodSummary(IdentifierInfo* ClsName, Selector S);
Ted Kremenekb3095252008-05-06 04:20:12 +0000693
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000694 bool isGCEnabled() const { return GCEnabled; }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000695};
696
697} // end anonymous namespace
698
699//===----------------------------------------------------------------------===//
700// Implementation of checker data structures.
701//===----------------------------------------------------------------------===//
702
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000703RetainSummaryManager::~RetainSummaryManager() {
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000704
705 // FIXME: The ArgEffects could eventually be allocated from BPAlloc,
706 // mitigating the need to do explicit cleanup of the
707 // Argument-Effect summaries.
708
Ted Kremenek46e49ee2008-05-05 23:55:01 +0000709 for (ArgEffectsSetTy::iterator I = ArgEffectsSet.begin(),
710 E = ArgEffectsSet.end(); I!=E; ++I)
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000711 I->getValue().~ArgEffects();
Ted Kremenek2fff37e2008-03-06 00:08:09 +0000712}
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000713
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000714ArgEffects* RetainSummaryManager::getArgEffects() {
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000715
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000716 if (ScratchArgs.empty())
717 return NULL;
718
719 // Compute a profile for a non-empty ScratchArgs.
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000720 llvm::FoldingSetNodeID profile;
721 profile.Add(ScratchArgs);
722 void* InsertPos;
723
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000724 // Look up the uniqued copy, or create a new one.
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000725 llvm::FoldingSetNodeWrapper<ArgEffects>* E =
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000726 ArgEffectsSet.FindNodeOrInsertPos(profile, InsertPos);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000727
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000728 if (E) {
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000729 ScratchArgs.clear();
730 return &E->getValue();
731 }
732
733 E = (llvm::FoldingSetNodeWrapper<ArgEffects>*)
Ted Kremenek553cf182008-06-25 21:21:56 +0000734 BPAlloc.Allocate<llvm::FoldingSetNodeWrapper<ArgEffects> >();
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000735
736 new (E) llvm::FoldingSetNodeWrapper<ArgEffects>(ScratchArgs);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000737 ArgEffectsSet.InsertNode(E, InsertPos);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000738
739 ScratchArgs.clear();
740 return &E->getValue();
741}
742
Ted Kremenek3c0cea32008-05-06 02:26:56 +0000743RetainSummary*
744RetainSummaryManager::getPersistentSummary(ArgEffects* AE, RetEffect RetEff,
Ted Kremenek1bffd742008-05-06 15:44:25 +0000745 ArgEffect ReceiverEff,
Ted Kremenek70a733e2008-07-18 17:24:20 +0000746 ArgEffect DefaultEff,
747 bool isEndPath) {
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000748
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000749 // Generate a profile for the summary.
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000750 llvm::FoldingSetNodeID profile;
Ted Kremenek2d1086c2008-07-18 17:39:56 +0000751 RetainSummary::Profile(profile, AE, RetEff, DefaultEff, ReceiverEff,
752 isEndPath);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000753
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000754 // Look up the uniqued summary, or create one if it doesn't exist.
755 void* InsertPos;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000756 RetainSummary* Summ = SummarySet.FindNodeOrInsertPos(profile, InsertPos);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000757
758 if (Summ)
759 return Summ;
760
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000761 // Create the summary and return it.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000762 Summ = (RetainSummary*) BPAlloc.Allocate<RetainSummary>();
Ted Kremenek70a733e2008-07-18 17:24:20 +0000763 new (Summ) RetainSummary(AE, RetEff, DefaultEff, ReceiverEff, isEndPath);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000764 SummarySet.InsertNode(Summ, InsertPos);
765
766 return Summ;
767}
768
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000769//===----------------------------------------------------------------------===//
Ted Kremenek234a4c22009-01-07 00:39:56 +0000770// Predicates.
771//===----------------------------------------------------------------------===//
772
773bool RetainSummaryManager::isTrackedObjectType(QualType T) {
774 if (!Ctx.isObjCObjectPointerType(T))
775 return false;
776
777 // Does it subclass NSObject?
778 ObjCInterfaceType* OT = dyn_cast<ObjCInterfaceType>(T.getTypePtr());
779
780 // We assume that id<..>, id, and "Class" all represent tracked objects.
781 if (!OT)
782 return true;
783
784 // Does the object type subclass NSObject?
785 // FIXME: We can memoize here if this gets too expensive.
786 IdentifierInfo* NSObjectII = &Ctx.Idents.get("NSObject");
787 ObjCInterfaceDecl* ID = OT->getDecl();
788
789 for ( ; ID ; ID = ID->getSuperClass())
790 if (ID->getIdentifier() == NSObjectII)
791 return true;
792
793 return false;
794}
795
796//===----------------------------------------------------------------------===//
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000797// Summary creation for functions (largely uses of Core Foundation).
798//===----------------------------------------------------------------------===//
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000799
Ted Kremenek12619382009-01-12 21:45:02 +0000800static bool isRetain(FunctionDecl* FD, const char* FName) {
801 const char* loc = strstr(FName, "Retain");
802 return loc && loc[sizeof("Retain")-1] == '\0';
803}
804
805static bool isRelease(FunctionDecl* FD, const char* FName) {
806 const char* loc = strstr(FName, "Release");
807 return loc && loc[sizeof("Release")-1] == '\0';
808}
809
Ted Kremenekab592272008-06-24 03:56:45 +0000810RetainSummary* RetainSummaryManager::getSummary(FunctionDecl* FD) {
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000811
812 SourceLocation Loc = FD->getLocation();
813
814 if (!Loc.isFileID())
815 return NULL;
Ted Kremenek2fff37e2008-03-06 00:08:09 +0000816
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000817 // Look up a summary in our cache of FunctionDecls -> Summaries.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000818 FuncSummariesTy::iterator I = FuncSummaries.find(FD);
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000819
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000820 if (I != FuncSummaries.end())
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000821 return I->second;
822
823 // No summary. Generate one.
Ted Kremenek12619382009-01-12 21:45:02 +0000824 RetainSummary *S = 0;
Ted Kremenek86ad3bc2008-05-05 16:51:50 +0000825
Ted Kremenek37d785b2008-07-15 16:50:12 +0000826 do {
Ted Kremenek12619382009-01-12 21:45:02 +0000827 // We generate "stop" summaries for implicitly defined functions.
828 if (FD->isImplicit()) {
829 S = getPersistentStopSummary();
830 break;
Ted Kremenek37d785b2008-07-15 16:50:12 +0000831 }
Ted Kremenek6ca31912008-11-04 00:36:12 +0000832
Ted Kremenek6ad315a2009-02-23 16:51:39 +0000833 // [PR 3337] Use 'getAsFunctionType' to strip away any typedefs on the
Ted Kremenek99890652009-01-16 18:40:33 +0000834 // function's type.
Ted Kremenek6ad315a2009-02-23 16:51:39 +0000835 const FunctionType* FT = FD->getType()->getAsFunctionType();
Ted Kremenek12619382009-01-12 21:45:02 +0000836 const char* FName = FD->getIdentifier()->getName();
837
838 // Inspect the result type.
839 QualType RetTy = FT->getResultType();
840
841 // FIXME: This should all be refactored into a chain of "summary lookup"
842 // filters.
843 if (strcmp(FName, "IOServiceGetMatchingServices") == 0) {
844 // FIXES: <rdar://problem/6326900>
845 // This should be addressed using a API table. This strcmp is also
846 // a little gross, but there is no need to super optimize here.
847 assert (ScratchArgs.empty());
848 ScratchArgs.push_back(std::make_pair(1, DecRef));
849 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
850 break;
Ted Kremenek64e859a2008-10-22 20:54:52 +0000851 }
Ted Kremenek12619382009-01-12 21:45:02 +0000852
853 // Handle: id NSMakeCollectable(CFTypeRef)
854 if (strcmp(FName, "NSMakeCollectable") == 0) {
855 S = (RetTy == Ctx.getObjCIdType())
856 ? getUnarySummary(FT, cfmakecollectable)
857 : getPersistentStopSummary();
858
859 break;
860 }
861
862 if (RetTy->isPointerType()) {
863 // For CoreFoundation ('CF') types.
864 if (isRefType(RetTy, "CF", &Ctx, FName)) {
865 if (isRetain(FD, FName))
866 S = getUnarySummary(FT, cfretain);
867 else if (strstr(FName, "MakeCollectable"))
868 S = getUnarySummary(FT, cfmakecollectable);
869 else
870 S = getCFCreateGetRuleSummary(FD, FName);
871
872 break;
873 }
874
875 // For CoreGraphics ('CG') types.
876 if (isRefType(RetTy, "CG", &Ctx, FName)) {
877 if (isRetain(FD, FName))
878 S = getUnarySummary(FT, cfretain);
879 else
880 S = getCFCreateGetRuleSummary(FD, FName);
881
882 break;
883 }
884
885 // For the Disk Arbitration API (DiskArbitration/DADisk.h)
886 if (isRefType(RetTy, "DADisk") ||
887 isRefType(RetTy, "DADissenter") ||
888 isRefType(RetTy, "DASessionRef")) {
889 S = getCFCreateGetRuleSummary(FD, FName);
890 break;
891 }
892
893 break;
894 }
895
896 // Check for release functions, the only kind of functions that we care
897 // about that don't return a pointer type.
898 if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
899 if (isRelease(FD, FName+2))
900 S = getUnarySummary(FT, cfrelease);
901 else {
Ted Kremenek68189282009-01-29 22:45:13 +0000902 assert (ScratchArgs.empty());
903 // Remaining CoreFoundation and CoreGraphics functions.
904 // We use to assume that they all strictly followed the ownership idiom
905 // and that ownership cannot be transferred. While this is technically
906 // correct, many methods allow a tracked object to escape. For example:
907 //
908 // CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
909 // CFDictionaryAddValue(y, key, x);
910 // CFRelease(x);
911 // ... it is okay to use 'x' since 'y' has a reference to it
912 //
913 // We handle this and similar cases with the follow heuristic. If the
914 // function name contains "InsertValue", "SetValue" or "AddValue" then
915 // we assume that arguments may "escape."
916 //
917 ArgEffect E = (CStrInCStrNoCase(FName, "InsertValue") ||
918 CStrInCStrNoCase(FName, "AddValue") ||
Ted Kremeneka92206e2009-02-05 22:34:53 +0000919 CStrInCStrNoCase(FName, "SetValue") ||
920 CStrInCStrNoCase(FName, "AppendValue"))
Ted Kremenek68189282009-01-29 22:45:13 +0000921 ? MayEscape : DoNothing;
922
923 S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
Ted Kremenek12619382009-01-12 21:45:02 +0000924 }
925 }
Ted Kremenek37d785b2008-07-15 16:50:12 +0000926 }
927 while (0);
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000928
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000929 FuncSummaries[FD] = S;
Ted Kremenek86ad3bc2008-05-05 16:51:50 +0000930 return S;
Ted Kremenek2fff37e2008-03-06 00:08:09 +0000931}
932
Ted Kremenek37d785b2008-07-15 16:50:12 +0000933RetainSummary*
934RetainSummaryManager::getCFCreateGetRuleSummary(FunctionDecl* FD,
935 const char* FName) {
936
Ted Kremenek86ad3bc2008-05-05 16:51:50 +0000937 if (strstr(FName, "Create") || strstr(FName, "Copy"))
938 return getCFSummaryCreateRule(FD);
Ted Kremenek37d785b2008-07-15 16:50:12 +0000939
Ted Kremenek86ad3bc2008-05-05 16:51:50 +0000940 if (strstr(FName, "Get"))
941 return getCFSummaryGetRule(FD);
942
943 return 0;
944}
945
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000946RetainSummary*
Ted Kremenek6ad315a2009-02-23 16:51:39 +0000947RetainSummaryManager::getUnarySummary(const FunctionType* FT,
948 UnaryFuncKind func) {
949
Ted Kremenek12619382009-01-12 21:45:02 +0000950 // Sanity check that this is *really* a unary function. This can
951 // happen if people do weird things.
Ted Kremenek6ad315a2009-02-23 16:51:39 +0000952 const FunctionTypeProto* FTP = dyn_cast<FunctionTypeProto>(FT);
Ted Kremenek12619382009-01-12 21:45:02 +0000953 if (!FTP || FTP->getNumArgs() != 1)
954 return getPersistentStopSummary();
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000955
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000956 assert (ScratchArgs.empty());
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000957
Ted Kremenek377e2302008-04-29 05:33:51 +0000958 switch (func) {
Ted Kremenek12619382009-01-12 21:45:02 +0000959 case cfretain: {
Ted Kremenek377e2302008-04-29 05:33:51 +0000960 ScratchArgs.push_back(std::make_pair(0, IncRef));
Ted Kremenek3eabf1c2008-05-22 17:31:13 +0000961 return getPersistentSummary(RetEffect::MakeAlias(0),
962 DoNothing, DoNothing);
Ted Kremenek377e2302008-04-29 05:33:51 +0000963 }
964
965 case cfrelease: {
Ted Kremenek377e2302008-04-29 05:33:51 +0000966 ScratchArgs.push_back(std::make_pair(0, DecRef));
Ted Kremenek3eabf1c2008-05-22 17:31:13 +0000967 return getPersistentSummary(RetEffect::MakeNoRet(),
968 DoNothing, DoNothing);
Ted Kremenek377e2302008-04-29 05:33:51 +0000969 }
970
971 case cfmakecollectable: {
Ted Kremenek27019002009-02-18 21:57:45 +0000972 ScratchArgs.push_back(std::make_pair(0, MakeCollectable));
973 return getPersistentSummary(RetEffect::MakeAlias(0),DoNothing, DoNothing);
Ted Kremenek377e2302008-04-29 05:33:51 +0000974 }
975
976 default:
Ted Kremenek86ad3bc2008-05-05 16:51:50 +0000977 assert (false && "Not a supported unary function.");
Ted Kremenek98530452008-08-12 20:41:56 +0000978 return 0;
Ted Kremenek940b1d82008-04-10 23:44:06 +0000979 }
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000980}
981
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000982RetainSummary* RetainSummaryManager::getCFSummaryCreateRule(FunctionDecl* FD) {
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000983 assert (ScratchArgs.empty());
Ted Kremenek070a8252008-07-09 18:11:16 +0000984
985 if (FD->getIdentifier() == CFDictionaryCreateII) {
986 ScratchArgs.push_back(std::make_pair(1, DoNothingByRef));
987 ScratchArgs.push_back(std::make_pair(2, DoNothingByRef));
988 }
989
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000990 return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000991}
992
Ted Kremenekd3dbcf42008-05-05 22:11:16 +0000993RetainSummary* RetainSummaryManager::getCFSummaryGetRule(FunctionDecl* FD) {
Ted Kremenek891d5cc2008-04-24 17:22:33 +0000994 assert (ScratchArgs.empty());
Ted Kremenek2d1652e2009-01-28 05:56:51 +0000995 return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
996 DoNothing, DoNothing);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +0000997}
998
Ted Kremenek6b3a0f72008-03-11 06:39:11 +0000999//===----------------------------------------------------------------------===//
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001000// Summary creation for Selectors.
1001//===----------------------------------------------------------------------===//
1002
Ted Kremenek1bffd742008-05-06 15:44:25 +00001003RetainSummary*
Ted Kremenek553cf182008-06-25 21:21:56 +00001004RetainSummaryManager::getInitMethodSummary(ObjCMessageExpr* ME) {
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001005 assert(ScratchArgs.empty());
1006
Ted Kremenekc3cf7b22009-02-20 00:05:35 +00001007 // 'init' methods only return an alias if the return type is a location type.
1008 QualType T = ME->getType();
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001009 RetainSummary* Summ =
Ted Kremenekc3cf7b22009-02-20 00:05:35 +00001010 getPersistentSummary(Loc::IsLocType(T) ? RetEffect::MakeReceiverAlias()
1011 : RetEffect::MakeNoRet());
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001012
Ted Kremenek553cf182008-06-25 21:21:56 +00001013 ObjCMethodSummaries[ME] = Summ;
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001014 return Summ;
1015}
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001016
Ted Kremenek553cf182008-06-25 21:21:56 +00001017
Ted Kremenek1bffd742008-05-06 15:44:25 +00001018RetainSummary*
Ted Kremenek553cf182008-06-25 21:21:56 +00001019RetainSummaryManager::getMethodSummary(ObjCMessageExpr* ME,
1020 ObjCInterfaceDecl* ID) {
Ted Kremenek1bffd742008-05-06 15:44:25 +00001021
1022 Selector S = ME->getSelector();
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001023
Ted Kremenek553cf182008-06-25 21:21:56 +00001024 // Look up a summary in our summary cache.
1025 ObjCMethodSummariesTy::iterator I = ObjCMethodSummaries.find(ID, S);
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001026
Ted Kremenek1f180c32008-06-23 22:21:20 +00001027 if (I != ObjCMethodSummaries.end())
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001028 return I->second;
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001029
Ted Kremenek234a4c22009-01-07 00:39:56 +00001030 // "initXXX": pass-through for receiver.
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001031 const char* s = S.getIdentifierInfoForSlot(0)->getName();
Ted Kremeneka4b695a2008-05-07 03:45:05 +00001032 assert (ScratchArgs.empty());
Ted Kremenekaee9e572008-05-06 06:09:09 +00001033
Ted Kremenekb80976c2009-02-21 05:13:43 +00001034 if (deriveNamingConvention(s) == InitRule)
Ted Kremenek234a4c22009-01-07 00:39:56 +00001035 return getInitMethodSummary(ME);
Ted Kremenek1bffd742008-05-06 15:44:25 +00001036
Ted Kremenek234a4c22009-01-07 00:39:56 +00001037 // Look for methods that return an owned object.
1038 if (!isTrackedObjectType(Ctx.getCanonicalType(ME->getType())))
Ted Kremenek84060db2008-05-07 04:25:59 +00001039 return 0;
Ted Kremeneka4b695a2008-05-07 03:45:05 +00001040
Ted Kremenek234a4c22009-01-07 00:39:56 +00001041 if (followsFundamentalRule(s)) {
1042 RetEffect E = isGCEnabled() ? RetEffect::MakeNoRet()
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001043 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremeneka4b695a2008-05-07 03:45:05 +00001044 RetainSummary* Summ = getPersistentSummary(E);
Ted Kremenek553cf182008-06-25 21:21:56 +00001045 ObjCMethodSummaries[ME] = Summ;
Ted Kremenek1bffd742008-05-06 15:44:25 +00001046 return Summ;
1047 }
Ted Kremenek1bffd742008-05-06 15:44:25 +00001048
Ted Kremenek46e49ee2008-05-05 23:55:01 +00001049 return 0;
1050}
1051
Ted Kremenekc8395602008-05-06 21:26:51 +00001052RetainSummary*
Ted Kremenek1f180c32008-06-23 22:21:20 +00001053RetainSummaryManager::getClassMethodSummary(IdentifierInfo* ClsName,
1054 Selector S) {
Ted Kremenekc8395602008-05-06 21:26:51 +00001055
Ted Kremenek553cf182008-06-25 21:21:56 +00001056 // FIXME: Eventually we should properly do class method summaries, but
1057 // it requires us being able to walk the type hierarchy. Unfortunately,
1058 // we cannot do this with just an IdentifierInfo* for the class name.
1059
Ted Kremenekc8395602008-05-06 21:26:51 +00001060 // Look up a summary in our cache of Selectors -> Summaries.
Ted Kremenek553cf182008-06-25 21:21:56 +00001061 ObjCMethodSummariesTy::iterator I = ObjCClassMethodSummaries.find(ClsName, S);
Ted Kremenekc8395602008-05-06 21:26:51 +00001062
Ted Kremenek1f180c32008-06-23 22:21:20 +00001063 if (I != ObjCClassMethodSummaries.end())
Ted Kremenekc8395602008-05-06 21:26:51 +00001064 return I->second;
1065
Ted Kremeneka22cc2f2008-05-06 23:07:13 +00001066 return 0;
Ted Kremenekc8395602008-05-06 21:26:51 +00001067}
1068
Ted Kremenek1f180c32008-06-23 22:21:20 +00001069void RetainSummaryManager::InitializeClassMethodSummaries() {
Ted Kremenek9c32d082008-05-06 00:30:21 +00001070
1071 assert (ScratchArgs.empty());
1072
Ted Kremeneka7344702008-06-23 18:02:52 +00001073 RetEffect E = isGCEnabled() ? RetEffect::MakeNoRet()
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001074 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremeneka7344702008-06-23 18:02:52 +00001075
Ted Kremenek9c32d082008-05-06 00:30:21 +00001076 RetainSummary* Summ = getPersistentSummary(E);
1077
Ted Kremenek553cf182008-06-25 21:21:56 +00001078 // Create the summaries for "alloc", "new", and "allocWithZone:" for
1079 // NSObject and its derivatives.
1080 addNSObjectClsMethSummary(GetNullarySelector("alloc", Ctx), Summ);
1081 addNSObjectClsMethSummary(GetNullarySelector("new", Ctx), Summ);
1082 addNSObjectClsMethSummary(GetUnarySelector("allocWithZone", Ctx), Summ);
Ted Kremenek70a733e2008-07-18 17:24:20 +00001083
1084 // Create the [NSAssertionHandler currentHander] summary.
Ted Kremenek9e476de2008-08-12 18:30:56 +00001085 addClsMethSummary(&Ctx.Idents.get("NSAssertionHandler"),
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001086 GetNullarySelector("currentHandler", Ctx),
1087 getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
Ted Kremenek6d348932008-10-21 15:53:15 +00001088
1089 // Create the [NSAutoreleasePool addObject:] summary.
Ted Kremenekabf43972009-01-28 21:44:40 +00001090 ScratchArgs.push_back(std::make_pair(0, Autorelease));
1091 addClsMethSummary(&Ctx.Idents.get("NSAutoreleasePool"),
1092 GetUnarySelector("addObject", Ctx),
1093 getPersistentSummary(RetEffect::MakeNoRet(),
Ted Kremenek022a3c42009-02-23 02:31:16 +00001094 DoNothing, Autorelease));
Ted Kremenek9c32d082008-05-06 00:30:21 +00001095}
1096
Ted Kremenek1f180c32008-06-23 22:21:20 +00001097void RetainSummaryManager::InitializeMethodSummaries() {
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001098
1099 assert (ScratchArgs.empty());
1100
Ted Kremenekc8395602008-05-06 21:26:51 +00001101 // Create the "init" selector. It just acts as a pass-through for the
1102 // receiver.
Ted Kremenek46347352009-02-23 16:54:00 +00001103 RetainSummary* InitSumm =
1104 getPersistentSummary(RetEffect::MakeReceiverAlias());
Ted Kremenek179064e2008-07-01 17:21:27 +00001105 addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
Ted Kremenekc8395602008-05-06 21:26:51 +00001106
1107 // The next methods are allocators.
Ted Kremeneka7344702008-06-23 18:02:52 +00001108 RetEffect E = isGCEnabled() ? RetEffect::MakeNoRet()
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001109 : RetEffect::MakeOwned(RetEffect::ObjC, true);
Ted Kremeneka7344702008-06-23 18:02:52 +00001110
Ted Kremenek179064e2008-07-01 17:21:27 +00001111 RetainSummary* Summ = getPersistentSummary(E);
Ted Kremenekc8395602008-05-06 21:26:51 +00001112
1113 // Create the "copy" selector.
Ted Kremenek98530452008-08-12 20:41:56 +00001114 addNSObjectMethSummary(GetNullarySelector("copy", Ctx), Summ);
1115
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001116 // Create the "mutableCopy" selector.
Ted Kremenek553cf182008-06-25 21:21:56 +00001117 addNSObjectMethSummary(GetNullarySelector("mutableCopy", Ctx), Summ);
Ted Kremenek98530452008-08-12 20:41:56 +00001118
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001119 // Create the "retain" selector.
1120 E = RetEffect::MakeReceiverAlias();
Ted Kremenek1c512f52009-02-18 18:54:33 +00001121 Summ = getPersistentSummary(E, IncRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001122 addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001123
1124 // Create the "release" selector.
Ted Kremenek1c512f52009-02-18 18:54:33 +00001125 Summ = getPersistentSummary(E, DecRefMsg);
Ted Kremenek553cf182008-06-25 21:21:56 +00001126 addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
Ted Kremenek299e8152008-05-07 21:17:39 +00001127
1128 // Create the "drain" selector.
1129 Summ = getPersistentSummary(E, isGCEnabled() ? DoNothing : DecRef);
Ted Kremenek553cf182008-06-25 21:21:56 +00001130 addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001131
1132 // Create the "autorelease" selector.
Ted Kremenekabf43972009-01-28 21:44:40 +00001133 Summ = getPersistentSummary(E, Autorelease);
Ted Kremenek553cf182008-06-25 21:21:56 +00001134 addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
Ted Kremenek98530452008-08-12 20:41:56 +00001135
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00001136 // Specially handle NSAutoreleasePool.
1137 addInstMethSummary("NSAutoreleasePool",
1138 getPersistentSummary(RetEffect::MakeReceiverAlias(),
1139 NewAutoreleasePool),
1140 "init", NULL);
1141
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001142 // For NSWindow, allocated objects are (initially) self-owned.
Ted Kremenek89e202d2009-02-23 02:51:29 +00001143 // FIXME: For now we opt for false negatives with NSWindow, as these objects
1144 // self-own themselves. However, they only do this once they are displayed.
1145 // Thus, we need to track an NSWindow's display status.
1146 // This is tracked in <rdar://problem/6062711>.
Ted Kremenek179064e2008-07-01 17:21:27 +00001147 RetainSummary *NSWindowSumm =
Ted Kremenek89e202d2009-02-23 02:51:29 +00001148 getPersistentSummary(RetEffect::MakeReceiverAlias(), StopTracking);
Ted Kremenekaf9dc272008-08-12 18:48:50 +00001149
1150 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1151 "styleMask", "backing", "defer", NULL);
1152
1153 addInstMethSummary("NSWindow", NSWindowSumm, "initWithContentRect",
1154 "styleMask", "backing", "defer", "screen", NULL);
1155
1156 // For NSPanel (which subclasses NSWindow), allocated objects are not
1157 // self-owned.
1158 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1159 "styleMask", "backing", "defer", NULL);
1160
1161 addInstMethSummary("NSPanel", InitSumm, "initWithContentRect",
1162 "styleMask", "backing", "defer", "screen", NULL);
Ted Kremenek553cf182008-06-25 21:21:56 +00001163
Ted Kremenek70a733e2008-07-18 17:24:20 +00001164 // Create NSAssertionHandler summaries.
Ted Kremenek9e476de2008-08-12 18:30:56 +00001165 addPanicSummary("NSAssertionHandler", "handleFailureInFunction", "file",
1166 "lineNumber", "description", NULL);
Ted Kremenek70a733e2008-07-18 17:24:20 +00001167
Ted Kremenek9e476de2008-08-12 18:30:56 +00001168 addPanicSummary("NSAssertionHandler", "handleFailureInMethod", "object",
1169 "file", "lineNumber", "description", NULL);
Ted Kremenekb3c3c282008-05-06 00:38:54 +00001170}
1171
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001172//===----------------------------------------------------------------------===//
Ted Kremenek13922612008-04-16 20:40:59 +00001173// Reference-counting logic (typestate + counts).
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001174//===----------------------------------------------------------------------===//
1175
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001176namespace {
1177
Ted Kremenek05cbe1a2008-04-09 23:49:11 +00001178class VISIBILITY_HIDDEN RefVal {
Ted Kremenek4fd88972008-04-17 18:12:53 +00001179public:
Ted Kremenek4fd88972008-04-17 18:12:53 +00001180 enum Kind {
1181 Owned = 0, // Owning reference.
1182 NotOwned, // Reference is not owned by still valid (not freed).
1183 Released, // Object has been released.
1184 ReturnedOwned, // Returned object passes ownership to caller.
1185 ReturnedNotOwned, // Return object does not pass ownership to caller.
1186 ErrorUseAfterRelease, // Object used after released.
1187 ErrorReleaseNotOwned, // Release of an object that was not owned.
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00001188 ErrorLeak, // A memory leak due to excessive reference counts.
1189 ErrorLeakReturned // A memory leak due to the returning method not having
1190 // the correct naming conventions.
Ted Kremenek4fd88972008-04-17 18:12:53 +00001191 };
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001192
1193private:
Ted Kremenek4fd88972008-04-17 18:12:53 +00001194 Kind kind;
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001195 RetEffect::ObjKind okind;
Ted Kremenek4fd88972008-04-17 18:12:53 +00001196 unsigned Cnt;
Ted Kremenek553cf182008-06-25 21:21:56 +00001197 QualType T;
1198
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001199 RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, QualType t)
1200 : kind(k), okind(o), Cnt(cnt), T(t) {}
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001201
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001202 RefVal(Kind k, unsigned cnt = 0)
1203 : kind(k), okind(RetEffect::AnyObj), Cnt(cnt) {}
1204
1205public:
Ted Kremenek4fd88972008-04-17 18:12:53 +00001206 Kind getKind() const { return kind; }
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001207
1208 RetEffect::ObjKind getObjKind() const { return okind; }
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001209
Ted Kremenek553cf182008-06-25 21:21:56 +00001210 unsigned getCount() const { return Cnt; }
1211 QualType getType() const { return T; }
Ted Kremenek4fd88972008-04-17 18:12:53 +00001212
1213 // Useful predicates.
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001214
Ted Kremenek73c750b2008-03-11 18:14:09 +00001215 static bool isError(Kind k) { return k >= ErrorUseAfterRelease; }
1216
Ted Kremenekf9790ae2008-10-24 20:32:50 +00001217 static bool isLeak(Kind k) { return k >= ErrorLeak; }
Ted Kremenekdb863712008-04-16 22:32:20 +00001218
Ted Kremeneke7bd9c22008-04-11 22:25:11 +00001219 bool isOwned() const {
1220 return getKind() == Owned;
1221 }
1222
Ted Kremenekdb863712008-04-16 22:32:20 +00001223 bool isNotOwned() const {
1224 return getKind() == NotOwned;
1225 }
1226
Ted Kremenek4fd88972008-04-17 18:12:53 +00001227 bool isReturnedOwned() const {
1228 return getKind() == ReturnedOwned;
1229 }
1230
1231 bool isReturnedNotOwned() const {
1232 return getKind() == ReturnedNotOwned;
1233 }
1234
1235 bool isNonLeakError() const {
1236 Kind k = getKind();
1237 return isError(k) && !isLeak(k);
1238 }
1239
1240 // State creation: normal state.
1241
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001242 static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
1243 unsigned Count = 1) {
1244 return RefVal(Owned, o, Count, t);
Ted Kremenek61b9f872008-04-10 23:09:18 +00001245 }
1246
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001247 static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
1248 unsigned Count = 0) {
1249 return RefVal(NotOwned, o, Count, t);
Ted Kremenek61b9f872008-04-10 23:09:18 +00001250 }
Ted Kremenek4fd88972008-04-17 18:12:53 +00001251
1252 static RefVal makeReturnedOwned(unsigned Count) {
1253 return RefVal(ReturnedOwned, Count);
1254 }
1255
1256 static RefVal makeReturnedNotOwned() {
1257 return RefVal(ReturnedNotOwned);
1258 }
1259
Ted Kremenek4fd88972008-04-17 18:12:53 +00001260 // Comparison, profiling, and pretty-printing.
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001261
Ted Kremenek4fd88972008-04-17 18:12:53 +00001262 bool operator==(const RefVal& X) const {
Ted Kremenek553cf182008-06-25 21:21:56 +00001263 return kind == X.kind && Cnt == X.Cnt && T == X.T;
Ted Kremenek4fd88972008-04-17 18:12:53 +00001264 }
Ted Kremenekf3948042008-03-11 19:44:10 +00001265
Ted Kremenek553cf182008-06-25 21:21:56 +00001266 RefVal operator-(size_t i) const {
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001267 return RefVal(getKind(), getObjKind(), getCount() - i, getType());
Ted Kremenek553cf182008-06-25 21:21:56 +00001268 }
1269
1270 RefVal operator+(size_t i) const {
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001271 return RefVal(getKind(), getObjKind(), getCount() + i, getType());
Ted Kremenek553cf182008-06-25 21:21:56 +00001272 }
1273
1274 RefVal operator^(Kind k) const {
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001275 return RefVal(k, getObjKind(), getCount(), getType());
Ted Kremenek553cf182008-06-25 21:21:56 +00001276 }
Ted Kremenek553cf182008-06-25 21:21:56 +00001277
Ted Kremenek4fd88972008-04-17 18:12:53 +00001278 void Profile(llvm::FoldingSetNodeID& ID) const {
1279 ID.AddInteger((unsigned) kind);
1280 ID.AddInteger(Cnt);
Ted Kremenek553cf182008-06-25 21:21:56 +00001281 ID.Add(T);
Ted Kremenek4fd88972008-04-17 18:12:53 +00001282 }
1283
Ted Kremenekf3948042008-03-11 19:44:10 +00001284 void print(std::ostream& Out) const;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001285};
Ted Kremenekf3948042008-03-11 19:44:10 +00001286
1287void RefVal::print(std::ostream& Out) const {
Ted Kremenek553cf182008-06-25 21:21:56 +00001288 if (!T.isNull())
1289 Out << "Tracked Type:" << T.getAsString() << '\n';
1290
Ted Kremenekf3948042008-03-11 19:44:10 +00001291 switch (getKind()) {
1292 default: assert(false);
Ted Kremenek61b9f872008-04-10 23:09:18 +00001293 case Owned: {
1294 Out << "Owned";
1295 unsigned cnt = getCount();
1296 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenekf3948042008-03-11 19:44:10 +00001297 break;
Ted Kremenek61b9f872008-04-10 23:09:18 +00001298 }
Ted Kremenekf3948042008-03-11 19:44:10 +00001299
Ted Kremenek61b9f872008-04-10 23:09:18 +00001300 case NotOwned: {
Ted Kremenek4fd88972008-04-17 18:12:53 +00001301 Out << "NotOwned";
Ted Kremenek61b9f872008-04-10 23:09:18 +00001302 unsigned cnt = getCount();
1303 if (cnt) Out << " (+ " << cnt << ")";
Ted Kremenekf3948042008-03-11 19:44:10 +00001304 break;
Ted Kremenek61b9f872008-04-10 23:09:18 +00001305 }
Ted Kremenekf3948042008-03-11 19:44:10 +00001306
Ted Kremenek4fd88972008-04-17 18:12:53 +00001307 case ReturnedOwned: {
1308 Out << "ReturnedOwned";
1309 unsigned cnt = getCount();
1310 if (cnt) Out << " (+ " << cnt << ")";
1311 break;
1312 }
1313
1314 case ReturnedNotOwned: {
1315 Out << "ReturnedNotOwned";
1316 unsigned cnt = getCount();
1317 if (cnt) Out << " (+ " << cnt << ")";
1318 break;
1319 }
1320
Ted Kremenekf3948042008-03-11 19:44:10 +00001321 case Released:
1322 Out << "Released";
1323 break;
1324
Ted Kremenekdb863712008-04-16 22:32:20 +00001325 case ErrorLeak:
1326 Out << "Leaked";
1327 break;
1328
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00001329 case ErrorLeakReturned:
1330 Out << "Leaked (Bad naming)";
1331 break;
1332
Ted Kremenekf3948042008-03-11 19:44:10 +00001333 case ErrorUseAfterRelease:
1334 Out << "Use-After-Release [ERROR]";
1335 break;
1336
1337 case ErrorReleaseNotOwned:
1338 Out << "Release of Not-Owned [ERROR]";
1339 break;
1340 }
1341}
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001342
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001343} // end anonymous namespace
1344
1345//===----------------------------------------------------------------------===//
1346// RefBindings - State used to track object reference counts.
1347//===----------------------------------------------------------------------===//
1348
Ted Kremenek2dabd432008-12-05 02:27:51 +00001349typedef llvm::ImmutableMap<SymbolRef, RefVal> RefBindings;
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001350static int RefBIndex = 0;
Ted Kremenek33b6f632009-02-19 23:47:02 +00001351static std::pair<const void*, const void*> LeakProgramPointTag(&RefBIndex, 0);
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001352
1353namespace clang {
Ted Kremenekb9d17f92008-08-17 03:20:02 +00001354 template<>
1355 struct GRStateTrait<RefBindings> : public GRStatePartialTrait<RefBindings> {
1356 static inline void* GDMIndex() { return &RefBIndex; }
1357 };
1358}
Ted Kremenek6d348932008-10-21 15:53:15 +00001359
1360//===----------------------------------------------------------------------===//
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001361// AutoreleaseBindings - State used to track objects in autorelease pools.
Ted Kremenek6d348932008-10-21 15:53:15 +00001362//===----------------------------------------------------------------------===//
1363
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001364typedef llvm::ImmutableMap<SymbolRef, unsigned> ARCounts;
1365typedef llvm::ImmutableMap<SymbolRef, ARCounts> ARPoolContents;
1366typedef llvm::ImmutableList<SymbolRef> ARStack;
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00001367
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001368static int AutoRCIndex = 0;
Ted Kremenek6d348932008-10-21 15:53:15 +00001369static int AutoRBIndex = 0;
1370
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001371namespace { class VISIBILITY_HIDDEN AutoreleasePoolContents {}; }
1372namespace { class VISIBILITY_HIDDEN AutoreleaseBindings {}; }
1373
Ted Kremenek6d348932008-10-21 15:53:15 +00001374namespace clang {
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001375template<> struct GRStateTrait<AutoreleaseBindings>
1376 : public GRStatePartialTrait<ARStack> {
1377 static inline void* GDMIndex() { return &AutoRBIndex; }
1378};
1379
1380template<> struct GRStateTrait<AutoreleasePoolContents>
1381 : public GRStatePartialTrait<ARPoolContents> {
1382 static inline void* GDMIndex() { return &AutoRCIndex; }
1383};
1384} // end clang namespace
Ted Kremenek6d348932008-10-21 15:53:15 +00001385
Ted Kremenek13922612008-04-16 20:40:59 +00001386//===----------------------------------------------------------------------===//
1387// Transfer functions.
1388//===----------------------------------------------------------------------===//
1389
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001390namespace {
1391
Ted Kremenek05cbe1a2008-04-09 23:49:11 +00001392class VISIBILITY_HIDDEN CFRefCount : public GRSimpleVals {
Ted Kremenek8dd56462008-04-18 03:39:05 +00001393public:
Ted Kremenekae6814e2008-08-13 21:24:49 +00001394 class BindingsPrinter : public GRState::Printer {
Ted Kremenekf3948042008-03-11 19:44:10 +00001395 public:
Ted Kremenekae6814e2008-08-13 21:24:49 +00001396 virtual void Print(std::ostream& Out, const GRState* state,
1397 const char* nl, const char* sep);
Ted Kremenekf3948042008-03-11 19:44:10 +00001398 };
Ted Kremenek8dd56462008-04-18 03:39:05 +00001399
1400private:
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001401 typedef llvm::DenseMap<const GRExprEngine::NodeTy*, const RetainSummary*>
1402 SummaryLogTy;
1403
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001404 RetainSummaryManager Summaries;
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001405 SummaryLogTy SummaryLog;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001406 const LangOptions& LOpts;
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001407 ARCounts::Factory ARCountFactory;
Ted Kremenekb9d17f92008-08-17 03:20:02 +00001408
Ted Kremenekcf701772009-02-05 06:50:21 +00001409 BugType *useAfterRelease, *releaseNotOwned;
1410 BugType *leakWithinFunction, *leakAtReturn;
1411 BugReporter *BR;
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001412
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001413 GRStateRef Update(GRStateRef state, SymbolRef sym, RefVal V, ArgEffect E,
1414 RefVal::Kind& hasErr);
1415
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001416 void ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
1417 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekdb863712008-04-16 22:32:20 +00001418 Expr* NodeExpr, Expr* ErrorExpr,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001419 ExplodedNode<GRState>* Pred,
1420 const GRState* St,
Ted Kremenek2dabd432008-12-05 02:27:51 +00001421 RefVal::Kind hasErr, SymbolRef Sym);
Ted Kremenekdb863712008-04-16 22:32:20 +00001422
Ted Kremenekf9790ae2008-10-24 20:32:50 +00001423 std::pair<GRStateRef, bool>
1424 HandleSymbolDeath(GRStateManager& VMgr, const GRState* St,
Ted Kremenek2dabd432008-12-05 02:27:51 +00001425 const Decl* CD, SymbolRef sid, RefVal V, bool& hasLeak);
Ted Kremenekdb863712008-04-16 22:32:20 +00001426
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001427public:
Ted Kremenek78d46242008-07-22 16:21:24 +00001428 CFRefCount(ASTContext& Ctx, bool gcenabled, const LangOptions& lopts)
Ted Kremenek377e2302008-04-29 05:33:51 +00001429 : Summaries(Ctx, gcenabled),
Ted Kremenekcf701772009-02-05 06:50:21 +00001430 LOpts(lopts), useAfterRelease(0), releaseNotOwned(0),
1431 leakWithinFunction(0), leakAtReturn(0), BR(0) {}
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001432
Ted Kremenekcf701772009-02-05 06:50:21 +00001433 virtual ~CFRefCount() {}
Ted Kremenek05cbe1a2008-04-09 23:49:11 +00001434
Ted Kremenekcf118d42009-02-04 23:49:09 +00001435 void RegisterChecks(BugReporter &BR);
Ted Kremenekf3948042008-03-11 19:44:10 +00001436
Ted Kremenek1c72ef02008-08-16 00:49:49 +00001437 virtual void RegisterPrinters(std::vector<GRState::Printer*>& Printers) {
1438 Printers.push_back(new BindingsPrinter());
Ted Kremenekf3948042008-03-11 19:44:10 +00001439 }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001440
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001441 bool isGCEnabled() const { return Summaries.isGCEnabled(); }
Ted Kremenek072192b2008-04-30 23:47:44 +00001442 const LangOptions& getLangOptions() const { return LOpts; }
1443
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001444 const RetainSummary *getSummaryOfNode(const ExplodedNode<GRState> *N) const {
1445 SummaryLogTy::const_iterator I = SummaryLog.find(N);
1446 return I == SummaryLog.end() ? 0 : I->second;
1447 }
1448
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001449 // Calls.
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001450
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001451 void EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001452 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001453 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001454 Expr* Ex,
1455 Expr* Receiver,
1456 RetainSummary* Summ,
Ted Kremenek55499762008-06-17 02:43:46 +00001457 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001458 ExplodedNode<GRState>* Pred);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001459
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001460 virtual void EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek199e1a02008-03-12 21:06:49 +00001461 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001462 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001463 CallExpr* CE, SVal L,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001464 ExplodedNode<GRState>* Pred);
Ted Kremenekfa34b332008-04-09 01:10:13 +00001465
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001466
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001467 virtual void EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek85348202008-04-15 23:44:31 +00001468 GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001469 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek85348202008-04-15 23:44:31 +00001470 ObjCMessageExpr* ME,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001471 ExplodedNode<GRState>* Pred);
Ted Kremenek85348202008-04-15 23:44:31 +00001472
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001473 bool EvalObjCMessageExprAux(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek85348202008-04-15 23:44:31 +00001474 GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001475 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek85348202008-04-15 23:44:31 +00001476 ObjCMessageExpr* ME,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001477 ExplodedNode<GRState>* Pred);
Ted Kremenek85348202008-04-15 23:44:31 +00001478
Ted Kremenek41573eb2009-02-14 01:43:44 +00001479 // Stores.
1480 virtual void EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val);
1481
Ted Kremeneke7bd9c22008-04-11 22:25:11 +00001482 // End-of-path.
1483
1484 virtual void EvalEndPath(GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001485 GREndPathNodeBuilder<GRState>& Builder);
Ted Kremeneke7bd9c22008-04-11 22:25:11 +00001486
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001487 virtual void EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek652adc62008-04-24 23:57:27 +00001488 GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001489 GRStmtNodeBuilder<GRState>& Builder,
1490 ExplodedNode<GRState>* Pred,
Ted Kremenek241677a2009-01-21 22:26:05 +00001491 Stmt* S, const GRState* state,
1492 SymbolReaper& SymReaper);
1493
Ted Kremenek4fd88972008-04-17 18:12:53 +00001494 // Return statements.
1495
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001496 virtual void EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4fd88972008-04-17 18:12:53 +00001497 GRExprEngine& Engine,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001498 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4fd88972008-04-17 18:12:53 +00001499 ReturnStmt* S,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001500 ExplodedNode<GRState>* Pred);
Ted Kremenekcb612922008-04-18 19:23:43 +00001501
1502 // Assumptions.
1503
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001504 virtual const GRState* EvalAssume(GRStateManager& VMgr,
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001505 const GRState* St, SVal Cond,
Ted Kremenek4323a572008-07-10 22:03:41 +00001506 bool Assumption, bool& isFeasible);
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001507};
1508
1509} // end anonymous namespace
1510
Ted Kremenek8dd56462008-04-18 03:39:05 +00001511
Ted Kremenekae6814e2008-08-13 21:24:49 +00001512void CFRefCount::BindingsPrinter::Print(std::ostream& Out, const GRState* state,
1513 const char* nl, const char* sep) {
1514
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001515 RefBindings B = state->get<RefBindings>();
Ted Kremenekf3948042008-03-11 19:44:10 +00001516
Ted Kremenekae6814e2008-08-13 21:24:49 +00001517 if (!B.isEmpty())
Ted Kremenekf3948042008-03-11 19:44:10 +00001518 Out << sep << nl;
1519
1520 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
1521 Out << (*I).first << " : ";
1522 (*I).second.print(Out);
1523 Out << nl;
1524 }
1525}
1526
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001527static inline ArgEffect GetArgE(RetainSummary* Summ, unsigned idx) {
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00001528 return Summ ? Summ->getArg(idx) : MayEscape;
Ted Kremenekf9561e52008-04-11 20:23:24 +00001529}
1530
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001531static inline RetEffect GetRetEffect(RetainSummary* Summ) {
1532 return Summ ? Summ->getRetEffect() : RetEffect::MakeNoRet();
Ted Kremenekf9561e52008-04-11 20:23:24 +00001533}
1534
Ted Kremenek14993892008-05-06 02:41:27 +00001535static inline ArgEffect GetReceiverE(RetainSummary* Summ) {
1536 return Summ ? Summ->getReceiverEffect() : DoNothing;
1537}
1538
Ted Kremenek70a733e2008-07-18 17:24:20 +00001539static inline bool IsEndPath(RetainSummary* Summ) {
1540 return Summ ? Summ->isEndPath() : false;
1541}
1542
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001543
Ted Kremenek553cf182008-06-25 21:21:56 +00001544/// GetReturnType - Used to get the return type of a message expression or
1545/// function call with the intention of affixing that type to a tracked symbol.
1546/// While the the return type can be queried directly from RetEx, when
1547/// invoking class methods we augment to the return type to be that of
1548/// a pointer to the class (as opposed it just being id).
1549static QualType GetReturnType(Expr* RetE, ASTContext& Ctx) {
1550
1551 QualType RetTy = RetE->getType();
1552
1553 // FIXME: We aren't handling id<...>.
Chris Lattner8b51fd72008-07-26 22:36:27 +00001554 const PointerType* PT = RetTy->getAsPointerType();
Ted Kremenek553cf182008-06-25 21:21:56 +00001555 if (!PT)
1556 return RetTy;
1557
1558 // If RetEx is not a message expression just return its type.
1559 // If RetEx is a message expression, return its types if it is something
1560 /// more specific than id.
1561
1562 ObjCMessageExpr* ME = dyn_cast<ObjCMessageExpr>(RetE);
1563
Steve Naroff389bf462009-02-12 17:52:19 +00001564 if (!ME || !Ctx.isObjCIdStructType(PT->getPointeeType()))
Ted Kremenek553cf182008-06-25 21:21:56 +00001565 return RetTy;
1566
1567 ObjCInterfaceDecl* D = ME->getClassInfo().first;
1568
1569 // At this point we know the return type of the message expression is id.
1570 // If we have an ObjCInterceDecl, we know this is a call to a class method
1571 // whose type we can resolve. In such cases, promote the return type to
1572 // Class*.
1573 return !D ? RetTy : Ctx.getPointerType(Ctx.getObjCInterfaceType(D));
1574}
1575
1576
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001577void CFRefCount::EvalSummary(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001578 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001579 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001580 Expr* Ex,
1581 Expr* Receiver,
1582 RetainSummary* Summ,
Ted Kremenek55499762008-06-17 02:43:46 +00001583 ExprIterator arg_beg, ExprIterator arg_end,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001584 ExplodedNode<GRState>* Pred) {
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001585
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001586 // Get the state.
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001587 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Ted Kremenekf9790ae2008-10-24 20:32:50 +00001588 ASTContext& Ctx = Eng.getStateManager().getContext();
Ted Kremenek14993892008-05-06 02:41:27 +00001589
1590 // Evaluate the effect of the arguments.
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001591 RefVal::Kind hasErr = (RefVal::Kind) 0;
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001592 unsigned idx = 0;
Ted Kremenekbcf50ad2008-04-11 18:40:51 +00001593 Expr* ErrorExpr = NULL;
Ted Kremenek2dabd432008-12-05 02:27:51 +00001594 SymbolRef ErrorSym = 0;
Ted Kremenekbcf50ad2008-04-11 18:40:51 +00001595
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001596 for (ExprIterator I = arg_beg; I != arg_end; ++I, ++idx) {
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001597 SVal V = state.GetSVal(*I);
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001598
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001599 if (isa<loc::SymbolVal>(V)) {
Ted Kremenek2dabd432008-12-05 02:27:51 +00001600 SymbolRef Sym = cast<loc::SymbolVal>(V).getSymbol();
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001601 if (RefBindings::data_type* T = state.get<RefBindings>(Sym)) {
1602 state = Update(state, Sym, *T, GetArgE(Summ, idx), hasErr);
1603 if (hasErr) {
Ted Kremenekbcf50ad2008-04-11 18:40:51 +00001604 ErrorExpr = *I;
Ted Kremeneke8fdc832008-07-07 16:21:19 +00001605 ErrorSym = Sym;
Ted Kremenekbcf50ad2008-04-11 18:40:51 +00001606 break;
1607 }
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001608 }
Ted Kremenekb8873552008-04-11 20:51:02 +00001609 }
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001610 else if (isa<Loc>(V)) {
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001611 if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(&V)) {
Ted Kremenek070a8252008-07-09 18:11:16 +00001612
1613 if (GetArgE(Summ, idx) == DoNothingByRef)
1614 continue;
1615
1616 // Invalidate the value of the variable passed by reference.
Ted Kremenek8c5633e2008-07-03 23:26:32 +00001617
1618 // FIXME: Either this logic should also be replicated in GRSimpleVals
1619 // or should be pulled into a separate "constraint engine."
Ted Kremenek070a8252008-07-09 18:11:16 +00001620
Ted Kremenek8c5633e2008-07-03 23:26:32 +00001621 // FIXME: We can have collisions on the conjured symbol if the
1622 // expression *I also creates conjured symbols. We probably want
1623 // to identify conjured symbols by an expression pair: the enclosing
1624 // expression (the context) and the expression itself. This should
Ted Kremenek070a8252008-07-09 18:11:16 +00001625 // disambiguate conjured symbols.
Ted Kremenek9e240492008-10-04 05:50:14 +00001626
Ted Kremenek993f1c72008-10-17 20:28:54 +00001627 const TypedRegion* R = dyn_cast<TypedRegion>(MR->getRegion());
Ted Kremenek90b32362008-12-17 19:42:34 +00001628
1629 // Blast through AnonTypedRegions to get the original region type.
1630 while (R) {
1631 const AnonTypedRegion* ATR = dyn_cast<AnonTypedRegion>(R);
1632 if (!ATR) break;
1633 R = dyn_cast<TypedRegion>(ATR->getSuperRegion());
1634 }
1635
Ted Kremenek9e240492008-10-04 05:50:14 +00001636 if (R) {
Ted Kremenek40e86d92008-12-18 23:34:57 +00001637
1638 // Is the invalidated variable something that we were tracking?
1639 SVal X = state.GetSVal(Loc::MakeVal(R));
1640
1641 if (isa<loc::SymbolVal>(X)) {
1642 SymbolRef Sym = cast<loc::SymbolVal>(X).getSymbol();
1643 state = state.remove<RefBindings>(Sym);
1644 }
1645
Ted Kremenek9e240492008-10-04 05:50:14 +00001646 // Set the value of the variable to be a conjured symbol.
1647 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenek6eddeb12008-12-13 21:49:13 +00001648 QualType T = R->getRValueType(Ctx);
Ted Kremenek9e240492008-10-04 05:50:14 +00001649
Ted Kremenekfd301942008-10-17 22:23:12 +00001650 // FIXME: handle structs.
Ted Kremenek062e2f92008-11-13 06:10:40 +00001651 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())) {
Ted Kremenek2dabd432008-12-05 02:27:51 +00001652 SymbolRef NewSym =
Ted Kremenekfd301942008-10-17 22:23:12 +00001653 Eng.getSymbolManager().getConjuredSymbol(*I, T, Count);
1654
Ted Kremenek90b32362008-12-17 19:42:34 +00001655 state = state.BindLoc(Loc::MakeVal(R),
Ted Kremenekfd301942008-10-17 22:23:12 +00001656 Loc::IsLocType(T)
1657 ? cast<SVal>(loc::SymbolVal(NewSym))
1658 : cast<SVal>(nonloc::SymbolVal(NewSym)));
1659 }
1660 else {
Ted Kremeneka441b7e2008-11-12 19:22:09 +00001661 state = state.BindLoc(*MR, UnknownVal());
Ted Kremenekfd301942008-10-17 22:23:12 +00001662 }
Ted Kremenek9e240492008-10-04 05:50:14 +00001663 }
1664 else
Ted Kremeneka441b7e2008-11-12 19:22:09 +00001665 state = state.BindLoc(*MR, UnknownVal());
Ted Kremenek8c5633e2008-07-03 23:26:32 +00001666 }
1667 else {
1668 // Nuke all other arguments passed by reference.
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001669 state = state.Unbind(cast<Loc>(V));
Ted Kremenek8c5633e2008-07-03 23:26:32 +00001670 }
Ted Kremenekb8873552008-04-11 20:51:02 +00001671 }
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001672 else if (isa<nonloc::LocAsInteger>(V))
1673 state = state.Unbind(cast<nonloc::LocAsInteger>(V).getLoc());
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001674 }
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001675
Ted Kremenek553cf182008-06-25 21:21:56 +00001676 // Evaluate the effect on the message receiver.
Ted Kremenek14993892008-05-06 02:41:27 +00001677 if (!ErrorExpr && Receiver) {
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001678 SVal V = state.GetSVal(Receiver);
1679 if (isa<loc::SymbolVal>(V)) {
Ted Kremenek2dabd432008-12-05 02:27:51 +00001680 SymbolRef Sym = cast<loc::SymbolVal>(V).getSymbol();
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001681 if (const RefVal* T = state.get<RefBindings>(Sym)) {
1682 state = Update(state, Sym, *T, GetReceiverE(Summ), hasErr);
1683 if (hasErr) {
Ted Kremenek14993892008-05-06 02:41:27 +00001684 ErrorExpr = Receiver;
Ted Kremeneke8fdc832008-07-07 16:21:19 +00001685 ErrorSym = Sym;
Ted Kremenek14993892008-05-06 02:41:27 +00001686 }
Ted Kremenek4d3957d2009-02-24 19:15:11 +00001687 }
Ted Kremenek14993892008-05-06 02:41:27 +00001688 }
1689 }
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001690
Ted Kremenek553cf182008-06-25 21:21:56 +00001691 // Process any errors.
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001692 if (hasErr) {
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001693 ProcessNonLeakError(Dst, Builder, Ex, ErrorExpr, Pred, state,
Ted Kremenek8dd56462008-04-18 03:39:05 +00001694 hasErr, ErrorSym);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001695 return;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00001696 }
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001697
Ted Kremenek70a733e2008-07-18 17:24:20 +00001698 // Consult the summary for the return value.
Ted Kremenek3c0cea32008-05-06 02:26:56 +00001699 RetEffect RE = GetRetEffect(Summ);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001700
1701 switch (RE.getKind()) {
1702 default:
1703 assert (false && "Unhandled RetEffect."); break;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001704
Ted Kremenekfd301942008-10-17 22:23:12 +00001705 case RetEffect::NoRet: {
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001706
Ted Kremenekf9561e52008-04-11 20:23:24 +00001707 // Make up a symbol for the return value (not reference counted).
Ted Kremenekb8873552008-04-11 20:51:02 +00001708 // FIXME: This is basically copy-and-paste from GRSimpleVals. We
1709 // should compose behavior, not copy it.
Ted Kremenekf9561e52008-04-11 20:23:24 +00001710
Ted Kremenekfd301942008-10-17 22:23:12 +00001711 // FIXME: We eventually should handle structs and other compound types
1712 // that are returned by value.
1713
1714 QualType T = Ex->getType();
1715
Ted Kremenek062e2f92008-11-13 06:10:40 +00001716 if (Loc::IsLocType(T) || (T->isIntegerType() && T->isScalarType())) {
Ted Kremenekf9561e52008-04-11 20:23:24 +00001717 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenek2dabd432008-12-05 02:27:51 +00001718 SymbolRef Sym = Eng.getSymbolManager().getConjuredSymbol(Ex, Count);
Ted Kremenekf9561e52008-04-11 20:23:24 +00001719
Ted Kremenekc3cf7b22009-02-20 00:05:35 +00001720 SVal X = Loc::IsLocType(T)
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001721 ? cast<SVal>(loc::SymbolVal(Sym))
1722 : cast<SVal>(nonloc::SymbolVal(Sym));
Ted Kremenekf9561e52008-04-11 20:23:24 +00001723
Ted Kremeneka441b7e2008-11-12 19:22:09 +00001724 state = state.BindExpr(Ex, X, false);
Ted Kremenekf9561e52008-04-11 20:23:24 +00001725 }
1726
Ted Kremenek940b1d82008-04-10 23:44:06 +00001727 break;
Ted Kremenekfd301942008-10-17 22:23:12 +00001728 }
Ted Kremenek940b1d82008-04-10 23:44:06 +00001729
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001730 case RetEffect::Alias: {
Ted Kremenek553cf182008-06-25 21:21:56 +00001731 unsigned idx = RE.getIndex();
Ted Kremenek55499762008-06-17 02:43:46 +00001732 assert (arg_end >= arg_beg);
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001733 assert (idx < (unsigned) (arg_end - arg_beg));
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001734 SVal V = state.GetSVal(*(arg_beg+idx));
Ted Kremeneka441b7e2008-11-12 19:22:09 +00001735 state = state.BindExpr(Ex, V, false);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001736 break;
1737 }
1738
Ted Kremenek14993892008-05-06 02:41:27 +00001739 case RetEffect::ReceiverAlias: {
1740 assert (Receiver);
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001741 SVal V = state.GetSVal(Receiver);
Ted Kremeneka441b7e2008-11-12 19:22:09 +00001742 state = state.BindExpr(Ex, V, false);
Ted Kremenek14993892008-05-06 02:41:27 +00001743 break;
1744 }
1745
Ted Kremeneka7344702008-06-23 18:02:52 +00001746 case RetEffect::OwnedAllocatedSymbol:
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001747 case RetEffect::OwnedSymbol: {
1748 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenek2dabd432008-12-05 02:27:51 +00001749 SymbolRef Sym = Eng.getSymbolManager().getConjuredSymbol(Ex, Count);
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001750 QualType RetT = GetReturnType(Ex, Eng.getContext());
1751 state =
1752 state.set<RefBindings>(Sym, RefVal::makeOwned(RE.getObjKind(), RetT));
Ted Kremeneka441b7e2008-11-12 19:22:09 +00001753 state = state.BindExpr(Ex, loc::SymbolVal(Sym), false);
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001754
Ted Kremeneka7344702008-06-23 18:02:52 +00001755 // FIXME: Add a flag to the checker where allocations are allowed to fail.
Ted Kremenekb2bf7cd2009-01-28 22:27:59 +00001756 if (RE.getKind() == RetEffect::OwnedAllocatedSymbol) {
1757 bool isFeasible;
1758 state = state.Assume(loc::SymbolVal(Sym), true, isFeasible);
1759 assert(isFeasible && "Cannot assume fresh symbol is non-null.");
1760 }
Ted Kremeneka7344702008-06-23 18:02:52 +00001761
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001762 break;
1763 }
1764
1765 case RetEffect::NotOwnedSymbol: {
1766 unsigned Count = Builder.getCurrentBlockCount();
Ted Kremenek2dabd432008-12-05 02:27:51 +00001767 SymbolRef Sym = Eng.getSymbolManager().getConjuredSymbol(Ex, Count);
Ted Kremenek553cf182008-06-25 21:21:56 +00001768 QualType RetT = GetReturnType(Ex, Eng.getContext());
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001769
Ted Kremenek2d1652e2009-01-28 05:56:51 +00001770 state =
1771 state.set<RefBindings>(Sym, RefVal::makeNotOwned(RE.getObjKind(),RetT));
Ted Kremeneka441b7e2008-11-12 19:22:09 +00001772 state = state.BindExpr(Ex, loc::SymbolVal(Sym), false);
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00001773 break;
1774 }
1775 }
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001776
Ted Kremenekf5b34b12009-02-18 02:00:25 +00001777 // Generate a sink node if we are at the end of a path.
1778 GRExprEngine::NodeTy *NewNode =
1779 IsEndPath(Summ) ? Builder.MakeSinkNode(Dst, Ex, Pred, state)
1780 : Builder.MakeNode(Dst, Ex, Pred, state);
1781
1782 // Annotate the edge with summary we used.
1783 // FIXME: This assumes that we always use the same summary when generating
1784 // this node.
1785 if (NewNode) SummaryLog[NewNode] = Summ;
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001786}
1787
1788
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001789void CFRefCount::EvalCall(ExplodedNodeSet<GRState>& Dst,
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001790 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001791 GRStmtNodeBuilder<GRState>& Builder,
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001792 CallExpr* CE, SVal L,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001793 ExplodedNode<GRState>* Pred) {
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001794
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001795 RetainSummary* Summ = !isa<loc::FuncVal>(L) ? 0
1796 : Summaries.getSummary(cast<loc::FuncVal>(L).getDecl());
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00001797
1798 EvalSummary(Dst, Eng, Builder, CE, 0, Summ,
1799 CE->arg_begin(), CE->arg_end(), Pred);
Ted Kremenek2fff37e2008-03-06 00:08:09 +00001800}
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00001801
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001802void CFRefCount::EvalObjCMessageExpr(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek85348202008-04-15 23:44:31 +00001803 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001804 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek85348202008-04-15 23:44:31 +00001805 ObjCMessageExpr* ME,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001806 ExplodedNode<GRState>* Pred) {
Ted Kremenekb3095252008-05-06 04:20:12 +00001807 RetainSummary* Summ;
Ted Kremenek9040c652008-05-01 21:31:50 +00001808
Ted Kremenek553cf182008-06-25 21:21:56 +00001809 if (Expr* Receiver = ME->getReceiver()) {
1810 // We need the type-information of the tracked receiver object
1811 // Retrieve it from the state.
1812 ObjCInterfaceDecl* ID = 0;
1813
1814 // FIXME: Wouldn't it be great if this code could be reduced? It's just
1815 // a chain of lookups.
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001816 const GRState* St = Builder.GetState(Pred);
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001817 SVal V = Eng.getStateManager().GetSVal(St, Receiver );
Ted Kremenek553cf182008-06-25 21:21:56 +00001818
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001819 if (isa<loc::SymbolVal>(V)) {
Ted Kremenek2dabd432008-12-05 02:27:51 +00001820 SymbolRef Sym = cast<loc::SymbolVal>(V).getSymbol();
Ted Kremenek553cf182008-06-25 21:21:56 +00001821
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001822 if (const RefVal* T = St->get<RefBindings>(Sym)) {
Ted Kremeneke8fdc832008-07-07 16:21:19 +00001823 QualType Ty = T->getType();
Ted Kremenek553cf182008-06-25 21:21:56 +00001824
1825 if (const PointerType* PT = Ty->getAsPointerType()) {
1826 QualType PointeeTy = PT->getPointeeType();
1827
1828 if (ObjCInterfaceType* IT = dyn_cast<ObjCInterfaceType>(PointeeTy))
1829 ID = IT->getDecl();
1830 }
1831 }
1832 }
1833
1834 Summ = Summaries.getMethodSummary(ME, ID);
Ted Kremenekf9790ae2008-10-24 20:32:50 +00001835
Ted Kremenek896cd9d2008-10-23 01:56:15 +00001836 // Special-case: are we sending a mesage to "self"?
1837 // This is a hack. When we have full-IP this should be removed.
1838 if (!Summ) {
1839 ObjCMethodDecl* MD =
1840 dyn_cast<ObjCMethodDecl>(&Eng.getGraph().getCodeDecl());
1841
1842 if (MD) {
1843 if (Expr* Receiver = ME->getReceiver()) {
1844 SVal X = Eng.getStateManager().GetSVal(St, Receiver);
1845 if (loc::MemRegionVal* L = dyn_cast<loc::MemRegionVal>(&X))
Ted Kremenekf9790ae2008-10-24 20:32:50 +00001846 if (L->getRegion() == Eng.getStateManager().getSelfRegion(St)) {
1847 // Create a summmary where all of the arguments "StopTracking".
1848 Summ = Summaries.getPersistentSummary(RetEffect::MakeNoRet(),
1849 DoNothing,
1850 StopTracking);
1851 }
Ted Kremenek896cd9d2008-10-23 01:56:15 +00001852 }
1853 }
1854 }
Ted Kremenek553cf182008-06-25 21:21:56 +00001855 }
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001856 else
Ted Kremenek1f180c32008-06-23 22:21:20 +00001857 Summ = Summaries.getClassMethodSummary(ME->getClassName(),
1858 ME->getSelector());
Ted Kremenek9ed18e62008-04-16 04:28:53 +00001859
Ted Kremenekb3095252008-05-06 04:20:12 +00001860 EvalSummary(Dst, Eng, Builder, ME, ME->getReceiver(), Summ,
1861 ME->arg_begin(), ME->arg_end(), Pred);
Ted Kremenek85348202008-04-15 23:44:31 +00001862}
Ted Kremenek5216ad72009-02-14 03:16:10 +00001863
1864namespace {
1865class VISIBILITY_HIDDEN StopTrackingCallback : public SymbolVisitor {
1866 GRStateRef state;
1867public:
1868 StopTrackingCallback(GRStateRef st) : state(st) {}
1869 GRStateRef getState() { return state; }
1870
1871 bool VisitSymbol(SymbolRef sym) {
1872 state = state.remove<RefBindings>(sym);
1873 return true;
1874 }
Ted Kremenekb3095252008-05-06 04:20:12 +00001875
Ted Kremenek5216ad72009-02-14 03:16:10 +00001876 const GRState* getState() const { return state.getState(); }
1877};
1878} // end anonymous namespace
1879
1880
Ted Kremenek41573eb2009-02-14 01:43:44 +00001881void CFRefCount::EvalBind(GRStmtNodeBuilderRef& B, SVal location, SVal val) {
Ted Kremenek41573eb2009-02-14 01:43:44 +00001882 // Are we storing to something that causes the value to "escape"?
Ted Kremenek13922612008-04-16 20:40:59 +00001883 bool escapes = false;
1884
Ted Kremeneka496d162008-10-18 03:49:51 +00001885 // A value escapes in three possible cases (this may change):
1886 //
1887 // (1) we are binding to something that is not a memory region.
1888 // (2) we are binding to a memregion that does not have stack storage
1889 // (3) we are binding to a memregion with stack storage that the store
Ted Kremenek41573eb2009-02-14 01:43:44 +00001890 // does not understand.
Ted Kremenek41573eb2009-02-14 01:43:44 +00001891 GRStateRef state = B.getState();
Ted Kremeneka496d162008-10-18 03:49:51 +00001892
Ted Kremenek41573eb2009-02-14 01:43:44 +00001893 if (!isa<loc::MemRegionVal>(location))
Ted Kremenek13922612008-04-16 20:40:59 +00001894 escapes = true;
Ted Kremenek9e240492008-10-04 05:50:14 +00001895 else {
Ted Kremenek41573eb2009-02-14 01:43:44 +00001896 const MemRegion* R = cast<loc::MemRegionVal>(location).getRegion();
1897 escapes = !B.getStateManager().hasStackStorage(R);
Ted Kremeneka496d162008-10-18 03:49:51 +00001898
1899 if (!escapes) {
1900 // To test (3), generate a new state with the binding removed. If it is
1901 // the same state, then it escapes (since the store cannot represent
1902 // the binding).
Ted Kremenek41573eb2009-02-14 01:43:44 +00001903 escapes = (state == (state.BindLoc(cast<Loc>(location), UnknownVal())));
Ted Kremeneka496d162008-10-18 03:49:51 +00001904 }
Ted Kremenek9e240492008-10-04 05:50:14 +00001905 }
Ted Kremenek41573eb2009-02-14 01:43:44 +00001906
Ted Kremenek5216ad72009-02-14 03:16:10 +00001907 // If our store can represent the binding and we aren't storing to something
1908 // that doesn't have local storage then just return and have the simulation
1909 // state continue as is.
1910 if (!escapes)
1911 return;
Ted Kremeneka496d162008-10-18 03:49:51 +00001912
Ted Kremenek5216ad72009-02-14 03:16:10 +00001913 // Otherwise, find all symbols referenced by 'val' that we are tracking
1914 // and stop tracking them.
1915 B.MakeNode(state.scanReachableSymbols<StopTrackingCallback>(val).getState());
Ted Kremenekdb863712008-04-16 22:32:20 +00001916}
1917
Ted Kremenekf9790ae2008-10-24 20:32:50 +00001918std::pair<GRStateRef,bool>
1919CFRefCount::HandleSymbolDeath(GRStateManager& VMgr,
1920 const GRState* St, const Decl* CD,
Ted Kremenek2dabd432008-12-05 02:27:51 +00001921 SymbolRef sid,
Ted Kremenekf9790ae2008-10-24 20:32:50 +00001922 RefVal V, bool& hasLeak) {
Ted Kremenekdb863712008-04-16 22:32:20 +00001923
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001924 GRStateRef state(St, VMgr);
Sanjiv Gupta31fc07d2008-10-31 09:52:39 +00001925 assert ((!V.isReturnedOwned() || CD) &&
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00001926 "CodeDecl must be available for reporting ReturnOwned errors.");
Ted Kremenek896cd9d2008-10-23 01:56:15 +00001927
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00001928 if (V.isReturnedOwned() && V.getCount() == 0)
1929 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(CD)) {
Chris Lattner077bf5e2008-11-24 03:33:13 +00001930 std::string s = MD->getSelector().getAsString();
Ted Kremenek4c79e552008-11-05 16:54:44 +00001931 if (!followsReturnRule(s.c_str())) {
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00001932 hasLeak = true;
Ted Kremenekf9790ae2008-10-24 20:32:50 +00001933 state = state.set<RefBindings>(sid, V ^ RefVal::ErrorLeakReturned);
1934 return std::make_pair(state, true);
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00001935 }
1936 }
Ted Kremenek896cd9d2008-10-23 01:56:15 +00001937
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00001938 // All other cases.
1939
1940 hasLeak = V.isOwned() ||
1941 ((V.isNotOwned() || V.isReturnedOwned()) && V.getCount() > 0);
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001942
Ted Kremenekdb863712008-04-16 22:32:20 +00001943 if (!hasLeak)
Ted Kremenekf9790ae2008-10-24 20:32:50 +00001944 return std::make_pair(state.remove<RefBindings>(sid), false);
Ted Kremenekdb863712008-04-16 22:32:20 +00001945
Ted Kremenekf9790ae2008-10-24 20:32:50 +00001946 return std::make_pair(state.set<RefBindings>(sid, V ^ RefVal::ErrorLeak),
1947 false);
Ted Kremenekdb863712008-04-16 22:32:20 +00001948}
1949
Ted Kremenek652adc62008-04-24 23:57:27 +00001950
Ted Kremeneke7bd9c22008-04-11 22:25:11 +00001951
Ted Kremenek652adc62008-04-24 23:57:27 +00001952// Dead symbols.
1953
Ted Kremenekcf701772009-02-05 06:50:21 +00001954
Ted Kremenek652adc62008-04-24 23:57:27 +00001955
Ted Kremenek4fd88972008-04-17 18:12:53 +00001956 // Return statements.
1957
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001958void CFRefCount::EvalReturn(ExplodedNodeSet<GRState>& Dst,
Ted Kremenek4fd88972008-04-17 18:12:53 +00001959 GRExprEngine& Eng,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001960 GRStmtNodeBuilder<GRState>& Builder,
Ted Kremenek4fd88972008-04-17 18:12:53 +00001961 ReturnStmt* S,
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001962 ExplodedNode<GRState>* Pred) {
Ted Kremenek4fd88972008-04-17 18:12:53 +00001963
1964 Expr* RetE = S->getRetValue();
1965 if (!RetE) return;
1966
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001967 GRStateRef state(Builder.GetState(Pred), Eng.getStateManager());
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001968 SVal V = state.GetSVal(RetE);
Ted Kremenek4fd88972008-04-17 18:12:53 +00001969
Zhongxing Xu1c96b242008-10-17 05:57:07 +00001970 if (!isa<loc::SymbolVal>(V))
Ted Kremenek4fd88972008-04-17 18:12:53 +00001971 return;
1972
1973 // Get the reference count binding (if any).
Ted Kremenek2dabd432008-12-05 02:27:51 +00001974 SymbolRef Sym = cast<loc::SymbolVal>(V).getSymbol();
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001975 const RefVal* T = state.get<RefBindings>(Sym);
Ted Kremenek4fd88972008-04-17 18:12:53 +00001976
1977 if (!T)
1978 return;
1979
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001980 // Change the reference count.
Ted Kremeneke8fdc832008-07-07 16:21:19 +00001981 RefVal X = *T;
Ted Kremenek4fd88972008-04-17 18:12:53 +00001982
Ted Kremenek72cd17f2008-08-14 21:16:54 +00001983 switch (X.getKind()) {
Ted Kremenek4fd88972008-04-17 18:12:53 +00001984 case RefVal::Owned: {
1985 unsigned cnt = X.getCount();
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00001986 assert (cnt > 0);
1987 X = RefVal::makeReturnedOwned(cnt - 1);
Ted Kremenek4fd88972008-04-17 18:12:53 +00001988 break;
1989 }
1990
1991 case RefVal::NotOwned: {
1992 unsigned cnt = X.getCount();
1993 X = cnt ? RefVal::makeReturnedOwned(cnt - 1)
1994 : RefVal::makeReturnedNotOwned();
1995 break;
1996 }
1997
1998 default:
Ted Kremenek4fd88972008-04-17 18:12:53 +00001999 return;
2000 }
2001
2002 // Update the binding.
Ted Kremenekb9d17f92008-08-17 03:20:02 +00002003 state = state.set<RefBindings>(Sym, X);
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002004 Builder.MakeNode(Dst, S, Pred, state);
Ted Kremenek4fd88972008-04-17 18:12:53 +00002005}
2006
Ted Kremenekcb612922008-04-18 19:23:43 +00002007// Assumptions.
2008
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002009const GRState* CFRefCount::EvalAssume(GRStateManager& VMgr,
2010 const GRState* St,
Zhongxing Xu1c96b242008-10-17 05:57:07 +00002011 SVal Cond, bool Assumption,
Ted Kremenek4323a572008-07-10 22:03:41 +00002012 bool& isFeasible) {
Ted Kremenekcb612922008-04-18 19:23:43 +00002013
2014 // FIXME: We may add to the interface of EvalAssume the list of symbols
2015 // whose assumptions have changed. For now we just iterate through the
2016 // bindings and check if any of the tracked symbols are NULL. This isn't
2017 // too bad since the number of symbols we will track in practice are
2018 // probably small and EvalAssume is only called at branches and a few
2019 // other places.
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002020 RefBindings B = St->get<RefBindings>();
Ted Kremenekcb612922008-04-18 19:23:43 +00002021
2022 if (B.isEmpty())
2023 return St;
2024
2025 bool changed = false;
Ted Kremenekb9d17f92008-08-17 03:20:02 +00002026
2027 GRStateRef state(St, VMgr);
2028 RefBindings::Factory& RefBFactory = state.get_context<RefBindings>();
Ted Kremenekcb612922008-04-18 19:23:43 +00002029
2030 for (RefBindings::iterator I=B.begin(), E=B.end(); I!=E; ++I) {
Ted Kremenekcb612922008-04-18 19:23:43 +00002031 // Check if the symbol is null (or equal to any constant).
2032 // If this is the case, stop tracking the symbol.
Zhongxing Xu39cfed32008-08-29 14:52:36 +00002033 if (VMgr.getSymVal(St, I.getKey())) {
Ted Kremenekcb612922008-04-18 19:23:43 +00002034 changed = true;
2035 B = RefBFactory.Remove(B, I.getKey());
2036 }
2037 }
2038
Ted Kremenekb9d17f92008-08-17 03:20:02 +00002039 if (changed)
2040 state = state.set<RefBindings>(B);
Ted Kremenekcb612922008-04-18 19:23:43 +00002041
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002042 return state;
Ted Kremenekcb612922008-04-18 19:23:43 +00002043}
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00002044
Ted Kremenek4d3957d2009-02-24 19:15:11 +00002045GRStateRef CFRefCount::Update(GRStateRef state, SymbolRef sym,
2046 RefVal V, ArgEffect E,
2047 RefVal::Kind& hasErr) {
Ted Kremenek1c512f52009-02-18 18:54:33 +00002048
2049 // In GC mode [... release] and [... retain] do nothing.
2050 switch (E) {
2051 default: break;
2052 case IncRefMsg: E = isGCEnabled() ? DoNothing : IncRef; break;
2053 case DecRefMsg: E = isGCEnabled() ? DoNothing : DecRef; break;
Ted Kremenek27019002009-02-18 21:57:45 +00002054 case MakeCollectable: E = isGCEnabled() ? DecRef : DoNothing; break;
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00002055 case NewAutoreleasePool: E = isGCEnabled() ? DoNothing :
2056 NewAutoreleasePool; break;
Ted Kremenek1c512f52009-02-18 18:54:33 +00002057 }
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00002058
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002059 switch (E) {
2060 default:
2061 assert (false && "Unhandled CFRef transition.");
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00002062
2063 case MayEscape:
2064 if (V.getKind() == RefVal::Owned) {
Ted Kremenek553cf182008-06-25 21:21:56 +00002065 V = V ^ RefVal::NotOwned;
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00002066 break;
2067 }
Ted Kremenek3eabf1c2008-05-22 17:31:13 +00002068 // Fall-through.
Ted Kremenekf9a8e2e2009-02-23 17:45:03 +00002069
2070 case NewAutoreleasePool: // FIXME: Implement pushing the pool to the stack.
Ted Kremenek070a8252008-07-09 18:11:16 +00002071 case DoNothingByRef:
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002072 case DoNothing:
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002073 if (!isGCEnabled() && V.getKind() == RefVal::Released) {
Ted Kremenek553cf182008-06-25 21:21:56 +00002074 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek9ed18e62008-04-16 04:28:53 +00002075 hasErr = V.getKind();
Ted Kremenek00a3a5f2008-03-12 01:21:45 +00002076 break;
Ted Kremenek9e476de2008-08-12 18:30:56 +00002077 }
Ted Kremenek4d3957d2009-02-24 19:15:11 +00002078 return state;
Ted Kremeneke19f4492008-06-30 16:57:41 +00002079
Ted Kremenekabf43972009-01-28 21:44:40 +00002080 case Autorelease:
Ted Kremenek4d3957d2009-02-24 19:15:11 +00002081 if (isGCEnabled()) return state;
Ted Kremenekabf43972009-01-28 21:44:40 +00002082 // Fall-through.
Ted Kremenek14993892008-05-06 02:41:27 +00002083 case StopTracking:
Ted Kremenek4d3957d2009-02-24 19:15:11 +00002084 return state.remove<RefBindings>(sym);
Ted Kremenek9e476de2008-08-12 18:30:56 +00002085
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002086 case IncRef:
2087 switch (V.getKind()) {
2088 default:
2089 assert(false);
2090
2091 case RefVal::Owned:
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002092 case RefVal::NotOwned:
Ted Kremenek553cf182008-06-25 21:21:56 +00002093 V = V + 1;
Ted Kremenek9e476de2008-08-12 18:30:56 +00002094 break;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002095 case RefVal::Released:
Ted Kremenekd3dbcf42008-05-05 22:11:16 +00002096 if (isGCEnabled())
Ted Kremenekbb8c5aa2009-02-18 22:57:22 +00002097 V = (V ^ RefVal::Owned) + 1;
Ted Kremenek65c91652008-04-29 05:44:10 +00002098 else {
Ted Kremenek553cf182008-06-25 21:21:56 +00002099 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek65c91652008-04-29 05:44:10 +00002100 hasErr = V.getKind();
2101 }
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002102 break;
Ted Kremenek9e476de2008-08-12 18:30:56 +00002103 }
Ted Kremenek940b1d82008-04-10 23:44:06 +00002104 break;
2105
Ted Kremenek553cf182008-06-25 21:21:56 +00002106 case SelfOwn:
2107 V = V ^ RefVal::NotOwned;
Ted Kremenek1c512f52009-02-18 18:54:33 +00002108 // Fall-through.
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002109 case DecRef:
2110 switch (V.getKind()) {
2111 default:
2112 assert (false);
Ted Kremenek9e476de2008-08-12 18:30:56 +00002113
Ted Kremenek553cf182008-06-25 21:21:56 +00002114 case RefVal::Owned:
Ted Kremenekbb8c5aa2009-02-18 22:57:22 +00002115 assert(V.getCount() > 0);
2116 if (V.getCount() == 1) V = V ^ RefVal::Released;
2117 V = V - 1;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002118 break;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002119
Ted Kremenek553cf182008-06-25 21:21:56 +00002120 case RefVal::NotOwned:
2121 if (V.getCount() > 0)
2122 V = V - 1;
Ted Kremenek61b9f872008-04-10 23:09:18 +00002123 else {
Ted Kremenek553cf182008-06-25 21:21:56 +00002124 V = V ^ RefVal::ErrorReleaseNotOwned;
Ted Kremenek9ed18e62008-04-16 04:28:53 +00002125 hasErr = V.getKind();
Ted Kremenek9e476de2008-08-12 18:30:56 +00002126 }
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002127 break;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002128
2129 case RefVal::Released:
Ted Kremenek553cf182008-06-25 21:21:56 +00002130 V = V ^ RefVal::ErrorUseAfterRelease;
Ted Kremenek9ed18e62008-04-16 04:28:53 +00002131 hasErr = V.getKind();
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002132 break;
Ted Kremenek9e476de2008-08-12 18:30:56 +00002133 }
Ted Kremenek940b1d82008-04-10 23:44:06 +00002134 break;
Ted Kremenek1ac08d62008-03-11 17:48:22 +00002135 }
Ted Kremenek4d3957d2009-02-24 19:15:11 +00002136 return state.set<RefBindings>(sym, V);
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00002137}
2138
Ted Kremenekfa34b332008-04-09 01:10:13 +00002139//===----------------------------------------------------------------------===//
Ted Kremenek05cbe1a2008-04-09 23:49:11 +00002140// Error reporting.
Ted Kremenekfa34b332008-04-09 01:10:13 +00002141//===----------------------------------------------------------------------===//
2142
Ted Kremenek8dd56462008-04-18 03:39:05 +00002143namespace {
2144
2145 //===-------------===//
2146 // Bug Descriptions. //
2147 //===-------------===//
2148
Ted Kremenekcf118d42009-02-04 23:49:09 +00002149 class VISIBILITY_HIDDEN CFRefBug : public BugType {
Ted Kremenek8dd56462008-04-18 03:39:05 +00002150 protected:
2151 CFRefCount& TF;
Ted Kremenekcf118d42009-02-04 23:49:09 +00002152
2153 CFRefBug(CFRefCount* tf, const char* name)
2154 : BugType(name, "Memory (Core Foundation/Objective-C)"), TF(*tf) {}
Ted Kremenek8dd56462008-04-18 03:39:05 +00002155 public:
Ted Kremenek072192b2008-04-30 23:47:44 +00002156
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00002157 CFRefCount& getTF() { return TF; }
Ted Kremenek789deac2008-05-05 23:16:31 +00002158 const CFRefCount& getTF() const { return TF; }
2159
Ted Kremenekcf118d42009-02-04 23:49:09 +00002160 // FIXME: Eventually remove.
2161 virtual const char* getDescription() const = 0;
2162
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00002163 virtual bool isLeak() const { return false; }
Ted Kremenek8dd56462008-04-18 03:39:05 +00002164 };
2165
2166 class VISIBILITY_HIDDEN UseAfterRelease : public CFRefBug {
2167 public:
Ted Kremenekcf118d42009-02-04 23:49:09 +00002168 UseAfterRelease(CFRefCount* tf)
2169 : CFRefBug(tf, "use-after-release") {}
Ted Kremenek8dd56462008-04-18 03:39:05 +00002170
Ted Kremenekcf118d42009-02-04 23:49:09 +00002171 const char* getDescription() const {
Ted Kremenek9e476de2008-08-12 18:30:56 +00002172 return "Reference-counted object is used after it is released.";
Ted Kremenekcf701772009-02-05 06:50:21 +00002173 }
Ted Kremenek8dd56462008-04-18 03:39:05 +00002174 };
2175
2176 class VISIBILITY_HIDDEN BadRelease : public CFRefBug {
2177 public:
Ted Kremenekcf118d42009-02-04 23:49:09 +00002178 BadRelease(CFRefCount* tf) : CFRefBug(tf, "bad release") {}
2179
2180 const char* getDescription() const {
Ted Kremenek8dd56462008-04-18 03:39:05 +00002181 return "Incorrect decrement of the reference count of a "
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002182 "CoreFoundation object: "
Ted Kremenek8dd56462008-04-18 03:39:05 +00002183 "The object is not owned at this point by the caller.";
2184 }
Ted Kremenek8dd56462008-04-18 03:39:05 +00002185 };
2186
2187 class VISIBILITY_HIDDEN Leak : public CFRefBug {
Ted Kremenekcf118d42009-02-04 23:49:09 +00002188 const bool isReturn;
2189 protected:
2190 Leak(CFRefCount* tf, const char* name, bool isRet)
2191 : CFRefBug(tf, name), isReturn(isRet) {}
Ted Kremenek8dd56462008-04-18 03:39:05 +00002192 public:
Ted Kremenek8dd56462008-04-18 03:39:05 +00002193
Ted Kremenekd3057212009-02-07 22:38:00 +00002194 const char* getDescription() const { return ""; }
Ted Kremenek3148eb42009-01-24 00:55:43 +00002195
Ted Kremeneke45e57f2009-02-05 00:38:00 +00002196 bool isLeak() const { return true; }
Ted Kremenek8dd56462008-04-18 03:39:05 +00002197 };
Ted Kremenekcf118d42009-02-04 23:49:09 +00002198
2199 class VISIBILITY_HIDDEN LeakAtReturn : public Leak {
2200 public:
2201 LeakAtReturn(CFRefCount* tf, const char* name)
2202 : Leak(tf, name, true) {}
2203 };
2204
2205 class VISIBILITY_HIDDEN LeakWithinFunction : public Leak {
2206 public:
2207 LeakWithinFunction(CFRefCount* tf, const char* name)
2208 : Leak(tf, name, false) {}
2209 };
Ted Kremenek8dd56462008-04-18 03:39:05 +00002210
2211 //===---------===//
2212 // Bug Reports. //
2213 //===---------===//
2214
2215 class VISIBILITY_HIDDEN CFRefReport : public RangedBugReport {
Ted Kremenek66d97062009-02-07 22:04:05 +00002216 protected:
Ted Kremenek2dabd432008-12-05 02:27:51 +00002217 SymbolRef Sym;
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002218 const CFRefCount &TF;
Ted Kremenek8dd56462008-04-18 03:39:05 +00002219 public:
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002220 CFRefReport(CFRefBug& D, const CFRefCount &tf,
2221 ExplodedNode<GRState> *n, SymbolRef sym)
2222 : RangedBugReport(D, D.getDescription(), n), Sym(sym), TF(tf) {}
Ted Kremenek8dd56462008-04-18 03:39:05 +00002223
2224 virtual ~CFRefReport() {}
2225
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00002226 CFRefBug& getBugType() {
2227 return (CFRefBug&) RangedBugReport::getBugType();
2228 }
2229 const CFRefBug& getBugType() const {
2230 return (const CFRefBug&) RangedBugReport::getBugType();
2231 }
2232
2233 virtual void getRanges(BugReporter& BR, const SourceRange*& beg,
2234 const SourceRange*& end) {
2235
Ted Kremeneke92c1b22008-05-02 20:53:50 +00002236 if (!getBugType().isLeak())
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00002237 RangedBugReport::getRanges(BR, beg, end);
Ted Kremenek9e476de2008-08-12 18:30:56 +00002238 else
2239 beg = end = 0;
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00002240 }
2241
Ted Kremenek2dabd432008-12-05 02:27:51 +00002242 SymbolRef getSymbol() const { return Sym; }
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002243
Ted Kremenek3148eb42009-01-24 00:55:43 +00002244 PathDiagnosticPiece* getEndPath(BugReporter& BR,
2245 const ExplodedNode<GRState>* N);
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00002246
Ted Kremenek3148eb42009-01-24 00:55:43 +00002247 std::pair<const char**,const char**> getExtraDescriptiveText();
Ted Kremenek8dd56462008-04-18 03:39:05 +00002248
Ted Kremenek3148eb42009-01-24 00:55:43 +00002249 PathDiagnosticPiece* VisitNode(const ExplodedNode<GRState>* N,
2250 const ExplodedNode<GRState>* PrevN,
2251 const ExplodedGraph<GRState>& G,
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002252 BugReporter& BR,
2253 NodeResolver& NR);
Ted Kremenek8dd56462008-04-18 03:39:05 +00002254 };
2255
Ted Kremenekcf118d42009-02-04 23:49:09 +00002256 class VISIBILITY_HIDDEN CFRefLeakReport : public CFRefReport {
Ted Kremeneke469fa02009-02-07 22:19:59 +00002257 SourceLocation AllocSite;
2258 const MemRegion* AllocBinding;
Ted Kremenekcf118d42009-02-04 23:49:09 +00002259 public:
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002260 CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2261 ExplodedNode<GRState> *n, SymbolRef sym,
Ted Kremenekd3057212009-02-07 22:38:00 +00002262 GRExprEngine& Eng);
Ted Kremenek66d97062009-02-07 22:04:05 +00002263
2264 PathDiagnosticPiece* getEndPath(BugReporter& BR,
2265 const ExplodedNode<GRState>* N);
2266
Ted Kremeneke469fa02009-02-07 22:19:59 +00002267 SourceLocation getLocation() const { return AllocSite; }
Ted Kremenekcf118d42009-02-04 23:49:09 +00002268 };
Ted Kremenek8dd56462008-04-18 03:39:05 +00002269} // end anonymous namespace
2270
Ted Kremenekcf118d42009-02-04 23:49:09 +00002271void CFRefCount::RegisterChecks(BugReporter& BR) {
Ted Kremenekcf701772009-02-05 06:50:21 +00002272 useAfterRelease = new UseAfterRelease(this);
2273 BR.Register(useAfterRelease);
2274
2275 releaseNotOwned = new BadRelease(this);
2276 BR.Register(releaseNotOwned);
Ted Kremenekcf118d42009-02-04 23:49:09 +00002277
2278 // First register "return" leaks.
2279 const char* name = 0;
2280
2281 if (isGCEnabled())
2282 name = "[naming convention] leak of returned object (GC)";
2283 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2284 name = "[naming convention] leak of returned object (hybrid MM, "
2285 "non-GC)";
2286 else {
2287 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2288 name = "[naming convention] leak of returned object";
2289 }
2290
Ted Kremenekcf701772009-02-05 06:50:21 +00002291 leakAtReturn = new LeakAtReturn(this, name);
2292 BR.Register(leakAtReturn);
Ted Kremenek8dd56462008-04-18 03:39:05 +00002293
Ted Kremenekcf118d42009-02-04 23:49:09 +00002294 // Second, register leaks within a function/method.
2295 if (isGCEnabled())
2296 name = "leak (GC)";
2297 else if (getLangOptions().getGCMode() == LangOptions::HybridGC)
2298 name = "leak (hybrid MM, non-GC)";
2299 else {
2300 assert(getLangOptions().getGCMode() == LangOptions::NonGC);
2301 name = "leak";
2302 }
2303
Ted Kremenekcf701772009-02-05 06:50:21 +00002304 leakWithinFunction = new LeakWithinFunction(this, name);
2305 BR.Register(leakWithinFunction);
2306
2307 // Save the reference to the BugReporter.
2308 this->BR = &BR;
Ted Kremenekcf118d42009-02-04 23:49:09 +00002309}
Ted Kremenek072192b2008-04-30 23:47:44 +00002310
2311static const char* Msgs[] = {
2312 "Code is compiled in garbage collection only mode" // GC only
2313 " (the bug occurs with garbage collection enabled).",
2314
2315 "Code is compiled without garbage collection.", // No GC.
2316
2317 "Code is compiled for use with and without garbage collection (GC)."
2318 " The bug occurs with GC enabled.", // Hybrid, with GC.
2319
2320 "Code is compiled for use with and without garbage collection (GC)."
2321 " The bug occurs in non-GC mode." // Hyrbird, without GC/
2322};
2323
2324std::pair<const char**,const char**> CFRefReport::getExtraDescriptiveText() {
2325 CFRefCount& TF = static_cast<CFRefBug&>(getBugType()).getTF();
2326
2327 switch (TF.getLangOptions().getGCMode()) {
2328 default:
2329 assert(false);
Ted Kremenek31593ac2008-05-01 04:02:04 +00002330
2331 case LangOptions::GCOnly:
2332 assert (TF.isGCEnabled());
Ted Kremenek9e476de2008-08-12 18:30:56 +00002333 return std::make_pair(&Msgs[0], &Msgs[0]+1);
2334
Ted Kremenek072192b2008-04-30 23:47:44 +00002335 case LangOptions::NonGC:
2336 assert (!TF.isGCEnabled());
Ted Kremenek072192b2008-04-30 23:47:44 +00002337 return std::make_pair(&Msgs[1], &Msgs[1]+1);
2338
2339 case LangOptions::HybridGC:
2340 if (TF.isGCEnabled())
2341 return std::make_pair(&Msgs[2], &Msgs[2]+1);
2342 else
2343 return std::make_pair(&Msgs[3], &Msgs[3]+1);
2344 }
2345}
2346
Ted Kremenek27019002009-02-18 21:57:45 +00002347static inline bool contains(const llvm::SmallVectorImpl<ArgEffect>& V,
2348 ArgEffect X) {
2349 for (llvm::SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
2350 I!=E; ++I)
2351 if (*I == X) return true;
2352
2353 return false;
2354}
2355
Ted Kremenek3148eb42009-01-24 00:55:43 +00002356PathDiagnosticPiece* CFRefReport::VisitNode(const ExplodedNode<GRState>* N,
2357 const ExplodedNode<GRState>* PrevN,
2358 const ExplodedGraph<GRState>& G,
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002359 BugReporter& BR,
2360 NodeResolver& NR) {
Ted Kremenek8dd56462008-04-18 03:39:05 +00002361
Ted Kremenek611a15a2009-01-28 05:29:13 +00002362 // Check if the type state has changed.
2363 GRStateManager &StMgr = cast<GRBugReporter>(BR).getStateManager();
2364 GRStateRef PrevSt(PrevN->getState(), StMgr);
2365 GRStateRef CurrSt(N->getState(), StMgr);
Ted Kremenek20982802009-01-28 05:06:46 +00002366
Ted Kremenek611a15a2009-01-28 05:29:13 +00002367 const RefVal* CurrT = CurrSt.get<RefBindings>(Sym);
2368 if (!CurrT) return NULL;
2369
2370 const RefVal& CurrV = *CurrT;
2371 const RefVal* PrevT = PrevSt.get<RefBindings>(Sym);
Ted Kremenekce48e002008-05-05 17:53:17 +00002372
Ted Kremenek27019002009-02-18 21:57:45 +00002373 // Create a string buffer to constain all the useful things we want
2374 // to tell the user.
2375 std::string sbuf;
2376 llvm::raw_string_ostream os(sbuf);
2377
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002378 // This is the allocation site since the previous node had no bindings
2379 // for this symbol.
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002380 if (!PrevT) {
Ted Kremenekce48e002008-05-05 17:53:17 +00002381 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2382
Ted Kremenek5c1cd522009-01-28 05:15:02 +00002383 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2384 // Get the name of the callee (if it is available).
2385 SVal X = CurrSt.GetSVal(CE->getCallee());
2386 if (loc::FuncVal* FV = dyn_cast<loc::FuncVal>(&X))
2387 os << "Call to function '" << FV->getDecl()->getNameAsString() <<'\'';
2388 else
Ted Kremeneka102c0c2009-01-28 06:01:42 +00002389 os << "function call";
Ted Kremenek5c1cd522009-01-28 05:15:02 +00002390 }
2391 else {
2392 assert (isa<ObjCMessageExpr>(S));
Ted Kremeneka102c0c2009-01-28 06:01:42 +00002393 os << "Method";
Ted Kremenekce48e002008-05-05 17:53:17 +00002394 }
Ted Kremenek5c1cd522009-01-28 05:15:02 +00002395
Ted Kremenek961b61d2009-01-28 06:06:36 +00002396 if (CurrV.getObjKind() == RetEffect::CF) {
2397 os << " returns a Core Foundation object with a ";
2398 }
2399 else {
2400 assert (CurrV.getObjKind() == RetEffect::ObjC);
2401 os << " returns an Objective-C object with a ";
2402 }
Ted Kremeneka102c0c2009-01-28 06:01:42 +00002403
Ted Kremenek23b8eaa2009-01-28 06:25:48 +00002404 if (CurrV.isOwned()) {
2405 os << "+1 retain count (owning reference).";
2406
2407 if (static_cast<CFRefBug&>(getBugType()).getTF().isGCEnabled()) {
2408 assert(CurrV.getObjKind() == RetEffect::CF);
2409 os << " "
2410 "Core Foundation objects are not automatically garbage collected.";
2411 }
2412 }
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002413 else {
2414 assert (CurrV.isNotOwned());
Ted Kremenek5c1cd522009-01-28 05:15:02 +00002415 os << "+0 retain count (non-owning reference).";
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002416 }
Ted Kremenekce48e002008-05-05 17:53:17 +00002417
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002418 FullSourceLoc Pos(S->getLocStart(), BR.getContext().getSourceManager());
Ted Kremeneka1f117e2009-01-28 04:47:13 +00002419 PathDiagnosticPiece* P = new PathDiagnosticPiece(Pos, os.str());
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002420
2421 if (Expr* Exp = dyn_cast<Expr>(S))
2422 P->addRange(Exp->getSourceRange());
2423
2424 return P;
2425 }
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002426
Ted Kremenek27019002009-02-18 21:57:45 +00002427 // Gather up the effects that were performed on the object at this
2428 // program point
2429 llvm::SmallVector<ArgEffect, 2> AEffects;
2430
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002431 if (const RetainSummary *Summ = TF.getSummaryOfNode(NR.getOriginalNode(N))) {
2432 // We only have summaries attached to nodes after evaluating CallExpr and
2433 // ObjCMessageExprs.
2434 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2435
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002436 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
2437 // Iterate through the parameter expressions and see if the symbol
2438 // was ever passed as an argument.
2439 unsigned i = 0;
2440
2441 for (CallExpr::arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
2442 AI!=AE; ++AI, ++i) {
Ted Kremenek27019002009-02-18 21:57:45 +00002443
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002444 // Retrieve the value of the arugment.
2445 SVal X = CurrSt.GetSVal(*AI);
Ted Kremenek27019002009-02-18 21:57:45 +00002446
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002447 // Is it the symbol we're interested in?
2448 if (!isa<loc::SymbolVal>(X) ||
2449 Sym != cast<loc::SymbolVal>(X).getSymbol())
2450 continue;
Ted Kremenek79c140b2008-04-18 05:32:44 +00002451
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002452 // We have an argument. Get the effect!
2453 AEffects.push_back(Summ->getArg(i));
Ted Kremenek79c140b2008-04-18 05:32:44 +00002454 }
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002455 }
2456 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
2457 if (Expr *receiver = ME->getReceiver()) {
Ted Kremenek27019002009-02-18 21:57:45 +00002458 SVal RetV = CurrSt.GetSVal(receiver);
2459 if (isa<loc::SymbolVal>(RetV) &&
2460 Sym == cast<loc::SymbolVal>(RetV).getSymbol()) {
2461 // The symbol we are tracking is the receiver.
2462 AEffects.push_back(Summ->getReceiverEffect());
2463 }
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002464 }
2465 }
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002466 }
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002467
Ted Kremenek27019002009-02-18 21:57:45 +00002468 do {
2469 // Get the previous type state.
2470 RefVal PrevV = *PrevT;
2471
2472 // Specially handle CFMakeCollectable and friends.
2473 if (contains(AEffects, MakeCollectable)) {
2474 // Get the name of the function.
2475 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2476 loc::FuncVal FV =
2477 cast<loc::FuncVal>(CurrSt.GetSVal(cast<CallExpr>(S)->getCallee()));
2478 const std::string& FName = FV.getDecl()->getNameAsString();
2479
2480 if (TF.isGCEnabled()) {
2481 // Determine if the object's reference count was pushed to zero.
2482 assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2483
2484 os << "In GC mode a call to '" << FName
2485 << "' decrements an object's retain count and registers the "
2486 "object with the garbage collector. ";
2487
Ted Kremenekbb8c5aa2009-02-18 22:57:22 +00002488 if (CurrV.getKind() == RefVal::Released) {
2489 assert(CurrV.getCount() == 0);
2490 os << "Since it now has a 0 retain count the object can be "
Ted Kremenek27019002009-02-18 21:57:45 +00002491 "automatically collected by the garbage collector.";
Ted Kremenekbb8c5aa2009-02-18 22:57:22 +00002492 }
Ted Kremenek27019002009-02-18 21:57:45 +00002493 else
2494 os << "An object must have a 0 retain count to be garbage collected. "
2495 "After this call its retain count is +" << CurrV.getCount()
2496 << '.';
2497 }
2498 else
2499 os << "When GC is not enabled a call to '" << FName
2500 << "' has no effect on its argument.";
2501
2502 // Nothing more to say.
2503 break;
2504 }
2505
2506 // Determine if the typestate has changed.
2507 if (!(PrevV == CurrV))
2508 switch (CurrV.getKind()) {
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002509 case RefVal::Owned:
2510 case RefVal::NotOwned:
2511
2512 if (PrevV.getCount() == CurrV.getCount())
2513 return 0;
2514
2515 if (PrevV.getCount() > CurrV.getCount())
2516 os << "Reference count decremented.";
2517 else
2518 os << "Reference count incremented.";
Ted Kremenekbb8c5aa2009-02-18 22:57:22 +00002519
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002520 if (unsigned Count = CurrV.getCount()) {
Ted Kremenekbb8c5aa2009-02-18 22:57:22 +00002521 os << " The object now has +" << Count;
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002522
2523 if (Count > 1)
2524 os << " retain counts.";
2525 else
2526 os << " retain count.";
2527 }
Ted Kremenekbb8c5aa2009-02-18 22:57:22 +00002528
2529 if (PrevV.getKind() == RefVal::Released) {
2530 assert(TF.isGCEnabled() && CurrV.getCount() > 0);
2531 os << " The object is not eligible for garbage collection until the "
2532 "retain count reaches 0 again.";
2533 }
2534
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002535 break;
2536
2537 case RefVal::Released:
2538 os << "Object released.";
2539 break;
2540
2541 case RefVal::ReturnedOwned:
2542 os << "Object returned to caller as an owning reference (single retain "
2543 "count transferred to caller).";
2544 break;
2545
2546 case RefVal::ReturnedNotOwned:
2547 os << "Object returned to caller with a +0 (non-owning) retain count.";
2548 break;
2549
2550 default:
2551 return NULL;
Ted Kremenek27019002009-02-18 21:57:45 +00002552 }
2553
2554 // Emit any remaining diagnostics for the argument effects (if any).
2555 for (llvm::SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
2556 E=AEffects.end(); I != E; ++I) {
2557
2558 // A bunch of things have alternate behavior under GC.
2559 if (TF.isGCEnabled())
2560 switch (*I) {
2561 default: break;
2562 case Autorelease:
2563 os << "In GC mode an 'autorelease' has no effect.";
2564 continue;
2565 case IncRefMsg:
2566 os << "In GC mode the 'retain' message has no effect.";
2567 continue;
2568 case DecRefMsg:
2569 os << "In GC mode the 'release' message has no effect.";
2570 continue;
2571 }
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002572 }
Ted Kremenek27019002009-02-18 21:57:45 +00002573 } while(0);
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002574
2575 if (os.str().empty())
2576 return 0; // We have nothing to say!
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002577
2578 Stmt* S = cast<PostStmt>(N->getLocation()).getStmt();
2579 FullSourceLoc Pos(S->getLocStart(), BR.getContext().getSourceManager());
Ted Kremeneka1f117e2009-01-28 04:47:13 +00002580 PathDiagnosticPiece* P = new PathDiagnosticPiece(Pos, os.str());
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002581
2582 // Add the range by scanning the children of the statement for any bindings
2583 // to Sym.
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002584 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I!=E; ++I)
2585 if (Expr* Exp = dyn_cast_or_null<Expr>(*I)) {
Ted Kremenek20982802009-01-28 05:06:46 +00002586 SVal X = CurrSt.GetSVal(Exp);
Zhongxing Xu1c96b242008-10-17 05:57:07 +00002587 if (loc::SymbolVal* SV = dyn_cast<loc::SymbolVal>(&X))
Ted Kremenek1f62ef32009-02-18 22:17:20 +00002588 if (SV->getSymbol() == Sym) {
2589 P->addRange(Exp->getSourceRange());
2590 break;
2591 }
Ted Kremenek2cf943a2008-04-18 04:55:01 +00002592 }
2593
2594 return P;
Ted Kremenek8dd56462008-04-18 03:39:05 +00002595}
2596
Ted Kremenek9e240492008-10-04 05:50:14 +00002597namespace {
2598class VISIBILITY_HIDDEN FindUniqueBinding :
2599 public StoreManager::BindingsHandler {
Ted Kremenek2dabd432008-12-05 02:27:51 +00002600 SymbolRef Sym;
Ted Kremenek9e240492008-10-04 05:50:14 +00002601 MemRegion* Binding;
2602 bool First;
2603
2604 public:
Ted Kremenek2dabd432008-12-05 02:27:51 +00002605 FindUniqueBinding(SymbolRef sym) : Sym(sym), Binding(0), First(true) {}
Ted Kremenek9e240492008-10-04 05:50:14 +00002606
Zhongxing Xu1c96b242008-10-17 05:57:07 +00002607 bool HandleBinding(StoreManager& SMgr, Store store, MemRegion* R, SVal val) {
2608 if (const loc::SymbolVal* SV = dyn_cast<loc::SymbolVal>(&val)) {
Ted Kremenek9e240492008-10-04 05:50:14 +00002609 if (SV->getSymbol() != Sym)
2610 return true;
2611 }
Zhongxing Xu1c96b242008-10-17 05:57:07 +00002612 else if (const nonloc::SymbolVal* SV=dyn_cast<nonloc::SymbolVal>(&val)) {
Ted Kremenek9e240492008-10-04 05:50:14 +00002613 if (SV->getSymbol() != Sym)
2614 return true;
2615 }
2616 else
2617 return true;
2618
2619 if (Binding) {
2620 First = false;
2621 return false;
2622 }
2623 else
2624 Binding = R;
2625
2626 return true;
2627 }
2628
2629 operator bool() { return First && Binding; }
2630 MemRegion* getRegion() { return Binding; }
2631};
2632}
2633
Ted Kremenek3148eb42009-01-24 00:55:43 +00002634static std::pair<const ExplodedNode<GRState>*,const MemRegion*>
Ted Kremeneke469fa02009-02-07 22:19:59 +00002635GetAllocationSite(GRStateManager& StateMgr, const ExplodedNode<GRState>* N,
Ted Kremenek2dabd432008-12-05 02:27:51 +00002636 SymbolRef Sym) {
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002637
Ted Kremenek2bc39c62008-08-29 00:47:32 +00002638 // Find both first node that referred to the tracked symbol and the
2639 // memory location that value was store to.
Ted Kremenek3148eb42009-01-24 00:55:43 +00002640 const ExplodedNode<GRState>* Last = N;
2641 const MemRegion* FirstBinding = 0;
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002642
2643 while (N) {
Ted Kremenek4adc81e2008-08-13 04:27:00 +00002644 const GRState* St = N->getState();
Ted Kremenek72cd17f2008-08-14 21:16:54 +00002645 RefBindings B = St->get<RefBindings>();
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002646
Ted Kremeneke8fdc832008-07-07 16:21:19 +00002647 if (!B.lookup(Sym))
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002648 break;
Ted Kremenek2bc39c62008-08-29 00:47:32 +00002649
Ted Kremeneke469fa02009-02-07 22:19:59 +00002650 FindUniqueBinding FB(Sym);
2651 StateMgr.iterBindings(St, FB);
2652 if (FB) FirstBinding = FB.getRegion();
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002653
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002654 Last = N;
2655 N = N->pred_empty() ? NULL : *(N->pred_begin());
2656 }
2657
Ted Kremenek2bc39c62008-08-29 00:47:32 +00002658 return std::make_pair(Last, FirstBinding);
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002659}
Ted Kremeneka22cc2f2008-05-06 23:07:13 +00002660
Ted Kremenek3148eb42009-01-24 00:55:43 +00002661PathDiagnosticPiece*
2662CFRefReport::getEndPath(BugReporter& br, const ExplodedNode<GRState>* EndN) {
Ted Kremenek1aa44c72008-05-22 23:45:19 +00002663
Ted Kremenek2bc39c62008-08-29 00:47:32 +00002664 GRBugReporter& BR = cast<GRBugReporter>(br);
Ted Kremenek1aa44c72008-05-22 23:45:19 +00002665 // Tell the BugReporter to report cases when the tracked symbol is
2666 // assigned to different variables, etc.
Ted Kremenekc0959972008-07-02 21:24:01 +00002667 cast<GRBugReporter>(BR).addNotableSymbol(Sym);
Ted Kremenek66d97062009-02-07 22:04:05 +00002668 return RangedBugReport::getEndPath(BR, EndN);
2669}
2670
2671PathDiagnosticPiece*
2672CFRefLeakReport::getEndPath(BugReporter& br, const ExplodedNode<GRState>* EndN){
2673
2674 GRBugReporter& BR = cast<GRBugReporter>(br);
2675 // Tell the BugReporter to report cases when the tracked symbol is
2676 // assigned to different variables, etc.
2677 cast<GRBugReporter>(BR).addNotableSymbol(Sym);
2678
2679 // We are reporting a leak. Walk up the graph to get to the first node where
2680 // the symbol appeared, and also get the first VarDecl that tracked object
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002681 // is stored to.
Ted Kremenek3148eb42009-01-24 00:55:43 +00002682 const ExplodedNode<GRState>* AllocNode = 0;
2683 const MemRegion* FirstBinding = 0;
Ted Kremenek2bc39c62008-08-29 00:47:32 +00002684
2685 llvm::tie(AllocNode, FirstBinding) =
Ted Kremeneke469fa02009-02-07 22:19:59 +00002686 GetAllocationSite(BR.getStateManager(), EndN, Sym);
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00002687
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002688 // Get the allocate site.
2689 assert (AllocNode);
2690 Stmt* FirstStmt = cast<PostStmt>(AllocNode->getLocation()).getStmt();
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00002691
Ted Kremeneke28565b2008-05-05 18:50:19 +00002692 SourceManager& SMgr = BR.getContext().getSourceManager();
Chris Lattnerf7cf85b2009-01-16 07:36:28 +00002693 unsigned AllocLine =SMgr.getInstantiationLineNumber(FirstStmt->getLocStart());
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00002694
Ted Kremenekd5597922009-02-18 23:28:26 +00002695 // Get the leak site. We want to find the last place where the symbol
2696 // was used in an expression.
2697 const ExplodedNode<GRState>* LeakN = EndN;
2698 Stmt *S = 0;
Ted Kremeneke28565b2008-05-05 18:50:19 +00002699
Ted Kremenekd5597922009-02-18 23:28:26 +00002700 while (LeakN) {
Ted Kremenek4094b342009-02-24 23:30:57 +00002701 bool atBranch = false;
Ted Kremenekd5597922009-02-18 23:28:26 +00002702 ProgramPoint P = LeakN->getLocation();
Ted Kremenekd5597922009-02-18 23:28:26 +00002703
2704 if (const PostStmt *PS = dyn_cast<PostStmt>(&P))
2705 S = PS->getStmt();
Ted Kremenek4094b342009-02-24 23:30:57 +00002706 else if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
2707 // FIXME: What we really want is to set LeakN to be the node
2708 // for the BlockEntrance for the branch we took and have BugReporter
2709 // do the right thing.
2710 atBranch = true;
Ted Kremenekd5597922009-02-18 23:28:26 +00002711 S = BE->getSrc()->getTerminator();
Ted Kremenek4094b342009-02-24 23:30:57 +00002712 }
Ted Kremenekd5597922009-02-18 23:28:26 +00002713
2714 if (S) {
2715 // Scan 'S' for uses of Sym.
2716 GRStateRef state(LeakN->getState(), BR.getStateManager());
2717 bool foundSymbol = false;
Ted Kremenekb1dbf152009-02-19 18:18:48 +00002718
2719 // First check if 'S' itself binds to the symbol.
2720 if (Expr *Ex = dyn_cast<Expr>(S)) {
2721 SVal X = state.GetSVal(Ex);
2722 if (isa<loc::SymbolVal>(X) &&
2723 cast<loc::SymbolVal>(X).getSymbol() == Sym)
2724 foundSymbol = true;
2725 }
2726
2727 if (!foundSymbol)
2728 for (Stmt::child_iterator I=S->child_begin(), E=S->child_end();
2729 I!=E; ++I)
2730 if (Expr *Ex = dyn_cast_or_null<Expr>(*I)) {
2731 SVal X = state.GetSVal(Ex);
2732 if (isa<loc::SymbolVal>(X) &&
2733 cast<loc::SymbolVal>(X).getSymbol() == Sym){
2734 foundSymbol = true;
2735 break;
2736 }
Ted Kremenekd5597922009-02-18 23:28:26 +00002737 }
Ted Kremenekb1dbf152009-02-19 18:18:48 +00002738
Ted Kremenekd5597922009-02-18 23:28:26 +00002739 if (foundSymbol)
2740 break;
2741 }
2742
Ted Kremenek4094b342009-02-24 23:30:57 +00002743 // Don't traverse any higher than the branch.
2744 if (atBranch)
2745 break;
2746
Ted Kremenekd5597922009-02-18 23:28:26 +00002747 LeakN = LeakN->pred_empty() ? 0 : *(LeakN->pred_begin());
2748 }
2749
2750 assert(LeakN && S && "No leak site found.");
Ted Kremeneke28565b2008-05-05 18:50:19 +00002751
Ted Kremeneke28565b2008-05-05 18:50:19 +00002752 // Generate the diagnostic.
Ted Kremenek572b2782009-02-18 22:59:04 +00002753 FullSourceLoc L(S->getLocStart(), SMgr);
Ted Kremenekc9e3d862009-02-07 21:59:45 +00002754 std::string sbuf;
2755 llvm::raw_string_ostream os(sbuf);
Ted Kremeneke92c1b22008-05-02 20:53:50 +00002756
Ted Kremeneke28565b2008-05-05 18:50:19 +00002757 os << "Object allocated on line " << AllocLine;
Ted Kremeneke92c1b22008-05-02 20:53:50 +00002758
Ted Kremenek2bc39c62008-08-29 00:47:32 +00002759 if (FirstBinding)
Ted Kremenek9e240492008-10-04 05:50:14 +00002760 os << " and stored into '" << FirstBinding->getString() << '\'';
2761
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00002762 // Get the retain count.
2763 const RefVal* RV = EndN->getState()->get<RefBindings>(Sym);
2764
2765 if (RV->getKind() == RefVal::ErrorLeakReturned) {
Ted Kremenek04f9d462008-12-02 01:26:07 +00002766 // FIXME: Per comments in rdar://6320065, "create" only applies to CF
2767 // ojbects. Only "copy", "alloc", "retain" and "new" transfer ownership
2768 // to the caller for NS objects.
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00002769 ObjCMethodDecl& MD = cast<ObjCMethodDecl>(BR.getGraph().getCodeDecl());
2770 os << " is returned from a method whose name ('"
Chris Lattner077bf5e2008-11-24 03:33:13 +00002771 << MD.getSelector().getAsString()
Ted Kremenek234a4c22009-01-07 00:39:56 +00002772 << "') does not contain 'copy' or otherwise starts with"
Ted Kremenek9d1d5702008-10-24 21:22:44 +00002773 " 'new' or 'alloc'. This violates the naming convention rules given"
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00002774 " in the Memory Management Guide for Cocoa (object leaked).";
2775 }
2776 else
Ted Kremenek9d1d5702008-10-24 21:22:44 +00002777 os << " is no longer referenced after this point and has a retain count of"
2778 " +"
Ted Kremenek3ad2cc82008-10-22 23:56:21 +00002779 << RV->getCount() << " (object leaked).";
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00002780
Ted Kremenek572b2782009-02-18 22:59:04 +00002781 return new PathDiagnosticPiece(L, os.str());
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00002782}
2783
Ted Kremenek989d5192008-04-17 23:43:50 +00002784
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002785CFRefLeakReport::CFRefLeakReport(CFRefBug& D, const CFRefCount &tf,
2786 ExplodedNode<GRState> *n,
Ted Kremenekd3057212009-02-07 22:38:00 +00002787 SymbolRef sym, GRExprEngine& Eng)
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002788 : CFRefReport(D, tf, n, sym)
Ted Kremeneke469fa02009-02-07 22:19:59 +00002789{
2790
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002791 // Most bug reports are cached at the location where they occured.
2792 // With leaks, we want to unique them by the location where they were
Ted Kremeneke469fa02009-02-07 22:19:59 +00002793 // allocated, and only report a single path. To do this, we need to find
2794 // the allocation site of a piece of tracked memory, which we do via a
2795 // call to GetAllocationSite. This will walk the ExplodedGraph backwards.
2796 // Note that this is *not* the trimmed graph; we are guaranteed, however,
2797 // that all ancestor nodes that represent the allocation site have the
2798 // same SourceLocation.
2799 const ExplodedNode<GRState>* AllocNode = 0;
2800
2801 llvm::tie(AllocNode, AllocBinding) = // Set AllocBinding.
Ted Kremenekd3057212009-02-07 22:38:00 +00002802 GetAllocationSite(Eng.getStateManager(), getEndNode(), getSymbol());
Ted Kremeneke469fa02009-02-07 22:19:59 +00002803
Ted Kremeneke469fa02009-02-07 22:19:59 +00002804 // Get the SourceLocation for the allocation site.
Ted Kremenekd3057212009-02-07 22:38:00 +00002805 ProgramPoint P = AllocNode->getLocation();
Ted Kremeneke469fa02009-02-07 22:19:59 +00002806 AllocSite = cast<PostStmt>(P).getStmt()->getLocStart();
Ted Kremenekd3057212009-02-07 22:38:00 +00002807
2808 // Fill in the description of the bug.
2809 Description.clear();
2810 llvm::raw_string_ostream os(Description);
2811 SourceManager& SMgr = Eng.getContext().getSourceManager();
2812 unsigned AllocLine = SMgr.getInstantiationLineNumber(AllocSite);
Ted Kremenekc5c60002009-02-07 22:54:59 +00002813 os << "Potential leak of object allocated on line " << AllocLine;
2814
2815 // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2816 if (AllocBinding)
2817 os << " and store into '" << AllocBinding->getString() << '\'';
Ted Kremenek6ed9afc2008-05-16 18:33:44 +00002818}
2819
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00002820//===----------------------------------------------------------------------===//
Ted Kremenekcf701772009-02-05 06:50:21 +00002821// Handle dead symbols and end-of-path.
2822//===----------------------------------------------------------------------===//
2823
2824void CFRefCount::EvalEndPath(GRExprEngine& Eng,
2825 GREndPathNodeBuilder<GRState>& Builder) {
2826
2827 const GRState* St = Builder.getState();
2828 RefBindings B = St->get<RefBindings>();
2829
2830 llvm::SmallVector<std::pair<SymbolRef, bool>, 10> Leaked;
2831 const Decl* CodeDecl = &Eng.getGraph().getCodeDecl();
2832
2833 for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
2834 bool hasLeak = false;
2835
2836 std::pair<GRStateRef, bool> X =
2837 HandleSymbolDeath(Eng.getStateManager(), St, CodeDecl,
2838 (*I).first, (*I).second, hasLeak);
2839
2840 St = X.first;
2841 if (hasLeak) Leaked.push_back(std::make_pair((*I).first, X.second));
2842 }
2843
2844 if (Leaked.empty())
2845 return;
2846
2847 ExplodedNode<GRState>* N = Builder.MakeNode(St);
2848
2849 if (!N)
2850 return;
2851
2852 for (llvm::SmallVector<std::pair<SymbolRef,bool>, 10>::iterator
2853 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
2854
2855 CFRefBug *BT = static_cast<CFRefBug*>(I->second ? leakAtReturn
2856 : leakWithinFunction);
2857 assert(BT && "BugType not initialized.");
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002858 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N, I->first, Eng);
Ted Kremenekcf701772009-02-05 06:50:21 +00002859 BR->EmitReport(report);
2860 }
2861}
2862
2863void CFRefCount::EvalDeadSymbols(ExplodedNodeSet<GRState>& Dst,
2864 GRExprEngine& Eng,
2865 GRStmtNodeBuilder<GRState>& Builder,
2866 ExplodedNode<GRState>* Pred,
2867 Stmt* S,
2868 const GRState* St,
2869 SymbolReaper& SymReaper) {
2870
Ted Kremenek33b6f632009-02-19 23:47:02 +00002871 // FIXME: a lot of copy-and-paste from EvalEndPath. Refactor.
Ted Kremenekcf701772009-02-05 06:50:21 +00002872 RefBindings B = St->get<RefBindings>();
2873 llvm::SmallVector<std::pair<SymbolRef,bool>, 10> Leaked;
2874
2875 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
2876 E = SymReaper.dead_end(); I != E; ++I) {
2877
2878 const RefVal* T = B.lookup(*I);
2879 if (!T) continue;
2880
2881 bool hasLeak = false;
2882
2883 std::pair<GRStateRef, bool> X
Ted Kremenek33b6f632009-02-19 23:47:02 +00002884 = HandleSymbolDeath(Eng.getStateManager(), St, 0, *I, *T, hasLeak);
Ted Kremenekcf701772009-02-05 06:50:21 +00002885
2886 St = X.first;
2887
2888 if (hasLeak)
2889 Leaked.push_back(std::make_pair(*I,X.second));
2890 }
2891
Ted Kremenek33b6f632009-02-19 23:47:02 +00002892 if (!Leaked.empty()) {
2893 // Create a new intermediate node representing the leak point. We
2894 // use a special program point that represents this checker-specific
2895 // transition. We use the address of RefBIndex as a unique tag for this
2896 // checker. We will create another node (if we don't cache out) that
2897 // removes the retain-count bindings from the state.
2898 // NOTE: We use 'generateNode' so that it does interplay with the
2899 // auto-transition logic.
2900 ExplodedNode<GRState>* N =
2901 Builder.generateNode(PostStmtCustom(S, &LeakProgramPointTag), St, Pred);
Ted Kremenekcf701772009-02-05 06:50:21 +00002902
Ted Kremenek33b6f632009-02-19 23:47:02 +00002903 if (!N)
2904 return;
2905
2906 // Generate the bug reports.
2907 for (llvm::SmallVectorImpl<std::pair<SymbolRef,bool> >::iterator
2908 I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
2909
2910 CFRefBug *BT = static_cast<CFRefBug*>(I->second ? leakAtReturn
2911 : leakWithinFunction);
2912 assert(BT && "BugType not initialized.");
Ted Kremenek46347352009-02-23 16:54:00 +00002913 CFRefLeakReport* report = new CFRefLeakReport(*BT, *this, N,
2914 I->first, Eng);
Ted Kremenek33b6f632009-02-19 23:47:02 +00002915 BR->EmitReport(report);
2916 }
Ted Kremenekcf701772009-02-05 06:50:21 +00002917
Ted Kremenek33b6f632009-02-19 23:47:02 +00002918 Pred = N;
Ted Kremenekcf701772009-02-05 06:50:21 +00002919 }
Ted Kremenek33b6f632009-02-19 23:47:02 +00002920
2921 // Now generate a new node that nukes the old bindings.
2922 GRStateRef state(St, Eng.getStateManager());
2923 RefBindings::Factory& F = state.get_context<RefBindings>();
2924
2925 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
2926 E = SymReaper.dead_end(); I!=E; ++I)
2927 B = F.Remove(B, *I);
2928
2929 state = state.set<RefBindings>(B);
2930 Builder.MakeNode(Dst, S, Pred, state);
Ted Kremenekcf701772009-02-05 06:50:21 +00002931}
2932
2933void CFRefCount::ProcessNonLeakError(ExplodedNodeSet<GRState>& Dst,
2934 GRStmtNodeBuilder<GRState>& Builder,
2935 Expr* NodeExpr, Expr* ErrorExpr,
2936 ExplodedNode<GRState>* Pred,
2937 const GRState* St,
2938 RefVal::Kind hasErr, SymbolRef Sym) {
2939 Builder.BuildSinks = true;
2940 GRExprEngine::NodeTy* N = Builder.MakeNode(Dst, NodeExpr, Pred, St);
2941
2942 if (!N) return;
2943
2944 CFRefBug *BT = 0;
2945
2946 if (hasErr == RefVal::ErrorUseAfterRelease)
2947 BT = static_cast<CFRefBug*>(useAfterRelease);
2948 else {
2949 assert(hasErr == RefVal::ErrorReleaseNotOwned);
2950 BT = static_cast<CFRefBug*>(releaseNotOwned);
2951 }
2952
Ted Kremenekfe9e5432009-02-18 03:48:14 +00002953 CFRefReport *report = new CFRefReport(*BT, *this, N, Sym);
Ted Kremenekcf701772009-02-05 06:50:21 +00002954 report->addRange(ErrorExpr->getSourceRange());
2955 BR->EmitReport(report);
2956}
2957
2958//===----------------------------------------------------------------------===//
Ted Kremenekd71ed262008-04-10 22:16:52 +00002959// Transfer function creation for external clients.
Ted Kremenek6b3a0f72008-03-11 06:39:11 +00002960//===----------------------------------------------------------------------===//
2961
Ted Kremenek072192b2008-04-30 23:47:44 +00002962GRTransferFuncs* clang::MakeCFRefCountTF(ASTContext& Ctx, bool GCEnabled,
2963 const LangOptions& lopts) {
Ted Kremenek78d46242008-07-22 16:21:24 +00002964 return new CFRefCount(Ctx, GCEnabled, lopts);
Ted Kremenek3ea0b6a2008-04-10 22:58:08 +00002965}